diff --git a/.omo/evidence/the-commons-hollow/task-55-the-commons-hollow-missing.json b/.omo/evidence/the-commons-hollow/task-55-the-commons-hollow-missing.json
new file mode 100644
index 0000000..baf7567
--- /dev/null
+++ b/.omo/evidence/the-commons-hollow/task-55-the-commons-hollow-missing.json
@@ -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
+}
\ No newline at end of file
diff --git a/.omo/evidence/the-commons-hollow/task-55-the-commons-hollow.json b/.omo/evidence/the-commons-hollow/task-55-the-commons-hollow.json
new file mode 100644
index 0000000..854c45e
--- /dev/null
+++ b/.omo/evidence/the-commons-hollow/task-55-the-commons-hollow.json
@@ -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
+}
\ No newline at end of file
diff --git a/demo/qr-scan.html b/demo/qr-scan.html
new file mode 100644
index 0000000..78ffca8
--- /dev/null
+++ b/demo/qr-scan.html
@@ -0,0 +1,10 @@
+
+
+
+
+ install-QR scan harness (test support, todo 55)
+
+
+
+
+
diff --git a/demo/qrScanHarness.ts b/demo/qrScanHarness.ts
new file mode 100644
index 0000000..db4aea0
--- /dev/null
+++ b/demo/qrScanHarness.ts
@@ -0,0 +1,36 @@
+import { decodeInstallUrlFromImage } from "../src/lib/miniappSharing.ts";
+
+declare global {
+ interface Window {
+ qrScanHarness: {
+ decodeDataUrl(dataUrl: string): Promise;
+ };
+ }
+}
+
+function loadImage(dataUrl: string): Promise {
+ 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 {
+ 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 };
diff --git a/e2e/installShare.e2e.mjs b/e2e/installShare.e2e.mjs
new file mode 100644
index 0000000..32d3d63
--- /dev/null
+++ b/e2e/installShare.e2e.mjs
@@ -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: `
${manifestName}
`,
+ });
+ 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;
+});
diff --git a/package.json b/package.json
index 78883e1..3d4b22e 100644
--- a/package.json
+++ b/package.json
@@ -5,6 +5,7 @@
"type": "module",
"scripts": {
"dev": "vite",
+ "dev:api": "node api/_lib/devServer.ts",
"build": "tsc -b && vite build",
"lint": "oxlint",
"preview": "vite preview",
diff --git a/src/AppRoutes.tsx b/src/AppRoutes.tsx
index f707409..e094391 100644
--- a/src/AppRoutes.tsx
+++ b/src/AppRoutes.tsx
@@ -1,6 +1,8 @@
import { Route, Routes } from "react-router-dom";
import { AdminSeedPanel } from "./admin/AdminSeedPanel";
import { HomePage } from "./shell/HomePage";
+import { InstallMiniappScreen } from "./shell/InstallMiniappScreen";
+import { InstalledMiniappScreen } from "./shell/InstalledMiniappScreen";
import { MiniappOutlet } from "./shell/MiniappOutlet";
import { NotFoundMiniapp } from "./shell/NotFoundMiniapp";
import { ShellLayout } from "./shell/ShellLayout";
@@ -12,6 +14,8 @@ export function AppRoutes() {
}>
} />
} />
+ } />
+ } />
} />
diff --git a/src/lib/db.ts b/src/lib/db.ts
index 08e0f9b..d0efd12 100644
--- a/src/lib/db.ts
+++ b/src/lib/db.ts
@@ -47,6 +47,14 @@ export interface MiniappPackageRecord {
/** Raw HTML source of the mini-app, stored as a blob. */
html: Blob;
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 {
@@ -68,6 +76,17 @@ export class CommonsDatabase extends Dexie {
eventLog: "++id, lamportTs",
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",
+ });
}
}
diff --git a/src/lib/miniappSharing.test.ts b/src/lib/miniappSharing.test.ts
new file mode 100644
index 0000000..3792ac3
--- /dev/null
+++ b/src/lib/miniappSharing.test.ts
@@ -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 = "shared mini-app"): Promise {
+ 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: "shared mini-app",
+ });
+ 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: "installed" }),
+ { 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("installed");
+ });
+
+ 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: "
x
" }), {
+ 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();
+ });
+});
diff --git a/src/lib/miniappSharing.ts b/src/lib/miniappSharing.ts
new file mode 100644
index 0000000..7a2ad6e
--- /dev/null
+++ b/src/lib/miniappSharing.ts
@@ -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/`. */
+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 {
+ 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 {
+ 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;
+}
diff --git a/src/lib/miniappUpload.ts b/src/lib/miniappUpload.ts
index 0182b88..004268f 100644
--- a/src/lib/miniappUpload.ts
+++ b/src/lib/miniappUpload.ts
@@ -24,6 +24,10 @@ export interface MiniappUploadInput {
manifest: unknown;
/** Raw HTML source of the mini-app, as uploaded. */
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 {
@@ -50,6 +54,7 @@ export async function uploadMiniapp(
manifest,
html: new Blob([input.html], { type: "text/html" }),
installedAt: Date.now(),
+ sourceBlobId: input.sourceBlobId,
};
await db.miniappPackages.add(record);
@@ -68,6 +73,15 @@ export async function listMiniappPackages(): Promise {
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 {
+ const all = await db.miniappPackages.toArray();
+ return all.find((pkg) => pkg.sourceBlobId === blobId);
+}
+
/** Decode a stored package's HTML blob back into text. */
export async function readPackageHtml(
record: StoredMiniappPackage,
diff --git a/src/shell/HomeGrid.module.css b/src/shell/HomeGrid.module.css
index 5748413..b9e8770 100644
--- a/src/shell/HomeGrid.module.css
+++ b/src/shell/HomeGrid.module.css
@@ -41,3 +41,9 @@
text-align: center;
color: #1f2430;
}
+
+.iconImage {
+ width: 32px;
+ height: 32px;
+ object-fit: contain;
+}
diff --git a/src/shell/HomeGrid.test.tsx b/src/shell/HomeGrid.test.tsx
index 7613011..db8f2eb 100644
--- a/src/shell/HomeGrid.test.tsx
+++ b/src/shell/HomeGrid.test.tsx
@@ -1,12 +1,20 @@
// @vitest-environment happy-dom
import "@testing-library/jest-dom/vitest";
-import { cleanup, fireEvent, render, screen } from "@testing-library/react";
-import { afterEach, describe, expect, it, vi } from "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 } from "../lib/miniappUpload";
import { HomeGrid } from "./HomeGrid";
import { miniappRegistry } from "./miniappRegistry";
afterEach(cleanup);
+beforeEach(async () => {
+ indexedDB.deleteDatabase(db.name);
+ db.close();
+ await db.open();
+});
+
describe("HomeGrid", () => {
it("renders exactly one tile per registry entry with correct icon and label", () => {
render( {}} />);
@@ -32,4 +40,28 @@ describe("HomeGrid", () => {
expect(onNavigate).toHaveBeenCalledTimes(1);
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: "
+ );
+}
diff --git a/vite.config.ts b/vite.config.ts
index df71d0a..0e116c4 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -4,6 +4,20 @@ import { VitePWA } from 'vite-plugin-pwa'
// https://vite.dev/config/
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: [
react(),
// Workbox-based service worker: precaches the app shell (HTML/JS/CSS