e1d28f971d7acae66ef3fce46af357c9449eae54
819
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
e1d28f971d |
El registro de actividad abre plegado en los diez más nuevos
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
"Muéstrame los últimos 10 y que diga mostrar más, para que no se vea todo eso para abajo." Exacto:
con 25 eventos el registro llenaba la pantalla y empujaba el resto del panel fuera de vista, y con un
día movido son cientos. El encabezado ya decía cuántos hay ("25 events, kept for 90 days"); el cuerpo
ahora empieza por los diez más nuevos y un botón **Show more** revela diez más por vez.
Tres detalles que lo hacen correcto en vez de sólo corto:
· **Lo que ya está cargado se revela antes de pedir nada.** El botón revela de la lista que tiene y
sólo va al servidor cuando no le queda nada por mostrar — y entonces pide la página siguiente con
`before`, que ya sabía hacer. Sin esto, cada clic sería un viaje de red para datos que ya estaban
en memoria.
· **Al lado del botón dice "10 of 25"**, así que nunca queda la duda de cuánto falta; el número sale
del `total` del servidor, no del largo de lo cargado.
· **El botón desaparece cuando no queda nada**, en vez de quedarse invitando a un clic que no hace
nada. Y al recargar (el ↻ del encabezado) vuelve a plegarse, que es el punto de plegarlo.
De paso, `load` ya no asume que la respuesta traiga `events`: una respuesta sin eventos es una
respuesta sin eventos, no un crash — y un crash acá se lleva la tarjeta entera del panel.
Tests: 4 en `Admin.test.jsx` (abre en diez y revela hasta el final; pide la página siguiente cuando se
le acaba lo cargado, y no antes; log vacío sin botón). Mutation-check de las dos mitades: sin el
recorte se renderizan todos, y con la página en 50 fallan los dos de plegado.
|
||
|
|
f36a32e8af |
Deploy path: pin the project name the instance already runs under
The file this deployment is pasted from had no `name:`, so the project name came from the directory Dokploy writes it in. It already runs as `kuentagym`, and the volumes are pinned by `name:` either way — this just stops a pasted copy from renaming the stack and the containers in every `docker` command and log line. |
||
|
|
cc257d2671 |
Deploy path: pasar las variables de supervisión, o no hay panel que supervisar
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
"¿Cómo superviso los usuarios que se han creado, los que están logueados y todo eso?" — no se podía, y la causa era de despliegue: `ADMIN_UIDS` es la ÚNICA forma de ser admin (nada en el código pone `user.admin`), y este compose lista el entorno variable por variable, así que llegaba al host y nunca al contenedor. Sin ella el servidor no ofrece `/api/admin/*`, `/api/me` responde `admin: false`, y la fila "Admin dashboard" no aparece en Ajustes: el panel existe y no hay puerta. Ahora el compose pasa las diez que faltaban: `ADMIN_UIDS`, `INVITE_ONLY`, `ALLOW_GUEST`, `SESSION_DAYS` (los interruptores de la instancia) y `AUDIT_LOG`, `AUDIT_MAX`, `AUDIT_DAYS`, `AUDIT_IP` (los límites del registro de actividad), más `VAPID_SUBJECT` y `REMINDER_TICK_MS`. Con los `:-` de siempre: una instancia que no las ponga queda exactamente como estaba. `docs/SELF_HOSTING.md` dice ahora, en el paso donde se habla de `ADMIN_UIDS`, que es la única puerta de entrada al panel y cómo leer los ids de una instancia que ya corre (un `node -e` sobre db.json dentro del contenedor, sin instalar nada). |
||
|
|
91606d9c9e |
Un fallo del Coach dice por qué, sin citar a nadie
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Reportado así: "Mira mi entrenamiento y dime qué cambiarías" → *The Coach answered with something the app couldn't use*, mientras que "¿Cómo fue mi sesión de Back & Triceps?" funcionaba. El código ya sabía la razón y la tiraba: el parser y el validador devuelven qué campo falló, y `pipeline.js` la descartaba — el registro guardaba sólo la clase de error, así que ni la persona ni el dueño podían distinguir prosa de un JSON cortado a la mitad, de un tipo de cambio que no existe, de un ejercicio que no está en el plan. Ahora `unusable` lleva `detail`: **la queja textual** del parser o del validador, que nombra el campo, más una descripción de la forma de la respuesta —prosa o "empieza como JSON", y cuántos caracteres—. Sin citarla nunca, y eso es deliberado: este renglón va al registro de instancia, que es visible para el admin y abarca a todos los perfiles, y ese registro lleva conteos y resultados, nunca los datos de una persona. Unos pocos caracteres de un plan serían exactamente cómo esa regla se rompe. La longitud más la forma es lo que separa "el modelo ignoró el modo JSON" de "la respuesta se cortó", y no dice nada de nadie. En el prompt de reparación esto es la *segunda* respuesta — la que el modelo manda después de que se le dijo qué estaba mal en la primera —, que es lo más informativo que hay: un modelo que no puede arreglar una queja que acaba de recibir es el problema, no este archivo. Documentado con la tabla de clases de error y qué significa cada una (`docs/AI_COACH.md`), porque el patrón que se reportó se lee solo con ella: el debrief es fácil —todo cadenas y un número— y el review es la tarea más difícil —una lista de cambios tipados, con objetivo, antes/después y un motivo de una tabla fija—. Un modelo que debriefa bien y no puede con el review es un enunciado sobre el modelo. Mutation-check: si el detalle vuelve a estar vacío, el test falla. API 279 en verde. |
||
|
|
9a4394aff5 |
Jev decide mirando el histórico completo, no los últimos 28 días
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
"Para que Jev tome decisiones debía mirar la sesión de progreso, que tiene todos los datos de los
entrenamientos pasados." Exacto, y no lo hacía: el estado llevaba una ventana de cuatro semanas, las
últimas tres sesiones en detalle y un puñado de conteos. Un ejercicio que no se mueve desde hace tres
meses se veía exactamente igual que uno que nunca se entrenó, que es justo la diferencia sobre la que
un plan tiene que decidir.
Ahora el estado lleva, por ejercicio y sobre **todo** el histórico:
· cuántas sesiones, y el mejor set de la primera y de la última;
· el mejor de siempre, con su fecha;
· una serie de hasta diez estimaciones, una por sesión, para que se vea la *forma* y no dos extremos;
· la dirección: las últimas tres sesiones contra las tres anteriores — no contra el récord de
marzo, porque un ejercicio que batió su récord en marzo y está plano desde entonces no progresa;
· y el cuerpo al que pertenece, para que una decisión de selección sepa de qué parte del cuerpo habla.
Más: la carga y el volumen por semana de las últimas diez, los totales de todo el histórico (sesiones,
series, desde cuándo entrena, cuántos sets en total) y los estancamientos del bloque actual. Los topes
son de lo que se *muestra* — 12 ejercicios, 10 puntos, 10 semanas — nunca de la aritmética: cada número
se calcula sobre todas las sesiones que el perfil tenga, y hay un test con 40 sesiones y cinco meses de
historia que falla si alguien mete una ventana otra vez.
La estimación de 1RM se comparte en vez de duplicarse: `api/coach/core/strength.js` es un espejo
deliberado de `frontend/src/lib/onerm.js` — mismo Epley, mismo tope de 12 repeticiones, mismas dos
exclusiones (series de calentamiento; máquinas asistidas, cuyo peso es la ayuda recibida y no la carga
levantada) — y `cohort.js`, que tenía su propia copia del cálculo, ahora usa esa. Un plan escrito desde
un número distinto al que dibuja la pantalla de Progreso es un plan que nadie puede verificar, así que
la fórmula vive en dos lugares a propósito y los tests la comparan con los mismos ejemplos.
Los ids de ejercicios del histórico viajan con su nombre, en la misma línea que ya lo hacían los
estancados: una decisión sobre *qué ejercicio cambiar* tiene que nombrar algo que la app pueda editar.
Tests: el histórico largo, las tres direcciones de tendencia, el tope de puntos con la aritmética
intacta, el volumen de una serie por tiempo (un set sin repeticiones suma al conteo y nada al volumen)
y la estimación compartida. API 279 en verde, frontend 1705.
|
||
|
|
f80ade25f6 |
Jev decide y el modelo escribe: el juicio entra en el trabajo del Coach, y juzga la selección
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Recordado como "para mejorar las decisiones en la selección de entrenamiento debe usar Jev y ChatGPT combinado". La combinación estaba a medias por dos razones, y las dos se cierran acá. **El juicio no estaba cuando se escribía el plan.** Viajaba al payload sólo si alguien lo había pedido en Salud hacía menos de seis horas; en la práctica, muchas veces no estaba. Ahora un trabajo del Coach —crear o revisar— **pide su propio juicio** cuando no hay uno fresco (`insightForCoach` en `api/insights.js`), con el mismo cupo que gasta el botón de Salud, así que lo automático no puede costar más que lo manual. Un debrief queda afuera: un veredicto de disposición no habla de una sesión. Y si el proveedor falla, si la instancia no tiene clave o si el cupo se agotó, el trabajo sigue exactamente como antes — el juicio es contexto, nunca una dependencia, y hay tests para los tres casos. **Las preguntas no cubrían la selección.** Jev juzgaba disposición, descarga, limitante y métrica a vigilar; nada sobre *qué cambiar*. Ahora, además de `volume` (hacia dónde va la carga de la semana, cuando hay historia suficiente para tener opinión), recibe **una pregunta por ejercicio estancado**: `keep`, `reduce`, `swap` o `drop`, con la clave del id de la biblioteca y el nombre en la rúbrica — así la respuesta es algo con lo que el plan se puede editar y el modelo lee palabras, no una clave. Los ids de ejercicios pasan a viajar en el estado, y sólo ellos: un id de biblioteca es una fila de un dataset público, no un identificador de persona, y el test de privacidad lo dice ahora en esos términos. Hay una sola forma de producir un juicio: `runInsight` en `api/insights.js`, que usan la ruta de Salud y el trabajo del Coach. Antes esa lógica vivía dentro de la ruta, con sus helpers duplicados en `server.js`; ahora la ruta es una envoltura fina y no hay dos maneras de pedir, cobrar o guardar. En el prompt del escritor quedó dicho con precisión qué es un `swap`: **una propuesta a considerar**, no una decisión a aplicar. Si la evidencia que el propio modelo ve dice que el ejercicio está bien, puede decir por qué y dejarlo; el cambio que envíe tiene que cumplir el esquema y nombrar un id real. Tests: seis del runner y de la regla de cuándo preguntar (contra un gateway de mentira, sin levantar servidor), más los de las preguntas nuevas. API 276 en verde, frontend 1705. |
||
|
|
9a339db85e |
El Coach ahora sabe para qué cuerpo escribe: tu semana de Salud y tu peso al crear
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Preguntado como "¿Jev está integrado en el Coach para crear o revisar, según mi peso, mis medidas y
los entrenamientos que ya he hecho?" — y la respuesta honesta tenía dos huecos, que este commit
cierra, y uno que no.
**Lo que ya estaba.** El payload del Coach lleva el cuestionario (objetivo, experiencia, días,
minutos, equipamiento, limitaciones), tu plan, `history.workingWeights` (el mejor peso que ya
manejaste en cada ejercicio, para que las cargas iniciales partan de evidencia), `window` +
`aggregates` en una revisión (las últimas tres sesiones serie por serie, las anteriores resumidas,
estancamientos, adherencia, series por parte del cuerpo), tu peso de las últimas semanas y la segunda
opinión de Jev cuando tiene menos de seis horas.
**Lo que faltaba.**
· **Una semana de Apple Health no llegaba nunca**: el Coach podía leer tu entrenamiento y no tu
recuperación. Ahora `health` viaja en el payload — por métrica y por campo, el promedio diario,
el valor más nuevo y cuántos días tienen datos, con tope de ocho métricas y en el orden del
catálogo. Promedios y no el archivo, a propósito: "durmiendo 6,2 h contra 7,1 la semana
anterior" cambia una decisión de volumen, y 288 muestras de pulso sólo gastan tokens. Va en
crear y en revisar; no en el debrief, porque el promedio de una semana no dice nada de una sesión.
El resumen vive en `jev.js`, junto al orden de métricas que ya usaba, y `jobs.js` lo lee del
mismo archivo que el teléfono escribe.
· **Al crear un plan no le llegaba tu peso.** Revisar y debrief siempre lo llevaron; crear no. Un
plan nuevo se escribía sin saber si estás en déficit o subiendo. Ahora el payload de crear lleva
el objetivo y los últimos ocho pesajes.
· Ambas cosas se documentan al modelo en `prompts/common.md`, con su límite dicho: dos días con
datos no son una semana, así que no se lee una tendencia de ahí.
**Lo que no existe, y lo digo en vez de dejarlo creer: medidas corporales.** La app guarda peso y
nada más — ni cintura, ni pecho, ni brazo. No hay dónde escribirlas, así que "según mis medidas"
todavía no es algo que esta instancia pueda hacer; lo que el Coach lee es la serie de peso. Está
escrito así en `docs/AI_COACH.md`, con la tabla de qué entra en el payload y de dónde sale cada cosa.
Tests: el resumen (promedios por campo, ventana, orden, métricas fuera de la ventana descartadas,
tope de ocho) y el payload (el resumen reducido y saneado, la clave ausente en vez de un objeto vacío,
y el peso en crear). API 269 en verde, frontend 1705.
|
||
|
|
f7b884be81 |
Salud: dos dispositivos, una caminata — el cubo guarda sus fuentes y muestra una
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
"En mi Apple Salud me dice 946 y en opengym 1700 y pico", y antes 499 contra 840. Ese factor —1,80 y
1,68— es la prueba: una suma de valores acumulados daría 12× o 24× al final del día, no 1,8×. Lo que
da 1,8× es **sumar dos dispositivos**. HealthKit de-duplica la misma caminata entre el Apple Watch y
el iPhone, la app Salud la cuenta una vez, y un payload que trae los dos como puntos separados no la
ha de-duplicado nadie. La tarjeta estaba leyendo dos cosas, exactamente como se sospechó.
Ahora cada cubo —una hora, y el día cuando el teléfono manda un total por día— **guarda sus fuentes
por separado y muestra una**: la que más reportó en ese cubo, después la más nueva, después la más
grande. No es una suma, no es un promedio y no es "el máximo": es el agregado propio de un
dispositivo, o sea el número que ese dispositivo muestra.
Y la elección es **por hora**, no por día, que es lo que hace correctas las dos situaciones a la vez:
una hora que solo registró el teléfono es del teléfono (no se pierde nada), y una hora que
registraron los dos se cuenta una vez (no se duplica nada). Con la elección por día, el caso
"caminata sin el reloj" se habría perdido.
Tres cosas que había que cuidar y están cubiertas por tests:
· **Un payload sin `source`** —casi todos, y en iOS 27+ es lo normal para datos acumulados— vive en
una sola fuente sin nombre, así que un cubo es el cubo y nada cambia para quien tiene un solo
dispositivo. Los 22 tests que ya existían pasaron sin tocarlos, que es la evidencia de eso.
· **Un cubo guardado antes de esto** se adopta como la fuente sin nombre en vez de tirarse: una
actualización no pierde el día que ya tenía, y las dos compiten por cantidad de muestras.
· **Reemplazar una hora borra solo la de esa fuente.** La hora en curso crece en cada envío de un
automatismo de cinco minutos y por eso se reemplaza, pero reemplazar el cubo entero es cómo un
dispositivo borraría en silencio el reporte del otro — que es lo contrario de lo que esto hace.
La hoja lo dice al final: `N días con datos · Apple Watch, iPhone · se usa Apple Watch`, para que el
número se pueda cotejar contra el dispositivo que lo produjo.
Cinco tests del merge más el orden de desempate. Mutation-check de las dos mitades: sin aplicar la
fuente ganadora fallan cuatro, y si reemplazar una hora borra la del otro dispositivo fallan tres.
API 267 en verde, frontend 1705, build OK.
|
||
|
|
309aba8766 |
Salud: un número por lugar, y la barra no se corrige a mitad del gesto
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
Dos reportes, y eran dos cosas distintas.
**"Veo todos los valores duplicados".** La hoja de una métrica mostraba el mismo número tres veces:
el titular, la lista de horas y el recibo que agregué en el commit anterior — que repetía la suma, el
valor más nuevo y los últimos tres valores *además* de las horas, que son esos mismos números. El
recibo existe para responder "por qué el número no coincide con la app Salud", y para eso alcanza con
la forma de lo que llegó (cuántos datos, cómo vienen marcados, de qué fuentes); los valores ya están
en la lista de horas. Así que ahora:
· el titular es el día, y nada más lo repite;
· la lista de horas son sus valores, y el recibo se queda solo con la forma **cuando hay horas**;
· "Día por día" empieza en ayer (hoy ya es el titular, en el tamaño que merece un titular);
· la lista de campos solo aparece cuando aporta algo — varios campos (Min/Avg/Max del pulso, las
fases del sueño) o una métrica que el catálogo no conoce — en vez de repetir el `qty` de arriba.
Un número, un lugar. El test lo comprueba contando: la lista de días no contiene el valor de hoy, y
el recibo con horas no trae valores.
**"Cuando bajo para ver las demás tarjetas se desplaza hacia arriba el menú".** Esto es el bug que
`lib/viewport-guard.js` ya documenta: en iOS el viewport visual se despega del de layout y todo lo
`position:fixed` — la barra de tabs, el temporizador — queda donde termina el layout viewport, o sea
a media pantalla. La corrección del módulo es un `scrollTo`, y la hacía en **cada** evento de scroll
del viewport visual. Durante un gesto `offsetTop` se mueve con el rebote del final de la página y con
la barra de Safari que se colapsa, así que corregir ahí vuelve a scrollear la página bajo el dedo
varias veces por segundo: lo que se ve es la barra deslizándose hacia arriba mientras uno scrollea,
en la pantalla más larga de la app. Ahora la corrección espera a que el scroll se detenga — una sola
vez, y un scroll que sigue reiniciando la espera. La corrección por teclado, que es para lo que se
escribió el módulo, no cambia.
Mutation-check del debounce: corrigiendo por evento otra vez, el test nuevo falla.
|
||
|
|
4ba9e29d1e |
La app avisa cuando la api es más vieja que ella
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
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.
|
||
|
|
407d7c47c9 |
Salud: el total del día es el día, y un recibo que explica el número que no cuadra
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
"Las actualizaciones están llegando pero las tarjetas no tienen los mismos números que Salud." Las actualizaciones llegan, entonces: el problema es qué se hace con ellas, y hay dos formas de que un día salga más grande de lo que el reloj dice. **El total del día leído como hora 00.** Si HAE manda el total del día con marca de medianoche en el mismo payload que las horas, ese punto caía en el cubo de las 00:00 y la suma del día lo contaba además de las horas — 499 declarados + 341 de horas = 840, que es exactamente el número reportado. Ahora un punto de medianoche que vale más que todo el resto del payload junto es el total del día (una hora no puede tener más que el día que la contiene) y nunca se convierte en hora 00; un 00:00 chico de verdad sigue siendo la primera hora y se suma como cualquier otra. **Horas sumadas a un total que ya las contenía.** Con el día declarado por el teléfono, cada hora que llegaba después se le sumaba encima — el mismo error, una capa más arriba. Ahora el total declarado **es** el día y las horas nunca se le agregan: son la forma del día, no un segundo número. Su suma queda al lado, en `hours_sum`, y la hoja de la métrica dice cuando los dos difieren, en palabras: tanto el teléfono declaró, tanto suman las horas, y cuál de los dos estás viendo. Un total que no se renueva en seis horas deja de mandar, así que cambiar una automatización de Días a Horas converge en vez de congelarse para el resto del día. Y para la otra forma — horas que en realidad son **totales acumulados** en vez de deltas, que también suman de más — cada envío deja un **recibo por métrica**, visible en la hoja: cuántos datos llegaron, cómo vienen marcados (un total por día, uno por hora, muestras sueltas o mezcla), de qué fuentes, cuánto suman y los tres últimos valores. Una corrida de números que suben (340 → 420 → 499) es la señal de que son acumulados, y eso es la diferencia entre 499 y 840 vista en la pantalla en vez de deducida. Es un recibo, no una lectura: el campo que cita se elige por una lista fija porque este módulo no tiene el catálogo, y nada de él entra en el cálculo de un día. Seis tests nuevos del merge y del recibo, dos de las filas de la hoja y uno de render por la hoja real. Mutation-check de las dos mitades del arreglo: leer el total como hora 00 falla, y sumarle las horas al total declarado falla. API 261 en verde, frontend 1701, build OK. |
||
|
|
81301523ab |
Salud: decir qué trajo el último envío, porque "no se mueve" son dos problemas
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
"No se están moviendo los datos de la tarjeta, se quedan igual." En esta pantalla, un teléfono que
está enviando cada cinco minutos y uno que dejó de enviar se ven idénticos: los mismos números, la
misma hora de la última lectura. Necesitan arreglos opuestos — uno se mira en el reloj, el otro en el
celular — y hasta ahora la pantalla no daba con qué distinguirlos: decía "actualizado hace X", que es
cuando llegó el último envío, y nada sobre lo que ese envío traía.
El endpoint ya devolvía el recibo (`last: {ts, points, duplicates, workouts}`) y se quedaba en la
respuesta. Ahora se muestra:
· "El último envío trajo 6 datos nuevos; 282 ya estaban guardados." → el teléfono trabaja y los
números se mueven cuando Apple Health tiene algo nuevo.
· "El último envío no trajo nada nuevo: todos los datos ya estaban guardados. El teléfono está
enviando; Apple Health no tiene nada más reciente que lo que ya está acá." → el problema está en
el reloj o en su sincronización con Salud, no en la app ni en el servidor.
· "Todavía no llegó ningún envío." → la automatización no corrió nunca.
Tres frases que llevan a tres lugares distintos, en una línea bajo el rango. Antes de sospechar del
merge, esto dice si hay algo que mergear.
El test usa el propio botón de actualizar para forzar la segunda lectura, así que también comprueba
que ese botón vuelve a preguntarle al servidor. Mutation-check: si el recibo pierde el caso "nada
nuevo", falla.
|
||
|
|
52d1a05426 |
Deploy path: pass OPENCODE_API_KEY through, not only JEV_API_KEY
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
The gateway hands you a variable called OPENCODE_API_KEY, and the compose lists the environment explicitly — a variable that is not named there reaches Dokploy and never reaches the container. Pasting the key under the name the console gave it would have left the second opinion reading as unconfigured, which is exactly the shape of bug that looks like the feature is broken rather than unconfigured. |
||
|
|
90aa802980 |
La segunda opinión: un juicio sobre tus números, con la probabilidad que trae
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
Preguntaste si se podía implementar Jev, y con qué API. Resulta que Jev se sirve por OpenCode Zen,
así que una sola cuenta cubre esto y cualquier otra cosa apuntada a ese gateway:
POST https://opencode.ai/zen/v1/systemone Bearer <clave> model: jev-1.13
Y ahí está la razón de que valga la pena: Jev no es un modelo de chat. Le mandás un *estado* y
preguntas tipadas — sí/no (`noul`), opción (`choice`), rúbrica (`score`) — y contesta todas en una
sola petición con el valor **y la probabilidad que le puso**. "62% probable" se puede discutir;
"tomate una semana de descarga" no. Así que no entra por el Coach (que necesita *escribir*) y no se
fuerza dentro de su lista de proveedores: tiene su módulo, sus dos rutas y su tarjeta.
Qué hace. En Salud, arriba de la grilla, una tarjeta con cuatro respuestas: qué tan listo estás para
entrenar fuerte (nivel 1-5, con el número al lado), si la semana pide bajar carga (62% probable), qué
parte del cuerpo parece menos recuperada, y qué métrica de salud merece atención — esa última con la
última lectura de la métrica que nombró, para que "vigilá tu frecuencia en reposo" venga con el 62
que lo motivó. La hoja detrás del ⓘ dice a dónde va y exactamente qué se envía, con el mismo resumen
que devuelve el servidor.
Lo que sale, y lo que no. Se decide en `api/jev.js` y son agregados: una semana de cada métrica por
campo como la escribió el teléfono, series por parte del cuerpo de 4 semanas y de la última, sesiones,
días desde la última, RPE medio, estancamientos *por nombre de ejercicio*, el último pesaje y su
cambio. Ningún identificador: ni perfil, ni nombre, ni títulos de entrenamientos, ni ids de
ejercicios, ni chat — hay un test que lo afirma sobre el JSON, porque es una promesa que hacen los
docs y nada más la miraba. La única excepción es deliberada y está documentada: la nota de
*limitaciones* del cuestionario del Coach, porque "hombro malo" cambia la respuesta. (Los títulos sí
estuvieron un rato ahí: los saqué al escribir ese test, y el test se quedó.)
Un juicio no es una instrucción, y el código lo trata así. Cada respuesta se muestra con su
probabilidad; una pregunta que el modelo no contestó se muestra como no contestada, nunca como un
cero; un nivel que no habíamos ofrecido se marca en vez de disfrazarse de propio; y si los datos
cambiaron desde que se pidió (una sesión registrada, una noche que llegó) la tarjeta lo dice en lugar
de seguir pareciendo actual. Tampoco corre por temporizador: cuesta una petición, así que pasa cuando
alguien aprieta *Preguntar*, con cupo por perfil y por día y un piso de diez minutos aplicados en el
servidor, no en la pantalla.
El Coach, además, lo recibe como `secondOpinion` en su payload **solo si tiene menos de seis horas**,
como evidencia con confianza adjunta para citar en `why`, nunca como una orden ni como un cambio de
plan. Es la mitad que faltaba de "y el Coach escribe con eso".
El lector de respuestas es tolerante a propósito: el contrato de la petición está documentado, la
respuesta no la vimos nunca del servicio real, así que acepta las formas plausibles
(`answers`/`results`, `option`/`answer`/`choice`, `probability` o una distribución sobre los niveles),
normaliza lo que encuentra y devuelve `null` por lo que no puede leer. El cuerpo crudo queda guardado
al lado del parseado (y sale con `?raw=1`): la primera llamada real se puede mirar, y una forma mal
adivinada es un arreglo, no un misterio.
Dos cosas que encontré escribiendo esto y que quedan arregladas: una variable de entorno vacía se
leía como **cero** (`Number('')` pasa un chequeo ingenuo), así que un cupo sin configurar era "cero
peticiones" — un feature que parece configurado y no funciona nunca; y agregar la palabra *Back*
para la espalda redefinió el botón *Atrás* de la app a "Espalda", porque en un objeto literal la
última clave gana y nada lo dice. El catálogo de español tiene ahora un test que falla si una clave
se escribe dos veces, mutación comprobada.
Cobertura: 11 tests del módulo (el estado, las preguntas, cada forma de respuesta, la promesa de
privacidad, el cupo), 5 de las rutas contra un gateway de mentira y el servidor real, 6 del modelo de
vista en el frontend y 5 de render por la tarjeta real. API 259 en verde, frontend 1696, build OK.
|
||
|
|
5c69540f62 |
Salud: reset one measurement, without losing the rest
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
"Podemos reiniciar los números de esas mediciones para yo enviar el de hoy." The whole-file reset
already existed two taps away in the setup sheet, but it is the wrong size for the question: the
four metrics he suspects are not the profile. Throwing away a month of heart rate to start steps
over is not a reset, it is a tax.
So a metric can now be forgotten on its own: the detail sheet has **Reset this measurement**, which
deletes that metric's days (and hours) and nothing else — the other metrics, the workouts and the
ingest key stay. With any Date Range wider than a day the phone re-sends that metric on its next
sync, which is what makes this a reset rather than a loss: Apple Health still has the data, and a
day total replaces the day it names, so the stored past is rewritten rather than duplicated.
The two destructive rows are worded apart on purpose and the confirm names the metric ("¿Reiniciar
Pasos?"), because the neighbouring action in the setup sheet takes every metric there is.
`dropMetric()` is pure and returns how many days it took, and the route answers `metric: null` for
a metric the profile does not have (or a profile with no health file at all) instead of an error —
a screen that says "nothing stored" is more useful than a 404 answering a button press. Tested
from both ends: the helper's purity and arithmetic, the route against a real server (one metric
gone, the others and the workouts intact, the key still working, and a re-sync rebuilding it), and
the sheet's flow through the real confirm. Mutation-checked: pointing the row at the whole-file
delete fails it.
|
||
|
|
d93861a73f |
Salud: one grid, every metric the same card
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
"Pasos, energía activa, horas de pie, tiempo de ejercicio se ven una sola tarjeta por fila y se ven grande; debe ser igual que las demás." That was the "Trends" section: the first four metrics in catalogue order drawn as full-width panels with a big chart and the window's own min/avg/high, with those four taken out of the grid below so nothing was drawn twice. It was a bad idea for two reasons. Four huge cards, one per row, above a tidy grid of small ones read as two screens stapled together — which is exactly what was reported. And the four it picked are the four most people open this screen for, so the grid looked like it was missing its own headline metrics: Steps was a panel *instead of* a card. Every metric is now one card in one grid, two to a row, with its sparkline; the chart worth reading is one tap away in the detail sheet, where it also has the hours and the day-by-day numbers around it. That makes `trendCards` and `seriesStats` unused, so they and their tests are gone with the section, along with the `.vh-charts` / `.vh-tchart*` rules that only it used. The render test now asserts the grid holds *every* metric (5 of 5 in the fixture, labels included), that no `.vh-tchart` is rendered anywhere, and that no "Trends" heading is left behind. Checked against the old behaviour by holding one metric back out of the grid: four tests fail. |
||
|
|
3c88e3c188 |
Salud: two cards to a row, at every width
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
Asked for as "filas de 2 tarjetas para que se vea bien". The grid used the shared `.tiles`, which is two columns on a phone and **four** at ≥1000px, so on a desktop the health cards were ~240px wide — narrow enough that the unit wrapped off the number and the sparkline flattened into a squiggle with no shape, which is the one thing it is there to show. The grid now carries `vh-tiles` and the stylesheet gives that pairing two columns, on any screen. It is a scoped rule rather than a change to `.tiles` because every other grid in the app — Home's quick tiles, Stats, the admin cards, the sheets — wants the four-column version; a health card is the only tile carrying a unit, a trend arrow and a chart. The test asserts both halves, because either one alone does nothing: the class on the grid, and the rule it applies. Checked against both bugs — removing the class fails it, and so does putting the rule back to four columns. |
||
|
|
aa6ec8ef22 |
Salud: a card opens onto the day, hour by hour, and onto the days before it
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
Reported as "le doy a cualquier actividad y solo me presenta los pasos de hoy… debiera presentarme una medida por hora, y no me da el histórico". Two separate things, and only one of them was the app's fault. **The history was the automation's setting.** With Date Range on its default (`Today`) every sync carries today and nothing else, so there is exactly one day in the file to draw. That is why a card looked frozen: not a rendering bug, a range that was never sent. The setup steps now say `Previous 7 Days` and say why. **The hours were thrown away by us.** Even when the phone sends 288 readings a day, the receiver folded every one of them into a single day aggregate, so "8,123 steps today" was all there could ever be — a number you cannot look into. Worse, the recommended setting was Time Grouping `Days`, which sends one point per metric per day: the intraday detail never arrived in the first place. The recommendation is now `Hours`, and the storage keeps the hours. The merge rule for them is the same shape as the day rule, for the same reason: a payload whose datapoints all sit on the hour is HAE's own hour grouping, and the hour *in progress* grows on every run of a five-minute automation, so it is replaced and never unioned — 500 + 900 + 1,340 steps in one hour is a number no watch recorded. The day is then recomputed as the sum of its hours, which is what keeps the card and the detail from ever disagreeing, and which also makes switching an automation from Days to Hours mid-day converge instead of double-count. Raw samples (real timestamps) still union by instant plus numbers, and they now land in their own hour, which is where intraday detail comes from when nothing is grouped. Three things that would have been silent bugs, caught while writing it: - The hour rule is decided from the **whole payload**, never from one timestamp. A five-minute automation produces samples that sit exactly on the hour, and reading one of those as an hour total wipes the hour it belongs to. There is a test with a 09:00:00 and a 09:05:00 sample in one payload, and it fails against the per-point version of the rule. - A day that arrived as a day total keeps its hours beside it, and a day stored before this existed keeps its aggregate when the first hour shows up — recomputing it from hours it does not have would delete 2,000 steps. Both are mutation-checked (removing either guard fails a test). - A payload grouped by hour writes the ledger row anyway, because a later payload with real minutes can describe the same instant and the union path can only see the ledger. Without it the raw-sample route test double-counts a single sample. The hours are the bulky part of this data, so they are kept for a week (the day aggregates still live the full 400 days), pruned when the night's file is written, and fetched one metric and one day at a time — `GET /api/vitals/hours`. A screen listing forty cards downloads none of them; the day view carries only a count per day, which is what tells the sheet whether it is worth asking. The sheet draws the hours, the days before it (tapping one moves the hour list to that day), and every field the watch sent; when the automation groups by Days it says so instead of leaving a gap where a chart should be. Coverage: 6 new tests in `api/test/vitals.test.js` (19 total) and a route test in `api/test/server-vitals.test.js` (5), the hour/history model in `vitals-view.test.js` (31), three render tests through the real sheet, the route documented in `api/openapi.yaml` and `website/api.html`, and `docs/HEALTH.md` with the settings, the new merge row and the two symptoms now in Troubleshooting. |
||
|
|
34d28fa5c5 |
Salud: one entry per metric, both ways it was showing two
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
Reported as "todos los medidores duplicados", and there were two separate causes. **The chart panels and the grid drew the same set.** The panels at the top took the first four metrics and the grid below still listed all of them, so Steps was a panel *and* a tile: the same number twice on one screen. The panels now take their metrics out of the grid — the same list feeds both, so nothing is drawn twice and no group is left as an empty heading. That is the one that was visible. **Two catalogue names for one measurement.** HAE has sent Apple's "Walking + Running Distance" as both `walking_running_distance` and `distance_walking_running`, and water as both `water` and `dietary_water` — depending on the export version and the iOS release, and both names can arrive in one export. Catalogued separately they were two cards with the same label and the same number. There is now an alias table: the richer entry wins (more days, then more samples, ties going to the documented name), and deliberately not a sum, because these are the same samples under two names rather than two sources. Guarded from both ends. The render test counts every metric on the screen across panels and tiles and fails if any label appears twice — checked against the bug, which is what it catches. The alias table has unit tests including the case that would have been tempting to get wrong: both names present with the same day must show one card and 5 km, not 10. |
||
|
|
4b6813d0bd |
Música: the add form now passes the id the list is keyed by
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
"Playlist added" and an empty list, every time. The form built the item without an id and
the store's guard was `if (!item.id) return` — a silent drop. The toast came from the sheet,
which had no idea; the list simply stayed as it was, and nothing in the app said why.
Two fixes, because there were two mistakes. The form passes `parsed.id`, which is the
playlist's own identifier and what the list is keyed by (adding the same link twice is still
a no-op). And the guard stops being silent: without an id the URL becomes the key, because a
missing key is a reason to pick a worse key, never a reason to throw away what somebody just
pasted.
The reason nothing caught it is worth recording: the tests called the store's addPlaylist
directly, with an item that had an id, so the form — the only path a person can take — was
never exercised. There is now a test that goes through the sheet itself: renders the screen
with the real Modals host, opens the form, fills the link, saves, and checks both the store
and the card on screen. Checked against the bug: it fails with the id removed, with exactly
the "expected { …(7) } to match object { id: 'pl.abc123' … }" that the empty list was.
|
||
|
|
caed0cbaa0 |
Música: a playlist screen per profile, with Apple's limits stated plainly
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
The idea was "each person types their Apple Music username and their public playlists appear". Apple does not allow that, and it is worth writing down rather than discovering later: there is no API for another person's public playlists — their own developer forums answer that request with "you can't" (threads 692941 and 123894) — and a profile page is rendered by JavaScript with nothing behind it to call. MusicKit offers the catalog and the *signed-in* user's own library, and the second needs an Apple Developer Program membership for a developer token plus a Music-User-Token per person: a private key and a third-party secret in an app that holds none, to fetch something other than what was asked for. What a self-hosted app can do is the share link, which every playlist has: Music → Share → Copy Link. So the Música screen (next to Salud in Home's header, plus a section in Settings) keeps a list of them per profile, in the profile document like the routines — so they sync to the other devices and travel in a backup — and tapping one opens it in Apple Music on the iPhone. The username is a link to the person's public profile. The list is nicer than a column of URLs because the API reads each link's public page for a title, artwork and track count. That is scraping, so it is built to lose: a page that says nothing leaves the card showing the name its owner typed, and nothing on the screen depends on it. `POST /api/music/lookup` is host-allowlisted to Apple's music hosts — https only, checked again on the URL a redirect lands on — because the api container sits on the same network as everything else the owner runs, and a route that fetches whatever it is handed is a request-forgery lever. That boundary has its own tests, including the LAN addresses it must refuse. The parsing lives in api/music.js rather than in both halves: two copies of a parser kept in step by hand is a bomb, and this is the same shape as vitals.js. It is in the Dockerfile's COPY for the same reason vitals.js had to be. |
||
|
|
45183c725f |
The splash is the photograph, and it is painted before the app exists
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
Two things about the launch screen on the phone. **No mark on it.** The photograph is the screen now — the logo that sat in the middle is gone, and so is the vignette that existed to keep that logo readable. Nothing to read, just the picture, which is what was asked for. **It no longer waits for React.** Until now the splash was a React element, so it could not appear until the bundle had downloaded, parsed and mounted — on a phone that is the long blank stretch between opening the app and seeing anything, and it is why the splash seemed to arrive late and then flash past: by the time it rendered, the app was nearly ready. index.html now paints the same photograph from inline styles, so it is on screen as soon as the HTML is parsed, with the bundle still downloading behind it. React replaces the container's contents when it mounts, and the two screens are identical — same image, same object-fit, same base colour behind it while the picture decodes — so the handover cannot be seen as anything but the app arriving. The blank before even that is iOS's own launch screen, which is what apple-touch-startup-image covers: production already serves all fourteen, so a PWA that still opens white is one that was installed before those existed. Removing the icon from the home screen and adding it again is what makes iOS pick them up — its launch images are read at install time, not on every launch. |
||
|
|
b6d3512c36 |
Glass everywhere, and a colour per metric rather than per family
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
Two things the Salud screen had and the rest of the app did not. **The panels.** Every card, tile, grouped list and list row is translucent now, because the aura is behind all of them: with a solid fill the background we added to every screen was only visible in the gaps between cards, which is not what a background is for. The tab bar and the sheets are translucent too, at a heavier weight — they float over content and have to stay readable, which is what the second token (`--glass-strong`) is for. The blur comes from one shared rule instead of each class carrying its own pair, and the per-view panels that paint their own surface (the effort table, the superset card, the check-in card, a note, a calendar cell) joined the list rather than being left behind. No opaque fallback for the panels, deliberately, where the tab bar keeps one: the bar scrolls over text, a card sits in the page flow with nothing behind it but the aura. **The colours.** They came from the group — every Activity metric the same green, every Heart metric the same pink — which is exactly the "all the same" that was wrong: resting heart rate and VO₂ max are both heart, and telling them apart by colour is the whole point. Each of the 50 metrics in the catalogue now carries its own, following the Health app's own logic: red for heart rate and blood pressure, indigo and violet for sleep, blue for body composition, teal for oxygen and breathing, oranges for movement and temperature. The label takes the colour too, as asked; the group tint stays as the fallback so a metric nobody has written a line for still gets one. Two bugs of my own on the way, both caught by tests rather than by looking: the spec() builder is an allow-list and was dropping the `color` it was handed, so every card fell straight back to its family colour; and the test that now asserts "within a family the colours are not all identical" is what would have kept that from shipping unnoticed. |
||
|
|
9e580c4794 |
Cards you can see through, a splash that waits, and iOS launch screens
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
**The transparency was there and invisible.** `--glass` was a near-black at 55% alpha, and a dark film over a dark background reads as solid no matter what the alpha says — so the cards looked exactly as opaque as before. It is 34% now, the family tint weighs a little more (14%) and the blur is 10px instead of 16: heavy blur flattens the backdrop into one colour, which hides the very thing that is supposed to show through. The opaque `@supports` fallback is gone as well. It was copied from the tab bar, where it is right — the bar floats over scrolling text — and it is wrong here: a card sits in the page flow and the only thing behind it is the aura. On any device that took that branch, the cards were solid by construction. **The splash now waits, which is what a launch screen does.** It stays until the boot is finished, with a floor of 1.1s so it can actually be read (a warm boot takes milliseconds, and a splash that lasts that long is a flicker) and a ceiling of 6s so a request that never answers cannot hold anybody behind a photograph — their workouts are already local. The mark pulses slowly while it waits, so it looks like a screen that is loading rather than a photograph that is stuck. **The long white is iOS, before any of our code runs.** The deployed HTML already carries the aura's base colour inline, so what is left is the installed web app's own launch screen: iOS paints it before the page exists, and without an `apple-touch-startup-image` that matches the device it paints nothing. Fourteen entries now cover the phone and tablet sizes the app is opened on, cropped from the same photograph (each device fetches only its own). build-app-icons.mjs fails when the sizes it generates and the sizes index.html links disagree, because a missing entry is the blank screen this exists to remove. |
||
|
|
3908dc524a |
Fix the shell: useState was used and never imported, so the app never mounted
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
The launch-screen work added a useState to App.jsx without adding it to the React import line, and the only symptom in production was a background: React threw while rendering the shell, so neither the app nor the splash ever mounted. "Uncaught ReferenceError: useState is not defined" at the top of the bundle is as fatal as a build error and much quieter — the page loads, the CSS applies, the aura paints, and nothing else happens. It shipped because no test rendered App. The whole point of a shell is that it can fail everything by failing once, so there is now a smoke test that mounts it against a mocked network: it checks the app renders at all, that the launch screen comes first with the photo and the mark on it, that the shell gets past it to a real screen, and that a signed-in device whose boot never finishes still gets its own data rather than being held on the splash. Checked against the bug itself — with useState removed from the import all three fail with that exact ReferenceError. Also swept every file in src/ for the same class of mistake (a hook called, its name not in the React import): App.jsx was the only one. |
||
|
|
a0f1f388bc |
The splash nobody could see, the white flash, and cards that let the aura through
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
Three things, and the first two were bugs rather than taste. **The launch screen never appeared.** Its condition was `!ready && !authed`, and `authed` is true from the saved profile — so a signed-in person (everybody who has ever opened the app) went straight past it and only a brand-new device ever saw the photo. It now shows for the first half second on every launch, and beyond that only while there is genuinely nothing to show yet (no profile and boot still running, the original behaviour, which stops the login screen flashing before the server config lands). Deliberately not "until ready": boot pulls from the server, and waiting for it would hide the local copy exactly when the network is bad — working from that copy is what the offline mode is for. **The white screen.** Until the app's stylesheet arrives the browser paints its own default, and the aura's dark base only existed in that stylesheet — so a cold load, or a service worker swapping in a new bundle, started white. index.html now carries the base colour inline, and, next to it, a few lines that apply the saved theme and accent before the first paint: the app reads those after boot, which meant everybody who had chosen anything saw the defaults flash first. Same storage key the store writes, same resolution of 'system'. **The cards.** They were solid --surface, which sat on top of the aura and hid it. Salud's tiles and chart panels are glass now — the family tint over a translucent fill, a hairline border in the same tint, and a 16px blur with a saturation lift so what shows through stays readable. The fill is a warm near-black rather than the neutral grey: a cool card over a warm gradient reads as a dirty edge. The token (`--glass`) is defined per theme, and where backdrop-filter is unsupported the cards go back to solid, which is the trade the tab bar already documents — the fallback block sits AFTER the glass rules, or the cascade would have handed it the blur it cannot render. Only Salud's cards are glass so far; the rest of the app is still opaque, which is a bigger decision than this change should make on its own. |
||
|
|
c3c1c2836c |
Salud: Today by default, chart panels, and an aura behind the whole app
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
Three things the screen was missing, plus the launch photo.
**Today.** The period filter started at 30 days, which buried the question a five-minute
cadence exists to answer: what do the numbers say right now? "Today" is now first and the
default, and it means today — the grid drops metrics nobody has measured today (the scale
is not stepped on every morning), and if nothing has come in yet the grid falls back to
everything and says so rather than showing an empty screen. The number on every card was
always the newest reading; what is new is that the card says which day it is and when it
landed ("hoy · hace 12 min"), so the claim can be checked instead of trusted. The screen
also refreshes itself every minute while it is open, which is what makes a five-minute
cadence visible.
The filter and the charts want different windows, and the view keeps them apart: a
sparkline or a trend needs history, so the fetch never asks for less than a week even in
"Today", and anything labelled with a window says which one it is. (The alternative —
fetching one day and drawing nothing — would have made Today the one mode with no charts.)
**Chart panels.** Every tile carries a 52px sparkline, which shows a shape and cannot be
read. The first few metrics in the catalogue's own order now get a full-width panel each:
axes, the window's min / avg / max, and the card's own colour, so a panel and its tile are
recognisably the same metric.
**The aura.** index.html carries the three "Diamond Weave" layers and index.css puts the
base colour on `body` where the blend modes composite against it, with `#app` lifted to
z-index 1 so the absolutely-positioned layers cannot paint over the page (everything modal
was already higher). Dark keeps `screen`; the light theme switches the same layers to
`multiply`, because screened amber over white is amber that has been washed away. The blur
radii follow the spec per breakpoint, and the layers are fixed rather than absolute so
scrolling never repaints two 200px blurs.
**The launch screen.** assets/splash.jpg is a 3862×5786 photograph from a camera, so
nothing ships it raw: build-app-icons.mjs now derives public/splash.webp (1170px wide, 62 KB
— WebP because it is a photo) for the boot screen and resources/splash.jpg (2732×2732,
fitted on the aura's base colour rather than cropped, so a portrait composition survives)
for @capacitor/assets. The 12 MB original is gitignored: the derived files are committed,
so a clone still builds, and the script says what is missing when regeneration is asked for
without it.
|
||
|
|
3b7c9011c4 |
Salud: one colour per family of metric, so the grid reads at a glance
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
Every card carried the same white number, which meant reading fourteen labels to find the one you came for. Each family now has a colour — activity green, heart pink, body blue, sleep indigo, vitals teal, everything unrecognised grey — and the card's number, its icon, its sparkline and a low wash behind it all read from a single `--tint` property set by lib/vitals-view.js. The detail sheet follows the same tint, so opening a card keeps its colour. The tints are the app's own palette variables, not hex values: the light theme redefines every one of them, so a card stays legible in both. They are deliberately not `var(--acc)` — the accent is whatever the person chose in Settings, and a dashboard whose "steps" colour changes with the theme accent is one nobody can learn. Grey for the unknown group is the honest choice: an unrecognised metric has no family to colour. The wash is 8% on purpose. The colour is there to sort the grid, not to shout, and a saturated tile behind a 26px number fights the number it is meant to highlight; the value itself carries the colour at full strength. Guarded twice: vitals-view.test.js checks every group resolves to a tint and that no two groups share one (sharing would defeat the point), and the render test checks the cards actually carry `--tint` — the wiring, not the shades, which is the part that can silently break. |
||
|
|
4222e8d86b |
Deploy path: X-Forwarded-For is the append form here, not $remote_addr
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
I changed this to $remote_addr when the resolver fix went in, on the reasoning that appending lets a client put its own address in front of the real one. That reasoning is right for web/nginx.conf.template and wrong here, and the deployment's own access log shows why: this nginx is NOT the edge. Traefik terminates TLS in front of it, logs the web container's peer as 10.0.1.182, and carries the real client (66.98.33.30) in the header it sends. $remote_addr therefore records Traefik's own address, and $proxy_add_x_forwarded_for — which puts the incoming header first — is what preserves the person's. The API reads the first entry, so the append form is the correct one in this shape. Comment 4 now spells out both directions: append here because a trusted proxy is in front, $remote_addr in the registry template because there the container answers the internet directly, where an incoming header is exactly what cannot be trusted. Nothing recorded was wrong in the meantime — AUDIT_IP is off unless an operator asks for it — but this is the setting to get right before anybody turns it on. |
||
|
|
41b004fea7 |
Salud: the ingest key shows up the moment it exists
Tests / test (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Clicking "Create an ingest key" said "Ingest key created" and then showed nothing to copy — no key, just the button again. The key was being created correctly the whole time (it is in the profile, and the phone could have used it); the sheet handing it over was what was broken. A sheet is rendered from the JSX captured when it was opened (useUI.openSheet keeps the element), so anything it reads off the screen's state is frozen at that moment. The header block keyed off the screen's `key`, which was null when the element was created and never re-rendered — the screen's state updated, the element did not, and the toast came from the store rather than from that tree, which is why the confirmation appeared and the key did not. The sheet now holds the key in its own state, seeded from the profile's existing one, and the two handlers resolve with the new key so the sheet can show it the instant it is created. Both blocks that were `data?.key` follow the same local state, so Replace the key updates what is on screen too. Two things came with it, because "where do I copy it from" was the actual complaint: the endpoint and the key each get a labelled button (Copy the URL / Copy the key) instead of a bare clipboard glyph next to a code box, and a line under the key says what to do with it. Guarded by two tests that need the real Modals host to be rendered at all: one creates the key through the sheet and asserts it appears in full, the other opens the sheet on a profile that already has one. The first was checked against the old behaviour — it fails when the sheet reads the frozen prop — so it is a regression guard and not a description. |
||
|
|
002e5e6bbb |
Deploy path: the header counts the traps it documents (there are four now)
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
|
||
|
|
7271dadbee |
The deploy path's nginx: re-resolve the api on every request
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
A plain `proxy_pass http://api:3000` is resolved once, when nginx starts, and the address stays pinned for the life of the container. Recreate the api — a deploy that changes its configuration, a --force-recreate, any restart that hands it a new IP — and the web container keeps talking to a dead address: every /api call answers 502, including /api/config, so the app cannot even boot. That is not hypothetical: it is what happened on gym.dploy.lol, where restarting the api to pick up new code produced 502 on every endpoint until the web container was restarted too. The generated config now asks Docker's embedded DNS again on every request instead: `resolver 127.0.0.11` plus `set $api_upstream http://api:3000` and `proxy_pass $api_upstream`. This is the same fix web/nginx.conf.template has carried for the registry-image shape (with a comment explaining issue #16), and comment 4 at the top of this file now records why the deploy path needs it too. Verified by rendering the command exactly as the container runs it and passing the result through an nginx config parser: both body limits in place, both locations on the variable, and the upstream still resolved through the embedded resolver. |
||
|
|
5eb0a5298a |
The deploy path's api container now keeps itself on the clone's revision
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
gym.dploy.lol runs deploy/compose-build-at-deploy.yml, and that stack has an asymmetry that has now cost two deploys: `web` serves the frontend build out of a shared volume, so every deploy refreshes the app by itself, while `api` copies the clone INTO its container at start-up. Compose recreates a service only when its configuration or image changed, and the clone is a volume, so neither does — the api kept running the previous revision while the frontend moved on. That is invisible from the outside except as a route that answers 404 although the screen that calls it is already deployed and visibly new, which is exactly what "Crear clave de ingesta → not found" was: POST /api/vitals/key hitting last week's server. The api's command is now a small loop instead of a one-liner: it syncs /app from the clone whenever the clone's revision changes, restarts the server on it, and starts it again if it ever exits (the old one-liner left that to the container restart policy, which also meant a full re-copy every time). Dependencies are reinstalled only when package.json itself changed, so a deploy costs a couple of seconds of downtime rather than a minute of npm install. It is careful about the window a deploy opens: `source` does `rm -rf /work/repo` before it re-clones, and the loop tests for api/server.js — a file a fresh clone writes and that rm removes — so a deploy caught mid-clone is waited out instead of half-copied. Two things this file has to get right, both verified rather than assumed. Every `$` in the container's script is written `$$`, because compose interpolates `$VAR` in block scalars too and an unescaped `$src` would have arrived empty (this is the same reason the web service writes `$$host`). And the loop's control flow was simulated before pushing: first start, a new clone, a package.json change, a server that dies, and a clone that disappears mid-deploy and comes back — five paths, all as intended. |
||
|
|
c150101232 |
The app's own mark: assets/logoym.png becomes the icon, the brand, and the Start button
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
Every icon the app ships now comes from one source image, generated rather than drawn: frontend/scripts/build-app-icons.mjs writes public/icon-512.png (declared "any maskable" in the manifest, hence an opaque square), public/icon-180.png (iOS home screen and favicon), public/logo.png (transparent, for the UI) and resources/icon.png (the @capacitor/assets source for the native shells). The file was a PNG despite its .jpeg name — it has a real alpha channel — so it is assets/logoym.png now. It is the file the owner dropped in, and the icons are derived from it, which is what keeps the PWA icon, the home-screen icon, the in-app mark and the native icon from ever drifting apart. The emblem is dark green (its most common colour is #031808, its accents are greens too) with transparent corners, which decides two things. The icon squares are filled with that same dark green and the mark is centred at 88% of the canvas: the corners blend into it, the maskable safe circle stays clean, and a transparent icon can't disappear on a dark home screen. And the tab bar's Start button keeps the accent as a RING instead of a fill — on the old lime disc the emblem would have read as a dark blob. The ring still marks the primary action, and it still turns orange with the pulse while a session is running, with the label underneath saying Start / Resume / Workout, so nothing that button communicated was lost by swapping its glyph for the mark. Login, the mobile onboarding and the boot placeholder in App.jsx showed the dumbbell glyph as a stand-in for the brand; they all show the mark now, so the app cannot flash a different logo on its way in. Three now-unused Icon imports go with it. Icons are written as 256-colour palettes: measured against the full RGBA versions the mean per-channel error is 1.5/255, invisible, and the files are ~2.5× smaller (161 KB for everything the browser downloads, against 532 KB of source). Transparency survives it as the palette's own alpha entries — verified, not assumed. docs/MOBILE.md says how to regenerate and why resources/icon.svg is now inert (@capacitor/assets tries .png before .svg, so the new icon.png wins), and that comment is repeated in the SVG itself so nobody edits the file that no longer decides anything. |
||
|
|
ba37ef8a44 |
Deploy path: give the health ingest 32 MB, and stop appending to X-Forwarded-For
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
gym.dploy.lol does not run docker-compose.yml. It runs deploy/compose-build-at-deploy.yml, where nginx is generated inline by the web service from a printf in its command, with a single global `client_max_body_size 5m`. The per-route 32 MB added for the Apple Health ingest lives in web/nginx.conf.template, which belongs to the registry-image path and is never read here — so a first export of more than 5 MB came back as nginx's own 413 HTML before the API saw a byte of it. That path now has a second location for /api/vitals/ingest with 32m; nginx picks the longest matching prefix, so that one route takes the bigger body and everything else keeps matching the API's MAX_BODY. Both limits are spelled out in comment 3 at the top, with a note that the two deployment shapes have to be changed together. Also fixes a smaller thing found while reading it: X-Forwarded-For was $proxy_add_x_forwarded_for, which APPENDS to whatever the client sent, and the API reads the first entry — so a caller could choose the address recorded about it. It is now $remote_addr, which is what web/nginx.conf.template already does and for the same reason documented there. Audit IPs are off by default, so nothing was being recorded; this matters the day somebody sets AUDIT_IP=net. Comment 3 also now records the two things that make a deploy confusing rather than broken: the api service copies the clone into /app at container start, so an api that was not recreated keeps serving the previous revision while web-build serves the new frontend (exactly the 404-on-a-new-route symptom), and web resolves api's IP once at start-up, so recreating api without web leaves nginx pointing at a dead address and every /api call answering 502. |
||
|
|
8d190bb591 |
Salud moves to Home's header: a sixth tab pushed Start off centre
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
The tab bar is a flex row of equal columns with the Start button raised in the middle, so the tab count has to stay odd. Adding Salud as a sixth pushed that disc half a column to the right, and it read immediately as "the button moved" — the app's primary action is the one thing in the bar that must not drift. Salud is now the heart button in Home's header, next to the gear, with the same destination and the same route (/health). It is reachable from Settings → Data as well, which was already there. The tab bar is back to five: Home, Plan, Start, Stats, Exercises. Two tests, because this is the kind of change that regresses silently: TabBar.test.jsx asserts the odd count and that the raised button is the middle child (plus that no tab points at /health), and Home.health-door.test.jsx asserts the heart sits in the same non-shrinking container as the gear and navigates to /health — if that breaks, the screen is only reachable from Settings, where nobody looks for it. Also: the Comments in Home, TabBar, README, CHANGELOG and docs/HEALTH.md now say where Salud is, and one test assertion checks flexGrow/flexShrink rather than the `flex: none` shorthand — the CSSOM rewrites that to `0 0 auto`, which is what the first version of the test tripped over. |
||
|
|
691e664d3f |
Apple Health (Salud): a per-profile ingest endpoint, and a tab that draws it
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
An iOS automation in Health Auto Export POSTs Apple Health to /api/vitals/ingest, and the new Salud tab (next to Plan) draws whatever arrived: steps, heart rate, sleep, weight, oxygen, workouts and every other metric HAE can export, grouped into cards with a trend, a sparkline and a 7/30/90/365-day range. Nothing on that screen is an input, and the watch's workouts stay out of the history on purpose — they carry no sets and no weights, so folding them into progression, PRs and the recovery model would be inventing data. The interesting part is duplicates. A five-minute automation re-sends overlapping windows: with Date Range "Today", appending would count a day of steps again on every run, and with "Since Last Sync", replacing would throw away everything but the last five minutes. So the endpoint decides per payload instead. Datapoints that sit on midnight are HAE's own day grouping, i.e. a *total*, and a day total replaces the day it names — re-sending the same day all afternoon converges on that day's total. Anything else is a real sample, identified by its instant plus its numbers and stored once, which is right for overlapping and disjoint windows alike. Every sync answers with a receipt (received / duplicates / stored), so a misconfigured automation is visible rather than silent, and day keys come from the date the phone wrote — never the server's clock, or every evening's steps would land on tomorrow. Per profile and private by construction. Each profile mints its own ingest key (Salud → ⚙), which is write-only: it can add to that one profile's health file and cannot read a single number back, so a key leaking out of a phone is a nuisance rather than a disclosure. It is its own credential, so rotating it disconnects a phone without signing anybody out anywhere. The data lives in data/vitals-<uid>.json, outside the synced state document, so a year of heart rate never round-trips through localStorage on every device, and it is bounded on write: 400 days per metric, a 72 h dedupe ledger, the newest 300 workouts. Two traps that only exist in production, both fixed here and both of which would have shipped broken. api/Dockerfile copies the modules server.js imports by name, and vitals.js was not on that list — a container that boots straight into ERR_MODULE_NOT_FOUND. And the web container's nginx capped every /api body at 5 MB, which a health export with Summarize Data off exceeds; that one route now gets the API's own 32 MB while every other path keeps 5 MB, with the shared proxy settings hoisted to server level so the two locations cannot drift apart. Coverage: vitals.js (13 tests — overlapping, disjoint, day-grouped, raw, heart rate, sleep, blood pressure, pruning, timezones), the routes against a real server (4 — isolation between profiles, a key that cannot read, ten re-sends changing nothing), the card model (18) and the screen (4). docs/HEALTH.md has the Health Auto Export settings and the merge table; the five endpoints are in api/openapi.yaml under the health tag, and website/api.html is rebuilt from it. |
||
|
|
0819d03efb |
Measure the iOS touch offset on the device that has it
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
Tests / test (push) Canceled after 0s
Press a row on an iPhone and the one above it reacts — but only sometimes, and only after typing. That is the shape of the keyboard displacement the app already fights in lib/viewport-guard.js: iOS slides the *visual* viewport inside the layout one, everything `position:fixed` is painted against the layout viewport, and the app and the finger disagree until something scrolls. The guard stands down while a text field has focus on purpose (touching the page there threw the keyboard back out — issue #242), and that is precisely the window this falls into. Which correction is right depends on numbers that only exist on the phone: visualViewport.offsetTop, innerHeight, the scale, whether the body is pinned. So this adds a readout instead of a guess. Open the app with `vvdebug` anywhere in the URL, type in a field, tap the row that misbehaves, and read what the viewports were at the moment of that tap — plus which element the browser believed was under the finger, which is the other half of the question ("did it hit the row above, or the row it hit is not where it is drawn?"). It renders nothing without the parameter, and removing it is this file plus one line in App.jsx. |
||
|
|
903a435af3 |
Build a routine with AI: the screen the builder was missing
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
"Add exercise" now has a sibling: it asks which muscles, whether the session
starts with cardio, and how hard — then the Coach fills the routine in. Three
taps instead of picking ten exercises one at a time, and it is the only place in
the app that asks what you want to train today.
Why it exists in this shape:
- The Coach's own intake asks about the *person* — goal, days, equipment, limits
— and is answered once. Nothing in it asks which muscles, so a three-day plan
reasonably came back full body; that is what prompted this. The builder asks
only what changes between sessions and reads the rest from the saved profile,
so a second routine costs three taps and not a questionnaire.
- It adds a NEW routine rather than filling the one you opened. The questions are
about a session you are about to build, and replacing the routine somebody
opened would be the wrong guess. It does not touch the week either: nobody was
asked about days.
- The muscle buttons are the catalogue's own body-part words ("back", "waist"),
which the Library and the body map already translate, so a button and the list
behind it cannot drift apart. "Light" and "Hard" are NOT reused for the effort
chips: those keys already mean the light theme and hard sets, and a chip reading
"Claro" for an easy session would be nonsense in Spanish.
The async half: requestPlan only *starts* a job (the server runs it in the
background and the result arrives on a status poll), so `awaitCoachJob` waits for
that job by the id of the last finished one — a proposal left over from an
earlier question can never be mistaken for this answer — and throws with the
job's own error class for jobErrorText to phrase.
Five tests drive the whole thing: the three steps, the exact questions sent (the
muscles as bp/tg selectors with cardio in the library, not only in the sentence),
that what comes back lands as a new routine with the cardios and the modes the app
owns normalised, that a failure is shown in the app's words and can be retried,
and that an answer with no routine is refused rather than added empty.
The 22 new strings exist in Spanish only, by decision. Rather than leave
check-locales.mjs permanently red — a guard nobody reads is not a guard — the
pending set is written down in src/locales/PENDING.md: the check still fails on
anything NEW, and the debt is a list somebody can work through.
|
||
|
|
996797bf00 |
Spanish exercise names for the whole catalogue
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
A Spanish profile now reads the catalogue in Spanish. Only pt-BR and hu had a
name pack, so every other language — Spanish included, which is this fork's
default — showed 1,324 English titles.
The pack is generated the way the pt-BR and hu ones were, with two differences
that matter to a self-hosted instance:
- `scripts/translate-es-exercise-names.mjs` talks to an OpenAI-compatible
endpoint instead of the `claude` CLI, because that is what the instance
already has: the same router the Coach runs on. Point it at one with
COACH_BASE_URL / COACH_MODEL / COACH_API_KEY.
- It is resumable. Ids already in the source file are skipped, so a run that
stops half way continues where it left off and a review only re-translates
what it deletes. With 1,324 rows, a pass that had to start over would never be
repeated.
Three rounds of review went into the file, each one caught by reading the output
rather than by the script succeeding:
1. "chin-up" and "pull-up" came back as English loanwords — the terms the
catalogue itself uses — so the core vocabulary is now pinned in the prompt and
asserted by the test (dominada, sentadilla, peso muerto, zancada, plancha…).
2. 142 rows led with the equipment ("Banda sentadilla", "Mancuerna press"), which
is the English word order. Spanish names the movement first: "Sentadilla con
banda". Those rows were re-translated, and the test now refuses a title that
starts with a piece of equipment — "Peso muerto" is why "Peso" is not on that
list.
3. Four rows dropped their (male) qualifier and four named variations kept an
English head noun ("Hack squat con barra"); both were fixed, the first by hand
since the review is allowed to edit the source.
The pack is honest about its provenance, like the pt-BR one: model-produced,
not reviewed by a native speaker, and the README says so.
|
||
|
|
40959de0a2 |
Forward the COACH_* variables to the api container in the deploy compose
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
The api service lists its environment explicitly, and that list is an allowlist:
a variable set in the host's .env reaches the container only when it is named
there. Everything else in the panel is used solely to substitute ${…} in the
compose file — which is how COACH_PROVIDER can sit in Dokploy looking applied
while the api never sees it, the Coach stays off, and no screen anywhere shows a
button. That is exactly what happened on this instance.
The `:-` defaults keep an instance that sets none of them byte-for-byte as it
was: an empty value reads as unset in coach/config.js.
|
||
|
|
238eb635c5 |
Configure the Coach from the environment
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
An instance can now be pointed at a model entirely from its environment — so a
container is redeployed with the Coach already working, and nobody has to open
an admin screen:
COACH_PROVIDER=compatible
COACH_BASE_URL=https://ai.example.com # WITHOUT /v1 — the adapter adds it
COACH_MODEL=vendor/model-name
COACH_API_KEY=sk-... # or the provider's own variable
Naming a provider is the whole configuration, so it also turns the Coach on: an
instance started this way that then reported itself "off" would be a puzzle with
no clue in it.
Three decisions worth stating:
- The environment is the *base*, the way DEFAULTS is, and the saved file is
layered on top: an admin who picked a provider in the app meant it, and this
only fills what is absent.
- The key is deliberately NOT a field of the config. That object is cached,
written to data/coach.json by any admin action, and included in the backup the
docs tell people to make. envCredentialFor reads it from the process
environment instead, so it is written nowhere and never surfaced by any route
that reports configuration. A pasted credential still outranks it, and a filed
one that fails to decrypt stays a failure rather than quietly falling back to
a key nobody knows is being spent.
- What the environment supplies is stripped before the file is written. A saved
config used to be written back whole, which would have frozen this start-up's
values on disk — and since the file outranks the environment, a later change
to COACH_MODEL would have been silently ignored.
Verified through the server's own path (config → credentialFor → jobEnv →
adapter) against the OpenAI-compatible router this fork runs on: a chest+triceps
request came back as a six-exercise routine with the cardio row first and
correctly marked `mode: cardio`.
|
||
|
|
327aa5211b |
The core of "build a routine with AI": muscles, cardio, intensity
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
The screen that will drive this needs three things underneath it, and all three
are here, tested, with no UI yet.
1. `librarySlice` can be narrowed to the muscles someone picked. A selector is
`{ bp }` or `{ tg }` — the target muscle matters because "biceps" and "triceps"
are both `upper arms`, and asking for one must not hand back the other — and an
exercise is kept when it matches any of them, so "back and biceps" is one list.
`catalogueOnly` drops the person's own exercises, which are the only rows in
the app with no animation; the builder promises every pick can be watched.
Both answers ride in the existing `intake` object rather than a second channel:
the intake is already how "which muscles" reaches the payload, and it travels
the whole way (route → job → build, and local → build) untouched. `cleanGroups`
sanitises it, since it is the one intake field that reaches a filter rather than
the model's reading.
2. `lib/ai-routine.js` — the three questions and what to do with the answer: the
intake the model is asked with, and the routine it hands back, normalised for
this app. Cardio lands in the library and not only in the sentence (a model told
to start with cardio but handed no cardio exercise can only improvise, which is
what it did the first time this was tried), a cardio row becomes one bout
whatever set count came back, and a missing mode is read from the exercise the
same way `modeOf` reads it everywhere else.
3. A validator fix found on the way: the cardio branch set `min` and `speed` but
never `clean.mode = 'cardio'`, unlike the time and reps branches. The app
recovered it from the catalogue, so nothing was visibly broken — but the bundle
did not describe its own prescription, and a model that omitted `mode` (which is
what a model prescribing "8 minutes of cardio" usually does) got "3 × 10 reps"
with a stray `min` nothing reads. Now the mode is stated, and inferred from the
catalogue when it is missing. `time` is deliberately not inferred: nothing in the
catalogue says an exercise is held for seconds.
Verified against the real router behind gym.dploy.lol with the real pipeline: a
back+biceps request produced a 6-exercise routine from an 80/80/22 library slice.
|
||
|
|
ea1af681c2 |
Read an answer that arrives with an SSE terminator glued to it
Publish Docker images / build (., ./web/Dockerfile, web) (push) Canceled after 0s
Publish Docker images / build (./api, ./api/Dockerfile, api) (push) Canceled after 0s
A gateway may answer a request that did not ask for streaming with SSE framing anyway: the whole chat.completion object followed by "\ndata: [DONE]". That body is not JSON, so readJson's strict parse rejected it, `data` came back null, and the job failed with "unexpected response shape: Cannot read properties of null (reading 'choices')" — while the answer it wanted sat in the first few kilobytes. Not hypothetical: the OpenAI-compatible router behind this fork's own instance answers exactly that way, which made every coach job fail against it with a message that says nothing about the real problem. The lenient read takes the first complete JSON value and ignores what follows, counting braces outside of strings so a "}" inside a rationale cannot end the scan early. It cannot paper over a truncated answer — an object that never closes still returns null, which is what the token-limit path depends on — and there are three tests for that: the terminator case, trailing junk after a complete object, and an object that never closes. |
||
|
|
1c201ab6f9 |
Merge #1: rebrand to KuentaGYM, pounds/Spanish defaults, build-at-deploy stack
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
|
||
|
|
1a48efdbcc |
Add deploy/compose-build-at-deploy.yml for hosts that build at deploy time
Tests / test (pull_request) Canceled after 0s
The instance at gym.dploy.lol runs a five-service stack that clones the source and builds it on every deploy, rather than pulling the images docker-compose.yml names. That shape has three requirements nothing in the repository stated, and getting any of them wrong costs a deploy: - web-build has to copy the whole repository and build from frontend/. The frontend imports the Coach's core from ../../../api/coach/core/, so a build stage holding only frontend/ fails with nine UNRESOLVED_IMPORT errors — the reason web/Dockerfile copies api/coach/core/ into its build stage. - The volume names have to be pinned with `name:`. Unpinned, a restyled stack silently creates empty volumes and the profiles and training history look gone. - nginx needs client_max_body_size. Its default request limit is 1 MB while the app PUTs the whole profile to /api/data and the API accepts 5 MB — the sync starts failing with a 413 the UI cannot explain once a history grows past 1 MB. web/nginx.conf.template already sets 5m; this matches it. The file is the shape that instance runs, with its volume names filled in. |
||
|
|
affac4a2a0 |
Add scripts/build-images.sh: build the two images and publish them
The images docker-compose.yml pulls are normally built by
.gitea/workflows/docker-publish.yml, which needs a registered Actions runner
and a PACKAGES_TOKEN secret. Neither exists on this instance's forge yet, so a
host that pulls rather than builds has nothing to pull — and the two builds are
easy to get wrong by hand: api builds from ./api, web from the repository root,
because the web image compiles frontend/ inside its first stage. A wrong context
produces an image that builds fine and then fails at runtime.
One command now does both and pushes them:
GITEA_TOKEN=<token with write:package> ./scripts/build-images.sh
TAG, REGISTRY, OWNER, PLATFORM, PUSH and API_TARGET (default vs coach) are all
overridable, and the tags default to exactly what docker-compose.yml asks for.
|
||
|
|
87bfd6d4c4 |
Rebrand to KuentaGYM, and start a new profile in pounds and Spanish
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). |
||
|
|
f91cde15a1 |
v1.3.8: twenty-four reports, the four promised items, and eleven community pull requests
versionCode 22. The milestone was due on the 27th; it ships a week early because the QA round that followed the bug fixes found — and closed — enough to be worth releasing on its own.v1.3.8 |
||
|
|
90a1e8956a |
Admin: delete an account, not just disable it (#107)
Disabling locks someone out but deliberately leaves their state file and credential on disk, so 'no data remains' was not reachable from the dashboard — which is what the request asked for. POST /api/admin/user/delete removes the user, their passkeys, their push subscriptions, their presence entry, their training history and any Coach credential of theirs. Two refusals, because nothing in the UI could undo either: an admin cannot delete their own account, and the last remaining admin cannot be removed. The invite code they joined with stays burned — it was used, and freeing it would quietly widen an invite-only instance. In the dashboard it asks twice, naming the account both times, and offers their data as a download first: the training history is theirs. Five tests drive the real server. |