Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

Show local tok/s on turns; handshake MCP App ui/initialize

justrach490f1cd2534d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index fe2beaf4..7a4c9f31 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -13,6 +13,8 @@ current is part of cutting a release.
## Unreleased
- Desktop ACP workers can park after a quiet period (`GRAFF_ACP_IDLE_MS`, default 30s) and `--resume` with the saved cache id. Parking is skipped while a prompt or `session/idle` subscriber is live; tab close still reaps immediately.
+- Turn chrome shows local tok/s while writing (and at settle); MCP tools/Apps wait instead of looking like slow generation (#1017).
+- MCP App frames answer `ui/initialize`; app-initiated `tools/call` still fails until the host forwards ACP (#1018).
- GUI usage replies show grouped metrics and plan limits; inline editing keeps the message bubble and grows with its text. Subtle transcript reveals respect reduced motion.
- `#1013`: keep the first answer after a no-tool retry without allowing older turns to replace a later answer (ADR 0139).
- GUI usage replies show grouped metrics and plan limits; inline editing keeps the message bubble and grows with its text. Subtle transcript reveals respect reduced motion.
diff --git a/apps/native/components/site/SnapshotView.tsx b/apps/native/components/site/SnapshotView.tsx
index a576e0c9..027e6dec 100644
--- a/apps/native/components/site/SnapshotView.tsx
+++ b/apps/native/components/site/SnapshotView.tsx
@@ -2,6 +2,7 @@
import {useState, useEffect, useRef} from "react";
import {validAppId} from "@/lib/mcp-apps";
+import {hostReply} from "@/lib/mcp-apps-host";
import motion from "./transcript-motion.module.css";
/** One saved HTML snapshot shown inside the transcript. The two kinds differ
@@ -37,6 +38,17 @@ export default function SnapshotView({kind, id}: {kind: SnapshotKind; id: string
const observer = new IntersectionObserver(([entry]) => setNearby(entry.isIntersecting), {rootMargin:'80px'});
observer.observe(host.current); return () => observer.disconnect();
}, [kind]);
+ useEffect(() => {
+ if (kind !== "mcp-app") return;
+ const onMessage = (event: MessageEvent) => {
+ if (event.source === null || event.origin !== window.location.origin) return;
+ const reply = hostReply(event.data);
+ if (!reply) return;
+ (event.source as Window).postMessage(reply, event.origin);
+ };
+ window.addEventListener("message", onMessage);
+ return () => window.removeEventListener("message", onMessage);
+ }, [kind]);
if (!validAppId(id)) return null;
const {label, title, src, sandbox, allow} = KINDS[kind];
const iframe = (kind !== "view" || nearby) && <iframe title={title} src={src(id)} sandbox={sandbox} allow={allow}
diff --git a/apps/native/components/site/TurnActivity.tsx b/apps/native/components/site/TurnActivity.tsx
index bd7cfa31..3a9d92c2 100644
--- a/apps/native/components/site/TurnActivity.tsx
+++ b/apps/native/components/site/TurnActivity.tsx
@@ -25,6 +25,6 @@ export default function TurnActivity({ turn, snapshot }: { turn: AssistantTurn;
}
return <div data-turn-activity={activity.state} className={`mt-4 flex flex-wrap items-center gap-x-2 gap-y-1 text-[12px] ${activity.state === "error" ? "text-red" : "text-ink-3"}`}>
<span aria-hidden="true">{activity.state === "snapshot" ? "○" : activity.state === "error" ? "!" : activity.label === "Stopped" ? "■" : "✓"}</span>
- <span role="status" aria-live="polite">{activity.label}</span>{activity.detail && <><span aria-hidden="true">·</span><span data-activity-detail className="tabular-nums">{activity.detail}</span></>}
+ <span role="status" aria-live="polite">{activity.label}</span>{activity.detail && <><span aria-hidden="true">·</span><span data-activity-detail data-tok-rate={activity.detail.includes("tok/s") ? activity.detail : undefined} className="tabular-nums">{activity.detail}</span></>}
</div>;
}
diff --git a/apps/native/lib/mcp-apps-host.test.ts b/apps/native/lib/mcp-apps-host.test.ts
new file mode 100644
index 00000000..60c4122b
--- /dev/null
+++ b/apps/native/lib/mcp-apps-host.test.ts
@@ -0,0 +1,18 @@
+import { expect, test } from "bun:test";
+import { hostReply, MCP_APPS_PROTOCOL } from "./mcp-apps-host";
+
+test("ui/initialize answers with the extension protocol version", () => {
+ expect(hostReply({ jsonrpc: "2.0", id: 1, method: "ui/initialize" })).toEqual({
+ jsonrpc: "2.0", id: 1, result: { protocolVersion: MCP_APPS_PROTOCOL },
+ });
+});
+
+test("app-initiated tools/call is refused until the host forwards ACP", () => {
+ const reply = hostReply({ jsonrpc: "2.0", id: 2, method: "tools/call", params: { name: "search" } });
+ expect(reply).toMatchObject({ jsonrpc: "2.0", id: 2, error: { code: -32000 } });
+});
+
+test("non-RPC traffic is ignored", () => {
+ expect(hostReply("ready")).toBeNull();
+ expect(hostReply({ method: "ui/initialize" })).toBeNull();
+});
diff --git a/apps/native/lib/mcp-apps-host.ts b/apps/native/lib/mcp-apps-host.ts
new file mode 100644
index 00000000..53cfeb25
--- /dev/null
+++ b/apps/native/lib/mcp-apps-host.ts
@@ -0,0 +1,24 @@
+/** MCP Apps extension dialect (ui/* over postMessage). Snapshot HTML still
+ * renders without this; app-initiated tools stay refused until the host
+ * forwards them through ACP. Spec: 2026-01-26. */
+
+export const MCP_APPS_PROTOCOL = "2026-01-26";
+
+type JsonRpc = { jsonrpc?: string; id?: unknown; method?: string; params?: unknown };
+
+export type HostReply =
+ | { jsonrpc: "2.0"; id: unknown; result: unknown }
+ | { jsonrpc: "2.0"; id: unknown; error: { code: number; message: string } };
+
+export function hostReply(data: unknown): HostReply | null {
+ if (!data || typeof data !== "object") return null;
+ const msg = data as JsonRpc;
+ if (msg.jsonrpc !== "2.0" || typeof msg.method !== "string" || msg.id === undefined) return null;
+ if (msg.method === "ui/initialize") {
+ return { jsonrpc: "2.0", id: msg.id, result: { protocolVersion: MCP_APPS_PROTOCOL } };
+ }
+ if (msg.method === "tools/call" || msg.method.startsWith("ui/")) {
+ return { jsonrpc: "2.0", id: msg.id, error: { code: -32000, message: "Host-mediated MCP App tool calls are not enabled yet." } };
+ }
+ return null;
+}
diff --git a/apps/native/lib/turn-activity.test.ts b/apps/native/lib/turn-activity.test.ts
index 5f8a9e3c..86b76766 100644
--- a/apps/native/lib/turn-activity.test.ts
+++ b/apps/native/lib/turn-activity.test.ts
@@ -69,3 +69,18 @@ test("elapsed work freezes at completion across remounts and repeated finalizati
expect(workDuration(60)).toBe("1m 0s");
expect(workDuration(3601)).toBe("1h 0m");
});
+
+test("streaming text reports tok/s; tools and MCP Apps wait instead", () => {
+ const writing = {
+ ...emptyTurn(), status: "streaming" as const, text: "x".repeat(80), connected: true,
+ startedAt: 0, lastUpdateAt: 1000, activityKind: "agent_message_chunk",
+ };
+ expect(turnActivity(writing, 1000).detail).toMatch(/tok\/s/);
+ const tools = applyAcpUpdate({ ...writing, text: "x".repeat(80) }, { sessionUpdate: "tool_call", toolCallId: "bash", kind: "execute", status: "in_progress" });
+ expect(turnActivity(tools, 1000).detail).toBe("Running 1 tool…");
+ expect(turnActivity(tools, 1000).detail).not.toMatch(/tok\/s/);
+ const app = { ...tools, tools: [{ ...tools.tools[0], mcpAppId: "a".repeat(32) }] };
+ expect(turnActivity(app, 1000).detail).toBe("Waiting on MCP App…");
+ const done = finishAcpTurn({ ...writing, startedAt: 0 }, 1000);
+ expect(turnActivity(done, 1000).detail).toMatch(/tok\/s/);
+});
diff --git a/apps/native/lib/turn-activity.ts b/apps/native/lib/turn-activity.ts
index 5d3420f6..92207bcf 100644
--- a/apps/native/lib/turn-activity.ts
+++ b/apps/native/lib/turn-activity.ts
@@ -7,17 +7,42 @@ export function workDuration(seconds: number): string {
return `${Math.floor(total / 3600)}h ${Math.floor(total % 3600 / 60)}m`;
}
+/** Local estimate until a usage event lands: codepoints / 4. */
+export function estimateTokens(text: string): number {
+ if (!text) return 0;
+ return Math.max(1, Math.round([...text].length / 4));
+}
+
+export function tokPerSec(tokens: number, elapsedMs: number): string | null {
+ if (tokens < 1 || elapsedMs < 400) return null;
+ const rate = tokens / (elapsedMs / 1000);
+ if (!Number.isFinite(rate) || rate <= 0) return null;
+ return rate >= 10 ? `${Math.round(rate)} tok/s` : `${rate.toFixed(1)} tok/s`;
+}
+
+function joinDetail(...parts: (string | null | undefined)[]): string {
+ return parts.filter(Boolean).join(" · ");
+}
+
export function turnActivity(turn: AssistantTurn, now: number, opts?: { snapshot?: boolean }) {
if (turn.status === "snapshot" || opts?.snapshot) return { state: "snapshot", label: "Saved snapshot", detail: "Live status unknown", live: false };
const live = turn.status === "thinking" || turn.status === "streaming";
const end = live ? now : turn.endedAt ?? turn.lastUpdateAt ?? turn.startedAt ?? now;
- const duration = workDuration((end - (turn.startedAt ?? end)) / 1000);
+ const elapsedMs = Math.max(0, end - (turn.startedAt ?? end));
+ const duration = workDuration(elapsedMs / 1000);
const idle = Math.max(0, Math.floor((now - (turn.lastUpdateAt ?? turn.startedAt ?? now)) / 1000));
const running = turn.tools.filter(tool => tool.status === "running").length;
+ const mcpApps = turn.tools.filter(tool => tool.status === "running" && tool.mcpAppId).length;
const missing = turn.tools.filter(tool => tool.status === "interrupted").length;
+ const rate = running ? null : tokPerSec(estimateTokens(turn.text), elapsedMs);
if (turn.status === "error") return { state: "error", label: "Response interrupted", detail: `After ${duration}. ${turn.tools.some(tool => tool.status === "ok") ? "Completed tool results are kept. " : ""}Send a follow-up to continue.`, live: false };
if (turn.status === "ask") return { state: "input", label: "Waiting for your answer", detail: "", live: false };
- if (!live) return { state: "done", label: turn.stopReason === "cancelled" ? "Stopped" : `Worked for ${duration}`, detail: turn.stopReason === "cancelled" ? `After ${duration}` : missing ? `${missing} tool ${missing === 1 ? "result" : "results"} not received` : "", live: false };
- const detail = !turn.connected ? "Starting…" : running ? `Running ${running} ${running === 1 ? "tool" : "tools"}…` : turn.activityKind === "agent_thought_chunk" ? "Thinking…" : turn.activityKind === "agent_message_chunk" && idle < 2 ? "Writing…" : "";
- return { state: idle >= 15 ? "waiting" : "working", label: `Working for ${duration}`, detail: idle >= 15 ? `${detail ? `${detail} · ` : ""}No update for ${workDuration(idle)}` : detail, live: true };
+ if (!live) {
+ const wait = missing ? `${missing} tool ${missing === 1 ? "result" : "results"} not received` : rate;
+ return { state: "done", label: turn.stopReason === "cancelled" ? "Stopped" : `Worked for ${duration}`, detail: turn.stopReason === "cancelled" ? `After ${duration}` : wait ?? "", live: false };
+ }
+ const waitingOn = mcpApps ? `Waiting on ${mcpApps === 1 ? "MCP App" : "MCP Apps"}…` : running ? `Running ${running} ${running === 1 ? "tool" : "tools"}…` : "";
+ const writing = !turn.connected ? "Starting…" : waitingOn || (turn.activityKind === "agent_thought_chunk" ? "Thinking…" : turn.activityKind === "agent_message_chunk" && idle < 2 ? "Writing…" : "");
+ const detail = idle >= 15 ? joinDetail(writing, `No update for ${workDuration(idle)}`) : joinDetail(writing, waitingOn ? null : rate);
+ return { state: idle >= 15 ? "waiting" : "working", label: `Working for ${duration}`, detail, live: true };
}
diff --git a/docs/mcp-apps.md b/docs/mcp-apps.md
index 7636f46b..6107373f 100644
--- a/docs/mcp-apps.md
+++ b/docs/mcp-apps.md
@@ -4,7 +4,7 @@ Call a connected MCP tool that declares an MCP Apps UI. In the native GUI, its t
In the REPL, run **`/mcp apps`** after the tool completes to open its latest saved view in the default browser. The link in the tool result also identifies the standalone HTML file. This works with the existing MCP server configuration and consent process; it does not install or authorize additional servers.
-Views can display results, scroll, resize, and offer source links. Clicking a source exposes an **Open source** link in trusted host chrome for a user click. Image-copy features depend on browser permissions; the isolated view may need the app's copy-link or manual-selection fallback. This version does not run app-initiated tool calls or inject messages into the agent conversation; those requests fail explicitly.
+Views can display results, scroll, resize, and offer source links. Clicking a source exposes an **Open source** link in trusted host chrome for a user click. Image-copy features depend on browser permissions; the isolated view may need the app's copy-link or manual-selection fallback. The framed app can send `ui/initialize` over postMessage (MCP Apps 2026-01-26). The host answers with the protocol version. App-initiated `tools/call` still fails explicitly until the host forwards those requests through ACP (#1018).
Snapshots are stored in the user's `.graff/mcp-apps` directory with private file permissions and opaque ids. They include the tool result and its view metadata, remain available across transcript reloads, and can be deleted when no longer needed. The REPL shortcut tracks the latest view in its current session; old snapshots remain openable by their saved links.