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.

Tests for the AI data sharing question

Duarte Santos0b2731938260
diff --git a/frontend/src/components/CoachConsentSheet.test.jsx b/frontend/src/components/CoachConsentSheet.test.jsx
new file mode 100644
index 000000000..da96e35bc
--- /dev/null
+++ b/frontend/src/components/CoachConsentSheet.test.jsx
@@ -0,0 +1,113 @@
+// @vitest-environment happy-dom
+// The sheet itself: it names the provider, says what goes there and which way, and every way of
+// leaving it settles the question. A sheet swiped away must count as "not now"; a promise that
+// never settles is a Coach button that spins forever.
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+globalThis.IS_REACT_ACT_ENVIRONMENT = true
+
+const mocks = vi.hoisted(() => ({ toast: vi.fn(), S: null, update: null }))
+vi.mock('../store/useUI.js', async () => {
+ const { create } = await import('zustand')
+ let n = 0
+ const useUI = create((set, get) => ({
+ sheets: [],
+ toast: (...a) => mocks.toast(...a),
+ openSheet(render) {
+ const id = 's' + (++n)
+ set(s => ({ sheets: [...s.sheets, { id, render }] }))
+ return { id, close: () => get().closeSheet(id) }
+ },
+ closeSheet(id) { set(s => ({ sheets: s.sheets.filter(x => x.id !== id) })) },
+ }))
+ return { useUI }
+})
+vi.mock('../store/useStore.js', () => {
+ const snap = () => ({ S: mocks.S, update: mocks.update })
+ const useStore = selector => (selector ? selector(snap()) : snap())
+ useStore.getState = snap
+ return { useStore }
+})
+vi.mock('../lib/mobile.js', () => ({ MOBILE: false, readJsonFile: async () => null, writeJsonFile: async () => {} }))
+vi.mock('../coach.css', () => ({}))
+
+const { useUI } = await import('../store/useUI.js')
+const { askAiConsent, AiConsentSection } = await import('./CoachConsentSheet.jsx')
+const { consentTarget, allowAi, hasAiConsent, _resetAiConsent } = await import('../lib/coach-consent.js')
+
+function Sheets() {
+ const sheets = useUI(s => s.sheets)
+ return <>{sheets.map(s => <div key={s.id} className="sheet">{s.render(() => useUI.getState().closeSheet(s.id))}</div>)}</>
+}
+
+let host, root
+beforeEach(() => {
+ localStorage.clear(); _resetAiConsent(); mocks.toast.mockReset()
+ mocks.S = { coach: { cadence: { everyWorkouts: 4 } } }
+ mocks.update = vi.fn(fn => fn(mocks.S))
+ useUI.setState({ sheets: [] })
+ host = document.createElement('div'); document.body.appendChild(host); root = createRoot(host)
+ act(() => root.render(<Sheets />))
+})
+afterEach(() => { act(() => root.unmount()); host.remove() })
+
+const button = text => [...host.querySelectorAll('button')].find(b => b.textContent.trim() === text)
+const click = async el => { await act(async () => { el.dispatchEvent(new MouseEvent('click', { bubbles: true })) }) }
+const server = consentTarget({ provider: 'gemini', host: 'generativelanguage.googleapis.com' }, 'server')
+const device = consentTarget({ provider: 'compatible', host: 'openrouter.ai' }, 'device')
+
+describe('asking', () => {
+ it('names the provider, the data and the route through the user\'s server', async () => {
+ let p
+ await act(async () => { p = askAiConsent(server) })
+ const text = host.textContent
+ expect(text).toContain('Send your training to Google Gemini?')
+ expect(text).toContain('through your openGym server to Google Gemini')
+ expect(text).toContain('your server’s admin picked')
+ for (const line of ['Your plan', 'Your workouts', 'Your body weight', 'Your answers to the Coach', 'Your unit and language', 'Anything you type to the Coach']) expect(text).toContain(line)
+ expect(text).not.toMatch(/—/)
+ await click(button('Allow'))
+ await expect(p).resolves.toBe(true)
+ expect(useUI.getState().sheets).toHaveLength(0)
+ })
+
+ it('says it goes straight from this device for the phone\'s own key, and "Not now" answers false', async () => {
+ let p
+ await act(async () => { p = askAiConsent(device) })
+ expect(host.textContent).toContain('this device sends this straight to openrouter.ai')
+ await click(button('Not now'))
+ await expect(p).resolves.toBe(false)
+ })
+
+ it('a sheet closed any other way (swiped down, the backdrop) is a "not now", not a hang', async () => {
+ let p
+ await act(async () => { p = askAiConsent(server) })
+ await act(async () => { useUI.getState().closeSheet(useUI.getState().sheets[0].id) })
+ await expect(p).resolves.toBe(false)
+ })
+})
+
+describe('the AI data sharing list', () => {
+ const mountList = async () => { await act(async () => { root.render(<><Sheets /><AiConsentSection /></>) }) }
+
+ it('says nothing is allowed yet, then shows what was', async () => {
+ await mountList()
+ expect(host.textContent).toContain('Nothing allowed yet')
+ await act(async () => { await allowAi(device) })
+ expect(host.textContent).toContain('openrouter.ai')
+ expect(host.textContent).toContain('With your API key')
+ })
+
+ it('withdrawing forgets the answer; for the server it also stops the automatic reviews', async () => {
+ await allowAi(server)
+ await mountList()
+ expect(host.textContent).toContain('Through your server')
+ await click(button('Withdraw'))
+ expect(await hasAiConsent(server)).toBe(false)
+ expect(mocks.S.coach.cadence).toBe('off')
+ expect(mocks.toast).toHaveBeenCalledWith('Withdrawn. The Coach will ask before it sends anything again.')
+ expect(host.textContent).toContain('Nothing allowed yet')
+ })
+})
diff --git a/frontend/src/lib/coach-api.consent.test.js b/frontend/src/lib/coach-api.consent.test.js
new file mode 100644
index 000000000..8c231b84e
--- /dev/null
+++ b/frontend/src/lib/coach-api.consent.test.js
@@ -0,0 +1,144 @@
+// @vitest-environment happy-dom
+// The door every Coach job goes through asks first (Apple 5.1.2(i)): once per provider and host,
+// before the first request that would send training data there. Pinned here with the real
+// coach-api.js and coach-consent.js; the sheet itself is a stand-in that answers as told, and
+// no request ever leaves (api.js, the phone's pipeline and the demo are all fakes).
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => ({
+ DEMO: false, MOBILE: false, coachLocal: null,
+ disclosure: { provider: 'openai', providerLabel: 'OpenAI API', host: 'api.openai.com', categories: [], version: 1 },
+ answer: true,
+}))
+vi.mock('./demo.js', () => ({ get DEMO() { return mocks.DEMO }, DEMO_SEEDED: 'gym_demo_seeded_v1', REPO: '' }))
+vi.mock('./mobile.js', () => ({ get MOBILE() { return mocks.MOBILE }, readJsonFile: async () => null, writeJsonFile: async () => {} }))
+vi.mock('./api.js', () => ({
+ api: vi.fn(async path => (path === '/api/coach/disclosure' ? mocks.disclosure : { job: { id: 'j1' } })),
+}))
+vi.mock('../store/useStore.js', () => ({ useStore: { getState: () => ({ S: { coach: {} }, coachLocal: mocks.coachLocal }) } }))
+vi.mock('../store/useUI.js', () => ({ useUI: { getState: () => ({ toast: vi.fn() }) } }))
+vi.mock('../components/CoachConsentSheet.jsx', () => ({ askAiConsent: vi.fn(async () => mocks.answer) }))
+vi.mock('./coach-local.js', () => ({
+ setNotifier: vi.fn(),
+ localDisclosure: vi.fn(async () => mocks.disclosure),
+ localReview: vi.fn(async () => ({ job: { id: 'local-1' } })),
+}))
+vi.mock('./coach-demo.js', () => ({
+ demoDisclosure: vi.fn(() => ({ provider: 'demo' })),
+ demoReview: vi.fn(async () => ({ job: { id: 'demo-1' } })),
+}))
+
+const { api } = await import('./api.js')
+const { askAiConsent } = await import('../components/CoachConsentSheet.jsx')
+const local = await import('./coach-local.js')
+const demo = await import('./coach-demo.js')
+const { requestReview, requestPlan, refinePlan, requestDebrief, isDeclined } = await import('./coach-api.js')
+const { aiConsents, withdrawAi, _resetAiConsent } = await import('./coach-consent.js')
+
+const jobCalls = () => vi.mocked(api).mock.calls.filter(([p]) => p !== '/api/coach/disclosure')
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ localStorage.clear()
+ _resetAiConsent()
+ Object.assign(mocks, {
+ DEMO: false, MOBILE: false, coachLocal: null, answer: true,
+ disclosure: { provider: 'openai', providerLabel: 'OpenAI API', host: 'api.openai.com', categories: [], version: 1 },
+ })
+})
+
+describe('the server Coach', () => {
+ it('asks once, right before the first request, and remembers the yes', async () => {
+ await requestReview('')
+ expect(askAiConsent).toHaveBeenCalledTimes(1)
+ expect(vi.mocked(askAiConsent).mock.calls[0][0]).toMatchObject({ via: 'server', provider: 'openai', name: 'OpenAI', host: 'api.openai.com' })
+ expect(jobCalls()).toHaveLength(1)
+
+ await requestPlan({ goal: 'muscle' })
+ await refinePlan('fewer squats')
+ await requestDebrief('w1')
+ expect(askAiConsent).toHaveBeenCalledTimes(1)
+ expect(jobCalls()).toHaveLength(4)
+ expect((await aiConsents()).map(c => c.name)).toEqual(['OpenAI'])
+ })
+
+ it('asks again when the admin points it at another provider or another endpoint', async () => {
+ await requestReview('')
+ mocks.disclosure = { provider: 'anthropic', providerLabel: 'Anthropic API', host: 'api.anthropic.com' }
+ await requestReview('')
+ expect(askAiConsent).toHaveBeenCalledTimes(2)
+ expect(vi.mocked(askAiConsent).mock.calls[1][0].name).toBe('Anthropic')
+
+ mocks.disclosure = { provider: 'compatible', providerLabel: 'OpenAI-compatible endpoint', host: 'openrouter.ai' }
+ await requestReview('')
+ mocks.disclosure = { provider: 'compatible', providerLabel: 'OpenAI-compatible endpoint', host: 'llm.example.org' }
+ await requestReview('')
+ expect(askAiConsent).toHaveBeenCalledTimes(4)
+ expect(vi.mocked(askAiConsent).mock.calls[3][0].name).toBe('llm.example.org')
+ })
+
+ it('"Not now" sends nothing, and rejects quietly with a class the screens let pass', async () => {
+ mocks.answer = false
+ const e = await requestReview('').catch(x => x)
+ expect(isDeclined(e)).toBe(true)
+ expect(e.quiet).toBe(true)
+ expect(jobCalls()).toHaveLength(0)
+ expect(await aiConsents()).toEqual([])
+ // …and the next request asks again rather than remembering the no.
+ mocks.answer = true
+ await requestReview('')
+ expect(askAiConsent).toHaveBeenCalledTimes(2)
+ expect(jobCalls()).toHaveLength(1)
+ })
+
+ it('withdrawn, the next request asks again', async () => {
+ await requestReview('')
+ const [c] = await aiConsents()
+ await withdrawAi(c.key)
+ await requestReview('')
+ expect(askAiConsent).toHaveBeenCalledTimes(2)
+ })
+
+ it('does not ask about a model on the server\'s own network', async () => {
+ mocks.disclosure = { provider: 'compatible', providerLabel: 'OpenAI-compatible endpoint', host: '192.168.1.20:11434' }
+ await requestReview('')
+ expect(askAiConsent).not.toHaveBeenCalled()
+ expect(jobCalls()).toHaveLength(1)
+ })
+
+ it('sends nothing when the disclosure itself cannot be read', async () => {
+ vi.mocked(api).mockRejectedValueOnce(Object.assign(new Error('offline'), { status: 0 }))
+ await expect(requestReview('')).rejects.toThrow('offline')
+ expect(jobCalls()).toHaveLength(0)
+ })
+})
+
+describe('the phone with its own key', () => {
+ beforeEach(() => { mocks.MOBILE = true; mocks.coachLocal = { mode: 'byok', provider: 'openai' } })
+
+ it('asks with the device wording, and a yes for the server is not a yes for the phone', async () => {
+ mocks.coachLocal = null
+ await requestReview('') // the server's OpenAI
+ mocks.coachLocal = { mode: 'byok', provider: 'openai' }
+ await requestReview('') // the phone's own OpenAI key
+ expect(askAiConsent).toHaveBeenCalledTimes(2)
+ expect(vi.mocked(askAiConsent).mock.calls[1][0]).toMatchObject({ via: 'device', name: 'OpenAI' })
+ expect(local.localReview).toHaveBeenCalledTimes(1)
+ })
+
+ it('"Not now" never reaches the pipeline', async () => {
+ mocks.answer = false
+ await expect(requestReview('')).rejects.toMatchObject({ code: 'declined' })
+ expect(local.localReview).not.toHaveBeenCalled()
+ })
+})
+
+describe('the demo', () => {
+ it('never asks: its Coach is canned and nothing leaves the device', async () => {
+ mocks.DEMO = true
+ await requestReview('')
+ expect(askAiConsent).not.toHaveBeenCalled()
+ expect(demo.demoReview).toHaveBeenCalledTimes(1)
+ expect(api).not.toHaveBeenCalled()
+ })
+})
diff --git a/frontend/src/lib/coach-consent.test.js b/frontend/src/lib/coach-consent.test.js
new file mode 100644
index 000000000..f70fe7399
--- /dev/null
+++ b/frontend/src/lib/coach-consent.test.js
@@ -0,0 +1,98 @@
+// @vitest-environment happy-dom
+// The per-provider "may the Coach send your training there?" answer: what counts as a third
+// party, how a disclosure becomes something to ask about, and that the answer is kept per
+// provider and host, on the phone in a file as well, and can be taken back.
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+
+const mocks = vi.hoisted(() => ({ MOBILE: false, files: {} }))
+vi.mock('./mobile.js', () => ({
+ get MOBILE() { return mocks.MOBILE },
+ readJsonFile: async name => (name in mocks.files ? JSON.parse(mocks.files[name]) : null),
+ writeJsonFile: async (name, data) => { mocks.files[name] = JSON.stringify(data) },
+}))
+
+const { isLocalHost, consentTarget, hasAiConsent, allowAi, withdrawAi, aiConsents, onAiConsentChange, _resetAiConsent } = await import('./coach-consent.js')
+
+beforeEach(() => {
+ mocks.MOBILE = false
+ mocks.files = {}
+ localStorage.clear()
+ _resetAiConsent()
+})
+
+describe('what is not a third party', () => {
+ it.each([
+ 'localhost:11434', '127.0.0.1', '[::1]:8080', '10.0.0.5', '192.168.1.20:11434', '172.20.0.3',
+ '100.101.102.103', 'ollama', 'ollama:11434', 'gpu-box.local', 'nas.lan', 'llm.home.arpa', 'box.tail1234.ts.net', 'fd12::1',
+ ])('%s is the user\'s own machine or network', host => expect(isLocalHost(host)).toBe(true))
+
+ it.each([
+ 'api.openai.com', 'api.anthropic.com', 'generativelanguage.googleapis.com', 'openrouter.ai',
+ '8.8.8.8', '172.32.0.1', '192.169.1.1', 'ollama.example.com', '', null,
+ ])('%s is somebody else\'s', host => expect(isLocalHost(host)).toBe(false))
+})
+
+describe('a disclosure, as something to ask about', () => {
+ it('names the company a person knows, not the API product', () => {
+ expect(consentTarget({ provider: 'openai', host: 'api.openai.com' }, 'device').name).toBe('OpenAI')
+ expect(consentTarget({ provider: 'anthropic', host: 'api.anthropic.com' }, 'device').name).toBe('Anthropic')
+ expect(consentTarget({ provider: 'gemini', host: 'generativelanguage.googleapis.com' }, 'server').name).toBe('Google Gemini')
+ // The server's runtime providers have no base URL, and go to the same companies.
+ expect(consentTarget({ provider: 'claude', host: null, providerLabel: 'Claude (Anthropic)' }, 'server').name).toBe('Anthropic')
+ })
+
+ it('names a compatible endpoint by its host, and keys on provider and host', () => {
+ const a = consentTarget({ provider: 'compatible', host: 'OpenRouter.ai', providerLabel: 'OpenAI-compatible endpoint' }, 'device')
+ expect(a).toMatchObject({ name: 'openrouter.ai', local: false, via: 'device' })
+ const b = consentTarget({ provider: 'compatible', host: 'llm.example.org' }, 'device')
+ expect(a.key).not.toBe(b.key)
+ expect(consentTarget({ provider: 'compatible', host: 'llm.example.org' }, 'server').key).not.toBe(b.key)
+ })
+
+ it('marks a model on the LAN as local, and has nothing to ask for the demo or the test fixture', () => {
+ expect(consentTarget({ provider: 'compatible', host: '192.168.1.20:11434' }, 'server').local).toBe(true)
+ expect(consentTarget({ provider: 'demo' }, 'server')).toBeNull()
+ expect(consentTarget({ provider: 'fixture' }, 'server')).toBeNull()
+ expect(consentTarget(null, 'server')).toBeNull()
+ })
+})
+
+describe('the remembered answer', () => {
+ const openai = consentTarget({ provider: 'openai', host: 'api.openai.com' }, 'device')
+ const gemini = consentTarget({ provider: 'gemini', host: 'generativelanguage.googleapis.com' }, 'device')
+
+ it('is kept per provider: a yes to one is not a yes to another', async () => {
+ expect(await hasAiConsent(openai)).toBe(false)
+ await allowAi(openai)
+ expect(await hasAiConsent(openai)).toBe(true)
+ expect(await hasAiConsent(gemini)).toBe(false)
+ const [row] = await aiConsents()
+ expect(row).toMatchObject({ key: openai.key, name: 'OpenAI', via: 'device', provider: 'openai', host: 'api.openai.com' })
+ expect(Date.parse(row.at)).not.toBeNaN()
+ })
+
+ it('survives a restart: from localStorage on the web', async () => {
+ await allowAi(openai)
+ _resetAiConsent()
+ expect(await hasAiConsent(openai)).toBe(true)
+ })
+
+ it('survives a restart on the phone even when the WebView lost its storage', async () => {
+ mocks.MOBILE = true
+ await allowAi(openai)
+ localStorage.clear()
+ _resetAiConsent()
+ expect(await hasAiConsent(openai)).toBe(true)
+ })
+
+ it('can be withdrawn, and then it is asked for again', async () => {
+ const seen = vi.fn()
+ onAiConsentChange(seen)
+ await allowAi(openai); await allowAi(gemini)
+ await withdrawAi(openai.key)
+ expect(await hasAiConsent(openai)).toBe(false)
+ expect(await hasAiConsent(gemini)).toBe(true)
+ expect((await aiConsents()).map(c => c.key)).toEqual([gemini.key])
+ expect(seen).toHaveBeenCalledTimes(3)
+ })
+})
diff --git a/frontend/src/views/CoachChat.refusal.test.jsx b/frontend/src/views/CoachChat.refusal.test.jsx
index 8edb2112c..ea64531df 100644
--- a/frontend/src/views/CoachChat.refusal.test.jsx
+++ b/frontend/src/views/CoachChat.refusal.test.jsx
@@ -124,4 +124,14 @@ describe('a request the server refuses', () => {
await send('x')
expect(mocks.toast).toHaveBeenCalledWith('Network unreachable')
})
+
+ it('"Not now" on the data-sharing question is an answer: no toast, no chat line, the text stays', async () => {
+ const before = mocks.S.coach.chat.length
+ vi.mocked(requestReview).mockRejectedValueOnce(Object.assign(new Error('Okay, nothing was sent.'), { code: 'declined', quiet: true, data: { code: 'declined' } }))
+ mount()
+ await send('look at my squats')
+ expect(mocks.toast).not.toHaveBeenCalled()
+ expect(mocks.S.coach.chat).toHaveLength(before)
+ expect(host.querySelector('.composer textarea').value).toBe('look at my squats')
+ })
})