~ knotless Search/
↑↓ move↵ open⇧↵ all results
0
0

The console's pages are looked at, as pictures, before they change

Merged chadtmiller.com asked to merge into main from chadtmiller.com/group-host:console/look
.claude/skills/ui/SKILL.mdnew+180−0
@@ -0,0 +1,180 @@
---
name: ui
description: Build or change the console's pages (web/) so they look right, not only work. Use for any change to a page, component or style under web/. Look at every state of what you touch with `just look` before pushing, hold it to the house rules here, and have it critiqued by eyes that did not write it.
---
# Building the console's pages
The e2e flows say a page works; they do not say it looks right, and
they only ever see the states their flow passes through. A page nobody
looked at shows it: a group with no banner gets a great empty block, an
empty list is two loose sentences, the button that leaves the group is
the heaviest thing on the card. So look, at every state, before pushing.
AGENTS.md has the mechanics (tokens, component layers, inline text).
This is how the pages should read, and how to check they do.
## Looking
`just look` draws pages as this checkout's source has them, over a world
of the reference PDS, the host and the console's dev server, and writes
pictures to `target/look` for you to open with Read. Starting a world
takes half a minute: run `just look-up` in the background once, and each
look after uses it and takes seconds. A change to a page shows at the
next look; a change to the host needs the world started again.
```sh
just look / # signed out: desktop light, phone dark
just look / --as alice # signed in, at alice's PDS, as a person does
just look /g/lanterns.groups.test --as alice --seed full # a group with everything in it
just look /g/riders.groups.test --as bob # a group bob is not in
just look /g/lanterns.groups.test --as alice --click 'button[popovertarget=invite]' # a dialog open
just look /g/lanterns.groups.test/settings --as alice --element .group-card --all # one element, in all four
just look / --phone --dark --click 'header [popovertarget=sign-in]' # a dialog, on a phone
just look /new --as alice --type '[name=displayName]=A name long enough to wrap twice over on a phone' # typed into, then shot
just look /g/lanterns.groups.test --as alice --out target/look/before --name group # pictures to keep apart
```
Each world starts with alice, bob, carol, dan, erin, frank, harbor and
maximilianaquinces (the longest handle the PDS takes), and Riders
(riders.groups.test), alice's, with nothing else in it: no banner, no
picture, no words, no one else. That is the bare state. A seed puts in
the rest, once per kept world:
- `full`: Lantern Hikers (lanterns.groups.test), alice's, with a banner,
a picture, words, links, two rules and a moderator role; bob, carol
(moderator), dan, erin and frank in it, past a page of members; harbor
asking to join; an invite waiting for maximilianaquinces.
- `long`: a group of dan's with the longest handle, name, words, link
and rule the host takes; frank asking with a long note.
- `waiting`: bob asking to join Riders; carol invited to it.
A state none of them makes is a seed of your own: a module that writes
it, `--seed path/to/it.mjs` (the top of `harness/look/look.mjs` says
what it is given). Add it to `harness/look/seeds` when others will want
it too.
It says when a page is wider than the screen, naming the element that
runs past the edge: fix that before anything else, as the page then
scrolls sideways on a phone. With `--click`, it centres what it clicks
and shoots the screen, not the whole page, as a dialog or menu is seen.
## The look
Warm paper, not a white sheet (`--bg`); each part of a page a card
lifted softly off it (`Section.svelte`, `.card`); one colour that acts,
`--primary`, so what to press is never in doubt; headings in the
system's rounded face (`--font-round`). Everything comes from the shared
rules in `web/src/app.css`, over the tokens in `web/src/tokens.css`:
take a token by name, and add one there when none fits. A colour for
what it means is its role (`--danger`, `--success`, `--attention`,
`--done`, `--neutral`), never the hue under it. A page has no styles of
its own: a new kind of thing gets a rule in app.css, written for every
page that will show it.
The components are layered, atomic design's way, and `node
harness/layers.mjs` holds each to its layer:
- `atoms`: one element (`Avatar`, `Tag`, `Copy`).
- `molecules`: a few atoms that mean something together (`Section`,
`Empty`, `Dialog`, `MemberRow`, `GroupRow`).
- `organisms`: a part of a page (`MemberList`, `GroupCard`,
`SiteHeader`).
- `templates`: a page's layout, without its data (`Page`, `GroupPage`,
`Welcome`).
Look in `web/src/lib` before making one; a component made for one page
is made at the layer it belongs to, for the next page too.
## The states to look at
For every list, page or component you touch, each that applies:
- **Signed out and signed in**; **member and not**; **admin and not**
(alice runs Lantern Hikers, carol moderates it, bob is a member, harbor
is asking, maximilianaquinces is invited).
- **Empty** (Riders), **one**, **many** (Lantern Hikers, past a page),
and **long text** (`--seed long`).
- **No picture**: a group with no banner or avatar, as Riders is.
- **Phone** and **dark**: the defaults draw desktop light and phone dark.
- **Open**: every dialog and menu it has (`--click`), on a phone as well.
- **After**: what a form says once sent, and once refused.
Look at a sibling page beside yours, so the new one matches it rather
than inventing.
## House rules
**Case.** Sentence case everywhere: buttons, links, headings, menu
items, field labels, dialog titles, notes and errors ("Invite someone",
"Asking to join", "Sign out"). Only the first word and proper nouns take
a capital: Atmosphere, Bluesky, PDS, DID, AI. Labels end with no full
stop; what is said, a sentence, ends with one. Names stay as written:
opensocial, handles, roles such as `admin`. No `text-transform`.
**Empty states.** One component, `Empty.svelte`, for every empty list or
part, drawn where the list's rows would be: inside the part's card, in
the same box, never as loose text under its heading. Its title says what
is empty in the reader's terms ("Nobody is asking to join", not "No
data"); its line says why, or what will fill it; and where there is a
way out (invite someone, start a group), it carries it as its action.
The same title, body, spacing and box on every page.
**Space.** Every block stacked on another has a gap from the space
scale; text never touches a row of controls. Things that belong together
sit closer than things that do not: a heading to its list, less than the
list to the next part.
**Weight.** One primary button on a view at most, for the act the view
is for. What undoes, removes or turns down is `class="quiet"` (Leave,
Take back, Turn down, Cancel, Sign out), and a quiet button never
outweighs what it sits beside: leaving a group is there, never the
loudest thing on the card. Quiet what is said about a thing (`.mute`,
`.small`) next to the thing itself.
**The same act, the same way.** A thing done on two pages is done the
same way on both: the same component, the same words, the same order of
controls.
- *Asking for input.* An act that takes a form (inviting, adding a
rule, a role, a link, a recovery key, an app password) is a button that
opens a dialog (`Dialog.svelte`) holding the form, as "Invite someone"
does: never a form inline on one page and a dialog on another. Editing
what is already there (a profile, its pictures) may be a form in place.
- *Confirming.* An act that cannot be undone (leaving, putting someone
out, deleting, ending) asks in the same kind of dialog: what will
happen, in a sentence; a quiet Cancel; the act, as the dialog's one
button that acts.
- *Lists.* Rows in the part's card, each with its avatar or mark, its
name, what is said about it, and its acts at the row's end, quiet ones
before the one that acts; the empty state in the rows' place; "Show
more" under the last row when there are more.
- *A part's heading.* `Section.svelte`: its title, with how many when
that is worth saying, and the one act on the whole part (Invite
someone, Add a rule) across from it, as a quiet button; never a link
or a button lower down the card doing the same.
- *Where to go.* Ways to a group's other pages sit together, as the
group's nav, never floating where a banner meets a card.
**Pictures.** A group or person with no picture is drawn as one with
none is meant to look (its initial on its colour), never a blank disc;
a group with no banner shows no banner block.
**People.** A person is their avatar and handle, by `MemberRow` or the
header's menu, never a bare DID where a handle is known.
## Critique
You read your own pictures kindly. Before pushing a change that moves a
page, hand the pictures to an agent that did not write it: the Agent
tool, a fresh one, given the paths under `target/look` (and a sibling
page's), this file's House rules, and only this question: "What looks
wrong, out of place, or unlike its siblings here? Be specific: element,
what is wrong, which rule." Not the code, nor what you meant: it judges
what is drawn. Fix what it finds, or say in the pull why not.
## Then
Give the pull the pictures of the states it changes, before and after,
each as an `--image` to `knotless pull` (or `knotless edit`): the
reviewer cannot see a dialog open or a list emptied otherwise.
docs/reference/cli.md+2−0
@@ -142,6 +142,8 @@ An unknown command or flag fails with its usage; any failure exits 1.
| `dev` | the console to use, over a world of its own: the reference PDS with alice, bob and harbor, the host, and the console at https://group-host.localtest.me ([development](../development.md#using-it)) |
| `serve` | the host |
| `web`, `web-dev` | the console built, or served as its source changes |
| `look <path>… [options]` | draws the console's pages as pictures in `target/look`, in any state: `--as <account>`, `--seed <name\|file>`, `--click`, `--type`, `--element`, `--phone`, `--desktop`, `--light`, `--dark`, `--all` ([development](../development.md#looking-at-the-console)) |
| `look-up` | a world for `look` to draw over, kept until ctrl-c |
| `e2e <args>` | builds the console and the host, then runs the console's flows in Chromium over the reference PDS, as the `e2e` check does |
| `opensocial <args>` | the command |
| `docs` | the docs' links and anchors, as the `docs` check runs it |
docs/development.md+27−0
@@ -62,6 +62,33 @@ resolves it. Chromium comes with `cd harness && npx playwright install
chromium`. A failed flow leaves its trace and a picture under
`target/e2e/results`.
## Looking at the console
`just look` draws the console's pages as pictures, in any state, for an
agent (or you) to open: it is how a page is seen to look right, where
the flows only see it work. The `ui` skill (`.claude/skills/ui`) says
which states to look at and what the pages are held to.
```sh
just look /g/riders.groups.test --as alice # signed in as alice
just look / --seed full --as bob --phone --dark # a seeded state, on a phone, dark
just look /g/lanterns.groups.test --as alice --click 'button[popovertarget=invite]'
```
It draws over a world as the flows' is (`harness/world.mjs`), behind the
same https front, but with the console served by its dev server, so the
pictures show the source as it is now, with no build. Signing in as an
account goes through its PDS's own page, as a person does, and is kept
for the next look. A seed (`--seed`, from `harness/look/seeds` or a
file of your own) writes the state a page should show: a group in full,
everything long, people waiting. Starting a world takes half a minute;
`just look-up`, left running, keeps one for every look until ctrl-c,
each seed written to it once. The pictures go to `target/look`
(`--out` for another place), desktop light and phone dark unless asked
otherwise, and it says when a page is wider than the screen, naming the
element that runs past its edge. Its options are at the top of
`harness/look/look.mjs`.
## The docs site
`docs/` reads on its own, in the repository's pages; `docs-site/` makes
harness/e2e/playwright.config.mjs+2−1
@@ -10,6 +10,7 @@
import { defineConfig } from '@playwright/test'
import { join, resolve } from 'node:path'
import { fileURLToPath } from 'node:url'
import { resolving } from '../world.mjs'
const root = resolve(fileURLToPath(new URL('.', import.meta.url)), '../..')
@@ -29,7 +30,7 @@ export default defineConfig({
// The console is reached as the PDS reaches it: over https, at the
// harness's console hostname, with the harness's own certificate.
ignoreHTTPSErrors: true,
launchOptions: { args: ['--host-resolver-rules=MAP console.group-host.internal 127.0.0.1'] },
launchOptions: { args: [resolving] },
trace: 'retain-on-failure',
screenshot: 'only-on-failure',
},
harness/e2e/setup.mjs+1−13
@@ -3,19 +3,7 @@
// the name harness/pds.mjs resolves for itself. Where everything is goes
// to the flows in E2E_WORLD. Returns the teardown.
import { spawn } from 'node:child_process'
import { join } from 'node:path'
import { line, root, start } from '../world.mjs'
/// The console's front: harness/tls-proxy.mjs, with the certificate the
/// PDS trusts, for the name only it resolves.
const front = async (consolePort, net, children) => {
const proxy = spawn('node', [join(root, 'harness/tls-proxy.mjs'), net.console.cert, net.console.key, String(consolePort)], {
stdio: ['pipe', 'pipe', 'inherit'],
})
children.push(proxy)
return `https://${net.console.host}:${(await line(proxy, (l) => /^\d+$/.test(l.trim()))).trim()}`
}
import { start, tlsFront as front } from '../world.mjs'
export default async function setup() {
// harbor is an account of its own, which alice moves here to become a group;
harness/look/seeds/full.mjsnew+28−0
@@ -0,0 +1,28 @@
// A group in full: Lantern Hikers (lanterns.groups.test), alice's, with a
// banner and a picture, words, links, two rules and a moderator role;
// bob, carol (its moderator), dan, erin and frank in it, more than a page
// of members; harbor asking to join with a note; and an invite waiting
// for maximilianaquinces.
export default async ({ world, opensocial, ask, page, picture, who, exists }) => {
const g = 'lanterns.groups.test'
if (!(await exists(g))) opensocial('alice', 'group', 'seed', g)
const links = [{ url: 'https://chat.lanterns.example', title: 'Our chat' }, { url: 'https://maps.lanterns.example/routes' }]
const about = 'Evening walks on the ridge trails, lanterns lit, every Thursday from April to October.'
opensocial('alice', 'profile', 'set', g, '--display-name', 'Lantern Hikers', '--description', about, '--links', JSON.stringify(links))
for (const name of ['bob', 'carol', 'dan', 'erin', 'frank']) {
await ask(name, g)
opensocial('alice', 'member', 'assign', g, who[name].handle, name === 'carol' ? 'member,moderator' : 'member')
}
await ask('harbor', g, 'I walk the north ridge most weeks and would love company.')
opensocial('alice', 'invite', 'send', g, who.maximilianaquinces.handle, '--message', 'Come walk with us.')
// Its pictures, through its settings, as only the console uploads them.
const p = await page('alice')
for (const [slot, png] of [['Avatar', picture(256, 256)], ['Banner', picture(1500, 500, [47, 122, 75], [246, 241, 234])]]) {
await p.goto(`${world.base}/g/${g}/settings`, { waitUntil: 'networkidle' })
await p.getByLabel(slot, { exact: true }).setInputFiles({ name: 'picture.png', mimeType: 'image/png', buffer: png })
await p.getByRole('button', { name: `Upload the ${slot.toLowerCase()}` }).click()
await p.waitForLoadState('networkidle')
}
await p.context().close()
}
harness/look/seeds/long.mjsnew+26−0
@@ -0,0 +1,26 @@
// Everything long: a group whose handle, name, words, links and rule
// run as long as the host takes them, dan's; maximilianaquinces in it,
// the longest handle the PDS takes; and frank asking to join with a
// note that wraps more than once.
export const GROUP = 'the-evening-society-of-ridge-walkers-and-lantern-keepers.groups.test'
export default async ({ opensocial, ask, who, exists }) => {
const g = GROUP
if (!(await exists(g))) opensocial('dan', 'group', 'create', g, '--join-policy', 'approval')
const name = 'The Evening Society of Ridge Walkers and Lantern Keepers, North'
const about =
'We walk the long ridge every Thursday evening from the first warm week of April until the clocks go back, lanterns lit, at a pace anyone can keep. Bring water, a warm layer, and a lantern if you have one; we lend them to whoever does not. Dogs are welcome on a lead.'
const links = [
{ url: 'https://a-very-long-domain-name-for-a-walking-group.example/routes/the-north-ridge/in-the-evening', title: 'Every route we walk, with its distances and where to park' },
{ url: 'https://chat.example' },
]
opensocial('dan', 'profile', 'set', g, '--display-name', name, '--description', about, '--links', JSON.stringify(links))
const rule = 'Wait for the last walker at every gate, stile and fork'
opensocial('dan', 'rule', 'set', g, '--title', rule, '--text', 'Nobody walks on until everyone is through; the walker at the back carries the second lantern and says when all are there.')
await ask('maximilianaquinces', g)
opensocial('dan', 'member', 'assign', g, who.maximilianaquinces.handle, 'member')
const note =
'I have walked the ridge alone for years, mostly at dusk, and have a spare lantern or two. I would like to walk with others, and can lead the slower group if that helps anyone.'
await ask('frank', g, note)
}
harness/look/seeds/waiting.mjsnew+7−0
@@ -0,0 +1,7 @@
// Riders waiting on people, and people on it: bob asking to join it with
// a note, and an invite to it waiting for carol.
export default async ({ opensocial, ask, who }) => {
await ask('bob', 'riders.groups.test', 'I ride most weekends.')
opensocial('alice', 'invite', 'send', 'riders.groups.test', who.carol.handle, '--message', 'Ride with us.')
}
harness/look/look.mjsnew+357−0
@@ -0,0 +1,357 @@
// A look at the console's pages as this checkout draws them, in any state,
// as pictures to open: not whether a page works, as the e2e flows say,
// but what it looks like.
//
// node harness/look/look.mjs <path>... [options] `just look`
// node harness/look/look.mjs --up `just look-up`
//
// The pages are drawn over a world (../world.mjs): the reference PDS with
// the accounts below, the host, and the console served by its dev server,
// so what is drawn is the source as it is now, with no build. Starting one
// takes a while; `--up` starts one and keeps it, until ctrl-c, for every
// look after to use. A look with none up starts its own, and stops it.
// A world starts with Riders (riders.groups.test), alice's, and nothing
// else in it: a seed (--seed) puts in what a page should show.
//
// Options:
//
// --as <name> signed in as that account (alice, bob, ...),
// at its PDS's own page, as a person signs in;
// signed out without it
// --seed <name|file> runs a seed first: one of harness/look/seeds
// by name (full, long, waiting), or a file of
// your own. On a kept world each runs once
// --click <selector> click it first (a button that opens a dialog
// or a menu), in turn; then only the screen is
// shot, not the whole page
// --type <selector>=<text> type into it, emptied, in turn with the clicks
// --press <key> press it, in turn with the clicks (Escape)
// --element <selector> only it, not the whole page
// --desktop --phone --light --dark only those; desktop light and
// phone dark if none is given
// --all all four
// --out <dir> where the pictures go; target/look
// --name <name> what the pictures are called, in place of
// the path's
//
// A seed is a module whose default export is given `tools` below and
// writes what a page should show: `opensocial(name, ...args)` runs the
// command as that account; `ask(name, handle, message?)` asks to join a
// group as them; `exists(handle)` says whether a group is here;
// `page(name)` is a page of the console signed in as them, for what only
// the console writes (a group's pictures); `picture(w, h)` a PNG to give
// it; `world` and `who` say where everything is, and each account.
//
// A page wider than the screen is said, with what runs past its edge.
// Each picture's path is printed, to open; a run writes over the pictures
// of the same name and project, and no others.
import { chromium } from '@playwright/test'
import { execFileSync } from 'node:child_process'
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { isAbsolute, join, resolve } from 'node:path'
import { crc32, deflateSync } from 'node:zlib'
import { resolving, root, serviceAuth, start, tlsFront } from '../world.mjs'
const say = (line) => console.log(`==> ${line}`)
const fail = (why) => {
say(why)
process.exit(2)
}
/// The accounts every look's world has: enough to fill a group past a
/// page of its members, harbor to move here, and one with a handle as long as the PDS takes.
export const ACCOUNTS = ['alice', 'bob', 'carol', 'dan', 'erin', 'frank', 'harbor', 'maximilianaquinces']
const PROJECTS = {
desktop: { viewport: { width: 1280, height: 800 }, deviceScaleFactor: 1 },
phone: { viewport: { width: 390, height: 844 }, deviceScaleFactor: 2, isMobile: true, hasTouch: true },
}
const kept = join(root, 'target/look/world.json')
const targets = []
const steps = []
const seeds = []
const sides = new Set()
let as = null
let element
let up = false
let out = join(root, 'target/look')
let name
const argv = process.argv.slice(2)
for (let i = 0; i < argv.length; i++) {
const a = argv[i]
const next = () => argv[++i] ?? fail(`${a} needs a value`)
if (a === '--up') up = true
else if (a === '--as') as = next().replace(/^@/, '').split('.')[0]
else if (a === '--seed') seeds.push(next())
else if (a === '--click') steps.push({ click: next() })
else if (a === '--type') {
const [, sel, text] = next().match(/^((?:\[[^\]]*\]|[^=[])+)=(.*)$/s) ?? fail('--type takes <selector>=<text>')
steps.push({ sel, text })
} else if (a === '--press') steps.push({ key: next() })
else if (a === '--element') element = next()
else if (a === '--out') out = resolve(next())
else if (a === '--name') name = next()
else if (a === '--all') for (const s of ['desktop', 'phone', 'light', 'dark']) sides.add(s)
else if (/^--(desktop|phone|light|dark)$/.test(a)) sides.add(a.slice(2))
else if (a.startsWith('--')) fail(`${a}: no such option`)
else targets.push(a)
}
if (!up && !targets.length) fail('which page? a path, as / or /g/riders.groups.test/settings')
for (const t of targets) if (!t.startsWith('/')) fail(`${t}: a page is its path, starting with /`)
if (as && !ACCOUNTS.includes(as)) fail(`--as ${as}: no such account; one of ${ACCOUNTS.join(', ')}`)
/// The projects asked for: each of the sizes and schemes given, or
/// desktop light and phone dark.
const projects = (() => {
const sizes = ['desktop', 'phone'].filter((s) => sides.has(s))
const schemes = ['light', 'dark'].filter((s) => sides.has(s))
if (!sizes.length && !schemes.length) return [['desktop', 'light'], ['phone', 'dark']]
return (sizes.length ? sizes : ['desktop', 'phone']).flatMap((size) => (schemes.length ? schemes : ['light']).map((scheme) => [size, scheme]))
})()
/// A kept world, if one is up and answering.
async function keptWorld() {
if (!existsSync(kept)) return null
const w = JSON.parse(readFileSync(kept, 'utf8'))
const alive = await fetch(`${w.host}/xrpc/_health`).then(
() => true,
() => false,
)
return alive ? w : null
}
/// A world of its own: started, and how to stop it.
async function newWorld() {
say('starting a world: the PDS, the host, the console (`just look-up` keeps one)')
const w = await start({ accounts: ACCOUNTS, front: tlsFront, live: true })
const { net } = w
return {
world: { base: w.base, host: w.host, did: w.did, pds: net.pds, mail: net.mail, accounts: net.accounts, riders: w.riders, seeded: [], signedIn: {} },
stop: w.stop,
}
}
if (up) {
if (await keptWorld()) fail(`a world is up already (${kept}); ctrl-c it first`)
const { world, stop } = await newWorld()
mkdirSync(join(root, 'target/look'), { recursive: true })
writeFileSync(kept, JSON.stringify(world, null, 2))
const end = () => {
rmSync(kept, { force: true })
stop()
process.exit(0)
}
process.on('SIGINT', end)
process.on('SIGTERM', end)
// A browser to ready it with: the console's pages compiled once, so the
// first look is no slower than the rest.
const browser = await chromium.launch({ args: [resolving] })
const page = await (await browser.newContext({ ignoreHTTPSErrors: true })).newPage()
await page.goto(world.base, { waitUntil: 'networkidle' })
await browser.close()
say(`a world is up at ${world.base}, for each \`just look\` until ctrl-c`)
await new Promise(() => {})
}
const own = (await keptWorld()) ? null : await newWorld()
const world = own?.world ?? (await keptWorld())
const save = () => {
if (!own) writeFileSync(kept, JSON.stringify(world, null, 2))
}
const who = Object.fromEntries(world.accounts.map((a) => [a.handle.split('.')[0], a]))
const browser = await chromium.launch({ args: [resolving] })
/// A browser signed in as `name`, at their PDS's own page, as a person
/// does: kept as the world keeps it, so each look after need not.
async function signedIn(name) {
if (world.signedIn[name]) return world.signedIn[name]
const context = await browser.newContext({ ignoreHTTPSErrors: true })
const page = await context.newPage()
// Once its script has run, as a person's click comes: before, the
// form posts itself, which the page's policy stops going elsewhere.
await page.goto(world.base, { waitUntil: 'networkidle' })
await page.getByRole('banner').getByRole('button', { name: 'Sign in' }).click()
const dialog = page.getByRole('dialog', { name: 'Sign in with your Atmosphere account' })
await dialog.getByRole('textbox', { name: 'Handle' }).fill(who[name].handle)
await dialog.getByRole('button', { name: 'Sign in' }).click()
await page.waitForURL((u) => u.origin === new URL(world.pds).origin)
await page.getByRole('textbox', { name: 'Password' }).fill(who[name].password)
await page.getByRole('button', { name: 'Sign in' }).click()
await page.getByRole('button', { name: /^(accept|authorize|allow)$/i }).click()
await page.locator('.sign-out').waitFor({ timeout: 30_000 })
world.signedIn[name] = await context.storageState()
await context.close()
save()
return world.signedIn[name]
}
/// What a seed is given: ways to write to the world as its people do.
const tools = {
world,
who,
/// The opensocial command, as `name`: what it prints.
opensocial: (name, ...args) =>
execFileSync(join(root, 'target/debug/opensocial'), args, {
encoding: 'utf8',
env: {
...process.env,
OPENSOCIAL_HOST: world.host,
OPENSOCIAL_HOST_DID: world.did,
PDS_URL: world.pds,
OPENSOCIAL_AS: who[name].handle,
OPENSOCIAL_PASSWORD: who[name].password,
},
}),
/// Whether the group `handle` is here already: a seed that failed
/// partway, run again, starts it only if not.
exists: (handle) => fetch(`${world.host}/xrpc/com.atproto.identity.resolveHandle?handle=${handle}`).then((r) => r.ok),
/// `name` asks to join the group `handle`, with `message` if given: let
/// in at once where anyone may join, else waiting.
ask: async (name, handle, message) => {
const { did } = await fetch(`${world.host}/xrpc/com.atproto.identity.resolveHandle?handle=${handle}`).then((r) => r.json())
const lxm = 'fyi.opensocial.requestJoin'
const token = await serviceAuth(world.pds, who[name], world.did, lxm)
const res = await fetch(`${world.host}/xrpc/${lxm}`, {
method: 'POST',
headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
body: JSON.stringify({ group: did, ...(message ? { message } : {}) }),
})
const said = await res.json()
// A seed run again, after one that failed partway, finds them in.
if (said.error === 'AlreadyMember') return said
if (!res.ok) throw new Error(`${name} asking to join ${handle}: ${JSON.stringify(said)}`)
return said
},
/// A page of the console, signed in as `name`, for what only the
/// console writes (a group's pictures): `page.goto(world.base + path)`;
/// closed with `page.context().close()`.
page: async (name) => {
const context = await browser.newContext({ ignoreHTTPSErrors: true, storageState: await signedIn(name) })
return context.newPage()
},
/// A PNG of `width` by `height`, a wash from one hue to another, to give
/// as a picture.
picture: (width, height, from = [184, 72, 43], to = [246, 241, 234]) => png(width, height, from, to),
}
for (const seed of seeds) {
if (world.seeded.includes(seed)) {
say(`--seed ${seed}: seeded already, in this world`)
continue
}
const file = /[/.]/.test(seed) ? (isAbsolute(seed) ? seed : resolve(seed)) : join(root, 'harness/look/seeds', `${seed}.mjs`)
if (!existsSync(file)) fail(`--seed ${seed}: no such seed (${file})`)
say(`seeding ${seed}`)
await (await import(file)).default(tools)
world.seeded.push(seed)
save()
}
const storageState = as ? await signedIn(as) : undefined
const named = (t) => name ?? (t.replace(/[^a-z0-9]+/gi, '-').replace(/^-|-$/g, '') || 'home')
mkdirSync(out, { recursive: true })
let shot = 0
try {
for (const [size, scheme] of projects) {
const project = `${size}-${scheme}`
const use = PROJECTS[size]
const context = await browser.newContext({ ...use, colorScheme: scheme, locale: 'en-US', ignoreHTTPSErrors: true, storageState })
for (const target of targets) {
const page = await context.newPage()
await page.goto(world.base + target, { waitUntil: 'networkidle' })
// Each in the middle of the screen, so what it opens is in the picture.
for (const s of steps) {
if (s.key) await page.keyboard.press(s.key)
else {
const it = page.locator(s.click ?? s.sel).first()
await it.evaluate((e) => e.scrollIntoView({ block: 'center' }))
if (s.sel) {
await it.fill('')
await it.pressSequentially(s.text)
} else await it.click()
}
await page.waitForTimeout(300)
await page.waitForLoadState('networkidle')
}
// A page wider than the screen scrolls sideways, which a picture of
// the whole page hides: said, with the innermost elements whose box or
// text runs past the screen's edge, which is where to look.
const wide = await page.evaluate(() => {
const w = document.documentElement.clientWidth
if (document.documentElement.scrollWidth <= w) return null
const past = (e) => {
const r = e.getBoundingClientRect()
return r.right > w + 1 || (getComputedStyle(e).overflowX === 'visible' && r.left + e.scrollWidth > w + 1)
}
const over = [...document.body.querySelectorAll('*')].filter((e) => past(e))
const inner = over.filter((e) => !over.some((o) => o !== e && e.contains(o)))
return { by: document.documentElement.scrollWidth - w, at: inner.slice(0, 3).map((e) => `${e.tagName.toLowerCase()}${[...e.classList].map((c) => `.${c}`).join('')} "${e.textContent.trim().slice(0, 30)}"`) }
})
if (wide) say(`${named(target)}-${project}: ${wide.by}px wider than the screen, at ${wide.at.join(', ')}`)
const file = join(out, `${named(target)}${as ? `-${as}` : ''}-${project}.png`)
const opts = { path: file, animations: 'disabled', caret: 'hide' }
if (element) await page.locator(element).first().screenshot(opts)
else await page.screenshot({ ...opts, fullPage: !steps.length })
if (use.deviceScaleFactor > 1) writeFileSync(file, dense(readFileSync(file), use.deviceScaleFactor))
console.log(file)
shot++
await page.close()
}
await context.close()
}
} finally {
await browser.close()
own?.stop()
}
say(`${shot} pictures in ${out}`)
process.exit(0)
/** `png` saying it was made at `scale` times 72 pixels to the inch, as a
* Mac's screenshot does: a pull it is attached to then draws it at the
* size it was seen, not at its pixels. */
function dense(png, scale) {
const chunk = Buffer.alloc(13)
chunk.write('pHYs')
const perMetre = Math.round((scale * 72) / 0.0254)
chunk.writeUInt32BE(perMetre, 4)
chunk.writeUInt32BE(perMetre, 8)
chunk[12] = 1
const len = Buffer.alloc(4)
len.writeUInt32BE(9)
const crc = Buffer.alloc(4)
crc.writeUInt32BE(crc32(chunk))
// After the signature and the header, which come first.
return Buffer.concat([png.subarray(0, 33), len, chunk, crc, png.subarray(33)])
}
/** A `width` by `height` PNG washing from the colour `from` at its top
* left to `to` at its bottom right. */
function png(width, height, from, to) {
const rows = Buffer.alloc((width * 3 + 1) * height)
for (let y = 0; y < height; y++) {
const at = y * (width * 3 + 1)
for (let x = 0; x < width; x++) {
const t = (x / width + y / height) / 2
for (let c = 0; c < 3; c++) rows[at + 1 + x * 3 + c] = Math.round(from[c] + (to[c] - from[c]) * t)
}
}
const chunk = (type, data) => {
const body = Buffer.concat([Buffer.from(type), data])
const len = Buffer.alloc(4)
len.writeUInt32BE(data.length)
const crc = Buffer.alloc(4)
crc.writeUInt32BE(crc32(body))
return Buffer.concat([len, body, crc])
}
const header = Buffer.alloc(13)
header.writeUInt32BE(width, 0)
header.writeUInt32BE(height, 4)
header[8] = 8
header[9] = 2
return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', header), chunk('IDAT', deflateSync(rows)), chunk('IEND', Buffer.alloc(0))])
}
harness/tls-proxy.mjs+14−0
@@ -8,6 +8,7 @@
import { readFileSync } from 'node:fs'
import { createServer } from 'node:https'
import { request } from 'node:http'
import { connect } from 'node:net'
const [cert, key, target] = process.argv.slice(2)
@@ -23,6 +24,19 @@ const server = createServer({ cert: readFileSync(cert), key: readFileSync(key) }
req.pipe(upstream)
})
// A WebSocket passed on as it is: the dev server's, which tells a page
// it is still there (harness/look serves the console so).
server.on('upgrade', (req, socket, head) => {
const upstream = connect(Number(target), '127.0.0.1', () => {
const headers = Object.entries(req.headers).map(([k, v]) => `${k}: ${v}`).join('\r\n')
upstream.write(`${req.method} ${req.url} HTTP/1.1\r\n${headers}\r\n\r\n`)
upstream.write(head)
socket.pipe(upstream).pipe(socket)
})
upstream.on('error', () => socket.destroy())
socket.on('error', () => upstream.destroy())
})
server.listen(0, '127.0.0.1', () => console.log(server.address().port))
process.stdin.on('end', () => process.exit(0))
process.stdin.on('close', () => process.exit(0))
harness/world.mjs+17−1
AGENTS.md+5−0
Justfile+20−0