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 asks before training data first goes to an AI provider
Duarte Santos3a1d3df7b605
diff --git a/frontend/src/components/CoachConsentSheet.jsx b/frontend/src/components/CoachConsentSheet.jsxnew file mode 100644index 000000000..e1420673c--- /dev/null+++ b/frontend/src/components/CoachConsentSheet.jsx@@ -0,0 +1,92 @@+// The question the Coach asks once per AI provider, right before your training would first go+// there (lib/coach-api.js ensureAiConsent), and the list in the Coach settings that takes it back.+//+// The lines below say what the payload actually carries (api/coach/core/payload.js build): one+// per DATA_CATEGORIES entry, plus what you type, which rides along as the review note or the+// refine text. Short on purpose; the intake's consent screen has the long version.+import { useEffect, useState } from 'react'+import { useUI } from '../store/useUI.js'+import { useStore } from '../store/useStore.js'+import { t } from '../lib/i18n.js'+import { fmtDate } from '../lib/format.js'+import { DATA_CATEGORIES } from '../../../api/coach/core/categories.js'+import { aiConsents, withdrawAi, onAiConsentChange } from '../lib/coach-consent.js'+import { emptyCoach } from '../lib/coach.js'+import Icon from './Icon.jsx'+import { Button, Section, Row } from './ui.jsx'+import '../coach.css'++// Literal t() calls, so check-source-strings sees every line.+const LINES = {+ plan: () => t('Your plan: routines, exercises, sets, reps and schedule'),+ training: () => t('Your workouts: weights, reps, times, effort and session notes'),+ bodyweight: () => t('Your body weight and goal weight'),+ profile: () => t('Your answers to the Coach: goal, days, equipment, limits and injuries'),+ prefs: () => t('Your unit and language')+}+export const sharedLines = () => [...DATA_CATEGORIES.map(k => LINES[k]?.()).filter(Boolean), t('Anything you type to the Coach')]++/** Resolves true for "Allow", false for "Not now" and for a sheet closed any other way. */+export function askAiConsent(target) {+ return new Promise(resolve => {+ let done = false+ const finish = v => { if (!done) { done = true; unsub && unsub(); resolve(v) } }+ const ui = useUI.getState()+ const { id, close } = ui.openSheet(() => <ConsentSheet target={target} onAnswer={v => { finish(v); close() }} />)+ // Swiped away or closed from outside: that is a "not now", and the request must not hang.+ const unsub = useUI.subscribe?.(s => { if (!s.sheets.some(x => x.id === id)) finish(false) })+ })+}++function ConsentSheet({ target, onAnswer }) {+ const server = target.via === 'server'+ return <div className="ai-consent">+ <div className="ob-eyebrow">{t('Your data, your call')}</div>+ <h3>{t('Send your training to {0}?', target.name)}</h3>+ <p className="muted" style={{ lineHeight: 1.5, margin: '6px 0 12px' }}>+ {server+ ? t('To answer, the Coach sends this through your openGym server to {0}, an AI service outside openGym that your server’s admin picked:', target.name)+ : t('To answer, this device sends this straight to {0}, an AI service outside openGym, with your API key:', target.name)}+ </p>+ <div className="ob-consent">+ {sharedLines().map(line => <div key={line} className="ob-consent-row"><Icon name="check" /><div><span>{line}</span></div></div>)}+ </div>+ <div className="ob-fine">+ <div>{t('Your name, email and sign-in stay put. {0} handles the rest under its own privacy terms.', target.name)}</div>+ <div>{t('Change your mind anytime under AI data sharing in the Coach menu.')}</div>+ </div>+ <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>+ <Button variant="primary" onClick={() => onAnswer(true)}>{t('Allow')}</Button>+ <Button onClick={() => onAnswer(false)}>{t('Not now')}</Button>+ </div>+ </div>+}++/** The allowed providers on this device, each with a way to take it back. */+export function AiConsentSection() {+ const [list, setList] = useState(null)+ const toast = useUI(s => s.toast)+ useEffect(() => {+ const load = () => aiConsents().then(setList).catch(() => setList([]))+ load()+ return onAiConsentChange(load)+ }, [])+ const withdraw = async c => {+ await withdrawAi(c.key)+ // Automatic reviews run on the server with nobody there to ask, so a "no" to the server's+ // provider switches them off too; turning them back on asks again (CoachChat CadenceSheet).+ const { S, update } = useStore.getState()+ const cadence = S?.coach?.cadence+ if (c.via === 'server' && cadence && cadence !== 'off') update(s => { (s.coach = s.coach || emptyCoach()).cadence = 'off' })+ toast(t('Withdrawn. The Coach will ask before it sends anything again.'))+ }+ if (!list) return null+ return <Section title={t('AI data sharing')}+ footer={t('Who the Coach may send your training to from this device. Withdraw it and the Coach asks again next time. A model on your own network never needs asking.')}>+ {!list.length && <Row icon="lock" iconTint="var(--green)" title={t('Nothing allowed yet')} subtitle={t('The Coach asks before anything leaves.')} />}+ {list.map(c => <Row key={c.key} icon="shield" iconTint="var(--acc)" title={c.name}+ subtitle={(c.via === 'server' ? t('Through your server') : t('With your API key')) + ' · ' + t('Allowed {0}', fmtDate(String(c.at).slice(0, 10), false, true))}>+ <Button size="sm" onClick={() => withdraw(c)}>{t('Withdraw')}</Button>+ </Row>)}+ </Section>+}diff --git a/frontend/src/lib/coach-api.js b/frontend/src/lib/coach-api.jsindex bba6ee15b..7680ea282 100644--- a/frontend/src/lib/coach-api.js+++ b/frontend/src/lib/coach-api.js@@ -59,15 +59,34 @@ const track = r => {export const awaitedJob = () => awaitedexport const settleAwaited = id => { if (!id || awaited === id) awaited = null }+/* The one question before anything leaves for an AI provider (Apple 5.1.2(i), and plain manners).+ Asked here, at the single door every job goes through, so no screen can start one around it:+ the provider and host come from the same disclosure the intake shows, and a yes is kept per+ provider and host on this device (lib/coach-consent.js). The demo answers locally and a model+ on your own network is not a third party, so neither asks. "Not now" rejects with code+ 'declined' and `quiet`, which the screens let pass without a toast: you said no, you know. */+export const coachVia = () => (DEMO ? 'demo' : LOCAL() ? 'device' : 'server')+export const isDeclined = e => e?.code === 'declined'+export async function ensureAiConsent() {+ if (DEMO) return true+ const { consentTarget, hasAiConsent, allowAi } = await import('./coach-consent.js')+ const target = consentTarget(await disclosure(), coachVia())+ if (!target || target.local || await hasAiConsent(target)) return true+ const { askAiConsent } = await import('../components/CoachConsentSheet.jsx')+ if (await askAiConsent(target)) { await allowAi(target); return true }+ throw Object.assign(new Error(t('Okay, nothing was sent.')), { code: 'declined', quiet: true, data: { code: 'declined' } })+}+const asked = fn => async (...a) => { await ensureAiConsent(); return fn(...a) }+export const coachStatus = async () => DEMO ? (await demo()).demoStatus() : LOCAL() ? (await local()).localStatus() : api('/api/coach/status')const _requestReview = async note => DEMO ? (await demo()).demoReview(S()) : LOCAL() ? (await local()).localReview(S(), note) : api('/api/coach/review', { method: 'POST', body: JSON.stringify({ note: note || '', lang: getLang() }) })-export const requestReview = (...a) => _requestReview(...a).then(track)+export const requestReview = (...a) => asked(_requestReview)(...a).then(track)const _requestPlan = async intake => DEMO ? (await demo()).demoPlan(S(), intake) : LOCAL() ? (await local()).localPlan(S(), intake) : api('/api/coach/plan', { method: 'POST', body: JSON.stringify({ intake, lang: getLang() }) })-export const requestPlan = (...a) => _requestPlan(...a).then(track)+export const requestPlan = (...a) => asked(_requestPlan)(...a).then(track)const _refinePlan = async text => DEMO ? (await demo()).demoRefine(S()) : LOCAL() ? (await local()).localRefine(S(), text) : api('/api/coach/plan', { method: 'POST', body: JSON.stringify({ refine: text, lang: getLang() }) })-export const refinePlan = (...a) => _refinePlan(...a).then(track)+export const refinePlan = (...a) => asked(_refinePlan)(...a).then(track)const _requestDebrief = async workoutId => DEMO ? (await demo()).demoDebrief(S(), workoutId) : LOCAL() ? (await local()).localDebrief(S(), workoutId) : api('/api/coach/debrief', { method: 'POST', body: JSON.stringify({ workoutId: workoutId || null, lang: getLang() }) })-export const requestDebrief = (...a) => _requestDebrief(...a).then(track)+export const requestDebrief = (...a) => asked(_requestDebrief)(...a).then(track)// 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-consent.js b/frontend/src/lib/coach-consent.jsnew file mode 100644index 000000000..8c0c132fa--- /dev/null+++ b/frontend/src/lib/coach-consent.js@@ -0,0 +1,106 @@+// Who the Coach may send your training to, as this device remembers it.+//+// The intake's consent (S.coach.consent) says yes to the Coach as an idea. This says yes to one+// particular AI service: the first request that would send training data to a provider asks,+// once, naming the provider and what goes there (components/CoachConsentSheet.jsx), and the+// answer is kept per provider and host. Point the Coach somewhere else and it asks again.+//+// A device fact, not training data, so not in S: it must not sync a yes given on one phone to+// another device that never showed the question, nor ride into an export. On the mobile build+// it is also written to a file, because the WebView may evict localStorage, and an app that+// forgets your answer asks again, which is annoying but never wrong.+//+// A model on your own machine or network (Ollama on the LAN, a box on your tailnet) is not a+// third party, so it is not asked about: see isLocalHost.+import { MOBILE, readJsonFile, writeJsonFile } from './mobile.js'++const KEY = 'gym_coach_ai_consent'+const FILE = 'opengym-coach-consent.json'++// The name a person knows the company by. A compatible endpoint is whatever it was pointed at,+// so it is named by its host; the runtime providers on a server talk to the same companies.+export const PROVIDER_NAMES = { anthropic: 'Anthropic', openai: 'OpenAI', gemini: 'Google Gemini', claude: 'Anthropic', codex: 'OpenAI' }+// Server providers that send nothing anywhere: the test fixture answers from a file.+const NOWHERE = new Set(['fixture', 'demo'])++/**+ * Whether a host is the user's own machine or network rather than somebody's service: loopback,+ * the private and link-local ranges, CGNAT (where Tailscale lives), and the names only a local+ * resolver answers (a bare `ollama`, `*.local`, `*.lan`, `*.home.arpa`, `*.internal`, `*.ts.net`).+ * A public name that happens to point at a home server cannot be told apart, and is asked about.+ */+export function isLocalHost(host) {+ let h = String(host || '').trim().toLowerCase()+ if (!h) return false+ if (h.startsWith('[')) h = h.slice(1, h.indexOf(']')) // [::1]:11434+ else if ((h.match(/:/g) || []).length === 1) h = h.split(':')[0] // name:port, v4:port+ if (h === 'localhost' || h.endsWith('.localhost') || h === '0.0.0.0' || h === '::1') return true+ const v4 = h.match(/^(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/)+ if (v4) {+ const [a, b] = [Number(v4[1]), Number(v4[2])]+ return a === 127 || a === 10 || (a === 192 && b === 168) || (a === 172 && b >= 16 && b <= 31) ||+ (a === 169 && b === 254) || (a === 100 && b >= 64 && b <= 127)+ }+ if (h.includes(':')) return /^(fc|fd|fe8|fe9|fea|feb)/.test(h) // unique-local and link-local v6+ if (!h.includes('.')) return true // a single-label name: docker, the LAN+ return /\.(local|lan|home\.arpa|internal|ts\.net)$/.test(h)+}++/**+ * What a disclosure (coach-api.js `disclosure()`) amounts to, for asking and for remembering.+ * `via` is 'server' (the paired or signed-in server runs it with its admin's provider) or+ * 'device' (this phone, with its own key). Null when there is nothing to ask about.+ */+export function consentTarget(info, via) {+ if (!info || !info.provider || NOWHERE.has(info.provider)) return null+ const provider = String(info.provider)+ const host = info.host ? String(info.host).toLowerCase() : null+ const name = (provider !== 'compatible' && PROVIDER_NAMES[provider]) || host || info.providerLabel || provider+ return { key: `${via}|${provider}|${host || ''}`, via, provider, host, name, local: isLocalHost(host) }+}++/* ---------- the remembered answers ---------- */++let cache = null+const listeners = new Set()+const readLocal = () => { try { return JSON.parse(localStorage.getItem(KEY)) } catch { return null } }++async function load() {+ if (cache) return cache+ const saved = (MOBILE && await readJsonFile(FILE)) || readLocal()+ cache = saved && typeof saved === 'object' && saved.list && typeof saved.list === 'object' ? saved : { list: {} }+ return cache+}+async function save(next) {+ cache = next+ try { localStorage.setItem(KEY, JSON.stringify(next)) } catch { /* the file, or memory, still has it */ }+ if (MOBILE) await writeJsonFile(FILE, next)+ listeners.forEach(fn => { try { fn() } catch { /* a listener's problem */ } })+}++export async function hasAiConsent(target) {+ if (!target) return false+ return !!(await load()).list[target.key]+}+export async function allowAi(target) {+ const c = await load()+ const { key, via, provider, host, name } = target+ await save({ list: { ...c.list, [key]: { via, provider, host, name, at: new Date().toISOString() } } })+}+export async function withdrawAi(key) {+ const c = await load()+ const list = { ...c.list }+ delete list[key]+ await save({ list })+}+/** Everything allowed on this device, newest first: what the settings list shows. */+export async function aiConsents() {+ return Object.entries((await load()).list).map(([key, v]) => ({ key, ...v })).sort((a, b) => String(b.at).localeCompare(String(a.at)))+}+export function onAiConsentChange(fn) {+ listeners.add(fn)+ return () => listeners.delete(fn)+}++// Test seam.+export function _resetAiConsent() { cache = null; listeners.clear() }diff --git a/frontend/src/views/CoachChat.jsx b/frontend/src/views/CoachChat.jsxindex eacc836ba..bfbab12a9 100644--- a/frontend/src/views/CoachChat.jsx+++ b/frontend/src/views/CoachChat.jsx@@ -29,7 +29,8 @@ import {changeTitle, changeValues, exName, canRevert, revertLast} from '../lib/coach.js'import { insightsFor, sessionInsights } from '../lib/coach-insights.js'-import { useCoachStatus, requestReview, requestDebrief, requestPlan, refinePlan, resolvePending, cohortStats, setCohortShare, jobErrorText, awaitedJob, settleAwaited, JOB_ERRORS } from '../lib/coach-api.js'+import { useCoachStatus, requestReview, requestDebrief, requestPlan, refinePlan, resolvePending, cohortStats, setCohortShare, jobErrorText, awaitedJob, settleAwaited, JOB_ERRORS, ensureAiConsent, isDeclined } from '../lib/coach-api.js'+import { AiConsentSection } from '../components/CoachConsentSheet.jsx'import { confirmSheet } from '../sheets.jsx'import Icon from '../components/Icon.jsx'import { glyphOf } from '../lib/glyphs.js'@@ -116,7 +117,8 @@ export default function CoachChat() {} catch (e) {// A server that refuses the job says so in English, with its class beside it: the class// picks the translated line. One with no line here ('shared') keeps the server's words.- toast(JOB_ERRORS[e.data?.code] || e.message || t('Could not ask the Coach'))+ // "Not now" on the data-sharing question is an answer, not a failure: the text stays put.+ if (!isDeclined(e)) toast(JOB_ERRORS[e.data?.code] || e.message || t('Could not ask the Coach'))}setBusy(false)}@@ -127,7 +129,7 @@ export default function CoachChat() {await fn()update(s => appendChat(s, { role: 'user', kind: 'text', text: line }))refresh()- } catch (e) { toast(JOB_ERRORS[e.data?.code] || e.message || t('Could not ask the Coach')) }+ } catch (e) { if (!isDeclined(e)) toast(JOB_ERRORS[e.data?.code] || e.message || t('Could not ask the Coach')) }setBusy(false)}const askReview = () => ask(() => requestReview(''), t('Have a look at my training and tell me what you would change.'))@@ -164,6 +166,7 @@ export default function CoachChat() {{idle && <Row icon="clipboard" iconTint="var(--indigo)" title={t('Start a new plan')} subtitle={t('A fresh plan from your answers; your workouts stay')} accessory="chevron" onClick={() => { close(); askNewPlan() }} />}<Row icon="pencil" iconTint="var(--indigo)" title={t('Edit my answers')} subtitle={t('Goal, days, equipment, limits')} accessory="chevron" onClick={() => closeThenNav(close, '/coach/intake?edit=1')} /><Row icon="clock" iconTint="var(--purple)" title={t('Automatic reviews')} subtitle={cadenceLabel(coach)} accessory="chevron" onClick={() => { close(); cadenceSheet(openSheet, update) }} />+ {!DEMO && <Row icon="shield" iconTint="var(--green)" title={t('AI data sharing')} subtitle={t('Who may see your training')} accessory="chevron" onClick={() => { close(); openSheet(() => <div className="chat-menu"><AiConsentSection /></div>) }} />}{canRevert(S) && <Row icon="reset" iconTint="var(--blue)" title={t('Undo the last Coach changes')} accessory="chevron" onClick={() => { close(); doRevert() }} />}</div><div style={{ height: 10 }} />@@ -749,10 +752,17 @@ 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'- const setMode = m => update(s => {- const c = (s.coach = s.coach || emptyCoach())- c.cadence = m === 'off' ? 'off' : m === 'weekly' ? { weekly: { day: 0, time: '18:00' } } : { everyWorkouts: 4 }- })+ // 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 => {+ if (m !== 'off') {+ try { await ensureAiConsent() } catch (e) { if (!isDeclined(e)) useUI.getState().toast(e.message || t('Could not ask the Coach')); return }+ }+ update(s => {+ const c = (s.coach = s.coach || emptyCoach())+ c.cadence = m === 'off' ? 'off' : m === 'weekly' ? { weekly: { day: 0, time: '18:00' } } : { everyWorkouts: 4 }+ })+ }const patch = fn => update(s => { const c = (s.coach = s.coach || emptyCoach()); fn(c) })return <><h3>{t('Automatic reviews')}</h3>diff --git a/frontend/src/views/CoachChat.refusal.test.jsx b/frontend/src/views/CoachChat.refusal.test.jsxindex 7821578cd..8edb2112c 100644--- a/frontend/src/views/CoachChat.refusal.test.jsx+++ b/frontend/src/views/CoachChat.refusal.test.jsx@@ -48,6 +48,8 @@ vi.mock('../lib/coach-api.js', () => ({setCohortShare: vi.fn(() => Promise.resolve({ ok: true })),jobErrorText: () => 'err',JOB_ERRORS: { busy: 'the app’s busy line' },+ ensureAiConsent: vi.fn(() => Promise.resolve(true)),+ isDeclined: e => e?.code === 'declined',}))vi.mock('../sheets.jsx', () => ({ startFlow: vi.fn(), confirmSheet: vi.fn() }))vi.mock('../lib/api.js', () => ({diff --git a/frontend/src/views/CoachChat.test.jsx b/frontend/src/views/CoachChat.test.jsxindex 12560025b..36d06c2ab 100644--- a/frontend/src/views/CoachChat.test.jsx+++ b/frontend/src/views/CoachChat.test.jsx@@ -43,6 +43,8 @@ vi.mock('../lib/coach-api.js', () => ({cohortStats: vi.fn(() => Promise.resolve({ ok: false, enabled: true, sharing: false })),setCohortShare: vi.fn(() => Promise.resolve({ ok: true, sharing: true })),JOB_ERRORS: { internal: 'x' },+ ensureAiConsent: vi.fn(() => Promise.resolve(true)),+ isDeclined: e => e?.code === 'declined',awaitedJob: () => null,settleAwaited: vi.fn(),}))diff --git a/frontend/src/views/CoachIntake.jsx b/frontend/src/views/CoachIntake.jsxindex c07c2aeaf..9c59a12e5 100644--- a/frontend/src/views/CoachIntake.jsx+++ b/frontend/src/views/CoachIntake.jsx@@ -16,7 +16,7 @@ import { t } from '../lib/i18n.js'import { DAYN } from '../lib/format.js'import { EXDB } from '../lib/exercises.js'import { emptyCoach, coachAvailable, hasConsent, CONSENT_VERSION, CATEGORY_TEXT, appendChat } from '../lib/coach.js'-import { requestPlan, disclosure, JOB_ERRORS } from '../lib/coach-api.js'+import { requestPlan, disclosure, JOB_ERRORS, isDeclined } from '../lib/coach-api.js'import { DEMO } from '../lib/demo.js'import { MOBILE } from '../lib/mobile.js'import { activeProfile } from '../lib/equipment.js'@@ -115,7 +115,9 @@ export default function CoachIntake() {nav('/coach', { replace: true })} catch (e) {// The server's refusal is English with its class beside it; the class picks the line.- toast(JOB_ERRORS[e.data?.code] || e.message || t('Could not ask the Coach')); setBusy(false)+ // "Not now" on the data-sharing question sends nothing and says nothing; the answers are saved.+ if (!isDeclined(e)) toast(JOB_ERRORS[e.data?.code] || e.message || t('Could not ask the Coach'))+ setBusy(false)}}diff --git a/frontend/src/views/CoachIntake.test.jsx b/frontend/src/views/CoachIntake.test.jsxindex b13dba67c..05cf99b97 100644--- a/frontend/src/views/CoachIntake.test.jsx+++ b/frontend/src/views/CoachIntake.test.jsx@@ -50,6 +50,8 @@ vi.mock('../lib/coach-api.js', () => ({requestPlan: vi.fn(() => Promise.resolve({})),disclosure: vi.fn(() => Promise.resolve(null)),JOB_ERRORS: { busy: 'the app’s busy line' },+ ensureAiConsent: vi.fn(() => Promise.resolve(true)),+ isDeclined: e => e?.code === 'declined',}))vi.mock('../coach.css', () => ({}))diff --git a/frontend/src/views/CoachSetup.jsx b/frontend/src/views/CoachSetup.jsxindex e0ffcdfa2..43fd7ac35 100644--- a/frontend/src/views/CoachSetup.jsx+++ b/frontend/src/views/CoachSetup.jsx@@ -20,6 +20,7 @@ import { getApiKey, setApiKey, clearApiKey } from '../lib/coach-secrets.js'import { HTTP_PROVIDERS, HTTP_PROVIDER_IDS, baseUrlFor, validateBaseUrl } from '../../../api/coach/core/providers.js'import { DATA_CATEGORIES } from '../../../api/coach/core/categories.js'import { ConnectSheet } from './MobileOnboarding.jsx'+import { AiConsentSection } from '../components/CoachConsentSheet.jsx'import Icon from '../components/Icon.jsx'import { Section, Row, Button, TextField } from '../components/ui.jsx'@@ -210,6 +211,8 @@ export default function CoachSetup() {</div></>}+ {coachLocal?.mode && coachLocal.mode !== 'off' && <AiConsentSection />}+{coachLocal?.mode && coachLocal.mode !== 'off' && <Section title={t('Controls')}><Row icon="signOut" iconTint="var(--red)" title={t('Turn the Coach off on this phone')} danger onClick={turnOff} /></Section>}