Coach: Vorschlaege bleiben, Diagramme in den Karten, Workout-Debrief, Vergleich auf der Instanz, Routine verbessern

Was der Coach vorgeschlagen hat, verschwindet nach Ja/Nein nicht mehr: die Chat-Zeile traegt
eine Referenz ins Log, das jetzt jede Aenderung samt before/after (auch abgelehnte), Notizen,
Evidenz und bei Plaenen die Routinen behaelt; eine Recap-Karte im Thread und ein Verlauf-
Sheet oeffnen alles wieder. Unter jeder Review liegen die Zahlen aus dem zitierten Fenster —
Sessions, Dauer, Volumen, Koerpergewicht als Kurve mit Ziel, geschaetztes 1RM erste→letzte
Session, Saetze pro Koerperregion — auf dem Geraet gerechnet (lib/coach-insights.js).

Neu: Job-Art `debrief` (eine Session, kein Planeingriff: Score 1–10, lief gut / beobachten /
naechstes Mal; validateDebrief im Core, eigener Prompt), Vergleich mit anderen auf der
Instanz (Admin-Schalter `community`, pro Person Opt-in serverseitig, Mediane ab drei
Teilnehmern, Epley-1RM, lb→kg; auch als `cohort` im Prompt), und "Routine verbessern"
als fokussierte Review. Schnell-Chips ueber dem Composer, deutsche Strings, Doku, Changelog.
Tests: api 136, frontend 799, mcp 36.
This commit is contained in:
Duarte Santos committed 2026-08-30 14:31:10 +02:00
1 parent b3340e31b5
commit 9edcdaa9f3
31 files changed
+1657 -68

No files matched your search

