feat(aia): Complete AIA V2.0 with universal streaming capabilities

Major Updates:
- Add StreamingService with OpenAI Compatible format (backend/common/streaming)
- Upgrade Chat component V2 with Ant Design X integration
- Implement AIA module with 12 intelligent agents
- Create AgentHub with 100% prototype V11 restoration
- Create ChatWorkspace with streaming response support
- Add ThinkingBlock for deep thinking display
- Add useAIStream Hook for OpenAI Compatible stream handling

Backend Common Capabilities (~400 lines):
- OpenAIStreamAdapter: SSE adapter with OpenAI format
- StreamingService: unified streaming service
- Support content and reasoning_content dual streams
- Deep thinking tag processing (<think>...</think>)

Frontend Common Capabilities (~2000 lines):
- AIStreamChat: modern streaming chat component
- ThinkingBlock: collapsible deep thinking display
- ConversationList: conversation management with grouping
- useAIStream: OpenAI Compatible stream handler Hook
- useConversations: conversation state management Hook
- Modern design styles (Ultramodern theme)

AIA Module Frontend (~1500 lines):
- AgentHub: 12 agent cards with timeline design
- ChatWorkspace: fullscreen immersive chat interface
- AgentCard: theme-colored cards (blue/yellow/teal/purple)
- 5 phases, 12 agents configuration
- Responsive layout (desktop + mobile)

AIA Module Backend (~900 lines):
- agentService: 12 agents config with system prompts
- conversationService: refactored with StreamingService
- attachmentService: file upload skeleton (30k token limit)
- 12 API endpoints with authentication
- Full CRUD for conversations and messages

Documentation:
- AIA module status and development guide
- Universal capabilities catalog (11 services)
- Quick reference card for developers
- System overview updates

Testing:
- Stream response verified (HTTP 200)
- Authentication working correctly
- Auto conversation creation working
- Deep thinking display working
- Message input and send working

Status: Core features completed (85%), attachment and history loading pending
This commit is contained in:
2026-01-14 19:09:28 +08:00
parent 4ed67a8846
commit 3d35e9c58b
38 changed files with 8448 additions and 335 deletions

View File

