tickets
All repositories: gitoria
195.6 KB
// tests/browser.mjs — THE GATE of tickets.worldapi.org: its own server on its own// storage, the import command, the JSON API, and TWO real headless Chromes (two// viewers) for the live push. Everything is checked in the browser's DOM, not in// curl output. Ticket #10 added: the strict API table (unknown / missing / empty /// wrong-type fields → 400 naming the field, nothing written), Vienna local time (checked// against node's Intl, also tests/localtime.hl's DST edges), and the paragraph import// (a CRLF fixture in .scratch/gate-import → #7, rendered with a blank line between).// Ticket #15 added: `author` required on every POST (missing/empty → 400 naming author),// invalid JSON → 400 { error } without source paths (jsoncheck.hl), the web forms have no// name field (author 'creator'), and list lines kept by the import (.scratch/gate-import-lists → hybriel #3).// Ticket #38 (mission 008) added: UUID keys + storage in <store>/mpackdb, per-project// numbers and URLs /<slug>/<number> (ticket #25; was /projects/<slug>/<number>). The gate FIRST writes an old-format store// (tests/oldstore.hl: 5 tickets, old #1–#5 in projects alpha / beta.example.org), migrates// it TWICE with tools/migrate-008.hl (the second run must write nothing), and runs the// server on the migrated tables: old numbers answer on /api/tickets/<n>, /tickets/<n>// redirects (301) to the new URL, the per-project API, live pushes carrying the new hrefs.// Ticket #7 (mission 011) added LOGIN VIA IDENT: the gate runs its OWN ident (a copy of// ident's code without .env / storage — codes go to a mail sink, never real mail; tests/identkit.mjs)// on :8353, registers tickets there (origin = this gate's server), and then: every API write// needs `Authorization: Bearer <token>` (401 otherwise, checked before the body; `author` in a// body → 400), a machine user "gate" logs in through the login button's server half// (/login/callback) and makes its token over the face; the FIRST server runs without// TICKETS_CREATOR_IDENTITY (nobody may confirm/reject → 403), the second with alice's per-app id.// In the browsers: signed out = reading only; A (alice, the creator) logs in with the identity// SELECTOR, B (bob) with ident's /login link (no header button since 2026-10-24); both get the display-name prompt; writes show the// user as author; bob cannot confirm/reject, alice can; bob's token on /you: shown once → API// write as bob → revoke → 401; forged face sessions (#31) are refused; old events keep their// authors; logout resets the selector.// Ticket #12 (mission 024) added THE MARKDOWN EDITOR; since mission 016 every Markdown field is the Hybriel MdEditor// (components/md-editor/) and the comments are the shared Comments block (components/comments/, layouts#2): typed with// real keys, Ctrl+Enter sends; "m016:" checks edit (the earlier version folds out), delete (asks first), like (toggle),// Edit / Delete only on your own comments, comments in place between the other history entries, a non-member reads// only and the server refuses them (faces + API), the comment API. The blocks' own gate: components.hybriel.worldapi.org.//// node tests/browser.mjs (TICKETS_GATE_PORT to move the server, default 8352;// TICKETS_GATE_IDENT_PORT the gate's ident, default 8353;// TICKETS_GATE_IDENT_DIR ident's code, default ../ident.worldapi.org)//// Debug ports: 8620-8629 (browser A) and 8630-8639 (browser B) — TICKETS_GATE_CHROME_A /// TICKETS_GATE_CHROME_B ("8810-8814") move them (mission 017: parallel workers get disjoint// port ranges); browser C (mission 046, the installable app / offline part at the end) 8640-8649,// TICKETS_GATE_CHROME_C. Screenshots at 390px// and 1280px land in .scratch/gate-*.png — LOOK at them. The whole server log is kept in// .scratch/gate-server.log. Every process started here (server, import runs, Chromes)// is stopped by PID in `finally`.import { spawn, spawnSync } from 'node:child_process';import http from 'node:http';import { rmSync, mkdirSync, writeFileSync, existsSync, readdirSync, copyFileSync, readFileSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import zlib from 'node:zlib';import { launchBrowser } from './cdp.mjs';import { startIdent } from './identkit.mjs';if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';const HERE = dirname(fileURLToPath(import.meta.url));const APP = resolve(HERE, '..');const BIN = join(APP, 'bin/hybriel');const PORT = Number(process.env.TICKETS_GATE_PORT || 8352);const BASE = `http://127.0.0.1:${PORT}`;const SCRATCH = join(APP, '.scratch');const STORE = join(SCRATCH, 'gate-store');const IDENT_PORT = Number(process.env.TICKETS_GATE_IDENT_PORT || 8353);// ident's CODE (read only — copied without .env/storage by identkit): the sibling folder,// or the Loreana path when the gate runs in a copy (.scratch/dev…)const IDENT_DIR = process.env.TICKETS_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));rmSync(STORE, { recursive: true, force: true });mkdirSync(join(STORE, 'mpackdb'), { recursive: true });// IW (creator 2026-10-24, "you removed the ident widget from all sites"): ident's <ident-selector> stands in the header, VISIBLE, top right — signed// out and signed in, on the phone and on the desktop. Returns 'ok' or what is wrong (hidden by an ancestor, no box, outside the viewport, not in the// header, not on the right, covered by something else).const SELECTOR_IN_HEADER = `(() => { const s = document.querySelector('application-header ident-selector'); if (!s) return 'no ident-selector in the header';for (let e = s; e && e !== document.documentElement; e = e.parentElement) { const c = getComputedStyle(e); if (c.display === 'none') return 'display:none on ' + e.tagName; if (c.visibility === 'hidden') return 'visibility:hidden on ' + e.tagName; if (+c.opacity === 0) return 'opacity 0 on ' + e.tagName; }const b = s.getBoundingClientRect(), h = document.querySelector('application-header').getBoundingClientRect();if (b.width < 40 || b.height < 30) return 'no box ' + b.width + 'x' + b.height;if (b.left < 0 || b.top < 0 || b.right > innerWidth + 0.5 || b.bottom > innerHeight) return 'outside the viewport ' + JSON.stringify([b.left, b.top, b.right, b.bottom]);if (b.top < h.top - 1 || b.bottom > h.bottom + 1) return 'not inside the header row ' + JSON.stringify([b.top, b.bottom, h.top, h.bottom]);if (b.left + b.width / 2 < innerWidth / 2) return 'not at the top right ' + b.left;const top = document.elementFromPoint(b.left + b.width / 2, b.top + b.height / 2); if (!top || !top.closest('ident-selector')) return 'covered by ' + (top && top.tagName);return 'ok'; })()`;let failures = 0, passes = 0;function check(label, ok, detail = '') {console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);if (ok) passes++; else failures++;}const sleep = (ms) => new Promise(r => setTimeout(r, ms));const J = JSON.stringify;// a re-vendored Hybriel compiles each entry at its first start (cold ~20 s on Loreana, hybriel#148; then ~1 s from// ~/.hybriel/cache/run): every start of a .hl program waits up to COLD_MS (TICKETS_COLD_MS, default 120 s)const COLD_MS = Number(process.env.TICKETS_COLD_MS || 120000);// ---- the legacy fixture (ticket #20): a store from before projects were own data; the server's migrate.hl// turns it into projects with ids, members and the new states at its first start ----------------------const hl = (script, env) => { const r = spawnSync(BIN, [script], { cwd: APP, env: { ...process.env, ...env }, encoding: 'utf8', timeout: COLD_MS }); return (r.stdout || '') + (r.stderr || ''); };const fixture = hl('tests/oldstore.hl', { TICKETS_STORAGE: join(STORE, 'mpackdb') });check('migrate: the pre-#20 fixture is written (2 projects, 5 tickets, 8 events)', /oldstore: 2 projects, 5 tickets, 8 events/.test(fixture), fixture);// ---- the servers: our own ident, then tickets (twice: without and with a creator) ----------let log = '';let server = null;let ident = null;// ticket #9 (mission 012): the exchanges ident RECEIVES from tickets, counted by a small proxy// between the two (tickets' IDENT_EXCHANGE_URL → here → our ident)const EXCH_PORT = Number(process.env.TICKETS_GATE_EXCHANGE_PORT || 8357);const exchanges = [];const exchProxy = http.createServer((req, res) => {let body = '';req.on('data', d => body += d);req.on('end', async () => {try {const r = await fetch(`http://127.0.0.1:${IDENT_PORT}${req.url}`, { method: req.method, headers: { 'content-type': req.headers['content-type'] || 'application/json' }, body: req.method === 'GET' ? undefined : body });const t = await r.text();let code = ''; try { code = JSON.parse(body).code || ''; } catch {}exchanges.push({ path: req.url, code, status: r.status });res.writeHead(r.status, { 'content-type': r.headers.get('content-type') || 'application/json' });res.end(t);} catch (e) { req.socket.destroy(); } // ident stopped: tickets must see NO answer, like a direct connection});});await new Promise((ok, bad) => { exchProxy.once('error', bad); exchProxy.listen(EXCH_PORT, '127.0.0.1', ok); });let APPKEY = null;function startTickets(extraEnv) {log += `\n==== tickets server start ${J(Object.keys(extraEnv))}\n`;server = spawn(BIN, ['project.hl'], {cwd: APP,env: { ...process.env, TICKETS_PORT: String(PORT), TICKETS_STORAGE: join(STORE, 'mpackdb'), TICKETS_SESSIONS: join(STORE, 'sessions'),IDENT_URL: `http://127.0.0.1:${IDENT_PORT}`, IDENT_EXCHANGE_URL: `http://127.0.0.1:${EXCH_PORT}`, TICKETS_PUBLIC_URL: BASE, IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret,TICKETS_CREATOR_IDENTITY: '', TICKETS_WATCH: '0', ...extraEnv },stdio: ['ignore', 'pipe', 'pipe'],});server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);}async function stopTickets() {if (!server) return;const s = server;try { s.kill('SIGTERM'); } catch {}await new Promise(r => { if (s.exitCode !== null || s.signalCode !== null) return r(); s.once('exit', r); setTimeout(r, 3000); });}async function ticketsUp() {for (const end = Date.now() + COLD_MS; Date.now() < end;) { try { const r = await fetch(BASE + '/'); if (r.ok) return; } catch {} await sleep(250); }throw new Error(`server did not come up within ${COLD_MS} ms\n` + log);}// THE API: reads never carry a token (reading is public); writes carry the gate user's// token unless another (or none: null) is givenlet TOKEN = null;const api = async (method, path, body, token = TOKEN) => {const headers = body ? { 'content-type': 'application/json' } : {};if (method !== 'GET' && token) headers.authorization = 'Bearer ' + token;const r = await fetch(BASE + path, { method, headers, body: body ? J(body) : undefined });let json = null; try { json = await r.json(); } catch {}return { status: r.status, json };};const runImport = (token = TOKEN) => {const r = spawnSync(BIN, ['tools/import.hl'], { cwd: APP, env: { ...process.env, TICKETS_URL: BASE, TICKETS_TOKEN: token || '' }, encoding: 'utf8', timeout: COLD_MS });return (r.stdout || '') + (r.stderr || '');};// a face over the REST carrier (POST /__hl/emit) with a cookie (or none)let emitI = 0;// hybriel#16 (mission 036): hl:web itself refuses an emit with one argument too many — the ack is// ok:false "… the `session` parameter is filled by the server, never by the peer"; the face never runs.const framework_refused = (raw) => { try { const j = JSON.parse(raw); return j.ok === false && /the `session` parameter is filled by the server/.test(j.error || ''); } catch { return false; } };const temit = async (event, payload, cookie) => {const r = await fetch(BASE + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: ++emitI, event, payload }) });const raw = await r.text();let j = null; try { j = JSON.parse(raw); } catch {}return { status: r.status, value: j ? j.value : undefined, raw };};const cookieOf = (r) => (r.headers.get('set-cookie') || '').split(';')[0];const texts = (page, sel) => page.evaluate(`Array.from(document.querySelectorAll(${J(sel)})).map(e => e.textContent.trim())`);// MISSION 016: the history as rows. A run of comments is ONE Comments block (components/comments/) in the history: each of its// comments is a row { kind 'comment', id, author, text (its Markdown, the block's hidden field), drawn (what the browser drew) };// every other entry a row { kind (the li's class), author, head, text (its event-text) }.const hist = (page) => page.evaluate(`[...document.querySelectorAll('#events > li')].flatMap(li => li.classList.contains('comments') ? [...li.querySelectorAll('li.comment')].map(c => ({ kind: 'comment', id: c.dataset.id, author: c.querySelector('.comment-author').textContent, text: (c.querySelector('md-editor[data-readonly="true"] input.value') || {}).value ?? '', drawn: (c.querySelector('md-editor[data-readonly="true"] article') || {}).textContent ?? '' })) : [{ kind: li.className, author: (li.querySelector('event-head strong') || {}).textContent ?? '', head: li.querySelector('event-head').textContent.replace(/\\s+/g, ' ').trim(), text: (li.querySelector('event-text:not(.edit)') || {}).textContent ?? '' }])`);// REAL keys: characters, '\n' = Enter; Shift+Enter (a line break in the MdEditor), Ctrl+Enter (sends the form), Endconst realKeys = async (page, text) => {for (const ch of text) {if (ch === '\n') {await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 });await page.send('Input.dispatchKeyEvent', { type: 'char', key: 'Enter', text: '\r' });await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 });} else {await page.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch });await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });}}};const modKey = async (page, key, modifiers, vk, text) => {await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key, code: key, windowsVirtualKeyCode: vk, modifiers });if (text) await page.send('Input.dispatchKeyEvent', { type: 'char', key, text, modifiers });await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key, code: key, windowsVirtualKeyCode: vk, modifiers });};const ctrlEnter = (page) => modKey(page, 'Enter', 2, 13);const shiftEnter = (page) => modKey(page, 'Enter', 8, 13, '\r');const endKey = (page) => modKey(page, 'End', 0, 35);// an MdEditor builds its content once the page is live (a CSS animation hands it over): wait until it shows `text`// a real click lands at the coordinates the element had when they were measured: a push re-draws the comments (the read-only// MdEditors build their text a moment later and move the buttons below them), and a press at the old spot hits nothing —// the server never saw the click (mission 019, "B: unliked"). So wait until the element has not moved for half a second.const calmClick = async (page, sel) => {await page.waitFor(`(() => { const e = document.querySelector(${J(sel)}); if (!e) return false; const r = e.getBoundingClientRect(), k = r.left + ',' + r.top + ',' + r.width + ',' + r.height, w = window.__calm || (window.__calm = { k: '', n: 0 }); w.n = w.k === k ? w.n + 1 : 0; w.k = k; return w.n >= 8; })()`, { label: 'calm: ' + sel, interval: 60 });await page.evaluate('delete window.__calm');await page.click(sel);};const mdShows = (page, sel, text, label) => page.waitFor(`(() => { const a = document.querySelector(${J(sel)}); return !!a && a.textContent === ${J(text)}; })()`, { label });const type = (page, sel, value) => page.evaluate(`(() => { const i = document.querySelector(${J(sel)}); i.value = ${J(value)}; i.dispatchEvent(new Event("input", { bubbles: true })); })()`);const choose = (page, sel, value) => page.evaluate(`(() => { const i = document.querySelector(${J(sel)}); i.value = ${J(value)}; i.dispatchEvent(new Event("change", { bubbles: true })); })()`);// CONNECTED = the server has READ the tab's `hello` (its mounts), not just an open socket: a push the server sends// before that reaches no component (mission 046: "inbox follows the state change live" failed ~1 in 5 when the API// write overtook the hello). A `ping` sent after the hello on the same socket is answered after it — its pong proves it.const helloRead = `new Promise((ok) => { const s = window.__hl.socket; const h = (ev) => { let f = null; try { f = JSON.parse(ev.data); } catch {} if (f && f.t === 'pong') { s.removeEventListener('message', h); ok(true); } }; s.addEventListener('message', h); s.send(JSON.stringify({ t: 'ping' })); setTimeout(() => ok(false), 10000); })`;const connected = async (page, label) => {await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label });if (!(await page.evaluate(helloRead))) throw new Error('no pong after the hello: ' + label);};// a client-side navigation by a REAL click, then the socket announced the new mountsconst clickNav = async (page, sel, cond, label) => { await page.click(sel); await page.waitFor(cond, { label }); await sleep(300); };async function viewport(page, width, height) {await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 });await sleep(250);}async function shot(page, name) {const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64'));}const noOverflow = (page) => page.evaluate('document.documentElement.scrollWidth <= window.innerWidth');// INSIDE ident's selector (shadow DOM): an expression over its root `r`, and a REAL clickconst sh = (expr) => `(() => { const h = document.querySelector('#selector'); const r = h && h.shadowRoot; if (!r) return null; return (${expr}); })()`;async function shClick(page, inner, name = null) {const find = `(() => { const h = document.querySelector('#selector'); const r = h && h.shadowRoot; if (!r) return null; const el = ${name === null ? `r.querySelector(${J(inner)})` : `[...r.querySelectorAll(${J(inner)})].find(b => b.textContent === ${J(name)})`}; if (!el) return null; el.scrollIntoView({ block: 'center' }); const b = el.getBoundingClientRect(); if (!b.width) return null; return { x: b.left + b.width / 2, y: b.top + b.height / 2 }; })()`;const box = await page.waitFor(find, { label: 'selector ' + inner + ' ' + (name || '') });const at = { x: Math.round(box.x), y: Math.round(box.y), button: 'left', clickCount: 1 };await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...at, buttons: 0 });await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...at, buttons: 1 });await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...at, buttons: 0 });}const connectedIdent = (page) => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'ident page hydrated' });// sign in to OUR ident on ident's own page (email → code from the sink → skip the names)async function identSignIn(page, email) {await page.goto(ident.base + '/');await page.waitForSelector('#email');await connectedIdent(page);await page.type('#email', email);await page.click('#sendcode');// ident#20: a sent code NAVIGATES to ident's /code page; type only once that page is hydratedawait page.waitFor('/\\/code$/.test(location.pathname) && !!document.querySelector("#code")', { label: 'ident /code page' });await connectedIdent(page);await page.type('#code', ident.lastCode(email));await page.click('#verify');await page.waitForSelector('#signout, #menusignout', { timeout: 10000 });}// TICKET #11 (mission 014): the gate must stay green while other browsers load the machine.// Every wait of a page (waitFor / waitForSelector / click / goto) gets SLOW× its timeout// (TICKETS_GATE_SLOW, default 3: 10 s → 30 s) — a wait that succeeds returns at once, so a green// run costs nothing; only a real failure waits longer before it says so.const SLOW = Number(process.env.TICKETS_GATE_SLOW || 3);function patient(page) {const waitFor = page.waitFor.bind(page);page.waitFor = (expr, o = {}) => waitFor(expr, { ...o, timeout: (o.timeout || 10000) * SLOW });const goto = page.goto.bind(page);page.goto = (url, o = {}) => goto(url, { ...o, timeout: (o.timeout || 15000) * SLOW });return page;}let A, B, C;const range = (v, dflt) => (v || dflt).split('-').map(Number);try {// ---- ticket #7: our own ident, tickets registered in it ----------------------------------ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });const alice = await ident.signIn('[email protected]');const bob = await ident.signIn('[email protected]');const gateAcct = await ident.signIn('[email protected]');APPKEY = await ident.registerApp(alice, 'tickets (gate)', [BASE]);check('ident: our own ident runs (a copy without .env), tickets is registered (key + secret)', /^pk_[0-9a-f]{32}$/.test(APPKEY.key) && /^sk_[0-9a-f]{48}$/.test(APPKEY.secret) && !existsSync(join(STORE, 'ident', 'ident-code', '.env')));// alice's per-app id — what the architect puts into TICKETS_CREATOR_IDENTITYconst ALICE_ID = await ident.exchange(APPKEY, await ident.selectorCode(alice, APPKEY, BASE));const GATE_ID = await ident.exchange(APPKEY, await ident.selectorCode(gateAcct, APPKEY, BASE));check('ident: one identity id per identity (a short id, or the old 32 hex)', /^[0-9a-z]{5,64}$/.test(ALICE_ID) && /^[0-9a-z]{5,64}$/.test(GATE_ID) && ALICE_ID !== GATE_ID, ALICE_ID + ' ' + GATE_ID);// ---- server #1: NO creator configured ---------------------------------------------------startTickets({});await ticketsUp();// the machine user "gate": the login button's SERVER half (ident → /login/callback?ident_code=)const first = await fetch(BASE + '/');let GATE_COOKIE_0 = '';// sessions are lazy (hybriel ac1ed9da): a plain page visit stores nothing and sets no cookie; the cookie comes with the first// thing a visitor stores. An upload start stores a session, so the visitor who is about to sign in gets his cookie from there.check('login: a plain page visit sets no cookie (sessions are lazy), the first thing stored gets the tickets session cookie (hlsid)', cookieOf(first) === '' && /^hlsid=[0-9a-f]+$/.test(await (async () => { const m = await fetch(BASE + '/__hl/upload', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name: 'a.bin', type: 'x', size: 1 }) }); await m.text(); GATE_COOKIE_0 = cookieOf(m); return GATE_COOKIE_0; })()), cookieOf(first) + ' / ' + GATE_COOKIE_0);let GATE_COOKIE = GATE_COOKIE_0;const noCode = await fetch(BASE + '/login/callback', { headers: { cookie: GATE_COOKIE }, redirect: 'manual' });check('login: /login/callback without a code → redirect to the app\'s error page (tickets#42), no session', noCode.status === 302 && noCode.headers.get('location') === '/login/failed/login-no-code' && !(noCode.headers.get('set-cookie') || '').includes('hlsid'));const badCode = await fetch(BASE + '/login/callback?ident_code=' + 'ab'.repeat(24), { headers: { cookie: GATE_COOKIE }, redirect: 'manual' });check('login: an unknown code → redirect to the error page "login-refused" (tickets#42), no session', badCode.status === 302 && badCode.headers.get('location') === '/login/failed/login-refused' && !(badCode.headers.get('set-cookie') || '').includes('hlsid'));const gateCode = await ident.selectorCode(gateAcct, APPKEY, BASE);const cb = await fetch(BASE + '/login/callback?ident_code=' + gateCode, { headers: { cookie: GATE_COOKIE }, redirect: 'manual' });check('login: /login/callback exchanges the code → 302 to /', cb.status === 302 && cb.headers.get('location') === '/', cb.status + ' ' + cb.headers.get('location'));// ident#28: the login stays on the session the browser brought (same cookie, same id); it is signed in afterwardsconst rotated = cookieOf(cb);check('login (ident#28): the login keeps the browser\'s session cookie and that cookie is signed in', (rotated === '' || rotated === GATE_COOKIE) && /^hlsid=[0-9a-f]+$/.test(GATE_COOKIE) && (await fetch(BASE + '/', { headers: { cookie: GATE_COOKIE } }).then(r => r.text())).includes('class="in"'), rotated + ' vs ' + GATE_COOKIE);if (rotated !== "") GATE_COOKIE = rotatedconst again = await fetch(BASE + '/login/callback?ident_code=' + gateCode, { headers: { cookie: GATE_COOKIE }, redirect: 'manual' });check('login: the same code again → redirect to the error page "login-refused" (single use; tickets#42)', again.status === 302 && again.headers.get('location') === '/login/failed/login-refused');// ticket #10: the button's return URL carries ?next=<page> (login.js); /login/callback follows// only a same-origin PATH, anything else → /for (const [next, want] of [['/projects/alpha/2', '/projects/alpha/2'], ['/project/alpha/state/open?x=1&y=2', '/project/alpha/state/open?x=1&y=2'], ['/inbox', '/inbox'],['/%2F%2Fevil.example', '/%2F%2Fevil.example'],['//evil.example/x', '/'], ['https://evil.example/', '/'], ['http:/evil.example', '/'], ['/\\evil.example', '/'], ['javascript:alert(1)', '/'],['evil.example', '/'], ['/a b', '/'], ['/x\r\nSet-Cookie: a=b', '/'], ['/x"><script>', '/'], ['/login/callback', '/'], ['/' + 'a'.repeat(500), '/'], ['', '/'],]) {const c = await ident.selectorCode(gateAcct, APPKEY, BASE);const r = await fetch(BASE + '/login/callback?next=' + encodeURIComponent(next) + '&ident_code=' + c, { headers: { cookie: GATE_COOKIE }, redirect: 'manual' });check(`return (#10): next=${J(next.length > 40 ? next.slice(0, 20) + '…(' + next.length + ')' : next)} → 302 ${want}`, r.status === 302 && r.headers.get('location') === want, r.status + ' ' + r.headers.get('location'));if (r.status === 302) GATE_COOKIE = cookieOf(r);}let html = await (await fetch(BASE + '/', { headers: { cookie: GATE_COOKIE } })).text();check('login: first login → the page asks for a display name, no write form yet', html.includes('id="nameform"') && !html.includes('id="newticketform"') && html.includes('class="in"'));check('login: the page never carries the identity id (only /you does)', !html.includes(GATE_ID));let f = await temit('commentOn', ['x', 'before the name'], GATE_COOKIE);check('login: no writing before a display name', f.value && /display name first/.test(f.value.error), f.raw);f = await temit('saveDisplayName', [' '], GATE_COOKIE);check('name: an empty display name is refused', f.value && /must not be empty/.test(f.value.error), f.raw);f = await temit('saveDisplayName', ['x'.repeat(61)], GATE_COOKIE);check('name: 61 characters are refused', f.value && /too long/.test(f.value.error), f.raw);f = await temit('saveDisplayName', ['gate'], GATE_COOKIE);check('name: "gate" saved (answer: name, named — no identity id)', f.value && f.value.name === 'gate' && f.value.named === true && !f.raw.includes(GATE_ID), f.raw);f = await temit('saveDisplayName', ['gate2'], GATE_COOKIE);check('name: asked once — a second name is refused', f.value && /already set/.test(f.value.error), f.raw);html = await (await fetch(BASE + '/', { headers: { cookie: GATE_COOKIE } })).text();check('name: afterwards no prompt; no role yet → no ticket form, a role hint (ticket #20)', !html.includes('id="nameform"') && !html.includes('id="newticketform"') && html.includes('id="rolehint"'));f = await temit('tokenCreate', ['gate machine'], GATE_COOKIE);TOKEN = f.value && f.value.token;check('token: created over the face — tkt_ + 48 hex, listed with its label', /^tkt_[0-9a-f]{48}$/.test(TOKEN || '') && f.value.tokens.length === 1 && f.value.tokens[0].label === 'gate machine' && !J(f.value.tokens).includes(TOKEN), f.raw);const you0 = await (await fetch(BASE + '/you', { headers: { cookie: GATE_COOKIE } })).text();check('/you shows the user its own ident id and "not a member of any project yet"', you0.includes(GATE_ID) && /not a member of any project yet/.test(you0) && !you0.includes(TOKEN));// ticket #20: the legacy projects have NO admin yet (no creator configured) and the gate user is no member: every write is refusedconst nm1 = await api('POST', '/api/tickets/1/comments', { text: 'not a member' });const nm2 = await api('POST', '/api/projects/alpha/tickets/1/state', { state: 'review' });const nm3 = await api('POST', '/api/projects/alpha/tickets', { subject: 'not a member' });check('roles: a non-member cannot comment / change the state / open a ticket → 403, nothing written', nm1.status === 403 && nm2.status === 403 && nm3.status === 403 && (await api('GET', '/api/tickets/1')).json.events.length === 3, J([nm1, nm2, nm3]) + J([(await api('GET', '/api/projects/alpha')).status, (await api('GET', '/api/tickets/1')).status]) + log.slice(-900) + log.slice(-600));check('migration: at the first start the log says what was migrated', /migrated: 2 project\(s\) turned into records/.test(log) && /migrated: 5 ticket\(s\) linked to their project by id/.test(log), log.slice(0, 400));await stopTickets();// ---- server #2: the gate user is the creator → admin of the legacy projects (its session + token survive) --startTickets({ TICKETS_CREATOR_IDENTITY: GATE_ID });await ticketsUp();html = await (await fetch(BASE + '/', { headers: { cookie: GATE_COOKIE } })).text();check('restart: the gate user is still logged in (session on disk)', /id="whoami"[^>]*>gate</.test(html), html.slice(0, 200));// ---- the migrated legacy tickets: old numbers still answer (ticket #38) ---------------const PT = (slug, n) => `/api/projects/${slug}/tickets/${n}`;const old1 = await api('GET', '/api/tickets/1');check('legacy: GET /api/tickets/1 (old number) answers alpha #1 with project, number, href, oldNumber',old1.status === 200 && old1.json.ticket.project === 'alpha' && old1.json.ticket.number === 1 && old1.json.ticket.ref === '#1' && old1.json.ticket.oldNumber === 1&& old1.json.ticket.href === '/alpha/1' && old1.json.ticket.apiHref === PT('alpha', 1) && /^[0-9a-z]{8,}$/.test(old1.json.ticket.id), J(old1.json).slice(0, 500));check('legacy: history kept in order with authors, texts and times (same ms → old order)',J(old1.json.events.map(e => [e.seq, e.kind, e.author, e.text, e.to, e.createdMs])) === J([[1, 'created', 'creator', '', '', 1790000000000], [2, 'comment', 'worker', 'legacy comment on one', '', 1790000300000], [3, 'state', 'worker', 'started', 'progress', 1790000300000]]), J(old1.json.events));check('legacy: state, subject, times and event count kept', old1.json.ticket.state === 'progress' && old1.json.ticket.subject === 'Legacy alpha one' && old1.json.ticket.createdMs === 1790000000000 && old1.json.ticket.updatedMs === 1790000300000 && old1.json.ticket.events === 3, J(old1.json.ticket));const a2 = await api('GET', PT('alpha', 2));check('legacy: GET /api/projects/alpha/tickets/2 is old #3 (per-project form)', a2.status === 200 && a2.json.ticket.oldNumber === 3 && a2.json.ticket.subject === 'Question: legacy alpha two' && J(a2.json.events.map(e => e.kind)) === J(['created', 'comment']), J(a2.json).slice(0, 300));check('legacy: old #4 is alpha #3, old #5 is beta.example.org #2', (await api('GET', '/api/tickets/4')).json.ticket.href === '/alpha/3' && (await api('GET', '/api/tickets/5')).json.ticket.href === '/beta.example.org/2');const byUuid = await api('GET', '/api/tickets/' + old1.json.ticket.id);check('legacy: /api/tickets/<uuid> answers the same ticket', byUuid.status === 200 && byUuid.json.ticket.href === '/alpha/1');check('legacy: unknown old number / number / project → 404', (await api('GET', '/api/tickets/6')).status === 404 && (await api('GET', PT('alpha', 4))).status === 404 && (await api('GET', PT('nope', 1))).status === 404 && (await api('GET', '/api/projects/nope/tickets')).status === 404);const oldCmt = await api('POST', '/api/tickets/4/comments', { text: 'via the old number' });check('legacy: POST /api/tickets/4/comments (old number, gate token) → 201, lands on alpha #3, author = the token\'s user', oldCmt.status === 201 && oldCmt.json.event.author === 'gate' && oldCmt.json.ticket.href === '/alpha/3' && oldCmt.json.ticket.oldNumber === 4 && oldCmt.json.event.seq === 2 && oldCmt.json.event.number === 3 && oldCmt.json.event.project === 'alpha', J(oldCmt.json));const newCmt = await api('POST', PT('alpha', 3) + '/comments', { text: 'via the project number' });check('legacy: POST /api/projects/alpha/tickets/3/comments → 201 on the same ticket', newCmt.status === 201 && newCmt.json.ticket.id === oldCmt.json.ticket.id && newCmt.json.ticket.events === 3);const newSt = await api('POST', PT('beta.example.org', 2) + '/state', { state: 'on-hold', text: 'parked' });check('legacy: POST /api/projects/beta.example.org/tickets/2/state → 201', newSt.status === 201 && newSt.json.ticket.state === 'pending' && (await api('GET', '/api/tickets/5')).json.ticket.state === 'pending', J(newSt.json));const a4 = await api('POST', '/api/projects/alpha/tickets', { subject: 'New alpha after the migration' });check('numbers: POST /api/projects/alpha/tickets → alpha #4, no old number', a4.status === 201 && a4.json.ticket.number === 4 && a4.json.ticket.href === '/alpha/4' && !('oldNumber' in a4.json.ticket) && a4.json.ticket.hasOld === false, J(a4.json));for (const t of ['gamma', 'antcolony', 'tickets.worldapi.org', 'ident.worldapi.org', 'gitoria.worldapi.org']) await api('POST', '/api/projects', { title: t, slug: t });const g1 = await api('POST', '/api/tickets', { project: 'gamma', subject: 'first of a new project' });check('numbers: a new project starts at 1 (POST /api/tickets)', g1.status === 201 && g1.json.ticket.project === 'gamma' && g1.json.ticket.number === 1 && g1.json.ticket.href === '/gamma/1', J(g1.json));const g2 = await api('POST', '/api/tickets', { project: 'gamma', subject: 'second of gamma' });check('numbers: … and counts on (gamma #2)', g2.json.ticket.number === 2 && (await api('GET', PT('gamma', 2))).json.ticket.subject === 'second of gamma');check('numbers: the per-project POST refuses a project field (strict)', (await api('POST', '/api/projects/alpha/tickets', { subject: 's', project: 'alpha' })).json.field === 'project');const redir = await fetch(BASE + '/tickets/3', { redirect: 'manual' });check('legacy: GET /tickets/3 (old page URL) → 301 Location /alpha/2', redir.status === 301 && redir.headers.get('location') === '/alpha/2', redir.status + ' ' + redir.headers.get('location'));check('legacy: GET /tickets/99 → 404', (await fetch(BASE + '/tickets/99', { redirect: 'manual' })).status === 404);const LEGACY = (await api('GET', '/api/tickets')).json.tickets.length; // 5 migrated + alpha #4 + gamma #1, #2// ---- import: the five AntColony ticket files, twice ----------------------------------const imp0 = runImport(null);check('import: without TICKETS_TOKEN every file is refused (401), nothing written', /import: 0 new, 0 already there, 5 failed/.test(imp0) && /FAIL .*: 401/.test(imp0) && (await api('GET', '/api/tickets')).json.tickets.length === LEGACY, imp0);const imp1 = runImport();check('import: first run creates all five', /import: 5 new, 0 already there, 0 failed/.test(imp1), imp1);check('import: numbered per project (antcolony #1, #2)', /NEW 0004-scheduler\.md → antcolony #1/.test(imp1) && /NEW 0005-agent\.md → antcolony #2/.test(imp1) && /NEW 0001-tickets-app\.md → tickets\.worldapi\.org #1/.test(imp1), imp1);const imp2 = runImport();check('import: second run is idempotent (0 new, 5 already there)', /import: 0 new, 5 already there, 0 failed/.test(imp2), imp2);let list = await api('GET', '/api/tickets');const TOTAL = LEGACY + 5;check('api: GET /api/tickets lists five more after two imports', list.status === 200 && list.json.tickets.length === TOTAL && list.json.tickets.filter(t => t.source).length === 5, J(list).slice(0, 300));let one = await api('GET', PT('tickets.worldapi.org', 1));check('api: tickets.worldapi.org #1 is the first file (project, subject, summary, a created event)',one.status === 200 && one.json.ticket.project === 'tickets.worldapi.org' && one.json.ticket.subject === 'Build the World Ticket System in Hybriel'&& one.json.ticket.summary.startsWith('Everyone can write everyone a ticket. This is the only state store of AntColony, so it comes first. Minimal scope:')&& one.json.events.length === 1 && one.json.events[0].kind === 'created' && one.json.events[0].text === 'imported from 0001-tickets-app.md' && one.json.events[0].author === 'gate', J(one.json).slice(0, 400));check('api: antcolony #1 is the scheduler file', (await api('GET', PT('antcolony', 1))).json.ticket.source === '0004-scheduler.md');check('api: unknown ticket is a 404', (await api('GET', '/api/tickets/99')).status === 404 && (await api('GET', PT('antcolony', 99))).status === 404);check('api: a ticket without subject is refused (400)', (await api('POST', '/api/tickets', { project: 'x' })).status === 400);check('api: an unknown state is refused (400)', (await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'nope' })).status === 400);check('api: an empty comment is refused (400)', (await api('POST', PT('ident.worldapi.org', 1) + '/comments', { text: ' ' })).status === 400);check('api: filter by project', (await api('GET', '/api/tickets?project=antcolony')).json.tickets.length === 2 && (await api('GET', '/api/projects/antcolony/tickets')).json.tickets.length === 2);check('api: filter by project + state on the per-project list', (await api('GET', '/api/projects/alpha/tickets?state=in-progress')).json.tickets.map(t => t.number).join() === '1');const projects = await api('GET', '/api/projects');const imported = (await api('GET', '/api/tickets')).json.tickets.filter(t => t.source);check('import: hard-wrapped lines are joined (no line break left in the five)', imported.length === 5 && imported.every(t => !t.summary.includes('\n')));check('api: projects (creation order) and states', J(projects.json.projects) === J(['alpha', 'beta.example.org', 'gamma', 'antcolony', 'tickets.worldapi.org', 'ident.worldapi.org', 'gitoria.worldapi.org']) && projects.json.states.length === 7, J(projects.json));// ---- the API is strict (ticket #10): every refused body writes NOTHING ----------------const rawPost = async (path, raw, auth = 'Bearer ' + TOKEN) => {const r = await fetch(BASE + path, { method: 'POST', headers: { 'content-type': 'application/json', ...(auth ? { authorization: auth } : {}) }, body: raw });let json = null; try { json = await r.clone().json(); } catch {}return { status: r.status, json, text: json ? '' : await r.text() };};const strictCases = [// [path, raw body, expected status, expected `field` (null = none), error must include]['/api/tickets', J({ project: 'x', subject: 's', bogus: '1' }), 400, 'bogus', "unknown field 'bogus'"],['/api/tickets', J({ project: 'x', subject: 's', Subject: 't' }), 400, 'Subject', "unknown field 'Subject'"],['/api/tickets', J({ project: 'x' }), 400, 'subject', "field 'subject' is required"],['/api/tickets', J({ subject: 's' }), 400, 'project', "field 'project' is required"],['/api/tickets', J({ project: 'x', subject: ' ' }), 400, 'subject', "field 'subject' must not be empty"],['/api/tickets', J({ project: '', subject: 's' }), 400, 'project', "field 'project' must not be empty"],['/api/tickets', J({ project: 'x', subject: 5 }), 400, 'subject', "field 'subject' must be a string"],['/api/tickets', J({ project: 'x', subject: 's', summary: null }), 400, 'summary', "field 'summary' must be a string"],['/api/tickets', J({ project: 'a b', subject: 's' }), 400, 'project', 'no such project'],// ticket #7: NO free author any more — the author is the token's user; a body naming one is refused['/api/tickets', J({ project: 'x', subject: 's', author: ['a'] }), 400, 'author', "no field 'author' any more"],['/api/tickets', J({ project: 'x', subject: 's', author: 'gate' }), 400, 'author', "no field 'author' any more: the author is the user of your API token"],['/api/tickets', J({ project: 'x', subject: 's', summary: 'y', author: ' ' }), 400, 'author', "no field 'author' any more"],['/api/tickets/2/comments', J({ text: 'x', author: 'creator' }), 400, 'author', "no field 'author' any more"],['/api/tickets/2/comments', J({ text: 'x', author: '' }), 400, 'author', "no field 'author' any more"],['/api/tickets/2/state', J({ state: 'in progress', author: 'creator' }), 400, 'author', "no field 'author' any more"],['/api/tickets/2/state', J({ state: 'confirmed', text: 'n', author: ' ' }), 400, 'author', "no field 'author' any more"],['/api/tickets', J([1, 2]), 400, '', 'must be a JSON object'],['/api/tickets', J('text'), 400, '', 'must be a JSON object'],['/api/tickets', '', 400, '', 'must be a JSON object'],['/api/tickets/2/comments', J({ text: 'hi', state: 'open' }), 400, 'state', "unknown field 'state'"],['/api/tickets/2/comments', J({}), 400, 'text', "field 'text' is required"],['/api/tickets/2/comments', J({ text: ' ' }), 400, 'text', "field 'text' must not be empty"],['/api/tickets/2/comments', J({ text: { a: 1 } }), 400, 'text', "field 'text' must be a string"],['/api/tickets/2/comments', J({ text: true }), 400, 'text', "field 'text' must be a string"],['/api/tickets/2/comments', J({ text: 'x', author: 7 }), 400, 'author', "no field 'author' any more"],['/api/tickets/2/state', J({ state: 'open', note: 'x' }), 400, 'note', "unknown field 'note'"],['/api/tickets/2/state', J({ text: 'x' }), 400, 'state', "field 'state' is required"],['/api/tickets/2/state', J({ state: '' }), 400, 'state', "field 'state' must not be empty"],['/api/tickets/2/state', J({ state: 3 }), 400, 'state', "field 'state' must be a string"],['/api/tickets/2/state', J({ state: 'nope' }), 400, 'state', 'unknown state'],['/api/tickets/2/state', J({ state: 'open' }), 400, 'state', 'already open'],['/api/tickets/99/comments', J({ text: 'x' }), 404, null, 'no such ticket'],// ticket #38: the slug is the project name, so a new name must be URL-safe; the per-project form is as strict['/api/tickets', J({ project: 'a#b', subject: 's' }), 400, 'project', 'no such project'],['/api/tickets', J({ project: 'ä', subject: 's' }), 400, 'project', 'no such project'],['/api/projects/beta.example.org/tickets/1/comments', J({ text: 'x', author: 'a' }), 400, 'author', "no field 'author' any more"],['/api/projects/beta.example.org/tickets/1/comments', J({ text: 'x', bogus: '1' }), 400, 'bogus', "unknown field 'bogus'"],['/api/projects/beta.example.org/tickets/1/state', J({ state: 'open' }), 400, 'state', 'already open'],['/api/projects/beta.example.org/tickets/1/state', J({ state: 5 }), 400, 'state', "field 'state' must be a string"],['/api/projects/beta.example.org/tickets', J({ subject: 's', author: 'a' }), 400, 'author', "no field 'author' any more"],['/api/projects/beta.example.org/tickets/9/comments', J({ text: 'x' }), 404, null, 'no such ticket'],['/api/projects/beta.example.org/tickets/x/comments', J({ text: 'x' }), 404, null, 'no such ticket'],];for (const [path, raw, want, field, says] of strictCases) {const r = await rawPost(path, raw);const ok = r.status === want && r.json && typeof r.json.error === 'string' && r.json.error.includes(says) && (field === null || r.json.field === field);check(`strict: POST ${path} ${raw || '(empty)'} → ${want}${field ? ' naming ' + field : ''}`, ok, r.status + ' ' + J(r.json) + r.text);}// invalid JSON (ticket #15): refused by jsoncheck.hl BEFORE JSON.parse → 400 { error },// no source path (workaround for hybriel #12: an uncaught JSON.parse answered 500 + api.hl:31:9)const badJsonCases = [['/api/tickets', '{"project":"x",', 15], ['/api/tickets', '{bad', 1], ['/api/tickets', "{'project':'x'}", 1],['/api/tickets', '{"project":"x","subject":"s","summary":"a",}', 43], ['/api/tickets', '[1 2]', 3],['/api/tickets/2/comments', '{"text":"x","n":"a"} trailing', 21], ['/api/tickets/2/comments', '{"text":"\\x","n":"a"}', 10],['/api/tickets/2/state', '{"state":01}', 10], ['/api/tickets/2/state', '['.repeat(70), 64], ['/api/tickets/2/state', ' ', 3],// LONE \u surrogate escapes: hl's JSON.parse still refuses them (would be a 500) → refused by the check// (a valid pair parses since hybriel#15, mission 036: see the two checks below)['/api/tickets/2/comments', '{"text":"\\ud800"}', 10], ['/api/tickets/2/comments', '{"text":"\\udc00"}', 10],['/api/tickets/2/comments', '{"text":"\\ud83dx"}', 10], ['/api/tickets/2/comments', '{"text":"\\ud83d\\u0041"}', 10],];for (const [path, raw, at] of badJsonCases) {const r = await rawPost(path, raw);const ok = r.status === 400 && r.json && J(Object.keys(r.json)) === J(['error']) && r.json.error === 'invalid JSON at character ' + at && !/\.hl|\//.test(r.json.error);check(`strict: invalid JSON POST ${path} ${raw.length > 40 ? raw.slice(0, 40) + '…' : raw} → 400 at ${at}, no source path`, ok, r.status + ' ' + J(r.json) + r.text);}// valid but unusual JSON is NOT mistaken for invalid (escapes, unicode, numbers, nesting) → normal field errorsconst oddValid = await rawPost('/api/tickets/2/comments', '{ "text" : "q\\"b\\\\s\\/\\u00e9\\n", "n": [-1.5e+3, 0, true, null, {"x":[]}] }');check('strict: valid unusual JSON passes the check (→ unknown field n, not invalid JSON)', oddValid.status === 400 && oddValid.json && oddValid.json.field === 'n', oddValid.status + ' ' + J(oddValid.json) + oddValid.text);const pairOnly = await rawPost('/api/tickets/2/comments', '{"text":"\\ud83d\\ude00","n":"a"}');check('strict: a valid \\u surrogate pair passes the check (hybriel#15 → unknown field n, not invalid JSON)', pairOnly.status === 400 && pairOnly.json && pairOnly.json.field === 'n', pairOnly.status + ' ' + J(pairOnly.json) + pairOnly.text);const escaped = await rawPost('/api/tickets/3/comments', '{"text":"q\\"b\\\\s\\/\\u00e9 \u{1F600} end \\ud83d\\ude00"}');check('strict: a comment with JSON escapes (\\" \\\\ \\/ \\u00e9 \\ud83d\\ude00) and a raw emoji is stored decoded (201)', escaped.status === 201 && escaped.json.event.text === 'q"b\\s/\u00e9 \u{1F600} end \u{1F600}', escaped.status + ' ' + J(escaped.json) + escaped.text);const afterStrict = await api('GET', '/api/tickets');check('strict: the refused requests wrote nothing (same ticket count, old #2 = beta.example.org #1 has one event)', afterStrict.json.tickets.length === TOTAL && (await api('GET', '/api/tickets/2')).json.events.length === 1 && (await api('GET', PT('beta.example.org', 1))).json.events.length === 1, J(afterStrict.json.tickets.map(t => t.ref)));check('strict: GET /api/inbox refuses POST (405)', (await rawPost('/api/inbox', '{}')).status === 405);// ---- ticket #7: API writes need a valid token — 401 BEFORE the body is looked at ----------const before401 = J((await api('GET', '/api/tickets')).json.tickets.map(t => [t.ref, t.events]));const authCases = [// [path, raw body, Authorization header (null = none), label]['/api/tickets', J({ project: 'x', subject: 's' }), null, 'no token'],['/api/projects/alpha/tickets', J({ subject: 's' }), null, 'no token'],['/api/tickets/2/comments', J({ text: 'x' }), null, 'no token'],['/api/projects/alpha/tickets/1/comments', J({ text: 'x' }), null, 'no token'],['/api/tickets/2/state', J({ state: 'in progress' }), null, 'no token'],['/api/projects/alpha/tickets/1/state', J({ state: 'on hold' }), null, 'no token'],['/api/tickets/2/comments', J({ text: 'x' }), 'Bearer tkt_' + '0'.repeat(48), 'an unknown token'],['/api/tickets/2/comments', J({ text: 'x' }), 'Bearer ' + TOKEN + '0', 'a token with one character more'],['/api/tickets/2/comments', J({ text: 'x' }), 'Bearer ' + TOKEN.slice(0, -1), 'a token with one character less'],['/api/tickets/2/comments', J({ text: 'x' }), TOKEN, 'the token without "Bearer"'],['/api/tickets/2/comments', J({ text: 'x' }), 'Basic ' + TOKEN, 'Basic instead of Bearer'],['/api/tickets/2/comments', J({ text: 'x' }), 'Bearer ', 'an empty Bearer'],['/api/tickets/2/comments', '{bad', null, 'no token + invalid JSON (auth first)'],['/api/tickets/2/comments', J({ text: 'x', author: 'creator' }), null, 'no token + an author field (auth first)'],];for (const [path, raw, auth, label] of authCases) {const r = await rawPost(path, raw, auth);check(`auth: POST ${path} with ${label} → 401`, r.status === 401 && r.json && /Authorization: Bearer/.test(r.json.error), r.status + ' ' + J(r.json) + r.text);}check('auth: the refused writes wrote nothing', J((await api('GET', '/api/tickets')).json.tickets.map(t => [t.ref, t.events])) === before401);const anonRead = await fetch(BASE + '/api/tickets/1');check('auth: reading needs no token (GET without Authorization → 200)', anonRead.status === 200);// ---- local time (ticket #10): Europe/Vienna, storage stays epoch ms -----------------------const vienna = new Intl.DateTimeFormat('sv-SE', { timeZone: 'Europe/Vienna', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' });const lt = spawnSync(BIN, ['tests/localtime.hl'], { cwd: APP, encoding: 'utf8', timeout: COLD_MS });const ltLines = (lt.stdout || '').trim().split('\n').filter(Boolean);const ltBad = ltLines.filter(l => { const [ms, ...rest] = l.split(' '); return vienna.format(new Date(Number(ms))) !== rest.join(' '); });check('time: localtime.hl matches Intl Europe/Vienna on DST edges 2000–2100', ltLines.length === 11 && ltBad.length === 0, J(ltBad) + (lt.stderr || ''));const t2 = (await api('GET', PT('ident.worldapi.org', 1))).json;check('time: API rows render updatedMs / createdMs in Vienna time', t2.ticket.updated === vienna.format(new Date(t2.ticket.updatedMs)) && t2.events[0].when === vienna.format(new Date(t2.events[0].createdMs)), J([t2.ticket.updated, t2.ticket.updatedMs, t2.events[0].when]));// ---- two viewers ------------------------------------------------------------------A = await launchBrowser({ debugPortRange: range(process.env.TICKETS_GATE_CHROME_A, '8620-8629') });B = await launchBrowser({ debugPortRange: range(process.env.TICKETS_GATE_CHROME_B, '8630-8639') });const a = patient(await A.newPage());const b = patient(await B.newPage());// SSR of the listawait a.goto(BASE + '/');await a.waitForSelector('#tickets li');await connected(a, 'A connected');check('list: SSR shows every ticket (migrated + new + imported)', (await texts(a, '#tickets li')).length === TOTAL, J(await texts(a, '#tickets li')));check('list: every row has a state badge, a #ref link and its project', await a.evaluate(`Array.from(document.querySelectorAll('#tickets li')).every(li => li.querySelector('ticket-state') && /^#\\d+/.test(li.querySelector('a.subject').textContent) && li.querySelector('ticket-meta a'))`));check('list: every ticket link is /<project>/<number> of its row (ticket #25)', await a.evaluate(`Array.from(document.querySelectorAll('#tickets li')).every(li => li.querySelector('a.subject').getAttribute('href') === '/' + li.querySelector('ticket-meta a').textContent + '/' + li.querySelector('ticket-ref').textContent.slice(1))`));check('list: the project filter offers all seven projects', (await texts(a, '#projectfilter a')).length === 8, J(await texts(a, '#projectfilter a')));check('list: palette — accent is purple #c586c0, danger #f44747; the brand is the theme\'s white title (mission 022: it was the accent)', await a.evaluate(`(() => { const cs = getComputedStyle(document.documentElement); return cs.getPropertyValue('--color-accent').trim() === '#c586c0' && getComputedStyle(document.querySelector('.brand')).color === 'rgb(245, 250, 255)' && getComputedStyle(document.body).backgroundColor === 'rgb(25, 30, 35)'; })()`), await a.evaluate(`getComputedStyle(document.querySelector('.brand')).color + ' ' + getComputedStyle(document.body).backgroundColor`));check('list: danger token resolves to #f44747', await a.evaluate(`(() => { const s = document.createElement('span'); s.style.color = 'var(--color-danger)'; document.body.append(s); const c = getComputedStyle(s).color; s.remove(); return c; })()`) === 'rgb(244, 71, 71)');// filters by real clicks (client-side navigation)await clickNav(a, '#projectfilter a[href="/project/antcolony"]', 'location.pathname === "/project/antcolony" && document.querySelectorAll("#tickets li").length === 2', 'project filter');check('filter: project antcolony shows its two tickets', J(await texts(a, '#tickets ticket-meta a')) === J(['antcolony', 'antcolony']), J(await texts(a, '#tickets ticket-meta a')));check('filter: the chosen project is marked selected', (await a.text('#projectfilter a.selected')) === 'antcolony');await clickNav(a, '#statefilter a[href="/project/antcolony/state/progress"]', 'location.pathname === "/project/antcolony/state/progress" && !!document.querySelector("#empty")', 'state filter');check('filter: project + state "progress" is empty (nothing in progress yet)', (await texts(a, '#tickets li')).length === 0);await clickNav(a, '#statefilter a[href="/project/antcolony"]', 'document.querySelectorAll("#tickets li").length === 2', 'state filter cleared');check('filter: clearing the state keeps the project', (await a.evaluate('location.pathname')) === '/project/antcolony');await a.goto(BASE + '/state/open');await a.waitForSelector('#tickets li');const OPEN = (await api('GET', '/api/tickets?state=open')).json.tickets.length;check('filter: /state/open by URL (SSR) shows every open ticket', (await texts(a, '#tickets li')).length === OPEN, OPEN);// ---- a migrated ticket in the browser: the old URL redirects, a real click opens the new oneawait a.goto(BASE + '/tickets/4');await a.waitForSelector('#subject');check('legacy: the old URL /tickets/4 lands on /alpha/3 (redirect in the browser)', (await a.evaluate('location.pathname')) === '/alpha/3' && (await a.text('#subject')) === 'Legacy alpha three' && (await a.text('#ref')) === '#3', await a.evaluate('location.href'));check('legacy: the page says "formerly #4"', (await a.text('#oldref')) === 'formerly #4', await a.text('#oldref'));await a.waitFor('document.querySelectorAll("#events li.comment").length === 2', { label: 'legacy: both API comments in the block' });const legacyH = await hist(a);check('legacy: its history holds the created event and both API comments, in order', J(legacyH.map(h => h.kind + ':' + h.text)) === J(['created:', 'comment:via the old number', 'comment:via the project number']), J(legacyH));await a.goto(BASE + '/project/alpha');await a.waitForSelector('#tickets li');await connected(a, 'A on alpha');await clickNav(a, '#tickets a.subject[href="/alpha/1"]', 'location.pathname === "/alpha/1" && !!document.querySelector("#events li.comment")', 'click alpha #1');const legacy1 = await hist(a);check('legacy: a real click on a list row opens /alpha/1 (old #1, history in order)', (await a.text('#subject')) === 'Legacy alpha one' && (await a.text('#oldref')) === 'formerly #1' && J(legacy1.filter(h => h.text).map(h => h.text)) === J(['legacy comment on one', 'started']), J(legacy1));await a.goto(BASE + '/gamma/1');await a.waitForSelector('#subject');check('numbers: a new ticket has no "formerly"', (await a.text('#ref')) === '#1' && !(await a.evaluate('!!document.querySelector("#oldref")')));await a.goto(BASE + '/alpha/99');await a.waitForSelector('#gone');check('numbers: an unknown number shows "no such ticket"', (await a.text('#gone')).includes('no such ticket'));await a.goto(BASE + '/gamma');await a.waitForSelector('#tickets li');check('numbers: /<slug> lists that project', (await texts(a, '#tickets li')).length === 2 && (await a.text('#heading')) === 'gamma');// ---- ticket #25: short URLs /<slug>, /<slug>/<number>; every old page URL answers 301; hl:web's own urls stay its ownconst SHORT_SSR = [['/gamma', 'id="heading">gamma<'], ['/gamma/1', 'first of a new project'], ['/beta.example.org/2', 'Legacy beta two'], ['/alpha/3', 'Legacy alpha three']];for (const [path, want] of SHORT_SSR) {const r = await fetch(BASE + path, { redirect: 'manual' });const body = await r.text();check(`short (#25): GET ${path} → 200, the page itself (SSR)`, r.status === 200 && body.includes(want), r.status + ' ' + body.slice(0, 200));}for (const [from, to] of [['/projects/gamma', '/gamma'], ['/projects/gamma/1', '/gamma/1'], ['/projects/gamma/tickets/2', '/gamma/2'], ['/projects/beta.example.org/tickets/2', '/beta.example.org/2'], ['/projects/alpha/3', '/alpha/3'], ['/tickets/5', '/beta.example.org/2']]) {const r = await fetch(BASE + from, { redirect: 'manual' });check(`short (#25): old ${from} → 301 Location ${to}`, r.status === 301 && r.headers.get('location') === to, r.status + ' ' + r.headers.get('location'));}for (const from of ['/projects/nope', '/projects/nope/1', '/projects/gamma/99', '/projects/gamma/tickets/99', '/projects/gamma/tickets/x', '/projects/gamma/%0d%0aSet-Cookie:x']) {const r = await fetch(BASE + from, { redirect: 'manual' });check(`short (#25): old ${from} names nothing → 404, no Location`, r.status === 404 && !r.headers.get('location'), r.status + ' ' + r.headers.get('location'));}const ssrNope = await (await fetch(BASE + '/nope')).text();check('short (#25): /nope (no such project) → the page says so', /no such project|nope/i.test(ssrNope) && ssrNope.includes('id="heading">nope<'), ssrNope.slice(0, 200));// hl:web appends its own urls AFTER the app's routes; /:projectSlug/:ticketNumber must not answer them (project.hl moves it last)for (const [path, type] of [['/__hl/app.css', 'text/css'], ['/__hl/hl-runtime.js', 'text/javascript'], ['/__hl/sw.js', 'text/javascript'], ['/__hl/manifest.webmanifest', 'application/manifest+json'], ['/__hl/web/client.js', 'text/javascript'], ['/components/ticket.hl', 'text/javascript'], ['/components/ticket_list.hl', 'text/javascript'], ['/components/main.hl', 'text/javascript']]) {const r = await fetch(BASE + path);const body = await r.text();check(`short (#25): hl:web's ${path} is still its own (${type}, no page)`, r.status === 200 && (r.headers.get('content-type') || '').startsWith(type) && !body.startsWith('<!doctype'), r.status + ' ' + r.headers.get('content-type'));}const em = await fetch(BASE + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ t: 'emit', i: 1, event: 'nosuchface', payload: [] }) });check('short (#25): POST /__hl/emit is still hl:web\'s carrier (JSON ack)', em.status === 200 && /"ok":false/.test(await em.text()));// in the browser: an old link lands on the short URL; the project link on the ticket page is a CLIENT navigation to /<slug>await a.goto(BASE + '/projects/gamma/tickets/1');await a.waitForSelector('#subject');check('short (#25): Chrome on /projects/gamma/tickets/1 lands on /gamma/1', (await a.evaluate('location.pathname')) === '/gamma/1' && (await a.text('#subject')) === 'first of a new project', await a.evaluate('location.href'));await connected(a, 'A on /gamma/1');await a.evaluate('window.__w083 = 1');check('short (#25): the ticket page links its project as /gamma', (await a.evaluate('document.querySelector("#project").getAttribute("href")')) === '/gamma');await clickNav(a, '#project', 'location.pathname === "/gamma" && document.querySelectorAll("#tickets li").length === 2', 'click the project');check('short (#25): a click on the project → /gamma, its list, without a reload', (await a.evaluate('window.__w083')) === 1 && (await a.text('#heading')) === 'gamma');await clickNav(a, '#tickets a.subject[href="/gamma/2"]', 'location.pathname === "/gamma/2" && !!document.querySelector("#subject")', 'click gamma #2');check('short (#25): … and a click on a row → /gamma/2, without a reload', (await a.evaluate('window.__w083')) === 1 && (await a.text('#subject')) === 'second of gamma');// reserved slugs: no project may be named like a path the app answers itselffor (const slug of ['api', 'Inbox', '__hl', 'components', 'projects', 'tickets', 'login.js', 'my', 'assets', 'sign-in']) {const r = await api('POST', '/api/projects', { title: 'Reserved ' + slug, slug });check(`short (#25): a new project with the slug ${slug} → 400 reserved`, r.status === 400 && r.json.field === 'slug' && /reserved/.test(r.json.error), J(r));}const toRes = await api('POST', '/api/projects/gamma', { slug: 'inbox' });check('short (#25): changing a slug to a reserved one → 400, gamma keeps its slug', toRes.status === 400 && /reserved/.test(toRes.json.error) && (await api('GET', '/api/projects/gamma')).json.project.slug === 'gamma', J(toRes));check('short (#25): no project was made by the refusals', !(await api('GET', '/api/projects')).json.projects.some(p => /reserved|^api$|^inbox$/i.test(p)));// every first segment a route of project.hl answers is a reserved slug (a new route must add its name)const routeHeads = [...readFileSync(join(APP, 'project.hl'), 'utf8').matchAll(/pattern = "\/([^/":]+)/g)].map(m => m[1]);const reservedSrc = readFileSync(join(APP, 'lib/projects.hl'), 'utf8').match(/static reservedSlugs = \[([^\]]*)\]/);const reserved = reservedSrc ? [...reservedSrc[1].matchAll(/'([^']*)'/g)].map(m => m[1]) : [];const missingHeads = [...new Set([...routeHeads, '__hl', 'components'])].filter(h => !reserved.includes(h));check(`short (#25): every first path segment of project.hl's routes (${new Set(routeHeads).size}) + __hl + components is reserved`, routeHeads.length > 10 && missingHeads.length === 0, J(missingHeads));// ---- old events keep their authors (ticket #7) --------------------------------------------await a.goto(BASE + '/projects/alpha/1');await a.waitForSelector('#events li.comment');check('legacy: old events show their stored authors (creator, worker, worker; the state note started is a card of worker, its line too)', J((await hist(a)).map(h => h.author)) === J(['creator', 'worker', 'worker', 'worker']), J(await hist(a)));// ---- signed out: reading only (ticket #7) --------------------------------------------------const IDENT1 = '/projects/ident.worldapi.org/1';await a.goto(BASE + IDENT1);await a.waitForSelector('#events li');await connected(a, 'A on ident #1 (signed out)');check('signed out: the ticket page shows the history, a login hint and NO write forms', (await hist(a)).length === 1 && !!(await a.evaluate('!!document.querySelector("#loginhint")')) && !(await a.evaluate('!!document.querySelector("#commentform")')));check('signed out: top right the selector ("choose ident") and NOTHING beside it — no second "Log in with ident" button (creator 2026-10-24)', await a.evaluate(`(() => { const s = document.querySelector('#selector'); const r = s && s.shadowRoot; const hb = document.querySelector('application-header').getBoundingClientRect(); const sb = s.getBoundingClientRect(); return !!r && /choose/.test(r.querySelector('#choose').textContent) && !s.hasAttribute('logged-in') && sb.right > hb.right - 400 && !document.querySelector('#loginbutton') && !document.querySelector('a[href*="/login?key="]'); })()`));check('signed out: the selector is restyled to tickets\' accent (purple)', await a.evaluate(sh('getComputedStyle(r.querySelector("#choose")).backgroundColor')) === 'rgb(197, 134, 192)');let anonCookie = (await a.cookies([BASE])).filter(c => c.name === 'hlsid').map(c => 'hlsid=' + c.value)[0];const anonTry = await temit('commentOn', [(await api('GET', PT('ident.worldapi.org', 1))).json.ticket.id, 'anonymous'], anonCookie);check('signed out: a web write (the face, with the browser\'s own cookie) is refused', anonTry.value && /log in with ident/.test(anonTry.value.error), anonTry.raw);for (const [w, h, name] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {await viewport(a, w, h);check(`layout ${name} ${w}px: signed-out header (the selector) has no horizontal overflow`, await noOverflow(a));check(`IW ${name} ${w}px signed out: ident's selector stands visible at the top right of the header`, (await a.evaluate(SELECTOR_IN_HEADER)) === 'ok', await a.evaluate(SELECTOR_IN_HEADER));await shot(a, `${name}-signedout`);}await viewport(a, 1280, 900);// ---- A = alice (the creator): sign in to ident, then the SELECTOR on tickets ---------------await identSignIn(a, '[email protected]');await a.goto(BASE + IDENT1);await a.waitForSelector('#events li');await connected(a, 'A on ident #1');await a.evaluate('window.__loginMarker = 1');await shClick(a, '#choose');await a.waitFor(sh(`r.querySelectorAll('[part~="identity"]').length > 0`), { label: 'selector list' });check('selector: lists alice\'s identity', J(await a.evaluate(sh(`[...r.querySelectorAll('[part~="identity"]')].map(b => b.textContent)`))) === J(['Default']));await shClick(a, '[part~="identity"]', 'Default');await a.waitForSelector('#nameform', { timeout: 10000 });check('selector login: no reload, the host set logged-in, the name prompt appears', (await a.evaluate('window.__loginMarker')) === 1 && await a.evaluate('document.querySelector("#selector").hasAttribute("logged-in") && document.querySelector("#selector").loggedIn === true') && /logged in with/.test(await a.evaluate(sh('r.querySelector("#status").textContent'))));check('selector login: still no write forms before the name', !(await a.evaluate('!!document.querySelector("#commentform")')));for (const [w, h, name] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {await viewport(a, w, h);check(`layout ${name} ${w}px: name prompt has no horizontal overflow`, await noOverflow(a));await shot(a, `${name}-name`);}await viewport(a, 1280, 900);await a.type('#displayname', 'alice');await a.click('#namesave');await a.waitFor('!document.querySelector("#nameform") && !!document.querySelector("#memberhint")', { label: 'A named, no role yet: a member hint, no forms' });check('name: saved; no role yet → a role hint, no comment form; top right shows "alice"', (await a.evaluate('window.__loginMarker')) === 1 && (await a.text('#whoami')) === 'alice' && !(await a.evaluate('!!document.querySelector("#commentform")')));// ticket #20: the admin (the gate user, the creator) gives alice a role in every project; the page follows liveconst grant = async (name, role) => { for (const slug of (await api('GET', '/api/projects')).json.projects) { const g = await api('POST', `/api/projects/${slug}/members`, { user: name, role }); if (g.status !== 200 && g.status !== 201) throw new Error('grant failed ' + slug + ' ' + J(g)); } };await grant('alice', 'admin');await a.goto(BASE + IDENT1);await a.waitFor('!!document.querySelector("#commentform")', { label: 'A: the forms appear after alice got a role' });await connected(a, 'A on ident #1 with a role');await a.evaluate('window.__loginMarker = 1');check('roles: alice made admin → the comment form appears (page reloaded), no member hint', !(await a.evaluate('!!document.querySelector("#memberhint")')));for (const [w, h, name] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {await viewport(a, w, h);check(`layout ${name} ${w}px: logged-in header has no horizontal overflow`, await noOverflow(a));check(`IW ${name} ${w}px signed in: ident's selector stands visible at the top right of the header and shows the chosen identity`, (await a.evaluate(SELECTOR_IN_HEADER)) === 'ok' && /logged in with/.test(await a.evaluate(sh('r.querySelector("#status").textContent'))), await a.evaluate(SELECTOR_IN_HEADER));check(`IW ${name} ${w}px signed in: only the selector, your name and a visible Log out stand top right (no user icon), both 44 px high and inside the screen`, await a.evaluate('(() => { const h = document.querySelector("app-header, header") || document.body; const ok = e => { if (!e) return false; const r = e.getBoundingClientRect(); return r.width > 0 && r.height >= 40 && r.top >= 0 && r.bottom <= innerHeight && r.right <= innerWidth; }; return !document.querySelector("button.user-toggle, user-menu") && ok(document.querySelector("#logout")) && ok(document.querySelector("a#whoami")); })()'));{ const gap = await a.evaluate('(() => { const t = e => { const r = document.createRange(); r.selectNodeContents(e); return r.getBoundingClientRect(); }; const a = document.querySelector("#whoami").getBoundingClientRect(), b = t(document.querySelector("#logout")); return b.left - a.right; })()'); check(`IW ${name} ${w}px signed in: the name and the text Log out do not touch (at least 3 px between the name and the text)`, gap >= 3, String(gap)); }await shot(a, `${name}-loggedin`);}await viewport(a, 1280, 900);const aliceCookie = (await a.cookies([BASE])).filter(c => c.name === 'hlsid').map(c => 'hlsid=' + c.value)[0];const aliceHtml = await (await fetch(BASE + '/', { headers: { cookie: aliceCookie } })).text();const ALICE_UID = (/\\?"user\\?":\{\\?"id\\?":\\?"([0-9a-z]{12})/.exec(aliceHtml) || [])[1];check('session: the page knows alice\'s tickets user id, NEVER her identity id', /^[0-9a-z]{12}$/.test(ALICE_UID || '') && !aliceHtml.includes(ALICE_ID), ALICE_UID);// ---- B = bob: sign in to ident, then the plain LOGIN LINK (ident /login, no button in the header any more) ---------------------------------------await identSignIn(b, '[email protected]');await b.goto(BASE + '/');await b.waitForSelector('#selector');await connected(b, 'B on / signed out');// the header has no login button any more; the old way (ident's /login with the app key and the callback) is still served — open it as the button's link didawait b.goto(`${ident.base}/login?key=${APPKEY.key}&return=${encodeURIComponent(BASE + '/login/callback')}`);await b.waitForSelector('#chooselist', { timeout: 10000 });check('button: tickets → ident /signin/<rid> (choose an identity)', (await b.evaluate('location.href')).startsWith(ident.base + '/signin/'));await connectedIdent(b);await b.click('#chooselist li:nth-child(1) .choose');await b.waitFor(`location.href === ${J(BASE + '/')} && !!document.querySelector('#nameform')`, { timeout: 10000, label: 'B back with the name prompt' });check('button: back on tickets (/login/callback → /), logged in, asked for a name', await b.evaluate('document.querySelector("#selector").classList.contains("in")') && !(await b.evaluate('!!document.querySelector("#newticketbutton")')));await connected(b, 'B on / after the button login');await b.type('#displayname', 'bob');await b.click('#namesave');await b.waitFor('!document.querySelector("#nameform") && !!document.querySelector("#rolehint")', { label: 'B named' });check('button: bob named (no role yet: a role hint, no new-ticket form)', (await b.text('#whoami')) === 'bob' && !(await b.evaluate('!!document.querySelector("#newticketbutton")')));await grant('bob', 'edit');await b.goto(BASE + '/');await b.waitFor('!!document.querySelector("#newticketbutton")', { label: 'B: the New ticket button appears with the role edit' });await connected(b, 'B on / with a role');check('roles: bob made edit → the new-ticket form appears', (await b.text('#whoami')) === 'bob');const bobCookie = (await b.cookies([BASE])).filter(c => c.name === 'hlsid').map(c => 'hlsid=' + c.value)[0];// ---- the ticket page, two viewers ---------------------------------------------------await b.goto(BASE + IDENT1);await b.waitForSelector('#events li');await connected(b, 'B on ident #1');await sleep(300);check('ticket: subject, ref, project, state', (await a.text('#subject')) === 'Rebuild ident in Hybriel: email OTP login' && (await a.text('#ref')) === '#1' && (await a.text('#project')) === 'ident.worldapi.org' && (await a.text('#state')) === 'open', [await a.text('#subject'), await a.text('#ref'), await a.text('#project'), await a.text('#state')].join(' | '));check('ticket: the imported summary is one paragraph (hard wraps joined)', await a.evaluate(`!document.querySelector('#summary').textContent.includes('\\n') && document.querySelector('#summary').textContent.startsWith('Login for all worldapi apps (tickets, gitoria, …). Only email one-time codes, no passwords. Built on hl:webex;')`), await a.text('#summary'));check('time: the ticket page shows Vienna time (opened / updated / history)', await a.evaluate(`[document.querySelector('ticket-view header time').textContent, document.querySelector('#updated').textContent, document.querySelector('#events li time').textContent]`).then(v => J(v) === J([t2.ticket.created, t2.ticket.updated, t2.events[0].when]) && t2.ticket.created === vienna.format(new Date(t2.events[0].createdMs))), J(t2.ticket));check('ticket: history starts with the import event (by the token\'s user "gate")', (await hist(a)).length === 1 && (await a.text('#events > li')).includes('gate opened the ticket'), await a.text('#events > li'));// A comments (real typing into the form, real click) → B sees it without reloadcheck('ticket: no author field (ticket #7: the author is the logged-in user)', await a.evaluate('!document.querySelector("#author") && !document.querySelector("input[name=author]")'));// mission 016: the form is the Comments block's (an MdEditor): REAL keys into it, a line break with Shift+Enter, sent with Ctrl+Enterawait mdShows(a, '#commentform md-editor article', '', 'A: the comment editor is live');await a.click('#commentform md-editor article');await realKeys(a, 'first comment from A');await shiftEnter(a);await realKeys(a, 'second line');await ctrlEnter(a);await a.waitFor('document.querySelectorAll("#events li.comment").length === 1', { label: 'A sees its comment' });const firstA = (await hist(a)).pop();check('comment: typed with real keys, sent with Ctrl+Enter — appended in the writing browser as a Comments block row, author = the login (alice)', firstA.kind === 'comment' && firstA.author === 'alice' && firstA.text === 'first comment from A\nsecond line', J(firstA));check('comment: the block\'s form starts empty again', await a.evaluate('document.querySelector("#commentform md-editor input.value").value === ""'));await b.waitFor('document.querySelectorAll("#events li.comment").length === 1', { label: 'B got the comment live' });check('live: B sees A\'s comment without a reload', (await hist(b)).pop().text === 'first comment from A\nsecond line');await mdShows(b, '#events li.comment md-editor[data-readonly="true"] article', 'first comment from Asecond line', 'B draws the comment (a line break, no paragraph)');// hybriel 64527baa+: a face taking `session` answers with a sync of the session-derived members — a list must// not get the new row twice (gitoria's keys/tokens did). Settle, then count.await sleep(600);for (const [p, who] of [[a, 'A'], [b, 'B']]) { const h = await hist(p); check(`once: ${who} shows A's comment exactly once (2 history rows)`, h.length === 2 && h.filter(r => r.text === 'first comment from A\nsecond line').length === 1, J(h)); }check('live: B did not reload (no navigation entry)', await b.evaluate('performance.getEntriesByType("navigation").length === 1 && performance.getEntriesByType("navigation")[0].type === "navigate"'));await b.evaluate('window.__gateMarker = 42'); // survives only if B never reloads// ---- mission 013: GitHub pipe tables in a comment (lib/markdown.hl) — typed with REAL keys into the comment editor's// Markdown source view (a real click on its "Markdown source" button), sent by a real click; B gets it live -----------const LONGCELL = 'averyveryverylongwordthatcannotwrapanywhereatallsothetablemustscrollinsideitsbox';const TABLE_MD = 'Table check:\n| Item | Qty | Note \\| x |\n|:---|:---:|---:|\n| **milk** | `2` | a\\|b |\n| bread | 1 | <script>window.__tablePwned = 1</script> [x](javascript:alert(1)) |\n|' + LONGCELL + '|3\n\na | b stays text\n\nafter the table';const keys = async (page, text) => {for (const ch of text) {if (ch === '\n') {await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 });await page.send('Input.dispatchKeyEvent', { type: 'char', key: 'Enter', text: '\r' });await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 });} else {await page.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch });await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });}}};// mission 016: the comment form is the block's MdEditor — its "Markdown source" button (a real click), then real keysawait a.click('#commentform md-editor button.source-switch');await a.waitFor(`(() => { const t = document.querySelector('#commentform md-editor textarea'); return !!t && t.offsetParent !== null; })()`, { label: 'A: the comment editor shows its Markdown source' });await a.click('#commentform md-editor textarea');await keys(a, TABLE_MD);check('tables: the typed keys reached the comment field as Markdown', (await a.evaluate('document.querySelector("#commentform md-editor input.value").value')) === TABLE_MD, await a.evaluate('document.querySelector("#commentform md-editor input.value").value'));await a.click('#commentform button.comment-post');const LASTC = `[...document.querySelectorAll('#events li.comment')].pop()`;await a.waitFor(`document.querySelectorAll("#events li.comment").length === 2 && !!${LASTC}.querySelector('md-editor[data-readonly="true"] article table')`, { label: 'A sees its table comment' });const TABLE_PROBE = `(() => { const t = ${LASTC}.querySelector('md-editor[data-readonly="true"] article'); const tb = t.querySelectorAll('table'); const tab = tb[0]; if (!tab) return null;const cell = (c) => ({ text: c.textContent, align: c.getAttribute('data-align'), css: getComputedStyle(c).textAlign, strong: [...c.querySelectorAll('strong')].map(e => e.textContent), code: [...c.querySelectorAll('code')].map(e => e.textContent), links: c.querySelectorAll('a').length });return { tables: tb.length, inBox: getComputedStyle(tab).display + ' ' + getComputedStyle(tab).overflowX, head: [...tab.querySelectorAll('thead th')].map(cell), rows: [...tab.querySelectorAll('tbody tr')].map(r => [...r.children].map(c => c.tagName.toLowerCase() + ':' + c.textContent)),cells: [...tab.querySelectorAll('tbody td')].map(cell), paras: [...t.querySelectorAll(':scope > p')].map(p => p.textContent).filter(x => x !== ''), scripts: t.querySelectorAll('script').length, pwned: window.__tablePwned === 1,border: getComputedStyle(tab.querySelector('th')).borderTopColor, borderW: getComputedStyle(tab.querySelector('th')).borderTopWidth }; })()`;const tA = await a.evaluate(TABLE_PROBE);check('tables: a comment with a pipe table renders ONE <table> (the block draws it with MdEditor: the table is its own scrolling box)', !!tA && tA.tables === 1 && tA.inBox === 'block auto', J(tA));check('tables: header cells, `\\|` is a pipe in a cell, alignment from |:---|:---:|---:| (data-align + the computed text-align)', !!tA && J(tA.head.map(c => [c.text, c.align, c.css])) === J([['Item', 'left', 'left'], ['Qty', 'center', 'center'], ['Note | x', 'right', 'right']]), J(tA && tA.head));check('tables: body rows — inline Markdown in cells (**milk** strong, `2` code, a\\|b), a short row padded, raw HTML / javascript: stay text', !!tA && J(tA.rows) === J([['td:milk', 'td:2', 'td:a|b'], ['td:bread', 'td:1', 'td:<script>window.__tablePwned = 1</script> [x](javascript:alert(1))'], ['td:' + LONGCELL, 'td:3', 'td:']]) && J(tA.cells[0].strong) === J(['milk']) && J(tA.cells[1].code) === J(['2']) && tA.cells.every(c => c.links === 0) && tA.scripts === 0 && !tA.pwned, J(tA && [tA.rows, tA.cells.slice(0, 2), tA.scripts]));check('tables: the paragraph before stays, "a | b stays text" (pipes, no delimiter row) stays a paragraph', !!tA && J(tA.paras) === J(['Table check:', 'a | b stays text', 'after the table']), J(tA && tA.paras));check('tables: thin grey lines (1px, the palette\'s border grey: no hue — channels within 12)', !!tA && tA.borderW === '1px' && (() => { const m = /rgba?\((\d+), (\d+), (\d+)/.exec(tA.border); if (!m) return false; const v = [m[1], m[2], m[3]].map(Number); return Math.max(...v) - Math.min(...v) <= 12; })(), J(tA && [tA.border, tA.borderW]));await b.waitFor(`!!${LASTC} && !!${LASTC}.querySelector('md-editor[data-readonly="true"] article table')`, { label: 'B got the table comment live' });const tB = await b.evaluate(TABLE_PROBE);check('tables: live — B shows the same table without a reload', J(tB) === J(tA) && (await b.evaluate('window.__gateMarker')) === 42, J(tB));// mission 016: the block draws a comment in the browser — the server's HTML carries its Markdown in the block's hidden field, escapedconst tSsr = (await (await fetch(BASE + IDENT1)).text());check('tables: the server-rendered page carries the comment\'s Markdown escaped in the block (no live <script> from it)', tSsr.includes('<script>window.__tablePwned') && !tSsr.includes('<script>window.__tablePwned') && /<comments-block/.test(tSsr), (tSsr.match(/<script>window.__tablePwned.{0,80}/) || ['not found'])[0]);const tJson = await api('GET', PT('ident.worldapi.org', 1));const tMdView = await (await fetch(BASE + PT('ident.worldapi.org', 1), { headers: { accept: 'text/markdown' } })).text();check('tables: the API keeps the raw Markdown (JSON text byte for byte; Accept: text/markdown shows the typed lines)', tJson.json.events[tJson.json.events.length - 1].text === TABLE_MD && tMdView.includes(TABLE_MD), J(tJson.json.events[tJson.json.events.length - 1]).slice(0, 300));for (const [w, h, name] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {await viewport(a, w, h);await a.evaluate(`${LASTC}.querySelector('md-editor[data-readonly="true"] article table').scrollIntoView({ block: "center" })`);const box = await a.evaluate(`(() => { const m = ${LASTC}.querySelector('md-editor[data-readonly="true"] article table'); const t = m; return { boxW: m.clientWidth, scrollW: m.scrollWidth, tableW: m.scrollWidth, right: m.getBoundingClientRect().right, tableRight: m.getBoundingClientRect().right, overflowX: getComputedStyle(m).overflowX }; })()`);check(`tables ${name} ${w}px: the table stays inside its box (wider than the box: the box scrolls; else its right line is inside), phone: it scrolls, the page does not scroll sideways`, (await noOverflow(a)) && box.overflowX === 'auto' && (box.tableW > box.boxW ? box.scrollW > box.boxW : box.scrollW <= box.boxW) /* mission 022: the old else-branch compared an element with itself (never true); with the theme's wider column (72rem, was 60rem) the fixture table fits the box on desktop: then nothing scrolls */ && (w > 600 || box.scrollW > box.boxW) && box.right <= w, J(box));await shot(a, `${name}-table`);}await viewport(a, 1280, 900);// ---- ticket #20: the new states, the roles, projects with members, the inbox (browser + API) ------------------// A (alice, admin) moves ident #1 to "review": B follows live; the ticket is assigned to the project's first admin (the gate user)check('shell: no inbox count yet (nothing assigned to bob)', (await b.text('application-header main-menu')).replace(/\s+/g, ' ').trim() === 'All ticketsInbox' && (await b.evaluate('document.querySelectorAll("application-header main-menu span.count").length')) === 0); // mission 023: the count is a badge; none while nothing is assignedcheck('state: the composer\'s State choices are "no change" first, then the new state names', J(await texts(a, '#commentform select[name=state] option')) .startsWith('["no change"') && J((await texts(a, '#commentform select[name=state] option')).sort()) === J(['canceled', 'done', 'no change', 'pending', 'progress', 'reopened', 'review']), J(await texts(a, '#commentform select[name=state] option')));// ==== m021 START — tickets#29: the editor's LOOK on the ticket page (the creator: "why did the md wysiwyg editor's layout change?")const LOOK = (sel) => `(() => { const m = document.querySelector(${J(sel)}); const c = getComputedStyle(m); const art = m.querySelector('article'); const f = m.querySelector('nav button.file'); const bs = [...m.querySelectorAll('nav button')].filter(x => getComputedStyle(x).display !== 'none').map(x => x.getBoundingClientRect()); return { cls: m.className, border: c.borderTopWidth + ' ' + c.borderTopStyle, pad: c.paddingTop, h: Math.round(m.getBoundingClientRect().height), art: Math.round(art.getBoundingClientRect().height), file: !!f && getComputedStyle(f).display !== 'none', rows: new Set(bs.map(r => Math.round(r.top))).size, minTap: Math.round(Math.min(...bs.map(r => Math.min(r.width, r.height)))) }; })()`;check('UX: the state form is gone — no second editor ("Note (optional)"), no separate state form on the ticket page', (await a.evaluate(`!document.querySelector('#stateform') && !document.querySelector('#statenote') && !document.querySelector('#statesend') && document.querySelectorAll('#commentform md-editor').length === 1`)));check('m021: no File button where the host has no upload (the toolbar has 11 buttons: no File button)', !(await a.evaluate(LOOK('#commentform md-editor'))).file);const cmLook = await a.evaluate(LOOK('#commentform md-editor'));check('m021: the comment form is ~3 lines tall (art 70-110 px), no frame', cmLook.art >= 70 && cmLook.art <= 110 && cmLook.border.startsWith('0px') && cmLook.pad === '0px', J(cmLook));// F4: under the tickets theme (`:focus-visible` and `textarea:focus` rules) the focused editor shows ONE ring (its own frame), never a second one on the surface / source textarea; the toolbar holds iconsawait a.click('#commentform md-editor article'); await sleep(250);const f4a = await a.evaluate(`(() => { const m = document.querySelector('#commentform md-editor'); const x = m.querySelector('article'); const c = getComputedStyle(x), r = getComputedStyle(document.querySelector('#commentform pick-area')); const bs = [...m.querySelectorAll('nav button')].filter(b => getComputedStyle(b).display !== 'none'); return { focused: document.activeElement === x, art: c.outlineStyle + '/' + c.outlineWidth, root: r.outlineStyle + '/' + r.outlineWidth, buttons: bs.length, svgs: bs.filter(b => b.querySelector('svg path') && b.textContent.trim() === '' && b.getAttribute('aria-label') === b.title).length }; })()`);check('F4 (UX: the editor sits in the composer box): the focused comment editor under the tickets theme: the surface has no outline of its own, the BOX around the editor and its files one 2 px ring; every toolbar button is an icon with title + aria-label (11 since components added the Table button)', f4a.focused && f4a.art.startsWith('none/') && f4a.root === 'solid/2px' && f4a.buttons === 11 && f4a.svgs === 11, J(f4a));await a.click('#commentform md-editor footer button.source-switch'); await sleep(300);await a.click('#commentform md-editor textarea'); await sleep(250);const f4b = await a.evaluate(`(() => { const m = document.querySelector('#commentform md-editor'); const t = m.querySelector('textarea'); const c = getComputedStyle(t), r = getComputedStyle(document.querySelector('#commentform pick-area')); return { focused: document.activeElement === t, ta: c.outlineStyle + '/' + c.outlineWidth, root: r.outlineStyle + '/' + r.outlineWidth }; })()`);check('F4: the focused source textarea under the tickets theme has no outline of its own (the frame keeps its ring)', f4b.focused && f4b.ta.startsWith('none/') && f4b.root === 'solid/2px', J(f4b));await a.click('#commentform md-editor footer button.source-switch'); await sleep(300);await a.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });await sleep(400);const noteLook390 = await a.evaluate(LOOK('#commentform md-editor'));check('m021 / E2: at 390 px the toolbar is two even rows (5 + 5, no swipe) and every button is a 44 px target', noteLook390.rows === 2 && noteLook390.minTap >= 44, J(noteLook390));await a.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });// ==== m021 END// UX mission: a state change alone — the State select (real keys) says "review", the button says "Set to review" (no text, no files), a real clickconst pickStateOf = async (page, name) => {await page.evaluate(`document.querySelector('#commentform select[name=state]').focus()`);for (let i = 0; i < 12; i++) {if ((await page.evaluate(`(() => { const s = document.querySelector('#commentform select[name=state]'); return s.options[s.selectedIndex].textContent.trim(); })()`)) === name) return true;await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40 });await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40 });await sleep(120);}return false;};const postLabelOf = (page) => page.evaluate(`document.querySelector('#commentform button.comment-post').textContent.trim()`);check('UX: the composer\'s button says "Comment" while nothing else is chosen', (await postLabelOf(a)) === 'Comment', await postLabelOf(a));check('UX: a real key press on the State select chooses "review"', await pickStateOf(a, 'review'));check('UX: with a state chosen and nothing written the button says "Set to review"', (await postLabelOf(a)) === 'Set to review', await postLabelOf(a));await a.click('#commentform button.comment-post');await a.waitFor('document.querySelector("#state").textContent === "review"', { label: 'A state changed' });check('state: A shows the new state and a state event (no comment came with it: the state alone)', (await a.text('#events > li:nth-last-child(2)')).includes('alice changed the state') && (await a.text('#events > li:nth-last-child(2) ticket-state')) === 'review' && (await a.evaluate(`document.querySelectorAll('#events > li:nth-last-child(2) event-text').length`)) === 0 && (await a.text('#events > li:last-child')).includes('assigned'), J(await texts(a, '#events > li')).slice(-400));await sleep(600);check('once: A shows the state change exactly once', (await texts(a, '#events > li')).filter(t => t.includes('alice changed the state') && t.includes('review')).length === 1, J(await texts(a, '#events > li')));await b.waitFor('document.querySelector("#state").textContent === "review"', { label: 'B state live' });check('live: B\'s state badge followed, no reload', (await b.evaluate('document.querySelector("#state").className')) === 'review' && (await b.evaluate('window.__gateMarker')) === 42);const inboxOf = async (tok) => { const r = await fetch(BASE + '/api/inbox', { headers: { authorization: 'Bearer ' + tok } }); let json = null; try { json = await r.json(); } catch {} return { status: r.status, json }; };const inbox0 = await inboxOf(TOKEN);check('inbox: the gate user (first admin) has ident #1 in review, only tickets assigned to them', inbox0.status === 200 && inbox0.json.review.some(t => t.subject === 'Rebuild ident in Hybriel: email OTP login') && [...inbox0.json.review, ...inbox0.json.pending].every(t => t.assignee === 'gate'), J(inbox0.json).slice(0, 400));const oldNames = await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'awaiting creator' });check('states: the old name "awaiting creator" is an alias of review (already there → 400 "already")', oldNames.status === 400 && /already review/.test(oldNames.json.error), J(oldNames));const aliasBack = await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'in progress' });check('states: "in progress" is an alias of progress (201)', aliasBack.status === 201 && aliasBack.json.ticket.state === 'progress', J(aliasBack).slice(0, 300));await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'open' });// roles: bob = use → comment + open ⇄ review, nothing else (web and API)let aliceTok0 = null;const bobTok = (await temit('tokenCreate', ['bob gate'], bobCookie)).value.token;await api('POST', '/api/projects/ident.worldapi.org/members', { user: 'bob', role: 'use' });await b.goto(BASE + IDENT1);await b.waitForSelector('#commentform select[name=state]');await connected(b, 'B on ident #1 as use');check('roles: bob (use) sees only review (besides "no change") in the state choices (ticket is open)', J(await texts(b, '#commentform select[name=state] option')) === J(['no change', 'review']), J(await texts(b, '#commentform select[name=state] option')));const useDone = await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'done' }, bobTok);const useReview = await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'review' }, bobTok);const useNew = await api('POST', '/api/projects/ident.worldapi.org/tickets', { subject: 'use may not' }, bobTok);const useSettings = await api('POST', '/api/projects/ident.worldapi.org/members', { user: 'bob', role: 'admin' }, bobTok);const useComment = await api('POST', PT('ident.worldapi.org', 1) + '/comments', { text: 'a use member comments' }, bobTok);check('roles: use → done 403, review 201, new ticket 403, members 403, comment 201', [useDone.status, useReview.status, useNew.status, useSettings.status, useComment.status].join() === '403,201,403,403,201', J([useDone, useNew, useSettings]).slice(0, 500));await b.goto(BASE + '/projects/ident.worldapi.org/settings');await b.waitForSelector('#notadmin');check('roles: the settings page of a non-admin says so and has no forms', !(await b.evaluate('!!document.querySelector("#detailsform")')));await api('POST', '/api/projects/ident.worldapi.org/members', { user: 'bob', role: 'edit' });const editAssign = await api('POST', PT('ident.worldapi.org', 1) + '/assign', { assignee: 'bob' }, bobTok);check('roles: edit may assign (201) and move to any state', editAssign.status === 201 || editAssign.status === 200, J(editAssign).slice(0, 300));const editPending = await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'pending' }, bobTok);check('roles: edit → pending 201; "on hold" is an alias of pending', editPending.status === 201 && editPending.json.ticket.state === 'pending', J(editPending).slice(0, 300));// the inbox page of bob: pending and review, only what is assigned to himawait b.goto(BASE + '/inbox');await b.waitForSelector('#pendingbox');await connected(b, 'B inbox');check('inbox: bob has ident #1 under pending, review is empty', (await texts(b, '#pending li a.subject')).length === 1 && (await b.text('#pending li a.subject')).includes('Rebuild ident') && !!(await b.evaluate('!!document.querySelector("#reviewempty")')), J(await texts(b, '#pendingbox')));await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'review' }, bobTok);await b.waitFor('document.querySelectorAll("#review li").length === 1 && document.querySelectorAll("#pending li").length === 0', { label: 'inbox follows the state change live' });check('inbox: the ticket moved from pending to review live, header count 1', (await b.text('application-header main-menu')).replace(/\s+/g, ' ').trim() === 'All ticketsInbox1'); // mission 023: the badge's own element after the plain label{// mission 023: the Inbox count is a badge (its own span.count), the label stays plain; `current` / aria-current marks the page's itemconst menuInfo = () => b.evaluate(`(() => { const m = document.querySelector('application-header main-menu'); return [...m.querySelectorAll('a')].map(a => ({ href: a.getAttribute('href'), aria: a.getAttribute('aria-current'), cls: a.className, label: a.firstChild && a.firstChild.nodeValue, badge: [...a.querySelectorAll('span.count')].map(x => x.textContent) })); })()`);const marked = async (href, label) => { await b.waitFor(`(() => { const a = document.querySelector('application-header main-menu a[href="${href}"]'); return !!a && a.getAttribute('aria-current') === 'page'; })()`, { label }).catch(() => {}); const m = await menuInfo(); return m.filter(x => x.aria === 'page').map(x => x.href).join() === href && m.filter(x => x.cls === 'current').length === 1; };const mi = await menuInfo();check('menu badge: the Inbox count is its own span.count (1), the label is the plain text "Inbox"', mi.length === 2 && J(mi[1].badge) === '["1"]' && mi[1].label === 'Inbox' && mi[0].badge.length === 0, J(mi));check('menu current: on /inbox the Inbox item has aria-current="page" and the class current, All tickets has not', await marked('/inbox', 'inbox marked'), J(await menuInfo()));await b.goto(`${BASE}/`); await b.waitForSelector('#tickets li');check('menu current: on the ticket list All tickets has aria-current="page", the Inbox has not', await marked('/', 'list marked'), J(await menuInfo()));const tHref = await b.evaluate(`(() => { const a = document.querySelector('#tickets li a.subject'); return a ? a.getAttribute('href') : ''; })()`);await b.goto(`${BASE}${tHref}`); await b.waitForSelector('#subject');check(`menu current: on a ticket page (${tHref}, no item's path) All tickets has aria-current="page"`, tHref !== '' && await marked('/', 'ticket marked'), J(await menuInfo()));await b.goto(`${BASE}/inbox`); await b.waitForSelector('#pendingbox'); await connected(b, 'B inbox again');check('menu current: back on /inbox the marker moved to the Inbox', await marked('/inbox', 'inbox marked again'), J(await menuInfo()));// mission 024 (hybriel#197): the marker is in the SERVER's HTML (a plain fetch, no browser, no script): in the first paint, no flicker{const ssr = async path => { const h = await (await fetch(BASE + path)).text(); const tags = [...h.matchAll(/<a\b[^>]*>/g)].map(m => m[0]).filter(t => /href="\/(inbox)?"/.test(t) && /aria-current=/.test(t)); return tags.map(t => (t.match(/href="([^"]*)"/) || [])[1] + (/aria-current="page"/.test(t) ? '*' : '')); };const proj = '/' + tHref.split('/')[1];for (const [path, want] of [['/', '/*,/inbox'], ['/inbox', '/,/inbox*'], [proj, '/*,/inbox'], [tHref, '/*,/inbox']]) {const got = await ssr(path); const uniq = [...new Set(got)].join();check(`menu current in the server's HTML (plain fetch of ${path}): ${want}`, uniq === want, J(got));}}}aliceTok0 = (await temit('tokenCreate', ['alice #20'], aliceCookie)).value.token;check('inbox: alice (admin, nothing assigned) has an empty inbox', (await inboxOf(aliceTok0)).json.review.length === 0);// ---- mission 016 (layouts#2): THE COMMENTS BLOCK — edit (author), delete (author, asks first), like (members, toggle), in place// in the history between the other events; a non-member reads only, and the server refuses them too (faces + API) ----------------const cbProj = await api('POST', '/api/projects', { title: 'Comments block' });const CB = cbProj.json && cbProj.json.project ? cbProj.json.project.slug : 'comments-block';await api('POST', `/api/projects/${CB}/members`, { user: 'alice', role: 'admin' });const cbT = (await api('POST', `/api/projects/${CB}/tickets`, { subject: 'Comments in place' })).json.ticket;const cbGate = (await api('POST', PT(CB, 1) + '/comments', { text: 'the **gate** writes first' })).json.event;await api('POST', PT(CB, 1) + '/state', { state: 'progress', text: 'working on it' });check('m016: the fixture — a project bob is not in, a ticket with created / gate\'s comment / a state change', cbProj.status === 201 && !!cbT && !!cbGate && cbGate.kind === 'comment', J(cbProj).slice(0, 300));const CBURL = '/' + CB + '/1';// B = bob, NOT a member: reads the comments in the block, in place; no form, no Edit / Delete; the like does nothingawait b.goto(BASE + CBURL);await b.waitForSelector('#events li.comment');await connected(b, 'B on the comments ticket (no member)');await mdShows(b, `li.comment[data-id="${cbGate.id}"] md-editor[data-readonly="true"] article`, 'the gate writes first', 'B draws gate\'s comment');const nmH = await hist(b);check('m016: in place — created, gate\'s comment (a Comments block row, Markdown drawn), then the state change', J(nmH.map(h => h.kind)) === J(['created', 'comment', 'comment', 'state']) && nmH[2].text === 'working on it' && nmH[1].author === 'gate' && nmH[1].text === 'the **gate** writes first' && (await b.evaluate(`document.querySelector('li.comment[data-id="${cbGate.id}"] article strong').textContent`)) === 'gate', J(nmH));check('m016: the block\'s count line and form are not shown inside the history (one visible comment form at most)', await b.evaluate(`[...document.querySelectorAll('#events h2.comments-count, #events form.comment-form')].every(e => e.offsetParent === null)`));check('m016: non-member — no comment form, the member hint, no Edit / Delete anywhere', await b.evaluate('!document.querySelector("#commentform") && !!document.querySelector("#memberhint") && !document.querySelector(".comment-edit-start, .comment-delete")'));await calmClick(b, `li.comment[data-id="${cbGate.id}"] button.comment-like`);await sleep(700);check('m016: non-member — pressing the like changes nothing (page and store)', (await b.evaluate(`document.querySelector('li.comment[data-id="${cbGate.id}"] button.comment-like').getAttribute('aria-pressed')`)) === 'false' && (await api('GET', PT(CB, 1))).json.events.find(e => e.id === cbGate.id).likes === undefined);// the server refuses a non-member too: the faces with bob's own session, and the API with bob's tokenconst nmFaces = [await temit('commentOn', [cbT.id, 'bob is no member'], bobCookie), await temit('ticketCommentLike', [cbT.id, cbGate.id], bobCookie), await temit('ticketCommentEdit', [cbT.id, cbGate.id, 'bob edits'], bobCookie), await temit('ticketCommentDelete', [cbT.id, cbGate.id], bobCookie)];check('m016: non-member — the faces (post, like, edit, delete with bob\'s own session) are refused', nmFaces.every(f => f.value && /member/.test(f.value.error || '')), J(nmFaces.map(f => f.raw)));const nmApi = [await api('POST', PT(CB, 1) + `/comments/${cbGate.id}/like`, null, bobTok), await api('POST', `/api/tickets/${cbT.id}/comments/${cbGate.id}/edit`, { text: 'bob edits' }, bobTok), await api('POST', PT(CB, 1) + `/comments/${cbGate.id}/delete`, {}, bobTok)];const afterNm = (await api('GET', PT(CB, 1))).json.events.find(e => e.id === cbGate.id);check('m016: non-member — the API answers 403 to like / edit / delete, the comment is untouched', J(nmApi.map(r => r.status)) === J([403, 403, 403]) && afterNm.text === 'the **gate** writes first' && afterNm.likes === undefined && afterNm.edited === undefined && afterNm.deleted === undefined, J(nmApi));// bob becomes a member (use): after a reload he has the formawait api('POST', `/api/projects/${CB}/members`, { user: 'bob', role: 'use' });await b.goto(BASE + CBURL);await b.waitForSelector('#commentform form.comment-form');await connected(b, 'B on the comments ticket (use)');await b.evaluate('window.__m016 = 1');// A = alice posts by REAL keys + Ctrl+Enter: a NEW block after the state change; both browsers// tickets#35: NO WAITING. The page is slowed to a quarter of the CPU (this machine is loaded), and the keys go in as soon as the editor can be// clicked, while the page is still starting up (before its scripts built the editor); nothing typed may be lost, in the editor or in the field that is sent.await a.send('Emulation.setCPUThrottlingRate', { rate: 4 });await a.goto(BASE + CBURL);await a.click('#commentform md-editor article');await realKeys(a, 'alice writes **later** now');await connected(a, 'A on the comments ticket');await a.send('Emulation.setCPUThrottlingRate', { rate: 1 });await sleep(1500);const typedField = await a.evaluate('document.querySelector("#commentform md-editor input.value").value');check('tickets#35: a reply typed right after the page loaded (before the page finished starting) is still in the field that is sent, and shown', typedField === 'alice writes **later** now' && (await a.evaluate('document.querySelector("#commentform md-editor article").textContent')).replace(/[\u00a0\u200b]/g, ' ').replace(/ +/g, ' ') === 'alice writes later now', typedField + ' | surface: ' + (await a.evaluate('document.querySelector("#commentform md-editor article").innerHTML')));await ctrlEnter(a);await a.waitFor('document.querySelectorAll("#events li.comment").length === 3', { label: 'A: its comment' }).catch(async (e) => { console.log('DUMP', J(await a.evaluate(`[...document.querySelectorAll('#events > li')].map(li => li.className + ':' + li.querySelectorAll('li.comment').length + ':' + li.textContent.replace(/\\s+/g,' ').slice(0,60))`)), J((await api('GET', PT(CB, 1))).json.events.map(e => e.kind)), a.dumpConsole().slice(-800)); throw e; });await b.waitFor('document.querySelectorAll("#events li.comment").length === 3', { label: 'B: alice\'s comment live' });const cbStored = (await api('GET', PT(CB, 1))).json.events;const aliceC = cbStored[cbStored.length - 1];const hA = await hist(a), hB = await hist(b);check('m016: post — stored once as alice\'s comment (the visual editor wrote **later**), in a new block after the state change, A and B', aliceC.kind === 'comment' && aliceC.author === 'alice' && aliceC.text === 'alice writes **later** now' && cbStored.filter(e => e.kind === 'comment').length === 2 && J(hA.map(h => h.kind)) === J(['created', 'comment', 'comment', 'state', 'comment']) && J(hB.map(h => h.kind + ':' + h.text)) === J(hA.map(h => h.kind + ':' + h.text)) && (await b.evaluate('document.querySelectorAll("#events > li.comments").length')) === 2, J([aliceC, hA, hB]));check('m016: Edit / Delete only on your own comment — A on alice\'s yes, on gate\'s no; B (bob) on neither', await a.evaluate(`!!document.querySelector('li.comment[data-id="${aliceC.id}"] .comment-edit-start') && !!document.querySelector('li.comment[data-id="${aliceC.id}"] .comment-delete') && !document.querySelector('li.comment[data-id="${cbGate.id}"] .comment-edit-start')`) && await b.evaluate('!document.querySelector(".comment-edit-start, .comment-delete")'));// EDIT: a real click on Edit, real keys at the end, Save → both browsers show the new text and "edited"; the earlier version folds outawait calmClick(a, `li.comment[data-id="${aliceC.id}"] button.comment-edit-start`);await mdShows(a, `li.comment[data-id="${aliceC.id}"] form.comment-edit md-editor article`, 'alice writes later now', 'A: the edit editor holds the comment');await a.click(`li.comment[data-id="${aliceC.id}"] form.comment-edit md-editor article`);await endKey(a);await realKeys(a, ' and edits');await calmClick(a, `li.comment[data-id="${aliceC.id}"] button.comment-save`);await a.waitFor(`!!document.querySelector('li.comment[data-id="${aliceC.id}"] details.comment-history')`, { label: 'A: edited' });await b.waitFor(`!!document.querySelector('li.comment[data-id="${aliceC.id}"] details.comment-history')`, { label: 'B: the edit live' });const edApi = (await api('GET', PT(CB, 1))).json.events.find(e => e.id === aliceC.id);check('m016: edit — stored as the new text, the earlier one kept (API: edited, editedWhen, earlier)', edApi.text === 'alice writes **later** now and edits' && edApi.edited === true && /^\d{4}-\d\d-\d\d \d\d:\d\d$/.test(edApi.editedWhen) && J(edApi.earlier.map(v => v.text)) === J(['alice writes **later** now']), J(edApi));await mdShows(b, `li.comment[data-id="${aliceC.id}"] md-editor[data-readonly="true"] article`, 'alice writes later now and edits', 'B draws the edited text');check('m016: edit — B shows the new text and "edited" without a reload', (await b.evaluate('window.__m016')) === 1 && (await b.text(`li.comment[data-id="${aliceC.id}"] details.comment-history summary`)) === 'edited');await b.click(`li.comment[data-id="${aliceC.id}"] details.comment-history summary`);await b.waitFor(`document.querySelector('li.comment[data-id="${aliceC.id}"] details.comment-history').open`, { label: 'B: history open' });check('m016: edit — a click on "edited" folds out the earlier version ("Edited once", its Markdown)', (await b.text(`li.comment[data-id="${aliceC.id}"] .comment-history-title`)) === 'Edited once' && J(await texts(b, `li.comment[data-id="${aliceC.id}"] details.comment-history li pre`)) === J(['alice writes **later** now']));// K1: the theme's framed foldable must not show: "edited" is a quiet label beside the time; the bubble hugs its content (the readonly editor had an inline min-height of 9em)const k1 = await b.evaluate(`(() => { const li = document.querySelector('li.comment[data-id="${aliceC.id}"]'); const d = li.querySelector('details.comment-history'); const s = d.querySelector('summary'); const t = li.querySelector('comment-meta time').getBoundingClientRect(); const sr = s.getBoundingClientRect(); const cs = getComputedStyle(d), ss = getComputedStyle(s); const bu = li.querySelector('comment-bubble'); const last = [...bu.children].filter(c => c.getBoundingClientRect().height > 0).pop().getBoundingClientRect(); return { box: cs.borderTopStyle, bg: ss.backgroundColor, sb: ss.borderBottomStyle, pad: ss.paddingTop, sameLine: Math.abs(sr.top - t.top) < 14 && sr.left > t.right - 1, h: Math.round(sr.height), slack: Math.round(bu.getBoundingClientRect().bottom - last.bottom - parseFloat(getComputedStyle(bu).paddingBottom)), inline: li.querySelector('md-editor article').style.minHeight }; })()`);check('k1: "edited" is a quiet label on the time\'s line (no frame, no header strip, its padding only the 44 px hit area, sync MC) and the bubble hugs its content', k1.box === 'none' && k1.bg === 'rgba(0, 0, 0, 0)' && k1.sb === 'none' && parseFloat(k1.pad) <= 14 && k1.sameLine && k1.h <= 48 && k1.slack <= 3 && k1.inline === '', J(k1));// sync of components.hybriel 4922f9c (SY): like / Edit / Delete and the "edited" label are 44 px targetsconst k1t = await b.evaluate(`[...document.querySelectorAll('comments-block button, comments-block summary')].filter(e => e.getBoundingClientRect().width > 0 && e.closest('md-editor') == null).map(e => { const r = e.getBoundingClientRect(); return (e.textContent || e.className).trim().slice(0, 10) + ' ' + Math.round(r.width) + 'x' + Math.round(r.height); }).filter(t => Number(t.split(' ').pop().split('x')[1]) < 43.5 || Number(t.split(' ').pop().split('x')[0]) < 43.5)`);check('sy: every like / Edit / Delete button and the "edited" label of the thread is a 44 px target', k1t.length === 0, J(k1t));// LIKE: bob likes alice's comment (toggle), alice sees the count liveawait calmClick(b, `li.comment[data-id="${aliceC.id}"] button.comment-like`);await b.waitFor(`document.querySelector('li.comment[data-id="${aliceC.id}"] button.comment-like').getAttribute('aria-pressed') === 'true'`, { label: 'B: liked' });await a.waitFor(`document.querySelector('li.comment[data-id="${aliceC.id}"] button.comment-like').textContent === '♡ 1'`, { label: 'A: the count live' });check('m016: like — B pressed: ♥ 1 (pressed), A sees ♡ 1 (not hers), the API says likes 1', (await b.text(`li.comment[data-id="${aliceC.id}"] button.comment-like`)) === '♥ 1' && (await api('GET', PT(CB, 1))).json.events.find(e => e.id === aliceC.id).likes === 1);await calmClick(b, `li.comment[data-id="${aliceC.id}"] button.comment-like`);await b.waitFor(`document.querySelector('li.comment[data-id="${aliceC.id}"] button.comment-like').getAttribute('aria-pressed') === 'false'`, { label: 'B: unliked' });await a.waitFor(`document.querySelector('li.comment[data-id="${aliceC.id}"] button.comment-like').textContent === '♡ 0'`, { label: 'A: back to 0' });check('m016: like — pressed again takes it back (♡ 0, no likes key in the API)', (await b.text(`li.comment[data-id="${aliceC.id}"] button.comment-like`)) === '♡ 0' && (await api('GET', PT(CB, 1))).json.events.find(e => e.id === aliceC.id).likes === undefined);// another user's comment: bob (a member now) may not edit / delete it — faces and API refusedconst otherFaces = [await temit('ticketCommentEdit', [cbT.id, aliceC.id, 'bob edits alice'], bobCookie), await temit('ticketCommentDelete', [cbT.id, aliceC.id], bobCookie)];const otherApi = [await api('POST', PT(CB, 1) + `/comments/${aliceC.id}/edit`, { text: 'bob edits alice' }, bobTok), await api('POST', PT(CB, 1) + `/comments/${aliceC.id}/delete`, null, bobTok)];check('m016: another user\'s comment — bob\'s edit / delete refused (faces: "only its author", API 403), nothing changed', otherFaces.every(f => f.value && /only its author/.test(f.value.error || '')) && J(otherApi.map(r => r.status)) === J([403, 403]) && (await api('GET', PT(CB, 1))).json.events.find(e => e.id === aliceC.id).text === 'alice writes **later** now and edits', J([otherFaces.map(f => f.raw), otherApi]));// DELETE asks first: Keep takes it back, Delete removes it from both browsers; one line stays in its placeawait calmClick(a, `li.comment[data-id="${aliceC.id}"] button.comment-delete`);await a.waitForSelector(`li.comment[data-id="${aliceC.id}"] comment-ask`);check('m016: delete — asks first ("Delete this comment?" Delete / Keep)', (await a.text(`li.comment[data-id="${aliceC.id}"] comment-ask span`)) === 'Delete this comment?' && !!(await a.evaluate(`!!document.querySelector('li.comment[data-id="${aliceC.id}"] .comment-delete-keep')`)));await calmClick(a, `li.comment[data-id="${aliceC.id}"] button.comment-delete-keep`);await sleep(600);check('m016: delete — Keep: nothing deleted', !(await a.evaluate(`!!document.querySelector('li.comment[data-id="${aliceC.id}"] comment-ask')`)) && (await api('GET', PT(CB, 1))).json.events.find(e => e.id === aliceC.id).deleted === undefined);await calmClick(a, `li.comment[data-id="${aliceC.id}"] button.comment-delete`);await calmClick(a, `li.comment[data-id="${aliceC.id}"] button.comment-delete-yes`);await a.waitFor(`!document.querySelector('li.comment[data-id="${aliceC.id}"]')`, { label: 'A: the comment is gone' });await b.waitFor(`!document.querySelector('li.comment[data-id="${aliceC.id}"]')`, { label: 'B: gone live' });const delApi = (await api('GET', PT(CB, 1))).json.events.find(e => e.id === aliceC.id);const hDel = await hist(b);check('m016: delete — gone from A and B; ONE line stays in its place ("alice commented (deleted …)"); the API: deleted, no text', delApi.deleted === true && delApi.text === '' && delApi.hasText === false && delApi.earlier === undefined && J(hDel.map(h => h.kind)) === J(['created', 'comment', 'comment', 'state', 'comment deleted']) && /^alice commented \(deleted \d{4}-\d\d-\d\d \d\d:\d\d\)/.test(hDel[4].head) && (await b.evaluate('window.__m016')) === 1, J([delApi, hDel]));const delMd = await (await fetch(BASE + PT(CB, 1), { headers: { accept: 'text/markdown' } })).text();check('m016: delete — the Markdown view keeps the line, not the text', /· alice commented \(deleted /.test(delMd) && !delMd.includes('alice writes'), delMd.slice(-400));const delAgain = [await api('POST', PT(CB, 1) + `/comments/${aliceC.id}/edit`, { text: 'again' }, aliceTok0), await api('POST', PT(CB, 1) + `/comments/${aliceC.id}/like`, null, aliceTok0)];check('m016: a deleted comment can be neither edited nor liked (400)', J(delAgain.map(r => r.status)) === J([400, 400]), J(delAgain));// THE API for programs: both URL forms, the token's user, refusals; an untouched comment keeps exactly its old keysconst apiPost = (await api('POST', PT(CB, 1) + '/comments', { text: 'gate via API' })).json.event;const apiEdit = await api('POST', `/api/tickets/${cbT.id}/comments/${apiPost.id}/edit`, { text: 'gate via API, edited' });const apiLike = await api('POST', PT(CB, 1) + `/comments/${apiPost.id}/like`, null);const apiUnlike = await api('POST', `/api/tickets/${cbT.id}/comments/${apiPost.id}/like`, {});check('m016: API — edit 200 (edited, earlier), like 200 liked:true likes 1, again 200 liked:false (no likes key)', apiEdit.status === 200 && apiEdit.json.event.text === 'gate via API, edited' && apiEdit.json.event.edited === true && apiLike.status === 200 && apiLike.json.liked === true && apiLike.json.event.likes === 1 && apiUnlike.status === 200 && apiUnlike.json.liked === false && apiUnlike.json.event.likes === undefined, J([apiEdit, apiLike, apiUnlike]).slice(0, 600));const apiRef = [await api('POST', PT(CB, 1) + `/comments/${apiPost.id}/edit`, { text: 'x' }, null), await api('POST', PT(CB, 1) + '/comments/zzzzzzzzzzzz/like', null), await api('POST', PT(CB, 1) + `/comments/${cbStored[0].id}/like`, null), await api('POST', PT(CB, 1) + `/comments/${apiPost.id}/edit`, { text: 'gate via API, edited' }), await api('POST', PT(CB, 1) + `/comments/${apiPost.id}/edit`, { text: ' ' }), await api('POST', PT(CB, 1) + `/comments/${apiPost.id}/edit`, { text: 'x', author: 'me' }), await api('POST', PT(CB, 1) + `/comments/${apiPost.id}/delete`, { why: 'x' }), await api('POST', PT(CB, 1) + '/comments/' + cbGate.id + '/edit', { text: 'x' }, aliceTok0)];check('m016: API refusals — no token 401, unknown comment 404, a non-comment entry 400, same text 400, empty 400, author 400, unknown field 400, alice on gate\'s 403', J(apiRef.map(r => r.status)) === J([401, 404, 400, 400, 400, 400, 400, 403]), J(apiRef.map(r => [r.status, r.json])));const keysOf = (e) => Object.keys(e).sort().join(',');const plainC = (await api('GET', PT(CB, 1))).json.events.find(e => e.id === cbGate.id);check('m016: an untouched comment has exactly the keys it had (as when it was written)', keysOf(plainC) === keysOf(cbGate) && plainC.text === cbGate.text, keysOf(plainC) + ' vs ' + keysOf(cbGate));for (const [w, h, name] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {await viewport(b, w, h);check(`m016 layout ${name} ${w}px: the history with the comment blocks has no horizontal overflow`, await noOverflow(b));await shot(b, `${name}-comments`);}await viewport(b, 1280, 900);// ---- mission 017 (tickets#27): ATTACHMENTS — pictures and files with a comment. The "Respond" block's form sits in the shared// FilesUpload (pick mode); the API takes multipart/form-data. REAL input: the chooser's file input (DOM.setFileInputFiles), a real// Ctrl+V of an image INTO the comment editor, real keys + Ctrl+Enter, real clicks. Checked: two chosen + one pasted picture go with// one comment, a second user (B) sees the three thumbnails live and opens one full size; a file over 10 MB is refused (page: in its row;// API: 413); a file that claims to be a PNG but is not is refused; a non-member cannot fetch an attachment (401 / 403) and sees no// thumbnail; the API post of a PNG (multipart) and its download (Content-Type, nosniff, the same bytes); an edit keeps the files,// a delete drops them (404, the bytes leave storage); the Markdown view lists them; 390 px: 44 px targets, no overflow.// Null-safe: on the old code every check here FAILS instead of ending the gate.{const crc = (buf) => { let c, t = []; for (let n = 0; n < 256; n++) { c = n; for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1; t[n] = c >>> 0; } let x = 0xffffffff; for (const v of buf) x = t[(x ^ v) & 0xff] ^ (x >>> 8); return (x ^ 0xffffffff) >>> 0; };const png = (w, h, rgb) => {const chunk = (type, data) => { const len = Buffer.alloc(4); len.writeUInt32BE(data.length); const td = Buffer.concat([Buffer.from(type), data]); const c = Buffer.alloc(4); c.writeUInt32BE(crc(td)); return Buffer.concat([len, td, c]); };const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2;const raw = Buffer.alloc((w * 3 + 1) * h); for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) raw.set([(rgb[0] + x) & 255, (rgb[1] + y) & 255, rgb[2]], y * (w * 3 + 1) + 1 + x * 3);return Buffer.concat([Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]), chunk('IHDR', ihdr), chunk('IDAT', zlib.deflateSync(raw)), chunk('IEND', Buffer.alloc(0))]);};const FD = join(SCRATCH, 'gate-files');rmSync(FD, { recursive: true, force: true });mkdirSync(FD, { recursive: true });const F = (n) => join(FD, n);writeFileSync(F('phone-390.png'), png(390, 640, [30, 90, 160]));writeFileSync(F('desktop-1280.png'), png(1280, 720, [160, 60, 30]));writeFileSync(F('api-shot.png'), png(200, 120, [10, 200, 90]));writeFileSync(F('huge.bin'), Buffer.alloc(11 * 1048576, 3));const ATT_DIR = join(STORE, 'attachments');const storedFiles = () => existsSync(ATT_DIR) ? readdirSync(ATT_DIR).filter(n => !n.startsWith('.')).length : 0;// the API with a multipart body (what a conductor's script does: curl -F / fetch FormData)const apiFiles = async (path, text, files, token = TOKEN) => {const fd = new FormData();if (text !== null) fd.append('text', text);for (const [name, buf, type] of files) fd.append('file', new Blob([buf], { type: type || 'application/octet-stream' }), name);// over the transport's maxBody (20 MiB) the server answers 413 BEFORE reading the body and closes the connection; a client still// writing sees the 413 or a reset (undici: "fetch failed"). Both are a refusal; status 'closed' stands for the reset.let r; try { r = await fetch(BASE + path, { method: 'POST', headers: token ? { authorization: 'Bearer ' + token } : {}, body: fd }); }catch (e) { if (/ECONNRESET|EPIPE|UND_ERR_SOCKET/.test(String(e.cause && e.cause.code) + String(e.cause))) return { status: 'closed', json: null }; throw e; }let json = null; try { json = await r.json(); } catch {}return { status: r.status, json };};const getFile = async (url, headers = {}) => { const r = await fetch(BASE + url, { headers }); return { status: r.status, type: r.headers.get('content-type'), nosniff: r.headers.get('x-content-type-options'), csp: r.headers.get('content-security-policy') || '', disp: r.headers.get('content-disposition') || '', buf: Buffer.from(await r.arrayBuffer()) }; };const atT = await api('POST', `/api/projects/${CB}/tickets`, { subject: 'Screenshots for the review' });const AT = atT.json && atT.json.ticket ? atT.json.ticket : {};const ATURL = '/' + CB + '/' + (AT.number || 2);const ATP = PT(CB, AT.number || 2);// 1. THE API: a PNG through multipart, as a conductor posts a screenshotconst stored0 = storedFiles();const viaApi = await apiFiles(ATP + '/comments', 'The phone view, from a script', [['api-shot.png', readFileSync(F('api-shot.png')), 'image/png']]);const apiAtt = viaApi.json && viaApi.json.event && viaApi.json.event.attachments ? viaApi.json.event.attachments : [];check('m017: API — POST …/comments as multipart (text + a PNG) → 201; the event lists the attachment { id, name, type image/png, size, image, url }', viaApi.status === 201 && apiAtt.length === 1 && apiAtt[0].name === 'api-shot.png' && apiAtt[0].type === 'image/png' && apiAtt[0].image === true && apiAtt[0].size === readFileSync(F('api-shot.png')).length && /^\/api\/attachments\/\w+$/.test(apiAtt[0].url || '') && viaApi.json.event.text === 'The phone view, from a script' && storedFiles() === stored0 + 1, J(viaApi).slice(0, 500));const apiUrl = apiAtt.length ? apiAtt[0].url : '/api/attachments/none';const dl = await getFile(apiUrl, { authorization: 'Bearer ' + TOKEN });check('m017: API — GET the attachment with the token: 200, Content-Type image/png (from its content), nosniff, a sandbox policy, inline, the same bytes', dl.status === 200 && dl.type === 'image/png' && dl.nosniff === 'nosniff' && /sandbox/.test(dl.csp) && /^inline; filename="api-shot.png"/.test(dl.disp) && dl.buf.equals(readFileSync(F('api-shot.png'))), J([dl.status, dl.type, dl.nosniff, dl.csp, dl.disp, dl.buf.length]));const getAgain = (await api('GET', ATP)).json;const apiEv = getAgain && getAgain.events ? getAgain.events.find(e => e.id === (viaApi.json && viaApi.json.event ? viaApi.json.event.id : '')) : null;check('m017: API — GET the ticket returns the attachment list with its URL', !!apiEv && J(apiEv.attachments) === J(apiAtt), J(apiEv).slice(0, 400));// refusals: a fake PNG, a file over 10 MB, more than 25 MB together, a bad field, a files-only post is fineconst fake = await apiFiles(ATP + '/comments', 'not a picture', [['fake.png', Buffer.from('this is text, not a PNG'), 'image/png']]);const huge = await apiFiles(ATP + '/comments', 'too big', [['huge.bin', readFileSync(F('huge.bin'))]]);const nine = Buffer.alloc(9 * 1048576, 5);const tooMuch = await apiFiles(ATP + '/comments', 'three times 9 MB', [['a.bin', nine], ['b.bin', nine], ['c.bin', nine]]);const badField = await (async () => { const fd = new FormData(); fd.append('text', 'x'); fd.append('subject', 'no'); const r = await fetch(BASE + ATP + '/comments', { method: 'POST', headers: { authorization: 'Bearer ' + TOKEN }, body: fd }); return { status: r.status, json: await r.json().catch(() => null) }; })();const noTokenFiles = await apiFiles(ATP + '/comments', 'x', [['api-shot.png', readFileSync(F('api-shot.png')), 'image/png']], null);check('m017: API refusals — a fake PNG 400 ("is not a PNG…"), 11 MB 413, 27 MB together 413 or the closed connection (over maxBody 20 MiB), an unknown field 400, no token 401; nothing stored', fake.status === 400 && /fake\.png is not a PNG, JPEG, GIF or WebP picture/.test((fake.json || {}).error || '') && huge.status === 413 && (tooMuch.status === 413 || tooMuch.status === 'closed') && badField.status === 400 && (badField.json || {}).field === 'subject' && noTokenFiles.status === 401 && storedFiles() === stored0 + 1, J([fake, huge, tooMuch, badField, noTokenFiles].map(r => [r.status, r.json])).slice(0, 700));const onlyFile = await apiFiles(ATP + '/comments', null, [['notes.txt', Buffer.from('plain words\n')]]);check('m017: API — a post with a file and no text is fine (201): a text file, served as a download (text/plain, attachment)', onlyFile.status === 201 && onlyFile.json.event.hasText === false && onlyFile.json.event.attachments[0].image === false && /^text\/plain/.test((await getFile(onlyFile.json.event.attachments[0].url, { authorization: 'Bearer ' + TOKEN })).type) && /^attachment;/.test((await getFile(onlyFile.json.event.attachments[0].url, { authorization: 'Bearer ' + TOKEN })).disp), J(onlyFile).slice(0, 400));const jsonStill = await api('POST', ATP + '/comments', { text: 'a JSON comment as before' });check('m017: API — a JSON comment works as before and carries no attachments key', jsonStill.status === 201 && jsonStill.json.event.attachments === undefined && jsonStill.json.event.text === 'a JSON comment as before', J(jsonStill).slice(0, 300));// 2. THE PAGE: A (alice) chooses two pictures, pastes a third into the editor (real Ctrl+V), types, Ctrl+Enter; B (bob) watchesawait A.conn.send('Browser.grantPermissions', { origin: BASE, permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'] }).catch(() => {});await b.goto(BASE + ATURL);await b.waitForSelector('#events li.comment');await connected(b, 'B on the attachments ticket');await b.evaluate('window.__m017 = 1');await a.goto(BASE + ATURL);await a.waitForSelector('#commentform form.comment-form');await connected(a, 'A on the attachments ticket');await a.waitFor(`[...document.querySelectorAll('#events ul.comment-files img')].length >= 1 && [...document.querySelectorAll('#events ul.comment-files img')].every(i => i.complete && i.naturalWidth > 0)`, { label: 'A: the API picture drawn' }).catch(() => {});check('m017: page — the API\'s picture shows as a drawn thumbnail (200 px) for a member, the text file as a row', (await a.evaluate(`(() => { const i = document.querySelector('#events ul.comment-files img'); return i ? i.naturalWidth : 0; })()`)) === 200 && (await a.evaluate(`[...document.querySelectorAll('#events a.comment-file .name')].map(n => n.textContent).join()`)) === 'notes.txt');const chooseOn = async (page, names) => {const { root } = await page.send('DOM.getDocument');const { nodeId } = await page.send('DOM.querySelector', { nodeId: root.nodeId, selector: '#commentform files-upload label.choose input[type=file]' });try { await page.send('DOM.setFileInputFiles', { files: names.map(F), nodeId }); } catch {}};const pickedOn = (page) => page.evaluate(`[...document.querySelectorAll('#commentform files-upload li.picked')].map(li => li.querySelector('.name').textContent + ':' + (li.querySelector('img.thumb') ? li.querySelector('img.thumb').naturalWidth : 'kind'))`);await chooseOn(a, ['phone-390.png', 'desktop-1280.png']);await a.waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 2 && [...document.querySelectorAll('#commentform files-upload img.thumb')].every(i => i.complete && i.naturalWidth > 0)`, { label: 'A: two chosen' }).catch(() => {});await mdShows(a, '#commentform md-editor article', '', 'A: the comment editor is live').catch(() => {});// the comment editors above the form draw their text a moment after the load and push the form down: a click at the spot measured before hits nothing// and the typed keys go to the body (gate runs F28D2: the editor at y=466 instead of 414, focus on BODY, text never typed). Wait until they have drawn// and the editor stands still, then click and check that the focus is in it.await a.waitFor(`[...document.querySelectorAll('#events li.comment md-editor')].every(m => m.mdMounted)`, { label: 'A: the comment editors have drawn their text' });await calmClick(a, '#commentform md-editor article');await a.waitFor(`document.querySelector('#commentform md-editor').contains(document.activeElement)`, { label: 'A: the focus is in the comment editor' });await realKeys(a, 'Review shots: phone, desktop and a paste');const put = await a.evaluate(`(async () => { try { const c = document.createElement('canvas'); c.width = 160; c.height = 100; const x = c.getContext('2d'); x.fillStyle = '#246'; x.fillRect(0, 0, 160, 100); const bl = await new Promise(r => c.toBlob(r, 'image/png')); await navigator.clipboard.write([new ClipboardItem({ 'image/png': bl })]); return 'ok'; } catch (e) { return 'ERR ' + e.message; } })()`);await a.send('Page.bringToFront');await a.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', modifiers: 2, key: 'v', code: 'KeyV', windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86, commands: ['paste'] });await a.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: 2, key: 'v', code: 'KeyV', windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86 });await a.waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 3 && [...document.querySelectorAll('#commentform files-upload img.thumb')].every(i => i.complete && i.naturalWidth > 0)`, { label: 'A: pasted' }).catch(() => {});const pk = await pickedOn(a);check('m017: page — two chosen pictures + a real Ctrl+V into the comment editor wait as three drawn thumbnails; the editor holds only the text', put === 'ok' && J(pk) === J(['phone-390.png:390', 'desktop-1280.png:1280', 'image.png:160']) && (await a.evaluate(`document.querySelector('#commentform md-editor input.value').value`)) === 'Review shots: phone, desktop and a paste', put + ' ' + J(pk));// a file over 10 MB is refused in its own row before anything is sentawait chooseOn(a, ['huge.bin']);await a.waitFor(`document.querySelectorAll('#commentform files-upload li.refused').length === 1`, { label: 'A: refused' }).catch(() => {});check('m017: page — an 11 MB file is refused in its row ("Too big — at most 10.0 MB"), the three pictures stay', (await a.evaluate(`[...document.querySelectorAll('#commentform files-upload li.refused .state')].map(s => s.textContent).join()`)) === 'Too big — at most 10.0 MB' && (await pickedOn(a)).length === 3);const before = storedFiles();await calmClick(a, '#commentform md-editor article');await ctrlEnter(a);await a.waitFor(`document.querySelectorAll('#commentform files-upload li').length === 0 && [...document.querySelectorAll('#events li.comment')].some(li => li.querySelectorAll('ul.comment-files img').length === 3)`, { timeout: 30000, label: 'A: posted with three' }).catch(() => {});const st = (await api('GET', ATP)).json;const shotC = st && st.events ? st.events.filter(e => e.kind === 'comment').pop() : null;check('m017: page — Ctrl+Enter sends text + the three pictures as ONE comment of alice; stored in order (390, 1280, the paste), the form empty again', !!shotC && shotC.author === 'alice' && shotC.text === 'Review shots: phone, desktop and a paste' && J((shotC.attachments || []).map(x => [x.name, x.type])) === J([['phone-390.png', 'image/png'], ['desktop-1280.png', 'image/png'], ['image.png', 'image/png']]) && storedFiles() === before + 3 && (await a.evaluate(`document.querySelectorAll('#commentform files-upload li').length`)) === 0, J(shotC).slice(0, 500));// B sees them live (no reload) and opens one full sizeawait b.waitFor(`!!document.querySelector('li.comment[data-id="${shotC ? shotC.id : 'x'}"]') && document.querySelectorAll('li.comment[data-id="${shotC ? shotC.id : 'x'}"] ul.comment-files img').length === 3 && [...document.querySelectorAll('li.comment[data-id="${shotC ? shotC.id : 'x'}"] ul.comment-files img')].every(i => i.complete && i.naturalWidth > 0)`, { timeout: 20000, label: 'B: three thumbnails live' }).catch(() => {});const bThumbs = await b.evaluate(`[...document.querySelectorAll('li.comment[data-id="${shotC ? shotC.id : 'x'}"] ul.comment-files img')].map(i => i.naturalWidth)`);check('m017: B (a second user) sees the three thumbnails live, drawn (390, 1280, 160 px wide), without a reload', (await b.evaluate('window.__m017')) === 1 && J(bThumbs) === J([390, 1280, 160]), J(bThumbs));const firstUrl = shotC && shotC.attachments ? shotC.attachments[1].url : '/none';const tabs0 = (await B.conn.send('Target.getTargets')).targetInfos.filter(t => t.type === 'page').length;await b.click(`li.comment[data-id="${shotC ? shotC.id : 'x'}"] ul.comment-files li:nth-child(2) a.comment-thumb`).catch(() => {});let opened = null;for (let i = 0; i < 40 && !opened; i++) { await sleep(250); opened = (await B.conn.send('Target.getTargets')).targetInfos.find(t => t.type === 'page' && t.url === BASE + firstUrl); }check('m017: B — a click on a thumbnail opens the full picture in a new tab', !!opened && (await B.conn.send('Target.getTargets')).targetInfos.filter(t => t.type === 'page').length === tabs0 + 1, J(opened));if (opened) await B.conn.send('Target.closeTarget', { targetId: opened.targetId }).catch(() => {});const bobFull = await getFile(firstUrl, { cookie: bobCookie });check('m017: B — the full picture (bob\'s session, a member): 200 image/png, the 1280 × 720 file byte for byte', bobFull.status === 200 && bobFull.type === 'image/png' && bobFull.buf.equals(readFileSync(F('desktop-1280.png'))), J([bobFull.status, bobFull.type, bobFull.buf.length]));// 3. A NON-MEMBER cannot fetch: a project bob is not in, a picture posted thereconst prv = await api('POST', '/api/projects', { title: 'Attachments private' });const PRV = prv.json && prv.json.project ? prv.json.project.slug : 'attachments-private';await api('POST', `/api/projects/${PRV}/tickets`, { subject: 'Members only' });const prvPost = await apiFiles(PT(PRV, 1) + '/comments', 'a private screenshot', [['private.png', readFileSync(F('api-shot.png')), 'image/png']]);const prvUrl = prvPost.json && prvPost.json.event && prvPost.json.event.attachments ? prvPost.json.event.attachments[0].url : '/api/attachments/none';const nm = [await getFile(prvUrl), await getFile(prvUrl, { cookie: bobCookie }), await getFile(prvUrl, { authorization: 'Bearer ' + bobTok }), await getFile(prvUrl, { authorization: 'Bearer ' + TOKEN }), await getFile('/api/attachments/zzzzzzzzzzzz', { authorization: 'Bearer ' + TOKEN })];check('tickets#37: reading is public, so are the files — no login 200, bob (no member) by session 200 and by token 200, a member 200; unknown 404', prvPost.status === 201 && J(nm.map(r => r.status)) === J([200, 200, 200, 200, 404]) && nm[0].type === 'image/png' && nm[0].buf.equals(readFileSync(F('api-shot.png'))), J(nm.map(r => [r.status, r.type])));await b.goto(BASE + '/' + PRV + '/1');await b.waitForSelector('#events li.comment');await connected(b, 'B on the private ticket');await sleep(500);check('m017: tickets#37: a non-member\'s page shows the picture as a loaded thumbnail inside a link that opens the file', (await b.evaluate(`(() => { const i = document.querySelector('#events ul.comment-files img'); const l = document.querySelector('#events ul.comment-files a'); return !!i && i.complete && i.naturalWidth > 0 && !!l && /^\\/api\\/attachments\\//.test(l.getAttribute('href') || ''); })()`)), await b.evaluate(`(document.querySelector('#events ul.comment-files') || {}).outerHTML`));const nmFace = await temit('commentWithFiles', [AT.id || '', 'x', []], bobCookie);const prvT = (await api('GET', PT(PRV, 1))).json.ticket;const nmFace2 = await temit('commentWithFiles', [prvT ? prvT.id : '', 'bob is no member', []], bobCookie);check('m017: the face commentWithFiles refuses a non-member (bob\'s own session)', !!nmFace2.value && /member/.test(nmFace2.value.error || ''), J([nmFace.raw, nmFace2.raw]));// 4. EDIT keeps the files, DELETE drops themconst edit = await api('POST', `${ATP}/comments/${viaApi.json && viaApi.json.event ? viaApi.json.event.id : 'x'}/edit`, { text: 'The phone view, from a script (edited)' });check('m017: an edit keeps the attachments (same list, the file still served)', edit.status === 200 && J(edit.json.event.attachments) === J(apiAtt) && (await getFile(apiUrl, { authorization: 'Bearer ' + TOKEN })).status === 200, J(edit).slice(0, 300));const n0 = storedFiles();await sleep(1000);await a.waitForSelector(`li.comment[data-id="${shotC ? shotC.id : 'x'}"] button.comment-delete`).catch(() => {});await a.click(`li.comment[data-id="${shotC ? shotC.id : 'x'}"] button.comment-delete`).catch(() => {});await a.waitForSelector(`li.comment[data-id="${shotC ? shotC.id : 'x'}"] button.comment-delete-yes`).catch(() => {});await a.click(`li.comment[data-id="${shotC ? shotC.id : 'x'}"] button.comment-delete-yes`).catch(() => {});await a.waitFor(`!document.querySelector('li.comment[data-id="${shotC ? shotC.id : 'x'}"]')`, { label: 'A: deleted' }).catch(() => {});const goneEv = (await api('GET', ATP)).json.events.find(e => e.id === (shotC ? shotC.id : ''));check('m017: a delete drops the files: no attachments in the API, the addresses answer 404, the three files left storage', !!goneEv && goneEv.deleted === true && goneEv.attachments === undefined && (await getFile(firstUrl, { cookie: aliceCookie })).status === 404 && (await getFile(firstUrl)).status === 404 && storedFiles() === n0 - 3, J([goneEv, storedFiles(), n0]).slice(0, 300));const md = await (await fetch(BASE + ATP, { headers: { accept: 'text/markdown' } })).text();check('m017: the Markdown view lists a comment\'s files with their addresses', md.includes('Attachments:') && md.includes(`- [api-shot.png](${BASE}${apiUrl}) · image/png · `) && !md.includes('phone-390.png'), md.slice(-600));// 5. 390 px: the form with picked files and the thumbnails; touch targets ≥ 44 px, nothing wider than the screenawait b.goto(BASE + ATURL);await b.waitForSelector('#commentform form.comment-form');await connected(b, 'B on the attachments ticket again');await b.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });await b.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });await sleep(300);await chooseOn(b, ['phone-390.png', 'huge.bin']);await b.waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 1 && document.querySelectorAll('#commentform files-upload li.refused').length === 1`, { label: 'B phone picked' }).catch(() => {});await sleep(400);const targets = await b.evaluate(`[...document.querySelectorAll('#events a.comment-thumb, #events a.comment-file, #commentform files-upload label.choose, #commentform files-upload label.camera, #commentform files-upload button.remove, #commentform button.comment-post')].map(el => { const r = el.getBoundingClientRect(); return el.className + ' ' + Math.round(r.width) + 'x' + Math.round(r.height); })`);check('m017 390px: every attachment target is at least 44 × 44 px (thumbnails, file rows, Choose files, Camera, ✕, Comment)', targets.length >= 7 && targets.every(t => { const [w, h] = t.split(' ').pop().split('x').map(Number); return w >= 44 && h >= 44; }), J(targets));check('m017 390px: no horizontal overflow with thumbnails, picked files and a refused row', await noOverflow(b) && (await b.evaluate(`[...document.querySelectorAll('#events ul.comment-files li, #commentform files-upload li')].every(li => li.getBoundingClientRect().right <= window.innerWidth)`)));await shot(b, 'phone-attachments');await b.send('Emulation.setTouchEmulationEnabled', { enabled: false });await viewport(b, 1280, 900);await shot(b, 'desktop-attachments');// ==== UX mission (creator 2026-10-24: "no one will understand that thats a separate form and what it does"): "Respond" is ONE composer —// the editor, the files right under it, and a footer with "Choose files" at the left and `State [select]` + the main button at the right.// REAL input: real keys (typing, the select, Ctrl+A / Backspace), real clicks, a real drop; the chooser's input via DOM.setFileInputFiles.await a.goto(BASE + ATURL);await a.waitForSelector('#commentform form.comment-form');await connected(a, 'A on the attachments ticket (composer)');await viewport(a, 1280, 900);await mdShows(a, '#commentform md-editor article', '', 'A: the composer editor is live').catch(() => {});const SELS = '#commentform select[name=state]';const labelNow = () => a.evaluate(`document.querySelector('#commentform button.comment-post').textContent.trim()`);const stateOf = () => a.evaluate(`document.querySelector('#state').textContent`);const selectedText = () => a.evaluate(`(() => { const s = document.querySelector(${J(SELS)}); return s.options[s.selectedIndex].textContent.trim(); })()`);const pickStateReal = async (name) => {await a.evaluate(`document.querySelector(${J(SELS)}).focus()`);for (let i = 0; i < 14; i++) {if ((await selectedText()) === name) return true;await a.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40 });await a.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40 });await sleep(120);}return false;};const lastEvents = async (n) => { const j = (await api('GET', ATP)).json; return j && j.events ? j.events.slice(-n) : []; };const stOpts = await texts(a, SELS + ' option');const stateStart = await stateOf();// the layout: one boxawait chooseOn(a, ['phone-390.png', 'api-shot.png']);await a.waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 2 && [...document.querySelectorAll('#commentform files-upload img.thumb')].every(i => i.complete && i.naturalWidth > 0)`, { label: 'A: two chosen (composer)' }).catch(() => {});const lay = await a.evaluate(`(() => { const R = (s) => { const e = document.querySelector(s); if (!e) return null; const b = e.getBoundingClientRect(); return { l: Math.round(b.left), r: Math.round(b.right), t: Math.round(b.top), b: Math.round(b.bottom) }; }; const box = document.querySelector('#commentform pick-area'); return { box: R('#commentform pick-area'), editor: R('#commentform md-editor'), list: R('#commentform files-upload ul.files.picked'), choose: R('#commentform pick-area label.choose'), select: R(${J(SELS)}), post: R('#commentform button.comment-post'), inBox: !!box && ['md-editor', 'ul.files', 'label.choose', 'select[name=state]', 'button.comment-post'].every(q => !!box.querySelector(q)), sepForm: !!document.querySelector('#stateform') || document.querySelectorAll('#commentform form').length !== 1 }; })()`);check('UX composer: the editor, the picked files, "Choose files", the State select and the main button are ONE box (one form, no separate state form)', lay.inBox && !lay.sepForm && lay.editor.t >= lay.box.t && lay.list.t >= lay.editor.b - 1 && lay.list.b <= lay.box.b, J(lay));check('UX composer: footer row — "Choose files" at the bottom left, `State [select]` and the main button at the right end, all under the files', lay.choose.l - lay.box.l <= 24 && lay.box.r - lay.post.r <= 24 && lay.select.l > lay.choose.r && lay.select.r < lay.post.l && lay.choose.t >= lay.list.b - 1 && lay.post.t >= lay.list.b - 1 && Math.abs((lay.choose.t + lay.choose.b) / 2 - (lay.post.t + lay.post.b) / 2) <= 8 && lay.post.b <= lay.box.b, J(lay));check('UX composer: the State select starts on "no change", the button says "Comment"', (await selectedText()) === 'no change' && (await labelNow()) === 'Comment' && stOpts[0] === 'no change', J([await selectedText(), await labelNow(), stOpts]));await shot(a, 'composer-desktop-files');// a real drop of a third file onto the EDITOR (not onto a drop zone) collects it tooconst edBox = await a.box('#commentform md-editor');const dropData = { items: [], files: [F('desktop-1280.png')], dragOperationsMask: 1 };for (const type of ['dragEnter', 'dragOver']) await a.send('Input.dispatchDragEvent', { type, x: Math.round(edBox.x), y: Math.round(edBox.y), data: dropData });await a.send('Input.dispatchDragEvent', { type: 'drop', x: Math.round(edBox.x), y: Math.round(edBox.y), data: dropData });await a.waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 3`, { label: 'A: dropped on the editor' }).catch(() => {});check('UX composer: a real drop onto the editor takes the file into the same box (three files waiting)', J(await pickedOn(a)).includes('desktop-1280.png') && (await a.evaluate(`document.querySelectorAll('#commentform files-upload li.picked').length`)) === 3, J(await pickedOn(a)));await a.click('#commentform files-upload li.picked[data-i="2"] button.remove');await a.click('#commentform files-upload li.picked[data-i="1"] button.remove');await a.waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 1`, { label: 'A: one file left' }).catch(() => {});await a.click('#commentform files-upload li.picked[data-i="0"] button.remove');await a.waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 0`, { label: 'A: no files' }).catch(() => {});// 1. COMMENT ONLYconst c0 = await a.evaluate(`document.querySelectorAll('#events li.comment').length`);await a.click('#commentform md-editor article');await realKeys(a, 'UX comment only');check('UX composer: text only → the button says "Comment"', (await labelNow()) === 'Comment', await labelNow());await a.click('#commentform button.comment-post');await a.waitFor(`document.querySelectorAll('#events li.comment').length === ${c0 + 1}`, { label: 'A: the comment shows' }).catch(() => {});const ev1 = await lastEvents(2);check('UX composer: comment only — a comment of alice with that text, no state change (the state stays ' + stateStart + ')', ev1.length === 2 && ev1[1].kind === 'comment' && ev1[1].author === 'alice' && ev1[1].text === 'UX comment only' && (await stateOf()) === stateStart && !(ev1[1].attachments && ev1[1].attachments.length), J(ev1).slice(-300));check('UX composer: after sending, the box is empty again and the button says "Comment"', (await a.evaluate(`document.querySelector('#commentform md-editor input.value').value === '' && document.querySelectorAll('#commentform files-upload li').length === 0`)) && (await selectedText()) === 'no change' && (await labelNow()) === 'Comment');// 2. BOTH, with files chosen through the box's buttonconst target = ['progress', 'open', 'reopened'].find(x => stOpts.includes(x) && x !== stateStart);await chooseOn(a, ['phone-390.png', 'api-shot.png']);await a.waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 2`, { label: 'A: two files (both)' }).catch(() => {});await a.click('#commentform md-editor article');await realKeys(a, 'UX both with files');check('UX composer: files and text, no state chosen → "Comment"', (await labelNow()) === 'Comment', await labelNow());check('UX composer: a real key press on the State select chooses "' + target + '"', await pickStateReal(target));check('UX composer: text + state → the button says "Comment and set to ' + target + '"', (await labelNow()) === 'Comment and set to ' + target, await labelNow());await shot(a, 'composer-desktop-both');await a.click('#commentform button.comment-post');await a.waitFor(`document.querySelector('#state').textContent === ${J(target)} && document.querySelectorAll('#events li.comment').length === ${c0 + 2}`, { label: 'A: comment and state' }).catch(() => {});const ev2 = await lastEvents(3);const cm2 = ev2.find(e => e.kind === 'comment' && e.text === 'UX both with files');check('UX composer: both — the comment arrives with its two files (in order), then the state event; one request each, rules as before', !!cm2 && J((cm2.attachments || []).map(x => x.name)) === J(['phone-390.png', 'api-shot.png']) && ev2[ev2.length - 1].kind === 'state' && ev2[ev2.length - 1].to === target && (ev2[ev2.length - 1].text || '') === '', J(ev2).slice(-500));check('UX composer: the comment shows two thumbnails on the page, the box is empty again', (await a.evaluate(`[...document.querySelectorAll('#events li.comment')].pop().querySelectorAll('ul.comment-files img').length`)) === 2 && (await a.evaluate(`document.querySelectorAll('#commentform files-upload li').length === 0`)) && (await selectedText()) === 'no change');// tickets#33 (caramboleyo: "a newly added comment has a different layout … it should be added to the data of the comments feed and the framework should render it automatically"):// a comment sent together with a state change is a card like every other, at once and after a reload; the state change is its own line without the textconst CARD = (txt) => `(() => { const walk = (n, d) => d > 6 ? '' : [...n.children].filter(c => !c.matches('ul.comment-files')).map(c => c.tagName.toLowerCase() + (c.className && typeof c.className === 'string' && !/\\d{3,}/.test(c.className) ? '.' + c.className.split(' ').sort().join('.') : '') + '(' + walk(c, d + 1) + ')').join(','); const li = [...document.querySelectorAll('#events li.comment')].find(x => x.textContent.includes(${J(txt)})); return li ? { sig: walk(li, 0), avatar: !!li.querySelector('.comment-avatar, [class*=avatar], img.avatar'), like: !!li.querySelector('button.comment-like, [class*=like]'), n: li.querySelectorAll('button').length } : null; })()`;const LINE = `(() => { const ls = [...document.querySelectorAll('#events > li:not(.comments)')]; const l = ls.filter(x => /changed the state/.test(x.textContent)).pop(); return l ? { text: l.textContent.replace(/\\s+/g, ' ').trim(), hasCard: !!l.querySelector('li.comment, md-editor, article') , paras: l.querySelectorAll('p').length } : null; })()`;const plain1 = await a.evaluate(CARD('UX comment only'));const both1 = await a.evaluate(CARD('UX both with files'));check('tickets#33: right after sending, the comment sent with a state change is a card with the same parts as a plain comment (avatar, reactions, buttons)', !!plain1 && !!both1 && plain1.sig === both1.sig && both1.n === plain1.n && both1.n >= 3, J([plain1, both1]).slice(0, 700));const line1 = await a.evaluate(LINE);check('tickets#33: the state change is its own line, without the comment text and without a card inside', !!line1 && !line1.text.includes('UX both with files') && !line1.hasCard && line1.paras === 0 && line1.text.includes(target), J(line1));await a.goto(BASE + ATURL);await a.waitForSelector('#commentform form.comment-form');await connected(a, 'A on the attachments ticket (reload)');// the editors draw their text a moment after the load (their own 100 ms mount); the page is connected before thatawait a.waitFor(`[...document.querySelectorAll('#events li.comment md-editor')].every(m => m.mdMounted)`, { label: 'A: the comment editors have drawn their text' });const plain2 = await a.evaluate(CARD('UX comment only'));const both2 = await a.evaluate(CARD('UX both with files'));check('tickets#33: after a reload the two cards still have the same parts', !!plain2 && !!both2 && plain2.sig === both2.sig && both2.sig === both1.sig, J([plain2, both2]).slice(0, 700) + ' DOM: ' + (await a.evaluate(`J=JSON.stringify; J([...document.querySelectorAll('#events li.comment')].map(l => l.textContent.replace(/\\s+/g, ' ').slice(0, 90)).concat([location.href, document.querySelector('#subject') && document.querySelector('#subject').textContent]))`)));const line2 = await a.evaluate(LINE);check('tickets#33: after a reload the state line is the same', !!line2 && line2.text === line1.text && !line2.text.includes('UX both with files'), J([line1, line2]));await shot(a, 'composer-desktop-after-reload');// 3. STATE ONLY, and the button's words switching with the textconst stOpts2 = await texts(a, SELS + ' option');const t2 = stOpts2.includes('done') ? 'done' : stOpts2.find(x => x !== 'no change' && x !== 'review' && x !== 'pending');check('UX composer: the choices now leave the new current state out and offer the one before', !stOpts2.includes(target) && stOpts2.includes(stateStart === target ? 'open' : stateStart), J(stOpts2));check('UX composer: a real key press chooses "' + t2 + '"', await pickStateReal(t2));check('UX composer: a state and nothing written → "Set to ' + t2 + '"', (await labelNow()) === 'Set to ' + t2, await labelNow());await a.click('#commentform md-editor article');await realKeys(a, 'x');check('UX composer: typing one letter switches the button to "Comment and set to ' + t2 + '"', (await labelNow()) === 'Comment and set to ' + t2, await labelNow());await modKey(a, 'a', 2, 65);await a.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8, nativeVirtualKeyCode: 8 });await a.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8, nativeVirtualKeyCode: 8 });await a.waitFor(`document.querySelector('#commentform button.comment-post').textContent.trim() === ${J('Set to ' + t2)}`, { label: 'A: back to Set to' }).catch(() => {});check('UX composer: deleting the text switches it back to "Set to ' + t2 + '"', (await labelNow()) === 'Set to ' + t2, await labelNow());await shot(a, 'composer-desktop-state');const c2 = await a.evaluate(`document.querySelectorAll('#events li.comment').length`);await a.click('#commentform button.comment-post');await a.waitFor(`document.querySelector('#state').textContent === ${J(t2)}`, { label: 'A: state only' }).catch(() => {});const ev3 = await lastEvents(2);check('UX composer: state only — a state event with no text, and no new comment', ev3[ev3.length - 1].kind === 'state' && ev3[ev3.length - 1].to === t2 && (ev3[ev3.length - 1].text || '') === '' && (await a.evaluate(`document.querySelectorAll('#events li.comment').length`)) === c2, J(ev3).slice(-300));// 4. a refused change keeps what was written: bob-like refusal is not possible for alice, so the empty post does nothingawait a.click('#commentform button.comment-post');await sleep(500);check('UX composer: pressing the button with nothing written and no state chosen sends nothing', J((await lastEvents(1))[0]) === J(ev3[ev3.length - 1]));// phone: the same composer at 390 px — one box, the footer wraps, every target 44 px, nothing wider than the screenawait viewport(a, 390, 844);await chooseOn(a, ['phone-390.png']);await a.waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 1`, { label: 'A: phone file' }).catch(() => {});const t3 = (await texts(a, SELS + ' option')).find(x => x !== 'no change' && x !== 'review' && x !== 'pending');await pickStateReal(t3);await a.evaluate(`document.querySelector('#commentform').scrollIntoView({ block: 'center' })`);const ph = await a.evaluate(`(() => { const box = document.querySelector('#commentform pick-area').getBoundingClientRect(); const tg = [...document.querySelectorAll('#commentform pick-area label.choose, #commentform pick-area label.camera, #commentform pick-area button.remove, #commentform select[name=state], #commentform button.comment-post')].filter(e => e.getBoundingClientRect().width > 0).map(e => { const r = e.getBoundingClientRect(); return e.tagName + '.' + e.className + ' ' + Math.round(r.width) + 'x' + Math.round(r.height) + (r.right > box.right + 1 || r.left < box.left - 1 ? ' OUTSIDE' : ''); }); return { tg, side: document.documentElement.scrollWidth, w: innerWidth }; })()`);check('UX composer 390 px: every control in the box is a 44 px target inside the box, no sideways scroll', ph.tg.length >= 4 && ph.tg.every(t => !/OUTSIDE/.test(t) && +t.split(' ').pop().split('x')[1] >= 44) && ph.side <= ph.w, J(ph));await shot(a, 'composer-phone');await a.evaluate(`document.querySelector('#commentform files-upload li.picked button.remove').click()`);await viewport(a, 1280, 900);check('m017: no console errors on the attachment pages (A and B)', [a, b].every(p => p.problems().filter(m => !/favicon/.test(m.text)).length === 0), a.dumpConsole().slice(-600) + ' | ' + b.dumpConsole().slice(-600));}// tickets#33: an older state change that carries a note (the fixture's alpha #1: "started") shows as a comment card, then the state line aloneawait a.goto(BASE + '/alpha/1');await a.waitForSelector('#events li.comment');await connected(a, 'A on alpha #1 (state note)');const legacyNote = await a.evaluate(`(() => { const walk = (n, d) => d > 6 ? '' : [...n.children].map(c => c.tagName.toLowerCase() + '(' + walk(c, d + 1) + ')').join(','); const cards = [...document.querySelectorAll('#events li.comment')]; const val = (x) => (x.querySelector('md-editor input.value') || {}).value || ''; const note = cards.find(x => val(x) === 'started'); const plain = cards.find(x => val(x) === 'legacy comment on one'); const lines = [...document.querySelectorAll('#events > li:not(.comments)')].filter(l => /changed the state/.test(l.textContent)); return { note: !!note, same: !!note && !!plain && walk(note, 0) === walk(plain, 0), buttons: note ? note.querySelectorAll('button').length : 0, line: lines.length ? lines[lines.length - 1].textContent.replace(/\\s+/g, ' ').trim() : '' }; })()`);check('tickets#33: a state change with a note ("started") shows as a comment card with the same parts as a comment, and its state line has no text', legacyNote.note && legacyNote.same && legacyNote.buttons >= 1 && /changed the state progress/.test(legacyNote.line) && !/started/.test(legacyNote.line), J(legacyNote));// Mission 030: editing a state note preserves the transition and the edit marker.const e30Ticket = await api('POST', '/api/projects/' + CB + '/tickets', { subject: 'Edited state note', summary: 'Mission 030 fixture' });const e30Path = PT(CB, e30Ticket.json.ticket.number);const e30State = await api('POST', e30Path + '/state', { state: 'progress', text: 'original state note' });const e30Id = e30State.json.event.id;const e30Edit = await api('POST', e30Path + '/comments/' + e30Id + '/edit', { text: 'edited state note' });const e30Row = e30Edit.json.event;check('m030: edited state note keeps JSON kind, transition, label and edit metadata', e30Row.kind === 'state' && e30Row.from === 'open' && e30Row.to === 'progress' && e30Row.label === 'changed the state' && e30Row.edited === true && e30Row.text === 'edited state note', J(e30Row));const e30Headline = 'changed the state: open → progress (edited ' + e30Row.editedWhen + ')';const e30Md = await (await fetch(BASE + e30Path, { headers: { accept: 'text/markdown' } })).text();check('m030: Markdown edited state headline retains transition and timestamp', e30Md.includes(e30Headline) && e30Md.includes('edited state note'), e30Md);const e30CommentMd = await (await fetch(BASE + PT(CB, 1), { headers: { accept: 'text/markdown' } })).text();check('m030: ordinary edited comments retain their Markdown label', e30CommentMd.includes('commented (edited '));await a.goto(BASE + e30Ticket.json.ticket.href);await connected(a, 'm030 edited state note');const e30Line = await a.text('#events > li.state event-head');check('m030: HTML edited note keeps its state line and target state', e30Line.includes('changed the state') && e30Line.includes('progress'), e30Line);// a new project by hand: title → slug proposed, admin can change it; old slugs keep workingawait a.goto(BASE + '/new-project');await a.waitForSelector('#projectform');await connected(a, 'A on /new-project');await type(a, '#projecttitle', 'My Project');await a.waitFor('document.querySelector("#projectslug").value === "my-project"', { label: 'slug proposed' });check('project: the slug my-project is proposed from the title', (await a.evaluate('document.querySelector("#projectslug").value')) === 'my-project');await a.click('#projectcreate');await a.waitForSelector('#created');const mp = await api('GET', '/api/projects/my-project');check('project: created; alice is its first admin; it has no tickets', mp.status === 200 && mp.json.project.title === 'My Project' && J(mp.json.members.map(m => [m.name, m.role])) === J([['alice', 'admin']]), J(mp.json).slice(0, 400));await a.goto(BASE + '/projects/my-project/settings');await a.waitForSelector('#detailsform');await connected(a, 'A on settings');await type(a, '#setslug', 'my-proj');await type(a, '#setdescription md-editor input.value', 'The **first** project.');await a.click('#detailssave');await a.waitFor('!!document.querySelector("#savemessage") && document.querySelector("#savemessage").textContent.length > 0', { label: 'saved' });const mp2 = await api('GET', '/api/projects/my-proj');const mpOld = await api('GET', '/api/projects/my-project');check('project: the slug changed, the description is kept, the old slug still resolves', mp2.status === 200 && mp2.json.project.description === 'The **first** project.' && mpOld.status === 200 && mpOld.json.project.slug === 'my-proj', J([mp2.json.project, mpOld.status]).slice(0, 400));const oldSlugMoved = await fetch(BASE + '/projects/my-project', { redirect: 'manual' });check('short (#25): /projects/<old slug> → 301 to /<current slug>', oldSlugMoved.status === 301 && oldSlugMoved.headers.get('location') === '/my-proj', oldSlugMoved.status + ' ' + oldSlugMoved.headers.get('location'));await a.goto(BASE + '/my-project');await a.waitForSelector('#heading');check('project: the old address still opens the project page', (await a.text('#heading')) === 'My Project' || (await a.text('#heading')).includes('My Project'), await a.text('#heading'));// members in the settings page: add bob as use; remove; the last admin cannot goawait a.goto(BASE + '/projects/my-proj/settings');await a.waitForSelector('#addform');await connected(a, 'A on settings again');await type(a, '#addref', 'bob');await choose(a, '#addrole', 'use');await a.click('#addsave');await a.waitFor('document.querySelectorAll("#members li").length === 2', { label: 'bob added' });await sleep(600);check('once: the settings page lists bob exactly once (2 members)', (await texts(a, '#members li')).length === 2 && (await texts(a, '#members li .membername')).filter(t => t === 'bob').length === 1, J(await texts(a, '#members li')));check('members: bob added as use in the settings page', J((await api('GET', '/api/projects/my-proj')).json.members.map(m => [m.name, m.role])) === J([['alice', 'admin'], ['bob', 'use']]));const lastAdmin = await api('POST', '/api/projects/my-proj/members', { user: 'alice', role: 'use' }, aliceTok0);check('members: the last admin cannot be demoted (400)', lastAdmin.status === 400 && /at least one admin/.test(lastAdmin.json.error), J(lastAdmin));const badRole = await api('POST', '/api/projects/my-proj/members', { user: 'bob', role: 'boss' }, aliceTok0);check('members: an unknown role is refused (400)', badRole.status === 400 && badRole.json.field === 'role', J(badRole));const rm = await api('POST', '/api/projects/my-proj/members/remove', { user: 'bob' }, aliceTok0);check('members: an admin removes a member (200)', rm.status === 200 && rm.json.members.length === 1, J(rm).slice(0, 300));// an invite link through identconst inv = await api('POST', '/api/projects/my-proj/invites', { role: 'use' }, aliceTok0);check('invite: an admin gets an ident invite link for the role use', inv.status === 201 && /^https?:\/\//.test(inv.json.url || ''), J(inv).slice(0, 400));// carol opens the link, chooses her identity at ident → ident sends her back to tickets with the invite id → she is a memberconst carol = await ident.signIn('[email protected]');const invPage = await fetch(inv.json.url, { redirect: 'manual' });const rid = (invPage.headers.get('location') || '').split('/').pop();const chosen = await ident.emit('chooseIdentity', [rid, carol.identities[0].id], carol.cookie);const back = chosen.value && chosen.value.url ? await fetch(chosen.value.url.replace(/^https?:\/\/[^/]+/, BASE), { redirect: 'manual' }) : { status: 0, headers: new Headers() };const carolCookie = (back.headers.get('set-cookie') || '').split(';')[0];const carolFace = await temit('saveDisplayName', ['carol'], carolCookie);const mp3 = (await api('GET', '/api/projects/my-proj')).json;check('invite: carol follows the link, picks an identity at ident, is sent back → member with the role use', invPage.status === 302 && back.status === 302 && J(mp3.members.map(m => [m.name, m.role]).filter(x => x[0] === 'carol' || x[1] === 'use')) === J([['carol', 'use']]), J([invPage.status, chosen.raw.slice(0, 200), back.status, mp3.members]).slice(0, 600));const invBob = await api('POST', '/api/projects/my-proj/invites', { role: 'use' }, bobTok);check('invite: a non-admin gets 403', invBob.status === 403, J(invBob).slice(0, 200));// the new pages fit the screen (phone and desktop), with the project's data on themfor (const [path, sel, name] of [['/projects/my-proj/settings', '#addform', 'settings'], ['/new-project', '#projectform', 'new-project'], ['/my-proj', '#heading', 'project']]) {await a.goto(BASE + path);await a.waitForSelector(sel);await connected(a, 'A on ' + path);for (const [w, h, dev] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {await viewport(a, w, h);check(`layout ${dev} ${w}px: ${name} page has no horizontal overflow`, await noOverflow(a));await shot(a, `${dev}-${name}`);}}await viewport(a, 1280, 900);await b.goto(BASE + '/inbox');await b.waitForSelector('#pendingbox');for (const [w, h, dev] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {await viewport(b, w, h);check(`layout ${dev} ${w}px: inbox page has no horizontal overflow`, await noOverflow(b));}await viewport(b, 1280, 900);// ---- ticket #25 (mission 012): /api/projects/<project id>/… answers as /api/projects/<slug>/… (every route under it);// tickets stay under their project, there is no new global /api/tickets/<x>const rawGet = async (path, md = false) => { const r = await fetch(BASE + path, { headers: md ? { accept: 'text/markdown' } : {} }); return r.status + ' ' + (r.headers.get('content-type') || '') + '\n' + await r.text(); };const idOf = async (slug) => (await api('GET', '/api/projects')).json.details.find(p => p.slug === slug).id;const gammaId = await idOf('gamma');check(`ids (#25): a project's id is its 12-character record id (gamma = ${gammaId})`, /^[0-9a-z]{12}$/.test(gammaId || ''), J(gammaId));for (const [byId, bySlug, md] of [[`/api/projects/${gammaId}`, '/api/projects/gamma', false], [`/api/projects/${gammaId}/tickets`, '/api/projects/gamma/tickets', false], [`/api/projects/${gammaId}/tickets`, '/api/projects/gamma/tickets', true], [`/api/projects/${gammaId}/tickets?state=open`, '/api/projects/gamma/tickets?state=open', false], [`/api/projects/${gammaId}/tickets?state=bogus`, '/api/projects/gamma/tickets?state=bogus', false], [`/api/projects/${gammaId}/tickets/1`, '/api/projects/gamma/tickets/1', false], [`/api/projects/${gammaId}/tickets/1`, '/api/projects/gamma/tickets/1', true], [`/api/projects/${gammaId}/tickets/99`, '/api/projects/gamma/tickets/99', false], [`/api/projects/${gammaId}/connections`, '/api/projects/gamma/connections', false]]) {const [x, y] = [await rawGet(byId, md), await rawGet(bySlug, md)];check(`ids (#25): GET ${byId.replace(gammaId, '<id>')}${md ? ' (Markdown)' : ''} answers byte for byte as the slug form`, x === y && /^(200|404|400) /.test(x), J([x.slice(0, 200), y.slice(0, 200)]));}for (const p of ['/api/projects/0zzzzzzzzzzz', '/api/projects/0zzzzzzzzzzz/tickets', '/api/projects/0zzzzzzzzzzz/tickets/1', '/api/projects/0zzzzzzzzzzz/connections']) {const r = await api('GET', p);check(`ids (#25): GET ${p} (no such id) → 404`, r.status === 404, J(r));}const glob = await api('GET', '/api/tickets/' + gammaId);check('ids (#25): no global /api/tickets/<project id> (→ 404, as before)', glob.status === 404, J(glob).slice(0, 200));// every write route under /api/projects/<id>/… on a project of its ownconst dp = await api('POST', '/api/projects', { title: 'Delta by id', slug: 'delta' });const did = dp.json && dp.json.project ? dp.json.project.id : null;const P = (rest) => `/api/projects/${did}${rest}`;const dt = await api('POST', P('/tickets'), { subject: 'made by id' });check('ids (#25): POST /api/projects/<id>/tickets → 201 in that project, #1', dp.status === 201 && dt.status === 201 && dt.json.ticket.project === 'delta' && dt.json.ticket.number === 1, J([dp.status, dt]).slice(0, 300));const dWrites = [['comments', await api('POST', P('/tickets/1/comments'), { text: 'comment by id' })],['state', await api('POST', P('/tickets/1/state'), { state: 'progress' })],['edit', await api('POST', P('/tickets/1/edit'), { subject: 'made by id, edited' })],['assign', await api('POST', P('/tickets/1/assign'), { assignee: 'gate' })],['parent', await api('POST', P('/tickets/1/parent'), { parent: 'gamma#1' })],['blocked-by', await api('POST', P('/tickets/1/blocked-by'), { add: 'gamma#2' })],];check('ids (#25): POST /api/projects/<id>/tickets/1/{comments,state,edit,assign,parent,blocked-by} → 201 each', dWrites.every(([, r]) => r.status === 201), J(dWrites.map(([k, r]) => [k, r.status, r.json && r.json.error])));const dRead = (await api('GET', '/api/projects/delta/tickets/1')).json;check('ids (#25): … and the slug form reads what they wrote', dRead.ticket.subject === 'made by id, edited' && dRead.ticket.state === 'progress' && dRead.ticket.assignee === 'gate' && dRead.ticket.parent && dRead.ticket.parent.key === 'gamma#1' && dRead.ticket.blockedBy.length === 1 && dRead.events.some(e => e.text === 'comment by id'), J(dRead.ticket).slice(0, 500));const dDesc = await api('POST', P(''), { description: 'set by id' });const dMem = await api('POST', P('/members'), { user: 'bob', role: 'use' });const dRm = await api('POST', P('/members/remove'), { user: 'bob' });const dInv = await api('POST', P('/invites'), { role: 'boss' });const dDis = await api('POST', P('/connections/remove'), { id: 'nope' });check('ids (#25): POST /api/projects/<id> (200), /members (200), /members/remove (200); /invites with a bad role and /connections/remove of an unknown key are refused by the PROJECT\'s checks (400, not 404)', dDesc.status === 200 && dDesc.json.project.description === 'set by id' && dMem.status === 200 && dRm.status === 200 && dInv.status === 400 && dInv.json.field === 'role' && dDis.status === 400, J([dDesc.status, dMem.status, dRm.status, dInv, dDis]).slice(0, 500));const zz = await api('POST', '/api/projects/0zzzzzzzzzzz/tickets', { subject: 'nowhere' });check('ids (#25): POST to an unknown id → refused, nothing made', zz.status >= 400 && zz.status < 500, J(zz));// the id survives a slug change; the old slug, the new one and the id answer the sameawait api('POST', P(''), { slug: 'delta2' });const [vId, vNew, vOld] = [await rawGet(P('/tickets/1')), await rawGet('/api/projects/delta2/tickets/1'), await rawGet('/api/projects/delta/tickets/1')];check('ids (#25): after a slug change the id, the new slug and the old slug answer the same ticket', vId === vNew && vNew === vOld && vId.startsWith('200 ') && vId.includes('"project":"delta2"'), J([vId.slice(0, 120), vOld.slice(0, 120)]));check('ids (#25): GET /api/projects/<id> after the slug change → the project with its current slug', (await api('GET', P(''))).json.project.slug === 'delta2');// ---- the browsers said nothing bad (checked BEFORE ident goes down, ticket #11) ------------------const problems = [...a.problems(), ...b.problems()].map(m => m.text).filter(t => !/favicon/.test(t));check('console: no errors or warnings in either browser', problems.length === 0, J(problems).slice(0, 800));// ---- ident down: a login fails politely, the server keeps serving ----------------------------// TICKET #11: no page may be loading while ident stops (a tickets page loads ident's// selector.js → ERR_CONNECTION_REFUSED in the console). Both browsers park on about:blank// first and stay there; the phase is checked with fetch only, and the console again after.for (const p of [a, b]) { await p.goto('about:blank'); }await sleep(300);const quietBefore = [...a.problems(), ...b.problems()].length;await ident.stop();const down = await fetch(BASE + '/login/callback?ident_code=' + 'cd'.repeat(24), { headers: { cookie: GATE_COOKIE }, redirect: 'manual' });const downText = await down.text();const downFace = await temit('identLogin', ['cd'.repeat(24)], GATE_COOKIE);check('ident down: /login/callback → redirect to the error page "login-no-answer" (no 500, no source path; tickets#42)', down.status === 302 && down.headers.get('location') === '/login/failed/login-no-answer' && !/\.hl/.test(downText), down.status + ' ' + downText.slice(0, 300));check('ident down: the selector face answers "ident did not answer", the server keeps serving', downFace.value && downFace.value.error === 'ident did not answer' && (await fetch(BASE + '/')).status === 200, downFace.raw);const lateProblems = [...a.problems(), ...b.problems()].slice(quietBefore).map(m => m.text);check('console: nothing new while ident was down (the browsers were parked, #11)', lateProblems.length === 0, J(lateProblems).slice(0, 800));// ---- THE INSTALLABLE APP (mission 046): manifest, icons, service worker, offline shell ----------------// Its own fresh Chrome C (no worker from A/B), at the END because it stops the server: the offline reload must// not reach the server even through the service worker (the CDP offline emulation is the page's, and it is what// makes navigator.onLine false for the shell's note). ident is already down here (its selector.js fails to load).const home = await (await fetch(BASE + '/')).text();const mhref = (home.match(/<link rel="manifest" href="([^"]+)"/) || [])[1];check('pwa: the page head links the manifest, the apple-touch-icon, the favicon and the theme colour (the header darker)', !!mhref && /<link rel="apple-touch-icon" href="\/icons\/apple-touch-icon.png">/.test(home) && /<link rel="icon" href="\/icons\/icon.svg">/.test(home) && /<meta name="theme-color" content="rgb\(15, 20, 25\)">/.test(home), J([mhref, (home.match(/<link rel="(icon|apple-touch-icon)"[^>]*>|<meta name="theme-color"[^>]*>/g) || [])]));const mres = await fetch(BASE + (mhref || '/__hl/manifest.webmanifest'));let man = {}; try { man = await mres.json(); } catch {}check('pwa: the manifest is served as a web manifest: name tickets, start_url /, display standalone, theme rgb(15, 20, 25)', /manifest\+json/.test(mres.headers.get('content-type') || '') && man.name === 'tickets' && man.start_url === '/' && man.display === 'standalone' && man.theme_color === 'rgb(15, 20, 25)' && man.background_color === 'rgb(25, 30, 35)', J(man).slice(0, 400));const pngSize = async (src) => { const r = await fetch(BASE + src); const buf = Buffer.from(await r.arrayBuffer()); return r.ok && /image\/png/.test(r.headers.get('content-type') || '') && buf.readUInt32BE(0) === 0x89504e47 ? buf.readUInt32BE(16) : 0; };const iconOk = [];for (const ic of man.icons || []) iconOk.push(ic.type === 'image/png' && await pngSize(ic.src) === Number(ic.sizes.split('x')[0]));check('pwa: every manifest icon is a real PNG of its declared size (192 and 512, any and maskable)', iconOk.length === 4 && iconOk.every(Boolean) && ['any', 'maskable'].every(p => (man.icons || []).some(i => i.sizes === '512x512' && i.purpose === p)), J(man.icons));const fav = await fetch(BASE + '/favicon.ico');const favBuf = Buffer.from(await fav.arrayBuffer());const svg = await fetch(BASE + '/icons/icon.svg');check('pwa: apple-touch-icon is a 180px PNG, /favicon.ico an icon file, /icons/icon.svg an SVG', await pngSize('/icons/apple-touch-icon.png') === 180 && fav.ok && /icon/.test(fav.headers.get('content-type') || '') && favBuf.readUInt32LE(0) === 0x00010000 && svg.ok && /svg/.test(svg.headers.get('content-type') || '') && /<svg/.test(await svg.text()));// ---- mission MT (mobile audit 2026-10-23): what a designer sees at 390 px. Each check below FAILED on the code before the fix// (the ticket number wrapped to "# / 2 / 6", two chip rows filled half the screen, fields stood beside their captions at their own// width, the Edit button was a centred slab, 500 rows drawn at once, member names broke mid-word, relation links were 24 px high)const bulkP = await api('POST', '/api/projects', { title: 'Bulk', slug: 'bulk-mt' }, aliceTok0);for (let i = 1; i <= 60; i++) await api('POST', '/api/projects/bulk-mt/tickets', { subject: i === 60 ? 'Bulk ticket 60 with a very long subject ' + 'unbrokenwords'.repeat(8) : 'Bulk ticket ' + i }, aliceTok0);check('mt: the bulk project has 60 tickets (setup)', bulkP.status === 201 && (await api('GET', '/api/projects/bulk-mt/tickets', undefined, aliceTok0)).json.tickets.length === 60, J(bulkP).slice(0, 200));await viewport(a, 390, 844);await a.goto(BASE + '/bulk-mt');await a.waitForSelector('#tickets li');await connected(a, 'A on /bulk-mt');const mtRows = await a.evaluate(`document.querySelectorAll('#tickets li').length`);check('mt (paging): the list draws the newest 50 of 60 tickets and a "Show 50 more (10 left)" button', mtRows === 50 && /Show 50 more \(10 left\)/.test(await a.text('#moretickets')), mtRows + ' ' + await a.evaluate(`(document.querySelector('#moretickets') || {}).textContent`));const mtOrder = await a.evaluate(`[...document.querySelectorAll('#tickets li a.subject')].map(x => x.textContent.replace(/^#\\d+/, '').slice(0, 14))`);check('mt (paging): the 50 rows are the NEWEST 50, newest first (Bulk ticket 60 … Bulk ticket 11)', mtOrder[0] === 'Bulk ticket 60' && mtOrder[1] === 'Bulk ticket 59' && mtOrder[49] === 'Bulk ticket 11', J([mtOrder[0], mtOrder[1], mtOrder[49]]));const mtRefs = await a.evaluate(`[...document.querySelectorAll('#tickets li a.subject ticket-ref')].map(r => Math.round(r.getBoundingClientRect().height))`);check('mt (list row): the ticket number stands on ONE line in front of the subject (never "# / 5 / 0" stacked) — 390 px, ≤ 30 px high', mtRefs.length === 50 && mtRefs.every(h => h <= 30), J(mtRefs));const mtFilter = await a.evaluate(`(() => { const n = document.querySelector('#projectfilter'), s = document.querySelector('#statefilter'); const tops = (e) => new Set([...e.querySelectorAll('a')].map(x => Math.round(x.getBoundingClientRect().top))).size; return [tops(n), tops(s), Math.round(n.getBoundingClientRect().height), Math.round(s.getBoundingClientRect().height)]; })()`);check('mt (filters): the project chips and the state chips are ONE row each at 390 px (they scroll inside their row, not wrap over half the screen)', mtFilter[0] === 1 && mtFilter[1] === 1 && mtFilter[2] <= 64 && mtFilter[3] <= 64, J(mtFilter));// UX mission (creator 2026-10-24: "this also looks placed weirdly and no one will ever understand new form is a collapsable"): "New ticket" is the// accent button and "New project" a quiet one, both at the right end of the heading row; no fold-out bar under the filtersconst mtAct = await a.evaluate(`(() => { const R = (s) => { const e = document.querySelector(s); if (!e) return null; const r = e.getBoundingClientRect(), c = getComputedStyle(e); return { l: Math.round(r.left), r: Math.round(r.right), t: Math.round(r.top), b: Math.round(r.bottom), bg: c.backgroundColor, tag: e.tagName }; }; const accent = getComputedStyle(document.documentElement).getPropertyValue('--color-accent').trim(); return { h1: R('#heading'), nt: R('#newticketbutton'), np: R('#newprojectlink'), row: R('heading-row'), bar: !!document.querySelector('#newticket, ticket-board > details'), accent, vw: innerWidth }; })()`);check('UX list: "New ticket" is an accent button, "New project" a quiet one (no background), both in the heading row at its right end, no fold-out bar', !!mtAct.nt && !!mtAct.np && mtAct.nt.tag === 'BUTTON' && mtAct.np.tag === 'BUTTON' && mtAct.nt.bg !== 'rgba(0, 0, 0, 0)' && mtAct.np.bg === 'rgba(0, 0, 0, 0)' && mtAct.np.r < mtAct.nt.l + 1 && mtAct.nt.r >= mtAct.row.r - 2 && mtAct.nt.t >= mtAct.row.t - 1 && mtAct.nt.b <= mtAct.row.b + 1 && mtAct.np.t >= mtAct.row.t - 1 && !mtAct.bar, J(mtAct));await shot(a, 'mt-phone-bulk');await a.click('#moretickets').catch(() => {});await a.waitFor(`document.querySelectorAll('#tickets li').length === 60`, { label: 'all 60 rows after the click' }).catch(() => {});check('mt (paging): a real click on "Show more" draws the other 10 (60 rows) and the button goes', (await a.evaluate(`document.querySelectorAll('#tickets li').length`)) === 60 && !(await a.evaluate(`!!document.querySelector('#moretickets')`)));check('mt (long subject): a subject of unbroken words does not widen the phone page', await noOverflow(a));const mtNew = await api('POST', '/api/projects/bulk-mt/tickets', { subject: 'Bulk ticket 61, arrives live' }, aliceTok0);await a.waitFor(`document.querySelectorAll('#tickets li').length === 61`, { label: 'live row' }).catch(() => {});check('mt (paging): with everything shown a new ticket arrives live at the top (61 rows, none cut off)', mtNew.status === 201 && (await a.evaluate(`document.querySelectorAll('#tickets li').length`)) === 61 && /Bulk ticket 61/.test(await a.evaluate(`document.querySelector('#tickets li a.subject').textContent`)));// fields: the caption above, the field the full width of its form — settings (admin), the ticket's manage forms, new ticket, /youconst fullW = (sels) => `(() => { const out = []; for (const s of ${J(sels)}) { const e = document.querySelector(s); if (!e) { out.push(s + ' missing'); continue; } const fe = e.closest('form'), cs = getComputedStyle(fe), f = fe.getBoundingClientRect(), r = e.getBoundingClientRect(), inner = f.width - parseFloat(cs.paddingLeft) - parseFloat(cs.paddingRight); if (r.width < inner - 2) out.push(s + ' ' + Math.round(r.width) + ' of ' + Math.round(f.width)); } return out; })()`;await a.goto(BASE + '/projects/my-proj/settings');await a.waitForSelector('#addform');await connected(a, 'A on settings');const mtSet = await a.evaluate(fullW(['#settitle', '#setslug', '#addref', '#addrole', '#inviterole', '#inviteuses', '#invitedays', '#inviteemail']));check('mt (settings): every field is as wide as its form at 390 px (caption above, not beside it)', mtSet.length === 0, J(mtSet));const mtNames = await a.evaluate(`[...document.querySelectorAll('#members .membername')].map(e => [e.textContent, Math.round(e.getBoundingClientRect().height), Math.round(e.getBoundingClientRect().width), Math.round(e.parentElement.getBoundingClientRect().width)])`);check('mt (settings): a member name has the whole first line of its row, unbroken (no mid-word break "AntColonySche / duler")', mtNames.length > 0 && mtNames.every(([, h, w, lw]) => h <= 30 && w >= lw - 40), J(mtNames));await shot(a, 'mt-phone-settings');await a.goto(BASE + '/you');await a.waitForSelector('#tokenform');await connected(a, 'A on /you');check('mt (you): the token label field is as wide as its form', (await a.evaluate(fullW(['#tokenlabel']))).length === 0, J(await a.evaluate(fullW(['#tokenlabel']))));const mtPar = await api('POST', '/api/projects/bulk-mt/tickets/2/parent', { parent: 'bulk-mt#1' }, aliceTok0);await a.goto(BASE + '/bulk-mt/2');await a.waitForSelector('#subject');await connected(a, 'A on the MT child ticket');await a.waitFor(`!!document.querySelector('#parentkey') && !!document.querySelector('#parent a')`, { label: 'manage forms and the parent link' }).catch(() => {});const mtMan = await a.evaluate(fullW(['#assignselect', '#parentkey', '#blockerkey']));check('mt (ticket): the manage and state fields are as wide as their forms at 390 px', mtMan.length === 0, J(mtMan));const mtEdit = await a.evaluate(`(() => { const e = document.querySelector('#editbutton'); return e ? Math.round(e.getBoundingClientRect().width) : -1; })()`);check('mt (ticket): "Edit" is a normal button, not a slab across the whole page (≤ 160 px wide at 390)', mtEdit > 0 && mtEdit <= 160, String(mtEdit));const mtRel = await a.evaluate(`[...document.querySelectorAll('#parent a, .refs a')].map(x => Math.round(x.getBoundingClientRect().height))`);check('mt (relations): the links to the parent / children / blockers are 44 px targets', mtRel.length > 0 && mtRel.every(h => h >= 44), J(mtRel));await shot(a, 'mt-phone-ticket');await a.goto(BASE + '/bulk-mt');await a.waitForSelector('#newticketbutton');await connected(a, 'A on bulk new ticket');const dlgOpen = (id) => a.evaluate(`!!document.querySelector('dialog#${id}[open]')`);await a.click('#newticketbutton');await a.waitFor(`!!document.querySelector('dialog#newticketmodal[open]')`, { label: 'A: the New ticket window opens' });await sleep(400);const mtNewF = await a.evaluate(fullW(['#newproject', '#newsubject']));check('mt (new ticket): project and subject fields are as wide as the form', mtNewF.length === 0, J(mtNewF));const full = await a.evaluate(`(() => { const r = document.querySelector('dialog#newticketmodal').getBoundingClientRect(); return { w: Math.round(r.width), h: Math.round(r.height), t: Math.round(r.top), l: Math.round(r.left), vw: innerWidth, vh: innerHeight }; })()`);check('UX list 390 px: the New ticket window is FULL SCREEN on a phone', full.w >= full.vw - 1 && full.h >= full.vh - 1 && full.t <= 1 && full.l <= 1, J(full));await shot(a, 'list-phone-new-ticket-window');await a.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27, nativeVirtualKeyCode: 27 });await a.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27, nativeVirtualKeyCode: 27 });await a.waitFor(`!document.querySelector('dialog[open]')`, { label: 'A: Esc closes the window' });check('UX list: Esc closes the New ticket window', !(await dlgOpen('newticketmodal')));await a.click('#newprojectlink');await a.waitFor(`!!document.querySelector('dialog#newprojectmodal[open]') && !!document.querySelector('dialog#newprojectmodal #projectform')`, { label: 'A: the New project window opens' });const fullP = await a.evaluate(`(() => { const r = document.querySelector('dialog#newprojectmodal').getBoundingClientRect(); return { w: Math.round(r.width), h: Math.round(r.height), vw: innerWidth, vh: innerHeight }; })()`);check('UX list 390 px: the New project window is full screen too', fullP.w >= fullP.vw - 1 && fullP.h >= fullP.vh - 1, J(fullP));await shot(a, 'list-phone-new-project-window');await a.click('dialog#newprojectmodal button.modal-x');await a.waitFor(`!document.querySelector('dialog[open]')`, { label: 'A: × closes the window' });check('UX list: the × closes the New project window', !(await dlgOpen('newprojectmodal')));await viewport(a, 1280, 900);await sleep(300);// desktop: a centred window; submit a ticket with real keys and a real click; the window closes, the page says so, the row arrivesawait a.click('#newticketbutton');await a.waitFor(`!!document.querySelector('dialog#newticketmodal[open]')`, { label: 'A: the New ticket window opens (desktop)' });await sleep(300);const dw = await a.evaluate(`(() => { const r = document.querySelector('dialog#newticketmodal').getBoundingClientRect(); return { w: Math.round(r.width), l: Math.round(r.left), vw: innerWidth, h: Math.round(r.height), vh: innerHeight }; })()`);check('UX list 1280 px: the New ticket window is a centred window, not full screen', dw.w < 700 && dw.w > 300 && Math.abs((dw.l + dw.w / 2) - dw.vw / 2) <= 4 && dw.h < dw.vh, J(dw));const rows0 = await a.evaluate(`document.querySelectorAll('#tickets li').length`);await a.click('#newsubmit');await sleep(500);check('UX list: submitting an empty subject does nothing (the field is required): the window stays open, no ticket', (await dlgOpen('newticketmodal')) && (await a.evaluate(`document.querySelectorAll('#tickets li').length`)) === rows0, String(rows0));await a.click('#newsubject');await realKeys(a, 'Opened from the window');await a.click('#newsummary md-editor article');await realKeys(a, 'summary typed in the window');await shot(a, 'list-desktop-new-ticket-window');await a.click('#newsubmit');await a.waitFor(`!document.querySelector('dialog[open]') && !!document.querySelector('#notice')`, { label: 'A: the window closes after submit' });// ticketCreated reaches the page after the shell's inbox-count face settles.await a.waitFor(`document.querySelector('#tickets li a.subject')?.textContent.includes('Opened from the window')`, { label: 'A: the newly opened ticket is at the top' });check('UX list: submit — the window closes, the page says "Opened bulk-mt #62." with a link, the new row is at the top', /Opened bulk-mt #62\./.test(await a.text('#notice')) && (await a.evaluate(`document.querySelector('#noticelink').getAttribute('href')`)) === '/bulk-mt/62' && (await a.evaluate(`document.querySelector('#tickets li a.subject').textContent`)).includes('Opened from the window'), await a.text('#notice'));const made = (await api('GET', '/api/projects/bulk-mt/tickets/62', undefined, aliceTok0)).json;check('UX list: the ticket is stored with subject and summary as typed, by alice', !!made && made.ticket && made.ticket.subject === 'Opened from the window' && made.ticket.summary === 'summary typed in the window' && made.ticket.createdBy === 'alice', J(made).slice(0, 300));await a.click('#newprojectlink');await a.waitFor(`!!document.querySelector('dialog#newprojectmodal[open]')`, { label: 'A: the New project window opens (desktop)' });await a.click('#projecttitle');await realKeys(a, 'Window Project');await a.waitFor(`document.querySelector('#projectslug').value === 'window-project'`, { label: 'slug proposed in the window' });await shot(a, 'list-desktop-new-project-window');await a.click('#projectcreate');await a.waitFor(`!document.querySelector('dialog[open]') && /Created Window Project/.test(document.querySelector('#notice') ? document.querySelector('#notice').textContent : '')`, { label: 'A: the project window closes after submit' });check('UX list: New project — the window closes, the page says "Created Window Project." and links its settings', (await a.evaluate(`document.querySelector('#noticelink').getAttribute('href')`)) === '/projects/window-project/settings' && (await api('GET', '/api/projects/window-project', undefined, aliceTok0)).status === 200, await a.text('#notice'));await viewport(a, 1280, 900);C = await launchBrowser({ debugPortRange: range(process.env.TICKETS_GATE_CHROME_C, '8640-8649') });const c = patient(await C.newPage());await viewport(c, 390, 844);await c.goto(BASE + '/');await c.waitForSelector('#tickets li');await connected(c, 'C connected');await c.waitFor('navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))', { label: 'service worker active' });await c.waitFor('!!navigator.serviceWorker.controller', { label: 'the worker controls the page' });check('pwa: a service worker is registered for the whole app and controls the page', await c.evaluate(`navigator.serviceWorker.getRegistration().then(r => !!r && new URL(r.scope).pathname === '/' && /\\/__hl\\/sw\\.js/.test(r.active.scriptURL))`));const inst = await c.send('Page.getInstallabilityErrors');check('pwa: Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, J(inst));// the list holds TOTAL + the one ticket made through /api/projects/<id>/tickets (mission 012) + mission 016's comments ticket + mission 017's attachments ticket + the 'Members only' ticket (reading a ticket is public; only its files are members-only)const LISTED = Math.min(50, TOTAL + 4 + 61); // mission MT: the list draws 50 rows (+ "Show more") — the bulk project of the phone checks adds 61const online = await c.evaluate(`[!!document.querySelector('#offline'), document.querySelectorAll('#tickets li').length]`);check('pwa: online the shell shows no offline note', online[0] === false && online[1] === LISTED, J(online) + " expected " + LISTED + " TOTAL " + TOTAL);const cProblems = c.problems().map(m => m.text).filter(t => !/favicon/.test(t) && !t.includes(':' + IDENT_PORT) && !/Failed to load resource/.test(t));check('pwa: no console errors in the installed app (ident is down: its selector.js is not counted)', cProblems.length === 0, J(cProblems).slice(0, 600));await sleep(1500);await shot(c, 'pwa-phone-online');// tickets#37: SIGNED OUT (browser C has no session) the picture of a comment is a loaded thumbnail inside a link, and its bytes come with no loginawait c.goto(BASE + '/attachments-private/1');await c.waitForSelector('#events li.comment');await c.waitFor(`!!document.querySelector('#events ul.comment-files img') && document.querySelector('#events ul.comment-files img').complete`, { label: 'C: the thumbnail loads' });check('tickets#37: signed out, the comment\'s picture is a loaded thumbnail inside a link to the file', await c.evaluate(`(() => { const i = document.querySelector('#events ul.comment-files img'); const l = document.querySelector('#events ul.comment-files a'); return !!i && i.naturalWidth > 0 && !!l && /^\\/api\\/attachments\\//.test(l.getAttribute('href') || ''); })()`));await shot(c, 'signed-out-thumbnail-phone');// OFFLINE: the network of the page is cut AND the server is gone; `/` reloads from the worker's cacheawait stopTickets();await c.setOffline(true);await c.goto(BASE + '/');await c.waitForSelector('#tickets li');await c.waitFor('!!document.querySelector("#offline")', { label: 'the offline note' });const off = await c.evaluate(`[document.querySelector('application-header .brand').textContent, document.querySelector('#offline').textContent, document.querySelectorAll('#tickets li').length, getComputedStyle(document.querySelector('#offline')).display]`);check('pwa: offline reload of / shows the shell (header), the last loaded list and says it is offline', off[0] === 'tickets' && /You are offline/.test(off[1]) && off[2] === LISTED && off[3] !== 'none', J(off));await sleep(300);await shot(c, 'pwa-phone-offline');check('layout phone 390px: the offline shell has no horizontal overflow', await noOverflow(c));await c.goto(BASE + '/inbox');await c.waitForSelector('main[data-hl-offline]');check('pwa: offline a page that is not kept (/inbox) gets "Unavailable offline"', /Unavailable offline/.test(await c.text('main')), await c.text('main'));await c.goto(BASE + '/');await c.waitForSelector('#offline');await c.setOffline(false);await c.waitFor('!document.querySelector("#offline")', { label: 'the note goes when the network is back' });check('pwa: the offline note goes when the browser is online again', true);} catch (e) {check('gate ran to the end', false, e.stack || String(e));} finally {for (const br of [A, B, C]) { if (br) { try { await br.close(); } catch {} } }await stopTickets();if (ident) { await ident.stop(); writeFileSync(join(SCRATCH, 'gate-ident.log'), ident.log()); }exchProxy.close();writeFileSync(join(SCRATCH, 'gate-server.log'), log);}console.log(`\n${passes} passed, ${failures} failed`);process.exit(failures ? 1 : 0);
Branches
Latest commits
- bf58534eMerge branch 'l33-final' into mainTickets
- 759a9ac3|||PR thin login (tickets#46, #45): merge main, route entry cleanupmre
- 239436d8Merge remote-tracking branch 'origin/main' into l33-finalmre
- 5822cb3aMerge branch 'o34-clean' into mainTickets
- 0870653c|||PR offline note from __hlOnline, no polling (tickets#41)mre
- 14cf96b4Merge branch 'records-t36' into mainTickets
- 07749fa1|||PR records: day72 + #40 mergedmre
- ecd7e226|||PR Consolidate login and move handler logic into topic libraries (partial)mre
- 6dea1c60Merge branch 'r35-day72' into mainTickets
- 7bcfdc22|||PR drop worker edits to conductor recordsmre
- 2617b6ee|||PR dialogs: host flag cleared on close, dialog gate (tickets#40)mre
- 6e701371|||PR record partial day72 dialog validationmre
- b9fb9a91|||PR bind ticket dialog visibility to member flagsmre
- 0788e65f|||PR re-vendor Hybriel day72mre
- e2a6bdcfMerge branch 'records-t35' into mainTickets
- d8d54df1|||PR records: R35 day72 + #40mre
- 8a7f475aMerge branch 'records-t33' into mainTickets
- e685d0c2|||PR records: PROCEDURES merge callmre
- b42aff2b|||PR records: GO 2026-11-23, workers L33 O34, PROCEDURES.mdmre
- ed091d44Merge branch 'records' into mainTickets