Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat: render complete HTML answers in tasks and companions
Chris14c9f0de03bc
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex af62289111..967cf242c9 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -1,6 +1,7 @@import { flushPluginUsageLifecycle } from './plugin-usage/current.js';import { registerAccessibilitySupportIpc } from './accessibility-support-ipc.js';import { mcpAppSchemePrivilege, registerMcpAppProtocol } from './mcp-apps/sandboxProtocol.js';+import { registerHtmlAnswerPreviewIpc } from './htmlAnswerPreview.js';import { prepareImportedAutomation, finishImportedAutomation } from './bot-import/automationRuntime.js';import { ensureImportedAutomationReady, recoverCompanionImports } from './bot-import/host.js';import { listWorktreeRecycleStatus, controlWorktreeRecycle } from './worktree/recycleControls';@@ -9059,6 +9060,7 @@ app.on('ready', async () => {registerRemoteMediaProtocolHandler();registerCindyMediaProtocolHandler();registerMcpAppProtocol();+ registerHtmlAnswerPreviewIpc();// Inject a Content-Security-Policy response header onto the app's own// top-level document (defaultSession mainFrame) before any window loads.diff --git a/apps/desktop/src/main/htmlAnswerPreview.ts b/apps/desktop/src/main/htmlAnswerPreview.tsnew file mode 100644index 0000000000..1a850ba60a--- /dev/null+++ b/apps/desktop/src/main/htmlAnswerPreview.ts@@ -0,0 +1,30 @@+import { ipcMain } from 'electron';+import { withHtmlPreviewCsp } from '@cindy/maker-shared/file-preview';+import { assertTrustedAppRendererEvent } from './security/trustedAppRenderer.js';+import { throwIpcError } from './utils/ipcValidate.js';+import { mountRemoteAppDocument, unmountRemoteAppDocument } from './mcp-apps/sandboxProtocol.js';++/** Reuse the isolated document store, without creating an MCP App or tool bridge. */+export function registerHtmlAnswerPreviewIpc(): void {+ ipcMain.handle('html-answer:preview', (event, input: unknown) => {+ assertTrustedAppRendererEvent(event);+ const value = input as { html?: unknown; viewId?: unknown } | null;+ const caller = `renderer:${event.sender.id}`;+ if (!value || typeof value !== 'object')+ throwIpcError('INVALID_PARAMS', 'HTML_ANSWER_INVALID_REQUEST');+ try {+ if (typeof value.viewId === 'string') {+ unmountRemoteAppDocument(value.viewId, caller);+ return null;+ }+ if (typeof value.html !== 'string') throw new Error('Invalid document');+ const viewId = mountRemoteAppDocument(+ { html: withHtmlPreviewCsp(value.html), prefersBorder: false },+ caller,+ );+ return { viewId, url: `cindy-mcp-app://${viewId}-view/resource` };+ } catch {+ throwIpcError('INVALID_PARAMS', 'HTML_ANSWER_PREVIEW_UNAVAILABLE');+ }+ });+}diff --git a/apps/desktop/src/main/mcp-apps/__tests__/sandboxProtocol.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/sandboxProtocol.test.tsindex fffbd22035..4557a267cc 100644--- a/apps/desktop/src/main/mcp-apps/__tests__/sandboxProtocol.test.ts+++ b/apps/desktop/src/main/mcp-apps/__tests__/sandboxProtocol.test.ts@@ -1,5 +1,7 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import { app, protocol, session, type WebContents } from 'electron';+import { app, ipcMain, protocol, session, type WebContents } from 'electron';+import { registerHtmlAnswerPreviewIpc } from '../../htmlAnswerPreview.js';+vi.mock('../../security/trustedAppRenderer.js', () => ({ assertTrustedAppRendererEvent: vi.fn() }));import { EventEmitter } from 'node:events';import type { McpAppsHost } from '../host.js';import { setMcpAppsHost } from '../runtime.js';@@ -52,6 +54,25 @@ const document = {prefersBorder: true,};describe('MCP App local protocol isolation', () => {+ // Unit: answer previews reuse document isolation, but must never acquire the App RPC bridge.+ it('mounts an HTML answer with no host bridge and only lets its caller release it', async () => {+ let serve!: (request: Request) => Promise<Response> | Response;+ let invoke!: (...args: any[]) => any;+ vi.spyOn(protocol, 'handle').mockImplementation((_scheme, callback) => { serve = callback; });+ vi.spyOn(ipcMain, 'handle').mockImplementation((_channel, callback) => { invoke = callback; });+ registerMcpAppProtocol();+ registerHtmlAnswerPreviewIpc();+ const event = { sender: { id: 1 } };+ const view = invoke(event, { html: '<html><body><button>Answer</button></body></html>' });+ const response = await serve(new Request(view.url));+ expect(response.status).toBe(200);+ expect(response.headers.get('Content-Security-Policy')).toContain("connect-src 'none'");+ expect(await response.text()).toContain('Content-Security-Policy');+ expect((await serve(new Request(`cindy-mcp-app://${view.viewId}/bridge`, { method: 'POST', body: '{}' }))).status).toBe(403);+ expect(() => invoke({ sender: { id: 2 } }, { viewId: view.viewId })).toThrow();+ invoke(event, { viewId: view.viewId });+ expect((await serve(new Request(view.url))).status).toBe(404);+ });it('gives remotely mounted documents the same authenticated bridge and releases their Main binding', async () => {let handler!: (request: Request) => Promise<Response> | Response;vi.spyOn(protocol, 'handle').mockImplementation((_scheme, callback) => { handler = callback; });diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 7e7c34bc1a..7c7bd341b9 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -4442,6 +4442,9 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('dialogue-workspace:reset'),},+ htmlAnswerPreview: (input: { html: string } | { viewId: string }): Promise<{ viewId: string; url: string } | null> =>+ ipcRenderer.invoke('html-answer:preview', input),+cindyMediaStorage: {/*** 本窗口草稿附件 URL 变化时上报(composerDraftStore mutator 尾部调用,diff --git a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsxindex 19e67cdb06..b5e647853d 100644--- a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx+++ b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx@@ -141,6 +141,7 @@ const StreamingBody = memo(function StreamingBody({<>{committedText && (<MarkdownRenderer+ renderHtmlAnswersworkingDir={workingDir}content={committedText}isStreaming@@ -365,6 +366,7 @@ export const AssistantMessage = memo(function AssistantMessage({// MarkdownRenderer。isStreaming 透传 — true 时 MarkdownRenderer 内部启用// 100ms throttle, false 时无节流, 行为和该文件性能优化前完全一致。<MarkdownRenderer+ renderHtmlAnswersworkingDir={workingDir}content={displayContent}isStreaming={isStreaming}diff --git a/apps/desktop/src/renderer/components/chat/HtmlAnswerPreview.tsx b/apps/desktop/src/renderer/components/chat/HtmlAnswerPreview.tsxnew file mode 100644index 0000000000..a5a3bc17e8--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/HtmlAnswerPreview.tsx@@ -0,0 +1,115 @@+import { useEffect, useMemo, useRef, useState } from 'react';+import { useTranslation } from 'react-i18next';+import { Code2, Eye } from 'lucide-react';+import { htmlAnswerHeight, prepareHtmlAnswer } from '@cindy/maker-shared/html-answer';+import { Button } from '@/components/ui/button';++function hostTheme() {+ const root = document.documentElement;+ const style = getComputedStyle(root);+ return {+ background: style.getPropertyValue('--surface').trim(),+ foreground: style.getPropertyValue('--text-primary').trim(),+ dark: root.classList.contains('dark'),+ };+}++export function HtmlAnswerPreview({ html }: { html: string }) {+ const { t } = useTranslation();+ const frame = useRef<HTMLIFrameElement>(null);+ const [theme, setTheme] = useState(hostTheme);+ const [source, setSource] = useState(false);+ const [height, setHeight] = useState(320);+ const [url, setUrl] = useState<string>();+ const [failed, setFailed] = useState(false);+ const [attempt, setAttempt] = useState(0);+ const documentHtml = useMemo(() => prepareHtmlAnswer(html, theme), [html, theme]);+ useEffect(() => {+ const observer = new MutationObserver(() => {+ const next = hostTheme();+ setTheme((current) =>+ current.background === next.background &&+ current.foreground === next.foreground &&+ current.dark === next.dark+ ? current+ : next,+ );+ });+ observer.observe(document.documentElement, {+ attributes: true,+ attributeFilter: ['class', 'style'],+ });+ return () => observer.disconnect();+ }, []);+ useEffect(() => {+ if (source) return;+ let disposed = false;+ let viewId: string | undefined;+ const release = () => {+ if (viewId) void window.electronAPI.htmlAnswerPreview({ viewId }).catch(() => {});+ };+ setUrl(undefined);+ setFailed(false);+ setHeight(320);+ void window.electronAPI+ .htmlAnswerPreview({ html: documentHtml })+ .then((view) => {+ if (!view) throw new Error('No preview');+ viewId = view.viewId;+ if (disposed) release();+ else setUrl(view.url);+ })+ .catch(() => {+ if (!disposed) setFailed(true);+ });+ return () => {+ disposed = true;+ release();+ };+ }, [documentHtml, source, attempt]);+ useEffect(() => {+ const receive = (event: MessageEvent) => {+ if (!frame.current || event.source !== frame.current.contentWindow) return;+ const next = htmlAnswerHeight(event.data);+ if (next !== null) setHeight(next);+ };+ window.addEventListener('message', receive);+ return () => window.removeEventListener('message', receive);+ }, []);+ const showSource = source || failed;+ return (+ <div className="my-3 min-w-0" data-html-answer="true">+ <div className="flex justify-end pb-1">+ <Button+ variant="secondary"+ tone="quiet"+ size="sm"+ compact+ title={t(showSource ? 'chat.htmlAnswer.preview' : 'chat.htmlAnswer.source')}+ aria-label={t(showSource ? 'chat.htmlAnswer.preview' : 'chat.htmlAnswer.source')}+ onClick={() => {+ if (failed) setAttempt((value) => value + 1);+ setFailed(false);+ setSource(!showSource);+ }}+ >+ {showSource ? <Eye size={14} /> : <Code2 size={14} />}+ </Button>+ </div>+ {showSource ? (+ <pre className="overflow-auto whitespace-pre-wrap break-words rounded-md bg-[var(--msg-tool-card-bg)] p-3">+ <code>{html}</code>+ </pre>+ ) : url ? (+ <iframe+ ref={frame}+ src={url}+ title="HTML"+ sandbox="allow-scripts"+ className="block w-full border-0"+ style={{ height }}+ />+ ) : null}+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsxindex e099dc897b..99eaee0135 100644--- a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx+++ b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx@@ -8,15 +8,18 @@* - Inline code: Stone bg + 4px padding + 6px radius* - GFM tables, lists, bold, italic, links* - HTML tags filtered (no <script>); safe single <img> tags are normalized- * into Markdown image nodes before HTML filtering.+ * into Markdown image nodes before HTML filtering. Complete assistant HTML answers+ * may opt into the separate sandbox preview after streaming finishes.*/+import { htmlAnswerDocument } from '@cindy/maker-shared/html-answer';+import { HtmlAnswerPreview } from './HtmlAnswerPreview';import { Tip } from '@/components/ui/tooltip';import { useImageLoadFailure } from './useImageLoadFailure';import { ChatLoadingImage } from './ChatLoadingImage';import { FileTypeIcon } from '@/components/ui/file-type-icon';import { CHAT_CODE_CLASS, CHAT_CODE_SURFACE_CLASS, CHAT_ICON_BUTTON_CLASS } from './chatChrome';-import { createElement, memo, useCallback, useEffect, useRef, useState, useMemo, isValidElement, type HTMLAttributes, type ReactNode } from 'react';+import { createContext, useContext, createElement, memo, useCallback, useEffect, useRef, useState, useMemo, isValidElement, type HTMLAttributes, type ReactNode } from 'react';import ReactMarkdown, { defaultUrlTransform } from 'react-markdown';import remarkGfm from 'remark-gfm';import remarkCjkFriendly from 'remark-cjk-friendly';@@ -331,7 +334,10 @@ const previewSafeUrlTransform: UrlTransform = (url, key) => {return defaultUrlTransform(url);};+const HtmlAnswerContext = createContext(false);+interface MarkdownRendererProps {+ renderHtmlAnswers?: boolean;/** F1: session cwd used to resolve relative paths in markdown links.* Stable per-session — only changes on session switch (parent remount). */workingDir: string;@@ -560,6 +566,7 @@ const baseComponents: Components = {// simpler renderer there. See line ~310 for the implementation.pre({ children, ...props }) {+ const htmlEnabled = useContext(HtmlAnswerContext);// Intercept ```diff fenced blocks before they fall through to highlight.js// — we render them with our own row/gutter/symbol layout (MarkdownDiffBlock)// so the visual matches the Edit-tool DiffView card and the GitHub red/green@@ -567,6 +574,11 @@ const baseComponents: Components = {// Other languages (js/ts/python/...) still go through the default pre+code// path with rehype-highlight.const firstChild = Array.isArray(children) ? children[0] : children;+ if (htmlEnabled && isValidElement<{ children?: ReactNode; className?: string }>(firstChild)+ && firstChild.props.className?.includes('language-html')) {+ const html = htmlAnswerDocument(nodeToText(firstChild.props.children));+ if (html) return <HtmlAnswerPreview html={html} />;+ }if (isDiffCodeChild(firstChild)) {const codeChildren = (firstChild as { props: { children?: ReactNode } }).props.children;@@ -1676,6 +1688,7 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({currentSessionTitle,allowPrivilegedLinks = true,emitSourceLines = false,+ renderHtmlAnswers = false,}: MarkdownRendererProps) {// Cap markdown re-parse + syntax highlight cost during streaming.// Static callers (TextLightbox) leave isStreaming undefined → false,@@ -1923,9 +1936,11 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({],);+ const htmlAnswer = renderHtmlAnswers && !isStreaming ? htmlAnswerDocument(content) : null;return (+ <HtmlAnswerContext.Provider value={renderHtmlAnswers && !isStreaming}><div className="msg-markdown select-text">- {isStreaming ? (+ {htmlAnswer ? <HtmlAnswerPreview html={htmlAnswer} /> : isStreaming ? (streamingChunks.map((chunk) => (<StreamingMarkdownChunkkey={chunk.start}@@ -1977,5 +1992,6 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({/>)}</div>+ </HtmlAnswerContext.Provider>);});diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.tsindex 75aeee776f..d393a20cc8 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts+++ b/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts@@ -22,6 +22,15 @@ const project = (items: RenderItem[], streaming: boolean) =>simplifyBotRenderItems(groupWorkRuns(items, streaming), streaming);describe('teammate final-result presentation', () => {+ // Unit: a complete HTML result before a trailing tool must survive companion answer compaction.+ it('retains a finished HTML answer before a trailing tool and closing reply', () => {+ const html = '<html><body><button>Result</button></body></html>';+ const rows = [message('u', 'user'), message('html', 'assistant', html), tool('notify'),+ message('final', 'assistant', 'Done', { turnCompleted: true })];+ expect(proseIds(project(rows, false))).toEqual(['html', 'final']);+ expect(proseIds(project([message('u', 'user'), message('html', 'assistant', html, { isStreaming: true })], true))).toEqual([]);+ });+it('keeps coordination input hidden while process, explicit inputs, results and errors remain visible', () => {const rows = [message('coordination', 'user', '[UI_ACTION_TRIGGER]File agreement', { isSyntheticTrigger: true }),tool('audit'), message('visible-input', 'user', 'Requested status'),diff --git a/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts b/apps/desktop/src/renderer/features/bots/botConversationPresentation.tsindex 6e89c38c47..42683ff48f 100644--- a/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts+++ b/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts@@ -1,4 +1,5 @@import { botTaskResultKey, readBotCollaborationMeta } from '@cindy/maker-shared/botCollaboration';+import { htmlAnswerDocument } from '@cindy/maker-shared/html-answer';import { extractRenderedMarkdownImageTargets } from '@/components/chat/markdownImageTargets';import { HISTORY_GAP_SPLIT_MS } from '@/lib/historyGap';import type { ChatMessage } from '@/lib/makerChatStore';@@ -22,6 +23,10 @@ function hasAttachments(message: ChatMessage): boolean {return Boolean(message.images?.length || message.files?.length);}+function hasHtmlAnswer(message: ChatMessage): boolean {+ return !message.isStreaming && htmlAnswerDocument(message.content) !== null;+}+function expandWorkGroups(items: readonly RenderItem[]): RenderItem[] {return items.flatMap((item): RenderItem[] =>item.type === 'work_group' ? expandWorkGroups(item.children) : [item]);@@ -171,7 +176,8 @@ function projectWindow(const isAddressedReply = (message: ChatMessage) => Boolean(message.content.trim())&& !(message.assistantPhase === 'commentary' && !message.explicitDelivery)&& (message.assistantPhase === 'final_answer' || Boolean(message.sourceGroup)- || Boolean(message.explicitDelivery) || isCompletedAssistantMessage(message) || sealedAnswers.has(message));+ || Boolean(message.explicitDelivery) || hasHtmlAnswer(message)+ || isCompletedAssistantMessage(message) || sealedAnswers.has(message));const result: RenderItem[] = [];let turn: RenderItem[] = [];const flushTurn = (active: boolean) => {@@ -180,7 +186,7 @@ function projectWindow(for (let index = 0; index < turn.length; index += 1) {const item = turn[index];if (isProse(item) && item.message.content.trim()) lastProse = index;- if ((isProse(item) && (hasAttachments(item.message)+ if ((isProse(item) && (hasAttachments(item.message) || hasHtmlAnswer(item.message)|| extractRenderedMarkdownImageTargets(item.message.content).length > 0))|| (item.type === 'message' && item.message.systemCardType === 'bot-session-task-result')|| (item.type === 'generated_files' && visibleGeneratedFileKeys?.has(item.key))@@ -203,7 +209,7 @@ function projectWindow(if (!item.message.content.trim() && !hasAttachments(item.message)) return;if (item.message.assistantPhase === 'commentary' && !item.message.explicitDelivery && !hasAttachments(item.message)) return;if (item.message.assistantPhase !== 'final_answer' && !item.message.sourceGroup && !item.message.explicitDelivery && !isCompletedAssistantMessage(item.message) && !sealedAnswers.has(item.message)- && !hasAttachments(item.message) && index !== fallbackProse+ && !hasAttachments(item.message) && !hasHtmlAnswer(item.message) && index !== fallbackProse&& extractRenderedMarkdownImageTargets(item.message.content).length === 0) {return;}diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 9f63cc937e..507bb8bf0a 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -11312,6 +11312,10 @@"selectionCount_one": "{{count}} selection","selectionCount_other": "{{count}} selections"},+ "htmlAnswer": {+ "preview": "Preview",+ "source": "View source"+ },"mermaid": {"clickToZoom": "Click to zoom","zoom": "Zoom",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex bcb7be84ac..5c9f3305c6 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -11268,6 +11268,10 @@"selectionCount_one": "{{count}} 件の引用","selectionCount_other": "{{count}} 件の引用"},+ "htmlAnswer": {+ "preview": "プレビュー",+ "source": "ソースを表示"+ },"mermaid": {"clickToZoom": "クリックで拡大","zoom": "拡大",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex b810af0d08..9a552e6c5e 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -11268,6 +11268,10 @@"selectionCount_one": "인용 {{count}}개","selectionCount_other": "인용 {{count}}개"},+ "htmlAnswer": {+ "preview": "미리 보기",+ "source": "소스 보기"+ },"mermaid": {"clickToZoom": "클릭하여 확대","zoom": "확대",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex c049583ddd..90baf5ab14 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -11268,6 +11268,10 @@"selectionCount_one": "{{count}} 处引用","selectionCount_other": "{{count}} 处引用"},+ "htmlAnswer": {+ "preview": "预览",+ "source": "查看源码"+ },"mermaid": {"clickToZoom": "点击放大","zoom": "放大",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex d7c89f329b..d663fa58e5 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -11267,6 +11267,10 @@"selectionCount_one": "{{count}} 處引用","selectionCount_other": "{{count}} 處引用"},+ "htmlAnswer": {+ "preview": "預覽",+ "source": "查看原始碼"+ },"mermaid": {"clickToZoom": "點選放大","zoom": "放大",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex d10bc10e6b..168575494b 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -3819,6 +3819,7 @@ interface ElectronAPI {reset(): Promise<import('../shared/dialogueWorkspaceSettings').DialogueWorkspaceSettingsState>;};+ htmlAnswerPreview: (input: { html: string } | { viewId: string }) => Promise<{ viewId: string; url: string } | null>;cindyMediaStorage: {/** 本窗口草稿附件 URL 变化时上报(fire-and-forget;多窗口防误删取证)。 */reportDraftUrls: (urls: string[]) => void;diff --git a/apps/mobile/src/session/HtmlAnswerPreview.tsx b/apps/mobile/src/session/HtmlAnswerPreview.tsxnew file mode 100644index 0000000000..fe4c492a33--- /dev/null+++ b/apps/mobile/src/session/HtmlAnswerPreview.tsx@@ -0,0 +1,65 @@+import { useMemo, useState } from "react";+import { Pressable, View } from "react-native";+import { useTranslation } from "react-i18next";+import { Text } from "@/components/AppText";+import { useTheme, textStyles } from "@/theme";+import { prepareHtmlAnswer } from "@cindy/maker-shared/html-answer";+import { HtmlFileReader } from "./HtmlFileReader";++export function HtmlAnswerPreview({+ html,+ active = true,+}: {+ html: string;+ active?: boolean;+}) {+ const { colors, mode } = useTheme();+ const { t } = useTranslation();+ const [source, setSource] = useState(false);+ const [height, setHeight] = useState(320);+ const documentHtml = useMemo(+ () =>+ prepareHtmlAnswer(html, {+ background: colors.surface,+ foreground: colors.textPrimary,+ dark: mode === "dark",+ }),+ [html, colors.surface, colors.textPrimary, mode],+ );+ return (+ <View testID="message.htmlAnswer" style={{ alignSelf: "stretch" }}>+ <Pressable+ accessibilityRole="button"+ onPress={() => setSource(!source)}+ style={{+ alignSelf: "flex-end",+ minHeight: 44,+ justifyContent: "center",+ paddingHorizontal: 8,+ }}+ >+ <Text style={[textStyles.bodySmall, { color: colors.textSecondary }]}>+ {t(+ source+ ? "files.preview.browserShowPage"+ : "files.preview.browserShowSource",+ )}+ </Text>+ </Pressable>+ {source ? (+ <Text+ selectable+ style={[textStyles.bodySmall, { color: colors.textPrimary }]}+ >+ {html}+ </Text>+ ) : (+ <View style={{ height }}>+ {active ? (+ <HtmlFileReader html={documentHtml} onContentHeight={setHeight} />+ ) : null}+ </View>+ )}+ </View>+ );+}diff --git a/apps/mobile/src/session/HtmlFileReader.tsx b/apps/mobile/src/session/HtmlFileReader.tsxindex 0903cbf8d9..1b30c923f8 100644--- a/apps/mobile/src/session/HtmlFileReader.tsx+++ b/apps/mobile/src/session/HtmlFileReader.tsx@@ -24,7 +24,7 @@* 出网由 htmlPreviewCsp 在引擎层封锁(导航回调管不到子资源请求)。* ⚠️ **不要把这套说成「零出网」**:WebRTC 不受 CSP 管辖,iOS 上仍是残留信道 ——* 准确边界与待裁决的取舍见 htmlPreviewCsp 头注的「残留信道」一节。- * 不挂 onMessage:页面里的 postMessage 无人消费,不给任意生成物开一条通向 RN 侧的通道。+ * 文件阅读不挂 onMessage;内联答案仅接收有界尺寸通知,不执行页面发来的任何命令。* Android 另关多窗口:`window.open` / `target="_blank"` 走的是 onCreateWindow,不经过下面* 的导航回调,不关掉等于给策略留一个后门(见 setSupportMultipleWindows 处的说明)。*@@ -42,6 +42,7 @@ import { sanitizeDiagnosticText } from '@/debug/fileDiagnostics';import { mobileDebugLog } from '@/debug/mobileDebugLog';import { interceptHtmlNavigation, interceptSnapshotNavigation } from '@/session/htmlNavigationPolicy';import { withHtmlPreviewCsp } from '@/session/htmlPreviewCsp';+import { htmlAnswerHeight } from '@cindy/maker-shared/html-answer';import type { MobileHtmlPreview } from '@/session/mobileHtmlPreview';import { useHtmlBrowserViewport } from '@/session/useHtmlBrowserViewport';import { browserViewportScrollScript } from '@/session/htmlBrowserViewport';@@ -130,7 +131,9 @@ export function HtmlSnapshotReader({ preview, onError, webViewRef, viewportInset/> : null}{(!preview || paintedPreview !== preview) && loading ? <View key="loading" style={StyleSheet.absoluteFill} pointerEvents="none">{loading}</View> : null}</View></View>;}-export function HtmlFileReader({ html, testID }: { html: string; testID?: string }) {+export function HtmlFileReader({ html, testID, onContentHeight }: {+ html: string; testID?: string; onContentHeight?: (height: number) => void;+}) {// CSP 注入放在**渲染载体这一层**,而不是取件那一层:任何进到这个 WebView 的// HTML 都必须带策略,不管它有没有同目录资源(见 htmlPreviewCsp 的说明)。const guardedHtml = useMemo(() => withHtmlPreviewCsp(html), [html]);@@ -151,7 +154,7 @@ export function HtmlFileReader({ html, testID }: { html: string; testID?: string);return (<View style={styles.fill} testID={testID}>- <WebView+ <WebView<{}>onShouldStartLoadWithRequest={interceptNavigation}// 首份文档加载完就上闩:此后 about:blank 这类替换文档的导航不再放行。onLoadEnd={() => { documentSettledRef.current = true; }}@@ -180,6 +183,14 @@ export function HtmlFileReader({ html, testID }: { html: string; testID?: string// 于是目录锚点在 Android 上点了没反应。显式对齐后两端都解析成// `about:blank#toc`,锚点放行、origin 仍是 opaque(不放宽权限面)。source={{ baseUrl: 'about:blank', html: guardedHtml }}+ // Inline answers may report a bounded height; no commands or host operations.+ onMessage={onContentHeight ? (event) => {+ try {+ if (event.nativeEvent.data.length > 256) return;+ const height = htmlAnswerHeight(JSON.parse(event.nativeEvent.data));+ if (height !== null) onContentHeight(height);+ } catch { /* malformed size notification */ }+ } : undefined}style={styles.fill}/></View>diff --git a/apps/mobile/src/session/MessageRenderer.tsx b/apps/mobile/src/session/MessageRenderer.tsxindex 8457d2a602..be4524fee2 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -1,3 +1,5 @@+import { htmlAnswerDocument } from '@cindy/maker-shared/html-answer';+import { HtmlAnswerPreview } from './HtmlAnswerPreview';import { PluginCardActions } from '@/plugins/PluginCardActions';import { McpAppCard } from './McpAppCard';import { RichContentContext } from './richContentContext';@@ -3804,6 +3806,7 @@ function MessageBubble({/>) : (<MarkdownBody+ renderHtmlAnswers={item.message.kind === 'assistant'}allowIosUITextView={!shouldCollapseLongMessage}markdownImageCacheKey={item.message.key}layout={contentLayout}@@ -5591,7 +5594,7 @@ const ViewabilityGatedMathFormula = memo(function ViewabilityGatedMathFormula({/** A frozen task result reads like a reply: same Markdown, links and file chips (Desktop MarkdownRenderer). */function CompanionCardMarkdown({ text, actions }: { text: string; actions: MessageActions }) {const layout = useMemo(() => buildMessageContentLayout({ screenWidth: actions.screenWidth }), [actions.screenWidth]);- return <MarkdownBody layout={layout} text={text} selectable+ return <MarkdownBody renderHtmlAnswers layout={layout} text={text} selectableonOpenPayload={actions.onOpenPayload} onOpenSessionLink={actions.onOpenSessionLink} />;}@@ -5599,6 +5602,7 @@ function CompanionCardMarkdown({ text, actions }: { text: string; actions: Messa// 文本选择 = 完成态消息的各块 Text 原生 selectable:长按文字就地弹系统选择手柄/Copy 菜单,// 不跳转界面;整条复制走操作条按钮。选择按块进行(原生 Text 能力边界,跨段选择做不到)。function MarkdownBody({+ renderHtmlAnswers = false,allowIosUITextView = true,markdownImageCacheKey,layout,@@ -5627,6 +5631,7 @@ function MarkdownBody({/** 消息流式中:文件 chip 层跳过远端验证。 */streaming?: boolean;text: string;+ renderHtmlAnswers?: boolean;}) {const { colors } = useTheme();const { t } = useTranslation();@@ -5647,6 +5652,7 @@ function MarkdownBody({const settledTextStyle = useMemo(() => pinSettledWidth? [styles.messageText, { width: contentWidth }]: styles.messageText, [contentWidth, pinSettledWidth, styles.messageText]);+ const htmlVisible = useContext(MessageHeavyContentVisibilityContext);const markdownParseRef = useRef<MobileMarkdownParseResult | null>(null);const markdownParse = useMemo(() => {const startedAt = typeof performance !== 'undefined' && typeof performance.now === 'function'@@ -5865,6 +5871,8 @@ function MarkdownBody({);}if (block.type === 'code') {+ const html = renderHtmlAnswers && !streaming && block.language === 'html' ? htmlAnswerDocument(block.text) : null;+ if (html) return <HtmlAnswerPreview key={block.key} html={html} active={htmlVisible} />;// 围栏代码在气泡内换行,不用横向 ScrollView:后者在展开长用户消息时// 会按未折行内容报出超高,气泡巨幅空白并把每行裁在右侧圆角外。return (@@ -6013,7 +6021,9 @@ function MarkdownBody({{renderInlines(block.inlines, spanFor(inlinesSelectable(block.inlines)))}</MarkdownSelectableText>);- }, [allowIosUITextView, contentWidth, inlinesSelectable, layout, onOpenPayload, pinSettledWidth, renderInlines, selectable, settledTextStyle, spanFor, styles, t]);+ }, [allowIosUITextView, contentWidth, inlinesSelectable, layout, onOpenPayload, pinSettledWidth, renderInlines, selectable, settledTextStyle, spanFor, styles, t, renderHtmlAnswers, streaming, htmlVisible]);+ const htmlAnswer = renderHtmlAnswers && !streaming ? htmlAnswerDocument(text) : null;+ if (htmlAnswer) return <HtmlAnswerPreview html={htmlAnswer} active={htmlVisible} />;return (<Viewcollapsable={false}diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.jsonindex 6264836188..99270c587c 100644--- a/packages/maker-shared/package.json+++ b/packages/maker-shared/package.json@@ -34,6 +34,7 @@"./goal-command": "./src/goalCommand.ts","./goal-verdict": "./src/goalVerdict.ts","./history-gap": "./src/historyGap.ts",+ "./html-answer": "./src/htmlAnswer.ts","./image-annotation": "./src/imageAnnotation.ts","./interaction": "./src/interaction.ts","./internal-citation": "./src/internalCitation.ts",diff --git a/packages/maker-shared/src/__tests__/htmlAnswer.test.ts b/packages/maker-shared/src/__tests__/htmlAnswer.test.tsnew file mode 100644index 0000000000..5a422efc5f--- /dev/null+++ b/packages/maker-shared/src/__tests__/htmlAnswer.test.ts@@ -0,0 +1,36 @@+import { describe, expect, it } from "vitest";+import {+ htmlAnswerDocument,+ htmlAnswerHeight,+ prepareHtmlAnswer,+} from "../htmlAnswer";++// Unit: full documents must survive answer delivery; snippets and unfinished streams stay code.+describe("HTML answer presentation", () => {+ const html = "<!doctype html><html><body><h1>Answer</h1></body></html>";+ it("recognizes complete raw or fenced documents without changing their source", () => {+ expect(htmlAnswerDocument(html)).toBe(html);+ expect(htmlAnswerDocument("```html\n" + html + "\n```")).toBe(html);+ expect(htmlAnswerDocument("```html\n<div>example</div>\n```")).toBeNull();+ expect(htmlAnswerDocument("<html><body>unfinished")).toBeNull();+ });+ it("only accepts finite size notifications and bounds the view without accepting commands", () => {+ expect(+ htmlAnswerHeight({ type: "cindy-html-answer-size", height: 500 }),+ ).toBe(500);+ expect(+ htmlAnswerHeight({ type: "cindy-html-answer-size", height: 1e9 }),+ ).toBe(1200);+ expect(+ htmlAnswerHeight({ type: "cindy-html-answer-size", height: NaN }),+ ).toBeNull();+ expect(htmlAnswerHeight({ type: "run-tool", height: 100 })).toBeNull();+ expect(+ prepareHtmlAnswer(html, {+ background: "</script>",+ foreground: "inherit",+ dark: false,+ }),+ ).toContain('"background":"\\u003c/script>"');+ });+});diff --git a/packages/maker-shared/src/__tests__/messageRender.test.ts b/packages/maker-shared/src/__tests__/messageRender.test.tsindex bac1293926..3330c62c09 100644--- a/packages/maker-shared/src/__tests__/messageRender.test.ts+++ b/packages/maker-shared/src/__tests__/messageRender.test.ts@@ -288,9 +288,10 @@ describe('message render shared model', () => {// 交付正文与位置无关地留在折叠组外。原始形状(2026-07-31 定时巡检):agent 先输出// 长篇简报,再调 notify 发通知,最后说一句「已触发通知」——SDK seal 只盖最后那句,// 「最终答复」回溯又遇工具即停,简报会被整段折进「工作过程」。- it('keeps delivery prose outside the work fold even before a trailing side-effect tool', () => {- const brief = `本轮 7 条有活动。${'逐条核对了改动落在哪些产品面。'.repeat(50)}`;- expect(brief.length).toBeGreaterThanOrEqual(600);+ it.each([+ `本轮 7 条有活动。${'逐条核对了改动落在哪些产品面。'.repeat(50)}`,+ '<html><body><h1>Short HTML answer</h1></body></html>',+ ])('keeps delivery prose outside the work fold even before a trailing side-effect tool: %s', (brief) => {const items = buildMessageRenderItems([message({ kind: 'user', source: source('user', 'brief me', 1), body: 'brief me', label: 'user' }),diff --git a/packages/maker-shared/src/htmlAnswer.ts b/packages/maker-shared/src/htmlAnswer.tsnew file mode 100644index 0000000000..638419f9a1--- /dev/null+++ b/packages/maker-shared/src/htmlAnswer.ts@@ -0,0 +1,50 @@+/** Presentation only: no instructions are added to the model's context. */+export function htmlAnswerDocument(text: string): string | null {+ let source = text.trim();+ const fence = source.match(/^(`{3,}|~{3,})html\s*\n([\s\S]*?)\n\1\s*$/i);+ if (fence) source = fence[2].trim();+ // A complete document is an answer artifact. Ordinary HTML examples stay code.+ return /^(?:<!doctype\s+html\b[^>]*>\s*)?<html(?:\s|>)/i.test(source) &&+ /<\/html>\s*$/i.test(source)+ ? source+ : null;+}++export function htmlAnswerHeight(value: unknown): number | null {+ if (!value || typeof value !== "object") return null;+ const data = value as { type?: unknown; height?: unknown };+ return data.type === "cindy-html-answer-size" &&+ typeof data.height === "number" &&+ Number.isFinite(data.height) &&+ data.height > 0+ ? Math.max(160, Math.min(1200, Math.ceil(data.height)))+ : null;+}++/** Host theme and a size-only notification. No tool or application bridge. */+export function prepareHtmlAnswer(+ html: string,+ theme: { background: string; foreground: string; dark: boolean },+): string {+ const encodedTheme = JSON.stringify(theme).replace(/</g, "\\u003c");+ return `<meta name="viewport" content="width=device-width, initial-scale=1"><style>+ :root { color-scheme: ${theme.dark ? "dark" : "light"}; }+ body { margin: 0; font: 16px/1.6 system-ui, sans-serif; background: var(--cindy-answer-bg); color: var(--cindy-answer-fg); overflow-wrap: anywhere; }+ img,video,svg,canvas { max-width: 100%; } * { box-sizing: border-box; }+ </style><script>(()=>{+ const theme=${encodedTheme};+ document.documentElement.style.setProperty('--cindy-answer-bg',theme.background);+ document.documentElement.style.setProperty('--cindy-answer-fg',theme.foreground);+ addEventListener('DOMContentLoaded',()=>{+ let previous=0;+ const measure=()=>{+ const height=Math.ceil(document.body.getBoundingClientRect().height);+ if(height===previous)return;previous=height;+ const data={type:'cindy-html-answer-size',height};+ if(window.ReactNativeWebView)window.ReactNativeWebView.postMessage(JSON.stringify(data));+ else parent.postMessage(data,'*');+ };+ new ResizeObserver(measure).observe(document.body);measure();+ },{once:true});+ })();</script>${html}`;+}diff --git a/packages/maker-shared/src/messageRender.ts b/packages/maker-shared/src/messageRender.tsindex 7d63cee2fe..619380439b 100644--- a/packages/maker-shared/src/messageRender.ts+++ b/packages/maker-shared/src/messageRender.ts@@ -1,3 +1,4 @@+import { htmlAnswerDocument } from './htmlAnswer.js';import { groupWorkRuns } from './workRunGrouping.js';import { isContinuationMessage } from './syntheticTrigger.js';export { groupWorkRuns, type WorkRunGroupingAdapter } from './workRunGrouping.js';@@ -1631,6 +1632,7 @@ const HTML_IMAGE_RE = /<img(?=[\s/>])[^<>]*\ssrc\s*=\s*["']?[^\s"'<>]+[^<>]*>/i;export function isDeliveryProseText(text: string): boolean {const trimmed = text.trim();if (trimmed.length === 0) return false;+ if (htmlAnswerDocument(trimmed)) return true;if (trimmed.length >= DELIVERY_PROSE_MIN_LENGTH) return true;if (MARKDOWN_HEADING_RE.test(trimmed)) return true;if (MARKDOWN_TABLE_DIVIDER_RE.test(trimmed)) return true;