Merge remote-tracking branch 'origin/main' into feat/gym-checkin-qr

# Conflicts:
#	frontend/package-lock.json
#	frontend/package.json
#	frontend/src/index.css
#	frontend/src/lib/pt-br-locale.test.js
#	frontend/src/locales/hu.js
#	frontend/src/locales/th.js
This commit is contained in:
Sebastian G committed 2026-09-04 13:14:01 +02:00
commit 3197f9e9be
122 files changed
+18404 -103

No files matched your search

+6 -1
View File
@@ -9,6 +9,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'
import '../admin.css'
// Admin-only operator dashboard (owner passkey + admin flag; guarded again server-side).
@@ -202,7 +203,7 @@ export default function Admin() {
<button className="iconbtn" onClick={() => { loadUsers(); loadInvites(); setTick(n => n + 1) }} aria-label="refresh">↻</button>
</div>
<div className="adm-intro">
Everything about running this instance: who uses it, how they get in, and what has happened on it. Nothing here shows anyone's training data beyond counts.
Everything about running this instance: who uses it, how they get in, the AI Coach, and what has happened on it. Nothing here shows anyone's training data beyond counts.
</div>
<div className="tiles" style={{ marginBottom: 12 }}>
@@ -222,6 +223,10 @@ export default function Admin() {
</div>)}
</div>}
{/* The Coach setup. 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} inviteOnly={inviteOnly} />
<div className="card">
+428
View File
@@ -0,0 +1,428 @@
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, laid out as a guided setup: one master switch, numbered
steps that each say what they are for, and everything an owner rarely needs folded away
under "Advanced" and "Activity". 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.
This is the ONLY place the Coach can be switched off for everyone. Users can decline the
consent screen for themselves, but they cannot disable the feature — that is an operator
decision, so it lives with the operator. */
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) + ' min ago'
if (s < 86400) return Math.floor(s / 3600) + ' h ago'
return Math.floor(s / 86400) + ' d ago'
}
// Which chips go under which heading. Runtime-backed providers are the ones that need the
// bigger `coach` image; the fixture exists so the whole loop can be walked without any account.
const RUNTIME_IDS = ['claude', 'codex']
const TESTING_IDS = ['fixture']
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)
// The models the endpoint serves, fetched on demand. Seeded from the status call when the
// stored key already let it list them.
const [models, setModels] = useState(null)
// The last "Test the Coach" outcome, shown inline where the button is rather than only as a
// toast that is gone before anyone has read the provider's reason.
const [testResult, setTestResult] = useState(null)
const load = () => api('/api/admin/coach').then(r => { setD(r); setModels(r.knownModels || null) }).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 loadModels = async () => {
setBusy(true)
try {
const r = await api('/api/admin/coach/models', { method: 'POST', body: '{}' })
if (r.ok) { setModels(r.models); toast(r.models.length + ' models') } else toast(r.error || 'Could not list models')
} catch (e) { toast(e.message) }
setBusy(false)
}
const test = async () => {
setBusy(true); setTestResult({ pending: true })
try {
const r = await api('/api/admin/coach/test', { method: 'POST', body: '{}' })
setTestResult(r)
toast(r.ok ? 'Coach test passed ✅' : 'Test failed')
await load()
} catch (e) { setTestResult({ ok: false, error: e.message }); toast(e.message) }
setBusy(false)
}
const disconnect = async () => {
setBusy(true)
try { await api('/api/admin/coach/disconnect', { method: 'POST', body: JSON.stringify({ provider: d.provider }) }); toast('Credential removed'); 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="adm-lead">Force-disabled by <code>COACH_DISABLED</code> in the server's environment. Remove that variable and restart to configure the Coach here.</div>
</div>
const meta = d.providers.find(p => p.id === d.provider) || {}
const authState = d.auth?.state
const authed = authState === 'connected' || authState === 'not-required' || authState === 'optional'
const needsEndpoint = !!meta.baseUrl
const hasEndpoint = !needsEndpoint || !!d.baseUrl
const live = d.enabled && d.runtime.ok && authed && hasEndpoint
const status = !d.enabled ? 'Off — users see no Coach anywhere in the app.'
: live ? <>On · {meta.label}{d.model ? ' · ' + d.model : ''}</>
: !hasEndpoint ? 'On, but no endpoint yet — finish step 2.'
: !authed ? 'On, but no credential yet — finish the Credential step.'
: !d.runtime.ok ? 'On, but the provider cannot be reached — see the Test step.'
: 'On'
// Chips, grouped.
const groups = [
{ title: 'Paste an API key', hint: 'Plain HTTPS to the provider. Works on the default api image — nothing extra to install.', items: d.providers.filter(p => p.http) },
{ title: 'Runs a local AI runtime', hint: 'Needs the bigger api image built with --target coach.', items: d.providers.filter(p => RUNTIME_IDS.includes(p.id)) },
{ title: 'Testing', hint: 'A built-in fake that answers instantly, so the whole loop can be tried without an account.', items: d.providers.filter(p => TESTING_IDS.includes(p.id)) }
]
const hasCredentialStep = !!(meta.setupToken || meta.apiKey)
const step1Done = !!d.provider
const step2Done = hasEndpoint
const step3Done = authed
const step4Done = !!d.model
const step5Done = !!testResult?.ok || !!d.lastSuccess
// Step numbers only count the steps this provider actually shows — and like any wizard,
// only the first unfinished step stands open; everything done folds to its summary line.
const flags = [step1Done, ...(needsEndpoint ? [step2Done] : []), ...(hasCredentialStep ? [step3Done] : []), step4Done, step5Done]
const doneCount = flags.filter(Boolean).length
const firstTodo = flags.indexOf(false)
let n = 1
let idx = 0
const num = () => n++
const stepAt = () => { const i = idx++; return { open: i === (firstTodo === -1 ? -1 : firstTodo), key: i + ':' + (i === firstTodo) } }
// Off = a quiet, optional feature: one clean pitch and one button, no half-dimmed controls.
if (!d.enabled) return <div className="card">
<div className="adm-hero">
<div className="adm-hero-av"><Icon name="sparkles" /></div>
<h2>AI Coach</h2>
<p>An optional coach that designs training plans and reviews what people actually log. Off right now — nobody sees it anywhere in the app.</p>
<div className="adm-hero-feats">
<div><Icon name="clipboard" /><span><b>Bring any AI.</b> An API key from Anthropic, OpenAI or Gemini — or a free local model via Ollama.</span></div>
<div><Icon name="shield" /><span><b>Private by design.</b> A strict allowlist decides what leaves; every change needs the user's yes and can be undone.</span></div>
<div><Icon name="person" /><span><b>Each user decides.</b> Turning it on only makes the Coach available; every person consents for themselves.</span></div>
</div>
<Button variant="primary" icon="sparkles" disabled={busy} onClick={() => patch({ enabled: true })}>Set up the Coach</Button>
</div>
</div>
return <div className="card" style={{ borderColor: live ? 'var(--acc)' : undefined }}>
<div className="row between" style={{ marginBottom: 2 }}>
<h2 style={{ margin: 0 }}>AI Coach</h2>
<Switch checked={!!d.enabled} disabled={busy} onChange={v => patch({ enabled: v })} />
</div>
<div className="adm-status">
<span className={'adm-pill ' + (live ? 'ok' : 'warn')}>{live ? 'ready' : 'not ready'}</span>
<span>{status}</span>
</div>
{!live && <div className="adm-progress" aria-hidden="true"><i style={{ width: Math.round(doneCount / flags.length * 100) + '%' }} /></div>}
<div className="adm-lead">
{live ? 'Users find the Coach under Plan → Coach. This switch is the only place it can be turned off for everyone.'
: `${doneCount} of ${flags.length} steps done — finish the open step and the next one unfolds.`}
</div>
{d.enabled && <>
{/* ---------- provider ---------- */}
<Step n={num()} title="Provider" hint={meta.label || 'Which AI answers the Coach'} done={step1Done} {...stepAt()}>
<div className="adm-hint">Pick who answers. A key or token you save stays with its provider, so you can switch back and forth without pasting it again.</div>
{groups.map(g => !!g.items.length && <div key={g.title} className="adm-group">
<div className="adm-group-t">{g.title}</div>
<div className="adm-chips">
{g.items.map(p => <button key={p.id} className={'chip' + (p.id === d.provider ? ' on' : '')} disabled={busy}
onClick={() => { setTestResult(null); patch({ provider: p.id }) }}>
{p.label}{p.connected && <span className="adm-chip-key">key saved</span>}
</button>)}
</div>
<div className="adm-hint" style={{ margin: '6px 0 0' }}>{g.hint}</div>
</div>)}
</Step>
{/* ---------- endpoint (compatible only) ---------- */}
{needsEndpoint && <Step n={num()} title="Endpoint" hint={d.baseUrl || 'Where the model runs'} done={step2Done} {...stepAt()}>
<div className="adm-hint">The address of any server that speaks OpenAI's chat API: <b>Ollama</b>, <b>LM Studio</b>, <b>vLLM</b>, <b>OpenRouter</b>, or a gateway of your own. Just the base — no <code>/v1</code>, no key in the URL.</div>
<div className="adm-field">
<label>Base URL</label>
<TextField key={d.baseUrl || ''} defaultValue={d.baseUrl || ''} placeholder="http://ollama:11434 or https://openrouter.ai/api" inputMode="url" autoCapitalize="none" autoCorrect="off"
onBlur={e => e.target.value !== (d.baseUrl || '') && patch({ baseUrl: e.target.value })} />
</div>
<div className="adm-hint" style={{ margin: 0 }}>The host is written to the job log, so you can always see where requests went.</div>
</Step>}
{/* ---------- credential ---------- */}
{hasCredentialStep && <Step n={num()} title="Credential" hint={credentialHint(d.auth, meta)} done={step3Done} {...stepAt()}>
<div className="row" style={{ gap: 8, flexWrap: 'wrap', marginBottom: 8 }}>
<CredentialPill auth={d.auth} />
</div>
{authState === 'connected' ? <>
<div className="adm-hint">Connected{d.auth.account ? ' as ' + d.auth.account : ''} via {credentialLabel(d.auth.type)}{d.auth.connectedAt ? ' · added ' + rel(d.auth.connectedAt) : ''}. The key is stored encrypted and is never shown again.</div>
<div className="adm-actions">
{meta.apiKey && <Button size="sm" variant="tinted" icon="lock" disabled={busy}
onClick={() => openSheet(close => <ApiKeySheet close={close} onDone={load} label={meta.label} placeholder={meta.keyPlaceholder} optional={meta.keyOptional} />)}>Replace key</Button>}
<Button size="sm" danger disabled={busy} onClick={disconnect}>Remove</Button>
</div>
</> : <>
{authState === 'unreadable' && <div className="adm-hint" style={{ color: 'var(--red)' }}>
The stored credential can't be decrypted. This usually means <code>./data</code> was restored without its <code>secret</code> file. Add the key again to fix it.
</div>}
{authState === 'optional' && <div className="adm-hint">This endpoint works without a key. Add one only if your server asks for it (OpenRouter does; a model on your own network usually does not).</div>}
{authState === 'none' && <div className="adm-hint">{meta.setupToken
? 'Paste either a Claude Code setup token (your subscription) or an Anthropic API key (pay per use).'
: 'Paste an API key from the provider\'s console. It is stored encrypted on this server and sent to the provider only while a job runs.'}</div>}
<div className="adm-actions">
{meta.setupToken && <Button size="sm" variant="primary" icon="key" disabled={busy}
onClick={() => openSheet(close => <SetupTokenSheet close={close} onDone={load} label={meta.label} />)}>Add Claude Code token</Button>}
{meta.apiKey && <Button size="sm" variant={meta.setupToken ? undefined : 'primary'} icon="lock" disabled={busy}
onClick={() => openSheet(close => <ApiKeySheet close={close} onDone={load} label={meta.label} placeholder={meta.keyPlaceholder} optional={meta.keyOptional} />)}>
{meta.keyOptional ? 'Add API key (optional)' : 'Add API key'}</Button>}
</div>
</>}
</Step>}
{/* ---------- model ---------- */}
<Step n={num()} title="Model" hint={d.model || (meta.defaultModel ? 'default: ' + meta.defaultModel : 'not chosen yet')} done={step4Done} {...stepAt()}>
<div className="adm-hint">{meta.http
? 'Which model the provider should use. "List models" asks the provider for its current list, so nothing here goes stale.'
: 'Optional. Leave it empty to use the runtime\'s own default.'}</div>
<div className="adm-field">
<label>Model</label>
{models && models.length
? <select className="adm-select" value={models.includes(d.model) ? d.model : ''} disabled={busy} onChange={e => patch({ model: e.target.value })}>
<option value="">{meta.defaultModel ? `Default (${meta.defaultModel})` : 'Pick a model…'}</option>
{d.model && !models.includes(d.model) && <option value={d.model}>{d.model} (not in the list)</option>}
{models.map(m => <option key={m} value={m}>{m}</option>)}
</select>
: <TextField key={d.provider} defaultValue={d.models?.[d.provider] || ''} placeholder={meta.defaultModel ? `Default: ${meta.defaultModel}` : needsEndpoint ? 'e.g. qwen2.5:3b — or press "List models"' : '(runtime default)'}
onBlur={e => e.target.value !== (d.models?.[d.provider] || '') && patch({ model: e.target.value })} />}
</div>
{meta.http && <div className="adm-actions">
<Button size="sm" variant="tinted" icon="reset" disabled={busy} onClick={loadModels}>{models ? 'Refresh list' : 'List models'}</Button>
{models && models.length ? <span className="dim small" style={{ alignSelf: 'center' }}>{models.length} served by the provider</span> : null}
</div>}
</Step>
{/* ---------- test ---------- */}
<Step n={num()} title="Test" hint={step5Done ? 'passed' : 'one real round trip, no user data'} done={step5Done} {...stepAt()} forceOpen={!!testResult}>
<div className="adm-hint">Sends one tiny question to the provider and checks the answer. No training data is involved. Do this after every change above.</div>
<div className="adm-actions">
<Button size="sm" variant="primary" icon="check" disabled={busy || !authed || !hasEndpoint} onClick={test}>Test the Coach</Button>
</div>
{(!authed || !hasEndpoint) && <div className="adm-hint" style={{ margin: '6px 0 0' }}>
{!hasEndpoint ? 'Finish the Endpoint step first.' : 'Finish the Credential step first.'}
</div>}
{testResult && <div className={'adm-result ' + (testResult.pending ? '' : testResult.ok ? 'ok' : 'bad')}>
{testResult.pending ? 'Asking the provider…'
: testResult.ok ? <><b>Passed</b>{testResult.version ? 'Provider: ' + testResult.version : 'The provider answered as expected.'}</>
: <><b>Failed</b>{testResult.error || 'No answer from the provider.'}</>}
</div>}
<div className="adm-kv" style={{ marginTop: 10 }}>
<span className="k">Runtime</span>
<span className="v">{d.runtime.ok ? <span className="adm-pill ok">ready</span> : <span className="adm-pill bad">missing</span>}{d.runtime.version ? <div className="dim small">{d.runtime.version}</div> : null}{!d.runtime.ok && d.runtime.error ? <div className="small" style={{ color: 'var(--red)' }}>{d.runtime.error}</div> : null}</span>
</div>
</Step>
{/* ---------- advanced ---------- */}
<details className="adm-fold">
<summary>Advanced <Icon name="chevronRight" className="chev" /></summary>
<div className="adm-fold-b">
<div className="adm-group-t">Limits</div>
<div className="adm-hint">How many Coach runs are allowed per day. Every run is one request on the provider account above. 0 means no limit.</div>
<div className="adm-kv"><span className="k">Per user, per day</span>
<span className="v"><input className="num" type="number" min="0" max="200" defaultValue={d.caps.perProfileDaily} disabled={busy}
onBlur={e => +e.target.value !== d.caps.perProfileDaily && patch({ caps: { ...d.caps, perProfileDaily: +e.target.value } })} /></span></div>
<div className="adm-kv"><span className="k">Whole instance, per day</span>
<span className="v"><input className="num" type="number" min="0" max="5000" defaultValue={d.caps.instanceDaily} disabled={busy}
onBlur={e => +e.target.value !== d.caps.instanceDaily && patch({ caps: { ...d.caps, instanceDaily: +e.target.value } })} /></span></div>
<div className="adm-group-t" style={{ marginTop: 14 }}>Compare with others</div>
<div className="row between" style={{ gap: 12, alignItems: 'flex-start' }}>
<div className="adm-hint" style={{ margin: 0 }}>
<b>Let people compare with each other.</b> Anonymous medians (estimated 1RM, sessions per week) across profiles that opt in; at least three must share before anyone sees a number. Each person switches themselves on in the Coach chat, and sees nothing unless they do.
</div>
<Switch checked={!!d.community} disabled={busy} onChange={v => patch({ community: v })} />
</div>
<div className="adm-group-t" style={{ marginTop: 14 }}>Whose account pays</div>
<div className="adm-hint">{d.authMode === 'profile'
? 'Each profile signs in with their own account.'
: d.auth?.type === 'apikey' || meta.http
? 'One API key for the whole instance: every profile may use the Coach with it, and the daily limits above are what bound the spend.'
: d.boundUid
? 'One personal account, already in use by one profile. Every other profile is refused, so nobody spends somebody else\'s subscription.'
: 'One personal account. The first profile to use it becomes the only one allowed to — every other profile is then refused. Paste an API key instead if the whole instance should have the Coach.'}</div>
<div className="adm-group-t" style={{ marginTop: 14 }}>Isolation</div>
<div className="adm-hint">{d.unprivileged && !d.unprivileged.ok
? <span style={{ color: 'var(--red)' }}>Jobs are blocked: {d.unprivileged.why}. Nothing runs until this is fixed.</span>
: d.unprivileged?.dropped
? 'Jobs run as a separate unprivileged user that cannot read your data directory or secrets.'
: d.unprivileged?.why?.includes('no child process')
? 'Not needed for this provider — it makes an HTTPS request and starts no program on this server.'
: 'Jobs run with the server\'s own user on this host (no separate user to drop to).'}</div>
</div>
</details>
{/* ---------- activity ---------- */}
<details className="adm-fold">
<summary>Activity <Icon name="chevronRight" className="chev" /></summary>
<div className="adm-fold-b">
<div className="tiles" style={{ textAlign: 'left', marginBottom: 10 }}>
<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 success</div><div className="v" style={{ fontSize: '.85rem' }}>{rel(d.lastSuccess?.at)}</div></div>
</div>
{d.lastError && <>
<div className="adm-group-t">Last failure</div>
<div className="adm-result bad" style={{ marginTop: 0, marginBottom: 10 }}>
<b>{failureTitle(d.lastError.errorClass)}</b>
{d.lastError.detail ? <span className="small">{d.lastError.detail}</span> : null}
<div className="dim" style={{ fontSize: '.72rem', marginTop: 4 }}>{rel(d.lastError.at)}</div>
</div>
</>}
<div className="adm-group-t">Recent jobs</div>
{d.recent?.length ? <div className="adm-log">
{d.recent.slice(0, 10).map((e, i) => <div key={i} className="adm-log-row">
<span>{e.kind === 'create' ? 'Plan' : 'Review'}{e.trigger === 'scheduled' ? ' · scheduled' : ''} · <span style={{ color: e.outcome === 'failed' ? 'var(--red)' : e.outcome === 'ready' ? 'var(--acc)' : 'var(--label-2)' }}>{e.outcome}</span>{e.ms ? ' · ' + Math.round(e.ms / 1000) + ' s' : ''}</span>
<span className="when">{rel(e.at)}</span>
</div>)}
</div> : <div className="adm-empty">No jobs yet.</div>}
<div className="adm-hint" style={{ margin: '8px 0 0' }}>Counts and outcomes only. What people asked the Coach, and what it answered, is never shown here.</div>
</div>
</details>
</>}
</div>
}
/* ---------------------------------- pieces ---------------------------------- */
function Step({ n, title, hint, done, open, forceOpen, children }) {
// `key` remounts the <details> when the wizard advances, so the next step unfolds itself.
return <details className={'adm-step ' + (done ? 'done' : 'todo')} open={open || forceOpen}>
<summary>
<span className="adm-num">{done ? <Icon name="check" /> : n}</span>
<span className="adm-step-t"><b>{title}</b><span>{hint}</span></span>
<Icon name="chevronRight" className="chev" />
</summary>
<div className="adm-step-b">{children}</div>
</details>
}
function CredentialPill({ auth }) {
const s = auth?.state
if (s === 'connected') return <span className="adm-pill ok">connected{auth.account ? ' · ' + auth.account : ''}</span>
if (s === 'not-required') return <span className="adm-pill">not needed</span>
if (s === 'optional') return <span className="adm-pill">optional — none saved</span>
if (s === 'unreadable') return <span className="adm-pill bad">can't be read</span>
return <span className="adm-pill warn">needed</span>
}
const credentialHint = (auth, meta) => {
const s = auth?.state
if (s === 'connected') return 'Connected' + (auth.account ? ' as ' + auth.account : '')
if (s === 'not-required') return 'Not needed'
if (s === 'optional') return 'Optional for this endpoint'
if (s === 'unreadable') return 'Stored key can\'t be read — add it again'
return meta.setupToken ? 'Token or API key needed' : 'API key needed'
}
const credentialLabel = type => ({
'cli-token': 'Claude Code setup token', 'chatgpt-cli': 'ChatGPT CLI login', oauth: 'legacy token', apikey: 'API key'
}[type] || 'credential')
// The failure classes jobs.js emits, in words an operator can act on.
const failureTitle = cls => ({
timeout: 'The provider took longer than the job budget (COACH_JOB_TIMEOUT_MS, default 5 minutes)',
missing: 'The provider runtime or key is missing',
auth: 'The provider rejected the credential',
provider: 'The provider returned an error',
unusable: 'The model answered, but not in a shape the app could use',
restart: 'The server restarted while a job was running',
nostate: 'The user\'s training data could not be read',
off: 'The Coach was off when the job ran',
internal: 'Something went wrong on the server'
}[cls] || cls || 'Failed')
/* ------------------------------- 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 ✅' : 'Token saved')
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. you@example.com)" onChange={e => setAccount(e.target.value)} />
<div style={{ height: 12 }} />
<Button variant="primary" disabled={busy || !token.trim()} onClick={save}>Save token</Button>
<div style={{ height: 8 }} />
</>
}
function ApiKeySheet({ close, onDone, label, placeholder, optional }) {
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 ✅' : 'Key saved')
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 sent to the provider only while a job runs. It is never shown again and never leaves the server{optional ? ' — and for an endpoint that takes no key, you can leave this empty and close the sheet.' : '.'}
</div>
<TextField value={key} autoFocus type="password" placeholder={placeholder || 'sk-…'} autoCapitalize="none" autoCorrect="off" 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 }} />
</>
}
+762
View File
@@ -0,0 +1,762 @@
// The conversation with the Coach.
//
// Everything the Coach does happens here: your answers as the opening message, a typing
// bubble while a job runs (with how long it usually takes), the plan or the suggestions as a
// card you page through, a composer to say what to change, and one button that imports the
// result. History stays in the thread — come back any time, ask for a review, refine again.
//
// The thread is `S.coach.chat` (small, synced) plus whatever is live right now from the
// status poll: a running job or a pending proposal. Nothing about the proposal is copied into
// the chat until a decision is made about it, so two devices can never disagree on what is
// pending. Once decided, the chat line carries a `ref` into `S.coach.log`, where the whole
// proposal — every change, accepted or not, the notes, the evidence — is kept, so saying yes
// or no never makes it disappear. Turning the Coach off is the admin's decision, not a control
// on this screen.
import { useEffect, useMemo, useRef, 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, fmtNum, DAYS } from '../lib/format.js'
import { exLine } from '../lib/history.js'
import { DEMO } from '../lib/demo.js'
import { MOBILE } from '../lib/mobile.js'
import {
coachAvailable, hasConsent, emptyCoach, appendChat, recordTiming, estimateMs, profileLines,
markStale, applicable, applyChangeSet, applyCreatedPlan, recordDismissal, recordDebrief, logEntry,
changeTitle, changeValues, exName, canRevert, revertLast
} from '../lib/coach.js'
import { insightsFor, sessionInsights } from '../lib/coach-insights.js'
import { useCoachStatus, requestReview, requestDebrief, refinePlan, resolvePending, cohortStats, setCohortShare, JOB_ERRORS } from '../lib/coach-api.js'
import { confirmSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import LineChart from '../components/LineChart.jsx'
import { Button, Check, Switch, Section, Row, SelectRow } from '../components/ui.jsx'
import '../coach.css'
export default function CoachChat() {
const nav = useNavigate()
const S = useStore(s => s.S)
const user = useStore(s => s.user)
const config = useStore(s => s.config)
const coachLocal = useStore(s => s.coachLocal)
const update = useStore(s => s.update)
const storeReady = useStore(s => s.ready)
const toast = useUI(s => s.toast)
const openSheet = useUI(s => s.openSheet)
const { job, pending, cap, loading, lastError, last, refresh } = useCoachStatus(true)
const [text, setText] = useState('')
const [busy, setBusy] = useState(false)
const endRef = useRef(null)
const prevJob = useRef(null)
const coachMode = coachLocal?.mode
const ok = coachAvailable(config, user, { demo: DEMO, mobile: MOBILE, coachMode })
const ready = ok && hasConsent(S) && !!S.coach?.profile
// Not before the store has loaded: a cold start straight on #/coach would otherwise read an
// empty state, decide there is no consent, and bounce a consenting user into the intake.
useEffect(() => {
if (!storeReady) return
if (!ok) nav('/home', { replace: true })
else if (!ready) nav('/coach/intake', { replace: true })
}, [storeReady, ok, ready])
// A job that ends is either a proposal, "nothing to change", or a failure. The server tells
// the client none of that directly — the job simply stops appearing — so the transition is
// read here, once, and written into the thread as the Coach's reply.
useEffect(() => {
if (loading) return
const was = prevJob.current
prevJob.current = job
if (!was || job) return
const ms = was.startedAt ? Date.now() - was.startedAt : 0
update(s => {
recordTiming(s, ms)
if (!pending) {
const cls = lastError?.errorClass || (last?.outcome === 'failed' ? (last.errorClass || 'internal') : null)
appendChat(s, cls
? { role: 'coach', kind: 'error', text: JOB_ERRORS[cls] || JOB_ERRORS.internal }
: { role: 'coach', kind: 'nochange', text: last?.reading
? last.reading
: t('I looked through everything and there is nothing I would change right now. Keep going — ask me again after a few more sessions.') })
}
})
}, [job, pending, loading])
useEffect(() => { if (typeof endRef.current?.scrollIntoView === 'function') endRef.current.scrollIntoView({ block: 'end' }) }, [S.coach?.chat?.length, !!job, !!pending])
if (!ready) return null
const coach = S.coach || emptyCoach()
const community = !!config?.coach?.community && !DEMO && !(MOBILE && coachMode === 'byok')
const send = async () => {
const msg = text.trim()
if (!msg || busy) return
setBusy(true)
try {
if (pending?.kind === 'create') await refinePlan(msg)
else await requestReview(msg)
update(s => appendChat(s, { role: 'user', kind: 'text', text: msg }))
setText('')
refresh()
} catch (e) {
toast(e.message || t('Could not ask the Coach'))
}
setBusy(false)
}
const ask = async (fn, line) => {
setBusy(true)
try {
await fn()
update(s => appendChat(s, { role: 'user', kind: 'text', text: line }))
refresh()
} catch (e) { toast(e.message || t('Could not ask the Coach')) }
setBusy(false)
}
const askReview = () => ask(() => requestReview(''), t('Have a look at my training and tell me what you would change.'))
const lastWorkout = (S.workouts || []).filter(w => w && w.d).at(-1) || null
const askDebrief = () => ask(() => requestDebrief(lastWorkout?.id || null), lastWorkout?.name
? t('How did my {0} session go?', lastWorkout.name)
: t('How did my last workout go?'))
const askImprove = r => ask(
() => requestReview(t('Focus only on my routine “{0}”. Improve it: exercise choice, order, sets and reps, rep ranges, progression. Leave the other routines alone.', r.name)),
t('Improve my routine “{0}”.', r.name))
const pickRoutine = () => openSheet(close => <div className="chat-menu">
<h3>{t('Improve which routine?')}</h3>
<div className="sect-b">
{(S.routines || []).map(r => <Row key={r.id} icon="dumbbell" iconTint="var(--acc)" title={`${r.emoji || ''} ${r.name}`.trim()} subtitle={t('{0} exercises', (r.ex || []).length)} accessory="chevron" onClick={() => { close(); askImprove(r) }} />)}
{!(S.routines || []).length && <div className="chat-empty">{t('You have no routines yet — ask the Coach for a plan first.')}</div>}
</div>
<div style={{ height: 10 }} />
</div>)
const showHistory = () => openSheet(close => <HistorySheet S={S} close={close} openSheet={openSheet} />)
const showCohort = () => openSheet(() => <CohortSheet S={S} update={update} toast={toast} />)
const idle = !job && !pending
const menu = () => openSheet(close => <div className="chat-menu">
<h3>{t('Coach')}</h3>
<div className="sect-b">
{idle && <Row icon="sparkles" iconTint="var(--acc)" title={t('Ask for a review')} subtitle={t('What would the Coach change after your last sessions?')} accessory="chevron" onClick={() => { close(); askReview() }} />}
{idle && !!lastWorkout && <Row icon="checkCircle" iconTint="var(--green)" title={t('Review my last workout')} subtitle={t('What went well, what to watch, what to do next time')} accessory="chevron" onClick={() => { close(); askDebrief() }} />}
{idle && !!(S.routines || []).length && <Row icon="wrench" iconTint="var(--orange)" title={t('Improve a routine')} subtitle={t('Pick one; the Coach works on just that')} accessory="chevron" onClick={() => { close(); pickRoutine() }} />}
{community && <Row icon="person" iconTint="var(--teal)" title={t('Compare with others here')} subtitle={t('Anonymous medians from this instance')} accessory="chevron" onClick={() => { close(); showCohort() }} />}
<Row icon="history" iconTint="var(--blue)" title={t('Everything the Coach proposed')} subtitle={t('Plans, suggestions and debriefs, kept')} accessory="chevron" onClick={() => { close(); showHistory() }} />
<Row icon="clipboard" iconTint="var(--indigo)" title={t('Edit my answers')} subtitle={t('Goal, days, equipment, limits')} accessory="chevron" onClick={() => { close(); nav('/coach/intake?edit=1') }} />
<Row icon="clock" iconTint="var(--purple)" title={t('Automatic reviews')} subtitle={cadenceLabel(coach)} accessory="chevron" onClick={() => { close(); cadenceSheet(openSheet, update) }} />
{canRevert(S) && <Row icon="reset" iconTint="var(--blue)" title={t('Undo the last Coach changes')} accessory="chevron" onClick={() => { close(); doRevert() }} />}
</div>
<div style={{ height: 10 }} />
</div>)
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); if (ok) appendChat(s, { role: 'coach', kind: 'reverted', text: t('Done — your plan is back to how it was before my last changes.') }) })
toast(ok ? t('Plan restored') : t('Nothing to undo'))
}
})
const status = job ? t('thinking…') : pending ? t('has a suggestion for you') : t('here when you need it')
const placeholder = pending?.kind === 'create'
? t('What should change?')
: job ? t('Coach is thinking…') : t('Message the Coach…')
return <div className="narrow chat">
<div className="chat-hdr">
<button className="iconbtn" onClick={() => nav('/plan')} aria-label={t('Back')}><Icon name="chevronLeft" /></button>
<div className="chat-av"><Icon name="sparkles" /></div>
<div className="grow">
<h1>{t('Coach')}</h1>
<div className={'chat-st' + (job ? ' live' : '')}>{status}</div>
</div>
<button className="iconbtn" onClick={menu} aria-label={t('More')}><Icon name="list" /></button>
</div>
<div className="msgs">
<Bubble role="coach">{t('Hi — I’m your Coach. I build your plan from your answers and adjust it from what you actually log. Nothing changes until you say so.')}</Bubble>
{(coach.chat || []).map(m => <Message key={m.id} m={m} S={S} profile={coach.profile} openSheet={openSheet} />)}
{job && <Typing S={S} kind={job.kind} coachLocal={coachLocal} config={config} />}
{pending && !job && (pending.kind === 'create'
? <PlanCard p={pending} S={S} update={update} toast={toast} nav={nav} refresh={refresh} />
: pending.kind === 'debrief'
? <DebriefCard p={pending} S={S} update={update} toast={toast} refresh={refresh} />
: <ReviewCard p={pending} S={S} update={update} toast={toast} refresh={refresh} />)}
<div ref={endRef} />
</div>
<div className="composer">
{idle && !busy && <div className="chips-row">
<button className="qchip" onClick={askReview}><Icon name="sparkles" />{t('Review my training')}</button>
{!!lastWorkout && <button className="qchip" onClick={askDebrief}><Icon name="checkCircle" />{t('Last workout')}</button>}
{!!(S.routines || []).length && <button className="qchip" onClick={pickRoutine}><Icon name="wrench" />{t('Improve a routine')}</button>}
{community && <button className="qchip" onClick={showCohort}><Icon name="person" />{t('Compare')}</button>}
</div>}
<div className="composer-in">
<textarea rows={1} value={text} maxLength={1000} placeholder={placeholder} disabled={!!job}
onChange={e => setText(e.target.value)}
onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send() } }} />
<button className="send" onClick={send} disabled={!text.trim() || busy || !!job} aria-label={t('Send')}><Icon name="arrowUp" /></button>
</div>
{cap?.limit > 0 && <div className="composer-cap">{t('{0} of {1} Coach runs used today', cap.used, cap.limit)}</div>}
</div>
</div>
}
/* ---------------------------------- bubbles ---------------------------------- */
function Bubble({ role, kind, at, children }) {
const cls = kind === 'error' ? ' err' : ''
return <div className={'msg ' + role}>
<div className={'bub' + cls}>{children}</div>
{at && <div className="msg-t">{stamp(at)}</div>}
</div>
}
function Message({ m, S, profile, openSheet }) {
if (m.kind === 'intake') {
const lines = profileLines(profile)
return <Bubble role="user" at={m.at}>
{t('Here is what I am working with:')}
<ul>{lines.map((l, i) => <li key={i}>{l}</li>)}</ul>
</Bubble>
}
if (m.kind === 'applied' || m.kind === 'dismissed' || m.kind === 'debrief') {
const entry = m.ref ? logEntry(S, m.ref) : null
return <div className="msg coach" style={entry ? { maxWidth: '100%', width: '100%' } : undefined}>
{!!m.text && <div className="bub">{m.text}</div>}
{entry && <Recap entry={entry} S={S} openSheet={openSheet} />}
{m.at && <div className="msg-t">{stamp(m.at)}</div>}
</div>
}
if (m.kind === 'reverted' || m.kind === 'nochange' || m.kind === 'error' || m.kind === 'text') {
return <Bubble role={m.role} kind={m.kind} at={m.at}>{m.text}</Bubble>
}
return null
}
const stamp = at => {
const d = new Date(at)
const today = new Date()
const time = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
return d.toDateString() === today.toDateString() ? time : fmtDate(d.toISOString().slice(0, 10)) + ' · ' + time
}
function Typing({ S, kind, coachLocal, config }) {
const ms = estimateMs(S)
// "Local" on either side: the phone's own OpenAI-compatible endpoint, or the server's —
// /api/config names the provider, and a model on the owner's box is nothing like a cloud API.
const local = (coachLocal?.mode === 'byok' && coachLocal?.provider === 'compatible') || config?.coach?.provider === 'compatible'
let eta
if (ms) {
const min = Math.round(ms / 60000)
eta = min < 1 ? t('Usually under a minute.') : t('Usually about {0} min.', min)
} else {
// Until a job has been measured, "a minute or two" is a cloud number — say nothing for a
// local model rather than something wrong; the next line already warns it takes longer.
eta = local ? '' : t('This usually takes a minute or two.')
}
const doing = kind === 'create' ? t('Building your plan…') : kind === 'debrief' ? t('Looking at that session…') : t('Reading your training…')
return <div className="msg coach">
<div className="bub typing"><i /><i /><i /></div>
<div className="typing-eta">
{doing} {eta}
{local ? ' ' + t('A local model can take longer.') : ''}
{' ' + t('You can leave — it keeps going.')}
</div>
</div>
}
/* ---------------------------------- the plan ---------------------------------- */
function PlanCard({ p, S, update, toast, nav, refresh }) {
const b = p.bundle
const [tab, setTab] = useState(0)
const [schedule, setSchedule] = useState(true)
const r = b.routines[Math.min(tab, b.routines.length - 1)]
const weekDays = useMemo(() => new Set(Object.keys(b.week || {}).map(Number)), [b])
const accept = () => {
try {
let n = 0
update(s => {
const res = applyCreatedPlan(s, p, { schedule })
n = res?.routines?.length || b.routines.length
appendChat(s, { role: 'coach', kind: 'applied', ref: res.logId, text: schedule
? t('Imported — {0} routines are in your plan and your week is set. See you at the next session.', n)
: t('Imported — {0} routines are in your plan. Your week is unchanged; schedule them whenever you like.', n) })
})
resolvePending({ accepted: ['plan'] }).catch(() => {})
toast(t('Your plan is live'))
refresh()
} 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 => { const ref = recordDismissal(s, p); appendChat(s, { role: 'coach', kind: 'dismissed', ref, text: t('Discarded. Tell me what was off and I will build a different one.') }) })
resolvePending({ dismissed: true }).catch(() => {})
refresh()
}
})
return <div className="msg coach" style={{ maxWidth: '100%', width: '100%' }}>
<div className="pcard">
<div className="pcard-hd">
<div className="pcard-eyebrow">{p.iteration > 1 ? t('Revision {0}', p.iteration) : t('Your plan')}</div>
<h2 className="pcard-h">{b.name || t('Coach plan')}</h2>
{!!b.summary && <p className="pcard-sum">{b.summary}</p>}
{!!b.basedOn && <p className="pcard-sum" style={{ fontSize: 13 }}>{b.basedOn}</p>}
</div>
<WeekStrip days={weekDays} />
{b.routines.length > 1 && <div className="pcard-tabs">
{b.routines.map((x, i) => <button key={x.id || i} className={'pcard-tab' + (i === tab ? ' on' : '')} onClick={() => setTab(i)}>{x.emoji} {x.name}</button>)}
</div>}
{r && <RoutineBlock r={r} unit={S.unit} />}
<div className="pcard-row">
<span className="lrow-m"><span className="lrow-t">{t('Use this weekly schedule')}</span><span className="lrow-s">{t('Replaces your current week. Days this plan leaves empty become rest days.')}</span></span>
<Switch checked={schedule} onChange={setSchedule} />
</div>
<div className="pcard-note">{t('The Coach is not a doctor or a physiotherapist. If something hurts, ask a professional.')}</div>
<div className="pcard-ft">
<Button variant="primary" icon="download" onClick={accept}>{t('Import this plan')}</Button>
<Button onClick={discard}>{t('Discard')}</Button>
</div>
</div>
<div className="msg-t">{t('Not quite right? Say what to change below and I will revise the whole plan.')}</div>
</div>
}
const WeekStrip = ({ days }) => <div className="pcard-week">
{[1, 2, 3, 4, 5, 6, 0].map(d => <div key={d} className={'pcard-wd' + (days.has(d) ? ' on' : '')}>{t(DAYS[d])}</div>)}
</div>
const RoutineBlock = ({ r, unit }) => <div className="pcard-rt">
<div className="pcard-rt-h"><b>{r.emoji} {r.name}</b><span>{t('{0} exercises', r.ex.length)}</span></div>
{!!r.why && <div className="pcard-why">{r.why}</div>}
{r.ex.map((e, i) => <div key={i} className="pcard-ex">
<div className="pcard-ex-r"><span className="pcard-ex-n">{exName(e.id)}</span><span className="pcard-ex-l">{exLine(e, unit)}</span></div>
{!!e.why && <div className="pcard-ex-w">{e.why}</div>}
</div>)}
</div>
/* ---------------------------------- a review ---------------------------------- */
function ReviewCard({ p, S, update, toast, refresh }) {
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 => {
const res = applyChangeSet(s, marked, ids)
appendChat(s, { role: 'coach', kind: 'applied', ref: res.logId, text: t(ids.length === 1 ? 'Applied {0} change to your plan.' : 'Applied {0} changes to your plan.', ids.length) })
})
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))
refresh()
} 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 => { const ref = recordDismissal(s, marked); appendChat(s, { role: 'coach', kind: 'dismissed', ref, text: t('Understood — I will not suggest these again without new evidence.') }) })
resolvePending({ dismissed: true }).catch(() => {})
refresh()
}
})
return <div className="msg coach" style={{ maxWidth: '100%', width: '100%' }}>
<div className="pcard">
<div className="pcard-hd">
<div className="pcard-eyebrow">{t('Suggestions')}</div>
<h2 className="pcard-h">{t(marked.changes.length === 1 ? '{0} suggestion' : '{0} suggestions', marked.changes.length)}</h2>
{!!marked.summary && <p className="pcard-sum">{marked.summary}</p>}
{!!marked.evidence?.sessions && <p className="pcard-sum" style={{ fontSize: 13 }}>
{t('Based on your last {0} sessions', marked.evidence.sessions)}{marked.evidence.from ? ` · ${fmtDate(marked.evidence.from)} – ${fmtDate(marked.evidence.to)}` : ''}
</p>}
{marked.planMoved && <p className="pcard-sum" style={{ fontSize: 13, color: 'var(--yellow)' }}>
{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.')}
</p>}
</div>
<Insights S={S} window={marked.evidence} />
{marked.changes.map(c => {
const stale = c.status === 'stale'
return <ChangeRow key={c.id} c={c} S={S} stale={stale}>
{!stale && <Check checked={accepted.has(c.id)} onChange={() => toggle(c.id)} />}
</ChangeRow>
})}
<Notes notes={marked.notes} />
<div className="pcard-note">{t('The Coach is not a doctor or a physiotherapist. If something hurts, ask a professional.')}</div>
<div className="pcard-ft">
<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>
<Button onClick={discard}>{t('Dismiss all')}</Button>
</div>
</div>
</div>
}
function ChangeRow({ c, S, stale, badge, children }) {
const vals = changeValues(c, S)
return <div className={'pcard-chg' + (stale ? ' stale' : '') + (c.status === 'rejected' ? ' declined' : '')}>
<div className="grow">
<div className="pcard-chg-t">{changeTitle(c, S)}{c.routineName ? <span className="dim" style={{ fontWeight: 400 }}> · {c.routineName}</span> : null}</div>
{vals && <div className="pcard-chg-v"><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="pcard-chg-w">{c.why}</div>
{stale && <div className="pcard-chg-stale">{t('Doesn’t match your plan any more — can’t be applied.')}</div>}
</div>
{badge}
{children}
</div>
}
const Notes = ({ notes }) => !!notes?.length && <div className="pcard-notes">
{notes.map((n, i) => <div key={i}><Icon name="lightbulb" />{n}</div>)}
</div>
/* ---------------------------------- insights ---------------------------------- */
const BP_LABEL = { back: 'Back muscles', cardio: 'Cardio', chest: 'Chest', 'lower arms': 'Forearms', 'lower legs': 'Calves', neck: 'Neck', shoulders: 'Shoulders', 'upper arms': 'Arms', 'upper legs': 'Legs', waist: 'Core', other: 'Other' }
const bpLabel = bp => t(BP_LABEL[bp] || bp)
/**
* The numbers the Coach read, drawn: how much and how often, where the body weight went,
* which lifts moved, which body parts got the work. Computed on the device for the window the
* proposal names, so the picture under a suggestion is the evidence behind it, not decoration.
*/
function Insights({ S, window: win, compact }) {
const ins = useMemo(() => insightsFor(S, win || {}), [S, win?.from, win?.to])
if (!ins.sessions && !ins.bodyweight.points.length) return null
const maxBp = ins.bodyParts[0]?.sets || 1
const bw = ins.bodyweight
return <div className="ins">
<div className="ins-tiles">
<Tile v={ins.sessions} l={t('Sessions')} />
<Tile v={ins.minutes != null ? ins.minutes : '—'} l={t('Min / session')} />
<Tile v={ins.volume ? kfmt(ins.volume) : '—'} l={t('Volume ({0})', S.unit)} />
<Tile v={ins.sets} l={t('Sets')} />
</div>
{bw.points.length > 1 && <div className="ins-block">
<div className="ins-h">
<span>{t('Body weight')}</span>
<span className={'ins-delta' + (bw.delta > 0 ? ' up' : bw.delta < 0 ? ' down' : '')}>
{bw.delta > 0 ? '+' : ''}{fmtNum(bw.delta)} {S.unit}{bw.goal != null ? ` · ${t('goal')} ${fmtNum(bw.goal)}` : ''}
</span>
</div>
<div className="chart"><LineChart points={bw.points} h={compact ? 96 : 120} unit={S.unit} goal={bw.goal} axes={!compact} /></div>
</div>}
{!!ins.strength.length && <div className="ins-block">
<div className="ins-h"><span>{t('Estimated 1RM')}</span><span className="dim">{t('first → last session')}</span></div>
{ins.strength.map(x => <div key={x.id} className="ins-row">
<span className="ins-row-n">{x.name}</span>
<span className="ins-row-v"><span className="tag">{fmtNum(x.first)}</span><Icon name="chevronRight" /><span className="tag acc">{fmtNum(x.last)}</span></span>
<span className={'ins-delta' + (x.delta > 0 ? ' up' : x.delta < 0 ? ' down' : '')}>{x.delta > 0 ? '▲' : x.delta < 0 ? '▼' : '•'} {Math.abs(x.pct)}%</span>
</div>)}
</div>}
{!!ins.bodyParts.length && !compact && <div className="ins-block">
<div className="ins-h"><span>{t('Work sets by body part')}</span></div>
{ins.bodyParts.slice(0, 6).map(b => <div key={b.bp} className="ins-bar">
<span className="ins-bar-l">{bpLabel(b.bp)}</span>
<span className="ins-bar-t"><i style={{ width: Math.max(4, Math.round(b.sets / maxBp * 100)) + '%' }} /></span>
<span className="ins-bar-v">{b.sets}</span>
</div>)}
</div>}
</div>
}
const Tile = ({ v, l }) => <div className="ins-tile"><div className="ins-tile-v">{v}</div><div className="ins-tile-l">{l}</div></div>
const kfmt = n => (n >= 10000 ? Math.round(n / 1000) + 'k' : fmtNum(n))
/* ---------------------------------- a debrief ---------------------------------- */
function DebriefBody({ p, S }) {
const w = p.workout || {}
const live = useMemo(() => sessionInsights(S, (S.workouts || []).find(x => x.id === w.id) || null), [S, w.id])
const score = Number.isFinite(p.score) ? Math.max(1, Math.min(10, p.score)) : null
return <>
{score != null && <div className="deb-score">
<div className="deb-ring" style={{ '--pct': score / 10 }}><span>{score}</span><small>/10</small></div>
<div className="deb-score-t"><b>{scoreWord(score)}</b><span>{w.name || t('Workout')}{w.d ? ' · ' + fmtDate(w.d) : ''}</span></div>
</div>}
{live && <div className="ins">
<div className="ins-tiles">
<Tile v={live.now.sets} l={t('Sets')} />
<Tile v={live.now.minutes != null ? live.now.minutes : '—'} l={t('Minutes')} />
<Tile v={live.now.volume ? kfmt(live.now.volume) : '—'} l={t('Volume ({0})', S.unit)} />
<Tile v={live.now.prs || '—'} l={t('PRs')} />
</div>
{live.then && <div className="ins-cmp">
{t('vs. last {0} on {1}:', w.name || t('session'), fmtDate(live.prevDate))}{' '}
<Delta v={live.now.volume - live.then.volume} unit={S.unit} label={t('volume')} />
{live.now.minutes != null && live.then.minutes != null && <Delta v={live.now.minutes - live.then.minutes} unit="min" label={t('time')} />}
</div>}
{!!live.lifts.length && <div className="ins-block">
<div className="ins-h"><span>{t('Best set, estimated 1RM')}</span></div>
{live.lifts.slice(0, 6).map(x => <div key={x.id} className="ins-row">
<span className="ins-row-n">{x.name} <span className="dim">{fmtNum(x.w)}×{x.r}</span></span>
<span className="ins-row-v"><span className="tag acc">{fmtNum(x.est)}</span></span>
{x.prev != null && <span className={'ins-delta' + (x.est > x.prev ? ' up' : x.est < x.prev ? ' down' : '')}>{x.est > x.prev ? '▲' : x.est < x.prev ? '▼' : '•'} {fmtNum(Math.abs(x.est - x.prev))}</span>}
</div>)}
</div>}
</div>}
<DebriefList icon="checkCircle" tint="var(--green)" title={t('What went well')} items={p.highlights} />
<DebriefList icon="warning" tint="var(--yellow)" title={t('Worth watching')} items={p.watch} />
<DebriefList icon="arrowUp" tint="var(--acc)" title={t('Next time')} items={p.nextTime} />
</>
}
const Delta = ({ v, unit, label }) => <span className={'ins-delta' + (v > 0 ? ' up' : v < 0 ? ' down' : '')}>{v > 0 ? '+' : ''}{fmtNum(v)} {unit} {label}</span>
const DebriefList = ({ icon, tint, title, items }) => !!items?.length && <div className="deb-list">
<div className="deb-list-h" style={{ color: tint }}><Icon name={icon} />{title}</div>
{items.map((x, i) => <div key={i} className="deb-item">{x}</div>)}
</div>
const scoreWord = s => s >= 9 ? t('Excellent session') : s >= 7 ? t('Good session') : s >= 5 ? t('Solid session') : t('Tough session')
function DebriefCard({ p, S, update, toast, refresh }) {
const done = () => {
update(s => { const ref = recordDebrief(s, p); appendChat(s, { role: 'coach', kind: 'debrief', ref, text: '' }) })
resolvePending({ accepted: ['debrief'] }).catch(() => {})
toast(t('Kept in your Coach history'))
refresh()
}
return <div className="msg coach" style={{ maxWidth: '100%', width: '100%' }}>
<div className="pcard">
<div className="pcard-hd">
<div className="pcard-eyebrow">{t('Workout debrief')}</div>
<h2 className="pcard-h">{p.workout?.name || t('Your last workout')}</h2>
{!!p.summary && <p className="pcard-sum">{p.summary}</p>}
</div>
<DebriefBody p={p} S={S} />
<div className="pcard-ft">
<Button variant="primary" icon="check" onClick={done}>{t('Got it')}</Button>
</div>
</div>
<div className="msg-t">{t('Want changes to the plan from this? Ask for a review below.')}</div>
</div>
}
/* ---------------------------------- what was decided ---------------------------------- */
/** A decided proposal, folded: one line of what it was and what you did, and a way back in. */
function Recap({ entry, S, openSheet }) {
const open = () => openSheet(() => <ProposalDetail entry={entry} S={S} />)
const decisions = entry.decisions || []
const acc = decisions.filter(d => d.status === 'accepted').length
const rej = decisions.length - acc
const kind = entry.kind
const eyebrow = kind === 'create' ? t('Plan') : kind === 'debrief' ? t('Workout debrief') : t('Suggestions')
const state = kind === 'debrief' ? null
: entry.dismissed ? { cls: 'no', text: t('Declined') }
: kind === 'create' ? { cls: 'yes', text: t('Imported') }
: rej ? { cls: 'mix', text: t('{0} accepted · {1} declined', acc, rej) } : { cls: 'yes', text: t('{0} accepted', acc) }
const title = kind === 'create' ? (entry.bundle?.name || t('Coach plan'))
: kind === 'debrief' ? (entry.workout?.name || t('Workout')) + (entry.score != null ? ` · ${entry.score}/10` : '')
: t(decisions.length === 1 ? '{0} suggestion' : '{0} suggestions', decisions.length)
return <button className="recap" onClick={open}>
<div className="recap-top">
<span className="pcard-eyebrow">{eyebrow}</span>
{state && <span className={'recap-state ' + state.cls}>{state.text}</span>}
</div>
<div className="recap-t">{title}</div>
{!!entry.summary && <div className="recap-s">{entry.summary}</div>}
{kind === 'review' && !!decisions.length && <div className="recap-chips">
{decisions.slice(0, 4).map(d => <span key={d.id} className={'recap-chip ' + (d.status === 'accepted' ? 'yes' : 'no')}><Icon name={d.status === 'accepted' ? 'check' : 'xmark'} />{changeTitle(d, S)}</span>)}
{decisions.length > 4 && <span className="recap-chip">+{decisions.length - 4}</span>}
</div>}
<div className="recap-more">{t('Show everything')}<Icon name="chevronRight" /></div>
</button>
}
/** The whole proposal, as it was, read-only. */
function ProposalDetail({ entry, S }) {
const [tab, setTab] = useState(0)
const kind = entry.kind
const b = entry.bundle
const r = b?.routines?.[Math.min(tab, (b?.routines?.length || 1) - 1)]
const weekDays = useMemo(() => new Set(Object.keys(b?.week || {}).map(Number)), [b])
return <div className="pdetail">
<div className="pcard-hd" style={{ paddingLeft: 0, paddingRight: 0 }}>
<div className="pcard-eyebrow">{kind === 'create' ? t('Plan') : kind === 'debrief' ? t('Workout debrief') : t('Suggestions')} · {fmtDate(new Date(entry.at).toISOString().slice(0, 10))}</div>
<h2 className="pcard-h">{kind === 'create' ? (b?.name || t('Coach plan')) : kind === 'debrief' ? (entry.workout?.name || t('Workout')) : t(entry.decisions?.length === 1 ? '{0} suggestion' : '{0} suggestions', entry.decisions?.length || 0)}</h2>
{!!entry.summary && <p className="pcard-sum">{entry.summary}</p>}
{entry.dismissed && <p className="pcard-sum" style={{ color: 'var(--red)' }}>{t('You declined this.')}</p>}
{!!entry.evidence?.sessions && <p className="pcard-sum" style={{ fontSize: 13 }}>
{t('Based on your last {0} sessions', entry.evidence.sessions)}{entry.evidence.from ? ` · ${fmtDate(entry.evidence.from)} – ${fmtDate(entry.evidence.to)}` : ''}
</p>}
</div>
{kind === 'review' && <>
<Insights S={S} window={entry.evidence} />
{(entry.decisions || []).map(d => <ChangeRow key={d.id} c={d} S={S} stale={d.status === 'stale'}
badge={<span className={'recap-state ' + (d.status === 'accepted' ? 'yes' : 'no')}>{d.status === 'accepted' ? t('Accepted') : d.status === 'stale' ? t('Expired') : t('Declined')}</span>} />)}
<Notes notes={entry.notes} />
</>}
{kind === 'create' && b && <>
<WeekStrip days={weekDays} />
{b.routines.length > 1 && <div className="pcard-tabs" style={{ paddingLeft: 0, paddingRight: 0 }}>
{b.routines.map((x, i) => <button key={x.id || i} className={'pcard-tab' + (i === tab ? ' on' : '')} onClick={() => setTab(i)}>{x.emoji} {x.name}</button>)}
</div>}
{r && <RoutineBlock r={r} unit={S.unit} />}
<p className="pcard-sum" style={{ fontSize: 13 }}>{entry.scheduled ? t('Your week was set to this schedule.') : t('Imported without changing your week.')}</p>
</>}
{kind === 'create' && !b && <p className="pcard-sum">{t('This plan was imported before the app kept proposals; only its summary is left.')}</p>}
{kind === 'debrief' && <DebriefBody p={entry} S={S} />}
{kind === 'revert' && <p className="pcard-sum">{t('Reverted the last Coach changes.')}</p>}
<div style={{ height: 10 }} />
</div>
}
/** Every proposal ever made, newest first. Nothing the Coach said is gone after a decision. */
function HistorySheet({ S, close, openSheet }) {
const log = [...(S.coach?.log || [])].reverse()
const icon = { create: ['clipboard', 'var(--indigo)'], review: ['sparkles', 'var(--acc)'], debrief: ['checkCircle', 'var(--green)'], revert: ['reset', 'var(--blue)'] }
return <div className="chat-menu">
<h3>{t('Everything the Coach proposed')}</h3>
{!log.length && <div className="chat-empty">{t('Nothing yet. Every plan, suggestion and debrief will be kept here — whether you said yes or no.')}</div>}
<div className="sect-b">
{log.map(e => {
const [ic, tint] = icon[e.kind] || ['sparkles', 'var(--acc)']
const n = (e.decisions || []).length
const acc = (e.decisions || []).filter(d => d.status === 'accepted').length
const title = e.kind === 'create' ? (e.bundle?.name || t('Coach plan')) + (e.iteration > 1 ? ` · ${t('Revision {0}', e.iteration)}` : '')
: e.kind === 'debrief' ? t('Debrief: {0}', e.workout?.name || t('Workout')) + (e.score != null ? ` · ${e.score}/10` : '')
: e.kind === 'revert' ? t('Reverted the last Coach changes.')
: t(n === 1 ? '{0} suggestion' : '{0} suggestions', n)
const sub = fmtDate(new Date(e.at).toISOString().slice(0, 10)) + ' · ' + (e.kind === 'debrief' ? String(e.summary || '').slice(0, 60)
: e.dismissed ? t('Declined') : e.kind === 'create' ? t('Imported') : e.kind === 'revert' ? '' : t('{0} accepted · {1} declined', acc, n - acc))
return <Row key={e.id} icon={ic} iconTint={tint} title={title} subtitle={sub} accessory="chevron"
onClick={() => { close(); openSheet(() => <ProposalDetail entry={e} S={S} />) }} />
})}
</div>
<div style={{ height: 10 }} />
</div>
}
/* ---------------------------------- the others here ---------------------------------- */
/**
* How you sit against everyone else on this instance — medians only, at least three people
* sharing, nothing that identifies anyone. The admin turns it on for the instance; each person
* turns it on for themselves; a person who does not share sees nothing either.
*/
function CohortSheet({ S, update, toast }) {
const [d, setD] = useState(null)
const [busy, setBusy] = useState(false)
const load = () => cohortStats().then(setD).catch(e => { toast(e.message || t('Could not load')); setD({ ok: false }) })
useEffect(() => { load() }, [])
const share = async v => {
setBusy(true)
try { await setCohortShare(v); update(s => { (s.coach = s.coach || emptyCoach()).share = v }); await load() }
catch (e) { toast(e.message || t('Could not save')) }
setBusy(false)
}
const sharing = !!d?.sharing
return <div className="chat-menu">
<h3>{t('Compare with others here')}</h3>
<Section footer={t('Only medians across everyone who shares, never a name, a body weight or a single session. Turning this off removes you from the numbers immediately.')}>
<Row icon="person" iconTint="var(--teal)" title={t('Include me')} subtitle={sharing ? t('Your lifts count towards the medians') : t('Off — you see nothing and share nothing')}>
<Switch checked={sharing} disabled={busy || !d} onChange={share} />
</Row>
</Section>
{!d && <div className="chat-empty">{t('Loading…')}</div>}
{d && sharing && !d.ok && <div className="chat-empty">{d.people != null
? t('Not enough people share yet — {0} of {1} needed. Ask your gym mates.', d.people, d.minPeople)
: t('Not available right now.')}</div>}
{d && sharing && d.ok && <div className="ins" style={{ padding: 0 }}>
<div className="ins-tiles">
<Tile v={d.people} l={t('People')} />
<Tile v={fmtNum(d.sessionsPerWeek.you)} l={t('Your sessions / wk')} />
<Tile v={fmtNum(d.sessionsPerWeek.median)} l={t('Median / wk')} />
<Tile v={d.rankPct != null ? d.rankPct + '%' : '—'} l={t('Your strength rank')} />
</div>
{!!d.exercises.length && <div className="ins-block">
<div className="ins-h"><span>{t('Estimated 1RM, you vs. median')}</span><span className="dim">{S.unit}</span></div>
{d.exercises.map(x => {
const max = Math.max(x.median, x.you || 0) || 1
return <div key={x.id} className="cmp">
<div className="cmp-h"><span>{x.name}</span><span className="dim">{x.people} {t('people')}</span></div>
<div className="cmp-bar you"><i style={{ width: Math.round((x.you || 0) / max * 100) + '%' }} /><span>{t('You')} · {x.you != null ? fmtNum(x.you) : '—'}</span></div>
<div className="cmp-bar"><i style={{ width: Math.round(x.median / max * 100) + '%' }} /><span>{t('Median')} · {fmtNum(x.median)}</span></div>
</div>
})}
</div>}
{!d.exercises.length && <div className="chat-empty">{t('No exercise is trained by three or more people yet.')}</div>}
</div>}
<div style={{ height: 10 }} />
</div>
}
/* ---------------------------------- cadence ---------------------------------- */
const cadenceLabel = coach => {
const c = coach.cadence && coach.cadence !== 'off' ? coach.cadence : null
if (!c) return t('Off')
if (c.weekly) return t('Weekly')
return t('After every few workouts')
}
function cadenceSheet(openSheet, update) {
openSheet(close => <CadenceSheet close={close} update={update} />)
}
function CadenceSheet({ update }) {
const coach = useStore(s => s.S.coach) || emptyCoach()
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 <>
<h3>{t('Automatic reviews')}</h3>
<Section 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>
</>
}
+212
View File
@@ -0,0 +1,212 @@
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 CoachChat from './CoachChat.jsx'
import { effectiveRoutine } from '../lib/history.js'
import { todayISO } from '../lib/format.js'
// The chat is where a plan is imported. These pin that the Import button applies the pending
// plan through the store, writes the decision into the thread, and leaves today startable.
const mocks = vi.hoisted(() => {
const state = { S: null, pending: null, job: null, community: false, nav: vi.fn(), toast: vi.fn(), openSheet: vi.fn(), refresh: vi.fn() }
state.storeSnapshot = () => ({
S: state.S,
user: { id: 'u1' },
ready: true,
config: { coach: { enabled: true, ...(state.community ? { community: true } : {}) } },
coachLocal: null,
update: mut => mut(state.S),
})
state.uiSnapshot = () => ({ toast: state.toast, openSheet: state.openSheet })
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, job: mocks.job, cap: null, loading: false, lastError: null, last: null, refresh: mocks.refresh }),
resolvePending: vi.fn(() => Promise.resolve({})),
refinePlan: vi.fn(() => Promise.resolve({})),
requestReview: vi.fn(() => Promise.resolve({})),
requestDebrief: vi.fn(() => Promise.resolve({})),
cohortStats: vi.fn(() => Promise.resolve({ ok: false, enabled: true, sharing: false })),
setCohortShare: vi.fn(() => Promise.resolve({ ok: true, sharing: true })),
JOB_ERRORS: { internal: 'x' },
}))
vi.mock('../sheets.jsx', () => ({ startFlow: vi.fn(), confirmSheet: vi.fn() }))
vi.mock('../lib/api.js', () => ({
api: vi.fn(() => Promise.resolve({})),
IS_APPLE: false, IS_ANDROID: false, BIO: 'biometrics',
}))
vi.mock('../coach.css', () => ({}))
let dom, root, container
const TODAY_WD = new Date(todayISO() + 'T12:00:00').getDay()
const bundle = week => ({
opengym_plan: 1, name: 'Coach plan', summary: 'a plan',
week,
routines: [
{ id: 'x1', name: 'Full body A', emoji: '💪', why: 'first', ex: [{ id: '0001', sets: 3, reps: 10, mode: 'reps', why: 'because' }] },
{ id: 'x2', name: 'Full body B', emoji: '🏋️', ex: [{ id: '0002', sets: 3, reps: 8, 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 },
profile: { goal: 'muscle', experience: 'new', daysPerWeek: 3, sessionMin: 60, preferredDays: [1, 3, 5], equipment: [] },
log: [], snapshots: [], chat: [{ id: 'c1', role: 'user', kind: 'intake', at: 1 }], timings: []
},
})
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, job = null, { community = false, S = state() } = {}) {
mocks.S = S
mocks.pending = pending
mocks.job = job
mocks.community = community
installDom()
await act(async () => { root.render(React.createElement(CoachChat)) })
}
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('the Coach chat', () => {
it('opens with the questionnaire summary and pitches the plan as a card with routine tabs', async () => {
await mount({ id: 'p1', kind: 'create', bundle: bundle(everyDay) })
expect(container.textContent).toContain('Build muscle')
expect(container.textContent).toContain('3 days a week')
expect(container.querySelectorAll('.pcard-tab').length).toBe(2)
expect(container.textContent).toContain('because')
await click([...container.querySelectorAll('.pcard-tab')][1])
expect(container.querySelector('.pcard-rt-h b').textContent).toContain('Full body B')
})
it('imports the plan through the store, records it in the thread, and leaves today startable', async () => {
await mount({ id: 'p1', kind: 'create', bundle: bundle(everyDay) })
await click(byText(/Import this plan/))
const s = mocks.S
expect(s.routines.length).toBe(2)
expect(s.week[TODAY_WD]).toBeTruthy()
const todays = effectiveRoutine(s, todayISO())
expect(todays && todays.ex.length).toBeGreaterThan(0)
expect(s.coach.chat.at(-1).kind).toBe('applied')
expect(s.coach.snapshots).toHaveLength(1)
expect(mocks.refresh).toHaveBeenCalled()
})
it('leaves the week alone when the schedule switch is off', async () => {
await mount({ id: 'p1', kind: 'create', bundle: bundle(everyDay) })
const sw = container.querySelector('[role="switch"]')
expect(sw.getAttribute('aria-checked')).toBe('true')
await click(sw)
await click(byText(/Import this plan/))
expect(Object.keys(mocks.S.week)).toHaveLength(0)
expect(mocks.S.routines.length).toBe(2)
})
it('shows the typing bubble with an estimate while a job runs, and disables the composer', async () => {
await mount(null, { id: 'j1', kind: 'create', state: 'running', startedAt: Date.now() })
expect(container.querySelector('.typing')).toBeTruthy()
expect(container.textContent).toContain('usually takes')
expect(container.querySelector('.composer textarea').disabled).toBe(true)
})
it('applies the accepted subset of a review and logs it', async () => {
mocks.S = state()
await mount({ id: 'r1', kind: 'review', summary: 's', changes: [
{ id: 'a', type: 'week', target: { weekday: 1 }, before: null, after: null, why: 'rest' },
{ id: 'b', type: 'add-routine', target: {}, before: null, after: { name: 'Legs', ex: [{ id: '0001', sets: 3, reps: 10 }] }, why: 'legs' }
] })
expect(container.querySelectorAll('[role="checkbox"]').length).toBe(2)
await click([...container.querySelectorAll('[role="checkbox"]')][0]) // drop the week change
await click(byText(/Apply 1 change/))
expect(mocks.S.routines.map(r => r.name)).toEqual(['Legs'])
expect(mocks.S.coach.chat.at(-1).kind).toBe('applied')
expect(mocks.S.coach.log.at(-1).decisions.map(d => d.status)).toEqual(['accepted', 'rejected'])
})
it('keeps an applied review in the thread as a card that opens the whole proposal', async () => {
await mount({ id: 'r1', kind: 'review', summary: 'a reading', changes: [
{ id: 'a', type: 'week', target: { weekday: 1 }, before: null, after: null, why: 'rest' },
{ id: 'b', type: 'add-routine', target: {}, before: null, after: { name: 'Legs', ex: [{ id: '0001', sets: 3, reps: 10 }] }, why: 'legs' }
] })
await click([...container.querySelectorAll('[role="checkbox"]')][0])
await click(byText(/Apply 1 change/))
// The decision is in the store; re-render with the proposal gone, as the poll would.
mocks.pending = null
await act(async () => { root.render(React.createElement(CoachChat)) })
const recap = container.querySelector('.recap')
expect(recap).toBeTruthy()
expect(recap.textContent).toContain('1 accepted · 1 declined')
expect(recap.querySelectorAll('.recap-chip.yes').length).toBe(1)
expect(recap.querySelectorAll('.recap-chip.no').length).toBe(1)
expect(mocks.S.coach.chat.at(-1).ref).toBe(mocks.S.coach.log.at(-1).id)
await click(recap)
expect(mocks.openSheet).toHaveBeenCalled()
})
it('shows a debrief with its score ring and files it on "Got it"', async () => {
await mount({ id: 'd1', kind: 'debrief', workout: { id: 'w1', name: 'Push', d: '2026-08-29' }, summary: 'ok', score: 8, highlights: ['a'], watch: [], nextTime: ['b'] })
expect(container.querySelector('.deb-ring')).toBeTruthy()
expect(container.textContent).toContain('Good session')
expect(container.textContent).toContain('What went well')
expect(container.textContent).not.toContain('Worth watching')
await click(byText(/Got it/))
expect(mocks.S.coach.log.at(-1).kind).toBe('debrief')
expect(mocks.S.coach.log.at(-1).score).toBe(8)
expect(mocks.S.coach.chat.at(-1).kind).toBe('debrief')
expect(mocks.S.coach.chat.at(-1).ref).toBe(mocks.S.coach.log.at(-1).id)
})
it('offers the quick actions only when nothing is running', async () => {
await mount(null)
expect(byText(/Review my training/)).toBeTruthy()
expect(byText(/Last workout/)).toBeFalsy() // no workout logged yet
await mount(null, { id: 'j1', kind: 'review', state: 'running', startedAt: Date.now() })
expect(byText(/Review my training/)).toBeFalsy()
})
it('offers the comparison only when the instance allows it', async () => {
await mount(null)
expect(byText(/^Compare$/)).toBeFalsy()
await mount(null, null, { community: true })
expect(byText(/^Compare$/)).toBeTruthy()
})
})
+260
View File
@@ -0,0 +1,260 @@
// 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 } from '../lib/coach.js'
import { requestPlan, disclosure } 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 } from '../components/ui.jsx'
import '../coach.css'
const GOALS = [
['strength', 'Get stronger', 'Heavier lifts, lower reps.', 'barbell'],
['muscle', 'Build muscle', 'Volume and progression.', 'arm'],
['general', 'General fitness', 'Balanced, sustainable training.', 'heart'],
['fatloss', 'Lose fat', 'Keep strength while leaning out.', 'flame'],
['endurance', 'Endurance', 'Higher reps, less rest, cardio.', 'figureRun']
]
const EXPERIENCE = [
['new', 'New to lifting', 'First months in the gym.', 'sparkles'],
['returning', 'Coming back after a break', 'You know the movements; the numbers need rebuilding.', 'reset'],
['regular', 'Training regularly', '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 toHHMM = min => String(Math.floor(min / 60)).padStart(2, '0') + ':' + String(min % 60).padStart(2, '0')
const fromHHMM = v => { const [h, m] = String(v || '').split(':').map(Number); return Number.isFinite(h) && Number.isFinite(m) ? h * 60 + m : null }
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))
const STEPS = [...(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: [1, 3, 5],
sessionMin: 60, equipment: [], limitations: '', likes: '', dislikes: '', notes: '',
...(S.coach?.profile || {})
}))
const set = patch => setP(v => ({ ...v, ...patch }))
if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE, coachMode })) { nav('/home', { replace: true }); 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 = () => {
update(s => { s.coach = { ...(s.coach || emptyCoach()), consent: { agreedAt: new Date().toISOString(), version: CONSENT_VERSION } } })
setStep(step + 1)
}
const finish = async () => {
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.
if (!editing || !(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) { 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]
})
const dots = STEPS.filter(s => s !== 'consent')
const dotIndex = dots.indexOf(key)
return <div className="narrow ob">
<div className="ob-top">
<button className="iconbtn" 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, label, sub, icon]) => <Choice key={v} on={p.goal === v} icon={icon} title={t(label)} sub={t(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, label, sub, icon]) => <Choice key={v} on={p.experience === v} icon={icon} title={t(label)} sub={t(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>
<div className="ob-days">
{[1, 2, 3, 4, 5, 6, 7].map(n => <button key={n} className={'ob-day' + (p.daysPerWeek === n ? ' on' : '')} onClick={() => set({ daysPerWeek: n })}>{n}</button>)}
</div>
<div className="ob-sub">{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' : '')} onClick={() => toggleDay(d)}>{t(DAYN[d]).slice(0, 2)}</button>)}
</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 — so two wheels (hours, minutes in fives), never the
native time input, which insists on AM/PM. */}
<div className="ob-time" role="group" aria-label={t('How long is a session?')}>
<select className="ob-wheel" value={Math.floor((p.sessionMin || 60) / 60)}
onChange={e => set({ sessionMin: (+e.target.value) * 60 + ((p.sessionMin || 60) % 60) || 5 })}>
{[0, 1, 2, 3].map(h => <option key={h} value={h}>{String(h).padStart(2, '0')}</option>)}
</select>
<span className="ob-time-sep">:</span>
<select className="ob-wheel" value={(p.sessionMin || 60) % 60}
onChange={e => set({ sessionMin: Math.floor((p.sessionMin || 60) / 60) * 60 + (+e.target.value) || 5 })}>
{[0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55].map(m => <option key={m} value={m}>{String(m).padStart(2, '0')}</option>)}
</select>
<span className="ob-time-l">{t('h:mm')}</span>
</div>
<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)}>{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 cannot 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?.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>{t(title)}</b><span>{t(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}>{t('I understand — let’s go')}</Button>
<Button onClick={onDecline}>{t('Not now')}</Button>
</div>
</>
}
+191
View File
@@ -0,0 +1,191 @@
// Mobile build only: how the Coach should run on this phone.
//
// Two answers. "Use my self-hosted openGym" hands the whole thing to the paired server — the
// same Coach the web app has, with whatever provider its admin configured; the phone only has
// to be paired. "Bring my own API key" runs the pipeline on the phone against Anthropic,
// OpenAI, Gemini or an OpenAI-compatible endpoint, with a key that stays in secure storage.
//
// The promise this screen keeps: nothing AI-shaped is loaded until a mode is chosen. Its only
// imports from the Coach core are the provider table and the five category names — the
// catalogue, the prompts and the validator arrive through one dynamic import, behind a
// progress line that reports real steps rather than a pretend byte counter.
import { useEffect, 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 { MOBILE } from '../lib/mobile.js'
import { CATEGORY_TEXT } from '../lib/coach.js'
import { getApiKey, setApiKey, clearApiKey } from '../lib/coach-secrets.js'
import { HTTP_PROVIDERS, HTTP_PROVIDER_IDS, baseUrlFor, validateBaseUrl } from '../../../api/coach/core/providers.js'
import { DATA_CATEGORIES } from '../../../api/coach/core/categories.js'
import { ConnectSheet } from './MobileOnboarding.jsx'
import Icon from '../components/Icon.jsx'
import { Section, Row, Button, TextField } from '../components/ui.jsx'
const STEPS = ['Loading the exercise catalogue…', 'Checking the endpoint…', 'Ready']
export default function CoachSetup() {
const nav = useNavigate()
const user = useStore(s => s.user)
const config = useStore(s => s.config)
const coachLocal = useStore(s => s.coachLocal)
const setCoachLocal = useStore(s => s.setCoachLocal)
const refreshConfig = useStore(s => s.refreshConfig)
const toast = useUI(s => s.toast)
const openSheet = useUI(s => s.openSheet)
const [choice, setChoice] = useState(null) // 'server' | 'byok' | null
const [provider, setProvider] = useState(coachLocal?.provider || 'anthropic')
const [baseUrl, setBaseUrl] = useState(coachLocal?.baseUrl || '')
const [model, setModel] = useState(coachLocal?.model || '')
const [key, setKey] = useState('')
const [hasKey, setHasKey] = useState(false)
const [models, setModels] = useState(null)
const [step, setStep] = useState(-1) // -1 idle, 0..2 running, 3 done
const [busy, setBusy] = useState(false)
useEffect(() => { if (!MOBILE) nav('/settings', { replace: true }) }, [])
useEffect(() => { getApiKey().then(k => setHasKey(!!k)) }, [])
// Ask the paired server afresh: the admin may have switched the Coach on since this phone booted.
useEffect(() => { if (user) refreshConfig() }, [user])
useEffect(() => { setModels(null); setModel(coachLocal?.provider === provider ? (coachLocal?.model || '') : '') }, [provider])
const meta = HTTP_PROVIDERS[provider] || {}
const host = hostOf(baseUrlFor(provider, { providerOptions: { [provider]: { baseUrl } } }))
const serverHasCoach = !!(user && config?.coach?.enabled)
const useServer = async () => {
if (!user) return openSheet(close => <ConnectSheet close={close} />)
await setCoachLocal({ mode: 'server' })
toast(t('The Coach is on'))
nav('/coach')
}
// The lazy load, and the reachability check, as three real steps.
const prepare = async () => {
const v = validateBaseUrl(meta.baseUrl ? baseUrl : '')
if (!v.ok) return toast(v.error)
if (!meta.keyOptional && !key.trim() && !hasKey) return toast(t('Enter your API key'))
setBusy(true); setStep(0)
try {
const local = await import('../lib/coach-local.js')
setStep(1)
const k = key.trim() || await getApiKey()
const r = await local.localModels({ provider, baseUrl: v.value }, k)
if (!r.ok) { setStep(-1); toast(t('Could not reach the provider: {0}', r.error)); return }
setModels(r.models)
setStep(2)
if (!model && meta.defaultModel && r.models.includes(meta.defaultModel)) setModel(meta.defaultModel)
} catch (e) {
setStep(-1); toast(e.message || t('Could not connect'))
} finally { setBusy(false) }
}
const save = async () => {
const chosen = model || meta.defaultModel
if (!chosen) return toast(t('Pick a model'))
setBusy(true)
try {
if (key.trim()) { await setApiKey(key.trim()); setHasKey(true); setKey('') }
await setCoachLocal({ mode: 'byok', provider, model: chosen, baseUrl: meta.baseUrl ? (validateBaseUrl(baseUrl).value || null) : null })
toast(t('The Coach is on'))
nav('/coach')
} finally { setBusy(false) }
}
const turnOff = async () => {
await clearApiKey(); setHasKey(false)
await setCoachLocal({ mode: 'off' })
const local = await import('../lib/coach-local.js').catch(() => null)
if (local) await local.localForget()
setChoice(null)
toast(t('The Coach is off'))
}
const current = coachLocal?.mode === 'server' ? t('Runs on your openGym server')
: coachLocal?.mode === 'byok' ? t('Runs on this phone with your own API key')
: t('Off — choose how the Coach should run.')
return <div className="narrow">
<div className="hdr">
<button className="iconbtn" onClick={() => nav('/settings')} aria-label={t('Back')}><Icon name="chevronLeft" /></button>
<div style={{ flex: 1, marginLeft: 10 }}><h1>{t('AI Coach')}</h1></div>
</div>
<Section title={t('How should the Coach run?')} footer={current}>
<Row icon="rocket" iconTint="var(--indigo)" title={t('Use my self-hosted openGym')}
subtitle={user ? (serverHasCoach ? t('Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.') : config == null ? t('Loading…') : t('Your server has no Coach enabled — ask its admin, or bring your own key below.')) : t('Connect to my server')}
accessory="chevron" onClick={() => { if (!user || serverHasCoach) useServer(); else setChoice('server') }} />
<Row icon="key" iconTint="var(--acc)" title={t('Bring my own API key')}
subtitle={t('This phone calls the provider directly with your key. Every request is charged to your account.')}
accessory="chevron" onClick={() => setChoice('byok')} />
</Section>
{choice === 'server' && !serverHasCoach && <div className="card">
<div className="muted small">{t('Your server has no Coach enabled — ask its admin, or bring your own key below.')}</div>
</div>}
{choice === 'byok' && <>
<Section title={t('Provider')}>
<div className="row" style={{ flexWrap: 'wrap', gap: 7, padding: '8px 12px' }}>
{HTTP_PROVIDER_IDS.map(id => <button key={id} className={'chip' + (id === provider ? ' on' : '')} disabled={busy}
onClick={() => setProvider(id)}>{HTTP_PROVIDERS[id].label}</button>)}
</div>
</Section>
{meta.baseUrl && <Section title={t('Endpoint')}>
<div style={{ padding: '8px 12px' }}>
<TextField value={baseUrl} placeholder="http://ollama.lan:11434" inputMode="url" autoCapitalize="none" autoCorrect="off"
onChange={e => setBaseUrl(e.target.value)} />
</div>
</Section>}
<Section title={t('API key')} footer={t('The key is stored in this phone’s secure storage and never leaves it except to call the provider.')}>
<div style={{ padding: '8px 12px' }}>
<TextField value={key} type="password" placeholder={hasKey ? '•••••••• ' + t('(saved)') : (meta.keyPlaceholder || 'sk-…')} autoCapitalize="none" autoCorrect="off"
onChange={e => setKey(e.target.value)} />
</div>
</Section>
<Section title={t('What leaves this phone')}>
{DATA_CATEGORIES.map(k => {
const [title, sub] = CATEGORY_TEXT[k] || [k, '']
return <Row key={k} icon="check" iconTint="var(--acc)" title={t(title)} subtitle={t(sub)} />
})}
</Section>
<p className="sect-f" style={{ marginTop: -18, marginBottom: 22, lineHeight: 1.5 }}>
{t('Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.', host || meta.label)}
</p>
{step >= 0 && <div className="card">
{STEPS.map((s, i) => <div key={s} className="row" style={{ gap: 8, padding: '3px 0', opacity: i > step ? .4 : 1 }}>
<span style={{ color: i < step || step === 2 ? 'var(--green)' : i === step ? 'var(--acc)' : 'var(--dim)' }}><Icon name={i < step || step === 2 ? 'check' : 'timer'} /></span>
<span className="small">{t(s)}</span>
</div>)}
</div>}
{models && <Section title={t('Model')}>
<div style={{ padding: '8px 12px' }}>
<select className="input" value={model} disabled={busy} onChange={e => setModel(e.target.value)} style={{ width: '100%' }}>
<option value="">{meta.defaultModel ? `(${meta.defaultModel})` : t('Pick a model')}</option>
{models.map(m => <option key={m} value={m}>{m}</option>)}
</select>
</div>
</Section>}
<div className="row" style={{ gap: 8, flexWrap: 'wrap' }}>
{!models
? <Button variant="primary" icon="sparkles" disabled={busy} onClick={prepare}>{t('List models')}</Button>
: <Button variant="primary" icon="check" disabled={busy} onClick={save}>{t('Save and use the Coach')}</Button>}
{models && <Button disabled={busy} onClick={prepare}>{t('List models')}</Button>}
</div>
</>}
{coachLocal?.mode && coachLocal.mode !== 'off' && <Section title={t('Controls')}>
<Row icon="signOut" iconTint="var(--red)" title={t('Turn the Coach off on this phone')} danger onClick={turnOff} />
</Section>}
</div>
}
const hostOf = url => { try { return new URL(url).host } catch { return '' } }
+25
View File
@@ -0,0 +1,25 @@
// The setup screen's one promise that is easy to break by accident: nothing AI-shaped loads
// until a mode is chosen. Asserted on the source, the way coach.test.js pins the store field —
// a static import of the core here would pass every behavioural test and still ship the
// catalogue, the prompts and the validator to a phone that never asked for a Coach.
import { describe, it, expect } from 'vitest'
import { readFileSync } from 'node:fs'
const src = readFileSync(new URL('./CoachSetup.jsx', import.meta.url), 'utf8')
const statics = [...src.matchAll(/^import .* from '([^']+)'/gm)].map(m => m[1])
describe('CoachSetup keeps the core out until a mode is chosen', () => {
it('imports only the provider table and the category names from the core', () => {
const core = statics.filter(p => p.includes('api/coach/core'))
expect(core.sort()).toEqual(['../../../api/coach/core/categories.js', '../../../api/coach/core/providers.js'])
})
it('never statically imports the phone pipeline', () => {
expect(statics.some(p => p.includes('coach-local'))).toBe(false)
expect(src).toMatch(/import\('\.\.\/lib\/coach-local\.js'\)/)
})
it('the categories module carries no catalogue', () => {
const cat = readFileSync(new URL('../../../api/coach/core/categories.js', import.meta.url), 'utf8')
expect(cat).not.toMatch(/^import /m)
expect(cat.length).toBeLessThan(1500)
})
})
+21
View File
@@ -7,11 +7,23 @@ import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
import { glyphOf, DEFAULT_GLYPH } from '../lib/glyphs.js'
import { DEMO } from '../lib/demo.js'
import { MOBILE } from '../lib/mobile.js'
import { coachAvailable } from '../lib/coach.js'
export default function Plan() {
const nav = useNavigate()
const S = useStore(s => s.S)
const update = useStore(s => s.update)
const config = useStore(s => s.config)
const coachMode = useStore(s => s.coachLocal?.mode)
const user = useStore(s => s.user)
/* The Coach's only entry point in the app. Its screens have existed since the UI landed and
nothing linked to them, so the feature was reachable only by typing the URL — enabled,
configured, and invisible. The same predicate every other Coach surface uses gates it, so
an instance without the feature sees exactly the Plan screen it saw before. */
const showCoach = coachAvailable(config, user, { demo: DEMO, mobile: MOBILE, coachMode })
const addRoutine = () => {
const r = { id: uid(), name: t('New routine'), emoji: DEFAULT_GLYPH, ex: [] }
@@ -24,6 +36,15 @@ export default function Plan() {
<div><h1>{t('Plan')}</h1><div className="sub">{t('Your weekly routine')}</div></div>
<button className="iconbtn" onClick={planToolsSheet} aria-label={t('Share your plan')} title={t('Share your plan')}><Icon name="upload" /></button>
</div>
{showCoach && <button className="coach-cta" onClick={() => nav('/coach')}>
<span className="coach-cta-av"><Icon name="sparkles" /></span>
<span className="coach-cta-t">
<b>{t('Coach')}</b>
<span>{t('Plan design and reviews, from your own training')}</span>
</span>
<Icon name="chevronRight" className="coach-cta-chev" />
</button>}
<div className="cols"><div>
<h4 className="sec">{t('Week schedule')}</h4>
<div className="list" style={{ display: 'flex', flexDirection: 'column' }}>
+8
View File
@@ -19,6 +19,7 @@ export default function Settings() {
const nav = useNavigate()
const S = useStore(s => s.S)
const user = useStore(s => s.user)
const coachLocal = useStore(s => s.coachLocal)
const { update, replaceState, setUser, pullState, pushState, signOut, signOutAll, resetDemo, disconnectServer } = useStore()
const toast = useUI(s => s.toast)
const fileRef = useRef(null)
@@ -110,6 +111,13 @@ export default function Settings() {
</Section>
{!user && !DEMO && !MOBILE && <p className="sect-f" style={{ marginTop: -18, marginBottom: 22 }}>{t('Guest mode — data lives only in this browser.')}</p>}
{/* ---------- the Coach on a phone: through the paired server, or with the user's own key ---------- */}
{MOBILE && <Section title={t('AI Coach')}>
<Row icon="sparkles" iconTint="var(--acc)" title={t('AI Coach')} accessory="chevron"
subtitle={coachLocal?.mode === 'server' ? t('Runs on your openGym server') : coachLocal?.mode === 'byok' ? t('Runs on this phone with your own API key') : t('Off — choose how the Coach should run.')}
onClick={() => nav('/coach/setup')} />
</Section>}
{/* ---------- general ---------- */}
<Section title={t('General')} footer={t('Note: switching units only changes the label — logged numbers are not converted.')}>
<SelectRow
+16 -6
View File
@@ -138,7 +138,7 @@ function MuscleBalance({ S }) {
const detrained = strengthOrder.filter(slug => strength[slug] < 1)
const top = worked.slice(0, 4)
const max = worked.length ? load[worked[0]] : 0
const sets = m => Math.round((load[m] || 0) * 10) / 10
const sets = m => fmtNum(Math.round((load[m] || 0) * 10) / 10)
return <div className="card">
<Segmented className="seg-range" value={view} onChange={setView}
@@ -206,11 +206,21 @@ function MuscleBalance({ S }) {
)) : <div className="muted small">{t('No exercises with an estimated 1RM yet.')}</div>}
</>}
{!sel && <div className="muted small" style={{ marginTop: 10 }}>{t('Tap a muscle to see its exercises.')}</div>}
{detrained.map(slug => <div key={slug} className="mrow">
<span className="nm">{t(MUSCLE_NAME[slug])}</span>
<span className="bar"><i style={{ width: Math.round(strength[slug] * 100) + '%' }} /></span>
<span className="v">{t('{0} sets', vol90[slug] || 0)}</span>
</div>)}
{/* Detrained muscles: the bar is retained strength, the value says how long ago the
muscle was last trained. Sets in the last 90 days ride along only when there are
any — a muscle is on this list precisely because it has not been trained lately, so
that number alone read as "0 sets" all the way down and told nobody anything. */}
{detrained.map(slug => {
const sets90 = Math.round((vol90[slug] || 0) * 10) / 10
return <div key={slug} className="mrow">
<span className="nm">{t(MUSCLE_NAME[slug])}</span>
<span className="bar"><i style={{ width: Math.round(strength[slug] * 100) + '%' }} /></span>
<span className="v" style={{ textAlign: 'right' }}>
{sets90 ? t('{0} sets', fmtNum(sets90)) : strengthHint(slug)}
{sets90 ? <span className="dim small" style={{ display: 'block', fontWeight: 400 }}>{strengthHint(slug)}</span> : null}
</span>
</div>
})}
</>}
</div>
}