gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitfd36da27fd36da27notes mission 010: the note editor is the Hybriel MdEditor block (components.hybriel 1442e58, verbatim); md-editor.js, its route, script tag and offlineFiles retired; gate 66/0, realdata-offline 12/0, round-trip and Chrome E2E tests; report 010mrefd36da27/tests/e2e-chrome.mjs

14.8 KB

  1. // tests/e2e-chrome.mjs (mission 010): END TO END in a REAL, already-running Chrome (lisbeth's LLM test Chrome through an ssh
  2. // tunnel), real mouse clicks and key events only, on a COPY of a deploy backup (a session of the creator is written into the copy).
  3. // node tests/e2e-chrome.mjs <label> <backup.tgz> <app-port> <cdp-port> <shots-dir>
  4. // <app-port> is also the port of a REVERSE forward on lisbeth (ssh -R <app-port>:127.0.0.1:<app-port>), so Chrome there reaches
  5. // http://127.0.0.1:<app-port>; <cdp-port> is the local end of ssh -L <cdp-port>:127.0.0.1:9223 lisbeth. ONE existing about:blank tab
  6. // is navigated (never /json/new, no clipboard); it is put back to about:blank at the end.
  7. // At 390 and 1280 px: open the list, New note, type a heading, text, bold (Ctrl+B), a list and a table with real keys, wait for
  8. // the save, RELOAD (the text is back), go OFFLINE (Network.emulateNetworkConditions, page and worker), reload offline, the list
  9. // and the note open, type more offline, back online → the server has it. Works on the old editor (md-editor.js) and the block.
  10. import { spawn, execFileSync } from 'node:child_process';
  11. import { writeFileSync, mkdirSync, rmSync, existsSync } from 'node:fs';
  12. import { createHash, randomBytes } from 'node:crypto';
  13. import { join, resolve, dirname } from 'node:path';
  14. import { fileURLToPath } from 'node:url';
  15. const [LABEL, tgz, portArg, cdpArg, shots] = process.argv.slice(2);
  16. const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');
  17. const PORT = Number(portArg), CDP = Number(cdpArg);
  18. const BASE = `http://127.0.0.1:${PORT}`, API = BASE;
  19. const W = join(APP, '.scratch/e2e-chrome-' + LABEL);
  20. const USER = '0muh6o5a3kkd';
  21. rmSync(W, { recursive: true, force: true });
  22. mkdirSync(join(W, 'data'), { recursive: true }); mkdirSync(join(W, 'sessions'), { recursive: true }); mkdirSync(shots, { recursive: true });
  23. execFileSync('tar', ['-xzf', resolve(tgz), '-C', join(W, 'data'), 'storage/mpackdb']);
  24. const sid = randomBytes(16).toString('hex'), now = Date.now();
  25. writeFileSync(join(W, 'sessions', createHash('sha256').update(sid).digest('hex')),
  26. JSON.stringify({ created: now, data: { tag: 'e2e' }, handled: [], id: sid, seen: now, user: { id: USER } }), { mode: 0o600 });
  27. let failures = 0, passes = 0;
  28. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} [${LABEL}] ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };
  29. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  30. const J = JSON.stringify;
  31. let log = '';
  32. const srv = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  33. env: { ...process.env, NOTES_PORT: String(PORT), NOTES_PUBLIC_URL: BASE, NOTES_STORAGE: join(W, 'data/storage/mpackdb'),
  34. NOTES_SESSIONS: join(W, 'sessions') + '/', NOTES_WATCH: '0', IDENT_URL: 'http://ident.test', IDENT_API_KEY: 'pk_e2e', IDENT_API_SECRET: 'sk_e2e' } });
  35. srv.stdout.on('data', d => log += d); srv.stderr.on('data', d => log += d);
  36. console.log('server pid', srv.pid);
  37. // ---- a tiny CDP client (one existing tab + the browser socket for the service workers) ----
  38. function connect(url) {
  39. return new Promise((ok, no) => {
  40. const ws = new WebSocket(url); let n = 0; const pend = new Map(); const handlers = [];
  41. ws.addEventListener('message', (m) => { const d = JSON.parse(m.data); if (d.id && pend.has(d.id)) { const p = pend.get(d.id); pend.delete(d.id); d.error ? p.no(new Error(d.error.message)) : p.ok(d.result); } else handlers.forEach(h => h(d)); });
  42. ws.addEventListener('open', () => ok({ ws, on: (h) => handlers.push(h), send: (method, params = {}, sessionId) => new Promise((ok2, no2) => { const id = ++n; pend.set(id, { ok: ok2, no: no2 }); ws.send(J({ id, method, params, ...(sessionId ? { sessionId } : {}) })); }) }));
  43. ws.addEventListener('error', () => no(new Error('ws error ' + url)));
  44. });
  45. }
  46. const get = async (path) => (await fetch(`http://127.0.0.1:${CDP}${path}`)).json();
  47. const api = async (path) => (await fetch(API + path, { headers: { cookie: 'notessid=' + sid } })).json();
  48. const alive = async () => { const out = []; for (const n of (await api('/api/notes')).notes.filter(n => !n.gone)) out.push({ ...n, text: (await api('/api/notes?id=' + n.id)).text }); return out; };
  49. let page = null, browser = null, tabUrlBefore = null;
  50. const ev = async (expr) => { const r = await page.send('Runtime.evaluate', { expression: expr, returnByValue: true, awaitPromise: true }); if (r.exceptionDetails) throw new Error('evaluate: ' + (r.exceptionDetails.exception && r.exceptionDetails.exception.description || r.exceptionDetails.text)); return r.result.value; };
  51. const waitFor = async (expr, label, timeout = 40000) => { const t0 = Date.now(); for (;;) { let v = false; try { v = await ev(expr); } catch {} if (v) return v; if (Date.now() - t0 > timeout) { let d = ''; try { d = await ev(`JSON.stringify({ path: location.pathname, hl: !!window.__hl, nt: !!document.getElementById('notetext'), md: !!document.querySelector('md-editor'), art: !!document.querySelector('md-editor article'), kids: document.querySelector('md-editor article') ? document.querySelector('md-editor article').children.length : -1, body: document.body.innerText.slice(0, 120) })`); } catch (e) { d = String(e); } throw new Error('timeout: ' + label + ' ' + d); } await sleep(100); } };
  52. const shot = async (name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(shots, `${LABEL}-${name}.png`), Buffer.from(data, 'base64')); };
  53. const size = async (w, h) => { await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile: w < 600 }); await sleep(400); };
  54. const click = async (x, y) => { for (const [type, buttons] of [['mouseMoved', 0], ['mousePressed', 1], ['mouseReleased', 0]]) await page.send('Input.dispatchMouseEvent', { type, x: Math.round(x), y: Math.round(y), button: 'left', clickCount: 1, buttons }); await sleep(120); };
  55. const clickSel = async (sel) => { const r = await ev(`(() => { const e = document.querySelector(${J(sel)}); if (!e) return null; e.scrollIntoView({ block: 'center' }); const q = e.getBoundingClientRect(); return { x: q.left + q.width / 2, y: q.top + q.height / 2 }; })()`); if (!r) throw new Error('no ' + sel); await click(r.x, r.y); };
  56. // the editor surface, old (shadow DOM, [part~=editor]) or new (the block's light DOM, article)
  57. const SURF = `(document.querySelector('md-editor') && ((document.querySelector('md-editor').shadowRoot && document.querySelector('md-editor').shadowRoot.querySelector('[part~=editor]')) || document.querySelector('md-editor article')))`;
  58. const value = () => ev(`(() => { const n = document.getElementById('notetext'); if (!n) return null; const i = n.querySelector('input[name=text]'); return i ? i.value : n.value; })()`);
  59. const clickEditor = async () => { const r = await ev(`(() => { const s = ${SURF}; if (!s) return null; s.scrollIntoView({ block: 'center' }); const q = s.getBoundingClientRect(); return { x: q.left + 24, y: q.top + 16 }; })()`); if (!r) throw new Error('no editor surface'); await click(r.x, r.y); };
  60. const key = async (k, code, vk, mods = 0, text) => { const t = text && !(mods & 2) ? text : undefined; await page.send('Input.dispatchKeyEvent', { type: t ? 'keyDown' : 'rawKeyDown', modifiers: mods, key: k, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk, ...(t ? { text: t, unmodifiedText: t } : {}) }); await page.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: mods, key: k, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk }); await sleep(40); };
  61. const enter = () => key('Enter', 'Enter', 13, 0, '\r');
  62. const tab = () => key('Tab', 'Tab', 9);
  63. const ctrl = (k, code, vk) => key(k, code, vk, 2);
  64. const type = async (s) => { for (const ch of s) { await page.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch }); await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch }); } await sleep(80); };
  65. const hydrated = () => waitFor(`!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1`, 'hydrated');
  66. const overflow = () => ev(`document.documentElement.scrollWidth > innerWidth`);
  67. try {
  68. for (let i = 0; i < 480; i++) { try { if ((await fetch(API + '/')).ok) break; } catch {} await sleep(250); }
  69. check('the copy: the session is the creator', (await api('/api/me')).user === USER);
  70. let n0 = (await alive()).length;
  71. // the ONE existing tab: about:blank (never /json/new)
  72. const tabs = (await get('/json/list')).filter(t => t.type === 'page' && t.url === 'about:blank');
  73. if (!tabs.length) throw new Error('no existing about:blank tab');
  74. tabUrlBefore = tabs[0].url;
  75. page = await connect(tabs[0].webSocketDebuggerUrl.replace(/ws:\/\/[^/]+/, `ws://127.0.0.1:${CDP}`));
  76. browser = await connect((await get('/json/version')).webSocketDebuggerUrl.replace(/ws:\/\/[^/]+/, `ws://127.0.0.1:${CDP}`));
  77. for (const m of ['Page.enable', 'Runtime.enable', 'Network.enable']) await page.send(m);
  78. await page.send('Network.setCookie', { name: 'notessid', value: sid, url: BASE + '/' });
  79. const workers = new Map();
  80. const setOffline = async (off) => {
  81. await page.send('Network.emulateNetworkConditions', { offline: off, latency: 0, downloadThroughput: -1, uploadThroughput: -1 });
  82. const { targetInfos } = await browser.send('Target.getTargets');
  83. for (const t of targetInfos) if (t.type === 'service_worker' && t.url.startsWith(BASE) && !workers.has(t.targetId)) {
  84. const { sessionId } = await browser.send('Target.attachToTarget', { targetId: t.targetId, flatten: true });
  85. await browser.send('Network.enable', {}, sessionId); workers.set(t.targetId, sessionId);
  86. }
  87. for (const s of workers.values()) await browser.send('Network.emulateNetworkConditions', { offline: off, latency: 0, downloadThroughput: -1, uploadThroughput: -1 }, s);
  88. };
  89. const goto = async (url) => { await page.send('Page.navigate', { url }); await sleep(300); await page.send('Page.bringToFront'); };
  90. for (const [W_, H_] of [[390, 844], [1280, 900]]) {
  91. const tag = String(W_);
  92. n0 = (await alive()).length; // each width starts from what the copy holds now
  93. const heading = `E2E ${LABEL} ${tag}`;
  94. await size(W_, H_);
  95. await goto(BASE + '/');
  96. await waitFor(`document.querySelectorAll('#notes a').length > 0`, 'list', 60000); await hydrated();
  97. await waitFor(`!!navigator.serviceWorker.controller`, 'service worker controls the page', 40000);
  98. await shot(`${tag}-1-list`);
  99. check(`${tag}: the list shows the copy's notes`, (await ev(`document.querySelectorAll('#notes a').length`)) === n0, String(n0));
  100. await clickSel('#newnote');
  101. await waitFor(`/^\\/note\\/l[0-9a-f]+$/.test(location.pathname) && ${SURF} && ${SURF}.children.length > 0`, 'the new note and its editor');
  102. await sleep(500);
  103. await clickEditor();
  104. // real keys: heading, text with bold, a list, a table
  105. await type('# ' + heading); await enter();
  106. await type('Plain '); await ctrl('b', 'KeyB', 66); await type('bold'); await ctrl('b', 'KeyB', 66); await type(' end'); await enter();
  107. await type('| Item | Qty |'); await enter(); await type('|:---|---:|'); await enter();
  108. await type('milk'); await tab(); await type('2'); await enter(); await enter();
  109. await type('- first'); await enter(); await type('second');
  110. await sleep(300);
  111. const typed = await value();
  112. await shot(`${tag}-2-typed`);
  113. check(`${tag}: typed heading, bold, list and table are Markdown in the note`, typed && typed.startsWith('# ' + heading) && /\*\*bold\*\*/.test(typed) && /^- first$/m.test(typed) && /^- second$/m.test(typed) && /\| Item +\| +Qty \|/.test(typed) && /milk/.test(typed) && /\| *2 *\|/.test(typed), J(typed));
  114. check(`${tag}: the editor shows a heading, a bold word, a list and a table`, await ev(`(() => { const s = ${SURF}; return !!(s.querySelector('h1') && s.querySelector('strong, b') && s.querySelector('ul li') && s.querySelector('table')); })()`));
  115. let saved = null;
  116. for (let i = 0; i < 80 && !saved; i++) { saved = (await alive()).find(n => n.text === typed); if (!saved) await sleep(250); }
  117. check(`${tag}: the server has the note, byte for byte what the editor holds`, !!saved, J(typed));
  118. check(`${tag}: no sideways scroll`, !(await overflow()));
  119. // RELOAD
  120. await goto(BASE + '/note/' + (saved ? saved.id : ''));
  121. await waitFor(`!!document.getElementById('notetext') && ${SURF} && ${SURF}.children.length > 0`, 'reloaded note', 60000);
  122. await sleep(600);
  123. const reloaded = await value();
  124. await shot(`${tag}-3-reloaded`);
  125. check(`${tag}: after a reload the note is saved and the same`, reloaded === typed, J(reloaded));
  126. // OFFLINE
  127. await setOffline(true);
  128. await goto(BASE + '/note/' + saved.id);
  129. await waitFor(`!!window.__hl && !!document.getElementById('notetext') && ${SURF} && ${SURF}.children.length > 0`, 'offline note', 60000);
  130. await sleep(800);
  131. check(`${tag}: offline the note opens with its text`, (await value()) === typed && (await ev(`document.querySelectorAll('#notes a').length`)) === n0 + 1, J(await value()));
  132. await clickEditor(); await ctrl('End', 'End', 35); await type(' offline' + tag);
  133. await sleep(2200);
  134. const offTyped = await value();
  135. check(`${tag}: offline the editor works (typing lands) and the page says it is offline`, /offline\d+$/.test(offTyped || '') && /Offline/.test(await ev(`(document.getElementById('syncstate') || {}).textContent || ''`)), J(offTyped));
  136. await shot(`${tag}-4-offline`);
  137. await goto(BASE + '/');
  138. await waitFor(`document.querySelectorAll('#notes a').length > 0`, 'offline list', 60000);
  139. check(`${tag}: offline the list opens`, (await ev(`document.querySelectorAll('#notes a').length`)) === n0 + 1);
  140. await setOffline(false);
  141. let back = null;
  142. for (let i = 0; i < 160 && !back; i++) { back = (await alive()).find(n => n.text === offTyped); if (!back) await sleep(250); }
  143. check(`${tag}: back online the offline edit reached the server (same note, no copy)`, !!back && back.id === saved.id && (await alive()).length === n0 + 1, J(offTyped));
  144. check(`${tag}: no sideways scroll at the end`, !(await overflow()));
  145. await goto(BASE + '/'); await waitFor(`document.querySelectorAll('#notes a').length > 0`, 'list again', 60000);
  146. await shot(`${tag}-5-end`);
  147. }
  148. check('the server logged no error', !/error|Error/.test(log.replace(/error absorbed/g, '')), log.slice(-400));
  149. } catch (e) {
  150. console.log('FAIL crashed — ' + (e && e.stack || e)); failures++; console.log(log.slice(-800));
  151. } finally {
  152. try { if (page) { await page.send('Network.emulateNetworkConditions', { offline: false, latency: 0, downloadThroughput: -1, uploadThroughput: -1 }); await page.send('Emulation.clearDeviceMetricsOverride'); await page.send('Page.navigate', { url: 'about:blank' }); } } catch {}
  153. try { if (page) page.ws.close(); if (browser) browser.ws.close(); } catch {}
  154. try { srv.kill('SIGTERM'); } catch {}
  155. await sleep(1000);
  156. rmSync(W, { recursive: true, force: true });
  157. console.log(`${passes} passed, ${failures} failed (copy deleted: ${!existsSync(W)})`);
  158. process.exit(failures ? 1 : 0);
  159. }

