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
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.
This commit is contained in:
1 parent
5c69540f62
commit
90aa802980
24 files changed
+2078
-6
No files matched your search
@@ -1362,6 +1362,21 @@ body.chips-dragging *{cursor:inherit}
|
||||
.vh-card .l .icn{color:var(--tint)}
|
||||
.vh-card .v{color:var(--tint)}
|
||||
.vh-unit{margin-left:4px;font-size:14px;font-weight:500;color:var(--label-2);letter-spacing:0}
|
||||
/* The second opinion: one card above the grid, tinted like the app's own accent rather than a
|
||||
metric family — it is not a measurement, it is a judgment about them. Each row is a question and
|
||||
the answer with its probability, and the probability is a smaller, dimmer line on purpose: the
|
||||
claim and how sure the model was must not read as the same weight. */
|
||||
.ins-card{--tint:var(--acc);padding:12px 14px 14px;margin-bottom:12px}
|
||||
.ins-hd{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-bottom:4px}
|
||||
.ins-t{display:flex;align-items:center;gap:6px;font-size:14px;font-weight:600;color:var(--tint)}
|
||||
.ins-t .icn{font-size:15px}
|
||||
.ins-i{background:none;border:0;padding:2px;color:var(--label-3);cursor:pointer;display:flex}
|
||||
.ins-i .icn{font-size:15px}
|
||||
.ins-rows{display:flex;flex-direction:column;gap:7px;margin:4px 0 0}
|
||||
.ins-row{display:flex;align-items:baseline;justify-content:space-between;gap:10px}
|
||||
.ins-k{font-size:12.5px;color:var(--label-2)}
|
||||
.ins-v{font-size:14.5px;font-weight:600;color:var(--label);text-align:right;letter-spacing:-.01em}
|
||||
.ins-v i{margin-left:5px;font-size:11.5px;font-weight:500;font-style:normal;color:var(--label-3);font-variant-numeric:tabular-nums}
|
||||
.vh-big{font-size:34px;color:var(--tint)}
|
||||
.vh-trend{
|
||||
float:right;display:inline-flex;align-items:center;gap:1px;
|
||||
|
||||
@@ -35,6 +35,7 @@ const LABELS = {
|
||||
'auth.health.key.rotate': 'Replaced the health ingest key',
|
||||
'auth.health.clear': 'Deleted their health data',
|
||||
'auth.health.metric.clear': 'Reset one health metric',
|
||||
'auth.health.insight': 'Asked for a second opinion',
|
||||
'admin.user.disable': 'Disabled an account',
|
||||
'admin.user.enable': 'Re-enabled an account',
|
||||
'admin.user.delete': 'Deleted an account',
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
/* The Spanish catalogue is one object literal, so a key written twice is legal JavaScript and the
|
||||
last one silently wins. That is not a style question: adding the body-part word "Back" to the
|
||||
second-opinion card redefined the app's own Back button from "Atrás" to "Espalda", and nothing —
|
||||
no test, no type, no linter — would have said a word. This reads the file as text, because by the
|
||||
time it is imported the duplicate is already gone.
|
||||
|
||||
Identical values are refused too, not just conflicting ones: a key written twice is a fact about
|
||||
the file that the next person editing either copy cannot see. */
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { readFileSync } from 'node:fs'
|
||||
|
||||
const source = readFileSync('src/locales/es.js', 'utf8')
|
||||
|
||||
describe('the Spanish catalogue', () => {
|
||||
it('has no key written twice', () => {
|
||||
const seen = new Map()
|
||||
const dupes = []
|
||||
for (const [i, line] of source.split('\n').entries()) {
|
||||
const m = /^ {2}'((?:[^'\\]|\\.)*)': (.*)$/.exec(line)
|
||||
if (!m) continue
|
||||
const [, key, value] = m
|
||||
if (seen.has(key)) dupes.push(`${key} (lines ${seen.get(key)} and ${i + 1})`)
|
||||
else seen.set(key, i + 1)
|
||||
}
|
||||
expect(dupes).toEqual([])
|
||||
// A floor, so a file that stopped parsing into keys at all cannot pass this by accident.
|
||||
expect(seen.size).toBeGreaterThan(1000)
|
||||
})
|
||||
|
||||
it('gives every key a non-empty translation', () => {
|
||||
const empty = source.split('\n')
|
||||
.map((line, i) => ({ line, i }))
|
||||
.filter(({ line }) => /^ {2}'(?:[^'\\]|\\.)*':\s*(''|"")/.test(line))
|
||||
.map(({ line, i }) => `${i + 1}: ${line.trim()}`)
|
||||
expect(empty).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,148 @@
|
||||
/* insight-view.js — the second opinion, as a card reads it.
|
||||
*
|
||||
* The server answers in the vocabulary of the questions it asked: a rubric level 1-5, a probability
|
||||
* of "yes", an option key that is either a body part the library uses or a health metric name. This
|
||||
* file is the only place that turns those into words, which is what makes the same answer legible
|
||||
* in Spanish and checkable in a test — a probability rendered as a sentence is exactly the kind of
|
||||
* thing that goes wrong quietly.
|
||||
*
|
||||
* Two rules it follows everywhere. **A probability is never rounded up into a claim**: 0.55 of a
|
||||
* deload is shown as "55% probable", not as "take a deload week". And **an answer that is missing
|
||||
* stays missing** — the card says the question was not answered rather than showing a zero.
|
||||
*/
|
||||
import { t } from './i18n-core.js'
|
||||
import { specOf, valueOfDay, fmtValue } from './vitals-view.js'
|
||||
|
||||
/* The five rubric levels the readiness question offers, in the order the server sends them. The
|
||||
labels are the answer's meaning, not the model's prose: this is what a level 3 *is*. */
|
||||
export const READINESS_LEVELS = ['empty', 'below-par', 'normal', 'fresh', 'peaking']
|
||||
const READINESS_LABEL = {
|
||||
empty: 'Empty',
|
||||
'below-par': 'Below par',
|
||||
normal: 'Normal',
|
||||
fresh: 'Fresh',
|
||||
peaking: 'Peaking'
|
||||
}
|
||||
|
||||
/** The body parts the feature's questions can name (the library's own `bp` vocabulary). */
|
||||
export const BODY_PARTS = ['chest', 'back', 'shoulders', 'upper arms', 'lower arms', 'waist', 'upper legs', 'lower legs', 'neck', 'cardio']
|
||||
const BODY_PART_LABEL = {
|
||||
chest: 'Chest',
|
||||
// Not 'Back': that key is the app's own Back button, and a translation key cannot mean two
|
||||
// things in two screens ('Atrás' for the button, 'Espalda' for the muscle).
|
||||
back: 'Back muscles',
|
||||
shoulders: 'Shoulders',
|
||||
'upper arms': 'Arms',
|
||||
'lower arms': 'Forearms',
|
||||
waist: 'Trunk',
|
||||
'upper legs': 'Legs',
|
||||
'lower legs': 'Calves',
|
||||
neck: 'Neck',
|
||||
cardio: 'Conditioning'
|
||||
}
|
||||
export const bodyPartLabel = bp => (BODY_PART_LABEL[bp] ? t(BODY_PART_LABEL[bp]) : String(bp || ''))
|
||||
|
||||
/** A probability, as a percentage a person reads — never as a decision. */
|
||||
export const pct = p => (p == null || !Number.isFinite(p) ? null : Math.round(p * 100))
|
||||
|
||||
/**
|
||||
* The readiness answer: the level the score lands nearest, its label, and the raw score beside it so
|
||||
* "Normal · 2,4/5" can be read rather than trusted. A distribution, when one came, is preferred for
|
||||
* the level because it is the model's own ranking rather than our rounding of its average.
|
||||
*/
|
||||
export function readinessOf(insight) {
|
||||
const a = insight && insight.answers && insight.answers.readiness
|
||||
if (!a || a.value == null || !Number.isFinite(a.value)) return null
|
||||
let idx = null
|
||||
const probs = a.probabilities
|
||||
if (probs && Object.keys(probs).length) {
|
||||
// Levels arrive either keyed by their text or by their number; take the most likely one.
|
||||
let bestP = -1
|
||||
Object.entries(probs).forEach(([k, p]) => {
|
||||
const byText = READINESS_LEVELS.indexOf(String(k))
|
||||
const byNum = Number(k)
|
||||
const level = byText >= 0 ? byText : (Number.isInteger(byNum) && byNum >= 1 && byNum <= READINESS_LEVELS.length ? byNum - 1 : null)
|
||||
if (level != null && p > bestP) { bestP = p; idx = level }
|
||||
})
|
||||
}
|
||||
if (idx == null) idx = Math.min(READINESS_LEVELS.length - 1, Math.max(0, Math.round(a.value) - 1))
|
||||
return {
|
||||
level: READINESS_LEVELS[idx],
|
||||
label: t(READINESS_LABEL[READINESS_LEVELS[idx]]),
|
||||
score: a.value,
|
||||
p: a.p ?? null
|
||||
}
|
||||
}
|
||||
|
||||
/** The deload answer: a probability of yes, and the plain reading of which side it fell. */
|
||||
export function deloadOf(insight) {
|
||||
const a = insight && insight.answers && insight.answers.deload
|
||||
if (!a || a.p == null || !Number.isFinite(a.p)) return null
|
||||
return { p: a.p, yes: a.p >= 0.5 }
|
||||
}
|
||||
|
||||
/** The limiter answer: a body part, or the honest "nothing stands out" the question offered. */
|
||||
export function limiterOf(insight) {
|
||||
const a = insight && insight.answers && insight.answers.limiter
|
||||
if (!a || !a.option) return null
|
||||
if (a.option === 'none') return { none: true, p: a.p ?? null, label: t('Nothing stands out') }
|
||||
// An option we did not offer is shown as it came, marked, rather than dressed up as one of ours.
|
||||
return { none: false, option: a.option, p: a.p ?? null, known: a.known !== false, label: bodyPartLabel(a.option) }
|
||||
}
|
||||
|
||||
/** The attention answer, with the metric's own label and number from the catalogue. */
|
||||
export function attentionOf(insight, data) {
|
||||
const a = insight && insight.answers && insight.answers.attention
|
||||
if (!a || !a.option) return null
|
||||
if (a.option === 'none') return { none: true, p: a.p ?? null, label: t('Nothing needs attention') }
|
||||
const s = specOf(a.option)
|
||||
const card = (data && data.metrics && data.metrics[a.option]) || null
|
||||
const today = card && Array.isArray(card.days) && card.days.length ? card.days[card.days.length - 1] : null
|
||||
const value = today ? valueOfDay(today, s) : null
|
||||
return {
|
||||
none: false,
|
||||
name: a.option,
|
||||
p: a.p ?? null,
|
||||
known: a.known !== false,
|
||||
label: s.unknown ? a.option : t(s.label),
|
||||
unit: s.unit || (card && card.units) || '',
|
||||
// The newest reading of the metric it named, so "watch your resting heart rate" arrives with
|
||||
// the number that prompted it. Null when the metric has no day the catalogue can read.
|
||||
value: value != null && Number.isFinite(value) ? value : null,
|
||||
dec: s.dec
|
||||
}
|
||||
}
|
||||
|
||||
/** Everything the card draws, or nulls where the question went unanswered. */
|
||||
export function insightView(insight, data) {
|
||||
if (!insight || !insight.answers) return null
|
||||
return {
|
||||
readiness: readinessOf(insight),
|
||||
deload: deloadOf(insight),
|
||||
limiter: limiterOf(insight),
|
||||
attention: attentionOf(insight, data),
|
||||
answered: Object.values(insight.answers).filter(Boolean).length,
|
||||
asked: Object.keys(insight.answers).length
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* What was sent, as lines the sheet can list — counts, metric names and a plain yes/no about the
|
||||
* limitations note. It is the same summary the server returns with an answer, and it exists so the
|
||||
* screen can say what leaving the instance means before anybody presses the button.
|
||||
*/
|
||||
export function sentRows(sent, data) {
|
||||
if (!sent) return []
|
||||
const labels = (sent.metrics || []).map(name => {
|
||||
const s = specOf(name)
|
||||
return s.unknown ? name : t(s.label)
|
||||
})
|
||||
return [
|
||||
{ key: 'metrics', label: t('Health metrics'), value: labels.length ? labels.join(', ') : t('none') },
|
||||
{ key: 'health_days', label: t('Days of health data'), value: fmtValue(sent.health_days || 0) },
|
||||
{ key: 'sessions', label: t('Sessions in the last 4 weeks'), value: fmtValue(sent.sessions || 0) },
|
||||
{ key: 'last', label: t('Last session'), value: sent.last_session_days_ago == null ? t('never') : t('{0} d ago', sent.last_session_days_ago) },
|
||||
{ key: 'parts', label: t('Body parts trained'), value: (sent.body_parts || []).map(bodyPartLabel).join(', ') || t('none') },
|
||||
{ key: 'limits', label: t('Your limitations note'), value: sent.includes_limitations ? t('yes') : t('no') }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
/* The second opinion as words: which level a score lands on, what a probability reads as, and what
|
||||
the sent summary says. Worth a test because every one of these is a *translation* of a number
|
||||
into a claim — the place where a 0.55 quietly becomes "do it" if nobody is looking. */
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import {
|
||||
readinessOf, deloadOf, limiterOf, attentionOf, insightView, sentRows, bodyPartLabel, pct, READINESS_LEVELS
|
||||
} from './insight-view.js'
|
||||
|
||||
const insight = answers => ({ v: 1, at: Date.parse('2026-09-23T18:00:00Z'), model: 'jev-1.13', answers })
|
||||
const bucket = v => ({ n: 1, sum: v, min: v, max: v, last: v, avg: v })
|
||||
const data = {
|
||||
metrics: {
|
||||
resting_heart_rate: { units: 'bpm', days: [{ day: '2026-09-22', n: 1, f: { qty: bucket(56) } }, { day: '2026-09-23', n: 1, f: { qty: bucket(62) } }] }
|
||||
}
|
||||
}
|
||||
|
||||
describe('the second opinion, as the card reads it', () => {
|
||||
it('puts a readiness score on a level, and keeps the number beside it', () => {
|
||||
expect(readinessOf(insight({ readiness: { type: 'score', value: 3.2, p: 0.5 } })))
|
||||
.toEqual({ level: 'normal', label: 'Normal', score: 3.2, p: 0.5 })
|
||||
expect(readinessOf(insight({ readiness: { type: 'score', value: 1.2 } })).level).toBe('empty')
|
||||
expect(readinessOf(insight({ readiness: { type: 'score', value: 9 } })).level).toBe('peaking')
|
||||
expect(READINESS_LEVELS.length).toBe(5)
|
||||
// A distribution is the model's own ranking, and beats our rounding of its average.
|
||||
expect(readinessOf(insight({ readiness: { type: 'score', value: 2.6, probabilities: { empty: 0.1, 'below-par': 0.5, normal: 0.4 } } })).level).toBe('below-par')
|
||||
expect(readinessOf(insight({ readiness: { type: 'score', value: 2.6, probabilities: { 1: 0.1, 2: 0.7, 3: 0.2 } } })).level).toBe('below-par')
|
||||
expect(readinessOf(insight({ readiness: null }))).toBeNull()
|
||||
expect(readinessOf(null)).toBeNull()
|
||||
})
|
||||
|
||||
it('reads a deload probability as a probability, never as an instruction', () => {
|
||||
expect(deloadOf(insight({ deload: { type: 'noul', p: 0.62 } }))).toEqual({ p: 0.62, yes: true })
|
||||
expect(deloadOf(insight({ deload: { type: 'noul', p: 0.49 } })).yes).toBe(false)
|
||||
expect(deloadOf(insight({ deload: null }))).toBeNull()
|
||||
expect(pct(0.62)).toBe(62)
|
||||
expect(pct(0.005)).toBe(1)
|
||||
expect(pct(null)).toBeNull()
|
||||
expect(pct(undefined)).toBeNull()
|
||||
})
|
||||
|
||||
it('names the body part, or says nothing stands out', () => {
|
||||
expect(limiterOf(insight({ limiter: { type: 'choice', option: 'upper legs', p: 0.7 } })))
|
||||
.toEqual({ none: false, option: 'upper legs', p: 0.7, known: true, label: 'Legs' })
|
||||
expect(limiterOf(insight({ limiter: { type: 'choice', option: 'none' } })).none).toBe(true)
|
||||
// An option we never offered is shown as it came, flagged: the card can then say so instead of
|
||||
// passing a stranger's word off as one of ours.
|
||||
const odd = limiterOf(insight({ limiter: { type: 'choice', option: 'left hip', known: false } }))
|
||||
expect(odd.label).toBe('left hip')
|
||||
expect(odd.known).toBe(false)
|
||||
expect(limiterOf(insight({ limiter: null }))).toBeNull()
|
||||
expect(bodyPartLabel('cardio')).toBe('Conditioning')
|
||||
expect(bodyPartLabel('something new')).toBe('something new')
|
||||
})
|
||||
|
||||
it('brings the number behind the metric it points at', () => {
|
||||
const a = attentionOf(insight({ attention: { type: 'choice', option: 'resting_heart_rate', p: 0.6 } }), data)
|
||||
expect(a.label).toBe('Resting heart rate')
|
||||
expect(a.unit).toBe('bpm')
|
||||
expect(a.value).toBe(62, 'the newest reading, not the one before it')
|
||||
expect(a.p).toBe(0.6)
|
||||
// A metric the catalogue does not know keeps its own name and simply has no number to show.
|
||||
const unknown = attentionOf(insight({ attention: { type: 'choice', option: 'some_future_metric' } }), data)
|
||||
expect(unknown.label).toBe('some_future_metric')
|
||||
expect(unknown.value).toBeNull()
|
||||
expect(unknown.known).toBe(true)
|
||||
expect(attentionOf(insight({ attention: { type: 'choice', option: 'none' } })).none).toBe(true)
|
||||
expect(attentionOf(insight({}), data)).toBeNull()
|
||||
})
|
||||
|
||||
it('summarises the whole answer, and counts what came back', () => {
|
||||
const v = insightView(insight({
|
||||
readiness: { type: 'score', value: 3 },
|
||||
deload: { type: 'noul', p: 0.3 },
|
||||
limiter: null,
|
||||
attention: { type: 'choice', option: 'resting_heart_rate' }
|
||||
}), data)
|
||||
expect(v.readiness.label).toBe('Normal')
|
||||
expect(v.deload.yes).toBe(false)
|
||||
expect(v.limiter).toBeNull()
|
||||
expect(v.attention.label).toBe('Resting heart rate')
|
||||
expect(v.asked).toBe(4)
|
||||
expect(v.answered).toBe(3)
|
||||
expect(insightView(null, data)).toBeNull()
|
||||
})
|
||||
|
||||
it('lists what leaves the instance, in words, for the sheet that promises it', () => {
|
||||
const rows = sentRows({
|
||||
metrics: ['resting_heart_rate', 'some_future_metric'],
|
||||
health_days: 7,
|
||||
sessions: 12,
|
||||
last_session_days_ago: 1,
|
||||
body_parts: ['chest', 'upper legs'],
|
||||
includes_limitations: true
|
||||
}, data)
|
||||
const get = k => rows.find(r => r.key === k).value
|
||||
expect(get('metrics')).toBe('Resting heart rate, some_future_metric')
|
||||
expect(get('health_days')).toBe('7')
|
||||
expect(get('sessions')).toBe('12')
|
||||
expect(get('last')).toBe('1 d ago')
|
||||
expect(get('parts')).toBe('Chest, Legs')
|
||||
expect(get('limits')).toBe('yes')
|
||||
// Nothing to say is said as nothing, not as a zero.
|
||||
expect(sentRows(null)).toEqual([])
|
||||
const empty = sentRows({ metrics: [], body_parts: [], last_session_days_ago: null })
|
||||
expect(empty.find(r => r.key === 'metrics').value).toBe('none')
|
||||
expect(empty.find(r => r.key === 'last').value).toBe('never')
|
||||
expect(empty.find(r => r.key === 'limits').value).toBe('no')
|
||||
})
|
||||
})
|
||||
@@ -1405,6 +1405,51 @@ export default {
|
||||
'Delete the health data': 'Borrar los datos de salud',
|
||||
// resetting one measurement, from its own detail sheet
|
||||
'Reset this measurement': 'Reiniciar esta medición',
|
||||
// segunda opinión (Jev)
|
||||
'Second opinion': 'Segunda opinión',
|
||||
'Second opinion updated': 'Segunda opinión actualizada',
|
||||
'What is sent': 'Qué se envía',
|
||||
'Where it goes': 'A dónde va',
|
||||
'not configured': 'sin configurar',
|
||||
'Readiness': 'Disposición',
|
||||
'Ease off this week': 'Bajar carga esta semana',
|
||||
'Least recovered': 'Menos recuperado',
|
||||
'Yes': 'Sí',
|
||||
'Empty': 'Vació',
|
||||
'Below par': 'Por debajo',
|
||||
'Normal': 'Normal',
|
||||
'Fresh': 'Fresco',
|
||||
'Peaking': 'En punto',
|
||||
'Trunk': 'Tronco',
|
||||
'Conditioning': 'Cardio',
|
||||
'Nothing stands out': 'No destaca nada',
|
||||
'Nothing needs attention': 'Nada necesita atención',
|
||||
'{0}% likely': '{0}% de probabilidad',
|
||||
'{0}% probable': '{0}% probable',
|
||||
'Asked {0}': 'Preguntado {0}',
|
||||
'Ask': 'Preguntar',
|
||||
'Ask again': 'Preguntar otra vez',
|
||||
'Ask now': 'Preguntar ahora',
|
||||
'Asking…': 'Preguntando…',
|
||||
'your data has moved since': 'tus datos han cambiado desde entonces',
|
||||
'It was made from numbers that have changed, so treat it as out of date until you ask again.': 'Se hizo con números que ya cambiaron, así que trátala como desactualizada hasta que vuelvas a preguntar.',
|
||||
'That is today\'s budget for this instance. It resets tomorrow.': 'Ese es el cupo de hoy en esta instancia. Se renueva mañana.',
|
||||
'You can ask again in a few minutes.': 'Podés volver a preguntar en unos minutos.',
|
||||
'The model answered none of the questions, so there is nothing to show. Asking again may work; it may also be the provider.': 'El modelo no respondió ninguna pregunta, así que no hay nada que mostrar. Puede funcionar si volvés a preguntar; también puede ser el proveedor.',
|
||||
'One judgment about your own numbers — how ready you are, whether this week should ease off, what is lagging — from a model that answers in probabilities. It costs a request, so it happens when you ask, never on a timer.': 'Un juicio sobre tus propios números — qué tan listo estás, si esta semana conviene bajar carga, qué va atrasado — de un modelo que responde con probabilidades. Cuesta una petición, así que pasa cuando preguntás, nunca por temporizador.',
|
||||
'A model reads a summary of your own numbers and answers four questions with probabilities: how ready you are, whether this week should ease off, which part of you looks least recovered, and which health metric deserves attention. It writes nothing into your plan — you decide what to do with it.': 'Un modelo lee un resumen de tus números y responde cuatro preguntas con probabilidades: qué tan listo estás, si esta semana conviene bajar carga, qué parte del cuerpo parece menos recuperada y qué métrica de salud merece atención. No escribe nada en tu plan: vos decidís qué hacer con eso.',
|
||||
'Aggregates and counts only: no name, no ids, no workout titles, no chat. The one piece of your own writing that goes is the limitations note from the Coach intake, because "bad shoulder" changes the answer — everything else you have typed stays here.': 'Solo agregados y conteos: ni nombre, ni identificadores, ni títulos de entrenamientos, ni chat. Lo único escrito por vos que sale es la nota de limitaciones del cuestionario del Coach, porque "hombro malo" cambia la respuesta; todo lo demás que escribiste se queda acá.',
|
||||
'Nothing yet — the summary appears after the first time you ask.': 'Todavía nada: el resumen aparece después de la primera vez que preguntes.',
|
||||
'Health metrics': 'Métricas de salud',
|
||||
'Days of health data': 'Días de datos de salud',
|
||||
'Sessions in the last 4 weeks': 'Sesiones en las últimas 4 semanas',
|
||||
'Last session': 'Última sesión',
|
||||
'Body parts trained': 'Partes entrenadas',
|
||||
'Your limitations note': 'Tu nota de limitaciones',
|
||||
'none': 'ninguna',
|
||||
'never': 'nunca',
|
||||
'yes': 'sí',
|
||||
'no': 'no',
|
||||
'Your next sync from the iPhone rebuilds it': 'El próximo envío desde el iPhone la reconstruye',
|
||||
'Resetting removes every day stored for this metric and nothing else: your other metrics, your workouts and your ingest key stay. With a Date Range of a week or more, the next sync sends it again from Apple Health.': 'Reiniciar borra todos los días guardados de esta métrica y nada más: tus otras métricas, tus entrenamientos y tu clave de ingesta se quedan. Con un rango de fechas de una semana o más, el próximo envío la manda otra vez desde Apple Health.',
|
||||
'Reset {0}?': '¿Reiniciar {0}?',
|
||||
@@ -1431,7 +1476,6 @@ export default {
|
||||
'Guest mode lives entirely in this browser, and your iPhone can only post to a profile on a server. Create one, then connect Apple Health from here — it takes a minute and nothing you logged as a guest is lost.': 'El modo invitado vive enteramente en este navegador, y tu iPhone solo puede enviar datos a un perfil en un servidor. Crea uno y luego conecta Apple Health desde aquí: toma un minuto y no se pierde nada de lo que registraste como invitado.',
|
||||
'Create a profile': 'Crear un perfil',
|
||||
// el filtro de periodo, las gráficas y el rótulo de frescura
|
||||
'Today': 'Hoy',
|
||||
'today': 'hoy',
|
||||
'yesterday': 'ayer',
|
||||
'Trends': 'Tendencias',
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
fmtValue, unitLabel, agoLabel, ingestUrl, detailRows, dayLabel,
|
||||
hourRows, hourChartPoints, historyRows
|
||||
} from '../lib/vitals-view.js'
|
||||
import { insightView, sentRows, pct } from '../lib/insight-view.js'
|
||||
|
||||
/* The period filter, "Today" first and by default: a card's headline is always the newest
|
||||
reading, and "is that right now?" is the question a five-minute cadence exists to answer. The
|
||||
@@ -87,6 +88,108 @@ function MetricCard({ card, onOpen }) {
|
||||
same card, two to a row; the shape of a week is the sparkline on it, and the chart worth reading
|
||||
is one tap away, where it also has the hours and the day-by-day numbers around it. */
|
||||
|
||||
/* ---------- the second opinion ---------- */
|
||||
|
||||
/**
|
||||
* The judgment card, above the grid. It exists only when the instance has a key configured — an
|
||||
* instance with no second opinion shows nothing at all rather than a card that cannot work.
|
||||
*
|
||||
* Everything on it is a probability: readiness is a level with the number behind it, a deload is
|
||||
* "62% probable" and not "take a week off", and the metric it points at arrives with the reading
|
||||
* that prompted it. That is the whole reason for asking a model that returns probabilities instead
|
||||
* of prose — a claim with its confidence attached can be argued with; a paragraph cannot.
|
||||
*/
|
||||
function InsightCard({ insight, view, sent, budget, busy, onAsk, onOpen }) {
|
||||
const stale = insight && !insight.fresh
|
||||
return <div className="card ins-card">
|
||||
<div className="ins-hd">
|
||||
<span className="ins-t"><Icon name="sparkles" />{t('Second opinion')}</span>
|
||||
<button className="ins-i" aria-label={t('What is sent')} onClick={onOpen}><Icon name="info" /></button>
|
||||
</div>
|
||||
|
||||
{!insight && <div className="small dim" style={{ lineHeight: 1.5, margin: '2px 0 10px' }}>
|
||||
{t('One judgment about your own numbers — how ready you are, whether this week should ease off, what is lagging — from a model that answers in probabilities. It costs a request, so it happens when you ask, never on a timer.')}
|
||||
</div>}
|
||||
|
||||
{insight && <div className="ins-rows">
|
||||
{view?.readiness && <div className="ins-row">
|
||||
<span className="ins-k">{t('Readiness')}</span>
|
||||
<span className="ins-v">{view.readiness.label}
|
||||
<i>{fmtValue(view.readiness.score, 1)}/5{view.readiness.p != null ? ' · ' + t('{0}% likely', pct(view.readiness.p)) : ''}</i>
|
||||
</span>
|
||||
</div>}
|
||||
{view?.deload && <div className="ins-row">
|
||||
<span className="ins-k">{t('Ease off this week')}</span>
|
||||
<span className="ins-v">{view.deload.yes ? t('Yes') : t('No')}
|
||||
<i>{t('{0}% probable', pct(view.deload.p))}</i>
|
||||
</span>
|
||||
</div>}
|
||||
{view?.limiter && <div className="ins-row">
|
||||
<span className="ins-k">{t('Least recovered')}</span>
|
||||
<span className="ins-v">{view.limiter.label}{view.limiter.p != null ? <i>{t('{0}% probable', pct(view.limiter.p))}</i> : null}</span>
|
||||
</div>}
|
||||
{view?.attention && <div className="ins-row">
|
||||
<span className="ins-k">{t('Worth watching')}</span>
|
||||
<span className="ins-v">{view.attention.label}
|
||||
{view.attention.value != null ? <i>{fmtValue(view.attention.value, view.attention.dec)} {unitLabel(view.attention.unit)}</i> : null}
|
||||
{view.attention.p != null ? <i>{t('{0}% probable', pct(view.attention.p))}</i> : null}
|
||||
</span>
|
||||
</div>}
|
||||
{view && view.answered === 0 && <div className="small dim">
|
||||
{t('The model answered none of the questions, so there is nothing to show. Asking again may work; it may also be the provider.')}
|
||||
</div>}
|
||||
</div>}
|
||||
|
||||
<div className="small dim" style={{ marginTop: 8, lineHeight: 1.45 }}>
|
||||
{insight
|
||||
? <>{t('Asked {0}', agoLabel(insight.at))}{insight.model ? ' · ' + insight.model : ''}{stale ? ' · ' + t('your data has moved since') : ''}</>
|
||||
: null}
|
||||
{stale && <div>{t('It was made from numbers that have changed, so treat it as out of date until you ask again.')}</div>}
|
||||
</div>
|
||||
|
||||
<div style={{ height: 10 }} />
|
||||
<Button size="sm" variant={insight ? 'ghost' : 'primary'} disabled={busy || !budget?.allowed} onClick={onAsk}>
|
||||
{busy ? t('Asking…') : insight ? t('Ask again') : t('Ask')}
|
||||
</Button>
|
||||
{!budget?.allowed && budget?.remaining === 0 && <div className="small dim" style={{ marginTop: 6 }}>
|
||||
{t('That is today\'s budget for this instance. It resets tomorrow.')}
|
||||
</div>}
|
||||
{!budget?.allowed && budget?.nextAt && <div className="small dim" style={{ marginTop: 6 }}>
|
||||
{t('You can ask again in a few minutes.')}
|
||||
</div>}
|
||||
</div>
|
||||
}
|
||||
|
||||
/** What leaves the server when you press the button, and where it goes. */
|
||||
function InsightSheet({ insight, sent, host, model, configured, onAsk, close }) {
|
||||
const rows = sentRows(sent)
|
||||
return <>
|
||||
<h3>{t('Second opinion')}</h3>
|
||||
<div className="small dim" style={{ lineHeight: 1.55, marginBottom: 14 }}>
|
||||
{t('A model reads a summary of your own numbers and answers four questions with probabilities: how ready you are, whether this week should ease off, which part of you looks least recovered, and which health metric deserves attention. It writes nothing into your plan — you decide what to do with it.')}
|
||||
</div>
|
||||
|
||||
<h4 className="sec">{t('Where it goes')}</h4>
|
||||
<div className="list">
|
||||
<Row icon="globe" title={t('Provider')} value={host || t('not configured')} />
|
||||
<Row icon="sparkles" title={t('Model')} value={model || '—'} />
|
||||
</div>
|
||||
|
||||
<h4 className="sec">{t('What is sent')}</h4>
|
||||
{rows.length
|
||||
? <div className="list">{rows.map(r => <Row key={r.key} title={r.label} value={r.value} />)}</div>
|
||||
: <div className="small dim">{t('Nothing yet — the summary appears after the first time you ask.')}</div>}
|
||||
<div className="small dim" style={{ marginTop: 10, lineHeight: 1.5 }}>
|
||||
{t('Aggregates and counts only: no name, no ids, no workout titles, no chat. The one piece of your own writing that goes is the limitations note from the Coach intake, because "bad shoulder" changes the answer — everything else you have typed stays here.')}
|
||||
</div>
|
||||
|
||||
{configured && <><div style={{ height: 10 }} />
|
||||
<Button size="sm" onClick={onAsk}>{t('Ask now')}</Button></>}
|
||||
<div style={{ height: 12 }} />
|
||||
<Button onClick={close}>{t('Close')}</Button>
|
||||
</>
|
||||
}
|
||||
|
||||
/* ---------- the two sheets ---------- */
|
||||
|
||||
/**
|
||||
@@ -284,6 +387,11 @@ export default function Health() {
|
||||
const [err, setErr] = useState('')
|
||||
const [days, setDays] = useState(1)
|
||||
const [loading, setLoading] = useState(true)
|
||||
/* The second opinion: whether this instance has one at all, what it said last, and whether it is
|
||||
still about the numbers on screen. Fetched once per visit, never on the 60-second tick — the
|
||||
store's own judgment does not change because a card refreshed. */
|
||||
const [ins, setIns] = useState(null)
|
||||
const [asking, setAsking] = useState(false)
|
||||
|
||||
/* Two different windows, and the screen keeps them apart on purpose.
|
||||
*
|
||||
@@ -301,6 +409,13 @@ export default function Health() {
|
||||
.catch(e => setErr(e.message))
|
||||
.finally(() => setLoading(false))
|
||||
}, [chartDays])
|
||||
|
||||
/* A failed call here must not take the screen down with it: the health data is the feature, this
|
||||
is a card on top of it. So the error is swallowed and the card simply stays as it was. */
|
||||
const loadInsight = useCallback(() => {
|
||||
api('/api/insights').then(r => setIns(r)).catch(() => {})
|
||||
}, [])
|
||||
useEffect(() => { if (!isGuest) loadInsight() }, [loadInsight, isGuest])
|
||||
useEffect(() => { if (!isGuest) load() }, [load, isGuest])
|
||||
// The phone posts every few minutes; a minute is often enough for the screen to feel live, and
|
||||
// it costs one small request. It never shows the loading state: `loading` is only rendered when
|
||||
@@ -351,6 +466,31 @@ export default function Health() {
|
||||
.catch(e => toast(e.message))
|
||||
})
|
||||
|
||||
const ask = () => {
|
||||
if (asking) return
|
||||
setAsking(true)
|
||||
api('/api/insights', { method: 'POST' })
|
||||
.then(r => {
|
||||
setIns(prev => ({
|
||||
...(prev || {}),
|
||||
configured: true,
|
||||
model: r.model,
|
||||
host: r.host,
|
||||
insight: r.insight,
|
||||
freshness: r.freshness,
|
||||
budget: r.budget,
|
||||
sent: r.sent || prev?.sent
|
||||
}))
|
||||
toast(t('Second opinion updated'))
|
||||
})
|
||||
.catch(e => toast(e.message))
|
||||
.finally(() => setAsking(false))
|
||||
}
|
||||
|
||||
const openInsight = () => openSheet(close => <InsightSheet
|
||||
insight={ins?.insight || null} sent={ins?.sent || null} host={ins?.host || null} model={ins?.model || null}
|
||||
configured={!!ins?.configured} onAsk={ask} close={close} />)
|
||||
|
||||
const setup = () => openSheet(close => <SetupSheet initialKey={data?.key} onKey={key} onRotate={rotate} onDelete={wipe} close={close} />)
|
||||
const openMetric = card => openSheet(close => <MetricSheet card={card} metric={data.metrics[card.name]} close={close}
|
||||
onReset={c => resetMetric(c, close)} />)
|
||||
@@ -382,6 +522,8 @@ export default function Health() {
|
||||
// twice in two different sizes (see the note above the sheets).
|
||||
const groups = groupedCards(cards)
|
||||
const workouts = workoutRows(data, { limit: 20 })
|
||||
// Everything the card draws, or null when nothing has been asked yet.
|
||||
const view = insightView(ins?.insight, data)
|
||||
const last = data?.last?.ts
|
||||
const ranges = RANGES.map(r => ({ value: r.value, label: r.key ? t(r.key) : r.label }))
|
||||
|
||||
@@ -405,6 +547,10 @@ export default function Health() {
|
||||
{!err && data && !hasVitals(data) && <Empty onSetup={setup} />}
|
||||
|
||||
{!err && hasVitals(data) && <>
|
||||
{ins?.configured && <InsightCard
|
||||
insight={ins.insight ? { ...ins.insight, fresh: ins.freshness?.fresh !== false } : null}
|
||||
view={view} sent={ins.sent} budget={ins.budget} busy={asking}
|
||||
onAsk={ask} onOpen={openInsight} />}
|
||||
<Segmented options={ranges} value={days} onChange={setDays} className="seg-range" />
|
||||
<div className="small dim" style={{ margin: '8px 2px 12px' }}>
|
||||
{/* The numbers below are always the newest reading, and with the phone pushing every few
|
||||
|
||||
@@ -199,6 +199,107 @@ const bucket = v => ({ n: 1, sum: v, min: v, max: v, last: v, avg: v })
|
||||
})
|
||||
})
|
||||
|
||||
/* The second opinion: a card that exists only when the instance has a key, that asks only when
|
||||
pressed, and that shows every answer with its probability rather than as a verdict. The API is
|
||||
mocked, so what is under test is the wiring — that a judgment from the server becomes words,
|
||||
that an unanswered question stays unanswered, and that nothing is asked without a press. */
|
||||
describe('the second opinion', () => {
|
||||
const INSIGHTS = {
|
||||
ok: true,
|
||||
configured: true,
|
||||
model: 'jev-1.13',
|
||||
host: 'opencode.ai',
|
||||
insight: {
|
||||
v: 1, at: Date.now() - 20 * 60000, model: 'jev-1.13',
|
||||
answers: {
|
||||
readiness: { type: 'score', value: 2.4, p: 0.58, probabilities: { empty: 0.1, 'below-par': 0.6, normal: 0.3 } },
|
||||
deload: { type: 'noul', p: 0.62 },
|
||||
limiter: { type: 'choice', option: 'back', p: 0.55, known: true },
|
||||
attention: { type: 'choice', option: 'resting_heart_rate', p: 0.6, known: true }
|
||||
}
|
||||
},
|
||||
freshness: { fresh: true, reason: null },
|
||||
budget: { used: 1, remaining: 11, allowed: true, waitMs: 0, nextAt: null },
|
||||
sent: { metrics: ['step_count', 'resting_heart_rate'], health_days: 7, sessions: 4, last_session_days_ago: 1, body_parts: ['chest', 'back'], includes_limitations: true }
|
||||
}
|
||||
const mountWith = async routes => {
|
||||
api.mockImplementation(async path => {
|
||||
const hit = Object.keys(routes).find(k => path.startsWith(k))
|
||||
if (!hit) throw new Error('unexpected ' + path)
|
||||
return typeof routes[hit] === 'function' ? routes[hit](path) : routes[hit]
|
||||
})
|
||||
await act(async () => { root.render(<><Health /><Modals /></>) })
|
||||
await act(async () => {})
|
||||
}
|
||||
const card = () => host.querySelector('.ins-card')
|
||||
const byText = needle => [...host.querySelectorAll('button')].find(b => b.textContent.includes(needle))
|
||||
|
||||
it('draws nothing at all on an instance with no key', async () => {
|
||||
await mountWith({ '/api/insights': { ok: true, configured: false, insight: null, freshness: { fresh: false }, budget: { allowed: true, remaining: 0 } }, '/api/vitals': VITALS })
|
||||
expect(card()).toBe(null)
|
||||
})
|
||||
|
||||
it('shows each answer with the probability it came with', async () => {
|
||||
await mountWith({ '/api/insights': INSIGHTS, '/api/vitals': VITALS })
|
||||
expect(card()).toBeTruthy()
|
||||
const text = card().textContent
|
||||
// The level is chosen by the distribution, not by rounding the score: 2.4 rounds to 2, and the
|
||||
// model put 0.6 on "below par" — its own ranking wins.
|
||||
expect(text).toContain('Below par')
|
||||
expect(text).toContain('2.4/5')
|
||||
expect(text).toContain('58% likely')
|
||||
// A deload is a probability, never "take a week off".
|
||||
expect(text).toContain('62% probable')
|
||||
expect(text).toContain('Back muscles')
|
||||
expect(text).toContain('Resting heart rate')
|
||||
expect(text).toContain('jev-1.13')
|
||||
expect(text).toContain('20 min ago')
|
||||
// Nothing was asked to draw that: the card reads what was already stored.
|
||||
expect(api.mock.calls.map(c => [c[0], c[1] && c[1].method])).not.toContainEqual(['/api/insights', 'POST'])
|
||||
})
|
||||
|
||||
it('asks only when pressed, and only once per press', async () => {
|
||||
const calls = []
|
||||
await mountWith({
|
||||
'/api/insights': async path => {
|
||||
calls.push(path)
|
||||
if (calls.filter(p => p === '/api/insights').length === 1) return INSIGHTS
|
||||
return { ...INSIGHTS, insight: { ...INSIGHTS.insight, answers: { ...INSIGHTS.insight.answers, deload: { type: 'noul', p: 0.2 } } } }
|
||||
},
|
||||
'/api/vitals': VITALS
|
||||
})
|
||||
// The card as loaded: no answer yet, so the button invites rather than repeats.
|
||||
expect(card().textContent).toContain('Ask')
|
||||
await act(async () => { byText('Ask').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
|
||||
await act(async () => {})
|
||||
expect(api.mock.calls.filter(c => c[0] === '/api/insights' && c[1] && c[1].method === 'POST').length).toBe(1)
|
||||
})
|
||||
|
||||
it('keeps the health screen working when the insights endpoint fails', async () => {
|
||||
await mountWith({
|
||||
'/api/insights': () => { throw new Error('HTTP 500') },
|
||||
'/api/vitals': VITALS
|
||||
})
|
||||
// The card is a card: the metrics below it are still drawn, and nothing shouts.
|
||||
expect(cards().length).toBe(5)
|
||||
expect(card()).toBe(null)
|
||||
expect(text()).not.toContain('HTTP 500')
|
||||
})
|
||||
|
||||
it('says what leaves the instance, in the sheet behind the info button', async () => {
|
||||
await mountWith({ '/api/insights': INSIGHTS, '/api/vitals': VITALS })
|
||||
await act(async () => { host.querySelector('.ins-i').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
|
||||
await act(async () => {})
|
||||
const sheet = document.body.textContent
|
||||
expect(sheet).toContain('opencode.ai')
|
||||
expect(sheet).toContain('Aggregates and counts only')
|
||||
// The metrics that go are named the way the grid names them, not as HAE spells them.
|
||||
expect(sheet).toContain('Resting heart rate')
|
||||
expect(sheet).toContain('Steps')
|
||||
expect(sheet).toContain('Body parts trained')
|
||||
})
|
||||
})
|
||||
|
||||
/* The detail sheet is where a number becomes a day. Tapping a card has to show the hours the
|
||||
phone actually sent, and it has to say so plainly when it sent none — a card whose automation
|
||||
groups by Day has no hours anywhere, and an empty chart there would read as a bug. The hours
|
||||
|
||||
Reference in new issue
Block a user