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 routine icons and balance plan exercise candidates

Ameer Khan043dd3031af8
diff --git a/api/coach/core/library.js b/api/coach/core/library.js
index 8058e03dc..cdc392533 100644
--- a/api/coach/core/library.js
+++ b/api/coach/core/library.js
@@ -16,9 +16,9 @@ export const libraryName = id => LIB_BY_ID.get(id)?.n || null;
/* ---------- the library slice the model gets to choose from ----------
Bounded. The whole catalogue is 1,324 rows — 10k+ tokens on every job, which costs real money
against a cloud API and does not fit a small local model's context at all; and a model does
- not choose better from 1,324 options than from 160. So the slice is capped and balanced: an
- even share of every body part, in catalogue order (deterministic, so repeated jobs keep the
- same prefix), with the exercises already in the user's plan or history always included —
+ not choose better from 1,324 options than from 160. So the slice is capped and balanced: a
+ weighted share of every body part, in catalogue order (deterministic, so repeated jobs keep
+ the same prefix), with the exercises already in the user's plan or history always included —
a review has to be able to name what it is talking about. */
export const MAX_LIBRARY = 160;
@@ -26,6 +26,36 @@ export const MAX_LIBRARY = 160;
// fields beyond body part never appear in a rationale and cost ~30 tokens an entry.
const slim = e => ({ id: e.id, n: e.n, bp: e.bp, ...(e.custom ? { custom: true } : {}) });
+/* Mobility work is not what a plan is built from, and at an even share per body part the
+ catalogue's 57 stretches crowded out the lifts that are: a first plan for someone who
+ stated no equipment arrived with "upper legs" as five stretches, a balance board and some
+ band work — no squat, no hinge, no lunge anywhere in the lane.
+
+ Dropped from the candidate pool, never from the catalogue. One already in someone's plan or
+ history is pinned by `keep` below and still travels, because a review has to be able to name
+ what it is talking about, and the validator still accepts every id the catalogue holds.
+
+ The word boundary is what stops this being a silent data bug: "single leg bridge with
+ outstretched leg" is a glute exercise, not a stretch. */
+export const isStretch = e => /\bstretch(es|ing)?\b/i.test((e && e.n) || '');
+
+/* ---------- what each body part is worth in candidates ----------
+ An equal lane per body part reads fair and is not: it spent as many of the 160 slots on
+ "lower arms" (37 rows, wrist curls to a one) as on "chest", and gave "neck" (two rows, both
+ stretches) a lane of its own. A plan is not drawn from an even spread of the catalogue's
+ taxonomy, so the lanes are weighted by how much programming actually draws on them.
+
+ These are shares, not quotas — a lane that runs out hands its remainder to the others, which
+ is what keeps a narrow equipment filter from returning a short slice. Anything not listed
+ gets 1, so a body part added to the catalogue later still appears rather than vanishing. */
+const LANE_WEIGHT = {
+ 'back': 4, 'chest': 4, 'upper legs': 4,
+ 'shoulders': 3,
+ 'upper arms': 2, 'waist': 2,
+ 'cardio': 1, 'lower arms': 1, 'lower legs': 1, 'neck': 1
+};
+const laneWeight = bp => LANE_WEIGHT[bp] ?? 1;
+
export function librarySlice(S, equipment, { keep = [], max = MAX_LIBRARY } = {}) {
const wanted = (equipment || []).map(x => String(x).toLowerCase());
const customs = (S.customEx || []).map(c => ({ id: c.id, n: c.n, bp: c.bp, tg: null, eq: 'custom', custom: true }));
@@ -33,7 +63,11 @@ export function librarySlice(S, equipment, { keep = [], max = MAX_LIBRARY } = {}
// leave the Coach unable to propose anything at all, which is a worse failure than a
// slightly larger payload.
const filtered = wanted.length ? LIBRARY.filter(e => wanted.includes((e.eq || '').toLowerCase())) : LIBRARY;
- const base = filtered.length ? filtered : LIBRARY;
+ const equipped = filtered.length ? filtered : LIBRARY;
+ // Same reasoning as the equipment fallback: a filter that removed everything is not a filter
+ // worth honouring. Someone whose only kit reaches nothing but stretches gets the stretches.
+ const lifts = equipped.filter(e => !isStretch(e));
+ const base = lifts.length ? lifts : equipped;
const pinned = new Set(keep.filter(id => LIB_BY_ID.has(id)));
const out = [];
@@ -44,18 +78,26 @@ export function librarySlice(S, equipment, { keep = [], max = MAX_LIBRARY } = {}
if (base.length + out.length <= max) {
base.forEach(add);
} else {
- // Round-robin across body parts so a 292-row "upper arms" cannot crowd out a 37-row
- // "lower arms"; order within a body part is the catalogue's own.
+ // Weighted round-robin across body parts, so a 292-row "upper arms" cannot crowd out a
+ // 37-row "lower arms" and a 37-row "lower arms" cannot claim as much room as "chest";
+ // order within a body part is the catalogue's own. Lanes are visited in sorted key order
+ // and each takes its weight per pass, so the slice stays deterministic.
const groups = new Map();
for (const e of base) { if (!groups.has(e.bp)) groups.set(e.bp, []); groups.get(e.bp).push(e); }
- const lanes = [...groups.keys()].sort().map(k => groups.get(k));
+ const keys = [...groups.keys()].sort();
+ const lanes = keys.map(k => groups.get(k));
+ const weights = keys.map(laneWeight);
const cursor = lanes.map(() => 0);
let progressed = true;
while (out.length < max && progressed) {
progressed = false;
for (let i = 0; i < lanes.length && out.length < max; i++) {
- while (cursor[i] < lanes[i].length && taken.has(lanes[i][cursor[i]].id)) cursor[i]++;
- if (cursor[i] < lanes[i].length) { add(lanes[i][cursor[i]++]); progressed = true; }
+ for (let n = 0; n < weights[i] && out.length < max; n++) {
+ while (cursor[i] < lanes[i].length && taken.has(lanes[i][cursor[i]].id)) cursor[i]++;
+ if (cursor[i] >= lanes[i].length) break; // lane spent; its share flows to the rest
+ add(lanes[i][cursor[i]++]);
+ progressed = true;
+ }
}
}
}
diff --git a/api/coach/core/payload.js b/api/coach/core/payload.js
index a1c144526..4727e0fe7 100644
--- a/api/coach/core/payload.js
+++ b/api/coach/core/payload.js
@@ -10,7 +10,7 @@
* handle stands in), passkey and credential material, push subscriptions, invite data, theme
* and appearance settings, and every other profile's everything.
*/
-import { LIBRARY, LIB_BY_ID, libraryHas, libraryName, librarySlice, MAX_LIBRARY } from './library.js';
+import { LIBRARY, LIB_BY_ID, libraryHas, libraryName, librarySlice, isStretch, MAX_LIBRARY } from './library.js';
export const CONTRACT = 1;
// Bounds from FR-22. A review reads a training block, not a training career: more history
@@ -153,7 +153,7 @@ export function cleanPlan(S) {
}
// The catalogue lives in library.js; re-exported so older imports keep resolving.
-export { LIBRARY, MAX_LIBRARY, libraryHas, libraryName, librarySlice };
+export { LIBRARY, MAX_LIBRARY, libraryHas, libraryName, librarySlice, isStretch };
/* ---------- effort scale (mirrors history.js effortOf) ---------- */
const effortOf = S => {
diff --git a/api/coach/core/validate.js b/api/coach/core/validate.js
index 17c5b9964..f0e3d332d 100644
--- a/api/coach/core/validate.js
+++ b/api/coach/core/validate.js
@@ -46,6 +46,10 @@ const isStr = v => typeof v === 'string' && v.trim().length > 0;
const isNum = v => typeof v === 'number' && Number.isFinite(v);
const isInt = (v, lo, hi) => Number.isInteger(v) && v >= lo && v <= hi;
const clampStr = (v, n) => String(v == null ? '' : v).slice(0, n);
+// A routine's `emoji` holds an icon key now ('figureStrength'), a legacy emoji only on old state —
+// and the model copies whichever it sees in the plan. Eight characters was sized for an emoji and
+// cut keys to 'figureSt'. The client's glyphOf() maps anything unknown to the default icon.
+const glyphStr = v => clampStr(v || '🏋️', 32);
/* ---------- the two v1.2.4 flags, enforced rather than merely accepted ----------
`prompts/common.md` tells the model that unilateral work is prescribed as the total across
@@ -154,7 +158,7 @@ export function validatePlan(data, ctx = {}) {
routines.push({
id: rid,
name: clampStr(r.name || 'Routine', 40),
- emoji: clampStr(r.emoji || '🏋️', 8),
+ emoji: glyphStr(r.emoji),
...(POLICIES.includes(r.prog) ? { prog: r.prog } : {}),
...(isStr(r.why) ? { why: clampStr(r.why, 400) } : {}),
ex
@@ -395,7 +399,7 @@ export function validateReview(data, plan, ctx = {}) {
const odd = ex.find(e => e.side && isInt(e.reps, 1, 100) && e.reps % 2);
if (odd) { errors.push(ODD_PER_SIDE(`${where}.after.ex "${odd.id}"`)); return; }
out.after = {
- name: clampStr(a.name, 40), emoji: clampStr(a.emoji || '🏋️', 8),
+ name: clampStr(a.name, 40), emoji: glyphStr(a.emoji),
...(POLICIES.includes(a.prog) ? { prog: a.prog } : {}),
ex: ex.map(e => ({
id: e.id, name: libraryName(e.id),
diff --git a/api/test/payload.test.js b/api/test/payload.test.js
index 5a643e6f1..db9a393ea 100644
--- a/api/test/payload.test.js
+++ b/api/test/payload.test.js
@@ -129,10 +129,9 @@ test('the library slice is capped, balanced across body parts, deterministic, an
all.forEach(e => { byBp[e.bp] = (byBp[e.bp] || 0) + 1; });
const parts = Object.keys(byBp).length;
assert.ok(parts >= 8, `only ${parts} body parts represented`);
- // Small groups (neck has two rows) run out early and their share flows to the rest, so the
- // bound is "nobody dominates", not "everyone equal".
+ // Lanes are weighted, not equal, and a lane that runs out hands its share to the rest — so
+ // the bound is "nobody dominates", not "everyone equal".
assert.ok(Math.max(...Object.values(byBp)) <= MAX_LIBRARY / 4, `one body part dominates: ${JSON.stringify(byBp)}`);
- assert.equal(byBp.neck, LIBRARY.filter(e => e.bp === 'neck').length, 'a tiny group is present in full');
assert.deepEqual(all.map(e => e.id), payload.librarySlice({}, []).map(e => e.id), 'same slice every time');
// An exercise the user already trains rides along even when the filter would exclude it.
@@ -149,6 +148,52 @@ test('the library slice is capped, balanced across body parts, deterministic, an
assert.ok(p.library.length <= MAX_LIBRARY + planIds.length);
});
+test('the lanes are weighted by what a plan is actually built from', () => {
+ const byBp = {};
+ payload.librarySlice({}, []).forEach(e => { byBp[e.bp] = (byBp[e.bp] || 0) + 1; });
+ // The regression this encodes: at an equal share, "lower arms" (37 rows of wrist curls) took
+ // as many of the 160 slots as "chest", and "neck" (two rows) held a lane of its own.
+ for (const heavy of ['chest', 'back', 'upper legs']) {
+ for (const light of ['lower arms', 'lower legs', 'cardio']) {
+ assert.ok(byBp[heavy] > byBp[light],
+ `${heavy} (${byBp[heavy]}) should outweigh ${light} (${byBp[light]})`);
+ }
+ }
+ // Every lane that survives the stretch filter is still represented — weighting narrows the
+ // share, it does not evict a body part.
+ for (const bp of ['lower arms', 'lower legs', 'cardio', 'waist', 'shoulders', 'upper arms']) {
+ assert.ok(byBp[bp] > 0, `${bp} fell out of the slice entirely`);
+ }
+});
+
+test('stretches are dropped from the candidate pool but not from the catalogue', () => {
+ const { LIBRARY, librarySlice, isStretch } = payload;
+ assert.ok(LIBRARY.some(isStretch), 'the catalogue has stretches, or this test proves nothing');
+ assert.ok(!librarySlice({}, []).some(isStretch), 'a stretch reached the slice');
+ assert.ok(!librarySlice({}, ['body weight']).some(isStretch));
+
+ // "outstretched" is not "stretch" — dropping this one would be a silent data bug.
+ const bridge = LIBRARY.find(e => e.n === 'single leg bridge with outstretched leg');
+ assert.ok(bridge && !isStretch(bridge), 'a glute exercise was read as a stretch');
+
+ // One already in the plan or history is pinned, and still travels: a review has to be able
+ // to name what it is talking about.
+ const stretch = LIBRARY.find(isStretch);
+ const kept = librarySlice({}, [], { keep: [stretch.id] });
+ assert.equal(kept[0].id, stretch.id, 'a stretch the user trains was dropped');
+});
+
+test('a first plan for someone who stated no equipment reaches the staple lifts', () => {
+ // The bug: an even share in catalogue (alphabetical) order gave "upper legs" five stretches,
+ // a balance board and some band work — no squat, no hinge, no lunge in the lane at all.
+ const names = payload.librarySlice({}, []).map(e => e.n);
+ const has = re => names.some(n => re.test(n));
+ assert.ok(has(/squat/i), 'no squat of any kind');
+ assert.ok(has(/deadlift/i), 'no hinge of any kind');
+ assert.ok(has(/bench press/i), 'no horizontal press');
+ assert.ok(has(/\brow\b/i), 'no horizontal pull');
+});
+
test('equipment nobody in the library has still yields a usable library', () => {
// Better a slightly larger payload than a Coach that cannot propose anything at all.
assert.ok(payload.librarySlice({}, ['moon rocks']).length > 0);
diff --git a/api/test/validate.test.js b/api/test/validate.test.js
index 1776dca9d..c33bea97f 100644
--- a/api/test/validate.test.js
+++ b/api/test/validate.test.js
@@ -55,6 +55,16 @@ test('a plan may reference a custom exercise it defines in the same answer', ()
assert.equal(r.bundle.customEx[0].n, 'Sandbag carry');
});
+test('a routine icon key survives whole, in a created plan and in an added routine', () => {
+ // Routines store icon keys; clamped to emoji length, 'figureStrength' reached the chat as 'figureSt'.
+ const plan = validatePlan({ routines: [{ id: 'r1', name: 'Chest', emoji: 'figureStrength', ex: [{ id: '0001', sets: 3, reps: 10 }] }] });
+ assert.equal(plan.ok, true);
+ assert.equal(plan.bundle.routines[0].emoji, 'figureStrength');
+ const added = review([change({ type: 'add-routine', target: {}, after: { name: 'C', emoji: 'figureStrength', ex: [{ id: '0001', sets: 3, reps: 10 }] } })]);
+ assert.equal(added.ok, true);
+ assert.equal(added.proposal.changes[0].after.emoji, 'figureStrength');
+});
+
test('the week may only point at routines the plan actually defines', () => {
const r = validatePlan({ routines: [{ id: 'r1', name: 'A', ex: [{ id: '0001', sets: 3, reps: 10 }] }], week: { 1: 'ghost' } });
assert.equal(r.ok, false);
diff --git a/frontend/src/coach.css b/frontend/src/coach.css
index f5e8e15f5..193f700bc 100644
--- a/frontend/src/coach.css
+++ b/frontend/src/coach.css
@@ -130,13 +130,13 @@
.pcard-tabs{display:flex;gap:6px;overflow-x:auto;padding:12px 18px 4px;scrollbar-width:none}
.pcard-tabs::-webkit-scrollbar{display:none}
.pcard-tab{
- flex:none;padding:8px 14px;border-radius:99px;background:var(--surface-2);color:var(--label-2);
+ flex:none;display:inline-flex;align-items:center;gap:6px;padding:8px 14px;border-radius:99px;background:var(--surface-2);color:var(--label-2);
font-size:14px;font-weight:500;transition:all var(--fast);white-space:nowrap
}
.pcard-tab.on{background:var(--label);color:var(--bg)}
.pcard-rt{padding:10px 18px 4px}
.pcard-rt-h{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
-.pcard-rt-h b{font-size:18px;font-weight:600;letter-spacing:-.015em}
+.pcard-rt-h b{display:inline-flex;align-items:center;gap:8px;font-size:18px;font-weight:600;letter-spacing:-.015em}
.pcard-rt-h span{font-size:13px;color:var(--label-2);white-space:nowrap}
.pcard-why{font-size:14px;color:var(--label-2);line-height:1.45;margin:4px 0 8px}
.pcard-ex{padding:11px 0;border-top:var(--hair) solid var(--sep)}
diff --git a/frontend/src/views/CoachChat.jsx b/frontend/src/views/CoachChat.jsx
index c5bcea349..bd4b76085 100644
--- a/frontend/src/views/CoachChat.jsx
+++ b/frontend/src/views/CoachChat.jsx
@@ -30,6 +30,7 @@ import { insightsFor, sessionInsights } from '../lib/coach-insights.js'
import { useCoachStatus, requestReview, requestDebrief, requestPlan, refinePlan, resolvePending, cohortStats, setCohortShare, jobErrorText } from '../lib/coach-api.js'
import { confirmSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
+import { glyphOf } from '../lib/glyphs.js'
import LineChart from '../components/LineChart.jsx'
import { Button, Check, Switch, Section, Row, SelectRow } from '../components/ui.jsx'
import '../coach.css'
@@ -130,7 +131,7 @@ export default function CoachChat() {
const pickRoutine = () => openSheet(close => <div className="chat-menu">
<h3>{t('Improve which routine?')}</h3>
<div className="sect-b">
- {(S.routines || []).map(r => <Row key={r.id} icon="dumbbell" iconTint="var(--acc)" title={`${r.emoji || ''} ${r.name}`.trim()} subtitle={t('{0} exercises', (r.ex || []).length)} accessory="chevron" onClick={() => { close(); askImprove(r) }} />)}
+ {(S.routines || []).map(r => <Row key={r.id} icon={glyphOf(r.emoji)} iconTint="var(--acc)" title={r.name} subtitle={t('{0} exercises', (r.ex || []).length)} accessory="chevron" onClick={() => { close(); askImprove(r) }} />)}
{!(S.routines || []).length && <div className="chat-empty">{t('You have no routines yet — ask the Coach for a plan first.')}</div>}
</div>
<div style={{ height: 10 }} />
@@ -327,7 +328,7 @@ function PlanCard({ p, S, update, toast, nav, refresh }) {
<WeekStrip days={weekDays} />
{b.routines.length > 1 && <div className="pcard-tabs">
- {b.routines.map((x, i) => <button key={x.id || i} className={'pcard-tab' + (i === tab ? ' on' : '')} onClick={() => setTab(i)}>{x.emoji} {x.name}</button>)}
+ {b.routines.map((x, i) => <button key={x.id || i} className={'pcard-tab' + (i === tab ? ' on' : '')} onClick={() => setTab(i)}><Icon name={glyphOf(x.emoji)} />{x.name}</button>)}
</div>}
{r && <RoutineBlock r={r} unit={S.unit} />}
@@ -351,7 +352,7 @@ const WeekStrip = ({ days }) => <div className="pcard-week">
</div>
const RoutineBlock = ({ r, unit }) => <div className="pcard-rt">
- <div className="pcard-rt-h"><b>{r.emoji} {r.name}</b><span>{t('{0} exercises', r.ex.length)}</span></div>
+ <div className="pcard-rt-h"><b><Icon name={glyphOf(r.emoji)} />{r.name}</b><span>{t('{0} exercises', r.ex.length)}</span></div>
{!!r.why && <div className="pcard-why">{r.why}</div>}
{r.ex.map((e, i) => <div key={i} className="pcard-ex">
<div className="pcard-ex-r"><span className="pcard-ex-n">{exName(e.id)}</span><span className="pcard-ex-l">{exLine(e, unit)}</span></div>
@@ -626,7 +627,7 @@ function ProposalDetail({ entry, S }) {
{kind === 'create' && b && <>
<WeekStrip days={weekDays} />
{b.routines.length > 1 && <div className="pcard-tabs" style={{ paddingLeft: 0, paddingRight: 0 }}>
- {b.routines.map((x, i) => <button key={x.id || i} className={'pcard-tab' + (i === tab ? ' on' : '')} onClick={() => setTab(i)}>{x.emoji} {x.name}</button>)}
+ {b.routines.map((x, i) => <button key={x.id || i} className={'pcard-tab' + (i === tab ? ' on' : '')} onClick={() => setTab(i)}><Icon name={glyphOf(x.emoji)} />{x.name}</button>)}
</div>}
{r && <RoutineBlock r={r} unit={S.unit} />}
<p className="pcard-sum" style={{ fontSize: 13 }}>{entry.scheduled ? t('Your week was set to this schedule.') : t('Imported without changing your week.')}</p>