Open-source gym & body-weight tracker, now in the App Store (iPhone + Apple Watch) and as an Android APK. Plan routines, log workouts, see which muscles are trained, import from Strong/Hevy/FitNotes. Self-host it or use it on the phone alone.
JavaScript apple-watchbodyweightdockerfitnessfitness-trackergymhealthiosmcpnodejspasskeysprogressive-web-applicationspwareactself-hostedself-hostingvitewebauthnweightliftingworkout-tracker
feat(coach): make the max message length configurable
bluzername754e35c92246
diff --git a/api/coach/config.js b/api/coach/config.jsindex 02abe5f94..1ff692f2a 100644--- a/api/coach/config.js+++ b/api/coach/config.js@@ -85,8 +85,16 @@ const DEFAULTS = {// Anonymous medians across profiles that opt in ("compare with others"). Off by default: it// is the one feature where one person's numbers feed into what another person sees.community: false,+ // How long a chat/refine message or review note can be. Was a bare 1000 literal in three+ // different files (routes.js, jobs.js, payload.js) before this was configurable — see issue+ // #267. The admin route clamps a write to [MAX_MESSAGE_LEN_FLOOR, MAX_MESSAGE_LEN_CEILING];+ // payload.js's own MAX_NOTE_CHARS ceiling has to stay at or above the latter, or a raised+ // limit here would still get clipped back down at build().+ maxMessageLen: 1000,log: []};+export const MAX_MESSAGE_LEN_FLOOR = 200;+export const MAX_MESSAGE_LEN_CEILING = 4000;const PER_PROVIDER = ['auth', 'models', 'providerOptions', 'boundUid'];const isPlainObj = v => !!v && typeof v === 'object' && !Array.isArray(v);const LOG_MAX = 100;diff --git a/api/coach/core/payload.js b/api/coach/core/payload.jsindex a1c144526..85ea5a5b2 100644--- a/api/coach/core/payload.js+++ b/api/coach/core/payload.js@@ -17,6 +17,12 @@ export const CONTRACT = 1;// makes the payload bigger and the reading vaguer, not better.export const MAX_WEEKS = 12;export const MAX_SESSIONS = 60;+// Last-resort ceiling for a free-text note/refine (issue #267). The real limit is the admin's+// `maxMessageLen`, enforced in jobs.js before a message ever reaches this module — this module+// stays a pure allowlist with no config import of its own, so it keeps its own constant instead.+// It has to stay >= config.js's MAX_MESSAGE_LEN_CEILING, or a raised admin limit would still get+// clipped back down here.+export const MAX_NOTE_CHARS = 4000;/* ---------- the data categories the consent screen names (FR-09/10) ----------Kept here, next to the code that acts on it, and rendered by the consent UI from the same@@ -399,7 +405,7 @@ export function build(S, opts = {}) {goal: S.targetW ?? null,series: (S.bodyweight || []).filter(b => !p.window.from || b.d >= p.window.from).map(b => ({ d: b.d, w: b.w }))};- if (opts.note) p.userNote = String(opts.note).slice(0, 1000);+ if (opts.note) p.userNote = String(opts.note).slice(0, MAX_NOTE_CHARS);if (opts.cohort) p.cohort = opts.cohort;// A review names mostly what is already trained; 60 candidates is plenty for a swap.p.library = librarySlice(S, profile?.equipment, { keep: trainedIds(S, workouts), max: 60 });@@ -419,12 +425,12 @@ export function build(S, opts = {}) {};}if (opts.refine && opts.previous) {- p.refine = { text: String(opts.refine).slice(0, 1000), previous: opts.previous };+ p.refine = { text: String(opts.refine).slice(0, MAX_NOTE_CHARS), previous: opts.previous };} else if (opts.refine) {// "Refine" with nothing to refine: the first plan failed, or was dismissed, and the// person typed what they want instead. That is a fresh plan with a note, not a// revision of a plan that does not exist — refine.md would be reading `previous: null`.- p.userNote = String(opts.refine).slice(0, 1000);+ p.userNote = String(opts.refine).slice(0, MAX_NOTE_CHARS);}}if (opts.kind !== 'debrief') {diff --git a/api/coach/jobs.js b/api/coach/jobs.jsindex e22017415..1a5b000aa 100644--- a/api/coach/jobs.js+++ b/api/coach/jobs.js@@ -177,6 +177,19 @@ class CoachError extends Error {}export { CoachError };+/**+ * Clamp a free-text note/refine message to the admin's configured `maxMessageLen` (issue #267).+ * The one place this is enforced — `routes.js` only applies a generous sanity ceiling before a+ * string reaches here, and `payload.js`'s own bound exists purely so a caller that skips this+ * module (coach-local.js's in-process pipeline) still has a limit. Exported so the clamp itself+ * is directly testable without walking the whole enqueue → execute pipeline.+ */+export function clampMessage(text) {+ if (!text) return null;+ const max = cfgStore.load().maxMessageLen || 1000;+ return String(text).slice(0, max);+}+/*** Enqueue a job. Throws CoachError with a code the routes layer maps to an HTTP status:* `off`, `busy`, `cap`, `consent`.@@ -230,8 +243,8 @@ export function enqueue(uid, opts) {trigger: opts.trigger || 'manual', // 'manual' | 'scheduled'workoutId: opts.workoutId ? String(opts.workoutId).slice(0, 40) : null,intake: opts.intake || null,- note: opts.note || null,- refine: opts.refine || null,+ note: clampMessage(opts.note),+ refine: clampMessage(opts.refine),state: 'queued',startedAt: Date.now()};diff --git a/api/coach/routes.js b/api/coach/routes.jsindex 1a9f81081..47f92d94e 100644--- a/api/coach/routes.js+++ b/api/coach/routes.js@@ -59,17 +59,22 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) {'GET /api/coach/status': async (req, res) => {const user = guard(req, res); if (!user) return;- json(res, 200, jobs.status(user.id));+ // The chat composer's maxLength rides on this poll rather than a one-off fetch, so an+ // admin raising or lowering the limit reaches an open chat within one poll cycle.+ json(res, 200, { ...jobs.status(user.id), maxMessageLen: cfgStore.load().maxMessageLen });},'POST /api/coach/plan': async (req, res) => {const user = guard(req, res); if (!user) return;const body = await readBody(req);try {+ // The admin's configured length is the real limit; jobs.enqueue is where it is actually+ // enforced (it is the one place that already loads config for every job). This slice is+ // only a sanity ceiling so an oversized string is not carried further than it has to be.const job = jobs.enqueue(user.id, {kind: 'create',intake: body.intake || null,- refine: body.refine ? String(body.refine).slice(0, 1000) : null+ refine: body.refine ? String(body.refine).slice(0, cfgStore.MAX_MESSAGE_LEN_CEILING) : null});json(res, 202, { job });} catch (e) { failEnqueue(res, e); }@@ -79,7 +84,10 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) {const user = guard(req, res); if (!user) return;const body = await readBody(req);try {- const job = jobs.enqueue(user.id, { kind: 'review', note: body.note ? String(body.note).slice(0, 1000) : null });+ const job = jobs.enqueue(user.id, {+ kind: 'review',+ note: body.note ? String(body.note).slice(0, cfgStore.MAX_MESSAGE_LEN_CEILING) : null+ });json(res, 202, { job });} catch (e) { failEnqueue(res, e); }},@@ -155,6 +163,7 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) {baseUrl: cfgStore.providerMeta(cfg).http ? baseUrlFor(cfg.provider, cfg) : null,knownModels: check.models || null,caps: cfg.caps,+ maxMessageLen: cfg.maxMessageLen,community: !!cfg.community,runtime: { ok: !!check.ok, version: check.version || null, error: check.error || null, needsKey: !!check.needsKey },authMode: cfg.authMode,@@ -216,6 +225,12 @@ export function coachRoutes({ json, readBody, readSession, requireAdmin }) {instanceDaily: Math.max(0, Math.min(5000, +body.caps.instanceDaily || 0))};}+ if (body.maxMessageLen !== undefined) {+ patch.maxMessageLen = Math.max(+ cfgStore.MAX_MESSAGE_LEN_FLOOR,+ Math.min(cfgStore.MAX_MESSAGE_LEN_CEILING, +body.maxMessageLen || current.maxMessageLen)+ );+ }cfgStore.save(patch);json(res, 200, { ok: true });},diff --git a/api/test/jobs.test.js b/api/test/jobs.test.jsindex 540c15456..d39dcf69f 100644--- a/api/test/jobs.test.js+++ b/api/test/jobs.test.js@@ -467,3 +467,41 @@ test('an HTTPS provider is not refused for lacking a privilege drop, and runs enserver.close();}});++test('a note is truncated to the admin\'s configured max, not clipped to the old 1000-char default (issue #267)', async () => {+ // Same shape as the HTTPS test above: a local server speaking OpenAI's Chat Completions shape,+ // so the exact string that reached the provider can be read back out of the request body.+ const http = await import('node:http');+ const seen = [];+ const server = http.createServer((req, res) => {+ let body = '';+ req.on('data', c => { body += c; });+ req.on('end', () => {+ seen.push(JSON.parse(body || '{}'));+ res.setHeader('content-type', 'application/json');+ res.end(JSON.stringify({ choices: [{ finish_reason: 'stop', message: { content: '{"coach_contract":1,"nochange":true,"reading":"ok"}' } }] }));+ });+ });+ await new Promise(r => server.listen(0, '127.0.0.1', r));+ const base = `http://127.0.0.1:${server.address().port}`;++ const uid = 'u-note-len';+ writeState(DIR, uid, sampleState());+ cfg.save({+ enabled: true, provider: 'compatible', providerOptions: { compatible: { baseUrl: base } },+ models: { compatible: 'local-model' }, maxMessageLen: 2500+ });+ forcePrivilegeVerdict({ ok: false, dropped: false, why: 'no `coach` user exists in this image' });+ try {+ jobs.enqueue(uid, { kind: 'review', note: 'x'.repeat(3000) });+ await settle(uid);+ const sentText = seen[0].messages[1].content;+ const match = sentText.match(/"userNote":"(x+)"/);+ assert.ok(match, 'the note rode in the payload');+ assert.equal(match[1].length, 2500, 'kept the admin\'s configured length rather than the old 1000-char default');+ } finally {+ forcePrivilegeVerdict({ ok: true, dropped: false, why: 'pinned by the test suite' });+ cfg.save({ provider: 'fixture', maxMessageLen: 1000 });+ server.close();+ }+});diff --git a/api/test/payload.test.js b/api/test/payload.test.jsindex 5a643e6f1..299e778e2 100644--- a/api/test/payload.test.js+++ b/api/test/payload.test.js@@ -221,6 +221,23 @@ test('a refine with no plan to refine is a fresh plan with a note, never refine.assert.equal(q.userNote, undefined);});+test('a note/refine is capped at MAX_NOTE_CHARS, not the old 1000-char literal (issue #267)', () => {+ // jobs.enqueue already truncates to the admin's configured maxMessageLen before this module+ // ever sees the string — this is the last-resort ceiling for anything that reaches build()+ // without going through that path (coach-local.js's in-process pipeline). It has to be at+ // least as generous as the admin's ceiling (coach/config.js clamps maxMessageLen to 4000), or+ // an admin who raised the limit would still see every note clipped back down here.+ assert.equal(payload.MAX_NOTE_CHARS, 4000);+ const S = sampleState();+ const long = 'n'.repeat(5000);+ const review = payload.build(S, { handle: handleFor('u1'), kind: 'review', note: long });+ assert.equal(review.userNote.length, payload.MAX_NOTE_CHARS);+ const create = payload.build(S, { handle: handleFor('u1'), kind: 'create', refine: long });+ assert.equal(create.userNote.length, payload.MAX_NOTE_CHARS);+ const refine = payload.build(S, { handle: handleFor('u1'), kind: 'create', refine: long, previous: { routines: [] } });+ assert.equal(refine.refine.text.length, payload.MAX_NOTE_CHARS);+});+test('the last few chat lines travel as conversation — user text and Coach verdicts only, never the message being sent', () => {const S = sampleState();S.coach = { ...(S.coach || {}), chat: [diff --git a/api/test/routes.test.js b/api/test/routes.test.jsindex e1affe81e..66a01c3f5 100644--- a/api/test/routes.test.js+++ b/api/test/routes.test.js@@ -201,3 +201,28 @@ test('a debrief is enqueued as its own kind, and the cohort routes gate on the awhile (jobs.status('admin-1').job && Date.now() < until) await new Promise(res => setTimeout(res, 25));assert.equal(jobs.status('admin-1').last.errorClass, 'noworkout');});++/* ---------- configurable max message length (issue #267) ---------- */+test('an admin can raise the Coach message length past the old 1000-char default, clamped to a sane range', async () => {+ fresh();+ const { call } = harness();++ // A safe default for an instance that has never touched the setting.+ assert.equal((await call('GET /api/admin/coach')).body.maxMessageLen, 1000);++ const set = await call('POST /api/admin/coach/config', { maxMessageLen: 2500 });+ assert.equal(set.status, 200);+ assert.equal((await call('GET /api/admin/coach')).body.maxMessageLen, 2500);+ assert.equal(cfg.load().maxMessageLen, 2500, 'persists with the rest of the Coach config');++ // Clamped, not trusted outright — the admin route validates the same way `caps` does above.+ await call('POST /api/admin/coach/config', { maxMessageLen: 999999 });+ assert.equal((await call('GET /api/admin/coach')).body.maxMessageLen, 4000, 'ceiling');+ await call('POST /api/admin/coach/config', { maxMessageLen: 1 });+ assert.equal((await call('GET /api/admin/coach')).body.maxMessageLen, 200, 'floor');++ // The chat UI reads the limit off the status poll, not the admin card it cannot reach.+ await call('POST /api/admin/coach/config', { maxMessageLen: 1800 });+ const status = await call('GET /api/coach/status');+ assert.equal(status.body.maxMessageLen, 1800);+});diff --git a/frontend/src/views/AdminCoach.jsx b/frontend/src/views/AdminCoach.jsxindex 54bd8f05f..4615ecc51 100644--- a/frontend/src/views/AdminCoach.jsx+++ b/frontend/src/views/AdminCoach.jsx@@ -261,6 +261,10 @@ export default function AdminCoach() {<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-hint" style={{ marginTop: 10 }}>How long a chat message, refinement or review note can be. The chat composer and the server both enforce this.</div>+ <div className="adm-kv"><span className="k">Max message length</span>+ <span className="v"><input className="num" type="number" min="200" max="4000" defaultValue={d.maxMessageLen} disabled={busy}+ onBlur={e => +e.target.value !== d.maxMessageLen && patch({ maxMessageLen: +e.target.value })} /></span></div><div className="adm-group-t" style={{ marginTop: 14 }}>Compare with others</div><div className="row between" style={{ gap: 12, alignItems: 'flex-start' }}>diff --git a/frontend/src/views/CoachChat.jsx b/frontend/src/views/CoachChat.jsxindex c5bcea349..33971500f 100644--- a/frontend/src/views/CoachChat.jsx+++ b/frontend/src/views/CoachChat.jsx@@ -44,7 +44,7 @@ export default function CoachChat() {const storeReady = useStore(s => s.ready)const toast = useUI(s => s.toast)const openSheet = useUI(s => s.openSheet)- const { job, pending, cap, loading, lastError, last, refresh } = useCoachStatus(true)+ const { job, pending, cap, loading, lastError, last, refresh, maxMessageLen } = useCoachStatus(true)const [text, setText] = useState('')const [busy, setBusy] = useState(false)const endRef = useRef(null)@@ -207,7 +207,7 @@ export default function CoachChat() {{community && <button className="qchip" onClick={showCohort}><Icon name="person" />{t('Compare')}</button>}</div>}<div className="composer-in">- <textarea rows={1} value={text} maxLength={1000} placeholder={placeholder} disabled={!!job}+ <textarea rows={1} value={text} maxLength={maxMessageLen || 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>diff --git a/frontend/src/views/CoachChat.test.jsx b/frontend/src/views/CoachChat.test.jsxindex ad88aeaee..7b7cdcb2f 100644--- a/frontend/src/views/CoachChat.test.jsx+++ b/frontend/src/views/CoachChat.test.jsx@@ -9,7 +9,7 @@ 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, community: false, nav: vi.fn(), toast: vi.fn(), openSheet: vi.fn(), refresh: vi.fn() }+ const state = { S: null, pending: null, job: null, community: false, maxMessageLen: 2200, nav: vi.fn(), toast: vi.fn(), openSheet: vi.fn(), refresh: vi.fn() }state.storeSnapshot = () => ({S: state.S,user: { id: 'u1' },@@ -34,7 +34,7 @@ vi.mock('../store/useUI.js', () => {})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 }),+ useCoachStatus: () => ({ pending: mocks.pending, job: mocks.job, cap: null, loading: false, lastError: null, last: null, refresh: mocks.refresh, maxMessageLen: mocks.maxMessageLen }),resolvePending: vi.fn(() => Promise.resolve({})),refinePlan: vi.fn(() => Promise.resolve({})),requestReview: vi.fn(() => Promise.resolve({})),@@ -148,6 +148,21 @@ describe('the Coach chat', () => {expect(container.querySelector('.composer textarea').disabled).toBe(true)})+ it('caps the composer at the admin\'s configured message length, not the old 1000-char default (issue #267)', async () => {+ await mount(null)+ expect(container.querySelector('.composer textarea').getAttribute('maxLength')).toBe('2200')+ })++ it('falls back to 1000 while the status poll has not answered yet', async () => {+ mocks.maxMessageLen = undefined+ try {+ await mount(null)+ expect(container.querySelector('.composer textarea').getAttribute('maxLength')).toBe('1000')+ } finally {+ mocks.maxMessageLen = 2200+ }+ })+it('applies the accepted subset of a review and logs it', async () => {mocks.S = state()await mount({ id: 'r1', kind: 'review', summary: 's', changes: [