Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

refactor: model playgrounds as typed artifacts

16francejde8a8e080148
diff --git a/plugins/portal/README.md b/plugins/portal/README.md
index df6c311f4..39c3ccbad 100644
--- a/plugins/portal/README.md
+++ b/plugins/portal/README.md
@@ -6,11 +6,10 @@ fronts every surface. It does provider-neutral **OIDC** sign-in (Google Workspac
is the email-first deployment default) and reverse-proxies — over Fly's private 6PN — to the
surfaces, 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`) |
-| `/m/:id/:key` | core | public bearer HTML playgrounds (miniapps); no session; CSP-sandboxed |
+| 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`) |
User deployments are never served on this authenticated origin; they use the dedicated apps domain.
@@ -28,12 +27,10 @@ surfaces, and it does **not** import the core.
the subject from userinfo. The verified `sub` **is** the core principal id. It mints a
signed `portal_session` cookie (`{sub, org, auth, exp}`, HMAC, 8h sliding lifetime with a
24h absolute maximum by default).
-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.
+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.
## Security model (the parts that must be right)
diff --git a/plugins/portal/src/index.ts b/plugins/portal/src/index.ts
index 6ba56ad55..16a001dd3 100644
--- a/plugins/portal/src/index.ts
+++ b/plugins/portal/src/index.ts
@@ -959,11 +959,6 @@ 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.ts
index 1fb5c0d4d..668fe5bfa 100644
--- a/plugins/portal/test/router.test.ts
+++ b/plugins/portal/test/router.test.ts
@@ -230,21 +230,6 @@ 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.ts
index d0e9c384d..28e2f158e 100644
--- a/plugins/web-ui/server/index.ts
+++ b/plugins/web-ui/server/index.ts
@@ -153,6 +153,19 @@ function withSecurityHeaders(headers: Record<string, string>): Record<string, st
}
const UNTRUSTED_CONTENT_SANDBOX_CSP = "sandbox allow-scripts allow-forms allow-popups allow-modals allow-downloads";
+const PLAYGROUND_CSP = [
+ "sandbox allow-scripts allow-pointer-lock",
+ "default-src 'none'",
+ "script-src 'unsafe-inline'",
+ "style-src 'unsafe-inline'",
+ "img-src data: blob:",
+ "media-src data: blob:",
+ "font-src data:",
+ "connect-src 'none'",
+ "worker-src blob:",
+ "base-uri 'none'",
+ "form-action 'none'",
+].join("; ");
interface ViteDevServer {
middlewares(req: IncomingMessage, res: ServerResponse, next: (err?: unknown) => void): void;
@@ -799,6 +812,46 @@ type WebRoute = { handle: (c: WebCtx) => unknown } & (
{ method: string; path: string } | { match: (method: string, pathname: string) => boolean }
);
+async function streamFileArtifact(c: WebCtx, playground = false): Promise<unknown> {
+ const { res, user, url } = c;
+ const id = c.params.id!;
+ const corePath = withSourceAuthNonce(
+ `/v1/files/${encodeURIComponent(id)}/content?viewer=${encodeURIComponent(user)}`,
+ CORE_SIGNING_SECRET,
+ );
+ const portalTok = portalTokenStore.getStore();
+ const r = await fetch(`${CORE}${corePath}`, {
+ headers: {
+ ...signedHeaders(CORE_SIGNING_SECRET, "GET", corePath, ""),
+ ...(portalTok ? { [PORTAL_IDENTITY_HEADER]: portalTok } : {}),
+ },
+ redirect: "manual",
+ });
+ if (!r.ok || !r.body) {
+ res.writeHead(r.status === 404 ? 404 : 502, { "content-type": "application/json" });
+ return res.end(JSON.stringify({ error: r.status === 404 ? "not_found" : "upstream_error" }));
+ }
+ const contentType = r.headers.get("content-type") ?? "application/octet-stream";
+ if (playground && !contentType.toLowerCase().startsWith("text/html")) {
+ res.writeHead(415, { "content-type": "application/json" });
+ return res.end(JSON.stringify({ error: "not_a_playground" }));
+ }
+ const asSource = playground && url.searchParams.get("source") === "1";
+ const length = r.headers.get("content-length");
+ // Playgrounds are framed, never downloaded, so they carry no disposition.
+ const disposition = playground ? null : r.headers.get("content-disposition");
+ res.writeHead(200, {
+ "content-type": asSource ? "text/plain; charset=utf-8" : contentType,
+ ...(length ? { "content-length": length } : {}),
+ ...(disposition ? { "content-disposition": disposition } : {}),
+ "content-security-policy": playground ? PLAYGROUND_CSP : UNTRUSTED_CONTENT_SANDBOX_CSP,
+ "referrer-policy": "no-referrer",
+ ...(playground ? { "x-frame-options": "SAMEORIGIN" } : {}),
+ "x-content-type-options": "nosniff",
+ });
+ return Readable.fromWeb(r.body as Parameters<typeof Readable.fromWeb>[0]).pipe(res);
+}
+
const apiRoutes: readonly WebRoute[] = [
{
match: (_method, pathname) => pathname === "/me",
@@ -1330,36 +1383,12 @@ const apiRoutes: readonly WebRoute[] = [
{
method: "GET",
path: "/api/files/:id/content",
- handle: async (c) => {
- const { res, user } = c;
- const id = c.params.id!;
- const corePath = withSourceAuthNonce(
- `/v1/files/${encodeURIComponent(id)}/content?viewer=${encodeURIComponent(user)}`,
- CORE_SIGNING_SECRET,
- );
- const portalTok = portalTokenStore.getStore();
- const r = await fetch(`${CORE}${corePath}`, {
- headers: {
- ...signedHeaders(CORE_SIGNING_SECRET, "GET", corePath, ""),
- ...(portalTok ? { [PORTAL_IDENTITY_HEADER]: portalTok } : {}),
- },
- redirect: "manual",
- });
- if (!r.ok || !r.body) {
- res.writeHead(r.status === 404 ? 404 : 502, { "content-type": "application/json" });
- return res.end(JSON.stringify({ error: r.status === 404 ? "not_found" : "upstream_error" }));
- }
- res.writeHead(200, {
- "content-type": r.headers.get("content-type") ?? "application/octet-stream",
- ...(r.headers.get("content-length") ? { "content-length": r.headers.get("content-length")! } : {}),
- ...(r.headers.get("content-disposition")
- ? { "content-disposition": r.headers.get("content-disposition")! }
- : {}),
- "content-security-policy": UNTRUSTED_CONTENT_SANDBOX_CSP,
- "x-content-type-options": "nosniff",
- });
- return Readable.fromWeb(r.body as Parameters<typeof Readable.fromWeb>[0]).pipe(res);
- },
+ handle: (c) => streamFileArtifact(c),
+ },
+ {
+ method: "GET",
+ path: "/api/playgrounds/:id",
+ handle: (c) => streamFileArtifact(c, true),
},
{
method: "GET",
@@ -2422,27 +2451,6 @@ 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.ts
index 11d40462f..af02c09d2 100644
--- a/plugins/web-ui/src/chat.ts
+++ b/plugins/web-ui/src/chat.ts
@@ -6,7 +6,6 @@ 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,
@@ -14,7 +13,6 @@ import {
Check,
ChevronRight,
Clock3,
- Code2,
Copy,
FileImage,
FileText,
@@ -71,16 +69,6 @@ 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";
@@ -113,6 +101,7 @@ import { backgroundLabel, clearWorking, conversationBackground, isAbandonedNewCh
import { liveTurnThreadRef } from "./working-dot";
import { newChatDraftKey, saveDraft, storedDraft } from "./drafts";
import { createForkOriginController, forkOriginView } from "./fork-origin";
+import { playgroundPath, playgroundsIn, type PlaygroundArtifact } from "./playground";
installMarkdownSanitizer();
@@ -129,50 +118,11 @@ 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));
@@ -560,13 +510,8 @@ export function createChatSurface(
if (chatState.agent) drawActiveChat();
}
- function redrawForMiniapp(): void {
- redrawTranscript();
- }
-
function dispose(): void {
redrawHooks.delete(redrawForConnector);
- redrawHooks.delete(redrawForMiniapp);
teardownActiveChat();
}
@@ -1293,13 +1238,6 @@ 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 &&
@@ -1312,8 +1250,7 @@ export function createChatSurface(
hit.errorMessage === msg.errorMessage &&
hit.approvalDecision === msg.approvalDecision &&
hit.sendFailure === msg.sendFailure &&
- hit.forkable === forkable &&
- hit.miniappKey === miniappKey
+ hit.forkable === forkable
) {
return hit.tpl;
}
@@ -1329,7 +1266,6 @@ export function createChatSurface(
approvalDecision: msg.approvalDecision,
sendFailure: msg.sendFailure,
forkable,
- miniappKey,
tpl,
});
return tpl;
@@ -1522,89 +1458,25 @@ 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>
+ function playgroundCard(playground: PlaygroundArtifact): TemplateResult {
+ const src = withBase(playgroundPath(playground.artifactId));
+ const source = withBase(playgroundPath(playground.artifactId, true));
+ return html`<section class="playground-card">
+ <header class="playground-header">
+ <span class="playground-title">${icon(Rocket, 16)}<strong>${playground.title}</strong></span>
+ <nav class="playground-actions" aria-label="Playground actions">
+ <a href=${source} target="_blank" rel="noreferrer">${icon(FileText, 14)} Source</a>
+ <a href=${src} target="_blank" rel="noreferrer">${icon(Maximize2, 14)} Open</a>
</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>`;
+ <iframe
+ class="playground-frame"
+ src=${src}
+ title=${playground.title}
+ sandbox="allow-scripts allow-forms allow-pointer-lock"
+ referrerpolicy="no-referrer"
+ ></iframe>
+ </section>`;
}
function assistantContent(message: AssistantMessage, isStreaming = false, hasWork = false): TemplateResult[] {
@@ -1612,9 +1484,7 @@ export function createChatSurface(
for (const chunk of message.content) {
if (chunk.type === "text" && chunk.text.trim()) {
const links = connectorLinksIn(chunk.text, location.origin);
- const apps = miniappsIn(chunk.text);
- let body = stripMiniappDirectives(chunk.text);
- if (links.length) body = stripConnectorLinks(body);
+ const body = links.length ? stripConnectorLinks(chunk.text) : chunk.text;
if (body.trim())
parts.push(
html`<div class="streaming-text ${isStreaming ? "live-stream" : ""}">
@@ -1622,7 +1492,6 @@ 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(
@@ -1633,6 +1502,9 @@ export function createChatSurface(
);
}
}
+ for (const playground of playgroundsIn((message as AssistantWork).work?.activity)) {
+ parts.push(playgroundCard(playground));
+ }
if (
parts.length === 0 &&
message.stopReason !== "error" &&
@@ -2452,7 +2324,6 @@ 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.ts
index 7621bdff3..05ff11c67 100644
--- a/plugins/web-ui/src/lazy-hljs.ts
+++ b/plugins/web-ui/src/lazy-hljs.ts
@@ -8,13 +8,6 @@ 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" };
@@ -54,8 +47,6 @@ 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.ts
deleted file mode 100644
index ac293c093..000000000
--- a/plugins/web-ui/src/miniapp.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-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/playground.ts b/plugins/web-ui/src/playground.ts
new file mode 100644
index 000000000..27c1b82d8
--- /dev/null
+++ b/plugins/web-ui/src/playground.ts
@@ -0,0 +1,48 @@
+import type { ToolActivity } from "./core-bridge";
+
+const MAX_PLAYGROUNDS_PER_MESSAGE = 5;
+
+export interface PlaygroundArtifact {
+ kind: "playground";
+ artifactId: string;
+ title: string;
+}
+
+/** Only the two fields the scan needs, so a transcript entry and a live one both fit. */
+export type PlaygroundActivity = Pick<ToolActivity, "type" | "payload">;
+
+function playgroundFromPayload(payload: unknown): PlaygroundArtifact | null {
+ if (!payload || typeof payload !== "object") return null;
+ const value = payload as Record<string, unknown>;
+ const display = value.display;
+ if (value.tool !== "miniapp" || value.isError === true || !display || typeof display !== "object") return null;
+ const artifact = (display as Record<string, unknown>).artifact;
+ if (!artifact || typeof artifact !== "object") return null;
+ const typed = artifact as Record<string, unknown>;
+ if (
+ typed.kind !== "playground" ||
+ typeof typed.artifactId !== "string" ||
+ !typed.artifactId ||
+ typeof typed.title !== "string" ||
+ !typed.title.trim()
+ )
+ return null;
+ return { kind: "playground", artifactId: typed.artifactId, title: typed.title };
+}
+
+export function playgroundsIn(activity: readonly PlaygroundActivity[] | undefined): PlaygroundArtifact[] {
+ const seen = new Set<string>();
+ const playgrounds: PlaygroundArtifact[] = [];
+ for (const entry of activity ?? []) {
+ if (entry.type !== "tool_result") continue;
+ const playground = playgroundFromPayload(entry.payload);
+ if (!playground || seen.has(playground.artifactId)) continue;
+ seen.add(playground.artifactId);
+ playgrounds.push(playground);
+ }
+ return playgrounds.slice(0, MAX_PLAYGROUNDS_PER_MESSAGE);
+}
+
+export function playgroundPath(artifactId: string, source = false): string {
+ return `/api/playgrounds/${encodeURIComponent(artifactId)}${source ? "?source=1" : ""}`;
+}
diff --git a/plugins/web-ui/src/shell.css b/plugins/web-ui/src/shell.css
index 20896efdd..371a5fb0a 100644
--- a/plugins/web-ui/src/shell.css
+++ b/plugins/web-ui/src/shell.css
@@ -3260,188 +3260,6 @@ 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;
@@ -8159,3 +7977,56 @@ h3.ambient-field-label {
margin-top: 16px;
align-self: flex-start;
}
+
+.playground-card {
+ overflow: hidden;
+ margin-top: 10px;
+ border: 1px solid var(--border);
+ border-radius: 12px;
+ background: var(--card);
+}
+.playground-header,
+.playground-title,
+.playground-actions,
+.playground-actions a {
+ display: flex;
+ align-items: center;
+}
+.playground-header {
+ justify-content: space-between;
+ gap: 12px;
+ min-height: 40px;
+ padding: 0 12px;
+ border-bottom: 1px solid var(--border);
+}
+.playground-title {
+ min-width: 0;
+ gap: 7px;
+}
+.playground-title strong {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+.playground-actions {
+ gap: 4px;
+}
+.playground-actions a {
+ gap: 4px;
+ padding: 5px 7px;
+ border-radius: 6px;
+ color: var(--muted-foreground);
+ font-size: 12px;
+ text-decoration: none;
+}
+.playground-actions a:hover {
+ color: var(--foreground);
+ background: var(--muted);
+}
+.playground-frame {
+ display: block;
+ width: 100%;
+ height: 360px;
+ border: 0;
+ background: white;
+}
diff --git a/plugins/web-ui/test/miniapp-proxy.test.ts b/plugins/web-ui/test/miniapp-proxy.test.ts
deleted file mode 100644
index eb0f7132c..000000000
--- a/plugins/web-ui/test/miniapp-proxy.test.ts
+++ /dev/null
@@ -1,46 +0,0 @@
-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.ts
deleted file mode 100644
index eebfcb86d..000000000
--- a/plugins/web-ui/test/miniapp.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-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/plugins/web-ui/test/playground-content.test.ts b/plugins/web-ui/test/playground-content.test.ts
new file mode 100644
index 000000000..7ce0c79e6
--- /dev/null
+++ b/plugins/web-ui/test/playground-content.test.ts
@@ -0,0 +1,56 @@
+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 HTML = "<!doctype html><button>Go</button><script>void 0</script>";
+const core = createServer((req: IncomingMessage, res) => {
+ if ((req.url ?? "").startsWith("/v1/files/html/content")) {
+ res.writeHead(200, {
+ "content-type": "text/html; charset=utf-8",
+ "content-length": String(Buffer.byteLength(HTML)),
+ });
+ return void res.end(HTML);
+ }
+ if ((req.url ?? "").startsWith("/v1/files/image/content")) {
+ res.writeHead(200, { "content-type": "image/png" });
+ return void res.end("png");
+ }
+ res.writeHead(404, { "content-type": "application/json" });
+ res.end(JSON.stringify({ error: "not_found" }));
+});
+await new Promise<void>((resolve) => core.listen(0, resolve));
+
+process.env.CORE_API_URL = `http://localhost:${(core.address() as AddressInfo).port}`;
+process.env.CORE_SIGNING_SECRET = "playground-content-test";
+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>((resolve) => surface.listen(0, resolve));
+const base = `http://localhost:${(surface.address() as AddressInfo).port}`;
+const headers = { cookie: "webuiuser=alice" };
+
+test.after(() => {
+ surface.close();
+ core.close();
+});
+
+test("playground content is same-origin frameable but isolated from network and parent origin", async () => {
+ const response = await fetch(`${base}/api/playgrounds/html`, { headers });
+ assert.equal(response.status, 200);
+ assert.equal(await response.text(), HTML);
+ const csp = response.headers.get("content-security-policy") ?? "";
+ assert.match(csp, /^sandbox allow-scripts/);
+ assert.match(csp, /default-src 'none'/);
+ assert.match(csp, /connect-src 'none'/);
+ assert.doesNotMatch(csp, /allow-same-origin/);
+ assert.equal(response.headers.get("x-frame-options"), "SAMEORIGIN");
+});
+
+test("source is plain text and non-HTML artifacts are refused", async () => {
+ const source = await fetch(`${base}/api/playgrounds/html?source=1`, { headers });
+ assert.match(source.headers.get("content-type") ?? "", /^text\/plain/);
+ assert.equal(await source.text(), HTML);
+ assert.equal((await fetch(`${base}/api/playgrounds/image`, { headers })).status, 415);
+});
diff --git a/plugins/web-ui/test/playground.test.ts b/plugins/web-ui/test/playground.test.ts
new file mode 100644
index 000000000..911d22939
--- /dev/null
+++ b/plugins/web-ui/test/playground.test.ts
@@ -0,0 +1,28 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { playgroundPath, playgroundsIn, type PlaygroundActivity } from "../src/playground.ts";
+
+test("playgrounds come only from typed successful tool results", () => {
+ const activity: PlaygroundActivity[] = [
+ {
+ type: "tool_result",
+ payload: { tool: "miniapp", display: { artifact: { kind: "playground", artifactId: "a1", title: "Demo" } } },
+ },
+ {
+ type: "tool_result",
+ payload: { tool: "miniapp", display: { artifact: { kind: "playground", artifactId: "a1", title: "Duplicate" } } },
+ },
+ {
+ type: "tool_result",
+ payload: {
+ tool: "miniapp",
+ display: { artifact: { kind: "playground", artifactId: "a2", title: "Bad" } },
+ isError: true,
+ },
+ },
+ { type: "text", payload: { text: "[[miniapp: /m/legacy | ignored]]" } },
+ ];
+
+ assert.deepEqual(playgroundsIn(activity), [{ kind: "playground", artifactId: "a1", title: "Demo" }]);
+ assert.equal(playgroundPath("a/b", true), "/api/playgrounds/a%2Fb?source=1");
+});
diff --git a/scripts/dev/supervisor/specs.ts b/scripts/dev/supervisor/specs.ts
index c611f1de8..5d8867f52 100644
--- a/scripts/dev/supervisor/specs.ts
+++ b/scripts/dev/supervisor/specs.ts
@@ -40,7 +40,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: i.baseEnv.PUBLIC_WEB_URL || `http://localhost:${i.ports.portal}`,
+ 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.md
index 321761204..71da6b332 100644
--- a/skills-seed/miniapp/SKILL.md
+++ b/skills-seed/miniapp/SKILL.md
@@ -1,44 +1,15 @@
---
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.
+description: Build a tiny interactive HTML playground only when someone asks to see, play with, or step through a mechanism.
---
# 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.
+In a web conversation, use the `miniapp` tool for a focused, one-screen interactive explanation, simulation, or small game. The tool is intentionally unavailable on surfaces that cannot render playground artifacts.
-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`.
+- Keep HTML, CSS, and JavaScript self-contained.
+- Do not use network requests, external assets, modules, or servers.
+- Make controls keyboard-accessible and label them clearly.
+- Let the document choose its own presentation; the host will not rewrite it.
+- Do not put a marker or artifact URL in the reply. The client attaches the playground from the typed tool result.
+- Use `publish` instead when the app needs persistence, a server, or multiple routes.
diff --git a/src/api/deps.ts b/src/api/deps.ts
index 55bea5fa5..d0dadd549 100644
--- a/src/api/deps.ts
+++ b/src/api/deps.ts
@@ -53,7 +53,6 @@ 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;
@@ -141,5 +140,4 @@ 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.ts
index e1e0a3ec9..7ea9ad2a6 100644
--- a/src/api/routes/index.ts
+++ b/src/api/routes/index.ts
@@ -27,7 +27,6 @@ import { egressAuditRoutes } from "./egress-audit.ts";
import { authBrokerRoutes } from "./auth-broker.ts";
import { searchRoutes } from "./search.ts";
import { userModelAuthRoutes } from "./user-model-auth.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 }) },
@@ -42,7 +41,6 @@ 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.ts
deleted file mode 100644
index f9be4e313..000000000
--- a/src/api/routes/miniapps.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-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.ts
index e25b10170..4b067e6c7 100644
--- a/src/core/orchestrator.ts
+++ b/src/core/orchestrator.ts
@@ -1860,7 +1860,6 @@ 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.ts
index 258bbe8ee..efe4b1e1a 100644
--- a/src/core/orchestrator/types.ts
+++ b/src/core/orchestrator/types.ts
@@ -57,7 +57,6 @@ 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";
@@ -126,7 +125,6 @@ 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.ts
index cd992a25e..df2d20140 100644
--- a/src/harness/pi-tools.ts
+++ b/src/harness/pi-tools.ts
@@ -3,7 +3,6 @@ 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";
@@ -90,10 +89,6 @@ 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;
@@ -368,6 +363,7 @@ export function createPiTools(ref: ToolContextRef, opts?: PiToolsOptions): ToolD
ret: T,
isError = false,
sourceScopeId?: ScopeId | null,
+ display?: Record<string, unknown>,
): Promise<T> => {
const t = ret.content
.filter((c) => c.type === "text")
@@ -384,7 +380,6 @@ export function createPiTools(ref: ToolContextRef, opts?: PiToolsOptions): ToolD
let persistedSummary = summary;
const screenExempt =
isPolicyNotice(summary) ||
- isFirstPartyToolResult(summary) ||
(summary.action === "post" &&
summary.ok === true &&
result === "[sent]" &&
@@ -423,6 +418,7 @@ export function createPiTools(ref: ToolContextRef, opts?: PiToolsOptions): ToolD
callId,
isError,
...(resultTruncated ? { resultTruncated: true } : {}),
+ ...(display ? { display } : {}),
result,
},
sourceScopeId,
@@ -951,31 +947,31 @@ export function createPiTools(ref: ToolContextRef, opts?: PiToolsOptions): ToolD
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.",
+ "Create a small interactive playground only when the person asks to see, play with, or step through a mechanism. " +
+ "Provide a self-contained HTML document with inline CSS and JavaScript; the browser runs it in an isolated frame " +
+ "without network access. The playground is attached to the turn automatically, so do not add a marker or URL to the reply.",
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`." })),
+ title: Type.String({ description: "Short title shown above the playground." }),
+ html: Type.Optional(Type.String({ description: "Self-contained HTML document or fragment." })),
+ file: Type.Optional(Type.String({ description: "Workspace 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);
+ if (params.html === undefined && params.file === undefined) throw new Error("provide html or file");
+ if (params.html !== undefined && params.file !== undefined) throw new Error("provide only one of html or file");
+ const html = params.file !== undefined ? (await tc.read(params.file)).content : params.html;
+ if (html == null) throw new Error(`no such file: ${params.file}`);
+ const artifact = await tc.createPlayground({ title: params.title, html });
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}`),
+ { tool: "miniapp" },
+ text(`Created playground "${artifact.title}".`),
+ false,
+ undefined,
+ { artifact },
);
} catch (e) {
const msg = errMessage(e);
@@ -3011,9 +3007,9 @@ export function createPiTools(ref: ToolContextRef, opts?: PiToolsOptions): ToolD
read,
write,
publish,
- miniapp,
memory,
history,
+ ...(opts?.surfaceName === "web" ? [miniapp] : []),
background,
...(controlTools ? [cron, webhook, share] : []),
...(controlTools || surfaceTools ? [guidance] : []),
diff --git a/src/miniapps/miniapp.ts b/src/miniapps/miniapp.ts
deleted file mode 100644
index 176a3219f..000000000
--- a/src/miniapps/miniapp.ts
+++ /dev/null
@@ -1,192 +0,0 @@
-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) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[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/playgrounds/playground.ts b/src/playgrounds/playground.ts
new file mode 100644
index 000000000..9e2106a34
--- /dev/null
+++ b/src/playgrounds/playground.ts
@@ -0,0 +1,49 @@
+import { randomUUID } from "node:crypto";
+import { artifactPath, fileArtifactId, type FileArtifactStore } from "../files/file-artifact-store.ts";
+import { headSlice } from "../util/text.ts";
+import type { ScopeId } from "../types.ts";
+
+const MAX_PLAYGROUND_HTML_BYTES = 512_000;
+const PLAYGROUND_TITLE_MAX = 80;
+
+export interface PlaygroundArtifact {
+ kind: "playground";
+ artifactId: string;
+ title: string;
+}
+
+export function normalizePlaygroundTitle(raw: string): string {
+ const title = raw.replace(/\s+/g, " ").trim() || "Playground";
+ return title.length > PLAYGROUND_TITLE_MAX ? `${headSlice(title, PLAYGROUND_TITLE_MAX - 1)}…` : title;
+}
+
+export function validatePlaygroundHtml(html: string): void {
+ const bytes = Buffer.byteLength(html, "utf8");
+ if (bytes > MAX_PLAYGROUND_HTML_BYTES) {
+ throw new Error(`playground HTML is ${bytes} bytes; keep it under ${MAX_PLAYGROUND_HTML_BYTES}`);
+ }
+ if (!html.trim()) throw new Error("playground HTML is empty");
+}
+
+export async function createPlaygroundArtifact(
+ store: FileArtifactStore,
+ input: { title: string; html: string; ownerScopeId: ScopeId; createdBy: string },
+): Promise<PlaygroundArtifact> {
+ validatePlaygroundHtml(input.html);
+ const title = normalizePlaygroundTitle(input.title);
+ const artifactId = fileArtifactId(`playground:${input.ownerScopeId}:${randomUUID()}`, "out", 0);
+ const name = `${artifactId}.html`;
+ await store.put({
+ id: artifactId,
+ ownerScopeId: input.ownerScopeId,
+ createdBy: input.createdBy,
+ name,
+ path: artifactPath(artifactId, name),
+ mimetype: "text/html",
+ data: Buffer.from(input.html),
+ direction: "out",
+ createdInScope: input.ownerScopeId,
+ maxBytes: MAX_PLAYGROUND_HTML_BYTES,
+ });
+ return { kind: "playground", artifactId, title };
+}
diff --git a/src/slack/lib.ts b/src/slack/lib.ts
index 76d7958d2..528082ce5 100644
--- a/src/slack/lib.ts
+++ b/src/slack/lib.ts
@@ -80,13 +80,6 @@ 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.ts
index 975eb8ce4..3e7321b7f 100644
--- a/src/slack/messaging.ts
+++ b/src/slack/messaging.ts
@@ -8,12 +8,9 @@ import {
applyReactions,
botIdentityArgs,
extractAgentRequests,
- extractMiniapps,
extractReactions,
stripAgentRequestDirectives,
- stripMiniappDirectives,
stripReactionDirectives,
- type MiniappEmbed,
} from "./lib.ts";
export type SlackConversationKind = "dm" | "channel" | "group";
@@ -59,16 +56,13 @@ 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: extractedMiniapps.text,
+ text: extractedRequests.text,
reactions: extractedReactions.reactions,
agentRequests: extractedRequests.requests,
- miniapps: extractedMiniapps.miniapps,
};
}
@@ -77,7 +71,7 @@ export function slackSurfaceInstructions(kind: SlackConversationKind): string {
}
export function stripSlackDirectives(text: string): string {
- return stripMiniappDirectives(stripAgentRequestDirectives(stripReactionDirectives(text)));
+ return stripAgentRequestDirectives(stripReactionDirectives(text));
}
export async function applyAndLogReactions(
diff --git a/src/slack/miniapps.ts b/src/slack/miniapps.ts
deleted file mode 100644
index 8cb8ca355..000000000
--- a/src/slack/miniapps.ts
+++ /dev/null
@@ -1,73 +0,0 @@
-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.ts
index 659bef302..30e3eb4aa 100644
--- a/src/tools/primitives.ts
+++ b/src/tools/primitives.ts
@@ -41,7 +41,6 @@ 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";
@@ -62,6 +61,7 @@ import type { ShareArtifactRequest, ShareArtifactResult } from "../api/artifact-
import type { Cron, Webhook } from "../types.ts";
import type { CapabilityClaims } from "../auth/capability-token.ts";
import type { VisibleCron } from "../api/app.ts";
+import { createPlaygroundArtifact, type PlaygroundArtifact } from "../playgrounds/playground.ts";
const SKILL_SKILLMD_RE = /^(?:\.\/)?skills\/([^/]+)\/SKILL\.md$/;
function skillTreeDirFor(path: string): string | null {
@@ -174,7 +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>;
+ createPlayground(input: { title: string; html: string }): Promise<PlaygroundArtifact>;
memorySearch(q: string, limit?: number): Promise<string[] | null>;
memoryRead(): Promise<string | null>;
memoryRemember(facts: string[]): Promise<number | null>;
@@ -396,7 +396,6 @@ export interface ToolContextDeps {
deploy: DeployService;
acl: AclStore;
files?: FileArtifactStore;
- miniapps?: MiniappStore;
auditLog?: AuditLog;
createdBy: string;
publicWebUrl?: string;
@@ -679,6 +678,17 @@ export function createToolContext(deps: ToolContextDeps): ToolContext {
});
},
+ async createPlayground(input: { title: string; html: string }): Promise<PlaygroundArtifact> {
+ if (!deps.files || !writableScopeId) throw new Error("playgrounds require a writable artifact store");
+ return once(() =>
+ createPlaygroundArtifact(deps.files!, {
+ ...input,
+ ownerScopeId: writableScopeId,
+ createdBy: deps.createdBy,
+ }),
+ );
+ },
+
async write(path: string, data?: string, share?: ShareDirective[]): Promise<WriteResult> {
const wantShare = share !== undefined && share.length > 0;
if (data === undefined && !wantShare) {
@@ -755,27 +765,6 @@ 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.ts
index 8e13e82be..181cd9fcb 100644
--- a/src/wiring.ts
+++ b/src/wiring.ts
@@ -116,7 +116,6 @@ 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";
@@ -380,7 +379,6 @@ export interface BuiltApp {
sandboxMigration: SandboxMigrationRunner;
blobTransfer: BlobTransferStore;
files: FileArtifactStore;
- miniapps: MiniappStore;
livenessCache: LivenessCache;
deviceFlowCutover: DeviceFlowCutoverStore;
replayDedupe?: ReplayDedupe;
@@ -600,7 +598,6 @@ export function buildApp(
const files: FileArtifactStore = config.databaseUrl
? createPostgresFileArtifactStore(config.databaseUrl, fileBytes)
: createMemoryFileArtifactStore(fileBytes);
- const miniapps: MiniappStore = artifactMap<MiniappRecord>("miniapps");
const defaultMemory: MemoryService = config.databaseUrl
? createPostgresMemoryService(config.databaseUrl)
: createMemoryService(workspace);
@@ -1111,7 +1108,6 @@ export function buildApp(
sessions,
workspace,
files,
- miniapps,
sandbox,
connectorTokens,
modelGateway,
@@ -1666,7 +1662,6 @@ export function buildApp(
advisoryLock,
blobTransfer,
files,
- miniapps,
livenessCache,
deviceFlowCutover,
...(replayDedupe ? { replayDedupe } : {}),
@@ -1754,7 +1749,6 @@ 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.ts
index cf621aa8c..8b5271c49 100644
--- a/test/dev-cli-lib.test.ts
+++ b/test/dev-cli-lib.test.ts
@@ -464,27 +464,6 @@ 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.ts
deleted file mode 100644
index 3dd56b6d3..000000000
--- a/test/miniapp.test.ts
+++ /dev/null
@@ -1,182 +0,0 @@
-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.ts
index 2e8bf5bec..8a32745d0 100644
--- a/test/pi-tools.test.ts
+++ b/test/pi-tools.test.ts
@@ -36,13 +36,8 @@ function fakeToolContext(sink?: { lastExecOpts?: Parameters<ToolContext["execute
url: `/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 createPlayground(input) {
+ return { kind: "playground", artifactId: "playground-1", title: input.title };
},
async memorySearch(q) {
return q.includes("billing") ? ["(2026-05-31) Owns the billing service"] : [];
@@ -342,6 +337,38 @@ const call = (tool: ReturnType<typeof createPiTools>[number] | undefined, params
return (tool.execute as unknown as (id: string, p: unknown) => Promise<unknown>)("t", params);
};
+test("miniapp records a typed artifact without requiring a reply directive", async () => {
+ const emitted: Emitted[] = [];
+ const ref: ToolContextRef = {
+ current: fakeToolContext(),
+ emit: (entry) => {
+ emitted.push(entry as Emitted);
+ },
+ scopeLabel: "personal:U1",
+ };
+ const miniapp = createPiTools(ref, { surfaceName: "web" }).find((tool) => tool.name === "miniapp");
+ const result = await call(miniapp, { title: "Demo", html: "<button>Go</button>" });
+
+ assert.equal((result as { content: Array<{ text: string }> }).content[0]?.text, 'Created playground "Demo".');
+ const payload = emitted.find((entry) => entry.type === "tool_result" && entry.payload.tool === "miniapp")?.payload;
+ assert.deepEqual(payload?.display?.artifact, {
+ kind: "playground",
+ artifactId: "playground-1",
+ title: "Demo",
+ });
+});
+
+test("miniapp is offered only on the web surface", () => {
+ assert.equal(
+ createPiTools({ current: fakeToolContext() }).some((tool) => tool.name === "miniapp"),
+ false,
+ );
+ assert.equal(
+ createPiTools({ current: fakeToolContext() }, { surfaceName: "web" }).some((tool) => tool.name === "miniapp"),
+ true,
+ );
+});
+
test("each pi tool emits a tool_call then a tool_result", async () => {
const emitted: Emitted[] = [];
const ref: ToolContextRef = {
@@ -537,27 +564,6 @@ test("the screen never rewrites a policy notice — an approval gate stays legib
assert.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(),
@@ -1043,11 +1049,11 @@ test("readOnly assembles ONLY observational tools — no execute/background/writ
const 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", "miniapp", "cron", "webhook", "guidance"]) {
+ for (const t of ["execute", "background", "read", "write", "publish", "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", "miniapp", "cron", "webhook", "guidance"]) {
+ for (const t of ["execute", "background", "read", "write", "publish", "cron", "webhook", "guidance"]) {
assert.ok(!names(readOnly).has(t), `read-only toolset drops ${t}`);
}
});
@@ -1189,10 +1195,7 @@ test("tool entries carry the call id + faithful model-facing result (WAL replay
},
scopeLabel: "personal:U1",
};
- 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")!;
+ const [execute, read, , , memory] = createPiTools(ref);
await callWith(execute, "call-exec", { command: "echo hi" });
await callWith(read, "call-read", { path: "a.txt" });
diff --git a/test/playground.test.ts b/test/playground.test.ts
new file mode 100644
index 000000000..871afa326
--- /dev/null
+++ b/test/playground.test.ts
@@ -0,0 +1,38 @@
+import { test } from "node:test";
+import assert from "node:assert/strict";
+import { createMemoryDurableByteStore } from "../src/files/durable-byte-store.ts";
+import { createMemoryFileArtifactStore } from "../src/files/file-artifact-store.ts";
+import {
+ createPlaygroundArtifact,
+ normalizePlaygroundTitle,
+ validatePlaygroundHtml,
+} from "../src/playgrounds/playground.ts";
+
+const HTML = "<!doctype html><button id='go'>Go</button><script>go.onclick=()=>go.textContent='Done'</script>";
+
+test("playgrounds are stored unchanged as ordinary scoped file artifacts", async () => {
+ const store = createMemoryFileArtifactStore(createMemoryDurableByteStore());
+ const result = await createPlaygroundArtifact(store, {
+ title: " Tiny demo ",
+ html: HTML,
+ ownerScopeId: "personal:alice",
+ createdBy: "alice",
+ });
+
+ assert.equal(result.kind, "playground");
+ assert.equal(result.title, "Tiny demo");
+ const opened = await store.open(result.artifactId);
+ assert.equal(opened?.artifact.mimetype, "text/html");
+ assert.equal(opened?.artifact.ownerScopeId, "personal:alice");
+ assert.equal(await opened?.stream.toArray().then((chunks) => Buffer.concat(chunks).toString()), HTML);
+});
+
+test("validation enforces storage limits without parsing or rewriting HTML", () => {
+ assert.throws(() => validatePlaygroundHtml(" "), /empty/);
+ assert.doesNotThrow(() => validatePlaygroundHtml("<script>document.body.append('ready')</script>"));
+ assert.equal(normalizePlaygroundTitle(" "), "Playground");
+ // The 80-char cut lands mid-emoji here; it must not leave a lone surrogate behind,
+ // because the title is persisted as JSON.
+ const clipped = normalizePlaygroundTitle(`${"a".repeat(78)}\u{1F680}tail`);
+ assert.equal(clipped, `${"a".repeat(78)}…`);
+});
diff --git a/test/route-auth-conformance.test.ts b/test/route-auth-conformance.test.ts
index 82358b298..fb486e4e0 100644
--- a/test/route-auth-conformance.test.ts
+++ b/test/route-auth-conformance.test.ts
@@ -69,7 +69,6 @@ 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.ts
index 42c076722..c67b8f570 100644
--- a/test/skill-conformance.test.ts
+++ b/test/skill-conformance.test.ts
@@ -21,13 +21,3 @@ 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/);
-});