gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit99ca1cf699ca1cf6Merge branch 'vendor-day56' into mainAtlas99ca1cf6/tests/browser.mjs

77.3 KB

  1. // tests/browser.mjs — THE GATE of notes.worldapi.org (tickets notes#1: sidebar + Markdown editor; notes#2: offline + sync;
  2. // notes#4: offline and sync in pure Hybriel — hl:web's own worker, kept state per user and queue; Chrome offline through CDP).
  3. // Its own notes server on its own storage, its OWN ident (a copy of ident's code without .env — codes go to a mail
  4. // sink, tests/identkit.mjs), real headless Chromes for everything visible. `*.notes.test` is mapped to 127.0.0.1
  5. // inside Chrome (--host-resolver-rules) so ident and the app are the same site, as on worldapi.org.
  6. //
  7. // node tests/browser.mjs (NOTES_GATE_PORT server, default 8702; NOTES_GATE_IDENT_PORT, default 8701;
  8. // NOTES_GATE_CHROME "8713-8719" = Chrome debug ports)
  9. // Screenshots (390 / 1280 px) land in .scratch/gate-*.png. Every process started is stopped by PID.
  10. // NOTES_GATE_SOFT=1 (old code only: waits do not stop the gate), NOTES_GATE_DEBUG=1 (a crash dumps both devices' state).
  11. // NOTES_GATE_UNTIL=<section> stops after that section (offline, outage, conflict, delete, …) while working on the gate.
  12. import { spawn } from 'node:child_process';
  13. import { rmSync, mkdirSync, writeFileSync, existsSync } from 'node:fs';
  14. import { dirname, join, resolve } from 'node:path';
  15. import { fileURLToPath } from 'node:url';
  16. import { launchBrowser } from './cdp.mjs';
  17. import { startIdent } from './identkit.mjs';
  18. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  19. const HERE = dirname(fileURLToPath(import.meta.url));
  20. const APP = resolve(HERE, '..');
  21. const BIN = join(APP, 'bin/hybriel');
  22. const PORT = Number(process.env.NOTES_GATE_PORT || 8702);
  23. const IDENT_PORT = Number(process.env.NOTES_GATE_IDENT_PORT || 8701);
  24. const API = `http://127.0.0.1:${PORT}`;
  25. const BASE = `http://notes.test:${PORT}`;
  26. const IDENT_B = `http://ident.notes.test:${IDENT_PORT}`;
  27. const [CH_FROM, CH_TO] = (process.env.NOTES_GATE_CHROME || '8703-8709').split('-').map(Number);
  28. process.env.HL_CHROME_ARGS = '--host-resolver-rules=MAP *.notes.test 127.0.0.1, MAP notes.test 127.0.0.1|--unsafely-treat-insecure-origin-as-secure=' + `http://notes.test:${PORT}`; // a service worker needs a secure origin (https on worldapi.org)
  29. const SCRATCH = join(APP, '.scratch');
  30. const STORE = join(SCRATCH, 'gate-store');
  31. const IDENT_DIR = process.env.NOTES_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));
  32. rmSync(STORE, { recursive: true, force: true });
  33. mkdirSync(STORE, { recursive: true });
  34. // 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
  35. // 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
  36. // header, not on the right, covered by something else).
  37. const SELECTOR_IN_HEADER = `(() => { const s = document.querySelector('application-header ident-selector'); if (!s) return 'no ident-selector in the header';
  38. 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; }
  39. const b = s.getBoundingClientRect(), h = document.querySelector('application-header').getBoundingClientRect();
  40. if (b.width < 40 || b.height < 30) return 'no box ' + b.width + 'x' + b.height;
  41. 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]);
  42. 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]);
  43. if (b.left + b.width / 2 < innerWidth / 2) return 'not at the top right ' + b.left;
  44. 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);
  45. return 'ok'; })()`;
  46. let failures = 0, passes = 0;
  47. function check(label, ok, detail = '') {
  48. console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);
  49. if (ok) passes++; else failures++;
  50. }
  51. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  52. const J = JSON.stringify;
  53. let log = '';
  54. let server = null, ident = null;
  55. const browsers = [];
  56. function startServer(extraEnv = {}) {
  57. log += '\n==== notes server start\n';
  58. server = spawn(BIN, ['project.hl'], {
  59. cwd: APP,
  60. env: { ...process.env, NOTES_PORT: String(PORT), NOTES_STORAGE: join(STORE, 'mpackdb'), NOTES_SESSIONS: join(STORE, 'sessions') + '/', NOTES_WATCH: '0',
  61. NOTES_PUBLIC_URL: BASE, IDENT_URL: IDENT_B, IDENT_EXCHANGE_URL: ident.base, ...extraEnv },
  62. stdio: ['ignore', 'pipe', 'pipe'],
  63. });
  64. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  65. }
  66. async function serverUp() {
  67. for (let i = 0; i < 480; i++) { try { const r = await fetch(API + '/'); if (r.ok) return; } catch {} await sleep(250); }
  68. throw new Error('notes did not come up\n' + log);
  69. }
  70. async function stopServer() {
  71. if (!server) return;
  72. try { server.kill('SIGTERM'); } catch {}
  73. await new Promise(r => { if (server.exitCode !== null || server.signalCode !== null) return r(); server.once('exit', r); setTimeout(r, 3000); });
  74. server = null;
  75. }
  76. const SLOW = Number(process.env.NOTES_GATE_SLOW || 3);
  77. // NOTES_GATE_SOFT=1: a wait that times out is logged and the gate goes on (the checks decide) — to run this gate against
  78. // OLD code and see which checks fail there; never for a real gate run
  79. const SOFT = process.env.NOTES_GATE_SOFT === '1';
  80. function patient(page) {
  81. const waitFor = page.waitFor.bind(page);
  82. page.waitFor = (expr, o = {}) => SOFT
  83. ? waitFor(expr, { ...o, timeout: o.timeout || 10000 }).catch((e) => { console.log('note (soft): ' + e.message); return false; })
  84. : waitFor(expr, { ...o, timeout: (o.timeout || 10000) * SLOW });
  85. const goto = page.goto.bind(page);
  86. page.goto = (url, o = {}) => goto(url, { ...o, timeout: (o.timeout || 15000) * SLOW });
  87. return page;
  88. }
  89. // a page of a NEW Chrome (own cookies), or — given `like` — another tab of the same Chrome (same login)
  90. async function newPage(like = null) {
  91. if (like) return patient(await like.__browser.newPage());
  92. const b = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });
  93. browsers.push(b);
  94. const p = patient(await b.newPage());
  95. p.__browser = b;
  96. return p;
  97. }
  98. async function viewport(page, width, height) {
  99. await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 });
  100. await sleep(250);
  101. }
  102. async function shot(page, name) {
  103. await page.send('Page.bringToFront');
  104. const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });
  105. writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64'));
  106. }
  107. const noOverflow = (page) => page.evaluate('document.documentElement.scrollWidth <= window.innerWidth');
  108. const hydrated = (page) => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'page hydrated' });
  109. const txt = (page, sel) => page.evaluate(`(document.querySelector(${J(sel)}) || {}).textContent || null`);
  110. const has = (page, sel) => page.evaluate(`!!document.querySelector(${J(sel)})`);
  111. const subjects = (page) => page.evaluate(`[...document.querySelectorAll('#notes a')].map(a => a.textContent)`);
  112. const UNTIL = process.env.NOTES_GATE_UNTIL || '';
  113. const until = (name) => { if (UNTIL === name) throw Object.assign(new Error('stopped after ' + name), { until: true }); };
  114. const visible = (page, sel) => page.evaluate(`(() => { const e = document.querySelector(${J(sel)}); return !!e && e.getBoundingClientRect().width > 0; })()`);
  115. async function identSignIn(page, email) {
  116. await page.goto(IDENT_B + '/');
  117. await page.waitForSelector('#email');
  118. await hydrated(page);
  119. await page.type('#email', email);
  120. await page.click('#sendcode');
  121. await page.waitFor('/\\/code$/.test(location.pathname) && !!document.querySelector("#code")', { label: 'ident /code page' });
  122. await hydrated(page);
  123. await page.type('#code', ident.lastCode(email));
  124. await page.click('#verify');
  125. await page.waitForSelector('#signout, #menusignout', { timeout: 10000 });
  126. }
  127. // the plain LOGIN LINK (ident's /login with the app key and the callback — the header has no button for it since 2026-10-24, the selector is the way
  128. // in, but the old way is still served): opened as the button's link did → ident's "choose an identity" → back
  129. let LOGIN_URL = null;
  130. async function buttonLogin(page) {
  131. await page.goto(LOGIN_URL);
  132. await page.waitForSelector('#chooselist', { timeout: 10000 });
  133. await hydrated(page);
  134. await page.click('#chooselist li:nth-child(1) button');
  135. }
  136. // ---- REAL clicks and keys into the editor's shadow DOM (as in tickets' gate) ----------------------------
  137. const mdR = (expr) => `(() => { const r = document.querySelector('#notetext md-editor'); if (!r) return null; return (${expr}); })()`;
  138. const CTRL = 2;
  139. async function mdClick(page, sel) {
  140. const bx = await page.evaluate(mdR(`(() => { const el = r.querySelector(${J(sel)}); if (!el) return null; el.scrollIntoView({ block: 'center' }); const q = el.getBoundingClientRect(); return { x: q.left, y: q.top, w: q.width, h: q.height }; })()`));
  141. if (!bx || !bx.w) throw new Error('mdClick: ' + sel + ' is not laid out');
  142. const x = Math.round(bx.x + bx.w / 2), y = Math.round(bx.y + bx.h / 2);
  143. for (const [type, buttons] of [['mouseMoved', 0], ['mousePressed', 1], ['mouseReleased', 0]]) await page.send('Input.dispatchMouseEvent', { type, x, y, button: 'left', clickCount: 1, buttons });
  144. await sleep(80);
  145. }
  146. async function mdPress(page, key, mods = 0) {
  147. const K = { Enter: [13, 'Enter', '\r'], End: [35, 'End'], Tab: [9, 'Tab'] }[key];
  148. const [vk, code, text] = K;
  149. const t = text && !(mods & CTRL) ? text : undefined;
  150. await page.send('Input.dispatchKeyEvent', { type: t ? 'keyDown' : 'rawKeyDown', modifiers: mods, key, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk, ...(t ? { text: t, unmodifiedText: t } : {}) });
  151. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: mods, key, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk });
  152. await sleep(30);
  153. }
  154. async function mdType(page, text) {
  155. for (const ch of text) {
  156. await page.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch });
  157. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });
  158. }
  159. await sleep(60);
  160. }
  161. const taVal = (page) => page.evaluate(`document.querySelector('#notetext input[name=text]').value`);
  162. // the block builds the surface's content once the page is live (a 100 ms animation, no mount event): wait for it, or a click lands in an empty surface
  163. const editorReady = (page, label) => page.waitFor(mdR(`!!r.querySelector('md-editor article > *')`), { label });
  164. const emitFace = async (event, payload, cookie) => {
  165. const r = await fetch(API + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: 1, event, payload }) });
  166. const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}
  167. return { status: r.status, raw: t, value: j && j.value };
  168. };
  169. // ---- CHROME OFFLINE (notes#4): CDP cuts the page AND its service worker. An open WebSocket survives the cut
  170. // (report 005), so every offline check first RELOADS offline: the page boots from hl:web's worker, no socket opens.
  171. async function workerSessions(page) {
  172. const conn = page.__browser.conn;
  173. page.__workers = page.__workers || new Map();
  174. const { targetInfos } = await conn.send('Target.getTargets');
  175. for (const t of targetInfos) {
  176. if (t.type === 'service_worker' && !page.__workers.has(t.targetId)) {
  177. const { sessionId } = await conn.send('Target.attachToTarget', { targetId: t.targetId, flatten: true });
  178. await conn.send('Network.enable', {}, sessionId);
  179. page.__workers.set(t.targetId, sessionId);
  180. }
  181. }
  182. return [...page.__workers.values()];
  183. }
  184. async function setOffline(page, off) {
  185. await page.setOffline(off);
  186. for (const s of await workerSessions(page)) await page.__browser.conn.send('Network.emulateNetworkConditions', { offline: off, latency: 0, downloadThroughput: -1, uploadThroughput: -1 }, s);
  187. }
  188. const socketOpen = (page) => page.evaluate('!!(window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1)');
  189. const booted = (page, label) => page.waitFor('!!window.__hl', { label });
  190. // what hl:web keeps in this browser (IndexedDB `hl-offline`: `state`, `queue`) and the worker's documents
  191. const keptCopy = (page) => page.evaluate(`(async () => {
  192. const dbs = (await indexedDB.databases()).map(d => d.name);
  193. // every database of this origin, every store (hl:web's \`hl-offline\` and anything else, e.g. the old notes-<user>)
  194. let state = [], queue = [];
  195. for (const name of dbs) {
  196. const db = await new Promise((ok, no) => { const r = indexedDB.open(name); r.onsuccess = () => ok(r.result); r.onerror = () => no(r.error); });
  197. const all = (st) => new Promise((ok) => { try { const r = db.transaction(st, 'readonly').objectStore(st).getAll(); r.onsuccess = () => ok(r.result); r.onerror = () => ok([]); } catch (e) { ok([]); } });
  198. for (const st of [...db.objectStoreNames]) { const rows = await all(st); if (name === 'hl-offline' && st === 'queue') queue = rows; else state.push({ db: name, store: st, rows }); }
  199. db.close();
  200. }
  201. const docs = [];
  202. for (const k of await caches.keys()) { const c = await caches.open(k); for (const r of await c.keys()) { const res = await c.match(r); if ((res.headers.get('content-type') || '').includes('text/html')) docs.push({ cache: k, path: new URL(r.url).pathname, html: await res.text() }); } }
  203. return { dbs, state: JSON.stringify(state), queue: queue.length, queueText: JSON.stringify(queue), docs };
  204. })()`);
  205. // the editor: <md-editor>'s own surface when the element is defined, else the plain textarea it wraps — real keys either way
  206. const mdDefined = (page) => page.evaluate(`!!document.querySelector('#notetext md-editor article')`);
  207. async function typeAtEnd(page, text) {
  208. if (await mdDefined(page)) {
  209. await editorReady(page, 'editor');
  210. await mdClick(page, 'md-editor article');
  211. await mdPress(page, 'End', CTRL);
  212. } else {
  213. await page.click('#notetext');
  214. await mdPress(page, 'End', CTRL);
  215. }
  216. await mdType(page, text);
  217. }
  218. try {
  219. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  220. const alice = await ident.signIn('[email protected]');
  221. await ident.signIn('[email protected]');
  222. const APPKEY = await ident.registerApp(alice, 'notes (gate)', [BASE]);
  223. LOGIN_URL = `${IDENT_B}/login?key=${APPKEY.key}&return=${encodeURIComponent(BASE + '/login/callback')}`;
  224. check('ident: our own ident runs (a copy without .env), notes is registered', /^pk_[0-9a-f]{32}$/.test(APPKEY.key) && !existsSync(join(STORE, 'ident', 'ident-code', '.env')));
  225. startServer({ IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret });
  226. await serverUp();
  227. // ---- signed out -------------------------------------------------------------------------------------
  228. let html = await (await fetch(API + '/')).text();
  229. check('signed out: the page only asks to log in (no list, no editor, no notes)', /Log in with ident/.test(html) && !/id="newnote"|<note-list|<md-editor|id="notesapp"/.test(html), html.slice(html.indexOf('<body')).slice(0, 300));
  230. // mission 015 (route marker, hybriel#197): the menu's one item "Notes" (href /) is marked in the SERVER's html on every page: the list, a note, the login failure
  231. for (const pg of ['/', '/note/abc123def456', '/login/failed']) {
  232. const h = await (await fetch(API + pg)).text();
  233. const links = [...h.matchAll(/<a [^>]*href="\/"[^>]*>Notes/g)].map(m => m[0]);
  234. check(`server html ${pg}: the menu marks Notes (aria-current=page, class current), in both menus, before any script`, links.length >= 2 && links.every(l => /aria-current="page"/.test(l) && /class="current"/.test(l)), J(links));
  235. }
  236. let r = await fetch(API + '/login/callback', { redirect: 'manual' });
  237. check('login: /login/callback without a code → /login/failed', r.status === 302 && r.headers.get('location') === '/login/failed');
  238. r = await fetch(API + '/api/notes');
  239. check('signed out: the notes API answers 401', r.status === 401);
  240. r = await (await fetch(API + '/api/me')).json();
  241. check('signed out: /api/me says nobody', r.user === null, J(r));
  242. // ---- log in with ident (the button flow) on device A ----------------------------------------------------
  243. const a = await newPage();
  244. globalThis.__debugPages = { A: a };
  245. await viewport(a, 1280, 900);
  246. await identSignIn(a, '[email protected]');
  247. await a.goto(BASE + '/');
  248. await hydrated(a);
  249. check('signed out (browser): the selector stands in the header and NOTHING beside it (no second "Log in with ident" button); no "New note"', await has(a, '#selector') && !(await has(a, '#loginbutton')) && !(await has(a, 'a[href*="/login?key="]')) && !(await has(a, '#newnote')));
  250. for (const [w, h] of [[390, 844], [1280, 900]]) {
  251. await viewport(a, w, h);
  252. check(`IW ${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));
  253. }
  254. await viewport(a, 1280, 900);
  255. await buttonLogin(a);
  256. await a.waitForSelector('#newnote', { timeout: 15000 });
  257. check('login: alice sees her (empty) list and "New note"', (await txt(a, '#empty')) !== null && (await subjects(a)).length === 0 && await has(a, '#logout'));
  258. for (const [w, h] of [[390, 844], [1280, 900]]) {
  259. await viewport(a, w, h);
  260. check(`IW ${w}px signed in: ident's selector stands visible at the top right of the header and shows it is logged in`, (await a.evaluate(SELECTOR_IN_HEADER)) === 'ok' && /logged in with/.test(await a.evaluate(`document.querySelector('#selector').shadowRoot.textContent`)), await a.evaluate(SELECTOR_IN_HEADER));
  261. check(`IW ${w}px signed in: Log out is reachable (the user menu opens by a real click and shows it, 44 px high, inside the screen)`, await a.evaluate('(() => { const b = document.querySelector("#logout").getBoundingClientRect(); return b.width > 0 && b.height >= 44 && b.bottom <= innerHeight && b.right <= innerWidth; })()'));
  262. }
  263. await viewport(a, 1280, 900);
  264. const cookieOf = async (page) => (await page.cookies([BASE])).filter(c => c.name === 'notessid').map(c => 'notessid=' + c.value)[0];
  265. const cookieA = await cookieOf(a);
  266. const apiGet = async (path, cookie) => { const x = await fetch(API + path, { headers: { cookie } }); return { status: x.status, json: await x.json().catch(() => null) }; };
  267. const apiPost = async (body, cookie) => { const x = await fetch(API + '/api/notes', { method: 'POST', headers: { cookie, 'content-type': 'application/json' }, body: typeof body === 'string' ? body : J(body) }); return { status: x.status, json: await x.json().catch(() => null) }; };
  268. const serverNotes = async (cookie) => {
  269. const list = (await apiGet('/api/notes', cookie)).json.notes.filter(n => !n.gone);
  270. const out = [];
  271. for (const n of list) out.push({ ...n, text: (await apiGet('/api/notes?id=' + n.id, cookie)).json.text });
  272. return out;
  273. };
  274. const untilServer = async (cookie, pred, label) => {
  275. for (let i = 0; i < 80; i++) { const ns = await serverNotes(cookie); if (pred(ns)) return ns; await sleep(250); }
  276. throw new Error('server never showed: ' + label + ' ' + J(await serverNotes(cookie)));
  277. };
  278. // the page has synced when its socket is open and nothing waits in hl:web's queue (the replay is done)
  279. const synced = async (page, label) => {
  280. await page.waitFor('!!(window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1)', { label: label + ' (socket)', timeout: 20000 });
  281. for (let i = 0; i < 120; i++) { if ((await keptCopy(page)).queue === 0) return true; await sleep(250); }
  282. console.log('note: ' + label + ': the queue never emptied'); // the checks after this decide
  283. return false;
  284. };
  285. const keptPaths = (page) => page.evaluate(`(async () => { const out = []; for (const k of await caches.keys()) { if (!k.startsWith('hl-shell-')) continue; const c = await caches.open(k); for (const r of await c.keys()) out.push(new URL(r.url).pathname); } return out.sort().join(' '); })()`);
  286. const shellKept = async (page) => { for (let i = 0; i < 80; i++) { if (/(^| )\/( |$)/.test(await keptPaths(page))) return true; await sleep(250); } console.log('note: the page was never kept by hl:web: ' + await keptPaths(page)); return false; };
  287. await a.waitFor('!!navigator.serviceWorker.controller', { label: 'page controlled by a service worker' });
  288. await shellKept(a);
  289. const kp = await keptPaths(a);
  290. check("offline: hl:web's worker keeps the page document and the shell (runtime, client half, stylesheet, page modules)",
  291. /(^| )\/( |$)/.test(kp) && /\/__hl\/hl-runtime\.js/.test(kp) && /\/__hl\/web\/client\.js/.test(kp) && /\/__hl\/app\.css/.test(kp) && /\/components\/notes\.hl/.test(kp), kp);
  292. // ---- THE INSTALLABLE APP (mission 046): hl:web's own manifest from project.hl appIcons, and since notes#4 its own
  293. // generated service worker too (`offline = [Notes]`): notes' /sw.js and /notes-offline.js are gone.
  294. const pwaHtml = await (await fetch(API + '/')).text();
  295. const mhref = (pwaHtml.match(/<link rel="manifest" href="([^"]+)"/) || [])[1];
  296. check('pwa: every page head links the manifest, the apple-touch-icon, the favicon and the theme colour (the header token `darker`)',
  297. mhref === '/__hl/manifest.webmanifest' && pwaHtml.includes('<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png">')
  298. && pwaHtml.includes('<link rel="icon" href="/icons/favicon.svg">') && pwaHtml.includes('<meta name="theme-color" content="rgb(15, 20, 25)">'), pwaHtml.slice(0, 900));
  299. const mres = await fetch(API + mhref);
  300. const man = await mres.json();
  301. check('pwa: the manifest is served as application/manifest+json: name "notes", start_url /, scope /, display standalone, the token colours',
  302. /manifest\+json/.test(mres.headers.get('content-type') || '') && man.name === 'notes' && man.short_name === 'notes' && man.start_url === '/' && man.scope === '/'
  303. && man.display === 'standalone' && man.theme_color === 'rgb(15, 20, 25)' && man.background_color === 'rgb(25, 30, 35)', J(man));
  304. const iconOk = [];
  305. for (const ic of man.icons || []) {
  306. const ir = await fetch(API + ic.src);
  307. const buf = Buffer.from(await ir.arrayBuffer());
  308. iconOk.push(ir.ok && ic.type === 'image/png' && buf.readUInt32BE(16) === Number(ic.sizes.split('x')[0]) && buf.readUInt32BE(20) === Number(ic.sizes.split('x')[1]));
  309. }
  310. check('pwa: every manifest icon loads and is a real PNG of its declared size (192 + 512, any + maskable)',
  311. iconOk.length === 4 && iconOk.every(Boolean) && ['any', 'maskable'].every(pu => ['192x192', '512x512'].every(sz => man.icons.some(i => i.purpose === pu && i.sizes === sz))), J(man.icons) + ' ' + J(iconOk));
  312. const touch = await fetch(API + '/icons/apple-touch-icon.png');
  313. const touchBytes = Buffer.from(await touch.arrayBuffer());
  314. const fav = await fetch(API + '/icons/favicon.svg');
  315. const favText = await fav.text();
  316. const ico = await fetch(API + '/favicon.ico');
  317. const icoBytes = Buffer.from(await ico.arrayBuffer());
  318. check('pwa: apple-touch-icon is a 180×180 PNG, the favicon an SVG in notes yellow, /favicon.ico a real icon file',
  319. touch.ok && touchBytes.readUInt32BE(16) === 180 && fav.ok && /image\/svg\+xml/.test(fav.headers.get('content-type') || '') && favText.includes('#dcdcaa')
  320. && ico.ok && icoBytes.readUInt32BE(0) === 0x00000100, `${touch.status} ${fav.status} ${ico.status}`);
  321. const am = await a.send('Page.getAppManifest');
  322. check('pwa: Chrome parses the manifest without errors', am.url && am.url.endsWith('/__hl/manifest.webmanifest') && (am.errors || []).length === 0, J(am.errors));
  323. const inst = await a.send('Page.getInstallabilityErrors');
  324. check('pwa: Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, J(inst));
  325. const regs = await a.evaluate(`navigator.serviceWorker.getRegistrations().then(rs => rs.map(r => new URL(r.scope).pathname + ' ' + new URL((r.active || r.waiting || r.installing).scriptURL).pathname).join(','))`);
  326. check("pwa: exactly one service worker — hl:web's generated /__hl/sw.js for scope /, it controls the page; /sw.js and /notes-offline.js are gone (404)",
  327. regs === '/ /__hl/sw.js' && new URL(await a.evaluate('navigator.serviceWorker.controller.scriptURL')).pathname === '/__hl/sw.js'
  328. && (await fetch(API + '/sw.js')).status === 404 && (await fetch(API + '/notes-offline.js')).status === 404, regs);
  329. const pageJs = await a.evaluate(`[...document.scripts].map(x => x.src ? new URL(x.src).pathname : 'inline').join(' ')`);
  330. check('no hand-written notes JavaScript on the page: only hl:web, ident and login.js (no md-editor.js: the Hybriel MdEditor block draws the editor)', !/notes-offline|\/sw\.js|md-editor/.test(pageJs), pageJs);
  331. check('mission 010: /md-editor.js is gone (404) and no <md-editor> custom element is defined — the block\'s <md-editor> is plain Hybriel', (await fetch(API + '/md-editor.js')).status === 404 && !(await a.evaluate(`!!customElements.get('md-editor')`)), pageJs);
  332. // ---- new note: heading and text; saved on the server ------------------------------------------------------
  333. await a.click('#newnote');
  334. await a.waitFor(`/^\\/note\\/l[0-9a-f]+$/.test(location.pathname)`, { label: 'the new note is open' });
  335. await a.waitForSelector('#notetext');
  336. await editorReady(a, 'editor on the new note');
  337. check('new note: opens on the right, the sidebar lists it as "Untitled note"', (await subjects(a)).join('|') === 'Untitled note' && await visible(a, 'note-list') && await visible(a, 'note-editor'), J(await subjects(a)));
  338. await mdClick(a, 'md-editor article');
  339. await mdType(a, '# Groceries');
  340. await mdPress(a, 'Enter');
  341. await mdType(a, 'milk and bread');
  342. await a.waitFor(`document.querySelector('#notes a').textContent === 'Groceries'`, { label: 'sidebar shows the heading as the subject' });
  343. const t1 = await taVal(a);
  344. check('editor: "# " became a heading, the textarea holds the Markdown', t1 === '# Groceries\n\nmilk and bread' || t1 === '# Groceries\nmilk and bread', J(t1));
  345. check('editor: the heading is formatted (h1 in the editor)', await a.evaluate(mdR(`!!r.querySelector('md-editor article h1')`)));
  346. let sn = await untilServer(cookieA, ns => ns.length === 1 && /^# Groceries/.test(ns[0].text) && /milk and bread$/.test(ns[0].text), 'Groceries');
  347. check('online: the note reached the server, which gave it its own id', /^[0-9a-z]{12}$/.test(sn[0].id), J(sn));
  348. await a.waitFor(`location.pathname === '/note/${sn[0].id}'`, { label: 'the address follows the server id' });
  349. const firstUrl = '/note/' + sn[0].id;
  350. await shot(a, 'desktop-one-note');
  351. // MD1 (components 7437e32): the note page comes with its text in server HTML. The moment the page is claimed (the surface has its listeners)
  352. // the editor must already show its text: on 5 fresh loads the longest wait from the claim to the text is at most 50 ms (the old 100 ms
  353. // animation left an empty editor on screen). No wait for editorReady.
  354. {
  355. const p2 = await newPage(a);
  356. const waits = [];
  357. try {
  358. for (const [w, h] of [[1280, 900], [390, 844]]) {
  359. waits.length = 0;
  360. await p2.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile: w < 600 });
  361. for (let run = 0; run < 5; run++) {
  362. p2.send('Page.navigate', { url: BASE + firstUrl + '?md1=' + run });
  363. let claimedAt = 0, textAt = 0;
  364. for (const t0 = Date.now(); Date.now() - t0 < 10000; ) {
  365. try {
  366. const r = await p2.send('Runtime.evaluate', { expression: "document.querySelector('#notetext md-editor article')" });
  367. if (!r.result || r.result.subtype !== 'node') { await sleep(2); continue; }
  368. const l = await p2.send('DOMDebugger.getEventListeners', { objectId: r.result.objectId });
  369. if (!claimedAt && l.listeners.length) claimedAt = Date.now();
  370. const tx = await p2.send('Runtime.evaluate', { expression: "(() => { const x = document.querySelector('#notetext md-editor article'); return !!x && x.textContent.includes('milk and bread'); })()", returnByValue: true });
  371. if (tx.result.value) { textAt = Date.now(); break; }
  372. } catch { /* the page is still navigating */ }
  373. await sleep(1);
  374. }
  375. waits.push(claimedAt && textAt ? textAt - claimedAt : 9999);
  376. }
  377. await shot(p2, 'md1-' + w);
  378. check(`MD1 at ${w} px: from the claim of the note page until its text is drawn, the editor waits at most 50 ms (5 loads)`, Math.max(...waits) <= 50, J(waits));
  379. }
  380. } finally { try { await p2.close(); } catch {} }
  381. }
  382. // ---- a second note; the edited one goes to the top ------------------------------------------------------------
  383. await a.click('#newnote');
  384. await a.waitFor(`/^\\/note\\/l/.test(location.pathname)`, { label: 'second note' });
  385. await a.waitFor(`document.getElementById('notetext') && document.querySelector('#notetext input[name=text]').value === ''`, { label: 'the second note is empty' });
  386. await editorReady(a, 'editor on the second note');
  387. await mdClick(a, 'md-editor article');
  388. await mdType(a, 'Zebra facts');
  389. await a.waitFor(`document.querySelector('#notes a').textContent === 'Zebra facts'`, { label: 'Zebra on top' });
  390. check('sidebar: two notes, the newest edited on top', (await subjects(a)).join('|') === 'Zebra facts|Groceries', J(await subjects(a)));
  391. await untilServer(cookieA, ns => ns.length === 2, 'two notes');
  392. await a.click(`#notes a[href="${firstUrl}"]`);
  393. await a.waitFor(`document.querySelector('#notetext input[name=text]').value.startsWith('# Groceries')`, { label: 'Groceries text loaded' });
  394. check('sidebar click: the note opens on the right with its text', location_ok(await a.evaluate('location.pathname'), firstUrl));
  395. function location_ok(x, y) { return x === y; }
  396. // ---- device B (another browser, same login) gets the notes -------------------------------------------------------
  397. const b = await newPage();
  398. globalThis.__debugPages.B = b;
  399. await viewport(b, 1280, 900);
  400. await identSignIn(b, '[email protected]');
  401. await b.goto(BASE + '/');
  402. await hydrated(b);
  403. await buttonLogin(b);
  404. await b.waitForSelector('#newnote', { timeout: 15000 });
  405. await b.waitFor(`document.querySelectorAll('#notes a').length === 2`, { label: 'device B pulled the notes' });
  406. check('second device: the same two notes appear after login', (await subjects(b)).join('|') === 'Zebra facts|Groceries', J(await subjects(b)));
  407. await b.goto(BASE + firstUrl);
  408. await b.waitForSelector('#notetext');
  409. await b.waitFor(`document.querySelector('#notetext input[name=text]').value.startsWith('# Groceries')`, { label: 'B opened Groceries by its address' });
  410. check('second device: a note address opens the note', true);
  411. const cookieB = await cookieOf(b);
  412. await shellKept(b);
  413. // ---- CHROME OFFLINE on A (notes#4): CDP cuts the page and its worker, then the page is RELOADED offline ---------------
  414. await setOffline(a, true);
  415. await a.goto(BASE + firstUrl);
  416. await booted(a, 'offline: the page boots from the worker');
  417. await a.waitForSelector('#notetext', { timeout: 20000 });
  418. await a.waitFor(`document.querySelector('#notetext input[name=text]').value.startsWith('# Groceries')`, { label: 'offline: the note opens from the browser copy' });
  419. check('offline: the page reloads with no network and shows the note and the list', (await subjects(a)).join('|') === 'Zebra facts|Groceries', J(await subjects(a)));
  420. check('chrome offline (new): the reload really is offline — the page booted from the worker and has no socket', !(await socketOpen(a)) && await a.evaluate('navigator.onLine === false'));
  421. await sleep(1500);
  422. check('chrome offline (new): the MdEditor block is there offline (it is in the page itself — no script file to keep)', await mdDefined(a), 'no md-editor article offline');
  423. await typeAtEnd(a, ' and eggs');
  424. await a.waitFor(`document.querySelector('#notes a').textContent === 'Groceries'`, { label: 'offline edit moves the note to the top' });
  425. await a.click('#newnote');
  426. await a.waitFor(`/^\\/note\\/l[0-9a-f]+$/.test(location.pathname)`, { label: 'offline: new note' });
  427. await a.waitFor(`document.getElementById('notetext') && document.querySelector('#notetext input[name=text]').value === ''`, { label: 'offline: the new note is empty' });
  428. await typeAtEnd(a, 'Written offline');
  429. await a.waitFor(`document.querySelector('#notes a').textContent === 'Written offline'`, { label: 'offline note in the list' });
  430. const saysOffline = await a.waitFor(`/Offline/.test((document.getElementById('syncstate') || {}).textContent || '')`, { label: 'the page says it is offline' }).then(() => true, () => false);
  431. check('offline: the sidebar says the changes are kept here', saysOffline, J(await txt(a, '#syncstate')));
  432. await sleep(2500);
  433. const waiting = await keptCopy(a);
  434. const onServer = (await serverNotes(cookieA)).map(n => n.text);
  435. check('chrome offline (new): the edit and the new note wait in the browser (hl:web queue) — the server has neither yet',
  436. waiting.queue >= 2 && /and eggs/.test(waiting.queueText) && /Written offline/.test(waiting.queueText) && !onServer.some(t => /and eggs|Written offline/.test(t)), J({ q: waiting.queue, onServer }));
  437. await a.goto(BASE + '/');
  438. await booted(a, 'offline / boots');
  439. await a.waitForSelector('#notes a');
  440. await a.waitFor(`/Offline/.test((document.getElementById('syncstate') || {}).textContent || '')`, { label: 'offline / says it is offline' });
  441. check('offline: a reload of / with no network opens the shell (header, brand, logout, the list) and says it is offline (mission 046)',
  442. (await txt(a, 'application-header .brand')) === 'notes' && await has(a, '#logout') && await has(a, 'note-list') && /Offline/.test(await txt(a, '#syncstate')));
  443. await viewport(a, 390, 844);
  444. await shot(a, 'pwa-phone-offline');
  445. await viewport(a, 1280, 900);
  446. check('offline: after another reload the offline edits are all there', (await subjects(a)).join('|') === 'Written offline|Groceries|Zebra facts', J(await subjects(a)));
  447. await a.click('#notes li:nth-child(2) a');
  448. await a.waitFor(`document.querySelector('#notetext input[name=text]').value.endsWith('milk and bread and eggs')`, { label: 'the offline edit is in the note' });
  449. check('offline: the edited text survived the reload', true);
  450. until('offline');
  451. // ---- back online: it reaches the server, and device B --------------------------------------------------------------
  452. await setOffline(a, false);
  453. sn = await untilServer(cookieA, ns => ns.length === 3 && ns.some(n => /milk and bread and eggs$/.test(n.text)) && ns.some(n => n.text === 'Written offline'), 'the offline edits');
  454. check('back online: the offline edit and the offline note reached the server', sn.filter(n => n.text === 'Written offline').length === 1, J(sn));
  455. await synced(a, 'A back online');
  456. await a.waitFor(`[...document.querySelectorAll('#notes a')].length === 3 && [...document.querySelectorAll('#notes a')].every(x => !/\\/note\\/l/.test(x.getAttribute('href')))`, { label: 'the offline note got a server id' });
  457. check('back online: the offline note now has a server id', true);
  458. await b.waitFor(`document.querySelectorAll('#notes a').length === 3`, { label: 'B got the offline note' });
  459. await b.waitFor(`document.querySelector('#notetext input[name=text]').value.endsWith('and eggs')`, { label: 'B shows the edit in the open note' });
  460. check('second device: sees the edit made offline on the first (open note refreshed) and the new note', (await subjects(b)).join('|') === 'Written offline|Groceries|Zebra facts', J(await subjects(b)));
  461. until('online');
  462. // ---- the same note edited on two devices while both are offline: nothing is lost -----------------------------------
  463. await b.click('#notes li:nth-child(3) a');
  464. await b.waitFor(`document.querySelector('#notetext input[name=text]').value === 'Zebra facts'`, { label: 'B opened Zebra' });
  465. await a.click('#notes li:nth-child(3) a');
  466. await a.waitFor(`document.querySelector('#notetext input[name=text]').value === 'Zebra facts'`, { label: 'A opened Zebra' });
  467. await stopServer();
  468. await typeAtEnd(a, ' on A');
  469. await sleep(1200);
  470. await typeAtEnd(b, ' on B');
  471. await sleep(300);
  472. startServer({ IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret });
  473. await serverUp();
  474. await synced(a, 'A after the outage');
  475. await synced(b, 'B after the outage');
  476. sn = await untilServer(cookieA, ns => ns.length === 4, 'the conflict copy');
  477. const texts = sn.map(n => n.text);
  478. check('conflict: the later edit (B) is the note, the other (A) is kept as a copy — nothing lost', texts.includes('Zebra facts on B') && texts.some(t => t.startsWith('Zebra facts on A') && /kept as a copy/.test(t)), J(texts));
  479. await a.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'A shows the copy' });
  480. await b.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'B shows the copy' });
  481. check('conflict: both devices end with the same four notes', (await subjects(a)).slice().sort().join('|') === (await subjects(b)).slice().sort().join('|'), J(await subjects(a)) + J(await subjects(b)));
  482. until('conflict');
  483. // mission 014 (hybriel#196): "Delete note" is pressed ONCE and the question must open and stay open >= 0.5 s. (Mission 012 pressed
  484. // again when it closed by itself; the cause was notes.hl open() setting `asking = false` only after the awaited flush(0) ack.)
  485. const openAsk = async (page, label) => {
  486. const shown = `document.querySelector('#deleteyes').getBoundingClientRect().width > 0`;
  487. await page.click('#delete');
  488. await page.waitFor(shown, { label: label + ' opens' });
  489. const t0 = Date.now();
  490. while (Date.now() - t0 < 500) {
  491. if (!(await page.evaluate(shown))) throw new Error('the delete question closed by itself within 0.5 s: ' + label);
  492. await sleep(50);
  493. }
  494. return 1;
  495. };
  496. // ---- delete on A reaches B -------------------------------------------------------------------------------------------------
  497. await a.click('#notes li:nth-child(1) a');
  498. await a.waitFor(`!!document.getElementById('notetext')`, { label: 'A opened a note to delete' });
  499. const doomed = await a.evaluate('document.querySelector("#notetext input[name=text]").value');
  500. check('delete: the question is hidden until "Delete note" is clicked', !(await visible(a, '#deleteyes')));
  501. await openAsk(a, 'delete question');
  502. await a.click('#deleteno');
  503. await a.waitFor(`document.querySelector('#deleteyes').getBoundingClientRect().width === 0`, { label: 'kept' });
  504. check('delete: "Keep" changes nothing', (await subjects(a)).length === 4);
  505. await openAsk(a, 'delete question again');
  506. await a.click('#deleteyes');
  507. await a.waitFor(`location.pathname === '/' && document.querySelectorAll('#notes a').length === 3`, { label: 'back to the list, one note less' });
  508. check('delete: the note is gone from the list and the page is the list again', await has(a, '#pick'));
  509. await untilServer(cookieA, ns => ns.length === 3 && !ns.some(n => n.text === doomed), 'the delete');
  510. await b.waitFor(`document.querySelectorAll('#notes a').length === 3`, { label: 'B follows the delete' });
  511. check('delete: the other device follows', true);
  512. until('delete');
  513. // ---- notes#15: a note MADE in this tab, typed, saved, then deleted leaves THIS tab's list at once (and stays gone) ------------
  514. // (its edit is keyed by the tab's own `l…` id; the delete used to remove only the edit keyed by the server id, so the edit laid
  515. // the note over the list again as soon as the server's list no longer held it)
  516. await a.goto(BASE + '/');
  517. await a.waitForSelector('#newnote');
  518. await hydrated(a);
  519. const before15 = (await subjects(a)).length;
  520. await a.click('#newnote');
  521. await a.waitFor(`/^\\/note\\/l/.test(location.pathname)`, { label: 'notes#15: new note' });
  522. await editorReady(a, 'notes#15: editor');
  523. await typeAtEnd(a, 'Doomed fifteen');
  524. await untilServer(cookieA, ns => ns.some(n => n.text === 'Doomed fifteen'), 'notes#15: saved');
  525. await synced(a, 'notes#15: saved');
  526. await a.waitFor(`[...document.querySelectorAll('#notes a')].some(x => x.textContent === 'Doomed fifteen')`, { label: 'notes#15: listed' });
  527. await b.waitFor(`[...document.querySelectorAll('#notes a')].some(x => x.textContent === 'Doomed fifteen')`, { label: 'notes#15: B lists it' });
  528. await a.click('#delete');
  529. await a.waitFor(`document.querySelector('#deleteyes').getBoundingClientRect().width > 0`, { label: 'notes#15: question' });
  530. await a.click('#deleteyes');
  531. await a.waitFor(`location.pathname === '/'`, { label: 'notes#15: back to the list' });
  532. await untilServer(cookieA, ns => !ns.some(n => n.text === 'Doomed fifteen'), 'notes#15: deleted on the server');
  533. await sleep(2500);
  534. check('notes#15: the deleted note (made in this tab) is gone from this tab\'s list, also 2.5 s after the server confirmed', !(await subjects(a)).includes('Doomed fifteen') && (await subjects(a)).length === before15, J(await subjects(a)));
  535. await b.waitFor(`![...document.querySelectorAll('#notes a')].some(x => x.textContent === 'Doomed fifteen')`, { label: 'notes#15: B follows' });
  536. check('notes#15: the other tab follows the delete too', (await subjects(b)).length === before15);
  537. until('notes15');
  538. // ---- NEW (notes#4): one device OFFLINE (Chrome, reloaded offline), the other online, the same note ----------------------
  539. const pickNote = async (page, subject) => {
  540. await page.evaluate(`[...document.querySelectorAll('#notes a')].find(x => x.textContent === ${J(subject)}).scrollIntoView()`);
  541. const i = await page.evaluate(`[...document.querySelectorAll('#notes a')].findIndex(x => x.textContent === ${J(subject)})`);
  542. await page.click(`#notes li:nth-child(${i + 1}) a`);
  543. };
  544. await pickNote(a, 'Written offline');
  545. await a.waitFor(`location.pathname.startsWith('/note/') && document.querySelector('#notetext input[name=text]').value === 'Written offline'`, { label: 'A opened "Written offline"' });
  546. const splitUrl = await a.evaluate('location.pathname');
  547. await setOffline(a, true);
  548. await a.goto(BASE + splitUrl);
  549. await booted(a, 'A offline again');
  550. await a.waitFor(`document.getElementById('notetext') && document.querySelector('#notetext input[name=text]').value === 'Written offline'`, { label: 'A offline: the note' });
  551. await typeAtEnd(a, ' / A offline');
  552. await a.waitFor(`document.querySelector('#notes a').textContent === 'Written offline / A offline'`, { label: 'A offline: typed' });
  553. await sleep(2000);
  554. await pickNote(b, 'Written offline');
  555. await b.waitFor(`document.querySelector('#notetext input[name=text]').value === 'Written offline'`, { label: 'B opened it' });
  556. await typeAtEnd(b, ' / B online');
  557. await untilServer(cookieA, ns => ns.some(n => n.text === 'Written offline / B online'), 'B online save');
  558. check('one offline (new): while A is offline, B\'s online edit reaches the server and A\'s does not',
  559. !(await serverNotes(cookieA)).some(n => /A offline/.test(n.text)) && (await keptCopy(a)).queue >= 1);
  560. await setOffline(a, false);
  561. sn = await untilServer(cookieA, ns => ns.length === 4, 'the copy of the offline edit');
  562. const split = sn.map(n => n.text);
  563. check('one offline (new): back online, the later edit (B) is the note and A\'s offline edit is kept as a copy — nothing lost',
  564. split.includes('Written offline / B online') && split.some(t => t.startsWith('Written offline / A offline') && /kept as a copy/.test(t)), J(split));
  565. await synced(a, 'A back after the split');
  566. await a.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'A shows the copy' });
  567. await b.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'B shows the copy' });
  568. await a.waitFor(`document.querySelector('#notetext input[name=text]').value === 'Written offline / B online'`, { label: 'A shows the winner in its editor' });
  569. check('one offline (new): both devices list the same four notes; A\'s editor now shows the winning text',
  570. (await subjects(a)).slice().sort().join('|') === (await subjects(b)).slice().sort().join('|'), J(await subjects(a)) + J(await subjects(b)));
  571. until('split');
  572. // ---- NEW (N1): TWO WRITERS on one note, both ways, by real keys: what B types must reach A as surely as A's reaches B ------------
  573. // (before the fix, tab A kept its own already-sent edit laid over the server's list, so B's text never showed in A)
  574. const twoPath = await a.evaluate('location.pathname');
  575. await b.goto(BASE + twoPath);
  576. await b.waitFor(`!!document.querySelector('#notetext md-editor article > *')`, { label: 'two writers: B opened the note' });
  577. await editorReady(a, 'two writers: A editor');
  578. const typeAt = async (page, mark) => { await mdClick(page, 'article'); await mdPress(page, 'End', CTRL); await mdType(page, mark); };
  579. let twoOk = true, twoWhy = '';
  580. for (let i = 1; i <= 3 && twoOk; i++) {
  581. for (const [src, dst, who, mark] of [[a, b, 'A', ` +a${i}`], [b, a, 'B', ` +b${i}`]]) {
  582. await typeAt(src, mark);
  583. try { await dst.waitFor(`document.querySelector('#notetext input[name=text]').value.endsWith(${J(mark)})`, { label: `two writers: ${who}'s ${mark} reaches the other tab`, timeout: 8000 }); }
  584. catch (e) { twoOk = false; twoWhy = `${who} typed ${mark}, the other tab shows …${(await taVal(dst)).slice(-30)}`; break; }
  585. }
  586. }
  587. check('two writers: text typed in tab B reaches tab A, and A\'s reaches B (3 rounds each way)', twoOk, twoWhy);
  588. await sleep(1500);
  589. const finalA = await taVal(a), finalB = await taVal(b);
  590. check('two writers: both tabs end with the same text holding every typed mark', finalA === finalB && [1, 2, 3].every(i => finalA.includes(` +a${i}`) && finalA.includes(` +b${i}`)), J(finalA.slice(-60)) + J(finalB.slice(-60)));
  591. await a.goto(BASE + twoPath);
  592. await editorReady(a, 'two writers: A reloaded');
  593. check('two writers: after a reload nothing is lost', (await taVal(a)).endsWith(' +b3') && (await taVal(a)).includes(' +a3'), J((await taVal(a)).slice(-40)));
  594. until('twowriters');
  595. // ---- somebody else sees nothing of it ----------------------------------------------------------------------------------------
  596. const bob = await newPage();
  597. await viewport(bob, 1280, 900);
  598. await identSignIn(bob, '[email protected]');
  599. await bob.goto(BASE + '/');
  600. await hydrated(bob);
  601. await buttonLogin(bob);
  602. await bob.waitForSelector('#newnote', { timeout: 15000 });
  603. await sleep(800);
  604. check('another user: an empty list', (await subjects(bob)).length === 0);
  605. const cookieBob = await cookieOf(bob);
  606. const alicePick = (await serverNotes(cookieA))[0];
  607. const aliceId = alicePick.id;
  608. check("another user: alice's note is not in bob's API", (await apiGet('/api/notes?id=' + aliceId, cookieBob)).status === 404 && (await apiGet('/api/notes', cookieBob)).json.notes.length === 0);
  609. await apiPost({ op: 'save', id: aliceId, local: '', text: 'hacked', base: 0, at: 1 }, cookieBob);
  610. await apiPost({ op: 'delete', id: aliceId, base: 0 }, cookieBob);
  611. check("another user: saving over / deleting alice's note does not touch it", (await serverNotes(cookieA)).some(n => n.id === aliceId && n.text === alicePick.text));
  612. check('a note over the size limit is refused, not cut', (await apiPost({ op: 'save', id: '', local: 'x1', text: 'x'.repeat(200001), base: 0, at: 1 }, cookieA)).status === 400);
  613. check('the API refuses invalid JSON and wrong fields with 400', (await apiPost('{nope', cookieA)).status === 400 && (await apiPost({ op: 'save', id: 5 }, cookieA)).status === 400 && (await apiPost({ op: 'zap' }, cookieA)).status === 400);
  614. // a retried push (the answer was lost) does not make a second note
  615. await apiPost({ op: 'save', id: '', local: 'lretry', text: 'retry me', base: 0, at: 5 }, cookieA);
  616. await apiPost({ op: 'save', id: '', local: 'lretry', text: 'retry me', base: 0, at: 5 }, cookieA);
  617. check('a push repeated after a lost answer makes no second note', (await serverNotes(cookieA)).filter(n => n.text === 'retry me').length === 1);
  618. // ---- MARKDOWN TABLES (notes#5): a table TYPED with real keys becomes a real <table>; a line with pipes stays text --------
  619. await a.goto(BASE + '/');
  620. await a.waitForSelector('#newnote');
  621. await hydrated(a); // the server-rendered button is clickable before the client mounts: that click is lost
  622. await a.click('#newnote');
  623. await a.waitFor(`/^\\/note\\/l/.test(location.pathname)`, { label: 'tables: new note' });
  624. await editorReady(a, 'tables: editor');
  625. await mdClick(a, 'md-editor article');
  626. await mdType(a, 'Shopping table');
  627. await mdPress(a, 'Enter');
  628. await mdType(a, 'a | b stays text');
  629. await mdPress(a, 'Enter');
  630. await mdType(a, '| Item | Qty | Note \\| x |');
  631. await mdPress(a, 'Enter');
  632. await mdType(a, '|:---|:---:|---:|');
  633. await mdPress(a, 'Enter');
  634. await mdType(a, '**milk**');
  635. await mdPress(a, 'Tab');
  636. await mdType(a, '`2`');
  637. await mdPress(a, 'Tab');
  638. await mdType(a, 'a|b');
  639. await mdPress(a, 'Enter');
  640. await mdType(a, 'bread');
  641. await mdPress(a, 'Tab');
  642. await mdType(a, '1');
  643. await mdPress(a, 'Tab');
  644. await mdType(a, 'Donaudampfschifffahrtsgesellschaftskapitaenswitwenrentenversicherung');
  645. await mdPress(a, 'Enter');
  646. await mdPress(a, 'Enter');
  647. await mdType(a, 'after the table');
  648. const tableOf = (page) => page.evaluate(mdR(`(() => {
  649. const t = r.querySelector('md-editor article table'); if (!t) return null;
  650. const cell = (c) => ({ text: c.textContent, html: c.innerHTML, align: c.getAttribute('data-align') || '', css: getComputedStyle(c).textAlign });
  651. return { head: [...t.querySelectorAll('thead th')].map(cell), rows: [...t.querySelectorAll('tbody tr')].map(tr => [...tr.children].map(cell)),
  652. ps: [...r.querySelectorAll('md-editor article > p')].map(p => p.textContent), order: [...r.querySelector('md-editor article').children].map(e => e.tagName).join(' ') };
  653. })()`));
  654. const tableOk = (t) => !!t && t.head.map(c => c.text).join('/') === 'Item/Qty/Note | x'
  655. && t.head.map(c => c.align + ':' + c.css).join(' ') === 'left:left center:center right:right'
  656. && t.rows.length === 2 && /^<strong>milk<\/strong>\u200b?$/.test(t.rows[0][0].html) && /^<code>2<\/code>\u200b?$/.test(t.rows[0][1].html) && t.rows[0][2].text === 'a|b'
  657. && t.rows[1].map(c => c.text).join('/').startsWith('bread/1/Donaudampf') && t.rows[1][1].css === 'center';
  658. await a.waitFor(`document.querySelector('#notetext input[name=text]').value.endsWith('after the table')`, { label: 'tables: typed to the end' });
  659. let tb = await tableOf(a);
  660. check('tables: typed header + delimiter + rows became a <table> (th, aligned left/center/right, bold + code cells, a typed pipe in a cell, \\| in the header)', tableOk(tb), J(tb));
  661. check('tables: the line with pipes stays a paragraph, text before and after the table too',
  662. !!tb && tb.ps.join('/') === 'Shopping table/a | b stays text/after the table' && tb.order === 'P P TABLE P', J(tb && [tb.ps, tb.order]));
  663. const md = await taVal(a);
  664. const mdLines = md.split('\n');
  665. const reparsed = mdLines.map(l => l === '' ? '' : l.startsWith('|') ? 'T' : 'p').join('').replace(/T+/g, 'T' + mdLines.filter(l => l.startsWith('|')).length);
  666. check('tables: the note is GitHub Markdown — pipe rows, `:---`/`:-:`/`--:`, escaped pipes, bold/code kept',
  667. /^\| Item +\| Qty +\| Note \\\| x +\|$/.test(mdLines.find(l => l.startsWith('| Item')) || '') && /^\| :-+ \| :-+: \| -+: \|$/.test(mdLines.find(l => /^\| :-/.test(l)) || '')
  668. && /\| \*\*milk\*\* +\| `2` +\| a\\\|b +\|/.test(md) && reparsed === 'ppT4p', J(md) + ' ' + reparsed);
  669. const tableNote = await untilServer(cookieA, ns => ns.some(n => n.text === md), 'the table note');
  670. const tableId = tableNote.find(n => n.text === md).id;
  671. await a.goto(BASE + '/note/' + tableId);
  672. await a.waitForSelector('#notetext');
  673. await editorReady(a, 'tables: reopened');
  674. await a.waitFor(mdR(`!!r.querySelector('md-editor article table')`), { label: 'tables: table after reload' });
  675. tb = await tableOf(a);
  676. check('tables: reopened from the server the note shows the same table, the text is unchanged', tableOk(tb) && (await taVal(a)) === md, J(tb));
  677. await viewport(a, 1280, 900);
  678. await shot(a, 'tables-desktop');
  679. await viewport(a, 390, 844);
  680. await sleep(300);
  681. const scroll = await a.evaluate(mdR(`(() => { const t = r.querySelector('md-editor article table'); const box = r.querySelector('md-editor article').getBoundingClientRect(); const q = t.getBoundingClientRect(); return { sw: t.scrollWidth, cw: t.clientWidth, inBox: q.right <= box.right + 1, ov: getComputedStyle(t).overflowX }; })()`));
  682. check('tables: on a phone the wide table scrolls inside its box, the page does not scroll sideways',
  683. scroll.sw > scroll.cw && scroll.inBox && /auto|scroll/.test(scroll.ov) && await noOverflow(a), J(scroll));
  684. await shot(a, 'tables-phone');
  685. const phoneEd = await a.evaluate(mdR(`(() => { const nav = r.querySelector('nav'); const bs = [...r.querySelectorAll('nav button')].map(x => x.getBoundingClientRect()); const q = r.getBoundingClientRect(); const tx = r.querySelector('article'); return { editorW: Math.round(q.width), viewW: innerWidth, small: bs.filter(x => x.width > 0 && (x.width < 43.5 || x.height < 43.5)).length, buttons: bs.length, fs: parseFloat(getComputedStyle(tx).fontSize), files: [...r.querySelectorAll('nav button')].some(x => /file/i.test(x.textContent) && x.getBoundingClientRect().width > 0) }; })()`));
  686. check('mission 010 (phone, 390): the editor fits the screen, every toolbar button is >= 44 px, the text is >= 16 px, no File button (files="off", the notes have no uploads)',
  687. phoneEd.editorW <= phoneEd.viewW && phoneEd.buttons > 0 && phoneEd.small === 0 && phoneEd.fs >= 16 && !phoneEd.files, J(phoneEd));
  688. await viewport(a, 1280, 900);
  689. // a cell edited in place: only that cell changes in the Markdown
  690. await mdClick(a, 'md-editor article tbody tr:first-child td:nth-child(2)');
  691. await mdPress(a, 'End');
  692. await mdType(a, '0');
  693. await a.waitFor(`document.querySelector('#notetext input[name=text]').value !== ${J(md)}`, { label: 'tables: cell edit' });
  694. const md2 = await taVal(a);
  695. const outside = (t) => t.split('\n').filter(l => !l.startsWith('|')).join('\n');
  696. const cellNow = (/\| \*\*milk\*\* +\| `(\d+)` +\|/.exec(md2) || [])[1] ? 'code:' + /\| \*\*milk\*\* +\| `(\d+)` +\|/.exec(md2)[1] : null;
  697. check('tables: typing in a cell changes that cell (`2` → `20`), the text around the table stays byte for byte', cellNow === 'code:20' && outside(md2) === outside(md) && md2.split('\n').filter(l => l.startsWith('|')).length === 4, J(md2));
  698. // offline: the table renders from the browser copy with the server gone
  699. await untilServer(cookieA, ns => ns.some(n => n.text === md2), 'the cell edit');
  700. await synced(a, 'tables: saved');
  701. await stopServer();
  702. await a.goto(BASE + '/note/' + tableId);
  703. await a.waitForSelector('#notetext', { timeout: 20000 });
  704. await a.waitFor(`document.querySelector('#notetext input[name=text]').value === ${J(md2)}`, { label: 'tables: offline text' });
  705. await sleep(1500);
  706. tb = null;
  707. if (await mdDefined(a)) {
  708. await editorReady(a, 'tables: offline');
  709. await a.waitFor(mdR(`!!r.querySelector('md-editor article table')`), { label: 'tables: offline table' });
  710. tb = await tableOf(a);
  711. }
  712. check('tables: offline (server stopped) the note opens from the browser copy with the table', !!tb && tb.rows.length === 2 && tb.rows[0][1].text === '20' && (await taVal(a)) === md2, tb ? J(tb) : 'no <md-editor> offline (Hybriel gap, report 007); the text itself is there: ' + ((await taVal(a)) === md2));
  713. startServer({ IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret });
  714. await serverUp();
  715. await synced(a, 'tables: after the outage');
  716. // ---- MT: the Table button, a pipe row typed into a cell, the table in the theme's look (caramboleyo 2026-10-24: "the notes apps markdown editor still does not support tables" / "i just see the text like | col | col |") ----
  717. const newNote = async (label) => {
  718. await a.goto(BASE + '/');
  719. await a.waitForSelector('#newnote');
  720. await hydrated(a);
  721. await a.click('#newnote');
  722. await a.waitFor(`/^\\/note\\/l/.test(location.pathname)`, { label: label + ': new note' });
  723. await editorReady(a, label + ': editor');
  724. };
  725. const cellsNow = (page) => page.evaluate(mdR(`(() => { const art = r.querySelector('md-editor article'); const t = art.querySelector('table'); if (!t) return null; return { head: [...t.querySelectorAll('thead th')].map(c => c.textContent), rows: [...t.querySelectorAll('tbody tr')].map(tr => [...tr.children].map(c => c.textContent)), order: [...art.children].map(e => e.tagName).join(' ') }; })()`));
  726. // (1) the toolbar's Table button, with a real tap at 390 px
  727. await newNote('mt button');
  728. await viewport(a, 390, 844);
  729. await mdClick(a, 'md-editor article');
  730. await mdType(a, 'Plan');
  731. await mdPress(a, 'Enter');
  732. const tbtn = await a.evaluate(mdR(`(() => { const b = r.querySelector('nav button.table'); if (!b) return null; const q = b.getBoundingClientRect(); const all = [...r.querySelectorAll('nav button')].filter(x => x.getBoundingClientRect().width > 0).map(x => Math.round(x.getBoundingClientRect().top)); return { w: Math.round(q.width), h: Math.round(q.height), label: b.getAttribute('aria-label'), svg: !!b.querySelector('svg path[d]'), rows: [...new Set(all)].length }; })()`));
  733. check('mt: the toolbar has a Table button (icon, label "Table"), a 44 px target at 390 px, the toolbar still two even rows', !!tbtn && tbtn.w >= 43.5 && tbtn.h >= 43.5 && tbtn.label === 'Table' && tbtn.svg && tbtn.rows === 2, J(tbtn));
  734. if (tbtn) {
  735. await mdClick(a, 'nav button.table');
  736. await sleep(200);
  737. await mdType(a, 'Item');
  738. await mdPress(a, 'Tab');
  739. await mdType(a, 'Qty');
  740. await mdPress(a, 'Tab');
  741. await mdType(a, 'milk');
  742. await mdPress(a, 'Tab');
  743. await mdType(a, '2');
  744. }
  745. await sleep(500);
  746. let tcells = await cellsNow(a);
  747. check('mt: the Table button puts a table into the editor under the paragraph; the caret is in its first header cell, so typing and Tab fill it', !!tcells && tcells.head.join('/') === 'Item/Qty' && tcells.rows.length === 1 && tcells.rows[0].join('/') === 'milk/2' && /^P TABLE/.test(tcells.order), J(tcells));
  748. if (tbtn) await a.waitFor(`/\\| Item +\\| Qty +\\|/.test(document.querySelector('#notetext input[name=text]').value)`, { label: 'mt: table text saved' }).catch(() => {});
  749. const mdBtn = await taVal(a);
  750. check('mt: the note text is the plain Markdown table (header, delimiter, row), "Plan" above it', /^Plan\n\n\| Item +\| Qty +\|\n\| -+ \| -+ \|\n\| milk +\| 2 +\|$/.test(mdBtn), J(mdBtn));
  751. await shot(a, 'mt-button-phone');
  752. // (2) a row typed with its pipes, the way the Markdown is written
  753. await newNote('mt rows');
  754. await viewport(a, 1280, 900);
  755. await mdClick(a, 'md-editor article');
  756. for (const line of ['| Item | Qty |', '| --- | --: |', '| milk | 2 |', '| bread | 1 |']) { await mdType(a, line); await mdPress(a, 'Enter'); }
  757. await mdPress(a, 'Enter');
  758. await mdType(a, 'after');
  759. await a.waitFor(`document.querySelector('#notetext input[name=text]').value.endsWith('after')`, { label: 'mt rows: typed' });
  760. tcells = await cellsNow(a);
  761. check('mt: typing "| milk | 2 |" and Enter in a table puts milk and 2 into the two cells (not the pipes into one cell), the next row follows', !!tcells && tcells.head.join('/') === 'Item/Qty' && tcells.rows.map(r => r.join('/')).join(' ') === 'milk/2 bread/1' && /TABLE P$/.test(tcells.order), J(tcells));
  762. const mdRows = await taVal(a);
  763. check('mt: the typed rows are saved as plain table rows, right-aligned Qty kept', /^\| Item +\| Qty +\|\n\| -+ \| -+: \|\n\| milk +\| 2 +\|\n\| bread +\| 1 +\|\n\nafter$/.test(mdRows), J(mdRows));
  764. // (3) the table looks like the theme's table: the same rules as a plain table of the page, no grid of its own
  765. const look = await a.evaluate(`(() => {
  766. const ref = document.createElement('table');
  767. ref.innerHTML = '<thead><tr><th>x</th></tr></thead><tbody><tr><td>a</td></tr><tr><td>b</td></tr></tbody>';
  768. document.body.appendChild(ref);
  769. const css = (el, ks) => Object.fromEntries(ks.map(k => [k, getComputedStyle(el)[k]]));
  770. const root = document.querySelector('#notetext md-editor');
  771. const t = root.querySelector('md-editor article table');
  772. const th = t.querySelector('th'), td = t.querySelector('tbody td'), td2 = t.querySelectorAll('tbody tr')[1].querySelector('td'), rtd = ref.querySelector('td'), rth = ref.querySelector('th'), rtd2 = ref.querySelectorAll('tbody tr')[1].querySelector('td');
  773. const out = {
  774. th: [css(th, ['color', 'fontWeight', 'paddingTop', 'paddingLeft', 'borderTopWidth', 'borderLeftWidth']), css(rth, ['color', 'fontWeight', 'paddingTop', 'paddingLeft', 'borderTopWidth', 'borderLeftWidth'])],
  775. td: [css(td, ['paddingTop', 'paddingLeft', 'borderTopWidth', 'borderLeftWidth', 'backgroundColor']), css(rtd, ['paddingTop', 'paddingLeft', 'borderTopWidth', 'borderLeftWidth', 'backgroundColor'])],
  776. row2: [getComputedStyle(td2.parentNode).backgroundColor, getComputedStyle(rtd2.parentNode).backgroundColor, getComputedStyle(td.parentNode).backgroundColor, getComputedStyle(rtd.parentNode).backgroundColor],
  777. };
  778. ref.remove();
  779. return out;
  780. })()`);
  781. const noBorder = (o) => { const { borderTopWidth, borderLeftWidth, ...rest } = o; return J(rest); };
  782. check('mt: the editor table is drawn by the theme — head colour, weight, padding and the striped rows are those of the theme\'s own table; the cell lines are 1 px (the notes theme\'s table rule, the component draws none)', noBorder(look.th[0]) === noBorder(look.th[1]) && noBorder(look.td[0]) === noBorder(look.td[1]) && look.row2[0] === look.row2[1] && look.row2[2] === look.row2[3] && look.td[0].borderTopWidth === '1px' && look.td[0].borderLeftWidth === '1px' && look.th[0].borderTopWidth === '1px' && look.td[1].borderTopWidth === '0px' && look.row2[2] !== look.row2[0], J(look));
  783. check('mt: the sidebar names the table note by its header words ("Item Qty"), not by the pipes', (await subjects(a))[0] === 'Item Qty', J(await subjects(a)));
  784. await shot(a, 'mt-rows-desktop');
  785. await viewport(a, 390, 844);
  786. await sleep(300);
  787. await shot(a, 'mt-rows-phone');
  788. check('mt: at 390 px the page does not scroll sideways with the table in it', await noOverflow(a));
  789. await viewport(a, 1280, 900);
  790. // ---- phone and desktop layout ----------------------------------------------------------------------------------------------------
  791. await a.goto(BASE + '/');
  792. await a.waitForSelector('#notes a');
  793. await hydrated(a); // the sidebar links are server-rendered too
  794. await viewport(a, 390, 844);
  795. check('phone: the list alone, no note', await visible(a, 'note-list') && !(await visible(a, 'note-reader')) && await noOverflow(a));
  796. await shot(a, 'phone-list');
  797. // MN (mobile audit): the list header stands on the 16 px gutter like the rows' text, not on the screen edge
  798. const hdr = await a.evaluate(`(() => { const h = document.querySelector('note-list h1').getBoundingClientRect(), b = document.querySelector('#newnote').getBoundingClientRect(), r = document.querySelector('#notes a').getBoundingClientRect(); return { h1: Math.round(h.left), btnGap: Math.round(innerWidth - b.right), rowText: Math.round(r.left + parseFloat(getComputedStyle(document.querySelector('#notes a')).paddingLeft)) }; })()`);
  799. check('MN phone list: "Notes" and "New note" stand on the 16 px gutter (same left edge as the row text, not 4 px from the screen edge)', hdr.h1 >= 14 && hdr.btnGap >= 14 && Math.abs(hdr.h1 - hdr.rowText) <= 2, J(hdr));
  800. await a.click('#notes a');
  801. await a.waitForSelector('#notetext');
  802. await editorReady(a, 'phone editor');
  803. check('phone: the opened note replaces the list, with a way back', !(await visible(a, 'note-list')) && await visible(a, 'note-editor') && await visible(a, '.back') && await noOverflow(a));
  804. await shot(a, 'phone-note');
  805. // MN: back link close to the editor; "Delete note" under the editor's edge; the delete question on its own line with two equal buttons
  806. const g1 = await a.evaluate(`(() => { const q = (x) => document.querySelector(x).getBoundingClientRect(); return { gap: Math.round(q('#notetext').top - q('a.back').bottom), delLeft: q('#delete').left, edLeft: q('#notetext').left, backLeft: q('a.back').left }; })()`);
  807. check('MN phone note: the gap between "All notes" and the editor is <= 20 px, "Delete note" button left edge = editor left edge = All notes left edge', g1.gap <= 20 && Math.abs(g1.delLeft - g1.edLeft) <= 1 && Math.abs(g1.backLeft - g1.edLeft) <= 1, J(g1));
  808. await a.click('#delete');
  809. await a.waitFor(`getComputedStyle(document.querySelector('#deleteask')).display !== 'none'`, { label: 'delete question open' });
  810. const g2 = await a.evaluate(`(() => { const q = (x) => document.querySelector(x).getBoundingClientRect(); const t = document.querySelector('#deleteask ask-text').getBoundingClientRect(); return { qLeft: t.left, edLeft: q('#notetext').left, edRight: q('#notetext').right, rowLeft: q('#deleteyes').left, rowRight: q('#deleteno').right, qBottom: Math.round(t.bottom), yesTop: Math.round(q('#deleteyes').top), noTop: Math.round(q('#deleteno').top), yesW: Math.round(q('#deleteyes').width), noW: Math.round(q('#deleteno').width), yesH: Math.round(q('#deleteyes').height), noH: Math.round(q('#deleteno').height) }; })()`);
  811. check('MN phone delete question: text on the editor edge, then Delete and Keep side by side, equal, >= 44 px, below the text',
  812. Math.abs(g2.qLeft - g2.edLeft) <= 1 && Math.abs(g2.rowLeft - g2.edLeft) <= 1 && Math.abs(g2.rowRight - g2.edRight) <= 1 && g2.yesTop >= g2.qBottom - 1 && Math.abs(g2.yesTop - g2.noTop) <= 1 && Math.abs(g2.yesW - g2.noW) <= 2 && g2.yesW >= 100 && g2.yesH >= 43 && g2.noH >= 43 && await noOverflow(a), J(g2));
  813. await shot(a, 'phone-delete-ask');
  814. await a.click('#deleteno');
  815. await a.waitFor(`getComputedStyle(document.querySelector('#deleteask')).display === 'none'`, { label: 'delete question closed' });
  816. await a.click('.back');
  817. await a.waitFor(`location.pathname === '/' && document.querySelector('note-list').getBoundingClientRect().width > 0`, { label: 'phone: back to the list' });
  818. check('phone: "All notes" brings the list back', await visible(a, 'note-list') && !(await visible(a, 'note-reader')));
  819. await viewport(a, 1280, 900);
  820. await a.click('#notes a');
  821. await editorReady(a, 'desktop editor');
  822. check('desktop: list and note side by side, no "All notes" link', await visible(a, 'note-list') && await visible(a, 'note-editor') && !(await visible(a, '.back')) && await noOverflow(a));
  823. await shot(a, 'desktop-two');
  824. // ---- KB (HL-STANDARD F5 + F21): keyboard use (Tab, Enter) and Back / Forward / reload / new tab on every address ------------------------
  825. // Real keys through CDP; the notes page has no <form> (New note and Delete are buttons, the editor is the MdEditor block), so Tab+Enter on
  826. // the main controls is: New note, the note list links, Delete / Keep, the editor surface.
  827. await viewport(a, 1280, 900);
  828. await a.goto(BASE + '/');
  829. await a.waitForSelector('#notes a');
  830. await hydrated(a);
  831. const focusNow = `(() => { const e = document.activeElement; if (!e || e === document.body) return ''; return e.id ? '#' + e.id : e.tagName.toLowerCase() + (e.getAttribute('href') ? '[' + e.getAttribute('href') + ']' : ''); })()`;
  832. // press Tab (or Shift+Tab) until the focused element satisfies `test` (a JS expression over `e`); returns the focus path or null
  833. async function tabTo(page, test, { max = 80, shift = false } = {}) {
  834. const path = [];
  835. for (let i = 0; i < max; i++) {
  836. await mdPress(page, 'Tab', shift ? 8 : 0);
  837. path.push(await page.evaluate(focusNow));
  838. if (await page.evaluate(`(() => { const e = document.activeElement; return !!e && e !== document.body && !!(${test}); })()`)) return path;
  839. }
  840. return null;
  841. }
  842. const stateOf = (page) => page.evaluate(`JSON.stringify({ path: location.pathname, current: [...document.querySelectorAll('#notes a[aria-current=page]')].map(x => x.getAttribute('href')), text: (document.querySelector('#notetext input[name=text]') || {}).value || null })`);
  843. const reloadPage = async (page) => {
  844. await page.evaluate('window.__kbMark = 1');
  845. await page.send('Page.reload');
  846. await page.waitFor('!window.__kbMark && document.readyState !== "loading" && !!document.querySelector("#notes a")', { label: 'KB: reloaded' })
  847. await hydrated(page);
  848. };
  849. const allHrefs = await a.evaluate(`[...document.querySelectorAll('#notes a')].map(x => x.getAttribute('href'))`);
  850. // the notes that have text (an empty "Untitled note" has no editor content to compare)
  851. const hrefs = await a.evaluate(`[...document.querySelectorAll('#notes a')].filter(x => x.textContent !== 'Untitled note').map(x => x.getAttribute('href'))`);
  852. check('KB setup: the list has at least 3 notes with text; every note link has a real address (href)', hrefs.length >= 3 && allHrefs.every(h => /^\/note\/[0-9a-z]+$/.test(h)), J(allHrefs));
  853. // Tab reaches New note, then every note link in list order, then Enter on a link opens that note
  854. const toNew = await tabTo(a, `e.id === 'newnote'`);
  855. check('KB Tab: from the top of the page Tab reaches "New note"', !!toNew, J(toNew));
  856. const seen = [];
  857. for (let i = 0; i < allHrefs.length; i++) { const p = await tabTo(a, `e.matches('#notes a')`, { max: 4 }); seen.push(p && p[p.length - 1]); }
  858. check('KB Tab: Tab then walks to every note link in list order (all links of the list)', J(seen) === J(allHrefs.map(h => 'a[' + h + ']')), J(seen));
  859. const shiftBack = await tabTo(a, `e.matches('#notes a')`, { max: 3, shift: true });
  860. check('KB Tab: Shift+Tab goes back to the previous note link', !!shiftBack && shiftBack[shiftBack.length - 1] === 'a[' + allHrefs[allHrefs.length - 2] + ']', J(shiftBack));
  861. await tabTo(a, `e.matches('#notes a')`, { max: 3 }); // the last link again
  862. // Enter on a link of the list: focus the 2nd link (Shift+Tab twice from the last when there are 3), press Enter
  863. const want = hrefs[1];
  864. while ((await a.evaluate(focusNow)) !== 'a[' + want + ']') { const p = await tabTo(a, `e.matches('#notes a')`, { max: 3, shift: true }); if (!p) break; }
  865. check('KB Enter: the 2nd note link has the keyboard focus', (await a.evaluate(focusNow)) === 'a[' + want + ']', await a.evaluate(focusNow));
  866. await mdPress(a, 'Enter');
  867. await a.waitFor(`location.pathname === ${J(want)} && !!document.querySelector('#notetext input[name=text]') && document.querySelector('#notetext input[name=text]').value !== ''`, { label: 'KB: Enter on a note link opened the note' }).catch(() => {})
  868. const opened = JSON.parse(await stateOf(a));
  869. if (!opened.text) opened.text = '';
  870. check('KB Enter: Enter on a note link opens that note (address, marked as current, its text in the editor)', opened.path === want && J(opened.current) === J([want]) && opened.text.length > 0, J(opened) + ' focus ' + await a.evaluate(focusNow));
  871. check('KB Enter: the focus stays on the link (the keyboard user is not thrown to the top)', (await a.evaluate(focusNow)) === 'a[' + want + ']', await a.evaluate(focusNow));
  872. // reload / new tab on the note address (Back / Forward: notes#13, add the checks back when it is fixed)
  873. await reloadPage(a);
  874. await editorReady(a, 'KB reload editor');
  875. const relState = JSON.parse(await stateOf(a));
  876. check('F5 reload: a reload of the note address shows the same note (address, current link, text)', relState.path === want && J(relState.current) === J([want]) && relState.text === opened.text, J(relState));
  877. const t2 = await newPage(a);
  878. await viewport(t2, 1280, 900);
  879. await t2.goto(BASE + want);
  880. await t2.waitForSelector('#notetext');
  881. await hydrated(t2);
  882. await t2.waitFor(`document.querySelector('#notetext input[name=text]').value !== ''`, { label: 'KB: new tab note text' }).catch(() => {})
  883. const tabState = JSON.parse(await stateOf(t2));
  884. check('F5 new tab: the note address opened in a new tab shows the same note', tabState.path === want && J(tabState.current) === J([want]) && tabState.text === opened.text, J(tabState));
  885. await t2.close();
  886. // the list address too: reload "/" shows the list with no note
  887. await a.goto(BASE + '/');
  888. await a.waitForSelector('#notes a');
  889. await hydrated(a);
  890. const listState = JSON.parse(await stateOf(a));
  891. check('F5 list address: "/" opened fresh shows the list and no open note', listState.path === '/' && listState.current.length === 0 && listState.text === null, J(listState));
  892. // buttons by keyboard: New note (Enter), Delete → Keep (Enter), the editor surface takes Tab focus and typed keys
  893. await a.goto(BASE + hrefs[0]);
  894. await a.waitForSelector('#notetext');
  895. await hydrated(a);
  896. await editorReady(a, 'KB editor');
  897. const toDel = await tabTo(a, `e.id === 'delete'`, { max: 120 });
  898. check('KB Tab: Tab reaches the "Delete note" button of the open note', !!toDel, J(toDel));
  899. await mdPress(a, 'Enter');
  900. await a.waitFor(`getComputedStyle(document.querySelector('#deleteask')).display !== 'none'`, { label: 'KB: Enter on Delete opened the question' }).catch(() => {});
  901. check('KB Enter: Enter on "Delete note" opens the question', await a.evaluate(`getComputedStyle(document.querySelector('#deleteask')).display !== 'none'`));
  902. const toKeep = await tabTo(a, `e.id === 'deleteno'`, { max: 4 });
  903. check('KB Tab: Tab goes on to Delete / Keep in the question', !!toKeep, J(toKeep));
  904. await mdPress(a, 'Enter');
  905. await a.waitFor(`getComputedStyle(document.querySelector('#deleteask')).display === 'none'`, { label: 'KB: Enter on Keep closed the question' }).catch(() => {});
  906. check('KB Enter: Enter on "Keep" closes the question and the note stays', await a.evaluate(`getComputedStyle(document.querySelector('#deleteask')).display === 'none'`) && (await a.evaluate('location.pathname')) === hrefs[0]);
  907. const listBefore = await a.evaluate(`[...document.querySelectorAll('#notes a')].map(x => x.getAttribute('href'))`);
  908. const toNote = await tabTo(a, `e.id === 'newnote'`, { max: 120, shift: true });
  909. check('KB Tab: Shift+Tab from the note goes back to "New note"', !!toNote, J(toNote));
  910. await mdPress(a, 'Enter');
  911. // the address may change from the provisional /note/l… to the saved id (settle()): accept either, but exactly one NEW note must be the selected one
  912. await a.waitFor(`location.pathname.startsWith('/note/') && ${J(listBefore)}.indexOf(location.pathname) < 0 && document.querySelectorAll('#notes a[aria-current=page]').length === 1 && document.querySelector('#notes a[aria-current=page]').getAttribute('href') === location.pathname`, { label: 'KB: Enter on New note selected one new note' }).catch(() => {});
  913. const made = await a.evaluate(`JSON.stringify({ path: location.pathname, list: [...document.querySelectorAll('#notes a')].map(x => x.getAttribute('href')), cur: [...document.querySelectorAll('#notes a[aria-current=page]')].map(x => x.getAttribute('href')) })`).then(JSON.parse);
  914. check('KB Enter: Enter on "New note" makes one new note and selects it (its address is /note/l… or the saved id)', /^\/note\/[0-9a-z]+$/.test(made.path) && !listBefore.includes(made.path) && made.list.length === listBefore.length + 1 && made.cur.length === 1 && made.cur[0] === made.path, J(made));
  915. await editorReady(a, 'KB new note editor');
  916. const toEd = await tabTo(a, `e.matches('#notetext md-editor article')`, { max: 120 });
  917. check('KB Tab: Tab reaches the editor surface of the open note', !!toEd, J(toEd));
  918. const before = await taVal(a);
  919. await mdType(a, 'Typed by keyboard');
  920. await a.waitFor(`document.querySelector('#notes a').textContent === 'Typed by keyboard'`, { label: 'KB: typed text in the list' }).catch(() => {});
  921. check('KB edit: keys typed into the focused editor change the note and its list entry', (await taVal(a)) === 'Typed by keyboard' && (await subjects(a))[0] === 'Typed by keyboard', J([before, await taVal(a), (await subjects(a))[0]]));
  922. // ---- log out: the browser forgets the notes ---------------------------------------------------------------------------------------
  923. // mission 011: Log out is in the theme's user menu (the icon at the header's right end opens it)
  924. await a.click('#logout');
  925. await a.waitForSelector('#loginhint');
  926. check('log out: the notes are gone from the page, the login hint shows', !(await has(a, '#notes')) && await has(a, '#loginhint'));
  927. await sleep(1500);
  928. const after = await keptCopy(a);
  929. const leak = (x) => /Groceries|milk and bread|Zebra facts|Written offline/.test(x);
  930. check("log out: this browser deleted its copy of the notes (hl:web's kept state, queue and kept documents)",
  931. !leak(after.state) && after.queue === 0 && !after.docs.some(d => leak(d.html)), J({ state: after.state.slice(0, 300), q: after.queue, docs: after.docs.map(d => d.path + (leak(d.html) ? ' LEAK' : '')) }));
  932. check('the server logged no error', !/error|Error/.test(log.replace(/error absorbed/g, '')), log.slice(-400));
  933. } catch (e) {
  934. if (process.env.NOTES_GATE_DEBUG) { for (const b of browsers) { try { for (const t of (await b.conn.send('Target.getTargets')).targetInfos.filter(t => t.type === 'page')) console.log('DEBUG page', t.url); } catch {} } }
  935. for (const [name, dp] of Object.entries(globalThis.__debugPages || {})) if (process.env.NOTES_GATE_DEBUG) { try { console.log('DEBUG ' + name, await dp.evaluate(`JSON.stringify({ path: location.pathname, hrefs: [...document.querySelectorAll('#notes a')].map(a => a.getAttribute('href') + ' ' + a.textContent), sock: window.__hl && window.__hl.socket && window.__hl.socket.readyState, sync: (document.getElementById('syncstate')||{}).textContent })`), JSON.stringify(await keptCopy(dp)).slice(0, 1500)); console.log(dp.dumpConsole().split('\n').filter(l => !/debug|ERR_INTERNET|ERR_FAILED/.test(l)).slice(-40).join('\n')); } catch (x) { console.log('debug failed', x); } }
  936. if (e && e.until) { console.log('---- ' + e.message + ' (NOTES_GATE_UNTIL)'); failures += 0; } else {
  937. console.log('FAIL gate crashed — ' + (e && e.stack || e));
  938. failures++;
  939. console.log(log.slice(-1500));
  940. }
  941. } finally {
  942. for (const b of browsers) { try { await b.close(); } catch {} }
  943. await stopServer();
  944. if (ident) await ident.stop();
  945. console.log(`${passes} passed, ${failures} failed`);
  946. process.exit(failures ? 1 : 0);
  947. }

