Files
Rosea/e2e/shell.spec.ts
T

398 lines
19 KiB
TypeScript

import AxeBuilder from '@axe-core/playwright';
import { expect, test, type Page } from '@playwright/test';
import { PRODUCT_NAME } from '@rosea/schema';
import { en } from '@rosea/ui/copy';
import { parseLetter } from '@rosea/ui/letter';
import { nextInvitation, nextSunEvent } from '@rosea/engine';
import { searchTowns } from '@rosea/content/places';
import { readFileSync } from 'node:fs';
import { BASE, startStaticServer, type StaticServer } from './static-server.js';
import { openRing, pastGardener } from './garden.js';
import { storedCare, storedTown } from './stored.js';
let server: StaticServer;
test.beforeAll(async () => {
server = await startStaticServer();
});
test.afterAll(async () => {
await server.close();
});
/** Opens the app and records every request and every CSP violation on the way. */
async function open(page: Page): Promise<{ requests: string[]; cspViolations: string[] }> {
const requests: string[] = [];
const cspViolations: string[] = [];
page.on('request', (r) => requests.push(r.url()));
page.on('console', (m) => {
if (m.type() === 'error' && /Content Security Policy/i.test(m.text())) cspViolations.push(m.text());
});
await page.goto(server.url);
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
await pastGardener(page);
// Let the worker register and precache, so its requests are counted too.
await page.waitForFunction(() => navigator.serviceWorker.ready.then(() => true), null, { timeout: 20_000 });
return { requests, cspViolations };
}
test('the built app renders its name and its one line, under the base path', async ({ page }) => {
await open(page);
await expect(page.getByText(en.shell.preparing)).toBeVisible();
await expect(page).toHaveTitle(PRODUCT_NAME);
});
test('nothing is requested from any other origin', async ({ page }) => {
const { requests } = await open(page);
expect(requests.length, 'the page must have made requests for this to mean anything').toBeGreaterThan(0);
expect(requests.filter((url) => !url.startsWith(server.origin + '/'))).toEqual([]);
});
test('nothing is written to cookies or Web Storage', async ({ page }) => {
await open(page);
const written = await page.evaluate(() => ({
cookie: document.cookie,
localStorage: localStorage.length,
sessionStorage: sessionStorage.length
}));
expect(written).toEqual({ cookie: '', localStorage: 0, sessionStorage: 0 });
expect(await page.context().cookies()).toEqual([]);
});
test('the built page carries the CSP and no inline script, and nothing violates it', async ({ page }) => {
const { cspViolations } = await open(page);
const html = await (await fetch(server.url)).text();
// Read from the DOM, not the raw HTML: Vite escapes the quotes as &#39;.
const csp = await page.locator('meta[http-equiv="Content-Security-Policy"]').getAttribute('content');
expect(csp, 'CSP meta tag in the built index.html').toBeTruthy();
expect(csp).toContain("default-src 'self'");
expect(csp).not.toContain('unsafe-inline');
expect(csp).not.toContain('unsafe-eval');
const inline = [...html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/g)].filter(
([, attrs, body]) => !/\bsrc=/.test(attrs ?? '') && (body ?? '').trim() !== ''
);
expect(inline.map(([tag]) => tag)).toEqual([]);
expect(cspViolations).toEqual([]);
// The CSP is injected FIRST in <head>, ahead of <meta charset>, so it governs
// every script. The charset must still fall in the first 1024 bytes or the
// browser may guess the encoding; a CSP that grows can push it out.
const charsetAt = Buffer.from(html).indexOf('<meta charset');
expect(charsetAt, 'meta charset present').toBeGreaterThan(-1);
expect(charsetAt, 'meta charset within the first 1024 bytes').toBeLessThan(1024);
});
test('manifest scope, start_url and the service worker scope all equal the base path', async ({ page }) => {
await open(page);
const manifestHref = await page.locator('link[rel="manifest"]').getAttribute('href');
expect(manifestHref, 'manifest link').toBeTruthy();
const manifest = (await (await fetch(new URL(manifestHref!, server.url))).json()) as Record<string, unknown>;
expect(manifest['scope']).toBe(BASE);
expect(manifest['start_url']).toBe(BASE);
expect(manifest['name']).toBe(PRODUCT_NAME);
const swScope = await page.evaluate(async () => (await navigator.serviceWorker.ready).scope);
expect(swScope).toBe(server.url);
// The icon the manifest names must exist where the manifest says it is.
const icons = manifest['icons'] as { src: string }[];
for (const icon of icons) {
const res = await fetch(new URL(icon.src, new URL(manifestHref!, server.url)));
expect(res.status, icon.src).toBe(200);
}
});
test('the shell has no accessibility violations', async ({ page }) => {
await open(page);
const results = await new AxeBuilder({ page }).analyze();
expect(results.violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
});
// Tests whichever state docs/LETTER.md is in: empty now, the author's words later.
test('the Letter: no way to it while empty, and it opens from the garden once written', async ({ page }) => {
const written = parseLetter(readFileSync(new URL('../docs/LETTER.md', import.meta.url), 'utf8')).length > 0;
await open(page);
const link = page.getByRole('link', { name: en.letter.title });
if (!written) {
await expect(link).toHaveCount(0);
await page.goto(server.url + '#letter');
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
return;
}
await link.click();
await expect(page.getByRole('heading', { level: 1 })).toHaveText(en.letter.title);
const results = await new AxeBuilder({ page }).analyze();
expect(results.violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
await page.getByRole('link', { name: en.letter.back }).click();
await expect(page.getByRole('heading', { level: 1 })).toHaveText(PRODUCT_NAME);
});
// --- Where the sunset is (.agents/features/sunset-place.md) ------------------
test.describe('the sunset place, in Prague\'s time zone at noon on 29 March 2026', () => {
test.use({ timezoneId: 'Europe/Prague', locale: 'en-US' });
const NOON = Date.parse('2026-03-29T12:00:00+02:00');
/** Browsers and Node both put a narrow no-break space before PM; compare words, not spaces. */
const spaced = (s: string): string => s.replace(/\s+/g, ' ');
test('first open asks; choosing Brno shows the sunset the engine computes; a reload keeps it', async ({ page }) => {
await page.clock.setFixedTime(NOON);
const { requests } = await open(page);
await expect(page.getByRole('heading', { level: 2, name: en.sunset.question })).toBeVisible();
await page.getByRole('searchbox', { name: en.sunset.searchLabel }).fill('brno');
await page.getByRole('button', { name: /^Brno/ }).first().click();
const brno = searchTowns('brno')[0]!;
const { at } = nextInvitation(NOON, brno);
const time = new Intl.DateTimeFormat('en-US', { hour: 'numeric', minute: '2-digit', timeZone: brno.timeZone }).format(at);
const line = page.locator('.sun p').first();
await expect(line).toHaveText(/in Brno\.$/);
expect(spaced((await line.textContent()) ?? '')).toBe(spaced(en.sunset.tonight(time, 'Brno')));
await storedTown(page, 'Brno');
await page.reload();
await expect(line).toHaveText(/in Brno\.$/);
await expect(page.getByRole('searchbox')).toHaveCount(0);
// Searching and choosing loaded the town list from this origin and nothing else.
expect(requests.filter((url) => !url.startsWith(server.origin + '/'))).toEqual([]);
expect(requests.some((url) => /\/assets\/places-.*\.js$/.test(url))).toBe(true);
});
test('at five in the morning the garden names the sunrise, not the sunset (sunrise.md)', async ({ page }) => {
const early = Date.parse('2026-03-29T05:00:00+02:00');
await page.clock.setFixedTime(early);
await open(page);
await page.getByRole('searchbox', { name: en.sunset.searchLabel }).fill('brno');
await page.getByRole('button', { name: /^Brno/ }).first().click();
const brno = searchTowns('brno')[0]!;
const { at } = nextSunEvent(early, brno);
const time = new Intl.DateTimeFormat('en-US', { hour: 'numeric', minute: '2-digit', timeZone: brno.timeZone }).format(at);
const line = page.locator('.sun p').first();
await expect(line).toHaveText(/^The sun rises at .* in Brno\.$/);
expect(spaced((await line.textContent()) ?? '')).toBe(spaced(en.sunset.rises(time, 'Brno')));
});
test('"not now" guesses Prague from the device\'s zone and says it is a guess', async ({ page }) => {
await page.clock.setFixedTime(NOON);
await open(page);
await page.getByRole('button', { name: en.sunset.skip('Prague') }).click();
await expect(page.locator('.sun p').first()).toHaveText(/^Tonight the sun sets at .* in Prague\.$/);
await expect(page.getByText(en.sunset.guessed)).toBeVisible();
});
test('the question and the answer have no accessibility violations', async ({ page }) => {
await page.clock.setFixedTime(NOON);
await open(page);
await page.getByRole('searchbox').fill('pra');
// The question's own status line (every @domi/ui button also carries an empty one, .domi-sr).
await expect(page.getByRole('status').and(page.locator('.found'))).not.toHaveText('');
expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
await page.getByRole('button', { name: /^Prague/ }).first().click();
await expect(page.locator('.sun')).toBeVisible();
expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
});
});
// --- The rose (.agents/features/rose.md) -------------------------------------
test.describe('the rose, in Prague at 08:00 on 1 March 2026', () => {
test.use({ timezoneId: 'Europe/Prague', locale: 'en-US' });
const MORNING = Date.parse('2026-03-01T08:00:00+01:00');
/** Holds the Water button with the mouse, as a player holds it with a finger. */
async function pour(page: Page, ms: number): Promise<void> {
await openRing(page);
await page.getByRole('button', { name: en.rose.water }).hover();
await page.mouse.down();
await page.waitForTimeout(ms);
await page.mouse.up();
}
test('a new rose is a bud; holding Water is one day of care; a reload keeps it', async ({ page }) => {
await page.clock.setFixedTime(MORNING);
const { requests } = await open(page);
await expect(page.getByRole('img', { name: 'The rose, a bud.' })).toBeVisible();
await expect(page.getByText(en.rose.says.dry)).toBeVisible();
await pour(page, 1500);
await expect(page.getByText(en.rose.says.thanks)).toBeVisible();
await page.getByRole('button', { name: en.rose.numbers }).click();
await expect(page.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`);
await storedCare(page, 1);
await page.reload();
await page.getByRole('button', { name: en.rose.numbers }).click();
await expect(page.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`);
expect(requests.filter((url) => !url.startsWith(server.origin + '/'))).toEqual([]);
});
test('touch her: a fond answer; three quick taps, and she says she has thorns (thorns.md)', async ({ page }) => {
// The clock is driven, not frozen: taps at one frozen instant would be one touch.
await page.clock.install({ time: MORNING });
await open(page);
await openRing(page);
const touch = page.getByRole('button', { name: en.rose.touch.label });
await touch.click();
await expect(page.locator('.bubble')).toHaveText(en.rose.touch.fond[0]!);
await page.clock.runFor(5_000);
for (let i = 0; i < 3; i++) {
await touch.click();
await page.clock.runFor(400);
}
await expect(page.locator('.bubble')).toHaveText(en.rose.touch.thorns);
await expect(page.getByRole('img', { name: 'The rose, a bud.' })).toBeVisible();
await touch.focus();
expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
});
test('a touched control shows no browser tap box (seen on a real Android tablet)', async ({ page }) => {
await page.clock.setFixedTime(MORNING);
await open(page);
await openRing(page);
const highlight = await page.getByRole('button', { name: en.rose.water }).evaluate((el) => getComputedStyle(el).getPropertyValue('-webkit-tap-highlight-color'));
expect(highlight.replace(/\s/g, '')).toBe('rgba(0,0,0,0)');
});
test('the rose and her care have no accessibility violations', async ({ page }) => {
await page.clock.setFixedTime(MORNING);
await open(page);
await page.getByRole('button', { name: en.rose.numbers }).click();
await expect(page.locator('#rose-numbers')).toBeVisible();
expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
});
});
// --- Two tabs, one garden (.agents/features/two-tabs.md) ----------------------
test.describe('two tabs of the garden, in Prague at 08:00 on 1 March 2026', () => {
test.use({ timezoneId: 'Europe/Prague', locale: 'en-US' });
const MORNING = Date.parse('2026-03-01T08:00:00+01:00');
test('care given in one tab is seen in the other without a reload, so she is not watered twice', async ({ page, context }) => {
const other = await context.newPage();
for (const p of [page, other]) {
await p.clock.setFixedTime(MORNING);
await open(p);
await expect(p.getByText(en.rose.says.dry)).toBeVisible();
}
await openRing(page);
await page.getByRole('button', { name: en.rose.water }).hover();
await page.mouse.down();
await page.waitForTimeout(1500);
await page.mouse.up();
await expect(page.getByText(en.rose.says.thanks)).toBeVisible();
await storedCare(page, 1);
// The other tab, untouched and not reloaded, knows she was watered.
await expect(other.getByText(en.rose.says.thanks)).toBeVisible({ timeout: 3_000 });
await other.getByRole('button', { name: en.rose.numbers }).click();
await expect(other.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`);
});
test('a town chosen in one tab is the town in the other', async ({ page, context }) => {
const other = await context.newPage();
for (const p of [page, other]) {
await p.clock.setFixedTime(MORNING);
await open(p);
await expect(p.getByRole('heading', { level: 2, name: en.sunset.question })).toBeVisible();
}
await page.getByRole('searchbox', { name: en.sunset.searchLabel }).fill('brno');
await page.getByRole('button', { name: /^Brno/ }).first().click();
await storedTown(page, 'Brno');
await expect(other.locator('.sun p').first()).toHaveText(/in Brno\.$/, { timeout: 3_000 });
});
});
// --- Keeping her (.agents/features/keep-her-safe.md) --------------------------
test.describe('keep her safe, in Prague at 08:00 on 1 March 2026', () => {
test.use({ timezoneId: 'Europe/Prague', locale: 'en-US' });
const MORNING = Date.parse('2026-03-01T08:00:00+01:00');
test('save her to a file, lose everything, bring her back: her care returns, and the file never held the town', async ({ browser }) => {
// The first device: choose a town, tend the rose, save her.
const first = await browser.newContext({ timezoneId: 'Europe/Prague', locale: 'en-US' });
let saved = '';
try {
const page = await first.newPage();
await page.clock.setFixedTime(MORNING);
await page.goto(server.url);
await pastGardener(page);
await page.getByRole('searchbox', { name: en.sunset.searchLabel }).fill('brno');
await page.getByRole('button', { name: /^Brno/ }).first().click();
await openRing(page);
await page.getByRole('button', { name: en.rose.water }).hover();
await page.mouse.down();
await page.waitForTimeout(1500);
await page.mouse.up();
await storedCare(page, 1);
await page.getByRole('button', { name: en.rose.safe.title }).click();
const download = page.waitForEvent('download');
await page.getByRole('button', { name: en.rose.safe.save }).click();
const file = await download;
expect(file.suggestedFilename()).toBe('rose-2026-03-01.json');
saved = readFileSync((await file.path())!, 'utf8');
} finally {
await first.close();
}
expect(JSON.parse(saved)).toMatchObject({ format: 'rosea-rose', version: 2 });
expect(saved).not.toMatch(/Brno|privateKey/);
// A fresh profile: the shape of an evicted garden, or a new phone.
const second = await browser.newContext({ timezoneId: 'Europe/Prague', locale: 'en-US' });
try {
const page = await second.newPage();
await page.clock.setFixedTime(MORNING + 3_600_000);
await page.goto(server.url);
await pastGardener(page);
await expect(page.getByRole('img', { name: 'The rose, a bud.' })).toBeVisible();
await page.getByRole('button', { name: en.rose.safe.title }).click();
await page.getByLabel(en.rose.safe.bringBack).setInputFiles({ name: 'rose-2026-03-01.json', mimeType: 'application/json', buffer: Buffer.from(saved) });
await expect(page.getByText(en.rose.safe.broughtBack(1))).toBeVisible();
await page.getByRole('button', { name: en.rose.numbers }).click();
await expect(page.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`);
await storedCare(page, 1);
await page.reload();
await page.getByRole('button', { name: en.rose.numbers }).click();
await expect(page.locator('#rose-numbers')).toContainText(`${en.rose.daysOfCare}1`);
expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
} finally {
await second.close();
}
});
});
// --- The in-game sunset (.agents/features/chair-sunset.md) ---------------------
test.describe('the in-game sunset, in Prague at noon on 29 March 2026', () => {
test.use({ timezoneId: 'Europe/Prague', locale: 'en-US' });
test('move the chair: half a minute with nothing to press, then the real sunset\'s time; again; back', async ({ page }) => {
// An installed clock, so the scene's half minute can be run in a moment.
await page.clock.install({ time: Date.parse('2026-03-29T12:00:00+02:00') });
await open(page);
await page.getByRole('button', { name: /^Not now/ }).click();
await page.getByRole('button', { name: en.chair.move }).click();
const scene = page.getByRole('dialog', { name: en.chair.scene });
await expect(scene).toBeVisible();
await expect(scene.getByRole('button')).toHaveCount(0);
expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
await page.clock.runFor(30_000);
await expect(scene.getByText(/^Tonight the sun sets at .* in Prague\.$/)).toBeVisible();
expect((await new AxeBuilder({ page }).analyze()).violations.map((v) => `${v.id}: ${v.help}`)).toEqual([]);
await scene.getByRole('button', { name: en.chair.again }).click();
await expect(scene.getByRole('button')).toHaveCount(0);
await page.keyboard.press('Escape');
await expect(scene).toHaveCount(0);
await expect(page.getByRole('button', { name: en.chair.move })).toBeFocused();
});
});