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
// The questionnaire — the first thing the Coach asks, the moment somebody first opens it.
//
// One question per screen, big targets, as little copy as the question allows. Only goal and
// experience are required; everything after them makes the plan better without gating it,
// and someone who wants to just get training can skip through. The consent disclosure is the
// first screen of this flow rather than a separate card, because "what leaves the server" is
// the first thing to know, not a setting to find later.
//
// `?edit=1` reuses every screen as the profile editor: consent is skipped, answers are
// prefilled, and the last button saves instead of building.
import { useEffect, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { t } from '../lib/i18n.js'
import { DAYN } from '../lib/format.js'
import { EXDB } from '../lib/exercises.js'
import { emptyCoach, coachAvailable, hasConsent, CONSENT_VERSION, CATEGORY_TEXT, appendChat, defaultTrainingDays } from '../lib/coach.js'
import { requestPlan, disclosure, JOB_ERRORS, isDeclined, coachVia } from '../lib/coach-api.js'
import { consentTarget, allowAi } from '../lib/coach-consent.js'
import { DEMO } from '../lib/demo.js'
import { useCoachGate } from '../lib/use-coach-gate.js'
import { MOBILE } from '../lib/mobile.js'
import { activeProfile } from '../lib/equipment.js'
import Icon from '../components/Icon.jsx'
import { Button, TextArea } from '../components/ui.jsx'
import { HourMinuteWheel } from '../components/DurationWheel.jsx'
import '../coach.css'
// Each choice's text returns [title, detail] in the current language, through literal t() calls
// so check-source-strings sees every key, as CATEGORY_TEXT in lib/coach.js does. When the screen
// passed these to t() as variables the checker could not see them, and the eight details had no
// translation in any pack.
const GOALS = [
['strength', () => [t('Get stronger'), t('Heavier lifts, lower reps.')], 'barbell'],
['muscle', () => [t('Build muscle'), t('Volume and progression.')], 'arm'],
['general', () => [t('General fitness'), t('Balanced, sustainable training.')], 'heart'],
['fatloss', () => [t('Lose fat'), t('Keep strength while leaning out.')], 'flame'],
['endurance', () => [t('Endurance'), t('Higher reps, less rest, cardio.')], 'figureRun']
]
const EXPERIENCE = [
['new', () => [t('New to lifting'), t('First months in the gym.')], 'sparkles'],
['returning', () => [t('Coming back after a break'), t('You know the movements; the numbers need rebuilding.')], 'reset'],
['regular', () => [t('Training regularly'), t('Consistent for a while now.')], 'trophy']
]
// Equipment options come from the library's own taxonomy, most common first, so every choice
// on screen has exercises behind it.
const EQUIPMENT = (() => {
const count = {}
EXDB.forEach(e => { if (e.eq) count[e.eq] = (count[e.eq] || 0) + 1 })
return Object.keys(count).sort((a, b) => count[b] - count[a]).slice(0, 14)
})()
const QUICK_MIN = [30, 45, 60, 90]
const sameDays = (a, b) => a.length === b.length && b.every(d => a.includes(d))
const toHHMM = min => Math.floor(min / 60) + ':' + String(min % 60).padStart(2, '0')
export default function CoachIntake() {
const nav = useNavigate()
const [params] = useSearchParams()
const editing = params.get('edit') === '1'
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 [needConsent] = useState(() => !editing && !hasConsent(S))
// An athlete who already answered the intake and only lacks the CURRENT consent (the wording
// changed and CONSENT_VERSION moved) reads the new terms and goes back to the Coach. Without
// this the redirect from the chat replayed all seven questions and ended in a new plan request.
const [reconsentOnly] = useState(() => !editing && !hasConsent(S) && !!S.coach?.profile)
const STEPS = reconsentOnly ? ['consent'] : [...(needConsent ? ['consent'] : []), 'goal', 'experience', 'days', 'length', 'equipment', 'limits', 'extras']
const [step, setStep] = useState(0)
const [busy, setBusy] = useState(false)
const [p, setP] = useState(() => ({
goal: null, experience: null, daysPerWeek: 3, preferredDays: defaultTrainingDays(3),
// A home gym already set up under Settings → Equipment is the best first guess here.
sessionMin: 60, equipment: (activeProfile(S)?.equipment || []).filter(e => EQUIPMENT.includes(e)), limitations: '', likes: '', dislikes: '', notes: '',
...(S.coach?.profile || {})
}))
const set = patch => setP(v => ({ ...v, ...patch }))
const gate = useCoachGate()
useEffect(() => { if (gate.known && !gate.ok) nav('/home', { replace: true }) }, [gate.known, gate.ok])
if (!gate.ok) return null
const key = STEPS[step]
const last = step === STEPS.length - 1
const canNext = key === 'goal' ? !!p.goal : key === 'experience' ? !!p.experience : key === 'length' ? p.sessionMin >= 10 : true
const optional = ['equipment', 'limits', 'extras'].includes(key)
const next = () => (last ? finish() : setStep(step + 1))
const back = () => (step ? setStep(step - 1) : nav(editing ? '/coach' : '/plan'))
const agree = info => {
// This screen just named the provider and listed what goes there, which is the question the
// data-sharing sheet asks before the first request (lib/coach-api.js ensureAiConsent). The
// yes counts for that provider and host too, so a first-timer is asked once, not twice.
// Only when the disclosure arrived: a screen that could not say where to is not a yes to it.
const target = !DEMO && consentTarget(info, coachVia())
if (target && !target.local) allowAi(target).catch(() => {})
update(s => { s.coach = { ...(s.coach || emptyCoach()), consent: { agreedAt: new Date().toISOString(), version: CONSENT_VERSION } } })
if (reconsentOnly) nav('/coach', { replace: true })
else setStep(step + 1)
}
const finish = async () => {
// `??`, not `||`: only a missing answer takes the default. Nought is an answer, and the clamp
// turns it into one day like every other count below the floor.
const profile = { ...p, daysPerWeek: Math.min(7, Math.max(1, p.daysPerWeek ?? 3)) }
update(s => {
const c = (s.coach = s.coach || emptyCoach())
c.profile = profile
// The conversation opens with the answers — rendered from the profile, so an edit later
// is reflected rather than duplicated. One intake line whoever is writing it: a first-timer
// whose plan request failed presses the button again, and must not open the thread with
// the questionnaire twice.
if (!(c.chat || []).some(m => m.kind === 'intake')) appendChat(s, { role: 'user', kind: 'intake' })
})
if (editing) { toast(t('Saved')); nav('/coach'); return }
setBusy(true)
try {
await requestPlan(profile)
nav('/coach', { replace: true })
} catch (e) {
// The server's refusal is English with its class beside it; the class picks the line.
// "Not now" on the data-sharing question sends nothing and says nothing; the answers are saved.
if (!isDeclined(e)) toast(JOB_ERRORS[e.data?.code] || e.message || t('Could not ask the Coach'))
setBusy(false)
}
}
// The weekdays start as the usual spread for the count and follow it until somebody picks their
// own. Mon/Wed/Fri left standing under a count of four saved a profile asking for four days
// that preferred three nobody had chosen (#620). Fewer picked days than the count stay a valid
// answer: the Coach fills the rest.
const setDays = n => {
const untouched = sameDays(p.preferredDays, defaultTrainingDays(p.daysPerWeek))
set({ daysPerWeek: n, preferredDays: untouched ? defaultTrainingDays(n) : p.preferredDays })
}
const toggleDay = d => set({
preferredDays: p.preferredDays.includes(d) ? p.preferredDays.filter(x => x !== d) : [...p.preferredDays, d].sort()
})
const toggleEq = e => set({
equipment: p.equipment.includes(e) ? p.equipment.filter(x => x !== e) : [...p.equipment, e]
})
const dots = STEPS.filter(s => s !== 'consent')
const dotIndex = dots.indexOf(key)
return <div className="narrow ob">
<div className="ob-top">
<button className="iconbtn" data-back={step ? '' : editing ? '/coach' : '/plan'} onClick={back} aria-label={t('Back')}><Icon name="chevronLeft" /></button>
{key !== 'consent' && <div className="ob-dots">
{dots.map((s, i) => <span key={s} className={'ob-dot' + (i === dotIndex ? ' on' : i < dotIndex ? ' done' : '')} />)}
</div>}
{optional && !last ? <button className="ob-skip" onClick={next}>{t('Skip')}</button> : <span style={{ width: 36 }} />}
</div>
<div className="ob-body">
{key === 'consent' && <Consent onAgree={agree} onDecline={() => nav('/plan')} />}
{key === 'goal' && <>
<div className="ob-eyebrow">{t('Your goal')}</div>
<h1 className="ob-h">{t('What are you training for?')}</h1>
<p className="ob-p">{t('The Coach builds the whole plan around this.')}</p>
<div className="ob-choices">
{GOALS.map(([v, text, icon]) => { const [title, sub] = text(); return <Choice key={v} on={p.goal === v} icon={icon} title={title} sub={sub} onClick={() => set({ goal: v })} /> })}
</div>
</>}
{key === 'experience' && <>
<div className="ob-eyebrow">{t('Experience')}</div>
<h1 className="ob-h">{t('Where are you starting from?')}</h1>
<p className="ob-p">{t('Sets the pace of progression, and how much the Coach assumes you know.')}</p>
<div className="ob-choices">
{EXPERIENCE.map(([v, text, icon]) => { const [title, sub] = text(); return <Choice key={v} on={p.experience === v} icon={icon} title={title} sub={sub} onClick={() => set({ experience: v })} /> })}
</div>
</>}
{key === 'days' && <>
<div className="ob-eyebrow">{t('Schedule')}</div>
<h1 className="ob-h">{t('How many days a week?')}</h1>
<p className="ob-p">{t('Pick what you will actually keep, not the best week you can imagine.')}</p>
{/* Two questions, two groups: how many (a count), then which (weekdays, optional). Each
has its own label, so the row of numbers never reads as dates. */}
<div className="ob-group" role="group" aria-labelledby="ob-days-l">
<div className="ob-sub ob-sub-first" id="ob-days-l">{t('Days per week')}</div>
<div className="ob-days">
{[1, 2, 3, 4, 5, 6, 7].map(n => <button key={n} className={'ob-day' + (p.daysPerWeek === n ? ' on' : '')} aria-pressed={p.daysPerWeek === n} onClick={() => setDays(n)}>{n}</button>)}
</div>
</div>
<div className="ob-group" role="group" aria-labelledby="ob-week-l">
<div className="ob-sub ob-sub-first" id="ob-week-l">{t('Which days suit you? (optional)')}</div>
<div className="ob-week">
{[1, 2, 3, 4, 5, 6, 0].map(d => <button key={d} className={'ob-wd' + (p.preferredDays.includes(d) ? ' on' : '')} aria-pressed={p.preferredDays.includes(d)} onClick={() => toggleDay(d)}>{t(DAYN[d]).slice(0, 2)}</button>)}
</div>
</div>
</>}
{key === 'length' && <>
<div className="ob-eyebrow">{t('Session length')}</div>
<h1 className="ob-h">{t('How long is a session?')}</h1>
<p className="ob-p">{t('The Coach fits the volume to the time you actually have, including rest between sets.')}</p>
{/* A duration, not a clock time: the app's own wheels (hours, minutes in fives), like every
other time picker, never the native time input, which insists on AM/PM. */}
<div className="dw-read" aria-hidden="true">{toHHMM(p.sessionMin || 60)}</div>
<HourMinuteWheel value={p.sessionMin || 60} onChange={m => set({ sessionMin: m })} min={10} />
<div className="ob-quick">
{QUICK_MIN.map(m => <button key={m} className={'chip' + (p.sessionMin === m ? ' on' : '')} onClick={() => set({ sessionMin: m })}>{m} {t('min')}</button>)}
</div>
</>}
{key === 'equipment' && <>
<div className="ob-eyebrow">{t('Equipment')}</div>
<h1 className="ob-h">{t('What can you train with?')}</h1>
<p className="ob-p">{t('Pick everything you have access to. Leave it empty and the Coach will use the whole library.')}</p>
<div className="ob-chips">
{EQUIPMENT.map(e => <button key={e} className={'chip' + (p.equipment.includes(e) ? ' on' : '')} onClick={() => toggleEq(e)}>{t(e)}</button>)}
</div>
</>}
{key === 'limits' && <>
<div className="ob-eyebrow">{t('Limits')}</div>
<h1 className="ob-h">{t('Anything to work around?')}</h1>
<p className="ob-p">{t('Injuries, joints that complain, movements you cannot do, or practical limits like training at 6am in a flat.')}</p>
<div className="ob-field">
<TextArea rows={4} maxLength={600} value={p.limitations} onChange={e => set({ limitations: e.target.value })}
placeholder={t('e.g. “dodgy left shoulder, no barbell overhead press”')} />
</div>
<div className="ob-note warn">{t('If something actually hurts, see a professional. The Coach will program conservatively, but it can’t diagnose anything.')}</div>
</>}
{key === 'extras' && <>
<div className="ob-eyebrow">{t('Almost there')}</div>
<h1 className="ob-h">{t('Anything else?')}</h1>
<p className="ob-p">{t('All optional. The more the Coach knows, the less it guesses.')}</p>
<div className="ob-sub" style={{ marginTop: 0 }}>{t('Exercises you love')}</div>
<div className="ob-field"><TextArea rows={2} maxLength={300} value={p.likes} onChange={e => set({ likes: e.target.value })} placeholder={t('e.g. “deadlifts, anything with a kettlebell”')} /></div>
<div className="ob-sub" style={{ marginTop: 4 }}>{t('Exercises you would rather not')}</div>
<div className="ob-field"><TextArea rows={2} maxLength={300} value={p.dislikes} onChange={e => set({ dislikes: e.target.value })} placeholder={t('e.g. “I hate lunges”')} /></div>
<div className="ob-sub" style={{ marginTop: 4 }}>{t('Anything you want the Coach to know')}</div>
<div className="ob-field"><TextArea rows={3} maxLength={600} value={p.notes} onChange={e => set({ notes: e.target.value })} placeholder={t('e.g. “I want visible arms progress by spring”')} /></div>
</>}
</div>
{key !== 'consent' && <div className="ob-foot">
<Button variant="primary" style={{ flex: 1 }} disabled={!canNext || busy} icon={last ? 'sparkles' : undefined} onClick={next}>
{last ? (editing ? t('Save') : t('Build my plan')) : t('Continue')}
</Button>
</div>}
{(key === 'goal' || key === 'experience') && !canNext && <div className="ob-hint">{t('Pick one to continue.')}</div>}
</div>
}
function Choice({ on, icon, title, sub, onClick }) {
return <button className={'ob-choice' + (on ? ' on' : '')} onClick={onClick}>
<Icon name={icon} />
<span className="ob-choice-t">{title}{sub && <span className="ob-choice-s">{sub}</span>}</span>
<Icon name="check" className="ob-k" />
</button>
}
/* The disclosure: what leaves, where to, who pays. Rendered from the same category list the
payload is built from, so the promise on screen cannot drift from what actually goes. */
function Consent({ onAgree, onDecline }) {
const config = useStore(s => s.config)
const [info, setInfo] = useState(null)
useEffect(() => { disclosure().then(setInfo).catch(() => {}) }, [])
const who = info?.payer === 'you'
? t('Sent straight to {0} with your own API key. You pay for every request.', info.host || info.providerLabel)
: t('Sent to {0}, running on this server under the instance owner’s account.', (info?.provider === 'compatible' && info.host) || info?.providerLabel || config?.coach?.providerLabel || t('the configured AI provider'))
return <>
<div className="ob-eyebrow">{t('Before we start')}</div>
<h1 className="ob-h">{t('Meet the Coach')}</h1>
<p className="ob-p">{t('It designs your plan from a few answers and adjusts it from what you actually log. It never changes anything without your say-so, and you can undo every change.')}</p>
<div className="ob-sub" style={{ marginTop: 0 }}>{t('What it reads')}</div>
<div className="ob-consent">
{(info?.categories || Object.keys(CATEGORY_TEXT)).map(k => {
const [title, sub] = CATEGORY_TEXT[k]?.() || [k, '']
return <div key={k} className="ob-consent-row"><Icon name="check" /><div><b>{title}</b><span>{sub}</span></div></div>
})}
</div>
<div className="ob-fine">
<div>{who}</div>
<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 style={{ color: 'var(--yellow)' }}>{t('The Coach is not a doctor or a physiotherapist. If something hurts, ask a professional.')}</div>
</div>
<div className="ob-foot" style={{ flexDirection: 'column' }}>
<Button variant="primary" onClick={() => onAgree(info)}>{t('I understand, let’s go')}</Button>
<Button onClick={onDecline}>{t('Not now')}</Button>
</div>
</>
}