Branches

Latest commits

  • 99ca1cf6Merge branch 'vendor-day56' into mainAtlas
  • 649cef37|||PR Vendor Hybriel day56Atlas
  • aadd0abcMerge branch 'hl-standard-2' into mainAtlas
  • 52ffac9f|||PR Keyboard and reload checks for the notes gate (HL-STANDARD F21, F5)Atlas
  • 617ee8c0Merge branch 'hl-standard' into mainAtlas
  • 452458ee|||PR Type the function parameters of notes' own .hl files (HL-STANDARD L10)Atlas
  • 23758cd6Re-vendor complete Hybriel plugins and runtime to day44mre
  • 5d7cc700Backup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre
  • 3e07b1cfVendor complete Hybriel day39 plugin sources and librariesmre
  • d7366702Check session cookie flags after login and assert anonymous GET stays cookielessmre
  • 16bc8fd8Re-vendor Hybriel day38b with the mpackdb store-open race fixmre
  • d860dc2dnotes#12: the markup names its own rules instead of hand-written class strings: the selected row is `aria-current="page"` (the list-first theme rule styles it, no class), the delete question is `Style.pAsk` and follows its own `open` attribute (bound to `asking`), the error line is `Style.pMessage` (body once in lib/looks.hl, rule in notes.hl, main.hl and loginfailed.hl). The CSS declarations are the same, only selectors changed (.ask -> p.ask, .ask.open -> p.ask[open], .message -> p.message); the pages look the same (AE 0 at 4 sizes). main.hl's selectorClass in/out stays (login.js reads it).mre
  • 2e7f8664notes#13: the list and back links pass the note key from the loop (emit pick(e, r.key)) instead of writing data-note into the View and reading it back with getAttribute; the two window.history.replaceState calls and the identcode e.target.value read stay (hl:web has no replace-navigation, a bound hidden input is not adopted on a script's change event), see NO13 reportmre
  • 4dc98282notes#15: a deleted note made in this tab leaves the list at once (the delete now removes this tab's edit under every key the row has: local id, server id); gate: browser.mjs notes#15 section, red on the old codemre
  • e4e7402fnotes#11: plain declarations instead of let for variables never reassigned (components/notes.hl 3, lib/jsoncheck.hl 5, lib/util.hl 2, tools/migrate-short-ids.hl 8)mre
  • 27b6a09enotes#8: Style blocks in the nested form (note-list, note-editor, .ask with their children nested, :empty as a nested pseudo-class); the same CSS rules, the pages look the samemre
  • 71a9538bnotes: B27W report, log linemre
  • 78ba0073notes: an ident access key (Authorization: Bearer idt_…) reads and writes its identity's notes through /api/me and /api/notes; gate tests/ident-access-notes.mjs (ident#27)mre
  • 3de46dacnotes: the sign-in callback keeps the session it finds and signs it in (same cookie, nothing signed out; ident#28); security gate 73+5 failing → 78 passedmre
  • 5909d458notes: MdEditor from components 59704ce (text on the clipboard always pastes, a file manager copy still attaches; pipe rows without a delimiter row; tickets#49, notes#5)mre