gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit15c46ced15c46ced|||PR Preserve note edits, conflict bases and visible historyAtlas15c46ced/tests/pr7-regressions.mjs

11.7 KB

  1. // Always-on checks for notes PR #7 findings 1–3. Synthetic storage and own headless Chrome.
  2. import { spawn } from 'node:child_process';
  3. import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
  4. import { resolve, join } from 'node:path';
  5. import { fileURLToPath } from 'node:url';
  6. import { launchBrowser, sleep } from './cdp.mjs';
  7. import { startIdent } from './identkit.mjs';
  8. const app = resolve(fileURLToPath(new URL('..', import.meta.url)));
  9. const scratch = join(app, '.scratch/pr7-regressions');
  10. const port = Number(process.env.NOTES_GATE_PORT || 8800);
  11. const identPort = Number(process.env.NOTES_GATE_IDENT_PORT || 8801);
  12. const base = `http://notes.test:${port}`;
  13. const api = `http://127.0.0.1:${port}`;
  14. 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=${base}`;
  15. rmSync(scratch, { recursive: true, force: true });
  16. mkdirSync(scratch, { recursive: true });
  17. let ident, server, browser, log = '', failures = 0, passes = 0;
  18. const check = (name, ok, detail) => { console.log((ok ? 'ok ' : 'FAIL ') + name + ' ' + JSON.stringify(detail)); ok ? passes++ : failures++; };
  19. try {
  20. ident = await startIdent({ identDir: '/media/STORAGE/projects/WorldAPI/ident.worldapi.org', workDir: join(scratch, 'ident'), port: identPort });
  21. const alice = await ident.signIn('[email protected]');
  22. const registered = await ident.registerApp(alice, 'PR7 regressions', [base]);
  23. server = spawn(join(app, 'bin/hybriel'), ['project.hl'], {
  24. cwd: app, env: { ...process.env, NOTES_PORT: String(port), NOTES_STORAGE: join(scratch, 'data'), NOTES_SESSIONS: join(scratch, 'sessions') + '/', NOTES_WATCH: '0', NOTES_PUBLIC_URL: base, IDENT_URL: `http://ident.notes.test:${identPort}`, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: registered.key, IDENT_API_SECRET: registered.secret },
  25. stdio: ['ignore', 'pipe', 'pipe'],
  26. });
  27. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  28. let up = false;
  29. for (const end = Date.now() + 180000; Date.now() < end && !up;) {
  30. try { up = (await fetch(api + '/')).ok; } catch {}
  31. if (!up) await sleep(250);
  32. }
  33. if (!up) throw new Error('server did not start: ' + log);
  34. const code = await ident.selectorCode(alice, registered, base);
  35. const login = await fetch(api + '/login/callback?ident_code=' + encodeURIComponent(code), { redirect: 'manual' });
  36. const cookie = login.headers.get('set-cookie')?.split(';')[0];
  37. if (login.status !== 302 || !cookie) throw new Error('login failed');
  38. const save = async (text, fields = {}) => {
  39. const res = await fetch(api + '/api/notes', { method: 'POST', headers: { cookie, 'content-type': 'application/json' }, body: JSON.stringify({ op: 'save', id: '', local: '', text, base: 0, at: Date.now(), ...fields }) });
  40. const value = await res.json();
  41. if (res.status !== 200 || !value.id) throw new Error('save failed: ' + JSON.stringify(value));
  42. return value;
  43. };
  44. const original = await save('Original note', { at: Date.now() - 10000 });
  45. const other = await save('Other note');
  46. browser = await launchBrowser({ debugPortRange: [8803, 8810] });
  47. const page = await browser.newPage();
  48. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  49. await page.send('Network.enable');
  50. await page.send('Network.setCookie', { name: 'notessid', value: cookie.slice('notessid='.length), url: base });
  51. const ready = async () => page.waitFor('window.__hl?.socket?.readyState === 1 && !window.__hl.navigating', { timeout: 120000 });
  52. const standing = async (path) => page.waitFor(`location.pathname === ${JSON.stringify(path)} && !window.__hl.navigating && window.__hl.page.instance.sel === ${JSON.stringify(path === '/' ? '' : path.slice(6))}`, { timeout: 30000 });
  53. const text = () => page.evaluate(`document.querySelector('#notetext input[name=text]')?.value`);
  54. const replaceText = async (value) => {
  55. await page.waitFor(`!!document.querySelector('#notetext md-editor article > *')`, { timeout: 30000 });
  56. await page.click('#notetext button.source-switch');
  57. await page.waitFor(`document.querySelector('#notetext textarea').getBoundingClientRect().width > 0`);
  58. await page.click('#notetext textarea');
  59. await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'a', code: 'KeyA', windowsVirtualKeyCode: 65, modifiers: 2 });
  60. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'a', code: 'KeyA', windowsVirtualKeyCode: 65, modifiers: 2 });
  61. await page.send('Input.insertText', { text: value });
  62. };
  63. const serverNote = async (id) => (await fetch(api + '/api/notes?id=' + id, { headers: { cookie } })).json();
  64. const serverList = async () => (await (await fetch(api + '/api/notes', { headers: { cookie } })).json()).notes.filter(n => !n.gone);
  65. const face = async (event, payload) => {
  66. const res = await fetch(api + '/__hl/emit', { method: 'POST', headers: { cookie, 'content-type': 'application/json' }, body: JSON.stringify({ t: 'emit', i: 1, event, payload }) });
  67. if (!res.ok) throw new Error('face ' + res.status);
  68. return res.json();
  69. };
  70. const offline = async (value) => {
  71. await page.setOffline(value);
  72. for (const target of (await browser.conn.send('Target.getTargets')).targetInfos.filter(t => t.type === 'service_worker')) {
  73. const { sessionId } = await browser.conn.send('Target.attachToTarget', { targetId: target.targetId, flatten: true });
  74. await browser.conn.send('Network.enable', {}, sessionId);
  75. await browser.conn.send('Network.emulateNetworkConditions', { offline: value, latency: 0, downloadThroughput: -1, uploadThroughput: -1 }, sessionId);
  76. }
  77. };
  78. const shot = async (name) => { const r = await page.send('Page.captureScreenshot', { format: 'png', captureBeyondViewport: true }); writeFileSync(join(scratch, name + '.png'), Buffer.from(r.data, 'base64')); };
  79. // Freeze CSS animations so no save tick can race the sub-delay history departure.
  80. // The source textarea receives real input. Reopen via a link (fresh instance), not Forward.
  81. await page.goto(base + '/'); await ready();
  82. await page.click(`#notes a[href="/note/${original.id}"]`); await standing('/note/' + original.id);
  83. // MdEditor itself initializes with an animation; let it finish before freezing the save tick.
  84. await page.waitFor(`!!document.querySelector('#notetext md-editor article > *')`, { timeout: 30000 });
  85. await page.send('Animation.enable');
  86. await page.send('Animation.setPlaybackRate', { playbackRate: 0 });
  87. await replaceText('Pending edit survives Back');
  88. const elapsed = await page.evaluate(`(() => { const e = window.__hl.page.instance.edits.find(e => e.key === window.__hl.page.instance.sel); const ms = e ? Date.now() - e.when : 0; history.back(); return ms; })()`);
  89. check('finding 1 setup: Back before the old 600 ms save delay', elapsed < 600, elapsed);
  90. await standing('/');
  91. await page.click(`#notes a[href="/note/${original.id}"]`); await standing('/note/' + original.id);
  92. check('finding 1: reopening through a link keeps the pending typed edit', await text() === 'Pending edit survives Back', { actual: await text() });
  93. await shot('pending-after-link');
  94. await page.send('Animation.setPlaybackRate', { playbackRate: 1 });
  95. // A repeated announcement of an already-saved input must not undo a remote patch.
  96. await replaceText('Duplicate input guard');
  97. for (const end = Date.now() + 30000; Date.now() < end;) { if ((await serverNote(original.id)).text === 'Duplicate input guard') break; await sleep(100); }
  98. const accepted = await serverNote(original.id);
  99. await save('Other device truth', { id: original.id, base: accepted.edited });
  100. await page.evaluate('window.__hl.page.instance.pull()');
  101. await page.waitFor('window.__hl.page.instance.notes.some(n => n.text === "Other device truth")');
  102. await page.evaluate(`(() => { const input = document.querySelector('#notetext input[name=text]'); input.value = 'Duplicate input guard'; input.dispatchEvent(new Event('input', { bubbles: true })); })()`);
  103. await sleep(1600);
  104. check('repeated accepted input does not overwrite a newer remote value', (await serverNote(original.id)).text === 'Other device truth', await serverNote(original.id));
  105. // A rejected draft predates the browser's reopen but postdates another device's save.
  106. const conflict = await save('Original conflict base', { at: Date.now() - 10000 });
  107. const concurrent = await save('Another device changed this', { id: conflict.id, base: conflict.edited, at: conflict.edited + 1000 });
  108. const rejected = 'Rejected draft ' + 'x'.repeat(200001 - 'Rejected draft '.length);
  109. await face('notesPut', [{ key: conflict.id, id: conflict.id, local: '', text: rejected, base: conflict.edited, when: concurrent.edited + 1000 }]);
  110. await page.goto(base + '/note/' + conflict.id); await ready();
  111. await page.waitFor(`document.querySelector('#notetext input[name=text]')?.value.length === 200001`, { timeout: 30000 });
  112. const restoredBase = await page.evaluate('window.__hl.page.instance.openRow.base');
  113. check('finding 2: rejected draft restores its original conflict base', restoredBase === conflict.edited, { original: conflict.edited, concurrent: concurrent.edited, restored: restoredBase });
  114. const beforeCount = (await serverList()).length;
  115. await replaceText('Corrected rejected draft');
  116. for (const end = Date.now() + 30000; Date.now() < end;) { if ((await serverNote(conflict.id)).text === 'Corrected rejected draft') break; await sleep(100); }
  117. const after = await serverList();
  118. const copies = [];
  119. for (const n of after) if (n.id !== conflict.id && (await serverNote(n.id)).text.startsWith('Another device changed this')) copies.push(n.id);
  120. check('finding 2: correcting the draft preserves the concurrent text in a conflict copy', after.length === beforeCount + 1 && copies.length === 1, { beforeCount, afterCount: after.length, copies });
  121. await shot('conflict-copy');
  122. // Create A offline, leave it retained under the shell while B is visible, then replay.
  123. await page.goto(base + '/'); await ready();
  124. await page.waitFor('!!navigator.serviceWorker.controller', { timeout: 120000 });
  125. await offline(true);
  126. await page.goto(base + '/', { timeout: 120000 });
  127. await page.waitFor('window.__hl?.page?.instance.__hlOnline === false', { timeout: 30000 });
  128. await page.click('#newnote');
  129. await page.waitFor('location.pathname.startsWith("/note/l") && !window.__hl.navigating', { timeout: 30000 });
  130. const provisional = await page.evaluate('location.pathname');
  131. await page.click(`#notes a[href="/note/${other.id}"]`); await standing('/note/' + other.id);
  132. await offline(false);
  133. await page.evaluate('dispatchEvent(new Event("online"))');
  134. await ready();
  135. await page.waitFor('window.__hl.page.instance.notes.some(n => n.local === ' + JSON.stringify(provisional.slice(6)) + ')', { timeout: 30000 });
  136. // Wait for any wrong global navigation to finish as well as the replay acknowledgement.
  137. await page.waitFor('!window.__hl.navigating && window.__hl.page.instance.__hlQueue.length === 0', { timeout: 30000 });
  138. const adopted = await page.evaluate(`({ path: location.pathname, sel: window.__hl.page.instance.sel, current: document.querySelector('#notes a[aria-current=page]')?.getAttribute('href') })`);
  139. check('finding 3: a retained provisional page cannot replace visible B on reconnect', adopted.path === '/note/' + other.id && adopted.sel === other.id && adopted.current === '/note/' + other.id, adopted);
  140. await shot('retained-adoption');
  141. } catch (e) { failures++; console.log('FAIL crashed ' + e.stack + '\n' + log.slice(-2000)); }
  142. finally {
  143. if (browser) await browser.close();
  144. if (server) { server.kill('SIGTERM'); await new Promise(r => { if (server.exitCode !== null || server.signalCode !== null) return r(); server.once('exit', r); }); }
  145. if (ident) await ident.stop();
  146. console.log(`${passes} passed, ${failures} failed`);
  147. process.exitCode = failures ? 1 : 0;
  148. }

