Files
metona-ai-desktop/src/components/chat/AssistantMessage.tsx
T
thzxx 99d0c54129
CI / 类型检查 + Lint + 单元测试 (push) Failing after 6m27s
CI / 产物编译验证 (push) Successful in 9m57s
CI / 全量测试 (Electron ABI) (push) Failing after 5m19s
feat: v0.7.4 时序语义修正 · 防线实效补漏 · 全量测试翻倍 — 2406 用例 + jsdom 组件测试全量回归
P1 修复面收口:
- 超时三态区分(aborted→USER_INTERRUPT / ETIMEDOUT→TIMEOUT / 其余→ERROR),
  根治"真实网络超时被误报为用户中断"
- 流空闲超时统一(SSE/Ollama/Anthropic 读循环 60s 无数据抛 504 进重试通道)
- 同会话并发 sendMessage 防重入(isRunning 守卫)+ 会话存在性预检 +
  前置调用移入 try(ERROR+DONE 双事件保证,根治 isStreaming 假死)
- 清空审计后 resetChainCache(根治 verifyChain 误报 TAMPERED)
- DONE 不再提前清理 TRACE(TERMINATED 统一收尾,补全最终迭代录制)
- IME 合成回车不发送(普通 Enter + Cmd/Ctrl+Enter 双分支)+ handleSend 闭包修复

P2 安全纵深:
- preload 移除原始 electronAPI 暴露(渲染层零使用,关掉 XSS invoke 任意通道单点风险)
- CORS 同源回显根治(仅当前浏览页面 Origin,did-navigate 同步)
- MEMORY.md 命令保护正则扩展(括号/$/反引号/< 重定向边界 + 前导路径)
- write_file append TOCTOU 统一(open 后 realpath 校验,新文件分支补漏)
- 敏感键归一化(authKey 驼峰/连字符命中)+ MCP headers 鉴权值加密落库
- ReDoS 检测共享化(search_files/file_editor 统一拦截)
- run_tests/lint_code 升风险 + 需确认 + npx --no-install(执行边界对齐 run_command)
- MCP/SearXNG/llm.baseURL/updateFeedUrl 配置类 URL 高危目标校验(IPv6 去括号 +
  十六进制映射解析 + 尾点剥离)

P3 架构还债:
- temperature/maxTokens 热生效(引擎/编排器/SubAgent 三处接线)+ setBatch 单事务落盘
- SessionRecorder flush 竞态根治(flushPromise 等待 + 超限内联落盘 + stopRecording async)
- 内存收口(lastConsolidationBySession LRU / subTraces 清理 / 会话删除 disposeEngine)
- i18n 全量收口(28 组件 + 353 key 双字典,状态标签改渲染时函数)
- 死代码清理(updateTraceStep/HEADER_HEIGHT/void preA/失实注释)
- 斜杠菜单 MUI 化 + 删除逻辑收敛 resetSessionState + Blob URL 统一释放 +
  用户消息"仅保存"落库(saveMessage 透传前端 id 修复 id 错位)

P4 能力演进:
- 死循环检测拆分(驻留前置 + 乒乓后置带进度信号,合法交替不误报)
- run-lock 30s 超时强制 abort(旧 run 卡死不无限排队)
- RETRY 双通道 stream_reset(前端按 run 归属精确清空,根治重试文本重复)
- FTS5 trigram 中文子串搜索(迁移 9 版本化 SCHEMA_VERSION=2,≤2 字符 LIKE 回退)
- getContextWindow 兜底 1M→128K(未知模型防 413)

测试:
- 855 → 2406 用例(+1551,2.8 倍):服务层 +325(含 MemoryManager 51 新用例)、
  工具实体 +483、IPC/适配器 +390(含 OpenAI/Anthropic/Ollama 独立套件)、
  纯函数表格化 +330;引入 jsdom + @testing-library(14 组件测试文件 249 用例)
- 修复 R1(saveMessage id 透传)/ R2(stream_reset 精确归属)两个回归缺陷
- 遗留低危项清零:git-tools 顺序耦合 / web-fetch 真实时间退避 / slo 内存断言 /
  mcp-security 多余 skipIf / deepseek-balance 命名误导 / 组件 mock 注入脆弱性

