gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit52ffac9f52ffac9f|||PR Keyboard and reload checks for the notes gate (HL-STANDARD F21, F5)Atlas52ffac9f/tests/e2e-outside.mjs

10.2 KB

  1. // tests/e2e-outside.mjs (F3, MdEditor outside value): END TO END in lisbeth's real Chrome (ssh -L <cdp>:127.0.0.1:9223 lisbeth, and -R <app-port> so Chrome
  2. // reaches http://<E2E_HOST|127.0.0.1>:<app-port>), real mouse and key events, on a COPY of a deploy backup. A note with a table is open; ANOTHER DEVICE
  3. // (an API save with the same login) changes a cell and adds a line; the open editor must show it, and the keys typed next (click the cell, End, "5")
  4. // must continue from the NEW text: saved `20` + `5` = `205` (the old editor wrote back its stale `2` + `5` = `25`).
  5. // node tests/e2e-outside.mjs prepare <label> <backup.tgz> <app-port> → copies the backup, makes a session, prints the env for the server (start it OUTSIDE the lisbeth lock)
  6. // node tests/e2e-outside.mjs run <label> <backup.tgz> <app-port> <cdp-port> <shots-dir> (one tab, navigated; put back to about:blank; the server is already up)
  7. import { spawn, execFileSync } from 'node:child_process';
  8. import { writeFileSync, readFileSync, mkdirSync, rmSync } from 'node:fs';
  9. import { createHash, randomBytes } from 'node:crypto';
  10. import { join, resolve, dirname } from 'node:path';
  11. import { fileURLToPath } from 'node:url';
  12. const [MODE, LABEL, tgz, portArg, cdpArg, shots] = process.argv.slice(2);
  13. const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');
  14. const PORT = Number(portArg), CDP = Number(cdpArg);
  15. const BASE = `http://${process.env.E2E_HOST || '127.0.0.1'}:${PORT}`, API = `http://127.0.0.1:${PORT}`;
  16. const W = join(APP, '.scratch/e2e-outside-' + LABEL);
  17. const USER = '0muh6o5a3kkd';
  18. if (MODE === 'prepare') {
  19. rmSync(W, { recursive: true, force: true });
  20. mkdirSync(join(W, 'data'), { recursive: true }); mkdirSync(join(W, 'sessions'), { recursive: true });
  21. execFileSync('tar', ['-xzf', resolve(tgz), '-C', join(W, 'data'), 'storage/mpackdb']);
  22. const sid0 = randomBytes(16).toString('hex'), now0 = Date.now();
  23. writeFileSync(join(W, 'sessions', createHash('sha256').update(sid0).digest('hex')), JSON.stringify({ created: now0, data: { tag: 'e2e' }, handled: [], id: sid0, seen: now0, user: { id: USER } }), { mode: 0o600 });
  24. writeFileSync(join(W, 'sid'), sid0);
  25. console.log(`cd ${APP} && NOTES_PORT=${PORT} NOTES_PUBLIC_URL=${BASE} NOTES_STORAGE=${W}/data/storage/mpackdb NOTES_SESSIONS=${W}/sessions/ NOTES_WATCH=0 IDENT_URL=http://ident.test IDENT_API_KEY=pk_e2e IDENT_API_SECRET=sk_e2e ./bin/hybriel project.hl`);
  26. process.exit(0);
  27. }
  28. mkdirSync(shots, { recursive: true });
  29. const sid = readFileSync(join(W, 'sid'), 'utf8');
  30. let failures = 0, passes = 0;
  31. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} [${LABEL}] ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };
  32. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  33. const J = JSON.stringify;
  34. function connect(url) {
  35. return new Promise((ok, no) => {
  36. const ws = new WebSocket(url); let n = 0; const pend = new Map();
  37. 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); } });
  38. ws.addEventListener('open', () => ok({ ws, send: (method, params = {}) => new Promise((ok2, no2) => { const id = ++n; pend.set(id, { ok: ok2, no: no2 }); ws.send(J({ id, method, params })); }) }));
  39. ws.addEventListener('error', () => no(new Error('ws error ' + url)));
  40. });
  41. }
  42. const get = async (path) => (await fetch(`http://127.0.0.1:${CDP}${path}`)).json();
  43. const hdr = { cookie: 'notessid=' + sid, 'content-type': 'application/json' };
  44. const api = async (path) => (await fetch(API + path, { headers: hdr })).json();
  45. const post = async (b) => (await fetch(API + '/api/notes', { method: 'POST', headers: hdr, body: J(b) })).json();
  46. let page = null, tabUrlBefore = null;
  47. 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; };
  48. 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) throw new Error('waitFor timed out: ' + label); await sleep(250); } };
  49. const shot = async (name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(shots, `${LABEL}-${name}.png`), Buffer.from(data, 'base64')); };
  50. const size = async (w, h) => { await page.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile: w < 600 }); await sleep(400); };
  51. 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(150); };
  52. 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); };
  53. const key = async (k, code, vk) => { await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: k, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk }); await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: k, code, windowsVirtualKeyCode: vk, nativeVirtualKeyCode: vk }); await sleep(60); };
  54. 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); };
  55. const value = () => ev(`(() => { const i = document.querySelector('#notetext input[name=text]'); return i ? i.value : null; })()`);
  56. const shown = () => ev(`(() => { const a = document.querySelector('md-editor article'); return a ? a.innerText : null; })()`);
  57. const TEXT1 = '# Outside E2E\n\n| Item | Qty |\n|:---|---:|\n| milk | 2 |\n| bread | 1 |\n';
  58. const TEXT2 = '# Outside E2E\n\n| Item | Qty |\n|:---|---:|\n| milk | 20 |\n| bread | 1 |\n\nChanged on another device\n';
  59. try {
  60. for (let i = 0; i < 480; i++) { try { if ((await fetch(API + '/')).ok) break; } catch {} await sleep(250); }
  61. check('the copy: the session is the creator', (await api('/api/me')).user === USER);
  62. const pages = (await get('/json/list')).filter(t => t.type === 'page');
  63. const tabs = pages.filter(t => t.url === 'about:blank');
  64. if (!tabs.length) tabs.push(...pages.filter(t => t.url.startsWith('http://127.0.0.1:') || t.url.startsWith('http://localhost:')).slice(0, 1));
  65. if (!tabs.length) throw new Error('no existing about:blank tab');
  66. tabUrlBefore = tabs[0].url;
  67. page = await connect(tabs[0].webSocketDebuggerUrl.replace(/ws:\/\/[^/]+/, `ws://127.0.0.1:${CDP}`));
  68. for (const m of ['Page.enable', 'Runtime.enable', 'Network.enable']) await page.send(m);
  69. await page.send('Network.setCookie', { name: 'notessid', value: sid, url: BASE + '/' });
  70. let n = 0;
  71. for (const [W_, H_] of [[390, 844], [1280, 900]]) {
  72. const tag = String(W_);
  73. await size(W_, H_);
  74. const local = 'lf3' + tag + Date.now().toString(16);
  75. const r1 = await post({ op: 'save', id: '', local, text: TEXT1, base: 0, at: Date.now() });
  76. check(`${tag}: the note is saved (${r1.id})`, !!r1.id, J(r1));
  77. await page.send('Page.navigate', { url: BASE + '/note/' + r1.id }); await sleep(300); await page.send('Page.bringToFront');
  78. await waitFor(`!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1`, 'hydrated', 60000);
  79. await waitFor(`!!document.querySelector('md-editor article table')`, 'the note and its table', 60000); await sleep(800);
  80. check(`${tag}: the open note shows qty 2`, /milk\s+2\b/.test(await shown()), J(await shown()));
  81. await shot(`${tag}-1-open`);
  82. // ANOTHER DEVICE changes the note: the page gets it as a push
  83. const r2 = await post({ op: 'save', id: r1.id, local, text: TEXT2, base: r1.edited, at: Date.now() });
  84. check(`${tag}: the other device's save is taken (${J(r2).slice(0, 80)})`, r2.text === TEXT2, J(r2));
  85. await waitFor(`((document.querySelector('#notetext input[name=text]') || {}).value || '').includes('Changed on another device')`, 'the field follows the push', 90000);
  86. await sleep(1500);
  87. const sh = await shown();
  88. check(`${tag}: the editor surface shows the pushed text (qty 20, the new line)`, /milk\s+20\b/.test(sh) && sh.includes('Changed on another device'), J(sh));
  89. await shot(`${tag}-2-after-push`);
  90. // the first edit: click in the Qty cell of milk, End, type 5
  91. const cell = await ev(`(() => { const c = [...document.querySelectorAll('md-editor article td')].find(t => t.textContent.trim() === '20' || t.textContent.trim() === '2'); if (!c) return null; c.scrollIntoView({ block: 'center' }); const q = c.getBoundingClientRect(); return { x: q.left + q.width / 2, y: q.top + q.height / 2 }; })()`);
  92. if (!cell) throw new Error('no qty cell');
  93. await click(cell.x, cell.y); await key('End', 'End', 35); await type('5'); await sleep(300);
  94. const v = await value();
  95. check(`${tag}: the field holds 205 (the first edit started from the new text), not 25 — ${J(v)}`, /\| milk +\| +205 +\|/.test(v) && v.includes('Changed on another device'), J(v));
  96. await shot(`${tag}-3-typed`);
  97. let saved = null;
  98. for (let i = 0; i < 60 && !saved; i++) { const t = (await api('/api/notes?id=' + r1.id)).text; if (/\| milk +\| +205 +\|/.test(t || '')) saved = t; else await sleep(500); }
  99. check(`${tag}: the server keeps 205 and the other device's line`, !!saved && saved.includes('Changed on another device'), J((await api('/api/notes?id=' + r1.id)).text));
  100. n++;
  101. }
  102. } catch (e) { failures++; console.log('FAIL crashed — ' + e.message); try { console.log('field', J(await value()), 'shown', J(await shown())); await shot('crash'); } catch {} }
  103. finally {
  104. try { if (page) { await page.send('Emulation.clearDeviceMetricsOverride'); await page.send('Page.navigate', { url: 'about:blank' }); page.ws.close(); } } catch {}
  105. console.log(`${passes} passed, ${failures} failed`);
  106. process.exit(failures ? 1 : 0);
  107. }

Branches

Latest commits

  • 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
  • 98bd6a98N5b: pipe rows without a delimiter row are a table (MdEditor ad4e929, plain copy); gate tests/dashboard-table.mjs; reportmre
  • dbf93319N5 report: components gate rerun 613 passed, 0 failedmre
  • 3a8bc0d2N5: empty Table-button table is written as a real pipe table (MdEditor 4bd1112, plain copy); gate tests/table-button.mjs; reportmre