gitoria

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit54fb0ce154fb0ce1calendar mission 002 (1/2): gate clock override GATE_CLOCK=HH:MM (this process and every page get Date shifted to that local time today)mre54fb0ce1/tests/browser.mjs

41.8 KB

  1. // tests/browser.mjs — THE GATE of calendar.worldapi.org: its own server on its own storage, its OWN ident (a copy of
  2. // ident's code without .env, codes to a mail sink: tests/identkit.mjs), real headless Chrome.
  3. // node tests/browser.mjs (CALENDAR_GATE_PORT server, default 8700; CALENDAR_GATE_IDENT_PORT ident, default 8701;
  4. // CALENDAR_GATE_CHROME "8702-8709" = Chrome debug ports)
  5. // Screenshots (390 / 1280 px) land in .scratch/gate-*.png. Every process started is stopped by PID.
  6. import { spawn } from 'node:child_process';
  7. import { writeFileSync, existsSync, mkdirSync, rmSync } from 'node:fs';
  8. import { dirname, join, resolve } from 'node:path';
  9. import { fileURLToPath } from 'node:url';
  10. import { launchBrowser } from './cdp.mjs';
  11. import { startIdent } from './identkit.mjs';
  12. // GATE_CLOCK=HH:MM (calendar mission 002): run the gate as if the local clock showed that time today — this process and
  13. // every page get Date shifted by the same amount (the server keeps its real clock; it only takes the UTC day for `soon`,
  14. // a −2…+9 day window). The reminder checks depend on the time of day; run them at 00:30 05:40 12:00 19:59 20:01 23:30.
  15. const CLOCK_SHIFT = (() => {
  16. const m = /^(\d\d):(\d\d)$/.exec(process.env.GATE_CLOCK || ''); if (!m) return 0;
  17. const n = new Date(); return new Date(n.getFullYear(), n.getMonth(), n.getDate(), Number(m[1]), Number(m[2])).getTime() - n.getTime();
  18. })();
  19. const CLOCK_SCRIPT = `(() => { const R = Date; class D extends R { constructor(...a) { if (a.length) super(...a); else super(R.now() + ${CLOCK_SHIFT}); } static now() { return R.now() + ${CLOCK_SHIFT}; } } globalThis.Date = D; })();`;
  20. if (CLOCK_SHIFT) (0, eval)(CLOCK_SCRIPT);
  21. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  22. const HERE = dirname(fileURLToPath(import.meta.url));
  23. const APP = resolve(HERE, '..');
  24. const PORT = Number(process.env.CALENDAR_GATE_PORT || 8700);
  25. const [CH_FROM, CH_TO] = (process.env.CALENDAR_GATE_CHROME || '8702-8709').split('-').map(Number);
  26. const IDENT_PORT = Number(process.env.CALENDAR_GATE_IDENT_PORT || 8701);
  27. const BASE = `http://127.0.0.1:${PORT}`;
  28. const STORE = join(APP, '.scratch', 'gate-store');
  29. const IDENT_DIR = process.env.CALENDAR_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));
  30. let ident = null;
  31. const SCRATCH = join(APP, '.scratch');
  32. const SESSIONS = join(SCRATCH, 'gate-sessions');
  33. rmSync(SESSIONS, { recursive: true, force: true });
  34. rmSync(STORE, { recursive: true, force: true });
  35. mkdirSync(SESSIONS, { recursive: true });
  36. let failures = 0, passes = 0;
  37. function check(label, ok, detail = '') {
  38. console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);
  39. if (ok) passes++; else failures++;
  40. }
  41. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  42. let spawnServer = null, log = '', server = null, browser = null, lastPage = null;
  43. async function stop() {
  44. if (ident) { try { await ident.stop(); } catch {} ident = null; }
  45. if (browser) { try { await browser.close(); } catch {} browser = null; }
  46. if (server) {
  47. try { server.kill('SIGTERM'); } catch {}
  48. await new Promise(r => { if (server.exitCode !== null || server.signalCode !== null) return r(); server.once('exit', r); setTimeout(r, 3000); });
  49. server = null;
  50. }
  51. }
  52. async function main() {
  53. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  54. const alice = await ident.signIn('[email protected]');
  55. const bob = await ident.signIn('[email protected]');
  56. const APPKEY = await ident.registerApp(alice, 'calendar (gate)', [BASE]);
  57. check('ident: our own ident runs (a copy without .env), the calendar is registered', /^pk_[0-9a-f]{32}$/.test(APPKEY.key) && !existsSync(join(STORE, 'ident', 'ident-code', '.env')));
  58. spawnServer = () => {
  59. server = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, env: { ...process.env, CALENDAR_PORT: String(PORT), CALENDAR_SESSIONS: SESSIONS + '/', CALENDAR_STORAGE: join(STORE, 'mpackdb'), CALENDAR_WATCH: '0',
  60. CALENDAR_PUBLIC_URL: BASE, IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: APPKEY.key, IDENT_API_SECRET: APPKEY.secret }, stdio: ['ignore', 'pipe', 'pipe'] });
  61. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  62. };
  63. spawnServer();
  64. for (let i = 0; ; i++) {
  65. try { if ((await fetch(BASE + '/')).ok) break; } catch {}
  66. if (i > 80) throw new Error('server did not come up\n' + log);
  67. await sleep(250);
  68. }
  69. // the app's first page is the month view, rendered on the server: 6 weeks of 7 days, one today
  70. const home = await (await fetch(BASE + '/')).text();
  71. check('server renders 42 days and one today', (home.match(/<li class=/g) || []).length === 42 && (home.match(/class="today"/g) || []).length === 1);
  72. browser = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });
  73. const page = await browser.newPage();
  74. lastPage = page;
  75. if (CLOCK_SHIFT) await page.addInitScript(CLOCK_SCRIPT);
  76. const SLOW = 3;
  77. const goto = page.goto.bind(page);
  78. page.goto = (u, o = {}) => goto(u, { ...o, timeout: 15000 * SLOW });
  79. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  80. await page.goto(BASE + '/');
  81. await page.waitForSelector('#month-title');
  82. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  83. const shot = async (name) => { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, `gate-${name}.png`), Buffer.from(data, 'base64')); };
  84. const ev = (e) => page.evaluate(e);
  85. const title = () => ev('document.querySelector("#month-title").textContent');
  86. const localToday = await ev(`(() => { const n = new Date(), p = x => String(x).padStart(2, '0'); return n.getFullYear() + '-' + p(n.getMonth() + 1) + '-' + p(n.getDate()); })()`);
  87. const expectTitle = (y, m) => ev(`new Intl.DateTimeFormat(navigator.language, { month: 'long' }).format(new Date(Date.UTC(${y}, ${m - 1}, 15, 12))) + ' ${y}'`);
  88. const [ty, tm] = localToday.split('-').map(Number);
  89. // ticket #6: the FIRST render (no mouse yet) already has the names, in the language of the request, when the server knows it
  90. const firstDays = await ev('[...document.querySelectorAll("#month-weekdays li")].map(l => l.textContent).join(" ")');
  91. const wantDays = await ev(`[1,2,3,4,5,6,7].map(i => new Intl.DateTimeFormat(navigator.language, { weekday: 'short' }).format(new Date(Date.UTC(2024, 0, i, 12)))).join(' ')`);
  92. if (/^(en|de|fr|es|it|nl|pt)/.test(await ev('navigator.language'))) check('first page already shows the weekday names in the browser language', firstDays === wantDays, firstDays + ' / ' + wantDays);
  93. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: 400, y: 300 }); // a real user's pointer reaches the month view
  94. await page.waitFor(`document.querySelector("#month-title").textContent.toLowerCase() === (${JSON.stringify(await expectTitle(ty, tm))}).toLowerCase()`, { label: 'title in the browser language' });
  95. check('title is the current month and year in the browser language', true);
  96. check('today is marked (browser date)', (await ev(`document.querySelector('li.today time').getAttribute('datetime')`)) === localToday, localToday);
  97. check('42 days, 6 weeks', (await ev('document.querySelectorAll("#month-days li").length')) === 42);
  98. const t0 = await title();
  99. // next / prev
  100. await page.click('#month-next');
  101. await page.waitFor(`document.querySelector("#month-title").textContent !== ${JSON.stringify(t0)}`, { label: 'next month' });
  102. const nm = tm === 12 ? 1 : tm + 1, ny = tm === 12 ? ty + 1 : ty;
  103. await page.waitFor(`document.querySelector("#month-title").textContent.toLowerCase() === ${JSON.stringify((await expectTitle(ny, nm)).toLowerCase())}`, { label: 'next month title' });
  104. check('next shows the next month', true);
  105. await page.click('#month-prev');
  106. await page.waitFor(`document.querySelector("#month-title").textContent === ${JSON.stringify(t0)}`, { label: 'prev month' });
  107. check('prev returns to the month, today marked again', (await ev('document.querySelectorAll("li.today").length')) === 1);
  108. // walk to February 2028 (leap year) and check its days and its first weekday (Tuesday)
  109. let guard = 0;
  110. const feb28 = (await expectTitle(2028, 2)).toLowerCase();
  111. while ((await title()).toLowerCase() !== feb28 && guard++ < 40) {
  112. const before = await title();
  113. await page.click('#month-next');
  114. await page.waitFor(`document.querySelector("#month-title").textContent !== ${JSON.stringify(before)}`, { label: 'paging' });
  115. }
  116. const feb = await ev(`(() => { const inM = [...document.querySelectorAll('month-view #month-days li:not(.outside) time')]; const first = document.querySelector('#month-days li:not(.outside)'); return { n: inM.length, col: [...first.parentNode.children].indexOf(first) % 7 }; })()`);
  117. check('Feb 2028: 29 days, the 1st is a Tuesday (column 2)', feb.n === 29 && feb.col === 1, JSON.stringify(feb));
  118. // year rollover: go back to December 2027 and January 2028 by prev
  119. await page.click('#month-prev');
  120. await page.click('#month-prev');
  121. const dec27 = (await expectTitle(2027, 12)).toLowerCase();
  122. await page.waitFor(`document.querySelector("#month-title").textContent.toLowerCase() === ${JSON.stringify(dec27)}`, { label: 'back to December' });
  123. const dec = await ev(`(() => ({ n: document.querySelectorAll('#month-days li:not(.outside)').length, col: [...document.querySelectorAll('#month-days li')].indexOf(document.querySelector('#month-days li:not(.outside)')) % 7 }))()`);
  124. check('Dec 2027: 31 days, the 1st is a Wednesday', dec.n === 31 && dec.col === 2, JSON.stringify(dec));
  125. check('no console errors', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  126. await languagePart();
  127. await shot('wide');
  128. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  129. await sleep(300);
  130. check('no horizontal overflow at 390 px', await ev('document.documentElement.scrollWidth <= window.innerWidth'));
  131. await shot('narrow');
  132. if (!process.env.GATE_SKIP_EVENTS) await eventsPart(page, { alice, bob, APPKEY });
  133. await remindersPart(page, { alice, APPKEY });
  134. }
  135. // ---- ticket calendar#2: login with ident, private events ------------------------------------------------------
  136. async function eventsPart(page, { alice, bob, APPKEY }) {
  137. const ev = (e) => page.evaluate(e);
  138. const J = JSON.stringify;
  139. // (a user's pointer reaches the month view first, and takes a moment before the click: the month view reads the browser then)
  140. const hydrated = async () => {
  141. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  142. const at = await page.evaluate(`(() => { const r = document.querySelector('#month-title').getBoundingClientRect(); return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) }; })()`);
  143. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: at.x, y: at.y });
  144. await sleep(700);
  145. };
  146. const setField = (sel, v) => ev(`(() => { const e = document.querySelector(${J(sel)}); e.value = ${J(v)}; e.dispatchEvent(new Event('input', { bubbles: true })); })()`);
  147. const pad = (n) => String(n).padStart(2, '0');
  148. const now = new Date();
  149. const ym = `${now.getFullYear()}-${pad(now.getMonth() + 1)}`;
  150. const day = (d) => `${ym}-${pad(d)}`;
  151. const cell = (d) => `#month-days li:has(time[datetime="${day(d)}"])`;
  152. const evTexts = (d) => ev(`[...document.querySelectorAll(${J(cell(d) + ' button.event')})].map(b => b.textContent)`);
  153. const editorOpen = () => ev(`document.querySelector('#eventeditor').classList.contains('open')`);
  154. const emitRaw = async (cookie, event, payload) => {
  155. const r = await fetch(BASE + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', cookie }, body: J({ t: 'emit', i: 1, event, payload }) });
  156. const t = await r.text(); let j = null; try { j = JSON.parse(t); } catch {}
  157. return j && j.value !== undefined ? j.value : t;
  158. };
  159. const loginAs = async (who) => {
  160. const code = await ident.selectorCode(who, APPKEY, BASE);
  161. await page.goto(BASE + '/login/callback?ident_code=' + code);
  162. await page.waitForSelector('#logout');
  163. await hydrated();
  164. };
  165. const cookieOf = async () => (await page.cookies([BASE])).map(c => c.name + '=' + c.value).join('; ');
  166. // signed out: no login, no editor, the faces refuse
  167. await page.goto(BASE + '/');
  168. await hydrated();
  169. check('signed out: "Log in with ident" shows', (await ev(`!!document.querySelector('#loginbutton')`)) && !(await ev(`!!document.querySelector('#logout')`)));
  170. await page.click(cell(15));
  171. await sleep(500);
  172. check('signed out: clicking a day opens no editor', !(await editorOpen()));
  173. const refused = await emitRaw('', 'calSave', [{ title: 'x', allDay: false, startDate: day(15), startTime: '09:00', endDate: '', endTime: '', place: '', notes: '', zone: 'UTC' }, day(1), day(28)]);
  174. check('signed out: the server refuses to save an event', refused && refused.error === 'log in with ident first', J(refused));
  175. let r = await fetch(BASE + '/login/callback', { redirect: 'manual' });
  176. check('login: /login/callback without a code → /login/failed', r.status === 302 && r.headers.get('location') === '/login/failed');
  177. // log in as alice, add an event on the 15th
  178. await loginAs(alice);
  179. check('logged in: "Log out" shows', await ev(`!!document.querySelector('#logout')`));
  180. await page.click(cell(15));
  181. await page.waitFor(`document.querySelector('#eventeditor').classList.contains('open')`, { label: 'editor opens' });
  182. await page.waitFor(`document.querySelector('#f-startdate').value === ${J(day(15))}`, { label: 'form shows the clicked date' });
  183. check('a click on a day opens the editor at that date', (await ev(`document.querySelector('#f-startdate').value`)) === day(15), await ev(`JSON.stringify([...document.querySelectorAll('#eventform input, #eventform textarea')].map(i => i.id + '=' + i.value))`));
  184. await page.click('#f-title');
  185. await page.type('#f-title', 'Dentist');
  186. await setField('#f-starttime', '18:00');
  187. await setField('#f-endtime', '19:00');
  188. await setField('#f-place', 'Dr. Huber');
  189. await setField('#f-notes', 'Bring the insurance card');
  190. check('typing into the title kept its focus and text', (await ev(`document.querySelector('#f-title').value`)) === 'Dentist');
  191. await page.click('#event-save');
  192. await page.waitFor(`document.querySelectorAll(${J(cell(15) + ' button.event')}).length === 1`, { label: 'event shows on its day' });
  193. check('the event shows on that day with its time', J(await evTexts(15)) === '["18:00 Dentist"]', J(await evTexts(15)));
  194. check('the editor closed after saving', !(await editorOpen()));
  195. // it survives a reload (server render for the signed-in user)
  196. await page.goto(BASE + '/');
  197. await hydrated();
  198. await page.waitFor(`document.querySelectorAll(${J(cell(15) + ' button.event')}).length === 1`, { label: 'event after reload' });
  199. check('after a reload the event is still there', J(await evTexts(15)) === '["18:00 Dentist"]');
  200. const html = await (await fetch(BASE + '/', { headers: { cookie: await cookieOf() } })).text();
  201. check('the server renders the event into the page for its owner', html.includes('18:00 Dentist'));
  202. check('a visitor without login gets no event in the page', !(await (await fetch(BASE + '/')).text()).includes('Dentist'));
  203. // edit
  204. const aliceEventId = await ev(`document.querySelector(${J(cell(15) + ' button.event')}).value`);
  205. await page.click(cell(15) + ' button.event');
  206. await page.waitFor(`document.querySelector('#eventeditor').classList.contains('open')`, { label: 'editor opens to edit' });
  207. check('a click on an event opens it with its values', (await ev(`[document.querySelector('#f-title').value, document.querySelector('#f-starttime').value, document.querySelector('#f-endtime').value, document.querySelector('#f-place').value, document.querySelector('#f-notes').value].join('|')`)) === 'Dentist|18:00|19:00|Dr. Huber|Bring the insurance card');
  208. await setField('#f-title', 'Dentist (moved)');
  209. await setField('#f-startdate', day(16));
  210. await setField('#f-enddate', day(16));
  211. await page.click('#event-save');
  212. await page.waitFor(`document.querySelectorAll(${J(cell(16) + ' button.event')}).length === 1`, { label: 'event moved' });
  213. check('editing moves and renames the event', J(await evTexts(16)) === '["18:00 Dentist (moved)"]' && (await evTexts(15)).length === 0, J([await evTexts(15), await evTexts(16)]));
  214. // all-day, several days
  215. await page.click(cell(20));
  216. await page.waitFor(`document.querySelector('#eventeditor').classList.contains('open')`, { label: 'editor opens (all day)' });
  217. await page.click('#kind-allday');
  218. await page.click('#f-title');
  219. await page.type('#f-title', 'Vacation');
  220. await setField('#f-enddate', day(22));
  221. check('all-day hides the time fields', !(await ev(`(() => { const e = document.querySelector('#f-starttime'); return e.offsetWidth > 0; })()`)));
  222. await page.click('#event-save');
  223. await page.waitFor(`document.querySelectorAll('#month-days button.event').length === 4`, { label: 'three all-day days' });
  224. check('an all-day event of three days shows on each day', J([await evTexts(20), await evTexts(21), await evTexts(22), await evTexts(23)]) === '[["Vacation"],["Vacation"],["Vacation"],[]]');
  225. // validation: the end before the start is refused with a message, nothing changes
  226. await page.click(cell(25));
  227. await page.waitFor(`document.querySelector('#eventeditor').classList.contains('open')`, { label: 'editor opens (bad)' });
  228. await page.click('#f-title');
  229. await page.type('#f-title', 'Backwards');
  230. await setField('#f-starttime', '10:00');
  231. await setField('#f-endtime', '09:00');
  232. await page.click('#event-save');
  233. await page.waitFor(`document.querySelector('#formerror').textContent.length > 0`, { label: 'error shows' });
  234. check('an end before the start is refused with a message', (await ev(`document.querySelector('#formerror').textContent`)).includes('before the start') && (await evTexts(25)).length === 0 && (await editorOpen()));
  235. await page.click('#event-cancel');
  236. check('cancel closes the editor', !(await editorOpen()));
  237. // paging loads the events of that month
  238. await page.click('#month-next');
  239. await page.waitFor(`document.querySelector('#month-title').textContent !== ${J(await ev(`document.querySelector('#month-title').textContent`))}`, { label: 'next month' });
  240. await page.click('#month-prev');
  241. await page.waitFor(`document.querySelectorAll('#month-days button.event').length === 4`, { label: 'events back after paging' });
  242. check('paging away and back shows the events again', true);
  243. // private: bob sees nothing of alice's and cannot change or delete them
  244. const aliceCookie = await cookieOf();
  245. await page.click('#logout');
  246. await page.waitForSelector('#loginbutton');
  247. await sleep(300);
  248. await page.goto(BASE + '/');
  249. await hydrated();
  250. check('after log out no event shows', (await ev(`document.querySelectorAll('#month-days button.event').length`)) === 0);
  251. await loginAs(bob);
  252. await page.goto(BASE + '/');
  253. await hydrated();
  254. await sleep(500);
  255. check("another identity does not see alice's events", (await ev(`document.querySelectorAll('#month-days button.event').length`)) === 0);
  256. const bobCookie = await cookieOf();
  257. const del = await emitRaw(bobCookie, 'calDelete', [aliceEventId, day(1), day(28)]);
  258. check("another identity cannot delete alice's event", del && del.error === 'no such event', J(del));
  259. const chg = await emitRaw(bobCookie, 'calSave', [{ id: aliceEventId, title: 'hacked', allDay: false, startDate: day(16), startTime: '09:00', endDate: '', endTime: '', place: '', notes: '', zone: 'UTC' }, day(1), day(28)]);
  260. check("another identity cannot change alice's event", chg && chg.error === 'no such event', J(chg));
  261. const rows = await emitRaw(bobCookie, 'calLoad', [day(1), day(28)]);
  262. check('another identity loads no events', rows && Array.isArray(rows.events) && rows.events.length === 0, J(rows));
  263. // validWindow / soonOf are plain (non-static) members of calendar.hl called from server faces (hybriel #115/#116, mission 048)
  264. const badWin = await emitRaw(bobCookie, 'calLoad', ['nope', day(28)]);
  265. check('the server refuses a window that is not two dates', badWin && badWin.error === 'not a date', J(badWin));
  266. const bad = await emitRaw(bobCookie, 'calSave', [{ title: '', allDay: false, startDate: 'nope', startTime: '09:00', endDate: '', endTime: '', place: '', notes: '', zone: 'UTC' }, day(1), day(28)]);
  267. check('the server validates an event strictly', bad && typeof bad.error === 'string' && bad.error.length > 0, J(bad));
  268. // alice again: her events are all there; delete one
  269. await page.click('#logout');
  270. await page.waitForSelector('#loginbutton');
  271. await sleep(300);
  272. await loginAs(alice);
  273. await page.goto(BASE + '/');
  274. await hydrated();
  275. await page.waitFor(`document.querySelectorAll('#month-days button.event').length === 4`, { label: 'alice events back' });
  276. check('logging in again shows her events', J(await evTexts(16)) === '["18:00 Dentist (moved)"]');
  277. { const { data } = await page.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(SCRATCH, 'gate-events-wide.png'), Buffer.from(data, 'base64')); }
  278. await page.click(cell(16) + ' button.event');
  279. await page.waitFor(`document.querySelector('#eventeditor').classList.contains('open')`, { label: 'editor opens to delete' });
  280. await page.click('#event-delete');
  281. await page.waitFor(`document.querySelectorAll(${J(cell(16) + ' button.event')}).length === 0`, { label: 'event deleted' });
  282. check('delete removes the event', (await evTexts(16)).length === 0 && !(await editorOpen()) && (await ev(`document.querySelectorAll('#month-days button.event').length`)) === 3);
  283. await page.goto(BASE + '/');
  284. await hydrated();
  285. await sleep(500);
  286. check('the deleted event stays gone after a reload', (await ev(`document.querySelectorAll('#month-days button.event').length`)) === 3);
  287. await page.send('Emulation.setDeviceMetricsOverride', { width: 390, height: 800, deviceScaleFactor: 1, mobile: true });
  288. await sleep(300);
  289. await page.click(cell(9));
  290. await page.waitFor(`document.querySelector('#eventeditor').classList.contains('open')`, { label: 'editor opens on a phone' });
  291. await sleep(200);
  292. const { data } = await page.send('Page.captureScreenshot', { format: 'png' });
  293. writeFileSync(join(SCRATCH, 'gate-editor-narrow.png'), Buffer.from(data, 'base64'));
  294. check('the editor fits a phone (no horizontal overflow)', await ev('document.documentElement.scrollWidth <= window.innerWidth'));
  295. // THE INSTALLABLE APP (ticket #3): manifest (served as manifest JSON, installable fields), icons, link, theme colour
  296. const mhref = await (async () => { const h = await (await fetch(BASE + '/')).text(); const m = h.match(/<link rel="manifest" href="([^"]+)"/); return m ? m[1] : null; })();
  297. check('the page head links the manifest', !!mhref, String(mhref));
  298. const mres = await fetch(BASE + (mhref || '/manifest.webmanifest'));
  299. const man = await mres.json();
  300. check('manifest is served as a web manifest with start_url, standalone display, name', /manifest\+json/.test(mres.headers.get('content-type') || '') && man.start_url === '/' && man.display === 'standalone' && !!man.name);
  301. const sizes = [];
  302. for (const ic of man.icons) { const r = await fetch(BASE + ic.src); const b = Buffer.from(await r.arrayBuffer()); sizes.push(r.ok && ic.type === 'image/png' && b.readUInt32BE(16) === Number(ic.sizes.split('x')[0])); }
  303. check('every icon of the manifest is a real PNG of its declared size (192 and 512, any and maskable)', sizes.length === 4 && sizes.every(Boolean) && man.icons.some(i => i.sizes === '512x512' && i.purpose === 'maskable'));
  304. await page.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  305. await page.goto(BASE + '/');
  306. await hydrated();
  307. // installable: Chrome finds the manifest, and hl:web's own service worker (offline = [ Calendar ]) is registered
  308. await page.waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && (r.active || r.installing || r.waiting)))`, { label: 'service worker registered' }).catch(() => {});
  309. await sleep(1500);
  310. const inst = await page.send('Page.getInstallabilityErrors');
  311. check('Chrome reports no installability error', (inst.installabilityErrors || []).length === 0, JSON.stringify(inst));
  312. check('a service worker is registered for the whole app', await ev(`navigator.serviceWorker.getRegistration().then(r => !!r && new URL(r.scope).pathname === '/')`));
  313. check('the page carries the theme colour', (await ev(`document.querySelector('meta[name="theme-color"]').getAttribute('content')`)) === '#191e23');
  314. check('no console errors during the event steps', page.problems().filter(m => !/favicon|Failed to load resource/.test(m.text)).length === 0, page.dumpConsole());
  315. }
  316. // ---- calendar#6 through hybriel #105: the page reads `headers['accept-language']` (no framework patch) ------------------
  317. // A fresh tab per language; its Accept-Language is set by CDP and the BROWSER's own language (Intl locale and
  318. // navigator.language) is set to the OTHER one, so
  319. // the names can only come from the request header. First page (no pointer yet), then two pages forward and one back
  320. // with a real pointer: the names stay in the header's language.
  321. async function languagePart() {
  322. const NAMES = {
  323. de: { months: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember'], days: 'Mo Di Mi Do Fr Sa So' },
  324. en: { months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'], days: 'Mon Tue Wed Thu Fri Sat Sun' },
  325. };
  326. for (const [lang, header, other] of [['de', 'de-DE,de;q=0.9,en;q=0.8', 'en-US'], ['en', 'en-US,en;q=0.9,de;q=0.8', 'de-DE']]) {
  327. const p = await browser.newPage();
  328. try {
  329. if (CLOCK_SHIFT) await p.addInitScript(CLOCK_SCRIPT);
  330. await p.send('Network.enable');
  331. await p.send('Network.setExtraHTTPHeaders', { headers: { 'Accept-Language': header } });
  332. await p.send('Emulation.setLocaleOverride', { locale: other });
  333. // navigator.language follows the machine (German on Loreana), not the override: pin it to the other language too
  334. await p.addInitScript(`Object.defineProperty(Navigator.prototype, 'language', { get: () => ${JSON.stringify(other)} }); Object.defineProperty(Navigator.prototype, 'languages', { get: () => [${JSON.stringify(other)}] });`);
  335. await p.goto(BASE + '/', { timeout: 45000 });
  336. await p.waitForSelector('#month-title');
  337. await p.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated (' + lang + ')' });
  338. const t = NAMES[lang];
  339. const seen = async () => ({ title: await p.evaluate('document.querySelector("#month-title").textContent'), days: await p.evaluate('[...document.querySelectorAll("#month-weekdays li")].map(l => l.textContent).join(" ")') });
  340. const monthOf = (title) => t.months.indexOf(title.replace(/ \d{4}$/, ''));
  341. const first = await seen();
  342. const m0 = monthOf(first.title);
  343. const own = await p.evaluate('navigator.language + " / Intl " + Intl.DateTimeFormat().resolvedOptions().locale');
  344. check(`language ${lang}: first page (browser itself: ${own}) has ${lang} names`, m0 >= 0 && first.days === t.days && !own.startsWith(lang) && own.endsWith('Intl ' + other), JSON.stringify(first) + ' ' + own);
  345. // the server's own document (before any script): the names are in it
  346. const html = await (await fetch(BASE + '/', { headers: { 'accept-language': header } })).text();
  347. const days = [...html.matchAll(/<li>([^<]*)<\/li>/g)].map(x => x[1]).slice(0, 7).join(' ');
  348. check(`language ${lang}: the server's HTML for Accept-Language ${header} carries ${lang} weekday names`, days === t.days, days);
  349. const steps = [['#month-next', 1], ['#month-next', 2], ['#month-prev', 1]];
  350. let ok = true, trail = [];
  351. for (const [btn, off] of steps) {
  352. const before = (await seen()).title;
  353. await p.click(btn); // a real pointer: the browser's own language would be read now if the server had not known one
  354. await p.waitFor(`document.querySelector("#month-title").textContent !== ${JSON.stringify(before)}`, { label: 'paging ' + lang });
  355. const now = await seen();
  356. trail.push(now.title + ' / ' + now.days);
  357. if (monthOf(now.title) !== (m0 + off) % 12 || now.days !== t.days) ok = false;
  358. }
  359. check(`language ${lang}: after paging (next, next, prev) the names are still ${lang}`, ok, trail.join(' | '));
  360. } finally { await p.close(); }
  361. }
  362. }
  363. // ---- ticket calendar#4: reminders and notifications, also offline -------------------------------------------------
  364. async function remindersPart(page, { alice, APPKEY }) {
  365. const ev = (e) => page.evaluate(e);
  366. const J = JSON.stringify;
  367. const pad = (n) => String(n).padStart(2, '0');
  368. const hydrated = async () => {
  369. await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { timeout: 30000, label: 'hydrated' });
  370. const at = await page.evaluate(`(() => { const r = document.querySelector('#month-title').getBoundingClientRect(); return { x: Math.round(r.x + r.width / 2), y: Math.round(r.y + r.height / 2) }; })()`);
  371. await page.send('Input.dispatchMouseEvent', { type: 'mouseMoved', x: at.x, y: at.y });
  372. await sleep(700);
  373. };
  374. const setField = (sel, v, type = 'input') => ev(`(() => { const e = document.querySelector(${J(sel)}); e.value = ${J(v)}; e.dispatchEvent(new Event(${J(type)}, { bubbles: true })); })()`);
  375. const dateOf = (d) => `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}`;
  376. const timeOf = (d) => `${pad(d.getHours())}:${pad(d.getMinutes())}`;
  377. const shown = () => ev(`document.querySelector('#notify-planned').textContent`);
  378. const notices = () => ev(`navigator.serviceWorker.getRegistration().then(r => r.getNotifications()).then(l => l.map(n => n.title + '|' + n.body))`);
  379. const cell = (d) => `#month-days li:has(time[datetime="${dateOf(d)}"])`;
  380. const openEditorOn = async (start) => {
  381. await ev(`document.querySelector(${J(cell(start) + ' time')}).click()`); // the day number: an event chip in the middle would edit that event
  382. await page.waitFor(`document.querySelector('#eventeditor').classList.contains('open')`, { label: 'editor opens' });
  383. await setField('#f-startdate', dateOf(start));
  384. await setField('#f-starttime', timeOf(start));
  385. await setField('#f-enddate', '');
  386. await setField('#f-endtime', '');
  387. const t = await ev(`document.querySelector('#f-title').value`);
  388. check('a new event starts with an empty title', t === '', J(t));
  389. };
  390. const addEvent = async (name, start, own) => {
  391. await openEditorOn(start);
  392. await setField('#f-title', name);
  393. if (own) {
  394. await page.click('#rem-own');
  395. await ev(`document.querySelectorAll('#rem-rows reminder-row button').forEach((b, i) => { if (i > 0) b.click(); })`);
  396. await sleep(300);
  397. await setField('#rem-rows reminder-row select', 'minutes', 'change');
  398. await setField('#rem-rows reminder-row input[type=number]', String(own), 'change');
  399. }
  400. await page.click('#event-save');
  401. await page.waitFor(`!document.querySelector('#eventeditor').classList.contains('open')`, { label: 'editor closed after save', timeout: 15000 });
  402. };
  403. const wanted = async (titles, ms) => {
  404. const t0 = Date.now(); let got = [];
  405. while (Date.now() - t0 < ms) { got = await notices(); if (titles.every(t => got.some(g => g.startsWith(t + '|')))) return got; await sleep(2000); }
  406. return got;
  407. };
  408. await page.send('Browser.grantPermissions', { origin: BASE, permissions: ['notifications'] });
  409. const code = await ident.selectorCode(alice, APPKEY, BASE);
  410. await page.goto(BASE + '/login/callback?ident_code=' + code);
  411. await page.waitForSelector('#logout');
  412. await hydrated();
  413. await page.waitFor(`navigator.serviceWorker.getRegistration().then(r => !!(r && r.active))`, { label: 'service worker active', timeout: 30000 });
  414. check('reminders: notifications are allowed, so no "Turn on notifications" button', await ev(`document.querySelector('#notify-ask').classList.contains('hidden')`) && await ev(`document.querySelector('#notify-blocked').classList.contains('hidden')`));
  415. // THE CALENDAR SETTINGS: the defaults are 1 hour before and the day before at 20:00
  416. await page.click('#settings-open');
  417. await page.waitFor(`document.querySelector('#settingseditor').classList.contains('open') && document.querySelectorAll('#set-rows reminder-row').length === 2`, { label: 'settings open with two rows' });
  418. const rowsOf = (sel) => ev(`[...document.querySelectorAll(${J(sel + ' reminder-row')})].map(r => [r.querySelector('input[type=number]').value, r.querySelector('select').value, r.querySelector('input[type=time]').value].join(' '))`);
  419. const first = await rowsOf('#set-rows');
  420. check('settings: the default reminders are 1 hour before and the day before at 20:00', first[0] === '1 hours 09:00' && first[1] === '1 days 20:00', J(first));
  421. await page.click('#set-cancel');
  422. // THE TICKET'S FIRST TEST: an event 70 minutes from now — with the defaults, one reminder (1 hour before) is planned
  423. const in70 = new Date(Date.now() + 70 * 60000);
  424. await addEvent('Bus to the lake', in70);
  425. const dayBefore = new Date(in70.getFullYear(), in70.getMonth(), in70.getDate() - 1, 20, 0, 0).getTime() > Date.now() ? 1 : 0;
  426. await page.waitFor(`document.querySelector('#notify-planned').textContent.length > 0`, { label: 'reminders planned' });
  427. const want = 1 + dayBefore;
  428. check('an event 70 minutes ahead gets the default reminders planned', (await shown()) === (want === 1 ? '1 reminder set for the next 7 days' : want + ' reminders set for the next 7 days'), await shown());
  429. // an event in another time zone: 30 minutes ahead in Tokyo → its 1-hour reminder is already past, whatever this browser's zone
  430. const tokyo = (t) => new Intl.DateTimeFormat('sv-SE', { timeZone: 'Asia/Tokyo', year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }).format(t).replace(' ', 'T');
  431. const browserZone = await ev('Intl.DateTimeFormat().resolvedOptions().timeZone');
  432. const tk = tokyo(new Date(Date.now() + 30 * 60000));
  433. const cookie = (await page.cookies([BASE])).map(c => c.name + '=' + c.value).join('; ');
  434. const win = [dateOf(new Date(Date.now() - 86400000)), dateOf(new Date(Date.now() + 86400000 * 5))];
  435. const emitRaw = async (event, payload) => {
  436. const r = await fetch(BASE + '/__hl/emit', { method: 'POST', headers: { 'content-type': 'application/json', cookie }, body: J({ t: 'emit', i: 1, event, payload }) });
  437. const j = JSON.parse(await r.text()); return j.value;
  438. };
  439. const tkHour = Number(tk.slice(11, 13));
  440. if (browserZone !== 'Asia/Tokyo' && tkHour < 19) {
  441. const saved = await emitRaw('calSave', [{ title: 'Tokyo call', allDay: false, startDate: tk.slice(0, 10), startTime: tk.slice(11, 16), endDate: '', endTime: '', place: '', notes: '', zone: 'Asia/Tokyo', custom: false, reminders: [] }, win[0], win[1]]);
  442. await page.goto(BASE + '/');
  443. await hydrated();
  444. await sleep(500);
  445. check('a time zone is honoured: 30 minutes ahead in Tokyo has no 1-hour reminder left', (await shown()) === (want === 1 ? '1 reminder set for the next 7 days' : want + ' reminders set for the next 7 days') && !saved.error, (await shown()) + ' ' + J(saved && saved.error));
  446. } else { console.log('skip Tokyo zone check (browser in Tokyo, or Tokyo evening)'); }
  447. // OWN REMINDERS: switch to "Own", the calendar's two rows are the start; drop one; it is kept
  448. const later = new Date(Date.now() + 5 * 3600000);
  449. await openEditorOn(later);
  450. await setField('#f-title', 'Own reminders');
  451. check('the editor offers "Calendar\'s" reminders first, in words', (await ev(`document.querySelector('#rem-default-text').textContent`)) === '1 hour before, the day before at 20:00');
  452. await page.click('#rem-own');
  453. await page.waitFor(`document.querySelectorAll('#rem-rows reminder-row').length === 2`, { label: 'own rows start from the calendar\'s' });
  454. await page.click('#rem-add');
  455. await page.waitFor(`document.querySelectorAll('#rem-rows reminder-row').length === 3`, { label: 'row added' });
  456. await setField('#rem-rows reminder-row:nth-child(3) input[type=number]', '15', 'change');
  457. await ev(`document.querySelector('#rem-rows reminder-row:nth-child(2) button').click()`);
  458. await page.waitFor(`document.querySelectorAll('#rem-rows reminder-row').length === 2`, { label: 'row removed' });
  459. const own = await rowsOf('#rem-rows');
  460. check('own reminders: add, change and remove a row', own[0] === '1 hours 09:00' && own[1] === '15 minutes 09:00', J(own));
  461. await page.click('#event-save');
  462. await page.waitFor(`!document.querySelector('#eventeditor').classList.contains('open')`, { label: 'saved' });
  463. await page.goto(BASE + '/');
  464. await hydrated();
  465. await page.click(`${cell(later)} button.event:last-child`).catch(() => {});
  466. await sleep(300);
  467. const evList = await emitRaw('calLoad', [win[0], win[1]]);
  468. const stored = (evList.events || []).find(e => e.title === 'Own reminders');
  469. check('the server keeps the own reminders as WorldAPI $reminders rows', stored && stored.custom === true && stored.rows.length === 2 && stored.rows[1].unit === 'minutes' && stored.rows[1].n === '15', J(stored));
  470. const plain = (evList.events || []).find(e => e.title === 'Bus to the lake');
  471. check('an event without its own reminders inherits (custom = false)', plain && plain.custom === false, J(evList.events));
  472. check('calLoad answers the soon list (soonOf, a plain member called from a face)', Array.isArray(evList.soon) && evList.soon.length > 0, J(evList.soon));
  473. const bad = await emitRaw('calSave', [{ title: 'x', allDay: false, startDate: dateOf(later), startTime: '10:00', endDate: '', endTime: '', place: '', notes: '', zone: 'UTC', custom: true, reminders: [{ unit: 'minutes', n: '-5', time: '' }] }, win[0], win[1]]);
  474. check('a bad reminder is refused by the server', bad && bad.error, J(bad));
  475. const badSet = await emitRaw('calSettingsSave', [[{ unit: 'weeks', n: '1', time: '' }]]);
  476. check('bad default reminders are refused', badSet && badSet.error, J(badSet));
  477. // SETTINGS SAVED: only "1 minute before"
  478. await page.goto(BASE + '/');
  479. await hydrated();
  480. await page.click('#settings-open');
  481. await page.waitFor(`document.querySelectorAll('#set-rows reminder-row').length === 2`, { label: 'settings rows' });
  482. await ev(`document.querySelector('#set-rows reminder-row:nth-child(2) button').click()`);
  483. await page.waitFor(`document.querySelectorAll('#set-rows reminder-row').length === 1`, { label: 'one row' });
  484. await setField('#set-rows reminder-row select', 'minutes', 'change');
  485. await setField('#set-rows reminder-row input[type=number]', '1', 'change');
  486. await page.click('#set-save');
  487. await page.waitFor(`!document.querySelector('#settingseditor').classList.contains('open')`, { label: 'settings saved' });
  488. await page.goto(BASE + '/');
  489. await hydrated();
  490. await page.click('#settings-open');
  491. await page.waitFor(`document.querySelectorAll('#set-rows reminder-row').length === 1`, { label: 'settings reload' });
  492. check('settings are kept: 1 minute before', J(await rowsOf('#set-rows')) === '["1 minutes 09:00"]', J(await rowsOf('#set-rows')));
  493. await page.click('#set-cancel');
  494. // NOTIFICATIONS ON TIME: A inherits (1 minute before the start), B has its own (2 minutes before)
  495. await addEvent('Inherits the default', new Date(Date.now() + 3 * 60000));
  496. await addEvent('Has its own reminder', new Date(Date.now() + 4 * 60000), 2);
  497. check('reminders are planned for both', Number((await shown()).split(' ')[0]) >= 4, await shown());
  498. const got = await wanted(['Inherits the default', 'Has its own reminder'], 240000);
  499. check('the notifications came on time, the default one saying "Starts in 1 minute"', got.includes('Inherits the default|Starts in 1 minute') && got.some(g => g.startsWith('Has its own reminder|Starts in 2 minutes')), J(got));
  500. // OFFLINE: the server is gone; an event with a reminder is added anyway and its notification still comes
  501. server.kill('SIGTERM');
  502. await new Promise(r => { server.once('exit', r); setTimeout(r, 3000); });
  503. await page.waitFor(`window.__hl.socket == null || window.__hl.socket.readyState !== 1`, { label: 'socket closed', timeout: 20000 });
  504. // the count only holds reminders still to come (the ones that fired are gone once the page counts again): the three
  505. // still waiting (Bus to the lake, the two of Own reminders) plus the new one; that it FIRES is the next check
  506. await addEvent('Added offline', new Date(Date.now() + 3 * 60000));
  507. check('offline: the event shows on its day and its reminder is planned', Number((await shown()).split(' ')[0]) >= 4, await shown());
  508. const got2 = await wanted(['Added offline'], 200000);
  509. check('offline: the notification still comes', got2.some(g => g.startsWith('Added offline|Starts in 1 minute')), J(got2));
  510. // back online: the queued save reaches the server
  511. spawnServer();
  512. let saved = false;
  513. for (let i = 0; i < 60 && !saved; i++) {
  514. await sleep(1500);
  515. try { const l = await emitRaw('calLoad', [win[0], win[1]]); saved = (l.events || []).some(e => e.title === 'Added offline'); } catch {}
  516. }
  517. check('back online: the event saved while offline reaches the server', saved);
  518. check('no console errors in the reminder steps', page.problems().filter(m => !/favicon|Failed to load resource|WebSocket|ERR_|calSave did not reach/.test(m.text)).length === 0, page.dumpConsole());
  519. }
  520. try { await main(); } catch (e) { check('gate ran', false, String(e && e.stack || e)); }
  521. if (failures) console.log('---- server log (tail)\n' + log.slice(-3000) + (lastPage ? '\n---- browser console\n' + lastPage.dumpConsole() : ''));
  522. await stop();
  523. if (CLOCK_SHIFT) console.log('clock: GATE_CLOCK ' + process.env.GATE_CLOCK + ' (shift ' + Math.round(CLOCK_SHIFT / 60000) + ' min), now ' + new Date().toString());
  524. console.log(`${passes} passed, ${failures} failed`);
  525. process.exit(failures ? 1 : 0);