版本: 0.7.4; README 同步(工具风险表/版本徽章); 依赖: 移除 @electron-toolkit/preload,
新增 jsdom/@testing-library(devDependencies 不打包)

回归: typecheck 双端 0 错误; ESLint 0/0; Electron ABI 全量 2406/2406 零跳过;
系统 Node 2110 通过 296 跳过(better-sqlite3 ABI)
2026-08-30 19:19:07 +08:00

400 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* AssistantMessage — Agent 回复消息卡片
*
* 分为三个阶段,流式时实时展示:
* 1. 💭 思考阶段 — ThoughtBlock 自动展开,流式追加 reasoning content
* 2. 🔧 工具调用 — ToolCallCard 展示调用和结果
* 3. ✏️ 回复阶段 — Markdown 渲染,打字光标指示流式输出
*
* F1 性能优化: 使用 React.memo 包裹,避免历史消息在流式 delta 时重渲染。
* 配合 agentStatus 选择器优化:历史消息(isStreaming=false)不订阅真实 agentStatus
* 避免 agentStatus 频繁变化(thinking/executing/idle)触发所有 AssistantMessage 重渲染。
*/
import { useState, useCallback, memo, useMemo } from 'react';
import { Box, Typography, Avatar, Stack, IconButton, Tooltip } from '@mui/material';
import { Bot, Copy, Check } from 'lucide-react';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeHighlight from 'rehype-highlight';
// F11: 移除 rehypeRaw — 避免解析 raw HTML 的开销 + 安全考虑(防止 AI 输出 HTML 注入)
// 如需恢复内联 HTML 渲染,可重新引入 rehype-raw
import type { ChatMessage } from '@renderer/stores/agent-store';
import { useAgentStore } from '@renderer/stores/agent-store';
import { ThoughtBlock } from './ThoughtBlock';
import { ToolCallCard } from './ToolCallCard';
import { ToolResultBlock } from './ToolResultBlock';
import { formatTime } from '@renderer/lib/formatters';
import { ContextMenu, createContextMenuItems } from '@renderer/components/ContextMenu';
// v0.7.4 P3-1: 文案出层(字典含注册副作用,须在 t() 使用前 import
import { t } from '@renderer/lib/i18n';
import '@renderer/lib/i18n-strings';
interface AssistantMessageProps {
message: ChatMessage;
isStreaming?: boolean;
}
function AssistantMessageImpl({ message, isStreaming }: AssistantMessageProps): React.JSX.Element {
// 直接使用 message.content — updateLastAssistantMessage 已实时更新此字段
const content = message.content;
const [contextMenu, setContextMenu] = useState<{ x: number; y: number } | null>(null);
// F1: 历史消息(isStreaming=false)固定返回 'idle',避免 agentStatus 变化触发重渲染
// 逻辑等价:原 isThinking = agentStatus === 'thinking' && isStreaming
// 新 isThinking = agentStatus === 'thinking'agentStatus 在非流式时恒为 'idle'
const agentStatus = useAgentStore((s) => (isStreaming ? s.agentStatus : 'idle'));
const contextMenuItems = createContextMenuItems('message', { content, role: 'assistant' });
const hasThinking = !!message.reasoningContent;
const hasTools = !!message.toolCalls?.length;
const hasContent = !!content;
const isThinking = agentStatus === 'thinking' && isStreaming;
// F7: useMemo 缓存 ReactMarkdown 元素,避免非流式时因 isStreaming/isLast 变化重新创建元素
// 流式时此元素不被渲染(用纯文本),useMemo 仍会更新但仅创建轻量 React 元素对象
// 非流式时 content 不变,useMemo 复用缓存,避免重新创建 ReactMarkdown 组件实例
const markdownElement = useMemo(
() => (
<Box className="prose-metona">
<ReactMarkdown
remarkPlugins={[remarkGfm]}
rehypePlugins={[rehypeHighlight]}
components={{
code({ className, children, ...props }) {
const match = /language-(\w+)/.exec(className ?? '');
// rehype-highlight 会把代码替换为 <span> 高亮元素,需提取纯文本
const codeStr = extractTextContent(children).replace(/\n$/, '');
if (!match)
return (
<code className={className} {...props}>
{children}
</code>
);
return <CodeBlock language={match[1]} code={codeStr} />;
},
}}
>
{content}
</ReactMarkdown>
</Box>
),
[content],
);
return (
<Stack
direction="row"
spacing={1.5}
sx={{ animation: 'fadeInUp 300ms ease-out' }}
onContextMenu={(e: React.MouseEvent) => {
e.preventDefault();
setContextMenu({ x: e.clientX, y: e.clientY });
}}
>
<Avatar
sx={{
width: 32,
height: 32,
bgcolor: 'secondary.main',
color: 'primary.main',
flexShrink: 0,
}}
>
<Bot size={16} />
</Avatar>
<Box
sx={{
flex: 1,
minWidth: 0,
maxWidth: 768,
borderRadius: 3,
px: 2,
py: 1.5,
bgcolor: 'background.paper',
border: '1px solid',
borderColor: 'divider',
transition: 'border-color 200ms, box-shadow 200ms',
...(isStreaming
? { borderColor: 'rgba(129,140,248,0.3)', boxShadow: '0 0 0 1px rgba(129,140,248,0.1)' }
: {}),
}}
>
{/* ===== 阶段 1: 思考过程 ===== */}
{hasThinking && (
<>
<Stack direction="row" spacing={1} sx={{ mb: 0.5, alignItems: 'center' }}>
<Typography
variant="caption"
sx={{
color: '#fbbf24',
fontWeight: 600,
fontSize: 10,
textTransform: 'uppercase',
letterSpacing: 0.5,
}}
>
💭 {isThinking ? t('assistant.thinking') : t('assistant.thinkingLabel')}
</Typography>
{isThinking && (
<Box
sx={{
width: 6,
height: 6,
borderRadius: '50%',
bgcolor: '#fbbf24',
animation: 'pulse 1.5s infinite',
}}
/>
)}
</Stack>
<ThoughtBlock content={message.reasoningContent!} defaultExpanded={!!isStreaming} />
</>
)}
{/* ===== 阶段 2: 工具调用 ===== */}
{hasTools && (
<>
{hasThinking && <Box sx={{ height: 8 }} />}
<Stack direction="row" spacing={1} sx={{ mb: 0.5, alignItems: 'center' }}>
<Typography
variant="caption"
sx={{
color: '#a855f7',
fontWeight: 600,
fontSize: 10,
textTransform: 'uppercase',
letterSpacing: 0.5,
}}
>
🔧 {t('assistant.toolCalls')}
</Typography>
</Stack>
{message.toolCalls!.map((tc) => (
<Box key={tc.id}>
<ToolCallCard toolCall={tc} />
{tc.status === 'success' && tc.result != null && <ToolResultBlock toolCall={tc} />}
</Box>
))}
</>
)}
{/* ===== 阶段 3: 回复内容 ===== */}
{(hasContent || isStreaming) && (
<>
{(hasThinking || hasTools) && (
<Stack direction="row" spacing={1} sx={{ mt: 0.5, mb: 0.5, alignItems: 'center' }}>
<Typography
variant="caption"
sx={{
color: '#34d399',
fontWeight: 600,
fontSize: 10,
textTransform: 'uppercase',
letterSpacing: 0.5,
}}
>
✏️ {t('assistant.reply')}
</Typography>
{isStreaming && !isThinking && (
<Box
sx={{
width: 6,
height: 6,
borderRadius: '50%',
bgcolor: '#34d399',
animation: 'pulse 1.5s infinite',
}}
/>
)}
</Stack>
)}
{hasContent ? (
isStreaming ? (
// F3: 流式时用纯文本渲染,避免 ReactMarkdown 对长内容重新解析导致卡顿。
// 根因:每个 delta 触发 ReactMarkdown 全量重新解析 + rehypeHighlight 高亮,
// 内容长度增加时单次解析耗时 O(n) 退化,30+ delta/秒下呈 O(n²) 卡死。
// 流结束后自动切换到 ReactMarkdown 一次性渲染(一次性 O(n),可接受)。
<Box
component="pre"
className="prose-metona prose-streaming"
sx={{
margin: 0,
padding: 0,
fontFamily: 'inherit',
fontSize: 14,
lineHeight: 1.6,
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
overflowWrap: 'break-word',
color: 'text.primary',
}}
>
{content}
</Box>
) : (
// F7: 使用 useMemo 缓存的 ReactMarkdown 元素
markdownElement
)
) : isStreaming ? (
<Typography
variant="body2"
sx={{ color: 'text.disabled', fontStyle: 'italic', py: 1 }}
>
{isThinking ? t('assistant.thinking') : t('assistant.generating')}
<Box
component="span"
sx={{
display: 'inline-block',
width: 8,
height: 16,
ml: 0.5,
bgcolor: 'primary.main',
animation: 'blink 1s step-end infinite',
verticalAlign: 'middle',
}}
/>
</Typography>
) : null}
{/* 流式打字光标 */}
{isStreaming && hasContent && (
<Box
component="span"
sx={{
display: 'inline-block',
width: 8,
height: 16,
ml: 0.25,
bgcolor: 'primary.main',
animation: 'blink 1s step-end infinite',
verticalAlign: 'middle',
}}
/>
)}
</>
)}
{/* 时间戳 */}
{!isStreaming && (
<Typography variant="caption" sx={{ mt: 0.5, display: 'block', color: 'text.disabled' }}>
{formatTime(message.timestamp)}
</Typography>
)}
</Box>
{contextMenu && (
<ContextMenu
x={contextMenu.x}
y={contextMenu.y}
items={contextMenuItems}
onClose={() => setContextMenu(null)}
/>
)}
</Stack>
);
}
/**
* F1: memo 包裹 AssistantMessage。
* - 流式 delta 时仅最后一条 message 引用变化,历史消息跳过 re-render
* - agentStatus 订阅已优化(非流式时返回 'idle'),历史消息不受 agentStatus 变化影响
*/
export const AssistantMessage = memo(AssistantMessageImpl);
function CodeBlock({ language, code }: { language: string; code: string }): React.JSX.Element {
const [copied, setCopied] = useState(false);
const handleCopy = useCallback(async () => {
try {
await navigator.clipboard.writeText(code);
} catch {
const ta = document.createElement('textarea');
ta.value = code;
document.body.appendChild(ta);
ta.select();
document.execCommand('copy');
document.body.removeChild(ta);
}
setCopied(true);
setTimeout(() => setCopied(false), 2000);
}, [code]);
return (
<Box sx={{ position: 'relative', my: 1, '&:hover .copy-btn': { opacity: 1 } }}>
<Stack
direction="row"
sx={{
px: 1.5,
py: 0.75,
borderTopLeftRadius: 8,
borderTopRightRadius: 8,
borderBottom: '1px solid',
borderColor: 'divider',
bgcolor: 'background.paper',
fontSize: 11,
color: 'text.secondary',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<span>{language}</span>
<Tooltip title={copied ? t('assistant.copied') : t('assistant.copy')}>
<IconButton
className="copy-btn"
size="small"
onClick={handleCopy}
sx={{ opacity: 0, transition: 'opacity 150ms', color: 'text.secondary' }}
>
{copied ? <Check size={10} /> : <Copy size={10} />}
</IconButton>
</Tooltip>
</Stack>
<Box
component="pre"
sx={{
m: 0,
bgcolor: 'background.default',
border: '1px solid',
borderColor: 'divider',
borderTop: 'none',
borderBottomLeftRadius: 8,
borderBottomRightRadius: 8,
p: 1.5,
overflowX: 'auto',
fontSize: 13,
lineHeight: 1.6,
color: 'text.primary',
}}
>
<code className={language ? `language-${language}` : ''}>{code}</code>
</Box>
</Box>
);
}
/**
* 从 React children(可能含高亮 span)递归提取纯文本
*
* L-1 修复: 添加 maxDepth 参数防止循环引用导致的栈溢出
* React children 正常深度不会超过 10,50 已足够安全裕量
*/
function extractTextContent(children: React.ReactNode, maxDepth = 50): string {
if (maxDepth <= 0) return ''; // 超出深度上限,停止递归
if (typeof children === 'string') return children;
if (typeof children === 'number') return String(children);
if (!children) return '';
if (Array.isArray(children))
return children.map((c) => extractTextContent(c, maxDepth - 1)).join('');
if (typeof children === 'object' && 'props' in children) {
// 使用 React.ReactElement<{ children?: React.ReactNode }> 显式声明 props.children 类型
return extractTextContent(
(children as React.ReactElement<{ children?: React.ReactNode }>).props
.children as React.ReactNode,
maxDepth - 1,
);
}
return '';
}