oficina / estilo Public

theme: the chrome is the system UI face; Onest retired (Paul, 2026-10-25)

Paul's rule: the chrome never flashes, invisible text included. Onest
cannot load in WebKit without a frame of invisible text: optional plus
a preload painted invisible text before the fallback (Astra's review of
aab5e14), and Onest inlined as a data: URL in a render-blocking
stylesheet still painted the page textless for 6-16 ms in native
WKWebView, 12 of 12 runs. Paul chose the system face.

- --rst-font is system-ui, -apple-system, "Segoe UI", Roboto,
  "Helvetica Neue", Arial, sans-serif (Modern Font Stacks' System UI,
  and day's). TestChromeFontIsSystemUI: that token, and no estilo
  stylesheet declares a face or names Onest.
- fonts.go back to v1, byte for byte (sha256 pinned), deprecated: kept
  so old pages and cached stylesheets never 404. With the new token a
  page still linking it downloads nothing (checked in the browser).
  The v2 prefix, FontHead and the estilo-fonts partial are gone.
- fonts_browser_test.go / fontflash.browser.mjs: Playwright, Chromium
  and WebKit, by pixels with Playwright's fonts-ready wait off. Every
  picture is unpainted or final; the final is the system face, visible;
  nothing is downloaded. Controls that flash (Onest with swap, text
  hidden 1 s) must be caught or the run fails as blind; putting Onest
  back in --rst-font fails it in both engines.
- AGENTS.md row 9, the Calma notes, README, Makefile: the ruling and
  its reason. CSP unchanged.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev a59fc234878bb7c21916044eee87061f97786efc parent aab5e14
11 files changed, +412 −436
  • AGENTS.md +11 −11
  • Makefile +6 −4
  • README.md +4 −5
  • chrome/chrome_test.go +0 −10
  • chrome/templates/fonts.html +0 −8
  • credits/fonts.go +5 −3
  • theme/estilo.css +5 −3
  • theme/fontflash.browser.mjs +107 −94
  • theme/fonts.go +35 −57
  • theme/fonts_browser_test.go +185 −183
  • theme/fonts_test.go +54 −58

CI passed — run details

diff --git a/AGENTS.md b/AGENTS.md
index 0f92cec..9b863c1 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -55,7 +55,7 @@ empty repo invites the opposite.)
| 6 | *(Superseded by 8.)* **Estilo's theme is `day`, unchanged — not "derived from" or "based on" it. Divergence is allowed but must be driven by a named need, not a preference** — §Theme | Restyling on the strength of "day as a base"; changing a token because it "would look better" | Paul, 2026-08-31 |
| 7 | **Private module path is `amadan.net/oficina/estilo.git`**, using authenticated Git and `GOPRIVATE` on every builder; checked consumer `go.sum` records integrity. Preserve this path when discovery support changes. | Public visibility solely to obtain Go metadata; local filesystem replaces; a later cosmetic module rename | Overnight coordinator, 2026-09-07; Claude Fable 5.1 branch review |
| 8 | **Estilo's theme is Calma, the suite's own — no longer `day`.** Every app's colour sits on one ring of equal OKLCH lightness (`theme/apps.go`); each app is themed with its own accent (`theme.ForApp`). The marks are Calma's (Fanned Oficina mark, app icons with a glow of their own hue) and the suite's ambient effect is a seeded nebula (`sky`), placed at the sign-in, the team's home and the front page, **never inside an app** — §Theme | Keeping `day` "as a base"; one hue per app chosen by eye (Mail and Files would not fit); rim light, cores and motes in the sky | Paul, 2026-09-28/29, after six rounds of design directions: *"Calma is by far the best"*; *"Grain and filaments. No cores, no rim lights. Then go."* |
-| 9 | **Chrome text never changes face, on a first visit or ever.** Onest is `font-display: optional` and preloaded from `<head>` (`theme.FontHead`, chrome's `estilo-fonts`): it is used if it is ready when the page first renders, and otherwise the page keeps the system face for its whole life; a late Onest is never swapped in. `TestOnestNeverSwapsIn` holds the rule in CI; `make test-browser` proves it in Chromium with the font slowed — §Theme | `swap` (a fallback face, then Onest: the flash); `block` (up to 3 s of invisible text, then the same swap); a metric-matched fallback (`size-adjust`), which is still a swap; a script gate (the door and the front page run without scripts); a system UI stack (drops Calma's typeface) | Rule: Paul, 2026-10-24 (*"There should never be a flash of unstyled text. Ever."*); mechanism: branch `fix/chrome-font-no-flash`, awaiting review |
+| 9 | **The chrome is set in the system UI face and downloads no font.** `--rst-font` is `system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif` (the Modern Font Stacks "System UI" stack, and `day`'s); no estilo stylesheet declares a face. Calma's typography moves from Onest to system UI. The reason: the chrome must never flash (Paul, 2026-10-24: *"There should never be a flash of unstyled text. Ever."*, invisible text included), and **Onest cannot load in WebKit without a frame of invisible text**. Measured on `fix/chrome-font-no-flash`: with `font-display: optional` and a preload, WebKit paints the page with the chrome text invisible before the fallback; with Onest inlined as a `data:` URL in a render-blocking stylesheet, native WKWebView still painted the page with no text for 6-16 ms before Onest, in 12 of 12 runs. The system face is resolved during layout, so nothing waits and nothing swaps. v1's font files stay served, byte for byte, for old pages; nothing links them. `TestChromeFontIsSystemUI` holds it in CI; `make test-browser` proves it in Chromium and WebKit with pixels — §Theme | Onest with `font-display: swap` (the flash) or `block` (invisible, then the same swap); `optional` with a preload (invisible text in WebKit and Firefox before the fallback); Onest inlined as `data:` (a frame of invisible text in WebKit, every load, and `font-src data:` in every CSP); a metric-matched fallback (still a swap); a script gate (the door and the front page run without scripts) | Paul, 2026-10-25, choosing between Onest with a frame of invisible text in Safari and the system face; reviews: GPT-6-Astra (Codex) on `aab5e14` |
**Two callers at design time is the bar for *extraction*. It says nothing
about *destination*.** Both consuming apps were told to propose their
@@ -83,21 +83,21 @@ is Paul's decision to give the suite an identity, recorded as row 8.
What Calma is, and where each part lives:
- **`theme/estilo.css`** — the suite's tokens: a cool off-white page,
- white cards, one grey text scale, 12px shapes, a long low shadow, and
- Oficina's own accent. Status tones are `day`'s, unchanged.
+ white cards, one grey text scale, the system UI face, 12px shapes, a
+ long low shadow, and Oficina's own accent. Status tones are `day`'s, unchanged.
- **`theme/apps.go`** — the ring. Every app has a hue; all share one
OKLCH lightness and chroma, so no app is louder than another. The hues
are spaced to the eye (34-50°, widest across the muddy yellow-greens),
with room for Mail and Files. `theme.ForApp(slug)` is an app's whole
theme: estilo.css, then its accent. The ring is a closed set.
-- **`theme/fonts.go`** — Onest, Calma's typeface, served by
- `theme.FontHandler`; the theme falls back to the system face without it.
- Every page links it with `{{template "estilo-fonts"}}` (or
- `theme.FontHead()`), first in `<head>`: a preload, then the stylesheet.
- **It never swaps** (row 9): `font-display: optional`, so a slow Onest
- leaves that page in the system face rather than replacing it mid-read.
- Changing either file's bytes, or the `@font-face`, moves `FontPrefix`'s
- version: both are cached for a year as immutable.
+- **Type is the system UI face** (row 9): `--rst-font` in estilo.css,
+ nothing downloaded, so the chrome cannot flash. **No webfont in the
+ chrome.** Whoever proposes one must first show it renders in WebKit
+ with no invisible frame — `make test-browser` is the bar, and on
+ 2026-10-25 no loading strategy for Onest passed it.
+ `theme/fonts.go` only keeps v1's Onest files answering, byte for byte,
+ for old pages (`FontHandler` at `FontPrefix`, both deprecated); link
+ nothing to them.
- **`brand/`** — the marks, generated from `icons.json` (hues must equal
the ring; `brand_test` checks) in web, iPhone and Mac shapes.
- **`sky/`** — the ambient nebula: seeded per team; its colour (haze and
diff --git a/Makefile b/Makefile
index e70fc39..c0f40e5 100644
--- a/Makefile
+++ b/Makefile
@@ -70,9 +70,11 @@ test-go:
CGO_ENABLED=0 go test -count=1 ./...
# The browser checks: not part of `make test` (and so not CI), because
-# they need a Chromium (ESTILO_CHROME, on PATH, or in a Puppeteer or
-# Playwright cache) and Node 22+. Today that is theme's no-flash check
-# for Onest (theme/fonts_browser_test.go). It runs the whole suite with
-# the tag. A missing browser fails it; it never skips to a pass.
+# they need Node 22+ and Playwright with its browsers (ESTILO_PLAYWRIGHT
+# for the package's directory if it is not resolvable from theme/;
+# ESTILO_BROWSERS, default chromium,webkit). Today that is theme's
+# no-flash check for the chrome text, by pixels
+# (theme/fonts_browser_test.go). It runs the whole suite with the tag.
+# An engine that will not launch fails it; it never skips to a pass.
test-browser:
CGO_ENABLED=0 go test -tags browser -count=1 ./...
diff --git a/README.md b/README.md
index adf3f43..268327e 100644
--- a/README.md
+++ b/README.md
@@ -6,11 +6,10 @@ authenticated Git and `GOPRIVATE=amadan.net/oficina/estilo.git`.
`theme` is Calma, the suite's look (AGENTS.md, "Theme"): `theme.CSS()` is
the suite's theme and `theme.ForApp(slug)` an app's, with its accent from
-the colour ring in `theme/apps.go`. `theme.FontHandler` serves Onest, the
-typeface; put chrome's `{{template "estilo-fonts"}}` (or `theme.FontHead()`)
-first in `<head>`, before the theme. It preloads the font, which is
-`font-display: optional`: used if it is there when the page first renders,
-never swapped in later. `brand` holds the marks,
+the colour ring in `theme/apps.go`. The chrome is set in
+the system UI face and downloads no font (AGENTS.md row 9);
+`theme.FontHandler` only keeps the retired Onest files of `fonts/v1/`
+answering for old pages, and nothing should link them. `brand` holds the marks,
and `sky` the seeded nebula for the sign-in, the team's home and the front
page — never inside an app.
diff --git a/chrome/chrome_test.go b/chrome/chrome_test.go
index 57fda3b..fd3a4b2 100644
--- a/chrome/chrome_test.go
+++ b/chrome/chrome_test.go
@@ -14,7 +14,6 @@ import (
"amadan.net/oficina/estilo.git/internal/tokencheck"
"amadan.net/oficina/estilo.git/menu"
"amadan.net/oficina/estilo.git/sky"
- "amadan.net/oficina/estilo.git/theme"
"github.com/carlosframework/rastrillo/ui"
)
@@ -556,12 +555,3 @@ func TestTheAccountCanSitAtARailsFoot(t *testing.T) {
t.Error("the rail trigger is rounded; an in-flow highlight is square")
}
}
-
-// estilo-fonts is theme.FontHead, byte for byte: the partial an app's
-// layout includes and the markup estilo's own font tests load cannot
-// drift apart, and a FontPrefix bump cannot leave the partial behind.
-func TestFontsPartialIsThemeFontHead(t *testing.T) {
- if got, want := render(t, "estilo-fonts", nil), string(theme.FontHead()); got != want {
- t.Fatalf("estilo-fonts renders\n%s\nwant theme.FontHead()\n%s", got, want)
- }
-}
diff --git a/chrome/templates/fonts.html b/chrome/templates/fonts.html
deleted file mode 100644
index 3fa09a6..0000000
--- a/chrome/templates/fonts.html
+++ /dev/null
@@ -1,8 +0,0 @@
-{{/* estilo-fonts: Onest's two <head> lines, the font's preload and then
- its stylesheet. No data. Put it as early in <head> as possible, right
- after <meta charset> and the viewport, and before every stylesheet;
- the preload is what gets the file there by first paint. Renders
- exactly theme.FontHead() (chrome_test checks), so a font version bump
- reaches the app with its estilo pin. */}}
-{{define "estilo-fonts"}}<link rel="preload" href="/static/estilo/fonts/v2/onest-latin.woff2" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="/static/estilo/fonts/v2/fonts.css">{{end}}
diff --git a/credits/fonts.go b/credits/fonts.go
index 08990f7..0a8fddd 100644
--- a/credits/fonts.go
+++ b/credits/fonts.go
@@ -5,9 +5,11 @@ import _ "embed"
//go:embed notices/onest-OFL.txt
var onestNotice string
-// Onest supplies the SIL Open Font License notice for Calma's typeface,
-// which estilo's theme package embeds and serves (theme/fonts.go). An app
-// that mounts theme.FontHandler lists it on its credits page.
+// Onest supplies the SIL Open Font License notice for Onest, Calma's
+// typeface until 2026-10-25 (the chrome is now the system face; AGENTS.md
+// row 9). estilo's theme package still embeds and serves v1's file for
+// old pages (theme/fonts.go), so an app that mounts theme.FontHandler
+// lists it on its credits page.
func Onest() Component {
// The version is the Google Fonts release the embedded file came from
// (its gstatic path, recorded in notices/onest-provenance.json).
diff --git a/theme/estilo.css b/theme/estilo.css
index 0d28537..fa8ef90 100644
--- a/theme/estilo.css
+++ b/theme/estilo.css
@@ -36,9 +36,11 @@
:root {
color-scheme: light dark;
- /* Type: the family only. Sizes and spacing stay in tokens.css. Onest
- where it is served (fonts.go), the system face where it is not. */
- --rst-font: "Onest", system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
+ /* Type: the family only. Sizes and spacing stay in tokens.css. The
+ system UI face, nothing downloaded: Paul, 2026-10-25 (AGENTS.md row
+ 9). A webfont cannot render in WebKit without a frame of invisible
+ text, and the chrome never flashes. TestChromeFontIsSystemUI. */
+ --rst-font: system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
/* Shape: soft and exact. */
--rst-radius: 12px;
diff --git a/theme/fontflash.browser.mjs b/theme/fontflash.browser.mjs
index 7110605..dc9713b 100644
--- a/theme/fontflash.browser.mjs
+++ b/theme/fontflash.browser.mjs
@@ -1,111 +1,124 @@
-// fontflash.browser.mjs: watch which face the chrome text is drawn in,
-// from the first painted frame until well after a slowed Onest arrives.
-// Driven by fonts_browser_test.go (go test -tags browser ./theme), which
-// serves the page, slows the font and makes every assertion; this file
-// only drives Chromium over the DevTools protocol and reports what it saw.
+// fontflash.browser.mjs: look at the chrome text, frame after frame, from
+// navigation until long after every font and stylesheet has arrived, in
+// each engine. Driven by fonts_browser_test.go (go test -tags browser
+// ./theme), which serves the pages, slows the responses and makes every
+// assertion; this file only drives the browsers and reports what it saw.
//
-// node fontflash.browser.mjs <browser websocket URL> <scenarios JSON>
+// ESTILO_PLAYWRIGHT=<path to the playwright package> \
+// node fontflash.browser.mjs <job JSON>
//
-// Scenarios: [{name, url, watchMs, visits}]. Each runs in a fresh browser
-// context (an empty cache), visiting url `visits` times. For each visit:
-// from navigation until watchMs, every sample after the page's first
-// rendered frame records the platform font each probe element is drawn in
-// (CSS.getPlatformFontsForNode: the face the renderer actually used, not
-// what the CSS asked for). Then a new element is added, as a menu opened
-// later would be, and its face recorded too. Writes JSON to stdout.
+// Job: {engines, clip, scenarios: [{name, url, watchMs}], refs: {name: url}}.
+// For each engine and scenario, in a fresh context (empty cache, page
+// scripts off, as on the door): a screenshot of `clip` on about:blank
+// (the "not painted yet" picture), then screenshots of the same clip as
+// fast as the engine allows from the moment navigation commits until
+// watchMs, then one "final" screenshot. Then each reference page,
+// settled. Every picture is reported as a hash of its PNG bytes: the
+// same pixels encode to the same bytes, so a hash IS a visual state.
//
-// No dependencies: Node's own WebSocket (Node 22+). estilo has no npm.
+// Pictures are taken with Playwright's wait for document.fonts.ready
+// turned off (PW_TEST_SCREENSHOT_NO_FONTS_READY): with it on, a
+// screenshot waits out exactly the invisible-text window this looks for.
+//
+// When ESTILO_FONTFLASH_OUT is set, every distinct picture is written
+// there as <engine>-<scenario>-<hash>.png, to look at.
-const [, , wsURL, scenariosJSON] = process.argv
-const scenarios = JSON.parse(scenariosJSON)
+process.env.PW_TEST_SCREENSHOT_NO_FONTS_READY = '1'
+import { createHash } from 'node:crypto'
+import { createRequire } from 'node:module'
+import { writeFileSync, mkdirSync } from 'node:fs'
+import { inflateSync } from 'node:zlib'
-const ws = new WebSocket(wsURL)
-let nextId = 0
-const pending = new Map()
-ws.onmessage = (e) => {
- const m = JSON.parse(e.data)
- if (m.id && pending.has(m.id)) {
- const { resolve, reject, method } = pending.get(m.id)
- pending.delete(m.id)
- if (m.error) reject(new Error(method + ': ' + JSON.stringify(m.error)))
- else resolve(m.result)
- }
-}
-await new Promise((resolve, reject) => {
- ws.onopen = resolve
- ws.onerror = () => reject(new Error('cannot connect to ' + wsURL))
-})
-const send = (method, params = {}, sessionId) =>
- new Promise((resolve, reject) => {
- const id = ++nextId
- pending.set(id, { resolve, reject, method })
- ws.send(JSON.stringify({ id, method, params, sessionId }))
- })
+const require = createRequire(import.meta.url)
+const pw = require(process.env.ESTILO_PLAYWRIGHT || 'playwright')
+const job = JSON.parse(process.argv[2])
+const out = process.env.ESTILO_FONTFLASH_OUT
+if (out) mkdirSync(out, { recursive: true })
-const PROBES = ['#bar', '#nav']
+const hash = (b) => createHash('sha256').update(b).digest('hex').slice(0, 12)
-async function faceOf(s, selector) {
- const { root } = await send('DOM.getDocument', { depth: 0 }, s)
- const { nodeId } = await send('DOM.querySelector', { nodeId: root.nodeId, selector }, s)
- if (!nodeId) return null
- // The probe's text node carries the fonts; asking the element works in
- // current Chromium, and a probe holds nothing but its text.
- const { fonts } = await send('CSS.getPlatformFontsForNode', { nodeId }, s)
- if (!fonts.length) return null
- // One face per probe is the expectation (Latin text, one family); keep
- // them all so a mixed run shows up in the report rather than hiding.
- return fonts.map((f) => `${f.isCustomFont ? 'web' : 'system'}:${f.familyName}`).join('+')
-}
-
-async function evaluate(s, expression) {
- const r = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }, s)
- if (r.exceptionDetails) throw new Error('page threw: ' + JSON.stringify(r.exceptionDetails))
- return r.result.value
+// unpainted reports whether every pixel of an 8-bit RGB or RGBA PNG is
+// white or fully transparent: an engine's "nothing painted yet" is
+// white (about:blank's) or transparent (WebKit, before a new page's
+// first frame), encoded differently from one
+// capture to the next, so it is recognised by its pixels rather than
+// its bytes. The probe page is tinted, so the page painted with its text
+// invisible is a different, non-white picture: never "unpainted".
+function unpainted(png) {
+ let pos = 8, w = 0, h = 0, bpp = 0
+ const idat = []
+ while (pos < png.length) {
+ const len = png.readUInt32BE(pos), type = png.toString('ascii', pos + 4, pos + 8)
+ const data = png.subarray(pos + 8, pos + 8 + len)
+ if (type === 'IHDR') {
+ w = data.readUInt32BE(0); h = data.readUInt32BE(4)
+ if (data[8] !== 8 || (data[9] !== 2 && data[9] !== 6) || data[12] !== 0) throw new Error('unsupported PNG')
+ bpp = data[9] === 6 ? 4 : 3
+ } else if (type === 'IDAT') idat.push(data)
+ pos += 12 + len
+ }
+ const raw = inflateSync(Buffer.concat(idat)), stride = w * bpp
+ let prev = Buffer.alloc(stride)
+ for (let y = 0; y < h; y++) {
+ const f = raw[y * (stride + 1)], line = Buffer.from(raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1)))
+ for (let i = 0; i < stride; i++) {
+ const a = i >= bpp ? line[i - bpp] : 0, b = prev[i], c = i >= bpp ? prev[i - bpp] : 0
+ const p = a + b - c, pa = Math.abs(p - a), pb = Math.abs(p - b), pc = Math.abs(p - c)
+ line[i] = (line[i] + [0, a, b, (a + b) >> 1, pa <= pb && pa <= pc ? a : pb <= pc ? b : c][f]) & 255
+ }
+ for (let x = 0; x < stride; x += bpp) {
+ const px = line.subarray(x, x + bpp)
+ const clear = bpp === 4 && px[3] === 0
+ if (!clear && (px[0] !== 255 || px[1] !== 255 || px[2] !== 255)) return false
+ }
+ prev = line
+ }
+ return true
}
const results = []
-for (const sc of scenarios) {
- const { browserContextId } = await send('Target.createBrowserContext', { disposeOnDetach: true })
- const { targetId } = await send('Target.createTarget', { url: 'about:blank', browserContextId })
- const { sessionId: s } = await send('Target.attachToTarget', { targetId, flatten: true })
- for (const domain of ['Page', 'DOM', 'CSS', 'Runtime']) await send(domain + '.enable', {}, s)
- // A frame counter from the document's first moment. requestAnimationFrame
- // runs only when the page renders, so a count above zero means a frame
- // has been produced; while Chromium holds rendering (a render-blocking
- // stylesheet, a preloaded optional font) it stays at zero.
- await send('Page.addScriptToEvaluateOnNewDocument', {
- source: `window.__estiloFrames = 0; requestAnimationFrame(function f() { window.__estiloFrames++; requestAnimationFrame(f) })`,
- }, s)
-
- const visits = []
- for (let v = 0; v < sc.visits; v++) {
+for (const engine of job.engines) {
+ let browser
+ try {
+ browser = await pw[engine].launch({ headless: true })
+ } catch (e) {
+ results.push({ engine, error: String(e.message || e).split('\n')[0] })
+ continue
+ }
+ const version = browser.version()
+ const shoot = async (page, keep) => {
+ const png = await page.screenshot({ clip: job.clip, timeout: 15000 })
+ const h = unpainted(png) ? 'blank' : hash(png)
+ if (out && keep) writeFileSync(`${out}/${engine}-${keep}-${h}.png`, png)
+ return h
+ }
+ const scenarios = []
+ for (const sc of job.scenarios) {
+ const context = await browser.newContext({ viewport: job.viewport, deviceScaleFactor: 1, javaScriptEnabled: false })
+ const page = await context.newPage()
+ await page.goto('about:blank')
+ await shoot(page, sc.name)
+ const blank = 'blank'
const samples = []
const started = Date.now()
- await send('Page.navigate', { url: sc.url }, s)
+ await page.goto(sc.url, { waitUntil: 'commit' })
while (Date.now() - started < sc.watchMs) {
- let painted = false
- try {
- painted = await evaluate(s, `location.href === ${JSON.stringify(sc.url)} && window.__estiloFrames > 0`)
- } catch {
- // The old document is being torn down mid-navigation: not painted yet.
- }
- if (painted) {
- const sample = { t: Date.now() - started }
- for (const p of PROBES) sample[p] = await faceOf(s, p).catch(() => null)
- samples.push(sample)
- }
- await new Promise((r) => setTimeout(r, 10))
+ const t = Date.now() - started
+ // Mid-navigation, before the new page has a frame, an engine may
+ // refuse to capture at all: reported as "none", nothing painted.
+ samples.push({ t, h: await shoot(page, sc.name).catch(() => 'none') })
+ }
+ const final = await shoot(page, sc.name)
+ const refs = {}
+ for (const [name, url] of Object.entries(job.refs)) {
+ await page.goto(url, { waitUntil: 'load' })
+ await page.waitForTimeout(500)
+ refs[name] = await shoot(page, 'ref-' + name)
}
- // A menu opened after the font has (or has not) arrived.
- await evaluate(s, `(() => { const d = document.createElement('div'); d.id = 'late'; d.textContent = 'Rename · Duplicate · Delete'; document.body.append(d); return new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(() => r(true)))) })()`)
- const late = await faceOf(s, '#late')
- const font = await evaluate(s, `(() => { const e = performance.getEntriesByType('resource').find((r) => r.name.endsWith('.woff2')); return e ? { responseEnd: Math.round(e.responseEnd), transferSize: e.transferSize } : null })()`)
- visits.push({ samples, late, font })
+ await context.close()
+ scenarios.push({ name: sc.name, blank, samples, final, refs })
}
- await send('Target.closeTarget', { targetId })
- await send('Target.disposeBrowserContext', { browserContextId }).catch(() => {})
- results.push({ name: sc.name, visits })
+ await browser.close()
+ results.push({ engine, version, scenarios })
}
process.stdout.write(JSON.stringify(results))
-ws.close()
-process.exit(0)
diff --git a/theme/fonts.go b/theme/fonts.go
index e368292..36b291e 100644
--- a/theme/fonts.go
+++ b/theme/fonts.go
@@ -2,82 +2,60 @@ package theme
import (
"embed"
- "html/template"
"net/http"
"strings"
)
-// Onest is Calma's typeface: the Latin subset of the variable font
-// (weights 300-800), SIL Open Font License 1.1. Provenance and the
-// licence are in credits/notices/onest-*; list them on the app's credits
-// page with credits.Onest().
+// The chrome is set in the system UI face (estilo.css, --rst-font) and
+// downloads no font: Paul, 2026-10-25, AGENTS.md row 9. This file only
+// keeps v1's two files answering, byte for byte, so a page or cached
+// stylesheet that still names them never meets a 404. No page links them
+// any more and --rst-font names no "Onest", so a page that still does
+// declares a face nothing uses: the font is never downloaded, nothing
+// waits for it and nothing swaps.
+//
+// Onest itself is SIL Open Font License 1.1; an app that still mounts
+// FontHandler serves the file, so it lists credits.Onest() until it
+// stops. Provenance and the licence are in credits/notices/onest-*.
//go:embed fonts/onest-latin.woff2
var fontFS embed.FS
-// FontPrefix is the URL path FontHandler serves under. Its version moves
-// whenever either file's bytes do (a new subset, a newer Onest, a changed
-// unicode-range, a changed font-display): browsers hold both for a year
-// under this path, so a change under the same version never reaches a
-// returning visitor. v2: font-display moved from swap to optional.
-const FontPrefix = "/static/estilo/fonts/v2/"
-
-// FontStylesheet and FontFile are the two URLs FontHandler answers. Link
-// them with FontHead (or chrome's "estilo-fonts" template), not by hand,
-// so the next version bump reaches every app with its estilo pin.
-const (
- FontStylesheet = FontPrefix + "fonts.css"
- FontFile = FontPrefix + "onest-latin.woff2"
-)
-
-// fontCSS declares Onest for the Latin range; a character outside it
-// falls through to the system face in --rst-font, glyph by glyph, and
-// never triggers a download.
+// FontPrefix is the path FontHandler answers under: v1, frozen. Its
+// bytes never change (TestFontV1IsUnchanged); a stylesheet with a
+// different rule would need a new version, and there is no chrome font
+// to need one.
//
-// font-display: optional is the no-flash rule (Paul, 2026-10-24: "There
-// should never be a flash of unstyled text. Ever."). Onest is used only
-// if it is ready within the browser's short block period (about 100 ms);
-// otherwise the page commits to the system face for its whole life, and
-// a late Onest is never swapped in. With FontHead's preload the file is
-// requested while <head> is parsed, so on a cached or normal first visit
-// it is there in time, and Chromium holds the first paint for a preloaded
-// optional font rather than painting invisible text. swap (a fallback
-// face, then Onest: the flash) and block (up to 3 s of invisible text,
-// then the same swap) both break the rule; fonts_browser_test.go shows it.
-const fontCSS = `/* Onest, Calma's typeface (estilo theme/fonts.go). optional: used
- if ready at first paint, else the system face for the page's life;
- never swapped in late. */
+// Deprecated: link nothing under it from a new page. Mount FontHandler
+// here only so old pages keep their stylesheet.
+const FontPrefix = "/static/estilo/fonts/v1/"
+
+// fontCSS is v1's stylesheet as it shipped. It said font-display: swap,
+// the flash this branch ends; it is unchanged because it is cached for a
+// year as immutable under this name.
+const fontCSS = `/* Onest, Calma's typeface (estilo theme/fonts.go). */
@font-face {
font-family: "Onest";
font-style: normal;
font-weight: 300 800;
- font-display: optional;
- src: url("` + FontFile + `") format("woff2");
+ font-display: swap;
+ src: url("` + FontPrefix + `onest-latin.woff2") format("woff2");
unicode-range: U+0000-00FF, U+0131, U+0152-0153, U+02BB-02BC, U+02C6, U+02DA, U+02DC, U+0304, U+0308, U+0329, U+2000-206F, U+20AC, U+2122, U+2191, U+2193, U+2212, U+2215, U+FEFF, U+FFFD;
}
`
-// FontCSS is the @font-face stylesheet, served by FontHandler as
-// FontStylesheet. Link it before theme.css, through FontHead. Without it
-// the theme still works, in the system face.
+// FontCSS is v1's stylesheet, served by FontHandler as FontPrefix +
+// "fonts.css".
+//
+// Deprecated: kept for old pages; link nothing to it.
func FontCSS() []byte { return []byte(fontCSS) }
-// fontHead is FontHead's markup. The preload comes first so the font is
-// requested before any stylesheet is parsed. crossorigin is required even
-// on the same origin: fonts are fetched in CORS mode, and the spec only
-// lets a preload stand in for a request made in the same mode.
-const fontHead = `<link rel="preload" href="` + FontFile + `" as="font" type="font/woff2" crossorigin>
-<link rel="stylesheet" href="` + FontStylesheet + `">`
-
-// FontHead is the two <head> lines every page with estilo chrome carries,
-// as early in <head> as possible and before theme.css: the font's
-// preload, then its stylesheet. chrome's "estilo-fonts" template renders
-// exactly this.
-func FontHead() template.HTML { return template.HTML(fontHead) }
-
-// FontHandler serves GET and HEAD for FontStylesheet and FontFile. Mount
-// it at FontPrefix; anything else under it is 404. Public, sessionless,
-// and the bytes never change under a name, so both are cached for a year.
+// FontHandler serves GET and HEAD for FontPrefix + "fonts.css" and
+// FontPrefix + "onest-latin.woff2", v1's bytes. Mount it at FontPrefix;
+// anything else under it is 404. Public, sessionless, and the bytes never
+// change under a name, so both are cached for a year. Keep it mounted
+// while anything might still name v1 (a stale tab, a mockup that hotlinks
+// it); it costs nothing on a page that doesn't.
func FontHandler() http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
name := strings.TrimPrefix(r.URL.Path, FontPrefix)
diff --git a/theme/fonts_browser_test.go b/theme/fonts_browser_test.go
index 45fd47c..def33be 100644
--- a/theme/fonts_browser_test.go
+++ b/theme/fonts_browser_test.go
@@ -1,16 +1,26 @@
//go:build browser
-// The no-flash check for the chrome's typeface, in a real Chromium. Not
-// part of `make test`: it needs a Chromium (ESTILO_CHROME or
-// RASTRILLO_CHROME, on PATH, or in a Puppeteer or Playwright cache) and
-// Node 22+. Run it with `make test-browser`. The gate vets this file with
-// the tag (make test-vet), so it cannot stop compiling unnoticed.
+// The no-flash check for the chrome's typeface, in real engines. Not
+// part of `make test`: it needs Node 22+ and Playwright with its
+// browsers (ESTILO_PLAYWRIGHT names the playwright package directory
+// when it is not resolvable from here; ESTILO_BROWSERS picks engines,
+// default "chromium,webkit"). Run it with `make test-browser`. The gate
+// vets this file with the tag (make test-vet), so it cannot stop
+// compiling unnoticed. An engine that will not launch fails the test; it
+// never skips to a pass.
//
// Paul, 2026-10-24: "There should never be a flash of unstyled text.
-// Ever." A visible stretch of invisible text counts too. So the
-// assertion is about the face the text is drawn in, sampled from the
-// first painted frame on: it is one face for the page's whole life, and
-// a menu added after a late font arrives is drawn in that same face.
+// Ever." A visible stretch of invisible text counts too. So this looks
+// at pixels, not at what the CSS asked for or what layout reported:
+// every picture of the chrome text from navigation on must be either
+// "nothing painted yet" or the final picture, in that order. A fallback
+// face, invisible text, or text that changes after it appears, is a
+// third picture, and fails. And the final picture must be the system
+// UI face (AGENTS.md row 9), visibly.
+//
+// The detector is checked against itself every run: two pages that do
+// flash (v1's Onest with font-display: swap, and the chrome with its
+// text hidden for a second) must be caught, or the run fails as blind.
package theme
import (
@@ -20,76 +30,73 @@ import (
"net/http/httptest"
"os"
"os/exec"
- "path/filepath"
- "runtime"
"strings"
"sync/atomic"
"testing"
"time"
)
-// probePage is a page as an app draws it: FontHead first in <head>, then
-// the theme, and chrome text in --rst-font (tokens.css sets body to it;
-// this page does the same with no tokens.css to keep the probe small).
-const probePage = `<!doctype html>
+// probe is chrome text as the bar and its nav draw it, in --rst-font at
+// the bar's weights, on a tinted page so "painted, text invisible" can
+// never look like the blank page.
+const probe = `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Chrome font probe</title>
%s
<link rel="stylesheet" href="/theme.css">
-<style>body { margin: 0; font-family: var(--rst-font); } #bar { font-weight: 600; }</style>
+<style>
+body { margin: 0; background: #dfe8f5; color: #15171c; font-family: var(--rst-font); font-size: 18px; line-height: 28px; }
+#bar { font-weight: 600; } %s
+</style>
</head>
<body>
-<header id="bar">Oficina Docs</header>
-<nav id="nav">Files · Shared · Settings · Sign out</nav>
+<div id="probe"><div id="bar">Oficina Docs</div><div>Files · Shared · Settings · Sign out</div></div>
</body>
</html>
`
-type scenario struct {
- Name string `json:"name"`
- URL string `json:"url"`
- WatchMs int `json:"watchMs"`
- Visits int `json:"visits"`
-
- delay time.Duration
- fetches *atomic.Int32
-}
+// production is rastrillo's default CSP, unchanged: the system face
+// needs nothing from it.
+const production = "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:"
-type visit struct {
- Samples []map[string]any `json:"samples"`
- Late *string `json:"late"`
- Font *struct {
- ResponseEnd float64 `json:"responseEnd"`
- TransferSize float64 `json:"transferSize"`
- } `json:"font"`
-}
+// systemStack is --rst-font spelled out, for the reference picture.
+const systemStack = `system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif`
-type result struct {
- Name string `json:"name"`
- Visits []visit `json:"visits"`
+type page struct {
+ head, css string
+ cssDelay time.Duration // theme.css held back this long
+ fontDelay time.Duration // v1's woff2 held back this long
+ fetched *atomic.Int32 // v1 woff2 requests
}
-// serve is one origin per scenario, so no two share a cache entry, with
-// the font's response held for delay.
-func serve(t *testing.T, delay time.Duration, fetches *atomic.Int32) string {
+func serve(t *testing.T, p page) string {
fonts := FontHandler()
+ if p.fetched == nil {
+ p.fetched = new(atomic.Int32)
+ }
mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.Header().Set("Cache-Control", "no-store")
- fmt.Fprintf(w, probePage, FontHead())
+ w.Header().Set("Content-Security-Policy", production)
+ fmt.Fprintf(w, probe, p.head, p.css)
})
mux.HandleFunc("GET /theme.css", func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case <-time.After(p.cssDelay):
+ case <-r.Context().Done():
+ return
+ }
w.Header().Set("Content-Type", "text/css; charset=utf-8")
_, _ = w.Write(CSS())
})
mux.Handle("GET "+FontPrefix, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.URL.Path == FontFile {
- fetches.Add(1)
+ if strings.HasSuffix(r.URL.Path, ".woff2") {
+ p.fetched.Add(1)
select {
- case <-time.After(delay):
+ case <-time.After(p.fontDelay):
case <-r.Context().Done():
return
}
@@ -101,167 +108,162 @@ func serve(t *testing.T, delay time.Duration, fetches *atomic.Int32) string {
return srv.URL + "/"
}
-func findChrome(t *testing.T) string {
- for _, env := range []string{"ESTILO_CHROME", "RASTRILLO_CHROME"} {
- if p := os.Getenv(env); p != "" {
- return p
- }
- }
- for _, name := range []string{"chromium", "chromium-browser", "google-chrome", "google-chrome-stable", "chrome"} {
- if p, err := exec.LookPath(name); err == nil {
- return p
- }
- }
- home, _ := os.UserHomeDir()
- var globs []string
- switch runtime.GOOS {
- case "darwin":
- globs = []string{
- "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
- "/Applications/Chromium.app/Contents/MacOS/Chromium",
- home + "/.cache/puppeteer/chrome/*/chrome-mac*/Google Chrome for Testing.app/Contents/MacOS/Google Chrome for Testing",
- home + "/Library/Caches/ms-playwright/chromium-*/chrome-mac*/Chromium.app/Contents/MacOS/Chromium",
- }
- default:
- globs = []string{
- home + "/.cache/puppeteer/chrome/*/chrome-linux*/chrome",
- home + "/.cache/ms-playwright/chromium-*/chrome-linux*/chrome",
- }
- }
- for _, g := range globs {
- if m, _ := filepath.Glob(g); len(m) > 0 {
- return m[len(m)-1] // the newest, by the caches' version-sorted names
- }
- }
- // Fatal, not Skip: asking for the browser tag and getting a pass
- // because there was no browser is the false green this repo has
- // already been bitten by.
- t.Fatal("no Chromium found: set ESTILO_CHROME to a Chrome or Chromium binary")
- return ""
-}
+type scenario struct {
+ Name string `json:"name"`
+ URL string `json:"url"`
+ WatchMs int `json:"watchMs"`
-// launch starts a headless Chromium and returns its browser websocket.
-func launch(t *testing.T) string {
- dir := t.TempDir()
- args := []string{
- "--headless", "--remote-debugging-port=0", "--user-data-dir=" + dir,
- "--no-first-run", "--no-default-browser-check", "--disable-extensions",
- "--disable-background-networking", "--disable-component-update", "--mute-audio",
- "about:blank",
- }
- if os.Getuid() == 0 {
- args = append(args, "--no-sandbox")
- }
- cmd := exec.Command(findChrome(t), args...)
- if err := cmd.Start(); err != nil {
- t.Fatalf("start Chromium: %v", err)
- }
- t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait() })
- for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(50 * time.Millisecond) {
- b, err := os.ReadFile(filepath.Join(dir, "DevToolsActivePort"))
- if lines := strings.Split(strings.TrimSpace(string(b)), "\n"); err == nil && len(lines) == 2 {
- return "ws://127.0.0.1:" + lines[0] + lines[1]
- }
- }
- t.Fatal("Chromium did not open its DevTools port")
- return ""
+ flashes bool // a control: the detector must catch it
+ fetched *atomic.Int32 // must stay 0 for the design: nothing is downloaded
}
-// faces lists the distinct faces a visit's samples saw for one probe, in
-// the order they first appeared.
-func faces(v visit, probe string) []string {
- var seen []string
- for _, s := range v.Samples {
- f, _ := s[probe].(string)
- if f == "" {
- continue
- }
- if len(seen) == 0 || seen[len(seen)-1] != f {
- seen = append(seen, f)
- }
- }
- return seen
+type observed struct {
+ Engine string `json:"engine"`
+ Version string `json:"version"`
+ Error string `json:"error"`
+ Scenarios []struct {
+ Name string `json:"name"`
+ Blank string `json:"blank"`
+ Final string `json:"final"`
+ Samples []struct {
+ T int `json:"t"`
+ H string `json:"h"`
+ } `json:"samples"`
+ Refs map[string]string `json:"refs"`
+ } `json:"scenarios"`
}
-func TestChromeTextNeverChangesFace(t *testing.T) {
+func TestChromeTextNeverFlashes(t *testing.T) {
if _, err := exec.LookPath("node"); err != nil {
- t.Fatal("node is required (Node 22+, for its WebSocket)")
+ t.Fatal("node is required (Node 22+)")
}
- ws := launch(t)
-
- // Delays: none (a normal first visit on a fast link); 400 ms, past
- // optional's ~100 ms block period but well inside block's 3 s, so a
- // held-invisible-then-Onest page shows as a change of face; and 3.5 s,
- // past block's 3 s too, so block's own late swap shows up as well.
+ engines := strings.Split(os.Getenv("ESTILO_BROWSERS"), ",")
+ if engines[0] == "" {
+ engines = []string{"chromium", "webkit"}
+ }
+ v1 := `<link rel="stylesheet" href="` + FontPrefix + `fonts.css">`
+ hide := `#probe { animation: hide 1s step-end; } @keyframes hide { from { color: transparent; } to { color: inherit; } }`
+ ms := func(d time.Duration) int { return int(d / time.Millisecond) }
var scs []*scenario
- for _, c := range []struct {
- name string
- delay time.Duration
- }{{"fast", 0}, {"slow-400ms", 400 * time.Millisecond}, {"slow-3500ms", 3500 * time.Millisecond}} {
- sc := &scenario{Name: c.name, delay: c.delay, fetches: new(atomic.Int32), Visits: 2,
- WatchMs: int((c.delay + 1500*time.Millisecond) / time.Millisecond)}
- sc.URL = serve(t, sc.delay, sc.fetches)
- scs = append(scs, sc)
+ add := func(name string, p page, watch time.Duration, sc scenario) {
+ p.fetched = new(atomic.Int32)
+ sc.Name, sc.URL, sc.WatchMs, sc.fetched = name, serve(t, p), ms(watch), p.fetched
+ scs = append(scs, &sc)
}
- arg, _ := json.Marshal(scs)
- cmd := exec.Command("node", "fontflash.browser.mjs", ws, string(arg))
+ // The design: the page with theme.css prompt, slower than optional's
+ // 100 ms block period, and slower than block's 3 s.
+ for _, d := range []time.Duration{0, 400 * time.Millisecond, 3500 * time.Millisecond} {
+ add(fmt.Sprintf("system UI, theme.css +%dms", ms(d)), page{cssDelay: d}, d+1500*time.Millisecond, scenario{})
+ }
+ // An app not yet adopted: its layout still links v1's fonts.css. The
+ // face is declared and nothing uses it, so it is never fetched.
+ add("system UI, page still linking v1 fonts.css", page{head: v1, fontDelay: time.Second}, 2500*time.Millisecond, scenario{})
+ // Controls, which do flash.
+ add("control: v1 Onest (swap), font +1000ms", page{head: v1, fontDelay: time.Second, css: `#probe { font-family: "Onest", var(--rst-font); }`}, 2500*time.Millisecond, scenario{flashes: true})
+ add("control: text hidden 1s", page{css: hide}, 2500*time.Millisecond, scenario{flashes: true})
+
+ refs := map[string]string{
+ "system": serve(t, page{css: `#probe { font-family: ` + systemStack + `; }`}), // the stack, spelled out
+ "hidden": serve(t, page{css: `#probe { color: transparent; }`}), // painted, text invisible
+ }
+ job, _ := json.Marshal(map[string]any{
+ "engines": engines,
+ "viewport": map[string]int{"width": 480, "height": 120},
+ "clip": map[string]int{"x": 0, "y": 0, "width": 480, "height": 56},
+ "scenarios": scs,
+ "refs": refs,
+ })
+ cmd := exec.Command("node", "fontflash.browser.mjs", string(job))
cmd.Stderr = os.Stderr
- out, err := cmd.Output()
+ raw, err := cmd.Output()
if err != nil {
t.Fatalf("node fontflash.browser.mjs: %v", err)
}
- var results []result
- if err := json.Unmarshal(out, &results); err != nil {
- t.Fatalf("driver output: %v\n%s", err, out)
+ var results []observed
+ if err := json.Unmarshal(raw, &results); err != nil {
+ t.Fatalf("driver output: %v\n%s", err, raw)
}
- for i, r := range results {
- sc := scs[i]
- for vi, v := range r.Visits {
- where := fmt.Sprintf("%s, visit %d", r.Name, vi+1)
- if len(v.Samples) < 10 {
- t.Errorf("%s: only %d painted samples; the watch did not see the page", where, len(v.Samples))
+ for _, r := range results {
+ if r.Error != "" {
+ t.Errorf("%s did not launch: %s", r.Engine, r.Error)
+ continue
+ }
+ for i, s := range r.Scenarios {
+ sc, where := scs[i], r.Engine+" "+r.Version+", "+s.Name
+ // A flash is any picture that is neither "not painted yet"
+ // nor the final one, or "not painted" again after the final
+ // one has shown.
+ var flash []string
+ painted, before := false, 0
+ for _, p := range s.Samples {
+ switch p.H {
+ case s.Blank, "none":
+ before++
+ if painted {
+ flash = append(flash, fmt.Sprintf("%dms blank again", p.T))
+ }
+ case s.Final:
+ painted = true
+ default:
+ flash = append(flash, fmt.Sprintf("%dms %s", p.T, p.H))
+ }
+ }
+ if len(s.Samples) < 10 {
+ t.Errorf("%s: only %d pictures; the watch did not see the page", where, len(s.Samples))
continue
}
- var committed string
- for _, probe := range []string{"#bar", "#nav"} {
- seen := faces(v, probe)
- if len(seen) != 1 {
- t.Errorf("%s: %s changed face after it was painted: %s", where, probe, strings.Join(seen, " -> "))
- continue
- }
- if committed == "" {
- committed = seen[0]
- }
+ if !painted {
+ t.Errorf("%s: the final picture never appeared during the watch", where)
}
- if v.Late == nil || *v.Late != committed {
- got := "nothing"
- if v.Late != nil {
- got = *v.Late
- }
- t.Errorf("%s: a menu added after the font settled is drawn in %s, the page in %s", where, got, committed)
+ if s.Final == s.Refs["hidden"] || s.Final == s.Blank {
+ t.Errorf("%s: the final picture has no visible text", where)
}
- if v.Font == nil || v.Font.ResponseEnd <= 0 || v.Font.ResponseEnd > float64(sc.WatchMs) {
- t.Errorf("%s: the font did not arrive inside the watch (%+v), so a late swap could not have been seen", where, v.Font)
+ if !sc.flashes {
+ if s.Final != s.Refs["system"] {
+ t.Errorf("%s: the final picture is not the system UI face", where)
+ }
+ if n := sc.fetched.Load(); n != 0 {
+ t.Errorf("%s: a font was downloaded %d times; the chrome downloads none", where, n)
+ }
}
- // What each visit must look like, not only that it held still:
- // a test where Onest never renders would otherwise pass.
- isOnest := strings.HasPrefix(committed, "web:Onest")
switch {
- case vi == 1 && !isOnest:
- t.Errorf("%s: a return visit (font cached) is drawn in %s, not Onest", where, committed)
- case r.Name == "fast" && !isOnest:
- t.Errorf("%s: a first visit with a prompt font is drawn in %s, not Onest", where, committed)
- case r.Name == "slow-3500ms" && vi == 0 && isOnest:
- t.Errorf("%s: drawn in Onest though the font took 3.5 s; the watch cannot have started at first paint", where)
+ case sc.flashes && len(flash) == 0:
+ t.Errorf("%s: a page that flashes was not caught; the detector is blind", where)
+ case !sc.flashes && len(flash) > 0:
+ t.Errorf("%s: FLASH: %d of %d pictures were neither blank nor final: %s", where, len(flash), len(s.Samples), strings.Join(first(flash, 6), ", "))
}
- t.Logf("%s: %s, %d samples from %vms, font at %vms", where, committed, len(v.Samples), v.Samples[0]["t"], v.Font.ResponseEnd)
+ t.Logf("%s: timeline %s", where, timeline(s.Samples, map[string]string{s.Blank: "blank", "none": "none", s.Final: "FINAL", s.Refs["system"]: "SYSTEM", s.Refs["hidden"]: "HIDDEN"}))
+ t.Logf("%s: %d pictures (%d before first paint, every %dms), %d off-final", where, len(s.Samples), before, s.Samples[len(s.Samples)-1].T/len(s.Samples), len(flash))
}
- // One download in all: the preload is the request the @font-face
- // uses, and the return visit is from cache (FontHandler's
- // one-year immutable).
- if n := sc.fetches.Load(); n != 1 {
- t.Errorf("%s: the font was requested %d times, want 1", r.Name, n)
+ }
+}
+
+// timeline is the run-length sequence of pictures: "blank 0-7ms, FINAL
+// 8-1500ms".
+func timeline(samples []struct {
+ T int `json:"t"`
+ H string `json:"h"`
+}, names map[string]string) string {
+ var out []string
+ for i := 0; i < len(samples); {
+ j := i
+ for j+1 < len(samples) && samples[j+1].H == samples[i].H {
+ j++
+ }
+ name := names[samples[i].H]
+ if name == "" {
+ name = samples[i].H
}
+ out = append(out, fmt.Sprintf("%s %d-%dms", name, samples[i].T, samples[j].T))
+ i = j + 1
+ }
+ return strings.Join(first(out, 12), ", ")
+}
+
+func first(s []string, n int) []string {
+ if len(s) > n {
+ return append(s[:n:n], fmt.Sprintf("... %d more", len(s)-n))
}
+ return s
}
diff --git a/theme/fonts_test.go b/theme/fonts_test.go
index e336b0e..ad6e0bf 100644
--- a/theme/fonts_test.go
+++ b/theme/fonts_test.go
@@ -5,20 +5,53 @@ import (
"encoding/hex"
"net/http"
"net/http/httptest"
+ "os"
+ "path/filepath"
"regexp"
"strings"
"testing"
)
-func TestFontHandlerServesOnlyItsTwoFiles(t *testing.T) {
+// Paul, 2026-10-25 (AGENTS.md row 9): the chrome is the system UI face
+// and downloads nothing, because no webfont renders in WebKit without a
+// frame of invisible text. Held here, in the plain suite, so CI keeps it
+// without a browser (fonts_browser_test.go is the proof in one): the
+// token is the system stack, and no stylesheet estilo ships declares a
+// face or names Onest.
+func TestChromeFontIsSystemUI(t *testing.T) {
+ const want = `system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif`
+ m := regexp.MustCompile(`--rst-font:\s*([^;]+);`).FindAllSubmatch(css, -1)
+ if len(m) != 1 || string(m[0][1]) != want {
+ t.Fatalf("--rst-font = %q, want the system UI stack %q", m, want)
+ }
+ sheets, _ := filepath.Glob("../*/*.css")
+ if len(sheets) < 8 {
+ t.Fatalf("found only %d stylesheets; the scan would pass vacuously", len(sheets))
+ }
+ for _, p := range sheets {
+ b, err := os.ReadFile(p)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if strings.Contains(p, "testdata") {
+ continue
+ }
+ if regexp.MustCompile(`(?i)@font-face|\bonest\b`).Match(b) {
+ t.Errorf("%s declares a webfont or names Onest; the chrome downloads no font", p)
+ }
+ }
+}
+
+func TestFontHandlerServesOnlyV1sTwoFiles(t *testing.T) {
h := FontHandler()
for path, want := range map[string]int{
- FontStylesheet: 200,
- FontFile: 200,
- FontPrefix + "onest.woff2": 404,
- FontPrefix + "../theme/estilo.css": 404,
- FontPrefix: 404,
- "/static/other/onest-latin.woff2": 404,
+ FontPrefix + "fonts.css": 200,
+ FontPrefix + "onest-latin.woff2": 200,
+ FontPrefix + "onest.woff2": 404,
+ FontPrefix + "../theme/estilo.css": 404,
+ FontPrefix: 404,
+ "/static/estilo/fonts/v2/fonts.css": 404,
+ "/static/other/onest-latin.woff2": 404,
} {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
@@ -33,56 +66,19 @@ func TestFontHandlerServesOnlyItsTwoFiles(t *testing.T) {
}
}
-// The embedded font is the one the provenance record names.
-func TestOnestIsTheRecordedFile(t *testing.T) {
- body, err := fontFS.ReadFile("fonts/onest-latin.woff2")
- if err != nil {
- t.Fatal(err)
- }
- sum := sha256.Sum256(body)
- if got := hex.EncodeToString(sum[:]); got != "cc61cbd632bb677cd55f0eec9ebdd3e1525c5f30904cbf0769e2ac50d0fba992" {
- t.Fatalf("onest-latin.woff2 is not the file credits/notices/onest-provenance.json records (sha256 %s)", got)
- }
-}
-
-// The no-flash rule, in the plain suite so CI holds it without a browser
-// (fonts_browser_test.go is the proof in one): the face is optional,
-// never swap, block, fallback or auto, each of which swaps Onest in late.
-func TestOnestNeverSwapsIn(t *testing.T) {
- got := regexp.MustCompile(`font-display:\s*([a-z]+)`).FindAllStringSubmatch(fontCSS, -1)
- if len(got) != 1 || got[0][1] != "optional" {
- t.Fatalf("fonts.css font-display = %v, want exactly one, optional", got)
- }
- if strings.Count(fontCSS, "@font-face") != 1 {
- t.Fatal("fonts.css declares more than one face; each needs the same rule and its own preload")
- }
-}
-
-// FontHead preloads the very file the @font-face names, as a CORS font
-// fetch (crossorigin) so the preload is the request the face uses, and
-// before the stylesheet.
-func TestFontHeadPreloadsTheFace(t *testing.T) {
- head := string(FontHead())
- preload := `<link rel="preload" href="` + FontFile + `" as="font" type="font/woff2" crossorigin>`
- sheet := `<link rel="stylesheet" href="` + FontStylesheet + `">`
- if head != preload+"\n"+sheet {
- t.Fatalf("FontHead = %q, want the preload then the stylesheet", head)
- }
- if !strings.Contains(fontCSS, `url("`+FontFile+`")`) {
- t.Fatal("the @font-face does not use the file FontHead preloads")
- }
-}
-
-// v1's fonts.css said swap and is cached for a year as immutable; serving
-// the new rule under the old name would never reach a returning visitor.
-// The prefix moved, and the old one is not served.
-func TestOldFontPrefixIsGone(t *testing.T) {
- if FontPrefix == "/static/estilo/fonts/v1/" {
- t.Fatal("font-display changed without a FontPrefix bump")
- }
- rec := httptest.NewRecorder()
- FontHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/static/estilo/fonts/v1/fonts.css", nil))
- if rec.Code != http.StatusNotFound {
- t.Fatalf("GET v1 fonts.css = %d, want 404", rec.Code)
+// v1 answers exactly as it shipped (both sha256s are origin/main
+// f14458a's): cached for a year as immutable under these names, and a
+// page that still links them keeps working.
+func TestFontV1IsUnchanged(t *testing.T) {
+ for path, want := range map[string]string{
+ FontPrefix + "fonts.css": "2b3d039ae92b9f87aa549c364a25d9ee2199127e4c53deff8760482d13deb336",
+ FontPrefix + "onest-latin.woff2": "cc61cbd632bb677cd55f0eec9ebdd3e1525c5f30904cbf0769e2ac50d0fba992",
+ } {
+ rec := httptest.NewRecorder()
+ FontHandler().ServeHTTP(rec, httptest.NewRequest(http.MethodGet, path, nil))
+ sum := sha256.Sum256(rec.Body.Bytes())
+ if got := hex.EncodeToString(sum[:]); got != want {
+ t.Errorf("%s changed (sha256 %s); it is cached as immutable under that name", path, got)
+ }
}
}