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.

Floating coach week: the week's sessions are a queue, the next coach week follows completion

Boris Kurktchiev2315f0ef7fa5
diff --git a/api/Dockerfile b/api/Dockerfile
index 3db39e238..80b90f296 100644
--- a/api/Dockerfile
+++ b/api/Dockerfile
@@ -53,7 +53,7 @@ RUN npm ci --omit=dev --omit=optional && npm cache clean --force
# Every module server.js imports from the api root has to be named here: the image carries nothing
# else, and one that is missing only shows at boot, as ERR_MODULE_NOT_FOUND.
-COPY server.js push-messages.js verify-error.js password.js rate-limit.js passkeys-store.js device-link.js media.js ./
+COPY server.js push-messages.js verify-error.js password.js rate-limit.js passkeys-store.js device-link.js media.js queue.js ./
COPY coach ./coach
ENV NODE_ENV=production
ENV PORT=3000
diff --git a/api/openapi.yaml b/api/openapi.yaml
index abb279e45..0f87205b1 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -3181,6 +3181,10 @@ components:
routines:
type: array
items: { $ref: '#/components/schemas/Routine' }
+ queue:
+ type: object
+ nullable: true
+ description: A planner's floating week {ids, since, startsOn, label} — the week's sessions as an ordered queue, the first undone one is today's. Written only by an API client (never by the app), read by the reminder tick.
week:
type: object
description: 'Weekly plan: weekday (0=Sunday … 6) → routine id.'
diff --git a/api/queue.js b/api/queue.js
new file mode 100644
index 000000000..f01fe30d9
--- /dev/null
+++ b/api/queue.js
@@ -0,0 +1,54 @@
+// Floating coach week — the "what's next" rule for web-push reminders. Hand-copied (not
+// imported) from frontend/src/lib/queue.js / lib/history.js: the same DONE RULE on both sides,
+// kept as a tiny standalone module here (rather than inline in server.js) so it can be
+// unit-tested without booting the whole server. `S.queue` is written by a planner — any API
+// client that PUTs state with a queue (a coaching agent, a script) — never by the app itself.
+//
+// DONE RULE: a queue session counts as done once a finished workout on its routine exists,
+// started at/after the queue was applied (`S.queue.since`) — or a "past workout" logged with an
+// early clock but DATED inside the week (on or after `startsOn`) whose merged name (`'A + B'`)
+// names the routine under its current title. The date bound keeps a past week's workout, which
+// a planner's reused ids and names can make look identical, from counting. Only finished
+// workouts (`S.workouts`) count; an in-progress session never does. Missed sets are the
+// planner's business, not the queue's.
+function routineIdsOf(w) {
+ return Array.isArray(w.routineIds) ? w.routineIds : (w.routineId ? [w.routineId] : []);
+}
+function nameParts(w) {
+ return String(w.name || '').split(' + ');
+}
+function queueDone(S, id, startsOn) {
+ const currentName = (S.routines || []).find(r => r?.id === id)?.name;
+ return (S.workouts || []).some(w => routineIdsOf(w).includes(id)
+ && ((w.start ?? 0) >= S.queue.since || (String(w.d || '') >= startsOn && nameParts(w).includes(currentName))));
+}
+// The reminder tick only ever asks "what's next right now" — there is no separate "today" to
+// preview a different date against, so `today` in the spec's `next(iso, today)` is just `iso`.
+// That collapses `iso === max(today, startsOn)` to the equivalent, simpler `iso >= startsOn`.
+function queueNext(S, iso) {
+ const q = S.queue;
+ if (!q || typeof q !== 'object' || !Array.isArray(q.ids)) return null;
+ // A missing startsOn means active now; a session whose routine was deleted is dropped from the
+ // week (the frontend's queue.js does the same — it could never be started or logged).
+ const startsOn = typeof q.startsOn === 'string' ? q.startsOn : new Date(q.since || 0).toISOString().slice(0, 10);
+ if (iso < startsOn) return null;
+ const ids = q.ids.filter(id => (S.routines || []).some(r => r?.id === id));
+ const remaining = ids.filter(id => !queueDone(S, id, startsOn));
+ return remaining.length ? remaining[0] : null;
+}
+
+// A weekday can hold a routine-id list (combine routines); the reminder only needs the first.
+// The `?.` on each routine entry is this copy's own: it reads whatever is on disk, including a
+// file written before PUT /api/data dropped null entries.
+// Per-date overrides win outright ('rest' -> null; an explicit routine id -> that id); otherwise
+// a live queue's next session wins over the plain weekday assignment, falling back to the weekday
+// only once the queue is finished, not yet started, or absent.
+export function effectiveRoutineId(S, iso) {
+ const ov = S.dayPlan?.[iso];
+ if (ov === 'rest') return null;
+ if (ov && S.routines?.some(r => r?.id === ov)) return ov;
+ const q = queueNext(S, iso);
+ if (q) return q;
+ const wd = new Date(iso + 'T12:00:00').getDay();
+ return [].concat(S.week?.[wd] || []).find(id => S.routines?.some(r => r?.id === id)) || null;
+}
diff --git a/api/server.js b/api/server.js
index debdd4840..0ccbb4108 100644
--- a/api/server.js
+++ b/api/server.js
@@ -31,6 +31,7 @@ import {
} from './passkeys-store.js';
import { createDeviceLink, findDeviceLink, burnDeviceLink, dropDeviceLinks } from './device-link.js';
import { createMediaStore, mediaLimits, mediaConfig, MediaError, HASH_RE } from './media.js';
+import { effectiveRoutineId } from './queue.js';
const PORT = +(process.env.PORT || 3000);
const DATA = process.env.DATA_DIR || '/data';
@@ -318,16 +319,7 @@ function cancelRestTimer(userId, deviceId) {
const deviceIdOf = v => (typeof v === 'string' && /^[A-Za-z0-9_-]{8,64}$/.test(v) ? v : undefined);
// "Workout planned today" reminder — one per user per day, at their chosen time.
-// Duplicated (not imported) from frontend/src/lib/history.js effectiveRoutineId — tiny pure helper, not worth sharing across the two runtimes.
-// The `?.` on each entry is this copy's own: it reads whatever is on disk, including a file written before PUT /api/data dropped null entries.
-// A weekday can hold a routine-id list (combine routines); the reminder only needs the first.
-function effectiveRoutineId(S, iso) {
- const ov = S.dayPlan?.[iso];
- if (ov === 'rest') return null;
- if (ov && S.routines?.some(r => r?.id === ov)) return ov;
- const wd = new Date(iso + 'T12:00:00').getDay();
- return [].concat(S.week?.[wd] || []).find(id => S.routines?.some(r => r?.id === id)) || null;
-}
+// effectiveRoutineId (queue-aware) lives in ./queue.js — see there for the DONE RULE.
// Computes "now" in an arbitrary IANA zone (e.g. "Europe/Lisbon") instead of the server's own —
// each user's reminder fires by their own clock, wherever they and their phone actually are.
function userNow(tz) {
diff --git a/api/test/queue.test.js b/api/test/queue.test.js
new file mode 100644
index 000000000..853e5fd82
--- /dev/null
+++ b/api/test/queue.test.js
@@ -0,0 +1,109 @@
+// Floating coach week — effectiveRoutineId() queue rule, used by the day-reminder tick in
+// server.js. Pure function, no server needed: the tick only calls this one export.
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { effectiveRoutineId } from '../queue.js';
+
+const routines = [
+ { id: 'r1', name: 'Push' },
+ { id: 'r2', name: 'Pull' },
+ { id: 'r3', name: 'Legs' },
+];
+const base = { routines, dayPlan: {}, week: {}, workouts: [] };
+
+test('no queue: unchanged weekday/override behaviour', () => {
+ const S = { ...base, week: { 1: 'r1' }, dayPlan: { '2026-09-09': 'rest', '2026-09-10': 'r2' } };
+ assert.equal(effectiveRoutineId(S, '2026-09-07'), 'r1'); // Monday -> week[1]
+ assert.equal(effectiveRoutineId(S, '2026-09-09'), null); // rest override
+ assert.equal(effectiveRoutineId(S, '2026-09-10'), 'r2'); // routine override
+ assert.equal(effectiveRoutineId(S, '2026-09-08'), null); // Tuesday, nothing planned
+});
+
+test('queue: returns the first not-done session once startsOn is reached', () => {
+ const S = { ...base, queue: { ids: ['r1', 'r2', 'r3'], since: 1000, startsOn: '2026-09-07', label: 'W1' } };
+ assert.equal(effectiveRoutineId(S, '2026-09-07'), 'r1');
+ assert.equal(effectiveRoutineId(S, '2026-09-08'), 'r1'); // still first undone, any later day
+});
+
+test('queue: waiting for startsOn falls back to the weekday answer', () => {
+ const S = {
+ ...base,
+ week: { 6: 'r3' }, // Saturday
+ queue: { ids: ['r1', 'r2'], since: 1000, startsOn: '2026-09-14', label: 'W2' },
+ };
+ // 2026-09-12 is a Saturday, still before the Monday startsOn: the queue has nothing to say
+ // yet, so the plain weekday assignment for that day shows through instead of going quiet.
+ assert.equal(effectiveRoutineId(S, '2026-09-12'), 'r3');
+ assert.equal(effectiveRoutineId(S, '2026-09-11'), null); // Friday, no weekday plan either
+});
+
+test('queue: a session is done once a finished workout on it landed at/after since', () => {
+ const S = {
+ ...base,
+ queue: { ids: ['r1', 'r2', 'r3'], since: 1000, startsOn: '2026-09-07', label: 'W1' },
+ workouts: [{ d: '2026-09-07', start: 2000, routineIds: ['r1'], name: 'Push' }],
+ };
+ assert.equal(effectiveRoutineId(S, '2026-09-08'), 'r2'); // r1 done, r2 is next
+});
+
+test('queue: a workout logged before "since" counts only when it is dated inside the week and its name still matches', () => {
+ const S = {
+ ...base,
+ queue: { ids: ['r1', 'r2'], since: 5000, startsOn: '2026-09-07', label: 'W1' },
+ workouts: [{ d: '2026-09-07', start: 1000, routineId: 'r1', name: 'Push' }], // early clock, dated in the week, name matches -> done
+ };
+ assert.equal(effectiveRoutineId(S, '2026-09-07'), 'r2');
+ const S0 = {
+ ...base,
+ queue: { ids: ['r1', 'r2'], since: 5000, startsOn: '2026-09-07', label: 'W1' },
+ workouts: [{ d: '2026-09-02', start: 1000, routineId: 'r1', name: 'Push' }], // a past week's session with the same name -> not done
+ };
+ assert.equal(effectiveRoutineId(S0, '2026-09-07'), 'r1');
+
+ const S2 = {
+ ...base,
+ queue: { ids: ['r1', 'r2'], since: 5000, startsOn: '2026-09-07', label: 'W1' },
+ workouts: [{ d: '2026-09-06', start: 1000, routineId: 'r1', name: 'Old Push Name' }], // before since, name stale -> not done
+ };
+ assert.equal(effectiveRoutineId(S2, '2026-09-07'), 'r1');
+});
+
+test('queue: keeps slot order even when a later session is logged out of order', () => {
+ const S = {
+ ...base,
+ queue: { ids: ['r1', 'r2', 'r3'], since: 1000, startsOn: '2026-09-07', label: 'W1' },
+ workouts: [{ d: '2026-09-07', start: 2000, routineIds: ['r2'], name: 'Pull' }],
+ };
+ assert.equal(effectiveRoutineId(S, '2026-09-08'), 'r1'); // r2 done out of order, r1 is still first undone
+});
+
+test('queue: complete week falls back to the weekday answer', () => {
+ const S = {
+ ...base,
+ week: { 1: 'r3' },
+ queue: { ids: ['r1', 'r2'], since: 1000, startsOn: '2026-09-07', label: 'W1' },
+ workouts: [
+ { d: '2026-09-07', start: 2000, routineIds: ['r1'], name: 'Push' },
+ { d: '2026-09-08', start: 3000, routineIds: ['r2'], name: 'Pull' },
+ ],
+ };
+ assert.equal(effectiveRoutineId(S, '2026-09-14'), 'r3'); // Monday, week complete -> weekday plan shows through
+});
+
+test('queue: per-date overrides still win over the queue', () => {
+ const S = {
+ ...base,
+ dayPlan: { '2026-09-07': 'rest' },
+ queue: { ids: ['r1', 'r2'], since: 1000, startsOn: '2026-09-07', label: 'W1' },
+ };
+ assert.equal(effectiveRoutineId(S, '2026-09-07'), null);
+});
+
+test('queue: a session whose routine was deleted is dropped; a missing startsOn means active now', () => {
+ const S = { ...base, queue: { ids: ['gone', 'r1', 'r2'], since: 1000, startsOn: '2026-09-07', label: 'W1' } };
+ assert.equal(effectiveRoutineId(S, '2026-09-08'), 'r1');
+ const noStart = { ...base, queue: { ids: ['r2'], since: 1000, label: 'W1' } };
+ assert.equal(effectiveRoutineId(noStart, '2026-09-08'), 'r2');
+ const bad = { ...base, week: { 2: 'r3' }, queue: { ids: 'r1' } };
+ assert.equal(effectiveRoutineId(bad, '2026-09-08'), 'r3'); // Tuesday: a malformed queue reads as none
+});
diff --git a/frontend/src/components/QueueRow.jsx b/frontend/src/components/QueueRow.jsx
new file mode 100644
index 000000000..8af3f654d
--- /dev/null
+++ b/frontend/src/components/QueueRow.jsx
@@ -0,0 +1,39 @@
+import { queueView } from '../lib/queue.js'
+import { effectiveRoutineIds } from '../lib/history.js'
+import { fmtDate } from '../lib/format.js'
+import { t } from '../lib/i18n.js'
+import Icon from './Icon.jsx'
+
+// Home's progress row for a coach week (S.queue) — it stands in for the seven weekday dots
+// while a planner-written queue runs the week, because its sessions have no weekday: they are done in
+// order, on whatever days you train. One chip per session in slot order; the next undone one
+// is lit, and any undone chip starts its own routine, in whatever order the day calls for. A
+// done chip is inert: that session is logged. Reads through queueView so the words here and
+// the today row (effectiveRoutineIds → queueNext) can never disagree about which is next.
+export default function QueueRow({ S, today, onStart }) {
+ const v = queueView(S, today)
+ if (!v) return null
+ const word = { done: t('Done'), next: t('Up next'), later: t('Later') }
+ const next = v.items.find(i => i.state === 'next')
+ // "today" only when the today row really offers it: a 'rest' or routine override for today
+ // wins over the queue there (effectiveRoutineIds), and this line must not contradict it.
+ const shownToday = !!next && effectiveRoutineIds(S, today, today).includes(next.id)
+ const status = v.complete ? t('Week complete, ask the coach')
+ : v.waiting ? t('Next week starts {0}', fmtDate(v.startsOn, true))
+ : shownToday ? t('Next: {0}, today', next.name) : t('Next: {0}', next.name)
+ return <div className="queue">
+ <div className="row between" style={{ marginBottom: 8 }}>
+ <div className="small muted" style={{ fontWeight: 500 }}>{v.label}</div>
+ <div className="small muted">{v.items.length - v.remaining.length} / {v.items.length}</div>
+ </div>
+ {/* three chips do not fit one phone row and .chips hides its scrollbar — wrap instead */}
+ <div className="chips" style={{ flexWrap: 'wrap' }}>
+ {v.items.map((i, n) => <button key={n} className={'chip' + (i.state === 'next' ? ' on' : '')}
+ disabled={i.state === 'done'} onClick={() => onStart(i.id)}
+ style={{ display: 'inline-flex', alignItems: 'center', gap: 5, opacity: i.state === 'done' ? 0.55 : undefined }}>
+ {i.state === 'done' && <Icon name="check" />}{i.name}<span className="dim">{word[i.state]}</span>
+ </button>)}
+ </div>
+ <div className="small muted queue-status" style={{ marginTop: 8 }}>{status}</div>
+ </div>
+}
diff --git a/frontend/src/lib/coach-local.test.js b/frontend/src/lib/coach-local.test.js
index f4456d806..1d6358ef1 100644
--- a/frontend/src/lib/coach-local.test.js
+++ b/frontend/src/lib/coach-local.test.js
@@ -151,6 +151,8 @@ describe('the Coach on a phone with its own key', () => {
await expect(local.localReview(state())).rejects.toMatchObject({ code: 'busy' })
await settle()
+ // The cap is keyed by the LOCAL date (todayISO), not the UTC one: in the evening in the
+ // Americas the two differ, and a UTC stamp here read as yesterday's record and let the run through.
await saveCoachDevice({ daily: { d: todayISO(), n: local.LOCAL_DAILY_CAP } })
await expect(local.localReview(state())).rejects.toMatchObject({ code: 'cap' })
expect((await local.localStatus()).cap).toEqual({ used: local.LOCAL_DAILY_CAP, limit: local.LOCAL_DAILY_CAP })
diff --git a/frontend/src/lib/history.js b/frontend/src/lib/history.js
index 4bcf90565..d69e3c103 100644
--- a/frontend/src/lib/history.js
+++ b/frontend/src/lib/history.js
@@ -17,6 +17,7 @@ const workRowsForMode = (entry = {}, mode = 'reps') => {
// for the hook — and it re-exports this very `t` from core, so nothing changes here except what
// gets dragged along behind it.
import { t } from './i18n-core.js'
+import { queueNext } from './queue.js'
// How an exercise is logged (issue #16). This used to be derived from the body part alone,
// which meant a plank or a farmer's carry could only be timed by filing it under cardio.
@@ -392,13 +393,21 @@ export function bestWeightFor(S, exId) {
*
* `S.dayPlan[iso]` stays scalar (a routine id, the `'rest'` sentinel, or undefined): the
* per-date override and Start-time are single-pick. All array-tolerance is on `S.week`.
+ *
+ * A coach week (`S.queue`, lib/queue.js) has no weekdays: its sessions are done in order, and
+ * the first undone one is today's session — so it goes in front of whatever the weekday
+ * holds. The planner's own weekday pointers (a week applied before the queue existed) are
+ * hidden behind it; routines you planned yourself ride along as a combined day. `today` is a
+ * parameter so tests and the reminder builder can pin the clock; the override still wins.
*/
-export function effectiveRoutineIds(S, iso) {
+export function effectiveRoutineIds(S, iso, today = todayISO()) {
const ov = S.dayPlan[iso]
if (ov === 'rest') return []
if (ov && S.routines.some(r => r.id === ov)) return [ov]
const wd = new Date(iso + 'T12:00:00').getDay()
- return [].concat(S.week[wd] || []).filter(id => S.routines.some(r => r.id === id))
+ const weekday = [].concat(S.week[wd] || []).filter(id => S.routines.some(r => r.id === id))
+ const q = queueNext(S, iso, today)
+ return q ? [q, ...weekday.filter(id => !S.queue.ids.includes(id))] : weekday
}
export function effectiveRoutines(S, iso) {
return effectiveRoutineIds(S, iso).map(id => S.routines.find(r => r.id === id)).filter(Boolean)
diff --git a/frontend/src/lib/history.test.js b/frontend/src/lib/history.test.js
index a483ff617..0f022c943 100644
--- a/frontend/src/lib/history.test.js
+++ b/frontend/src/lib/history.test.js
@@ -2,6 +2,7 @@ import { describe, it, expect } from 'vitest'
import { nextTrainingDay, modeOf, isTimed, fmtSec, setLabel, defaultConfig, buildSets, freestyleConfig, exLine, workoutVolume, bestWeightFor, bestWeightForEntry, completedRepsOf, metricRowsForEntry, effortOf, stepEffort, capEffort, isBw, isPerSide, sideReps, repStep, cascadeWeight, insertWarmupRow, removeRowAt, workSetsDone, setsDone, setsDoneActive, setUnits, doneUnits, setUnitsTotal, pairAdjacent, unpairSuperset, supersetUnits, sessionSections, applyIntensifierPlan, pinnedNoteFor, exNoteFor, effectiveRoutineIds, effectiveRoutines, effectiveRoutineId, effectiveRoutine, lastEntryFor, entryExcluded, entryRoutineId, setsRepsOf } from './history.js'
import { makeSideSet, setSideField, toggleSide, WEIGHT_ORIGIN_MANUAL } from './workout-model.js'
import { EXDB } from './exercises.js'
+import { todayISO, isoOf } from './format.js'
// Real ids out of the shipped catalogue, so the body-part fallback is exercised for real.
const CARDIO = EXDB.find(e => e.bp === 'cardio').id
@@ -1099,6 +1100,17 @@ describe('nextTrainingDay', () => {
const off = base({ week: { 3: 'r1', 5: 'r2' }, dayPlan: { '2026-08-19': 'rest' } })
expect(nextTrainingDay(off, TUE)).toMatchObject({ weekday: 5 })
})
+
+ it('finds a coach week waiting on its start day (lib/queue.js)', () => {
+ // effectiveRoutineIds defaults `today` to the clock, so this one case is pinned relative
+ // to the real today: a queue that starts in three days is found three days out.
+ const today = todayISO()
+ const d = new Date(today + 'T12:00:00'); d.setDate(d.getDate() + 3)
+ const startsOn = isoOf(d)
+ const S = base({ workouts: [], queue: { ids: ['r2'], since: Date.now(), startsOn, label: 'W2' } })
+ expect(nextTrainingDay(S, today)).toMatchObject({ iso: startsOn })
+ expect(nextTrainingDay(S, today).routine.name).toBe('B')
+ })
})
describe('pinnedNoteFor', () => {
@@ -1284,6 +1296,58 @@ describe('effectiveRoutineIds / effectiveRoutines', () => {
})
})
+// ---- coach queue: the week's sessions in order, the first undone one is today's (lib/queue.js) ----
+describe('effectiveRoutineIds — coach queue', () => {
+ const routines = [
+ { id: 'd1', name: 'US W1 D1', ex: [{ id: '1' }] }, { id: 'd2', name: 'US W1 D2', ex: [{ id: '1' }] },
+ { id: 'own', name: 'Core', ex: [{ id: '2' }] },
+ ]
+ const TODAY = '2026-09-09' // a Wednesday → getDay() 3
+ const SINCE = Date.parse('2026-09-07T08:00:00')
+ const S = (over = {}) => ({
+ routines, week: {}, dayPlan: {}, workouts: [],
+ queue: { ids: ['d1', 'd2'], since: SINCE, startsOn: '2026-09-07', label: 'US W1' },
+ ...over,
+ })
+ const done = id => ({ id: 'w' + id, d: '2026-09-08', start: SINCE + 3600000, routineIds: [id], routineId: id, name: routines.find(r => r.id === id).name })
+
+ it('today gets the first undone session; other days get nothing from the queue', () => {
+ expect(effectiveRoutineIds(S(), TODAY, TODAY)).toEqual(['d1'])
+ expect(effectiveRoutineIds(S(), '2026-09-10', TODAY)).toEqual([])
+ expect(effectiveRoutineIds(S({ workouts: [done('d1')] }), TODAY, TODAY)).toEqual(['d2'])
+ })
+
+ it('before startsOn the session sits on that day, not on today', () => {
+ const s = S({ queue: { ...S().queue, startsOn: '2026-09-14' } })
+ expect(effectiveRoutineIds(s, TODAY, TODAY)).toEqual([])
+ expect(effectiveRoutineIds(s, '2026-09-14', TODAY)).toEqual(['d1'])
+ })
+
+ it('a complete week hands the day back to the weekday plan', () => {
+ const s = S({ workouts: [done('d1'), done('d2')], week: { 3: ['own'] } })
+ expect(effectiveRoutineIds(s, TODAY, TODAY)).toEqual(['own'])
+ expect(effectiveRoutineIds(S({ workouts: [done('d1'), done('d2')] }), TODAY, TODAY)).toEqual([])
+ })
+
+ it('a per-date override still wins over the queue', () => {
+ expect(effectiveRoutineIds(S({ dayPlan: { [TODAY]: 'rest' } }), TODAY, TODAY)).toEqual([])
+ expect(effectiveRoutineIds(S({ dayPlan: { [TODAY]: 'own' } }), TODAY, TODAY)).toEqual(['own'])
+ })
+
+ it('own routines on the weekday ride along behind the session', () => {
+ expect(effectiveRoutineIds(S({ week: { 3: ['own'] } }), TODAY, TODAY)).toEqual(['d1', 'own'])
+ })
+
+ it('legacy coach weekday pointers are hidden behind the queue', () => {
+ expect(effectiveRoutineIds(S({ week: { 3: ['d2', 'own'] } }), TODAY, TODAY)).toEqual(['d1', 'own'])
+ expect(effectiveRoutineIds(S({ week: { 3: 'd1' } }), TODAY, TODAY)).toEqual(['d1'])
+ })
+
+ it('without a queue the weekday plan answers as before', () => {
+ expect(effectiveRoutineIds(S({ queue: null, week: { 3: ['own'] } }), TODAY, TODAY)).toEqual(['own'])
+ })
+})
+
describe('nextTrainingDay on a combined day', () => {
const TUE = '2026-08-18'
it('is trainable when any one routine of the day has exercises; return shape carries routines', () => {
diff --git a/frontend/src/lib/mobile.js b/frontend/src/lib/mobile.js
index 6f5da81e2..4b7e15261 100644
--- a/frontend/src/lib/mobile.js
+++ b/frontend/src/lib/mobile.js
@@ -108,8 +108,10 @@ export function buildReminderNotifications(S, now = new Date()) {
day.setDate(date.getDate() + offset)
const iso = isoOf(day)
if (completed.has(iso)) continue
- // A weekday can hold several routines; name them all, or fall back to a count.
- const dayRoutines = effectiveRoutineIds(state, iso).map(id => routines.find(x => x.id === id)).filter(Boolean)
+ // A weekday can hold several routines; name them all, or fall back to a count. Each day is
+ // asked as if it were today: a coach week's next session is due every day until it is done,
+ // so it is reminded every day (the app re-syncs these after every workout and on open).
+ const dayRoutines = effectiveRoutineIds(state, iso, iso).map(id => routines.find(x => x.id === id)).filter(Boolean)
if (!dayRoutines.length) continue
const label = dayRoutines.length <= 2 ? dayRoutines.map(r => r.name).join(' + ') : t('{0} routines', dayRoutines.length)
const at = new Date(day)
diff --git a/frontend/src/lib/mobile.test.js b/frontend/src/lib/mobile.test.js
index eeef27444..f33d78389 100644
--- a/frontend/src/lib/mobile.test.js
+++ b/frontend/src/lib/mobile.test.js
@@ -74,4 +74,18 @@ describe('buildReminderNotifications', () => {
const n = buildReminderNotifications(state({ week: { 1: ['push', 'pull', 'legs'] } }), now)[0]
expect(n.body).toContain('3 routines')
})
-})
\ No newline at end of file
+
+ it("a coach week's next session is reminded every day until it is done, with no weekday behind it", () => {
+ const now = new Date(2026, 8, 7, 7, 0) // Monday 07:00, before the 08:00 reminder
+ const queue = { ids: ['push', 'pull'], since: 0, startsOn: iso(now), label: 'US W1' }
+ const notifications = buildReminderNotifications(state({ week: {}, queue }), now)
+ expect(notifications.length).toBeGreaterThanOrEqual(3)
+ expect(notifications.every(n => n.body.includes('Push'))).toBe(true)
+ expect(notifications[0].schedule.at.getDate()).toBe(7)
+ expect(notifications[1].schedule.at.getDate()).toBe(8)
+ // …and nothing before the week starts; the weekday plan speaks for those days.
+ const waiting = buildReminderNotifications(state({ week: { 2: 'legs' }, queue: { ...queue, startsOn: iso(new Date(2026, 8, 9)) } }), now)
+ expect(waiting[0].body).toContain('Legs') // Tue: weekday plan
+ expect(waiting[1].body).toContain('Push') // Wed: startsOn — the queue takes over
+ })
+})
diff --git a/frontend/src/lib/queue.js b/frontend/src/lib/queue.js
new file mode 100644
index 000000000..14279ec70
--- /dev/null
+++ b/frontend/src/lib/queue.js
@@ -0,0 +1,103 @@
+// The floating coach week (`S.queue`): the week's sessions are an ordered list, and the first
+// one not done yet is "today's session" on whatever day you next train. No weekday is attached
+// to any of them — the weekday model (`S.week` / `S.dayPlan`) stays for the routines you plan
+// yourself, and effectiveRoutineIds (history.js) puts the two side by side.
+//
+// S.queue = null | {
+// ids: string[] routine ids in slot order = the week's sessions
+// since: number ms epoch of the apply; a workout STARTED at/after it is this week's
+// startsOn: 'YYYY-MM-DD' local date the queue becomes active (the planner's calendar-week rule)
+// label: string progress-row title, e.g. 'US W1'
+// }
+//
+// The app never writes `S.queue`; a planner does — any API client that PUTs state with a queue
+// (a coaching agent, a script). null = the weekday model alone.
+//
+// DONE RULE — kept word for word with the api's reminder copy (api/queue.js), and the rule a
+// planner has to mirror, so nobody disagrees about which session is next: a session is done
+// when any FINISHED workout on that routine exists after the week was applied. Missed sets are
+// the planner's business. `S.active` is not in `S.workouts`, so a session in progress never
+// counts. The name clause is for a "past workout" logged with an early clock: its start predates
+// `since`, but it is dated inside the week (on or after `startsOn`) and its name — a merged
+// session reads 'US W1 D1 + Core' — says which routines were done. The date bound matters: a
+// planner may reuse its routine ids and names every week (W1 again after a restart), so a
+// workout from a past week that happens to carry this week's name must never count.
+
+import { isoOf } from './format.js'
+
+const routineIdsOf = w => (Array.isArray(w.routineIds) ? w.routineIds : (w.routineId ? [w.routineId] : []))
+const nameParts = w => String(w.name || '').split(' + ')
+
+// Tolerant reader: whole-state sync is last-writer-wins, so a half-written or older-shaped
+// queue can arrive from another client. A bad shape reads as "no queue" rather than taking
+// Home down with it. A session whose routine no longer exists (deleted in the editor — the
+// app never rewrites S.queue) is dropped from the week: it could never be started or logged,
+// and keeping it would pin the whole week on it; a queue left with no session at all reads as
+// no queue. A missing startsOn means active since the day of the apply.
+const queueOf = S => {
+ const q = S?.queue
+ if (!q || typeof q !== 'object' || !Array.isArray(q.ids)) return null
+ const routines = Array.isArray(S.routines) ? S.routines : []
+ const ids = q.ids.filter(id => routines.some(r => r.id === id))
+ if (!ids.length) return null
+ return { ...q, ids, startsOn: typeof q.startsOn === 'string' ? q.startsOn : isoOf(new Date(q.since || 0)) }
+}
+
+const isDone = (S, q, id) => {
+ const name = S.routines.find(r => r.id === id)?.name
+ return S.workouts.some(w => routineIdsOf(w).includes(id)
+ && ((w.start ?? 0) >= q.since || (String(w.d || '') >= q.startsOn && nameParts(w).includes(name))))
+}
+
+/** The week's sessions already done, in slot order. `[]` without a queue. */
+export function queueDone(S) {
+ const q = queueOf(S)
+ return q ? q.ids.filter(id => isDone(S, q, id)) : []
+}
+
+/** The sessions still to do, in slot order — the first is the next one. `[]` without a queue. */
+export function queueRemaining(S) {
+ const q = queueOf(S)
+ return q ? q.ids.filter(id => !isDone(S, q, id)) : []
+}
+
+/**
+ * The queue's answer for a date: the next undone session, on exactly one day — today, or
+ * `startsOn` while that is still ahead (Home's "next week is waiting"). Every other date gets
+ * null, so the calendar and the reminders do not paint the same session onto every day.
+ * Dates are compared as ISO strings; `today` is passed in so callers and tests agree on it.
+ */
+export function queueNext(S, iso, today) {
+ const q = queueOf(S)
+ if (!q) return null
+ // The one date the queue answers for is known before any workout is looked at — the calendar
+ // asks for thirty dates in a row, so the done-scan runs only for the one that can match.
+ const on = today > q.startsOn ? today : q.startsOn
+ if (iso !== on) return null
+ const remaining = queueRemaining(S)
+ return remaining.length ? remaining[0] : null
+}
+
+/**
+ * Everything Home's progress row shows, derived once. `items` keep slot order; `state` is
+ * 'done', 'next' (the first undone one, whether or not the queue is active yet) or 'later'.
+ * `waiting` = the queue is sitting on a future `startsOn`. null without a queue.
+ */
+export function queueView(S, today) {
+ const q = queueOf(S)
+ if (!q) return null
+ const remaining = queueRemaining(S)
+ // A routine the planner has since retired keeps its id as the name — better than a blank chip.
+ const nameOf = id => S.routines.find(r => r.id === id)?.name ?? id
+ return {
+ label: q.label || '',
+ items: q.ids.map(id => ({
+ id, name: nameOf(id),
+ state: !remaining.includes(id) ? 'done' : id === remaining[0] ? 'next' : 'later',
+ })),
+ remaining,
+ complete: remaining.length === 0,
+ startsOn: q.startsOn,
+ waiting: today < q.startsOn,
+ }
+}
diff --git a/frontend/src/lib/queue.test.js b/frontend/src/lib/queue.test.js
new file mode 100644
index 000000000..9c66a4f1b
--- /dev/null
+++ b/frontend/src/lib/queue.test.js
@@ -0,0 +1,155 @@
+import { describe, it, expect } from 'vitest'
+import { queueDone, queueRemaining, queueNext, queueView } from './queue.js'
+
+// The DONE RULE is shared with the api's reminder copy (and any planner writing S.queue); these
+// cases are the ones every copy must agree on. Dates are plain strings so nothing here reads the clock.
+const routines = [{ id: 'd1', name: 'US W1 D1' }, { id: 'd2', name: 'US W1 D2' }, { id: 'd3', name: 'US W1 D3' }]
+const SINCE = Date.parse('2026-09-07T08:00:00')
+const TODAY = '2026-09-09'
+const S = (over = {}) => ({
+ routines, workouts: [],
+ queue: { ids: ['d1', 'd2', 'd3'], since: SINCE, startsOn: '2026-09-07', label: 'US W1' },
+ ...over,
+})
+const w = (over = {}) => ({ id: 'w', d: '2026-09-08', start: SINCE + 3600000, routineIds: [], routineId: null, name: '', ...over })
+
+describe('DONE RULE', () => {
+ it('a finished workout on the routine, started at or after the apply, marks it done', () => {
+ expect(queueDone(S({ workouts: [w({ routineIds: ['d1'], start: SINCE, name: 'US W1 D1' })] }))).toEqual(['d1'])
+ expect(queueRemaining(S({ workouts: [w({ routineIds: ['d1'], start: SINCE })] }))).toEqual(['d2', 'd3'])
+ })
+
+ it('a workout from before the apply is last week\'s, unless its name says otherwise', () => {
+ const old = w({ routineIds: ['d1'], start: SINCE - 1, name: 'Push' })
+ expect(queueDone(S({ workouts: [old] }))).toEqual([])
+ // Adopted weeks: the workout predates `since`, but the merged session name carries the
+ // routine's current name — that is the planner's own record of what was done.
+ const adopted = w({ routineIds: ['d1'], start: SINCE - 86400000, name: 'US W1 D1 + Core' })
+ expect(queueDone(S({ workouts: [adopted] }))).toEqual(['d1'])
+ })
+
+ it('a past week\'s workout that carries this week\'s name does not count — the name clause is bounded to the week', () => {
+ // A planner may reuse its routine ids and names (W1 again after a restart): the sessions
+ // trained under the ORIGINAL W1 must not tick the NEW W1 done on the day it is applied.
+ const lastMonth = w({ routineIds: ['d2'], start: SINCE - 8 * 86400000, d: '2026-08-30', name: 'US W1 D2' })
+ expect(queueDone(S({ workouts: [lastMonth] }))).toEqual([])
+ // …whereas a "past workout" dated inside the week, logged with an early clock, does.
+ const backfilled = w({ routineIds: ['d2'], start: SINCE - 86400000, d: '2026-09-07', name: 'US W1 D2' })
+ expect(queueDone(S({ workouts: [backfilled] }))).toEqual(['d2'])
+ })
+
+ it('the routine id has to be on the workout — a name alone is not enough', () => {
+ expect(queueDone(S({ workouts: [w({ routineIds: ['x'], name: 'US W1 D1' })] }))).toEqual([])
+ expect(queueDone(S({ workouts: [w({ routineIds: [], name: 'US W1 D1' })] }))).toEqual([])
+ })
+
+ it('reads the legacy scalar routineId on a workout from before routineIds existed', () => {
+ // No `routineIds` key at all — an empty array would be a real (freestyle) answer and wins.
+ expect(queueDone(S({ workouts: [w({ routineIds: undefined, routineId: 'd2' })] }))).toEqual(['d2'])
+ expect(queueDone(S({ workouts: [w({ routineIds: [], routineId: 'd2' })] }))).toEqual([])
+ })
+
+ it('a merged session counts for every routine in it', () => {
+ expect(queueDone(S({ workouts: [w({ routineIds: ['d1', 'd3'] })] }))).toEqual(['d1', 'd3'])
+ expect(queueRemaining(S({ workouts: [w({ routineIds: ['d1', 'd3'] })] }))).toEqual(['d2'])
+ })
+
+ it('a workout with no start (imported history) counts only through its name', () => {
+ expect(queueDone(S({ workouts: [w({ routineIds: ['d1'], start: undefined, name: 'Push' })] }))).toEqual([])
+ expect(queueDone(S({ workouts: [w({ routineIds: ['d1'], start: undefined, name: 'US W1 D1' })] }))).toEqual(['d1'])
+ })
+
+ it('the session in progress never counts — only finished workouts do', () => {
+ const s = S({ active: { id: 'a', routineIds: ['d1'], start: SINCE + 1, name: 'US W1 D1' } })
+ expect(queueDone(s)).toEqual([])
+ expect(queueRemaining(s)).toEqual(['d1', 'd2', 'd3'])
+ })
+
+ it('without a queue nothing is done, nothing remains, and there is no view', () => {
+ const s = S({ queue: null, workouts: [w({ routineIds: ['d1'] })] })
+ expect(queueDone(s)).toEqual([])
+ expect(queueRemaining(s)).toEqual([])
+ expect(queueNext(s, TODAY, TODAY)).toBeNull()
+ expect(queueView(s, TODAY)).toBeNull()
+ })
+
+ it('a queue of the wrong shape reads as no queue instead of throwing', () => {
+ for (const queue of [{}, { ids: 'd1' }, 'd1', 7]) {
+ expect(queueRemaining(S({ queue }))).toEqual([])
+ expect(queueNext(S({ queue }), TODAY, TODAY)).toBeNull()
+ expect(queueView(S({ queue }), TODAY)).toBeNull()
+ }
+ })
+})
+
+describe('queueNext', () => {
+ it('answers on today once the week is active, and on no other day', () => {
+ expect(queueNext(S(), TODAY, TODAY)).toBe('d1')
+ expect(queueNext(S(), '2026-09-08', TODAY)).toBeNull()
+ expect(queueNext(S(), '2026-09-10', TODAY)).toBeNull()
+ })
+
+ it('moves on to the next undone session in slot order', () => {
+ expect(queueNext(S({ workouts: [w({ routineIds: ['d1'] })] }), TODAY, TODAY)).toBe('d2')
+ expect(queueNext(S({ workouts: [w({ routineIds: ['d2'] })] }), TODAY, TODAY)).toBe('d1')
+ })
+
+ it('while the week waits on a future startsOn, the session sits on that day, not on today', () => {
+ const s = S({ queue: { ...S().queue, startsOn: '2026-09-14' } })
+ expect(queueNext(s, TODAY, TODAY)).toBeNull()
+ expect(queueNext(s, '2026-09-14', TODAY)).toBe('d1')
+ expect(queueNext(s, '2026-09-15', TODAY)).toBeNull()
+ })
+
+ it('is null once the week is complete', () => {
+ const s = S({ workouts: [w({ routineIds: ['d1', 'd2', 'd3'] })] })
+ expect(queueNext(s, TODAY, TODAY)).toBeNull()
+ })
+})
+
+describe('queueView', () => {
+ it('lists the sessions in slot order with one lit as next', () => {
+ const v = queueView(S({ workouts: [w({ routineIds: ['d1'] })] }), TODAY)
+ expect(v.label).toBe('US W1')
+ expect(v.items).toEqual([
+ { id: 'd1', name: 'US W1 D1', state: 'done' },
+ { id: 'd2', name: 'US W1 D2', state: 'next' },
+ { id: 'd3', name: 'US W1 D3', state: 'later' },
+ ])
+ expect(v.remaining).toEqual(['d2', 'd3'])
+ expect(v).toMatchObject({ complete: false, startsOn: '2026-09-07', waiting: false })
+ })
+
+ it('says the week is waiting before startsOn, and still names the next session', () => {
+ const v = queueView(S({ queue: { ...S().queue, startsOn: '2026-09-14' } }), TODAY)
+ expect(v.waiting).toBe(true)
+ expect(v.items[0].state).toBe('next')
+ expect(v.startsOn).toBe('2026-09-14')
+ })
+
+ it('a complete week has every chip done and nothing remaining', () => {
+ const v = queueView(S({ workouts: [w({ routineIds: ['d1', 'd2', 'd3'] })] }), TODAY)
+ expect(v.items.map(i => i.state)).toEqual(['done', 'done', 'done'])
+ expect(v).toMatchObject({ remaining: [], complete: true })
+ })
+
+ it('a session whose routine no longer exists is dropped from the week, not pinned as next forever', () => {
+ // Deleted in the editor (the app never rewrites S.queue): it can never be started or logged.
+ const v = queueView(S({ queue: { ...S().queue, ids: ['gone', 'd1', 'd2'] } }), TODAY)
+ expect(v.items.map(i => i.id)).toEqual(['d1', 'd2'])
+ expect(v.items[0].state).toBe('next')
+ expect(queueRemaining(S({ queue: { ...S().queue, ids: ['gone', 'd1'] } }))).toEqual(['d1'])
+ expect(queueNext(S({ queue: { ...S().queue, ids: ['gone', 'd1'] } }), TODAY, TODAY)).toBe('d1')
+ // …and a week of nothing but deleted routines reads as no queue at all, so Home shows the plan.
+ expect(queueView(S({ queue: { ...S().queue, ids: ['gone'] } }), TODAY)).toBeNull()
+ expect(queueNext(S({ queue: { ...S().queue, ids: ['gone'] } }), TODAY, TODAY)).toBeNull()
+ })
+
+ it('a queue without a startsOn is active since the day of the apply, not silently dead', () => {
+ const noStart = S({ queue: { ids: ['d1', 'd2'], since: SINCE, label: 'US W1' } })
+ expect(queueNext(noStart, TODAY, TODAY)).toBe('d1')
+ expect(queueView(noStart, TODAY)).toMatchObject({ waiting: false, startsOn: '2026-09-07' })
+ const nullStart = S({ queue: { ids: ['d1'], since: SINCE, startsOn: null, label: 'US W1' } })
+ expect(queueNext(nullStart, TODAY, TODAY)).toBe('d1')
+ })
+})
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index 07697206c..769e424b7 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -1716,4 +1716,11 @@ export default {
'Teal': 'أزرق مخضر',
'Yellow': 'أصفر',
'Enter how long it took — at least 1 minute.': 'أدخل المدة التي استغرقها — دقيقة واحدة على الأقل.',
+ // --- coach week (Home progress row, components/QueueRow.jsx) ---
+ 'Next: {0}, today': 'التالي: {0}، اليوم',
+ 'Next: {0}': 'التالي: {0}',
+ 'Next week starts {0}': 'يبدأ الأسبوع التالي {0}',
+ 'Week complete, ask the coach': 'اكتمل الأسبوع، اسأل المدرب',
+ 'Up next': 'التالي',
+ 'Later': 'لاحقًا',
}
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index 663a5a5bb..85d055e4b 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -1399,6 +1399,13 @@ export default {
'{0} %': '{0} %',
'{0} MB': '{0} MB',
'Checksum not available — not installing': 'Prüfsumme nicht verfügbar — Installation abgebrochen',
+ // --- coach week (Home progress row, components/QueueRow.jsx) ---
+ 'Next: {0}, today': 'Als Nächstes: {0}, heute',
+ 'Next: {0}': 'Als Nächstes: {0}',
+ 'Next week starts {0}': 'Nächste Woche beginnt am {0}',
+ 'Week complete, ask the coach': 'Woche abgeschlossen, frag den Coach',
+ 'Up next': 'Als Nächstes',
+ 'Later': 'Später',
// --- combine routines / layout / deload (v1.3.6) ---
'Add routine': 'Routine hinzufügen',
'Bring another routine into this session': 'Eine weitere Routine in diese Einheit holen',
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 8e1d9aa99..6aff8fd1f 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -1379,6 +1379,13 @@ export default {
'{0} %': '{0} %',
'{0} MB': '{0} MB',
'Checksum not available — not installing': 'Suma de verificación no disponible — no se instala',
+ // --- coach week (Home progress row, components/QueueRow.jsx) ---
+ 'Next: {0}, today': 'Siguiente: {0}, hoy',
+ 'Next: {0}': 'Siguiente: {0}',
+ 'Next week starts {0}': 'La próxima semana empieza el {0}',
+ 'Week complete, ask the coach': 'Semana completada, pregunta al entrenador',
+ 'Up next': 'Siguiente',
+ 'Later': 'Más tarde',
// --- combine routines / layout / deload (v1.3.6) ---
'Add routine': 'Añadir rutina',
'Bring another routine into this session': 'Traer otra rutina a esta sesión',
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index ee904194c..5e5de7745 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -1379,6 +1379,13 @@ export default {
'{0} %': '{0} %',
'{0} MB': '{0} Mo',
'Checksum not available — not installing': 'Somme de contrôle indisponible — installation annulée',
+ // --- coach week (Home progress row, components/QueueRow.jsx) ---
+ 'Next: {0}, today': 'À suivre : {0}, aujourd’hui',
+ 'Next: {0}': 'À suivre : {0}',
+ 'Next week starts {0}': 'La semaine prochaine commence le {0}',
+ 'Week complete, ask the coach': 'Semaine terminée, demandez au coach',
+ 'Up next': 'À suivre',
+ 'Later': 'Plus tard',
// --- combine routines / layout / deload (v1.3.6) ---
'Add routine': 'Ajouter une routine',
'Bring another routine into this session': 'Ajouter une autre routine à cette séance',
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index ccb0ca2aa..b26c7ba02 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -1379,6 +1379,13 @@ export default {
'{0} %': '{0}%',
'{0} MB': '{0} MB',
'Checksum not available — not installing': 'चेकसम उपलब्ध नहीं — इंस्टॉल नहीं किया गया',
+ // --- coach week (Home progress row, components/QueueRow.jsx) ---
+ 'Next: {0}, today': 'अगला: {0}, आज',
+ 'Next: {0}': 'अगला: {0}',
+ 'Next week starts {0}': 'अगला सप्ताह {0} से शुरू होगा',
+ 'Week complete, ask the coach': 'सप्ताह पूरा हुआ, कोच से पूछें',
+ 'Up next': 'अगला',
+ 'Later': 'बाद में',
// --- combine routines / layout / deload (v1.3.6) ---
'Add routine': 'रूटीन जोड़ें',
'Bring another routine into this session': 'इस सत्र में एक और रूटीन लाएँ',
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index 61b151edc..f49278c24 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -1382,6 +1382,13 @@ export default {
'{0} %': '{0} %',
'{0} MB': '{0} MB',
'Checksum not available — not installing': 'Ellenőrző összeg nem érhető el — nincs telepítés',
+ // --- coach week (Home progress row, components/QueueRow.jsx) ---
+ 'Next: {0}, today': 'Következő: {0}, ma',
+ 'Next: {0}': 'Következő: {0}',
+ 'Next week starts {0}': 'A következő hét kezdete: {0}',
+ 'Week complete, ask the coach': 'A hét kész, kérdezd az edzőt',
+ 'Up next': 'Következő',
+ 'Later': 'Később',
// --- combine routines / layout / deload (v1.3.6) ---
'Add routine': 'Rutin hozzáadása',
'Bring another routine into this session': 'Másik rutin behozása ebbe az edzésbe',
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index 48e5dd34d..3cf16565a 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -1379,6 +1379,13 @@ export default {
'{0} %': '{0} %',
'{0} MB': '{0} MB',
'Checksum not available — not installing': 'Checksum non disponibile — installazione annullata',
+ // --- coach week (Home progress row, components/QueueRow.jsx) ---
+ 'Next: {0}, today': 'Prossima: {0}, oggi',
+ 'Next: {0}': 'Prossima: {0}',
+ 'Next week starts {0}': 'La prossima settimana inizia {0}',
+ 'Week complete, ask the coach': 'Settimana completata, chiedi al coach',
+ 'Up next': 'Prossima',
+ 'Later': 'Più tardi',
// --- combine routines / layout / deload (v1.3.6) ---
'Add routine': 'Aggiungi routine',
'Bring another routine into this session': 'Porta un’altra routine in questa sessione',
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index 02628fa0a..1204b0322 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -1379,6 +1379,13 @@ export default {
'{0} %': '{0}%',
'{0} MB': '{0} MB',
'Checksum not available — not installing': '체크섬을 확인할 수 없어 설치하지 않습니다',
+ // --- coach week (Home progress row, components/QueueRow.jsx) ---
+ 'Next: {0}, today': '다음: {0}, 오늘',
+ 'Next: {0}': '다음: {0}',
+ 'Next week starts {0}': '다음 주는 {0}에 시작됩니다',
+ 'Week complete, ask the coach': '주 완료, 코치에게 문의하세요',
+ 'Up next': '다음',
+ 'Later': '나중에',
// --- combine routines / layout / deload (v1.3.6) ---
'Add routine': '루틴 추가',
'Bring another routine into this session': '이 세션에 다른 루틴 가져오기',
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index f5910a684..1d32c58bf 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -1379,6 +1379,13 @@ export default {
'{0} %': '{0}%',
'{0} MB': '{0} MB',
'Checksum not available — not installing': 'Suma kontrolna niedostępna — instalacja przerwana',
+ // --- coach week (Home progress row, components/QueueRow.jsx) ---
+ 'Next: {0}, today': 'Następny: {0}, dziś',
+ 'Next: {0}': 'Następny: {0}',
+ 'Next week starts {0}': 'Następny tydzień zaczyna się {0}',
+ 'Week complete, ask the coach': 'Tydzień ukończony, zapytaj trenera',
+ 'Up next': 'Następny',
+ 'Later': 'Później',
// --- combine routines / layout / deload (v1.3.6) ---
'Add routine': 'Dodaj rutynę',
'Bring another routine into this session': 'Dołącz kolejną rutynę do tej sesji',
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 41505d76e..28a2ef308 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -1008,6 +1008,13 @@ export const PT_BR_OVERRIDES = {
'Teal': 'Turquesa',
'Yellow': 'Amarelo',
'Enter how long it took — at least 1 minute.': 'Informe quanto tempo levou — pelo menos 1 minuto.',
+ // --- coach week (Home progress row, components/QueueRow.jsx) ---
+ 'Next: {0}, today': 'Próximo: {0}, hoje',
+ 'Next: {0}': 'Próximo: {0}',
+ 'Next week starts {0}': 'A próxima semana começa em {0}',
+ 'Week complete, ask the coach': 'Semana concluída, pergunte ao Coach',
+ 'Up next': 'Próximo',
+ 'Later': 'Depois',
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index 65dd8ff54..e8ab6a34b 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -1379,6 +1379,13 @@ export default {
'{0} %': '{0} %',
'{0} MB': '{0} MB',
'Checksum not available — not installing': 'Soma de verificação indisponível — não instalado',
+ // --- coach week (Home progress row, components/QueueRow.jsx) ---
+ 'Next: {0}, today': 'A seguir: {0}, hoje',
+ 'Next: {0}': 'A seguir: {0}',
+ 'Next week starts {0}': 'A próxima semana começa a {0}',
+ 'Week complete, ask the coach': 'Semana concluída, pergunta ao treinador',
+ 'Up next': 'A seguir',
+ 'Later': 'Mais tarde',
// --- combine routines / layout / deload (v1.3.6) ---
'Add routine': 'Adicionar rotina',
'Bring another routine into this session': 'Trazer outra rotina para esta sessão',
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 2df1568f7..58b2e9836 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -1379,6 +1379,13 @@ export default {
'{0} %': '{0} %',
'{0} MB': '{0} МБ',
'Checksum not available — not installing': 'Контрольная сумма недоступна — установка отменена',
+ // --- coach week (Home progress row, components/QueueRow.jsx) ---
+ 'Next: {0}, today': 'Далее: {0}, сегодня',
+ 'Next: {0}': 'Далее: {0}',
+ 'Next week starts {0}': 'Следующая неделя начнётся {0}',
+ 'Week complete, ask the coach': 'Неделя завершена, спросите тренера',
+ 'Up next': 'Далее',
+ 'Later': 'Позже',
// --- combine routines / layout / deload (v1.3.6) ---
'Add routine': 'Добавить программу',
'Bring another routine into this session': 'Добавить ещё одну программу в эту тренировку',
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index 3604d80fa..6cd2ef0d6 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -1390,6 +1390,13 @@ export default {
'{0} %': '{0}%',
'{0} MB': '{0} MB',
'Checksum not available — not installing': 'ไม่มีค่าตรวจสอบ — ยกเลิกการติดตั้ง',
+ // --- coach week (Home progress row, components/QueueRow.jsx) ---
+ 'Next: {0}, today': 'ถัดไป: {0}, วันนี้',
+ 'Next: {0}': 'ถัดไป: {0}',
+ 'Next week starts {0}': 'สัปดาห์หน้าเริ่ม {0}',
+ 'Week complete, ask the coach': 'จบสัปดาห์แล้ว ถามโค้ช',
+ 'Up next': 'ถัดไป',
+ 'Later': 'ภายหลัง',
// --- combine routines / layout / deload (v1.3.6) ---
'Add routine': 'เพิ่มรูทีน',
'Bring another routine into this session': 'นำรูทีนอื่นเข้ามาในเซสชันนี้',
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index 1c96ebc30..53905b41e 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -1379,6 +1379,13 @@ export default {
'{0} %': '%{0}',
'{0} MB': '{0} MB',
'Checksum not available — not installing': 'Sağlama toplamı yok — yüklenmedi',
+ // --- coach week (Home progress row, components/QueueRow.jsx) ---
+ 'Next: {0}, today': 'Sıradaki: {0}, bugün',
+ 'Next: {0}': 'Sıradaki: {0}',
+ 'Next week starts {0}': 'Gelecek hafta {0} başlıyor',
+ 'Week complete, ask the coach': 'Hafta tamamlandı, koça sor',
+ 'Up next': 'Sıradaki',
+ 'Later': 'Daha sonra',
// --- combine routines / layout / deload (v1.3.6) ---
'Add routine': 'Rutin ekle',
'Bring another routine into this session': 'Bu seansa başka bir rutin getir',
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index ba239e0c8..04c3fc8d4 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -1660,4 +1660,11 @@ export default {
'Teal': 'Бірюзовий',
'Yellow': 'Жовтий',
'Enter how long it took — at least 1 minute.': 'Вкажи, скільки це тривало — щонайменше 1 хвилину.',
+ // --- coach week (Home progress row, components/QueueRow.jsx) ---
+ 'Next: {0}, today': 'Далі: {0}, сьогодні',
+ 'Next: {0}': 'Далі: {0}',
+ 'Next week starts {0}': 'Наступний тиждень починається {0}',
+ 'Week complete, ask the coach': 'Тиждень завершено, звернися до тренера',
+ 'Up next': 'Далі',
+ 'Later': 'Пізніше',
}
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 84237894a..eb862c175 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -1379,6 +1379,13 @@ export default {
'{0} %': '{0}%',
'{0} MB': '{0} MB',
'Checksum not available — not installing': '校验和不可用,已取消安装',
+ // --- coach week (Home progress row, components/QueueRow.jsx) ---
+ 'Next: {0}, today': '下一个:{0},今天',
+ 'Next: {0}': '下一个:{0}',
+ 'Next week starts {0}': '下周于 {0} 开始',
+ 'Week complete, ask the coach': '本周已完成,请咨询教练',
+ 'Up next': '下一个',
+ 'Later': '稍后',
// --- combine routines / layout / deload (v1.3.6) ---
'Add routine': '添加训练日',
'Bring another routine into this session': '把另一个训练日并入本次训练',
diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.js
index ba46ca8f2..344d9578b 100644
--- a/frontend/src/store/useStore.js
+++ b/frontend/src/store/useStore.js
@@ -75,6 +75,7 @@ export const DEF = {
unit: 'kg', restSec: 90, restPauseSec: 15, sound: true, soundOnSilent: false, timerFlash: false, timedSetOvertime: false, keepAwake: true, lang: 'en',
theme: 'dark', accent: 'lime', body: 'male', targetW: null,
bodyweight: [], routines: [], week: {}, dayPlan: {},
+ queue: null, // a planner's floating week (lib/queue.js) — written only through the API, never by the app
exWeights: {}, workouts: [], active: null, customEx: [], gifSize: 'full',
// Stats activity heatmap metric. Profiles without this key continue to open on time.
heatmapMetric: 'time',
diff --git a/frontend/src/views/Home.jsx b/frontend/src/views/Home.jsx
index 2e16b77fd..73a9fc2cd 100644
--- a/frontend/src/views/Home.jsx
+++ b/frontend/src/views/Home.jsx
@@ -7,6 +7,8 @@ import { t, dateLocale } from '../lib/i18n.js'
import { bwSheet, goalSheet, dayOverrideSheet, calendarSheet, startFlow, starterPlanSheet, bwDeltaColor, weighInsSheet } from '../sheets.jsx'
import LineChart from '../components/LineChart.jsx'
import Icon from '../components/Icon.jsx'
+import QueueRow from '../components/QueueRow.jsx'
+import { queueView } from '../lib/queue.js'
import { Button } from '../components/ui.jsx'
import { tappable } from '../lib/use-sheet-keyboard.js'
import { glyphOf } from '../lib/glyphs.js'
@@ -56,12 +58,22 @@ export default function Home() {
const wkLabel = weekOffset === 0 ? t('This week') : `${wkStart.getDate()} ${wkStart.toLocaleDateString(dateLocale(), { month: 'short' })} – ${wkEnd.getDate()} ${wkEnd.toLocaleDateString(dateLocale(), { month: 'short' })}`
const wThisWeek = S.workouts.filter(w => weekKey(w.d, ws) === weekKey(todayISO(), ws)).length
- // Days scheduled, not routines — a combined day counts as 1, matching wThisWeek (one w).
- const plannedPerWeek = Object.values(S.week).filter(ids => ids?.length).length
+ // A coach week (S.queue) read through the same tolerant reader QueueRow uses, so a malformed
+ // queue from another client shows the weekday dots, never an empty card.
+ const queue = queueView(S, todayISO())
+ // Days scheduled, not routines — a combined day counts as 1, matching wThisWeek (one w). A
+ // coach week has no weekdays: its sessions are the plan.
+ const plannedPerWeek = queue ? queue.items.length : Object.values(S.week).filter(ids => ids?.length).length
+ // …and the numerator counts the same thing: the queue's done sessions, not the calendar week's
+ // workouts (a coach week may straddle a weekend, and both fractions sit on one card).
+ const doneThisWeek = queue ? queue.items.length - queue.remaining.length : wThisWeek
const bwPoints = S.bodyweight.slice(-30).map(b => ({ t: b.t || new Date(b.d).getTime(), y: b.w, d: b.d }))
// today's session shown right under the week strip
const onToday = () => { if (S.active) nav('/workout'); else if (todayRoutines.length) startFlow(effectiveRoutineIds(S, todayISO())); else dayOverrideSheet(todayISO()) }
+ // A chip on the coach week's progress row starts that one routine, in any order. A session
+ // already in progress wins, as on the today row — starting another would overwrite it.
+ const onQueueStart = id => { if (S.active) nav('/workout'); else startFlow([id]) }
return <div className="narrow">
<div className="hdr">
@@ -70,12 +82,17 @@ export default function Home() {
</div>
<div className="card">
- <div className="row between" style={{ marginBottom: 8 }}>
- <button className="iconbtn" style={{ width: 30, height: 30, fontSize: 15 }} onClick={() => setWeekOffset(w => w - 1)} aria-label={t('Previous week')}><Icon name="chevronLeft" /></button>
- <div className="small muted" style={{ fontWeight: 500 }}>{wkLabel}</div>
- <button className="iconbtn" style={{ width: 30, height: 30, fontSize: 15 }} onClick={() => setWeekOffset(w => w + 1)} aria-label={t('Next week')}><Icon name="chevronRight" /></button>
- </div>
- <div className="week">{strip}</div>
+ {/* A coach week runs by order, not by weekday, so its progress row stands in for the
+ seven dots (components/QueueRow.jsx). The today row below stays as it is: the queue's
+ next session reaches it through effectiveRoutineIds like any planned routine. */}
+ {queue ? <QueueRow S={S} today={todayISO()} onStart={onQueueStart} /> : <>
+ <div className="row between" style={{ marginBottom: 8 }}>
+ <button className="iconbtn" style={{ width: 30, height: 30, fontSize: 15 }} onClick={() => setWeekOffset(w => w - 1)} aria-label={t('Previous week')}><Icon name="chevronLeft" /></button>
+ <div className="small muted" style={{ fontWeight: 500 }}>{wkLabel}</div>
+ <button className="iconbtn" style={{ width: 30, height: 30, fontSize: 15 }} onClick={() => setWeekOffset(w => w + 1)} aria-label={t('Next week')}><Icon name="chevronRight" /></button>
+ </div>
+ <div className="week">{strip}</div>
+ </>}
{/* Once today's session is logged the row stops asking for it. The week strip already
knew (its dot goes 'done'); this row did not, so a finished day kept showing the
routine name behind a green Start tag and read as still outstanding (issue #4).
@@ -185,7 +202,7 @@ export default function Home() {
<Icon name="flame" style={{ color: 'var(--orange)' }} />
{t('{0} week streak', streakWeeks(S))}
</div>
- <div className="muted small" style={{ marginTop: 2 }}>{wThisWeek}{plannedPerWeek ? ' / ' + plannedPerWeek : ''} {t('this week')} · {t(S.workouts.length === 1 ? '{0} workout total' : '{0} workouts total', S.workouts.length)}</div>
+ <div className="muted small" style={{ marginTop: 2 }}>{doneThisWeek}{plannedPerWeek ? ' / ' + plannedPerWeek : ''} {t('this week')} · {t(S.workouts.length === 1 ? '{0} workout total' : '{0} workouts total', S.workouts.length)}</div>
</div>
<Icon name="calendar" className="chev" style={{ fontSize: 20 }} />
</div>
diff --git a/frontend/src/views/Home.queue.test.jsx b/frontend/src/views/Home.queue.test.jsx
new file mode 100644
index 000000000..13d20b095
--- /dev/null
+++ b/frontend/src/views/Home.queue.test.jsx
@@ -0,0 +1,147 @@
+// @vitest-environment happy-dom
+// A coach week (S.queue) runs by order, not by weekday, so Home swaps the seven dots for a
+// progress row. Pinned here: one chip per session in slot order with its state word, a tap on
+// an undone chip starting that routine alone, a done chip staying inert, the status line's
+// three states, and the today row still answering through the same helper.
+import React, { act } from 'react'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { createRoot } from 'react-dom/client'
+import { useStore } from '../store/useStore.js'
+import { startFlow } from '../sheets.jsx'
+import { todayISO, isoOf, fmtDate } from '../lib/format.js'
+import Home from './Home.jsx'
+
+vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))
+vi.mock('../sheets.jsx', () => ({
+ starterPlanSheet: vi.fn(), bwSheet: vi.fn(), goalSheet: vi.fn(), dayOverrideSheet: vi.fn(),
+ calendarSheet: vi.fn(), startFlow: vi.fn(), bwDeltaColor: () => '',
+}))
+
+const routines = [
+ { id: 'd1', name: 'US W1 D1', emoji: null, ex: [{ id: '0025' }] },
+ { id: 'd2', name: 'US W1 D2', emoji: null, ex: [{ id: '0025' }] },
+ { id: 'd3', name: 'US W1 D3', emoji: null, ex: [{ id: '0025' }] },
+ { id: 'own', name: 'Core', emoji: null, ex: [{ id: '0025' }] },
+]
+// Home reads the clock, so the queue is pinned relative to the real today: applied three days
+// ago, active since the day before yesterday, its logged session on a day that is not today.
+const SINCE = Date.now() - 3 * 86400000
+const daysFromToday = n => { const d = new Date(todayISO() + 'T12:00:00'); d.setDate(d.getDate() + n); return isoOf(d) }
+const queue = (over = {}) => ({ ids: ['d1', 'd2', 'd3'], since: SINCE, startsOn: daysFromToday(-2), label: 'US W1', ...over })
+const logged = id => {
+ const start = SINCE + 3600000
+ return { id: 'w-' + id, d: isoOf(new Date(start)), start, end: start + 3600000, routineIds: [id], routineId: id, name: routines.find(r => r.id === id).name, entries: [] }
+}
+
+let host, root
+beforeEach(() => {
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ startFlow.mockClear()
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+})
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+})
+
+const setS = (over = {}) => useStore.setState(s => ({
+ S: { ...s.S, routines, week: {}, dayPlan: {}, workouts: [], active: null, queue: queue(), ...over }, user: null,
+}))
+const mount = () => act(() => root.render(<Home />))
+const chips = () => [...host.querySelectorAll('.queue .chip')]
+const chipTexts = () => chips().map(c => c.textContent)
+const status = () => host.querySelector('.queue .queue-status')?.textContent
+const todayTitle = () => host.querySelector('.today-row .ttl')?.textContent
+
+describe('Home — coach week progress row', () => {
+ it('replaces the weekday dots with one chip per session, in slot order, and lights the first', () => {
+ setS()
+ mount()
+ expect(host.querySelector('.week')).toBeNull()
+ expect(host.querySelectorAll('.wday').length).toBe(0)
+ expect(host.querySelector('.queue .row .small').textContent).toBe('US W1')
+ expect(chipTexts()).toEqual(['US W1 D1Up next', 'US W1 D2Later', 'US W1 D3Later'])
+ expect(chips()[0].className).toBe('chip on')
+ expect(status()).toBe('Next: US W1 D1, today')
+ expect(todayTitle()).toBe('US W1 D1')
+ })
+
+ it('a finished workout on a routine marks its chip done and moves the light on', () => {
+ setS({ workouts: [logged('d1')] })
+ mount()
+ expect(chipTexts()).toEqual(['US W1 D1Done', 'US W1 D2Up next', 'US W1 D3Later'])
+ expect(chips()[0].disabled).toBe(true)
+ expect(chips()[1].className).toBe('chip on')
+ expect(host.querySelectorAll('.queue .row .small')[1].textContent).toBe('1 / 3')
+ expect(status()).toBe('Next: US W1 D2, today')
+ expect(todayTitle()).toBe('US W1 D2')
+ })
+
+ it('tapping an undone chip starts that routine alone, in any order; a done chip does nothing', () => {
+ setS({ workouts: [logged('d1')] })
+ mount()
+ act(() => { chips()[2].click() })
+ expect(startFlow).toHaveBeenCalledTimes(1)
+ expect(startFlow).toHaveBeenCalledWith(['d3'])
+ act(() => { chips()[0].click() })
+ expect(startFlow).toHaveBeenCalledTimes(1)
+ })
+
+ it('a session in progress wins over a chip tap, as on the today row', () => {
+ setS({ active: { id: 'a', name: 'US W1 D1', start: Date.now(), cur: 0, entries: [], routineIds: ['d1'] } })
+ mount()
+ act(() => { chips()[1].click() })
+ expect(startFlow).not.toHaveBeenCalled()
+ })
+
+ it('before startsOn it says when the week starts, and the today row points at that day', () => {
+ const startsOn = daysFromToday(2)
+ setS({ queue: queue({ startsOn }) })
+ mount()
+ expect(status()).toBe('Next week starts ' + fmtDate(startsOn, true))
+ expect(chipTexts()[0]).toBe('US W1 D1Up next')
+ expect(todayTitle()).toBe('Rest day')
+ expect(host.querySelector('.today-row .ss').textContent).toMatch(/^Next session: \w+, US W1 D1$/)
+ })
+
+ it('a complete week says so, every chip is inert, and the day goes back to the weekday plan', () => {
+ setS({ workouts: [logged('d1'), logged('d2'), logged('d3')], week: { [new Date().getDay()]: ['own'] } })
+ mount()
+ expect(status()).toBe('Week complete, ask the coach')
+ expect(chips().every(c => c.disabled)).toBe(true)
+ expect(host.querySelectorAll('.queue .row .small')[1].textContent).toBe('3 / 3')
+ expect(todayTitle()).toBe('Core')
+ })
+
+ it('own routines on the weekday ride along beside the queue session', () => {
+ setS({ week: { [new Date().getDay()]: ['own'] } })
+ mount()
+ expect(todayTitle()).toBe('US W1 D1 + Core')
+ expect(chipTexts().length).toBe(3)
+ })
+
+ it('a rest override for today wins on the today row, and the status line stops saying "today"', () => {
+ setS({ dayPlan: { [todayISO()]: 'rest' } })
+ mount()
+ expect(todayTitle()).toBe('Rest day')
+ expect(status()).toBe('Next: US W1 D1')
+ expect(chips()[0].className).toContain('on')
+ })
+
+ it('a malformed queue from another client shows the weekday dots, never an empty card', () => {
+ setS({ queue: { ids: 'd1' }, week: { [new Date().getDay()]: ['own'] } })
+ mount()
+ expect(host.querySelector('.queue')).toBeNull()
+ expect(host.querySelectorAll('.week .wday').length).toBe(7)
+ expect(todayTitle()).toBe('Core')
+ })
+
+ it('without a queue the weekday dots are back', () => {
+ setS({ queue: null })
+ mount()
+ expect(host.querySelector('.queue')).toBeNull()
+ expect(host.querySelectorAll('.wday').length).toBe(7)
+ })
+})