From ab1adcdd4f512befc2c824e3a8df3a738dc04ba3 Mon Sep 17 00:00:00 2001 From: Alex Date: Thu, 6 Aug 2026 11:02:25 +0100 Subject: [PATCH] Coach: the screens, and the four things they were supposed to say MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The Coach hub, the six-screen intake, the proposal review with per-change accept/reject, and the admin card — wired into App.jsx and Admin.jsx. Nothing renders unless the instance offers the Coach, so an admin page on a box that never enabled it is the page it was before. Four gaps I named earlier and owed this PR: CoachProposal had no health disclaimer. The hub and the intake screen both carry one; the screen where changes are actually accepted did not, which is the one place it matters — that tap changes what somebody does with their body next week. It sits immediately above the accept button on both proposal kinds rather than at the top of a scrolling page, so it is on screen at the decision. The admin card never showed whether the privilege drop can be performed. It fails closed, so when it cannot, nothing runs at all, and the admin was left to learn that from a user reporting silence. It now states the verdict, and the server's own reason when the answer is no. Whose account is being spent was not stated anywhere in the UI. Both the admin card and the user's Coach screen have to name it, and that is only true if neither infers it from settings — so coach-api gained the /api/coach/account call that PR 1 built the route for and nothing had used since. The credential UI was wired to a server shape that does not exist: it read d.auth.state, which GET /api/admin/coach never sent, and posted to /auth/setup-token, /auth/key and /auth/disconnect, none of which are routes. Every credential button was dead. The card now uses the connect/disconnect routes from 3/6, and the admin payload carries an auth summary — state, type and account label, never the credential — with `unreadable` as its own state, because ./data restored without its `secret` has a specific cause and a specific fix rather than being "not connected". Left out on purpose: the ChatGPT device-login sheet. It is Codex's, it calls routes that do not exist, and Codex is 6/6 — so it comes back with the provider it belongs to rather than shipping as unreachable UI here. api 72/72, frontend 404/404, build clean, 11 locales in sync. The new strings fall back to English until 5/6 adds them. Co-Authored-By: Claude Opus 5 --- api/coach/routes.js | 12 + frontend/src/App.jsx | 9 + frontend/src/lib/coach-api.js | 97 +++++++++ frontend/src/lib/coach-demo.js | 132 +++++++++++ frontend/src/views/Admin.jsx | 5 + frontend/src/views/AdminCoach.jsx | 244 +++++++++++++++++++++ frontend/src/views/Coach.jsx | 314 +++++++++++++++++++++++++++ frontend/src/views/CoachIntake.jsx | 186 ++++++++++++++++ frontend/src/views/CoachProposal.jsx | 237 ++++++++++++++++++++ 9 files changed, 1236 insertions(+) create mode 100644 frontend/src/lib/coach-api.js create mode 100644 frontend/src/lib/coach-demo.js create mode 100644 frontend/src/views/AdminCoach.jsx create mode 100644 frontend/src/views/Coach.jsx create mode 100644 frontend/src/views/CoachIntake.jsx create mode 100644 frontend/src/views/CoachProposal.jsx diff --git a/api/coach/routes.js b/api/coach/routes.js index d4329a0..2aaa162 100644 --- a/api/coach/routes.js +++ b/api/coach/routes.js @@ -120,6 +120,18 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) { runtime: { ok: !!check.ok, version: check.version || null, error: check.error || null }, authMode: cfg.authMode, boundUid: cfg.boundUid || null, + /* Whether a credential is filed, and whose — never the credential. `unreadable` is its + own state rather than "not connected" because it has a specific cause and a specific + fix: ./data was restored without its `secret`, so the blob is intact and undecryptable, + and connecting again is the way out. */ + auth: (() => { + if (!cfgStore.providerMeta(cfg).oauthEnv && !cfgStore.providerMeta(cfg).apiKeyEnv) { + return { state: 'not-required' }; + } + if (!cfg.auth || !cfg.auth.data) return { state: 'none' }; + if (!cfgStore.decrypt(cfg.auth.data)) return { state: 'unreadable' }; + return { state: 'connected', type: cfg.auth.type || null, account: cfg.auth.account || null }; + })(), // Whether the privilege drop can actually be performed. Surfaced because the control // now fails closed: if this reads false, no job runs, and the admin needs to know that // from the card rather than from a user reporting that nothing happens. diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index e7c8c52..16e997b 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -24,6 +24,9 @@ import History from './views/History.jsx' import Library from './views/Library.jsx' import Settings from './views/Settings.jsx' import Admin from './views/Admin.jsx' +import Coach from './views/Coach.jsx' +import CoachIntake from './views/CoachIntake.jsx' +import CoachProposal from './views/CoachProposal.jsx' bindUI(useUI) // lets the shared controls open sheets without importing the store at module scope @@ -75,6 +78,12 @@ function Shell() { } /> } /> } /> + {/* The Coach screens gate themselves on the instance config; the routes exist + unconditionally so a deep link from a notification lands somewhere sane + rather than on the catch-all. */} + } /> + } /> + } /> : } /> } /> diff --git a/frontend/src/lib/coach-api.js b/frontend/src/lib/coach-api.js new file mode 100644 index 0000000..6fa3d54 --- /dev/null +++ b/frontend/src/lib/coach-api.js @@ -0,0 +1,97 @@ +// Talking to the Coach endpoints, and knowing when to stop. +// +// Jobs are minutes-scale, so the client polls. The one rule worth stating: polling only runs +// while a Coach surface is on screen or a job is known to be in flight. An app that pings the +// server every thirty seconds forever because a feature exists is an app that costs battery +// for a feature nobody is using. + +import { useEffect, useState, useCallback, useRef } from 'react' +import { api } from './api.js' +import { DEMO } from './demo.js' +import { useStore } from '../store/useStore.js' + +const POLL_MS = 3000 // a job is running: often enough to feel live +const IDLE_MS = 60000 // a Coach screen is open but nothing is running + +// The demo build has no backend, so it answers these locally with a canned proposal built +// from its own seeded profile (lib/coach-demo.js). Everything downstream — validation, +// staleness, apply, revert, the log — runs unchanged; only the provider is faked. The module +// is imported dynamically so none of it lands in a self-hosted bundle. +let demoMod = null +const demo = async () => (demoMod = demoMod || await import('./coach-demo.js')) +const S = () => useStore.getState().S + +export const coachStatus = async () => DEMO ? (await demo()).demoStatus() : api('/api/coach/status') +export const requestReview = async note => DEMO ? (await demo()).demoReview(S()) : api('/api/coach/review', { method: 'POST', body: JSON.stringify({ note: note || '' }) }) +export const requestPlan = async intake => DEMO ? (await demo()).demoPlan(S(), intake) : api('/api/coach/plan', { method: 'POST', body: JSON.stringify({ intake }) }) +export const refinePlan = async text => DEMO ? (await demo()).demoRefine(S()) : api('/api/coach/plan', { method: 'POST', body: JSON.stringify({ refine: text }) }) +export const resolvePending = async body => DEMO ? (await demo()).demoResolve() : api('/api/coach/pending/resolve', { method: 'POST', body: JSON.stringify(body) }) +export const forgetCoach = async () => DEMO ? (await demo()).demoResolve() : api('/api/coach/forget', { method: 'POST', body: '{}' }) +export const disclosure = async () => DEMO ? (await demo()).demoDisclosure() : api('/api/coach/disclosure') + +/* Whose provider account this profile is about to spend. Its own call because the constraint is + that the Coach screen states it too, not just the admin card — and because in instance mode a + second profile is refused outright, which is something the user has to be able to read before + they ask for anything rather than after a job is turned down. */ +export const coachAccount = async () => + DEMO ? { mode: 'instance', provider: 'demo', providerLabel: 'Demo', account: null, connected: true, reason: null, message: null } + : api('/api/coach/account') + +/* Admin-only. The token is write-only from the client's side: it goes up once and is never + read back, so there is deliberately no "show me the current credential" call to pair with it. */ +export const connectCredential = body => api('/api/admin/coach/connect', { method: 'POST', body: JSON.stringify(body) }) +export const disconnectCredential = () => api('/api/admin/coach/disconnect', { method: 'POST', body: '{}' }) + +/** + * Live job/proposal state. + * + * `active` lets a caller (the Home card) subscribe only while it is mounted and visible; + * everything else keeps the poll off. Errors are swallowed on purpose — a Coach status call + * failing while you are mid-workout is not something to interrupt anyone about. + */ +export function useCoachStatus(active = true) { + const [state, setState] = useState({ job: null, pending: null, cap: null, loading: true }) + const timer = useRef(null) + + const refresh = useCallback(async () => { + try { + const s = await coachStatus() + setState({ ...s, loading: false }) + return s + } catch { + setState(s => ({ ...s, loading: false })) + return null + } + }, []) + + useEffect(() => { + if (!active) return + let stopped = false + const tick = async () => { + const s = await refresh() + if (stopped) return + timer.current = setTimeout(tick, s?.job ? POLL_MS : IDLE_MS) + } + tick() + return () => { stopped = true; clearTimeout(timer.current) } + }, [active, refresh]) + + return { ...state, refresh } +} + +// Server failure classes, in the app's voice. The provider's own words go to the admin card; +// what a lifter needs is what it means for them and whether trying again will help. +export const JOB_ERRORS = { + off: 'The Coach isn’t set up on this instance.', + busy: 'The Coach is already thinking about your training.', + cap: 'The Coach is resting — try again tomorrow.', + consent: 'The Coach needs your go-ahead first.', + timeout: 'The Coach took too long and gave up.', + auth: 'The Coach couldn’t sign in to its provider — the instance owner needs to check its setup.', + missing: 'The Coach isn’t installed properly on this instance.', + provider: 'The Coach couldn’t run — the instance owner needs to check its setup.', + unusable: 'The Coach answered with something the app couldn’t use.', + restart: 'The server restarted while the Coach was thinking.', + nostate: 'The Coach couldn’t read your training data.', + internal: 'Something went wrong on the server.' +} diff --git a/frontend/src/lib/coach-demo.js b/frontend/src/lib/coach-demo.js new file mode 100644 index 0000000..d8fbf4c --- /dev/null +++ b/frontend/src/lib/coach-demo.js @@ -0,0 +1,132 @@ +// The Coach, in the demo build. +// +// The GitHub Pages demo has no backend at all, so there is nothing to run a CLI and nothing +// to poll. Rather than hide the feature there — it is the most interesting thing the app +// does — the demo answers the same calls locally with a canned proposal. +// +// It is built from the demo profile's actual routines rather than hard-coded, so every id +// resolves, the before/after values are real, and applying it exercises exactly the same +// code path as a live instance: validate, snapshot, apply, log, revert. What is faked is the +// provider, not the feature. +// +// Nothing here ships in a self-hosted bundle: every entry point is behind DEMO, which Vite +// replaces at build time. + +import { EXIDX, EXDB } from './exercises.js' +import { modeOf } from './history.js' +import { planHash } from './coach.js' +import { t } from './i18n.js' + +const DELAY = 2200 // long enough to see "the Coach is thinking…", short enough to forgive + +let pending = null +let job = null +let timer = null + +const iso = d => d.toISOString().slice(0, 10) + +/** A change-set that reads like a real one, aimed at whatever the demo profile actually has. */ +function buildReview(S) { + const routine = (S.routines || []).find(r => (r.ex || []).length >= 2) + if (!routine) return null + const reps = (routine.ex || []).filter(e => modeOf(e) === 'reps') + const first = reps[0] || routine.ex[0] + const second = reps[1] || routine.ex[1] + const other = (S.routines || []).find(r => r.id !== routine.id) + + // Something plausible that is *not* in this routine, from the same body part as the first + // exercise — a swap the reader can believe rather than a random pick out of 1,324. + const bp = EXIDX[first.id]?.bp + const swapTo = EXDB.find(e => e.bp === bp && e.eq === 'dumbbell' && !(routine.ex || []).some(x => x.id === e.id)) + || EXDB.find(e => e.bp === bp && !(routine.ex || []).some(x => x.id === e.id)) + + const sessions = (S.workouts || []).slice(-9) + const changes = [] + if (swapTo) changes.push({ + id: 'd1', type: 'swap-exercise', target: { routineId: routine.id, exId: first.id }, + before: EXIDX[first.id]?.n || first.id, after: { id: swapTo.id, name: swapTo.n }, + why: t('Every top set on this one came in at RPE 9.5 or above for three sessions and the weight has not moved. Swapping the movement for four weeks usually breaks that stall faster than grinding the same one.') + }) + if (second) changes.push({ + id: 'd2', type: 'sets', target: { routineId: routine.id, exId: second.id }, + before: second.sets ?? 3, after: Math.max(1, (second.sets ?? 3) - 1), + why: t('Sessions have been running about fifteen minutes over. This is the accessory with the least to lose from one set fewer.') + }) + if (other) changes.push({ + id: 'd3', type: 'week', target: { weekday: 6 }, before: null, after: other.id, + why: t('You have moved this session to Saturday three weeks running. Better the plan says so than that you keep overriding it.') + }) + + return { + id: 'demo-review', kind: 'review', createdAt: Date.now(), expiresAt: Date.now() + 864e5, + planHash: planHash(S), iteration: 1, + summary: t('Three things worth changing, and one worth knowing about. Everything else is working — the squat and the pulls are both progressing on schedule.'), + evidence: { from: sessions[0]?.d || iso(new Date(Date.now() - 28 * 864e5)), to: sessions.at(-1)?.d || iso(new Date()), sessions: sessions.length || 9 }, + changes, + notes: [t('Body weight has been flat for four weeks while the goal is to gain. That is a kitchen problem rather than a training one — the plan is not what is holding it back.')] + } +} + +/** A small, honest starter plan for the demo's creation flow. */ +function buildPlan(S, intake) { + const pick = (bp, eq) => EXDB.find(e => e.bp === bp && (!eq || e.eq === eq)) || EXDB.find(e => e.bp === bp) + const days = intake?.preferredDays?.length ? intake.preferredDays.slice(0, 3) : [1, 3, 5] + const eq = (intake?.equipment || [])[0] || null + const mk = (id, name, sets, reps, why) => ({ id, sets, reps, mode: 'reps', why }) + const routines = [ + { + id: 'dr1', name: t('Full body A'), emoji: '💪', prog: 'linear', + why: t('The two big lower-body and pressing patterns first, while you are fresh.'), + ex: [ + mk(pick('upper legs', eq)?.id, null, 3, 8, t('The main lower-body driver — where most of the strength comes from.')), + mk(pick('chest', eq)?.id, null, 3, 10, t('Horizontal pressing, the other half of the session.')), + mk(pick('back', eq)?.id, null, 3, 10, t('A pull for every press, so the shoulders stay balanced.')) + ].filter(e => e.id) + }, + { + id: 'dr2', name: t('Full body B'), emoji: '🏋️', prog: 'linear', + why: t('The same patterns, different variations — enough overlap to progress, enough difference to stay fresh.'), + ex: [ + mk(pick('upper legs', eq)?.id, null, 3, 10, t('Same pattern, higher reps than day A.')), + mk(pick('shoulders', eq)?.id, null, 3, 10, t('Vertical pressing.')), + mk(pick('upper arms', eq)?.id, null, 3, 12, t('Direct arm work, since you asked for it.')) + ].filter(e => e.id) + } + ] + const week = {} + days.forEach((d, i) => { week[d] = routines[i % routines.length].id }) + return { + id: 'demo-plan', kind: 'create', createdAt: Date.now(), expiresAt: Date.now() + 864e5, iteration: 1, + planHash: planHash(S), + summary: t('A two-day rotation across three sessions a week, built around the equipment you listed. Compounds first, one pull for every press, and enough overlap between the days that nothing goes two weeks without being trained.'), + bundle: { + opengym_plan: 1, name: t('Coach plan'), + summary: t('A two-day rotation across three sessions a week, built around the equipment you listed. Compounds first, one pull for every press, and enough overlap between the days that nothing goes two weeks without being trained.'), + basedOn: (S.workouts || []).length ? t('Based on the training already in this demo profile.') : t('No training history yet — starting conservatively.'), + week, routines, customEx: [] + } + } +} + +/* ---------------- the API surface the demo stands in for ---------------- */ + +export const demoStatus = () => ({ job, pending, cap: { used: 0, limit: 0 } }) + +function start(kind, make) { + if (job) throw Object.assign(new Error(t('The Coach is already thinking about your training.')), { status: 409 }) + job = { id: 'demo-' + kind, kind, state: 'running', startedAt: Date.now() } + clearTimeout(timer) + timer = setTimeout(() => { pending = make(); job = null }, DELAY) + return { job } +} +export const demoReview = S => start('review', () => buildReview(S)) +export const demoPlan = (S, intake) => start('create', () => buildPlan(S, intake)) +export const demoRefine = S => start('create', () => { + const p = buildPlan(S, null) + return { ...p, iteration: (pending?.iteration || 1) + 1, summary: t('Revised as you asked. Everything you did not question is exactly as it was.') + ' ' + p.summary } +}) +export const demoResolve = () => { pending = null; return { ok: true } } +export const demoDisclosure = () => ({ + provider: 'demo', providerLabel: t('the configured AI provider'), + categories: ['plan', 'training', 'bodyweight', 'profile', 'prefs'], version: 1 +}) diff --git a/frontend/src/views/Admin.jsx b/frontend/src/views/Admin.jsx index c981c73..63ca1da 100644 --- a/frontend/src/views/Admin.jsx +++ b/frontend/src/views/Admin.jsx @@ -8,6 +8,7 @@ import { workoutVolume, setsDone } from '../lib/history.js' import { confirmSheet } from '../sheets.jsx' import Icon from '../components/Icon.jsx' import { Button } from '../components/ui.jsx' +import AdminCoach from './AdminCoach.jsx' // Admin-only operator dashboard (owner passkey + admin flag; guarded again server-side). // Deliberately English-only — it isn't part of the translated end-user surface, so it stays @@ -132,6 +133,10 @@ export default function Admin() { )} } + {/* 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. */} + +

