Coach: die Bibliothek im Payload ist gedeckelt (160, ausgewogen, das eigene Training immer dabei)

Bisher gingen alle 1.324 Uebungen mit — 10k+ Tokens pro Job, teuer gegen eine Cloud-API
und in den Kontext eines kleinen lokalen Modells passte es gar nicht. Jetzt: Round-Robin
ueber die Koerperteile in Katalogreihenfolge (deterministisch), Plan- und History-Uebungen
werden immer eingepinnt, damit eine Review benennen kann, worueber sie spricht. Dazu
COACH_JOB_TIMEOUT_MS fuer Boxen, auf denen ein lokales Modell laenger als fuenf Minuten
braucht.
This commit is contained in:
Duarte Santos committed 2026-08-29 20:42:24 +02:00
1 parent d73481e32e
commit aef950cf7c
7 files changed
+95 -694

No files matched your search

-310
View File
@@ -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>
</>
}
-246
View File
@@ -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>
}
-125
View File
@@ -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)
})
})