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 auf dem Handy: ueber den gepaarten Server, oder mit eigenem API-Key
Duarte Santos1986a507b0b1
diff --git a/api/coach/core/categories.js b/api/coach/core/categories.jsnew file mode 100644index 000000000..c7600697a--- /dev/null+++ b/api/coach/core/categories.js@@ -0,0 +1,13 @@+/* The data categories the consent screen names (FR-09/10).+ *+ * Its own tiny module so a screen that only needs to *say* what would leave — the mobile setup+ * screen, before anything AI-related has been loaded — can import five strings without pulling+ * the payload builder and the exercise catalogue behind it. payload.js re-exports it, and+ * builds from it, so the screen cannot drift from the payload. */+export const DATA_CATEGORIES = Object.freeze([+ 'plan', // routines, exercises, sets/reps, schedule, progression settings+ 'training', // logged sets, targets, effort ratings, durations, PRs in the review window+ 'bodyweight', // weigh-ins in the window and your goal weight+ 'profile', // the intake answers you gave the Coach, including any limitations+ 'prefs' // unit, language, effort scale+]);diff --git a/api/coach/core/payload.js b/api/coach/core/payload.jsindex 9646a32d1..bdad4796a 100644--- a/api/coach/core/payload.js+++ b/api/coach/core/payload.js@@ -21,13 +21,7 @@ export const MAX_SESSIONS = 60;/* ---------- the data categories the consent screen names (FR-09/10) ----------Kept here, next to the code that acts on it, and rendered by the consent UI from the samelist — a screen that drifts from the payload is worse than no screen. */-export const DATA_CATEGORIES = [- 'plan', // routines, exercises, sets/reps, schedule, progression settings- 'training', // logged sets, targets, effort ratings, durations, PRs in the review window- 'bodyweight', // weigh-ins in the window and your goal weight- 'profile', // the intake answers you gave the Coach, including any limitations- 'prefs' // unit, language, effort scale-];+export { DATA_CATEGORIES } from './categories.js';/* ---------- reading a session the way the engine reads it ----------Duplicated from frontend/src/lib/history.js rather than shared: the two runtimes have nodiff --git a/frontend/package-lock.json b/frontend/package-lock.jsonindex 7bd7ccebb..47e78246e 100644--- a/frontend/package-lock.json+++ b/frontend/package-lock.json@@ -9,6 +9,7 @@"version": "1.2.11","license": "AGPL-3.0-or-later","dependencies": {+ "@aparajita/capacitor-secure-storage": "^7.1.6","@capacitor/app": "^7.1.2","@capacitor/core": "^7.6.8","@capacitor/filesystem": "^7.1.8",@@ -31,6 +32,20 @@"vitest": "^4.1.10"}},+ "node_modules/@aparajita/capacitor-secure-storage": {+ "version": "7.1.6",+ "resolved": "https://registry.npmjs.org/@aparajita/capacitor-secure-storage/-/capacitor-secure-storage-7.1.6.tgz",+ "integrity": "sha512-KIfLOm/oSciUiWsOMtMv2nzlnwW3LERid0DvZ3djt7UORBQvFqpvSefiLG5kkc8D34pGkb2ZqAz0ZprrI9LiTQ==",+ "dependencies": {+ "@capacitor/android": "^7.4.4",+ "@capacitor/app": "^7.1.0",+ "@capacitor/core": "^7.4.4",+ "@capacitor/ios": "^7.4.4"+ },+ "engines": {+ "node": ">=20.0.0"+ }+ },"node_modules/@babel/code-frame": {"version": "7.29.7","resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz",@@ -58,7 +73,6 @@"version": "7.6.8","resolved": "https://registry.npmjs.org/@capacitor/android/-/android-7.6.8.tgz","integrity": "sha512-N5LXe1ls+TA0mq+RhtyDdP1JISzAAI+OuLGL3G7OWQxfQQOZYkiEjEJMYqMV6JR421IqpRsYj08JOfC0PFC3NA==",- "dev": true,"peerDependencies": {"@capacitor/core": "^7.6.0"}@@ -510,7 +524,6 @@"version": "7.6.8","resolved": "https://registry.npmjs.org/@capacitor/ios/-/ios-7.6.8.tgz","integrity": "sha512-TAM1FdI1Cfl8e/wLBo7x5m61V/J1fMEpyxU2psZzHzsa436k2pwEME6CQoBRYdw6Q6gud0jZSPwOVrNn+MI7Ag==",- "dev": true,"peerDependencies": {"@capacitor/core": "^7.6.0"}diff --git a/frontend/package.json b/frontend/package.jsonindex 6743f20e4..73039dd4c 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -14,6 +14,7 @@},"license": "AGPL-3.0-or-later","dependencies": {+ "@aparajita/capacitor-secure-storage": "^7.1.6","@capacitor/app": "^7.1.2","@capacitor/core": "^7.6.8","@capacitor/filesystem": "^7.1.8",diff --git a/frontend/src/App.jsx b/frontend/src/App.jsxindex 90264da64..6be608b06 100644--- a/frontend/src/App.jsx+++ b/frontend/src/App.jsx@@ -29,6 +29,7 @@ import Admin from './views/Admin.jsx'import Coach from './views/Coach.jsx'import CoachIntake from './views/CoachIntake.jsx'import CoachProposal from './views/CoachProposal.jsx'+import CoachSetup from './views/CoachSetup.jsx'bindUI(useUI) // lets the shared controls open sheets without importing the store at module scope@@ -102,6 +103,7 @@ function Shell() {<Route path="/coach" element={<Coach />} /><Route path="/coach/intake" element={<CoachIntake />} /><Route path="/coach/proposal" element={<CoachProposal />} />+ <Route path="/coach/setup" element={<CoachSetup />} /><Route path="/admin" element={user?.admin ? <Admin /> : <Navigate to="/home" replace />} /><Route path="*" element={<Navigate to="/home" replace />} /></Routes>diff --git a/frontend/src/lib/capacitor-fetch.js b/frontend/src/lib/capacitor-fetch.jsnew file mode 100644index 000000000..bc074756d--- /dev/null+++ b/frontend/src/lib/capacitor-fetch.js@@ -0,0 +1,43 @@+// A fetch for the phone that does not go through the WebView.+//+// The Coach's HTTP adapters take an injectable `fetch`. In the native app the WebView's origin+// is capacitor://localhost, and a provider that has no CORS story for that origin would refuse+// the preflight before a single byte of the request went out. CapacitorHttp.request() makes+// the call from native code instead, where CORS does not exist.+//+// Deliberately an explicit shim rather than the `plugins.CapacitorHttp.enabled` switch: that+// flag replaces window.fetch for the whole app, which would silently reroute every api() call+// a paired phone makes to its own server as well. Only the Coach's provider calls go this way.+//+// Only the subset the adapters use is implemented: method, headers, a JSON body, an abort+// signal, and a response with ok/status/text()/json().+export async function nativeFetch(url, init = {}) {+ let cap = null+ try { cap = await import('@capacitor/core') } catch { /* not a Capacitor build */ }+ if (!cap || !cap.Capacitor || !cap.Capacitor.isNativePlatform()) return fetch(url, init)++ const headers = { ...(init.headers || {}) }+ let data = init.body+ if (typeof data === 'string') { try { data = JSON.parse(data) } catch { /* send as-is */ } }++ const request = cap.CapacitorHttp.request({+ url, method: init.method || 'GET', headers, data,+ responseType: 'text', connectTimeout: 30000, readTimeout: 6 * 60000+ })+ const res = init.signal ? await Promise.race([request, abortOf(init.signal)]) : await request+ const text = typeof res.data === 'string' ? res.data : res.data == null ? '' : JSON.stringify(res.data)+ return {+ ok: res.status >= 200 && res.status < 300,+ status: res.status,+ text: async () => text,+ json: async () => JSON.parse(text)+ }+}++function abortOf(signal) {+ return new Promise((_, reject) => {+ const err = () => reject(Object.assign(new Error('aborted'), { name: 'AbortError' }))+ if (signal.aborted) return err()+ signal.addEventListener('abort', err, { once: true })+ })+}diff --git a/frontend/src/lib/coach-api.js b/frontend/src/lib/coach-api.jsindex 6fa3d5498..d7ec9ecdd 100644--- a/frontend/src/lib/coach-api.js+++ b/frontend/src/lib/coach-api.js@@ -8,7 +8,10 @@import { useEffect, useState, useCallback, useRef } from 'react'import { api } from './api.js'import { DEMO } from './demo.js'+import { MOBILE } from './mobile.js'+import { t } from './i18n.js'import { useStore } from '../store/useStore.js'+import { useUI } from '../store/useUI.js'const POLL_MS = 3000 // a job is running: often enough to feel liveconst IDLE_MS = 60000 // a Coach screen is open but nothing is running@@ -21,13 +24,32 @@ let demoMod = nullconst demo = async () => (demoMod = demoMod || await import('./coach-demo.js'))const S = () => useStore.getState().S-export const coachStatus = async () => DEMO ? (await demo()).demoStatus() : api('/api/coach/status')-export const requestReview = async note => DEMO ? (await demo()).demoReview(S()) : api('/api/coach/review', { method: 'POST', body: JSON.stringify({ note: note || '' }) })-export const requestPlan = async intake => DEMO ? (await demo()).demoPlan(S(), intake) : api('/api/coach/plan', { method: 'POST', body: JSON.stringify({ intake }) })-export const refinePlan = async text => DEMO ? (await demo()).demoRefine(S()) : api('/api/coach/plan', { method: 'POST', body: JSON.stringify({ refine: text }) })-export const resolvePending = async body => DEMO ? (await demo()).demoResolve() : api('/api/coach/pending/resolve', { method: 'POST', body: JSON.stringify(body) })-export const forgetCoach = async () => DEMO ? (await demo()).demoResolve() : api('/api/coach/forget', { method: 'POST', body: '{}' })-export const disclosure = async () => DEMO ? (await demo()).demoDisclosure() : api('/api/coach/disclosure')+// The mobile build's third answer: a phone that brought its own API key runs the Coach itself+// (lib/coach-local.js — the same core the server runs, imported lazily so the catalogue and the+// validator only ever load on a phone that chose this). A paired phone takes the api() branch+// like the web app does; nothing on the web or demo builds reaches this.+let localMod = null+const LOCAL = () => MOBILE && useStore.getState().coachLocal?.mode === 'byok'+const local = async () => {+ if (!localMod) {+ localMod = await import('./coach-local.js')+ // 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+ if (ev.kind === 'failed') toast(JOB_ERRORS[ev.errorClass] || JOB_ERRORS.internal)+ else if (ev.kind === 'nochange') toast(t('Nothing to change right now: {0}', String(ev.reading || '').slice(0, 140)))+ })+ }+ return localMod+}++export const coachStatus = async () => DEMO ? (await demo()).demoStatus() : LOCAL() ? (await local()).localStatus() : api('/api/coach/status')+export 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 || '' }) })+export 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 }) })+export 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 }) })+export const resolvePending = async body => DEMO ? (await demo()).demoResolve() : LOCAL() ? (await local()).localResolve(body) : api('/api/coach/pending/resolve', { method: 'POST', body: JSON.stringify(body) })+export const forgetCoach = async () => DEMO ? (await demo()).demoResolve() : LOCAL() ? (await local()).localForget() : api('/api/coach/forget', { method: 'POST', body: '{}' })+export const disclosure = async () => DEMO ? (await demo()).demoDisclosure() : LOCAL() ? (await local()).localDisclosure() : api('/api/coach/disclosure')/* Whose provider account this profile is about to spend. Its own call because the constraint isthat the Coach screen states it too, not just the admin card — and because in instance mode a@@ -35,7 +57,8 @@ export const disclosure = async () => DEMO ? (await demo()).demoDisclosure() : athey ask for anything rather than after a job is turned down. */export const coachAccount = async () =>DEMO ? { mode: 'instance', provider: 'demo', providerLabel: 'Demo', account: null, connected: true, reason: null, message: null }- : api('/api/coach/account')+ : LOCAL() ? { mode: 'device', provider: useStore.getState().coachLocal.provider, providerLabel: null, account: null, connected: true, reason: null, message: null }+ : api('/api/coach/account')/* Admin-only. The token is write-only from the client's side: it goes up once and is neverread back, so there is deliberately no "show me the current credential" call to pair with it. */diff --git a/frontend/src/lib/coach-device.js b/frontend/src/lib/coach-device.jsnew file mode 100644index 000000000..0410e87c5--- /dev/null+++ b/frontend/src/lib/coach-device.js@@ -0,0 +1,37 @@+// Mobile build only: how the Coach runs on this phone, and the little it keeps between runs.+//+// 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+// not even here: see coach-secrets.js.+//+// This module is intentionally light. The setup screen imports it before the user has chosen+// anything, and the promise there is that nothing AI-shaped loads until they do.+import { readJsonFile, writeJsonFile } from './mobile.js'++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 }++let cache = null+export async function loadCoachDevice() {+ if (cache) return cache+ const saved = await readJsonFile(FILE)+ cache = { ...DEFAULTS, ...(saved && typeof saved === 'object' ? saved : {}) }+ if (!COACH_MODES.includes(cache.mode)) cache.mode = 'off'+ return cache+}+export async function saveCoachDevice(patch) {+ const next = { ...(await loadCoachDevice()), ...patch }+ cache = next+ await writeJsonFile(FILE, next)+ return next+}+/** The part of it a UI may show: never the pending proposal, never the handle. */+export const coachDeviceSettings = d => d ? { mode: d.mode, provider: d.provider, model: d.model, baseUrl: d.baseUrl } : null++// Test seam.+export function _resetCoachDevice() { cache = null }diff --git a/frontend/src/lib/coach-local.js b/frontend/src/lib/coach-local.jsnew file mode 100644index 000000000..7098030a7--- /dev/null+++ b/frontend/src/lib/coach-local.js@@ -0,0 +1,165 @@+// The Coach, on a phone that brings its own API key.+//+// No server. The pipeline the server runs — payload allowlist, prompt, provider call, parser,+// validator, one repair round — is imported from api/coach/core and run here, in-process, so+// the phone gets exactly the code the server has and not a second opinion of it. The apply+// engine, staleness, snapshot/revert and the log are the ones every build already uses.+//+// This module is the one static importer of the core, which makes `import('./coach-local.js')`+// the whole lazy chunk: the exercise catalogue, the prompts and the validator arrive together+// and only after the user chose this mode. coach-api.js dispatches here the same way it+// dispatches to the demo provider, so the screens never learn that there is no server.+//+// What is different from the server, and on purpose:+// - the user pays. There is no cfg.caps to lean on, so a local daily cap is not optional.+// - the pseudonym is drawn at random once and kept, rather than derived from a secret.+// - a proposal waits in the device file, not in S, so it survives an app kill without+// riding into a backup or a sync.+import * as payloadLib from '../../../api/coach/core/payload.js'+import { runPipeline } from '../../../api/coach/core/pipeline.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'+import gemini from '../../../api/coach/core/adapters/gemini.js'+import compatible from '../../../api/coach/core/adapters/compatible.js'+import { nativeFetch } from './capacitor-fetch.js'+import { getApiKey } from './coach-secrets.js'+import { loadCoachDevice, saveCoachDevice } from './coach-device.js'+import { planHash } from './coach.js'+import { todayISO } from './format.js'+import { t } from './i18n.js'++export const ADAPTERS = { anthropic, openai, gemini, compatible }+export const LOCAL_DAILY_CAP = 10+export const TIMEOUT_MS = 5 * 60000+const PENDING_DAYS = 14+const HANDLE_LENGTH = 16++let job = null+let lastError = null+// Reported to the screens through the same status shape the server answers with; a toast is+// also raised because on the server a failed job lands in the admin card, and here there is+// no admin card — the user is the operator.+let notify = null+export function setNotifier(fn) { notify = fn }++/* ---------- what this phone is configured with ---------- */++const cfgOf = d => ({ provider: d.provider, providerOptions: d.baseUrl ? { [d.provider]: { baseUrl: d.baseUrl } } : {} })+const envOf = (d, key) => (key ? { [HTTP_PROVIDERS[d.provider].apiKeyEnv]: key } : {})++function mintHandle() {+ const bytes = new Uint8Array(12)+ ;(globalThis.crypto || {}).getRandomValues ? crypto.getRandomValues(bytes) : bytes.forEach((_, i) => { bytes[i] = Math.floor(Math.random() * 256) })+ let bin = ''; bytes.forEach(b => { bin += String.fromCharCode(b) })+ return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '').slice(0, HANDLE_LENGTH)+}+async function handle() {+ const d = await loadCoachDevice()+ if (d.handle && d.handle.length === HANDLE_LENGTH) return d.handle+ const h = mintHandle()+ await saveCoachDevice({ handle: h })+ return h+}++/* ---------- the cap ---------- */++async function capState() {+ const d = await loadCoachDevice()+ const today = todayISO()+ const used = d.daily && d.daily.d === today ? d.daily.n : 0+ return { used, limit: LOCAL_DAILY_CAP }+}+async function bumpDaily() {+ const { used } = await capState()+ await saveCoachDevice({ daily: { d: todayISO(), n: used + 1 } })+}++/* ---------- the API surface coach-api.js dispatches to ---------- */++export async function localStatus() {+ const d = await loadCoachDevice()+ if (d.pending && d.pending.expiresAt && d.pending.expiresAt < Date.now()) await saveCoachDevice({ pending: null })+ return { job, pending: (await loadCoachDevice()).pending || null, cap: await capState(), lastError }+}++export const localReview = (S, note) => start(S, 'review', { note: note ? String(note).slice(0, 1000) : null })+export const localPlan = (S, intake) => start(S, 'create', { intake: intake || null })+export const localRefine = async (S, text) => {+ const d = await loadCoachDevice()+ const pendingCreate = d.pending && d.pending.kind === 'create' ? d.pending : null+ return start(S, 'create', { refine: String(text || '').slice(0, 1000), previous: pendingCreate?.bundle || null, iteration: (pendingCreate?.iteration || 1) + 1 })+}+export async function localResolve() { await saveCoachDevice({ pending: null }); return { ok: true } }+export async function localForget() { job = null; lastError = null; await saveCoachDevice({ pending: null, daily: null }); return { ok: true } }++export async function localDisclosure() {+ const d = await loadCoachDevice()+ const meta = HTTP_PROVIDERS[d.provider] || {}+ const base = d.provider ? baseUrlFor(d.provider, cfgOf(d)) : ''+ return {+ provider: d.provider, providerLabel: meta.label || t('the configured AI provider'),+ categories: payloadLib.DATA_CATEGORIES, version: 1,+ // The honest difference from the self-hosted flow: it is the user's own account.+ payer: 'you', host: hostOf(base)+ }+}++/** The models the configured endpoint serves — the setup screen's list, and its reachability test. */+export async function localModels(settings, key) {+ const adapter = ADAPTERS[settings.provider]+ if (!adapter) return { ok: false, error: 'unknown provider', models: [] }+ return adapter.models(cfgOf(settings), envOf(settings, key), { fetch: nativeFetch, timeoutMs: 20000 })+}++const hostOf = url => { try { return new URL(url).host } catch { return url || '' } }++/* ---------- running a job ---------- */++async function start(S, kind, opts) {+ if (job) throw Object.assign(new Error(t('The Coach is already thinking about your training.')), { status: 409, code: 'busy' })+ if (!S?.coach?.consent?.agreedAt) throw Object.assign(new Error(t('The Coach needs your go-ahead first.')), { status: 403, code: 'consent' })+ const d = await loadCoachDevice()+ const adapter = ADAPTERS[d.provider]+ if (d.mode !== 'byok' || !adapter) throw Object.assign(new Error(t('The Coach isn’t set up on this phone.')), { status: 503, code: 'off' })+ const cap = await capState()+ if (cap.used >= cap.limit) throw Object.assign(new Error(t('The Coach is resting — you have 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() }+ 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 })+ return { job }+}++async function run(S, kind, opts, d, adapter) {+ const key = await getApiKey()+ const payload = payloadLib.build(S, {+ handle: await handle(), kind, intake: opts.intake, note: opts.note, refine: opts.refine, previous: opts.previous+ })+ const attempt = await runPipeline({+ adapter, cfg: cfgOf(d), kind, payload,+ model: d.model || HTTP_PROVIDERS[d.provider].defaultModel, timeoutMs: TIMEOUT_MS,+ invokeOpts: { env: envOf(d, key), fetch: nativeFetch }+ })+ if (!attempt.ok) {+ lastError = { errorClass: attempt.errorClass, detail: attempt.detail || null }+ if (notify) notify({ kind: 'failed', errorClass: attempt.errorClass, detail: attempt.detail || null })+ return+ }+ if (attempt.nochange) {+ if (notify) notify({ kind: 'nochange', reading: attempt.reading })+ return+ }+ const pending = {+ id: job.id, kind, createdAt: Date.now(), expiresAt: Date.now() + PENDING_DAYS * 86400000,+ planHash: planHash(S), iteration: opts.iteration || 1,+ ...attempt.result+ }+ await saveCoachDevice({ pending })+ if (notify) notify({ kind: 'ready', pending })+}++// Test seam.+export function _resetLocal() { job = null; lastError = null }diff --git a/frontend/src/lib/coach-local.test.js b/frontend/src/lib/coach-local.test.jsnew file mode 100644index 000000000..f8c4e9800--- /dev/null+++ b/frontend/src/lib/coach-local.test.js@@ -0,0 +1,181 @@+// The Coach on a phone with its own key: the same core the server runs, driven end to end+// here with a fake provider — payload → prompt → HTTP adapter → parser → validator → a proposal+// the apply engine accepts. Also the three things this mode has to get right on its own: the+// daily cap, the key never touching S, and a proposal surviving in the device file.+import { describe, it, expect, vi, beforeEach } from 'vitest'++// The device file and the secret store are in-memory here; nativeFetch is the script.+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)) }+}))+const secret = { key: 'sk-test-1' }+vi.mock('./coach-secrets.js', () => ({ getApiKey: async () => secret.key, setApiKey: async v => { secret.key = v }, clearApiKey: async () => { secret.key = null } }))+const wire = { calls: [], answer: null }+vi.mock('./capacitor-fetch.js', () => ({+ nativeFetch: async (url, init) => {+ wire.calls.push({ url, init, body: JSON.parse(init.body) })+ const a = typeof wire.answer === 'function' ? wire.answer(wire.calls.length) : 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, saveCoachDevice } = await import('./coach-device.js')+const { applyChangeSet, markStale, planHash } = await import('./coach.js')+const { EXERCISES } = await import('../../../api/coach/core/library-data.js')++const EX = EXERCISES[0].id, EX2 = EXERCISES[1].id+const state = () => ({+ unit: 'kg', lang: 'en',+ routines: [{ id: 'r1', name: 'A', ex: [{ id: EX, sets: 3, reps: 8, mode: 'reps' }, { id: EX2, sets: 3, reps: 10, mode: 'reps' }] }],+ week: { 1: 'r1' }, dayPlan: {}, customEx: [], bodyweight: [], workouts: [+ { d: '2026-08-20', start: 1, end: 3600001, 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 }] }] }+ ],+ coach: { consent: { agreedAt: '2026-08-01T00:00:00Z', version: 1 }, profile: null, cadence: 'off', lastReview: null, log: [], snapshots: [] }+})+const chat = content => ({ status: 200, body: { choices: [{ finish_reason: 'stop', message: { content } }] } })+const review = { coach_contract: 1, summary: 'One tweak.', evidence: { from: '2026-08-01', to: '2026-08-20', sessions: 1 },+ changes: [{ id: 'c1', type: 'sets', target: { routineId: 'r1', exId: EX }, after: 4, why: 'every set was clean' }] }++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('the Coach on a phone with its own key', () => {+ beforeEach(async () => {+ _resetCoachDevice(); local._resetLocal()+ device.data = { mode: 'byok', provider: 'openai', model: 'gpt-t', baseUrl: null }+ wire.calls = []; wire.answer = chat(JSON.stringify(review)); secret.key = 'sk-test-1'+ })++ it('runs a review through the real pipeline and produces a proposal the apply engine accepts', async () => {+ const S = state()+ await local.localReview(S, 'shoulder')+ const s = await settle()+ expect(s.pending).toBeTruthy()+ expect(s.pending.kind).toBe('review')+ expect(s.pending.planHash).toBe(planHash(S))+ expect(s.pending.changes).toHaveLength(1)+ expect(s.pending.changes[0].before).toBe(3) // computed server-side… which is here+ // What went on the wire: OpenAI's shape, the key as a bearer, the payload in the user turn.+ expect(wire.calls).toHaveLength(1)+ expect(wire.calls[0].url).toBe('https://api.openai.com/v1/chat/completions')+ expect(wire.calls[0].init.headers.authorization).toBe('Bearer sk-test-1')+ expect(wire.calls[0].body.model).toBe('gpt-t')+ expect(wire.calls[0].body.messages[1].content).toContain('"userNote": "shoulder"')+ // …and the proposal applies with the ordinary engine.+ const marked = markStale(s.pending, S)+ expect(marked.changes[0].status).not.toBe('stale')+ applyChangeSet(S, marked, ['c1'])+ expect(S.routines[0].ex[0].sets).toBe(4)+ expect(S.coach.snapshots).toHaveLength(1)+ })++ it('spends the single repair round when the first answer is unusable, then gives up', async () => {+ wire.answer = n => n === 1 ? chat('{"coach_contract":1,"changes":[{"id":"x","type":"teleport"}]}') : chat(JSON.stringify(review))+ await local.localReview(state())+ const s = await settle()+ expect(wire.calls).toHaveLength(2)+ expect(wire.calls[1].body.messages[1].content).toContain('teleport') // the errors went back verbatim+ expect(s.pending.changes).toHaveLength(1)++ local._resetLocal(); wire.calls = []+ await saveCoachDevice({ pending: null })+ wire.answer = chat('not json at all')+ await local.localReview(state())+ const f = await settle()+ expect(wire.calls).toHaveLength(2)+ expect(f.pending).toBeNull()+ expect(f.lastError.errorClass).toBe('unusable')+ })++ it('a 401 is an auth failure, and never a proposal', async () => {+ wire.answer = { status: 401, body: { error: { message: 'bad key' } } }+ await local.localReview(state())+ const s = await settle()+ expect(s.pending).toBeNull()+ expect(s.lastError.errorClass).toBe('auth')+ })++ it('the key never enters S, the device file, or the proposal', async () => {+ const S = state()+ await local.localReview(S)+ const s = await settle()+ expect(JSON.stringify(S)).not.toContain('sk-test-1')+ expect(JSON.stringify(device.data)).not.toContain('sk-test-1')+ expect(JSON.stringify(s.pending)).not.toContain('sk-test-1')+ })++ it('mints one 16-character pseudonym and keeps it; the payload carries it and never a name', async () => {+ await local.localReview({ ...state(), name: 'Duarte' })+ await settle()+ const first = (await loadCoachDevice()).handle+ expect(first).toHaveLength(16)+ const payload = wire.calls[0].body.messages[1].content+ expect(payload).toContain(`"profile": "${first}"`)+ expect(payload).not.toContain('Duarte')+ local._resetLocal(); await saveCoachDevice({ pending: null })+ await local.localReview(state()); await settle()+ expect((await loadCoachDevice()).handle).toBe(first)+ })++ it('refuses without consent, refuses while busy, and stops at the daily cap', async () => {+ const noConsent = state(); noConsent.coach.consent = null+ await expect(local.localReview(noConsent)).rejects.toMatchObject({ code: 'consent' })++ await local.localReview(state())+ await expect(local.localReview(state())).rejects.toMatchObject({ code: 'busy' })+ await settle()++ await saveCoachDevice({ daily: { d: new Date().toISOString().slice(0, 10), n: local.LOCAL_DAILY_CAP } })+ await expect(local.localReview(state())).rejects.toMatchObject({ code: 'cap' })+ expect((await local.localStatus()).cap).toEqual({ used: local.LOCAL_DAILY_CAP, limit: local.LOCAL_DAILY_CAP })+ })++ it('a proposal waits in the device file, expires, and is cleared by resolve', async () => {+ await local.localReview(state())+ await settle()+ expect(device.data.pending).toBeTruthy()+ await saveCoachDevice({ pending: { ...device.data.pending, expiresAt: Date.now() - 1 } })+ expect((await local.localStatus()).pending).toBeNull()+ await local.localReview(state()); await settle()+ await local.localResolve()+ expect(device.data.pending).toBeNull()+ })++ it('creates a plan from an intake, and refines it against the previous bundle', async () => {+ const plan = { coach_contract: 1, opengym_plan: 1, name: 'P', summary: 's', basedOn: 'b', week: { 1: 'r1', 3: 'r2', 5: 'r1' },+ routines: [+ { id: 'r1', name: 'A', emoji: '💪', why: 'w', ex: [{ id: EX, sets: 3, mode: 'reps', reps: 8, why: 'w' }, { id: EX2, sets: 3, mode: 'reps', reps: 10, why: 'w' }, { id: EXERCISES[2].id, sets: 3, mode: 'reps', reps: 10, why: 'w' }] },+ { id: 'r2', name: 'B', emoji: '🏋️', why: 'w', ex: [{ id: EXERCISES[3].id, sets: 3, mode: 'reps', reps: 8, why: 'w' }, { id: EXERCISES[4].id, sets: 3, mode: 'reps', reps: 10, why: 'w' }, { id: EXERCISES[5].id, sets: 3, mode: 'reps', reps: 10, why: 'w' }] }+ ], customEx: [] }+ wire.answer = chat(JSON.stringify(plan))+ const S = { ...state(), routines: [], week: {} }+ await local.localPlan(S, { goal: 'muscle', daysPerWeek: 3 })+ const s = await settle()+ expect(s.pending.kind).toBe('create')+ expect(s.pending.bundle.routines).toHaveLength(2)+ expect(wire.calls[0].body.messages[1].content).toContain('"daysPerWeek": 3')++ await local.localRefine(S, 'no lunges')+ const r = await settle()+ expect(r.pending.iteration).toBe(2)+ expect(wire.calls[1].body.messages[1].content).toContain('no lunges')+ expect(wire.calls[1].body.messages[1].content).toContain('"previous"')+ })++ it('disclosure says who pays and where it goes', async () => {+ const d = await local.localDisclosure()+ expect(d.payer).toBe('you')+ expect(d.host).toBe('api.openai.com')+ expect(d.categories).toEqual(['plan', 'training', 'bodyweight', 'profile', 'prefs'])+ })+})diff --git a/frontend/src/lib/coach-secrets.js b/frontend/src/lib/coach-secrets.jsnew file mode 100644index 000000000..f97fd9415--- /dev/null+++ b/frontend/src/lib/coach-secrets.js@@ -0,0 +1,43 @@+// Where the phone keeps the user's own API key: the platform's secure storage — the Keychain on+// iOS, the Keystore-backed EncryptedSharedPreferences on Android — and nowhere else. Never in+// S (which syncs and exports), never in localStorage (which the WebView evicts and any page on+// the same origin can read), never in the coach device file next to it.+//+// The plugin is imported lazily and every call is wrapped: on a plain web dev run it stores+// to localStorage by its own admission, and in a test there is no platform at all. In both+// cases the fallback is a process-local map that forgets on reload, which is the honest+// behaviour for a place that cannot keep a secret.+const KEY = 'coach.apiKey'+const memory = new Map()++let pluginPromise = null+function plugin() {+ if (!pluginPromise) {+ pluginPromise = import('@aparajita/capacitor-secure-storage')+ .then(m => (m && m.SecureStorage && typeof m.SecureStorage.get === 'function' ? m.SecureStorage : null))+ .catch(() => null)+ }+ return pluginPromise+}++export async function getApiKey() {+ const p = await plugin()+ if (p) {+ try { const v = await p.get(KEY); return typeof v === 'string' && v ? v : null } catch { /* fall through */ }+ }+ return memory.get(KEY) || null+}+export async function setApiKey(value) {+ const v = String(value || '').trim()+ if (!v) return clearApiKey()+ const p = await plugin()+ if (p) {+ try { await p.set(KEY, v); memory.delete(KEY); return } catch { /* fall through */ }+ }+ memory.set(KEY, v)+}+export async function clearApiKey() {+ const p = await plugin()+ if (p) { try { await p.remove(KEY) } catch { /* nothing to clear */ } }+ memory.delete(KEY)+}diff --git a/frontend/src/lib/coach.js b/frontend/src/lib/coach.jsindex b2db4ede9..bd8508b27 100644--- a/frontend/src/lib/coach.js+++ b/frontend/src/lib/coach.js@@ -41,10 +41,25 @@ const coachOf = s => (s.coach = s.coach || emptyCoach())//// The demo build is the one exception, and it is deliberate: it has no backend and no// account, but it does have a canned provider, and hiding the app's most interesting feature-// from the page people are sent to look at it on would be a strange choice. The mobile build-// stays out — there is no server there to fake anything with.-export const coachAvailable = (config, user, { demo, mobile } = {}) =>- mobile ? false : demo ? true : !!(config?.coach?.enabled && user)+// from the page people are sent to look at it on would be a strange choice.+//+// The mobile build has two ways in, both chosen in Settings (views/CoachSetup.jsx): a phone+// paired to a self-hosted server is an ordinary signed-in profile and takes the web rule; a+// phone that brought its own API key runs the Coach itself (lib/coach-local.js). Nothing+// chosen means nothing shown — the same "invisible unless configured" promise the web keeps.+export const coachAvailable = (config, user, { demo, mobile, coachMode } = {}) =>+ mobile ? (coachMode === 'byok' || !!(config?.coach?.enabled && user))+ : demo ? true : !!(config?.coach?.enabled && user)++// What each data category means, in the user's words. Rendered from the same list the payload+// builder uses (api/coach/core/categories.js), so the screen cannot promise less than leaves.+export const CATEGORY_TEXT = {+ plan: ['Your plan', 'Routines, exercises, sets and reps, your weekly schedule and progression settings.'],+ training: ['Your logged training', 'Sets you logged in the review window — weights, reps, times, effort ratings and how long sessions took.'],+ bodyweight: ['Body weight', 'Weigh-ins from the same window, and your goal weight if you set one.'],+ profile: ['What you tell the Coach', 'Your intake answers, including any limitations or injuries you describe.'],+ prefs: ['A few preferences', 'Your unit, your language and which effort scale you log.']+}export const hasConsent = S => !!S?.coach?.consent?.agreedAt && S.coach.consent.version === CONSENT_VERSION/* ============================ plan fingerprint ============================ */diff --git a/frontend/src/lib/coach.test.js b/frontend/src/lib/coach.test.jsindex 42910f485..af6fcfe94 100644--- a/frontend/src/lib/coach.test.js+++ b/frontend/src/lib/coach.test.js@@ -40,9 +40,19 @@ describe('gating', () => {expect(coachAvailable({ coach: { enabled: true } }, null)).toBe(false)})- it('is off in the mobile build, which has no server to run anything', () => {- expect(coachAvailable({ coach: { enabled: true } }, { id: 'u' }, { mobile: true })).toBe(false)+ it('is off in the mobile build until a mode is chosen in Settings', () => {expect(coachAvailable(null, null, { mobile: true })).toBe(false)+ expect(coachAvailable(null, null, { mobile: true, coachMode: 'off' })).toBe(false)+ // Only its own key makes a local-only phone eligible; "server" without a pairing is nothing.+ expect(coachAvailable(null, null, { mobile: true, coachMode: 'server' })).toBe(false)+ expect(coachAvailable(null, null, { mobile: true, coachMode: 'byok' })).toBe(true)+ })++ it('a phone paired to a server takes the web rule — the server must offer the Coach', () => {+ expect(coachAvailable({ coach: { enabled: true } }, { id: 'u' }, { mobile: true })).toBe(true)+ expect(coachAvailable({ coach: { enabled: true } }, { id: 'u' }, { mobile: true, coachMode: 'server' })).toBe(true)+ expect(coachAvailable({}, { id: 'u' }, { mobile: true, coachMode: 'server' })).toBe(false)+ expect(coachAvailable({ coach: { enabled: true } }, null, { mobile: true, coachMode: 'server' })).toBe(false)})it('is on in the demo build, which fakes the provider locally', () => {diff --git a/frontend/src/lib/mobile.js b/frontend/src/lib/mobile.jsindex cc848d2c1..30e94ca15 100644--- a/frontend/src/lib/mobile.js+++ b/frontend/src/lib/mobile.js@@ -37,6 +37,22 @@ export async function nativeSave(state) {// travel as if it were training data.const REMOTE_FILE = 'opengym-remote.json'+// Small JSON files in the app's private data directory, for device facts that must not ride+// in S (which syncs and exports): the pairing, and how the Coach runs on this phone.+export async function readJsonFile(name) {+ try {+ const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')+ const r = await Filesystem.readFile({ path: name, directory: Directory.Data, encoding: Encoding.UTF8 })+ return JSON.parse(r.data)+ } catch (e) { return null }+}+export async function writeJsonFile(name, data) {+ try {+ const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')+ await Filesystem.writeFile({ path: name, directory: Directory.Data, data: JSON.stringify(data), encoding: Encoding.UTF8 })+ } catch (e) { /* not a Capacitor build, or the write failed — the caller's in-memory copy stands */ }+}+export async function loadRemoteFile() {try {const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem')diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.jsindex 4315a72cc..a83921f2f 100644--- a/frontend/src/lib/pt-br-locale.test.js+++ b/frontend/src/lib/pt-br-locale.test.js@@ -27,11 +27,11 @@ describe('Brazilian Portuguese locale', () => {.sort(byCodeUnit)const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')- expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(362)- expect(inherited).toHaveLength(517)+ expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(390)+ expect(inherited).toHaveLength(522)// If this fails, review the changed keys and wording before accepting a new hash. From// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list- expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('56fd46aefb32a69e0bd6ed0c9f263d521113d3db6f44cfdcefb66d88d26312e5')+ expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('215c0ce2464d4ab771a208158dcc005f26f8538c15023fb5ff77828dfbc235f5')})test('does not leak European Portuguese UI terms', () => {diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex dedd6b587..34bc3d443 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -832,5 +832,40 @@ export default {'Add session note': 'Notiz zum Training','Edit session note': 'Notiz bearbeiten','How the session went as a whole.': 'Wie das Training insgesamt lief.',- 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-Pause trainiert immer als ein Aufwärmsatz mit dieser Wiederholungszahl und ein Rest-Pause-Arbeitssatz — „Sätze“ wird nicht verwendet.'+ 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-Pause trainiert immer als ein Aufwärmsatz mit dieser Wiederholungszahl und ein Rest-Pause-Arbeitssatz — „Sätze“ wird nicht verwendet.',++ // --- AI Coach on the phone ---+ '(saved)': '(gespeichert)',+ 'AI Coach': 'KI-Coach',+ 'API key': 'API-Schlüssel',+ 'An AI coach that can design your plan and adjust it from what you actually log. It runs with your own API key, it never changes anything without your say-so, and it is off until you turn it on.': 'Ein KI-Coach, der deinen Plan entwirft und ihn anhand dessen anpasst, was du wirklich einträgst. Er läuft mit deinem eigenen API-Schlüssel, ändert nie etwas ohne dein Okay und ist aus, bis du ihn einschaltest.',+ 'Bring my own API key': 'Eigenen API-Schlüssel verwenden',+ 'Could not reach the provider: {0}': 'Anbieter nicht erreichbar: {0}',+ 'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Jede Anfrage geht direkt mit deinem Schlüssel an {0} — niemand sonst sieht sie, und du bezahlst dafür.',+ 'Endpoint': 'Endpunkt',+ 'Enter your API key': 'Gib deinen API-Schlüssel ein',+ 'How should the Coach run?': 'Wie soll der Coach laufen?',+ 'List models': 'Modelle laden',+ 'Model': 'Modell',+ 'Nothing to change right now: {0}': 'Gerade nichts zu ändern: {0}',+ 'Off — choose how the Coach should run.': 'Aus — wähle, wie der Coach laufen soll.',+ 'Pick a model': 'Modell wählen',+ 'Provider': 'Anbieter',+ 'Runs on this phone with your own API key': 'Läuft auf diesem Handy mit deinem eigenen API-Schlüssel',+ 'Runs on your openGym server': 'Läuft auf deinem openGym-Server',+ 'Save and use the Coach': 'Speichern und Coach nutzen',+ 'The Coach is already thinking about your training.': 'Der Coach denkt schon über dein Training nach.',+ 'The Coach is resting — you have used today’s {0} runs on this phone.': 'Der Coach pausiert — du hast die {0} Läufe für heute auf diesem Handy aufgebraucht.',+ 'The Coach isn’t set up on this phone.': 'Der Coach ist auf diesem Handy nicht eingerichtet.',+ 'The Coach needs your go-ahead first.': 'Der Coach braucht zuerst dein Okay.',+ 'The key is stored in this phone’s secure storage and never leaves it except to call the provider.': 'Der Schlüssel liegt im sicheren Speicher dieses Handys und verlässt es nur, um den Anbieter aufzurufen.',+ 'This phone calls the provider directly with your key. Every request is charged to your account.': 'Dieses Handy ruft den Anbieter direkt mit deinem Schlüssel auf. Jede Anfrage geht auf dein Konto.',+ 'Turn the Coach off on this phone': 'Coach auf diesem Handy ausschalten',+ 'Use my self-hosted openGym': 'Mein selbst gehostetes openGym nutzen',+ 'What leaves this phone': 'Was dieses Handy verlässt',+ 'When you ask for a plan or a review, this phone sends the following straight to {0}, using your own API key. You pay for every request.': 'Wenn du einen Plan oder eine Auswertung anforderst, schickt dieses Handy Folgendes direkt an {0}, mit deinem eigenen API-Schlüssel. Du bezahlst jede Anfrage.',+ 'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'Auf deinem Server ist kein Coach aktiviert — frag den Admin, oder nutze unten deinen eigenen Schlüssel.',+ 'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'Dein Server betreibt den Coach mit dem Anbieter, den sein Admin eingerichtet hat. Über das ohnehin Synchronisierte hinaus verlässt nichts Neues dieses Handy.',+ 'Loading the exercise catalogue…': 'Übungskatalog wird geladen…',+ 'Checking the endpoint…': 'Endpunkt wird geprüft…'}diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex 3d6fff7d7..e8dae0bdc 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -815,5 +815,40 @@ export default {'Add session note': 'Añadir nota de la sesión','Edit session note': 'Editar nota de la sesión','How the session went as a whole.': 'Cómo fue la sesión en conjunto.',- 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause siempre entrena como una serie de calentamiento con estas reps y una serie de trabajo rest-pause — «Series» no se usa.'+ 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause siempre entrena como una serie de calentamiento con estas reps y una serie de trabajo rest-pause — «Series» no se usa.',++ // --- AI Coach on the phone ---+ '(saved)': '(guardada)',+ 'AI Coach': 'Entrenador IA',+ 'API key': 'Clave de API',+ 'An AI coach that can design your plan and adjust it from what you actually log. It runs with your own API key, it never changes anything without your say-so, and it is off until you turn it on.': 'Un entrenador con IA que diseña tu plan y lo ajusta según lo que realmente registras. Funciona con tu propia clave de API, nunca cambia nada sin tu permiso y está apagado hasta que lo enciendas.',+ 'Bring my own API key': 'Usar mi propia clave de API',+ 'Could not reach the provider: {0}': 'No se pudo contactar con el proveedor: {0}',+ 'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Cada solicitud va directamente a {0} con tu clave: nadie más la ve, y la pagas tú.',+ 'Endpoint': 'Endpoint',+ 'Enter your API key': 'Introduce tu clave de API',+ 'How should the Coach run?': '¿Cómo debe funcionar el entrenador?',+ 'List models': 'Listar modelos',+ 'Model': 'Modelo',+ 'Nothing to change right now: {0}': 'Nada que cambiar por ahora: {0}',+ 'Off — choose how the Coach should run.': 'Apagado: elige cómo debe funcionar el entrenador.',+ 'Pick a model': 'Elige un modelo',+ 'Provider': 'Proveedor',+ 'Runs on this phone with your own API key': 'Funciona en este teléfono con tu propia clave de API',+ 'Runs on your openGym server': 'Funciona en tu servidor openGym',+ 'Save and use the Coach': 'Guardar y usar el entrenador',+ 'The Coach is already thinking about your training.': 'El entrenador ya está analizando tu entrenamiento.',+ 'The Coach is resting — you have used today’s {0} runs on this phone.': 'El entrenador descansa: ya has usado las {0} consultas de hoy en este teléfono.',+ 'The Coach isn’t set up on this phone.': 'El entrenador no está configurado en este teléfono.',+ 'The Coach needs your go-ahead first.': 'El entrenador necesita primero tu permiso.',+ 'The key is stored in this phone’s secure storage and never leaves it except to call the provider.': 'La clave se guarda en el almacenamiento seguro de este teléfono y solo sale de él para llamar al proveedor.',+ 'This phone calls the provider directly with your key. Every request is charged to your account.': 'Este teléfono llama al proveedor directamente con tu clave. Cada solicitud se cobra a tu cuenta.',+ 'Turn the Coach off on this phone': 'Apagar el entrenador en este teléfono',+ 'Use my self-hosted openGym': 'Usar mi openGym autoalojado',+ 'What leaves this phone': 'Qué sale de este teléfono',+ 'When you ask for a plan or a review, this phone sends the following straight to {0}, using your own API key. You pay for every request.': 'Cuando pides un plan o una revisión, este teléfono envía lo siguiente directamente a {0}, con tu propia clave de API. Pagas cada solicitud.',+ 'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'Tu servidor no tiene el entrenador activado: pregunta a su administrador o usa tu propia clave abajo.',+ 'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'Tu servidor ejecuta el entrenador con el proveedor que configuró su administrador. Nada nuevo sale de este teléfono más allá de lo que ya se sincroniza.',+ 'Loading the exercise catalogue…': 'Cargando el catálogo de ejercicios…',+ 'Checking the endpoint…': 'Comprobando el endpoint…'}diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex b5916d11b..915c2c8a5 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -815,5 +815,40 @@ export default {'Add session note': 'Ajouter une note de séance','Edit session note': 'Modifier la note de séance','How the session went as a whole.': 'Comment la séance s’est passée dans l’ensemble.',- 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Le rest-pause s’entraîne toujours comme une série d’échauffement à ce nombre de reps, puis une série de travail rest-pause — « Séries » n’est pas utilisé.'+ 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Le rest-pause s’entraîne toujours comme une série d’échauffement à ce nombre de reps, puis une série de travail rest-pause — « Séries » n’est pas utilisé.',++ // --- AI Coach on the phone ---+ '(saved)': '(enregistrée)',+ 'AI Coach': 'Coach IA',+ 'API key': 'Clé API',+ 'An AI coach that can design your plan and adjust it from what you actually log. It runs with your own API key, it never changes anything without your say-so, and it is off until you turn it on.': 'Un coach IA qui conçoit ton plan et l’ajuste d’après ce que tu enregistres vraiment. Il fonctionne avec ta propre clé API, ne change jamais rien sans ton accord et reste désactivé tant que tu ne l’actives pas.',+ 'Bring my own API key': 'Utiliser ma propre clé API',+ 'Could not reach the provider: {0}': 'Impossible de joindre le fournisseur : {0}',+ 'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Chaque requête part directement vers {0} avec ta clé — personne d’autre ne la voit, et c’est toi qui la paies.',+ 'Endpoint': 'Point d’accès',+ 'Enter your API key': 'Saisis ta clé API',+ 'How should the Coach run?': 'Comment le coach doit-il fonctionner ?',+ 'List models': 'Lister les modèles',+ 'Model': 'Modèle',+ 'Nothing to change right now: {0}': 'Rien à changer pour l’instant : {0}',+ 'Off — choose how the Coach should run.': 'Désactivé — choisis comment le coach doit fonctionner.',+ 'Pick a model': 'Choisis un modèle',+ 'Provider': 'Fournisseur',+ 'Runs on this phone with your own API key': 'Fonctionne sur ce téléphone avec ta propre clé API',+ 'Runs on your openGym server': 'Fonctionne sur ton serveur openGym',+ 'Save and use the Coach': 'Enregistrer et utiliser le coach',+ 'The Coach is already thinking about your training.': 'Le coach réfléchit déjà à ton entraînement.',+ 'The Coach is resting — you have used today’s {0} runs on this phone.': 'Le coach se repose — tu as utilisé les {0} exécutions du jour sur ce téléphone.',+ 'The Coach isn’t set up on this phone.': 'Le coach n’est pas configuré sur ce téléphone.',+ 'The Coach needs your go-ahead first.': 'Le coach a d’abord besoin de ton accord.',+ 'The key is stored in this phone’s secure storage and never leaves it except to call the provider.': 'La clé est conservée dans le stockage sécurisé de ce téléphone et n’en sort que pour appeler le fournisseur.',+ 'This phone calls the provider directly with your key. Every request is charged to your account.': 'Ce téléphone appelle directement le fournisseur avec ta clé. Chaque requête est facturée sur ton compte.',+ 'Turn the Coach off on this phone': 'Désactiver le coach sur ce téléphone',+ 'Use my self-hosted openGym': 'Utiliser mon openGym auto-hébergé',+ 'What leaves this phone': 'Ce qui quitte ce téléphone',+ 'When you ask for a plan or a review, this phone sends the following straight to {0}, using your own API key. You pay for every request.': 'Quand tu demandes un plan ou une révision, ce téléphone envoie ce qui suit directement à {0}, avec ta propre clé API. Chaque requête est à ta charge.',+ 'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'Aucun coach n’est activé sur ton serveur — demande à son admin, ou utilise ta propre clé ci-dessous.',+ 'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'Ton serveur fait tourner le coach avec le fournisseur choisi par son admin. Rien de nouveau ne quitte ce téléphone au-delà de ce qui se synchronise déjà.',+ 'Loading the exercise catalogue…': 'Chargement du catalogue d’exercices…',+ 'Checking the endpoint…': 'Vérification du point d’accès…'}diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex 88b57562c..cc8f738d6 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -815,5 +815,40 @@ export default {'Add session note': 'सत्र का नोट जोड़ें','Edit session note': 'सत्र का नोट बदलें','How the session went as a whole.': 'पूरा सत्र कैसा रहा।',- 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'रेस्ट-पॉज़ हमेशा इसी रेप्स संख्या के एक वार्म-अप सेट और एक रेस्ट-पॉज़ वर्क सेट के रूप में किया जाता है — “सेट” का उपयोग नहीं होता।'+ 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'रेस्ट-पॉज़ हमेशा इसी रेप्स संख्या के एक वार्म-अप सेट और एक रेस्ट-पॉज़ वर्क सेट के रूप में किया जाता है — “सेट” का उपयोग नहीं होता।',++ // --- AI Coach on the phone ---+ '(saved)': '(सहेजी गई)',+ 'AI Coach': 'AI कोच',+ 'API key': 'API कुंजी',+ 'An AI coach that can design your plan and adjust it from what you actually log. It runs with your own API key, it never changes anything without your say-so, and it is off until you turn it on.': 'एक AI कोच जो आपकी योजना बनाता है और आपके वास्तविक रिकॉर्ड के आधार पर उसे समायोजित करता है। यह आपकी अपनी API कुंजी से चलता है, आपकी अनुमति के बिना कुछ नहीं बदलता, और जब तक आप इसे चालू न करें, बंद रहता है।',+ 'Bring my own API key': 'अपनी API कुंजी इस्तेमाल करें',+ 'Could not reach the provider: {0}': 'प्रदाता से संपर्क नहीं हो सका: {0}',+ 'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'हर अनुरोध आपकी कुंजी के साथ सीधे {0} को जाता है — कोई और इसे नहीं देखता, और भुगतान आप करते हैं।',+ 'Endpoint': 'एंडपॉइंट',+ 'Enter your API key': 'अपनी API कुंजी दर्ज करें',+ 'How should the Coach run?': 'कोच कैसे चले?',+ 'List models': 'मॉडल सूची',+ 'Model': 'मॉडल',+ 'Nothing to change right now: {0}': 'अभी कुछ बदलने की ज़रूरत नहीं: {0}',+ 'Off — choose how the Coach should run.': 'बंद — चुनें कि कोच कैसे चले।',+ 'Pick a model': 'एक मॉडल चुनें',+ 'Provider': 'प्रदाता',+ 'Runs on this phone with your own API key': 'इस फ़ोन पर आपकी अपनी API कुंजी से चलता है',+ 'Runs on your openGym server': 'आपके openGym सर्वर पर चलता है',+ 'Save and use the Coach': 'सहेजें और कोच का उपयोग करें',+ 'The Coach is already thinking about your training.': 'कोच पहले से ही आपके प्रशिक्षण पर सोच रहा है।',+ 'The Coach is resting — you have used today’s {0} runs on this phone.': 'कोच आराम कर रहा है — इस फ़ोन पर आज की {0} बार चलाने की सीमा पूरी हो गई।',+ 'The Coach isn’t set up on this phone.': 'इस फ़ोन पर कोच सेट नहीं है।',+ 'The Coach needs your go-ahead first.': 'कोच को पहले आपकी अनुमति चाहिए।',+ 'The key is stored in this phone’s secure storage and never leaves it except to call the provider.': 'कुंजी इस फ़ोन के सुरक्षित भंडारण में रहती है और प्रदाता को कॉल करने के अलावा कभी बाहर नहीं जाती।',+ 'This phone calls the provider directly with your key. Every request is charged to your account.': 'यह फ़ोन आपकी कुंजी से सीधे प्रदाता को कॉल करता है। हर अनुरोध का शुल्क आपके खाते से लिया जाता है।',+ 'Turn the Coach off on this phone': 'इस फ़ोन पर कोच बंद करें',+ 'Use my self-hosted openGym': 'मेरा सेल्फ़-होस्टेड openGym इस्तेमाल करें',+ 'What leaves this phone': 'इस फ़ोन से क्या बाहर जाता है',+ 'When you ask for a plan or a review, this phone sends the following straight to {0}, using your own API key. You pay for every request.': 'जब आप योजना या समीक्षा माँगते हैं, तो यह फ़ोन आपकी अपनी API कुंजी से निम्नलिखित सीधे {0} को भेजता है। हर अनुरोध का भुगतान आप करते हैं।',+ 'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'आपके सर्वर पर कोच सक्षम नहीं है — इसके एडमिन से पूछें, या नीचे अपनी कुंजी इस्तेमाल करें।',+ 'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'आपका सर्वर उस प्रदाता से कोच चलाता है जिसे उसके एडमिन ने सेट किया है। जो पहले से सिंक होता है उसके अलावा इस फ़ोन से कुछ नया बाहर नहीं जाता।',+ 'Loading the exercise catalogue…': 'व्यायाम सूची लोड हो रही है…',+ 'Checking the endpoint…': 'एंडपॉइंट जाँचा जा रहा है…'}diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex 2ff452eaf..ff32f20b9 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -815,5 +815,40 @@ export default {'Add session note': 'Aggiungi nota della sessione','Edit session note': 'Modifica nota della sessione','How the session went as a whole.': 'Com’è andata la sessione nel complesso.',- 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Il rest-pause si allena sempre come una serie di riscaldamento a queste ripetizioni e una serie di lavoro rest-pause — “Serie” non viene usato.'+ 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Il rest-pause si allena sempre come una serie di riscaldamento a queste ripetizioni e una serie di lavoro rest-pause — “Serie” non viene usato.',++ // --- AI Coach on the phone ---+ '(saved)': '(salvata)',+ 'AI Coach': 'Coach IA',+ 'API key': 'Chiave API',+ 'An AI coach that can design your plan and adjust it from what you actually log. It runs with your own API key, it never changes anything without your say-so, and it is off until you turn it on.': 'Un coach con IA che progetta il tuo piano e lo adatta in base a ciò che registri davvero. Funziona con la tua chiave API, non cambia mai nulla senza il tuo consenso ed è spento finché non lo accendi.',+ 'Bring my own API key': 'Usare la mia chiave API',+ 'Could not reach the provider: {0}': 'Impossibile raggiungere il provider: {0}',+ 'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Ogni richiesta va direttamente a {0} con la tua chiave: nessun altro la vede, e la paghi tu.',+ 'Endpoint': 'Endpoint',+ 'Enter your API key': 'Inserisci la tua chiave API',+ 'How should the Coach run?': 'Come deve funzionare il Coach?',+ 'List models': 'Elenca i modelli',+ 'Model': 'Modello',+ 'Nothing to change right now: {0}': 'Niente da cambiare per ora: {0}',+ 'Off — choose how the Coach should run.': 'Spento: scegli come deve funzionare il Coach.',+ 'Pick a model': 'Scegli un modello',+ 'Provider': 'Provider',+ 'Runs on this phone with your own API key': 'Funziona su questo telefono con la tua chiave API',+ 'Runs on your openGym server': 'Funziona sul tuo server openGym',+ 'Save and use the Coach': 'Salva e usa il Coach',+ 'The Coach is already thinking about your training.': 'Il Coach sta già pensando al tuo allenamento.',+ 'The Coach is resting — you have used today’s {0} runs on this phone.': 'Il Coach riposa: hai usato le {0} esecuzioni di oggi su questo telefono.',+ 'The Coach isn’t set up on this phone.': 'Il Coach non è configurato su questo telefono.',+ 'The Coach needs your go-ahead first.': 'Il Coach ha prima bisogno del tuo consenso.',+ 'The key is stored in this phone’s secure storage and never leaves it except to call the provider.': 'La chiave è conservata nell’archivio sicuro di questo telefono e non lo lascia mai, se non per chiamare il provider.',+ 'This phone calls the provider directly with your key. Every request is charged to your account.': 'Questo telefono chiama il provider direttamente con la tua chiave. Ogni richiesta viene addebitata al tuo account.',+ 'Turn the Coach off on this phone': 'Spegni il Coach su questo telefono',+ 'Use my self-hosted openGym': 'Usa il mio openGym self-hosted',+ 'What leaves this phone': 'Cosa lascia questo telefono',+ 'When you ask for a plan or a review, this phone sends the following straight to {0}, using your own API key. You pay for every request.': 'Quando chiedi un piano o una revisione, questo telefono invia quanto segue direttamente a {0}, con la tua chiave API. Ogni richiesta la paghi tu.',+ 'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'Il tuo server non ha il Coach attivo: chiedi all’amministratore, oppure usa la tua chiave qui sotto.',+ 'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'Il tuo server esegue il Coach con il provider impostato dal suo amministratore. Da questo telefono non esce nulla di nuovo oltre a ciò che già si sincronizza.',+ 'Loading the exercise catalogue…': 'Caricamento del catalogo esercizi…',+ 'Checking the endpoint…': 'Verifica dell’endpoint…'}diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex deb04d5ce..3f85216e4 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -815,5 +815,40 @@ export default {'Add session note': '운동 메모 추가','Edit session note': '운동 메모 편집','How the session went as a whole.': '이번 운동이 전체적으로 어땠는지.',- 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': '레스트포즈는 항상 이 횟수의 워밍업 세트 하나와 레스트포즈 작업 세트 하나로 진행됩니다 — ‘세트’는 사용하지 않습니다.'+ 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': '레스트포즈는 항상 이 횟수의 워밍업 세트 하나와 레스트포즈 작업 세트 하나로 진행됩니다 — ‘세트’는 사용하지 않습니다.',++ // --- AI Coach on the phone ---+ '(saved)': '(저장됨)',+ 'AI Coach': 'AI 코치',+ 'API key': 'API 키',+ 'An AI coach that can design your plan and adjust it from what you actually log. It runs with your own API key, it never changes anything without your say-so, and it is off until you turn it on.': '당신의 계획을 설계하고 실제 기록에 따라 조정하는 AI 코치입니다. 당신의 API 키로 실행되며, 동의 없이는 아무것도 바꾸지 않고, 켜기 전까지는 꺼져 있습니다.',+ 'Bring my own API key': '내 API 키 사용',+ 'Could not reach the provider: {0}': '제공자에 연결할 수 없습니다: {0}',+ 'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': '모든 요청은 당신의 키로 {0}에 바로 전송됩니다 — 다른 누구도 볼 수 없고, 비용은 당신이 냅니다.',+ 'Endpoint': '엔드포인트',+ 'Enter your API key': 'API 키를 입력하세요',+ 'How should the Coach run?': '코치를 어떻게 실행할까요?',+ 'List models': '모델 목록',+ 'Model': '모델',+ 'Nothing to change right now: {0}': '지금은 바꿀 것이 없습니다: {0}',+ 'Off — choose how the Coach should run.': '꺼짐 — 코치 실행 방식을 선택하세요.',+ 'Pick a model': '모델을 선택하세요',+ 'Provider': '제공자',+ 'Runs on this phone with your own API key': '이 휴대폰에서 내 API 키로 실행',+ 'Runs on your openGym server': '내 openGym 서버에서 실행',+ 'Save and use the Coach': '저장하고 코치 사용',+ 'The Coach is already thinking about your training.': '코치가 이미 당신의 훈련을 검토 중입니다.',+ 'The Coach is resting — you have used today’s {0} runs on this phone.': '코치가 쉬는 중입니다 — 이 휴대폰에서 오늘의 {0}회 실행을 모두 사용했습니다.',+ 'The Coach isn’t set up on this phone.': '이 휴대폰에는 코치가 설정되어 있지 않습니다.',+ 'The Coach needs your go-ahead first.': '먼저 코치에게 동의가 필요합니다.',+ 'The key is stored in this phone’s secure storage and never leaves it except to call the provider.': '키는 이 휴대폰의 보안 저장소에 보관되며 제공자를 호출할 때 외에는 절대 밖으로 나가지 않습니다.',+ 'This phone calls the provider directly with your key. Every request is charged to your account.': '이 휴대폰이 당신의 키로 제공자를 직접 호출합니다. 모든 요청은 당신의 계정에 청구됩니다.',+ 'Turn the Coach off on this phone': '이 휴대폰에서 코치 끄기',+ 'Use my self-hosted openGym': '내 자체 호스팅 openGym 사용',+ 'What leaves this phone': '이 휴대폰에서 나가는 것',+ 'When you ask for a plan or a review, this phone sends the following straight to {0}, using your own API key. You pay for every request.': '계획이나 검토를 요청하면 이 휴대폰이 당신의 API 키로 다음 내용을 {0}에 바로 보냅니다. 모든 요청의 비용은 당신이 냅니다.',+ 'Your server has no Coach enabled — ask its admin, or bring your own key below.': '서버에 코치가 활성화되어 있지 않습니다 — 관리자에게 문의하거나 아래에서 내 키를 사용하세요.',+ 'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': '서버가 관리자가 설정한 제공자로 코치를 실행합니다. 이미 동기화되는 것 외에는 이 휴대폰에서 새로 나가는 것이 없습니다.',+ 'Loading the exercise catalogue…': '운동 카탈로그 불러오는 중…',+ 'Checking the endpoint…': '엔드포인트 확인 중…'}diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex 481aedc4c..5fe7a2c08 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -815,5 +815,40 @@ export default {'Add session note': 'Dodaj notatkę do sesji','Edit session note': 'Edytuj notatkę do sesji','How the session went as a whole.': 'Jak przebiegła cała sesja.',- 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause zawsze trenuje się jako jedna seria rozgrzewkowa o tej liczbie powtórzeń i jedna seria robocza rest-pause — „Serie” nie są używane.'+ 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause zawsze trenuje się jako jedna seria rozgrzewkowa o tej liczbie powtórzeń i jedna seria robocza rest-pause — „Serie” nie są używane.',++ // --- AI Coach on the phone ---+ '(saved)': '(zapisany)',+ 'AI Coach': 'Trener AI',+ 'API key': 'Klucz API',+ 'An AI coach that can design your plan and adjust it from what you actually log. It runs with your own API key, it never changes anything without your say-so, and it is off until you turn it on.': 'Trener AI, który projektuje Twój plan i dostosowuje go do tego, co naprawdę zapisujesz. Działa z Twoim własnym kluczem API, nigdy nic nie zmienia bez Twojej zgody i jest wyłączony, dopóki go nie włączysz.',+ 'Bring my own API key': 'Użyj mojego klucza API',+ 'Could not reach the provider: {0}': 'Nie można połączyć się z dostawcą: {0}',+ 'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Każde zapytanie trafia prosto do {0} z Twoim kluczem — nikt inny go nie widzi, a płacisz Ty.',+ 'Endpoint': 'Endpoint',+ 'Enter your API key': 'Wpisz swój klucz API',+ 'How should the Coach run?': 'Jak ma działać trener?',+ 'List models': 'Pokaż modele',+ 'Model': 'Model',+ 'Nothing to change right now: {0}': 'Na razie nic do zmiany: {0}',+ 'Off — choose how the Coach should run.': 'Wyłączony — wybierz, jak ma działać trener.',+ 'Pick a model': 'Wybierz model',+ 'Provider': 'Dostawca',+ 'Runs on this phone with your own API key': 'Działa na tym telefonie z Twoim kluczem API',+ 'Runs on your openGym server': 'Działa na Twoim serwerze openGym',+ 'Save and use the Coach': 'Zapisz i używaj trenera',+ 'The Coach is already thinking about your training.': 'Trener już analizuje Twój trening.',+ 'The Coach is resting — you have used today’s {0} runs on this phone.': 'Trener odpoczywa — wykorzystano dzisiejsze {0} uruchomień na tym telefonie.',+ 'The Coach isn’t set up on this phone.': 'Trener nie jest skonfigurowany na tym telefonie.',+ 'The Coach needs your go-ahead first.': 'Trener potrzebuje najpierw Twojej zgody.',+ 'The key is stored in this phone’s secure storage and never leaves it except to call the provider.': 'Klucz jest przechowywany w bezpiecznej pamięci tego telefonu i opuszcza go tylko po to, by wywołać dostawcę.',+ 'This phone calls the provider directly with your key. Every request is charged to your account.': 'Ten telefon łączy się z dostawcą bezpośrednio z Twoim kluczem. Każde zapytanie obciąża Twoje konto.',+ 'Turn the Coach off on this phone': 'Wyłącz trenera na tym telefonie',+ 'Use my self-hosted openGym': 'Użyj mojego własnego openGym',+ 'What leaves this phone': 'Co opuszcza ten telefon',+ 'When you ask for a plan or a review, this phone sends the following straight to {0}, using your own API key. You pay for every request.': 'Gdy prosisz o plan lub przegląd, ten telefon wysyła poniższe dane prosto do {0}, z Twoim własnym kluczem API. Płacisz za każde zapytanie.',+ 'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'Twój serwer nie ma włączonego trenera — zapytaj administratora albo użyj własnego klucza poniżej.',+ 'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'Twój serwer uruchamia trenera z dostawcą ustawionym przez administratora. Z tego telefonu nie wychodzi nic nowego poza tym, co i tak jest synchronizowane.',+ 'Loading the exercise catalogue…': 'Wczytywanie katalogu ćwiczeń…',+ 'Checking the endpoint…': 'Sprawdzanie endpointu…'}diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex dba31daf1..f6a38d392 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -377,7 +377,36 @@ export const PT_BR_OVERRIDES = {'Undid the last changes': 'Desfez as últimas alterações','{0}: hold time': '{0}: tempo de isometria','Add routine “{0}”': 'Adicionar rotina “{0}”',- 'Rename routine to “{0}”': 'Renomear rotina para “{0}”'+ 'Rename routine to “{0}”': 'Renomear rotina para “{0}”',+ // --- AI Coach on the phone ---+ 'AI Coach': 'Treinador IA',+ 'Bring my own API key': 'Usar minha própria chave de API',+ 'An AI coach that can design your plan and adjust it from what you actually log. It runs with your own API key, it never changes anything without your say-so, and it is off until you turn it on.': 'Um treinador com IA que cria seu plano e o ajusta com base no que você registra. Roda com a sua própria chave de API, nunca muda nada sem a sua autorização e fica desligado até você ligá-lo.',+ 'Could not reach the provider: {0}': 'Não foi possível contatar o provedor: {0}',+ 'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Cada pedido vai direto para {0} com a sua chave — ninguém mais o vê, e é você quem paga.',+ 'Enter your API key': 'Digite sua chave de API',+ 'How should the Coach run?': 'Como o Treinador deve rodar?',+ 'Off — choose how the Coach should run.': 'Desligado — escolha como o Treinador deve rodar.',+ 'Pick a model': 'Escolha um modelo',+ 'Provider': 'Provedor',+ 'Runs on this phone with your own API key': 'Roda neste celular com a sua própria chave de API',+ 'Runs on your openGym server': 'Roda no seu servidor openGym',+ 'Save and use the Coach': 'Salvar e usar o Treinador',+ 'The Coach is already thinking about your training.': 'O Treinador já está pensando no seu treino.',+ 'The Coach is resting — you have used today’s {0} runs on this phone.': 'O Treinador está descansando — você já usou os {0} usos de hoje neste celular.',+ 'The Coach isn’t set up on this phone.': 'O Treinador não está configurado neste celular.',+ 'The Coach needs your go-ahead first.': 'O Treinador precisa primeiro da sua autorização.',+ 'The key is stored in this phone’s secure storage and never leaves it except to call the provider.': 'A chave fica no armazenamento seguro deste celular e só sai dele para chamar o provedor.',+ 'This phone calls the provider directly with your key. Every request is charged to your account.': 'Este celular chama o provedor diretamente com a sua chave. Cada pedido é cobrado na sua conta.',+ 'Turn the Coach off on this phone': 'Desligar o Treinador neste celular',+ 'Use my self-hosted openGym': 'Usar meu openGym self-hosted',+ 'What leaves this phone': 'O que sai deste celular',+ 'When you ask for a plan or a review, this phone sends the following straight to {0}, using your own API key. You pay for every request.': 'Quando você pede um plano ou uma revisão, este celular envia o seguinte direto para {0}, com a sua própria chave de API. Você paga cada pedido.',+ 'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'Seu servidor não tem o Treinador ativado — pergunte ao administrador, ou use sua própria chave abaixo.',+ 'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'Seu servidor roda o Treinador com o provedor que o administrador configurou. Nada de novo sai deste celular além do que já é sincronizado.',+ 'Loading the exercise catalogue…': 'Carregando o catálogo de exercícios…',+ 'Checking the endpoint…': 'Verificando o endpoint…',+ '(saved)': '(salva)'}export default { ...pt, ...PT_BR_OVERRIDES }diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex 2e328946e..4c6203a88 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -815,5 +815,40 @@ export default {'Add session note': 'Adicionar nota da sessão','Edit session note': 'Editar nota da sessão','How the session went as a whole.': 'Como correu a sessão no seu todo.',- 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'O rest-pause treina sempre como uma série de aquecimento com estas repetições e uma série de trabalho rest-pause — «Séries» não é usado.'+ 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'O rest-pause treina sempre como uma série de aquecimento com estas repetições e uma série de trabalho rest-pause — «Séries» não é usado.',++ // --- AI Coach on the phone ---+ '(saved)': '(guardada)',+ 'AI Coach': 'Treinador IA',+ 'API key': 'Chave de API',+ 'An AI coach that can design your plan and adjust it from what you actually log. It runs with your own API key, it never changes anything without your say-so, and it is off until you turn it on.': 'Um treinador com IA que cria o teu plano e o ajusta com base no que registas. Corre com a tua própria chave de API, nunca muda nada sem a tua autorização e está desligado até o ligares.',+ 'Bring my own API key': 'Usar a minha própria chave de API',+ 'Could not reach the provider: {0}': 'Não foi possível contactar o fornecedor: {0}',+ 'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Cada pedido vai diretamente para {0} com a tua chave — mais ninguém o vê, e és tu que pagas.',+ 'Endpoint': 'Endpoint',+ 'Enter your API key': 'Introduz a tua chave de API',+ 'How should the Coach run?': 'Como deve correr o Treinador?',+ 'List models': 'Listar modelos',+ 'Model': 'Modelo',+ 'Nothing to change right now: {0}': 'Nada a mudar por agora: {0}',+ 'Off — choose how the Coach should run.': 'Desligado — escolhe como o Treinador deve correr.',+ 'Pick a model': 'Escolhe um modelo',+ 'Provider': 'Fornecedor',+ 'Runs on this phone with your own API key': 'Corre neste telemóvel com a tua própria chave de API',+ 'Runs on your openGym server': 'Corre no teu servidor openGym',+ 'Save and use the Coach': 'Guardar e usar o Treinador',+ 'The Coach is already thinking about your training.': 'O Treinador já está a pensar no teu treino.',+ 'The Coach is resting — you have used today’s {0} runs on this phone.': 'O Treinador está a descansar — já usaste as {0} utilizações de hoje neste telemóvel.',+ 'The Coach isn’t set up on this phone.': 'O Treinador não está configurado neste telemóvel.',+ 'The Coach needs your go-ahead first.': 'O Treinador precisa primeiro da tua autorização.',+ 'The key is stored in this phone’s secure storage and never leaves it except to call the provider.': 'A chave fica no armazenamento seguro deste telemóvel e só sai dele para chamar o fornecedor.',+ 'This phone calls the provider directly with your key. Every request is charged to your account.': 'Este telemóvel chama o fornecedor diretamente com a tua chave. Cada pedido é cobrado na tua conta.',+ 'Turn the Coach off on this phone': 'Desligar o Treinador neste telemóvel',+ 'Use my self-hosted openGym': 'Usar o meu openGym self-hosted',+ 'What leaves this phone': 'O que sai deste telemóvel',+ 'When you ask for a plan or a review, this phone sends the following straight to {0}, using your own API key. You pay for every request.': 'Quando pedes um plano ou uma revisão, este telemóvel envia o seguinte diretamente para {0}, com a tua própria chave de API. Pagas cada pedido.',+ 'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'O teu servidor não tem o Treinador ativado — pergunta ao administrador, ou usa a tua própria chave abaixo.',+ 'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'O teu servidor corre o Treinador com o fornecedor que o administrador configurou. Nada de novo sai deste telemóvel para além do que já é sincronizado.',+ 'Loading the exercise catalogue…': 'A carregar o catálogo de exercícios…',+ 'Checking the endpoint…': 'A verificar o endpoint…'}diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex 65c9e930e..4456b785f 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -815,5 +815,40 @@ export default {'Add session note': 'Добавить заметку','Edit session note': 'Изменить заметку','How the session went as a whole.': 'Как прошла тренировка в целом.',- 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause всегда выполняется как один разминочный подход с этим числом повторений и один рабочий подход rest-pause — «Подходы» не используются.'+ 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause всегда выполняется как один разминочный подход с этим числом повторений и один рабочий подход rest-pause — «Подходы» не используются.',++ // --- AI Coach on the phone ---+ '(saved)': '(сохранён)',+ 'AI Coach': 'ИИ-тренер',+ 'API key': 'API-ключ',+ 'An AI coach that can design your plan and adjust it from what you actually log. It runs with your own API key, it never changes anything without your say-so, and it is off until you turn it on.': 'ИИ-тренер, который составляет план и корректирует его по тому, что вы реально записываете. Работает с вашим собственным API-ключом, ничего не меняет без вашего согласия и выключен, пока вы его не включите.',+ 'Bring my own API key': 'Использовать свой API-ключ',+ 'Could not reach the provider: {0}': 'Не удалось связаться с провайдером: {0}',+ 'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Каждый запрос уходит напрямую в {0} с вашим ключом — больше никто его не видит, и платите за него вы.',+ 'Endpoint': 'Эндпоинт',+ 'Enter your API key': 'Введите API-ключ',+ 'How should the Coach run?': 'Как должен работать тренер?',+ 'List models': 'Показать модели',+ 'Model': 'Модель',+ 'Nothing to change right now: {0}': 'Пока менять нечего: {0}',+ 'Off — choose how the Coach should run.': 'Выключен — выберите, как должен работать тренер.',+ 'Pick a model': 'Выберите модель',+ 'Provider': 'Провайдер',+ 'Runs on this phone with your own API key': 'Работает на этом телефоне с вашим API-ключом',+ 'Runs on your openGym server': 'Работает на вашем сервере openGym',+ 'Save and use the Coach': 'Сохранить и использовать тренера',+ 'The Coach is already thinking about your training.': 'Тренер уже думает над вашей тренировкой.',+ 'The Coach is resting — you have used today’s {0} runs on this phone.': 'Тренер отдыхает — на этом телефоне израсходованы {0} запусков на сегодня.',+ 'The Coach isn’t set up on this phone.': 'Тренер на этом телефоне не настроен.',+ 'The Coach needs your go-ahead first.': 'Сначала тренеру нужно ваше согласие.',+ 'The key is stored in this phone’s secure storage and never leaves it except to call the provider.': 'Ключ хранится в защищённом хранилище этого телефона и покидает его только для обращения к провайдеру.',+ 'This phone calls the provider directly with your key. Every request is charged to your account.': 'Этот телефон обращается к провайдеру напрямую с вашим ключом. Каждый запрос списывается с вашего счёта.',+ 'Turn the Coach off on this phone': 'Выключить тренера на этом телефоне',+ 'Use my self-hosted openGym': 'Использовать мой собственный openGym',+ 'What leaves this phone': 'Что уходит с этого телефона',+ 'When you ask for a plan or a review, this phone sends the following straight to {0}, using your own API key. You pay for every request.': 'Когда вы просите план или разбор, этот телефон отправляет следующее напрямую в {0} с вашим собственным API-ключом. Каждый запрос оплачиваете вы.',+ 'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'На вашем сервере тренер не включён — спросите администратора или используйте свой ключ ниже.',+ 'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'Ваш сервер запускает тренера с тем провайдером, которого настроил администратор. С этого телефона не уходит ничего нового сверх того, что и так синхронизируется.',+ 'Loading the exercise catalogue…': 'Загрузка каталога упражнений…',+ 'Checking the endpoint…': 'Проверка эндпоинта…'}diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex 74d361561..fd94aad28 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -815,5 +815,40 @@ export default {'Add session note': 'Antrenman notu ekle','Edit session note': 'Antrenman notunu düzenle','How the session went as a whole.': 'Antrenmanın genel olarak nasıl geçtiği.',- 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause her zaman bu tekrar sayısında bir ısınma seti ve bir rest-pause çalışma seti olarak çalışılır — “Setler” kullanılmaz.'+ 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause her zaman bu tekrar sayısında bir ısınma seti ve bir rest-pause çalışma seti olarak çalışılır — “Setler” kullanılmaz.',++ // --- AI Coach on the phone ---+ '(saved)': '(kaydedildi)',+ 'AI Coach': 'Yapay Zekâ Koçu',+ 'API key': 'API anahtarı',+ 'An AI coach that can design your plan and adjust it from what you actually log. It runs with your own API key, it never changes anything without your say-so, and it is off until you turn it on.': 'Planını tasarlayan ve gerçekten kaydettiklerine göre ayarlayan bir yapay zekâ koçu. Kendi API anahtarınla çalışır, onayın olmadan hiçbir şeyi değiştirmez ve sen açana kadar kapalıdır.',+ 'Bring my own API key': 'Kendi API anahtarımı kullan',+ 'Could not reach the provider: {0}': 'Sağlayıcıya ulaşılamadı: {0}',+ 'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Her istek anahtarınla doğrudan {0} adresine gider — başka kimse görmez ve ücretini sen ödersin.',+ 'Endpoint': 'Uç nokta',+ 'Enter your API key': 'API anahtarını gir',+ 'How should the Coach run?': 'Koç nasıl çalışsın?',+ 'List models': 'Modelleri listele',+ 'Model': 'Model',+ 'Nothing to change right now: {0}': 'Şu an değiştirilecek bir şey yok: {0}',+ 'Off — choose how the Coach should run.': 'Kapalı — koçun nasıl çalışacağını seç.',+ 'Pick a model': 'Bir model seç',+ 'Provider': 'Sağlayıcı',+ 'Runs on this phone with your own API key': 'Bu telefonda kendi API anahtarınla çalışır',+ 'Runs on your openGym server': 'openGym sunucunda çalışır',+ 'Save and use the Coach': 'Kaydet ve koçu kullan',+ 'The Coach is already thinking about your training.': 'Koç zaten antrenmanını düşünüyor.',+ 'The Coach is resting — you have used today’s {0} runs on this phone.': 'Koç dinleniyor — bu telefonda bugünkü {0} çalıştırmayı kullandın.',+ 'The Coach isn’t set up on this phone.': 'Koç bu telefonda kurulu değil.',+ 'The Coach needs your go-ahead first.': 'Koçun önce senin onayına ihtiyacı var.',+ 'The key is stored in this phone’s secure storage and never leaves it except to call the provider.': 'Anahtar bu telefonun güvenli deposunda saklanır ve yalnızca sağlayıcıyı çağırmak için dışarı çıkar.',+ 'This phone calls the provider directly with your key. Every request is charged to your account.': 'Bu telefon sağlayıcıyı doğrudan senin anahtarınla çağırır. Her istek senin hesabına yansır.',+ 'Turn the Coach off on this phone': 'Koçu bu telefonda kapat',+ 'Use my self-hosted openGym': 'Kendi openGym sunucumu kullan',+ 'What leaves this phone': 'Bu telefondan neler gider',+ 'When you ask for a plan or a review, this phone sends the following straight to {0}, using your own API key. You pay for every request.': 'Bir plan veya değerlendirme istediğinde bu telefon aşağıdakileri kendi API anahtarınla doğrudan {0} adresine gönderir. Her isteğin ücretini sen ödersin.',+ 'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'Sunucunda koç etkin değil — yöneticisine sor ya da aşağıda kendi anahtarını kullan.',+ 'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'Sunucun koçu yöneticisinin kurduğu sağlayıcıyla çalıştırır. Zaten eşitlenenler dışında bu telefondan yeni bir şey gitmez.',+ 'Loading the exercise catalogue…': 'Egzersiz kataloğu yükleniyor…',+ 'Checking the endpoint…': 'Uç nokta kontrol ediliyor…'}diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex c4a0c7138..49e69db94 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -815,5 +815,40 @@ export default {'Add session note': '添加训练备注','Edit session note': '编辑训练备注','How the session went as a whole.': '这次训练整体感觉如何。',- 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause 始终按这个次数练一个热身组,再加一个 rest-pause 正式组 —— 不使用“组数”。'+ 'Rest-pause always trains as one warm-up set at this rep count, then one rest-pause work set — "Sets" is not used.': 'Rest-pause 始终按这个次数练一个热身组,再加一个 rest-pause 正式组 —— 不使用“组数”。',++ // --- AI Coach on the phone ---+ '(saved)': '(已保存)',+ 'AI Coach': 'AI 教练',+ 'API key': 'API 密钥',+ 'An AI coach that can design your plan and adjust it from what you actually log. It runs with your own API key, it never changes anything without your say-so, and it is off until you turn it on.': '一个能为你设计计划并根据你实际记录进行调整的 AI 教练。它使用你自己的 API 密钥运行,未经你同意不会更改任何内容,并且在你开启之前保持关闭。',+ 'Bring my own API key': '使用我自己的 API 密钥',+ 'Could not reach the provider: {0}': '无法连接到提供商:{0}',+ 'Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': '每个请求都会用你的密钥直接发送到 {0}——其他人看不到,费用由你承担。',+ 'Endpoint': '端点',+ 'Enter your API key': '请输入你的 API 密钥',+ 'How should the Coach run?': '教练应如何运行?',+ 'List models': '列出模型',+ 'Model': '模型',+ 'Nothing to change right now: {0}': '目前无需更改:{0}',+ 'Off — choose how the Coach should run.': '已关闭——选择教练的运行方式。',+ 'Pick a model': '选择一个模型',+ 'Provider': '提供商',+ 'Runs on this phone with your own API key': '在此手机上使用你自己的 API 密钥运行',+ 'Runs on your openGym server': '在你的 openGym 服务器上运行',+ 'Save and use the Coach': '保存并使用教练',+ 'The Coach is already thinking about your training.': '教练已经在思考你的训练了。',+ 'The Coach is resting — you have used today’s {0} runs on this phone.': '教练正在休息——今天在这部手机上的 {0} 次运行已用完。',+ 'The Coach isn’t set up on this phone.': '此手机上尚未设置教练。',+ 'The Coach needs your go-ahead first.': '教练需要先获得你的同意。',+ 'The key is stored in this phone’s secure storage and never leaves it except to call the provider.': '密钥保存在此手机的安全存储中,除调用提供商外不会离开手机。',+ 'This phone calls the provider directly with your key. Every request is charged to your account.': '此手机使用你的密钥直接调用提供商。每个请求都会计入你的账户。',+ 'Turn the Coach off on this phone': '在此手机上关闭教练',+ 'Use my self-hosted openGym': '使用我自托管的 openGym',+ 'What leaves this phone': '哪些数据会离开此手机',+ 'When you ask for a plan or a review, this phone sends the following straight to {0}, using your own API key. You pay for every request.': '当你请求计划或评估时,此手机会使用你自己的 API 密钥将以下内容直接发送到 {0}。每个请求的费用由你承担。',+ 'Your server has no Coach enabled — ask its admin, or bring your own key below.': '你的服务器未启用教练——请联系管理员,或在下方使用你自己的密钥。',+ 'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': '你的服务器使用管理员设置的提供商运行教练。除了已同步的内容外,此手机不会发送任何新数据。',+ 'Loading the exercise catalogue…': '正在加载动作库…',+ 'Checking the endpoint…': '正在检查端点…'}diff --git a/frontend/src/store/useStore.js b/frontend/src/store/useStore.jsindex f6b73f61a..7a85ccdf3 100644--- a/frontend/src/store/useStore.js+++ b/frontend/src/store/useStore.js@@ -6,6 +6,7 @@ import { DEMO, DEMO_SEEDED } from '../lib/demo.js'import { guestAllowed } from '../lib/guest.js'import { MOBILE, nativeLoad, nativeSave, syncReminder, writeAutoBackup } from '../lib/mobile.js'import { loadRemote, chooseLocal, forgetRemote, connect } from '../lib/remote.js'+import { loadCoachDevice, saveCoachDevice, coachDeviceSettings } from '../lib/coach-device.js'const KEY = 'gym_state_v1'export const DEF = {@@ -98,6 +99,12 @@ export const useStore = create((set, get) => {always did, and a configured one is the only place any of it appears. */config: null,needsMobileOnboarding: false, // mobile build only — set true by boot() on a genuine first launch+ // Mobile build only: how the Coach runs on this phone — { mode: 'off'|'server'|'byok',+ // provider, model, baseUrl } from lib/coach-device.js. Never the key, never a proposal.+ coachLocal: null,+ async setCoachLocal(patch) {+ set({ coachLocal: coachDeviceSettings(await saveCoachDevice(patch)) })+ },// Mutate a draft of S via producer fn, then persist + schedule sync.update(mut, push = true) {@@ -211,6 +218,7 @@ export const useStore = create((set, get) => {// case it behaves exactly like the signed-in web flow below, straight from here.if (MOBILE) {const remote = await loadRemote()+ set({ coachLocal: coachDeviceSettings(await loadCoachDevice()) })if (remote?.mode === 'remote') {setRemoteAuth(remote.base, remote.token)try {diff --git a/frontend/src/views/Coach.jsx b/frontend/src/views/Coach.jsxindex d9340f4ff..5969ede22 100644--- a/frontend/src/views/Coach.jsx+++ b/frontend/src/views/Coach.jsx@@ -7,7 +7,7 @@ import { fmtDate } from '../lib/format.js'import { DEMO } from '../lib/demo.js'import { MOBILE } from '../lib/mobile.js'import {- coachAvailable, hasConsent, CONSENT_VERSION, emptyCoach,+ coachAvailable, hasConsent, CONSENT_VERSION, emptyCoach, CATEGORY_TEXT,canRevert, revertLast, changeTitle, recordDismissal} from '../lib/coach.js'import {@@ -23,21 +23,13 @@ import { Section, Row, Button, TextArea, Switch, SelectRow } from '../componentsconst GOALS = ['strength', 'muscle', 'general fitness', 'fat loss', 'endurance']-// Rendered from the same list the server builds payloads from (GET /api/coach/disclosure),-// so the promise on screen cannot drift from what actually leaves the box.-const CATEGORY_TEXT = {- plan: ['Your plan', 'Routines, exercises, sets and reps, your weekly schedule and progression settings.'],- training: ['Your logged training', 'Sets you logged in the review window — weights, reps, times, effort ratings and how long sessions took.'],- bodyweight: ['Body weight', 'Weigh-ins from the same window, and your goal weight if you set one.'],- profile: ['What you tell the Coach', 'Your intake answers, including any limitations or injuries you describe.'],- prefs: ['A few preferences', 'Your unit, your language and which effort scale you log.']-}export default function Coach() {const nav = useNavigate()const S = useStore(s => s.S)const user = useStore(s => s.user)const config = useStore(s => s.config)+ const coachMode = useStore(s => s.coachLocal?.mode)const update = useStore(s => s.update)const toast = useUI(s => s.toast)const [note, setNote] = useState('')@@ -46,8 +38,8 @@ export default function Coach() {// Gating lives in one predicate; if the instance isn't offering the Coach this route simply// isn't a place you can be.- useEffect(() => { if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE })) nav('/home', { replace: true }) }, [config, user])- if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE })) return null+ useEffect(() => { if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE, coachMode })) nav('/home', { replace: true }) }, [config, user, coachMode])+ if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE, coachMode })) return nullconst consented = hasConsent(S)const coach = S.coach || emptyCoach()@@ -162,8 +154,10 @@ function ConsentCard({ onDone }) {const open = () => openSheet(close => <><h3>{t('Before the Coach starts')}</h3><div className="muted small" style={{ lineHeight: 1.5, marginBottom: 12 }}>- {t('When you ask for a plan or a review, this instance sends the following to {0}, running on this server under the instance owner’s account.',- info?.providerLabel || config?.coach?.providerLabel || t('the configured AI provider'))}+ {info?.payer === 'you'+ ? t('When you ask for a plan or a review, this phone sends the following straight to {0}, using your own API key. You pay for every request.', info.host || info.providerLabel)+ : t('When you ask for a plan or a review, this instance sends the following to {0}, running on this server under the instance owner’s account.',+ info?.providerLabel || config?.coach?.providerLabel || t('the configured AI provider'))}</div><div className="sect-b">{(info?.categories || Object.keys(CATEGORY_TEXT)).map(k => {@@ -192,7 +186,9 @@ function ConsentCard({ onDone }) {<div className="big" style={{ fontSize: 20 }}>{t('Meet the Coach')}</div></div><div className="muted small" style={{ marginBottom: 12, lineHeight: 1.5 }}>- {t('An AI coach that can design your plan and adjust it from what you actually log. It runs on this server, it never changes anything without your say-so, and it is off until you turn it on.')}+ {info?.payer === 'you'+ ? t('An AI coach that can design your plan and adjust it from what you actually log. It runs with your own API key, it never changes anything without your say-so, and it is off until you turn it on.')+ : t('An AI coach that can design your plan and adjust it from what you actually log. It runs on this server, it never changes anything without your say-so, and it is off until you turn it on.')}</div><Button variant="primary" icon="sparkles" onClick={open}>{t('See what it would use')}</Button></div>diff --git a/frontend/src/views/CoachIntake.jsx b/frontend/src/views/CoachIntake.jsxindex 6d300cf5a..ea34c68e9 100644--- a/frontend/src/views/CoachIntake.jsx+++ b/frontend/src/views/CoachIntake.jsx@@ -47,6 +47,7 @@ export default function CoachIntake() {const S = useStore(s => s.S)const user = useStore(s => s.user)const config = useStore(s => s.config)+ const coachMode = useStore(s => s.coachLocal?.mode)const update = useStore(s => s.update)const toast = useUI(s => s.toast)const [step, setStep] = useState(0)@@ -58,7 +59,7 @@ export default function CoachIntake() {}))const set = patch => setP(v => ({ ...v, ...patch }))- if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE })) { nav('/home', { replace: true }); return null }+ if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE, coachMode })) { nav('/home', { replace: true }); return null }const key = STEPS[step]const canNext = key !== 'goal' || (p.goal && p.experience)diff --git a/frontend/src/views/CoachProposal.jsx b/frontend/src/views/CoachProposal.jsxindex f7d0cdf5a..f84b4df25 100644--- a/frontend/src/views/CoachProposal.jsx+++ b/frontend/src/views/CoachProposal.jsx@@ -30,11 +30,12 @@ export default function CoachProposal() {const S = useStore(s => s.S)const user = useStore(s => s.user)const config = useStore(s => s.config)+ const coachMode = useStore(s => s.coachLocal?.mode)const update = useStore(s => s.update)const toast = useUI(s => s.toast)const { pending, loading, refresh } = useCoachStatus(true)- useEffect(() => { if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE })) nav('/home', { replace: true }) }, [config, user])+ useEffect(() => { if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE, coachMode })) nav('/home', { replace: true }) }, [config, user])useEffect(() => { if (!loading && !pending) nav('/coach', { replace: true }) }, [loading, pending])if (!pending) return nulldiff --git a/frontend/src/views/CoachSetup.jsx b/frontend/src/views/CoachSetup.jsxnew file mode 100644index 000000000..ab8218737--- /dev/null+++ b/frontend/src/views/CoachSetup.jsx@@ -0,0 +1,188 @@+// Mobile build only: how the Coach should run on this phone.+//+// Two answers. "Use my self-hosted openGym" hands the whole thing to the paired server — the+// same Coach the web app has, with whatever provider its admin configured; the phone only has+// to be paired. "Bring my own API key" runs the pipeline on the phone against Anthropic,+// OpenAI, Gemini or an OpenAI-compatible endpoint, with a key that stays in secure storage.+//+// The promise this screen keeps: nothing AI-shaped is loaded until a mode is chosen. Its only+// imports from the Coach core are the provider table and the five category names — the+// catalogue, the prompts and the validator arrive through one dynamic import, behind a+// progress line that reports real steps rather than a pretend byte counter.+import { useEffect, useState } from 'react'+import { useNavigate } from 'react-router-dom'+import { useStore } from '../store/useStore.js'+import { useUI } from '../store/useUI.js'+import { t } from '../lib/i18n.js'+import { MOBILE } from '../lib/mobile.js'+import { CATEGORY_TEXT } from '../lib/coach.js'+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 Icon from '../components/Icon.jsx'+import { Section, Row, Button, TextField } from '../components/ui.jsx'++const STEPS = ['Loading the exercise catalogue…', 'Checking the endpoint…', 'Ready']++export default function CoachSetup() {+ const nav = useNavigate()+ const user = useStore(s => s.user)+ const config = useStore(s => s.config)+ const coachLocal = useStore(s => s.coachLocal)+ const setCoachLocal = useStore(s => s.setCoachLocal)+ const toast = useUI(s => s.toast)+ const openSheet = useUI(s => s.openSheet)++ const [choice, setChoice] = useState(null) // 'server' | 'byok' | null+ const [provider, setProvider] = useState(coachLocal?.provider || 'anthropic')+ const [baseUrl, setBaseUrl] = useState(coachLocal?.baseUrl || '')+ const [model, setModel] = useState(coachLocal?.model || '')+ const [key, setKey] = useState('')+ const [hasKey, setHasKey] = useState(false)+ const [models, setModels] = useState(null)+ const [step, setStep] = useState(-1) // -1 idle, 0..2 running, 3 done+ const [busy, setBusy] = useState(false)++ useEffect(() => { if (!MOBILE) nav('/settings', { replace: true }) }, [])+ useEffect(() => { getApiKey().then(k => setHasKey(!!k)) }, [])+ useEffect(() => { setModels(null); setModel(coachLocal?.provider === provider ? (coachLocal?.model || '') : '') }, [provider])++ const meta = HTTP_PROVIDERS[provider] || {}+ const host = hostOf(baseUrlFor(provider, { providerOptions: { [provider]: { baseUrl } } }))+ const serverHasCoach = !!(user && config?.coach?.enabled)++ const useServer = async () => {+ if (!user) return openSheet(close => <ConnectSheet close={close} />)+ await setCoachLocal({ mode: 'server' })+ toast(t('The Coach is on'))+ nav('/coach')+ }++ // The lazy load, and the reachability check, as three real steps.+ const prepare = async () => {+ const v = validateBaseUrl(meta.baseUrl ? baseUrl : '')+ if (!v.ok) return toast(v.error)+ if (!meta.keyOptional && !key.trim() && !hasKey) return toast(t('Enter your API key'))+ setBusy(true); setStep(0)+ try {+ const local = await import('../lib/coach-local.js')+ setStep(1)+ const k = key.trim() || await getApiKey()+ const r = await local.localModels({ provider, baseUrl: v.value }, k)+ if (!r.ok) { setStep(-1); toast(t('Could not reach the provider: {0}', r.error)); return }+ setModels(r.models)+ setStep(2)+ if (!model && meta.defaultModel && r.models.includes(meta.defaultModel)) setModel(meta.defaultModel)+ } catch (e) {+ setStep(-1); toast(e.message || t('Could not connect'))+ } finally { setBusy(false) }+ }++ const save = async () => {+ const chosen = model || meta.defaultModel+ if (!chosen) return toast(t('Pick a model'))+ setBusy(true)+ try {+ if (key.trim()) { await setApiKey(key.trim()); setHasKey(true); setKey('') }+ await setCoachLocal({ mode: 'byok', provider, model: chosen, baseUrl: meta.baseUrl ? (validateBaseUrl(baseUrl).value || null) : null })+ toast(t('The Coach is on'))+ nav('/coach')+ } finally { setBusy(false) }+ }++ const turnOff = async () => {+ await clearApiKey(); setHasKey(false)+ await setCoachLocal({ mode: 'off' })+ const local = await import('../lib/coach-local.js').catch(() => null)+ if (local) await local.localForget()+ setChoice(null)+ toast(t('The Coach is off'))+ }++ const current = coachLocal?.mode === 'server' ? t('Runs on your openGym server')+ : coachLocal?.mode === 'byok' ? t('Runs on this phone with your own API key')+ : t('Off — choose how the Coach should run.')++ return <div className="narrow">+ <div className="hdr">+ <button className="iconbtn" onClick={() => nav('/settings')} aria-label={t('Back')}><Icon name="chevronLeft" /></button>+ <div style={{ flex: 1, marginLeft: 10 }}><h1>{t('AI Coach')}</h1></div>+ </div>++ <Section title={t('How should the Coach run?')} footer={current}>+ <Row icon="rocket" iconTint="var(--indigo)" title={t('Use my self-hosted openGym')}+ subtitle={user ? (serverHasCoach ? t('Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.') : t('Your server has no Coach enabled — ask its admin, or bring your own key below.')) : t('Connect to my server')}+ accessory="chevron" onClick={() => { if (!user || serverHasCoach) useServer(); else setChoice('server') }} />+ <Row icon="key" iconTint="var(--acc)" title={t('Bring my own API key')}+ subtitle={t('This phone calls the provider directly with your key. Every request is charged to your account.')}+ accessory="chevron" onClick={() => setChoice('byok')} />+ </Section>++ {choice === 'server' && !serverHasCoach && <div className="card">+ <div className="muted small">{t('Your server has no Coach enabled — ask its admin, or bring your own key below.')}</div>+ </div>}++ {choice === 'byok' && <>+ <Section title={t('Provider')}>+ <div className="row" style={{ flexWrap: 'wrap', gap: 7, padding: '8px 12px' }}>+ {HTTP_PROVIDER_IDS.map(id => <button key={id} className={'chip' + (id === provider ? ' on' : '')} disabled={busy}+ onClick={() => setProvider(id)}>{HTTP_PROVIDERS[id].label}</button>)}+ </div>+ </Section>++ {meta.baseUrl && <Section title={t('Endpoint')}>+ <div style={{ padding: '8px 12px' }}>+ <TextField value={baseUrl} placeholder="http://ollama.lan:11434" inputMode="url" autoCapitalize="none" autoCorrect="off"+ onChange={e => setBaseUrl(e.target.value)} />+ </div>+ </Section>}++ <Section title={t('API key')} footer={t('The key is stored in this phone’s secure storage and never leaves it except to call the provider.')}>+ <div style={{ padding: '8px 12px' }}>+ <TextField value={key} type="password" placeholder={hasKey ? '•••••••• ' + t('(saved)') : (meta.keyPlaceholder || 'sk-…')} autoCapitalize="none" autoCorrect="off"+ onChange={e => setKey(e.target.value)} />+ </div>+ </Section>++ <Section title={t('What leaves this phone')}>+ {DATA_CATEGORIES.map(k => {+ const [title, sub] = CATEGORY_TEXT[k] || [k, '']+ return <Row key={k} icon="check" iconTint="var(--acc)" title={t(title)} subtitle={t(sub)} />+ })}+ </Section>+ <p className="sect-f" style={{ marginTop: -18, marginBottom: 22, lineHeight: 1.5 }}>+ {t('Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.', host || meta.label)}+ </p>++ {step >= 0 && <div className="card">+ {STEPS.map((s, i) => <div key={s} className="row" style={{ gap: 8, padding: '3px 0', opacity: i > step ? .4 : 1 }}>+ <span style={{ color: i < step || step === 2 ? 'var(--green)' : i === step ? 'var(--acc)' : 'var(--dim)' }}><Icon name={i < step || step === 2 ? 'check' : 'timer'} /></span>+ <span className="small">{t(s)}</span>+ </div>)}+ </div>}++ {models && <Section title={t('Model')}>+ <div style={{ padding: '8px 12px' }}>+ <select className="input" value={model} disabled={busy} onChange={e => setModel(e.target.value)} style={{ width: '100%' }}>+ <option value="">{meta.defaultModel ? `(${meta.defaultModel})` : t('Pick a model')}</option>+ {models.map(m => <option key={m} value={m}>{m}</option>)}+ </select>+ </div>+ </Section>}++ <div className="row" style={{ gap: 8, flexWrap: 'wrap' }}>+ {!models+ ? <Button variant="primary" icon="sparkles" disabled={busy} onClick={prepare}>{t('List models')}</Button>+ : <Button variant="primary" icon="check" disabled={busy} onClick={save}>{t('Save and use the Coach')}</Button>}+ {models && <Button disabled={busy} onClick={prepare}>{t('List models')}</Button>}+ </div>+ </>}++ {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>}+ </div>+}++const hostOf = url => { try { return new URL(url).host } catch { return '' } }diff --git a/frontend/src/views/CoachSetup.test.jsx b/frontend/src/views/CoachSetup.test.jsxnew file mode 100644index 000000000..4cb583be7--- /dev/null+++ b/frontend/src/views/CoachSetup.test.jsx@@ -0,0 +1,25 @@+// The setup screen's one promise that is easy to break by accident: nothing AI-shaped loads+// until a mode is chosen. Asserted on the source, the way coach.test.js pins the store field —+// a static import of the core here would pass every behavioural test and still ship the+// catalogue, the prompts and the validator to a phone that never asked for a Coach.+import { describe, it, expect } from 'vitest'+import { readFileSync } from 'node:fs'++const src = readFileSync(new URL('./CoachSetup.jsx', import.meta.url), 'utf8')+const statics = [...src.matchAll(/^import .* from '([^']+)'/gm)].map(m => m[1])++describe('CoachSetup keeps the core out until a mode is chosen', () => {+ it('imports only the provider table and the category names from the core', () => {+ const core = statics.filter(p => p.includes('api/coach/core'))+ expect(core.sort()).toEqual(['../../../api/coach/core/categories.js', '../../../api/coach/core/providers.js'])+ })+ it('never statically imports the phone pipeline', () => {+ expect(statics.some(p => p.includes('coach-local'))).toBe(false)+ expect(src).toMatch(/import\('\.\.\/lib\/coach-local\.js'\)/)+ })+ it('the categories module carries no catalogue', () => {+ const cat = readFileSync(new URL('../../../api/coach/core/categories.js', import.meta.url), 'utf8')+ expect(cat).not.toMatch(/^import /m)+ expect(cat.length).toBeLessThan(1500)+ })+})diff --git a/frontend/src/views/Plan.jsx b/frontend/src/views/Plan.jsxindex e2b955daa..a429d240e 100644--- a/frontend/src/views/Plan.jsx+++ b/frontend/src/views/Plan.jsx@@ -15,13 +15,14 @@ export default function Plan() {const S = useStore(s => s.S)const update = useStore(s => s.update)const config = useStore(s => s.config)+ const coachMode = useStore(s => s.coachLocal?.mode)const user = useStore(s => s.user)/* The Coach's only entry point in the app. Its screens have existed since the UI landed andnothing linked to them, so the feature was reachable only by typing the URL — enabled,configured, and invisible. The same predicate every other Coach surface uses gates it, soan instance without the feature sees exactly the Plan screen it saw before. */- const showCoach = coachAvailable(config, user, { demo: DEMO, mobile: MOBILE })+ const showCoach = coachAvailable(config, user, { demo: DEMO, mobile: MOBILE, coachMode })const addRoutine = () => {const r = { id: uid(), name: t('New routine'), emoji: DEFAULT_GLYPH, ex: [] }diff --git a/frontend/src/views/Settings.jsx b/frontend/src/views/Settings.jsxindex 2f4c0a4c4..b063582b8 100644--- a/frontend/src/views/Settings.jsx+++ b/frontend/src/views/Settings.jsx@@ -19,6 +19,7 @@ export default function Settings() {const nav = useNavigate()const S = useStore(s => s.S)const user = useStore(s => s.user)+ const coachLocal = useStore(s => s.coachLocal)const { update, replaceState, setUser, pullState, pushState, signOut, signOutAll, resetDemo, disconnectServer } = useStore()const toast = useUI(s => s.toast)const fileRef = useRef(null)@@ -110,6 +111,13 @@ export default function Settings() {</Section>{!user && !DEMO && !MOBILE && <p className="sect-f" style={{ marginTop: -18, marginBottom: 22 }}>{t('Guest mode — data lives only in this browser.')}</p>}+ {/* ---------- the Coach on a phone: through the paired server, or with the user's own key ---------- */}+ {MOBILE && <Section title={t('AI Coach')}>+ <Row icon="sparkles" iconTint="var(--acc)" title={t('AI Coach')} accessory="chevron"+ subtitle={coachLocal?.mode === 'server' ? t('Runs on your openGym server') : coachLocal?.mode === 'byok' ? t('Runs on this phone with your own API key') : t('Off — choose how the Coach should run.')}+ onClick={() => nav('/coach/setup')} />+ </Section>}+{/* ---------- general ---------- */}<Section title={t('General')} footer={t('Note: switching units only changes the label — logged numbers are not converted.')}><SelectRow