Skip to content

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.

Coach: the screens, and the four things they were supposed to say

Alexab1adcdd4f51
diff --git a/api/coach/routes.js b/api/coach/routes.js
index d4329a0e5..2aaa162be 100644
--- a/api/coach/routes.js
+++ b/api/coach/routes.js
@@ -120,6 +120,18 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) {
runtime: { ok: !!check.ok, version: check.version || null, error: check.error || null },
authMode: cfg.authMode,
boundUid: cfg.boundUid || null,
+ /* Whether a credential is filed, and whose — never the credential. `unreadable` is its
+ own state rather than "not connected" because it has a specific cause and a specific
+ fix: ./data was restored without its `secret`, so the blob is intact and undecryptable,
+ and connecting again is the way out. */
+ auth: (() => {
+ if (!cfgStore.providerMeta(cfg).oauthEnv && !cfgStore.providerMeta(cfg).apiKeyEnv) {
+ return { state: 'not-required' };
+ }
+ if (!cfg.auth || !cfg.auth.data) return { state: 'none' };
+ if (!cfgStore.decrypt(cfg.auth.data)) return { state: 'unreadable' };
+ return { state: 'connected', type: cfg.auth.type || null, account: cfg.auth.account || null };
+ })(),
// Whether the privilege drop can actually be performed. Surfaced because the control
// now fails closed: if this reads false, no job runs, and the admin needs to know that
// from the card rather than from a user reporting that nothing happens.
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index e7c8c5221..16e997b3b 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -24,6 +24,9 @@ import History from './views/History.jsx'
import Library from './views/Library.jsx'
import Settings from './views/Settings.jsx'
import Admin from './views/Admin.jsx'
+import Coach from './views/Coach.jsx'
+import CoachIntake from './views/CoachIntake.jsx'
+import CoachProposal from './views/CoachProposal.jsx'
bindUI(useUI) // lets the shared controls open sheets without importing the store at module scope
@@ -75,6 +78,12 @@ function Shell() {
<Route path="/history" element={<History />} />
<Route path="/library" element={<Library />} />
<Route path="/settings" element={<Settings />} />
+ {/* The Coach screens gate themselves on the instance config; the routes exist
+ unconditionally so a deep link from a notification lands somewhere sane
+ rather than on the catch-all. */}
+ <Route path="/coach" element={<Coach />} />
+ <Route path="/coach/intake" element={<CoachIntake />} />
+ <Route path="/coach/proposal" element={<CoachProposal />} />
<Route path="/admin" element={user?.admin ? <Admin /> : <Navigate to="/home" replace />} />
<Route path="*" element={<Navigate to="/home" replace />} />
</Routes>
diff --git a/frontend/src/lib/coach-api.js b/frontend/src/lib/coach-api.js
new file mode 100644
index 000000000..6fa3d5498
--- /dev/null
+++ b/frontend/src/lib/coach-api.js
@@ -0,0 +1,97 @@
+// 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 { useStore } from '../store/useStore.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
+
+export const coachStatus = async () => DEMO ? (await demo()).demoStatus() : api('/api/coach/status')
+export const requestReview = async note => DEMO ? (await demo()).demoReview(S()) : api('/api/coach/review', { method: 'POST', body: JSON.stringify({ note: note || '' }) })
+export const requestPlan = async intake => DEMO ? (await demo()).demoPlan(S(), intake) : api('/api/coach/plan', { method: 'POST', body: JSON.stringify({ intake }) })
+export const refinePlan = async text => DEMO ? (await demo()).demoRefine(S()) : api('/api/coach/plan', { method: 'POST', body: JSON.stringify({ refine: text }) })
+export const resolvePending = async body => DEMO ? (await demo()).demoResolve() : api('/api/coach/pending/resolve', { method: 'POST', body: JSON.stringify(body) })
+export const forgetCoach = async () => DEMO ? (await demo()).demoResolve() : api('/api/coach/forget', { method: 'POST', body: '{}' })
+export const disclosure = async () => DEMO ? (await demo()).demoDisclosure() : 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 }
+ : 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 refresh = useCallback(async () => {
+ try {
+ const s = await coachStatus()
+ setState({ ...s, loading: false })
+ 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
+ timer.current = setTimeout(tick, s?.job ? POLL_MS : IDLE_MS)
+ }
+ tick()
+ return () => { stopped = true; 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.',
+ internal: 'Something went wrong on the server.'
+}
diff --git a/frontend/src/lib/coach-demo.js b/frontend/src/lib/coach-demo.js
new file mode 100644
index 000000000..d8fbf4cd9
--- /dev/null
+++ b/frontend/src/lib/coach-demo.js
@@ -0,0 +1,132 @@
+// 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 } from './history.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: []
+ }
+ }
+}
+
+/* ---------------- 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 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
+})
diff --git a/frontend/src/views/Admin.jsx b/frontend/src/views/Admin.jsx
index c981c732b..63ca1da30 100644
--- a/frontend/src/views/Admin.jsx
+++ b/frontend/src/views/Admin.jsx
@@ -8,6 +8,7 @@ import { workoutVolume, setsDone } from '../lib/history.js'
import { confirmSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
+import AdminCoach from './AdminCoach.jsx'
// Admin-only operator dashboard (owner passkey + admin flag; guarded again server-side).
// Deliberately English-only — it isn't part of the translated end-user surface, so it stays
@@ -132,6 +133,10 @@ export default function Admin() {
</div>)}
</div>}
+ {/* Renders nothing at all unless the instance offers the Coach, so an admin page on a
+ box that never enabled it is byte-for-byte the page it was before. */}
+ <AdminCoach />
+
<InvitesCard invites={invites} reload={loadInvites} />
<h4 className="sec">Users</h4>
diff --git a/frontend/src/views/AdminCoach.jsx b/frontend/src/views/AdminCoach.jsx
new file mode 100644
index 000000000..0aae6abab
--- /dev/null
+++ b/frontend/src/views/AdminCoach.jsx
@@ -0,0 +1,244 @@
+import { useEffect, useState } from 'react'
+import { useUI } from '../store/useUI.js'
+import { api } from '../lib/api.js'
+import Icon from '../components/Icon.jsx'
+import { Button, Switch, TextField } from '../components/ui.jsx'
+
+/* The operator's side of the Coach: is it on, can it reach a model, and what has it been
+ doing. Like the rest of the admin dashboard this is deliberately English-only — it isn't
+ part of the translated end-user surface.
+ *
+ * What it never shows: anybody's intake answers, payloads or proposals. An admin can enable
+ * the feature and see that jobs ran; they cannot read what their users asked it. */
+
+const rel = ts => {
+ if (!ts) return 'never'
+ const s = Math.max(0, (Date.now() - new Date(ts).getTime()) / 1000)
+ if (s < 60) return 'just now'
+ if (s < 3600) return Math.floor(s / 60) + 'm ago'
+ if (s < 86400) return Math.floor(s / 3600) + 'h ago'
+ return Math.floor(s / 86400) + 'd ago'
+}
+
+export default function AdminCoach() {
+ const toast = useUI(s => s.toast)
+ const openSheet = useUI(s => s.openSheet)
+ const [d, setD] = useState(null)
+ const [busy, setBusy] = useState(false)
+
+ const load = () => api('/api/admin/coach').then(setD).catch(e => toast(e.message || 'Failed to load'))
+ useEffect(() => { load() }, [])
+
+ const patch = async body => {
+ setBusy(true)
+ try { await api('/api/admin/coach/config', { method: 'POST', body: JSON.stringify(body) }); await load() }
+ catch (e) { toast(e.message) }
+ setBusy(false)
+ }
+ const test = async () => {
+ setBusy(true)
+ try {
+ const r = await api('/api/admin/coach/test', { method: 'POST', body: '{}' })
+ toast(r.ok ? 'Coach test passed ✅' : 'Test failed: ' + (r.error || 'unknown'))
+ await load()
+ } catch (e) { toast(e.message) }
+ setBusy(false)
+ }
+ const disconnect = async () => {
+ setBusy(true)
+ try { await api('/api/admin/coach/disconnect', { method: 'POST', body: '{}' }); toast('Disconnected'); await load() }
+ catch (e) { toast(e.message) }
+ setBusy(false)
+ }
+
+ if (!d) return <div className="card"><div className="muted small">Loading Coach status…</div></div>
+
+ if (d.disabledByEnv) return <div className="card">
+ <h2 style={{ margin: '0 0 6px' }}>AI Coach</h2>
+ <div className="muted small">Force-disabled by <code>COACH_DISABLED</code> in the environment. Remove it to configure the Coach here.</div>
+ </div>
+
+ const meta = d.providers.find(p => p.id === d.provider) || {}
+ const authed = d.auth?.state === 'connected' || d.auth?.state === 'not-required'
+ const live = d.enabled && d.runtime.ok && authed
+
+ return <div className="card" style={{ borderColor: live ? 'var(--acc)' : undefined }}>
+ <div className="row between" style={{ marginBottom: 8 }}>
+ <h2 style={{ margin: 0 }}>AI Coach</h2>
+ <Switch checked={!!d.enabled} disabled={busy} onChange={v => patch({ enabled: v })} />
+ </div>
+
+ {!d.enabled && <div className="muted small">Off. Users see no Coach anywhere in the app.</div>}
+
+ {d.enabled && <>
+ <div className="tiles" style={{ textAlign: 'left', marginBottom: 10 }}>
+ <div className="tile"><div className="l">Runtime</div>
+ <div className="v" style={{ fontSize: '.9rem', color: d.runtime.ok ? 'var(--green)' : 'var(--red)' }}>{d.runtime.ok ? 'ready' : 'missing'}</div></div>
+ <div className="tile"><div className="l">Credential</div>
+ <div className="v" style={{ fontSize: '.9rem', color: authed ? 'var(--green)' : 'var(--red)' }}>{authLabel(d.auth)}</div></div>
+ <div className="tile"><div className="l">Jobs today</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.jobsToday}</div></div>
+ <div className="tile"><div className="l">Last run</div><div className="v" style={{ fontSize: '.85rem' }}>{rel(d.lastSuccess?.at)}</div></div>
+ </div>
+
+ {d.runtime.version && <div className="dim small" style={{ marginBottom: 8 }}>{meta.runtime || meta.label} · {d.runtime.version}</div>}
+ {!d.runtime.ok && d.runtime.error && <div className="small" style={{ color: 'var(--red)', marginBottom: 8 }}>{d.runtime.error}</div>}
+
+ {/* The privilege drop, stated plainly. It fails closed, so when this reads no, nothing
+ runs at all — and the admin needs to learn that here rather than from a user
+ reporting that the Coach does nothing. The reason is the server's own words. */}
+ {d.unprivileged && !d.unprivileged.ok &&
+ <div className="small" style={{ color: 'var(--red)', marginBottom: 8, lineHeight: 1.5 }}>
+ Jobs are disabled: {d.unprivileged.why}. No job will run until this is fixed.
+ </div>}
+ {d.unprivileged?.ok &&
+ <div className="dim small" style={{ marginBottom: 8 }}>
+ Jobs run unprivileged: {d.unprivileged.dropped ? 'yes' : 'no — this host has no separate user to drop to'}
+ </div>}
+
+ {/* Whose account is being spent, in the admin's own view. The same fact the user sees on
+ their Coach screen, because "the admin card and the user screen must both name the
+ account" is only true if neither is inferring it from settings. */}
+ <div className="dim small" style={{ marginBottom: 8 }}>
+ {d.authMode === 'profile'
+ ? 'Each profile signs in with their own account.'
+ : d.boundUid
+ ? 'One shared account, already in use by a profile. Any other profile is refused.'
+ : 'One shared account. The first profile to use it binds it; every other profile is then refused.'}
+ </div>
+
+ {/* provider */}
+ <h4 className="sec" style={{ marginTop: 4 }}>Provider</h4>
+ <div className="row" style={{ flexWrap: 'wrap', gap: 7, marginBottom: 10 }}>
+ {d.providers.map(p => <button key={p.id} className={'chip' + (p.id === d.provider ? ' on' : '')}
+ disabled={busy} onClick={() => patch({ provider: p.id })}>{p.label}</button>)}
+ </div>
+
+ {/* credential */}
+ {(meta.setupToken || meta.apiKey) && <>
+ <h4 className="sec">Credential</h4>
+ {d.auth?.state === 'connected' ? <>
+ <div className="small muted" style={{ marginBottom: 8 }}>
+ Connected{d.auth.account ? ' as ' + d.auth.account : ''} via {credentialLabel(d.auth.type)} · {rel(d.auth.connectedAt)}
+ </div>
+ <div className="row" style={{ gap: 8 }}>
+ <Button size="sm" icon="check" disabled={busy} onClick={test}>Test the Coach</Button>
+ <Button size="sm" danger disabled={busy} onClick={disconnect}>Disconnect</Button>
+ </div>
+ </> : <>
+ {d.auth?.state === 'expired' && <div className="small" style={{ color: 'var(--red)', marginBottom: 8 }}>The stored credential expired — connect again.</div>}
+ {d.auth?.state === 'replace-required' && <div className="small" style={{ color: 'var(--red)', marginBottom: 8 }}>
+ The old Claude credential is no longer used. Add a Claude Code setup token instead.
+ </div>}
+ {d.auth?.state === 'unreadable' && <div className="small" style={{ color: 'var(--red)', marginBottom: 8 }}>
+ The stored credential can't be decrypted — this usually means ./data was restored without its <code>secret</code> file. Connect again.
+ </div>}
+ <div className="row" style={{ gap: 8, flexWrap: 'wrap' }}>
+ {meta.setupToken && <Button size="sm" variant="primary" icon="key" disabled={busy}
+ onClick={() => openSheet(close => <SetupTokenSheet close={close} onDone={load} label={meta.label} />)}>Add CLI token</Button>}
+ {meta.apiKey && !meta.setupToken && <Button size="sm" icon="lock" disabled={busy}
+ onClick={() => openSheet(close => <ApiKeySheet close={close} onDone={load} label={meta.label} />)}>Use an API key</Button>}
+ </div>
+ </>}
+ </>}
+
+ {/* limits */}
+ <h4 className="sec">Limits</h4>
+ <div className="row" style={{ gap: 10, flexWrap: 'wrap', marginBottom: 4 }}>
+ <label className="small muted">Per user / day
+ <input className="num" type="number" min="0" max="200" defaultValue={d.caps.perProfileDaily} style={{ width: 70, marginLeft: 8 }}
+ onBlur={e => patch({ caps: { ...d.caps, perProfileDaily: +e.target.value } })} /></label>
+ <label className="small muted">Whole instance / day
+ <input className="num" type="number" min="0" max="5000" defaultValue={d.caps.instanceDaily} style={{ width: 70, marginLeft: 8 }}
+ onBlur={e => patch({ caps: { ...d.caps, instanceDaily: +e.target.value } })} /></label>
+ </div>
+ <div className="dim small" style={{ marginBottom: 10 }}>0 = no limit. Every job is one session on your provider account.</div>
+
+ <h4 className="sec">Model</h4>
+ <TextField defaultValue={d.model || ''} placeholder="(the provider default)"
+ onBlur={e => e.target.value !== (d.model || '') && patch({ model: e.target.value })} />
+
+ {d.lastError && <>
+ <h4 className="sec">Last failure</h4>
+ <div className="small" style={{ color: 'var(--red)' }}>{d.lastError.errorClass}{d.lastError.detail ? ' — ' + d.lastError.detail : ''}</div>
+ <div className="dim" style={{ fontSize: '.72rem' }}>{rel(d.lastError.at)}</div>
+ </>}
+
+ {!!d.recent?.length && <>
+ <h4 className="sec">Recent jobs</h4>
+ {d.recent.slice(0, 8).map((e, i) => <div key={i} className="row between" style={{ padding: '5px 2px', borderBottom: '1px solid var(--sep)' }}>
+ <span className="small">{e.kind}{e.trigger === 'scheduled' ? ' · scheduled' : ''}</span>
+ <span className="dim" style={{ fontSize: '.72rem' }}>
+ <span style={{ color: e.outcome === 'failed' ? 'var(--red)' : e.outcome === 'ready' ? 'var(--acc)' : undefined }}>{e.outcome}</span>
+ {e.ms ? ' · ' + Math.round(e.ms / 1000) + 's' : ''} · {rel(e.at)}
+ </span>
+ </div>)}
+ </>}
+ </>}
+ </div>
+}
+
+const authLabel = a => ({
+ connected: 'connected', 'not-required': 'n/a', disconnected: 'needed', expired: 'expired', unreadable: 'unreadable', 'replace-required': 'replace'
+}[a?.state] || '—')
+
+const credentialLabel = type => ({
+ 'cli-token': 'Claude Code setup token', 'chatgpt-cli': 'ChatGPT CLI login', oauth: 'legacy token', apikey: 'API key'
+}[type] || 'credential')
+
+/* ------------------------------- setup token -------------------------------- */
+
+function SetupTokenSheet({ close, onDone, label }) {
+ const toast = useUI(s => s.toast)
+ const [token, setToken] = useState('')
+ // Which account this token belongs to. Optional, and stored as a plain label — it is what the
+ // admin card and the user's Coach screen both show when they name whose account is spent.
+ const [account, setAccount] = useState('')
+ const [busy, setBusy] = useState(false)
+
+ const save = async () => {
+ setBusy(true)
+ try {
+ const r = await api('/api/admin/coach/connect', { method: 'POST', body: JSON.stringify({ type: 'cli-token', token: token.trim(), account: account.trim() }) })
+ setToken('')
+ toast(r.test?.ok ? 'Connected ✅' : 'Saved, but the test failed: ' + (r.test?.error || ''))
+ close(); onDone()
+ } catch (e) { toast(e.message); setBusy(false) }
+ }
+
+ return <>
+ <h3>Connect {label}</h3>
+ <div className="muted small" style={{ lineHeight: 1.5, marginBottom: 12 }}>
+ On a trusted computer where you use Claude Code, run <code>claude setup-token</code>, complete its normal browser sign-in, then paste the token it prints here. This app never opens or handles Claude's authorization flow.
+ </div>
+ <TextField value={token} autoFocus type="password" placeholder="paste setup token" onChange={e => setToken(e.target.value)} />
+ <div style={{ height: 8 }} />
+ <TextField value={account} placeholder="whose account is this? (e.g. [email protected])" onChange={e => setAccount(e.target.value)} />
+ <div style={{ height: 12 }} />
+ <Button variant="primary" disabled={busy || !token.trim()} onClick={save}>Save and test</Button>
+ <div style={{ height: 8 }} />
+ </>
+}
+
+function ApiKeySheet({ close, onDone, label }) {
+ const toast = useUI(s => s.toast)
+ const [key, setKey] = useState('')
+ const [busy, setBusy] = useState(false)
+ const save = async () => {
+ setBusy(true)
+ try {
+ const r = await api('/api/admin/coach/connect', { method: 'POST', body: JSON.stringify({ type: 'apikey', token: key.trim() }) })
+ toast(r.test?.ok ? 'Key saved ✅' : 'Saved, but the test failed: ' + (r.test?.error || ''))
+ close(); onDone()
+ } catch (e) { toast(e.message); setBusy(false) }
+ }
+ return <>
+ <h3>{label} API key</h3>
+ <div className="muted small" style={{ lineHeight: 1.5, marginBottom: 12 }}>
+ Stored encrypted on this server and passed to the provider runtime only while a job runs. It is never shown again and never leaves the server.
+ </div>
+ <TextField value={key} autoFocus type="password" placeholder="sk-…" onChange={e => setKey(e.target.value)} />
+ <div style={{ height: 12 }} />
+ <Button variant="primary" disabled={busy || !key.trim()} onClick={save}>Save key</Button>
+ <div style={{ height: 8 }} />
+ </>
+}
diff --git a/frontend/src/views/Coach.jsx b/frontend/src/views/Coach.jsx
new file mode 100644
index 000000000..d9340f4ff
--- /dev/null
+++ b/frontend/src/views/Coach.jsx
@@ -0,0 +1,314 @@
+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,
+ 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']
+
+// Rendered from the same list the server builds payloads from (GET /api/coach/disclosure),
+// so the promise on screen cannot drift from what actually leaves the box.
+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 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 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 })) nav('/home', { replace: true }) }, [config, user])
+ if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE })) 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 }}>
+ {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 }}>
+ {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/CoachIntake.jsx b/frontend/src/views/CoachIntake.jsx
new file mode 100644
index 000000000..6d300cf5a
--- /dev/null
+++ b/frontend/src/views/CoachIntake.jsx
@@ -0,0 +1,186 @@
+import { 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 } from '../lib/coach.js'
+import { requestPlan } from '../lib/coach-api.js'
+import { DEMO } from '../lib/demo.js'
+import { MOBILE } from '../lib/mobile.js'
+import Icon from '../components/Icon.jsx'
+import { Button, TextArea, Segmented } from '../components/ui.jsx'
+
+/* The intake: one topic per screen, because a single form with eleven fields is a form people
+ abandon. Only the first two questions are required — everything after them improves the
+ plan without gating it, and someone who wants to just get training should be able to. */
+
+const GOALS = [
+ ['strength', 'Get stronger'],
+ ['muscle', 'Build muscle'],
+ ['general', 'General fitness'],
+ ['fatloss', 'Lose fat'],
+ ['endurance', 'Endurance']
+]
+const EXPERIENCE = [
+ ['new', 'New to lifting'],
+ ['returning', 'Coming back after a break'],
+ ['regular', 'Training regularly']
+]
+const SESSION_MIN = [30, 45, 60, 75, 90]
+
+// 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 STEPS = ['goal', 'days', 'length', 'equipment', 'limits', 'extras']
+
+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 update = useStore(s => s.update)
+ const toast = useUI(s => s.toast)
+ const [step, setStep] = useState(0)
+ const [busy, setBusy] = useState(false)
+ const [p, setP] = useState(() => ({
+ goal: null, experience: null, daysPerWeek: 3, preferredDays: [1, 3, 5],
+ sessionMin: 45, equipment: [], limitations: '', likes: '', dislikes: '', notes: '',
+ ...(S.coach?.profile || {})
+ }))
+ const set = patch => setP(v => ({ ...v, ...patch }))
+
+ if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE })) { nav('/home', { replace: true }); return null }
+
+ const key = STEPS[step]
+ const canNext = key !== 'goal' || (p.goal && p.experience)
+ const last = step === STEPS.length - 1
+
+ const save = () => { update(s => { const c = (s.coach = s.coach || emptyCoach()); c.profile = p }) }
+
+ const finish = async () => {
+ save()
+ if (editing) { toast(t('Saved')); nav('/coach'); return }
+ setBusy(true)
+ try {
+ await requestPlan(p)
+ toast(t('The Coach is building your plan…'))
+ nav('/coach')
+ } catch (e) { toast(e.message || t('Could not ask the Coach')); setBusy(false) }
+ }
+
+ 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]
+ })
+
+ return <div className="narrow">
+ <div className="hdr">
+ <button className="iconbtn" onClick={() => step ? setStep(step - 1) : nav('/coach')} aria-label={t('Back')}><Icon name="chevronLeft" /></button>
+ <div style={{ flex: 1, marginLeft: 10 }}>
+ <h1>{editing ? t('Coach profile') : t('Your plan')}</h1>
+ <div className="sub">{t('Step {0} of {1}', step + 1, STEPS.length)}</div>
+ </div>
+ </div>
+
+ {/* progress rail — the wizard's only chrome; six dots read faster than "1 of 6" alone */}
+ <div className="row" style={{ gap: 5, marginBottom: 14 }}>
+ {STEPS.map((s, i) => <div key={s} style={{
+ height: 3, flex: 1, borderRadius: 2,
+ background: i <= step ? 'var(--acc)' : 'var(--surface-3)'
+ }} />)}
+ </div>
+
+ <div className="card">
+ {key === 'goal' && <>
+ <h2 style={{ marginTop: 0 }}>{t('What are you training for?')}</h2>
+ <div className="sect-b">
+ {GOALS.map(([v, label]) => <button key={v} className="lrow tap" onClick={() => set({ goal: v })}>
+ <span className="lrow-m"><span className="lrow-t">{t(label)}</span></span>
+ {p.goal === v && <Icon name="check" className="lrow-k" />}
+ </button>)}
+ </div>
+ <h2>{t('Where are you starting from?')}</h2>
+ <div className="sect-b">
+ {EXPERIENCE.map(([v, label]) => <button key={v} className="lrow tap" onClick={() => set({ experience: v })}>
+ <span className="lrow-m"><span className="lrow-t">{t(label)}</span></span>
+ {p.experience === v && <Icon name="check" className="lrow-k" />}
+ </button>)}
+ </div>
+ </>}
+
+ {key === 'days' && <>
+ <h2 style={{ marginTop: 0 }}>{t('How many days a week?')}</h2>
+ <Segmented options={[2, 3, 4, 5, 6].map(n => ({ value: n, label: String(n) }))}
+ value={p.daysPerWeek} onChange={v => set({ daysPerWeek: v })} />
+ <div className="muted small" style={{ margin: '14px 0 8px' }}>{t('Which days suit you? (optional)')}</div>
+ <div className="week">
+ {[1, 2, 3, 4, 5, 6, 0].map(d => <div key={d} className={'wday' + (p.preferredDays.includes(d) ? ' today' : '')}
+ onClick={() => toggleDay(d)} style={{ cursor: 'pointer' }}>
+ <div className="lbl">{t(DAYN[d]).slice(0, 2)}</div>
+ <div className={'dot' + (p.preferredDays.includes(d) ? ' plan' : '')} />
+ </div>)}
+ </div>
+ </>}
+
+ {key === 'length' && <>
+ <h2 style={{ marginTop: 0 }}>{t('How long is a session?')}</h2>
+ <Segmented options={SESSION_MIN.map(n => ({ value: n, label: n + ' ' + t('min') }))}
+ value={p.sessionMin} onChange={v => set({ sessionMin: v })} />
+ <div className="muted small" style={{ marginTop: 12 }}>{t('The Coach fits the volume to the time you actually have, including rest between sets.')}</div>
+ </>}
+
+ {key === 'equipment' && <>
+ <h2 style={{ marginTop: 0 }}>{t('What can you train with?')}</h2>
+ <div className="muted small" style={{ marginBottom: 10 }}>{t('Pick everything you have access to. Leave it empty and the Coach will use the whole library.')}</div>
+ <div className="row" style={{ flexWrap: 'wrap', gap: 7 }}>
+ {EQUIPMENT.map(e => <button key={e} className={'chip' + (p.equipment.includes(e) ? ' on' : '')}
+ onClick={() => toggleEq(e)} style={{ textTransform: 'capitalize' }}>{e}</button>)}
+ </div>
+ </>}
+
+ {key === 'limits' && <>
+ <h2 style={{ marginTop: 0 }}>{t('Anything to work around?')}</h2>
+ <div className="muted small" style={{ marginBottom: 10 }}>
+ {t('Injuries, joints that complain, movements you cannot do, or practical limits like training at 6am in a flat.')}
+ </div>
+ <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 className="dim small" style={{ marginTop: 8, lineHeight: 1.5, color: 'var(--yellow)' }}>
+ {t('If something actually hurts, see a professional — the Coach will program conservatively but it cannot diagnose anything.')}
+ </div>
+ </>}
+
+ {key === 'extras' && <>
+ <h2 style={{ marginTop: 0 }}>{t('Anything else?')}</h2>
+ <div className="muted small" style={{ marginBottom: 6 }}>{t('Exercises you love')}</div>
+ <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 className="muted small" style={{ margin: '12px 0 6px' }}>{t('Exercises you would rather not')}</div>
+ <TextArea rows={2} maxLength={300} value={p.dislikes} onChange={e => set({ dislikes: e.target.value })} placeholder={t('e.g. “I hate lunges”')} />
+ <div className="muted small" style={{ margin: '12px 0 6px' }}>{t('Anything you want the Coach to know')}</div>
+ <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 className="row" style={{ gap: 10 }}>
+ {step > 0 && <Button onClick={() => setStep(step - 1)} style={{ flex: 1 }}>{t("Back")}</Button>}
+ {!last
+ ? <Button variant="primary" style={{ flex: 1 }} disabled={!canNext} onClick={() => setStep(step + 1)}>{t('Next')}</Button>
+ : <Button variant="primary" style={{ flex: 1 }} icon="sparkles" disabled={busy} onClick={finish}>
+ {editing ? t('Save') : t('Build my plan')}
+ </Button>}
+ </div>
+ {!canNext && <div className="dim small" style={{ textAlign: 'center', marginTop: 10 }}>{t('Pick a goal and where you are starting from to continue.')}</div>}
+ <div style={{ height: 20 }} />
+ </div>
+}
diff --git a/frontend/src/views/CoachProposal.jsx b/frontend/src/views/CoachProposal.jsx
new file mode 100644
index 000000000..8794e198c
--- /dev/null
+++ b/frontend/src/views/CoachProposal.jsx
@@ -0,0 +1,237 @@
+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 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 })) 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'))
+ nav('/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))
+ nav('/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>
+}