Files
orangecat/scripts/check-broken-words.mjs
CatoandClaude Fable 5.1 50b96a1b92 ci(broken-words): say why sign-in got no answer, and try once more (#1569)
* ci(broken-words): say why sign-in got no answer, and try once more

Main went red twice on 8a3e050 (#1567) in build-and-smoke → check:broken-words
with `authPostStatuses: []`: the click sent the token request to the
self-hosted auth and no response ever came back. The diagnostic recorded
only responses, so it could not say whether the form had submitted at all.
The same sign-in from outside the runner answered 200 at the time.

- Record auth requests that FAILED (Playwright `requestfailed`, error text
  only) beside the ones that answered.
- Include the page's own alert text (first 160 characters; never input).
- When no auth request got any answer, wait 20 s and try once more before
  the gate gives up — the usual cause is the runner or the shared account
  being throttled for a moment.

Checks run directly (eslint 0 errors, 2 pre-existing warnings; prettier;
node --check): `pnpm exec` cannot resolve the private writingkit tarball
from this sandbox, so the hooks that wrap it were bypassed; CI is the gate.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvpWNTLxXNfwUHS7MD

* ci(broken-words): also name preflights that failed and auth requests still pending

The first diagnostic (1d0a135) ran on CI and reported nothing at all: no
response, no failed POST, no alert, twice. A cross-origin POST is preceded
by an OPTIONS preflight, and a connection the box silently drops answers
neither — so record every auth-path request that failed, whatever its
method, every preflight rejected with 4xx/5xx, and every auth request still
unanswered when the gate gives up.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmvpWNTLxXNfwUHS7MD

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-06 02:21:50 +01:00

242 lines
9.8 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/* eslint-disable no-console */
/**
* check:broken-words — no word is drawn across two lines.
*
* A word may wrap onto the next line; it may never be cut in two. Substrata's
* answer table read "Te / rm" and "Di / re / ct / or / y" at 390px
* (2026-10-22), and reading the CSS finds none of that: it is a LAYOUT fact,
* real glyphs in a real font at a real width. So this gate opens the screens
* the owner looks at most in a real browser, at a phone's narrowest width, the
* reference phone and a desktop, and measures every word. The measurement is
* `@bitbaum/chatkit/audit` → `findBrokenWords` (handed to Playwright as a
* function, never as source text), the fleet's one definition of a cut word (words beside - / . @ : _ and over 24 characters are exempt — a URL
* or an identifier has to break somewhere).
*
* Screens: the landing page, the Cat chat page (the chatkit surface) and the
* money surface (/receive, /send, /requests, /pay/<username>). The signed-in
* ones open with E2E_USER_EMAIL / E2E_USER_PASSWORD, the same credentials the
* P0 matrix uses; without them those pages are reported as not opened, never
* as passed. Widths: 320, 390, 1440.
*
* Fails listing page, width and the words. A page that does not answer 2xx,
* or bounces to sign-in, fails too — an audit of a 404 is not an audit.
*
* Run (needs a server; not part of `pnpm run verify`, which runs no browser —
* CI runs it in the build-and-smoke job against the standalone server):
* pnpm run dev -p 3020
* BASE_URL=http://localhost:3020 pnpm run check:broken-words
* Options: PAY_USERNAME (default cato), CHROMIUM_PATH (an executable to use
* instead of Playwright's own download), BROKEN_WORDS_SCREENSHOTS=1 (writes
* .tmp/broken-words/page-<n>-<width>.png, n = the page's place in PAGES for every failure).
*/
import { mkdirSync } from 'node:fs';
import { join } from 'node:path';
import { chromium } from 'playwright';
import { findBrokenWords } from '@bitbaum/chatkit/audit';
const BASE_URL = new URL(process.env.BASE_URL ?? 'http://localhost:3000').origin;
const WIDTHS = [320, 390, 1440];
const PAY_USERNAME = /^[a-z0-9_-]{1,40}$/i.test(process.env.PAY_USERNAME ?? '')
? process.env.PAY_USERNAME
: 'cato';
const EMAIL = process.env.E2E_USER_EMAIL ?? process.env.E2E_TEST_USER_EMAIL;
const PASSWORD = process.env.E2E_USER_PASSWORD ?? process.env.E2E_TEST_USER_PASSWORD;
const SHOTS = process.env.BROKEN_WORDS_SCREENSHOTS === '1';
const SHOT_DIR = join(process.cwd(), '.tmp', 'broken-words');
/** Every screen the gate opens. `signedIn` pages need the E2E credentials. */
const PAGES = [
{ path: '/', signedIn: false },
{ path: `/pay/${PAY_USERNAME}`, signedIn: false },
{ path: '/dashboard/cat', signedIn: true },
{ path: '/receive', signedIn: true },
{ path: '/send', signedIn: true },
{ path: '/requests', signedIn: true },
];
/** Let the page finish: network quiet, fonts in, hydration done. */
async function settle(page) {
await page.waitForLoadState('networkidle', { timeout: 30_000 }).catch(() => {});
await page.evaluate(() => document.fonts.ready);
// Client-only screens hydrate after the network goes quiet; auth-gated
// ones swap a spinner for content. Wait until nothing is spinning.
await page
.waitForFunction(() => document.querySelectorAll('.animate-spin').length === 0, null, {
timeout: 15_000,
})
.catch(() => {});
await page.waitForTimeout(500);
}
/**
* Same steps as tests/e2e/helpers/login.ts, without @playwright/test.
*
* The diagnostic names what the page did, never what was typed. It records
* auth requests that FAILED as well as the ones that answered: on 2026-11-06
* main went red twice with `authPostStatuses: []` — the click had sent the
* token request and the self-hosted auth never answered it — and "no
* response recorded" told nobody whether the form had even submitted. A
* request the runner could not complete is the usual cause (the account or
* the runner throttled, a box restarting), so it is tried once more after a
* pause before the gate gives up.
*/
async function signIn(context, attempt = 1) {
const page = await context.newPage();
const authPostStatuses = [];
const authFailures = [];
// Requests that were sent and never answered or failed by the time the gate
// gave up: a connection the box silently drops looks exactly like this.
const authPending = new Map();
const isAuthPath = request => /\/(?:api\/)?auth\//.test(new URL(request.url()).pathname);
page.on('request', request => {
if (isAuthPath(request)) {
authPending.set(request, `${request.method()} ${new URL(request.url()).pathname}`);
}
});
page.on('response', response => {
authPending.delete(response.request());
if (response.request().method() === 'POST' && isAuthPath(response.request())) {
authPostStatuses.push(response.status());
}
});
// Every method: a cross-origin POST is preceded by an OPTIONS preflight, and
// when THAT fails the POST is never sent — a list that only watched POSTs
// read as "no request at all" (2026-11-06, three runs in a row).
page.on('requestfailed', request => {
authPending.delete(request);
if (isAuthPath(request)) {
authFailures.push(`${request.method()} ${request.failure()?.errorText ?? 'failed'}`);
}
});
page.on('response', response => {
const request = response.request();
if (request.method() === 'OPTIONS' && isAuthPath(request) && response.status() >= 400) {
authFailures.push(`OPTIONS ${response.status()}`);
}
});
try {
await page.goto(`${BASE_URL}/auth?mode=login`, { waitUntil: 'domcontentloaded' });
await page.getByLabel('Email address').fill(EMAIL);
await page.getByRole('textbox', { name: 'Password' }).fill(PASSWORD);
await page.getByRole('button', { name: 'Sign in', exact: true }).click();
// Leaving /auth establishes authentication. Each audited page settles its
// own assets: a slow image must not hold this on the full load event.
await page.waitForURL(url => !url.pathname.startsWith('/auth'), {
timeout: 30_000,
waitUntil: 'domcontentloaded',
});
} catch {
// Never include request/response bodies, query strings, email or password.
// The alert's words are the page's own copy ("Too many attempts…"), not input.
const alerts = await page
.getByRole('alert')
.allInnerTexts()
.catch(() => []);
const diagnostic = {
attempt,
path: new URL(page.url()).pathname,
readyState: await page.evaluate(() => document.readyState).catch(() => 'unknown'),
alerts: alerts.map(text => text.trim().slice(0, 160)).filter(Boolean),
authPostStatuses: authPostStatuses.slice(-10),
authFailures: authFailures.slice(-10),
authPending: [...authPending.values()].slice(-10),
};
await page.close();
if (attempt === 1 && authPostStatuses.length === 0) {
console.warn(
`check:broken-words: sign-in got no answer ${JSON.stringify(diagnostic)}; trying once more in 20s`
);
await new Promise(resolve => setTimeout(resolve, 20_000));
return signIn(context, 2);
}
throw new Error(`Sign-in did not reach an authenticated page: ${JSON.stringify(diagnostic)}`);
}
await page.close();
}
async function audit(context, path, width, shotName) {
const page = await context.newPage();
await page.setViewportSize({ width, height: width < 600 ? 844 : 900 });
try {
const response = await page.goto(`${BASE_URL}${path}`, {
waitUntil: 'domcontentloaded',
timeout: 60_000,
});
const status = response?.status() ?? 0;
if (status < 200 || status >= 300) {
return { error: `answered ${status}` };
}
await settle(page);
const landed = new URL(page.url()).pathname;
if (landed.startsWith('/auth')) {
return { error: `bounced to sign-in (${landed})` };
}
const words = await page.evaluate(findBrokenWords);
if (words.length > 0 && SHOTS) {
mkdirSync(SHOT_DIR, { recursive: true });
await page.screenshot({ path: join(SHOT_DIR, `${shotName}-${width}.png`), fullPage: true });
}
return { words };
} finally {
await page.close();
}
}
async function main() {
const browser = await chromium.launch({
executablePath: process.env.CHROMIUM_PATH || undefined,
});
const failures = [];
const skipped = [];
let audited = 0;
try {
const context = await browser.newContext();
const canSignIn = Boolean(EMAIL && PASSWORD);
if (canSignIn) {
await signIn(context);
}
for (const [index, { path, signedIn }] of PAGES.entries()) {
if (signedIn && !canSignIn) {
skipped.push(path);
continue;
}
for (const width of WIDTHS) {
const result = await audit(context, path, width, `page-${index}`);
audited += 1;
if (result.error) {
failures.push(`${path} @ ${width}px: ${result.error}`);
} else if (result.words.length > 0) {
const list = result.words.map(w => `"${w}"`).join(', ');
failures.push(`${path} @ ${width}px: ${list}`);
}
}
}
} finally {
await browser.close();
}
if (skipped.length > 0) {
console.warn(
`check:broken-words — NOT opened (set E2E_USER_EMAIL / E2E_USER_PASSWORD): ${skipped.join(', ')}`
);
}
if (failures.length > 0) {
console.error(
`check:broken-words — ${failures.length} screen(s) failed (page @ width: words cut, or why it did not open):`
);
for (const f of failures) console.error(` ${f}`);
if (SHOTS) console.error(` screenshots in ${SHOT_DIR}`);
process.exit(1);
}
const pages = PAGES.length - skipped.length;
console.log(
`check:broken-words passed — ${pages} page(s) × ${WIDTHS.join('/')}px (${audited} screens) at ${BASE_URL}, no word cut across lines.`
);
}
main().catch(error => {
console.error('check:broken-words could not run:', error.message);
process.exit(1);
});