Phase 6: Mini App
A Telegram Mini App served by the core under /app/, embedded in the binary. - API under /app/api/ with initData validated (HMAC, age) on every call - Pages: Home, Queue, Buy (target, product, invoice), History, Groups, group detail (Overview, Settings, Wallet, Usage) and Me - Every action runs through the same service, billing and scheduler code as the chat, so limits, prices and admin checks are decided on the server - Texts come from the catalog over the API; layout mirrors for RTL - Front end in web/miniapp (Vite, React, TypeScript); the build is committed and guarded by a source hash test; the Docker image rebuilds it - MINIAPP_ENABLED with an https PUBLIC_URL; entry points from /app, group settings and the over-limit offer - Browser test (make miniapp-e2e) against a core in test mode - Fix: each download attempt gets its own scratch directory, so a retry cannot lose its file to the cleanup of the failed attempt Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Fable 5.2
parent
51371da0e0
commit
4f11f939a0
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/usr/bin/env bash
|
||||
# Runs the browser test of the Mini App: a complete core in test mode
|
||||
# (fake Telegram, fake LNbits, scripted yt-dlp) and headless Chromium
|
||||
# clicking through the built app.
|
||||
#
|
||||
# web/miniapp/e2e/run.sh [screenshot dir]
|
||||
#
|
||||
# Needs Node.js with "npm ci" done in web/miniapp, and a Chromium that
|
||||
# Playwright can start: "npx playwright-core install chromium", or
|
||||
# CHROMIUM_PATH pointing at a Chrome or Chromium binary.
|
||||
set -euo pipefail
|
||||
|
||||
root="$(cd "$(dirname "$0")/../../.." && pwd)"
|
||||
stage="$(mktemp -d)"
|
||||
shots="${1:-}"
|
||||
log="$stage/core.log"
|
||||
|
||||
cleanup() {
|
||||
touch "$stage/stop"
|
||||
wait "$core" 2>/dev/null || true
|
||||
rm -rf "$stage"
|
||||
}
|
||||
|
||||
cd "$root"
|
||||
(cd web/miniapp && npm run build >/dev/null)
|
||||
|
||||
DLBOT_STAGE_DIR="$stage" go test ./internal/app/ -run '^TestMiniAppStage$' -count=1 -timeout 20m >"$log" 2>&1 &
|
||||
core=$!
|
||||
trap cleanup EXIT
|
||||
|
||||
for _ in $(seq 1 600); do
|
||||
[ -f "$stage/stage.json" ] && break
|
||||
if ! kill -0 "$core" 2>/dev/null; then
|
||||
echo "the core did not start:" >&2
|
||||
cat "$log" >&2
|
||||
exit 1
|
||||
fi
|
||||
sleep 0.2
|
||||
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")
|
||||
@@ -0,0 +1,294 @@
|
||||
// Browser test of the Mini App against a running core.
|
||||
//
|
||||
// It opens the built app in headless Chromium, with a stand-in for
|
||||
// Telegram's bridge script that hands the app signed initData, and clicks
|
||||
// through the flows a user has: look a link up and download it, cancel a
|
||||
// download, resend from history, buy a pass, manage a group, top up a
|
||||
// group wallet, change preferences. Any error in the page's console fails
|
||||
// the run.
|
||||
//
|
||||
// Usage: node e2e/smoke.mjs <stage dir> [screenshot dir]
|
||||
// The stage dir holds stage.json, written by TestMiniAppStage. Run both
|
||||
// together with "make miniapp-e2e" from the repository root.
|
||||
// CHROMIUM_PATH picks the browser binary when Playwright's own is absent.
|
||||
|
||||
import { chromium } from "playwright-core";
|
||||
import { mkdirSync, readFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
|
||||
const stageDir = process.argv[2];
|
||||
const shotDir = process.argv[3] || "";
|
||||
if (!stageDir) {
|
||||
console.error("usage: node e2e/smoke.mjs <stage dir> [screenshot dir]");
|
||||
process.exit(2);
|
||||
}
|
||||
const stage = JSON.parse(readFileSync(join(stageDir, "stage.json"), "utf8"));
|
||||
if (shotDir) mkdirSync(shotDir, { recursive: true });
|
||||
|
||||
// What the app sees instead of telegram-web-app.js.
|
||||
const bridge = (initData) => `
|
||||
window.__opened = [];
|
||||
window.__back = { shown: false, cb: null };
|
||||
window.Telegram = { WebApp: {
|
||||
initData: ${JSON.stringify(initData)},
|
||||
initDataUnsafe: {},
|
||||
colorScheme: "light",
|
||||
version: "8.0",
|
||||
isVersionAtLeast: () => true,
|
||||
ready() {}, expand() {}, close() {},
|
||||
openLink(u) { window.__opened.push(u); },
|
||||
openTelegramLink(u) { window.__opened.push(u); },
|
||||
showConfirm(message, cb) { window.__confirmed = message; cb(true); },
|
||||
BackButton: {
|
||||
show() { window.__back.shown = true; },
|
||||
hide() { window.__back.shown = false; },
|
||||
onClick(cb) { window.__back.cb = cb; },
|
||||
offClick() {},
|
||||
},
|
||||
HapticFeedback: { impactOccurred() {}, notificationOccurred() {}, selectionChanged() {} },
|
||||
} };
|
||||
`;
|
||||
|
||||
const browser = await chromium.launch({ executablePath: process.env.CHROMIUM_PATH || undefined });
|
||||
const problems = [];
|
||||
let step = "start";
|
||||
|
||||
async function open(initData, tweak) {
|
||||
const context = await browser.newContext({ viewport: { width: 390, height: 844 }, locale: "en-US" });
|
||||
await context.grantPermissions(["clipboard-read", "clipboard-write"]);
|
||||
const page = await context.newPage();
|
||||
await page.route("https://telegram.org/**", (route) =>
|
||||
route.fulfill({ contentType: "application/javascript", body: bridge(initData) }),
|
||||
);
|
||||
if (tweak) await tweak(page);
|
||||
page.on("console", (m) => {
|
||||
if (m.type() === "error") problems.push(`[${step}] console: ${m.text()}`);
|
||||
});
|
||||
page.on("pageerror", (e) => problems.push(`[${step}] page error: ${e.message}`));
|
||||
await page.goto(stage.url);
|
||||
return page;
|
||||
}
|
||||
|
||||
let shots = 0;
|
||||
async function shot(page, name) {
|
||||
if (shotDir) await page.screenshot({ path: join(shotDir, `${String(++shots).padStart(2, "0")}-${name}.png`) });
|
||||
}
|
||||
|
||||
const tab = (page, name) => page.getByRole("navigation").getByRole("button", { name: new RegExp("^" + name) });
|
||||
const toast = (page, text) => page.getByRole("status").filter({ hasText: text }).waitFor();
|
||||
const back = (page) => page.evaluate(() => window.__back.cb && window.__back.cb());
|
||||
|
||||
async function expectText(page, text) {
|
||||
await page.getByText(text, { exact: false }).first().waitFor({ timeout: 10000 });
|
||||
}
|
||||
|
||||
async function run(name, fn) {
|
||||
step = name;
|
||||
const started = Date.now();
|
||||
await fn();
|
||||
console.log(`ok ${name} (${Date.now() - started} ms)`);
|
||||
}
|
||||
|
||||
try {
|
||||
const page = await open(stage.init_data.admin);
|
||||
|
||||
await run("home shows the plan, usage and recent downloads", async () => {
|
||||
await expectText(page, "Free plan");
|
||||
await expectText(page, "1 of ");
|
||||
await page.getByText("Test Video").first().waitFor();
|
||||
await page.getByRole("button", { name: "Send again" }).first().waitFor();
|
||||
await shot(page, "home");
|
||||
});
|
||||
|
||||
await run("a pasted link is looked up and started", async () => {
|
||||
await page.getByPlaceholder("Paste a link").fill("https://example.com/watch?v=browser");
|
||||
await page.getByRole("button", { name: "Look up" }).click();
|
||||
await page.getByRole("button", { name: /^Best/ }).waitFor();
|
||||
await shot(page, "lookup");
|
||||
await page.getByRole("button", { name: /^Best/ }).click();
|
||||
await toast(page, "Started");
|
||||
// The app moves to the queue by itself.
|
||||
await expectText(page, "Your downloads");
|
||||
await page.getByText(/Downloading|Position|Sending/).first().waitFor();
|
||||
await shot(page, "queue");
|
||||
});
|
||||
|
||||
await run("a running download can be cancelled", async () => {
|
||||
await page.getByRole("button", { name: "Cancel", exact: true }).click();
|
||||
await toast(page, "Cancelled");
|
||||
await expectText(page, "Nothing in the queue.");
|
||||
const asked = await page.evaluate(() => window.__confirmed);
|
||||
if (!asked || !asked.includes("Test Video")) throw new Error("no confirmation was asked: " + asked);
|
||||
});
|
||||
|
||||
await run("history sends a file again", async () => {
|
||||
await tab(page, "Home").click();
|
||||
await page.getByRole("button", { name: "All", exact: true }).click();
|
||||
await expectText(page, "History");
|
||||
if (!(await page.evaluate(() => window.__back.shown))) throw new Error("no back button on a sub page");
|
||||
await page.getByRole("button", { name: "Send again" }).first().click();
|
||||
await toast(page, "Started");
|
||||
await shot(page, "history");
|
||||
await back(page);
|
||||
await expectText(page, "New download");
|
||||
});
|
||||
|
||||
await run("buying a pass shows an invoice and notices the payment", async () => {
|
||||
await tab(page, "Buy").click();
|
||||
await expectText(page, "Who is it for?");
|
||||
await shot(page, "buy-target");
|
||||
await page.getByRole("button", { name: /^Me Balance/ }).click();
|
||||
await expectText(page, "Pass for Me");
|
||||
await shot(page, "buy-product");
|
||||
await page.getByRole("button", { name: /Day pass/ }).click();
|
||||
await page.getByAltText("Lightning invoice as a QR code").waitFor();
|
||||
await expectText(page, "Waiting for payment");
|
||||
await shot(page, "invoice");
|
||||
await page.getByRole("button", { name: "Copy invoice" }).click();
|
||||
await toast(page, "Copied");
|
||||
const copied = await page.evaluate(() => navigator.clipboard.readText());
|
||||
if (!copied.startsWith("lnbc")) throw new Error("clipboard holds " + copied.slice(0, 20));
|
||||
await page.getByRole("button", { name: "Open in wallet" }).click();
|
||||
const opened = await page.evaluate(() => window.__opened.at(-1));
|
||||
if (!/\/pay\/[0-9A-Za-z]+$/.test(opened || "")) throw new Error("wallet link = " + opened);
|
||||
// The stage pays the invoice after three seconds.
|
||||
await page.getByText("Paid", { exact: true }).waitFor({ timeout: 15000 });
|
||||
await shot(page, "paid");
|
||||
await page.getByRole("button", { name: "Done" }).click();
|
||||
await expectText(page, "Pass active");
|
||||
await shot(page, "home-with-pass");
|
||||
});
|
||||
|
||||
await run("group settings can be changed by an admin", async () => {
|
||||
await tab(page, "Groups").click();
|
||||
await expectText(page, "Your groups");
|
||||
await shot(page, "groups");
|
||||
await page.locator("button.cell").first().click();
|
||||
await page.getByRole("tab", { name: "Overview" }).waitFor();
|
||||
await shot(page, "group-overview");
|
||||
await page.getByRole("tab", { name: "Settings" }).click();
|
||||
const detect = page.getByRole("switch", { name: "Detect pasted links" });
|
||||
if ((await detect.getAttribute("aria-checked")) !== "false") throw new Error("auto detect starts on");
|
||||
await detect.click();
|
||||
await page.getByLabel("Who can use it").selectOption("admins");
|
||||
await page.getByLabel("Largest file, in MB").fill("25");
|
||||
await page.getByPlaceholder("example.com").last().fill("https://www.Blocked.example/x");
|
||||
await page.getByRole("button", { name: "Add" }).last().click();
|
||||
await page.getByRole("button", { name: "Remove blocked.example" }).waitFor();
|
||||
await shot(page, "group-settings");
|
||||
await page.getByRole("button", { name: "Save" }).click();
|
||||
await toast(page, "Saved");
|
||||
// What the core stored is what a fresh load shows.
|
||||
await page.reload();
|
||||
await tab(page, "Groups").click();
|
||||
await page.locator("button.cell").first().click();
|
||||
await page.getByRole("tab", { name: "Settings" }).click();
|
||||
if ((await page.getByRole("switch", { name: "Detect pasted links" }).getAttribute("aria-checked")) !== "true")
|
||||
throw new Error("auto detect was not saved");
|
||||
if ((await page.getByLabel("Who can use it").inputValue()) !== "admins") throw new Error("who can use was not saved");
|
||||
if ((await page.getByLabel("Largest file, in MB").inputValue()) !== "25") throw new Error("size cap was not saved");
|
||||
await page.getByRole("button", { name: "Remove blocked.example" }).waitFor();
|
||||
});
|
||||
|
||||
await run("a group wallet is topped up and its rules are set", async () => {
|
||||
await page.getByRole("tab", { name: "Wallet" }).click();
|
||||
await expectText(page, "0 sats");
|
||||
await page.getByLabel("Group credits").selectOption("capped");
|
||||
await page.getByLabel("Sats per person per day").fill("200");
|
||||
await page.getByRole("button", { name: "Save" }).click();
|
||||
await toast(page, "Saved");
|
||||
await page.getByRole("button", { name: "Top up or buy a pass" }).click();
|
||||
await expectText(page, "Credits");
|
||||
await page.getByRole("button", { name: /^1,000 sats/ }).click();
|
||||
await page.getByAltText("Lightning invoice as a QR code").waitFor();
|
||||
await page.getByText("Paid", { exact: true }).waitFor({ timeout: 15000 });
|
||||
await page.getByRole("button", { name: "Done" }).click();
|
||||
// Back in the group, the balance is there.
|
||||
await page.getByRole("tab", { name: "Wallet" }).click();
|
||||
await expectText(page, "1,000 sats");
|
||||
await shot(page, "group-wallet");
|
||||
await page.getByRole("tab", { name: "Usage" }).click();
|
||||
await page.getByText(/Usage, last 7 days/).waitFor();
|
||||
await shot(page, "group-usage");
|
||||
});
|
||||
|
||||
await run("preferences are saved", async () => {
|
||||
await tab(page, "Me").click();
|
||||
await page.getByLabel("Default quality").selectOption("720");
|
||||
await toast(page, "Saved");
|
||||
await page.getByRole("switch", { name: "Audio only" }).click();
|
||||
await page.locator('[role="switch"][aria-checked="true"]').waitFor();
|
||||
await page.getByRole("button", { name: "Copy link" }).click();
|
||||
const link = await page.evaluate(() => navigator.clipboard.readText());
|
||||
if (!/\?start=ref_\d+$/.test(link)) throw new Error("referral link = " + link);
|
||||
await page.getByRole("button", { name: "Share" }).click();
|
||||
const shared = await page.evaluate(() => window.__opened.at(-1));
|
||||
if (!shared.startsWith("https://t.me/share/url?url=")) throw new Error("share link = " + shared);
|
||||
await shot(page, "me");
|
||||
});
|
||||
await page.context().close();
|
||||
|
||||
await run("a member who is not an admin sees no groups", async () => {
|
||||
const member = await open(stage.init_data.member);
|
||||
await tab(member, "Groups").click();
|
||||
await expectText(member, "No groups yet.");
|
||||
await member.context().close();
|
||||
});
|
||||
|
||||
await run("a deep link opens the group it names", async () => {
|
||||
const deep = await open(stage.init_data.admin, (p) =>
|
||||
p.route("**/app/api/me", async (route) => {
|
||||
const res = await route.fetch();
|
||||
const me = await res.json();
|
||||
me.start_param = "group_" + stage.group;
|
||||
await route.fulfill({ response: res, json: me });
|
||||
}),
|
||||
);
|
||||
await deep.getByRole("tab", { name: "Settings" }).waitFor();
|
||||
await deep.getByRole("switch", { name: "Detect pasted links" }).waitFor();
|
||||
await deep.context().close();
|
||||
});
|
||||
|
||||
await run("a right-to-left language mirrors the layout", async () => {
|
||||
const rtl = await open(stage.init_data.admin, (p) =>
|
||||
p.route("**/app/api/i18n", async (route) => {
|
||||
const res = await route.fetch();
|
||||
const body = await res.json();
|
||||
body.dir = "rtl";
|
||||
await route.fulfill({ response: res, json: body });
|
||||
}),
|
||||
);
|
||||
await expectText(rtl, "Recent downloads");
|
||||
const layout = await rtl.evaluate(() => {
|
||||
const first = document.querySelector("nav button").getBoundingClientRect();
|
||||
const last = [...document.querySelectorAll("nav button")].at(-1).getBoundingClientRect();
|
||||
const title = document.querySelector(".section-title span").getBoundingClientRect();
|
||||
return { dir: document.documentElement.dir, firstTabX: first.x, lastTabX: last.x, titleRight: title.right, width: innerWidth };
|
||||
});
|
||||
if (layout.dir !== "rtl" || layout.firstTabX < layout.lastTabX || layout.titleRight < layout.width / 2)
|
||||
throw new Error("layout is not mirrored: " + JSON.stringify(layout));
|
||||
await shot(rtl, "rtl");
|
||||
await rtl.context().close();
|
||||
});
|
||||
|
||||
await run("outside Telegram the app explains itself", async () => {
|
||||
const stranger = await open("");
|
||||
await expectText(stranger, "Open this page from Telegram");
|
||||
await shot(stranger, "outside-telegram");
|
||||
await stranger.context().close();
|
||||
// The refused calls show up as console errors; they are the point.
|
||||
for (let i = problems.length - 1; i >= 0; i--) {
|
||||
if (problems[i].startsWith(`[${step}]`) && problems[i].includes("401")) problems.splice(i, 1);
|
||||
}
|
||||
});
|
||||
} catch (err) {
|
||||
problems.push(`[${step}] ${err.stack || err}`);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
|
||||
if (problems.length > 0) {
|
||||
console.error("\nFAILED:\n" + problems.join("\n"));
|
||||
process.exit(1);
|
||||
}
|
||||
console.log("\nall browser checks passed");
|
||||
Reference in New Issue
Block a user