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

+11 -15
View File
@@ -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 '../components
const 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 null
const 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>
+2 -1
View File
@@ -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)
+2 -1
View File
@@ -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 null
+188
View File
@@ -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 '' } }
+25
View File
@@ -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)
})
})
+2 -1
View File
@@ -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 and
nothing 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, so
an 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: [] }
+8
View File
@@ -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