Compare commits

...

8 Commits

Author SHA1 Message Date
fe65f23fa7 feat: 网页端添加文件上传功能
- 支持图片上传(预览显示)
- 支持文本文件上传(txt, md, json, csv等)
- 支持 PDF 和 Word 文档
- 文件内容自动添加到消息中供 AI 分析
- 多文件同时上传支持
2026-04-13 23:31:20 +08:00
d1431ac521 fix: WebSocket history 消息添加 extra_data 字段,搜索结果可正确显示 2026-04-13 23:10:13 +08:00
49e15130f1 fix: 使用 insertAdjacentHTML 在设置 innerHTML 后添加搜索结果 2026-04-13 19:00:26 +08:00
9aaff7ee87 fix: appendMessage 接收 extraData 参数,在创建消息时直接处理搜索结果显示 2026-04-13 17:52:59 +08:00
b5284ce18e fix: 搜索结果持久化保存,刷新页面后历史对话也显示搜索结果
- 用户消息 extra_data 存储搜索结果
- API 返回消息时包含 extra_data
- 前端 displayHistory 处理历史搜索结果显示
2026-04-13 17:36:19 +08:00
8aa1f5fd88 fix: 搜索结果数量根据工具配置读取,不再固定5条 2026-04-13 17:16:37 +08:00
813b4887ed fix: 调整对话流程顺序
1. 用户发送消息 → 前端立即显示
2. 后端收到 → 广播用户消息 → 执行搜索 → 发送搜索结果
3. AI生成回复 → 显示

- sendMessage 立即显示用户消息
- user_message 事件避免重复显示
- 后端处理顺序:广播 → 搜索 → 保存 → LLM
2026-04-13 17:11:11 +08:00
3cbdddf773 fix: 搜索结果放到用户消息下面,折叠显示
- 搜索结果追加到最后一条用户消息的 message-body 中
- 默认折叠,点击展开/收起
- 显示搜索关键词和结果数量
2026-04-13 17:01:08 +08:00
2 changed files with 356 additions and 142 deletions

View File

