aboutsummaryrefslogtreecommitdiffstats
path: root/tools/thread-like-count-test.js
diff options
context:
space:
mode:
Diffstat (limited to 'tools/thread-like-count-test.js')
-rw-r--r--tools/thread-like-count-test.js91
1 files changed, 91 insertions, 0 deletions
diff --git a/tools/thread-like-count-test.js b/tools/thread-like-count-test.js
new file mode 100644
index 0000000..6d81b3f
--- /dev/null
+++ b/tools/thread-like-count-test.js
@@ -0,0 +1,91 @@
+// The heart's number in a thread matches the people the who-panel lists.
+// A thread remembers its counts between visits; a reaction that arrived
+// through the feed's own count fetch before the thread was opened again
+// must raise the remembered number, not be outvoted by it.
+// Run: bun tools/thread-like-count-test.js
+import assert from 'node:assert/strict';
+import puppeteer from './puppeteer.js';
+import { generateSecretKey, finalizeEvent } from 'nostr-tools/pure';
+import { nip19 } from 'nostr-tools';
+import { buildHtml } from '../build.js';
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const sk = generateSecretKey(), now = Math.floor(Date.now() / 1000);
+const notes = Array.from({ length: 12 }, (_, i) => finalizeEvent({ kind: 1, created_at: now - 60 - i * 60, tags: [],
+ content: `Post number ${i}. The tide was out and the gulls had the whole beach to themselves.` }, sk));
+const target = notes[0];
+const react = (n) => finalizeEvent({ kind: 7, created_at: now - 30 + n, content: '+', tags: [['e', target.id], ['p', target.pubkey]] }, generateSecretKey());
+const reactions = [react(1), react(2)];
+const profile = finalizeEvent({ kind: 0, created_at: now, tags: [], content: JSON.stringify({ name: 'Poster' }) }, sk);
+const html = await buildHtml({ minify: true, pwa: false });
+const snapshot = JSON.stringify({ version: 1, generatedAt: Date.now(), notes, profiles: [profile], popUntil: now - 3600 });
+const server = Bun.serve({ port: 0, fetch: (req) => new URL(req.url).pathname === '/api/feed'
+ ? new Response(snapshot, { headers: { 'content-type': 'application/json' } })
+ : new Response(html, { headers: { 'content-type': 'text/html; charset=utf-8' } }) });
+const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox'] });
+try {
+ const page = await browser.newPage();
+ const errors = [];
+ page.on('pageerror', (e) => errors.push(String(e)));
+ await page.setViewport({ width: 390, height: 844, isMobile: true, hasTouch: true });
+ await page.setRequestInterception(true);
+ page.on('request', (r) => r.url().startsWith(server.url.origin) ? r.continue() : r.abort());
+ // The relay serves as many of the two reactions as localStorage says
+ // (one on the first visit, both on the second).
+ await page.evaluateOnNewDocument(([notes, profile, reactions]) => {
+ class FakeSocket extends EventTarget {
+ constructor(url) { super(); this.url = url; this.readyState = 0; this.subs = new Set();
+ setTimeout(() => { this.readyState = 1; this.emit('open', new Event('open')); }, 0); }
+ emit(type, ev) { this.dispatchEvent(ev); this['on' + type]?.(ev); }
+ message(d) { this.emit('message', new MessageEvent('message', { data: JSON.stringify(d) })); }
+ send(raw) {
+ let m; try { m = JSON.parse(raw); } catch { return; }
+ if (m[0] === 'CLOSE') { this.subs.delete(m[1]); return; }
+ if (m[0] !== 'REQ') return;
+ const [, id, f] = m; this.subs.add(id);
+ const n = Number(localStorage.getItem('test-reactions') || 1);
+ let evs = [];
+ if (f.kinds?.includes(1) && !f.since) evs = notes.filter((e) => (!f.until || e.created_at <= f.until)
+ && (!f.authors || f.authors.includes(e.pubkey)) && (!f.ids || f.ids.includes(e.id))).slice(0, f.limit || 100);
+ if (f.kinds?.includes(0) && f.authors?.includes(profile.pubkey)) evs = [profile];
+ if (f['#e']) evs = f.kinds?.includes(7) ? reactions.slice(0, n).filter((r) => f['#e'].includes(r.tags[0][1])) : [];
+ if (f.ids) evs = notes.filter((e) => f.ids.includes(e.id));
+ setTimeout(() => { if (!this.subs.has(id)) return; for (const e of evs) this.message(['EVENT', id, e]); this.message(['EOSE', id]); }, 30);
+ }
+ close() { this.readyState = 3; this.emit('close', new Event('close')); }
+ }
+ Object.assign(FakeSocket, { CONNECTING: 0, OPEN: 1, CLOSING: 2, CLOSED: 3 });
+ window.WebSocket = FakeSocket;
+ }, [notes, profile, reactions]);
+ const heartSel = (scope, id) => `${scope} .note-post[data-zap-post="${id}"] .note-acts > .note-act:nth-child(4) .note-act-n`;
+ const heart = (scope, id) => page.evaluate((s) => document.querySelector(s)?.textContent || '', heartSel(scope, id));
+ const openRow = (id) => page.evaluate((id) => document.querySelector('.notes-feed .note-post[data-zap-post="' + id + '"] > .note-content > .note-text').click(), id);
+ const visit = async (n, path = '/feed') => {
+ await page.goto(server.url.origin + '/feed', { waitUntil: 'domcontentloaded' });
+ await page.evaluate((n) => localStorage.setItem('test-reactions', String(n)), n);
+ await page.goto(server.url.origin + path, { waitUntil: 'domcontentloaded' });
+ };
+ // first visit: the thread itself, from a link (a notification, say), with
+ // one heart on the relay — the count answer lands while the thread is
+ // open, so the thread remembers it
+ await visit(1, '/' + nip19.neventEncode({ id: target.id }));
+ await page.waitForFunction((s) => document.querySelector(s)?.textContent === '1', { timeout: 15000 }, heartSel('.thread-page', target.id));
+ await sleep(1500); // the thread is persisted
+ // second visit: the feed, where the count fetch brings both hearts; the
+ // thread is then opened from the row
+ await visit(2);
+ await page.waitForFunction(() => document.querySelectorAll('.notes-feed > [data-zap-post]').length >= 5, { timeout: 20000 });
+ await page.waitForFunction((s) => document.querySelector(s)?.textContent === '2', { timeout: 10000 }, heartSel('.notes-feed', target.id));
+ await openRow(target.id);
+ await page.waitForFunction((s) => document.querySelector(s), { timeout: 10000 }, heartSel('.thread-page', target.id));
+ await sleep(800);
+ const n = await heart('.thread-page', target.id);
+ const who = await page.evaluate((id) => {
+ const row = document.querySelector('.thread-page .note-post[data-zap-post="' + id + '"]');
+ row.querySelector('.note-acts > .note-act:last-child').click();
+ return new Promise((r) => setTimeout(() => r(row.querySelectorAll('.note-who-person').length), 300));
+ }, target.id);
+ assert.equal(who, 2, 'the panel lists both people');
+ assert.equal(n, '2', `the heart in the thread says 2, not the remembered 1 (got "${n}")`);
+ assert.deepEqual(errors, []);
+ console.log('✓ the thread\'s heart count catches up with the people who reacted');
+} finally { await browser.close(); server.stop(true); }