+98
View File
@@ -181,3 +181,101 @@
/* menu sheet rows reuse .lrow; the cadence sub-sheet reuses Section */
.chat-menu .lrow-t{font-size:17px}
/* ---------- quick actions above the composer ---------- */
.chips-row{max-width:560px;margin:0 auto 8px;display:flex;gap:6px;overflow-x:auto;scrollbar-width:none;padding:0 2px}
.chips-row::-webkit-scrollbar{display:none}
.qchip{
flex:none;display:inline-flex;align-items:center;gap:6px;padding:8px 13px;border-radius:99px;
background:var(--surface);color:var(--label);font-size:13px;font-weight:500;letter-spacing:-.006em;
border:1px solid var(--sep-op);transition:transform var(--fast),background var(--fast)
}
.qchip .icn{font-size:14px;color:var(--acc)}
.qchip:active{transform:scale(.96);background:var(--surface-2)}
.chat-empty{font-size:14px;color:var(--label-2);line-height:1.45;padding:14px 4px}
/* ---------- the numbers behind a card ---------- */
.ins{padding:6px 18px 4px;display:grid;gap:10px}
.ins-tiles{display:grid;grid-template-columns:repeat(4,1fr);gap:6px}
.ins-tile{background:var(--surface-2);border-radius:14px;padding:10px 6px 9px;text-align:center;min-width:0}
.ins-tile-v{font-size:19px;font-weight:700;letter-spacing:-.03em;font-variant-numeric:tabular-nums;line-height:1.05;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.ins-tile-l{font-size:10.5px;color:var(--label-2);margin-top:4px;letter-spacing:-.004em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.ins-block{background:var(--surface-2);border-radius:16px;padding:12px 14px 10px}
.ins-h{display:flex;justify-content:space-between;align-items:baseline;gap:8px;font-size:13px;font-weight:600;letter-spacing:-.008em;margin-bottom:6px}
.ins-h .dim{font-weight:400;font-size:12px}
.ins-block .chart{margin:2px -4px 0}
.ins-delta{font-size:12px;font-weight:600;font-variant-numeric:tabular-nums;color:var(--label-2);white-space:nowrap}
.ins-delta.up{color:var(--green)}
.ins-delta.down{color:var(--red)}
.ins-row{display:flex;align-items:center;gap:8px;padding:7px 0;border-top:var(--hair) solid var(--sep)}
.ins-row:first-of-type{border-top:none}
.ins-row-n{flex:1;min-width:0;font-size:14px;letter-spacing:-.008em;text-transform:capitalize;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.ins-row-n .dim{font-size:12px;text-transform:none}
.ins-row-v{display:flex;align-items:center;gap:4px;font-size:12px}
.ins-row-v .icn{font-size:11px;color:var(--label-3)}
.ins-row-v .tag{font-size:12px;font-variant-numeric:tabular-nums}
.ins-bar{display:grid;grid-template-columns:76px 1fr 28px;align-items:center;gap:8px;padding:4px 0}
.ins-bar-l{font-size:12.5px;color:var(--label-2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.ins-bar-t{height:8px;border-radius:99px;background:var(--surface-3);overflow:hidden}
.ins-bar-t i{display:block;height:100%;border-radius:99px;background:var(--acc);transition:width var(--med) var(--ease)}
.ins-bar-v{font-size:12px;font-weight:600;text-align:right;font-variant-numeric:tabular-nums}
.ins-cmp{font-size:12.5px;color:var(--label-2);line-height:1.5;display:flex;flex-wrap:wrap;gap:4px 10px;align-items:baseline;padding:0 2px}
.pcard-notes div{display:flex;gap:8px;align-items:flex-start}
.pcard-notes .icn{color:var(--yellow);flex:none;font-size:15px;margin-top:1px}
/* ---------- a workout debrief ---------- */
.deb-score{display:flex;align-items:center;gap:14px;padding:6px 18px 10px}
.deb-ring{
--pct:.5;width:64px;height:64px;border-radius:99px;flex:none;display:flex;align-items:baseline;justify-content:center;
background:conic-gradient(var(--acc) calc(var(--pct) * 360deg),var(--surface-3) 0);position:relative
}
.deb-ring::before{content:"";position:absolute;inset:6px;border-radius:99px;background:var(--surface)}
.deb-ring span{position:relative;font-size:24px;font-weight:700;letter-spacing:-.03em;line-height:64px}
.deb-ring small{position:relative;font-size:11px;color:var(--label-2);line-height:64px;margin-left:1px}
.deb-score-t{display:flex;flex-direction:column;gap:2px;min-width:0}
.deb-score-t b{font-size:17px;font-weight:600;letter-spacing:-.015em}
.deb-score-t span{font-size:13px;color:var(--label-2)}
.deb-list{padding:8px 18px 4px}
.deb-list-h{display:flex;align-items:center;gap:7px;font-size:13px;font-weight:600;letter-spacing:.02em;text-transform:uppercase;margin-bottom:4px}
.deb-list-h .icn{font-size:15px}
.deb-item{font-size:14.5px;line-height:1.45;letter-spacing:-.008em;padding:6px 0 6px 22px;position:relative;border-top:var(--hair) solid var(--sep)}
.deb-item:first-of-type{border-top:none}
.deb-item::before{content:"";position:absolute;left:8px;top:14px;width:5px;height:5px;border-radius:99px;background:var(--label-3)}
/* ---------- a decided proposal, folded into the thread ---------- */
.recap{
display:block;width:100%;text-align:left;margin-top:6px;padding:14px 16px 12px;border-radius:var(--r-xl);
background:var(--surface);border:1px solid var(--sep-op);color:var(--label);transition:transform var(--fast),background var(--fast)
}
.recap:active{transform:scale(.99);background:var(--surface-2)}
.recap-top{display:flex;justify-content:space-between;align-items:center;gap:8px}
.recap-top .pcard-eyebrow{margin:0}
.recap-state{font-size:11px;font-weight:600;padding:3px 9px;border-radius:99px;background:var(--surface-2);color:var(--label-2);white-space:nowrap;flex:none}
.recap-state.yes{background:color-mix(in srgb,var(--green) 16%,transparent);color:var(--green)}
.recap-state.no{background:color-mix(in srgb,var(--red) 14%,transparent);color:var(--red)}
.recap-state.mix{background:var(--acc-soft);color:var(--acc)}
.recap-t{font-size:17px;font-weight:600;letter-spacing:-.018em;margin-top:6px;line-height:1.2}
.recap-s{font-size:13.5px;color:var(--label-2);line-height:1.42;margin-top:4px;display:-webkit-box;-webkit-line-clamp:2;-webkit-box-orient:vertical;overflow:hidden}
.recap-chips{display:flex;flex-wrap:wrap;gap:5px;margin-top:9px}
.recap-chip{display:inline-flex;align-items:center;gap:4px;font-size:12px;padding:4px 9px;border-radius:99px;background:var(--surface-2);color:var(--label-2);text-transform:capitalize;max-width:100%}
.recap-chip .icn{font-size:11px;flex:none}
.recap-chip.yes .icn{color:var(--green)}
.recap-chip.no{text-decoration:line-through;opacity:.75}
.recap-chip.no .icn{color:var(--red)}
.recap-more{display:flex;align-items:center;gap:3px;font-size:13px;color:var(--acc);font-weight:500;margin-top:10px}
.recap-more .icn{font-size:12px}
.pcard-chg.declined .pcard-chg-t{color:var(--label-2)}
.pcard-chg .recap-state{align-self:center}
.pdetail .pcard-chg,.pdetail .pcard-notes,.pdetail .ins{padding-left:0;padding-right:0}
.pdetail .pcard-rt{padding-left:0;padding-right:0}
.pdetail .pcard-week{padding-left:0;padding-right:0}
/* ---------- you against the room ---------- */
.cmp{padding:8px 0;border-top:var(--hair) solid var(--sep)}
.cmp:first-of-type{border-top:none}
.cmp-h{display:flex;justify-content:space-between;font-size:13.5px;font-weight:500;text-transform:capitalize;margin-bottom:5px}
.cmp-h .dim{font-weight:400;font-size:12px;text-transform:none}
.cmp-bar{position:relative;height:22px;border-radius:7px;background:var(--surface-3);overflow:hidden;margin-top:4px}
.cmp-bar i{display:block;height:100%;border-radius:7px;background:var(--label-3);opacity:.55}
.cmp-bar.you i{background:var(--acc);opacity:1}
.cmp-bar span{position:absolute;left:8px;top:0;line-height:22px;font-size:11.5px;font-weight:600;color:var(--label);font-variant-numeric:tabular-nums;text-shadow:0 0 6px var(--bg)}
+6
View File
@@ -47,6 +47,11 @@ export const coachStatus = async () => DEMO ? (await demo()).demoStatus() : LOCA
export const requestReview = async note => DEMO ? (await demo()).demoReview(S()) : LOCAL() ? (await local()).localReview(S(), note) : api('/api/coach/review', { method: 'POST', body: JSON.stringify({ note: note || '' }) })
export const requestPlan = async intake => DEMO ? (await demo()).demoPlan(S(), intake) : LOCAL() ? (await local()).localPlan(S(), intake) : api('/api/coach/plan', { method: 'POST', body: JSON.stringify({ intake }) })
export const refinePlan = async text => DEMO ? (await demo()).demoRefine(S()) : LOCAL() ? (await local()).localRefine(S(), text) : api('/api/coach/plan', { method: 'POST', body: JSON.stringify({ refine: text }) })
export const requestDebrief = async workoutId => DEMO ? (await demo()).demoDebrief(S(), workoutId) : LOCAL() ? (await local()).localDebrief(S(), workoutId) : api('/api/coach/debrief', { method: 'POST', body: JSON.stringify({ workoutId: workoutId || null }) })
// The room: anonymous medians across the profiles on this instance that opted in. Only a
// server has a room; a phone with its own key and the demo both answer locally.
export const cohortStats = async () => DEMO ? (await demo()).demoCohort(S()) : LOCAL() ? { ok: false, enabled: false } : api('/api/coach/cohort')
export const setCohortShare = async share => (DEMO || LOCAL()) ? { ok: true, sharing: !!share } : api('/api/coach/cohort/share', { method: 'POST', body: JSON.stringify({ share: !!share }) })
export const resolvePending = async body => DEMO ? (await demo()).demoResolve() : LOCAL() ? (await local()).localResolve(body) : api('/api/coach/pending/resolve', { method: 'POST', body: JSON.stringify(body) })
export const forgetCoach = async () => DEMO ? (await demo()).demoResolve() : LOCAL() ? (await local()).localForget() : api('/api/coach/forget', { method: 'POST', body: '{}' })
export const disclosure = async () => DEMO ? (await demo()).demoDisclosure() : LOCAL() ? (await local()).localDisclosure() : api('/api/coach/disclosure')
@@ -116,5 +121,6 @@ export const JOB_ERRORS = {
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.',
noworkout: 'There is no workout to look at yet — log one first.',
internal: 'Something went wrong on the server.'
}
+51 -1
View File
@@ -13,7 +13,10 @@
// replaces at build time.
import { EXIDX, EXDB } from './exercises.js'
import { modeOf } from './history.js'
import { modeOf, workoutVolume } from './history.js'
import { isWarmupRow } from './workout-model.js'
import { best1RM } from './onerm.js'
import { fmtNum } from './format.js'
import { planHash } from './coach.js'
import { t } from './i18n.js'
@@ -108,6 +111,49 @@ function buildPlan(S, intake) {
}
}
/** One session, read back with its own numbers — no plan changes, just what a coach would say after. */
function buildDebrief(S, workoutId) {
const all = (S.workouts || []).filter(w => w && w.d)
const w = all.find(x => x.id === workoutId) || all[all.length - 1]
if (!w) return null
const done = (w.entries || []).reduce((n, en) => n + (en.sets || []).filter(s => s.done && !isWarmupRow(s)).length, 0)
const planned = (w.entries || []).reduce((n, en) => n + (en.sets || []).filter(s => !isWarmupRow(s)).length, 0)
const vol = Math.round(Number.isFinite(w.vol) ? w.vol : workoutVolume(w))
const prs = (w.prs || []).length
const minutes = w.end && w.start ? Math.round((w.end - w.start) / 60000) : null
const complete = planned > 0 && done >= planned
const score = complete ? (prs ? 9 : 8) : 7
const highlights = [
complete ? t('Every planned set done — {0} of {1}.', done, planned) : t('{0} of {1} planned sets done.', done, planned),
t('{0} {1} moved in total.', fmtNum(vol), S.unit)
]
if (prs) highlights.push(t('{0} new personal records.', prs))
const watch = minutes && minutes > 80 ? [t('{0} minutes is long — rest periods may be creeping up.', minutes)] : [t('Top sets logged without an effort rating; add RIR so the next review can read how hard they were.')]
const nextTime = [complete ? t('Add the next load step on the main lift.') : t('Repeat the same loads and get every set.'), t('Keep the session under an hour and a quarter.')]
return {
id: 'demo-debrief', kind: 'debrief', createdAt: Date.now(), expiresAt: Date.now() + 864e5,
planHash: planHash(S), iteration: 1,
workout: { id: w.id, d: w.d, name: w.name || null, minutes, vol, sets: done, prs },
summary: complete
? t('A clean session: everything on the sheet got done and the loads held. This is exactly what progress looks like from the inside — unremarkable, repeated.')
: t('Most of the work got done. One or two sets fell short, which is fine once — it becomes a signal if the same sets miss next time.'),
score, highlights, watch, nextTime
}
}
/** What "the room" would say on a busy instance — five people, plausible medians, your real bests. */
export function demoCohort(S) {
const since = Date.now() - 56 * 864e5
const you = Math.round((S.workouts || []).filter(w => (w.start || new Date(w.d).getTime()) > since).length / 8 * 10) / 10
const ids = [...new Set((S.routines || []).flatMap(r => (r.ex || []).map(e => e.id)))].slice(0, 5)
const exercises = ids.map(id => {
const b = best1RM(S, id)
const mine = b ? Math.round(b.est * 10) / 10 : null
return { id, name: EXIDX[id]?.n || id, people: 4, median: mine ? Math.round(mine * 0.92) : 60, you: mine }
})
return { ok: true, enabled: true, sharing: true, people: 5, minPeople: 3, unit: S.unit, sessionsPerWeek: { median: 3, you }, exercises, rankPct: 62 }
}
/* ---------------- the API surface the demo stands in for ---------------- */
export const demoStatus = () => ({ job, pending, cap: { used: 0, limit: 0 } })
@@ -125,6 +171,10 @@ 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 demoDebrief = (S, workoutId) => {
if (!(S.workouts || []).some(w => w && w.d)) throw Object.assign(new Error(t('There is no workout to look at yet — log one first.')), { status: 409, code: 'noworkout' })
return start('debrief', () => buildDebrief(S, workoutId))
}
export const demoResolve = () => { pending = null; return { ok: true } }
export const demoDisclosure = () => ({
provider: 'demo', providerLabel: t('the configured AI provider'),
+106
View File
@@ -0,0 +1,106 @@
// The numbers behind a Coach card, computed on the device from the same training log the
// Coach read — so the chart under a suggestion shows exactly the window the suggestion cites,
// and nothing the model wrote is ever taken as a statistic.
//
// Pure functions over S. Nothing here is persisted: a card recomputes its insights from the
// window it names, which is why an old proposal in the thread still draws its chart months
// later, against the data as it was then.
import { EXIDX } from './exercises.js'
import { workoutVolume } from './history.js'
import { isWarmupRow } from './workout-model.js'
import { bestSetOf } from './onerm.js'
const median = arr => {
const a = arr.filter(n => Number.isFinite(n)).sort((x, y) => x - y)
return a.length ? a[Math.floor(a.length / 2)] : null
}
const bpOf = (S, id) => EXIDX[id]?.bp || (S.customEx || []).find(c => c.id === id)?.bp || null
const nameOf = (S, id) => EXIDX[id]?.n || (S.customEx || []).find(c => c.id === id)?.n || id
const tsOf = w => w.start || new Date(w.d + 'T12:00:00').getTime()
/** Workouts inside an inclusive ISO-date window; either bound may be missing. */
export function windowWorkouts(S, { from, to } = {}) {
return (S.workouts || []).filter(w => w && w.d && (!from || w.d >= from) && (!to || w.d <= to))
}
/**
* What a review looked at, in numbers: how much, how long, which body parts, where the body
* weight went and which lifts moved. `strength` holds up to `topN` exercises with at least two
* estimable sessions in the window, most-trained first, with the first→last e1RM change.
*/
export function insightsFor(S, win = {}, { topN = 3 } = {}) {
const ws = windowWorkouts(S, win)
const minutes = ws.map(w => (w.end && w.start ? Math.round((w.end - w.start) / 60000) : null)).filter(n => n > 0)
const volume = ws.reduce((n, w) => n + (Number.isFinite(w.vol) ? w.vol : workoutVolume(w)), 0)
const byBp = {}
let setsTotal = 0
ws.forEach(w => (w.entries || []).forEach(en => {
const n = (en.sets || []).filter(s => s.done && !isWarmupRow(s)).length
if (!n) return
setsTotal += n
const bp = bpOf(S, en.id) || 'other'
byBp[bp] = (byBp[bp] || 0) + n
}))
const bodyParts = Object.entries(byBp).map(([bp, sets]) => ({ bp, sets, share: setsTotal ? sets / setsTotal : 0 }))
.sort((a, b) => b.sets - a.sets)
const from = win.from || ws[0]?.d || null
const to = win.to || ws[ws.length - 1]?.d || null
const bw = (S.bodyweight || []).filter(b => b && b.d && (!from || b.d >= from) && (!to || b.d <= to))
.map(b => ({ t: b.t || new Date(b.d + 'T12:00:00').getTime(), y: b.w, d: b.d }))
const bodyweight = {
points: bw,
delta: bw.length > 1 ? Math.round((bw[bw.length - 1].y - bw[0].y) * 10) / 10 : null,
last: bw.length ? bw[bw.length - 1].y : null,
goal: Number.isFinite(S.targetW) ? S.targetW : null
}
const series = new Map()
ws.forEach(w => (w.entries || []).forEach(en => {
const best = bestSetOf(en)
if (!best) return
if (!series.has(en.id)) series.set(en.id, [])
series.get(en.id).push({ t: tsOf(w), d: w.d, y: Math.round(best.est * 10) / 10 })
}))
const strength = [...series.entries()]
.filter(([, pts]) => pts.length >= 2)
.sort((a, b) => b[1].length - a[1].length)
.slice(0, topN)
.map(([id, pts]) => {
const first = pts[0].y, last = pts[pts.length - 1].y
return { id, name: nameOf(S, id), sessions: pts.length, first, last, delta: Math.round((last - first) * 10) / 10, pct: first ? Math.round((last - first) / first * 100) : 0, points: pts }
})
return {
from, to, sessions: ws.length, minutes: median(minutes), volume: Math.round(volume), sets: setsTotal,
bodyParts, bodyweight, strength
}
}
/**
* One workout against the last time the same routine was trained: the numbers a debrief
* card puts above the Coach's words.
*/
export function sessionInsights(S, workout) {
if (!workout) return null
const all = (S.workouts || []).filter(w => w && w.d)
const idx = all.findIndex(w => (workout.id && w.id === workout.id) || (w.d === workout.d && w.start === workout.start))
const before = (idx >= 0 ? all.slice(0, idx) : all).filter(w => w.name && w.name === workout.name)
const prev = before[before.length - 1] || null
const stat = w => ({
volume: Math.round(Number.isFinite(w.vol) ? w.vol : workoutVolume(w)),
sets: (w.entries || []).reduce((n, en) => n + (en.sets || []).filter(s => s.done && !isWarmupRow(s)).length, 0),
minutes: w.end && w.start ? Math.round((w.end - w.start) / 60000) : null,
prs: (w.prs || []).length
})
const now = stat(workout)
const then = prev ? stat(prev) : null
const lifts = (workout.entries || []).map(en => {
const best = bestSetOf(en)
const pe = prev?.entries?.find(x => x.id === en.id)
const pb = pe ? bestSetOf(pe) : null
return best ? { id: en.id, name: nameOf(S, en.id), est: Math.round(best.est * 10) / 10, w: best.w, r: best.r, prev: pb ? Math.round(pb.est * 10) / 10 : null } : null
}).filter(Boolean)
return { now, then, prevDate: prev?.d || null, lifts }
}
+97
View File
@@ -0,0 +1,97 @@
import { describe, it, expect } from 'vitest'
import { insightsFor, sessionInsights, windowWorkouts } from './coach-insights.js'
import { EXIDX } from './exercises.js'
// Pick two real catalogue ids from different body parts so the body-part grouping is real.
const ids = Object.keys(EXIDX)
const chest = ids.find(id => EXIDX[id].bp === 'chest')
const legs = ids.find(id => EXIDX[id].bp === 'upper legs')
const day = (d, h = 10) => new Date(d + 'T' + String(h).padStart(2, '0') + ':00:00').getTime()
const w = (id, d, entries, over = {}) => ({ id, d, name: 'Push', start: day(d), end: day(d) + 55 * 60000, entries, ...over })
const set = (w_, r, extra = {}) => ({ done: true, w: w_, r, ...extra })
const S = () => ({
unit: 'kg', targetW: 80, customEx: [{ id: 'cx1', n: 'My row', bp: 'back' }],
bodyweight: [{ d: '2026-07-01', w: 90 }, { d: '2026-08-02', w: 84 }, { d: '2026-08-10', w: 83 }, { d: '2026-08-20', w: 82.5 }],
workouts: [
w('w0', '2026-07-20', [{ id: chest, sets: [set(60, 10)] }]), // outside the window
w('w1', '2026-08-03', [{ id: chest, sets: [set(40, 8, { phase: 'warmup' }), set(60, 10), set(60, 10)] }, { id: legs, sets: [set(100, 5)] }]),
w('w2', '2026-08-06', [{ id: chest, sets: [set(65, 10), set(65, 9)] }, { id: 'cx1', sets: [set(50, 10)] }], { name: 'Pull' }),
w('w3', '2026-08-12', [{ id: chest, sets: [set(70, 10), set(70, 10), { done: false, w: 70, r: 0 }] }, { id: legs, sets: [set(110, 5)] }], { prs: [chest] })
]
})
describe('insightsFor', () => {
const win = { from: '2026-08-01', to: '2026-08-15' }
it('counts only the window, and only done, non-warm-up work sets', () => {
const i = insightsFor(S(), win)
expect(i.sessions).toBe(3)
expect(windowWorkouts(S(), win).map(x => x.id)).toEqual(['w1', 'w2', 'w3'])
expect(i.sets).toBe(2 + 1 + 2 + 1 + 2 + 1)
expect(i.minutes).toBe(55)
// volume excludes the warm-up and the unchecked set
expect(i.volume).toBe(60 * 10 * 2 + 100 * 5 + 65 * 10 + 65 * 9 + 50 * 10 + 70 * 10 * 2 + 110 * 5)
})
it('groups sets by body part, custom exercises included, biggest first', () => {
const i = insightsFor(S(), win)
expect(i.bodyParts[0]).toMatchObject({ bp: 'chest', sets: 6 })
expect(i.bodyParts.map(b => b.bp)).toContain('back')
expect(i.bodyParts.reduce((n, b) => n + b.share, 0)).toBeCloseTo(1, 5)
})
it('reads the body weight inside the window with its delta and goal', () => {
const i = insightsFor(S(), win)
expect(i.bodyweight.points.map(p => p.y)).toEqual([84, 83])
expect(i.bodyweight.delta).toBe(-1)
expect(i.bodyweight.goal).toBe(80)
expect(i.bodyweight.last).toBe(83)
})
it('tracks estimated 1RM first → last for exercises with two or more sessions, most-trained first', () => {
const i = insightsFor(S(), win, { topN: 1 })
expect(i.strength).toHaveLength(1)
const c = i.strength[0]
expect(c.id).toBe(chest)
expect(c.sessions).toBe(3)
expect(c.last).toBeGreaterThan(c.first)
expect(c.pct).toBeGreaterThan(0)
expect(c.delta).toBeCloseTo(c.last - c.first, 1)
expect(insightsFor(S(), win).strength.length).toBe(2) // chest + legs; the custom row has one session
})
it('falls back to the workouts’ own span when no window is given', () => {
const i = insightsFor(S())
expect(i.sessions).toBe(4)
expect(i.from).toBe('2026-07-20')
expect(i.to).toBe('2026-08-12')
})
it('is empty-safe', () => {
const i = insightsFor({ workouts: [], bodyweight: [] })
expect(i.sessions).toBe(0)
expect(i.minutes).toBeNull()
expect(i.bodyweight.delta).toBeNull()
expect(i.strength).toEqual([])
})
})
describe('sessionInsights', () => {
it('compares a workout with the previous one of the same name', () => {
const s = S()
const r = sessionInsights(s, s.workouts[3]) // w3 'Push' — previous Push is w1
expect(r.prevDate).toBe('2026-08-03')
expect(r.now.sets).toBe(3)
expect(r.now.prs).toBe(1)
expect(r.then.sets).toBe(3)
expect(r.now.volume - r.then.volume).toBe((70 * 10 * 2 + 110 * 5) - (60 * 10 * 2 + 100 * 5))
const chestLift = r.lifts.find(l => l.id === chest)
expect(chestLift.w).toBe(70)
expect(chestLift.prev).not.toBeNull()
expect(chestLift.est).toBeGreaterThan(chestLift.prev)
})
it('has no comparison when the name was never trained before', () => {
const s = S()
const r = sessionInsights(s, s.workouts[2]) // the only 'Pull'
expect(r.then).toBeNull()
expect(r.prevDate).toBeNull()
expect(r.lifts.every(l => l.prev === null)).toBe(true)
})
it('returns null for nothing', () => { expect(sessionInsights(S(), null)).toBeNull() })
})
+12 -1
View File
@@ -95,6 +95,7 @@ export const localRefine = async (S, text) => {
const pendingCreate = d.pending && d.pending.kind === 'create' ? d.pending : null
return start(S, 'create', { refine: String(text || '').slice(0, 1000), previous: pendingCreate?.bundle || null, iteration: (pendingCreate?.iteration || 1) + 1 })
}
export const localDebrief = (S, workoutId) => start(S, 'debrief', { workoutId: workoutId || null })
export async function localResolve() { await saveCoachDevice({ pending: null }); return { ok: true } }
export async function localForget() { job = null; lastError = null; await saveCoachDevice({ pending: null, daily: null }); return { ok: true } }
@@ -141,7 +142,7 @@ async function start(S, kind, opts) {
async function run(S, kind, opts, d, adapter) {
const key = await getApiKey()
const payload = payloadLib.build(S, {
handle: await handle(), kind, intake: opts.intake, note: opts.note, refine: opts.refine, previous: opts.previous
handle: await handle(), kind, intake: opts.intake, note: opts.note, refine: opts.refine, previous: opts.previous, workoutId: opts.workoutId
})
const attempt = await runPipeline({
adapter, cfg: cfgOf(d), kind, payload,
@@ -162,6 +163,7 @@ async function run(S, kind, opts, d, adapter) {
const pending = {
id: job.id, kind, createdAt: Date.now(), expiresAt: Date.now() + PENDING_DAYS * 86400000,
planHash: planHash(S), iteration: opts.iteration || 1,
...(kind === 'debrief' ? { workout: workoutMetaOf(S, opts.workoutId) } : {}),
...attempt.result
}
await saveCoachDevice({ pending })
@@ -169,5 +171,14 @@ async function run(S, kind, opts, d, adapter) {
if (notify) notify({ kind: 'ready', pending })
}
// The session a debrief is about, in the shape the card reads. The core builds it for the
// server; the fallback covers a core that predates it.
function workoutMetaOf(S, workoutId) {
if (typeof payloadLib.workoutMeta === 'function') return payloadLib.workoutMeta(S, workoutId)
const all = (S.workouts || []).filter(w => w && w.d)
const w = all.find(x => x.id === workoutId) || all[all.length - 1]
return w ? { id: w.id, d: w.d, name: w.name || null } : null
}
// Test seam.
export function _resetLocal() { job = null; lastError = null; last = null }
+51 -9
View File
@@ -262,9 +262,35 @@ export const canRevert = S => !!(S?.coach?.snapshots || []).length
export function appendLog(s, entry) {
const c = coachOf(s)
c.log = [...(c.log || []), { id: entry.id || uid(), ...entry }].slice(-LOG_MAX)
const e = { id: entry.id || uid(), ...entry }
c.log = [...(c.log || []), e].slice(-LOG_MAX)
trim(s)
return e.id
}
export const logEntry = (S, id) => (S?.coach?.log || []).find(e => e.id === id) || null
/**
* What a created plan looked like, small enough to keep: names, days and prescriptions, no
* rationale text. The full bundle was merged into the plan already; this is what the chat
* shows back when someone opens an old proposal months later.
*/
export function lightBundle(b) {
if (!b) return null
return {
name: b.name || '', summary: b.summary || '', week: { ...(b.week || {}) },
routines: (b.routines || []).map(r => ({
id: r.id, name: r.name, emoji: r.emoji || '', why: r.why || '',
ex: (r.ex || []).map(e => ({
id: e.id, sets: e.sets, mode: e.mode || 'reps',
...(e.reps != null ? { reps: e.reps } : {}), ...(e.sec != null ? { sec: e.sec } : {}),
...(e.min != null ? { min: e.min } : {}), ...(e.weight ? { weight: e.weight } : {}),
...(e.why ? { why: String(e.why).slice(0, 200) } : {})
}))
}))
}
}
const decisionOf = (c, status) => ({ id: c.id, type: c.type, target: c.target || null, before: c.before ?? null, after: c.after ?? null, why: c.why, routineName: c.routineName || null, status })
/**
* Last line of defence for the 5 MB sync body: if the Coach namespace ever outgrows its
@@ -346,9 +372,10 @@ export function applyCreatedPlan(s, proposal, { schedule } = {}) {
// Only when the week actually moved — with the switch off the old schedule still stands, and
// so do the reschedules made against it.
if (schedule) sweepDayPlan(s, todayISO())
appendLog(s, {
res.logId = appendLog(s, {
kind: 'create', at: Date.now(), proposalId: proposal.id,
summary: proposal.summary || '', routines: res.routines, iteration: proposal.iteration || 1
summary: proposal.summary || '', routines: res.routines, iteration: proposal.iteration || 1,
bundle: lightBundle(bundle), scheduled: !!schedule
})
return res
}
@@ -498,29 +525,44 @@ export function applyChangeSet(s, proposal, acceptedIds) {
const applied = []
for (const c of changes) {
CHANGE_APPLY[c.type](s, c)
applied.push({ id: c.id, type: c.type, target: c.target, before: c.before, after: c.after, why: c.why, status: 'accepted' })
applied.push(decisionOf(c, 'accepted'))
}
// Turned-down changes keep their before/after too: the chat shows the whole proposal back
// later, and "you declined something about sets" is not a memory anyone can use.
const rejected = (proposal.changes || [])
.filter(c => !accepted.has(c.id))
.map(c => ({ id: c.id, type: c.type, why: c.why, status: 'rejected' }))
.map(c => decisionOf(c, c.status === 'stale' ? 'stale' : 'rejected'))
appendLog(s, {
const logId = appendLog(s, {
kind: 'review', at: Date.now(), proposalId: proposal.id,
summary: proposal.summary || '', evidence: proposal.evidence || null,
notes: proposal.notes || [], decisions: [...applied, ...rejected]
})
coachOf(s).lastReview = { at: Date.now() }
return { applied: applied.length, rejected: rejected.length }
return { applied: applied.length, rejected: rejected.length, logId }
}
/** Turned down whole, or expired: recorded so a later review knows not to re-propose it. */
export function recordDismissal(s, proposal) {
appendLog(s, {
const logId = appendLog(s, {
kind: proposal.kind === 'create' ? 'create' : 'review', at: Date.now(), proposalId: proposal.id,
summary: proposal.summary || '', dismissed: true,
decisions: (proposal.changes || []).map(c => ({ id: c.id, type: c.type, why: c.why, status: 'rejected' }))
evidence: proposal.evidence || null, notes: proposal.notes || [],
...(proposal.bundle ? { bundle: lightBundle(proposal.bundle), iteration: proposal.iteration || 1 } : {}),
decisions: (proposal.changes || []).map(c => decisionOf(c, 'rejected'))
})
if (proposal.kind !== 'create') coachOf(s).lastReview = { at: Date.now() }
return logId
}
/** A debrief has no decision to make: it is read, kept, and shown again on request. */
export function recordDebrief(s, proposal) {
return appendLog(s, {
kind: 'debrief', at: Date.now(), proposalId: proposal.id,
workout: proposal.workout || null,
summary: proposal.summary || '', score: proposal.score ?? null,
highlights: proposal.highlights || [], watch: proposal.watch || [], nextTime: proposal.nextTime || []
})
}
/* ============================ display helpers ============================ */
+57 -1
View File
@@ -3,6 +3,7 @@ import {
canonicalPlan, planHash, hashPlan, markStale, applicable, currentValue,
pushSnapshot, revertLast, canRevert, appendLog, applyChangeSet, applyCreatedPlan,
recordDismissal, validateProposal, coachAvailable, hasConsent,
recordDebrief, logEntry, lightBundle,
CHANGE_TYPES, SNAPSHOT_MAX, LOG_MAX, CONSENT_VERSION
} from './coach.js'
import { registerCustom } from './exercises.js'
@@ -298,7 +299,7 @@ describe('accepting a subset', () => {
change({ id: 'c2', type: 'reps', before: 10, after: 12 })
])
const res = applyChangeSet(s, p, ['c1'])
expect(res).toEqual({ applied: 1, rejected: 1 })
expect(res).toMatchObject({ applied: 1, rejected: 1 })
expect(s.routines[0].ex[0].sets).toBe(4)
expect(s.routines[0].ex[0].reps).toBe(10)
const decisions = s.coach.log.at(-1).decisions
@@ -552,3 +553,58 @@ describe('removing a routine takes its per-date reschedules with it', () => {
expect(s.dayPlan['2099-01-01']).toBe('r2')
})
})
describe('what the log keeps, so a decision never makes a proposal vanish', () => {
const plan = {
opengym_plan: 1, name: 'Coach plan', summary: 'p', week: { 1: 'x1' },
routines: [{ id: 'x1', name: 'A', emoji: '💪', why: 'w', ex: [{ id: '0001', sets: 3, reps: 10, mode: 'reps', why: 'y'.repeat(300), secret: 1 }] }],
customEx: []
}
it('applyChangeSet returns the log id and keeps the declined change whole', () => {
const s = JSON.parse(JSON.stringify(state()))
const p = proposal([change(), change({ id: 'c2', type: 'reps', before: 10, after: 8, why: 'too many' })])
const res = applyChangeSet(s, p, ['c1'])
expect(res.logId).toBe(s.coach.log.at(-1).id)
const rej = s.coach.log.at(-1).decisions.find(d => d.id === 'c2')
expect(rej).toMatchObject({ status: 'rejected', type: 'reps', before: 10, after: 8, target: { routineId: 'r1', exId: '0001' } })
expect(logEntry(s, res.logId).kind).toBe('review')
})
it('applyCreatedPlan keeps a light copy of the bundle and whether the week was taken', () => {
const s = JSON.parse(JSON.stringify(state()))
const res = applyCreatedPlan(s, { id: 'p1', kind: 'create', bundle: plan, iteration: 2 }, { schedule: false })
const e = logEntry(s, res.logId)
expect(e.kind).toBe('create')
expect(e.scheduled).toBe(false)
expect(e.iteration).toBe(2)
expect(e.bundle.routines[0].ex[0]).toEqual({ id: '0001', sets: 3, mode: 'reps', reps: 10, why: 'y'.repeat(200) })
expect(e.bundle.routines[0].why).toBe('w')
})
it('recordDismissal returns the id and keeps a discarded plan too', () => {
const s = JSON.parse(JSON.stringify(state()))
const id = recordDismissal(s, { id: 'p1', kind: 'create', summary: 'nope', bundle: plan })
const e = logEntry(s, id)
expect(e.dismissed).toBe(true)
expect(e.bundle.name).toBe('Coach plan')
expect(s.coach.lastReview).toBeUndefined()
const rid = recordDismissal(s, proposal([change()], { evidence: { sessions: 4 }, notes: ['n'] }))
expect(logEntry(s, rid)).toMatchObject({ evidence: { sessions: 4 }, notes: ['n'] })
expect(logEntry(s, rid).decisions[0]).toMatchObject({ status: 'rejected', before: 3, after: 4 })
})
it('recordDebrief files the whole reading', () => {
const s = JSON.parse(JSON.stringify(state()))
const id = recordDebrief(s, { id: 'd1', kind: 'debrief', workout: { id: 'w1', name: 'Push' }, summary: 'ok', score: 8, highlights: ['a'], watch: [], nextTime: ['b'] })
expect(logEntry(s, id)).toMatchObject({ kind: 'debrief', score: 8, highlights: ['a'], nextTime: ['b'], workout: { id: 'w1' } })
})
it('lightBundle drops what the card does not show', () => {
const b = lightBundle({ ...plan, customEx: [{ id: 'z' }], basedOn: 'x' })
expect(b.customEx).toBeUndefined()
expect(b.basedOn).toBeUndefined()
expect(Object.keys(b.routines[0].ex[0])).not.toContain('secret')
expect(lightBundle(null)).toBeNull()
})
})
+103 -1
View File
@@ -921,5 +921,107 @@ export default {
'here when you need it': 'da, wenn du ihn brauchst',
'thinking…': 'denkt nach…',
'{0} min per session': '{0} Min. pro Einheit',
'1 day a week': '1 Tag pro Woche'
'1 day a week': '1 Tag pro Woche',
// --- coach: debrief, history, comparison ---
'How did my {0} session go?': 'Wie lief meine Einheit „{0}“?',
'How did my last workout go?': 'Wie lief mein letztes Training?',
'Focus only on my routine “{0}”. Improve it: exercise choice, order, sets and reps, rep ranges, progression. Leave the other routines alone.': 'Konzentriere dich nur auf meine Routine „{0}“. Verbessere sie: Übungsauswahl, Reihenfolge, Sätze und Wiederholungen, Wiederholungsbereiche, Progression. Lass die anderen Routinen unverändert.',
'Improve my routine “{0}”.': 'Verbessere meine Routine „{0}“.',
'Improve which routine?': 'Welche Routine verbessern?',
'You have no routines yet — ask the Coach for a plan first.': 'Du hast noch keine Routinen – bitte den Coach zuerst um einen Plan.',
'Review my last workout': 'Mein letztes Training bewerten',
'What went well, what to watch, what to do next time': 'Was gut lief, worauf du achten solltest, was beim nächsten Mal',
'Improve a routine': 'Eine Routine verbessern',
'Pick one; the Coach works on just that': 'Wähle eine aus; der Coach arbeitet nur daran',
'Compare with others here': 'Mit anderen hier vergleichen',
'Anonymous medians from this instance': 'Anonyme Mediane dieser Instanz',
'Everything the Coach proposed': 'Alles, was der Coach vorgeschlagen hat',
'Plans, suggestions and debriefs, kept': 'Pläne, Vorschläge und Auswertungen, aufbewahrt',
'Review my training': 'Mein Training prüfen',
'Last workout': 'Letztes Training',
'Compare': 'Vergleichen',
'Looking at that session…': 'Schaut sich die Einheit an…',
'Coach plan': 'Coach-Plan',
'Sessions': 'Einheiten',
'Min / session': 'Min. / Einheit',
'Volume ({0})': 'Volumen ({0})',
'Work sets': 'Arbeitssätze',
'goal': 'Ziel',
'first → last session': 'erste → letzte Einheit',
'Work sets by body part': 'Arbeitssätze nach Körperpartie',
'Workout': 'Training',
'vs. last {0} on {1}:': 'vs. letztes {0} am {1}:',
'session': 'Einheit',
'volume': 'Volumen',
'time': 'Zeit',
'Best set, estimated 1RM': 'Bester Satz, geschätztes 1RM',
'What went well': 'Was gut lief',
'Worth watching': 'Im Auge behalten',
'Next time': 'Nächstes Mal',
'Excellent session': 'Hervorragende Einheit',
'Good session': 'Gute Einheit',
'Solid session': 'Solide Einheit',
'Tough session': 'Harte Einheit',
'Kept in your Coach history': 'Im Coach-Verlauf gespeichert',
'Workout debrief': 'Trainings-Auswertung',
'Your last workout': 'Dein letztes Training',
'Got it': 'Verstanden',
'Want changes to the plan from this? Ask for a review below.': 'Sollen daraus Änderungen am Plan werden? Bitte unten um eine Überprüfung.',
'Declined': 'Abgelehnt',
'Imported': 'Importiert',
'{0} accepted · {1} declined': '{0} angenommen · {1} abgelehnt',
'{0} accepted': '{0} angenommen',
'Show everything': 'Alles anzeigen',
'You declined this.': 'Das hast du abgelehnt.',
'Accepted': 'Angenommen',
'Expired': 'Abgelaufen',
'Your week was set to this schedule.': 'Deine Woche wurde auf diesen Zeitplan gesetzt.',
'Imported without changing your week.': 'Importiert, ohne deine Woche zu ändern.',
'This plan was imported before the app kept proposals; only its summary is left.': 'Dieser Plan wurde importiert, bevor die App Vorschläge aufbewahrt hat; nur die Zusammenfassung ist übrig.',
'Nothing yet. Every plan, suggestion and debrief will be kept here — whether you said yes or no.': 'Noch nichts. Jeder Plan, Vorschlag und jede Auswertung wird hier aufbewahrt – egal ob du Ja oder Nein gesagt hast.',
'Debrief: {0}': 'Auswertung: {0}',
'Could not load': 'Konnte nicht geladen werden',
'Could not save': 'Konnte nicht gespeichert werden',
'Only medians across everyone who shares, never a name, a body weight or a single session. Turning this off removes you from the numbers immediately.': 'Nur Mediane über alle, die teilen – nie ein Name, ein Körpergewicht oder eine einzelne Einheit. Wenn du das ausschaltest, bist du sofort aus den Zahlen raus.',
'Include me': 'Mich einbeziehen',
'Your lifts count towards the medians': 'Deine Lifts zählen zu den Medianen',
'Off — you see nothing and share nothing': 'Aus – du siehst nichts und teilst nichts',
'Loading…': 'Lädt…',
'Not enough people share yet — {0} of {1} needed. Ask your gym mates.': 'Noch teilen zu wenige – {0} von {1} nötig. Frag deine Trainingspartner.',
'Not available right now.': 'Gerade nicht verfügbar.',
'People': 'Personen',
'Your sessions / wk': 'Deine Einheiten / Wo.',
'Median / wk': 'Median / Wo.',
'Your strength rank': 'Dein Kraft-Rang',
'Estimated 1RM, you vs. median': 'Geschätztes 1RM, du vs. Median',
'people': 'Personen',
'You': 'Du',
'Median': 'Median',
'No exercise is trained by three or more people yet.': 'Noch keine Übung wird von drei oder mehr Personen trainiert.',
'Applied {0} change to your plan.': '{0} Änderung auf deinen Plan angewendet.',
'Applied {0} changes to your plan.': '{0} Änderungen auf deinen Plan angewendet.',
'{0} change applied': '{0} Änderung angewendet',
'{0} changes applied': '{0} Änderungen angewendet',
'{0} suggestion': '{0} Vorschlag',
'{0} suggestions': '{0} Vorschläge',
'Apply {0} change': '{0} Änderung anwenden',
'Apply {0} changes': '{0} Änderungen anwenden',
'Neck': 'Nacken',
'Arms': 'Arme',
'Legs': 'Beine',
'Core': 'Rumpf',
'Other': 'Sonstiges',
'There is no workout to look at yet — log one first.': 'Es gibt noch kein Training zum Anschauen – logge zuerst eins.',
'Every planned set done — {0} of {1}.': 'Alle geplanten Sätze geschafft – {0} von {1}.',
'{0} of {1} planned sets done.': '{0} von {1} geplanten Sätzen geschafft.',
'{0} {1} moved in total.': 'Insgesamt {0} {1} bewegt.',
'{0} new personal records.': '{0} neue persönliche Rekorde.',
'{0} minutes is long — rest periods may be creeping up.': '{0} Minuten sind lang – die Pausen werden womöglich länger.',
'Top sets logged without an effort rating; add RIR so the next review can read how hard they were.': 'Top-Sätze ohne Anstrengungs-Bewertung geloggt; ergänze RIR, damit die nächste Überprüfung sehen kann, wie hart sie waren.',
'Add the next load step on the main lift.': 'Beim Hauptlift die nächste Gewichtsstufe drauflegen.',
'Repeat the same loads and get every set.': 'Dieselben Gewichte wiederholen und jeden Satz schaffen.',
'Keep the session under an hour and a quarter.': 'Die Einheit unter eineinviertel Stunden halten.',
'A clean session: everything on the sheet got done and the loads held. This is exactly what progress looks like from the inside — unremarkable, repeated.': 'Eine saubere Einheit: alles auf dem Zettel wurde erledigt und die Gewichte haben gehalten. Genau so sieht Fortschritt von innen aus – unspektakulär, wiederholt.',
'Most of the work got done. One or two sets fell short, which is fine once — it becomes a signal if the same sets miss next time.': 'Der Großteil der Arbeit ist erledigt. Ein oder zwei Sätze blieben kurz – einmal ist das in Ordnung; ein Signal wird es, wenn dieselben Sätze beim nächsten Mal wieder fehlen.'
}
+8
View File
@@ -236,6 +236,14 @@ export default function AdminCoach() {
<span className="v"><input className="num" type="number" min="0" max="5000" defaultValue={d.caps.instanceDaily} disabled={busy}
onBlur={e => +e.target.value !== d.caps.instanceDaily && patch({ caps: { ...d.caps, instanceDaily: +e.target.value } })} /></span></div>
<div className="adm-group-t" style={{ marginTop: 14 }}>Compare with others</div>
<div className="row between" style={{ gap: 12, alignItems: 'flex-start' }}>
<div className="adm-hint" style={{ margin: 0 }}>
<b>Let people compare with each other.</b> Anonymous medians (estimated 1RM, sessions per week) across profiles that opt in; at least three must share before anyone sees a number. Each person switches themselves on in the Coach chat, and sees nothing unless they do.
</div>
<Switch checked={!!d.community} disabled={busy} onChange={v => patch({ community: v })} />
</div>
<div className="adm-group-t" style={{ marginTop: 14 }}>Whose account pays</div>
<div className="adm-hint">{d.authMode === 'profile'
? 'Each profile signs in with their own account.'
+379 -41
View File
@@ -8,24 +8,29 @@
// 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.
// pending. Once decided, the chat line carries a `ref` into `S.coach.log`, where the whole
// proposal — every change, accepted or not, the notes, the evidence — is kept, so saying yes
// or no never makes it disappear. Turning the Coach off is the admin's decision, not a control
// on this screen.
import { useEffect, useMemo, useRef, useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { t } from '../lib/i18n.js'
import { fmtDate, DAYS } from '../lib/format.js'
import { fmtDate, fmtNum, DAYS } from '../lib/format.js'
import { exLine } from '../lib/history.js'
import { DEMO } from '../lib/demo.js'
import { MOBILE } from '../lib/mobile.js'
import {
coachAvailable, hasConsent, emptyCoach, appendChat, recordTiming, estimateMs, profileLines,
markStale, applicable, applyChangeSet, applyCreatedPlan, recordDismissal,
markStale, applicable, applyChangeSet, applyCreatedPlan, recordDismissal, recordDebrief, logEntry,
changeTitle, changeValues, exName, canRevert, revertLast
} from '../lib/coach.js'
import { useCoachStatus, requestReview, refinePlan, resolvePending, JOB_ERRORS } from '../lib/coach-api.js'
import { insightsFor, sessionInsights } from '../lib/coach-insights.js'
import { useCoachStatus, requestReview, requestDebrief, refinePlan, resolvePending, cohortStats, setCohortShare, JOB_ERRORS } from '../lib/coach-api.js'
import { confirmSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import LineChart from '../components/LineChart.jsx'
import { Button, Check, Switch, Section, Row, SelectRow } from '../components/ui.jsx'
import '../coach.css'
@@ -78,6 +83,7 @@ export default function CoachChat() {
if (!ready) return null
const coach = S.coach || emptyCoach()
const community = !!config?.coach?.community && !DEMO && !(MOBILE && coachMode === 'byok')
const send = async () => {
const msg = text.trim()
@@ -95,20 +101,45 @@ export default function CoachChat() {
setBusy(false)
}
const askReview = async () => {
const ask = async (fn, line) => {
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.') }))
await fn()
update(s => appendChat(s, { role: 'user', kind: 'text', text: line }))
refresh()
} catch (e) { toast(e.message || t('Could not ask the Coach')) }
setBusy(false)
}
const askReview = () => ask(() => requestReview(''), t('Have a look at my training and tell me what you would change.'))
const lastWorkout = (S.workouts || []).filter(w => w && w.d).at(-1) || null
const askDebrief = () => ask(() => requestDebrief(lastWorkout?.id || null), lastWorkout?.name
? t('How did my {0} session go?', lastWorkout.name)
: t('How did my last workout go?'))
const askImprove = r => ask(
() => requestReview(t('Focus only on my routine “{0}”. Improve it: exercise choice, order, sets and reps, rep ranges, progression. Leave the other routines alone.', r.name)),
t('Improve my routine “{0}”.', r.name))
const pickRoutine = () => openSheet(close => <div className="chat-menu">
<h3>{t('Improve which routine?')}</h3>
<div className="sect-b">
{(S.routines || []).map(r => <Row key={r.id} icon="dumbbell" iconTint="var(--acc)" title={`${r.emoji || ''} ${r.name}`.trim()} subtitle={t('{0} exercises', (r.ex || []).length)} accessory="chevron" onClick={() => { close(); askImprove(r) }} />)}
{!(S.routines || []).length && <div className="chat-empty">{t('You have no routines yet — ask the Coach for a plan first.')}</div>}
</div>
<div style={{ height: 10 }} />
</div>)
const showHistory = () => openSheet(close => <HistorySheet S={S} close={close} openSheet={openSheet} />)
const showCohort = () => openSheet(() => <CohortSheet S={S} update={update} toast={toast} />)
const idle = !job && !pending
const menu = () => openSheet(close => <div className="chat-menu">
<h3>{t('Coach')}</h3>
<div className="sect-b">
{!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() }} />}
{idle && <Row icon="sparkles" iconTint="var(--acc)" title={t('Ask for a review')} subtitle={t('What would the Coach change after your last sessions?')} accessory="chevron" onClick={() => { close(); askReview() }} />}
{idle && !!lastWorkout && <Row icon="checkCircle" iconTint="var(--green)" title={t('Review my last workout')} subtitle={t('What went well, what to watch, what to do next time')} accessory="chevron" onClick={() => { close(); askDebrief() }} />}
{idle && !!(S.routines || []).length && <Row icon="wrench" iconTint="var(--orange)" title={t('Improve a routine')} subtitle={t('Pick one; the Coach works on just that')} accessory="chevron" onClick={() => { close(); pickRoutine() }} />}
{community && <Row icon="person" iconTint="var(--teal)" title={t('Compare with others here')} subtitle={t('Anonymous medians from this instance')} accessory="chevron" onClick={() => { close(); showCohort() }} />}
<Row icon="history" iconTint="var(--blue)" title={t('Everything the Coach proposed')} subtitle={t('Plans, suggestions and debriefs, kept')} accessory="chevron" onClick={() => { close(); showHistory() }} />
<Row icon="clipboard" iconTint="var(--indigo)" title={t('Edit my answers')} subtitle={t('Goal, days, equipment, limits')} accessory="chevron" onClick={() => { close(); nav('/coach/intake?edit=1') }} />
<Row icon="clock" iconTint="var(--purple)" title={t('Automatic reviews')} subtitle={cadenceLabel(coach)} accessory="chevron" onClick={() => { close(); cadenceSheet(openSheet, update) }} />
{canRevert(S) && <Row icon="reset" iconTint="var(--blue)" title={t('Undo the last Coach changes')} accessory="chevron" onClick={() => { close(); doRevert() }} />}
@@ -146,18 +177,26 @@ export default function CoachChat() {
<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} />)}
{(coach.chat || []).map(m => <Message key={m.id} m={m} S={S} profile={coach.profile} openSheet={openSheet} />)}
{job && <Typing S={S} kind={job.kind} coachLocal={coachLocal} config={config} />}
{pending && !job && (pending.kind === 'create'
? <PlanCard p={pending} S={S} update={update} toast={toast} nav={nav} refresh={refresh} />
: <ReviewCard p={pending} S={S} update={update} toast={toast} refresh={refresh} />)}
: pending.kind === 'debrief'
? <DebriefCard p={pending} S={S} update={update} toast={toast} refresh={refresh} />
: <ReviewCard p={pending} S={S} update={update} toast={toast} refresh={refresh} />)}
<div ref={endRef} />
</div>
<div className="composer">
{idle && !busy && <div className="chips-row">
<button className="qchip" onClick={askReview}><Icon name="sparkles" />{t('Review my training')}</button>
{!!lastWorkout && <button className="qchip" onClick={askDebrief}><Icon name="checkCircle" />{t('Last workout')}</button>}
{!!(S.routines || []).length && <button className="qchip" onClick={pickRoutine}><Icon name="wrench" />{t('Improve a routine')}</button>}
{community && <button className="qchip" onClick={showCohort}><Icon name="person" />{t('Compare')}</button>}
</div>}
<div className="composer-in">
<textarea rows={1} value={text} maxLength={1000} placeholder={placeholder} disabled={!!job}
onChange={e => setText(e.target.value)}
@@ -179,7 +218,7 @@ function Bubble({ role, kind, at, children }) {
</div>
}
function Message({ m, profile }) {
function Message({ m, S, profile, openSheet }) {
if (m.kind === 'intake') {
const lines = profileLines(profile)
return <Bubble role="user" at={m.at}>
@@ -187,7 +226,15 @@ function Message({ m, profile }) {
<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') {
if (m.kind === 'applied' || m.kind === 'dismissed' || m.kind === 'debrief') {
const entry = m.ref ? logEntry(S, m.ref) : null
return <div className="msg coach" style={entry ? { maxWidth: '100%', width: '100%' } : undefined}>
{!!m.text && <div className="bub">{m.text}</div>}
{entry && <Recap entry={entry} S={S} openSheet={openSheet} />}
{m.at && <div className="msg-t">{stamp(m.at)}</div>}
</div>
}
if (m.kind === 'reverted' || m.kind === 'nochange' || m.kind === 'error' || m.kind === 'text') {
return <Bubble role={m.role} kind={m.kind} at={m.at}>{m.text}</Bubble>
}
return null
@@ -214,10 +261,11 @@ function Typing({ S, kind, coachLocal, config }) {
// local model rather than something wrong; the next line already warns it takes longer.
eta = local ? '' : t('This usually takes a minute or two.')
}
const doing = kind === 'create' ? t('Building your plan…') : kind === 'debrief' ? t('Looking at that session…') : t('Reading your training…')
return <div className="msg coach">
<div className="bub typing"><i /><i /><i /></div>
<div className="typing-eta">
{kind === 'create' ? t('Building your plan…') : t('Reading your training…')} {eta}
{doing} {eta}
{local ? ' ' + t('A local model can take longer.') : ''}
{' ' + t('You can leave — it keeps going.')}
</div>
@@ -239,7 +287,7 @@ function PlanCard({ p, S, update, toast, nav, refresh }) {
update(s => {
const res = applyCreatedPlan(s, p, { schedule })
n = res?.routines?.length || b.routines.length
appendChat(s, { role: 'coach', kind: 'applied', text: schedule
appendChat(s, { role: 'coach', kind: 'applied', ref: res.logId, text: schedule
? t('Imported — {0} routines are in your plan and your week is set. See you at the next session.', n)
: t('Imported — {0} routines are in your plan. Your week is unchanged; schedule them whenever you like.', n) })
})
@@ -252,7 +300,7 @@ function PlanCard({ p, S, update, toast, nav, refresh }) {
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.') }) })
update(s => { const ref = recordDismissal(s, p); appendChat(s, { role: 'coach', kind: 'dismissed', ref, text: t('Discarded. Tell me what was off and I will build a different one.') }) })
resolvePending({ dismissed: true }).catch(() => {})
refresh()
}
@@ -267,22 +315,13 @@ function PlanCard({ p, S, update, toast, nav, refresh }) {
{!!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>
<WeekStrip days={weekDays} />
{b.routines.length > 1 && <div className="pcard-tabs">
{b.routines.map((x, i) => <button key={x.id || i} className={'pcard-tab' + (i === tab ? ' on' : '')} onClick={() => setTab(i)}>{x.emoji} {x.name}</button>)}
</div>}
{r && <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>}
{r && <RoutineBlock r={r} unit={S.unit} />}
<div className="pcard-row">
<span className="lrow-m"><span className="lrow-t">{t('Use this weekly schedule')}</span><span className="lrow-s">{t('Replaces your current week. Days this plan leaves empty become rest days.')}</span></span>
@@ -298,6 +337,19 @@ function PlanCard({ p, S, update, toast, nav, refresh }) {
</div>
}
const WeekStrip = ({ days }) => <div className="pcard-week">
{[1, 2, 3, 4, 5, 6, 0].map(d => <div key={d} className={'pcard-wd' + (days.has(d) ? ' on' : '')}>{t(DAYS[d])}</div>)}
</div>
const RoutineBlock = ({ r, unit }) => <div className="pcard-rt">
<div className="pcard-rt-h"><b>{r.emoji} {r.name}</b><span>{t('{0} exercises', r.ex.length)}</span></div>
{!!r.why && <div className="pcard-why">{r.why}</div>}
{r.ex.map((e, i) => <div key={i} className="pcard-ex">
<div className="pcard-ex-r"><span className="pcard-ex-n">{exName(e.id)}</span><span className="pcard-ex-l">{exLine(e, unit)}</span></div>
{!!e.why && <div className="pcard-ex-w">{e.why}</div>}
</div>)}
</div>
/* ---------------------------------- a review ---------------------------------- */
function ReviewCard({ p, S, update, toast, refresh }) {
@@ -311,8 +363,8 @@ function ReviewCard({ p, S, update, toast, refresh }) {
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) })
const res = applyChangeSet(s, marked, ids)
appendChat(s, { role: 'coach', kind: 'applied', ref: res.logId, text: t(ids.length === 1 ? 'Applied {0} change to your plan.' : 'Applied {0} changes to your plan.', ids.length) })
})
resolvePending({ accepted: ids, rejected: marked.changes.filter(c => !ids.includes(c.id)).map(c => c.id) }).catch(() => {})
toast(t(ids.length === 1 ? '{0} change applied' : '{0} changes applied', ids.length))
@@ -323,7 +375,7 @@ function ReviewCard({ p, S, update, toast, refresh }) {
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.') }) })
update(s => { const ref = recordDismissal(s, marked); appendChat(s, { role: 'coach', kind: 'dismissed', ref, text: t('Understood — I will not suggest these again without new evidence.') }) })
resolvePending({ dismissed: true }).catch(() => {})
refresh()
}
@@ -343,23 +395,16 @@ function ReviewCard({ p, S, update, toast, refresh }) {
</p>}
</div>
<Insights S={S} window={marked.evidence} />
{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>
return <ChangeRow key={c.id} c={c} stale={stale}>
{!stale && <Check checked={accepted.has(c.id)} onChange={() => toggle(c.id)} />}
</div>
</ChangeRow>
})}
{!!marked.notes?.length && <div className="pcard-notes">
{marked.notes.map((n, i) => <div key={i}>💬 {n}</div>)}
</div>}
<Notes notes={marked.notes} />
<div className="pcard-note">{t('The Coach is not a doctor or a physiotherapist. If something hurts, ask a professional.')}</div>
<div className="pcard-ft">
@@ -372,6 +417,299 @@ function ReviewCard({ p, S, update, toast, refresh }) {
</div>
}
function ChangeRow({ c, stale, badge, children }) {
const vals = changeValues(c)
return <div className={'pcard-chg' + (stale ? ' stale' : '') + (c.status === 'rejected' ? ' declined' : '')}>
<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>
{badge}
{children}
</div>
}
const Notes = ({ notes }) => !!notes?.length && <div className="pcard-notes">
{notes.map((n, i) => <div key={i}><Icon name="lightbulb" />{n}</div>)}
</div>
/* ---------------------------------- insights ---------------------------------- */
const BP_LABEL = { back: 'Back', cardio: 'Cardio', chest: 'Chest', 'lower arms': 'Forearms', 'lower legs': 'Calves', neck: 'Neck', shoulders: 'Shoulders', 'upper arms': 'Arms', 'upper legs': 'Legs', waist: 'Core', other: 'Other' }
const bpLabel = bp => t(BP_LABEL[bp] || bp)
/**
* The numbers the Coach read, drawn: how much and how often, where the body weight went,
* which lifts moved, which body parts got the work. Computed on the device for the window the
* proposal names, so the picture under a suggestion is the evidence behind it, not decoration.
*/
function Insights({ S, window: win, compact }) {
const ins = useMemo(() => insightsFor(S, win || {}), [S, win?.from, win?.to])
if (!ins.sessions && !ins.bodyweight.points.length) return null
const maxBp = ins.bodyParts[0]?.sets || 1
const bw = ins.bodyweight
return <div className="ins">
<div className="ins-tiles">
<Tile v={ins.sessions} l={t('Sessions')} />
<Tile v={ins.minutes != null ? ins.minutes : '—'} l={t('Min / session')} />
<Tile v={ins.volume ? kfmt(ins.volume) : '—'} l={t('Volume ({0})', S.unit)} />
<Tile v={ins.sets} l={t('Work sets')} />
</div>
{bw.points.length > 1 && <div className="ins-block">
<div className="ins-h">
<span>{t('Body weight')}</span>
<span className={'ins-delta' + (bw.delta > 0 ? ' up' : bw.delta < 0 ? ' down' : '')}>
{bw.delta > 0 ? '+' : ''}{fmtNum(bw.delta)} {S.unit}{bw.goal != null ? ` · ${t('goal')} ${fmtNum(bw.goal)}` : ''}
</span>
</div>
<div className="chart"><LineChart points={bw.points} h={compact ? 96 : 120} unit={S.unit} goal={bw.goal} axes={!compact} /></div>
</div>}
{!!ins.strength.length && <div className="ins-block">
<div className="ins-h"><span>{t('Estimated 1RM')}</span><span className="dim">{t('first → last session')}</span></div>
{ins.strength.map(x => <div key={x.id} className="ins-row">
<span className="ins-row-n">{x.name}</span>
<span className="ins-row-v"><span className="tag">{fmtNum(x.first)}</span><Icon name="chevronRight" /><span className="tag acc">{fmtNum(x.last)}</span></span>
<span className={'ins-delta' + (x.delta > 0 ? ' up' : x.delta < 0 ? ' down' : '')}>{x.delta > 0 ? '▲' : x.delta < 0 ? '▼' : '•'} {Math.abs(x.pct)}%</span>
</div>)}
</div>}
{!!ins.bodyParts.length && !compact && <div className="ins-block">
<div className="ins-h"><span>{t('Work sets by body part')}</span></div>
{ins.bodyParts.slice(0, 6).map(b => <div key={b.bp} className="ins-bar">
<span className="ins-bar-l">{bpLabel(b.bp)}</span>
<span className="ins-bar-t"><i style={{ width: Math.max(4, Math.round(b.sets / maxBp * 100)) + '%' }} /></span>
<span className="ins-bar-v">{b.sets}</span>
</div>)}
</div>}
</div>
}
const Tile = ({ v, l }) => <div className="ins-tile"><div className="ins-tile-v">{v}</div><div className="ins-tile-l">{l}</div></div>
const kfmt = n => (n >= 10000 ? Math.round(n / 1000) + 'k' : fmtNum(n))
/* ---------------------------------- a debrief ---------------------------------- */
function DebriefBody({ p, S }) {
const w = p.workout || {}
const live = useMemo(() => sessionInsights(S, (S.workouts || []).find(x => x.id === w.id) || null), [S, w.id])
const score = Number.isFinite(p.score) ? Math.max(1, Math.min(10, p.score)) : null
return <>
{score != null && <div className="deb-score">
<div className="deb-ring" style={{ '--pct': score / 10 }}><span>{score}</span><small>/10</small></div>
<div className="deb-score-t"><b>{scoreWord(score)}</b><span>{w.name || t('Workout')}{w.d ? ' · ' + fmtDate(w.d) : ''}</span></div>
</div>}
{live && <div className="ins">
<div className="ins-tiles">
<Tile v={live.now.sets} l={t('Work sets')} />
<Tile v={live.now.minutes != null ? live.now.minutes : '—'} l={t('Minutes')} />
<Tile v={live.now.volume ? kfmt(live.now.volume) : '—'} l={t('Volume ({0})', S.unit)} />
<Tile v={live.now.prs || '—'} l={t('PRs')} />
</div>
{live.then && <div className="ins-cmp">
{t('vs. last {0} on {1}:', w.name || t('session'), fmtDate(live.prevDate))}{' '}
<Delta v={live.now.volume - live.then.volume} unit={S.unit} label={t('volume')} />
{live.now.minutes != null && live.then.minutes != null && <Delta v={live.now.minutes - live.then.minutes} unit="min" label={t('time')} />}
</div>}
{!!live.lifts.length && <div className="ins-block">
<div className="ins-h"><span>{t('Best set, estimated 1RM')}</span></div>
{live.lifts.slice(0, 6).map(x => <div key={x.id} className="ins-row">
<span className="ins-row-n">{x.name} <span className="dim">{fmtNum(x.w)}×{x.r}</span></span>
<span className="ins-row-v"><span className="tag acc">{fmtNum(x.est)}</span></span>
{x.prev != null && <span className={'ins-delta' + (x.est > x.prev ? ' up' : x.est < x.prev ? ' down' : '')}>{x.est > x.prev ? '▲' : x.est < x.prev ? '▼' : '•'} {fmtNum(Math.abs(x.est - x.prev))}</span>}
</div>)}
</div>}
</div>}
<DebriefList icon="checkCircle" tint="var(--green)" title={t('What went well')} items={p.highlights} />
<DebriefList icon="warning" tint="var(--yellow)" title={t('Worth watching')} items={p.watch} />
<DebriefList icon="arrowUp" tint="var(--acc)" title={t('Next time')} items={p.nextTime} />
</>
}
const Delta = ({ v, unit, label }) => <span className={'ins-delta' + (v > 0 ? ' up' : v < 0 ? ' down' : '')}>{v > 0 ? '+' : ''}{fmtNum(v)} {unit} {label}</span>
const DebriefList = ({ icon, tint, title, items }) => !!items?.length && <div className="deb-list">
<div className="deb-list-h" style={{ color: tint }}><Icon name={icon} />{title}</div>
{items.map((x, i) => <div key={i} className="deb-item">{x}</div>)}
</div>
const scoreWord = s => s >= 9 ? t('Excellent session') : s >= 7 ? t('Good session') : s >= 5 ? t('Solid session') : t('Tough session')
function DebriefCard({ p, S, update, toast, refresh }) {
const done = () => {
update(s => { const ref = recordDebrief(s, p); appendChat(s, { role: 'coach', kind: 'debrief', ref, text: '' }) })
resolvePending({ accepted: ['debrief'] }).catch(() => {})
toast(t('Kept in your Coach history'))
refresh()
}
return <div className="msg coach" style={{ maxWidth: '100%', width: '100%' }}>
<div className="pcard">
<div className="pcard-hd">
<div className="pcard-eyebrow">{t('Workout debrief')}</div>
<h2 className="pcard-h">{p.workout?.name || t('Your last workout')}</h2>
{!!p.summary && <p className="pcard-sum">{p.summary}</p>}
</div>
<DebriefBody p={p} S={S} />
<div className="pcard-ft">
<Button variant="primary" icon="check" onClick={done}>{t('Got it')}</Button>
</div>
</div>
<div className="msg-t">{t('Want changes to the plan from this? Ask for a review below.')}</div>
</div>
}
/* ---------------------------------- what was decided ---------------------------------- */
/** A decided proposal, folded: one line of what it was and what you did, and a way back in. */
function Recap({ entry, S, openSheet }) {
const open = () => openSheet(() => <ProposalDetail entry={entry} S={S} />)
const decisions = entry.decisions || []
const acc = decisions.filter(d => d.status === 'accepted').length
const rej = decisions.length - acc
const kind = entry.kind
const eyebrow = kind === 'create' ? t('Plan') : kind === 'debrief' ? t('Workout debrief') : t('Suggestions')
const state = kind === 'debrief' ? null
: entry.dismissed ? { cls: 'no', text: t('Declined') }
: kind === 'create' ? { cls: 'yes', text: t('Imported') }
: rej ? { cls: 'mix', text: t('{0} accepted · {1} declined', acc, rej) } : { cls: 'yes', text: t('{0} accepted', acc) }
const title = kind === 'create' ? (entry.bundle?.name || t('Coach plan'))
: kind === 'debrief' ? (entry.workout?.name || t('Workout')) + (entry.score != null ? ` · ${entry.score}/10` : '')
: t(decisions.length === 1 ? '{0} suggestion' : '{0} suggestions', decisions.length)
return <button className="recap" onClick={open}>
<div className="recap-top">
<span className="pcard-eyebrow">{eyebrow}</span>
{state && <span className={'recap-state ' + state.cls}>{state.text}</span>}
</div>
<div className="recap-t">{title}</div>
{!!entry.summary && <div className="recap-s">{entry.summary}</div>}
{kind === 'review' && !!decisions.length && <div className="recap-chips">
{decisions.slice(0, 4).map(d => <span key={d.id} className={'recap-chip ' + (d.status === 'accepted' ? 'yes' : 'no')}><Icon name={d.status === 'accepted' ? 'check' : 'xmark'} />{changeTitle(d)}</span>)}
{decisions.length > 4 && <span className="recap-chip">+{decisions.length - 4}</span>}
</div>}
<div className="recap-more">{t('Show everything')}<Icon name="chevronRight" /></div>
</button>
}
/** The whole proposal, as it was, read-only. */
function ProposalDetail({ entry, S }) {
const [tab, setTab] = useState(0)
const kind = entry.kind
const b = entry.bundle
const r = b?.routines?.[Math.min(tab, (b?.routines?.length || 1) - 1)]
const weekDays = useMemo(() => new Set(Object.keys(b?.week || {}).map(Number)), [b])
return <div className="pdetail">
<div className="pcard-hd" style={{ paddingLeft: 0, paddingRight: 0 }}>
<div className="pcard-eyebrow">{kind === 'create' ? t('Plan') : kind === 'debrief' ? t('Workout debrief') : t('Suggestions')} · {fmtDate(new Date(entry.at).toISOString().slice(0, 10))}</div>
<h2 className="pcard-h">{kind === 'create' ? (b?.name || t('Coach plan')) : kind === 'debrief' ? (entry.workout?.name || t('Workout')) : t(entry.decisions?.length === 1 ? '{0} suggestion' : '{0} suggestions', entry.decisions?.length || 0)}</h2>
{!!entry.summary && <p className="pcard-sum">{entry.summary}</p>}
{entry.dismissed && <p className="pcard-sum" style={{ color: 'var(--red)' }}>{t('You declined this.')}</p>}
{!!entry.evidence?.sessions && <p className="pcard-sum" style={{ fontSize: 13 }}>
{t('Based on your last {0} sessions', entry.evidence.sessions)}{entry.evidence.from ? ` · ${fmtDate(entry.evidence.from)} – ${fmtDate(entry.evidence.to)}` : ''}
</p>}
</div>
{kind === 'review' && <>
<Insights S={S} window={entry.evidence} />
{(entry.decisions || []).map(d => <ChangeRow key={d.id} c={d} stale={d.status === 'stale'}
badge={<span className={'recap-state ' + (d.status === 'accepted' ? 'yes' : 'no')}>{d.status === 'accepted' ? t('Accepted') : d.status === 'stale' ? t('Expired') : t('Declined')}</span>} />)}
<Notes notes={entry.notes} />
</>}
{kind === 'create' && b && <>
<WeekStrip days={weekDays} />
{b.routines.length > 1 && <div className="pcard-tabs" style={{ paddingLeft: 0, paddingRight: 0 }}>
{b.routines.map((x, i) => <button key={x.id || i} className={'pcard-tab' + (i === tab ? ' on' : '')} onClick={() => setTab(i)}>{x.emoji} {x.name}</button>)}
</div>}
{r && <RoutineBlock r={r} unit={S.unit} />}
<p className="pcard-sum" style={{ fontSize: 13 }}>{entry.scheduled ? t('Your week was set to this schedule.') : t('Imported without changing your week.')}</p>
</>}
{kind === 'create' && !b && <p className="pcard-sum">{t('This plan was imported before the app kept proposals; only its summary is left.')}</p>}
{kind === 'debrief' && <DebriefBody p={entry} S={S} />}
{kind === 'revert' && <p className="pcard-sum">{t('Reverted the last Coach changes.')}</p>}
<div style={{ height: 10 }} />
</div>
}
/** Every proposal ever made, newest first. Nothing the Coach said is gone after a decision. */
function HistorySheet({ S, close, openSheet }) {
const log = [...(S.coach?.log || [])].reverse()
const icon = { create: ['clipboard', 'var(--indigo)'], review: ['sparkles', 'var(--acc)'], debrief: ['checkCircle', 'var(--green)'], revert: ['reset', 'var(--blue)'] }
return <div className="chat-menu">
<h3>{t('Everything the Coach proposed')}</h3>
{!log.length && <div className="chat-empty">{t('Nothing yet. Every plan, suggestion and debrief will be kept here — whether you said yes or no.')}</div>}
<div className="sect-b">
{log.map(e => {
const [ic, tint] = icon[e.kind] || ['sparkles', 'var(--acc)']
const n = (e.decisions || []).length
const acc = (e.decisions || []).filter(d => d.status === 'accepted').length
const title = e.kind === 'create' ? (e.bundle?.name || t('Coach plan')) + (e.iteration > 1 ? ` · ${t('Revision {0}', e.iteration)}` : '')
: e.kind === 'debrief' ? t('Debrief: {0}', e.workout?.name || t('Workout')) + (e.score != null ? ` · ${e.score}/10` : '')
: e.kind === 'revert' ? t('Reverted the last Coach changes.')
: t(n === 1 ? '{0} suggestion' : '{0} suggestions', n)
const sub = fmtDate(new Date(e.at).toISOString().slice(0, 10)) + ' · ' + (e.kind === 'debrief' ? String(e.summary || '').slice(0, 60)
: e.dismissed ? t('Declined') : e.kind === 'create' ? t('Imported') : e.kind === 'revert' ? '' : t('{0} accepted · {1} declined', acc, n - acc))
return <Row key={e.id} icon={ic} iconTint={tint} title={title} subtitle={sub} accessory="chevron"
onClick={() => { close(); openSheet(() => <ProposalDetail entry={e} S={S} />) }} />
})}
</div>
<div style={{ height: 10 }} />
</div>
}
/* ---------------------------------- the others here ---------------------------------- */
/**
* How you sit against everyone else on this instance — medians only, at least three people
* sharing, nothing that identifies anyone. The admin turns it on for the instance; each person
* turns it on for themselves; a person who does not share sees nothing either.
*/
function CohortSheet({ S, update, toast }) {
const [d, setD] = useState(null)
const [busy, setBusy] = useState(false)
const load = () => cohortStats().then(setD).catch(e => { toast(e.message || t('Could not load')); setD({ ok: false }) })
useEffect(() => { load() }, [])
const share = async v => {
setBusy(true)
try { await setCohortShare(v); update(s => { (s.coach = s.coach || emptyCoach()).share = v }); await load() }
catch (e) { toast(e.message || t('Could not save')) }
setBusy(false)
}
const sharing = !!d?.sharing
return <div className="chat-menu">
<h3>{t('Compare with others here')}</h3>
<Section footer={t('Only medians across everyone who shares, never a name, a body weight or a single session. Turning this off removes you from the numbers immediately.')}>
<Row icon="person" iconTint="var(--teal)" title={t('Include me')} subtitle={sharing ? t('Your lifts count towards the medians') : t('Off — you see nothing and share nothing')}>
<Switch checked={sharing} disabled={busy || !d} onChange={share} />
</Row>
</Section>
{!d && <div className="chat-empty">{t('Loading…')}</div>}
{d && sharing && !d.ok && <div className="chat-empty">{d.people != null
? t('Not enough people share yet — {0} of {1} needed. Ask your gym mates.', d.people, d.minPeople)
: t('Not available right now.')}</div>}
{d && sharing && d.ok && <div className="ins" style={{ padding: 0 }}>
<div className="ins-tiles">
<Tile v={d.people} l={t('People')} />
<Tile v={fmtNum(d.sessionsPerWeek.you)} l={t('Your sessions / wk')} />
<Tile v={fmtNum(d.sessionsPerWeek.median)} l={t('Median / wk')} />
<Tile v={d.rankPct != null ? d.rankPct + '%' : '—'} l={t('Your strength rank')} />
</div>
{!!d.exercises.length && <div className="ins-block">
<div className="ins-h"><span>{t('Estimated 1RM, you vs. median')}</span><span className="dim">{S.unit}</span></div>
{d.exercises.map(x => {
const max = Math.max(x.median, x.you || 0) || 1
return <div key={x.id} className="cmp">
<div className="cmp-h"><span>{x.name}</span><span className="dim">{x.people} {t('people')}</span></div>
<div className="cmp-bar you"><i style={{ width: Math.round((x.you || 0) / max * 100) + '%' }} /><span>{t('You')} · {x.you != null ? fmtNum(x.you) : '—'}</span></div>
<div className="cmp-bar"><i style={{ width: Math.round(x.median / max * 100) + '%' }} /><span>{t('Median')} · {fmtNum(x.median)}</span></div>
</div>
})}
</div>}
{!d.exercises.length && <div className="chat-empty">{t('No exercise is trained by three or more people yet.')}</div>}
</div>}
<div style={{ height: 10 }} />
</div>
}
/* ---------------------------------- cadence ---------------------------------- */
const cadenceLabel = coach => {
+56 -4
View File
@@ -9,11 +9,11 @@ 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() }
const state = { S: null, pending: null, job: null, community: false, nav: vi.fn(), toast: vi.fn(), openSheet: vi.fn(), refresh: vi.fn() }
state.storeSnapshot = () => ({
S: state.S,
user: { id: 'u1' },
config: { coach: { enabled: true } },
config: { coach: { enabled: true, ...(state.community ? { community: true } : {}) } },
coachLocal: null,
update: mut => mut(state.S),
})
@@ -37,6 +37,9 @@ vi.mock('../lib/coach-api.js', () => ({
resolvePending: vi.fn(() => Promise.resolve({})),
refinePlan: vi.fn(() => Promise.resolve({})),
requestReview: vi.fn(() => Promise.resolve({})),
requestDebrief: vi.fn(() => Promise.resolve({})),
cohortStats: vi.fn(() => Promise.resolve({ ok: false, enabled: true, sharing: false })),
setCohortShare: vi.fn(() => Promise.resolve({ ok: true, sharing: true })),
JOB_ERRORS: { internal: 'x' },
}))
vi.mock('../sheets.jsx', () => ({ startFlow: vi.fn(), confirmSheet: vi.fn() }))
@@ -82,10 +85,11 @@ function installDom() {
root = createRoot(container)
}
async function mount(pending, job = null) {
mocks.S = state()
async function mount(pending, job = null, { community = false, S = state() } = {}) {
mocks.S = S
mocks.pending = pending
mocks.job = job
mocks.community = community
installDom()
await act(async () => { root.render(React.createElement(CoachChat)) })
}
@@ -156,4 +160,52 @@ describe('the Coach chat', () => {
expect(mocks.S.coach.chat.at(-1).kind).toBe('applied')
expect(mocks.S.coach.log.at(-1).decisions.map(d => d.status)).toEqual(['accepted', 'rejected'])
})
it('keeps an applied review in the thread as a card that opens the whole proposal', async () => {
await mount({ id: 'r1', kind: 'review', summary: 'a reading', changes: [
{ id: 'a', type: 'week', target: { weekday: 1 }, before: null, after: null, why: 'rest' },
{ id: 'b', type: 'add-routine', target: {}, before: null, after: { name: 'Legs', ex: [{ id: '0001', sets: 3, reps: 10 }] }, why: 'legs' }
] })
await click([...container.querySelectorAll('[role="checkbox"]')][0])
await click(byText(/Apply 1 change/))
// The decision is in the store; re-render with the proposal gone, as the poll would.
mocks.pending = null
await act(async () => { root.render(React.createElement(CoachChat)) })
const recap = container.querySelector('.recap')
expect(recap).toBeTruthy()
expect(recap.textContent).toContain('1 accepted · 1 declined')
expect(recap.querySelectorAll('.recap-chip.yes').length).toBe(1)
expect(recap.querySelectorAll('.recap-chip.no').length).toBe(1)
expect(mocks.S.coach.chat.at(-1).ref).toBe(mocks.S.coach.log.at(-1).id)
await click(recap)
expect(mocks.openSheet).toHaveBeenCalled()
})
it('shows a debrief with its score ring and files it on "Got it"', async () => {
await mount({ id: 'd1', kind: 'debrief', workout: { id: 'w1', name: 'Push', d: '2026-08-29' }, summary: 'ok', score: 8, highlights: ['a'], watch: [], nextTime: ['b'] })
expect(container.querySelector('.deb-ring')).toBeTruthy()
expect(container.textContent).toContain('Good session')
expect(container.textContent).toContain('What went well')
expect(container.textContent).not.toContain('Worth watching')
await click(byText(/Got it/))
expect(mocks.S.coach.log.at(-1).kind).toBe('debrief')
expect(mocks.S.coach.log.at(-1).score).toBe(8)
expect(mocks.S.coach.chat.at(-1).kind).toBe('debrief')
expect(mocks.S.coach.chat.at(-1).ref).toBe(mocks.S.coach.log.at(-1).id)
})
it('offers the quick actions only when nothing is running', async () => {
await mount(null)
expect(byText(/Review my training/)).toBeTruthy()
expect(byText(/Last workout/)).toBeFalsy() // no workout logged yet
await mount(null, { id: 'j1', kind: 'review', state: 'running', startedAt: Date.now() })
expect(byText(/Review my training/)).toBeFalsy()
})
it('offers the comparison only when the instance allows it', async () => {
await mount(null)
expect(byText(/^Compare$/)).toBeFalsy()
await mount(null, null, { community: true })
expect(byText(/^Compare$/)).toBeTruthy()
})
})