Skip to content

Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.

Coach: a paired phone hears about the server's automatic review (Discord)

Duarte Santos2fccc98191fd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8a9791847..ec4b571ec 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -119,6 +119,9 @@ you leave it alone. Handy for deciding whether those legs are really ready (than
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.
+- A phone app connected to your server now hears about a suggestion the server's automatic
+ review left. The server only knew how to say it by web push, which the app doesn't have, so the
+ review ran and the phone stayed quiet. Now the app tells you when you next open it.
## v1.4.2 (2026-10-18)
diff --git a/api/coach/jobs.js b/api/coach/jobs.js
index 9bddf90dc..d64764465 100644
--- a/api/coach/jobs.js
+++ b/api/coach/jobs.js
@@ -156,7 +156,7 @@ export function status(uid) {
}
function lastOutcome(rec) {
const h = (rec.history || []).at(-1);
- return h ? { id: h.id, kind: h.kind, outcome: h.outcome, errorClass: h.errorClass || null, at: h.at, ...(h.reading ? { reading: h.reading } : {}) } : null;
+ return h ? { id: h.id, kind: h.kind, outcome: h.outcome, errorClass: h.errorClass || null, at: h.at, ...(h.trigger === 'scheduled' ? { trigger: 'scheduled' } : {}), ...(h.reading ? { reading: h.reading } : {}) } : null;
}
function archive(uid, rec, outcome) {
const history = [...(rec.history || []), {
@@ -394,6 +394,9 @@ async function execute(job) {
expiresAt: Date.now() + PENDING_DAYS * 86400000,
planHash: hashPlan(payloadLib.canonicalPlan(S)),
iteration: job.refine ? (pendingCreate?.iteration || 1) + 1 : 1,
+ // Nobody asked for a scheduled one, so nobody is watching for it: a phone app has no web
+ // push, and says so itself when it next comes to the foreground (lib/coach-schedule.js).
+ ...(job.trigger === 'scheduled' ? { trigger: 'scheduled' } : {}),
// A debrief names the session it read, so the card can show it after the fact.
...(job.kind === 'debrief' ? { workout: payloadLib.workoutMeta(S, job.workoutId) } : {}),
...(job.kind === 'ask' ? { prev: waitingProposal(readUser(job.uid).pending) } : {}),
diff --git a/api/openapi.yaml b/api/openapi.yaml
index 6cb5b2226..9d3007802 100644
--- a/api/openapi.yaml
+++ b/api/openapi.yaml
@@ -4071,6 +4071,7 @@ components:
oneOf: [{ type: string }, { type: 'null' }]
description: e.g. `provider`, `unusable`, `restart`, `forgotten`, `consent`, `noworkout`.
at: { type: integer, description: Epoch ms. }
+ trigger: { type: string, enum: [scheduled], description: Present when it was an automatic review. }
reading: { type: string, description: "Present on `nochange`: why there was nothing to change." }
- type: 'null'
@@ -4088,6 +4089,7 @@ components:
expiresAt: { type: integer, description: Epoch ms. }
planHash: { type: string, description: The plan this was written against. A later edit makes it stale. }
iteration: { type: integer, description: "1, or higher after a refine." }
+ trigger: { type: string, enum: [scheduled], description: "Present when an automatic review made it, which nobody was watching for." }
summary: { type: string, maxLength: 1200 }
changes:
type: array
diff --git a/api/test/coach-limits.test.js b/api/test/coach-limits.test.js
index dab991da3..44952ec05 100644
--- a/api/test/coach-limits.test.js
+++ b/api/test/coach-limits.test.js
@@ -251,6 +251,9 @@ test('a proposal nobody has answered is not replaced by the next scheduled revie
const first = await settle(uid);
assert.equal(lastOutcome(uid).outcome, 'ready');
assert.ok(first.pending, 'a proposal is waiting');
+ // Nobody asked for it, so the phone app (no web push) is told by the status it reads (Discord).
+ assert.equal(first.pending.trigger, 'scheduled');
+ assert.equal(first.last.trigger, 'scheduled');
S.workouts.push(newWorkout('w2'));
writeState(DIR, uid, S);
@@ -264,6 +267,13 @@ test('a proposal nobody has answered is not replaced by the next scheduled revie
assert.ok(jobs.status(uid).job, 'the workout since the last review is due');
await settle(uid);
assert.equal(jobs.readUser(uid).history.filter(h => h.outcome === 'ready').length, 2);
+
+ // One somebody asked for is not marked.
+ jobs.resolvePending(uid, { dismissed: true });
+ jobs.enqueue(uid, { kind: 'review' });
+ const asked = await settle(uid);
+ assert.equal(asked.pending.trigger, undefined);
+ assert.equal(asked.last.trigger, undefined);
});
test('a rejected answer tells the admin which rule broke, without quoting the plan', async () => {
diff --git a/docs/AI_COACH.md b/docs/AI_COACH.md
index 012437898..8ddf906db 100644
--- a/docs/AI_COACH.md
+++ b/docs/AI_COACH.md
@@ -467,7 +467,9 @@ The App-Store build has no server of its own, so the Coach there is a choice mad
- **Use my self-hosted openGym.** Pair the phone with your instance (the same pairing flow as
syncing — **Settings → Account → Pair the mobile app** on the site, then the address and code on the
phone). A paired phone is an ordinary profile: the Coach runs on your server with whatever
- provider the admin configured, under the rules above, and nothing on the phone changes.
+ provider the admin configured, under the rules above, and nothing on the phone changes. The
+ one thing the server cannot do is push to the app, so a suggestion its automatic review left
+ is announced by the app itself, once, when it next comes to the foreground.
- **Bring my own API key.** The phone calls Anthropic, OpenAI, Gemini or a compatible endpoint
directly, with a key you paste. It runs the same payload allowlist, the same validator and
the same single repair round as the server, in the app. The key is kept in the platform's
diff --git a/frontend/src/lib/coach-api.js b/frontend/src/lib/coach-api.js
index 90e6c596d..bfdc53aa1 100644
--- a/frontend/src/lib/coach-api.js
+++ b/frontend/src/lib/coach-api.js
@@ -106,6 +106,18 @@ export async function scheduledReview() {
if (target && !target.local && !await hasAiConsent(target)) return null
return (await local()).localScheduled(S())
}
+// A phone paired with a server leaves the reviews to the server's tick, and the server tells
+// people about a proposal by web push, which the phone app does not have. So the phone asks once
+// when it comes to the foreground, and says it once per proposal.
+const ANNOUNCED_KEY = 'gym_coach_announced'
+export async function scheduledNotice() {
+ if (DEMO || LOCAL() || !MOBILE) return null
+ const p = (await api('/api/coach/status'))?.pending
+ if (!p || p.trigger !== 'scheduled') return null
+ try { if (localStorage.getItem(ANNOUNCED_KEY) === p.id) return null; localStorage.setItem(ANNOUNCED_KEY, p.id) } catch { /* said again next time, at worst */ }
+ await announceProposal(p)
+ return p
+}
// "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.
diff --git a/frontend/src/lib/coach-api.schedule.test.js b/frontend/src/lib/coach-api.schedule.test.js
index a888477e6..296f6187b 100644
--- a/frontend/src/lib/coach-api.schedule.test.js
+++ b/frontend/src/lib/coach-api.schedule.test.js
@@ -10,10 +10,11 @@ const mocks = vi.hoisted(() => ({
disclosure: { provider: 'openai', providerLabel: 'OpenAI API', host: 'api.openai.com', categories: [], version: 1 },
notifier: null,
toast: null,
+ status: {},
}))
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('./api.js', () => ({ api: vi.fn(async () => mocks.status) }))
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) }))
@@ -25,9 +26,10 @@ vi.mock('./coach-local.js', () => ({
const { askAiConsent } = await import('../components/CoachConsentSheet.jsx')
const local = await import('./coach-local.js')
-const { scheduledReview } = await import('./coach-api.js')
+const { api } = await import('./api.js')
+const { scheduledReview, scheduledNotice } = await import('./coach-api.js')
const { allowAi, consentTarget, _resetAiConsent } = await import('./coach-consent.js')
-const { checkScheduledReview, mayBeDue } = await import('./coach-schedule.js')
+const { checkScheduledReview, mayBeDue, mayHaveNews } = await import('./coach-schedule.js')
beforeEach(() => {
vi.clearAllMocks()
@@ -35,6 +37,7 @@ beforeEach(() => {
_resetAiConsent()
mocks.coachLocal = { mode: 'byok' }
mocks.toast = vi.fn()
+ mocks.status = {}
})
describe('automatic reviews on a phone with its own key', () => {
@@ -83,3 +86,41 @@ describe('automatic reviews on a phone with its own key', () => {
expect(local.localScheduled).toHaveBeenCalledTimes(1)
})
})
+
+describe('a phone paired with a server', () => {
+ const paired = { coachLocal: { mode: 'off' }, config: { coach: { enabled: true } }, user: { id: 'u1' }, S: { coach: { cadence: { weekly: { day: 0 } } } } }
+ const proposal = id => ({ id, kind: 'review', trigger: 'scheduled', changes: [{ id: 'c1' }] })
+
+ it('hears about a proposal the server\'s automatic review left, once', async () => {
+ mocks.coachLocal = { mode: 'off' }
+ mocks.status = { job: null, pending: proposal('p1') }
+ expect(await scheduledNotice()).toMatchObject({ id: 'p1' })
+ expect(api).toHaveBeenCalledWith('/api/coach/status')
+ expect(mocks.toast).toHaveBeenCalledTimes(1)
+ expect(mocks.toast.mock.calls[0][0]).toMatch(/1 suggestion/)
+ expect(await scheduledNotice()).toBeNull()
+ expect(mocks.toast).toHaveBeenCalledTimes(1)
+ mocks.status = { job: null, pending: proposal('p2') }
+ await scheduledNotice()
+ expect(mocks.toast).toHaveBeenCalledTimes(2)
+ })
+
+ it('says nothing about a proposal somebody asked for', async () => {
+ mocks.coachLocal = { mode: 'server' }
+ mocks.status = { job: null, pending: { ...proposal('p3'), trigger: undefined } }
+ expect(await scheduledNotice()).toBeNull()
+ expect(mocks.toast).not.toHaveBeenCalled()
+ })
+
+ it('asks only on the way back to the foreground, and only with automatic reviews on', async () => {
+ expect(mayHaveNews(paired)).toBe(true)
+ expect(mayHaveNews({ ...paired, coachLocal: { mode: 'byok' } })).toBe(false)
+ expect(mayHaveNews({ ...paired, config: {} })).toBe(false)
+ expect(mayHaveNews({ ...paired, S: { coach: { cadence: 'off' } } })).toBe(false)
+ mocks.coachLocal = { mode: 'off' }
+ mocks.status = { job: null, pending: proposal('p4') }
+ expect(await checkScheduledReview(() => paired)).toBeNull()
+ expect(api).not.toHaveBeenCalled()
+ expect(await checkScheduledReview(() => paired, true)).toMatchObject({ id: 'p4' })
+ })
+})
diff --git a/frontend/src/lib/coach-schedule.js b/frontend/src/lib/coach-schedule.js
index b1e544cc5..a28e2b317 100644
--- a/frontend/src/lib/coach-schedule.js
+++ b/frontend/src/lib/coach-schedule.js
@@ -7,8 +7,12 @@
// 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.
+// A phone paired with a server leaves the running to the server, which has no way to reach the
+// phone app (no web push there): on start and on every return to the foreground the phone asks
+// whether a scheduled review left a proposal, and says so once.
+//
+// The check itself is cheap and says no early: without automatic reviews on, or with the Coach
+// off on this phone, it stops here, before the Coach's code is even loaded.
import { MOBILE } from './mobile.js'
const TICK_MS = 60000
@@ -18,15 +22,24 @@ export function mayBeDue(store) {
const cadence = store?.S?.coach?.cadence
return store?.coachLocal?.mode === 'byok' && !!cadence && cadence !== 'off'
}
+/** Whether the paired server could have run one this phone has not heard of. */
+export function mayHaveNews(store) {
+ const cadence = store?.S?.coach?.cadence
+ // A paired phone without a key of its own uses its server's Coach (coachAvailable, lib/coach.js).
+ return store?.coachLocal?.mode !== 'byok' && !!store?.config?.coach?.enabled && !!store?.user && !!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
+/** One look: runs the review when it is due (own key), or, on the way back to the foreground,
+ * asks the paired server whether one is waiting. Resolves to what it found, or null. */
+export async function checkScheduledReview(getStore, foreground = false) {
+ const store = getStore()
+ const own = mayBeDue(store), paired = foreground && mayHaveNews(store)
+ if (running || (!own && !paired)) return null
running = true
try {
- const { scheduledReview } = await import('./coach-api.js')
- return await scheduledReview()
+ const api = await import('./coach-api.js')
+ return await (own ? api.scheduledReview() : api.scheduledNotice())
} catch { return null } finally { running = false }
}
@@ -34,15 +47,15 @@ let started = false
export function initCoachSchedule(getStore) {
if (!MOBILE || started) return
started = true
- const look = () => {
+ const look = (foreground = false) => {
if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return
- checkScheduledReview(getStore)
+ checkScheduledReview(getStore, foreground)
}
- setTimeout(look, 5000) // after start-up, not in the middle of it
- setInterval(look, TICK_MS)
- if (typeof document !== 'undefined') document.addEventListener('visibilitychange', look)
+ setTimeout(() => look(true), 5000) // after start-up, not in the middle of it
+ setInterval(() => look(), TICK_MS)
+ if (typeof document !== 'undefined') document.addEventListener('visibilitychange', () => look(true))
// 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() })
+ App.addListener('appStateChange', ({ isActive }) => { if (isActive) look(true) })
).catch(() => {})
}
diff --git a/website/api.html b/website/api.html
index 20698141c..56a18f44c 100644
--- a/website/api.html
+++ b/website/api.html
@@ -4901,6 +4901,11 @@ main.api-main .lead { color: var(--fg-2); max-width: 58ch; margin: 14px 0 0; fon
<span class="p-type">integer</span>
<span class="p-desc">1, or higher after a refine.</span>
</div>
+ <div class="prow">
+ <span class="p-name">trigger</span>
+ <span class="p-type">&quot;scheduled&quot;</span>
+ <span class="p-desc">Present when an automatic review made it, which nobody was watching for.</span>
+ </div>
<div class="prow">
<span class="p-name">summary</span>
<span class="p-type">string <span class="p-hint">(&le; 1200 chars)</span></span>