web: dashboard, gaming and health paint glyphs

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Krzysztof Rudnicki 2026-11-11 11:55:42 +01:00
parent 9f52d27893
commit 7e0ae61164
12 changed files with 269 additions and 102 deletions

View File

@ -41,7 +41,8 @@ const show = (over: Record<string, Handler> = {}) => {
mount(PAGE) mount(PAGE)
return mock return mock
} }
const fact = (label: string) => screen.getByText(label, { selector: 'dt' }).nextElementSibling as HTMLElement // A fact's term is a glyph whose label is spoken (sr-only).
const fact = (label: string) => screen.getByText(label, { selector: 'dt .sr-only' }).closest('dt')?.nextElementSibling as HTMLElement
const box = (name: string) => screen.getByRole('region', { name }) const box = (name: string) => screen.getByRole('region', { name })
describe('Dashboard', () => { describe('Dashboard', () => {
@ -101,7 +102,8 @@ describe('Dashboard', () => {
vi.setSystemTime(Date.parse('2026-10-23T11:07:58Z')) vi.setSystemTime(Date.parse('2026-10-23T11:07:58Z'))
expect(fact('Total block')).toHaveTextContent('1h 8m left') expect(fact('Total block')).toHaveTextContent('1h 8m left')
vi.advanceTimersByTime(1000) vi.advanceTimersByTime(1000)
const first = Number(/^(\d)s left$/.exec(fact('Total block').textContent)?.[1]) // Painted ⏳ + number; "left" is spoken (sr-only).
const first = Number(/^(\d)s left$/.exec(fact('Total block').querySelector('.sr-only')?.textContent ?? '')?.[1])
expect([3, 4]).toContain(first) expect([3, 4]).toContain(first)
vi.advanceTimersByTime(1000) vi.advanceTimersByTime(1000)
expect(fact('Total block')).toHaveTextContent(`${first - 1}s left`) expect(fact('Total block')).toHaveTextContent(`${first - 1}s left`)
@ -152,7 +154,7 @@ describe('Dashboard', () => {
it('keeps a failed daemon run on screen with its reason', async () => { it('keeps a failed daemon run on screen with its reason', async () => {
const failed = { ...bg3, phase: 'failed', percent: null, elapsed_seconds: 0, error: 'Refusing to mark it as installed' } const failed = { ...bg3, phase: 'failed', percent: null, elapsed_seconds: 0, error: 'Refusing to mark it as installed' }
show({ 'GET /api/daemon': daemon([failed]) }) show({ 'GET /api/daemon': daemon([failed]) })
expect(await screen.findByText("Fast install of Baldur's Gate 3 failed: Refusing to mark it as installed")).toHaveClass('text-danger') expect((await screen.findByText("Fast install of Baldur's Gate 3 failed: Refusing to mark it as installed")).closest('p')).toHaveClass('text-danger')
expect(screen.getByText("Steam's own download took over.")).toBeInTheDocument() expect(screen.getByText("Steam's own download took over.")).toBeInTheDocument()
expect(screen.queryByRole('progressbar', { name: "Baldur's Gate 3 download" })).not.toBeInTheDocument() expect(screen.queryByRole('progressbar', { name: "Baldur's Gate 3 download" })).not.toBeInTheDocument()
}) })

View File

@ -1,17 +1,26 @@
// Dashboard sections (was screens/Dashboard.tsx): what the enforcer is doing // Dashboard sections (was screens/Dashboard.tsx): what the enforcer is doing
// right now, at a glance. // right now, at a glance. Textgate: glyphs and numbers are painted, every
// sentence is spoken only (sr-only), game names stay visible as content.
import type { FastInstallRun, StatusPayload } from '../api/contract' import type { FastInstallRun, StatusPayload } from '../api/contract'
import { q } from '../api/queries' import { q } from '../api/queries'
import { commandLabel } from '../commands/catalog' import { COMMAND_ICON, commandLabel } from '../commands/catalog'
import '../commands/commandButton' import '../commands/commandButton'
import { fmtDuration, fmtRemaining } from '../format' import { fmtDuration, fmtRemaining } from '../format'
import { progressBar, stateBadge, type BarTone } from '../jobs/progress' import { progressBar, stateBadge, type BarTone } from '../jobs/progress'
import { define, h, hx } from '../lib/dom' import { define, h, hx } from '../lib/dom'
import { LiveElement } from '../lib/element' import { LiveElement } from '../lib/element'
import { jobHref } from '../lib/runner' import { jobHref } from '../lib/runner'
import { card, empty, errorNotice, facts, link, loading } from '../ui/build' import { card, empty, errorNotice, facts, glyph, link, loading } from '../ui/build'
import { ago } from '../ui/format' import { ago } from '../ui/format'
import { said } from './spoken'
/** "5 min ago" painted as 🕓 5 min (the word "ago" spoken only). */
export function since(iso: string | null): HTMLSpanElement {
const spoken = ago(iso)
const short = spoken === 'just now' ? '<1 min' : spoken.replace(/ ago$/, '')
return said(spoken, '🕓 ', short)
}
/** Seconds left on the total block: from `until` when known, else the /** Seconds left on the total block: from `until` when known, else the
* server's `days_remaining` (rounded to 0.1 d). */ * server's `days_remaining` (rounded to 0.1 d). */
@ -29,18 +38,29 @@ export class BlockCountdownElement extends LiveElement {
protected update(): void { protected update(): void {
const block = q.status.state.data?.total_block const block = q.status.state.data?.total_block
this.replaceChildren(...(block ? [h('span', { class: 'text-danger' }, `${fmtRemaining(blockSecondsLeft(block))} left`)] : [])) if (!block) {
this.replaceChildren()
return
}
const left = fmtRemaining(blockSecondsLeft(block))
this.replaceChildren(h('span', { class: 'text-danger' }, said(`${left} left`, '⏳ ', left)))
} }
} }
function statusFacts(s: StatusPayload): HTMLDListElement { function statusFacts(s: StatusPayload): HTMLDListElement {
return facts([ return facts([
['Installed', s.assigned_game_installed ? 'Yes' : h('span', { class: 'text-warning' }, 'No — install it from Library')], [
['Games finished', s.finished_count], glyph('💾', 'Installed'),
['Store', s.store_blocked ? 'Blocked' : h('span', { class: 'text-warning' }, 'Unblocked')], s.assigned_game_installed ? glyph('✅', 'Yes') : h('span', { class: 'text-warning' }, glyph('⚠️', 'No — install it from Library')),
['Installed games', s.installed_count], ],
['Total block', s.total_block.active ? hx('block-countdown') : 'Off'], [glyph('🏆', 'Games finished'), s.finished_count],
['Manual picks', s.manual_picks.length ? s.manual_picks.map((p) => `${p.name} (${p.age_days} d)`).join(', ') : 'None'], [glyph('🛒', 'Store'), s.store_blocked ? glyph('🔒', 'Blocked') : h('span', { class: 'text-warning' }, glyph('🔓', 'Unblocked'))],
[glyph('🗂️', 'Installed games'), s.installed_count],
[glyph('⛔', 'Total block'), s.total_block.active ? hx('block-countdown') : glyph('➖', 'Off')],
[
glyph('📌', 'Manual picks'),
s.manual_picks.length ? s.manual_picks.map((p) => `${p.name} (${p.age_days} d)`).join(', ') : glyph('➖', 'None'),
],
]) ])
} }
@ -51,13 +71,16 @@ export class DashboardStatusElement extends LiveElement {
protected update(): void { protected update(): void {
const { data, error } = q.status.state const { data, error } = q.status.state
const icon = '🎯'
if (error) { if (error) {
this.replaceChildren(card('Assignment', errorNotice(error))) this.replaceChildren(card('Assignment', errorNotice(error), { icon }))
} else if (!data) { } else if (!data) {
this.replaceChildren(card('Assignment', loading('status'))) this.replaceChildren(card('Assignment', loading('status'), { icon }))
} else { } else {
const game = data.current_game_name ?? glyph('📭', 'Nothing assigned')
this.replaceChildren( this.replaceChildren(
card('Assignment', [h('p', { class: 'hero-game' }, data.current_game_name ?? 'Nothing assigned'), statusFacts(data)], { card('Assignment', [h('p', { class: 'hero-game' }, game), statusFacts(data)], {
icon,
// Its own element, so it follows the command catalog by itself. // Its own element, so it follows the command catalog by itself.
aside: hx('command-button', { name: 'check', label: 'Check now' }), aside: hx('command-button', { name: 'check', label: 'Check now' }),
}), }),
@ -71,6 +94,12 @@ function budgetTone(blocked: boolean, used: number): BarTone {
return used > 0.8 ? 'warning' : 'accent' return used > 0.8 ? 'warning' : 'accent'
} }
function billingLine(blocked: boolean, label: string): HTMLParagraphElement {
if (blocked) return h('p', { class: 'field-help' }, glyph('⛔', 'Blocked for today.'))
if (!label) return h('p', { class: 'field-help' }, said('Now: nothing billing', '⏸️'))
return h('p', { class: 'field-help' }, said(`Now: ${label}`, '▶️ ', label))
}
export class BudgetGlanceElement extends LiveElement { export class BudgetGlanceElement extends LiveElement {
protected override setup(): void { protected override setup(): void {
this.watch(q.budget) this.watch(q.budget)
@ -78,12 +107,13 @@ export class BudgetGlanceElement extends LiveElement {
protected update(): void { protected update(): void {
const { data, error } = q.budget.state const { data, error } = q.budget.state
const icon = '⏱️'
if (error) { if (error) {
this.replaceChildren(card('Gaming today', errorNotice(error))) this.replaceChildren(card('Gaming today', errorNotice(error), { icon }))
return return
} }
if (!data) { if (!data) {
this.replaceChildren(card('Gaming today', loading('budget'))) this.replaceChildren(card('Gaming today', loading('budget'), { icon }))
return return
} }
const t = data.today const t = data.today
@ -93,37 +123,35 @@ export class BudgetGlanceElement extends LiveElement {
'p', 'p',
{ class: 'hero-num' }, { class: 'hero-num' },
`${fmtDuration(t.seconds_remaining)} `, `${fmtDuration(t.seconds_remaining)} `,
h('span', { class: 'muted' }, `left of ${fmtDuration(t.budget_seconds)}`), h('span', { class: 'muted' }, said(`left of ${fmtDuration(t.budget_seconds)}`, `/ ${fmtDuration(t.budget_seconds)}`)),
), ),
progressBar(t.fraction_used, 'Budget used', budgetTone(t.blocked, t.fraction_used)), progressBar(t.fraction_used, 'Budget used', budgetTone(t.blocked, t.fraction_used)),
h('p', { class: 'field-help' }, t.blocked ? 'Blocked for today.' : `Now: ${data.session.billing_label || 'nothing billing'}`), billingLine(t.blocked, data.session.billing_label),
] ]
: h('p', { class: 'text-danger' }, data.error ?? 'Budget state unavailable.') : h('p', { class: 'text-danger' }, data.error ?? glyph('⚠️', 'Budget state unavailable.'))
this.replaceChildren(card('Gaming today', body, { aside: link('/gaming/', 'Details') })) this.replaceChildren(card('Gaming today', body, { icon, aside: link('/gaming/', glyph('➡️', 'Details')) }))
} }
} }
function fastInstallLine(r: FastInstallRun): string {
const where = r.percent === null ? r.phase : `${Math.floor(r.percent)}% (${r.phase})`
return `Fast-installing ${r.name} — ${where}`
}
function fastInstallRow(r: FastInstallRun): HTMLDivElement { function fastInstallRow(r: FastInstallRun): HTMLDivElement {
if (r.error) { if (r.error) {
// The daemon has no job to report to: a failure stays here until Steam finishes. // The daemon has no job to report to: a failure stays here until Steam finishes.
// The error is the daemon's own message (content), the framing is spoken.
return h( return h(
'div', 'div',
{}, {},
h('p', { class: 'text-danger' }, `Fast install of ${r.name} failed: ${r.error}`), h('p', { class: 'text-danger' }, said(`Fast install of ${r.name} failed: ${r.error}`, '⛔ ', r.name, ': ', r.error)),
h('p', { class: 'field-help' }, "Steam's own download took over."), h('p', { class: 'field-help' }, glyph('↪️', "Steam's own download took over.")),
) )
} }
const pct = r.percent === null ? null : Math.floor(r.percent)
const where = pct === null ? r.phase : `${pct}% (${r.phase})`
return h( return h(
'div', 'div',
{}, {},
h('p', {}, fastInstallLine(r)), h('p', {}, said(`Fast-installing ${r.name} — ${where}`, '⚡ ', r.name, pct === null ? '' : ` ${pct}%`)),
progressBar(r.percent === null ? null : Math.floor(r.percent) / 100, `${r.name} download`), progressBar(pct === null ? null : pct / 100, `${r.name} download`),
h('p', { class: 'field-help' }, `${fmtDuration(r.elapsed_seconds)} elapsed`), h('p', { class: 'field-help' }, said(`${fmtDuration(r.elapsed_seconds)} elapsed`, '⏳ ', fmtDuration(r.elapsed_seconds))),
) )
} }
@ -135,7 +163,7 @@ export class FastInstallsElement extends LiveElement {
protected update(): void { protected update(): void {
const runs = q.daemon.state.data?.fast_installs ?? [] const runs = q.daemon.state.data?.fast_installs ?? []
this.replaceChildren(...(runs.length ? [card('Fast install', runs.map(fastInstallRow))] : [])) this.replaceChildren(...(runs.length ? [card('Fast install', runs.map(fastInstallRow), { icon: '⚡' })] : []))
} }
} }
@ -162,16 +190,18 @@ export class RecentJobsElement extends LiveElement {
h( h(
'a', 'a',
{ href: jobHref(j.id), class: 'row-link' }, { href: jobHref(j.id), class: 'row-link' },
h('span', {}, commandLabel(j.command)), glyph(COMMAND_ICON[j.command], commandLabel(j.command)),
h('span', { class: 'muted grow ellipsis' }, j.summary ?? j.progress?.label ?? ''), // The job's summary is a server sentence: spoken here, shown in the job view.
h('span', { class: 'muted' }, ago(j.created_at)), h('span', { class: 'sr-only' }, j.summary ?? j.progress?.label ?? ''),
h('span', { class: 'grow' }),
h('span', { class: 'muted' }, since(j.created_at)),
stateBadge(j.state), stateBadge(j.state),
), ),
), ),
), ),
), ),
], ],
{ aside: link('/jobs/', 'All jobs') }, { icon: '⚙️', aside: link('/jobs/', glyph('➡️', 'All jobs')) },
), ),
) )
} }