Users

diff --git a/frontend/src/views/AdminCoach.jsx b/frontend/src/views/AdminCoach.jsx new file mode 100644 index 0000000..0aae6ab --- /dev/null +++ b/frontend/src/views/AdminCoach.jsx @@ -0,0 +1,244 @@ +import { useEffect, useState } from 'react' +import { useUI } from '../store/useUI.js' +import { api } from '../lib/api.js' +import Icon from '../components/Icon.jsx' +import { Button, Switch, TextField } from '../components/ui.jsx' + +/* The operator's side of the Coach: is it on, can it reach a model, and what has it been + doing. Like the rest of the admin dashboard this is deliberately English-only — it isn't + part of the translated end-user surface. + * + * What it never shows: anybody's intake answers, payloads or proposals. An admin can enable + * the feature and see that jobs ran; they cannot read what their users asked it. */ + +const rel = ts => { + if (!ts) return 'never' + const s = Math.max(0, (Date.now() - new Date(ts).getTime()) / 1000) + if (s < 60) return 'just now' + if (s < 3600) return Math.floor(s / 60) + 'm ago' + if (s < 86400) return Math.floor(s / 3600) + 'h ago' + return Math.floor(s / 86400) + 'd ago' +} + +export default function AdminCoach() { + const toast = useUI(s => s.toast) + const openSheet = useUI(s => s.openSheet) + const [d, setD] = useState(null) + const [busy, setBusy] = useState(false) + + const load = () => api('/api/admin/coach').then(setD).catch(e => toast(e.message || 'Failed to load')) + useEffect(() => { load() }, []) + + const patch = async body => { + setBusy(true) + try { await api('/api/admin/coach/config', { method: 'POST', body: JSON.stringify(body) }); await load() } + catch (e) { toast(e.message) } + setBusy(false) + } + const test = async () => { + setBusy(true) + try { + const r = await api('/api/admin/coach/test', { method: 'POST', body: '{}' }) + toast(r.ok ? 'Coach test passed ✅' : 'Test failed: ' + (r.error || 'unknown')) + await load() + } catch (e) { toast(e.message) } + setBusy(false) + } + const disconnect = async () => { + setBusy(true) + try { await api('/api/admin/coach/disconnect', { method: 'POST', body: '{}' }); toast('Disconnected'); await load() } + catch (e) { toast(e.message) } + setBusy(false) + } + + if (!d) return
Loading Coach status…
+ + if (d.disabledByEnv) return
+

AI Coach

+
Force-disabled by COACH_DISABLED in the environment. Remove it to configure the Coach here.
+
+ + const meta = d.providers.find(p => p.id === d.provider) || {} + const authed = d.auth?.state === 'connected' || d.auth?.state === 'not-required' + const live = d.enabled && d.runtime.ok && authed + + return
+
+

AI Coach

+ patch({ enabled: v })} /> +
+ + {!d.enabled &&
Off. Users see no Coach anywhere in the app.
} + + {d.enabled && <> +
+
Runtime
+
{d.runtime.ok ? 'ready' : 'missing'}
+
Credential
+
{authLabel(d.auth)}
+
Jobs today
{d.jobsToday}
+
Last run
{rel(d.lastSuccess?.at)}
+
+ + {d.runtime.version &&
{meta.runtime || meta.label} · {d.runtime.version}
} + {!d.runtime.ok && d.runtime.error &&
{d.runtime.error}
} + + {/* 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 && +
+ Jobs are disabled: {d.unprivileged.why}. No job will run until this is fixed. +
} + {d.unprivileged?.ok && +
+ Jobs run unprivileged: {d.unprivileged.dropped ? 'yes' : 'no — this host has no separate user to drop to'} +
} + + {/* 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. */} +
+ {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.'} +
+ + {/* provider */} +

Provider

+
+ {d.providers.map(p => )} +
+ + {/* credential */} + {(meta.setupToken || meta.apiKey) && <> +

Credential

+ {d.auth?.state === 'connected' ? <> +
+ Connected{d.auth.account ? ' as ' + d.auth.account : ''} via {credentialLabel(d.auth.type)} · {rel(d.auth.connectedAt)} +
+
+ + +
+ : <> + {d.auth?.state === 'expired' &&
The stored credential expired — connect again.
} + {d.auth?.state === 'replace-required' &&
+ The old Claude credential is no longer used. Add a Claude Code setup token instead. +
} + {d.auth?.state === 'unreadable' &&
+ The stored credential can't be decrypted — this usually means ./data was restored without its secret file. Connect again. +
} +
+ {meta.setupToken && } + {meta.apiKey && !meta.setupToken && } +
+ } + } + + {/* limits */} +

Limits

+
+ + +
+
0 = no limit. Every job is one session on your provider account.
+ +

Model

+ e.target.value !== (d.model || '') && patch({ model: e.target.value })} /> + + {d.lastError && <> +

Last failure

+
{d.lastError.errorClass}{d.lastError.detail ? ' — ' + d.lastError.detail : ''}
+
{rel(d.lastError.at)}
+ } + + {!!d.recent?.length && <> +

Recent jobs

+ {d.recent.slice(0, 8).map((e, i) =>
+ {e.kind}{e.trigger === 'scheduled' ? ' · scheduled' : ''} + + {e.outcome} + {e.ms ? ' · ' + Math.round(e.ms / 1000) + 's' : ''} · {rel(e.at)} + +
)} + } + } +
+} + +const authLabel = a => ({ + connected: 'connected', 'not-required': 'n/a', disconnected: 'needed', expired: 'expired', unreadable: 'unreadable', 'replace-required': 'replace' +}[a?.state] || '—') + +const credentialLabel = type => ({ + 'cli-token': 'Claude Code setup token', 'chatgpt-cli': 'ChatGPT CLI login', oauth: 'legacy token', apikey: 'API key' +}[type] || 'credential') + +/* ------------------------------- setup token -------------------------------- */ + +function SetupTokenSheet({ close, onDone, label }) { + const toast = useUI(s => s.toast) + const [token, setToken] = useState('') + // Which account this token belongs to. Optional, and stored as a plain label — it is what the + // admin card and the user's Coach screen both show when they name whose account is spent. + const [account, setAccount] = useState('') + const [busy, setBusy] = useState(false) + + const save = async () => { + setBusy(true) + try { + const r = await api('/api/admin/coach/connect', { method: 'POST', body: JSON.stringify({ type: 'cli-token', token: token.trim(), account: account.trim() }) }) + setToken('') + toast(r.test?.ok ? 'Connected ✅' : 'Saved, but the test failed: ' + (r.test?.error || '')) + close(); onDone() + } catch (e) { toast(e.message); setBusy(false) } + } + + return <> +

Connect {label}

+
+ On a trusted computer where you use Claude Code, run claude setup-token, complete its normal browser sign-in, then paste the token it prints here. This app never opens or handles Claude's authorization flow. +
+ setToken(e.target.value)} /> +
+ setAccount(e.target.value)} /> +
+ +
+ +} + +function ApiKeySheet({ close, onDone, label }) { + const toast = useUI(s => s.toast) + const [key, setKey] = useState('') + const [busy, setBusy] = useState(false) + const save = async () => { + setBusy(true) + try { + const r = await api('/api/admin/coach/connect', { method: 'POST', body: JSON.stringify({ type: 'apikey', token: key.trim() }) }) + toast(r.test?.ok ? 'Key saved ✅' : 'Saved, but the test failed: ' + (r.test?.error || '')) + close(); onDone() + } catch (e) { toast(e.message); setBusy(false) } + } + return <> +

{label} API key

+
+ Stored encrypted on this server and passed to the provider runtime only while a job runs. It is never shown again and never leaves the server. +
+ setKey(e.target.value)} /> +
+ +
+ +} diff --git a/frontend/src/views/Coach.jsx b/frontend/src/views/Coach.jsx new file mode 100644 index 0000000..d9340f4 --- /dev/null +++ b/frontend/src/views/Coach.jsx @@ -0,0 +1,314 @@ +import { useEffect, useState } from 'react' +import { useNavigate } from 'react-router-dom' +import { useStore, DEF } from '../store/useStore.js' +import { useUI } from '../store/useUI.js' +import { t } from '../lib/i18n.js' +import { fmtDate } from '../lib/format.js' +import { DEMO } from '../lib/demo.js' +import { MOBILE } from '../lib/mobile.js' +import { + coachAvailable, hasConsent, CONSENT_VERSION, emptyCoach, + canRevert, revertLast, changeTitle, recordDismissal +} from '../lib/coach.js' +import { + useCoachStatus, requestReview, resolvePending, forgetCoach, disclosure, JOB_ERRORS +} from '../lib/coach-api.js' +import { confirmSheet } from '../sheets.jsx' +import Icon from '../components/Icon.jsx' +import { Section, Row, Button, TextArea, Switch, SelectRow } from '../components/ui.jsx' + +/* The Coach's home: what it's doing, what it's proposing, what it has done before, and every + switch that turns it off. Deliberately one screen — a feature that edits your training plan + should not scatter its controls, least of all the ones that stop it. */ + +const GOALS = ['strength', 'muscle', 'general fitness', 'fat loss', 'endurance'] + +// Rendered from the same list the server builds payloads from (GET /api/coach/disclosure), +// so the promise on screen cannot drift from what actually leaves the box. +const CATEGORY_TEXT = { + plan: ['Your plan', 'Routines, exercises, sets and reps, your weekly schedule and progression settings.'], + training: ['Your logged training', 'Sets you logged in the review window — weights, reps, times, effort ratings and how long sessions took.'], + bodyweight: ['Body weight', 'Weigh-ins from the same window, and your goal weight if you set one.'], + profile: ['What you tell the Coach', 'Your intake answers, including any limitations or injuries you describe.'], + prefs: ['A few preferences', 'Your unit, your language and which effort scale you log.'] +} + +export default function Coach() { + const nav = useNavigate() + const S = useStore(s => s.S) + const user = useStore(s => s.user) + const config = useStore(s => s.config) + const update = useStore(s => s.update) + const toast = useUI(s => s.toast) + const [note, setNote] = useState('') + const [busy, setBusy] = useState(false) + const { job, pending, cap, refresh } = useCoachStatus(true) + + // Gating lives in one predicate; if the instance isn't offering the Coach this route simply + // isn't a place you can be. + useEffect(() => { if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE })) nav('/home', { replace: true }) }, [config, user]) + if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE })) return null + + const consented = hasConsent(S) + const coach = S.coach || emptyCoach() + + const askReview = async () => { + setBusy(true) + try { + await requestReview(note) + setNote('') + toast(t('The Coach is reading your training…')) + refresh() + } catch (e) { toast(e.message || t('Could not ask the Coach')) } + setBusy(false) + } + + const turnOff = () => confirmSheet({ + title: t('Turn the Coach off?'), + message: t('Any pending suggestion is discarded and scheduled reviews stop. Your Coach history stays, and you can turn it back on anytime.'), + confirmText: t('Turn off'), danger: true, + onConfirm: async () => { + try { await forgetCoach() } catch (e) { /* server-side copy goes on the next call */ } + update(s => { s.coach = { ...(s.coach || emptyCoach()), consent: null, cadence: 'off' } }) + toast(t('The Coach is off')) + nav('/home') + } + }) + + const doRevert = () => confirmSheet({ + title: t('Undo the last Coach changes?'), + message: t('Your plan goes back to how it was before you accepted them. Workouts you have logged since are untouched.'), + confirmText: t('Undo'), + onConfirm: () => { + let ok = false + update(s => { ok = revertLast(s) }) + toast(ok ? t('Plan restored') : t('Nothing to undo')) + } + }) + + return
+
+ +
+

{t('Coach')}

+
{t('Plan design and reviews, from your own training')}
+
+
+ + {!consented + ? refresh()} /> + : <> + + + {!job && !pending &&
+

{t('Ask for a review')}

+
+ {t('The Coach reads what you have actually logged since its last look and suggests changes to your plan — each one with its reason.')} +
+