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.

Coach: a run that fails before the first status poll still gets its reply in the chat, and an older status answer no longer puts back the day's run count

Duarte Santos43a20547473a
diff --git a/frontend/src/lib/coach-api.js b/frontend/src/lib/coach-api.js
index 0db547cde..558f4f970 100644
--- a/frontend/src/lib/coach-api.js
+++ b/frontend/src/lib/coach-api.js
@@ -46,11 +46,29 @@ const local = async () => {
return localMod
}
+// The job this app last started and has not written a reply for yet. A run that fails before
+// the first status poll — a provider refusing the connection answers in milliseconds — is never
+// seen running, so "running, then gone" cannot be the only way the chat learns a run ended: it
+// also compares the server's last outcome with the id the start request returned. Kept here,
+// at module level, because the plan the intake asks for is started on another screen.
+let awaited = null
+const track = async p => {
+ const r = await p
+ if (r?.job?.id) awaited = r.job.id
+ return r
+}
+export const awaitedJob = () => awaited
+export const settleAwaited = id => { if (!id || awaited === id) awaited = null }
+
export const coachStatus = async () => DEMO ? (await demo()).demoStatus() : LOCAL() ? (await local()).localStatus() : api('/api/coach/status')
-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 || '', lang: getLang() }) })
-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, lang: getLang() }) })
-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, lang: getLang() }) })
-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, lang: getLang() }) })
+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 || '', lang: getLang() }) })
+export const requestReview = async (...a) => track(_requestReview(...a))
+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, lang: getLang() }) })
+export const requestPlan = async (...a) => track(_requestPlan(...a))
+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, lang: getLang() }) })
+export const refinePlan = async (...a) => track(_refinePlan(...a))
+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, lang: getLang() }) })
+export const requestDebrief = async (...a) => track(_requestDebrief(...a))
// 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')
@@ -84,10 +102,16 @@ export function useCoachStatus(active = true) {
const [state, setState] = useState({ job: null, pending: null, cap: null, loading: true })
const timer = useRef(null)
const loop = useRef(null) // the running poll loop's `tick`, so a manual refresh can re-pace it
+ const seq = useRef(0) // which status request is the newest one
const refresh = useCallback(async () => {
+ const mine = ++seq.current
try {
const s = await coachStatus()
+ // An answer that arrives after a newer request was sent is older than what that request
+ // will bring: the idle poll in flight when a run is started must not land after the
+ // refresh that follows the start, putting back the run count and last outcome from before.
+ if (mine !== seq.current) return s
setState({ ...s, loading: false })
// A refresh that finds a job in flight — the one the caller just started — must not leave
// the loop asleep on its idle cadence: without this the card shows up to a minute after
@@ -95,7 +119,7 @@ export function useCoachStatus(active = true) {
if (s?.job && loop.current) { clearTimeout(timer.current); timer.current = setTimeout(loop.current, POLL_MS) }
return s
} catch {
- setState(s => ({ ...s, loading: false }))
+ if (mine === seq.current) setState(s => ({ ...s, loading: false }))
return null
}
}, [])
diff --git a/frontend/src/views/CoachChat.fast-failure.test.jsx b/frontend/src/views/CoachChat.fast-failure.test.jsx
new file mode 100644
index 000000000..49e07869f
--- /dev/null
+++ b/frontend/src/views/CoachChat.fast-failure.test.jsx
@@ -0,0 +1,159 @@
+// @vitest-environment happy-dom
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import CoachChat from './CoachChat.jsx'
+import { requestPlan, settleAwaited } from '../lib/coach-api.js'
+
+// A run that fails before the first status poll. A provider that refuses the connection fails
+// the job in milliseconds, so by the time the chat asks for the status the job is already gone
+// and the server's last outcome is `failed` / `provider`. The chat used to write a reply only
+// when it had seen the job running and then gone, so these runs ended with no reply at all —
+// three questions in a row, three silences. The real lib/coach-api.js runs here; only the HTTP
+// layer is faked, answering the way the server does.
+const mocks = vi.hoisted(() => {
+ const state = { S: null, nav: vi.fn(), toast: vi.fn(), openSheet: vi.fn(), server: null, statusGate: null }
+ 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
+ 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('../sheets.jsx', () => ({ startFlow: vi.fn(), confirmSheet: vi.fn() }))
+vi.mock('../coach.css', () => ({}))
+// The server: a start bumps the day's count and the run fails at once, before anyone polls.
+vi.mock('../lib/api.js', () => ({
+ IS_APPLE: false, IS_ANDROID: false, BIO: 'biometrics',
+ api: vi.fn(async (path, opts) => {
+ const srv = mocks.server
+ if (path === '/api/coach/status') {
+ const snap = { job: null, pending: null, cap: { used: srv.used, limit: 10 }, last: srv.last, maxMessageLen: 1000 }
+ if (mocks.statusGate) { const gate = mocks.statusGate; mocks.statusGate = null; await gate }
+ return snap
+ }
+ if (opts?.method === 'POST' && /^\/api\/coach\/(review|plan|debrief)$/.test(path)) {
+ const id = 'job' + (++srv.n)
+ srv.used++
+ srv.last = { id, kind: path.endsWith('plan') ? 'create' : 'review', outcome: 'failed', errorClass: 'provider', at: Date.now() }
+ return { job: { id } }
+ }
+ return {}
+ }),
+}))
+
+const FAILED = 'The Coach couldn’t run — the instance owner needs to check its setup.'
+let root, container
+
+function installDom() {
+ document.body.innerHTML = '<div id="root"></div>'
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ container = document.getElementById('root')
+ root = createRoot(container)
+}
+const flush = async () => { for (let i = 0; i < 30; i++) await Promise.resolve() }
+const settle = async () => { await act(async () => { await flush() }) }
+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 MouseEvent('click', { bubbles: true })); await flush() })
+}
+async function mount() {
+ installDom()
+ await act(async () => { root.render(React.createElement(CoachChat)) })
+ await settle()
+}
+
+const state = routines => ({
+ unit: 'kg', lang: 'en', customEx: [], workouts: [{ id: 'w1', name: 'Push Day', d: '2026-09-01', entries: [] }], 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: []
+ },
+})
+const routine = { id: 'r1', name: 'Day A', ex: [{ id: '0001', sets: 3, reps: 10 }, { id: '0002', sets: 3, reps: 10 }] }
+const replies = () => mocks.S.coach.chat.filter(m => m.role === 'coach')
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ settleAwaited()
+ mocks.statusGate = null
+ // An earlier run that failed the same way: already answered, and must not be answered again.
+ mocks.server = { n: 0, used: 4, last: { id: 'old', kind: 'review', outcome: 'failed', errorClass: 'provider', at: 1 } }
+})
+afterEach(async () => {
+ if (root) { await act(async () => { root.unmount() }); root = null }
+ container = null
+})
+
+describe('a Coach run that fails before the first poll', () => {
+ it('“Review my training” gets the error reply, once, and the counter reads what the server counted', async () => {
+ mocks.S = state([routine])
+ await mount()
+ expect(replies()).toHaveLength(0) // opening the chat answers nothing old
+
+ await click(chip(/Review my training/))
+ expect(mocks.S.coach.chat.at(-1)).toMatchObject({ role: 'coach', kind: 'error', text: FAILED })
+ expect(mocks.S.coach.chat.at(-2)).toMatchObject({ role: 'user', kind: 'text' })
+ expect(container.querySelector('.composer-cap').textContent).toBe('5 of 10 Coach runs used today')
+
+ await settle()
+ expect(replies()).toHaveLength(1) // written once, not on every render
+
+ await click(chip(/Review my training/))
+ expect(replies()).toHaveLength(2)
+ expect(container.querySelector('.composer-cap').textContent).toBe('6 of 10 Coach runs used today')
+ })
+
+ it('a message asking for a plan gets the error reply', async () => {
+ mocks.S = state([]) // no routines: a message asks for a plan
+ await mount()
+ const ta = container.querySelector('.composer textarea')
+ await act(async () => {
+ Object.getOwnPropertyDescriptor(ta.constructor.prototype, 'value').set.call(ta, 'Add more legs please')
+ ta.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+ await click(container.querySelector('.composer .send'))
+ expect(mocks.S.coach.chat.at(-2)).toMatchObject({ role: 'user', kind: 'text', text: 'Add more legs please' })
+ expect(mocks.S.coach.chat.at(-1)).toMatchObject({ role: 'coach', kind: 'error', text: FAILED })
+ expect(mocks.server.last.kind).toBe('create')
+ })
+
+ it('the plan the intake asked for, failed before the chat opened, is answered when it opens', async () => {
+ mocks.S = state([])
+ await requestPlan(mocks.S.coach.profile) // CoachIntake's finish(), then nav('/coach')
+ await mount()
+ expect(replies()).toHaveLength(1)
+ expect(replies()[0]).toMatchObject({ kind: 'error', text: FAILED })
+ })
+
+ it('a status answer taken before the start and landing after it does not put back the old count', async () => {
+ mocks.S = state([routine])
+ // The chat's first poll is still on its way when the run is started: its snapshot is from
+ // before the start, and it arrives after the refresh that follows the start.
+ let release
+ mocks.statusGate = new Promise(r => { release = r })
+ await mount()
+ await click(chip(/Review my training/))
+ expect(container.querySelector('.composer-cap').textContent).toBe('5 of 10 Coach runs used today')
+ await act(async () => { release(); await flush() })
+ expect(container.querySelector('.composer-cap').textContent).toBe('5 of 10 Coach runs used today')
+ expect(replies()).toHaveLength(1)
+ expect(replies()[0]).toMatchObject({ kind: 'error', text: FAILED })
+ })
+})
diff --git a/frontend/src/views/CoachChat.jsx b/frontend/src/views/CoachChat.jsx
index bfa56d0e5..6fda295bd 100644
--- a/frontend/src/views/CoachChat.jsx
+++ b/frontend/src/views/CoachChat.jsx
@@ -28,7 +28,7 @@ import {
changeTitle, changeValues, exName, canRevert, revertLast
} from '../lib/coach.js'
import { insightsFor, sessionInsights } from '../lib/coach-insights.js'
-import { useCoachStatus, requestReview, requestDebrief, requestPlan, refinePlan, resolvePending, cohortStats, setCohortShare, jobErrorText } from '../lib/coach-api.js'
+import { useCoachStatus, requestReview, requestDebrief, requestPlan, refinePlan, resolvePending, cohortStats, setCohortShare, jobErrorText, awaitedJob, settleAwaited } from '../lib/coach-api.js'
import { confirmSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { glyphOf } from '../lib/glyphs.js'
@@ -65,15 +65,23 @@ export default function CoachChat() {
// A job that ends is either a proposal, "nothing to change", or a failure. The server tells
// the client none of that directly — the job simply stops appearing — so the transition is
- // read here, once, and written into the thread as the Coach's reply.
+ // read here, once, and written into the thread as the Coach's reply. Two ways to see it end:
+ // the job was seen running and is now gone, or the run this app started (its id came back
+ // from the start request) is already the server's last outcome — a provider that refuses the
+ // connection fails the run before the first status poll, and it is never seen running at all.
useEffect(() => {
if (loading) return
const was = prevJob.current
prevJob.current = job
- if (!was || job) return
- const ms = was.startedAt ? Date.now() - was.startedAt : 0
+ if (job) return
+ const mine = awaitedJob()
+ const endedUnseen = !was && !!mine && last?.id === mine
+ if (!was && !endedUnseen) return
+ settleAwaited(was ? was.id : mine)
+ const ms = was?.startedAt ? Date.now() - was.startedAt : 0
update(s => {
- recordTiming(s, ms)
+ // A run that ended unseen has no duration worth learning from.
+ if (was) recordTiming(s, ms)
if (!pending) {
const cls = lastError?.errorClass || (last?.outcome === 'failed' ? (last.errorClass || 'internal') : null)
appendChat(s, cls
@@ -83,7 +91,7 @@ export default function CoachChat() {
: t('I looked through everything and there is nothing I would change right now. Keep going — ask me again after a few more sessions.') })
}
})
- }, [job, pending, loading])
+ }, [job, pending, loading, last?.id])
useEffect(() => { if (typeof endRef.current?.scrollIntoView === 'function') endRef.current.scrollIntoView({ block: 'end' }) }, [S.coach?.chat?.length, !!job, !!pending])
diff --git a/frontend/src/views/CoachChat.test.jsx b/frontend/src/views/CoachChat.test.jsx
index 7b7cdcb2f..f1d19586d 100644
--- a/frontend/src/views/CoachChat.test.jsx
+++ b/frontend/src/views/CoachChat.test.jsx
@@ -42,6 +42,8 @@ vi.mock('../lib/coach-api.js', () => ({
cohortStats: vi.fn(() => Promise.resolve({ ok: false, enabled: true, sharing: false })),
setCohortShare: vi.fn(() => Promise.resolve({ ok: true, sharing: true })),
JOB_ERRORS: { internal: 'x' },
+ awaitedJob: () => null,
+ settleAwaited: vi.fn(),
}))
vi.mock('../sheets.jsx', () => ({ startFlow: vi.fn(), confirmSheet: vi.fn() }))
vi.mock('../lib/api.js', () => ({