Coach: a failed run on the phone says why, a message with no plan asks for one, the chat has context

- Phone with own key: the provider's or validator's reason reaches the chat line and toast
  (BYOK_ERRORS + jobErrorText); no more "instance owner" wording where there is none (#58)
- CoachChat: a message with no routines refines/creates instead of reviewing an empty window;
  menu entry "Start a new plan" (Discord "Coach reset" thread)
- payload: refine without a previous plan becomes a create with userNote; the last six chat
  lines travel as `conversation` (documented in common.md, prompts.js regenerated)
- OpenAI model list cut to Chat-Completions models (isChatModel); Gemini placeholder names AQ. keys
- 3 new strings in 14 packs, pt-BR guard 626/616/3db560d7; tests for all of it
This commit is contained in:
Duarte Santos committed 2026-09-07 17:05:07 +02:00
1 parent 5c2005e81f
commit d0aaa7205d
26 files changed
+208 -13

No files matched your search

+20 -1
View File
@@ -36,7 +36,7 @@ const local = async () => {
// There is no admin card on a phone: the user is the operator, so failures go to them.
localMod.setNotifier(ev => {
const toast = useUI.getState().toast
if (ev.kind === 'failed') toast(JOB_ERRORS[ev.errorClass] || JOB_ERRORS.internal)
if (ev.kind === 'failed') toast(jobErrorText(ev.errorClass, ev.detail))
else if (ev.kind === 'nochange') toast(t('Nothing to change right now: {0}', String(ev.reading || '').slice(0, 140)))
})
}
@@ -131,3 +131,22 @@ export const JOB_ERRORS = {
noworkout: 'There is no workout to look at yet — log one first.',
internal: 'Something went wrong on the server.'
}
// The same failures on a phone that brought its own key: there is no instance owner to
// check anything, the person reading this is the operator, and the provider's own words
// are the only thing that lets them fix it (a spent quota, a wrong model, a rejected key).
export const BYOK_ERRORS = {
auth: 'Your AI provider rejected the key on this phone — check it under Settings → AI Coach.',
missing: 'The Coach isn’t set up on this phone — check Settings → AI Coach.',
provider: 'Your AI provider couldn’t answer.',
unusable: 'The Coach answered with something the app couldn’t use.',
internal: 'Something went wrong on this phone.'
}
/** The line the person sees for a failed job — with the reason attached where they can act on it. */
export function jobErrorText(cls, detail) {
const own = LOCAL()
const base = (own && BYOK_ERRORS[cls]) || JOB_ERRORS[cls] || (own ? BYOK_ERRORS.internal : JOB_ERRORS.internal)
const why = own && detail ? String(detail).trim().slice(0, 300) : ''
return why ? `${base}\n${why}` : base
}
+7 -2
View File
@@ -150,9 +150,14 @@ async function run(S, kind, opts, d, adapter) {
invokeOpts: { env: envOf(d, key), fetch: nativeFetch }
})
if (!attempt.ok) {
lastError = { errorClass: attempt.errorClass, detail: attempt.detail || null }
// There is no admin card on a phone, so the reason has to reach the person holding it:
// the provider's own words for a refusal, the validator's for an answer that did not fit.
const detail = attempt.detail || (Array.isArray(attempt.errors) && attempt.errors.length
? attempt.errors.slice(0, 3).map(String).join(' · ').slice(0, 300)
: null)
lastError = { errorClass: attempt.errorClass, detail }
last = { id: job.id, kind, outcome: 'failed', errorClass: attempt.errorClass, at: Date.now() }
if (notify) notify({ kind: 'failed', errorClass: attempt.errorClass, detail: attempt.detail || null })
if (notify) notify({ kind: 'failed', errorClass: attempt.errorClass, detail })
return
}
if (attempt.nochange) {
+14
View File
@@ -95,6 +95,20 @@ describe('the Coach on a phone with its own key', () => {
expect(wire.calls).toHaveLength(2)
expect(f.pending).toBeNull()
expect(f.lastError.errorClass).toBe('unusable')
expect(f.lastError.detail).toMatch(/JSON|object/i) // the validator's reason reaches the phone — there is no admin card
})
it('a provider refusal carries the provider’s own words, so the person holding the key can act on it', async () => {
// A 4xx the adapter does not retry (429 would wait out two retries first); the wording is OpenAI's.
wire.answer = { status: 404, body: { error: { message: 'The model `gpt-4o-mini-tts` does not exist or you do not have access to it.' } } }
const seen = []
local.setNotifier(ev => seen.push(ev))
await local.localReview(state())
const s = await settle()
expect(s.lastError.errorClass).toBe('provider')
expect(s.lastError.detail).toMatch(/^404 The model `gpt-4o-mini-tts` does not exist/)
expect(seen.at(-1)).toMatchObject({ kind: 'failed', errorClass: 'provider', detail: expect.stringMatching(/does not exist/) })
local.setNotifier(null)
})
it('a 401 is an auth failure, and never a proposal', async () => {
+2 -2
View File
@@ -28,10 +28,10 @@ describe('Brazilian Portuguese locale', () => {
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(626)
expect(inherited).toHaveLength(613)
expect(inherited).toHaveLength(616)
// If this fails, review the changed keys and wording before accepting a new hash. From
// frontend/: node scripts/pt-br-inheritance-fingerprint.mjs --list
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('81d277306b3029090b7a2ba6cc19108ca207ea65d738487155123260b6e9525d')
expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('3db560d7104c324bcc54c94867c5f1e2b7f5eedf393d55e424b1c8d0bd5e7901')
})
test('does not leak European Portuguese UI terms', () => {
+3
View File
@@ -963,6 +963,9 @@ export default {
'Discarded. Tell me what was off and I will build a different one.': 'Verworfen. Sag mir, was nicht gepasst hat, und ich baue einen anderen.',
'Done — your plan is back to how it was before my last changes.': 'Erledigt — dein Plan ist wieder wie vor meinen letzten Änderungen.',
'Edit my answers': 'Meine Antworten bearbeiten',
'Start a new plan': 'Einen neuen Plan beginnen',
'A fresh plan from your answers; your workouts stay': 'Ein frischer Plan aus deinen Antworten; deine Trainings bleiben',
'Build me a fresh plan from my answers.': 'Erstell mir einen frischen Plan aus meinen Antworten.',
'Experience': 'Erfahrung',
'Goal, days, equipment, limits': 'Ziel, Tage, Equipment, Einschränkungen',
'Have a look at my training and tell me what you would change.': 'Schau dir mein Training an und sag mir, was du ändern würdest.',
+3
View File
@@ -946,6 +946,9 @@ export default {
'Discarded. Tell me what was off and I will build a different one.': 'Descartado. Dime qué no encajaba y haré otro distinto.',
'Done — your plan is back to how it was before my last changes.': 'Hecho: tu plan vuelve a estar como antes de mis últimos cambios.',
'Edit my answers': 'Editar mis respuestas',
'Start a new plan': 'Empezar un plan nuevo',
'A fresh plan from your answers; your workouts stay': 'Un plan nuevo a partir de tus respuestas; tus entrenamientos se conservan',
'Build me a fresh plan from my answers.': 'Hazme un plan nuevo a partir de mis respuestas.',
'Experience': 'Experiencia',
'Goal, days, equipment, limits': 'Objetivo, días, equipamiento, límites',
'Have a look at my training and tell me what you would change.': 'Mira mi entrenamiento y dime qué cambiarías.',
+3
View File
@@ -946,6 +946,9 @@ export default {
'Discarded. Tell me what was off and I will build a different one.': 'Abandonné. Dis-moi ce qui n’allait pas et j’en construis un autre.',
'Done — your plan is back to how it was before my last changes.': 'C’est fait — ton plan est revenu à l’état d’avant mes dernières modifications.',
'Edit my answers': 'Modifier mes réponses',
'Start a new plan': 'Commencer un nouveau plan',
'A fresh plan from your answers; your workouts stay': 'Un plan tout neuf à partir de tes réponses ; tes séances restent',
'Build me a fresh plan from my answers.': 'Fais-moi un plan tout neuf à partir de mes réponses.',
'Experience': 'Expérience',
'Goal, days, equipment, limits': 'Objectif, jours, matériel, limites',
'Have a look at my training and tell me what you would change.': 'Regarde mon entraînement et dis-moi ce que tu changerais.',
+3
View File
@@ -946,6 +946,9 @@ export default {
'Discarded. Tell me what was off and I will build a different one.': 'हटा दिया। बताएँ क्या ठीक नहीं था, मैं दूसरी बना दूँगा।',
'Done — your plan is back to how it was before my last changes.': 'हो गया — आपकी योजना मेरे पिछले बदलावों से पहले जैसी हो गई।',
'Edit my answers': 'मेरे उत्तर संपादित करें',
'Start a new plan': 'नई योजना शुरू करें',
'A fresh plan from your answers; your workouts stay': 'आपके जवाबों से एक नई योजना; आपके वर्कआउट बने रहेंगे',
'Build me a fresh plan from my answers.': 'मेरे जवाबों से मेरे लिए एक नई योजना बनाओ।',
'Experience': 'अनुभव',
'Goal, days, equipment, limits': 'लक्ष्य, दिन, उपकरण, सीमाएँ',
'Have a look at my training and tell me what you would change.': 'मेरा प्रशिक्षण देखो और बताओ तुम क्या बदलोगे।',
+3
View File
@@ -996,6 +996,9 @@ export default {
'Discarded. Tell me what was off and I will build a different one.': 'Elvetve. Mondd el, mi nem stimmelt, és készítek egy másikat.',
'Done — your plan is back to how it was before my last changes.': 'Kész — a terved visszaállt a legutóbbi módosításaim előtti állapotba.',
'Edit my answers': 'Válaszaim szerkesztése',
'Start a new plan': 'Új terv indítása',
'A fresh plan from your answers; your workouts stay': 'Új terv a válaszaidból; az edzéseid megmaradnak',
'Build me a fresh plan from my answers.': 'Készíts nekem új tervet a válaszaimból.',
'Experience': 'Tapasztalat',
'Goal, days, equipment, limits': 'Cél, napok, felszerelés, korlátok',
'Have a look at my training and tell me what you would change.': 'Nézd át az edzéseimet, és mondd el, min változtatnál.',
+3
View File
@@ -946,6 +946,9 @@ export default {
'Discarded. Tell me what was off and I will build a different one.': 'Scartato. Dimmi cosa non andava e ne costruisco un altro.',
'Done — your plan is back to how it was before my last changes.': 'Fatto: il tuo piano è tornato com’era prima delle mie ultime modifiche.',
'Edit my answers': 'Modifica le mie risposte',
'Start a new plan': 'Inizia un nuovo piano',
'A fresh plan from your answers; your workouts stay': 'Un piano nuovo dalle tue risposte; i tuoi allenamenti restano',
'Build me a fresh plan from my answers.': 'Preparami un piano nuovo dalle mie risposte.',
'Experience': 'Esperienza',
'Goal, days, equipment, limits': 'Obiettivo, giorni, attrezzatura, limiti',
'Have a look at my training and tell me what you would change.': 'Guarda il mio allenamento e dimmi cosa cambieresti.',
+3
View File
@@ -946,6 +946,9 @@ export default {
'Discarded. Tell me what was off and I will build a different one.': '폐기했습니다. 무엇이 맞지 않았는지 알려주시면 다른 계획을 만들게요.',
'Done — your plan is back to how it was before my last changes.': '완료 — 계획이 제 마지막 변경 전으로 돌아갔습니다.',
'Edit my answers': '내 답변 수정',
'Start a new plan': '새 계획 시작',
'A fresh plan from your answers; your workouts stay': '답변을 바탕으로 새 계획을 만듭니다. 운동 기록은 그대로 남습니다',
'Build me a fresh plan from my answers.': '내 답변을 바탕으로 새 계획을 만들어 줘.',
'Experience': '경험',
'Goal, days, equipment, limits': '목표, 요일, 장비, 제한',
'Have a look at my training and tell me what you would change.': '내 훈련을 보고 무엇을 바꿀지 알려주세요.',
+3
View File
@@ -946,6 +946,9 @@ export default {
'Discarded. Tell me what was off and I will build a different one.': 'Odrzucono. Powiedz, co było nie tak, a zbuduję inny.',
'Done — your plan is back to how it was before my last changes.': 'Gotowe — Twój plan wrócił do stanu sprzed moich ostatnich zmian.',
'Edit my answers': 'Edytuj moje odpowiedzi',
'Start a new plan': 'Zacznij nowy plan',
'A fresh plan from your answers; your workouts stay': 'Nowy plan na podstawie Twoich odpowiedzi; treningi zostają',
'Build me a fresh plan from my answers.': 'Ułóż mi nowy plan na podstawie moich odpowiedzi.',
'Experience': 'Doświadczenie',
'Goal, days, equipment, limits': 'Cel, dni, sprzęt, ograniczenia',
'Have a look at my training and tell me what you would change.': 'Przejrzyj mój trening i powiedz, co byś zmienił.',
+3
View File
@@ -946,6 +946,9 @@ export default {
'Discarded. Tell me what was off and I will build a different one.': 'Descartado. Diz-me o que não encaixou e eu faço outro.',
'Done — your plan is back to how it was before my last changes.': 'Feito — o teu plano voltou ao que era antes das minhas últimas alterações.',
'Edit my answers': 'Editar as minhas respostas',
'Start a new plan': 'Começar um plano novo',
'A fresh plan from your answers; your workouts stay': 'Um plano novo a partir das tuas respostas; os teus treinos ficam',
'Build me a fresh plan from my answers.': 'Faz-me um plano novo a partir das minhas respostas.',
'Experience': 'Experiência',
'Goal, days, equipment, limits': 'Objetivo, dias, equipamento, limitações',
'Have a look at my training and tell me what you would change.': 'Vê o meu treino e diz-me o que mudarias.',
+3
View File
@@ -946,6 +946,9 @@ export default {
'Discarded. Tell me what was off and I will build a different one.': 'Отклонено. Скажите, что не подошло, и я составлю другой.',
'Done — your plan is back to how it was before my last changes.': 'Готово — ваш план вернулся к состоянию до моих последних изменений.',
'Edit my answers': 'Изменить мои ответы',
'Start a new plan': 'Начать новый план',
'A fresh plan from your answers; your workouts stay': 'Новый план по вашим ответам; тренировки сохраняются',
'Build me a fresh plan from my answers.': 'Составь мне новый план по моим ответам.',
'Experience': 'Опыт',
'Goal, days, equipment, limits': 'Цель, дни, инвентарь, ограничения',
'Have a look at my training and tell me what you would change.': 'Посмотрите на мои тренировки и скажите, что бы вы изменили.',
+3
View File
@@ -1004,6 +1004,9 @@ export default {
'Discarded. Tell me what was off and I will build a different one.': 'ทิ้งแล้ว บอกฉันว่าอะไรไม่ถูกต้อง แล้วฉันจะสร้างแผนใหม่ให้',
'Done — your plan is back to how it was before my last changes.': 'เสร็จแล้ว — แผนของคุณกลับไปเป็นเหมือนก่อนการเปลี่ยนแปลงล่าสุดของฉัน',
'Edit my answers': 'แก้ไขคำตอบของฉัน',
'Start a new plan': 'เริ่มแผนใหม่',
'A fresh plan from your answers; your workouts stay': 'แผนใหม่จากคำตอบของคุณ การออกกำลังกายของคุณยังอยู่',
'Build me a fresh plan from my answers.': 'สร้างแผนใหม่ให้ฉันจากคำตอบของฉัน',
'Experience': 'ประสบการณ์',
'Goal, days, equipment, limits': 'เป้าหมาย วัน อุปกรณ์ ข้อจำกัด',
'Have a look at my training and tell me what you would change.': 'ดูการฝึกของฉันแล้วบอกว่าจะเปลี่ยนอะไรบ้าง',
+3
View File
@@ -946,6 +946,9 @@ export default {
'Discarded. Tell me what was off and I will build a different one.': 'Vazgeçildi. Neyin uymadığını söyle, farklı bir tane hazırlayayım.',
'Done — your plan is back to how it was before my last changes.': 'Tamam — planın son değişikliklerimden önceki haline döndü.',
'Edit my answers': 'Cevaplarımı düzenle',
'Start a new plan': 'Yeni bir plan başlat',
'A fresh plan from your answers; your workouts stay': 'Cevaplarından yeni bir plan; antrenmanların kalır',
'Build me a fresh plan from my answers.': 'Cevaplarımdan bana yeni bir plan hazırla.',
'Experience': 'Deneyim',
'Goal, days, equipment, limits': 'Hedef, günler, ekipman, sınırlar',
'Have a look at my training and tell me what you would change.': 'Antrenmanıma bak ve neyi değiştireceğini söyle.',
+3
View File
@@ -946,6 +946,9 @@ export default {
'Discarded. Tell me what was off and I will build a different one.': '已放弃。告诉我哪里不合适,我会重新制定一个。',
'Done — your plan is back to how it was before my last changes.': '完成——你的计划已恢复到我上次更改之前的状态。',
'Edit my answers': '编辑我的回答',
'Start a new plan': '开始新计划',
'A fresh plan from your answers; your workouts stay': '根据你的回答生成新计划;训练记录保留',
'Build me a fresh plan from my answers.': '根据我的回答给我制定一个新计划。',
'Experience': '经验',
'Goal, days, equipment, limits': '目标、天数、器材、限制',
'Have a look at my training and tell me what you would change.': '看看我的训练,告诉我你会改什么。',
+8 -3
View File
@@ -27,7 +27,7 @@ import {
changeTitle, changeValues, exName, canRevert, revertLast
} from '../lib/coach.js'
import { insightsFor, sessionInsights } from '../lib/coach-insights.js'
import { useCoachStatus, requestReview, requestDebrief, refinePlan, resolvePending, cohortStats, setCohortShare, JOB_ERRORS } from '../lib/coach-api.js'
import { useCoachStatus, requestReview, requestDebrief, requestPlan, refinePlan, resolvePending, cohortStats, setCohortShare, jobErrorText } from '../lib/coach-api.js'
import { confirmSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import LineChart from '../components/LineChart.jsx'
@@ -75,7 +75,7 @@ export default function CoachChat() {
if (!pending) {
const cls = lastError?.errorClass || (last?.outcome === 'failed' ? (last.errorClass || 'internal') : null)
appendChat(s, cls
? { role: 'coach', kind: 'error', text: JOB_ERRORS[cls] || JOB_ERRORS.internal }
? { role: 'coach', kind: 'error', text: jobErrorText(cls, lastError?.detail) }
: { role: 'coach', kind: 'nochange', text: last?.reading
? last.reading
: t('I looked through everything and there is nothing I would change right now. Keep going — ask me again after a few more sessions.') })
@@ -94,7 +94,10 @@ export default function CoachChat() {
if (!msg || busy) return
setBusy(true)
try {
if (pending?.kind === 'create') await refinePlan(msg)
// A message about a proposed plan refines it. With no plan at all — the first attempt
// failed, or nothing was ever built — the message asks for one; a review would only
// answer that there is no workout to look at, which is how people got stuck.
if (pending?.kind === 'create' || !(S.routines || []).length) await refinePlan(msg)
else await requestReview(msg)
update(s => appendChat(s, { role: 'user', kind: 'text', text: msg }))
setText('')
@@ -119,6 +122,7 @@ export default function CoachChat() {
const askDebrief = () => ask(() => requestDebrief(lastWorkout?.id || null), lastWorkout?.name
? t('How did my {0} session go?', lastWorkout.name)
: t('How did my last workout go?'))
const askNewPlan = () => ask(() => requestPlan(coach.profile), t('Build me a fresh plan from my answers.'))
const askImprove = r => ask(
() => requestReview(t('Focus only on my routine “{0}”. Improve it: exercise choice, order, sets and reps, rep ranges, progression. Leave the other routines alone.', r.name)),
t('Improve my routine “{0}”.', r.name))
@@ -144,6 +148,7 @@ export default function CoachChat() {
{idle && !!(S.routines || []).length && <Row icon="wrench" iconTint="var(--orange)" title={t('Improve a routine')} subtitle={t('Pick one; the Coach works on just that')} accessory="chevron" onClick={() => { close(); pickRoutine() }} />}
{community && <Row icon="person" iconTint="var(--teal)" title={t('Compare with others here')} subtitle={t('Anonymous medians from this instance')} accessory="chevron" onClick={() => { close(); showCohort() }} />}
<Row icon="history" iconTint="var(--blue)" title={t('Everything the Coach proposed')} subtitle={t('Plans, suggestions and debriefs, kept')} accessory="chevron" onClick={() => { close(); showHistory() }} />
{idle && <Row icon="sparkles" iconTint="var(--indigo)" title={t('Start a new plan')} subtitle={t('A fresh plan from your answers; your workouts stay')} accessory="chevron" onClick={() => { close(); askNewPlan() }} />}
<Row icon="clipboard" iconTint="var(--indigo)" title={t('Edit my answers')} subtitle={t('Goal, days, equipment, limits')} accessory="chevron" onClick={() => { close(); nav('/coach/intake?edit=1') }} />
<Row icon="clock" iconTint="var(--purple)" title={t('Automatic reviews')} subtitle={cadenceLabel(coach)} accessory="chevron" onClick={() => { close(); cadenceSheet(openSheet, update) }} />
{canRevert(S) && <Row icon="reset" iconTint="var(--blue)" title={t('Undo the last Coach changes')} accessory="chevron" onClick={() => { close(); doRevert() }} />}