Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

fix(coach): CoachSetup's Save, the demo Coach's failure state, and the intake line

Boris 'B' Kurktchiev8b2376c7b1b6
diff --git a/api/coach/routes.js b/api/coach/routes.js
index 1a9f81081..9972ca905 100644
--- a/api/coach/routes.js
+++ b/api/coach/routes.js
@@ -207,6 +207,11 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) {
if (!cfgStore.PROVIDERS[target].baseUrl) return json(res, 400, { error: `${target} has a fixed endpoint` });
const v = validateBaseUrl(body.baseUrl);
if (!v.ok) return json(res, 400, { error: v.error });
+ // An empty value passes the validator on purpose: for a provider with a default it means
+ // "back to the default". A provider with none (compatible) would be saved pointing at ''
+ // and baseUrlFor() would hand the adapter nothing to call. The phone's CoachSetup refuses
+ // the same case; the admin route has to as well or the hole just moves.
+ if (!v.value && !cfgStore.PROVIDERS[target].defaultBase) return json(res, 400, { error: `${target} has no default endpoint, enter one` });
patch.providerOptions = { ...current.providerOptions, [target]: { ...(current.providerOptions[target] || {}), baseUrl: v.value } };
}
if (body.community !== undefined) patch.community = !!body.community;
diff --git a/api/test/routes.test.js b/api/test/routes.test.js
index e1affe81e..281bc385b 100644
--- a/api/test/routes.test.js
+++ b/api/test/routes.test.js
@@ -123,6 +123,14 @@ test('the compatible endpoint: base URL is validated, a keyless endpoint counts
const { call } = harness();
let r = await call('POST /api/admin/coach/config', { provider: 'compatible', baseUrl: 'http://user:pw@x' });
assert.equal(r.status, 400);
+ // Empty passes validateBaseUrl on purpose (it means "the default" for anthropic/openai/gemini),
+ // but compatible has no default, so empty is nowhere to call. This used to save baseUrl: null
+ // and baseUrlFor() then handed the adapter ''. The phone refuses it too.
+ r = await call('POST /api/admin/coach/config', { provider: 'compatible', baseUrl: '' });
+ assert.equal(r.status, 400, 'an empty endpoint for a provider with no default');
+ assert.match(r.body.error, /no default endpoint/);
+ r = await call('POST /api/admin/coach/config', { provider: 'compatible', baseUrl: ' ' });
+ assert.equal(r.status, 400, 'whitespace is empty');
r = await call('POST /api/admin/coach/config', { provider: 'compatible', baseUrl: base + '/' });
assert.equal(r.status, 200);
diff --git a/frontend/src/lib/coach-demo.js b/frontend/src/lib/coach-demo.js
index 1c9e9daf7..44c8e5643 100644
--- a/frontend/src/lib/coach-demo.js
+++ b/frontend/src/lib/coach-demo.js
@@ -25,16 +25,23 @@ const DELAY = 2200 // long enough to see "the Coach is thinking…", short
let pending = null
let job = null
let timer = null
+let lastError = null // the last job that ended without a proposal, in the server's shape
const iso = d => d.toISOString().slice(0, 10)
+/** The routine the canned review aims at: the first with two exercises, one to swap and one to cut a set from. */
+const reviewable = S => (S.routines || []).find(r => (r.ex || []).length >= 2)
+
/** 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)
+ const routine = reviewable(S)
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]
+ // Anything but `first`: the two changes below swap `first` away and re-set `second`, so the
+ // same entry in both aborts the whole change-set on apply (`missing target`). `reps[1]` was
+ // not enough — a routine whose only rep-mode exercise sits at index 1 landed on it twice.
+ const second = reps.find(e => e !== first) || routine.ex.find(e => e !== first)
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
@@ -116,9 +123,14 @@ 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))
+ // workoutVolume() reads `w.entries` and `e.sets` without a guard; every other line here
+ // tolerates both being absent. A workout carrying a date and nothing else therefore threw
+ // inside the timer below, where at the time nothing caught it — the job stayed 'running'
+ // for ever and every later request answered 409.
+ const entries = (w.entries || []).map(en => ({ ...en, sets: en.sets || [] }))
+ const done = entries.reduce((n, en) => n + en.sets.filter(s => s.done && !isWarmupRow(s)).length, 0)
+ const planned = 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, entries }))
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
@@ -156,19 +168,38 @@ export function demoCohort(S) {
/* ---------------- the API surface the demo stands in for ---------------- */
-export const demoStatus = () => ({ job, pending, cap: { used: 0, limit: 0 } })
+export const demoStatus = () => ({ job, pending, cap: { used: 0, limit: 0 }, lastError })
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() }
+ lastError = null
clearTimeout(timer)
- timer = setTimeout(() => { pending = make(); job = null }, DELAY)
+ // A builder that throws still has to end the job: left uncaught, one throw kept `job` at
+ // 'running' for ever and every later request answered 409 until the page was reloaded. The
+ // failure is recorded the way the server and the phone record theirs, so the chat's
+ // job-ended effect writes the same error line it would for them. `nostate` because the only
+ // thing a builder can trip over is the shape of the profile's own data.
+ timer = setTimeout(() => {
+ try { pending = make() }
+ catch (e) { lastError = { errorClass: 'nostate', detail: String(e && e.message || e) } }
+ finally { job = null }
+ }, DELAY)
return { job }
}
-export const demoReview = S => start('review', () => buildReview(S))
+export const demoReview = S => {
+ // Refused before the job starts, the way demoDebrief refuses with no workout: without a
+ // two-exercise routine buildReview has nothing to aim at, and a job that runs the whole wait
+ // and ends with neither a proposal nor an error reads as the Coach ignoring you.
+ if (!reviewable(S)) throw Object.assign(new Error(t('There is no routine to review yet — build one with at least two exercises first.')), { status: 409, code: 'noroutine' })
+ return start('review', () => buildReview(S))
+}
export const demoPlan = (S, intake) => start('create', () => buildPlan(S, intake))
+// A refine re-reads the saved answers, as the server's payload does when a refine carries no
+// intake of its own (`opts.intake || coach.profile`). Built from nothing, every revised plan
+// went back to Mon/Wed/Fri whatever days were chosen at intake.
export const demoRefine = S => start('create', () => {
- const p = buildPlan(S, null)
+ const p = buildPlan(S, S.coach?.profile || 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) => {
diff --git a/frontend/src/lib/coach-demo.test.js b/frontend/src/lib/coach-demo.test.js
new file mode 100644
index 000000000..5d7d71b87
--- /dev/null
+++ b/frontend/src/lib/coach-demo.test.js
@@ -0,0 +1,404 @@
+// The Coach in the demo build: the canned provider behind lib/coach-api.js when DEMO is set.
+//
+// Nothing here is a render test. What matters about this module is the job machine (one job at
+// a time, an answer 2.2 s later, a pending proposal that survives until it is resolved) and the
+// fact that every proposal it makes is aimed at the demo profile's OWN ids — so applying one
+// exercises the same validate → snapshot → apply → revert path a live instance does. The
+// asserts below are therefore about the change-set and the state machine, not about strings.
+//
+// The module keeps `job`, `pending` and `timer` at module scope with no reset hook, so every
+// test here starts a job and then drains it. A test that leaves one running would 409 the next.
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import {
+ demoStatus, demoPlan, demoReview, demoRefine, demoDebrief, demoResolve, demoCohort, demoDisclosure
+} from './coach-demo.js'
+import { EXDB, EXIDX } from './exercises.js'
+import { planHash, validateProposal, applyChangeSet } from './coach.js'
+import { DATA_CATEGORIES } from '../../../api/coach/core/categories.js'
+
+const DELAY = 2200 // the module's own thinking time
+const NOW = new Date('2026-09-22T12:00:00Z').getTime()
+const day = n => new Date(NOW - n * 864e5).toISOString().slice(0, 10)
+
+// Real catalogue ids, so EXIDX lookups and the body-part search behave as they do in the app.
+const PRESS = EXDB.find(e => e.bp === 'chest').id
+const ROW = EXDB.find(e => e.bp === 'back').id
+const SQUAT = EXDB.find(e => e.bp === 'upper legs').id
+const PLANK = EXDB.find(e => e.bp === 'waist').id
+
+const workout = (over = {}) => ({
+ id: 'w1', d: day(1), start: NOW - 864e5, end: NOW - 864e5 + 3600e3, prs: [],
+ entries: [{ id: PRESS, target: { sets: 3, reps: 8 }, sets: [
+ { done: true, w: 60, r: 8 }, { done: true, w: 60, r: 8 }, { done: true, w: 60, r: 8 }
+ ] }],
+ ...over
+})
+
+const state = (over = {}) => ({
+ unit: 'kg', lang: 'en', customEx: [], bodyweight: [], exWeights: {}, dayPlan: {},
+ routines: [
+ { id: 'r1', name: 'Push', ex: [{ id: PRESS, sets: 3, reps: 8, mode: 'reps' }, { id: ROW, sets: 3, reps: 10, mode: 'reps' }] },
+ { id: 'r2', name: 'Legs', ex: [{ id: SQUAT, sets: 4, reps: 5, mode: 'reps' }] }
+ ],
+ week: { 1: 'r1', 4: 'r2' },
+ workouts: [workout()],
+ coach: { consent: { agreedAt: '2026-09-01T00:00:00Z', version: 1 }, profile: null, log: [], snapshots: [], chat: [], timings: [] },
+ ...over
+})
+
+// Start a job and let the 2.2 s land; returns whatever the module parked as `pending`.
+const think = start => { start(); vi.advanceTimersByTime(DELAY); return demoStatus().pending }
+
+beforeEach(() => {
+ vi.useFakeTimers()
+ vi.setSystemTime(NOW)
+ demoResolve() // no pending proposal leaks between tests
+})
+afterEach(() => { vi.useRealTimers() })
+
+describe('coach-demo — the job machine', () => {
+ it('is idle until asked, and reports the same cap shape the real status does', () => {
+ expect(demoStatus()).toEqual({ job: null, pending: null, cap: { used: 0, limit: 0 }, lastError: null })
+ })
+
+ it('answers 2.2 s later, not before — the job is visible for the whole wait', () => {
+ const S = state()
+ const { job } = demoPlan(S, null)
+ expect(job).toMatchObject({ id: 'demo-create', kind: 'create', state: 'running', startedAt: NOW })
+ expect(demoStatus().job).toBe(job)
+
+ vi.advanceTimersByTime(DELAY - 1)
+ expect(demoStatus().job).toBe(job)
+ expect(demoStatus().pending).toBe(null)
+
+ vi.advanceTimersByTime(1)
+ expect(demoStatus().job).toBe(null)
+ expect(demoStatus().pending).toMatchObject({ kind: 'create' })
+ })
+
+ it('refuses a second request while one is running, with the 409 the UI reads', () => {
+ const S = state()
+ demoPlan(S, null)
+ let err
+ try { demoReview(S) } catch (e) { err = e }
+ expect(err).toBeInstanceOf(Error)
+ expect(err.status).toBe(409)
+ expect(err.message).toBe('The Coach is already thinking about your training.')
+ // and the running job is untouched by the refusal
+ expect(demoStatus().job.kind).toBe('create')
+ vi.advanceTimersByTime(DELAY)
+ })
+
+ it('a pending proposal survives until it is resolved, and resolving clears only it', () => {
+ const S = state()
+ expect(think(() => demoReview(S))).toBeTruthy()
+ vi.advanceTimersByTime(864e5)
+ expect(demoStatus().pending).toBeTruthy()
+ expect(demoResolve()).toEqual({ ok: true })
+ expect(demoStatus()).toEqual({ job: null, pending: null, cap: { used: 0, limit: 0 }, lastError: null })
+ })
+
+ it('a builder that throws ends the job, records the failure, and does not refuse the next request', () => {
+ // Before this a throw inside the timer left `job` at 'running' for ever and every later
+ // request answered 409 until the page was reloaded. Any throw will do; a getter is the one
+ // way to provoke it that no later hardening of the builders can quietly remove.
+ const S = state()
+ Object.defineProperty(S, 'workouts', { get() { throw new Error('boom') } })
+ demoPlan(S, null)
+ expect(demoStatus().job).toMatchObject({ kind: 'create', state: 'running' })
+ expect(() => vi.advanceTimersByTime(DELAY)).not.toThrow()
+
+ expect(demoStatus().job).toBe(null)
+ expect(demoStatus().pending).toBe(null)
+ // The shape CoachChat reads off the server's status: `lastError.errorClass` picks the line,
+ // `detail` rides along for the phone's own-words rendering.
+ expect(demoStatus().lastError).toEqual({ errorClass: 'nostate', detail: 'boom' })
+
+ // and the next request is taken, not 409'd, and starts with a clean slate
+ expect(() => demoReview(state())).not.toThrow()
+ expect(demoStatus().job).toMatchObject({ kind: 'review', state: 'running' })
+ expect(demoStatus().lastError).toBe(null)
+ vi.advanceTimersByTime(DELAY)
+ expect(demoStatus().pending).toMatchObject({ kind: 'review' })
+ })
+})
+
+describe('coach-demo — the starter plan', () => {
+ it('schedules the preferred days round-robin across the two routines', () => {
+ const p = think(() => demoPlan(state(), { preferredDays: [2, 4, 6, 0], equipment: [] }))
+ expect(Object.keys(p.bundle.week).map(Number).sort((a, b) => a - b)).toEqual([2, 4, 6]) // sliced to 3
+ expect(p.bundle.week).toEqual({ 2: 'dr1', 4: 'dr2', 6: 'dr1' })
+ })
+
+ it('falls back to Mon/Wed/Fri when the intake named no days', () => {
+ expect(think(() => demoPlan(state(), { equipment: [] })).bundle.week).toEqual({ 1: 'dr1', 3: 'dr2', 5: 'dr1' })
+ expect(think(() => demoPlan(state(), null)).bundle.week).toEqual({ 1: 'dr1', 3: 'dr2', 5: 'dr1' })
+ })
+
+ it('builds every exercise from the first listed equipment, falling back to the catalogue', () => {
+ const p = think(() => demoPlan(state(), { equipment: ['dumbbell', 'barbell'] }))
+ const ids = p.bundle.routines.flatMap(r => r.ex.map(e => e.id))
+ expect(ids).toHaveLength(6)
+ for (const bp of ['upper legs', 'chest', 'back', 'shoulders', 'upper arms']) {
+ const want = (EXDB.find(e => e.bp === bp && e.eq === 'dumbbell') || EXDB.find(e => e.bp === bp)).id
+ expect(ids).toContain(want)
+ }
+ // every id resolves in the catalogue — the whole point of building from EXDB
+ ids.forEach(id => expect(EXIDX[id]).toBeTruthy())
+ })
+
+ it('says whether it had any history to go on', () => {
+ expect(think(() => demoPlan(state(), null)).bundle.basedOn)
+ .toBe('Based on the training already in this demo profile.')
+ expect(think(() => demoPlan(state({ workouts: [] }), null)).bundle.basedOn)
+ .toBe('No training history yet — starting conservatively.')
+ })
+
+ it('stamps the plan hash of the state it was built from, so the app can spot a stale one', () => {
+ const S = state()
+ expect(think(() => demoPlan(S, null)).planHash).toBe(planHash(S))
+ })
+
+ it('produces a bundle the app’s own validator accepts', () => {
+ const p = think(() => demoPlan(state(), null))
+ expect(validateProposal(p)).toBe(true)
+ expect(p.bundle.opengym_plan).toBe(1)
+ expect(Object.values(p.bundle.week).every(id => p.bundle.routines.some(r => r.id === id))).toBe(true)
+ })
+})
+
+describe('coach-demo — refining a plan', () => {
+ it('counts iterations off the proposal on the table and keeps the rest of the plan', () => {
+ const S = state()
+ const first = think(() => demoPlan(S, { preferredDays: [2, 4] }))
+ expect(first.iteration).toBe(1)
+
+ const second = think(() => demoRefine(S))
+ expect(second.iteration).toBe(2)
+ expect(second.summary.startsWith('Revised as you asked.')).toBe(true)
+ expect(think(() => demoRefine(S)).iteration).toBe(3)
+ })
+
+ it('a refine with nothing pending still starts at iteration 2', () => {
+ expect(demoStatus().pending).toBe(null)
+ expect(think(() => demoRefine(state())).iteration).toBe(2)
+ })
+
+ it('a refined plan keeps the days the intake chose', () => {
+ // The answers live in S.coach.profile once the intake has saved them, and that is where the
+ // server's payload reads them from when a refine carries no intake of its own. Built from
+ // nothing, every revised plan went back to Mon/Wed/Fri.
+ const S = state()
+ S.coach.profile = { preferredDays: [2, 4, 6], equipment: [] }
+ think(() => demoPlan(S, S.coach.profile))
+ expect(think(() => demoRefine(S)).bundle.week).toEqual({ 2: 'dr1', 4: 'dr2', 6: 'dr1' })
+ // and still the default when there are no answers on file
+ expect(think(() => demoRefine(state())).bundle.week).toEqual({ 1: 'dr1', 3: 'dr2', 5: 'dr1' })
+ })
+})
+
+describe('coach-demo — the review', () => {
+ it('aims three changes at the profile’s own routines, and swaps in something it does not already have', () => {
+ const S = state()
+ const p = think(() => demoReview(S))
+ expect(p.changes.map(c => c.id)).toEqual(['d1', 'd2', 'd3'])
+ expect(p.changes.map(c => c.type)).toEqual(['swap-exercise', 'sets', 'week'])
+
+ const [swap, sets, week] = p.changes
+ expect(swap.target).toEqual({ routineId: 'r1', exId: PRESS })
+ expect(EXIDX[swap.after.id].bp).toBe(EXIDX[PRESS].bp) // same body part
+ expect(S.routines[0].ex.some(e => e.id === swap.after.id)).toBe(false) // not already in the routine
+ expect(sets.target).toEqual({ routineId: 'r1', exId: ROW })
+ expect(sets.before).toBe(3)
+ expect(sets.after).toBe(2)
+ expect(week).toMatchObject({ target: { weekday: 6 }, before: null, after: 'r2' })
+ expect(validateProposal(p)).toBe(true)
+ })
+
+ it('never proposes fewer than one set, and reads a missing set count as three', () => {
+ const S = state()
+ S.routines[0].ex[1] = { id: ROW, reps: 10, mode: 'reps' } // no `sets` key at all
+ expect(think(() => demoReview(S)).changes[1]).toMatchObject({ before: 3, after: 2 })
+
+ const S1 = state()
+ S1.routines[0].ex[1].sets = 1
+ expect(think(() => demoReview(S1)).changes[1]).toMatchObject({ before: 1, after: 1 })
+ })
+
+ it('still finds a swap for a body part the catalogue has no dumbbell for', () => {
+ const NECK = EXDB.find(e => e.bp === 'neck').id
+ expect(EXDB.some(e => e.bp === 'neck' && e.eq === 'dumbbell')).toBe(false)
+ const S = state({ routines: [{ id: 'r1', name: 'Neck', ex: [{ id: NECK, sets: 3, reps: 10, mode: 'reps' }, { id: ROW, sets: 3, reps: 10, mode: 'reps' }] }] })
+ const swap = think(() => demoReview(S)).changes[0]
+ expect(swap.target.exId).toBe(NECK)
+ expect(EXIDX[swap.after.id].bp).toBe('neck')
+ expect(swap.after.id).not.toBe(NECK)
+ })
+
+ it('leaves out the weekday change when there is only one routine', () => {
+ const S = state({ routines: [state().routines[0]], week: { 1: 'r1' } })
+ expect(think(() => demoReview(S)).changes.map(c => c.type)).toEqual(['swap-exercise', 'sets'])
+ })
+
+ it('reports the last nine sessions as its evidence window', () => {
+ const workouts = Array.from({ length: 12 }, (_, i) => workout({ id: 'w' + i, d: day(12 - i) }))
+ const p = think(() => demoReview(state({ workouts })))
+ expect(p.evidence).toEqual({ from: day(9), to: day(1), sessions: 9 })
+ })
+
+ it('falls back to a four-week window when the profile has never trained', () => {
+ const p = think(() => demoReview(state({ workouts: [] })))
+ expect(p.evidence).toEqual({ from: day(28), to: day(0), sessions: 9 })
+ })
+
+ it('refuses up front when no routine has two exercises to work with, and starts no job', () => {
+ // The canned review swaps one exercise and cuts a set from another, so it needs a routine
+ // with two. Refused before the job starts, the way demoDebrief refuses with no workout;
+ // before this the job ran the whole wait and vanished with neither a proposal nor an error.
+ const S = state({ routines: [{ id: 'r1', name: 'Solo', ex: [{ id: PRESS, sets: 3, reps: 8, mode: 'reps' }] }] })
+ let err
+ try { demoReview(S) } catch (e) { err = e }
+ expect(err.status).toBe(409)
+ expect(err.code).toBe('noroutine')
+ expect(err.message).toBe('There is no routine to review yet — build one with at least two exercises first.')
+ expect(demoStatus().job).toBe(null)
+ vi.advanceTimersByTime(DELAY)
+ expect(demoStatus().pending).toBe(null)
+ })
+})
+
+describe('coach-demo — the debrief', () => {
+ it('refuses up front when there is nothing to look at, and starts no job', () => {
+ let err
+ try { demoDebrief(state({ workouts: [] })) } catch (e) { err = e }
+ expect(err.status).toBe(409)
+ expect(err.code).toBe('noworkout')
+ expect(err.message).toBe('There is no workout to look at yet — log one first.')
+ expect(demoStatus().job).toBe(null)
+ })
+
+ it('reads the workout it was named, and the latest one when it was named nothing', () => {
+ const S = state({ workouts: [workout({ id: 'old', d: day(9) }), workout({ id: 'new', d: day(1) })] })
+ expect(think(() => demoDebrief(S, 'old')).workout.id).toBe('old')
+ expect(think(() => demoDebrief(S, 'nope')).workout.id).toBe('new')
+ expect(think(() => demoDebrief(S)).workout.id).toBe('new')
+ })
+
+ it('scores a clean session 8, a clean session with records 9, and a short one 7', () => {
+ const S = state()
+ expect(think(() => demoDebrief(S)).score).toBe(8)
+ expect(think(() => demoDebrief(state({ workouts: [workout({ prs: ['a', 'b'] })] }))).score).toBe(9)
+
+ const short = workout()
+ short.entries[0].sets[2].done = false
+ expect(think(() => demoDebrief(state({ workouts: [short] }))).score).toBe(7)
+ })
+
+ it('counts neither warm-up rows nor their volume', () => {
+ const w = workout()
+ w.entries[0].sets.unshift({ done: true, w: 20, r: 10, phase: 'warmup' })
+ const p = think(() => demoDebrief(state({ workouts: [w] })))
+ expect(p.workout.sets).toBe(3) // 4 rows logged, 3 of them work
+ expect(p.highlights[0]).toBe('Every planned set done — 3 of 3.')
+ expect(p.workout.vol).toBe(3 * 60 * 8) // the 20×10 warm-up is not in it
+ })
+
+ it('trusts a stored volume over recomputing it', () => {
+ const p = think(() => demoDebrief(state({ workouts: [workout({ vol: 1234.4 })] })))
+ expect(p.workout.vol).toBe(1234)
+ })
+
+ it('warns about the clock only past eighty minutes, and about missing effort otherwise', () => {
+ const long = workout({ start: NOW - 864e5, end: NOW - 864e5 + 81 * 60e3 })
+ expect(think(() => demoDebrief(state({ workouts: [long] }))).watch)
+ .toEqual(['81 minutes is long — rest periods may be creeping up.'])
+ expect(think(() => demoDebrief(state({ workouts: [workout()] }))).watch[0])
+ .toMatch(/^Top sets logged without an effort rating/)
+ })
+
+ it('reports no minutes at all when the workout was never clocked', () => {
+ const p = think(() => demoDebrief(state({ workouts: [workout({ start: undefined, end: undefined })] })))
+ expect(p.workout.minutes).toBe(null)
+ expect(p.watch[0]).toMatch(/^Top sets logged without an effort rating/)
+ })
+})
+
+describe('coach-demo — the cohort panel', () => {
+ it('compares your own bests against a median it derives from them', () => {
+ const c = demoCohort(state())
+ expect(c).toMatchObject({ ok: true, enabled: true, sharing: true, people: 5, minPeople: 3, unit: 'kg', rankPct: 62 })
+ const mine = c.exercises.find(e => e.id === PRESS)
+ expect(mine.you).toBeGreaterThan(0)
+ expect(mine.median).toBe(Math.round(mine.you * 0.92))
+ expect(mine.name).toBe(EXIDX[PRESS].n)
+ })
+
+ it('shows an untrained exercise as a flat 60 with no number of your own', () => {
+ expect(demoCohort(state()).exercises.find(e => e.id === SQUAT)).toEqual({
+ id: SQUAT, name: EXIDX[SQUAT].n, people: 4, median: 60, you: null
+ })
+ })
+
+ it('takes at most five distinct exercises across every routine', () => {
+ const ids = EXDB.slice(0, 8).map(e => e.id)
+ const S = state({
+ routines: [
+ { id: 'r1', name: 'A', ex: ids.slice(0, 5).map(id => ({ id, sets: 3, reps: 8 })) },
+ { id: 'r2', name: 'B', ex: [...ids.slice(0, 5), ...ids.slice(5)].map(id => ({ id, sets: 3, reps: 8 })) }
+ ]
+ })
+ const c = demoCohort(S)
+ expect(c.exercises.map(e => e.id)).toEqual(ids.slice(0, 5))
+ })
+
+ it('reports your sessions per week over the last eight weeks', () => {
+ const workouts = Array.from({ length: 8 }, (_, i) => workout({ id: 'w' + i, start: NOW - (i + 1) * 864e5 }))
+ workouts.push(workout({ id: 'ancient', d: day(400), start: NOW - 400 * 864e5 }))
+ expect(demoCohort(state({ workouts })).sessionsPerWeek).toEqual({ median: 3, you: 1 })
+ expect(demoCohort(state({ workouts: [] })).sessionsPerWeek).toEqual({ median: 3, you: 0 })
+ })
+})
+
+describe('coach-demo — the disclosure', () => {
+ it('names exactly the categories the consent screen is built from', () => {
+ expect(demoDisclosure()).toEqual({
+ provider: 'demo', providerLabel: 'the configured AI provider',
+ categories: [...DATA_CATEGORIES], version: 1
+ })
+ })
+})
+
+describe('coach-demo — defects found while writing these tests', () => {
+ // DEFECT 1 (fixed in coach-demo.js, see the report): when a routine's only rep-mode exercise
+ // sits at index 1, `first` and `second` resolved to the same entry, so the demo proposed
+ // swapping an exercise away AND changing the set count of the exercise it had just swapped
+ // away. Accepting both is what the review screen's "Apply" does by default, and the apply
+ // engine throws `missing target` on the second change — which aborts the whole change-set.
+ it('never aims two changes at the same exercise', () => {
+ const S = state({
+ routines: [
+ { id: 'r1', name: 'Core + press', ex: [{ id: PLANK, sec: 45, mode: 'time' }, { id: PRESS, sets: 3, reps: 8, mode: 'reps' }] },
+ { id: 'r2', name: 'Legs', ex: [{ id: SQUAT, sets: 4, reps: 5, mode: 'reps' }] }
+ ]
+ })
+ const p = think(() => demoReview(S))
+ const targets = p.changes.filter(c => c.target?.exId).map(c => c.target.exId)
+ expect(new Set(targets).size).toBe(targets.length)
+
+ // and the whole change-set applies cleanly, which is what the contradiction broke
+ const s = structuredClone(S)
+ expect(() => applyChangeSet(s, p, p.changes.map(c => c.id))).not.toThrow()
+ })
+
+ // DEFECT 2 (fixed in coach-demo.js, see the report): buildDebrief guards `w.entries` twice
+ // and then hands the raw workout to workoutVolume(), which does `w.entries.forEach`. A
+ // workout carrying a date but no entries threw *inside the 2.2 s timer*, where nothing
+ // catches it — `job` stayed 'running' for ever and every later request 409'd, so the demo
+ // Coach was bricked until the page was reloaded.
+ it('survives a workout that carries a date and nothing else', () => {
+ const S = state({ workouts: [{ id: 'bare', d: day(1) }] })
+ expect(() => think(() => demoDebrief(S))).not.toThrow()
+ expect(demoStatus().pending).toMatchObject({ kind: 'debrief', workout: { id: 'bare', vol: 0, sets: 0 } })
+ expect(demoStatus().job).toBe(null)
+ })
+})
diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js
index 05eaeab8c..330b71f2f 100644
--- a/frontend/src/lib/pt-br-locale.test.js
+++ b/frontend/src/lib/pt-br-locale.test.js
@@ -27,7 +27,7 @@ describe('Brazilian Portuguese locale', () => {
.sort(byCodeUnit)
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
- expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(645)
+ expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(647)
expect(inherited).toHaveLength(660)
// If this fails, review the changed keys and wording before accepting a new hash. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index dc0a877ca..04e9031e2 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -950,6 +950,8 @@ export default {
'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Jede Anfrage geht direkt mit deinem Schlüssel an {0} — niemand sonst sieht sie, und du bezahlst dafür.',
'Endpoint': 'Endpunkt',
'Enter your API key': 'Gib deinen API-Schlüssel ein',
+ 'Enter the endpoint URL': 'Gib die Endpunkt-URL ein',
+ 'There is no routine to review yet — build one with at least two exercises first.': 'Es gibt noch keine Routine zum Prüfen – lege zuerst eine mit mindestens zwei Übungen an.',
'How should the Coach run?': 'Wie soll der Coach laufen?',
'List models': 'Modelle laden',
'Model': 'Modell',
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 2393a0c16..b101bc465 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -932,6 +932,8 @@ export default {
'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Cada solicitud va directamente a {0} con tu clave: nadie más la ve, y la pagas tú.',
'Endpoint': 'Endpoint',
'Enter your API key': 'Introduce tu clave de API',
+ 'Enter the endpoint URL': 'Introduce la URL del endpoint',
+ 'There is no routine to review yet — build one with at least two exercises first.': 'Aún no hay ninguna rutina que revisar — crea primero una con al menos dos ejercicios.',
'How should the Coach run?': '¿Cómo debe funcionar el entrenador?',
'List models': 'Listar modelos',
'Model': 'Modelo',
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 15e014795..2b5a1c87d 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -932,6 +932,8 @@ export default {
'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Chaque requête part directement vers {0} avec ta clé — personne d’autre ne la voit, et c’est toi qui la paies.',
'Endpoint': 'Point d’accès',
'Enter your API key': 'Saisis ta clé API',
+ 'Enter the endpoint URL': 'Saisis l’URL du point d’accès',
+ 'There is no routine to review yet — build one with at least two exercises first.': 'Aucune routine à examiner pour l’instant — crées-en une avec au moins deux exercices d’abord.',
'How should the Coach run?': 'Comment le coach doit-il fonctionner ?',
'List models': 'Lister les modèles',
'Model': 'Modèle',
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index 95c35c135..1f6111d4e 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -932,6 +932,8 @@ export default {
'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'हर अनुरोध आपकी कुंजी के साथ सीधे {0} को जाता है — कोई और इसे नहीं देखता, और भुगतान आप करते हैं।',
'Endpoint': 'एंडपॉइंट',
'Enter your API key': 'अपनी API कुंजी दर्ज करें',
+ 'Enter the endpoint URL': 'एंडपॉइंट URL दर्ज करें',
+ 'There is no routine to review yet — build one with at least two exercises first.': 'अभी समीक्षा के लिए कोई रूटीन नहीं — पहले कम से कम दो व्यायामों वाला एक रूटीन बनाएँ।',
'How should the Coach run?': 'कोच कैसे चले?',
'List models': 'मॉडल सूची',
'Model': 'मॉडल',
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index a1cf236c0..b9fdbb0fa 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -996,6 +996,8 @@ export default {
'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Minden kérés közvetlenül ide megy a kulcsoddal: {0} — más nem látja, és te fizeted.',
'Endpoint': 'Végpont',
'Enter your API key': 'Add meg az API-kulcsodat',
+ 'Enter the endpoint URL': 'Add meg a végpont URL-jét',
+ 'There is no routine to review yet — build one with at least two exercises first.': 'Még nincs átnézhető rutin — előbb hozz létre egyet legalább két gyakorlattal.',
'How should the Coach run?': 'Hogyan fusson az Edző?',
'List models': 'Modellek listázása',
'Model': 'Modell',
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 89d904785..ce8fbd2a7 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -932,6 +932,8 @@ export default {
'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Ogni richiesta va direttamente a {0} con la tua chiave: nessun altro la vede, e la paghi tu.',
'Endpoint': 'Endpoint',
'Enter your API key': 'Inserisci la tua chiave API',
+ 'Enter the endpoint URL': 'Inserisci l’URL dell’endpoint',
+ 'There is no routine to review yet — build one with at least two exercises first.': 'Non c’è ancora nessuna routine da rivedere — creane prima una con almeno due esercizi.',
'How should the Coach run?': 'Come deve funzionare il Coach?',
'List models': 'Elenca i modelli',
'Model': 'Modello',
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index f36bbe008..c5effff5c 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -932,6 +932,8 @@ export default {
'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': '모든 요청은 당신의 키로 {0}에 바로 전송됩니다 — 다른 누구도 볼 수 없고, 비용은 당신이 냅니다.',
'Endpoint': '엔드포인트',
'Enter your API key': 'API 키를 입력하세요',
+ 'Enter the endpoint URL': '엔드포인트 URL을 입력하세요',
+ 'There is no routine to review yet — build one with at least two exercises first.': '아직 검토할 루틴이 없어요 — 먼저 운동이 두 개 이상인 루틴을 만드세요.',
'How should the Coach run?': '코치를 어떻게 실행할까요?',
'List models': '모델 목록',
'Model': '모델',
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 529d5ab92..50abbc63b 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -932,6 +932,8 @@ export default {
'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Każde zapytanie trafia prosto do {0} z Twoim kluczem — nikt inny go nie widzi, a płacisz Ty.',
'Endpoint': 'Endpoint',
'Enter your API key': 'Wpisz swój klucz API',
+ 'Enter the endpoint URL': 'Wpisz adres URL endpointu',
+ 'There is no routine to review yet — build one with at least two exercises first.': 'Nie ma jeszcze planu treningowego do przejrzenia — najpierw utwórz taki z co najmniej dwoma ćwiczeniami.',
'How should the Coach run?': 'Jak ma działać trener?',
'List models': 'Pokaż modele',
'Model': 'Model',
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 087c69641..1cceeec25 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -635,6 +635,8 @@ export const PT_BR_OVERRIDES = {
'Scan': 'Escanear',
'e.g. FitZone downtown': 'ex. FitZone centro',
'Gym card': 'Cartão da academia',
+ 'Enter the endpoint URL': 'Digite a URL do endpoint',
+ 'There is no routine to review yet — build one with at least two exercises first.': 'Ainda não há nenhuma rotina para revisar — crie primeiro uma com pelo menos dois exercícios.',
'Re-scan': 'Escanear de novo',
'Scan it with the camera or import a photo.': 'Escaneie com a câmera ou importe uma foto.',
'Import a photo of your membership card or scan it with the camera. No extra app needed at the gym — just open this screen.': 'Importe uma foto do seu cartão de sócio ou escaneie com a câmera. Não é preciso outro app na academia — é só abrir esta tela.',
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index d07541e8d..7ee12ed2c 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -932,6 +932,8 @@ export default {
'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Cada pedido vai diretamente para {0} com a tua chave — mais ninguém o vê, e és tu que pagas.',
'Endpoint': 'Endpoint',
'Enter your API key': 'Introduz a tua chave de API',
+ 'Enter the endpoint URL': 'Introduz o URL do endpoint',
+ 'There is no routine to review yet — build one with at least two exercises first.': 'Ainda não há nenhuma rotina para rever — cria primeiro uma com pelo menos dois exercícios.',
'How should the Coach run?': 'Como deve correr o Treinador?',
'List models': 'Listar modelos',
'Model': 'Modelo',
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index accc919de..dacad5075 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -932,6 +932,8 @@ export default {
'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Каждый запрос уходит напрямую в {0} с вашим ключом — больше никто его не видит, и платите за него вы.',
'Endpoint': 'Эндпоинт',
'Enter your API key': 'Введите API-ключ',
+ 'Enter the endpoint URL': 'Введите URL эндпоинта',
+ 'There is no routine to review yet — build one with at least two exercises first.': 'Пока нет программы для разбора — сначала создай одну хотя бы с двумя упражнениями.',
'How should the Coach run?': 'Как должен работать тренер?',
'List models': 'Показать модели',
'Model': 'Модель',
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index e8fdc2ff5..958bdc9d5 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -1004,6 +1004,8 @@ export default {
'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'ทุกคำขอส่งตรงไปยัง {0} ด้วยคีย์ของคุณ — ไม่มีใครเห็น และคุณเป็นผู้จ่าย',
'Endpoint': 'ปลายทาง',
'Enter your API key': 'ป้อนคีย์ API ของคุณ',
+ 'Enter the endpoint URL': 'ป้อน URL ปลายทาง',
+ 'There is no routine to review yet — build one with at least two exercises first.': 'ยังไม่มีรูทีนให้ตรวจ — สร้างรูทีนที่มีอย่างน้อยสองท่าก่อน',
'How should the Coach run?': 'ให้โค้ชทำงานอย่างไร',
'List models': 'แสดงรายการโมเดล',
'Model': 'โมเดล',
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index 82f934fed..d147a5209 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -932,6 +932,8 @@ export default {
'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Her istek anahtarınla doğrudan {0} adresine gider — başka kimse görmez ve ücretini sen ödersin.',
'Endpoint': 'Uç nokta',
'Enter your API key': 'API anahtarını gir',
+ 'Enter the endpoint URL': 'Uç nokta URL’sini gir',
+ 'There is no routine to review yet — build one with at least two exercises first.': 'İncelenecek rutin yok — önce en az iki hareketi olan bir rutin oluştur.',
'How should the Coach run?': 'Koç nasıl çalışsın?',
'List models': 'Modelleri listele',
'Model': 'Model',
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 7f4492b44..1068d9a5c 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -932,6 +932,8 @@ export default {
'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': '每个请求都会用你的密钥直接发送到 {0}——其他人看不到,费用由你承担。',
'Endpoint': '端点',
'Enter your API key': '请输入你的 API 密钥',
+ 'Enter the endpoint URL': '请输入端点 URL',
+ 'There is no routine to review yet — build one with at least two exercises first.': '还没有可点评的训练计划——先创建一个至少包含两个动作的计划。',
'How should the Coach run?': '教练应如何运行?',
'List models': '列出模型',
'Model': '模型',
diff --git a/frontend/src/views/CoachChat.demo-failure.test.jsx b/frontend/src/views/CoachChat.demo-failure.test.jsx
new file mode 100644
index 000000000..02ca5121d
--- /dev/null
+++ b/frontend/src/views/CoachChat.demo-failure.test.jsx
@@ -0,0 +1,120 @@
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { parseHTML } from 'linkedom'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import CoachChat from './CoachChat.jsx'
+
+// The demo Coach's failure state, end to end. Every other CoachChat test mocks lib/coach-api.js;
+// this one runs the real thing with DEMO forced on, so the chain under test is exactly what the
+// GitHub Pages build ships: a builder throws inside lib/coach-demo.js's timer → demoStatus()
+// reports `lastError` → useCoachStatus hands it over on the next poll → the job-ended effect
+// writes an error line into the thread, and the next request is taken rather than 409'd.
+// Before the catch in coach-demo.js the job stayed 'running' for ever and the demo Coach was
+// bricked until the page was reloaded.
+const mocks = vi.hoisted(() => {
+ const state = { S: null, nav: vi.fn(), toast: vi.fn(), openSheet: vi.fn() }
+ state.storeSnapshot = () => ({
+ S: state.S, user: { id: 'u1' }, ready: true,
+ config: { coach: { enabled: true } }, coachLocal: null,
+ update: mut => mut(state.S),
+ })
+ state.uiSnapshot = () => ({ toast: state.toast, openSheet: state.openSheet })
+ return state
+})
+
+vi.mock('../store/useStore.js', () => {
+ const useStore = selector => selector(mocks.storeSnapshot())
+ useStore.getState = mocks.storeSnapshot // coach-api.js reads S() from here in demo mode
+ return { useStore }
+})
+vi.mock('../store/useUI.js', () => {
+ const useUI = selector => (selector ? selector(mocks.uiSnapshot()) : mocks.uiSnapshot())
+ useUI.getState = mocks.uiSnapshot
+ return { useUI }
+})
+vi.mock('react-router-dom', () => ({ useNavigate: () => mocks.nav }))
+vi.mock('../lib/demo.js', () => ({ DEMO: true, DEMO_SEEDED: 'gym_demo_seeded_v1', REPO: '' }))
+vi.mock('../sheets.jsx', () => ({ startFlow: vi.fn(), confirmSheet: vi.fn() }))
+vi.mock('../lib/api.js', () => ({
+ api: vi.fn(() => Promise.resolve({})), IS_APPLE: false, IS_ANDROID: false, BIO: 'biometrics',
+}))
+vi.mock('../coach.css', () => ({}))
+
+const DELAY = 2200 // coach-demo.js's thinking time
+const POLL_MS = 3000 // coach-api.js's cadence while a job is in flight
+
+let dom, root, container
+
+function installDom() {
+ const parsed = parseHTML('<!doctype html><html><body><div id="root"></div></body></html>')
+ dom = parsed.window
+ globalThis.window = dom
+ globalThis.document = dom.document
+ Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })
+ for (const key of ['HTMLElement', 'Node', 'Element', 'Event', 'Blob']) globalThis[key] = dom[key]
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ container = document.getElementById('root')
+ root = createRoot(container)
+}
+
+const chip = re => [...container.querySelectorAll('.qchip')].find(b => re.test(b.textContent || ''))
+async function click(el) {
+ expect(el).toBeTruthy()
+ await act(async () => { el.dispatchEvent(new dom.Event('click', { bubbles: true })); await flush() })
+}
+// Microtasks only: the dynamic import of coach-demo.js and the status refresh both settle here.
+const flush = async () => { for (let i = 0; i < 20; i++) await Promise.resolve() }
+const settle = async () => { await act(async () => { await flush() }) }
+const elapse = async ms => { await act(async () => { await vi.advanceTimersByTimeAsync(ms); await flush() }) }
+
+// A workout the chat can list (it reads `d` and `name` only) but the debrief builder cannot
+// read: `entries` throws the moment buildDebrief touches it, inside the demo's timer.
+const brokenWorkout = () => ({ id: 'w1', name: 'Push Day', d: '2026-09-01', get entries() { throw new Error('boom') } })
+const state = () => ({
+ unit: 'kg', lang: 'en', customEx: [], workouts: [brokenWorkout()], bodyweight: [], exWeights: {},
+ dayPlan: {}, routines: [], week: {},
+ coach: {
+ consent: { agreedAt: '2026-07-01T00:00:00Z', version: 1 },
+ profile: { goal: 'muscle', experience: 'new', daysPerWeek: 3, sessionMin: 60, preferredDays: [1, 3, 5], equipment: [] },
+ log: [], snapshots: [], chat: [{ id: 'c1', role: 'user', kind: 'intake', at: 1 }], timings: []
+ },
+})
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ // Only what the demo and the poll use. Module loading and React's scheduler stay on real clocks.
+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'Date'] })
+})
+afterEach(async () => {
+ if (root) { await act(async () => { root.unmount() }); root = null }
+ container = null; dom = null
+ vi.useRealTimers()
+})
+
+describe('the demo Coach failing inside its timer', () => {
+ it('ends as an error line in the thread, and the next request is taken', async () => {
+ mocks.S = state()
+ installDom()
+ await act(async () => { root.render(React.createElement(CoachChat)) })
+ await settle()
+
+ await click(chip(/Last workout/))
+ expect(mocks.toast).not.toHaveBeenCalled() // the request was accepted
+ expect(mocks.S.coach.chat.at(-1)).toMatchObject({ role: 'user', kind: 'text', text: 'How did my Push Day session go?' })
+ const lines = mocks.S.coach.chat.length
+
+ await elapse(DELAY) // the builder throws in here
+ await elapse(POLL_MS) // the poll sees the job gone
+ expect(mocks.S.coach.chat).toHaveLength(lines + 1)
+ expect(mocks.S.coach.chat.at(-1)).toMatchObject({
+ role: 'coach', kind: 'error', text: 'The Coach couldn’t read your training data.'
+ })
+ expect(mocks.S.coach.timings).toHaveLength(1) // the effect ran once, as for a real job
+
+ // Not bricked: a second ask goes through instead of "already thinking".
+ await click(chip(/Last workout/))
+ expect(mocks.toast).not.toHaveBeenCalled()
+ expect(mocks.S.coach.chat.at(-1)).toMatchObject({ role: 'user', kind: 'text' })
+ await elapse(DELAY); await elapse(POLL_MS) // drain it, so nothing is left running
+ })
+})
diff --git a/frontend/src/views/CoachIntake.jsx b/frontend/src/views/CoachIntake.jsx
index 6e33ed7cc..93a3a74fe 100644
--- a/frontend/src/views/CoachIntake.jsx
+++ b/frontend/src/views/CoachIntake.jsx
@@ -85,13 +85,17 @@ export default function CoachIntake() {
}
const finish = async () => {
- const profile = { ...p, daysPerWeek: Math.min(7, Math.max(1, p.daysPerWeek || 3)) }
+ // `??`, not `||`: only a missing answer takes the default. Nought is an answer, and the clamp
+ // turns it into one day like every other count below the floor.
+ const profile = { ...p, daysPerWeek: Math.min(7, Math.max(1, p.daysPerWeek ?? 3)) }
update(s => {
const c = (s.coach = s.coach || emptyCoach())
c.profile = profile
// The conversation opens with the answers — rendered from the profile, so an edit later
- // is reflected rather than duplicated.
- if (!editing || !(c.chat || []).some(m => m.kind === 'intake')) appendChat(s, { role: 'user', kind: 'intake' })
+ // is reflected rather than duplicated. One intake line whoever is writing it: a first-timer
+ // whose plan request failed presses the button again, and must not open the thread with
+ // the questionnaire twice.
+ if (!(c.chat || []).some(m => m.kind === 'intake')) appendChat(s, { role: 'user', kind: 'intake' })
})
if (editing) { toast(t('Saved')); nav('/coach'); return }
setBusy(true)
diff --git a/frontend/src/views/CoachIntake.test.jsx b/frontend/src/views/CoachIntake.test.jsx
new file mode 100644
index 000000000..9cdf5aefa
--- /dev/null
+++ b/frontend/src/views/CoachIntake.test.jsx
@@ -0,0 +1,453 @@
+// @vitest-environment happy-dom
+// The intake questionnaire: the eight-screen state machine the Coach opens with, and the same
+// eight screens again as the profile editor behind `?edit=1`.
+//
+// What is worth pinning here is not that the screens render — it is the order they run in, the
+// two answers that gate Continue, what reaches the store when the last button is pressed, and
+// the two paths that are awkward to reach by hand: a plan request that fails after the answers
+// are already saved, and the editor's rule about not opening a second conversation.
+//
+// coach.js is deliberately NOT mocked: `hasConsent`, `emptyCoach`, `appendChat` and
+// `coachAvailable` are the contract this screen is written against, so the tests run the real
+// ones. MOBILE and DEMO are both false in a test build, which is the web gate.
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import CoachIntake from './CoachIntake.jsx'
+import { requestPlan, disclosure } from '../lib/coach-api.js'
+import { CONSENT_VERSION } from '../lib/coach.js'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+
+const mocks = vi.hoisted(() => {
+ const state = { S: null, user: null, config: null, search: '', nav: vi.fn(), toast: vi.fn() }
+ state.snapshot = () => ({
+ S: state.S,
+ user: state.user,
+ config: state.config,
+ coachLocal: null,
+ update: mut => mut(state.S),
+ })
+ return state
+})
+vi.mock('../store/useStore.js', () => {
+ const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()
+ useStore.getState = mocks.snapshot
+ return { useStore }
+})
+vi.mock('../store/useUI.js', () => {
+ const snap = () => ({ toast: (...a) => mocks.toast(...a), openSheet: vi.fn() })
+ const useUI = selector => selector ? selector(snap()) : snap()
+ useUI.getState = snap
+ return { useUI }
+})
+vi.mock('react-router-dom', () => ({
+ useNavigate: () => mocks.nav,
+ useSearchParams: () => [new URLSearchParams(mocks.search), vi.fn()],
+}))
+vi.mock('../lib/coach-api.js', () => ({
+ requestPlan: vi.fn(() => Promise.resolve({})),
+ disclosure: vi.fn(() => Promise.resolve(null)),
+}))
+vi.mock('../coach.css', () => ({}))
+
+let host, root
+const fresh = () => ({
+ unit: 'kg', lang: 'en', customEx: [], workouts: [], bodyweight: [], exWeights: {},
+ dayPlan: {}, routines: [], week: {},
+})
+
+beforeEach(() => {
+ mocks.S = fresh()
+ mocks.user = { uid: 'u1', name: 'Ana' }
+ mocks.config = { coach: { enabled: true } }
+ mocks.search = ''
+ mocks.nav.mockReset(); mocks.toast.mockReset()
+ vi.mocked(requestPlan).mockReset().mockResolvedValue({})
+ vi.mocked(disclosure).mockReset().mockResolvedValue(null)
+ host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
+})
+afterEach(() => { act(() => root.unmount()); host.remove() })
+
+const mount = () => act(() => root.render(<CoachIntake />))
+const settle = async () => { await act(async () => { await Promise.resolve(); await Promise.resolve() }) }
+
+const eyebrow = () => host.querySelector('.ob-eyebrow')?.textContent
+const all = sel => [...host.querySelectorAll(sel)]
+const find = (sel, text) => all(sel).find(el => el.textContent.trim().startsWith(text))
+const tap = (sel, text) => {
+ const el = find(sel, text)
+ expect(el, `no ${sel} starting with "${text}"`).toBeTruthy()
+ act(() => el.click())
+}
+const footBtn = () => host.querySelector('.ob-foot .btn')
+const cont = () => act(() => footBtn().click())
+// A <select> is driven the same way an <input> is: React tracks the value through the
+// prototype setter, so a bare el.value never reaches onChange.
+const pick = (el, value) => act(() => {
+ Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, String(value))
+ el.dispatchEvent(new Event('change', { bubbles: true }))
+})
+const typeIn = (el, value) => act(() => {
+ Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)
+ el.dispatchEvent(new Event('input', { bubbles: true }))
+})
+
+// Walk the flow to a named screen, answering only what Continue is actually waiting for — so
+// a test that already made its own choice keeps it.
+const walkTo = target => {
+ for (let i = 0; i < 12 && eyebrow() !== target; i++) {
+ if (eyebrow() === 'Before we start') { tap('button', 'I understand'); continue }
+ if (footBtn().disabled) {
+ if (eyebrow() === 'Your goal') tap('.ob-choice', 'Build muscle')
+ else if (eyebrow() === 'Experience') tap('.ob-choice', 'Training regularly')
+ }
+ cont()
+ }
+ expect(eyebrow()).toBe(target)
+}
+
+describe('CoachIntake — who gets in', () => {
+ it('sends you home and renders nothing when the Coach is not available', () => {
+ mocks.config = { coach: { enabled: false } }
+ mount()
+ expect(mocks.nav).toHaveBeenCalledWith('/home', { replace: true })
+ expect(host.textContent).toBe('')
+ })
+
+ it('needs a signed-in user as well as a server with the Coach on', () => {
+ mocks.user = null
+ mount()
+ expect(mocks.nav).toHaveBeenCalledWith('/home', { replace: true })
+ })
+})
+
+describe('CoachIntake — the consent screen', () => {
+ it('is the first screen on a fresh profile, and is not one of the progress dots', () => {
+ mount()
+ expect(eyebrow()).toBe('Before we start')
+ expect(all('.ob-dot')).toHaveLength(0)
+ expect(host.querySelector('.ob-foot .btn').textContent).toContain('I understand')
+ })
+
+ it('agreeing records the version the app checks for, and opens the first question', () => {
+ mount()
+ tap('button', 'I understand')
+ expect(mocks.S.coach.consent.version).toBe(CONSENT_VERSION)
+ expect(Date.parse(mocks.S.coach.consent.agreedAt)).not.toBeNaN()
+ expect(mocks.S.coach.profile).toBe(null) // nothing else written yet
+ expect(eyebrow()).toBe('Your goal')
+ expect(all('.ob-dot')).toHaveLength(7)
+ })
+
+ it('"Not now" writes nothing at all and goes back to the plan', () => {
+ mount()
+ tap('button', 'Not now')
+ expect(mocks.S.coach).toBeUndefined()
+ expect(mocks.nav).toHaveBeenCalledWith('/plan')
+ })
+
+ it('lists the built-in categories first, then whatever the server says actually goes', async () => {
+ vi.mocked(disclosure).mockResolvedValue({ categories: ['plan', 'prefs'], providerLabel: 'Anthropic', payer: 'you', host: 'api.anthropic.com' })
+ mount()
+ expect(all('.ob-consent-row')).toHaveLength(5) // CATEGORY_TEXT, before the call lands
+ await settle()
+ expect(all('.ob-consent-row')).toHaveLength(2)
+ expect(host.textContent).toContain('Sent straight to api.anthropic.com with your own API key')
+ })
+
+ it('names the instance owner as the payer when the server is the one calling', async () => {
+ vi.mocked(disclosure).mockResolvedValue({ categories: ['plan'], providerLabel: 'Anthropic', payer: 'instance' })
+ mount(); await settle()
+ expect(host.textContent).toContain('Sent to Anthropic, running on this server under the instance owner')
+ })
+
+ it('names the provider when the phone pays but there is no host to name', async () => {
+ vi.mocked(disclosure).mockResolvedValue({ categories: ['plan'], providerLabel: 'Anthropic API', payer: 'you' })
+ mount(); await settle()
+ expect(host.textContent).toContain('Sent straight to Anthropic API with your own API key')
+ })
+
+ it('falls back to the server’s own label, then to a generic one, when the call fails', async () => {
+ vi.mocked(disclosure).mockRejectedValue(new Error('offline'))
+ mocks.config = { coach: { enabled: true, providerLabel: 'Claude Agent SDK' } }
+ mount(); await settle()
+ expect(host.textContent).toContain('Sent to Claude Agent SDK, running on this server')
+ expect(all('.ob-consent-row')).toHaveLength(5) // and the built-in list stands in
+
+ act(() => root.unmount())
+ mocks.config = { coach: { enabled: true } }
+ root = createRoot(host)
+ mount(); await settle()
+ expect(host.textContent).toContain('Sent to the configured AI provider, running on this server')
+ })
+
+ it('shows a category the app has no copy for under its own key', async () => {
+ vi.mocked(disclosure).mockResolvedValue({ categories: ['plan', 'sleep'], providerLabel: 'x', payer: 'instance' })
+ mount(); await settle()
+ expect(all('.ob-consent-row').map(r => r.querySelector('b').textContent)).toEqual(['Your plan', 'sleep'])
+ })
+
+ it('is skipped entirely once consent is on file', () => {
+ mocks.S.coach = { consent: { agreedAt: '2026-09-01T00:00:00Z', version: CONSENT_VERSION }, profile: null, chat: [] }
+ mount()
+ expect(eyebrow()).toBe('Your goal')
+ })
+})
+
+describe('CoachIntake — the two answers that gate the flow', () => {
+ it('will not leave the goal screen until one is picked', () => {
+ mount(); tap('button', 'I understand')
+ expect(footBtn().disabled).toBe(true)
+ expect(host.querySelector('.ob-hint').textContent).toBe('Pick one to continue.')
+ cont()
+ expect(eyebrow()).toBe('Your goal')
+
+ tap('.ob-choice', 'Lose fat')
+ expect(footBtn().disabled).toBe(false)
+ expect(host.querySelector('.ob-hint')).toBe(null)
+ cont()
+ expect(eyebrow()).toBe('Experience')
+ })
+
+ it('will not leave the experience screen until one is picked', () => {
+ mount(); walkTo('Experience')
+ expect(footBtn().disabled).toBe(true)
+ cont()
+ expect(eyebrow()).toBe('Experience')
+ tap('.ob-choice', 'New to lifting')
+ cont()
+ expect(eyebrow()).toBe('Schedule')
+ })
+
+ it('refuses a session shorter than ten minutes', () => {
+ mount(); walkTo('Session length')
+ const [hours, minutes] = all('.ob-wheel')
+ expect(footBtn().disabled).toBe(false)
+
+ // 00:00 is not a session, so the screen snaps it to five minutes — and five is still refused.
+ pick(hours, 0)
+ expect(footBtn().disabled).toBe(true)
+ expect(minutes.value).toBe('5')
+
+ pick(minutes, 0) // both wheels at nought snaps back to five, not zero
+ expect(minutes.value).toBe('5')
+ expect(footBtn().disabled).toBe(true)
+
+ pick(minutes, 15)
+ expect(footBtn().disabled).toBe(false)
+ cont()
+ expect(eyebrow()).toBe('Equipment')
+ })
+})
+
+describe('CoachIntake — moving around', () => {
+ it('Back walks the steps and then leaves for the plan', () => {
+ mount(); walkTo('Schedule')
+ act(() => host.querySelector('.iconbtn').click())
+ expect(eyebrow()).toBe('Experience')
+ act(() => host.querySelector('.iconbtn').click())
+ expect(eyebrow()).toBe('Your goal')
+ act(() => host.querySelector('.iconbtn').click())
+ expect(eyebrow()).toBe('Before we start')
+ act(() => host.querySelector('.iconbtn').click())
+ expect(mocks.nav).toHaveBeenCalledWith('/plan')
+ })
+
+ it('Back from the first screen of the editor goes to the conversation, not the plan', () => {
+ mocks.search = 'edit=1'
+ mount()
+ expect(eyebrow()).toBe('Your goal')
+ act(() => host.querySelector('.iconbtn').click())
+ expect(mocks.nav).toHaveBeenCalledWith('/coach')
+ })
+
+ it('Skip is offered only on the three optional screens, and never on the last one', () => {
+ mount(); walkTo('Your goal')
+ expect(host.querySelector('.ob-skip')).toBe(null)
+ walkTo('Equipment')
+ expect(host.querySelector('.ob-skip')).toBeTruthy()
+ act(() => host.querySelector('.ob-skip').click())
+ expect(eyebrow()).toBe('Limits')
+ expect(host.querySelector('.ob-skip')).toBeTruthy()
+ act(() => host.querySelector('.ob-skip').click())
+ expect(eyebrow()).toBe('Almost there')
+ expect(host.querySelector('.ob-skip')).toBe(null)
+ expect(footBtn().textContent).toContain('Build my plan')
+ })
+
+ it('the dots count the seven questions and follow the one on screen', () => {
+ mount(); walkTo('Your goal')
+ const at = () => all('.ob-dot').findIndex(d => d.classList.contains('on'))
+ expect(all('.ob-dot')).toHaveLength(7)
+ expect(at()).toBe(0)
+ walkTo('Schedule')
+ expect(at()).toBe(2)
+ expect(all('.ob-dot').filter(d => d.classList.contains('done'))).toHaveLength(2)
+ })
+})
+
+describe('CoachIntake — the answers themselves', () => {
+ it('preferred days toggle off and back on, and stay in weekday order', () => {
+ mount(); walkTo('Schedule')
+ const wd = () => all('.ob-wd').filter(b => b.classList.contains('on')).map(b => b.textContent)
+ expect(wd()).toEqual(['Mo', 'We', 'Fr'])
+ tap('.ob-wd', 'We')
+ expect(wd()).toEqual(['Mo', 'Fr'])
+ tap('.ob-wd', 'Su') // Sunday is 0 and is rendered last
+ expect(wd()).toEqual(['Mo', 'Fr', 'Su'])
+ tap('.ob-day', '5')
+ walkTo('Almost there')
+ cont()
+ expect(mocks.S.coach.profile).toMatchObject({ daysPerWeek: 5, preferredDays: [0, 1, 5] })
+ })
+
+ it('equipment chips toggle and reach the profile', () => {
+ mount(); walkTo('Equipment')
+ const chips = all('.ob-chips .chip')
+ expect(chips.length).toBeGreaterThan(2)
+ act(() => chips[0].click()); act(() => chips[2].click()); act(() => chips[0].click())
+ walkTo('Almost there'); cont()
+ expect(mocks.S.coach.profile.equipment).toEqual([chips[2].textContent])
+ })
+
+ it('the quick length chips and the two wheels write the same field', () => {
+ mount(); walkTo('Session length')
+ tap('.ob-quick .chip', '90')
+ const [hours, minutes] = all('.ob-wheel')
+ expect(hours.value).toBe('1')
+ expect(minutes.value).toBe('30')
+ pick(hours, 2)
+ expect(host.querySelector('.ob-quick .chip.on')).toBe(null)
+ walkTo('Almost there'); cont()
+ expect(mocks.S.coach.profile.sessionMin).toBe(150)
+ })
+
+ it('the free-text screens land in the profile as typed', () => {
+ mount(); walkTo('Limits')
+ typeIn(host.querySelector('.ob-field textarea'), 'dodgy left shoulder')
+ cont()
+ const [likes, dislikes, notes] = all('.ob-field textarea')
+ typeIn(likes, 'deadlifts'); typeIn(dislikes, 'lunges'); typeIn(notes, 'arms by spring')
+ cont()
+ expect(mocks.S.coach.profile).toMatchObject({
+ limitations: 'dodgy left shoulder', likes: 'deadlifts', dislikes: 'lunges', notes: 'arms by spring'
+ })
+ })
+})
+
+describe('CoachIntake — building the plan', () => {
+ it('saves the answers, opens the thread with one intake line, and asks for a plan', async () => {
+ mount(); walkTo('Almost there')
+ let resolve
+ vi.mocked(requestPlan).mockReturnValue(new Promise(r => { resolve = r }))
+ cont()
+
+ expect(requestPlan).toHaveBeenCalledTimes(1)
+ const sent = vi.mocked(requestPlan).mock.calls[0][0]
+ expect(sent).toMatchObject({ goal: 'muscle', experience: 'regular', daysPerWeek: 3, sessionMin: 60 })
+ expect(mocks.S.coach.profile).toEqual(sent)
+ expect(mocks.S.coach.chat).toHaveLength(1)
+ expect(mocks.S.coach.chat[0]).toMatchObject({ role: 'user', kind: 'intake' })
+ expect(footBtn().disabled).toBe(true) // no second request while one is in flight
+ expect(mocks.nav).not.toHaveBeenCalled()
+
+ await act(async () => { resolve({}); await Promise.resolve() })
+ expect(mocks.nav).toHaveBeenCalledWith('/coach', { replace: true })
+ })
+
+ it('a failed request keeps the answers, says why, and lets you press it again without a second intake line', async () => {
+ vi.mocked(requestPlan).mockRejectedValueOnce(new Error('The Coach is already thinking about your training.'))
+ mount(); walkTo('Almost there')
+ cont(); await settle()
+
+ expect(mocks.toast).toHaveBeenCalledWith('The Coach is already thinking about your training.')
+ expect(mocks.nav).not.toHaveBeenCalled()
+ expect(mocks.S.coach.profile.goal).toBe('muscle') // the answers are already saved
+ expect(footBtn().disabled).toBe(false)
+
+ cont(); await settle()
+ expect(requestPlan).toHaveBeenCalledTimes(2)
+ // One intake line however many times the button is pressed. The rule in finish() used to
+ // be guarded by `editing`, so a first-time retry opened the thread with the questionnaire twice.
+ expect(mocks.S.coach.chat).toHaveLength(1)
+ expect(mocks.S.coach.chat[0]).toMatchObject({ role: 'user', kind: 'intake' })
+ })
+
+ it('falls back to a generic message when the failure carries none', async () => {
+ vi.mocked(requestPlan).mockRejectedValueOnce(new Error())
+ mount(); walkTo('Almost there')
+ cont(); await settle()
+ expect(mocks.toast).toHaveBeenCalledWith('Could not ask the Coach')
+ })
+
+ // The screen itself only offers 1–7, but a profile carried in from an import, an older
+ // build or another device can hold anything, and the editor saves it straight back.
+ const savingDayCount = n => {
+ mocks.search = 'edit=1'
+ mocks.S.coach = { consent: null, chat: [{ id: 'c1', role: 'user', kind: 'intake' }],
+ profile: { goal: 'strength', experience: 'new', daysPerWeek: n, preferredDays: [1], sessionMin: 60, equipment: [] } }
+ mount(); walkTo('Almost there'); cont()
+ return mocks.S.coach.profile.daysPerWeek
+ }
+ it('clamps a prefilled day count down to the seven a week can hold', () => expect(savingDayCount(99)).toBe(7))
+ it('clamps a negative day count up to one', () => expect(savingDayCount(-2)).toBe(1))
+ // Nought is an answer, not a missing one: it goes through the clamp like -2 does. It used to
+ // fall through `|| 3` and save as three while -1 saved as one.
+ it('clamps a zero day count up to one, like any other count below the floor', () => expect(savingDayCount(0)).toBe(1))
+ it('reads a missing day count as "not answered" and saves the default three', () => expect(savingDayCount(null)).toBe(3))
+})
+
+describe('CoachIntake — the editor behind ?edit=1', () => {
+ const editing = (profile, chat = [{ id: 'c1', role: 'user', kind: 'intake', at: 1 }]) => {
+ mocks.search = 'edit=1'
+ mocks.S.coach = { consent: { agreedAt: '2026-09-01T00:00:00Z', version: CONSENT_VERSION }, profile, chat }
+ }
+ const PROFILE = {
+ goal: 'strength', experience: 'returning', daysPerWeek: 4, preferredDays: [2, 4],
+ sessionMin: 45, equipment: ['barbell'], limitations: 'bad knee', likes: 'x', dislikes: 'y', notes: 'z'
+ }
+
+ it('skips consent, prefills every answer, and ends on Save', () => {
+ editing(PROFILE)
+ mount()
+ expect(eyebrow()).toBe('Your goal')
+ expect(host.querySelector('.ob-choice.on').textContent).toContain('Get stronger')
+ walkTo('Experience')
+ expect(host.querySelector('.ob-choice.on').textContent).toContain('Coming back after a break')
+ walkTo('Schedule')
+ expect(all('.ob-day').find(b => b.classList.contains('on')).textContent).toBe('4')
+ expect(all('.ob-wd').filter(b => b.classList.contains('on')).map(b => b.textContent)).toEqual(['Tu', 'Th'])
+ walkTo('Limits')
+ expect(host.querySelector('.ob-field textarea').value).toBe('bad knee')
+ walkTo('Almost there')
+ expect(footBtn().textContent).toContain('Save')
+ })
+
+ it('skips consent even when none was ever given — the editor is not a second opt-in', () => {
+ editing(PROFILE, [])
+ mocks.S.coach.consent = null
+ mount()
+ expect(eyebrow()).toBe('Your goal')
+ })
+
+ it('saves without asking for a plan, and never opens a second conversation', () => {
+ editing(PROFILE)
+ mount(); walkTo('Your goal')
+ tap('.ob-choice', 'Endurance')
+ walkTo('Almost there'); cont()
+
+ expect(requestPlan).not.toHaveBeenCalled()
+ expect(mocks.toast).toHaveBeenCalledWith('Saved')
+ expect(mocks.nav).toHaveBeenCalledWith('/coach')
+ expect(mocks.nav).not.toHaveBeenCalledWith('/coach', { replace: true })
+ expect(mocks.S.coach.profile.goal).toBe('endurance')
+ expect(mocks.S.coach.chat).toHaveLength(1)
+ })
+
+ it('still opens the thread when an edit is the first thing that ever happened', () => {
+ editing(PROFILE, [{ id: 'c9', role: 'coach', kind: 'text', text: 'hi', at: 1 }])
+ mount(); walkTo('Almost there'); cont()
+ expect(mocks.S.coach.chat.map(m => m.kind)).toEqual(['text', 'intake'])
+ })
+})
diff --git a/frontend/src/views/CoachSetup.flow.test.jsx b/frontend/src/views/CoachSetup.flow.test.jsx
new file mode 100644
index 000000000..a4720851d
--- /dev/null
+++ b/frontend/src/views/CoachSetup.flow.test.jsx
@@ -0,0 +1,455 @@
+// @vitest-environment happy-dom
+// The mobile build's "how should the Coach run?" screen. CoachSetup.test.jsx already pins the
+// promise about what this file may import; this one drives what it does.
+//
+// Two answers, and everything hard about them lives in the refusals: a server with no Coach on
+// it, a phone with no key, a base URL that is not one, an endpoint that does not answer, and
+// the two failures on "Save" that issue #42 was about — the settings write and the secure-store
+// write, which the screen deliberately does in that order.
+//
+// coach-local.js is mocked here only so the DYNAMIC import inside prepare()/turnOff() resolves
+// without a network stack. providers.js, categories.js and coach.js are the real ones, so the
+// provider table, the validator and the category copy are exactly what ships.
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import CoachSetup from './CoachSetup.jsx'
+import { getApiKey, setApiKey, clearApiKey } from '../lib/coach-secrets.js'
+import { localModels, localForget } from '../lib/coach-local.js'
+import { CATEGORY_TEXT } from '../lib/coach.js'
+import { HTTP_PROVIDERS } from '../../../api/coach/core/providers.js'
+import { DATA_CATEGORIES } from '../../../api/coach/core/categories.js'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+
+const mocks = vi.hoisted(() => {
+ const state = {
+ mobile: true, user: null, config: null, coachLocal: null,
+ nav: vi.fn(), toast: vi.fn(), openSheet: vi.fn(), setCoachLocal: vi.fn(), refreshConfig: vi.fn(),
+ }
+ state.snapshot = () => ({
+ user: state.user, config: state.config, coachLocal: state.coachLocal,
+ setCoachLocal: (...a) => state.setCoachLocal(...a),
+ refreshConfig: (...a) => state.refreshConfig(...a),
+ })
+ return state
+})
+vi.mock('../store/useStore.js', () => {
+ const useStore = selector => selector ? selector(mocks.snapshot()) : mocks.snapshot()
+ useStore.getState = mocks.snapshot
+ return { useStore }
+})
+vi.mock('../store/useUI.js', () => {
+ const snap = () => ({ toast: (...a) => mocks.toast(...a), openSheet: (...a) => mocks.openSheet(...a) })
+ const useUI = selector => selector ? selector(snap()) : snap()
+ useUI.getState = snap
+ return { useUI }
+})
+vi.mock('react-router-dom', () => ({ useNavigate: () => mocks.nav }))
+// A getter, so one test can be the web build and the rest the phone.
+vi.mock('../lib/mobile.js', () => ({ get MOBILE() { return mocks.mobile } }))
+vi.mock('../lib/coach-secrets.js', () => ({
+ getApiKey: vi.fn(() => Promise.resolve(null)),
+ setApiKey: vi.fn(() => Promise.resolve()),
+ clearApiKey: vi.fn(() => Promise.resolve()),
+}))
+vi.mock('../lib/coach-local.js', () => ({
+ localModels: vi.fn(() => Promise.resolve({ ok: true, models: [] })),
+ localForget: vi.fn(() => Promise.resolve({ ok: true })),
+}))
+vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => <div className="connect-sheet" /> }))
+
+let host, root
+beforeEach(() => {
+ mocks.mobile = true
+ mocks.user = { uid: 'u1', name: 'Ana' }
+ mocks.config = { coach: { enabled: true } }
+ mocks.coachLocal = null
+ mocks.nav.mockReset(); mocks.toast.mockReset(); mocks.openSheet.mockReset()
+ mocks.setCoachLocal.mockReset().mockResolvedValue(undefined)
+ mocks.refreshConfig.mockReset()
+ vi.mocked(getApiKey).mockReset().mockResolvedValue(null)
+ vi.mocked(setApiKey).mockReset().mockResolvedValue(undefined)
+ vi.mocked(clearApiKey).mockReset().mockResolvedValue(undefined)
+ vi.mocked(localModels).mockReset().mockResolvedValue({ ok: true, models: [] })
+ vi.mocked(localForget).mockReset().mockResolvedValue({ ok: true })
+ host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
+})
+afterEach(() => { act(() => root.unmount()); host.remove() })
+
+const mount = async () => { await act(async () => { root.render(<CoachSetup />) }) }
+const settle = async () => { await act(async () => { for (let i = 0; i < 6; i++) await Promise.resolve() }) }
+
+const all = sel => [...host.querySelectorAll(sel)]
+const rowTitled = title => all('.lrow').find(r => r.querySelector('.lrow-t')?.textContent === title)
+const btn = text => all('.btn').find(b => b.textContent.trim() === text)
+const chip = label => all('.chip').find(b => b.textContent.trim() === label)
+const field = type => all('input').find(i => (i.getAttribute('type') || 'text') === type)
+const click = el => { expect(el).toBeTruthy(); return act(() => el.click()) }
+const typeIn = (el, value) => act(() => {
+ Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)
+ el.dispatchEvent(new Event('input', { bubbles: true }))
+})
+const pickModel = value => act(() => {
+ const el = host.querySelector('select')
+ Object.getOwnPropertyDescriptor(el.constructor.prototype, 'value').set.call(el, value)
+ el.dispatchEvent(new Event('change', { bubbles: true }))
+})
+const openByok = async () => { await click(rowTitled('Bring my own API key')) }
+
+describe('CoachSetup — where it runs at all', () => {
+ it('is a phone screen: the web build is sent straight back to Settings', async () => {
+ mocks.mobile = false
+ await mount()
+ expect(mocks.nav).toHaveBeenCalledWith('/settings', { replace: true })
+ })
+
+ it('re-asks the paired server what it can do, because the admin may have switched it on', async () => {
+ await mount()
+ expect(mocks.refreshConfig).toHaveBeenCalledTimes(1)
+ })
+
+ it('asks nothing of a server it is not signed in to', async () => {
+ mocks.user = null; mocks.config = null
+ await mount()
+ expect(mocks.refreshConfig).not.toHaveBeenCalled()
+ })
+})
+
+describe('CoachSetup — "use my self-hosted openGym"', () => {
+ it('hands the Coach to the server and leaves for the conversation', async () => {
+ await mount()
+ await click(rowTitled('Use my self-hosted openGym'))
+ await settle()
+ expect(mocks.setCoachLocal).toHaveBeenCalledWith({ mode: 'server' })
+ expect(mocks.toast).toHaveBeenCalledWith('The Coach is on')
+ expect(mocks.nav).toHaveBeenCalledWith('/coach')
+ })
+
+ it('an unpaired phone is asked to connect first, and nothing is written', async () => {
+ mocks.user = null; mocks.config = null
+ await mount()
+ expect(rowTitled('Use my self-hosted openGym').textContent).toContain('Connect to my server')
+ await click(rowTitled('Use my self-hosted openGym'))
+ expect(mocks.openSheet).toHaveBeenCalledTimes(1)
+ expect(mocks.setCoachLocal).not.toHaveBeenCalled()
+ expect(mocks.nav).not.toHaveBeenCalled()
+ })
+
+ it('a paired server with no Coach on it refuses, explains, and writes nothing', async () => {
+ mocks.config = { coach: { enabled: false } }
+ await mount()
+ const row = rowTitled('Use my self-hosted openGym')
+ expect(row.textContent).toContain('Your server has no Coach enabled')
+ await click(row)
+ expect(mocks.setCoachLocal).not.toHaveBeenCalled()
+ expect(mocks.nav).not.toHaveBeenCalled()
+ expect(host.querySelector('.card').textContent).toContain('ask its admin, or bring your own key below')
+ })
+
+ it('says it is still asking while the server has not answered yet', async () => {
+ mocks.config = null
+ await mount()
+ expect(rowTitled('Use my self-hosted openGym').textContent).toContain('Loading…')
+ })
+
+ it('Back returns to Settings', async () => {
+ await mount()
+ await click(host.querySelector('.hdr .iconbtn'))
+ expect(mocks.nav).toHaveBeenCalledWith('/settings')
+ })
+})
+
+describe('CoachSetup — bringing your own key', () => {
+ it('offers exactly the providers the shared table lists, Anthropic first', async () => {
+ await mount(); await openByok()
+ expect(all('.chip').map(c => c.textContent)).toEqual(Object.values(HTTP_PROVIDERS).map(p => p.label))
+ expect(chip('Anthropic API').classList.contains('on')).toBe(true)
+ })
+
+ it('names every category the payload is built from, in that order, and where it would go', async () => {
+ await mount(); await openByok()
+ const section = all('.sect').find(s => s.querySelector('.sect-t')?.textContent === 'What leaves this phone')
+ expect([...section.querySelectorAll('.lrow-t')].map(t => t.textContent))
+ .toEqual(DATA_CATEGORIES.map(k => CATEGORY_TEXT[k][0]))
+ expect(host.textContent).toContain('Each request goes straight to api.anthropic.com with your key')
+ })
+
+ it('shows an endpoint field only for the OpenAI-compatible provider', async () => {
+ await mount(); await openByok()
+ expect(host.textContent).not.toContain('Endpoint')
+ await click(chip('OpenAI-compatible endpoint'))
+ expect(host.textContent).toContain('Endpoint')
+ expect(field('text').getAttribute('placeholder')).toBe('http://ollama.lan:11434')
+ // With nothing typed there is no host to name, so the line falls back to the provider.
+ expect(host.textContent).toContain('Each request goes straight to OpenAI-compatible endpoint with your key')
+ typeIn(field('text'), 'http://ollama.lan:11434')
+ expect(host.textContent).toContain('Each request goes straight to ollama.lan:11434 with your key')
+ })
+
+ it('refuses to reach out with no key, and never loads the pipeline to find out', async () => {
+ await mount(); await openByok()
+ await click(btn('List models')); await settle()
+ expect(mocks.toast).toHaveBeenCalledWith('Enter your API key')
+ expect(localModels).not.toHaveBeenCalled()
+ expect(host.querySelector('.card')).toBe(null) // no progress steps started
+ })
+
+ it('a key already in the phone’s store counts — the field says so and stays optional', async () => {
+ vi.mocked(getApiKey).mockResolvedValue('sk-saved')
+ await mount(); await settle(); await openByok()
+ expect(field('password').getAttribute('placeholder')).toContain('(saved)')
+ await click(btn('List models')); await settle()
+ expect(localModels).toHaveBeenCalledWith({ provider: 'anthropic', baseUrl: null }, 'sk-saved')
+ })
+
+ it('a typed key wins over the saved one and is never read back out of storage', async () => {
+ vi.mocked(getApiKey).mockResolvedValue('sk-saved')
+ await mount(); await settle(); await openByok()
+ typeIn(field('password'), ' sk-typed ')
+ await click(btn('List models')); await settle()
+ expect(localModels).toHaveBeenCalledWith({ provider: 'anthropic', baseUrl: null }, 'sk-typed')
+ })
+
+ it('the OpenAI-compatible endpoint needs no key at all', async () => {
+ await mount(); await openByok()
+ await click(chip('OpenAI-compatible endpoint'))
+ typeIn(field('text'), 'http://ollama.lan:11434/')
+ await click(btn('List models')); await settle()
+ expect(mocks.toast).not.toHaveBeenCalled()
+ expect(localModels).toHaveBeenCalledWith({ provider: 'compatible', baseUrl: 'http://ollama.lan:11434' }, null)
+ })
+
+ it('turns down a base URL that is not one, before anything is loaded', async () => {
+ await mount(); await openByok()
+ await click(chip('OpenAI-compatible endpoint'))
+ const cases = [
+ ['ollama.lan', 'not a valid URL'],
+ // host:port with no scheme parses as a scheme of its own ("ollama.lan:"), so it lands on
+ // the protocol message rather than the parse one — worth knowing, the placeholder is a URL.
+ ['ollama.lan:11434', 'only http:// and https:// endpoints are supported'],
+ ['ftp://ollama.lan', 'only http:// and https:// endpoints are supported'],
+ ['http://me:[email protected]', 'put the key in the credential field, not in the URL'],
+ ['http://ollama.lan?k=1', 'a base URL has no query string'],
+ ]
+ for (const [url, error] of cases) {
+ mocks.toast.mockClear()
+ typeIn(field('text'), url)
+ await click(btn('List models')); await settle()
+ expect(mocks.toast, url).toHaveBeenCalledWith(error)
+ }
+ expect(localModels).not.toHaveBeenCalled()
+ })
+
+ it('an empty compatible endpoint is refused before anything is loaded', async () => {
+ // validateBaseUrl('') is {ok:true,value:null} on purpose: for a provider with a fixed
+ // endpoint, empty means the default. `compatible` has none, so the screen refuses it here
+ // rather than sending "List models" out with nowhere to go and failing at the adapter.
+ await mount(); await openByok()
+ await click(chip('OpenAI-compatible endpoint'))
+ await click(btn('List models')); await settle()
+ expect(mocks.toast).toHaveBeenCalledWith('Enter the endpoint URL')
+ expect(localModels).not.toHaveBeenCalled()
+ expect(host.querySelector('.card')).toBe(null) // no progress steps started
+ })
+})
+
+describe('CoachSetup — listing the models', () => {
+ const withKey = async () => {
+ await mount(); await openByok()
+ typeIn(field('password'), 'sk-1')
+ }
+
+ it('walks the three steps, lists what the endpoint serves and pre-picks the default', async () => {
+ vi.mocked(localModels).mockResolvedValue({ ok: true, models: ['claude-opus-5', 'claude-haiku-4'] })
+ await withKey()
+ await click(btn('List models')); await settle()
+
+ expect(all('.card .small').map(s => s.textContent))
+ .toEqual(['Loading the exercise catalogue…', 'Checking the endpoint…', 'Ready'])
+ const select = host.querySelector('select')
+ expect([...select.options].map(o => o.value)).toEqual(['', 'claude-opus-5', 'claude-haiku-4'])
+ expect(select.value).toBe('claude-opus-5')
+ expect(btn('Save and use the Coach')).toBeTruthy()
+ expect(btn('List models')).toBeTruthy() // still there, to re-list
+ })
+
+ it('leaves the model unchosen when the endpoint does not serve the default', async () => {
+ vi.mocked(localModels).mockResolvedValue({ ok: true, models: ['qwen3-27b'] })
+ await withKey()
+ await click(btn('List models')); await settle()
+ expect(host.querySelector('select').value).toBe('')
+ expect(host.querySelector('select option').textContent).toBe('(claude-opus-5)')
+ })
+
+ it('an endpoint that will not answer clears the progress and says why', async () => {
+ vi.mocked(localModels).mockResolvedValue({ ok: false, error: 'connection refused' })
+ await withKey()
+ await click(btn('List models')); await settle()
+ expect(mocks.toast).toHaveBeenCalledWith('Could not reach the provider: connection refused')
+ expect(host.querySelector('.card')).toBe(null)
+ expect(host.querySelector('select')).toBe(null)
+ expect(btn('List models').disabled).toBe(false) // and you can try again
+ })
+
+ it('a thrown failure is reported in its own words', async () => {
+ vi.mocked(localModels).mockRejectedValue(new Error('secure storage timed out'))
+ await withKey()
+ await click(btn('List models')); await settle()
+ expect(mocks.toast).toHaveBeenCalledWith('secure storage timed out')
+ expect(host.querySelector('.card')).toBe(null)
+ })
+
+ it('a thrown failure with nothing to say still says something', async () => {
+ vi.mocked(localModels).mockRejectedValue(new Error())
+ await withKey()
+ await click(btn('List models')); await settle()
+ expect(mocks.toast).toHaveBeenCalledWith('Could not connect')
+ })
+
+ it('switching provider throws the list away — a model name is not portable', async () => {
+ vi.mocked(localModels).mockResolvedValue({ ok: true, models: ['claude-opus-5'] })
+ await withKey()
+ await click(btn('List models')); await settle()
+ expect(host.querySelector('select')).toBeTruthy()
+
+ await click(chip('Google Gemini'))
+ expect(host.querySelector('select')).toBe(null)
+ expect(btn('Save and use the Coach')).toBeUndefined()
+
+ vi.mocked(localModels).mockResolvedValue({ ok: true, models: ['gemini-2.5-pro'] })
+ await click(btn('List models')); await settle()
+ expect(localModels).toHaveBeenLastCalledWith({ provider: 'gemini', baseUrl: null }, 'sk-1')
+ expect(host.querySelector('select').value).toBe('gemini-2.5-pro')
+ })
+})
+
+describe('CoachSetup — saving', () => {
+ const listed = async (provider, models, { key = 'sk-1', baseUrl } = {}) => {
+ await mount(); await openByok()
+ if (provider) await click(chip(HTTP_PROVIDERS[provider].label))
+ if (baseUrl != null) typeIn(field('text'), baseUrl)
+ if (key) typeIn(field('password'), key)
+ vi.mocked(localModels).mockResolvedValue({ ok: true, models })
+ await click(btn('List models')); await settle()
+ }
+
+ it('writes the mode, the provider and the chosen model, then stores the key and leaves', async () => {
+ await listed(null, ['claude-opus-5'])
+ await click(btn('Save and use the Coach')); await settle()
+ expect(mocks.setCoachLocal).toHaveBeenCalledWith({ mode: 'byok', provider: 'anthropic', model: 'claude-opus-5', baseUrl: null })
+ expect(setApiKey).toHaveBeenCalledWith('sk-1')
+ expect(mocks.toast).toHaveBeenCalledWith('The Coach is on')
+ expect(mocks.nav).toHaveBeenCalledWith('/coach')
+ })
+
+ it('normalises the endpoint it saves for a compatible provider, and saves the model you pick', async () => {
+ await listed('compatible', ['qwen3-27b', 'llama-3.3'], { key: null, baseUrl: 'http://ollama.lan:11434//' })
+ pickModel('llama-3.3')
+ await click(btn('Save and use the Coach')); await settle()
+ expect(mocks.setCoachLocal).toHaveBeenCalledWith({
+ mode: 'byok', provider: 'compatible', model: 'llama-3.3', baseUrl: 'http://ollama.lan:11434'
+ })
+ expect(setApiKey).not.toHaveBeenCalled()
+ })
+
+ it('does not touch the secure store when the key field was left alone', async () => {
+ vi.mocked(getApiKey).mockResolvedValue('sk-saved')
+ await mount(); await settle(); await openByok()
+ vi.mocked(localModels).mockResolvedValue({ ok: true, models: ['claude-opus-5'] })
+ await click(btn('List models')); await settle()
+ await click(btn('Save and use the Coach')); await settle()
+ expect(setApiKey).not.toHaveBeenCalled()
+ expect(mocks.nav).toHaveBeenCalledWith('/coach')
+ })
+
+ it('refuses to save a provider with no model picked and no default to fall back on', async () => {
+ await listed('compatible', [], { key: null, baseUrl: 'http://ollama.lan:11434' })
+ await click(btn('Save and use the Coach')); await settle()
+ expect(mocks.toast).toHaveBeenCalledWith('Pick a model')
+ expect(mocks.setCoachLocal).not.toHaveBeenCalled()
+ expect(mocks.nav).not.toHaveBeenCalled()
+ })
+
+ // DEFECT (fixed in CoachSetup.jsx, see the report): "List models" validates the endpoint and
+ // "Save" did not. Editing the field after a successful listing — the one order in which the
+ // two disagree — saved `baseUrl: null`, said "The Coach is on" and left for the conversation
+ // with the phone pointed at nothing.
+ it('refuses on Save the same endpoint it refused on List models', async () => {
+ await listed('compatible', ['qwen3-27b'], { key: null, baseUrl: 'http://ollama.lan:11434' })
+ pickModel('qwen3-27b')
+ typeIn(field('text'), 'ollama.lan')
+ await click(btn('Save and use the Coach')); await settle()
+ expect(mocks.toast).toHaveBeenCalledWith('not a valid URL')
+ expect(mocks.setCoachLocal).not.toHaveBeenCalled()
+ expect(mocks.nav).not.toHaveBeenCalled()
+ })
+
+ it('refuses on Save an endpoint field cleared after a successful listing', async () => {
+ // The same hole as above in the one shape the validator lets through: empty. Cleared after
+ // listing, Save would have written `baseUrl: null` and pointed the phone at nothing.
+ await listed('compatible', ['qwen3-27b'], { key: null, baseUrl: 'http://ollama.lan:11434' })
+ pickModel('qwen3-27b')
+ typeIn(field('text'), '')
+ await click(btn('Save and use the Coach')); await settle()
+ expect(mocks.toast).toHaveBeenCalledWith('Enter the endpoint URL')
+ expect(mocks.setCoachLocal).not.toHaveBeenCalled()
+ expect(mocks.nav).not.toHaveBeenCalled()
+ })
+
+ // Issue #42: both of these used to leave the button greyed out for ever with no explanation.
+ it('a settings write that fails says so, keeps you here and never stores the key', async () => {
+ await listed(null, ['claude-opus-5'])
+ mocks.setCoachLocal.mockRejectedValueOnce(new Error('could not write the settings file'))
+ await click(btn('Save and use the Coach')); await settle()
+ expect(mocks.toast).toHaveBeenCalledWith('could not write the settings file')
+ expect(setApiKey).not.toHaveBeenCalled()
+ expect(mocks.nav).not.toHaveBeenCalled()
+ expect(btn('Save and use the Coach').disabled).toBe(false)
+ })
+
+ it('a secure-store write that fails says so — but the mode is already on, by design', async () => {
+ await listed(null, ['claude-opus-5'])
+ vi.mocked(setApiKey).mockRejectedValueOnce(new Error('secure storage timed out'))
+ await click(btn('Save and use the Coach')); await settle()
+ expect(mocks.setCoachLocal).toHaveBeenCalledWith(expect.objectContaining({ mode: 'byok' }))
+ expect(mocks.toast).toHaveBeenCalledWith('secure storage timed out')
+ expect(mocks.nav).not.toHaveBeenCalled()
+ expect(btn('Save and use the Coach').disabled).toBe(false)
+ })
+})
+
+describe('CoachSetup — turning it off', () => {
+ it('offers the control only once the Coach is actually on', async () => {
+ await mount()
+ expect(rowTitled('Turn the Coach off on this phone')).toBeUndefined()
+ expect(host.textContent).toContain('Off — choose how the Coach should run.')
+ })
+
+ it('says which way it is running now', async () => {
+ mocks.coachLocal = { mode: 'server' }
+ await mount()
+ expect(host.textContent).toContain('Runs on your openGym server')
+ expect(rowTitled('Turn the Coach off on this phone')).toBeTruthy()
+ })
+
+ it('forgets the key, the mode and everything the pipeline was holding', async () => {
+ mocks.coachLocal = { mode: 'byok', provider: 'openai', model: 'gpt-5.6' }
+ await mount()
+ expect(host.textContent).toContain('Runs on this phone with your own API key')
+
+ await click(rowTitled('Turn the Coach off on this phone')); await settle()
+ expect(clearApiKey).toHaveBeenCalledTimes(1)
+ expect(mocks.setCoachLocal).toHaveBeenCalledWith({ mode: 'off' })
+ expect(localForget).toHaveBeenCalledTimes(1)
+ expect(mocks.toast).toHaveBeenCalledWith('The Coach is off')
+ expect(mocks.nav).not.toHaveBeenCalled() // you stay on the screen
+ })
+
+ it('starts the key picker on the provider the phone was already using', async () => {
+ mocks.coachLocal = { mode: 'byok', provider: 'openai', model: 'gpt-5.6' }
+ await mount(); await openByok()
+ expect(chip('OpenAI API').classList.contains('on')).toBe(true)
+ expect(field('password').getAttribute('placeholder')).toBe('sk-…')
+ })
+})
diff --git a/frontend/src/views/CoachSetup.jsx b/frontend/src/views/CoachSetup.jsx
index 878d266ac..7bb5b6d4a 100644
--- a/frontend/src/views/CoachSetup.jsx
+++ b/frontend/src/views/CoachSetup.jsx
@@ -66,6 +66,9 @@ export default function CoachSetup() {
const prepare = async () => {
const v = validateBaseUrl(meta.baseUrl ? baseUrl : '')
if (!v.ok) return toast(v.error)
+ // An empty field passes the validator on purpose: for a provider with a fixed endpoint,
+ // empty means the default. This one has no default, so empty is nowhere to call.
+ if (meta.baseUrl && !meta.defaultBase && !v.value) return toast(t('Enter the endpoint URL'))
if (!meta.keyOptional && !key.trim() && !hasKey) return toast(t('Enter your API key'))
setBusy(true); setStep(0)
try {
@@ -83,6 +86,12 @@ export default function CoachSetup() {
}
const save = async () => {
+ // The same check "List models" makes. The endpoint field stays editable after a successful
+ // listing, and taking `.value` off an unchecked result turned a typo into `baseUrl: null` —
+ // saved, "The Coach is on", and the phone pointed at nothing.
+ const v = validateBaseUrl(meta.baseUrl ? baseUrl : '')
+ if (!v.ok) return toast(v.error)
+ if (meta.baseUrl && !meta.defaultBase && !v.value) return toast(t('Enter the endpoint URL'))
const chosen = model || meta.defaultModel
if (!chosen) return toast(t('Pick a model'))
setBusy(true)
@@ -90,7 +99,7 @@ export default function CoachSetup() {
// The mode first, the key second: the settings file is the cheap, reliable write, the
// key goes through the platform's secure store, which is the step that can misbehave.
// Either way the user hears what happened instead of watching a greyed-out button (#42).
- await setCoachLocal({ mode: 'byok', provider, model: chosen, baseUrl: meta.baseUrl ? (validateBaseUrl(baseUrl).value || null) : null })
+ await setCoachLocal({ mode: 'byok', provider, model: chosen, baseUrl: meta.baseUrl ? v.value : null })
if (key.trim()) { await setApiKey(key.trim()); setHasKey(true); setKey('') }
toast(t('The Coach is on'))
nav('/coach')