notes
All repositories: gitoria
52.1 KB
// tests/browser.mjs — THE GATE of notes.worldapi.org (tickets notes#1: sidebar + Markdown editor; notes#2: offline + sync;// notes#4: offline and sync in pure Hybriel — hl:web's own worker, kept state per user and queue; Chrome offline through CDP).// Its own notes server on its own storage, its OWN ident (a copy of ident's code without .env — codes go to a mail// sink, tests/identkit.mjs), real headless Chromes for everything visible. `*.notes.test` is mapped to 127.0.0.1// inside Chrome (--host-resolver-rules) so ident and the app are the same site, as on worldapi.org.//// node tests/browser.mjs (NOTES_GATE_PORT server, default 8702; NOTES_GATE_IDENT_PORT, default 8701;// NOTES_GATE_CHROME "8713-8719" = Chrome debug ports)// Screenshots (390 / 1280 px) land in .scratch/gate-*.png. Every process started is stopped by PID.// NOTES_GATE_SOFT=1 (old code only: waits do not stop the gate), NOTES_GATE_DEBUG=1 (a crash dumps both devices' state).// NOTES_GATE_UNTIL=<section> stops after that section (offline, outage, conflict, delete, …) while working on the gate.import { spawn } from 'node:child_process';import { rmSync, mkdirSync, writeFileSync, existsSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { launchBrowser } from './cdp.mjs';import { startIdent } from './identkit.mjs';if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';const HERE = dirname(fileURLToPath(import.meta.url));const APP = resolve(HERE, '..');const BIN = join(APP, 'bin/hybriel');const PORT = Number(process.env.NOTES_GATE_PORT || 8702);const IDENT_PORT = Number(process.env.NOTES_GATE_IDENT_PORT || 8701);const API = `http://127.0.0.1:${PORT}`;const BASE = `http://notes.test:${PORT}`;const IDENT_B = `http://ident.notes.test:${IDENT_PORT}`;const [CH_FROM, CH_TO] = (process.env.NOTES_GATE_CHROME || '8703-8709').split('-').map(Number);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)const SCRATCH = join(APP, '.scratch');const STORE = join(SCRATCH, 'gate-store');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')));rmSync(STORE, { recursive: true, force: true });mkdirSync(STORE, { recursive: true });let failures = 0, passes = 0;function check(label, ok, detail = '') {console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);if (ok) passes++; else failures++;}const sleep = (ms) => new Promise(r => setTimeout(r, ms));const J = JSON.stringify;let log = '';let server = null, ident = null;const browsers = [];function startServer(extraEnv = {}) {log += '\n==== notes server start\n';server = spawn(BIN, ['project.hl'], {cwd: APP,env: { ...process.env, NOTES_PORT: String(PORT), NOTES_STORAGE: join(STORE, 'mpackdb'), NOTES_SESSIONS: join(STORE, 'sessions') + '/', NOTES_WATCH: '0',NOTES_PUBLIC_URL: BASE, IDENT_URL: IDENT_B, IDENT_EXCHANGE_URL: ident.base, ...extraEnv },stdio: ['ignore', 'pipe', 'pipe'],});server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);}async function serverUp() {for (let i = 0; i < 480; i++) { try { const r = await fetch(API + '/'); if (r.ok) return; } catch {} await sleep(250); }throw new Error('notes did not come up\n' + log);}async function stopServer() {if (!server) return;try { server.kill('SIGTERM'); } catch {}await new Promise(r => { if (server.exitCode !== null || server.signalCode !== null) return r(); server.once('exit', r); setTimeout(r, 3000); });server = null;}const SLOW = Number(process.env.NOTES_GATE_SLOW || 3);// NOTES_GATE_SOFT=1: a wait that times out is logged and the gate goes on (the checks decide) — to run this gate against// OLD code and see which checks fail there; never for a real gate runconst SOFT = process.env.NOTES_GATE_SOFT === '1';function patient(page) {const waitFor = page.waitFor.bind(page);page.waitFor = (expr, o = {}) => SOFT? waitFor(expr, { ...o, timeout: o.timeout || 10000 }).catch((e) => { console.log('note (soft): ' + e.message); return false; }): waitFor(expr, { ...o, timeout: (o.timeout || 10000) * SLOW });const goto = page.goto.bind(page);page.goto = (url, o = {}) => goto(url, { ...o, timeout: (o.timeout || 15000) * SLOW });return page;}// a page of a NEW Chrome (own cookies), or — given `like` — another tab of the same Chrome (same login)async function newPage(like = null) {if (like) return patient(await like.__browser.newPage());const b = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });browsers.push(b);const p = patient(await b.newPage());p.__browser = b;return p;}async function viewport(page, width, height) {await page.send('Emulation.setDeviceMetricsOverride', { width, height, deviceScaleFactor: 1, mobile: width < 600 });await sleep(250);}async function shot(page, name) {await page.send('Page.bringToFront');const { data } = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true });writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64'));}const noOverflow = (page) => page.evaluate('document.documentElement.scrollWidth <= window.innerWidth');const hydrated = (page) => page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'page hydrated' });const txt = (page, sel) => page.evaluate(`(document.querySelector(${J(sel)}) || {}).textContent || null`);const has = (page, sel) => page.evaluate(`!!document.querySelector(${J(sel)})`);const subjects = (page) => page.evaluate(`[...document.querySelectorAll('#notes a')].map(a => a.textContent)`);const UNTIL = process.env.NOTES_GATE_UNTIL || '';const until = (name) => { if (UNTIL === name) throw Object.assign(new Error('stopped after ' + name), { until: true }); };const visible = (page, sel) => page.evaluate(`(() => { const e = document.querySelector(${J(sel)}); return !!e && e.getBoundingClientRect().width > 0; })()`);async function identSignIn(page, email) {await page.goto(IDENT_B + '/');await page.waitForSelector('#email');await hydrated(page);await page.type('#email', email);await page.click('#sendcode');await page.waitFor('/\\/code$/.test(location.pathname) && !!document.querySelector("#code")', { label: 'ident /code page' });await hydrated(page);await page.type('#code', ident.lastCode(email));await page.click('#verify');await page.waitForSelector('#signout', { timeout: 10000 });}// the login button of the page we are on → ident's "choose an identity" → backasync function buttonLogin(page) {await page.click('#loginbutton');await page.waitForSelector('#chooselist', { timeout: 10000 });await hydrated(page);await page.click('#chooselist li:nth-child(1) .choose');}// ---- REAL clicks and keys into the editor's shadow DOM (as in tickets' gate) ----------------------------const mdR = (expr) => `(() => { const r = document.querySelector('#notetext md-editor'); if (!r) return null; return (${expr}); })()`;const CTRL = 2;async function mdClick(page, sel) {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 }; })()`));if (!bx || !bx.w) throw new Error('mdClick: ' + sel + ' is not laid out');const x = Math.round(bx.x + bx.w / 2), y = Math.round(bx.y + bx.h / 2);for (const [type, buttons] of [['mouseMoved', 0], ['mousePressed', 1], ['mouseReleased', 0]]) await page.send('Input.dispatchMouseEvent', { type, x, y, button: 'left', clickCount: 1, buttons });await sleep(80);}async function mdPress(page, key, mods = 0) {const K = { Enter: [13, 'Enter', '\r'], End: [35, 'End'], Tab: [9, 'Tab'] }[key];const [vk, code, text] = K;const t = text && !(mods & CTRL) ? text : undefined;await page.send('Input.dispatchKeyEvent', { type: t ? 'keyDown' : 'rawKeyDown', modifiers: mods, key, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk, ...(t ? { text: t, unmodifiedText: t } : {}) });await page.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: mods, key, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk });await sleep(30);}async function mdType(page, text) {for (const ch of text) {await page.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch });await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });}await sleep(60);}const taVal = (page) => page.evaluate(`document.querySelector('#notetext input[name=text]').value`);// 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 surfaceconst editorReady = (page, label) => page.waitFor(mdR(`!!r.querySelector('md-editor article > *')`), { label });const emitFace = async (event, payload, cookie) => {const r = await fetch(API + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', ...(cookie ? { cookie } : {}) }, body: J({ t: 'emit', i: 1, event, payload }) });const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}return { status: r.status, raw: t, value: j && j.value };};// ---- CHROME OFFLINE (notes#4): CDP cuts the page AND its service worker. An open WebSocket survives the cut// (report 005), so every offline check first RELOADS offline: the page boots from hl:web's worker, no socket opens.async function workerSessions(page) {const conn = page.__browser.conn;page.__workers = page.__workers || new Map();const { targetInfos } = await conn.send('Target.getTargets');for (const t of targetInfos) {if (t.type === 'service_worker' && !page.__workers.has(t.targetId)) {const { sessionId } = await conn.send('Target.attachToTarget', { targetId: t.targetId, flatten: true });await conn.send('Network.enable', {}, sessionId);page.__workers.set(t.targetId, sessionId);}}return [...page.__workers.values()];}async function setOffline(page, off) {await page.setOffline(off);for (const s of await workerSessions(page)) await page.__browser.conn.send('Network.emulateNetworkConditions', { offline: off, latency: 0, downloadThroughput: -1, uploadThroughput: -1 }, s);}const socketOpen = (page) => page.evaluate('!!(window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1)');const booted = (page, label) => page.waitFor('!!window.__hl', { label });// what hl:web keeps in this browser (IndexedDB `hl-offline`: `state`, `queue`) and the worker's documentsconst keptCopy = (page) => page.evaluate(`(async () => {const dbs = (await indexedDB.databases()).map(d => d.name);// every database of this origin, every store (hl:web's \`hl-offline\` and anything else, e.g. the old notes-<user>)let state = [], queue = [];for (const name of dbs) {const db = await new Promise((ok, no) => { const r = indexedDB.open(name); r.onsuccess = () => ok(r.result); r.onerror = () => no(r.error); });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([]); } });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 }); }db.close();}const docs = [];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() }); } }return { dbs, state: JSON.stringify(state), queue: queue.length, queueText: JSON.stringify(queue), docs };})()`);// the editor: <md-editor>'s own surface when the element is defined, else the plain textarea it wraps — real keys either wayconst mdDefined = (page) => page.evaluate(`!!document.querySelector('#notetext md-editor article')`);async function typeAtEnd(page, text) {if (await mdDefined(page)) {await editorReady(page, 'editor');await mdClick(page, 'md-editor article');await mdPress(page, 'End', CTRL);} else {await page.click('#notetext');await mdPress(page, 'End', CTRL);}await mdType(page, text);}try {ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });const alice = await ident.signIn('[email protected]');await ident.signIn('[email protected]');const APPKEY = await ident.registerApp(alice, 'notes (gate)', [BASE]);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')));startServer({ IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret });await serverUp();// ---- signed out -------------------------------------------------------------------------------------let html = await (await fetch(API + '/')).text();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));// 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 failurefor (const pg of ['/', '/note/abc123def456', '/login/failed']) {const h = await (await fetch(API + pg)).text();const links = [...h.matchAll(/<a [^>]*href="\/"[^>]*>Notes/g)].map(m => m[0]);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));}let r = await fetch(API + '/login/callback', { redirect: 'manual' });check('login: /login/callback without a code → /login/failed', r.status === 302 && r.headers.get('location') === '/login/failed');r = await fetch(API + '/api/notes');check('signed out: the notes API answers 401', r.status === 401);r = await (await fetch(API + '/api/me')).json();check('signed out: /api/me says nobody', r.user === null, J(r));// ---- log in with ident (the button flow) on device A ----------------------------------------------------const a = await newPage();globalThis.__debugPages = { A: a };await viewport(a, 1280, 900);await identSignIn(a, '[email protected]');await a.goto(BASE + '/');await hydrated(a);check('signed out (browser): "Log in with ident" shows, no "New note"', await has(a, '#loginbutton') && !(await has(a, '#newnote')));await buttonLogin(a);await a.waitForSelector('#newnote', { timeout: 15000 });check('login: alice sees her (empty) list and "New note"', (await txt(a, '#empty')) !== null && (await subjects(a)).length === 0 && await has(a, '#logout'));const cookieOf = async (page) => (await page.cookies([BASE])).filter(c => c.name === 'notessid').map(c => 'notessid=' + c.value)[0];const cookieA = await cookieOf(a);const apiGet = async (path, cookie) => { const x = await fetch(API + path, { headers: { cookie } }); return { status: x.status, json: await x.json().catch(() => null) }; };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) }; };const serverNotes = async (cookie) => {const list = (await apiGet('/api/notes', cookie)).json.notes.filter(n => !n.gone);const out = [];for (const n of list) out.push({ ...n, text: (await apiGet('/api/notes?id=' + n.id, cookie)).json.text });return out;};const untilServer = async (cookie, pred, label) => {for (let i = 0; i < 80; i++) { const ns = await serverNotes(cookie); if (pred(ns)) return ns; await sleep(250); }throw new Error('server never showed: ' + label + ' ' + J(await serverNotes(cookie)));};// the page has synced when its socket is open and nothing waits in hl:web's queue (the replay is done)const synced = async (page, label) => {await page.waitFor('!!(window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1)', { label: label + ' (socket)', timeout: 20000 });for (let i = 0; i < 120; i++) { if ((await keptCopy(page)).queue === 0) return true; await sleep(250); }console.log('note: ' + label + ': the queue never emptied'); // the checks after this decidereturn false;};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(' '); })()`);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; };await a.waitFor('!!navigator.serviceWorker.controller', { label: 'page controlled by a service worker' });await shellKept(a);const kp = await keptPaths(a);check("offline: hl:web's worker keeps the page document and the shell (runtime, client half, stylesheet, page modules)",/(^| )\/( |$)/.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);// ---- THE INSTALLABLE APP (mission 046): hl:web's own manifest from project.hl appIcons, and since notes#4 its own// generated service worker too (`offline = [Notes]`): notes' /sw.js and /notes-offline.js are gone.const pwaHtml = await (await fetch(API + '/')).text();const mhref = (pwaHtml.match(/<link rel="manifest" href="([^"]+)"/) || [])[1];check('pwa: every page head links the manifest, the apple-touch-icon, the favicon and the theme colour (the header token `darker`)',mhref === '/__hl/manifest.webmanifest' && pwaHtml.includes('<link rel="apple-touch-icon" href="/icons/apple-touch-icon.png">')&& pwaHtml.includes('<link rel="icon" href="/icons/favicon.svg">') && pwaHtml.includes('<meta name="theme-color" content="rgb(15, 20, 25)">'), pwaHtml.slice(0, 900));const mres = await fetch(API + mhref);const man = await mres.json();check('pwa: the manifest is served as application/manifest+json: name "notes", start_url /, scope /, display standalone, the token colours',/manifest\+json/.test(mres.headers.get('content-type') || '') && man.name === 'notes' && man.short_name === 'notes' && man.start_url === '/' && man.scope === '/'&& man.display === 'standalone' && man.theme_color === 'rgb(15, 20, 25)' && man.background_color === 'rgb(25, 30, 35)', J(man));const iconOk = [];for (const ic of man.icons || []) {const ir = await fetch(API + ic.src);const buf = Buffer.from(await ir.arrayBuffer());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]));}check('pwa: every manifest icon loads and is a real PNG of its declared size (192 + 512, any + maskable)',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));const touch = await fetch(API + '/icons/apple-touch-icon.png');const touchBytes = Buffer.from(await touch.arrayBuffer());const fav = await fetch(API + '/icons/favicon.svg');const favText = await fav.text();const ico = await fetch(API + '/favicon.ico');const icoBytes = Buffer.from(await ico.arrayBuffer());check('pwa: apple-touch-icon is a 180×180 PNG, the favicon an SVG in notes yellow, /favicon.ico a real icon file',touch.ok && touchBytes.readUInt32BE(16) === 180 && fav.ok && /image\/svg\+xml/.test(fav.headers.get('content-type') || '') && favText.includes('#dcdcaa')&& ico.ok && icoBytes.readUInt32BE(0) === 0x00000100, `${touch.status} ${fav.status} ${ico.status}`);const am = await a.send('Page.getAppManifest');check('pwa: Chrome parses the manifest without errors', am.url && am.url.endsWith('/__hl/manifest.webmanifest') && (am.errors || []).length === 0, J(am.errors));const inst = await a.send('Page.getInstallabilityErrors');check('pwa: Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, J(inst));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(','))`);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)",regs === '/ /__hl/sw.js' && new URL(await a.evaluate('navigator.serviceWorker.controller.scriptURL')).pathname === '/__hl/sw.js'&& (await fetch(API + '/sw.js')).status === 404 && (await fetch(API + '/notes-offline.js')).status === 404, regs);const pageJs = await a.evaluate(`[...document.scripts].map(x => x.src ? new URL(x.src).pathname : 'inline').join(' ')`);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);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);// ---- new note: heading and text; saved on the server ------------------------------------------------------await a.click('#newnote');await a.waitFor(`/^\\/note\\/l[0-9a-f]+$/.test(location.pathname)`, { label: 'the new note is open' });await a.waitForSelector('#notetext');await editorReady(a, 'editor on the new note');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)));await mdClick(a, 'md-editor article');await mdType(a, '# Groceries');await mdPress(a, 'Enter');await mdType(a, 'milk and bread');await a.waitFor(`document.querySelector('#notes a').textContent === 'Groceries'`, { label: 'sidebar shows the heading as the subject' });const t1 = await taVal(a);check('editor: "# " became a heading, the textarea holds the Markdown', t1 === '# Groceries\n\nmilk and bread' || t1 === '# Groceries\nmilk and bread', J(t1));check('editor: the heading is formatted (h1 in the editor)', await a.evaluate(mdR(`!!r.querySelector('md-editor article h1')`)));let sn = await untilServer(cookieA, ns => ns.length === 1 && /^# Groceries/.test(ns[0].text) && /milk and bread$/.test(ns[0].text), 'Groceries');check('online: the note reached the server, which gave it its own id', /^[0-9a-z]{12}$/.test(sn[0].id), J(sn));await a.waitFor(`location.pathname === '/note/${sn[0].id}'`, { label: 'the address follows the server id' });const firstUrl = '/note/' + sn[0].id;await shot(a, 'desktop-one-note');// ---- a second note; the edited one goes to the top ------------------------------------------------------------await a.click('#newnote');await a.waitFor(`/^\\/note\\/l/.test(location.pathname)`, { label: 'second note' });await a.waitFor(`document.getElementById('notetext') && document.querySelector('#notetext input[name=text]').value === ''`, { label: 'the second note is empty' });await editorReady(a, 'editor on the second note');await mdClick(a, 'md-editor article');await mdType(a, 'Zebra facts');await a.waitFor(`document.querySelector('#notes a').textContent === 'Zebra facts'`, { label: 'Zebra on top' });check('sidebar: two notes, the newest edited on top', (await subjects(a)).join('|') === 'Zebra facts|Groceries', J(await subjects(a)));await untilServer(cookieA, ns => ns.length === 2, 'two notes');await a.click(`#notes a[href="${firstUrl}"]`);await a.waitFor(`document.querySelector('#notetext input[name=text]').value.startsWith('# Groceries')`, { label: 'Groceries text loaded' });check('sidebar click: the note opens on the right with its text', location_ok(await a.evaluate('location.pathname'), firstUrl));function location_ok(x, y) { return x === y; }// ---- device B (another browser, same login) gets the notes -------------------------------------------------------const b = await newPage();globalThis.__debugPages.B = b;await viewport(b, 1280, 900);await identSignIn(b, '[email protected]');await b.goto(BASE + '/');await hydrated(b);await buttonLogin(b);await b.waitForSelector('#newnote', { timeout: 15000 });await b.waitFor(`document.querySelectorAll('#notes a').length === 2`, { label: 'device B pulled the notes' });check('second device: the same two notes appear after login', (await subjects(b)).join('|') === 'Zebra facts|Groceries', J(await subjects(b)));await b.goto(BASE + firstUrl);await b.waitForSelector('#notetext');await b.waitFor(`document.querySelector('#notetext input[name=text]').value.startsWith('# Groceries')`, { label: 'B opened Groceries by its address' });check('second device: a note address opens the note', true);const cookieB = await cookieOf(b);await shellKept(b);// ---- CHROME OFFLINE on A (notes#4): CDP cuts the page and its worker, then the page is RELOADED offline ---------------await setOffline(a, true);await a.goto(BASE + firstUrl);await booted(a, 'offline: the page boots from the worker');await a.waitForSelector('#notetext', { timeout: 20000 });await a.waitFor(`document.querySelector('#notetext input[name=text]').value.startsWith('# Groceries')`, { label: 'offline: the note opens from the browser copy' });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)));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'));await sleep(1500);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');await typeAtEnd(a, ' and eggs');await a.waitFor(`document.querySelector('#notes a').textContent === 'Groceries'`, { label: 'offline edit moves the note to the top' });await a.click('#newnote');await a.waitFor(`/^\\/note\\/l[0-9a-f]+$/.test(location.pathname)`, { label: 'offline: new note' });await a.waitFor(`document.getElementById('notetext') && document.querySelector('#notetext input[name=text]').value === ''`, { label: 'offline: the new note is empty' });await typeAtEnd(a, 'Written offline');await a.waitFor(`document.querySelector('#notes a').textContent === 'Written offline'`, { label: 'offline note in the list' });const saysOffline = await a.waitFor(`/Offline/.test((document.getElementById('syncstate') || {}).textContent || '')`, { label: 'the page says it is offline' }).then(() => true, () => false);check('offline: the sidebar says the changes are kept here', saysOffline, J(await txt(a, '#syncstate')));await sleep(2500);const waiting = await keptCopy(a);const onServer = (await serverNotes(cookieA)).map(n => n.text);check('chrome offline (new): the edit and the new note wait in the browser (hl:web queue) — the server has neither yet',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 }));await a.goto(BASE + '/');await booted(a, 'offline / boots');await a.waitForSelector('#notes a');await a.waitFor(`/Offline/.test((document.getElementById('syncstate') || {}).textContent || '')`, { label: 'offline / says it is offline' });check('offline: a reload of / with no network opens the shell (header, brand, logout, the list) and says it is offline (mission 046)',(await txt(a, 'application-header .brand')) === 'notes' && await has(a, '#logout') && await has(a, 'note-list') && /Offline/.test(await txt(a, '#syncstate')));await viewport(a, 390, 844);await shot(a, 'pwa-phone-offline');await viewport(a, 1280, 900);check('offline: after another reload the offline edits are all there', (await subjects(a)).join('|') === 'Written offline|Groceries|Zebra facts', J(await subjects(a)));await a.click('#notes li:nth-child(2) a');await a.waitFor(`document.querySelector('#notetext input[name=text]').value.endsWith('milk and bread and eggs')`, { label: 'the offline edit is in the note' });check('offline: the edited text survived the reload', true);until('offline');// ---- back online: it reaches the server, and device B --------------------------------------------------------------await setOffline(a, false);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');check('back online: the offline edit and the offline note reached the server', sn.filter(n => n.text === 'Written offline').length === 1, J(sn));await synced(a, 'A back online');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' });check('back online: the offline note now has a server id', true);await b.waitFor(`document.querySelectorAll('#notes a').length === 3`, { label: 'B got the offline note' });await b.waitFor(`document.querySelector('#notetext input[name=text]').value.endsWith('and eggs')`, { label: 'B shows the edit in the open note' });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)));until('online');// ---- the same note edited on two devices while both are offline: nothing is lost -----------------------------------await b.click('#notes li:nth-child(3) a');await b.waitFor(`document.querySelector('#notetext input[name=text]').value === 'Zebra facts'`, { label: 'B opened Zebra' });await a.click('#notes li:nth-child(3) a');await a.waitFor(`document.querySelector('#notetext input[name=text]').value === 'Zebra facts'`, { label: 'A opened Zebra' });await stopServer();await typeAtEnd(a, ' on A');await sleep(1200);await typeAtEnd(b, ' on B');await sleep(300);startServer({ IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret });await serverUp();await synced(a, 'A after the outage');await synced(b, 'B after the outage');sn = await untilServer(cookieA, ns => ns.length === 4, 'the conflict copy');const texts = sn.map(n => n.text);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));await a.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'A shows the copy' });await b.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'B shows the copy' });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)));until('conflict');// mission 014 (hybriel#196): "Delete note" is pressed ONCE and the question must open and stay open >= 0.5 s. (Mission 012 pressed// again when it closed by itself; the cause was notes.hl open() setting `asking = false` only after the awaited flush(0) ack.)const openAsk = async (page, label) => {const shown = `document.querySelector('#deleteyes').getBoundingClientRect().width > 0`;await page.click('#delete');await page.waitFor(shown, { label: label + ' opens' });const t0 = Date.now();while (Date.now() - t0 < 500) {if (!(await page.evaluate(shown))) throw new Error('the delete question closed by itself within 0.5 s: ' + label);await sleep(50);}return 1;};// ---- delete on A reaches B -------------------------------------------------------------------------------------------------await a.click('#notes li:nth-child(1) a');await a.waitFor(`!!document.getElementById('notetext')`, { label: 'A opened a note to delete' });const doomed = await a.evaluate('document.querySelector("#notetext input[name=text]").value');check('delete: the question is hidden until "Delete note" is clicked', !(await visible(a, '#deleteyes')));await openAsk(a, 'delete question');await a.click('#deleteno');await a.waitFor(`document.querySelector('#deleteyes').getBoundingClientRect().width === 0`, { label: 'kept' });check('delete: "Keep" changes nothing', (await subjects(a)).length === 4);await openAsk(a, 'delete question again');await a.click('#deleteyes');await a.waitFor(`location.pathname === '/' && document.querySelectorAll('#notes a').length === 3`, { label: 'back to the list, one note less' });check('delete: the note is gone from the list and the page is the list again', await has(a, '#pick'));await untilServer(cookieA, ns => ns.length === 3 && !ns.some(n => n.text === doomed), 'the delete');await b.waitFor(`document.querySelectorAll('#notes a').length === 3`, { label: 'B follows the delete' });check('delete: the other device follows', true);until('delete');// ---- NEW (notes#4): one device OFFLINE (Chrome, reloaded offline), the other online, the same note ----------------------const pickNote = async (page, subject) => {await page.evaluate(`[...document.querySelectorAll('#notes a')].find(x => x.textContent === ${J(subject)}).scrollIntoView()`);const i = await page.evaluate(`[...document.querySelectorAll('#notes a')].findIndex(x => x.textContent === ${J(subject)})`);await page.click(`#notes li:nth-child(${i + 1}) a`);};await pickNote(a, 'Written offline');await a.waitFor(`location.pathname.startsWith('/note/') && document.querySelector('#notetext input[name=text]').value === 'Written offline'`, { label: 'A opened "Written offline"' });const splitUrl = await a.evaluate('location.pathname');await setOffline(a, true);await a.goto(BASE + splitUrl);await booted(a, 'A offline again');await a.waitFor(`document.getElementById('notetext') && document.querySelector('#notetext input[name=text]').value === 'Written offline'`, { label: 'A offline: the note' });await typeAtEnd(a, ' / A offline');await a.waitFor(`document.querySelector('#notes a').textContent === 'Written offline / A offline'`, { label: 'A offline: typed' });await sleep(2000);await pickNote(b, 'Written offline');await b.waitFor(`document.querySelector('#notetext input[name=text]').value === 'Written offline'`, { label: 'B opened it' });await typeAtEnd(b, ' / B online');await untilServer(cookieA, ns => ns.some(n => n.text === 'Written offline / B online'), 'B online save');check('one offline (new): while A is offline, B\'s online edit reaches the server and A\'s does not',!(await serverNotes(cookieA)).some(n => /A offline/.test(n.text)) && (await keptCopy(a)).queue >= 1);await setOffline(a, false);sn = await untilServer(cookieA, ns => ns.length === 4, 'the copy of the offline edit');const split = sn.map(n => n.text);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',split.includes('Written offline / B online') && split.some(t => t.startsWith('Written offline / A offline') && /kept as a copy/.test(t)), J(split));await synced(a, 'A back after the split');await a.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'A shows the copy' });await b.waitFor(`document.querySelectorAll('#notes a').length === 4`, { label: 'B shows the copy' });await a.waitFor(`document.querySelector('#notetext input[name=text]').value === 'Written offline / B online'`, { label: 'A shows the winner in its editor' });check('one offline (new): both devices list the same four notes; A\'s editor now shows the winning text',(await subjects(a)).slice().sort().join('|') === (await subjects(b)).slice().sort().join('|'), J(await subjects(a)) + J(await subjects(b)));until('split');// ---- 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 ------------// (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)const twoPath = await a.evaluate('location.pathname');await b.goto(BASE + twoPath);await b.waitFor(`!!document.querySelector('#notetext md-editor article > *')`, { label: 'two writers: B opened the note' });await editorReady(a, 'two writers: A editor');const typeAt = async (page, mark) => { await mdClick(page, 'article'); await mdPress(page, 'End', CTRL); await mdType(page, mark); };let twoOk = true, twoWhy = '';for (let i = 1; i <= 3 && twoOk; i++) {for (const [src, dst, who, mark] of [[a, b, 'A', ` +a${i}`], [b, a, 'B', ` +b${i}`]]) {await typeAt(src, mark);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 }); }catch (e) { twoOk = false; twoWhy = `${who} typed ${mark}, the other tab shows …${(await taVal(dst)).slice(-30)}`; break; }}}check('two writers: text typed in tab B reaches tab A, and A\'s reaches B (3 rounds each way)', twoOk, twoWhy);await sleep(1500);const finalA = await taVal(a), finalB = await taVal(b);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)));await a.goto(BASE + twoPath);await editorReady(a, 'two writers: A reloaded');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)));until('twowriters');// ---- somebody else sees nothing of it ----------------------------------------------------------------------------------------const bob = await newPage();await viewport(bob, 1280, 900);await identSignIn(bob, '[email protected]');await bob.goto(BASE + '/');await hydrated(bob);await buttonLogin(bob);await bob.waitForSelector('#newnote', { timeout: 15000 });await sleep(800);check('another user: an empty list', (await subjects(bob)).length === 0);const cookieBob = await cookieOf(bob);const alicePick = (await serverNotes(cookieA))[0];const aliceId = alicePick.id;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);await apiPost({ op: 'save', id: aliceId, local: '', text: 'hacked', base: 0, at: 1 }, cookieBob);await apiPost({ op: 'delete', id: aliceId, base: 0 }, cookieBob);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));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);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);// a retried push (the answer was lost) does not make a second noteawait apiPost({ op: 'save', id: '', local: 'lretry', text: 'retry me', base: 0, at: 5 }, cookieA);await apiPost({ op: 'save', id: '', local: 'lretry', text: 'retry me', base: 0, at: 5 }, cookieA);check('a push repeated after a lost answer makes no second note', (await serverNotes(cookieA)).filter(n => n.text === 'retry me').length === 1);// ---- MARKDOWN TABLES (notes#5): a table TYPED with real keys becomes a real <table>; a line with pipes stays text --------await a.goto(BASE + '/');await a.waitForSelector('#newnote');await hydrated(a); // the server-rendered button is clickable before the client mounts: that click is lostawait a.click('#newnote');await a.waitFor(`/^\\/note\\/l/.test(location.pathname)`, { label: 'tables: new note' });await editorReady(a, 'tables: editor');await mdClick(a, 'md-editor article');await mdType(a, 'Shopping table');await mdPress(a, 'Enter');await mdType(a, 'a | b stays text');await mdPress(a, 'Enter');await mdType(a, '| Item | Qty | Note \\| x |');await mdPress(a, 'Enter');await mdType(a, '|:---|:---:|---:|');await mdPress(a, 'Enter');await mdType(a, '**milk**');await mdPress(a, 'Tab');await mdType(a, '`2`');await mdPress(a, 'Tab');await mdType(a, 'a|b');await mdPress(a, 'Enter');await mdType(a, 'bread');await mdPress(a, 'Tab');await mdType(a, '1');await mdPress(a, 'Tab');await mdType(a, 'Donaudampfschifffahrtsgesellschaftskapitaenswitwenrentenversicherung');await mdPress(a, 'Enter');await mdPress(a, 'Enter');await mdType(a, 'after the table');const tableOf = (page) => page.evaluate(mdR(`(() => {const t = r.querySelector('md-editor article table'); if (!t) return null;const cell = (c) => ({ text: c.textContent, html: c.innerHTML, align: c.getAttribute('data-align') || '', css: getComputedStyle(c).textAlign });return { head: [...t.querySelectorAll('thead th')].map(cell), rows: [...t.querySelectorAll('tbody tr')].map(tr => [...tr.children].map(cell)),ps: [...r.querySelectorAll('md-editor article > p')].map(p => p.textContent), order: [...r.querySelector('md-editor article').children].map(e => e.tagName).join(' ') };})()`));const tableOk = (t) => !!t && t.head.map(c => c.text).join('/') === 'Item/Qty/Note | x'&& t.head.map(c => c.align + ':' + c.css).join(' ') === 'left:left center:center right:right'&& 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'&& t.rows[1].map(c => c.text).join('/').startsWith('bread/1/Donaudampf') && t.rows[1][1].css === 'center';await a.waitFor(`document.querySelector('#notetext input[name=text]').value.endsWith('after the table')`, { label: 'tables: typed to the end' });let tb = await tableOf(a);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));check('tables: the line with pipes stays a paragraph, text before and after the table too',!!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]));const md = await taVal(a);const mdLines = md.split('\n');const reparsed = mdLines.map(l => l === '' ? '' : l.startsWith('|') ? 'T' : 'p').join('').replace(/T+/g, 'T' + mdLines.filter(l => l.startsWith('|')).length);check('tables: the note is GitHub Markdown — pipe rows, `:---`/`:-:`/`--:`, escaped pipes, bold/code kept',/^\| Item +\| Qty +\| Note \\\| x +\|$/.test(mdLines.find(l => l.startsWith('| Item')) || '') && /^\| :-+ \| :-+: \| -+: \|$/.test(mdLines.find(l => /^\| :-/.test(l)) || '')&& /\| \*\*milk\*\* +\| `2` +\| a\\\|b +\|/.test(md) && reparsed === 'ppT4p', J(md) + ' ' + reparsed);const tableNote = await untilServer(cookieA, ns => ns.some(n => n.text === md), 'the table note');const tableId = tableNote.find(n => n.text === md).id;await a.goto(BASE + '/note/' + tableId);await a.waitForSelector('#notetext');await editorReady(a, 'tables: reopened');await a.waitFor(mdR(`!!r.querySelector('md-editor article table')`), { label: 'tables: table after reload' });tb = await tableOf(a);check('tables: reopened from the server the note shows the same table, the text is unchanged', tableOk(tb) && (await taVal(a)) === md, J(tb));await viewport(a, 1280, 900);await shot(a, 'tables-desktop');await viewport(a, 390, 844);await sleep(300);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 }; })()`));check('tables: on a phone the wide table scrolls inside its box, the page does not scroll sideways',scroll.sw > scroll.cw && scroll.inBox && /auto|scroll/.test(scroll.ov) && await noOverflow(a), J(scroll));await shot(a, 'tables-phone');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) }; })()`));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)',phoneEd.editorW <= phoneEd.viewW && phoneEd.buttons > 0 && phoneEd.small === 0 && phoneEd.fs >= 16 && !phoneEd.files, J(phoneEd));await viewport(a, 1280, 900);// a cell edited in place: only that cell changes in the Markdownawait mdClick(a, 'md-editor article tbody tr:first-child td:nth-child(2)');await mdPress(a, 'End');await mdType(a, '0');await a.waitFor(`document.querySelector('#notetext input[name=text]').value !== ${J(md)}`, { label: 'tables: cell edit' });const md2 = await taVal(a);const outside = (t) => t.split('\n').filter(l => !l.startsWith('|')).join('\n');const cellNow = (/\| \*\*milk\*\* +\| `(\d+)` +\|/.exec(md2) || [])[1] ? 'code:' + /\| \*\*milk\*\* +\| `(\d+)` +\|/.exec(md2)[1] : null;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));// offline: the table renders from the browser copy with the server goneawait untilServer(cookieA, ns => ns.some(n => n.text === md2), 'the cell edit');await synced(a, 'tables: saved');await stopServer();await a.goto(BASE + '/note/' + tableId);await a.waitForSelector('#notetext', { timeout: 20000 });await a.waitFor(`document.querySelector('#notetext input[name=text]').value === ${J(md2)}`, { label: 'tables: offline text' });await sleep(1500);tb = null;if (await mdDefined(a)) {await editorReady(a, 'tables: offline');await a.waitFor(mdR(`!!r.querySelector('md-editor article table')`), { label: 'tables: offline table' });tb = await tableOf(a);}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));startServer({ IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret });await serverUp();await synced(a, 'tables: after the outage');// ---- phone and desktop layout ----------------------------------------------------------------------------------------------------await a.goto(BASE + '/');await a.waitForSelector('#notes a');await hydrated(a); // the sidebar links are server-rendered tooawait viewport(a, 390, 844);check('phone: the list alone, no note', await visible(a, 'note-list') && !(await visible(a, 'note-reader')) && await noOverflow(a));await shot(a, 'phone-list');await a.click('#notes a');await a.waitForSelector('#notetext');await editorReady(a, 'phone editor');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));await shot(a, 'phone-note');await a.click('.back');await a.waitFor(`location.pathname === '/' && document.querySelector('note-list').getBoundingClientRect().width > 0`, { label: 'phone: back to the list' });check('phone: "All notes" brings the list back', await visible(a, 'note-list') && !(await visible(a, 'note-reader')));await viewport(a, 1280, 900);await a.click('#notes a');await editorReady(a, 'desktop editor');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));await shot(a, 'desktop-two');// ---- log out: the browser forgets the notes ---------------------------------------------------------------------------------------// mission 011: Log out is in the theme's user menu (the icon at the header's right end opens it)await a.click('button.user-toggle');await a.waitFor(`document.querySelector('#user-menu').matches(':popover-open')`, { label: 'user menu open' });await a.click('#logout');await a.waitForSelector('#loginhint');check('log out: the notes are gone from the page, the login hint shows', !(await has(a, '#notes')) && await has(a, '#loginbutton'));await sleep(1500);const after = await keptCopy(a);const leak = (x) => /Groceries|milk and bread|Zebra facts|Written offline/.test(x);check("log out: this browser deleted its copy of the notes (hl:web's kept state, queue and kept documents)",!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' : '')) }));check('the server logged no error', !/error|Error/.test(log.replace(/error absorbed/g, '')), log.slice(-400));} catch (e) {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 {} } }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); } }if (e && e.until) { console.log('---- ' + e.message + ' (NOTES_GATE_UNTIL)'); failures += 0; } else {console.log('FAIL gate crashed — ' + (e && e.stack || e));failures++;console.log(log.slice(-1500));}} finally {for (const b of browsers) { try { await b.close(); } catch {} }await stopServer();if (ident) await ident.stop();console.log(`${passes} passed, ${failures} failed`);process.exit(failures ? 1 : 0);}
Branches
Latest commits
- 90c73ed3notes mobile: back link gapmre
- 72bd4f83notes mobile: list header on the gutter, delete confirmation as a question + two equal buttons, Delete note under the editor edgemre
- ba1e73f8notes: a sent edit is done once the server's version is not older, so a second writer's text shows in the first tab; gate: two writers both waysmre
- c69ef9ebsync components.hybriel 134b4e3: MdEditor builds an editor put into the page at once, redraws a surface put in anew (F5, hybriel#211)mre
- 2eb783f5sync components 9a: shared Icon (icons/icons.hl), md-editor toolbar icons + single focus ring (components f4-icons ba96735)mre
- 4dd46dadsync-components: copy icons/icons.hl + README (F4); testsmre
- c92e4a0ftests/e2e-outside.mjs: real-Chrome E2E, a note pushed from another device while open, then typingmre
- 0516b4ccmd-editor.hl: verbatim copy of components f3-mdvalue (an older text handed back is kept)mre
- 38cc11ecmd-editor.hl: verbatim copy of components f3-mdvalue (an outside value change is shown by the editor)mre
- 3e7e79f5reports/H1-hydrate.mdmre
- d98775e8tests/browser.mjs: wait for hydration before the clicks after a goto('/') (tables new note, phone sidebar)mre
- 1f3198b6tests/cdp.mjs: HL_CPU_THROTTLE=<rate> optional CPU throttling for gate runsmre
- 39cf9fdfre-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
- db07aa84tests: short-id-switch ports from env (NOTES_SWITCH_IDENT_PORT/_PORT), defaults unchangedmre
- ef9f9feere-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
- 5485467cdocker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
- 86ea4a85deploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
- edeab20fnotes mission 015: mission, report, LOG, STATUSmre
- 542a0383notes mission 015: e2e-chrome E2E_HOST (own cookie jar in the shared Chrome)mre
- 8b30f510notes mission 015: main-menu from layouts 0bcc629, current = true kept (route marks only /), server-HTML marker checksmre