View File

@ -74,7 +74,7 @@ describe('todayUnavailable', () => {
describe('liveCard', () => { describe('liveCard', () => {
it('reports an engaged session with its game', () => { it('reports an engaged session with its game', () => {
show(liveCard(makeBudgetSession())) show(liveCard(makeBudgetSession()))
expect(screen.getByText(/Billing — you are playing/)).toHaveClass('budget-verdict--engaged') expect(screen.getByText(/Billing — you are playing/).closest('.budget-verdict')).toHaveClass('budget-verdict--engaged')
expect(screen.getByText(/Assigned game/)).toBeInTheDocument() expect(screen.getByText(/Assigned game/)).toBeInTheDocument()
// Engaged, so the credited game is described in the present tense. // Engaged, so the credited game is described in the present tense.
expect(screen.getByText(/Billing to/)).toBeInTheDocument() expect(screen.getByText(/Billing to/)).toBeInTheDocument()

View File

@ -1,11 +1,15 @@
// The four budget panel sections (were BudgetTodayCard, BudgetLiveCard, // The four budget panel sections (were BudgetTodayCard, BudgetLiveCard,
// BudgetHistoryChart and BudgetRulesCard.tsx) as pure DOM builders. // BudgetHistoryChart and BudgetRulesCard.tsx) as pure DOM builders.
// Textgate: glyphs, numbers and game names are painted; every sentence and
// label is spoken only (`said`/`glyph`), and the meter/verdict colours stay.
import { seriesClass } from '../../budgetSeries' import { OTHER_KEY, UNATTRIBUTED_KEY, seriesClass } from '../../budgetSeries'
import { fmtAgo, fmtDuration } from '../../format' import { fmtAgo, fmtDuration } from '../../format'
import { budgetHistorySvg } from '../../lib/charts/budgetHistory' import { budgetHistorySvg } from '../../lib/charts/budgetHistory'
import { h } from '../../lib/dom' import { h } from '../../lib/dom'
import type { BudgetHistoryDay, BudgetLegendEntry, BudgetRules, BudgetSession, BudgetToday } from '../../types' import type { BudgetHistoryDay, BudgetLegendEntry, BudgetRules, BudgetSession, BudgetToday } from '../../types'
import { glyph } from '../../ui/build'
import { said } from '../spoken'
/** Which colour the meter takes: normal, into the warning band, or spent. /** Which colour the meter takes: normal, into the warning band, or spent.
* *
@ -19,7 +23,22 @@ function meterState(today: BudgetToday): string {
return today.warned_seconds.length > 0 ? 'warn' : 'ok' return today.warned_seconds.length > 0 ? 'warn' : 'ok'
} }
function warningLine(today: BudgetToday, maskedCount: number): HTMLElement | string { /** A series name: game names are content; the sentinels and the "(launcher)" tag are glyphs. */
export function seriesLabel(key: string, label: string): HTMLElement {
if (key === OTHER_KEY) return glyph('➕', label)
if (key === UNATTRIBUTED_KEY) return glyph('❔', label)
if (key.startsWith('launcher:')) return said(label, '🚀 ', label.replace(/\s*\(launcher\)$/, ''))
return h('span', {}, label)
}
/** "5m ago" painted as 🕓 5m. */
function asOf(iso: string): HTMLElement {
const ago = fmtAgo(iso)
const short = ago === 'unknown' ? '?' : ago === 'just now' ? '<10s' : ago.replace(/ ago$/, '')
return said(`as of ${ago}`, '🕓 ', short)
}
function warningLine(today: BudgetToday, maskedCount: number): HTMLElement {
if (today.blocked) { if (today.blocked) {
// Read the live mount count rather than inferring it from `blocked`: the // Read the live mount count rather than inferring it from `blocked`: the
// total-block branch releases every mount while leaving `blocked_at` set, // total-block branch releases every mount while leaving `blocked_at` set,
@ -28,12 +47,23 @@ function warningLine(today: BudgetToday, maskedCount: number): HTMLElement | str
return h( return h(
'span', 'span',
{ class: 'budget-badge budget-badge--blocked' }, { class: 'budget-badge budget-badge--blocked' },
maskedCount > 0 ? 'Cutoff engaged — launchers are masked' : 'Cutoff engaged — launchers are not currently masked', maskedCount > 0
? glyph('⛔🔒', 'Cutoff engaged — launchers are masked')
: glyph('⛔🔓', 'Cutoff engaged — launchers are not currently masked'),
) )
} }
return today.next_warning_seconds === null const next = today.next_warning_seconds
? 'No further warnings today.' return next === null
: `Next warning at ${fmtDuration(today.next_warning_seconds)} remaining.` ? glyph('🔕', 'No further warnings today.')
: said(`Next warning at ${fmtDuration(next)} remaining.`, '🔔 ', fmtDuration(next))
}
function usageLine(t: BudgetToday): HTMLElement {
const used = `${fmtDuration(t.seconds_used)} / ${fmtDuration(t.budget_seconds)} · ${Math.round(t.fraction_used * 100)}%`
const spoken =
`${fmtDuration(t.seconds_used)} of ${fmtDuration(t.budget_seconds)} used · ` +
`${Math.round(t.fraction_used * 100)}% · gaming day ${t.gaming_day} (starts ${t.day_starts_at})`
return said(spoken, used, ' · 📅 ', t.gaming_day, ' · 🌅 ', t.day_starts_at.replace(/\s*local$/, ''))
} }
export function todayCard(today: BudgetToday, legend: readonly BudgetLegendEntry[], maskedCount: number): HTMLElement { export function todayCard(today: BudgetToday, legend: readonly BudgetLegendEntry[], maskedCount: number): HTMLElement {
@ -46,19 +76,14 @@ export function todayCard(today: BudgetToday, legend: readonly BudgetLegendEntry
return h( return h(
'section', 'section',
{ class: 'budget-today' }, { class: 'budget-today' },
h('h2', {}, 'Today'), h('h2', {}, glyph('📅', 'Today')),
h('p', { class: 'budget-hero' }, h('strong', {}, fmtDuration(today.seconds_remaining)), ' left'), h('p', { class: 'budget-hero' }, h('strong', {}, fmtDuration(today.seconds_remaining)), h('span', { class: 'sr-only' }, ' left')),
h('div', { class: `budget-meter budget-meter--${meterState(today)}` }, fill), h('div', { class: `budget-meter budget-meter--${meterState(today)}` }, fill),
h( h('p', { class: 'hint' }, usageLine(today)),
'p',
{ class: 'hint' },
`${fmtDuration(today.seconds_used)} of ${fmtDuration(today.budget_seconds)} used · ` +
`${Math.round(today.fraction_used * 100)}% · gaming day ${today.gaming_day} (starts ${today.day_starts_at})`,
),
h('p', { class: 'hint' }, warningLine(today, maskedCount)), h('p', { class: 'hint' }, warningLine(today, maskedCount)),
today.games.length > 0 today.games.length > 0
? [ ? [
h('h3', { class: 'budget-subhead' }, 'Today by game'), h('h3', { class: 'budget-subhead' }, glyph('🎮', 'Today by game')),
h( h(
'ul', 'ul',
{ class: 'budget-games' }, { class: 'budget-games' },
@ -67,7 +92,7 @@ export function todayCard(today: BudgetToday, legend: readonly BudgetLegendEntry
'li', 'li',
{}, {},
h('span', { class: `swatch ${seriesClass(game.key, indexFor.get(game.key) ?? i)}`, 'aria-hidden': 'true' }), h('span', { class: `swatch ${seriesClass(game.key, indexFor.get(game.key) ?? i)}`, 'aria-hidden': 'true' }),
h('span', { class: 'budget-game-name' }, game.label), h('span', { class: 'budget-game-name' }, seriesLabel(game.key, game.label)),
h('span', { class: 'budget-game-time' }, fmtDuration(game.seconds)), h('span', { class: 'budget-game-time' }, fmtDuration(game.seconds)),
h('span', { class: 'budget-game-share' }, `${Math.round(game.fraction * 100)}%`), h('span', { class: 'budget-game-share' }, `${Math.round(game.fraction * 100)}%`),
), ),
@ -80,34 +105,37 @@ export function todayCard(today: BudgetToday, legend: readonly BudgetLegendEntry
/** Shown in place of `todayCard` when the state file cannot be read. */ /** Shown in place of `todayCard` when the state file cannot be read. */
export function todayUnavailable(error: string | null): HTMLElement { export function todayUnavailable(error: string | null): HTMLElement {
return h('section', { class: 'budget-today' }, h('h2', {}, 'Today'), h('p', { class: 'error' }, error ?? 'Budget state unavailable.')) return h(
'section',
{ class: 'budget-today' },
h('h2', {}, glyph('📅', 'Today')),
// The server's own error is shown as is; the fallback is a glyph.
h('p', { class: 'error' }, error ?? glyph('⚠️', 'Budget state unavailable.')),
)
} }
const VERDICT_LABELS = new Map([ const VERDICT = new Map([
['engaged', 'Billing — you are playing'], ['engaged', ['▶️', 'Billing — you are playing']],
['not_applicable', 'Not billing — no game running'], ['not_applicable', ['⏸️', 'Not billing — no game running']],
]) ])
export function liveCard(session: BudgetSession): HTMLElement { export function liveCard(session: BudgetSession): HTMLElement {
const title = h('h2', {}, 'Right now') const title = h('h2', {}, glyph('📡', 'Right now'))
if (!session.available) { if (!session.available) {
return h('section', { class: 'budget-live' }, title, h('p', { class: 'hint' }, 'No verdict has been logged yet.')) return h('section', { class: 'budget-live' }, title, h('p', { class: 'hint' }, glyph('📭', 'No verdict has been logged yet.')))
} }
const [icon, verdict] = VERDICT.get(session.state) ?? ['❔', session.state]
return h( return h(
'section', 'section',
{ class: 'budget-live' }, { class: 'budget-live' },
title, title,
h( h('p', {}, h('span', { class: `budget-verdict budget-verdict--${session.state}` }, glyph(icon, verdict))),
'p',
{},
h('span', { class: `budget-verdict budget-verdict--${session.state}` }, VERDICT_LABELS.get(session.state) ?? session.state),
),
session.qualifying_count > 0 session.qualifying_count > 0
? h( ? h(
'p', 'p',
{ class: 'hint' }, { class: 'hint' },
session.game_name ? ['Assigned game ', h('strong', {}, session.game_name), ' · '] : null, session.game_name ? [said('Assigned game ', '🎯 '), h('strong', {}, session.game_name), ' · '] : null,
`${session.qualifying_count} qualifying processes`, said(`${session.qualifying_count} qualifying processes`, '⚙️ ', session.qualifying_count),
) )
: null, : null,
// The assignment above is what the enforcer told you to play; this is // The assignment above is what the enforcer told you to play; this is
@ -118,24 +146,24 @@ export function liveCard(session: BudgetSession): HTMLElement {
? h( ? h(
'p', 'p',
{ class: 'hint' }, { class: 'hint' },
session.state === 'engaged' ? 'Billing to ' : 'Last billed to ', session.state === 'engaged' ? said('Billing to ', '💸 ') : said('Last billed to ', '⏮️💸 '),
h('strong', {}, session.billing_label), h('strong', {}, session.billing_label),
) )
: null, : null,
// The daemon logs on change or a 5-minute heartbeat, so this reading can // The daemon logs on change or a 5-minute heartbeat, so this reading can
// legitimately be minutes old. Saying so beats implying "now". // legitimately be minutes old. Saying so beats implying "now".
h('p', { class: 'hint' }, `as of ${fmtAgo(session.observed_at)}`), h('p', { class: 'hint' }, asOf(session.observed_at)),
) )
} }
export function historyCard(days: readonly BudgetHistoryDay[], legend: readonly BudgetLegendEntry[], budgetSeconds: number): HTMLElement { export function historyCard(days: readonly BudgetHistoryDay[], legend: readonly BudgetLegendEntry[], budgetSeconds: number): HTMLElement {
const title = h('h2', {}, 'Last 14 days') const title = h('h2', {}, glyph('📊', 'Last 14 days'))
if (days.length === 0) { if (days.length === 0) {
return h( return h(
'div', 'div',
{ class: 'chart' }, { class: 'chart' },
title, title,
h('p', { class: 'hint' }, 'No budget history recorded yet — a bar appears for each gaming day from now on.'), h('p', { class: 'hint' }, glyph('📭', 'No budget history recorded yet — a bar appears for each gaming day from now on.')),
) )
} }
// A <template> parses the markup as HTML, which puts <svg> in the SVG namespace. // A <template> parses the markup as HTML, which puts <svg> in the SVG namespace.
@ -149,33 +177,36 @@ export function historyCard(days: readonly BudgetHistoryDay[], legend: readonly
h( h(
'ul', 'ul',
{ class: 'chart-legend' }, { class: 'chart-legend' },
legend.map((entry, i) => h('li', {}, h('span', { class: `swatch ${seriesClass(entry.key, i)}`, 'aria-hidden': 'true' }), entry.label)), legend.map((entry, i) =>
h('li', {}, h('span', { class: `swatch ${seriesClass(entry.key, i)}`, 'aria-hidden': 'true' }), seriesLabel(entry.key, entry.label)),
),
), ),
h( h(
'p', 'p',
{ class: 'hint' }, { class: 'sr-only' },
"Billed gaming time per day, split by game. The dashed line is the daily budget; today's bar can still move.", "Billed gaming time per day, split by game. The dashed line is the daily budget; today's bar can still move.",
), ),
) )
} }
const onOff = (value: boolean): string => (value ? 'on' : 'off') const onOff = (value: boolean, on: string, off: string) => (value ? glyph('✅', on) : glyph('➖', off))
export function rulesCard(rules: BudgetRules): HTMLElement { export function rulesCard(rules: BudgetRules): HTMLElement {
const row = (term: string, value: string) => [h('dt', {}, term), h('dd', {}, value)] const row = (icon: string, term: string, value: Node | string) => [h('dt', {}, glyph(icon, term)), h('dd', {}, value)]
const warn = rules.warn_at.map((s) => fmtDuration(s)).join(', ')
return h( return h(
'section', 'section',
{ class: 'budget-rules' }, { class: 'budget-rules' },
h('h2', {}, 'Rules in effect'), h('h2', {}, glyph('📏', 'Rules in effect')),
h( h(
'dl', 'dl',
{ class: 'budget-rules-list' }, { class: 'budget-rules-list' },
row('Daily budget', fmtDuration(rules.budget_seconds)), row('⏱️', 'Daily budget', fmtDuration(rules.budget_seconds)),
row('Enforcement', onOff(rules.enforcement)), row('🛡️', 'Enforcement', onOff(rules.enforcement, 'on', 'off')),
row('Counts launchers', rules.counts_launchers ? 'yes' : 'no'), row('🚀', 'Counts launchers', onOff(rules.counts_launchers, 'yes', 'no')),
row('Warnings at', `${rules.warn_at.map((s) => fmtDuration(s)).join(', ')} remaining`), row('🔔', 'Warnings at', said(`${warn} remaining`, warn)),
rules.demo ? row('Mode', 'demo (short budget, separate state)') : null, rules.demo ? row('🧪', 'Mode', glyph('🧪', 'demo (short budget, separate state)')) : null,
rules.masked_launchers.length > 0 ? row('Masked now', rules.masked_launchers.join(', ')) : null, rules.masked_launchers.length > 0 ? row('🔒', 'Masked now', rules.masked_launchers.join(', ')) : null,
), ),
) )
} }

View File

@ -41,7 +41,7 @@ describe('<budget-panel>', () => {
it('shows a loading line before the first response', () => { it('shows a loading line before the first response', () => {
stubApi({ 'GET /api/budget': () => new Promise(() => undefined) }) stubApi({ 'GET /api/budget': () => new Promise(() => undefined) })
mount('<budget-panel></budget-panel>') mount('<budget-panel></budget-panel>')
expect(screen.getByText(/Reading budget state/)).toBeInTheDocument() expect(screen.getByText(/Loading budget state/)).toBeInTheDocument()
}) })
it('reads the production budget and renders all four sections', async () => { it('reads the production budget and renders all four sections', async () => {
@ -66,7 +66,7 @@ describe('<budget-panel>', () => {
it('surfaces a transport failure', async () => { it('surfaces a transport failure', async () => {
stubApi({ 'GET /api/budget': () => Promise.reject(new Error('API returned 500 Server Error')) }) stubApi({ 'GET /api/budget': () => Promise.reject(new Error('API returned 500 Server Error')) })
mount('<budget-panel></budget-panel>') mount('<budget-panel></budget-panel>')
expect(await screen.findByText('Could not read budget state: API returned 500 Server Error')).toHaveClass('error') expect((await screen.findByText('Could not read budget state: API returned 500 Server Error')).closest('p')).toHaveClass('error')
expect(screen.getByText('./run.sh serve')).toBeInTheDocument() expect(screen.getByText('./run.sh serve')).toBeInTheDocument()
}) })
@ -145,6 +145,6 @@ describe('<budget-panel>', () => {
resolve(makeBudget()) resolve(makeBudget())
await flush(10) await flush(10)
expect(el.querySelector('.budget')).toBeNull() expect(el.querySelector('.budget')).toBeNull()
expect(el).toHaveTextContent('Reading budget state…') expect(el).toHaveTextContent('Loading budget state')
}) })
}) })

View File

@ -7,6 +7,8 @@ import { explain } from '../../api/errors'
import { q } from '../../api/queries' import { q } from '../../api/queries'
import { define, h } from '../../lib/dom' import { define, h } from '../../lib/dom'
import { LiveElement } from '../../lib/element' import { LiveElement } from '../../lib/element'
import { commandLine, glyph, loading } from '../../ui/build'
import { said } from '../spoken'
import { historyCard, liveCard, rulesCard, todayCard, todayUnavailable } from './cards' import { historyCard, liveCard, rulesCard, todayCard, todayUnavailable } from './cards'
/** True on `/gaming/?demo=1` (and the legacy `?demo=true`). */ /** True on `/gaming/?demo=1` (and the legacy `?demo=true`). */
@ -19,8 +21,13 @@ export function isDemo(search: string = location.search): boolean {
export class BudgetModeLinkElement extends LiveElement { export class BudgetModeLinkElement extends LiveElement {
protected update(): void { protected update(): void {
const demo = isDemo() const demo = isDemo()
// 🧪 switches to the demo budget, 🏭 back to production; the words are spoken.
this.replaceChildren( this.replaceChildren(
h('a', { href: demo ? '/gaming/' : '/gaming/?demo=1', class: 'btn btn-ghost' }, demo ? 'Show production budget' : 'Show demo budget'), h(
'a',
{ href: demo ? '/gaming/' : '/gaming/?demo=1', class: 'btn btn-ghost' },
demo ? glyph('🏭', 'Show production budget') : glyph('🧪', 'Show demo budget'),
),
) )
} }
} }
@ -41,14 +48,17 @@ export class BudgetPanelElement extends LiveElement {
h( h(
'div', 'div',
{ class: 'status' }, { class: 'status' },
h('p', { class: 'error' }, `Could not read budget state: ${explain(error).detail}`), // The server's own detail is painted; the framing is spoken. The
h('p', { class: 'hint' }, 'Is the backend running? Start it with ', h('code', {}, './run.sh serve'), '.'), // command is the recovery path, so it stays with a copy button.
h('p', { class: 'error' }, said(`Could not read budget state: ${explain(error).detail}`, '⛔ ', explain(error).detail)),
h('p', { class: 'hint' }, h('span', { class: 'sr-only' }, 'Is the backend running? Start it with')),
commandLine('./run.sh serve'),
), ),
) )
return return
} }
if (!data) { if (!data) {
this.replaceChildren(h('div', { class: 'status' }, h('p', { class: 'hint' }, 'Reading budget state…'))) this.replaceChildren(h('div', { class: 'status' }, loading('budget state')))
return return
} }
this.replaceChildren( this.replaceChildren(

View File

@ -8,7 +8,7 @@ import { applyFilters } from '../estimate'
import { timelineChart } from '../lib/charts/timeline' import { timelineChart } from '../lib/charts/timeline'
import { define, h } from '../lib/dom' import { define, h } from '../lib/dom'
import { LiveElement } from '../lib/element' import { LiveElement } from '../lib/element'
import { card, errorNotice, link, loading } from '../ui/build' import { card, errorNotice, glyph, link, loading } from '../ui/build'
import { defaultFilters } from './backlog/plannerFilters' import { defaultFilters } from './backlog/plannerFilters'
import { summaryCards } from './backlog/summary' import { summaryCards } from './backlog/summary'
@ -19,9 +19,10 @@ export class BacklogOverviewElement extends LiveElement {
protected update(): void { protected update(): void {
const { data, error } = q.dataset.state const { data, error } = q.dataset.state
const aside = link('/backlog/', 'Open the planner') const aside = link('/backlog/', glyph('➡️', 'Open the planner'))
const icon = '📚'
if (!data) { if (!data) {
this.replaceChildren(card('Backlog outlook', error ? errorNotice(error) : loading('backlog'), { aside })) this.replaceChildren(card('Backlog outlook', error ? errorNotice(error) : loading('backlog'), { aside, icon }))
return return
} }
const filters = defaultFilters(data.defaults) const filters = defaultFilters(data.defaults)
@ -43,7 +44,7 @@ export class BacklogOverviewElement extends LiveElement {
}), }),
timelineChart(result, filters, data.state), timelineChart(result, filters, data.state),
), ),
{ aside }, { aside, icon },
), ),
) )
} }

View File

@ -0,0 +1,8 @@
// Textgate helper: paint glyphs, numbers and names; speak the sentence.
import { h, type Child } from '../lib/dom'
/** `painted` is shown (glyphs, numbers, names); `spoken` is the sentence a screen reader hears. */
export function said(spoken: string, ...painted: Child[]): HTMLSpanElement {
return h('span', {}, h('span', { 'aria-hidden': 'true' }, ...painted), h('span', { class: 'sr-only' }, spoken))
}

View File

@ -6,7 +6,7 @@ import './health'
const server = (over = {}) => ({ stale: false, started_at: '2026-10-10T10:00:00Z', version: '1.2.3', ...over }) const server = (over = {}) => ({ stale: false, started_at: '2026-10-10T10:00:00Z', version: '1.2.3', ...over })
const daemon = (state: string) => ({ state, started_at: null, pid: null, journal_tail: [], restart_available_at: null }) const daemon = (state: string) => ({ state, started_at: null, pid: null, journal_tail: [], restart_available_at: null })
const pill = (el: Element, text: string) => [...el.querySelectorAll('.pill')].find((p) => p.textContent === text) const pill = (el: Element, text: string) => [...el.querySelectorAll('.pill')].find((p) => p.getAttribute('data-state') === text)
const never = () => new Promise(() => undefined) const never = () => new Promise(() => undefined)
describe('<health-badges>', () => { describe('<health-badges>', () => {
@ -16,13 +16,17 @@ describe('<health-badges>', () => {
expect(pill(el, 'Server ok')).toHaveClass('pill-success') expect(pill(el, 'Server ok')).toHaveClass('pill-success')
expect(pill(el, 'Daemon …')).toHaveClass('pill-neutral') expect(pill(el, 'Daemon …')).toHaveClass('pill-neutral')
expect(pill(el, 'Server ok')).not.toHaveAttribute('title') expect(pill(el, 'Server ok')).not.toHaveAttribute('title')
expect(pill(el, 'Server ok')?.querySelector('[aria-hidden]')).toHaveTextContent('🌐✅')
expect(pill(el, 'Daemon …')?.querySelector('[aria-hidden]')).toHaveTextContent('🛡️…')
}) })
it('shows a healthy server with its version, and a running daemon', async () => { it('shows a healthy server with its version, and a running daemon', async () => {
stubApi({ 'GET /api/server': server(), 'GET /api/daemon': daemon('running') }) stubApi({ 'GET /api/server': server(), 'GET /api/daemon': daemon('running') })
const el = mount('<health-badges></health-badges>') const el = mount('<health-badges></health-badges>')
await vi.waitFor(() => { expect(pill(el, 'Daemon running')).toHaveClass('pill-success') }) await vi.waitFor(() => { expect(pill(el, 'Daemon running')).toHaveClass('pill-success') })
expect(pill(el, 'Server ok')).toHaveAttribute('title', 'v1.2.3') // The version is spoken, never a tooltip (textgate).
expect(pill(el, 'Server ok')).not.toHaveAttribute('title')
expect(pill(el, 'Server ok')?.querySelector('.sr-only')).toHaveTextContent('Server ok v1.2.3')
}) })
it('flags a stale server and a restarting daemon', async () => { it('flags a stale server and a restarting daemon', async () => {

View File

@ -4,10 +4,21 @@
import { q } from '../api/queries' import { q } from '../api/queries'
import { define, h } from '../lib/dom' import { define, h } from '../lib/dom'
import { LiveElement } from '../lib/element' import { LiveElement } from '../lib/element'
import { errorNotice } from '../ui/build' import { errorNotice, glyph } from '../ui/build'
import { ServerRestart } from './serverRestart' import { ServerRestart } from './serverRestart'
const DAEMON_TONE = { running: 'success', restarting: 'warning', unreachable: 'danger' } as const const DAEMON_TONE = { running: 'success', restarting: 'warning', unreachable: 'danger' } as const
const STATE_GLYPH: Record<string, string> = { success: '✅', warning: '⚠️', danger: '⛔', neutral: '…' }
/** A health pill: glyphs painted, `text` (+ `extra`) spoken. `data-state` holds the words for tests. */
function badge(tone: string, icons: string, text: string, extra = ''): HTMLSpanElement {
return h(
'span',
{ class: `pill pill-${tone}`, 'data-state': text },
h('span', { 'aria-hidden': 'true' }, icons),
h('span', { class: 'sr-only' }, text + extra),
)
}
export class HealthBadgesElement extends LiveElement { export class HealthBadgesElement extends LiveElement {
protected override setup(): void { protected override setup(): void {
@ -20,12 +31,15 @@ export class HealthBadgesElement extends LiveElement {
const d = q.daemon.state.data?.state const d = q.daemon.state.data?.state
const serverTone = server.error ? 'danger' : server.data?.stale ? 'warning' : 'success' const serverTone = server.error ? 'danger' : server.data?.stale ? 'warning' : 'success'
const serverText = server.error ? 'Server down' : server.data?.stale ? 'Server stale' : 'Server ok' const serverText = server.error ? 'Server down' : server.data?.stale ? 'Server stale' : 'Server ok'
// Textgate: 🌐 server / 🛡️ daemon + a state glyph, on the tone colour; the
// words (and the version, formerly a tooltip) are spoken only.
const version = server.data ? ` v${server.data.version}` : ''
this.replaceChildren( this.replaceChildren(
h( h(
'div', 'div',
{ class: 'health', 'aria-label': 'Health' }, { class: 'health', 'aria-label': 'Health' },
h('span', { class: `pill pill-${serverTone}`, title: server.data ? `v${server.data.version}` : null }, serverText), badge(serverTone, `🌐${STATE_GLYPH[serverTone]}`, serverText, version),
h('span', { class: `pill pill-${d ? DAEMON_TONE[d] : 'neutral'}` }, `Daemon ${d ?? '…'}`), badge(d ? DAEMON_TONE[d] : 'neutral', `🛡️${STATE_GLYPH[d ? DAEMON_TONE[d] : 'neutral']}`, `Daemon ${d ?? '…'}`),
), ),
) )
} }
@ -53,7 +67,7 @@ export class StaleBannerElement extends LiveElement {
h( h(
'div', 'div',
{ class: 'banner banner-warning', role: 'status' }, { class: 'banner banner-warning', role: 'status' },
h('span', {}, h('strong', {}, 'The web server is running stale code.'), ' Restart it to pick up the new version.'), glyph('⚠️🌐', 'The web server is running stale code. Restart it to pick up the new version.'),
h( h(
'button', 'button',
{ {
@ -61,8 +75,9 @@ export class StaleBannerElement extends LiveElement {
class: 'btn btn-primary btn-small', class: 'btn btn-primary btn-small',
disabled: this.restart.restarting || action.pending, disabled: this.restart.restarting || action.pending,
onclick: () => void action.run(), onclick: () => void action.run(),
'aria-label': this.restart.restarting ? 'Restarting…' : 'Restart server',
}, },
this.restart.restarting ? 'Restarting…' : 'Restart server', h('span', { 'aria-hidden': 'true' }, this.restart.restarting ? '⏳' : '🔄'),
), ),
action.error ? errorNotice(action.error) : null, action.error ? errorNotice(action.error) : null,
), ),

View File

@ -3,12 +3,13 @@
import type { Job } from '../api/jobContract' import type { Job } from '../api/jobContract'
import { isActive, q } from '../api/queries' import { isActive, q } from '../api/queries'
import { commandLabel } from '../commands/catalog' import { COMMAND_ICON, commandLabel } from '../commands/catalog'
import { hub } from '../jobs/hub' import { hub } from '../jobs/hub'
import { progressBar } from '../jobs/progress' import { progressBar } from '../jobs/progress'
import { define, h } from '../lib/dom' import { define, h } from '../lib/dom'
import { LiveElement } from '../lib/element' import { LiveElement } from '../lib/element'
import { jobHref } from '../lib/runner' import { jobHref } from '../lib/runner'
import { glyph } from '../ui/build'
export function jobChip(job: Job): HTMLAnchorElement { export function jobChip(job: Job): HTMLAnchorElement {
const live = hub.get(job.id) const live = hub.get(job.id)
@ -24,7 +25,13 @@ export function jobChip(job: Job): HTMLAnchorElement {
class: waiting ? 'jobchip jobchip-wait' : 'jobchip', class: waiting ? 'jobchip jobchip-wait' : 'jobchip',
'aria-label': `${label}: ${waiting ? 'needs your input' : (p?.label ?? 'running')}`, 'aria-label': `${label}: ${waiting ? 'needs your input' : (p?.label ?? 'running')}`,
}, },
h('span', { class: 'jobchip-label' }, label, h('span', { class: 'jobchip-sub' }, waiting ? 'needs input' : p?.total ? `${p.step}/${p.total}` : '…')), // Textgate: the command's glyph is painted; its name and "needs input" are spoken (aria-label above).
h(
'span',
{ class: 'jobchip-label' },
glyph(COMMAND_ICON[job.command], label),
h('span', { class: 'jobchip-sub' }, waiting ? glyph('✋', 'needs input') : p?.total ? `${p.step}/${p.total}` : '…'),
),
progressBar(fraction, label, waiting ? 'warning' : 'accent', true), progressBar(fraction, label, waiting ? 'warning' : 'accent', true),
) )
} }

View File

@ -0,0 +1,59 @@
// Guard test (textgate-rework R6): the dashboard and gaming panels paint
// glyphs, numbers and game names only; every label and sentence is spoken.
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { makeBudget } from './factories'
import { makeJob, makeSpec, makeStatus } from './fixtures'
import { installEventSource, mount, stubApi } from './harness'
import { visibleWords } from './visibleWords'
import '../sections/dashboard'
import '../sections/gaming/panel'
import '../shell/health'
import '../shell/jobIndicator'
const daemon = {
state: 'running',
started_at: null,
pid: 1,
journal_tail: [],
restart_available_at: null,
fast_installs: [{ app_id: 1, name: 'Celeste', phase: 'downloading depot 3/8', percent: 40, elapsed_seconds: 60 }],
}
beforeEach(installEventSource)
describe('textgate guard: dashboard + gaming', () => {
it('paints no chrome words once everything has loaded', async () => {
const budget = makeBudget()
stubApi({
'GET /api/status': makeStatus({ total_block: { active: true, days_remaining: 1, until: null } }),
'GET /api/daemon': daemon,
'GET /api/server': { stale: true, started_at: null, version: '1.2.3' },
'GET /api/budget': budget,
'GET /api/jobs': [makeJob({ id: 'a', command: 'scan', state: 'running', summary: 'Scanned 12' })],
'GET /api/commands': [makeSpec('check'), makeSpec('scan')],
})
const el = mount(
'<main><health-badges></health-badges><stale-banner></stale-banner><job-indicator></job-indicator>' +
'<dashboard-status></dashboard-status><budget-glance></budget-glance><fast-installs></fast-installs>' +
'<recent-jobs></recent-jobs><budget-panel></budget-panel></main>',
)
await vi.waitFor(() => {
expect(el.querySelector('.budget-rules')).not.toBeNull()
expect(el.querySelector('.hero-game')).not.toBeNull()
expect(el.querySelector('.banner')).not.toBeNull()
}, { timeout: 3000 })
const content = [
...budget.legend.map((e) => e.label),
...(budget.today?.games.map((g) => g.label) ?? []),
budget.session.game_name,
budget.session.billing_label,
budget.rules.masked_launchers.join(', '),
makeStatus().current_game_name ?? '',
'Celeste',
// Chart bar tooltips are "<day> · <game>: <duration>": all content.
...[...el.querySelectorAll('svg title')].map((t) => t.textContent.trim()),
]
expect(visibleWords(el, content)).toEqual([])
})
})