gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit447da53d447da53dnotes mission 014: report — remaining gates and lisbeth E2E proofmre447da53d/tests/realdata-offline.mjs

12.4 KB

  1. // tests/realdata-offline.mjs (notes#4, mission 007): the offline notes on a COPY of real data, in real Chrome.
  2. // node tests/realdata-offline.mjs <backup.tgz> <port> <chrome-from>-<chrome-to>
  3. // Unpacks storage/mpackdb of the backup into .scratch/realdata-offline (a fresh copy, deleted at the end), signs in as the
  4. // creator (identity az5b2 → users @id 0muh6o5a3kkd) through a session file written before the start, then: every live
  5. // note is listed; screenshots 390 / 1280; Chrome offline (CDP, page + worker), reload offline, edit a note with real keys;
  6. // back online → the server has the edit (in that note, no copy). Kills only what it started.
  7. import { spawn, execFileSync } from 'node:child_process';
  8. import { writeFileSync, mkdirSync, rmSync, existsSync } 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. import { launchBrowser } from './cdp.mjs';
  13. const [tgz, portArg, chromeArg] = process.argv.slice(2);
  14. const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');
  15. const PORT = Number(portArg);
  16. const [CH_FROM, CH_TO] = (chromeArg || '8735-8739').split('-').map(Number);
  17. const BASE = `http://notes.test:${PORT}`, API = `http://127.0.0.1:${PORT}`;
  18. const W = join(APP, '.scratch/realdata-offline');
  19. const USER = '0muh6o5a3kkd';
  20. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  21. process.env.HL_CHROME_ARGS = `--host-resolver-rules=MAP notes.test 127.0.0.1|--unsafely-treat-insecure-origin-as-secure=${BASE}`;
  22. rmSync(W, { recursive: true, force: true });
  23. mkdirSync(join(W, 'data'), { recursive: true }); mkdirSync(join(W, 'sessions'), { recursive: true });
  24. execFileSync('tar', ['-xzf', resolve(tgz), '-C', join(W, 'data'), 'storage/mpackdb']);
  25. const sid = randomBytes(16).toString('hex');
  26. const now = Date.now();
  27. writeFileSync(join(W, 'sessions', createHash('sha256').update(sid).digest('hex')),
  28. JSON.stringify({ created: now, data: { tag: 'rd-offline' }, handled: [], id: sid, seen: now, user: { id: USER } }), { mode: 0o600 });
  29. const COOKIE = 'notessid=' + sid;
  30. let failures = 0, passes = 0;
  31. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };
  32. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  33. const J = JSON.stringify;
  34. let log = '';
  35. const srv = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  36. env: { ...process.env, NOTES_PORT: String(PORT), NOTES_PUBLIC_URL: BASE, NOTES_STORAGE: join(W, 'data/storage/mpackdb'),
  37. NOTES_SESSIONS: join(W, 'sessions') + '/', NOTES_WATCH: '0', IDENT_URL: 'http://ident.test', IDENT_API_KEY: 'pk_rd', IDENT_API_SECRET: 'sk_rd' } });
  38. srv.stdout.on('data', d => log += d); srv.stderr.on('data', d => log += d);
  39. let b = null;
  40. const api = async (path) => (await fetch(API + path, { headers: { cookie: COOKIE } })).json();
  41. const alive = async () => (await api('/api/notes')).notes.filter(n => !n.gone);
  42. try {
  43. for (let i = 0; i < 480; i++) { try { if ((await fetch(API + '/')).ok) break; } catch {} await sleep(250); }
  44. check('the session is the creator', (await api('/api/me')).user === USER);
  45. const live = await alive();
  46. console.log('live notes in the copy:', live.length);
  47. b = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });
  48. const p = await b.newPage();
  49. p.__browser = b;
  50. await p.send('Network.enable');
  51. await p.send('Network.setCookie', { name: 'notessid', value: sid, url: BASE + '/' });
  52. const size = async (w, h) => { await p.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile: w < 600 }); await sleep(300); };
  53. const shot = async (name) => { const { data } = await p.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(APP, '.scratch', `realdata-${name}.png`), Buffer.from(data, 'base64')); };
  54. const look = () => p.evaluate(`JSON.stringify((() => { const c = (s) => { const e = document.querySelector(s); if (!e) return null; const st = getComputedStyle(e); const r = e.getBoundingClientRect(); return { color: st.color, bg: st.backgroundColor, w: Math.round(r.width), h: Math.round(r.height), vis: r.width > 0 && st.display !== 'none' }; };
  55. return { list: c('note-list'), reader: c('note-reader'), header: c('application-header'), brand: c('application-header .brand'), selected: c('#notes a.selected'), item: c('#notes a'), md: c('md-editor'), ta: c('#notetext'), state: (document.getElementById('syncstate') || {}).textContent, overflow: document.documentElement.scrollWidth > innerWidth, mdDefined: !!document.querySelector('md-editor article') }; })())`);
  56. await size(1280, 900);
  57. await p.goto(BASE + '/');
  58. await p.waitFor('document.querySelectorAll("#notes a").length > 0', { timeout: 60000 });
  59. await sleep(1000);
  60. const shown = await p.evaluate(`[...document.querySelectorAll('#notes a')].map(a => a.getAttribute('href').slice(6))`);
  61. check(`all ${live.length} live notes are listed (by id)`, shown.length === live.length && live.every(n => shown.includes(n.id)), `${shown.length} shown`);
  62. await p.waitFor('!!navigator.serviceWorker.controller', { timeout: 30000 });
  63. // the note to edit: the newest one; open it
  64. const target = shown[0];
  65. const before = (await api('/api/notes?id=' + target)).text;
  66. await p.click('#notes a');
  67. await p.waitFor(`location.pathname === '/note/${target}' && document.getElementById('notetext') && document.querySelector('#notetext input[name=text]').value === ${J(before)}`, { timeout: 30000 });
  68. await sleep(1500);
  69. console.log('look 1280 online:', await look()); await shot('1280-online');
  70. await size(390, 844); console.log('look 390 online:', await look()); await shot('390-online');
  71. await size(1280, 900);
  72. // Chrome offline: page + worker, then reload offline
  73. const conn = b.conn; const workers = [];
  74. for (const t of (await conn.send('Target.getTargets')).targetInfos.filter(t => t.type === 'service_worker')) {
  75. const { sessionId } = await conn.send('Target.attachToTarget', { targetId: t.targetId, flatten: true });
  76. await conn.send('Network.enable', {}, sessionId); workers.push(sessionId);
  77. }
  78. const offline = async (o) => { await p.setOffline(o); for (const s of workers) await conn.send('Network.emulateNetworkConditions', { offline: o, latency: 0, downloadThroughput: -1, uploadThroughput: -1 }, s); };
  79. await offline(true);
  80. await p.goto(BASE + '/note/' + target);
  81. await p.waitFor(`!!window.__hl && document.getElementById('notetext') && document.querySelector('#notetext input[name=text]').value === ${J(before)}`, { timeout: 30000 });
  82. await sleep(1500);
  83. const offCount = await p.evaluate(`document.querySelectorAll('#notes a').length`);
  84. check(`offline reload: all ${live.length} notes still listed, the open note shows its text, no socket`, offCount === live.length && !(await p.evaluate('!!(window.__hl.socket && window.__hl.socket.readyState === 1)')), String(offCount));
  85. // MOBILE (mission 008): the offline pages at 390 px measured in the DOM: no visible element wider than 390 (shadow DOM
  86. // included), every visible tap target (a, button, input, textarea, select, [role=button]) at least 44 x 44 px
  87. const measure = (label) => p.evaluate(`JSON.stringify((() => { const wide = [], small = [], seen = [];
  88. const walk = (root) => { for (const e of root.querySelectorAll('*')) { if (e.shadowRoot) walk(e.shadowRoot);
  89. const r = e.getBoundingClientRect(); const st = getComputedStyle(e); if (!r.width || !r.height || st.display === 'none' || st.visibility === 'hidden') continue;
  90. const name = e.tagName.toLowerCase() + (e.id ? '#' + e.id : '') + (e.className && typeof e.className === 'string' ? '.' + e.className.trim().split(/\\s+/).join('.') : '');
  91. const scrolled = e.closest('nav') && /auto|scroll/.test(getComputedStyle(e.closest('nav')).overflowX); /* the phone toolbar is one row that scrolls inside its own box */
  92. if (!scrolled && (r.right > 390.5 || r.left < -0.5)) wide.push(name + ' ' + Math.round(r.left) + '..' + Math.round(r.right));
  93. if (e.matches('a, button, input:not([type=hidden]), textarea, select, [role=button], [contenteditable]') && (r.height < 43.5 || r.width < 43.5)) small.push(name + ' ' + Math.round(r.width) + 'x' + Math.round(r.height) + ' "' + (e.textContent || '').trim().slice(0, 20) + '"');
  94. if (e.matches('a, button, input:not([type=hidden]), textarea, select, [role=button], [contenteditable]')) seen.push(name); } };
  95. walk(document); return { scrollW: document.documentElement.scrollWidth, innerW: innerWidth, wide: wide.slice(0, 8), small: small.slice(0, 12), taps: seen.length, editor: !!document.querySelector('md-editor article > *') }; })())`).then(JSON.parse);
  96. await size(390, 844);
  97. for (const [what, url, ready] of [['note', BASE + '/note/' + target, `!!document.getElementById('notetext')`], ['list', BASE + '/', `document.querySelectorAll('#notes a').length > 0`]]) {
  98. await p.goto(url);
  99. try { await p.waitFor(`!!window.__hl && ${ready}`, { timeout: 30000 }); } catch (e) { console.log('DEBUG', what, await p.evaluate(`JSON.stringify({ path: location.pathname, hl: !!window.__hl, nt: !!document.getElementById('notetext'), body: document.body.innerText.slice(0, 300) })`)); throw e; }
  100. await sleep(2000);
  101. const m = await measure(what);
  102. console.log('390 offline ' + what + ':', J(m));
  103. check(`390 px offline, ${what}: the MdEditor block is drawn (surface built, no editor script any more)`, what === 'list' || m.editor, J(m));
  104. check(`390 px offline, ${what}: no element wider than 390 px, page scroll width ${m.scrollW}`, m.scrollW <= 390 && m.wide.length === 0, J(m.wide));
  105. check(`390 px offline, ${what}: ${m.taps} tap targets, all at least 44 x 44 px`, m.small.length === 0 && m.taps > 0, J(m.small));
  106. }
  107. await size(1280, 900);
  108. await p.goto(BASE + '/note/' + target);
  109. await p.waitFor(`!!window.__hl && document.getElementById('notetext') && document.querySelector('#notetext input[name=text]').value === ${J(before)}`, { timeout: 30000 });
  110. await sleep(1500);
  111. // real keys at the end of the text (the MdEditor block is in the page: nothing to load offline)
  112. await p.waitFor(`!!document.querySelector('md-editor article > *')`, { timeout: 30000 });
  113. const bx = await p.evaluate(`(() => { const r = document.querySelector('md-editor article').getBoundingClientRect(); return { x: r.left + 20, y: r.top + 10 }; })()`);
  114. for (const [type, buttons] of [['mouseMoved', 0], ['mousePressed', 1], ['mouseReleased', 0]]) await p.send('Input.dispatchMouseEvent', { type, x: bx.x, y: bx.y, button: 'left', clickCount: 1, buttons });
  115. await p.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', modifiers: 2, key: 'End', code: 'End', windowsVirtualKeyCode: 35, nativeVirtualKeyCode: 35 });
  116. await p.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: 2, key: 'End', code: 'End', windowsVirtualKeyCode: 35, nativeVirtualKeyCode: 35 });
  117. const add = ' (offline edit, mission 007)';
  118. for (const ch of add) { await p.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch }); await p.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch }); }
  119. await sleep(2500);
  120. console.log('look 1280 offline:', await look()); await shot('1280-offline');
  121. await size(390, 844); console.log('look 390 offline:', await look()); await shot('390-offline'); await size(1280, 900);
  122. const typed = await p.evaluate(`document.querySelector('#notetext input[name=text]').value`);
  123. check('offline: the edit is in the note, the server does not have it yet', typed === before + add && (await api('/api/notes?id=' + target)).text === before, J(typed.slice(-60)));
  124. await offline(false);
  125. let after = null;
  126. for (let i = 0; i < 120; i++) { after = (await api('/api/notes?id=' + target)).text; if (after === before + add) break; await sleep(250); }
  127. const live2 = await alive();
  128. check('back online: the offline edit synced into the same note (no copy, same count)', after === before + add && live2.length === live.length, J({ tail: (after || '').slice(-60), n: live2.length }));
  129. check('the server logged no error', !/error|Error/.test(log.replace(/error absorbed/g, '')), log.slice(-400));
  130. } catch (e) {
  131. console.log('FAIL crashed — ' + (e && e.stack || e)); failures++; console.log(log.slice(-1000));
  132. } finally {
  133. if (b) { try { await b.close(); } catch {} }
  134. try { srv.kill('SIGTERM'); } catch {}
  135. await sleep(1000);
  136. rmSync(W, { recursive: true, force: true });
  137. console.log(`${passes} passed, ${failures} failed (copy deleted: ${!existsSync(W)})`);
  138. process.exit(failures ? 1 : 0);
  139. }

Branches

Latest commits

  • 447da53dnotes mission 014: report — remaining gates and lisbeth E2E proofmre
  • fd9f92c3notes mission 014: report (partial), LOG, STATUSmre
  • b2501360notes mission 014: open() sets asking=false before flush(0) (hybriel#196)mre
  • 9414ce59notes mission 014: merge theme 76f99f6, components 3794c59, strict single-press openAsk (fails on old open())mre
  • c08c655anotes 013: theme re-copied from layouts 76f99f6 (menu marks the current page), current = true on the menu item, e2e marker checks, reportmre
  • 21c8f65dnotes mission 012: STATUSmre
  • 0bbb3dd9notes mission 012: delete section of the browser gate de-flaked (openAsk: calm wait, press again when the question closes by itself); report 012mre
  • f431bdf8notes mission 011: notes on the layouts theme (ListFirst shell), styles cut, check-theme gate, E2E extended; reportmre
  • 1a8603d1notes mission 011 WIP: deploy.sh gate summary also matches check-theme, browser.mjs logout via the user menumre
  • dae2e508notes mission 011 WIP: theme dbe3de7, shell on AppHeader/MainMenu/UserMenu/Sidebar + ListFirst, styles cut to the app's own, check-theme gate, e2e auditmre
  • 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