The app is now KuentaGYM everywhere a user can see it, and a fresh profile no longer starts on upstream's English/kg defaults. Both are this fork's decisions, so both are pinned by tests rather than left to a find-and-replace. Rename (1,270 references, 149 files) - Visible surfaces: the Login/Home/mobile-onboarding wordmark, the Settings version line, the printed plan, the PWA title + manifest, and the 17 branded strings across all 14 locale packs. - Infrastructure: repo links, the container images and the release endpoints now name git.dploy.lol/dsantillan/kuentagym; .gitea/workflows/docker-publish.yml publishes to this forge's registry instead of gitea.com. - The Android/iOS application id stays ch.duartesantos.opengym on purpose: changing it would make the mobile app a different app that could never update an installed copy. Three things the mechanical pass would have broken, fixed here - The update check asked gitlab.com for upstream's releases and would have installed upstream's APK, putting the old name back on the phone. It now reads this fork's Gitea releases API (the assets shape differs), with the tests rewritten to the payload Gitea actually returns. - Renaming the mobile state/pairing files (opengym-state.json, opengym-remote.json) would lose the on-device copy of a history whose WebView storage may have been evicted, and silently unpair the device. Both are read under their old names and written forward under the new ones. - Renaming the exported plan-file marker (openGym_plan) rejected every plan shared before the rename as "not a plan file". Both markers are accepted. Defaults: pounds and Spanish - DEF.unit = 'lb', DEF.lang = 'es', plus every fallback that independently assumed en/kg (the <html lang> attribute, the Settings pickers, the Store, the MCP, the Coach payload). - Server-generated push copy existed only in English and pt-BR, so a Spanish profile would have been notified in English; Spanish added. - The demo seed states unit: 'kg' — its seeded numbers are kilograms, and inheriting the new default would have introduced an 82.4 lb lifter benching 60. - The module-level language in i18n-core stays English: it is the only language whose strings need no pack, so `t()`, dates, numbers and lists agree before a pack loads. Starting there on 'es' formats a Spanish-shaped UI with English strings. Also - api/package.json's test glob missed push-messages.test.js and verify-error.test.js, which sat beside the modules they cover and never ran. - README, docs/, website/ and the issue templates no longer describe upstream's GitLab/GitHub pipeline, Discord, sponsorship or public demo as if they were this fork's; upstream history and attribution are preserved (NOTICE.md).
140 lines
6.1 KiB
JavaScript
140 lines
6.1 KiB
JavaScript
/* kuentagym-mcp state — reads ./data/state-<uid>.json + db.json (read-only). Cached with an
|
|
fs.watch + mtime fallback so a session the api server just wrote is visible on the next
|
|
tool call without a restart. */
|
|
import fs from 'node:fs'
|
|
import path from 'node:path'
|
|
|
|
const DATA_DIR = process.env.KUENTAGYM_DATA || path.join(process.cwd(), 'data')
|
|
|
|
// null = no state file (brand-new account); undefined = not yet loaded.
|
|
let _state = undefined
|
|
let _db = undefined
|
|
let _uid = null
|
|
let _watcher = null
|
|
let _loadedMtime = 0 // mtimeMs we last read at — used to catch watcher omissions
|
|
|
|
function readJsonOrNull(file) {
|
|
try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return null }
|
|
}
|
|
|
|
function reloadDb() { _db = readJsonOrNull(path.join(DATA_DIR, 'db.json')) || { users: [], creds: [], subs: [], invites: [] } }
|
|
|
|
function stateFile(uid) {
|
|
return path.join(DATA_DIR, 'state-' + uid.replace(/[^a-zA-Z0-9_-]/g, '') + '.json')
|
|
}
|
|
|
|
// Pick the uid: KUENTAGYM_UID env, else the only state-* file, else the only user in db.json.
|
|
// Throws listing the options if ambiguous. The sanitiser on stateFile() keeps a sneaky
|
|
// '..' in KUENTAGYM_UID harmless.
|
|
function resolveUid() {
|
|
const envUid = (process.env.KUENTAGYM_UID || '').trim()
|
|
if (envUid) {
|
|
if (!/^[a-zA-Z0-9_-]+$/.test(envUid)) throw new Error(`KUENTAGYM_UID contains characters that aren't safe in a filename: ${JSON.stringify(envUid)}`)
|
|
return envUid
|
|
}
|
|
const files = fs.readdirSync(DATA_DIR)
|
|
.filter(f => /^state-[a-zA-Z0-9_-]+\.json$/.test(f))
|
|
.map(f => f.replace(/^state-/, '').replace(/\.json$/, ''))
|
|
if (files.length === 1) return files[0]
|
|
if (files.length === 0) {
|
|
reloadDb()
|
|
if (_db.users.length === 1) return _db.users[0].id
|
|
if (_db.users.length === 0) throw new Error(`no KuentaGYM 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 KuentaGYM users found — set KUENTAGYM_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)`
|
|
)
|
|
}
|
|
throw new Error(
|
|
`multiple KuentaGYM users found — set KUENTAGYM_UID to one of: ${files.join(', ')}\n` +
|
|
` (look them up in ${path.join(DATA_DIR, 'db.json')} under "users"[].id)`
|
|
)
|
|
}
|
|
|
|
// Idempotent. Picks the uid, loads db.json, attaches the watcher, primes state.
|
|
export function init() {
|
|
if (_uid !== null) return
|
|
if (!fs.existsSync(DATA_DIR)) throw new Error(`KUENTAGYM_DATA dir does not exist: ${DATA_DIR}`)
|
|
_uid = resolveUid()
|
|
reloadDb()
|
|
const file = stateFile(_uid)
|
|
if (fs.existsSync(file)) {
|
|
_state = readJsonOrNull(file)
|
|
if (_state) _state = Object.assign({}, defaultsShape(), _state)
|
|
try { _loadedMtime = fs.statSync(file).mtimeMs } catch {}
|
|
}
|
|
if (_watcher) _watcher.close()
|
|
// fs.watch is best-effort: the api server's atomic write at PUT /api/data is the source of
|
|
// truth, and a stale read just gets corrected on the next change or the next tool call.
|
|
try {
|
|
_watcher = fs.watch(file, () => {
|
|
// On change, simply clear the cache — the next getState() will re-read. Avoids reading
|
|
// twice if the watcher fires multiple events for one atomic-write (rename + create).
|
|
_state = undefined
|
|
_loadedMtime = 0
|
|
})
|
|
// Unref'd, or the watcher alone holds the event loop open and the process outlives the
|
|
// client that spawned it — "exits when the LLM client disconnects" stops being true the
|
|
// moment there is a state file to watch. Most clients kill the child anyway, but one that
|
|
// merely closes the pipe would leak a process per session. Watching is unaffected: the
|
|
// stdio transport is what keeps the loop alive while a client is actually attached.
|
|
_watcher.unref()
|
|
} catch { /* fs.watch unsupported on this platform; tools will re-read on mtime change */ }
|
|
}
|
|
|
|
// Returns the state object, or null for a fresh account that never signed in on a device.
|
|
export function getState() {
|
|
init()
|
|
const file = stateFile(_uid)
|
|
// Re-read if the file's mtime changed since our last load — covers watcher omissions and
|
|
// platforms with no fs.watch.
|
|
let mtime
|
|
try { mtime = fs.statSync(file).mtimeMs } catch {
|
|
return _state === undefined ? null : _state
|
|
}
|
|
if (_state === undefined || mtime !== _loadedMtime) {
|
|
const fresh = readJsonOrNull(file)
|
|
if (fresh) {
|
|
// Same shape the frontend builds on pullState — defaults merged with stored state so any
|
|
// field the app added since the snapshot was last saved shows up undefined-safe.
|
|
_state = Object.assign({}, defaultsShape(), fresh)
|
|
_loadedMtime = mtime
|
|
} else if (_state === undefined) {
|
|
_state = null // no state file at all — never signed in on a device
|
|
}
|
|
}
|
|
return _state
|
|
}
|
|
|
|
// Returns the user record (id + name). No passkey material, no VAPID keys, no push subs.
|
|
export function getUser() {
|
|
init()
|
|
const u = _db.users.find(x => x.id === _uid) || { id: _uid, name: 'Profile', created: null }
|
|
return { id: u.id, name: u.name, created: u.created || null }
|
|
}
|
|
|
|
export const dataDir = () => DATA_DIR
|
|
|
|
// Test-only: work against a passed-in state, not the disk.
|
|
export function _seedStateForTests(state) {
|
|
_uid = 'test-uid'
|
|
_db = { users: [{ id: _uid, name: 'Test', created: '2026-07-26T00:00:00.000Z' }], creds: [], subs: [], invites: [] }
|
|
_state = state
|
|
_loadedMtime = Number.MAX_SAFE_INTEGER // never re-read from disk in a test
|
|
if (_watcher) { _watcher.close(); _watcher = null }
|
|
}
|
|
|
|
// Mirrors DEF in frontend/src/store/useStore.js, so the MCP reports the same unit and language a
|
|
// profile with no saved value is shown in. Only ever a fallback: a real state file carries both.
|
|
function defaultsShape() {
|
|
return {
|
|
unit: 'lb', restSec: 90, sound: true, lang: 'es',
|
|
theme: 'dark', accent: 'lime', body: 'male', targetW: null,
|
|
bodyweight: [], routines: [], week: {}, dayPlan: {},
|
|
exWeights: {}, workouts: [], customEx: [], gifSize: 'full',
|
|
reminder: { on: false, time: '08:00', tz: null }
|
|
}
|
|
}
|