@@ -0,0 +1,469 @@
/**
* AIStreamChat - 流式对话组件
*
* 基于 Ant Design X 构建的现代感 AI 对话组件
* 支持:
* - OpenAI Compatible 流式响应
* - 深度思考展示
* - 打字机效果
* - 快捷提示
* - 附件上传
*/
import React, { useState, useCallback, useRef, useEffect, useMemo } from 'react';
import { Bubble, Sender, Welcome, Prompts } from '@ant-design/x';
import { Button, Space, Upload, message as antMessage } from 'antd';
import {
ThunderboltOutlined,
PaperClipOutlined,
SendOutlined,
StopOutlined,
} from '@ant-design/icons';
import type { BubbleProps } from '@ant-design/x/es/bubble/interface';
import { useAIStream } from './hooks/useAIStream';
import { ThinkingBlock } from './ThinkingBlock';
import type { ChatMessage } from './types';
import './styles/ai-stream-chat.css';
/**
* 快捷提示项
*/
export interface PromptItem {
key: string;
icon?: React.ReactNode;
label: string;
description?: string;
}
/**
* 欢迎配置
*/
export interface WelcomeConfig {
title: string;
description?: string;
icon?: React.ReactNode;
prompts?: PromptItem[];
}
/**
* AIStreamChat Props
*/
export interface AIStreamChatProps {
/** API 端点 */
apiEndpoint: string;
/** 请求头(如 Authorization */
headers?: Record<string, string>;
/** 会话 ID */
conversationId?: string;
/** 智能体 ID */
agentId?: string;
/** 是否启用深度思考 */
enableDeepThinking?: boolean;
/** 欢迎配置 */
welcome?: WelcomeConfig;
/** 快捷提示 */
prompts?: PromptItem[];
/** 初始消息 */
initialMessages?: ChatMessage[];
/** 消息发送回调 */
onMessageSent?: (message: ChatMessage) => void;
/** 消息接收回调 */
onMessageReceived?: (message: ChatMessage) => void;
/** 错误回调 */
onError?: (error: Error) => void;
/** 支持附件上传 */
enableAttachment?: boolean;
/** 自定义类名 */
className?: string;
/** 占位文本 */
placeholder?: string;
}
/**
* 内部消息格式
*/
interface InternalMessage {
id: string | number;
role: 'user' | 'assistant';
content: string;
thinking?: string;
status: 'local' | 'loading' | 'streaming' | 'thinking' | 'success' | 'error';
timestamp: number;
}
/**
* 流式对话组件
*/
export const AIStreamChat: React.FC<AIStreamChatProps> = ({
apiEndpoint,
headers = {},
conversationId,
agentId,
enableDeepThinking = false,
welcome,
prompts = [],
initialMessages = [],
onMessageSent,
onMessageReceived,
onError,
enableAttachment = false,
className = '',
placeholder = '输入消息...',
}) => {
// 消息列表
const [messages, setMessages] = useState<InternalMessage[]>(() =>
initialMessages.map(m => ({
...m,
status: 'success' as const,
timestamp: m.timestamp || Date.now(),
}))
);
// 输入框值
const [inputValue, setInputValue] = useState('');
// 深度思考开关
const [deepThinkingEnabled, setDeepThinkingEnabled] = useState(enableDeepThinking);
// 附件列表
const [attachments, setAttachments] = useState<any[]>([]);
// 滚动容器 ref
const messagesEndRef = useRef<HTMLDivElement>(null);
// 流式响应 Hook
const {
content: streamContent,
thinking: streamThinking,
status: streamStatus,
isStreaming,
isThinking,
error: streamError,
sendMessage,
abort,
reset: resetStream,
} = useAIStream({
apiEndpoint,
headers,
});
// 当前正在流式输出的消息 ID
const streamingMessageIdRef = useRef<string | null>(null);
// 滚动到底部
const scrollToBottom = useCallback(() => {
setTimeout(() => {
messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
}, 100);
}, []);
// 消息变化时滚动
useEffect(() => {
scrollToBottom();
}, [messages, streamContent, scrollToBottom]);
// 更新流式消息内容
useEffect(() => {
if (!streamingMessageIdRef.current) return;
setMessages(prev =>
prev.map(msg =>
msg.id === streamingMessageIdRef.current
? {
...msg,
content: streamContent,
thinking: streamThinking,
status: streamStatus === 'complete' ? 'success' : streamStatus,
}
: msg
)
);
// 流式完成后
if (streamStatus === 'complete' && streamingMessageIdRef.current) {
const finalMessage: ChatMessage = {
id: streamingMessageIdRef.current,
role: 'assistant',
content: streamContent,
status: 'success',
timestamp: Date.now(),
metadata: { thinking: streamThinking },
};
onMessageReceived?.(finalMessage);
streamingMessageIdRef.current = null;
}
}, [streamContent, streamThinking, streamStatus, onMessageReceived]);
// 错误处理
useEffect(() => {
if (streamError && streamingMessageIdRef.current) {
setMessages(prev =>
prev.map(msg =>
msg.id === streamingMessageIdRef.current
? { ...msg, content: `错误: ${streamError}`, status: 'error' }
: msg
)
);
onError?.(new Error(streamError));
streamingMessageIdRef.current = null;
}
}, [streamError, onError]);
/**
* 发送消息
*/
const handleSend = useCallback(async (text?: string) => {
const content = text || inputValue;
if (!content.trim() || isStreaming) return;
// 清空输入
setInputValue('');
// 添加用户消息
const userMessage: InternalMessage = {
id: `user-${Date.now()}`,
role: 'user',
content,
status: 'success',
timestamp: Date.now(),
};
setMessages(prev => [...prev, userMessage]);
onMessageSent?.({
id: userMessage.id,
role: 'user',
content,
status: 'success',
timestamp: userMessage.timestamp,
});
// 添加 AI 消息占位
const aiMessageId = `ai-${Date.now()}`;
streamingMessageIdRef.current = aiMessageId;
const aiMessage: InternalMessage = {
id: aiMessageId,
role: 'assistant',
content: '',
thinking: '',
status: 'loading',
timestamp: Date.now(),
};
setMessages(prev => [...prev, aiMessage]);
// 重置流式状态
resetStream();
// 发送请求
await sendMessage(content, {
conversationId,
agentId,
enableDeepThinking: deepThinkingEnabled,
attachmentIds: attachments.map(a => a.id),
});
// 清空附件
setAttachments([]);
}, [
inputValue,
isStreaming,
conversationId,
agentId,
deepThinkingEnabled,
attachments,
onMessageSent,
sendMessage,
resetStream,
]);
/**
* 处理快捷提示点击
*/
const handlePromptClick = useCallback((item: PromptItem) => {
handleSend(item.label);
}, [handleSend]);
/**
* 停止生成
*/
const handleStop = useCallback(() => {
abort();
if (streamingMessageIdRef.current) {
setMessages(prev =>
prev.map(msg =>
msg.id === streamingMessageIdRef.current
? { ...msg, status: 'success' }
: msg
)
);
streamingMessageIdRef.current = null;
}
}, [abort]);
/**
* 渲染消息内容
*/
const renderMessageContent = useCallback((msg: InternalMessage) => {
// 显示思考过程
const showThinking = msg.role === 'assistant' && (msg.thinking || isThinking);
return (
<div className="message-wrapper">
{/* 深度思考块 */}
{showThinking && (
<ThinkingBlock
content={msg.id === streamingMessageIdRef.current ? streamThinking : (msg.thinking || '')}
isThinking={msg.id === streamingMessageIdRef.current && isThinking}
defaultExpanded={true}
/>
)}
{/* 消息内容 */}
<div className="message-text">
{msg.content}
{msg.status === 'streaming' && (
<span className="typing-cursor"></span>
)}
</div>
</div>
);
}, [streamThinking, isThinking]);
// 转换为 Bubble.List 格式
const bubbleItems: BubbleProps[] = useMemo(() => {
return messages.map((msg) => ({
key: msg.id,
placement: msg.role === 'user' ? 'end' : 'start',
content: renderMessageContent(msg),
loading: msg.status === 'loading',
typing: msg.status === 'streaming' ? { step: 2, interval: 50 } : undefined,
}));
}, [messages, renderMessageContent]);
// 是否显示欢迎页
const showWelcome = messages.length === 0 && welcome;
// 发送按钮
const sendButton = isStreaming ? (
<Button
type="text"
danger
icon={<StopOutlined />}
onClick={handleStop}
/>
) : (
<Button
type="primary"
icon={<SendOutlined />}
disabled={!inputValue.trim()}
onClick={() => handleSend()}
/>
);
// 深度思考按钮
const deepThinkingButton = (
<Button
type={deepThinkingEnabled ? 'primary' : 'default'}
ghost={deepThinkingEnabled}
icon={<ThunderboltOutlined />}
onClick={() => setDeepThinkingEnabled(!deepThinkingEnabled)}
className={`deep-thinking-btn ${deepThinkingEnabled ? 'active' : ''}`}
>
</Button>
);
// 附件按钮
const attachmentButton = enableAttachment && (
<Upload
beforeUpload={(file) => {
if (attachments.length >= 5) {
antMessage.warning('最多上传 5 个附件');
return false;
}
setAttachments(prev => [...prev, { id: Date.now(), file }]);
return false;
}}
showUploadList={false}
>
<Button type="text" icon={<PaperClipOutlined />} />
</Upload>
);
return (
<div className={`ai-stream-chat ${className}`}>
{/* 消息区域 */}
<div className="chat-messages-area">
{showWelcome ? (
<div className="welcome-container">
<Welcome
icon={welcome.icon}
title={welcome.title}
description={welcome.description}
className="welcome-card"
/>
{/* 快捷提示 */}
{(welcome.prompts || prompts).length > 0 && (
<Prompts
items={(welcome.prompts || prompts).map(p => ({
key: p.key,
icon: p.icon,
label: p.label,
description: p.description,
}))}
onItemClick={(_, item) => handlePromptClick(item as unknown as PromptItem)}
className="welcome-prompts"
/>
)}
</div>
) : (
<Bubble.List
items={bubbleItems}
className="messages-list"
/>
)}
<div ref={messagesEndRef} />
</div>
{/* 输入区域 */}
<div className="chat-input-area">
<div className="input-toolbar">
{deepThinkingButton}
{attachmentButton}
</div>
<Sender
value={inputValue}
onChange={setInputValue}
onSubmit={handleSend}
placeholder={placeholder}
loading={isStreaming}
className="chat-sender"
actions={sendButton}
/>
{/* 附件预览 */}
{attachments.length > 0 && (
<div className="attachments-preview">
{attachments.map((att, index) => (
<div key={att.id} className="attachment-item">
<PaperClipOutlined />
<span>{att.file.name}</span>
<Button
type="text"
size="small"
onClick={() => setAttachments(prev => prev.filter((_, i) => i !== index))}
>
×
</Button>
</div>
))}
</div>
)}
</div>
</div>
);
};
export default AIStreamChat;

View File

@@ -0,0 +1,169 @@
/**
* ConversationList - 会话列表组件
*
* 现代感设计的会话列表,支持:
* - 分组显示(今天、昨天、更早)
* - 新建会话
* - 会话切换
* - 会话删除
* - 智能体图标
*/
import React, { useMemo } from 'react';
import { Button, Typography, Dropdown, Empty } from 'antd';
import {
PlusOutlined,
MessageOutlined,
DeleteOutlined,
MoreOutlined,
RobotOutlined,
} from '@ant-design/icons';
import type { Conversation, ConversationGroup } from './hooks/useConversations';
import './styles/conversation-list.css';
const { Text } = Typography;
/**
* ConversationList Props
*/
export interface ConversationListProps {
/** 分组会话列表 */
groups: ConversationGroup[];
/** 当前会话 ID */
currentId: string | null;
/** 会话点击回调 */
onSelect: (id: string) => void;
/** 新建会话回调 */
onNew: () => void;
/** 删除会话回调 */
onDelete?: (id: string) => void;
/** 标题 */
title?: string;
/** Logo */
logo?: React.ReactNode;
/** 自定义类名 */
className?: string;
/** 是否加载中 */
loading?: boolean;
}
/**
* 会话列表组件
*/
export const ConversationList: React.FC<ConversationListProps> = ({
groups,
currentId,
onSelect,
onNew,
onDelete,
title = 'AI 助手',
logo,
className = '',
loading = false,
}) => {
// 会话项菜单
const getMenuItems = (conv: Conversation) => [
{
key: 'delete',
icon: <DeleteOutlined />,
label: '删除对话',
danger: true,
onClick: () => onDelete?.(conv.id),
},
];
// 是否为空
const isEmpty = useMemo(() => {
return groups.every(g => g.conversations.length === 0);
}, [groups]);
return (
<div className={`conversation-list ${className}`}>
{/* 头部 */}
<div className="conversation-list-header">
<div className="conversation-list-logo">
{logo || <RobotOutlined className="default-logo" />}
<span className="conversation-list-title">{title}</span>
</div>
</div>
{/* 新建会话按钮 */}
<div className="conversation-list-new">
<Button
type="default"
icon={<PlusOutlined />}
onClick={onNew}
block
className="new-conversation-btn"
>
</Button>
</div>
{/* 会话列表 */}
<div className="conversation-list-content">
{isEmpty ? (
<Empty
image={Empty.PRESENTED_IMAGE_SIMPLE}
description="暂无对话"
className="conversation-empty"
/>
) : (
groups.map(group => (
<div key={group.key} className="conversation-group">
<div className="conversation-group-label">
<Text type="secondary">{group.label}</Text>
</div>
{group.conversations.map(conv => (
<div
key={conv.id}
className={`conversation-item ${currentId === conv.id ? 'active' : ''}`}
onClick={() => onSelect(conv.id)}
>
<div className="conversation-item-icon">
{conv.agentIcon ? (
<span className="agent-icon">{conv.agentIcon}</span>
) : (
<MessageOutlined />
)}
</div>
<div className="conversation-item-content">
<div className="conversation-item-title">
{conv.title || '新对话'}
</div>
{conv.lastMessage && (
<div className="conversation-item-preview">
{conv.lastMessage}
</div>
)}
</div>
{onDelete && (
<Dropdown
menu={{ items: getMenuItems(conv) }}
trigger={['click']}
placement="bottomRight"
>
<Button
type="text"
size="small"
icon={<MoreOutlined />}
className="conversation-item-more"
onClick={(e) => e.stopPropagation()}
/>
</Dropdown>
)}
</div>
))}
</div>
))
)}
</div>
</div>
);
};
export default ConversationList;