Branches

Latest commits

  • fd36da27notes mission 010: the note editor is the Hybriel MdEditor block (components.hybriel 1442e58, verbatim); md-editor.js, its route, script tag and offlineFiles retired; gate 66/0, realdata-offline 12/0, round-trip and Chrome E2E tests; report 010mre
  • efa92170notes tests/identkit.mjs: refuse a taken ident port, cold-wait deadline, emit, identities; mission 009 reportmre
  • f3dec0f1Merge branch 'w7'mre
  • d1cf966dre-vendor hybriel 97bcf128: offlineFiles for the editor script, 44 px taps, 390 px offline checks, mission 008mre
  • 4a610a21paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • eeaea980report 007: say which runs included the removed checkmre
  • 8a8ad9banotes mission 007: report, LOG, STATUSmre
  • 2cce9c96code order: plain declarations where never reassigned (letcount 0 never); gate: scan every IndexedDB at log-out, soft mode for old-code runs, drop a check that could not failmre
  • 7f6a4090README: offline in Hybriel (hl:web offline, continuation, known md-editor gap); gate waits report instead of crash; realdata-offline checkmre
  • 632223f2notes#4: delete notes-offline.js and sw.js (hl:web's generated worker and kept state replace them)mre
  • 52a2acadgate: offline checks on hl:web's worker/queue, Chrome offline via CDP (reload offline first), one-offline conflict, log-out forgets the kept copymre
  • e5785b03notes#4: the notes page in Hybriel — hl:web offline = [Notes], queued faces notesPut/notesDrop, push notesChanged, value-form notesPull on a tick; notes-offline.js/sw.js no longer loaded or routedmre
  • 510aff75notes#4: server continues a run of saves of one login (by + since), loser keeps writing into its copy; notesFor listmre
  • 0176c4b5mission brief 007mre
  • 06cfa870notes mission 006: re-vendor hybriel 0f396652 (static), reportmre
  • 6c07bd91mission brief w6mre
  • cf64d3d5notes mission 005: stopped at a Hybriel gap (for list repainted during hl:web boot throws, rowKidless); report, LOG, STATUSmre
  • a43b5d2dmission brief 005mre
  • 04a625edmission 004: re-vendor hybriel a832f73b (native bin + plugins as tickets), compose HL_CACHE_DIR volume + tmpfs /tmp, deploy URL wait 120 s, tests wait 120 s per start; gate 57/0 old and new; real-data same output. Not deployed.mre
  • aefb9d44mission brief w4mre