Coach auf dem Handy: ueber den gepaarten Server, oder mit eigenem API-Key

Einstellungen → KI-Coach hat zwei Antworten. Ein gepaartes Handy ist ein normales
Profil und nimmt die Web-Regel — der Server rechnet mit dem Provider, den sein Admin
eingerichtet hat. Ein Handy mit eigenem Key laesst dieselbe Pipeline (api/coach/core)
lokal laufen: Payload, Prompt, HTTPS-Adapter, Parser, Validator, eine Reparaturrunde;
der Key liegt im sicheren Speicher (Keychain/Keystore), nie in S. Nichts davon wird
geladen, bevor ein Modus gewaehlt ist — coach-local ist ein eigener Lazy-Chunk (156 KB),
und CoachSetup importiert aus dem Kern nur die Provider-Tabelle und fuenf Kategorienamen.
Provider-Aufrufe gehen ueber CapacitorHttp statt durch die WebView (kein CORS), und
zwar als expliziter Shim, damit die api()-Aufrufe eines gepaarten Handys unberuehrt
bleiben. Ein lokales Tageslimit, weil hier der Nutzer zahlt. 33 neue Strings in
zwoelf Packs.
This commit is contained in:
Duarte Santos committed 2026-08-29 17:28:02 +02:00
1 parent 7047346da1
commit 1986a507b0
35 files changed
+1254 -56

No files matched your search

+43
View File
@@ -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 })
})
}
+31 -8
View File
@@ -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 live
const IDLE_MS = 60000 // a Coach screen is open but nothing is running
@@ -21,13 +24,32 @@ let demoMod = null
const 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 is
that 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() : a
they 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 never
read back, so there is deliberately no "show me the current credential" call to pair with it. */
+37
View File
@@ -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 }
+165
View File
@@ -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 }
+181
View File
@@ -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'])
})
})
+43
View File
@@ -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)
}
+19 -4
View File
@@ -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 ============================ */
+12 -2
View File
@@ -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', () => {
+16
View File
@@ -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')
+3 -3
View File
@@ -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', () => {