Multiplayer agent harness for work.
feat: embed interactive playgrounds in the web thread
Sina Matianf1981fe80cca
diff --git a/plugins/portal/README.md b/plugins/portal/README.mdindex 39c3ccbad..df6c311f4 100644--- a/plugins/portal/README.md+++ b/plugins/portal/README.md@@ -6,10 +6,11 @@ fronts every surface. It does provider-neutral **OIDC** sign-in (Google Workspacis the email-first deployment default) and reverse-proxies — over Fly's private 6PN — to thesurfaces, which all stay **private** (no public `[http_service]` of their own):-| Path | → upstream | Notes |-| ----------- | ----------------- | ----------------------------------------------------------------------------- |-| `/*` (root) | `<prefix>-web-ui` | Pi web UI SPA, root-mounted (`/web-ui/*` 308-redirects to root for old links) |-| `/admin/*` | `<prefix>-admin` | governance — admin access derived from the core (`canAdminister`) |+| Path | → upstream | Notes |+| ------------- | ----------------- | ----------------------------------------------------------------------------- |+| `/*` (root) | `<prefix>-web-ui` | Pi web UI SPA, root-mounted (`/web-ui/*` 308-redirects to root for old links) |+| `/admin/*` | `<prefix>-admin` | governance — admin access derived from the core (`canAdminister`) |+| `/m/:id/:key` | core | public bearer HTML playgrounds (miniapps); no session; CSP-sandboxed |User deployments are never served on this authenticated origin; they use the dedicated apps domain.@@ -27,10 +28,12 @@ surfaces, and it does **not** import the core.the subject from userinfo. The verified `sub` **is** the core principal id. It mints asigned `portal_session` cookie (`{sub, org, auth, exp}`, HMAC, 8h sliding lifetime with a24h absolute maximum by default).-3. **Proxy** — every other path requires a valid session. The portal picks the upstream by the- **exact first path segment**, strips the prefix, and proxies to the private upstream,- synthesizing the surface cookie for compatibility and attaching a short-lived signed portal- identity. Surfaces pass that identity to core, which verifies it before any user-scoped action.+3. **Proxy** — inbound webhooks, OAuth callbacks, and miniapp playgrounds (`GET /m/:id/:key`)+ pass through to core without a session. Every other path requires a valid session. The portal+ picks the upstream by the **exact first path segment**, strips the prefix, and proxies to the+ private upstream, synthesizing the surface cookie for compatibility and attaching a short-lived+ signed portal identity. Surfaces pass that identity to core, which verifies it before any+ user-scoped action.## Security model (the parts that must be right)diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.tsindex 16a001dd3..6ba56ad55 100644--- a/plugins/portal/src/index.ts+++ b/plugins/portal/src/index.ts@@ -959,6 +959,11 @@ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void>return proxyToUpstream(req, res, { baseUrl: CORE, path: pathname, search: url.search }, FORWARD_WEBHOOK_HEADERS);}+ if (method === "GET" && /^\/m\/[^/]+\/[^/]+$/.test(pathname)) {+ res.removeHeader("x-frame-options");+ return proxyToUpstream(req, res, { baseUrl: CORE, path: pathname, search: url.search }, ["accept"]);+ }+const consentBounce = (): void => {res.writeHead(302, { location: `/auth/login?returnTo=${encodeURIComponent(`${pathname}${url.search}`)}` });return void res.end();diff --git a/plugins/portal/test/router.test.ts b/plugins/portal/test/router.test.tsindex 668fe5bfa..1fb5c0d4d 100644--- a/plugins/portal/test/router.test.ts+++ b/plugins/portal/test/router.test.ts@@ -230,6 +230,21 @@ test("the webhook passthrough is exact-shape + POST-only (no widening of /v1)",assert.equal((await fetch(`${base}/v1/webhooks`, { method: "POST" })).status, 404);});+test("miniapps pass through to the core with NO session so Slack buttons and iframes work", async () => {+ const r = await fetch(`${base}/m/aa/bb`, { headers: { accept: "text/html" }, redirect: "manual" });+ assert.equal(r.status, 200);+ const body = (await r.json()) as { url: string; cookie: string | null };+ assert.equal(body.url, "/m/aa/bb");+ assert.equal(body.cookie, null);+ assert.equal(r.headers.get("x-frame-options"), null);+});++test("the miniapp passthrough is GET /m/:id/:key only", async () => {+ assert.equal((await fetch(`${base}/m/aa`, { redirect: "manual" })).status, 401);+ assert.equal((await fetch(`${base}/m/aa/bb/cc`, { redirect: "manual" })).status, 401);+ assert.equal((await fetch(`${base}/m/aa/bb`, { method: "POST", redirect: "manual" })).status, 401);+});+test("the provider callback still passes through publicly with NO session/cookie", async () => {const cb = await fetch(`${base}/v1/connectors/oauth/google/callback?code=c&state=s`, { redirect: "manual" });assert.equal(cb.status, 200);diff --git a/plugins/web-ui/server/index.ts b/plugins/web-ui/server/index.tsindex 3bc374989..60b8a2c9b 100644--- a/plugins/web-ui/server/index.ts+++ b/plugins/web-ui/server/index.ts@@ -2346,6 +2346,27 @@ const routeRequest = async (req: IncomingMessage, res: ServerResponse) => {return found.route.handle({ req, res, url, user, params: found.params });}+ if (method === "GET" && path.startsWith("/m/")) {+ const rest = path.slice("/m/".length);+ const slash = rest.indexOf("/");+ if (slash === -1) return json(res, 404, { error: "not_found" });+ const id = decodeURIComponent(rest.slice(0, slash));+ const key = decodeURIComponent(rest.slice(slash + 1).split("/")[0] ?? "");+ const corePath = `/m/${encodeURIComponent(id)}/${encodeURIComponent(key)}${url.search}`;+ const up = await fetch(`${CORE}${corePath}`, { method: "GET", redirect: "manual" });+ const buf = Buffer.from(await up.arrayBuffer());+ res.removeHeader("x-frame-options");+ res.writeHead(up.status, {+ "content-type": up.headers.get("content-type") ?? "text/html; charset=utf-8",+ "content-length": String(buf.length),+ "content-security-policy": up.headers.get("content-security-policy") ?? UNTRUSTED_CONTENT_SANDBOX_CSP,+ "x-content-type-options": "nosniff",+ "referrer-policy": "no-referrer",+ "cache-control": up.headers.get("cache-control") ?? "private, no-cache",+ });+ return res.end(buf);+ }+if (method === "GET" && path.startsWith("/deployments/")) {const user = cookieUser(req);if (!user) return unauthorized(res, req);diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.tsindex 9ff43b31d..11d40462f 100644--- a/plugins/web-ui/src/chat.ts+++ b/plugins/web-ui/src/chat.ts@@ -6,6 +6,7 @@ import "./marked-dedupe";import "@mariozechner/mini-lit/dist/MarkdownBlock.js";import "@mariozechner/mini-lit/dist/CodeBlock.js";import { html, nothing, render, type TemplateResult } from "lit";+import { unsafeHTML } from "lit/directives/unsafe-html.js";import {Activity,Ban,@@ -13,6 +14,7 @@ import {Check,ChevronRight,Clock3,+ Code2,Copy,FileImage,FileText,@@ -69,6 +71,16 @@ import {} from "./core-bridge";import { buildTimeline, toolRowKind, type TimelineItem, type ToolPayload, type ToolRowModel } from "./timeline";import { CONNECTOR_NAMES, connectorLinksIn, stripConnectorLinks, type ConnectorLink } from "./connector-link";+import {+ miniappsIn,+ miniappFrameSrc,+ miniappSourceSrc,+ formatMiniappHtml,+ currentMiniappTheme,+ stripMiniappDirectives,+ type MiniappEmbed,+} from "./miniapp";+import hljs, { whenHighlightReady } from "./lazy-hljs";import { deepLinkPath, UI_BASE } from "./deep-link";import type { ChatSurface, ConvCtx } from "./conv-types";import { errMessage, swallow } from "../../chassis/src/errors";@@ -117,11 +129,50 @@ interface SettledRowKey {approvalDecision: unknown;sendFailure: unknown;forkable: boolean;+ miniappKey: string;tpl: TemplateResult | typeof nothing;}const settledRowCache = new WeakMap<object, SettledRowKey>();const connectedConnectors = new Set<string>();+const miniappPaneByUrl = new Map<string, "play" | "code">();+const miniappSourceByUrl = new Map<string, string>();+const miniappBootByPath = new Map<string, { ok: boolean; error?: string }>();+const miniappBootTimerByPath = new Map<string, number>();const redrawHooks = new Set<() => void>();++function miniappPathOf(src: string): string {+ try {+ return new URL(src, location.origin).pathname;+ } catch {+ return src;+ }+}++function noteMiniappBoot(path: string, boot: { ok: boolean; error?: string }): void {+ if (miniappBootByPath.get(path)?.ok && boot.ok) return;+ miniappBootByPath.set(path, boot);+ const timer = miniappBootTimerByPath.get(path);+ if (timer !== undefined) window.clearTimeout(timer);+ miniappBootTimerByPath.delete(path);+ for (const hook of redrawHooks) hook();+}++window.addEventListener("message", (event) => {+ const data = event.data as { source?: string; path?: string; ok?: boolean; error?: string } | null;+ if (!data || data.source !== "qm-miniapp" || typeof data.path !== "string") return;+ noteMiniappBoot(data.path, { ok: Boolean(data.ok), ...(typeof data.error === "string" && data.error ? { error: data.error } : {}) });+});++function armMiniappBoot(src: string): void {+ const path = miniappPathOf(src);+ if (miniappBootByPath.has(path) || miniappBootTimerByPath.has(path)) return;+ miniappBootTimerByPath.set(+ path,+ window.setTimeout(() => {+ if (!miniappBootByPath.has(path)) noteMiniappBoot(path, { ok: true });+ }, 1500),+ );+}let proactiveOpenerStarted = false;export const sleep = (ms: number): Promise<void> => new Promise((r) => setTimeout(r, ms));@@ -509,8 +560,13 @@ export function createChatSurface(if (chatState.agent) drawActiveChat();}+ function redrawForMiniapp(): void {+ redrawTranscript();+ }+function dispose(): void {redrawHooks.delete(redrawForConnector);+ redrawHooks.delete(redrawForMiniapp);teardownActiveChat();}@@ -1237,6 +1293,13 @@ export function createChatSurface((!work || ((work.status === "complete" || work.status === "failed") && !work.pendingApprovals?.length));if (!cacheable) return chatMessage(message, index, isStreaming);const forkable = Boolean(chatState.threadRef && chatState.sessionId && chatState.agent);+ const miniappKey = miniappsIn(messageText(message))+ .map((app) => {+ const src = miniappFrameSrc(app.url, withBase, currentMiniappTheme());+ const boot = miniappBootByPath.get(miniappPathOf(src));+ return `${app.url}:${miniappPaneByUrl.get(app.url) ?? "play"}:${miniappSourceByUrl.get(app.url) ?? ""}:${boot ? `${boot.ok}:${boot.error ?? ""}` : "pending"}`;+ })+ .join("\n");const hit = settledRowCache.get(message as object);if (hit &&@@ -1249,7 +1312,8 @@ export function createChatSurface(hit.errorMessage === msg.errorMessage &&hit.approvalDecision === msg.approvalDecision &&hit.sendFailure === msg.sendFailure &&- hit.forkable === forkable+ hit.forkable === forkable &&+ hit.miniappKey === miniappKey) {return hit.tpl;}@@ -1265,6 +1329,7 @@ export function createChatSurface(approvalDecision: msg.approvalDecision,sendFailure: msg.sendFailure,forkable,+ miniappKey,tpl,});return tpl;@@ -1457,12 +1522,99 @@ export function createChatSurface(</a>`;}+ function loadMiniappSource(url: string, sourceSrc: string): void {+ if (miniappSourceByUrl.has(url)) return;+ miniappSourceByUrl.set(url, "");+ void fetch(sourceSrc, { cache: "reload" })+ .then(async (r) => {+ miniappSourceByUrl.set(url, r.ok ? await r.text() : "Couldn't load the source.");+ redrawTranscript();+ })+ .catch(() => {+ miniappSourceByUrl.set(url, "Couldn't load the source.");+ redrawTranscript();+ });+ }++ function miniappSourceView(source: string | undefined): TemplateResult {+ if (!source) return html`<pre class="miniapp-source" tabindex="0">Loading source…</pre>`;+ const formatted = formatMiniappHtml(source);+ if (!hljs.getLanguage("html") && !hljs.getLanguage("xml")) {+ void whenHighlightReady().then(() => redrawTranscript());+ }+ return html`<pre class="miniapp-source" tabindex="0">${unsafeHTML(hljs.highlight(formatted, { language: "html" }).value)}</pre>`;+ }++ function miniappCard(app: MiniappEmbed): TemplateResult {+ const src = miniappFrameSrc(app.url, withBase, currentMiniappTheme());+ const sourceSrc = miniappSourceSrc(src);+ const pane = miniappPaneByUrl.get(app.url) ?? "play";+ if (pane === "code") loadMiniappSource(app.url, sourceSrc);+ const source = miniappSourceByUrl.get(app.url);+ const path = miniappPathOf(src);+ if (pane === "play") armMiniappBoot(src);+ const boot = miniappBootByPath.get(path);+ return html`<div class="miniapp-card">+ <header class="miniapp-card-bar">+ <span class="miniapp-card-icon">${icon(Files, 16)}</span>+ <strong class="miniapp-card-title">${app.title}</strong>+ <nav class="miniapp-tabs" aria-label="Playground views">+ <button+ class="miniapp-tab ${pane === "play" ? "on" : ""}"+ type="button"+ aria-pressed=${pane === "play"}+ @click=${() => {+ miniappPaneByUrl.set(app.url, "play");+ redrawTranscript();+ }}+ >+ Play+ </button>+ <button+ class="miniapp-tab ${pane === "code" ? "on" : ""}"+ type="button"+ aria-pressed=${pane === "code"}+ @click=${() => {+ miniappPaneByUrl.set(app.url, "code");+ loadMiniappSource(app.url, sourceSrc);+ redrawTranscript();+ }}+ >+ ${icon(Code2, 13)} Code+ </button>+ </nav>+ <a class="miniapp-card-open" href=${src} target="_blank" rel="noreferrer" title="Open in a new tab"+ >${icon(Maximize2, 14)} Open</a+ >+ </header>+ <div class="miniapp-stage">+ <iframe+ class="miniapp-frame ${pane === "code" ? "is-hidden" : ""}"+ src=${src}+ title=${app.title}+ sandbox="allow-scripts allow-forms allow-pointer-lock allow-modals allow-popups"+ referrerpolicy="no-referrer"+ ></iframe>+ ${+ pane === "play" && !boot+ ? html`<div class="miniapp-boot" role="status">Starting…</div>`+ : pane === "play" && boot && !boot.ok+ ? html`<div class="miniapp-boot err" role="alert">${boot.error || "Playground hit an error."}</div>`+ : nothing+ }+ ${pane === "code" ? miniappSourceView(source) : nothing}+ </div>+ </div>`;+ }+function assistantContent(message: AssistantMessage, isStreaming = false, hasWork = false): TemplateResult[] {const parts: TemplateResult[] = [];for (const chunk of message.content) {if (chunk.type === "text" && chunk.text.trim()) {const links = connectorLinksIn(chunk.text, location.origin);- const body = links.length ? stripConnectorLinks(chunk.text) : chunk.text;+ const apps = miniappsIn(chunk.text);+ let body = stripMiniappDirectives(chunk.text);+ if (links.length) body = stripConnectorLinks(body);if (body.trim())parts.push(html`<div class="streaming-text ${isStreaming ? "live-stream" : ""}">@@ -1470,6 +1622,7 @@ export function createChatSurface(</div>`,);for (const link of links) parts.push(connectorWidget(link));+ if (!isStreaming) for (const app of apps) parts.push(miniappCard(app));}if (chunk.type === "thinking" && chunk.thinking.trim()) {parts.push(@@ -2299,6 +2452,7 @@ export function createChatSurface(}redrawHooks.add(redrawForConnector);+ redrawHooks.add(redrawForMiniapp);return {state: chatState,diff --git a/plugins/web-ui/src/lazy-hljs.ts b/plugins/web-ui/src/lazy-hljs.tsindex 05ff11c67..7621bdff3 100644--- a/plugins/web-ui/src/lazy-hljs.ts+++ b/plugins/web-ui/src/lazy-hljs.ts@@ -8,6 +8,13 @@ type Hljs = {let real: Hljs | null = null;let loading: Promise<void> | null = null;+const readyWaiters: Array<() => void> = [];++export function whenHighlightReady(): Promise<void> {+ if (real) return Promise.resolve();+ ensureLoading();+ return new Promise((resolve) => readyWaiters.push(resolve));+}const LANGS = ["javascript", "typescript", "python", "xml", "css", "json", "bash", "sql", "markdown"] as const;const LANG_ALIASES: Record<string, string> = { html: "xml" };@@ -47,6 +54,8 @@ function ensureLoading(): void {}real = hljs;rerenderMountedBlocks();+ const waiters = readyWaiters.splice(0);+ for (const fn of waiters) fn();}).catch(() => {loading = null;diff --git a/plugins/web-ui/src/miniapp.ts b/plugins/web-ui/src/miniapp.tsnew file mode 100644index 000000000..ac293c093--- /dev/null+++ b/plugins/web-ui/src/miniapp.ts@@ -0,0 +1,114 @@+export interface MiniappEmbed {+ url: string;+ title: string;+}++const MINIAPP_DIRECTIVE = /\[\[miniapp:\s*(\S+?)\s*(?:\|\s*([^\]]*?))?\]\]/gi;+const TRAILING_OPEN = /\[\[miniapp:[\s\S]*$/i;++export function parseMiniappUrl(raw: string): string | null {+ const value = raw.trim().replace(/^<|>$/g, "");+ if (!value) return null;+ if (value.startsWith("/m/")) {+ const parts = value.slice(3).split("/").filter(Boolean);+ if (parts.length === 2 && parts[0] && parts[1]) return `/m/${parts[0]}/${parts[1]}`;+ return null;+ }+ try {+ const u = new URL(value);+ if (u.protocol !== "http:" && u.protocol !== "https:") return null;+ if (u.username || u.password) return null;+ const parts = u.pathname.replace(/\/+$/, "").split("/").filter(Boolean);+ if (parts[0] !== "m" || parts.length !== 3) return null;+ return u.toString();+ } catch {+ return null;+ }+}++export function miniappsIn(text: string): MiniappEmbed[] {+ const out: MiniappEmbed[] = [];+ const seen = new Set<string>();+ for (const m of text.matchAll(MINIAPP_DIRECTIVE)) {+ const url = parseMiniappUrl(m[1] ?? "");+ if (!url || seen.has(url)) continue;+ seen.add(url);+ out.push({ url, title: (m[2] ?? "").trim() || "Playground" });+ }+ return out.slice(0, 5);+}++export function stripMiniappDirectives(text: string): string {+ if (!text) return text ?? "";+ return text+ .replace(MINIAPP_DIRECTIVE, "")+ .replace(TRAILING_OPEN, "")+ .replace(/[ \t]+\n/g, "\n")+ .replace(/\n{3,}/g, "\n\n")+ .trim();+}++export function currentMiniappTheme(): "light" | "dark" {+ if (typeof document === "undefined") return "light";+ return document.documentElement.classList.contains("dark") ? "dark" : "light";+}++export function miniappFrameSrc(url: string, withBase: (path: string) => string, theme?: "light" | "dark"): string {+ let src = url;+ if (url.startsWith("/m/")) src = withBase(url);+ else {+ try {+ const u = new URL(url);+ const parts = u.pathname.replace(/\/+$/, "").split("/").filter(Boolean);+ if (parts[0] === "m" && parts.length === 3) src = withBase(`/${parts.join("/")}`);+ } catch {+ src = url;+ }+ }+ if (!theme) return src;+ return withMiniappParam(src, "theme", theme);+}++export function miniappSourceSrc(frameSrc: string): string {+ return withMiniappParam(frameSrc, "view", "source");+}++const VOID_TAGS = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr"]);++export function formatMiniappHtml(html: string): string {+ const holes: string[] = [];+ const parked = html.replace(/<(script|style)\b[\s\S]*?<\/\1>/gi, (block) => {+ holes.push(block);+ return `\0${holes.length - 1}\0`;+ });+ const lines = parked+ .replace(/\0(\d+)\0/g, "\n\0$1\0\n")+ .replace(/></g, ">\n<")+ .split("\n")+ .map((line) => line.trim())+ .filter(Boolean);+ let depth = 0;+ return lines+ .map((line) => {+ const close = /^<\/([a-zA-Z][\w:-]*)/.exec(line);+ const open = /^<([a-zA-Z][\w:-]*)\b[^>]*>/.exec(line);+ if (close) depth = Math.max(0, depth - 1);+ const pad = " ".repeat(depth);+ const name = open?.[1]?.toLowerCase() ?? "";+ const self = /\/\s*>$/.test(line) || VOID_TAGS.has(name);+ const paired = Boolean(open && new RegExp(`</${open[1]}\\s*>$`, "i").test(line));+ if (open && !close && !self && !paired && !line.startsWith("<!")) depth++;+ return pad + line.replace(/\0(\d+)\0/g, (_, i) => holes[Number(i)] ?? "");+ })+ .join("\n");+}++function withMiniappParam(src: string, key: string, value: string): string {+ if (/^https?:/i.test(src)) {+ const u = new URL(src);+ u.searchParams.set(key, value);+ return u.toString();+ }+ const sep = src.includes("?") ? "&" : "?";+ return `${src}${sep}${key}=${value}`;+}diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.cssindex 08e458f58..ba046cf53 100644--- a/plugins/web-ui/src/shell.css+++ b/plugins/web-ui/src/shell.css@@ -3260,6 +3260,188 @@ a.chat-row-open {margin-left: auto;color: var(--muted-foreground);}+.miniapp-card {+ display: flex;+ flex-direction: column;+ min-width: 0;+ max-width: 100%;+ height: min(62dvh, 560px);+ margin: 10px 0 12px;+ border: 1px solid color-mix(in srgb, var(--brand-accent) 22%, var(--border));+ border-radius: var(--radius-lg);+ overflow: hidden;+ background: var(--background);+ color: var(--foreground);+ box-shadow: 0 1px 2px color-mix(in srgb, var(--foreground) 6%, transparent);+}+.miniapp-card-bar {+ display: flex;+ align-items: center;+ gap: 8px;+ flex: 0 0 auto;+ min-height: 40px;+ padding: 0 12px;+ border-bottom: 1px solid var(--border);+ background: color-mix(in srgb, var(--secondary) 70%, var(--background));+}+.miniapp-card-icon {+ display: inline-flex;+ color: var(--muted-foreground);+}+.miniapp-card-title {+ flex: 1;+ min-width: 0;+ font-size: 13px;+ font-weight: 600;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+.miniapp-tabs {+ display: flex;+ align-items: center;+ gap: 2px;+ padding: 2px;+ border-radius: 8px;+ background: var(--secondary);+}+.miniapp-tab {+ appearance: none;+ display: inline-flex;+ align-items: center;+ gap: 4px;+ margin: 0;+ padding: 4px 10px;+ border: 0;+ border-radius: 6px;+ background: transparent;+ color: var(--muted-foreground);+ font: inherit;+ font-size: 12px;+ font-weight: 600;+ line-height: 1;+ cursor: pointer;+ transition:+ background 160ms ease,+ color 160ms ease,+ box-shadow 160ms ease;+}+.miniapp-tab.on {+ background: var(--background);+ color: var(--foreground);+ box-shadow: 0 1px 2px color-mix(in srgb, var(--foreground) 10%, transparent);+}+.miniapp-tab:hover:not(.on) {+ color: var(--foreground);+}+.miniapp-card-open {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ color: var(--muted-foreground);+ font-size: 12px;+ font-weight: 500;+ text-decoration: none;+}+.miniapp-card-open:hover {+ color: var(--foreground);+}+.miniapp-stage {+ position: relative;+ flex: 1 1 auto;+ min-height: 0;+ overflow: hidden;+ background: var(--background);+}+.miniapp-boot {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ padding: 16px;+ background: var(--background);+ color: var(--muted-foreground);+ font-size: 13px;+ text-align: center;+ pointer-events: none;+}+.miniapp-boot.err {+ color: var(--foreground);+ pointer-events: auto;+}+.miniapp-frame {+ position: absolute;+ inset: 0;+ display: block;+ width: 100%;+ height: 100%;+ border: 0;+ overflow: hidden;+ background: var(--background);+ color-scheme: inherit;+ transition: opacity 180ms ease;+}+.miniapp-frame.is-hidden {+ opacity: 0;+ pointer-events: none;+}+.miniapp-source {+ position: absolute;+ inset: 0;+ margin: 0;+ padding: 14px 16px;+ overflow: auto;+ background: color-mix(in srgb, var(--secondary) 82%, var(--background));+ color: var(--foreground);+ font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;+ font-size: 12px;+ line-height: 1.55;+ white-space: pre;+ tab-size: 2;+ animation: miniapp-source-in 200ms ease;+}+.miniapp-source .hljs-tag,+.miniapp-source .hljs-name,+.miniapp-source .hljs-keyword {+ color: var(--brand-accent);+}+.miniapp-source .hljs-attr {+ color: color-mix(in srgb, var(--foreground) 70%, var(--brand-accent));+}+.miniapp-source .hljs-string {+ color: color-mix(in srgb, #0f766e 75%, var(--foreground));+}+.miniapp-source .hljs-number {+ color: color-mix(in srgb, #c2410c 80%, var(--foreground));+}+.miniapp-source .hljs-comment {+ color: var(--muted-foreground);+}+@keyframes miniapp-source-in {+ from {+ opacity: 0;+ transform: translateY(6px);+ }+ to {+ opacity: 1;+ transform: none;+ }+}+@media (prefers-reduced-motion: reduce) {+ .miniapp-tab,+ .miniapp-frame {+ transition: none;+ }+ .miniapp-source {+ animation: none;+ }+}+@media (max-width: 640px) {+ .miniapp-card {+ height: min(56dvh, 480px);+ }+}.connector-desc {margin: 2px 0 0;font-size: 13px;diff --git a/plugins/web-ui/test/miniapp-proxy.test.ts b/plugins/web-ui/test/miniapp-proxy.test.tsnew file mode 100644index 000000000..eb0f7132c--- /dev/null+++ b/plugins/web-ui/test/miniapp-proxy.test.ts@@ -0,0 +1,46 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import { createServer, type IncomingMessage } from "node:http";+import type { AddressInfo } from "node:net";++const core = createServer((req: IncomingMessage, res) => {+ if ((req.url ?? "").startsWith("/m/")) {+ res.writeHead(200, {+ "content-type": "text/html; charset=utf-8",+ "content-security-policy":+ "sandbox allow-scripts allow-forms allow-pointer-lock allow-modals allow-popups; default-src 'none'; connect-src 'none'",+ });+ return void res.end(`<canvas data-url="${req.url ?? ""}"></canvas><script>void 0</script>`);+ }+ res.writeHead(404, { "content-type": "application/json" });+ res.end(JSON.stringify({ error: "not_found" }));+});+await new Promise<void>((r) => core.listen(0, r));+const coreUrl = `http://localhost:${(core.address() as AddressInfo).port}`;++process.env.CORE_API_URL = coreUrl;+process.env.CORE_SIGNING_SECRET = "miniapp-proxy-test-secret";+process.env.WEB_UI_PRINCIPALS = "alice";++const { handler } = await import("../server/index.ts");+const surface = createServer((req, res) => void handler(req, res));+await new Promise<void>((r) => surface.listen(0, r));+const base = `http://localhost:${(surface.address() as AddressInfo).port}`;++test.after(() => {+ surface.close();+ core.close();+});++test("miniapp HTML is public, sandboxed, and iframeable", async () => {+ const r = await fetch(`${base}/m/aa/bb`);+ assert.equal(r.status, 200);+ assert.match(await r.text(), /<canvas/);+ const csp = r.headers.get("content-security-policy") ?? "";+ assert.match(csp, /^sandbox\b/);+ assert.ok(!/allow-same-origin/.test(csp));+ assert.equal(r.headers.get("x-frame-options"), null);+ assert.equal(r.headers.get("x-content-type-options"), "nosniff");+ const themed = await fetch(`${base}/m/aa/bb?theme=light`);+ assert.match(await themed.text(), /theme=light/);+});diff --git a/plugins/web-ui/test/miniapp.test.ts b/plugins/web-ui/test/miniapp.test.tsnew file mode 100644index 000000000..eebfcb86d--- /dev/null+++ b/plugins/web-ui/test/miniapp.test.ts@@ -0,0 +1,50 @@+import assert from "node:assert/strict";+import { test } from "node:test";+import {+ miniappsIn,+ miniappFrameSrc,+ miniappSourceSrc,+ formatMiniappHtml,+ parseMiniappUrl,+ stripMiniappDirectives,+} from "../src/miniapp.ts";++test("miniappsIn pulls title and url and stripMiniappDirectives removes the marker", () => {+ const text = "Here you go\n[[miniapp: https://qm.test/m/abc/def | Slope]]";+ const apps = miniappsIn(text);+ assert.equal(apps.length, 1);+ assert.equal(apps[0]!.title, "Slope");+ assert.equal(apps[0]!.url, "https://qm.test/m/abc/def");+ assert.equal(stripMiniappDirectives(text), "Here you go");+ assert.equal(+ stripMiniappDirectives("[[miniapp: sandbox:/mnt/user-data/outputs/x.html | Blocks]]"),+ "",+ );+});++test("parseMiniappUrl rejects non-miniapp urls", () => {+ assert.equal(parseMiniappUrl("javascript:alert(1)"), null);+ assert.equal(parseMiniappUrl("https://evil.test/hack"), null);+ assert.equal(parseMiniappUrl("/m/aa/bb"), "/m/aa/bb");+});++test("miniappFrameSrc rewrites playground urls onto the ui origin", () => {+ const withBase = (p: string) => `/ui${p}`;+ assert.equal(miniappFrameSrc("/m/aa/bb", withBase), "/ui/m/aa/bb");+ assert.equal(miniappFrameSrc("https://qm.test/m/aa/bb", withBase), "/ui/m/aa/bb");+ assert.equal(miniappFrameSrc("/m/aa/bb", withBase, "light"), "/ui/m/aa/bb?theme=light");+ assert.equal(miniappSourceSrc("/ui/m/aa/bb?theme=light"), "/ui/m/aa/bb?theme=light&view=source");+});++test("formatMiniappHtml indents tags and keeps script blocks intact", () => {+ const formatted = formatMiniappHtml(+ "<!doctype html><html><head><style>body{margin:0}</style></head><body><h2>Hi</h2><canvas id=c></canvas><script>void 0</script></body></html>",+ );+ assert.match(formatted, /<html>\n/);+ assert.match(formatted, /^\s*<head>/m);+ assert.match(formatted, /<style>body\{margin:0\}<\/style>/);+ assert.match(formatted, /^\s*<body>/m);+ assert.match(formatted, /<h2>Hi<\/h2>/);+ assert.match(formatted, /<script>void 0<\/script>/);+ assert.match(formatted, /\n<\/html>$/);+});diff --git a/scripts/dev/supervisor/specs.ts b/scripts/dev/supervisor/specs.tsindex 33c0b364c..d7c78ec4a 100644--- a/scripts/dev/supervisor/specs.ts+++ b/scripts/dev/supervisor/specs.ts@@ -36,7 +36,7 @@ export function buildChildSpecs(i: SpecInputs): ChildSpec[] {PORT: String(i.ports.core),...(i.databaseUrl ? { DATABASE_URL: i.databaseUrl } : {}),...(i.adminGrantsSeed ? { ADMIN_GRANTS: i.adminGrantsSeed } : {}),- PUBLIC_WEB_URL: `http://localhost:${i.ports.portal}`,+ PUBLIC_WEB_URL: i.baseEnv.PUBLIC_WEB_URL || `http://localhost:${i.ports.portal}`,...(i.slack? {SLACK_BOT_TOKEN: i.slack.botToken,diff --git a/skills-seed/miniapp/SKILL.md b/skills-seed/miniapp/SKILL.mdnew file mode 100644index 000000000..321761204--- /dev/null+++ b/skills-seed/miniapp/SKILL.md@@ -0,0 +1,44 @@+---+name: miniapp+description: Build a tiny interactive HTML playground only when they asked to see, play with, or step a mechanism. Not for ordinary Q&A, facts, writing, or long explanations.+---++# Miniapp++Use the `miniapp` tool only when both are true: they asked to see, play with, step, or drag the idea — and a short paragraph cannot carry it. A derivative as Minecraft blocks, a sorting algorithm they can step, a compound-interest slider. Do not build a playground just because the topic could be visualized. "Explain how LLMs work" is prose. "Let me drag the number of rectangles" is a miniapp.++A miniapp is one self-contained HTML page. It is not `publish`: no server, no `PORT`, no durable process. `publish` is for long-lived internal apps.++## Build++Write the page first (`write`, or pass `html` directly). Then:++```+miniapp({ title: "Slope as mining speed", html: "<!doctype html>…" })+```++or `file: "work/playground.html"` instead of `html`.++The tool parses every inline script and checks the page has something to show before it stores. If it fails, fix the HTML and call `miniapp` again — do not put a broken directive in the reply. Never invent a path, a `sandbox:` URL, or a filename — only the url the tool returned. The host knows the first paint happened; do not wait for the page to "stabilize."++```+[[miniapp: <url> | <title>]]+```++Do not paste the raw HTML into the chat.++## Constraints++- One HTML document. Inline CSS and JS. No `fetch`, no CDNs, no remote fonts/images — the playground is sandboxed with no network.+- Keep it under ~500KB.+- Fill the host frame. `html,body` are 100% height with `overflow: hidden`. One concise screen — no `overflow: auto`, no `overflow: scroll`, no page or inner scroll. Put the live bit (`canvas`, svg, stage) in a flex child that grows.+- Label the moving number. Accent is the value they control; muted is everything else. Animate the change with `requestAnimationFrame` (lerp, step) — no page scroll, no decorative loaders.+- Match the chat, not a separate dark app. Use only these tokens — never hardcode a palette: `var(--background)`, `var(--foreground)`, `var(--border)`, `var(--secondary)`, `var(--muted-foreground)`, `var(--brand-accent)`. The host injects light or dark to match the person.+- It must work on a phone as well as a desktop.++## When not to++- They asked a question a paragraph answers — facts, definitions, how-tos, advice, summaries.+- Writing, ops, code edits, lookup, calendar, mail, memory, or "are you there."+- They asked for a durable internal app, dashboard, or anything that must keep running — that is `publish`.+- Anything that needs their logged-in session on another site — that is `browse`.diff --git a/src/api/deps.ts b/src/api/deps.tsindex 7e0b60d0c..b1ff2c9d5 100644--- a/src/api/deps.ts+++ b/src/api/deps.ts@@ -52,6 +52,7 @@ import type { UiStateStore } from "../surfaces/ui-state.ts";import type { RateLimiter } from "../ratelimit/rate-limiter.ts";import type { AdvisoryLock } from "../persistence/advisory-lock.ts";import type { SlackInstallationStore, SlackSocketAppIdReader } from "../surfaces/slack-installation.ts";+import type { MiniappStore } from "../miniapps/miniapp.ts";export interface ServerDeps {production?: boolean;@@ -137,4 +138,5 @@ export interface ServerDeps {secretDrops?: SecretDropStore;fireDropResolution?: (drop: DropResolution) => Promise<unknown>;blobTransfer?: BlobTransferStore;+ miniapps?: MiniappStore;}diff --git a/src/api/routes/index.ts b/src/api/routes/index.tsindex c6b54f744..e35a8f2d5 100644--- a/src/api/routes/index.ts+++ b/src/api/routes/index.ts@@ -25,6 +25,7 @@ import { contextPolicyRoutes } from "./context-policy.ts";import { deploymentLayerRoutes } from "./deployment-layer.ts";import { egressAuditRoutes } from "./egress-audit.ts";import { authBrokerRoutes } from "./auth-broker.ts";+import { miniappRawRoutes } from "./miniapps.ts";export const rawRoutes: ReadonlyArray<Route<BaseCtx>> = [{ method: "GET", path: "/healthz", auth: "public", handle: ({ res }) => sendJson(res, 200, { ok: true }) },@@ -39,6 +40,7 @@ export const rawRoutes: ReadonlyArray<Route<BaseCtx>> = [...blobRoutes,...sessionStateRawRoutes,...webhookRawRoutes,+ ...miniappRawRoutes,];export const apiRoutes: ReadonlyArray<Route<ApiCtx>> = [diff --git a/src/api/routes/miniapps.ts b/src/api/routes/miniapps.tsnew file mode 100644index 000000000..f9be4e313--- /dev/null+++ b/src/api/routes/miniapps.ts@@ -0,0 +1,51 @@+import type { BaseCtx, Route } from "./route.ts";+import {+ MINIAPP_CSP,+ openMiniapp,+ parseMiniappTheme,+ parseMiniappView,+ skinMiniappHtml,+} from "../../miniapps/miniapp.ts";++const NOT_FOUND = `<!doctype html><meta charset="utf-8"><title>Not found</title><body style="font-family:system-ui;margin:4rem auto;max-width:32rem;padding:0 1rem"><h1>Playground not found</h1><p>This miniapp is gone or the link is wrong.</p></body>`;++async function serveMiniapp(ctx: BaseCtx): Promise<void> {+ const { res, deps, params } = ctx;+ if (!deps.miniapps) {+ res.writeHead(404, { "content-type": "text/html; charset=utf-8" });+ res.end(NOT_FOUND);+ return;+ }+ const rec = await openMiniapp(deps.miniapps, params.id ?? "", params.key ?? "");+ if (!rec) {+ res.writeHead(404, { "content-type": "text/html; charset=utf-8" });+ res.end(NOT_FOUND);+ return;+ }+ const theme = parseMiniappTheme(ctx.url.searchParams.get("theme"));+ if (parseMiniappView(ctx.url.searchParams.get("view"))) {+ res.writeHead(200, {+ "content-type": "text/plain; charset=utf-8",+ "content-length": String(Buffer.byteLength(rec.html, "utf8")),+ "x-content-type-options": "nosniff",+ "referrer-policy": "no-referrer",+ "cache-control": "private, no-cache",+ });+ res.end(rec.html);+ return;+ }+ const body = skinMiniappHtml(rec.html, theme);+ res.writeHead(200, {+ "content-type": "text/html; charset=utf-8",+ "content-length": String(Buffer.byteLength(body, "utf8")),+ "content-security-policy": MINIAPP_CSP,+ "x-content-type-options": "nosniff",+ "referrer-policy": "no-referrer",+ "cache-control": "private, no-cache",+ });+ res.end(body);+}++export const miniappRawRoutes: ReadonlyArray<Route<BaseCtx>> = [+ { method: "GET", path: "/m/:id/:key", auth: "public", handle: serveMiniapp },+];diff --git a/src/core/orchestrator.ts b/src/core/orchestrator.tsindex b19b393fa..6deea7e0c 100644--- a/src/core/orchestrator.ts+++ b/src/core/orchestrator.ts@@ -1849,6 +1849,7 @@ export function createOrchestrator(deps: OrchestratorDeps): Orchestrator {deploy: deps.deploy,acl: deps.acl,files: deps.files,+ miniapps: deps.miniapps,auditLog: deps.auditLog,createdBy: actor.id,...(() => {diff --git a/src/core/orchestrator/types.ts b/src/core/orchestrator/types.tsindex a68404b8a..e94b000d6 100644--- a/src/core/orchestrator/types.ts+++ b/src/core/orchestrator/types.ts@@ -56,6 +56,7 @@ import type { OAuthClientResolver } from "../../connectors/oauth.ts";import type { SkillBundleStore } from "../../skills/skill-bundle-store.ts";import type { BrokeredLayerTool, DeploymentLayerRuntime } from "../../deployment/load-layer.ts";import type { FileArtifactStore } from "../../files/file-artifact-store.ts";+import type { MiniappStore } from "../../miniapps/miniapp.ts";import type { DeployService } from "../../deploy/deploy-service.ts";import type { AclStore } from "../../acl/acl-store.ts";import type { ChannelPolicyStore } from "../../surface-cache/channel-policy-store.ts";@@ -121,6 +122,7 @@ export interface OrchestratorDeps {capabilitySecret?: string;apiBaseUrl?: string;publicWebUrl?: string;+ miniapps?: MiniappStore;/** The public base for an inbound webhook URL (PUBLIC_WEB_URL ?? api url) — what the webhook* tool hands the user to point the sender at; matches the HTTP webhook route's base exactly. */webhookPublicUrl?: string;diff --git a/src/harness/pi-tools.ts b/src/harness/pi-tools.tsindex 08bf6a583..cd992a25e 100644--- a/src/harness/pi-tools.ts+++ b/src/harness/pi-tools.ts@@ -3,6 +3,7 @@ import { Type } from "typebox";import { CONFIG_DEFAULTS, type Config } from "../config.ts";import type { CronFireLogEntry, EntryType, ScopeId } from "../types.ts";import type { ToolContext, PublishInput, PublishAudienceDescriptor, ShareDirective } from "../tools/primitives.ts";+import type { MiniappInput } from "../miniapps/miniapp.ts";import type { GapWork } from "../sessions/session-store.ts";import { NeedsApproval, CommandDenied } from "../tools/primitives.ts";import { classifyScopeLabel } from "../classify/scope-classifier.ts";@@ -89,6 +90,10 @@ function isPolicyNotice(summary: Record<string, unknown>): boolean {return summary.blocked !== undefined || summary.denied !== undefined;}+function isFirstPartyToolResult(summary: Record<string, unknown>): boolean {+ return summary.tool === "miniapp" || summary.tool === "publish";+}+const MAX_TOOL_RESULT_CHARS = 100_000;const TRUNCATED_TAIL_CHARS = 10_000;@@ -379,6 +384,7 @@ export function createPiTools(ref: ToolContextRef, opts?: PiToolsOptions): ToolDlet persistedSummary = summary;const screenExempt =isPolicyNotice(summary) ||+ isFirstPartyToolResult(summary) ||(summary.action === "post" &&summary.ok === true &&result === "[sent]" &&@@ -941,6 +947,43 @@ export function createPiTools(ref: ToolContextRef, opts?: PiToolsOptions): ToolD},});+ const miniapp = defineTool({+ name: "miniapp",+ label: "miniapp",+ description:+ "Create an interactive playground only when they asked to see, play with, or step a mechanism — " ++ "not for ordinary Q&A or a long explanation. Self-contained HTML " ++ "mini-app (a simulation, a visual explainer, a tiny game). Inline CSS/JS, " ++ "no network, no server. Fill the host frame — one screen, no overflow, no scroll. Use var(--background) var(--foreground) var(--border) " ++ "var(--secondary) var(--muted-foreground) var(--brand-accent) — never a hardcoded dark palette. " ++ "Scripts are parsed before store — a broken script is rejected, not sent. " ++ "Returns a url; include the EXACT `[[miniapp: <url> | <title>]]` directive the tool returned — never " ++ "invent a file path or sandbox: URL. Use `publish` instead for a long-lived internal app that needs a process and PORT.",+ parameters: Type.Object({+ title: Type.String({ description: "Short name shown on the playground card." }),+ html: Type.Optional(+ Type.String({ description: "Self-contained HTML document or fragment (inline CSS/JS, no network)." }),+ ),+ file: Type.Optional(Type.String({ description: "Workspace path of an HTML file to use instead of `html`." })),+ }),+ async execute(callId, params) {+ const tc = ref.current;+ if (!tc) return text("[error] no active tool context");+ await recordCall(callId, { tool: "miniapp", title: params.title, ...(params.file ? { file: params.file } : {}) });+ try {+ const r = await tc.miniapp(params as MiniappInput);+ return recordResult(+ callId,+ { tool: "miniapp", id: r.id, title: r.title, url: r.url },+ text(`Miniapp "${r.title}" → ${r.url}\nInclude this in your reply so it renders: ${r.directive}`),+ );+ } catch (e) {+ const msg = errMessage(e);+ return recordResult(callId, { tool: "miniapp", error: msg }, text(`[miniapp failed] ${msg}`), true);+ }+ },+ });+const memory = defineTool({name: "memory",label: "memory",@@ -2968,6 +3011,7 @@ export function createPiTools(ref: ToolContextRef, opts?: PiToolsOptions): ToolDread,write,publish,+ miniapp,memory,history,background,diff --git a/src/miniapps/miniapp.ts b/src/miniapps/miniapp.tsnew file mode 100644index 000000000..176a3219f--- /dev/null+++ b/src/miniapps/miniapp.ts@@ -0,0 +1,192 @@+import { randomBytes } from "node:crypto";+import type { ScopeId } from "../types.ts";+import type { DurableMap } from "../persistence/durable-map.ts";+import { constantTimeEqual } from "../util/crypto.ts";+import { errMessage } from "../util/errors.ts";++function escapeHtml(s: string): string {+ return s.replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]!);+}++export const MAX_MINIAPP_HTML_BYTES = 512_000;+export const MINIAPP_TITLE_MAX = 80;+export const MINIAPP_CSP =+ "sandbox allow-scripts allow-forms allow-pointer-lock allow-modals allow-popups; default-src 'none'; script-src 'unsafe-inline' 'unsafe-eval' blob:; style-src 'unsafe-inline'; img-src data: blob:; media-src data: blob:; font-src data:; connect-src 'none'; worker-src blob:; frame-ancestors *";++export type MiniappTheme = "light" | "dark";++const LIGHT = {+ background: "#ffffff",+ foreground: "#0a0a0a",+ border: "#e5e5e5",+ secondary: "#f5f5f5",+ muted: "#737373",+ accent: "#4f46e5",+};+const DARK = {+ background: "#0a0a0a",+ foreground: "#fafafa",+ border: "#2a2a2a",+ secondary: "#171717",+ muted: "#a3a3a3",+ accent: "#818cf8",+};++function tokenBlock(t: typeof LIGHT): string {+ return `--background:${t.background};--foreground:${t.foreground};--border:${t.border};--secondary:${t.secondary};--muted-foreground:${t.muted};--brand-accent:${t.accent}`;+}++const SKIN_RULES =+ "html,body{margin:0!important;width:100%!important;height:100%!important;max-height:100%!important;overflow:hidden!important;background:var(--background)!important;color:var(--foreground)!important;font-family:ui-sans-serif,system-ui,-apple-system,'Segoe UI',Roboto,Helvetica,Arial,sans-serif!important;font-size:13px;line-height:1.35}" ++ "body{display:flex!important;flex-direction:column!important;box-sizing:border-box!important;padding:12px!important;gap:8px!important}" ++ "h1,h2,h3,p{margin:0}h1,h2,h3{font-size:15px;font-weight:600}" ++ "p,label,small{color:var(--muted-foreground)}" ++ "div,section,main,article,aside{overflow:hidden!important;max-width:100%;box-sizing:border-box}" ++ "canvas,svg{display:block;width:100%!important;flex:1 1 auto!important;min-height:0!important;max-height:none!important;background:var(--secondary)!important;border:1px solid var(--border);border-radius:12px}" ++ "select,input,button,textarea{background:var(--secondary);color:var(--foreground);border:1px solid var(--border);border-radius:8px;font:inherit;padding:5px 8px}" ++ "input[type=range]{appearance:none;height:4px;padding:0;background:var(--border);border:0;border-radius:99px;accent-color:var(--brand-accent);width:100%}" ++ "input[type=range]::-webkit-slider-thumb{appearance:none;width:16px;height:16px;border-radius:50%;background:var(--brand-accent);border:2px solid var(--background);box-shadow:0 1px 2px color-mix(in srgb,var(--foreground) 20%,transparent)}" ++ "input[type=range]::-moz-range-thumb{width:16px;height:16px;border-radius:50%;background:var(--brand-accent);border:2px solid var(--background)}" ++ "*{scrollbar-width:none}" ++ "*::-webkit-scrollbar{width:0;height:0;display:none}";++const PROBE =+ `<script id="qm-miniapp-probe">(function(){var err=null;function fail(e){if(!err)err=(e&&e.message)||String(e);tell(false)}function tell(ok){try{parent.postMessage({source:"qm-miniapp",ok:ok,path:location.pathname,error:err||undefined},"*")}catch(x){}document.documentElement.setAttribute("data-qm-miniapp",ok?"ok":"err")}addEventListener("error",function(e){fail(e.error||e.message)},true);addEventListener("unhandledrejection",function(e){fail(e.reason)});function paint(){if(err)return;tell(true)}function afterPaint(){requestAnimationFrame(function(){requestAnimationFrame(paint)})}if(document.readyState==="complete")afterPaint();else addEventListener("load",afterPaint)})();</script>`;++export function parseMiniappTheme(raw: string | null | undefined): MiniappTheme | undefined {+ return raw === "dark" || raw === "light" ? raw : undefined;+}++export function parseMiniappView(raw: string | null | undefined): "source" | undefined {+ return raw === "source" ? "source" : undefined;+}++export function skinMiniappHtml(html: string, theme?: MiniappTheme): string {+ const root = theme+ ? `:root{color-scheme:${theme};${tokenBlock(theme === "dark" ? DARK : LIGHT)}}`+ : `:root{color-scheme:light;${tokenBlock(LIGHT)}}@media (prefers-color-scheme:dark){:root{color-scheme:dark;${tokenBlock(DARK)}}}`;+ const tag = `<style id="qm-miniapp-skin">${root}${SKIN_RULES}</style>`;+ const stripped = html+ .replace(/<style id="qm-miniapp-skin">[\s\S]*?<\/style>/, "")+ .replace(/<script id="qm-miniapp-probe">[\s\S]*?<\/script>/, "");+ const withSkin = /<head[^>]*>/i.test(stripped) ? stripped.replace(/<head[^>]*>/i, (m) => `${m}${tag}`) : `${tag}${stripped}`;+ if (/<\/body>/i.test(withSkin)) return withSkin.replace(/<\/body>/i, `${PROBE}</body>`);+ return `${withSkin}${PROBE}`;+}++export function assertMiniappOk(html: string): void {+ const body = html.match(/<body\b[^>]*>([\s\S]*)<\/body>/i)?.[1] ?? html;+ const visible = body+ .replace(/<script\b[\s\S]*?<\/script>/gi, "")+ .replace(/<style\b[\s\S]*?<\/style>/gi, "")+ .replace(/<[^>]+>/g, " ")+ .replace(/\s+/g, " ")+ .trim();+ const hasStage = /<(canvas|svg|input|button|select)\b/i.test(body);+ if (!visible && !hasStage) throw new Error("miniapp has nothing to show — add a canvas, a control, or some text");+ if (/\bfetch\s*\(|XMLHttpRequest|navigator\.sendBeacon/i.test(html)) {+ throw new Error("miniapp cannot use the network — inline everything");+ }+ for (const m of html.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)) {+ const attrs = m[1] ?? "";+ if (/\bsrc\s*=/i.test(attrs)) throw new Error("miniapp scripts must be inline — no src=");+ if (/\btype\s*=\s*["']module["']/i.test(attrs)) throw new Error("miniapp cannot use type=module");+ const code = (m[2] ?? "").trim();+ if (!code) continue;+ try {+ new Function(code);+ } catch (e) {+ throw new Error(`miniapp script does not parse: ${errMessage(e)}`);+ }+ }+}++export interface MiniappRecord {+ id: string;+ key: string;+ title: string;+ html: string;+ ownerScopeId: ScopeId;+ createdBy: string;+ createdAt: number;+}++export interface MiniappInput {+ title: string;+ html?: string;+ file?: string;+}++export interface MiniappResult {+ id: string;+ title: string;+ url: string;+ directive: string;+}++export type MiniappStore = DurableMap<MiniappRecord>;++export function clipMiniappTitle(raw: string): string {+ const title = raw.replace(/\s+/g, " ").trim();+ if (!title) return "Playground";+ return title.length > MINIAPP_TITLE_MAX ? `${title.slice(0, MINIAPP_TITLE_MAX - 1)}…` : title;+}++export function documentHtml(title: string, html: string): string {+ const trimmed = html.trim();+ if (/^<!doctype html|<html[\s>]/i.test(trimmed)) return trimmed;+ return `<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escapeHtml(title)}</title></head><body>${trimmed}</body></html>`;+}++export function miniappPath(rec: Pick<MiniappRecord, "id" | "key">): string {+ return `/m/${rec.id}/${rec.key}`;+}++export function miniappUrl(base: string | undefined, rec: Pick<MiniappRecord, "id" | "key">): string {+ const path = miniappPath(rec);+ const root = base?.replace(/\/$/, "");+ return root ? `${root}${path}` : path;+}++export function miniappDirective(url: string, title: string): string {+ return `[[miniapp: ${url} | ${title}]]`;+}++export async function putMiniapp(+ store: MiniappStore,+ input: {+ title: string;+ html: string;+ ownerScopeId: ScopeId;+ createdBy: string;+ publicBase?: string;+ now?: number;+ },+): Promise<MiniappResult> {+ const title = clipMiniappTitle(input.title);+ const html = documentHtml(title, input.html);+ assertMiniappOk(html);+ const bytes = Buffer.byteLength(html, "utf8");+ if (bytes > MAX_MINIAPP_HTML_BYTES) {+ throw new Error(`miniapp HTML is ${bytes} bytes; keep it under ${MAX_MINIAPP_HTML_BYTES}`);+ }+ const rec: MiniappRecord = {+ id: randomBytes(12).toString("hex"),+ key: randomBytes(18).toString("base64url"),+ title,+ html,+ ownerScopeId: input.ownerScopeId,+ createdBy: input.createdBy,+ createdAt: input.now ?? Date.now(),+ };+ await store.put(rec.id, rec);+ const url = miniappUrl(input.publicBase, rec);+ return { id: rec.id, title, url, directive: miniappDirective(url, title) };+}++export async function openMiniapp(store: MiniappStore, id: string, key: string): Promise<MiniappRecord | null> {+ if (!id || !key) return null;+ const rec = await store.get(id);+ if (!rec || !constantTimeEqual(rec.key, key)) return null;+ return rec;+}diff --git a/src/slack/lib.ts b/src/slack/lib.tsindex 528082ce5..76d7958d2 100644--- a/src/slack/lib.ts+++ b/src/slack/lib.ts@@ -80,6 +80,13 @@ export {extractAgentRequests,stripAgentRequestDirectives,} from "./agent-requests.ts";+export {+ extractMiniapps,+ miniappActionBlocks,+ parseMiniappUrl,+ stripMiniappDirectives,+ type MiniappEmbed,+} from "./miniapps.ts";export {encodeTs,decodeTs,diff --git a/src/slack/messaging.ts b/src/slack/messaging.tsindex 3e7321b7f..975eb8ce4 100644--- a/src/slack/messaging.ts+++ b/src/slack/messaging.ts@@ -8,9 +8,12 @@ import {applyReactions,botIdentityArgs,extractAgentRequests,+ extractMiniapps,extractReactions,stripAgentRequestDirectives,+ stripMiniappDirectives,stripReactionDirectives,+ type MiniappEmbed,} from "./lib.ts";export type SlackConversationKind = "dm" | "channel" | "group";@@ -56,13 +59,16 @@ export function cleanAgentReplyForSlack(text: string): {text: string;reactions: ReactionDirective[];agentRequests: AgentRequestDirective[];+ miniapps: MiniappEmbed[];} {const extractedReactions = extractReactions(text);const extractedRequests = extractAgentRequests(extractedReactions.text);+ const extractedMiniapps = extractMiniapps(extractedRequests.text);return {- text: extractedRequests.text,+ text: extractedMiniapps.text,reactions: extractedReactions.reactions,agentRequests: extractedRequests.requests,+ miniapps: extractedMiniapps.miniapps,};}@@ -71,7 +77,7 @@ export function slackSurfaceInstructions(kind: SlackConversationKind): string {}export function stripSlackDirectives(text: string): string {- return stripAgentRequestDirectives(stripReactionDirectives(text));+ return stripMiniappDirectives(stripAgentRequestDirectives(stripReactionDirectives(text)));}export async function applyAndLogReactions(diff --git a/src/slack/miniapps.ts b/src/slack/miniapps.tsnew file mode 100644index 000000000..8cb8ca355--- /dev/null+++ b/src/slack/miniapps.ts@@ -0,0 +1,73 @@+import { extractDirectives } from "./directives.ts";+import { clip } from "./util.ts";++export interface MiniappEmbed {+ url: string;+ title: string;+}++const MINIAPP_DIRECTIVE = /\[\[miniapp:\s*(\S+?)\s*(?:\|\s*([^\]]*?))?\]\]/gi;+const TRAILING_OPEN_MINIAPP_DIRECTIVE = /\[\[miniapp:[\s\S]*$/i;+const BUTTON_TEXT_MAX = 75;+const MAX_MINIAPPS = 5;++export function parseMiniappUrl(raw: string): string | null {+ const value = raw.trim().replace(/^<|>$/g, "");+ if (!value) return null;+ if (value.startsWith("/m/")) {+ const parts = value.slice(3).split("/").filter(Boolean);+ if (parts.length === 2 && parts[0] && parts[1]) return `/m/${parts[0]}/${parts[1]}`;+ return null;+ }+ try {+ const u = new URL(value);+ if (u.protocol !== "http:" && u.protocol !== "https:") return null;+ if (u.username || u.password) return null;+ const parts = u.pathname.replace(/\/+$/, "").split("/").filter(Boolean);+ if (parts[0] !== "m" || parts.length !== 3) return null;+ return u.toString();+ } catch {+ return null;+ }+}++export function extractMiniapps(reply: string): { text: string; miniapps: MiniappEmbed[] } {+ const { text, matches } = extractDirectives(+ reply,+ MINIAPP_DIRECTIVE,+ TRAILING_OPEN_MINIAPP_DIRECTIVE,+ ([url, title]) => {+ const parsed = parseMiniappUrl(url ?? "");+ if (!parsed) return undefined;+ const label = (title ?? "").trim() || "Playground";+ return { url: parsed, title: label };+ },+ );+ const seen = new Set<string>();+ const miniapps: MiniappEmbed[] = [];+ for (const item of matches) {+ if (seen.has(item.url)) continue;+ seen.add(item.url);+ miniapps.push(item);+ }+ return { text, miniapps: miniapps.slice(0, MAX_MINIAPPS) };+}++export function stripMiniappDirectives(partial: string): string {+ if (!partial) return partial ?? "";+ return extractMiniapps(partial).text;+}++export function miniappActionBlocks(miniapps: readonly MiniappEmbed[]): Array<Record<string, unknown>> {+ const buttons = miniapps+ .filter((m) => /^https?:\/\//i.test(m.url))+ .slice(0, MAX_MINIAPPS)+ .map((m, i) => ({+ type: "button",+ action_id: `miniapp_open:${i}`,+ text: { type: "plain_text", text: clip(m.title, BUTTON_TEXT_MAX) || "Open playground" },+ url: m.url,+ }));+ if (!buttons.length) return [];+ return [{ type: "actions", block_id: "miniapp_open", elements: buttons }];+}diff --git a/src/tools/primitives.ts b/src/tools/primitives.tsindex d3ea49029..3c417686b 100644--- a/src/tools/primitives.ts+++ b/src/tools/primitives.ts@@ -41,6 +41,7 @@ import type { AuditLog } from "../audit/audit-log.ts";import { mimeFromName } from "../core/attachments.ts";import { swallow } from "../util/errors.ts";import { fileArtifactId, isArtifactPath, type FileArtifactStore } from "../files/file-artifact-store.ts";+import { putMiniapp, type MiniappInput, type MiniappResult, type MiniappStore } from "../miniapps/miniapp.ts";import type { ScopedConfigStore } from "../resolution/config-store.ts";import { MEMORY_FILE, type MemoryService } from "../memory/memory-service.ts";import type { McpToolService, McpToolDescriptor } from "../mcp/mcp-tool-service.ts";@@ -173,6 +174,7 @@ export interface ToolContext extends SurfaceToolDeps {read(path: string): Promise<ReadResult>;write(path: string, data?: string, share?: ShareDirective[]): Promise<WriteResult>;publish(input: PublishInput): Promise<PublishResult>;+ miniapp(input: MiniappInput): Promise<MiniappResult>;memorySearch(q: string, limit?: number): Promise<string[] | null>;memoryRead(): Promise<string | null>;memoryRemember(facts: string[]): Promise<number | null>;@@ -394,6 +396,7 @@ export interface ToolContextDeps {deploy: DeployService;acl: AclStore;files?: FileArtifactStore;+ miniapps?: MiniappStore;auditLog?: AuditLog;createdBy: string;publicWebUrl?: string;@@ -752,6 +755,27 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {);},+ async miniapp(input: MiniappInput): Promise<MiniappResult> {+ if (!deps.miniapps) throw new Error("miniapps are not available");+ if (!writableScopeId) throw new Error("miniapp needs a writable scope to own the playground");+ let html = input.html;+ if ((html === undefined || !html.trim()) && input.file) {+ if (hasParentPathSegment(input.file)) throw new Error("miniapp file must stay inside the workspace");+ const handle = await deps.provision();+ const bytes = await deps.sandbox.readFileBytes(handle, input.file);+ if (bytes === null) throw new Error(`miniapp: no such file ${input.file}`);+ html = Buffer.from(bytes).toString("utf8");+ }+ if (!html?.trim()) throw new Error("miniapp needs `html` or a `file` with HTML in it");+ return putMiniapp(deps.miniapps, {+ title: input.title,+ html,+ ownerScopeId: writableScopeId,+ createdBy: deps.createdBy,+ publicBase: deps.publicWebUrl ?? deps.webhookPublicUrl,+ });+ },+async publish(input: PublishInput): Promise<PublishResult> {if (!writableScopeId) throw new Error("publish needs a writable scope to own the app");const owner: ScopeId = scopeId("personal", deps.createdBy);diff --git a/src/wiring.ts b/src/wiring.tsindex f37513cea..63e46f448 100644--- a/src/wiring.ts+++ b/src/wiring.ts@@ -109,6 +109,7 @@ import {} from "./files/durable-byte-store.ts";import { createMemoryFileArtifactStore, type FileArtifactStore } from "./files/file-artifact-store.ts";import { createPostgresFileArtifactStore } from "./files/postgres-file-artifact-store.ts";+import { type MiniappRecord, type MiniappStore } from "./miniapps/miniapp.ts";import { createAwsSandbox, type StoredMicrovm } from "./sandbox/aws-sandbox.ts";import { createLocalSandbox } from "./sandbox/local-sandbox.ts";import { createSpritesSandbox } from "./sandbox/sprites-sandbox.ts";@@ -365,6 +366,7 @@ export interface BuiltApp {sandboxMigration: SandboxMigrationRunner;blobTransfer: BlobTransferStore;files: FileArtifactStore;+ miniapps: MiniappStore;livenessCache: LivenessCache;deviceFlowCutover: DeviceFlowCutoverStore;replayDedupe?: ReplayDedupe;@@ -581,6 +583,7 @@ export function buildApp(const files: FileArtifactStore = config.databaseUrl? createPostgresFileArtifactStore(config.databaseUrl, fileBytes): createMemoryFileArtifactStore(fileBytes);+ const miniapps: MiniappStore = artifactMap<MiniappRecord>("miniapps");const baseMemory: MemoryService = config.databaseUrl? createPostgresMemoryService(config.databaseUrl): createMemoryService(workspace);@@ -1012,6 +1015,7 @@ export function buildApp(sessions,workspace,files,+ miniapps,sandbox,connectorTokens,modelGateway,@@ -1564,6 +1568,7 @@ export function buildApp(advisoryLock,blobTransfer,files,+ miniapps,livenessCache,deviceFlowCutover,...(replayDedupe ? { replayDedupe } : {}),@@ -1648,6 +1653,7 @@ export function serverDeps(runs: built.runs,workspace: built.workspace,files: built.files,+ miniapps: built.miniapps,memory: built.memory,blobTransfer: built.blobTransfer,sandboxBackend: built.sandbox.profile.backend,diff --git a/test/dev-cli-lib.test.ts b/test/dev-cli-lib.test.tsindex 3b0dd58b1..18ae733be 100644--- a/test/dev-cli-lib.test.ts+++ b/test/dev-cli-lib.test.ts@@ -391,6 +391,27 @@ test("child specs omit Slack env when no Slack tokens are supplied", () => {assert.equal(core.env.DEV_INTROSPECTION, undefined);assert.equal(core.env.DEV_HEALTH_PORT, undefined);assert.equal(core.env.CORE_ORG_ID, "acme");+ assert.equal(core.env.PUBLIC_WEB_URL, `http://localhost:${inputs.ports.portal}`);+});++test("child specs keep an operator-set PUBLIC_WEB_URL so Slack playground links are reachable", () => {+ const inputs: SpecInputs = {+ worktree: "/tmp/worktree",+ ports: slotPorts("pool1"),+ baseEnv: { PUBLIC_WEB_URL: "https://tunnel.example" },+ watch: false,+ webUiBasePath: "/",+ sessionStore: "memory",+ runStore: "memory",+ databaseUrl: "",+ adminGrantsSeed: "",+ coreSigningSecret: "",+ portalSessionSecret: "secret",+ portalDevPrincipal: "U1",+ sandboxEnv: {},+ };+ const core = buildChildSpecs(inputs).find((spec) => spec.name === "core")!;+ assert.equal(core.env.PUBLIC_WEB_URL, "https://tunnel.example");});test("formatAge renders the bash-compatible shapes", () => {diff --git a/test/miniapp.test.ts b/test/miniapp.test.tsnew file mode 100644index 000000000..3dd56b6d3--- /dev/null+++ b/test/miniapp.test.ts@@ -0,0 +1,182 @@+import { test } from "node:test";+import assert from "node:assert/strict";+import type { AddressInfo } from "node:net";+import { createServer } from "../src/api/server.ts";+import { buildApp } from "../src/wiring.ts";+import {+ putMiniapp,+ MAX_MINIAPP_HTML_BYTES,+ documentHtml,+ clipMiniappTitle,+ parseMiniappView,+ skinMiniappHtml,+ assertMiniappOk,+} from "../src/miniapps/miniapp.ts";+import { createToolContext } from "../src/tools/primitives.ts";+import { testConfig } from "./support/test-config.ts";+import { scopeId } from "../src/types.ts";+import { extractMiniapps, parseMiniappUrl, miniappActionBlocks } from "../src/slack/lib.ts";+import { cleanAgentReplyForSlack, slackSurfaceInstructions } from "../src/slack/messaging.ts";++const SECRET = "miniapp-test-secret-value-32chars!!";++test("skinMiniappHtml injects host tokens and follows the requested theme", () => {+ const light = skinMiniappHtml("<!doctype html><html><head></head><body>x</body></html>", "light");+ assert.match(light, /id="qm-miniapp-skin"/);+ assert.match(light, /--background:#ffffff/);+ assert.match(light, /overflow:hidden/);+ assert.match(light, /height:100%/);+ const dark = skinMiniappHtml(light, "dark");+ assert.equal(dark.match(/id="qm-miniapp-skin"/g)?.length, 1);+ assert.match(dark, /--background:#0a0a0a/);+ assert.doesNotMatch(dark, /--background:#ffffff/);+});++test("assertMiniappOk accepts a real playground and rejects broken ones", () => {+ assert.doesNotThrow(() => assertMiniappOk("<!doctype html><html><body><canvas id=c></canvas><script>void 0</script></body></html>"));+ assert.throws(() => assertMiniappOk("<!doctype html><html><body></body></html>"), /nothing to show/);+ assert.throws(() => assertMiniappOk("<!doctype html><html><body><canvas></canvas><script>fetch('/')</script></body></html>"), /network/);+ assert.throws(() => assertMiniappOk("<!doctype html><html><body><p>x</p><script>function (</script></body></html>"), /does not parse/);+ assert.throws(+ () => assertMiniappOk("<!doctype html><html><body><p>x</p><script src='https://x.test/a.js'></script></body></html>"),+ /inline/,+ );+});++test("parseMiniappView only accepts source", () => {+ assert.equal(parseMiniappView("source"), "source");+ assert.equal(parseMiniappView("play"), undefined);+});++test("documentHtml wraps fragments and leaves full documents alone", () => {+ const wrapped = documentHtml("Hi", "<p>x</p>");+ assert.match(wrapped, /<!doctype html>/i);+ assert.match(wrapped, /<title>Hi<\/title>/);+ const full = "<!doctype html><html><body>ok</body></html>";+ assert.equal(documentHtml("Hi", full), full);+});++test("clipMiniappTitle falls back and truncates", () => {+ assert.equal(clipMiniappTitle(" "), "Playground");+ assert.equal(clipMiniappTitle("a".repeat(90)).length, 80);+});++test("extractMiniapps strips the directive and keeps a valid url", () => {+ const r = extractMiniapps("Here you go\n[[miniapp: https://qm.test/m/abc/def | Slope]]");+ assert.equal(r.text, "Here you go");+ assert.equal(r.miniapps.length, 1);+ assert.equal(r.miniapps[0]!.title, "Slope");+ assert.equal(r.miniapps[0]!.url, "https://qm.test/m/abc/def");+ assert.equal(parseMiniappUrl("javascript:alert(1)"), null);+ assert.equal(parseMiniappUrl("/m/abc/def"), "/m/abc/def");+ assert.equal(parseMiniappUrl("https://evil.test/x"), null);+});++test("miniapp Slack buttons are url buttons", () => {+ const blocks = miniappActionBlocks([{ url: "https://qm.test/m/a/b", title: "Play" }]);+ assert.equal(blocks[0]!.type, "actions");+ const btn = (blocks[0] as { elements: Array<{ type: string; url: string }> }).elements[0]!;+ assert.equal(btn.type, "button");+ assert.equal(btn.url, "https://qm.test/m/a/b");+ assert.equal(miniappActionBlocks([{ url: "/m/a/b", title: "Play" }]).length, 0);+});++test("cleanAgentReplyForSlack strips miniapp markers and Slack does not render them", () => {+ const cleaned = cleanAgentReplyForSlack("Try this\n[[miniapp: https://qm.test/m/aa/bb | Blocks]]");+ assert.equal(cleaned.text, "Try this");+ assert.equal(cleaned.miniapps[0]!.title, "Blocks");+ assert.doesNotMatch(slackSurfaceInstructions("dm"), /\[\[miniapp:/);+});++test("putMiniapp stores HTML and GET /m/:id/:key serves it sandboxed", async () => {+ const built = buildApp(testConfig({ signingSecret: SECRET }));+ const rec = await putMiniapp(built.miniapps, {+ title: "Slope",+ html: "<canvas id=c></canvas><script>c.getContext('2d')</script>",+ ownerScopeId: scopeId("personal", "U1"),+ createdBy: "U1",+ publicBase: "https://qm.test",+ });+ assert.match(rec.url, /^https:\/\/qm\.test\/m\/[0-9a-f]+\/[A-Za-z0-9_-]+$/);+ assert.match(rec.directive, /\[\[miniapp:/);++ const server = createServer(built.app, { signingSecret: SECRET, miniapps: built.miniapps });+ await new Promise<void>((r) => server.listen(0, r));+ const port = (server.address() as AddressInfo).port;+ try {+ const path = new URL(rec.url).pathname;+ const ok = await fetch(`http://localhost:${port}${path}`);+ assert.equal(ok.status, 200);+ const html = await ok.text();+ assert.match(html, /<canvas/);+ assert.match(html, /id="qm-miniapp-skin"/);+ assert.match(html, /id="qm-miniapp-probe"/);+ assert.match(html, /source:"qm-miniapp"/);+ const themed = await fetch(`http://localhost:${port}${path}?theme=dark`);+ assert.match(await themed.text(), /--background:#0a0a0a/);+ const source = await fetch(`http://localhost:${port}${path}?view=source`);+ assert.equal(source.status, 200);+ assert.match(source.headers.get("content-type") ?? "", /text\/plain/);+ const raw = await source.text();+ assert.match(raw, /<canvas/);+ assert.doesNotMatch(raw, /id="qm-miniapp-skin"/);+ const csp = ok.headers.get("content-security-policy") ?? "";+ assert.match(csp, /^sandbox\b/);+ assert.ok(!/allow-same-origin/.test(csp));+ assert.match(csp, /connect-src 'none'/);+ const miss = await fetch(`http://localhost:${port}/m/${rec.id}/wrong-key`);+ assert.equal(miss.status, 404);+ } finally {+ await new Promise<void>((r) => server.close(() => r()));+ }+});++test("miniapp tool writes a playground and returns a directive", async () => {+ const built = buildApp(testConfig({ signingSecret: SECRET }));+ const tc = createToolContext({+ sandbox: { provision: async () => ({}) } as never,+ provision: async () => ({}) as never,+ layers: [{ scopeId: scopeId("personal", "U1"), mountPath: "", mode: "rw" }],+ commandPolicy: () => ({}) as never,+ authorizeCommand: () => true,+ grantedHandles: [],+ workspace: {} as never,+ deploy: { deployOrUpdate: async () => ({ id: "x" }) } as never,+ acl: built.acl,+ createdBy: "U1",+ miniapps: built.miniapps,+ publicWebUrl: "https://qm.test",+ });+ const r = await tc.miniapp({ title: "Blocks", html: "<p>hi</p>" });+ assert.equal(r.title, "Blocks");+ assert.match(r.url, /^https:\/\/qm\.test\/m\//);+ assert.match(r.directive, /\[\[miniapp: https:\/\/qm\.test\/m\//);+});++test("putMiniapp refuses a playground that cannot render", async () => {+ const built = buildApp(testConfig({ signingSecret: SECRET }));+ await assert.rejects(+ () =>+ putMiniapp(built.miniapps, {+ title: "broken",+ html: "<p>x</p><script>function (</script>",+ ownerScopeId: scopeId("personal", "U1"),+ createdBy: "U1",+ }),+ /does not parse/,+ );+});++test("miniapp rejects oversized HTML", async () => {+ const built = buildApp(testConfig({ signingSecret: SECRET }));+ await assert.rejects(+ () =>+ putMiniapp(built.miniapps, {+ title: "big",+ html: "x".repeat(MAX_MINIAPP_HTML_BYTES + 1),+ ownerScopeId: scopeId("personal", "U1"),+ createdBy: "U1",+ }),+ /keep it under/,+ );+});diff --git a/test/pi-tools.test.ts b/test/pi-tools.test.tsindex 6e89b8fed..2e8bf5bec 100644--- a/test/pi-tools.test.ts+++ b/test/pi-tools.test.ts@@ -36,6 +36,14 @@ function fakeToolContext(sink?: { lastExecOpts?: Parameters<ToolContext["executeurl: `/d/${input.name ?? "dep-1"}/`,};},+ async miniapp(input) {+ return {+ id: "mini-1",+ title: input.title,+ url: "https://qm.test/m/mini-1/key",+ directive: `[[miniapp: https://qm.test/m/mini-1/key | ${input.title}]]`,+ };+ },async memorySearch(q) {return q.includes("billing") ? ["(2026-05-31) Owns the billing service"] : [];},@@ -529,6 +537,27 @@ test("the screen never rewrites a policy notice — an approval gate stays legibassert.equal(pending.length, 1);});+test("miniapp and publish results are first-party and never quarantined", async () => {+ const emitted: Emitted[] = [];+ const ref: ToolContextRef = {+ current: fakeToolContext(),+ emit: (e) => {+ emitted.push(e as Emitted);+ },+ scopeLabel: "personal:U1",+ screenToolResult: async () => false,+ };+ const tools = createPiTools(ref);+ const miniapp = tools.find((t) => t.name === "miniapp");+ const publish = tools.find((t) => t.name === "publish");+ const mini = (await call(miniapp, { title: "Blocks", html: "<p>hi</p>" })) as { content: Array<{ text?: string }> };+ assert.match(mini.content[0]?.text ?? "", /\[\[miniapp:/);+ assert.equal(emitted.find((e) => e.type === "tool_result" && e.payload.tool === "miniapp")!.payload.quarantined, undefined);+ const pub = (await call(publish, { name: "app", dir: "app" })) as { content: Array<{ text?: string }> };+ assert.match(pub.content[0]?.text ?? "", /Published/);+ assert.equal(emitted.find((e) => e.type === "tool_result" && e.payload.tool === "publish")!.payload.quarantined, undefined);+});+test("the screen never rewrites a policy denial either", async () => {const denied: ToolContext = {...fakeToolContext(),@@ -1014,11 +1043,11 @@ test("readOnly assembles ONLY observational tools — no execute/background/writconst readOnly = createPiTools(ref, { controlTools: true, scratchExec: true, reachExec: true, readOnly: true });const names = (ts: ReturnType<typeof createPiTools>) => new Set(ts.map((t) => t.name));- for (const t of ["execute", "background", "read", "write", "publish", "cron", "webhook", "guidance"]) {+ for (const t of ["execute", "background", "read", "write", "publish", "miniapp", "cron", "webhook", "guidance"]) {assert.ok(names(full).has(t), `full toolset has ${t}`);}assert.deepEqual([...names(readOnly)].sort(), ["finish_silently", "history", "memory"]);- for (const t of ["execute", "background", "read", "write", "publish", "cron", "webhook", "guidance"]) {+ for (const t of ["execute", "background", "read", "write", "publish", "miniapp", "cron", "webhook", "guidance"]) {assert.ok(!names(readOnly).has(t), `read-only toolset drops ${t}`);}});@@ -1160,7 +1189,10 @@ test("tool entries carry the call id + faithful model-facing result (WAL replay},scopeLabel: "personal:U1",};- const [execute, read, , , memory] = createPiTools(ref);+ const tools = createPiTools(ref);+ const execute = tools.find((t) => t.name === "execute")!;+ const read = tools.find((t) => t.name === "read")!;+ const memory = tools.find((t) => t.name === "memory")!;await callWith(execute, "call-exec", { command: "echo hi" });await callWith(read, "call-read", { path: "a.txt" });diff --git a/test/route-auth-conformance.test.ts b/test/route-auth-conformance.test.tsindex fb486e4e0..82358b298 100644--- a/test/route-auth-conformance.test.ts+++ b/test/route-auth-conformance.test.ts@@ -69,6 +69,7 @@ test("every pinned dedicated-audience route actually resolves in the table", ()test("raw routes keep their declared auth contracts (they self-enforce, so the declaration is the pin)", () => {const pins: Array<[string, string, RouteAuth]> = [["GET", "/healthz", "public"],+ ["GET", "/m/sample/sample", "public"],["GET", "/v1/credentials/git/gitlab/acme/repo.git/info/refs", { aud: CREDENTIAL_BROKER_AUD }],["POST", "/v1/credentials/git/gitlab/acme/repo.git/git-upload-pack", { aud: CREDENTIAL_BROKER_AUD }],];diff --git a/test/skill-conformance.test.ts b/test/skill-conformance.test.tsindex c67b8f570..42c076722 100644--- a/test/skill-conformance.test.ts+++ b/test/skill-conformance.test.ts@@ -21,3 +21,13 @@ test("every seed SKILL.md parses with a name, description, and body", () => {assert.ok(m.name && m.description && m.body.trim(), `${path} is missing a required field`);}});++test("miniapp skill teaches the miniapp tool and the reply directive", () => {+ const skill = readFileSync(join(SEED_DIR, "miniapp", "SKILL.md"), "utf8");+ assert.match(skill, /`miniapp` tool/);+ assert.match(skill, /\[\[miniapp:/);+ assert.match(skill, /publish/);+ assert.match(skill, /Do not build a playground just because/);+ assert.doesNotMatch(skill, /Prefer this over a long prose explanation/);+ assert.doesNotMatch(skill, /PORT env/);+});