From 903a435af3cbe8972441c57ee36054273f391852 Mon Sep 17 00:00:00 2001 From: Daniel Santillan Date: Mon, 21 Sep 2026 15:56:51 -0400 Subject: [PATCH] Build a routine with AI: the screen the builder was missing MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "Add exercise" now has a sibling: it asks which muscles, whether the session starts with cardio, and how hard — then the Coach fills the routine in. Three taps instead of picking ten exercises one at a time, and it is the only place in the app that asks what you want to train today. Why it exists in this shape: - The Coach's own intake asks about the *person* — goal, days, equipment, limits — and is answered once. Nothing in it asks which muscles, so a three-day plan reasonably came back full body; that is what prompted this. The builder asks only what changes between sessions and reads the rest from the saved profile, so a second routine costs three taps and not a questionnaire. - It adds a NEW routine rather than filling the one you opened. The questions are about a session you are about to build, and replacing the routine somebody opened would be the wrong guess. It does not touch the week either: nobody was asked about days. - The muscle buttons are the catalogue's own body-part words ("back", "waist"), which the Library and the body map already translate, so a button and the list behind it cannot drift apart. "Light" and "Hard" are NOT reused for the effort chips: those keys already mean the light theme and hard sets, and a chip reading "Claro" for an easy session would be nonsense in Spanish. The async half: requestPlan only *starts* a job (the server runs it in the background and the result arrives on a status poll), so `awaitCoachJob` waits for that job by the id of the last finished one — a proposal left over from an earlier question can never be mistaken for this answer — and throws with the job's own error class for jobErrorText to phrase. Five tests drive the whole thing: the three steps, the exact questions sent (the muscles as bp/tg selectors with cardio in the library, not only in the sentence), that what comes back lands as a new routine with the cardios and the modes the app owns normalised, that a failure is shown in the app's words and can be retried, and that an answer with no routine is refused rather than added empty. The 22 new strings exist in Spanish only, by decision. Rather than leave check-locales.mjs permanently red — a guard nobody reads is not a guard — the pending set is written down in src/locales/PENDING.md: the check still fails on anything NEW, and the debt is a list somebody can work through. --- frontend/scripts/check-locales.mjs | 40 +++++- frontend/src/lib/ai-routine.js | 23 ++-- frontend/src/lib/coach-api.js | 33 +++++ frontend/src/locales/PENDING.md | 32 +++++ frontend/src/locales/es.js | 23 ++++ frontend/src/sheets.ai-routine.test.jsx | 158 ++++++++++++++++++++++++ frontend/src/sheets.jsx | 128 ++++++++++++++++++- frontend/src/views/RoutineEdit.jsx | 19 ++- 8 files changed, 440 insertions(+), 16 deletions(-) create mode 100644 frontend/src/locales/PENDING.md create mode 100644 frontend/src/sheets.ai-routine.test.jsx diff --git a/frontend/scripts/check-locales.mjs b/frontend/scripts/check-locales.mjs index ffc0036..880f0f5 100644 --- a/frontend/scripts/check-locales.mjs +++ b/frontend/scripts/check-locales.mjs @@ -8,8 +8,14 @@ // // The reference is the union of all locales, not one blessed file: a key added to a // single locale then flags the other ten instead of passing unnoticed. +// +// Keys listed in src/locales/PENDING.md are reported and counted, not failed on. That file exists +// because a guard that is red for a known reason is a guard nobody reads: the moment it always +// fails, the next genuine drift it catches looks exactly like the noise. Keeping the pending set +// written down means this check still goes red for anything *new*, and the debt stays a list +// somebody can work through rather than a permanent red line. -import { readdirSync } from 'node:fs' +import { readdirSync, readFileSync, existsSync } from 'node:fs' import { dirname, join } from 'node:path' import { fileURLToPath, pathToFileURL } from 'node:url' @@ -21,6 +27,16 @@ if (!files.length) { process.exit(1) } +// One pending key per line prefixed with "- ", the shape a Markdown list already has. +const pendingPath = join(localesDir, 'PENDING.md') +const pending = new Set( + existsSync(pendingPath) + ? readFileSync(pendingPath, 'utf8').split('\n') + .filter(line => line.trim().startsWith('- ')) + .map(line => line.trim().slice(2).trim()) + : [] +) + const locales = new Map() for (const file of files) { const { default: dict } = await import(pathToFileURL(join(localesDir, file)).href) @@ -31,6 +47,14 @@ for (const file of files) { locales.set(file.replace(/\.js$/, ''), new Set(Object.keys(dict))) } +// A key every locale already carries cannot be pending: it would let a locale drop it silently. +const stalePending = [...pending].filter(k => [...locales.values()].every(keys => keys.has(k))) +if (stalePending.length) { + console.error('\nThese keys are in every locale already and must come out of PENDING.md:') + for (const k of stalePending) console.error(` ${JSON.stringify(k)}`) + process.exit(1) +} + // How many locales carry each key — 1 means the key was added to a single file only, // which is the usual shape of the bug and worth naming separately from plain gaps. const seen = new Map() @@ -38,9 +62,14 @@ for (const keys of locales.values()) for (const k of keys) seen.set(k, (seen.get const union = [...seen.keys()] let failed = false +const waiting = new Set() for (const [lang, keys] of locales) { - const missing = union.filter(k => !keys.has(k)) - const orphans = union.filter(k => keys.has(k) && seen.get(k) === 1) + const gaps = union.filter(k => !keys.has(k)) + const missing = gaps.filter(k => !pending.has(k)) + for (const k of gaps) if (pending.has(k)) waiting.add(k) + // A key only one locale carries is never "pending": it means that locale invented a string + // nobody else has, which is a mistake rather than a translation waiting to happen. + const orphans = union.filter(k => keys.has(k) && seen.get(k) === 1 && !pending.has(k)) if (missing.length || orphans.length) { failed = true console.error(`\n${lang}.js: ${keys.size}/${union.length} keys`) @@ -54,4 +83,7 @@ if (failed) { process.exit(1) } -console.log(`${locales.size} locales, ${union.length} keys each — in sync.`) +const tail = waiting.size + ? `${waiting.size} key${waiting.size === 1 ? '' : 's'} pending translation in ${locales.size - 1} locales (see src/locales/PENDING.md)` + : 'in sync' +console.log(`${locales.size} locales, ${union.length} keys each — ${tail}.`) diff --git a/frontend/src/lib/ai-routine.js b/frontend/src/lib/ai-routine.js index e0fe66e..dcab982 100644 --- a/frontend/src/lib/ai-routine.js +++ b/frontend/src/lib/ai-routine.js @@ -20,14 +20,14 @@ import { t } from './i18n.js' too coarse — "biceps" and "triceps" are both `upper arms`, and asking for one must not hand back the other. */ export const MUSCLE_GROUPS = [ - { key: 'chest', label: 'Chest', selectors: [{ bp: 'chest' }] }, - { key: 'back', label: 'Back', selectors: [{ bp: 'back' }] }, - { key: 'shoulders', label: 'Shoulders', selectors: [{ bp: 'shoulders' }] }, - { key: 'biceps', label: 'Biceps', selectors: [{ tg: 'biceps' }] }, - { key: 'triceps', label: 'Triceps', selectors: [{ tg: 'triceps' }] }, - { key: 'legs', label: 'Legs', selectors: [{ bp: 'upper legs' }, { bp: 'lower legs' }] }, - { key: 'glutes', label: 'Glutes', selectors: [{ tg: 'glutes' }] }, - { key: 'core', label: 'Core', selectors: [{ bp: 'waist' }] }, + { key: 'chest', label: 'chest', selectors: [{ bp: 'chest' }] }, + { key: 'back', label: 'back', selectors: [{ bp: 'back' }] }, + { key: 'shoulders', label: 'shoulders', selectors: [{ bp: 'shoulders' }] }, + { key: 'biceps', label: 'biceps', selectors: [{ tg: 'biceps' }] }, + { key: 'triceps', label: 'triceps', selectors: [{ tg: 'triceps' }] }, + { key: 'legs', label: 'upper legs', selectors: [{ bp: 'upper legs' }, { bp: 'lower legs' }] }, + { key: 'glutes', label: 'glutes', selectors: [{ tg: 'glutes' }] }, + { key: 'core', label: 'waist', selectors: [{ bp: 'waist' }] }, ] /* ---------- the intensity buttons ---------- @@ -35,10 +35,13 @@ export const MUSCLE_GROUPS = [ model reads, and once as the intake fields it is told to obey. A model that follows the prose and a model that follows the fields then agree. `CARDIAC_MIN` is what "start with cardio" asks for — a warm-up, not a conditioning block. */ +// `label` is its own key rather than "Light"/"Hard": those already exist in the locale packs +// meaning the light *theme* and hard *sets*, and a chip that says "Claro" for an easy session +// would be nonsense in Spanish. ("Medium" has no entry at all.) export const INTENSITIES = [ - { key: 'light', label: 'Light', sets: '2-3', reps: '12-15', exercises: '4-5', sessionMin: 45 }, + { key: 'light', label: 'Easy', sets: '2-3', reps: '12-15', exercises: '4-5', sessionMin: 45 }, { key: 'medium', label: 'Medium', sets: '3-4', reps: '8-12', exercises: '6-7', sessionMin: 60 }, - { key: 'hard', label: 'Hard', sets: '4-5', reps: '6-10', exercises: '7-9', sessionMin: 75 }, + { key: 'hard', label: 'Intense', sets: '4-5', reps: '6-10', exercises: '7-9', sessionMin: 75 }, ] export const CARDIAC_MIN = 8 const byKey = (list, key) => list.find(x => x.key === key) || null diff --git a/frontend/src/lib/coach-api.js b/frontend/src/lib/coach-api.js index b6f1a7f..d34a9bb 100644 --- a/frontend/src/lib/coach-api.js +++ b/frontend/src/lib/coach-api.js @@ -150,3 +150,36 @@ export function jobErrorText(cls, detail) { const why = own && detail ? String(detail).trim().slice(0, 300) : '' return why ? `${base}\n${why}` : base } + +/** + * Wait for the job that was just started, and hand back what it produced. + * + * `requestPlan` and friends only *start* a job: on the server it runs in the background and its + * result arrives as a `pending` proposal on the next status poll, and on a phone the same code + * runs in-process behind the same shape. The chat polls for this itself because it is a + * conversation; a screen that asked one question and wants one answer should not have to grow + * its own poll loop to get it. + * + * Identifies "its" job by the id of the last finished one, so a proposal left over from an + * earlier question is never mistaken for this answer. Throws with the job's own error class, + * which `jobErrorText` turns into the line the person reads. + */ +export async function awaitCoachJob({ timeoutMs = 6 * 60000, everyMs = 1200 } = {}) { + const before = (await coachStatus()).last?.id || null + const deadline = Date.now() + timeoutMs + for (;;) { + if (Date.now() > deadline) throw Object.assign(new Error(''), { code: 'timeout' }) + await new Promise(r => setTimeout(r, everyMs)) + const st = await coachStatus() + // Still working. This is also the state a job passes through before it is visible at all, + // so "no job" below is only read as "finished" once something has been seen or ruled out. + if (st.job) continue + if (st.last && st.last.id !== before) { + if (st.last.outcome === 'ready' && st.pending) return st.pending + throw Object.assign(new Error(st.last.reading || ''), { code: st.last.errorClass || (st.last.outcome === 'nochange' ? 'nochange' : 'provider') }) + } + // Nothing running and nothing new finished. `requestPlan` throws on a refusal (a cap, an + // unreachable server, no consent), so reaching here means the job is between being accepted + // and being visible — the loop keeps waiting, and the deadline above is what ends it. + } +} diff --git a/frontend/src/locales/PENDING.md b/frontend/src/locales/PENDING.md new file mode 100644 index 0000000..bcbd111 --- /dev/null +++ b/frontend/src/locales/PENDING.md @@ -0,0 +1,32 @@ +# Translations pending + +Spanish-only for now, by decision: the app ships in Spanish, so these are written in +es.js and left here for the other locales rather than dropped into twelve files in a +language nobody has reviewed. Until a key is translated everywhere it shows the English +source string, which is why this is a list and not a broken check. + +Remove a line when every locale carries the key; check-locales.mjs fails if a key is +listed here and no longer missing. + +- Build a routine with AI +- Which muscles? +- Pick one or two — usually a big muscle and the arms that help it. +- Pick at least one muscle. +- Start with cardio? +- A warm-up before the first working set. +- Yes, {0} minutes +- No +- How hard should it be? +- Sets and reps for each exercise, and how long the session runs. +- Easy +- Medium +- Intense +- Build the routine +- Building your routine… +- The Coach is choosing exercises for {0}. This usually takes a few seconds. +- your session +- Thinking… +- The Coach could not build that +- Try again +- Start over +- “{0}” added to your plan diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js index afc2294..8960d0b 100644 --- a/frontend/src/locales/es.js +++ b/frontend/src/locales/es.js @@ -1250,4 +1250,27 @@ export default { 'already added': 'ya añadido', 'no exercises': 'sin ejercicios', 'Pick equipment': 'Elegir equipamiento', + // ---- crear una rutina con IA (lib/ai-routine.js + el asistente de sheets.jsx) ---- + 'Build a routine with AI': 'Crear rutina con IA', + 'Which muscles?': '¿Qué músculos?', + 'Pick one or two — usually a big muscle and the arms that help it.': 'Elige uno o dos — normalmente un músculo grande y los brazos que le ayudan.', + 'Pick at least one muscle.': 'Elige al menos un músculo.', + 'Start with cardio?': '¿Empezar con cardio?', + 'A warm-up before the first working set.': 'Un calentamiento antes de la primera serie de trabajo.', + 'Yes, {0} minutes': 'Sí, {0} minutos', + 'No': 'No', + 'How hard should it be?': '¿Qué intensidad?', + 'Sets and reps for each exercise, and how long the session runs.': 'Series y repeticiones de cada ejercicio, y cuánto dura la sesión.', + 'Easy': 'Suave', + 'Medium': 'Media', + 'Intense': 'Intensa', + 'Build the routine': 'Crear la rutina', + 'Building your routine…': 'Creando tu rutina…', + 'The Coach is choosing exercises for {0}. This usually takes a few seconds.': 'El Coach está eligiendo ejercicios para {0}. Suele tardar unos segundos.', + 'your session': 'tu sesión', + 'Thinking…': 'Pensando…', + 'The Coach could not build that': 'El Coach no pudo crear la rutina', + 'Try again': 'Reintentar', + 'Start over': 'Empezar de nuevo', + '“{0}” added to your plan': '«{0}» añadida a tu plan', } diff --git a/frontend/src/sheets.ai-routine.test.jsx b/frontend/src/sheets.ai-routine.test.jsx new file mode 100644 index 0000000..ee20ddf --- /dev/null +++ b/frontend/src/sheets.ai-routine.test.jsx @@ -0,0 +1,158 @@ +// @vitest-environment happy-dom +// The routine builder, driven the way a person drives it: muscles, cardio, effort, build, add. +// +// The Coach itself is mocked — the real one is a network job — so what is asserted is everything +// around it: the questions that reach the model, that a routine only one muscle wide is refused, +// and that what comes back lands in the plan as a NEW routine without touching the week. +import React, { act } from 'react' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { createRoot } from 'react-dom/client' + +vi.mock('./lib/coach-api.js', () => ({ + requestPlan: vi.fn(async () => ({ job: { id: 'j1' } })), + awaitCoachJob: vi.fn(), + jobErrorText: (cls, detail) => `ERROR(${cls})${detail ? ': ' + detail : ''}`, +})) + +import { useStore } from './store/useStore.js' +import { useUI } from './store/useUI.js' +import { aiRoutineSheet } from './sheets.jsx' +import { requestPlan, awaitCoachJob } from './lib/coach-api.js' +import { EXDB } from './lib/exercises.js' + +const mounted = [] +const BACK = EXDB.find(e => e.bp === 'back' && e.n.includes('barbell bent over row')) || EXDB.find(e => e.bp === 'back') +const BICEPS = EXDB.find(e => e.tg === 'biceps') +const RUN = EXDB.find(e => e.bp === 'cardio') + +function renderSheet() { + aiRoutineSheet() + const sheet = useUI.getState().sheets.at(-1) + const host = document.createElement('div') + document.body.appendChild(host) + const root = createRoot(host) + mounted.push(root) + act(() => root.render(sheet.render(() => useUI.getState().closeSheet(sheet.id)))) + return host +} +const button = (host, label) => [...host.querySelectorAll('button')].find(b => b.textContent.trim() === label) +const click = (host, label) => act(() => button(host, label).click()) + +/** The plan the mocked Coach hands back: one day, one routine. */ +const bundle = { + coach_contract: 1, + name: 'Plan', + summary: 's', + basedOn: 'a', + customEx: [], + week: { 0: 'r1' }, + routines: [{ + id: 'r1', name: 'Espalda y bíceps', emoji: '💪', + ex: [ + { id: RUN.id, sets: 3, min: 8 }, + { id: BACK.id, sets: 3, reps: 10, mode: 'reps' }, + { id: BICEPS.id, sets: 3, reps: 10, mode: 'reps' }, + ], + }], +} + +describe('build a routine with AI', () => { + beforeEach(() => { + globalThis.IS_REACT_ACT_ENVIRONMENT = true + useUI.setState({ sheets: [], toastMsg: '' }) + useStore.setState(s => ({ S: { ...s.S, unit: 'lb', lang: 'es', routines: [], week: {}, coach: { profile: { equipment: ['barbell'] } } } })) + document.body.innerHTML = '' + vi.clearAllMocks() + }) + afterEach(() => { act(() => { mounted.splice(0).forEach(root => root.unmount()) }) }) + + it('asks which muscles first, and will not go on with none', () => { + const host = renderSheet() + expect(host.textContent).toContain('Which muscles?') + expect(button(host, 'Continue').disabled).toBe(true) + click(host, 'back') + expect(button(host, 'Continue').disabled).toBe(false) + }) + + it('puts the muscles, the cardio and the effort into the questions it asks the model', async () => { + const host = renderSheet() + click(host, 'back') + click(host, 'biceps') + click(host, 'Continue') + + expect(host.textContent).toContain('Start with cardio?') + click(host, 'Yes, 8 minutes') + click(host, 'Continue') + + expect(host.textContent).toContain('How hard should it be?') + click(host, 'Medium') + await act(async () => { button(host, 'Build the routine').click() }) + + expect(requestPlan).toHaveBeenCalledTimes(1) + const intake = requestPlan.mock.calls[0][0] + // The muscles travel as catalogue selectors — a target muscle for the arms, because biceps + // and triceps share one body part — plus cardio, which has to be in the library and not only + // in the sentence or the model can only improvise a warm-up. + expect(intake.groups).toEqual([{ bp: 'back' }, { tg: 'biceps' }, { bp: 'cardio' }]) + expect(intake.catalogueOnly).toBe(true) + expect(intake.daysPerWeek).toBe(1) + expect(intake.notes).toContain('back') + expect(intake.notes).toContain('mode "cardio"') + // The profile's equipment rides along, so it only proposes what this person owns. + expect(intake.equipment).toEqual(['barbell']) + }) + + it('adds what came back as a new routine, and leaves the week alone', async () => { + awaitCoachJob.mockResolvedValue({ id: 'p1', kind: 'create', bundle }) + const host = renderSheet() + click(host, 'back') + click(host, 'Continue') + click(host, 'No') + click(host, 'Continue') + click(host, 'Easy') + await act(async () => { button(host, 'Build the routine').click() }) + + // The preview: the routine's own name, and its exercises with their prescription. + expect(host.textContent).toContain('Espalda y bíceps') + + click(host, 'Add to my plan') + const S = useStore.getState().S + expect(S.routines).toHaveLength(1) + expect(S.routines[0].name).toBe('Espalda y bíceps') + expect(S.routines[0].ex.map(e => e.id)).toEqual([RUN.id, BACK.id, BICEPS.id]) + // Cardio is one bout whatever the model sent, and the mode it left out is read from the + // exercise — the two normalisations the app owns rather than trusting the answer for. + expect(S.routines[0].ex[0]).toMatchObject({ sets: 1, mode: 'cardio', min: 8 }) + expect(S.routines[0].ex[1].mode).toBe('reps') + // A new routine, unscheduled: the week is the person's, and the builder was never asked + // about days. + expect(S.week).toEqual({}) + expect(useUI.getState().sheets).toHaveLength(0) + }) + + it('shows the failure in the app’s own words and lets the person try again', async () => { + awaitCoachJob.mockRejectedValue(Object.assign(new Error(''), { code: 'auth' })) + const host = renderSheet() + click(host, 'back') + click(host, 'Continue') + click(host, 'Continue') + await act(async () => { button(host, 'Build the routine').click() }) + + expect(host.textContent).toContain('ERROR(auth)') + click(host, 'Try again') + expect(host.textContent).toContain('Which muscles?') + expect(useStore.getState().S.routines).toHaveLength(0) + }) + + it('refuses an answer with no routine in it rather than adding an empty one', async () => { + awaitCoachJob.mockResolvedValue({ id: 'p1', kind: 'create', bundle: { routines: [], week: {} } }) + const host = renderSheet() + click(host, 'back') + click(host, 'Continue') + click(host, 'Continue') + await act(async () => { button(host, 'Build the routine').click() }) + + expect(host.textContent).toContain('ERROR(unusable)') + expect(useStore.getState().S.routines).toHaveLength(0) + }) +}) diff --git a/frontend/src/sheets.jsx b/frontend/src/sheets.jsx index 2d4e19c..cf2c7cb 100644 --- a/frontend/src/sheets.jsx +++ b/frontend/src/sheets.jsx @@ -4,7 +4,7 @@ import { useUI } from './store/useUI.js' import { EXDB, EXIDX, BODYPARTS, isCardio, isBodyweightEq, allExercises, equipmentOf, smOf, searchExercises, exOr, isAssisted, betterWeight, beatsWeight } from './lib/exercises.js' import { activeProfile, exAvailable, ALL_EQUIPMENT, newProfile } from './lib/equipment.js' import { fmtDate, fmtNum, capWords, fmtVol, fmtDur, durPart, todayISO, isoOf, uid, exCount, routineCount, DAYN, DAYS, weekOrder, weekStartOf, weekDayOffset, MONTHS_LONG, ACCENTS } from './lib/format.js' -import { lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, effectiveRoutineIds, workoutVolume, setsDone, setsDoneActive, setUnitsTotal, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, EFFORT, capEffort, stepEffort, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX } from './lib/history.js' +import { lastEntryFor, bestWeightFor, bestWeightForEntry, buildSets, effectiveRoutineIds, workoutVolume, setsDone, setsDoneActive, setUnitsTotal, lastBW, supersetUnits, unitOf, setLabel, defaultConfig, cleanupSg, modeOf, effortOf, EFFORT, capEffort, stepEffort, isBw, isPerSide, sideReps, workSetsDone, applyIntensifierPlan, MAX_PLANNED_WARMUPS, NOTE_MAX, exLine } from './lib/history.js' import { usesBar, barWeightFor, defaultBarWeight, hasBarOverride, isNoBar } from './lib/bar.js' import { toScale, rirOf, EFFORT_PRESETS, effortColor } from './lib/effort.js' import { beep, vibrate } from './lib/sound.js' @@ -37,6 +37,8 @@ import { isFav, toggleFav, sortFavouritesFirst } from './lib/favourites.js' import { buildSessionEntries } from './lib/session-start.js' import { buildCombinedEntries, deriveSessionName } from './lib/session-merge.js' import { workoutsOn, backfillStart, backfillEnd, completeBackfill } from './lib/backfill.js' +import { MUSCLE_GROUPS, INTENSITIES, CARDIAC_MIN, buildIntake, muscleWords, routineFrom } from './lib/ai-routine.js' +import { requestPlan, awaitCoachJob, jobErrorText } from './lib/coach-api.js' const S = () => useStore.getState().S const update = (...a) => useStore.getState().update(...a) @@ -282,6 +284,130 @@ export function bwSheet(opts = {}) { return h } +/* ============================ build a routine with AI ============================ */ +// Three questions, one routine. The Coach's own intake asks about the *person* — goal, days, +// equipment, limits — and is answered once; the only thing that changes between routines is +// what you want to train today and how hard, which is all this asks. Everything else is read +// from the saved profile, so a second routine costs three taps rather than a questionnaire. +// +// What comes back is one routine, never a week: the payload asks for a single training day, and +// that is what makes "back and biceps" produce a back-and-biceps session instead of the +// full-body split a three-day plan reasonably becomes. +function AiRoutineSheet({ close }) { + const st = useStore(s => s.S) + const profile = st.coach?.profile || null + const [step, setStep] = useState('muscles') + // Cardio on by default: this is a routine builder, and most sessions start with a warm-up. + // The question is still asked, because "always" and "never" are both somebody's answer. + const [cardio, setCardio] = useState(true) + const [intensity, setIntensity] = useState('medium') + const [picked, setPicked] = useState([]) + const [routine, setRoutine] = useState(null) + const [failed, setFailed] = useState(null) + + const groups = MUSCLE_GROUPS.filter(g => picked.includes(g.key)) + const toggle = key => setPicked(p => (p.includes(key) ? p.filter(k => k !== key) : [...p, key])) + + const generate = async () => { + setStep('working') + setFailed(null) + try { + const intake = buildIntake({ muscles: groups, cardio, intensity, equipment: profile?.equipment || [], limitations: profile?.limitations || '' }) + await requestPlan(intake) + const pending = await awaitCoachJob() + const built = routineFrom(pending.bundle, { fallbackName: muscleWords(groups).join(' + ') }) + if (!built || !built.ex.length) throw Object.assign(new Error(''), { code: 'unusable' }) + setRoutine(built) + setStep('ready') + } catch (e) { + setFailed(jobErrorText(e.code || 'provider', e.message)) + setStep('failed') + } + } + + const apply = () => { + const id = uid() + update(s => { s.routines.push({ id, name: routine.name, emoji: routine.emoji, ...(routine.prog ? { prog: routine.prog } : {}), ex: routine.ex }) }) + close() + toast(t('“{0}” added to your plan', routine.name)) + nav('/plan/r/' + id) + } + + if (step === 'working') return <> +

