Multiplayer agent harness for work.
fix: clean up playground delivery and checks
Joshua France657c00b9f080
diff --git a/plugins/web-ui/src/chat.ts b/plugins/web-ui/src/chat.tsindex 11d40462f..6af2f181c 100644--- a/plugins/web-ui/src/chat.ts+++ b/plugins/web-ui/src/chat.ts@@ -160,7 +160,10 @@ function noteMiniappBoot(path: string, boot: { ok: boolean; error?: string }): vwindow.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 } : {}) });+ noteMiniappBoot(data.path, {+ ok: Boolean(data.ok),+ ...(typeof data.error === "string" && data.error ? { error: data.error } : {}),+ });});function armMiniappBoot(src: string): void {@@ -1542,7 +1545,19 @@ export function createChatSurface(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>`;+ return html`<pre class="miniapp-source" tabindex="0">+${unsafeHTML(hljs.highlight(formatted, { language: "html" }).value)}</pre>`;+ }++ function miniappBootState(+ pane: "play" | "code",+ boot: { ok: boolean; error?: string } | undefined,+ ): TemplateResult | typeof nothing {+ if (pane !== "play") return nothing;+ if (!boot) return html`<div class="miniapp-boot" role="status">Starting…</div>`;+ if (!boot.ok)+ return html`<div class="miniapp-boot err" role="alert">${boot.error || "Playground hit an error."}</div>`;+ return nothing;}function miniappCard(app: MiniappEmbed): TemplateResult {@@ -1595,14 +1610,7 @@ export function createChatSurface(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}+ ${miniappBootState(pane, boot)} ${pane === "code" ? miniappSourceView(source) : nothing}</div></div>`;}diff --git a/plugins/web-ui/src/miniapp.ts b/plugins/web-ui/src/miniapp.tsindex ac293c093..604acf505 100644--- a/plugins/web-ui/src/miniapp.ts+++ b/plugins/web-ui/src/miniapp.ts@@ -73,7 +73,22 @@ 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"]);+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[] = [];diff --git a/plugins/web-ui/test/miniapp.test.ts b/plugins/web-ui/test/miniapp.test.tsindex eebfcb86d..275a18d26 100644--- a/plugins/web-ui/test/miniapp.test.ts+++ b/plugins/web-ui/test/miniapp.test.ts@@ -16,10 +16,7 @@ test("miniappsIn pulls title and url and stripMiniappDirectives removes the markassert.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]]"),- "",- );+ assert.equal(stripMiniappDirectives("[[miniapp: sandbox:/mnt/user-data/outputs/x.html | Blocks]]"), "");});test("parseMiniappUrl rejects non-miniapp urls", () => {diff --git a/src/miniapps/miniapp.ts b/src/miniapps/miniapp.tsindex 176a3219f..0a86b6130 100644--- a/src/miniapps/miniapp.ts+++ b/src/miniapps/miniapp.ts@@ -9,7 +9,7 @@ function escapeHtml(s: string): string {}export const MAX_MINIAPP_HTML_BYTES = 512_000;-export const MINIAPP_TITLE_MAX = 80;+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 *";@@ -50,8 +50,7 @@ const SKIN_RULES ="*{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>`;+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;@@ -69,7 +68,9 @@ export function skinMiniappHtml(html: string, theme?: MiniappTheme): string {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}`;+ 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}`;}@@ -96,7 +97,7 @@ export function assertMiniappOk(html: string): void {try {new Function(code);} catch (e) {- throw new Error(`miniapp script does not parse: ${errMessage(e)}`);+ throw new Error(`miniapp script does not parse: ${errMessage(e)}`, { cause: e });}}}@@ -138,17 +139,17 @@ export function documentHtml(title: string, html: string): string {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 {+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 {+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 {+function miniappDirective(url: string, title: string): string {return `[[miniapp: ${url} | ${title}]]`;}diff --git a/src/slack/lib.ts b/src/slack/lib.tsindex 76d7958d2..ea3ad3626 100644--- a/src/slack/lib.ts+++ b/src/slack/lib.ts@@ -80,13 +80,7 @@ export {extractAgentRequests,stripAgentRequestDirectives,} from "./agent-requests.ts";-export {- extractMiniapps,- miniappActionBlocks,- parseMiniappUrl,- stripMiniappDirectives,- type MiniappEmbed,-} from "./miniapps.ts";+export { extractMiniapps, parseMiniappUrl, stripMiniappDirectives, type MiniappEmbed } from "./miniapps.ts";export {encodeTs,decodeTs,diff --git a/src/slack/messaging.ts b/src/slack/messaging.tsindex 975eb8ce4..b03fa68d4 100644--- a/src/slack/messaging.ts+++ b/src/slack/messaging.ts@@ -13,7 +13,6 @@ import {stripAgentRequestDirectives,stripMiniappDirectives,stripReactionDirectives,- type MiniappEmbed,} from "./lib.ts";export type SlackConversationKind = "dm" | "channel" | "group";@@ -59,16 +58,15 @@ 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);+ const miniappLinks = extractedMiniapps.miniapps.map(({ title, url }) => `${title}: ${url}`).join("\n");return {- text: extractedMiniapps.text,+ text: [extractedMiniapps.text, miniappLinks].filter(Boolean).join("\n"),reactions: extractedReactions.reactions,agentRequests: extractedRequests.requests,- miniapps: extractedMiniapps.miniapps,};}diff --git a/src/slack/miniapps.ts b/src/slack/miniapps.tsindex 8cb8ca355..63af01293 100644--- a/src/slack/miniapps.ts+++ b/src/slack/miniapps.ts@@ -1,5 +1,4 @@import { extractDirectives } from "./directives.ts";-import { clip } from "./util.ts";export interface MiniappEmbed {url: string;@@ -8,7 +7,6 @@ export interface MiniappEmbed {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 {@@ -57,17 +55,3 @@ 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/test/miniapp.test.ts b/test/miniapp.test.tsindex 3dd56b6d3..a7180eb79 100644--- a/test/miniapp.test.ts+++ b/test/miniapp.test.ts@@ -15,7 +15,7 @@ import {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 { extractMiniapps, parseMiniappUrl } from "../src/slack/lib.ts";import { cleanAgentReplyForSlack, slackSurfaceInstructions } from "../src/slack/messaging.ts";const SECRET = "miniapp-test-secret-value-32chars!!";@@ -33,12 +33,21 @@ test("skinMiniappHtml injects host tokens and follows the requested theme", () =});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.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>"),+ () => 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/,);});@@ -72,19 +81,9 @@ test("extractMiniapps strips the directive and keeps a valid url", () => {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", () => {+test("cleanAgentReplyForSlack replaces miniapp markers with durable links", () => {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.equal(cleaned.text, "Try this\nBlocks: https://qm.test/m/aa/bb");assert.doesNotMatch(slackSurfaceInstructions("dm"), /\[\[miniapp:/);});diff --git a/test/pi-tools.test.ts b/test/pi-tools.test.tsindex 2e8bf5bec..a29b81924 100644--- a/test/pi-tools.test.ts+++ b/test/pi-tools.test.ts@@ -552,10 +552,16 @@ test("miniapp and publish results are first-party and never quarantined", asyncconst 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);+ 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);+ 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 () => {