Merge remote-tracking branch 'origin/main' into feat/gym-checkin-qr
# Conflicts: # frontend/package-lock.json # frontend/package.json # frontend/src/index.css # frontend/src/lib/pt-br-locale.test.js # frontend/src/locales/hu.js # frontend/src/locales/th.js
This commit is contained in:
commit
3197f9e9be
122 files changed
+18404
-103
No files matched your search
@@ -0,0 +1,46 @@
|
||||
// A fetch for the phone that does not go through the WebView.
|
||||
//
|
||||
// The Coach's HTTP adapters take an injectable `fetch`. In the native app the WebView's origin
|
||||
// is capacitor://localhost, and a provider that has no CORS story for that origin would refuse
|
||||
// the preflight before a single byte of the request went out. CapacitorHttp.request() makes
|
||||
// the call from native code instead, where CORS does not exist.
|
||||
//
|
||||
// Deliberately an explicit shim rather than the `plugins.CapacitorHttp.enabled` switch: that
|
||||
// flag replaces window.fetch for the whole app, which would silently reroute every api() call
|
||||
// a paired phone makes to its own server as well. Only the Coach's provider calls go this way.
|
||||
//
|
||||
// Only the subset the adapters use is implemented: method, headers, a JSON body, an abort
|
||||
// signal, and a response with ok/status/text()/json().
|
||||
export async function nativeFetch(url, init = {}) {
|
||||
let cap = null
|
||||
try { cap = await import('@capacitor/core') } catch { /* not a Capacitor build */ }
|
||||
if (!cap || !cap.Capacitor || !cap.Capacitor.isNativePlatform()) return fetch(url, init)
|
||||
|
||||
const headers = { ...(init.headers || {}) }
|
||||
let data = init.body
|
||||
if (typeof data === 'string') { try { data = JSON.parse(data) } catch { /* send as-is */ } }
|
||||
|
||||
const request = cap.CapacitorHttp.request({
|
||||
url, method: init.method || 'GET', headers, data,
|
||||
// The read timeout is not the job timeout: that is the AbortSignal's job (see abortOf),
|
||||
// and coach-local.js derives it from the provider. This only has to be longer than any
|
||||
// job may legitimately run, so a local model on a laptop is never cut off by the transport.
|
||||
responseType: 'text', connectTimeout: 30000, readTimeout: 40 * 60000
|
||||
})
|
||||
const res = init.signal ? await Promise.race([request, abortOf(init.signal)]) : await request
|
||||
const text = typeof res.data === 'string' ? res.data : res.data == null ? '' : JSON.stringify(res.data)
|
||||
return {
|
||||
ok: res.status >= 200 && res.status < 300,
|
||||
status: res.status,
|
||||
text: async () => text,
|
||||
json: async () => JSON.parse(text)
|
||||
}
|
||||
}
|
||||
|
||||
function abortOf(signal) {
|
||||
return new Promise((_, reject) => {
|
||||
const err = () => reject(Object.assign(new Error('aborted'), { name: 'AbortError' }))
|
||||
if (signal.aborted) return err()
|
||||
signal.addEventListener('abort', err, { once: true })
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
// Talking to the Coach endpoints, and knowing when to stop.
|
||||
//
|
||||
// Jobs are minutes-scale, so the client polls. The one rule worth stating: polling only runs
|
||||
// while a Coach surface is on screen or a job is known to be in flight. An app that pings the
|
||||
// server every thirty seconds forever because a feature exists is an app that costs battery
|
||||
// for a feature nobody is using.
|
||||
|
||||
import { useEffect, useState, useCallback, useRef } from 'react'
|
||||
import { api } from './api.js'
|
||||
import { DEMO } from './demo.js'
|
||||
import { MOBILE } from './mobile.js'
|
||||
import { t } from './i18n.js'
|
||||
import { useStore } from '../store/useStore.js'
|
||||
import { useUI } from '../store/useUI.js'
|
||||
|
||||
const POLL_MS = 3000 // a job is running: often enough to feel live
|
||||
const IDLE_MS = 60000 // a Coach screen is open but nothing is running
|
||||
|
||||
// The demo build has no backend, so it answers these locally with a canned proposal built
|
||||
// from its own seeded profile (lib/coach-demo.js). Everything downstream — validation,
|
||||
// staleness, apply, revert, the log — runs unchanged; only the provider is faked. The module
|
||||
// is imported dynamically so none of it lands in a self-hosted bundle.
|
||||
let demoMod = null
|
||||
const demo = async () => (demoMod = demoMod || await import('./coach-demo.js'))
|
||||
const S = () => useStore.getState().S
|
||||
|
||||
// The mobile build's third answer: a phone that brought its own API key runs the Coach itself
|
||||
// (lib/coach-local.js — the same core the server runs, imported lazily so the catalogue and the
|
||||
// validator only ever load on a phone that chose this). A paired phone takes the api() branch
|
||||
// like the web app does; nothing on the web or demo builds reaches this.
|
||||
let localMod = null
|
||||
const LOCAL = () => MOBILE && useStore.getState().coachLocal?.mode === 'byok'
|
||||
const local = async () => {
|
||||
if (!localMod) {
|
||||
localMod = await import('./coach-local.js')
|
||||
// There is no admin card on a phone: the user is the operator, so failures go to them.
|
||||
localMod.setNotifier(ev => {
|
||||
const toast = useUI.getState().toast
|
||||
if (ev.kind === 'failed') toast(JOB_ERRORS[ev.errorClass] || JOB_ERRORS.internal)
|
||||
else if (ev.kind === 'nochange') toast(t('Nothing to change right now: {0}', String(ev.reading || '').slice(0, 140)))
|
||||
})
|
||||
}
|
||||
return localMod
|
||||
}
|
||||
|
||||
export const coachStatus = async () => DEMO ? (await demo()).demoStatus() : LOCAL() ? (await local()).localStatus() : api('/api/coach/status')
|
||||
export const requestReview = async note => DEMO ? (await demo()).demoReview(S()) : LOCAL() ? (await local()).localReview(S(), note) : api('/api/coach/review', { method: 'POST', body: JSON.stringify({ note: note || '' }) })
|
||||
export const requestPlan = async intake => DEMO ? (await demo()).demoPlan(S(), intake) : LOCAL() ? (await local()).localPlan(S(), intake) : api('/api/coach/plan', { method: 'POST', body: JSON.stringify({ intake }) })
|
||||
export const refinePlan = async text => DEMO ? (await demo()).demoRefine(S()) : LOCAL() ? (await local()).localRefine(S(), text) : api('/api/coach/plan', { method: 'POST', body: JSON.stringify({ refine: text }) })
|
||||
export const requestDebrief = async workoutId => DEMO ? (await demo()).demoDebrief(S(), workoutId) : LOCAL() ? (await local()).localDebrief(S(), workoutId) : api('/api/coach/debrief', { method: 'POST', body: JSON.stringify({ workoutId: workoutId || null }) })
|
||||
// The room: anonymous medians across the profiles on this instance that opted in. Only a
|
||||
// server has a room; a phone with its own key and the demo both answer locally.
|
||||
export const cohortStats = async () => DEMO ? (await demo()).demoCohort(S()) : LOCAL() ? { ok: false, enabled: false } : api('/api/coach/cohort')
|
||||
export const setCohortShare = async share => (DEMO || LOCAL()) ? { ok: true, sharing: !!share } : api('/api/coach/cohort/share', { method: 'POST', body: JSON.stringify({ share: !!share }) })
|
||||
export const resolvePending = async body => DEMO ? (await demo()).demoResolve() : LOCAL() ? (await local()).localResolve(body) : api('/api/coach/pending/resolve', { method: 'POST', body: JSON.stringify(body) })
|
||||
export const forgetCoach = async () => DEMO ? (await demo()).demoResolve() : LOCAL() ? (await local()).localForget() : api('/api/coach/forget', { method: 'POST', body: '{}' })
|
||||
export const disclosure = async () => DEMO ? (await demo()).demoDisclosure() : LOCAL() ? (await local()).localDisclosure() : api('/api/coach/disclosure')
|
||||
|
||||
/* Whose provider account this profile is about to spend. Its own call because the constraint is
|
||||
that the Coach screen states it too, not just the admin card — and because in instance mode a
|
||||
second profile is refused outright, which is something the user has to be able to read before
|
||||
they ask for anything rather than after a job is turned down. */
|
||||
export const coachAccount = async () =>
|
||||
DEMO ? { mode: 'instance', provider: 'demo', providerLabel: 'Demo', account: null, connected: true, reason: null, message: null }
|
||||
: LOCAL() ? { mode: 'device', provider: useStore.getState().coachLocal.provider, providerLabel: null, account: null, connected: true, reason: null, message: null }
|
||||
: api('/api/coach/account')
|
||||
|
||||
/* Admin-only. The token is write-only from the client's side: it goes up once and is never
|
||||
read back, so there is deliberately no "show me the current credential" call to pair with it. */
|
||||
export const connectCredential = body => api('/api/admin/coach/connect', { method: 'POST', body: JSON.stringify(body) })
|
||||
export const disconnectCredential = () => api('/api/admin/coach/disconnect', { method: 'POST', body: '{}' })
|
||||
|
||||
/**
|
||||
* Live job/proposal state.
|
||||
*
|
||||
* `active` lets a caller (the Home card) subscribe only while it is mounted and visible;
|
||||
* everything else keeps the poll off. Errors are swallowed on purpose — a Coach status call
|
||||
* failing while you are mid-workout is not something to interrupt anyone about.
|
||||
*/
|
||||
export function useCoachStatus(active = true) {
|
||||
const [state, setState] = useState({ job: null, pending: null, cap: null, loading: true })
|
||||
const timer = useRef(null)
|
||||
const loop = useRef(null) // the running poll loop's `tick`, so a manual refresh can re-pace it
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
try {
|
||||
const s = await coachStatus()
|
||||
setState({ ...s, loading: false })
|
||||
// A refresh that finds a job in flight — the one the caller just started — must not leave
|
||||
// the loop asleep on its idle cadence: without this the card shows up to a minute after
|
||||
// the job ended, sitting on "thinking…" the whole time.
|
||||
if (s?.job && loop.current) { clearTimeout(timer.current); timer.current = setTimeout(loop.current, POLL_MS) }
|
||||
return s
|
||||
} catch {
|
||||
setState(s => ({ ...s, loading: false }))
|
||||
return null
|
||||
}
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!active) return
|
||||
let stopped = false
|
||||
const tick = async () => {
|
||||
const s = await refresh()
|
||||
if (stopped) return
|
||||
clearTimeout(timer.current)
|
||||
timer.current = setTimeout(tick, s?.job ? POLL_MS : IDLE_MS)
|
||||
}
|
||||
loop.current = tick
|
||||
tick()
|
||||
return () => { stopped = true; loop.current = null; clearTimeout(timer.current) }
|
||||
}, [active, refresh])
|
||||
|
||||
return { ...state, refresh }
|
||||
}
|
||||
|
||||
// Server failure classes, in the app's voice. The provider's own words go to the admin card;
|
||||
// what a lifter needs is what it means for them and whether trying again will help.
|
||||
export const JOB_ERRORS = {
|
||||
off: 'The Coach isn’t set up on this instance.',
|
||||
busy: 'The Coach is already thinking about your training.',
|
||||
cap: 'The Coach is resting — try again tomorrow.',
|
||||
consent: 'The Coach needs your go-ahead first.',
|
||||
timeout: 'The Coach took too long and gave up.',
|
||||
auth: 'The Coach couldn’t sign in to its provider — the instance owner needs to check its setup.',
|
||||
missing: 'The Coach isn’t installed properly on this instance.',
|
||||
provider: 'The Coach couldn’t run — the instance owner needs to check its setup.',
|
||||
unusable: 'The Coach answered with something the app couldn’t use.',
|
||||
restart: 'The server restarted while the Coach was thinking.',
|
||||
nostate: 'The Coach couldn’t read your training data.',
|
||||
noworkout: 'There is no workout to look at yet — log one first.',
|
||||
internal: 'Something went wrong on the server.'
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
// The Coach, in the demo build.
|
||||
//
|
||||
// The GitHub Pages demo has no backend at all, so there is nothing to run a CLI and nothing
|
||||
// to poll. Rather than hide the feature there — it is the most interesting thing the app
|
||||
// does — the demo answers the same calls locally with a canned proposal.
|
||||
//
|
||||
// It is built from the demo profile's actual routines rather than hard-coded, so every id
|
||||
// resolves, the before/after values are real, and applying it exercises exactly the same
|
||||
// code path as a live instance: validate, snapshot, apply, log, revert. What is faked is the
|
||||
// provider, not the feature.
|
||||
//
|
||||
// Nothing here ships in a self-hosted bundle: every entry point is behind DEMO, which Vite
|
||||
// replaces at build time.
|
||||
|
||||
import { EXIDX, EXDB } from './exercises.js'
|
||||
import { modeOf, workoutVolume } from './history.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
import { best1RM } from './onerm.js'
|
||||
import { fmtNum } from './format.js'
|
||||
import { planHash } from './coach.js'
|
||||
import { t } from './i18n.js'
|
||||
|
||||
const DELAY = 2200 // long enough to see "the Coach is thinking…", short enough to forgive
|
||||
|
||||
let pending = null
|
||||
let job = null
|
||||
let timer = null
|
||||
|
||||
const iso = d => d.toISOString().slice(0, 10)
|
||||
|
||||
/** A change-set that reads like a real one, aimed at whatever the demo profile actually has. */
|
||||
function buildReview(S) {
|
||||
const routine = (S.routines || []).find(r => (r.ex || []).length >= 2)
|
||||
if (!routine) return null
|
||||
const reps = (routine.ex || []).filter(e => modeOf(e) === 'reps')
|
||||
const first = reps[0] || routine.ex[0]
|
||||
const second = reps[1] || routine.ex[1]
|
||||
const other = (S.routines || []).find(r => r.id !== routine.id)
|
||||
|
||||
// Something plausible that is *not* in this routine, from the same body part as the first
|
||||
// exercise — a swap the reader can believe rather than a random pick out of 1,324.
|
||||
const bp = EXIDX[first.id]?.bp
|
||||
const swapTo = EXDB.find(e => e.bp === bp && e.eq === 'dumbbell' && !(routine.ex || []).some(x => x.id === e.id))
|
||||
|| EXDB.find(e => e.bp === bp && !(routine.ex || []).some(x => x.id === e.id))
|
||||
|
||||
const sessions = (S.workouts || []).slice(-9)
|
||||
const changes = []
|
||||
if (swapTo) changes.push({
|
||||
id: 'd1', type: 'swap-exercise', target: { routineId: routine.id, exId: first.id },
|
||||
before: EXIDX[first.id]?.n || first.id, after: { id: swapTo.id, name: swapTo.n },
|
||||
why: t('Every top set on this one came in at RPE 9.5 or above for three sessions and the weight has not moved. Swapping the movement for four weeks usually breaks that stall faster than grinding the same one.')
|
||||
})
|
||||
if (second) changes.push({
|
||||
id: 'd2', type: 'sets', target: { routineId: routine.id, exId: second.id },
|
||||
before: second.sets ?? 3, after: Math.max(1, (second.sets ?? 3) - 1),
|
||||
why: t('Sessions have been running about fifteen minutes over. This is the accessory with the least to lose from one set fewer.')
|
||||
})
|
||||
if (other) changes.push({
|
||||
id: 'd3', type: 'week', target: { weekday: 6 }, before: null, after: other.id,
|
||||
why: t('You have moved this session to Saturday three weeks running. Better the plan says so than that you keep overriding it.')
|
||||
})
|
||||
|
||||
return {
|
||||
id: 'demo-review', kind: 'review', createdAt: Date.now(), expiresAt: Date.now() + 864e5,
|
||||
planHash: planHash(S), iteration: 1,
|
||||
summary: t('Three things worth changing, and one worth knowing about. Everything else is working — the squat and the pulls are both progressing on schedule.'),
|
||||
evidence: { from: sessions[0]?.d || iso(new Date(Date.now() - 28 * 864e5)), to: sessions.at(-1)?.d || iso(new Date()), sessions: sessions.length || 9 },
|
||||
changes,
|
||||
notes: [t('Body weight has been flat for four weeks while the goal is to gain. That is a kitchen problem rather than a training one — the plan is not what is holding it back.')]
|
||||
}
|
||||
}
|
||||
|
||||
/** A small, honest starter plan for the demo's creation flow. */
|
||||
function buildPlan(S, intake) {
|
||||
const pick = (bp, eq) => EXDB.find(e => e.bp === bp && (!eq || e.eq === eq)) || EXDB.find(e => e.bp === bp)
|
||||
const days = intake?.preferredDays?.length ? intake.preferredDays.slice(0, 3) : [1, 3, 5]
|
||||
const eq = (intake?.equipment || [])[0] || null
|
||||
const mk = (id, name, sets, reps, why) => ({ id, sets, reps, mode: 'reps', why })
|
||||
const routines = [
|
||||
{
|
||||
id: 'dr1', name: t('Full body A'), emoji: '💪', prog: 'linear',
|
||||
why: t('The two big lower-body and pressing patterns first, while you are fresh.'),
|
||||
ex: [
|
||||
mk(pick('upper legs', eq)?.id, null, 3, 8, t('The main lower-body driver — where most of the strength comes from.')),
|
||||
mk(pick('chest', eq)?.id, null, 3, 10, t('Horizontal pressing, the other half of the session.')),
|
||||
mk(pick('back', eq)?.id, null, 3, 10, t('A pull for every press, so the shoulders stay balanced.'))
|
||||
].filter(e => e.id)
|
||||
},
|
||||
{
|
||||
id: 'dr2', name: t('Full body B'), emoji: '🏋️', prog: 'linear',
|
||||
why: t('The same patterns, different variations — enough overlap to progress, enough difference to stay fresh.'),
|
||||
ex: [
|
||||
mk(pick('upper legs', eq)?.id, null, 3, 10, t('Same pattern, higher reps than day A.')),
|
||||
mk(pick('shoulders', eq)?.id, null, 3, 10, t('Vertical pressing.')),
|
||||
mk(pick('upper arms', eq)?.id, null, 3, 12, t('Direct arm work, since you asked for it.'))
|
||||
].filter(e => e.id)
|
||||
}
|
||||
]
|
||||
const week = {}
|
||||
days.forEach((d, i) => { week[d] = routines[i % routines.length].id })
|
||||
return {
|
||||
id: 'demo-plan', kind: 'create', createdAt: Date.now(), expiresAt: Date.now() + 864e5, iteration: 1,
|
||||
planHash: planHash(S),
|
||||
summary: t('A two-day rotation across three sessions a week, built around the equipment you listed. Compounds first, one pull for every press, and enough overlap between the days that nothing goes two weeks without being trained.'),
|
||||
bundle: {
|
||||
opengym_plan: 1, name: t('Coach plan'),
|
||||
summary: t('A two-day rotation across three sessions a week, built around the equipment you listed. Compounds first, one pull for every press, and enough overlap between the days that nothing goes two weeks without being trained.'),
|
||||
basedOn: (S.workouts || []).length ? t('Based on the training already in this demo profile.') : t('No training history yet — starting conservatively.'),
|
||||
week, routines, customEx: []
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** One session, read back with its own numbers — no plan changes, just what a coach would say after. */
|
||||
function buildDebrief(S, workoutId) {
|
||||
const all = (S.workouts || []).filter(w => w && w.d)
|
||||
const w = all.find(x => x.id === workoutId) || all[all.length - 1]
|
||||
if (!w) return null
|
||||
const done = (w.entries || []).reduce((n, en) => n + (en.sets || []).filter(s => s.done && !isWarmupRow(s)).length, 0)
|
||||
const planned = (w.entries || []).reduce((n, en) => n + (en.sets || []).filter(s => !isWarmupRow(s)).length, 0)
|
||||
const vol = Math.round(Number.isFinite(w.vol) ? w.vol : workoutVolume(w))
|
||||
const prs = (w.prs || []).length
|
||||
const minutes = w.end && w.start ? Math.round((w.end - w.start) / 60000) : null
|
||||
const complete = planned > 0 && done >= planned
|
||||
const score = complete ? (prs ? 9 : 8) : 7
|
||||
const highlights = [
|
||||
complete ? t('Every planned set done — {0} of {1}.', done, planned) : t('{0} of {1} planned sets done.', done, planned),
|
||||
t('{0} {1} moved in total.', fmtNum(vol), S.unit)
|
||||
]
|
||||
if (prs) highlights.push(t('{0} new personal records.', prs))
|
||||
const watch = minutes && minutes > 80 ? [t('{0} minutes is long — rest periods may be creeping up.', minutes)] : [t('Top sets logged without an effort rating; add RIR so the next review can read how hard they were.')]
|
||||
const nextTime = [complete ? t('Add the next load step on the main lift.') : t('Repeat the same loads and get every set.'), t('Keep the session under an hour and a quarter.')]
|
||||
return {
|
||||
id: 'demo-debrief', kind: 'debrief', createdAt: Date.now(), expiresAt: Date.now() + 864e5,
|
||||
planHash: planHash(S), iteration: 1,
|
||||
workout: { id: w.id, d: w.d, name: w.name || null, minutes, vol, sets: done, prs },
|
||||
summary: complete
|
||||
? t('A clean session: everything on the sheet got done and the loads held. This is exactly what progress looks like from the inside — unremarkable, repeated.')
|
||||
: t('Most of the work got done. One or two sets fell short, which is fine once — it becomes a signal if the same sets miss next time.'),
|
||||
score, highlights, watch, nextTime
|
||||
}
|
||||
}
|
||||
|
||||
/** What "the room" would say on a busy instance — five people, plausible medians, your real bests. */
|
||||
export function demoCohort(S) {
|
||||
const since = Date.now() - 56 * 864e5
|
||||
const you = Math.round((S.workouts || []).filter(w => (w.start || new Date(w.d).getTime()) > since).length / 8 * 10) / 10
|
||||
const ids = [...new Set((S.routines || []).flatMap(r => (r.ex || []).map(e => e.id)))].slice(0, 5)
|
||||
const exercises = ids.map(id => {
|
||||
const b = best1RM(S, id)
|
||||
const mine = b ? Math.round(b.est * 10) / 10 : null
|
||||
return { id, name: EXIDX[id]?.n || id, people: 4, median: mine ? Math.round(mine * 0.92) : 60, you: mine }
|
||||
})
|
||||
return { ok: true, enabled: true, sharing: true, people: 5, minPeople: 3, unit: S.unit, sessionsPerWeek: { median: 3, you }, exercises, rankPct: 62 }
|
||||
}
|
||||
|
||||
/* ---------------- the API surface the demo stands in for ---------------- */
|
||||
|
||||
export const demoStatus = () => ({ job, pending, cap: { used: 0, limit: 0 } })
|
||||
|
||||
function start(kind, make) {
|
||||
if (job) throw Object.assign(new Error(t('The Coach is already thinking about your training.')), { status: 409 })
|
||||
job = { id: 'demo-' + kind, kind, state: 'running', startedAt: Date.now() }
|
||||
clearTimeout(timer)
|
||||
timer = setTimeout(() => { pending = make(); job = null }, DELAY)
|
||||
return { job }
|
||||
}
|
||||
export const demoReview = S => start('review', () => buildReview(S))
|
||||
export const demoPlan = (S, intake) => start('create', () => buildPlan(S, intake))
|
||||
export const demoRefine = S => start('create', () => {
|
||||
const p = buildPlan(S, null)
|
||||
return { ...p, iteration: (pending?.iteration || 1) + 1, summary: t('Revised as you asked. Everything you did not question is exactly as it was.') + ' ' + p.summary }
|
||||
})
|
||||
export const demoDebrief = (S, workoutId) => {
|
||||
if (!(S.workouts || []).some(w => w && w.d)) throw Object.assign(new Error(t('There is no workout to look at yet — log one first.')), { status: 409, code: 'noworkout' })
|
||||
return start('debrief', () => buildDebrief(S, workoutId))
|
||||
}
|
||||
export const demoResolve = () => { pending = null; return { ok: true } }
|
||||
export const demoDisclosure = () => ({
|
||||
provider: 'demo', providerLabel: t('the configured AI provider'),
|
||||
categories: ['plan', 'training', 'bodyweight', 'profile', 'prefs'], version: 1
|
||||
})
|
||||
@@ -0,0 +1,37 @@
|
||||
// Mobile build only: how the Coach runs on this phone, and the little it keeps between runs.
|
||||
//
|
||||
// Deliberately NOT part of S. S is the training log — it syncs to a paired server, travels in
|
||||
// the JSON export, and is what "back up your data" means. Which provider this phone talks to,
|
||||
// the pseudonym it uses, today's run count and a proposal waiting to be looked at are device
|
||||
// facts, so they live in their own file next to the remote-pairing one. The API key itself is
|
||||
// not even here: see coach-secrets.js.
|
||||
//
|
||||
// This module is intentionally light. The setup screen imports it before the user has chosen
|
||||
// anything, and the promise there is that nothing AI-shaped loads until they do.
|
||||
import { readJsonFile, writeJsonFile } from './mobile.js'
|
||||
|
||||
const FILE = 'opengym-coach.json'
|
||||
|
||||
export const COACH_MODES = ['off', 'server', 'byok']
|
||||
|
||||
const DEFAULTS = { mode: 'off', provider: null, model: null, baseUrl: null, handle: null, daily: null, pending: null }
|
||||
|
||||
let cache = null
|
||||
export async function loadCoachDevice() {
|
||||
if (cache) return cache
|
||||
const saved = await readJsonFile(FILE)
|
||||
cache = { ...DEFAULTS, ...(saved && typeof saved === 'object' ? saved : {}) }
|
||||
if (!COACH_MODES.includes(cache.mode)) cache.mode = 'off'
|
||||
return cache
|
||||
}
|
||||
export async function saveCoachDevice(patch) {
|
||||
const next = { ...(await loadCoachDevice()), ...patch }
|
||||
cache = next
|
||||
await writeJsonFile(FILE, next)
|
||||
return next
|
||||
}
|
||||
/** The part of it a UI may show: never the pending proposal, never the handle. */
|
||||
export const coachDeviceSettings = d => d ? { mode: d.mode, provider: d.provider, model: d.model, baseUrl: d.baseUrl } : null
|
||||
|
||||
// Test seam.
|
||||
export function _resetCoachDevice() { cache = null }
|
||||
@@ -0,0 +1,106 @@
|
||||
// The numbers behind a Coach card, computed on the device from the same training log the
|
||||
// Coach read — so the chart under a suggestion shows exactly the window the suggestion cites,
|
||||
// and nothing the model wrote is ever taken as a statistic.
|
||||
//
|
||||
// Pure functions over S. Nothing here is persisted: a card recomputes its insights from the
|
||||
// window it names, which is why an old proposal in the thread still draws its chart months
|
||||
// later, against the data as it was then.
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { workoutVolume } from './history.js'
|
||||
import { isWarmupRow } from './workout-model.js'
|
||||
import { bestSetOf } from './onerm.js'
|
||||
|
||||
const median = arr => {
|
||||
const a = arr.filter(n => Number.isFinite(n)).sort((x, y) => x - y)
|
||||
return a.length ? a[Math.floor(a.length / 2)] : null
|
||||
}
|
||||
const bpOf = (S, id) => EXIDX[id]?.bp || (S.customEx || []).find(c => c.id === id)?.bp || null
|
||||
const nameOf = (S, id) => EXIDX[id]?.n || (S.customEx || []).find(c => c.id === id)?.n || id
|
||||
const tsOf = w => w.start || new Date(w.d + 'T12:00:00').getTime()
|
||||
|
||||
/** Workouts inside an inclusive ISO-date window; either bound may be missing. */
|
||||
export function windowWorkouts(S, { from, to } = {}) {
|
||||
return (S.workouts || []).filter(w => w && w.d && (!from || w.d >= from) && (!to || w.d <= to))
|
||||
}
|
||||
|
||||
/**
|
||||
* What a review looked at, in numbers: how much, how long, which body parts, where the body
|
||||
* weight went and which lifts moved. `strength` holds up to `topN` exercises with at least two
|
||||
* estimable sessions in the window, most-trained first, with the first→last e1RM change.
|
||||
*/
|
||||
export function insightsFor(S, win = {}, { topN = 3 } = {}) {
|
||||
const ws = windowWorkouts(S, win)
|
||||
const minutes = ws.map(w => (w.end && w.start ? Math.round((w.end - w.start) / 60000) : null)).filter(n => n > 0)
|
||||
const volume = ws.reduce((n, w) => n + (Number.isFinite(w.vol) ? w.vol : workoutVolume(w)), 0)
|
||||
|
||||
const byBp = {}
|
||||
let setsTotal = 0
|
||||
ws.forEach(w => (w.entries || []).forEach(en => {
|
||||
const n = (en.sets || []).filter(s => s.done && !isWarmupRow(s)).length
|
||||
if (!n) return
|
||||
setsTotal += n
|
||||
const bp = bpOf(S, en.id) || 'other'
|
||||
byBp[bp] = (byBp[bp] || 0) + n
|
||||
}))
|
||||
const bodyParts = Object.entries(byBp).map(([bp, sets]) => ({ bp, sets, share: setsTotal ? sets / setsTotal : 0 }))
|
||||
.sort((a, b) => b.sets - a.sets)
|
||||
|
||||
const from = win.from || ws[0]?.d || null
|
||||
const to = win.to || ws[ws.length - 1]?.d || null
|
||||
const bw = (S.bodyweight || []).filter(b => b && b.d && (!from || b.d >= from) && (!to || b.d <= to))
|
||||
.map(b => ({ t: b.t || new Date(b.d + 'T12:00:00').getTime(), y: b.w, d: b.d }))
|
||||
const bodyweight = {
|
||||
points: bw,
|
||||
delta: bw.length > 1 ? Math.round((bw[bw.length - 1].y - bw[0].y) * 10) / 10 : null,
|
||||
last: bw.length ? bw[bw.length - 1].y : null,
|
||||
goal: Number.isFinite(S.targetW) ? S.targetW : null
|
||||
}
|
||||
|
||||
const series = new Map()
|
||||
ws.forEach(w => (w.entries || []).forEach(en => {
|
||||
const best = bestSetOf(en)
|
||||
if (!best) return
|
||||
if (!series.has(en.id)) series.set(en.id, [])
|
||||
series.get(en.id).push({ t: tsOf(w), d: w.d, y: Math.round(best.est * 10) / 10 })
|
||||
}))
|
||||
const strength = [...series.entries()]
|
||||
.filter(([, pts]) => pts.length >= 2)
|
||||
.sort((a, b) => b[1].length - a[1].length)
|
||||
.slice(0, topN)
|
||||
.map(([id, pts]) => {
|
||||
const first = pts[0].y, last = pts[pts.length - 1].y
|
||||
return { id, name: nameOf(S, id), sessions: pts.length, first, last, delta: Math.round((last - first) * 10) / 10, pct: first ? Math.round((last - first) / first * 100) : 0, points: pts }
|
||||
})
|
||||
|
||||
return {
|
||||
from, to, sessions: ws.length, minutes: median(minutes), volume: Math.round(volume), sets: setsTotal,
|
||||
bodyParts, bodyweight, strength
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One workout against the last time the same routine was trained: the numbers a debrief
|
||||
* card puts above the Coach's words.
|
||||
*/
|
||||
export function sessionInsights(S, workout) {
|
||||
if (!workout) return null
|
||||
const all = (S.workouts || []).filter(w => w && w.d)
|
||||
const idx = all.findIndex(w => (workout.id && w.id === workout.id) || (w.d === workout.d && w.start === workout.start))
|
||||
const before = (idx >= 0 ? all.slice(0, idx) : all).filter(w => w.name && w.name === workout.name)
|
||||
const prev = before[before.length - 1] || null
|
||||
const stat = w => ({
|
||||
volume: Math.round(Number.isFinite(w.vol) ? w.vol : workoutVolume(w)),
|
||||
sets: (w.entries || []).reduce((n, en) => n + (en.sets || []).filter(s => s.done && !isWarmupRow(s)).length, 0),
|
||||
minutes: w.end && w.start ? Math.round((w.end - w.start) / 60000) : null,
|
||||
prs: (w.prs || []).length
|
||||
})
|
||||
const now = stat(workout)
|
||||
const then = prev ? stat(prev) : null
|
||||
const lifts = (workout.entries || []).map(en => {
|
||||
const best = bestSetOf(en)
|
||||
const pe = prev?.entries?.find(x => x.id === en.id)
|
||||
const pb = pe ? bestSetOf(pe) : null
|
||||
return best ? { id: en.id, name: nameOf(S, en.id), est: Math.round(best.est * 10) / 10, w: best.w, r: best.r, prev: pb ? Math.round(pb.est * 10) / 10 : null } : null
|
||||
}).filter(Boolean)
|
||||
return { now, then, prevDate: prev?.d || null, lifts }
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { insightsFor, sessionInsights, windowWorkouts } from './coach-insights.js'
|
||||
import { EXIDX } from './exercises.js'
|
||||
|
||||
// Pick two real catalogue ids from different body parts so the body-part grouping is real.
|
||||
const ids = Object.keys(EXIDX)
|
||||
const chest = ids.find(id => EXIDX[id].bp === 'chest')
|
||||
const legs = ids.find(id => EXIDX[id].bp === 'upper legs')
|
||||
|
||||
const day = (d, h = 10) => new Date(d + 'T' + String(h).padStart(2, '0') + ':00:00').getTime()
|
||||
const w = (id, d, entries, over = {}) => ({ id, d, name: 'Push', start: day(d), end: day(d) + 55 * 60000, entries, ...over })
|
||||
const set = (w_, r, extra = {}) => ({ done: true, w: w_, r, ...extra })
|
||||
|
||||
const S = () => ({
|
||||
unit: 'kg', targetW: 80, customEx: [{ id: 'cx1', n: 'My row', bp: 'back' }],
|
||||
bodyweight: [{ d: '2026-07-01', w: 90 }, { d: '2026-08-02', w: 84 }, { d: '2026-08-10', w: 83 }, { d: '2026-08-20', w: 82.5 }],
|
||||
workouts: [
|
||||
w('w0', '2026-07-20', [{ id: chest, sets: [set(60, 10)] }]), // outside the window
|
||||
w('w1', '2026-08-03', [{ id: chest, sets: [set(40, 8, { phase: 'warmup' }), set(60, 10), set(60, 10)] }, { id: legs, sets: [set(100, 5)] }]),
|
||||
w('w2', '2026-08-06', [{ id: chest, sets: [set(65, 10), set(65, 9)] }, { id: 'cx1', sets: [set(50, 10)] }], { name: 'Pull' }),
|
||||
w('w3', '2026-08-12', [{ id: chest, sets: [set(70, 10), set(70, 10), { done: false, w: 70, r: 0 }] }, { id: legs, sets: [set(110, 5)] }], { prs: [chest] })
|
||||
]
|
||||
})
|
||||
|
||||
describe('insightsFor', () => {
|
||||
const win = { from: '2026-08-01', to: '2026-08-15' }
|
||||
it('counts only the window, and only done, non-warm-up work sets', () => {
|
||||
const i = insightsFor(S(), win)
|
||||
expect(i.sessions).toBe(3)
|
||||
expect(windowWorkouts(S(), win).map(x => x.id)).toEqual(['w1', 'w2', 'w3'])
|
||||
expect(i.sets).toBe(2 + 1 + 2 + 1 + 2 + 1)
|
||||
expect(i.minutes).toBe(55)
|
||||
// volume excludes the warm-up and the unchecked set
|
||||
expect(i.volume).toBe(60 * 10 * 2 + 100 * 5 + 65 * 10 + 65 * 9 + 50 * 10 + 70 * 10 * 2 + 110 * 5)
|
||||
})
|
||||
it('groups sets by body part, custom exercises included, biggest first', () => {
|
||||
const i = insightsFor(S(), win)
|
||||
expect(i.bodyParts[0]).toMatchObject({ bp: 'chest', sets: 6 })
|
||||
expect(i.bodyParts.map(b => b.bp)).toContain('back')
|
||||
expect(i.bodyParts.reduce((n, b) => n + b.share, 0)).toBeCloseTo(1, 5)
|
||||
})
|
||||
it('reads the body weight inside the window with its delta and goal', () => {
|
||||
const i = insightsFor(S(), win)
|
||||
expect(i.bodyweight.points.map(p => p.y)).toEqual([84, 83])
|
||||
expect(i.bodyweight.delta).toBe(-1)
|
||||
expect(i.bodyweight.goal).toBe(80)
|
||||
expect(i.bodyweight.last).toBe(83)
|
||||
})
|
||||
it('tracks estimated 1RM first → last for exercises with two or more sessions, most-trained first', () => {
|
||||
const i = insightsFor(S(), win, { topN: 1 })
|
||||
expect(i.strength).toHaveLength(1)
|
||||
const c = i.strength[0]
|
||||
expect(c.id).toBe(chest)
|
||||
expect(c.sessions).toBe(3)
|
||||
expect(c.last).toBeGreaterThan(c.first)
|
||||
expect(c.pct).toBeGreaterThan(0)
|
||||
expect(c.delta).toBeCloseTo(c.last - c.first, 1)
|
||||
expect(insightsFor(S(), win).strength.length).toBe(2) // chest + legs; the custom row has one session
|
||||
})
|
||||
it('falls back to the workouts’ own span when no window is given', () => {
|
||||
const i = insightsFor(S())
|
||||
expect(i.sessions).toBe(4)
|
||||
expect(i.from).toBe('2026-07-20')
|
||||
expect(i.to).toBe('2026-08-12')
|
||||
})
|
||||
it('is empty-safe', () => {
|
||||
const i = insightsFor({ workouts: [], bodyweight: [] })
|
||||
expect(i.sessions).toBe(0)
|
||||
expect(i.minutes).toBeNull()
|
||||
expect(i.bodyweight.delta).toBeNull()
|
||||
expect(i.strength).toEqual([])
|
||||
})
|
||||
})
|
||||
|
||||
describe('sessionInsights', () => {
|
||||
it('compares a workout with the previous one of the same name', () => {
|
||||
const s = S()
|
||||
const r = sessionInsights(s, s.workouts[3]) // w3 'Push' — previous Push is w1
|
||||
expect(r.prevDate).toBe('2026-08-03')
|
||||
expect(r.now.sets).toBe(3)
|
||||
expect(r.now.prs).toBe(1)
|
||||
expect(r.then.sets).toBe(3)
|
||||
expect(r.now.volume - r.then.volume).toBe((70 * 10 * 2 + 110 * 5) - (60 * 10 * 2 + 100 * 5))
|
||||
const chestLift = r.lifts.find(l => l.id === chest)
|
||||
expect(chestLift.w).toBe(70)
|
||||
expect(chestLift.prev).not.toBeNull()
|
||||
expect(chestLift.est).toBeGreaterThan(chestLift.prev)
|
||||
})
|
||||
it('has no comparison when the name was never trained before', () => {
|
||||
const s = S()
|
||||
const r = sessionInsights(s, s.workouts[2]) // the only 'Pull'
|
||||
expect(r.then).toBeNull()
|
||||
expect(r.prevDate).toBeNull()
|
||||
expect(r.lifts.every(l => l.prev === null)).toBe(true)
|
||||
})
|
||||
it('returns null for nothing', () => { expect(sessionInsights(S(), null)).toBeNull() })
|
||||
})
|
||||
@@ -0,0 +1,184 @@
|
||||
// The Coach, on a phone that brings its own API key.
|
||||
//
|
||||
// No server. The pipeline the server runs — payload allowlist, prompt, provider call, parser,
|
||||
// validator, one repair round — is imported from api/coach/core and run here, in-process, so
|
||||
// the phone gets exactly the code the server has and not a second opinion of it. The apply
|
||||
// engine, staleness, snapshot/revert and the log are the ones every build already uses.
|
||||
//
|
||||
// This module is the one static importer of the core, which makes `import('./coach-local.js')`
|
||||
// the whole lazy chunk: the exercise catalogue, the prompts and the validator arrive together
|
||||
// and only after the user chose this mode. coach-api.js dispatches here the same way it
|
||||
// dispatches to the demo provider, so the screens never learn that there is no server.
|
||||
//
|
||||
// What is different from the server, and on purpose:
|
||||
// - the user pays. There is no cfg.caps to lean on, so a local daily cap is not optional.
|
||||
// - the pseudonym is drawn at random once and kept, rather than derived from a secret.
|
||||
// - a proposal waits in the device file, not in S, so it survives an app kill without
|
||||
// riding into a backup or a sync.
|
||||
import * as payloadLib from '../../../api/coach/core/payload.js'
|
||||
import { runPipeline } from '../../../api/coach/core/pipeline.js'
|
||||
import { HTTP_PROVIDERS, baseUrlFor } from '../../../api/coach/core/providers.js'
|
||||
import anthropic from '../../../api/coach/core/adapters/anthropic.js'
|
||||
import openai from '../../../api/coach/core/adapters/openai.js'
|
||||
import gemini from '../../../api/coach/core/adapters/gemini.js'
|
||||
import compatible from '../../../api/coach/core/adapters/compatible.js'
|
||||
import { nativeFetch } from './capacitor-fetch.js'
|
||||
import { getApiKey } from './coach-secrets.js'
|
||||
import { loadCoachDevice, saveCoachDevice } from './coach-device.js'
|
||||
import { planHash } from './coach.js'
|
||||
import { todayISO } from './format.js'
|
||||
import { t } from './i18n.js'
|
||||
|
||||
export const ADAPTERS = { anthropic, openai, gemini, compatible }
|
||||
export const LOCAL_DAILY_CAP = 10
|
||||
// Five minutes is right for a cloud API and wrong for a model on somebody's laptop; the
|
||||
// OpenAI-compatible endpoint is the one that may be local, so it gets the long budget.
|
||||
export const TIMEOUT_MS = 5 * 60000
|
||||
export const LOCAL_ENDPOINT_TIMEOUT_MS = 25 * 60000
|
||||
export const timeoutFor = provider => (provider === 'compatible' ? LOCAL_ENDPOINT_TIMEOUT_MS : TIMEOUT_MS)
|
||||
const PENDING_DAYS = 14
|
||||
const HANDLE_LENGTH = 16
|
||||
|
||||
let job = null
|
||||
let lastError = null
|
||||
let last = null // how the most recent job ended — the same shape the server's status() reports
|
||||
// Reported to the screens through the same status shape the server answers with; a toast is
|
||||
// also raised because on the server a failed job lands in the admin card, and here there is
|
||||
// no admin card — the user is the operator.
|
||||
let notify = null
|
||||
export function setNotifier(fn) { notify = fn }
|
||||
|
||||
/* ---------- what this phone is configured with ---------- */
|
||||
|
||||
const cfgOf = d => ({ provider: d.provider, providerOptions: d.baseUrl ? { [d.provider]: { baseUrl: d.baseUrl } } : {} })
|
||||
const envOf = (d, key) => (key ? { [HTTP_PROVIDERS[d.provider].apiKeyEnv]: key } : {})
|
||||
|
||||
function mintHandle() {
|
||||
const bytes = new Uint8Array(12)
|
||||
;(globalThis.crypto || {}).getRandomValues ? crypto.getRandomValues(bytes) : bytes.forEach((_, i) => { bytes[i] = Math.floor(Math.random() * 256) })
|
||||
let bin = ''; bytes.forEach(b => { bin += String.fromCharCode(b) })
|
||||
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '').slice(0, HANDLE_LENGTH)
|
||||
}
|
||||
async function handle() {
|
||||
const d = await loadCoachDevice()
|
||||
if (d.handle && d.handle.length === HANDLE_LENGTH) return d.handle
|
||||
const h = mintHandle()
|
||||
await saveCoachDevice({ handle: h })
|
||||
return h
|
||||
}
|
||||
|
||||
/* ---------- the cap ---------- */
|
||||
|
||||
async function capState() {
|
||||
const d = await loadCoachDevice()
|
||||
const today = todayISO()
|
||||
const used = d.daily && d.daily.d === today ? d.daily.n : 0
|
||||
return { used, limit: LOCAL_DAILY_CAP }
|
||||
}
|
||||
async function bumpDaily() {
|
||||
const { used } = await capState()
|
||||
await saveCoachDevice({ daily: { d: todayISO(), n: used + 1 } })
|
||||
}
|
||||
|
||||
/* ---------- the API surface coach-api.js dispatches to ---------- */
|
||||
|
||||
export async function localStatus() {
|
||||
const d = await loadCoachDevice()
|
||||
if (d.pending && d.pending.expiresAt && d.pending.expiresAt < Date.now()) await saveCoachDevice({ pending: null })
|
||||
return { job, pending: (await loadCoachDevice()).pending || null, cap: await capState(), lastError, last }
|
||||
}
|
||||
|
||||
export const localReview = (S, note) => start(S, 'review', { note: note ? String(note).slice(0, 1000) : null })
|
||||
export const localPlan = (S, intake) => start(S, 'create', { intake: intake || null })
|
||||
export const localRefine = async (S, text) => {
|
||||
const d = await loadCoachDevice()
|
||||
const pendingCreate = d.pending && d.pending.kind === 'create' ? d.pending : null
|
||||
return start(S, 'create', { refine: String(text || '').slice(0, 1000), previous: pendingCreate?.bundle || null, iteration: (pendingCreate?.iteration || 1) + 1 })
|
||||
}
|
||||
export const localDebrief = (S, workoutId) => start(S, 'debrief', { workoutId: workoutId || null })
|
||||
export async function localResolve() { await saveCoachDevice({ pending: null }); return { ok: true } }
|
||||
export async function localForget() { job = null; lastError = null; await saveCoachDevice({ pending: null, daily: null }); return { ok: true } }
|
||||
|
||||
export async function localDisclosure() {
|
||||
const d = await loadCoachDevice()
|
||||
const meta = HTTP_PROVIDERS[d.provider] || {}
|
||||
const base = d.provider ? baseUrlFor(d.provider, cfgOf(d)) : ''
|
||||
return {
|
||||
provider: d.provider, providerLabel: meta.label || t('the configured AI provider'),
|
||||
categories: payloadLib.DATA_CATEGORIES, version: 1,
|
||||
// The honest difference from the self-hosted flow: it is the user's own account.
|
||||
payer: 'you', host: hostOf(base)
|
||||
}
|
||||
}
|
||||
|
||||
/** The models the configured endpoint serves — the setup screen's list, and its reachability test. */
|
||||
export async function localModels(settings, key) {
|
||||
const adapter = ADAPTERS[settings.provider]
|
||||
if (!adapter) return { ok: false, error: 'unknown provider', models: [] }
|
||||
return adapter.models(cfgOf(settings), envOf(settings, key), { fetch: nativeFetch, timeoutMs: 20000 })
|
||||
}
|
||||
|
||||
const hostOf = url => { try { return new URL(url).host } catch { return url || '' } }
|
||||
|
||||
/* ---------- running a job ---------- */
|
||||
|
||||
async function start(S, kind, opts) {
|
||||
if (job) throw Object.assign(new Error(t('The Coach is already thinking about your training.')), { status: 409, code: 'busy' })
|
||||
if (!S?.coach?.consent?.agreedAt) throw Object.assign(new Error(t('The Coach needs your go-ahead first.')), { status: 403, code: 'consent' })
|
||||
const d = await loadCoachDevice()
|
||||
const adapter = ADAPTERS[d.provider]
|
||||
if (d.mode !== 'byok' || !adapter) throw Object.assign(new Error(t('The Coach isn’t set up on this phone.')), { status: 503, code: 'off' })
|
||||
const cap = await capState()
|
||||
if (cap.used >= cap.limit) throw Object.assign(new Error(t('The Coach is resting — you have used today’s {0} runs on this phone.', cap.limit)), { status: 429, code: 'cap' })
|
||||
|
||||
await bumpDaily()
|
||||
job = { id: 'local-' + Date.now().toString(36), kind, state: 'running', startedAt: Date.now() }
|
||||
lastError = null
|
||||
// Not awaited: the screens poll, exactly as they do against a server.
|
||||
run(S, kind, opts, d, adapter).catch(e => { lastError = { errorClass: 'internal', detail: String(e && e.message || e) } }).finally(() => { job = null })
|
||||
return { job }
|
||||
}
|
||||
|
||||
async function run(S, kind, opts, d, adapter) {
|
||||
const key = await getApiKey()
|
||||
const payload = payloadLib.build(S, {
|
||||
handle: await handle(), kind, intake: opts.intake, note: opts.note, refine: opts.refine, previous: opts.previous, workoutId: opts.workoutId
|
||||
})
|
||||
const attempt = await runPipeline({
|
||||
adapter, cfg: cfgOf(d), kind, payload,
|
||||
model: d.model || HTTP_PROVIDERS[d.provider].defaultModel, timeoutMs: timeoutFor(d.provider),
|
||||
invokeOpts: { env: envOf(d, key), fetch: nativeFetch }
|
||||
})
|
||||
if (!attempt.ok) {
|
||||
lastError = { errorClass: attempt.errorClass, detail: attempt.detail || null }
|
||||
last = { id: job.id, kind, outcome: 'failed', errorClass: attempt.errorClass, at: Date.now() }
|
||||
if (notify) notify({ kind: 'failed', errorClass: attempt.errorClass, detail: attempt.detail || null })
|
||||
return
|
||||
}
|
||||
if (attempt.nochange) {
|
||||
last = { id: job.id, kind, outcome: 'nochange', errorClass: null, at: Date.now(), reading: attempt.reading }
|
||||
if (notify) notify({ kind: 'nochange', reading: attempt.reading })
|
||||
return
|
||||
}
|
||||
const pending = {
|
||||
id: job.id, kind, createdAt: Date.now(), expiresAt: Date.now() + PENDING_DAYS * 86400000,
|
||||
planHash: planHash(S), iteration: opts.iteration || 1,
|
||||
...(kind === 'debrief' ? { workout: workoutMetaOf(S, opts.workoutId) } : {}),
|
||||
...attempt.result
|
||||
}
|
||||
await saveCoachDevice({ pending })
|
||||
last = { id: job.id, kind, outcome: 'ready', errorClass: null, at: Date.now() }
|
||||
if (notify) notify({ kind: 'ready', pending })
|
||||
}
|
||||
|
||||
// The session a debrief is about, in the shape the card reads. The core builds it for the
|
||||
// server; the fallback covers a core that predates it.
|
||||
function workoutMetaOf(S, workoutId) {
|
||||
if (typeof payloadLib.workoutMeta === 'function') return payloadLib.workoutMeta(S, workoutId)
|
||||
const all = (S.workouts || []).filter(w => w && w.d)
|
||||
const w = all.find(x => x.id === workoutId) || all[all.length - 1]
|
||||
return w ? { id: w.id, d: w.d, name: w.name || null } : null
|
||||
}
|
||||
|
||||
// Test seam.
|
||||
export function _resetLocal() { job = null; lastError = null; last = null }
|
||||
@@ -0,0 +1,196 @@
|
||||
// The Coach on a phone with its own key: the same core the server runs, driven end to end
|
||||
// here with a fake provider — payload → prompt → HTTP adapter → parser → validator → a proposal
|
||||
// the apply engine accepts. Also the three things this mode has to get right on its own: the
|
||||
// daily cap, the key never touching S, and a proposal surviving in the device file.
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
|
||||
// The device file and the secret store are in-memory here; nativeFetch is the script.
|
||||
const device = { data: null }
|
||||
vi.mock('./mobile.js', () => ({
|
||||
MOBILE: true,
|
||||
readJsonFile: async () => device.data,
|
||||
writeJsonFile: async (_n, d) => { device.data = JSON.parse(JSON.stringify(d)) }
|
||||
}))
|
||||
const secret = { key: 'sk-test-1' }
|
||||
vi.mock('./coach-secrets.js', () => ({ getApiKey: async () => secret.key, setApiKey: async v => { secret.key = v }, clearApiKey: async () => { secret.key = null } }))
|
||||
const wire = { calls: [], answer: null }
|
||||
vi.mock('./capacitor-fetch.js', () => ({
|
||||
nativeFetch: async (url, init) => {
|
||||
wire.calls.push({ url, init, body: JSON.parse(init.body) })
|
||||
const a = typeof wire.answer === 'function' ? wire.answer(wire.calls.length) : wire.answer
|
||||
return { ok: a.status < 300, status: a.status, text: async () => JSON.stringify(a.body), json: async () => a.body }
|
||||
}
|
||||
}))
|
||||
|
||||
const local = await import('./coach-local.js')
|
||||
const { _resetCoachDevice, loadCoachDevice, saveCoachDevice } = await import('./coach-device.js')
|
||||
const { applyChangeSet, markStale, planHash } = await import('./coach.js')
|
||||
const { EXERCISES } = await import('../../../api/coach/core/library-data.js')
|
||||
|
||||
const EX = EXERCISES[0].id, EX2 = EXERCISES[1].id
|
||||
const state = () => ({
|
||||
unit: 'kg', lang: 'en',
|
||||
routines: [{ id: 'r1', name: 'A', ex: [{ id: EX, sets: 3, reps: 8, mode: 'reps' }, { id: EX2, sets: 3, reps: 10, mode: 'reps' }] }],
|
||||
week: { 1: 'r1' }, dayPlan: {}, customEx: [], bodyweight: [], workouts: [
|
||||
{ d: '2026-08-20', start: 1, end: 3600001, entries: [{ id: EX, target: { sets: 3, reps: 8 }, sets: [{ done: true, w: 40, r: 8 }, { done: true, w: 40, r: 8 }, { done: true, w: 40, r: 8 }] }] }
|
||||
],
|
||||
coach: { consent: { agreedAt: '2026-08-01T00:00:00Z', version: 1 }, profile: null, cadence: 'off', lastReview: null, log: [], snapshots: [] }
|
||||
})
|
||||
const chat = content => ({ status: 200, body: { choices: [{ finish_reason: 'stop', message: { content } }] } })
|
||||
const review = { coach_contract: 1, summary: 'One tweak.', evidence: { from: '2026-08-01', to: '2026-08-20', sessions: 1 },
|
||||
changes: [{ id: 'c1', type: 'sets', target: { routineId: 'r1', exId: EX }, after: 4, why: 'every set was clean' }] }
|
||||
|
||||
async function settle() {
|
||||
for (let i = 0; i < 200; i++) {
|
||||
const s = await local.localStatus()
|
||||
if (!s.job) return s
|
||||
await new Promise(r => setTimeout(r, 5))
|
||||
}
|
||||
throw new Error('never settled')
|
||||
}
|
||||
|
||||
describe('the Coach on a phone with its own key', () => {
|
||||
beforeEach(async () => {
|
||||
_resetCoachDevice(); local._resetLocal()
|
||||
device.data = { mode: 'byok', provider: 'openai', model: 'gpt-t', baseUrl: null }
|
||||
wire.calls = []; wire.answer = chat(JSON.stringify(review)); secret.key = 'sk-test-1'
|
||||
})
|
||||
|
||||
it('runs a review through the real pipeline and produces a proposal the apply engine accepts', async () => {
|
||||
const S = state()
|
||||
await local.localReview(S, 'shoulder')
|
||||
const s = await settle()
|
||||
expect(s.pending).toBeTruthy()
|
||||
expect(s.pending.kind).toBe('review')
|
||||
expect(s.pending.planHash).toBe(planHash(S))
|
||||
expect(s.pending.changes).toHaveLength(1)
|
||||
expect(s.pending.changes[0].before).toBe(3) // computed server-side… which is here
|
||||
// What went on the wire: OpenAI's shape, the key as a bearer, the payload in the user turn.
|
||||
expect(wire.calls).toHaveLength(1)
|
||||
expect(wire.calls[0].url).toBe('https://api.openai.com/v1/chat/completions')
|
||||
expect(wire.calls[0].init.headers.authorization).toBe('Bearer sk-test-1')
|
||||
expect(wire.calls[0].body.model).toBe('gpt-t')
|
||||
expect(wire.calls[0].body.messages[1].content).toContain('"userNote":"shoulder"')
|
||||
// …and the proposal applies with the ordinary engine.
|
||||
const marked = markStale(s.pending, S)
|
||||
expect(marked.changes[0].status).not.toBe('stale')
|
||||
applyChangeSet(S, marked, ['c1'])
|
||||
expect(S.routines[0].ex[0].sets).toBe(4)
|
||||
expect(S.coach.snapshots).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('spends the single repair round when the first answer is unusable, then gives up', async () => {
|
||||
wire.answer = n => n === 1 ? chat('{"coach_contract":1,"changes":[{"id":"x","type":"teleport"}]}') : chat(JSON.stringify(review))
|
||||
await local.localReview(state())
|
||||
const s = await settle()
|
||||
expect(wire.calls).toHaveLength(2)
|
||||
expect(wire.calls[1].body.messages[1].content).toContain('teleport') // the errors went back verbatim
|
||||
expect(s.pending.changes).toHaveLength(1)
|
||||
|
||||
local._resetLocal(); wire.calls = []
|
||||
await saveCoachDevice({ pending: null })
|
||||
wire.answer = chat('not json at all')
|
||||
await local.localReview(state())
|
||||
const f = await settle()
|
||||
expect(wire.calls).toHaveLength(2)
|
||||
expect(f.pending).toBeNull()
|
||||
expect(f.lastError.errorClass).toBe('unusable')
|
||||
})
|
||||
|
||||
it('a 401 is an auth failure, and never a proposal', async () => {
|
||||
wire.answer = { status: 401, body: { error: { message: 'bad key' } } }
|
||||
await local.localReview(state())
|
||||
const s = await settle()
|
||||
expect(s.pending).toBeNull()
|
||||
expect(s.lastError.errorClass).toBe('auth')
|
||||
})
|
||||
|
||||
it('the key never enters S, the device file, or the proposal', async () => {
|
||||
const S = state()
|
||||
await local.localReview(S)
|
||||
const s = await settle()
|
||||
expect(JSON.stringify(S)).not.toContain('sk-test-1')
|
||||
expect(JSON.stringify(device.data)).not.toContain('sk-test-1')
|
||||
expect(JSON.stringify(s.pending)).not.toContain('sk-test-1')
|
||||
})
|
||||
|
||||
it('mints one 16-character pseudonym and keeps it; the payload carries it and never a name', async () => {
|
||||
await local.localReview({ ...state(), name: 'Duarte' })
|
||||
await settle()
|
||||
const first = (await loadCoachDevice()).handle
|
||||
expect(first).toHaveLength(16)
|
||||
const payload = wire.calls[0].body.messages[1].content
|
||||
expect(payload).toContain(`"profile":"${first}"`)
|
||||
expect(payload).not.toContain('Duarte')
|
||||
local._resetLocal(); await saveCoachDevice({ pending: null })
|
||||
await local.localReview(state()); await settle()
|
||||
expect((await loadCoachDevice()).handle).toBe(first)
|
||||
})
|
||||
|
||||
it('refuses without consent, refuses while busy, and stops at the daily cap', async () => {
|
||||
const noConsent = state(); noConsent.coach.consent = null
|
||||
await expect(local.localReview(noConsent)).rejects.toMatchObject({ code: 'consent' })
|
||||
|
||||
await local.localReview(state())
|
||||
await expect(local.localReview(state())).rejects.toMatchObject({ code: 'busy' })
|
||||
await settle()
|
||||
|
||||
await saveCoachDevice({ daily: { d: new Date().toISOString().slice(0, 10), n: local.LOCAL_DAILY_CAP } })
|
||||
await expect(local.localReview(state())).rejects.toMatchObject({ code: 'cap' })
|
||||
expect((await local.localStatus()).cap).toEqual({ used: local.LOCAL_DAILY_CAP, limit: local.LOCAL_DAILY_CAP })
|
||||
})
|
||||
|
||||
it('a proposal waits in the device file, expires, and is cleared by resolve', async () => {
|
||||
await local.localReview(state())
|
||||
await settle()
|
||||
expect(device.data.pending).toBeTruthy()
|
||||
await saveCoachDevice({ pending: { ...device.data.pending, expiresAt: Date.now() - 1 } })
|
||||
expect((await local.localStatus()).pending).toBeNull()
|
||||
await local.localReview(state()); await settle()
|
||||
await local.localResolve()
|
||||
expect(device.data.pending).toBeNull()
|
||||
})
|
||||
|
||||
it('creates a plan from an intake, and refines it against the previous bundle', async () => {
|
||||
const plan = { coach_contract: 1, opengym_plan: 1, name: 'P', summary: 's', basedOn: 'b', week: { 1: 'r1', 3: 'r2', 5: 'r1' },
|
||||
routines: [
|
||||
{ id: 'r1', name: 'A', emoji: '💪', why: 'w', ex: [{ id: EX, sets: 3, mode: 'reps', reps: 8, why: 'w' }, { id: EX2, sets: 3, mode: 'reps', reps: 10, why: 'w' }, { id: EXERCISES[2].id, sets: 3, mode: 'reps', reps: 10, why: 'w' }] },
|
||||
{ id: 'r2', name: 'B', emoji: '🏋️', why: 'w', ex: [{ id: EXERCISES[3].id, sets: 3, mode: 'reps', reps: 8, why: 'w' }, { id: EXERCISES[4].id, sets: 3, mode: 'reps', reps: 10, why: 'w' }, { id: EXERCISES[5].id, sets: 3, mode: 'reps', reps: 10, why: 'w' }] }
|
||||
], customEx: [] }
|
||||
wire.answer = chat(JSON.stringify(plan))
|
||||
const S = { ...state(), routines: [], week: {} }
|
||||
await local.localPlan(S, { goal: 'muscle', daysPerWeek: 3 })
|
||||
const s = await settle()
|
||||
expect(s.pending.kind).toBe('create')
|
||||
expect(s.pending.bundle.routines).toHaveLength(2)
|
||||
expect(wire.calls[0].body.messages[1].content).toContain('"daysPerWeek":3')
|
||||
|
||||
await local.localRefine(S, 'no lunges')
|
||||
const r = await settle()
|
||||
expect(r.pending.iteration).toBe(2)
|
||||
expect(wire.calls[1].body.messages[1].content).toContain('no lunges')
|
||||
expect(wire.calls[1].body.messages[1].content).toContain('"previous"')
|
||||
})
|
||||
|
||||
it('disclosure says who pays and where it goes', async () => {
|
||||
const d = await local.localDisclosure()
|
||||
expect(d.payer).toBe('you')
|
||||
expect(d.host).toBe('api.openai.com')
|
||||
expect(d.categories).toEqual(['plan', 'training', 'bodyweight', 'profile', 'prefs'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('timeouts on the phone', () => {
|
||||
it('gives a local endpoint the long budget and cloud providers the short one', async () => {
|
||||
const { timeoutFor, TIMEOUT_MS, LOCAL_ENDPOINT_TIMEOUT_MS } = await import('./coach-local.js')
|
||||
expect(timeoutFor('compatible')).toBe(LOCAL_ENDPOINT_TIMEOUT_MS)
|
||||
expect(LOCAL_ENDPOINT_TIMEOUT_MS).toBeGreaterThanOrEqual(20 * 60000)
|
||||
for (const p of ['anthropic', 'openai', 'gemini']) expect(timeoutFor(p)).toBe(TIMEOUT_MS)
|
||||
})
|
||||
it('the native transport read timeout outlasts the longest job', async () => {
|
||||
const src = (await import('node:fs')).readFileSync(new URL('./capacitor-fetch.js', import.meta.url), 'utf8')
|
||||
const m = src.match(/readTimeout:\s*(\d+)\s*\*\s*60000/)
|
||||
expect(m).toBeTruthy()
|
||||
expect(+m[1] * 60000).toBeGreaterThan(25 * 60000)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,70 @@
|
||||
/* The server's copies of three tiny reading rules, pinned against the frontend's originals.
|
||||
*
|
||||
* api/coach/payload.js re-implements modeOf, isBw and isPerSide because the api container has
|
||||
* no build step in common with the frontend and does not copy frontend/ into its image. That
|
||||
* trade-off is fine; what is not fine is the copy drifting, which is exactly what happened
|
||||
* when v1.2.4 taught the app about bodyweight work and per-side reps: the server kept reading
|
||||
* every set as a loaded rep set, so a push-up progression that was working would have looked
|
||||
* like a stalled bench press with the weight left at zero.
|
||||
*
|
||||
* This test only runs under vitest, which can load both runtimes. It compares behaviour over a
|
||||
* table of configs rather than comparing source, so the two are free to be written differently
|
||||
* as long as they answer the same.
|
||||
*/
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { modeOf as uiModeOf, isBw as uiIsBw, isPerSide as uiIsPerSide } from './history.js'
|
||||
import { modeOf as srvModeOf, isBw as srvIsBw, isPerSide as srvIsPerSide } from '../../../api/coach/core/payload.js'
|
||||
import { exOr } from './exercises.js'
|
||||
|
||||
// Real ids from the catalogue, so `eq`/`bp` are whatever the dataset actually says rather than
|
||||
// whatever this test assumed. 0001 is a bodyweight sit-up; the others are looked up the same way.
|
||||
const IDS = ['0001', '0025', '0043', 'no-such-exercise']
|
||||
|
||||
const CONFIGS = [
|
||||
{},
|
||||
{ mode: 'reps' },
|
||||
{ mode: 'time' },
|
||||
{ mode: 'cardio' },
|
||||
{ mode: 'nonsense' },
|
||||
{ mode: '' },
|
||||
{ bodyweight: true },
|
||||
{ bodyweight: false },
|
||||
{ bodyweight: true, mode: 'time' },
|
||||
{ side: true },
|
||||
{ side: false },
|
||||
{ side: true, bodyweight: true, mode: 'reps' },
|
||||
{ reps: 8, sets: 3 },
|
||||
{ repsMax: 20, reps: 12 }
|
||||
]
|
||||
|
||||
describe('server/client reading rules agree', () => {
|
||||
for (const id of IDS) {
|
||||
const ex = exOr(id)
|
||||
for (const base of CONFIGS) {
|
||||
const cfg = { ...base, id }
|
||||
const label = `${id} ${JSON.stringify(base)}`
|
||||
|
||||
it(`modeOf — ${label}`, () => {
|
||||
expect(srvModeOf(cfg, ex)).toBe(uiModeOf(cfg))
|
||||
})
|
||||
|
||||
it(`isBw — ${label}`, () => {
|
||||
expect(srvIsBw(cfg, ex)).toBe(uiIsBw(cfg))
|
||||
})
|
||||
|
||||
it(`isPerSide — ${label}`, () => {
|
||||
expect(srvIsPerSide(cfg)).toBe(uiIsPerSide(cfg))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
it('an explicit flag beats the catalogue, on both sides', () => {
|
||||
const bodyweightEx = exOr('0001')
|
||||
expect(uiIsBw({ id: '0001' })).toBe(true)
|
||||
expect(srvIsBw({ id: '0001' }, bodyweightEx)).toBe(true)
|
||||
// A dip done with a belt turns it off; the server must agree, or it keeps reading the
|
||||
// added load as no load.
|
||||
expect(uiIsBw({ id: '0001', bodyweight: false })).toBe(false)
|
||||
expect(srvIsBw({ id: '0001', bodyweight: false }, bodyweightEx)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
// Where the phone keeps the user's own API key: the platform's secure storage — the Keychain on
|
||||
// iOS, the Keystore-backed EncryptedSharedPreferences on Android — and nowhere else. Never in
|
||||
// S (which syncs and exports), never in localStorage (which the WebView evicts and any page on
|
||||
// the same origin can read), never in the coach device file next to it.
|
||||
//
|
||||
// The plugin is imported lazily and every call is wrapped: on a plain web dev run it stores
|
||||
// to localStorage by its own admission, and in a test there is no platform at all. In both
|
||||
// cases the fallback is a process-local map that forgets on reload, which is the honest
|
||||
// behaviour for a place that cannot keep a secret.
|
||||
const KEY = 'coach.apiKey'
|
||||
const memory = new Map()
|
||||
|
||||
let pluginPromise = null
|
||||
function plugin() {
|
||||
if (!pluginPromise) {
|
||||
pluginPromise = import('@aparajita/capacitor-secure-storage')
|
||||
.then(m => (m && m.SecureStorage && typeof m.SecureStorage.get === 'function' ? m.SecureStorage : null))
|
||||
.catch(() => null)
|
||||
}
|
||||
return pluginPromise
|
||||
}
|
||||
|
||||
export async function getApiKey() {
|
||||
const p = await plugin()
|
||||
if (p) {
|
||||
try { const v = await p.get(KEY); return typeof v === 'string' && v ? v : null } catch { /* fall through */ }
|
||||
}
|
||||
return memory.get(KEY) || null
|
||||
}
|
||||
export async function setApiKey(value) {
|
||||
const v = String(value || '').trim()
|
||||
if (!v) return clearApiKey()
|
||||
const p = await plugin()
|
||||
if (p) {
|
||||
try { await p.set(KEY, v); memory.delete(KEY); return } catch { /* fall through */ }
|
||||
}
|
||||
memory.set(KEY, v)
|
||||
}
|
||||
export async function clearApiKey() {
|
||||
const p = await plugin()
|
||||
if (p) { try { await p.remove(KEY) } catch { /* nothing to clear */ } }
|
||||
memory.delete(KEY)
|
||||
}
|
||||
@@ -0,0 +1,622 @@
|
||||
// The AI Coach, on the client side: everything that decides what a proposal *does* to a plan.
|
||||
//
|
||||
// The server produces proposals; it never writes into your state. Applying one is ordinary
|
||||
// local editing — snapshot, mutate the draft, log — which is what makes it work offline, sync
|
||||
// like every other change, and stay reversible without the server knowing anything about it.
|
||||
//
|
||||
// Every function here is pure over a draft state `s` (call them inside store.update), so the
|
||||
// interesting parts are testable without a browser, a server or an AI account. That matters
|
||||
// more here than elsewhere in the app: this is the code that edits a plan on the strength of
|
||||
// something a language model said, and "it looked right on my phone" is not a standard.
|
||||
//
|
||||
// The screens that call it arrive in PR 4. Nothing in this file needs one to be tested, which
|
||||
// is the point of it being separate from them.
|
||||
|
||||
import { EXIDX } from './exercises.js'
|
||||
import { modeOf, isBw, isPerSide, cleanupSg } from './history.js'
|
||||
import { uid, todayISO, DAYN } from './format.js'
|
||||
import { mergePlan } from './plan-share.js'
|
||||
import { POLICIES } from './progression.js'
|
||||
import { t } from './i18n.js'
|
||||
|
||||
// Bumping this re-prompts everyone: it means what we share, or who we share it with, changed.
|
||||
export const CONSENT_VERSION = 1
|
||||
|
||||
// Bounds. The whole state has to stay inside the server's 5 MB body limit, and a Coach log
|
||||
// that grows forever is exactly the kind of thing that eats it invisibly. Worst case here is
|
||||
// ~75 KB; the namespace guard is the backstop for the case nobody predicted.
|
||||
export const SNAPSHOT_MAX = 3
|
||||
export const LOG_MAX = 50
|
||||
export const CHAT_MAX = 40
|
||||
export const TIMINGS_MAX = 5
|
||||
const NAMESPACE_MAX = 256 * 1024
|
||||
|
||||
export const emptyCoach = () => ({
|
||||
consent: null, profile: null, cadence: 'off', lastReview: null, log: [], snapshots: [],
|
||||
// The conversation as the user saw it (views/CoachChat.jsx): their messages, and what the
|
||||
// Coach did with them. Short, synced, and trimmed with the log — the proposal itself lives
|
||||
// server-side (or in the phone's device file) until it is applied or dismissed.
|
||||
chat: [],
|
||||
// How long the last few jobs took, so the typing bubble can say "usually about 2 minutes".
|
||||
timings: []
|
||||
})
|
||||
const coachOf = s => (s.coach = s.coach || emptyCoach())
|
||||
|
||||
/* ============================ gating ============================ */
|
||||
|
||||
// One predicate, one place. Every Coach entry point in the UI is behind it, which is what
|
||||
// makes "an instance with no provider is byte-identical to before" a claim worth testing.
|
||||
//
|
||||
// The demo build is the one exception, and it is deliberate: it has no backend and no
|
||||
// account, but it does have a canned provider, and hiding the app's most interesting feature
|
||||
// from the page people are sent to look at it on would be a strange choice.
|
||||
//
|
||||
// The mobile build has two ways in, both chosen in Settings (views/CoachSetup.jsx): a phone
|
||||
// paired to a self-hosted server is an ordinary signed-in profile and takes the web rule; a
|
||||
// phone that brought its own API key runs the Coach itself (lib/coach-local.js). Nothing
|
||||
// chosen means nothing shown — the same "invisible unless configured" promise the web keeps.
|
||||
export const coachAvailable = (config, user, { demo, mobile, coachMode } = {}) =>
|
||||
mobile ? (coachMode === 'byok' || !!(config?.coach?.enabled && user))
|
||||
: demo ? true : !!(config?.coach?.enabled && user)
|
||||
|
||||
// What each data category means, in the user's words. Rendered from the same list the payload
|
||||
// builder uses (api/coach/core/categories.js), so the screen cannot promise less than leaves.
|
||||
export const CATEGORY_TEXT = {
|
||||
plan: ['Your plan', 'Routines, exercises, sets and reps, your weekly schedule and progression settings.'],
|
||||
training: ['Your logged training', 'Sets you logged in the review window — weights, reps, times, effort ratings and how long sessions took.'],
|
||||
bodyweight: ['Body weight', 'Weigh-ins from the same window, and your goal weight if you set one.'],
|
||||
profile: ['What you tell the Coach', 'Your intake answers, including any limitations or injuries you describe.'],
|
||||
prefs: ['A few preferences', 'Your unit, your language and which effort scale you log.']
|
||||
}
|
||||
export const hasConsent = S => !!S?.coach?.consent?.agreedAt && S.coach.consent.version === CONSENT_VERSION
|
||||
|
||||
/* ============================ plan fingerprint ============================ */
|
||||
|
||||
/**
|
||||
* Mirror of `canonicalPlan` in api/coach/payload.js — field for field, including the rule
|
||||
* that every absent value is written out as a zero so "no weight" and "0 kg" cannot hash
|
||||
* apart, and that `bodyweight`/`side` are *resolved* against the catalogue rather than copied,
|
||||
* so a plan that says nothing and an exercise the dataset already calls bodyweight hash the
|
||||
* same. If you change one, change both; coach.test.js checks them against shared fixtures.
|
||||
*/
|
||||
export function canonicalPlan(S) {
|
||||
return {
|
||||
routines: (S.routines || []).map(r => ({
|
||||
id: r.id, name: r.name || '', prog: r.prog || '',
|
||||
ex: (r.ex || []).map(e => {
|
||||
const mode = modeOf(e)
|
||||
return {
|
||||
id: e.id, mode, sets: e.sets || 0,
|
||||
reps: mode === 'reps' ? (e.reps || 0) : 0,
|
||||
sec: mode === 'time' ? (e.sec || 0) : 0,
|
||||
min: mode === 'cardio' ? (e.min || 0) : 0,
|
||||
speed: mode === 'cardio' ? (e.speed || 0) : 0,
|
||||
weight: mode === 'cardio' ? 0 : (e.weight || 0),
|
||||
prog: e.prog || '', inc: e.inc || 0, repsMin: e.repsMin || 0, repsMax: e.repsMax || 0,
|
||||
bodyweight: isBw(e), side: isPerSide(e),
|
||||
sg: e.sg || ''
|
||||
}
|
||||
})
|
||||
})),
|
||||
week: Object.fromEntries([1, 2, 3, 4, 5, 6, 0].filter(d => S.week?.[d]).map(d => [d, S.week[d]]))
|
||||
}
|
||||
}
|
||||
|
||||
/** FNV-1a-ish 64-bit fingerprint. Mirror of hashPlan in api/coach/jobs.js. */
|
||||
export function hashPlan(plan) {
|
||||
const canon = JSON.stringify({
|
||||
routines: (plan?.routines || []).map(r => [r.id, r.name, r.prog, (r.ex || []).map(e =>
|
||||
[e.id, e.mode, e.sets, e.reps, e.sec, e.min, e.speed, e.weight, e.prog, e.inc,
|
||||
e.repsMin, e.repsMax, e.bodyweight, e.side, e.sg].join(':')
|
||||
)]),
|
||||
week: Object.keys(plan?.week || {}).sort().map(k => k + '=' + plan.week[k])
|
||||
})
|
||||
let h1 = 0x811c9dc5, h2 = 0x01000193
|
||||
for (let i = 0; i < canon.length; i++) {
|
||||
const c = canon.charCodeAt(i)
|
||||
h1 = Math.imul(h1 ^ c, 0x01000193) >>> 0
|
||||
h2 = Math.imul(h2 ^ ((c << 3) | i & 7), 0x85ebca6b) >>> 0
|
||||
}
|
||||
return h1.toString(16).padStart(8, '0') + h2.toString(16).padStart(8, '0')
|
||||
}
|
||||
export const planHash = S => hashPlan(canonicalPlan(S))
|
||||
|
||||
/* ============================ staleness ============================ */
|
||||
|
||||
const findRoutine = (S, id) => (S.routines || []).find(r => r.id === id) || null
|
||||
const findEx = (routine, id) => (routine?.ex || []).find(e => e.id === id) || null
|
||||
|
||||
/** The plan's current value for whatever a change is about — what `before` is checked against. */
|
||||
export function currentValue(S, change) {
|
||||
const r = findRoutine(S, change.target?.routineId)
|
||||
const e = change.target?.exId ? findEx(r, change.target.exId) : null
|
||||
switch (change.type) {
|
||||
case 'sets': return e?.sets ?? null
|
||||
case 'reps': return e?.reps ?? null
|
||||
case 'repsMin': return e?.repsMin ?? null
|
||||
case 'repsMax': return e?.repsMax ?? null
|
||||
case 'sec': return e?.sec ?? null
|
||||
case 'inc': return e?.inc ?? null
|
||||
case 'exercise-prog': return e?.prog ?? null
|
||||
case 'routine-prog': return r?.prog ?? null
|
||||
case 'rename-routine': return r?.name ?? null
|
||||
case 'week': return S.week?.[change.target?.weekday] ?? null
|
||||
default: return undefined // structural changes have no single scalar to compare
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark what can no longer be applied. Two independent checks, because they fail differently:
|
||||
* the whole proposal is stale when the plan has moved since it was computed, and an individual
|
||||
* change is stale when the thing it names is gone or has already been changed by hand.
|
||||
*
|
||||
* A stale change is disabled, never silently skipped — someone who edited their plan on
|
||||
* another device should be told why the suggestion is greyed out.
|
||||
*/
|
||||
export function markStale(proposal, S) {
|
||||
if (!proposal) return proposal
|
||||
const planMoved = !!proposal.planHash && proposal.planHash !== planHash(S)
|
||||
const changes = (proposal.changes || []).map(c => {
|
||||
const r = c.target?.routineId ? findRoutine(S, c.target.routineId) : null
|
||||
let stale = false
|
||||
if (c.type !== 'add-routine' && c.type !== 'week' && !r) stale = true
|
||||
else if (c.target?.exId && !findEx(r, c.target.exId)) stale = true
|
||||
else {
|
||||
const cur = currentValue(S, c)
|
||||
// `before` is what the Coach saw. If the live plan disagrees, someone has already
|
||||
// changed it — applying would silently overwrite their edit with a stale premise.
|
||||
if (cur !== undefined && c.before != null && cur !== c.before && cur !== null) stale = true
|
||||
}
|
||||
return { ...c, status: stale ? 'stale' : (c.status === 'stale' ? 'proposed' : c.status || 'proposed') }
|
||||
})
|
||||
return { ...proposal, planMoved, changes }
|
||||
}
|
||||
export const applicable = proposal => (proposal?.changes || []).filter(c => c.status !== 'stale')
|
||||
|
||||
/* ============================ validation ============================ */
|
||||
|
||||
/** Client-side mirror of the server's gate — the plan must survive a bad day at either end. */
|
||||
export function validateProposal(p) {
|
||||
if (!p || typeof p !== 'object') throw new Error(t('That proposal can’t be read.'))
|
||||
if (p.bundle) {
|
||||
if (!Array.isArray(p.bundle.routines) || !p.bundle.routines.length) throw new Error(t('That proposal can’t be read.'))
|
||||
// The server rejects a routine with no exercises; so must this, or an empty one is appended,
|
||||
// gets scheduled, and "start today's session" opens a workout with nothing in it.
|
||||
for (const r of p.bundle.routines) {
|
||||
if (!Array.isArray(r.ex) || !r.ex.length) throw new Error(t('That proposal can’t be read.'))
|
||||
}
|
||||
return true
|
||||
}
|
||||
if (!Array.isArray(p.changes)) throw new Error(t('That proposal can’t be read.'))
|
||||
for (const c of p.changes) {
|
||||
if (!CHANGE_APPLY[c.type]) throw new Error(t('That proposal can’t be read.'))
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/* ============================ snapshots & revert ============================ */
|
||||
|
||||
const clone = o => JSON.parse(JSON.stringify(o))
|
||||
|
||||
/**
|
||||
* Remember the `dayPlan` entries an apply step deleted, on the snapshot that will undo it.
|
||||
*
|
||||
* A patch, not a clone: `dayPlan` holds every date the user ever rescheduled, and three copies
|
||||
* of it in the snapshot ring would crowd real snapshots out of the 256 KB namespace budget that
|
||||
* `trim()` enforces. The first value recorded for a date wins — that is the pre-apply one.
|
||||
*/
|
||||
function recordDayPlanDrops(s, dropped) {
|
||||
if (!Object.keys(dropped).length) return
|
||||
const snaps = coachOf(s).snapshots || []
|
||||
const snap = snaps[snaps.length - 1]
|
||||
if (!snap) return
|
||||
snap.dayPlanRestore = { ...dropped, ...(snap.dayPlanRestore || {}) }
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop per-date reschedules from `iso` onwards.
|
||||
*
|
||||
* A created plan replaces the whole week, so overrides made against the old one are no longer
|
||||
* about anything: `'rest'` would hide a session the new plan schedules, and a routine id wins
|
||||
* over the new week on that day. Past dates stay — those are history, not intent.
|
||||
*/
|
||||
function sweepDayPlan(s, fromIso) {
|
||||
const dropped = {}
|
||||
Object.keys(s.dayPlan || {}).forEach(iso => {
|
||||
if (iso >= fromIso) { dropped[iso] = s.dayPlan[iso]; delete s.dayPlan[iso] }
|
||||
})
|
||||
recordDayPlanDrops(s, dropped)
|
||||
}
|
||||
|
||||
/** Snapshot `{routines, week}` before touching either. The unit of revert (FR-30/31). */
|
||||
export function pushSnapshot(s, proposalId, label) {
|
||||
const c = coachOf(s)
|
||||
c.snapshots = [...(c.snapshots || []), {
|
||||
at: Date.now(), proposalId: proposalId || null, label: label || '',
|
||||
routines: clone(s.routines || []), week: clone(s.week || {})
|
||||
}].slice(-SNAPSHOT_MAX)
|
||||
trim(s)
|
||||
}
|
||||
|
||||
/**
|
||||
* Put the plan back the way it was before the last applied change-set.
|
||||
*
|
||||
* Workouts are untouched, and that is not an oversight: the log is what happened. Reverting a
|
||||
* plan re-derives every future target from that same history, which is exactly what the
|
||||
* progression engine does anyway.
|
||||
*/
|
||||
export function revertLast(s) {
|
||||
const c = coachOf(s)
|
||||
const snap = (c.snapshots || []).pop()
|
||||
if (!snap) return false
|
||||
s.routines = clone(snap.routines)
|
||||
s.week = clone(snap.week)
|
||||
// Snapshots taken before this field existed have nothing to put back.
|
||||
if (snap.dayPlanRestore) Object.assign(s.dayPlan, snap.dayPlanRestore)
|
||||
appendLog(s, { kind: 'revert', at: Date.now(), proposalId: snap.proposalId, summary: t('Reverted the last Coach changes.') })
|
||||
return true
|
||||
}
|
||||
export const canRevert = S => !!(S?.coach?.snapshots || []).length
|
||||
|
||||
/* ============================ the log ============================ */
|
||||
|
||||
export function appendLog(s, entry) {
|
||||
const c = coachOf(s)
|
||||
const e = { id: entry.id || uid(), ...entry }
|
||||
c.log = [...(c.log || []), e].slice(-LOG_MAX)
|
||||
trim(s)
|
||||
return e.id
|
||||
}
|
||||
export const logEntry = (S, id) => (S?.coach?.log || []).find(e => e.id === id) || null
|
||||
|
||||
/**
|
||||
* What a created plan looked like, small enough to keep: names, days and prescriptions, no
|
||||
* rationale text. The full bundle was merged into the plan already; this is what the chat
|
||||
* shows back when someone opens an old proposal months later.
|
||||
*/
|
||||
export function lightBundle(b) {
|
||||
if (!b) return null
|
||||
return {
|
||||
name: b.name || '', summary: b.summary || '', week: { ...(b.week || {}) },
|
||||
routines: (b.routines || []).map(r => ({
|
||||
id: r.id, name: r.name, emoji: r.emoji || '', why: r.why || '',
|
||||
ex: (r.ex || []).map(e => ({
|
||||
id: e.id, sets: e.sets, mode: e.mode || 'reps',
|
||||
...(e.reps != null ? { reps: e.reps } : {}), ...(e.sec != null ? { sec: e.sec } : {}),
|
||||
...(e.min != null ? { min: e.min } : {}), ...(e.weight ? { weight: e.weight } : {}),
|
||||
...(e.why ? { why: String(e.why).slice(0, 200) } : {})
|
||||
}))
|
||||
}))
|
||||
}
|
||||
}
|
||||
const decisionOf = (c, status) => ({ id: c.id, type: c.type, target: c.target || null, before: c.before ?? null, after: c.after ?? null, why: c.why, routineName: c.routineName || null, status })
|
||||
|
||||
|
||||
/**
|
||||
* Last line of defence for the 5 MB sync body: if the Coach namespace ever outgrows its
|
||||
* budget, drop the oldest history rather than let a PUT start failing for reasons nobody
|
||||
* would connect to this feature.
|
||||
*/
|
||||
function trim(s) {
|
||||
const c = coachOf(s)
|
||||
let guard = 0
|
||||
while (JSON.stringify(c).length > NAMESPACE_MAX && guard++ < 60) {
|
||||
if ((c.chat || []).length > 8) c.chat.shift()
|
||||
else if ((c.snapshots || []).length > 1) c.snapshots.shift()
|
||||
else if ((c.log || []).length > 1) c.log.shift()
|
||||
else break
|
||||
}
|
||||
}
|
||||
|
||||
/* ============================ the conversation ============================ */
|
||||
|
||||
/**
|
||||
* One line of the chat: `{ id, role: 'user'|'coach', kind, text?, at, ref? }`.
|
||||
* kinds — user: 'intake' (the questionnaire, rendered from the live profile), 'text';
|
||||
* coach: 'text', 'applied', 'dismissed', 'reverted', 'error', 'nochange'.
|
||||
*/
|
||||
export function appendChat(s, entry) {
|
||||
const c = coachOf(s)
|
||||
c.chat = [...(c.chat || []), { id: entry.id || uid(), at: entry.at || Date.now(), ...entry }].slice(-CHAT_MAX)
|
||||
trim(s)
|
||||
}
|
||||
|
||||
/** A job just finished: remember how long it took, for the next typing bubble. */
|
||||
export function recordTiming(s, ms) {
|
||||
if (!(ms > 0)) return
|
||||
const c = coachOf(s)
|
||||
c.timings = [...(c.timings || []), Math.round(ms)].slice(-TIMINGS_MAX)
|
||||
}
|
||||
/**
|
||||
* What to promise in the typing bubble. Median of the observed runs, but never slower than
|
||||
* the most recent one: after a speed-up (a faster model, a warmed cache) the median drags
|
||||
* three old 8-minute runs along, and telling someone "about 8 min" for a one-minute job is
|
||||
* worse than being briefly optimistic. A slow outlier still cannot scare anyone — the median
|
||||
* wins in that direction.
|
||||
*/
|
||||
export function estimateMs(S) {
|
||||
const raw = (S?.coach?.timings || []).filter(n => n > 0)
|
||||
if (!raw.length) return null
|
||||
const sorted = [...raw].sort((a, b) => a - b)
|
||||
return Math.min(sorted[Math.floor(sorted.length / 2)], raw[raw.length - 1])
|
||||
}
|
||||
|
||||
/** The questionnaire, as the lines the chat shows back to the user. */
|
||||
export function profileLines(p) {
|
||||
if (!p) return []
|
||||
const goal = { strength: 'Get stronger', muscle: 'Build muscle', general: 'General fitness', fatloss: 'Lose fat', endurance: 'Endurance' }[p.goal]
|
||||
const exp = { new: 'New to lifting', returning: 'Coming back after a break', regular: 'Training regularly' }[p.experience]
|
||||
const lines = []
|
||||
if (goal) lines.push(t(goal))
|
||||
if (exp) lines.push(t(exp))
|
||||
if (p.daysPerWeek) lines.push(p.daysPerWeek === 1 ? t('1 day a week') : t('{0} days a week', p.daysPerWeek))
|
||||
if (p.sessionMin) lines.push(t('{0} min per session', p.sessionMin))
|
||||
if (p.equipment?.length) lines.push(p.equipment.join(', '))
|
||||
if (p.limitations) lines.push(t('Limits: {0}', p.limitations))
|
||||
if (p.likes) lines.push(t('Likes: {0}', p.likes))
|
||||
if (p.dislikes) lines.push(t('Avoid: {0}', p.dislikes))
|
||||
if (p.notes) lines.push(p.notes)
|
||||
return lines
|
||||
}
|
||||
|
||||
/* ============================ applying a created plan ============================ */
|
||||
|
||||
/**
|
||||
* Accepting a created plan is exactly importing a plan file (FR-18): routines arrive as new
|
||||
* ones with fresh ids, existing routines and history are never touched, and the week schedule
|
||||
* only moves if you asked it to.
|
||||
*/
|
||||
export function applyCreatedPlan(s, proposal, { schedule } = {}) {
|
||||
validateProposal(proposal)
|
||||
pushSnapshot(s, proposal.id, t('Before the Coach’s plan'))
|
||||
const bundle = proposal.bundle
|
||||
// The Coach's `why` texts are for the review screen; they have no place in the routine data.
|
||||
const stripped = {
|
||||
...bundle,
|
||||
routines: bundle.routines.map(r => ({ ...r, why: undefined, ex: r.ex.map(e => ({ ...e, why: undefined, name: undefined })) }))
|
||||
}
|
||||
const res = mergePlan(s, stripped, { schedule })
|
||||
// Only when the week actually moved — with the switch off the old schedule still stands, and
|
||||
// so do the reschedules made against it.
|
||||
if (schedule) sweepDayPlan(s, todayISO())
|
||||
res.logId = appendLog(s, {
|
||||
kind: 'create', at: Date.now(), proposalId: proposal.id,
|
||||
summary: proposal.summary || '', routines: res.routines, iteration: proposal.iteration || 1,
|
||||
bundle: lightBundle(bundle), scheduled: !!schedule
|
||||
})
|
||||
return res
|
||||
}
|
||||
|
||||
/* ============================ applying a change-set ============================ */
|
||||
|
||||
// One implementation per allowed type. The object is the closed list on this side of the
|
||||
// wire: a type with no entry here cannot be applied, whatever the server let through.
|
||||
const CHANGE_APPLY = {
|
||||
'add-exercise': (s, c) => {
|
||||
const r = need(findRoutine(s, c.target.routineId))
|
||||
const a = c.after || {}
|
||||
const e = { id: a.id, sets: a.sets || 3, mode: a.mode || 'reps' }
|
||||
if (e.mode === 'cardio') { e.min = a.min || 20; e.speed = a.speed || 8 }
|
||||
else if (e.mode === 'time') e.sec = a.sec || 45
|
||||
else e.reps = a.reps || 10
|
||||
if (a.weight > 0) e.weight = a.weight
|
||||
if (POLICIES.includes(a.prog)) e.prog = a.prog
|
||||
if (Number.isInteger(a.repsMin)) e.repsMin = a.repsMin
|
||||
if (Number.isInteger(a.repsMax)) e.repsMax = a.repsMax
|
||||
// Only when the Coach disagreed with the catalogue: an absent flag has always meant
|
||||
// "whatever the exercise says", and writing one out would freeze today's dataset into
|
||||
// the plan.
|
||||
if (a.bodyweight != null) e.bodyweight = !!a.bodyweight
|
||||
if (a.side) e.side = true
|
||||
const at = Number.isInteger(a.position) ? Math.min(a.position, r.ex.length) : r.ex.length
|
||||
r.ex.splice(at, 0, e)
|
||||
cleanupSg(r.ex)
|
||||
},
|
||||
'remove-exercise': (s, c) => {
|
||||
const r = need(findRoutine(s, c.target.routineId))
|
||||
r.ex = r.ex.filter(e => e.id !== c.target.exId)
|
||||
cleanupSg(r.ex)
|
||||
},
|
||||
'swap-exercise': (s, c) => {
|
||||
const r = need(findRoutine(s, c.target.routineId))
|
||||
const i = r.ex.findIndex(e => e.id === c.target.exId)
|
||||
if (i < 0) throw new Error('missing exercise')
|
||||
const old = r.ex[i], a = c.after || {}
|
||||
// Keep the old prescription unless the Coach deliberately changed it: a swap is about the
|
||||
// movement, and silently resetting sets and reps would be a second change nobody approved.
|
||||
//
|
||||
// The two v1.2.4 flags are the exception, and they have to be: they describe the *movement*,
|
||||
// not the prescription. Carrying `side: true` from a lunge onto a leg press would make the
|
||||
// app halve a rep count that was never per-side, so an explicit flag is dropped and the new
|
||||
// exercise goes back to whatever the catalogue says about it.
|
||||
const { bodyweight, side, ...keep } = old
|
||||
r.ex[i] = { ...keep, id: a.id, ...(a.sets ? { sets: a.sets } : {}), ...(a.reps ? { reps: a.reps } : {}), ...(a.weight > 0 ? { weight: a.weight } : {}) }
|
||||
},
|
||||
sets: (s, c) => { need(findExIn(s, c)).sets = c.after },
|
||||
reps: (s, c) => { need(findExIn(s, c)).reps = c.after },
|
||||
repsMin: (s, c) => { need(findExIn(s, c)).repsMin = c.after },
|
||||
repsMax: (s, c) => { need(findExIn(s, c)).repsMax = c.after },
|
||||
sec: (s, c) => { need(findExIn(s, c)).sec = c.after },
|
||||
cardio: (s, c) => {
|
||||
const e = need(findExIn(s, c))
|
||||
if (c.after?.min != null) e.min = c.after.min
|
||||
if (c.after?.speed != null) e.speed = c.after.speed
|
||||
},
|
||||
inc: (s, c) => { need(findExIn(s, c)).inc = c.after },
|
||||
'exercise-prog': (s, c) => { need(findExIn(s, c)).prog = c.after },
|
||||
'routine-prog': (s, c) => { need(findRoutine(s, c.target.routineId)).prog = c.after },
|
||||
reorder: (s, c) => {
|
||||
const r = need(findRoutine(s, c.target.routineId))
|
||||
const by = new Map(r.ex.map(e => [e.id, e]))
|
||||
const next = c.after.map(id => by.get(id)).filter(Boolean)
|
||||
// Distinct exercises, not just the right count: an order naming one id twice maps to the
|
||||
// same object twice and still counts right, which drops an exercise and leaves the
|
||||
// survivor aliased into two slots that then edit each other.
|
||||
if (next.length !== r.ex.length || new Set(next).size !== r.ex.length) throw new Error('incomplete reorder')
|
||||
r.ex = next
|
||||
cleanupSg(r.ex)
|
||||
},
|
||||
superset: (s, c) => {
|
||||
const r = need(findRoutine(s, c.target.routineId))
|
||||
const i = r.ex.findIndex(e => e.id === c.target.exId)
|
||||
if (i < 0) throw new Error('missing exercise')
|
||||
if (!c.after?.link) { delete r.ex[i].sg; cleanupSg(r.ex); return }
|
||||
// Splicing the partner out from under the anchor when they are the same exercise leaves
|
||||
// nothing to tag; refuse rather than reorder the routine on the way to a TypeError.
|
||||
if (c.after.with === c.target.exId) throw new Error('superset with itself')
|
||||
const j = r.ex.findIndex(e => e.id === c.after.with)
|
||||
if (j < 0) throw new Error('missing partner')
|
||||
// Supersets are a property of adjacency in this app; move the partner next to it first.
|
||||
const [partner] = r.ex.splice(j, 1)
|
||||
const at = r.ex.findIndex(e => e.id === c.target.exId)
|
||||
r.ex.splice(at + 1, 0, partner)
|
||||
const tag = uid().slice(0, 6)
|
||||
r.ex[at].sg = tag
|
||||
r.ex[at + 1].sg = tag
|
||||
},
|
||||
'add-routine': (s, c) => {
|
||||
const a = c.after
|
||||
s.routines.push({
|
||||
id: uid(), name: a.name, emoji: a.emoji || '🏋️',
|
||||
...(POLICIES.includes(a.prog) ? { prog: a.prog } : {}),
|
||||
ex: a.ex.map(e => ({
|
||||
id: e.id, sets: e.sets || 3, mode: e.mode || 'reps',
|
||||
...(e.mode === 'time' ? { sec: e.sec || 45 } : { reps: e.reps || 10 }),
|
||||
...(Number.isInteger(e.repsMax) ? { repsMax: e.repsMax } : {}),
|
||||
...(e.bodyweight != null ? { bodyweight: !!e.bodyweight } : {}),
|
||||
...(e.side ? { side: true } : {})
|
||||
}))
|
||||
})
|
||||
},
|
||||
'remove-routine': (s, c) => {
|
||||
const id = c.target.routineId
|
||||
s.routines = s.routines.filter(r => r.id !== id)
|
||||
// A week pointing at a routine that no longer exists reads as a rest day anyway; clearing
|
||||
// it keeps the plan honest rather than merely harmless.
|
||||
Object.keys(s.week || {}).forEach(d => { if (s.week[d] === id) delete s.week[d] })
|
||||
// RoutineEdit does the same on a hand-deleted routine. A pointer left behind here is not
|
||||
// merely inert: the day still counts as overridden, so it wears a "rescheduled" badge for good.
|
||||
const dropped = {}
|
||||
Object.keys(s.dayPlan || {}).forEach(iso => {
|
||||
if (s.dayPlan[iso] === id) { dropped[iso] = id; delete s.dayPlan[iso] }
|
||||
})
|
||||
recordDayPlanDrops(s, dropped)
|
||||
},
|
||||
'rename-routine': (s, c) => { need(findRoutine(s, c.target.routineId)).name = c.after },
|
||||
week: (s, c) => {
|
||||
const d = c.target.weekday
|
||||
if (c.after == null || c.after === 'rest') delete s.week[d]
|
||||
else s.week[d] = c.after
|
||||
}
|
||||
}
|
||||
export const CHANGE_TYPES = Object.keys(CHANGE_APPLY)
|
||||
|
||||
function findExIn(s, c) { return findEx(findRoutine(s, c.target.routineId), c.target.exId) }
|
||||
function need(x) { if (!x) throw new Error('missing target'); return x }
|
||||
|
||||
/**
|
||||
* Apply the accepted subset, atomically (FR-30).
|
||||
*
|
||||
* Atomic comes free from how the store works: `update()` hands us a throwaway clone and only
|
||||
* keeps it if we return normally. Throwing part-way through therefore discards every change
|
||||
* this function already made, which is precisely the transaction we want — no half-applied
|
||||
* change-set, ever.
|
||||
*/
|
||||
export function applyChangeSet(s, proposal, acceptedIds) {
|
||||
validateProposal(proposal)
|
||||
const accepted = new Set(acceptedIds || [])
|
||||
const changes = (proposal.changes || []).filter(c => accepted.has(c.id) && c.status !== 'stale')
|
||||
if (!changes.length) return { applied: 0 }
|
||||
|
||||
pushSnapshot(s, proposal.id, t('Before the Coach’s changes'))
|
||||
const applied = []
|
||||
for (const c of changes) {
|
||||
CHANGE_APPLY[c.type](s, c)
|
||||
applied.push(decisionOf(c, 'accepted'))
|
||||
}
|
||||
// Turned-down changes keep their before/after too: the chat shows the whole proposal back
|
||||
// later, and "you declined something about sets" is not a memory anyone can use.
|
||||
const rejected = (proposal.changes || [])
|
||||
.filter(c => !accepted.has(c.id))
|
||||
.map(c => decisionOf(c, c.status === 'stale' ? 'stale' : 'rejected'))
|
||||
|
||||
const logId = appendLog(s, {
|
||||
kind: 'review', at: Date.now(), proposalId: proposal.id,
|
||||
summary: proposal.summary || '', evidence: proposal.evidence || null,
|
||||
notes: proposal.notes || [], decisions: [...applied, ...rejected]
|
||||
})
|
||||
coachOf(s).lastReview = { at: Date.now() }
|
||||
return { applied: applied.length, rejected: rejected.length, logId }
|
||||
}
|
||||
|
||||
/** Turned down whole, or expired: recorded so a later review knows not to re-propose it. */
|
||||
export function recordDismissal(s, proposal) {
|
||||
const logId = appendLog(s, {
|
||||
kind: proposal.kind === 'create' ? 'create' : 'review', at: Date.now(), proposalId: proposal.id,
|
||||
summary: proposal.summary || '', dismissed: true,
|
||||
evidence: proposal.evidence || null, notes: proposal.notes || [],
|
||||
...(proposal.bundle ? { bundle: lightBundle(proposal.bundle), iteration: proposal.iteration || 1 } : {}),
|
||||
decisions: (proposal.changes || []).map(c => decisionOf(c, 'rejected'))
|
||||
})
|
||||
if (proposal.kind !== 'create') coachOf(s).lastReview = { at: Date.now() }
|
||||
return logId
|
||||
}
|
||||
|
||||
/** A debrief has no decision to make: it is read, kept, and shown again on request. */
|
||||
export function recordDebrief(s, proposal) {
|
||||
return appendLog(s, {
|
||||
kind: 'debrief', at: Date.now(), proposalId: proposal.id,
|
||||
workout: proposal.workout || null,
|
||||
summary: proposal.summary || '', score: proposal.score ?? null,
|
||||
highlights: proposal.highlights || [], watch: proposal.watch || [], nextTime: proposal.nextTime || []
|
||||
})
|
||||
}
|
||||
|
||||
/* ============================ display helpers ============================ */
|
||||
|
||||
export const exName = id => EXIDX[id]?.n || t('Unknown exercise')
|
||||
// Catalogue names are lower-case; a title reads better with each word capitalised, and doing it
|
||||
// here rather than with CSS keeps a German sentence around the name from being Title Cased too.
|
||||
const cap = s => String(s || '').replace(/(^|\s)(\p{L})/gu, (m, sp, ch) => sp + ch.toUpperCase())
|
||||
export const exTitle = id => cap(exName(id))
|
||||
|
||||
/** Human label for a change, used on the review screen and in the log. */
|
||||
export function changeTitle(c, S) {
|
||||
const ex = c.target?.exId ? exTitle(c.target.exId) : null
|
||||
switch (c.type) {
|
||||
case 'add-exercise': return t('Add {0}', exTitle(c.after?.id))
|
||||
case 'remove-exercise': return t('Drop {0}', ex)
|
||||
case 'swap-exercise': return t('Swap {0} for {1}', ex, exTitle(c.after?.id))
|
||||
case 'sets': return t('{0}: sets', ex)
|
||||
case 'reps': return t('{0}: reps', ex)
|
||||
case 'repsMin': return t('{0}: rep-range floor', ex)
|
||||
case 'repsMax': return t('{0}: rep-range ceiling', ex)
|
||||
case 'sec': return t('{0}: hold time', ex)
|
||||
case 'cardio': return t('{0}: duration & pace', ex)
|
||||
case 'inc': return t('{0}: load step', ex)
|
||||
case 'exercise-prog': return t('{0}: progression', ex)
|
||||
case 'routine-prog': return t('Routine progression')
|
||||
case 'reorder': return t('Reorder exercises')
|
||||
case 'superset': return c.after?.link ? t('Superset {0} with {1}', ex, exTitle(c.after.with)) : t('Unlink superset on {0}', ex)
|
||||
case 'add-routine': return t('Add routine “{0}”', c.after?.name)
|
||||
case 'remove-routine': return t('Remove a routine')
|
||||
case 'rename-routine': return t('Rename routine to “{0}”', c.after)
|
||||
case 'week': return Number.isInteger(c.target?.weekday) ? t('{0}: what’s planned', t(DAYN[c.target.weekday])) : t('Change what’s planned on one day')
|
||||
default: return c.type
|
||||
}
|
||||
}
|
||||
|
||||
/** Short before/after strings for the diff column. */
|
||||
export function changeValues(c, S) {
|
||||
const routineName = id => (S?.routines || []).find(r => r.id === id)?.name || id
|
||||
const fmt = v => {
|
||||
if (v == null) return c.type === 'week' ? t('Rest') : '—'
|
||||
if (typeof v === 'object') return v.id ? exTitle(v.id) : v.name || JSON.stringify(v)
|
||||
if (Array.isArray(v)) return v.length + ''
|
||||
if (c.type === 'week') return v === 'rest' ? t('Rest') : routineName(v)
|
||||
return String(v)
|
||||
}
|
||||
if (['add-exercise', 'add-routine', 'reorder'].includes(c.type)) return null
|
||||
if (['remove-exercise', 'remove-routine'].includes(c.type)) return null
|
||||
return { before: fmt(c.before), after: fmt(c.after) }
|
||||
}
|
||||
@@ -0,0 +1,610 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
canonicalPlan, planHash, hashPlan, markStale, applicable, currentValue,
|
||||
pushSnapshot, revertLast, canRevert, appendLog, applyChangeSet, applyCreatedPlan,
|
||||
recordDismissal, validateProposal, coachAvailable, hasConsent,
|
||||
recordDebrief, logEntry, lightBundle,
|
||||
CHANGE_TYPES, SNAPSHOT_MAX, LOG_MAX, CONSENT_VERSION
|
||||
} from './coach.js'
|
||||
import { registerCustom } from './exercises.js'
|
||||
|
||||
// The two runtimes share no build step, so the client's copy of the fingerprint logic is
|
||||
// checked against the server's actual source rather than against a transcribed expectation.
|
||||
import * as serverPayload from '../../../api/coach/core/payload.js'
|
||||
import { hashPlan as serverHashPlan } from '../../../api/coach/core/plan-hash.js'
|
||||
|
||||
const state = (over = {}) => ({
|
||||
unit: 'kg', lang: 'en', customEx: [], workouts: [], bodyweight: [], exWeights: {}, dayPlan: {},
|
||||
routines: [{
|
||||
id: 'r1', name: 'Full body A', emoji: '💪', prog: 'linear',
|
||||
ex: [
|
||||
{ id: '0001', sets: 3, reps: 10, mode: 'reps', weight: 20, prog: 'linear' },
|
||||
{ id: '0007', sets: 3, sec: 45, mode: 'time' },
|
||||
{ id: '0009', sets: 3, reps: 12, mode: 'reps' }
|
||||
]
|
||||
}, { id: 'r2', name: 'Full body B', ex: [{ id: '0002', sets: 4, reps: 6, mode: 'reps' }] }],
|
||||
week: { 1: 'r1', 3: 'r2', 5: 'r1' },
|
||||
coach: { consent: { agreedAt: '2026-07-01T00:00:00Z', version: CONSENT_VERSION }, log: [], snapshots: [], cadence: 'off' },
|
||||
...over
|
||||
})
|
||||
|
||||
const change = over => ({ id: 'c1', type: 'sets', target: { routineId: 'r1', exId: '0001' }, before: 3, after: 4, why: 'stalled twice', ...over })
|
||||
const proposal = (changes, over = {}) => ({ id: 'p1', kind: 'review', summary: 's', changes, ...over })
|
||||
/** Apply against a throwaway draft, the way the store does. */
|
||||
const apply = (S, p, ids) => { const s = JSON.parse(JSON.stringify(S)); applyChangeSet(s, p, ids); return s }
|
||||
|
||||
describe('gating', () => {
|
||||
it('shows nothing unless the instance offers it and someone is signed in', () => {
|
||||
expect(coachAvailable({ coach: { enabled: true } }, { id: 'u' })).toBe(true)
|
||||
expect(coachAvailable({}, { id: 'u' })).toBe(false)
|
||||
expect(coachAvailable(null, { id: 'u' })).toBe(false)
|
||||
expect(coachAvailable({ coach: { enabled: true } }, null)).toBe(false)
|
||||
})
|
||||
|
||||
it('is off in the mobile build until a mode is chosen in Settings', () => {
|
||||
expect(coachAvailable(null, null, { mobile: true })).toBe(false)
|
||||
expect(coachAvailable(null, null, { mobile: true, coachMode: 'off' })).toBe(false)
|
||||
// Only its own key makes a local-only phone eligible; "server" without a pairing is nothing.
|
||||
expect(coachAvailable(null, null, { mobile: true, coachMode: 'server' })).toBe(false)
|
||||
expect(coachAvailable(null, null, { mobile: true, coachMode: 'byok' })).toBe(true)
|
||||
})
|
||||
|
||||
it('a phone paired to a server takes the web rule — the server must offer the Coach', () => {
|
||||
expect(coachAvailable({ coach: { enabled: true } }, { id: 'u' }, { mobile: true })).toBe(true)
|
||||
expect(coachAvailable({ coach: { enabled: true } }, { id: 'u' }, { mobile: true, coachMode: 'server' })).toBe(true)
|
||||
expect(coachAvailable({}, { id: 'u' }, { mobile: true, coachMode: 'server' })).toBe(false)
|
||||
expect(coachAvailable({ coach: { enabled: true } }, null, { mobile: true, coachMode: 'server' })).toBe(false)
|
||||
})
|
||||
|
||||
it('is on in the demo build, which fakes the provider locally', () => {
|
||||
expect(coachAvailable(null, null, { demo: true })).toBe(true)
|
||||
})
|
||||
|
||||
it('treats an older consent version as no consent', () => {
|
||||
expect(hasConsent(state())).toBe(true)
|
||||
expect(hasConsent(state({ coach: { consent: { agreedAt: 'x', version: 0 } } }))).toBe(false)
|
||||
expect(hasConsent(state({ coach: {} }))).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('plan fingerprint', () => {
|
||||
it('ignores nothing that matters and reacts to nothing that does not', () => {
|
||||
const S = state()
|
||||
expect(planHash(S)).toBe(planHash(state()))
|
||||
// A field the plan does not carry cannot move the hash.
|
||||
expect(planHash(state({ theme: 'light' }))).toBe(planHash(S))
|
||||
// Everything the Coach can change does.
|
||||
const moved = state(); moved.routines[0].ex[0].sets = 4
|
||||
expect(planHash(moved)).not.toBe(planHash(S))
|
||||
const week = state(); week.week[6] = 'r1'
|
||||
expect(planHash(week)).not.toBe(planHash(S))
|
||||
})
|
||||
|
||||
it('cannot tell "no weight" from "0 kg" — both mean unloaded', () => {
|
||||
const a = state(); delete a.routines[0].ex[2].weight
|
||||
const b = state(); b.routines[0].ex[2].weight = 0
|
||||
expect(planHash(a)).toBe(planHash(b))
|
||||
})
|
||||
|
||||
it('moves for the rep ceiling and the two v1.2.4 flags', () => {
|
||||
// These are plan fields a user can edit by hand, so a proposal computed before the edit
|
||||
// has to read as stale afterwards. They were in canonicalPlan and not in the hash.
|
||||
const S = state()
|
||||
for (const [field, value] of Object.entries({ repsMax: 20, bodyweight: false, side: true })) {
|
||||
const edited = state(); edited.routines[0].ex[0][field] = value
|
||||
expect(planHash(edited), field).not.toBe(planHash(S))
|
||||
}
|
||||
})
|
||||
|
||||
it('agrees with the server, field for field', () => {
|
||||
const withFlags = state()
|
||||
withFlags.routines[0].ex[0] = { ...withFlags.routines[0].ex[0], repsMin: 8, repsMax: 20, bodyweight: true }
|
||||
withFlags.routines[1].ex[0] = { ...withFlags.routines[1].ex[0], side: true, reps: 16 }
|
||||
for (const S of [state(), state({ week: {} }), state({ routines: [] }), withFlags]) {
|
||||
expect(canonicalPlan(S)).toEqual(serverPayload.canonicalPlan(S))
|
||||
expect(planHash(S)).toBe(serverHashPlan(serverPayload.canonicalPlan(S)))
|
||||
expect(hashPlan(canonicalPlan(S))).toBe(serverHashPlan(serverPayload.canonicalPlan(S)))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('staleness', () => {
|
||||
it('flags the whole proposal when the plan moved underneath it', () => {
|
||||
const S = state()
|
||||
const p = { ...proposal([change()]), planHash: planHash(S) }
|
||||
expect(markStale(p, S).planMoved).toBe(false)
|
||||
const edited = state(); edited.routines[0].ex[0].sets = 5
|
||||
expect(markStale(p, edited).planMoved).toBe(true)
|
||||
})
|
||||
|
||||
it('flags a change whose target is gone', () => {
|
||||
const S = state(); S.routines[0].ex = S.routines[0].ex.filter(e => e.id !== '0001')
|
||||
const [c] = markStale(proposal([change()]), S).changes
|
||||
expect(c.status).toBe('stale')
|
||||
})
|
||||
|
||||
it('flags a change someone already made by hand, rather than overwriting them', () => {
|
||||
const S = state(); S.routines[0].ex[0].sets = 5 // Coach saw 3, user has since set 5
|
||||
const [c] = markStale(proposal([change()]), S).changes
|
||||
expect(c.status).toBe('stale')
|
||||
expect(applicable(markStale(proposal([change()]), S))).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('leaves an untouched change applyable', () => {
|
||||
const [c] = markStale(proposal([change()]), state()).changes
|
||||
expect(c.status).toBe('proposed')
|
||||
})
|
||||
|
||||
it('reads the current value for every scalar change type', () => {
|
||||
const S = state()
|
||||
S.routines[0].ex[0].repsMax = 20
|
||||
expect(currentValue(S, change({ type: 'sets' }))).toBe(3)
|
||||
expect(currentValue(S, change({ type: 'reps' }))).toBe(10)
|
||||
expect(currentValue(S, change({ type: 'repsMax' }))).toBe(20)
|
||||
expect(currentValue(S, change({ type: 'exercise-prog' }))).toBe('linear')
|
||||
expect(currentValue(S, change({ type: 'routine-prog' }))).toBe('linear')
|
||||
expect(currentValue(S, change({ type: 'week', target: { weekday: 1 } }))).toBe('r1')
|
||||
})
|
||||
})
|
||||
|
||||
describe('applying changes', () => {
|
||||
it('has an implementation for every type the server can send', async () => {
|
||||
const { CHANGE_TYPES: serverTypes } = await import('../../../api/coach/core/validate.js')
|
||||
expect([...CHANGE_TYPES].sort()).toEqual([...serverTypes].sort())
|
||||
})
|
||||
|
||||
it('sets, reps, rep floor, rep ceiling, hold time, load step and policies', () => {
|
||||
const S = state()
|
||||
expect(apply(S, proposal([change({ type: 'sets', after: 4 })]), ['c1']).routines[0].ex[0].sets).toBe(4)
|
||||
expect(apply(S, proposal([change({ type: 'reps', after: 12 })]), ['c1']).routines[0].ex[0].reps).toBe(12)
|
||||
expect(apply(S, proposal([change({ type: 'repsMin', after: 8 })]), ['c1']).routines[0].ex[0].repsMin).toBe(8)
|
||||
expect(apply(S, proposal([change({ type: 'repsMax', before: null, after: 20 })]), ['c1']).routines[0].ex[0].repsMax).toBe(20)
|
||||
expect(apply(S, proposal([change({ type: 'sec', target: { routineId: 'r1', exId: '0007' }, before: 45, after: 60 })]), ['c1']).routines[0].ex[1].sec).toBe(60)
|
||||
expect(apply(S, proposal([change({ type: 'inc', before: null, after: 5 })]), ['c1']).routines[0].ex[0].inc).toBe(5)
|
||||
expect(apply(S, proposal([change({ type: 'exercise-prog', before: 'linear', after: 'double' })]), ['c1']).routines[0].ex[0].prog).toBe('double')
|
||||
expect(apply(S, proposal([change({ type: 'routine-prog', target: { routineId: 'r1' }, before: 'linear', after: 'greyskull' })]), ['c1']).routines[0].prog).toBe('greyskull')
|
||||
})
|
||||
|
||||
it('adds an exercise at the position asked for', () => {
|
||||
const out = apply(state(), proposal([change({
|
||||
type: 'add-exercise', target: { routineId: 'r1' }, before: null,
|
||||
after: { id: '0002', sets: 3, reps: 8, mode: 'reps', position: 1 }
|
||||
})]), ['c1'])
|
||||
expect(out.routines[0].ex.map(e => e.id)).toEqual(['0001', '0002', '0007', '0009'])
|
||||
expect(out.routines[0].ex[1].sets).toBe(3)
|
||||
})
|
||||
|
||||
it('carries a rep ceiling and the two flags onto an added exercise, and only when set', () => {
|
||||
const withFlags = apply(state(), proposal([change({
|
||||
type: 'add-exercise', target: { routineId: 'r1' }, before: null,
|
||||
after: { id: '0002', sets: 3, reps: 16, mode: 'reps', repsMin: 10, repsMax: 24, bodyweight: true, side: true }
|
||||
})]), ['c1']).routines[0].ex.at(-1)
|
||||
expect(withFlags).toMatchObject({ repsMin: 10, repsMax: 24, bodyweight: true, side: true })
|
||||
|
||||
const plain = apply(state(), proposal([change({
|
||||
type: 'add-exercise', target: { routineId: 'r1' }, before: null,
|
||||
after: { id: '0002', sets: 3, reps: 8, mode: 'reps' }
|
||||
})]), ['c1']).routines[0].ex.at(-1)
|
||||
// Absent means "whatever the catalogue says". Writing a flag out would freeze today's
|
||||
// dataset into the plan.
|
||||
expect(plain.bodyweight).toBeUndefined()
|
||||
expect(plain.side).toBeUndefined()
|
||||
})
|
||||
|
||||
it('drops an exercise without touching the rest', () => {
|
||||
const out = apply(state(), proposal([change({ type: 'remove-exercise' })]), ['c1'])
|
||||
expect(out.routines[0].ex.map(e => e.id)).toEqual(['0007', '0009'])
|
||||
})
|
||||
|
||||
it('keeps the prescription when swapping the movement', () => {
|
||||
const out = apply(state(), proposal([change({ type: 'swap-exercise', after: { id: '0002' } })]), ['c1'])
|
||||
const e = out.routines[0].ex[0]
|
||||
expect(e.id).toBe('0002')
|
||||
expect(e.sets).toBe(3)
|
||||
expect(e.reps).toBe(10) // not silently reset — that would be a change nobody approved
|
||||
})
|
||||
|
||||
it('drops flags that described the old movement when swapping', () => {
|
||||
const S = state()
|
||||
S.routines[0].ex[0] = { ...S.routines[0].ex[0], side: true, reps: 16, bodyweight: true }
|
||||
const e = apply(S, proposal([change({ type: 'swap-exercise', after: { id: '0002' } })]), ['c1']).routines[0].ex[0]
|
||||
// A lunge's "per side" is not a leg press's. Carrying it over would have the app halve a
|
||||
// rep count that was never per-side; the new exercise goes back to the catalogue.
|
||||
expect(e.side).toBeUndefined()
|
||||
expect(e.bodyweight).toBeUndefined()
|
||||
expect(e.reps).toBe(16) // the prescription itself still survives
|
||||
})
|
||||
|
||||
it('reorders only with a complete permutation', () => {
|
||||
const out = apply(state(), proposal([change({ type: 'reorder', target: { routineId: 'r1' }, after: ['0009', '0001', '0007'] })]), ['c1'])
|
||||
expect(out.routines[0].ex.map(e => e.id)).toEqual(['0009', '0001', '0007'])
|
||||
expect(() => apply(state(), proposal([change({ type: 'reorder', target: { routineId: 'r1' }, after: ['0009'] })]), ['c1'])).toThrow()
|
||||
// A repeated id counts right and resolves to the same object twice: the third exercise
|
||||
// disappears and the survivor is aliased into two slots. Both gates have to catch this,
|
||||
// because it is the one change type with nothing in the diff column to give it away.
|
||||
expect(() => apply(state(), proposal([change({
|
||||
type: 'reorder', target: { routineId: 'r1' }, after: ['0009', '0009', '0001']
|
||||
})]), ['c1'])).toThrow()
|
||||
})
|
||||
|
||||
it('refuses to superset an exercise with itself', () => {
|
||||
// Reachable only if the server let it past. By the message, not merely by throwing: the
|
||||
// unfixed path also threw — a TypeError, after it had already moved the exercise — so
|
||||
// asserting "it throws" would pass against the bug this is here to pin.
|
||||
expect(() => apply(state(), proposal([change({
|
||||
type: 'superset', after: { link: true, with: '0001' }
|
||||
})]), ['c1'])).toThrow('superset with itself')
|
||||
})
|
||||
|
||||
it('supersets by moving the partner adjacent and tagging both', () => {
|
||||
const out = apply(state(), proposal([change({ type: 'superset', after: { link: true, with: '0009' } })]), ['c1'])
|
||||
const ex = out.routines[0].ex
|
||||
expect(ex[0].id).toBe('0001')
|
||||
expect(ex[1].id).toBe('0009')
|
||||
expect(ex[0].sg).toBeTruthy()
|
||||
expect(ex[0].sg).toBe(ex[1].sg)
|
||||
})
|
||||
|
||||
it('unlinks a superset and cleans up the orphan tag', () => {
|
||||
const S = state()
|
||||
S.routines[0].ex[0].sg = 'a'; S.routines[0].ex[1].sg = 'a'
|
||||
const out = apply(S, proposal([change({ type: 'superset', after: { link: false } })]), ['c1'])
|
||||
expect(out.routines[0].ex[0].sg).toBeUndefined()
|
||||
expect(out.routines[0].ex[1].sg).toBeUndefined()
|
||||
})
|
||||
|
||||
it('adds, renames and removes routines, clearing any day that pointed at one', () => {
|
||||
const added = apply(state(), proposal([change({
|
||||
type: 'add-routine', target: {}, before: null,
|
||||
after: { name: 'Full body C', ex: [{ id: '0001', sets: 3, reps: 10, mode: 'reps' }] }
|
||||
})]), ['c1'])
|
||||
expect(added.routines).toHaveLength(3)
|
||||
expect(added.routines[2].id).not.toBe('r1')
|
||||
|
||||
const renamed = apply(state(), proposal([change({ type: 'rename-routine', target: { routineId: 'r1' }, before: 'Full body A', after: 'Upper' })]), ['c1'])
|
||||
expect(renamed.routines[0].name).toBe('Upper')
|
||||
|
||||
const removed = apply(state(), proposal([change({ type: 'remove-routine', target: { routineId: 'r2' } })]), ['c1'])
|
||||
expect(removed.routines.map(r => r.id)).toEqual(['r1'])
|
||||
expect(removed.week[3]).toBeUndefined() // Wednesday pointed at r2
|
||||
})
|
||||
|
||||
it('moves a day, and clears one', () => {
|
||||
const moved = apply(state(), proposal([change({ type: 'week', target: { weekday: 6 }, before: null, after: 'r1' })]), ['c1'])
|
||||
expect(moved.week[6]).toBe('r1')
|
||||
const cleared = apply(state(), proposal([change({ type: 'week', target: { weekday: 1 }, before: 'r1', after: 'rest' })]), ['c1'])
|
||||
expect(cleared.week[1]).toBeUndefined()
|
||||
})
|
||||
|
||||
it('never touches history, weigh-ins or settings', () => {
|
||||
const S = state({
|
||||
workouts: [{ id: 'w1', d: '2026-07-20', entries: [] }],
|
||||
bodyweight: [{ d: '2026-07-20', w: 80 }],
|
||||
exWeights: { '0001': { w: 20 } }, unit: 'kg', restSec: 90
|
||||
})
|
||||
const out = apply(S, proposal([change({ type: 'sets', after: 4 })]), ['c1'])
|
||||
expect(out.workouts).toEqual(S.workouts)
|
||||
expect(out.bodyweight).toEqual(S.bodyweight)
|
||||
expect(out.exWeights).toEqual(S.exWeights)
|
||||
expect(out.unit).toBe('kg')
|
||||
expect(out.restSec).toBe(90)
|
||||
})
|
||||
})
|
||||
|
||||
describe('accepting a subset', () => {
|
||||
it('applies only what was accepted and records the rest as declined', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
const p = proposal([
|
||||
change({ id: 'c1', type: 'sets', after: 4 }),
|
||||
change({ id: 'c2', type: 'reps', before: 10, after: 12 })
|
||||
])
|
||||
const res = applyChangeSet(s, p, ['c1'])
|
||||
expect(res).toMatchObject({ applied: 1, rejected: 1 })
|
||||
expect(s.routines[0].ex[0].sets).toBe(4)
|
||||
expect(s.routines[0].ex[0].reps).toBe(10)
|
||||
const decisions = s.coach.log.at(-1).decisions
|
||||
expect(decisions.find(d => d.id === 'c2').status).toBe('rejected')
|
||||
})
|
||||
|
||||
it('refuses to apply a stale change even if it was ticked', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
const p = markStale(proposal([change()]), { ...s, routines: [{ id: 'r1', name: 'A', ex: [] }] })
|
||||
expect(applyChangeSet(s, p, ['c1'])).toEqual({ applied: 0 })
|
||||
})
|
||||
|
||||
it('is all-or-nothing: a failure part-way leaves the plan exactly as it was', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
const before = JSON.stringify(s.routines)
|
||||
const p = proposal([
|
||||
change({ id: 'c1', type: 'sets', after: 4 }),
|
||||
change({ id: 'c2', type: 'reps', target: { routineId: 'r1', exId: 'ghost' }, before: null, after: 12 })
|
||||
])
|
||||
// The store hands us a clone and keeps it only if we return; throwing discards everything.
|
||||
expect(() => applyChangeSet(s, p, ['c1', 'c2'])).toThrow()
|
||||
const s2 = JSON.parse(JSON.stringify(state()))
|
||||
try { applyChangeSet(s2, p, ['c1', 'c2']) } catch { /* draft discarded by the caller */ }
|
||||
expect(JSON.stringify(state().routines)).toBe(before)
|
||||
})
|
||||
})
|
||||
|
||||
describe('snapshots and revert', () => {
|
||||
it('puts the plan back and leaves the training log alone', () => {
|
||||
const s = JSON.parse(JSON.stringify(state({ workouts: [{ id: 'w1', d: '2026-07-20', entries: [] }] })))
|
||||
const original = JSON.stringify(s.routines)
|
||||
applyChangeSet(s, proposal([change({ type: 'sets', after: 4 })]), ['c1'])
|
||||
expect(s.routines[0].ex[0].sets).toBe(4)
|
||||
expect(canRevert(s)).toBe(true)
|
||||
expect(revertLast(s)).toBe(true)
|
||||
expect(JSON.stringify(s.routines)).toBe(original)
|
||||
expect(s.workouts).toHaveLength(1)
|
||||
expect(s.coach.log.at(-1).kind).toBe('revert')
|
||||
})
|
||||
|
||||
it('keeps a bounded number of snapshots', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
for (let i = 0; i < SNAPSHOT_MAX + 3; i++) pushSnapshot(s, 'p' + i)
|
||||
expect(s.coach.snapshots).toHaveLength(SNAPSHOT_MAX)
|
||||
expect(s.coach.snapshots.at(-1).proposalId).toBe('p' + (SNAPSHOT_MAX + 2))
|
||||
})
|
||||
|
||||
it('reverting with nothing to revert to is a no-op, not a crash', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
expect(revertLast(s)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the log', () => {
|
||||
it('is bounded', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
for (let i = 0; i < LOG_MAX + 10; i++) appendLog(s, { kind: 'review', at: i, summary: 's' + i })
|
||||
expect(s.coach.log).toHaveLength(LOG_MAX)
|
||||
expect(s.coach.log.at(-1).summary).toBe('s' + (LOG_MAX + 9))
|
||||
})
|
||||
|
||||
it('stays well inside the sync budget even when full', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
for (let i = 0; i < LOG_MAX; i++) {
|
||||
appendLog(s, { kind: 'review', at: i, summary: 'x'.repeat(200), decisions: [{ id: 'c', type: 'sets', why: 'y'.repeat(200), status: 'accepted' }] })
|
||||
}
|
||||
for (let i = 0; i < SNAPSHOT_MAX; i++) pushSnapshot(s, 'p' + i)
|
||||
expect(JSON.stringify(s.coach).length).toBeLessThan(300 * 1024)
|
||||
})
|
||||
|
||||
it('records a dismissal so a later review knows not to nag', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
recordDismissal(s, proposal([change()]))
|
||||
expect(s.coach.log.at(-1).decisions[0].status).toBe('rejected')
|
||||
})
|
||||
})
|
||||
|
||||
describe('created plans', () => {
|
||||
// Accepting a plan replaces the whole week, so reschedules aimed at the old one are stale:
|
||||
// 'rest' would hide a session the new plan schedules, and an id outranks the new week.
|
||||
describe('per-date reschedules', () => {
|
||||
const past = '2020-01-02'
|
||||
const future = '2099-12-31'
|
||||
const withOverrides = () => JSON.parse(JSON.stringify(state({
|
||||
dayPlan: { [past]: 'r1', [future]: 'rest' }
|
||||
})))
|
||||
|
||||
it('drops today-and-later overrides when the schedule moves, and keeps past ones', () => {
|
||||
const s = withOverrides()
|
||||
applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle }, { schedule: true })
|
||||
expect(s.dayPlan[future]).toBeUndefined()
|
||||
expect(s.dayPlan[past]).toBe('r1') // history, not intent
|
||||
})
|
||||
|
||||
it('leaves them alone when the schedule was not taken', () => {
|
||||
const s = withOverrides()
|
||||
applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle }, { schedule: false })
|
||||
expect(s.dayPlan[future]).toBe('rest')
|
||||
expect(s.dayPlan[past]).toBe('r1')
|
||||
})
|
||||
|
||||
it('puts the dropped overrides back on revert', () => {
|
||||
const s = withOverrides()
|
||||
applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle }, { schedule: true })
|
||||
expect(revertLast(s)).toBe(true)
|
||||
expect(s.dayPlan[future]).toBe('rest')
|
||||
expect(s.dayPlan[past]).toBe('r1')
|
||||
})
|
||||
|
||||
it('reverts cleanly for a snapshot taken before the patch existed', () => {
|
||||
const s = withOverrides()
|
||||
pushSnapshot(s, 'old', 'legacy')
|
||||
delete s.coach.snapshots[s.coach.snapshots.length - 1].dayPlanRestore
|
||||
expect(() => revertLast(s)).not.toThrow()
|
||||
expect(s.dayPlan[future]).toBe('rest')
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses a bundle carrying a routine with no exercises', () => {
|
||||
// The server rejects this; if the client does not, the empty routine gets scheduled and
|
||||
// starting today's session opens a workout with nothing in it.
|
||||
const empty = { ...bundle, routines: [{ id: 'x1', name: 'A', ex: [] }] }
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
expect(() => applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle: empty }, {})).toThrow()
|
||||
expect(s.routines).toHaveLength(2)
|
||||
})
|
||||
|
||||
const bundle = {
|
||||
opengym_plan: 1, name: 'Coach plan', summary: 'three days',
|
||||
week: { 1: 'x1', 3: 'x2' },
|
||||
routines: [
|
||||
{ id: 'x1', name: 'A', emoji: '💪', why: 'why A', ex: [{ id: '0001', sets: 3, reps: 10, mode: 'reps', why: 'why ex' }] },
|
||||
{ id: 'x2', name: 'B', emoji: '🏋️', ex: [{ id: '0002', sets: 3, reps: 8, mode: 'reps' }] }
|
||||
],
|
||||
customEx: []
|
||||
}
|
||||
|
||||
it('adds routines as new ones and never modifies what was already there', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle }, { schedule: false })
|
||||
expect(s.routines).toHaveLength(4)
|
||||
expect(s.routines[0].name).toBe('Full body A') // untouched
|
||||
expect(s.routines[2].id).not.toBe('x1') // fresh ids, like a plan import
|
||||
expect(s.week[1]).toBe('r1') // schedule left alone
|
||||
})
|
||||
|
||||
it('replaces the week only when asked, and remaps to the new ids', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle }, { schedule: true })
|
||||
expect(s.week[1]).toBe(s.routines[2].id)
|
||||
expect(s.week[3]).toBe(s.routines[3].id)
|
||||
expect(s.week[5]).toBeUndefined() // a day the new plan leaves empty is rest
|
||||
})
|
||||
|
||||
it('keeps the Coach\'s prose out of the routine data', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle }, {})
|
||||
expect(s.routines[2].why).toBeUndefined()
|
||||
expect(s.routines[2].ex[0].why).toBeUndefined()
|
||||
expect(s.routines[2].ex[0].name).toBeUndefined()
|
||||
})
|
||||
|
||||
it('carries the rep ceiling and the flags the validator let through', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
applyCreatedPlan(s, {
|
||||
id: 'p1', kind: 'create',
|
||||
bundle: {
|
||||
...bundle,
|
||||
routines: [{ id: 'x1', name: 'A', ex: [{ id: '0001', sets: 3, reps: 12, mode: 'reps', repsMin: 8, repsMax: 20, bodyweight: true }] }]
|
||||
}
|
||||
}, {})
|
||||
expect(s.routines[2].ex[0]).toMatchObject({ repsMin: 8, repsMax: 20, bodyweight: true })
|
||||
})
|
||||
|
||||
it('is revertible like any other change', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle }, { schedule: true })
|
||||
revertLast(s)
|
||||
expect(s.routines).toHaveLength(2)
|
||||
expect(s.week[1]).toBe('r1')
|
||||
})
|
||||
|
||||
it('brings custom exercises along and registers them', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
applyCreatedPlan(s, {
|
||||
id: 'p1', kind: 'create',
|
||||
bundle: { ...bundle, routines: [{ id: 'x1', name: 'A', ex: [{ id: 'cx1', sets: 3, reps: 10 }] }], customEx: [{ id: 'cx1', n: 'Sandbag carry', bp: 'back' }] }
|
||||
}, {})
|
||||
expect(s.customEx).toHaveLength(1)
|
||||
registerCustom(s.customEx)
|
||||
expect(s.routines[2].ex[0].id).toBe(s.customEx[0].id)
|
||||
})
|
||||
})
|
||||
|
||||
describe('validation', () => {
|
||||
it('rejects an unreadable proposal rather than half-applying it', () => {
|
||||
expect(() => validateProposal(null)).toThrow()
|
||||
expect(() => validateProposal({})).toThrow()
|
||||
expect(() => validateProposal({ changes: [{ type: 'drop-database' }] })).toThrow()
|
||||
expect(() => validateProposal({ bundle: { routines: [] } })).toThrow()
|
||||
expect(validateProposal({ changes: [change()] })).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('the gate has something real to read', () => {
|
||||
it('the store actually exposes the `config` field every Coach entry point reads', async () => {
|
||||
// coachAvailable(config, …) is false when `config` is undefined, which is indistinguishable
|
||||
// from "this instance has no Coach". The views were ported once without the store field they
|
||||
// depend on, so every Coach surface silently vanished on every instance: no entry point, and
|
||||
// /#/coach redirecting straight back to /home. A missing key must fail here, not in a browser.
|
||||
// Asserted against the source rather than the live store: useStore touches `document` at
|
||||
// import time, so it cannot be instantiated in this environment. Crude, but it fails on
|
||||
// exactly the two edits that broke it — dropping the field, or dropping the fetch.
|
||||
// Matched loosely on purpose: boot() fetches through loadConfig() rather than inlining the
|
||||
// call, so what matters is that the field exists and that something writes /api/config
|
||||
// into it — not the spelling of the expression that does it.
|
||||
const { readFileSync } = await import('node:fs')
|
||||
const src = readFileSync(new URL('../store/useStore.js', import.meta.url), 'utf8')
|
||||
expect(src).toMatch(/\bconfig:\s*null\b/)
|
||||
expect(src).toMatch(/set\(\s*\{\s*config[:\s]/)
|
||||
expect(src).toMatch(/api\(['"]\/api\/config['"]\)/)
|
||||
// and boot() must actually reach it, however it is spelled
|
||||
expect(src).toMatch(/loadConfig\(\)|config:\s*await api\(/)
|
||||
})
|
||||
|
||||
it('a configured instance with a signed-in user opens the gate', () => {
|
||||
// The exact shape GET /api/config returns when the Coach is on.
|
||||
const config = { invite_only: false, coach: { enabled: true, provider: 'claude', authMode: 'instance' } }
|
||||
expect(coachAvailable(config, { id: 'u' })).toBe(true)
|
||||
expect(coachAvailable(undefined, { id: 'u' })).toBe(false) // the bug, pinned
|
||||
})
|
||||
})
|
||||
|
||||
describe('removing a routine takes its per-date reschedules with it', () => {
|
||||
// RoutineEdit does this on a hand-deleted routine. A pointer left behind still counts as an
|
||||
// override, so the day wears a "rescheduled" badge for good with no way to clear it.
|
||||
const c = { id: 'c1', type: 'remove-routine', target: { routineId: 'r2' }, before: null, after: null, why: 'unused' }
|
||||
|
||||
it('clears dayPlan entries pointing at the removed routine', () => {
|
||||
const S = state({ dayPlan: { '2099-01-01': 'r2', '2099-01-02': 'r1' } })
|
||||
const s = apply(S, proposal([c]), ['c1'])
|
||||
expect(s.dayPlan['2099-01-01']).toBeUndefined()
|
||||
expect(s.dayPlan['2099-01-02']).toBe('r1') // a different routine is none of its business
|
||||
expect(s.week[3]).toBeUndefined()
|
||||
})
|
||||
|
||||
it('restores them on revert', () => {
|
||||
const S = state({ dayPlan: { '2099-01-01': 'r2' } })
|
||||
const s = apply(S, proposal([c]), ['c1'])
|
||||
expect(revertLast(s)).toBe(true)
|
||||
expect(s.dayPlan['2099-01-01']).toBe('r2')
|
||||
})
|
||||
})
|
||||
|
||||
describe('what the log keeps, so a decision never makes a proposal vanish', () => {
|
||||
const plan = {
|
||||
opengym_plan: 1, name: 'Coach plan', summary: 'p', week: { 1: 'x1' },
|
||||
routines: [{ id: 'x1', name: 'A', emoji: '💪', why: 'w', ex: [{ id: '0001', sets: 3, reps: 10, mode: 'reps', why: 'y'.repeat(300), secret: 1 }] }],
|
||||
customEx: []
|
||||
}
|
||||
|
||||
it('applyChangeSet returns the log id and keeps the declined change whole', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
const p = proposal([change(), change({ id: 'c2', type: 'reps', before: 10, after: 8, why: 'too many' })])
|
||||
const res = applyChangeSet(s, p, ['c1'])
|
||||
expect(res.logId).toBe(s.coach.log.at(-1).id)
|
||||
const rej = s.coach.log.at(-1).decisions.find(d => d.id === 'c2')
|
||||
expect(rej).toMatchObject({ status: 'rejected', type: 'reps', before: 10, after: 8, target: { routineId: 'r1', exId: '0001' } })
|
||||
expect(logEntry(s, res.logId).kind).toBe('review')
|
||||
})
|
||||
|
||||
it('applyCreatedPlan keeps a light copy of the bundle and whether the week was taken', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
const res = applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle: plan, iteration: 2 }, { schedule: false })
|
||||
const e = logEntry(s, res.logId)
|
||||
expect(e.kind).toBe('create')
|
||||
expect(e.scheduled).toBe(false)
|
||||
expect(e.iteration).toBe(2)
|
||||
expect(e.bundle.routines[0].ex[0]).toEqual({ id: '0001', sets: 3, mode: 'reps', reps: 10, why: 'y'.repeat(200) })
|
||||
expect(e.bundle.routines[0].why).toBe('w')
|
||||
})
|
||||
|
||||
it('recordDismissal returns the id and keeps a discarded plan too', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
const id = recordDismissal(s, { id: 'p1', kind: 'create', summary: 'nope', bundle: plan })
|
||||
const e = logEntry(s, id)
|
||||
expect(e.dismissed).toBe(true)
|
||||
expect(e.bundle.name).toBe('Coach plan')
|
||||
expect(s.coach.lastReview).toBeUndefined()
|
||||
const rid = recordDismissal(s, proposal([change()], { evidence: { sessions: 4 }, notes: ['n'] }))
|
||||
expect(logEntry(s, rid)).toMatchObject({ evidence: { sessions: 4 }, notes: ['n'] })
|
||||
expect(logEntry(s, rid).decisions[0]).toMatchObject({ status: 'rejected', before: 3, after: 4 })
|
||||
})
|
||||
|
||||
it('recordDebrief files the whole reading', () => {
|
||||
const s = JSON.parse(JSON.stringify(state()))
|
||||
const id = recordDebrief(s, { id: 'd1', kind: 'debrief', workout: { id: 'w1', name: 'Push' }, summary: 'ok', score: 8, highlights: ['a'], watch: [], nextTime: ['b'] })
|
||||
expect(logEntry(s, id)).toMatchObject({ kind: 'debrief', score: 8, highlights: ['a'], nextTime: ['b'], workout: { id: 'w1' } })
|
||||
})
|
||||
|
||||
it('lightBundle drops what the card does not show', () => {
|
||||
const b = lightBundle({ ...plan, customEx: [{ id: 'z' }], basedOn: 'x' })
|
||||
expect(b.customEx).toBeUndefined()
|
||||
expect(b.basedOn).toBeUndefined()
|
||||
expect(Object.keys(b.routines[0].ex[0])).not.toContain('secret')
|
||||
expect(lightBundle(null)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -822,6 +822,56 @@ describe('warm-up rows identified by phase alone', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('nextTrainingDay', () => {
|
||||
// 2026-08-18 is a Tuesday; the week map is keyed by getDay(), so 0 is Sunday.
|
||||
const TUE = '2026-08-18'
|
||||
const base = (over = {}) => ({
|
||||
dayPlan: {},
|
||||
routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001' }] }, { id: 'r2', name: 'B', ex: [{ id: '0002' }] }],
|
||||
week: {},
|
||||
...over
|
||||
})
|
||||
|
||||
it('finds the next scheduled day and names its routine', () => {
|
||||
const S = base({ week: { 4: 'r2' } }) // Thursday
|
||||
expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-20', weekday: 4 })
|
||||
expect(nextTrainingDay(S, TUE).routine.name).toBe('B')
|
||||
})
|
||||
|
||||
it('looks forward only — today itself is never the answer', () => {
|
||||
// Only Tuesday is scheduled and today is Tuesday, so the next one is a week out. (The UI
|
||||
// cannot reach this: a day with a session takes the other branch and never asks.)
|
||||
const S = base({ week: { 2: 'r1' } })
|
||||
expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-25', weekday: 2 })
|
||||
})
|
||||
|
||||
it('wraps around the end of the week', () => {
|
||||
const S = base({ week: { 1: 'r1' } }) // Monday, six days on
|
||||
expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-24', weekday: 1 })
|
||||
})
|
||||
|
||||
it('is null when every day is rest', () => {
|
||||
expect(nextTrainingDay(base(), TUE)).toBeNull()
|
||||
})
|
||||
|
||||
it('skips a day whose routine no longer exists', () => {
|
||||
const S = base({ week: { 3: 'gone', 5: 'r1' } })
|
||||
expect(nextTrainingDay(S, TUE)).toMatchObject({ iso: '2026-08-21', weekday: 5 })
|
||||
})
|
||||
|
||||
it('skips a routine with no exercises — starting it would open an empty session', () => {
|
||||
const S = base({ routines: [{ id: 'r1', name: 'A', ex: [] }, { id: 'r2', name: 'B', ex: [{ id: '1' }] }], week: { 3: 'r1', 5: 'r2' } })
|
||||
expect(nextTrainingDay(S, TUE)).toMatchObject({ weekday: 5 })
|
||||
})
|
||||
|
||||
it('respects a per-date override in both directions', () => {
|
||||
const moved = base({ week: {}, dayPlan: { '2026-08-19': 'r1' } })
|
||||
expect(nextTrainingDay(moved, TUE)).toMatchObject({ iso: '2026-08-19' })
|
||||
const off = base({ week: { 3: 'r1', 5: 'r2' }, dayPlan: { '2026-08-19': 'rest' } })
|
||||
expect(nextTrainingDay(off, TUE)).toMatchObject({ weekday: 5 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('pinnedNoteFor', () => {
|
||||
const S = {
|
||||
workouts: [
|
||||
|
||||
@@ -38,6 +38,22 @@ export async function nativeSave(state) {
|
||||
// travel as if it were training data.
|
||||
const REMOTE_FILE = 'opengym-remote.json'
|
||||
|
||||
// Small JSON files in the app's private data directory, for device facts that must not ride
|
||||
// in S (which syncs and exports): the pairing, and how the Coach runs on this phone.
|
||||
export async function readJsonFile(name) {
|
||||
try {
|
||||
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
|
||||
const r = await Filesystem.readFile({ path: name, directory: Directory.Data, encoding: Encoding.UTF8 })
|
||||
return JSON.parse(r.data)
|
||||
} catch (e) { return null }
|
||||
}
|
||||
export async function writeJsonFile(name, data) {
|
||||
try {
|
||||
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
|
||||
await Filesystem.writeFile({ path: name, directory: Directory.Data, data: JSON.stringify(data), encoding: Encoding.UTF8 })
|
||||
} catch (e) { /* not a Capacitor build, or the write failed — the caller's in-memory copy stands */ }
|
||||
}
|
||||
|
||||
export async function loadRemoteFile() {
|
||||
try {
|
||||
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')
|
||||
|
||||
@@ -160,7 +160,7 @@ export function parsePlan(raw) {
|
||||
export function mergePlan(s, bundle, { schedule } = {}) {
|
||||
s.customEx = s.customEx || []
|
||||
const exIdMap = {}
|
||||
bundle.customEx.forEach(c => {
|
||||
;(bundle.customEx || []).forEach(c => {
|
||||
const same = s.customEx.find(x => (x.n || '').toLowerCase() === (c.n || '').toLowerCase() && x.bp === c.bp)
|
||||
if (same) { exIdMap[c.id] = same.id; return }
|
||||
const nid = uid()
|
||||
|
||||
@@ -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(354)
|
||||
expect(inherited).toHaveLength(475)
|
||||
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(598)
|
||||
expect(inherited).toHaveLength(565)
|
||||
// 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('d379a3a509af71a6773017d3374938c2067cc870bbf7bd5bbc0bb8ad853d0781')
|
||||
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('e6addc025574b25e392121fe543012a189116d8cb9c91fe5e96caeb3c3e450f2')
|
||||
})
|
||||
|
||||
test('does not leak European Portuguese UI terms', () => {
|
||||
|
||||
Reference in new issue
Block a user