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.

Coach: Fragebogen beim ersten Mal, dann ein Chat mit dem Coach; Admin-Dashboard lesbar

Duarte Santos18dd33e9d3dc
diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx
index 6be608b06..0d2519a27 100644
--- a/frontend/src/App.jsx
+++ b/frontend/src/App.jsx
@@ -26,9 +26,8 @@ import History from './views/History.jsx'
import Library from './views/Library.jsx'
import Settings from './views/Settings.jsx'
import Admin from './views/Admin.jsx'
-import Coach from './views/Coach.jsx'
+import CoachChat from './views/CoachChat.jsx'
import CoachIntake from './views/CoachIntake.jsx'
-import CoachProposal from './views/CoachProposal.jsx'
import CoachSetup from './views/CoachSetup.jsx'
bindUI(useUI) // lets the shared controls open sheets without importing the store at module scope
@@ -100,9 +99,9 @@ function Shell() {
{/* The Coach screens gate themselves on the instance config; the routes exist
unconditionally so a deep link from a notification lands somewhere sane
rather than on the catch-all. */}
- <Route path="/coach" element={<Coach />} />
+ <Route path="/coach" element={<CoachChat />} />
<Route path="/coach/intake" element={<CoachIntake />} />
- <Route path="/coach/proposal" element={<CoachProposal />} />
+ <Route path="/coach/proposal" element={<Navigate to="/coach" replace />} />
<Route path="/coach/setup" element={<CoachSetup />} />
<Route path="/admin" element={user?.admin ? <Admin /> : <Navigate to="/home" replace />} />
<Route path="*" element={<Navigate to="/home" replace />} />
diff --git a/frontend/src/admin.css b/frontend/src/admin.css
new file mode 100644
index 000000000..98d307b67
--- /dev/null
+++ b/frontend/src/admin.css
@@ -0,0 +1,112 @@
+/* Admin dashboard — operator-facing, English-only. Sits on top of the app's tokens; nothing
+ here is used outside views/Admin.jsx and views/AdminCoach.jsx. */
+
+.adm-intro{color:var(--label-2);font-size:14px;line-height:1.45;margin:-6px 0 16px}
+
+/* one sentence under a card heading that says what the card is for */
+.adm-lead{color:var(--label-2);font-size:13px;line-height:1.45;margin:2px 0 12px}
+
+/* status pill: a word and a colour, never a paragraph */
+.adm-pill{
+ display:inline-flex;align-items:center;gap:6px;padding:3px 10px;border-radius:999px;
+ font-size:12.5px;font-weight:600;letter-spacing:-.004em;line-height:1.5;white-space:nowrap;
+ background:var(--surface-2);color:var(--label-2)
+}
+.adm-pill::before{content:'';width:7px;height:7px;border-radius:50%;background:currentColor;flex:none}
+.adm-pill.ok{background:color-mix(in srgb,var(--green) 16%,transparent);color:var(--green)}
+.adm-pill.warn{background:color-mix(in srgb,var(--yellow) 18%,transparent);color:var(--yellow)}
+.adm-pill.bad{background:color-mix(in srgb,var(--red) 16%,transparent);color:var(--red)}
+.adm-pill.acc{background:var(--acc-soft);color:var(--acc)}
+
+/* the one-line "what state is this in" under the card title */
+.adm-status{display:flex;align-items:center;gap:8px;flex-wrap:wrap;font-size:14px;color:var(--label-2);margin:4px 0 14px;line-height:1.4}
+
+/* numbered setup steps: a <details> per step, so a finished step folds away */
+.adm-step{border-top:var(--hair) solid var(--sep);padding:2px 0}
+.adm-step:first-of-type{border-top:0}
+.adm-step>summary{
+ list-style:none;cursor:pointer;display:flex;align-items:center;gap:12px;min-height:50px;padding:6px 0;
+ -webkit-tap-highlight-color:transparent
+}
+.adm-step>summary::-webkit-details-marker{display:none}
+.adm-step>summary:active{opacity:.7}
+.adm-num{
+ width:26px;height:26px;border-radius:50%;flex:none;display:grid;place-items:center;
+ font-size:13px;font-weight:700;background:var(--surface-3);color:var(--label)
+}
+.adm-step.done .adm-num{background:var(--acc);color:var(--on-acc)}
+.adm-step.todo .adm-num{background:var(--surface-3);color:var(--label-2)}
+.adm-step-t{flex:1;min-width:0;display:flex;flex-direction:column;gap:1px}
+.adm-step-t b{font-size:16px;font-weight:600;letter-spacing:-.012em;line-height:1.25}
+.adm-step-t span{font-size:13px;color:var(--label-2);line-height:1.3}
+.adm-step>summary .chev{color:var(--label-3);font-size:14px;transition:transform .18s ease;flex:none}
+.adm-step[open]>summary .chev{transform:rotate(90deg)}
+.adm-step-b{padding:2px 0 14px 38px}
+@media (max-width:380px){.adm-step-b{padding-left:0}}
+
+/* a dim explainer that reads like a sentence, not a footnote */
+.adm-hint{font-size:13px;color:var(--label-2);line-height:1.45;margin:6px 0 10px}
+.adm-hint code{font-size:12px;background:var(--surface-2);padding:1px 5px;border-radius:5px}
+
+/* provider chips grouped under a small heading */
+.adm-group{margin:0 0 12px}
+.adm-group-t{font-size:11.5px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--label-3);margin:0 0 7px}
+.adm-chips{display:flex;flex-wrap:wrap;gap:8px}
+.adm-chips .chip{min-height:38px;display:inline-flex;align-items:center;gap:7px}
+.adm-chip-key{
+ font-size:10.5px;font-weight:700;letter-spacing:.02em;padding:1px 6px;border-radius:999px;
+ background:var(--acc-soft);color:var(--acc)
+}
+.chip.on .adm-chip-key{background:rgba(0,0,0,.18);color:inherit}
+
+/* label + control pairs inside a step */
+.adm-field{display:flex;flex-direction:column;gap:6px;margin:0 0 10px}
+.adm-field>label{font-size:13px;font-weight:600;color:var(--label-2)}
+.adm-field .field{width:100%}
+.adm-select{
+ width:100%;min-height:44px;padding:10px 38px 10px 12px;border-radius:var(--r);border:0;
+ background:var(--surface-2);color:var(--label);font-size:15px;appearance:none;-webkit-appearance:none;
+ background-image:linear-gradient(45deg,transparent 50%,var(--label-2) 50%),linear-gradient(135deg,var(--label-2) 50%,transparent 50%);
+ background-position:calc(100% - 20px) 50%,calc(100% - 14px) 50%;background-size:6px 6px;background-repeat:no-repeat
+}
+.adm-actions{display:flex;flex-wrap:wrap;gap:8px;margin-top:6px}
+.adm-actions .btn{min-height:44px}
+
+/* inline result box under the Test button */
+.adm-result{
+ margin-top:10px;padding:10px 12px;border-radius:var(--r);font-size:13.5px;line-height:1.45;
+ background:var(--surface-2);color:var(--label)
+}
+.adm-result.ok{background:color-mix(in srgb,var(--green) 14%,transparent)}
+.adm-result.bad{background:color-mix(in srgb,var(--red) 14%,transparent)}
+.adm-result b{display:block;margin-bottom:2px}
+
+/* advanced / activity folds */
+.adm-fold{border-top:var(--hair) solid var(--sep);margin-top:4px}
+.adm-fold>summary{
+ list-style:none;cursor:pointer;display:flex;align-items:center;justify-content:space-between;gap:10px;
+ min-height:48px;padding:6px 0;font-size:15px;font-weight:600;letter-spacing:-.012em
+}
+.adm-fold>summary::-webkit-details-marker{display:none}
+.adm-fold>summary .chev{color:var(--label-3);font-size:14px;transition:transform .18s ease}
+.adm-fold[open]>summary .chev{transform:rotate(90deg)}
+.adm-fold-b{padding:0 0 12px}
+
+.adm-kv{display:flex;justify-content:space-between;gap:12px;padding:9px 0;border-bottom:var(--hair) solid var(--sep);font-size:14px}
+.adm-kv:last-child{border-bottom:0}
+.adm-kv .k{color:var(--label-2);flex:none}
+.adm-kv .v{text-align:right;min-width:0;overflow-wrap:anywhere}
+.adm-kv .v input{width:72px;text-align:right}
+
+.adm-log{display:flex;flex-direction:column}
+.adm-log-row{display:flex;justify-content:space-between;gap:10px;padding:8px 0;border-bottom:var(--hair) solid var(--sep);font-size:13.5px}
+.adm-log-row:last-child{border-bottom:0}
+.adm-log-row .when{color:var(--label-3);font-size:12px;flex:none}
+
+/* users list rows with a copy affordance for invite codes */
+.adm-code{
+ font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-weight:600;letter-spacing:.08em;
+ background:var(--surface-2);padding:4px 9px;border-radius:8px;font-size:14px
+}
+.adm-iconbtn{width:44px;height:44px;border-radius:12px;font-size:17px}
+.adm-empty{color:var(--label-3);font-size:13.5px;padding:10px 2px}
diff --git a/frontend/src/coach.css b/frontend/src/coach.css
new file mode 100644
index 000000000..aaa5157f6
--- /dev/null
+++ b/frontend/src/coach.css
@@ -0,0 +1,181 @@
+/* The Coach's two screens — the questionnaire and the conversation.
+ Everything here sits on the app's tokens (index.css); nothing is redefined. */
+
+/* ---------- onboarding ---------- */
+.ob{display:flex;flex-direction:column;min-height:calc(100dvh - var(--sat) - 200px)}
+.ob-top{display:flex;align-items:center;justify-content:space-between;margin:2px 0 26px;min-height:36px}
+.ob-dots{display:flex;gap:6px;align-items:center}
+.ob-dot{width:6px;height:6px;border-radius:99px;background:var(--label-4);transition:all var(--med) var(--ease)}
+.ob-dot.on{background:var(--acc);width:18px}
+.ob-dot.done{background:var(--acc);opacity:.55}
+.ob-skip{background:none;color:var(--label-2);font-size:15px;padding:6px 2px}
+.ob-body{flex:1}
+.ob-eyebrow{color:var(--acc);font-size:13px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;margin-bottom:8px}
+.ob-h{font-size:30px;line-height:1.12;font-weight:700;letter-spacing:-.026em;margin:0 0 8px}
+.ob-p{color:var(--label-2);font-size:16px;line-height:1.45;margin:0 0 24px;letter-spacing:-.006em}
+.ob-choices{display:flex;flex-direction:column;gap:10px}
+.ob-choice{
+ display:flex;align-items:center;gap:14px;width:100%;text-align:left;
+ padding:16px 18px;border-radius:var(--r-lg);background:var(--surface);
+ font-size:17px;letter-spacing:-.012em;color:var(--label);
+ border:1.5px solid transparent;transition:border-color var(--fast),background var(--fast),transform var(--fast)
+}
+.ob-choice:active{transform:scale(.985);background:var(--surface-2)}
+.ob-choice.on{border-color:var(--acc);background:var(--acc-soft)}
+.ob-choice .icn{font-size:22px;color:var(--acc);flex:none}
+.ob-choice .ob-choice-t{flex:1}
+.ob-choice .ob-choice-s{display:block;font-size:13px;color:var(--label-2);margin-top:2px}
+.ob-choice .ob-k{color:var(--acc);font-size:18px;--icon-stroke:2.6;flex:none;opacity:0}
+.ob-choice.on .ob-k{opacity:1}
+.ob-days{display:grid;grid-template-columns:repeat(7,1fr);gap:8px;margin:6px 0 4px}
+.ob-day{
+ aspect-ratio:1;border-radius:99px;background:var(--surface);color:var(--label);
+ font-size:20px;font-weight:600;display:flex;align-items:center;justify-content:center;
+ border:1.5px solid transparent;transition:all var(--fast)
+}
+.ob-day.on{background:var(--acc);color:var(--on-acc);border-color:var(--acc)}
+.ob-day:active{transform:scale(.94)}
+.ob-week{display:grid;grid-template-columns:repeat(7,1fr);gap:6px;margin-top:6px}
+.ob-wd{
+ padding:10px 0 9px;border-radius:var(--r);background:var(--surface);text-align:center;
+ font-size:13px;font-weight:600;color:var(--label-2);border:1.5px solid transparent;transition:all var(--fast)
+}
+.ob-wd.on{color:var(--acc);border-color:var(--acc);background:var(--acc-soft)}
+.ob-sub{font-size:15px;color:var(--label-2);margin:22px 0 10px;letter-spacing:-.006em}
+.ob-time{
+ display:flex;align-items:center;justify-content:center;gap:10px;
+ background:var(--surface);border-radius:var(--r-xl);padding:26px 18px;margin-top:4px
+}
+.ob-time input[type=time]{
+ font-size:44px;font-weight:600;letter-spacing:-.03em;background:none;border:none;color:var(--label);
+ font-variant-numeric:tabular-nums;padding:0;outline:none;text-align:center;width:auto;min-width:180px;
+ -webkit-appearance:none;appearance:none;color-scheme:dark
+}
+:root[data-theme="light"] .ob-time input[type=time]{color-scheme:light}
+.ob-time input[type=time]::-webkit-calendar-picker-indicator{display:none}
+.ob-time .ob-time-l{font-size:15px;color:var(--label-2)}
+.ob-quick{display:flex;gap:7px;justify-content:center;flex-wrap:wrap;margin-top:12px}
+.ob-chips{display:flex;flex-wrap:wrap;gap:8px}
+.ob-chips .chip{padding:10px 16px;font-size:15px;border:1.5px solid transparent}
+.ob-chips .chip.on{background:var(--acc-soft);color:var(--acc);border-color:var(--acc)}
+.ob-field{margin-bottom:14px}
+.ob-field .field{font-size:16px}
+.ob-note{font-size:13px;line-height:1.45;color:var(--label-2);margin-top:10px}
+.ob-note.warn{color:var(--yellow)}
+.ob-consent{display:flex;flex-direction:column;gap:10px;margin-bottom:18px}
+.ob-consent-row{display:flex;gap:12px;align-items:flex-start;background:var(--surface);border-radius:var(--r-lg);padding:13px 15px}
+.ob-consent-row .icn{color:var(--acc);font-size:19px;flex:none;margin-top:2px}
+.ob-consent-row b{display:block;font-size:15px;font-weight:600;margin-bottom:2px;letter-spacing:-.008em}
+.ob-consent-row span{font-size:13px;color:var(--label-2);line-height:1.4}
+.ob-fine{font-size:13px;color:var(--label-2);line-height:1.5;display:grid;gap:8px;margin-bottom:20px}
+.ob-foot{position:sticky;bottom:calc(84px + var(--sab));padding:12px 0 4px;background:linear-gradient(to top,var(--bg) 70%,transparent);display:flex;gap:10px;margin-top:18px}
+.ob-foot .btn{font-size:17px;padding:15px 18px;border-radius:var(--r-lg)}
+.ob-hint{text-align:center;font-size:13px;color:var(--label-3);margin-top:8px}
+
+/* ---------- chat ---------- */
+.chat{padding-bottom:96px}
+.chat-hdr{display:flex;align-items:center;gap:10px;margin:2px 0 14px}
+.chat-hdr .chat-av{
+ width:38px;height:38px;border-radius:99px;background:var(--acc);color:var(--on-acc);
+ display:flex;align-items:center;justify-content:center;font-size:20px;flex:none
+}
+.chat-hdr h1{font-size:20px;font-weight:700;letter-spacing:-.02em;margin:0;line-height:1.1}
+.chat-hdr .chat-st{font-size:13px;color:var(--label-2);margin-top:2px}
+.chat-hdr .chat-st.live{color:var(--acc)}
+.chat-hdr .grow{flex:1;min-width:0}
+.msgs{display:flex;flex-direction:column;gap:10px}
+.msg{display:flex;flex-direction:column;max-width:88%;animation:msg-in var(--med) var(--ease)}
+.msg.coach{align-self:flex-start}
+.msg.user{align-self:flex-end;align-items:flex-end}
+.bub{
+ padding:11px 15px;border-radius:20px;font-size:16px;line-height:1.42;letter-spacing:-.008em;
+ background:var(--surface);color:var(--label);white-space:pre-wrap;word-break:break-word
+}
+.msg.coach .bub{border-bottom-left-radius:6px}
+.msg.user .bub{background:var(--acc);color:var(--on-acc);border-bottom-right-radius:6px}
+.bub.err{background:color-mix(in srgb,var(--red) 14%,var(--surface));color:var(--label)}
+.bub.sys{background:none;color:var(--label-2);font-size:13px;text-align:center;padding:4px 8px;align-self:center;max-width:100%}
+.msg.sys{align-self:center;max-width:100%;align-items:center}
+.bub ul{margin:6px 0 0;padding-left:18px}
+.bub li{margin:2px 0}
+.msg-t{font-size:11px;color:var(--label-3);margin:4px 8px 0}
+.typing{display:flex;align-items:center;gap:5px;padding:14px 16px;min-width:64px}
+.typing i{width:8px;height:8px;border-radius:99px;background:var(--label-2);animation:typing 1.2s infinite ease-in-out}
+.typing i:nth-child(2){animation-delay:.15s}
+.typing i:nth-child(3){animation-delay:.3s}
+.typing-eta{font-size:13px;color:var(--label-2);margin:6px 8px 0;line-height:1.4}
+@keyframes typing{0%,80%,100%{transform:translateY(0);opacity:.45}40%{transform:translateY(-4px);opacity:1}}
+@keyframes msg-in{from{opacity:0;transform:translateY(6px)}to{opacity:1;transform:none}}
+
+/* the proposal, as a card inside the coach's column */
+.pcard{
+ background:var(--surface);border-radius:var(--r-xl);overflow:hidden;width:100%;
+ border:1px solid var(--sep-op)
+}
+.pcard-hd{padding:16px 18px 6px}
+.pcard-eyebrow{font-size:12px;font-weight:600;letter-spacing:.05em;text-transform:uppercase;color:var(--acc);margin-bottom:4px}
+.pcard-h{font-size:22px;font-weight:700;letter-spacing:-.022em;line-height:1.15;margin:0}
+.pcard-sum{font-size:15px;color:var(--label-2);line-height:1.45;margin:8px 0 0}
+.pcard-tabs{display:flex;gap:6px;overflow-x:auto;padding:12px 18px 4px;scrollbar-width:none}
+.pcard-tabs::-webkit-scrollbar{display:none}
+.pcard-tab{
+ flex:none;padding:8px 14px;border-radius:99px;background:var(--surface-2);color:var(--label-2);
+ font-size:14px;font-weight:500;transition:all var(--fast);white-space:nowrap
+}
+.pcard-tab.on{background:var(--label);color:var(--bg)}
+.pcard-rt{padding:10px 18px 4px}
+.pcard-rt-h{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
+.pcard-rt-h b{font-size:18px;font-weight:600;letter-spacing:-.015em}
+.pcard-rt-h span{font-size:13px;color:var(--label-2);white-space:nowrap}
+.pcard-why{font-size:14px;color:var(--label-2);line-height:1.45;margin:4px 0 8px}
+.pcard-ex{padding:11px 0;border-top:var(--hair) solid var(--sep)}
+.pcard-ex:first-of-type{border-top:none}
+.pcard-ex-r{display:flex;justify-content:space-between;gap:10px;align-items:baseline}
+.pcard-ex-n{font-size:16px;font-weight:500;letter-spacing:-.01em;text-transform:capitalize}
+.pcard-ex-l{font-size:14px;color:var(--label-2);white-space:nowrap;font-variant-numeric:tabular-nums}
+.pcard-ex-w{font-size:13px;color:var(--label-2);line-height:1.42;margin-top:3px}
+.pcard-week{display:flex;gap:5px;padding:10px 18px 4px}
+.pcard-wd{flex:1;text-align:center;font-size:11px;font-weight:600;padding:7px 0;border-radius:var(--r-sm);background:var(--surface-2);color:var(--label-3)}
+.pcard-wd.on{background:var(--acc-soft);color:var(--acc)}
+.pcard-row{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:12px 18px;border-top:var(--hair) solid var(--sep)}
+.pcard-row .lrow-t{font-size:15px}
+.pcard-row .lrow-s{font-size:12px}
+.pcard-ft{padding:12px 18px 16px;display:flex;flex-direction:column;gap:8px;border-top:var(--hair) solid var(--sep)}
+.pcard-ft .btn{font-size:16px;padding:14px 18px;border-radius:var(--r-lg)}
+.pcard-note{font-size:12px;color:var(--yellow);line-height:1.45;padding:0 18px 6px}
+.pcard-chg{display:flex;gap:12px;align-items:flex-start;padding:12px 18px;border-top:var(--hair) solid var(--sep)}
+.pcard-chg.stale{opacity:.5}
+.pcard-chg .grow{flex:1;min-width:0}
+.pcard-chg-t{font-size:15px;font-weight:600;letter-spacing:-.01em;text-transform:capitalize}
+.pcard-chg-v{display:flex;align-items:center;gap:6px;margin:4px 0;font-size:13px}
+.pcard-chg-v .tag{font-size:12px}
+.pcard-chg-w{font-size:13px;color:var(--label-2);line-height:1.42}
+.pcard-chg-stale{font-size:12px;color:var(--yellow);margin-top:4px}
+.pcard-notes{padding:10px 18px 4px;border-top:var(--hair) solid var(--sep)}
+.pcard-notes div{font-size:13px;color:var(--label-2);line-height:1.45;padding:4px 0}
+
+/* composer */
+.composer{
+ position:fixed;left:0;right:0;bottom:calc(78px + var(--sab));z-index:40;
+ padding:8px var(--pad) 10px;
+ background:color-mix(in srgb,var(--bg) 88%,transparent);
+ -webkit-backdrop-filter:saturate(180%) blur(12px);backdrop-filter:saturate(180%) blur(12px)
+}
+.composer-in{max-width:560px;margin:0 auto;display:flex;gap:8px;align-items:flex-end}
+.composer textarea{
+ flex:1;min-height:44px;max-height:120px;resize:none;border-radius:22px;padding:11px 16px;
+ font-size:16px;line-height:1.35;background:var(--surface);color:var(--label);border:none;outline:none;
+ font-family:inherit;letter-spacing:-.008em
+}
+.composer textarea:focus{box-shadow:inset 0 0 0 1.5px var(--acc)}
+.composer textarea::placeholder{color:var(--label-3)}
+.send{
+ width:44px;height:44px;border-radius:99px;background:var(--acc);color:var(--on-acc);flex:none;
+ display:flex;align-items:center;justify-content:center;font-size:20px;transition:transform var(--fast),opacity var(--fast)
+}
+.send:active{transform:scale(.92)}
+.send:disabled{opacity:.3}
+.composer-cap{max-width:560px;margin:4px auto 0;text-align:center;font-size:11px;color:var(--label-3)}
+
+/* menu sheet rows reuse .lrow; the cadence sub-sheet reuses Section */
+.chat-menu .lrow-t{font-size:17px}
diff --git a/frontend/src/lib/coach-local.js b/frontend/src/lib/coach-local.js
index 7098030a7..c9c6e36b3 100644
--- a/frontend/src/lib/coach-local.js
+++ b/frontend/src/lib/coach-local.js
@@ -37,6 +37,7 @@ const HANDLE_LENGTH = 16
let job = null
let lastError = null
+let last = null // how the most recent job ended — the same shape the server's status() reports
// Reported to the screens through the same status shape the server answers with; a toast is
// also raised because on the server a failed job lands in the admin card, and here there is
// no admin card — the user is the operator.
@@ -80,7 +81,7 @@ 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 }
+ return { job, pending: (await loadCoachDevice()).pending || null, cap: await capState(), lastError, last }
}
export const localReview = (S, note) => start(S, 'review', { note: note ? String(note).slice(0, 1000) : null })
@@ -145,10 +146,12 @@ async function run(S, kind, opts, d, adapter) {
})
if (!attempt.ok) {
lastError = { errorClass: attempt.errorClass, detail: attempt.detail || null }
+ 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 })
return
}
if (attempt.nochange) {
+ last = { id: job.id, kind, outcome: 'nochange', errorClass: null, at: Date.now(), reading: attempt.reading }
if (notify) notify({ kind: 'nochange', reading: attempt.reading })
return
}
@@ -158,8 +161,9 @@ async function run(S, kind, opts, d, adapter) {
...attempt.result
}
await saveCoachDevice({ pending })
+ last = { id: job.id, kind, outcome: 'ready', errorClass: null, at: Date.now() }
if (notify) notify({ kind: 'ready', pending })
}
// Test seam.
-export function _resetLocal() { job = null; lastError = null }
+export function _resetLocal() { job = null; lastError = null; last = null }
diff --git a/frontend/src/lib/coach.js b/frontend/src/lib/coach.js
index bd8508b27..73e9eb460 100644
--- a/frontend/src/lib/coach.js
+++ b/frontend/src/lib/coach.js
@@ -27,10 +27,18 @@ export const CONSENT_VERSION = 1
// ~75 KB; the namespace guard is the backstop for the case nobody predicted.
export const SNAPSHOT_MAX = 3
export const LOG_MAX = 50
+export const CHAT_MAX = 40
+export const TIMINGS_MAX = 5
const NAMESPACE_MAX = 256 * 1024
export const emptyCoach = () => ({
- consent: null, profile: null, cadence: 'off', lastReview: null, log: [], snapshots: []
+ consent: null, profile: null, cadence: 'off', lastReview: null, log: [], snapshots: [],
+ // The conversation as the user saw it (views/CoachChat.jsx): their messages, and what the
+ // Coach did with them. Short, synced, and trimmed with the log — the proposal itself lives
+ // server-side (or in the phone's device file) until it is applied or dismissed.
+ chat: [],
+ // How long the last few jobs took, so the typing bubble can say "usually about 2 minutes".
+ timings: []
})
const coachOf = s => (s.coach = s.coach || emptyCoach())
@@ -267,12 +275,57 @@ function trim(s) {
const c = coachOf(s)
let guard = 0
while (JSON.stringify(c).length > NAMESPACE_MAX && guard++ < 60) {
- if ((c.snapshots || []).length > 1) c.snapshots.shift()
+ if ((c.chat || []).length > 8) c.chat.shift()
+ else if ((c.snapshots || []).length > 1) c.snapshots.shift()
else if ((c.log || []).length > 1) c.log.shift()
else break
}
}
+/* ============================ the conversation ============================ */
+
+/**
+ * One line of the chat: `{ id, role: 'user'|'coach', kind, text?, at, ref? }`.
+ * kinds — user: 'intake' (the questionnaire, rendered from the live profile), 'text';
+ * coach: 'text', 'applied', 'dismissed', 'reverted', 'error', 'nochange'.
+ */
+export function appendChat(s, entry) {
+ const c = coachOf(s)
+ c.chat = [...(c.chat || []), { id: entry.id || uid(), at: entry.at || Date.now(), ...entry }].slice(-CHAT_MAX)
+ trim(s)
+}
+
+/** A job just finished: remember how long it took, for the next typing bubble. */
+export function recordTiming(s, ms) {
+ if (!(ms > 0)) return
+ const c = coachOf(s)
+ c.timings = [...(c.timings || []), Math.round(ms)].slice(-TIMINGS_MAX)
+}
+/** Median of the observed job durations, or null before any. */
+export function estimateMs(S) {
+ const arr = [...(S?.coach?.timings || [])].filter(n => n > 0).sort((a, b) => a - b)
+ if (!arr.length) return null
+ return arr[Math.floor(arr.length / 2)]
+}
+
+/** The questionnaire, as the lines the chat shows back to the user. */
+export function profileLines(p) {
+ if (!p) return []
+ const goal = { strength: 'Get stronger', muscle: 'Build muscle', general: 'General fitness', fatloss: 'Lose fat', endurance: 'Endurance' }[p.goal]
+ const exp = { new: 'New to lifting', returning: 'Coming back after a break', regular: 'Training regularly' }[p.experience]
+ const lines = []
+ if (goal) lines.push(t(goal))
+ if (exp) lines.push(t(exp))
+ if (p.daysPerWeek) lines.push(t('{0} days a week', p.daysPerWeek))
+ if (p.sessionMin) lines.push(t('{0} min per session', p.sessionMin))
+ if (p.equipment?.length) lines.push(p.equipment.join(', '))
+ if (p.limitations) lines.push(t('Limits: {0}', p.limitations))
+ if (p.likes) lines.push(t('Likes: {0}', p.likes))
+ if (p.dislikes) lines.push(t('Avoid: {0}', p.dislikes))
+ if (p.notes) lines.push(p.notes)
+ return lines
+}
+
/* ============================ applying a created plan ============================ */
/**
diff --git a/frontend/src/lib/pt-br-locale.test.js b/frontend/src/lib/pt-br-locale.test.js
index a83921f2f..b19b451d9 100644
--- a/frontend/src/lib/pt-br-locale.test.js
+++ b/frontend/src/lib/pt-br-locale.test.js
@@ -27,11 +27,11 @@ describe('Brazilian Portuguese locale', () => {
.sort(byCodeUnit)
const fingerprint = createHash('sha256').update(JSON.stringify(inherited)).digest('hex')
- expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(390)
- expect(inherited).toHaveLength(522)
+ expect(Object.keys(PT_BR_OVERRIDES)).toHaveLength(422)
+ expect(inherited).toHaveLength(541)
// 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('215c0ce2464d4ab771a208158dcc005f26f8538c15023fb5ff77828dfbc235f5')
+ expect(fingerprint, 'pt-PT inheritance changed; review the inherited pt-BR wording').toBe('d4f338190ba41fe089ddb45049a812c36fbbda0887cc4f6ab073114c98a49e90')
})
test('does not leak European Portuguese UI terms', () => {
diff --git a/frontend/src/locales/de.js b/frontend/src/locales/de.js
index 34bc3d443..67029e06b 100644
--- a/frontend/src/locales/de.js
+++ b/frontend/src/locales/de.js
@@ -867,5 +867,58 @@ export default {
'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'Auf deinem Server ist kein Coach aktiviert — frag den Admin, oder nutze unten deinen eigenen Schlüssel.',
'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'Dein Server betreibt den Coach mit dem Anbieter, den sein Admin eingerichtet hat. Über das ohnehin Synchronisierte hinaus verlässt nichts Neues dieses Handy.',
'Loading the exercise catalogue…': 'Übungskatalog wird geladen…',
- 'Checking the endpoint…': 'Endpunkt wird geprüft…'
+ 'Checking the endpoint…': 'Endpunkt wird geprüft…',
+
+ // --- AI Coach chat ---
+ 'A local model can take longer.': 'Ein lokales Modell kann länger brauchen.',
+ 'All optional. The more the Coach knows, the less it guesses.': 'Alles optional. Je mehr der Coach weiß, desto weniger muss er raten.',
+ 'Almost there': 'Fast geschafft',
+ 'Ask for a review, or tell the Coach something…': 'Um eine Auswertung bitten oder dem Coach etwas sagen…',
+ 'Avoid: {0}': 'Vermeiden: {0}',
+ 'Before we start': 'Bevor wir loslegen',
+ 'Building your plan…': 'Dein Plan wird erstellt…',
+ 'Continue': 'Weiter',
+ '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',
+ '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.',
+ 'Here is what I am working with:': 'Das sind meine Voraussetzungen:',
+ 'Hi — I’m your Coach. I build your plan from your answers and adjust it from what you actually log. Nothing changes until you say so.': 'Hi — ich bin dein Coach. Ich baue deinen Plan aus deinen Antworten und passe ihn an das an, was du wirklich einträgst. Nichts ändert sich, bevor du es sagst.',
+ 'I looked through everything and there is nothing I would change right now. Keep going — ask me again after a few more sessions.': 'Ich habe alles durchgesehen und würde gerade nichts ändern. Mach weiter — frag mich nach ein paar weiteren Einheiten nochmal.',
+ 'I understand — let’s go': 'Verstanden — los geht’s',
+ 'Imported — {0} routines are in your plan and your week is set. See you at the next session.': 'Übernommen — {0} Routinen sind in deinem Plan und deine Woche steht. Bis zur nächsten Einheit.',
+ 'Imported — {0} routines are in your plan. Your week is unchanged; schedule them whenever you like.': 'Übernommen — {0} Routinen sind in deinem Plan. Deine Woche bleibt unverändert; plane sie ein, wann du willst.',
+ 'It designs your plan from a few answers and adjusts it from what you actually log. It never changes anything without your say-so, and you can undo every change.': 'Er entwirft deinen Plan aus ein paar Antworten und passt ihn an das an, was du wirklich einträgst. Er ändert nie etwas ohne dein Okay, und jede Änderung lässt sich rückgängig machen.',
+ 'Likes: {0}': 'Mag: {0}',
+ 'Limits': 'Einschränkungen',
+ 'Limits: {0}': 'Einschränkungen: {0}',
+ 'Not quite right? Say what to change below and I will revise the whole plan.': 'Nicht ganz richtig? Schreib unten, was sich ändern soll, und ich überarbeite den ganzen Plan.',
+ 'Pick one to continue.': 'Wähle eins, um weiterzumachen.',
+ 'Pick what you will actually keep, not the best week you can imagine.': 'Wähle, was du wirklich durchhältst — nicht die beste Woche, die du dir vorstellen kannst.',
+ 'Reading your training…': 'Dein Training wird gelesen…',
+ 'Schedule': 'Zeitplan',
+ 'Send': 'Senden',
+ 'Sent straight to {0} with your own API key — you pay for every request.': 'Geht direkt mit deinem eigenen API-Schlüssel an {0} — du bezahlst jede Anfrage.',
+ 'Sent to {0}, running on this server under the instance owner’s account.': 'Geht an {0}, das auf diesem Server im Konto des Betreibers läuft.',
+ 'Session length': 'Trainingsdauer',
+ 'Sets the pace of progression, and how much the Coach assumes you know.': 'Bestimmt das Tempo der Progression und wie viel der Coach voraussetzt.',
+ 'Suggestions': 'Vorschläge',
+ 'Tell the Coach what to change…': 'Sag dem Coach, was sich ändern soll…',
+ 'The Coach builds the whole plan around this.': 'Darum herum baut der Coach den ganzen Plan.',
+ 'This usually takes a minute or two.': 'Das dauert meist ein bis zwei Minuten.',
+ 'Understood — I will not suggest these again without new evidence.': 'Verstanden — ohne neue Hinweise schlage ich das nicht wieder vor.',
+ 'Usually about {0} min.': 'Dauert meist etwa {0} Min.',
+ 'Usually under a minute.': 'Dauert meist unter einer Minute.',
+ 'Wait for the Coach to finish…': 'Warte, bis der Coach fertig ist…',
+ 'What it reads': 'Was er liest',
+ 'What would the Coach change after your last sessions?': 'Was würde der Coach nach deinen letzten Einheiten ändern?',
+ 'You can leave — it keeps going.': 'Du kannst gehen — es läuft weiter.',
+ 'Your goal': 'Dein Ziel',
+ 'h:mm': 'h:mm',
+ 'has a suggestion for you': 'hat einen Vorschlag für dich',
+ 'here when you need it': 'da, wenn du ihn brauchst',
+ 'thinking…': 'denkt nach…',
+ '{0} min per session': '{0} Min. pro Einheit'
}
diff --git a/frontend/src/locales/es.js b/frontend/src/locales/es.js
index e8dae0bdc..de2a2b585 100644
--- a/frontend/src/locales/es.js
+++ b/frontend/src/locales/es.js
@@ -850,5 +850,58 @@ export default {
'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'Tu servidor no tiene el entrenador activado: pregunta a su administrador o usa tu propia clave abajo.',
'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'Tu servidor ejecuta el entrenador con el proveedor que configuró su administrador. Nada nuevo sale de este teléfono más allá de lo que ya se sincroniza.',
'Loading the exercise catalogue…': 'Cargando el catálogo de ejercicios…',
- 'Checking the endpoint…': 'Comprobando el endpoint…'
+ 'Checking the endpoint…': 'Comprobando el endpoint…',
+
+ // --- AI Coach chat ---
+ 'A local model can take longer.': 'Un modelo local puede tardar más.',
+ 'All optional. The more the Coach knows, the less it guesses.': 'Todo opcional. Cuanto más sepa el entrenador, menos tendrá que adivinar.',
+ 'Almost there': 'Ya casi',
+ 'Ask for a review, or tell the Coach something…': 'Pide una revisión o cuéntale algo al entrenador…',
+ 'Avoid: {0}': 'Evitar: {0}',
+ 'Before we start': 'Antes de empezar',
+ 'Building your plan…': 'Creando tu plan…',
+ 'Continue': 'Continuar',
+ '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',
+ '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.',
+ 'Here is what I am working with:': 'Esto es con lo que cuento:',
+ 'Hi — I’m your Coach. I build your plan from your answers and adjust it from what you actually log. Nothing changes until you say so.': 'Hola, soy tu entrenador. Construyo tu plan a partir de tus respuestas y lo ajusto según lo que realmente registras. Nada cambia hasta que tú lo digas.',
+ 'I looked through everything and there is nothing I would change right now. Keep going — ask me again after a few more sessions.': 'Lo he revisado todo y ahora mismo no cambiaría nada. Sigue así y pregúntame de nuevo tras unas sesiones más.',
+ 'I understand — let’s go': 'Entendido, vamos',
+ 'Imported — {0} routines are in your plan and your week is set. See you at the next session.': 'Importado: {0} rutinas están en tu plan y tu semana ya está configurada. Nos vemos en la próxima sesión.',
+ 'Imported — {0} routines are in your plan. Your week is unchanged; schedule them whenever you like.': 'Importado: {0} rutinas están en tu plan. Tu semana no cambia; prográmalas cuando quieras.',
+ 'It designs your plan from a few answers and adjusts it from what you actually log. It never changes anything without your say-so, and you can undo every change.': 'Diseña tu plan a partir de unas pocas respuestas y lo ajusta según lo que realmente registras. Nunca cambia nada sin tu permiso, y puedes deshacer cada cambio.',
+ 'Likes: {0}': 'Le gusta: {0}',
+ 'Limits': 'Límites',
+ 'Limits: {0}': 'Límites: {0}',
+ 'Not quite right? Say what to change below and I will revise the whole plan.': '¿No es lo que buscabas? Escribe abajo qué cambiar y revisaré todo el plan.',
+ 'Pick one to continue.': 'Elige una opción para continuar.',
+ 'Pick what you will actually keep, not the best week you can imagine.': 'Elige lo que de verdad vas a mantener, no la mejor semana que puedas imaginar.',
+ 'Reading your training…': 'Leyendo tu entrenamiento…',
+ 'Schedule': 'Horario',
+ 'Send': 'Enviar',
+ 'Sent straight to {0} with your own API key — you pay for every request.': 'Se envía directamente a {0} con tu propia clave de API: tú pagas cada solicitud.',
+ 'Sent to {0}, running on this server under the instance owner’s account.': 'Se envía a {0}, que se ejecuta en este servidor con la cuenta del propietario.',
+ 'Session length': 'Duración de la sesión',
+ 'Sets the pace of progression, and how much the Coach assumes you know.': 'Marca el ritmo de progresión y cuánto asume el entrenador que ya sabes.',
+ 'Suggestions': 'Sugerencias',
+ 'Tell the Coach what to change…': 'Dile al entrenador qué cambiar…',
+ 'The Coach builds the whole plan around this.': 'El entrenador construye todo el plan en torno a esto.',
+ 'This usually takes a minute or two.': 'Suele tardar uno o dos minutos.',
+ 'Understood — I will not suggest these again without new evidence.': 'Entendido: no volveré a sugerirlo sin nuevas evidencias.',
+ 'Usually about {0} min.': 'Suele tardar unos {0} min.',
+ 'Usually under a minute.': 'Suele tardar menos de un minuto.',
+ 'Wait for the Coach to finish…': 'Espera a que el entrenador termine…',
+ 'What it reads': 'Qué lee',
+ 'What would the Coach change after your last sessions?': '¿Qué cambiaría el entrenador tras tus últimas sesiones?',
+ 'You can leave — it keeps going.': 'Puedes salir: sigue en marcha.',
+ 'Your goal': 'Tu objetivo',
+ 'h:mm': 'h:mm',
+ 'has a suggestion for you': 'tiene una sugerencia para ti',
+ 'here when you need it': 'aquí cuando lo necesites',
+ 'thinking…': 'pensando…',
+ '{0} min per session': '{0} min por sesión'
}
diff --git a/frontend/src/locales/fr.js b/frontend/src/locales/fr.js
index 915c2c8a5..33dd6f5b9 100644
--- a/frontend/src/locales/fr.js
+++ b/frontend/src/locales/fr.js
@@ -850,5 +850,58 @@ export default {
'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'Aucun coach n’est activé sur ton serveur — demande à son admin, ou utilise ta propre clé ci-dessous.',
'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'Ton serveur fait tourner le coach avec le fournisseur choisi par son admin. Rien de nouveau ne quitte ce téléphone au-delà de ce qui se synchronise déjà.',
'Loading the exercise catalogue…': 'Chargement du catalogue d’exercices…',
- 'Checking the endpoint…': 'Vérification du point d’accès…'
+ 'Checking the endpoint…': 'Vérification du point d’accès…',
+
+ // --- AI Coach chat ---
+ 'A local model can take longer.': 'Un modèle local peut prendre plus de temps.',
+ 'All optional. The more the Coach knows, the less it guesses.': 'Tout est facultatif. Plus le coach en sait, moins il devine.',
+ 'Almost there': 'Presque fini',
+ 'Ask for a review, or tell the Coach something…': 'Demande une révision, ou dis quelque chose au coach…',
+ 'Avoid: {0}': 'À éviter : {0}',
+ 'Before we start': 'Avant de commencer',
+ 'Building your plan…': 'Création de ton plan…',
+ 'Continue': 'Continuer',
+ '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',
+ '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.',
+ 'Here is what I am working with:': 'Voici ce dont je dispose :',
+ 'Hi — I’m your Coach. I build your plan from your answers and adjust it from what you actually log. Nothing changes until you say so.': 'Salut — je suis ton coach. Je construis ton plan à partir de tes réponses et je l’ajuste d’après ce que tu enregistres vraiment. Rien ne change sans ton accord.',
+ 'I looked through everything and there is nothing I would change right now. Keep going — ask me again after a few more sessions.': 'J’ai tout passé en revue et je ne changerais rien pour l’instant. Continue — redemande-moi après quelques séances.',
+ 'I understand — let’s go': 'Compris — c’est parti',
+ 'Imported — {0} routines are in your plan and your week is set. See you at the next session.': 'Importé — {0} routines sont dans ton plan et ta semaine est réglée. À la prochaine séance.',
+ 'Imported — {0} routines are in your plan. Your week is unchanged; schedule them whenever you like.': 'Importé — {0} routines sont dans ton plan. Ta semaine ne change pas ; planifie-les quand tu veux.',
+ 'It designs your plan from a few answers and adjusts it from what you actually log. It never changes anything without your say-so, and you can undo every change.': 'Il conçoit ton plan à partir de quelques réponses et l’ajuste d’après ce que tu enregistres vraiment. Il ne change jamais rien sans ton accord, et chaque modification peut être annulée.',
+ 'Likes: {0}': 'Aime : {0}',
+ 'Limits': 'Limites',
+ 'Limits: {0}': 'Limites : {0}',
+ 'Not quite right? Say what to change below and I will revise the whole plan.': 'Pas tout à fait ça ? Dis-moi ci-dessous quoi changer et je revois tout le plan.',
+ 'Pick one to continue.': 'Choisis-en une pour continuer.',
+ 'Pick what you will actually keep, not the best week you can imagine.': 'Choisis ce que tu tiendras vraiment, pas la meilleure semaine imaginable.',
+ 'Reading your training…': 'Lecture de ton entraînement…',
+ 'Schedule': 'Planning',
+ 'Send': 'Envoyer',
+ 'Sent straight to {0} with your own API key — you pay for every request.': 'Envoyé directement à {0} avec ta propre clé API — tu paies chaque requête.',
+ 'Sent to {0}, running on this server under the instance owner’s account.': 'Envoyé à {0}, exécuté sur ce serveur avec le compte du propriétaire de l’instance.',
+ 'Session length': 'Durée de la séance',
+ 'Sets the pace of progression, and how much the Coach assumes you know.': 'Détermine le rythme de progression, et ce que le coach suppose que tu sais déjà.',
+ 'Suggestions': 'Suggestions',
+ 'Tell the Coach what to change…': 'Dis au coach quoi changer…',
+ 'The Coach builds the whole plan around this.': 'Le coach construit tout le plan autour de ça.',
+ 'This usually takes a minute or two.': 'Ça prend en général une ou deux minutes.',
+ 'Understood — I will not suggest these again without new evidence.': 'Compris — je ne le proposerai plus sans nouveaux éléments.',
+ 'Usually about {0} min.': 'En général environ {0} min.',
+ 'Usually under a minute.': 'En général moins d’une minute.',
+ 'Wait for the Coach to finish…': 'Attends que le coach ait fini…',
+ 'What it reads': 'Ce qu’il lit',
+ 'What would the Coach change after your last sessions?': 'Que changerait le coach après tes dernières séances ?',
+ 'You can leave — it keeps going.': 'Tu peux partir — ça continue.',
+ 'Your goal': 'Ton objectif',
+ 'h:mm': 'h:mm',
+ 'has a suggestion for you': 'a une suggestion pour toi',
+ 'here when you need it': 'là quand tu en as besoin',
+ 'thinking…': 'réfléchit…',
+ '{0} min per session': '{0} min par séance'
}
diff --git a/frontend/src/locales/hi.js b/frontend/src/locales/hi.js
index cc8f738d6..4f79d8605 100644
--- a/frontend/src/locales/hi.js
+++ b/frontend/src/locales/hi.js
@@ -850,5 +850,58 @@ export default {
'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'आपके सर्वर पर कोच सक्षम नहीं है — इसके एडमिन से पूछें, या नीचे अपनी कुंजी इस्तेमाल करें।',
'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'आपका सर्वर उस प्रदाता से कोच चलाता है जिसे उसके एडमिन ने सेट किया है। जो पहले से सिंक होता है उसके अलावा इस फ़ोन से कुछ नया बाहर नहीं जाता।',
'Loading the exercise catalogue…': 'व्यायाम सूची लोड हो रही है…',
- 'Checking the endpoint…': 'एंडपॉइंट जाँचा जा रहा है…'
+ 'Checking the endpoint…': 'एंडपॉइंट जाँचा जा रहा है…',
+
+ // --- AI Coach chat ---
+ 'A local model can take longer.': 'स्थानीय मॉडल में अधिक समय लग सकता है।',
+ 'All optional. The more the Coach knows, the less it guesses.': 'सब वैकल्पिक है। कोच जितना अधिक जानेगा, उतना कम अनुमान लगाएगा।',
+ 'Almost there': 'लगभग हो गया',
+ 'Ask for a review, or tell the Coach something…': 'समीक्षा माँगें, या कोच को कुछ बताएँ…',
+ 'Avoid: {0}': 'बचें: {0}',
+ 'Before we start': 'शुरू करने से पहले',
+ 'Building your plan…': 'आपकी योजना बन रही है…',
+ 'Continue': 'जारी रखें',
+ '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': 'मेरे उत्तर संपादित करें',
+ 'Experience': 'अनुभव',
+ 'Goal, days, equipment, limits': 'लक्ष्य, दिन, उपकरण, सीमाएँ',
+ 'Have a look at my training and tell me what you would change.': 'मेरा प्रशिक्षण देखो और बताओ तुम क्या बदलोगे।',
+ 'Here is what I am working with:': 'मेरी स्थिति यह है:',
+ 'Hi — I’m your Coach. I build your plan from your answers and adjust it from what you actually log. Nothing changes until you say so.': 'नमस्ते — मैं आपका कोच हूँ। मैं आपके उत्तरों से योजना बनाता हूँ और आपके वास्तविक रिकॉर्ड के आधार पर उसे समायोजित करता हूँ। आपके कहे बिना कुछ नहीं बदलता।',
+ 'I looked through everything and there is nothing I would change right now. Keep going — ask me again after a few more sessions.': 'मैंने सब देख लिया, अभी कुछ बदलने की ज़रूरत नहीं। जारी रखें — कुछ और सत्रों के बाद फिर पूछें।',
+ 'I understand — let’s go': 'समझ गया — चलिए',
+ 'Imported — {0} routines are in your plan and your week is set. See you at the next session.': 'आयात हो गया — {0} रूटीन आपकी योजना में हैं और आपका सप्ताह सेट है। अगले सत्र में मिलते हैं।',
+ 'Imported — {0} routines are in your plan. Your week is unchanged; schedule them whenever you like.': 'आयात हो गया — {0} रूटीन आपकी योजना में हैं। आपका सप्ताह वैसा ही है; जब चाहें उन्हें शेड्यूल करें।',
+ 'It designs your plan from a few answers and adjusts it from what you actually log. It never changes anything without your say-so, and you can undo every change.': 'यह कुछ उत्तरों से आपकी योजना बनाता है और आपके वास्तविक रिकॉर्ड के आधार पर उसे समायोजित करता है। आपकी अनुमति के बिना कुछ नहीं बदलता, और हर बदलाव को पूर्ववत किया जा सकता है।',
+ 'Likes: {0}': 'पसंद: {0}',
+ 'Limits': 'सीमाएँ',
+ 'Limits: {0}': 'सीमाएँ: {0}',
+ 'Not quite right? Say what to change below and I will revise the whole plan.': 'ठीक नहीं लगा? नीचे बताएँ क्या बदलना है और मैं पूरी योजना संशोधित कर दूँगा।',
+ 'Pick one to continue.': 'जारी रखने के लिए एक चुनें।',
+ 'Pick what you will actually keep, not the best week you can imagine.': 'वह चुनें जो आप सच में निभा पाएँगे, न कि सबसे अच्छा सप्ताह जो आप सोच सकते हैं।',
+ 'Reading your training…': 'आपका प्रशिक्षण पढ़ा जा रहा है…',
+ 'Schedule': 'शेड्यूल',
+ 'Send': 'भेजें',
+ 'Sent straight to {0} with your own API key — you pay for every request.': 'आपकी अपनी API कुंजी से सीधे {0} को भेजा जाता है — हर अनुरोध का भुगतान आप करते हैं।',
+ 'Sent to {0}, running on this server under the instance owner’s account.': '{0} को भेजा जाता है, जो इस सर्वर पर इंस्टेंस स्वामी के खाते से चलता है।',
+ 'Session length': 'सत्र की अवधि',
+ 'Sets the pace of progression, and how much the Coach assumes you know.': 'प्रगति की गति और कोच आपसे कितनी जानकारी मानकर चलेगा, यह तय करता है।',
+ 'Suggestions': 'सुझाव',
+ 'Tell the Coach what to change…': 'कोच को बताएँ क्या बदलना है…',
+ 'The Coach builds the whole plan around this.': 'कोच पूरी योजना इसी के इर्द-गिर्द बनाता है।',
+ 'This usually takes a minute or two.': 'इसमें आमतौर पर एक-दो मिनट लगते हैं।',
+ 'Understood — I will not suggest these again without new evidence.': 'समझ गया — नए सबूत के बिना मैं इन्हें दोबारा नहीं सुझाऊँगा।',
+ 'Usually about {0} min.': 'आमतौर पर लगभग {0} मिनट।',
+ 'Usually under a minute.': 'आमतौर पर एक मिनट से कम।',
+ 'Wait for the Coach to finish…': 'कोच के पूरा होने का इंतज़ार करें…',
+ 'What it reads': 'यह क्या पढ़ता है',
+ 'What would the Coach change after your last sessions?': 'आपके पिछले सत्रों के बाद कोच क्या बदलेगा?',
+ 'You can leave — it keeps going.': 'आप जा सकते हैं — यह चलता रहेगा।',
+ 'Your goal': 'आपका लक्ष्य',
+ 'h:mm': 'घं:मि',
+ 'has a suggestion for you': 'आपके लिए एक सुझाव है',
+ 'here when you need it': 'जब ज़रूरत हो, यहाँ है',
+ 'thinking…': 'सोच रहा है…',
+ '{0} min per session': 'प्रति सत्र {0} मिनट'
}
diff --git a/frontend/src/locales/it.js b/frontend/src/locales/it.js
index ff32f20b9..6c61e9c87 100644
--- a/frontend/src/locales/it.js
+++ b/frontend/src/locales/it.js
@@ -850,5 +850,58 @@ export default {
'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'Il tuo server non ha il Coach attivo: chiedi all’amministratore, oppure usa la tua chiave qui sotto.',
'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'Il tuo server esegue il Coach con il provider impostato dal suo amministratore. Da questo telefono non esce nulla di nuovo oltre a ciò che già si sincronizza.',
'Loading the exercise catalogue…': 'Caricamento del catalogo esercizi…',
- 'Checking the endpoint…': 'Verifica dell’endpoint…'
+ 'Checking the endpoint…': 'Verifica dell’endpoint…',
+
+ // --- AI Coach chat ---
+ 'A local model can take longer.': 'Un modello locale può metterci di più.',
+ 'All optional. The more the Coach knows, the less it guesses.': 'Tutto facoltativo. Più il Coach sa, meno deve indovinare.',
+ 'Almost there': 'Ci siamo quasi',
+ 'Ask for a review, or tell the Coach something…': 'Chiedi una revisione, o di’ qualcosa al Coach…',
+ 'Avoid: {0}': 'Da evitare: {0}',
+ 'Before we start': 'Prima di iniziare',
+ 'Building your plan…': 'Sto creando il tuo piano…',
+ 'Continue': 'Continua',
+ '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',
+ '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.',
+ 'Here is what I am working with:': 'Ecco da cosa parto:',
+ 'Hi — I’m your Coach. I build your plan from your answers and adjust it from what you actually log. Nothing changes until you say so.': 'Ciao, sono il tuo Coach. Costruisco il tuo piano dalle tue risposte e lo adatto in base a ciò che registri davvero. Niente cambia finché non lo dici tu.',
+ 'I looked through everything and there is nothing I would change right now. Keep going — ask me again after a few more sessions.': 'Ho guardato tutto e al momento non cambierei nulla. Continua così: richiedimelo dopo qualche altra sessione.',
+ 'I understand — let’s go': 'Ho capito, andiamo',
+ 'Imported — {0} routines are in your plan and your week is set. See you at the next session.': 'Importato: {0} routine sono nel tuo piano e la settimana è impostata. Ci vediamo alla prossima sessione.',
+ 'Imported — {0} routines are in your plan. Your week is unchanged; schedule them whenever you like.': 'Importato: {0} routine sono nel tuo piano. La settimana resta com’è; pianificale quando vuoi.',
+ 'It designs your plan from a few answers and adjusts it from what you actually log. It never changes anything without your say-so, and you can undo every change.': 'Progetta il tuo piano da poche risposte e lo adatta in base a ciò che registri davvero. Non cambia mai nulla senza il tuo consenso, e puoi annullare ogni modifica.',
+ 'Likes: {0}': 'Piace: {0}',
+ 'Limits': 'Limiti',
+ 'Limits: {0}': 'Limiti: {0}',
+ 'Not quite right? Say what to change below and I will revise the whole plan.': 'Non è proprio così? Scrivi qui sotto cosa cambiare e rivedo l’intero piano.',
+ 'Pick one to continue.': 'Scegline una per continuare.',
+ 'Pick what you will actually keep, not the best week you can imagine.': 'Scegli quello che manterrai davvero, non la settimana migliore che riesci a immaginare.',
+ 'Reading your training…': 'Sto leggendo il tuo allenamento…',
+ 'Schedule': 'Programma',
+ 'Send': 'Invia',
+ 'Sent straight to {0} with your own API key — you pay for every request.': 'Inviato direttamente a {0} con la tua chiave API: paghi tu ogni richiesta.',
+ 'Sent to {0}, running on this server under the instance owner’s account.': 'Inviato a {0}, in esecuzione su questo server con l’account del proprietario.',
+ 'Session length': 'Durata della sessione',
+ 'Sets the pace of progression, and how much the Coach assumes you know.': 'Determina il ritmo di progressione e quanto il Coach dà per scontato.',
+ 'Suggestions': 'Suggerimenti',
+ 'Tell the Coach what to change…': 'Di’ al Coach cosa cambiare…',
+ 'The Coach builds the whole plan around this.': 'Il Coach costruisce l’intero piano attorno a questo.',
+ 'This usually takes a minute or two.': 'Di solito ci vogliono uno o due minuti.',
+ 'Understood — I will not suggest these again without new evidence.': 'Capito: non lo proporrò di nuovo senza nuove evidenze.',
+ 'Usually about {0} min.': 'Di solito circa {0} min.',
+ 'Usually under a minute.': 'Di solito meno di un minuto.',
+ 'Wait for the Coach to finish…': 'Aspetta che il Coach finisca…',
+ 'What it reads': 'Cosa legge',
+ 'What would the Coach change after your last sessions?': 'Cosa cambierebbe il Coach dopo le tue ultime sessioni?',
+ 'You can leave — it keeps going.': 'Puoi uscire: continua da solo.',
+ 'Your goal': 'Il tuo obiettivo',
+ 'h:mm': 'h:mm',
+ 'has a suggestion for you': 'ha un suggerimento per te',
+ 'here when you need it': 'qui quando serve',
+ 'thinking…': 'sta pensando…',
+ '{0} min per session': '{0} min a sessione'
}
diff --git a/frontend/src/locales/ko.js b/frontend/src/locales/ko.js
index 3f85216e4..0be827500 100644
--- a/frontend/src/locales/ko.js
+++ b/frontend/src/locales/ko.js
@@ -850,5 +850,58 @@ export default {
'Your server has no Coach enabled — ask its admin, or bring your own key below.': '서버에 코치가 활성화되어 있지 않습니다 — 관리자에게 문의하거나 아래에서 내 키를 사용하세요.',
'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': '서버가 관리자가 설정한 제공자로 코치를 실행합니다. 이미 동기화되는 것 외에는 이 휴대폰에서 새로 나가는 것이 없습니다.',
'Loading the exercise catalogue…': '운동 카탈로그 불러오는 중…',
- 'Checking the endpoint…': '엔드포인트 확인 중…'
+ 'Checking the endpoint…': '엔드포인트 확인 중…',
+
+ // --- AI Coach chat ---
+ 'A local model can take longer.': '로컬 모델은 더 오래 걸릴 수 있습니다.',
+ 'All optional. The more the Coach knows, the less it guesses.': '모두 선택 사항입니다. 코치가 많이 알수록 추측이 줄어듭니다.',
+ 'Almost there': '거의 다 됐어요',
+ 'Ask for a review, or tell the Coach something…': '검토를 요청하거나 코치에게 말해 보세요…',
+ 'Avoid: {0}': '피할 것: {0}',
+ 'Before we start': '시작하기 전에',
+ 'Building your plan…': '계획을 만드는 중…',
+ 'Continue': '계속',
+ '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': '내 답변 수정',
+ 'Experience': '경험',
+ 'Goal, days, equipment, limits': '목표, 요일, 장비, 제한',
+ 'Have a look at my training and tell me what you would change.': '내 훈련을 보고 무엇을 바꿀지 알려주세요.',
+ 'Here is what I am working with:': '제 상황은 이렇습니다:',
+ 'Hi — I’m your Coach. I build your plan from your answers and adjust it from what you actually log. Nothing changes until you say so.': '안녕하세요 — 당신의 코치입니다. 답변을 바탕으로 계획을 만들고 실제 기록에 따라 조정합니다. 당신이 말하기 전에는 아무것도 바뀌지 않습니다.',
+ 'I looked through everything and there is nothing I would change right now. Keep going — ask me again after a few more sessions.': '전부 살펴봤는데 지금은 바꿀 것이 없습니다. 계속하세요 — 몇 번 더 운동한 뒤 다시 물어보세요.',
+ 'I understand — let’s go': '알겠습니다 — 시작해요',
+ 'Imported — {0} routines are in your plan and your week is set. See you at the next session.': '가져왔습니다 — {0}개의 루틴이 계획에 들어갔고 주간 일정이 설정되었습니다. 다음 세션에서 봐요.',
+ 'Imported — {0} routines are in your plan. Your week is unchanged; schedule them whenever you like.': '가져왔습니다 — {0}개의 루틴이 계획에 들어갔습니다. 주간 일정은 그대로이니 원할 때 배정하세요.',
+ 'It designs your plan from a few answers and adjusts it from what you actually log. It never changes anything without your say-so, and you can undo every change.': '몇 가지 답변으로 계획을 설계하고 실제 기록에 따라 조정합니다. 동의 없이는 아무것도 바꾸지 않으며, 모든 변경을 되돌릴 수 있습니다.',
+ 'Likes: {0}': '좋아함: {0}',
+ 'Limits': '제한',
+ 'Limits: {0}': '제한: {0}',
+ 'Not quite right? Say what to change below and I will revise the whole plan.': '마음에 안 드나요? 아래에 바꿀 점을 말해주시면 계획 전체를 수정할게요.',
+ 'Pick one to continue.': '계속하려면 하나를 선택하세요.',
+ 'Pick what you will actually keep, not the best week you can imagine.': '상상 속 최고의 한 주가 아니라 실제로 지킬 수 있는 만큼 고르세요.',
+ 'Reading your training…': '훈련 기록을 읽는 중…',
+ 'Schedule': '일정',
+ 'Send': '보내기',
+ 'Sent straight to {0} with your own API key — you pay for every request.': '당신의 API 키로 {0}에 바로 전송됩니다 — 모든 요청의 비용은 당신이 냅니다.',
+ 'Sent to {0}, running on this server under the instance owner’s account.': '이 서버에서 인스턴스 소유자 계정으로 실행되는 {0}에 전송됩니다.',
+ 'Session length': '세션 길이',
+ 'Sets the pace of progression, and how much the Coach assumes you know.': '진행 속도와 코치가 당신이 얼마나 알고 있다고 가정할지를 정합니다.',
+ 'Suggestions': '제안',
+ 'Tell the Coach what to change…': '코치에게 바꿀 점을 말해 보세요…',
+ 'The Coach builds the whole plan around this.': '코치는 이것을 중심으로 전체 계획을 세웁니다.',
+ 'This usually takes a minute or two.': '보통 1~2분 정도 걸립니다.',
+ 'Understood — I will not suggest these again without new evidence.': '알겠습니다 — 새로운 근거 없이는 다시 제안하지 않을게요.',
+ 'Usually about {0} min.': '보통 약 {0}분 걸립니다.',
+ 'Usually under a minute.': '보통 1분 이내입니다.',
+ 'Wait for the Coach to finish…': '코치가 끝날 때까지 기다려 주세요…',
+ 'What it reads': '읽는 내용',
+ 'What would the Coach change after your last sessions?': '최근 세션 이후 코치는 무엇을 바꿀까요?',
+ 'You can leave — it keeps going.': '자리를 비워도 계속 진행됩니다.',
+ 'Your goal': '목표',
+ 'h:mm': '시:분',
+ 'has a suggestion for you': '제안이 있습니다',
+ 'here when you need it': '필요할 때 여기 있어요',
+ 'thinking…': '생각 중…',
+ '{0} min per session': '세션당 {0}분'
}
diff --git a/frontend/src/locales/pl.js b/frontend/src/locales/pl.js
index 5fe7a2c08..ce8434560 100644
--- a/frontend/src/locales/pl.js
+++ b/frontend/src/locales/pl.js
@@ -850,5 +850,58 @@ export default {
'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'Twój serwer nie ma włączonego trenera — zapytaj administratora albo użyj własnego klucza poniżej.',
'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'Twój serwer uruchamia trenera z dostawcą ustawionym przez administratora. Z tego telefonu nie wychodzi nic nowego poza tym, co i tak jest synchronizowane.',
'Loading the exercise catalogue…': 'Wczytywanie katalogu ćwiczeń…',
- 'Checking the endpoint…': 'Sprawdzanie endpointu…'
+ 'Checking the endpoint…': 'Sprawdzanie endpointu…',
+
+ // --- AI Coach chat ---
+ 'A local model can take longer.': 'Model lokalny może potrzebować więcej czasu.',
+ 'All optional. The more the Coach knows, the less it guesses.': 'Wszystko opcjonalne. Im więcej trener wie, tym mniej zgaduje.',
+ 'Almost there': 'Prawie gotowe',
+ 'Ask for a review, or tell the Coach something…': 'Poproś o przegląd albo powiedz coś trenerowi…',
+ 'Avoid: {0}': 'Unikać: {0}',
+ 'Before we start': 'Zanim zaczniemy',
+ 'Building your plan…': 'Tworzę Twój plan…',
+ 'Continue': 'Dalej',
+ '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',
+ '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ł.',
+ 'Here is what I am working with:': 'Oto, z czym pracuję:',
+ 'Hi — I’m your Coach. I build your plan from your answers and adjust it from what you actually log. Nothing changes until you say so.': 'Cześć — jestem Twoim trenerem. Buduję plan z Twoich odpowiedzi i dostosowuję go do tego, co naprawdę zapisujesz. Nic się nie zmienia, dopóki nie zdecydujesz.',
+ 'I looked through everything and there is nothing I would change right now. Keep going — ask me again after a few more sessions.': 'Przejrzałem wszystko i na razie niczego bym nie zmieniał. Trenuj dalej — zapytaj mnie znów po kilku sesjach.',
+ 'I understand — let’s go': 'Rozumiem — zaczynamy',
+ 'Imported — {0} routines are in your plan and your week is set. See you at the next session.': 'Zaimportowano — {0} rutyn jest w Twoim planie, a tydzień ustawiony. Do zobaczenia na następnym treningu.',
+ 'Imported — {0} routines are in your plan. Your week is unchanged; schedule them whenever you like.': 'Zaimportowano — {0} rutyn jest w Twoim planie. Tydzień bez zmian; zaplanuj je, kiedy chcesz.',
+ 'It designs your plan from a few answers and adjusts it from what you actually log. It never changes anything without your say-so, and you can undo every change.': 'Projektuje plan z kilku odpowiedzi i dostosowuje go do tego, co naprawdę zapisujesz. Nigdy nic nie zmienia bez Twojej zgody, a każdą zmianę możesz cofnąć.',
+ 'Likes: {0}': 'Lubi: {0}',
+ 'Limits': 'Ograniczenia',
+ 'Limits: {0}': 'Ograniczenia: {0}',
+ 'Not quite right? Say what to change below and I will revise the whole plan.': 'Nie do końca to? Napisz poniżej, co zmienić, a poprawię cały plan.',
+ 'Pick one to continue.': 'Wybierz jedną, aby przejść dalej.',
+ 'Pick what you will actually keep, not the best week you can imagine.': 'Wybierz to, co naprawdę utrzymasz, a nie najlepszy tydzień, jaki sobie wyobrażasz.',
+ 'Reading your training…': 'Czytam Twój trening…',
+ 'Schedule': 'Harmonogram',
+ 'Send': 'Wyślij',
+ 'Sent straight to {0} with your own API key — you pay for every request.': 'Wysyłane prosto do {0} z Twoim własnym kluczem API — płacisz za każde zapytanie.',
+ 'Sent to {0}, running on this server under the instance owner’s account.': 'Wysyłane do {0}, działającego na tym serwerze na koncie właściciela.',
+ 'Session length': 'Długość sesji',
+ 'Sets the pace of progression, and how much the Coach assumes you know.': 'Ustala tempo progresji i to, ile trener zakłada, że już wiesz.',
+ 'Suggestions': 'Sugestie',
+ 'Tell the Coach what to change…': 'Powiedz trenerowi, co zmienić…',
+ 'The Coach builds the whole plan around this.': 'Trener buduje cały plan wokół tego.',
+ 'This usually takes a minute or two.': 'Zwykle zajmuje to minutę lub dwie.',
+ 'Understood — I will not suggest these again without new evidence.': 'Rozumiem — nie zaproponuję tego ponownie bez nowych danych.',
+ 'Usually about {0} min.': 'Zwykle około {0} min.',
+ 'Usually under a minute.': 'Zwykle mniej niż minutę.',
+ 'Wait for the Coach to finish…': 'Poczekaj, aż trener skończy…',
+ 'What it reads': 'Co czyta',
+ 'What would the Coach change after your last sessions?': 'Co zmieniłby trener po Twoich ostatnich treningach?',
+ 'You can leave — it keeps going.': 'Możesz wyjść — to działa dalej.',
+ 'Your goal': 'Twój cel',
+ 'h:mm': 'g:mm',
+ 'has a suggestion for you': 'ma dla Ciebie propozycję',
+ 'here when you need it': 'tu, gdy potrzebujesz',
+ 'thinking…': 'myśli…',
+ '{0} min per session': '{0} min na sesję'
}
diff --git a/frontend/src/locales/pt-BR.js b/frontend/src/locales/pt-BR.js
index f6a38d392..732198d91 100644
--- a/frontend/src/locales/pt-BR.js
+++ b/frontend/src/locales/pt-BR.js
@@ -406,7 +406,40 @@ export const PT_BR_OVERRIDES = {
'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'Seu servidor roda o Treinador com o provedor que o administrador configurou. Nada de novo sai deste celular além do que já é sincronizado.',
'Loading the exercise catalogue…': 'Carregando o catálogo de exercícios…',
'Checking the endpoint…': 'Verificando o endpoint…',
- '(saved)': '(salva)'
+ '(saved)': '(salva)',
+ // --- AI Coach chat ---
+ 'Ask for a review, or tell the Coach something…': 'Peça uma revisão, ou diga algo ao Treinador…',
+ 'Building your plan…': 'Criando seu plano…',
+ 'Discarded. Tell me what was off and I will build a different one.': 'Descartado. Me diga o que não encaixou e eu faço outro.',
+ 'Done — your plan is back to how it was before my last changes.': 'Feito — seu plano voltou ao que era antes das minhas últimas alterações.',
+ 'Edit my answers': 'Editar minhas respostas',
+ 'Have a look at my training and tell me what you would change.': 'Dê uma olhada no meu treino e me diga o que você mudaria.',
+ 'Hi — I’m your Coach. I build your plan from your answers and adjust it from what you actually log. Nothing changes until you say so.': 'Olá — sou seu Treinador. Construo seu plano a partir das suas respostas e o ajusto com base no que você registra. Nada muda até você dizer.',
+ 'I looked through everything and there is nothing I would change right now. Keep going — ask me again after a few more sessions.': 'Vi tudo e neste momento não mudaria nada. Continue — me pergunte de novo depois de mais algumas sessões.',
+ 'I understand — let’s go': 'Entendi — vamos lá',
+ 'Imported — {0} routines are in your plan and your week is set. See you at the next session.': 'Importado — {0} rotinas estão no seu plano e sua semana está definida. Até a próxima sessão.',
+ 'Imported — {0} routines are in your plan. Your week is unchanged; schedule them whenever you like.': 'Importado — {0} rotinas estão no seu plano. Sua semana não muda; agende quando quiser.',
+ 'It designs your plan from a few answers and adjusts it from what you actually log. It never changes anything without your say-so, and you can undo every change.': 'Ele cria seu plano a partir de algumas respostas e o ajusta com base no que você registra. Nunca muda nada sem a sua autorização, e você pode desfazer cada alteração.',
+ 'Not quite right? Say what to change below and I will revise the whole plan.': 'Não ficou bom? Diga abaixo o que mudar e eu reviso o plano inteiro.',
+ 'Pick one to continue.': 'Escolha uma para continuar.',
+ 'Pick what you will actually keep, not the best week you can imagine.': 'Escolha o que você vai realmente cumprir, não a melhor semana que consegue imaginar.',
+ 'Reading your training…': 'Lendo seu treino…',
+ 'Sent straight to {0} with your own API key — you pay for every request.': 'Enviado direto para {0} com a sua própria chave de API — você paga cada pedido.',
+ 'Sent to {0}, running on this server under the instance owner’s account.': 'Enviado para {0}, que roda neste servidor na conta do proprietário.',
+ 'Sets the pace of progression, and how much the Coach assumes you know.': 'Define o ritmo da progressão e o quanto o Treinador assume que você já sabe.',
+ 'Tell the Coach what to change…': 'Diga ao Treinador o que mudar…',
+ 'The Coach builds the whole plan around this.': 'O Treinador constrói o plano inteiro em torno disto.',
+ 'Understood — I will not suggest these again without new evidence.': 'Entendido — não vou sugerir isto de novo sem novas evidências.',
+ 'Wait for the Coach to finish…': 'Espere o Treinador terminar…',
+ 'What would the Coach change after your last sessions?': 'O que o Treinador mudaria depois das suas últimas sessões?',
+ 'You can leave — it keeps going.': 'Você pode sair — ele continua trabalhando.',
+ 'Your goal': 'Seu objetivo',
+ 'has a suggestion for you': 'tem uma sugestão para você',
+ 'here when you need it': 'aqui quando você precisar',
+ 'thinking…': 'pensando…',
+ 'Here is what I am working with:': 'É com isto que eu conto:',
+ 'Almost there': 'Quase lá',
+ 'Before we start': 'Antes de começarmos'
}
export default { ...pt, ...PT_BR_OVERRIDES }
diff --git a/frontend/src/locales/pt.js b/frontend/src/locales/pt.js
index 4c6203a88..0dd558b8c 100644
--- a/frontend/src/locales/pt.js
+++ b/frontend/src/locales/pt.js
@@ -850,5 +850,58 @@ export default {
'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'O teu servidor não tem o Treinador ativado — pergunta ao administrador, ou usa a tua própria chave abaixo.',
'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'O teu servidor corre o Treinador com o fornecedor que o administrador configurou. Nada de novo sai deste telemóvel para além do que já é sincronizado.',
'Loading the exercise catalogue…': 'A carregar o catálogo de exercícios…',
- 'Checking the endpoint…': 'A verificar o endpoint…'
+ 'Checking the endpoint…': 'A verificar o endpoint…',
+
+ // --- AI Coach chat ---
+ 'A local model can take longer.': 'Um modelo local pode demorar mais.',
+ 'All optional. The more the Coach knows, the less it guesses.': 'Tudo opcional. Quanto mais o Treinador souber, menos tem de adivinhar.',
+ 'Almost there': 'Quase lá',
+ 'Ask for a review, or tell the Coach something…': 'Pede uma revisão, ou diz algo ao Treinador…',
+ 'Avoid: {0}': 'Evitar: {0}',
+ 'Before we start': 'Antes de começarmos',
+ 'Building your plan…': 'A criar o teu plano…',
+ 'Continue': 'Continuar',
+ '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',
+ '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.',
+ 'Here is what I am working with:': 'É com isto que conto:',
+ 'Hi — I’m your Coach. I build your plan from your answers and adjust it from what you actually log. Nothing changes until you say so.': 'Olá — sou o teu Treinador. Construo o teu plano a partir das tuas respostas e ajusto-o com base no que registas. Nada muda até dizeres.',
+ 'I looked through everything and there is nothing I would change right now. Keep going — ask me again after a few more sessions.': 'Vi tudo e neste momento não mudaria nada. Continua — pergunta-me de novo depois de mais algumas sessões.',
+ 'I understand — let’s go': 'Percebi — vamos a isso',
+ 'Imported — {0} routines are in your plan and your week is set. See you at the next session.': 'Importado — {0} rotinas estão no teu plano e a tua semana está definida. Até à próxima sessão.',
+ 'Imported — {0} routines are in your plan. Your week is unchanged; schedule them whenever you like.': 'Importado — {0} rotinas estão no teu plano. A tua semana não muda; agenda-as quando quiseres.',
+ 'It designs your plan from a few answers and adjusts it from what you actually log. It never changes anything without your say-so, and you can undo every change.': 'Cria o teu plano a partir de algumas respostas e ajusta-o com base no que registas. Nunca muda nada sem a tua autorização, e podes anular cada alteração.',
+ 'Likes: {0}': 'Gosta: {0}',
+ 'Limits': 'Limitações',
+ 'Limits: {0}': 'Limitações: {0}',
+ 'Not quite right? Say what to change below and I will revise the whole plan.': 'Não é bem isso? Diz abaixo o que mudar e eu revejo o plano todo.',
+ 'Pick one to continue.': 'Escolhe uma para continuar.',
+ 'Pick what you will actually keep, not the best week you can imagine.': 'Escolhe o que vais mesmo cumprir, não a melhor semana que consegues imaginar.',
+ 'Reading your training…': 'A ler o teu treino…',
+ 'Schedule': 'Horário',
+ 'Send': 'Enviar',
+ 'Sent straight to {0} with your own API key — you pay for every request.': 'Enviado diretamente para {0} com a tua própria chave de API — pagas cada pedido.',
+ 'Sent to {0}, running on this server under the instance owner’s account.': 'Enviado para {0}, que corre neste servidor na conta do proprietário.',
+ 'Session length': 'Duração da sessão',
+ 'Sets the pace of progression, and how much the Coach assumes you know.': 'Define o ritmo da progressão e o que o Treinador assume que já sabes.',
+ 'Suggestions': 'Sugestões',
+ 'Tell the Coach what to change…': 'Diz ao Treinador o que mudar…',
+ 'The Coach builds the whole plan around this.': 'O Treinador constrói o plano todo à volta disto.',
+ 'This usually takes a minute or two.': 'Costuma demorar um ou dois minutos.',
+ 'Understood — I will not suggest these again without new evidence.': 'Percebi — não volto a sugerir isto sem novas evidências.',
+ 'Usually about {0} min.': 'Costuma demorar cerca de {0} min.',
+ 'Usually under a minute.': 'Costuma demorar menos de um minuto.',
+ 'Wait for the Coach to finish…': 'Espera que o Treinador termine…',
+ 'What it reads': 'O que lê',
+ 'What would the Coach change after your last sessions?': 'O que mudaria o Treinador depois das tuas últimas sessões?',
+ 'You can leave — it keeps going.': 'Podes sair — continua a trabalhar.',
+ 'Your goal': 'O teu objetivo',
+ 'h:mm': 'h:mm',
+ 'has a suggestion for you': 'tem uma sugestão para ti',
+ 'here when you need it': 'aqui quando precisares',
+ 'thinking…': 'a pensar…',
+ '{0} min per session': '{0} min por sessão'
}
diff --git a/frontend/src/locales/ru.js b/frontend/src/locales/ru.js
index 4456b785f..0fcc26ca7 100644
--- a/frontend/src/locales/ru.js
+++ b/frontend/src/locales/ru.js
@@ -850,5 +850,58 @@ export default {
'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'На вашем сервере тренер не включён — спросите администратора или используйте свой ключ ниже.',
'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'Ваш сервер запускает тренера с тем провайдером, которого настроил администратор. С этого телефона не уходит ничего нового сверх того, что и так синхронизируется.',
'Loading the exercise catalogue…': 'Загрузка каталога упражнений…',
- 'Checking the endpoint…': 'Проверка эндпоинта…'
+ 'Checking the endpoint…': 'Проверка эндпоинта…',
+
+ // --- AI Coach chat ---
+ 'A local model can take longer.': 'Локальная модель может работать дольше.',
+ 'All optional. The more the Coach knows, the less it guesses.': 'Всё необязательно. Чем больше тренер знает, тем меньше он гадает.',
+ 'Almost there': 'Почти готово',
+ 'Ask for a review, or tell the Coach something…': 'Попросите разбор или напишите тренеру…',
+ 'Avoid: {0}': 'Избегать: {0}',
+ 'Before we start': 'Прежде чем начать',
+ 'Building your plan…': 'Составляю ваш план…',
+ 'Continue': 'Далее',
+ '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': 'Изменить мои ответы',
+ 'Experience': 'Опыт',
+ 'Goal, days, equipment, limits': 'Цель, дни, инвентарь, ограничения',
+ 'Have a look at my training and tell me what you would change.': 'Посмотрите на мои тренировки и скажите, что бы вы изменили.',
+ 'Here is what I am working with:': 'Вот с чем я работаю:',
+ 'Hi — I’m your Coach. I build your plan from your answers and adjust it from what you actually log. Nothing changes until you say so.': 'Привет — я ваш тренер. Я составляю план из ваших ответов и корректирую его по тому, что вы реально записываете. Ничего не меняется без вашего слова.',
+ 'I looked through everything and there is nothing I would change right now. Keep going — ask me again after a few more sessions.': 'Я всё просмотрел и сейчас ничего бы не менял. Продолжайте — спросите меня снова через несколько тренировок.',
+ 'I understand — let’s go': 'Понятно — поехали',
+ 'Imported — {0} routines are in your plan and your week is set. See you at the next session.': 'Импортировано — {0} рутин в вашем плане, неделя настроена. До встречи на следующей тренировке.',
+ 'Imported — {0} routines are in your plan. Your week is unchanged; schedule them whenever you like.': 'Импортировано — {0} рутин в вашем плане. Неделя не изменилась; распланируйте их, когда захотите.',
+ 'It designs your plan from a few answers and adjusts it from what you actually log. It never changes anything without your say-so, and you can undo every change.': 'Он составляет план из нескольких ответов и корректирует его по тому, что вы реально записываете. Он ничего не меняет без вашего согласия, и любое изменение можно отменить.',
+ 'Likes: {0}': 'Нравится: {0}',
+ 'Limits': 'Ограничения',
+ 'Limits: {0}': 'Ограничения: {0}',
+ 'Not quite right? Say what to change below and I will revise the whole plan.': 'Не совсем то? Напишите ниже, что изменить, и я пересмотрю весь план.',
+ 'Pick one to continue.': 'Выберите вариант, чтобы продолжить.',
+ 'Pick what you will actually keep, not the best week you can imagine.': 'Выберите то, что реально выдержите, а не лучшую неделю, которую можете представить.',
+ 'Reading your training…': 'Читаю ваши тренировки…',
+ 'Schedule': 'Расписание',
+ 'Send': 'Отправить',
+ 'Sent straight to {0} with your own API key — you pay for every request.': 'Отправляется напрямую в {0} с вашим собственным API-ключом — каждый запрос оплачиваете вы.',
+ 'Sent to {0}, running on this server under the instance owner’s account.': 'Отправляется в {0}, работающий на этом сервере под учётной записью владельца.',
+ 'Session length': 'Длительность тренировки',
+ 'Sets the pace of progression, and how much the Coach assumes you know.': 'Задаёт темп прогрессии и то, сколько тренер считает известным вам.',
+ 'Suggestions': 'Предложения',
+ 'Tell the Coach what to change…': 'Скажите тренеру, что изменить…',
+ 'The Coach builds the whole plan around this.': 'Вокруг этого тренер строит весь план.',
+ 'This usually takes a minute or two.': 'Обычно это занимает минуту-две.',
+ 'Understood — I will not suggest these again without new evidence.': 'Понял — без новых данных я не буду предлагать это снова.',
+ 'Usually about {0} min.': 'Обычно около {0} мин.',
+ 'Usually under a minute.': 'Обычно меньше минуты.',
+ 'Wait for the Coach to finish…': 'Подождите, пока тренер закончит…',
+ 'What it reads': 'Что он читает',
+ 'What would the Coach change after your last sessions?': 'Что тренер изменил бы после ваших последних тренировок?',
+ 'You can leave — it keeps going.': 'Можете уйти — работа продолжится.',
+ 'Your goal': 'Ваша цель',
+ 'h:mm': 'ч:мм',
+ 'has a suggestion for you': 'есть предложение для вас',
+ 'here when you need it': 'здесь, когда нужен',
+ 'thinking…': 'думает…',
+ '{0} min per session': '{0} мин за тренировку'
}
diff --git a/frontend/src/locales/tr.js b/frontend/src/locales/tr.js
index fd94aad28..fc8d3c78d 100644
--- a/frontend/src/locales/tr.js
+++ b/frontend/src/locales/tr.js
@@ -850,5 +850,58 @@ export default {
'Your server has no Coach enabled — ask its admin, or bring your own key below.': 'Sunucunda koç etkin değil — yöneticisine sor ya da aşağıda kendi anahtarını kullan.',
'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': 'Sunucun koçu yöneticisinin kurduğu sağlayıcıyla çalıştırır. Zaten eşitlenenler dışında bu telefondan yeni bir şey gitmez.',
'Loading the exercise catalogue…': 'Egzersiz kataloğu yükleniyor…',
- 'Checking the endpoint…': 'Uç nokta kontrol ediliyor…'
+ 'Checking the endpoint…': 'Uç nokta kontrol ediliyor…',
+
+ // --- AI Coach chat ---
+ 'A local model can take longer.': 'Yerel bir model daha uzun sürebilir.',
+ 'All optional. The more the Coach knows, the less it guesses.': 'Hepsi isteğe bağlı. Koç ne kadar çok bilirse o kadar az tahmin eder.',
+ 'Almost there': 'Neredeyse bitti',
+ 'Ask for a review, or tell the Coach something…': 'Bir değerlendirme iste ya da koça bir şey söyle…',
+ 'Avoid: {0}': 'Kaçınılacaklar: {0}',
+ 'Before we start': 'Başlamadan önce',
+ 'Building your plan…': 'Planın hazırlanıyor…',
+ 'Continue': 'Devam',
+ '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',
+ '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.',
+ 'Here is what I am working with:': 'Elimdekiler şunlar:',
+ 'Hi — I’m your Coach. I build your plan from your answers and adjust it from what you actually log. Nothing changes until you say so.': 'Merhaba — ben senin koçunum. Planını cevaplarından kurar, gerçekten kaydettiklerine göre ayarlarım. Sen demeden hiçbir şey değişmez.',
+ 'I looked through everything and there is nothing I would change right now. Keep going — ask me again after a few more sessions.': 'Her şeye baktım, şu an değiştireceğim bir şey yok. Devam et — birkaç antrenman sonra tekrar sor.',
+ 'I understand — let’s go': 'Anladım — başlayalım',
+ 'Imported — {0} routines are in your plan and your week is set. See you at the next session.': 'İçe aktarıldı — {0} rutin planında, haftan ayarlandı. Bir sonraki antrenmanda görüşürüz.',
+ 'Imported — {0} routines are in your plan. Your week is unchanged; schedule them whenever you like.': 'İçe aktarıldı — {0} rutin planında. Haftan değişmedi; istediğin zaman programla.',
+ 'It designs your plan from a few answers and adjusts it from what you actually log. It never changes anything without your say-so, and you can undo every change.': 'Planını birkaç cevaptan tasarlar ve gerçekten kaydettiklerine göre ayarlar. Onayın olmadan hiçbir şeyi değiştirmez ve her değişikliği geri alabilirsin.',
+ 'Likes: {0}': 'Sevdikleri: {0}',
+ 'Limits': 'Sınırlar',
+ 'Limits: {0}': 'Sınırlar: {0}',
+ 'Not quite right? Say what to change below and I will revise the whole plan.': 'Tam olmadı mı? Aşağıya neyi değiştireceğimi yaz, tüm planı gözden geçireyim.',
+ 'Pick one to continue.': 'Devam etmek için birini seç.',
+ 'Pick what you will actually keep, not the best week you can imagine.': 'Hayal edebildiğin en iyi haftayı değil, gerçekten sürdüreceğini seç.',
+ 'Reading your training…': 'Antrenmanın okunuyor…',
+ 'Schedule': 'Program',
+ 'Send': 'Gönder',
+ 'Sent straight to {0} with your own API key — you pay for every request.': 'Kendi API anahtarınla doğrudan {0} adresine gönderilir — her isteğin ücretini sen ödersin.',
+ 'Sent to {0}, running on this server under the instance owner’s account.': 'Bu sunucuda örnek sahibinin hesabıyla çalışan {0} adresine gönderilir.',
+ 'Session length': 'Antrenman süresi',
+ 'Sets the pace of progression, and how much the Coach assumes you know.': 'İlerleme hızını ve koçun ne kadar bildiğini varsayacağını belirler.',
+ 'Suggestions': 'Öneriler',
+ 'Tell the Coach what to change…': 'Koça neyi değiştireceğini söyle…',
+ 'The Coach builds the whole plan around this.': 'Koç tüm planı bunun etrafında kurar.',
+ 'This usually takes a minute or two.': 'Genellikle bir iki dakika sürer.',
+ 'Understood — I will not suggest these again without new evidence.': 'Anlaşıldı — yeni kanıt olmadan bunları tekrar önermeyeceğim.',
+ 'Usually about {0} min.': 'Genellikle yaklaşık {0} dk.',
+ 'Usually under a minute.': 'Genellikle bir dakikadan az.',
+ 'Wait for the Coach to finish…': 'Koçun bitirmesini bekle…',
+ 'What it reads': 'Neleri okur',
+ 'What would the Coach change after your last sessions?': 'Son antrenmanlarından sonra koç neyi değiştirirdi?',
+ 'You can leave — it keeps going.': 'Çıkabilirsin — devam ediyor.',
+ 'Your goal': 'Hedefin',
+ 'h:mm': 's:dd',
+ 'has a suggestion for you': 'senin için bir önerisi var',
+ 'here when you need it': 'ihtiyacın olduğunda burada',
+ 'thinking…': 'düşünüyor…',
+ '{0} min per session': 'Seans başına {0} dk'
}
diff --git a/frontend/src/locales/zh.js b/frontend/src/locales/zh.js
index 49e69db94..3ce2dc7ca 100644
--- a/frontend/src/locales/zh.js
+++ b/frontend/src/locales/zh.js
@@ -850,5 +850,58 @@ export default {
'Your server has no Coach enabled — ask its admin, or bring your own key below.': '你的服务器未启用教练——请联系管理员,或在下方使用你自己的密钥。',
'Your server runs the Coach with whatever provider its admin set up. Nothing new leaves this phone beyond what already syncs.': '你的服务器使用管理员设置的提供商运行教练。除了已同步的内容外,此手机不会发送任何新数据。',
'Loading the exercise catalogue…': '正在加载动作库…',
- 'Checking the endpoint…': '正在检查端点…'
+ 'Checking the endpoint…': '正在检查端点…',
+
+ // --- AI Coach chat ---
+ 'A local model can take longer.': '本地模型可能需要更长时间。',
+ 'All optional. The more the Coach knows, the less it guesses.': '全部可选。教练了解得越多,猜测就越少。',
+ 'Almost there': '快完成了',
+ 'Ask for a review, or tell the Coach something…': '请求评估,或告诉教练一些事情…',
+ 'Avoid: {0}': '避免:{0}',
+ 'Before we start': '开始之前',
+ 'Building your plan…': '正在制定你的计划…',
+ 'Continue': '继续',
+ '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': '编辑我的回答',
+ 'Experience': '经验',
+ 'Goal, days, equipment, limits': '目标、天数、器材、限制',
+ 'Have a look at my training and tell me what you would change.': '看看我的训练,告诉我你会改什么。',
+ 'Here is what I am working with:': '这是我的情况:',
+ 'Hi — I’m your Coach. I build your plan from your answers and adjust it from what you actually log. Nothing changes until you say so.': '你好——我是你的教练。我根据你的回答制定计划,并根据你的实际记录进行调整。没有你的同意,什么都不会改变。',
+ 'I looked through everything and there is nothing I would change right now. Keep going — ask me again after a few more sessions.': '我看了一遍,目前没有需要改的。继续加油——再练几次后再问我。',
+ 'I understand — let’s go': '明白了——开始吧',
+ 'Imported — {0} routines are in your plan and your week is set. See you at the next session.': '已导入——{0} 个训练已加入你的计划,本周已安排好。下次训练见。',
+ 'Imported — {0} routines are in your plan. Your week is unchanged; schedule them whenever you like.': '已导入——{0} 个训练已加入你的计划。本周安排不变,随时可以安排它们。',
+ 'It designs your plan from a few answers and adjusts it from what you actually log. It never changes anything without your say-so, and you can undo every change.': '它根据几个回答设计你的计划,并根据你的实际记录进行调整。未经你同意它不会更改任何内容,每项更改都可以撤销。',
+ 'Likes: {0}': '喜欢:{0}',
+ 'Limits': '限制',
+ 'Limits: {0}': '限制:{0}',
+ 'Not quite right? Say what to change below and I will revise the whole plan.': '不太合适?在下方说说要改什么,我会重新修改整个计划。',
+ 'Pick one to continue.': '选择一项以继续。',
+ 'Pick what you will actually keep, not the best week you can imagine.': '选择你真正能坚持的,而不是你能想象的最完美的一周。',
+ 'Reading your training…': '正在查看你的训练…',
+ 'Schedule': '日程',
+ 'Send': '发送',
+ 'Sent straight to {0} with your own API key — you pay for every request.': '使用你自己的 API 密钥直接发送到 {0}——每个请求的费用由你承担。',
+ 'Sent to {0}, running on this server under the instance owner’s account.': '发送到在此服务器上以实例所有者账户运行的 {0}。',
+ 'Session length': '训练时长',
+ 'Sets the pace of progression, and how much the Coach assumes you know.': '决定进阶的节奏,以及教练默认你已掌握多少。',
+ 'Suggestions': '建议',
+ 'Tell the Coach what to change…': '告诉教练要改什么…',
+ 'The Coach builds the whole plan around this.': '教练会围绕这一点制定整个计划。',
+ 'This usually takes a minute or two.': '通常需要一两分钟。',
+ 'Understood — I will not suggest these again without new evidence.': '明白了——没有新的证据我不会再建议这些。',
+ 'Usually about {0} min.': '通常约 {0} 分钟。',
+ 'Usually under a minute.': '通常不到一分钟。',
+ 'Wait for the Coach to finish…': '请等待教练完成…',
+ 'What it reads': '它会读取什么',
+ 'What would the Coach change after your last sessions?': '教练在你最近几次训练后会改什么?',
+ 'You can leave — it keeps going.': '你可以离开——它会继续进行。',
+ 'Your goal': '你的目标',
+ 'h:mm': '时:分',
+ 'has a suggestion for you': '有一个建议给你',
+ 'here when you need it': '随时待命',
+ 'thinking…': '思考中…',
+ '{0} min per session': '每次 {0} 分钟'
}
diff --git a/frontend/src/views/Admin.jsx b/frontend/src/views/Admin.jsx
index dc14b4346..6b63b08c9 100644
--- a/frontend/src/views/Admin.jsx
+++ b/frontend/src/views/Admin.jsx
@@ -10,20 +10,25 @@ import { confirmSheet } from '../sheets.jsx'
import Icon from '../components/Icon.jsx'
import { Button } from '../components/ui.jsx'
import AdminCoach from './AdminCoach.jsx'
+import '../admin.css'
// Admin-only operator dashboard (owner passkey + admin flag; guarded again server-side).
// Deliberately English-only — it isn't part of the translated end-user surface, so it stays
// out of the per-language string packs.
+//
+// One page of cards, each opening with a sentence that says what it is for. An operator who
+// looks at this twice a year should not have to remember what "synced 3d ago" or an invite
+// code means.
const rel = ts => {
if (!ts) return 'never'
const s = Math.max(0, (Date.now() - ts) / 1000)
if (s < 60) return 'just now'
- if (s < 3600) return Math.floor(s / 60) + 'm ago'
- if (s < 86400) return Math.floor(s / 3600) + 'h ago'
- return Math.floor(s / 86400) + 'd ago'
+ if (s < 3600) return Math.floor(s / 60) + ' min ago'
+ if (s < 86400) return Math.floor(s / 3600) + ' h ago'
+ return Math.floor(s / 86400) + ' d ago'
}
-const dur = ms => { const m = Math.max(0, Math.floor(ms / 60000)); return m < 60 ? m + 'm' : Math.floor(m / 60) + 'h' + (m % 60) + 'm' }
+const dur = ms => { const m = Math.max(0, Math.floor(ms / 60000)); return m < 60 ? m + ' min' : Math.floor(m / 60) + ' h ' + (m % 60) + ' min' }
function UserDetail({ id, onChanged, close }) {
const [d, setD] = useState(null)
@@ -39,10 +44,10 @@ function UserDetail({ id, onChanged, close }) {
return <>
<h3 className="capitalize">{u.name}</h3>
<div className="row" style={{ gap: 6, flexWrap: 'wrap', margin: '8px 0 12px' }}>
- {u.admin && <span className="tag acc">admin</span>}
- {u.disabled && <span className="tag" style={{ color: 'var(--red)' }}>disabled</span>}
- {u.invitedBy && <span className="tag">invite {u.invitedBy}</span>}
- <span className="tag">joined {u.created ? fmtDate(u.created.slice(0, 10)) : '—'}</span>
+ {u.admin && <span className="adm-pill acc">admin</span>}
+ {u.disabled && <span className="adm-pill bad">disabled</span>}
+ {u.invitedBy && <span className="adm-pill">invite {u.invitedBy}</span>}
+ <span className="adm-pill">joined {u.created ? fmtDate(u.created.slice(0, 10)) : '—'}</span>
</div>
<div className="tiles" style={{ textAlign: 'left' }}>
<div className="tile"><div className="l">Workouts</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.workouts.length}</div></div>
@@ -50,10 +55,13 @@ function UserDetail({ id, onChanged, close }) {
<div className="tile"><div className="l">Routines</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.routines.length}</div></div>
<div className="tile"><div className="l">Last sync</div><div className="v" style={{ fontSize: '.95rem' }}>{rel(d.lastSync)}</div></div>
</div>
- {!u.admin && <button className={'btn ' + (u.disabled ? 'primary' : 'danger')} style={{ margin: '12px 0 4px' }}
- onClick={() => u.disabled ? setDisabled(false)
- : confirmSheet({ title: 'Disable ' + u.name + '?', message: 'They are signed out everywhere and can no longer sync or log in until re-enabled.', confirmText: 'Disable', danger: true, onConfirm: () => setDisabled(true) })}>
- {u.disabled ? 'Enable account' : 'Disable account'}</button>}
+ {!u.admin && <>
+ <button className={'btn ' + (u.disabled ? 'primary' : 'danger')} style={{ margin: '12px 0 4px' }}
+ onClick={() => u.disabled ? setDisabled(false)
+ : confirmSheet({ title: 'Disable ' + u.name + '?', message: 'They are signed out everywhere and can no longer sync or log in until re-enabled. Their data stays.', confirmText: 'Disable', danger: true, onConfirm: () => setDisabled(true) })}>
+ {u.disabled ? 'Enable account' : 'Disable account'}</button>
+ <div className="adm-hint">{u.disabled ? 'Enabling lets them sign in and sync again.' : 'Disabling signs them out everywhere and blocks sign-in. Nothing is deleted.'}</div>
+ </>}
<h4 className="sec">Workout history</h4>
{d.workouts.length ? <div className="list" style={{ gap: 0 }}>
{d.workouts.slice(0, 60).map(w => <div key={w.id} className="row between" style={{ padding: '9px 2px', borderBottom: '1px solid var(--sep)' }}>
@@ -61,32 +69,49 @@ function UserDetail({ id, onChanged, close }) {
<div className="dim" style={{ fontSize: '.72rem' }}>{fmtDate(w.d, true)} · {fmtDur((w.end || w.start) - w.start)} · {setsDone(w)} sets{w.prs?.length ? ' · ' + w.prs.length + ' PR' : ''}</div></div>
<span className="small muted">{fmtVol(w.vol ?? workoutVolume(w), d.unit)}</span>
</div>)}
- </div> : <div className="empty small">No workouts logged.</div>}
+ </div> : <div className="adm-empty">No workouts logged.</div>}
</>
}
-function InvitesCard({ invites, reload }) {
+function InvitesCard({ invites, reload, inviteOnly }) {
const toast = useUI(s => s.toast)
const gen = () => api('/api/admin/invites/new', { method: 'POST', body: '{}' })
.then(({ invite }) => { navigator.clipboard?.writeText(invite.code).catch(() => {}); toast('Code ' + invite.code + ' created & copied'); reload() })
.catch(e => toast(e.message))
- const revoke = code => api('/api/admin/invites/revoke', { method: 'POST', body: JSON.stringify({ code }) })
- .then(() => { toast('Code revoked'); reload() }).catch(e => toast(e.message))
+ const revoke = code => confirmSheet({
+ title: 'Revoke code ' + code + '?', message: 'Anyone who has it can no longer use it. People who already signed up with it are not affected.',
+ confirmText: 'Revoke', danger: true,
+ onConfirm: () => api('/api/admin/invites/revoke', { method: 'POST', body: JSON.stringify({ code }) })
+ .then(() => { toast('Code revoked'); reload() }).catch(e => toast(e.message))
+ })
+ const copy = code => { navigator.clipboard?.writeText(code).catch(() => {}); toast('Copied ' + code) }
const open = (invites || []).filter(i => !i.usedBy)
const used = (invites || []).filter(i => i.usedBy)
return <div className="card">
<div className="row between"><h2 style={{ margin: 0 }}>Invite codes</h2>
- <Button variant="primary" size="sm" onClick={gen} icon="plus">Generate</Button></div>
- <div className="small muted" style={{ margin: '6px 0 10px' }}>{open.length} unused · {used.length} redeemed</div>
- {open.map(i => <div key={i.code} className="row between" style={{ padding: '7px 2px', borderBottom: '1px solid var(--sep)' }}>
- <span style={{ fontFamily: 'ui-monospace,SFMono-Regular,Menlo,monospace', fontWeight: 500, letterSpacing: '.06em' }}
- onClick={() => { navigator.clipboard?.writeText(i.code).catch(() => {}); toast('Copied ' + i.code) }}>{i.code}</span>
- <button className="iconbtn" style={{ width: 32, height: 30, borderRadius: 8, fontSize: 15, color: 'var(--red)' }} onClick={() => revoke(i.code)} aria-label="revoke"><Icon name="trash" /></button>
- </div>)}
- {used.map(i => <div key={i.code} className="row between dim" style={{ padding: '7px 2px', fontSize: '.8rem' }}>
- <span style={{ fontFamily: 'monospace' }}>{i.code}</span><span>→ {i.usedByName || 'used'}</span>
- </div>)}
- {!open.length && !used.length && <div className="dim small">No codes yet — generate one to invite someone.</div>}
+ <Button variant="primary" size="sm" onClick={gen} icon="plus">New code</Button></div>
+ <div className="adm-lead">
+ {inviteOnly
+ ? 'Sign-up is invite-only: someone needs one of these codes to create a profile. Each code works once.'
+ : 'Sign-up is open, so codes are optional here — they only record who invited whom.'}
+ </div>
+ {open.length ? <>
+ <div className="adm-group-t">Unused · tap to copy</div>
+ {open.map(i => <div key={i.code} className="row between" style={{ padding: '6px 0', borderBottom: 'var(--hair) solid var(--sep)' }}>
+ <button className="adm-code" onClick={() => copy(i.code)} aria-label={'copy ' + i.code}>{i.code}</button>
+ <div className="row" style={{ gap: 4 }}>
+ <button className="iconbtn adm-iconbtn" onClick={() => copy(i.code)} aria-label="copy"><Icon name="clipboard" /></button>
+ <button className="iconbtn adm-iconbtn" style={{ color: 'var(--red)' }} onClick={() => revoke(i.code)} aria-label="revoke"><Icon name="trash" /></button>
+ </div>
+ </div>)}
+ </> : null}
+ {used.length ? <>
+ <div className="adm-group-t" style={{ marginTop: open.length ? 12 : 0 }}>Already used</div>
+ {used.map(i => <div key={i.code} className="row between dim" style={{ padding: '6px 0', fontSize: '.82rem' }}>
+ <span style={{ fontFamily: 'ui-monospace,SFMono-Regular,Menlo,monospace', letterSpacing: '.06em' }}>{i.code}</span><span>→ {i.usedByName || 'used'}</span>
+ </div>)}
+ </> : null}
+ {!open.length && !used.length && <div className="adm-empty">No codes yet. "New code" makes one and copies it to your clipboard.</div>}
</div>
}
@@ -119,30 +144,31 @@ function AuditCard({ tick }) {
return <div className="card">
<div className="row between"><h2 style={{ margin: 0 }}>Activity log</h2>
- <button className="iconbtn" style={{ width: 32, height: 30, borderRadius: 8, fontSize: 15, color: 'var(--red)' }}
- onClick={clear} aria-label="clear log"><Icon name="trash" /></button></div>
- <div className="small muted" style={{ margin: '6px 0 10px' }}>
- {meta ? fmtNum(meta.total) + ' events'
- + (meta.retention.days ? ' · last ' + meta.retention.days + ' days' : '')
- + (meta.ip_mode === 'off' ? ' · no IP addresses' : '') : 'Loading…'}</div>
+ <button className="iconbtn adm-iconbtn" style={{ color: 'var(--red)' }} onClick={clear} aria-label="clear log"><Icon name="trash" /></button></div>
+ <div className="adm-lead">
+ Who signed in, what failed, and what an admin changed.
+ {meta ? ' ' + fmtNum(meta.total) + ' events'
+ + (meta.retention.days ? ', kept for ' + meta.retention.days + ' days' : '')
+ + (meta.ip_mode === 'off' ? ', without IP addresses' : '') + '.' : ''}
+ </div>
<div className="chips" style={{ marginBottom: 10 }}>
{[['', 'All'], ['auth', 'Sign-ins'], ['admin', 'Admin'], ['fail', 'Failed']].map(([v, l]) =>
<button key={v} className={'chip' + (cat === v ? ' on' : '')} onClick={() => pick(v)}>{l}</button>)}
</div>
{rows.map(e => {
const line = auditLine(e)
- return <div key={e.id} className="row between" style={{ padding: '8px 2px', borderBottom: '1px solid var(--sep)' }}>
+ return <div key={e.id} className="row between" style={{ padding: '8px 2px', borderBottom: 'var(--hair) solid var(--sep)' }}>
<div className="grow">
<div className="small" style={{ fontWeight: 600 }}>{line.title}
{/* a red pill, not a red row: twenty fumbled Face IDs in a row shouldn't read as an incident */}
- {!e.ok && <span className="tag" style={{ marginLeft: 6, color: 'var(--red)' }}>failed</span>}
- {auditCat(e.ev) === 'admin' && <span className="tag acc" style={{ marginLeft: 6 }}>admin</span>}</div>
+ {!e.ok && <span className="adm-pill bad" style={{ marginLeft: 6 }}>failed</span>}
+ {auditCat(e.ev) === 'admin' && <span className="adm-pill acc" style={{ marginLeft: 6 }}>admin</span>}</div>
{line.sub && <div className="dim" style={{ fontSize: '.72rem' }}>{line.sub}</div>}
</div>
<span className="small muted" style={{ flex: 'none', marginLeft: 8 }}>{fmtWhen(e.ts, meta?.now)}</span>
</div>
})}
- {meta && !rows.length && <div className="dim small">Nothing logged yet.</div>}
+ {meta && !rows.length && <div className="adm-empty">Nothing logged yet.</div>}
{meta?.nextBefore && <div style={{ marginTop: 10 }}>
<Button size="sm" onClick={() => load(cat, meta.nextBefore)}>Show more</Button></div>}
</div>
@@ -176,37 +202,44 @@ export default function Admin() {
<div className="sub">{users ? users.length + ' users · ' + activeCount + ' active this week' : 'Loading…'}</div></div>
<button className="iconbtn" onClick={() => { loadUsers(); loadInvites(); setTick(n => n + 1) }} aria-label="refresh">↻</button>
</div>
+ <div className="adm-intro">
+ Everything about running this instance: who uses it, how they get in, and the AI Coach. Nothing here shows anyone's training data beyond counts.
+ </div>
<div className="tiles" style={{ marginBottom: 12 }}>
<div className="tile"><div className="l">Users</div><div className="v">{users ? users.length : '—'}</div></div>
<div className="tile"><div className="l">Training now</div><div className="v" style={{ color: liveUsers.length ? 'var(--acc)' : undefined }}>{users ? liveUsers.length : '—'}</div></div>
- <div className="tile"><div className="l">Active 7d</div><div className="v">{users ? activeCount : '—'}</div></div>
+ <div className="tile"><div className="l">Active 7 days</div><div className="v">{users ? activeCount : '—'}</div></div>
<div className="tile"><div className="l">Disabled</div><div className="v">{users ? disabledCount : '—'}</div></div>
</div>
{liveUsers.length > 0 && <div className="card" style={{ borderColor: 'var(--acc)' }}>
- <h2 className="row" style={{ margin: '0 0 8px', gap: 6 }}><Icon name="dot" style={{ fontSize: 10, color: 'var(--green)' }} />Training now</h2>
- {liveUsers.map(u => <div key={u.id} className="row between" style={{ padding: '8px 2px', borderBottom: '1px solid var(--sep)' }} onClick={() => openUser(u.id)}>
+ <h2 className="row" style={{ margin: '0 0 2px', gap: 6 }}><Icon name="dot" style={{ fontSize: 10, color: 'var(--green)' }} />Training now</h2>
+ <div className="adm-lead">Sessions running at this moment. Tap a name for details.</div>
+ {liveUsers.map(u => <div key={u.id} className="row between" style={{ padding: '8px 2px', borderBottom: 'var(--hair) solid var(--sep)' }} onClick={() => openUser(u.id)}>
<div><div className="small" style={{ fontWeight: 600 }}>{u.name}</div>
- <div className="dim" style={{ fontSize: '.72rem' }}>{u.live.name} · ex {u.live.exIdx}/{u.live.exTotal} · {u.live.setsDone}/{u.live.setsTotal} sets</div></div>
- <span className="tag acc">{dur(Date.now() - u.live.startedAt)}</span>
+ <div className="dim" style={{ fontSize: '.72rem' }}>{u.live.name} · exercise {u.live.exIdx} of {u.live.exTotal} · {u.live.setsDone}/{u.live.setsTotal} sets</div></div>
+ <span className="adm-pill acc">{dur(Date.now() - u.live.startedAt)}</span>
</div>)}
</div>}
- {/* Renders nothing at all unless the instance offers the Coach, so an admin page on a
- box that never enabled it is byte-for-byte the page it was before. */}
+ {/* The Coach setup. Renders nothing at all unless the instance offers the Coach, so an admin
+ page on a box that never enabled it is byte-for-byte the page it was before. */}
<AdminCoach />
- <InvitesCard invites={invites} reload={loadInvites} />
-
- <h4 className="sec">Users</h4>
- <div className="list">
- {(users || []).map(u => <div key={u.id} className="item" onClick={() => openUser(u.id)} style={u.disabled ? { opacity: .55 } : null}>
- <div className="grow"><div className="tt">{u.live && <Icon name="dot" style={{ fontSize: 9, color: 'var(--green)', display: 'inline-block', marginRight: 5 }} />}{u.name} {u.admin && <span className="tag acc" style={{ marginLeft: 4 }}>admin</span>}{u.disabled && <span className="tag" style={{ marginLeft: 4, color: 'var(--red)' }}>off</span>}</div>
- <div className="ss">{u.live ? 'training now · ' + u.live.name : u.workouts + ' workouts' + (u.lastWorkout ? ' · last ' + fmtDate(u.lastWorkout) : '') + ' · synced ' + rel(u.lastSync)}</div></div>
- {u.hasPush && <Icon name="bell" title="push enabled" style={{ fontSize: 15, color: 'var(--label-3)' }} />}<Icon name="chevronRight" className="chev" />
- </div>)}
- {users && !users.length && <div className="empty">No users yet.</div>}
+ <InvitesCard invites={invites} reload={loadInvites} inviteOnly={inviteOnly} />
+
+ <div className="card">
+ <h2 style={{ margin: 0 }}>Users</h2>
+ <div className="adm-lead">Everyone with a profile on this instance. Tap one to see their activity or to disable the account — their data is never deleted from here.</div>
+ <div className="list">
+ {(users || []).map(u => <div key={u.id} className="item" onClick={() => openUser(u.id)} style={u.disabled ? { opacity: .55 } : null}>
+ <div className="grow"><div className="tt">{u.live && <Icon name="dot" style={{ fontSize: 9, color: 'var(--green)', display: 'inline-block', marginRight: 5 }} />}{u.name} {u.admin && <span className="adm-pill acc" style={{ marginLeft: 4 }}>admin</span>}{u.disabled && <span className="adm-pill bad" style={{ marginLeft: 4 }}>disabled</span>}</div>
+ <div className="ss">{u.live ? 'training now · ' + u.live.name : u.workouts + ' workouts' + (u.lastWorkout ? ' · last ' + fmtDate(u.lastWorkout) : '') + ' · last sync ' + rel(u.lastSync)}</div></div>
+ {u.hasPush && <Icon name="bell" title="push notifications on" style={{ fontSize: 15, color: 'var(--label-3)' }} />}<Icon name="chevronRight" className="chev" />
+ </div>)}
+ {users && !users.length && <div className="adm-empty">No users yet.</div>}
+ </div>
</div>
<div style={{ marginTop: 14 }}><AuditCard tick={tick} /></div>
diff --git a/frontend/src/views/AdminCoach.jsx b/frontend/src/views/AdminCoach.jsx
index eab65681a..4cb52d939 100644
--- a/frontend/src/views/AdminCoach.jsx
+++ b/frontend/src/views/AdminCoach.jsx
@@ -4,22 +4,32 @@ import { api } from '../lib/api.js'
import Icon from '../components/Icon.jsx'
import { Button, Switch, TextField } from '../components/ui.jsx'
-/* The operator's side of the Coach: is it on, can it reach a model, and what has it been
- doing. Like the rest of the admin dashboard this is deliberately English-only — it isn't
- part of the translated end-user surface.
- *
- * What it never shows: anybody's intake answers, payloads or proposals. An admin can enable
- * the feature and see that jobs ran; they cannot read what their users asked it. */
+/* The operator's side of the Coach, laid out as a guided setup: one master switch, numbered
+ steps that each say what they are for, and everything an owner rarely needs folded away
+ under "Advanced" and "Activity". Like the rest of the admin dashboard this is deliberately
+ English-only — it isn't part of the translated end-user surface.
+
+ What it never shows: anybody's intake answers, payloads or proposals. An admin can enable
+ the feature and see that jobs ran; they cannot read what their users asked it.
+
+ This is the ONLY place the Coach can be switched off for everyone. Users can decline the
+ consent screen for themselves, but they cannot disable the feature — that is an operator
+ decision, so it lives with the operator. */
const rel = ts => {
if (!ts) return 'never'
const s = Math.max(0, (Date.now() - new Date(ts).getTime()) / 1000)
if (s < 60) return 'just now'
- if (s < 3600) return Math.floor(s / 60) + 'm ago'
- if (s < 86400) return Math.floor(s / 3600) + 'h ago'
- return Math.floor(s / 86400) + 'd ago'
+ if (s < 3600) return Math.floor(s / 60) + ' min ago'
+ if (s < 86400) return Math.floor(s / 3600) + ' h ago'
+ return Math.floor(s / 86400) + ' d ago'
}
+// Which chips go under which heading. Runtime-backed providers are the ones that need the
+// bigger `coach` image; the fixture exists so the whole loop can be walked without any account.
+const RUNTIME_IDS = ['claude', 'codex']
+const TESTING_IDS = ['fixture']
+
export default function AdminCoach() {
const toast = useUI(s => s.toast)
const openSheet = useUI(s => s.openSheet)
@@ -28,16 +38,11 @@ export default function AdminCoach() {
// The models the endpoint serves, fetched on demand. Seeded from the status call when the
// stored key already let it list them.
const [models, setModels] = useState(null)
+ // The last "Test the Coach" outcome, shown inline where the button is rather than only as a
+ // 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'))
- const loadModels = async () => {
- setBusy(true)
- try {
- const r = await api('/api/admin/coach/models', { method: 'POST', body: '{}' })
- if (r.ok) { setModels(r.models); toast(r.models.length + ' models') } else toast(r.error || 'Could not list models')
- } catch (e) { toast(e.message) }
- setBusy(false)
- }
useEffect(() => { load() }, [])
const patch = async body => {
@@ -46,18 +51,27 @@ export default function AdminCoach() {
catch (e) { toast(e.message) }
setBusy(false)
}
- const test = async () => {
+ const loadModels = async () => {
setBusy(true)
+ try {
+ const r = await api('/api/admin/coach/models', { method: 'POST', body: '{}' })
+ if (r.ok) { setModels(r.models); toast(r.models.length + ' models') } else toast(r.error || 'Could not list models')
+ } catch (e) { toast(e.message) }
+ setBusy(false)
+ }
+ const test = async () => {
+ setBusy(true); setTestResult({ pending: true })
try {
const r = await api('/api/admin/coach/test', { method: 'POST', body: '{}' })
- toast(r.ok ? 'Coach test passed ✅' : 'Test failed: ' + (r.error || 'unknown'))
+ setTestResult(r)
+ toast(r.ok ? 'Coach test passed ✅' : 'Test failed')
await load()
- } catch (e) { toast(e.message) }
+ } catch (e) { setTestResult({ ok: false, error: e.message }); toast(e.message) }
setBusy(false)
}
const disconnect = async () => {
setBusy(true)
- try { await api('/api/admin/coach/disconnect', { method: 'POST', body: '{}' }); toast('Disconnected'); await load() }
+ try { await api('/api/admin/coach/disconnect', { method: 'POST', body: JSON.stringify({ provider: d.provider }) }); toast('Credential removed'); await load() }
catch (e) { toast(e.message) }
setBusy(false)
}
@@ -66,160 +80,258 @@ export default function AdminCoach() {
if (d.disabledByEnv) return <div className="card">
<h2 style={{ margin: '0 0 6px' }}>AI Coach</h2>
- <div className="muted small">Force-disabled by <code>COACH_DISABLED</code> in the environment. Remove it to configure the Coach here.</div>
+ <div className="adm-lead">Force-disabled by <code>COACH_DISABLED</code> in the server's environment. Remove that variable and restart to configure the Coach here.</div>
</div>
const meta = d.providers.find(p => p.id === d.provider) || {}
- const authed = d.auth?.state === 'connected' || d.auth?.state === 'not-required' || d.auth?.state === 'optional'
- const live = d.enabled && d.runtime.ok && authed
+ const authState = d.auth?.state
+ const authed = authState === 'connected' || authState === 'not-required' || authState === 'optional'
+ const needsEndpoint = !!meta.baseUrl
+ const hasEndpoint = !needsEndpoint || !!d.baseUrl
+ const live = d.enabled && d.runtime.ok && authed && hasEndpoint
+
+ const status = !d.enabled ? 'Off — users see no Coach anywhere in the app.'
+ : live ? <>On · {meta.label}{d.model ? ' · ' + d.model : ''}</>
+ : !hasEndpoint ? 'On, but no endpoint yet — finish step 2.'
+ : !authed ? 'On, but no credential yet — finish the Credential step.'
+ : !d.runtime.ok ? 'On, but the provider cannot be reached — see the Test step.'
+ : 'On'
+
+ // Chips, grouped.
+ const groups = [
+ { title: 'Paste an API key', hint: 'Plain HTTPS to the provider. Works on the default api image — nothing extra to install.', items: d.providers.filter(p => p.http) },
+ { title: 'Runs a local AI runtime', hint: 'Needs the bigger api image built with --target coach.', items: d.providers.filter(p => RUNTIME_IDS.includes(p.id)) },
+ { title: 'Testing', hint: 'A built-in fake that answers instantly, so the whole loop can be tried without an account.', items: d.providers.filter(p => TESTING_IDS.includes(p.id)) }
+ ]
+
+ const hasCredentialStep = !!(meta.setupToken || meta.apiKey)
+ const step1Done = !!d.provider
+ const step2Done = hasEndpoint
+ const step3Done = authed
+ const step4Done = !!d.model
+ const step5Done = !!testResult?.ok || !!d.lastSuccess
+ // Step numbers only count the steps this provider actually shows.
+ let n = 1
+ const num = () => n++
return <div className="card" style={{ borderColor: live ? 'var(--acc)' : undefined }}>
- <div className="row between" style={{ marginBottom: 8 }}>
+ <div className="row between" style={{ marginBottom: 2 }}>
<h2 style={{ margin: 0 }}>AI Coach</h2>
<Switch checked={!!d.enabled} disabled={busy} onChange={v => patch({ enabled: v })} />
</div>
-
- {!d.enabled && <div className="muted small">Off. Users see no Coach anywhere in the app.</div>}
+ <div className="adm-status">
+ <span className={'adm-pill ' + (!d.enabled ? '' : live ? 'ok' : 'warn')}>{!d.enabled ? 'off' : live ? 'ready' : 'not ready'}</span>
+ <span>{status}</span>
+ </div>
+ <div className="adm-lead">
+ The Coach designs a training plan and adjusts it from what people log. This switch is the only place it can be turned off for everyone — users decide for themselves whether to use it, but cannot disable it.
+ </div>
{d.enabled && <>
- <div className="tiles" style={{ textAlign: 'left', marginBottom: 10 }}>
- <div className="tile"><div className="l">Runtime</div>
- <div className="v" style={{ fontSize: '.9rem', color: d.runtime.ok ? 'var(--green)' : 'var(--red)' }}>{d.runtime.ok ? 'ready' : 'missing'}</div></div>
- <div className="tile"><div className="l">Credential</div>
- <div className="v" style={{ fontSize: '.9rem', color: authed ? 'var(--green)' : 'var(--red)' }}>{authLabel(d.auth)}</div></div>
- <div className="tile"><div className="l">Jobs today</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.jobsToday}</div></div>
- <div className="tile"><div className="l">Last run</div><div className="v" style={{ fontSize: '.85rem' }}>{rel(d.lastSuccess?.at)}</div></div>
- </div>
-
- {d.runtime.version && <div className="dim small" style={{ marginBottom: 8 }}>{meta.runtime || meta.label} · {d.runtime.version}</div>}
- {!d.runtime.ok && d.runtime.error && <div className="small" style={{ color: 'var(--red)', marginBottom: 8 }}>{d.runtime.error}</div>}
-
- {/* The privilege drop, stated plainly. It fails closed, so when this reads no, nothing
- runs at all — and the admin needs to learn that here rather than from a user
- reporting that the Coach does nothing. The reason is the server's own words. */}
- {d.unprivileged && !d.unprivileged.ok &&
- <div className="small" style={{ color: 'var(--red)', marginBottom: 8, lineHeight: 1.5 }}>
- Jobs are disabled: {d.unprivileged.why}. No job will run until this is fixed.
- </div>}
- {d.unprivileged?.ok &&
- <div className="dim small" style={{ marginBottom: 8 }}>
- Jobs run unprivileged: {d.unprivileged.dropped ? 'yes' : 'no — this host has no separate user to drop to'}
- </div>}
-
- {/* Whose account is being spent, in the admin's own view. The same fact the user sees on
- their Coach screen, because "the admin card and the user screen must both name the
- account" is only true if neither is inferring it from settings. */}
- <div className="dim small" style={{ marginBottom: 8 }}>
- {d.authMode === 'profile'
- ? 'Each profile signs in with their own account.'
- : d.boundUid
- ? 'One shared account, already in use by a profile. Any other profile is refused.'
- : 'One shared account. The first profile to use it binds it; every other profile is then refused.'}
- </div>
-
- {/* provider */}
- <h4 className="sec" style={{ marginTop: 4 }}>Provider</h4>
- <div className="row" style={{ flexWrap: 'wrap', gap: 7, marginBottom: 10 }}>
- {d.providers.map(p => <button key={p.id} className={'chip' + (p.id === d.provider ? ' on' : '')} title={p.connected ? 'a key is stored for this provider' : undefined}
- disabled={busy} onClick={() => patch({ provider: p.id })}>{p.label}{p.connected ? ' ·' : ''}</button>)}
- </div>
- {meta.http && <div className="dim small" style={{ marginTop: -4, marginBottom: 10 }}>
- Plain HTTPS to the provider — no AI runtime needed in the image, so this works on the default <code>api</code> image. Keys stay per provider when you switch.
- </div>}
-
- {/* endpoint — only for the provider whose endpoint is the whole configuration */}
- {meta.baseUrl && <>
- <h4 className="sec">Endpoint</h4>
- <TextField defaultValue={d.baseUrl || ''} placeholder="http://ollama.lan:11434 or https://openrouter.ai/api"
- onBlur={e => e.target.value !== (d.baseUrl || '') && patch({ baseUrl: e.target.value })} />
- <div className="dim small" style={{ marginBottom: 10 }}>Anything that serves OpenAI's Chat Completions shape: Ollama, LM Studio, vLLM, OpenRouter, a gateway of your own. The host is written to the job log.</div>
- </>}
-
- {/* credential */}
- {(meta.setupToken || meta.apiKey) && <>
- <h4 className="sec">Credential</h4>
- {d.auth?.state === 'connected' ? <>
- <div className="small muted" style={{ marginBottom: 8 }}>
- Connected{d.auth.account ? ' as ' + d.auth.account : ''} via {credentialLabel(d.auth.type)} · {rel(d.auth.connectedAt)}
+ {/* ---------- provider ---------- */}
+ <Step n={num()} title="Provider" hint={meta.label || 'Which AI answers the Coach'} done={step1Done} open={!step1Done}>
+ <div className="adm-hint">Pick who answers. A key or token you save stays with its provider, so you can switch back and forth without pasting it again.</div>
+ {groups.map(g => !!g.items.length && <div key={g.title} className="adm-group">
+ <div className="adm-group-t">{g.title}</div>
+ <div className="adm-chips">
+ {g.items.map(p => <button key={p.id} className={'chip' + (p.id === d.provider ? ' on' : '')} disabled={busy}
+ onClick={() => { setTestResult(null); patch({ provider: p.id }) }}>
+ {p.label}{p.connected && <span className="adm-chip-key">key saved</span>}
+ </button>)}
</div>
- <div className="row" style={{ gap: 8 }}>
- <Button size="sm" icon="check" disabled={busy} onClick={test}>Test the Coach</Button>
- <Button size="sm" danger disabled={busy} onClick={disconnect}>Disconnect</Button>
+ <div className="adm-hint" style={{ margin: '6px 0 0' }}>{g.hint}</div>
+ </div>)}
+ </Step>
+
+ {/* ---------- endpoint (compatible only) ---------- */}
+ {needsEndpoint && <Step n={num()} title="Endpoint" hint={d.baseUrl || 'Where the model runs'} done={step2Done} open={!step2Done}>
+ <div className="adm-hint">The address of any server that speaks OpenAI's chat API: <b>Ollama</b>, <b>LM Studio</b>, <b>vLLM</b>, <b>OpenRouter</b>, or a gateway of your own. Just the base — no <code>/v1</code>, no key in the URL.</div>
+ <div className="adm-field">
+ <label>Base URL</label>
+ <TextField key={d.baseUrl || ''} defaultValue={d.baseUrl || ''} placeholder="http://ollama:11434 or https://openrouter.ai/api" inputMode="url" autoCapitalize="none" autoCorrect="off"
+ onBlur={e => e.target.value !== (d.baseUrl || '') && patch({ baseUrl: e.target.value })} />
+ </div>
+ <div className="adm-hint" style={{ margin: 0 }}>The host is written to the job log, so you can always see where requests went.</div>
+ </Step>}
+
+ {/* ---------- credential ---------- */}
+ {hasCredentialStep && <Step n={num()} title="Credential" hint={credentialHint(d.auth, meta)} done={step3Done} open={!step3Done}>
+ <div className="row" style={{ gap: 8, flexWrap: 'wrap', marginBottom: 8 }}>
+ <CredentialPill auth={d.auth} />
+ </div>
+ {authState === 'connected' ? <>
+ <div className="adm-hint">Connected{d.auth.account ? ' as ' + d.auth.account : ''} via {credentialLabel(d.auth.type)}{d.auth.connectedAt ? ' · added ' + rel(d.auth.connectedAt) : ''}. The key is stored encrypted and is never shown again.</div>
+ <div className="adm-actions">
+ {meta.apiKey && <Button size="sm" icon="lock" disabled={busy}
+ onClick={() => openSheet(close => <ApiKeySheet close={close} onDone={load} label={meta.label} placeholder={meta.keyPlaceholder} optional={meta.keyOptional} />)}>Replace key</Button>}
+ <Button size="sm" danger disabled={busy} onClick={disconnect}>Remove</Button>
</div>
</> : <>
- {d.auth?.state === 'expired' && <div className="small" style={{ color: 'var(--red)', marginBottom: 8 }}>The stored credential expired — connect again.</div>}
- {d.auth?.state === 'replace-required' && <div className="small" style={{ color: 'var(--red)', marginBottom: 8 }}>
- The old Claude credential is no longer used. Add a Claude Code setup token instead.
+ {authState === 'unreadable' && <div className="adm-hint" style={{ color: 'var(--red)' }}>
+ The stored credential can't be decrypted. This usually means <code>./data</code> was restored without its <code>secret</code> file. Add the key again to fix it.
</div>}
- {d.auth?.state === 'unreadable' && <div className="small" style={{ color: 'var(--red)', marginBottom: 8 }}>
- The stored credential can't be decrypted — this usually means ./data was restored without its <code>secret</code> file. Connect again.
- </div>}
- <div className="row" style={{ gap: 8, flexWrap: 'wrap' }}>
+ {authState === 'optional' && <div className="adm-hint">This endpoint works without a key. Add one only if your server asks for it (OpenRouter does; a model on your own network usually does not).</div>}
+ {authState === 'none' && <div className="adm-hint">{meta.setupToken
+ ? 'Paste either a Claude Code setup token (your subscription) or an Anthropic API key (pay per use).'
+ : 'Paste an API key from the provider\'s console. It is stored encrypted on this server and sent to the provider only while a job runs.'}</div>}
+ <div className="adm-actions">
{meta.setupToken && <Button size="sm" variant="primary" icon="key" disabled={busy}
- onClick={() => openSheet(close => <SetupTokenSheet close={close} onDone={load} label={meta.label} />)}>Add CLI token</Button>}
+ onClick={() => openSheet(close => <SetupTokenSheet close={close} onDone={load} label={meta.label} />)}>Add Claude Code token</Button>}
{meta.apiKey && <Button size="sm" variant={meta.setupToken ? undefined : 'primary'} icon="lock" disabled={busy}
onClick={() => openSheet(close => <ApiKeySheet close={close} onDone={load} label={meta.label} placeholder={meta.keyPlaceholder} optional={meta.keyOptional} />)}>
- {meta.keyOptional ? 'Add an API key (optional)' : 'Use an API key'}</Button>}
- {meta.keyOptional && <Button size="sm" icon="check" disabled={busy} onClick={test}>Test the Coach</Button>}
+ {meta.keyOptional ? 'Add API key (optional)' : 'Add API key'}</Button>}
</div>
</>}
- </>}
-
- {/* limits */}
- <h4 className="sec">Limits</h4>
- <div className="row" style={{ gap: 10, flexWrap: 'wrap', marginBottom: 4 }}>
- <label className="small muted">Per user / day
- <input className="num" type="number" min="0" max="200" defaultValue={d.caps.perProfileDaily} style={{ width: 70, marginLeft: 8 }}
- onBlur={e => patch({ caps: { ...d.caps, perProfileDaily: +e.target.value } })} /></label>
- <label className="small muted">Whole instance / day
- <input className="num" type="number" min="0" max="5000" defaultValue={d.caps.instanceDaily} style={{ width: 70, marginLeft: 8 }}
- onBlur={e => patch({ caps: { ...d.caps, instanceDaily: +e.target.value } })} /></label>
- </div>
- <div className="dim small" style={{ marginBottom: 10 }}>0 = no limit. Every job is one session on your provider account.</div>
-
- <h4 className="sec">Model</h4>
- {models && models.length ? <>
- <select className="sel" value={models.includes(d.model) ? d.model : ''} disabled={busy} style={{ width: '100%' }}
- onChange={e => patch({ model: e.target.value })}>
- <option value="">{meta.defaultModel ? `(default: ${meta.defaultModel})` : '(pick a model)'}</option>
- {!models.includes(d.model) && d.model && <option value={d.model}>{d.model} (not in the list)</option>}
- {models.map(m => <option key={m} value={m}>{m}</option>)}
- </select>
- </> : <TextField key={d.provider} defaultValue={d.models?.[d.provider] || ''} placeholder={meta.defaultModel ? `(default: ${meta.defaultModel})` : meta.baseUrl ? 'pick one from the endpoint' : '(the provider default)'}
- onBlur={e => e.target.value !== (d.models?.[d.provider] || '') && patch({ model: e.target.value })} />}
- {meta.http && <div className="row" style={{ gap: 8, marginTop: 6, marginBottom: 6 }}>
- <Button size="sm" disabled={busy} onClick={loadModels}>{models ? 'Refresh models' : 'List models'}</Button>
- {models && models.length ? <span className="dim small">{models.length} served by the endpoint</span> : null}
- </div>}
-
- {d.lastError && <>
- <h4 className="sec">Last failure</h4>
- <div className="small" style={{ color: 'var(--red)' }}>{d.lastError.errorClass}{d.lastError.detail ? ' — ' + d.lastError.detail : ''}</div>
- <div className="dim" style={{ fontSize: '.72rem' }}>{rel(d.lastError.at)}</div>
- </>}
-
- {!!d.recent?.length && <>
- <h4 className="sec">Recent jobs</h4>
- {d.recent.slice(0, 8).map((e, i) => <div key={i} className="row between" style={{ padding: '5px 2px', borderBottom: '1px solid var(--sep)' }}>
- <span className="small">{e.kind}{e.trigger === 'scheduled' ? ' · scheduled' : ''}</span>
- <span className="dim" style={{ fontSize: '.72rem' }}>
- <span style={{ color: e.outcome === 'failed' ? 'var(--red)' : e.outcome === 'ready' ? 'var(--acc)' : undefined }}>{e.outcome}</span>
- {e.ms ? ' · ' + Math.round(e.ms / 1000) + 's' : ''} · {rel(e.at)}
- </span>
- </div>)}
- </>}
+ </Step>}
+
+ {/* ---------- model ---------- */}
+ <Step n={num()} title="Model" hint={d.model || (meta.defaultModel ? 'default: ' + meta.defaultModel : 'not chosen yet')} done={step4Done} open={!step4Done}>
+ <div className="adm-hint">{meta.http
+ ? 'Which model the provider should use. "List models" asks the provider for its current list, so nothing here goes stale.'
+ : 'Optional. Leave it empty to use the runtime\'s own default.'}</div>
+ <div className="adm-field">
+ <label>Model</label>
+ {models && models.length
+ ? <select className="adm-select" value={models.includes(d.model) ? d.model : ''} disabled={busy} onChange={e => patch({ model: e.target.value })}>
+ <option value="">{meta.defaultModel ? `Default (${meta.defaultModel})` : 'Pick a model…'}</option>
+ {d.model && !models.includes(d.model) && <option value={d.model}>{d.model} (not in the list)</option>}
+ {models.map(m => <option key={m} value={m}>{m}</option>)}
+ </select>
+ : <TextField key={d.provider} defaultValue={d.models?.[d.provider] || ''} placeholder={meta.defaultModel ? `Default: ${meta.defaultModel}` : needsEndpoint ? 'e.g. qwen2.5:3b — or press "List models"' : '(runtime default)'}
+ onBlur={e => e.target.value !== (d.models?.[d.provider] || '') && patch({ model: e.target.value })} />}
+ </div>
+ {meta.http && <div className="adm-actions">
+ <Button size="sm" disabled={busy} onClick={loadModels}>{models ? 'Refresh list' : 'List models'}</Button>
+ {models && models.length ? <span className="dim small" style={{ alignSelf: 'center' }}>{models.length} served by the provider</span> : null}
+ </div>}
+ </Step>
+
+ {/* ---------- test ---------- */}
+ <Step n={num()} title="Test" hint={step5Done ? 'passed' : 'one real round trip, no user data'} done={step5Done} open={!step5Done || !!testResult}>
+ <div className="adm-hint">Sends one tiny question to the provider and checks the answer. No training data is involved. Do this after every change above.</div>
+ <div className="adm-actions">
+ <Button size="sm" variant="primary" icon="check" disabled={busy || !authed || !hasEndpoint} onClick={test}>Test the Coach</Button>
+ </div>
+ {testResult && <div className={'adm-result ' + (testResult.pending ? '' : testResult.ok ? 'ok' : 'bad')}>
+ {testResult.pending ? 'Asking the provider…'
+ : testResult.ok ? <><b>Passed</b>{testResult.version ? 'Provider: ' + testResult.version : 'The provider answered as expected.'}</>
+ : <><b>Failed</b>{testResult.error || 'No answer from the provider.'}</>}
+ </div>}
+ <div className="adm-kv" style={{ marginTop: 10 }}>
+ <span className="k">Runtime</span>
+ <span className="v">{d.runtime.ok ? <span className="adm-pill ok">ready</span> : <span className="adm-pill bad">missing</span>}{d.runtime.version ? <div className="dim small">{d.runtime.version}</div> : null}{!d.runtime.ok && d.runtime.error ? <div className="small" style={{ color: 'var(--red)' }}>{d.runtime.error}</div> : null}</span>
+ </div>
+ </Step>
+
+ {/* ---------- advanced ---------- */}
+ <details className="adm-fold">
+ <summary>Advanced <Icon name="chevronRight" className="chev" /></summary>
+ <div className="adm-fold-b">
+ <div className="adm-group-t">Limits</div>
+ <div className="adm-hint">How many Coach runs are allowed per day. Every run is one request on the provider account above. 0 means no limit.</div>
+ <div className="adm-kv"><span className="k">Per user, per day</span>
+ <span className="v"><input className="num" type="number" min="0" max="200" defaultValue={d.caps.perProfileDaily} disabled={busy}
+ onBlur={e => +e.target.value !== d.caps.perProfileDaily && patch({ caps: { ...d.caps, perProfileDaily: +e.target.value } })} /></span></div>
+ <div className="adm-kv"><span className="k">Whole instance, per day</span>
+ <span className="v"><input className="num" type="number" min="0" max="5000" defaultValue={d.caps.instanceDaily} disabled={busy}
+ onBlur={e => +e.target.value !== d.caps.instanceDaily && patch({ caps: { ...d.caps, instanceDaily: +e.target.value } })} /></span></div>
+
+ <div className="adm-group-t" style={{ marginTop: 14 }}>Whose account pays</div>
+ <div className="adm-hint">{d.authMode === 'profile'
+ ? 'Each profile signs in with their own account.'
+ : d.boundUid
+ ? 'One shared account, already in use by one profile. Every other profile is refused, so nobody spends somebody else\'s subscription.'
+ : 'One shared account. The first profile to use it becomes the only one allowed to — every other profile is then refused.'}</div>
+
+ <div className="adm-group-t" style={{ marginTop: 14 }}>Isolation</div>
+ <div className="adm-hint">{d.unprivileged && !d.unprivileged.ok
+ ? <span style={{ color: 'var(--red)' }}>Jobs are blocked: {d.unprivileged.why}. Nothing runs until this is fixed.</span>
+ : d.unprivileged?.dropped
+ ? 'Jobs run as a separate unprivileged user that cannot read your data directory or secrets.'
+ : d.unprivileged?.why?.includes('no child process')
+ ? 'Not needed for this provider — it makes an HTTPS request and starts no program on this server.'
+ : 'Jobs run with the server\'s own user on this host (no separate user to drop to).'}</div>
+ </div>
+ </details>
+
+ {/* ---------- activity ---------- */}
+ <details className="adm-fold">
+ <summary>Activity <Icon name="chevronRight" className="chev" /></summary>
+ <div className="adm-fold-b">
+ <div className="tiles" style={{ textAlign: 'left', marginBottom: 10 }}>
+ <div className="tile"><div className="l">Jobs today</div><div className="v" style={{ fontSize: '1.1rem' }}>{d.jobsToday}</div></div>
+ <div className="tile"><div className="l">Last success</div><div className="v" style={{ fontSize: '.85rem' }}>{rel(d.lastSuccess?.at)}</div></div>
+ </div>
+ {d.lastError && <>
+ <div className="adm-group-t">Last failure</div>
+ <div className="adm-result bad" style={{ marginTop: 0, marginBottom: 10 }}>
+ <b>{failureTitle(d.lastError.errorClass)}</b>
+ {d.lastError.detail ? <span className="small">{d.lastError.detail}</span> : null}
+ <div className="dim" style={{ fontSize: '.72rem', marginTop: 4 }}>{rel(d.lastError.at)}</div>
+ </div>
+ </>}
+ <div className="adm-group-t">Recent jobs</div>
+ {d.recent?.length ? <div className="adm-log">
+ {d.recent.slice(0, 10).map((e, i) => <div key={i} className="adm-log-row">
+ <span>{e.kind === 'create' ? 'Plan' : 'Review'}{e.trigger === 'scheduled' ? ' · scheduled' : ''} · <span style={{ color: e.outcome === 'failed' ? 'var(--red)' : e.outcome === 'ready' ? 'var(--acc)' : 'var(--label-2)' }}>{e.outcome}</span>{e.ms ? ' · ' + Math.round(e.ms / 1000) + ' s' : ''}</span>
+ <span className="when">{rel(e.at)}</span>
+ </div>)}
+ </div> : <div className="adm-empty">No jobs yet.</div>}
+ <div className="adm-hint" style={{ margin: '8px 0 0' }}>Counts and outcomes only. What people asked the Coach, and what it answered, is never shown here.</div>
+ </div>
+ </details>
</>}
</div>
}
-const authLabel = a => ({
- connected: 'connected', 'not-required': 'n/a', none: 'needed', optional: 'none (optional)', disconnected: 'needed', expired: 'expired', unreadable: 'unreadable', 'replace-required': 'replace'
-}[a?.state] || '—')
+/* ---------------------------------- pieces ---------------------------------- */
+
+function Step({ n, title, hint, done, open, children }) {
+ return <details className={'adm-step ' + (done ? 'done' : 'todo')} open={open}>
+ <summary>
+ <span className="adm-num">{done ? <Icon name="check" /> : n}</span>
+ <span className="adm-step-t"><b>{title}</b><span>{hint}</span></span>
+ <Icon name="chevronRight" className="chev" />
+ </summary>
+ <div className="adm-step-b">{children}</div>
+ </details>
+}
+
+function CredentialPill({ auth }) {
+ const s = auth?.state
+ if (s === 'connected') return <span className="adm-pill ok">connected{auth.account ? ' · ' + auth.account : ''}</span>
+ if (s === 'not-required') return <span className="adm-pill">not needed</span>
+ if (s === 'optional') return <span className="adm-pill">optional — none saved</span>
+ if (s === 'unreadable') return <span className="adm-pill bad">can't be read</span>
+ return <span className="adm-pill warn">needed</span>
+}
+
+const credentialHint = (auth, meta) => {
+ const s = auth?.state
+ if (s === 'connected') return 'Connected' + (auth.account ? ' as ' + auth.account : '')
+ if (s === 'not-required') return 'Not needed'
+ if (s === 'optional') return 'Optional for this endpoint'
+ if (s === 'unreadable') return 'Stored key can\'t be read — add it again'
+ return meta.setupToken ? 'Token or API key needed' : 'API key needed'
+}
const credentialLabel = type => ({
'cli-token': 'Claude Code setup token', 'chatgpt-cli': 'ChatGPT CLI login', oauth: 'legacy token', apikey: 'API key'
}[type] || 'credential')
+// The failure classes jobs.js emits, in words an operator can act on.
+const failureTitle = cls => ({
+ timeout: 'The provider took too long (over 5 minutes)',
+ missing: 'The provider runtime or key is missing',
+ auth: 'The provider rejected the credential',
+ provider: 'The provider returned an error',
+ unusable: 'The model answered, but not in a shape the app could use',
+ restart: 'The server restarted while a job was running',
+ nostate: 'The user\'s training data could not be read',
+ off: 'The Coach was off when the job ran',
+ internal: 'Something went wrong on the server'
+}[cls] || cls || 'Failed')
+
/* ------------------------------- setup token -------------------------------- */
function SetupTokenSheet({ close, onDone, label }) {
@@ -235,7 +347,7 @@ function SetupTokenSheet({ close, onDone, label }) {
try {
const r = await api('/api/admin/coach/connect', { method: 'POST', body: JSON.stringify({ type: 'cli-token', token: token.trim(), account: account.trim() }) })
setToken('')
- toast(r.test?.ok ? 'Connected ✅' : 'Saved, but the test failed: ' + (r.test?.error || ''))
+ toast(r.test?.ok ? 'Connected ✅' : 'Token saved')
close(); onDone()
} catch (e) { toast(e.message); setBusy(false) }
}
@@ -249,7 +361,7 @@ function SetupTokenSheet({ close, onDone, label }) {
<div style={{ height: 8 }} />
<TextField value={account} placeholder="whose account is this? (e.g. [email protected])" onChange={e => setAccount(e.target.value)} />
<div style={{ height: 12 }} />
- <Button variant="primary" disabled={busy || !token.trim()} onClick={save}>Save and test</Button>
+ <Button variant="primary" disabled={busy || !token.trim()} onClick={save}>Save token</Button>
<div style={{ height: 8 }} />
</>
}
@@ -262,16 +374,16 @@ function ApiKeySheet({ close, onDone, label, placeholder, optional }) {
setBusy(true)
try {
const r = await api('/api/admin/coach/connect', { method: 'POST', body: JSON.stringify({ type: 'apikey', token: key.trim() }) })
- toast(r.test?.ok ? 'Key saved ✅' : 'Saved, but the test failed: ' + (r.test?.error || ''))
+ toast(r.test?.ok ? 'Key saved ✅' : 'Key saved')
close(); onDone()
} catch (e) { toast(e.message); setBusy(false) }
}
return <>
<h3>{label} API key</h3>
<div className="muted small" style={{ lineHeight: 1.5, marginBottom: 12 }}>
- Stored encrypted on this server and sent to the provider only while a job runs. It is never shown again and never leaves the server{optional ? ' — and for an endpoint that takes no key, leave this empty.' : '.'}
+ Stored encrypted on this server and sent to the provider only while a job runs. It is never shown again and never leaves the server{optional ? ' — and for an endpoint that takes no key, you can leave this empty and close the sheet.' : '.'}
</div>
- <TextField value={key} autoFocus type="password" placeholder={placeholder || 'sk-…'} onChange={e => setKey(e.target.value)} />
+ <TextField value={key} autoFocus type="password" placeholder={placeholder || 'sk-…'} autoCapitalize="none" autoCorrect="off" onChange={e => setKey(e.target.value)} />
<div style={{ height: 12 }} />
<Button variant="primary" disabled={busy || !key.trim()} onClick={save}>Save key</Button>
<div style={{ height: 8 }} />
diff --git a/frontend/src/views/CoachChat.jsx b/frontend/src/views/CoachChat.jsx
new file mode 100644
index 000000000..e38b0570c
--- /dev/null
+++ b/frontend/src/views/CoachChat.jsx
@@ -0,0 +1,416 @@
+// The conversation with the Coach.
+//
+// Everything the Coach does happens here: your answers as the opening message, a typing
+// bubble while a job runs (with how long it usually takes), the plan or the suggestions as a
+// card you page through, a composer to say what to change, and one button that imports the
+// result. History stays in the thread — come back any time, ask for a review, refine again.
+//
+// The thread is `S.coach.chat` (small, synced) plus whatever is live right now from the
+// status poll: a running job or a pending proposal. Nothing about the proposal is copied into
+// the chat until a decision is made about it, so two devices can never disagree on what is
+// pending. Turning the Coach off is the admin's decision, not a control on this screen.
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { useNavigate } from 'react-router-dom'
+import { useStore } from '../store/useStore.js'
+import { useUI } from '../store/useUI.js'
+import { t } from '../lib/i18n.js'
+import { fmtDate, DAYS } from '../lib/format.js'
+import { exLine } from '../lib/history.js'
+import { DEMO } from '../lib/demo.js'
+import { MOBILE } from '../lib/mobile.js'
+import {
+ coachAvailable, hasConsent, emptyCoach, appendChat, recordTiming, estimateMs, profileLines,
+ markStale, applicable, applyChangeSet, applyCreatedPlan, recordDismissal,
+ changeTitle, changeValues, exName, canRevert, revertLast
+} from '../lib/coach.js'
+import { useCoachStatus, requestReview, refinePlan, resolvePending, JOB_ERRORS } from '../lib/coach-api.js'
+import { confirmSheet } from '../sheets.jsx'
+import Icon from '../components/Icon.jsx'
+import { Button, Check, Switch, Section, Row, SelectRow } from '../components/ui.jsx'
+import '../coach.css'
+
+export default function CoachChat() {
+ const nav = useNavigate()
+ const S = useStore(s => s.S)
+ const user = useStore(s => s.user)
+ const config = useStore(s => s.config)
+ const coachLocal = useStore(s => s.coachLocal)
+ const update = useStore(s => s.update)
+ const toast = useUI(s => s.toast)
+ const openSheet = useUI(s => s.openSheet)
+ const { job, pending, cap, loading, lastError, last, refresh } = useCoachStatus(true)
+ const [text, setText] = useState('')
+ const [busy, setBusy] = useState(false)
+ const endRef = useRef(null)
+ const prevJob = useRef(null)
+ const coachMode = coachLocal?.mode
+
+ const ok = coachAvailable(config, user, { demo: DEMO, mobile: MOBILE, coachMode })
+ const ready = ok && hasConsent(S) && !!S.coach?.profile
+ useEffect(() => {
+ if (!ok) nav('/home', { replace: true })
+ else if (!ready) nav('/coach/intake', { replace: true })
+ }, [ok, ready])
+
+ // A job that ends is either a proposal, "nothing to change", or a failure. The server tells
+ // the client none of that directly — the job simply stops appearing — so the transition is
+ // read here, once, and written into the thread as the Coach's reply.
+ useEffect(() => {
+ if (loading) return
+ const was = prevJob.current
+ prevJob.current = job
+ if (!was || job) return
+ const ms = was.startedAt ? Date.now() - was.startedAt : 0
+ update(s => {
+ recordTiming(s, ms)
+ 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: '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.') })
+ }
+ })
+ }, [job, pending, loading])
+
+ useEffect(() => { if (typeof endRef.current?.scrollIntoView === 'function') endRef.current.scrollIntoView({ block: 'end' }) }, [S.coach?.chat?.length, !!job, !!pending])
+
+ if (!ready) return null
+ const coach = S.coach || emptyCoach()
+
+ const send = async () => {
+ const msg = text.trim()
+ if (!msg || busy) return
+ setBusy(true)
+ try {
+ if (pending?.kind === 'create') await refinePlan(msg)
+ else await requestReview(msg)
+ update(s => appendChat(s, { role: 'user', kind: 'text', text: msg }))
+ setText('')
+ refresh()
+ } catch (e) {
+ toast(e.message || t('Could not ask the Coach'))
+ }
+ setBusy(false)
+ }
+
+ const askReview = async () => {
+ setBusy(true)
+ try {
+ await requestReview('')
+ update(s => appendChat(s, { role: 'user', kind: 'text', text: t('Have a look at my training and tell me what you would change.') }))
+ refresh()
+ } catch (e) { toast(e.message || t('Could not ask the Coach')) }
+ setBusy(false)
+ }
+
+ const menu = () => openSheet(close => <div className="chat-menu">
+ <h3>{t('Coach')}</h3>
+ <div className="sect-b">
+ {!job && !pending && <Row icon="sparkles" iconTint="var(--acc)" title={t('Ask for a review')} subtitle={t('What would the Coach change after your last sessions?')} accessory="chevron" onClick={() => { close(); askReview() }} />}
+ <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() }} />}
+ </div>
+ <div style={{ height: 10 }} />
+ </div>)
+
+ const doRevert = () => confirmSheet({
+ title: t('Undo the last Coach changes?'),
+ message: t('Your plan goes back to how it was before you accepted them. Workouts you have logged since are untouched.'),
+ confirmText: t('Undo'),
+ onConfirm: () => {
+ let ok = false
+ update(s => { ok = revertLast(s); if (ok) appendChat(s, { role: 'coach', kind: 'reverted', text: t('Done — your plan is back to how it was before my last changes.') }) })
+ toast(ok ? t('Plan restored') : t('Nothing to undo'))
+ }
+ })
+
+ const status = job ? t('thinking…') : pending ? t('has a suggestion for you') : t('here when you need it')
+ const placeholder = pending?.kind === 'create'
+ ? t('Tell the Coach what to change…')
+ : job ? t('Wait for the Coach to finish…') : t('Ask for a review, or tell the Coach something…')
+
+ return <div className="narrow chat">
+ <div className="chat-hdr">
+ <button className="iconbtn" onClick={() => nav('/plan')} aria-label={t('Back')}><Icon name="chevronLeft" /></button>
+ <div className="chat-av"><Icon name="sparkles" /></div>
+ <div className="grow">
+ <h1>{t('Coach')}</h1>
+ <div className={'chat-st' + (job ? ' live' : '')}>{status}</div>
+ </div>
+ <button className="iconbtn" onClick={menu} aria-label={t('More')}><Icon name="list" /></button>
+ </div>
+
+ <div className="msgs">
+ <Bubble role="coach">{t('Hi — I’m your Coach. I build your plan from your answers and adjust it from what you actually log. Nothing changes until you say so.')}</Bubble>
+
+ {(coach.chat || []).map(m => <Message key={m.id} m={m} profile={coach.profile} />)}
+
+ {job && <Typing S={S} kind={job.kind} coachLocal={coachLocal} />}
+
+ {pending && !job && (pending.kind === 'create'
+ ? <PlanCard p={pending} S={S} update={update} toast={toast} nav={nav} refresh={refresh} />
+ : <ReviewCard p={pending} S={S} update={update} toast={toast} refresh={refresh} />)}
+
+ <div ref={endRef} />
+ </div>
+
+ <div className="composer">
+ <div className="composer-in">
+ <textarea rows={1} value={text} maxLength={1000} placeholder={placeholder} disabled={!!job}
+ onChange={e => setText(e.target.value)}
+ onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send() } }} />
+ <button className="send" onClick={send} disabled={!text.trim() || busy || !!job} aria-label={t('Send')}><Icon name="arrowUp" /></button>
+ </div>
+ {cap?.limit > 0 && <div className="composer-cap">{t('{0} of {1} Coach runs used today', cap.used, cap.limit)}</div>}
+ </div>
+ </div>
+}
+
+/* ---------------------------------- bubbles ---------------------------------- */
+
+function Bubble({ role, kind, at, children }) {
+ const cls = kind === 'error' ? ' err' : ''
+ return <div className={'msg ' + role}>
+ <div className={'bub' + cls}>{children}</div>
+ {at && <div className="msg-t">{stamp(at)}</div>}
+ </div>
+}
+
+function Message({ m, profile }) {
+ if (m.kind === 'intake') {
+ const lines = profileLines(profile)
+ return <Bubble role="user" at={m.at}>
+ {t('Here is what I am working with:')}
+ <ul>{lines.map((l, i) => <li key={i}>{l}</li>)}</ul>
+ </Bubble>
+ }
+ if (m.kind === 'applied' || m.kind === 'dismissed' || m.kind === 'reverted' || m.kind === 'nochange' || m.kind === 'error' || m.kind === 'text') {
+ return <Bubble role={m.role} kind={m.kind} at={m.at}>{m.text}</Bubble>
+ }
+ return null
+}
+
+const stamp = at => {
+ const d = new Date(at)
+ const today = new Date()
+ const time = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
+ return d.toDateString() === today.toDateString() ? time : fmtDate(d.toISOString().slice(0, 10)) + ' · ' + time
+}
+
+function Typing({ S, kind, coachLocal }) {
+ const ms = estimateMs(S)
+ const local = coachLocal?.mode === 'byok' && coachLocal?.provider === 'compatible'
+ let eta
+ if (ms) {
+ const min = Math.round(ms / 60000)
+ eta = min < 1 ? t('Usually under a minute.') : t('Usually about {0} min.', min)
+ } else {
+ eta = t('This usually takes a minute or two.')
+ }
+ return <div className="msg coach">
+ <div className="bub typing"><i /><i /><i /></div>
+ <div className="typing-eta">
+ {kind === 'create' ? t('Building your plan…') : t('Reading your training…')} {eta}
+ {local ? ' ' + t('A local model can take longer.') : ''}
+ {' ' + t('You can leave — it keeps going.')}
+ </div>
+ </div>
+}
+
+/* ---------------------------------- the plan ---------------------------------- */
+
+function PlanCard({ p, S, update, toast, nav, refresh }) {
+ const b = p.bundle
+ const [tab, setTab] = useState(0)
+ const [schedule, setSchedule] = useState(true)
+ const r = b.routines[Math.min(tab, b.routines.length - 1)]
+ const weekDays = useMemo(() => new Set(Object.keys(b.week || {}).map(Number)), [b])
+
+ const accept = () => {
+ try {
+ let n = 0
+ update(s => {
+ const res = applyCreatedPlan(s, p, { schedule })
+ n = res?.routines?.length || b.routines.length
+ appendChat(s, { role: 'coach', kind: 'applied', text: schedule
+ ? t('Imported — {0} routines are in your plan and your week is set. See you at the next session.', n)
+ : t('Imported — {0} routines are in your plan. Your week is unchanged; schedule them whenever you like.', n) })
+ })
+ resolvePending({ accepted: ['plan'] }).catch(() => {})
+ toast(t('Your plan is live'))
+ refresh()
+ } catch (e) { toast(e.message || t('That proposal can’t be read.')) }
+ }
+ const discard = () => confirmSheet({
+ title: t('Discard this plan?'), message: t('Nothing is saved, and you can ask again anytime.'),
+ confirmText: t('Discard'), danger: true,
+ onConfirm: () => {
+ update(s => { recordDismissal(s, p); appendChat(s, { role: 'coach', kind: 'dismissed', text: t('Discarded. Tell me what was off and I will build a different one.') }) })
+ resolvePending({ dismissed: true }).catch(() => {})
+ refresh()
+ }
+ })
+
+ return <div className="msg coach" style={{ maxWidth: '100%', width: '100%' }}>
+ <div className="pcard">
+ <div className="pcard-hd">
+ <div className="pcard-eyebrow">{p.iteration > 1 ? t('Revision {0}', p.iteration) : t('Your plan')}</div>
+ <h2 className="pcard-h">{b.name || t('Coach plan')}</h2>
+ {!!b.summary && <p className="pcard-sum">{b.summary}</p>}
+ {!!b.basedOn && <p className="pcard-sum" style={{ fontSize: 13 }}>{b.basedOn}</p>}
+ </div>
+
+ <div className="pcard-week">
+ {[1, 2, 3, 4, 5, 6, 0].map(d => <div key={d} className={'pcard-wd' + (weekDays.has(d) ? ' on' : '')}>{t(DAYS[d])}</div>)}
+ </div>
+
+ {b.routines.length > 1 && <div className="pcard-tabs">
+ {b.routines.map((x, i) => <button key={x.id || i} className={'pcard-tab' + (i === tab ? ' on' : '')} onClick={() => setTab(i)}>{x.emoji} {x.name}</button>)}
+ </div>}
+
+ {r && <div className="pcard-rt">
+ <div className="pcard-rt-h"><b>{r.emoji} {r.name}</b><span>{t('{0} exercises', r.ex.length)}</span></div>
+ {!!r.why && <div className="pcard-why">{r.why}</div>}
+ {r.ex.map((e, i) => <div key={i} className="pcard-ex">
+ <div className="pcard-ex-r"><span className="pcard-ex-n">{exName(e.id)}</span><span className="pcard-ex-l">{exLine(e, S.unit)}</span></div>
+ {!!e.why && <div className="pcard-ex-w">{e.why}</div>}
+ </div>)}
+ </div>}
+
+ <div className="pcard-row">
+ <span className="lrow-m"><span className="lrow-t">{t('Use this weekly schedule')}</span><span className="lrow-s">{t('Replaces your current week. Days this plan leaves empty become rest days.')}</span></span>
+ <Switch checked={schedule} onChange={setSchedule} />
+ </div>
+ <div className="pcard-note">{t('The Coach is not a doctor or a physiotherapist. If something hurts, ask a professional.')}</div>
+ <div className="pcard-ft">
+ <Button variant="primary" icon="download" onClick={accept}>{t('Import this plan')}</Button>
+ <Button onClick={discard}>{t('Discard')}</Button>
+ </div>
+ </div>
+ <div className="msg-t">{t('Not quite right? Say what to change below and I will revise the whole plan.')}</div>
+ </div>
+}
+
+/* ---------------------------------- a review ---------------------------------- */
+
+function ReviewCard({ p, S, update, toast, refresh }) {
+ const marked = useMemo(() => markStale(p, S), [p, S])
+ const usable = applicable(marked)
+ const [accepted, setAccepted] = useState(() => new Set(usable.map(c => c.id)))
+ const toggle = id => setAccepted(s => { const n = new Set(s); n.has(id) ? n.delete(id) : n.add(id); return n })
+
+ const apply = () => {
+ const ids = [...accepted].filter(id => usable.some(c => c.id === id))
+ if (!ids.length) { discard(); return }
+ try {
+ update(s => {
+ applyChangeSet(s, marked, ids)
+ appendChat(s, { role: 'coach', kind: 'applied', text: t(ids.length === 1 ? 'Applied {0} change to your plan.' : 'Applied {0} changes to your plan.', ids.length) })
+ })
+ resolvePending({ accepted: ids, rejected: marked.changes.filter(c => !ids.includes(c.id)).map(c => c.id) }).catch(() => {})
+ toast(t(ids.length === 1 ? '{0} change applied' : '{0} changes applied', ids.length))
+ refresh()
+ } catch (e) { toast(e.message || t('Could not apply those changes')) }
+ }
+ const discard = () => confirmSheet({
+ title: t('Dismiss these suggestions?'), message: t('Nothing changes, and the Coach will remember you turned these down.'),
+ confirmText: t('Dismiss'), danger: true,
+ onConfirm: () => {
+ update(s => { recordDismissal(s, marked); appendChat(s, { role: 'coach', kind: 'dismissed', text: t('Understood — I will not suggest these again without new evidence.') }) })
+ resolvePending({ dismissed: true }).catch(() => {})
+ refresh()
+ }
+ })
+
+ return <div className="msg coach" style={{ maxWidth: '100%', width: '100%' }}>
+ <div className="pcard">
+ <div className="pcard-hd">
+ <div className="pcard-eyebrow">{t('Suggestions')}</div>
+ <h2 className="pcard-h">{t(marked.changes.length === 1 ? '{0} suggestion' : '{0} suggestions', marked.changes.length)}</h2>
+ {!!marked.summary && <p className="pcard-sum">{marked.summary}</p>}
+ {!!marked.evidence?.sessions && <p className="pcard-sum" style={{ fontSize: 13 }}>
+ {t('Based on your last {0} sessions', marked.evidence.sessions)}{marked.evidence.from ? ` · ${fmtDate(marked.evidence.from)} – ${fmtDate(marked.evidence.to)}` : ''}
+ </p>}
+ {marked.planMoved && <p className="pcard-sum" style={{ fontSize: 13, color: 'var(--yellow)' }}>
+ {t('Your plan changed since the Coach looked at it. Suggestions that no longer match are greyed out — ask for a fresh review to see them again.')}
+ </p>}
+ </div>
+
+ {marked.changes.map(c => {
+ const stale = c.status === 'stale'
+ const vals = changeValues(c)
+ return <div key={c.id} className={'pcard-chg' + (stale ? ' stale' : '')}>
+ <div className="grow">
+ <div className="pcard-chg-t">{changeTitle(c)}{c.routineName ? <span className="dim" style={{ fontWeight: 400 }}> · {c.routineName}</span> : null}</div>
+ {vals && <div className="pcard-chg-v"><span className="tag">{vals.before}</span><Icon name="chevronRight" style={{ fontSize: 12, color: 'var(--label-3)' }} /><span className="tag acc">{vals.after}</span></div>}
+ <div className="pcard-chg-w">{c.why}</div>
+ {stale && <div className="pcard-chg-stale">{t('Doesn’t match your plan any more — can’t be applied.')}</div>}
+ </div>
+ {!stale && <Check checked={accepted.has(c.id)} onChange={() => toggle(c.id)} />}
+ </div>
+ })}
+
+ {!!marked.notes?.length && <div className="pcard-notes">
+ {marked.notes.map((n, i) => <div key={i}>💬 {n}</div>)}
+ </div>}
+
+ <div className="pcard-note">{t('The Coach is not a doctor or a physiotherapist. If something hurts, ask a professional.')}</div>
+ <div className="pcard-ft">
+ <Button variant="primary" icon="check" onClick={apply}>
+ {accepted.size ? t(accepted.size === 1 ? 'Apply {0} change' : 'Apply {0} changes', accepted.size) : t('Apply nothing')}
+ </Button>
+ <Button onClick={discard}>{t('Dismiss all')}</Button>
+ </div>
+ </div>
+ </div>
+}
+
+/* ---------------------------------- cadence ---------------------------------- */
+
+const cadenceLabel = coach => {
+ const c = coach.cadence && coach.cadence !== 'off' ? coach.cadence : null
+ if (!c) return t('Off')
+ if (c.weekly) return t('Weekly')
+ return t('After every few workouts')
+}
+
+function cadenceSheet(openSheet, update) {
+ openSheet(close => <CadenceSheet close={close} update={update} />)
+}
+function CadenceSheet({ update }) {
+ const coach = useStore(s => s.S.coach) || emptyCoach()
+ const cadence = coach.cadence && coach.cadence !== 'off' ? coach.cadence : null
+ const mode = !cadence ? 'off' : cadence.weekly ? 'weekly' : 'every'
+ const setMode = m => update(s => {
+ const c = (s.coach = s.coach || emptyCoach())
+ c.cadence = m === 'off' ? 'off' : m === 'weekly' ? { weekly: { day: 0, time: '18:00' } } : { everyWorkouts: 4 }
+ })
+ const patch = fn => update(s => { const c = (s.coach = s.coach || emptyCoach()); fn(c) })
+ return <>
+ <h3>{t('Automatic reviews')}</h3>
+ <Section footer={mode === 'off' ? t('Off — the Coach only looks when you ask it to.') : t('You are only notified when the Coach actually has something to suggest.')}>
+ <SelectRow icon="clock" iconTint="var(--purple)" title={t('When')} value={mode} onChange={setMode}
+ options={[
+ { value: 'off', label: t('Off') },
+ { value: 'weekly', label: t('Weekly'), subtitle: t('On a day and time you choose') },
+ { value: 'every', label: t('After every few workouts'), subtitle: t('As soon as you have logged enough') }
+ ]} />
+ {mode === 'weekly' && <>
+ <SelectRow icon="calendar" iconTint="var(--orange)" title={t('Day')} value={cadence.weekly.day}
+ onChange={v => patch(c => { c.cadence = { weekly: { ...c.cadence.weekly, day: v } } })}
+ options={['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'].map((d, i) => ({ value: i, label: t(d) }))} />
+ <Row icon="clock" iconTint="var(--purple)" title={t('Time')}>
+ <input type="time" className="timef" value={cadence.weekly.time || '18:00'}
+ onChange={e => patch(c => { c.cadence = { weekly: { ...c.cadence.weekly, time: e.target.value } } })} />
+ </Row>
+ </>}
+ {mode === 'every' && <SelectRow icon="dumbbell" iconTint="var(--teal)" title={t('After how many workouts')}
+ value={cadence.everyWorkouts || 4}
+ onChange={v => patch(c => { c.cadence = { everyWorkouts: v } })}
+ options={[3, 4, 5, 6, 8, 10].map(n => ({ value: n, label: t('{0} workouts', n) }))} />}
+ </Section>
+ </>
+}
diff --git a/frontend/src/views/CoachChat.test.jsx b/frontend/src/views/CoachChat.test.jsx
new file mode 100644
index 000000000..1b5cee1f4
--- /dev/null
+++ b/frontend/src/views/CoachChat.test.jsx
@@ -0,0 +1,159 @@
+import React, { act } from 'react'
+import { createRoot } from 'react-dom/client'
+import { parseHTML } from 'linkedom'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import CoachChat from './CoachChat.jsx'
+import { effectiveRoutine } from '../lib/history.js'
+import { todayISO } from '../lib/format.js'
+
+// The chat is where a plan is imported. These pin that the Import button applies the pending
+// plan through the store, writes the decision into the thread, and leaves today startable.
+const mocks = vi.hoisted(() => {
+ const state = { S: null, pending: null, job: null, nav: vi.fn(), toast: vi.fn(), openSheet: vi.fn(), refresh: vi.fn() }
+ state.storeSnapshot = () => ({
+ S: state.S,
+ user: { id: 'u1' },
+ config: { coach: { enabled: true } },
+ coachLocal: null,
+ update: mut => mut(state.S),
+ })
+ state.uiSnapshot = () => ({ toast: state.toast, openSheet: state.openSheet })
+ return state
+})
+
+vi.mock('../store/useStore.js', () => {
+ const useStore = selector => selector(mocks.storeSnapshot())
+ useStore.getState = mocks.storeSnapshot
+ return { useStore }
+})
+vi.mock('../store/useUI.js', () => {
+ const useUI = selector => selector ? selector(mocks.uiSnapshot()) : mocks.uiSnapshot()
+ useUI.getState = mocks.uiSnapshot
+ return { useUI }
+})
+vi.mock('react-router-dom', () => ({ useNavigate: () => mocks.nav }))
+vi.mock('../lib/coach-api.js', () => ({
+ useCoachStatus: () => ({ pending: mocks.pending, job: mocks.job, cap: null, loading: false, lastError: null, last: null, refresh: mocks.refresh }),
+ resolvePending: vi.fn(() => Promise.resolve({})),
+ refinePlan: vi.fn(() => Promise.resolve({})),
+ requestReview: vi.fn(() => Promise.resolve({})),
+ JOB_ERRORS: { internal: 'x' },
+}))
+vi.mock('../sheets.jsx', () => ({ startFlow: vi.fn(), confirmSheet: vi.fn() }))
+vi.mock('../lib/api.js', () => ({
+ api: vi.fn(() => Promise.resolve({})),
+ IS_APPLE: false, IS_ANDROID: false, BIO: 'biometrics',
+}))
+vi.mock('../coach.css', () => ({}))
+
+let dom, root, container
+const TODAY_WD = new Date(todayISO() + 'T12:00:00').getDay()
+
+const bundle = week => ({
+ opengym_plan: 1, name: 'Coach plan', summary: 'a plan',
+ week,
+ routines: [
+ { id: 'x1', name: 'Full body A', emoji: '💪', why: 'first', ex: [{ id: '0001', sets: 3, reps: 10, mode: 'reps', why: 'because' }] },
+ { id: 'x2', name: 'Full body B', emoji: '🏋️', ex: [{ id: '0002', sets: 3, reps: 8, mode: 'reps' }] }
+ ],
+ customEx: [],
+})
+const everyDay = Object.fromEntries([0, 1, 2, 3, 4, 5, 6].map(d => [d, 'x1']))
+
+const state = () => ({
+ unit: 'kg', lang: 'en', customEx: [], workouts: [], bodyweight: [], exWeights: {},
+ dayPlan: {}, routines: [], week: {},
+ coach: {
+ consent: { agreedAt: '2026-07-01T00:00:00Z', version: 1 },
+ profile: { goal: 'muscle', experience: 'new', daysPerWeek: 3, sessionMin: 60, preferredDays: [1, 3, 5], equipment: [] },
+ log: [], snapshots: [], chat: [{ id: 'c1', role: 'user', kind: 'intake', at: 1 }], timings: []
+ },
+})
+
+function installDom() {
+ const parsed = parseHTML('<!doctype html><html><body><div id="root"></div></body></html>')
+ dom = parsed.window
+ globalThis.window = dom
+ globalThis.document = dom.document
+ Object.defineProperty(globalThis, 'navigator', { configurable: true, value: dom.navigator })
+ for (const key of ['HTMLElement', 'Node', 'Element', 'Event', 'Blob']) globalThis[key] = dom[key]
+ globalThis.IS_REACT_ACT_ENVIRONMENT = true
+ container = document.getElementById('root')
+ root = createRoot(container)
+}
+
+async function mount(pending, job = null) {
+ mocks.S = state()
+ mocks.pending = pending
+ mocks.job = job
+ installDom()
+ await act(async () => { root.render(React.createElement(CoachChat)) })
+}
+
+const byText = re => [...container.querySelectorAll('button')].find(b => re.test(b.textContent || ''))
+async function click(el) {
+ expect(el).toBeTruthy()
+ await act(async () => { el.dispatchEvent(new dom.Event('click', { bubbles: true })) })
+}
+
+beforeEach(() => { vi.clearAllMocks() })
+afterEach(async () => {
+ if (root) { await act(async () => { root.unmount() }); root = null }
+ container = null; dom = null
+})
+
+describe('the Coach chat', () => {
+ it('opens with the questionnaire summary and pitches the plan as a card with routine tabs', async () => {
+ await mount({ id: 'p1', kind: 'create', bundle: bundle(everyDay) })
+ expect(container.textContent).toContain('Build muscle')
+ expect(container.textContent).toContain('3 days a week')
+ expect(container.querySelectorAll('.pcard-tab').length).toBe(2)
+ expect(container.textContent).toContain('because')
+ await click([...container.querySelectorAll('.pcard-tab')][1])
+ expect(container.querySelector('.pcard-rt-h b').textContent).toContain('Full body B')
+ })
+
+ it('imports the plan through the store, records it in the thread, and leaves today startable', async () => {
+ await mount({ id: 'p1', kind: 'create', bundle: bundle(everyDay) })
+ await click(byText(/Import this plan/))
+ const s = mocks.S
+ expect(s.routines.length).toBe(2)
+ expect(s.week[TODAY_WD]).toBeTruthy()
+ const todays = effectiveRoutine(s, todayISO())
+ expect(todays && todays.ex.length).toBeGreaterThan(0)
+ expect(s.coach.chat.at(-1).kind).toBe('applied')
+ expect(s.coach.snapshots).toHaveLength(1)
+ expect(mocks.refresh).toHaveBeenCalled()
+ })
+
+ it('leaves the week alone when the schedule switch is off', async () => {
+ await mount({ id: 'p1', kind: 'create', bundle: bundle(everyDay) })
+ const sw = container.querySelector('[role="switch"]')
+ expect(sw.getAttribute('aria-checked')).toBe('true')
+ await click(sw)
+ await click(byText(/Import this plan/))
+ expect(Object.keys(mocks.S.week)).toHaveLength(0)
+ expect(mocks.S.routines.length).toBe(2)
+ })
+
+ it('shows the typing bubble with an estimate while a job runs, and disables the composer', async () => {
+ await mount(null, { id: 'j1', kind: 'create', state: 'running', startedAt: Date.now() })
+ expect(container.querySelector('.typing')).toBeTruthy()
+ expect(container.textContent).toContain('usually takes')
+ expect(container.querySelector('.composer textarea').disabled).toBe(true)
+ })
+
+ it('applies the accepted subset of a review and logs it', async () => {
+ mocks.S = state()
+ await mount({ id: 'r1', kind: 'review', summary: 's', changes: [
+ { id: 'a', type: 'week', target: { weekday: 1 }, before: null, after: null, why: 'rest' },
+ { id: 'b', type: 'add-routine', target: {}, before: null, after: { name: 'Legs', ex: [{ id: '0001', sets: 3, reps: 10 }] }, why: 'legs' }
+ ] })
+ expect(container.querySelectorAll('[role="checkbox"]').length).toBe(2)
+ await click([...container.querySelectorAll('[role="checkbox"]')][0]) // drop the week change
+ await click(byText(/Apply 1 change/))
+ expect(mocks.S.routines.map(r => r.name)).toEqual(['Legs'])
+ expect(mocks.S.coach.chat.at(-1).kind).toBe('applied')
+ expect(mocks.S.coach.log.at(-1).decisions.map(d => d.status)).toEqual(['accepted', 'rejected'])
+ })
+})
diff --git a/frontend/src/views/CoachIntake.jsx b/frontend/src/views/CoachIntake.jsx
index ea34c68e9..46007fa92 100644
--- a/frontend/src/views/CoachIntake.jsx
+++ b/frontend/src/views/CoachIntake.jsx
@@ -1,34 +1,40 @@
-import { useState } from 'react'
+// The questionnaire — the first thing the Coach asks, the moment somebody first opens it.
+//
+// One question per screen, big targets, as little copy as the question allows. Only goal and
+// experience are required; everything after them makes the plan better without gating it,
+// and someone who wants to just get training can skip through. The consent disclosure is the
+// first screen of this flow rather than a separate card, because "what leaves the server" is
+// the first thing to know, not a setting to find later.
+//
+// `?edit=1` reuses every screen as the profile editor: consent is skipped, answers are
+// prefilled, and the last button saves instead of building.
+import { useEffect, useState } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { useStore } from '../store/useStore.js'
import { useUI } from '../store/useUI.js'
import { t } from '../lib/i18n.js'
import { DAYN } from '../lib/format.js'
import { EXDB } from '../lib/exercises.js'
-import { emptyCoach, coachAvailable } from '../lib/coach.js'
-import { requestPlan } from '../lib/coach-api.js'
+import { emptyCoach, coachAvailable, hasConsent, CONSENT_VERSION, CATEGORY_TEXT, appendChat } from '../lib/coach.js'
+import { requestPlan, disclosure } from '../lib/coach-api.js'
import { DEMO } from '../lib/demo.js'
import { MOBILE } from '../lib/mobile.js'
import Icon from '../components/Icon.jsx'
-import { Button, TextArea, Segmented } from '../components/ui.jsx'
-
-/* The intake: one topic per screen, because a single form with eleven fields is a form people
- abandon. Only the first two questions are required — everything after them improves the
- plan without gating it, and someone who wants to just get training should be able to. */
+import { Button, TextArea } from '../components/ui.jsx'
+import '../coach.css'
const GOALS = [
- ['strength', 'Get stronger'],
- ['muscle', 'Build muscle'],
- ['general', 'General fitness'],
- ['fatloss', 'Lose fat'],
- ['endurance', 'Endurance']
+ ['strength', 'Get stronger', 'Heavier lifts, lower reps.', 'barbell'],
+ ['muscle', 'Build muscle', 'Volume and progression.', 'arm'],
+ ['general', 'General fitness', 'Balanced, sustainable training.', 'heart'],
+ ['fatloss', 'Lose fat', 'Keep strength while leaning out.', 'flame'],
+ ['endurance', 'Endurance', 'Higher reps, less rest, cardio.', 'figureRun']
]
const EXPERIENCE = [
- ['new', 'New to lifting'],
- ['returning', 'Coming back after a break'],
- ['regular', 'Training regularly']
+ ['new', 'New to lifting', 'First months in the gym.', 'sparkles'],
+ ['returning', 'Coming back after a break', 'You know the movements; the numbers need rebuilding.', 'reset'],
+ ['regular', 'Training regularly', 'Consistent for a while now.', 'trophy']
]
-const SESSION_MIN = [30, 45, 60, 75, 90]
// Equipment options come from the library's own taxonomy, most common first, so every choice
// on screen has exercises behind it.
@@ -38,7 +44,9 @@ const EQUIPMENT = (() => {
return Object.keys(count).sort((a, b) => count[b] - count[a]).slice(0, 14)
})()
-const STEPS = ['goal', 'days', 'length', 'equipment', 'limits', 'extras']
+const QUICK_MIN = [30, 45, 60, 90]
+const toHHMM = min => String(Math.floor(min / 60)).padStart(2, '0') + ':' + String(min % 60).padStart(2, '0')
+const fromHHMM = v => { const [h, m] = String(v || '').split(':').map(Number); return Number.isFinite(h) && Number.isFinite(m) ? h * 60 + m : null }
export default function CoachIntake() {
const nav = useNavigate()
@@ -50,11 +58,13 @@ export default function CoachIntake() {
const coachMode = useStore(s => s.coachLocal?.mode)
const update = useStore(s => s.update)
const toast = useUI(s => s.toast)
+ const [needConsent] = useState(() => !editing && !hasConsent(S))
+ const STEPS = [...(needConsent ? ['consent'] : []), 'goal', 'experience', 'days', 'length', 'equipment', 'limits', 'extras']
const [step, setStep] = useState(0)
const [busy, setBusy] = useState(false)
const [p, setP] = useState(() => ({
goal: null, experience: null, daysPerWeek: 3, preferredDays: [1, 3, 5],
- sessionMin: 45, equipment: [], limitations: '', likes: '', dislikes: '', notes: '',
+ sessionMin: 60, equipment: [], limitations: '', likes: '', dislikes: '', notes: '',
...(S.coach?.profile || {})
}))
const set = patch => setP(v => ({ ...v, ...patch }))
@@ -62,19 +72,32 @@ export default function CoachIntake() {
if (!coachAvailable(config, user, { demo: DEMO, mobile: MOBILE, coachMode })) { nav('/home', { replace: true }); return null }
const key = STEPS[step]
- const canNext = key !== 'goal' || (p.goal && p.experience)
const last = step === STEPS.length - 1
+ const canNext = key === 'goal' ? !!p.goal : key === 'experience' ? !!p.experience : key === 'length' ? p.sessionMin >= 10 : true
+ const optional = ['equipment', 'limits', 'extras'].includes(key)
+
+ const next = () => (last ? finish() : setStep(step + 1))
+ const back = () => (step ? setStep(step - 1) : nav(editing ? '/coach' : '/plan'))
- const save = () => { update(s => { const c = (s.coach = s.coach || emptyCoach()); c.profile = p }) }
+ const agree = () => {
+ update(s => { s.coach = { ...(s.coach || emptyCoach()), consent: { agreedAt: new Date().toISOString(), version: CONSENT_VERSION } } })
+ setStep(step + 1)
+ }
const finish = async () => {
- save()
+ const profile = { ...p, daysPerWeek: Math.min(7, Math.max(1, p.daysPerWeek || 3)) }
+ update(s => {
+ const c = (s.coach = s.coach || emptyCoach())
+ c.profile = profile
+ // The conversation opens with the answers — rendered from the profile, so an edit later
+ // is reflected rather than duplicated.
+ if (!editing || !(c.chat || []).some(m => m.kind === 'intake')) appendChat(s, { role: 'user', kind: 'intake' })
+ })
if (editing) { toast(t('Saved')); nav('/coach'); return }
setBusy(true)
try {
- await requestPlan(p)
- toast(t('The Coach is building your plan…'))
- nav('/coach')
+ await requestPlan(profile)
+ nav('/coach', { replace: true })
} catch (e) { toast(e.message || t('Could not ask the Coach')); setBusy(false) }
}
@@ -85,103 +108,144 @@ export default function CoachIntake() {
equipment: p.equipment.includes(e) ? p.equipment.filter(x => x !== e) : [...p.equipment, e]
})
- return <div className="narrow">
- <div className="hdr">
- <button className="iconbtn" onClick={() => step ? setStep(step - 1) : nav('/coach')} aria-label={t('Back')}><Icon name="chevronLeft" /></button>
- <div style={{ flex: 1, marginLeft: 10 }}>
- <h1>{editing ? t('Coach profile') : t('Your plan')}</h1>
- <div className="sub">{t('Step {0} of {1}', step + 1, STEPS.length)}</div>
- </div>
- </div>
+ const dots = STEPS.filter(s => s !== 'consent')
+ const dotIndex = dots.indexOf(key)
- {/* progress rail — the wizard's only chrome; six dots read faster than "1 of 6" alone */}
- <div className="row" style={{ gap: 5, marginBottom: 14 }}>
- {STEPS.map((s, i) => <div key={s} style={{
- height: 3, flex: 1, borderRadius: 2,
- background: i <= step ? 'var(--acc)' : 'var(--surface-3)'
- }} />)}
+ return <div className="narrow ob">
+ <div className="ob-top">
+ <button className="iconbtn" onClick={back} aria-label={t('Back')}><Icon name="chevronLeft" /></button>
+ {key !== 'consent' && <div className="ob-dots">
+ {dots.map((s, i) => <span key={s} className={'ob-dot' + (i === dotIndex ? ' on' : i < dotIndex ? ' done' : '')} />)}
+ </div>}
+ {optional && !last ? <button className="ob-skip" onClick={next}>{t('Skip')}</button> : <span style={{ width: 36 }} />}
</div>
- <div className="card">
+ <div className="ob-body">
+ {key === 'consent' && <Consent onAgree={agree} onDecline={() => nav('/plan')} />}
+
{key === 'goal' && <>
- <h2 style={{ marginTop: 0 }}>{t('What are you training for?')}</h2>
- <div className="sect-b">
- {GOALS.map(([v, label]) => <button key={v} className="lrow tap" onClick={() => set({ goal: v })}>
- <span className="lrow-m"><span className="lrow-t">{t(label)}</span></span>
- {p.goal === v && <Icon name="check" className="lrow-k" />}
- </button>)}
+ <div className="ob-eyebrow">{t('Your goal')}</div>
+ <h1 className="ob-h">{t('What are you training for?')}</h1>
+ <p className="ob-p">{t('The Coach builds the whole plan around this.')}</p>
+ <div className="ob-choices">
+ {GOALS.map(([v, label, sub, icon]) => <Choice key={v} on={p.goal === v} icon={icon} title={t(label)} sub={t(sub)} onClick={() => set({ goal: v })} />)}
</div>
- <h2>{t('Where are you starting from?')}</h2>
- <div className="sect-b">
- {EXPERIENCE.map(([v, label]) => <button key={v} className="lrow tap" onClick={() => set({ experience: v })}>
- <span className="lrow-m"><span className="lrow-t">{t(label)}</span></span>
- {p.experience === v && <Icon name="check" className="lrow-k" />}
- </button>)}
+ </>}
+
+ {key === 'experience' && <>
+ <div className="ob-eyebrow">{t('Experience')}</div>
+ <h1 className="ob-h">{t('Where are you starting from?')}</h1>
+ <p className="ob-p">{t('Sets the pace of progression, and how much the Coach assumes you know.')}</p>
+ <div className="ob-choices">
+ {EXPERIENCE.map(([v, label, sub, icon]) => <Choice key={v} on={p.experience === v} icon={icon} title={t(label)} sub={t(sub)} onClick={() => set({ experience: v })} />)}
</div>
</>}
{key === 'days' && <>
- <h2 style={{ marginTop: 0 }}>{t('How many days a week?')}</h2>
- <Segmented options={[2, 3, 4, 5, 6].map(n => ({ value: n, label: String(n) }))}
- value={p.daysPerWeek} onChange={v => set({ daysPerWeek: v })} />
- <div className="muted small" style={{ margin: '14px 0 8px' }}>{t('Which days suit you? (optional)')}</div>
- <div className="week">
- {[1, 2, 3, 4, 5, 6, 0].map(d => <div key={d} className={'wday' + (p.preferredDays.includes(d) ? ' today' : '')}
- onClick={() => toggleDay(d)} style={{ cursor: 'pointer' }}>
- <div className="lbl">{t(DAYN[d]).slice(0, 2)}</div>
- <div className={'dot' + (p.preferredDays.includes(d) ? ' plan' : '')} />
- </div>)}
+ <div className="ob-eyebrow">{t('Schedule')}</div>
+ <h1 className="ob-h">{t('How many days a week?')}</h1>
+ <p className="ob-p">{t('Pick what you will actually keep, not the best week you can imagine.')}</p>
+ <div className="ob-days">
+ {[1, 2, 3, 4, 5, 6, 7].map(n => <button key={n} className={'ob-day' + (p.daysPerWeek === n ? ' on' : '')} onClick={() => set({ daysPerWeek: n })}>{n}</button>)}
+ </div>
+ <div className="ob-sub">{t('Which days suit you? (optional)')}</div>
+ <div className="ob-week">
+ {[1, 2, 3, 4, 5, 6, 0].map(d => <button key={d} className={'ob-wd' + (p.preferredDays.includes(d) ? ' on' : '')} onClick={() => toggleDay(d)}>{t(DAYN[d]).slice(0, 2)}</button>)}
</div>
</>}
{key === 'length' && <>
- <h2 style={{ marginTop: 0 }}>{t('How long is a session?')}</h2>
- <Segmented options={SESSION_MIN.map(n => ({ value: n, label: n + ' ' + t('min') }))}
- value={p.sessionMin} onChange={v => set({ sessionMin: v })} />
- <div className="muted small" style={{ marginTop: 12 }}>{t('The Coach fits the volume to the time you actually have, including rest between sets.')}</div>
+ <div className="ob-eyebrow">{t('Session length')}</div>
+ <h1 className="ob-h">{t('How long is a session?')}</h1>
+ <p className="ob-p">{t('The Coach fits the volume to the time you actually have, including rest between sets.')}</p>
+ <div className="ob-time">
+ <input type="time" value={toHHMM(p.sessionMin || 60)} step={300} min="00:10" max="04:00"
+ onChange={e => { const m = fromHHMM(e.target.value); if (m != null) set({ sessionMin: m }) }} />
+ <span className="ob-time-l">{t('h:mm')}</span>
+ </div>
+ <div className="ob-quick">
+ {QUICK_MIN.map(m => <button key={m} className={'chip' + (p.sessionMin === m ? ' on' : '')} onClick={() => set({ sessionMin: m })}>{m} {t('min')}</button>)}
+ </div>
</>}
{key === 'equipment' && <>
- <h2 style={{ marginTop: 0 }}>{t('What can you train with?')}</h2>
- <div className="muted small" style={{ marginBottom: 10 }}>{t('Pick everything you have access to. Leave it empty and the Coach will use the whole library.')}</div>
- <div className="row" style={{ flexWrap: 'wrap', gap: 7 }}>
- {EQUIPMENT.map(e => <button key={e} className={'chip' + (p.equipment.includes(e) ? ' on' : '')}
- onClick={() => toggleEq(e)} style={{ textTransform: 'capitalize' }}>{e}</button>)}
+ <div className="ob-eyebrow">{t('Equipment')}</div>
+ <h1 className="ob-h">{t('What can you train with?')}</h1>
+ <p className="ob-p">{t('Pick everything you have access to. Leave it empty and the Coach will use the whole library.')}</p>
+ <div className="ob-chips">
+ {EQUIPMENT.map(e => <button key={e} className={'chip' + (p.equipment.includes(e) ? ' on' : '')} onClick={() => toggleEq(e)}>{e}</button>)}
</div>
</>}
{key === 'limits' && <>
- <h2 style={{ marginTop: 0 }}>{t('Anything to work around?')}</h2>
- <div className="muted small" style={{ marginBottom: 10 }}>
- {t('Injuries, joints that complain, movements you cannot do, or practical limits like training at 6am in a flat.')}
- </div>
- <TextArea rows={4} maxLength={600} value={p.limitations} onChange={e => set({ limitations: e.target.value })}
- placeholder={t('e.g. “dodgy left shoulder — no barbell overhead press”')} />
- <div className="dim small" style={{ marginTop: 8, lineHeight: 1.5, color: 'var(--yellow)' }}>
- {t('If something actually hurts, see a professional — the Coach will program conservatively but it cannot diagnose anything.')}
+ <div className="ob-eyebrow">{t('Limits')}</div>
+ <h1 className="ob-h">{t('Anything to work around?')}</h1>
+ <p className="ob-p">{t('Injuries, joints that complain, movements you cannot do, or practical limits like training at 6am in a flat.')}</p>
+ <div className="ob-field">
+ <TextArea rows={4} maxLength={600} value={p.limitations} onChange={e => set({ limitations: e.target.value })}
+ placeholder={t('e.g. “dodgy left shoulder — no barbell overhead press”')} />
</div>
+ <div className="ob-note warn">{t('If something actually hurts, see a professional — the Coach will program conservatively but it cannot diagnose anything.')}</div>
</>}
{key === 'extras' && <>
- <h2 style={{ marginTop: 0 }}>{t('Anything else?')}</h2>
- <div className="muted small" style={{ marginBottom: 6 }}>{t('Exercises you love')}</div>
- <TextArea rows={2} maxLength={300} value={p.likes} onChange={e => set({ likes: e.target.value })} placeholder={t('e.g. “deadlifts, anything with a kettlebell”')} />
- <div className="muted small" style={{ margin: '12px 0 6px' }}>{t('Exercises you would rather not')}</div>
- <TextArea rows={2} maxLength={300} value={p.dislikes} onChange={e => set({ dislikes: e.target.value })} placeholder={t('e.g. “I hate lunges”')} />
- <div className="muted small" style={{ margin: '12px 0 6px' }}>{t('Anything you want the Coach to know')}</div>
- <TextArea rows={3} maxLength={600} value={p.notes} onChange={e => set({ notes: e.target.value })} placeholder={t('e.g. “I want visible arms progress by spring”')} />
+ <div className="ob-eyebrow">{t('Almost there')}</div>
+ <h1 className="ob-h">{t('Anything else?')}</h1>
+ <p className="ob-p">{t('All optional. The more the Coach knows, the less it guesses.')}</p>
+ <div className="ob-sub" style={{ marginTop: 0 }}>{t('Exercises you love')}</div>
+ <div className="ob-field"><TextArea rows={2} maxLength={300} value={p.likes} onChange={e => set({ likes: e.target.value })} placeholder={t('e.g. “deadlifts, anything with a kettlebell”')} /></div>
+ <div className="ob-sub" style={{ marginTop: 4 }}>{t('Exercises you would rather not')}</div>
+ <div className="ob-field"><TextArea rows={2} maxLength={300} value={p.dislikes} onChange={e => set({ dislikes: e.target.value })} placeholder={t('e.g. “I hate lunges”')} /></div>
+ <div className="ob-sub" style={{ marginTop: 4 }}>{t('Anything you want the Coach to know')}</div>
+ <div className="ob-field"><TextArea rows={3} maxLength={600} value={p.notes} onChange={e => set({ notes: e.target.value })} placeholder={t('e.g. “I want visible arms progress by spring”')} /></div>
</>}
</div>
- <div className="row" style={{ gap: 10 }}>
- {step > 0 && <Button onClick={() => setStep(step - 1)} style={{ flex: 1 }}>{t("Back")}</Button>}
- {!last
- ? <Button variant="primary" style={{ flex: 1 }} disabled={!canNext} onClick={() => setStep(step + 1)}>{t('Next')}</Button>
- : <Button variant="primary" style={{ flex: 1 }} icon="sparkles" disabled={busy} onClick={finish}>
- {editing ? t('Save') : t('Build my plan')}
- </Button>}
- </div>
- {!canNext && <div className="dim small" style={{ textAlign: 'center', marginTop: 10 }}>{t('Pick a goal and where you are starting from to continue.')}</div>}
- <div style={{ height: 20 }} />
+ {key !== 'consent' && <div className="ob-foot">
+ <Button variant="primary" style={{ flex: 1 }} disabled={!canNext || busy} icon={last ? 'sparkles' : undefined} onClick={next}>
+ {last ? (editing ? t('Save') : t('Build my plan')) : t('Continue')}
+ </Button>
+ </div>}
+ {(key === 'goal' || key === 'experience') && !canNext && <div className="ob-hint">{t('Pick one to continue.')}</div>}
</div>
}
+
+function Choice({ on, icon, title, sub, onClick }) {
+ return <button className={'ob-choice' + (on ? ' on' : '')} onClick={onClick}>
+ <Icon name={icon} />
+ <span className="ob-choice-t">{title}{sub && <span className="ob-choice-s">{sub}</span>}</span>
+ <Icon name="check" className="ob-k" />
+ </button>
+}
+
+/* The disclosure: what leaves, where to, who pays. Rendered from the same category list the
+ payload is built from, so the promise on screen cannot drift from what actually goes. */
+function Consent({ onAgree, onDecline }) {
+ const config = useStore(s => s.config)
+ const [info, setInfo] = useState(null)
+ useEffect(() => { disclosure().then(setInfo).catch(() => {}) }, [])
+ const who = info?.payer === 'you'
+ ? t('Sent straight to {0} with your own API key — you pay for every request.', info.host || info.providerLabel)
+ : t('Sent to {0}, running on this server under the instance owner’s account.', info?.providerLabel || config?.coach?.providerLabel || t('the configured AI provider'))
+ return <>
+ <div className="ob-eyebrow">{t('Before we start')}</div>
+ <h1 className="ob-h">{t('Meet the Coach')}</h1>
+ <p className="ob-p">{t('It designs your plan from a few answers and adjusts it from what you actually log. It never changes anything without your say-so, and you can undo every change.')}</p>
+ <div className="ob-sub" style={{ marginTop: 0 }}>{t('What it reads')}</div>
+ <div className="ob-consent">
+ {(info?.categories || Object.keys(CATEGORY_TEXT)).map(k => {
+ const [title, sub] = CATEGORY_TEXT[k] || [k, '']
+ return <div key={k} className="ob-consent-row"><Icon name="check" /><div><b>{t(title)}</b><span>{t(sub)}</span></div></div>
+ })}
+ </div>
+ <div className="ob-fine">
+ <div>{who}</div>
+ <div>{t('Your name, your sign-in details and everything else about your account stay here. Other people’s data is never included.')}</div>
+ <div style={{ color: 'var(--yellow)' }}>{t('The Coach is not a doctor or a physiotherapist. If something hurts, ask a professional.')}</div>
+ </div>
+ <div className="ob-foot" style={{ flexDirection: 'column' }}>
+ <Button variant="primary" onClick={onAgree}>{t('I understand — let’s go')}</Button>
+ <Button onClick={onDecline}>{t('Not now')}</Button>
+ </div>
+ </>
+}