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.
This commit is contained in:
dsantillan committed 2026-09-23 11:05:32 -04:00
1 parent 002e5e6bbb
commit 41b004fea7
3 files changed
+84 -16

No files matched your search

+3
View File
@@ -1376,6 +1376,9 @@ export default {
'URL': 'URL',
'Close': 'Cerrar',
'Create an ingest key': 'Crear una clave de ingesta',
'Copy the key': 'Copiar la clave',
'Copy the URL': 'Copiar la URL',
'Paste that as the value of the Authorization header in Health Auto Export. You can come back to this screen and copy it again whenever you need it.': 'Pega eso como valor del encabezado Authorization en Health Auto Export. Podés volver a esta pantalla y copiarla de nuevo cuando la necesites.',
'1. The endpoint': '1. El endpoint',
'2. The header': '2. El encabezado',
'3. In Health Auto Export': '3. En Health Auto Export',
+34 -16
View File
@@ -100,10 +100,19 @@ function MetricSheet({ card, metric, close }) {
}
/** Setup: the URL, the header, the settings in Health Auto Export that keep the numbers exact. */
function SetupSheet({ data, onKey, onRotate, onDelete, close }) {
function SetupSheet({ initialKey, onKey, onRotate, onDelete, close }) {
const toast = useUI(s => s.toast)
/* The key lives in THIS component's state, not in the screen's. A sheet is rendered from a
function captured when it was opened (useUI.openSheet keeps the element), so a `key` prop
read off the screen would still be the pre-creation value: the first version said "Ingest key
created" and then showed nothing to copy, because the element holding the key had already
been created with `key: null` and nothing re-rendered it. Local state re-renders the sheet
itself, which is what makes the key appear the moment it exists. */
const [key, setKey] = useState(initialKey || null)
const url = ingestUrl()
const copy = (text, label) => { navigator.clipboard?.writeText(text).catch(() => {}); toast(t('{0} copied', label)) }
const create = () => onKey().then(k => { if (k) setKey(k) })
const rotate = () => onRotate().then(k => { if (k) setKey(k) })
return <>
<h3>{t('Connect Apple Health')}</h3>
<div className="small dim" style={{ lineHeight: 1.5, marginBottom: 14 }}>
@@ -111,14 +120,21 @@ function SetupSheet({ data, onKey, onRotate, onDelete, close }) {
</div>
<h4 className="sec">{t('1. The endpoint')}</h4>
<div className="cfgrow"><code className="vh-code">{url}</code>
<button className="iconbtn" onClick={() => copy(url, t('URL'))} aria-label={t('Copy')}><Icon name="clipboard" /></button></div>
<div className="cfgrow"><code className="vh-code">{url}</code></div>
<div style={{ height: 8 }} />
<Button icon="clipboard" onClick={() => copy(url, t('URL'))}>{t('Copy the URL')}</Button>
<h4 className="sec">{t('2. The header')}</h4>
{data?.key
? <div className="cfgrow"><code className="vh-code">Authorization: Bearer {data.key}</code>
<button className="iconbtn" onClick={() => copy('Bearer ' + data.key, t('Key'))} aria-label={t('Copy')}><Icon name="clipboard" /></button></div>
: <Button variant="primary" icon="key" onClick={onKey}>{t('Create an ingest key')}</Button>}
{key
? <>
<div className="cfgrow"><code className="vh-code">Authorization: Bearer {key}</code></div>
<div style={{ height: 8 }} />
<Button variant="primary" icon="clipboard" onClick={() => copy('Bearer ' + key, t('Key'))}>{t('Copy the key')}</Button>
<div className="small dim" style={{ marginTop: 8, lineHeight: 1.5 }}>
{t('Paste that as the value of the Authorization header in Health Auto Export. You can come back to this screen and copy it again whenever you need it.')}
</div>
</>
: <Button variant="primary" icon="key" onClick={create}>{t('Create an ingest key')}</Button>}
<h4 className="sec">{t('3. In Health Auto Export')}</h4>
<div className="list">
@@ -136,10 +152,10 @@ function SetupSheet({ data, onKey, onRotate, onDelete, close }) {
{t('Pick a cadence that suits you — every 5 minutes, hourly, or once a day all land the same way.')}
</div>
{data?.key && <>
{key && <>
<h4 className="sec">{t('Manage')}</h4>
<div className="list">
<Row icon="reset" title={t('Replace the key')} subtitle={t('The old one stops working immediately')} accessory="chevron" onClick={onRotate} />
<Row icon="reset" title={t('Replace the key')} subtitle={t('The old one stops working immediately')} accessory="chevron" onClick={rotate} />
<Row icon="trash" iconTint="var(--red)" title={t('Delete the health data')} subtitle={t('Keeps your workouts and your key')} onClick={onDelete} />
</div>
</>}
@@ -180,18 +196,20 @@ export default function Health() {
}, [days])
useEffect(() => { if (!isGuest) load() }, [load, isGuest])
// Both of these resolve with the key so the setup sheet can show it the instant it exists — the
// sheet cannot read it off this screen's state (see the note in SetupSheet).
const key = () => api('/api/vitals/key', { method: 'POST' })
.then(r => { setData(d => ({ ...d, key: r.key })); toast(t('Ingest key created')) })
.catch(e => toast(e.message))
.then(r => { setData(d => ({ ...d, key: r.key })); toast(t('Ingest key created')); return r.key })
.catch(e => { toast(e.message); return null })
const rotate = () => confirmSheet({
const rotate = () => new Promise(resolve => confirmSheet({
title: t('Replace the ingest key?'),
message: t('Your iPhone stops syncing until you paste the new key into Health Auto Export. Nothing already stored is lost.'),
confirmText: t('Replace'), danger: true,
onConfirm: () => api('/api/vitals/key/rotate', { method: 'POST' })
.then(r => { setData(d => ({ ...d, key: r.key })); toast(t('New key created')) })
.catch(e => toast(e.message))
})
.then(r => { setData(d => ({ ...d, key: r.key })); toast(t('New key created')); resolve(r.key) })
.catch(e => { toast(e.message); resolve(null) })
}))
const wipe = () => confirmSheet({
title: t('Delete the health data?'),
@@ -202,7 +220,7 @@ export default function Health() {
.catch(e => toast(e.message))
})
const setup = () => openSheet(close => <SetupSheet data={data} onKey={key} onRotate={rotate} onDelete={wipe} 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} />)
/* Guest mode keeps everything in this browser and never talks to a server, so there is nothing
+47
View File
@@ -16,6 +16,7 @@ vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() }))
vi.mock('../sheets.jsx', () => ({ confirmSheet: vi.fn() }))
const { default: Health } = await import('./Health.jsx')
const { default: Modals } = await import('../components/Modals.jsx')
const bucket = v => ({ n: 1, sum: v, min: v, max: v, last: v, avg: v })
const day = (d, f, n = 1) => ({ day: d, n, f })
@@ -110,3 +111,49 @@ describe('Salud', () => {
expect(text()).not.toContain('No health data yet')
})
})
/* The setup sheet is rendered from an element captured when it was opened (useUI.openSheet keeps
the JSX), so anything it reads off the screen's state is frozen at that moment. The first
version keyed the whole "2. The header" block off the screen's `key`, which meant clicking
Create showed the toast and nothing else: the key existed and the sheet still said "Create an
ingest key". This is that regression, and it needs the real Modals host to be visible at all. */
describe('the ingest key', () => {
const mountWithSheets = async () => {
await act(async () => { root.render(<><Health /><Modals /></>) })
await act(async () => {})
}
const byText = needle => [...document.querySelectorAll('button')].find(b => b.textContent.includes(needle))
const click = el => act(() => { el.dispatchEvent(new MouseEvent('click', { bubbles: true })) })
it('appears the moment it is created, ready to copy', async () => {
api.mockImplementation(async path => {
if (path.startsWith('/api/vitals?')) return { ...VITALS, key: null }
if (path === '/api/vitals/key') return { ok: true, key: 'kghealth_NEWKEY123' }
throw new Error('unexpected ' + path)
})
await mountWithSheets()
click(host.querySelector('button[aria-label="Connect Apple Health"]'))
expect(document.body.textContent).toContain('Create an ingest key')
await act(async () => { byText('Create an ingest key').dispatchEvent(new MouseEvent('click', { bubbles: true })) })
await act(async () => {})
// The key itself, in full, with a button that says what it does.
expect(document.body.textContent).toContain('Authorization: Bearer kghealth_NEWKEY123')
expect(byText('Copy the key')).toBeTruthy()
expect(document.body.textContent).not.toContain('Create an ingest key')
// ...and the endpoint, which is the other half of the configuration.
expect(byText('Copy the URL')).toBeTruthy()
})
it('is shown right away when the profile already has one', async () => {
api.mockImplementation(async path => {
if (path.startsWith('/api/vitals?')) return VITALS // key: kghealth_TESTKEY
throw new Error('unexpected ' + path)
})
await mountWithSheets()
click(host.querySelector('button[aria-label="Connect Apple Health"]'))
expect(document.body.textContent).toContain('Authorization: Bearer kghealth_TESTKEY')
})
})