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: the admin sees it as soon as it is on, the docs say where it lives, and the phone says why an http:// endpoint cannot work
Duarte Santos7883a054117e
diff --git a/docs/AI_COACH.md b/docs/AI_COACH.mdindex f005d7850..cd89cf09e 100644--- a/docs/AI_COACH.md+++ b/docs/AI_COACH.md@@ -30,13 +30,38 @@ child process to drop privileges on, no runtime to carry in the image, and nothiA model on your own LAN is the compatible endpoint with no key: point it at`http://ollama.lan:11434` and pick a model from the list it serves. That is the whole-configuration.+configuration. (On the server, that is. The phone app's own-key Coach needs `https://`; see+[On the phone](#on-the-phone).)## Turning it onNothing here is an environment variable or a restart — the whole point of the admin card is thatenabling the Coach is a decision you make in the app.+### Where people find it++The Coach has one door: a **Coach** card at the top of the **Plan** tab (*Plan design and+reviews, from your own training*), which opens the chat. The phone app also has+**Settings → AI Coach**, where the phone chooses between your server's Coach and a key of its+own (see [On the phone](#on-the-phone)).++The card appears only when all of these hold:++- **The master switch is on.** That is **Set up the Coach** on the admin card+ (**Settings → Admin → AI Coach**), and afterwards the toggle at the top of the same card. A+ provider that is connected and passes **Test the Coach** is not enough on its own: with the+ switch off, the server tells every app there is no Coach, and the card reads *Off right+ now — nobody sees it anywhere in the app*.+- **The provider is connected**, so the admin card reads **ready**: a credential saved, or for+ a compatible endpoint without a key, an endpoint.+- **The person is signed in.** A guest in the browser has no Coach, because a job reads a+ profile's synced data.+- **`COACH_DISABLED` is not set** in the server's environment (see+ [Off is really off](#off-is-really-off)).++The admin's own app shows the change as soon as the admin card saves it. Everyone else's app+picks it up the next time it is opened or reloaded.+### With an API key (Anthropic, OpenAI, Gemini, compatible)**1. Get a key** from the provider's own console. For a compatible endpoint, get the URL it@@ -61,7 +86,7 @@ The card says two things worth reading: which account is being spent, and — foproviders — that jobs run no child process at all, so the privilege-drop line reads as notapplicable rather than as a problem.-**3. Use it.** Each person opens **Plan → AI Coach**, agrees to the consent screen — which lists+**3. Use it.** Each person opens **Plan → Coach**, agrees to the consent screen — which listsexactly what leaves the server, generated from the same module that builds payloads — andanswers a short intake, one question per screen: goal, experience, days per week, sessionlength, equipment, limitations. From then on the Coach is a chat. The answers are its first@@ -414,6 +439,13 @@ The App-Store build has no server of its own, so the Coach there is a choice madsays which host each request goes to and what leaves the device before you choose, and alocal daily cap stands in for the one an admin would have set.+ A compatible endpoint has to be **`https://`** here. Android does not let apps send+ unencrypted `http://` traffic, so a model on your LAN at `http://ollama.lan:11434` cannot be+ reached from the phone, and the setup screen says so as soon as such an address is typed.+ Either put HTTPS in front of the model (Tailscale's HTTPS certificates, or a reverse proxy+ with a certificate), or use the first option: the server has no such rule, and its Coach+ reaches an `http://` model on its own network.+## Off is really off`COACH_DISABLED=1` forces the Coach off everywhere regardless of what is stored — the fleetdiff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.jsindex 680046ae9..4fd45de02 100644--- a/frontend/src/lib/pt-br-locale.test.js+++ b/frontend/src/lib/pt-br-locale.test.js@@ -27,7 +27,7 @@ describe('Brazilian Portuguese locale', () => {.sort(byCodeUnit)const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')- expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(679)+ expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(680)expect(inherited).toHaveLength(674)// If this fails, review the changed keys and wording before accepting a new hash. From// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --listdiff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.jsindex 32d2c3246..2c59d308a 100644--- a/frontend/src/locales/de.js+++ b/frontend/src/locales/de.js@@ -944,6 +944,7 @@ export default {'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',+ '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.': 'Android blockiert unverschlüsselte http://-Verbindungen aus Apps, deshalb erreicht dieses Handy nur einen https://-Endpunkt. Stell HTTPS davor (Tailscale oder ein Reverse Proxy) oder wähle „Mein selbst gehostetes openGym nutzen“: Dein Server erreicht ein http://-Modell in seinem eigenen Netzwerk.','Enter your API key': 'Gib deinen API-Schlüssel ein','How should the Coach run?': 'Wie soll der Coach laufen?','List models': 'Modelle laden',diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.jsindex dc3c3c90b..2724799e0 100644--- a/frontend/src/locales/es.js+++ b/frontend/src/locales/es.js@@ -926,6 +926,7 @@ export default {'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',+ '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.': 'Android bloquea las conexiones http:// sin cifrar desde las apps, así que este teléfono solo puede llegar a un endpoint https://. Pon HTTPS delante (Tailscale o un proxy inverso), o elige «Usar mi openGym autoalojado»: tu servidor sí puede llegar a un modelo http:// en su propia red.','Enter your API key': 'Introduce tu clave de API','How should the Coach run?': '¿Cómo debe funcionar el entrenador?','List models': 'Listar modelos',diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.jsindex 3f46498a1..6418026f9 100644--- a/frontend/src/locales/fr.js+++ b/frontend/src/locales/fr.js@@ -926,6 +926,7 @@ export default {'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',+ '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.': 'Android bloque les connexions http:// non chiffrées depuis les applis, donc ce téléphone ne peut joindre qu’un endpoint https://. Mets HTTPS devant (Tailscale ou un reverse proxy), ou choisis « Utiliser mon openGym auto-hébergé » : ton serveur, lui, peut joindre un modèle en http:// sur son propre réseau.','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',diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.jsindex 7224b5c82..05a66b6fe 100644--- a/frontend/src/locales/hi.js+++ b/frontend/src/locales/hi.js@@ -926,6 +926,7 @@ export default {'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': 'एंडपॉइंट',+ '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.': 'Android ऐप्स से बिना एन्क्रिप्शन वाले http:// कनेक्शन ब्लॉक करता है, इसलिए यह फ़ोन सिर्फ़ https:// एंडपॉइंट तक पहुँच सकता है। उसके आगे HTTPS लगाएं (Tailscale या रिवर्स प्रॉक्सी), या “मेरा सेल्फ़-होस्टेड openGym इस्तेमाल करें” चुनें: आपका सर्वर अपने नेटवर्क पर http:// मॉडल तक पहुँच सकता है।','Enter your API key': 'अपनी API कुंजी दर्ज करें','How should the Coach run?': 'कोच कैसे चले?','List models': 'मॉडल सूची',diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.jsindex acf40c392..f87c04c78 100644--- a/frontend/src/locales/hu.js+++ b/frontend/src/locales/hu.js@@ -990,6 +990,7 @@ export default {'Could not reach the provider: {0}': 'A szolgáltató nem érhető el: {0}','Each request goes straight to {0} with your key — nobody else sees it, and you pay for it.': 'Minden kérés közvetlenül ide megy a kulcsoddal: {0} — más nem látja, és te fizeted.','Endpoint': 'Végpont',+ '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.': 'Az Android letiltja az appokból induló titkosítatlan http:// kapcsolatokat, ezért ez a telefon csak https:// végpontot ér el. Tegyél elé HTTPS-t (Tailscale vagy reverse proxy), vagy válaszd „A saját openGym-szerveremet használom” lehetőséget: a szervered a saját hálózatán elér egy http:// modellt is.','Enter your API key': 'Add meg az API-kulcsodat','How should the Coach run?': 'Hogyan fusson az Edző?','List models': 'Modellek listázása',diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.jsindex 7d0102c2d..76d9d8825 100644--- a/frontend/src/locales/it.js+++ b/frontend/src/locales/it.js@@ -926,6 +926,7 @@ export default {'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',+ '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.': 'Android blocca le connessioni http:// non cifrate dalle app, quindi questo telefono può raggiungere solo un endpoint https://. Metti HTTPS davanti (Tailscale o un reverse proxy), oppure scegli «Usa il mio openGym self-hosted»: il tuo server può raggiungere un modello http:// sulla sua rete.','Enter your API key': 'Inserisci la tua chiave API','How should the Coach run?': 'Come deve funzionare il Coach?','List models': 'Elenca i modelli',diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.jsindex 639191aeb..5406fa689 100644--- a/frontend/src/locales/ko.js+++ b/frontend/src/locales/ko.js@@ -926,6 +926,7 @@ export default {'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': '엔드포인트',+ '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.': 'Android는 앱의 암호화되지 않은 http:// 연결을 차단하므로 이 휴대폰은 https:// 엔드포인트에만 연결할 수 있습니다. 앞단에 HTTPS를 두거나(Tailscale 또는 리버스 프록시) “내 자체 호스팅 openGym 사용”을 선택하세요. 서버는 자체 네트워크의 http:// 모델에 연결할 수 있습니다.','Enter your API key': 'API 키를 입력하세요','How should the Coach run?': '코치를 어떻게 실행할까요?','List models': '모델 목록',diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.jsindex 3484d0ed2..295a7ae0e 100644--- a/frontend/src/locales/pl.js+++ b/frontend/src/locales/pl.js@@ -926,6 +926,7 @@ export default {'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',+ '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.': 'Android blokuje nieszyfrowane połączenia http:// z aplikacji, więc ten telefon połączy się tylko z punktem końcowym https://. Postaw przed nim HTTPS (Tailscale albo reverse proxy) albo wybierz „Użyj mojego własnego openGym”: twój serwer połączy się z modelem http:// we własnej sieci.','Enter your API key': 'Wpisz swój klucz API','How should the Coach run?': 'Jak ma działać trener?','List models': 'Pokaż modele',diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.jsindex 0ca0b9917..cef1ff060 100644--- a/frontend/src/locales/pt-BR.js+++ b/frontend/src/locales/pt-BR.js@@ -439,6 +439,7 @@ export const PT_BR_OVERRIDES = {'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}',+ '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.': 'O Android bloqueia conexões http:// não criptografadas feitas por aplicativos, então este celular só consegue acessar um endpoint https://. Coloque HTTPS na frente (Tailscale ou um proxy reverso), ou escolha “Usar meu openGym self-hosted”: seu servidor consegue acessar um modelo http:// na própria rede.','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?',diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.jsindex 1066f2628..3bdcfea5a 100644--- a/frontend/src/locales/pt.js+++ b/frontend/src/locales/pt.js@@ -926,6 +926,7 @@ export default {'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',+ '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.': 'O Android bloqueia ligações http:// não cifradas a partir de apps, por isso este telemóvel só chega a um endpoint https://. Põe HTTPS à frente (Tailscale ou um reverse proxy), ou escolhe «Usar o meu openGym self-hosted»: o teu servidor consegue chegar a um modelo http:// na própria rede.','Enter your API key': 'Introduz a tua chave de API','How should the Coach run?': 'Como deve correr o Treinador?','List models': 'Listar modelos',diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.jsindex b70e25ed6..98d28d7c5 100644--- a/frontend/src/locales/ru.js+++ b/frontend/src/locales/ru.js@@ -926,6 +926,7 @@ export default {'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': 'Эндпоинт',+ '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.': 'Android блокирует незашифрованные подключения http:// из приложений, поэтому этот телефон может обращаться только к адресу https://. Поставьте перед ним HTTPS (Tailscale или обратный прокси) или выберите «Использовать мой собственный openGym»: ваш сервер может обращаться к модели по http:// в своей сети.','Enter your API key': 'Введите API-ключ','How should the Coach run?': 'Как должен работать тренер?','List models': 'Показать модели',diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.jsindex fc9c869d3..09000465d 100644--- a/frontend/src/locales/th.js+++ b/frontend/src/locales/th.js@@ -998,6 +998,7 @@ export default {'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': 'ปลายทาง',+ '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.': 'Android บล็อกการเชื่อมต่อ http:// ที่ไม่เข้ารหัสจากแอป โทรศัพท์เครื่องนี้จึงเข้าถึงได้เฉพาะ endpoint แบบ https:// ให้วาง HTTPS ไว้ด้านหน้า (Tailscale หรือ reverse proxy) หรือเลือก “ใช้ openGym ที่ฉันโฮสต์เอง”: เซิร์ฟเวอร์ของคุณเข้าถึงโมเดล http:// ในเครือข่ายของตัวเองได้','Enter your API key': 'ป้อนคีย์ API ของคุณ','How should the Coach run?': 'ให้โค้ชทำงานอย่างไร','List models': 'แสดงรายการโมเดล',diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.jsindex 1272dcd6a..6ab0261c9 100644--- a/frontend/src/locales/tr.js+++ b/frontend/src/locales/tr.js@@ -926,6 +926,7 @@ export default {'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',+ '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.': 'Android, uygulamalardan gelen şifrelenmemiş http:// bağlantılarını engeller; bu yüzden bu telefon yalnızca bir https:// uç noktasına ulaşabilir. Önüne HTTPS koy (Tailscale ya da ters proxy) veya “Kendi openGym sunucumu kullan” seçeneğini seç: sunucun kendi ağındaki bir http:// modele ulaşabilir.','Enter your API key': 'API anahtarını gir','How should the Coach run?': 'Koç nasıl çalışsın?','List models': 'Modelleri listele',diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.jsindex ff1605287..1de127669 100644--- a/frontend/src/locales/zh.js+++ b/frontend/src/locales/zh.js@@ -926,6 +926,7 @@ export default {'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': '端点',+ '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.': 'Android 会阻止应用发起未加密的 http:// 连接,所以这部手机只能连接 https:// 端点。请在它前面加一层 HTTPS(Tailscale 或反向代理),或选择“使用我自托管的 openGym”:你的服务器可以访问它自己网络中的 http:// 模型。','Enter your API key': '请输入你的 API 密钥','How should the Coach run?': '教练应如何运行?','List models': '列出模型',diff --git a/frontend/src/views/AdminCoach.config.test.jsx b/frontend/src/views/AdminCoach.config.test.jsxnew file mode 100644index 000000000..9248ccf47--- /dev/null+++ b/frontend/src/views/AdminCoach.config.test.jsx@@ -0,0 +1,69 @@+// @vitest-environment happy-dom+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, describe, expect, it, vi } from 'vitest'++globalThis.IS_REACT_ACT_ENVIRONMENT = true++/* The Plan tab's Coach card hangs off /api/config, which the app reads once per boot. An admin+ who switched the Coach on and connected it used to find no Coach anywhere until a reload+ (Discord #install-help, 2026-09-19). Every change on the admin card now re-reads it. */+const mocks = vi.hoisted(() => ({+ refreshConfig: vi.fn(async () => ({})),+ calls: [],+ // The shape GET /api/admin/coach answers with (api/coach/routes.js), trimmed to one provider.+ status: {+ disabledByEnv: false, enabled: false, provider: 'anthropic',+ providers: [{ id: 'anthropic', label: 'Anthropic API', runtime: 'HTTPS', apiKey: true, http: true, connected: false }],+ model: null, models: {}, baseUrl: null, knownModels: null,+ caps: { perProfileDaily: 5, instanceDaily: 0 }, community: false,+ runtime: { ok: false, version: null, error: null, needsKey: true }, authMode: 'shared', boundUid: null,+ auth: { state: 'none' }, unprivileged: { ok: true, dropped: false, why: 'this provider runs no child process' },+ jobsToday: 0, lastSuccess: null, lastError: null, recent: [],+ },+}))+vi.mock('../lib/api.js', () => ({+ api: async (path, opts) => {+ mocks.calls.push([path, opts?.method || 'GET'])+ if (path === '/api/admin/coach') return structuredClone(mocks.status)+ if (path === '/api/admin/coach/config') { mocks.status.enabled = JSON.parse(opts.body).enabled; return { ok: true } }+ return {}+ },+}))+vi.mock('../store/useStore.js', () => {+ const snap = () => ({ refreshConfig: mocks.refreshConfig })+ const useStore = selector => selector ? selector(snap()) : snap()+ useStore.getState = snap+ return { useStore }+})+vi.mock('../store/useUI.js', () => {+ const snap = () => ({ toast: vi.fn(), openSheet: vi.fn() })+ const useUI = selector => selector ? selector(snap()) : snap()+ useUI.getState = snap+ return { useUI }+})++const { default: AdminCoach } = await import('./AdminCoach.jsx')++const mounted = []+afterEach(() => { act(() => { mounted.splice(0).forEach(({ root, host }) => { root.unmount(); host.remove() }) }) })+const flush = () => act(async () => { for (let i = 0; i < 5; i++) await Promise.resolve() })++describe('AdminCoach keeps the app\'s own config current', () => {+ it('re-reads /api/config after loading and after switching the Coach on', async () => {+ const host = document.createElement('div')+ document.body.appendChild(host)+ const root = createRoot(host)+ mounted.push({ root, host })+ act(() => root.render(<AdminCoach />))+ await flush()+ expect(mocks.refreshConfig).toHaveBeenCalledTimes(1)++ const setUp = [...host.querySelectorAll('button')].find(b => b.textContent.includes('Set up the Coach'))+ expect(setUp).toBeTruthy()+ await act(async () => { setUp.click() })+ await flush()+ expect(mocks.calls).toContainEqual(['/api/admin/coach/config', 'POST'])+ expect(mocks.refreshConfig).toHaveBeenCalledTimes(2)+ })+})diff --git a/frontend/src/views/AdminCoach.jsx b/frontend/src/views/AdminCoach.jsxindex 98eedada5..6fc27686d 100644--- a/frontend/src/views/AdminCoach.jsx+++ b/frontend/src/views/AdminCoach.jsx@@ -1,5 +1,6 @@import { useEffect, useState } from 'react'import { useUI } from '../store/useUI.js'+import { useStore } from '../store/useStore.js'import { api } from '../lib/api.js'import Icon from '../components/Icon.jsx'import { Button, Switch, TextField } from '../components/ui.jsx'@@ -42,7 +43,11 @@ export default function AdminCoach() {// toast that is gone before anyone has read the provider's reason.const [testResult, setTestResult] = useState(null)- const load = () => api('/api/admin/coach').then(r => { setD(r); setModels(r.knownModels || null) }).catch(e => toast(e.message || 'Failed to load'))+ // Every change on this card ends in load(), so load() also re-reads /api/config. The app reads+ // that once per boot, and the Plan tab's Coach card hangs off it: without the re-read, an admin+ // who has just switched the Coach on and connected it finds no Coach anywhere until a reload,+ // which reads as a setup that failed (Discord #install-help, 2026-09-19).+ const load = () => api('/api/admin/coach').then(r => { setD(r); setModels(r.knownModels || null); useStore.getState().refreshConfig() }).catch(e => toast(e.message || 'Failed to load'))useEffect(() => { load() }, [])const patch = async body => {diff --git a/frontend/src/views/CoachSetup.cleartext.test.jsx b/frontend/src/views/CoachSetup.cleartext.test.jsxnew file mode 100644index 000000000..8d0f8339a--- /dev/null+++ b/frontend/src/views/CoachSetup.cleartext.test.jsx@@ -0,0 +1,91 @@+// @vitest-environment happy-dom+import React, { act } from 'react'+import { createRoot } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++globalThis.IS_REACT_ACT_ENVIRONMENT = true++/* The phone's own-key Coach and an http:// endpoint. Android refuses unencrypted traffic from+ the app, so a LAN model at http://… used to fail as a bare "could not reach the provider".+ The screen now says why as soon as the address is typed, and never tries the request. */+const mocks = vi.hoisted(() => ({ toast: vi.fn(), localModels: vi.fn(async () => ({ ok: true, models: ['llama3'] })), setCoachLocal: vi.fn(async () => {}) }))++vi.mock('../store/useStore.js', () => {+ const snap = () => ({ user: null, config: null, coachLocal: null, setCoachLocal: mocks.setCoachLocal, refreshConfig: vi.fn() })+ const useStore = selector => selector ? selector(snap()) : snap()+ useStore.getState = snap+ return { useStore }+})+vi.mock('../store/useUI.js', () => {+ const snap = () => ({ toast: (...a) => mocks.toast(...a), openSheet: vi.fn() })+ const useUI = selector => selector ? selector(snap()) : snap()+ useUI.getState = snap+ return { useUI }+})+vi.mock('react-router-dom', () => ({ useNavigate: () => () => {} }))+vi.mock('../lib/mobile.js', () => ({ MOBILE: true }))+vi.mock('../lib/coach-secrets.js', () => ({ getApiKey: async () => null, setApiKey: vi.fn(async () => {}), clearApiKey: vi.fn(async () => {}) }))+vi.mock('../lib/coach-local.js', () => ({ localModels: (...a) => mocks.localModels(...a), localForget: vi.fn() }))+vi.mock('./MobileOnboarding.jsx', () => ({ ConnectSheet: () => null }))++const { default: CoachSetup } = await import('./CoachSetup.jsx')++const mounted = []+function mount(el) {+ const host = document.createElement('div')+ document.body.appendChild(host)+ const root = createRoot(host)+ mounted.push({ root, host })+ act(() => root.render(el))+ return host+}+afterEach(() => { act(() => { mounted.splice(0).forEach(({ root, host }) => { root.unmount(); host.remove() }) }) })+beforeEach(() => { mocks.toast.mockClear(); mocks.localModels.mockClear(); mocks.setCoachLocal.mockClear() })++const settle = () => act(() => new Promise(r => setTimeout(r, 0)))+const byText = (el, sel, text) => [...el.querySelectorAll(sel)].find(n => n.textContent === text)+const rowByTitle = (el, title) => [...el.querySelectorAll('.lrow')].find(r => r.querySelector('.lrow-t')?.textContent === title)+function type(input, value) {+ const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set+ act(() => { set.call(input, value); input.dispatchEvent(new Event('input', { bubbles: true })) })+}+async function openCompatible() {+ const page = mount(<CoachSetup />)+ await settle()+ act(() => rowByTitle(page, 'Bring my own API key').click())+ act(() => byText(page, 'button.chip', 'OpenAI-compatible endpoint').click())+ const endpoint = [...page.querySelectorAll('.sect')].find(s => s.querySelector('.sect-t')?.textContent === 'Endpoint')+ return { page, endpoint, input: endpoint.querySelector('input') }+}+const REFUSAL = /Android blocks unencrypted http:\/\/ connections/++describe('CoachSetup and an http:// endpoint', () => {+ it('says why as soon as an http:// address is typed, and refuses to try it', async () => {+ const { endpoint, input, page } = await openCompatible()+ expect(endpoint.querySelector('.sect-f')).toBeNull()+ type(input, 'http://192.168.1.20:11434')+ expect(endpoint.querySelector('.sect-f').textContent).toMatch(REFUSAL)+ expect(endpoint.querySelector('.sect-f').textContent).toContain('Use my self-hosted openGym')++ await act(async () => { byText(page, 'button', 'List models').click() })+ expect(mocks.localModels).not.toHaveBeenCalled()+ expect(mocks.toast).toHaveBeenCalledWith(expect.stringMatching(REFUSAL))+ })++ it('an https:// address goes through, and editing it back to http:// after listing still cannot be saved', async () => {+ const { endpoint, input, page } = await openCompatible()+ type(input, 'https://ollama.example.com')+ expect(endpoint.querySelector('.sect-f')).toBeNull()+ await act(async () => { byText(page, 'button', 'List models').click() })+ await settle()+ expect(mocks.localModels).toHaveBeenCalledTimes(1)+ expect(mocks.localModels.mock.calls[0][0]).toMatchObject({ provider: 'compatible', baseUrl: 'https://ollama.example.com' })++ type(input, 'HTTP://ollama.lan:11434')+ const select = page.querySelector('select')+ act(() => { select.value = 'llama3'; select.dispatchEvent(new Event('change', { bubbles: true })) })+ await act(async () => { byText(page, 'button', 'Save and use the Coach').click() })+ expect(mocks.setCoachLocal).not.toHaveBeenCalled()+ expect(mocks.toast).toHaveBeenLastCalledWith(expect.stringMatching(REFUSAL))+ })+})diff --git a/frontend/src/views/CoachSetup.jsx b/frontend/src/views/CoachSetup.jsxindex 878d266ac..b462b3741 100644--- a/frontend/src/views/CoachSetup.jsx+++ b/frontend/src/views/CoachSetup.jsx@@ -25,6 +25,15 @@ import { Section, Row, Button, TextField } from '../components/ui.jsx'const STEPS = ['Loading the exercise catalogue…', 'Checking the endpoint…', '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)@@ -66,6 +75,7 @@ export default function CoachSetup() {const prepare = async () => {const v = validateBaseUrl(meta.baseUrl ? baseUrl : '')if (!v.ok) return toast(v.error)+ 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 {@@ -85,6 +95,8 @@ export default function CoachSetup() {const save = async () => {const chosen = model || meta.defaultModelif (!chosen) return toast(t('Pick a model'))+ // The endpoint can still be edited after the models were listed.+ if (meta.baseUrl && isCleartext(baseUrl)) return toast(cleartextRefused())setBusy(true)try {// The mode first, the key second: the settings file is the cheap, reliable write, the@@ -139,9 +151,10 @@ export default function CoachSetup() {</div></Section>- {meta.baseUrl && <Section title={t('Endpoint')}>+ {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="http://ollama.lan:11434" inputMode="url" autoCapitalize="none" autoCorrect="off"+ <TextField value={baseUrl} placeholder="https://ollama.example.com" inputMode="url" autoCapitalize="none" autoCorrect="off"onChange={e => setBaseUrl(e.target.value)} /></div></Section>}