{t('Building your routine…')}

+
+ {t('The Coach is choosing exercises for {0}. This usually takes a few seconds.', muscleWords(groups).join(', ') || t('your session'))} +
+
{t('Thinking…')}
+ + + if (step === 'failed') return <> +

{t('The Coach could not build that')}

+
{failed}
+
+ +
+ + + + if (step === 'ready') return <> +

{routine.emoji} {routine.name}

+
{exCount(routine.ex.length)}
+
+ {routine.ex.map((e, i) =>
+ {exerciseNameFor(EXIDX[e.id] || { id: e.id, n: e.id })} + {exLine(e, st.unit)} +
)} +
+
+ +
+ + + + if (step === 'cardio') return <> +

{t('Start with cardio?')}

+
{t('A warm-up before the first working set.')}
+
+ + +
+
+ + + + if (step === 'intensity') return <> +

{t('How hard should it be?')}

+
+ {t('Sets and reps for each exercise, and how long the session runs.')} +
+
+ {INTENSITIES.map(l => )} +
+
+ +
+ + + + return <> +

{t('Which muscles?')}

+
+ {t('Pick one or two — usually a big muscle and the arms that help it.')} +
+
+ {MUSCLE_GROUPS.map(g => )} +
+
+ + {!picked.length &&
{t('Pick at least one muscle.')}
} + +} +export function aiRoutineSheet() { + return ui().openSheet(close => ) +} + + /* ============================ import from another app ============================ */ // Shows what a parsed export would actually do before anything is written. An import is // the one action where "just try it" is expensive — it's someone's entire training diff --git a/frontend/src/views/RoutineEdit.jsx b/frontend/src/views/RoutineEdit.jsx index b6b18d1..3a817d8 100644 --- a/frontend/src/views/RoutineEdit.jsx +++ b/frontend/src/views/RoutineEdit.jsx @@ -8,10 +8,13 @@ import { uid } from '../lib/format.js' import { t, exerciseNameFor } from '../lib/i18n.js' import { supersetUnits, moveSupersetUnit, cleanupSg, exLine, defaultConfig } from '../lib/history.js' import { Thumb } from '../components/Media.jsx' -import { glyphPicker, exercisePicker, exConfigSheet, confirmSheet } from '../sheets.jsx' +import { glyphPicker, exercisePicker, exConfigSheet, confirmSheet, aiRoutineSheet } from '../sheets.jsx' import Icon from '../components/Icon.jsx' import { glyphOf } from '../lib/glyphs.js' import { Button, Row, SelectRow, Switch } from '../components/ui.jsx' +import { coachAvailable } from '../lib/coach.js' +import { DEMO } from '../lib/demo.js' +import { MOBILE } from '../lib/mobile.js' import SwipeToDelete from '../components/SwipeToDelete.jsx' import { copyRoutine } from '../lib/routines.js' import { POLICIES_FOR, POLICY_NAME, POLICY_DESC } from '../lib/progression.js' @@ -309,6 +312,13 @@ export default function RoutineEdit() { const S = useStore(s => s.S) const update = useStore(s => s.update) const toast = useUI(s => s.toast) + // Same predicate every other Coach surface uses: an instance without the feature, or a profile + // that has not agreed to it, sees exactly the editor it saw before — no button that leads to a + // screen which then refuses. + const config = useStore(s => s.config) + const user = useStore(s => s.user) + const coachMode = useStore(s => s.coachLocal?.mode) + const coachEnabled = coachAvailable(config, user, { demo: DEMO, mobile: MOBILE, coachMode }) const r = S.routines.find(x => x.id === id) useEffect(() => { if (!r) nav('/plan') }, [!!r]) // Editing here has no explicit "save" — every field change persists immediately. A single @@ -438,6 +448,13 @@ export default function RoutineEdit() { exConfigSheet(ex, null, cfg => edit(x => { x.push({ id: ex.id, ...cfg }) }), null, r) } })} icon="plus">{t('Add exercise')} + {/* Below "Add exercise", because it is the same thing done differently: this asks for the + muscles and the effort and lets the Coach fill the routine in, which is a faster way to + get a session than picking ten exercises one at a time. It adds a NEW routine rather than + filling this one — the questions are about a session you are about to build, and quietly + replacing the routine somebody opened would be the wrong guess. */} +
+