Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(chat): unify streaming component delivery across harnesses
Chris1185ad0300ea
diff --git a/apps/desktop/src/main/bootstrap-electron.ts b/apps/desktop/src/main/bootstrap-electron.tsindex 967cf242c9..af62289111 100644--- a/apps/desktop/src/main/bootstrap-electron.ts+++ b/apps/desktop/src/main/bootstrap-electron.ts@@ -1,7 +1,6 @@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';@@ -9060,7 +9059,6 @@ 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/device-link/__tests__/dispatchSendSafety.test.ts b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.tsindex 781b11a8d5..0d5c27a60c 100644--- a/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts+++ b/apps/desktop/src/main/device-link/__tests__/dispatchSendSafety.test.ts@@ -1315,3 +1315,19 @@ describe('remote recorded-turn actions', () => {expect(write).not.toHaveBeenCalled();});});++it('compacts rich answer history into a complete replayable snapshot instead of cutting its JSON', () => {+ const sendInvokeResult = vi.fn().mockImplementationOnce(() => { throw tooLarge(); });+ const client = mkClient({ sendInvokeResult });+ const ops = [JSON.stringify({ seq: 1, op: 'create', id: 'text', kind: 'text', props: { text: 'Initial' } })];+ for (let seq = 2; seq <= 80; seq++) ops.push(JSON.stringify({ seq, op: 'patch', id: 'text', props: { text: '中'.repeat(600) + seq } }));+ const content = '```cindy-ui\n' + ops.join('\n') + '\n```';+ __testing.sendInvokeResultSafe(client as never, 'mobile', 'rich-history', { ok: true, result: [{ id: 'rich', role: 'assistant', content }] }, 'local-db:messages:list');+ expect(sendInvokeResult).toHaveBeenCalledTimes(2);+ const result = sendInvokeResult.mock.calls[1][2].result[0].content;+ expect(result).toContain('```cindy-ui\n');+ const operation = JSON.parse(result.split('\n')[1]);+ expect(operation).toMatchObject({ seq: 1, op: 'create', id: 'text', props: { text: '中'.repeat(600) + '80' } });+ expect(result.endsWith('\n```\n')).toBe(true);+ expect(encodedByteLength(result)).toBeLessThan(128 * 1024);+});diff --git a/apps/desktop/src/main/device-link/dispatch.ts b/apps/desktop/src/main/device-link/dispatch.tsindex 2dceda1f04..059ea3cdcc 100644--- a/apps/desktop/src/main/device-link/dispatch.ts+++ b/apps/desktop/src/main/device-link/dispatch.ts@@ -1,3 +1,4 @@+import { hasRichAnswer, compactRichAnswer, richAnswerText } from '@cindy/maker-shared/rich-answer';import type { RemoteAgentLimitUsage } from '../../shared/remoteAgentLimits.js';import { executeTaskTags, TASK_TAG_CHANNEL } from '../localDb/ipc/taskTags.js';import { encodeMessageBodies, versionMessageBody } from './sessionMessageReuse.js';@@ -3876,7 +3877,15 @@ function sanitizeRemoteMessage(record: Record<string, unknown>): Record<string,}function compactRemoteMessageContent(content: unknown, limit: number): unknown {- if (typeof content === 'string') return truncateRemoteInvokeString(content, limit);+ if (typeof content === 'string') {+ if (encodedByteLength(content) > limit && hasRichAnswer(content)) {+ const snapshot = compactRichAnswer(content);+ // Complete references and operations only; never send a cut JSON line.+ if (encodedByteLength(snapshot) <= limit) return snapshot;+ return truncateRemoteInvokeString(richAnswerText(content), limit);+ }+ return truncateRemoteInvokeString(content, limit);+ }const serialized = safeJsonStringify(content);if (!serialized || encodedByteLength(serialized) <= limit) return content;return REMOTE_INVOKE_TRUNCATED_CONTENT;diff --git a/apps/desktop/src/main/htmlAnswerPreview.ts b/apps/desktop/src/main/htmlAnswerPreview.tsdeleted file mode 100644index 1a850ba60a..0000000000--- a/apps/desktop/src/main/htmlAnswerPreview.ts+++ /dev/null@@ -1,30 +0,0 @@-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/localDb/__tests__/mapperMarkdownPreview.test.ts b/apps/desktop/src/main/localDb/__tests__/mapperMarkdownPreview.test.tsindex 7b6d44d302..1030fc8143 100644--- a/apps/desktop/src/main/localDb/__tests__/mapperMarkdownPreview.test.ts+++ b/apps/desktop/src/main/localDb/__tests__/mapperMarkdownPreview.test.ts@@ -73,3 +73,12 @@ describe('sidebar Markdown preview', () => {expect(finalizePlainPreview(text, 'assistant')).toBe(expected);});});+it('uses component prose instead of internal operation JSON in answer previews', () => {+ const source = '```cindy-ui\n' + JSON.stringify({ seq: 1, op: 'create', id: 'heading', kind: 'heading', props: { text: '费用比较' } }) + '\n' + JSON.stringify({ seq: 2, op: 'create', id: 'stat', kind: 'stat', props: { label: '按年', value: 180, prefix: '¥' } }) + '\n' + JSON.stringify({ seq: 3, op: 'create', id: 'extra', kind: 'check', props: { label: '附加服务', default: false } }) + '\n```';+ const result = extractMessagePreview(JSON.stringify(source), 'assistant');+ expect(result).toContain('费用比较');+ expect(result).toContain('¥180');+ expect(result).not.toContain('"seq"');+ expect(result).toContain('☐ 附加服务');+ expect(result).not.toContain('false');+});diff --git a/apps/desktop/src/main/localDb/mapper.ts b/apps/desktop/src/main/localDb/mapper.tsindex 07c8605f72..4bf3fe965d 100644--- a/apps/desktop/src/main/localDb/mapper.ts+++ b/apps/desktop/src/main/localDb/mapper.ts@@ -1,3 +1,4 @@+import { richAnswerText } from '@cindy/maker-shared/rich-answer';/*** chat-data-localization F5:IPC 边界 row ↔ camel/ISO 转换。*@@ -154,7 +155,7 @@ export function finalizePlainPreview(// role='user' 的正常落库行,但对用户不可见 —— 预览显示隐藏英文指令会暴露// 实现细节。返回 null 与"无预览"同渲染语义。if (isSyntheticTriggerText(next)) return null;- if (role === 'assistant') next = stripInternalWebCitations(next);+ if (role === 'assistant') next = richAnswerText(stripInternalWebCitations(next));// Strip formatting before the display limit: URLs must not consume the preview budget.const collapsed = markdownPreviewText(next);if (!collapsed) return null;diff --git a/apps/desktop/src/main/maker-host/pi-host.ts b/apps/desktop/src/main/maker-host/pi-host.tsindex 09c11dcd58..cadd481d31 100644--- a/apps/desktop/src/main/maker-host/pi-host.ts+++ b/apps/desktop/src/main/maker-host/pi-host.ts@@ -1,3 +1,4 @@+import { ANSWER_DELIVERY_PROMPT } from '@cindy/maker-shared/rich-answer-guide';import { listCindyManagedSkills } from './managed-skills.js';import { scanLocalCustomizations } from '../skillhub/customizationScanHost';import { resolveCompanionRuntimeEnvironment } from '../bot-import/runtime.js';@@ -864,6 +865,7 @@ function buildDesktopPiRuntimeConfig(): AgentRuntimeConfig {taskShellEnv: inputHandoffTaskShellEnv,// 保留 host 共用身份段,再追加 Pi 专属行为段;maker-core 会整体追加到 Pi 原生 prompt。systemPrompt: composePiSystemPrompt(hostSystemPrompt, piSystemPrompt),+ answerDeliveryPrompt: ANSWER_DELIVERY_PROMPT,// Pi 的 grep 以及 Cindy 覆盖的 find 都固定复用随 Desktop 校验、打包的 rg。// 下发绝对路径而非 PATH,避免 Windows 从不受信工作目录优先命中同名 rg.exe。managedExecutablePaths: { ripgrep: ripgrepPath },diff --git a/apps/desktop/src/main/maker-host/runtime-configs.ts b/apps/desktop/src/main/maker-host/runtime-configs.tsindex eb68830d2c..df799d91d3 100644--- a/apps/desktop/src/main/maker-host/runtime-configs.ts+++ b/apps/desktop/src/main/maker-host/runtime-configs.ts@@ -1,3 +1,4 @@+import { ANSWER_DELIVERY_PROMPT } from '@cindy/maker-shared/rich-answer-guide';/*** Desktop AgentRuntimeConfig 实现。* endpoint、行为开关与宿主资源路径由 desktop host 在这里统一注入,@@ -185,6 +186,7 @@ export function buildDesktopClaudeRuntimeConfig(endpointFn: () => string): AgenttaskShellEnv: inputHandoffTaskShellEnv,// 产品身份 + Skill 来源优先级 + Claude 专属段,按顺序拼接后给 maker-core append。systemPrompt: composeHostPrompt(claudeSystemPrompt),+ answerDeliveryPrompt: ANSWER_DELIVERY_PROMPT,// Maker Memory 需要的 user-data 绝对路径 (maker-core 没 Electron 依赖, 必须 host 注入)。userDataPath: app.getPath('userData'),get memoryEnabled() {@@ -307,6 +309,7 @@ export const desktopCodexRuntimeConfig: AgentRuntimeConfig = {taskShellEnv: inputHandoffTaskShellEnv,// 产品身份 + Skill 来源优先级 + Codex 专属段。systemPrompt: composeHostPrompt(codexSystemPrompt),+ answerDeliveryPrompt: ANSWER_DELIVERY_PROMPT,// lazy getter(与 endpoint/memoryEnabled 同一惯用法,issue #1956):import 期// 不探测 bundled ripgrep,纯 node / vitest 环境 import 本模块不再炸;真正的// fail-fast 由 maker-host 启动期的 ensureBundledRipgrepReady() 承担,此处 getterdiff --git a/apps/desktop/src/main/mcp-apps/__tests__/sandboxProtocol.test.ts b/apps/desktop/src/main/mcp-apps/__tests__/sandboxProtocol.test.tsindex 4557a267cc..fffbd22035 100644--- a/apps/desktop/src/main/mcp-apps/__tests__/sandboxProtocol.test.ts+++ b/apps/desktop/src/main/mcp-apps/__tests__/sandboxProtocol.test.ts@@ -1,7 +1,5 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import { app, ipcMain, protocol, session, type WebContents } from 'electron';-import { registerHtmlAnswerPreviewIpc } from '../../htmlAnswerPreview.js';-vi.mock('../../security/trustedAppRenderer.js', () => ({ assertTrustedAppRendererEvent: vi.fn() }));+import { app, protocol, session, type WebContents } from 'electron';import { EventEmitter } from 'node:events';import type { McpAppsHost } from '../host.js';import { setMcpAppsHost } from '../runtime.js';@@ -54,25 +52,6 @@ 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 7c7bd341b9..7e7c34bc1a 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -4442,9 +4442,6 @@ 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 cc0a73f886..526876d64e 100644--- a/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx+++ b/apps/desktop/src/renderer/components/chat/AssistantMessage.tsx@@ -1,3 +1,4 @@+import { hasRichAnswer, richAnswerText } from '@cindy/maker-shared/rich-answer';import { BotLearningFooter } from '@/features/bots/BotLearningFooter';import { BotSessionTaskResultCard } from '@/features/bots/BotSessionTaskResultCard';import { botTaskResultKey, type BotCollaborationMeta } from '@cindy/maker-shared/botCollaboration';@@ -141,7 +142,7 @@ const StreamingBody = memo(function StreamingBody({<>{committedText && (<MarkdownRenderer- renderHtmlAnswers+ renderRichAnswersworkingDir={workingDir}content={committedText}isStreaming@@ -358,7 +359,7 @@ export const AssistantMessage = memo(function AssistantMessage({running={false}sessionId={currentSessionId}/>- ) : isStreaming && USE_LINE_COMMIT_STREAMING ? (+ ) : isStreaming && USE_LINE_COMMIT_STREAMING && !hasRichAnswer(content) ? (<StreamingBodyworkingDir={workingDir}content={displayContent}@@ -373,7 +374,7 @@ export const AssistantMessage = memo(function AssistantMessage({// MarkdownRenderer。isStreaming 透传 — true 时 MarkdownRenderer 内部启用// 100ms throttle, false 时无节流, 行为和该文件性能优化前完全一致。<MarkdownRenderer- renderHtmlAnswers+ renderRichAnswersworkingDir={workingDir}content={displayContent}isStreaming={isStreaming}@@ -431,7 +432,7 @@ export const AssistantMessage = memo(function AssistantMessage({{!isStreaming && showActionBar && (<MessageActionBarcreatedAt={createdAt}- copyText={content}+ copyText={richAnswerText(content)}copyLinkText={messageDeepLink}align="left"hovered={hovered}diff --git a/apps/desktop/src/renderer/components/chat/HtmlAnswerPreview.tsx b/apps/desktop/src/renderer/components/chat/HtmlAnswerPreview.tsxdeleted file mode 100644index c7656ab74d..0000000000--- a/apps/desktop/src/renderer/components/chat/HtmlAnswerPreview.tsx+++ /dev/null@@ -1,96 +0,0 @@-import { useEffect, useMemo, useRef, useState } from 'react';-import { useTranslation } from 'react-i18next';-import { HTML_ANSWER_MAX_HEIGHT, 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 [height, setHeight] = useState(1);- 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(() => {- let disposed = false;- let viewId: string | undefined;- const release = () => {- if (viewId) void window.electronAPI.htmlAnswerPreview({ viewId }).catch(() => {});- };- setUrl(undefined);- setFailed(false);- setHeight(1);- 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, 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);- }, []);- return (- <div className="min-w-0" data-html-answer="true">- {failed ? (- <Button variant="secondary" tone="quiet" size="sm"- onClick={() => setAttempt(value => value + 1)}>- {t('commonUi.retry')}- </Button>- ) : url ? (- <iframe- ref={frame}- src={url}- title="HTML"- sandbox="allow-scripts"- scrolling={height >= HTML_ANSWER_MAX_HEIGHT ? 'auto' : 'no'}- 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 99eaee0135..bf52e04f6c 100644--- a/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx+++ b/apps/desktop/src/renderer/components/chat/MarkdownRenderer.tsx@@ -1,3 +1,5 @@+import { splitRichAnswer, richMediaSource, richMarkdown, richString, type RichNode } from '@cindy/maker-shared/rich-answer';+import { RichAnswer } from './RichAnswer';/*** MarkdownRenderer* ---------------------------------------------------------------------------@@ -8,18 +10,15 @@* - 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. Complete assistant HTML answers- * may opt into the separate sandbox preview after streaming finishes.+ * into Markdown image nodes before HTML filtering.*/-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 { createContext, useContext, createElement, memo, useCallback, useEffect, useRef, useState, useMemo, isValidElement, type HTMLAttributes, type ReactNode } from 'react';+import { createElement, memo, useId, 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';@@ -334,10 +333,8 @@ const previewSafeUrlTransform: UrlTransform = (url, key) => {return defaultUrlTransform(url);};-const HtmlAnswerContext = createContext(false);-interface MarkdownRendererProps {- renderHtmlAnswers?: boolean;+ renderRichAnswers?: boolean;/** F1: session cwd used to resolve relative paths in markdown links.* Stable per-session — only changes on session switch (parent remount). */workingDir: string;@@ -566,7 +563,6 @@ 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@@ -574,11 +570,6 @@ 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;@@ -1678,7 +1669,7 @@ function InlineCodeWithTarget({);}-export const MarkdownRenderer = memo(function MarkdownRenderer({+const MarkdownRendererBase = memo(function MarkdownRendererBase({workingDir,content,isStreaming = false,@@ -1688,7 +1679,6 @@ 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,@@ -1936,11 +1926,9 @@ 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">- {htmlAnswer ? <HtmlAnswerPreview html={htmlAnswer} /> : isStreaming ? (+ {isStreaming ? (streamingChunks.map((chunk) => (<StreamingMarkdownChunkkey={chunk.start}@@ -1992,6 +1980,28 @@ export const MarkdownRenderer = memo(function MarkdownRenderer({/>)}</div>- </HtmlAnswerContext.Provider>);});++/** Assistant-only envelope decoding, before Markdown chunking or repairs. */+export const MarkdownRenderer = memo(function MarkdownRenderer(props: MarkdownRendererProps) {+ const instanceKey = useId();+ const sessionFileCtx = useChatSessionFile();+ const source = useStreamingThrottle(props.content, props.isStreaming ?? false);+ const renderMedia = (node: RichNode) => {+ if (node.kind === 'image') return <MarkdownRendererBase {...props} content={richMarkdown(node) ?? ''} isStreaming={false} />;+ const raw = richMediaSource(node);+ if (!raw) return null;+ const normalized = raw.startsWith('xdt-audio://') && props.allowPrivilegedLinks !== false ? raw : normalizeMarkdownImageSrc(raw, props.workingDir, props.allowPrivilegedLinks !== false);+ if (!normalized) return null;+ const src = rewriteToRemoteMediaOrigin(normalized, props.currentSessionId ? toRemoteMediaOrigin(sessionFileCtx.origin, sessionFileCtx.workingDir) : undefined);+ return node.kind === 'audio' ? <InlineXdtAudioPlayer src={src} /> : <ChatVideoView src={src} filename={richString(node, 'alt', 'video')} variant="tool-output" sessionId={props.currentSessionId} />;+ };+ const parts = useMemo(() => props.renderRichAnswers ? splitRichAnswer(source) : [], [source, props.renderRichAnswers]);+ if (!parts.some(part => part.kind === 'rich')) return <MarkdownRendererBase {...props} />;+ return <div className="rich-answer-body">{parts.map(part => part.kind === 'rich'+ ? <RichAnswer renderMedia={renderMedia} key={part.key} source={part.source} complete={part.complete || !props.isStreaming}+ stateKey={`${props.streamFadeKey ?? instanceKey}:${part.key}`}+ renderMarkdown={(content, id) => <MarkdownRendererBase {...props} content={content} streamFadeKey={`${props.streamFadeKey}:${part.key}:${id}`} />} />+ : <MarkdownRendererBase {...props} key={part.key} content={part.source} isStreaming={!part.complete && props.isStreaming} streamFadeKey={`${props.streamFadeKey}:${part.key}`} />)}</div>;+});diff --git a/apps/desktop/src/renderer/components/chat/RichAnswer.tsx b/apps/desktop/src/renderer/components/chat/RichAnswer.tsxnew file mode 100644index 0000000000..e5f756458f--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/RichAnswer.tsx@@ -0,0 +1,344 @@+import {+ Fragment,+ useMemo,+ useRef,+ useState,+ useEffect,+ useSyncExternalStore,+ type ReactNode,+ type CSSProperties,+} from 'react';+import { useTranslation } from 'react-i18next';+import {+ RichAnswerStream,+ RichInteractionMemory,+ richAction,+ richChart,+ richResolvedValues,+ richCalculationUnavailable,+ richLabel,+ richMarkdown,+ richNumber,+ richOptions,+ richRange,+ richString,+ type RichNode,+ type RichValue,+} from '@cindy/maker-shared/rich-answer';+import { useAuth } from '@/contexts/AuthContext';+import { Button } from '@/components/ui/button';+import { Input } from '@/components/ui/input';+import { Slider } from '@/components/ui/slider';+import './rich-answer.css';++const memory = new RichInteractionMemory({+ async read() {+ return localStorage.getItem('cindy.richAnswer.viewState.v1');+ },+ writeSync(value) { localStorage.setItem('cindy.richAnswer.viewState.v1', value); },+ async write(value) {+ localStorage.setItem('cindy.richAnswer.viewState.v1', value);+ },+});+/** Component identities and user input survive content patches; no generated HTML executes. */+export function RichAnswer({+ source,+ complete,+ stateKey,+ renderMarkdown,+ renderMedia,+}: {+ source: string;+ complete: boolean;+ stateKey: string;+ renderMedia?: (node: RichNode) => ReactNode;+ renderMarkdown: (source: string, id: string) => ReactNode;+}) {+ const { user } = useAuth();+ return (+ <RichAnswerDocument+ key={`${user?.id ?? 'signed-out'}:${stateKey}`}+ source={source}+ complete={complete}+ stateKey={`${user?.id ?? 'signed-out'}:${stateKey}`}+ renderMarkdown={renderMarkdown}+ renderMedia={renderMedia}+ />+ );+}+function RichAnswerDocument({+ source,+ complete,+ stateKey,+ renderMarkdown,+ renderMedia,+}: {+ source: string;+ complete: boolean;+ stateKey: string;+ renderMedia?: (node: RichNode) => ReactNode;+ renderMarkdown: (source: string, id: string) => ReactNode;+}) {+ const { t } = useTranslation();+ const parser = useRef(new RichAnswerStream());+ const doc = useMemo(() => parser.current.update(source, complete), [source, complete]);+ const edited = useSyncExternalStore(memory.subscribe, () => memory.get(stateKey));+ useEffect(() => {+ void memory.load();+ const save = () => memory.flushSync();+ window.addEventListener('pagehide', save);+ return () => {+ window.removeEventListener('pagehide', save);+ void memory.flush();+ };+ }, []);+ const values = richResolvedValues(doc, edited);+ const change = (key: string, v: RichValue) => memory.set(stateKey, { [key]: v });+ const apply = (node: RichNode) => memory.set(stateKey, richAction(node, values));+ const render = (id: string): ReactNode => {+ const node = doc.nodes.get(id);+ if (!node) return null;+ if (richCalculationUnavailable(node, values)) return <p className="rich-answer-caption" role="status">{complete ? t('richAnswer.calculationUnavailable') : '…'}</p>;+ const bind = richString(node, 'bind', id),+ label = richString(node, 'label');+ const children = node.children.map((child) => <Fragment key={child}>{render(child)}</Fragment>);+ if ((['image', 'video', 'audio'].includes(node.kind)) && renderMedia)+ return (+ <div className="rich-answer-content">+ {renderMedia(node)}+ {richString(node, 'caption') && (+ <div className="rich-answer-caption">{richString(node, 'caption')}</div>+ )}+ </div>+ );+ const md = richMarkdown(node);+ if (md !== null)+ return (+ <div data-rich-node={id} className="rich-answer-content">+ {renderMarkdown(md, id)}+ {richString(node, 'caption') && (+ <div className="rich-answer-caption">{richString(node, 'caption')}</div>+ )}+ </div>+ );+ switch (node.kind) {+ case 'heading':+ return <h3 className="rich-answer-heading">{richLabel(node, values)}</h3>;+ case 'text':+ return <p className="rich-answer-text">{richLabel(node, values)}</p>;+ case 'divider':+ return <hr className="rich-answer-divider" />;+ case 'stack':+ case 'row':+ case 'grid':+ case 'group':+ return (+ <div+ data-rich-node={id}+ className={`rich-answer-layout rich-answer-${node.kind}${richString(node, 'layout') === 'aside' ? ' rich-answer-aside' : ''}`}+ style={+ {+ '--rich-columns': Math.round(+ Math.max(1, Math.min(3, richNumber(node, 'columns', 2))),+ ),+ } as CSSProperties+ }+ >+ {children}+ </div>+ );+ case 'stat':+ return (+ <div className="rich-answer-stat">+ <div className="rich-answer-caption">{label}</div>+ <output>{richLabel(node, values)}</output>+ </div>+ );+ case 'range': {+ const range = richRange(node, values[bind]);+ return (+ <div className="rich-answer-control">+ <div className="rich-answer-control-label">+ <span>{label}</span>+ <output>+ {range.value}+ {richString(node, 'suffix')}+ </output>+ </div>+ <Slider+ aria-label={label}+ min={range.min}+ max={range.max}+ step={range.step}+ value={[range.value]}+ onValueChange={(v) => change(bind, v[0])}+ />+ </div>+ );+ }+ case 'input':+ return (+ <label className="rich-answer-control">+ {label}+ <Input+ aria-label={label}+ value={String(values[bind] ?? '')}+ placeholder={richString(node, 'placeholder')}+ maxLength={4096}+ onChange={(value) => change(bind, value)}+ />+ </label>+ );+ case 'check':+ return (+ <label className="rich-answer-check">+ <input+ type="checkbox"+ checked={Boolean(values[bind])}+ onChange={(event) => change(bind, event.target.checked)}+ />+ <span>{label || richString(node, 'text')}</span>+ </label>+ );+ case 'select':+ return (+ <label className="rich-answer-control">+ {label}+ <select+ className="rich-answer-select"+ value={String(values[bind] ?? '')}+ onChange={(event) => change(bind, event.target.value)}+ >+ <option value="" disabled>+ {richString(node, 'placeholder', label)}+ </option>+ {richOptions(node).map((option) => (+ <option key={option.value} value={option.value}>+ {option.label}+ </option>+ ))}+ </select>+ </label>+ );+ case 'button':+ return (+ <Button variant="secondary" tone="quiet" onClick={() => apply(node)}>+ {label || richString(node, 'text')}+ </Button>+ );+ case 'form':+ return (+ <form+ className="rich-answer-layout rich-answer-stack"+ onSubmit={(event) => {+ event.preventDefault();+ apply(node);+ }}+ >+ {children}+ {label && (+ <Button type="submit" variant="secondary">+ {label}+ </Button>+ )}+ </form>+ );+ case 'details':+ return (+ <details+ open={Boolean(values[bind])}+ onToggle={(event) => {+ if (Boolean(values[bind]) !== event.currentTarget.open)+ change(bind, event.currentTarget.open);+ }}+ >+ <summary>{label}</summary>+ <div className="rich-answer-layout rich-answer-stack">{children}</div>+ </details>+ );+ case 'tabs': {+ const selected = node.children.includes(String(values[bind]))+ ? String(values[bind])+ : node.children[0];+ return (+ <div>+ <div className="rich-answer-tabs" role="tablist" aria-label={label}>+ {node.children.map((child) => (+ <Button+ key={child}+ role="tab"+ aria-selected={selected === child}+ variant="secondary"+ tone="quiet"+ onClick={() => change(bind, child)}+ >+ {richString(doc.nodes.get(child)!, 'label', child)}+ </Button>+ ))}+ </div>+ {node.children.map((child) => (+ <div key={child} role="tabpanel" hidden={selected !== child}>+ {render(child)}+ </div>+ ))}+ </div>+ );+ }+ case 'chart': {+ const data = richChart(node, values),+ min = Math.min(0, ...data.map((item) => item.value)),+ max = Math.max(0, ...data.map((item) => item.value)),+ span = max - min || 1;+ return (+ <figure className="rich-answer-chart">+ <figcaption>{label}</figcaption>+ {richString(node, 'variant') === 'line' ? (+ <svg role="img" aria-label={label} viewBox="0 0 480 180">+ <polyline+ fill="none"+ stroke="currentColor"+ strokeWidth="2"+ points={data+ .map(+ (item, i) =>+ `${10 + (i / Math.max(1, data.length - 1)) * 460},${170 - ((item.value - min) / span) * 160}`,+ )+ .join(' ')}+ />+ </svg>+ ) : null}+ <dl>+ {data.map((item, i) => (+ <div key={i}>+ <div className="rich-answer-control-label">+ <dt>{item.label}</dt>+ <dd>{item.value}</dd>+ </div>+ {richString(node, 'variant') !== 'line' && (+ <div className="rich-answer-track">+ <div style={{ marginLeft: `${((Math.min(0, item.value) - min) / span) * 100}%`, width: `${(Math.abs(item.value) / span) * 100}%` }} />+ </div>+ )}+ </div>+ ))}+ </dl>+ </figure>+ );+ }+ default:+ return null;+ }+ };+ return (+ <div className="rich-answer" data-rich-answer>+ {doc.roots.map((id) => (+ <Fragment key={id}>{render(id)}</Fragment>+ ))}+ {doc.issues > 0 && (+ <p className="rich-answer-caption" role="status">+ {t('richAnswer.incomplete')}+ </p>+ )}+ </div>+ );+}diff --git a/apps/desktop/src/renderer/components/chat/__tests__/RichAnswer.test.tsx b/apps/desktop/src/renderer/components/chat/__tests__/RichAnswer.test.tsxnew file mode 100644index 0000000000..777b69d2cc--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/__tests__/RichAnswer.test.tsx@@ -0,0 +1,51 @@+// @vitest-environment jsdom+import { afterEach, expect, it, vi } from 'vitest';+import { cleanup, fireEvent, render, screen } from '@testing-library/react';+vi.mock('@/contexts/AuthContext', () => ({ useAuth: () => ({ user: { id: 'test-owner' } }) }));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+import { RichAnswer } from '../RichAnswer';+afterEach(cleanup);+const line = (seq: number, op: Record<string, unknown>) => JSON.stringify({ seq, ...op }) + '\n';+// Tier 1: mount the production renderer; input identity/state must survive+// streamed patches, the final marker, and message-list virtualization.+it('preserves edited controls through patches, finalization and remount', () => {+ const source = line(1, { op: 'create', id: 'name', kind: 'input', props: { label: 'Name', default: 'Original' } }) + line(2, { op: 'create', id: 'note', kind: 'text', props: { text: 'Before' } });+ const props = { stateKey: 'stream-state', renderMarkdown: (text: string) => <span>{text}</span> };+ const view = render(<RichAnswer {...props} source={source} complete={false} />);+ const input = screen.getByLabelText('Name');+ fireEvent.change(input, { target: { value: 'Edited' } });+ const updated = source + line(3, { op: 'patch', id: 'name', props: { default: 'New default' } }) + line(4, { op: 'append', id: 'note', text: ' and after' });+ view.rerender(<RichAnswer {...props} source={updated} complete={true} />);+ expect(screen.getByLabelText('Name')).toBe(input);+ expect((input as HTMLInputElement).value).toBe('Edited');+ // Immediate reload must save the edit before the debounce fires.+ fireEvent(window, new Event('pagehide'));+ const saved = JSON.parse(localStorage.getItem('cindy.richAnswer.viewState.v1')!);+ expect(saved.entries.find(([key]: [string]) => key === 'test-owner:stream-state')[1].name).toBe('Edited');+ expect(screen.getByText('Before and after')).toBeTruthy();+ view.unmount();+ render(<RichAnswer {...props} source={updated} complete />);+ expect((screen.getByLabelText('Name') as HTMLInputElement).value).toBe('Edited');+});+it('routes image media through the host renderer without evaluating generated markup', () => {+ const source = line(1, { op: 'create', id: 'image', kind: 'image', props: { src: 'library:assets/a.png', alt: 'Preview' } }) + line(2, { op: 'create', id: 'text', kind: 'text', props: { text: '<script>throw 1</script>' } });+ const renderMarkdown = vi.fn((text: string) => <span>{text}</span>);+ const view = render(<RichAnswer stateKey="media" source={source} complete renderMarkdown={renderMarkdown} />);+ expect(renderMarkdown).toHaveBeenCalledWith('', 'image');+ expect(view.container.querySelector('script')).toBeNull();+ expect(screen.getByText('<script>throw 1</script>')).toBeTruthy();+});+// Tier 1: a referenced result may arrive after its consumer in a live answer.+// Pending/error states must not erase readable content or misrepresent a total.+it('renders pending calculated references, resolves them and isolates invalid final values', () => {+ const first = line(1, { op: 'create', id: 'total', kind: 'stat', props: { label: 'Total', value: { ref: 'price' } } }) + line(2, { op: 'create', id: 'note', kind: 'text', props: { text: 'Existing explanation' } });+ const props = { stateKey: 'forward-reference', renderMarkdown: (text: string) => <span>{text}</span> };+ const view = render(<RichAnswer {...props} source={first} complete={false} />);+ expect(screen.getByRole('status').textContent).toBe('…');+ view.rerender(<RichAnswer {...props} source={first + line(3, { op: 'create', id: 'price', kind: 'stat', props: { value: 25 } })} complete />);+ expect(screen.queryByText('…')).toBeNull();+ expect(screen.getAllByText('25')).toHaveLength(2);+ view.rerender(<RichAnswer {...props} source={first} complete />);+ expect(screen.getByRole('status').textContent).toBe('richAnswer.calculationUnavailable');+ expect(screen.getByText('Existing explanation')).toBeTruthy();+});diff --git a/apps/desktop/src/renderer/components/chat/rich-answer.css b/apps/desktop/src/renderer/components/chat/rich-answer.cssnew file mode 100644index 0000000000..eb75fad906--- /dev/null+++ b/apps/desktop/src/renderer/components/chat/rich-answer.css@@ -0,0 +1,156 @@+/* Answer primitives inherit the host theme and typography. No generated CSS or HTML. */+.rich-answer {+ display: flex;+ flex-direction: column;+ gap: var(--space-4);+ min-width: 0;+ container-type: inline-size;+}+.rich-answer p.rich-answer-text {+ margin: 0;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+}+.rich-answer h3.rich-answer-heading {+ margin: 0;+ font-size: var(--text-lg);+ font-weight: 500;+ line-height: 1.5;+}+.rich-answer-layout {+ display: flex;+ gap: var(--space-4);+ min-width: 0;+}+.rich-answer-stack,+.rich-answer-group {+ flex-direction: column;+}+.rich-answer-row {+ flex-wrap: wrap;+}+.rich-answer-row > * {+ flex: 1;+ min-width: 0;+}+.rich-answer-grid {+ display: grid;+ grid-template-columns: repeat(var(--rich-columns, 2), minmax(0, 1fr));+}+.rich-answer-aside {+ grid-template-columns: minmax(100px, 0.7fr) minmax(0, 1.8fr);+}+.rich-answer-content {+ min-width: 0;+}+.rich-answer-content img,+.rich-answer-content video {+ max-width: 100%;+}+.rich-answer-caption {+ color: var(--text-secondary);+ font-size: var(--text-xs);+ font-weight: 400;+}+.rich-answer-stat {+ border-top: 1px solid var(--border-default);+ padding-block: var(--space-3);+}+.rich-answer-stat output {+ font-size: var(--text-2xl);+ font-variant-numeric: tabular-nums;+}+.rich-answer-control {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ min-width: 0;+}+.rich-answer-control-label {+ display: flex;+ justify-content: space-between;+ gap: var(--space-3);+}+.rich-answer-check {+ display: flex;+ gap: var(--space-3);+ align-items: center;+ min-height: 36px;+}+.rich-answer-check input {+ accent-color: var(--text-primary);+}+.rich-answer-select {+ border: 1px solid var(--border-default);+ border-radius: var(--radius-full);+ padding: var(--space-2) var(--space-3);+ background: var(--surface);+ color: var(--text-primary);+ min-height: 36px;+}+.rich-answer-select:focus-visible,+.rich-answer-check input:focus-visible {+ outline: 2px solid var(--text-primary);+ outline-offset: 2px;+}+.rich-answer-tabs {+ display: flex;+ flex-wrap: wrap;+ gap: var(--space-2);+ margin-bottom: var(--space-3);+}+.rich-answer-tabs [aria-selected='true'] {+ font-weight: 600;+}+.rich-answer summary {+ cursor: pointer;+ min-height: 36px;+}+.rich-answer hr.rich-answer-divider {+ border: 0;+ border-top: 1px solid var(--border-default);+ margin: var(--space-2) 0;+}+.rich-answer-chart {+ margin: 0;+}+.rich-answer-chart svg {+ display: block;+ width: 100%;+ max-height: 180px;+}+.rich-answer-chart dl {+ display: flex;+ flex-direction: column;+ gap: var(--space-3);+ margin: var(--space-3) 0 0;+}+.rich-answer-chart dd {+ margin: 0;+}+.rich-answer-track {+ height: 8px;+ background: var(--surface-elevated);+ border-radius: 2px;+ overflow: hidden;+ margin-top: var(--space-2);+}+.rich-answer-track > div {+ height: 100%;+ background: var(--text-secondary);+}+@container (max-width:360px) {+ .rich-answer-grid {+ grid-template-columns: 1fr;+ }+ .rich-answer-aside {+ grid-template-columns: minmax(88px, 0.7fr) minmax(0, 1.8fr);+ }+}++.rich-answer-body {+ display: flex;+ flex-direction: column;+ gap: var(--space-4);+ min-width: 0;+}diff --git a/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx b/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsxindex 3ee545bd86..e9a22f1455 100644--- a/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx+++ b/apps/desktop/src/renderer/features/bots/BotCollaborationCard.tsx@@ -479,6 +479,8 @@ export function BotTaskCard({<MarkdownRendererworkingDir={workingDir}currentSessionId={childSessionId ?? undefined}+ renderRichAnswers+ streamFadeKey={`bot-result:${childSessionId ?? parentSessionId}:${card.delegationId}`}content={resultText}/>) : (diff --git a/apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx b/apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsxindex 00425541f0..5172cc319a 100644--- a/apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx+++ b/apps/desktop/src/renderer/features/bots/CloudCompanionOfflineView.tsx@@ -194,7 +194,7 @@ export function CloudCompanionOfflineView({ botId, deviceId, name, avatar, avata</article>) : (<article key={message.id} className={`flex min-w-0 flex-col gap-2 text-[var(--msg-assistant-text)] ${CHAT_BODY_CLASS}`}>- {message.text ? <MarkdownRenderer workingDir="" content={message.text} allowPrivilegedLinks={false} /> : null}+ {message.text ? <MarkdownRenderer renderRichAnswers streamFadeKey={`cloud:${botId}:${message.id}`} workingDir="" content={message.text} allowPrivilegedLinks={false} /> : null}{message.attachments?.length ? <CloudMessageAttachments botId={botId} files={message.attachments} align="start" /> : null}</article>))}diff --git a/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts b/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.tsindex 4c3ce23df1..7e4c0b7f37 100644--- a/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts+++ b/apps/desktop/src/renderer/features/bots/__tests__/botConversationPresentation.test.ts@@ -22,15 +22,6 @@ 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([]);- });-// #6351: provider final_answer only closes a message, not a successful sample.// Failed output remains in the expandable work history rather than being lifted// beside the real answer; normal commentary is governed by the existing rules.@@ -368,3 +359,10 @@ it('keeps an unanswered historical receipt visible while the next user turn stremessage('next-answer', 'assistant', 'First words', { assistantPhase: 'final_answer', isStreaming: true })];expect(allKeys(project(next, true))).toEqual(['msg-old-user', 'msg-receipt', 'msg-next-user', 'msg-next-answer']);});++it('keeps streaming component answers visible through commentary and later tools', () => {+ const body = '```cindy-ui\n' + JSON.stringify({ seq: 1, op: 'create', id: 'heading', kind: 'heading', props: { text: 'Result' } }) + '\n';+ const rows = [message('u', 'user'), message('rich', 'assistant', body, { assistantPhase: 'commentary', isStreaming: true }), tool('later')];+ expect(proseIds(project(rows, true))).toContain('rich');+ expect(rows[1].type === 'message' && rows[1].message.content).toBe(body);+});diff --git a/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts b/apps/desktop/src/renderer/features/bots/botConversationPresentation.tsindex 872435f122..464a5762f2 100644--- a/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts+++ b/apps/desktop/src/renderer/features/bots/botConversationPresentation.ts@@ -1,5 +1,5 @@+import { hasRichAnswer } from '@cindy/maker-shared/rich-answer';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';@@ -23,10 +23,6 @@ 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]);@@ -175,10 +171,9 @@ function projectWindow(}const isAddressedReply = (message: ChatMessage) => Boolean(message.content.trim())&& !message.failedSamplingAttempt- && !(message.assistantPhase === 'commentary' && !message.explicitDelivery)- && (message.assistantPhase === 'final_answer' || Boolean(message.sourceGroup)- || Boolean(message.explicitDelivery) || hasHtmlAnswer(message)- || isCompletedAssistantMessage(message) || sealedAnswers.has(message));+ && !(message.assistantPhase === 'commentary' && !message.explicitDelivery && !hasRichAnswer(message.content))+ && (hasRichAnswer(message.content) || message.assistantPhase === 'final_answer' || Boolean(message.sourceGroup)+ || Boolean(message.explicitDelivery) || isCompletedAssistantMessage(message) || sealedAnswers.has(message));const result: RenderItem[] = [];let turn: RenderItem[] = [];const flushTurn = (active: boolean) => {@@ -187,7 +182,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) || hasHtmlAnswer(item.message)+ if ((isProse(item) && (hasAttachments(item.message) || hasRichAnswer(item.message.content)|| extractRenderedMarkdownImageTargets(item.message.content).length > 0))|| (item.type === 'message' && item.message.systemCardType === 'bot-session-task-result')|| (item.type === 'generated_files' && visibleGeneratedFileKeys?.has(item.key))@@ -207,10 +202,10 @@ function projectWindow(if (item.type === 'message' && item.message.role === 'thinking') return;if (item.type === 'message' && item.message.isSyntheticTrigger) return;if (isProse(item)) {- if (!item.message.content.trim() && !hasAttachments(item.message)) return;- if (item.message.assistantPhase === 'commentary' && !item.message.explicitDelivery && !hasAttachments(item.message)) return;+ if (!item.message.content.trim() && !hasAttachments(item.message) && !hasRichAnswer(item.message.content)) return;+ if (item.message.assistantPhase === 'commentary' && !item.message.explicitDelivery && !hasAttachments(item.message) && !hasRichAnswer(item.message.content)) return;if (item.message.assistantPhase !== 'final_answer' && !item.message.sourceGroup && !item.message.explicitDelivery && !isCompletedAssistantMessage(item.message) && !sealedAnswers.has(item.message)- && !hasAttachments(item.message) && !hasHtmlAnswer(item.message) && index !== fallbackProse+ && !hasAttachments(item.message) && !hasRichAnswer(item.message.content) && 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 1cc77ab5a2..eded78a72a 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -16588,5 +16588,9 @@"messageSource": "Sent by $t(mcpApps.appName) “{{name}}”","serverId": "MCP Server ID: {{id}}","exitFullscreen": "Exit Fullscreen"+ },+ "richAnswer": {+ "calculationUnavailable": "Unable to calculate this value.",+ "incomplete": "Some content could not be displayed."}}diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex c3e759b866..245302f7ee 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -16529,5 +16529,9 @@"messageSource": "$t(mcpApps.appName)「{{name}}」から送信","serverId": "MCP サーバー ID:{{id}}","exitFullscreen": "全画面表示を終了"+ },+ "richAnswer": {+ "calculationUnavailable": "この値を計算できません。",+ "incomplete": "一部の内容を表示できませんでした。"}}diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 37776db4db..d947c793bf 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -16529,5 +16529,9 @@"messageSource": "$t(mcpApps.appName) “{{name}}”에서 전송","serverId": "MCP 서버 ID: {{id}}","exitFullscreen": "전체 화면 종료"+ },+ "richAnswer": {+ "calculationUnavailable": "이 값을 계산할 수 없습니다.",+ "incomplete": "일부 내용을 표시하지 못했습니다."}}diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 19f0125717..8e0bd57799 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -16529,5 +16529,9 @@"messageSource": "由 $t(mcpApps.appName)「{{name}}」发送","serverId": "MCP 服务器 ID:{{id}}","exitFullscreen": "退出全屏"+ },+ "richAnswer": {+ "calculationUnavailable": "此项暂时无法计算。",+ "incomplete": "部分内容未能显示。"}}diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 097e7685e9..09fae0f998 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -16529,5 +16529,9 @@"messageSource": "由 $t(mcpApps.appName)「{{name}}」傳送","serverId": "MCP 伺服器 ID:{{id}}","exitFullscreen": "離開全螢幕"+ },+ "richAnswer": {+ "calculationUnavailable": "此項暫時無法計算。",+ "incomplete": "部分內容未能顯示。"}}diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 168575494b..d10bc10e6b 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -3819,7 +3819,6 @@ 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/__tests__/companionConversationPresentation.test.ts b/apps/mobile/src/__tests__/companionConversationPresentation.test.tsindex 393f2dd49b..3e96ede7b5 100644--- a/apps/mobile/src/__tests__/companionConversationPresentation.test.ts+++ b/apps/mobile/src/__tests__/companionConversationPresentation.test.ts@@ -181,3 +181,9 @@ it.each([true, false])('keeps guest-safe explicit delivery without sealing adjacexpect(text).not.toContain('Before');expect(text).not.toContain('After');});+it('keeps a component progress answer visible before finalization and later tool calls', () => {+ const content = '```cindy-ui\n' + JSON.stringify({ seq: 1, op: 'create', id: 'heading', kind: 'heading', props: { text: 'Result' } }) + '\n';+ const source = [row('u0', 'user', 'Help'), row('a1', 'assistant', content, { assistantPhase: 'commentary' }), ...base.slice(2)];+ const result = bodies(source, true);+ expect(result.some(item => item.type === 'message' && item.message.body === content)).toBe(true);+});diff --git a/apps/mobile/src/i18n/locales/en/message.json b/apps/mobile/src/i18n/locales/en/message.jsonindex 7756980bc3..dfbf08f2ed 100644--- a/apps/mobile/src/i18n/locales/en/message.json+++ b/apps/mobile/src/i18n/locales/en/message.json@@ -391,5 +391,9 @@"memory": "Remembered: {{title}}","skillCreated": "Created skill: {{title}}","skillUpdated": "Updated skill: {{title}}"+ },+ "richAnswer": {+ "calculationUnavailable": "Unable to calculate this value.",+ "incomplete": "Some content could not be displayed."}}diff --git a/apps/mobile/src/i18n/locales/ja/message.json b/apps/mobile/src/i18n/locales/ja/message.jsonindex 4ab767211c..949eca957b 100644--- a/apps/mobile/src/i18n/locales/ja/message.json+++ b/apps/mobile/src/i18n/locales/ja/message.json@@ -391,5 +391,9 @@"memory": "記憶しました:{{title}}","skillCreated": "スキルを作成:{{title}}","skillUpdated": "スキルを更新:{{title}}"+ },+ "richAnswer": {+ "calculationUnavailable": "この値を計算できません。",+ "incomplete": "一部の内容を表示できませんでした。"}}diff --git a/apps/mobile/src/i18n/locales/ko/message.json b/apps/mobile/src/i18n/locales/ko/message.jsonindex db93a0c533..9a6c998d42 100644--- a/apps/mobile/src/i18n/locales/ko/message.json+++ b/apps/mobile/src/i18n/locales/ko/message.json@@ -391,5 +391,9 @@"memory": "기억했어요: {{title}}","skillCreated": "스킬 생성: {{title}}","skillUpdated": "스킬 업데이트: {{title}}"+ },+ "richAnswer": {+ "calculationUnavailable": "이 값을 계산할 수 없습니다.",+ "incomplete": "일부 내용을 표시하지 못했습니다."}}diff --git a/apps/mobile/src/i18n/locales/zh-CN/message.json b/apps/mobile/src/i18n/locales/zh-CN/message.jsonindex 4bc844d3ad..840982e704 100644--- a/apps/mobile/src/i18n/locales/zh-CN/message.json+++ b/apps/mobile/src/i18n/locales/zh-CN/message.json@@ -391,5 +391,9 @@"memory": "已记住:{{title}}","skillCreated": "已建立技能:{{title}}","skillUpdated": "已更新技能:{{title}}"+ },+ "richAnswer": {+ "calculationUnavailable": "此项暂时无法计算。",+ "incomplete": "部分内容未能显示。"}}diff --git a/apps/mobile/src/i18n/locales/zh-TW/message.json b/apps/mobile/src/i18n/locales/zh-TW/message.jsonindex 3f6156e808..257459c08c 100644--- a/apps/mobile/src/i18n/locales/zh-TW/message.json+++ b/apps/mobile/src/i18n/locales/zh-TW/message.json@@ -391,5 +391,9 @@"memory": "已記住:{{title}}","skillCreated": "已建立技能:{{title}}","skillUpdated": "已更新技能:{{title}}"+ },+ "richAnswer": {+ "calculationUnavailable": "此項暫時無法計算。",+ "incomplete": "部分內容未能顯示。"}}diff --git a/apps/mobile/src/session/CloudCompanionScreen.tsx b/apps/mobile/src/session/CloudCompanionScreen.tsxindex 93929a3d14..8497dc74c4 100644--- a/apps/mobile/src/session/CloudCompanionScreen.tsx+++ b/apps/mobile/src/session/CloudCompanionScreen.tsx@@ -23,6 +23,10 @@ import { useUserBubbleAppearance } from '@/theme/userBubblePreference';import { goBackGuarded } from '@/utils/backGuard';import { BOT_GROUP_MESSAGE_AVATAR_SIZE } from './BotGroupAvatars';import { BotGroupMarkdownText, BotGroupUserText } from './BotGroupMessageText';+import { hasRichAnswer } from '@cindy/maker-shared/rich-answer';+import { MarkdownBody } from './MessageRenderer';+import { buildMessageContentLayout } from './messageContentLayout';+import { useAdaptiveWindow } from '@/platform/AdaptiveWindowContext';import { CHAT_HEADER_MARK_SIZE, ChatIdentityHeader, ChatIdentitySubtitle } from './ChatIdentityHeader';import { CompanionCardActions, CompanionCardButton } from './CompanionCardButton';import { CompanionSettingsRow } from './CompanionSettingsRow';@@ -51,6 +55,8 @@ export function CloudCompanionScreen({ actorId, botId, deviceId, deviceName, tit}) {const { t } = useTranslation();const { colors } = useTheme();+ const { width } = useAdaptiveWindow();+ const answerLayout = useMemo(() => buildMessageContentLayout({ screenWidth: width }), [width]);const styles = useThemedStyles(makeStyles);const router = useRouter();const { user } = useAuth();@@ -210,7 +216,9 @@ export function CloudCompanionScreen({ actorId, botId, deviceId, deviceName, titconst continued = index > 0 && messages[index - 1]!.fromCompanion;return <View key={message.id} style={[styles.replyRow, continued && styles.replyRowContinued]} testID="cloudCompanion.message.companion">{continued ? <View style={styles.avatarSpacer} /> : <View style={styles.avatarSlot}>{avatar(BOT_GROUP_MESSAGE_AVATAR_SIZE)}</View>}- <View style={styles.replyColumn}><BotGroupMarkdownText content={message.text} /></View>+ <View style={styles.replyColumn}>{hasRichAnswer(message.text)+ ? <MarkdownBody renderRichAnswers markdownImageCacheKey={`cloud:${actorId}:${message.id}`} layout={answerLayout} text={message.text} selectable />+ : <BotGroupMarkdownText content={message.text} />}</View></View>;})}</ScrollView>;diff --git a/apps/mobile/src/session/HtmlAnswerPreview.tsx b/apps/mobile/src/session/HtmlAnswerPreview.tsxdeleted file mode 100644index f823155f6e..0000000000--- a/apps/mobile/src/session/HtmlAnswerPreview.tsx+++ /dev/null@@ -1,33 +0,0 @@-import { useMemo, useState } from "react";-import { View } from "react-native";-import { useTheme } from "@/theme";-import { HTML_ANSWER_MAX_HEIGHT, 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 [height, setHeight] = useState(1);- 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", height }}>- {active ? (- <HtmlFileReader html={documentHtml} onContentHeight={setHeight}- scrollEnabled={height >= HTML_ANSWER_MAX_HEIGHT} />- ) : null}- </View>- );-}diff --git a/apps/mobile/src/session/HtmlFileReader.tsx b/apps/mobile/src/session/HtmlFileReader.tsxindex f1240e28ff..0903cbf8d9 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;内联答案仅接收有界尺寸通知,不执行页面发来的任何命令。+ * 不挂 onMessage:页面里的 postMessage 无人消费,不给任意生成物开一条通向 RN 侧的通道。* Android 另关多窗口:`window.open` / `target="_blank"` 走的是 onCreateWindow,不经过下面* 的导航回调,不关掉等于给策略留一个后门(见 setSupportMultipleWindows 处的说明)。*@@ -42,7 +42,6 @@ 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';@@ -131,9 +130,7 @@ 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, onContentHeight, scrollEnabled = true }: {- html: string; testID?: string; onContentHeight?: (height: number) => void; scrollEnabled?: boolean;-}) {+export function HtmlFileReader({ html, testID }: { html: string; testID?: string }) {// CSP 注入放在**渲染载体这一层**,而不是取件那一层:任何进到这个 WebView 的// HTML 都必须带策略,不管它有没有同目录资源(见 htmlPreviewCsp 的说明)。const guardedHtml = useMemo(() => withHtmlPreviewCsp(html), [html]);@@ -154,13 +151,13 @@ export function HtmlFileReader({ html, testID, onContentHeight, scrollEnabled =);return (<View style={styles.fill} testID={testID}>- <WebView<{}>+ <WebViewonShouldStartLoadWithRequest={interceptNavigation}// 首份文档加载完就上闩:此后 about:blank 这类替换文档的导航不再放行。onLoadEnd={() => { documentSettledRef.current = true; }}// 见头注:收窄会让 RNW 在回调前把非白名单 URL 交给 Linking,绕过下面的策略。originWhitelist={['*']}- scrollEnabled={scrollEnabled}+ scrollEnabled// Android:关掉多窗口(review P1)。留着默认支持时,`window.open(...)` 与// `target="_blank"` 会走 onCreateWindow 而**不经过** onShouldStartLoadWithRequest,// 于是程序化打开 https 或自定义 scheme 能整个绕过上面的 click 门与 scheme 拒绝。@@ -183,14 +180,6 @@ export function HtmlFileReader({ html, testID, onContentHeight, scrollEnabled =// 于是目录锚点在 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 1408b3b8b3..d73c79be5c 100644--- a/apps/mobile/src/session/MessageRenderer.tsx+++ b/apps/mobile/src/session/MessageRenderer.tsx@@ -1,5 +1,5 @@-import { htmlAnswerDocument } from '@cindy/maker-shared/html-answer';-import { HtmlAnswerPreview } from './HtmlAnswerPreview';+import { splitRichAnswer, richAnswerText, richMediaSource, richMarkdown, richString, type RichNode } from '@cindy/maker-shared/rich-answer';+import { RichAnswer } from './RichAnswer';import { PluginCardActions } from '@/plugins/PluginCardActions';import { McpAppCard } from './McpAppCard';import { RichContentContext } from './richContentContext';@@ -28,7 +28,7 @@ import { CompanionEntering } from '@/session/CompanionEntering';import { mobileDebugEnabled, mobileDebugLog } from '@/debug/mobileDebugLog';import { createScrollDebugSampler } from '@/debug/scrollDebugSampler';import { errorText, resolvedUrlKind } from '@/debug/fileDiagnostics';-import { createContext, Fragment, memo, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type Dispatch, type ReactElement, type ReactNode, type SetStateAction } from 'react';+import { createContext, Fragment, memo, useId, useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, type ComponentProps, type Dispatch, type ReactElement, type ReactNode, type SetStateAction } from 'react';import { useTranslation } from 'react-i18next';import { MessageLoadingImage, MessageImagePlaceholder } from './MessageLoadingImage';import { InputHandoffRecordRow } from '@/inputHandoff/InputHandoffRecordRow';@@ -2923,7 +2923,7 @@ const RenderItemView = memo(function RenderItemView({? <AuthorizationMessageCard message={item.message} />: item.message.companion? <CompanionMessageCard message={item.message}- renderMarkdown={(text) => <CompanionCardMarkdown text={text} actions={actions} />} />+ renderMarkdown={(text) => <CompanionCardMarkdown messageKey={item.key} text={text} actions={actions} />} />: item.message.orcaCard? (<>@@ -3437,7 +3437,8 @@ function MessageBubble({const shareSelectionActive = actions.shareSelectionActive === true&& shareableMessage;const isFirstUserMessage = item.message.kind === 'user' && clientId === actions.firstUserMessageClientId;- const copyText = buildMobileMessageCopyText(item.message);+ const rawCopyText = buildMobileMessageCopyText(item.message);+ const copyText = item.message.kind === 'assistant' ? richAnswerText(rawCopyText) : rawCopyText;const canUseCompletedActions = !isStreamingAssistant;// 操作行只挂在每轮收尾正文、且该行确实是一条发言(判据见// mobileMessageShowsActionBar):中间句不再逐条带复制/分叉/时间,系统边界卡整行@@ -3806,7 +3807,8 @@ function MessageBubble({/>) : (<MarkdownBody- renderHtmlAnswers={item.message.kind === 'assistant'}+ renderRichAnswers={item.message.kind === 'assistant'}+ richStateKey={item.message.source.clientId ?? item.message.key}allowIosUITextView={!shouldCollapseLongMessage}markdownImageCacheKey={item.message.key}layout={contentLayout}@@ -3946,7 +3948,7 @@ function MessageBubble({&& item.message.body.trim() ? readBotTaskResults(item.message.source.agentMeta?.botTaskResults).map(meta => (<CompanionTaskResultCard key={botTaskResultKey(meta)} meta={meta} attacheddeviceId={actions.remoteDeviceId ?? ''} parentSessionId={item.message.source.sessionId}- renderMarkdown={text => <CompanionCardMarkdown text={text} actions={actions} />} />+ renderMarkdown={text => <CompanionCardMarkdown messageKey={`${item.key}:${botTaskResultKey(meta)}`} text={text} actions={actions} />} />)) : null}{item.message.kind === 'assistant' && item.message.modelMismatch ? (// 模型降级提示(对齐桌面 AssistantMessage):所选模型本轮被上游静默替换,@@ -5597,17 +5599,16 @@ 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 }) {+function CompanionCardMarkdown({ text, actions, messageKey }: { text: string; actions: MessageActions; messageKey: string }) {const layout = useMemo(() => buildMessageContentLayout({ screenWidth: actions.screenWidth }), [actions.screenWidth]);- return <MarkdownBody renderHtmlAnswers layout={layout} text={text} selectable+ return <MarkdownBody renderRichAnswers markdownImageCacheKey={messageKey} layout={layout} text={text} selectableonOpenPayload={actions.onOpenPayload} onOpenSessionLink={actions.onOpenSessionLink} />;}// 消息正文统一走原生 markdown 渲染(流式与完成态同一条路径,完成时无"原生→WebView"的切换跳变)。// 文本选择 = 完成态消息的各块 Text 原生 selectable:长按文字就地弹系统选择手柄/Copy 菜单,// 不跳转界面;整条复制走操作条按钮。选择按块进行(原生 Text 能力边界,跨段选择做不到)。-function MarkdownBody({- renderHtmlAnswers = false,+function MarkdownBodyBase({allowIosUITextView = true,markdownImageCacheKey,layout,@@ -5619,6 +5620,9 @@ function MarkdownBody({text,}: {/** 超长展开正文在 iOS 回退 RN Text,避免超高 UITextView 空白;仍保留整块复制。 */+ renderRichAnswers?: boolean;+ /** Persisted row ids may replace stream ids; clientId stays stable across that handoff. */+ richStateKey?: string;allowIosUITextView?: boolean;/** 本地 Markdown 图片的稳定消息身份,避免后续消息复用同一路径的旧媒体缓存。 */markdownImageCacheKey?: string;@@ -5636,7 +5640,6 @@ function MarkdownBody({/** 消息流式中:文件 chip 层跳过远端验证。 */streaming?: boolean;text: string;- renderHtmlAnswers?: boolean;}) {const { colors } = useTheme();const { t } = useTranslation();@@ -5657,7 +5660,6 @@ 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'@@ -5876,8 +5878,6 @@ 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 (@@ -6026,9 +6026,7 @@ function MarkdownBody({{renderInlines(block.inlines, spanFor(inlinesSelectable(block.inlines)))}</MarkdownSelectableText>);- }, [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} />;+ }, [allowIosUITextView, contentWidth, inlinesSelectable, layout, onOpenPayload, pinSettledWidth, renderInlines, selectable, settledTextStyle, spanFor, styles, t]);return (<Viewcollapsable={false}@@ -9840,3 +9838,40 @@ const makeStyles = (colors: ThemeColors) => StyleSheet.create({todoPending: { color: colors.textTertiary },todoDone: { fontWeight: fontWeight.medium },});++export function MarkdownBody(props: Parameters<typeof MarkdownBodyBase>[0]) {+ const instanceKey = useId();+ const origin = useContext(ChatFilePathContext);+ const renderMedia = (node: RichNode) => <RichAnswerMedia node={node} body={props} />;+ const parts = useMemo(() => props.renderRichAnswers ? splitRichAnswer(props.text) : [], [props.text, props.renderRichAnswers]);+ if (!parts.some(part => part.kind === 'rich')) return <MarkdownBodyBase {...props} />;+ return <View style={{ gap: spacing.lg }}>{parts.map(part => part.kind === 'rich'+ ? <RichAnswer renderMedia={renderMedia} key={part.key} source={part.source} complete={part.complete || !props.streaming}+ stateKey={`${origin?.deviceId ?? ''}:${origin?.sessionId ?? ''}:${props.richStateKey ?? props.markdownImageCacheKey ?? instanceKey}:${part.key}`}+ renderMarkdown={(text, id) => <MarkdownBodyBase {...props} text={text} markdownImageCacheKey={`${props.markdownImageCacheKey}:${part.key}:${id}`} />} />+ : <MarkdownBodyBase {...props} key={part.key} text={part.source} streaming={!part.complete && props.streaming} />)}</View>;+}++/** Each composed column supplies its actual width; media never assumes a full message row. */+function RichAnswerMedia({ node, body }: { node: RichNode; body: Parameters<typeof MarkdownBodyBase>[0] }) {+ const origin = useContext(ChatFilePathContext);+ const resolver = useContext(MarkdownRemoteMediaContext);+ const [width, setWidth] = useState(0);+ const raw = richMediaSource(node);+ if (!raw || (node.kind !== 'image' && node.kind !== 'video' && node.kind !== 'audio')) return null;+ const direct = /^(?:https?|xdt-audio|xdt-video|cindy-media):\/\//.test(raw);+ const url = direct ? raw : mobileMarkdownManagedImagePreviewUrl(raw, origin?.workdir, body.markdownImageCacheKey, origin?.remoteHostId, origin?.sessionId);+ // Outside-workdir files retain the existing explicit-open path; never fetch them automatically.+ if (!url) return <MarkdownBodyBase {...body} text={richMarkdown(node) ?? ''} streaming={false} />;+ const label = richString(node, 'alt', node.kind);+ const media: NormalizedToolMedia = { kind: node.kind, url, title: label, previewable: isDirectPreviewableMediaUrl(url) };+ const imageWidth = Math.min(body.layout.imagePreviewWidth, width);+ const layout = { ...body.layout, imagePreviewWidth: imageWidth,+ imagePreviewHeight: imageWidth * body.layout.imagePreviewHeight / body.layout.imagePreviewWidth,+ mediaPreviewWidth: Math.min(body.layout.mediaPreviewWidth, width) };+ return <View style={{ minWidth: 0 }} onLayout={event => setWidth(event.nativeEvent.layout.width)}>+ {width > 0 ? <MediaPreview layout={layout} media={media} label={label} onResolveRemoteMedia={resolver}+ usePreviewState={useState}+ onOpen={body.onOpenPayload ? () => body.onOpenPayload!(buildMediaPayload(media, label)) : undefined} /> : null}+ </View>;+}diff --git a/apps/mobile/src/session/RichAnswer.tsx b/apps/mobile/src/session/RichAnswer.tsxnew file mode 100644index 0000000000..a1431097f0--- /dev/null+++ b/apps/mobile/src/session/RichAnswer.tsx@@ -0,0 +1,540 @@+import AsyncStorage from "@react-native-async-storage/async-storage";+import {+ Fragment,+ useMemo,+ useRef,+ useState,+ useEffect,+ useSyncExternalStore,+ type ReactNode,+} from "react";+import {+ View,+ AppState,+ Text,+ Pressable,+ TextInput,+ Switch,+ StyleSheet,+ type GestureResponderEvent,+} from "react-native";+import Svg, { Polyline } from "react-native-svg";+import { useTranslation } from "react-i18next";+import { useAuth } from "@/auth/AuthContext";+import {+ useTheme,+ useThemedStyles,+ spacing,+ radius,+ textStyles,+ fontWeight,+ type ThemeColors,+} from "@/theme";+import {+ RichAnswerStream,+ RichInteractionMemory,+ richAction,+ richChart,+ richResolvedValues,+ richCalculationUnavailable,+ richLabel,+ richMarkdown,+ richNumber,+ richOptions,+ richRange,+ richString,+ type RichNode,+ type RichValue,+} from "@cindy/maker-shared/rich-answer";++const memory = new RichInteractionMemory({+ async read() {+ return AsyncStorage.getItem("cindy.richAnswer.viewState.v1");+ },+ async write(value) {+ await AsyncStorage.setItem("cindy.richAnswer.viewState.v1", value);+ },+});+type Props = {+ source: string;+ complete: boolean;+ stateKey: string;+ renderMedia?: (node: RichNode) => ReactNode;+ renderMarkdown: (source: string, id: string) => ReactNode;+};+export function RichAnswer(props: Props) {+ const { user } = useAuth();+ const key = `${user?.id ?? "signed-out"}:${props.stateKey}`;+ return <RichDocumentView {...props} key={key} stateKey={key} />;+}+function RichDocumentView({+ source,+ complete,+ stateKey,+ renderMarkdown,+ renderMedia,+}: Props) {+ const { t } = useTranslation();+ const { colors } = useTheme();+ const styles = useThemedStyles(makeStyles);+ const parser = useRef(new RichAnswerStream());+ const doc = useMemo(+ () => parser.current.update(source, complete),+ [source, complete],+ );+ const edited = useSyncExternalStore(memory.subscribe, () =>+ memory.get(stateKey),+ );+ useEffect(() => {+ void memory.load();+ const subscription = AppState.addEventListener('change', state => { if (state !== 'active') void memory.flush(); });+ return () => {+ subscription.remove();+ void memory.flush();+ };+ }, []);+ const [width, setWidth] = useState(0);+ const values = richResolvedValues(doc, edited);+ const change = (key: string, value: RichValue) => {+ memory.set(stateKey, { [key]: value });+ };+ const apply = (node: RichNode) => {+ memory.set(stateKey, richAction(node, values));+ };+ const button = (label: string, action: () => void, selected?: boolean) => (+ <Pressable+ accessibilityRole="button"+ accessibilityState={{ selected }}+ onPress={action}+ style={[styles.button, selected && styles.selected]}+ >+ <Text style={styles.buttonText}>{label}</Text>+ </Pressable>+ );+ const render = (id: string): ReactNode => {+ const node = doc.nodes.get(id);+ if (!node) return null;+ if (richCalculationUnavailable(node, values)) return <Text style={styles.caption}>{complete ? t("message.richAnswer.calculationUnavailable") : '…'}</Text>;+ const bind = richString(node, "bind", id),+ label = richString(node, "label");+ const children = node.children.map((child) => (+ <Fragment key={child}>{render(child)}</Fragment>+ ));+ if ((["image", "video", "audio"].includes(node.kind)) && renderMedia)+ return (+ <View style={styles.content}>+ {renderMedia(node)}+ {richString(node, "caption") ? (+ <Text style={styles.caption}>{richString(node, "caption")}</Text>+ ) : null}+ </View>+ );+ const md = richMarkdown(node);+ if (md !== null)+ return (+ <View style={styles.content}>+ {renderMarkdown(md, id)}+ {richString(node, "caption") ? (+ <Text style={styles.caption}>{richString(node, "caption")}</Text>+ ) : null}+ </View>+ );+ switch (node.kind) {+ case "text":+ case "heading":+ return (+ <Text+ selectable+ style={node.kind === "heading" ? styles.heading : styles.text}+ >+ {richLabel(node, values)}+ </Text>+ );+ case "divider":+ return <View style={styles.divider} />;+ case "stack":+ case "group":+ return <View style={styles.stack}>{children}</View>;+ case "row":+ case "grid": {+ const aside = richString(node, "layout") === "aside";+ const columns =+ width < 360 && !aside+ ? 1+ : Math.round(+ Math.max(1, Math.min(3, richNumber(node, "columns", 2))),+ );+ return (+ <View style={styles.row}>+ {node.children.map((child, index) => (+ <View+ key={child}+ style={+ aside+ ? {+ flexBasis: index === 0 ? "30%" : "60%",+ flexGrow: 1,+ minWidth: 0,+ }+ : {+ width: `${100 / columns - (columns > 1 ? 2 : 0)}%`,+ minWidth: 0,+ }+ }+ >+ {render(child)}+ </View>+ ))}+ </View>+ );+ }+ case "stat":+ return (+ <View style={styles.stat}>+ <Text style={styles.caption}>{label}</Text>+ <Text selectable style={styles.statValue}>+ {richLabel(node, values)}+ </Text>+ </View>+ );+ case "input":+ return (+ <View style={styles.stack}>+ <Text style={styles.text}>{label}</Text>+ <TextInput+ accessibilityLabel={label}+ value={String(values[bind] ?? "")}+ onChangeText={(v) => change(bind, v)}+ maxLength={4096}+ placeholder={richString(node, "placeholder")}+ placeholderTextColor={colors.textPlaceholder}+ style={styles.input}+ />+ </View>+ );+ case "range":+ return (+ <View>+ <View style={styles.labelRow}>+ <Text style={styles.text}>{label}</Text>+ <Text style={styles.text}>+ {richRange(node, values[bind]).value}+ {richString(node, "suffix")}+ </Text>+ </View>+ <AnswerRange+ node={node}+ value={values[bind]}+ onChange={(v) => change(bind, v)}+ />+ </View>+ );+ case "check":+ return (+ <View style={styles.labelRow}>+ <Text style={[styles.text, styles.content]}>+ {label || richString(node, "text")}+ </Text>+ <Switch+ accessibilityLabel={label}+ value={Boolean(values[bind])}+ onValueChange={(v) => change(bind, v)}+ trackColor={{+ false: colors.borderStrong,+ true: colors.textSecondary,+ }}+ />+ </View>+ );+ case "select":+ return (+ <View style={styles.stack}>+ <Text style={styles.text}>{label}</Text>+ <View style={styles.row}>+ {richOptions(node).map((option) => (+ <Fragment key={option.value}>+ {button(+ option.label,+ () => change(bind, option.value),+ values[bind] === option.value,+ )}+ </Fragment>+ ))}+ </View>+ </View>+ );+ case "button":+ return button(label || richString(node, "text"), () => apply(node));+ case "form":+ return (+ <View style={styles.stack}>+ {children}+ {label ? button(label, () => apply(node)) : null}+ </View>+ );+ case "details":+ return (+ <View style={styles.stack}>+ <Pressable+ accessibilityRole="button"+ accessibilityState={{ expanded: Boolean(values[bind]) }}+ onPress={() => change(bind, !values[bind])}+ style={styles.button}+ >+ <Text style={styles.buttonText}>{label}</Text>+ </Pressable>+ <View style={!values[bind] ? styles.hidden : undefined}>+ {children}+ </View>+ </View>+ );+ case "tabs": {+ const selected = node.children.includes(String(values[bind]))+ ? String(values[bind])+ : node.children[0];+ return (+ <View style={styles.stack}>+ <View style={styles.row}>+ {node.children.map((child) => (+ <Fragment key={child}>+ {button(+ richString(doc.nodes.get(child)!, "label", child),+ () => change(bind, child),+ selected === child,+ )}+ </Fragment>+ ))}+ </View>+ {node.children.map((child) => (+ <View+ key={child}+ style={selected !== child ? styles.hidden : undefined}+ >+ {render(child)}+ </View>+ ))}+ </View>+ );+ }+ case "chart": {+ const data = richChart(node, values),+ min = Math.min(0, ...data.map((item) => item.value)),+ max = Math.max(0, ...data.map((item) => item.value)),+ span = max - min || 1;+ return (+ <View style={styles.stack}>+ <Text style={styles.text}>{label}</Text>+ {richString(node, "variant") === "line" ? (+ <Svg+ accessibilityLabel={label}+ width="100%"+ height={160}+ viewBox="0 0 480 180"+ >+ <Polyline+ fill="none"+ stroke={colors.textPrimary}+ strokeWidth={2}+ points={data+ .map(+ (item, i) =>+ `${10 + (i / Math.max(1, data.length - 1)) * 460},${170 - ((item.value - min) / span) * 160}`,+ )+ .join(" ")}+ />+ </Svg>+ ) : null}+ {data.map((item, index) => (+ <View key={index}>+ <View style={styles.labelRow}>+ <Text style={styles.caption}>{item.label}</Text>+ <Text style={styles.caption}>{item.value}</Text>+ </View>+ {richString(node, "variant") !== "line" ? (+ <View style={styles.track}>+ <View+ style={[+ styles.bar,+ { marginLeft: `${((Math.min(0, item.value) - min) / span) * 100}%`, width: `${(Math.abs(item.value) / span) * 100}%` },+ ]}+ />+ </View>+ ) : null}+ </View>+ ))}+ </View>+ );+ }+ default:+ return null;+ }+ };+ return (+ <View+ testID="message.richAnswer"+ style={styles.stack}+ onLayout={(event) => setWidth(event.nativeEvent.layout.width)}+ >+ {doc.roots.map((id) => (+ <Fragment key={id}>{render(id)}</Fragment>+ ))}+ {doc.issues ? (+ <Text style={styles.caption}>{t("message.richAnswer.incomplete")}</Text>+ ) : null}+ </View>+ );+}+function AnswerRange({+ node,+ value,+ onChange,+}: {+ node: RichNode;+ value: unknown;+ onChange: (value: number) => void;+}) {+ const styles = useThemedStyles(makeStyles);+ const [width, setWidth] = useState(0);+ const range = richRange(node, value),+ usable = Math.max(1, width - 28);+ const clamp = (n: number) => Math.max(range.min, Math.min(range.max, n));+ const pick = (event: GestureResponderEvent) => {+ const ratio = Math.max(+ 0,+ Math.min(1, (event.nativeEvent.locationX - 14) / usable),+ );+ onChange(+ clamp(+ range.min ++ Math.round((ratio * (range.max - range.min)) / range.step) *+ range.step,+ ),+ );+ };+ return (+ <View+ accessible+ accessibilityRole="adjustable"+ accessibilityLabel={richString(node, "label")}+ accessibilityValue={{ min: range.min, max: range.max, now: range.value }}+ accessibilityActions={[{ name: "increment" }, { name: "decrement" }]}+ onAccessibilityAction={(event) =>+ onChange(+ clamp(+ range.value ++ (event.nativeEvent.actionName === "increment"+ ? range.step+ : -range.step),+ ),+ )+ }+ onLayout={(event) => setWidth(event.nativeEvent.layout.width)}+ onStartShouldSetResponder={() => true}+ onMoveShouldSetResponder={() => true}+ onResponderTerminationRequest={() => false}+ onResponderGrant={pick}+ onResponderMove={pick}+ style={styles.range}+ >+ <View pointerEvents="none" style={styles.rangeTrack} />+ <View+ pointerEvents="none"+ style={[+ styles.thumb,+ {+ left:+ ((range.value - range.min) / (range.max - range.min)) * usable,+ },+ ]}+ />+ </View>+ );+}+const makeStyles = (colors: ThemeColors) =>+ StyleSheet.create({+ stack: { gap: spacing.lg, minWidth: 0 },+ content: { minWidth: 0, flexShrink: 1 },+ row: { flexDirection: "row", flexWrap: "wrap", gap: spacing.sm },+ labelRow: {+ flexDirection: "row",+ justifyContent: "space-between",+ alignItems: "center",+ gap: spacing.md,+ },+ text: {+ ...textStyles.bodyLarge,+ color: colors.textPrimary,+ fontWeight: fontWeight.regular,+ flexShrink: 1,+ },+ heading: {+ ...textStyles.subtitle,+ color: colors.textPrimary,+ fontWeight: fontWeight.medium,+ },+ caption: {+ ...textStyles.footnote,+ color: colors.textSecondary,+ fontWeight: fontWeight.regular,+ },+ stat: {+ borderTopWidth: StyleSheet.hairlineWidth,+ borderTopColor: colors.border,+ paddingVertical: spacing.md,+ gap: spacing.xs,+ },+ statValue: {+ ...textStyles.headline,+ color: colors.textPrimary,+ fontWeight: fontWeight.medium,+ },+ divider: {+ borderTopWidth: StyleSheet.hairlineWidth,+ borderTopColor: colors.border,+ },+ button: {+ minHeight: 44,+ justifyContent: "center",+ paddingHorizontal: spacing.lg,+ paddingVertical: spacing.sm,+ backgroundColor: colors.surfaceElevated,+ borderRadius: radius.pill,+ alignSelf: "flex-start",+ },+ selected: { borderWidth: 1, borderColor: colors.borderStrong },+ buttonText: {+ ...textStyles.body,+ color: colors.textPrimary,+ fontWeight: fontWeight.medium,+ },+ input: {+ ...textStyles.body,+ color: colors.textPrimary,+ backgroundColor: colors.surfaceElevated,+ borderRadius: radius.pill,+ minHeight: 44,+ paddingHorizontal: spacing.lg,+ },+ hidden: { display: "none" },+ track: {+ height: 8,+ backgroundColor: colors.surfaceElevated,+ borderRadius: radius.micro,+ overflow: "hidden",+ },+ bar: { height: "100%", backgroundColor: colors.textSecondary },+ range: { height: 44, justifyContent: "center" },+ rangeTrack: {+ height: 4,+ marginHorizontal: 14,+ backgroundColor: colors.borderStrong,+ borderRadius: radius.pill,+ },+ thumb: {+ position: "absolute",+ height: 28,+ width: 28,+ borderRadius: radius.pill,+ backgroundColor: colors.textPrimary,+ },+ });diff --git a/apps/mobile/src/session/companionConversationPresentation.ts b/apps/mobile/src/session/companionConversationPresentation.tsindex 48ae8611ad..25e8c14681 100644--- a/apps/mobile/src/session/companionConversationPresentation.ts+++ b/apps/mobile/src/session/companionConversationPresentation.ts@@ -1,9 +1,10 @@+import { hasRichAnswer } from '@cindy/maker-shared/rich-answer';import { botTaskResultKey, readBotTaskResults } from '@cindy/maker-shared/botCollaboration';import { HISTORY_GAP_SPLIT_MS } from '@cindy/maker-shared/history-gap';import { collectMobileMarkdownImages } from './messageMarkdown';import type { MobileMessageRenderItem } from './messageRenderModel';-const isDelivery = (item: MobileMessageRenderItem) => item.type === 'tool_media' && item.tools.some(tool => !!tool.media?.length || !!tool.files?.length)+const isDelivery = (item: MobileMessageRenderItem) => (item.type === 'message' && !item.message.failedSamplingAttempt && item.message.kind === 'assistant' && hasRichAnswer(item.message.body)) || item.type === 'tool_media' && item.tools.some(tool => !!tool.media?.length || !!tool.files?.length)|| item.type === 'message' && !item.message.failedSamplingAttempt && (item.message.companion?.kind === 'task' && item.message.companion.meta.role === 'delegation-result'|| !!item.message.attachments?.length || !!item.message.media?.length|| !!item.message.files?.length || collectMobileMarkdownImages(item.message.body).length > 0);diff --git a/docs/design-rules/DESIGN.md b/docs/design-rules/DESIGN.mdindex 2b12637e5c..a459b61c8f 100644--- a/docs/design-rules/DESIGN.md+++ b/docs/design-rules/DESIGN.md@@ -2144,3 +2144,7 @@ and media position (`ui/media-scrubber`, seconds in/out). Native media controls> **(6) 需拆开读**〔2026-07-29 二次修正〕:手机短屏 / 长屏的**品牌簇**(立绘 / SLOGAN / 字标)新稿基准与避脸落值**保留生效**;同条的**功能区落位**(`loginY` **622 / 827**)在 2026-07-28 曾随跳过登录剥离一并退回 main 原值(694 / 933),但那会与已换新稿的品牌簇拼出稿内不存在的 92 / 131.65 间距(实机可见空白),**2026-07-29 审图后恢复为新稿标注值**(方案 B,60 落到底部留白;详见上方 §16.2「面板 500→440 少掉的 60 去向」)。dh<1334 段**不采用**该条曾写过的 `dh-712`,而是「紧凑底距 18 + 钳到 622」(`dh-712` 会压盖窄屏字标,见 §16.2 对应条目)。**pad 竖屏推导值**(`loginY` 573.353 / `splashOffset` 206)仍然**作废**、保持 main 原值 621 / 158——pad 无 figma 新稿帧,其品牌簇也未换新稿基准,内部自洽,不受本次修正影响。> 手机端保持无游客 / 无账号行为不变。详见> [`design-decision-log.md`](./design-decision-log.md)「2026-07-28」条。++## 流式正文与可组合组件(2026-10-18)++用户确认的答案方向:正文由流式编辑器与共享组件库承载,模型自由组合图文、图表和交互布局;普通任务与伙伴采用同一能力。每个完整节点增量出现,局部修订保留稳定控件身份和用户操作值。视觉沿现有正文、控件和媒体规范,不以整页 HTML 预览框替代连续正文。两端主题与窄屏同等实现。协议、能力发现与当前验收边界见 [流式正文与可组合组件](../rich-answers.md)。diff --git a/docs/images/rich-answers/desktop-cost.png b/docs/images/rich-answers/desktop-cost.pngnew file mode 100644index 0000000000..8771378369Binary files /dev/null and b/docs/images/rich-answers/desktop-cost.png differdiff --git a/docs/images/rich-answers/mobile-cost-dark.png b/docs/images/rich-answers/mobile-cost-dark.pngnew file mode 100644index 0000000000..2e1b0bebd6Binary files /dev/null and b/docs/images/rich-answers/mobile-cost-dark.png differdiff --git a/docs/images/rich-answers/mobile-cost-light.png b/docs/images/rich-answers/mobile-cost-light.pngnew file mode 100644index 0000000000..991a310ab4Binary files /dev/null and b/docs/images/rich-answers/mobile-cost-light.png differdiff --git a/docs/rich-answers.md b/docs/rich-answers.mdnew file mode 100644index 0000000000..4e1cfa0d78--- /dev/null+++ b/docs/rich-answers.md@@ -0,0 +1,49 @@+# 流式正文与可组合组件++2026-10-18 用户确认:Cindy 提供流式编辑器和组件库,模型自由编排正文。普通任务与伙伴、外露进展与最终答案共用一套展示能力。不是完整 HTML 文件预览,也不依赖特定模型或 OpenAI 内部协议。++## 输入与展示++文本型 Harness 复用现有累积文本事件,以 `cindy-ui` 围栏承载逐行操作。每一完整操作行即可提交,无需等围栏或回答完成。普通 Markdown 仍用现有正文组件。用户消息、引用内嵌示例与文件预览不启用组件解释。++共享解析器保存稳定节点:create、append、patch、move、remove。节点按 id 更新;输入、勾选和选择值与模型默认值分开。Markdown、图片、视频、公式和 Mermaid 沿用现有文件来源与预览边界。布局仅接受组件属性,不执行模型 HTML、CSS 或 JavaScript。数值表达式只支持有界的算术/选择树;按钮仅修改本地界面状态。++Desktop 使用原生 React 组件;Mobile 使用原生 View/Text 与既有媒体组件,不新增原生依赖或 runtime fingerprint。浅深主题取各端语义 token,窄屏按可用宽度换行。++## 恢复与容量++原始操作流作为原消息正文持久保存,重新打开时从原文还原文档。完整累计文本快照天然包含断线前的操作;序号重复不重复执行,缺口保留已提交内容并报告未能显示部分。历史传输超过原有预算时先合并为完整树快照,仍超限则使用可读正文降级并保留原有远程截断标记,不传半截操作 JSON。++用户值在查看端保存,按账号、消息、片段隔离;手机另包含来源设备和任务身份,不进入模型上下文。缓存最多 256 个片段、总序列化 524288 个字符;未修改控件继续使用模型默认值。异步读取不会覆盖加载期间新输入。当前查看端之间不自动同步控件状态。旧客户端没有组件渲染器,可能显示原始围栏;对不支持组件的渠道可使用普通 Markdown。++## 公共交付入口++统一路径只有:**公共交付说明与已有用户偏好 → 当前模型生成 → Cindy 流式展示**。++`ANSWER_DELIVERY_PROMPT` 在 `packages/maker-shared/src/richAnswerGuide.ts` 定义一次;Desktop Host 通过 runtime config 的 `answerDeliveryPrompt` 提供给三个适配器。Codex 使用现有 developer instructions,Claude Code 使用现有 system append(本地与远端),Pi 使用现有 `--append-system-prompt`。普通任务和伙伴都使用这一段,不因伙伴跳过普通 Cindy 身份说明而丢失交付能力。隔离 Reviewer 不注入这一段。++这是一项明确的宿主提示词改动:直接告诉当前模型可用组件、流式操作格式与交互边界。无需先调用发现工具,也不增加第二次答案优化调用。能力查询仍返回同一份协议,避免两份规则。用户偏好沿用已有 userPrompt、伙伴用户档案与当轮请求,不新增偏好存储,不修改或覆盖 CLI 二进制、原生提示词和模型缓存。++模型自由组合布局;简单回答、代码和显式要求的格式保持简洁。组件仅适用于 Cindy 正文,外部渠道沿用其格式。控件只改变本地查看状态,不执行工具、不提交用户输入。原有执行、停止、上下文压缩及工作过程折叠流程不变。计算可引用输入与其它计算节点;缺失、循环或非法计算显示局部不可用,不伪造零值。流式尚未到达的引用先等待。++## 验收状态++本地实现与定向测试已完成。通过隔离 Cindy 的实际 maker 入口运行 18 次:5 个自然请求(费用比较、图文、简短算术、代码、勾选清单)× Codex / Claude Code / Pi,加上三种 Harness 各一个测试伙伴。12 份组件正文均无解析错误和不可用计算,6 份简单/代码回答使用普通正文。三个费用比较在 12 个月并开启服务时均显示 300 / 240、省 60;清单勾选两项后均为 2 / 4。伙伴沿用用户档案的“清单在前、完成数量在后”偏好。单次样本不代表稳定成功率;Claude Code 的代码回答多了一句说明,费用回答有空代码围栏,已在报告保留。++iPhone 原生测试版回放真实结果,已检查任务、伙伴、流式到完成态、控件联动、窄列图文、浅深色与重启恢复。原生无障碍滑杆增减已验证,手指拖动尚未单独验收。手机使用已有 Visual Mock 接口,不代替登录后的跨设备 Device Link 全链路;该链路以及本次视频播放、SSH 媒体仍未重新实测。++共享解析/消息测试 85 项;Desktop 组件、伙伴投影、历史摘要和远程传输 145 项;Mobile 伙伴投影 23 项;三 Harness 真实指令组装定向测试 4 项。两端类型检查、共享包构建检查通过,未跑无关全量。实测修复了移动端流式到历史行的身份切换、桌面立即重载丢控件值,以及计算节点引用静默归零。++当前组件使用宿主主题,不支持任意 HTML/CSS 或文字颜色;按钮只改本地状态。原型中的外部动作、自定义隔离可视化尚未接入,不宣称全部原型设想已交付。++旧完整 HTML 预览路径已移除,其旧验收不覆盖本实现。送审不代表跨设备补充验收已完成;合并/发布前仍须补齐上面列明的相关场景。++## 界面证据++真实模型费用比较,12 个月并开启服务;宿主原生组件显示 300 / 240、省 60。图片只含本任务合成测试内容。++++| iOS 浅色(原生回放) | iOS 深色(原生回放) |+| --- | --- |+|  |  |diff --git a/packages/lizi-mcps/src/xdt-helper/capabilities.ts b/packages/lizi-mcps/src/xdt-helper/capabilities.tsindex e04cb79d1e..75083fba82 100644--- a/packages/lizi-mcps/src/xdt-helper/capabilities.ts+++ b/packages/lizi-mcps/src/xdt-helper/capabilities.ts@@ -17,6 +17,7 @@* 因为后者是 Cindy 最差异化的能力,值得独立索引项让模型一眼能查到。*/+import { RICH_ANSWER_GUIDE } from '@cindy/maker-shared/rich-answer-guide';import { BRAND_NAME } from '@cindy/maker-shared/branding';export interface CapabilityEntry {@@ -27,6 +28,12 @@ export interface CapabilityEntry {}export const CAPABILITIES: readonly CapabilityEntry[] = [+ {+ key: 'rich-answers',+ title: '流式正文与可组合组件',+ oneLiner: '模型可自由组合正文图文、图表与交互控件,增量更新;按需查询组件协议,不要求另存 HTML。',+ detail: RICH_ANSWER_GUIDE,+ },{key: 'grok-login',title: 'Grok / SuperGrok 授权登录',diff --git a/packages/maker-core/src/agents/claude-code/__tests__/bot-profile-prompt.test.ts b/packages/maker-core/src/agents/claude-code/__tests__/bot-profile-prompt.test.tsindex 5d37d19708..8eef2e3c86 100644--- a/packages/maker-core/src/agents/claude-code/__tests__/bot-profile-prompt.test.ts+++ b/packages/maker-core/src/agents/claude-code/__tests__/bot-profile-prompt.test.ts@@ -6,6 +6,7 @@ describe('Claude Bot Profile prompt assembly', () => {it('keeps the Bot SOUL as the first Cindy-owned stable segment', () => {const prompt = buildClaudeSystemPromptAppend({botProfilePrompt: 'BOT SOUL',+ answerDeliveryPrompt: 'DELIVERY PROTOCOL',botProfileContextPrompt: 'ACTIVE BOT PROFILE',makerMemoryRules: 'MEMORY RULES',hostSystemPrompt: 'HOST RULES',@@ -14,7 +15,7 @@ describe('Claude Bot Profile prompt assembly', () => {userPrompt: 'USER OVERRIDE',});- expect(prompt.startsWith('BOT SOUL\n\n')).toBe(true);+ expect(prompt.startsWith('BOT SOUL\n\nDELIVERY PROTOCOL')).toBe(true);expect(prompt.indexOf('BOT SOUL')).toBeLessThan(prompt.indexOf('MEMORY RULES'));expect(prompt.indexOf('ACTIVE BOT PROFILE')).toBeGreaterThan(prompt.indexOf('MEMORY RULES'));expect(prompt.indexOf('ACTIVE BOT PROFILE')).toBeLessThan(prompt.indexOf('HOST RULES'));diff --git a/packages/maker-core/src/agents/claude-code/index.ts b/packages/maker-core/src/agents/claude-code/index.tsindex 793885be70..601121e845 100644--- a/packages/maker-core/src/agents/claude-code/index.ts+++ b/packages/maker-core/src/agents/claude-code/index.ts@@ -247,11 +247,13 @@ export function buildClaudeSystemPromptAppend(parts: {botProfileContextPrompt?: string;botUserProfilePrompt?: string;userPrompt?: string;+ answerDeliveryPrompt?: string;/** 设备托管:项目在哪台电脑、文件与命令工具是哪些。 */deviceHostedNote?: string;}): string {return [parts.botProfilePrompt,+ parts.answerDeliveryPrompt,MAKER_SYSTEM_PROMPT_APPEND,parts.deviceHostedNote,parts.makerMemoryRules,@@ -3817,6 +3819,7 @@ export class ClaudeCodeAgent extends BaseAgent {: {}),systemPrompt: (() => {const appendText = buildClaudeSystemPromptAppend({+ answerDeliveryPrompt: reviewMode ? undefined : this.deps.runtimeConfig.answerDeliveryPrompt,makerMemoryRules,contactsRules,ghostRosterPrompt,@@ -4374,6 +4377,7 @@ export class ClaudeCodeAgent extends BaseAgent {// 空段被 .filter 跳过 (.md 文件为空 / userPrompt 为空 = 不 append).systemPrompt: (() => {const appendText = buildClaudeSystemPromptAppend({+ answerDeliveryPrompt: reviewMode ? undefined : this.deps.runtimeConfig.answerDeliveryPrompt,makerMemoryRules,contactsRules,ghostRosterPrompt,diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex e53a8d40b5..486dcc60b5 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -2376,7 +2376,9 @@ describe('CodexAgent permissions', () => {});it('keeps Bot identity and MCP config while honoring the selected task permission mode', async () => {- const agent = new CodexAgent(createDeps());+ const deps = createDeps();+ deps.runtimeConfig.answerDeliveryPrompt = 'DELIVERY PROTOCOL';+ const agent = new CodexAgent(deps);const host = installFakeHost(agent, undefined, {buildSessionMcpConfig: () => ({'mcp_servers.bot_helper.url': 'http://127.0.0.1:45831/mcp',@@ -2403,6 +2405,7 @@ describe('CodexAgent permissions', () => {});expect(threadStart).not.toHaveProperty('permissions');expect(threadStart.developerInstructions).toContain('BOT SOUL');+ expect(threadStart.developerInstructions).toContain('DELIVERY PROTOCOL');await handle.setPermissionMode?.('ask');await handle.send({ type: 'user', content: 'Inspect the project.' });diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex f0fc737f08..4e51f1a02b 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -443,9 +443,11 @@ function buildCodexDeveloperInstructions(parts: {botProfileContextPrompt?: string;botUserProfilePrompt?: string;userPrompt?: string;+ answerDeliveryPrompt?: string;}): string {return [parts.botProfilePrompt,+ parts.answerDeliveryPrompt,MAKER_CODEX_SYSTEM_PROMPT_APPEND,parts.makerMemoryRules,parts.contactsRules,@@ -6974,6 +6976,7 @@ assertRouteCurrent();? '': (this.deps.getGhostRosterPrompt?.({ workingDir: opts.workingDir }) ?? '');const developerInstructions = buildCodexDeveloperInstructions({+ answerDeliveryPrompt: reviewMode ? undefined : this.deps.runtimeConfig.answerDeliveryPrompt,makerMemoryRules,contactsRules,ghostRosterPrompt,diff --git a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.tsindex 52cefd2be5..24a8a4c026 100644--- a/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts+++ b/packages/maker-core/src/agents/pi/__tests__/pi-auto-review-dispatch.test.ts@@ -3252,6 +3252,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {deps.resolvePiGlobalContextHome = vi.fn(() => { throw new Error('Bot must not read user context'); });deps.getGhostRosterPrompt = vi.fn(() => 'BOT ROSTER');deps.runtimeConfig.memoryEnabled = false;+ deps.runtimeConfig.answerDeliveryPrompt = 'DELIVERY PROTOCOL';const handle = await new PiAgent(deps).startSession({sessionId: 'bot-read-only-session',workingDir: cwd,@@ -3287,6 +3288,7 @@ describe('pi auto-review dispatch & spawn config (mocked pi process)', () => {expect(deps.resolvePiGlobalContextHome).not.toHaveBeenCalled();const promptIndex = captured.args.indexOf('--append-system-prompt');expect(captured.args[promptIndex + 1]).toContain('BOT SOUL');+ expect(captured.args[promptIndex + 1]).toContain('DELIVERY PROTOCOL');expect(captured.args[promptIndex + 1]).not.toContain('BOT ROSTER');expect(captured.args[promptIndex + 1]).not.toContain('You are Cindy.');expect(captured.args[promptIndex + 1]).not.toContain('GLOBAL USER PROMPT');diff --git a/packages/maker-core/src/agents/pi/index.ts b/packages/maker-core/src/agents/pi/index.tsindex 6e9f36b741..68fb11f120 100644--- a/packages/maker-core/src/agents/pi/index.ts+++ b/packages/maker-core/src/agents/pi/index.ts@@ -3744,6 +3744,7 @@ export class PiAgent extends BaseAgent {? '': (this.deps.getGhostRosterPrompt?.({ workingDir: opts.workingDir }) ?? '');const appendSections = [+ reviewMode ? undefined : this.deps.runtimeConfig.answerDeliveryPrompt?.trim(),reviewMode ? undefined : opts.botProfilePrompt?.trim(),opts.botRuntimeProfile ? undefined : this.deps.runtimeConfig.systemPrompt?.trim(),ghostRosterPrompt.trim(),diff --git a/packages/maker-core/src/interfaces/runtime-config.ts b/packages/maker-core/src/interfaces/runtime-config.tsindex cd3e81b38c..48bc285ed2 100644--- a/packages/maker-core/src/interfaces/runtime-config.ts+++ b/packages/maker-core/src/interfaces/runtime-config.ts@@ -157,6 +157,9 @@ export interface AgentRuntimeConfig {* Codex: SDK 不支持,传了也忽略。*/systemPrompt?: string;+ /** Host-owned answer presentation protocol. Shared by normal and Bot sessions;+ * appended to native instructions, never replaces the CLI's own prompt. */+ answerDeliveryPrompt?: string;/*** 是否启用 agent 的自动记忆 (Claude auto-memory / Codex experimental memories)。diff --git a/packages/maker-shared/package.json b/packages/maker-shared/package.jsonindex 99270c587c..446d2e9304 100644--- a/packages/maker-shared/package.json+++ b/packages/maker-shared/package.json@@ -34,7 +34,6 @@"./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",@@ -42,6 +41,8 @@"./math-markdown": "./src/mathMarkdown.ts","./mention-ref": "./src/mentionRef.ts","./mermaid-autofix": "./src/mermaidAutofix.ts",+ "./rich-answer": "./src/richAnswer.ts",+ "./rich-answer-guide": "./src/richAnswerGuide.ts","./message-render": "./src/messageRender.ts","./message-normalize": "./src/messageNormalize.ts","./mcp-apps": "./src/mcpApps.ts",diff --git a/packages/maker-shared/src/__tests__/htmlAnswer.test.ts b/packages/maker-shared/src/__tests__/htmlAnswer.test.tsdeleted file mode 100644index 5b65c99a16..0000000000--- a/packages/maker-shared/src/__tests__/htmlAnswer.test.ts+++ /dev/null@@ -1,38 +0,0 @@-import { describe, expect, it } from "vitest";-import {- HTML_ANSWER_MAX_HEIGHT,- 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: 4800 })).toBe(4800);- expect(- htmlAnswerHeight({ type: "cindy-html-answer-size", height: 1e9 }),- ).toBe(HTML_ANSWER_MAX_HEIGHT);- 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 3330c62c09..bac1293926 100644--- a/packages/maker-shared/src/__tests__/messageRender.test.ts+++ b/packages/maker-shared/src/__tests__/messageRender.test.ts@@ -288,10 +288,9 @@ describe('message render shared model', () => {// 交付正文与位置无关地留在折叠组外。原始形状(2026-07-31 定时巡检):agent 先输出// 长篇简报,再调 notify 发通知,最后说一句「已触发通知」——SDK seal 只盖最后那句,// 「最终答复」回溯又遇工具即停,简报会被整段折进「工作过程」。- 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) => {+ 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);const items = buildMessageRenderItems([message({ kind: 'user', source: source('user', 'brief me', 1), body: 'brief me', label: 'user' }),diff --git a/packages/maker-shared/src/__tests__/richAnswer.test.ts b/packages/maker-shared/src/__tests__/richAnswer.test.tsnew file mode 100644index 0000000000..edc718f03a--- /dev/null+++ b/packages/maker-shared/src/__tests__/richAnswer.test.ts@@ -0,0 +1,108 @@+import { describe, expect, it } from 'vitest';+import { RichAnswerStream, RichInteractionMemory, hasRichAnswer, splitRichAnswer, richDefaults, richEvaluate, richLabel, richResolvedValues, richChart, richCalculationUnavailable } from '../richAnswer';+// Tier 1: actual stream reducer. Regression targets are partial transport, edits,+// replay and preservation of user input; no DOM/source-string contracts.+const line = (seq: number, op: Record<string, unknown>) => JSON.stringify({ seq, ...op }) + '\n';+describe('streaming answer documents', () => {+ it('commits complete operations before the closing fence without exposing partial protocol', () => {+ const first = line(1, { op: 'create', id: 'title', kind: 'heading', props: { text: '你好' } });+ const second = line(2, { op: 'append', id: 'title', text: ',世界' });+ const parser = new RichAnswerStream();+ const input = 'Introduction\n```cindy-ui\n' + first + second;+ for (let length = 0; length <= input.length; length++) {+ const parts = splitRichAnswer(input.slice(0, length));+ const part = parts.find(p => p.kind === 'rich');+ if (!part) continue;+ const doc = parser.update(part.source, part.complete);+ const expected = length >= input.length ? '你好,世界' : length >= input.length - second.length ? '你好' : undefined;+ expect(doc.nodes.get('title')?.props.text).toBe(expected);+ expect(doc.issues).toBe(0);+ }+ expect(hasRichAnswer('```cindy-ui')).toBe(true);+ expect(hasRichAnswer('````markdown\n```cindy-ui\n{}\n```\n````')).toBe(false);+ });+ it('replays source snapshots, ignores duplicate operations and never mutates earlier snapshots', () => {+ const create = line(1, { op: 'create', id: 'a', kind: 'text', props: { text: 'one' } });+ const append = line(2, { op: 'append', id: 'a', text: ' two' });+ const parser = new RichAnswerStream(), first = parser.update(create);+ const next = parser.update(create + append + append);+ expect(next.nodes.get('a')?.props.text).toBe('one two');+ expect(first.nodes.get('a')?.props.text).toBe('one');+ expect(new RichAnswerStream().update(create + append).nodes).toEqual(next.nodes);+ expect(parser.update(create).nodes.get('a')?.props.text).toBe('one');+ });+ it('keeps user-edited state while model defaults and calculated data change', () => {+ const parser = new RichAnswerStream(), memory = new RichInteractionMemory();+ const source = line(1, { op: 'create', id: 'months', kind: 'range', props: { default: 6 } }) + line(2, { op: 'create', id: 'cost', kind: 'stat', props: { value: { op: 'mul', args: [{ ref: 'months' }, 10] } } });+ let doc = parser.update(source);+ memory.set('owner/device/message', { months: 9 });+ doc = parser.update(source + line(3, { op: 'patch', id: 'months', props: { default: 12 } }));+ const values = { ...richDefaults(doc), ...memory.get('owner/device/message') };+ expect(richLabel(doc.nodes.get('cost')!, values)).toBe('90');+ expect(memory.get('other-owner/device/message')).toEqual({});+ expect(richEvaluate({ op: 'div', args: [1, 0] }, values)).toBeUndefined();+ });+ it('moves and removes subtrees and isolates invalid updates from existing readable content', () => {+ const ops = [+ { op: 'create', id: 'group', kind: 'stack' },+ { op: 'create', id: 'text', kind: 'text', parent: 'group', props: { text: 'Readable' } },+ { op: 'move', id: 'group', parent: 'group' },+ { op: 'move', id: 'text', parent: 'root' },+ { op: 'remove', id: 'group' },+ ];+ const doc = new RichAnswerStream().update(ops.map((op, i) => line(i + 1, op)).join(''));+ expect(doc.roots).toEqual(['text']);+ expect(doc.nodes.get('text')?.props.text).toBe('Readable');+ expect(doc.issues).toBe(1);+ });+});+it('restores persisted controls without overwriting input entered during a slow load', async () => {+ let release!: (value: string | null) => void;+ let persisted = '';+ const memory = new RichInteractionMemory({+ read: () => new Promise(resolve => { release = resolve; }),+ write: async value => { persisted = value; },+ });+ const loading = memory.load();+ memory.set('owner/device/message', { months: 9 });+ release(JSON.stringify({ version: 1, entries: [['owner/device/message', { months: 2, enabled: true }]] }));+ await loading;+ expect(memory.get('owner/device/message')).toEqual({ months: 9, enabled: true });+ await memory.flush();+ const restored = new RichInteractionMemory({ read: async () => persisted, write: async () => {} });+ await restored.load();+ expect(restored.get('owner/device/message')).toEqual({ months: 9, enabled: true });+});++// Tier 1: a real Claude comparison referenced calculated stat IDs. Previously+// totals were right but the winner, savings and chart silently treated them as zero.+it('resolves calculated references and updates dependent labels and charts after input', () => {+ const source = [+ { id: 'months', kind: 'range', props: { default: 6 } },+ { id: 'extra', kind: 'check', props: { default: false } },+ { id: 'saving', kind: 'stat', props: { value: { op: 'sub', args: [{ ref: 'monthly' }, { ref: 'yearly' }] } } },+ { id: 'monthly', kind: 'stat', props: { value: { op: 'mul', args: [{ ref: 'months' }, { op: 'if', args: [{ ref: 'extra' }, 25, 20] }] } } },+ { id: 'yearly', kind: 'stat', props: { value: { op: 'add', args: [180, { op: 'if', args: [{ ref: 'extra' }, { op: 'mul', args: [5, { ref: 'months' }] }, 0] }] } } },+ { id: 'winner', kind: 'text', props: { value: { op: 'if', args: [{ op: 'gt', args: [{ ref: 'saving' }, 0] }, 'yearly', 'monthly'] } } },+ { id: 'chart', kind: 'chart', props: { data: [{ label: 'Monthly', value: { ref: 'monthly' } }, { label: 'Yearly', value: { ref: 'yearly' } }] } },+ ].map((node, i) => line(i + 1, { op: 'create', ...node })).join('');+ const doc = new RichAnswerStream().update(source, true);+ const initial = richResolvedValues(doc);+ expect(richLabel(doc.nodes.get('winner')!, initial)).toBe('monthly');+ const edited = richResolvedValues(doc, { months: 12, extra: true });+ expect(richLabel(doc.nodes.get('saving')!, edited)).toBe('60');+ expect(richLabel(doc.nodes.get('winner')!, edited)).toBe('yearly');+ expect(richChart(doc.nodes.get('chart')!, edited).map(x => x.value)).toEqual([300, 240]);+});+it('keeps missing, cyclic and invalid calculations unavailable instead of reporting zero', () => {+ const source = line(1, { op: 'create', id: 'a', kind: 'stat', props: { value: { ref: 'b' } } });+ const parser = new RichAnswerStream();+ let doc = parser.update(source);+ expect(richCalculationUnavailable(doc.nodes.get('a')!, richResolvedValues(doc))).toBe(true);+ doc = parser.update(source + line(2, { op: 'create', id: 'b', kind: 'stat', props: { value: { ref: 'a' } } }));+ expect(richLabel(doc.nodes.get('a')!, richResolvedValues(doc))).toBe('—');+ doc = parser.update(source + line(2, { op: 'create', id: 'b', kind: 'stat', props: { value: 25 } }));+ expect(richLabel(doc.nodes.get('a')!, richResolvedValues(doc))).toBe('25');+ expect(richEvaluate({ op: 'add', args: ['', 2] }, {})).toBeUndefined();+ expect(richEvaluate({ op: 'concat', args: Array(32).fill({ ref: 'text' }) }, { text: 'a'.repeat(4096) })).toBeUndefined();+});diff --git a/packages/maker-shared/src/htmlAnswer.ts b/packages/maker-shared/src/htmlAnswer.tsdeleted file mode 100644index e2f8190cce..0000000000--- a/packages/maker-shared/src/htmlAnswer.ts+++ /dev/null@@ -1,55 +0,0 @@-/** 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;-}--// Bound pathological documents without making ordinary long answers a nested scroller.-export const HTML_ANSWER_MAX_HEIGHT = 100_000;--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(1, Math.min(HTML_ANSWER_MAX_HEIGHT, 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"}; }- html, body { min-height: 0 !important; }- 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 body=document.body,style=getComputedStyle(body);- const height=Math.max(1,Math.ceil(Math.max(body.scrollHeight,body.getBoundingClientRect().height)+(parseFloat(style.marginTop)||0)+(parseFloat(style.marginBottom)||0)));- 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 7adb91a08b..17c8eb1e99 100644--- a/packages/maker-shared/src/messageRender.ts+++ b/packages/maker-shared/src/messageRender.ts@@ -1,4 +1,4 @@-import { htmlAnswerDocument } from './htmlAnswer.js';+import { hasRichAnswer } from './richAnswer';import { groupWorkRuns } from './workRunGrouping.js';import { isContinuationMessage } from './syntheticTrigger.js';export { groupWorkRuns, type WorkRunGroupingAdapter } from './workRunGrouping.js';@@ -1635,7 +1635,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 (hasRichAnswer(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;diff --git a/packages/maker-shared/src/richAnswer.ts b/packages/maker-shared/src/richAnswer.tsnew file mode 100644index 0000000000..11fa999b17--- /dev/null+++ b/packages/maker-shared/src/richAnswer.ts@@ -0,0 +1,731 @@+/** Model-neutral, declarative answer components. No code evaluation or I/O. */+export const RICH_ANSWER_LANGUAGE = "cindy-ui";+export const RICH_ANSWER_KINDS = [+ "text",+ "markdown",+ "heading",+ "stack",+ "row",+ "grid",+ "group",+ "divider",+ "image",+ "video",+ "audio",+ "code",+ "math",+ "diagram",+ "stat",+ "chart",+ "range",+ "input",+ "check",+ "select",+ "button",+ "form",+ "details",+ "tabs",+] as const;+export type RichAnswerKind = (typeof RICH_ANSWER_KINDS)[number];+export type RichValue = string | number | boolean;+export type RichValues = Readonly<Record<string, RichValue | undefined>>;+export interface RichNode {+ id: string;+ kind: RichAnswerKind;+ props: Record<string, unknown>;+ children: string[];+}+export interface RichDocument {+ nodes: ReadonlyMap<string, RichNode>;+ roots: readonly string[];+ revision: number;+ issues: number;+}+export type RichPart = {+ kind: "markdown" | "rich";+ key: number;+ source: string;+ complete: boolean;+};+const ID = /^[a-zA-Z0-9_-]{1,80}$/;+const MAX_SOURCE = 2_000_000;+const MAX_NODES = 2048;+const MAX_DEPTH = 32;+const record = (v: unknown): v is Record<string, unknown> =>+ !!v && typeof v === "object" && !Array.isArray(v);+const value = (v: unknown): v is RichValue =>+ typeof v === "string" ||+ typeof v === "boolean" ||+ (typeof v === "number" && Number.isFinite(v));+const own = (o: object, k: string) =>+ Object.prototype.hasOwnProperty.call(o, k);++/** Split only explicit answer fences, never a cindy-ui example inside another fence. */+export function splitRichAnswer(source: string): RichPart[] {+ const parts: RichPart[] = [];+ let cursor = 0,+ start = 0,+ richStart = -1;+ let fence: { char: string; count: number; rich: boolean } | undefined;+ // Line iteration preserves source offsets/keys as the tail grows.+ for (const line of source.split(/(?<=\n)/)) {+ const body = line.replace(/\r?\n$/, "");+ if (!fence) {+ const open = body.match(/^ {0,3}(`{3,}|~{3,})([^\r\n]*)$/);+ if (open) {+ fence = {+ char: open[1][0],+ count: open[1].length,+ rich: open[2].trim() === RICH_ANSWER_LANGUAGE,+ };+ if (fence.rich) {+ if (cursor > start)+ parts.push({+ kind: "markdown",+ key: start,+ source: source.slice(start, cursor),+ complete: true,+ });+ richStart = cursor;+ start = cursor + line.length;+ }+ }+ } else if (+ new RegExp(`^ {0,3}${fence.char}{${fence.count},}\\s*$`).test(body)+ ) {+ if (fence.rich && richStart >= 0) {+ parts.push({+ kind: "rich",+ key: richStart,+ source: source.slice(start, cursor),+ complete: true,+ });+ start = cursor + line.length;+ richStart = -1;+ }+ fence = undefined;+ }+ cursor += line.length;+ }+ if (richStart >= 0)+ parts.push({+ kind: "rich",+ key: richStart,+ source: source.slice(start),+ complete: false,+ });+ else if (start < source.length)+ parts.push({+ kind: "markdown",+ key: start,+ source: source.slice(start),+ complete: false,+ });+ return parts;+}+export const hasRichAnswer = (source: string): boolean =>+ splitRichAnswer(source).some((p) => p.kind === "rich");++/** One instance per answer fragment. Snapshot corrections rebuild; append-only deltas parse once. */+export class RichAnswerStream {+ private source = "";+ private offset = 0;+ private seq = 0;+ private nodes = new Map<string, RichNode>();+ private roots: string[] = [];+ private revision = 0;+ private issues = 0;+ update(source: string, complete = false): RichDocument {+ if (!source.startsWith(this.source)) {+ this.source = "";+ this.offset = 0;+ this.seq = 0;+ this.nodes = new Map();+ this.roots = [];+ this.issues = 0;+ this.revision++;+ }+ if (source.length > MAX_SOURCE) {+ this.issues = Math.max(1, this.issues);+ return this.snapshot();+ }+ this.source = source;+ this.nodes = new Map(this.nodes);+ let end: number;+ while ((end = source.indexOf("\n", this.offset)) !== -1) {+ this.line(source.slice(this.offset, end));+ this.offset = end + 1;+ }+ if (complete && this.offset < source.length) {+ this.line(source.slice(this.offset));+ this.offset = source.length;+ }+ return this.snapshot();+ }+ private snapshot(): RichDocument {+ return {+ nodes: this.nodes,+ roots: this.roots,+ revision: this.revision,+ issues: this.issues,+ };+ }+ private line(line: string) {+ if (!line.trim()) return;+ try {+ const op: unknown = JSON.parse(line);+ if (!record(op) || !Number.isSafeInteger(op.seq) || Number(op.seq) < 1)+ throw Error("sequence");+ const seq = Number(op.seq);+ if (seq <= this.seq) return;+ if (seq !== this.seq + 1) throw Error("gap");+ this.seq = seq;+ if (op.version !== undefined && op.version !== 1) throw Error("version");+ if (typeof op.id !== "string" || !ID.test(op.id)) throw Error("id");+ const current = this.nodes.get(op.id);+ if (op.op === "create") {+ if (+ current ||+ this.nodes.size >= MAX_NODES ||+ !RICH_ANSWER_KINDS.includes(op.kind as RichAnswerKind)+ )+ throw Error("component");+ const parent =+ op.parent === undefined || op.parent === "root"+ ? null+ : this.nodes.get(String(op.parent));+ if (op.parent && op.parent !== "root" && !parent) throw Error("parent");+ if (+ parent &&+ ![+ "stack",+ "row",+ "grid",+ "group",+ "form",+ "details",+ "tabs",+ ].includes(parent.kind)+ )+ throw Error("leaf");+ const node: RichNode = {+ id: op.id,+ kind: op.kind as RichAnswerKind,+ props: this.props(op.props),+ children: [],+ };+ // The bounded depth also limits recursive React rendering.+ if (parent && this.depth(parent.id) >= MAX_DEPTH) throw Error("depth");+ this.nodes.set(node.id, node);+ const index = Number.isInteger(op.index)+ ? Math.max(0, Number(op.index))+ : Infinity;+ if (parent) {+ const children = [...parent.children];+ children.splice(index, 0, node.id);+ this.nodes.set(parent.id, { ...parent, children });+ } else {+ this.roots = [...this.roots];+ this.roots.splice(index, 0, node.id);+ }+ } else if (op.op === "append") {+ if (+ !current ||+ !["text", "markdown", "heading", "code", "math", "diagram"].includes(+ current.kind,+ ) ||+ typeof op.text !== "string"+ )+ throw Error("text");+ this.nodes.set(current.id, {+ ...current,+ props: {+ ...current.props,+ text: richString(current, "text") + op.text,+ },+ });+ } else if (op.op === "patch") {+ if (!current) throw Error("target");+ this.nodes.set(current.id, {+ ...current,+ props: { ...current.props, ...this.props(op.props) },+ });+ } else if (op.op === "remove") {+ if (!current) throw Error("target");+ const remove = (id: string) => {+ this.nodes.get(id)?.children.forEach(remove);+ this.nodes.delete(id);+ };+ remove(current.id);+ this.roots = this.roots.filter((id) => id !== current.id);+ for (const [id, node] of this.nodes)+ if (node.children.includes(current.id))+ this.nodes.set(id, {+ ...node,+ children: node.children.filter((x) => x !== current.id),+ });+ } else if (op.op === "move") {+ if (!current) throw Error("target");+ const parent =+ op.parent === "root" ? null : this.nodes.get(String(op.parent));+ if (op.parent !== "root" && !parent) throw Error("parent");+ if (+ parent &&+ (![+ "stack",+ "row",+ "grid",+ "group",+ "form",+ "details",+ "tabs",+ ].includes(parent.kind) ||+ this.descendant(current.id, parent.id))+ )+ throw Error("cycle");+ const height = (id: string): number =>+ 1 + Math.max(0, ...(this.nodes.get(id)?.children.map(height) ?? []));+ if (+ (parent ? this.depth(parent.id) : 0) + height(current.id) >+ MAX_DEPTH+ )+ throw Error("depth");+ this.roots = this.roots.filter((id) => id !== current.id);+ for (const [id, node] of this.nodes)+ if (node.children.includes(current.id))+ this.nodes.set(id, {+ ...node,+ children: node.children.filter((x) => x !== current.id),+ });+ const index = Number.isInteger(op.index)+ ? Math.max(0, Number(op.index))+ : Infinity;+ if (parent) {+ const node = this.nodes.get(parent.id)!;+ const children = [...node.children];+ children.splice(index, 0, current.id);+ this.nodes.set(node.id, { ...node, children });+ } else {+ this.roots = [...this.roots];+ this.roots.splice(index, 0, current.id);+ }+ } else throw Error("operation");+ this.revision++;+ } catch {+ this.issues++;+ }+ }+ private props(v: unknown): Record<string, unknown> {+ if (v === undefined) return {};+ if (!record(v) || JSON.stringify(v).length > 65_536) throw Error("props");+ return Object.fromEntries(+ Object.entries(v).filter(+ ([key]) => !["__proto__", "constructor", "prototype"].includes(key),+ ),+ );+ }+ private descendant(root: string, id: string): boolean {+ return (+ root === id ||+ !!this.nodes+ .get(root)+ ?.children.some((child) => this.descendant(child, id))+ );+ }+ private depth(id: string): number {+ for (const node of this.nodes.values())+ if (node.children.includes(id)) return 1 + this.depth(node.id);+ return 1;+ }+}+export function richString(node: RichNode, key: string, fallback = ""): string {+ return typeof node.props[key] === "string"+ ? (node.props[key] as string)+ : fallback;+}+export function richNumber(+ node: RichNode,+ key: string,+ fallback: number,+): number {+ const v = node.props[key];+ return typeof v === "number" && Number.isFinite(v) ? v : fallback;+}+export function richOptions(+ node: RichNode,+): { label: string; value: string }[] {+ return Array.isArray(node.props.options)+ ? node.props.options+ .slice(0, 100)+ .filter(record)+ .filter(+ (x) => typeof x.label === "string" && typeof x.value === "string",+ )+ .map((x) => ({ label: String(x.label), value: String(x.value) }))+ : [];+}+export function richDefaults(+ document: RichDocument,+): Record<string, RichValue> {+ return Object.fromEntries(+ [...document.nodes.values()]+ .filter((n) =>+ ["input", "range", "select", "check", "tabs", "details"].includes(+ n.kind,+ ),+ )+ .map((n) => [+ richString(n, "bind", n.id),+ value(n.props.default)+ ? n.props.default+ : n.kind === "check" || n.kind === "details"+ ? false+ : n.kind === "range"+ ? richNumber(n, "min", 0)+ : "",+ ]),+ );+}+/** Resolve inputs and calculated node references from one document snapshot.+ * Forward references are supported; cycles and missing values stay unavailable. */+export function richResolvedValues(document: RichDocument, edited: RichValues = {}): RichValues {+ const values: Record<string, RichValue | undefined> = { ...richDefaults(document), ...edited };+ const visiting = new Set<string>();+ const resolve = (id: string): RichValue | undefined => {+ if (own(values, id)) return values[id];+ if (visiting.has(id) || visiting.size >= MAX_DEPTH) return undefined;+ const node = document.nodes.get(id);+ if (!node || !["stat", "text", "heading"].includes(node.kind)) return undefined;+ visiting.add(id);+ const result = richEvaluate(node.props.value ?? node.props.text, values, 0, resolve);+ visiting.delete(id);+ Object.defineProperty(values, id, { value: result, enumerable: true, configurable: true });+ return result;+ };+ for (const node of document.nodes.values()) resolve(node.id);+ return values;+}++/** Whitelisted arithmetic, never JavaScript. Unavailable values cannot coerce to zero. */+export function richEvaluate(+ expr: unknown,+ values: RichValues,+ depth = 0,+ resolve?: (id: string) => RichValue | undefined,+): RichValue | undefined {+ if (value(expr)) return expr;+ if (!record(expr) || depth > 16) return undefined;+ if (typeof expr.ref === "string")+ return own(values, expr.ref) ? values[expr.ref] : resolve?.(expr.ref);+ if (!Array.isArray(expr.args) || expr.args.length > 32) return undefined;+ const evaluate = (x: unknown) => richEvaluate(x, values, depth + 1, resolve);+ // Evaluate only the selected branch: an unused forward reference is harmless.+ if (expr.op === "if") {+ if (expr.args.length !== 3) return undefined;+ const condition = evaluate(expr.args[0]);+ return condition === undefined ? undefined : evaluate(expr.args[condition ? 1 : 2]);+ }+ const args = expr.args.map(evaluate);+ if (args.some(x => x === undefined)) return undefined;+ if (expr.op === "concat") {+ // Computed references may share and repeatedly double strings. Bound the+ // result before allocating it, just like an individual node props payload.+ if (args.reduce<number>((size, arg) => size + String(arg).length, 0) > 65_536) return undefined;+ return args.join("");+ }+ if (["eq", "lt", "gt", "sub", "div"].includes(String(expr.op)) && args.length !== 2) return undefined;+ if (expr.op === "eq") return args[0] === args[1];+ if (args.length === 0 || args.some(x => typeof x === "string" && !x.trim())) return undefined;+ const nums = args.map(Number);+ if (!nums.every(Number.isFinite)) return undefined;+ let result: number;+ switch (expr.op) {+ case "add": result = nums.reduce((a, b) => a + b, 0); break;+ case "mul": result = nums.reduce((a, b) => a * b, 1); break;+ case "sub": result = nums[0] - nums[1]; break;+ case "div": result = nums[0] / nums[1]; break;+ case "min": result = Math.min(...nums); break;+ case "max": result = Math.max(...nums); break;+ case "lt": return nums[0] < nums[1];+ case "gt": return nums[0] > nums[1];+ default: return undefined;+ }+ return Number.isFinite(result) ? result : undefined;+}+export function richValue(node: RichNode, values: RichValues): RichValue | undefined {+ return richEvaluate(node.props.value ?? node.props.text ?? "", values);+}+export function richLabel(node: RichNode, values: RichValues): string {+ const result = richValue(node, values);+ return result === undefined ? "—" : richString(node, "prefix") + String(result) + richString(node, "suffix");+}+/** Component-local pending/error display; unaffected prose and controls remain usable. */+export function richCalculationUnavailable(node: RichNode, values: RichValues): boolean {+ if (["stat", "text", "heading"].includes(node.kind)) return richValue(node, values) === undefined;+ return node.kind === "chart" && Array.isArray(node.props.data) && node.props.data.some(item => {+ if (!record(item)) return true;+ const result = richEvaluate(item.value, values);+ return result === undefined || (typeof result === "string" && !result.trim()) || !Number.isFinite(Number(result));+ });+}+export function richAction(node: RichNode, values: RichValues): Record<string, RichValue> {+ const action = node.props.set;+ if (!record(action)) return {};+ const changes: Record<string, RichValue> = {};+ for (const [key, expr] of Object.entries(action).filter(([key]) => ID.test(key)).slice(0, 100)) {+ const result = richEvaluate(expr, values);+ if (result === undefined) return {}; // an invalid form cannot partially apply+ Object.defineProperty(changes, key, { value: result, enumerable: true, configurable: true });+ }+ return changes;+}++/** Route media and links through the existing Markdown trust and file-origin path. */+export function richMarkdown(node: RichNode): string | null {+ const text = richString(node, "text");+ const fenced = (language: string) => {+ const fence = "`".repeat(+ Math.max(3, ...[...text.matchAll(/`+/g)].map((m) => m[0].length + 1)),+ );+ return `${fence}${language}\n${text}\n${fence}`;+ };+ if (node.kind === "markdown") return text;+ if (node.kind === "code")+ return fenced(richString(node, "language").replace(/[^\w+-]/g, ""));+ if (node.kind === "diagram") return fenced("mermaid");+ if (node.kind === "math") return `$$\n${text}\n$$`;+ if (["image", "video", "audio"].includes(node.kind)) {+ const src = richString(node, "src").replace(/[\n\r<>]/g, "");+ const alt = richString(node, "alt").replace(/[\[\]\\\n\r]/g, "");+ return src ? `` : "";+ }+ return null;+}++/** View-state cache, keyed by owner/device/message/fragment by each host. Never model context. */+export interface RichStateStorage {+ read(): Promise<string | null>;+ write(serialized: string): Promise<void>;+ writeSync?(serialized: string): void;+}+export class RichInteractionMemory {+ private entries = new Map<string, RichValues>();+ private empty: RichValues = Object.freeze({});+ private listeners = new Set<() => void>();+ private loading?: Promise<void>;+ private timer?: ReturnType<typeof setTimeout>;+ private writes = Promise.resolve();+ constructor(private storage?: RichStateStorage) {}+ get(key: string): RichValues {+ return this.entries.get(key) ?? this.empty;+ }+ subscribe = (listener: () => void): (() => void) => {+ this.listeners.add(listener);+ return () => {+ this.listeners.delete(listener);+ };+ };+ private notify(): void {+ this.listeners.forEach((listener) => listener());+ }+ load(): Promise<void> {+ return (this.loading ??= (async () => {+ if (!this.storage) return;+ try {+ const raw = await this.storage.read();+ if (!raw || raw.length > 524288) return;+ const parsed: unknown = JSON.parse(raw);+ if (+ !record(parsed) ||+ parsed.version !== 1 ||+ !Array.isArray(parsed.entries)+ )+ return;+ const stored = new Map<string, RichValues>();+ for (const pair of parsed.entries.slice(-256)) {+ if (+ !Array.isArray(pair) ||+ typeof pair[0] !== "string" ||+ !record(pair[1])+ )+ continue;+ const values = Object.fromEntries(+ Object.entries(pair[1]).filter(+ ([key, v]) => ID.test(key) && value(v),+ ),+ );+ if (JSON.stringify(values).length <= 65536)+ stored.set(pair[0], values as Record<string, RichValue>);+ }+ // A slow read never overwrites input entered while hydration is pending.+ for (const [key, edited] of this.entries)+ stored.set(key, { ...stored.get(key), ...edited });+ this.entries = stored;+ this.trim();+ this.notify();+ } catch {+ /* View-state recovery must not prevent reading the answer. */+ }+ })());+ }+ set(key: string, patch: RichValues): RichValues {+ const next = { ...this.get(key), ...patch };+ if (Object.keys(next).length > 2048 || JSON.stringify(next).length > 65536)+ return this.get(key);+ this.entries.delete(key);+ this.entries.set(key, next);+ this.trim();+ this.notify();+ if (this.storage) {+ clearTimeout(this.timer);+ this.timer = setTimeout(() => {+ void this.flush();+ }, 200);+ }+ return next;+ }+ private serialize(): string {+ return JSON.stringify({ version: 1, entries: [...this.entries] });+ }+ private trim(): void {+ while (this.entries.size > 256 || this.serialize().length > 524288)+ this.entries.delete(this.entries.keys().next().value!);+ }+ flushSync(): void {+ clearTimeout(this.timer);+ try { this.storage?.writeSync?.(this.serialize()); } catch { /* Storage unavailable: keep in-memory values. */ }+ }+ async flush(): Promise<void> {+ clearTimeout(this.timer);+ await this.load();+ const serialized = this.serialize();+ this.writes = this.writes+ .then(() => this.storage?.write(serialized))+ .then(() => undefined)+ .catch(() => undefined);+ return this.writes;+ }+ clear(): void {+ this.entries.clear();+ this.notify();+ }+}+export function richChart(+ node: RichNode,+ values: RichValues,+): { label: string; value: number }[] {+ return Array.isArray(node.props.data)+ ? node.props.data+ .slice(0, 100)+ .filter(record)+ .map((item) => ({+ label: typeof item.label === "string" ? item.label : "",+ value: Number(richEvaluate(item.value, values)),+ }))+ .filter((item) => Number.isFinite(item.value))+ : [];+}+export function richRange(+ node: RichNode,+ current: unknown,+): { min: number; max: number; step: number; value: number } {+ const min = richNumber(node, "min", 0),+ max = Math.max(min + 1, richNumber(node, "max", 100));+ const step = Math.max(Number.EPSILON, richNumber(node, "step", 1));+ const n = Number(current);+ return {+ min,+ max,+ step,+ value: Math.min(max, Math.max(min, Number.isFinite(n) ? n : min)),+ };+}++/** Readable copy/export for channels without a component renderer. */+export function richAnswerText(source: string): string {+ return splitRichAnswer(source)+ .map((part) => {+ if (part.kind === "markdown") return part.source;+ const doc = new RichAnswerStream().update(part.source, true);+ const values = richResolvedValues(doc);+ const visit = (id: string): string => {+ const node = doc.nodes.get(id);+ if (!node) return "";+ const md = richMarkdown(node);+ if (md !== null)+ return (+ md ++ (richString(node, "caption")+ ? `\n${richString(node, "caption")}`+ : "")+ );+ if (node.children.length)+ return [richString(node, "label"), ...node.children.map(visit)]+ .filter(Boolean)+ .join("\n\n");+ if (node.kind === "heading") return `### ${richLabel(node, values)}`;+ if (node.kind === "text") return richLabel(node, values);+ if (node.kind === "divider") return "---";+ if (node.kind === "stat")+ return `${richString(node, "label")}: ${richLabel(node, values)}`;+ if (node.kind === "chart")+ return [+ richString(node, "label"),+ ...richChart(node, values).map(+ (item) => `${item.label}: ${item.value}`,+ ),+ ].join("\n");+ const current = values[richString(node, "bind", node.id)];+ if (node.kind === "check")+ return `${current ? "☑" : "☐"} ${richString(node, "label", richString(node, "text"))}`;+ return (+ richString(node, "label") ++ (current === undefined ? "" : `: ${current}`)+ );+ };+ return doc.roots.map(visit).filter(Boolean).join("\n\n");+ })+ .join("\n\n");+}+/** Collapse redundant operations into a complete replayable tree for bounded history frames. */+export function compactRichAnswer(source: string): string {+ return splitRichAnswer(source)+ .map((part) => {+ if (part.kind === "markdown") return part.source;+ const doc = new RichAnswerStream().update(part.source, true);+ const events: string[] = [];+ const visit = (id: string, parent?: string) => {+ const node = doc.nodes.get(id);+ if (!node) return;+ events.push(+ JSON.stringify({+ version: 1,+ seq: events.length + 1,+ op: "create",+ id,+ kind: node.kind,+ ...(parent ? { parent } : {}),+ props: node.props,+ }),+ );+ node.children.forEach((child) => visit(child, id));+ };+ doc.roots.forEach((id) => visit(id));+ return "```cindy-ui\n" + events.join("\n") + "\n```\n";+ })+ .join("");+}++export function richMediaSource(node: RichNode): string | null {+ const src = richString(node, "src").trim();+ if (!src || /[\r\n]/.test(src)) return null;+ if (+ /^[a-zA-Z][\w+.-]*:/.test(src) &&+ !/^[a-zA-Z]:[\\/]/.test(src) &&+ !/^(https?:\/\/|file:\/\/|xdt-(?:file|image|video|audio):\/\/|cindy-(?:remote-)?media:\/\/)/.test(+ src,+ )+ )+ return null;+ return src;+}diff --git a/packages/maker-shared/src/richAnswerGuide.ts b/packages/maker-shared/src/richAnswerGuide.tsnew file mode 100644index 0000000000..d244630458--- /dev/null+++ b/packages/maker-shared/src/richAnswerGuide.ts@@ -0,0 +1,44 @@+/** Single delivery protocol used by host instructions and optional capability lookup. */+export const RICH_ANSWER_GUIDE = `Cindy can render a streaming component document directly in an assistant progress message or final answer. You choose content and layout; ordinary Markdown remains available. No HTML file or extra model call is needed.++To use components, place newline-delimited JSON operations inside a cindy-ui fenced block. Each complete line is rendered immediately; do not wait for a whole document. Put ordinary Markdown before/after the block when useful. A code example must be nested inside a longer outer Markdown fence so it stays an example.++Each block starts seq=1 and increments by one. Its first operation has version:1. Node id: 1–80 letters/digits/underscore/hyphen, stable across edits. Operations:+- create: {seq,version:1,op:"create",id,kind,parent?,index?,props?}. Omit parent for root. Create containers before children.+- append: {seq,op:"append",id,text} appends text to text/markdown/heading/code/math/diagram.+- patch: {seq,op:"patch",id,props} changes only supplied properties. Use this for local revisions; do not repeat whole blocks.+- move: {seq,op:"move",id,parent:"root"|containerId,index?}.+- remove: {seq,op:"remove",id} removes the subtree.++Components and props (no arbitrary HTML, CSS, scripts or tool access):+- text/heading: text; markdown: text supports lists/tables/links.+- stack/group: vertical children. row/grid: columns 1–3; grid layout:"aside" for image + text. Containers combine freely and adapt to the available width.+- divider.+- image/video/audio: src (existing managed reference, URL or task file), alt, caption. Reuse actual media; never invent asset URLs or embed base64 data.+- code: text, language. math: text (LaTeX). diagram: text (Mermaid).+- stat: label, value, prefix?, suffix?.+- chart: label, variant:"bar"|"line", data:[{label,value}].+- range: label, bind?, min,max,step,default,suffix?. input: label,bind?,default,placeholder. check: label,bind?,default boolean. select: label,bind?,default,options:[{label,value}].+- details: label,default boolean,children. tabs: children are containers with label; default is selected child id.+- button/form: label,set:{stateKey:expression}. Button or form submit only changes local UI values. It does not execute tools, navigate, or send messages.++bind defaults to node id. User values persist locally per account/device/message and take precedence over later model defaults. They are not automatically sent to the model or synchronized across viewing devices. Do not ask for credentials in these controls.+value and chart data may use a scalar, {ref:"stateKeyOrComputedNodeId"}, or {op,args:[...]}. Supported op: add,sub,mul,div,min,max,lt,gt,eq,if,concat. References can target input bindings or computed stat/text node ids, including nodes declared later. Never create circular references. Missing or invalid references are unavailable, not zero. No JavaScript evaluation. Use descriptive labels and units.++Example (each object is one line within the cindy-ui block):+{"version":1,"seq":1,"op":"create","id":"months","kind":"range","props":{"label":"Months","min":1,"max":24,"default":6}}+{"seq":2,"op":"create","id":"cost","kind":"stat","props":{"label":"Total","prefix":"¥","value":{"op":"mul","args":[{"ref":"months"},20]}}}+{"seq":3,"op":"patch","id":"cost","props":{"value":{"op":"mul","args":[{"ref":"months"},18]}}}++Keep blocks under 128 KB, with no more than 2048 nodes and depth 32. Finish each line before starting the next. Media loads via the existing host path. Interrupted output keeps committed nodes; incomplete lines wait for completion. Unknown or malformed operations show a local readable fallback, never execute code. New Cindy clients render components; older clients may show the fenced source. Use Markdown when the receiving channel does not support components.`;+++/** Host addition only: native CLI instructions and execution remain unchanged. */+export const ANSWER_DELIVERY_PROMPT = `## Cindy answer delivery+Deliver your answer directly in the conversation, respecting the user's current request and saved presentation preferences already in your context. These delivery capabilities apply equally to ordinary tasks and companions. They do not change how you execute tasks, use tools, or finish a turn.++The conversation supports the native components below, including live controls and calculations. When a user wants to adjust, compare or check things directly in the reply, those controls work here; an HTML code block is only source code, not an interactive answer. Choose and compose the layout yourself. Plain text and Markdown are equally valid for simple answers, code-only requests or when requested. Do not add decoration, duplicate the answer, or create a separate file merely to display it. User-requested files remain deliverables.++Use components only on Cindy conversation surfaces. When delivering to an external channel or a consumer requiring a specific text/JSON format, honor that destination's format instead. Component controls hold local viewing state; never claim they execute work or send input back to you.++${RICH_ANSWER_GUIDE}`;