Branches

Latest commits

  • 15c46ced|||PR Preserve note edits, conflict bases and visible historyAtlas
  • 4c6e0bf6Merge branch 'notes13-day61' into mainAtlas
  • eb51864f|||PR Back/Forward via navigate, server drafts, Hybriel day61Atlas
  • 3537cf7eMerge branch 'vendor-day59' into mainAtlas
  • c13d188b|||PR Vendor Hybriel day59Atlas
  • 24c95433Merge branch 'notes17-ghost-note' into mainAtlas
  • ae1075b2Preserve rejected drafts during note ID adoptionAtlas
  • 383cce23|||PR Prevent saved local edits from restoring deleted notesAtlas
  • 99ca1cf6Merge branch 'vendor-day56' into mainAtlas
  • 649cef37|||PR Vendor Hybriel day56Atlas
  • aadd0abcMerge branch 'hl-standard-2' into mainAtlas
  • 52ffac9f|||PR Keyboard and reload checks for the notes gate (HL-STANDARD F21, F5)Atlas
  • 617ee8c0Merge branch 'hl-standard' into mainAtlas
  • 452458ee|||PR Type the function parameters of notes' own .hl files (HL-STANDARD L10)Atlas
  • 23758cd6Re-vendor complete Hybriel plugins and runtime to day44mre
  • 5d7cc700Backup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre
  • 3e07b1cfVendor complete Hybriel day39 plugin sources and librariesmre
  • d7366702Check session cookie flags after login and assert anonymous GET stays cookielessmre
  • 16bc8fd8Re-vendor Hybriel day38b with the mpackdb store-open race fixmre
  • d860dc2dnotes#12: the markup names its own rules instead of hand-written class strings: the selected row is `aria-current="page"` (the list-first theme rule styles it, no class), the delete question is `Style.pAsk` and follows its own `open` attribute (bound to `asking`), the error line is `Style.pMessage` (body once in lib/looks.hl, rule in notes.hl, main.hl and loginfailed.hl). The CSS declarations are the same, only selectors changed (.ask -> p.ask, .ask.open -> p.ask[open], .message -> p.message); the pages look the same (AE 0 at 4 sizes). main.hl's selectorClass in/out stays (login.js reads it).mre