@@ -648,6 +648,7 @@ async def get_messages(conversation_id: str, db: Session = Depends(get_db)):
"role": m.role,
"content": m.content,
"thinking_content": m.thinking_content, # v2新增
"extra_data": m.extra_data, # 包含搜索结果等
"source": m.source,
"agent_id": m.agent_id, # v2新增
"model_used": m.model_used, # v2新增
@@ -742,6 +743,7 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
"role": m.role,
"content": m.content,
"thinking_content": m.thinking_content,
"extra_data": m.extra_data, # 包含搜索结果等
"agent_id": m.agent_id, # 每条消息的Agent ID
"source": m.source,
"created_at": m.created_at.isoformat()
@@ -764,6 +766,7 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
elif action == "chat":
message = data.get("message", "")
files = data.get("files", []) # 上传的文件
conversation_id = data.get("conversation_id")
enable_thinking = data.get("enable_thinking", True)
agent_id_override = data.get("agent_id")
@@ -774,106 +777,27 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
if agent and agent.is_active:
current_agent_id = agent_id_override
if not message.strip():
# 如果没有消息但有文件,构造消息
if not message.strip() and files:
message = "[上传文件]"
if not message.strip() and not files:
continue
# 获取Agent配置
# 处理文件内容,添加到消息
if files:
for f in files:
if f.get('type') and f['type'].startswith('image/'):
message += f"\n[图片: {f['name']}]"
elif f.get('content'):
# 文本文件内容
message += f"\n\n文件 {f['name']} 内容:\n{f['content'][:3000]}"
# 1. 获取Agent配置
agent_config = agent_service.get_agent_config(current_agent_id)
agent_tools = agent_config.get('agent', {}).get('tools', [])
# 检查是否需要执行搜索
search_context = None
search_results_for_client = None # 用于发送给前端
logger.info(f"检查搜索条件: agent_tools={agent_tools}, disabled_tools={disabled_tools}")
if 'search' in agent_tools and 'search' not in disabled_tools:
# 只要启用了搜索工具且未禁用,就执行搜索
logger.info("搜索条件满足,开始执行搜索")
# 执行搜索
tool_service = ToolService(db)
search_tool = tool_service.get_default_tool('search')
logger.info(f"获取到搜索工具: {search_tool.name if search_tool else 'None'}")
if search_tool and search_tool.config.get('api_key'):
# 执行搜索
tool_service = ToolService(db)
search_tool = tool_service.get_default_tool('search')
if search_tool and search_tool.config.get('api_key'):
import httpx
import time
start_time = time.time()
try:
logger.info(f"执行搜索: query={message}")
tavily_url = "https://api.tavily.com/search"
config = search_tool.config
payload = {
"api_key": config.get('api_key'),
"query": message,
"max_results": config.get('max_results', 5),
"search_depth": config.get('search_depth', 'basic')
}
# 同步调用
with httpx.Client(timeout=30) as client:
resp = client.post(tavily_url, json=payload)
search_result = resp.json()
duration_ms = int((time.time() - start_time) * 1000)
if search_result.get("results"):
# 构建搜索上下文给LLM
search_context = "\n\n【搜索结果】\n"
for i, r in enumerate(search_result["results"][:5], 1):
search_context += f"{i}. {r.get('title', 'N/A')}\n {r.get('content', r.get('snippet', 'N/A'))[:200]}\n 来源: {r.get('url', 'N/A')}\n"
logger.info(f"搜索完成: {len(search_result['results'])} 条结果")
# 构建搜索结果给前端展示
search_results_for_client = [
{
"title": r.get('title', 'N/A'),
"snippet": r.get('content', r.get('snippet', ''))[:150],
"url": r.get('url', 'N/A')
}
for r in search_result["results"][:5]
]
# 发送搜索结果给前端
await websocket.send_json({
"type": "search_results",
"conversation_id": conversation_id,
"results": search_results_for_client,
"query": message
})
# 更新统计和日志
tool_service.increment_stats(search_tool.id, True)
tool_service.log_usage({
'tool_id': search_tool.id,
'tool_type': 'search',
'query': message,
'success': True,
'result_summary': f'{len(search_result["results"])} results',
'conversation_id': conversation_id,
'agent_id': current_agent_id,
'duration_ms': duration_ms
})
except Exception as e:
duration_ms = int((time.time() - start_time) * 1000)
logger.error(f"搜索失败: {e}")
tool_service.increment_stats(search_tool.id, False)
tool_service.log_usage({
'tool_id': search_tool.id,
'tool_type': 'search',
'query': message,
'success': False,
'error_message': str(e),
'conversation_id': conversation_id,
'duration_ms': duration_ms
})
# 获取或创建会话
# 2. 获取或创建会话(先有 conversation_id
if conversation_id:
conversation = conv_service.get_conversation(conversation_id)
else:
@@ -884,30 +808,122 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
"conversation_id": conversation_id
})
# 保存用户消息
user_msg = conv_service.add_message(
conversation_id=conversation.id,
role='user',
content=message,
source='web'
)
# 广播用户消息
# 3. 广播用户消息(前端立即看到)
await manager.send_to_user(MAIN_USER_ID, {
"type": "user_message",
"conversation_id": conversation_id,
"message": {
"id": user_msg.id,
"id": None, # 临时,后面会保存
"role": "user",
"content": message,
"source": "web",
"created_at": user_msg.created_at.isoformat()
"created_at": datetime.utcnow().isoformat()
}
})
# 获取Agent配置
agent_config = agent_service.get_agent_config(current_agent_id)
# 4. 执行搜索并发送搜索结果
search_context = None
search_results_for_client = None # 用于发送给前端和保存
logger.info(f"检查搜索条件: agent_tools={agent_tools}, disabled_tools={disabled_tools}")
if 'search' in agent_tools and 'search' not in disabled_tools:
logger.info("搜索条件满足,开始执行搜索")
tool_service = ToolService(db)
search_tool = tool_service.get_default_tool('search')
logger.info(f"获取到搜索工具: {search_tool.name if search_tool else 'None'}")
if search_tool and search_tool.config.get('api_key'):
import httpx
import time
start_time = time.time()
try:
logger.info(f"执行搜索: query={message}")
tavily_url = "https://api.tavily.com/search"
config = search_tool.config
payload = {
"api_key": config.get('api_key'),
"query": message,
"max_results": config.get('max_results', 5),
"search_depth": config.get('search_depth', 'basic')
}
with httpx.Client(timeout=30) as client:
resp = client.post(tavily_url, json=payload)
search_result = resp.json()
duration_ms = int((time.time() - start_time) * 1000)
if search_result.get("results"):
# 构建搜索上下文给LLM
max_for_llm = config.get('max_results', 5)
search_context = "\n\n【搜索结果】\n"
for i, r in enumerate(search_result["results"][:max_for_llm], 1):
search_context += f"{i}. {r.get('title', 'N/A')}\n {r.get('content', r.get('snippet', 'N/A'))[:200]}\n 来源: {r.get('url', 'N/A')}\n"
logger.info(f"搜索完成: {len(search_result['results'])} 条结果,使用 {min(len(search_result['results']), max_for_llm)}")
# 发送搜索结果给前端(按配置的数量)
max_display = config.get('max_results', 5)
search_results_for_client = [
{
"title": r.get('title', 'N/A'),
"snippet": r.get('content', r.get('snippet', ''))[:150],
"url": r.get('url', 'N/A')
}
for r in search_result["results"][:max_display]
]
await websocket.send_json({
"type": "search_results",
"conversation_id": conversation_id,
"results": search_results_for_client,
"query": message
})
# 更新统计和日志
tool_service.increment_stats(search_tool.id, True)
tool_service.log_usage({
'tool_id': search_tool.id,
'tool_type': 'search',
'query': message,
'success': True,
'result_summary': f'{len(search_result["results"])} results',
'conversation_id': conversation_id,
'agent_id': current_agent_id,
'duration_ms': duration_ms
})
except Exception as e:
duration_ms = int((time.time() - start_time) * 1000)
logger.error(f"搜索失败: {e}")
tool_service.increment_stats(search_tool.id, False)
tool_service.log_usage({
'tool_id': search_tool.id,
'tool_type': 'search',
'query': message,
'success': False,
'error_message': str(e),
'conversation_id': conversation_id,
'duration_ms': duration_ms
})
# 5. 保存用户消息到数据库(包含搜索结果)
user_msg = conv_service.add_message(
conversation_id=conversation.id,
role='user',
content=message,
source='web',
extra_data={'search_results': search_results_for_client, 'search_query': message} if search_results_for_client else None
)
# 6. 获取对话历史(包含刚保存的用户消息)
history = conv_service.get_conversation_history(conversation_id, limit=agent_config['agent'].get('max_history', 20))
# 7. 如果有搜索结果,添加到消息中
if search_context:
modified_system_prompt = agent_config['agent'].get('system_prompt', '') + "\n\n如果提供了搜索结果,请基于搜索结果回答用户问题,并注明信息来源。"
agent_config['agent']['system_prompt'] = modified_system_prompt
history.append({"role": "system", "content": f"以下是搜索到的相关信息,请参考这些内容回答用户问题:{search_context}"})
# 8. 调用LLM返回回复
if not agent_config or not agent_config.get('provider'):
await websocket.send_json({
"type": "error",
@@ -915,20 +931,7 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
})
continue
# 获取对话历史
history = conv_service.get_conversation_history(conversation_id, limit=agent_config['agent'].get('max_history', 20))
# 如果有搜索结果,添加到消息中
if search_context:
# 在系统提示中添加搜索结果说明
modified_system_prompt = agent_config['agent'].get('system_prompt', '') + "\n\n如果提供了搜索结果,请基于搜索结果回答用户问题,并注明信息来源。"
agent_config['agent']['system_prompt'] = modified_system_prompt
# 将搜索结果作为系统消息添加到历史
history.append({"role": "system", "content": f"以下是搜索到的相关信息,请参考这些内容回答用户问题:{search_context}"})
# 使用非流式调用LLM简化版本确保稳定
try:
# 调用LLM非流式
response, thinking_content = await llm_service.chat(
messages=history,
provider_config=agent_config['provider'],
@@ -949,7 +952,7 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
model_used=agent_config['provider'].get('default_model')
)
# 发送完整回复(包含思考内容)
# 发送AI回复
await websocket.send_json({
"type": "assistant_message",
"conversation_id": conversation_id,
@@ -967,7 +970,6 @@ async def websocket_endpoint(websocket: WebSocket, user_id: str):
logger.info(f"AI回复已发送: conversation_id={conversation_id}")
# 启用发送按钮
await websocket.send_json({
"type": "stream_end",
"conversation_id": conversation_id

View File

@@ -86,13 +86,17 @@
.thinking-toggle { font-size: 12px; color: #667eea; }
.thinking-content { margin-top: 12px; display: none; }
.thinking-content.expanded { display: block; }
.search-results-box { margin: 8px 0; padding: 12px; background: #f8f9fa; border-radius: 8px; border: 1px solid #e9ecef; }
.search-results-box h5 { margin: 0 0 8px; font-size: 14px; color: #495057; }
.search-result-item { margin-bottom: 8px; padding: 8px; background: white; border-radius: 6px; }
.search-results-box { margin: 12px 0; padding: 10px 12px; background: linear-gradient(135deg, #f0f7ff 0%, #e8f4f8 100%); border-radius: 8px; border: 1px solid #d0e8f0; }
.search-results-header { display: flex; align-items: center; justify-content: space-between; cursor: pointer; }
.search-results-header h5 { margin: 0; font-size: 13px; color: #10a37f; display: flex; align-items: center; gap: 6px; }
.search-results-toggle { font-size: 12px; color: #666; }
.search-results-content { margin-top: 10px; display: none; }
.search-results-content.expanded { display: block; }
.search-result-item { margin-bottom: 8px; padding: 8px 10px; background: white; border-radius: 6px; border: 1px solid #eee; }
.search-result-item:last-child { margin-bottom: 0; }
.search-result-title { font-size: 13px; color: #10a37f; font-weight: 500; margin-bottom: 4px; }
.search-result-snippet { font-size: 12px; color: #666; line-height: 1.4; }
.search-result-url { font-size: 11px; color: #999; margin-top: 4px; }
.search-result-url { font-size: 11px; color: #999; margin-top: 4px; overflow: hidden; text-overflow: ellipsis; }
/* Agent信息 */
.agent-info { font-size: 12px; color: #999; margin-top: 8px; }
@@ -103,10 +107,23 @@
.input-row { display: flex; gap: 12px; align-items: center; }
.input-row textarea { flex: 1; padding: 12px 16px; border: 1px solid #ddd; border-radius: 12px; font-size: 16px; resize: none; outline: none; max-height: 200px; min-height: 48px; line-height: 1.5; }
.input-row textarea:focus { border-color: #10a37f; }
.upload-btn { width: 48px; height: 48px; border-radius: 12px; background: #f5f5f5; border: 1px solid #ddd; cursor: pointer; font-size: 20px; display: flex; align-items: center; justify-content: center; transition: all 0.2s; color: #666; }
.upload-btn:hover { background: #e8e8e8; border-color: #10a37f; color: #10a37f; }
.send-btn { width: 48px; height: 48px; border-radius: 12px; background: #10a37f; border: none; color: #fff; cursor: pointer; font-size: 20px; display: flex; align-items: center; justify-content: center; transition: background 0.2s; }
.send-btn:hover { background: #0d8c6d; }
.send-btn:disabled { background: #ccc; cursor: not-allowed; }
/* 文件预览 */
.file-preview-area { margin-top: 12px; display: flex; gap: 8px; flex-wrap: wrap; }
.file-preview-item { position: relative; border: 1px solid #e0e0e0; border-radius: 8px; padding: 8px; background: #f8f9fa; max-width: 200px; }
.file-preview-item.image-preview { padding: 4px; }
.file-preview-item img { max-width: 180px; max-height: 120px; border-radius: 6px; }
.file-preview-item .file-icon { display: flex; align-items: center; gap: 8px; }
.file-preview-item .file-icon i { font-size: 24px; color: #10a37f; }
.file-preview-item .file-name { font-size: 12px; color: #666; max-width: 150px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.file-preview-item .file-remove { position: absolute; top: 4px; right: 4px; width: 20px; height: 20px; border-radius: 50%; background: #ff4757; color: white; border: none; cursor: pointer; font-size: 12px; display: flex; align-items: center; justify-content: center; }
.file-preview-item .file-remove:hover { background: #ff6b7a; }
/* 快捷语句 - 横向扁平 */
.quick-phrases-bar { display: flex; align-items: center; gap: 8px; margin-top: 12px; position: relative; }
.add-phrase-btn { padding: 6px 10px; background: #f0f0f0; border: 1px solid #ddd; border-radius: 6px; cursor: pointer; font-size: 12px; color: #666; white-space: nowrap; flex-shrink: 0; }
@@ -162,9 +179,12 @@
<div class="input-container">
<div class="input-area">
<div class="input-row">
<input type="file" id="fileInput" multiple accept="image/*,.pdf,.txt,.md,.json,.csv,.doc,.docx" style="display:none" onchange="handleFileUpload(event)">
<button class="upload-btn" onclick="document.getElementById('fileInput').click()" title="上传文件"><i class="ri-attachment-2"></i></button>
<textarea id="messageInput" placeholder="输入消息..." rows="1"></textarea>
<button class="send-btn" id="sendBtn" onclick="sendMessage()"><i class="ri-send-plane-fill"></i></button>
</div>
<div class="file-preview-area" id="filePreviewArea"></div>
<div class="quick-phrases-bar">
<div class="tool-toggle">
<input type="checkbox" id="enableSearch" checked>
@@ -276,9 +296,11 @@
case 'stream_end': document.getElementById('sendBtn').disabled = false; break;
case 'user_message':
lastUserMessage = data.message.content; // 存储最后一条用户消息
if (!isRegenerating) {
// 如果是刚发送的消息,已经显示了,不再重复显示
if (!isRegenerating && data.message.content !== lastSentMessage) {
appendMessage('user', data.message.content);
}
lastSentMessage = null; // 清除标记
// 注意:不要在这里重置 isRegenerating要等 assistant_message 处理后再重置
break;
case 'assistant_message':
@@ -298,7 +320,7 @@
}
// 消息渲染
function appendMessage(role, content, thinking = null, agentName = null) {
function appendMessage(role, content, thinking = null, agentName = null, extraData = null) {
const container = document.getElementById('messagesContainer');
container.querySelector('.welcome')?.remove();
@@ -365,6 +387,23 @@
html += '</div>';
div.innerHTML = html;
// 如果是用户消息且有搜索结果在设置innerHTML后追加
if (role === 'user' && extraData) {
console.log('Processing extraData for user message:', extraData);
console.log('search_results exists:', extraData.search_results);
if (extraData.search_results && extraData.search_results.length > 0) {
console.log('Building search results HTML for', extraData.search_results.length, 'results');
const searchHtml = buildSearchResultsHtml(extraData.search_results, extraData.search_query || content);
const bodyDiv = div.querySelector('.message-body');
console.log('bodyDiv found:', bodyDiv != null);
if (bodyDiv) {
bodyDiv.insertAdjacentHTML('beforeend', searchHtml);
console.log('Search results HTML inserted');
}
}
}
container.appendChild(div);
container.scrollTop = container.scrollHeight;
}
@@ -616,7 +655,10 @@
function displayHistory(messages) {
const container = document.getElementById('messagesContainer');
container.innerHTML = '';
messages.forEach(m => appendMessage(m.role, m.content, m.thinking_content));
messages.forEach(m => {
console.log('displayHistory message:', m.role, 'extra_data:', m.extra_data);
appendMessage(m.role, m.content, m.thinking_content, null, m.extra_data);
});
}
function clearMessages() {
@@ -635,12 +677,37 @@
if (!results || results.length === 0) return;
const container = document.getElementById('messagesContainer');
const div = document.createElement('div');
div.className = 'message assistant';
let html = `<div class="message-avatar">🔍</div><div class="message-body">
<div class="search-results-box">
<h5>搜索: ${escapeHtml(query.substring(0, 50))}${query.length > 50 ? '...' : ''}</h5>`;
// 找到最后一条用户消息
const userMessages = container.querySelectorAll('.message.user');
const lastUserMsg = userMessages[userMessages.length - 1];
if (!lastUserMsg) {
// 没有用户消息,作为独立消息显示
const div = document.createElement('div');
div.className = 'message assistant';
div.innerHTML = `<div class="message-avatar">🔍</div><div class="message-body">${buildSearchResultsHtml(results, query)}</div>`;
container.appendChild(div);
} else {
// 在用户消息的 message-body 中追加搜索结果
const msgBody = lastUserMsg.querySelector('.message-body');
if (msgBody) {
msgBody.innerHTML += buildSearchResultsHtml(results, query);
}
}
// 滚动到底部
container.scrollTop = container.scrollHeight;
}
function buildSearchResultsHtml(results, query) {
const resultId = 'sr-' + Date.now();
let html = `<div class="search-results-box">
<div class="search-results-header" onclick="toggleSearchResults('${resultId}')">
<h5><i class="ri-search-line"></i> 搜索: ${escapeHtml(query.substring(0, 30))}${query.length > 30 ? '...' : ''} (${results.length}条结果)</h5>
<span class="search-results-toggle" id="${resultId}-toggle">展开 <i class="ri-arrow-down-s-line"></i></span>
</div>
<div class="search-results-content" id="${resultId}">`;
for (const r of results) {
html += `<div class="search-result-item">
@@ -651,11 +718,19 @@
}
html += '</div></div>';
div.innerHTML = html;
container.appendChild(div);
// 滚动到底部
container.scrollTop = container.scrollHeight;
return html;
}
function toggleSearchResults(id) {
const content = document.getElementById(id);
const toggle = document.getElementById(id + '-toggle');
if (content.classList.contains('expanded')) {
content.classList.remove('expanded');
toggle.innerHTML = '展开 <i class="ri-arrow-down-s-line"></i>';
} else {
content.classList.add('expanded');
toggle.innerHTML = '收起 <i class="ri-arrow-up-s-line"></i>';
}
}
// 会话管理
@@ -714,27 +789,164 @@
function sendMessage() {
const input = document.getElementById('messageInput');
const msg = input.value.trim();
if (!msg) return;
// 如果没有消息且没有文件,不发送
if (!msg && pendingFiles.length === 0) return;
document.getElementById('sendBtn').disabled = true;
input.value = '';
input.style.height = 'auto';
// 立即显示用户消息(包含文件)
lastSentMessage = msg;
appendMessageWithFiles('user', msg, pendingFiles);
// 清空文件预览
pendingFiles = [];
document.getElementById('filePreviewArea').innerHTML = '';
// 获取工具禁用状态
const enableSearch = document.getElementById('enableSearch').checked;
const disabledTools = [];
if (!enableSearch) disabledTools.push('search');
// 发送消息(包含文件)
if (ws?.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({
action: 'chat',
message: msg,
conversation_id: currentConversationId,
agent_id: currentAgentId,
disabled_tools: disabledTools // 禁用的工具列表
disabled_tools: disabledTools,
files: lastSentFiles || [] // 发送的文件列表
}));
}
lastSentFiles = null; // 清空
}
let lastSentFiles = null; // 记录发送的文件
// 显示带文件的用户消息
function appendMessageWithFiles(role, content, files) {
const container = document.getElementById('messagesContainer');
container.querySelector('.welcome')?.remove();
const div = document.createElement('div');
div.className = `message ${role}`;
// 构建消息内容
let msgContent = content;
if (files && files.length > 0) {
lastSentFiles = files.map(f => ({
name: f.name,
type: f.type,
content: f.content
}));
// 添加文件信息到消息
let filesText = '\n\n[附件]';
for (const f of files) {
if (f.type.startsWith('image/')) {
filesText += `\n图片: ${f.name}`;
} else {
filesText += `\n文件: ${f.name}`;
// 文本文件显示内容摘要
if (!f.type.startsWith('image/') && f.content && f.content.length < 2000) {
filesText += `\n内容: ${f.content.substring(0, 500)}${f.content.length > 500 ? '...' : ''}`;
}
}
}
msgContent += filesText;
}
const avatar = role === 'user' ? '👤' : '🤖';
let html = `<div class="message-avatar">${avatar}</div><div class="message-body">`;
html += `<div class="message-content"><div class="user-message-text">${escapeHtml(msgContent)}</div></div>`;
html += `<input type="hidden" class="copy-source" value="${msgContent.replace(/"/g, '&quot;')}">`;
html += `<div class="message-actions"><button class="action-btn" onclick="copyMessage(this)"><i class="ri-file-copy-line"></i> 复制</button></div>`;
html += '</div>';
div.innerHTML = html;
container.appendChild(div);
container.scrollTop = container.scrollHeight;
}
let pendingFiles = []; // 待发送的文件
// 文件上传处理
function handleFileUpload(event) {
const files = event.target.files;
const previewArea = document.getElementById('filePreviewArea');
for (const file of files) {
const fileId = 'file-' + Date.now() + '-' + Math.random().toString(36).substr(2, 9);
// 读取文件内容
const reader = new FileReader();
reader.onload = (e) => {
const fileData = {
id: fileId,
name: file.name,
type: file.type,
size: file.size,
content: e.target.result
};
pendingFiles.push(fileData);
// 显示预览
const previewItem = document.createElement('div');
previewItem.className = 'file-preview-item';
previewItem.id = fileId + '-preview';
if (file.type.startsWith('image/')) {
previewItem.classList.add('image-preview');
previewItem.innerHTML = `
<img src="${e.target.result}" alt="${file.name}">
<button class="file-remove" onclick="removeFile('${fileId}')"><i class="ri-close-line"></i></button>
`;
} else {
// 文件图标
let iconClass = 'ri-file-text-line';
if (file.name.endsWith('.pdf')) iconClass = 'ri-file-pdf-line';
else if (file.name.endsWith('.json')) iconClass = 'ri-code-line';
else if (file.name.endsWith('.csv')) iconClass = 'ri-table-line';
else if (file.type.includes('word') || file.name.endsWith('.doc') || file.name.endsWith('.docx')) iconClass = 'ri-file-word-line';
previewItem.innerHTML = `
<div class="file-icon">
<i class="${iconClass}"></i>
<span class="file-name">${file.name}</span>
</div>
<button class="file-remove" onclick="removeFile('${fileId}')"><i class="ri-close-line"></i></button>
`;
}
previewArea.appendChild(previewItem);
};
// 根据文件类型选择读取方式
if (file.type.startsWith('image/')) {
reader.readAsDataURL(file);
} else if (file.type === 'application/pdf') {
reader.readAsDataURL(file);
} else {
// 文本类文件直接读取内容
reader.readAsText(file);
}
}
// 清空 input 以便再次选择
event.target.value = '';
}
function removeFile(fileId) {
pendingFiles = pendingFiles.filter(f => f.id !== fileId);
const preview = document.getElementById(fileId + '-preview');
if (preview) preview.remove();
}
// 发送消息
function setupTextarea() {
const textarea = document.getElementById('messageInput');
textarea.addEventListener('keydown', e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); } });