Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 计划审阅气泡渲染计划 Markdown,不再直出源码 (#1083)
Dash9030f891267e
diff --git a/apps/desktop/src/renderer/__tests__/planReviewBubbleMarkdown.test.tsx b/apps/desktop/src/renderer/__tests__/planReviewBubbleMarkdown.test.tsxnew file mode 100644index 0000000000..f2de16cb22--- /dev/null+++ b/apps/desktop/src/renderer/__tests__/planReviewBubbleMarkdown.test.tsx@@ -0,0 +1,205 @@+// @vitest-environment jsdom+//+// 计划审阅气泡的计划正文必须走 Markdown 渲染,而不是直出源码。+// 回归背景:approved 态原本用 <pre> 打印 planReviewPlan,聊天记录里回看时满屏+// `#` / `**` / 表格竖线,和底部 Plan Viewer Card 的排版观感完全脱节。++import { cleanup, fireEvent, render, screen } from '@testing-library/react';+import { afterEach, describe, expect, it, vi } from 'vitest';++vi.mock('react-i18next', () => ({+ useTranslation: () => ({ t: (key: string) => key }),+}));++// MarkdownRenderer 本体拖着 rehype-highlight / mermaid / lightbox 一串重依赖,+// 这里只关心"计划正文有没有交给它渲染",用桩替掉即可。+vi.mock('@/components/chat/MarkdownRenderer', () => ({+ MarkdownRenderer: ({+ content,+ workingDir,+ currentSessionId,+ currentSessionTitle,+ localFileRefs,+ }: {+ content: string;+ workingDir: string;+ currentSessionId?: string;+ currentSessionTitle?: string | null;+ localFileRefs?: readonly { name: string }[];+ }) => (+ <div+ data-testid="markdown"+ data-working-dir={workingDir}+ data-session-id={currentSessionId ?? ''}+ data-session-title={currentSessionTitle ?? ''}+ data-file-refs={(localFileRefs ?? []).map((r) => r.name).join(',')}+ >+ {content}+ </div>+ ),+}));++import { PlanReviewBubble } from '@/components/chat/PlanReviewBubble';+import type { ChatMessage } from '@/lib/makerChatStore';++const PLAN = '# 计划标题\n\n- 第一步\n- 第二步\n';++function planReviewMessage(overrides: Partial<ChatMessage> = {}): ChatMessage {+ return {+ clientId: 'plan-1',+ role: 'plan_review',+ content: '',+ planReviewPlan: PLAN,+ planReviewStatus: 'approved',+ ...overrides,+ } as ChatMessage;+}++/** 限高容器 = MarkdownRenderer 桩的祖父节点(桩 → 测高 div → 限高容器)。 */+function collapsedBoxOf(markdown: HTMLElement): HTMLElement {+ const box = markdown.parentElement?.parentElement;+ if (!box) throw new Error('collapsed box not found');+ return box;+}++/**+ * 让 offsetHeight 返回一个超过折叠上限的值,逼出折叠分支。jsdom 不做布局,+ * offsetHeight 恒 0,否则永远测不到 overflowing=true 这一半。+ */+function withOverflowingContent(run: () => void) {+ const original = Object.getOwnPropertyDescriptor(HTMLElement.prototype, 'offsetHeight');+ Object.defineProperty(HTMLElement.prototype, 'offsetHeight', {+ configurable: true,+ get: () => 9999,+ });+ try {+ run();+ } finally {+ if (original) Object.defineProperty(HTMLElement.prototype, 'offsetHeight', original);+ else delete (HTMLElement.prototype as unknown as Record<string, unknown>).offsetHeight;+ }+}++afterEach(() => {+ cleanup();+ vi.clearAllMocks();+});++describe('PlanReviewBubble 计划正文渲染', () => {+ it('approved 态把计划交给 MarkdownRenderer,并透传 workingDir', () => {+ const { container } = render(+ <PlanReviewBubble message={planReviewMessage()} workingDir="/tmp/repo" />,+ );++ const markdown = screen.getByTestId('markdown');+ expect(markdown.textContent).toBe(PLAN);+ expect(markdown.getAttribute('data-working-dir')).toBe('/tmp/repo');+ // 源码直出的 <pre> 不再出现。+ expect(container.querySelector('pre')).toBeNull();+ });++ // 回归护栏(PR #1083 review):计划正文是会话消息内容,必须拿到与+ // AssistantMessage 同一套解析上下文。currentSessionId 缺失时+ // MarkdownRenderer 的 remoteMediaOrigin 恒 undefined,device / ssh 会话里+ // 计划内的图片会绕过 cindy-remote-media:// 改写而坏图。+ it('把会话解析上下文透传给 MarkdownRenderer', () => {+ render(+ <PlanReviewBubble+ message={planReviewMessage()}+ workingDir="/tmp/repo"+ currentSessionId="sess-42"+ currentSessionTitle="改计划审阅气泡"+ localFileRefs={[{ name: 'spec.docx', absPath: '/tmp/repo/spec.docx' } as never]}+ />,+ );++ const markdown = screen.getByTestId('markdown');+ expect(markdown.getAttribute('data-session-id')).toBe('sess-42');+ expect(markdown.getAttribute('data-session-title')).toBe('改计划审阅气泡');+ expect(markdown.getAttribute('data-file-refs')).toBe('spec.docx');+ });++ it('expired / cancelled 态同样渲染 Markdown、同样带会话上下文', () => {+ for (const status of ['expired', 'cancelled'] as const) {+ const { unmount } = render(+ <PlanReviewBubble+ message={planReviewMessage({ planReviewStatus: status })}+ workingDir="/tmp/repo"+ currentSessionId="sess-42"+ />,+ );+ expect(screen.getByTestId('markdown').textContent).toBe(PLAN);+ expect(screen.getByTestId('markdown').getAttribute('data-session-id')).toBe('sess-42');+ unmount();+ }+ });++ it('内容没超过折叠高度时不折叠:不设 inert、不出展开按钮', () => {+ // jsdom 里 offsetHeight 恒 0,等价于"内容没超高"这一分支。+ render(<PlanReviewBubble message={planReviewMessage()} workingDir="/tmp/repo" />);++ expect(collapsedBoxOf(screen.getByTestId('markdown')).hasAttribute('inert')).toBe(false);+ expect(screen.queryByRole('button')).toBeNull();+ });++ it('revised 态的用户反馈保持纯文本,不当 Markdown 解析', () => {+ render(+ <PlanReviewBubble+ message={planReviewMessage({+ planReviewStatus: 'revised',+ planReviewFeedback: '# 这是我原话里的井号',+ })}+ workingDir="/tmp/repo"+ />,+ );++ expect(screen.queryByTestId('markdown')).toBeNull();+ expect(screen.getByText('# 这是我原话里的井号')).toBeTruthy();+ });++ // 回归护栏(PR #1083 review 第二轮):overflow-hidden + mask 只挡"看得见",+ // 被裁掉的 Markdown 链接 / 文件 chip / 代码块按钮仍留在 tab 序与 a11y 树里 ——+ // 键盘用户能激活看不见的控件,焦点进入还会滚动容器把折叠预览顶掉。+ describe('折叠态', () => {+ it('三态被裁时都设 inert 且都给得出展开入口', () => {+ for (const status of ['approved', 'expired', 'cancelled'] as const) {+ withOverflowingContent(() => {+ const { unmount } = render(+ <PlanReviewBubble+ message={planReviewMessage({ planReviewStatus: status })}+ workingDir="/tmp/repo"+ />,+ );++ expect(collapsedBoxOf(screen.getByTestId('markdown')).hasAttribute('inert')).toBe(true);+ expect(screen.getByRole('button').getAttribute('aria-expanded')).toBe('false');+ unmount();+ });+ }+ });++ it('展开后解除 inert,正文恢复可聚焦可选中', () => {+ withOverflowingContent(() => {+ render(<PlanReviewBubble message={planReviewMessage()} workingDir="/tmp/repo" />);++ const toggle = screen.getByRole('button');+ fireEvent.click(toggle);++ expect(collapsedBoxOf(screen.getByTestId('markdown')).hasAttribute('inert')).toBe(false);+ expect(screen.getByRole('button').getAttribute('aria-expanded')).toBe('true');+ });+ });+ });++ it('pending 态只有等待提示,不渲染计划正文', () => {+ render(+ <PlanReviewBubble+ message={planReviewMessage({ planReviewStatus: 'pending' })}+ workingDir="/tmp/repo"+ />,+ );++ expect(screen.queryByTestId('markdown')).toBeNull();+ expect(screen.getByText('chat.planReviewBubble.pendingHint')).toBeTruthy();+ });+});diff --git a/apps/desktop/src/renderer/components/chat/MessageStream.tsx b/apps/desktop/src/renderer/components/chat/MessageStream.tsxindex 8138d941f5..17f3178323 100644--- a/apps/desktop/src/renderer/components/chat/MessageStream.tsx+++ b/apps/desktop/src/renderer/components/chat/MessageStream.tsx@@ -3843,7 +3843,18 @@ const MessageItem = memo(function MessageItem({case 'ask_user':return <AskUserQuestionBubble message={message} />;case 'plan_review':- return <PlanReviewBubble message={message} />;+ // 计划正文是会话消息内容,解析上下文与 AssistantMessage 保持一致+ // (currentSessionId 缺失会让远程会话里计划内的媒体链接绕过+ // cindy-remote-media:// 改写而坏图)。+ return (+ <PlanReviewBubble+ message={message}+ workingDir={workingDir}+ currentSessionId={sessionId}+ currentSessionTitle={sessionTitle}+ localFileRefs={localFileRefs}+ />+ );case 'error':// interrupted-turn-resume:app 退出中断标记行不进消息流(2026-07-05 产品// 决策)——它作为「会话尾部是否停在中断态」的判定源保留在 messages 数组里,diff --git a/apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx b/apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsxindex c1a2c93877..c63b92f13f 100644--- a/apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx+++ b/apps/desktop/src/renderer/components/chat/PlanReviewBubble.tsx@@ -5,23 +5,29 @@** pending — simple "Agent is waiting for plan approval" hint (the real UI* is the Plan Viewer Card + Action Card in the bottom region).- * approved — plan summary (first few lines) + "Approved" badge + expand- * toggle to reveal the full Markdown source.+ * approved — rendered plan Markdown (collapsed preview + expand toggle)+ * + "Approved" badge.* revised — user's feedback text, styled as a quoted assistant-side note.* expired — the session was closed before the user decided; read-only.* cancelled— the user dismissed the review (agent stays in plan mode).*+ * 计划正文走 MarkdownRenderer(与底部 Plan Viewer Card 同一个渲染器),不再直出+ * Markdown 源码 —— 历史里回看计划时标题层级、列表、表格、代码块都应该是排版好+ * 的样子,和 agent 当时给出的 Plan Viewer 观感一致。+ ** Styling mirrors AskUserQuestionBubble for visual cohesion: same 12px radius,* 1px Board border, 20px padding, ask-card tokens (the bubble is a neutral* info surface, not a primary action). All colors are grayscale per docs/design-rules/cindy-design-system.md.*/-import { useState } from 'react';+import { useLayoutEffect, useRef, useState } from 'react';import { useTranslation } from 'react-i18next';import { ChevronDown, ChevronRight } from 'lucide-react';import { cn } from '@/lib/utils';import type { ChatMessage } from '@/lib/makerChatStore';+import type { KnownLocalFileRef } from '@/lib/localPathResolver';+import { MarkdownRenderer } from './MarkdownRenderer';// ---------------------------------------------------------------------------// Props@@ -29,24 +35,58 @@ import type { ChatMessage } from '@/lib/makerChatStore';interface PlanReviewBubbleProps {message: ChatMessage;+ /** Session cwd — forwarded to MarkdownRenderer so local-path links inside the+ * plan (e.g. `apps/desktop/src/...`) resolve to the right file. */+ workingDir: string;+ /**+ * 计划正文是**会话消息内容**,所以要拿到和 AssistantMessage 同一套解析上下文,+ * 而不是 TextLightbox 那种"渲染文件内容"的裸调用:+ * - currentSessionId 是 MarkdownRenderer 里远程媒体改写的门控 —— 缺了它+ * remoteMediaOrigin 恒 undefined,device / ssh 会话里计划内的图片/音频会+ * 去加载本机 URL 而不是走 cindy-remote-media:// 管道,直接坏图。+ * - localFileRefs 把计划里 `[spec.docx](spec.docx)` 这类写法解析回用户上传+ * 的原附件路径。+ * - currentSessionTitle 供计划里可能出现的会话交接卡片构建返回链接。+ */+ currentSessionId?: string;+ currentSessionTitle?: string | null;+ localFileRefs?: readonly KnownLocalFileRef[];}// ----------------------------------------------------------------------------// Helpers+// Constants// ----------------------------------------------------------------------------/** First N non-empty lines of the plan for the collapsed summary. */-function summarizePlan(plan: string, maxLines = 3): string {- const lines = plan.split('\n').map((l) => l.trim()).filter(Boolean);- const head = lines.slice(0, maxLines).join('\n');- return lines.length > maxLines ? `${head}\n…` : head;-}+/**+ * 折叠态高度上限(px)。渲染后的 Markdown 没法按"源码行数"截断 —— 截在围栏+ * 代码块或表格中间会让语法失效,所以整段照常解析,只在容器上限高 + 底部渐隐。+ *+ * approved ≈ 一个标题 + 两三行正文,足够认出"这是哪份计划"。+ * expired / cancelled 是失效痕迹,只给更浅的一瞥(展开入口三态都有,见+ * PlanMarkdownBody —— 被裁的内容必须给得出揭示途径)。+ */+const APPROVED_COLLAPSED_MAX_HEIGHT = 120;+const INACTIVE_COLLAPSED_MAX_HEIGHT = 56;++/**+ * 折叠态底部的淡出遮罩(见 PlanMarkdownBody 里的说明)。与 TabBar 的溢出 fade+ * 同一写法:`black` / `transparent` 在这里是 mask 的 alpha 载体,不是主题色值,+ * 所以不走 token(也不受"组件内禁止硬编码颜色"约束)。+ */+const COLLAPSED_FADE_MASK =+ 'linear-gradient(to bottom, black calc(100% - 28px), transparent 100%)';// ---------------------------------------------------------------------------// Component// ----------------------------------------------------------------------------export function PlanReviewBubble({ message }: PlanReviewBubbleProps) {+export function PlanReviewBubble({+ message,+ workingDir,+ currentSessionId,+ currentSessionTitle,+ localFileRefs,+}: PlanReviewBubbleProps) {const { t } = useTranslation();const status = message.planReviewStatus ?? 'pending';// Important #4: planReviewPlan is the single source of truth. No fallback@@ -55,15 +95,7 @@ export function PlanReviewBubble({ message }: PlanReviewBubbleProps) {const plan = message.planReviewPlan ?? '';const feedback = message.planReviewFeedback ?? '';- const [expanded, setExpanded] = useState(false);-const showApprovedBadge = status === 'approved';- const summary = summarizePlan(plan);- // Minor #7: the collapsed summary keeps 3 non-empty lines. Compare against- // the actual line count of the plan, not string length — otherwise a long- // single line would falsely trigger the expand toggle.- const planLineCount = plan.split('\n').filter((l) => l.trim().length > 0).length;- const canExpand = planLineCount > 3;return (<div@@ -119,38 +151,14 @@ export function PlanReviewBubble({ message }: PlanReviewBubbleProps) {)}{status === 'approved' && (- <div className="flex flex-col gap-[8px]">- <pre- className={cn(- 'whitespace-pre-wrap break-words text-13 leading-[1.6]',- 'text-[var(--plan-bubble-summary-text)]',- )}- >- {expanded ? plan : summary}- </pre>- {canExpand && (- <button- type="button"- onClick={() => setExpanded((v) => !v)}- className={cn(- 'inline-flex w-fit items-center gap-[4px] text-12',- 'text-[var(--ask-option-desc)] hover:text-[var(--ask-header-text)]',- 'transition-colors',- )}- >- {expanded ? (- <ChevronDown size={12} />- ) : (- <ChevronRight size={12} />- )}- <span>- {expanded- ? t('chat.planReviewBubble.collapse')- : t('chat.planReviewBubble.showFull')}- </span>- </button>- )}- </div>+ <PlanMarkdownBody+ workingDir={workingDir}+ currentSessionId={currentSessionId}+ currentSessionTitle={currentSessionTitle}+ localFileRefs={localFileRefs}+ plan={plan}+ collapsedMaxHeight={APPROVED_COLLAPSED_MAX_HEIGHT}+ />)}{status === 'revised' && (@@ -158,6 +166,7 @@ export function PlanReviewBubble({ message }: PlanReviewBubbleProps) {<span className="text-13 text-[var(--ask-answered-text)]">{t('chat.planReviewBubble.feedbackLabel')}</span>+ {/* 反馈是用户自己敲的原话,保持纯文本(不当 Markdown 解析)。 */}<pclassName={cn('whitespace-pre-wrap break-words text-14 leading-[1.6]',@@ -170,14 +179,136 @@ export function PlanReviewBubble({ message }: PlanReviewBubbleProps) {)}{(status === 'expired' || status === 'cancelled') && plan && (- <p+ <PlanMarkdownBody+ workingDir={workingDir}+ currentSessionId={currentSessionId}+ currentSessionTitle={currentSessionTitle}+ localFileRefs={localFileRefs}+ plan={plan}+ collapsedMaxHeight={INACTIVE_COLLAPSED_MAX_HEIGHT}+ />+ )}+ </div>+ );+}++// ---------------------------------------------------------------------------+// Sub-components+// ---------------------------------------------------------------------------++/**+ * 渲染后的计划正文 + 折叠。+ *+ * 折叠不按源码行数,而是按渲染结果的实际高度:标题、列表、表格、代码块各自的+ * 行高与外边距差得很远,行数和视觉高度没有稳定关系,而"能否展开"必须和用户+ * 真正看到的有没有被切掉一致 —— 否则会出现按钮点了没变化(或该给按钮时没给)。+ *+ * 折叠态整块 inert(见下方注释):裁掉的部分只是视觉上不见了,DOM 里仍在 tab 序+ * 与 a11y 树里。所以任何会被裁的状态都必须给得出展开入口 —— 三态共用同一个+ * 折叠+展开机制,只有折叠高度不同。+ */+function PlanMarkdownBody({+ workingDir,+ currentSessionId,+ currentSessionTitle,+ localFileRefs,+ plan,+ collapsedMaxHeight,+}: {+ workingDir: string;+ currentSessionId?: string;+ currentSessionTitle?: string | null;+ localFileRefs?: readonly KnownLocalFileRef[];+ plan: string;+ collapsedMaxHeight: number;+}) {+ const { t } = useTranslation();+ const [expanded, setExpanded] = useState(false);+ const [overflowing, setOverflowing] = useState(false);+ // 测高元素刻意放在限高容器**内层**:外层被 max-height 夹住后尺寸恒定,+ // ResizeObserver 观察它拿不到内容变化(图片/字体/窗口宽度导致的回流)。+ const bodyRef = useRef<HTMLDivElement>(null);++ // useLayoutEffect:首帧就在 paint 前定下折叠与否,否则长计划会先整段铺开+ // 再收起,滚动位置和卡片高度跳一下。+ useLayoutEffect(() => {+ const el = bodyRef.current;+ if (!el) return;+ const measure = () => {+ setOverflowing(el.offsetHeight > collapsedMaxHeight + 1);+ };+ measure();+ if (typeof ResizeObserver === 'undefined') return;+ const observer = new ResizeObserver(measure);+ observer.observe(el);+ return () => observer.disconnect();+ }, [collapsedMaxHeight, plan]);++ const collapsed = !expanded && overflowing;++ return (+ <div className="flex flex-col gap-[8px]">+ <div+ className={cn('min-w-0', collapsed && 'overflow-hidden')}+ // 折叠态整块 inert。overflow-hidden 与 mask 只挡住"看得见",被裁掉的+ // Markdown 链接、文件 chip、代码块按钮仍留在 tab 序与 a11y 树里:键盘+ // 用户能聚焦并激活一个看不见的控件,而且焦点一进去浏览器就会滚动这个+ // overflow-hidden 容器,把折叠预览顶掉、露出本该藏起来的下半部分。+ // inert 一次解决聚焦、点击和 a11y 三条路径,唯一入口收敛到下方的展开+ // 按钮(它在本容器之外,不受影响)。+ // 代价:inert 子树内的文字不能选中,所以折叠预览无法复制 —— 这也是三态+ // 都必须给展开按钮的原因,展开后完整可选可交互。+ inert={collapsed}+ style={+ collapsed+ ? ({+ maxHeight: collapsedMaxHeight,+ // 截断处淡出,提示"下面还有"。用 mask-image(按 alpha 吃掉内容)而+ // 不是叠一层卡片色渐变:透出的是卡片自己的底色,Light / Dark /+ // 任意扩展主题天然正确,也没有 from-transparent 那种插值灰边。+ WebkitMaskImage: COLLAPSED_FADE_MASK,+ maskImage: COLLAPSED_FADE_MASK,+ } as React.CSSProperties)+ : undefined+ }+ >+ <div+ ref={bodyRef}className={cn(- 'line-clamp-2 text-13 leading-[1.6]',- 'text-[var(--plan-bubble-summary-text)]',+ 'min-w-0 text-14 leading-[1.6]',+ 'text-[var(--plan-bubble-body-text)]',+ // 首尾块元素的外边距归零,避免卡片内出现比 20px padding 更大的留白。+ '[&_.msg-markdown>*:first-child]:mt-0',+ '[&_.msg-markdown>*:last-child]:mb-0',)}>- {summary}- </p>+ <MarkdownRenderer+ workingDir={workingDir}+ content={plan}+ currentSessionId={currentSessionId}+ currentSessionTitle={currentSessionTitle}+ localFileRefs={localFileRefs}+ />+ </div>+ </div>+ {overflowing && (+ <button+ type="button"+ aria-expanded={expanded}+ onClick={() => setExpanded((v) => !v)}+ className={cn(+ 'inline-flex w-fit items-center gap-[4px] text-12',+ 'text-[var(--ask-option-desc)] hover:text-[var(--ask-header-text)]',+ 'transition-colors',+ )}+ >+ {expanded ? <ChevronDown size={12} /> : <ChevronRight size={12} />}+ <span>+ {expanded+ ? t('chat.planReviewBubble.collapse')+ : t('chat.planReviewBubble.showFull')}+ </span>+ </button>)}</div>);