// Scheduled posts: the composer's clock button picks a time; Schedule signs // the note with that created_at and hands it to the notifier (POST // nwcpush /schedule), nothing goes to a relay, the composer closes and the // post waits in a "Scheduled" list, where Cancel sends a kind 5 for it to // /schedule/cancel. The notifier is stubbed. // Run: bun tools/scheduled-post-test.js import puppeteer from './puppeteer.js'; import { verifyEvent } from 'nostr-tools/pure'; import { buildHtml } from '../build.js'; const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); let ok = true; const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; }; const html = await buildHtml({ minify: true, pwa: false }); const server = Bun.serve({ port: 5316, fetch: (req) => { const p = new URL(req.url).pathname; if (p === '/verify-worker.js' || p.startsWith('/punks')) return new Response(Bun.file('dist' + p)); return new Response(html, { headers: { 'content-type': 'text/html' } }); } }); const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox'] }); const page = await browser.newPage(); await page.evaluateOnNewDocument(() => { window.__published = []; const Real = window.WebSocket; window.WebSocket = function (...a) { const ws = new Real(...a); const send = ws.send.bind(ws); ws.send = (d) => { try { const m = JSON.parse(d); if (m[0] === 'REQ') { setTimeout(() => ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EOSE', m[1]]) })), 0); return; } if (m[0] === 'EVENT') { window.__published.push(m[1]); setTimeout(() => ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['OK', m[1].id, true, '']) })), 0); return; } } catch {} return send(d); }; return ws; }; window.WebSocket.prototype = Real.prototype; Object.assign(window.WebSocket, Real); }); const held = new Map(); const calls = []; await page.setRequestInterception(true); page.on('request', (r) => { const u = new URL(r.url()); if (u.host !== 'nwcpush.coinos.io' || !u.pathname.startsWith('/schedule')) return r.continue(); const cors = { 'access-control-allow-origin': '*', 'access-control-allow-headers': 'content-type' }; if (r.method() === 'OPTIONS') return r.respond({ status: 200, headers: cors, body: '' }); const body = r.postData() ? JSON.parse(r.postData()) : null; calls.push({ path: u.pathname, body }); let res = { ok: true }; if (u.pathname === '/schedule') held.set(body.event.id, body.event); if (u.pathname === '/schedule/cancel') { let n = 0; for (const [k, id] of body.event.tags) if (k === 'e' && held.delete(id)) n++; res = { ok: true, cancelled: n }; } if (u.pathname === '/schedule/status') res = Object.fromEntries(u.searchParams.get('ids').split(',').map((id) => [id, held.has(id) ? 'pending' : 'gone'])); r.respond({ status: 200, headers: { ...cors, 'content-type': 'application/json' }, body: JSON.stringify(res) }); }); const errs = []; page.on('pageerror', (e) => errs.push(String(e))); const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t); const waitText = async (x, ms = 25000) => { for (let i = 0; i < ms / 250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; }; const waitFor = async (fn, ms = 15000, arg) => { for (let i = 0; i < ms / 200; i++) { if (await page.evaluate(fn, arg)) return true; await sleep(200); } return false; }; try { await page.setViewport({ width: 390, height: 844 }); await page.goto('http://localhost:5316/', { waitUntil: 'domcontentloaded' }); await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest')); await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(400); await click('create a new wallet'); await sleep(600); await page.waitForSelector('.words .w .t'); await click('skip verification'); await waitText('receive', 20000); await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]')?.click()); await waitFor(() => !!document.querySelector('.feed-post-fab'), 15000); await page.evaluate(() => document.querySelector('.feed-post-fab').click()); await waitFor(() => !!document.querySelector('.post-input'), 8000); await page.focus('.post-input'); await page.keyboard.type('later, #coinos', { delay: 10 }); await page.evaluate(() => document.querySelector('.post-actions button[aria-label="Schedule for later"]').click()); check('the clock button shows a time field, about an hour ahead', await waitFor(() => !!document.querySelector('.sched-pick input[type=datetime-local]'), 5000)); const shown = await page.$eval('.sched-pick input', (e) => e.value); const shownAt = new Date(shown).getTime(); check('...on a quarter hour', shownAt - Date.now() > 3500_000 && shownAt - Date.now() < 4500_000 && new Date(shownAt).getMinutes() % 15 === 0, shown); check('the main button reads Schedule', await page.evaluate(() => document.querySelector('.post-actions .btn-primary').textContent.trim() === 'Schedule')); // two hours ahead, typed as the user would const want = new Date(Date.now() + 2 * 3600_000); want.setSeconds(0, 0); const local = new Date(want.getTime() - want.getTimezoneOffset() * 60000).toISOString().slice(0, 16); await page.evaluate((v) => { const i = document.querySelector('.sched-pick input'); i.value = v; i.dispatchEvent(new Event('input', { bubbles: true })); }, local); await page.evaluate(() => { window.__published = []; document.querySelector('.post-actions .btn-primary').click(); }); await waitFor(() => !document.querySelector('.post-input'), 8000); const sc = calls.find((c) => c.path === '/schedule'); const ev = sc && sc.body.event; check('the notifier gets a signed kind 1 dated at the chosen time', !!ev && ev.kind === 1 && verifyEvent(ev) && ev.created_at === Math.floor(want.getTime() / 1000), ev && new Date(ev.created_at * 1000).toISOString()); check('...with its tags (t coinos, client) and the relays to send it to', !!ev && ev.tags.some((x) => x[0] === 't' && x[1] === 'coinos') && ev.tags.some((x) => x[0] === 'client') && sc.body.relays.length > 0, JSON.stringify(sc?.body.relays)); check('nothing went to a relay', !(await page.evaluate(() => window.__published.some((e) => e.kind === 1)))); check('the composer closed and the draft is cleared', await page.evaluate(() => !document.querySelector('.post-input'))); check('the post is not in the feed yet', await page.evaluate(() => !document.body.innerText.includes('later, #coinos') || !!document.querySelector('.sched-list')) && !(await page.evaluate(() => [...document.querySelectorAll('.note-text')].some((n) => n.textContent.includes('later, #coinos'))))); // the list shows with the composer open and on your profile await page.evaluate(() => document.querySelector('.feed-post-fab').click()); check('the composer lists it under Scheduled (1)', await waitFor(() => /Scheduled \(1\)/.test(document.querySelector('.sched-list')?.innerText || ''), 5000)); check('...with its words', await page.evaluate(() => document.querySelector('.sched-item').innerText.includes('later, #coinos'))); await page.reload({ waitUntil: 'domcontentloaded' }); await waitText('receive', 20000); await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]')?.click()); await waitFor(() => !!document.querySelector('.feed-post-fab'), 15000); await page.evaluate(() => document.querySelector('.feed-post-fab').click()); check('it survives a reload (and the status check keeps it)', await waitFor(() => !!document.querySelector('.sched-item'), 8000) && calls.some((c) => c.path === '/schedule/status')); await page.evaluate(() => [...document.querySelectorAll('.sched-item button')].find((b) => b.textContent.trim() === 'Cancel').click()); await waitFor(() => !document.querySelector('.sched-item'), 8000); const cc = calls.find((c) => c.path === '/schedule/cancel'); check('Cancel sends a kind 5 naming it, signed by the author', !!cc && cc.body.event.kind === 5 && verifyEvent(cc.body.event) && cc.body.event.pubkey === ev.pubkey && cc.body.event.tags.some((x) => x[0] === 'e' && x[1] === ev.id)); check('...and it leaves the list', await page.evaluate(() => !document.querySelector('.sched-list'))); check('no page errors', !errs.length, errs.join(' | ')); } catch (e) { check('ran', false, e.stack); } await browser.close(); server.stop(); console.log(ok ? '\nALL PASS' : '\nFAILED'); process.exit(ok ? 0 : 1);