import { createContext, memo, useCallback, useContext, useEffect, useId, useMemo, useRef, useState } from 'react'; import { getHostTheme, getCssTokens, extractHtmlTitle, ensureHtmlDocument, formatReceiptPrompt, fillComposerDom, } from './mcp-app.js'; import css from './McpAppFrame.module.css'; /** * Composer fill channel shared by every McpAppFrame in one Reader tree. * Provided by Blocks from the session-scoped Reader face (sanctioned * conversation input API); absent outside a Reader, where the DOM fallback * applies. React context avoids threading the callback through the whole * markdown pipeline (MarkdownText -> render context -> code fence). */ export type ComposerFill = (text: string) => boolean; export const ComposerFillContext = createContext(undefined); export function useComposerFill(): ComposerFill | undefined { return useContext(ComposerFillContext); } export interface McpAppFrameProps { html: string; title?: string; initialHeight?: number; /** Session-scoped composer writer; falls back to context, then DOM. */ fillComposer?: ComposerFill; } export const McpAppFrame = memo(function McpAppFrame({ html, title: initialTitle, initialHeight = 240, fillComposer: fillComposerProp, }: McpAppFrameProps) { const fillComposerFromContext = useComposerFill(); const writeComposer = useMemo( () => fillComposerProp ?? fillComposerFromContext ?? fillComposerDom, [fillComposerProp, fillComposerFromContext], ); const iframeRef = useRef(null); const lastParamsRef = useRef>({}); const [height, setHeight] = useState(() => Math.max(60, Math.min(2400, initialHeight))); const [receipt, setReceipt] = useState(null); const [lastPrompt, setLastPrompt] = useState(null); const [reloadNonce, setReloadNonce] = useState(0); const frameId = useId(); const title = useMemo(() => { return initialTitle || extractHtmlTitle(html) || '交互式 MCP App'; }, [initialTitle, html]); // Capture the host theme ONCE for the initial srcDoc. Live theme switches // are delivered via postMessage (broadcastTheme), so the srcDoc identity // stays stable and the iframe never reloads (which would wipe user state // such as checked boxes or selected tabs). const [initialTheme] = useState(getHostTheme); const preparedHtml = useMemo(() => ensureHtmlDocument(html, initialTheme), [html, initialTheme]); const fillComposer = useCallback((params: Record) => { const prompt = formatReceiptPrompt(params, title); setLastPrompt(prompt); try { if (writeComposer(prompt)) return true; // Composer refused: leave the prompt visible in the receipt bar and // stash a clipboard copy as a fallback. try { void navigator.clipboard?.writeText(prompt); } catch { // Clipboard unavailable; the visible receipt text remains copyable. } } catch { // Ignore DOM query errors in non-browser environments } return false; }, [title, writeComposer]); const handleUserSubmit = useCallback((params: Record) => { lastParamsRef.current = params; let summary: string; if (typeof params.choice === 'string') { const desc = typeof params.desc === 'string' ? ` (${params.desc})` : ''; summary = `选择: ${params.choice}${desc}`; } else if (typeof params.action === 'string') { summary = `操作: ${params.action}${params.payload ? ` (${JSON.stringify(params.payload)})` : ''}`; } else if (typeof params.selectedVariant === 'string') { summary = `方案: ${params.selectedVariant}`; } else { summary = JSON.stringify(params); } setReceipt(summary); // Populate DSH composer with natural prompt and trigger React input state fillComposer(params); }, [fillComposer]); useEffect(() => { const handleMessage = (event: MessageEvent) => { const iframe = iframeRef.current; if (!iframe || event.source !== iframe.contentWindow) return; const data = event.data; if (!data || typeof data !== 'object') return; // Protocol SEP-1865 JSON-RPC 2.0 const currentTheme = getHostTheme(); const cssTokens = getCssTokens(currentTheme); // 1. ui/initialize (View -> Host) if (data.method === 'ui/initialize') { const response = { jsonrpc: '2.0', id: data.id, result: { protocolVersion: '2026-01-26', hostContext: { theme: currentTheme, locale: 'zh-CN', styles: { variables: cssTokens, }, }, }, }; iframe.contentWindow?.postMessage(response, '*'); return; } // ui/ready is a notification. The frame has no ready flag to flip. if (data.method === 'ui/ready' || data.method === 'ui/notifications/initialized') return; // ui/resize if (data.method === 'ui/resize' && data.params?.height) { const h = Number(data.params.height); if (Number.isFinite(h) && h > 0) { setHeight(Math.max(60, Math.min(2400, Math.round(h)))); } return; } // ui/submit or ui/update-model-context if (data.method === 'ui/submit' || data.method === 'ui/update-model-context') { const params = (data.params as Record) || {}; handleUserSubmit(params); return; } }; window.addEventListener('message', handleMessage); // Broadcast live theme changes to running iframe const broadcastTheme = () => { const newTheme = getHostTheme(); const tokens = getCssTokens(newTheme); iframeRef.current?.contentWindow?.postMessage({ jsonrpc: '2.0', method: 'ui/notifications/host-context-changed', params: { theme: newTheme, styles: { variables: tokens }, }, }, '*'); }; let observer: MutationObserver | null = null; if (typeof MutationObserver !== 'undefined' && typeof document !== 'undefined') { observer = new MutationObserver(broadcastTheme); if (document.body) { observer.observe(document.body, { attributes: true, attributeFilter: ['data-ds-dark-theme', 'class', 'style', 'data-theme'] }); } if (document.documentElement) { observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-theme', 'class', 'style'] }); } } const media = typeof window !== 'undefined' && window.matchMedia ? window.matchMedia('(prefers-color-scheme: dark)') : null; media?.addEventListener?.('change', broadcastTheme); return () => { window.removeEventListener('message', handleMessage); observer?.disconnect(); media?.removeEventListener?.('change', broadcastTheme); }; }, [handleUserSubmit]); const handleFrameLoad = useCallback(() => { const iframe = iframeRef.current; if (!iframe) return; // Proactive Host -> View initialize notification for boilerplate compatibility const currentTheme = getHostTheme(); const cssTokens = getCssTokens(currentTheme); iframe.contentWindow?.postMessage({ jsonrpc: '2.0', method: 'ui/initialize', params: { theme: currentTheme, locale: 'zh-CN', styles: { variables: cssTokens, }, }, }, '*'); }, []); const handleReload = useCallback(() => { setReloadNonce(n => n + 1); setReceipt(null); }, []); return (
{title}