Files
pdtv26/status/status.js
T
dckc f35da9b883
check / check (push) Canceled after 0s
fixup! feat(status): a status page, for the phone of whoever looks after the box
booting: a ready counts unless it's from before the latest outage
the server saw. The box's services restart together, so the button's
ready can come before the next check sees the IR port up; comparing
ready with when the port came up read that as booting, until the next
ready. A server restarted while the box stayed up did the same.

Generated-by: Claude Opus 5.5
2026-12-02 18:23:54 -06:00

176 lines
8.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* @file The agent's status, for a page whoever looks after the box can check from a phone: is it up,
* is it ready, and how many burgers sold (conversations, turns, IR presses, looks).
* Events come from the box (its button and ir services); checks are TCP connects to the box's ir
* capability, the speech server, and the brain's channel. No transcripts here: just counts and times.
* @see status-server.js
*/
/** What the box may report, and what each counts toward. */
export const KINDS = ['ready', 'conversation', 'turn', 'huh', 'interrupt', 'end', 'ir', 'look'];
/** The button service says it's alive this often; three missed and it's not responding. */
export const HEARTBEAT_MS = 60_000;
/** The parts the page checks, in order, with what to say when one is down. */
export const CHECKS = [
{ name: 'box', label: 'the box (its IR port)', down: 'unplugged, booting, or off the network' },
{ name: 'speech', label: 'ears and voice (the speech server)', down: 'the speech server is down: no transcripts, no voice' },
{ name: 'brain', label: 'the brain (its channel)', down: 'the channel is not listening: is it waiting at its prompt?' },
];
/** The button service's events, whatever its name before the source names were pdtv26's. @param {string} source */
const fromButton = (source) => source.endsWith('-button');
/**
* @typedef {{ at: number, kind: string, source: string, reason?: string, code?: string, times?: number }} Event
* @typedef {{ name: string, up: boolean, at: number, since: number, outage?: number }} Check outage: when the latest outage we saw began
* @typedef {{ conversations: number, turns: number, huh: number, interrupts: number, irPresses: number, looks: number }} Tally
* @typedef {{ word: string, since?: number, why?: string }} State
* @typedef {{ state: State, heartbeat?: number, checks: (typeof CHECKS[number] & Partial<Check>)[], today: Tally, total: Tally, recent: Event[] }} Summary
*/
/**
* @param {any} raw an event as the box sent it, stamped with our time
* @returns {Event | undefined} the parts we keep, or undefined if it's not one of ours
*/
export const cleanEvent = (raw) => {
if (!raw || typeof raw !== 'object' || !KINDS.includes(raw.kind)) return undefined;
/** @type {Event} */
const ev = { at: Number(raw.at), kind: raw.kind, source: String(raw.source ?? '').slice(0, 20) };
if (typeof raw.reason === 'string') ev.reason = raw.reason.slice(0, 40);
if (typeof raw.code === 'string' && /^[0-9A-F ]{2,47}$/.test(raw.code)) ev.code = raw.code;
if (Number.isInteger(raw.times) && raw.times > 0 && raw.times <= 20) ev.times = raw.times;
return ev;
};
/** @param {Event[]} evs @returns {Tally} */
const tally = (evs) => {
/** @param {string} kind */
const n = (kind) => evs.filter((e) => e.kind === kind).length;
return {
conversations: n('conversation'),
turns: n('turn'),
huh: n('huh'),
interrupts: n('interrupt'),
irPresses: evs.filter((e) => e.kind === 'ir').reduce((sum, e) => sum + (e.times ?? 1), 0),
looks: n('look'),
};
};
/** Events, checks, and the latest heartbeat; summary(now) says what they add up to. */
export class Status {
#dayOf;
/** @type {Event[]} */
#events = [];
/** @type {Map<string, Check>} */
#checks = new Map();
/** @type {number | undefined} when the button service last said it's alive: kept in memory, not in the event log */
#heartbeat;
/** @param {(t: number) => string} dayOf names the local day t falls on */
constructor(dayOf) {
this.#dayOf = dayOf;
}
/** @param {Event} ev */
record(ev) { this.#events.push(ev); }
/** @param {number} at */
beat(at) { this.#heartbeat = at; }
/** @param {string} name @param {boolean} up @param {number} at */
check(name, up, at) {
const prev = this.#checks.get(name);
const since = prev && prev.up === up ? prev.since : at;
const outage = up ? prev?.outage : since;
this.#checks.set(name, { name, up, at, since, ...(outage === undefined ? {} : { outage }) });
}
size() { return this.#events.length; }
/** The box's state, from its checks and events. @param {number} now @returns {State} */
#state(now) {
const up = this.#checks.get('box');
if (!up) return { word: 'not checked yet' };
if (!up.up) return { word: 'unreachable', since: up.since };
const ready = this.#events.findLast((e) => e.kind === 'ready');
// Services restart together, so ready can come before the check sees the box up again: a ready
// counts unless it's from before the latest outage we saw.
if (!ready || ready.at < (up.outage ?? -Infinity)) return { word: 'booting', since: up.since };
const alive = Math.max(this.#heartbeat ?? 0, this.#events.findLast((e) => fromButton(e.source))?.at ?? 0);
if (now - alive > 3 * HEARTBEAT_MS) return { word: 'not responding', since: alive, why: 'no heartbeat from its button service' };
const last = this.#events.findLast((e) => e.kind === 'conversation' || e.kind === 'end');
if (last?.kind === 'conversation' && now - last.at < 10 * 60_000) return { word: 'in a conversation', since: last.at };
return { word: 'ready for duty', since: ready.at };
}
/** @param {number} now @returns {Summary} */
summary(now) {
const today = this.#dayOf(now);
return {
state: this.#state(now),
heartbeat: this.#heartbeat,
checks: CHECKS.map((c) => ({ ...c, ...this.#checks.get(c.name) })),
today: tally(this.#events.filter((e) => this.#dayOf(e.at) === today)),
total: tally(this.#events),
recent: this.#events.slice(-12).reverse(),
};
}
}
/** @param {unknown} s */
const esc = (s) => String(s).replace(/[&<>"]/g, (c) => /** @type {Record<string, string>} */ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
/**
* The page: phone-sized, no script, refreshes itself.
* @param {Summary} s
* @param {(t: number) => string} clock formats a time for people
* @param {string} name the box's name, for the title
*/
export const render = (s, clock, name) => {
/** @param {number | undefined} t */
const since = (t) => (t ? ` since ${esc(clock(t))}` : '');
// One row per count, so the table stays phone-narrow however many counts there are.
/** @type {[string, keyof Tally][]} */
const COUNTS = [['talks', 'conversations'], ['turns', 'turns'], ['huh?', 'huh'],
['interrupted', 'interrupts'], ['IR presses', 'irPresses'], ['looks', 'looks']];
/** @param {[string, keyof Tally]} count */
const row = ([label, key]) => `<tr><td>${label}</td><td>${s.today[key]}</td><td>${s.total[key]}</td></tr>`;
/** @param {Event} e */
const describe = (e) => [e.kind, e.reason, e.code && `${e.code}${(e.times ?? 1) > 1 ? ` ×${e.times}` : ''}`].filter(Boolean).join(' ');
return `<!doctype html>
<html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="refresh" content="15">
<title>${esc(name)} status</title>
<style>
:root { color-scheme: light dark; --ok: #1a7f37; --bad: #cf222e; --muted: #6e7781; }
body { font: 17px/1.4 system-ui, sans-serif; margin: 0 auto; max-width: 32rem; padding: 1rem; }
h1 { font-size: 1.6rem; margin: 0 0 .25rem; }
.state { font-size: 1.3rem; margin-bottom: 1rem; }
.up { color: var(--ok); } .down { color: var(--bad); } .muted { color: var(--muted); font-size: .9rem; }
table { border-collapse: collapse; width: 100%; margin: .5rem 0 1rem; }
td, th { padding: .25rem .4rem; text-align: right; } td:first-child, th:first-child { text-align: left; }
ul { padding-left: 1.2rem; margin: .25rem 0 1rem; }
</style></head><body>
<h1>${esc(name)}</h1>
<div class="state"><b>${esc(s.state.word)}</b>${since(s.state.since)}${s.state.why ? `<br><span class="muted">${esc(s.state.why)}</span>` : ''}</div>
<ul>
${s.checks.map((c) => c.at === undefined
? `<li class="muted">${esc(c.label)}: not checked yet</li>`
: `<li class="${c.up ? 'up' : 'down'}">${c.up ? '✓' : '✗'} ${esc(c.label)}${since(c.since)}${c.up ? '' : `<br><span class="muted">${esc(c.down)}</span>`}</li>`).join('\n')}
</ul>
<table>
<tr><th></th><th>today</th><th>all time</th></tr>
${COUNTS.map(row).join('\n')}
</table>
<div class="muted">last heartbeat: ${s.heartbeat ? esc(clock(s.heartbeat)) : 'none yet'}</div>
<div class="muted">recent</div>
<ul class="muted">
${s.recent.map((e) => `<li>${esc(clock(e.at))} ${esc(describe(e))}</li>`).join('\n') || '<li>nothing yet</li>'}
</ul>
</body></html>
`;
};