feat(upload): add shareable install-QR cross-device flow

This commit is contained in:
OmO Orchestrator committed 2026-11-17 22:12:46 -05:00
1 parent 7d6c57fc4b
commit f54d01870e
25 files changed
+1467 -4

No files matched your search

@@ -0,0 +1,32 @@
{
"task": "55. Upload: install-QR sharing flow",
"qa": "failure/deleted",
"description": "A QR is generated and shared as normal, then the shared mini-app's backing blob is deleted (its on-disk files removed - todo 56's backend has no DELETE endpoint, so direct file removal is the only way to make a blob genuinely vanish). Device B then scans the now-dangling QR and installs: asserts a clear 'no longer available' message renders, with no crash and no uncaught page error, and nothing is installed.",
"tool": "Playwright (chromium), two isolated browser contexts over a real Vite dev server + a real Node http.Server blob/KV backend (api/_lib/devServer.ts)",
"run_command": "node e2e/installShare.e2e.mjs",
"timestamp": "2026-11-18T03:12:25.357Z",
"result": {
"scenario": "failure/deleted",
"steps": {
"sharedFromDeviceA": {
"blobId": "a2d40dc0-7b79-47ca-826d-404bf0446bf7",
"installUrl": "http://127.0.0.1:47644/install/a2d40dc0-7b79-47ca-826d-404bf0446bf7"
},
"blobDeletedFromBackend": {
"deletedFiles": [
"a2d40dc0-7b79-47ca-826d-404bf0446bf7.bin",
"a2d40dc0-7b79-47ca-826d-404bf0446bf7.meta.json"
],
"mechanism": "blob's on-disk files removed directly from BLOB_STORE_DIR - the only way todo 56's backend (no DELETE endpoint) can lose a blob"
},
"deviceBSawCleanMessage": {
"noticeText": "This mini-app is no longer available (it may have been deleted). Ask the sender to share it again.",
"matchesExpectedCopy": true,
"noUncaughtPageErrors": true,
"shellStillResponsive": true
}
},
"pass": true
},
"pass": true
}
@@ -0,0 +1,37 @@
{
"task": "55. Upload: install-QR sharing flow",
"qa": "happy",
"description": "Full generate-scan-install round trip: device A uploads+shares a mini-app via a real install QR (real qrcode render, real POST to /api/blob), device B (a genuinely separate browser context/storage origin) decodes it with real jsQR (no camera), fetches it from the real /api/blob backend, installs it via the real validate+store path, and it appears as a new tile on device B's home grid.",
"tool": "Playwright (chromium), two isolated browser contexts (separate IndexedDB/storage per context) over a real Vite dev server + a real Node http.Server blob/KV backend (api/_lib/devServer.ts)",
"run_command": "node e2e/installShare.e2e.mjs",
"separateStorageBoundary": "ctxA and ctxB are distinct Playwright BrowserContexts - each has its own isolated cookies/localStorage/IndexedDB partition, standing in for two separate physical devices; neither context's IndexedDB is ever shared or reused across the other.",
"noAccountCreationStep": "installMiniappFromBlob (src/lib/miniappSharing.ts) never touches identity/account state - it is pure fetch -> assertValidManifest -> uploadMiniapp; no login/signup UI exists anywhere in the install flow.",
"timestamp": "2026-11-18T03:12:25.357Z",
"result": {
"scenario": "happy",
"steps": {
"uploadedOnDeviceA": {
"packageId": "8d46b092-f1a1-4344-9138-18c44207332e"
},
"sharedFromDeviceA": {
"qrIsRealPng": true,
"installUrl": "http://127.0.0.1:47644/install/512bbf33-78c3-4979-a492-c2b8f1c40bdb"
},
"deviceBScannedQr": {
"decodedUrl": "http://127.0.0.1:47644/install/512bbf33-78c3-4979-a492-c2b8f1c40bdb",
"matchesSharedUrl": true
},
"deviceBInstalled": {
"installSuccessText": "“Shared Garden Tracker” installed.\n\nGo to home"
},
"newTileOnDeviceBHomeGrid": {
"tileVisible": true,
"tileCountBefore": 13,
"tileCountAfter": 14,
"increasedByExactlyOne": true
}
},
"pass": true
},
"pass": true
}
+10
View File
@@ -0,0 +1,10 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>install-QR scan harness (test support, todo 55)</title>
</head>
<body>
<script type="module" src="/demo/qrScanHarness.ts"></script>
</body>
</html>
+36
View File
@@ -0,0 +1,36 @@
import { decodeInstallUrlFromImage } from "../src/lib/miniappSharing.ts";
declare global {
interface Window {
qrScanHarness: {
decodeDataUrl(dataUrl: string): Promise<string | null>;
};
}
}
function loadImage(dataUrl: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = () => reject(new Error("qr-scan harness: failed to load QR image"));
img.src = dataUrl;
});
}
async function decodeDataUrl(dataUrl: string): Promise<string | null> {
const img = await loadImage(dataUrl);
const canvas = document.createElement("canvas");
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
const ctx = canvas.getContext("2d");
if (!ctx) throw new Error("qr-scan harness: 2d canvas context unavailable");
ctx.drawImage(img, 0, 0);
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
return decodeInstallUrlFromImage({
data: imageData.data,
width: imageData.width,
height: imageData.height,
});
}
window.qrScanHarness = { decodeDataUrl };
+355
View File
@@ -0,0 +1,355 @@
// Install-QR cross-device sharing acceptance test (plan todo 55).
//
// Self-contained Playwright runner, same shape as e2e/assemblyPartition.e2e.mjs
// (todo 23): starts the REAL blob/KV backend (api/_lib/devServer.ts, todo 56)
// and a real Vite dev server proxying '/api' to it, then opens TWO isolated
// browser contexts - genuinely separate storage origins (separate IndexedDB,
// exactly like two different devices) - and drives the real app UI through
// real routes, no mocks:
//
// HAPPY: device A uploads a mini-app (via the real uploadMiniapp lib,
// seeding local storage the same way any upload UI would), opens its
// install-share screen, clicks "Share install QR" (POSTs to the real
// /api/blob), and gets back a real QR PNG. Device B - a transient harness
// page loaded ONLY inside device B's own isolated context - decodes that
// PNG with the real jsQR (bypassing the camera), device B's real app then
// navigates to the decoded install URL (GETs the real /api/blob/:id),
// installs via the real validate+store path, and the mini-app shows up
// as a new tile on device B's home grid.
//
// FAILURE: the same share is generated, then the blob's backing files are
// deleted directly from the real on-disk store (the only way todo 56's
// blob backend can lose a blob - there is no DELETE endpoint), and device
// B scans/installs the now-dangling QR: asserts a clear "no longer
// available" message, not a crash.
import { chromium } from "playwright";
import { createServer as createViteServer } from "vite";
import { mkdtemp, readdir, rm, unlink } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, dirname, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const __dirname = dirname(fileURLToPath(import.meta.url));
const ROOT = resolve(__dirname, "..");
const API_PORT = 44000 + Math.floor(Math.random() * 10000);
const VITE_PORT = 45000 + Math.floor(Math.random() * 10000);
const APP_URL = `http://127.0.0.1:${VITE_PORT}`;
const SCAN_HARNESS_URL = `${APP_URL}/demo/qr-scan.html`;
async function waitFor(fn, label, timeoutMs = 10000) {
const start = Date.now();
while (Date.now() - start < timeoutMs) {
const value = await fn();
if (value) return value;
await new Promise((r) => setTimeout(r, 100));
}
throw new Error(`timeout waiting for: ${label}`);
}
/** Uploads a sample mini-app on `page` via the REAL uploadMiniapp lib
* (Vite serves raw TS modules, so a dynamic import of the real app source
* from the page genuinely exercises it - no mock, no bypass of todo
* 53/54's validation+storage path) and returns its package id. */
async function uploadSampleMiniapp(page, name) {
await page.goto(`${APP_URL}/`);
return page.evaluate(async (manifestName) => {
const { uploadMiniapp } = await import(
/* @vite-ignore */ `${window.location.origin}/src/lib/miniappUpload.ts`
);
const record = await uploadMiniapp({
manifest: {
name: manifestName,
icon: "\uD83C\uDF31",
entryPoint: "index.html",
permissions: ["ledger.read"],
},
html: `<html><body><p>${manifestName}</p></body></html>`,
});
return record.id;
}, name);
}
/** Opens device A's share screen for `packageId`, clicks "Share install
* QR", and returns the real rendered QR data URL + install URL text. */
async function generateShareQr(page, packageId) {
await page.goto(`${APP_URL}/package/${packageId}`);
await page.getByRole("button", { name: "Share install QR" }).click();
const qrImage = page.getByTestId("install-qr-image");
await qrImage.waitFor({ state: "attached" });
const qrDataUrl = await waitFor(
() => qrImage.getAttribute("src"),
"QR data URL to render",
);
const installUrl = await page.getByTestId("install-url").innerText();
return { qrDataUrl, installUrl };
}
/** Decodes `qrDataUrl` to its encoded text using the REAL jsQR package,
* via a transient harness page loaded inside `context` - bypassing the
* camera for the automated test while still genuinely scanning the real
* rendered QR pixels (see demo/qrScanHarness.ts). */
async function scanQrCode(context, qrDataUrl) {
const scanPage = await context.newPage();
try {
await scanPage.goto(SCAN_HARNESS_URL);
await scanPage.waitForFunction(() => Boolean(window.qrScanHarness));
const decoded = await scanPage.evaluate(
(dataUrl) => window.qrScanHarness.decodeDataUrl(dataUrl),
qrDataUrl,
);
return decoded;
} finally {
await scanPage.close();
}
}
async function deleteBlobFromDisk(storeDir, blobId) {
const files = await readdir(storeDir);
const matches = files.filter((f) => f.startsWith(blobId));
if (matches.length === 0) {
throw new Error(`no on-disk blob files found for id ${blobId} in ${storeDir}`);
}
await Promise.all(matches.map((f) => unlink(join(storeDir, f))));
return matches;
}
async function runHappyPath(browser) {
const ctxA = await browser.newContext();
const ctxB = await browser.newContext();
const evidence = { scenario: "happy", steps: {} };
try {
const pageA = await ctxA.newPage();
const packageId = await uploadSampleMiniapp(pageA, "Shared Garden Tracker");
evidence.steps.uploadedOnDeviceA = { packageId };
const { qrDataUrl, installUrl } = await generateShareQr(pageA, packageId);
evidence.steps.sharedFromDeviceA = {
qrIsRealPng: qrDataUrl.startsWith("data:image/png;base64,"),
installUrl,
};
const pageB = await ctxB.newPage();
await pageB.goto(`${APP_URL}/`);
const preInstallTileCount = await pageB.getByRole("button").count();
const decodedUrl = await scanQrCode(ctxB, qrDataUrl);
if (decodedUrl !== installUrl) {
throw new Error(
`happy: decoded URL "${decodedUrl}" does not match the shared install URL "${installUrl}"`,
);
}
evidence.steps.deviceBScannedQr = { decodedUrl, matchesSharedUrl: true };
await pageB.goto(decodedUrl);
await pageB.getByTestId("install-success").waitFor();
const installSuccessText = await pageB.getByTestId("install-success").innerText();
evidence.steps.deviceBInstalled = { installSuccessText };
await pageB.getByRole("button", { name: "Go to home" }).click();
await pageB.waitForURL(`${APP_URL}/`);
const newTile = pageB.getByRole("button", { name: "Shared Garden Tracker" });
await newTile.waitFor();
const postInstallTileCount = await pageB.getByRole("button").count();
evidence.steps.newTileOnDeviceBHomeGrid = {
tileVisible: await newTile.isVisible(),
tileCountBefore: preInstallTileCount,
tileCountAfter: postInstallTileCount,
increasedByExactlyOne: postInstallTileCount === preInstallTileCount + 1,
};
if (!evidence.steps.newTileOnDeviceBHomeGrid.increasedByExactlyOne) {
throw new Error(
`happy: expected exactly one new tile on device B's home grid, before=${preInstallTileCount} after=${postInstallTileCount}`,
);
}
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 ctxA.close();
await ctxB.close();
}
}
async function runDeletedPath(browser, storeDir) {
const ctxA = await browser.newContext();
const ctxB = await browser.newContext();
const evidence = { scenario: "failure/deleted", steps: {} };
try {
const pageA = await ctxA.newPage();
const packageId = await uploadSampleMiniapp(pageA, "Soon-To-Be-Deleted Mini-App");
const { qrDataUrl, installUrl } = await generateShareQr(pageA, packageId);
const blobId = new URL(installUrl).pathname.split("/").pop();
evidence.steps.sharedFromDeviceA = { blobId, installUrl };
const deletedFiles = await deleteBlobFromDisk(storeDir, blobId);
evidence.steps.blobDeletedFromBackend = {
deletedFiles,
mechanism:
"blob's on-disk files removed directly from BLOB_STORE_DIR - the only way todo 56's backend (no DELETE endpoint) can lose a blob",
};
const pageB = await ctxB.newPage();
await pageB.goto(`${APP_URL}/`);
const decodedUrl = await scanQrCode(ctxB, qrDataUrl);
if (decodedUrl !== installUrl) {
throw new Error(`failure: decoded URL "${decodedUrl}" does not match "${installUrl}"`);
}
await pageB.goto(decodedUrl);
const notice = pageB.getByTestId("miniapp-no-longer-available");
await notice.waitFor();
const noticeText = await notice.innerText();
const pageErrors = [];
pageB.on("pageerror", (err) => pageErrors.push(String(err)));
await pageB.waitForTimeout(200);
evidence.steps.deviceBSawCleanMessage = {
noticeText,
matchesExpectedCopy: /no longer available/i.test(noticeText),
noUncaughtPageErrors: pageErrors.length === 0,
shellStillResponsive: await pageB.getByRole("link", { name: "Back to home" }).isVisible(),
};
if (!evidence.steps.deviceBSawCleanMessage.matchesExpectedCopy) {
throw new Error(`failure: notice text "${noticeText}" doesn't read as "no longer available"`);
}
if (!evidence.steps.deviceBSawCleanMessage.noUncaughtPageErrors) {
throw new Error(`failure: uncaught page errors occurred: ${pageErrors.join("; ")}`);
}
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 ctxA.close();
await ctxB.close();
}
}
async function main() {
const storeDir = await mkdtemp(join(tmpdir(), "commons-share-blob-test-"));
process.env.BLOB_STORE_DIR = storeDir;
// Dynamic import, deliberately AFTER BLOB_STORE_DIR is set: blobStore.ts
// reads it into a module-top-level const, so a static import (hoisted
// before this line runs) would freeze the default `.data/blobs` dir
// instead - the exact latent bug reproduced in the existing
// api/blob.integration.test.ts (it leaks real files into the repo's
// .data/blobs/ for the same reason; pre-existing, out of todo 55's scope).
const { createApiServer } = await import("../api/_lib/devServer.ts");
const apiServer = createApiServer();
await new Promise((r) => apiServer.listen(API_PORT, "127.0.0.1", r));
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,
proxy: {
"/api": { target: `http://127.0.0.1:${API_PORT}`, changeOrigin: 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.deleted = await runDeletedPath(browser, storeDir);
} catch (e) {
failed = true;
results.deleted = e.evidence ?? { scenario: "failure/deleted", pass: false, error: String(e) };
}
} finally {
await browser.close();
await vite.close();
await new Promise((r) => apiServer.close(r));
delete process.env.BLOB_STORE_DIR;
await rm(storeDir, { recursive: true, force: true });
}
const evDir = resolve(ROOT, ".omo/evidence/the-commons-hollow");
const { mkdirSync, writeFileSync } = await import("node:fs");
mkdirSync(evDir, { recursive: true });
const now = new Date().toISOString();
writeFileSync(
resolve(evDir, "task-55-the-commons-hollow.json"),
JSON.stringify(
{
task: "55. Upload: install-QR sharing flow",
qa: "happy",
description:
"Full generate-scan-install round trip: device A uploads+shares a mini-app via a real install QR (real qrcode render, real POST to /api/blob), device B (a genuinely separate browser context/storage origin) decodes it with real jsQR (no camera), fetches it from the real /api/blob backend, installs it via the real validate+store path, and it appears as a new tile on device B's home grid.",
tool:
"Playwright (chromium), two isolated browser contexts (separate IndexedDB/storage per context) over a real Vite dev server + a real Node http.Server blob/KV backend (api/_lib/devServer.ts)",
run_command: "node e2e/installShare.e2e.mjs",
separateStorageBoundary:
"ctxA and ctxB are distinct Playwright BrowserContexts - each has its own isolated cookies/localStorage/IndexedDB partition, standing in for two separate physical devices; neither context's IndexedDB is ever shared or reused across the other.",
noAccountCreationStep:
"installMiniappFromBlob (src/lib/miniappSharing.ts) never touches identity/account state - it is pure fetch -> assertValidManifest -> uploadMiniapp; no login/signup UI exists anywhere in the install flow.",
timestamp: now,
result: results.happy,
pass: Boolean(results.happy && results.happy.pass),
},
null,
2,
),
);
writeFileSync(
resolve(evDir, "task-55-the-commons-hollow-missing.json"),
JSON.stringify(
{
task: "55. Upload: install-QR sharing flow",
qa: "failure/deleted",
description:
"A QR is generated and shared as normal, then the shared mini-app's backing blob is deleted (its on-disk files removed - todo 56's backend has no DELETE endpoint, so direct file removal is the only way to make a blob genuinely vanish). Device B then scans the now-dangling QR and installs: asserts a clear 'no longer available' message renders, with no crash and no uncaught page error, and nothing is installed.",
tool:
"Playwright (chromium), two isolated browser contexts over a real Vite dev server + a real Node http.Server blob/KV backend (api/_lib/devServer.ts)",
run_command: "node e2e/installShare.e2e.mjs",
timestamp: now,
result: results.deleted,
pass: Boolean(results.deleted && results.deleted.pass),
},
null,
2,
),
);
console.log("\n===== e2e RESULT =====");
console.log(JSON.stringify(results, null, 2));
const happyOk = Boolean(results.happy && results.happy.pass);
const deletedOk = Boolean(results.deleted && results.deleted.pass);
console.log(`\nSUMMARY: happy=${happyOk ? "PASS" : "FAIL"} deleted=${deletedOk ? "PASS" : "FAIL"}`);
if (failed || !happyOk || !deletedOk) {
process.exitCode = 1;
}
}
main().catch((e) => {
console.error("FATAL", e);
process.exitCode = 1;
});
+1
View File
@@ -5,6 +5,7 @@
"type": "module", "type": "module",
"scripts": { "scripts": {
"dev": "vite", "dev": "vite",
"dev:api": "node api/_lib/devServer.ts",
"build": "tsc -b && vite build", "build": "tsc -b && vite build",
"lint": "oxlint", "lint": "oxlint",
"preview": "vite preview", "preview": "vite preview",
+4
View File
@@ -1,6 +1,8 @@
import { Route, Routes } from "react-router-dom"; import { Route, Routes } from "react-router-dom";
import { AdminSeedPanel } from "./admin/AdminSeedPanel"; import { AdminSeedPanel } from "./admin/AdminSeedPanel";
import { HomePage } from "./shell/HomePage"; import { HomePage } from "./shell/HomePage";
import { InstallMiniappScreen } from "./shell/InstallMiniappScreen";
import { InstalledMiniappScreen } from "./shell/InstalledMiniappScreen";
import { MiniappOutlet } from "./shell/MiniappOutlet"; import { MiniappOutlet } from "./shell/MiniappOutlet";
import { NotFoundMiniapp } from "./shell/NotFoundMiniapp"; import { NotFoundMiniapp } from "./shell/NotFoundMiniapp";
import { ShellLayout } from "./shell/ShellLayout"; import { ShellLayout } from "./shell/ShellLayout";
@@ -12,6 +14,8 @@ export function AppRoutes() {
<Route element={<ShellLayout />}> <Route element={<ShellLayout />}>
<Route index element={<HomePage />} /> <Route index element={<HomePage />} />
<Route path="miniapp/:miniappId" element={<MiniappOutlet />} /> <Route path="miniapp/:miniappId" element={<MiniappOutlet />} />
<Route path="install/:blobId" element={<InstallMiniappScreen />} />
<Route path="package/:packageId" element={<InstalledMiniappScreen />} />
<Route path="*" element={<NotFoundMiniapp />} /> <Route path="*" element={<NotFoundMiniapp />} />
</Route> </Route>
</Routes> </Routes>
+19
View File
@@ -47,6 +47,14 @@ export interface MiniappPackageRecord {
/** Raw HTML source of the mini-app, stored as a blob. */ /** Raw HTML source of the mini-app, stored as a blob. */
html: Blob; html: Blob;
installedAt: number; installedAt: number;
/** The blob/KV id this package was installed from via the install-QR
* sharing flow (todo 55), or `undefined` for a directly-uploaded
* package. Lets `installMiniappFromBlob` (src/lib/miniappSharing.ts)
* recognize "this exact shared package is already installed" and return
* the existing record instead of creating a duplicate tile - re-scanning
* the same install link (or a double effect run) must not install the
* same mini-app twice. */
sourceBlobId?: string;
} }
export class CommonsDatabase extends Dexie { export class CommonsDatabase extends Dexie {
@@ -68,6 +76,17 @@ export class CommonsDatabase extends Dexie {
eventLog: "++id, lamportTs", eventLog: "++id, lamportTs",
miniappPackages: "id", miniappPackages: "id",
}); });
// A unique index on sourceBlobId (todo 55): IndexedDB simply omits a
// record from a unique index when that property is absent, so plain
// local uploads (no sourceBlobId) are never affected - only a genuine
// duplicate install of the SAME shared blob collides, which is exactly
// the race `installMiniappFromBlob` (src/lib/miniappSharing.ts) relies
// on the database itself to reject atomically.
this.version(4).stores({
identity: "id",
eventLog: "++id, lamportTs",
miniappPackages: "id, &sourceBlobId",
});
} }
} }
+185
View File
@@ -0,0 +1,185 @@
import QRCode from "qrcode";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { db } from "./db";
import {
MiniappNoLongerAvailableError,
MiniappShareError,
buildInstallUrl,
decodeInstallUrlFromImage,
installMiniappFromBlob,
parseBlobIdFromInstallUrl,
shareMiniapp,
} from "./miniappSharing";
import { ManifestValidationError } from "./miniappManifest";
import { getMiniappPackage, uploadMiniapp, type StoredMiniappPackage } from "./miniappUpload";
beforeEach(async () => {
indexedDB.deleteDatabase(db.name);
db.close();
await db.open();
});
afterEach(() => {
vi.unstubAllGlobals();
});
const validManifest = {
name: "Shared Garden Tracker",
icon: "\uD83C\uDF31",
entryPoint: "index.html",
permissions: ["ledger.read"],
};
async function storeSamplePackage(html = "<html><body>shared mini-app</body></html>"): Promise<StoredMiniappPackage> {
return uploadMiniapp({ manifest: validManifest, html });
}
function stubFetch(impl: typeof fetch): void {
vi.stubGlobal("fetch", impl);
}
/** Renders `text` to a real QR bitmap via the `qrcode` package's own module
* matrix (no canvas/PNG decoder needed), exactly like the project's existing
* `qrSneakernet.test.ts` helper - proving `decodeInstallUrlFromImage` really
* runs `jsqr` against real `qrcode` output, not a stub. */
async function renderTextToImageData(text: string): Promise<{
data: Uint8ClampedArray;
width: number;
height: number;
}> {
const qr = QRCode.create(text, { errorCorrectionLevel: "M" });
const size = qr.modules.size;
const bits = qr.modules.data;
const scale = 8;
const margin = 4;
const dim = (size + margin * 2) * scale;
const data = new Uint8ClampedArray(dim * dim * 4).fill(255);
for (let i = 3; i < data.length; i += 4) data[i] = 255;
for (let row = 0; row < size; row++) {
for (let col = 0; col < size; col++) {
if (bits[row * size + col] !== 1) continue;
const px0 = (col + margin) * scale;
const py0 = (row + margin) * scale;
for (let dy = 0; dy < scale; dy++) {
for (let dx = 0; dx < scale; dx++) {
const idx = ((py0 + dy) * dim + (px0 + dx)) * 4;
data[idx] = 0;
data[idx + 1] = 0;
data[idx + 2] = 0;
data[idx + 3] = 255;
}
}
}
}
return { data, width: dim, height: dim };
}
describe("miniappSharing: install URL helpers", () => {
it("builds and parses an install URL round-trip", () => {
const url = buildInstallUrl("blob-id-123", "https://commons.example");
expect(url).toBe("https://commons.example/install/blob-id-123");
expect(parseBlobIdFromInstallUrl(url)).toBe("blob-id-123");
});
it("returns null for a URL that isn't an install link", () => {
expect(parseBlobIdFromInstallUrl("https://commons.example/miniapp/fair-share")).toBeNull();
expect(parseBlobIdFromInstallUrl("not a url at all")).toBeNull();
});
});
describe("miniappSharing.shareMiniapp", () => {
it("POSTs the package's manifest+HTML to the real /api/blob contract and returns an install URL + real QR", async () => {
const record = await storeSamplePackage();
let capturedBody: string | undefined;
stubFetch(async (_url, init) => {
capturedBody = init?.body as string;
return new Response(JSON.stringify({ id: "11111111-1111-1111-1111-111111111111" }), {
status: 201,
headers: { "Content-Type": "application/json" },
});
});
const result = await shareMiniapp(record, { origin: "https://commons.example" });
expect(JSON.parse(capturedBody!)).toEqual({
manifest: validManifest,
html: "<html><body>shared mini-app</body></html>",
});
expect(result.blobId).toBe("11111111-1111-1111-1111-111111111111");
expect(result.installUrl).toBe(
"https://commons.example/install/11111111-1111-1111-1111-111111111111",
);
expect(result.qrDataUrl.startsWith("data:image/png;base64,")).toBe(true);
});
it("throws MiniappShareError when the backend rejects the share", async () => {
const record = await storeSamplePackage();
stubFetch(async () => new Response("payload too large", { status: 413 }));
await expect(shareMiniapp(record)).rejects.toThrow(MiniappShareError);
});
});
describe("miniappSharing.installMiniappFromBlob", () => {
it("fetches the shared payload, re-validates it, and stores it via the real uploadMiniapp write path", async () => {
stubFetch(async () =>
new Response(
JSON.stringify({ manifest: validManifest, html: "<html><body>installed</body></html>" }),
{ status: 200, headers: { "Content-Type": "application/json" } },
),
);
const installed = await installMiniappFromBlob("22222222-2222-2222-2222-222222222222");
expect(installed.manifest).toEqual(validManifest);
const persisted = await getMiniappPackage(installed.id);
expect(persisted).toBeDefined();
expect(await persisted!.html.text()).toBe("<html><body>installed</body></html>");
});
it("throws MiniappNoLongerAvailableError for a 404 and stores nothing", async () => {
stubFetch(async () => new Response(JSON.stringify({ error: "not found" }), { status: 404 }));
await expect(installMiniappFromBlob("deleted-id")).rejects.toThrow(
MiniappNoLongerAvailableError,
);
expect(await db.miniappPackages.toArray()).toHaveLength(0);
});
it("rejects a re-fetched manifest that fails real validation rather than storing it", async () => {
const invalidManifest = { ...validManifest, permissions: ["not-a-real-permission"] };
stubFetch(async () =>
new Response(JSON.stringify({ manifest: invalidManifest, html: "<p>x</p>" }), {
status: 200,
headers: { "Content-Type": "application/json" },
}),
);
await expect(installMiniappFromBlob("some-id")).rejects.toThrow(ManifestValidationError);
expect(await db.miniappPackages.toArray()).toHaveLength(0);
});
});
describe("miniappSharing.decodeInstallUrlFromImage", () => {
it("decodes a real qrcode-rendered install URL back via real jsQR, with no camera involved", async () => {
const url = buildInstallUrl("33333333-3333-3333-3333-333333333333", "https://commons.example");
const image = await renderTextToImageData(url);
expect(decodeInstallUrlFromImage(image)).toBe(url);
});
it("returns null for a QR that doesn't encode an install URL", async () => {
const image = await renderTextToImageData("https://commons.example/miniapp/fair-share");
expect(decodeInstallUrlFromImage(image)).toBeNull();
});
it("returns null for an image with no QR code at all", () => {
const blank = {
data: new Uint8ClampedArray(64 * 64 * 4).fill(255),
width: 64,
height: 64,
};
expect(decodeInstallUrlFromImage(blank)).toBeNull();
});
});
+221
View File
@@ -0,0 +1,221 @@
/**
* Cross-device install-QR sharing flow for an uploaded mini-app (plan todo
* 55, Wave 6 upload).
*
* The SENDING device bundles an already-uploaded mini-app package's
* manifest + HTML (todo 53/54) into a single JSON payload, POSTs it to the
* real minimal blob/KV backend (todo 56, `api/blob/index.ts`), and renders
* an install URL + QR code (the real `qrcode` package, already used by
* Assembly's QR-sneakernet transport, `src/lib/qrSneakernet.ts`) that any
* other device can scan.
*
* The RECEIVING device decodes the QR (the real `jsqr` package - same
* library, same sneakernet precedent), GETs the payload back from the blob
* backend by id, re-validates the manifest with the real
* `assertValidManifest` (todo 53 - a payload that arrived over the wire is
* never trusted just because it round-tripped), and stores it locally via
* the real `uploadMiniapp` (todo 54) - the exact same write path a local
* upload uses. No identity/account step is involved anywhere in this
* module: installing a shared mini-app never requires the receiving
* resident to create an account (draft D9 - frictionless).
*/
import QRCode from "qrcode";
import jsQR from "jsqr";
import { assertValidManifest, type MiniappManifest } from "./miniappManifest";
import {
findPackageBySourceBlobId,
uploadMiniapp,
type StoredMiniappPackage,
} from "./miniappUpload";
/** The wire payload stored at the blob id: the manifest + HTML bundled
* together so a single GET is enough for the receiving device to install. */
interface SharedMiniappPayload {
manifest: MiniappManifest;
html: string;
}
/** Base error for anything this sharing flow rejects. */
export class MiniappShareError extends Error {
constructor(message: string) {
super(message);
this.name = "MiniappShareError";
}
}
/**
* Thrown when an install URL's referenced blob no longer exists - e.g. the
* shared mini-app was deleted after the QR was generated. Callers must
* surface this as a clear, specific message rather than a generic failure
* or a crash.
*/
export class MiniappNoLongerAvailableError extends MiniappShareError {
readonly blobId: string;
constructor(blobId: string) {
super(
`This mini-app is no longer available (it may have been deleted). Ask the sender to share it again.`,
);
this.name = "MiniappNoLongerAvailableError";
this.blobId = blobId;
}
}
/** Path prefix for install deep links, e.g. `/install/<blobId>`. */
export const INSTALL_PATH_PREFIX = "/install/";
/** Builds the install URL a QR code encodes for `blobId`. Defaults to the
* current page's origin (how this behaves in the shipped PWA - the same
* origin serves both the static frontend and the `/api/blob` functions);
* callers outside a browser (tests, scripts) pass `origin` explicitly. */
export function buildInstallUrl(blobId: string, origin?: string): string {
const base = origin ?? (typeof window !== "undefined" ? window.location.origin : "");
return `${base}${INSTALL_PATH_PREFIX}${blobId}`;
}
/** Extracts the blob id from an install URL produced by {@link buildInstallUrl},
* or `null` if `url` doesn't look like one. */
export function parseBlobIdFromInstallUrl(url: string): string | null {
try {
const { pathname } = new URL(url);
if (!pathname.startsWith(INSTALL_PATH_PREFIX)) return null;
const id = pathname.slice(INSTALL_PATH_PREFIX.length);
return id.length > 0 ? id : null;
} catch {
return null;
}
}
export interface ShareOptions {
/** Base URL of the blob/KV backend's POST endpoint. Defaults to the
* same-origin `/api/blob` path (how the shipped PWA reaches it; the
* local dev server proxies this to `api/_lib/devServer.ts`, see
* `vite.config.ts`). Tests pass an explicit absolute URL. */
apiBaseUrl?: string;
/** Origin embedded in the generated install URL. Defaults to
* `window.location.origin`. */
origin?: string;
}
export interface ShareResult {
/** The id the backend assigned this shared payload. */
blobId: string;
/** The deep link another device's install flow fetches and installs. */
installUrl: string;
/** A PNG data URL (from the real `qrcode` package) encoding `installUrl`,
* ready to render on screen for a camera to scan. */
qrDataUrl: string;
}
/**
* Packages `record`'s manifest + HTML, POSTs it to the real `/api/blob`
* backend, and returns an install URL + QR code for another device to
* scan. Throws `MiniappShareError` if the backend rejects the upload (e.g.
* oversized - `api/_lib/blobStore.ts`'s real 413 contract).
*/
export async function shareMiniapp(
record: StoredMiniappPackage,
options: ShareOptions = {},
): Promise<ShareResult> {
const apiBaseUrl = options.apiBaseUrl ?? "/api/blob";
const payload: SharedMiniappPayload = {
manifest: record.manifest,
html: await record.html.text(),
};
const res = await fetch(apiBaseUrl, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
if (!res.ok) {
const detail = await res.text().catch(() => "");
throw new MiniappShareError(
`failed to share mini-app: backend responded ${res.status}${detail ? ` (${detail})` : ""}`,
);
}
const { id } = (await res.json()) as { id: string };
const installUrl = buildInstallUrl(id, options.origin);
const qrDataUrl = await QRCode.toDataURL(installUrl, { errorCorrectionLevel: "M" });
return { blobId: id, installUrl, qrDataUrl };
}
export interface InstallOptions {
/** Base URL of the blob/KV backend (the `/api/blob` collection, not
* including the id). Defaults to the same-origin `/api/blob` path. */
apiBaseUrl?: string;
}
/**
* Fetches the shared payload for `blobId` from the real `/api/blob`
* backend, re-validates its manifest with the real `assertValidManifest`,
* and stores it locally via the real `uploadMiniapp` write path - the
* same surface a local upload uses, so the installed package shows up
* wherever `listMiniappPackages` is read (the home grid). Throws
* `MiniappNoLongerAvailableError` for a 404 (deleted or never existed)
* rather than a generic failure or a crash. Involves no identity/account
* step: this device's own non-custodial identity (already bootstrapped by
* the shell) is never touched here. Idempotent per `blobId`: re-installing
* an already-installed shared package (re-opening the same install link,
* or a duplicate call from a double effect run) returns the existing
* record rather than creating a second tile for the same mini-app.
*/
export async function installMiniappFromBlob(
blobId: string,
options: InstallOptions = {},
): Promise<StoredMiniappPackage> {
const already = await findPackageBySourceBlobId(blobId);
if (already) return already;
const apiBaseUrl = options.apiBaseUrl ?? "/api/blob";
const res = await fetch(`${apiBaseUrl}/${blobId}`);
if (res.status === 404) {
throw new MiniappNoLongerAvailableError(blobId);
}
if (!res.ok) {
throw new MiniappShareError(
`failed to fetch shared mini-app: backend responded ${res.status}`,
);
}
const payload = (await res.json()) as SharedMiniappPayload;
const manifest = assertValidManifest(payload.manifest);
try {
return await uploadMiniapp({ manifest, html: payload.html, sourceBlobId: blobId });
} catch (err) {
// Two concurrent installs of the SAME blobId (e.g. React StrictMode's
// dev-mode double effect run, or re-opening the same install link in
// two tabs at once) both pass the `already` check above before either
// writes. The database's own unique `sourceBlobId` index (db.ts) is
// what actually resolves the race: the loser's insert throws here, and
// by then the winner's record is already committed - return it instead
// of surfacing a confusing constraint error.
const winner = await findPackageBySourceBlobId(blobId);
if (winner) return winner;
throw err;
}
}
/** One decoded camera/image frame's raw RGBA pixels, as produced by
* `canvas.getImageData` - the same shape Assembly's QR-sneakernet
* transport scans (`src/lib/qrSneakernet.ts`), kept independent here so
* this module has no import-time dependency on that one. */
export interface ScannedImage {
data: Uint8ClampedArray;
width: number;
height: number;
}
/**
* Decodes an install URL out of a scanned QR image using the real `jsqr`
* package, bypassing the camera entirely for an automated caller that
* already has pixel data (e.g. a canvas-rendered QR, or a captured camera
* frame). Returns `null` if no QR is found, or if what was found doesn't
* look like an install URL this module produced.
*/
export function decodeInstallUrlFromImage(image: ScannedImage): string | null {
const result = jsQR(image.data, image.width, image.height);
if (!result) return null;
return parseBlobIdFromInstallUrl(result.data) !== null ? result.data : null;
}
+14
View File
@@ -24,6 +24,10 @@ export interface MiniappUploadInput {
manifest: unknown; manifest: unknown;
/** Raw HTML source of the mini-app, as uploaded. */ /** Raw HTML source of the mini-app, as uploaded. */
html: string; html: string;
/** Set by the install-QR sharing flow (todo 55, src/lib/miniappSharing.ts)
* to the blob id this package was installed from; omitted for a direct
* local upload. */
sourceBlobId?: string;
} }
function generatePackageId(): string { function generatePackageId(): string {
@@ -50,6 +54,7 @@ export async function uploadMiniapp(
manifest, manifest,
html: new Blob([input.html], { type: "text/html" }), html: new Blob([input.html], { type: "text/html" }),
installedAt: Date.now(), installedAt: Date.now(),
sourceBlobId: input.sourceBlobId,
}; };
await db.miniappPackages.add(record); await db.miniappPackages.add(record);
@@ -68,6 +73,15 @@ export async function listMiniappPackages(): Promise<StoredMiniappPackage[]> {
return db.miniappPackages.toArray(); return db.miniappPackages.toArray();
} }
/** The already-installed package sourced from `blobId` via the install-QR
* sharing flow, or `undefined` if none exists yet. */
export async function findPackageBySourceBlobId(
blobId: string,
): Promise<StoredMiniappPackage | undefined> {
const all = await db.miniappPackages.toArray();
return all.find((pkg) => pkg.sourceBlobId === blobId);
}
/** Decode a stored package's HTML blob back into text. */ /** Decode a stored package's HTML blob back into text. */
export async function readPackageHtml( export async function readPackageHtml(
record: StoredMiniappPackage, record: StoredMiniappPackage,
+6
View File
@@ -41,3 +41,9 @@
text-align: center; text-align: center;
color: #1f2430; color: #1f2430;
} }
.iconImage {
width: 32px;
height: 32px;
object-fit: contain;
}
+34 -2
View File
@@ -1,12 +1,20 @@
// @vitest-environment happy-dom // @vitest-environment happy-dom
import "@testing-library/jest-dom/vitest"; import "@testing-library/jest-dom/vitest";
import { cleanup, fireEvent, render, screen } from "@testing-library/react"; import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { db } from "../lib/db";
import { uploadMiniapp } from "../lib/miniappUpload";
import { HomeGrid } from "./HomeGrid"; import { HomeGrid } from "./HomeGrid";
import { miniappRegistry } from "./miniappRegistry"; import { miniappRegistry } from "./miniappRegistry";
afterEach(cleanup); afterEach(cleanup);
beforeEach(async () => {
indexedDB.deleteDatabase(db.name);
db.close();
await db.open();
});
describe("HomeGrid", () => { describe("HomeGrid", () => {
it("renders exactly one tile per registry entry with correct icon and label", () => { it("renders exactly one tile per registry entry with correct icon and label", () => {
render(<HomeGrid onNavigate={() => {}} />); render(<HomeGrid onNavigate={() => {}} />);
@@ -32,4 +40,28 @@ describe("HomeGrid", () => {
expect(onNavigate).toHaveBeenCalledTimes(1); expect(onNavigate).toHaveBeenCalledTimes(1);
expect(onNavigate).toHaveBeenCalledWith(target.id); expect(onNavigate).toHaveBeenCalledWith(target.id);
}); });
it("renders an additional tile for each locally installed mini-app package and navigates via onNavigatePackage", async () => {
const installed = await uploadMiniapp({
manifest: {
name: "Shared Garden Tracker",
icon: "\uD83C\uDF31",
entryPoint: "index.html",
permissions: ["ledger.read"],
},
html: "<p>hi</p>",
});
const onNavigatePackage = vi.fn();
render(<HomeGrid onNavigate={() => {}} onNavigatePackage={onNavigatePackage} />);
const installedTile = await screen.findByTestId(`installed-tile-${installed.id}`);
expect(installedTile).toHaveTextContent("Shared Garden Tracker");
await waitFor(() => {
expect(screen.getAllByRole("button")).toHaveLength(miniappRegistry.length + 1);
});
fireEvent.click(installedTile);
expect(onNavigatePackage).toHaveBeenCalledWith(installed.id);
});
}); });
+40 -1
View File
@@ -1,11 +1,35 @@
import { useEffect, useState } from "react";
import { listMiniappPackages, type StoredMiniappPackage } from "../lib/miniappUpload";
import styles from "./HomeGrid.module.css"; import styles from "./HomeGrid.module.css";
import { miniappRegistry } from "./miniappRegistry"; import { miniappRegistry } from "./miniappRegistry";
export interface HomeGridProps { export interface HomeGridProps {
onNavigate: (miniappId: string) => void; onNavigate: (miniappId: string) => void;
/** Fired when an installed (not statically registered) mini-app package
* tile is clicked - see `src/lib/miniappSharing.ts` / todo 55. */
onNavigatePackage?: (packageId: string) => void;
} }
export function HomeGrid({ onNavigate }: HomeGridProps) { function TileIcon({ icon }: { icon: string }) {
if (icon.startsWith("data:") || icon.startsWith("http:") || icon.startsWith("https:")) {
return <img src={icon} alt="" className={styles.iconImage} />;
}
return <>{icon}</>;
}
export function HomeGrid({ onNavigate, onNavigatePackage }: HomeGridProps) {
const [packages, setPackages] = useState<StoredMiniappPackage[]>([]);
useEffect(() => {
let cancelled = false;
listMiniappPackages().then((records) => {
if (!cancelled) setPackages(records);
});
return () => {
cancelled = true;
};
}, []);
return ( return (
<div className={styles.grid} role="grid" aria-label="Miniapps"> <div className={styles.grid} role="grid" aria-label="Miniapps">
{miniappRegistry.map((entry) => ( {miniappRegistry.map((entry) => (
@@ -22,6 +46,21 @@ export function HomeGrid({ onNavigate }: HomeGridProps) {
<span className={styles.label}>{entry.label}</span> <span className={styles.label}>{entry.label}</span>
</button> </button>
))} ))}
{packages.map((pkg) => (
<button
key={`package:${pkg.id}`}
type="button"
className={styles.tile}
onClick={() => onNavigatePackage?.(pkg.id)}
aria-label={pkg.manifest.name}
data-testid={`installed-tile-${pkg.id}`}
>
<span className={styles.icon} aria-hidden="true">
<TileIcon icon={pkg.manifest.icon} />
</span>
<span className={styles.label}>{pkg.manifest.name}</span>
</button>
))}
</div> </div>
); );
} }
+6 -1
View File
@@ -4,5 +4,10 @@ import { HomeGrid } from "./HomeGrid";
export function HomePage() { export function HomePage() {
const navigate = useNavigate(); const navigate = useNavigate();
return <HomeGrid onNavigate={(miniappId) => navigate(`/miniapp/${miniappId}`)} />; return (
<HomeGrid
onNavigate={(miniappId) => navigate(`/miniapp/${miniappId}`)}
onNavigatePackage={(packageId) => navigate(`/package/${packageId}`)}
/>
);
} }
+16
View File
@@ -0,0 +1,16 @@
.status {
padding: 2rem 1rem;
text-align: center;
color: #1f2430;
}
.goHomeButton {
margin-top: 1rem;
background: #1677ff;
color: #fff;
border: none;
border-radius: 8px;
padding: 0.6rem 1rem;
font: inherit;
cursor: pointer;
}
+74
View File
@@ -0,0 +1,74 @@
// @vitest-environment happy-dom
import "@testing-library/jest-dom/vitest";
import { cleanup, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { db } from "../lib/db";
import { InstallMiniappScreen } from "./InstallMiniappScreen";
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
beforeEach(async () => {
indexedDB.deleteDatabase(db.name);
db.close();
await db.open();
});
function renderAt(blobId: string) {
return render(
<MemoryRouter initialEntries={[`/install/${blobId}`]}>
<Routes>
<Route path="install/:blobId" element={<InstallMiniappScreen />} />
</Routes>
</MemoryRouter>,
);
}
const sharedManifest = {
name: "Shared Garden Tracker",
icon: "\uD83C\uDF31",
entryPoint: "index.html",
permissions: ["ledger.read"],
};
describe("InstallMiniappScreen", () => {
it("installs the fetched mini-app via the real write path and lets the resident go home - no account step", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () =>
new Response(
JSON.stringify({ manifest: sharedManifest, html: "<p>garden</p>" }),
{ status: 200, headers: { "Content-Type": "application/json" } },
),
),
);
renderAt("55555555-5555-5555-5555-555555555555");
await waitFor(() => {
expect(screen.getByTestId("install-success")).toHaveTextContent("Shared Garden Tracker");
});
expect(await db.miniappPackages.toArray()).toHaveLength(1);
expect(screen.queryByRole("button", { name: /sign in|create account|log in/i })).toBeNull();
});
it("shows a clear 'no longer available' message, not a crash, when the shared mini-app was deleted", async () => {
vi.stubGlobal(
"fetch",
vi.fn(async () => new Response(JSON.stringify({ error: "not found" }), { status: 404 })),
);
renderAt("deleted-blob-id");
await waitFor(() => {
expect(screen.getByTestId("miniapp-no-longer-available")).toBeInTheDocument();
});
expect(screen.getByTestId("miniapp-no-longer-available")).toHaveTextContent(
/no longer available/i,
);
expect(await db.miniappPackages.toArray()).toHaveLength(0);
});
});
+96
View File
@@ -0,0 +1,96 @@
import { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import {
installMiniappFromBlob,
MiniappNoLongerAvailableError,
} from "../lib/miniappSharing";
import type { StoredMiniappPackage } from "../lib/miniappUpload";
import styles from "./InstallMiniappScreen.module.css";
type InstallState =
| { status: "installing" }
| { status: "installed"; record: StoredMiniappPackage }
| { status: "unavailable"; message: string }
| { status: "error"; message: string };
/**
* The receiving end of the install-QR sharing flow (plan todo 55). Routed
* at `/install/:blobId` - the deep link a scanned QR resolves to. Fetches
* and installs via the real `installMiniappFromBlob` with no identity or
* account step of any kind, then hands the resident straight to their home
* grid where the installed mini-app now shows up as a tile.
*/
export function InstallMiniappScreen() {
const { blobId } = useParams<{ blobId: string }>();
const navigate = useNavigate();
const [state, setState] = useState<InstallState>({ status: "installing" });
useEffect(() => {
let cancelled = false;
if (!blobId) {
setState({ status: "error", message: "No mini-app was specified to install." });
return;
}
installMiniappFromBlob(blobId)
.then((record) => {
if (!cancelled) setState({ status: "installed", record });
})
.catch((err: unknown) => {
if (cancelled) return;
if (err instanceof MiniappNoLongerAvailableError) {
setState({ status: "unavailable", message: err.message });
} else {
setState({
status: "error",
message: err instanceof Error ? err.message : String(err),
});
}
});
return () => {
cancelled = true;
};
}, [blobId]);
if (state.status === "installing") {
return (
<div className={styles.status} data-testid="install-in-progress">
Installing mini-app…
</div>
);
}
if (state.status === "unavailable") {
return (
<div
className={styles.status}
role="alert"
data-testid="miniapp-no-longer-available"
>
{state.message}
</div>
);
}
if (state.status === "error") {
return (
<div className={styles.status} role="alert" data-testid="install-error">
{state.message}
</div>
);
}
return (
<div className={styles.status} data-testid="install-success">
<p>“{state.record.manifest.name}” installed.</p>
<button
type="button"
className={styles.goHomeButton}
onClick={() => navigate("/")}
>
Go to home
</button>
</div>
);
}
@@ -0,0 +1,4 @@
.screen {
display: flex;
flex-direction: column;
}
+55
View File
@@ -0,0 +1,55 @@
// @vitest-environment happy-dom
import "@testing-library/jest-dom/vitest";
import { cleanup, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter, Route, Routes } from "react-router-dom";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { db } from "../lib/db";
import { uploadMiniapp } from "../lib/miniappUpload";
import { InstalledMiniappScreen } from "./InstalledMiniappScreen";
afterEach(cleanup);
beforeEach(async () => {
indexedDB.deleteDatabase(db.name);
db.close();
await db.open();
});
function renderAt(packageId: string) {
return render(
<MemoryRouter initialEntries={[`/package/${packageId}`]}>
<Routes>
<Route path="package/:packageId" element={<InstalledMiniappScreen />} />
</Routes>
</MemoryRouter>,
);
}
describe("InstalledMiniappScreen", () => {
it("mounts the installed package and offers a real share panel for it", async () => {
const record = await uploadMiniapp({
manifest: {
name: "Shared Garden Tracker",
icon: "\uD83C\uDF31",
entryPoint: "index.html",
permissions: ["ledger.read"],
},
html: "<p>garden</p>",
});
renderAt(record.id);
await waitFor(() => {
expect(screen.getByTestId("miniapp-mount-container")).toBeInTheDocument();
});
expect(screen.getByTestId("share-install-qr")).toBeInTheDocument();
});
it("renders the not-found fallback for an unknown package id, not a crash", async () => {
renderAt("no-such-package");
await waitFor(() => {
expect(screen.getByTestId("miniapp-not-found")).toBeInTheDocument();
});
});
});
+36
View File
@@ -0,0 +1,36 @@
import { useEffect, useState } from "react";
import { useParams } from "react-router-dom";
import { getMiniappPackage, type StoredMiniappPackage } from "../lib/miniappUpload";
import { MountedMiniapp } from "./MountedMiniapp";
import { NotFoundMiniapp } from "./NotFoundMiniapp";
import { ShareInstallQr } from "./ShareInstallQr";
import styles from "./InstalledMiniappScreen.module.css";
export function InstalledMiniappScreen() {
const { packageId } = useParams<{ packageId: string }>();
const [record, setRecord] = useState<StoredMiniappPackage | null>();
useEffect(() => {
let cancelled = false;
if (!packageId) {
setRecord(null);
return;
}
getMiniappPackage(packageId).then((found) => {
if (!cancelled) setRecord(found ?? null);
});
return () => {
cancelled = true;
};
}, [packageId]);
if (record === null) return <NotFoundMiniapp />;
if (record === undefined) return null;
return (
<div className={styles.screen}>
<ShareInstallQr record={record} />
<MountedMiniapp record={record} />
</div>
);
}
+46
View File
@@ -0,0 +1,46 @@
.panel {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.75rem;
padding: 1rem;
}
.shareButton {
background: #1677ff;
color: #fff;
border: none;
border-radius: 8px;
padding: 0.6rem 1rem;
font: inherit;
cursor: pointer;
}
.shareButton:disabled {
opacity: 0.6;
cursor: default;
}
.error {
color: #d4380d;
}
.result {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 0.5rem;
}
.qrImage {
width: 200px;
height: 200px;
border-radius: 8px;
border: 1px solid #e5e8eb;
}
.installUrl {
color: #1677ff;
word-break: break-all;
font-size: 0.85rem;
}
+69
View File
@@ -0,0 +1,69 @@
// @vitest-environment happy-dom
import "@testing-library/jest-dom/vitest";
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { db } from "../lib/db";
import { uploadMiniapp, type StoredMiniappPackage } from "../lib/miniappUpload";
import { ShareInstallQr } from "./ShareInstallQr";
afterEach(() => {
cleanup();
vi.unstubAllGlobals();
});
beforeEach(async () => {
indexedDB.deleteDatabase(db.name);
db.close();
await db.open();
});
const manifest = {
name: "Shared Garden Tracker",
icon: "\uD83C\uDF31",
entryPoint: "index.html",
permissions: ["ledger.read"],
};
async function storeSamplePackage(): Promise<StoredMiniappPackage> {
return uploadMiniapp({ manifest, html: "<p>hi</p>" });
}
describe("ShareInstallQr", () => {
it("generates and displays the real install QR + URL after a click", async () => {
const record = await storeSamplePackage();
vi.stubGlobal(
"fetch",
vi.fn(async () =>
new Response(JSON.stringify({ id: "44444444-4444-4444-4444-444444444444" }), {
status: 201,
headers: { "Content-Type": "application/json" },
}),
),
);
render(<ShareInstallQr record={record} />);
fireEvent.click(screen.getByRole("button", { name: "Share install QR" }));
const qrImage = await screen.findByTestId("install-qr-image");
expect(qrImage.getAttribute("src")).toMatch(/^data:image\/png;base64,/);
expect(screen.getByTestId("install-url")).toHaveTextContent(
"/install/44444444-4444-4444-4444-444444444444",
);
});
it("surfaces a clear error instead of crashing when sharing fails", async () => {
const record = await storeSamplePackage();
vi.stubGlobal(
"fetch",
vi.fn(async () => new Response("oversized", { status: 413 })),
);
render(<ShareInstallQr record={record} />);
fireEvent.click(screen.getByRole("button", { name: "Share install QR" }));
await waitFor(() => {
expect(screen.getByTestId("share-error")).toBeInTheDocument();
});
expect(screen.queryByTestId("install-qr-image")).not.toBeInTheDocument();
});
});
+57
View File
@@ -0,0 +1,57 @@
import { useState } from "react";
import type { StoredMiniappPackage } from "../lib/miniappUpload";
import { shareMiniapp, type ShareResult } from "../lib/miniappSharing";
import styles from "./ShareInstallQr.module.css";
export function ShareInstallQr({ record }: { record: StoredMiniappPackage }) {
const [share, setShare] = useState<ShareResult>();
const [error, setError] = useState<string>();
const [pending, setPending] = useState(false);
async function handleShare() {
setPending(true);
setError(undefined);
try {
setShare(await shareMiniapp(record));
} catch (err) {
setError(err instanceof Error ? err.message : String(err));
} finally {
setPending(false);
}
}
return (
<div className={styles.panel} data-testid="share-install-qr">
<button
type="button"
className={styles.shareButton}
onClick={handleShare}
disabled={pending}
>
{pending ? "Preparing install QR…" : "Share install QR"}
</button>
{error && (
<p className={styles.error} role="alert" data-testid="share-error">
{error}
</p>
)}
{share && (
<div className={styles.result} data-testid="share-result">
<img
className={styles.qrImage}
src={share.qrDataUrl}
alt={`Install QR code for ${record.manifest.name}`}
data-testid="install-qr-image"
/>
<a
className={styles.installUrl}
href={share.installUrl}
data-testid="install-url"
>
{share.installUrl}
</a>
</div>
)}
</div>
);
}
+14
View File
@@ -4,6 +4,20 @@ import { VitePWA } from 'vite-plugin-pwa'
// https://vite.dev/config/ // https://vite.dev/config/
export default defineConfig({ export default defineConfig({
server: {
// Local dev only: forwards the frontend's same-origin '/api/blob*'
// calls (install-QR cross-device sharing, todo 55) to the local blob
// API dev server (`node api/_lib/devServer.ts`, todo 56). At deploy
// time (todo 57) this proxy is unnecessary - Vercel serves `api/*.ts`
// functions from the exact same origin as the static frontend
// automatically, so '/api/blob' already resolves without a proxy.
proxy: {
'/api': {
target: `http://127.0.0.1:${process.env.BLOB_API_PORT ?? 3001}`,
changeOrigin: true,
},
},
},
plugins: [ plugins: [
react(), react(),
// Workbox-based service worker: precaches the app shell (HTML/JS/CSS // Workbox-based service worker: precaches the app shell (HTML/JS/CSS