Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(apps): keep a change an MCP app card made on its row (#4532)
AdityaUmalee69a52ff933a
diff --git a/server/chat-apps-mcp.test.ts b/server/chat-apps-mcp.test.tsindex 5a5769663e..a318864c28 100644--- a/server/chat-apps-mcp.test.ts+++ b/server/chat-apps-mcp.test.ts@@ -204,6 +204,33 @@ describe("rpc", () => {expect(await rpc("m1", "tools/call", { name: "wipe_board", arguments: {} })).toMatchObject({ status: 200 });}, 30_000);+ it("keeps a change the card made itself on its row, so a reopened conversation shows it done (#4532)", async () => {+ const { record, rpc, row } = setup({ approval: "full" });+ await record();+ // looking and the app's own plumbing are not changes+ await rpc("m1", "tools/call", { name: "show_board", arguments: { cards: 5 } });+ await rpc("m1", "tools/call", { name: "save_board", arguments: { state: "s" } });+ expect(row("m1").app.done).toBeUndefined();+ expect(await rpc("m1", "tools/call", { name: "paint_board", arguments: { color: "blue" } })).toMatchObject({ status: 200 });+ expect(row("m1").app.done).toEqual({ tool: "Paint board", text: "Painted blue", at: expect.any(Number) });+ // the row keeps everything else it had+ expect(row("m1").app).toMatchObject({ source: "mcp", mcp: { server: "board", tool: "show_board" } });+ }, 30_000);++ it("keeps no secret from the result in the note", async () => {+ const { record, rpc, row } = setup({ approval: "full" });+ await record();+ await rpc("m1", "tools/call", { name: "paint_board", arguments: { color: "ghp_abcdefghijklmnopqrstuvwxyz0123456789" } });+ expect(JSON.stringify(row("m1").app.done)).not.toContain("ghp_abcdefghijklmnopqrstuvwxyz0123456789");+ }, 30_000);++ it("records nothing when the change is declined", async () => {+ const { record, rpc, row } = setup();+ await record();+ expect(await rpc("m1", "tools/call", { name: "paint_board", arguments: { color: "red" } })).toMatchObject({ status: 403 });+ expect(row("m1").app.done).toBeUndefined();+ }, 30_000);+it("refuses a tool the server lacks, one its view may not call, one outside the selection, and bad arguments", async () => {const { record, rpc } = setup({ scope: { allow: ["mcp:board:show_board", "mcp:board:peek_board"] } });await record();diff --git a/server/chat-apps-mcp.ts b/server/chat-apps-mcp.tsindex dba14ad179..9012a23d70 100644--- a/server/chat-apps-mcp.ts+++ b/server/chat-apps-mcp.ts@@ -1,8 +1,8 @@import { approvalModeFor } from "../shared/approval-mode.ts";-import { APP_LIMITS, APP_MIME, appBlockedText, mcpAppFallbackText, oneLine, type AppBlockedReason, type AppCan, type AppDocument, type AppPayload, type AppToolResult } from "../shared/app.ts";+import { APP_LIMITS, APP_MIME, appBlockedText, appDoneOf, mcpAppFallbackText, oneLine, type AppBlockedReason, type AppCan, type AppDocument, type AppDoneState, type AppPayload, type AppToolResult } from "../shared/app.ts";import { mcpAppNetwork } from "../shared/app-frame/csp.ts";import { allowsTool, canUseMcpServer } from "../shared/tool-scope.ts";-import { rowRate, type ChatApps } from "./chat-apps.ts";+import { appRow, rowRate, type ChatApps } from "./chat-apps.ts";import type { AgentCardResult } from "./chat-widgets.ts";import type { McpServerSpec } from "./contracts.ts";import { McpAppCatalog, mcpServerConfigHash } from "./mcp-app-catalog.ts";@@ -97,6 +97,19 @@ type ResourceRead =| { ok: true; html: string; ui: Json | undefined }| { ok: false; reason: AppBlockedReason };+function mcpToolTitle(definition: Json): string {+ const name = String(definition.name);+ const annotations = isRecord(definition.annotations) ? definition.annotations : {};+ return oneLine(String((typeof definition.title === "string" && definition.title) || (typeof annotations.title === "string" && annotations.title) || name)).slice(0, APP_LIMITS.title) || name.slice(0, APP_LIMITS.title);+}++/** The note is stored and shown, so a secret in the result never is; a link a secret was found in is dropped. */+function redactedDone(done: AppDoneState): AppDoneState {+ const { text, url, ...rest } = done;+ const clean = text && redactSecretsInText(text);+ return { ...rest, ...(clean ? { text: clean } : {}), ...(url && redactSecretsInText(url) === url ? { url } : {}) };+}+const rpcError = (status: number, code: number, message: string, extra: Json = {}): McpRpcAnswer => ({ status, body: { error: { code, message }, ...extra } });export function createChatAppsMcp(deps: ChatAppsMcpDeps): ChatAppsMcp {@@ -182,8 +195,7 @@ export function createChatAppsMcp(deps: ChatAppsMcpDeps): ChatAppsMcp {const read: ResourceRead = spec ? await readResource(name, spec, resourceUri) : { ok: false, reason: "signed-out" };const info = isRecord(input.serverInfo) ? input.serverInfo : (spec ? await connections.serverInfo(name, spec) : undefined);const serverTitle = oneLine(String((typeof info?.title === "string" && info.title) || (typeof info?.name === "string" && info.name) || name)).slice(0, 80);- const annotations = isRecord(definition.annotations) ? definition.annotations : {};- const toolTitle = oneLine(String((typeof definition.title === "string" && definition.title) || (typeof annotations.title === "string" && annotations.title) || definition.name)).slice(0, APP_LIMITS.title) || definition.name.slice(0, APP_LIMITS.title);+ const toolTitle = mcpToolTitle(definition);const toolResult: AppToolResult = {content: result.content,...(result.structuredContent !== undefined ? { structuredContent: result.structuredContent } : {}),@@ -306,7 +318,13 @@ export function createChatAppsMcp(deps: ChatAppsMcpDeps): ChatAppsMcp {|| approvalOf(bot.id, request.threadId) === "full";if (!runs) return rpcError(403, -32000, APP_WRITE_DECLINED);const result = await connections.request(name, server, "tools/call", { name: tool.name, arguments: callArgs }, AbortSignal.timeout(RPC_CALL_MS), extension);- return { status: 200, body: isRecord(result) ? result : { content: [] } };+ const body = isRecord(result) ? result : { content: [] };+ // A change the card made itself stays on its row, so the reopened conversation says it is done.+ if (visibility.includes("model") && annotations.readOnlyHint !== true && body.isError !== true) {+ const row = appRow(store, request.threadId, request.row.id);+ if (row) store.patchMessage(request.threadId, row.id, { app: { ...row.app, done: redactedDone(appDoneOf(mcpToolTitle(tool), body, now())) } });+ }+ return { status: 200, body };}async function rpc(request: McpRpcRequest): Promise<McpRpcAnswer> {diff --git a/shared/app.test.ts b/shared/app.test.tsindex 04d302c946..6da3262e83 100644--- a/shared/app.test.ts+++ b/shared/app.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import { APP_LIMITS, appBlockedText, htmlFallbackText, htmlVisibleText, mcpAppFallbackText, parseShowHtmlInput, parseUpdateHtmlInput, utf8Bytes, wrapHtmlFragment } from "./app.ts";+import { APP_LIMITS, appBlockedText, appDoneOf, htmlFallbackText, htmlVisibleText, mcpAppFallbackText, parseShowHtmlInput, parseUpdateHtmlInput, utf8Bytes, wrapHtmlFragment } from "./app.ts";describe("parseShowHtmlInput", () => {it("keeps a whole document as written, trimmed", () => {@@ -88,3 +88,24 @@ describe("utf8Bytes", () => {for (const text of ["", "abc", "é", "€", "😀", "a😀é€", "\ud800 lone"]) expect(utf8Bytes(text), text).toBe(new TextEncoder().encode(text).length);});});++describe("appDoneOf", () => {+ const text = (value: string) => ({ type: "text", text: value });+ it("takes the plain text as one line and its first https link", () => {+ expect(appDoneOf("Create issue", { content: [text("Created issue #12\n https://github.com/o/r/issues/12 (label not applied)")] }, 5))+ .toEqual({ tool: "Create issue", text: "Created issue #12 https://github.com/o/r/issues/12 (label not applied)", url: "https://github.com/o/r/issues/12", at: 5 });+ });+ it("shows no raw JSON: a JSON block gives only its html_url, else its url", () => {+ expect(appDoneOf("Create issue", { content: [text('{"url":"https://api.github.com/repos/o/r/issues/12","html_url":"https://github.com/o/r/issues/12","number":12}')] }, 1))+ .toEqual({ tool: "Create issue", url: "https://github.com/o/r/issues/12", at: 1 });+ expect(appDoneOf("Create issue", { content: [text('{"id":"1","url":"https://github.com/o/r/issues/13"}')] }, 1))+ .toEqual({ tool: "Create issue", url: "https://github.com/o/r/issues/13", at: 1 });+ expect(appDoneOf("Create issue", { content: [], structuredContent: { html_url: "https://github.com/o/r/pull/7" } }, 1).url).toBe("https://github.com/o/r/pull/7");+ });+ it("keeps only https links and clips long text", () => {+ const done = appDoneOf("Run", { content: [text(`see http://x.test/a and javascript:alert(1) ${"y".repeat(400)}`)], structuredContent: { url: "javascript:alert(1)" } }, 1);+ expect(done.url).toBeUndefined();+ expect(done.text!.length).toBeLessThanOrEqual(APP_LIMITS.doneText);+ expect(appDoneOf("Run", { content: [] }, 1)).toEqual({ tool: "Run", at: 1 });+ });+});diff --git a/shared/app.ts b/shared/app.tsindex 2418fe1977..540789879d 100644--- a/shared/app.ts+++ b/shared/app.ts@@ -18,6 +18,8 @@ export const APP_LIMITS = {messageText: 4_000,/** ui/update-model-context text, stored per row. */contextText: 4_000,+ /** The result line of an app row's "Done" note. */+ doneText: 300,/** An MCP server's UI resource, decoded. */mcpHtmlBytes: 2 * 1024 * 1024,/** tools/call arguments on the rpc route. */@@ -51,6 +53,18 @@ export interface AppContextState {delivered: boolean;}+/** The last change an MCP app made from its own card: a tool the bot could call too, not read-only, that did+ * not fail. Shown under the card, so a reopened conversation does not look as if it was never sent. */+export interface AppDoneState {+ /** the tool's title, else its name */+ tool: string;+ /** the result's plain text, one line */+ text?: string;+ /** an https link the result names (html_url, else url) */+ url?: string;+ at: number;+}+export interface AppMcpRef {/** the mount name in config.json mcpServers */server: string;@@ -92,6 +106,7 @@ export interface AppPayload {/** The latest ui/update-model-context, delivered with the person's next* message in this thread. */context?: AppContextState;+ done?: AppDoneState;/** Why the document could not be stored or read when the row was written* (`too-large`, or an MCP server that was signed out or unreachable). The* row is still written, with its text. */@@ -344,6 +359,27 @@ export function mcpAppFallbackText(serverTitle: string, toolTitle: string, resulreturn clip(excerpt ? `${head}\n${excerpt}` : head, APP_LIMITS.fallback);}+const httpsLink = (value: unknown): string | undefined =>+ typeof value === "string" && value.length <= 2_048 && /^https:\/\/[^\s"'<>]+$/.test(value) ? value : undefined;+const namedLink = (value: unknown): string | undefined => (isRecord(value) ? httpsLink(value.html_url) ?? httpsLink(value.url) : undefined);++/** A JSON text block gives only its link; plain text gives the note's line and, failing a named link, its first+ * https link. */+export function appDoneOf(tool: string, result: { content?: unknown; structuredContent?: unknown }, at: number): AppDoneState {+ let url = namedLink(result.structuredContent);+ let text: string | undefined;+ for (const block of Array.isArray(result.content) ? result.content : []) {+ if (!isRecord(block) || block.type !== "text" || typeof block.text !== "string") continue;+ const raw = block.text.trim();+ let parsed: unknown;+ try { parsed = /^[{[]/.test(raw) ? JSON.parse(raw) : undefined; } catch { parsed = undefined; }+ if (parsed !== undefined) { url ??= namedLink(parsed); continue; }+ url ??= httpsLink(/https:\/\/[^\s"'<>)\]]+/.exec(raw)?.[0]);+ text ??= clip(oneLine(raw), APP_LIMITS.doneText) || undefined;+ }+ return { tool, ...(text ? { text } : {}), ...(url ? { url } : {}), at };+}+export function appBlockedText(reason: AppBlockedReason, server?: string): string {const name = server?.trim() || "This app's server";switch (reason) {diff --git a/src/components/app/AppChrome.tsx b/src/components/app/AppChrome.tsxindex 6ae9258d90..fe6c169b1a 100644--- a/src/components/app/AppChrome.tsx+++ b/src/components/app/AppChrome.tsx@@ -1,8 +1,9 @@import { useEffect, useState, type ReactNode } from "react";-import { AppWindow, CircleAlert, Info, Loader2, RotateCw } from "lucide-react";+import { AppWindow, CircleAlert, CircleCheck, Info, Loader2, RotateCw } from "lucide-react";import { cn } from "@/lib/cn";import { t } from "@/lib/i18n";-import type { AppNetwork } from "../../../shared/app";+import { openExternalLink } from "@/lib/app-links";+import type { AppDoneState, AppNetwork } from "../../../shared/app";import { ASK_CHIP, ASK_CHIP_IDLE, ASK_QUIET_BUTTON } from "../AskCard";export const APP_SURFACE = "w-full overflow-hidden rounded-2xl bg-composer ring-1 ring-composer-ring";@@ -109,6 +110,17 @@ export function AppStrip({ text, action, bordered, tone = "warning" }: {);}+/** The last change the card made itself, kept on the row: a reopened conversation shows it was sent. */+export function AppDone({ done, bordered }: { done: AppDoneState; bordered: boolean }) {+ return (+ <div role="status" data-app-done className={cn("flex items-center gap-2 border-t border-ink/[0.12] py-2.5 text-[13px] leading-[18px] text-ink-secondary", bordered ? "mx-4" : "mt-2")}>+ <CircleCheck aria-hidden="true" size={14} className="shrink-0 text-success" />+ <span dir="auto" className="min-w-0 flex-1 break-words">{t("app.done", { tool: done.tool })}{done.text ? ` · ${done.text}` : ""}</span>+ {done.url && <button type="button" onClick={() => openExternalLink(done.url!)} className={ASK_QUIET_BUTTON}>{t("app.doneOpen")}</button>}+ </div>+ );+}+/** Keeps the frame's height while no frame runs, so the transcript does not jump. */export function AppPlaceholder({ height, loading, open, label, children }: {height: number;diff --git a/src/components/app/AppMessage.test.ts b/src/components/app/AppMessage.test.tsindex 9fbd1b3447..ebe9e858e4 100644--- a/src/components/app/AppMessage.test.ts+++ b/src/components/app/AppMessage.test.ts@@ -125,6 +125,18 @@ describe("the row before its frame runs", () => {expect(renderToStaticMarkup(view(row(mcpPayload())))).toContain("App from Excalidraw");});+ it("shows the last change the card made itself, so a reopened conversation does not look unsent (#4532)", async () => {+ expect(renderToStaticMarkup(view(row(mcpPayload())))).not.toContain("data-app-done");+ const done = { tool: "Create issue", text: "Created issue #12", url: "https://github.com/o/r/issues/12", at: 2 };+ const markup = renderToStaticMarkup(view(row(mcpPayload({ done }))));+ expect(markup).toContain("Done: Create issue · Created issue #12");+ expect(markup.indexOf("data-app-done")).toBeGreaterThan(markup.indexOf("data-app-box"));+ expect(renderToStaticMarkup(view(row(mcpPayload({ done: { tool: "Create issue", at: 2 } }))))).not.toMatch(/data-app-done[^]*<button/);+ await mount(row(mcpPayload({ done })));+ await act(async () => { find<HTMLButtonElement>("[data-app-done] button")!.click(); });+ expect((window as unknown as { ogb: { openExternal: ReturnType<typeof vi.fn> } }).ogb.openExternal).toHaveBeenCalledWith("https://github.com/o/r/issues/12");+ });+it("reads as its text when there is no payload", () => {const markup = renderToStaticMarkup(view(row(undefined)));expect(markup).not.toContain("data-app=");diff --git a/src/components/app/AppMessage.tsx b/src/components/app/AppMessage.tsxindex 17add9507d..e3b31c0cad 100644--- a/src/components/app/AppMessage.tsx+++ b/src/components/app/AppMessage.tsx@@ -7,7 +7,7 @@ import { appBlockedText } from "../../../shared/app";import { APP_FRAME_LIMITS } from "../../../shared/app-frame/bridge";import { AppDocumentError, fetchAppDocument, type AppFetchFailure } from "./app-api";import { APP_POOL_LIMITS, useAppPoolSlot, type AppPool } from "./app-pool";-import { AppHeader, AppInfo, AppOpenButton, AppPlaceholder, AppStrip, APP_SURFACE } from "./AppChrome";+import { AppDone, AppHeader, AppInfo, AppOpenButton, AppPlaceholder, AppStrip, APP_SURFACE } from "./AppChrome";import { AppFrame, type AppFrameHandle, type AppFrameProblem } from "./AppFrame";import { PAGE_HEIGHT, PageFullScreen, PageNotes, PageToolbar, usePagePoint, usePageShare, usePageVersion } from "./PageTools";@@ -253,6 +253,7 @@ function AppRow({ botId, botName, threadId, message, payload, pool }: {</div>)}{body}+ {payload.done && <AppDone done={payload.done} bordered={bordered} />}{strip && <AppStrip text={strip.text} action={strip.action} bordered={bordered} />}</div>{page && fullScreen && current && (diff --git a/src/locales/en.json b/src/locales/en.jsonindex 611cb6fc76..43aefa44a7 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -7251,6 +7251,8 @@"page.broken.reload": "Reload","app.open": "Open app","app.openAgain": "Open again",+ "app.done": "Done: {tool}",+ "app.doneOpen": "Open","app.loading": "Opening the app","app.strip.signIn": "Sign in to {server} again","app.strip.signInAction": "Sign in",