Skip to content

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.

feat(coach): BYOK gets an Advanced section for the phone's daily cap and token ceiling (#527)

Hsueh0216018b53b09939
diff --git a/docs/AI_COACH.md b/docs/AI_COACH.md
index aac9b922a..cdc9bdcb0 100644
--- a/docs/AI_COACH.md
+++ b/docs/AI_COACH.md
@@ -494,8 +494,11 @@ The App-Store build has no server of its own, so the Coach there is a choice mad
the same single repair round as the server, in the app. The key is kept in the platform's
secure storage — Keychain on iOS, the Keystore-backed store on Android — and never in the
app's state, so it cannot ride along in a backup, an export or a sync. You pay: the screen
- says which host each request goes to and what leaves the device before you choose, and a
- local daily cap stands in for the one an admin would have set.
+ says which host each request goes to and what leaves the device before you choose. An
+ **Advanced** section on the same screen is the phone's admin card — since there is no
+ instance, you are the admin: the daily cap (0 for no limit), the output-token ceiling a
+ reasoning model needs raised, and the maximum message length, with the same ranges the
+ server clamps to.
Automatic reviews (weekly, or after every few workouts) run on the phone too, by the server's
rule (`api/coach/core/due.js`), but only while the app is open: there is no server to run them
diff --git a/frontend/src/lib/coach-device.js b/frontend/src/lib/coach-device.js
index 5b4677d96..4cdb413e2 100644
--- a/frontend/src/lib/coach-device.js
+++ b/frontend/src/lib/coach-device.js
@@ -15,7 +15,30 @@ 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, reviewedAt: null }
+const DEFAULTS = { mode: 'off', provider: null, model: null, baseUrl: null, handle: null, daily: null, pending: null, reviewedAt: null, limits: null }
+
+/* The three dials the BYOK setup screen's "Advanced" exposes, with the same ranges the server's
+ admin card clamps to (api/coach/config.js). That file is node-only — it reads ./data and
+ encrypts credentials — so the phone restates the numbers here rather than importing it; the
+ three defaults are what the phone already did before the dials existed. `daily` 0 means no
+ limit, exactly as the instance cap does. */
+export const COACH_LIMITS = {
+ maxOutputTokens: { def: 16000, min: 1024, max: 65536 },
+ daily: { def: 10, min: 0, max: 200 },
+ maxMessageLen: { def: 1000, min: 200, max: 4000 }
+}
+export const clampCoachLimit = (key, value) => {
+ const c = COACH_LIMITS[key]
+ const n = Math.round(Number(value))
+ return Number.isFinite(n) ? Math.max(c.min, Math.min(c.max, n)) : c.def
+}
+/** The effective dials, every one clamped and defaulted — the only shape the Coach reads. */
+export const coachLimits = d => {
+ const l = (d && d.limits) || {}
+ const out = {}
+ for (const key of Object.keys(COACH_LIMITS)) out[key] = clampCoachLimit(key, l[key] ?? COACH_LIMITS[key].def)
+ return out
+}
let cache = null
export async function loadCoachDevice() {
@@ -26,13 +49,17 @@ export async function loadCoachDevice() {
return cache
}
export async function saveCoachDevice(patch) {
- const next = { ...(await loadCoachDevice()), ...patch }
+ const cur = await loadCoachDevice()
+ const next = { ...cur, ...patch }
+ // A hand-edited file (or a caller that skipped a clamp) must not leave an out-of-range dial
+ // behind: the stored object is always the clamped one, merged with whatever was there before.
+ if (patch && patch.limits) next.limits = coachLimits({ limits: { ...coachLimits(cur), ...patch.limits } })
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
+export const coachDeviceSettings = d => d ? { mode: d.mode, provider: d.provider, model: d.model, baseUrl: d.baseUrl, limits: coachLimits(d) } : null
// Test seam.
export function _resetCoachDevice() { cache = null }
diff --git a/frontend/src/lib/coach-local.js b/frontend/src/lib/coach-local.js
index c58f4a291..8b0429614 100644
--- a/frontend/src/lib/coach-local.js
+++ b/frontend/src/lib/coach-local.js
@@ -11,7 +11,9 @@
// 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 user pays. There is no cfg.caps to lean on, so a local daily cap is not optional —
+// but on a LAN model even that is friction, so it is one of the three dials the setup
+// screen's Advanced section keeps in the device file (#527).
// - 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.
@@ -26,13 +28,12 @@ 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 { loadCoachDevice, saveCoachDevice, coachLimits } from './coach-device.js'
import { planHash } from './coach.js'
import { todayISO } from './format.js'
import { t, getLang } from './i18n.js'
export const ADAPTERS = { anthropic, openai, gemini, compatible }
-export const LOCAL_DAILY_CAP = 10
// Five minutes is right for a cloud API and wrong for a model on somebody's laptop; the
// OpenAI-compatible endpoint is the one that may be local, so it gets the long budget.
export const TIMEOUT_MS = 5 * 60000
@@ -75,7 +76,7 @@ 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 }
+ return { used, limit: coachLimits(d).daily }
}
async function bumpDaily() {
const { used } = await capState()
@@ -87,15 +88,18 @@ async function bumpDaily() {
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, last }
+ return { job, pending: (await loadCoachDevice()).pending || null, cap: await capState(), lastError, last, maxMessageLen: coachLimits(d).maxMessageLen }
}
-export const localReview = (S, note) => start(S, 'review', { note: note ? String(note).slice(0, 1000) : null })
+export const localReview = async (S, note) => {
+ const d = await loadCoachDevice()
+ return start(S, 'review', { note: note ? String(note).slice(0, coachLimits(d).maxMessageLen) : 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 })
+ return start(S, 'create', { refine: String(text || '').slice(0, coachLimits(d).maxMessageLen), previous: pendingCreate?.bundle || null, iteration: (pendingCreate?.iteration || 1) + 1 })
}
export const localDebrief = (S, workoutId) => start(S, 'debrief', { workoutId: workoutId || null })
export const localAsk = (S, text, today) => start(S, 'ask', { note: String(text || '').slice(0, 1000), today: today || null })
@@ -164,7 +168,8 @@ async function start(S, kind, opts) {
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 taking a breather. You’ve used today’s {0} runs on this phone.', cap.limit)), { status: 429, code: 'cap' })
+ // 0 is the documented "no limit" (the dial's own floor), same as the instance cap.
+ if (cap.limit > 0 && cap.used >= cap.limit) throw Object.assign(new Error(t('The Coach is taking a breather. You’ve 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(), ...(opts.scheduled ? { trigger: 'scheduled' } : {}) }
@@ -183,7 +188,7 @@ async function run(S, kind, opts, d, adapter) {
const attempt = await runPipeline({
adapter, cfg: cfgOf(d), kind, payload,
model: d.model || HTTP_PROVIDERS[d.provider].defaultModel, timeoutMs: timeoutFor(d.provider),
- invokeOpts: { env: envOf(d, key), fetch: nativeFetch }
+ invokeOpts: { env: envOf(d, key), fetch: nativeFetch, maxTokens: coachLimits(d).maxOutputTokens }
})
if (!attempt.ok) {
// There is no admin card on a phone, so the reason has to reach the person holding it:
diff --git a/frontend/src/lib/coach-local.test.js b/frontend/src/lib/coach-local.test.js
index 3e0b4138e..170d66b5e 100644
--- a/frontend/src/lib/coach-local.test.js
+++ b/frontend/src/lib/coach-local.test.js
@@ -24,7 +24,7 @@ vi.mock('./capacitor-fetch.js', () => ({
}))
const local = await import('./coach-local.js')
-const { _resetCoachDevice, loadCoachDevice, saveCoachDevice } = await import('./coach-device.js')
+const { _resetCoachDevice, loadCoachDevice, saveCoachDevice, COACH_LIMITS } = await import('./coach-device.js')
const { applyChangeSet, markStale, planHash } = await import('./coach.js')
const { todayISO } = await import('./format.js')
const { EXERCISES } = await import('../../../api/coach/core/library-data.js')
@@ -153,9 +153,43 @@ describe('the Coach on a phone with its own key', () => {
// The cap is keyed by the LOCAL date (todayISO), not the UTC one: in the evening in the
// Americas the two differ, and a UTC stamp here read as yesterday's record and let the run through.
- await saveCoachDevice({ daily: { d: todayISO(), n: local.LOCAL_DAILY_CAP } })
+ const cap = COACH_LIMITS.daily.def
+ await saveCoachDevice({ daily: { d: todayISO(), n: 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 })
+ expect((await local.localStatus()).cap).toEqual({ used: cap, limit: cap })
+ })
+
+ it('reads the daily cap from the device dial, and 0 is no limit', async () => {
+ await saveCoachDevice({ limits: { daily: 3 }, daily: { d: todayISO(), n: 3 } })
+ await expect(local.localReview(state())).rejects.toMatchObject({ code: 'cap' })
+ expect((await local.localStatus()).cap).toEqual({ used: 3, limit: 3 })
+
+ // The documented "unlimited": stored runs above any limit no longer refuse the next one.
+ await saveCoachDevice({ limits: { daily: 0 } })
+ await local.localReview(state())
+ const s = await settle()
+ expect(s.pending).toBeTruthy()
+ expect(s.cap).toEqual({ used: 4, limit: 0 })
+ })
+
+ it('sends the device output-token ceiling on the wire', async () => {
+ await saveCoachDevice({ limits: { maxOutputTokens: 48000 } })
+ await local.localReview(state())
+ await settle()
+ expect(wire.calls[0].body.max_completion_tokens).toBe(48000)
+ })
+
+ it('clips free text to the device message dial, clamped to the floor', async () => {
+ // Below the floor is raised to it and reported as such, both to the composer and to the clip.
+ await saveCoachDevice({ limits: { maxMessageLen: 50 } })
+ expect((await local.localStatus()).maxMessageLen).toBe(COACH_LIMITS.maxMessageLen.min)
+
+ const note = 'x'.repeat(500)
+ await local.localReview(state(), note)
+ await settle()
+ const sent = wire.calls[0].body.messages[1].content
+ expect(sent).toContain('"userNote":"' + 'x'.repeat(COACH_LIMITS.maxMessageLen.min) + '"')
+ expect(sent).not.toContain('x'.repeat(COACH_LIMITS.maxMessageLen.min + 1))
})
it('a proposal waits in the device file, expires, and is cleared by resolve', async () => {
diff --git a/frontend/src/locales/ar.js b/frontend/src/locales/ar.js
index 96ce359d8..4286a4bcb 100644
--- a/frontend/src/locales/ar.js
+++ b/frontend/src/locales/ar.js
@@ -2519,4 +2519,13 @@ export default {
'Add them to “{1}”': 'أضِفها إلى «{1}»',
'Thinking about your question…': 'أفكر في سؤالك…',
'This is the demo, so there is no AI model behind me. On your own server I answer questions like “{0}” with your plan, your last sessions and the workout you are doing right now.': 'هذا هو العرض التجريبي، لذا لا يوجد نموذج ذكاء اصطناعي خلفي. على خادمك الخاص أجيب عن أسئلة مثل «{0}» بالاعتماد على خطتك وجلساتك الأخيرة والتمرين الذي تقوم به الآن.',
+
+ // --- AI Coach on the phone: the BYOK limits (#527) ---
+ 'Advanced': 'متقدم',
+ 'Max output tokens': 'الحد الأقصى لرموز الإخراج',
+ 'The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.': 'الحد الأقصى للإجابة الواحدة. تحتسب النماذج الاستدلالية تفكيرها الخفي ضمن هذا الحد، لذا ارفعه إذا قُطع خطتك.',
+ 'Daily runs': 'عمليات التشغيل اليومية',
+ 'Every Coach run is one request on your provider account. 0 means no limit.': 'كل تشغيل للمدرب هو طلب واحد على حساب مزودك. تعني 0 بلا حد.',
+ 'Max message length': 'الحد الأقصى لطول الرسالة',
+ 'How long a message, refinement or review note can be.': 'كم يمكن أن يطول نص رسالة أو طلب تعديل أو ملاحظة مراجعة.',
}
diff --git a/frontend/src/locales/bn.js b/frontend/src/locales/bn.js
index 92cc05958..a67f72f0a 100644
--- a/frontend/src/locales/bn.js
+++ b/frontend/src/locales/bn.js
@@ -2543,4 +2543,13 @@ export default {
'Add them to “{1}”': 'সবগুলো “{1}”-এ যোগ করুন',
'Thinking about your question…': 'আপনার প্রশ্ন নিয়ে ভাবছি…',
'This is the demo, so there is no AI model behind me. On your own server I answer questions like “{0}” with your plan, your last sessions and the workout you are doing right now.': 'এটি ডেমো, তাই আমার পেছনে কোনো AI মডেল নেই। আপনার নিজের সার্ভারে আমি “{0}”-এর মতো প্রশ্নের উত্তর দিই আপনার প্ল্যান, সাম্প্রতিক সেশন আর এখন চলা ওয়ার্কআউট দেখে।',
+
+ // --- AI Coach on the phone: the BYOK limits (#527) ---
+ 'Advanced': 'উন্নত',
+ 'Max output tokens': 'সর্বোচ্চ আউটপুট টোকেন',
+ 'The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.': 'একটি উত্তরের সীমা। যুক্তি-ভিত্তিক মডেলগুলো তাদের গোপন চিন্তা এতে গোনে, তাই কোনো পরিকল্পনা কাটা পড়লে এটি বাড়ান।',
+ 'Daily runs': 'প্রতিদিনের রান',
+ 'Every Coach run is one request on your provider account. 0 means no limit.': 'কোচের প্রতিটি রান আপনার প্রদানকারীর অ্যাকাউন্টে একটি অনুরোধ। 0 মানে কোনো সীমা নেই।',
+ 'Max message length': 'সর্বোচ্চ বার্তার দৈর্ঘ্য',
+ 'How long a message, refinement or review note can be.': 'একটি বার্তা, পরিমার্জনার অনুরোধ বা পর্যালোচনা নোট কত দীর্ঘ হতে পারে।',
}
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index c4ee2b60a..0ba41b4bc 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -2484,4 +2484,13 @@ export default {
'Add them to “{1}”': 'Alle zu „{1}“ hinzufügen',
'Thinking about your question…': 'Ich denke über deine Frage nach…',
'This is the demo, so there is no AI model behind me. On your own server I answer questions like “{0}” with your plan, your last sessions and the workout you are doing right now.': 'Das ist die Demo, hinter mir steckt also kein KI-Modell. Auf deinem eigenen Server beantworte ich Fragen wie „{0}“ mit deinem Plan, deinen letzten Einheiten und dem Training, das du gerade machst.',
+
+ // --- AI Coach on the phone: the BYOK limits (#527) ---
+ 'Advanced': 'Erweitert',
+ 'Max output tokens': 'Max. Ausgabe-Token',
+ 'The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.': 'Die Obergrenze für eine Antwort. Denkende Modelle rechnen ihr verborgenes Nachdenken darauf an; erhöhe sie, wenn ein Plan abgeschnitten wird.',
+ 'Daily runs': 'Läufe pro Tag',
+ 'Every Coach run is one request on your provider account. 0 means no limit.': 'Jeder Coach-Lauf ist eine Anfrage über dein Anbieterkonto. 0 bedeutet kein Limit.',
+ 'Max message length': 'Maximale Nachrichtenlänge',
+ 'How long a message, refinement or review note can be.': 'Wie lang eine Nachricht, ein Überarbeitungswunsch oder eine Analyse-Notiz sein darf.',
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index 20b82b39d..4488dd196 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -2464,4 +2464,13 @@ export default {
'Add them to “{1}”': 'Añadirlos a «{1}»',
'Thinking about your question…': 'Pensando en tu pregunta…',
'This is the demo, so there is no AI model behind me. On your own server I answer questions like “{0}” with your plan, your last sessions and the workout you are doing right now.': 'Esto es la demo, así que no hay ningún modelo de IA detrás de mí. En tu propio servidor respondo preguntas como «{0}» con tu plan, tus últimas sesiones y el entrenamiento que estás haciendo ahora.',
+
+ // --- AI Coach on the phone: the BYOK limits (#527) ---
+ 'Advanced': 'Avanzado',
+ 'Max output tokens': 'Máximo de tokens de salida',
+ 'The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.': 'El límite de una respuesta. Los modelos de razonamiento cuentan su pensamiento oculto para este límite, así que súbelo si un plan se corta.',
+ 'Daily runs': 'Ejecuciones por día',
+ 'Every Coach run is one request on your provider account. 0 means no limit.': 'Cada ejecución del Entrenador es una solicitud en tu cuenta del proveedor. 0 significa sin límite.',
+ 'Max message length': 'Longitud máxima del mensaje',
+ 'How long a message, refinement or review note can be.': 'Cuánto puede tener un mensaje, una petición de refinamiento o una nota de análisis.',
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 927f2b890..0c80a9487 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -2464,4 +2464,13 @@ export default {
'Add them to “{1}”': 'Les ajouter à « {1} »',
'Thinking about your question…': 'Je réfléchis à ta question…',
'This is the demo, so there is no AI model behind me. On your own server I answer questions like “{0}” with your plan, your last sessions and the workout you are doing right now.': 'Ceci est la démo : il n’y a donc aucun modèle d’IA derrière moi. Sur ton propre serveur, je réponds à des questions comme « {0} » avec ton programme, tes dernières séances et l’entraînement que tu fais en ce moment.',
+
+ // --- AI Coach on the phone: the BYOK limits (#527) ---
+ 'Advanced': 'Avancé',
+ 'Max output tokens': 'Jetons de sortie max.',
+ 'The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.': 'Le plafond d’une réponse. Les modèles de raisonnement comptent leur réflexion cachée dans ce plafond, alors augmentez-le si un plan est coupé.',
+ 'Daily runs': 'Exécutions par jour',
+ 'Every Coach run is one request on your provider account. 0 means no limit.': 'Chaque exécution du Coach est une requête sur votre compte fournisseur. 0 signifie aucune limite.',
+ 'Max message length': 'Longueur maximale du message',
+ 'How long a message, refinement or review note can be.': 'La longueur autorisée d’un message, d’une demande de révision ou d’une note d’analyse.',
}
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index dec360d4b..6bf7e5409 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -2464,4 +2464,13 @@ export default {
'Add them to “{1}”': 'सभी को “{1}” में जोड़ें',
'Thinking about your question…': 'आपके सवाल पर सोच रहा हूँ…',
'This is the demo, so there is no AI model behind me. On your own server I answer questions like “{0}” with your plan, your last sessions and the workout you are doing right now.': 'यह डेमो है, इसलिए मेरे पीछे कोई AI मॉडल नहीं है। आपके अपने सर्वर पर मैं “{0}” जैसे सवालों का जवाब आपकी योजना, पिछले सेशन और अभी चल रहे वर्कआउट के आधार पर देता हूँ।',
+
+ // --- AI Coach on the phone: the BYOK limits (#527) ---
+ 'Advanced': 'उन्नत',
+ 'Max output tokens': 'अधिकतम आउटपुट टोकन',
+ 'The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.': 'एक उत्तर की सीमा। तर्क करने वाले मॉडल अपनी छिपी सोच को इसमें गिनते हैं, इसलिए यदि कोई योजना कट जाए तो इसे बढ़ाएँ।',
+ 'Daily runs': 'प्रतिदिन रन',
+ 'Every Coach run is one request on your provider account. 0 means no limit.': 'कोच का हर रन आपके प्रदाता खाते पर एक अनुरोध है। 0 का अर्थ है कोई सीमा नहीं।',
+ 'Max message length': 'अधिकतम संदेश लंबाई',
+ 'How long a message, refinement or review note can be.': 'संदेश, सुधार अनुरोध या समीक्षा नोट कितना लंबा हो सकता है।',
}
diff --git a/frontend/src/locales/hu.js b/frontend/src/locales/hu.js
index f70a28cb1..bdb424b94 100644
--- a/frontend/src/locales/hu.js
+++ b/frontend/src/locales/hu.js
@@ -2467,4 +2467,13 @@ export default {
'Add them to “{1}”': 'Mind hozzáadása ehhez: „{1}”',
'Thinking about your question…': 'Gondolkodom a kérdéseden…',
'This is the demo, so there is no AI model behind me. On your own server I answer questions like “{0}” with your plan, your last sessions and the workout you are doing right now.': 'Ez a demó, így nincs mögöttem MI-modell. A saját szervereden az olyan kérdésekre, mint „{0}”, a terved, a legutóbbi edzéseid és az épp folyó edzésed alapján válaszolok.',
+
+ // --- AI Coach on the phone: the BYOK limits (#527) ---
+ 'Advanced': 'Speciális',
+ 'Max output tokens': 'Max. kimeneti token',
+ 'The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.': 'Egy válasz felső korlátja. A gondolkodó modellek a rejtett gondolkodásukat is beleszámítják, ezért emeld meg, ha egy terv elvágódik.',
+ 'Daily runs': 'Napi futtatások',
+ 'Every Coach run is one request on your provider account. 0 means no limit.': 'Minden Edző-futtatás egy kérés a szolgáltatói fiókodon. A 0 azt jelenti, nincs korlát.',
+ 'Max message length': 'Max. üzenethossz',
+ 'How long a message, refinement or review note can be.': 'Milyen hosszú lehet egy üzenet, finomítási kérés vagy elemzési megjegyzés.',
}
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index e8b245e0f..0bca92695 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -2464,4 +2464,13 @@ export default {
'Add them to “{1}”': 'Aggiungili a «{1}»',
'Thinking about your question…': 'Sto pensando alla tua domanda…',
'This is the demo, so there is no AI model behind me. On your own server I answer questions like “{0}” with your plan, your last sessions and the workout you are doing right now.': 'Questa è la demo, quindi dietro di me non c’è nessun modello di IA. Sul tuo server rispondo a domande come “{0}” usando il tuo piano, le ultime sessioni e l’allenamento che stai facendo adesso.',
+
+ // --- AI Coach on the phone: the BYOK limits (#527) ---
+ 'Advanced': 'Avanzate',
+ 'Max output tokens': 'Token di output massimi',
+ 'The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.': 'Il limite di una risposta. I modelli di ragionamento contano il loro pensiero nascosto su questo limite, quindi alzalo se un piano viene troncato.',
+ 'Daily runs': 'Esecuzioni al giorno',
+ 'Every Coach run is one request on your provider account. 0 means no limit.': 'Ogni esecuzione del Coach è una richiesta sul tuo account del provider. 0 significa nessun limite.',
+ 'Max message length': 'Lunghezza massima del messaggio',
+ 'How long a message, refinement or review note can be.': 'Quanto può essere lungo un messaggio, una richiesta di revisione o una nota di analisi.',
}
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index 13fd54cac..03ed893ad 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -2464,4 +2464,13 @@ export default {
'Add them to “{1}”': '모두 “{1}”에 추가',
'Thinking about your question…': '질문을 생각하고 있어요…',
'This is the demo, so there is no AI model behind me. On your own server I answer questions like “{0}” with your plan, your last sessions and the workout you are doing right now.': '이것은 데모라서 뒤에 AI 모델이 없습니다. 내 서버에서는 “{0}” 같은 질문에 계획, 최근 세션, 지금 하고 있는 운동을 바탕으로 답합니다.',
+
+ // --- AI Coach on the phone: the BYOK limits (#527) ---
+ 'Advanced': '고급',
+ 'Max output tokens': '최대 출력 토큰',
+ 'The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.': '한 응답의 상한입니다. 추론 모델은 숨은 사고를 여기에 포함하므로, 계획이 잘리면 이 값을 높이세요.',
+ 'Daily runs': '일일 실행 횟수',
+ 'Every Coach run is one request on your provider account. 0 means no limit.': '코치 실행은 매번 제공자 계정으로 보내는 한 번의 요청입니다. 0은 무제한을 뜻합니다.',
+ 'Max message length': '최대 메시지 길이',
+ 'How long a message, refinement or review note can be.': '메시지, 수정 요청 또는 리뷰 메모의 최대 길이입니다.',
}
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 90d92344a..7f305ca60 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -2464,4 +2464,13 @@ export default {
'Add them to “{1}”': { one: 'Dodaj do „{1}”', few: 'Dodaj wszystkie do „{1}”', many: 'Dodaj wszystkie do „{1}”' },
'Thinking about your question…': 'Myślę nad Twoim pytaniem…',
'This is the demo, so there is no AI model behind me. On your own server I answer questions like “{0}” with your plan, your last sessions and the workout you are doing right now.': 'To jest demo, więc nie stoi za mną żaden model AI. Na Twoim własnym serwerze odpowiadam na pytania w rodzaju „{0}”, korzystając z Twojego planu, ostatnich sesji i treningu, który właśnie robisz.',
+
+ // --- AI Coach on the phone: the BYOK limits (#527) ---
+ 'Advanced': 'Zaawansowane',
+ 'Max output tokens': 'Maks. tokenów wyjściowych',
+ 'The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.': 'Limit jednej odpowiedzi. Modele rozumujące wliczają w niego swoje ukryte rozumowanie, więc zwiększ go, jeśli plan zostanie ucięty.',
+ 'Daily runs': 'Uruchomienia dziennie',
+ 'Every Coach run is one request on your provider account. 0 means no limit.': 'Każde uruchomienie Trenera to jedno żądanie na Twoim koncie dostawcy. 0 oznacza brak limitu.',
+ 'Max message length': 'Maksymalna długość wiadomości',
+ 'How long a message, refinement or review note can be.': 'Jak długi może być komunikat, prośba o korektę lub notatka z analizy.',
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index 25d33f154..03bf3ab57 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -1577,6 +1577,15 @@ export const PT_BR_OVERRIDES = {
'Add them to “{1}”': 'Adicionar todos a “{1}”',
'Thinking about your question…': 'Pensando na sua pergunta…',
'This is the demo, so there is no AI model behind me. On your own server I answer questions like “{0}” with your plan, your last sessions and the workout you are doing right now.': 'Esta é a demo, então não há nenhum modelo de IA por trás de mim. No seu próprio servidor eu respondo perguntas como “{0}” com o seu plano, suas últimas sessões e o treino que você está fazendo agora.',
+
+ // --- AI Coach on the phone: the BYOK limits (#527) ---
+ 'Advanced': 'Avançado',
+ 'Max output tokens': 'Máximo de tokens de saída',
+ 'The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.': 'O limite de uma resposta. Modelos de raciocínio contam o pensamento oculto nesse limite, então aumente se um plano for cortado.',
+ 'Daily runs': 'Execuções por dia',
+ 'Every Coach run is one request on your provider account. 0 means no limit.': 'Cada execução do Treinador é uma requisição na sua conta do provedor. 0 significa sem limite.',
+ 'Max message length': 'Comprimento máximo da mensagem',
+ 'How long a message, refinement or review note can be.': 'Quanto pode ter uma mensagem, um pedido de refinamento ou uma nota de análise.',
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index 956a18012..d521a142c 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -2464,4 +2464,13 @@ export default {
'Add them to “{1}”': 'Adicioná-los a «{1}»',
'Thinking about your question…': 'A pensar na tua pergunta…',
'This is the demo, so there is no AI model behind me. On your own server I answer questions like “{0}” with your plan, your last sessions and the workout you are doing right now.': 'Isto é a demo, por isso não há nenhum modelo de IA por trás de mim. No teu próprio servidor respondo a perguntas como “{0}” com o teu plano, as tuas últimas sessões e o treino que estás a fazer agora.',
+
+ // --- AI Coach on the phone: the BYOK limits (#527) ---
+ 'Advanced': 'Avançado',
+ 'Max output tokens': 'Máximo de tokens de saída',
+ 'The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.': 'O limite de uma resposta. Os modelos de raciocínio contam o seu pensamento oculto para este limite, por isso aumenta-o se um plano for cortado.',
+ 'Daily runs': 'Execuções por dia',
+ 'Every Coach run is one request on your provider account. 0 means no limit.': 'Cada execução do Treinador é um pedido na tua conta do fornecedor. 0 significa sem limite.',
+ 'Max message length': 'Comprimento máximo da mensagem',
+ 'How long a message, refinement or review note can be.': 'Quanto pode ter uma mensagem, um pedido de revisão ou uma nota de análise.',
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index e95cf9817..a6bc34384 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -2468,4 +2468,13 @@ export default {
'Add them to “{1}”': { one: 'Добавить в «{1}»', few: 'Добавить все в «{1}»', many: 'Добавить все в «{1}»' },
'Thinking about your question…': 'Думаю над вашим вопросом…',
'This is the demo, so there is no AI model behind me. On your own server I answer questions like “{0}” with your plan, your last sessions and the workout you are doing right now.': 'Это демо, поэтому за мной нет модели ИИ. На вашем собственном сервере я отвечаю на вопросы вроде «{0}», учитывая ваш план, последние тренировки и тренировку, которую вы делаете сейчас.',
+
+ // --- AI Coach on the phone: the BYOK limits (#527) ---
+ 'Advanced': 'Дополнительно',
+ 'Max output tokens': 'Макс. токенов вывода',
+ 'The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.': 'Потолок одного ответа. Рассуждающие модели учитывают в нём свои скрытые размышления, поэтому увеличьте его, если план обрывается.',
+ 'Daily runs': 'Запусков в день',
+ 'Every Coach run is one request on your provider account. 0 means no limit.': 'Каждый запуск Тренера — один запрос на вашем аккаунте провайдера. 0 означает без ограничений.',
+ 'Max message length': 'Макс. длина сообщения',
+ 'How long a message, refinement or review note can be.': 'Насколько длинным может быть сообщение, просьба о доработке или заметка к разбору.',
}
diff --git a/frontend/src/locales/th.js b/frontend/src/locales/th.js
index a1e0e7e3a..1125796c0 100644
--- a/frontend/src/locales/th.js
+++ b/frontend/src/locales/th.js
@@ -2475,4 +2475,13 @@ export default {
'Add them to “{1}”': 'เพิ่มทั้งหมดใน “{1}”',
'Thinking about your question…': 'กำลังคิดเรื่องคำถามของคุณ…',
'This is the demo, so there is no AI model behind me. On your own server I answer questions like “{0}” with your plan, your last sessions and the workout you are doing right now.': 'นี่คือเดโม จึงไม่มีโมเดล AI อยู่เบื้องหลัง บนเซิร์ฟเวอร์ของคุณเอง ฉันจะตอบคำถามอย่าง “{0}” โดยใช้แผน เซสชันล่าสุด และการออกกำลังกายที่คุณกำลังทำอยู่',
+
+ // --- AI Coach on the phone: the BYOK limits (#527) ---
+ 'Advanced': 'ขั้นสูง',
+ 'Max output tokens': 'จำนวนโทเคนเอาต์พุตสูงสุด',
+ 'The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.': 'เพดานของคำตอบหนึ่งครั้ง โมเดลที่คิดวิเคราะห์จะนับการคิดที่ซ่อนอยู่รวมในเพดานนี้ ดังนั้นให้เพิ่มค่านี้หากแผนถูกตัดขาด',
+ 'Daily runs': 'จำนวนครั้งต่อวัน',
+ 'Every Coach run is one request on your provider account. 0 means no limit.': 'โค้ชแต่ละครั้งคือหนึ่งคำขอในบัญชีผู้ให้บริการของคุณ 0 หมายถึงไม่จำกัด',
+ 'Max message length': 'ความยาวข้อความสูงสุด',
+ 'How long a message, refinement or review note can be.': 'ข้อความ คำขอปรับแก้ หรือบันทึกการวิเคราะห์ยาวได้เท่าใด',
}
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index 234bd46ba..5e7ae78bb 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -2464,4 +2464,13 @@ export default {
'Add them to “{1}”': 'Hepsini “{1}” rutinine ekle',
'Thinking about your question…': 'Sorunu düşünüyorum…',
'This is the demo, so there is no AI model behind me. On your own server I answer questions like “{0}” with your plan, your last sessions and the workout you are doing right now.': 'Bu bir demo, yani arkamda bir yapay zekâ modeli yok. Kendi sunucunda “{0}” gibi sorulara planın, son antrenmanların ve şu anda yaptığın antrenmanla cevap veririm.',
+
+ // --- AI Coach on the phone: the BYOK limits (#527) ---
+ 'Advanced': 'Gelişmiş',
+ 'Max output tokens': 'Maks. çıktı token’ı',
+ 'The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.': 'Tek bir yanıtın üst sınırı. Akıl yürüten modeller gizli düşünmelerini bu sınıra sayar; bir plan kesilirse bunu yükselt.',
+ 'Daily runs': 'Günlük çalıştırma',
+ 'Every Coach run is one request on your provider account. 0 means no limit.': 'Her Koç çalıştırması sağlayıcı hesabında bir istektir. 0 sınırsız demektir.',
+ 'Max message length': 'Maks. mesaj uzunluğu',
+ 'How long a message, refinement or review note can be.': 'Bir mesajın, iyileştirme isteğinin veya inceleme notunun ne kadar uzun olabileceği.',
}
diff --git a/frontend/src/locales/uk.js b/frontend/src/locales/uk.js
index d8a69d961..4646b32e8 100644
--- a/frontend/src/locales/uk.js
+++ b/frontend/src/locales/uk.js
@@ -2461,4 +2461,13 @@ export default {
'Add them to “{1}”': { one: 'Додати до «{1}»', few: 'Додати всі до «{1}»', many: 'Додати всі до «{1}»' },
'Thinking about your question…': 'Думаю над вашим запитанням…',
'This is the demo, so there is no AI model behind me. On your own server I answer questions like “{0}” with your plan, your last sessions and the workout you are doing right now.': 'Це демо, тож за мною немає моделі ШІ. На вашому власному сервері я відповідаю на запитання на кшталт «{0}», враховуючи ваш план, останні тренування і тренування, яке ви робите зараз.',
+
+ // --- AI Coach on the phone: the BYOK limits (#527) ---
+ 'Advanced': 'Додатково',
+ 'Max output tokens': 'Макс. вихідних токенів',
+ 'The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.': 'Стеля однієї відповіді. Міркувальні моделі враховують у ній свої приховані роздуми, тож підніміть її, якщо план обривається.',
+ 'Daily runs': 'Запусків на день',
+ 'Every Coach run is one request on your provider account. 0 means no limit.': 'Кожен запуск Тренера — це один запит на вашому акаунті постачальника. 0 означає без обмежень.',
+ 'Max message length': 'Макс. довжина повідомлення',
+ 'How long a message, refinement or review note can be.': 'Наскільки довгим може бути повідомлення, прохання про доопрацювання чи нотатка до розбору.',
}
diff --git a/frontend/src/locales/zh-TW.js b/frontend/src/locales/zh-TW.js
index 46dcf2095..3e1e61e9c 100644
--- a/frontend/src/locales/zh-TW.js
+++ b/frontend/src/locales/zh-TW.js
@@ -2457,4 +2457,13 @@ export default {
'Add them to “{1}”': '全部加入「{1}」',
'Thinking about your question…': '正在思考你的問題…',
'This is the demo, so there is no AI model behind me. On your own server I answer questions like “{0}” with your plan, your last sessions and the workout you are doing right now.': '這是展示版,我背後沒有 AI 模型。在你自己的伺服器上,我會根據你的計畫、最近幾次訓練和你正在進行的訓練,回答像「{0}」這樣的問題。',
+
+ // --- AI Coach on the phone: the BYOK limits (#527) ---
+ 'Advanced': '進階',
+ 'Max output tokens': '最大輸出 token 數',
+ 'The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.': '單次回答的上限。推理模型會把隱藏的思考計入其中,所以如果計畫被截斷,就把它調高。',
+ 'Daily runs': '每日執行次數',
+ 'Every Coach run is one request on your provider account. 0 means no limit.': '教練每執行一次,就會向你的提供商帳戶發出一次請求。0 代表不限制。',
+ 'Max message length': '最大訊息長度',
+ 'How long a message, refinement or review note can be.': '訊息、修改要求或評論備註可以有多長。',
}
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 84f9a50e3..61e79dc84 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -2464,4 +2464,13 @@ export default {
'Add them to “{1}”': '全部加入「{1}」',
'Thinking about your question…': '正在思考你的问题…',
'This is the demo, so there is no AI model behind me. On your own server I answer questions like “{0}” with your plan, your last sessions and the workout you are doing right now.': '这是演示版,我背后没有 AI 模型。在你自己的服务器上,我会结合你的计划、最近几次训练和你正在进行的训练,回答像“{0}”这样的问题。',
+
+ // --- AI Coach on the phone: the BYOK limits (#527) ---
+ 'Advanced': '高级',
+ 'Max output tokens': '最大输出 token 数',
+ 'The ceiling on one answer. Reasoning models count its hidden thinking against it, so raise it if a plan is cut off.': '单次回答的上限。推理模型会把隐藏的思考计入其中,所以如果计划被截断,就把它调高。',
+ 'Daily runs': '每日运行次数',
+ 'Every Coach run is one request on your provider account. 0 means no limit.': '教练每次运行都会向你的提供商账户发送一次请求。0 表示不限制。',
+ 'Max message length': '最大消息长度',
+ 'How long a message, refinement or review note can be.': '消息、修改要求或点评备注可以有多长。',
}
diff --git a/frontend/src/views/CoachSetup.jsx b/frontend/src/views/CoachSetup.jsx
index bd80af9df..d5f8e2b84 100644
--- a/frontend/src/views/CoachSetup.jsx
+++ b/frontend/src/views/CoachSetup.jsx
@@ -17,6 +17,7 @@ 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'
@@ -55,12 +56,24 @@ export default function CoachSetup() {
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 } } }))
@@ -203,6 +216,20 @@ export default function CoachSetup() {
</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>
@@ -220,3 +247,19 @@ export default function CoachSetup() {
}
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>
+}