View File

@@ -1,196 +1,200 @@
# Chat 通用组件库
# Chat 通用组件库 V2
> 基于 **Ant Design X** 构建的 AI 对话通用组件,支持多场景复用
> 基于 **Ant Design X 2.x** 构建的现代感 AI 对话组件
> 支持流式响应、深度思考、会话管理等完整能力
---
## 🆕 V2 新特性
-**流式响应** - 逐字显示,打字机效果
-**深度思考** - ThinkingBlock 组件,可折叠展示
-**OpenAI Compatible** - 兼容标准 API 格式
-**会话管理** - ConversationList 组件,分组显示
-**现代感设计** - 参考 Ant Design X Ultramodern
---
## 📚 技术栈
- **@ant-design/x** (2.1.0) - UI 组件Bubble, Sender
- **@ant-design/x-sdk** (2.1.0) - 数据流管理(可选)
- **@ant-design/x** (2.1.0+) - UI 组件Bubble, Sender, Welcome, Prompts, Think
- **React 19** + **TypeScript 5**
- **Prism.js** - 代码语法高亮
---
## ✨ 特性
-**多场景支持**AIA、PKB个人知识库、Tool C 等
-**开箱即用**:基于 Ant Design X无需复杂配置
-**类型安全**:完整的 TypeScript 类型定义
-**高度可定制**:支持自定义消息渲染、样式配置
-**代码执行**Tool C 专用,支持代码块展示和执行
---
## 📦 安装
组件已内置在项目中,无需额外安装。如需单独使用,确保安装以下依赖:
```bash
npm install @ant-design/x @ant-design/x-sdk prismjs
```
- **OpenAI Compatible API** - 标准流式格式
---
## 🚀 快速开始
### 基础用法
### 流式对话(推荐)
```typescript
import { ChatContainer } from '@/shared/components/Chat';
```tsx
import { AIStreamChat } from '@/shared/components/Chat';
<ChatContainer
conversationType="aia"
providerConfig={{
apiEndpoint: '/api/chat',
<AIStreamChat
apiEndpoint="/api/v1/aia/conversations/xxx/messages/stream"
headers={{ Authorization: `Bearer ${token}` }}
conversationId="xxx"
agentId="general"
enableDeepThinking={true}
welcome={{
title: 'AI 智能助手',
description: '有什么可以帮您的?',
prompts: [
{ key: '1', label: '帮我分析数据', icon: '📊' },
{ key: '2', label: '写一份报告', icon: '📝' },
],
}}
/>
```
### Tool C 集成(完整示例)
### 带会话列表的完整布局
```typescript
import { ChatContainer, MessageRenderer } from '@/shared/components/Chat';
```tsx
import { AIStreamChat, ConversationList, useConversations } from '@/shared/components/Chat';
<ChatContainer
conversationType="tool-c"
conversationKey={sessionId}
providerConfig={{
apiEndpoint: `/api/dc/tool-c/process`,
requestFn: async (message: string) => {
const response = await fetch(`/api/dc/tool-c/process`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ sessionId, userMessage: message }),
});
return await response.json();
},
}}
customMessageRenderer={(msgInfo) => (
<MessageRenderer
messageInfo={msgInfo}
onExecuteCode={handleExecuteCode}
isExecuting={isExecuting}
/>
)}
onMessageReceived={(msg) => {
if (msg.metadata?.newDataPreview) {
updateDataGrid(msg.metadata.newDataPreview);
}
}}
/>
function ChatPage() {
const {
groupedConversations,
currentId,
setCurrent,
addConversation,
deleteConversation,
} = useConversations();
return (
<div style={{ display: 'flex', height: '100vh' }}>
{/* 左侧会话列表 */}
<ConversationList
groups={groupedConversations}
currentId={currentId}
onSelect={setCurrent}
onNew={() => addConversation({ title: '新对话' })}
onDelete={deleteConversation}
title="AI 助手"
/>
{/* 右侧对话区域 */}
<div style={{ flex: 1 }}>
<AIStreamChat
apiEndpoint={`/api/v1/aia/conversations/${currentId}/messages/stream`}
conversationId={currentId}
enableDeepThinking={true}
/>
</div>
</div>
);
}
```
---
## 📖 API 文档
### ChatContainer Props
### AIStreamChat Props
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| `conversationType` | `ConversationType` | ✅ | - | 对话类型('aia' \| 'pkb' \| 'tool-c' |
| `conversationKey` | `string` | ❌ | - | 会话 ID用于多会话管理 |
| `providerConfig` | `ChatProviderConfig` | | - | API 配置 |
| `defaultMessages` | `ChatMessage[]` | ❌ | `[]` | 初始消息列表 |
| `customMessageRenderer` | `Function` | ❌ | - | 自定义消息渲染器 |
| `senderProps` | `SenderProps` | ❌ | `{}` | Sender 组件配置 |
| `apiEndpoint` | `string` | ✅ | - | API 端点(需支持 OpenAI Compatible 格式 |
| `headers` | `Record<string, string>` | ❌ | `{}` | 请求头(如 Authorization |
| `conversationId` | `string` | | - | 会话 ID |
| `agentId` | `string` | ❌ | - | 智能体 ID |
| `enableDeepThinking` | `boolean` | ❌ | `false` | 是否启用深度思考 |
| `welcome` | `WelcomeConfig` | ❌ | - | 欢迎页配置 |
| `prompts` | `PromptItem[]` | ❌ | `[]` | 快捷提示列表 |
| `enableAttachment` | `boolean` | ❌ | `false` | 是否支持附件上传 |
| `placeholder` | `string` | ❌ | `'输入消息...'` | 输入框占位文本 |
| `onMessageSent` | `Function` | ❌ | - | 消息发送回调 |
| `onMessageReceived` | `Function` | ❌ | - | 消息接收回调 |
| `onError` | `Function` | ❌ | - | 错误回调 |
### ChatProviderConfig
### ThinkingBlock Props
```typescript
interface ChatProviderConfig {
apiEndpoint: string; // API 端点
method?: 'GET' | 'POST'; // 请求方法
headers?: Record<string, string>; // 请求头
requestFn?: (message: string, context?: any) => Promise<any>; // 自定义请求函数
}
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| `content` | `string` | ✅ | - | 思考内容 |
| `isThinking` | `boolean` | ❌ | `false` | 是否正在思考 |
| `duration` | `number` | ❌ | - | 思考耗时(秒) |
| `defaultExpanded` | `boolean` | ❌ | `false` | 默认是否展开 |
### ConversationList Props
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|------|------|------|--------|------|
| `groups` | `ConversationGroup[]` | ✅ | - | 分组会话列表 |
| `currentId` | `string \| null` | ✅ | - | 当前会话 ID |
| `onSelect` | `Function` | ✅ | - | 会话点击回调 |
| `onNew` | `Function` | ✅ | - | 新建会话回调 |
| `onDelete` | `Function` | ❌ | - | 删除会话回调 |
| `title` | `string` | ❌ | `'AI 助手'` | 标题 |
| `logo` | `ReactNode` | ❌ | - | Logo |
---
## 🎣 Hooks
### useAIStream
处理 OpenAI Compatible 格式的流式响应。
```tsx
import { useAIStream } from '@/shared/components/Chat';
const {
content, // 当前内容
thinking, // 思考内容
status, // 流式状态
isStreaming, // 是否正在流式输出
isThinking, // 是否正在思考
error, // 错误信息
sendMessage, // 发送消息
abort, // 中断请求
reset, // 重置状态
} = useAIStream({
apiEndpoint: '/api/v1/aia/chat/stream',
headers: { Authorization: `Bearer ${token}` },
});
```
### ChatMessage
### useConversations
```typescript
interface ChatMessage {
id: string | number;
role: 'user' | 'assistant' | 'system';
content: string;
status?: 'local' | 'loading' | 'success' | 'error';
code?: string; // Tool C 专用
explanation?: string; // Tool C 专用
timestamp?: number;
metadata?: Record<string, any>;
}
管理多会话状态。
```tsx
import { useConversations } from '@/shared/components/Chat';
const {
conversations, // 会话列表
groupedConversations, // 分组会话
current, // 当前会话
currentId, // 当前会话 ID
setCurrent, // 设置当前会话
addConversation, // 添加会话
updateConversation, // 更新会话
deleteConversation, // 删除会话
} = useConversations();
```
---
## 🎨 自定义渲染
## 🔌 后端 API 格式
### MessageRenderer默认渲染器
### OpenAI Compatible SSE 格式
```typescript
import { MessageRenderer } from '@/shared/components/Chat';
后端需要输出以下格式的 SSE 流:
<MessageRenderer
messageInfo={msgInfo}
onExecuteCode={(code) => console.log('Execute:', code)}
isExecuting={false}
/>
```
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"delta":{"role":"assistant"}}]}\n\n
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"delta":{"reasoning_content":"让我思考一下..."}}]}\n\n
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"delta":{"content":"好的,"}}]}\n\n
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"delta":{"content":"我来帮您..."}}]}\n\n
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"delta":{},"finish_reason":"stop"}]}\n\n
data: [DONE]\n\n
```
### CodeBlockRenderer代码块渲染器
```typescript
import { CodeBlockRenderer } from '@/shared/components/Chat';
<CodeBlockRenderer
code="df['age'].fillna(df['age'].mean(), inplace=True)"
language="python"
onExecute={handleExecute}
isExecuting={false}
executionResult={{ success: true }}
/>
```
---
## 🔧 高级用法
### 自定义消息渲染
```typescript
<ChatContainer
conversationType="custom"
providerConfig={{ apiEndpoint: '/api/custom' }}
customMessageRenderer={(msgInfo) => {
const msg = msgInfo.message;
return (
<div>
<strong>{msg.role}:</strong> {msg.content}
{msg.code && <pre>{msg.code}</pre>}
</div>
);
}}
/>
```
### 处理后端响应
后端 API 应返回以下格式:
```json
{
"messageId": "xxx",
"explanation": "好的,我将帮您...",
"code": "df['sex'].fillna(df['sex'].mode()[0], inplace=True)",
"success": true,
"metadata": {
"newDataPreview": [...]
}
}
```
关键字段:
- `choices[0].delta.content` - 正文内容
- `choices[0].delta.reasoning_content` - 深度思考内容DeepSeek 风格)
- `choices[0].finish_reason` - 完成原因
---
@@ -198,99 +202,49 @@ import { CodeBlockRenderer } from '@/shared/components/Chat';
```
shared/components/Chat/
├── types.ts # TypeScript 类型定义
├── ChatContainer.tsx # 核心容器组件
├── MessageRenderer.tsx # 默认消息渲染器
├── CodeBlockRenderer.tsx # 代码块渲染器
├── index.ts # 统一导出
├── types.ts # 类型定义
├── AIStreamChat.tsx # 🆕 流式对话组件(推荐)
├── ThinkingBlock.tsx # 🆕 深度思考展示
├── ConversationList.tsx # 🆕 会话列表
├── ChatContainer.tsx # 传统对话容器(向后兼容)
├── MessageRenderer.tsx # 消息渲染器
├── CodeBlockRenderer.tsx # 代码块渲染器
├── hooks/
│ ├── index.ts
│ ├── useAIStream.ts # 🆕 流式响应 Hook
│ └── useConversations.ts # 🆕 会话管理 Hook
├── styles/
── chat.css # 样式文件
├── index.ts # 统一导出
└── README.md # 本文档
── chat.css # 传统样式
│ ├── ai-stream-chat.css # 🆕 流式对话样式
│ ├── thinking.css # 🆕 深度思考样式
│ └── conversation-list.css # 🆕 会话列表样式
└── README.md # 本文档
```
---
## 🎯 使用场景
## 🎨 设计风格
### 1. AIAAI智能问答
采用**现代感设计**(参考 Ant Design X Ultramodern
```typescript
<ChatContainer
conversationType="aia"
providerConfig={{
apiEndpoint: '/api/aia/chat',
}}
/>
```
### 2. PKB个人知识库
```typescript
<ChatContainer
conversationType="pkb"
conversationKey={knowledgeBaseId}
providerConfig={{
apiEndpoint: '/api/pkb/query',
}}
/>
```
### 3. Tool C数据清洗
```typescript
<ChatContainer
conversationType="tool-c"
conversationKey={sessionId}
providerConfig={{
apiEndpoint: '/api/dc/tool-c/process',
}}
customMessageRenderer={(msgInfo) => (
<MessageRenderer
messageInfo={msgInfo}
onExecuteCode={handleExecuteCode}
/>
)}
/>
```
---
## 🐛 常见问题
### Q1: 如何自定义样式?
通过 `className``style` 属性:
```typescript
<ChatContainer
className="my-custom-chat"
style={{ height: '600px' }}
// ...
/>
```
或修改 `styles/chat.css`
### Q2: 如何处理流式响应?
当前版本暂不支持流式响应,计划在后续版本中支持。
### Q3: 如何添加新的对话类型?
1.`types.ts` 中扩展 `ConversationType`
2. 根据需要自定义 `customMessageRenderer`
- **配色**:主色 Indigo (#6366f1),思考色 Violet (#a78bfa)
- **圆角**:大圆角 12-16px
- **阴影**:柔和阴影,层次分明
- **动画**:流畅过渡,微交互
- **布局**:清爽简洁,留白适度
---
## 📝 开发记录
- **2025-12-07**: 初始版本,基于 Ant Design X 2.1.0 重构
- 完整开发记录:`docs/03-业务模块/DC-数据清洗整理/06-开发记录/`
- **2025-01-14**: V2 版本发布,新增流式响应、深度思考、会话管理
- **2025-12-07**: V1 初始版本,基于 Ant Design X 2.1.0 构建
---
## 📚 参考资料
- [Ant Design X 官方文档](https://x.ant.design)
- [Ant Design X SDK 文档](https://x.ant.design/x-sdks/introduce-cn)
- [项目架构文档](../../../docs/00-系统总体设计/)
- [Ant Design X Ultramodern Playground](https://x.ant.design/docs/playground/ultramodern-cn)
- [OpenAI API 流式响应格式](https://platform.openai.com/docs/api-reference/chat/streaming)

View File

@@ -0,0 +1,132 @@
/**
* ThinkingBlock - 深度思考展示组件
*
* 展示 AI 的深度思考过程,支持:
* - 流式显示思考内容
* - 折叠/展开
* - 思考时间显示
* - 现代感动画效果
*/
import React, { useState, useEffect, useMemo } from 'react';
import { Collapse, Typography } from 'antd';
import {
ThunderboltOutlined,
LoadingOutlined,
CheckCircleOutlined,
} from '@ant-design/icons';
import './styles/thinking.css';
const { Text } = Typography;
/**
* ThinkingBlock Props
*/
export interface ThinkingBlockProps {
/** 思考内容 */
content: string;
/** 是否正在思考 */
isThinking?: boolean;
/** 思考耗时(秒) */
duration?: number;
/** 默认是否展开 */
defaultExpanded?: boolean;
/** 自定义类名 */
className?: string;
}
/**
* 深度思考展示组件
*/
export const ThinkingBlock: React.FC<ThinkingBlockProps> = ({
content,
isThinking = false,
duration,
defaultExpanded = false,
className = '',
}) => {
const [expanded, setExpanded] = useState(defaultExpanded);
const [startTime] = useState(Date.now());
const [elapsedTime, setElapsedTime] = useState(0);
// 计时器
useEffect(() => {
if (!isThinking) return;
const timer = setInterval(() => {
setElapsedTime(Math.floor((Date.now() - startTime) / 1000));
}, 1000);
return () => clearInterval(timer);
}, [isThinking, startTime]);
// 显示时间
const displayTime = useMemo(() => {
const seconds = duration ?? elapsedTime;
if (seconds < 60) {
return `${seconds}`;
}
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
return `${minutes}${remainingSeconds}`;
}, [duration, elapsedTime]);
// 状态图标
const StatusIcon = isThinking ? (
<LoadingOutlined className="thinking-icon spinning" />
) : (
<CheckCircleOutlined className="thinking-icon done" />
);
// 标题
const title = (
<div className="thinking-header">
<ThunderboltOutlined className="thinking-bolt" />
<span className="thinking-title">
{isThinking ? '深度思考中...' : '深度思考'}
</span>
{StatusIcon}
<Text className="thinking-time" type="secondary">
{displayTime}
</Text>
</div>
);
// 如果没有内容且不在思考中,不显示
if (!content && !isThinking) {
return null;
}
return (
<div className={`thinking-block ${isThinking ? 'thinking' : 'done'} ${className}`}>
<Collapse
activeKey={expanded ? ['thinking'] : []}
onChange={(keys) => setExpanded(keys.includes('thinking'))}
bordered={false}
expandIconPosition="end"
items={[{
key: 'thinking',
label: title,
children: (
<div className="thinking-content">
{content ? (
<div className="thinking-text">
{content}
{isThinking && <span className="thinking-cursor"></span>}
</div>
) : isThinking ? (
<div className="thinking-placeholder">
<LoadingOutlined style={{ fontSize: 14, marginRight: 8 }} />
<span>...</span>
</div>
) : null}
</div>
),
}]}
/>
</div>
);
};
export default ThinkingBlock;

View File

@@ -0,0 +1,21 @@
/**
* Chat 通用组件 - Hooks 导出
*/
export { useAIStream } from './useAIStream';
export type {
UseAIStreamConfig,
UseAIStreamReturn,
StreamStatus,
StreamResult,
SendOptions,
} from './useAIStream';
export { useConversations } from './useConversations';
export type {
UseConversationsConfig,
UseConversationsReturn,
Conversation,
ConversationGroup,
} from './useConversations';

View File

@@ -0,0 +1,313 @@
/**
* useAIStream - AI 流式响应 Hook
*
* 处理 OpenAI Compatible 格式的 SSE 流式响应
* 支持:
* - 内容流式显示
* - 深度思考展示reasoning_content
* - 中断请求
* - 错误处理
*/
import { useState, useCallback, useRef } from 'react';
/**
* OpenAI Compatible Chunk 格式
*/
interface OpenAIChunk {
id: string;
object: string;
created: number;
model: string;
choices: Array<{
index: number;
delta: {
role?: string;
content?: string;
reasoning_content?: string;
};
finish_reason: string | null;
}>;
usage?: {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
};
}
/**
* 流式状态
*/
export type StreamStatus = 'idle' | 'connecting' | 'streaming' | 'thinking' | 'complete' | 'error' | 'aborted';
/**
* 流式响应结果
*/
export interface StreamResult {
content: string;
thinking: string;
messageId: string;
usage?: {
promptTokens: number;
completionTokens: number;
totalTokens: number;
};
}
/**
* useAIStream Hook 配置
*/
export interface UseAIStreamConfig {
/** API 端点 */
apiEndpoint: string;
/** 请求头 */
headers?: Record<string, string>;
/** 超时时间(毫秒) */
timeout?: number;
}
/**
* useAIStream Hook 返回值
*/
export interface UseAIStreamReturn {
/** 当前内容 */
content: string;
/** 思考内容 */
thinking: string;
/** 流式状态 */
status: StreamStatus;
/** 是否正在流式输出 */
isStreaming: boolean;
/** 是否正在思考 */
isThinking: boolean;
/** 错误信息 */
error: string | null;
/** 发送消息 */
sendMessage: (message: string, options?: SendOptions) => Promise<StreamResult | null>;
/** 中断请求 */
abort: () => void;
/** 重置状态 */
reset: () => void;
}
/**
* 发送选项
*/
export interface SendOptions {
/** 会话 ID */
conversationId?: string;
/** 智能体 ID */
agentId?: string;
/** 启用深度思考 */
enableDeepThinking?: boolean;
/** 附件 ID 列表 */
attachmentIds?: string[];
/** 额外参数 */
extra?: Record<string, any>;
}
/**
* AI 流式响应 Hook
*/
export function useAIStream(config: UseAIStreamConfig): UseAIStreamReturn {
const { apiEndpoint, headers = {}, timeout = 60000 } = config;
// 状态
const [content, setContent] = useState('');
const [thinking, setThinking] = useState('');
const [status, setStatus] = useState<StreamStatus>('idle');
const [error, setError] = useState<string | null>(null);
// Refs
const abortControllerRef = useRef<AbortController | null>(null);
const messageIdRef = useRef<string>('');
/**
* 重置状态
*/
const reset = useCallback(() => {
setContent('');
setThinking('');
setStatus('idle');
setError(null);
messageIdRef.current = '';
}, []);
/**
* 中断请求
*/
const abort = useCallback(() => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
setStatus('aborted');
}
}, []);
/**
* 发送消息
*/
const sendMessage = useCallback(async (
message: string,
options: SendOptions = {}
): Promise<StreamResult | null> => {
// 重置状态
reset();
setStatus('connecting');
// 创建 AbortController
abortControllerRef.current = new AbortController();
const signal = abortControllerRef.current.signal;
// 设置超时
const timeoutId = setTimeout(() => {
abort();
setError('请求超时');
}, timeout);
let fullContent = '';
let fullThinking = '';
let usage: StreamResult['usage'] | undefined;
try {
const response = await fetch(apiEndpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'text/event-stream',
...headers,
},
body: JSON.stringify({
content: message,
conversationId: options.conversationId,
agentId: options.agentId,
enableDeepThinking: options.enableDeepThinking,
attachmentIds: options.attachmentIds,
...options.extra,
}),
signal,
});
clearTimeout(timeoutId);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const reader = response.body?.getReader();
if (!reader) {
throw new Error('无法获取响应流');
}
const decoder = new TextDecoder();
let buffer = '';
setStatus('streaming');
while (true) {
const { done, value } = await reader.read();
if (done) break;
buffer += decoder.decode(value, { stream: true });
const lines = buffer.split('\n');
buffer = lines.pop() || '';
for (const line of lines) {
if (!line.startsWith('data: ')) continue;
const data = line.slice(6).trim();
// [DONE] 标识
if (data === '[DONE]') {
setStatus('complete');
continue;
}
try {
const chunk: OpenAIChunk = JSON.parse(data);
// 错误处理
if ((chunk as any).error) {
throw new Error((chunk as any).error.message);
}
// 保存消息 ID
if (chunk.id && !messageIdRef.current) {
messageIdRef.current = chunk.id;
}
// 处理 choices
const delta = chunk.choices?.[0]?.delta;
if (delta) {
// 思考内容
if (delta.reasoning_content) {
setStatus('thinking');
fullThinking += delta.reasoning_content;
setThinking(fullThinking);
}
// 正文内容
if (delta.content) {
setStatus('streaming');
fullContent += delta.content;
setContent(fullContent);
}
}
// 使用量
if (chunk.usage) {
usage = {
promptTokens: chunk.usage.prompt_tokens,
completionTokens: chunk.usage.completion_tokens,
totalTokens: chunk.usage.total_tokens,
};
}
// 完成标识
if (chunk.choices?.[0]?.finish_reason === 'stop') {
setStatus('complete');
}
} catch (parseError) {
console.warn('[useAIStream] 解析 Chunk 失败:', data, parseError);
}
}
}
return {
content: fullContent,
thinking: fullThinking,
messageId: messageIdRef.current,
usage,
};
} catch (err: any) {
clearTimeout(timeoutId);
if (err.name === 'AbortError') {
setStatus('aborted');
return null;
}
setError(err.message || '请求失败');
setStatus('error');
console.error('[useAIStream] 错误:', err);
return null;
}
}, [apiEndpoint, headers, timeout, reset, abort]);
return {
content,
thinking,
status,
isStreaming: status === 'streaming' || status === 'connecting',
isThinking: status === 'thinking',
error,
sendMessage,
abort,
reset,
};
}
export default useAIStream;

View File

@@ -0,0 +1,242 @@
/**
* useConversations - 会话管理 Hook
*
* 管理多会话状态,支持:
* - 会话列表 CRUD
* - 当前会话切换
* - 会话分组(今天、昨天、更早)
*/
import { useState, useCallback, useMemo } from 'react';
/**
* 会话信息
*/
export interface Conversation {
id: string;
title: string;
agentId?: string;
agentName?: string;
agentIcon?: string;
createdAt: Date;
updatedAt: Date;
messageCount?: number;
lastMessage?: string;
}
/**
* 会话分组
*/
export interface ConversationGroup {
label: string;
key: 'today' | 'yesterday' | 'earlier';
conversations: Conversation[];
}
/**
* useConversations 配置
*/
export interface UseConversationsConfig {
/** 初始会话列表 */
initialConversations?: Conversation[];
/** 当前会话 ID */
currentId?: string;
/** 会话变更回调 */
onConversationChange?: (conversation: Conversation | null) => void;
}
/**
* useConversations 返回值
*/
export interface UseConversationsReturn {
/** 会话列表 */
conversations: Conversation[];
/** 分组会话 */
groupedConversations: ConversationGroup[];
/** 当前会话 */
current: Conversation | null;
/** 当前会话 ID */
currentId: string | null;
/** 设置当前会话 */
setCurrent: (id: string | null) => void;
/** 添加会话 */
addConversation: (conversation: Omit<Conversation, 'id' | 'createdAt' | 'updatedAt'>) => Conversation;
/** 更新会话 */
updateConversation: (id: string, updates: Partial<Conversation>) => void;
/** 删除会话 */
deleteConversation: (id: string) => void;
/** 设置会话列表 */
setConversations: (conversations: Conversation[]) => void;
/** 刷新会话列表(外部调用) */
refresh: () => void;
}
/**
* 生成唯一 ID
*/
function generateId(): string {
return `conv-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`;
}
/**
* 判断是否是今天
*/
function isToday(date: Date): boolean {
const today = new Date();
return (
date.getDate() === today.getDate() &&
date.getMonth() === today.getMonth() &&
date.getFullYear() === today.getFullYear()
);
}
/**
* 判断是否是昨天
*/
function isYesterday(date: Date): boolean {
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
return (
date.getDate() === yesterday.getDate() &&
date.getMonth() === yesterday.getMonth() &&
date.getFullYear() === yesterday.getFullYear()
);
}
/**
* 会话管理 Hook
*/
export function useConversations(config: UseConversationsConfig = {}): UseConversationsReturn {
const { initialConversations = [], onConversationChange } = config;
// 会话列表
const [conversations, setConversationsState] = useState<Conversation[]>(initialConversations);
// 当前会话 ID
const [currentId, setCurrentId] = useState<string | null>(config.currentId || null);
// 当前会话
const current = useMemo(() => {
if (!currentId) return null;
return conversations.find(c => c.id === currentId) || null;
}, [conversations, currentId]);
// 分组会话
const groupedConversations = useMemo<ConversationGroup[]>(() => {
const today: Conversation[] = [];
const yesterday: Conversation[] = [];
const earlier: Conversation[] = [];
// 按更新时间排序
const sorted = [...conversations].sort(
(a, b) => new Date(b.updatedAt).getTime() - new Date(a.updatedAt).getTime()
);
sorted.forEach(conv => {
const updatedAt = new Date(conv.updatedAt);
if (isToday(updatedAt)) {
today.push(conv);
} else if (isYesterday(updatedAt)) {
yesterday.push(conv);
} else {
earlier.push(conv);
}
});
const groups: ConversationGroup[] = [];
if (today.length > 0) {
groups.push({ label: '今天', key: 'today', conversations: today });
}
if (yesterday.length > 0) {
groups.push({ label: '昨天', key: 'yesterday', conversations: yesterday });
}
if (earlier.length > 0) {
groups.push({ label: '更早', key: 'earlier', conversations: earlier });
}
return groups;
}, [conversations]);
/**
* 设置当前会话
*/
const setCurrent = useCallback((id: string | null) => {
setCurrentId(id);
const conv = id ? conversations.find(c => c.id === id) : null;
onConversationChange?.(conv || null);
}, [conversations, onConversationChange]);
/**
* 添加会话
*/
const addConversation = useCallback((
data: Omit<Conversation, 'id' | 'createdAt' | 'updatedAt'>
): Conversation => {
const now = new Date();
const newConversation: Conversation = {
...data,
id: generateId(),
createdAt: now,
updatedAt: now,
};
setConversationsState(prev => [newConversation, ...prev]);
return newConversation;
}, []);
/**
* 更新会话
*/
const updateConversation = useCallback((id: string, updates: Partial<Conversation>) => {
setConversationsState(prev =>
prev.map(conv =>
conv.id === id
? { ...conv, ...updates, updatedAt: new Date() }
: conv
)
);
}, []);
/**
* 删除会话
*/
const deleteConversation = useCallback((id: string) => {
setConversationsState(prev => prev.filter(conv => conv.id !== id));
// 如果删除的是当前会话,清空选择
if (currentId === id) {
setCurrent(null);
}
}, [currentId, setCurrent]);
/**
* 设置会话列表
*/
const setConversations = useCallback((newConversations: Conversation[]) => {
setConversationsState(newConversations);
}, []);
/**
* 刷新(占位,由外部实现)
*/
const refresh = useCallback(() => {
// 由外部实现数据获取
console.log('[useConversations] refresh called');
}, []);
return {
conversations,
groupedConversations,
current,
currentId,
setCurrent,
addConversation,
updateConversation,
deleteConversation,
setConversations,
refresh,
};
}
export default useConversations;

View File

@@ -1,13 +1,62 @@
/**
* Chat 通用组件库 - 统一导出
*
* 用于前端通用能力层的 AI 对话组件
* 基于 Ant Design X 构建的 AI 对话通用组件
* 支持流式响应、深度思考、会话管理等能力
*
* @version 2.0.0 (升级版)
*/
// ============================================
// 核心组件
// ============================================
/** 流式对话组件(推荐) */
export { AIStreamChat } from './AIStreamChat';
export type { AIStreamChatProps, WelcomeConfig, PromptItem } from './AIStreamChat';
/** 深度思考展示组件 */
export { ThinkingBlock } from './ThinkingBlock';
export type { ThinkingBlockProps } from './ThinkingBlock';
/** 会话列表组件 */
export { ConversationList } from './ConversationList';
export type { ConversationListProps } from './ConversationList';
// ============================================
// 传统组件(向后兼容)
// ============================================
/** 传统对话容器(非流式) */
export { ChatContainer } from './ChatContainer';
/** 消息渲染器 */
export { MessageRenderer } from './MessageRenderer';
/** 代码块渲染器 */
export { CodeBlockRenderer } from './CodeBlockRenderer';
// ============================================
// Hooks
// ============================================
export { useAIStream, useConversations } from './hooks';
export type {
UseAIStreamConfig,
UseAIStreamReturn,
StreamStatus,
StreamResult,
SendOptions,
UseConversationsConfig,
UseConversationsReturn,
Conversation,
ConversationGroup,
} from './hooks';
// ============================================
// 类型定义
// ============================================
export type {
ChatContainerProps,
ChatMessage,
@@ -17,4 +66,3 @@ export type {
CodeBlockRendererProps,
ChatProviderConfig,
} from './types';

View File

@@ -0,0 +1,277 @@
/**
* AIStreamChat 流式对话组件样式
*
* 现代感设计(参考 Ant Design X Ultramodern
* - 大标题欢迎页
* - 卡片式消息
* - 渐变按钮
* - 流畅动画
*/
.ai-stream-chat {
display: flex;
flex-direction: column;
height: 100%;
background: linear-gradient(180deg, #ffffff 0%, #f8fafc 100%);
}
/* 消息区域 */
.chat-messages-area {
flex: 1;
overflow-y: auto;
padding: 24px;
}
/* 欢迎页 */
.welcome-container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 60vh;
padding: 40px 20px;
}
.welcome-card {
max-width: 600px;
text-align: center;
}
.welcome-card :global(.ant-welcome-icon) {
font-size: 64px;
margin-bottom: 24px;
color: #6366f1;
}
.welcome-card :global(.ant-welcome-title) {
font-size: 32px;
font-weight: 700;
color: #111827;
letter-spacing: -0.02em;
margin-bottom: 12px;
}
.welcome-card :global(.ant-welcome-description) {
font-size: 16px;
color: #6b7280;
line-height: 1.6;
}
/* 快捷提示 */
.welcome-prompts {
margin-top: 32px;
max-width: 600px;
}
.welcome-prompts :global(.ant-prompts-item) {
padding: 16px 20px;
border-radius: 12px;
border: 1px solid #e5e7eb;
background: white;
transition: all 0.3s ease;
cursor: pointer;
}
.welcome-prompts :global(.ant-prompts-item:hover) {
border-color: #6366f1;
box-shadow: 0 4px 12px rgba(99, 102, 241, 0.12);
transform: translateY(-2px);
}
.welcome-prompts :global(.ant-prompts-item-icon) {
color: #6366f1;
font-size: 18px;
}
/* 消息列表 */
.messages-list {
max-width: 800px;
margin: 0 auto;
}
/* 消息气泡样式 */
.messages-list :global(.ant-bubble) {
margin-bottom: 20px;
}
/* AI 消息 */
.messages-list :global(.ant-bubble-start) {
background: white;
border: 1px solid #e5e7eb;
border-radius: 16px;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
padding: 16px 20px;
max-width: 85%;
}
/* 用户消息 */
.messages-list :global(.ant-bubble-end) {
background: linear-gradient(135deg, #6366f1 0%, #4f46e5 100%);
color: white;
border-radius: 16px;
padding: 12px 18px;
max-width: 70%;
box-shadow: 0 4px 12px rgba(99, 102, 241, 0.25);
}
.messages-list :global(.ant-bubble-end *) {
color: white !important;
}
/* 消息内容包装 */
.message-wrapper {
display: flex;
flex-direction: column;
gap: 12px;
}
.message-text {
font-size: 15px;
line-height: 1.7;
color: #334155;
white-space: pre-wrap;
word-break: break-word;
}
/* 打字光标 */
.typing-cursor {
display: inline-block;
animation: cursor-blink 0.8s step-end infinite;
color: #6366f1;
margin-left: 2px;
}
@keyframes cursor-blink {
0%, 100% {
opacity: 1;
}
50% {
opacity: 0;
}
}
/* 输入区域 */
.chat-input-area {
padding: 16px 24px 24px;
background: white;
border-top: 1px solid #e5e7eb;
box-shadow: 0 -4px 12px rgba(0, 0, 0, 0.02);
}
/* 工具栏 */
.input-toolbar {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 12px;
}
/* 深度思考按钮 */
.deep-thinking-btn {
border-radius: 20px;
font-size: 13px;
height: 32px;
transition: all 0.3s ease;
}
.deep-thinking-btn.active {
background: linear-gradient(135deg, #a78bfa 0%, #8b5cf6 100%);
border-color: transparent;
color: white;
box-shadow: 0 2px 8px rgba(139, 92, 246, 0.3);
}
.deep-thinking-btn.active:hover {
background: linear-gradient(135deg, #9f7ff6 0%, #7c3aed 100%);
}
/* 发送器 */
.chat-sender {
border-radius: 16px;
border: 2px solid #e5e7eb;
background: #f9fafb;
transition: all 0.3s ease;
overflow: hidden;
}
.chat-sender:focus-within {
border-color: #6366f1;
background: white;
box-shadow: 0 0 0 4px rgba(99, 102, 241, 0.1);
}
.chat-sender :global(.ant-sender-content) {
padding: 12px 16px;
}
.chat-sender :global(.ant-sender-actions) {
padding: 8px 12px;
background: transparent;
}
/* 附件预览 */
.attachments-preview {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-top: 12px;
}
.attachment-item {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 12px;
background: #f3f4f6;
border-radius: 8px;
font-size: 13px;
color: #4b5563;
}
.attachment-item :global(.anticon) {
color: #6366f1;
}
/* 滚动条 */
.chat-messages-area::-webkit-scrollbar {
width: 8px;
}
.chat-messages-area::-webkit-scrollbar-track {
background: transparent;
}
.chat-messages-area::-webkit-scrollbar-thumb {
background: #e5e7eb;
border-radius: 4px;
}
.chat-messages-area::-webkit-scrollbar-thumb:hover {
background: #d1d5db;
}
/* 响应式 */
@media (max-width: 768px) {
.chat-messages-area {
padding: 16px;
}
.chat-input-area {
padding: 12px 16px 16px;
}
.welcome-card :global(.ant-welcome-title) {
font-size: 24px;
}
.messages-list :global(.ant-bubble-start),
.messages-list :global(.ant-bubble-end) {
max-width: 90%;
}
}
/* 暗色模式支持(预留) */
@media (prefers-color-scheme: dark) {
/* 可在此添加暗色模式样式 */
}

View File

@@ -0,0 +1,213 @@
/**
* ConversationList 会话列表样式
*
* 现代感设计(参考 Ant Design X Ultramodern
* - 简洁清爽
* - 柔和阴影
* - 流畅过渡
*/
.conversation-list {
display: flex;
flex-direction: column;
height: 100%;
width: 280px;
background: #ffffff;
border-right: 1px solid #e5e7eb;
}
/* 头部 */
.conversation-list-header {
padding: 20px 16px;
border-bottom: 1px solid #f3f4f6;
}
.conversation-list-logo {
display: flex;
align-items: center;
gap: 12px;
}
.conversation-list-logo .default-logo {
font-size: 24px;
color: #6366f1;
}
.conversation-list-title {
font-size: 18px;
font-weight: 600;
color: #111827;
letter-spacing: -0.02em;
}
/* 新建会话按钮 */
.conversation-list-new {
padding: 12px 16px;
}
.new-conversation-btn {
height: 44px;
border-radius: 12px;
border: 1px dashed #d1d5db;
background: linear-gradient(135deg, #f9fafb 0%, #f3f4f6 100%);
color: #6366f1;
font-weight: 500;
transition: all 0.3s ease;
}
.new-conversation-btn:hover {
border-color: #6366f1;
background: linear-gradient(135deg, #eef2ff 0%, #e0e7ff 100%);
color: #4f46e5;
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(99, 102, 241, 0.15);
}
/* 会话列表内容 */
.conversation-list-content {
flex: 1;
overflow-y: auto;
padding: 8px 12px;
}
/* 分组标签 */
.conversation-group {
margin-bottom: 16px;
}
.conversation-group-label {
padding: 8px 4px;
font-size: 12px;
font-weight: 500;
text-transform: uppercase;
letter-spacing: 0.05em;
}
/* 会话项 */
.conversation-item {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 12px;
border-radius: 12px;
cursor: pointer;
transition: all 0.2s ease;
margin-bottom: 4px;
position: relative;
}
.conversation-item:hover {
background: #f9fafb;
}
.conversation-item.active {
background: linear-gradient(135deg, #eef2ff 0%, #e0e7ff 100%);
}
.conversation-item.active::before {
content: '';
position: absolute;
left: 0;
top: 50%;
transform: translateY(-50%);
width: 3px;
height: 24px;
background: #6366f1;
border-radius: 0 3px 3px 0;
}
/* 会话图标 */
.conversation-item-icon {
flex-shrink: 0;
width: 36px;
height: 36px;
display: flex;
align-items: center;
justify-content: center;
border-radius: 10px;
background: #f3f4f6;
color: #6b7280;
font-size: 16px;
}
.conversation-item.active .conversation-item-icon {
background: #6366f1;
color: white;
}
.agent-icon {
font-size: 20px;
}
/* 会话内容 */
.conversation-item-content {
flex: 1;
min-width: 0;
overflow: hidden;
}
.conversation-item-title {
font-size: 14px;
font-weight: 500;
color: #111827;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
line-height: 1.4;
}
.conversation-item-preview {
font-size: 12px;
color: #6b7280;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
margin-top: 4px;
line-height: 1.4;
}
/* 更多按钮 */
.conversation-item-more {
opacity: 0;
flex-shrink: 0;
color: #9ca3af;
transition: opacity 0.2s ease;
}
.conversation-item:hover .conversation-item-more {
opacity: 1;
}
/* 空状态 */
.conversation-empty {
padding: 40px 20px;
}
/* 滚动条 */
.conversation-list-content::-webkit-scrollbar {
width: 6px;
}
.conversation-list-content::-webkit-scrollbar-track {
background: transparent;
}
.conversation-list-content::-webkit-scrollbar-thumb {
background: #e5e7eb;
border-radius: 3px;
}
.conversation-list-content::-webkit-scrollbar-thumb:hover {
background: #d1d5db;
}
/* 响应式 */
@media (max-width: 768px) {
.conversation-list {
width: 100%;
border-right: none;
border-bottom: 1px solid #e5e7eb;
max-height: 40vh;
}
}

View File

@@ -0,0 +1,150 @@
/**
* ThinkingBlock 深度思考组件样式
*
* 现代感设计:
* - 渐变边框
* - 柔和阴影
* - 流畅动画
*/
.thinking-block {
margin: 12px 0;
border-radius: 12px;
overflow: hidden;
background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
border: 1px solid #e2e8f0;
transition: all 0.3s ease;
}
.thinking-block.thinking {
border-color: #a78bfa;
box-shadow: 0 0 0 1px rgba(167, 139, 250, 0.2), 0 4px 12px rgba(167, 139, 250, 0.1);
}
.thinking-block.done {
border-color: #10b981;
}
/* 折叠面板样式覆盖 */
.thinking-block :global(.ant-collapse) {
background: transparent;
border: none;
}
.thinking-block :global(.ant-collapse-item) {
border: none;
}
.thinking-block :global(.ant-collapse-header) {
padding: 12px 16px !important;
background: transparent;
}
.thinking-block :global(.ant-collapse-content) {
border-top: 1px solid #e2e8f0;
background: rgba(255, 255, 255, 0.8);
}
.thinking-block :global(.ant-collapse-content-box) {
padding: 16px !important;
}
/* 头部样式 */
.thinking-header {
display: flex;
align-items: center;
gap: 8px;
}
.thinking-bolt {
font-size: 16px;
color: #a78bfa;
}
.thinking-block.thinking .thinking-bolt {
animation: pulse 1.5s ease-in-out infinite;
}
.thinking-title {
font-weight: 500;
color: #334155;
font-size: 14px;
}
.thinking-icon {
font-size: 14px;
margin-left: auto;
}
.thinking-icon.spinning {
color: #a78bfa;
animation: spin 1s linear infinite;
}
.thinking-icon.done {
color: #10b981;
}
.thinking-time {
font-size: 12px;
color: #94a3b8;
margin-left: 8px;
}
/* 内容样式 */
.thinking-content {
font-size: 14px;
line-height: 1.8;
color: #475569;
}
.thinking-text {
white-space: pre-wrap;
word-break: break-word;
}
.thinking-cursor {
display: inline-block;
animation: blink 0.8s step-end infinite;
color: #a78bfa;
margin-left: 2px;
}
.thinking-placeholder {
display: flex;
align-items: center;
gap: 12px;
color: #94a3b8;
font-style: italic;
}
/* 动画 */
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@keyframes pulse {
0%, 100% {
opacity: 1;
transform: scale(1);
}
50% {
opacity: 0.6;
transform: scale(1.1);
}
}
@keyframes blink {
0%, 100% {
opacity: 1;
}
50% {
opacity: 0;
}
}