Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Pages, apps and widgets in rooms, view-only (#4612)
Milind Soni65c67319d6f0
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 6456f93e65..6eb34d57da 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -579,7 +579,7 @@ jobs:env:OMB_UI_E2E: "1"OMB_UI_EVIDENCE_DIR: .omb-scratch/verify-evidence- run: pnpm exec vitest run scripts/testing/control-omb-ui.e2e.test.ts scripts/testing/bot-tools-ui.e2e.test.ts scripts/testing/thinking-timer-ui.e2e.test.ts scripts/testing/team-share-ui.e2e.test.ts scripts/testing/org-library-ui.e2e.test.ts scripts/testing/presets-ui.e2e.test.ts scripts/testing/browser-evidence.e2e.test.ts scripts/testing/browser-fill.e2e.test.ts scripts/testing/rich-table-composer-ui.e2e.test.ts scripts/testing/computer-panel-focus-ui.e2e.test.ts scripts/testing/mobile-code-blocks-ui.e2e.test.ts scripts/testing/inline-page-height-ui.e2e.test.ts+ run: pnpm exec vitest run scripts/testing/control-omb-ui.e2e.test.ts scripts/testing/bot-tools-ui.e2e.test.ts scripts/testing/thinking-timer-ui.e2e.test.ts scripts/testing/team-share-ui.e2e.test.ts scripts/testing/org-library-ui.e2e.test.ts scripts/testing/presets-ui.e2e.test.ts scripts/testing/browser-evidence.e2e.test.ts scripts/testing/browser-fill.e2e.test.ts scripts/testing/rich-table-composer-ui.e2e.test.ts scripts/testing/computer-panel-focus-ui.e2e.test.ts scripts/testing/mobile-code-blocks-ui.e2e.test.ts scripts/testing/inline-page-height-ui.e2e.test.ts scripts/testing/room-pages-ui.e2e.test.ts- name: Upload the renderer screenshotuses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1if: always()@@ -591,6 +591,7 @@ jobs:.omb-scratch/verify-evidence/share-team-dialog.png.omb-scratch/verify-evidence/mobile-code-blocks/.omb-scratch/verify-evidence/inline-page-height/+ .omb-scratch/verify-evidence/room-pages-*.pngif-no-files-found: warnretention-days: 7diff --git a/docs/verification/README.md b/docs/verification/README.mdindex ba892ddb2f..097db7f76c 100644--- a/docs/verification/README.md+++ b/docs/verification/README.md@@ -70,6 +70,7 @@ Use only mapped, tested commands:- [Waits: tell me when, with no AI while waiting](waits.md)- [A new Cloud's first hour](first-hour.md)- [Chat widgets](widgets.md)+- [Pages and apps in a room](room-pages.md)- [The Inbox on every plan](inbox.md)- [Reactions](reactions.md)- [Chat widgets: prompts to try with a real bot](widget-prompts.md)diff --git a/docs/verification/evidence/room-pages/clicked-app.png b/docs/verification/evidence/room-pages/clicked-app.pngnew file mode 100644index 0000000000..9065f6426aBinary files /dev/null and b/docs/verification/evidence/room-pages/clicked-app.png differdiff --git a/docs/verification/evidence/room-pages/clicked-send.png b/docs/verification/evidence/room-pages/clicked-send.pngnew file mode 100644index 0000000000..8f373abd7eBinary files /dev/null and b/docs/verification/evidence/room-pages/clicked-send.png differdiff --git a/docs/verification/evidence/room-pages/shown.png b/docs/verification/evidence/room-pages/shown.pngnew file mode 100644index 0000000000..c8ecf1abf8Binary files /dev/null and b/docs/verification/evidence/room-pages/shown.png differdiff --git a/docs/verification/room-pages.md b/docs/verification/room-pages.mdnew file mode 100644index 0000000000..0db0291fe5--- /dev/null+++ b/docs/verification/room-pages.md@@ -0,0 +1,53 @@+# Pages and apps in a room++A bot in a room can show a page (`show_html`), a widget (`show_widget`), an MCP server's app or a published page's+card there, and everyone who can see the room sees it, view-only. Inside a room's frame, `mausbot.room` is `true`,+and `mausbot.send` and `mausbot.setContext` resolve without doing anything; the host refuses `ui/message`,+`ui/update-model-context` and an MCP app's calls to its server; and the server refuses an app's message, its context,+its server calls and a widget press for a room's thread.++## Renderer and server, end to end++```sh+pnpm exec vitest run scripts/testing/room-pages-ui.e2e.test.ts+```++It runs when an agent-browser binary resolves, as in [Chat UI, driven headlessly](chat-ui.md), and is skipped+otherwise; `OMB_UI_E2E=1` forces the verified download. The launcher's fixture runs the fake engine in `slow` mode,+with the fake MCP app server (`server/testing/fake-stdio-app-server.ts`) added as the `board` server. Pepper and Basil+share a room whose lead is Pepper.++- A message typed in the room opens Pepper's room turn, and with that turn's token the page goes to+ `/api/internal/options-card` as `show_html`: the row is Pepper's (`from`).+- `@Basil show the board` opens Basil's room turn with the `board` server behind its gate; a `show_board` call through+ that gate reports the app, and its row is Basil's.+- `GET /api/threads/<room>/messages/<id>/app` answers both with `room: true` and `can` with `message`,+ `modelContext`, `serverTools` and `serverResources` off.+- Both rows are live in the room, the page with Full screen but without Point or Share.+- A real mouse click on the page's send button makes the page report that `send()` resolved (it grows to 300px; a+ refusal would leave it at 240px), and a click on the board's "Paint it red" is answered by the host with the room's+ refusal. The renderer makes no request but GETs meanwhile, the room gains no message and no app row gains context,+ and a direct `POST /api/bots/<id>/messages` with the page's `appMessage` is refused with 409.++Evidence (with `OMB_UI_EVIDENCE_DIR`): `room-pages-shown.png`, `room-pages-clicked-send.png`,+`room-pages-clicked-app.png` and `room-pages.json` (the rows, the page document's head, the requests and the console).++What it looks like when the recipe passes: both rows in the room, the page without Point or Share+(`evidence/room-pages/shown.png`); the page after a real click on its send button, which resolved and posted nothing+(`evidence/room-pages/clicked-send.png`); and the board after a click on "Paint it red", answered by the host with the+room's refusal (`evidence/room-pages/clicked-app.png`).++++++++## Who may load a room's page++```sh+pnpm exec vitest run server/routes/chat-apps.test.ts server/page-files.test.ts server/routes/bot-messages-apps.test.ts+```++The document route answers 404 to a person who cannot see the room. A folder page's files load with that person's own+token, which answers only while they can still see the room and the page is still in it.diff --git a/scripts/testing/room-pages-ui.e2e.test.ts b/scripts/testing/room-pages-ui.e2e.test.tsnew file mode 100644index 0000000000..8cdd9505dc--- /dev/null+++ b/scripts/testing/room-pages-ui.e2e.test.ts@@ -0,0 +1,220 @@+// A page and an MCP app shown in a room: two members' real room turns put them there through the internal card route+// and the MCP gate, and the real renderer shows both to the room, view-only. A real mouse click on the page's send+// button and on the app's server button posts nothing. Needs the pinned agent-browser binary: runs when one resolves+// (tools directory, OMB_AGENT_BROWSER_PATH or PATH) or OMB_UI_E2E=1 asks for the verified download; otherwise skipped.+import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join, resolve } from "node:path";+import { createInterface } from "node:readline";+import { fileURLToPath } from "node:url";+import { afterAll, expect, it } from "vitest";++import { ROOM_VIEW_ONLY } from "../../shared/app.ts";+import { resolveAgentBrowserBinary } from "../../server/browser-engine.ts";+import { removeTempDir, waitForExit } from "../../server/testing/cleanup.ts";+import { runControlOmb } from "../control-omb.ts";+import { agentBrowser, sessionEnv, UI_TOOLS_DIR, type UiHandle } from "./control-omb-ui.ts";+import { fixtureApi } from "./preview-fixture.ts";++const ROOT = fileURLToPath(new URL("../..", import.meta.url));+const FAKE_APP = join(ROOT, "server", "testing", "fake-stdio-app-server.ts");+const forced = process.env.OMB_UI_E2E === "1";+const enabled = forced || Boolean(resolveAgentBrowserBinary({ dataDir: UI_TOOLS_DIR, env: process.env }));+if (!enabled) console.log("skipping room pages ui e2e: no agent-browser binary resolves; set OMB_UI_E2E=1 to install the pinned release");+const LAUNCH_TIMEOUT_MS = forced ? 600_000 : 180_000;++const evidenceDir = process.env.OMB_UI_EVIDENCE_DIR ? resolve(ROOT, process.env.OMB_UI_EVIDENCE_DIR) : mkdtempSync(join(tmpdir(), "omb-ui-evidence-"));+afterAll(async () => { if (!process.env.OMB_UI_EVIDENCE_DIR) await removeTempDir(evidenceDir); });++/** The send button sits at a fixed place in the page, so a real mouse can find it inside the frame. What send() did+ * shows in the page and in its height, which the host's frame follows: 300px when it resolved, 240px when refused. */+const PAGE = `<!DOCTYPE html><html><head><meta charset="utf-8"><style>+body{margin:0;font:15px/1.4 var(--font-sans);color:var(--color-text-primary)}+#mode{position:absolute;left:16px;top:12px;margin:0}+#send{position:absolute;left:16px;top:48px;width:260px;height:44px;font:inherit;cursor:pointer}+#out{position:absolute;left:16px;top:104px;margin:0;font-weight:600}+</style></head><body><p id="mode"></p><button id="send">Send "3 cups" to the bot</button><p id="out">Not clicked yet</p>+<div id="room" style="height:160px"></div><script>+document.getElementById("mode").textContent = "mausbot.room is " + window.mausbot.room + ": this page is view-only here";+document.getElementById("send").onclick = function () {+ window.mausbot.setContext("3 cups on screen");+ window.mausbot.send("I have had 3 cups").then(function () {+ document.getElementById("out").textContent = "Clicked: send() resolved and posted nothing";+ document.getElementById("room").style.height = "300px";+ }, function (error) {+ document.getElementById("out").textContent = "Clicked: send() refused: " + error.message;+ document.getElementById("room").style.height = "240px";+ });+};+</script></body></html>`;++async function launch(env: NodeJS.ProcessEnv): Promise<{ child: ReturnType<typeof spawn>; info: { ui: string; url: string; botId: string; dataDir: string; logPath: string } }> {+ const child = spawn(process.execPath, ["--experimental-strip-types", join(ROOT, "scripts", "control-omb.ts"), "ui", "launch", "--mode", "slow"], {+ cwd: ROOT, env, stdio: ["ignore", "pipe", "pipe"], detached: process.platform !== "win32",+ });+ let stdout = "", stderr = "";+ child.stdout!.on("data", (chunk) => { stdout += String(chunk); });+ child.stderr!.on("data", (chunk) => { stderr += String(chunk); });+ const deadline = Date.now() + LAUNCH_TIMEOUT_MS;+ for (;;) {+ if (child.exitCode !== null) throw new Error(`ui launch exited ${child.exitCode}: ${stderr}`);+ const start = stdout.indexOf("{");+ if (start !== -1) {+ try { return { child, info: JSON.parse(stdout.slice(start)) }; } catch { /* not all of it yet */ }+ }+ if (Date.now() > deadline) throw new Error(`ui launch printed no handle: ${stderr}`);+ await new Promise((done) => setTimeout(done, 250));+ }+}++async function until<T>(probe: () => Promise<T> | T, what: string, timeoutMs = 30_000): Promise<NonNullable<T>> {+ const deadline = Date.now() + timeoutMs;+ for (;;) {+ const value = await probe();+ if (value) return value as NonNullable<T>;+ if (Date.now() > deadline) throw new Error(`${what} did not happen within ${timeoutMs}ms`);+ await new Promise((done) => setTimeout(done, 250));+ }+}++(enabled ? it : it.skip)("shows a member's page and another member's MCP app to the room, and a click in either posts nothing", async () => {+ const scratch = mkdtempSync(join(tmpdir(), "omb-room-pages-"));+ const gate = join(scratch, "finish");+ const { child, info } = await launch({ ...process.env, FAKE_CLAUDE_SLOW_FINISH_GATE: gate, FAKE_CLAUDE_VERSION: "2.1.270" });+ let engineSide: ChildProcessWithoutNullStreams | undefined;+ try {+ const api = fixtureApi(info.url, { headers: { origin: info.url } });+ const ui = (verb: string, ...args: string[]) => runControlOmb(["ui", verb, "--ui", info.ui, ...args]) as Promise<Record<string, any>>;+ const evaluate = async (js: string) => (await ui("eval", "--js", js)).result;+ const browser = JSON.parse(readFileSync(info.ui, "utf8")) as UiHandle;+ const mouse = (...args: string[]) => agentBrowser(browser.binary, sessionEnv(browser), ["mouse", ...args]);+ /** The accessibility tree reaches into the frames: what a page or an app shows is readable here. */+ const shows = async (text: string) => JSON.stringify(await ui("snapshot")).includes(JSON.stringify(text).slice(1, -1));+ await agentBrowser(browser.binary, sessionEnv(browser), ["set", "viewport", "1280", "1000"]);+ const dump = () => { try { return JSON.parse(readFileSync(join(info.dataDir, "fake-claude-dump.json"), "utf8")); } catch { return null; } };+ const card = async (token: string, body: unknown) => {+ const response = await fetch(`${info.url}/api/internal/options-card`, { method: "POST", headers: { "content-type": "application/json", authorization: `Bearer ${token}` }, body: JSON.stringify(body) });+ return { status: response.status, body: await response.json() as Record<string, any> };+ };++ await api("POST", "/api/mcp/servers", { name: "board", command: process.execPath, args: ["--experimental-strip-types", "--no-warnings", FAKE_APP] });+ await api("PATCH", "/api/mcp/servers/board", { enabled: true });+ expect(await api("POST", "/api/mcp/servers/board/test")).toMatchObject({ ok: true });+ const basil = (await api("POST", "/api/bots", { name: "Basil" })).bot;+ const room = (await api("POST", "/api/groups", {+ memberIds: [info.botId, basil.id], name: "Launch room", setup: { bulletin: "", defaultResponder: { kind: "member", botId: info.botId } },+ })).group;+ const transcript = async (): Promise<any[]> => (await api("GET", `/api/threads/${room.threadId}/messages`)).messages;+ const roomTurn = (botId: string) => until(() => {+ const env = dump()?.mcpConfig?.mcpServers?.agents?.env;+ return env?.OMB_BOT_ID === botId && env?.OMB_THREAD_ID === room.threadId ? { token: env.OMB_COMMS_TOKEN as string, mounts: dump().mcpConfig.mcpServers } : null;+ }, `${botId}'s room turn`, 60_000);+ const settled = async () => {+ writeFileSync(gate, "finish");+ await until(async () => !(await api("GET", "/api/bots?messages=0")).bots.some((bot: any) => bot.busy), "the room's turns to end", 60_000);+ rmSync(gate, { force: true });+ };++ const row = `[data-sidebar-group-row="${room.id}"]`;+ await until(() => evaluate(`Boolean(document.querySelector('${row}'))`), "the room's sidebar row");+ await evaluate(`document.querySelector('${row}').click(); true`);+ await until(() => evaluate(`Boolean(document.querySelector('${row}[aria-current="page"]'))`), "the room to open");++ // Pepper answers the room and shows a page there through the same internal route show_html uses.+ await ui("type", "--name", "Message Launch room", "--text", "Pepper, show us the coffee counter");+ await ui("press", "--keys", "Enter");+ const pepper = await roomTurn(info.botId);+ const shown = await card(pepper.token, { tool: "show_html", html: PAGE, title: "Coffee counter", height: 180 });+ expect(shown, JSON.stringify(shown.body)).toMatchObject({ status: 201, body: { messageId: expect.any(String) } });+ const pageId = shown.body.messageId as string;+ await settled();++ // Basil's room turn calls an MCP tool with a UI; the gate the engine runs it through reports it to the room.+ await api("POST", `/api/groups/${room.id}/messages`, { text: "@Basil show the board", mentions: [basil.id], sendId: "room-pages-ui-send-0001" });+ const basilTurn = await roomTurn(basil.id);+ expect(basilTurn.mounts.board).toBeTruthy();+ engineSide = spawn(basilTurn.mounts.board.command, ["--experimental-strip-types", "--no-warnings", ...basilTurn.mounts.board.args],+ { stdio: "pipe", env: { ...process.env, ...basilTurn.mounts.board.env } });+ const lines = createInterface({ input: engineSide.stdout })[Symbol.asyncIterator]();+ const ask = async (id: number, method: string, params?: unknown) => {+ engineSide!.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, ...(params ? { params } : {}) })}\n`);+ return JSON.parse((await lines.next()).value as string);+ };+ await ask(1, "initialize", { protocolVersion: "2025-11-25", capabilities: {}, clientInfo: { name: "claude-code", version: "2.1.270" } });+ await ask(2, "tools/list");+ expect((await ask(3, "tools/call", { name: "show_board", arguments: { cards: 4 } })).result.content[0].text).toBe("Board with 4 cards");+ const boardRow = await until(async () => (await transcript()).find((message) => message.kind === "app" && message.app?.source === "mcp"), "the board's row");+ await settled();++ const rows = (await transcript()).filter((message) => message.kind === "app");+ expect(rows.map((message) => [message.id, message.from?.botId])).toEqual([[pageId, info.botId], [boardRow.id, basil.id]]);+ const pageDoc = await api("GET", `/api/threads/${room.threadId}/messages/${pageId}/app`);+ expect(pageDoc).toMatchObject({ room: true, can: { message: false, modelContext: false, serverTools: false, openLinks: true } });+ expect(await api("GET", `/api/threads/${room.threadId}/messages/${boardRow.id}/app`)).toMatchObject({ room: true, can: { serverTools: false, serverResources: false, message: false } });++ // Both rows render in the room for the person, view-only: no Point and no Share on the page.+ const live = (id: string) => `[data-app="${id}"][data-app-room][data-app-state="live"] iframe[data-app-frame]`;+ await until(() => evaluate(`Boolean(document.querySelector('${live(pageId)}') && document.querySelector('${live(boardRow.id)}'))`), "both frames to go live", 30_000);+ expect(await evaluate(`[...document.querySelectorAll('[data-app="${pageId}"] button')].map((b) => b.textContent.trim()).filter((t) => t === "Point" || t === "Share")`)).toEqual([]);+ expect(await evaluate(`Boolean([...document.querySelectorAll('[data-app="${pageId}"] button')].find((b) => b.getAttribute("aria-label") === "Full screen"))`)).toBe(true);+ mkdirSync(evidenceDir, { recursive: true });++ // Every request the renderer makes goes through fetch: from here on each one is kept.+ await evaluate(`(() => { window.__requests = []; const original = window.fetch; window.fetch = (input, init) => {+ window.__requests.push([String(input instanceof Request ? input.url : input), (init && init.method) || "GET"]); return original(input, init); }; return true; })()`);+ const frameBox = async (id: string): Promise<{ left: number; top: number; height: number; viewport: number }> => evaluate(`(() => {+ const r = document.querySelector('[data-app="${id}"] iframe').getBoundingClientRect(); return { left: r.left, top: r.top, height: r.height, viewport: innerHeight }; })()`);+ const inView = (id: string) => until(async () => {+ await evaluate(`document.querySelector('[data-app="${id}"]').scrollIntoView({ block: "center" }); true`);+ await new Promise((done) => setTimeout(done, 400));+ const box = await frameBox(id);+ return box.top >= 0 && box.top + 150 <= box.viewport ? box : null;+ }, `the frame of ${id} to be in view`);+ /** A real mouse press and release at a point inside the frame. */+ const click = async (box: { left: number; top: number }, x: number, y: number) => {+ await mouse("move", String(Math.round(box.left + x)), String(Math.round(box.top + y)));+ await mouse("down");+ await mouse("up");+ };++ const sentBefore = (await transcript()).filter((message) => message.role === "user").length;+ const page = await inView(pageId);+ await ui("screenshot", "--out", join(evidenceDir, "room-pages-shown.png"));+ await click(page, 146, 70);+ // 300px: send() resolved in the page without asking the host; a refusal would leave it at 240px.+ await until(async () => (await frameBox(pageId)).height === 300, "the page to show what its send did");+ expect(await shows("Clicked: send() resolved and posted nothing")).toBe(true);+ await inView(pageId);+ await ui("screenshot", "--out", join(evidenceDir, "room-pages-clicked-send.png"));++ const board = await inView(boardRow.id);+ // The board's "Paint it red" button: under its heading and its result line, in the browser's default styles.+ await click(board, 48, 124);+ await until(() => shows(`Error -32000: ${ROOM_VIEW_ONLY}`), "the board to show the host's refusal");+ await inView(boardRow.id);+ await ui("screenshot", "--out", join(evidenceDir, "room-pages-clicked-app.png"));++ await evaluate(`fetch("/api/health").catch(() => {}); true`);+ const requests = await until(async () => {+ const seen = await evaluate("window.__requests") as Array<[string, string]>;+ return seen.some(([url]) => url.endsWith("/api/health")) ? seen : null;+ }, "the request recorder to see its own check");+ expect(requests.filter(([, method]) => method !== "GET")).toEqual([]);+ const after = await transcript();+ expect(after.filter((message) => message.role === "user")).toHaveLength(sentBefore);+ expect(after.filter((message) => message.kind === "app").map((message) => message.app?.context)).toEqual([undefined, undefined]);+ // The server refuses the same calls a page or a client could make on its own.+ const refused = await fetch(`${info.url}/api/bots/${info.botId}/messages`, { method: "POST", headers: { "content-type": "application/json", origin: info.url },+ body: JSON.stringify({ threadId: room.threadId, sendId: "room-pages-ui-send-0002", appMessage: { messageId: pageId, text: "I have had 3 cups" } }) });+ expect({ status: refused.status, body: await refused.json() }).toEqual({ status: 409, body: { error: ROOM_VIEW_ONLY } });+ const logs = await ui("console");+ writeFileSync(join(evidenceDir, "room-pages.json"), JSON.stringify({ room, rows, pageDoc: { ...pageDoc, srcdoc: `${String(pageDoc.srcdoc).slice(0, 200)}…` }, requests, console: logs }, null, 2));+ expect((logs.messages as Array<{ type: string; text: string }>).filter((message) => message.type === "error")).toEqual([]);+ } finally {+ if (engineSide && engineSide.exitCode === null) await waitForExit(engineSide, { signal: "SIGTERM", graceMs: 5_000 });+ await waitForExit(child, { signal: "SIGINT", graceMs: 30_000 });+ expect(existsSync(info.dataDir)).toBe(false);+ await removeTempDir(scratch);+ }+}, LAUNCH_TIMEOUT_MS + 240_000);diff --git a/server/chat-apps-mcp.test.ts b/server/chat-apps-mcp.test.tsindex a318864c28..27f86b3b8a 100644--- a/server/chat-apps-mcp.test.ts+++ b/server/chat-apps-mcp.test.ts@@ -122,9 +122,18 @@ describe("recordMcpAppCall", () => {bot: { id: bot.id, name: bot.name, color: "blue" }, threadId: THREAD, input: { tool: "mcp_app" } })).toEqual({ ok: false, status: 400, error: "MCP apps are not available on this computer." });}, 30_000);- it("writes no row for a room, an unmounted server, one outside the bot's scope, or one whose apps are off (rule 17)", async () => {+ it("shows a room member's app in the room as that bot's row, view-only for everyone", async () => {+ const { record, row, apps } = setup();+ expect(await record(REPORT, ROOM)).toEqual({ ok: true, messageId: "m1" });+ expect(row("m1", ROOM)).toMatchObject({ role: "bot", kind: "app", from: { botId: "bot-scout", name: "Scout", color: "blue" }, app: { source: "mcp", title: "Show board" } });+ const doc = apps.appDocument(ROOM, "m1")!;+ expect(doc.srcdoc).toContain("<h1>Fake board</h1>");+ expect(doc).toMatchObject({ room: true, toolResult: REPORT.result, can: { serverTools: false, serverResources: false, message: false, modelContext: false, openLinks: true } });+ expect(doc).not.toHaveProperty("blocked");+ }, 30_000);++ it("writes no row for an unmounted server, one outside the bot's scope, or one whose apps are off (rule 17)", async () => {const base = setup();- expect(await base.record(REPORT, ROOM)).toMatchObject({ ok: false, status: 409 });expect(await base.record({ ...REPORT, server: "elsewhere" })).toMatchObject({ ok: false, status: 404 });expect(await base.record({ ...REPORT, definition: { ...REPORT.definition, _meta: {} } })).toMatchObject({ ok: false, status: 400 });expect(await base.record({ ...REPORT, result: { content: "x" } })).toMatchObject({ ok: false, status: 400 });diff --git a/server/chat-apps-mcp.ts b/server/chat-apps-mcp.tsindex 4b9a4d92a3..272d72e93b 100644--- a/server/chat-apps-mcp.ts+++ b/server/chat-apps-mcp.ts@@ -3,7 +3,7 @@ import { APP_LIMITS, APP_MIME, appBlockedText, appDoneOf, mcpAppFallbackText, onimport { mcpAppNetwork } from "../shared/app-frame/csp.ts";import { allowsTool, canUseMcpServer } from "../shared/tool-scope.ts";import { appRow, rowRate, type ChatApps } from "./chat-apps.ts";-import type { AgentCardResult } from "./chat-widgets.ts";+import { speakerIn, type AgentCardResult } from "./chat-widgets.ts";import type { McpServerSpec } from "./contracts.ts";import { McpAppCatalog, mcpServerConfigHash } from "./mcp-app-catalog.ts";import { AppConnections } from "./mcp-app-connections.ts";@@ -170,9 +170,8 @@ export function createChatAppsMcp(deps: ChatAppsMcpDeps): ChatAppsMcp {async function recordMcpAppCall(args: McpAppCallArgs): Promise<AgentCardResult> {const { threadId, input } = args;- // No row for a room, an unmounted server, one outside the bot's scope or one whose apps are off; the- // observer reads nothing back.- if (store.groupByThread(threadId)) return { ok: false, status: 409, error: "Apps are not shown in rooms yet." };+ // No row for an unmounted server, one outside the bot's scope or one whose apps are off; the observer reads nothing+ // back.const bot = store.bot(args.bot.id);if (!bot) return { ok: false, status: 404, error: "No such bot." };const name = input.server;@@ -230,7 +229,7 @@ export function createChatAppsMcp(deps: ChatAppsMcpDeps): ChatAppsMcp {payload = { v: 1, source: "mcp", title: toolTitle, doc: "", rev: 0, bytes: 0, border: true, network: { connect: [], resources: [] }, mcp: ref, blocked: read.reason };}const message = store.appendMessage(threadId, {- role: "bot", kind: "app", text: redactSecretsInText(mcpAppFallbackText(serverTitle, toolTitle, toolResult)), app: payload,+ role: "bot", kind: "app", text: redactSecretsInText(mcpAppFallbackText(serverTitle, toolTitle, toolResult)), app: payload, ...speakerIn(store, threadId, bot),});args.authored?.(message.id);catalog.recordTool(name, server, definition);diff --git a/server/chat-apps.test.ts b/server/chat-apps.test.tsindex 16c8933a9a..2e6cba085d 100644--- a/server/chat-apps.test.ts+++ b/server/chat-apps.test.ts@@ -6,7 +6,7 @@ import { afterEach, describe, expect, it, vi } from "vitest";import { APP_LIMITS, APP_PAGE_VERSIONS, type AppPayload } from "../shared/app.ts";import { BOT_HTML_CSP, BOT_HTML_NETWORK } from "../shared/app-frame/csp.ts";import { CSP_META_PREFIX } from "../shared/app-frame/document.ts";-import { APP_HELPER_SOURCE } from "../shared/app-frame/helper.ts";+import { APP_HELPER_SOURCE, APP_ROOM_HELPER_SOURCE } from "../shared/app-frame/helper.ts";import { AppDocs } from "./app-docs.ts";import {appContextBlock, appDocument, AppMessageRate, createAppCard, createChatApps, pageVersion, prepareAppMessage, publishablePage, rowRate, setAppContext,@@ -86,16 +86,25 @@ describe("show_html", () => {expect(docs.read(row("m1").app!.doc)?.html).toBe("<!DOCTYPE html><html><head><meta charset=\"utf-8\"></head><body><b>hi</b></body></html>");});- it("refuses rooms and input over the limits, and writes nothing", () => {- const { call, rows } = setup(["room-thread"]);- expect(call({ tool: "show_html", html: PAGE, title: "t" }, "room-thread")).toEqual({ ok: false, status: 409, error: "Pages are not available in rooms yet. Answer in text." });+ it("refuses input over the limits, and writes nothing", () => {+ const { call, rows } = setup();expect(call({ tool: "show_html", html: "x".repeat(APP_LIMITS.htmlBytes + 1), title: "t" })).toMatchObject({ ok: false, status: 400, error: expect.stringMatching(/^html:/) });expect(call({ tool: "show_html", html: PAGE, title: "t".repeat(81) })).toMatchObject({ ok: false, status: 400, error: expect.stringMatching(/^title:/) });expect(call({ tool: "show_html", html: PAGE })).toMatchObject({ ok: false, status: 400 });- expect(rows("room-thread")).toEqual([]);expect(rows(THREAD)).toEqual([]);});+ it("shows a page in a room as the bot's own row, which only that bot can replace", () => {+ const { call, row, store, docs } = setup(["room-thread"]);+ expect(call({ tool: "show_html", html: PAGE, title: "Sales" }, "room-thread")).toEqual({ ok: true, messageId: "m1" });+ expect(row("m1", "room-thread")).toMatchObject({ role: "bot", kind: "app", from: { botId: SCOUT.id, name: "Scout", color: "blue" }, app: { source: "html", title: "Sales" } });+ const other = { id: "bot-other", name: "Other", color: "red" as const };+ expect(createAppCard({ store, docs, bot: other, threadId: "room-thread", input: { tool: "update_html", app_id: "m1", html: "<p>mine now</p>" } }))+ .toEqual({ ok: false, status: 404, error: "No page with that id in this conversation." });+ expect(call({ tool: "update_html", app_id: "m1", html: "<p>v2</p>" }, "room-thread")).toEqual({ ok: true, messageId: "m1" });+ expect(row("m1", "room-thread").app).toMatchObject({ rev: 1 });+ });+it("scrubs secrets from the page, the title and the fallback before anything is stored, and says so", () => {const { call, row, docs } = setup();const result = call({ tool: "show_html", html: `<p>key ${API_KEY}</p><script>const t = "${GITHUB_TOKEN}"</script>`, title: `Deploy ${GITHUB_TOKEN}` });@@ -337,7 +346,7 @@ describe("publish_page in the chat", () => {it("shows the published page as its own inline card, with the link", async () => {const { store, docs, row } = setup();const { bundle } = await folder();- const id = showPublishedPage({ store, docs, threadId: THREAD, card: LIVE, bundle: await bundle() });+ const id = showPublishedPage({ store, docs, bot: SCOUT, threadId: THREAD, card: LIVE, bundle: await bundle() });expect(id).toBe("m1");expect(row("m1")).toMatchObject({ kind: "app", text: "[App] Dash\nDash", publishedPage: LIVE, app: { source: "html", title: "Dash", rev: 0 } });expect(docs.readFile(row("m1").app!.doc, "data.csv")?.toString()).toBe("a\n1");@@ -348,12 +357,12 @@ describe("publish_page in the chat", () => {const { base, bundle } = await folder();await createAppCard({ store, docs, bot: SCOUT, threadId: THREAD, input: { tool: "show_html", path: "dash", title: "Dash" }, folders: async () => ({ roots: [base], vmWorkspace: null }) });writeFileSync(join(base, "dash", "data.csv"), "a\n2");- expect(showPublishedPage({ store, docs, threadId: THREAD, card: LIVE, bundle: await bundle() })).toBe("m1");+ expect(showPublishedPage({ store, docs, bot: SCOUT, threadId: THREAD, card: LIVE, bundle: await bundle() })).toBe("m1");expect(rows(THREAD)).toHaveLength(1);expect(row("m1")).toMatchObject({ publishedPage: LIVE, app: { rev: 1 } });expect(row("m1").text).toBe("[App] Dash\nDash");expect(docs.readFile(row("m1").app!.doc, "data.csv")?.toString()).toBe("a\n2");- expect(showPublishedPage({ store, docs, threadId: THREAD, card: { ...LIVE, url: `${LIVE.url}?again` }, bundle: await bundle() })).toBe("m1");+ expect(showPublishedPage({ store, docs, bot: SCOUT, threadId: THREAD, card: { ...LIVE, url: `${LIVE.url}?again` }, bundle: await bundle() })).toBe("m1");expect(row("m1")).toMatchObject({ app: { rev: 1 }, publishedPage: { url: `${LIVE.url}?again` } });});@@ -365,18 +374,31 @@ describe("publish_page in the chat", () => {writeFileSync(join(base, "dash", "index.html"), "<h1>Dash, edited</h1>");const published = await bundle();expect(published.skipped).toEqual([{ path: "clip.webm", why: "video" }]);- expect(showPublishedPage({ store, docs, threadId: THREAD, card: LIVE, bundle: published })).toBe("m1");+ expect(showPublishedPage({ store, docs, bot: SCOUT, threadId: THREAD, card: LIVE, bundle: published })).toBe("m1");expect(row("m1")).toMatchObject({ publishedPage: LIVE, app: { rev: 1 } });expect(docs.read(row("m1").app!.doc)!.html).toBe("<h1>Dash, edited</h1>");expect(docs.video(row("m1").app!.doc, "clip.webm")).toMatchObject({ bytes: 4 });});- it("leaves a room, a limit card and a page with no index.html to the plain link card", async () => {- const { store, docs, rows } = setup(["room-1"]);+ it("shows it in a room too, as the publishing bot's card, and gives the link only to that bot's own card", async () => {+ const { store, docs, row, rows } = setup(["room-1"]);+ const { base, bundle } = await folder();+ const other = { id: "bot-other", name: "Other", color: "red" as const };+ await createAppCard({ store, docs, bot: other, threadId: "room-1", input: { tool: "show_html", path: "dash", title: "Dash" }, folders: async () => ({ roots: [base], vmWorkspace: null }) });+ expect(showPublishedPage({ store, docs, bot: SCOUT, threadId: "room-1", card: LIVE, bundle: await bundle() })).toBe("m2");+ expect(row("m2", "room-1")).toMatchObject({ kind: "app", publishedPage: LIVE, from: { botId: SCOUT.id, name: "Scout", color: "blue" }, app: { rev: 0 } });+ expect(row("m1", "room-1")).not.toHaveProperty("publishedPage");+ expect(showPublishedPage({ store, docs, bot: SCOUT, threadId: "room-1", card: { ...LIVE, url: `${LIVE.url}?again` }, bundle: await bundle() })).toBe("m2");+ expect(rows("room-1")).toHaveLength(2);+ const doc = appDocument({ store, docs, threadId: "room-1", messageId: "m2" });+ expect(doc).toMatchObject({ room: true, can: { message: false, modelContext: false, serverTools: false, openLinks: true } });+ });++ it("leaves a limit card and a page with no index.html to the plain link card", async () => {+ const { store, docs, rows } = setup();const { bundle } = await folder();- expect(showPublishedPage({ store, docs, threadId: "room-1", card: LIVE, bundle: await bundle() })).toBeNull();- expect(showPublishedPage({ store, docs, threadId: THREAD, card: { state: "limit", title: "Dash", message: "Used up." }, bundle: await bundle() })).toBeNull();- expect(showPublishedPage({ store, docs, threadId: THREAD, card: LIVE, bundle: { source: "/x", files: [{ path: "a.csv", data: Buffer.from("a") }], bytes: 1, skipped: [] } })).toBeNull();+ expect(showPublishedPage({ store, docs, bot: SCOUT, threadId: THREAD, card: { state: "limit", title: "Dash", message: "Used up." }, bundle: await bundle() })).toBeNull();+ expect(showPublishedPage({ store, docs, bot: SCOUT, threadId: THREAD, card: LIVE, bundle: { source: "/x", files: [{ path: "a.csv", data: Buffer.from("a") }], bytes: 1, skipped: [] } })).toBeNull();expect(rows(THREAD)).toEqual([]);});});@@ -470,6 +492,26 @@ describe("appDocument", () => {expect(doc).not.toHaveProperty("tool");});+ it("serves a room's page and MCP app view-only: no message, context or server, and the room's helper", () => {+ const { call, store, docs } = setup(["room-thread"]);+ call({ tool: "show_html", html: PAGE, title: "Sales" }, "room-thread");+ const page = appDocument({ store, docs, threadId: "room-thread", messageId: "m1" })!;+ expect(page.room).toBe(true);+ expect(page.can).toEqual({ serverTools: false, serverResources: false, message: false, openLinks: true, modelContext: false });+ expect(page.srcdoc).toContain(APP_ROOM_HELPER_SOURCE);+ expect(page.srcdoc).not.toContain(APP_HELPER_SOURCE);+ expect(page.csp).toBe(BOT_HTML_CSP);+ const stored = docs.put({ source: "mcp", html: "<p>view</p>", data: { tool: { name: "get-time" }, network: { connect: [], resources: [] } } });+ if (!stored.ok) throw new Error("not stored");+ store.appendMessage("room-thread", { role: "bot", kind: "app", text: "Basic · Get time", from: { botId: SCOUT.id, name: "Scout", color: "blue" },+ app: { v: 1, source: "mcp", title: "Get time", doc: stored.doc, rev: 0, bytes: 11, border: true, network: { connect: [], resources: [] }, mcp: { server: "basic", tool: "get-time", resourceUri: "ui://basic/view" } } });+ const open = { serverTools: true, serverResources: true, message: true, openLinks: true, modelContext: true };+ const app = appDocument({ store, docs, threadId: "room-thread", messageId: "m2", mcpAccess: () => ({ can: open }) })!;+ expect(app).toMatchObject({ room: true, tool: { name: "get-time" }, can: { serverTools: false, serverResources: false, message: false, openLinks: true, modelContext: false } });+ expect(app).not.toHaveProperty("blocked");+ expect(appDocument({ store, docs, threadId: THREAD, messageId: "m2" })).toBeNull();+ });+it("is null for a row that is not an app, another thread's row, and a row whose document is not stored", () => {const { call, store, docs } = setup([], 100);call({ tool: "show_html", html: PAGE, title: "Big" });diff --git a/server/chat-apps.ts b/server/chat-apps.tsindex d26961ade0..b3647a7fc2 100644--- a/server/chat-apps.ts+++ b/server/chat-apps.ts@@ -5,20 +5,20 @@ import {type AppCan, type AppDocument, type AppPayload,} from "../shared/app.ts";import { BOT_HTML_NETWORK } from "../shared/app-frame/csp.ts";-import { botHtmlDocument, mcpAppDocument, publishedBotHtml } from "../shared/app-frame/document.ts";+import { botHtmlDocument, mcpAppDocument, publishedBotHtml, ROOM_CAN } from "../shared/app-frame/document.ts";import { jsxPublishedHtml } from "../shared/app-frame/jsx-page.ts";import { AppDocs, type AppDocData, type AppDocPut } from "./app-docs.ts";-import type { AgentCardResult, AgentCardStore } from "./chat-widgets.ts";+import { speakerIn, type AgentCardResult, type AgentCardStore } from "./chat-widgets.ts";import { compileJsxPage } from "./jsx-compile.ts";import { appDocRefs } from "./message-db.ts";-import { createPageFiles } from "./page-files.ts";+import { createPageFiles, type PageFilesViewer } from "./page-files.ts";import { PageBundleError, readBotPageBundle, skippedNote, type BotFolders, type PageBundle, type PageFile } from "./pages/bundle.ts";import { redactSecretsInText } from "./redact.ts";import type { Message, StoreChange } from "./store.ts";import { userError, type UserError } from "./user-errors.ts";import type { PublishedPageCard as PublishedPage } from "../shared/published-page.ts";+import type { MausColor } from "../shared/wire.ts";-const ROOM_REFUSAL = "Pages are not available in rooms yet. Answer in text.";const NO_SUCH_PAGE = "No page with that id in this conversation.";const NOT_A_PAGE = "That app came from an MCP server, not from show_html; it cannot be replaced. Show a new page instead.";@@ -102,7 +102,7 @@ const pageFallback = (title: string, page: PageText, given?: string) =>export function createAppCard(args: {store: AgentCardStore;docs: AppDocs;- bot: { id: string; name: string };+ bot: { id: string; name: string; color: MausColor };threadId: string;input: Record<string, unknown>;authored?(messageId: string): void;@@ -112,7 +112,6 @@ export function createAppCard(args: {if (input.tool !== "show_html" && input.tool !== "update_html") {return { ok: false, status: 400, error: "tool: must be show_html or update_html." };}- if (store.groupByThread(threadId)) return { ok: false, status: 409, error: ROOM_REFUSAL };const parsed = input.tool === "show_html" ? parseShowHtmlInput(input) : parseUpdateHtmlInput(input);if (!parsed.ok) return { ok: false, status: 400, error: parsed.error };const existing = "appId" in parsed.value ? appRow(store, threadId, parsed.value.appId) : undefined;@@ -127,7 +126,7 @@ export function createAppCard(args: {}function placePage(- args: { store: AgentCardStore; docs: AppDocs; bot: { id: string }; threadId: string; authored?(messageId: string): void },+ args: { store: AgentCardStore; docs: AppDocs; bot: { id: string; name: string; color: MausColor }; threadId: string; authored?(messageId: string): void },value: { appId?: string; height?: number; fallbackText?: string; frameless?: boolean },made: MadePage,): AgentCardResult {@@ -144,8 +143,7 @@ function placePage(network: { connect: [...BOT_HTML_NETWORK.connect], resources: [...BOT_HTML_NETWORK.resources] },...(stored.ok ? {} : { blocked: "too-large" as const }),};- // No `from`: in a direct thread a bot-authored row carrying one is replayed as another bot's line.- const message = store.appendMessage(threadId, { role: "bot", kind: "app", text: pageFallback(made.title, page, value.fallbackText), app: payload });+ const message = store.appendMessage(threadId, { role: "bot", kind: "app", text: pageFallback(made.title, page, value.fallbackText), app: payload, ...speakerIn(store, threadId, bot) });args.authored?.(message.id);return { ok: true, messageId: message.id, ...(made.masked ? { masked: true as const } : {}), ...(made.leftOut ? { leftOut: made.leftOut } : {}) };}@@ -202,7 +200,7 @@ export function pageVersion(app: AppPayload, rev?: number): { doc: string; rev:}export function appDocument(args: {- store: Pick<AgentCardStore, "messagesFor">;+ store: Pick<AgentCardStore, "messagesFor" | "groupByThread">;docs: AppDocs;threadId: string;messageId: string;@@ -219,14 +217,15 @@ export function appDocument(args: {const stored = args.docs.read(version.doc);if (!stored || stored.source !== row.app.source) return null;const rev = version.rev;+ const room = Boolean(args.store.groupByThread(args.threadId));if (stored.source === "html") {const files = stored.data?.folder && args.files? `${args.files.origin}${args.files.folder({ threadId: args.threadId, messageId: row.id, doc: version.doc })}` : undefined;return botHtmlDocument({ messageId: row.id, rev, html: stored.html, title: row.app.title,- ...(stored.data?.format === "jsx" ? { format: "jsx" as const } : {}), ...(files ? { files } : {}) });+ ...(stored.data?.format === "jsx" ? { format: "jsx" as const } : {}), ...(files ? { files } : {}), ...(room ? { room } : {}) });}if (!stored.data?.tool) return null;- const access = (args.mcpAccess ?? MCP_READ_ONLY)(row, args.threadId);+ const access: ReturnType<McpAppAccess> = room ? { can: ROOM_CAN } : (args.mcpAccess ?? MCP_READ_ONLY)(row, args.threadId);return mcpAppDocument({messageId: row.id, rev, html: stored.html,network: { connect: stored.data.network?.connect ?? [], resources: stored.data.network?.resources ?? [] },@@ -235,6 +234,7 @@ export function appDocument(args: {...(stored.data.toolResult ? { toolResult: stored.data.toolResult } : {}),can: access.can,...(access.blocked ? { blocked: access.blocked } : {}),+ ...(room ? { room } : {}),});}@@ -267,18 +267,19 @@ export function publishablePage(args: { store: Pick<AgentCardStore, "messagesForreturn { ok: true, title, files, rev: version.rev, ...(stored.data?.folder ? { folder: stored.data.folder } : {}) };}-/** Where publish_page's page shows in its conversation: the inline card of a page already shown from the same file or- * folder gains the new version and the link, or a new card holds both. null when a card can't hold it (a room, or a+/** Where publish_page's page shows in its conversation: the inline card of a page the same bot already showed from the+ * same file or folder gains the new version and the link, or a new card holds both. null when a card can't hold it (a* page with nothing to preview); the caller then posts the plain link. */export function showPublishedPage(args: {- store: AgentCardStore; docs: AppDocs; threadId: string; card: PublishedPage; bundle: PageBundle;+ store: AgentCardStore; docs: AppDocs; threadId: string; card: PublishedPage; bundle: PageBundle; bot: { id: string; name: string; color: MausColor };}): string | null {const { store, docs, threadId, card, bundle } = args;- if (store.groupByThread(threadId) || card.state !== "live") return null;+ if (card.state !== "live") return null;const made = bundlePage(bundle, card.title);if (!made.ok) return null;+ const speaker = speakerIn(store, threadId, args.bot);const shown = store.messagesFor(threadId).filter((message): message is Message & { app: AppPayload } =>- message.kind === "app" && isRecord(message.app) && message.app.source === "html" && !message.from)+ message.kind === "app" && isRecord(message.app) && message.app.source === "html" && message.from?.botId === speaker.from?.botId).reverse().find((message) => message.app.doc && docs.read(message.app.doc)?.data?.folder === bundle.source);if (shown) {const videos = docs.read(shown.app.doc)?.data?.videos;@@ -292,7 +293,7 @@ export function showPublishedPage(args: {v: 1, source: "html", title: made.title, doc: stored.doc, rev: 0, bytes: pageBytes(made.page), border: true,network: { connect: [...BOT_HTML_NETWORK.connect], resources: [...BOT_HTML_NETWORK.resources] },};- return store.appendMessage(threadId, { role: "bot", kind: "app", text: pageFallback(made.title, made.page), app: payload, publishedPage: card }).id;+ return store.appendMessage(threadId, { role: "bot", kind: "app", text: pageFallback(made.title, made.page), app: payload, publishedPage: card, ...speaker }).id;}export type AppRouteResult = { ok: true } | { ok: false; status: 400 | 404 | 409 | 429; error: string };@@ -445,12 +446,13 @@ export function rowRate(limit: number, windowMs: number): { take(key: string, noexport interface ChatApps {readonly docs: AppDocs;createAppCard(args: {- bot: { id: string; name: string }; threadId: string; input: Record<string, unknown>; authored?(messageId: string): void; folders?: BotFolders;+ bot: { id: string; name: string; color: MausColor }; threadId: string; input: Record<string, unknown>; authored?(messageId: string): void; folders?: BotFolders;}): AgentCardResult | Promise<AgentCardResult>;- /** `origin`: the web origin the client reaches this app at, which a folder page's files load from. */- appDocument(threadId: string, messageId: string, rev?: number, origin?: string): AppDocument | null;+ /** `origin`: the web origin the client reaches this app at, which a folder page's files load from. `viewer`: who asked,+ * whose own token those files load with. */+ appDocument(threadId: string, messageId: string, rev?: number, origin?: string, viewer?: PageFilesViewer): AppDocument | null;publishablePage(threadId: string, messageId: string, rev?: number): PublishablePage;- showPublishedPage(args: { threadId: string; card: PublishedPage; bundle: PageBundle }): string | null;+ showPublishedPage(args: { threadId: string; card: PublishedPage; bundle: PageBundle; bot: { id: string; name: string; color: MausColor } }): string | null;/** The folder pages' files route, ahead of the sign-in gate: true when the request was its own. */serveFile(req: IncomingMessage, res: ServerResponse, path: string, method: string): boolean;setAppContext(args: { threadId: string; messageId: string; content?: unknown; structuredContent?: unknown }): AppRouteResult;@@ -491,11 +493,16 @@ export function createChatApps(deps: {});if (deps.sweeps !== false) later(30_000);const files = createPageFiles({ docs });+ const stillShown = (target: { threadId: string; messageId: string; doc: string }) => {+ const row = appRow(deps.store, target.threadId, target.messageId);+ return Boolean(row && (row.app.doc === target.doc || row.app.history?.includes(target.doc)));+ };const apps: ChatApps = {docs,createAppCard: (args) => createAppCard({ ...args, store: deps.store, docs }),- appDocument: (threadId, messageId, rev, origin) => appDocument({ store: deps.store, docs, threadId, messageId, ...(rev !== undefined ? { rev } : {}),- ...(apps.mcpAccess ? { mcpAccess: apps.mcpAccess } : {}), ...(origin ? { files: { origin, folder: files.folder } } : {}) }),+ appDocument: (threadId, messageId, rev, origin, viewer) => appDocument({ store: deps.store, docs, threadId, messageId, ...(rev !== undefined ? { rev } : {}),+ ...(apps.mcpAccess ? { mcpAccess: apps.mcpAccess } : {}),+ ...(origin ? { files: { origin, folder: (target) => files.folder(target, { key: viewer?.key ?? "", allowed: () => stillShown(target) && (viewer?.allowed() ?? true) }) } } : {}) }),publishablePage: (threadId, messageId, rev) => publishablePage({ store: deps.store, docs, threadId, messageId, ...(rev !== undefined ? { rev } : {}) }),showPublishedPage: (args) => showPublishedPage({ ...args, store: deps.store, docs }),serveFile: (req, res, path, method) => files.serve(req, res, path, method),diff --git a/server/chat-widgets.test.ts b/server/chat-widgets.test.tsindex 14b17c9165..dce5c4f2ca 100644--- a/server/chat-widgets.test.ts+++ b/server/chat-widgets.test.ts@@ -75,7 +75,7 @@ describe("show_widget", () => {});it("tells the caller which row it wrote, on a show and on an update, and never on a refusal", () => {- const fake = fakeStore(["thread-room"]);+ const fake = fakeStore();const authored = vi.fn();const call = (input: unknown, threadId = THREAD) => createAgentCard({ store: fake.store, bot: SCOUT, threadId, input, authored });expect(call({ tool: "show_widget", widget: WIDGET_SAMPLES.buildStatus })).toEqual({ ok: true, messageId: "m1" });@@ -83,7 +83,6 @@ describe("show_widget", () => {expect(authored.mock.calls).toEqual([["m1"], ["m1"]]);expect(call({ tool: "show_widget", widget: { type: "Carousel" } }).ok).toBe(false);expect(call({ tool: "update_widget", widget_id: "nope", widget: WIDGET_SAMPLES.buildStatus }).ok).toBe(false);- expect(call({ tool: "show_widget", widget: WIDGET_SAMPLES.buildStatus }, "thread-room").ok).toBe(false);expect(call({ title: "Deploy now?", subtitle: "The build is green.", options: ["Yes", "No"] }).ok).toBe(false);expect(authored).toHaveBeenCalledTimes(2);});@@ -94,15 +93,15 @@ describe("show_widget", () => {expect(fake.rows(THREAD)[0]).toMatchObject({ text: "Deploy finished.", widget: { root: { type: "Card", children: [{ type: "Text", value: "Deploy finished." }] } } });});- it("is refused in a room, before anything is read or written", () => {+ it("shows in a room as the bot's own row, which only that bot can replace", () => {const fake = fakeStore(["thread-room"]);- expect(show(fake, WIDGET_SAMPLES.pullRequests, {}, "thread-room")).toEqual({- ok: false, status: 409, error: "Widgets are not available in rooms yet. Answer in text.",- });- expect(createAgentCard({ store: fake.store, bot: SCOUT, threadId: "thread-room", input: { tool: "update_widget", widget_id: "m1", widget: WIDGET_SAMPLES.pullRequests } }))- .toMatchObject({ ok: false, status: 409 });- expect(fake.appendMessage).not.toHaveBeenCalled();- expect(fake.patchMessage).not.toHaveBeenCalled();+ expect(show(fake, WIDGET_SAMPLES.pullRequests, {}, "thread-room")).toEqual({ ok: true, messageId: "m1" });+ expect(fake.rows("thread-room")[0]).toMatchObject({ role: "bot", kind: "widget", from: { botId: SCOUT.id, name: "Scout", color: "blue" } });+ const other = { id: "bot-other", name: "Other", color: "red" as const };+ expect(createAgentCard({ store: fake.store, bot: other, threadId: "thread-room", input: { tool: "update_widget", widget_id: "m1", widget: WIDGET_SAMPLES.buildStatus } }))+ .toEqual({ ok: false, status: 404, error: "No widget with that id in this conversation." });+ expect(createAgentCard({ store: fake.store, bot: SCOUT, threadId: "thread-room", input: { tool: "update_widget", widget_id: "m1", widget: WIDGET_SAMPLES.buildStatus } }))+ .toEqual({ ok: true, messageId: "m1" });});it("answers malformed input with the parser's sentence and posts nothing", () => {diff --git a/server/chat-widgets.ts b/server/chat-widgets.tsindex 483fc03d74..87fcb85e0c 100644--- a/server/chat-widgets.ts+++ b/server/chat-widgets.ts@@ -23,7 +23,6 @@ export type AgentCardResult =| { ok: true; messageId: string; masked?: true; leftOut?: string }| { ok: false; status: 400 | 403 | 404 | 409; error: string };-const ROOM_REFUSAL = "Widgets are not available in rooms yet. Answer in text.";const NO_SUCH_WIDGET = "No widget with that id in this conversation.";const EMPTY_FALLBACK = "[widget]";@@ -31,6 +30,12 @@ function isRecord(value: unknown): value is Record<string, unknown> {return Boolean(value) && typeof value === "object" && !Array.isArray(value);}+/** A room's row names the bot that wrote it. A direct thread's never does: there a bot-authored row carrying `from` is+ * replayed as another bot's line. */+export function speakerIn(store: Pick<AgentCardStore, "groupByThread">, threadId: string, bot: { id: string; name: string; color: MausColor }): Pick<Message, "from"> {+ return store.groupByThread(threadId) ? { from: { botId: bot.id, name: bot.name, color: bot.color } } : {};+}+/** Every string loses its secrets. Under an action's `payload` and a chart's `data` rows the keys are the bot's, so they are* scrubbed too, and a key naming a secret (api_key, db_password) masks its value whatever it looks like. */function redactValue(value: unknown, botKeys: boolean): unknown {@@ -130,13 +135,11 @@ export function createAgentCard(args: AgentCardArgs): AgentCardResult | Promise<if (input.tool !== "show_widget" && input.tool !== "update_widget") {return { ok: false, status: 400, error: "tool: must be show_widget or update_widget." };}- if (store.groupByThread(threadId)) return { ok: false, status: 409, error: ROOM_REFUSAL };if (input.tool === "show_widget") {const widget = canonicalWidget(input);if (!widget.ok) return widget;- // No `from`: in a direct thread a bot-authored row carrying one is replayed as another bot's line.- const message = store.appendMessage(threadId, { role: "bot", kind: "widget", text: widget.text, widget: { v: 1, root: widget.root }, ...(args.serverCard ? { serverCard: true as const } : {}) });+ const message = store.appendMessage(threadId, { role: "bot", kind: "widget", text: widget.text, widget: { v: 1, root: widget.root }, ...speakerIn(store, threadId, bot), ...(args.serverCard ? { serverCard: true as const } : {}) });args.authored?.(message.id);return { ok: true, messageId: message.id, ...(widget.masked ? { masked: true as const } : {}) };}diff --git a/server/drivers/agents-app-tools.ts b/server/drivers/agents-app-tools.tsindex c0eedf17b4..ba74e79fbc 100644--- a/server/drivers/agents-app-tools.ts+++ b/server/drivers/agents-app-tools.ts@@ -2,7 +2,7 @@ export const APP_TOOL_DEFINITIONS = [{name: "show_html",description:- "Show a small self-contained web page in this chat, where the person watches it appear and can point at a part to change: a mini app, a game, a chart, a calculator, a report. For maps, canvases, games or anything that fills the window, pass `height`. For forms and choices use show_widget instead, and for plain data a markdown table. Send `html`, one HTML document (a fragment is wrapped) with inline style and script, or `jsx`, one React component file with a default export: it can import react, lucide-react icons, echarts, and Chart and useTheme from \"mausbot\", and style with Tailwind classes. Or send `path`, a folder in your working folder with index.html and its files (scripts, images, csv, geojson or parquet data; up to 5 MB). It runs in a locked sandbox: no network requests, cookies, storage, popups or form posts. Scripts, styles and fonts load only from cdnjs.cloudflare.com, cdn.jsdelivr.net, unpkg.com and Google Fonts; images must be data: URLs or come from those CDNs. Embed the data you need. Use the CSS variables --color-text-primary, --color-background-primary, --color-border-primary and --font-sans to match the person's theme. In the page, mausbot.send(text) sends text as the person's next message (only after they click in it), mausbot.open(url) opens a link, and mausbot.setContext(text) tells you what they see, with their next message. At most 256 KB. To replace a page you showed, in place, call this again with the app_id it returned and new html, jsx or path (was update_html); it reloads, so anything the person did in it is lost. Never put secrets in it. Not available in rooms. For a data dashboard, follow the data-dashboards skill.",+ "Show a small self-contained web page in this chat, where the person watches it appear and can point at a part to change: a mini app, a game, a chart, a calculator, a report. For maps, canvases, games or anything that fills the window, pass `height`. For forms and choices use show_widget instead, and for plain data a markdown table. Send `html`, one HTML document (a fragment is wrapped) with inline style and script, or `jsx`, one React component file with a default export: it can import react, lucide-react icons, echarts, and Chart and useTheme from \"mausbot\", and style with Tailwind classes. Or send `path`, a folder in your working folder with index.html and its files (scripts, images, csv, geojson or parquet data; up to 5 MB). It runs in a locked sandbox: no network requests, cookies, storage, popups or form posts. Scripts, styles and fonts load only from cdnjs.cloudflare.com, cdn.jsdelivr.net, unpkg.com and Google Fonts; images must be data: URLs or come from those CDNs. Embed the data you need. Use the CSS variables --color-text-primary, --color-background-primary, --color-border-primary and --font-sans to match the person's theme. In the page, mausbot.send(text) sends text as the person's next message (only after they click in it), mausbot.open(url) opens a link, and mausbot.setContext(text) tells you what they see, with their next message. At most 256 KB. To replace a page you showed, in place, call this again with the app_id it returned and new html, jsx or path (was update_html); it reloads, so anything the person did in it is lost. Never put secrets in it. In rooms everyone sees it, view-only: send and setContext do nothing. For a data dashboard, follow the data-dashboards skill.",inputSchema: {type: "object",additionalProperties: false,diff --git a/server/drivers/agents-call-cards.test.ts b/server/drivers/agents-call-cards.test.tsindex e747fbf723..748cbd8012 100644--- a/server/drivers/agents-call-cards.test.ts+++ b/server/drivers/agents-call-cards.test.ts@@ -46,7 +46,7 @@ describe("the widget tools in the catalog", () => {expect(show.description).toContain("Ask only what you cannot find or sensibly default, one question per widget;");expect(show.description).toContain("if they type something else instead, that is their answer");expect(show.description).not.toMatch(/without being asked/);- expect(show.description).toMatch(/Never ask for passwords here\. Not available in rooms\.$/);+ expect(show.description).toMatch(/Never ask for passwords here\. In rooms it is view-only: ask in text there\.$/);expect(show.description).toContain("To replace a widget in place (a progress bar moving, a status changing), call this again with the widget_id it returned (was update_widget); one the person already answered cannot be replaced, so show a new one.");for (const name of ["attach_file", "show_widget"]) expect(tools.get(name), name).not.toHaveProperty("annotations");});@@ -110,9 +110,9 @@ describe("show_widget", () => {});it("hands the harness's refusal to the model as an error", async () => {- const room = harness({ ok: false, status: 409, body: { error: "Widgets are not available in rooms yet. Answer in text." } });- expect(await callTool("show_widget", { widget: WIDGET_SAMPLES.pullRequests }, room.context))- .toEqual({ text: "Widgets are not available in rooms yet. Answer in text.", isError: true });+ const answered = harness({ ok: false, status: 409, body: { error: "The person already answered that widget. Show a new one." } });+ expect(await callTool("show_widget", { widget: WIDGET_SAMPLES.pullRequests }, answered.context))+ .toEqual({ text: "The person already answered that widget. Show a new one.", isError: true });const silent = harness({ ok: false, status: 500, body: {} });expect(await callTool("show_widget", { widget: WIDGET_SAMPLES.pullRequests }, silent.context)).toEqual({ text: "Could not show that widget.", isError: true });});@@ -156,7 +156,7 @@ describe("the chat-app tools", () => {expect(tools.get("show_html")!.description).toMatch(/^Show a small self-contained web page in this chat, where the person watches it appear and can point at a part to change: /);expect(tools.get("show_html")!.description).toContain("or `jsx`, one React component file with a default export");// Its last sentence points a dashboard at the bundled data-dashboards skill.- expect(tools.get("show_html")!.description).toMatch(/At most 256 KB\. To replace a page you showed, in place, call this again with the app_id it returned and new html, jsx or path \(was update_html\); it reloads, so anything the person did in it is lost\. Never put secrets in it\. Not available in rooms\. For a data dashboard, follow the data-dashboards skill\.$/);+ expect(tools.get("show_html")!.description).toMatch(/At most 256 KB\. To replace a page you showed, in place, call this again with the app_id it returned and new html, jsx or path \(was update_html\); it reloads, so anything the person did in it is lost\. Never put secrets in it\. In rooms everyone sees it, view-only: send and setContext do nothing\. For a data dashboard, follow the data-dashboards skill\.$/);expect(tools.get("show_html")!.inputSchema).not.toHaveProperty("required");expect(Object.keys((tools.get("show_html")!.inputSchema as unknown as { properties: object }).properties)).toEqual(expect.arrayContaining(["html", "jsx", "path", "title", "app_id"]));expect(Buffer.byteLength(JSON.stringify(tools.get("show_html")))).toBeLessThan(12 * 1024);@@ -202,8 +202,9 @@ describe("the chat-app tools", () => {expect(await callTool("show_html", { html: "x".repeat(262_145), title: "Hi" }, context)).toMatchObject({ isError: true });expect(await callTool("update_html", { html: "<p>x</p>" }, context)).toEqual({ text: "app_id: is required, the id show_html returned.", isError: true });expect(apiResponse).not.toHaveBeenCalled();- const room = harness({ ok: false, status: 409, body: { error: "Pages are not available in rooms yet. Answer in text." } });- expect(await callTool("show_html", { html: "<p>x</p>", title: "x" }, room.context)).toEqual({ text: "Pages are not available in rooms yet. Answer in text.", isError: true });+ const fromMcp = harness({ ok: false, status: 409, body: { error: "That app came from an MCP server, not from show_html; it cannot be replaced. Show a new page instead." } });+ expect(await callTool("show_html", { html: "<p>x</p>", title: "x" }, fromMcp.context))+ .toEqual({ text: "That app came from an MCP server, not from show_html; it cannot be replaced. Show a new page instead.", isError: true });const silent = harness({ ok: false, status: 500, body: {} });expect(await callTool("update_html", { app_id: "m1", html: "<p>x</p>" }, silent.context)).toEqual({ text: "Could not update that page.", isError: true });});diff --git a/server/drivers/agents-catalog-goldens/bridged.profiles.json b/server/drivers/agents-catalog-goldens/bridged.profiles.jsonindex 26c9bf1bed..650fd7aa10 100644--- a/server/drivers/agents-catalog-goldens/bridged.profiles.json+++ b/server/drivers/agents-catalog-goldens/bridged.profiles.json@@ -586,8 +586,8 @@]},"default+room": {- "bytes": 16200,- "sha256": "42c900429ff018befde76478a185ba9db75bdc06d5c5f70c9f00ac2ddfa6c4bc",+ "bytes": 16224,+ "sha256": "8041cc813eea774101cee916dd7914b45de35c25b367bfcf56cd8f68b243778e","tools": ["tool_result_read","list_room_targets",@@ -607,8 +607,8 @@]},"non-chief+room": {- "bytes": 16083,- "sha256": "cd88896555595729f19b1c41316ec6c06edb639372f3a97665c408f58b4d38aa",+ "bytes": 16107,+ "sha256": "f03a3c14bcb5be6d1e2fc81679224f22fa612d7675a59bcc5b2db6d9278a313c","tools": ["tool_result_read","list_room_targets",diff --git a/server/drivers/agents-catalog-goldens/full.tools-list.json b/server/drivers/agents-catalog-goldens/full.tools-list.jsonindex f74d48e38d..565b869cd2 100644--- a/server/drivers/agents-catalog-goldens/full.tools-list.json+++ b/server/drivers/agents-catalog-goldens/full.tools-list.json@@ -415,7 +415,7 @@},{"name": "show_widget",- "description": "Show an interactive widget in this chat: one question answered with a tap instead of typing (a time, a day, one of a few options), a form prefilled (defaultValue) with what they want to change, or a live status. Ask only what you cannot find or sensibly default, one question per widget; for a pick-one, a Card with a Row of Buttons, one per option (onClickAction sends it in one tap), at most six. Several fields only to change something that exists, or for required details you cannot default; \"remind me every weekday\" gets a TimePicker and a DayPicker. A plain yes or no needs none: ask it in your message, and a word or a 👍 or 👎 answers it. Data, comparisons and results go in a markdown table in your message instead, which the chat can copy and export. `widget` is one JSON tree. The root is {type:\"Card\"|\"ListView\", title?, caption?, children:[...], confirm?:{label,action}, cancel?:{label,action}}. Nodes: Row, Col, Box, Spacer, Divider, Text, Title, Caption, Markdown, Badge{label,color}, Icon{name}, Image{src}, Progress{value 0-1, or value and max}, Chart{data,series:[{type,dataKey}],xAxis}, Button{label,onClickAction}, Form{onSubmitAction,children}. Fields, each with a name and a short label: Select|RadioGroup{options:[{label,value}]}, DatePicker{min?,max?} (YYYY-MM-DD), TimePicker{min?,max?,step?} (HH:MM, 24-hour), DayPicker (days of the week, sent as \"mon,wed,fri\"), Checkbox, Input, Textarea. A ListView holds ListViewItem{children}; to have the person choose one row, give the ListView a name and each row a value, and confirm sends the pick. Select, RadioGroup and such a list also let the person type their own answer instead; set allowOther:false only when nothing but an option will do. An action is {type,payload?}; {type:\"open_url\",payload:{url}} opens a link. Labels are plain words, no emoji. A press (confirm, cancel, a button) arrives as their next message, even mid-turn; if they type something else instead, that is their answer. Do what does not depend on it, then end your turn; never wait for it. To replace a widget in place (a progress bar moving, a status changing), call this again with the widget_id it returned (was update_widget); one the person already answered cannot be replaced, so show a new one. Keep it small: one confirm, one cancel, at most 8 rows. Never ask for passwords here. Not available in rooms.",+ "description": "Show an interactive widget in this chat: one question answered with a tap instead of typing (a time, a day, one of a few options), a form prefilled (defaultValue) with what they want to change, or a live status. Ask only what you cannot find or sensibly default, one question per widget; for a pick-one, a Card with a Row of Buttons, one per option (onClickAction sends it in one tap), at most six. Several fields only to change something that exists, or for required details you cannot default; \"remind me every weekday\" gets a TimePicker and a DayPicker. A plain yes or no needs none: ask it in your message, and a word or a 👍 or 👎 answers it. Data, comparisons and results go in a markdown table in your message instead, which the chat can copy and export. `widget` is one JSON tree. The root is {type:\"Card\"|\"ListView\", title?, caption?, children:[...], confirm?:{label,action}, cancel?:{label,action}}. Nodes: Row, Col, Box, Spacer, Divider, Text, Title, Caption, Markdown, Badge{label,color}, Icon{name}, Image{src}, Progress{value 0-1, or value and max}, Chart{data,series:[{type,dataKey}],xAxis}, Button{label,onClickAction}, Form{onSubmitAction,children}. Fields, each with a name and a short label: Select|RadioGroup{options:[{label,value}]}, DatePicker{min?,max?} (YYYY-MM-DD), TimePicker{min?,max?,step?} (HH:MM, 24-hour), DayPicker (days of the week, sent as \"mon,wed,fri\"), Checkbox, Input, Textarea. A ListView holds ListViewItem{children}; to have the person choose one row, give the ListView a name and each row a value, and confirm sends the pick. Select, RadioGroup and such a list also let the person type their own answer instead; set allowOther:false only when nothing but an option will do. An action is {type,payload?}; {type:\"open_url\",payload:{url}} opens a link. Labels are plain words, no emoji. A press (confirm, cancel, a button) arrives as their next message, even mid-turn; if they type something else instead, that is their answer. Do what does not depend on it, then end your turn; never wait for it. To replace a widget in place (a progress bar moving, a status changing), call this again with the widget_id it returned (was update_widget); one the person already answered cannot be replaced, so show a new one. Keep it small: one confirm, one cancel, at most 8 rows. Never ask for passwords here. In rooms it is view-only: ask in text there.","inputSchema": {"type": "object","additionalProperties": false,@@ -441,7 +441,7 @@},{"name": "show_html",- "description": "Show a small self-contained web page in this chat, where the person watches it appear and can point at a part to change: a mini app, a game, a chart, a calculator, a report. For maps, canvases, games or anything that fills the window, pass `height`. For forms and choices use show_widget instead, and for plain data a markdown table. Send `html`, one HTML document (a fragment is wrapped) with inline style and script, or `jsx`, one React component file with a default export: it can import react, lucide-react icons, echarts, and Chart and useTheme from \"mausbot\", and style with Tailwind classes. Or send `path`, a folder in your working folder with index.html and its files (scripts, images, csv, geojson or parquet data; up to 5 MB). It runs in a locked sandbox: no network requests, cookies, storage, popups or form posts. Scripts, styles and fonts load only from cdnjs.cloudflare.com, cdn.jsdelivr.net, unpkg.com and Google Fonts; images must be data: URLs or come from those CDNs. Embed the data you need. Use the CSS variables --color-text-primary, --color-background-primary, --color-border-primary and --font-sans to match the person's theme. In the page, mausbot.send(text) sends text as the person's next message (only after they click in it), mausbot.open(url) opens a link, and mausbot.setContext(text) tells you what they see, with their next message. At most 256 KB. To replace a page you showed, in place, call this again with the app_id it returned and new html, jsx or path (was update_html); it reloads, so anything the person did in it is lost. Never put secrets in it. Not available in rooms. For a data dashboard, follow the data-dashboards skill.",+ "description": "Show a small self-contained web page in this chat, where the person watches it appear and can point at a part to change: a mini app, a game, a chart, a calculator, a report. For maps, canvases, games or anything that fills the window, pass `height`. For forms and choices use show_widget instead, and for plain data a markdown table. Send `html`, one HTML document (a fragment is wrapped) with inline style and script, or `jsx`, one React component file with a default export: it can import react, lucide-react icons, echarts, and Chart and useTheme from \"mausbot\", and style with Tailwind classes. Or send `path`, a folder in your working folder with index.html and its files (scripts, images, csv, geojson or parquet data; up to 5 MB). It runs in a locked sandbox: no network requests, cookies, storage, popups or form posts. Scripts, styles and fonts load only from cdnjs.cloudflare.com, cdn.jsdelivr.net, unpkg.com and Google Fonts; images must be data: URLs or come from those CDNs. Embed the data you need. Use the CSS variables --color-text-primary, --color-background-primary, --color-border-primary and --font-sans to match the person's theme. In the page, mausbot.send(text) sends text as the person's next message (only after they click in it), mausbot.open(url) opens a link, and mausbot.setContext(text) tells you what they see, with their next message. At most 256 KB. To replace a page you showed, in place, call this again with the app_id it returned and new html, jsx or path (was update_html); it reloads, so anything the person did in it is lost. Never put secrets in it. In rooms everyone sees it, view-only: send and setContext do nothing. For a data dashboard, follow the data-dashboards skill.","inputSchema": {"type": "object","additionalProperties": false,diff --git a/server/drivers/agents-catalog-goldens/profiles.json b/server/drivers/agents-catalog-goldens/profiles.jsonindex 59f824df3c..2a2f64f0ce 100644--- a/server/drivers/agents-catalog-goldens/profiles.json+++ b/server/drivers/agents-catalog-goldens/profiles.json@@ -1,7 +1,7 @@{"default": {- "bytes": 59411,- "sha256": "92746f6c81a83ce92dc4ff786677d396366d2acd36d5391fae643ec0d900258f",+ "bytes": 59478,+ "sha256": "8e07ae3ff4fd30289eef2c3434f74e2fa935225d1282def2ef7822aeb7cdd8b7","tools": ["tool_result_read","list_room_targets",@@ -51,8 +51,8 @@]},"voice": {- "bytes": 60192,- "sha256": "39737fd096d648156b3fc1a72525b165e66960a60b54c513a3bbd8c323ced5e8",+ "bytes": 60259,+ "sha256": "d5bcd597eba9ccc0be8a156e4eb01755a8cbc571130a33f97ebaaba188dc6ef5","tools": ["tool_result_read","list_room_targets",@@ -103,8 +103,8 @@]},"shared": {- "bytes": 61676,- "sha256": "488aa058a44ca826f1af4328830236be670a148d432a37f0409ecdc1a9f61d75",+ "bytes": 61743,+ "sha256": "5203eb1f9f06e00a902940e66e5eca126ddd97cd479941ef29d38436949333f6","tools": ["tool_result_read","list_shared_computers",@@ -156,8 +156,8 @@]},"shared+voice": {- "bytes": 62457,- "sha256": "1e3256702ed19ae0b429916c8eb6f32e085709a18e730bd41c81c2d5900ee932",+ "bytes": 62524,+ "sha256": "1bdc4efcc929391224755ee9a32b107a74bbce800bd966b550d25393e95a2d3b","tools": ["tool_result_read","list_shared_computers",@@ -210,8 +210,8 @@]},"skills": {- "bytes": 62338,- "sha256": "3a9c86f8eaf455cab5e599187d172856c300dab747ba3b4ddb882402ed8bcf43",+ "bytes": 62405,+ "sha256": "4ed77f59d167c026cbf60eba9f80c8d3bfaaa67aff29c386c98aa0bec4eeaf93","tools": ["tool_result_read","list_room_targets",@@ -263,8 +263,8 @@]},"skills+voice": {- "bytes": 63119,- "sha256": "1222c7a07f23660d63a08659df22985d79183c42f69ee7f7ccd50f61f76e7ea8",+ "bytes": 63186,+ "sha256": "0502042d50b435ba41233933caed6831b816505c189566194f97b2801193c59d","tools": ["tool_result_read","list_room_targets",@@ -317,8 +317,8 @@]},"skills+shared": {- "bytes": 64603,- "sha256": "fa9f4d5e0056c3d297f03d15f9ec63d3496f2b48afa82ae684933531abc92d17",+ "bytes": 64670,+ "sha256": "0dbe4b7a647203bd23afc8cc6cce5bb78836b05102eae8f2c23f8ff21c56ffe3","tools": ["tool_result_read","list_shared_computers",@@ -372,8 +372,8 @@]},"skills+shared+voice": {- "bytes": 65384,- "sha256": "e2a98bfde725ce6507e0a7f03fbd173cb8256085df68cd443bff6ccca4d44484",+ "bytes": 65451,+ "sha256": "a88ef5bf48c8f56135088ca7b9ba4dacddc28bb681d6514034be06272e826ec9","tools": ["tool_result_read","list_shared_computers",@@ -428,8 +428,8 @@]},"non-chief": {- "bytes": 50195,- "sha256": "c416529edad65a113fe6885dc0fc43f9836d040cbe177256a2ed85aeab37615b",+ "bytes": 50262,+ "sha256": "e6b1181a06d973e27b09baf9dbdd0f9633d4678931a90f9252106d0292c390b4","tools": ["tool_result_read","list_room_targets",@@ -472,8 +472,8 @@]},"voice+non-chief": {- "bytes": 50976,- "sha256": "243437fdbc5b76ad0ea4082dad5ca5845620bbb91b00d49fc3d73c0230df5382",+ "bytes": 51043,+ "sha256": "90ad9cc73be606e7a91013ba03945c377e2cd4e3f422eab4e794cff9af7cb304","tools": ["tool_result_read","list_room_targets",@@ -517,8 +517,8 @@]},"shared+non-chief": {- "bytes": 52460,- "sha256": "da825d7472f3c74b4d8f0a57abc7d7430b1a5bd20ef5a245b3164154875351cb",+ "bytes": 52527,+ "sha256": "0da1550327e11b82ab67cdd03f6bea1b4a5fc122411a42a62fcce8a2c68d8b50","tools": ["tool_result_read","list_shared_computers",@@ -563,8 +563,8 @@]},"shared+voice+non-chief": {- "bytes": 53241,- "sha256": "ddca5aa4d01dc838fe9d685265c7a49b42764370ecd99e3ff4ee85f801cd3f9e",+ "bytes": 53308,+ "sha256": "394aed5bab36aef20c56def7de6f04a7a799428b10b8103ca2d30d0fc7a0bd12","tools": ["tool_result_read","list_shared_computers",@@ -610,8 +610,8 @@]},"skills+non-chief": {- "bytes": 53122,- "sha256": "4cc1ecd0c12d8e2f1807484a6bc5ed81a31923f23be5eb51de2f6156a4cd2650",+ "bytes": 53189,+ "sha256": "4ccc97de0802256668b18f63a6f03ad14089f9eb191cf42c479e8bccc060d0a7","tools": ["tool_result_read","list_room_targets",@@ -656,8 +656,8 @@]},"skills+voice+non-chief": {- "bytes": 53903,- "sha256": "bd1152c61fd04996d0b2f1905892398227979feb4902dd4b92b62fbe29405a2c",+ "bytes": 53970,+ "sha256": "3089d9115a0cdacb938a9b64afb6c39e873efdba0b5d4db06e2cac0e0ee0a5e8","tools": ["tool_result_read","list_room_targets",@@ -703,8 +703,8 @@]},"skills+shared+non-chief": {- "bytes": 55387,- "sha256": "69b471ad769167d513c398017d52a211369348e5bd77aac7208915773b736ec3",+ "bytes": 55454,+ "sha256": "1efdaf6d484479d10fc2786b6486507f15275aae71dfe5655d087a927dd5f59d","tools": ["tool_result_read","list_shared_computers",@@ -751,8 +751,8 @@]},"skills+shared+voice+non-chief": {- "bytes": 56168,- "sha256": "4649de6f71aa8487e7be340055a45db2c6ec4dc795264b543b77ff75a818fbb8",+ "bytes": 56235,+ "sha256": "01e2fc9f73b6dee0c8c0f74db36800c21c1eba819a42df22a5706bb1d39ecca4","tools": ["tool_result_read","list_shared_computers",@@ -800,8 +800,8 @@]},"skills+shared+voice+cloud-home": {- "bytes": 65150,- "sha256": "4ca55ca8251e1c064c244550b9a0460cbd0a28f4d8d89098bbf8dbe944a6bc82",+ "bytes": 65217,+ "sha256": "ded4df78145b339e861973cb81ff0d9ea8df381cfdee417aa282178607d19b5e","tools": ["tool_result_read","list_shared_computers",@@ -856,8 +856,8 @@]},"skills+shared+voice+non-chief+cloud-home": {- "bytes": 55934,- "sha256": "e9a006f18596594da5b517986539d8a249c9eb34f22aabbfe52b6b5725217a47",+ "bytes": 56001,+ "sha256": "45b5caa01b3141617e1430fad91981eed6898a8c0db00815af3a95e940f9b505","tools": ["tool_result_read","list_shared_computers",@@ -905,8 +905,8 @@]},"skills+shared+voice+escalations": {- "bytes": 66214,- "sha256": "3807d0f133d10f4dc8a562bcc87a1715ffc6cc90a8afd45088971912a7d70e3d",+ "bytes": 66281,+ "sha256": "b63fe88e73865406b564e71f6e91f40c12069c2624349f091f08a94a0a544235","tools": ["tool_result_read","list_shared_computers",@@ -962,8 +962,8 @@]},"skills+shared+voice+escalations+x": {- "bytes": 70053,- "sha256": "4bb5c837d554cd5e067c46d9e94d5cb195699c1fd11e08dbf8e853ff8498b6c0",+ "bytes": 70120,+ "sha256": "2fc49767342762ba9c074cdbb633ec1c372f5ee351ec1f1375e59440cb1f9bb8","tools": ["tool_result_read","list_shared_computers",@@ -1023,8 +1023,8 @@]},"skills+shared+voice+escalations+x+team": {- "bytes": 70053,- "sha256": "4bb5c837d554cd5e067c46d9e94d5cb195699c1fd11e08dbf8e853ff8498b6c0",+ "bytes": 70120,+ "sha256": "2fc49767342762ba9c074cdbb633ec1c372f5ee351ec1f1375e59440cb1f9bb8","tools": ["tool_result_read","list_shared_computers",@@ -1084,8 +1084,8 @@]},"skills+shared+voice+escalations+x+team+images": {- "bytes": 70826,- "sha256": "4f07e931b2d53fbfb83ad3a0bebec14b33a610562e96aadebda6d6c5bc90c865",+ "bytes": 70893,+ "sha256": "a4b10013fb38374177ba3937f8eefc44b9af07d75640d033f3a99c34b2d82b5f","tools": ["tool_result_read","list_shared_computers",@@ -1146,8 +1146,8 @@]},"default+legacy-switches": {- "bytes": 59411,- "sha256": "92746f6c81a83ce92dc4ff786677d396366d2acd36d5391fae643ec0d900258f",+ "bytes": 59478,+ "sha256": "8e07ae3ff4fd30289eef2c3434f74e2fa935225d1282def2ef7822aeb7cdd8b7","tools": ["tool_result_read","list_room_targets",@@ -1197,8 +1197,8 @@]},"default+mausbot": {- "bytes": 60062,- "sha256": "cc1227d90bd7379c143a78e33c053e037015c8040ee6736de4db8c801c29f4ac",+ "bytes": 60129,+ "sha256": "fa21ad7f1c83770f05156d9b3e0a03e8dc9831efe57b23e6febe26db30251c6b","tools": ["tool_result_read","list_room_targets",@@ -1250,8 +1250,8 @@]},"skills+shared+voice+mausbot": {- "bytes": 66035,- "sha256": "587b2af70ab760ce531494979953f95b6906141c62bed667e14efe9d1520cf21",+ "bytes": 66102,+ "sha256": "6afc5e9977b9591bf339d1c9ca393cfb0a24db3fdc38a48fa887a8fd765faf49","tools": ["tool_result_read","list_shared_computers",@@ -1308,8 +1308,8 @@]},"default+no-computer-pick": {- "bytes": 58199,- "sha256": "0576c65146d00ee3dcd69d0e1fbaf9ad9c1b64c8adb5d143921538395fea2e45",+ "bytes": 58266,+ "sha256": "dbf8a7c7721d81eef5923a79253f89667478dcdcb637a95ffec57424f28344a0","tools": ["tool_result_read","list_room_targets",@@ -1358,8 +1358,8 @@]},"default+room": {- "bytes": 51025,- "sha256": "1eeb67d32783ab5281a04d68b63e5398ac8b863b3cbffb89968837fd8bd8d5a2",+ "bytes": 56622,+ "sha256": "b52d0a102cefa9ebf3dffecf227d95974133471d92b25011bea4e4b4ecd97861","tools": ["tool_result_read","list_room_targets",@@ -1373,6 +1373,8 @@"start_thread","vm_exec","attach_file",+ "show_widget",+ "show_html","publish_page","unpublish_page","post_to_room",@@ -1403,8 +1405,8 @@]},"non-chief+room": {- "bytes": 41809,- "sha256": "dbf465585a45cf2c45de06eec811a1e5a5807db3d6a2126ee824db0dbda4d183",+ "bytes": 47406,+ "sha256": "2a5b36e363abab653c3b8d66ac6e5fce8421d810ee2a0d9095a5022c553c93a8","tools": ["tool_result_read","list_room_targets",@@ -1418,6 +1420,8 @@"start_thread","vm_exec","attach_file",+ "show_widget",+ "show_html","publish_page","unpublish_page","post_to_room",@@ -1441,8 +1445,8 @@]},"default+images": {- "bytes": 60184,- "sha256": "b299760e81057dca5f8f4c969deac0df2eff1e8035611f481a279618cadfc766",+ "bytes": 60251,+ "sha256": "e97167bd0c812c6f28dffa6edf0957a4c68ff2792dd116ac8fb8b8d155436773","tools": ["tool_result_read","list_room_targets",diff --git a/server/drivers/agents-catalog-profile.ts b/server/drivers/agents-catalog-profile.tsindex 302c9d9431..8939b3aee3 100644--- a/server/drivers/agents-catalog-profile.ts+++ b/server/drivers/agents-catalog-profile.ts@@ -27,8 +27,7 @@ export interface CatalogProfile {/** A direct chat whose bot may pick where it works (Works on is not Off and no team computer is its own): select_computer* is mounted, and the harness refuses a pick on any turn but a person's own message. */computerSelection?: boolean;- /** A room's thread: the widget and page tools, which rooms refuse, and the wait tools, since a room holds no wait,- * are not mounted. */+ /** A room's thread: the wait tools are not mounted, since a room holds no wait. */room?: boolean;imageGeneration?: boolean;}diff --git a/server/drivers/agents-catalog-wire.test.ts b/server/drivers/agents-catalog-wire.test.tsindex 83a93b577e..0fb8bb36e5 100644--- a/server/drivers/agents-catalog-wire.test.ts+++ b/server/drivers/agents-catalog-wire.test.ts@@ -84,13 +84,13 @@ const FULL = "skills+shared+voice+escalations+x+team+images";/** Bytes when the budget was last set; a profile may move at most 2% either way (lower it to lock in a win). */const BUDGET_BASELINE: Record<string, number> = {"default": 59416,- "voice": 59031,- "shared": 60515,- "shared+voice": 61296,+ "voice": 60259,+ "shared": 61743,+ "shared+voice": 62524,"skills": 62343,"skills+voice": 63124,"skills+shared": 64608,- "skills+shared+voice": 64115,+ "skills+shared+voice": 65451,"non-chief": 49935,"voice+non-chief": 50716,"shared+non-chief": 52200,@@ -102,14 +102,14 @@ const BUDGET_BASELINE: Record<string, number> = {"skills+shared+voice+cloud-home": 64782,"skills+shared+voice+non-chief+cloud-home": 55566,"default+legacy-switches": 59416,- "default+mausbot": 58901,- "skills+shared+voice+mausbot": 64766,- "skills+shared+voice+escalations": 64945,+ "default+mausbot": 60129,+ "skills+shared+voice+mausbot": 66102,+ "skills+shared+voice+escalations": 66281,"skills+shared+voice+escalations+x": 68784,"skills+shared+voice+escalations+x+team": 69416,"default+no-computer-pick": 58204,- "default+room": 50849,- "non-chief+room": 41633,+ "default+room": 56622,+ "non-chief+room": 47406,"skills+shared+voice+escalations+x+team+images": 70755,"default+images": 60113,};@@ -335,11 +335,12 @@ describe("agents proxy tools/list golden", () => {const names = (name: string) => toolsOf(wires[name]!).map((tool) => tool.name);expect(names("default+no-computer-pick")).toEqual(names("default").filter((tool) => tool !== "select_computer"));for (const name of ["default", "non-chief"]) {- expect(names(`${name}+room`), name).toEqual(names(name).filter((tool) => !["select_computer", "show_widget", "show_html", "wait_until", "list_waits", "cancel_wait"].includes(tool)));+ expect(names(`${name}+room`), name).toEqual(names(name).filter((tool) => !["select_computer", "wait_until", "list_waits", "cancel_wait"].includes(tool)));}for (const [name, profile] of Object.entries(PROFILES)) {expect(names(name).includes("select_computer"), name).toBe(profile.env.OMB_COMPUTER_SELECTION === "1");- expect(names(name).includes("show_widget"), name).toBe(profile.env.OMB_ROOM !== "1");+ expect(names(name).includes("show_widget"), name).toBe(true);+ expect(names(name).includes("show_html"), name).toBe(true);expect(names(name).includes("wait_until"), name).toBe(profile.env.OMB_ROOM !== "1");}});diff --git a/server/drivers/agents-catalog.ts b/server/drivers/agents-catalog.tsindex 64f41d43ba..bfd8b354a3 100644--- a/server/drivers/agents-catalog.ts+++ b/server/drivers/agents-catalog.ts@@ -885,8 +885,8 @@ const CHIEF_TARGET_TOOL_NAMES = new Set(["propose_profile", "propose_model"]);const WATCHER_TOOL_NAMES = new Set(["create_options_card"]);const LOCAL_VM_TOOL_NAMES = new Set(["vm_exec"]);-/** Refused in a room's thread (chat-widgets.ts, chat-apps.ts, routes/waits.ts), and list_waits, since a room holds no wait. */-const ROOM_REFUSED_TOOL_NAMES = new Set(["show_widget", "show_html", ...WAIT_TOOL_NAMES]);+/** Refused in a room's thread (routes/waits.ts), and list_waits, since a room holds no wait. */+const ROOM_REFUSED_TOOL_NAMES = WAIT_TOOL_NAMES;const CLOUD_HOME_SURFACE = {type: "string", enum: ["auto", "cloud", "browser"],description: "auto = suitable configured computer, cloud = the bot's cloud computer, browser = built-in browser. Omit to list. This server runs in the cloud: the user's own computer and a Local VM are not places here.",diff --git a/server/drivers/agents-widget-tools.ts b/server/drivers/agents-widget-tools.tsindex cd2834014e..4deb1f8f97 100644--- a/server/drivers/agents-widget-tools.ts+++ b/server/drivers/agents-widget-tools.ts@@ -3,7 +3,7 @@ export const WIDGET_TOOL_DEFINITIONS = [{name: "show_widget",description:- "Show an interactive widget in this chat: one question answered with a tap instead of typing (a time, a day, one of a few options), a form prefilled (defaultValue) with what they want to change, or a live status. Ask only what you cannot find or sensibly default, one question per widget; for a pick-one, a Card with a Row of Buttons, one per option (onClickAction sends it in one tap), at most six. Several fields only to change something that exists, or for required details you cannot default; \"remind me every weekday\" gets a TimePicker and a DayPicker. A plain yes or no needs none: ask it in your message, and a word or a 👍 or 👎 answers it. Data, comparisons and results go in a markdown table in your message instead, which the chat can copy and export. `widget` is one JSON tree. The root is {type:\"Card\"|\"ListView\", title?, caption?, children:[...], confirm?:{label,action}, cancel?:{label,action}}. Nodes: Row, Col, Box, Spacer, Divider, Text, Title, Caption, Markdown, Badge{label,color}, Icon{name}, Image{src}, Progress{value 0-1, or value and max}, Chart{data,series:[{type,dataKey}],xAxis}, Button{label,onClickAction}, Form{onSubmitAction,children}. Fields, each with a name and a short label: Select|RadioGroup{options:[{label,value}]}, DatePicker{min?,max?} (YYYY-MM-DD), TimePicker{min?,max?,step?} (HH:MM, 24-hour), DayPicker (days of the week, sent as \"mon,wed,fri\"), Checkbox, Input, Textarea. A ListView holds ListViewItem{children}; to have the person choose one row, give the ListView a name and each row a value, and confirm sends the pick. Select, RadioGroup and such a list also let the person type their own answer instead; set allowOther:false only when nothing but an option will do. An action is {type,payload?}; {type:\"open_url\",payload:{url}} opens a link. Labels are plain words, no emoji. A press (confirm, cancel, a button) arrives as their next message, even mid-turn; if they type something else instead, that is their answer. Do what does not depend on it, then end your turn; never wait for it. To replace a widget in place (a progress bar moving, a status changing), call this again with the widget_id it returned (was update_widget); one the person already answered cannot be replaced, so show a new one. Keep it small: one confirm, one cancel, at most 8 rows. Never ask for passwords here. Not available in rooms.",+ "Show an interactive widget in this chat: one question answered with a tap instead of typing (a time, a day, one of a few options), a form prefilled (defaultValue) with what they want to change, or a live status. Ask only what you cannot find or sensibly default, one question per widget; for a pick-one, a Card with a Row of Buttons, one per option (onClickAction sends it in one tap), at most six. Several fields only to change something that exists, or for required details you cannot default; \"remind me every weekday\" gets a TimePicker and a DayPicker. A plain yes or no needs none: ask it in your message, and a word or a 👍 or 👎 answers it. Data, comparisons and results go in a markdown table in your message instead, which the chat can copy and export. `widget` is one JSON tree. The root is {type:\"Card\"|\"ListView\", title?, caption?, children:[...], confirm?:{label,action}, cancel?:{label,action}}. Nodes: Row, Col, Box, Spacer, Divider, Text, Title, Caption, Markdown, Badge{label,color}, Icon{name}, Image{src}, Progress{value 0-1, or value and max}, Chart{data,series:[{type,dataKey}],xAxis}, Button{label,onClickAction}, Form{onSubmitAction,children}. Fields, each with a name and a short label: Select|RadioGroup{options:[{label,value}]}, DatePicker{min?,max?} (YYYY-MM-DD), TimePicker{min?,max?,step?} (HH:MM, 24-hour), DayPicker (days of the week, sent as \"mon,wed,fri\"), Checkbox, Input, Textarea. A ListView holds ListViewItem{children}; to have the person choose one row, give the ListView a name and each row a value, and confirm sends the pick. Select, RadioGroup and such a list also let the person type their own answer instead; set allowOther:false only when nothing but an option will do. An action is {type,payload?}; {type:\"open_url\",payload:{url}} opens a link. Labels are plain words, no emoji. A press (confirm, cancel, a button) arrives as their next message, even mid-turn; if they type something else instead, that is their answer. Do what does not depend on it, then end your turn; never wait for it. To replace a widget in place (a progress bar moving, a status changing), call this again with the widget_id it returned (was update_widget); one the person already answered cannot be replaced, so show a new one. Keep it small: one confirm, one cancel, at most 8 rows. Never ask for passwords here. In rooms it is view-only: ask in text there.",inputSchema: {type: "object",additionalProperties: false,diff --git a/server/index.ts b/server/index.tsindex 1bb707189d..8022cf5240 100644--- a/server/index.ts+++ b/server/index.ts@@ -9869,7 +9869,7 @@ async function runClaimedGroupMemberTurn(return true;}if (instance.adapter.capabilities.customMcp === true) {- attachCustomMcp(integrations, { ...await mcpServersHost.prepare(bot).then(() => teamConnections.turnMcp(bot, threadId, internalGeneration)), ...lentMcp.mounts(bot, { botId: bot.id, threadId, generation: internalGeneration }) }, cfg, { botId: bot.id, threadId });+ const custom = { ...await mcpServersHost.prepare(bot).then(() => teamConnections.turnMcp(bot, threadId, internalGeneration)), ...lentMcp.mounts(bot, { botId: bot.id, threadId, generation: internalGeneration }) }; attachCustomMcp(integrations, custom, cfg, { botId: bot.id, threadId }); Object.assign(integrations, chatAppsMcp.turnMounts(custom, bot.toolScope));}// An interrupt during connected-app setup must still stop the queued room operation before it starts a process.if (isCancelled?.()) return false;@@ -12151,7 +12151,7 @@ ROUTES.push(createBotMessageRoutes({}));const chatApps = createChatApps({ store, dataDir: DATA_DIR });const chatAppsMcp = createChatAppsMcp({ store, apps: chatApps, dataDir: DATA_DIR, storedServers: () => cfg.mcpServers ?? {}, mountedServers: engineMcpServers, personMcp: teamConnections.personMcp, oauth: mcpOAuth });-ROUTES.push(createChatAppRoutes({ store, apps: chatApps, threadRefusal: cloudThreadRefusal, mcpRpc: chatAppsMcp.rpc }));+ROUTES.push(createChatAppRoutes({ store, apps: chatApps, threadRefusal: cloudThreadRefusal, mcpRpc: chatAppsMcp.rpc, threadVisible: (auth, threadId) => (auth.kind !== "session" || sessions.isLive(auth.session.id)) && visibleTo(viewerFor(auth)).thread(threadId) }));const { react } = createReactions({store, reply: (input) => teamMessages.reactedIn(input.auth, input.threadId, input.target.id, input.answer, { sendId: input.sendId, sender: messageSender(input.auth) }) ?? personReplies.deliver({ ...input, about: "message" }),answerCard: (input) => respondToCard({ ...input, via: "reaction" }), withdraw: personReplies.withdraw,@@ -13023,7 +13023,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {throw Object.assign(new Error("the internal turn capability has expired"), { status: 401 });}};- const botFolders = async () => ({ roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), vmWorkspace: (await attachmentVmForTurn(internalCapability))?.workspaceDir ?? null }); if (await lentMcp.route({ method, path, req, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS || await internalToolRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, folders: botFolders }) !== PASS || await waitRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, ...waitTurnChecks(internalCapability, internalSender) }) !== PASS || await teamMessages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await devsReports.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || (computerAsks && await computerAsks.internal({ method, path, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS) || await imageTools.internal({ method, path, res, json, readBody: readInternalBody, threadId: internalCapability.threadId, requireActive: requireActiveInternalCapability, personTurn: turnOrigin(internalCapability).kind === "user" || (Boolean(roomRun(internalCapability.generation)?.requestMessageId) && guestDrivenTurns.get(internalCapability.threadId) !== internalCapability.generation) }) !== PASS) return; const pagesCall = new AbortController(); res.once("close", () => { if (!res.writableEnded) pagesCall.abort(); }); if (await publishedPages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, requireActive: requireActiveInternalCapability, signal: pagesCall.signal, folders: botFolders, post: (text, publishedPage, bundle) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return !source ? null : (!source.group && bundle && publishedPages.show({ threadId: internalCapability.threadId, card: publishedPage, bundle })) || store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, publishedPage, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id; } }) !== PASS) return;+ const botFolders = async () => ({ roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), vmWorkspace: (await attachmentVmForTurn(internalCapability))?.workspaceDir ?? null }); if (await lentMcp.route({ method, path, req, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS || await internalToolRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, folders: botFolders }) !== PASS || await waitRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, ...waitTurnChecks(internalCapability, internalSender) }) !== PASS || await teamMessages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await devsReports.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || (computerAsks && await computerAsks.internal({ method, path, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS) || await imageTools.internal({ method, path, res, json, readBody: readInternalBody, threadId: internalCapability.threadId, requireActive: requireActiveInternalCapability, personTurn: turnOrigin(internalCapability).kind === "user" || (Boolean(roomRun(internalCapability.generation)?.requestMessageId) && guestDrivenTurns.get(internalCapability.threadId) !== internalCapability.generation) }) !== PASS) return; const pagesCall = new AbortController(); res.once("close", () => { if (!res.writableEnded) pagesCall.abort(); }); if (await publishedPages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, requireActive: requireActiveInternalCapability, signal: pagesCall.signal, folders: botFolders, post: (text, publishedPage, bundle) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return !source ? null : (bundle && publishedPages.show({ threadId: internalCapability.threadId, card: publishedPage, bundle, bot: internalSender })) || store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, publishedPage, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id; } }) !== PASS) return;const delegatedThisTurn = (taskId: string) => {(internalCapability.delegatedThisTurn ??= new Set()).add(taskId);};diff --git a/server/page-files.test.ts b/server/page-files.test.tsindex 90fefe0a58..f91fad6627 100644--- a/server/page-files.test.ts+++ b/server/page-files.test.ts@@ -45,6 +45,20 @@ describe("a folder page's files route", () => {expect(files.folder({ threadId: "t1", messageId: "m2", doc: stored.doc })).not.toBe(folder);});+ it("gives each viewer a token of their own, which stops answering the moment they may no longer see the page", () => {+ const { files, folder, get, stored } = setup();+ let seesIt = true;+ const ann = files.folder({ threadId: "t1", messageId: "m1", doc: stored.doc }, { key: "session:ann", allowed: () => seesIt });+ const bob = files.folder({ threadId: "t1", messageId: "m1", doc: stored.doc }, { key: "session:bob", allowed: () => true });+ expect(new Set([folder, ann, bob]).size).toBe(3);+ expect(files.folder({ threadId: "t1", messageId: "m1", doc: stored.doc }, { key: "session:ann", allowed: () => seesIt })).toBe(ann);+ expect(get(`${ann}app.js`).status).toBe(200);+ seesIt = false;+ expect(get(`${ann}app.js`)).toMatchObject({ status: 404, body: Buffer.from("Not found.") });+ expect(get(ann).status).toBe(404);+ expect(get(`${bob}app.js`).status).toBe(200);+ });+it("serves the stored files read-only, sandboxed if opened directly, and readable from the frame's opaque origin", () => {const { folder, get } = setup();const script = get(`${folder}app.js`);diff --git a/server/page-files.ts b/server/page-files.tsindex 57d0ca3d8f..e06f6369cc 100644--- a/server/page-files.ts+++ b/server/page-files.ts@@ -2,7 +2,9 @@// sign-in, so the route answers before the sign-in gate, and the token is the whole of its authority://// - a token is made only for a document the person was allowed to fetch, names that one document (one version of one-// page in one conversation), and is forgotten after a day unused;+// page in one conversation), and is that person's own: it answers only while they may still see that conversation and+// the page is still in it, so someone who leaves a room, or loses sight of a bot, loses its files too. It is forgotten+// after a day unused;// - only the files stored with that document are served, by their exact path. The one exception is a video the document// recorded when it was shown: it stays in the bot's folder, and is served only while the file that was checked then// is still the file on disk, compared on the open handle;@@ -46,6 +48,12 @@ export interface PageFilesTarget {doc: string;}+/** Who a token is for: `key` names them, and `allowed()` is asked again on every file. */+export interface PageFilesViewer {+ key: string;+ allowed(): boolean;+}+/** A path inside the folder, as stored: segments of the folder's own names, never "." or "..", no backslash or NUL.* null for anything else. */export function pageFilePath(raw: string): string | null {@@ -80,9 +88,9 @@ async function openRecordedVideo(video: PageVideo): Promise<FileHandle | null> {export function createPageFiles(deps: { docs: AppDocs; now?: () => number }) {const now = deps.now ?? Date.now;- const tokens = new Map<string, PageFilesTarget & { used: number }>();+ const tokens = new Map<string, PageFilesTarget & { viewer: string; allowed?: () => boolean; used: number }>();const byTarget = new Map<string, string>();- const keyOf = (target: PageFilesTarget) => `${target.threadId}\n${target.messageId}\n${target.doc}`;+ const keyOf = (target: PageFilesTarget & { viewer: string }) => `${target.threadId}\n${target.messageId}\n${target.doc}\n${target.viewer}`;const forget = (token: string) => {const known = tokens.get(token);tokens.delete(token);@@ -116,17 +124,18 @@ export function createPageFiles(deps: { docs: AppDocs; now?: () => number }) {};return {- /** The folder URL path a document's files load from: the same token while it is in use. */- folder(target: PageFilesTarget): string {+ /** The folder URL path a document's files load from for this viewer: the same token while it is in use. */+ folder(target: PageFilesTarget, viewer?: PageFilesViewer): string {const at = now();for (const [token, known] of tokens) if (at - known.used > DAY_MS) forget(token);- let token = byTarget.get(keyOf(target));+ const entry = { threadId: target.threadId, messageId: target.messageId, doc: target.doc, viewer: viewer?.key ?? "", ...(viewer ? { allowed: viewer.allowed } : {}) };+ let token = byTarget.get(keyOf(entry));if (!token) {while (tokens.size >= MAX_TOKENS) forget(tokens.keys().next().value!);token = randomBytes(32).toString("base64url");- byTarget.set(keyOf(target), token);+ byTarget.set(keyOf(entry), token);}- tokens.set(token, { ...target, used: at });+ tokens.set(token, { ...entry, used: at });return `${PAGE_FILES_PREFIX}${token}/`;},@@ -146,7 +155,7 @@ export function createPageFiles(deps: { docs: AppDocs; now?: () => number }) {return true;}const target = TOKEN.test(token) ? tokens.get(token) : undefined;- if (!target || now() - target.used > DAY_MS || slash === -1) {+ if (!target || now() - target.used > DAY_MS || slash === -1 || (target.allowed && !target.allowed())) {answer(res, 404, "Not found.");return true;}diff --git a/server/routes/bot-messages-apps.test.ts b/server/routes/bot-messages-apps.test.tsindex 44ceb686b3..f8b649cf97 100644--- a/server/routes/bot-messages-apps.test.ts+++ b/server/routes/bot-messages-apps.test.ts@@ -6,6 +6,9 @@ import { createServer, type Server } from "node:http";import type { AddressInfo } from "node:net";import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { ROOM_VIEW_ONLY } from "../../shared/app.ts";+import { WIDGET_SAMPLES } from "../../shared/widget-samples.ts";+import { createAgentCard } from "../chat-widgets.ts";import { createChatApps, type ChatApps } from "../chat-apps.ts";import { DATA_DIR } from "../config.ts";import type { ModelSelection } from "../contracts.ts";@@ -167,6 +170,22 @@ describe("POST /api/bots/:id/messages with appMessage", () => {expect(sent()).toEqual([]);});+ it("refuses an app's words and a widget press in a room, so nothing speaks for anyone there", async () => {+ const { store, bot, state, post, page } = await fixture();+ const other = store.createBot({ name: "Basil" });+ const room = store.createGroup("Launch", [bot.id, other.id]);+ const appId = page("Booking", room.threadId);+ const widget = createAgentCard({ store, bot, threadId: room.threadId, input: { tool: "show_widget", widget: WIDGET_SAMPLES.pullRequests } });+ if (!widget.ok) throw new Error(widget.error);+ const before = store.messagesFor(room.threadId).length;+ expect(await post({ threadId: room.threadId, sendId: sendId(), appMessage: { messageId: appId, text: "Book the 3pm slot" } }))+ .toEqual({ status: 409, body: { error: ROOM_VIEW_ONLY } });+ expect(await post({ threadId: room.threadId, sendId: sendId(), widgetAction: { messageId: widget.messageId, ref: "n2" } }))+ .toEqual({ status: 409, body: { error: ROOM_VIEW_ONLY } });+ expect(state.accepted).toEqual([]);+ expect(store.messagesFor(room.threadId)).toHaveLength(before);+ });+it("holds an app row to 20 messages an hour, gives a refused send's slot back, and lets a retry through", async () => {const { threadId, state, post, page, sent } = await fixture();const appId = page();diff --git a/server/routes/bot-messages.ts b/server/routes/bot-messages.tsindex c7b7bd21c8..c209106f36 100644--- a/server/routes/bot-messages.ts+++ b/server/routes/bot-messages.ts@@ -2,6 +2,7 @@ import { randomUUID } from "node:crypto";import type { IncomingMessage, ServerResponse } from "node:http";import { z } from "zod";+import { ROOM_VIEW_ONLY } from "../../shared/app.ts";import { approvalModeFor } from "../../shared/approval-mode.ts";import { isPersistentQuestionCard } from "../../shared/ask-question.ts";import { normalizeReaction, reactionAnswer } from "../../shared/reactions.ts";@@ -225,6 +226,7 @@ export function createBotMessageRoutes(deps: BotMessageRouteDeps): RouteHandlerreturn json(res, 400, { error: "threadId must be a task id" });}const threadId = body.threadId ?? bot.threadId;+ if ((pressed || fromAnApp) && store.groupByThread(threadId)) return json(res, 409, { error: ROOM_VIEW_ONLY });const notYours = cloudGuestSendRefusal(auth, threadId);if (notYours) return json(res, 403, { error: notYours });if (body.mode !== undefined && body.mode !== "chat" && body.mode !== "goal") return json(res, 400, { error: "mode must be chat or goal" });diff --git a/server/routes/chat-apps.test.ts b/server/routes/chat-apps.test.tsindex 55ca10bffc..ef923b64f8 100644--- a/server/routes/chat-apps.test.ts+++ b/server/routes/chat-apps.test.ts@@ -1,9 +1,11 @@-import { rmSync } from "node:fs";+import { mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";import { createServer, type Server } from "node:http";import type { AddressInfo } from "node:net";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import type { AppPayload } from "../../shared/app.ts";+import { ROOM_VIEW_ONLY, type AppPayload } from "../../shared/app.ts";import { BOT_HTML_CSP } from "../../shared/app-frame/csp.ts";import { CSP_META_PREFIX } from "../../shared/app-frame/document.ts";import { createChatApps, type ChatApps } from "../chat-apps.ts";@@ -35,7 +37,12 @@ async function fixture(extra: Partial<ChatAppRouteDeps> = {}) {const server = createServer(async (req, res) => {const url = new URL(req.url ?? "/", "http://localhost");try {- const auth = { kind: "loopback", scopes: ["admin", "client"] } as RequestAuth;+ if (chatApps.serveFile(req, res, url.pathname, req.method ?? "GET")) return;+ // A test names a paired person with x-session; otherwise the request is the owner's, on this computer.+ const person = req.headers["x-session"];+ const auth = (typeof person === "string"+ ? { kind: "session", session: { id: person, email: `${person}@example.com` }, via: "bearer", scopes: ["client"] }+ : { kind: "loopback", scopes: ["admin", "client"] }) as RequestAuth;if (!await dispatchRoutes(routes, { req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody })) json(res, 404, { from: "inline routes" });} catch (error) {json(res, (error as { status?: number }).status ?? 500, { error: error instanceof Error ? error.message : String(error) });@@ -44,10 +51,14 @@ async function fixture(extra: Partial<ChatAppRouteDeps> = {}) {servers.push(server);await new Promise<void>((ready) => server.listen(0, "127.0.0.1", ready));const base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;- const get = async (path: string) => {- const response = await fetch(`${base}${path}`);+ const get = async (path: string, session?: string) => {+ const response = await fetch(`${base}${path}`, session ? { headers: { "x-session": session } } : {});return { status: response.status, body: await response.json() as Record<string, any>, cache: response.headers.get("cache-control") };};+ const file = async (url: string) => {+ const response = await fetch(url);+ return { status: response.status, text: await response.text() };+ };const post = async (path: string, body: unknown) => {const response = await fetch(`${base}${path}`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });return { status: response.status, body: await response.json() as Record<string, any> };@@ -63,7 +74,18 @@ async function fixture(extra: Partial<ChatAppRouteDeps> = {}) {const app: AppPayload = { v: 1, source: "mcp", title: "Get time", doc: stored.doc, rev: 0, bytes: 11, border: true, network: { connect: [], resources: [] }, mcp: { server: "basic", tool: "get-time", resourceUri: "ui://basic/view" } };return store.appendMessage(threadId, { role: "bot", kind: "app", text: "Basic · Get time", app }).id;};- return { store, bot, other, chatApps, get, post, page, mcpRow };+ const room = () => store.createGroup("Launch", [bot.id, other.id]);+ /** A folder page with a data file beside its index.html, shown by `bot` in `threadId`. */+ const folderPage = async (threadId: string) => {+ const base = realpathSync(mkdtempSync(join(tmpdir(), "omb-room-page-")));+ mkdirSync(join(base, "dash"));+ writeFileSync(join(base, "dash", "index.html"), "<h1>Dash</h1>");+ writeFileSync(join(base, "dash", "data.csv"), "a\n1");+ const result = await chatApps.createAppCard({ bot, threadId, input: { tool: "show_html", path: "dash", title: "Dash" }, folders: async () => ({ roots: [base], vmWorkspace: null }) });+ if (!result.ok) throw new Error(result.error);+ return result.messageId;+ };+ return { store, bot, other, chatApps, get, post, page, mcpRow, room, folderPage, file, base };}describe("GET /api/threads/:threadId/messages/:messageId/app", () => {@@ -128,6 +150,70 @@ describe("POST /api/bots/:botId/apps/:messageId/context", () => {});});+describe("an app shown in a room", () => {+ it("is served to whoever can see the room, view-only, and to nobody else", async () => {+ let roomVisible = true;+ const { bot, get, page, room } = await fixture({ threadVisible: (auth, threadId) => auth.kind !== "session" || (threadId === group.threadId ? roomVisible : true) });+ const group = room();+ const id = page(group.threadId);+ const seen = await get(`/api/threads/${group.threadId}/messages/${id}/app`, "ann");+ expect(seen.status).toBe(200);+ expect(seen.body).toMatchObject({ room: true, can: { message: false, modelContext: false, serverTools: false, serverResources: false, openLinks: true } });+ expect(String(seen.body.srcdoc)).toContain("var room = true;");+ roomVisible = false;+ expect(await get(`/api/threads/${group.threadId}/messages/${id}/app`, "ann")).toMatchObject({ status: 404, body: { error: "no such conversation" } });+ expect((await get(`/api/threads/${group.threadId}/messages/${id}/app`)).status).toBe(200);+ const own = await get(`/api/threads/${bot.threadId}/messages/${page()}/app`, "ann");+ expect(own.body).toMatchObject({ can: { message: true, modelContext: true } });+ expect(own.body).not.toHaveProperty("room");+ });++ it("loads a folder page's files only with the viewer's own token, and only while they can see the room", async () => {+ let annSees = true;+ const { get, room, folderPage, file, base } = await fixture({ threadVisible: (auth) => auth.kind !== "session" || auth.session.id !== "ann" || annSees });+ const group = room();+ const id = await folderPage(group.threadId);+ const folderOf = async (session: string) => {+ const answer = await get(`/api/threads/${group.threadId}/messages/${id}/app?origin=${encodeURIComponent(base)}`, session);+ expect(answer.status).toBe(200);+ return /<base href="([^"]+)">/.exec(String(answer.body.srcdoc))![1]!;+ };+ const ann = await folderOf("ann");+ const bob = await folderOf("bob");+ expect(ann).not.toBe(bob);+ expect(await file(`${ann}data.csv`)).toEqual({ status: 200, text: "a\n1" });+ annSees = false;+ expect(await file(`${ann}data.csv`)).toEqual({ status: 404, text: "Not found." });+ expect(await file(`${bob}data.csv`)).toEqual({ status: 200, text: "a\n1" });+ });++ it("stops a page's files once the page is gone from its conversation", async () => {+ const { store, get, room, folderPage, file, base } = await fixture();+ const group = room();+ const id = await folderPage(group.threadId);+ const answer = await get(`/api/threads/${group.threadId}/messages/${id}/app?origin=${encodeURIComponent(base)}`);+ const folder = /<base href="([^"]+)">/.exec(String(answer.body.srcdoc))![1]!;+ expect((await file(`${folder}data.csv`)).status).toBe(200);+ const row = store.messagesFor(group.threadId).find((message) => message.id === id)!;+ store.patchMessage(group.threadId, id, { app: { ...row.app!, doc: "", history: [] } });+ expect(await file(`${folder}data.csv`)).toEqual({ status: 404, text: "Not found." });+ });++ it("refuses its context and its server calls on the server, whatever the page or the client sends", async () => {+ const mcpRpc = vi.fn();+ const { store, bot, post, page, mcpRow, room } = await fixture({ mcpRpc });+ const group = room();+ const id = page(group.threadId);+ const app = mcpRow(group.threadId);+ expect(await post(`/api/bots/${bot.id}/apps/${id}/context`, { threadId: group.threadId, content: [{ type: "text", text: "Ann is looking at March" }] }))+ .toEqual({ status: 409, body: { error: ROOM_VIEW_ONLY } });+ expect(await post(`/api/bots/${bot.id}/apps/${app}/rpc`, { threadId: group.threadId, method: "tools/call", params: { name: "get-time", arguments: {} } }))+ .toEqual({ status: 409, body: { error: ROOM_VIEW_ONLY } });+ expect(mcpRpc).not.toHaveBeenCalled();+ expect(store.messagesFor(group.threadId).find((message) => message.id === id)?.app).not.toHaveProperty("context");+ });+});+describe("POST /api/bots/:botId/apps/:messageId/rpc", () => {it("refuses a bot page: it has no server (404)", async () => {const mcpRpc = vi.fn();diff --git a/server/routes/chat-apps.ts b/server/routes/chat-apps.tsindex 7e9f531920..2527bbf873 100644--- a/server/routes/chat-apps.ts+++ b/server/routes/chat-apps.ts@@ -1,4 +1,4 @@-import { APP_LIMITS, type AppPayload } from "../../shared/app.ts";+import { APP_LIMITS, ROOM_VIEW_ONLY, type AppPayload } from "../../shared/app.ts";import { APP_RPC_METHODS, type AppRpcMethod } from "../../shared/app-frame/bridge.ts";import { webOrigin } from "../../shared/app-frame/csp.ts";import { appRow, createChatApps, rowRate, type ChatApps } from "../chat-apps.ts";@@ -30,6 +30,9 @@ export interface ChatAppRouteDeps {apps: ChatApps;/** On a Cloud home, a guest changes only conversations it started. */threadRefusal?(auth: RequestAuth, threadId: string): string | null;+ /** Whether this person may see the conversation now: asked when its app is fetched and again for every file of a folder+ * page they load, so leaving a room, or losing sight of its bot, closes its pages to them. */+ threadVisible?(auth: RequestAuth, threadId: string): boolean;mcpRpc?(request: McpRpcRequest): Promise<McpRpcAnswer>;}@@ -50,12 +53,15 @@ export function createChatAppRoutes(deps: ChatAppRouteDeps): RouteHandler {const threadId = m[1]!;// An unknown thread answers before the store materialises it.if (!store.botByThread(threadId) && !store.groupByThread(threadId)) return json(res, 404, { error: "no such conversation" });+ const visible = deps.threadVisible;+ if (visible && !visible(auth, threadId)) return json(res, 404, { error: "no such conversation" });if (!appRow(store, threadId, m[2]!)) return json(res, 404, { error: "no app on that message" });const asked = url.searchParams.get("rev");if (asked !== null && !/^\d{1,6}$/.test(asked)) return json(res, 400, { error: "rev must be a version number" });// A folder page's files load from wherever this client reaches the app; it names that origin itself.const origin = webOrigin(url.searchParams.get("origin")) ?? webOrigin(url.origin) ?? undefined;- const doc = apps.appDocument(threadId, m[2]!, asked === null ? undefined : Number(asked), origin);+ const viewer = { key: auth.kind === "session" ? `session:${auth.session.id}` : auth.kind, allowed: () => !visible || visible(auth, threadId) };+ const doc = apps.appDocument(threadId, m[2]!, asked === null ? undefined : Number(asked), origin, viewer);if (!doc) return json(res, 404, userError(asked === null ? "serverError.page.notStored" : "serverError.page.versionGone"));// `can` and `blocked` change with sign-in and settings: never cached.res.setHeader("cache-control", "private, no-store");@@ -72,6 +78,7 @@ export function createChatAppRoutes(deps: ChatAppRouteDeps): RouteHandler {const threadId = body.threadId;const bot = store.bot(botId);if (!bot) return json(res, 404, { error: "no such bot" });+ if (store.groupByThread(threadId)) return json(res, 409, { error: ROOM_VIEW_ONLY });if (!store.taskByThread(bot.id, threadId)) return json(res, 404, { error: "no such conversation" });const refused = deps.threadRefusal?.(auth, threadId);if (refused) return json(res, 403, { error: refused });diff --git a/shared/app-frame/app-host.html b/shared/app-frame/app-host.htmlindex 3bf5b324c3..389a66e30b 100644--- a/shared/app-frame/app-host.html+++ b/shared/app-frame/app-host.html@@ -1,10 +1,10 @@-<!-- mausbot app-host v1 sha256:709aa85e40e778b512faee30625551dd4a5a0a009f0d116ebc1b2bf29bea32ff -->+<!-- mausbot app-host v1 sha256:9ae69d787fb6c8375f42953219855ba80b5d8116310bd39bee6de2e6c9d1573d --><!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"><meta name="color-scheme" content="light dark"><title>App</title><style>html,body{margin:0;padding:0;background:transparent;overflow:hidden}iframe{display:block;width:100%;border:0;background:transparent}</style></head><body>-<script id="mausbot-app-host">(()=>{var E="2026-01-26";var j={htmlBytes:262144,title:80,fallback:1500,fallbackExcerpt:600,heightMin:80,heightMax:720,messageText:4e3,contextText:4e3,doneText:300,mcpHtmlBytes:2097152,rpcArgumentsBytes:65536,rpcResourceBytes:8388608,messagesPerHour:20,rpcPerMinute:60};function O(e){let r=0;for(let s=0;s<e.length;s+=1){let c=e.charCodeAt(s);if(c<128)r+=1;else if(c<2048)r+=2;else if(c>=55296&&c<=56319&&s+1<e.length){let a=e.charCodeAt(s+1);a>=56320&&a<=57343?(r+=4,s+=1):r+=3}else r+=3}return r}var G=["tools/call","tools/list","resources/read","resources/list"],B=-32601,T=-32602,y=-32e3,d={messageBytes:1e6,minHeight:48,defaultHeight:160,maxHeight:720,linkChars:2048,teardownMs:1e3,engagedTouchMs:1e4,contextCoalesceMs:1e3,logsPerMinute:50,rates:{message:[[3e3,1],[6e5,10]],openLink:[[2e3,1]],rpc:[[1e4,10],[6e5,120]]}};function K(e){let r=$(e);return{...e.can.openLinks?{openLinks:{}}:{},logging:{},...e.can.modelContext?{updateModelContext:{text:{},structuredContent:{}}}:{},...e.can.message?{message:{text:{}}}:{},...r&&e.can.serverTools?{serverTools:{}}:{},...r&&e.can.serverResources?{serverResources:{}}:{},sandbox:{permissions:{},csp:{connectDomains:[...e.network.connect],resourceDomains:[...e.network.resources]}}}}function $(e){return!!e.tool}function H(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function D(e){return typeof e=="string"&&e.length<=200||typeof e=="number"&&Number.isFinite(e)}function X(e){let r;try{r=JSON.stringify(e)}catch{return null}return r===void 0?null:r.length*3<=d.messageBytes?r.length:O(r)}function Z(e){if(!H(e)||e.jsonrpc!=="2.0")return null;let r=X(e);return r===null||r>d.messageBytes||e.params!==void 0&&!H(e.params)?null:typeof e.method=="string"?!e.method||e.method.length>200||"id"in e&&!D(e.id)?null:e:e.method!==void 0||!D(e.id)?null:"result"in e||H(e.error)&&typeof e.error.code=="number"&&typeof e.error.message=="string"?e:null}function I(e,r){let s=[],c=Math.max(...e.map(([a])=>a));return{take(){let a=r();for(;s.length&&a-s[0]>=c;)s.shift();for(let[f,u]of e)if(s.filter(w=>a-w<f).length>=u)return!1;return s.push(a),!0}}}function S(e){return H(e)&&typeof e.code=="number"&&Number.isInteger(e.code)?{code:e.code,message:typeof e.message=="string"&&e.message?e.message:"The host refused this."}:{code:y,message:e instanceof Error&&e.message?e.message:"The host could not do that."}}function Q(e){if(typeof e!="string"||!e||e.length>d.linkChars)return null;let r;try{r=new URL(e)}catch{return null}return r.protocol!=="http:"&&r.protocol!=="https:"||r.username||r.password?null:r.href.length<=d.linkChars?r.href:null}function ee(e){if(!e||e.role!=="user"||!Array.isArray(e.content)||e.content.length===0)return null;let r=[];for(let c of e.content){if(!H(c)||c.type!=="text"||typeof c.text!="string")return null;r.push(c.text)}let s=r.join(`-`).trim();return s&&s.length<=j.messageText?s:null}function J(e){let{doc:r,adapter:s}=e,c=$(r),a=e.timers??{set:(t,l)=>setTimeout(t,l),clear:t=>clearTimeout(t)},f=()=>s.now(),u={...e.hostContext,...c&&r.tool?{toolInfo:{tool:r.tool}}:{}},w=null,M=!1,h=!1,x=!1,C=!1,_=0,R=new Map,k={message:I(d.rates.message,f),openLink:I(d.rates.openLink,f),rpc:I(d.rates.rpc,f),log:I([[6e4,d.logsPerMinute]],f)},b=null,n=null,p=-1/0,g=t=>{if(!x)try{s.post(t)}catch{}},A=(t,l)=>g({jsonrpc:"2.0",id:t,result:l}),i=(t,l,o)=>g({jsonrpc:"2.0",id:t,error:{code:l,message:o}}),P=()=>{let t=e.limits?.maxHeight,l=u.containerDimensions?.maxHeight,o=typeof t=="number"&&t>0?t:typeof l=="number"&&l>0?l:d.maxHeight;return Math.max(d.minHeight,o)},L=()=>{if(n=null,x||!b)return;let t=b;b=null,p=f(),Promise.resolve().then(()=>s.setContext(t)).catch(()=>{})},U=async()=>{if(n===null||!b)return;a.clear(n),n=null;let t=b;b=null,p=f();try{await s.setContext(t)}catch{}},q=()=>{if(c&&!C&&(C=!0,g({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:r.toolInput??{}}}),g({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:r.toolResult??{content:[]}})),w){let t=w;w=null,g({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:t})}},V=async(t,l,o)=>{if(!c)return i(t,B,"Method not found");if(!(l.startsWith("tools/")?r.can.serverTools:r.can.serverResources))return i(t,y,r.blocked?.text??"This app cannot reach its server right now.");if(l==="tools/call"&&(typeof o.name!="string"||!o.name||o.arguments!==void 0&&!H(o.arguments)))return i(t,T,"tools/call needs {name, arguments?}.");if(l==="resources/read"&&typeof o.uri!="string")return i(t,T,"resources/read needs {uri}.");if(!k.rpc.take())return i(t,y,"Too many calls from this app. Wait a moment.");try{let v=await s.callRpc(l,o);A(t,v??{})}catch(v){let N=S(v);i(t,N.code,N.message)}},W=async(t,l,o)=>{if(l==="ui/initialize")return M=!0,A(t,{protocolVersion:E,hostInfo:{name:"mausbot",version:e.hostVersion},hostCapabilities:K(r),hostContext:u});if(h)switch(l){case"ping":return A(t,{});case"ui/request-display-mode":return A(t,{mode:"inline"});case"ui/open-link":{if(!r.can.openLinks)return i(t,y,"This app cannot open links here.");if(!s.engaged())return i(t,y,"Links open only after the person clicks in the app.");let m=Q(o?.url);if(!m)return i(t,T,"Only http and https links of at most 2,048 characters, without a user name or password, can be opened.");if(!k.openLink.take())return i(t,y,"Too many links from this app. Wait a moment.");try{return await s.openLink(m),A(t,{})}catch(v){return i(t,y,S(v).message)}}case"ui/message":{if(!r.can.message)return i(t,y,"This app cannot send messages here.");if(!s.engaged())return i(t,y,"Messages are sent only after the person clicks in the app.");let m=ee(o);if(m===null)return i(t,T,`Only text messages of 1 to ${j.messageText} characters can be sent.`);if(!k.message.take())return i(t,y,"Too many messages from this app. Wait a moment.");try{return await U(),await s.sendMessage(m),A(t,{})}catch(v){return i(t,y,S(v).message)}}case"ui/update-model-context":{if(!r.can.modelContext)return i(t,y,"This app cannot update the model's context here.");if(o?.content!==void 0&&!Array.isArray(o.content)||o?.structuredContent!==void 0&&!H(o.structuredContent))return i(t,T,"ui/update-model-context takes {content?, structuredContent?}.");if(b={...Array.isArray(o?.content)?{content:o.content}:{},...H(o?.structuredContent)?{structuredContent:o.structuredContent}:{}},n===null){let m=p+d.contextCoalesceMs-f();m<=0?L():n=a.set(L,m)}return A(t,{})}default:return G.includes(l)?V(t,l,o??{}):i(t,B,"Method not found")}},Y=(t,l)=>{if(t==="ui/notifications/initialized"){if(!M||h)return;h=!0,q();return}if(h)switch(t){case"ui/notifications/size-changed":{let o=l?.height;if(typeof o!="number"||!Number.isFinite(o))return;s.resize(Math.round(Math.min(P(),Math.max(d.minHeight,o))));return}case"notifications/message":e.log&&k.log.take()&&e.log(l);return;case"ui/notifications/request-teardown":s.teardownRequested();return;default:}};return{get initialized(){return h},handleMessage(t){if(x)return;let l=e.source();if(l==null||t.source!==l)return;let o=Z(t.data);if(!o)return;if("method"in o){"id"in o?W(o.id,o.method,o.params):Y(o.method,o.params);return}let m=R.get(o.id);m&&(R.delete(o.id),m(o))},contextChanged(t){x||(u={...u,...t},h?g({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:t}):M&&(w={...w,...t}))},teardown(){return x||!h?Promise.resolve():new Promise(t=>{let l=`host:${++_}`,o=!1,m=()=>{o||(o=!0,R.delete(l),a.clear(v),t())},v=a.set(m,d.teardownMs);R.set(l,m),g({jsonrpc:"2.0",id:l,method:"ui/resource-teardown",params:{}})})},dispose(){x=!0,n!==null&&a.clear(n),n=null;for(let t of R.values())t({jsonrpc:"2.0",id:"",result:{}});R.clear()}}}var F=1;function te(e){let s=e.webkit?.messageHandlers?.appHost;if(s&&typeof s.postMessage=="function")return{send:a=>s.postMessage(a)};let c=e.appHost;return c&&typeof c.postMessage=="function"?{send:a=>c.postMessage(JSON.stringify(a)),listen:a=>{c.onmessage=f=>{if(typeof f.data!="string")return;let u;try{u=JSON.parse(f.data)}catch{return}u&&typeof u=="object"&&u.v===F&&a(u)}}}:null}function ne(e,r){let s=r??te(e);if(!s)return null;let c=e.document,a=null,f=null,u=0,w=!1,M=0,h=new Map,x=n=>{try{s.send(n)}catch{}},C=(n,p)=>new Promise((g,A)=>{let i=`c${++M}`;h.set(i,{resolve:g,reject:A}),x({v:1,type:"call",callId:i,op:n,params:p})}),_=()=>{for(let n of h.values())n.reject({code:-32e3,message:"This app was closed."});h.clear()};e.addEventListener("message",n=>{a&&(a.handleMessage({source:n.source,data:n.data}),!w&&a.initialized&&(w=!0,x({v:1,type:"initialized"})))});let R=()=>{a?.dispose(),a=null,f?.remove(),f=null,w=!1,_()},k={load(n){if(!n||n.v!==F||!n.doc||typeof n.doc.srcdoc!="string")return;R(),typeof n.engagedAt=="number"&&(u=n.engagedAt);let p=c.createElement("iframe");p.setAttribute("sandbox","allow-scripts allow-forms"),p.setAttribute("referrerpolicy","no-referrer"),p.setAttribute("title","App");let g=Math.max(d.minHeight,Math.round(n.limits?.height??d.defaultHeight));p.style.height=`${g}px`,a=J({doc:n.doc,hostContext:n.hostContext??{},hostVersion:n.hostVersion??"phone",...n.limits?.maxHeight?{limits:{maxHeight:n.limits.maxHeight}}:{},source:()=>p.contentWindow,adapter:{post:i=>p.contentWindow?.postMessage(i,"*"),callRpc:(i,P)=>C("rpc",{method:i,params:P}),sendMessage:async i=>{await C("message",{text:i})},openLink:async i=>{await C("open-link",{url:i})},setContext:async i=>{await C("context",{...i})},resize:i=>{p.style.height=`${i}px`,x({v:1,type:"size",height:i})},engaged:()=>Date.now()-u<=d.engagedTouchMs,teardownRequested:()=>x({v:1,type:"teardown-request"}),now:()=>Date.now()}}),f=p,p.srcdoc=n.doc.srcdoc,c.body.appendChild(p)},contextChanged(n){a?.contextChanged(n??{})},engaged(n){typeof n=="number"&&Number.isFinite(n)&&(u=Math.max(u,n))},async teardown(){a&&await a.teardown(),R(),x({v:1,type:"torn-down"})},reply(n,p){let g=h.get(n);g&&(h.delete(n),p&&"error"in p&&p.error?g.reject(p.error):g.resolve(p&&"result"in p?p.result:void 0))}};s.listen?.(n=>{switch(n.call){case"load":return k.load(n.args[0]);case"contextChanged":return k.contextChanged(n.args[0]);case"engaged":return k.engaged(n.args[0]);case"teardown":return void k.teardown();case"reply":return k.reply(n.args[0],n.args[1])}});let b=e;return b.appHost&&typeof b.appHost.postMessage=="function"||(b.appHost=k),b.mausbotAppHost=k,x({v:1,type:"ready"}),k}function z(){typeof window<"u"&&ne(window)}z();})();</script>+<script id="mausbot-app-host">(()=>{var E="2026-01-26";var S={htmlBytes:262144,title:80,fallback:1500,fallbackExcerpt:600,heightMin:80,heightMax:720,messageText:4e3,contextText:4e3,doneText:300,mcpHtmlBytes:2097152,rpcArgumentsBytes:65536,rpcResourceBytes:8388608,messagesPerHour:20,rpcPerMinute:60};var T="In a room, pages, apps and widgets are view-only: they cannot send messages or tell a bot what anyone sees.";function B(e){let n=0;for(let s=0;s<e.length;s+=1){let c=e.charCodeAt(s);if(c<128)n+=1;else if(c<2048)n+=2;else if(c>=55296&&c<=56319&&s+1<e.length){let a=e.charCodeAt(s+1);a>=56320&&a<=57343?(n+=4,s+=1):n+=3}else n+=3}return n}var K=["tools/call","tools/list","resources/read","resources/list"],D=-32601,I=-32602,y=-32e3,d={messageBytes:1e6,minHeight:48,defaultHeight:160,maxHeight:720,linkChars:2048,teardownMs:1e3,engagedTouchMs:1e4,contextCoalesceMs:1e3,logsPerMinute:50,rates:{message:[[3e3,1],[6e5,10]],openLink:[[2e3,1]],rpc:[[1e4,10],[6e5,120]]}};function X(e){let n=J(e);return{...e.can.openLinks?{openLinks:{}}:{},logging:{},...e.can.modelContext?{updateModelContext:{text:{},structuredContent:{}}}:{},...e.can.message?{message:{text:{}}}:{},...n&&e.can.serverTools?{serverTools:{}}:{},...n&&e.can.serverResources?{serverResources:{}}:{},sandbox:{permissions:{},csp:{connectDomains:[...e.network.connect],resourceDomains:[...e.network.resources]}}}}function J(e){return!!e.tool}function H(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function $(e){return typeof e=="string"&&e.length<=200||typeof e=="number"&&Number.isFinite(e)}function Z(e){let n;try{n=JSON.stringify(e)}catch{return null}return n===void 0?null:n.length*3<=d.messageBytes?n.length:B(n)}function Q(e){if(!H(e)||e.jsonrpc!=="2.0")return null;let n=Z(e);return n===null||n>d.messageBytes||e.params!==void 0&&!H(e.params)?null:typeof e.method=="string"?!e.method||e.method.length>200||"id"in e&&!$(e.id)?null:e:e.method!==void 0||!$(e.id)?null:"result"in e||H(e.error)&&typeof e.error.code=="number"&&typeof e.error.message=="string"?e:null}function _(e,n){let s=[],c=Math.max(...e.map(([a])=>a));return{take(){let a=n();for(;s.length&&a-s[0]>=c;)s.shift();for(let[f,u]of e)if(s.filter(w=>a-w<f).length>=u)return!1;return s.push(a),!0}}}function O(e){return H(e)&&typeof e.code=="number"&&Number.isInteger(e.code)?{code:e.code,message:typeof e.message=="string"&&e.message?e.message:"The host refused this."}:{code:y,message:e instanceof Error&&e.message?e.message:"The host could not do that."}}function ee(e){if(typeof e!="string"||!e||e.length>d.linkChars)return null;let n;try{n=new URL(e)}catch{return null}return n.protocol!=="http:"&&n.protocol!=="https:"||n.username||n.password?null:n.href.length<=d.linkChars?n.href:null}function te(e){if(!e||e.role!=="user"||!Array.isArray(e.content)||e.content.length===0)return null;let n=[];for(let c of e.content){if(!H(c)||c.type!=="text"||typeof c.text!="string")return null;n.push(c.text)}let s=n.join(`+`).trim();return s&&s.length<=S.messageText?s:null}function F(e){let{doc:n,adapter:s}=e,c=J(n),a=e.timers??{set:(t,l)=>setTimeout(t,l),clear:t=>clearTimeout(t)},f=()=>s.now(),u={...e.hostContext,...c&&n.tool?{toolInfo:{tool:n.tool}}:{}},w=null,C=!1,h=!1,x=!1,M=!1,P=0,R=new Map,k={message:_(d.rates.message,f),openLink:_(d.rates.openLink,f),rpc:_(d.rates.rpc,f),log:_([[6e4,d.logsPerMinute]],f)},b=null,r=null,p=-1/0,g=t=>{if(!x)try{s.post(t)}catch{}},A=(t,l)=>g({jsonrpc:"2.0",id:t,result:l}),i=(t,l,o)=>g({jsonrpc:"2.0",id:t,error:{code:l,message:o}}),j=()=>{let t=e.limits?.maxHeight,l=u.containerDimensions?.maxHeight,o=typeof t=="number"&&t>0?t:typeof l=="number"&&l>0?l:d.maxHeight;return Math.max(d.minHeight,o)},L=()=>{if(r=null,x||!b)return;let t=b;b=null,p=f(),Promise.resolve().then(()=>s.setContext(t)).catch(()=>{})},V=async()=>{if(r===null||!b)return;a.clear(r),r=null;let t=b;b=null,p=f();try{await s.setContext(t)}catch{}},q=()=>{if(c&&!M&&(M=!0,g({jsonrpc:"2.0",method:"ui/notifications/tool-input",params:{arguments:n.toolInput??{}}}),g({jsonrpc:"2.0",method:"ui/notifications/tool-result",params:n.toolResult??{content:[]}})),w){let t=w;w=null,g({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:t})}},W=async(t,l,o)=>{if(!c)return i(t,D,"Method not found");if(!(l.startsWith("tools/")?n.can.serverTools:n.can.serverResources))return i(t,y,n.room?T:n.blocked?.text??"This app cannot reach its server right now.");if(l==="tools/call"&&(typeof o.name!="string"||!o.name||o.arguments!==void 0&&!H(o.arguments)))return i(t,I,"tools/call needs {name, arguments?}.");if(l==="resources/read"&&typeof o.uri!="string")return i(t,I,"resources/read needs {uri}.");if(!k.rpc.take())return i(t,y,"Too many calls from this app. Wait a moment.");try{let v=await s.callRpc(l,o);A(t,v??{})}catch(v){let N=O(v);i(t,N.code,N.message)}},Y=async(t,l,o)=>{if(l==="ui/initialize")return C=!0,A(t,{protocolVersion:E,hostInfo:{name:"mausbot",version:e.hostVersion},hostCapabilities:X(n),hostContext:u});if(h)switch(l){case"ping":return A(t,{});case"ui/request-display-mode":return A(t,{mode:"inline"});case"ui/open-link":{if(!n.can.openLinks)return i(t,y,"This app cannot open links here.");if(!s.engaged())return i(t,y,"Links open only after the person clicks in the app.");let m=ee(o?.url);if(!m)return i(t,I,"Only http and https links of at most 2,048 characters, without a user name or password, can be opened.");if(!k.openLink.take())return i(t,y,"Too many links from this app. Wait a moment.");try{return await s.openLink(m),A(t,{})}catch(v){return i(t,y,O(v).message)}}case"ui/message":{if(!n.can.message)return i(t,y,n.room?T:"This app cannot send messages here.");if(!s.engaged())return i(t,y,"Messages are sent only after the person clicks in the app.");let m=te(o);if(m===null)return i(t,I,`Only text messages of 1 to ${S.messageText} characters can be sent.`);if(!k.message.take())return i(t,y,"Too many messages from this app. Wait a moment.");try{return await V(),await s.sendMessage(m),A(t,{})}catch(v){return i(t,y,O(v).message)}}case"ui/update-model-context":{if(!n.can.modelContext)return i(t,y,n.room?T:"This app cannot update the model's context here.");if(o?.content!==void 0&&!Array.isArray(o.content)||o?.structuredContent!==void 0&&!H(o.structuredContent))return i(t,I,"ui/update-model-context takes {content?, structuredContent?}.");if(b={...Array.isArray(o?.content)?{content:o.content}:{},...H(o?.structuredContent)?{structuredContent:o.structuredContent}:{}},r===null){let m=p+d.contextCoalesceMs-f();m<=0?L():r=a.set(L,m)}return A(t,{})}default:return K.includes(l)?W(t,l,o??{}):i(t,D,"Method not found")}},G=(t,l)=>{if(t==="ui/notifications/initialized"){if(!C||h)return;h=!0,q();return}if(h)switch(t){case"ui/notifications/size-changed":{let o=l?.height;if(typeof o!="number"||!Number.isFinite(o))return;s.resize(Math.round(Math.min(j(),Math.max(d.minHeight,o))));return}case"notifications/message":e.log&&k.log.take()&&e.log(l);return;case"ui/notifications/request-teardown":s.teardownRequested();return;default:}};return{get initialized(){return h},handleMessage(t){if(x)return;let l=e.source();if(l==null||t.source!==l)return;let o=Q(t.data);if(!o)return;if("method"in o){"id"in o?Y(o.id,o.method,o.params):G(o.method,o.params);return}let m=R.get(o.id);m&&(R.delete(o.id),m(o))},contextChanged(t){x||(u={...u,...t},h?g({jsonrpc:"2.0",method:"ui/notifications/host-context-changed",params:t}):C&&(w={...w,...t}))},teardown(){return x||!h?Promise.resolve():new Promise(t=>{let l=`host:${++P}`,o=!1,m=()=>{o||(o=!0,R.delete(l),a.clear(v),t())},v=a.set(m,d.teardownMs);R.set(l,m),g({jsonrpc:"2.0",id:l,method:"ui/resource-teardown",params:{}})})},dispose(){x=!0,r!==null&&a.clear(r),r=null;for(let t of R.values())t({jsonrpc:"2.0",id:"",result:{}});R.clear()}}}var z=1;function ne(e){let s=e.webkit?.messageHandlers?.appHost;if(s&&typeof s.postMessage=="function")return{send:a=>s.postMessage(a)};let c=e.appHost;return c&&typeof c.postMessage=="function"?{send:a=>c.postMessage(JSON.stringify(a)),listen:a=>{c.onmessage=f=>{if(typeof f.data!="string")return;let u;try{u=JSON.parse(f.data)}catch{return}u&&typeof u=="object"&&u.v===z&&a(u)}}}:null}function re(e,n){let s=n??ne(e);if(!s)return null;let c=e.document,a=null,f=null,u=0,w=!1,C=0,h=new Map,x=r=>{try{s.send(r)}catch{}},M=(r,p)=>new Promise((g,A)=>{let i=`c${++C}`;h.set(i,{resolve:g,reject:A}),x({v:1,type:"call",callId:i,op:r,params:p})}),P=()=>{for(let r of h.values())r.reject({code:-32e3,message:"This app was closed."});h.clear()};e.addEventListener("message",r=>{a&&(a.handleMessage({source:r.source,data:r.data}),!w&&a.initialized&&(w=!0,x({v:1,type:"initialized"})))});let R=()=>{a?.dispose(),a=null,f?.remove(),f=null,w=!1,P()},k={load(r){if(!r||r.v!==z||!r.doc||typeof r.doc.srcdoc!="string")return;R(),typeof r.engagedAt=="number"&&(u=r.engagedAt);let p=c.createElement("iframe");p.setAttribute("sandbox","allow-scripts allow-forms"),p.setAttribute("referrerpolicy","no-referrer"),p.setAttribute("title","App");let g=Math.max(d.minHeight,Math.round(r.limits?.height??d.defaultHeight));p.style.height=`${g}px`,a=F({doc:r.doc,hostContext:r.hostContext??{},hostVersion:r.hostVersion??"phone",...r.limits?.maxHeight?{limits:{maxHeight:r.limits.maxHeight}}:{},source:()=>p.contentWindow,adapter:{post:i=>p.contentWindow?.postMessage(i,"*"),callRpc:(i,j)=>M("rpc",{method:i,params:j}),sendMessage:async i=>{await M("message",{text:i})},openLink:async i=>{await M("open-link",{url:i})},setContext:async i=>{await M("context",{...i})},resize:i=>{p.style.height=`${i}px`,x({v:1,type:"size",height:i})},engaged:()=>Date.now()-u<=d.engagedTouchMs,teardownRequested:()=>x({v:1,type:"teardown-request"}),now:()=>Date.now()}}),f=p,p.srcdoc=r.doc.srcdoc,c.body.appendChild(p)},contextChanged(r){a?.contextChanged(r??{})},engaged(r){typeof r=="number"&&Number.isFinite(r)&&(u=Math.max(u,r))},async teardown(){a&&await a.teardown(),R(),x({v:1,type:"torn-down"})},reply(r,p){let g=h.get(r);g&&(h.delete(r),p&&"error"in p&&p.error?g.reject(p.error):g.resolve(p&&"result"in p?p.result:void 0))}};s.listen?.(r=>{switch(r.call){case"load":return k.load(r.args[0]);case"contextChanged":return k.contextChanged(r.args[0]);case"engaged":return k.engaged(r.args[0]);case"teardown":return void k.teardown();case"reply":return k.reply(r.args[0],r.args[1])}});let b=e;return b.appHost&&typeof b.appHost.postMessage=="function"||(b.appHost=k),b.mausbotAppHost=k,x({v:1,type:"ready"}),k}function U(){typeof window<"u"&&re(window)}U();})();</script></body></html>diff --git a/shared/app-frame/bridge.ts b/shared/app-frame/bridge.tsindex fb1c431fc5..f7e4965950 100644--- a/shared/app-frame/bridge.ts+++ b/shared/app-frame/bridge.ts@@ -1,7 +1,7 @@// The host side of the MCP Apps bridge (io.modelcontextprotocol/ui, stable 2026-01-26) for one app frame. It// runs in the desktop renderer and, bundled, in the phones' web views, so it never touches a window: a platform// hands it each `message` event and an adapter for the rest.-import { APP_LIMITS, APP_PROTOCOL_VERSION, utf8Bytes, type AppDocument } from "../app.ts";+import { APP_LIMITS, APP_PROTOCOL_VERSION, ROOM_VIEW_ONLY, utf8Bytes, type AppDocument } from "../app.ts";export type JsonRpcId = string | number;@@ -280,7 +280,7 @@ export function createAppBridge(options: AppBridgeOptions): AppBridge {const onRpc = async (id: JsonRpcId, method: AppRpcMethod, params: Record<string, unknown>) => {if (!mcp) return fail(id, RPC_METHOD_NOT_FOUND, "Method not found");const allowed = method.startsWith("tools/") ? doc.can.serverTools : doc.can.serverResources;- if (!allowed) return fail(id, RPC_HOST_REFUSED, doc.blocked?.text ?? "This app cannot reach its server right now.");+ if (!allowed) return fail(id, RPC_HOST_REFUSED, doc.room ? ROOM_VIEW_ONLY : doc.blocked?.text ?? "This app cannot reach its server right now.");if (method === "tools/call" && (typeof params.name !== "string" || !params.name || (params.arguments !== undefined && !isRecord(params.arguments)))) {return fail(id, RPC_INVALID_PARAMS, "tools/call needs {name, arguments?}.");}@@ -326,7 +326,7 @@ export function createAppBridge(options: AppBridgeOptions): AppBridge {}}case "ui/message": {- if (!doc.can.message) return fail(id, RPC_HOST_REFUSED, "This app cannot send messages here.");+ if (!doc.can.message) return fail(id, RPC_HOST_REFUSED, doc.room ? ROOM_VIEW_ONLY : "This app cannot send messages here.");if (!adapter.engaged()) return fail(id, RPC_HOST_REFUSED, "Messages are sent only after the person clicks in the app.");const text = messageText(params);if (text === null) return fail(id, RPC_INVALID_PARAMS, `Only text messages of 1 to ${APP_LIMITS.messageText} characters can be sent.`);@@ -340,7 +340,7 @@ export function createAppBridge(options: AppBridgeOptions): AppBridge {}}case "ui/update-model-context": {- if (!doc.can.modelContext) return fail(id, RPC_HOST_REFUSED, "This app cannot update the model's context here.");+ if (!doc.can.modelContext) return fail(id, RPC_HOST_REFUSED, doc.room ? ROOM_VIEW_ONLY : "This app cannot update the model's context here.");if ((params?.content !== undefined && !Array.isArray(params.content)) || (params?.structuredContent !== undefined && !isRecord(params.structuredContent))) {return fail(id, RPC_INVALID_PARAMS, "ui/update-model-context takes {content?, structuredContent?}.");}diff --git a/shared/app-frame/document.test.ts b/shared/app-frame/document.test.tsindex 4ce2b24595..b6d99ccec5 100644--- a/shared/app-frame/document.test.ts+++ b/shared/app-frame/document.test.ts@@ -2,7 +2,7 @@ import { describe, expect, it } from "vitest";import { BOT_HTML_CSP, mcpAppCsp } from "./csp.ts";import { botHtmlDocument, buildSrcdoc, CSP_META_PREFIX, mcpAppDocument, stripDocumentPreamble } from "./document.ts";-import { APP_HELPER_SOURCE, APP_THEME_STYLE } from "./helper.ts";+import { APP_HELPER_SOURCE, APP_ROOM_HELPER_SOURCE, APP_THEME_STYLE } from "./helper.ts";import { APP_POINT_SOURCE } from "./point.ts";const CSP = "default-src 'none'";@@ -45,6 +45,7 @@ describe("buildSrcdoc", () => {it("keeps the helper free of anything that would end its script element", () => {expect(APP_HELPER_SOURCE).not.toMatch(/<\/script/i);+ expect(APP_ROOM_HELPER_SOURCE).not.toMatch(/<\/script/i);expect(APP_POINT_SOURCE).not.toMatch(/<\/script|<!--/i);expect(APP_THEME_STYLE).not.toMatch(/<\/style/i);});@@ -64,6 +65,21 @@ describe("documents", () => {expect(doc.tool).toBeUndefined();});+ it("in a room, the same policy and sandbox, with nothing that acts for anyone", () => {+ const html = "<!DOCTYPE html><html><body>hi</body></html>";+ const own = botHtmlDocument({ messageId: "m1", rev: 0, html });+ const room = botHtmlDocument({ messageId: "m1", rev: 0, html, room: true });+ expect(room).toMatchObject({ csp: own.csp, network: own.network, room: true });+ expect(room.can).toEqual({ serverTools: false, serverResources: false, message: false, openLinks: true, modelContext: false });+ expect(room.srcdoc).toBe(own.srcdoc.replace(APP_HELPER_SOURCE, APP_ROOM_HELPER_SOURCE));+ expect(own).not.toHaveProperty("room");+ const network = { connect: ["https://esm.sh"], resources: [] };+ const app = mcpAppDocument({ messageId: "m2", rev: 0, html: "<p>app</p>", network, tool: { name: "t" }, room: true,+ can: { serverTools: true, serverResources: true, message: true, openLinks: true, modelContext: true }, blocked: { reason: "apps-off", text: "off" } });+ expect(app).toMatchObject({ csp: mcpAppCsp(network), room: true, can: { serverTools: false, serverResources: false, message: false, openLinks: true, modelContext: false } });+ expect(app).not.toHaveProperty("blocked");+ });+it("an MCP app carries the construction from its filtered network set", () => {const network = { connect: ["https://esm.sh"], resources: ["https://esm.sh"] };const doc = mcpAppDocument({diff --git a/shared/app-frame/document.ts b/shared/app-frame/document.tsindex 3f27829466..d13b7d8e66 100644--- a/shared/app-frame/document.ts+++ b/shared/app-frame/document.ts@@ -3,7 +3,7 @@// which already sits in the head the parser opened for it.import type { AppCan, AppDocument, AppToolDefinition, AppToolResult } from "../app.ts";import { BOT_HTML_CSP, BOT_HTML_NETWORK, folderPageCsp, folderPageNetwork, mcpAppCsp } from "./csp.ts";-import { APP_HELPER_SOURCE, APP_THEME_STYLE } from "./helper.ts";+import { APP_HELPER_SOURCE, APP_ROOM_HELPER_SOURCE, APP_THEME_STYLE } from "./helper.ts";import { jsxPageHtml } from "./jsx-page.ts";import { APP_POINT_SOURCE } from "./point.ts";@@ -31,9 +31,10 @@ export function stripDocumentPreamble(html: string): string {}/** `base`: where a folder page's relative URLs resolve, ahead of anything of the page's. */-export function buildSrcdoc(input: { html: string; csp: string; botHelper?: boolean; base?: string }): string {+export function buildSrcdoc(input: { html: string; csp: string; botHelper?: boolean; room?: boolean; base?: string }): string {const head = `${CSP_META_PREFIX}${escapeAttribute(input.csp)}">`;- const helper = input.botHelper ? `<style>${APP_THEME_STYLE}</style><script>${APP_HELPER_SOURCE}</script><script>${APP_POINT_SOURCE}</script>` : "";+ const source = input.room ? APP_ROOM_HELPER_SOURCE : APP_HELPER_SOURCE;+ const helper = input.botHelper ? `<style>${APP_THEME_STYLE}</style><script>${source}</script><script>${APP_POINT_SOURCE}</script>` : "";const base = input.base ? `<base href="${escapeAttribute(input.base)}">` : "";return `${head}${base}${helper}${stripDocumentPreamble(input.html)}`;}@@ -49,10 +50,12 @@ export function publishedBotHtml(html: string): string {}export const BOT_HTML_CAN: AppCan = { serverTools: false, serverResources: false, message: true, openLinks: true, modelContext: true };+/** Any app in a room: links open for whoever clicks them, and nothing acts for anyone. */+export const ROOM_CAN: AppCan = { serverTools: false, serverResources: false, message: false, openLinks: true, modelContext: false };/** `format: "jsx"`: `html` is a React component file, served inside the page shell. `files`: a folder page, whose* other files load from that folder URL (the token route's, ending in "/"). */-export function botHtmlDocument(input: { messageId: string; rev: number; html: string; format?: "jsx"; title?: string; files?: string }): AppDocument {+export function botHtmlDocument(input: { messageId: string; rev: number; html: string; format?: "jsx"; title?: string; files?: string; room?: boolean }): AppDocument {const html = input.format === "jsx" ? jsxPageHtml({ title: input.title ?? "Page", source: input.html }) : input.html;const csp = input.files ? folderPageCsp(input.files) : BOT_HTML_CSP;const network = input.files ? folderPageNetwork(input.files) : BOT_HTML_NETWORK;@@ -60,10 +63,11 @@ export function botHtmlDocument(input: { messageId: string; rev: number; html: sv: 1,messageId: input.messageId,rev: input.rev,- srcdoc: buildSrcdoc({ html, csp, botHelper: true, ...(input.files ? { base: input.files } : {}) }),+ srcdoc: buildSrcdoc({ html, csp, botHelper: true, room: input.room === true, ...(input.files ? { base: input.files } : {}) }),csp,network: { connect: [...network.connect], resources: [...network.resources] },- can: { ...BOT_HTML_CAN },+ can: { ...(input.room ? ROOM_CAN : BOT_HTML_CAN) },+ ...(input.room ? { room: true as const } : {}),};}@@ -77,6 +81,7 @@ export function mcpAppDocument(input: {toolResult?: AppToolResult;can: AppCan;blocked?: AppDocument["blocked"];+ room?: boolean;}): AppDocument {const network = { connect: [...input.network.connect], resources: [...input.network.resources] };const csp = mcpAppCsp(network);@@ -90,7 +95,8 @@ export function mcpAppDocument(input: {tool: input.tool,...(input.toolInput ? { toolInput: input.toolInput } : {}),...(input.toolResult ? { toolResult: input.toolResult } : {}),- can: { ...input.can },- ...(input.blocked ? { blocked: input.blocked } : {}),+ can: { ...(input.room ? ROOM_CAN : input.can) },+ ...(input.blocked && !input.room ? { blocked: input.blocked } : {}),+ ...(input.room ? { room: true as const } : {}),};}diff --git a/shared/app-frame/helper.test.ts b/shared/app-frame/helper.test.tsindex d32f096199..3cd96fb352 100644--- a/shared/app-frame/helper.test.ts+++ b/shared/app-frame/helper.test.ts@@ -1,10 +1,11 @@import { Window } from "happy-dom";import { afterEach, describe, expect, it } from "vitest";-import type { AppDocument } from "../app.ts";+import { ROOM_VIEW_ONLY, type AppDocument } from "../app.ts";import { createAppBridge, type AppBridge } from "./bridge.ts";import { BOT_HTML_CSP, BOT_HTML_NETWORK } from "./csp.ts";-import { APP_HELPER_SOURCE } from "./helper.ts";+import { ROOM_CAN } from "./document.ts";+import { APP_HELPER_SOURCE, APP_ROOM_HELPER_SOURCE } from "./helper.ts";const DOC: AppDocument = {v: 1, messageId: "m1", rev: 0, srcdoc: "", csp: BOT_HTML_CSP,@@ -23,7 +24,8 @@ interface Scene {under?: Array<{ position?: "absolute" | "fixed"; width: number | "window"; height: number | "window"; freed?: number }>;}-function boot(engaged = true, options: { scene?: Scene; start?: number; loaded?: boolean } = {}) {+function boot(engaged = true, options: { scene?: Scene; start?: number; loaded?: boolean; room?: boolean } = {}) {+ const room = options.room === true;const page = new Window();pages.push(page);const listeners = new Set<Listener>();@@ -75,7 +77,7 @@ function boot(engaged = true, options: { scene?: Scene; start?: number; loaded?:}const seen = { messages: [] as string[], links: [] as string[], contexts: [] as unknown[], heights: [] as number[] };bridge = createAppBridge({- doc: DOC,+ doc: room ? { ...DOC, can: { ...ROOM_CAN }, room: true } : DOC,hostContext: { theme: "dark", styles: { variables: { "--color-text-primary": "#fafafa", "not-a-variable": "x" } } },source: () => frame,hostVersion: "1",@@ -100,14 +102,14 @@ function boot(engaged = true, options: { scene?: Scene; start?: number; loaded?:observe() {}}// The helper's free names, bound to this fake frame: it runs exactly as written.- const run = new Function("window", "document", "ResizeObserver", "requestAnimationFrame", APP_HELPER_SOURCE);+ const run = new Function("window", "document", "ResizeObserver", "requestAnimationFrame", room ? APP_ROOM_HELPER_SOURCE : APP_HELPER_SOURCE);run(frame, document, scene ? FakeResizeObserver : undefined, (callback: () => void) => setTimeout(callback, 0));return {bridge, seen, frame, root,load: () => { options.loaded = true; for (const listener of loads) listener(); },reflow: () => { for (const observed of observers) setTimeout(observed, 0); },mausbot: () => frame.mausbot as {- send(text: string): Promise<void>; open(url: string): Promise<void>; setContext(text: string): Promise<void>; theme: string;+ send(text: string): Promise<void>; open(url: string): Promise<void>; setContext(text: string): Promise<void>; theme: string; room: boolean;},};}@@ -149,6 +151,31 @@ describe("the bot-page helper", () => {expect(page.seen.contexts[0]).toEqual({ content: [{ type: "text", text: "Looking at March" }] });});+ it("in a room, says so, and its send and setContext resolve without asking the host; a page that asks anyway is refused", async () => {+ const page = boot(true, { room: true });+ expect(page.mausbot().room).toBe(true);+ await page.mausbot().send("Book the 3pm slot");+ await page.mausbot().setContext("Looking at March");+ await page.mausbot().open("https://example.com/docs");+ expect(page.seen.links).toEqual(["https://example.com/docs"]);+ const answers: unknown[] = [];+ (page.frame.addEventListener as (type: string, listener: Listener) => void)("message", (event) => {+ if ([7, 8].includes((event.data as { id?: unknown }).id as number)) answers.push(event.data);+ });+ const parent = page.frame.parent as { postMessage(data: unknown): void };+ parent.postMessage({ jsonrpc: "2.0", id: 7, method: "ui/message", params: { role: "user", content: [{ type: "text", text: "Book it" }] } });+ parent.postMessage({ jsonrpc: "2.0", id: 8, method: "ui/update-model-context", params: { content: [{ type: "text", text: "March" }] } });+ await expect.poll(() => answers.length).toBe(2);+ expect(answers).toEqual([+ { jsonrpc: "2.0", id: 7, error: { code: -32000, message: ROOM_VIEW_ONLY } },+ { jsonrpc: "2.0", id: 8, error: { code: -32000, message: ROOM_VIEW_ONLY } },+ ]);+ await new Promise((resolve) => setTimeout(resolve, 1_100));+ expect(page.seen.messages).toEqual([]);+ expect(page.seen.contexts).toEqual([]);+ expect(boot().mausbot().room).toBe(false);+ });+it("rejects when the host refuses, as it does without a click in the page", async () => {const page = boot(false);await expect(page.mausbot().send("hi")).rejects.toThrow(/click/);diff --git a/shared/app-frame/helper.ts b/shared/app-frame/helper.tsindex 1c77dfa2c3..89cbf98ec4 100644--- a/shared/app-frame/helper.ts+++ b/shared/app-frame/helper.ts@@ -6,6 +6,7 @@// open(url): Promise<void>, // ui/open-link// setContext(text): Promise<void>, // ui/update-model-context// theme: "light" | "dark",+// room: boolean, // shown in a room: send and setContext resolve and do nothing// }//// A page pasted from an SDK build runs its own App beside this one: the helper's request ids are strings@@ -25,8 +26,9 @@ export const APP_THEME_STYLE = [].join("");/** Plain ES2017 with no imports: it runs as written in every browser engine the apps ship in. */-export const APP_HELPER_SOURCE = `(function () {+const helperSource = (room: boolean) => `(function () {"use strict";+ var room = ${room};var parent = window.parent;if (!parent || parent === window) return;var root = document.documentElement;@@ -41,7 +43,7 @@ export const APP_HELPER_SOURCE = `(function () {});};var notify = function (method, params) { post({ jsonrpc: "2.0", method: method, params: params || {} }); };- var api = { theme: "light" };+ var api = { theme: "light", room: room };var apply = function (context) {if (!context || typeof context !== "object") return;if (context.theme === "light" || context.theme === "dark") {@@ -159,6 +161,7 @@ export const APP_HELPER_SOURCE = `(function () {if (result && result.isError) throw new Error("The host could not do that.");};api.send = function (text) {+ if (room) return Promise.resolve();return ready.then(function () {return request("ui/message", { role: "user", content: [{ type: "text", text: String(text) }] });}).then(checked);@@ -167,9 +170,14 @@ export const APP_HELPER_SOURCE = `(function () {return ready.then(function () { return request("ui/open-link", { url: String(url) }); }).then(checked);};api.setContext = function (text) {+ if (room) return Promise.resolve();return ready.then(function () {return request("ui/update-model-context", { content: [{ type: "text", text: String(text) }] });}).then(function () {});};Object.defineProperty(window, "mausbot", { value: api, enumerable: true });})();`;++export const APP_HELPER_SOURCE = helperSource(false);+/** A room's page: everyone in the room sees it, and it speaks for none of them. */+export const APP_ROOM_HELPER_SOURCE = helperSource(true);diff --git a/shared/app.ts b/shared/app.tsindex 540789879d..47c11451fc 100644--- a/shared/app.ts+++ b/shared/app.ts@@ -174,8 +174,14 @@ export interface AppDocument {can: AppCan;/** Why serverTools/serverResources are off: drawn as a strip under the frame. */blocked?: { reason: AppBlockedReason; text: string };+ /** Shown in a room, to everyone who can see it: view-only. `can` has message, modelContext, serverTools and+ * serverResources off, and a bot's page reads `mausbot.room === true`. */+ room?: true;}+/** Why a room refuses what an app or a widget would do for the person: nobody in a room speaks for the others. */+export const ROOM_VIEW_ONLY = "In a room, pages, apps and widgets are view-only: they cannot send messages or tell a bot what anyone sees.";+/** Exactly one of `html` (wrapped when it was a fragment), `jsx` and `path` (a folder with index.html, or an .html* file, in the bot's own folders), none yet scrubbed of secrets. */export interface ShowHtmlInput {diff --git a/src/components/GroupView.tsx b/src/components/GroupView.tsxindex b2ae592cc9..9e1dc6e05e 100644--- a/src/components/GroupView.tsx+++ b/src/components/GroupView.tsx@@ -88,7 +88,7 @@ import { citationPreviewText, splitTranscriptCitations, type CitationAttachmentimport { highlightCitationSource } from "@/lib/citations-dom";import { latestFailure, latestReply, type TranscriptSnapshot } from "@/lib/transcript-announcer";import { pendingApprovals } from "./PendingApproval";-import { DataResultChip } from "./DataResultChip"; import { PublishedPageCard } from "./PublishedPageCard";+import { DataResultChip } from "./DataResultChip"; import { PublishedPageCard } from "./PublishedPageCard"; import { RoomRichRow } from "./RichMessageRow";import { TranscriptAnnouncer } from "./TranscriptAnnouncer";import { dayLabel, localDay } from "@/lib/transcript-derivations";import { roomThreadSpeakerId, roomThreadWorking } from "@/lib/room-threads";@@ -462,7 +462,7 @@ export const Transcript = memo(function Transcript({<CompactionChip message={m} />) : m.kind === "digest" ? (showToolCalls ? <DigestChip message={m} /> : null- ) : m.publishedPage ? <PublishedPageCard message={m} /> : m.kind === "text" && (m.text || m.attachments?.length) ? (+ ) : (m.kind === "app" || m.kind === "widget") && m.from ? <RoomRichRow message={m} from={m.from} threadId={group.threadId} /> : m.publishedPage ? <PublishedPageCard message={m} /> : m.kind === "text" && (m.text || m.attachments?.length) ? (!user && isPureLeakedSystemHarnessMessage(m.text) && !m.attachments?.length ? null : (<RoomTextMessagegroup={group}diff --git a/src/components/RichMessageRow.tsx b/src/components/RichMessageRow.tsxindex 208d6a396d..3b1cdd40b4 100644--- a/src/components/RichMessageRow.tsx+++ b/src/components/RichMessageRow.tsx@@ -17,7 +17,8 @@ export function richRowKind(message: Message): Message["kind"] {return message.kind;}-export function RichMessageRow({ botId, botName, threadId, message }: { botId: string; botName: string; threadId?: string; message: Message }) {+/** `room`: shown to everyone in a room, view-only. */+export function RichMessageRow({ botId, botName, threadId, message, room }: { botId: string; botName: string; threadId?: string; message: Message; room?: boolean }) {return (<MessageBoundary fallbackText={message.text ?? ""}>{message.setupSuggestion@@ -25,12 +26,21 @@ export function RichMessageRow({ botId, botName, threadId, message }: { botId: s: message.kind === "goal.run"? <GoalRunRow botId={botId} threadId={threadId} message={message} />: message.kind === "app"- ? <AppMessage botId={botId} botName={botName} threadId={threadId} message={message} />- : <WidgetMessage botId={botId} threadId={threadId} message={message} />}+ ? <AppMessage botId={botId} botName={botName} threadId={threadId} message={message} room={room} />+ : <WidgetMessage botId={botId} threadId={threadId} message={message} viewOnly={room} />}</MessageBoundary>);}+/** A page, an app or a widget a room member showed: the same row as in its own chat, view-only. */+export function RoomRichRow({ message, from, threadId }: { message: Message; from: NonNullable<Message["from"]>; threadId: string }) {+ return (+ <div className="flex justify-start">+ <RichMessageRow botId={from.botId} botName={from.name} threadId={threadId} message={message} room />+ </div>+ );+}+export function UserLineNote({ message }: { message: Message }) {// A @devs message: its report's status ("Got it, we're looking", then "Fixed in 0.1.x").if (message.bugReport) return <BugReportNote report={message.bugReport} />;diff --git a/src/components/app/AppMessage.test.ts b/src/components/app/AppMessage.test.tsindex ebe9e858e4..cddaa09b4b 100644--- a/src/components/app/AppMessage.test.ts+++ b/src/components/app/AppMessage.test.ts@@ -6,7 +6,7 @@ import { renderToStaticMarkup } from "react-dom/server";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { BotEditorStore, type Message, type useStore } from "@/state/store";-import type { AppDocument, AppPayload } from "../../../shared/app";+import { ROOM_VIEW_ONLY, type AppDocument, type AppPayload } from "../../../shared/app";import { APP_SAMPLES, MCP_APP_SAMPLES } from "../../../shared/app-samples";import { botHtmlDocument, mcpAppDocument } from "../../../shared/app-frame/document";import { createAppPool, type AppPool } from "./app-pool";@@ -47,12 +47,12 @@ let host: HTMLDivElement;let root: Root;let pool: AppPool;-const view = (message: Message) => createElement(BotEditorStore, {+const view = (message: Message, room?: boolean) => createElement(BotEditorStore, {value: store,- children: createElement(AppMessage, { botId: "pepper", botName: "Pepper", threadId: "t1", message, pool }),+ children: createElement(AppMessage, { botId: "pepper", botName: "Pepper", threadId: "t1", message, pool, ...(room ? { room } : {}) }),});-const mount = async (message: Message) => {- await act(async () => { root.render(view(message)); });+const mount = async (message: Message, room?: boolean) => {+ await act(async () => { root.render(view(message, room)); });await settle();};/** Let fetches, pool grants and effects run. */@@ -212,6 +212,26 @@ describe("a bot's page", () => {expect(frame().style.height).toBe("333px");});+ it("in a room, shows the page to everyone with Full screen but no Point or Share, and sends nothing for anyone", async () => {+ fetchMock.mockImplementation(async (path) => /\/app(\?|$)/.test(path) ? json(200, botHtmlDocument({ messageId: "a1", rev: 0, html: counter.html, room: true })) : json(202, { ok: true }));+ await mount(row(htmlPayload()), true);+ expect(find("[data-app]")!.hasAttribute("data-app-room")).toBe(true);+ expect(frame().getAttribute("sandbox")).toBe("allow-scripts allow-forms");+ expect(frame().getAttribute("srcdoc")).toContain("var room = true;");+ expect(button("Point")).toBeUndefined();+ expect(button("Share")).toBeUndefined();+ expect(button("Full screen")).toBeTruthy();+ await handshake();+ await engage();+ await fromView({ jsonrpc: "2.0", id: "m1", method: "ui/message", params: { role: "user", content: [{ type: "text", text: "I have had 3 cups." }] } });+ await fromView({ jsonrpc: "2.0", id: "c1", method: "ui/update-model-context", params: { content: [{ type: "text", text: "3 cups" }] } });+ await settle();+ expect(toView.find((message) => message.id === "m1")).toEqual({ jsonrpc: "2.0", id: "m1", error: { code: -32000, message: ROOM_VIEW_ONLY } });+ expect(toView.find((message) => message.id === "c1")).toEqual({ jsonrpc: "2.0", id: "c1", error: { code: -32000, message: ROOM_VIEW_ONLY } });+ expect(posts("/messages")).toEqual([]);+ expect(posts("/context")).toEqual([]);+ });+it("opens a link the person clicked through the desktop's browser", async () => {await mount(row(htmlPayload()));await handshake();diff --git a/src/components/app/AppMessage.tsx b/src/components/app/AppMessage.tsxindex c46d1948ae..ff98d60056 100644--- a/src/components/app/AppMessage.tsx+++ b/src/components/app/AppMessage.tsx@@ -46,12 +46,14 @@ function useAutoMount(botId: string, threadId: string | undefined, messageId: streturn !newest || newest.has(messageId) || !messages?.some((message) => message.id === messageId);}-export function AppMessage({ botId, botName, threadId, message, pool }: {+export function AppMessage({ botId, botName, threadId, message, pool, room }: {botId: string;botName: string;threadId?: string;message: Message;pool?: AppPool;+ /** Shown in a room: view-only. */+ room?: boolean;}) {const payload = message.app;if (!isAppPayload(payload) || !threadId) {@@ -59,20 +61,21 @@ export function AppMessage({ botId, botName, threadId, message, pool }: {? <div className="chat-text w-fit max-w-[min(42rem,78%)] rounded-2xl bg-card px-4 py-2.5 text-[15px] leading-relaxed whitespace-pre-wrap text-ink">{message.text}</div>: null;}- return <AppRow botId={botId} botName={botName} threadId={threadId} message={message} payload={payload} pool={pool} />;+ return <AppRow botId={botId} botName={botName} threadId={threadId} message={message} payload={payload} pool={pool} room={room} />;}type Loaded =| { key: string; doc: AppDocument; failure?: undefined }| { key: string; doc?: undefined; failure: AppFetchFailure };-function AppRow({ botId, botName, threadId, message, payload, pool }: {+function AppRow({ botId, botName, threadId, message, payload, pool, room }: {botId: string;botName: string;threadId: string;message: Message;payload: AppPayload;pool?: AppPool;+ room?: boolean;}) {const { dispatch } = useStore();const uid = useId();@@ -151,7 +154,7 @@ function AppRow({ botId, botName, threadId, message, payload, pool }: {threadId, appId: message.id, rev, title: payload.title, picked: () => setFullScreen(false),});const share = usePageShare(threadId, message.id, message.publishedPage);- const tools = { version, point, share, ready: Boolean(current), fullScreen: { open: fullScreen, toggle: () => { point.stop(); setFullScreen((open) => !open); } } };+ const tools = { version, point, share, room, ready: Boolean(current), fullScreen: { open: fullScreen, toggle: () => { point.stop(); setFullScreen((open) => !open); } } };const reloadNow = () => {setProblem(null);@@ -234,6 +237,7 @@ function AppRow({ botId, botName, threadId, message, payload, pool }: {data-app-state={state}data-app-source={payload.source}{...(page ? { "data-app-rev": rev } : {})}+ {...(room ? { "data-app-room": "" } : {})}className={cn("w-full text-start", WIDTH)}><div className={cn(bordered ? APP_SURFACE : "w-full")}>@@ -248,7 +252,7 @@ function AppRow({ botId, botName, threadId, message, payload, pool }: {bordered={bordered}/>{page && <PageToolbar {...tools} className={bordered ? "px-4 pb-3" : "pb-2"} />}- {page && <PageNotes version={version} point={point} share={share} className={bordered ? "px-4 pb-3" : "pb-2"} />}+ {page && <PageNotes version={version} point={point} share={share} room={room} className={bordered ? "px-4 pb-3" : "pb-2"} />}{infoOpen && <AppInfo id={infoId} network={payload.network ?? { connect: [], resources: [] }} bytes={payload.bytes ?? 0} bordered={bordered} />}{collapsed && (<div className={cn("flex", bordered ? "px-4 pb-3.5" : "pb-2")}>diff --git a/src/components/app/PageTools.tsx b/src/components/app/PageTools.tsxindex 20a0d97f6e..3e91d2d82d 100644--- a/src/components/app/PageTools.tsx+++ b/src/components/app/PageTools.tsx@@ -123,10 +123,12 @@ export interface PageToolsProps {share: ReturnType<typeof usePageShare>;ready: boolean;fullScreen: { open: boolean; toggle(): void };+ /** Shown in a room: view-only, so no Point and no Share. */+ room?: boolean;}/** The card's toolbar: ‹ v2 › and Updated on the left; Point, Share, Open in new tab and Full screen on the right. */-export function PageToolbar({ version, point, share, ready, fullScreen, className }: PageToolsProps & { className?: string }) {+export function PageToolbar({ version, point, share, ready, fullScreen, room, className }: PageToolsProps & { className?: string }) {const label = version.latest ? t("chat.preview.version", { n: version.rev + 1 }) : t("chat.preview.versionOf", { n: version.rev + 1, count: version.last + 1 });const busy = share.share.kind === "busy";return (@@ -141,13 +143,15 @@ export function PageToolbar({ version, point, share, ready, fullScreen, classNam{version.flash && <span role="status" data-page-updated className="ms-1 rounded-full bg-accent/15 px-2 py-px font-medium text-accent-text">{t("chat.preview.updated")}</span>}</div><div className="ms-auto flex items-center gap-1">- <button type="button" aria-pressed={point.pointing} onClick={point.toggle} disabled={!ready} title={t("chat.preview.pointHint")}- className={cn(ASK_CHIP, point.pointing ? ASK_CHIP_PICKED : ASK_CHIP_IDLE)}>- <Crosshair size={14} />{t("chat.preview.point")}- </button>- <button type="button" onClick={() => void share.run(version.rev)} disabled={busy} className={cn(ASK_CHIP, ASK_CHIP_IDLE)}>- {busy ? <Loader2 size={14} className="animate-spin" /> : <Share2 size={14} />}{t("chat.preview.share")}- </button>+ {!room && <>+ <button type="button" aria-pressed={point.pointing} onClick={point.toggle} disabled={!ready} title={t("chat.preview.pointHint")}+ className={cn(ASK_CHIP, point.pointing ? ASK_CHIP_PICKED : ASK_CHIP_IDLE)}>+ <Crosshair size={14} />{t("chat.preview.point")}+ </button>+ <button type="button" onClick={() => void share.run(version.rev)} disabled={busy} className={cn(ASK_CHIP, ASK_CHIP_IDLE)}>+ {busy ? <Loader2 size={14} className="animate-spin" /> : <Share2 size={14} />}{t("chat.preview.share")}+ </button>+ </>}<button type="button" className={TOOL} disabled={!share.url} onClick={() => share.url && void openExternalLink(share.url)}aria-label={t("chat.preview.openTab")} title={share.url ? t("chat.preview.openTab") : t("chat.preview.openTabNeedsLink")}><ArrowUpRight size={15} />@@ -164,7 +168,7 @@ export function PageToolbar({ version, point, share, ready, fullScreen, classNam/** Under the toolbar: the public link with Copy, Update link and Unpublish once shared, or why sharing failed; the Point* hint. */-export function PageNotes({ version, point, share, className }: Pick<PageToolsProps, "version" | "point" | "share"> & { className?: string }) {+export function PageNotes({ version, point, share, room, className }: Pick<PageToolsProps, "version" | "point" | "share" | "room"> & { className?: string }) {const { dispatch } = useStore();const { state: copied, copy } = useCopyFeedback(share.url ?? "");const state = share.share;@@ -179,9 +183,11 @@ export function PageNotes({ version, point, share, className }: Pick<PageToolsPr<button type="button" onClick={copy} className={cn(ASK_CHIP, ASK_CHIP_IDLE)}>{copied === "copied" ? <Check size={14} /> : <Copy size={14} />}{t(copied === "copied" ? "chat.page.copied" : "chat.page.copyLink")}</button>- <button type="button" onClick={() => void share.run(version.rev)} disabled={state.kind === "busy"} className={cn(ASK_CHIP, ASK_CHIP_IDLE)}>- {t("chat.preview.republish")}- </button>+ {!room && (+ <button type="button" onClick={() => void share.run(version.rev)} disabled={state.kind === "busy"} className={cn(ASK_CHIP, ASK_CHIP_IDLE)}>+ {t("chat.preview.republish")}+ </button>+ )}<button type="button" onClick={() => void share.unpublish()} disabled={state.kind === "unpublishing"} className={cn(ASK_CHIP, ASK_CHIP_IDLE)}>{state.kind === "unpublishing" ? <Loader2 size={14} className="animate-spin" /> : <Trash2 size={14} />}{t("chat.page.unpublish")}</button>@@ -232,7 +238,7 @@ export function PageFullScreen(props: PageToolsProps & {<div ref={closer} className="flex flex-col gap-2 border-b border-hairline/40 px-4 pb-3 pt-3"><div className="truncate text-[15px] font-semibold text-ink" title={props.title}><bdi dir="auto">{props.title}</bdi></div><PageToolbar {...props} />- <PageNotes version={props.version} point={point} share={props.share} />+ <PageNotes version={props.version} point={point} share={props.share} room={props.room} /></div><div className={cn("relative min-h-0 flex-1 bg-app", point.pointing && "ring-2 ring-inset ring-accent/60")}><AppFrame doc={props.doc} botId={props.botId} threadId={props.threadId} title={props.title} height={600} handle={props.handle}diff --git a/src/components/widget/WidgetMessage.test.ts b/src/components/widget/WidgetMessage.test.tsindex 609926465c..c4843f57c8 100644--- a/src/components/widget/WidgetMessage.test.ts+++ b/src/components/widget/WidgetMessage.test.ts@@ -30,13 +30,14 @@ const fetchMock = vi.fn<(path: string, init?: RequestInit) => Promise<Response>>const openExternal = vi.fn(async (_url: string) => {});const flushBotPatches = vi.fn<(botId: string) => Promise<null>>();const store = { state: {}, dispatch: vi.fn(), flushBotPatches } as unknown as ReturnType<typeof useStore>;-const inStore = (message: Message) => createElement(BotEditorStore, { value: store, children: createElement(WidgetMessage, { botId: "scout", threadId: "t1", message }) });+const inStore = (message: Message, viewOnly?: boolean) =>+ createElement(BotEditorStore, { value: store, children: createElement(WidgetMessage, { botId: "scout", threadId: "t1", message, ...(viewOnly ? { viewOnly } : {}) }) });let host: HTMLDivElement;let root: Root;-function mount(message: Message) {- act(() => root.render(inStore(message)));+function mount(message: Message, viewOnly?: boolean) {+ act(() => root.render(inStore(message, viewOnly)));}const find = <T extends Element = HTMLElement>(selector: string) => host.querySelector<T>(selector);@@ -514,6 +515,19 @@ describe("pressing", () => {expect(line.querySelector("svg.lucide-x")).not.toBeNull();});+ it("in a room, locks every press and field, still opens a link, and posts nothing", async () => {+ mount(row(sample("routineForm")), true);+ expect(find('[data-widget="w1"]')!.getAttribute("data-widget-state")).toBe("view-only");+ const create = button("Create routine")!;+ expect(create.disabled).toBe(true);+ await press(create);+ for (const control of all<HTMLInputElement | HTMLButtonElement>("[data-widget-field]")) expect(control.matches(":disabled, [aria-disabled=true]"), control.outerHTML.slice(0, 80)).toBe(true);+ mount(row(sample("kitchenSink")), true);+ await press(button("Open the docs")!);+ expect(openExternal).toHaveBeenLastCalledWith("https://mausbot.com/docs");+ expect(fetchMock).not.toHaveBeenCalled();+ });+it("opens an open_url link on this device and posts nothing", async () => {mount(row(sample("sources")));const link = find<HTMLButtonElement>('[role="listitem"] > button')!;diff --git a/src/components/widget/WidgetMessage.tsx b/src/components/widget/WidgetMessage.tsxindex 78e73c13b8..287ba31e11 100644--- a/src/components/widget/WidgetMessage.tsx+++ b/src/components/widget/WidgetMessage.tsx@@ -37,7 +37,8 @@ function isEmpty(field: WidgetField, values: WidgetValues, other: WidgetOther):return field.type === "Checkbox" ? value !== true : typeof value !== "string" || !value.trim();}-export function WidgetMessage({ botId, threadId, message }: { botId: string; threadId?: string; message: Message }) {+/** `viewOnly`: shown in a room, where a press would speak for everyone; links and thread jumps still open. */+export function WidgetMessage({ botId, threadId, message, viewOnly }: { botId: string; threadId?: string; message: Message; viewOnly?: boolean }) {const simple = !useAdvancedMode();const serverCard = (message as { serverCard?: true }).serverCard === true;const locale = activeLocale();@@ -48,10 +49,10 @@ export function WidgetMessage({ botId, threadId, message }: { botId: string; thr: null;}// Replacing a widget renumbers node ids, so a new revision remounts the card.- return <WidgetCard key={payload.rev ?? 0} botId={botId} threadId={threadId} messageId={message.id} payload={payload} />;+ return <WidgetCard key={payload.rev ?? 0} botId={botId} threadId={threadId} messageId={message.id} payload={payload} viewOnly={viewOnly === true} />;}-function WidgetCard({ botId, threadId, messageId, payload }: { botId: string; threadId?: string; messageId: string; payload: WidgetPayload }) {+function WidgetCard({ botId, threadId, messageId, payload, viewOnly }: { botId: string; threadId?: string; messageId: string; payload: WidgetPayload; viewOnly: boolean }) {const root = payload.root;const { state, dispatch, flushBotPatches } = useStore();const showThreads = useShowThreads();@@ -127,7 +128,7 @@ function WidgetCard({ botId, threadId, messageId, payload }: { botId: string; thif (target) openThread(dispatch, target, state, showThreads);return;}- if (settled) return;+ if (settled || viewOnly) return;let sending: WidgetValues | undefined;let sendingOther: WidgetOther | undefined;if (entry.tone !== "cancel") {@@ -204,7 +205,7 @@ function WidgetCard({ botId, threadId, messageId, payload }: { botId: string; thsetOtherEdits((current) => ({ ...current, [name]: text }));if (problem?.field === name) setProblem(undefined);},- locked: isSettled || pending !== undefined,+ locked: isSettled || pending !== undefined || viewOnly,invalid: problem?.field,errorId,fields,@@ -229,7 +230,7 @@ function WidgetCard({ botId, threadId, messageId, payload }: { botId: string; tharia-label={name}aria-busy={pending !== undefined || undefined}data-widget={messageId}- data-widget-state={settled ? "settled" : pending !== undefined ? "sending" : "live"}+ data-widget-state={settled ? "settled" : viewOnly ? "view-only" : pending !== undefined ? "sending" : "live"}data-widget-compact={compact || undefined}className={cn("w-full text-start", WIDTH[widgetString(root, "size") ?? "lg"] ?? WIDTH.lg)}>