Files
kuentagym/api/test/server-insights.test.js
T
dsantillan 4ba9e29d1e
Tests / test (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
La app avisa cuando la api es más vieja que ella
Validado desde afuera, y era esto: **el frontend desplegado es el nuevo y la api no**. Los hashes que
sirve producción coinciden byte a byte con mi build de HEAD, y el bundle contiene las novedades
("What arrived last", "one total an hour"); pero `/api/vitals/hours`, `/api/insights` y
`/api/music/lookup` responden **404** donde esta versión responde 401. O sea: el número de cada
tarjeta lo calcula la api — y la api que corre es la de antes de las horas, la que lee el total del
día como si fuera la hora 00 y suma 840 donde el reloj dice 499.

Eso explica el reporte completo sin ninguna otra suposición: las actualizaciones llegan, se guardan,
y la pantalla nueva pide cosas que ese servidor no tiene (de ahí que el detalle por hora y el recibo
no aparezcan nunca) mientras muestra el número que el servidor viejo le manda.

La causa de fondo es de despliegue: `web` se reconstruye desde el código en cada deploy, pero el
código de la api se copia *dentro* de su contenedor, y Dokploy no recrea un servicio que ya está
Running. Un deploy entonces refresca la mitad de la aplicación.

Arreglar eso no puede depender de que alguien se acuerde, así que la app ahora lo pregunta:
`GET /api/config` publica `features` — una lista de capacidades, nunca configuración ni credenciales —
y Salud muestra una línea ámbar cuando esa lista falta o no llega hasta `vitals.hours`. Un servidor
viejo ya no puede parecer una pantalla rota.

Tests: el config contra el servidor real (la lista existe, nombra las rutas nuevas, y esas rutas
contestan 401 y no 404, sin claves adentro), y el aviso en la pantalla para los dos casos — api sin
lista y api al día. Mutation-check: si el aviso deja de dispararse con una api sin lista, falla.
2026-09-23 18:06:50 -04:00

251 lines
12 KiB
JavaScript

/* The second opinion, end to end against the real server: a stub gateway stands in for OpenCode
Zen (the real one needs a paid key, and what is being tested here is our side of the contract).
Two claims matter and both are about money and privacy rather than correctness in the abstract:
an instance with no key has no feature at all, and an instance with one does not let a signed-in
person spend without limit. Everything else is about turning an answer into something a screen
can render without inventing a number. */
import { test } from 'node:test';
import assert from 'node:assert/strict';
import crypto from 'node:crypto';
import http from 'node:http';
import net from 'node:net';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const API = path.join(path.dirname(fileURLToPath(import.meta.url)), '..');
const SECRET = crypto.randomBytes(32).toString('hex');
function mintSession(uid, sv = 0) {
const payload = `${uid}:${Date.now() + 86400000}:${sv}`;
return payload + '.' + crypto.createHmac('sha256', SECRET).update(payload).digest('base64url');
}
const cookie = uid => ({ Cookie: `gymsid=${mintSession(uid)}` });
const freePort = () => new Promise(r => {
const s = net.createServer(); s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => r(p)); });
});
/** A gateway that records what it was asked and answers with a fixed, documented-shaped body. */
async function startGateway(t, answer) {
const calls = [];
const server = http.createServer((req, res) => {
let body = '';
req.on('data', c => { body += c; });
req.on('end', () => {
calls.push({ url: req.url, auth: req.headers.authorization, body: JSON.parse(body || '{}') });
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(typeof answer === 'function' ? answer(calls.length) : answer));
});
});
const port = await freePort();
await new Promise(r => server.listen(port, '127.0.0.1', r));
t.after(() => server.close());
return { url: `http://127.0.0.1:${port}`, calls };
}
const USERS = [{ id: 'u_j1', name: 'One', created: '2026-01-01T00:00:00.000Z' }];
async function startServer(t, env = {}) {
const dataDir = fs.mkdtempSync(path.join(os.tmpdir(), 'gym-jev-'));
fs.writeFileSync(path.join(dataDir, 'secret'), SECRET, { mode: 0o600 });
fs.writeFileSync(path.join(dataDir, 'db.json'), JSON.stringify({ users: USERS, creds: [], subs: [], invites: [] }));
const port = await freePort();
const child = spawn(process.execPath, ['server.js'], {
cwd: API, stdio: ['ignore', 'pipe', 'pipe'],
env: {
...process.env, PORT: String(port), DATA_DIR: dataDir, ORIGIN: 'http://localhost:8080', RP_ID: 'localhost',
JEV_API_KEY: '', OPENCODE_API_KEY: '', ...env
}
});
const h = { api: `http://127.0.0.1:${port}`, dataDir, log: '' };
child.stdout.on('data', d => h.log += d);
child.stderr.on('data', d => h.log += d);
t.after(() => { child.kill('SIGKILL'); fs.rmSync(dataDir, { recursive: true, force: true }); });
let up = false;
for (let i = 0; i < 100 && !up; i++) {
try { up = (await fetch(`${h.api}/api/health`)).ok; } catch { /* not up yet */ }
if (!up) await new Promise(r => setTimeout(r, 100));
}
assert.ok(up, `server never came up:\n${h.log}`);
return h;
}
/** A profile with a plan, a session and a night of health data, pushed the way the app does. */
async function seed(h, uid) {
const today = new Date().toISOString().slice(0, 10);
const state = {
unit: 'kg', lang: 'es', body: 'male',
coach: { profile: { goal: 'build muscle', daysPerWeek: 3, limitations: 'bad shoulder' } },
week: { 1: ['r1'], 3: ['r1'] },
routines: [{ id: 'r1', ex: [{ id: '0662' }] }],
bodyweight: [{ d: today, kg: 80 }],
workouts: [{ d: today, name: 'Push', start: 1000, end: 3601000, entries: [{ id: '0662', sets: [{ w: 60, r: 8, done: true, rpe: 8 }] }] }]
};
const put = await fetch(`${h.api}/api/data`, {
method: 'PUT',
headers: { ...cookie(uid), 'Content-Type': 'application/json', 'Sec-Fetch-Site': 'same-origin' },
body: JSON.stringify({ state })
});
assert.equal(put.status, 200, await put.text());
const key = (await (await fetch(`${h.api}/api/vitals/key`, { method: 'POST', headers: cookie(uid) })).json()).key;
const ingest = await fetch(`${h.api}/api/vitals/ingest`, {
method: 'POST',
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },
body: JSON.stringify({ data: { metrics: [
{ name: 'step_count', units: 'count', data: [{ qty: 840, date: `${today} 00:00:00 +0000` }] },
{ name: 'resting_heart_rate', units: 'bpm', data: [{ qty: 62, date: `${today} 09:00:00 +0000` }] }
] } })
});
assert.equal(ingest.status, 200);
}
const ask = (h, uid) => fetch(`${h.api}/api/insights`, { method: 'POST', headers: { ...cookie(uid), 'Sec-Fetch-Site': 'same-origin' } });
const read = (h, uid, q = '') => fetch(`${h.api}/api/insights${q}`, { headers: cookie(uid) });
/* The app and the api are deployed separately — `web` is rebuilt from source on every deploy, the
api's code is copied into a container that a deploy does not have to recreate — so the newest
screen can end up talking to an older server. `/api/config` is how the screen finds out, which
only works if the list is actually there and actually names the new routes. */
test('the public config lists what this build of the api can do', async t => {
const h = await startServer(t);
const cfg = await (await fetch(`${h.api}/api/config`)).json();
assert.equal(typeof cfg.invite_only, 'boolean');
assert.ok(Array.isArray(cfg.features), 'a client cannot detect a stale api without the list');
assert.ok(cfg.features.includes('vitals.hours'));
assert.ok(cfg.features.includes('insights'));
// ...and the routes those names promise are the ones this server actually answers.
assert.equal((await fetch(`${h.api}/api/vitals/hours`)).status, 401, 'a route that exists refuses without a session');
assert.equal((await fetch(`${h.api}/api/insights`)).status, 401);
assert.equal((await fetch(`${h.api}/api/music/lookup`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' })).status, 401);
// Nothing in it is configuration or a credential.
assert.equal(JSON.stringify(cfg).includes('key'), false);
});
test('an instance with no key has no second opinion, and says so instead of failing', async t => {
const h = await startServer(t);
await seed(h, 'u_j1');
const before = await (await read(h, 'u_j1')).json();
assert.equal(before.ok, true);
assert.equal(before.configured, false);
assert.equal(before.insight, null);
assert.equal(before.model, null);
assert.equal(before.host, null);
// Asking anyway is a readable answer about the instance, not a crash and not a silent no-op.
assert.equal((await ask(h, 'u_j1')).status, 400);
const refused = await (await ask(h, 'u_j1')).json();
assert.match(refused.error, /JEV_API_KEY/);
// ...and a session is needed even to look.
assert.equal((await fetch(`${h.api}/api/insights`)).status, 401);
assert.equal((await fetch(`${h.api}/api/insights`, { method: 'POST', headers: { 'Sec-Fetch-Site': 'same-origin' } })).status, 401);
});
test('asking sends the state to the configured gateway and stores what comes back', async t => {
const gw = await startGateway(t, {
answers: {
readiness: { value: 2.4, probability: 0.58 },
deload: { probability: 0.62 },
limiter: { choice: 'shoulders', probabilities: { chest: 0.2, shoulders: 0.55, none: 0.25 } },
attention: { choice: 'resting_heart_rate', probabilities: { step_count: 0.3, resting_heart_rate: 0.6 } }
}
});
const h = await startServer(t, { JEV_API_KEY: 'test-key', JEV_BASE_URL: gw.url, JEV_MODEL: 'jev-test' });
await seed(h, 'u_j1');
const res = await ask(h, 'u_j1');
const body = await res.json();
assert.equal(res.status, 200, JSON.stringify(body));
assert.equal(body.ok, true);
assert.equal(body.configured, true);
assert.equal(body.model, 'jev-test');
assert.equal(body.host, gw.url.replace('http://', ''));
// One request, every question, and the model and key the environment named.
assert.equal(gw.calls.length, 1);
assert.equal(gw.calls[0].url, '/v1/systemone');
assert.equal(gw.calls[0].auth, 'Bearer test-key');
assert.equal(gw.calls[0].body.model, 'jev-test');
assert.deepEqual(Object.keys(gw.calls[0].body.questions).sort(), ['attention', 'deload', 'limiter', 'readiness']);
const sent = gw.calls[0].body.state;
assert.equal(sent.training.sessions, 1);
assert.equal(sent.training.sets_by_body_part_28d.chest, 1, 'the library put push-up in chest');
assert.deepEqual(sent.health.metrics.map(m => m.name).sort(), ['resting_heart_rate', 'step_count']);
assert.equal(sent.profile.limitations, 'bad shoulder', 'the one free-text field that goes, on purpose');
// What the screen renders: the answer, parsed, with the probability it came with.
assert.equal(body.insight.answers.readiness.value, 2.4);
assert.equal(body.insight.answers.deload.p, 0.62);
assert.equal(body.insight.answers.limiter.option, 'shoulders');
assert.equal(body.insight.answers.attention.option, 'resting_heart_rate');
assert.equal(body.insight.model, 'jev-test');
assert.ok(body.insight.at > 0);
assert.equal(body.freshness.fresh, true);
// Counts, never content: this is what the sheet shows before it sends anything.
assert.deepEqual(body.sent.metrics.sort(), ['resting_heart_rate', 'step_count']);
assert.equal(body.sent.sessions, 1);
assert.equal(body.sent.includes_limitations, true);
// It is stored, and reading it back does not call the gateway again.
const got = await (await read(h, 'u_j1')).json();
assert.equal(got.configured, true);
assert.equal(got.insight.answers.deload.p, 0.62);
assert.equal(got.insight.raw, undefined, 'the raw payload is not what a screen polls for');
assert.equal(gw.calls.length, 1);
assert.equal(got.budget.used, 1);
// ...unless it is asked for by name, which is how a shape this code guessed wrong gets looked at.
const raw = await (await read(h, 'u_j1', '?raw=1')).json();
assert.deepEqual(raw.raw.answers.deload, { probability: 0.62 });
});
test('a gateway that answers badly is reported, not stored, and costs nothing', async t => {
const gw = await startGateway(t, { hello: 'world' });
const h = await startServer(t, { OPENCODE_API_KEY: 'k2', JEV_BASE_URL: gw.url });
await seed(h, 'u_j1');
const res = await ask(h, 'u_j1');
assert.equal(res.status, 200);
const body = await res.json();
// Every question came back unanswered, and that is what is stored: nulls, not invented values.
assert.deepEqual(Object.values(body.insight.answers), [null, null, null, null]);
const got = await (await read(h, 'u_j1')).json();
assert.equal(got.insight.answers.readiness, null);
});
test('the same profile cannot ask more than the budget allows', async t => {
const gw = await startGateway(t, { answers: { deload: { probability: 0.5 } } });
const h = await startServer(t, { JEV_API_KEY: 'k3', JEV_BASE_URL: gw.url, JEV_MAX_PER_DAY: '2', JEV_MIN_INTERVAL_MS: '0' });
await seed(h, 'u_j1');
assert.equal((await ask(h, 'u_j1')).status, 200);
assert.equal((await ask(h, 'u_j1')).status, 200);
const spent = await ask(h, 'u_j1');
assert.equal(spent.status, 429);
assert.match((await spent.json()).error, /as often as this instance allows/);
assert.equal(gw.calls.length, 2, 'a refused request never reaches the gateway');
// The interval is its own guard, on a fresh profile with budget to spare.
const h2 = await startServer(t, { JEV_API_KEY: 'k4', JEV_BASE_URL: gw.url, JEV_MIN_INTERVAL_MS: '60000' });
await seed(h2, 'u_j1');
assert.equal((await ask(h2, 'u_j1')).status, 200);
const tooSoon = await ask(h2, 'u_j1');
assert.equal(tooSoon.status, 429);
assert.match((await tooSoon.json()).error, /try again in 1 min/);
});
test('wiping the health data takes the judgment with it', async t => {
const gw = await startGateway(t, { answers: { deload: { probability: 0.4 } } });
const h = await startServer(t, { JEV_API_KEY: 'k5', JEV_BASE_URL: gw.url });
await seed(h, 'u_j1');
assert.equal((await ask(h, 'u_j1')).status, 200);
await fetch(`${h.api}/api/vitals`, { method: 'DELETE', headers: { ...cookie('u_j1'), 'Sec-Fetch-Site': 'same-origin' } });
const after = await (await read(h, 'u_j1')).json();
assert.equal(after.insight, null, 'a judgment about data that no longer exists is gone too');
});