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.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
Coach: automatic reviews run on a phone with its own key (Discord)
Duarte Santosc4dc5b91b00e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 263b7fa53..8a9791847 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -115,6 +115,10 @@ you leave it alone. Handy for deciding whether those legs are really ready (than- The Coach answers questions now. Type "how many sets of dips is that?" in the chat and you getan answer in words instead of a whole revised plan, and a suggestion you were asking about isstill there afterwards (#660, thanks @TheBlackSide243).+- Automatic Coach reviews on a phone with its own API key finally happen. The setting saved and+ then nothing ever ran them, because only a server ran them. Now the phone does it while the app+ is open: right after the workout that completes the count, or the first time you open it after+ your weekly slot. It only speaks up when it has something to suggest.## v1.4.2 (2026-10-18)diff --git a/api/coach/cadence.js b/api/coach/cadence.jsindex db5398875..36f06c6a4 100644--- a/api/coach/cadence.js+++ b/api/coach/cadence.js@@ -11,92 +11,12 @@*/import * as jobs from './jobs.js';import * as cfgStore from './config.js';+import { isDue } from './core/due.js';-const TICK_MS = 60000;--/** Weekly cadence fires within the minute; everyWorkouts fires as soon as the count is met.- * `reviewedAt` is when the server last finished a review for this person: the client stamps- * lastReview only once someone acts on a proposal, and a review nobody has opened yet — or- * one that found nothing to change — still read those workouts. */-export function isDue(coach, S, now, reviewedAt = 0, tz = null) {- const cadence = coach.cadence;- if (!cadence || cadence === 'off') return false;- const lastAt = Math.max(coach.lastReview?.at || 0, reviewedAt);-- // Nothing new to read is the most common reason not to run, and it applies to both modes.- const workouts = S.workouts || [];- // A workout's `end` is on the same clock as the review's timestamp; its `d` is the phone's- // local day, which can run ahead of the server's UTC day, so the date only stands in for a- // workout that has no end.- const since = workouts.filter(w => !lastAt || (w.end ? w.end > lastAt : w.d > new Date(lastAt).toISOString().slice(0, 10)));- if (!since.length) return false;+// Re-exported so nothing that reached it through this module has to move.+export { isDue };- if (cadence.everyWorkouts) {- return since.length >= Math.max(1, Math.min(20, cadence.everyWorkouts));- }- if (cadence.weekly) {- if (!now) return false;- // Due once the week's slot has passed and this week's review has not run — not on the one- // minute it falls. The tick is every 60 s and unaligned, so the exact-minute test lost the- // whole week to a restart, a redeploy or a busy event loop across that minute; the same- // reason the workout reminder stopped asking for its exact minute. `lastAt` is the marker- // that says whether it already ran: the server's own finished-review timestamps (the- // `reviewedAt` the caller computes from the job history) and the client's lastReview.- const at = weeklySlotAt(now, cadence.weekly.day ?? 0, cadence.weekly.time || '18:00', tz);- return at != null && lastAt < at;- }- return false;-}--/* When this week's slot fell, as an epoch timestamp — the clock `lastAt` is on.- *- * `now` is the user's own wall clock (date, hh:mm, weekday, from their reminder timezone) and- * the marker is epoch milliseconds, so a wall clock reading has to be turned into an instant.- * What turns one into the other is the zone's offset, and the offset that matters is the one AT- * the slot, not the one here now: the slot can be six days old, and twice a year the zone moved- * in between. Using today's offset on last Sunday's slot puts it an hour out, which on the- * fall-back Sunday is enough to call a review due eight hours before its time — and then again- * at its time, so the week gets two.- *- * So the slot is resolved at its own instant: instant = wall − offset(instant), settled in two- * passes. The first uses the offset where the caller is now (at most an hour out), the second the- * offset at that approximation, which is the slot's own on either side of a changeover. A wall- * clock inside a skipped hour names no instant at all; it lands within the hour either way, which- * is as close as the question ("has this week's slot passed") can be asked.- *- * "This week's" is the slot's most recent occurrence at or before now, so on the slot's own day- * but before its time it is last week's — which the last run is already past, so nothing fires- * early. Null when the shapes do not parse. */-function weeklySlotAt(now, wantDay, wantTime, tz) {- const d = /^(\d{4})-(\d{2})-(\d{2})$/.exec(now.date || '');- const nowMin = hhmmToMin(now.hhmm), wantMin = hhmmToMin(wantTime);- if (!d || !Number.isFinite(nowMin) || !Number.isFinite(wantMin)) return null;- const midnight = Date.UTC(+d[1], +d[2] - 1, +d[3]);- let back = (now.weekday - wantDay + 7) % 7;- if (back === 0 && nowMin < wantMin) back = 7;- const wall = midnight - back * 86400000 + wantMin * 60000;- const here = midnight + nowMin * 60000;- return wall - offsetAt(tz, wall - offsetAt(tz, Date.now(), here), here);-}-/* The zone's offset from UTC at one instant, in ms: what a wall clock reading there is ahead of- * the instant it names. Without a usable zone — no tz, or a string Intl refuses — it falls back- * to the offset where the caller is right now, which is all this ever had to go on. */-function offsetAt(tz, ms, hereWall) {- try {- const p = new Intl.DateTimeFormat('en-CA', {- timeZone: tz, hourCycle: 'h23',- year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit'- }).formatToParts(new Date(ms));- const g = t => Number(p.find(x => x.type === t).value);- return Date.UTC(g('year'), g('month') - 1, g('day'), g('hour'), g('minute'), g('second')) - ms;- } catch {- return hereWall - Date.now();- }-}-const hhmmToMin = v => {- const m = /^(\d{1,2}):(\d{2})$/.exec(v || '');- return m ? Number(m[1]) * 60 + Number(m[2]) : NaN;-};+const TICK_MS = 60000;/*** @param {object} deps { users(): [{id}], userNow(tz): {date,hhmm,weekday}, skip?(uid): bool }diff --git a/api/coach/core/due.js b/api/coach/core/due.jsnew file mode 100644index 000000000..e0b37909c--- /dev/null+++ b/api/coach/core/due.js@@ -0,0 +1,87 @@+/* When a scheduled review is due: the one rule, shared by the server's tick (../cadence.js) and+ * the phone that brings its own API key (frontend/src/lib/coach-local.js), which has no server+ * to run the tick for it. Pure: the caller hands in the clock, the run marker and the zone. */++/** Weekly cadence fires within the minute; everyWorkouts fires as soon as the count is met.+ * `reviewedAt` is when the server last finished a review for this person: the client stamps+ * lastReview only once someone acts on a proposal, and a review nobody has opened yet — or+ * one that found nothing to change — still read those workouts. */+export function isDue(coach, S, now, reviewedAt = 0, tz = null) {+ const cadence = coach.cadence;+ if (!cadence || cadence === 'off') return false;+ const lastAt = Math.max(coach.lastReview?.at || 0, reviewedAt);++ // Nothing new to read is the most common reason not to run, and it applies to both modes.+ const workouts = S.workouts || [];+ // A workout's `end` is on the same clock as the review's timestamp; its `d` is the phone's+ // local day, which can run ahead of the server's UTC day, so the date only stands in for a+ // workout that has no end.+ const since = workouts.filter(w => !lastAt || (w.end ? w.end > lastAt : w.d > new Date(lastAt).toISOString().slice(0, 10)));+ if (!since.length) return false;++ if (cadence.everyWorkouts) {+ return since.length >= Math.max(1, Math.min(20, cadence.everyWorkouts));+ }+ if (cadence.weekly) {+ if (!now) return false;+ // Due once the week's slot has passed and this week's review has not run — not on the one+ // minute it falls. The tick is every 60 s and unaligned, so the exact-minute test lost the+ // whole week to a restart, a redeploy or a busy event loop across that minute; the same+ // reason the workout reminder stopped asking for its exact minute. `lastAt` is the marker+ // that says whether it already ran: the server's own finished-review timestamps (the+ // `reviewedAt` the caller computes from the job history) and the client's lastReview.+ const at = weeklySlotAt(now, cadence.weekly.day ?? 0, cadence.weekly.time || '18:00', tz);+ return at != null && lastAt < at;+ }+ return false;+}++/* When this week's slot fell, as an epoch timestamp — the clock `lastAt` is on.+ *+ * `now` is the user's own wall clock (date, hh:mm, weekday, from their reminder timezone) and+ * the marker is epoch milliseconds, so a wall clock reading has to be turned into an instant.+ * What turns one into the other is the zone's offset, and the offset that matters is the one AT+ * the slot, not the one here now: the slot can be six days old, and twice a year the zone moved+ * in between. Using today's offset on last Sunday's slot puts it an hour out, which on the+ * fall-back Sunday is enough to call a review due eight hours before its time — and then again+ * at its time, so the week gets two.+ *+ * So the slot is resolved at its own instant: instant = wall − offset(instant), settled in two+ * passes. The first uses the offset where the caller is now (at most an hour out), the second the+ * offset at that approximation, which is the slot's own on either side of a changeover. A wall+ * clock inside a skipped hour names no instant at all; it lands within the hour either way, which+ * is as close as the question ("has this week's slot passed") can be asked.+ *+ * "This week's" is the slot's most recent occurrence at or before now, so on the slot's own day+ * but before its time it is last week's — which the last run is already past, so nothing fires+ * early. Null when the shapes do not parse. */+function weeklySlotAt(now, wantDay, wantTime, tz) {+ const d = /^(\d{4})-(\d{2})-(\d{2})$/.exec(now.date || '');+ const nowMin = hhmmToMin(now.hhmm), wantMin = hhmmToMin(wantTime);+ if (!d || !Number.isFinite(nowMin) || !Number.isFinite(wantMin)) return null;+ const midnight = Date.UTC(+d[1], +d[2] - 1, +d[3]);+ let back = (now.weekday - wantDay + 7) % 7;+ if (back === 0 && nowMin < wantMin) back = 7;+ const wall = midnight - back * 86400000 + wantMin * 60000;+ const here = midnight + nowMin * 60000;+ return wall - offsetAt(tz, wall - offsetAt(tz, Date.now(), here), here);+}+/* The zone's offset from UTC at one instant, in ms: what a wall clock reading there is ahead of+ * the instant it names. Without a usable zone — no tz, or a string Intl refuses — it falls back+ * to the offset where the caller is right now, which is all this ever had to go on. */+function offsetAt(tz, ms, hereWall) {+ try {+ const p = new Intl.DateTimeFormat('en-CA', {+ timeZone: tz, hourCycle: 'h23',+ year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', second: '2-digit'+ }).formatToParts(new Date(ms));+ const g = t => Number(p.find(x => x.type === t).value);+ return Date.UTC(g('year'), g('month') - 1, g('day'), g('hour'), g('minute'), g('second')) - ms;+ } catch {+ return hereWall - Date.now();+ }+}+const hhmmToMin = v => {+ const m = /^(\d{1,2}):(\d{2})$/.exec(v || '');+ return m ? Number(m[1]) * 60 + Number(m[2]) : NaN;+};diff --git a/docs/AI_COACH.md b/docs/AI_COACH.mdindex 70dc9773a..012437898 100644--- a/docs/AI_COACH.md+++ b/docs/AI_COACH.md@@ -476,6 +476,12 @@ The App-Store build has no server of its own, so the Coach there is a choice madsays which host each request goes to and what leaves the device before you choose, and alocal daily cap stands in for the one an admin would have set.+ Automatic reviews (weekly, or after every few workouts) run on the phone too, by the server's+ rule (`api/coach/core/due.js`), but only while the app is open: there is no server to run them+ and an app does not run JavaScript while it is closed. So a review that is due runs right after+ the workout that completes the count, or on the first open after the weekly slot, and says+ something only when it has a suggestion. Up to v1.4.2 nothing ran them on a phone at all.+A compatible endpoint has to be **`https://`** here. Android does not let apps sendunencrypted `http://` traffic, so a model on your LAN at `http://ollama.lan:11434` cannot bereached from the phone, and the setup screen says so as soon as such an address is typed.diff --git a/frontend/src/lib/coach-api.js b/frontend/src/lib/coach-api.jsindex 49fe76c57..90e6c596d 100644--- a/frontend/src/lib/coach-api.js+++ b/frontend/src/lib/coach-api.js@@ -9,7 +9,7 @@ import { useEffect, useState, useCallback, useRef } from 'react'import { api } from './api.js'import { DEMO } from './demo.js'import { MOBILE } from './mobile.js'-import { t, getLang } from './i18n.js'+import { t, tn, getLang } from './i18n.js'import { useStore } from '../store/useStore.js'import { todayForCoach } from './coach-context.js'import { useUI } from '../store/useUI.js'@@ -40,6 +40,9 @@ const local = async () => {// There is no admin card on a phone: the user is the operator, so failures go to them.localMod.setNotifier(ev => {const toast = useUI.getState().toast+ // An automatic review speaks only when it has something to suggest, like the server's+ // (api/coach/cadence.js): a skip, a failure or "nothing to change" nobody asked for is noise.+ if (ev.scheduled) { if (ev.kind === 'ready') announceProposal(ev.pending); return }if (ev.kind === 'failed') toast(jobErrorText(ev.errorClass, ev.detail))else if (ev.kind === 'nochange') toast(t('Nothing to change right now: {0}', String(ev.reading || '').slice(0, 140)))})@@ -92,6 +95,36 @@ export const requestDebrief = (...a) => asked(_requestDebrief)(...a).then(track)// (lib/coach-context.js): the server never holds it.const _askCoach = async text => DEMO ? (await demo()).demoAsk(S(), text) : LOCAL() ? (await local()).localAsk(S(), text, todayForCoach(S())) : api('/api/coach/ask', { method: 'POST', body: JSON.stringify({ text, today: todayForCoach(S()), lang: getLang() }) })export const askCoach = (...a) => asked(_askCoach)(...a).then(track)+// An automatic review, if one is due (lib/coach-schedule.js asks while the app is open). Only a+// phone with its own key runs them here; a server runs its own on its tick. The data-sharing+// question was asked when they were switched on, and nobody is there to ask it now: a "yes"+// withdrawn since (Coach menu, AI data sharing) means no run, not a dialog out of nowhere.+export async function scheduledReview() {+ if (DEMO || !LOCAL()) return null+ const { consentTarget, hasAiConsent } = await import('./coach-consent.js')+ const target = consentTarget(await disclosure(), 'device')+ if (target && !target.local && !await hasAiConsent(target)) return null+ return (await local()).localScheduled(S())+}+// "The Coach has something for you", for a proposal nobody is looking at yet: a toast while the+// app is on screen, a notification when it went to the background meanwhile (a review takes a+// minute or two). Never a permission prompt: notifications were allowed in Settings, or not.+const PROPOSAL_NOTIFICATION_ID = 3100+async function announceProposal(pending) {+ const n = (pending?.changes || []).length+ if (!n) return+ const body = tn('{0} suggestion', '{0} suggestions', n)+ if (typeof document === 'undefined' || document.visibilityState !== 'hidden') {+ useUI.getState().toast(t('Coach') + ': ' + body)+ return+ }+ try {+ const { LocalNotifications } = await import('@capacitor/local-notifications')+ if ((await LocalNotifications.checkPermissions()).display !== 'granted') return+ await LocalNotifications.schedule({ notifications: [{ id: PROPOSAL_NOTIFICATION_ID, title: t('Coach'), body, schedule: { at: new Date(Date.now() + 1000) } }] })+ } catch { /* no notification plugin: the proposal still waits in the Coach tab */ }+}+// The room: anonymous medians across the profiles on this instance that opted in. Only a// server has a room; a phone with its own key and the demo both answer locally.export const cohortStats = async () => DEMO ? (await demo()).demoCohort(S()) : LOCAL() ? { ok: false, enabled: false } : api('/api/coach/cohort')diff --git a/frontend/src/lib/coach-api.schedule.test.js b/frontend/src/lib/coach-api.schedule.test.jsnew file mode 100644index 000000000..a888477e6--- /dev/null+++ b/frontend/src/lib/coach-api.schedule.test.js@@ -0,0 +1,85 @@+// @vitest-environment happy-dom+// The phone's automatic reviews, at the door every Coach job goes through (Discord, 10-19). The+// data-sharing question was asked when they were switched on; nobody is there to ask it when one+// comes due, so a scheduled run never opens the sheet, and a yes withdrawn since means no run.+// And they speak only when there is something to suggest.+import { beforeEach, describe, expect, it, vi } from 'vitest'++const mocks = vi.hoisted(() => ({+ coachLocal: { mode: 'byok' },+ disclosure: { provider: 'openai', providerLabel: 'OpenAI API', host: 'api.openai.com', categories: [], version: 1 },+ notifier: null,+ toast: null,+}))+vi.mock('./demo.js', () => ({ DEMO: false, DEMO_SEEDED: 'gym_demo_seeded_v1', REPO: '' }))+vi.mock('./mobile.js', () => ({ MOBILE: true, readJsonFile: async () => null, writeJsonFile: async () => {} }))+vi.mock('./api.js', () => ({ api: vi.fn(async () => ({})) }))+vi.mock('../store/useStore.js', () => ({ useStore: { getState: () => ({ S: { coach: { cadence: { everyWorkouts: 3 } } }, coachLocal: mocks.coachLocal }) } }))+vi.mock('../store/useUI.js', () => ({ useUI: { getState: () => ({ toast: mocks.toast }) } }))+vi.mock('../components/CoachConsentSheet.jsx', () => ({ askAiConsent: vi.fn(async () => true) }))+vi.mock('./coach-local.js', () => ({+ setNotifier: vi.fn(fn => { mocks.notifier = fn }),+ localDisclosure: vi.fn(async () => mocks.disclosure),+ localScheduled: vi.fn(async () => ({ job: { id: 'local-1', trigger: 'scheduled' } })),+}))++const { askAiConsent } = await import('../components/CoachConsentSheet.jsx')+const local = await import('./coach-local.js')+const { scheduledReview } = await import('./coach-api.js')+const { allowAi, consentTarget, _resetAiConsent } = await import('./coach-consent.js')+const { checkScheduledReview, mayBeDue } = await import('./coach-schedule.js')++beforeEach(() => {+ vi.clearAllMocks()+ localStorage.clear()+ _resetAiConsent()+ mocks.coachLocal = { mode: 'byok' }+ mocks.toast = vi.fn()+})++describe('automatic reviews on a phone with its own key', () => {+ it('run with the yes given when they were switched on, and never ask again', async () => {+ await allowAi(consentTarget(mocks.disclosure, 'device'))+ expect(await scheduledReview()).toMatchObject({ job: { trigger: 'scheduled' } })+ expect(local.localScheduled).toHaveBeenCalledTimes(1)+ expect(askAiConsent).not.toHaveBeenCalled()+ })++ it('a yes withdrawn since means no run, and no dialog out of nowhere', async () => {+ expect(await scheduledReview()).toBeNull()+ expect(local.localScheduled).not.toHaveBeenCalled()+ expect(askAiConsent).not.toHaveBeenCalled()+ })++ it('a phone on its server leaves them to the server', async () => {+ mocks.coachLocal = { mode: 'server' }+ expect(await scheduledReview()).toBeNull()+ expect(local.localScheduled).not.toHaveBeenCalled()+ })++ it('speak only when there is something to suggest', async () => {+ await allowAi(consentTarget(mocks.disclosure, 'device'))+ await scheduledReview() // loads the phone's Coach, which hands over its notifier+ mocks.notifier({ kind: 'failed', errorClass: 'provider', detail: '503', scheduled: true })+ mocks.notifier({ kind: 'nochange', reading: 'All good.', scheduled: true })+ expect(mocks.toast).not.toHaveBeenCalled()+ mocks.notifier({ kind: 'ready', pending: { changes: [{ id: 'c1' }, { id: 'c2' }] }, scheduled: true })+ expect(mocks.toast).toHaveBeenCalledTimes(1)+ expect(mocks.toast.mock.calls[0][0]).toMatch(/2 suggestions/)+ // A run somebody asked for still reports its failure, as before.+ mocks.notifier({ kind: 'failed', errorClass: 'provider', detail: '503' })+ expect(mocks.toast).toHaveBeenCalledTimes(2)+ })++ it('the minute check says no before loading anything when nothing could be due', async () => {+ expect(mayBeDue({ coachLocal: { mode: 'byok' }, S: { coach: { cadence: 'off' } } })).toBe(false)+ expect(mayBeDue({ coachLocal: { mode: 'server' }, S: { coach: { cadence: { everyWorkouts: 3 } } } })).toBe(false)+ expect(mayBeDue({ coachLocal: null, S: { coach: { cadence: { weekly: { day: 0 } } } } })).toBe(false)+ expect(await checkScheduledReview(() => ({ coachLocal: { mode: 'byok' }, S: { coach: { cadence: 'off' } } }))).toBeNull()+ expect(local.localScheduled).not.toHaveBeenCalled()++ await allowAi(consentTarget(mocks.disclosure, 'device'))+ expect(await checkScheduledReview(() => ({ coachLocal: { mode: 'byok' }, S: { coach: { cadence: { everyWorkouts: 3 } } } }))).toBeTruthy()+ expect(local.localScheduled).toHaveBeenCalledTimes(1)+ })+})diff --git a/frontend/src/lib/coach-device.js b/frontend/src/lib/coach-device.jsindex 0410e87c5..5b4677d96 100644--- a/frontend/src/lib/coach-device.js+++ b/frontend/src/lib/coach-device.js@@ -3,7 +3,8 @@// Deliberately NOT part of S. S is the training log — it syncs to a paired server, travels in// the JSON export, and is what "back up your data" means. Which provider this phone talks to,// the pseudonym it uses, today's run count and a proposal waiting to be looked at are device-// facts, so they live in their own file next to the remote-pairing one. The API key itself is+// facts, so they live in their own file next to the remote-pairing one. So is when it last ran a+// review (`reviewedAt`): the marker its automatic reviews are timed from (coach-local.js). The API key itself is// not even here: see coach-secrets.js.//// This module is intentionally light. The setup screen imports it before the user has chosen@@ -14,7 +15,7 @@ const FILE = 'opengym-coach.json'export const COACH_MODES = ['off', 'server', 'byok']-const DEFAULTS = { mode: 'off', provider: null, model: null, baseUrl: null, handle: null, daily: null, pending: null }+const DEFAULTS = { mode: 'off', provider: null, model: null, baseUrl: null, handle: null, daily: null, pending: null, reviewedAt: null }let cache = nullexport async function loadCoachDevice() {diff --git a/frontend/src/lib/coach-local.js b/frontend/src/lib/coach-local.jsindex 0312322bb..c58f4a291 100644--- a/frontend/src/lib/coach-local.js+++ b/frontend/src/lib/coach-local.js@@ -18,6 +18,7 @@import * as payloadLib from '../../../api/coach/core/payload.js'import { runPipeline } from '../../../api/coach/core/pipeline.js'import { waitingProposal } from '../../../api/coach/core/pending.js'+import { isDue } from '../../../api/coach/core/due.js'import { HTTP_PROVIDERS, baseUrlFor } from '../../../api/coach/core/providers.js'import anthropic from '../../../api/coach/core/adapters/anthropic.js'import openai from '../../../api/coach/core/adapters/openai.js'@@ -98,13 +99,40 @@ export const localRefine = async (S, text) => {}export const localDebrief = (S, workoutId) => start(S, 'debrief', { workoutId: workoutId || null })export const localAsk = (S, text, today) => start(S, 'ask', { note: String(text || '').slice(0, 1000), today: today || null })++/* Automatic reviews. On a server the cadence tick runs them (api/coach/cadence.js); a phone with+ its own key has no server, and for a long time nothing ran them at all: the setting saved, the+ reviews never came (Discord, 10-19). So the phone asks the same question, with the same rule+ (core/due.js), whenever the app is open (lib/coach-schedule.js): right after a workout, and on+ the first open after a weekly slot. `reviewedAt` in the device file is the run marker, kept+ the way the server keeps its job history: a review the model answered counts, whether it+ proposed something, found nothing to change, or answered unusably (paid for all the same).+ Returns the started job, or null when nothing is due. Never throws: a skip is silent. */+export async function localScheduled(S, now = new Date()) {+ const cadence = S?.coach?.cadence+ if (job || !cadence || cadence === 'off' || !S?.coach?.consent?.agreedAt) return null+ const d = await loadCoachDevice()+ if (d.mode !== 'byok' || !ADAPTERS[d.provider]) return null+ // A proposal nobody has answered is not replaced by the next one, as on the server.+ if (d.pending && !(d.pending.expiresAt && d.pending.expiresAt < now.getTime())) return null+ if ((await capState()).used >= LOCAL_DAILY_CAP) return null+ const tz = deviceZone()+ if (!isDue(S.coach, S, wallClock(now), d.reviewedAt || 0, tz)) return null+ try { return await start(S, 'review', { scheduled: true }) } catch { return null }+}+// The phone's own clock, in the shape the server's userNow() hands the tick.+export function wallClock(now) {+ const p = n => String(n).padStart(2, '0')+ return { date: `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())}`, hhmm: `${p(now.getHours())}:${p(now.getMinutes())}`, weekday: now.getDay() }+}+const deviceZone = () => { try { return Intl.DateTimeFormat().resolvedOptions().timeZone || null } catch { return null } }// A read answer gives back the proposal it was asked beside, as the server does.export async function localResolve() {const d = await loadCoachDevice()await saveCoachDevice({ pending: d.pending?.kind === 'ask' ? waitingProposal(d.pending.prev) : null })return { ok: true }}-export async function localForget() { job = null; lastError = null; await saveCoachDevice({ pending: null, daily: null }); return { ok: true } }+export async function localForget() { job = null; lastError = null; await saveCoachDevice({ pending: null, daily: null, reviewedAt: null }); return { ok: true } }export async function localDisclosure() {const d = await loadCoachDevice()@@ -139,7 +167,7 @@ async function start(S, kind, opts) {if (cap.used >= cap.limit) throw Object.assign(new Error(t('The Coach is taking a breather. You’ve used today’s {0} runs on this phone.', cap.limit)), { status: 429, code: 'cap' })await bumpDaily()- job = { id: 'local-' + Date.now().toString(36), kind, state: 'running', startedAt: Date.now() }+ job = { id: 'local-' + Date.now().toString(36), kind, state: 'running', startedAt: Date.now(), ...(opts.scheduled ? { trigger: 'scheduled' } : {}) }lastError = null// Not awaited: the screens poll, exactly as they do against a server.run(S, kind, opts, d, adapter).catch(e => { lastError = { errorClass: 'internal', detail: String(e && e.message || e) } }).finally(() => { job = null })@@ -165,12 +193,14 @@ async function run(S, kind, opts, d, adapter) {: null)lastError = { errorClass: attempt.errorClass, detail }last = { id: job.id, kind, outcome: 'failed', errorClass: attempt.errorClass, at: Date.now() }- if (notify) notify({ kind: 'failed', errorClass: attempt.errorClass, detail })+ if (kind === 'review' && attempt.errorClass === 'unusable') await markReviewed()+ if (notify) notify({ kind: 'failed', errorClass: attempt.errorClass, detail, scheduled: !!opts.scheduled })return}if (attempt.nochange) {last = { id: job.id, kind, outcome: 'nochange', errorClass: null, at: Date.now(), reading: attempt.reading }- if (notify) notify({ kind: 'nochange', reading: attempt.reading })+ if (kind === 'review') await markReviewed()+ if (notify) notify({ kind: 'nochange', reading: attempt.reading, scheduled: !!opts.scheduled })return}const pending = {@@ -180,10 +210,12 @@ async function run(S, kind, opts, d, adapter) {...(kind === 'ask' ? { prev: waitingProposal((await loadCoachDevice()).pending) } : {}),...attempt.result}- await saveCoachDevice({ pending })+ await saveCoachDevice({ pending, ...(kind === 'review' ? { reviewedAt: Date.now() } : {}) })last = { id: job.id, kind, outcome: 'ready', errorClass: null, at: Date.now() }- if (notify) notify({ kind: 'ready', pending })+ if (notify) notify({ kind: 'ready', pending, scheduled: !!opts.scheduled })}+// Any review the model read counts as the latest one, asked for or scheduled, as on the server.+const markReviewed = () => saveCoachDevice({ reviewedAt: Date.now() })// The session a debrief is about, in the shape the card reads. The core builds it for the// server; the fallback covers a core that predates it.diff --git a/frontend/src/lib/coach-local.schedule.test.js b/frontend/src/lib/coach-local.schedule.test.jsnew file mode 100644index 000000000..b4c817879--- /dev/null+++ b/frontend/src/lib/coach-local.schedule.test.js@@ -0,0 +1,129 @@+// Automatic reviews on a phone with its own key (Discord, 10-19: "I enabled it a week ago and+// haven't gotten anything"). The server runs them on its tick; this phone has no server, and+// nothing ran them at all. Driven here like coach-local.test.js: the real pipeline, a fake+// provider, the device file in memory.+import { describe, it, expect, vi, beforeEach } from 'vitest'++const device = { data: null }+vi.mock('./mobile.js', () => ({+ MOBILE: true,+ readJsonFile: async () => device.data,+ writeJsonFile: async (_n, d) => { device.data = JSON.parse(JSON.stringify(d)) }+}))+vi.mock('./coach-secrets.js', () => ({ getApiKey: async () => 'sk-test-1' }))+const wire = { calls: [], answer: null }+vi.mock('./capacitor-fetch.js', () => ({+ nativeFetch: async (url, init) => {+ wire.calls.push({ url, body: JSON.parse(init.body) })+ const a = wire.answer+ return { ok: a.status < 300, status: a.status, text: async () => JSON.stringify(a.body), json: async () => a.body }+ }+}))++const local = await import('./coach-local.js')+const { _resetCoachDevice, loadCoachDevice } = await import('./coach-device.js')+const { EXERCISES } = await import('../../../api/coach/core/library-data.js')++const EX = EXERCISES[0].id+const chat = content => ({ status: 200, body: { choices: [{ finish_reason: 'stop', message: { content } }] } })+const REVIEW = { coach_contract: 1, summary: 'One tweak.', evidence: { from: '2026-10-01', to: '2026-10-15', sessions: 1 },+ changes: [{ id: 'c1', type: 'sets', target: { routineId: 'r1', exId: EX }, after: 4, why: 'every set was clean' }] }+const NOCHANGE = { coach_contract: 1, nochange: true, reading: 'Too early to judge.' }++const at = (d, h = 18, m = 0) => new Date(2026, 9, d, h, m) // October 2026, the phone's own clock+const workout = (id, end) => ({ id, d: '2026-10-' + String(end.getDate()).padStart(2, '0'), start: end.getTime() - 3600000, end: end.getTime(),+ entries: [{ id: EX, target: { sets: 3, reps: 8 }, sets: [{ done: true, w: 40, r: 8 }, { done: true, w: 40, r: 8 }, { done: true, w: 40, r: 8 }] }] })+const state = (cadence, workouts, lastReview = null) => ({+ unit: 'kg', lang: 'en',+ routines: [{ id: 'r1', name: 'A', ex: [{ id: EX, sets: 3, reps: 8, mode: 'reps' }] }],+ week: { 1: 'r1' }, dayPlan: {}, customEx: [], bodyweight: [], workouts,+ coach: { consent: { agreedAt: '2026-08-01T00:00:00Z', version: 1 }, profile: null, cadence, lastReview, log: [], snapshots: [] }+})++async function settle() {+ for (let i = 0; i < 200; i++) {+ const s = await local.localStatus()+ if (!s.job) return s+ await new Promise(r => setTimeout(r, 5))+ }+ throw new Error('never settled')+}++describe('automatic reviews on a phone with its own key', () => {+ const seen = []+ beforeEach(() => {+ _resetCoachDevice(); local._resetLocal()+ device.data = { mode: 'byok', provider: 'compatible', model: 'llama', baseUrl: 'https://llm.home.example/v1' }+ wire.calls = []; wire.answer = chat(JSON.stringify(REVIEW))+ seen.length = 0; local.setNotifier(ev => seen.push(ev))+ })++ it('after every few workouts: runs once the count is met, and once per batch', async () => {+ const S = state({ everyWorkouts: 2 }, [workout('w1', at(12))])+ expect(await local.localScheduled(S, at(12, 19))).toBeNull()+ expect(wire.calls).toHaveLength(0)++ S.workouts.push(workout('w2', at(14)))+ const started = await local.localScheduled(S, at(14, 19))+ expect(started?.job?.trigger).toBe('scheduled')+ const s = await settle()+ expect(wire.calls).toHaveLength(1)+ expect(wire.calls[0].url).toBe('https://llm.home.example/v1/chat/completions')+ expect(s.pending.kind).toBe('review')+ expect(seen.at(-1)).toMatchObject({ kind: 'ready', scheduled: true })++ // A proposal nobody has answered is not replaced, however many workouts follow.+ S.workouts.push(workout('w3', at(15)), workout('w4', at(16)))+ expect(await local.localScheduled(S, at(16, 19))).toBeNull()++ // Answered: the two workouts it read are not read again; two new ones are a new batch.+ await local.localResolve()+ const reviewedAt = (await loadCoachDevice()).reviewedAt+ expect(reviewedAt).toBeGreaterThan(0)+ S.workouts = S.workouts.map(w => ({ ...w, end: Math.min(w.end, reviewedAt - 1) }))+ expect(await local.localScheduled(S, new Date(reviewedAt + 60000))).toBeNull()+ S.workouts.push(workout('w5', new Date(reviewedAt + 3600000)), workout('w6', new Date(reviewedAt + 7200000)))+ expect(await local.localScheduled(S, new Date(reviewedAt + 7300000))).toBeTruthy()+ await settle()+ expect(wire.calls).toHaveLength(2)+ })++ it('weekly: not before the slot, on the first look after it, and not again that week', async () => {+ wire.answer = chat(JSON.stringify(NOCHANGE))+ // Sunday 18:00. The last review was the Sunday before; a workout since.+ const S = state({ weekly: { day: 0, time: '18:00' } }, [workout('w1', at(14))], { at: at(11, 18, 5).getTime() })+ expect(await local.localScheduled(S, at(18, 17, 30))).toBeNull()+ expect(await local.localScheduled(S, at(18, 18, 0))).toBeTruthy()+ await settle()+ expect(wire.calls).toHaveLength(1)+ // "Nothing to change" counts as this week's review, and says nothing about it.+ expect(seen.at(-1)).toMatchObject({ kind: 'nochange', scheduled: true })+ S.workouts.push(workout('w2', new Date(Date.now() + 60000)))+ expect(await local.localScheduled(S, at(18, 21, 0))).toBeNull()+ expect(wire.calls).toHaveLength(1)+ })++ it('a phone the slot passed while closed runs it on the next open', async () => {+ wire.answer = chat(JSON.stringify(NOCHANGE))+ const S = state({ weekly: { day: 0, time: '18:00' } }, [workout('w1', at(14))], { at: at(11, 18, 5).getTime() })+ expect(await local.localScheduled(S, at(20, 7, 45))).toBeTruthy() // Tuesday morning+ await settle()+ expect(wire.calls).toHaveLength(1)+ })++ it('stays out of the way: off, no consent, another mode, a job running', async () => {+ const two = [workout('w1', at(12)), workout('w2', at(13))]+ expect(await local.localScheduled(state('off', two), at(14))).toBeNull()+ const noConsent = state({ everyWorkouts: 1 }, two); noConsent.coach.consent = null+ expect(await local.localScheduled(noConsent, at(14))).toBeNull()+ device.data = { ...device.data, mode: 'server' }; _resetCoachDevice()+ expect(await local.localScheduled(state({ everyWorkouts: 1 }, two), at(14))).toBeNull()+ expect(wire.calls).toHaveLength(0)++ device.data = { ...device.data, mode: 'byok' }; _resetCoachDevice()+ await local.localReview(state('off', two))+ expect(await local.localScheduled(state({ everyWorkouts: 1 }, two), at(14))).toBeNull()+ await settle()+ expect(wire.calls).toHaveLength(1)+ })+})diff --git a/frontend/src/lib/coach-schedule.js b/frontend/src/lib/coach-schedule.jsnew file mode 100644index 000000000..b1e544cc5--- /dev/null+++ b/frontend/src/lib/coach-schedule.js@@ -0,0 +1,48 @@+// Automatic reviews on a phone that brings its own API key (Discord, 10-19).+//+// On a server the cadence tick runs them (api/coach/cadence.js). A phone in BYOK mode has no+// server, and nothing ran them: "Weekly" and "After every few workouts" saved, and no review ever+// came. There is no running JavaScript while the app is closed, so the phone asks while it is+// open, with the server's rule (api/coach/core/due.js): on start, on every return to the+// foreground, and once a minute while on screen. That last one is what catches a workout the+// moment it is finished, and a weekly slot that passes with the app open.+//+// The check itself is cheap and says no early: anything but a phone in BYOK mode with automatic+// reviews on stops here, before the Coach's code is even loaded.+import { MOBILE } from './mobile.js'++const TICK_MS = 60000++/** Whether this state could have a review due here at all, before anything is loaded. */+export function mayBeDue(store) {+ const cadence = store?.S?.coach?.cadence+ return store?.coachLocal?.mode === 'byok' && !!cadence && cadence !== 'off'+}++let running = false+/** One look: runs the review when it is due. Resolves to the started job, or null. */+export async function checkScheduledReview(getStore) {+ if (running || !mayBeDue(getStore())) return null+ running = true+ try {+ const { scheduledReview } = await import('./coach-api.js')+ return await scheduledReview()+ } catch { return null } finally { running = false }+}++let started = false+export function initCoachSchedule(getStore) {+ if (!MOBILE || started) return+ started = true+ const look = () => {+ if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return+ checkScheduledReview(getStore)+ }+ setTimeout(look, 5000) // after start-up, not in the middle of it+ setInterval(look, TICK_MS)+ if (typeof document !== 'undefined') document.addEventListener('visibilitychange', look)+ // The same promise rule as initReminderSync (lib/mobile.js): returned into the catch.+ import('@capacitor/app').then(({ App }) =>+ App.addListener('appStateChange', ({ isActive }) => { if (isActive) look() })+ ).catch(() => {})+}diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.jsindex 20e675f15..96ce359d8 100644--- a/frontend/src/locales/ar.js+++ b/frontend/src/locales/ar.js@@ -804,6 +804,7 @@ export default {'Automatic reviews': 'مراجعات تلقائية','Off. The Coach only looks when you ask.': 'متوقف. لا ينظر المدرب إلا عندما تطلب منه.','You are only notified when the Coach actually has something to suggest.': 'لا يصلك إشعار إلا عندما يكون لدى المدرب ما يقترحه فعلًا.',+ 'On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.': 'على هذا الهاتف لا يستطيع المدرب النظر إلا والتطبيق مفتوح: بعد التمرين مباشرة، أو في المرة التالية التي تفتحه فيها.','When': 'متى','Weekly': 'أسبوعيًا','On a day and time you choose': 'في يوم ووقت تختارهما',diff --git a/frontend/src/locales/bn.js b/frontend/src/locales/bn.jsindex 83f35aaae..92cc05958 100644--- a/frontend/src/locales/bn.js+++ b/frontend/src/locales/bn.js@@ -930,6 +930,7 @@ export default {'Automatic reviews': 'স্বয়ংক্রিয় রিভিউ','Off. The Coach only looks when you ask.': 'বন্ধ। আপনি চাইলে তবেই কোচ দেখে।','You are only notified when the Coach actually has something to suggest.': 'কোচের সত্যিই কোনো পরামর্শ থাকলে তবেই আপনাকে জানানো হয়।',+ 'On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.': 'এই ফোনে অ্যাপ খোলা থাকলেই কোচ দেখতে পারে: ওয়ার্কআউটের ঠিক পরে, বা পরের বার আপনি অ্যাপটি খুললে।','When': 'কখন','Weekly': 'সাপ্তাহিক','On a day and time you choose': 'আপনার বেছে নেওয়া দিন ও সময়ে',diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex 8311b6450..c4ee2b60a 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -866,6 +866,7 @@ export default {'Automatic reviews': 'Automatische Auswertungen','Off. The Coach only looks when you ask.': 'Aus. Der Coach schaut nur, wenn du ihn fragst.','You are only notified when the Coach actually has something to suggest.': 'Du wirst nur benachrichtigt, wenn der Coach wirklich etwas vorzuschlagen hat.',+ 'On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.': 'Auf diesem Handy kann der Coach nur nachsehen, solange die App offen ist: direkt nach einem Training oder beim nächsten Öffnen.','When': 'Wann','Weekly': 'Wöchentlich','On a day and time you choose': 'An einem Tag und zu einer Uhrzeit deiner Wahl',diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex 280b13721..20b82b39d 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -848,6 +848,7 @@ export default {'Automatic reviews': 'Revisiones automáticas','Off. The Coach only looks when you ask.': 'Desactivado. El Entrenador solo mira cuando se lo pides.','You are only notified when the Coach actually has something to suggest.': 'Solo recibes aviso cuando el Entrenador tiene algo que sugerir.',+ 'On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.': 'En este móvil el Entrenador solo puede mirar mientras la app está abierta: justo después de un entrenamiento o la próxima vez que la abras.','When': 'Cuándo','Weekly': 'Semanal','On a day and time you choose': 'El día y la hora que elijas',diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex 0eb5769e3..927f2b890 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -848,6 +848,7 @@ export default {'Automatic reviews': 'Bilans automatiques','Off. The Coach only looks when you ask.': 'Désactivés. Le Coach ne regarde que si tu le lui demandes.','You are only notified when the Coach actually has something to suggest.': 'Tu n’es prévenu que lorsque le Coach a vraiment quelque chose à proposer.',+ 'On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.': 'Sur ce téléphone, le Coach ne peut regarder que quand l’app est ouverte : juste après une séance, ou la prochaine fois que tu l’ouvres.','When': 'Quand','Weekly': 'Hebdomadaire','On a day and time you choose': 'Le jour et à l’heure de ton choix',diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex f8857fb07..dec360d4b 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -848,6 +848,7 @@ export default {'Automatic reviews': 'स्वचालित समीक्षाएँ','Off. The Coach only looks when you ask.': 'बंद। कोच तभी देखता है जब आप कहें।','You are only notified when the Coach actually has something to suggest.': 'सूचना तभी मिलती है जब कोच के पास वाकई कुछ सुझाने को हो।',+ 'On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.': 'इस फ़ोन पर कोच तभी देख सकता है जब ऐप खुला हो: वर्कआउट के ठीक बाद, या अगली बार जब आप इसे खोलें।','When': 'कब','Weekly': 'साप्ताहिक','On a day and time you choose': 'आपके चुने दिन और समय पर',diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex 70f5c8e1f..f70a28cb1 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -1006,6 +1006,7 @@ export default {'Automatic reviews': 'Automatikus áttekintések','Off. The Coach only looks when you ask.': 'Ki. Az Edző csak akkor néz rá, ha kéred.','You are only notified when the Coach actually has something to suggest.': 'Csak akkor kapsz értesítést, ha az Edzőnek tényleg van javaslata.',+ 'On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.': 'Ezen a telefonon az Edző csak akkor tud ránézni, amikor az app nyitva van: rögtön egy edzés után, vagy amikor legközelebb megnyitod.','When': 'Mikor','Weekly': 'Hetente','On a day and time you choose': 'Az általad választott napon és időben',diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex 107c7713a..e8b245e0f 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -848,6 +848,7 @@ export default {'Automatic reviews': 'Revisioni automatiche','Off. The Coach only looks when you ask.': 'Disattivate. Il Coach guarda solo quando glielo chiedi.','You are only notified when the Coach actually has something to suggest.': 'Ricevi una notifica solo quando il Coach ha davvero qualcosa da suggerire.',+ 'On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.': 'Su questo telefono il Coach può dare un’occhiata solo mentre l’app è aperta: subito dopo un allenamento o la prossima volta che la apri.','When': 'Quando','Weekly': 'Settimanale','On a day and time you choose': 'Nel giorno e nell’ora che scegli',diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex 314c45d81..13fd54cac 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -848,6 +848,7 @@ export default {'Automatic reviews': '자동 리뷰','Off. The Coach only looks when you ask.': '꺼짐. 코치는 요청할 때만 살펴봐요.','You are only notified when the Coach actually has something to suggest.': '코치가 실제로 제안할 것이 있을 때만 알림이 옵니다.',+ 'On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.': '이 폰에서는 앱이 열려 있을 때만 코치가 살펴볼 수 있어요: 운동 직후, 또는 다음에 앱을 열 때.','When': '시점','Weekly': '매주','On a day and time you choose': '내가 고른 요일과 시각에',diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex e8532afee..90d92344a 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -848,6 +848,7 @@ export default {'Automatic reviews': 'Automatyczne przeglądy','Off. The Coach only looks when you ask.': 'Wyłączone. Trener patrzy tylko wtedy, gdy go poprosisz.','You are only notified when the Coach actually has something to suggest.': 'Powiadomienie dostajesz tylko wtedy, gdy Trener naprawdę ma coś do zaproponowania.',+ 'On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.': 'Na tym telefonie Trener może zajrzeć tylko wtedy, gdy aplikacja jest otwarta: zaraz po treningu albo przy następnym otwarciu.','When': 'Kiedy','Weekly': 'Co tydzień','On a day and time you choose': 'W wybranym dniu i o wybranej godzinie',diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex e44bdd7c2..25d33f154 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -508,6 +508,7 @@ export const PT_BR_OVERRIDES = {'Review': 'Revisar','Off. The Coach only looks when you ask.': 'Desligado. O Treinador só olha quando você pede.','You are only notified when the Coach actually has something to suggest.': 'Você só é avisado quando o Treinador realmente tem algo a sugerir.',+ 'On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.': 'Neste celular o Treinador só consegue olhar enquanto o app está aberto: logo depois de um treino, ou na próxima vez que você abrir.','On a day and time you choose': 'No dia e hora que você escolher','As soon as you have logged enough': 'Assim que você tiver registrado o suficiente','Your plan': 'Seu plano',diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex 2bed6802d..956a18012 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -848,6 +848,7 @@ export default {'Automatic reviews': 'Revisões automáticas','Off. The Coach only looks when you ask.': 'Desligado. O Treinador só analisa quando lhe pedes.','You are only notified when the Coach actually has something to suggest.': 'Só recebes aviso quando o Treinador tem mesmo algo a sugerir.',+ 'On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.': 'Neste telemóvel o Treinador só pode ver enquanto a app está aberta: logo a seguir a um treino, ou da próxima vez que a abrires.','When': 'Quando','Weekly': 'Semanal','On a day and time you choose': 'No dia e hora que escolheres',diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex 3b8185d40..e95cf9817 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -829,6 +829,7 @@ export default {'Automatic reviews': 'Автоматические разборы','Off. The Coach only looks when you ask.': 'Выключено. Тренер смотрит, только когда вы просите.','You are only notified when the Coach actually has something to suggest.': 'Уведомление приходит, только если Тренеру действительно есть что предложить.',+ 'On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.': 'На этом телефоне Тренер может посмотреть, только пока приложение открыто: сразу после тренировки или при следующем открытии.','When': 'Когда','Weekly': 'Еженедельно','On a day and time you choose': 'В выбранный день и час',diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex 49ac1f7e1..a1e0e7e3a 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -1014,6 +1014,7 @@ export default {'Automatic reviews': 'รีวิวอัตโนมัติ','Off. The Coach only looks when you ask.': 'ปิดอยู่ โค้ชจะดูเฉพาะตอนที่คุณขอเท่านั้น','You are only notified when the Coach actually has something to suggest.': 'คุณจะได้รับแจ้งเตือนเฉพาะเมื่อโค้ชมีข้อเสนอแนะจริง ๆ',+ 'On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.': 'บนโทรศัพท์เครื่องนี้ โค้ชดูได้เฉพาะตอนที่แอปเปิดอยู่: ทันทีหลังออกกำลังกาย หรือครั้งถัดไปที่คุณเปิดแอป','When': 'เมื่อไร','Weekly': 'รายสัปดาห์','On a day and time you choose': 'ในวันและเวลาที่คุณเลือก',diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex 804df3808..234bd46ba 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -848,6 +848,7 @@ export default {'Automatic reviews': 'Otomatik değerlendirmeler','Off. The Coach only looks when you ask.': 'Kapalı. Koç yalnızca sen istediğinde bakar.','You are only notified when the Coach actually has something to suggest.': 'Yalnızca Koç’un gerçekten önerecek bir şeyi olduğunda bildirim alırsın.',+ 'On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.': 'Bu telefonda Koç yalnızca uygulama açıkken bakabilir: bir antrenmandan hemen sonra ya da uygulamayı bir sonraki açışında.','When': 'Ne zaman','Weekly': 'Haftalık','On a day and time you choose': 'Seçtiğin gün ve saatte',diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.jsindex 3ccf906a8..d8a69d961 100644--- a/frontend/src/locales/uk.js+++ b/frontend/src/locales/uk.js@@ -658,6 +658,7 @@ export default {'Automatic reviews': 'Автоматичні розбори','Off. The Coach only looks when you ask.': 'Вимкнено. Тренер дивиться лише тоді, коли ти просиш.','You are only notified when the Coach actually has something to suggest.': 'Сповіщення приходить, лише якщо Тренеру справді є що запропонувати.',+ 'On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.': 'На цьому телефоні Тренер може зазирнути, лише поки застосунок відкритий: одразу після тренування або коли ти відкриєш його наступного разу.','When': 'Коли','Weekly': 'Щотижня','On a day and time you choose': 'У вибраний день і час',diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.jsindex a564122cb..46dcf2095 100644--- a/frontend/src/locales/zh-TW.js+++ b/frontend/src/locales/zh-TW.js@@ -840,6 +840,7 @@ export default {'Automatic reviews': '定期自動檢討','Off. The Coach only looks when you ask.': '已關閉。教練只在你開口時才會看。','You are only notified when the Coach actually has something to suggest.': '僅在教練有實質性調整建議時才會主動發出通知。',+ 'On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.': '在這支手機上,教練只能在 App 開著時查看:剛練完的時候,或你下次打開 App 時。','When': '時機','Weekly': '每週定期','On a day and time you choose': '在自訂的特定日期與時間',diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex 5fb5d470c..84f9a50e3 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -848,6 +848,7 @@ export default {'Automatic reviews': '自动复盘','Off. The Coach only looks when you ask.': '已关闭。教练只在你开口时才看。','You are only notified when the Coach actually has something to suggest.': '只有当教练确实有建议时才会通知你。',+ 'On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.': '在这部手机上,教练只能在应用打开时查看:刚练完的时候,或者你下次打开应用时。','When': '时间','Weekly': '每周','On a day and time you choose': '在你选定的日期和时间',diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex ad27bd6ad..9a797c587 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -23,6 +23,7 @@ import { linkTokenFromSearch, stripLinkFromUrl } from '../lib/device-link.js'import { loadRemote, chooseLocal, forgetRemote, connect, normalizeServerUrl, renewToken } from '../lib/remote.js'import { loadCfAccess } from '../lib/cf-access.js'import { loadCoachDevice, saveCoachDevice, coachDeviceSettings } from '../lib/coach-device.js'+import { initCoachSchedule } from '../lib/coach-schedule.js'import { RTL_LANGS } from '../lib/i18n-core.js'import { DEFAULT_TEMPLATE_ID } from '../lib/structuralBalanceTemplates.js'@@ -509,6 +510,8 @@ export const useStore = create((set, get) => {}initReminderSync(() => get().S)+ // A phone with its own Coach key runs its automatic reviews itself, while the app is open.+ initCoachSchedule(() => get())// What it reads back from the health hub (heart rate, weigh-ins) goes in as any change does.initHealthSync(() => get().S, fn => get().update(fn))diff --git a/frontend/src/views/CoachChat.jsx b/frontend/src/views/CoachChat.jsxindex b1e067f40..705066f83 100644--- a/frontend/src/views/CoachChat.jsx+++ b/frontend/src/views/CoachChat.jsx@@ -772,6 +772,9 @@ function CadenceSheet({ update }) {const coach = useStore(s => s.S.coach) || emptyCoach()const cadence = coach.cadence && coach.cadence !== 'off' ? coach.cadence : nullconst mode = !cadence ? 'off' : cadence.weekly ? 'weekly' : 'every'+ // A phone with its own key runs them itself, and only while the app is open (lib/coach-schedule.js).+ const deviceMode = useStore(s => s.coachLocal?.mode)+ const onPhone = MOBILE && deviceMode === 'byok'// Automatic reviews send your training while nobody is looking, so switching them on is where// the data-sharing question is asked for them. "Not now" leaves them off.const setMode = async m => {@@ -786,7 +789,8 @@ function CadenceSheet({ update }) {const patch = fn => update(s => { const c = (s.coach = s.coach || emptyCoach()); fn(c) })return <><h3>{t('Automatic reviews')}</h3>- <Section footer={mode === 'off' ? t('Off. The Coach only looks when you ask.') : t('You are only notified when the Coach actually has something to suggest.')}>+ <Section footer={mode === 'off' ? t('Off. The Coach only looks when you ask.') : t('You are only notified when the Coach actually has something to suggest.')+ + (onPhone ? ' ' + t('On this phone the Coach can only look while the app is open: right after a workout, or the next time you open it.') : '')}><SelectRow icon="clock" iconTint="var(--purple)" title={t('When')} value={mode} onChange={setMode}options={[{ value: 'off', label: t('Off') },