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
fix(mcp): say what is wrong with the data folder
Boris 'B' Kurktchievf49dc38a0639
diff --git a/mcp/src/state.js b/mcp/src/state.jsindex 72c2b03bb..9a786440b 100644--- a/mcp/src/state.js+++ b/mcp/src/state.js@@ -13,8 +13,30 @@ let _uid = nulllet _watcher = nulllet _loadedMtime = 0 // mtimeMs we last read at — used to catch watcher omissions+// null means one thing only: the file is not there (an account that never synced from a device).+// Every other failure — no permission on the mount, a truncated or corrupt file — is a real fault,+// and reporting it as "no synced state yet, sign in from a device" sends the operator to fix the+// wrong thing while the data sits there unreadable.function readJsonOrNull(file) {- try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null }+ let raw+ try {+ raw = fs.readFileSync(file, 'utf8')+ } catch (e) {+ if (e.code === 'ENOENT') return null+ // Node's own message repeats the path it was given, and that is the server's absolute path:+ // the basename identifies the file just as well.+ const base = path.basename(file)+ const err = new Error(`cannot read ${base}: ${e.code || e.name} — ${String(e.message).replaceAll(file, base)}`)+ err.code = 'EIO'+ throw err+ }+ try {+ return JSON.parse(raw)+ } catch (e) {+ const err = new Error(`${path.basename(file)} is not valid JSON: ${e.message}`)+ err.code = 'EIO'+ throw err+ }}function reloadDb() { _db = readJsonOrNull(path.join(DATA_DIR, 'db.json')) || { users: [], creds: [], subs: [], invites: [] } }@@ -40,17 +62,23 @@ function resolveUid() {reloadDb()if (_db.users.length === 1) return _db.users[0].idif (_db.users.length === 0) throw new Error(`no openGym users found in ${path.join(DATA_DIR, 'db.json')} — sign in at least once on a device`)- // Multiple users in db.json but no state files yet — list their ids, not the (empty)- // files list. Hit when accounts exist but none has signed in on a device.- throw new Error(- `multiple openGym users found — set OPENGYM_UID to one of: ${_db.users.map(u => u.id).join(', ')}\n` +- ` (look them up in ${path.join(DATA_DIR, 'db.json')} under "users"[].id)`- )+ // Multiple users in db.json but no state file yet — hit when accounts exist but none has+ // signed in on a device.+ throw ambiguousUid(_db.users.map(u => u.id))}- throw new Error(- `multiple openGym users found — set OPENGYM_UID to one of: ${files.join(', ')}\n` +- ` (look them up in ${path.join(DATA_DIR, 'db.json')} under "users"[].id)`- )+ throw ambiguousUid(files)+}++// "Which profile?" is a config question for the operator, and this message travels as a tool+// result: into the model's context and into whatever transcript it lands in. Every account id on+// the box, plus the server's absolute paths, has no business there. The count and the setting to+// change are what the model can act on; the ids and the path go to the server log on stderr,+// where the operator is already reading the startup line.+function ambiguousUid(ids) {+ console.error(`[opengym-mcp] ${ids.length} openGym profiles in ${DATA_DIR}: ${ids.join(', ')} — set OPENGYM_UID to one of them`)+ const err = new Error(`this openGym data directory holds ${ids.length} profiles — set OPENGYM_UID to the one this server should read (the ids are on the server's stderr, and in db.json under "users"[].id)`)+ err.code = 'EINVAL'+ return err}// Idempotent. Picks the uid, loads db.json, attaches the watcher, primes state.diff --git a/mcp/test/state.test.js b/mcp/test/state.test.jsnew file mode 100644index 000000000..8ec00ed6c--- /dev/null+++ b/mcp/test/state.test.js@@ -0,0 +1,122 @@+// Tests for mcp/src/state.js — the uid/config resolution and what a read failure looks like.+// state.js reads OPENGYM_DATA at module load and caches module-globally, so each case stubs the+// env and imports a fresh copy. Temp dirs only; nothing here touches a real profile.+import { describe, test, expect, afterEach, afterAll, vi } from 'vitest'+import fs from 'node:fs'+import os from 'node:os'+import path from 'node:path'++const DB = JSON.stringify({+ users: [{ id: 'alex', name: 'Alex', created: '2026-01-01' }],+ creds: [], subs: [], invites: []+})+const DB_MANY = JSON.stringify({+ users: [+ { id: 'alex', name: 'Alex', created: '2026-01-01' },+ { id: 'secret-partner-uid', name: 'Someone Else', created: '2026-02-02' },+ { id: 'third-account', name: 'Third', created: '2026-03-03' }+ ],+ creds: [], subs: [], invites: []+})++const dirs = []+function mk(files) {+ const d = fs.mkdtempSync(path.join(os.tmpdir(), 'mcp-state-'))+ dirs.push(d)+ for (const [f, body] of Object.entries(files)) {+ if (body === null) fs.mkdirSync(path.join(d, f)) // a directory where a file belongs+ else fs.writeFileSync(path.join(d, f), body)+ }+ return d+}++// A fresh state.js bound to `dir`.+async function load(dir, uid = 'alex') {+ vi.resetModules()+ vi.stubEnv('OPENGYM_DATA', dir)+ vi.stubEnv('OPENGYM_UID', uid)+ return import('../src/state.js')+}++afterEach(() => { vi.unstubAllEnvs() })+afterAll(() => { dirs.forEach(d => fs.rmSync(d, { recursive: true, force: true })) })++describe('a read failure is not "you never signed in"', () => {+ test('no state file at all is still null — that account really has never synced', async () => {+ const { getState } = await load(mk({ 'db.json': DB }))+ expect(getState()).toBeNull()+ })++ test('a corrupt state file throws EIO naming the parse failure', async () => {+ const { getState } = await load(mk({ 'db.json': DB, 'state-alex.json': '{ not json' }))+ let err = null+ try { getState() } catch (e) { err = e }+ expect(err).toBeTruthy()+ expect(err.code).toBe('EIO')+ expect(err.message).toMatch(/state-alex\.json is not valid JSON/)+ expect(err.message).not.toMatch(/sign in/i)+ })++ test('a state file that cannot be read throws EIO naming the failure, not null', async () => {+ const { getState } = await load(mk({ 'db.json': DB, 'state-alex.json': null }))+ let err = null+ try { getState() } catch (e) { err = e }+ expect(err).toBeTruthy()+ expect(err.code).toBe('EIO')+ expect(err.message).toMatch(/cannot read state-alex\.json: EISDIR/)+ })++ // Root reads a mode-000 file anyway (the GitLab CI container runs as root), so the failure this+ // needs cannot be made there.+ const asRoot = typeof process.getuid === 'function' && process.getuid() === 0+ test.skipIf(asRoot)('a permission failure names the file, not the server\'s path', async () => {+ const dir = mk({ 'db.json': DB, 'state-alex.json': '{}' })+ fs.chmodSync(path.join(dir, 'state-alex.json'), 0o000)+ const { getState } = await load(dir)+ let err = null+ try { getState() } catch (e) { err = e }+ fs.chmodSync(path.join(dir, 'state-alex.json'), 0o600)+ expect(err).toBeTruthy()+ expect(err.code).toBe('EIO')+ expect(err.message).toMatch(/cannot read state-alex\.json: EACCES/)+ expect(err.message).not.toContain(dir)+ })++ test('a good state file still loads, with the app defaults merged in', async () => {+ const { getState } = await load(mk({ 'db.json': DB, 'state-alex.json': JSON.stringify({ unit: 'lb', routines: [{ id: 'r1', name: 'R', ex: [] }] }) }))+ const S = getState()+ expect(S.unit).toBe('lb')+ expect(S.routines.length).toBe(1)+ expect(S.dayPlan).toEqual({}) // a default the snapshot did not carry+ })+})++describe('the "which profile?" error is a config message, not a roster', () => {+ const uids = ['alex', 'secret-partner-uid', 'third-account']++ // Several state files, and several users with no state file, resolve the uid the same way.+ for (const [label, files] of [+ ['several state files', Object.fromEntries([['db.json', DB_MANY], ...uids.map(u => [`state-${u}.json`, '{}'])])],+ ['several users, none synced yet', { 'db.json': DB_MANY }]+ ]) {+ test(`${label}: names no uid and no absolute path`, async () => {+ const logs = []+ const spy = vi.spyOn(console, 'error').mockImplementation((...a) => logs.push(a.join(' ')))+ const dir = mk(files)+ const { getState } = await load(dir, '') // no OPENGYM_UID pinned+ let err = null+ try { getState() } catch (e) { err = e }+ spy.mockRestore()+ expect(err).toBeTruthy()+ expect(err.code).toBe('EINVAL')+ expect(err.message).toMatch(/holds 3 profiles/)+ expect(err.message).toMatch(/set OPENGYM_UID/)+ for (const u of uids) expect(err.message).not.toContain(u)+ expect(err.message).not.toContain(dir)+ expect(err.message).not.toContain('/')+ // the operator still gets the detail, on the server's own log+ expect(logs.join('\n')).toContain(dir)+ for (const u of uids) expect(logs.join('\n')).toContain(u)+ })+ }+})