gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit1c10857b1c10857bTickets conductor: P51 eval, brief 027mre1c10857b/tests/browser.mjs

193.9 KB

  1. // tests/browser.mjs — THE GATE of tickets.worldapi.org: its own server on its own
  2. // storage, the import command, the JSON API, and TWO real headless Chromes (two
  3. // viewers) for the live push. Everything is checked in the browser's DOM, not in
  4. // curl output. Ticket #10 added: the strict API table (unknown / missing / empty /
  5. // wrong-type fields → 400 naming the field, nothing written), Vienna local time (checked
  6. // against node's Intl, also tests/localtime.hl's DST edges), and the paragraph import
  7. // (a CRLF fixture in .scratch/gate-import → #7, rendered with a blank line between).
  8. // Ticket #15 added: `author` required on every POST (missing/empty → 400 naming author),
  9. // invalid JSON → 400 { error } without source paths (jsoncheck.hl), the web forms have no
  10. // name field (author 'creator'), and list lines kept by the import (.scratch/gate-import-lists → hybriel #3).
  11. // Ticket #38 (mission 008) added: UUID keys + storage in <store>/mpackdb, per-project
  12. // numbers and URLs /<slug>/<number> (ticket #25; was /projects/<slug>/<number>). The gate FIRST writes an old-format store
  13. // (tests/oldstore.hl: 5 tickets, old #1–#5 in projects alpha / beta.example.org), migrates
  14. // it TWICE with tools/migrate-008.hl (the second run must write nothing), and runs the
  15. // server on the migrated tables: old numbers answer on /api/tickets/<n>, /tickets/<n>
  16. // redirects (301) to the new URL, the per-project API, live pushes carrying the new hrefs.
  17. // Ticket #7 (mission 011) added LOGIN VIA IDENT: the gate runs its OWN ident (a copy of
  18. // ident's code without .env / storage — codes go to a mail sink, never real mail; tests/identkit.mjs)
  19. // on :8353, registers tickets there (origin = this gate's server), and then: every API write
  20. // needs `Authorization: Bearer <token>` (401 otherwise, checked before the body; `author` in a
  21. // body → 400), a machine user "gate" logs in through the login button's server half
  22. // (/login/callback) and makes its token over the face; the FIRST server runs without
  23. // TICKETS_CREATOR_IDENTITY (nobody may confirm/reject → 403), the second with alice's per-app id.
  24. // In the browsers: signed out = reading only; A (alice, the creator) logs in with the identity
  25. // SELECTOR, B (bob) with ident's /login link (no header button since 2026-10-24); both get the display-name prompt; writes show the
  26. // user as author; bob cannot confirm/reject, alice can; bob's token on /you: shown once → API
  27. // write as bob → revoke → 401; forged face sessions (#31) are refused; old events keep their
  28. // authors; logout resets the selector.
  29. // Ticket #12 (mission 024) added THE MARKDOWN EDITOR; since mission 016 every Markdown field is the Hybriel MdEditor
  30. // (components/md-editor/) and the comments are the shared Comments block (components/comments/, layouts#2): typed with
  31. // real keys, Ctrl+Enter sends; "m016:" checks edit (the earlier version folds out), delete (asks first), like (toggle),
  32. // Edit / Delete only on your own comments, comments in place between the other history entries, a non-member reads
  33. // only and the server refuses them (faces + API), the comment API. The blocks' own gate: components.hybriel.worldapi.org.
  34. //
  35. // node tests/browser.mjs (TICKETS_GATE_PORT to move the server, default 8352;
  36. // TICKETS_GATE_IDENT_PORT the gate's ident, default 8353;
  37. // TICKETS_GATE_IDENT_DIR ident's code, default ../ident.worldapi.org)
  38. //
  39. // Debug ports: 8620-8629 (browser A) and 8630-8639 (browser B) — TICKETS_GATE_CHROME_A /
  40. // TICKETS_GATE_CHROME_B ("8810-8814") move them (mission 017: parallel workers get disjoint
  41. // port ranges); browser C (mission 046, the installable app / offline part at the end) 8640-8649,
  42. // TICKETS_GATE_CHROME_C. Screenshots at 390px
  43. // and 1280px land in .scratch/gate-*.png — LOOK at them. The whole server log is kept in
  44. // .scratch/gate-server.log. Every process started here (server, import runs, Chromes)
  45. // is stopped by PID in `finally`.
  46. import { spawn, spawnSync } from 'node:child_process';
  47. import http from 'node:http';
  48. import { rmSync, mkdirSync, writeFileSync, existsSync, readdirSync, copyFileSync, readFileSync } from 'node:fs';
  49. import { dirname, join, resolve } from 'node:path';
  50. import { fileURLToPath } from 'node:url';
  51. import zlib from 'node:zlib';
  52. import { launchBrowser } from './cdp.mjs';
  53. import { startIdent } from './identkit.mjs';
  54. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  55. const HERE = dirname(fileURLToPath(import.meta.url));
  56. const APP = resolve(HERE, '..');
  57. const BIN = join(APP, 'bin/hybriel');
  58. const PORT = Number(process.env.TICKETS_GATE_PORT || 8352);
  59. const BASE = `http://127.0.0.1:${PORT}`;
  60. const SCRATCH = join(APP, '.scratch');
  61. const STORE = join(SCRATCH, 'gate-store');
  62. const IDENT_PORT = Number(process.env.TICKETS_GATE_IDENT_PORT || 8353);
  63. // ident's CODE (read only — copied without .env/storage by identkit): the sibling folder,
  64. // or the Loreana path when the gate runs in a copy (.scratch/dev…)
  65. 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')));
  66. rmSync(STORE, { recursive: true, force: true });
  67. mkdirSync(join(STORE, 'mpackdb'), { recursive: true });
  68. // 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
  69. // 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
  70. // header, not on the right, covered by something else).
  71. const SELECTOR_IN_HEADER = `(() => { const s = document.querySelector('application-header ident-selector'); if (!s) return 'no ident-selector in the header';
  72. 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; }
  73. const b = s.getBoundingClientRect(), h = document.querySelector('application-header').getBoundingClientRect();
  74. if (b.width < 40 || b.height < 30) return 'no box ' + b.width + 'x' + b.height;
  75. 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]);
  76. 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]);
  77. if (b.left + b.width / 2 < innerWidth / 2) return 'not at the top right ' + b.left;
  78. 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);
  79. return 'ok'; })()`;
  80. let failures = 0, passes = 0;
  81. function check(label, ok, detail = '') {
  82. console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);
  83. if (ok) passes++; else failures++;
  84. }
  85. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  86. const J = JSON.stringify;
  87. // a re-vendored Hybriel compiles each entry at its first start (cold ~20 s on Loreana, hybriel#148; then ~1 s from
  88. // ~/.hybriel/cache/run): every start of a .hl program waits up to COLD_MS (TICKETS_COLD_MS, default 120 s)
  89. const COLD_MS = Number(process.env.TICKETS_COLD_MS || 120000);
  90. // ---- the legacy fixture (ticket #20): a store from before projects were own data; the server's migrate.hl
  91. // turns it into projects with ids, members and the new states at its first start ----------------------
  92. 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 || ''); };
  93. const fixture = hl('tests/oldstore.hl', { TICKETS_STORAGE: join(STORE, 'mpackdb') });
  94. check('migrate: the pre-#20 fixture is written (2 projects, 5 tickets, 8 events)', /oldstore: 2 projects, 5 tickets, 8 events/.test(fixture), fixture);
  95. // ---- the servers: our own ident, then tickets (twice: without and with a creator) ----------
  96. let log = '';
  97. let server = null;
  98. let ident = null;
  99. // ticket #9 (mission 012): the exchanges ident RECEIVES from tickets, counted by a small proxy
  100. // between the two (tickets' IDENT_EXCHANGE_URL → here → our ident)
  101. const EXCH_PORT = Number(process.env.TICKETS_GATE_EXCHANGE_PORT || 8357);
  102. const exchanges = [];
  103. const exchProxy = http.createServer((req, res) => {
  104. let body = '';
  105. req.on('data', d => body += d);
  106. req.on('end', async () => {
  107. try {
  108. 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 });
  109. const t = await r.text();
  110. let code = ''; try { code = JSON.parse(body).code || ''; } catch {}
  111. exchanges.push({ path: req.url, code, status: r.status });
  112. res.writeHead(r.status, { 'content-type': r.headers.get('content-type') || 'application/json' });
  113. res.end(t);
  114. } catch (e) { req.socket.destroy(); } // ident stopped: tickets must see NO answer, like a direct connection
  115. });
  116. });
  117. await new Promise((ok, bad) => { exchProxy.once('error', bad); exchProxy.listen(EXCH_PORT, '127.0.0.1', ok); });
  118. let APPKEY = null;
  119. function startTickets(extraEnv) {
  120. log += `\n==== tickets server start ${J(Object.keys(extraEnv))}\n`;
  121. server = spawn(BIN, ['project.hl'], {
  122. cwd: APP,
  123. env: { ...process.env, TICKETS_PORT: String(PORT), TICKETS_STORAGE: join(STORE, 'mpackdb'), TICKETS_SESSIONS: join(STORE, 'sessions'),
  124. 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,
  125. TICKETS_CREATOR_IDENTITY: '', TICKETS_WATCH: '0', ...extraEnv },
  126. stdio: ['ignore', 'pipe', 'pipe'],
  127. });
  128. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  129. }
  130. async function stopTickets() {
  131. if (!server) return;
  132. const s = server;
  133. try { s.kill('SIGTERM'); } catch {}
  134. await new Promise(r => { if (s.exitCode !== null || s.signalCode !== null) return r(); s.once('exit', r); setTimeout(r, 3000); });
  135. }
  136. async function ticketsUp() {
  137. for (const end = Date.now() + COLD_MS; Date.now() < end;) { try { const r = await fetch(BASE + '/'); if (r.ok) return; } catch {} await sleep(250); }
  138. throw new Error(`server did not come up within ${COLD_MS} ms\n` + log);
  139. }
  140. // THE API: reads never carry a token (reading is public); writes carry the gate user's
  141. // token unless another (or none: null) is given
  142. let TOKEN = null;
  143. const api = async (method, path, body, token = TOKEN) => {
  144. const headers = body ? { 'content-type': 'application/json' } : {};
  145. if (method !== 'GET' && token) headers.authorization = 'Bearer ' + token;
  146. const r = await fetch(BASE + path, { method, headers, body: body ? J(body) : undefined });
  147. let json = null; try { json = await r.json(); } catch {}
  148. return { status: r.status, json };
  149. };
  150. const runImport = (token = TOKEN) => {
  151. const r = spawnSync(BIN, ['tools/import.hl'], { cwd: APP, env: { ...process.env, TICKETS_URL: BASE, TICKETS_TOKEN: token || '' }, encoding: 'utf8', timeout: COLD_MS });
  152. return (r.stdout || '') + (r.stderr || '');
  153. };
  154. // a face over the REST carrier (POST /__hl/emit) with a cookie (or none)
  155. let emitI = 0;
  156. // hybriel#16 (mission 036): hl:web itself refuses an emit with one argument too many — the ack is
  157. // ok:false "… the `session` parameter is filled by the server, never by the peer"; the face never runs.
  158. 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; } };
  159. const temit = async (event, payload, cookie) => {
  160. const r = await fetch(BASE + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: ++emitI, event, payload }) });
  161. const raw = await r.text();
  162. let j = null; try { j = JSON.parse(raw); } catch {}
  163. return { status: r.status, value: j ? j.value : undefined, raw };
  164. };
  165. const cookieOf = (r) => (r.headers.get('set-cookie') || '').split(';')[0];
  166. const texts = (page, sel) => page.evaluate(`Array.from(document.querySelectorAll(${J(sel)})).map(e => e.textContent.trim())`);
  167. // MISSION 016: the history as rows. A run of comments is ONE Comments block (components/comments/) in the history: each of its
  168. // comments is a row { kind 'comment', id, author, text (its Markdown, the block's hidden field), drawn (what the browser drew) };
  169. // every other entry a row { kind (the li's class), author, head, text (its event-text) }.
  170. 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 ?? '' }])`);
  171. // REAL keys: characters, '\n' = Enter; Shift+Enter (a line break in the MdEditor), Ctrl+Enter (sends the form), End
  172. const realKeys = async (page, text) => {
  173. for (const ch of text) {
  174. if (ch === '\n') {
  175. await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 });
  176. await page.send('Input.dispatchKeyEvent', { type: 'char', key: 'Enter', text: '\r' });
  177. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 });
  178. } else {
  179. await page.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch });
  180. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });
  181. }
  182. }
  183. };
  184. const modKey = async (page, key, modifiers, vk, text) => {
  185. await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key, code: key, windowsVirtualKeyCode: vk, modifiers });
  186. if (text) await page.send('Input.dispatchKeyEvent', { type: 'char', key, text, modifiers });
  187. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key, code: key, windowsVirtualKeyCode: vk, modifiers });
  188. };
  189. const ctrlEnter = (page) => modKey(page, 'Enter', 2, 13);
  190. const shiftEnter = (page) => modKey(page, 'Enter', 8, 13, '\r');
  191. const endKey = (page) => modKey(page, 'End', 0, 35);
  192. // an MdEditor builds its content once the page is live (a CSS animation hands it over): wait until it shows `text`
  193. // a real click lands at the coordinates the element had when they were measured: a push re-draws the comments (the read-only
  194. // MdEditors build their text a moment later and move the buttons below them), and a press at the old spot hits nothing —
  195. // the server never saw the click (mission 019, "B: unliked"). So wait until the element has not moved for half a second.
  196. const calmClick = async (page, sel) => {
  197. 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 });
  198. await page.evaluate('delete window.__calm');
  199. await page.click(sel);
  200. };
  201. const mdShows = (page, sel, text, label) => page.waitFor(`(() => { const a = document.querySelector(${J(sel)}); return !!a && a.textContent === ${J(text)}; })()`, { label });
  202. const type = (page, sel, value) => page.evaluate(`(() => { const i = document.querySelector(${J(sel)}); i.value = ${J(value)}; i.dispatchEvent(new Event("input", { bubbles: true })); })()`);
  203. const choose = (page, sel, value) => page.evaluate(`(() => { const i = document.querySelector(${J(sel)}); i.value = ${J(value)}; i.dispatchEvent(new Event("change", { bubbles: true })); })()`);
  204. // CONNECTED = the server has READ the tab's `hello` (its mounts), not just an open socket: a push the server sends
  205. // before that reaches no component (mission 046: "inbox follows the state change live" failed ~1 in 5 when the API
  206. // write overtook the hello). A `ping` sent after the hello on the same socket is answered after it — its pong proves it.
  207. 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); })`;
  208. const connected = async (page, label) => {
  209. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label });
  210. if (!(await page.evaluate(helloRead))) throw new Error('no pong after the hello: ' + label);
  211. };
  212. // a client-side navigation by a REAL click, then the socket announced the new mounts
  213. const clickNav = async (page, sel, cond, label) => { await page.click(sel); await page.waitFor(cond, { label }); await sleep(300); };
  214. async function viewport(page, width, height) {
  215. await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 });
  216. await sleep(250);
  217. }
  218. async function shot(page, name) {
  219. const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  220. writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64'));
  221. }
  222. const noOverflow = (page) => page.evaluate('document.documentElement.scrollWidth <= window.innerWidth');
  223. // INSIDE ident's selector (shadow DOM): an expression over its root `r`, and a REAL click
  224. const sh = (expr) => `(() => { const h = document.querySelector('#selector'); const r = h && h.shadowRoot; if (!r) return null; return (${expr}); })()`;
  225. async function shClick(page, inner, name = null) {
  226. 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 }; })()`;
  227. const box = await page.waitFor(find, { label: 'selector ' + inner + ' ' + (name || '') });
  228. const at = { x: Math.round(box.x), y: Math.round(box.y), button: 'left', clickCount: 1 };
  229. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', ...at, buttons: 0 });
  230. await page.send('Input.dispatchMouseEvent', { type: 'mousePressed', ...at, buttons: 1 });
  231. await page.send('Input.dispatchMouseEvent', { type: 'mouseReleased', ...at, buttons: 0 });
  232. }
  233. const connectedIdent = (page) => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'ident page hydrated' });
  234. // sign in to OUR ident on ident's own page (email → code from the sink → skip the names)
  235. async function identSignIn(page, email) {
  236. await page.goto(ident.base + '/');
  237. await page.waitForSelector('#email');
  238. await connectedIdent(page);
  239. await page.type('#email', email);
  240. await page.click('#sendcode');
  241. // ident#20: a sent code NAVIGATES to ident's /code page; type only once that page is hydrated
  242. await page.waitFor('/\\/code$/.test(location.pathname) && !!document.querySelector("#code")', { label: 'ident /code page' });
  243. await connectedIdent(page);
  244. await page.type('#code', ident.lastCode(email));
  245. await page.click('#verify');
  246. await page.waitForSelector('#signout, #menusignout', { timeout: 10000 });
  247. }
  248. // TICKET #11 (mission 014): the gate must stay green while other browsers load the machine.
  249. // Every wait of a page (waitFor / waitForSelector / click / goto) gets SLOW× its timeout
  250. // (TICKETS_GATE_SLOW, default 3: 10 s → 30 s) — a wait that succeeds returns at once, so a green
  251. // run costs nothing; only a real failure waits longer before it says so.
  252. const SLOW = Number(process.env.TICKETS_GATE_SLOW || 3);
  253. function patient(page) {
  254. const waitFor = page.waitFor.bind(page);
  255. page.waitFor = (expr, o = {}) => waitFor(expr, { ...o, timeout: (o.timeout || 10000) * SLOW });
  256. const goto = page.goto.bind(page);
  257. page.goto = (url, o = {}) => goto(url, { ...o, timeout: (o.timeout || 15000) * SLOW });
  258. return page;
  259. }
  260. let A, B, C;
  261. const range = (v, dflt) => (v || dflt).split('-').map(Number);
  262. try {
  263. // ---- ticket #7: our own ident, tickets registered in it ----------------------------------
  264. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  265. const alice = await ident.signIn('[email protected]');
  266. const bob = await ident.signIn('[email protected]');
  267. const gateAcct = await ident.signIn('[email protected]');
  268. APPKEY = await ident.registerApp(alice, 'tickets (gate)', [BASE]);
  269. 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')));
  270. // alice's per-app id — what the architect puts into TICKETS_CREATOR_IDENTITY
  271. const ALICE_ID = await ident.exchange(APPKEY, await ident.selectorCode(alice, APPKEY, BASE));
  272. const GATE_ID = await ident.exchange(APPKEY, await ident.selectorCode(gateAcct, APPKEY, BASE));
  273. 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);
  274. // ---- server #1: NO creator configured ---------------------------------------------------
  275. startTickets({});
  276. await ticketsUp();
  277. // the machine user "gate": the login button's SERVER half (ident → /login/callback?ident_code=)
  278. const first = await fetch(BASE + '/');
  279. let GATE_COOKIE_0 = '';
  280. // sessions are lazy (hybriel ac1ed9da): a plain page visit stores nothing and sets no cookie; the cookie comes with the first
  281. // thing a visitor stores. An upload start stores a session, so the visitor who is about to sign in gets his cookie from there.
  282. 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);
  283. let GATE_COOKIE = GATE_COOKIE_0;
  284. const noCode = await fetch(BASE + '/login/callback', { headers: { cookie: GATE_COOKIE }, redirect: 'manual' });
  285. 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'));
  286. const badCode = await fetch(BASE + '/login/callback?ident_code=' + 'ab'.repeat(24), { headers: { cookie: GATE_COOKIE }, redirect: 'manual' });
  287. 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'));
  288. const gateCode = await ident.selectorCode(gateAcct, APPKEY, BASE);
  289. const cb = await fetch(BASE + '/login/callback?ident_code=' + gateCode, { headers: { cookie: GATE_COOKIE }, redirect: 'manual' });
  290. check('login: /login/callback exchanges the code → 302 to /', cb.status === 302 && cb.headers.get('location') === '/', cb.status + ' ' + cb.headers.get('location'));
  291. // ident#28: the login stays on the session the browser brought (same cookie, same id); it is signed in afterwards
  292. const rotated = cookieOf(cb);
  293. 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);
  294. if (rotated !== "") GATE_COOKIE = rotated
  295. const again = await fetch(BASE + '/login/callback?ident_code=' + gateCode, { headers: { cookie: GATE_COOKIE }, redirect: 'manual' });
  296. 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');
  297. // ticket #10: the button's return URL carries ?next=<page> (login.js); /login/callback follows
  298. // only a same-origin PATH, anything else → /
  299. for (const [next, want] of [
  300. ['/projects/alpha/2', '/projects/alpha/2'], ['/project/alpha/state/open?x=1&y=2', '/project/alpha/state/open?x=1&y=2'], ['/inbox', '/inbox'],
  301. ['/%2F%2Fevil.example', '/%2F%2Fevil.example'],
  302. ['//evil.example/x', '/'], ['https://evil.example/', '/'], ['http:/evil.example', '/'], ['/\\evil.example', '/'], ['javascript:alert(1)', '/'],
  303. ['evil.example', '/'], ['/a b', '/'], ['/x\r\nSet-Cookie: a=b', '/'], ['/x"><script>', '/'], ['/login/callback', '/'], ['/' + 'a'.repeat(500), '/'], ['', '/'],
  304. ]) {
  305. const c = await ident.selectorCode(gateAcct, APPKEY, BASE);
  306. const r = await fetch(BASE + '/login/callback?next=' + encodeURIComponent(next) + '&ident_code=' + c, { headers: { cookie: GATE_COOKIE }, redirect: 'manual' });
  307. 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'));
  308. if (r.status === 302) GATE_COOKIE = cookieOf(r);
  309. }
  310. let html = await (await fetch(BASE + '/', { headers: { cookie: GATE_COOKIE } })).text();
  311. 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"'));
  312. check('login: the page never carries the identity id (only /you does)', !html.includes(GATE_ID));
  313. let f = await temit('commentOn', ['x', 'before the name'], GATE_COOKIE);
  314. check('login: no writing before a display name', f.value && /display name first/.test(f.value.error), f.raw);
  315. f = await temit('saveDisplayName', [' '], GATE_COOKIE);
  316. check('name: an empty display name is refused', f.value && /must not be empty/.test(f.value.error), f.raw);
  317. f = await temit('saveDisplayName', ['x'.repeat(61)], GATE_COOKIE);
  318. check('name: 61 characters are refused', f.value && /too long/.test(f.value.error), f.raw);
  319. f = await temit('saveDisplayName', ['gate'], GATE_COOKIE);
  320. 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);
  321. f = await temit('saveDisplayName', ['gate2'], GATE_COOKIE);
  322. check('name: asked once — a second name is refused', f.value && /already set/.test(f.value.error), f.raw);
  323. html = await (await fetch(BASE + '/', { headers: { cookie: GATE_COOKIE } })).text();
  324. 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"'));
  325. f = await temit('tokenCreate', ['gate machine'], GATE_COOKIE);
  326. TOKEN = f.value && f.value.token;
  327. 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);
  328. const you0 = await (await fetch(BASE + '/you', { headers: { cookie: GATE_COOKIE } })).text();
  329. 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));
  330. // ticket #20: the legacy projects have NO admin yet (no creator configured) and the gate user is no member: every write is refused
  331. const nm1 = await api('POST', '/api/tickets/1/comments', { text: 'not a member' });
  332. const nm2 = await api('POST', '/api/projects/alpha/tickets/1/state', { state: 'review' });
  333. const nm3 = await api('POST', '/api/projects/alpha/tickets', { subject: 'not a member' });
  334. 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));
  335. 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));
  336. await stopTickets();
  337. // ---- server #2: the gate user is the creator → admin of the legacy projects (its session + token survive) --
  338. startTickets({ TICKETS_CREATOR_IDENTITY: GATE_ID });
  339. await ticketsUp();
  340. html = await (await fetch(BASE + '/', { headers: { cookie: GATE_COOKIE } })).text();
  341. check('restart: the gate user is still logged in (session on disk)', /id="whoami"[^>]*>gate</.test(html), html.slice(0, 200));
  342. // ---- the migrated legacy tickets: old numbers still answer (ticket #38) ---------------
  343. const PT = (slug, n) => `/api/projects/${slug}/tickets/${n}`;
  344. const old1 = await api('GET', '/api/tickets/1');
  345. check('legacy: GET /api/tickets/1 (old number) answers alpha #1 with project, number, href, oldNumber',
  346. old1.status === 200 && old1.json.ticket.project === 'alpha' && old1.json.ticket.number === 1 && old1.json.ticket.ref === '#1' && old1.json.ticket.oldNumber === 1
  347. && 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));
  348. check('legacy: history kept in order with authors, texts and times (same ms → old order)',
  349. 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));
  350. 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));
  351. const a2 = await api('GET', PT('alpha', 2));
  352. 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));
  353. 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');
  354. const byUuid = await api('GET', '/api/tickets/' + old1.json.ticket.id);
  355. check('legacy: /api/tickets/<uuid> answers the same ticket', byUuid.status === 200 && byUuid.json.ticket.href === '/alpha/1');
  356. 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);
  357. const oldCmt = await api('POST', '/api/tickets/4/comments', { text: 'via the old number' });
  358. 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));
  359. const newCmt = await api('POST', PT('alpha', 3) + '/comments', { text: 'via the project number' });
  360. 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);
  361. const newSt = await api('POST', PT('beta.example.org', 2) + '/state', { state: 'on-hold', text: 'parked' });
  362. 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));
  363. const a4 = await api('POST', '/api/projects/alpha/tickets', { subject: 'New alpha after the migration' });
  364. 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));
  365. for (const t of ['gamma', 'antcolony', 'tickets.worldapi.org', 'ident.worldapi.org', 'gitoria.worldapi.org']) await api('POST', '/api/projects', { title: t, slug: t });
  366. const g1 = await api('POST', '/api/tickets', { project: 'gamma', subject: 'first of a new project' });
  367. 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));
  368. const g2 = await api('POST', '/api/tickets', { project: 'gamma', subject: 'second of gamma' });
  369. check('numbers: … and counts on (gamma #2)', g2.json.ticket.number === 2 && (await api('GET', PT('gamma', 2))).json.ticket.subject === 'second of gamma');
  370. 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');
  371. const redir = await fetch(BASE + '/tickets/3', { redirect: 'manual' });
  372. 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'));
  373. check('legacy: GET /tickets/99 → 404', (await fetch(BASE + '/tickets/99', { redirect: 'manual' })).status === 404);
  374. const LEGACY = (await api('GET', '/api/tickets')).json.tickets.length; // 5 migrated + alpha #4 + gamma #1, #2
  375. // ---- import: the five AntColony ticket files, twice ----------------------------------
  376. const imp0 = runImport(null);
  377. 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);
  378. const imp1 = runImport();
  379. check('import: first run creates all five', /import: 5 new, 0 already there, 0 failed/.test(imp1), imp1);
  380. 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);
  381. const imp2 = runImport();
  382. check('import: second run is idempotent (0 new, 5 already there)', /import: 0 new, 5 already there, 0 failed/.test(imp2), imp2);
  383. let list = await api('GET', '/api/tickets');
  384. const TOTAL = LEGACY + 5;
  385. 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));
  386. let one = await api('GET', PT('tickets.worldapi.org', 1));
  387. check('api: tickets.worldapi.org #1 is the first file (project, subject, summary, a created event)',
  388. one.status === 200 && one.json.ticket.project === 'tickets.worldapi.org' && one.json.ticket.subject === 'Build the World Ticket System in Hybriel'
  389. && 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:')
  390. && 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));
  391. check('api: antcolony #1 is the scheduler file', (await api('GET', PT('antcolony', 1))).json.ticket.source === '0004-scheduler.md');
  392. check('api: unknown ticket is a 404', (await api('GET', '/api/tickets/99')).status === 404 && (await api('GET', PT('antcolony', 99))).status === 404);
  393. check('api: a ticket without subject is refused (400)', (await api('POST', '/api/tickets', { project: 'x' })).status === 400);
  394. check('api: an unknown state is refused (400)', (await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'nope' })).status === 400);
  395. check('api: an empty comment is refused (400)', (await api('POST', PT('ident.worldapi.org', 1) + '/comments', { text: ' ' })).status === 400);
  396. 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);
  397. 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');
  398. const projects = await api('GET', '/api/projects');
  399. const imported = (await api('GET', '/api/tickets')).json.tickets.filter(t => t.source);
  400. check('import: hard-wrapped lines are joined (no line break left in the five)', imported.length === 5 && imported.every(t => !t.summary.includes('\n')));
  401. 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));
  402. // ---- the API is strict (ticket #10): every refused body writes NOTHING ----------------
  403. const rawPost = async (path, raw, auth = 'Bearer ' + TOKEN) => {
  404. const r = await fetch(BASE + path, { method: 'POST', headers: { 'content-type': 'application/json', ...(auth ? { authorization: auth } : {}) }, body: raw });
  405. let json = null; try { json = await r.clone().json(); } catch {}
  406. return { status: r.status, json, text: json ? '' : await r.text() };
  407. };
  408. const strictCases = [
  409. // [path, raw body, expected status, expected `field` (null = none), error must include]
  410. ['/api/tickets', J({ project: 'x', subject: 's', bogus: '1' }), 400, 'bogus', "unknown field 'bogus'"],
  411. ['/api/tickets', J({ project: 'x', subject: 's', Subject: 't' }), 400, 'Subject', "unknown field 'Subject'"],
  412. ['/api/tickets', J({ project: 'x' }), 400, 'subject', "field 'subject' is required"],
  413. ['/api/tickets', J({ subject: 's' }), 400, 'project', "field 'project' is required"],
  414. ['/api/tickets', J({ project: 'x', subject: ' ' }), 400, 'subject', "field 'subject' must not be empty"],
  415. ['/api/tickets', J({ project: '', subject: 's' }), 400, 'project', "field 'project' must not be empty"],
  416. ['/api/tickets', J({ project: 'x', subject: 5 }), 400, 'subject', "field 'subject' must be a string"],
  417. ['/api/tickets', J({ project: 'x', subject: 's', summary: null }), 400, 'summary', "field 'summary' must be a string"],
  418. ['/api/tickets', J({ project: 'a b', subject: 's' }), 400, 'project', 'no such project'],
  419. // ticket #7: NO free author any more — the author is the token's user; a body naming one is refused
  420. ['/api/tickets', J({ project: 'x', subject: 's', author: ['a'] }), 400, 'author', "no field 'author' any more"],
  421. ['/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"],
  422. ['/api/tickets', J({ project: 'x', subject: 's', summary: 'y', author: ' ' }), 400, 'author', "no field 'author' any more"],
  423. ['/api/tickets/2/comments', J({ text: 'x', author: 'creator' }), 400, 'author', "no field 'author' any more"],
  424. ['/api/tickets/2/comments', J({ text: 'x', author: '' }), 400, 'author', "no field 'author' any more"],
  425. ['/api/tickets/2/state', J({ state: 'in progress', author: 'creator' }), 400, 'author', "no field 'author' any more"],
  426. ['/api/tickets/2/state', J({ state: 'confirmed', text: 'n', author: ' ' }), 400, 'author', "no field 'author' any more"],
  427. ['/api/tickets', J([1, 2]), 400, '', 'must be a JSON object'],
  428. ['/api/tickets', J('text'), 400, '', 'must be a JSON object'],
  429. ['/api/tickets', '', 400, '', 'must be a JSON object'],
  430. ['/api/tickets/2/comments', J({ text: 'hi', state: 'open' }), 400, 'state', "unknown field 'state'"],
  431. ['/api/tickets/2/comments', J({}), 400, 'text', "field 'text' is required"],
  432. ['/api/tickets/2/comments', J({ text: ' ' }), 400, 'text', "field 'text' must not be empty"],
  433. ['/api/tickets/2/comments', J({ text: { a: 1 } }), 400, 'text', "field 'text' must be a string"],
  434. ['/api/tickets/2/comments', J({ text: true }), 400, 'text', "field 'text' must be a string"],
  435. ['/api/tickets/2/comments', J({ text: 'x', author: 7 }), 400, 'author', "no field 'author' any more"],
  436. ['/api/tickets/2/state', J({ state: 'open', note: 'x' }), 400, 'note', "unknown field 'note'"],
  437. ['/api/tickets/2/state', J({ text: 'x' }), 400, 'state', "field 'state' is required"],
  438. ['/api/tickets/2/state', J({ state: '' }), 400, 'state', "field 'state' must not be empty"],
  439. ['/api/tickets/2/state', J({ state: 3 }), 400, 'state', "field 'state' must be a string"],
  440. ['/api/tickets/2/state', J({ state: 'nope' }), 400, 'state', 'unknown state'],
  441. ['/api/tickets/2/state', J({ state: 'open' }), 400, 'state', 'already open'],
  442. ['/api/tickets/99/comments', J({ text: 'x' }), 404, null, 'no such ticket'],
  443. // ticket #38: the slug is the project name, so a new name must be URL-safe; the per-project form is as strict
  444. ['/api/tickets', J({ project: 'a#b', subject: 's' }), 400, 'project', 'no such project'],
  445. ['/api/tickets', J({ project: 'ä', subject: 's' }), 400, 'project', 'no such project'],
  446. ['/api/projects/beta.example.org/tickets/1/comments', J({ text: 'x', author: 'a' }), 400, 'author', "no field 'author' any more"],
  447. ['/api/projects/beta.example.org/tickets/1/comments', J({ text: 'x', bogus: '1' }), 400, 'bogus', "unknown field 'bogus'"],
  448. ['/api/projects/beta.example.org/tickets/1/state', J({ state: 'open' }), 400, 'state', 'already open'],
  449. ['/api/projects/beta.example.org/tickets/1/state', J({ state: 5 }), 400, 'state', "field 'state' must be a string"],
  450. ['/api/projects/beta.example.org/tickets', J({ subject: 's', author: 'a' }), 400, 'author', "no field 'author' any more"],
  451. ['/api/projects/beta.example.org/tickets/9/comments', J({ text: 'x' }), 404, null, 'no such ticket'],
  452. ['/api/projects/beta.example.org/tickets/x/comments', J({ text: 'x' }), 404, null, 'no such ticket'],
  453. ];
  454. for (const [path, raw, want, field, says] of strictCases) {
  455. const r = await rawPost(path, raw);
  456. const ok = r.status === want && r.json && typeof r.json.error === 'string' && r.json.error.includes(says) && (field === null || r.json.field === field);
  457. check(`strict: POST ${path} ${raw || '(empty)'} → ${want}${field ? ' naming ' + field : ''}`, ok, r.status + ' ' + J(r.json) + r.text);
  458. }
  459. // invalid JSON (ticket #15): refused by jsoncheck.hl BEFORE JSON.parse → 400 { error },
  460. // no source path (workaround for hybriel #12: an uncaught JSON.parse answered 500 + api.hl:31:9)
  461. const badJsonCases = [
  462. ['/api/tickets', '{"project":"x",', 15], ['/api/tickets', '{bad', 1], ['/api/tickets', "{'project':'x'}", 1],
  463. ['/api/tickets', '{"project":"x","subject":"s","summary":"a",}', 43], ['/api/tickets', '[1 2]', 3],
  464. ['/api/tickets/2/comments', '{"text":"x","n":"a"} trailing', 21], ['/api/tickets/2/comments', '{"text":"\\x","n":"a"}', 10],
  465. ['/api/tickets/2/state', '{"state":01}', 10], ['/api/tickets/2/state', '['.repeat(70), 64], ['/api/tickets/2/state', ' ', 3],
  466. // LONE \u surrogate escapes: hl's JSON.parse still refuses them (would be a 500) → refused by the check
  467. // (a valid pair parses since hybriel#15, mission 036: see the two checks below)
  468. ['/api/tickets/2/comments', '{"text":"\\ud800"}', 10], ['/api/tickets/2/comments', '{"text":"\\udc00"}', 10],
  469. ['/api/tickets/2/comments', '{"text":"\\ud83dx"}', 10], ['/api/tickets/2/comments', '{"text":"\\ud83d\\u0041"}', 10],
  470. ];
  471. for (const [path, raw, at] of badJsonCases) {
  472. const r = await rawPost(path, raw);
  473. 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);
  474. 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);
  475. }
  476. // valid but unusual JSON is NOT mistaken for invalid (escapes, unicode, numbers, nesting) → normal field errors
  477. const oddValid = await rawPost('/api/tickets/2/comments', '{ "text" : "q\\"b\\\\s\\/\\u00e9\\n", "n": [-1.5e+3, 0, true, null, {"x":[]}] }');
  478. 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);
  479. const pairOnly = await rawPost('/api/tickets/2/comments', '{"text":"\\ud83d\\ude00","n":"a"}');
  480. 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);
  481. const escaped = await rawPost('/api/tickets/3/comments', '{"text":"q\\"b\\\\s\\/\\u00e9 \u{1F600} end \\ud83d\\ude00"}');
  482. 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);
  483. const afterStrict = await api('GET', '/api/tickets');
  484. 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)));
  485. check('strict: GET /api/inbox refuses POST (405)', (await rawPost('/api/inbox', '{}')).status === 405);
  486. // ---- ticket #7: API writes need a valid token — 401 BEFORE the body is looked at ----------
  487. const before401 = J((await api('GET', '/api/tickets')).json.tickets.map(t => [t.ref, t.events]));
  488. const authCases = [
  489. // [path, raw body, Authorization header (null = none), label]
  490. ['/api/tickets', J({ project: 'x', subject: 's' }), null, 'no token'],
  491. ['/api/projects/alpha/tickets', J({ subject: 's' }), null, 'no token'],
  492. ['/api/tickets/2/comments', J({ text: 'x' }), null, 'no token'],
  493. ['/api/projects/alpha/tickets/1/comments', J({ text: 'x' }), null, 'no token'],
  494. ['/api/tickets/2/state', J({ state: 'in progress' }), null, 'no token'],
  495. ['/api/projects/alpha/tickets/1/state', J({ state: 'on hold' }), null, 'no token'],
  496. ['/api/tickets/2/comments', J({ text: 'x' }), 'Bearer tkt_' + '0'.repeat(48), 'an unknown token'],
  497. ['/api/tickets/2/comments', J({ text: 'x' }), 'Bearer ' + TOKEN + '0', 'a token with one character more'],
  498. ['/api/tickets/2/comments', J({ text: 'x' }), 'Bearer ' + TOKEN.slice(0, -1), 'a token with one character less'],
  499. ['/api/tickets/2/comments', J({ text: 'x' }), TOKEN, 'the token without "Bearer"'],
  500. ['/api/tickets/2/comments', J({ text: 'x' }), 'Basic ' + TOKEN, 'Basic instead of Bearer'],
  501. ['/api/tickets/2/comments', J({ text: 'x' }), 'Bearer ', 'an empty Bearer'],
  502. ['/api/tickets/2/comments', '{bad', null, 'no token + invalid JSON (auth first)'],
  503. ['/api/tickets/2/comments', J({ text: 'x', author: 'creator' }), null, 'no token + an author field (auth first)'],
  504. ];
  505. for (const [path, raw, auth, label] of authCases) {
  506. const r = await rawPost(path, raw, auth);
  507. 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);
  508. }
  509. check('auth: the refused writes wrote nothing', J((await api('GET', '/api/tickets')).json.tickets.map(t => [t.ref, t.events])) === before401);
  510. const anonRead = await fetch(BASE + '/api/tickets/1');
  511. check('auth: reading needs no token (GET without Authorization → 200)', anonRead.status === 200);
  512. // ---- local time (ticket #10): Europe/Vienna, storage stays epoch ms -----------------------
  513. 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' });
  514. const lt = spawnSync(BIN, ['tests/localtime.hl'], { cwd: APP, encoding: 'utf8', timeout: COLD_MS });
  515. const ltLines = (lt.stdout || '').trim().split('\n').filter(Boolean);
  516. const ltBad = ltLines.filter(l => { const [ms, ...rest] = l.split(' '); return vienna.format(new Date(Number(ms))) !== rest.join(' '); });
  517. check('time: localtime.hl matches Intl Europe/Vienna on DST edges 2000–2100', ltLines.length === 11 && ltBad.length === 0, J(ltBad) + (lt.stderr || ''));
  518. const t2 = (await api('GET', PT('ident.worldapi.org', 1))).json;
  519. 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]));
  520. // ---- two viewers ------------------------------------------------------------------
  521. A = await launchBrowser({ debugPortRange: range(process.env.TICKETS_GATE_CHROME_A, '8620-8629') });
  522. B = await launchBrowser({ debugPortRange: range(process.env.TICKETS_GATE_CHROME_B, '8630-8639') });
  523. const a = patient(await A.newPage());
  524. const b = patient(await B.newPage());
  525. // SSR of the list
  526. await a.goto(BASE + '/');
  527. await a.waitForSelector('#tickets li');
  528. await connected(a, 'A connected');
  529. check('list: SSR shows every ticket (migrated + new + imported)', (await texts(a, '#tickets li')).length === TOTAL, J(await texts(a, '#tickets li')));
  530. 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'))`));
  531. 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))`));
  532. check('list: the project filter offers all seven projects', (await texts(a, '#projectfilter a')).length === 8, J(await texts(a, '#projectfilter a')));
  533. 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`));
  534. 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)');
  535. // filters by real clicks (client-side navigation)
  536. await clickNav(a, '#projectfilter a[href="/project/antcolony"]', 'location.pathname === "/project/antcolony" && document.querySelectorAll("#tickets li").length === 2', 'project filter');
  537. 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')));
  538. check('filter: the chosen project is marked selected', (await a.text('#projectfilter a.selected')) === 'antcolony');
  539. await clickNav(a, '#statefilter a[href="/project/antcolony/state/progress"]', 'location.pathname === "/project/antcolony/state/progress" && !!document.querySelector("#empty")', 'state filter');
  540. check('filter: project + state "progress" is empty (nothing in progress yet)', (await texts(a, '#tickets li')).length === 0);
  541. await clickNav(a, '#statefilter a[href="/project/antcolony"]', 'document.querySelectorAll("#tickets li").length === 2', 'state filter cleared');
  542. check('filter: clearing the state keeps the project', (await a.evaluate('location.pathname')) === '/project/antcolony');
  543. await a.goto(BASE + '/state/open');
  544. await a.waitForSelector('#tickets li');
  545. const OPEN = (await api('GET', '/api/tickets?state=open')).json.tickets.length;
  546. check('filter: /state/open by URL (SSR) shows every open ticket', (await texts(a, '#tickets li')).length === OPEN, OPEN);
  547. // ---- a migrated ticket in the browser: the old URL redirects, a real click opens the new one
  548. await a.goto(BASE + '/tickets/4');
  549. await a.waitForSelector('#subject');
  550. 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'));
  551. check('legacy: the page says "formerly #4"', (await a.text('#oldref')) === 'formerly #4', await a.text('#oldref'));
  552. await a.waitFor('document.querySelectorAll("#events li.comment").length === 2', { label: 'legacy: both API comments in the block' });
  553. const legacyH = await hist(a);
  554. 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));
  555. await a.goto(BASE + '/project/alpha');
  556. await a.waitForSelector('#tickets li');
  557. await connected(a, 'A on alpha');
  558. await clickNav(a, '#tickets a.subject[href="/alpha/1"]', 'location.pathname === "/alpha/1" && !!document.querySelector("#events li.comment")', 'click alpha #1');
  559. const legacy1 = await hist(a);
  560. 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));
  561. await a.goto(BASE + '/gamma/1');
  562. await a.waitForSelector('#subject');
  563. check('numbers: a new ticket has no "formerly"', (await a.text('#ref')) === '#1' && !(await a.evaluate('!!document.querySelector("#oldref")')));
  564. await a.goto(BASE + '/alpha/99');
  565. await a.waitForSelector('#gone');
  566. check('numbers: an unknown number shows "no such ticket"', (await a.text('#gone')).includes('no such ticket'));
  567. await a.goto(BASE + '/gamma');
  568. await a.waitForSelector('#tickets li');
  569. check('numbers: /<slug> lists that project', (await texts(a, '#tickets li')).length === 2 && (await a.text('#heading')) === 'gamma');
  570. // ---- ticket #25: short URLs /<slug>, /<slug>/<number>; every old page URL answers 301; hl:web's own urls stay its own
  571. const 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']];
  572. for (const [path, want] of SHORT_SSR) {
  573. const r = await fetch(BASE + path, { redirect: 'manual' });
  574. const body = await r.text();
  575. check(`short (#25): GET ${path} → 200, the page itself (SSR)`, r.status === 200 && body.includes(want), r.status + ' ' + body.slice(0, 200));
  576. }
  577. 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']]) {
  578. const r = await fetch(BASE + from, { redirect: 'manual' });
  579. check(`short (#25): old ${from} → 301 Location ${to}`, r.status === 301 && r.headers.get('location') === to, r.status + ' ' + r.headers.get('location'));
  580. }
  581. 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']) {
  582. const r = await fetch(BASE + from, { redirect: 'manual' });
  583. check(`short (#25): old ${from} names nothing → 404, no Location`, r.status === 404 && !r.headers.get('location'), r.status + ' ' + r.headers.get('location'));
  584. }
  585. const ssrNope = await (await fetch(BASE + '/nope')).text();
  586. 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));
  587. // hl:web appends its own urls AFTER the app's routes; /:projectSlug/:ticketNumber must not answer them (project.hl moves it last)
  588. 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']]) {
  589. const r = await fetch(BASE + path);
  590. const body = await r.text();
  591. 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'));
  592. }
  593. const em = await fetch(BASE + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json' }, body: J({ t: 'emit', i: 1, event: 'nosuchface', payload: [] }) });
  594. check('short (#25): POST /__hl/emit is still hl:web\'s carrier (JSON ack)', em.status === 200 && /"ok":false/.test(await em.text()));
  595. // in the browser: an old link lands on the short URL; the project link on the ticket page is a CLIENT navigation to /<slug>
  596. await a.goto(BASE + '/projects/gamma/tickets/1');
  597. await a.waitForSelector('#subject');
  598. 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'));
  599. await connected(a, 'A on /gamma/1');
  600. await a.evaluate('window.__w083 = 1');
  601. check('short (#25): the ticket page links its project as /gamma', (await a.evaluate('document.querySelector("#project").getAttribute("href")')) === '/gamma');
  602. await clickNav(a, '#project', 'location.pathname === "/gamma" && document.querySelectorAll("#tickets li").length === 2', 'click the project');
  603. 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');
  604. await clickNav(a, '#tickets a.subject[href="/gamma/2"]', 'location.pathname === "/gamma/2" && !!document.querySelector("#subject")', 'click gamma #2');
  605. 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');
  606. // reserved slugs: no project may be named like a path the app answers itself
  607. for (const slug of ['api', 'Inbox', '__hl', 'components', 'projects', 'tickets', 'login.js', 'my', 'assets', 'sign-in']) {
  608. const r = await api('POST', '/api/projects', { title: 'Reserved ' + slug, slug });
  609. 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));
  610. }
  611. const toRes = await api('POST', '/api/projects/gamma', { slug: 'inbox' });
  612. 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));
  613. 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)));
  614. // every first segment a route of project.hl answers is a reserved slug (a new route must add its name)
  615. const routeHeads = [...readFileSync(join(APP, 'project.hl'), 'utf8').matchAll(/pattern = "\/([^/":]+)/g)].map(m => m[1]);
  616. const reservedSrc = readFileSync(join(APP, 'lib/projects.hl'), 'utf8').match(/static reservedSlugs = \[([^\]]*)\]/);
  617. const reserved = reservedSrc ? [...reservedSrc[1].matchAll(/'([^']*)'/g)].map(m => m[1]) : [];
  618. const missingHeads = [...new Set([...routeHeads, '__hl', 'components'])].filter(h => !reserved.includes(h));
  619. 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));
  620. // ---- old events keep their authors (ticket #7) --------------------------------------------
  621. await a.goto(BASE + '/projects/alpha/1');
  622. await a.waitForSelector('#events li.comment');
  623. 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)));
  624. // ---- signed out: reading only (ticket #7) --------------------------------------------------
  625. const IDENT1 = '/projects/ident.worldapi.org/1';
  626. await a.goto(BASE + IDENT1);
  627. await a.waitForSelector('#events li');
  628. await connected(a, 'A on ident #1 (signed out)');
  629. 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")')));
  630. 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="]'); })()`));
  631. check('signed out: the selector is restyled to tickets\' accent (purple)', await a.evaluate(sh('getComputedStyle(r.querySelector("#choose")).backgroundColor')) === 'rgb(197, 134, 192)');
  632. let anonCookie = (await a.cookies([BASE])).filter(c => c.name === 'hlsid').map(c => 'hlsid=' + c.value)[0];
  633. const anonTry = await temit('commentOn', [(await api('GET', PT('ident.worldapi.org', 1))).json.ticket.id, 'anonymous'], anonCookie);
  634. 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);
  635. for (const [w, h, name] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {
  636. await viewport(a, w, h);
  637. check(`layout ${name} ${w}px: signed-out header (the selector) has no horizontal overflow`, await noOverflow(a));
  638. 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));
  639. await shot(a, `${name}-signedout`);
  640. }
  641. await viewport(a, 1280, 900);
  642. // ---- A = alice (the creator): sign in to ident, then the SELECTOR on tickets ---------------
  643. await identSignIn(a, '[email protected]');
  644. await a.goto(BASE + IDENT1);
  645. await a.waitForSelector('#events li');
  646. await connected(a, 'A on ident #1');
  647. await a.evaluate('window.__loginMarker = 1');
  648. await shClick(a, '#choose');
  649. await a.waitFor(sh(`r.querySelectorAll('[part~="identity"]').length > 0`), { label: 'selector list' });
  650. check('selector: lists alice\'s identity', J(await a.evaluate(sh(`[...r.querySelectorAll('[part~="identity"]')].map(b => b.textContent)`))) === J(['Default']));
  651. await shClick(a, '[part~="identity"]', 'Default');
  652. await a.waitForSelector('#nameform', { timeout: 10000 });
  653. 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'))));
  654. check('selector login: still no write forms before the name', !(await a.evaluate('!!document.querySelector("#commentform")')));
  655. for (const [w, h, name] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {
  656. await viewport(a, w, h);
  657. check(`layout ${name} ${w}px: name prompt has no horizontal overflow`, await noOverflow(a));
  658. await shot(a, `${name}-name`);
  659. }
  660. await viewport(a, 1280, 900);
  661. await a.type('#displayname', 'alice');
  662. await a.click('#namesave');
  663. await a.waitFor('!document.querySelector("#nameform") && !!document.querySelector("#memberhint")', { label: 'A named, no role yet: a member hint, no forms' });
  664. 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")')));
  665. // ticket #20: the admin (the gate user, the creator) gives alice a role in every project; the page follows live
  666. const 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)); } };
  667. await grant('alice', 'admin');
  668. await a.goto(BASE + IDENT1);
  669. await a.waitFor('!!document.querySelector("#commentform")', { label: 'A: the forms appear after alice got a role' });
  670. await connected(a, 'A on ident #1 with a role');
  671. await a.evaluate('window.__loginMarker = 1');
  672. check('roles: alice made admin → the comment form appears (page reloaded), no member hint', !(await a.evaluate('!!document.querySelector("#memberhint")')));
  673. for (const [w, h, name] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {
  674. await viewport(a, w, h);
  675. check(`layout ${name} ${w}px: logged-in header has no horizontal overflow`, await noOverflow(a));
  676. 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));
  677. 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")); })()'));
  678. { 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)); }
  679. await shot(a, `${name}-loggedin`);
  680. }
  681. await viewport(a, 1280, 900);
  682. const aliceCookie = (await a.cookies([BASE])).filter(c => c.name === 'hlsid').map(c => 'hlsid=' + c.value)[0];
  683. const aliceHtml = await (await fetch(BASE + '/', { headers: { cookie: aliceCookie } })).text();
  684. const ALICE_UID = (/\\?"user\\?":\{\\?"id\\?":\\?"([0-9a-z]{12})/.exec(aliceHtml) || [])[1];
  685. 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);
  686. // ---- B = bob: sign in to ident, then the plain LOGIN LINK (ident /login, no button in the header any more) ---------------------------------------
  687. await identSignIn(b, '[email protected]');
  688. await b.goto(BASE + '/');
  689. await b.waitForSelector('#selector');
  690. await connected(b, 'B on / signed out');
  691. // 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 did
  692. await b.goto(`${ident.base}/login?key=${APPKEY.key}&return=${encodeURIComponent(BASE + '/login/callback')}`);
  693. await b.waitForSelector('#chooselist', { timeout: 10000 });
  694. check('button: tickets → ident /signin/<rid> (choose an identity)', (await b.evaluate('location.href')).startsWith(ident.base + '/signin/'));
  695. await connectedIdent(b);
  696. await b.click('#chooselist li:nth-child(1) .choose');
  697. await b.waitFor(`location.href === ${J(BASE + '/')} && !!document.querySelector('#nameform')`, { timeout: 10000, label: 'B back with the name prompt' });
  698. 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")')));
  699. await connected(b, 'B on / after the button login');
  700. await b.type('#displayname', 'bob');
  701. await b.click('#namesave');
  702. await b.waitFor('!document.querySelector("#nameform") && !!document.querySelector("#rolehint")', { label: 'B named' });
  703. 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")')));
  704. await grant('bob', 'edit');
  705. await b.goto(BASE + '/');
  706. await b.waitFor('!!document.querySelector("#newticketbutton")', { label: 'B: the New ticket button appears with the role edit' });
  707. await connected(b, 'B on / with a role');
  708. check('roles: bob made edit → the new-ticket form appears', (await b.text('#whoami')) === 'bob');
  709. const bobCookie = (await b.cookies([BASE])).filter(c => c.name === 'hlsid').map(c => 'hlsid=' + c.value)[0];
  710. // ---- the ticket page, two viewers ---------------------------------------------------
  711. await b.goto(BASE + IDENT1);
  712. await b.waitForSelector('#events li');
  713. await connected(b, 'B on ident #1');
  714. await sleep(300);
  715. 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(' | '));
  716. 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'));
  717. 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));
  718. 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'));
  719. // A comments (real typing into the form, real click) → B sees it without reload
  720. check('ticket: no author field (ticket #7: the author is the logged-in user)', await a.evaluate('!document.querySelector("#author") && !document.querySelector("input[name=author]")'));
  721. // mission 016: the form is the Comments block's (an MdEditor): REAL keys into it, a line break with Shift+Enter, sent with Ctrl+Enter
  722. await mdShows(a, '#commentform md-editor article', '', 'A: the comment editor is live');
  723. await a.click('#commentform md-editor article');
  724. await realKeys(a, 'first comment from A');
  725. await shiftEnter(a);
  726. await realKeys(a, 'second line');
  727. await ctrlEnter(a);
  728. await a.waitFor('document.querySelectorAll("#events li.comment").length === 1', { label: 'A sees its comment' });
  729. const firstA = (await hist(a)).pop();
  730. 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));
  731. check('comment: the block\'s form starts empty again', await a.evaluate('document.querySelector("#commentform md-editor input.value").value === ""'));
  732. await b.waitFor('document.querySelectorAll("#events li.comment").length === 1', { label: 'B got the comment live' });
  733. check('live: B sees A\'s comment without a reload', (await hist(b)).pop().text === 'first comment from A\nsecond line');
  734. 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)');
  735. // hybriel 64527baa+: a face taking `session` answers with a sync of the session-derived members — a list must
  736. // not get the new row twice (gitoria's keys/tokens did). Settle, then count.
  737. await sleep(600);
  738. 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)); }
  739. check('live: B did not reload (no navigation entry)', await b.evaluate('performance.getEntriesByType("navigation").length === 1 && performance.getEntriesByType("navigation")[0].type === "navigate"'));
  740. await b.evaluate('window.__gateMarker = 42'); // survives only if B never reloads
  741. // ---- mission 013: GitHub pipe tables in a comment (lib/markdown.hl) — typed with REAL keys into the comment editor's
  742. // Markdown source view (a real click on its "Markdown source" button), sent by a real click; B gets it live -----------
  743. const LONGCELL = 'averyveryverylongwordthatcannotwrapanywhereatallsothetablemustscrollinsideitsbox';
  744. 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';
  745. const keys = async (page, text) => {
  746. for (const ch of text) {
  747. if (ch === '\n') {
  748. await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 });
  749. await page.send('Input.dispatchKeyEvent', { type: 'char', key: 'Enter', text: '\r' });
  750. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Enter', code: 'Enter', windowsVirtualKeyCode: 13 });
  751. } else {
  752. await page.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch });
  753. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });
  754. }
  755. }
  756. };
  757. // mission 016: the comment form is the block's MdEditor — its "Markdown source" button (a real click), then real keys
  758. await a.click('#commentform md-editor button.source-switch');
  759. 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' });
  760. await a.click('#commentform md-editor textarea');
  761. await keys(a, TABLE_MD);
  762. 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'));
  763. await a.click('#commentform button.comment-post');
  764. const LASTC = `[...document.querySelectorAll('#events li.comment')].pop()`;
  765. 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' });
  766. 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;
  767. 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 });
  768. 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)),
  769. 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,
  770. border: getComputedStyle(tab.querySelector('th')).borderTopColor, borderW: getComputedStyle(tab.querySelector('th')).borderTopWidth }; })()`;
  771. const tA = await a.evaluate(TABLE_PROBE);
  772. 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));
  773. 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));
  774. 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]));
  775. 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));
  776. 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]));
  777. await b.waitFor(`!!${LASTC} && !!${LASTC}.querySelector('md-editor[data-readonly="true"] article table')`, { label: 'B got the table comment live' });
  778. const tB = await b.evaluate(TABLE_PROBE);
  779. check('tables: live — B shows the same table without a reload', J(tB) === J(tA) && (await b.evaluate('window.__gateMarker')) === 42, J(tB));
  780. // mission 016: the block draws a comment in the browser — the server's HTML carries its Markdown in the block's hidden field, escaped
  781. const tSsr = (await (await fetch(BASE + IDENT1)).text());
  782. check('tables: the server-rendered page carries the comment\'s Markdown escaped in the block (no live <script> from it)', tSsr.includes('&lt;script&gt;window.__tablePwned') && !tSsr.includes('<script>window.__tablePwned') && /<comments-block/.test(tSsr), (tSsr.match(/&lt;script&gt;window.__tablePwned.{0,80}/) || ['not found'])[0]);
  783. const tJson = await api('GET', PT('ident.worldapi.org', 1));
  784. const tMdView = await (await fetch(BASE + PT('ident.worldapi.org', 1), { headers: { accept: 'text/markdown' } })).text();
  785. 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));
  786. for (const [w, h, name] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {
  787. await viewport(a, w, h);
  788. await a.evaluate(`${LASTC}.querySelector('md-editor[data-readonly="true"] article table').scrollIntoView({ block: "center" })`);
  789. 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 }; })()`);
  790. 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));
  791. await shot(a, `${name}-table`);
  792. }
  793. await viewport(a, 1280, 900);
  794. // ---- ticket #20: the new states, the roles, projects with members, the inbox (browser + API) ------------------
  795. // A (alice, admin) moves ident #1 to "review": B follows live; the ticket is assigned to the project's first admin (the gate user)
  796. 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 assigned
  797. check('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')));
  798. // ==== m021 START — tickets#29: the editor's LOOK on the ticket page (the creator: "why did the md wysiwyg editor's layout change?")
  799. 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)))) }; })()`;
  800. 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`)));
  801. 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);
  802. const cmLook = await a.evaluate(LOOK('#commentform md-editor'));
  803. 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));
  804. // 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 icons
  805. await a.click('#commentform md-editor article'); await sleep(250);
  806. 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 }; })()`);
  807. 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));
  808. await a.click('#commentform md-editor footer button.source-switch'); await sleep(300);
  809. await a.click('#commentform md-editor textarea'); await sleep(250);
  810. 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 }; })()`);
  811. 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));
  812. await a.click('#commentform md-editor footer button.source-switch'); await sleep(300);
  813. await a.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 1, mobile: true });
  814. await sleep(400);
  815. const noteLook390 = await a.evaluate(LOOK('#commentform md-editor'));
  816. 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));
  817. await a.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  818. // ==== m021 END
  819. // 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 click
  820. const pickStateOf = async (page, name) => {
  821. await page.evaluate(`document.querySelector('#commentform select[name=state]').focus()`);
  822. for (let i = 0; i < 12; i++) {
  823. if ((await page.evaluate(`(() => { const s = document.querySelector('#commentform select[name=state]'); return s.options[s.selectedIndex].textContent.trim(); })()`)) === name) return true;
  824. await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40 });
  825. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40 });
  826. await sleep(120);
  827. }
  828. return false;
  829. };
  830. const postLabelOf = (page) => page.evaluate(`document.querySelector('#commentform button.comment-post').textContent.trim()`);
  831. check('UX: the composer\'s button says "Comment" while nothing else is chosen', (await postLabelOf(a)) === 'Comment', await postLabelOf(a));
  832. check('UX: a real key press on the State select chooses "review"', await pickStateOf(a, 'review'));
  833. check('UX: with a state chosen and nothing written the button says "Set to review"', (await postLabelOf(a)) === 'Set to review', await postLabelOf(a));
  834. await a.click('#commentform button.comment-post');
  835. await a.waitFor('document.querySelector("#state").textContent === "review"', { label: 'A state changed' });
  836. 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));
  837. await sleep(600);
  838. 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')));
  839. await b.waitFor('document.querySelector("#state").textContent === "review"', { label: 'B state live' });
  840. check('live: B\'s state badge followed, no reload', (await b.evaluate('document.querySelector("#state").className')) === 'review' && (await b.evaluate('window.__gateMarker')) === 42);
  841. 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 }; };
  842. const inbox0 = await inboxOf(TOKEN);
  843. 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));
  844. const oldNames = await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'awaiting creator' });
  845. 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));
  846. const aliasBack = await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'in progress' });
  847. check('states: "in progress" is an alias of progress (201)', aliasBack.status === 201 && aliasBack.json.ticket.state === 'progress', J(aliasBack).slice(0, 300));
  848. await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'open' });
  849. // roles: bob = use → comment + open ⇄ review, nothing else (web and API)
  850. let aliceTok0 = null;
  851. const bobTok = (await temit('tokenCreate', ['bob gate'], bobCookie)).value.token;
  852. await api('POST', '/api/projects/ident.worldapi.org/members', { user: 'bob', role: 'use' });
  853. await b.goto(BASE + IDENT1);
  854. await b.waitForSelector('#commentform select[name=state]');
  855. await connected(b, 'B on ident #1 as use');
  856. 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')));
  857. const useDone = await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'done' }, bobTok);
  858. const useReview = await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'review' }, bobTok);
  859. const useNew = await api('POST', '/api/projects/ident.worldapi.org/tickets', { subject: 'use may not' }, bobTok);
  860. const useSettings = await api('POST', '/api/projects/ident.worldapi.org/members', { user: 'bob', role: 'admin' }, bobTok);
  861. const useComment = await api('POST', PT('ident.worldapi.org', 1) + '/comments', { text: 'a use member comments' }, bobTok);
  862. 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));
  863. await b.goto(BASE + '/projects/ident.worldapi.org/settings');
  864. await b.waitForSelector('#notadmin');
  865. check('roles: the settings page of a non-admin says so and has no forms', !(await b.evaluate('!!document.querySelector("#detailsform")')));
  866. await api('POST', '/api/projects/ident.worldapi.org/members', { user: 'bob', role: 'edit' });
  867. const editAssign = await api('POST', PT('ident.worldapi.org', 1) + '/assign', { assignee: 'bob' }, bobTok);
  868. check('roles: edit may assign (201) and move to any state', editAssign.status === 201 || editAssign.status === 200, J(editAssign).slice(0, 300));
  869. const editPending = await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'pending' }, bobTok);
  870. 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));
  871. // the inbox page of bob: pending and review, only what is assigned to him
  872. await b.goto(BASE + '/inbox');
  873. await b.waitForSelector('#pendingbox');
  874. await connected(b, 'B inbox');
  875. 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')));
  876. await api('POST', PT('ident.worldapi.org', 1) + '/state', { state: 'review' }, bobTok);
  877. await b.waitFor('document.querySelectorAll("#review li").length === 1 && document.querySelectorAll("#pending li").length === 0', { label: 'inbox follows the state change live' });
  878. 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
  879. {
  880. // mission 023: the Inbox count is a badge (its own span.count), the label stays plain; `current` / aria-current marks the page's item
  881. const 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) })); })()`);
  882. 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; };
  883. const mi = await menuInfo();
  884. 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));
  885. 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()));
  886. await b.goto(`${BASE}/`); await b.waitForSelector('#tickets li');
  887. check('menu current: on the ticket list All tickets has aria-current="page", the Inbox has not', await marked('/', 'list marked'), J(await menuInfo()));
  888. const tHref = await b.evaluate(`(() => { const a = document.querySelector('#tickets li a.subject'); return a ? a.getAttribute('href') : ''; })()`);
  889. await b.goto(`${BASE}${tHref}`); await b.waitForSelector('#subject');
  890. 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()));
  891. await b.goto(`${BASE}/inbox`); await b.waitForSelector('#pendingbox'); await connected(b, 'B inbox again');
  892. check('menu current: back on /inbox the marker moved to the Inbox', await marked('/inbox', 'inbox marked again'), J(await menuInfo()));
  893. // 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
  894. {
  895. 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) ? '*' : '')); };
  896. const proj = '/' + tHref.split('/')[1];
  897. for (const [path, want] of [['/', '/*,/inbox'], ['/inbox', '/,/inbox*'], [proj, '/*,/inbox'], [tHref, '/*,/inbox']]) {
  898. const got = await ssr(path); const uniq = [...new Set(got)].join();
  899. check(`menu current in the server's HTML (plain fetch of ${path}): ${want}`, uniq === want, J(got));
  900. }
  901. }
  902. }
  903. aliceTok0 = (await temit('tokenCreate', ['alice #20'], aliceCookie)).value.token;
  904. check('inbox: alice (admin, nothing assigned) has an empty inbox', (await inboxOf(aliceTok0)).json.review.length === 0);
  905. // ---- mission 016 (layouts#2): THE COMMENTS BLOCK — edit (author), delete (author, asks first), like (members, toggle), in place
  906. // in the history between the other events; a non-member reads only, and the server refuses them too (faces + API) ----------------
  907. const cbProj = await api('POST', '/api/projects', { title: 'Comments block' });
  908. const CB = cbProj.json && cbProj.json.project ? cbProj.json.project.slug : 'comments-block';
  909. await api('POST', `/api/projects/${CB}/members`, { user: 'alice', role: 'admin' });
  910. const cbT = (await api('POST', `/api/projects/${CB}/tickets`, { subject: 'Comments in place' })).json.ticket;
  911. const cbGate = (await api('POST', PT(CB, 1) + '/comments', { text: 'the **gate** writes first' })).json.event;
  912. await api('POST', PT(CB, 1) + '/state', { state: 'progress', text: 'working on it' });
  913. 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));
  914. const CBURL = '/' + CB + '/1';
  915. // B = bob, NOT a member: reads the comments in the block, in place; no form, no Edit / Delete; the like does nothing
  916. await b.goto(BASE + CBURL);
  917. await b.waitForSelector('#events li.comment');
  918. await connected(b, 'B on the comments ticket (no member)');
  919. await mdShows(b, `li.comment[data-id="${cbGate.id}"] md-editor[data-readonly="true"] article`, 'the gate writes first', 'B draws gate\'s comment');
  920. const nmH = await hist(b);
  921. 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));
  922. 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)`));
  923. 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")'));
  924. await calmClick(b, `li.comment[data-id="${cbGate.id}"] button.comment-like`);
  925. await sleep(700);
  926. 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);
  927. // the server refuses a non-member too: the faces with bob's own session, and the API with bob's token
  928. const 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)];
  929. 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)));
  930. 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)];
  931. const afterNm = (await api('GET', PT(CB, 1))).json.events.find(e => e.id === cbGate.id);
  932. 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));
  933. // bob becomes a member (use): after a reload he has the form
  934. await api('POST', `/api/projects/${CB}/members`, { user: 'bob', role: 'use' });
  935. await b.goto(BASE + CBURL);
  936. await b.waitForSelector('#commentform form.comment-form');
  937. await connected(b, 'B on the comments ticket (use)');
  938. await b.evaluate('window.__m016 = 1');
  939. // A = alice posts by REAL keys + Ctrl+Enter: a NEW block after the state change; both browsers
  940. // 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
  941. // 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.
  942. await a.send('Emulation.setCPUThrottlingRate', { rate: 4 });
  943. await a.goto(BASE + CBURL);
  944. await a.click('#commentform md-editor article');
  945. await realKeys(a, 'alice writes **later** now');
  946. await connected(a, 'A on the comments ticket');
  947. await a.send('Emulation.setCPUThrottlingRate', { rate: 1 });
  948. await sleep(1500);
  949. const typedField = await a.evaluate('document.querySelector("#commentform md-editor input.value").value');
  950. 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')));
  951. await ctrlEnter(a);
  952. 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; });
  953. await b.waitFor('document.querySelectorAll("#events li.comment").length === 3', { label: 'B: alice\'s comment live' });
  954. const cbStored = (await api('GET', PT(CB, 1))).json.events;
  955. const aliceC = cbStored[cbStored.length - 1];
  956. const hA = await hist(a), hB = await hist(b);
  957. 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]));
  958. 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")'));
  959. // EDIT: a real click on Edit, real keys at the end, Save → both browsers show the new text and "edited"; the earlier version folds out
  960. await calmClick(a, `li.comment[data-id="${aliceC.id}"] button.comment-edit-start`);
  961. 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');
  962. await a.click(`li.comment[data-id="${aliceC.id}"] form.comment-edit md-editor article`);
  963. await endKey(a);
  964. await realKeys(a, ' and edits');
  965. await calmClick(a, `li.comment[data-id="${aliceC.id}"] button.comment-save`);
  966. await a.waitFor(`!!document.querySelector('li.comment[data-id="${aliceC.id}"] details.comment-history')`, { label: 'A: edited' });
  967. await b.waitFor(`!!document.querySelector('li.comment[data-id="${aliceC.id}"] details.comment-history')`, { label: 'B: the edit live' });
  968. const edApi = (await api('GET', PT(CB, 1))).json.events.find(e => e.id === aliceC.id);
  969. 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));
  970. 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');
  971. 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');
  972. await b.click(`li.comment[data-id="${aliceC.id}"] details.comment-history summary`);
  973. await b.waitFor(`document.querySelector('li.comment[data-id="${aliceC.id}"] details.comment-history').open`, { label: 'B: history open' });
  974. 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']));
  975. // 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)
  976. 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 }; })()`);
  977. 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));
  978. // sync of components.hybriel 4922f9c (SY): like / Edit / Delete and the "edited" label are 44 px targets
  979. const 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)`);
  980. check('sy: every like / Edit / Delete button and the "edited" label of the thread is a 44 px target', k1t.length === 0, J(k1t));
  981. // LIKE: bob likes alice's comment (toggle), alice sees the count live
  982. await calmClick(b, `li.comment[data-id="${aliceC.id}"] button.comment-like`);
  983. await b.waitFor(`document.querySelector('li.comment[data-id="${aliceC.id}"] button.comment-like').getAttribute('aria-pressed') === 'true'`, { label: 'B: liked' });
  984. await a.waitFor(`document.querySelector('li.comment[data-id="${aliceC.id}"] button.comment-like').textContent === '♡ 1'`, { label: 'A: the count live' });
  985. 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);
  986. await calmClick(b, `li.comment[data-id="${aliceC.id}"] button.comment-like`);
  987. await b.waitFor(`document.querySelector('li.comment[data-id="${aliceC.id}"] button.comment-like').getAttribute('aria-pressed') === 'false'`, { label: 'B: unliked' });
  988. await a.waitFor(`document.querySelector('li.comment[data-id="${aliceC.id}"] button.comment-like').textContent === '♡ 0'`, { label: 'A: back to 0' });
  989. 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);
  990. // another user's comment: bob (a member now) may not edit / delete it — faces and API refused
  991. const otherFaces = [await temit('ticketCommentEdit', [cbT.id, aliceC.id, 'bob edits alice'], bobCookie), await temit('ticketCommentDelete', [cbT.id, aliceC.id], bobCookie)];
  992. 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)];
  993. 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]));
  994. // DELETE asks first: Keep takes it back, Delete removes it from both browsers; one line stays in its place
  995. await calmClick(a, `li.comment[data-id="${aliceC.id}"] button.comment-delete`);
  996. await a.waitForSelector(`li.comment[data-id="${aliceC.id}"] comment-ask`);
  997. 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')`)));
  998. await calmClick(a, `li.comment[data-id="${aliceC.id}"] button.comment-delete-keep`);
  999. await sleep(600);
  1000. 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);
  1001. await calmClick(a, `li.comment[data-id="${aliceC.id}"] button.comment-delete`);
  1002. await calmClick(a, `li.comment[data-id="${aliceC.id}"] button.comment-delete-yes`);
  1003. await a.waitFor(`!document.querySelector('li.comment[data-id="${aliceC.id}"]')`, { label: 'A: the comment is gone' });
  1004. await b.waitFor(`!document.querySelector('li.comment[data-id="${aliceC.id}"]')`, { label: 'B: gone live' });
  1005. const delApi = (await api('GET', PT(CB, 1))).json.events.find(e => e.id === aliceC.id);
  1006. const hDel = await hist(b);
  1007. 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]));
  1008. const delMd = await (await fetch(BASE + PT(CB, 1), { headers: { accept: 'text/markdown' } })).text();
  1009. check('m016: delete — the Markdown view keeps the line, not the text', /· alice commented \(deleted /.test(delMd) && !delMd.includes('alice writes'), delMd.slice(-400));
  1010. 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)];
  1011. check('m016: a deleted comment can be neither edited nor liked (400)', J(delAgain.map(r => r.status)) === J([400, 400]), J(delAgain));
  1012. // THE API for programs: both URL forms, the token's user, refusals; an untouched comment keeps exactly its old keys
  1013. const apiPost = (await api('POST', PT(CB, 1) + '/comments', { text: 'gate via API' })).json.event;
  1014. const apiEdit = await api('POST', `/api/tickets/${cbT.id}/comments/${apiPost.id}/edit`, { text: 'gate via API, edited' });
  1015. const apiLike = await api('POST', PT(CB, 1) + `/comments/${apiPost.id}/like`, null);
  1016. const apiUnlike = await api('POST', `/api/tickets/${cbT.id}/comments/${apiPost.id}/like`, {});
  1017. 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));
  1018. 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)];
  1019. 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])));
  1020. const keysOf = (e) => Object.keys(e).sort().join(',');
  1021. const plainC = (await api('GET', PT(CB, 1))).json.events.find(e => e.id === cbGate.id);
  1022. 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));
  1023. for (const [w, h, name] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {
  1024. await viewport(b, w, h);
  1025. check(`m016 layout ${name} ${w}px: the history with the comment blocks has no horizontal overflow`, await noOverflow(b));
  1026. await shot(b, `${name}-comments`);
  1027. }
  1028. await viewport(b, 1280, 900);
  1029. // ---- mission 017 (tickets#27): ATTACHMENTS — pictures and files with a comment. The "Respond" block's form sits in the shared
  1030. // FilesUpload (pick mode); the API takes multipart/form-data. REAL input: the chooser's file input (DOM.setFileInputFiles), a real
  1031. // Ctrl+V of an image INTO the comment editor, real keys + Ctrl+Enter, real clicks. Checked: two chosen + one pasted picture go with
  1032. // 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;
  1033. // 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
  1034. // thumbnail; the API post of a PNG (multipart) and its download (Content-Type, nosniff, the same bytes); an edit keeps the files,
  1035. // a delete drops them (404, the bytes leave storage); the Markdown view lists them; 390 px: 44 px targets, no overflow.
  1036. // Null-safe: on the old code every check here FAILS instead of ending the gate.
  1037. {
  1038. 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; };
  1039. const png = (w, h, rgb) => {
  1040. 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]); };
  1041. const ihdr = Buffer.alloc(13); ihdr.writeUInt32BE(w, 0); ihdr.writeUInt32BE(h, 4); ihdr[8] = 8; ihdr[9] = 2;
  1042. 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);
  1043. 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))]);
  1044. };
  1045. const FD = join(SCRATCH, 'gate-files');
  1046. rmSync(FD, { recursive: true, force: true });
  1047. mkdirSync(FD, { recursive: true });
  1048. const F = (n) => join(FD, n);
  1049. writeFileSync(F('phone-390.png'), png(390, 640, [30, 90, 160]));
  1050. writeFileSync(F('desktop-1280.png'), png(1280, 720, [160, 60, 30]));
  1051. writeFileSync(F('api-shot.png'), png(200, 120, [10, 200, 90]));
  1052. writeFileSync(F('huge.bin'), Buffer.alloc(11 * 1048576, 3));
  1053. const ATT_DIR = join(STORE, 'attachments');
  1054. const storedFiles = () => existsSync(ATT_DIR) ? readdirSync(ATT_DIR).filter(n => !n.startsWith('.')).length : 0;
  1055. // the API with a multipart body (what a conductor's script does: curl -F / fetch FormData)
  1056. const apiFiles = async (path, text, files, token = TOKEN) => {
  1057. const fd = new FormData();
  1058. if (text !== null) fd.append('text', text);
  1059. for (const [name, buf, type] of files) fd.append('file', new Blob([buf], { type: type || 'application/octet-stream' }), name);
  1060. // over the transport's maxBody (20 MiB) the server answers 413 BEFORE reading the body and closes the connection; a client still
  1061. // writing sees the 413 or a reset (undici: "fetch failed"). Both are a refusal; status 'closed' stands for the reset.
  1062. let r; try { r = await fetch(BASE + path, { method: 'POST', headers: token ? { authorization: 'Bearer ' + token } : {}, body: fd }); }
  1063. 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; }
  1064. let json = null; try { json = await r.json(); } catch {}
  1065. return { status: r.status, json };
  1066. };
  1067. 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()) }; };
  1068. const atT = await api('POST', `/api/projects/${CB}/tickets`, { subject: 'Screenshots for the review' });
  1069. const AT = atT.json && atT.json.ticket ? atT.json.ticket : {};
  1070. const ATURL = '/' + CB + '/' + (AT.number || 2);
  1071. const ATP = PT(CB, AT.number || 2);
  1072. // 1. THE API: a PNG through multipart, as a conductor posts a screenshot
  1073. const stored0 = storedFiles();
  1074. const viaApi = await apiFiles(ATP + '/comments', 'The phone view, from a script', [['api-shot.png', readFileSync(F('api-shot.png')), 'image/png']]);
  1075. const apiAtt = viaApi.json && viaApi.json.event && viaApi.json.event.attachments ? viaApi.json.event.attachments : [];
  1076. 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));
  1077. const apiUrl = apiAtt.length ? apiAtt[0].url : '/api/attachments/none';
  1078. const dl = await getFile(apiUrl, { authorization: 'Bearer ' + TOKEN });
  1079. 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]));
  1080. const getAgain = (await api('GET', ATP)).json;
  1081. const apiEv = getAgain && getAgain.events ? getAgain.events.find(e => e.id === (viaApi.json && viaApi.json.event ? viaApi.json.event.id : '')) : null;
  1082. check('m017: API — GET the ticket returns the attachment list with its URL', !!apiEv && J(apiEv.attachments) === J(apiAtt), J(apiEv).slice(0, 400));
  1083. // refusals: a fake PNG, a file over 10 MB, more than 25 MB together, a bad field, a files-only post is fine
  1084. const fake = await apiFiles(ATP + '/comments', 'not a picture', [['fake.png', Buffer.from('this is text, not a PNG'), 'image/png']]);
  1085. const huge = await apiFiles(ATP + '/comments', 'too big', [['huge.bin', readFileSync(F('huge.bin'))]]);
  1086. const nine = Buffer.alloc(9 * 1048576, 5);
  1087. const tooMuch = await apiFiles(ATP + '/comments', 'three times 9 MB', [['a.bin', nine], ['b.bin', nine], ['c.bin', nine]]);
  1088. 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) }; })();
  1089. const noTokenFiles = await apiFiles(ATP + '/comments', 'x', [['api-shot.png', readFileSync(F('api-shot.png')), 'image/png']], null);
  1090. 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));
  1091. const onlyFile = await apiFiles(ATP + '/comments', null, [['notes.txt', Buffer.from('plain words\n')]]);
  1092. 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));
  1093. const jsonStill = await api('POST', ATP + '/comments', { text: 'a JSON comment as before' });
  1094. 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));
  1095. // 2. THE PAGE: A (alice) chooses two pictures, pastes a third into the editor (real Ctrl+V), types, Ctrl+Enter; B (bob) watches
  1096. await A.conn.send('Browser.grantPermissions', { origin: BASE, permissions: ['clipboardReadWrite', 'clipboardSanitizedWrite'] }).catch(() => {});
  1097. await b.goto(BASE + ATURL);
  1098. await b.waitForSelector('#events li.comment');
  1099. await connected(b, 'B on the attachments ticket');
  1100. await b.evaluate('window.__m017 = 1');
  1101. await a.goto(BASE + ATURL);
  1102. await a.waitForSelector('#commentform form.comment-form');
  1103. await connected(a, 'A on the attachments ticket');
  1104. 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(() => {});
  1105. 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');
  1106. const chooseOn = async (page, names) => {
  1107. const { root } = await page.send('DOM.getDocument');
  1108. const { nodeId } = await page.send('DOM.querySelector', { nodeId: root.nodeId, selector: '#commentform files-upload label.choose input[type=file]' });
  1109. try { await page.send('DOM.setFileInputFiles', { files: names.map(F), nodeId }); } catch {}
  1110. };
  1111. 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'))`);
  1112. await chooseOn(a, ['phone-390.png', 'desktop-1280.png']);
  1113. 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(() => {});
  1114. await mdShows(a, '#commentform md-editor article', '', 'A: the comment editor is live').catch(() => {});
  1115. // 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
  1116. // 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
  1117. // and the editor stands still, then click and check that the focus is in it.
  1118. await a.waitFor(`[...document.querySelectorAll('#events li.comment md-editor')].every(m => m.mdMounted)`, { label: 'A: the comment editors have drawn their text' });
  1119. await calmClick(a, '#commentform md-editor article');
  1120. await a.waitFor(`document.querySelector('#commentform md-editor').contains(document.activeElement)`, { label: 'A: the focus is in the comment editor' });
  1121. await realKeys(a, 'Review shots: phone, desktop and a paste');
  1122. 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; } })()`);
  1123. await a.send('Page.bringToFront');
  1124. await a.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', modifiers: 2, key: 'v', code: 'KeyV', windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86, commands: ['paste'] });
  1125. await a.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: 2, key: 'v', code: 'KeyV', windowsVirtualKeyCode: 86, nativeVirtualKeyCode: 86 });
  1126. 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(() => {});
  1127. const pk = await pickedOn(a);
  1128. 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));
  1129. // a file over 10 MB is refused in its own row before anything is sent
  1130. await chooseOn(a, ['huge.bin']);
  1131. await a.waitFor(`document.querySelectorAll('#commentform files-upload li.refused').length === 1`, { label: 'A: refused' }).catch(() => {});
  1132. 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);
  1133. const before = storedFiles();
  1134. await calmClick(a, '#commentform md-editor article');
  1135. await ctrlEnter(a);
  1136. 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(() => {});
  1137. const st = (await api('GET', ATP)).json;
  1138. const shotC = st && st.events ? st.events.filter(e => e.kind === 'comment').pop() : null;
  1139. 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));
  1140. // B sees them live (no reload) and opens one full size
  1141. await 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(() => {});
  1142. const bThumbs = await b.evaluate(`[...document.querySelectorAll('li.comment[data-id="${shotC ? shotC.id : 'x'}"] ul.comment-files img')].map(i => i.naturalWidth)`);
  1143. 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));
  1144. const firstUrl = shotC && shotC.attachments ? shotC.attachments[1].url : '/none';
  1145. const tabs0 = (await B.conn.send('Target.getTargets')).targetInfos.filter(t => t.type === 'page').length;
  1146. await b.click(`li.comment[data-id="${shotC ? shotC.id : 'x'}"] ul.comment-files li:nth-child(2) a.comment-thumb`).catch(() => {});
  1147. let opened = null;
  1148. 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); }
  1149. 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));
  1150. if (opened) await B.conn.send('Target.closeTarget', { targetId: opened.targetId }).catch(() => {});
  1151. const bobFull = await getFile(firstUrl, { cookie: bobCookie });
  1152. 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]));
  1153. // 3. A NON-MEMBER cannot fetch: a project bob is not in, a picture posted there
  1154. const prv = await api('POST', '/api/projects', { title: 'Attachments private' });
  1155. const PRV = prv.json && prv.json.project ? prv.json.project.slug : 'attachments-private';
  1156. await api('POST', `/api/projects/${PRV}/tickets`, { subject: 'Members only' });
  1157. const prvPost = await apiFiles(PT(PRV, 1) + '/comments', 'a private screenshot', [['private.png', readFileSync(F('api-shot.png')), 'image/png']]);
  1158. const prvUrl = prvPost.json && prvPost.json.event && prvPost.json.event.attachments ? prvPost.json.event.attachments[0].url : '/api/attachments/none';
  1159. 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 })];
  1160. 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])));
  1161. await b.goto(BASE + '/' + PRV + '/1');
  1162. await b.waitForSelector('#events li.comment');
  1163. await connected(b, 'B on the private ticket');
  1164. await sleep(500);
  1165. 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`));
  1166. const nmFace = await temit('commentWithFiles', [AT.id || '', 'x', []], bobCookie);
  1167. const prvT = (await api('GET', PT(PRV, 1))).json.ticket;
  1168. const nmFace2 = await temit('commentWithFiles', [prvT ? prvT.id : '', 'bob is no member', []], bobCookie);
  1169. 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]));
  1170. // 4. EDIT keeps the files, DELETE drops them
  1171. const 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)' });
  1172. 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));
  1173. const n0 = storedFiles();
  1174. await sleep(1000);
  1175. await a.waitForSelector(`li.comment[data-id="${shotC ? shotC.id : 'x'}"] button.comment-delete`).catch(() => {});
  1176. await a.click(`li.comment[data-id="${shotC ? shotC.id : 'x'}"] button.comment-delete`).catch(() => {});
  1177. await a.waitForSelector(`li.comment[data-id="${shotC ? shotC.id : 'x'}"] button.comment-delete-yes`).catch(() => {});
  1178. await a.click(`li.comment[data-id="${shotC ? shotC.id : 'x'}"] button.comment-delete-yes`).catch(() => {});
  1179. await a.waitFor(`!document.querySelector('li.comment[data-id="${shotC ? shotC.id : 'x'}"]')`, { label: 'A: deleted' }).catch(() => {});
  1180. const goneEv = (await api('GET', ATP)).json.events.find(e => e.id === (shotC ? shotC.id : ''));
  1181. 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));
  1182. const md = await (await fetch(BASE + ATP, { headers: { accept: 'text/markdown' } })).text();
  1183. 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));
  1184. // 5. 390 px: the form with picked files and the thumbnails; touch targets ≥ 44 px, nothing wider than the screen
  1185. await b.goto(BASE + ATURL);
  1186. await b.waitForSelector('#commentform form.comment-form');
  1187. await connected(b, 'B on the attachments ticket again');
  1188. await b.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 844, deviceScaleFactor: 2, mobile: true });
  1189. await b.send('Emulation.setTouchEmulationEnabled', { enabled: true, maxTouchPoints: 5 });
  1190. await sleep(300);
  1191. await chooseOn(b, ['phone-390.png', 'huge.bin']);
  1192. 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(() => {});
  1193. await sleep(400);
  1194. 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); })`);
  1195. 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));
  1196. 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)`)));
  1197. await shot(b, 'phone-attachments');
  1198. await b.send('Emulation.setTouchEmulationEnabled', { enabled: false });
  1199. await viewport(b, 1280, 900);
  1200. await shot(b, 'desktop-attachments');
  1201. // ==== UX mission (creator 2026-10-24: "no one will understand that thats a separate form and what it does"): "Respond" is ONE composer —
  1202. // 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.
  1203. // REAL input: real keys (typing, the select, Ctrl+A / Backspace), real clicks, a real drop; the chooser's input via DOM.setFileInputFiles.
  1204. await a.goto(BASE + ATURL);
  1205. await a.waitForSelector('#commentform form.comment-form');
  1206. await connected(a, 'A on the attachments ticket (composer)');
  1207. await viewport(a, 1280, 900);
  1208. await mdShows(a, '#commentform md-editor article', '', 'A: the composer editor is live').catch(() => {});
  1209. const SELS = '#commentform select[name=state]';
  1210. const labelNow = () => a.evaluate(`document.querySelector('#commentform button.comment-post').textContent.trim()`);
  1211. const stateOf = () => a.evaluate(`document.querySelector('#state').textContent`);
  1212. const selectedText = () => a.evaluate(`(() => { const s = document.querySelector(${J(SELS)}); return s.options[s.selectedIndex].textContent.trim(); })()`);
  1213. const pickStateReal = async (name) => {
  1214. await a.evaluate(`document.querySelector(${J(SELS)}).focus()`);
  1215. for (let i = 0; i < 14; i++) {
  1216. if ((await selectedText()) === name) return true;
  1217. await a.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40 });
  1218. await a.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40 });
  1219. await sleep(120);
  1220. }
  1221. return false;
  1222. };
  1223. const lastEvents = async (n) => { const j = (await api('GET', ATP)).json; return j && j.events ? j.events.slice(-n) : []; };
  1224. const stOpts = await texts(a, SELS + ' option');
  1225. const stateStart = await stateOf();
  1226. // the layout: one box
  1227. await chooseOn(a, ['phone-390.png', 'api-shot.png']);
  1228. 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(() => {});
  1229. 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 }; })()`);
  1230. 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));
  1231. 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));
  1232. 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]));
  1233. await shot(a, 'composer-desktop-files');
  1234. // a real drop of a third file onto the EDITOR (not onto a drop zone) collects it too
  1235. const edBox = await a.box('#commentform md-editor');
  1236. const dropData = { items: [], files: [F('desktop-1280.png')], dragOperationsMask: 1 };
  1237. for (const type of ['dragEnter', 'dragOver']) await a.send('Input.dispatchDragEvent', { type, x: Math.round(edBox.x), y: Math.round(edBox.y), data: dropData });
  1238. await a.send('Input.dispatchDragEvent', { type: 'drop', x: Math.round(edBox.x), y: Math.round(edBox.y), data: dropData });
  1239. await a.waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 3`, { label: 'A: dropped on the editor' }).catch(() => {});
  1240. 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)));
  1241. await a.click('#commentform files-upload li.picked[data-i="2"] button.remove');
  1242. await a.click('#commentform files-upload li.picked[data-i="1"] button.remove');
  1243. await a.waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 1`, { label: 'A: one file left' }).catch(() => {});
  1244. await a.click('#commentform files-upload li.picked[data-i="0"] button.remove');
  1245. await a.waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 0`, { label: 'A: no files' }).catch(() => {});
  1246. // 1. COMMENT ONLY
  1247. const c0 = await a.evaluate(`document.querySelectorAll('#events li.comment').length`);
  1248. await a.click('#commentform md-editor article');
  1249. await realKeys(a, 'UX comment only');
  1250. check('UX composer: text only → the button says "Comment"', (await labelNow()) === 'Comment', await labelNow());
  1251. await a.click('#commentform button.comment-post');
  1252. await a.waitFor(`document.querySelectorAll('#events li.comment').length === ${c0 + 1}`, { label: 'A: the comment shows' }).catch(() => {});
  1253. const ev1 = await lastEvents(2);
  1254. 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));
  1255. 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');
  1256. // 2. BOTH, with files chosen through the box's button
  1257. const target = ['progress', 'open', 'reopened'].find(x => stOpts.includes(x) && x !== stateStart);
  1258. await chooseOn(a, ['phone-390.png', 'api-shot.png']);
  1259. await a.waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 2`, { label: 'A: two files (both)' }).catch(() => {});
  1260. await a.click('#commentform md-editor article');
  1261. await realKeys(a, 'UX both with files');
  1262. check('UX composer: files and text, no state chosen → "Comment"', (await labelNow()) === 'Comment', await labelNow());
  1263. check('UX composer: a real key press on the State select chooses "' + target + '"', await pickStateReal(target));
  1264. check('UX composer: text + state → the button says "Comment and set to ' + target + '"', (await labelNow()) === 'Comment and set to ' + target, await labelNow());
  1265. await shot(a, 'composer-desktop-both');
  1266. await a.click('#commentform button.comment-post');
  1267. await a.waitFor(`document.querySelector('#state').textContent === ${J(target)} && document.querySelectorAll('#events li.comment').length === ${c0 + 2}`, { label: 'A: comment and state' }).catch(() => {});
  1268. const ev2 = await lastEvents(3);
  1269. const cm2 = ev2.find(e => e.kind === 'comment' && e.text === 'UX both with files');
  1270. 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));
  1271. 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');
  1272. // 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"):
  1273. // 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 text
  1274. const 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; })()`;
  1275. 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; })()`;
  1276. const plain1 = await a.evaluate(CARD('UX comment only'));
  1277. const both1 = await a.evaluate(CARD('UX both with files'));
  1278. 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));
  1279. const line1 = await a.evaluate(LINE);
  1280. 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));
  1281. await a.goto(BASE + ATURL);
  1282. await a.waitForSelector('#commentform form.comment-form');
  1283. await connected(a, 'A on the attachments ticket (reload)');
  1284. // the editors draw their text a moment after the load (their own 100 ms mount); the page is connected before that
  1285. await a.waitFor(`[...document.querySelectorAll('#events li.comment md-editor')].every(m => m.mdMounted)`, { label: 'A: the comment editors have drawn their text' });
  1286. const plain2 = await a.evaluate(CARD('UX comment only'));
  1287. const both2 = await a.evaluate(CARD('UX both with files'));
  1288. 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]))`)));
  1289. const line2 = await a.evaluate(LINE);
  1290. 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]));
  1291. await shot(a, 'composer-desktop-after-reload');
  1292. // 3. STATE ONLY, and the button's words switching with the text
  1293. const stOpts2 = await texts(a, SELS + ' option');
  1294. const t2 = stOpts2.includes('done') ? 'done' : stOpts2.find(x => x !== 'no change' && x !== 'review' && x !== 'pending');
  1295. 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));
  1296. check('UX composer: a real key press chooses "' + t2 + '"', await pickStateReal(t2));
  1297. check('UX composer: a state and nothing written → "Set to ' + t2 + '"', (await labelNow()) === 'Set to ' + t2, await labelNow());
  1298. await a.click('#commentform md-editor article');
  1299. await realKeys(a, 'x');
  1300. check('UX composer: typing one letter switches the button to "Comment and set to ' + t2 + '"', (await labelNow()) === 'Comment and set to ' + t2, await labelNow());
  1301. await modKey(a, 'a', 2, 65);
  1302. await a.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8, nativeVirtualKeyCode: 8 });
  1303. await a.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Backspace', code: 'Backspace', windowsVirtualKeyCode: 8, nativeVirtualKeyCode: 8 });
  1304. await a.waitFor(`document.querySelector('#commentform button.comment-post').textContent.trim() === ${J('Set to ' + t2)}`, { label: 'A: back to Set to' }).catch(() => {});
  1305. check('UX composer: deleting the text switches it back to "Set to ' + t2 + '"', (await labelNow()) === 'Set to ' + t2, await labelNow());
  1306. await shot(a, 'composer-desktop-state');
  1307. const c2 = await a.evaluate(`document.querySelectorAll('#events li.comment').length`);
  1308. await a.click('#commentform button.comment-post');
  1309. await a.waitFor(`document.querySelector('#state').textContent === ${J(t2)}`, { label: 'A: state only' }).catch(() => {});
  1310. const ev3 = await lastEvents(2);
  1311. 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));
  1312. // 4. a refused change keeps what was written: bob-like refusal is not possible for alice, so the empty post does nothing
  1313. await a.click('#commentform button.comment-post');
  1314. await sleep(500);
  1315. 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]));
  1316. // phone: the same composer at 390 px — one box, the footer wraps, every target 44 px, nothing wider than the screen
  1317. await viewport(a, 390, 844);
  1318. await chooseOn(a, ['phone-390.png']);
  1319. await a.waitFor(`document.querySelectorAll('#commentform files-upload li.picked').length === 1`, { label: 'A: phone file' }).catch(() => {});
  1320. const t3 = (await texts(a, SELS + ' option')).find(x => x !== 'no change' && x !== 'review' && x !== 'pending');
  1321. await pickStateReal(t3);
  1322. await a.evaluate(`document.querySelector('#commentform').scrollIntoView({ block: 'center' })`);
  1323. 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 }; })()`);
  1324. 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));
  1325. await shot(a, 'composer-phone');
  1326. await a.evaluate(`document.querySelector('#commentform files-upload li.picked button.remove').click()`);
  1327. await viewport(a, 1280, 900);
  1328. 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));
  1329. }
  1330. // 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 alone
  1331. await a.goto(BASE + '/alpha/1');
  1332. await a.waitForSelector('#events li.comment');
  1333. await connected(a, 'A on alpha #1 (state note)');
  1334. 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() : '' }; })()`);
  1335. 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));
  1336. // a new project by hand: title → slug proposed, admin can change it; old slugs keep working
  1337. await a.goto(BASE + '/new-project');
  1338. await a.waitForSelector('#projectform');
  1339. await connected(a, 'A on /new-project');
  1340. await type(a, '#projecttitle', 'My Project');
  1341. await a.waitFor('document.querySelector("#projectslug").value === "my-project"', { label: 'slug proposed' });
  1342. check('project: the slug my-project is proposed from the title', (await a.evaluate('document.querySelector("#projectslug").value')) === 'my-project');
  1343. await a.click('#projectcreate');
  1344. await a.waitForSelector('#created');
  1345. const mp = await api('GET', '/api/projects/my-project');
  1346. 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));
  1347. await a.goto(BASE + '/projects/my-project/settings');
  1348. await a.waitForSelector('#detailsform');
  1349. await connected(a, 'A on settings');
  1350. await type(a, '#setslug', 'my-proj');
  1351. await type(a, '#setdescription md-editor input.value', 'The **first** project.');
  1352. await a.click('#detailssave');
  1353. await a.waitFor('!!document.querySelector("#savemessage") && document.querySelector("#savemessage").textContent.length > 0', { label: 'saved' });
  1354. const mp2 = await api('GET', '/api/projects/my-proj');
  1355. const mpOld = await api('GET', '/api/projects/my-project');
  1356. 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));
  1357. const oldSlugMoved = await fetch(BASE + '/projects/my-project', { redirect: 'manual' });
  1358. 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'));
  1359. await a.goto(BASE + '/my-project');
  1360. await a.waitForSelector('#heading');
  1361. 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'));
  1362. // members in the settings page: add bob as use; remove; the last admin cannot go
  1363. await a.goto(BASE + '/projects/my-proj/settings');
  1364. await a.waitForSelector('#addform');
  1365. await connected(a, 'A on settings again');
  1366. await type(a, '#addref', 'bob');
  1367. await choose(a, '#addrole', 'use');
  1368. await a.click('#addsave');
  1369. await a.waitFor('document.querySelectorAll("#members li").length === 2', { label: 'bob added' });
  1370. await sleep(600);
  1371. 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')));
  1372. 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']]));
  1373. const lastAdmin = await api('POST', '/api/projects/my-proj/members', { user: 'alice', role: 'use' }, aliceTok0);
  1374. check('members: the last admin cannot be demoted (400)', lastAdmin.status === 400 && /at least one admin/.test(lastAdmin.json.error), J(lastAdmin));
  1375. const badRole = await api('POST', '/api/projects/my-proj/members', { user: 'bob', role: 'boss' }, aliceTok0);
  1376. check('members: an unknown role is refused (400)', badRole.status === 400 && badRole.json.field === 'role', J(badRole));
  1377. const rm = await api('POST', '/api/projects/my-proj/members/remove', { user: 'bob' }, aliceTok0);
  1378. check('members: an admin removes a member (200)', rm.status === 200 && rm.json.members.length === 1, J(rm).slice(0, 300));
  1379. // an invite link through ident
  1380. const inv = await api('POST', '/api/projects/my-proj/invites', { role: 'use' }, aliceTok0);
  1381. 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));
  1382. // carol opens the link, chooses her identity at ident → ident sends her back to tickets with the invite id → she is a member
  1383. const carol = await ident.signIn('[email protected]');
  1384. const invPage = await fetch(inv.json.url, { redirect: 'manual' });
  1385. const rid = (invPage.headers.get('location') || '').split('/').pop();
  1386. const chosen = await ident.emit('chooseIdentity', [rid, carol.identities[0].id], carol.cookie);
  1387. const back = chosen.value && chosen.value.url ? await fetch(chosen.value.url.replace(/^https?:\/\/[^/]+/, BASE), { redirect: 'manual' }) : { status: 0, headers: new Headers() };
  1388. const carolCookie = (back.headers.get('set-cookie') || '').split(';')[0];
  1389. const carolFace = await temit('saveDisplayName', ['carol'], carolCookie);
  1390. const mp3 = (await api('GET', '/api/projects/my-proj')).json;
  1391. 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));
  1392. const invBob = await api('POST', '/api/projects/my-proj/invites', { role: 'use' }, bobTok);
  1393. check('invite: a non-admin gets 403', invBob.status === 403, J(invBob).slice(0, 200));
  1394. // the new pages fit the screen (phone and desktop), with the project's data on them
  1395. for (const [path, sel, name] of [['/projects/my-proj/settings', '#addform', 'settings'], ['/new-project', '#projectform', 'new-project'], ['/my-proj', '#heading', 'project']]) {
  1396. await a.goto(BASE + path);
  1397. await a.waitForSelector(sel);
  1398. await connected(a, 'A on ' + path);
  1399. for (const [w, h, dev] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {
  1400. await viewport(a, w, h);
  1401. check(`layout ${dev} ${w}px: ${name} page has no horizontal overflow`, await noOverflow(a));
  1402. await shot(a, `${dev}-${name}`);
  1403. }
  1404. }
  1405. await viewport(a, 1280, 900);
  1406. await b.goto(BASE + '/inbox');
  1407. await b.waitForSelector('#pendingbox');
  1408. for (const [w, h, dev] of [[390, 844, 'phone'], [1280, 900, 'desktop']]) {
  1409. await viewport(b, w, h);
  1410. check(`layout ${dev} ${w}px: inbox page has no horizontal overflow`, await noOverflow(b));
  1411. }
  1412. await viewport(b, 1280, 900);
  1413. // ---- ticket #25 (mission 012): /api/projects/<project id>/… answers as /api/projects/<slug>/… (every route under it);
  1414. // tickets stay under their project, there is no new global /api/tickets/<x>
  1415. 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(); };
  1416. const idOf = async (slug) => (await api('GET', '/api/projects')).json.details.find(p => p.slug === slug).id;
  1417. const gammaId = await idOf('gamma');
  1418. check(`ids (#25): a project's id is its 12-character record id (gamma = ${gammaId})`, /^[0-9a-z]{12}$/.test(gammaId || ''), J(gammaId));
  1419. 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]]) {
  1420. const [x, y] = [await rawGet(byId, md), await rawGet(bySlug, md)];
  1421. 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)]));
  1422. }
  1423. for (const p of ['/api/projects/0zzzzzzzzzzz', '/api/projects/0zzzzzzzzzzz/tickets', '/api/projects/0zzzzzzzzzzz/tickets/1', '/api/projects/0zzzzzzzzzzz/connections']) {
  1424. const r = await api('GET', p);
  1425. check(`ids (#25): GET ${p} (no such id) → 404`, r.status === 404, J(r));
  1426. }
  1427. const glob = await api('GET', '/api/tickets/' + gammaId);
  1428. check('ids (#25): no global /api/tickets/<project id> (→ 404, as before)', glob.status === 404, J(glob).slice(0, 200));
  1429. // every write route under /api/projects/<id>/… on a project of its own
  1430. const dp = await api('POST', '/api/projects', { title: 'Delta by id', slug: 'delta' });
  1431. const did = dp.json && dp.json.project ? dp.json.project.id : null;
  1432. const P = (rest) => `/api/projects/${did}${rest}`;
  1433. const dt = await api('POST', P('/tickets'), { subject: 'made by id' });
  1434. 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));
  1435. const dWrites = [
  1436. ['comments', await api('POST', P('/tickets/1/comments'), { text: 'comment by id' })],
  1437. ['state', await api('POST', P('/tickets/1/state'), { state: 'progress' })],
  1438. ['edit', await api('POST', P('/tickets/1/edit'), { subject: 'made by id, edited' })],
  1439. ['assign', await api('POST', P('/tickets/1/assign'), { assignee: 'gate' })],
  1440. ['parent', await api('POST', P('/tickets/1/parent'), { parent: 'gamma#1' })],
  1441. ['blocked-by', await api('POST', P('/tickets/1/blocked-by'), { add: 'gamma#2' })],
  1442. ];
  1443. 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])));
  1444. const dRead = (await api('GET', '/api/projects/delta/tickets/1')).json;
  1445. 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));
  1446. const dDesc = await api('POST', P(''), { description: 'set by id' });
  1447. const dMem = await api('POST', P('/members'), { user: 'bob', role: 'use' });
  1448. const dRm = await api('POST', P('/members/remove'), { user: 'bob' });
  1449. const dInv = await api('POST', P('/invites'), { role: 'boss' });
  1450. const dDis = await api('POST', P('/connections/remove'), { id: 'nope' });
  1451. 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));
  1452. const zz = await api('POST', '/api/projects/0zzzzzzzzzzz/tickets', { subject: 'nowhere' });
  1453. check('ids (#25): POST to an unknown id → refused, nothing made', zz.status >= 400 && zz.status < 500, J(zz));
  1454. // the id survives a slug change; the old slug, the new one and the id answer the same
  1455. await api('POST', P(''), { slug: 'delta2' });
  1456. const [vId, vNew, vOld] = [await rawGet(P('/tickets/1')), await rawGet('/api/projects/delta2/tickets/1'), await rawGet('/api/projects/delta/tickets/1')];
  1457. 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)]));
  1458. 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');
  1459. // ---- the browsers said nothing bad (checked BEFORE ident goes down, ticket #11) ------------------
  1460. const problems = [...a.problems(), ...b.problems()].map(m => m.text).filter(t => !/favicon/.test(t));
  1461. check('console: no errors or warnings in either browser', problems.length === 0, J(problems).slice(0, 800));
  1462. // ---- ident down: a login fails politely, the server keeps serving ----------------------------
  1463. // TICKET #11: no page may be loading while ident stops (a tickets page loads ident's
  1464. // selector.js → ERR_CONNECTION_REFUSED in the console). Both browsers park on about:blank
  1465. // first and stay there; the phase is checked with fetch only, and the console again after.
  1466. for (const p of [a, b]) { await p.goto('about:blank'); }
  1467. await sleep(300);
  1468. const quietBefore = [...a.problems(), ...b.problems()].length;
  1469. await ident.stop();
  1470. const down = await fetch(BASE + '/login/callback?ident_code=' + 'cd'.repeat(24), { headers: { cookie: GATE_COOKIE }, redirect: 'manual' });
  1471. const downText = await down.text();
  1472. const downFace = await temit('identLogin', ['cd'.repeat(24)], GATE_COOKIE);
  1473. 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));
  1474. 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);
  1475. const lateProblems = [...a.problems(), ...b.problems()].slice(quietBefore).map(m => m.text);
  1476. check('console: nothing new while ident was down (the browsers were parked, #11)', lateProblems.length === 0, J(lateProblems).slice(0, 800));
  1477. // ---- THE INSTALLABLE APP (mission 046): manifest, icons, service worker, offline shell ----------------
  1478. // Its own fresh Chrome C (no worker from A/B), at the END because it stops the server: the offline reload must
  1479. // not reach the server even through the service worker (the CDP offline emulation is the page's, and it is what
  1480. // makes navigator.onLine false for the shell's note). ident is already down here (its selector.js fails to load).
  1481. const home = await (await fetch(BASE + '/')).text();
  1482. const mhref = (home.match(/<link rel="manifest" href="([^"]+)"/) || [])[1];
  1483. 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) || [])]));
  1484. const mres = await fetch(BASE + (mhref || '/__hl/manifest.webmanifest'));
  1485. let man = {}; try { man = await mres.json(); } catch {}
  1486. 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));
  1487. 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; };
  1488. const iconOk = [];
  1489. for (const ic of man.icons || []) iconOk.push(ic.type === 'image/png' && await pngSize(ic.src) === Number(ic.sizes.split('x')[0]));
  1490. 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));
  1491. const fav = await fetch(BASE + '/favicon.ico');
  1492. const favBuf = Buffer.from(await fav.arrayBuffer());
  1493. const svg = await fetch(BASE + '/icons/icon.svg');
  1494. 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()));
  1495. // ---- mission MT (mobile audit 2026-10-23): what a designer sees at 390 px. Each check below FAILED on the code before the fix
  1496. // (the ticket number wrapped to "# / 2 / 6", two chip rows filled half the screen, fields stood beside their captions at their own
  1497. // width, the Edit button was a centred slab, 500 rows drawn at once, member names broke mid-word, relation links were 24 px high)
  1498. const bulkP = await api('POST', '/api/projects', { title: 'Bulk', slug: 'bulk-mt' }, aliceTok0);
  1499. 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);
  1500. 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));
  1501. await viewport(a, 390, 844);
  1502. await a.goto(BASE + '/bulk-mt');
  1503. await a.waitForSelector('#tickets li');
  1504. await connected(a, 'A on /bulk-mt');
  1505. const mtRows = await a.evaluate(`document.querySelectorAll('#tickets li').length`);
  1506. 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`));
  1507. const mtOrder = await a.evaluate(`[...document.querySelectorAll('#tickets li a.subject')].map(x => x.textContent.replace(/^#\\d+/, '').slice(0, 14))`);
  1508. 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]]));
  1509. const mtRefs = await a.evaluate(`[...document.querySelectorAll('#tickets li a.subject ticket-ref')].map(r => Math.round(r.getBoundingClientRect().height))`);
  1510. 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));
  1511. 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)]; })()`);
  1512. 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));
  1513. // 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
  1514. // accent button and "New project" a quiet one, both at the right end of the heading row; no fold-out bar under the filters
  1515. const 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 }; })()`);
  1516. 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));
  1517. await shot(a, 'mt-phone-bulk');
  1518. await a.click('#moretickets').catch(() => {});
  1519. await a.waitFor(`document.querySelectorAll('#tickets li').length === 60`, { label: 'all 60 rows after the click' }).catch(() => {});
  1520. 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')`)));
  1521. check('mt (long subject): a subject of unbroken words does not widen the phone page', await noOverflow(a));
  1522. const mtNew = await api('POST', '/api/projects/bulk-mt/tickets', { subject: 'Bulk ticket 61, arrives live' }, aliceTok0);
  1523. await a.waitFor(`document.querySelectorAll('#tickets li').length === 61`, { label: 'live row' }).catch(() => {});
  1524. 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`)));
  1525. // fields: the caption above, the field the full width of its form — settings (admin), the ticket's manage forms, new ticket, /you
  1526. const 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; })()`;
  1527. await a.goto(BASE + '/projects/my-proj/settings');
  1528. await a.waitForSelector('#addform');
  1529. await connected(a, 'A on settings');
  1530. const mtSet = await a.evaluate(fullW(['#settitle', '#setslug', '#addref', '#addrole', '#inviterole', '#inviteuses', '#invitedays', '#inviteemail']));
  1531. check('mt (settings): every field is as wide as its form at 390 px (caption above, not beside it)', mtSet.length === 0, J(mtSet));
  1532. 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)])`);
  1533. 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));
  1534. await shot(a, 'mt-phone-settings');
  1535. await a.goto(BASE + '/you');
  1536. await a.waitForSelector('#tokenform');
  1537. await connected(a, 'A on /you');
  1538. 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']))));
  1539. const mtPar = await api('POST', '/api/projects/bulk-mt/tickets/2/parent', { parent: 'bulk-mt#1' }, aliceTok0);
  1540. await a.goto(BASE + '/bulk-mt/2');
  1541. await a.waitForSelector('#subject');
  1542. await connected(a, 'A on the MT child ticket');
  1543. await a.waitFor(`!!document.querySelector('#parentkey') && !!document.querySelector('#parent a')`, { label: 'manage forms and the parent link' }).catch(() => {});
  1544. const mtMan = await a.evaluate(fullW(['#assignselect', '#parentkey', '#blockerkey']));
  1545. check('mt (ticket): the manage and state fields are as wide as their forms at 390 px', mtMan.length === 0, J(mtMan));
  1546. const mtEdit = await a.evaluate(`(() => { const e = document.querySelector('#editbutton'); return e ? Math.round(e.getBoundingClientRect().width) : -1; })()`);
  1547. 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));
  1548. const mtRel = await a.evaluate(`[...document.querySelectorAll('#parent a, .refs a')].map(x => Math.round(x.getBoundingClientRect().height))`);
  1549. check('mt (relations): the links to the parent / children / blockers are 44 px targets', mtRel.length > 0 && mtRel.every(h => h >= 44), J(mtRel));
  1550. await shot(a, 'mt-phone-ticket');
  1551. await a.goto(BASE + '/bulk-mt');
  1552. await a.waitForSelector('#newticketbutton');
  1553. await connected(a, 'A on bulk new ticket');
  1554. const dlgOpen = (id) => a.evaluate(`!!document.querySelector('dialog#${id}[open]')`);
  1555. await a.click('#newticketbutton');
  1556. await a.waitFor(`!!document.querySelector('dialog#newticketmodal[open]')`, { label: 'A: the New ticket window opens' });
  1557. await sleep(400);
  1558. const mtNewF = await a.evaluate(fullW(['#newproject', '#newsubject']));
  1559. check('mt (new ticket): project and subject fields are as wide as the form', mtNewF.length === 0, J(mtNewF));
  1560. 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 }; })()`);
  1561. 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));
  1562. await shot(a, 'list-phone-new-ticket-window');
  1563. await a.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27, nativeVirtualKeyCode: 27 });
  1564. await a.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'Escape', code: 'Escape', windowsVirtualKeyCode: 27, nativeVirtualKeyCode: 27 });
  1565. await a.waitFor(`!document.querySelector('dialog[open]')`, { label: 'A: Esc closes the window' });
  1566. check('UX list: Esc closes the New ticket window', !(await dlgOpen('newticketmodal')));
  1567. await a.click('#newprojectlink');
  1568. await a.waitFor(`!!document.querySelector('dialog#newprojectmodal[open]') && !!document.querySelector('dialog#newprojectmodal #projectform')`, { label: 'A: the New project window opens' });
  1569. 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 }; })()`);
  1570. 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));
  1571. await shot(a, 'list-phone-new-project-window');
  1572. await a.click('dialog#newprojectmodal button.modal-x');
  1573. await a.waitFor(`!document.querySelector('dialog[open]')`, { label: 'A: × closes the window' });
  1574. check('UX list: the × closes the New project window', !(await dlgOpen('newprojectmodal')));
  1575. await viewport(a, 1280, 900);
  1576. await sleep(300);
  1577. // desktop: a centred window; submit a ticket with real keys and a real click; the window closes, the page says so, the row arrives
  1578. await a.click('#newticketbutton');
  1579. await a.waitFor(`!!document.querySelector('dialog#newticketmodal[open]')`, { label: 'A: the New ticket window opens (desktop)' });
  1580. await sleep(300);
  1581. 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 }; })()`);
  1582. 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));
  1583. const rows0 = await a.evaluate(`document.querySelectorAll('#tickets li').length`);
  1584. await a.click('#newsubmit');
  1585. await sleep(500);
  1586. 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));
  1587. await a.click('#newsubject');
  1588. await realKeys(a, 'Opened from the window');
  1589. await a.click('#newsummary md-editor article');
  1590. await realKeys(a, 'summary typed in the window');
  1591. await shot(a, 'list-desktop-new-ticket-window');
  1592. await a.click('#newsubmit');
  1593. await a.waitFor(`!document.querySelector('dialog[open]') && !!document.querySelector('#notice')`, { label: 'A: the window closes after submit' });
  1594. // ticketCreated reaches the page after the shell's inbox-count face settles.
  1595. 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' });
  1596. 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'));
  1597. const made = (await api('GET', '/api/projects/bulk-mt/tickets/62', undefined, aliceTok0)).json;
  1598. 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));
  1599. await a.click('#newprojectlink');
  1600. await a.waitFor(`!!document.querySelector('dialog#newprojectmodal[open]')`, { label: 'A: the New project window opens (desktop)' });
  1601. await a.click('#projecttitle');
  1602. await realKeys(a, 'Window Project');
  1603. await a.waitFor(`document.querySelector('#projectslug').value === 'window-project'`, { label: 'slug proposed in the window' });
  1604. await shot(a, 'list-desktop-new-project-window');
  1605. await a.click('#projectcreate');
  1606. 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' });
  1607. 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'));
  1608. await viewport(a, 1280, 900);
  1609. C = await launchBrowser({ debugPortRange: range(process.env.TICKETS_GATE_CHROME_C, '8640-8649') });
  1610. const c = patient(await C.newPage());
  1611. await viewport(c, 390, 844);
  1612. await c.goto(BASE + '/');
  1613. await c.waitForSelector('#tickets li');
  1614. await connected(c, 'C connected');
  1615. await c.waitFor('navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))', { label: 'service worker active' });
  1616. await c.waitFor('!!navigator.serviceWorker.controller', { label: 'the worker controls the page' });
  1617. 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))`));
  1618. const inst = await c.send('Page.getInstallabilityErrors');
  1619. check('pwa: Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, J(inst));
  1620. // 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)
  1621. 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 61
  1622. const online = await c.evaluate(`[!!document.querySelector('#offline'), document.querySelectorAll('#tickets li').length]`);
  1623. check('pwa: online the shell shows no offline note', online[0] === false && online[1] === LISTED, J(online) + " expected " + LISTED + " TOTAL " + TOTAL);
  1624. const cProblems = c.problems().map(m => m.text).filter(t => !/favicon/.test(t) && !t.includes(':' + IDENT_PORT) && !/Failed to load resource/.test(t));
  1625. 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));
  1626. await sleep(1500);
  1627. await shot(c, 'pwa-phone-online');
  1628. // 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 login
  1629. await c.goto(BASE + '/attachments-private/1');
  1630. await c.waitForSelector('#events li.comment');
  1631. await c.waitFor(`!!document.querySelector('#events ul.comment-files img') && document.querySelector('#events ul.comment-files img').complete`, { label: 'C: the thumbnail loads' });
  1632. 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') || ''); })()`));
  1633. await shot(c, 'signed-out-thumbnail-phone');
  1634. // OFFLINE: the network of the page is cut AND the server is gone; `/` reloads from the worker's cache
  1635. await stopTickets();
  1636. await c.setOffline(true);
  1637. await c.goto(BASE + '/');
  1638. await c.waitForSelector('#tickets li');
  1639. await c.waitFor('!!document.querySelector("#offline")', { label: 'the offline note' });
  1640. 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]`);
  1641. 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));
  1642. await sleep(300);
  1643. await shot(c, 'pwa-phone-offline');
  1644. check('layout phone 390px: the offline shell has no horizontal overflow', await noOverflow(c));
  1645. await c.goto(BASE + '/inbox');
  1646. await c.waitForSelector('main[data-hl-offline]');
  1647. check('pwa: offline a page that is not kept (/inbox) gets "Unavailable offline"', /Unavailable offline/.test(await c.text('main')), await c.text('main'));
  1648. await c.goto(BASE + '/');
  1649. await c.waitForSelector('#offline');
  1650. await c.setOffline(false);
  1651. await c.waitFor('!document.querySelector("#offline")', { label: 'the note goes when the network is back' });
  1652. check('pwa: the offline note goes when the browser is online again', true);
  1653. } catch (e) {
  1654. check('gate ran to the end', false, e.stack || String(e));
  1655. } finally {
  1656. for (const br of [A, B, C]) { if (br) { try { await br.close(); } catch {} } }
  1657. await stopTickets();
  1658. if (ident) { await ident.stop(); writeFileSync(join(SCRATCH, 'gate-ident.log'), ident.log()); }
  1659. exchProxy.close();
  1660. writeFileSync(join(SCRATCH, 'gate-server.log'), log);
  1661. }
  1662. console.log(`\n${passes} passed, ${failures} failed`);
  1663. process.exit(failures ? 1 : 0);

Branches

Latest commits

  • 1c10857bTickets conductor: P51 eval, brief 027mre
  • e725969dTickets conductor: #51 directionmre
  • 1b5c63ddTickets conductor: P51 startedmre
  • 9f13fbdaTickets conductor: brief 026 prioritymre
  • acc477d9Tickets conductor: brief 026 + Vinzenz recommendationsmre
  • 9233a734Tickets conductor: brief 026 completemre
  • 5da589fdTickets conductor: brief 026 + Gitoria's answermre
  • a3cd5329Tickets conductor: tickets#51 opened, brief 026 draftmre
  • 6f6e5797Tickets conductor: STATUS wordingmre
  • 957de51fTickets conductor: T36 live, #36 review, #50 donemre
  • bc2fde32Merge branch 'main' into t36-stylemre
  • b7ca093atests: wait for the new row and normalize editor marker spacesmre
  • 41da3525Tickets conductor: flake cause, T36 deploy stepmre
  • 64c477e6Tickets conductor: deploy waits for Arachnemre
  • 467d7286Tickets conductor: T36 done, deploy questionmre
  • fed5ca81ticket_list: remove repeated selected-state coloursmre
  • 8542fc8aTickets conductor: T36 proof reviewedmre
  • 35980936inbox: preserve desktop columns after list styles were scopedmre
  • 2a5b8b91Tickets conductor: T36 cap stop, resumed for proofmre
  • c077a5cbstyles: format Style with nested language rulesmre