Merge merge request !20 (intensifiers, pairing, theme, security hardening)

Takes the nine commits as submitted, with three adjustments:

- remote.test.js ran in the node environment while remote.js pulls in
  api.js, which reads navigator.userAgent at module scope — the file failed
  to import. Same @vitest-environment happy-dom pragma the api tests use.
- Drops skills-lock.json. It pins a personal Claude Code skill chain to
  third-party GitHub repos by hash; that is contributor tooling, not a
  project artefact, and this project's GitHub access is gone. CLAUDE.md
  itself is kept — it is an accurate description of the repo.
- Corrects two stale claims in that CLAUDE.md: the website deploys from
  .gitlab-ci.yml, not GitHub Pages, and the CI gate is GitLab, not Gitea
  Actions with a dormant GitHub copy.

pt-BR: 23 of the 44 new pt strings are European (ficheiro, telemóvel,
Definições, «guillemets», tu-forms), so they get Brazilian overrides
rather than being inherited; fingerprint re-baselined.
This commit is contained in:
Duarte Santos committed 2026-08-25 14:28:10 +02:00
commit 7d2460c2c2
47 files changed
+2296 -109

No files matched your search

+20 -1
View File
@@ -9,8 +9,27 @@ export const VAULT = IS_APPLE ? 'iCloud Keychain' : IS_ANDROID ? 'Google Passwor
// only after the user chooses a passkey action and surface any genuine browser error there.
export const webauthnOK = () => typeof window.PublicKeyCredential !== 'undefined'
// The paired mobile app (lib/remote.js) is the only caller of these — everywhere else stays on
// same-origin cookies, so remoteBase/remoteToken stay empty and api() behaves exactly as before.
let remoteBase = ''
let remoteToken = null
export function setRemoteAuth(base, token) { remoteBase = base || ''; remoteToken = token || null }
export async function api(path, opts) {
const r = await fetch(path, Object.assign({ headers: { 'Content-Type': 'application/json' } }, opts))
const headers = Object.assign({ 'Content-Type': 'application/json' }, opts && opts.headers)
if (remoteToken) headers.Authorization = 'Bearer ' + remoteToken
const r = await fetch(remoteBase + path, Object.assign({}, opts, { headers }))
const data = await r.json().catch(() => ({}))
if (!r.ok) { const e = new Error(data.error || ('HTTP ' + r.status)); e.status = r.status; throw e }
return data
}
// Bootstraps the connection itself: the base isn't configured yet (that's what this call decides),
// so it talks straight to the server the user typed in, no Authorization header.
export async function pairRedeem(serverBase, code) {
const r = await fetch(serverBase + '/api/pair/redeem', {
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code })
})
const data = await r.json().catch(() => ({}))
if (!r.ok) { const e = new Error(data.error || ('HTTP ' + r.status)); e.status = r.status; throw e }
return data
+43 -3
View File
@@ -1,7 +1,7 @@
// Pure helpers over the state object S (ported 1:1 from the vanilla app).
import { todayISO, isoOf, weekKey, fmtNum } from './format.js'
import { isCardio, isBodyweightEq } from './exercises.js'
import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode } from './workout-model.js'
import { phaseForSet, modeForSet, modeForEntry, isWarmupRow, normalizeMode, extraVolumeOf, nextDropWeight, splitBurstReps } from './workout-model.js'
const objectOf = value => value && typeof value === 'object' && !Array.isArray(value) ? value : {}
// Completed-state-independent work rows whose authoritative mode matches the requested mode.
const workRowsForMode = (entry = {}, mode = 'reps') => {
@@ -286,11 +286,51 @@ export function buildSets(S, cfg, options = {}) {
}
return sets
}
/**
* Stamp every work row with the exercise's planned intensifier and pre-fill its drops/clusters,
* already computed and editable — the plan designs the set, not a button pressed mid-workout.
*
* Must run AFTER applyPrescription: a drop-set's chain of drops is a percentage of each row's
* own `w`, so it has to be computed from the final prescribed weight, not the pre-progression
* one buildSets started from — otherwise a bumped working weight would leave stale, cheaper
* drops sitting underneath it.
*/
export function applyIntensifierPlan(sets, cfg) {
const kind = cfg && cfg.intensifier && cfg.intensifier.type
if (kind !== 'dropset' && kind !== 'restpause') return sets
if (kind === 'dropset') {
const count = Math.max(1, Math.round(cfg.intensifier.count) || 1)
const pct = cfg.intensifier.pct
return sets.map(s => {
if (isWarmupRow(s)) return s
const drops = []
let w = s.w || 0
for (let k = 0; k < count; k++) { w = nextDropWeight(w, pct); drops.push({ w, r: s.r }) }
return { ...s, type: 'dropset', drops }
})
}
// Rest-pause trains as exactly two sets, not one per configured `sets` count: a warm-up at
// the exercise's own configured reps, then a single rest-pause work set. Doing the full
// activation+bursts protocol several times over isn't how rest-pause is actually trained, so
// planning it replaces whatever buildSets built rather than stamping each of those rows.
// The work row's own reps are the total — not "the total minus what the bursts carry" — and
// the bursts are the full breakdown of that same total, down to the last one. See
// extraVolumeOf/setTonnage: a rest-pause row's `clusters` are read-only display of how `r`
// breaks down, not extra volume on top of it, precisely so this doesn't double-count.
const restSec = Math.max(5, cfg.intensifier.restSec || 15)
const totalReps = Math.max(1, Math.round(cfg.intensifier.totalReps) || 1)
const w = (sets.find(s => !isWarmupRow(s)) || sets[0] || {}).w || 0
const warmup = { w, r: Math.max(1, Math.round(cfg.reps) || 1), done: false, phase: 'warmup' }
const work = { w, r: totalReps, done: false, type: 'restpause', clusters: splitBurstReps(totalReps).map(r => ({ r, restSec })) }
return [warmup, work]
}
export function workoutVolume(w) {
let v = 0
// No special case for unilateral work: a per-side set logs its total, so both sides are
// already in the rep count that arrives here.
w.entries.forEach(e => e.sets.forEach(s => { if (s.done) v += (s.w || 0) * (s.r || 0) }))
// already in the rep count that arrives here. Drop-set drops and rest-pause bursts add their
// own weight x reps on top of the row's main/activation set (see extraVolumeOf).
w.entries.forEach(e => e.sets.forEach(s => { if (s.done) v += (s.w || 0) * (s.r || 0) + extraVolumeOf(s) }))
return v
}
export function setsDone(w) {
+65 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest'
import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits } from './history.js'
import { modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, pairAdjacent, unpairSuperset, supersetUnits, applyIntensifierPlan } from './history.js'
import { EXDB } from './exercises.js'
// Real ids out of the shipped catalogue, so the body-part fallback is exercised for real.
@@ -456,6 +456,55 @@ describe('buildSets', () => {
expect(buildSets(S, { id: LIFT, sets: 2, reps: 8, weight: 50 }, { preferLast: true }))
.toEqual([{ w: 60, r: 10, done: false }, { w: 62.5, r: 8, done: false }])
})
})
describe('applyIntensifierPlan', () => {
it('pre-fills every work row with a chain of drops, each pct% lighter than the one before', () => {
const sets = [{ w: 100, r: 8, done: false }, { w: 100, r: 8, done: false }]
const out = applyIntensifierPlan(sets, { intensifier: { type: 'dropset', count: 2, pct: 20 } })
expect(out).toEqual([
{ w: 100, r: 8, done: false, type: 'dropset', drops: [{ w: 80, r: 8 }, { w: 64, r: 8 }] },
{ w: 100, r: 8, done: false, type: 'dropset', drops: [{ w: 80, r: 8 }, { w: 64, r: 8 }] },
])
})
it('collapses rest-pause to exactly two rows regardless of how many sets were configured: a warm-up at the exercise\'s own reps, then one work set whose own reps ARE the total', () => {
const sets = [{ w: 60, r: 8, done: false }, { w: 60, r: 8, done: false }, { w: 60, r: 8, done: false }]
const out = applyIntensifierPlan(sets, { reps: 8, intensifier: { type: 'restpause', totalReps: 12, restSec: 15 } })
expect(out).toEqual([
{ w: 60, r: 8, done: false, phase: 'warmup' },
{ w: 60, r: 12, done: false, type: 'restpause', clusters: [{ r: 6, restSec: 15 }, { r: 3, restSec: 15 }, { r: 2, restSec: 15 }, { r: 1, restSec: 15 }] },
])
// the full breakdown always sums back to the row's own r — no reps missing, none double-counted
expect(out[1].clusters.reduce((sum, c) => sum + c.r, 0)).toBe(out[1].r)
})
it('the warm-up reps come from the exercise\'s own configured reps, not the rest-pause total', () => {
const sets = [{ w: 60, r: 8, done: false }]
const out = applyIntensifierPlan(sets, { reps: 5, intensifier: { type: 'restpause', totalReps: 20, restSec: 15 } })
expect(out[0]).toEqual({ w: 60, r: 5, done: false, phase: 'warmup' })
})
it('carries the prescribed weight from the built sets onto both new rows', () => {
const sets = [{ w: 82.5, r: 8, done: false }]
const out = applyIntensifierPlan(sets, { reps: 8, intensifier: { type: 'restpause', totalReps: 4, restSec: 15 } })
expect(out[0].w).toBe(82.5)
expect(out[1].w).toBe(82.5)
})
it('never touches a warm-up row', () => {
const sets = [{ w: 20, r: 8, done: false, phase: 'warmup' }, { w: 100, r: 8, done: false }]
const out = applyIntensifierPlan(sets, { intensifier: { type: 'dropset', count: 1, pct: 20 } })
expect(out[0]).toEqual({ w: 20, r: 8, done: false, phase: 'warmup' })
expect(out[1].type).toBe('dropset')
})
it('leaves sets untouched with no intensifier configured', () => {
const sets = [{ w: 100, r: 8, done: false }]
expect(applyIntensifierPlan(sets, {})).toBe(sets)
expect(applyIntensifierPlan(sets, { intensifier: { type: 'nonsense' } })).toBe(sets)
})
})
describe('workoutVolume', () => {
@@ -473,6 +522,21 @@ describe('workoutVolume', () => {
expect(workoutVolume(w)).toBe(320)
})
it('adds drop-set drops on top of the row\'s main set', () => {
const dropRow = { type: 'dropset', w: 100, r: 5, done: true, drops: [{ w: 80, r: 5 }, { w: 60, r: 5 }] }
expect(workoutVolume({ entries: [{ id: LIFT, sets: [dropRow] }] })).toBe(100 * 5 + 80 * 5 + 60 * 5)
})
it('counts a rest-pause row once — its own r is already the total across every burst', () => {
const burstRow = { type: 'restpause', w: 60, r: 20, done: true, clusters: [{ r: 10, restSec: 15 }, { r: 5, restSec: 15 }, { r: 3, restSec: 15 }, { r: 1, restSec: 15 }, { r: 1, restSec: 15 }] }
expect(workoutVolume({ entries: [{ id: LIFT, sets: [burstRow] }] })).toBe(60 * 20)
})
it('ignores drops/bursts on a row that was never checked off', () => {
const dropRow = { type: 'dropset', w: 100, r: 5, done: false, drops: [{ w: 80, r: 5 }] }
expect(workoutVolume({ entries: [{ id: LIFT, sets: [dropRow] }] })).toBe(0)
})
it('leaves an unloaded bodyweight set at zero volume rather than inventing a number', () => {
const w = { entries: [{ id: BW, target: { bodyweight: true }, sets: [{ w: 0, r: 20, done: true }] }] }
expect(workoutVolume(w)).toBe(0)
+39
View File
@@ -10,6 +10,7 @@
// Like the demo build, MOBILE is replaced at build time, so all of this folds away in
// web bundles; the Capacitor plugins are only ever imported behind it.
import { t } from './i18n-core.js'
import { todayISO } from './format.js'
export const MOBILE = import.meta.env.VITE_MOBILE === '1'
@@ -30,6 +31,27 @@ export async function nativeSave(state) {
} catch (e) { /* keep the localStorage copy */ }
}
// "Connect to my server" mode (lib/remote.js): which of local-only / a paired remote account this
// device chose, kept in its own file — never inside opengym-state.json, since that file's content
// is exactly what pushState() PUTs to a server, and a device's own connection secret must never
// travel as if it were training data.
const REMOTE_FILE = 'opengym-remote.json'
export async function loadRemoteFile() {
try {
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
const r = await Filesystem.readFile({ path: REMOTE_FILE, directory: Directory.Data, encoding: Encoding.UTF8 })
return JSON.parse(r.data)
} catch (e) { return null } // never decided yet
}
export async function saveRemoteFile(data) {
try {
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
await Filesystem.writeFile({ path: REMOTE_FILE, directory: Directory.Data, data: JSON.stringify(data), encoding: Encoding.UTF8 })
} catch (e) { /* worst case: onboarding asks again next launch */ }
}
// (Re)schedule the workout-day reminder: one repeating notification per weekday that has a
// routine in the weekly plan. Cheap enough to run after any state change — the plan or the
// reminder time may just have been edited. `interactive` gates the OS permission prompt to
@@ -66,3 +88,20 @@ export async function shareExport(json, filename) {
const w = await Filesystem.writeFile({ path: filename, directory: Directory.Cache, data: json, encoding: Encoding.UTF8 })
await Share.share({ title: filename, url: w.uri })
}
// "Auto-backup on changes" (Settings): a dated snapshot dropped into the Documents folder —
// visible in Files (iOS) / a file manager (Android), unlike the private mirror nativeSave keeps
// — so whatever the user points at that folder (a sync app, a manual copy) always has something
// recent. One file per day; later triggers the same day just overwrite it.
export async function writeAutoBackup(state) {
try {
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
await Filesystem.writeFile({
path: `opengym-backup-${todayISO()}.json`,
directory: Directory.Documents,
data: JSON.stringify(state),
encoding: Encoding.UTF8,
recursive: true,
})
} catch (e) { /* best effort — the private mirror in Directory.Data still has the data */ }
}
+26
View File
@@ -148,6 +148,32 @@ describe('is1RMRecord', () => {
})
describe('drop-sets, rest-pause sets and 1RM', () => {
it('estimates only from the main/activation weight×reps, ignoring lighter drops', () => {
const entry = { id: 'x', sets: [
{ type: 'dropset', w: 100, r: 5, done: true, drops: [{ w: 80, r: 5 }, { w: 60, r: 5 }] },
] }
expect(bestSetOf(entry)).toEqual(bestSetOf({ id: 'x', sets: [{ w: 100, r: 5, done: true }] }))
})
it('estimates only from the row\'s own w/r, ignoring rest-pause bursts', () => {
const entry = { id: 'x', sets: [
{ type: 'restpause', w: 60, r: 8, done: true, clusters: [{ r: 4, restSec: 15 }, { r: 3, restSec: 15 }] },
] }
expect(bestSetOf(entry)).toEqual(bestSetOf({ id: 'x', sets: [{ w: 60, r: 8, done: true }] }))
})
it('refuses to estimate a planned rest-pause row once its total reps exceed REP_CAP, same as any other high-rep set', () => {
// A planned rest-pause row's own r is the total across every burst (see
// applyIntensifierPlan/history.js), so it commonly lands above REP_CAP — the row is real
// work, but "estimate a max from 20 broken-up reps" is exactly the fantasy REP_CAP refuses.
const entry = { id: 'x', sets: [
{ type: 'restpause', w: 60, r: 20, done: true, clusters: [{ r: 10, restSec: 15 }, { r: 5, restSec: 15 }, { r: 3, restSec: 15 }, { r: 1, restSec: 15 }, { r: 1, restSec: 15 }] },
] }
expect(bestSetOf(entry)).toBeNull()
})
})
describe('warm-up sets and 1RM', () => {
const ENTRY = { id: 'warm-test', sets: [
{ w: 20, r: 8, done: true, warmup: true },
+6 -1
View File
@@ -272,7 +272,12 @@ export function applyPrescription(sets, p) {
// would both invent work and never terminate the loop. Leave the entry untouched.
if (!workRows.length) return out
const seed = workRows[workRows.length - 1]
while (out.filter(s => !isWarmupRow(s)).length < p.sets) out.push({ ...seed, done: false })
// A freshly appended row hasn't been performed, so it never inherits a seed's already-
// logged drops/clusters — that would invent extra work the row never actually did. Its
// `type` is kept: that's the exercise's plan (every set is a drop-set/rest-pause), not
// something this particular row logged.
const { drops, clusters, ...plainSeed } = seed
while (out.filter(s => !isWarmupRow(s)).length < p.sets) out.push({ ...plainSeed, done: false })
}
return out
}
+31
View File
@@ -523,3 +523,34 @@ describe('applyPrescription never touches warm-up rows (round 3)', () => {
expect(out).toEqual(sets) // no work row to seed growth from - nothing grows, no loop
})
})
describe('drop-sets and rest-pause sets in progression', () => {
it('readSession judges a drop-set row on its own main weight/reps, ignoring the drops', () => {
const withDrops = readSession({ id: LIFT, target: { sets: 1, reps: 5 }, sets: [
{ type: 'dropset', w: 60, r: 5, done: true, drops: [{ w: 40, r: 8 }, { w: 20, r: 10 }] },
] })
const plain = readSession({ id: LIFT, target: { sets: 1, reps: 5 }, sets: [{ w: 60, r: 5, done: true }] })
expect(withDrops).toEqual(plain)
})
it('readSession judges a rest-pause row on its activation weight/reps, ignoring the bursts', () => {
const withBursts = readSession({ id: LIFT, target: { sets: 1, reps: 8 }, sets: [
{ type: 'restpause', w: 60, r: 8, done: true, clusters: [{ r: 4, restSec: 15 }, { r: 3, restSec: 15 }] },
] })
const plain = readSession({ id: LIFT, target: { sets: 1, reps: 8 }, sets: [{ w: 60, r: 8, done: true }] })
expect(withBursts).toEqual(plain)
})
it('applyPrescription still rewrites a drop-set/rest-pause row\'s own weight, leaving its drops/clusters untouched', () => {
const sets = [{ type: 'dropset', w: 60, r: 5, done: false, drops: [{ w: 40, r: 8 }] }]
const out = applyPrescription(sets, { kind: 'up', weight: 62.5 })
expect(out[0]).toEqual({ type: 'dropset', w: 62.5, r: 5, done: false, drops: [{ w: 40, r: 8 }] })
})
it('a newly grown row keeps the seed\'s planned type but not its already-logged drops/clusters', () => {
const sets = [{ type: 'dropset', w: 0, r: 10, done: false, drops: [{ w: 0, r: 12 }] }]
const out = applyPrescription(sets, { kind: 'up', weight: 0, reps: 10, sets: 2 })
expect(out).toHaveLength(2)
expect(out[1]).toEqual({ type: 'dropset', w: 0, r: 10, done: false })
})
})
+3 -3
View File
@@ -27,11 +27,11 @@ describe('Brazilian Portuguese locale', () => {
.sort(byCodeUnit)
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(260)
expect(inherited).toHaveLength(416)
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(283)
expect(inherited).toHaveLength(437)
// If this fails, review the changed keys and wording before accepting a new hash. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('4c32711daa44d6d35d775efd5324036d351b2d6c61d06c734e813b7096f8f704')
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('70fd93bc049da76bc578701a82ecde33b1521ddae37a403076ad48b9694cc4e3')
})
test('does not leak European Portuguese UI terms', () => {
+24 -4
View File
@@ -1,6 +1,6 @@
import { EXIDX } from './exercises.js'
import { MUSCLES, musclesOf } from './muscles.js'
import { isWarmupRow } from './workout-model.js'
import { isWarmupRow, dropsOf } from './workout-model.js'
// A "normal" hard session for one muscle, in primary-set equivalents. The saturation curve
// 1 - exp(-stimulus / REF) maps any session size onto [0,1) so volume raises the starting
@@ -172,6 +172,25 @@ function session1RMs(workout, opts = {}) {
return best
}
// Extra tonnage from a drop-set's drops, weighted the same way as the row's own main set — a
// drop taken near failure counts the same as any other hard rep for fatigue purposes, it just
// carries its own (usually lighter) load.
//
// A rest-pause row's `clusters` are NOT extra here: the row's own `r` already is the total reps
// across every burst (see applyIntensifierPlan/history.js), so the main tonnage term below
// already covers it — adding clusters on top would double-count the same reps.
function extraTonnage(ex, entry, set, workout, oneRm, opts = {}) {
const drops = dropsOf(set)
if (!drops.length) return 0
const isBwEx = bodyweightConfigured(ex, entry, set, workout, opts)
const weigh = (load, reps) => {
if (!(load > 0) || !(reps > 0)) return 0
const raw = load * reps
return isBwEx || !(oneRm > 0) ? raw : raw * Math.min(1, load / oneRm) ** 1.5
}
return drops.reduce((sum, d) => sum + weigh(loadKgFor(ex, entry, d, workout, opts), Number(d?.r) || 0), 0)
}
// Intensity-weighted tonnage for one completed set: load x reps x (load / exercise 1RM)^1.5.
// The exponent saturates the "hard set" effect - a set at 90% of your 1RM counts ~0.81 of its
// raw tonnage, one at 50% only ~0.35. Cardio, timed holds, and sets whose exercise has no
@@ -186,13 +205,14 @@ function setTonnage(ex, entry, set, workout, oneRm, opts = {}) {
const reps = set?.r || 1
const load = loadKgFor(ex, entry, set, workout, opts)
const raw = load * reps
const extra = extraTonnage(ex, entry, set, workout, oneRm, opts)
// A bodyweight target is already an external-load-normalised total (body mass + any added
// load). It has no meaningful barbell-style 1RM intensity ratio in the legacy data model, so
// retain the monotonic total-load stimulus instead of letting a newly created low 1RM shrink
// a weighted bodyweight set below the unloaded version.
if (bodyweightConfigured(ex, entry, set, workout, opts)) return raw
if (!(oneRm > 0) || !(load > 0)) return raw
return raw * Math.min(1, load / oneRm) ** 1.5
if (bodyweightConfigured(ex, entry, set, workout, opts)) return raw + extra
if (!(oneRm > 0) || !(load > 0)) return raw + extra
return raw * Math.min(1, load / oneRm) ** 1.5 + extra
}
// One session's per-muscle stimulus, calculated only from that session. A completed zero-load
+41
View File
@@ -403,6 +403,47 @@ describe('warm-up flag in strength and fatigue', () => {
})
})
describe('drop-set drops add fatigue tonnage on top of the main set', () => {
// Same within-session Epley baseline setTonnage derives from the row's own w/r (8 reps,
// under REP_CAP), so a drop is weighted against the same 1RM as the main set.
const oneRm = 80 * (1 + 8 / 30)
it('a drop-set drop adds its own intensity-weighted tonnage', () => {
const dropRow = { done: true, type: 'dropset', w: 80, r: 8, drops: [{ w: 60, r: 6 }] }
const dropTonnage = 60 * 6 * Math.min(1, 60 / oneRm) ** 1.5
const expected = expectedFatigue([{ stimulus: V + dropTonnage }])
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [dropRow])], NOW)[SINGLE_SLUG]).toBeCloseTo(expected, 8)
// strictly more than the plain 80x8 set alone — the drop is real extra work
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [dropRow])], NOW)[SINGLE_SLUG])
.toBeGreaterThan(fatigueOf([doneWorkoutAt(SINGLE.id, NOW)], NOW)[SINGLE_SLUG])
})
it('leaves fatigue unchanged for a straight set with no drops', () => {
const plain = { done: true, w: 80, r: 8 }
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [plain])], NOW)[SINGLE_SLUG])
.toBeCloseTo(expectedFatigue([{ stimulus: V }]), 8)
})
})
describe('a rest-pause row\'s clusters add no extra fatigue tonnage', () => {
// Its own r is already the total across every burst (see applyIntensifierPlan/history.js),
// so setTonnage's main w x r term already covers all of it — clusters are a breakdown only.
it('matches a plain set of the same w/r exactly, regardless of how the clusters break it down', () => {
const burstRow = { done: true, type: 'restpause', w: 80, r: 8, clusters: [{ r: 4, restSec: 15 }] }
const plainRow = { done: true, w: 80, r: 8 }
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [burstRow])], NOW)[SINGLE_SLUG])
.toBeCloseTo(fatigueOf([workoutAt(SINGLE.id, NOW, [plainRow])], NOW)[SINGLE_SLUG], 10)
})
it('holds for a realistic planned total too — a full descending split adds nothing beyond the row\'s own r', () => {
const burstRow = { done: true, type: 'restpause', w: 80, r: 20, clusters: [{ r: 10, restSec: 15 }, { r: 5, restSec: 15 }, { r: 3, restSec: 15 }, { r: 1, restSec: 15 }, { r: 1, restSec: 15 }] }
const plainRow = { done: true, w: 80, r: 20 }
expect(fatigueOf([workoutAt(SINGLE.id, NOW, [burstRow])], NOW)[SINGLE_SLUG])
.toBeCloseTo(fatigueOf([workoutAt(SINGLE.id, NOW, [plainRow])], NOW)[SINGLE_SLUG], 10)
})
})
describe('canonical loads and configured bodyweight', () => {
const loaded = EXDB.find(ex => {
const weights = musclesOf(ex)
+48
View File
@@ -0,0 +1,48 @@
// Mobile build only: "connect to my server" mode (see mobile.js's header comment for why the
// mobile flavor has no backend at all by default). This is the alternative — pairing the app to
// an already self-hosted openGym server instead of keeping data device-local.
//
// Passkeys can't be used from inside the app's own WebView (its origin never matches the
// server's RP_ID), so auth here is a short one-time code redeemed from an already signed-in
// browser tab (Settings → "Pair the mobile app") for a bearer token — see api/server.js's
// /api/pair/create + /api/pair/redeem.
import { pairRedeem, setRemoteAuth } from './api.js'
import { loadRemoteFile, saveRemoteFile } from './mobile.js'
// Accepts what someone actually types: bare host, no scheme, trailing slash, stray whitespace.
// Defaults to https:// (self-hosting docs already push for HTTPS; the one exception, localhost,
// still parses fine without a scheme). Returns null for anything that isn't a usable URL at all.
export function normalizeServerUrl(raw) {
const s = String(raw || '').trim()
if (!s) return null
const withScheme = /^[a-z][a-z0-9+.-]*:\/\//i.test(s) ? s : 'https://' + s
try {
const u = new URL(withScheme)
if (!u.hostname) return null
return u.origin
} catch (e) { return null }
}
export async function loadRemote() {
return loadRemoteFile()
}
export async function chooseLocal() {
await saveRemoteFile({ mode: 'local' })
}
export async function forgetRemote() {
await saveRemoteFile({ mode: 'local' })
setRemoteAuth('', null)
}
// Redeems the pairing code, wires api.js at the resolved base, and persists the connection so
// boot() can restore it on the next launch.
export async function connect(rawUrl, code) {
const base = normalizeServerUrl(rawUrl)
if (!base) throw new Error('Enter a valid server address')
const { token, user } = await pairRedeem(base, String(code || '').trim())
setRemoteAuth(base, token)
await saveRemoteFile({ mode: 'remote', base, token, user })
return user
}
+27
View File
@@ -0,0 +1,27 @@
// @vitest-environment happy-dom
import { describe, expect, it } from 'vitest'
import { normalizeServerUrl } from './remote.js'
// The pairing flow lives or dies on this being forgiving about what someone types on a phone
// keyboard, while still refusing input that can't possibly be a server address.
describe('normalizeServerUrl', () => {
it('accepts a bare host and adds https://', () => {
expect(normalizeServerUrl('gym.example.com')).toBe('https://gym.example.com')
})
it('keeps an explicit scheme, including http for LAN testing', () => {
expect(normalizeServerUrl('http://192.168.1.20:8080')).toBe('http://192.168.1.20:8080')
expect(normalizeServerUrl('https://gym.example.com')).toBe('https://gym.example.com')
})
it('trims whitespace and a trailing path/slash down to the origin', () => {
expect(normalizeServerUrl(' gym.example.com/ ')).toBe('https://gym.example.com')
expect(normalizeServerUrl('https://gym.example.com/some/path')).toBe('https://gym.example.com')
})
it('rejects empty or unusable input', () => {
for (const v of ['', ' ', null, undefined, 'not a url at all!!']) {
expect(normalizeServerUrl(v)).toBe(null)
}
})
})
+106
View File
@@ -22,6 +22,112 @@ export function isWarmupRow(set) {
return phaseForSet(set) === 'warmup'
}
// A row's shape beyond warm-up/work: 'straight' (default), 'dropset' (a main set followed by
// weight drops logged with no rest) or 'restpause' (an activation set followed by short-rest
// bursts). Both extras ride on the row itself — same card, not a new set in the array — the
// same trick `phase` uses for warm-ups, so the rest of the app can keep reading a row's own
// `w`/`r` and stay correct without knowing this field exists.
export function setType(set) {
const source = objectOf(set)
return source.type === 'dropset' || source.type === 'restpause' ? source.type : 'straight'
}
export const isDropSet = set => setType(set) === 'dropset'
export const isRestPauseSet = set => setType(set) === 'restpause'
/** A drop-set's weight drops, oldest first; empty for anything else. */
export function dropsOf(set) {
const source = objectOf(set)
return isDropSet(source) && Array.isArray(source.drops) ? source.drops : []
}
/** A rest-pause set's short-rest bursts, oldest first; empty for anything else. */
export function clustersOf(set) {
const source = objectOf(set)
return isRestPauseSet(source) && Array.isArray(source.clusters) ? source.clusters : []
}
/**
* Weight x reps from a drop-set's drops, on top of its own main set. The 1RM estimate and the
* progression engine deliberately read only a row's own `w`/`r` (the heaviest effort), so this
* is the one place a drop-set's extra volume gets added back in for totals.
*
* A rest-pause row is different: its own `r` IS the total (every burst's reps included), and
* `clusters` is only how that total breaks down — not extra volume on top of it. Adding
* `clustersOf(set)` here as well would double-count the same reps twice.
*/
export function extraVolumeOf(set) {
const drops = dropsOf(set)
return drops.reduce((v, d) => v + (Number(d?.w) || 0) * (Number(d?.r) || 0), 0)
}
/** Append a weight drop to a row, marking it a drop-set. */
export function addDrop(set, drop) {
const prev = Array.isArray(objectOf(set).drops) ? objectOf(set).drops : []
return { ...objectOf(set), type: 'dropset', drops: [...prev, { w: Number(drop?.w) || 0, r: Number(drop?.r) || 0 }] }
}
/** Append a short-rest burst to a row, marking it a rest-pause set. */
export function addCluster(set, cluster) {
const prev = Array.isArray(objectOf(set).clusters) ? objectOf(set).clusters : []
return { ...objectOf(set), type: 'restpause', clusters: [...prev, { r: Number(cluster?.r) || 0, restSec: Number(cluster?.restSec) || 0 }] }
}
/** Remove one drop by index. Clearing the last one reverts the row to a straight set. */
export function removeDropAt(set, i) {
const drops = (objectOf(set).drops || []).filter((_, idx) => idx !== i)
return drops.length ? { ...objectOf(set), drops } : { ...objectOf(set), type: 'straight', drops }
}
/** Remove one burst by index. Clearing the last one reverts the row to a straight set. */
export function removeClusterAt(set, i) {
const clusters = (objectOf(set).clusters || []).filter((_, idx) => idx !== i)
return clusters.length ? { ...objectOf(set), clusters } : { ...objectOf(set), type: 'straight', clusters }
}
/** Patch one drop's fields in place (weight/reps steppers edit an existing drop). */
export function setDropAt(set, i, patch) {
const drops = (objectOf(set).drops || []).slice()
if (!drops[i]) return set
drops[i] = { ...drops[i], ...patch }
return { ...objectOf(set), drops }
}
/** Patch one burst's fields in place (a reps stepper edits an existing burst). */
export function setClusterAt(set, i, patch) {
const clusters = (objectOf(set).clusters || []).slice()
if (!clusters[i]) return set
clusters[i] = { ...clusters[i], ...patch }
return { ...objectOf(set), clusters }
}
/** Suggested weight for the next drop: pct% lighter than the previous weight, rounded to .5. */
export function nextDropWeight(prevWeight, pct = 20) {
const p = Math.min(90, Math.max(1, Number(pct) || 20))
return Math.round(Math.max(0, (Number(prevWeight) || 0) * (1 - p / 100)) * 2) / 2
}
/** Suggested reps for the next rest-pause burst: roughly half the previous rep count. */
export function nextBurstReps(prevReps) {
return Math.max(1, Math.round((Number(prevReps) || 0) / 2))
}
/**
* Split a rest-pause total (the extra reps you want past the activation set) into a descending,
* roughly-halving sequence of bursts that adds back up to it — e.g. 12 -> [6, 3, 2, 1]. This is
* what a planned rest-pause exercise configures directly, rather than a burst count picked by
* hand: you say how many reps you want out of the whole rest-pause portion, not how many rests.
*/
export function splitBurstReps(total) {
const bursts = []
let remaining = Math.max(0, Math.round(Number(total) || 0))
while (remaining > 0) {
const burst = Math.min(remaining, nextBurstReps(remaining))
bursts.push(burst)
remaining -= burst
}
return bursts
}
export function normalizeMode(value, fallback = 'reps') {
const token = typeof value === 'string' ? value.trim().toLowerCase() : ''
if (MODES.includes(token)) return token
+181
View File
@@ -0,0 +1,181 @@
import { describe, it, expect } from 'vitest'
import {
phaseForSet, isWarmupRow, modeForSet, modeForEntry,
setType, isDropSet, isRestPauseSet, dropsOf, clustersOf, extraVolumeOf,
addDrop, addCluster, removeDropAt, removeClusterAt, setDropAt, setClusterAt,
nextDropWeight, nextBurstReps, splitBurstReps,
} from './workout-model.js'
describe('phaseForSet / isWarmupRow', () => {
it('reads both the explicit phase and the legacy boolean', () => {
expect(isWarmupRow({ phase: 'warmup' })).toBe(true)
expect(isWarmupRow({ warmup: true })).toBe(true)
expect(isWarmupRow({ phase: 'work' })).toBe(false)
expect(isWarmupRow({})).toBe(false)
})
})
describe('setType / isDropSet / isRestPauseSet', () => {
it('defaults to straight for anything without a recognised type', () => {
expect(setType({})).toBe('straight')
expect(setType({ type: 'nonsense' })).toBe('straight')
expect(setType(null)).toBe('straight')
expect(isDropSet({})).toBe(false)
expect(isRestPauseSet({})).toBe(false)
})
it('recognises drop-set and rest-pause rows', () => {
expect(setType({ type: 'dropset' })).toBe('dropset')
expect(isDropSet({ type: 'dropset' })).toBe(true)
expect(setType({ type: 'restpause' })).toBe('restpause')
expect(isRestPauseSet({ type: 'restpause' })).toBe(true)
})
it('is a separate axis from warm-up — a row is not both at once by construction, but phase never leaks into type', () => {
expect(setType({ phase: 'warmup', type: 'dropset' })).toBe('dropset')
expect(isWarmupRow({ phase: 'warmup', type: 'dropset' })).toBe(true)
})
})
describe('dropsOf / clustersOf', () => {
it('only return rows for their own type', () => {
const drop = { type: 'dropset', drops: [{ w: 80, r: 5 }] }
const burst = { type: 'restpause', clusters: [{ r: 4, restSec: 15 }] }
expect(dropsOf(drop)).toEqual([{ w: 80, r: 5 }])
expect(clustersOf(drop)).toEqual([])
expect(clustersOf(burst)).toEqual([{ r: 4, restSec: 15 }])
expect(dropsOf(burst)).toEqual([])
})
it('is defensive about missing/malformed arrays', () => {
expect(dropsOf({ type: 'dropset' })).toEqual([])
expect(dropsOf({ type: 'dropset', drops: 'nope' })).toEqual([])
expect(clustersOf(null)).toEqual([])
})
})
describe('extraVolumeOf', () => {
it('sums weight x reps across a drop-set\'s own drops', () => {
const set = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }, { w: 60, r: 6 }] }
expect(extraVolumeOf(set)).toBe(80 * 5 + 60 * 6)
})
it('is zero for rest-pause — its own r is already the total across every burst, so clusters are a breakdown, not extra volume', () => {
const set = { type: 'restpause', w: 60, r: 20, clusters: [{ r: 10, restSec: 15 }, { r: 5, restSec: 15 }, { r: 3, restSec: 15 }, { r: 1, restSec: 15 }, { r: 1, restSec: 15 } ] }
expect(extraVolumeOf(set)).toBe(0)
})
it('is zero for a straight or warm-up set', () => {
expect(extraVolumeOf({ w: 100, r: 5 })).toBe(0)
expect(extraVolumeOf({ phase: 'warmup', w: 20, r: 8 })).toBe(0)
})
})
describe('addDrop / addCluster', () => {
it('appends a drop and stamps the row as a drop-set', () => {
const set = { w: 100, r: 5, done: true }
const next = addDrop(set, { w: 80, r: 5 })
expect(next.type).toBe('dropset')
expect(next.drops).toEqual([{ w: 80, r: 5 }])
expect(set.drops).toBeUndefined() // pure — the original row is untouched
expect(addDrop(next, { w: 60, r: 4 }).drops).toEqual([{ w: 80, r: 5 }, { w: 60, r: 4 }])
})
it('appends a burst and stamps the row as a rest-pause set', () => {
const set = { w: 60, r: 8, done: true }
const next = addCluster(set, { r: 4, restSec: 15 })
expect(next.type).toBe('restpause')
expect(next.clusters).toEqual([{ r: 4, restSec: 15 }])
})
})
describe('removeDropAt / removeClusterAt', () => {
it('removes one entry by index, leaving the rest in place', () => {
const set = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }, { w: 60, r: 5 }] }
expect(removeDropAt(set, 0).drops).toEqual([{ w: 60, r: 5 }])
})
it('removes one burst by index', () => {
const set = { type: 'restpause', w: 60, r: 8, clusters: [{ r: 4, restSec: 15 }, { r: 3, restSec: 15 }] }
expect(removeClusterAt(set, 1).clusters).toEqual([{ r: 4, restSec: 15 }])
})
it('reverts the row to a straight set once its last drop/burst is removed', () => {
const drop = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }] }
expect(removeDropAt(drop, 0)).toEqual({ type: 'straight', w: 100, r: 5, drops: [] })
expect(isDropSet(removeDropAt(drop, 0))).toBe(false)
const burst = { type: 'restpause', w: 60, r: 8, clusters: [{ r: 4, restSec: 15 }] }
expect(removeClusterAt(burst, 0)).toEqual({ type: 'straight', w: 60, r: 8, clusters: [] })
expect(isRestPauseSet(removeClusterAt(burst, 0))).toBe(false)
})
})
describe('setDropAt / setClusterAt', () => {
it('patches one drop\'s fields, leaving the others untouched', () => {
const set = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }, { w: 60, r: 5 }] }
expect(setDropAt(set, 0, { w: 82.5 }).drops).toEqual([{ w: 82.5, r: 5 }, { w: 60, r: 5 }])
expect(setDropAt(set, 1, { r: 6 }).drops).toEqual([{ w: 80, r: 5 }, { w: 60, r: 6 }])
})
it('patches one burst\'s reps', () => {
const set = { type: 'restpause', w: 60, r: 8, clusters: [{ r: 4, restSec: 15 }] }
expect(setClusterAt(set, 0, { r: 5 }).clusters).toEqual([{ r: 5, restSec: 15 }])
})
it('is a no-op for an index that does not exist', () => {
const set = { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }] }
expect(setDropAt(set, 3, { w: 1 })).toBe(set)
})
})
describe('nextDropWeight / nextBurstReps', () => {
it('drops by the given percentage, rounded to the nearest .5', () => {
expect(nextDropWeight(100, 20)).toBe(80)
expect(nextDropWeight(80, 20)).toBe(64)
expect(nextDropWeight(61, 10)).toBe(55)
})
it('defaults to 20% and never goes negative', () => {
expect(nextDropWeight(100)).toBe(80)
expect(nextDropWeight(0, 20)).toBe(0)
})
it('roughly halves the previous rep count, floored at 1', () => {
expect(nextBurstReps(8)).toBe(4)
expect(nextBurstReps(1)).toBe(1)
expect(nextBurstReps(0)).toBe(1)
})
})
describe('splitBurstReps', () => {
it('splits a total into a descending, roughly-halving sequence that adds back up to it', () => {
expect(splitBurstReps(12)).toEqual([6, 3, 2, 1])
expect(splitBurstReps(6)).toEqual([3, 2, 1])
expect(splitBurstReps(1)).toEqual([1])
})
it('every split sums exactly to the requested total', () => {
for (const total of [1, 2, 3, 5, 7, 10, 15, 20, 33]) {
expect(splitBurstReps(total).reduce((a, b) => a + b, 0)).toBe(total)
}
})
it('is empty for zero or invalid input', () => {
expect(splitBurstReps(0)).toEqual([])
expect(splitBurstReps(-5)).toEqual([])
expect(splitBurstReps(undefined)).toEqual([])
})
})
describe('modeForSet / modeForEntry stay reps-mode for drop-sets and rest-pause sets', () => {
it('infers reps mode from the row\'s own r field regardless of type', () => {
expect(modeForSet({ type: 'dropset', w: 100, r: 5 })).toBe('reps')
expect(modeForSet({ type: 'restpause', w: 60, r: 8 })).toBe('reps')
})
it('an entry mixing straight and drop-set rows still reads as one reps-mode entry', () => {
const entry = { sets: [{ w: 100, r: 5 }, { type: 'dropset', w: 100, r: 5, drops: [{ w: 80, r: 5 }] }] }
expect(modeForEntry(entry)).toBe('reps')
})
})