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
// 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 { coachLimits, clampCoachLimit, COACH_LIMITS } from '../lib/coach-device.js'
import { HTTP_PROVIDERS, HTTP_PROVIDER_IDS, baseUrlFor, validateBaseUrl } from '../../../api/coach/core/providers.js'
import { DATA_CATEGORIES } from '../../../api/coach/core/categories.js'
import { ConnectSheet } from './MobileOnboarding.jsx'
import { AiConsentSection } from '../components/CoachConsentSheet.jsx'
import Icon from '../components/Icon.jsx'
import { Section, Row, Button, TextField } from '../components/ui.jsx'
// Literal t() calls, so check-source-strings sees the three lines; t(s) over a list of keys hid them.
const STEPS = () => [t('Loading the exercise catalogue…'), t('Checking the endpoint…'), t('Ready')]
// The phone calls the provider through CapacitorHttp, native networking that obeys the
// platform's cleartext rule, and Android refuses unencrypted http:// from apps
// (network_security_config.xml leaves it at the default, off). An http:// endpoint on the LAN
// therefore failed as a bare "could not reach the provider", with nothing to say why. It is
// refused up front with the two ways that work: HTTPS in front of the model, or the server's
// Coach, which has no such rule and reaches http:// on its own network.
const isCleartext = url => /^http:\/\//i.test(String(url || '').trim())
const cleartextRefused = () => t('Android blocks unencrypted http:// connections from apps, so this phone can only reach an https:// endpoint. Put HTTPS in front of it (Tailscale or a reverse proxy), or choose “Use my self-hosted openGym”: your server can reach an http:// model on its own network.')
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 refreshConfig = useStore(s => s.refreshConfig)
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)
// The three dials the server's admin card has and the phone never did (issue #527). Read from
// the device file as clamped, effective values; kept in local state so a number can be typed
// freely and is only clamped and saved when the field is left.
const [limits, setLimits] = useState(() => coachLimits(coachLocal))
useEffect(() => { if (!MOBILE) nav('/settings', { replace: true }) }, [])
useEffect(() => { getApiKey().then(k => setHasKey(!!k)) }, [])
// Ask the paired server afresh: the admin may have switched the Coach on since this phone booted.
useEffect(() => { if (user) refreshConfig() }, [user])
useEffect(() => { setModels(null); setModel(coachLocal?.provider === provider ? (coachLocal?.model || '') : '') }, [provider])
useEffect(() => { setLimits(coachLimits(coachLocal)) }, [coachLocal])
const editLimit = (k, raw) => setLimits(l => ({ ...l, [k]: raw }))
const commitLimit = k => {
const clamped = clampCoachLimit(k, limits[k])
setLimits(l => ({ ...l, [k]: clamped }))
setCoachLocal({ limits: { ...limits, [k]: clamped } })
}
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)
// An empty field passes the validator on purpose: for a provider with a fixed endpoint,
// empty means the default. This one has no default, so empty is nowhere to call.
if (meta.baseUrl && !meta.defaultBase && !v.value) return toast(t('Enter the endpoint URL'))
if (isCleartext(v.value)) return toast(cleartextRefused())
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 () => {
// The same check "List models" makes. The endpoint field stays editable after a successful
// listing, and taking `.value` off an unchecked result turned a typo into `baseUrl: null` —
// saved, "The Coach is on", and the phone pointed at nothing.
const v = validateBaseUrl(meta.baseUrl ? baseUrl : '')
if (!v.ok) return toast(v.error)
if (meta.baseUrl && !meta.defaultBase && !v.value) return toast(t('Enter the endpoint URL'))
const chosen = model || meta.defaultModel
if (!chosen) return toast(t('Pick a model'))
// The endpoint can still be edited after the models were listed.
if (isCleartext(v.value)) return toast(cleartextRefused())
setBusy(true)
try {
// The mode first, the key second: the settings file is the cheap, reliable write, the
// key goes through the platform's secure store, which is the step that can misbehave.
// Either way the user hears what happened instead of watching a greyed-out button (#42).
await setCoachLocal({ mode: 'byok', provider, model: chosen, baseUrl: meta.baseUrl ? v.value : null })
if (key.trim()) { await setApiKey(key.trim()); setHasKey(true); setKey('') }
toast(t('The Coach is on'))
nav('/coach')
} catch (e) {
toast(e?.message || t('Could not connect'))
} 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" data-back="/settings" onClick={() => nav('/settings')} aria-label={t('Back')}><Icon name="chevronLeft" /></button>
<div style={{ flex: 1, marginInlineStart: 12 }}><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.') : config == null ? t('Loading…') : 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')}
footer={isCleartext(baseUrl) ? <span style={{ color: 'var(--red)' }}>{cleartextRefused()}</span> : null}>
<div style={{ padding: '8px 12px' }}>
<TextField value={baseUrl} placeholder="https://ollama.example.com" 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={title} subtitle={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' : 'hourglass'} /></span>
<span className="small">{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>}
{/* The server's admin card, for the person who owns this phone: in BYOK mode there is no
other profile, so the limits protect nobody but the account already holding the key. */}
<Section title={t('Advanced')}>
<LimitRow label={t('Max output tokens')} hint={t('The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.')}
value={limits.maxOutputTokens} min={COACH_LIMITS.maxOutputTokens.min} max={COACH_LIMITS.maxOutputTokens.max}
onChange={v => editLimit('maxOutputTokens', v)} onCommit={() => commitLimit('maxOutputTokens')} />
<LimitRow label={t('Daily runs')} hint={t('Every Coach run is one request on your provider account. 0 means no limit.')}
value={limits.daily} min={COACH_LIMITS.daily.min} max={COACH_LIMITS.daily.max}
onChange={v => editLimit('daily', v)} onCommit={() => commitLimit('daily')} />
<LimitRow label={t('Max message length')} hint={t('How long a message, refinement or review note can be.')}
value={limits.maxMessageLen} min={COACH_LIMITS.maxMessageLen.min} max={COACH_LIMITS.maxMessageLen.max}
onChange={v => editLimit('maxMessageLen', v)} onCommit={() => commitLimit('maxMessageLen')} />
</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' && <AiConsentSection />}
{coachLocal?.mode && coachLocal.mode !== 'off' && <Section title={t('Controls')}>
<Row icon="signOut" iconTint="var(--red)" title={t('Turn the Coach off on this phone')} danger onClick={turnOff} />
</Section>}
</div>
}
const hostOf = url => { try { return new URL(url).host } catch { return '' } }
// One numeric dial of the Advanced section: a label and its hint on the left, a plain number
// field on the right, clamped and saved when it is left rather than on every keystroke — a
// floor applied mid-typing turns a just-typed "1" into "1024".
function LimitRow({ label, hint, value, min, max, onChange, onCommit }) {
return <div className="row between" style={{ gap: 12, padding: '10px 12px', alignItems: 'flex-start' }}>
<div style={{ minWidth: 0 }}>
<div style={{ fontWeight: 500 }}>{label}</div>
<div className="muted small">{hint}</div>
</div>
<div style={{ width: 118, flex: 'none' }}>
<TextField type="number" inputMode="numeric" min={min} max={max} value={value}
onChange={e => onChange(e.target.value)} onBlur={onCommit} />
</div>
</div>
}