Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Coach: die Bibliothek im Payload ist gedeckelt (160, ausgewogen, das eigene Training immer dabei)
Duarte Santosaef950cf7c67
diff --git a/api/coach/core/library.js b/api/coach/core/library.jsindex 3df420467..0a0643add 100644--- a/api/coach/core/library.js+++ b/api/coach/core/library.js@@ -13,13 +13,47 @@ export const LIB_BY_ID = new Map(LIBRARY.map(e => [e.id, e]));export const libraryHas = id => LIB_BY_ID.has(id);export const libraryName = id => LIB_BY_ID.get(id)?.n || null;-/* ---------- the library slice the model gets to choose from ---------- */-export function librarySlice(S, equipment) {+/* ---------- the library slice the model gets to choose from ----------+ Bounded. The whole catalogue is 1,324 rows — 10k+ tokens on every job, which costs real money+ against a cloud API and does not fit a small local model's context at all; and a model does+ not choose better from 1,324 options than from 160. So the slice is capped and balanced: an+ even share of every body part, in catalogue order (deterministic, so repeated jobs keep the+ same prefix), with the exercises already in the user's plan or history always included —+ a review has to be able to name what it is talking about. */+export const MAX_LIBRARY = 160;++export function librarySlice(S, equipment, { keep = [], max = MAX_LIBRARY } = {}) {const wanted = (equipment || []).map(x => String(x).toLowerCase());const customs = (S.customEx || []).map(c => ({ id: c.id, n: c.n, bp: c.bp, tg: null, eq: 'custom', custom: true }));// No equipment stated (or "everything") ⇒ the whole catalogue. Filtering to nothing would// leave the Coach unable to propose anything at all, which is a worse failure than a// slightly larger payload.- const base = wanted.length ? LIBRARY.filter(e => wanted.includes((e.eq || '').toLowerCase())) : LIBRARY;- return [...customs, ...(base.length ? base : LIBRARY)];+ const filtered = wanted.length ? LIBRARY.filter(e => wanted.includes((e.eq || '').toLowerCase())) : LIBRARY;+ const base = filtered.length ? filtered : LIBRARY;++ const pinned = new Set(keep.filter(id => LIB_BY_ID.has(id)));+ const out = [];+ const taken = new Set();+ const add = e => { if (!taken.has(e.id)) { taken.add(e.id); out.push(e); } };+ // What the user already trains comes first, filter or no filter.+ for (const id of pinned) add(LIB_BY_ID.get(id));+ if (base.length + out.length <= max) {+ base.forEach(add);+ } else {+ // Round-robin across body parts so a 292-row "upper arms" cannot crowd out a 37-row+ // "lower arms"; order within a body part is the catalogue's own.+ const groups = new Map();+ for (const e of base) { if (!groups.has(e.bp)) groups.set(e.bp, []); groups.get(e.bp).push(e); }+ const lanes = [...groups.keys()].sort().map(k => groups.get(k));+ const cursor = lanes.map(() => 0);+ let progressed = true;+ while (out.length < max && progressed) {+ progressed = false;+ for (let i = 0; i < lanes.length && out.length < max; i++) {+ while (cursor[i] < lanes[i].length && taken.has(lanes[i][cursor[i]].id)) cursor[i]++;+ if (cursor[i] < lanes[i].length) { add(lanes[i][cursor[i]++]); progressed = true; }+ }+ }+ }+ return [...customs, ...out];}diff --git a/api/coach/core/payload.js b/api/coach/core/payload.jsindex bdad4796a..5163fb990 100644--- a/api/coach/core/payload.js+++ b/api/coach/core/payload.js@@ -10,7 +10,7 @@* handle stands in), passkey and credential material, push subscriptions, invite data, theme* and appearance settings, and every other profile's everything.*/-import { LIBRARY, LIB_BY_ID, libraryHas, libraryName, librarySlice } from './library.js';+import { LIBRARY, LIB_BY_ID, libraryHas, libraryName, librarySlice, MAX_LIBRARY } from './library.js';export const CONTRACT = 1;// Bounds from FR-22. A review reads a training block, not a training career: more history@@ -140,7 +140,7 @@ export function cleanPlan(S) {}// The catalogue lives in library.js; re-exported so older imports keep resolving.-export { LIBRARY, libraryHas, libraryName, librarySlice };+export { LIBRARY, MAX_LIBRARY, libraryHas, libraryName, librarySlice };/* ---------- effort scale (mirrors history.js effortOf) ---------- */const effortOf = S => {@@ -201,6 +201,15 @@ function aggregates(S, workouts) {};}+/** Every exercise id the plan names or the given workouts logged — the ones a proposal has to+ * be able to refer to, so they ride in the library slice whatever the cap or the filter. */+function trainedIds(S, workouts) {+ const ids = new Set();+ (S.routines || []).forEach(r => (r.ex || []).forEach(e => ids.add(e.id)));+ (workouts || []).forEach(w => (w.entries || []).forEach(en => ids.add(en.id)));+ return [...ids];+}+/** One workout, reduced to what a coach reads. */function cleanWorkout(w) {return {@@ -289,9 +298,9 @@ export function build(S, opts = {}) {series: (S.bodyweight || []).filter(b => !p.window.from || b.d >= p.window.from).map(b => ({ d: b.d, w: b.w }))};if (opts.note) p.userNote = String(opts.note).slice(0, 1000);- p.library = librarySlice(S, profile?.equipment);+ p.library = librarySlice(S, profile?.equipment, { keep: trainedIds(S, workouts) });} else {- p.library = librarySlice(S, profile?.equipment);+ p.library = librarySlice(S, profile?.equipment, { keep: trainedIds(S, S.workouts || []) });// Creation for a returning user: what they have actually handled, so proposed baselines// start from evidence rather than optimism (B2/FR-20).const best = {};diff --git a/api/coach/jobs.js b/api/coach/jobs.jsindex 01eab3086..92d4b9711 100644--- a/api/coach/jobs.js+++ b/api/coach/jobs.js@@ -33,7 +33,9 @@ export { hashPlan, buildPrompt };const DATA = process.env.DATA_DIR || '/data';const COACH_DIR = path.join(DATA, 'coach');-export const TIMEOUT_MS = 5 * 60000;+// Five minutes by default. A local model on a small CPU box can legitimately need more; a+// cloud API that needs more has a problem. COACH_JOB_TIMEOUT_MS overrides, never below one minute.+export const TIMEOUT_MS = Math.max(60000, +process.env.COACH_JOB_TIMEOUT_MS || 5 * 60000);const MAX_CONCURRENT = 2; // these are minutes-scale jobs on often-single-core boxesconst PENDING_DAYS = 14; // FR-33const HISTORY_MAX = 20;@@ -104,9 +106,16 @@ export function status(uid) {return {job: rec.current ? { id: rec.current.id, kind: rec.current.kind, state: rec.current.state, startedAt: rec.current.startedAt } : null,pending: rec.pending || null,- cap: capState(uid)+ cap: capState(uid),+ // How the most recent job ended, so the chat can say "nothing to change" or "that failed"+ // in the Coach's own bubble rather than leaving a job that silently stopped appearing.+ last: lastOutcome(rec)};}+function lastOutcome(rec) {+ const h = (rec.history || []).at(-1);+ return h ? { id: h.id, kind: h.kind, outcome: h.outcome, errorClass: h.errorClass || null, at: h.at, ...(h.reading ? { reading: h.reading } : {}) } : null;+}function archive(uid, rec, outcome) {const history = [...(rec.history || []), {id: rec.pending?.id, kind: rec.pending?.kind, outcome, at: Date.now()diff --git a/api/test/payload.test.js b/api/test/payload.test.jsindex 50422f541..4e109f6a5 100644--- a/api/test/payload.test.js+++ b/api/test/payload.test.js@@ -108,14 +108,44 @@ test('creation payload carries working weights so baselines start from evidence'});test('the library is filtered to the equipment someone actually has', () => {- const all = payload.librarySlice({}, []).length;- const dumbbell = payload.librarySlice({}, ['dumbbell']).length;- assert.ok(dumbbell < all && dumbbell > 0);+ const dumbbell = payload.librarySlice({}, ['dumbbell']);+ assert.ok(dumbbell.length > 0);+ assert.ok(dumbbell.every(e => e.eq === 'dumbbell'), 'nothing outside the filter');+ assert.ok(payload.librarySlice({}, ['dumbbell', 'barbell']).some(e => e.eq === 'barbell'));// Custom exercises always travel: they exist nowhere else and the model cannot guess them.const withCustom = payload.librarySlice({ customEx: [{ id: 'cx1', n: 'Sandbag carry', bp: 'back' }] }, ['dumbbell']);assert.equal(withCustom[0].id, 'cx1');});+test('the library slice is capped, balanced across body parts, deterministic, and keeps what the user trains', () => {+ const { MAX_LIBRARY, LIBRARY } = payload;+ const all = payload.librarySlice({}, []);+ assert.ok(LIBRARY.length > MAX_LIBRARY, 'the catalogue is bigger than the cap, or this test proves nothing');+ assert.equal(all.length, MAX_LIBRARY);+ const byBp = {};+ all.forEach(e => { byBp[e.bp] = (byBp[e.bp] || 0) + 1; });+ const parts = Object.keys(byBp).length;+ assert.ok(parts >= 8, `only ${parts} body parts represented`);+ // Small groups (neck has two rows) run out early and their share flows to the rest, so the+ // bound is "nobody dominates", not "everyone equal".+ assert.ok(Math.max(...Object.values(byBp)) <= MAX_LIBRARY / 4, `one body part dominates: ${JSON.stringify(byBp)}`);+ assert.equal(byBp.neck, LIBRARY.filter(e => e.bp === 'neck').length, 'a tiny group is present in full');+ assert.deepEqual(all.map(e => e.id), payload.librarySlice({}, []).map(e => e.id), 'same slice every time');++ // An exercise the user already trains rides along even when the filter would exclude it.+ const barbell = LIBRARY.find(e => e.eq === 'barbell');+ const kept = payload.librarySlice({}, ['dumbbell'], { keep: [barbell.id] });+ assert.equal(kept[0].id, barbell.id);+ assert.ok(kept.length <= MAX_LIBRARY + 1);++ // …and through build(): the plan's own exercises are in the slice for a review.+ const S = sampleState();+ const planIds = S.routines.flatMap(r => r.ex.map(e => e.id));+ const p = payload.build(S, { handle: 'h'.repeat(16), kind: 'review' });+ assert.ok(planIds.every(id => p.library.some(e => e.id === id)), 'every plan exercise is in the slice');+ assert.ok(p.library.length <= MAX_LIBRARY + planIds.length);+});+test('equipment nobody in the library has still yields a usable library', () => {// Better a slightly larger payload than a Coach that cannot propose anything at all.assert.ok(payload.librarySlice({}, ['moon rocks']).length > 0);diff --git a/frontend/src/views/Coach.jsx b/frontend/src/views/Coach.jsxdeleted file mode 100644index 5969ede22..000000000--- a/frontend/src/views/Coach.jsx+++ /dev/null@@ -1,310 +0,0 @@-import { useEffect, useState } from 'react'-import { useNavigate } from 'react-router-dom'-import { useStore, DEF } from '../store/useStore.js'-import { useUI } from '../store/useUI.js'-import { t } from '../lib/i18n.js'-import { fmtDate } from '../lib/format.js'-import { DEMO } from '../lib/demo.js'-import { MOBILE } from '../lib/mobile.js'-import {- coachAvailable, hasConsent, CONSENT_VERSION, emptyCoach, CATEGORY_TEXT,- canRevert, revertLast, changeTitle, recordDismissal-} from '../lib/coach.js'-import {- useCoachStatus, requestReview, resolvePending, forgetCoach, disclosure, JOB_ERRORS-} from '../lib/coach-api.js'-import { confirmSheet } from '../sheets.jsx'-import Icon from '../components/Icon.jsx'-import { Section, Row, Button, TextArea, Switch, SelectRow } from '../components/ui.jsx'--/* The Coach's home: what it's doing, what it's proposing, what it has done before, and every- switch that turns it off. Deliberately one screen — a feature that edits your training plan- should not scatter its controls, least of all the ones that stop it. */--const GOALS = ['strength', 'muscle', 'general fitness', 'fat loss', 'endurance']---export default function Coach() {- const nav = useNavigate()- const S = useStore(s => s.S)- const user = useStore(s => s.user)- const config = useStore(s => s.config)- const coachMode = useStore(s => s.coachLocal?.mode)- const update = useStore(s => s.update)- const toast = useUI(s => s.toast)- const [note, setNote] = useState('')- const [busy, setBusy] = useState(false)- const { job, pending, cap, refresh } = useCoachStatus(true)-- // Gating lives in one predicate; if the instance isn't offering the Coach this route simply- // isn't a place you can be.- useEffect(() => { if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE, coachMode })) nav('/home', { replace: true }) }, [config, user, coachMode])- if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE, coachMode })) return null-- const consented = hasConsent(S)- const coach = S.coach || emptyCoach()-- const askReview = async () => {- setBusy(true)- try {- await requestReview(note)- setNote('')- toast(t('The Coach is reading your training…'))- refresh()- } catch (e) { toast(e.message || t('Could not ask the Coach')) }- setBusy(false)- }-- const turnOff = () => confirmSheet({- title: t('Turn the Coach off?'),- message: t('Any pending suggestion is discarded and scheduled reviews stop. Your Coach history stays, and you can turn it back on anytime.'),- confirmText: t('Turn off'), danger: true,- onConfirm: async () => {- try { await forgetCoach() } catch (e) { /* server-side copy goes on the next call */ }- update(s => { s.coach = { ...(s.coach || emptyCoach()), consent: null, cadence: 'off' } })- toast(t('The Coach is off'))- nav('/home')- }- })-- const doRevert = () => confirmSheet({- title: t('Undo the last Coach changes?'),- message: t('Your plan goes back to how it was before you accepted them. Workouts you have logged since are untouched.'),- confirmText: t('Undo'),- onConfirm: () => {- let ok = false- update(s => { ok = revertLast(s) })- toast(ok ? t('Plan restored') : t('Nothing to undo'))- }- })-- return <div className="narrow">- <div className="hdr">- <button className="iconbtn" onClick={() => nav('/plan')} aria-label={t('Back')}><Icon name="chevronLeft" /></button>- <div style={{ flex: 1, marginLeft: 10 }}>- <h1>{t('Coach')}</h1>- <div className="sub">{t('Plan design and reviews, from your own training')}</div>- </div>- </div>-- {!consented- ? <ConsentCard onDone={() => refresh()} />- : <>- <StatusCard job={job} pending={pending} nav={nav} />-- {!job && !pending && <div className="card">- <h2 style={{ margin: '0 0 6px' }}>{t('Ask for a review')}</h2>- <div className="muted small" style={{ marginBottom: 10 }}>- {t('The Coach reads what you have actually logged since its last look and suggests changes to your plan — each one with its reason.')}- </div>- <TextArea rows={2} value={note} maxLength={1000} onChange={e => setNote(e.target.value)}- placeholder={t('Anything it should know? (optional) — e.g. “right shoulder pinches on overhead work”')} />- <div style={{ height: 10 }} />- <Button variant="primary" icon="sparkles" disabled={busy} onClick={askReview}>{t('Ask for a review')}</Button>- {cap?.limit > 0 && <div className="dim small" style={{ marginTop: 8, textAlign: 'center' }}>- {t('{0} of {1} Coach runs used today', cap.used, cap.limit)}- </div>}- </div>}-- {!S.routines.length && <div className="card">- <div className="muted small" style={{ marginBottom: 10 }}>{t('No plan yet — the Coach can build you one from a few questions.')}</div>- <Button variant="primary" icon="sparkles" onClick={() => nav('/coach/intake')}>{t('Let the Coach build my plan')}</Button>- </div>}-- <CadenceCard coach={coach} update={update} />-- <Section title={t('Coach profile')} footer={t('Used by every proposal — keep limitations here up to date.')}>- <Row icon="clipboard" iconTint="var(--indigo)" title={t('Your answers')}- subtitle={coach.profile ? summarise(coach.profile) : t('Not set yet')}- accessory="chevron" onClick={() => nav('/coach/intake?edit=1')} />- </Section>-- <LogCard coach={coach} />-- <Section title={t('Controls')}>- {canRevert(S) && <Row icon="reset" iconTint="var(--blue)" title={t('Undo the last Coach changes')} accessory="chevron" onClick={doRevert} />}- <Row icon="signOut" iconTint="var(--red)" title={t('Turn the Coach off')} danger onClick={turnOff} />- </Section>- </>}- </div>-}--const summarise = p => [- p.goal && t(p.goal),- p.daysPerWeek && t('{0} days a week', p.daysPerWeek),- p.sessionMin && t('{0} min', p.sessionMin)-].filter(Boolean).join(' · ')--/* ---------------------------------- consent ---------------------------------- */--function ConsentCard({ onDone }) {- const update = useStore(s => s.update)- const config = useStore(s => s.config)- const toast = useUI(s => s.toast)- const openSheet = useUI(s => s.openSheet)- const [info, setInfo] = useState(null)- useEffect(() => { disclosure().then(setInfo).catch(() => {}) }, [])-- const agree = () => {- update(s => { s.coach = { ...(s.coach || emptyCoach()), consent: { agreedAt: new Date().toISOString(), version: CONSENT_VERSION } } })- toast(t('The Coach is on'))- onDone()- }-- const open = () => openSheet(close => <>- <h3>{t('Before the Coach starts')}</h3>- <div className="muted small" style={{ lineHeight: 1.5, marginBottom: 12 }}>- {info?.payer === 'you'- ? t('When you ask for a plan or a review, this phone sends the following straight to {0}, using your own API key. You pay for every request.', info.host || info.providerLabel)- : t('When you ask for a plan or a review, this instance sends the following to {0}, running on this server under the instance owner’s account.',- info?.providerLabel || config?.coach?.providerLabel || t('the configured AI provider'))}- </div>- <div className="sect-b">- {(info?.categories || Object.keys(CATEGORY_TEXT)).map(k => {- const [title, sub] = CATEGORY_TEXT[k] || [k, '']- return <div key={k} className="lrow">- <span className="lrow-i" style={{ '--tint': 'var(--acc)' }}><Icon name="check" /></span>- <span className="lrow-m"><span className="lrow-t">{t(title)}</span><span className="lrow-s">{t(sub)}</span></span>- </div>- })}- </div>- <div className="dim small" style={{ lineHeight: 1.5, display: 'grid', gap: 8, marginTop: 12 }}>- <div>{t('Your name, your sign-in details and everything else about your account stay here. Other people’s data is never included.')}</div>- <div>{t('Nothing the Coach suggests is applied on its own — you review every change and can undo it afterwards.')}</div>- <div>{t('You can turn this off at any time, which also discards anything the Coach is holding for you.')}</div>- <div style={{ color: 'var(--yellow)' }}>{t('The Coach is not a doctor or a physiotherapist. If something hurts, ask a professional.')}</div>- </div>- <div style={{ height: 14 }} />- <Button variant="primary" onClick={() => { close(); agree() }}>{t('I understand — turn the Coach on')}</Button>- <div style={{ height: 8 }} />- <Button onClick={close}>{t('Not now')}</Button>- </>)-- return <div className="card">- <div className="row" style={{ gap: 10, marginBottom: 6 }}>- <span className="lrow-i" style={{ '--tint': 'var(--acc)' }}><Icon name="sparkles" /></span>- <div className="big" style={{ fontSize: 20 }}>{t('Meet the Coach')}</div>- </div>- <div className="muted small" style={{ marginBottom: 12, lineHeight: 1.5 }}>- {info?.payer === 'you'- ? t('An AI coach that can design your plan and adjust it from what you actually log. It runs with your own API key, it never changes anything without your say-so, and it is off until you turn it on.')- : t('An AI coach that can design your plan and adjust it from what you actually log. It runs on this server, it never changes anything without your say-so, and it is off until you turn it on.')}- </div>- <Button variant="primary" icon="sparkles" onClick={open}>{t('See what it would use')}</Button>- </div>-}--/* ---------------------------------- status ---------------------------------- */--function StatusCard({ job, pending, nav }) {- if (job) return <div className="card">- <div className="row" style={{ gap: 10 }}>- <span className="lrow-i" style={{ background: 'var(--orange)' }}><Icon name="sparkles" /></span>- <div>- <div style={{ fontWeight: 600 }}>{t('The Coach is thinking…')}</div>- <div className="muted small">{t('This takes a minute or two. You can leave this screen — it keeps going.')}</div>- </div>- </div>- </div>-- if (pending) return <div className="card" style={{ borderColor: 'var(--acc)' }}>- <div className="today-row" onClick={() => nav('/coach/proposal')}>- <div className="row" style={{ gap: 9, minWidth: 0 }}>- <span className="lrow-i" style={{ background: 'var(--acc)' }}><Icon name="clipboard" /></span>- <div style={{ minWidth: 0 }}>- <div className="lbl2">{pending.kind === 'create' ? t('Your plan is ready') : t('Suggestions ready')}</div>- <div className="ttl">{pending.kind === 'create'- ? t('{0} routines to look over', pending.bundle?.routines?.length || 0)- : t(pending.changes?.length === 1 ? '{0} suggestion' : '{0} suggestions', pending.changes?.length || 0)}</div>- </div>- </div>- <span className="tag acc">{t('Review')}</span>- </div>- </div>-- return null-}--/* ---------------------------------- cadence ---------------------------------- */--function CadenceCard({ coach, update }) {- const cadence = coach.cadence && coach.cadence !== 'off' ? coach.cadence : null- const mode = !cadence ? 'off' : cadence.weekly ? 'weekly' : 'every'- const setMode = m => update(s => {- const c = (s.coach = s.coach || emptyCoach())- c.cadence = m === 'off' ? 'off' : m === 'weekly' ? { weekly: { day: 0, time: '18:00' } } : { everyWorkouts: 4 }- })- const patch = fn => update(s => { const c = (s.coach = s.coach || emptyCoach()); fn(c) })-- return <Section title={t('Automatic reviews')}- footer={mode === 'off'- ? t('Off — the Coach only looks when you ask it to.')- : t('You are only notified when the Coach actually has something to suggest.')}>- <SelectRow icon="clock" iconTint="var(--purple)" title={t('When')}- value={mode} onChange={setMode}- options={[- { value: 'off', label: t('Off') },- { value: 'weekly', label: t('Weekly'), subtitle: t('On a day and time you choose') },- { value: 'every', label: t('After every few workouts'), subtitle: t('As soon as you have logged enough') }- ]} />- {mode === 'weekly' && <>- <SelectRow icon="calendar" iconTint="var(--orange)" title={t('Day')}- value={cadence.weekly.day}- onChange={v => patch(c => { c.cadence = { weekly: { ...c.cadence.weekly, day: v } } })}- options={['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'].map((d, i) => ({ value: i, label: t(d) }))} />- <Row icon="clock" iconTint="var(--purple)" title={t('Time')}>- <input type="time" className="timef" value={cadence.weekly.time || '18:00'}- onChange={e => patch(c => { c.cadence = { weekly: { ...c.cadence.weekly, time: e.target.value } } })} />- </Row>- </>}- {mode === 'every' && <SelectRow icon="dumbbell" iconTint="var(--teal)" title={t('After how many workouts')}- value={cadence.everyWorkouts || 4}- onChange={v => patch(c => { c.cadence = { everyWorkouts: v } })}- options={[3, 4, 5, 6, 8, 10].map(n => ({ value: n, label: t('{0} workouts', n) }))} />}- </Section>-}--/* ---------------------------------- log ---------------------------------- */--function LogCard({ coach }) {- const openSheet = useUI(s => s.openSheet)- const log = [...(coach.log || [])].reverse()- if (!log.length) return null-- const detail = e => openSheet(close => <>- <h3>{e.kind === 'create' ? t('Plan from the Coach') : e.kind === 'revert' ? t('Undo') : t('Coach review')}</h3>- <div className="dim small" style={{ marginBottom: 10 }}>{fmtDate(new Date(e.at).toISOString().slice(0, 10), true)}</div>- {e.summary && <div className="muted small" style={{ lineHeight: 1.5, marginBottom: 12 }}>{e.summary}</div>}- {!!e.evidence?.sessions && <div className="dim small" style={{ marginBottom: 10 }}>- {t('Based on {0} sessions', e.evidence.sessions)}{e.evidence.from ? ' · ' + fmtDate(e.evidence.from) + ' – ' + fmtDate(e.evidence.to) : ''}- </div>}- {(e.decisions || []).map(d => <div key={d.id} className="row between" style={{ padding: '8px 2px', borderBottom: '1px solid var(--sep)', gap: 10 }}>- <div style={{ minWidth: 0 }}>- <div className="small" style={{ fontWeight: 600 }}>{changeTitle(d)}</div>- {d.why && <div className="dim" style={{ fontSize: '.72rem', lineHeight: 1.4 }}>{d.why}</div>}- </div>- <span className="tag" style={d.status === 'accepted' ? { color: 'var(--acc)' } : { color: 'var(--label-3)' }}>- {d.status === 'accepted' ? t('applied') : t('declined')}- </span>- </div>)}- {(e.notes || []).map((n, i) => <div key={i} className="muted small" style={{ marginTop: 10, lineHeight: 1.5 }}>💬 {n}</div>)}- <div style={{ height: 10 }} />- </>)-- return <>- <h4 className="sec">{t('Coach history')}</h4>- <div className="list">- {log.slice(0, 20).map(e => {- const applied = (e.decisions || []).filter(d => d.status === 'accepted').length- return <div key={e.id} className="item" onClick={() => detail(e)}>- <div className="grow">- <div className="tt">{e.kind === 'create' ? t('Built a plan') : e.kind === 'revert' ? t('Undid the last changes') : t('Reviewed your training')}</div>- <div className="ss">{fmtDate(new Date(e.at).toISOString().slice(0, 10))}- {e.kind === 'review' ? ' · ' + t('{0} applied', applied) : ''}</div>- </div>- <Icon name="chevronRight" className="chev" />- </div>- })}- </div>- </>-}diff --git a/frontend/src/views/CoachProposal.jsx b/frontend/src/views/CoachProposal.jsxdeleted file mode 100644index f84b4df25..000000000--- a/frontend/src/views/CoachProposal.jsx+++ /dev/null@@ -1,246 +0,0 @@-import { useEffect, useMemo, useState } from 'react'-import { useNavigate } from 'react-router-dom'-import { useStore } from '../store/useStore.js'-import { useUI } from '../store/useUI.js'-import { t } from '../lib/i18n.js'-import { fmtDate } from '../lib/format.js'-import { exLine } from '../lib/history.js'-import { loadOfRoutine } from '../lib/muscles.js'-import { DEMO } from '../lib/demo.js'-import { MOBILE } from '../lib/mobile.js'-import {- markStale, applicable, applyChangeSet, applyCreatedPlan, recordDismissal,- changeTitle, changeValues, exName, coachAvailable-} from '../lib/coach.js'-import { useCoachStatus, resolvePending, refinePlan } from '../lib/coach-api.js'-import { confirmSheet } from '../sheets.jsx'-import Icon from '../components/Icon.jsx'-import BodyMap from '../components/BodyMap.jsx'-import { Button, Check, Switch, TextArea } from '../components/ui.jsx'--/* Reviewing what the Coach came back with.- *- * The screen's whole job is to make approving something a decision rather than a formality:- * every change carries the evidence behind it, shows what it would replace, and starts- * accepted only because rejecting three of four is more common than accepting none. Anything- * that can no longer be applied is greyed out with a reason instead of silently vanishing. */--export default function CoachProposal() {- const nav = useNavigate()- const S = useStore(s => s.S)- const user = useStore(s => s.user)- const config = useStore(s => s.config)- const coachMode = useStore(s => s.coachLocal?.mode)- const update = useStore(s => s.update)- const toast = useUI(s => s.toast)- const { pending, loading, refresh } = useCoachStatus(true)-- useEffect(() => { if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE, coachMode })) nav('/home', { replace: true }) }, [config, user])- useEffect(() => { if (!loading && !pending) nav('/coach', { replace: true }) }, [loading, pending])- if (!pending) return null-- return pending.kind === 'create'- ? <CreatedPlan p={pending} S={S} update={update} toast={toast} nav={nav} refresh={refresh} />- : <ChangeSet p={pending} S={S} update={update} toast={toast} nav={nav} />-}--/* ============================ a created plan ============================ */--function CreatedPlan({ p, S, update, toast, nav, refresh }) {- const [schedule, setSchedule] = useState(true)- const [refine, setRefine] = useState('')- const [busy, setBusy] = useState(false)- const b = p.bundle-- const accept = () => {- try {- update(s => { applyCreatedPlan(s, p, { schedule }) })- resolvePending({ accepted: ['plan'] }).catch(() => {})- toast(t('Your plan is live'))- // With the schedule on, the week just moved, so the useful next screen is the one that- // knows what today is and can start it. /plan has no notion of today and no way in.- nav(schedule ? '/home' : '/plan')- } catch (e) { toast(e.message || t('That proposal can’t be read.')) }- }- const discard = () => confirmSheet({- title: t('Discard this plan?'), message: t('Nothing is saved, and you can ask again anytime.'),- confirmText: t('Discard'), danger: true,- onConfirm: () => {- update(s => { recordDismissal(s, p) })- resolvePending({ dismissed: true }).catch(() => {})- nav('/coach')- }- })- const askRefine = async () => {- if (!refine.trim()) return- setBusy(true)- try {- await refinePlan(refine.trim())- setRefine('')- toast(t('The Coach is revising it…'))- nav('/coach')- } catch (e) { toast(e.message || t('Could not ask the Coach')); setBusy(false) }- }-- return <div className="narrow">- <Header title={t('Your plan')} sub={p.iteration > 1 ? t('Revision {0}', p.iteration) : b.name} nav={nav} />-- {!!b.summary && <div className="card"><div className="muted small" style={{ lineHeight: 1.55 }}>{b.summary}</div>- {!!b.basedOn && <div className="dim small" style={{ marginTop: 8 }}>{b.basedOn}</div>}</div>}-- {b.routines.map(r => <div key={r.id} className="card">- <div className="row between" style={{ marginBottom: 4 }}>- <h2 style={{ margin: 0 }}>{r.emoji} {r.name}</h2>- <span className="dim small">{t('{0} exercises', r.ex.length)}</span>- </div>- {!!r.why && <div className="dim small" style={{ marginBottom: 10, lineHeight: 1.5 }}>{r.why}</div>}- {r.ex.map((e, i) => <div key={i} style={{ padding: '8px 0', borderTop: i ? '1px solid var(--sep)' : 'none' }}>- <div className="row between">- <span className="small capitalize" style={{ fontWeight: 500 }}>{exName(e.id)}</span>- <span className="small muted" style={{ whiteSpace: 'nowrap' }}>{exLine(e, S.unit)}</span>- </div>- {!!e.why && <div className="dim" style={{ fontSize: '.72rem', marginTop: 3, lineHeight: 1.4 }}>{e.why}</div>}- </div>)}- <div style={{ marginTop: 10 }}><BodyMap load={loadOfRoutine(r)} body={S.body} /></div>- </div>)}-- <div className="card">- <div className="row between">- <div style={{ minWidth: 0 }}>- <div className="lrow-t">{t('Use this weekly schedule')}</div>- <div className="lrow-s">{t('Replaces your current week. Days this plan leaves empty become rest days.')}</div>- </div>- <Switch checked={schedule} onChange={setSchedule} />- </div>- </div>-- <div className="card">- <h2 style={{ margin: '0 0 6px' }}>{t('Want something different?')}</h2>- <div className="muted small" style={{ marginBottom: 10 }}>{t('Say it in your own words and the Coach will revise the whole plan.')}</div>- <TextArea rows={2} maxLength={1000} value={refine} onChange={e => setRefine(e.target.value)}- placeholder={t('e.g. “swap the squats for split squats, and Mondays are short”')} />- <div style={{ height: 10 }} />- <Button icon="reset" disabled={busy || !refine.trim()} onClick={askRefine}>{t('Ask for a revision')}</Button>- </div>-- <HealthNote />- <Button variant="primary" icon="check" onClick={accept}>{t('Accept plan')}</Button>- <div style={{ height: 8 }} />- <Button danger onClick={discard}>{t('Discard')}</Button>- <div style={{ height: 24 }} />- </div>-}--/* ============================ a change-set ============================ */--function ChangeSet({ p, S, update, toast, nav }) {- // Staleness is decided against the *live* plan every render: someone may have edited it on- // another device while this screen was open.- const marked = useMemo(() => markStale(p, S), [p, S])- const usable = applicable(marked)- const [accepted, setAccepted] = useState(() => new Set(usable.map(c => c.id)))- const toggle = id => setAccepted(s => { const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n })-- const apply = () => {- const ids = [...accepted].filter(id => usable.some(c => c.id === id))- if (!ids.length) { discard(); return }- try {- update(s => { applyChangeSet(s, marked, ids) })- resolvePending({ accepted: ids, rejected: marked.changes.filter(c => !ids.includes(c.id)).map(c => c.id) }).catch(() => {})- toast(t(ids.length === 1 ? '{0} change applied' : '{0} changes applied', ids.length))- // Same rule as an accepted plan: go to the screen that knows about today, but only when- // something actually moved the week. Editing sets and reps leaves the schedule alone.- const movedWeek = ids.some(id => {- const c = usable.find(x => x.id === id)- return !!c && (c.type === 'week' || c.type === 'remove-routine')- })- nav(movedWeek ? '/home' : '/plan')- } catch (e) { toast(e.message || t('Could not apply those changes')) }- }- const discard = () => confirmSheet({- title: t('Dismiss these suggestions?'), message: t('Nothing changes, and the Coach will remember you turned these down.'),- confirmText: t('Dismiss'), danger: true,- onConfirm: () => {- update(s => { recordDismissal(s, marked) })- resolvePending({ dismissed: true }).catch(() => {})- nav('/coach')- }- })-- return <div className="narrow">- <Header title={t('Coach suggestions')} nav={nav}- sub={marked.evidence?.sessions- ? t('Based on your last {0} sessions', marked.evidence.sessions) +- (marked.evidence.from ? ` · ${fmtDate(marked.evidence.from)} – ${fmtDate(marked.evidence.to)}` : '')- : null} />-- {!!marked.summary && <div className="card"><div className="muted small" style={{ lineHeight: 1.55 }}>{marked.summary}</div></div>}-- {marked.planMoved && <div className="card" style={{ borderColor: 'var(--yellow)' }}>- <div className="row" style={{ gap: 9 }}>- <span className="lrow-i" style={{ '--tint': 'var(--yellow)' }}><Icon name="info" /></span>- <div className="small" style={{ lineHeight: 1.45 }}>- {t('Your plan changed since the Coach looked at it. Suggestions that no longer match are greyed out — ask for a fresh review to see them again.')}- </div>- </div>- </div>}-- {marked.changes.map(c => {- const stale = c.status === 'stale'- const vals = changeValues(c)- return <div key={c.id} className="card" style={stale ? { opacity: .55 } : null}>- <div className="row between" style={{ gap: 10, alignItems: 'flex-start' }}>- <div style={{ minWidth: 0, flex: 1 }}>- <div className="row" style={{ gap: 8, marginBottom: 3 }}>- <span className="small capitalize" style={{ fontWeight: 600 }}>{changeTitle(c)}</span>- </div>- {vals && <div className="row" style={{ gap: 7, marginBottom: 5 }}>- <span className="tag">{vals.before}</span>- <Icon name="chevronRight" style={{ fontSize: 12, color: 'var(--label-3)' }} />- <span className="tag acc">{vals.after}</span>- </div>}- <div className="dim small" style={{ lineHeight: 1.45 }}>{c.why}</div>- {stale && <div className="small" style={{ color: 'var(--yellow)', marginTop: 6 }}>- {t('Doesn’t match your plan any more — can’t be applied.')}- </div>}- </div>- {!stale && <Check checked={accepted.has(c.id)} onChange={() => toggle(c.id)} />}- </div>- </div>- })}-- {!!marked.notes?.length && <div className="card">- <h2 style={{ margin: '0 0 8px' }}>{t('Notes from the Coach')}</h2>- {marked.notes.map((n, i) => <div key={i} className="muted small" style={{ lineHeight: 1.5, padding: '6px 0', borderTop: i ? '1px solid var(--sep)' : 'none' }}>{n}</div>)}- <div className="dim small" style={{ marginTop: 8 }}>{t('These change nothing on their own.')}</div>- </div>}-- <HealthNote />- <Button variant="primary" icon="check" onClick={apply}>- {accepted.size ? t(accepted.size === 1 ? 'Apply {0} change' : 'Apply {0} changes', accepted.size) : t('Apply nothing')}- </Button>- <div style={{ height: 8 }} />- <Button danger onClick={discard}>{t('Dismiss all')}</Button>- <div style={{ height: 24 }} />- </div>-}--/* The hub and the intake screen both carry this; the screen where changes are actually accepted- did not, which is the one place it matters most — this is the tap that changes what somebody- will do with their body next week. Deliberately immediately above the accept button rather- than at the top of a scrolling page, so it is on screen at the moment of the decision. */-function HealthNote() {- return <div className="dim small" style={{ lineHeight: 1.5, margin: '4px 0 12px', color: 'var(--yellow)' }}>- {t('The Coach is not a doctor or a physiotherapist. If something hurts, ask a professional.')}- </div>-}--function Header({ title, sub, nav }) {- return <div className="hdr">- <button className="iconbtn" onClick={() => nav('/coach')} aria-label={t('Back')}><Icon name="chevronLeft" /></button>- <div style={{ flex: 1, marginLeft: 10 }}>- <h1>{title}</h1>- {sub && <div className="sub">{sub}</div>}- </div>- </div>-}diff --git a/frontend/src/views/CoachProposal.test.jsx b/frontend/src/views/CoachProposal.test.jsxdeleted file mode 100644index fe02eb094..000000000--- a/frontend/src/views/CoachProposal.test.jsx+++ /dev/null@@ -1,125 +0,0 @@-import React, { act } from 'react'-import { createRoot } from 'react-dom/client'-import { parseHTML } from 'linkedom'-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'-import CoachProposal from './CoachProposal.jsx'-import { applyCreatedPlan } from '../lib/coach.js'-import { effectiveRoutine } from '../lib/history.js'-import { todayISO } from '../lib/format.js'--// Accepting a plan used to end on /plan, a screen with no notion of today and no way to start-// anything. These tests pin the destination, and — more to the point — that the destination can-// actually start today's session through the app's one start path rather than a second copy.-const mocks = vi.hoisted(() => {- const state = { S: null, pending: null, nav: vi.fn(), toast: vi.fn() }- state.storeSnapshot = () => ({- S: state.S,- user: { id: 'u1' },- config: { coach: { enabled: true } },- update: mut => mut(state.S),- })- state.uiSnapshot = () => ({ toast: state.toast })- return state-})--vi.mock('../store/useStore.js', () => {- const useStore = selector => selector(mocks.storeSnapshot())- useStore.getState = mocks.storeSnapshot- return { useStore }-})-vi.mock('../store/useUI.js', () => {- const useUI = selector => selector ? selector(mocks.uiSnapshot()) : mocks.uiSnapshot()- useUI.getState = mocks.uiSnapshot- return { useUI }-})-vi.mock('react-router-dom', () => ({ useNavigate: () => mocks.nav }))-vi.mock('../lib/coach-api.js', () => ({- useCoachStatus: () => ({ pending: mocks.pending, loading: false, refresh: vi.fn() }),- resolvePending: vi.fn(() => Promise.resolve({})),- refinePlan: vi.fn(() => Promise.resolve({})),-}))-vi.mock('../sheets.jsx', () => ({ startFlow: vi.fn(), confirmSheet: vi.fn() }))-vi.mock('../components/BodyMap.jsx', () => ({ default: () => null }))-vi.mock('../lib/api.js', () => ({- api: vi.fn(() => Promise.resolve({})),- IS_APPLE: false, IS_ANDROID: false, BIO: 'biometrics',-}))--let dom, root, container--const TODAY_WD = new Date(todayISO() + 'T12:00:00').getDay()--// A plan that trains every day, so "today" has a session whatever day the suite runs on.-const bundle = (week) => ({- opengym_plan: 1, name: 'Coach plan', summary: 'a plan',- week,- routines: [{ id: 'x1', name: 'Full body A', emoji: '💪', ex: [{ id: '0001', sets: 3, reps: 10, mode: 'reps' }] }],- customEx: [],-})-const everyDay = Object.fromEntries([0, 1, 2, 3, 4, 5, 6].map(d => [d, 'x1']))--const state = () => ({- unit: 'kg', lang: 'en', customEx: [], workouts: [], bodyweight: [], exWeights: {},- dayPlan: {}, routines: [], week: {},- coach: { consent: { agreedAt: '2026-07-01T00:00:00Z', version: 1 }, log: [], snapshots: [] },-})--function installDom() {- const parsed = parseHTML('<!doctype html><html><body><div id="root"></div></body></html>')- dom = parsed.window- globalThis.window = dom- globalThis.document = dom.document- Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })- for (const key of ['HTMLElement', 'Node', 'Element', 'Event', 'Blob']) globalThis[key] = dom[key]- globalThis.IS_REACT_ACT_ENVIRONMENT = true- container = document.getElementById('root')- root = createRoot(container)-}--async function mount(pending) {- mocks.S = state()- mocks.pending = pending- installDom()- await act(async () => { root.render(React.createElement(CoachProposal)) })-}--const byText = re => [...container.querySelectorAll('button')].find(b => re.test(b.textContent || ''))--async function click(el) {- expect(el).toBeTruthy()- await act(async () => { el.dispatchEvent(new dom.Event('click', { bubbles: true })) })-}--beforeEach(() => { vi.clearAllMocks() })-afterEach(async () => {- if (root) { await act(async () => { root.unmount() }); root = null }- container = null; dom = null-})--describe('accepting a created plan hands off to training', () => {- it('lands on the screen that knows about today when it took the schedule', async () => {- await mount({ id: 'p1', kind: 'create', bundle: bundle(everyDay) })- await click(byText(/Accept plan/))- expect(mocks.nav).toHaveBeenCalledWith('/home')- })-- it('leaves the user on the plan screen when the schedule was declined', async () => {- await mount({ id: 'p1', kind: 'create', bundle: bundle(everyDay) })- const sw = container.querySelector('[role="switch"]')- expect(sw.getAttribute('aria-checked')).toBe('true') // on by default- await click(sw)- await click(byText(/Accept plan/))- expect(mocks.nav).toHaveBeenCalledWith('/plan')- })-- it('leaves today startable through the app’s one start path', async () => {- // What the destination can actually do: the same lookup Home does on render resolves a- // routine with exercises, which is exactly what it hands to startFlow.- const s = state()- applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle: bundle(everyDay) }, { schedule: true })- const todays = effectiveRoutine(s, todayISO())- expect(todays).toBeTruthy()- expect(todays.ex.length).toBeGreaterThan(0)- expect(s.week[TODAY_WD]).toBe(todays.id)- })-})