Files
patriothacks/e2e/uploadMiniapp.e2e.mjs

267 lines
10 KiB
JavaScript

// Upload-a-mini-app UI acceptance test (plan todo 10, Wave 2 upload
// visibility). Self-contained Playwright runner, same shape as
// e2e/installShare.e2e.mjs: starts a real Vite dev server and drives the
// REAL app UI through real routes - no mocks, no test-only internal
// function call (never imports/calls `uploadMiniapp()` directly; every
// step goes through the rendered form).
//
// HAPPY: from the home grid, click "+ Upload a mini-app", fill the
// manifest form (name/icon/entryPoint/one permission checkbox), attach
// a real minimal HTML file via the real <input type="file">, submit,
// and confirm the new package appears as a tile on the home grid after
// returning home.
//
// FAILURE: the same flow with the required "name" field left blank -
// asserts a specific, actionable rejection message (naming the missing
// field) is shown, not a silent failure or crash, and that nothing new
// was installed.
import { chromium } from "playwright";
import { createServer as createViteServer } from "vite";
import { mkdirSync, writeFileSync } from "node:fs";
import { dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..");
const VITE_PORT = 46000 + Math.floor(Math.random() * 10000);
const APP_URL = `http://127.0.0.1:${VITE_PORT}`;
const SAMPLE_HTML = "<html><body><p>Counter Widget</p></body></html>";
async function fillManifestForm(page, { name, icon = "\uD83C\uDF31", entryPoint = "index.html" }) {
if (name !== undefined) {
await page.getByLabel("Mini-app name").fill(name);
}
await page.getByLabel("Icon (emoji or data URI)").fill(icon);
await page.getByLabel("Entry point").fill(entryPoint);
}
async function runHappyPath(browser) {
const context = await browser.newContext();
const evidence = { scenario: "happy", steps: {} };
try {
const page = await context.newPage();
await page.goto(`${APP_URL}/`);
const preUploadTileCount = await page.getByRole("button").count();
await page.getByRole("button", { name: "+ Upload a mini-app" }).click();
evidence.steps.navigatedToUploadScreen = {
url: page.url(),
reachedViaHomeGridAffordance: true,
};
await fillManifestForm(page, { name: "Counter Widget" });
await page.getByLabel("ledger.read").check();
await page.setInputFiles("#upload-html-file", {
name: "index.html",
mimeType: "text/html",
buffer: Buffer.from(SAMPLE_HTML),
});
evidence.steps.filledRealUiForm = {
name: "Counter Widget",
permissionChecked: "ledger.read",
htmlFileAttachedViaRealFileInput: true,
};
await page.getByRole("button", { name: "Upload mini-app" }).click();
await page.getByTestId("upload-success").waitFor();
const successText = await page.getByTestId("upload-success").innerText();
evidence.steps.uploadSucceeded = { successText };
await page.getByRole("button", { name: "Go to home" }).click();
await page.waitForURL(`${APP_URL}/`);
const newTile = page.getByRole("button", { name: "Counter Widget" });
await newTile.waitFor();
const postUploadTileCount = await page.getByRole("button").count();
evidence.steps.newTileOnHomeGrid = {
tileVisible: await newTile.isVisible(),
tileCountBefore: preUploadTileCount,
tileCountAfter: postUploadTileCount,
increasedByExactlyOne: postUploadTileCount === preUploadTileCount + 1,
};
if (!evidence.steps.newTileOnHomeGrid.increasedByExactlyOne) {
throw new Error(
`happy: expected exactly one new tile on the home grid, before=${preUploadTileCount} after=${postUploadTileCount}`,
);
}
if (!/Counter Widget/.test(successText)) {
throw new Error(`happy: success message "${successText}" did not name the uploaded package`);
}
evidence.pass = true;
return evidence;
} catch (err) {
evidence.pass = false;
evidence.error = String(err && err.message ? err.message : err);
throw Object.assign(err, { evidence });
} finally {
await context.close();
}
}
async function runInvalidManifestPath(browser) {
const context = await browser.newContext();
const evidence = { scenario: "failure/invalid-manifest", steps: {} };
try {
const page = await context.newPage();
await page.goto(`${APP_URL}/`);
const preUploadTileCount = await page.getByRole("button").count();
await page.getByRole("button", { name: "+ Upload a mini-app" }).click();
// Leave "Mini-app name" blank - the real assertValidManifest contract's
// own required-field check, exercised through the real UI form, not a
// direct function call.
await fillManifestForm(page, { name: undefined });
await page.setInputFiles("#upload-html-file", {
name: "index.html",
mimeType: "text/html",
buffer: Buffer.from(SAMPLE_HTML),
});
evidence.steps.filledFormWithMissingName = { nameFieldLeftBlank: true };
await page.getByRole("button", { name: "Upload mini-app" }).click();
const alert = page.getByRole("alert");
await alert.waitFor();
const alertText = await alert.innerText();
const pageErrors = [];
page.on("pageerror", (err) => pageErrors.push(String(err)));
await page.waitForTimeout(200);
evidence.steps.sawSpecificActionableRejection = {
alertText,
namesTheMissingField: /name/i.test(alertText) && /missing required field/i.test(alertText),
noUncaughtPageErrors: pageErrors.length === 0,
noUploadSuccessShown: await page.getByTestId("upload-success").count() === 0,
};
if (!evidence.steps.sawSpecificActionableRejection.namesTheMissingField) {
throw new Error(
`failure: alert text "${alertText}" does not specifically name the missing "name" field`,
);
}
if (!evidence.steps.sawSpecificActionableRejection.noUncaughtPageErrors) {
throw new Error(`failure: uncaught page errors occurred: ${pageErrors.join("; ")}`);
}
await page.goto(`${APP_URL}/`);
const postRejectTileCount = await page.getByRole("button").count();
evidence.steps.nothingInstalled = {
tileCountBefore: preUploadTileCount,
tileCountAfter: postRejectTileCount,
unchanged: postRejectTileCount === preUploadTileCount,
};
if (!evidence.steps.nothingInstalled.unchanged) {
throw new Error(
`failure: expected no new tile after a rejected upload, before=${preUploadTileCount} after=${postRejectTileCount}`,
);
}
evidence.pass = true;
return evidence;
} catch (err) {
evidence.pass = false;
evidence.error = String(err && err.message ? err.message : err);
throw Object.assign(err, { evidence });
} finally {
await context.close();
}
}
async function main() {
const vite = await createViteServer({
root: ROOT,
configFile: resolve(ROOT, "vite.config.ts"),
logLevel: "warn",
server: {
host: "127.0.0.1",
port: VITE_PORT,
strictPort: true,
},
});
await vite.listen();
const browser = await chromium.launch({ headless: true, args: ["--no-sandbox"] });
const results = {};
let failed = false;
try {
try {
results.happy = await runHappyPath(browser);
} catch (e) {
failed = true;
results.happy = e.evidence ?? { scenario: "happy", pass: false, error: String(e) };
}
try {
results.invalid = await runInvalidManifestPath(browser);
} catch (e) {
failed = true;
results.invalid = e.evidence ?? { scenario: "failure/invalid-manifest", pass: false, error: String(e) };
}
} finally {
await browser.close();
await vite.close();
}
const evDir = resolve(ROOT, ".omo/evidence/the-commons-hollow-polish");
mkdirSync(evDir, { recursive: true });
const now = new Date().toISOString();
writeFileSync(
resolve(evDir, "task-10-the-commons-hollow-polish.json"),
JSON.stringify(
{
task: "10. Build a real upload-a-mini-app UI, reachable from the home grid",
qa: "happy",
description:
"From the home grid, clicks the real '+ Upload a mini-app' affordance, fills the real manifest form (name/icon/entryPoint/permission checkbox), attaches a real minimal HTML file via the real <input type=\"file\">, submits through the real uploadMiniapp() storage path (no bypass, no test-only internal function call), and confirms the new package appears as a tile on the home grid after returning home.",
tool: "Playwright (chromium) over a real Vite dev server, one browser context",
run_command: "node e2e/uploadMiniapp.e2e.mjs",
noTestOnlyInternalCall:
"Every step drives the rendered UI (page.getByRole/getByLabel/setInputFiles/click) - uploadMiniapp() is never imported or called directly from this script.",
timestamp: now,
result: results.happy,
pass: Boolean(results.happy && results.happy.pass),
},
null,
2,
),
);
writeFileSync(
resolve(evDir, "task-10-the-commons-hollow-polish-invalid.json"),
JSON.stringify(
{
task: "10. Build a real upload-a-mini-app UI, reachable from the home grid",
qa: "failure/invalid-manifest",
description:
"The same real-UI upload flow with the required 'Mini-app name' field left blank - asserts a specific, actionable rejection message naming the missing field is shown (reusing assertValidManifest's existing contract unchanged), with no uncaught page error and no new tile/package installed.",
tool: "Playwright (chromium) over a real Vite dev server, one browser context",
run_command: "node e2e/uploadMiniapp.e2e.mjs",
timestamp: now,
result: results.invalid,
pass: Boolean(results.invalid && results.invalid.pass),
},
null,
2,
),
);
console.log("\n===== e2e RESULT =====");
console.log(JSON.stringify(results, null, 2));
const happyOk = Boolean(results.happy && results.happy.pass);
const invalidOk = Boolean(results.invalid && results.invalid.pass);
console.log(`\nSUMMARY: happy=${happyOk ? "PASS" : "FAIL"} invalid=${invalidOk ? "PASS" : "FAIL"}`);
if (failed || !happyOk || !invalidOk) {
process.exitCode = 1;
}
}
main().catch((e) => {
console.error("FATAL", e);
process.exitCode = 1;
});