Phase 8: widgets and polish

- Live job card widget (progress bar, in-widget cancel via widget_query)
  and live invoice widget (QR drawn from a bitmap, countdown, paid state),
  Bot API 10.4 sendWidget, private chats only
- Automatic fallback to the ordinary message when sendWidget fails, with
  a breaker that pauses widgets after repeated failures or on servers
  without the method; TELEGRAM_WIDGETS
- Prometheus metrics on the core (/metrics) and on every worker: queue
  depth and wait, slots, heartbeats, job outcomes, errors per site,
  deliveries, cache, invoices, Lightning, ledger check, widgets
- Example Prometheus config and alert rules, Caddyfile, dashboard notes
- Load test: cmd/loadtest and deploy/loadtest (make loadtest)
- Browser check of the widgets' HTML, including decoding a drawn QR
- docs/DEPLOY.md (production in under an hour) and docs/MONITORING.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Michilis
2026-11-18 18:24:36 +00:00
co-authored by Claude Opus 5.5
parent f1f9c6156c
commit 3c153af97f
45 changed files with 3158 additions and 20 deletions
+1 -1
View File
@@ -39,4 +39,4 @@ for _ in $(seq 1 600); do
done
[ -f "$stage/stage.json" ] || { echo "timed out waiting for the core" >&2; cat "$log" >&2; exit 1; }
(cd web/miniapp && node e2e/smoke.mjs "$stage" "$shots")
(cd web/miniapp && node e2e/smoke.mjs "$stage" "$shots" && node e2e/widgets.mjs "$shots")
+129
View File
@@ -0,0 +1,129 @@
// Renders the bot's HTML widgets (internal/widget/*.html) in headless
// Chromium with a stand-in for Telegram's TelegramWidget object, and
// checks what they draw for each state. Telegram runs widgets in its own
// sandbox, not a browser; this catches script errors and wrong output,
// not differences of that sandbox.
//
// Usage: node e2e/widgets.mjs [screenshot dir]
import { chromium } from "playwright-core";
import jsQR from "jsqr";
import { mkdirSync, readFileSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
const root = join(dirname(fileURLToPath(import.meta.url)), "../../..");
const shotDir = process.argv[2] || "";
if (shotDir) mkdirSync(shotDir, { recursive: true });
const html = (name) => readFileSync(join(root, "internal/widget", name + ".html"), "utf8");
const stub = (chat, pub) => `
window.__requests = [];
window.__handlers = {};
window.TelegramWidget = {
chatData: ${JSON.stringify(chat)}, publicData: ${JSON.stringify(pub)},
onEvent(name, fn) { (window.__handlers[name] ||= []).push(fn); },
request(data) { window.__requests.push(data); return Promise.resolve({ result: "Cancelled." }); },
ready() { window.__ready = true; },
};
window.__set = (chat) => { TelegramWidget.chatData = chat; (window.__handlers.chatDataChanged || []).forEach((f) => f()); };
`;
const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH || undefined });
const problems = [];
const page = async (name, chat, pub) => {
const p = await browser.newPage({ viewport: { width: 340, height: 420 } });
p.on("pageerror", (e) => problems.push(`${name}: ${e.message}`));
p.on("console", (m) => m.type() === "error" && problems.push(`${name}: ${m.text()}`));
await p.setContent("<script>" + stub(chat, pub) + "</script>" + html(name));
return p;
};
const check = (cond, what) => {
if (!cond) problems.push(what);
};
const shot = async (p, n) => shotDir && p.screenshot({ path: join(shotDir, n + ".png") });
// --- job card ---------------------------------------------------------------
{
const p = await page("job", JSON.stringify({ k: "running", m: "Descargando…", d: "42 % · 4,2 MB de 10 MB", p: 0.42, x: "Cancelar" }));
check(await p.evaluate(() => window.__ready), "job: ready() not called");
check((await p.textContent("#m")) === "Descargando…", "job: message not shown");
check((await p.textContent("#x")) === "Cancelar" && (await p.isVisible("#x")), "job: no cancel button");
const w = await p.evaluate(() => getComputedStyle(document.getElementById("f")).width);
check(w !== "0px", "job: progress bar is empty at 42%");
await shot(p, "widget-job-running");
await p.click("#x");
check((await p.evaluate(() => window.__requests)).join() === "cx", "job: cancel did not send the request");
check(await p.isDisabled("#x"), "job: cancel stays enabled while waiting");
await p.waitForFunction(() => document.getElementById("d").textContent === "Cancelled.");
await p.evaluate(() => window.__set(JSON.stringify({ k: "queued", m: "Position 2, about 1 minute", p: -1, x: "Cancel" })));
check(!(await p.isVisible("#t")), "job: progress bar shown while queued");
await p.evaluate(() => window.__set(JSON.stringify({ k: "running", m: "Processing", p: -1, x: "Cancel" })));
check((await p.getAttribute("body", "class")) === "busy", "job: unknown progress does not move");
await p.evaluate(() => window.__set(JSON.stringify({ k: "end", m: "Done. Enjoy.", p: 0 })));
check(!(await p.isVisible("#x")) && !(await p.isVisible("#t")), "job: controls left after the end");
check((await p.textContent("#m")) === "Done. Enjoy.", "job: end message not shown");
await shot(p, "widget-job-done");
await p.evaluate(() => window.__set(JSON.stringify({ k: "running", m: "تنزيل", p: 0.5, x: "إلغاء", r: true })));
check((await p.evaluate(() => document.documentElement.dir)) === "rtl", "job: right-to-left not applied");
await p.close();
}
// --- invoice ----------------------------------------------------------------
{
// A real code from the Go side would be better; this is the shape: the
// 21x21 finder-only pattern is enough to see that modules are drawn.
const n = 21;
const bits = new Uint8Array(Math.ceil((n * n) / 8));
for (let r = 0; r < n; r++) for (let c = 0; c < n; c++) if ((r < 7 && c < 7) || (r + c) % 3 === 0) bits[(r * n + c) >> 3] |= 0x80 >> ((r * n + c) & 7);
const q = Buffer.from(bits).toString("base64");
const pub = JSON.stringify({
t: "Day pass", a: "700 sats", e: Math.floor(Date.now() / 1000) + 125, w: "Waiting for payment · {T}", c: "Checking for the payment…", q, n,
});
const p = await page("invoice", JSON.stringify({ s: "pending" }), pub);
check((await p.textContent("#a")) === "700 sats", "invoice: amount not shown");
check(/Waiting for payment · 2:0[0-5]/.test(await p.textContent("#w")), "invoice: countdown wrong: " + (await p.textContent("#w")));
const size = await p.evaluate(() => document.getElementById("q").width);
check(size >= (n + 4) * 2, "invoice: QR canvas not drawn");
const dark = await p.evaluate(() => {
const c = document.getElementById("q");
const d = c.getContext("2d").getImageData(0, 0, c.width, c.height).data;
let k = 0;
for (let i = 0; i < d.length; i += 4) if (d[i] < 50) k++;
return k;
});
check(dark > 0, "invoice: QR has no dark modules");
await shot(p, "widget-invoice-pending");
await p.evaluate(() => window.__set(JSON.stringify({ s: "paid", m: "Paid. Day pass · 700 sats" })));
check(await p.isVisible("#k"), "invoice: no paid mark");
check(!(await p.isVisible("#q")) && !(await p.isVisible("#w")), "invoice: QR or countdown left after payment");
await shot(p, "widget-invoice-paid");
await p.evaluate(() => window.__set(JSON.stringify({ s: "expired", m: "This invoice has expired." })));
check(!(await p.isVisible("#k")) && !(await p.isVisible("#q")), "invoice: expired still shows QR or paid mark");
await p.close();
// A real invoice code from the Go side, drawn by the widget, must scan.
const fx = JSON.parse(readFileSync(join(root, "internal/widget/testdata/qr.json"), "utf8"));
const real = await page("invoice", JSON.stringify({ s: "pending" }), JSON.stringify({ t: "x", a: "x", e: 0, w: "", c: "", q: fx.q, n: fx.n }));
const img = await real.evaluate(() => {
const c = document.getElementById("q");
return { w: c.width, h: c.height, d: Array.from(c.getContext("2d").getImageData(0, 0, c.width, c.height).data) };
});
const decoded = jsQR(Uint8ClampedArray.from(img.d), img.w, img.h);
check(decoded && decoded.data === fx.text, "invoice: the drawn QR does not scan back to the invoice: " + (decoded && decoded.data));
await shot(real, "widget-invoice-real-qr");
await real.close();
const late = await page("invoice", JSON.stringify({ s: "pending" }), pub.replace(/"e":\d+/, '"e":1'));
check((await late.textContent("#w")) === "Checking for the payment…", "invoice: no checking text at zero");
await late.close();
}
await browser.close();
if (problems.length) {
console.error("FAILED:\n" + problems.join("\n"));
process.exit(1);
}
console.log("widgets render as expected");