Coach: Fragebogen beim ersten Mal, dann ein Chat mit dem Coach; Admin-Dashboard lesbar
Der Coach ist jetzt ein Gespraech. Beim ersten Mal ein Onboarding im Apple-Stil — eine Frage pro Bildschirm, 1–7 Tage frei, Trainingsdauer als HH:MM — danach der Chat: die Antworten als erste Nachricht, eine Tipp-Blase mit gemessener Dauer waehrend der Job laeuft, der Plan als Karte mit Routinen-Tabs und Begruendungen, Freitext zum Nachbessern, ein Knopf zum Uebernehmen. Zurueckkommen, Review anfordern, Antworten aendern — alles im selben Chat. Der Aus-Schalter fuer Nutzer ist weg: abschalten kann nur noch der Admin. Das Admin-Dashboard fuehrt in nummerierten Schritten (Provider → Endpunkt → Zugang → Modell → Test) mit Statuspille und Klartext; Limits, Konto und Isolation unter 'Advanced', die Jobs unter 'Activity'.
This commit is contained in:
1 parent
aef950cf7c
commit
18dd33e9d3
23 files changed
+2070
-321
No files matched your search
@@ -10,20 +10,25 @@ 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).
|
||||
// Deliberately English-only — it isn't part of the translated end-user surface, so it stays
|
||||
// out of the per-language string packs.
|
||||
//
|
||||
// One page of cards, each opening with a sentence that says what it is for. An operator who
|
||||
// looks at this twice a year should not have to remember what "synced 3d ago" or an invite
|
||||
// code means.
|
||||
|
||||
const rel = ts => {
|
||||
if (!ts) return 'never'
|
||||
const s = Math.max(0, (Date.now() - ts) / 1000)
|
||||
if (s < 60) return 'just now'
|
||||
if (s < 3600) return Math.floor(s / 60) + 'm ago'
|
||||
if (s < 86400) return Math.floor(s / 3600) + 'h ago'
|
||||
return Math.floor(s / 86400) + 'd ago'
|
||||
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'
|
||||
}
|
||||
const dur = ms => { const m = Math.max(0, Math.floor(ms / 60000)); return m < 60 ? m + 'm' : Math.floor(m / 60) + 'h' + (m % 60) + 'm' }
|
||||
const dur = ms => { const m = Math.max(0, Math.floor(ms / 60000)); return m < 60 ? m + ' min' : Math.floor(m / 60) + ' h ' + (m % 60) + ' min' }
|
||||
|
||||
function UserDetail({ id, onChanged, close }) {
|
||||
const [d, setD] = useState(null)
|
||||
@@ -39,10 +44,10 @@ function UserDetail({ id, onChanged, close }) {
|
||||
return <>
|
||||
<h3 className="capitalize">{u.name}</h3>
|
||||
<div className="row" style={{ gap: 6, flexWrap: 'wrap', margin: '8px 0 12px' }}>
|
||||
{u.admin && <span className="tag acc">admin</span>}
|
||||
{u.disabled && <span className="tag" style={{ color: 'var(--red)' }}>disabled</span>}
|
||||
{u.invitedBy && <span className="tag">invite {u.invitedBy}</span>}
|
||||
<span className="tag">joined {u.created ? fmtDate(u.created.slice(0, 10)) : '—'}</span>
|
||||
{u.admin && <span className="adm-pill acc">admin</span>}
|
||||
{u.disabled && <span className="adm-pill bad">disabled</span>}
|
||||
{u.invitedBy && <span className="adm-pill">invite {u.invitedBy}</span>}
|
||||
<span className="adm-pill">joined {u.created ? fmtDate(u.created.slice(0, 10)) : '—'}</span>
|
||||
</div>
|
||||
<div className="tiles" style={{ textAlign: 'left' }}>
|
||||
<div className="tile"><div className="l">Workouts</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.workouts.length}</div></div>
|
||||
@@ -50,10 +55,13 @@ function UserDetail({ id, onChanged, close }) {
|
||||
<div className="tile"><div className="l">Routines</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.routines.length}</div></div>
|
||||
<div className="tile"><div className="l">Last sync</div><div className="v" style={{ fontSize: '.95rem' }}>{rel(d.lastSync)}</div></div>
|
||||
</div>
|
||||
{!u.admin && <button className={'btn ' + (u.disabled ? 'primary' : 'danger')} style={{ margin: '12px 0 4px' }}
|
||||
onClick={() => u.disabled ? setDisabled(false)
|
||||
: confirmSheet({ title: 'Disable ' + u.name + '?', message: 'They are signed out everywhere and can no longer sync or log in until re-enabled.', confirmText: 'Disable', danger: true, onConfirm: () => setDisabled(true) })}>
|
||||
{u.disabled ? 'Enable account' : 'Disable account'}</button>}
|
||||
{!u.admin && <>
|
||||
<button className={'btn ' + (u.disabled ? 'primary' : 'danger')} style={{ margin: '12px 0 4px' }}
|
||||
onClick={() => u.disabled ? setDisabled(false)
|
||||
: confirmSheet({ title: 'Disable ' + u.name + '?', message: 'They are signed out everywhere and can no longer sync or log in until re-enabled. Their data stays.', confirmText: 'Disable', danger: true, onConfirm: () => setDisabled(true) })}>
|
||||
{u.disabled ? 'Enable account' : 'Disable account'}</button>
|
||||
<div className="adm-hint">{u.disabled ? 'Enabling lets them sign in and sync again.' : 'Disabling signs them out everywhere and blocks sign-in. Nothing is deleted.'}</div>
|
||||
</>}
|
||||
<h4 className="sec">Workout history</h4>
|
||||
{d.workouts.length ? <div className="list" style={{ gap: 0 }}>
|
||||
{d.workouts.slice(0, 60).map(w => <div key={w.id} className="row between" style={{ padding: '9px 2px', borderBottom: '1px solid var(--sep)' }}>
|
||||
@@ -61,32 +69,49 @@ function UserDetail({ id, onChanged, close }) {
|
||||
<div className="dim" style={{ fontSize: '.72rem' }}>{fmtDate(w.d, true)} · {fmtDur((w.end || w.start) - w.start)} · {setsDone(w)} sets{w.prs?.length ? ' · ' + w.prs.length + ' PR' : ''}</div></div>
|
||||
<span className="small muted">{fmtVol(w.vol ?? workoutVolume(w), d.unit)}</span>
|
||||
</div>)}
|
||||
</div> : <div className="empty small">No workouts logged.</div>}
|
||||
</div> : <div className="adm-empty">No workouts logged.</div>}
|
||||
</>
|
||||
}
|
||||
|
||||
function InvitesCard({ invites, reload }) {
|
||||
function InvitesCard({ invites, reload, inviteOnly }) {
|
||||
const toast = useUI(s => s.toast)
|
||||
const gen = () => api('/api/admin/invites/new', { method: 'POST', body: '{}' })
|
||||
.then(({ invite }) => { navigator.clipboard?.writeText(invite.code).catch(() => {}); toast('Code ' + invite.code + ' created & copied'); reload() })
|
||||
.catch(e => toast(e.message))
|
||||
const revoke = code => api('/api/admin/invites/revoke', { method: 'POST', body: JSON.stringify({ code }) })
|
||||
.then(() => { toast('Code revoked'); reload() }).catch(e => toast(e.message))
|
||||
const revoke = code => confirmSheet({
|
||||
title: 'Revoke code ' + code + '?', message: 'Anyone who has it can no longer use it. People who already signed up with it are not affected.',
|
||||
confirmText: 'Revoke', danger: true,
|
||||
onConfirm: () => api('/api/admin/invites/revoke', { method: 'POST', body: JSON.stringify({ code }) })
|
||||
.then(() => { toast('Code revoked'); reload() }).catch(e => toast(e.message))
|
||||
})
|
||||
const copy = code => { navigator.clipboard?.writeText(code).catch(() => {}); toast('Copied ' + code) }
|
||||
const open = (invites || []).filter(i => !i.usedBy)
|
||||
const used = (invites || []).filter(i => i.usedBy)
|
||||
return <div className="card">
|
||||
<div className="row between"><h2 style={{ margin: 0 }}>Invite codes</h2>
|
||||
<Button variant="primary" size="sm" onClick={gen} icon="plus">Generate</Button></div>
|
||||
<div className="small muted" style={{ margin: '6px 0 10px' }}>{open.length} unused · {used.length} redeemed</div>
|
||||
{open.map(i => <div key={i.code} className="row between" style={{ padding: '7px 2px', borderBottom: '1px solid var(--sep)' }}>
|
||||
<span style={{ fontFamily: 'ui-monospace,SFMono-Regular,Menlo,monospace', fontWeight: 500, letterSpacing: '.06em' }}
|
||||
onClick={() => { navigator.clipboard?.writeText(i.code).catch(() => {}); toast('Copied ' + i.code) }}>{i.code}</span>
|
||||
<button className="iconbtn" style={{ width: 32, height: 30, borderRadius: 8, fontSize: 15, color: 'var(--red)' }} onClick={() => revoke(i.code)} aria-label="revoke"><Icon name="trash" /></button>
|
||||
</div>)}
|
||||
{used.map(i => <div key={i.code} className="row between dim" style={{ padding: '7px 2px', fontSize: '.8rem' }}>
|
||||
<span style={{ fontFamily: 'monospace' }}>{i.code}</span><span>→ {i.usedByName || 'used'}</span>
|
||||
</div>)}
|
||||
{!open.length && !used.length && <div className="dim small">No codes yet — generate one to invite someone.</div>}
|
||||
<Button variant="primary" size="sm" onClick={gen} icon="plus">New code</Button></div>
|
||||
<div className="adm-lead">
|
||||
{inviteOnly
|
||||
? 'Sign-up is invite-only: someone needs one of these codes to create a profile. Each code works once.'
|
||||
: 'Sign-up is open, so codes are optional here — they only record who invited whom.'}
|
||||
</div>
|
||||
{open.length ? <>
|
||||
<div className="adm-group-t">Unused · tap to copy</div>
|
||||
{open.map(i => <div key={i.code} className="row between" style={{ padding: '6px 0', borderBottom: 'var(--hair) solid var(--sep)' }}>
|
||||
<button className="adm-code" onClick={() => copy(i.code)} aria-label={'copy ' + i.code}>{i.code}</button>
|
||||
<div className="row" style={{ gap: 4 }}>
|
||||
<button className="iconbtn adm-iconbtn" onClick={() => copy(i.code)} aria-label="copy"><Icon name="clipboard" /></button>
|
||||
<button className="iconbtn adm-iconbtn" style={{ color: 'var(--red)' }} onClick={() => revoke(i.code)} aria-label="revoke"><Icon name="trash" /></button>
|
||||
</div>
|
||||
</div>)}
|
||||
</> : null}
|
||||
{used.length ? <>
|
||||
<div className="adm-group-t" style={{ marginTop: open.length ? 12 : 0 }}>Already used</div>
|
||||
{used.map(i => <div key={i.code} className="row between dim" style={{ padding: '6px 0', fontSize: '.82rem' }}>
|
||||
<span style={{ fontFamily: 'ui-monospace,SFMono-Regular,Menlo,monospace', letterSpacing: '.06em' }}>{i.code}</span><span>→ {i.usedByName || 'used'}</span>
|
||||
</div>)}
|
||||
</> : null}
|
||||
{!open.length && !used.length && <div className="adm-empty">No codes yet. "New code" makes one and copies it to your clipboard.</div>}
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -119,30 +144,31 @@ function AuditCard({ tick }) {
|
||||
|
||||
return <div className="card">
|
||||
<div className="row between"><h2 style={{ margin: 0 }}>Activity log</h2>
|
||||
<button className="iconbtn" style={{ width: 32, height: 30, borderRadius: 8, fontSize: 15, color: 'var(--red)' }}
|
||||
onClick={clear} aria-label="clear log"><Icon name="trash" /></button></div>
|
||||
<div className="small muted" style={{ margin: '6px 0 10px' }}>
|
||||
{meta ? fmtNum(meta.total) + ' events'
|
||||
+ (meta.retention.days ? ' · last ' + meta.retention.days + ' days' : '')
|
||||
+ (meta.ip_mode === 'off' ? ' · no IP addresses' : '') : 'Loading…'}</div>
|
||||
<button className="iconbtn adm-iconbtn" style={{ color: 'var(--red)' }} onClick={clear} aria-label="clear log"><Icon name="trash" /></button></div>
|
||||
<div className="adm-lead">
|
||||
Who signed in, what failed, and what an admin changed.
|
||||
{meta ? ' ' + fmtNum(meta.total) + ' events'
|
||||
+ (meta.retention.days ? ', kept for ' + meta.retention.days + ' days' : '')
|
||||
+ (meta.ip_mode === 'off' ? ', without IP addresses' : '') + '.' : ''}
|
||||
</div>
|
||||
<div className="chips" style={{ marginBottom: 10 }}>
|
||||
{[['', 'All'], ['auth', 'Sign-ins'], ['admin', 'Admin'], ['fail', 'Failed']].map(([v, l]) =>
|
||||
<button key={v} className={'chip' + (cat === v ? ' on' : '')} onClick={() => pick(v)}>{l}</button>)}
|
||||
</div>
|
||||
{rows.map(e => {
|
||||
const line = auditLine(e)
|
||||
return <div key={e.id} className="row between" style={{ padding: '8px 2px', borderBottom: '1px solid var(--sep)' }}>
|
||||
return <div key={e.id} className="row between" style={{ padding: '8px 2px', borderBottom: 'var(--hair) solid var(--sep)' }}>
|
||||
<div className="grow">
|
||||
<div className="small" style={{ fontWeight: 600 }}>{line.title}
|
||||
{/* a red pill, not a red row: twenty fumbled Face IDs in a row shouldn't read as an incident */}
|
||||
{!e.ok && <span className="tag" style={{ marginLeft: 6, color: 'var(--red)' }}>failed</span>}
|
||||
{auditCat(e.ev) === 'admin' && <span className="tag acc" style={{ marginLeft: 6 }}>admin</span>}</div>
|
||||
{!e.ok && <span className="adm-pill bad" style={{ marginLeft: 6 }}>failed</span>}
|
||||
{auditCat(e.ev) === 'admin' && <span className="adm-pill acc" style={{ marginLeft: 6 }}>admin</span>}</div>
|
||||
{line.sub && <div className="dim" style={{ fontSize: '.72rem' }}>{line.sub}</div>}
|
||||
</div>
|
||||
<span className="small muted" style={{ flex: 'none', marginLeft: 8 }}>{fmtWhen(e.ts, meta?.now)}</span>
|
||||
</div>
|
||||
})}
|
||||
{meta && !rows.length && <div className="dim small">Nothing logged yet.</div>}
|
||||
{meta && !rows.length && <div className="adm-empty">Nothing logged yet.</div>}
|
||||
{meta?.nextBefore && <div style={{ marginTop: 10 }}>
|
||||
<Button size="sm" onClick={() => load(cat, meta.nextBefore)}>Show more</Button></div>}
|
||||
</div>
|
||||
@@ -176,37 +202,44 @@ export default function Admin() {
|
||||
<div className="sub">{users ? users.length + ' users · ' + activeCount + ' active this week' : 'Loading…'}</div></div>
|
||||
<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 the AI Coach. Nothing here shows anyone's training data beyond counts.
|
||||
</div>
|
||||
|
||||
<div className="tiles" style={{ marginBottom: 12 }}>
|
||||
<div className="tile"><div className="l">Users</div><div className="v">{users ? users.length : '—'}</div></div>
|
||||
<div className="tile"><div className="l">Training now</div><div className="v" style={{ color: liveUsers.length ? 'var(--acc)' : undefined }}>{users ? liveUsers.length : '—'}</div></div>
|
||||
<div className="tile"><div className="l">Active 7d</div><div className="v">{users ? activeCount : '—'}</div></div>
|
||||
<div className="tile"><div className="l">Active 7 days</div><div className="v">{users ? activeCount : '—'}</div></div>
|
||||
<div className="tile"><div className="l">Disabled</div><div className="v">{users ? disabledCount : '—'}</div></div>
|
||||
</div>
|
||||
|
||||
{liveUsers.length > 0 && <div className="card" style={{ borderColor: 'var(--acc)' }}>
|
||||
<h2 className="row" style={{ margin: '0 0 8px', gap: 6 }}><Icon name="dot" style={{ fontSize: 10, color: 'var(--green)' }} />Training now</h2>
|
||||
{liveUsers.map(u => <div key={u.id} className="row between" style={{ padding: '8px 2px', borderBottom: '1px solid var(--sep)' }} onClick={() => openUser(u.id)}>
|
||||
<h2 className="row" style={{ margin: '0 0 2px', gap: 6 }}><Icon name="dot" style={{ fontSize: 10, color: 'var(--green)' }} />Training now</h2>
|
||||
<div className="adm-lead">Sessions running at this moment. Tap a name for details.</div>
|
||||
{liveUsers.map(u => <div key={u.id} className="row between" style={{ padding: '8px 2px', borderBottom: 'var(--hair) solid var(--sep)' }} onClick={() => openUser(u.id)}>
|
||||
<div><div className="small" style={{ fontWeight: 600 }}>{u.name}</div>
|
||||
<div className="dim" style={{ fontSize: '.72rem' }}>{u.live.name} · ex {u.live.exIdx}/{u.live.exTotal} · {u.live.setsDone}/{u.live.setsTotal} sets</div></div>
|
||||
<span className="tag acc">{dur(Date.now() - u.live.startedAt)}</span>
|
||||
<div className="dim" style={{ fontSize: '.72rem' }}>{u.live.name} · exercise {u.live.exIdx} of {u.live.exTotal} · {u.live.setsDone}/{u.live.setsTotal} sets</div></div>
|
||||
<span className="adm-pill acc">{dur(Date.now() - u.live.startedAt)}</span>
|
||||
</div>)}
|
||||
</div>}
|
||||
|
||||
{/* Renders nothing at all unless the instance offers the Coach, so an admin page on a
|
||||
box that never enabled it is byte-for-byte the page it was before. */}
|
||||
{/* 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} />
|
||||
<InvitesCard invites={invites} reload={loadInvites} inviteOnly={inviteOnly} />
|
||||
|
||||
<h4 className="sec">Users</h4>
|
||||
<div className="list">
|
||||
{(users || []).map(u => <div key={u.id} className="item" onClick={() => openUser(u.id)} style={u.disabled ? { opacity: .55 } : null}>
|
||||
<div className="grow"><div className="tt">{u.live && <Icon name="dot" style={{ fontSize: 9, color: 'var(--green)', display: 'inline-block', marginRight: 5 }} />}{u.name} {u.admin && <span className="tag acc" style={{ marginLeft: 4 }}>admin</span>}{u.disabled && <span className="tag" style={{ marginLeft: 4, color: 'var(--red)' }}>off</span>}</div>
|
||||
<div className="ss">{u.live ? 'training now · ' + u.live.name : u.workouts + ' workouts' + (u.lastWorkout ? ' · last ' + fmtDate(u.lastWorkout) : '') + ' · synced ' + rel(u.lastSync)}</div></div>
|
||||
{u.hasPush && <Icon name="bell" title="push enabled" style={{ fontSize: 15, color: 'var(--label-3)' }} />}<Icon name="chevronRight" className="chev" />
|
||||
</div>)}
|
||||
{users && !users.length && <div className="empty">No users yet.</div>}
|
||||
<div className="card">
|
||||
<h2 style={{ margin: 0 }}>Users</h2>
|
||||
<div className="adm-lead">Everyone with a profile on this instance. Tap one to see their activity or to disable the account — their data is never deleted from here.</div>
|
||||
<div className="list">
|
||||
{(users || []).map(u => <div key={u.id} className="item" onClick={() => openUser(u.id)} style={u.disabled ? { opacity: .55 } : null}>
|
||||
<div className="grow"><div className="tt">{u.live && <Icon name="dot" style={{ fontSize: 9, color: 'var(--green)', display: 'inline-block', marginRight: 5 }} />}{u.name} {u.admin && <span className="adm-pill acc" style={{ marginLeft: 4 }}>admin</span>}{u.disabled && <span className="adm-pill bad" style={{ marginLeft: 4 }}>disabled</span>}</div>
|
||||
<div className="ss">{u.live ? 'training now · ' + u.live.name : u.workouts + ' workouts' + (u.lastWorkout ? ' · last ' + fmtDate(u.lastWorkout) : '') + ' · last sync ' + rel(u.lastSync)}</div></div>
|
||||
{u.hasPush && <Icon name="bell" title="push notifications on" style={{ fontSize: 15, color: 'var(--label-3)' }} />}<Icon name="chevronRight" className="chev" />
|
||||
</div>)}
|
||||
{users && !users.length && <div className="adm-empty">No users yet.</div>}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div style={{ marginTop: 14 }}><AuditCard tick={tick} /></div>
|
||||
|
||||
+261
-149
@@ -4,22 +4,32 @@ import { api } from '../lib/api.js'
|
||||
import Icon from '../components/Icon.jsx'
|
||||
import { Button, Switch, TextField } from '../components/ui.jsx'
|
||||
|
||||
/* The operator's side of the Coach: is it on, can it reach a model, and what has it been
|
||||
doing. Like the rest of the admin dashboard this is deliberately English-only — it isn't
|
||||
part of the translated end-user surface.
|
||||
*
|
||||
* What it never shows: anybody's intake answers, payloads or proposals. An admin can enable
|
||||
* the feature and see that jobs ran; they cannot read what their users asked it. */
|
||||
/* 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) + 'm ago'
|
||||
if (s < 86400) return Math.floor(s / 3600) + 'h ago'
|
||||
return Math.floor(s / 86400) + 'd ago'
|
||||
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)
|
||||
@@ -28,16 +38,11 @@ export default function AdminCoach() {
|
||||
// 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'))
|
||||
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)
|
||||
}
|
||||
useEffect(() => { load() }, [])
|
||||
|
||||
const patch = async body => {
|
||||
@@ -46,18 +51,27 @@ export default function AdminCoach() {
|
||||
catch (e) { toast(e.message) }
|
||||
setBusy(false)
|
||||
}
|
||||
const test = async () => {
|
||||
const loadModels = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const r = await api('/api/admin/coach/test', { method: 'POST', body: '{}' })
|
||||
toast(r.ok ? 'Coach test passed ✅' : 'Test failed: ' + (r.error || 'unknown'))
|
||||
await load()
|
||||
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: '{}' }); toast('Disconnected'); await load() }
|
||||
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)
|
||||
}
|
||||
@@ -66,160 +80,258 @@ export default function AdminCoach() {
|
||||
|
||||
if (d.disabledByEnv) return <div className="card">
|
||||
<h2 style={{ margin: '0 0 6px' }}>AI Coach</h2>
|
||||
<div className="muted small">Force-disabled by <code>COACH_DISABLED</code> in the environment. Remove it to configure the Coach here.</div>
|
||||
<div 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 authed = d.auth?.state === 'connected' || d.auth?.state === 'not-required' || d.auth?.state === 'optional'
|
||||
const live = d.enabled && d.runtime.ok && authed
|
||||
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.
|
||||
let n = 1
|
||||
const num = () => n++
|
||||
|
||||
return <div className="card" style={{ borderColor: live ? 'var(--acc)' : undefined }}>
|
||||
<div className="row between" style={{ marginBottom: 8 }}>
|
||||
<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>
|
||||
|
||||
{!d.enabled && <div className="muted small">Off. Users see no Coach anywhere in the app.</div>}
|
||||
<div className="adm-status">
|
||||
<span className={'adm-pill ' + (!d.enabled ? '' : live ? 'ok' : 'warn')}>{!d.enabled ? 'off' : live ? 'ready' : 'not ready'}</span>
|
||||
<span>{status}</span>
|
||||
</div>
|
||||
<div className="adm-lead">
|
||||
The Coach designs a training plan and adjusts it from what people log. This switch is the only place it can be turned off for everyone — users decide for themselves whether to use it, but cannot disable it.
|
||||
</div>
|
||||
|
||||
{d.enabled && <>
|
||||
<div className="tiles" style={{ textAlign: 'left', marginBottom: 10 }}>
|
||||
<div className="tile"><div className="l">Runtime</div>
|
||||
<div className="v" style={{ fontSize: '.9rem', color: d.runtime.ok ? 'var(--green)' : 'var(--red)' }}>{d.runtime.ok ? 'ready' : 'missing'}</div></div>
|
||||
<div className="tile"><div className="l">Credential</div>
|
||||
<div className="v" style={{ fontSize: '.9rem', color: authed ? 'var(--green)' : 'var(--red)' }}>{authLabel(d.auth)}</div></div>
|
||||
<div className="tile"><div className="l">Jobs today</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.jobsToday}</div></div>
|
||||
<div className="tile"><div className="l">Last run</div><div className="v" style={{ fontSize: '.85rem' }}>{rel(d.lastSuccess?.at)}</div></div>
|
||||
</div>
|
||||
|
||||
{d.runtime.version && <div className="dim small" style={{ marginBottom: 8 }}>{meta.runtime || meta.label} · {d.runtime.version}</div>}
|
||||
{!d.runtime.ok && d.runtime.error && <div className="small" style={{ color: 'var(--red)', marginBottom: 8 }}>{d.runtime.error}</div>}
|
||||
|
||||
{/* The privilege drop, stated plainly. It fails closed, so when this reads no, nothing
|
||||
runs at all — and the admin needs to learn that here rather than from a user
|
||||
reporting that the Coach does nothing. The reason is the server's own words. */}
|
||||
{d.unprivileged && !d.unprivileged.ok &&
|
||||
<div className="small" style={{ color: 'var(--red)', marginBottom: 8, lineHeight: 1.5 }}>
|
||||
Jobs are disabled: {d.unprivileged.why}. No job will run until this is fixed.
|
||||
</div>}
|
||||
{d.unprivileged?.ok &&
|
||||
<div className="dim small" style={{ marginBottom: 8 }}>
|
||||
Jobs run unprivileged: {d.unprivileged.dropped ? 'yes' : 'no — this host has no separate user to drop to'}
|
||||
</div>}
|
||||
|
||||
{/* Whose account is being spent, in the admin's own view. The same fact the user sees on
|
||||
their Coach screen, because "the admin card and the user screen must both name the
|
||||
account" is only true if neither is inferring it from settings. */}
|
||||
<div className="dim small" style={{ marginBottom: 8 }}>
|
||||
{d.authMode === 'profile'
|
||||
? 'Each profile signs in with their own account.'
|
||||
: d.boundUid
|
||||
? 'One shared account, already in use by a profile. Any other profile is refused.'
|
||||
: 'One shared account. The first profile to use it binds it; every other profile is then refused.'}
|
||||
</div>
|
||||
|
||||
{/* provider */}
|
||||
<h4 className="sec" style={{ marginTop: 4 }}>Provider</h4>
|
||||
<div className="row" style={{ flexWrap: 'wrap', gap: 7, marginBottom: 10 }}>
|
||||
{d.providers.map(p => <button key={p.id} className={'chip' + (p.id === d.provider ? ' on' : '')} title={p.connected ? 'a key is stored for this provider' : undefined}
|
||||
disabled={busy} onClick={() => patch({ provider: p.id })}>{p.label}{p.connected ? ' ·' : ''}</button>)}
|
||||
</div>
|
||||
{meta.http && <div className="dim small" style={{ marginTop: -4, marginBottom: 10 }}>
|
||||
Plain HTTPS to the provider — no AI runtime needed in the image, so this works on the default <code>api</code> image. Keys stay per provider when you switch.
|
||||
</div>}
|
||||
|
||||
{/* endpoint — only for the provider whose endpoint is the whole configuration */}
|
||||
{meta.baseUrl && <>
|
||||
<h4 className="sec">Endpoint</h4>
|
||||
<TextField defaultValue={d.baseUrl || ''} placeholder="http://ollama.lan:11434 or https://openrouter.ai/api"
|
||||
onBlur={e => e.target.value !== (d.baseUrl || '') && patch({ baseUrl: e.target.value })} />
|
||||
<div className="dim small" style={{ marginBottom: 10 }}>Anything that serves OpenAI's Chat Completions shape: Ollama, LM Studio, vLLM, OpenRouter, a gateway of your own. The host is written to the job log.</div>
|
||||
</>}
|
||||
|
||||
{/* credential */}
|
||||
{(meta.setupToken || meta.apiKey) && <>
|
||||
<h4 className="sec">Credential</h4>
|
||||
{d.auth?.state === 'connected' ? <>
|
||||
<div className="small muted" style={{ marginBottom: 8 }}>
|
||||
Connected{d.auth.account ? ' as ' + d.auth.account : ''} via {credentialLabel(d.auth.type)} · {rel(d.auth.connectedAt)}
|
||||
{/* ---------- provider ---------- */}
|
||||
<Step n={num()} title="Provider" hint={meta.label || 'Which AI answers the Coach'} done={step1Done} open={!step1Done}>
|
||||
<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="row" style={{ gap: 8 }}>
|
||||
<Button size="sm" icon="check" disabled={busy} onClick={test}>Test the Coach</Button>
|
||||
<Button size="sm" danger disabled={busy} onClick={disconnect}>Disconnect</Button>
|
||||
<div 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} open={!step2Done}>
|
||||
<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} open={!step3Done}>
|
||||
<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" 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>
|
||||
</> : <>
|
||||
{d.auth?.state === 'expired' && <div className="small" style={{ color: 'var(--red)', marginBottom: 8 }}>The stored credential expired — connect again.</div>}
|
||||
{d.auth?.state === 'replace-required' && <div className="small" style={{ color: 'var(--red)', marginBottom: 8 }}>
|
||||
The old Claude credential is no longer used. Add a Claude Code setup token instead.
|
||||
{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>}
|
||||
{d.auth?.state === 'unreadable' && <div className="small" style={{ color: 'var(--red)', marginBottom: 8 }}>
|
||||
The stored credential can't be decrypted — this usually means ./data was restored without its <code>secret</code> file. Connect again.
|
||||
</div>}
|
||||
<div className="row" style={{ gap: 8, flexWrap: 'wrap' }}>
|
||||
{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 CLI token</Button>}
|
||||
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 an API key (optional)' : 'Use an API key'}</Button>}
|
||||
{meta.keyOptional && <Button size="sm" icon="check" disabled={busy} onClick={test}>Test the Coach</Button>}
|
||||
{meta.keyOptional ? 'Add API key (optional)' : 'Add API key'}</Button>}
|
||||
</div>
|
||||
</>}
|
||||
</>}
|
||||
</Step>}
|
||||
|
||||
{/* limits */}
|
||||
<h4 className="sec">Limits</h4>
|
||||
<div className="row" style={{ gap: 10, flexWrap: 'wrap', marginBottom: 4 }}>
|
||||
<label className="small muted">Per user / day
|
||||
<input className="num" type="number" min="0" max="200" defaultValue={d.caps.perProfileDaily} style={{ width: 70, marginLeft: 8 }}
|
||||
onBlur={e => patch({ caps: { ...d.caps, perProfileDaily: +e.target.value } })} /></label>
|
||||
<label className="small muted">Whole instance / day
|
||||
<input className="num" type="number" min="0" max="5000" defaultValue={d.caps.instanceDaily} style={{ width: 70, marginLeft: 8 }}
|
||||
onBlur={e => patch({ caps: { ...d.caps, instanceDaily: +e.target.value } })} /></label>
|
||||
</div>
|
||||
<div className="dim small" style={{ marginBottom: 10 }}>0 = no limit. Every job is one session on your provider account.</div>
|
||||
{/* ---------- model ---------- */}
|
||||
<Step n={num()} title="Model" hint={d.model || (meta.defaultModel ? 'default: ' + meta.defaultModel : 'not chosen yet')} done={step4Done} open={!step4Done}>
|
||||
<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" 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>
|
||||
|
||||
<h4 className="sec">Model</h4>
|
||||
{models && models.length ? <>
|
||||
<select className="sel" value={models.includes(d.model) ? d.model : ''} disabled={busy} style={{ width: '100%' }}
|
||||
onChange={e => patch({ model: e.target.value })}>
|
||||
<option value="">{meta.defaultModel ? `(default: ${meta.defaultModel})` : '(pick a model)'}</option>
|
||||
{!models.includes(d.model) && 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})` : meta.baseUrl ? 'pick one from the endpoint' : '(the provider default)'}
|
||||
onBlur={e => e.target.value !== (d.models?.[d.provider] || '') && patch({ model: e.target.value })} />}
|
||||
{meta.http && <div className="row" style={{ gap: 8, marginTop: 6, marginBottom: 6 }}>
|
||||
<Button size="sm" disabled={busy} onClick={loadModels}>{models ? 'Refresh models' : 'List models'}</Button>
|
||||
{models && models.length ? <span className="dim small">{models.length} served by the endpoint</span> : null}
|
||||
</div>}
|
||||
{/* ---------- test ---------- */}
|
||||
<Step n={num()} title="Test" hint={step5Done ? 'passed' : 'one real round trip, no user data'} done={step5Done} open={!step5Done || !!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>
|
||||
{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>
|
||||
|
||||
{d.lastError && <>
|
||||
<h4 className="sec">Last failure</h4>
|
||||
<div className="small" style={{ color: 'var(--red)' }}>{d.lastError.errorClass}{d.lastError.detail ? ' — ' + d.lastError.detail : ''}</div>
|
||||
<div className="dim" style={{ fontSize: '.72rem' }}>{rel(d.lastError.at)}</div>
|
||||
</>}
|
||||
{/* ---------- 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>
|
||||
|
||||
{!!d.recent?.length && <>
|
||||
<h4 className="sec">Recent jobs</h4>
|
||||
{d.recent.slice(0, 8).map((e, i) => <div key={i} className="row between" style={{ padding: '5px 2px', borderBottom: '1px solid var(--sep)' }}>
|
||||
<span className="small">{e.kind}{e.trigger === 'scheduled' ? ' · scheduled' : ''}</span>
|
||||
<span className="dim" style={{ fontSize: '.72rem' }}>
|
||||
<span style={{ color: e.outcome === 'failed' ? 'var(--red)' : e.outcome === 'ready' ? 'var(--acc)' : undefined }}>{e.outcome}</span>
|
||||
{e.ms ? ' · ' + Math.round(e.ms / 1000) + 's' : ''} · {rel(e.at)}
|
||||
</span>
|
||||
</div>)}
|
||||
</>}
|
||||
<div 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.boundUid
|
||||
? 'One shared account, already in use by one profile. Every other profile is refused, so nobody spends somebody else\'s subscription.'
|
||||
: 'One shared account. The first profile to use it becomes the only one allowed to — every other profile is then refused.'}</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>
|
||||
}
|
||||
|
||||
const authLabel = a => ({
|
||||
connected: 'connected', 'not-required': 'n/a', none: 'needed', optional: 'none (optional)', disconnected: 'needed', expired: 'expired', unreadable: 'unreadable', 'replace-required': 'replace'
|
||||
}[a?.state] || '—')
|
||||
/* ---------------------------------- pieces ---------------------------------- */
|
||||
|
||||
function Step({ n, title, hint, done, open, children }) {
|
||||
return <details className={'adm-step ' + (done ? 'done' : 'todo')} open={open}>
|
||||
<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 too long (over 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 }) {
|
||||
@@ -235,7 +347,7 @@ function SetupTokenSheet({ close, onDone, label }) {
|
||||
try {
|
||||
const r = await api('/api/admin/coach/connect', { method: 'POST', body: JSON.stringify({ type: 'cli-token', token: token.trim(), account: account.trim() }) })
|
||||
setToken('')
|
||||
toast(r.test?.ok ? 'Connected ✅' : 'Saved, but the test failed: ' + (r.test?.error || ''))
|
||||
toast(r.test?.ok ? 'Connected ✅' : 'Token saved')
|
||||
close(); onDone()
|
||||
} catch (e) { toast(e.message); setBusy(false) }
|
||||
}
|
||||
@@ -249,7 +361,7 @@ function SetupTokenSheet({ close, onDone, label }) {
|
||||
<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 and test</Button>
|
||||
<Button variant="primary" disabled={busy || !token.trim()} onClick={save}>Save token</Button>
|
||||
<div style={{ height: 8 }} />
|
||||
</>
|
||||
}
|
||||
@@ -262,16 +374,16 @@ function ApiKeySheet({ close, onDone, label, placeholder, optional }) {
|
||||
setBusy(true)
|
||||
try {
|
||||
const r = await api('/api/admin/coach/connect', { method: 'POST', body: JSON.stringify({ type: 'apikey', token: key.trim() }) })
|
||||
toast(r.test?.ok ? 'Key saved ✅' : 'Saved, but the test failed: ' + (r.test?.error || ''))
|
||||
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, leave this empty.' : '.'}
|
||||
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-…'} onChange={e => setKey(e.target.value)} />
|
||||
<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 }} />
|
||||
|
||||
@@ -0,0 +1,416 @@
|
||||
// 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. 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, 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,
|
||||
changeTitle, changeValues, exName, canRevert, revertLast
|
||||
} from '../lib/coach.js'
|
||||
import { useCoachStatus, requestReview, refinePlan, resolvePending, JOB_ERRORS } from '../lib/coach-api.js'
|
||||
import { confirmSheet } from '../sheets.jsx'
|
||||
import Icon from '../components/Icon.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 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
|
||||
useEffect(() => {
|
||||
if (!ok) nav('/home', { replace: true })
|
||||
else if (!ready) nav('/coach/intake', { replace: true })
|
||||
}, [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 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 askReview = async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await requestReview('')
|
||||
update(s => appendChat(s, { role: 'user', kind: 'text', text: t('Have a look at my training and tell me what you would change.') }))
|
||||
refresh()
|
||||
} catch (e) { toast(e.message || t('Could not ask the Coach')) }
|
||||
setBusy(false)
|
||||
}
|
||||
|
||||
const menu = () => openSheet(close => <div className="chat-menu">
|
||||
<h3>{t('Coach')}</h3>
|
||||
<div className="sect-b">
|
||||
{!job && !pending && <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() }} />}
|
||||
<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('Tell the Coach what to change…')
|
||||
: job ? t('Wait for the Coach to finish…') : t('Ask for a review, or tell the Coach something…')
|
||||
|
||||
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} profile={coach.profile} />)}
|
||||
|
||||
{job && <Typing S={S} kind={job.kind} coachLocal={coachLocal} />}
|
||||
|
||||
{pending && !job && (pending.kind === 'create'
|
||||
? <PlanCard p={pending} S={S} update={update} toast={toast} nav={nav} refresh={refresh} />
|
||||
: <ReviewCard p={pending} S={S} update={update} toast={toast} refresh={refresh} />)}
|
||||
|
||||
<div ref={endRef} />
|
||||
</div>
|
||||
|
||||
<div className="composer">
|
||||
<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, profile }) {
|
||||
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 === '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 }) {
|
||||
const ms = estimateMs(S)
|
||||
const local = coachLocal?.mode === 'byok' && coachLocal?.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 {
|
||||
eta = t('This usually takes a minute or two.')
|
||||
}
|
||||
return <div className="msg coach">
|
||||
<div className="bub typing"><i /><i /><i /></div>
|
||||
<div className="typing-eta">
|
||||
{kind === 'create' ? t('Building your plan…') : t('Reading your training…')} {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', 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 => { recordDismissal(s, p); appendChat(s, { role: 'coach', kind: 'dismissed', 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>
|
||||
|
||||
<div className="pcard-week">
|
||||
{[1, 2, 3, 4, 5, 6, 0].map(d => <div key={d} className={'pcard-wd' + (weekDays.has(d) ? ' on' : '')}>{t(DAYS[d])}</div>)}
|
||||
</div>
|
||||
|
||||
{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 && <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, S.unit)}</span></div>
|
||||
{!!e.why && <div className="pcard-ex-w">{e.why}</div>}
|
||||
</div>)}
|
||||
</div>}
|
||||
|
||||
<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>
|
||||
}
|
||||
|
||||
/* ---------------------------------- 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 => {
|
||||
applyChangeSet(s, marked, ids)
|
||||
appendChat(s, { role: 'coach', kind: 'applied', 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 => { recordDismissal(s, marked); appendChat(s, { role: 'coach', kind: 'dismissed', 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>
|
||||
|
||||
{marked.changes.map(c => {
|
||||
const stale = c.status === 'stale'
|
||||
const vals = changeValues(c)
|
||||
return <div key={c.id} className={'pcard-chg' + (stale ? ' stale' : '')}>
|
||||
<div className="grow">
|
||||
<div className="pcard-chg-t">{changeTitle(c)}{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>
|
||||
{!stale && <Check checked={accepted.has(c.id)} onChange={() => toggle(c.id)} />}
|
||||
</div>
|
||||
})}
|
||||
|
||||
{!!marked.notes?.length && <div className="pcard-notes">
|
||||
{marked.notes.map((n, i) => <div key={i}>💬 {n}</div>)}
|
||||
</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="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>
|
||||
}
|
||||
|
||||
/* ---------------------------------- 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>
|
||||
</>
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
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, nav: vi.fn(), toast: vi.fn(), openSheet: vi.fn(), refresh: vi.fn() }
|
||||
state.storeSnapshot = () => ({
|
||||
S: state.S,
|
||||
user: { id: 'u1' },
|
||||
config: { coach: { enabled: 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({})),
|
||||
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) {
|
||||
mocks.S = state()
|
||||
mocks.pending = pending
|
||||
mocks.job = job
|
||||
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'])
|
||||
})
|
||||
})
|
||||
@@ -1,34 +1,40 @@
|
||||
import { useState } from 'react'
|
||||
// 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 } from '../lib/coach.js'
|
||||
import { requestPlan } from '../lib/coach-api.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, Segmented } from '../components/ui.jsx'
|
||||
|
||||
/* The intake: one topic per screen, because a single form with eleven fields is a form people
|
||||
abandon. Only the first two questions are required — everything after them improves the
|
||||
plan without gating it, and someone who wants to just get training should be able to. */
|
||||
import { Button, TextArea } from '../components/ui.jsx'
|
||||
import '../coach.css'
|
||||
|
||||
const GOALS = [
|
||||
['strength', 'Get stronger'],
|
||||
['muscle', 'Build muscle'],
|
||||
['general', 'General fitness'],
|
||||
['fatloss', 'Lose fat'],
|
||||
['endurance', 'Endurance']
|
||||
['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'],
|
||||
['returning', 'Coming back after a break'],
|
||||
['regular', 'Training regularly']
|
||||
['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']
|
||||
]
|
||||
const SESSION_MIN = [30, 45, 60, 75, 90]
|
||||
|
||||
// Equipment options come from the library's own taxonomy, most common first, so every choice
|
||||
// on screen has exercises behind it.
|
||||
@@ -38,7 +44,9 @@ const EQUIPMENT = (() => {
|
||||
return Object.keys(count).sort((a, b) => count[b] - count[a]).slice(0, 14)
|
||||
})()
|
||||
|
||||
const STEPS = ['goal', 'days', 'length', 'equipment', 'limits', 'extras']
|
||||
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()
|
||||
@@ -50,11 +58,13 @@ export default function CoachIntake() {
|
||||
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: 45, equipment: [], limitations: '', likes: '', dislikes: '', notes: '',
|
||||
sessionMin: 60, equipment: [], limitations: '', likes: '', dislikes: '', notes: '',
|
||||
...(S.coach?.profile || {})
|
||||
}))
|
||||
const set = patch => setP(v => ({ ...v, ...patch }))
|
||||
@@ -62,19 +72,32 @@ export default function CoachIntake() {
|
||||
if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE, coachMode })) { nav('/home', { replace: true }); return null }
|
||||
|
||||
const key = STEPS[step]
|
||||
const canNext = key !== 'goal' || (p.goal && p.experience)
|
||||
const last = step === STEPS.length - 1
|
||||
const canNext = key === 'goal' ? !!p.goal : key === 'experience' ? !!p.experience : key === 'length' ? p.sessionMin >= 10 : true
|
||||
const optional = ['equipment', 'limits', 'extras'].includes(key)
|
||||
|
||||
const save = () => { update(s => { const c = (s.coach = s.coach || emptyCoach()); c.profile = p }) }
|
||||
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 () => {
|
||||
save()
|
||||
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(p)
|
||||
toast(t('The Coach is building your plan…'))
|
||||
nav('/coach')
|
||||
await requestPlan(profile)
|
||||
nav('/coach', { replace: true })
|
||||
} catch (e) { toast(e.message || t('Could not ask the Coach')); setBusy(false) }
|
||||
}
|
||||
|
||||
@@ -85,103 +108,144 @@ export default function CoachIntake() {
|
||||
equipment: p.equipment.includes(e) ? p.equipment.filter(x => x !== e) : [...p.equipment, e]
|
||||
})
|
||||
|
||||
return <div className="narrow">
|
||||
<div className="hdr">
|
||||
<button className="iconbtn" onClick={() => step ? setStep(step - 1) : nav('/coach')} aria-label={t('Back')}><Icon name="chevronLeft" /></button>
|
||||
<div style={{ flex: 1, marginLeft: 10 }}>
|
||||
<h1>{editing ? t('Coach profile') : t('Your plan')}</h1>
|
||||
<div className="sub">{t('Step {0} of {1}', step + 1, STEPS.length)}</div>
|
||||
</div>
|
||||
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>
|
||||
|
||||
{/* progress rail — the wizard's only chrome; six dots read faster than "1 of 6" alone */}
|
||||
<div className="row" style={{ gap: 5, marginBottom: 14 }}>
|
||||
{STEPS.map((s, i) => <div key={s} style={{
|
||||
height: 3, flex: 1, borderRadius: 2,
|
||||
background: i <= step ? 'var(--acc)' : 'var(--surface-3)'
|
||||
}} />)}
|
||||
</div>
|
||||
<div className="ob-body">
|
||||
{key === 'consent' && <Consent onAgree={agree} onDecline={() => nav('/plan')} />}
|
||||
|
||||
<div className="card">
|
||||
{key === 'goal' && <>
|
||||
<h2 style={{ marginTop: 0 }}>{t('What are you training for?')}</h2>
|
||||
<div className="sect-b">
|
||||
{GOALS.map(([v, label]) => <button key={v} className="lrow tap" onClick={() => set({ goal: v })}>
|
||||
<span className="lrow-m"><span className="lrow-t">{t(label)}</span></span>
|
||||
{p.goal === v && <Icon name="check" className="lrow-k" />}
|
||||
</button>)}
|
||||
<div 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>
|
||||
<h2>{t('Where are you starting from?')}</h2>
|
||||
<div className="sect-b">
|
||||
{EXPERIENCE.map(([v, label]) => <button key={v} className="lrow tap" onClick={() => set({ experience: v })}>
|
||||
<span className="lrow-m"><span className="lrow-t">{t(label)}</span></span>
|
||||
{p.experience === v && <Icon name="check" className="lrow-k" />}
|
||||
</button>)}
|
||||
</>}
|
||||
|
||||
{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' && <>
|
||||
<h2 style={{ marginTop: 0 }}>{t('How many days a week?')}</h2>
|
||||
<Segmented options={[2, 3, 4, 5, 6].map(n => ({ value: n, label: String(n) }))}
|
||||
value={p.daysPerWeek} onChange={v => set({ daysPerWeek: v })} />
|
||||
<div className="muted small" style={{ margin: '14px 0 8px' }}>{t('Which days suit you? (optional)')}</div>
|
||||
<div className="week">
|
||||
{[1, 2, 3, 4, 5, 6, 0].map(d => <div key={d} className={'wday' + (p.preferredDays.includes(d) ? ' today' : '')}
|
||||
onClick={() => toggleDay(d)} style={{ cursor: 'pointer' }}>
|
||||
<div className="lbl">{t(DAYN[d]).slice(0, 2)}</div>
|
||||
<div className={'dot' + (p.preferredDays.includes(d) ? ' plan' : '')} />
|
||||
</div>)}
|
||||
<div 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' && <>
|
||||
<h2 style={{ marginTop: 0 }}>{t('How long is a session?')}</h2>
|
||||
<Segmented options={SESSION_MIN.map(n => ({ value: n, label: n + ' ' + t('min') }))}
|
||||
value={p.sessionMin} onChange={v => set({ sessionMin: v })} />
|
||||
<div className="muted small" style={{ marginTop: 12 }}>{t('The Coach fits the volume to the time you actually have, including rest between sets.')}</div>
|
||||
<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>
|
||||
<div className="ob-time">
|
||||
<input type="time" value={toHHMM(p.sessionMin || 60)} step={300} min="00:10" max="04:00"
|
||||
onChange={e => { const m = fromHHMM(e.target.value); if (m != null) set({ sessionMin: m }) }} />
|
||||
<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' && <>
|
||||
<h2 style={{ marginTop: 0 }}>{t('What can you train with?')}</h2>
|
||||
<div className="muted small" style={{ marginBottom: 10 }}>{t('Pick everything you have access to. Leave it empty and the Coach will use the whole library.')}</div>
|
||||
<div className="row" style={{ flexWrap: 'wrap', gap: 7 }}>
|
||||
{EQUIPMENT.map(e => <button key={e} className={'chip' + (p.equipment.includes(e) ? ' on' : '')}
|
||||
onClick={() => toggleEq(e)} style={{ textTransform: 'capitalize' }}>{e}</button>)}
|
||||
<div 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' && <>
|
||||
<h2 style={{ marginTop: 0 }}>{t('Anything to work around?')}</h2>
|
||||
<div className="muted small" style={{ marginBottom: 10 }}>
|
||||
{t('Injuries, joints that complain, movements you cannot do, or practical limits like training at 6am in a flat.')}
|
||||
</div>
|
||||
<TextArea rows={4} maxLength={600} value={p.limitations} onChange={e => set({ limitations: e.target.value })}
|
||||
placeholder={t('e.g. “dodgy left shoulder — no barbell overhead press”')} />
|
||||
<div className="dim small" style={{ marginTop: 8, lineHeight: 1.5, color: 'var(--yellow)' }}>
|
||||
{t('If something actually hurts, see a professional — the Coach will program conservatively but it cannot diagnose anything.')}
|
||||
<div 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' && <>
|
||||
<h2 style={{ marginTop: 0 }}>{t('Anything else?')}</h2>
|
||||
<div className="muted small" style={{ marginBottom: 6 }}>{t('Exercises you love')}</div>
|
||||
<TextArea rows={2} maxLength={300} value={p.likes} onChange={e => set({ likes: e.target.value })} placeholder={t('e.g. “deadlifts, anything with a kettlebell”')} />
|
||||
<div className="muted small" style={{ margin: '12px 0 6px' }}>{t('Exercises you would rather not')}</div>
|
||||
<TextArea rows={2} maxLength={300} value={p.dislikes} onChange={e => set({ dislikes: e.target.value })} placeholder={t('e.g. “I hate lunges”')} />
|
||||
<div className="muted small" style={{ margin: '12px 0 6px' }}>{t('Anything you want the Coach to know')}</div>
|
||||
<TextArea rows={3} maxLength={600} value={p.notes} onChange={e => set({ notes: e.target.value })} placeholder={t('e.g. “I want visible arms progress by spring”')} />
|
||||
<div 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>
|
||||
|
||||
<div className="row" style={{ gap: 10 }}>
|
||||
{step > 0 && <Button onClick={() => setStep(step - 1)} style={{ flex: 1 }}>{t("Back")}</Button>}
|
||||
{!last
|
||||
? <Button variant="primary" style={{ flex: 1 }} disabled={!canNext} onClick={() => setStep(step + 1)}>{t('Next')}</Button>
|
||||
: <Button variant="primary" style={{ flex: 1 }} icon="sparkles" disabled={busy} onClick={finish}>
|
||||
{editing ? t('Save') : t('Build my plan')}
|
||||
</Button>}
|
||||
</div>
|
||||
{!canNext && <div className="dim small" style={{ textAlign: 'center', marginTop: 10 }}>{t('Pick a goal and where you are starting from to continue.')}</div>}
|
||||
<div style={{ height: 20 }} />
|
||||
{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>
|
||||
</>
|
||||
}
|
||||
Reference in new issue
Block a user