Branches

Latest commits

  • 54fb0ce1calendar mission 002 (1/2): gate clock override GATE_CLOCK=HH:MM (this process and every page get Date shifted to that local time today)mre
  • c838ee79mission brief 002mre
  • f2bc67ecdocker-compose: init: true (hybriel#156, PID 1 ignored SIGTERM, every restart waited 10 s)mre
  • 2881119fcalendar mission 001 (4/4): code order — README layout + same-output test, STATUS, LOG, report; tests/letcount.py (sub-folders), tests/realdata-baseline.mjs, tests/realdata-compare.pymre
  • 3b2a4cd0calendar mission 001 (3/4): code order — let only where reassigned (147 dropped incl. components/month-view; 110 left: 67 reassigned, 43 loop-bound); gates 78/0 (3 of 4 runs; 1 known 'next month' flake) + 18/0, live-data run = step 2mre
  • f5ce6b1dcalendar mission 001 (2/4): code order — topics, map, thin faces: lib/util.hl, lib/events(-helpers).hl (+calendarView/settingsView/soonOf), lib/settings.hl, lib/users.hl (+userOfLoginCode, tagOf), lib/api(-helpers).hl; project.hl = map; login route takes &req/&sessions (failed-login reason now kept); gates 78/0 + 18/0mre
  • c6fbd011calendar mission 001 (1/4): code order — files moved: lib/events.hl, lib/users.hl, components/styles.hl (imports only); gates 78/0 + 18/0, live-data run identicalmre
  • d6c59290calendar: Hybriel master 06617221 (plugin allocators 3a781359 + 413f60e4, mpackdb 2cb7ae5e, http1 773de63e); gates 78/0 + 18/0mre
  • 7bd0337ccalendar: Hybriel master 190aa11d (fc838894 GC correctness, #126 closure scopes, #127); gates 78/0 + 18/0mre
  • ff41310ccalendar: Hybriel master 8efba065 (#126 memory, #48 lambda copy; audit: no & needed)mre
  • 14ba08c7antcolony#40: mission references point to the moved missionsmre
  • 99c73346antcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre
  • 76edaa62calendar: Hybriel master ff51cf46 (re-vendor round, static workaround removed)mre
  • 90a3fc2cdeploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre
  • 6722b72ddeploy.sh: never send .git or .gitignore to Byrodinmre
  • be099807State of 2026-09-27, before the move to gitoriamre