修复在线预览.doc/.ppt等一些问题

This commit is contained in:
runny committed 2026-05-07 15:38:18 +08:00
1 parent 66b108f9d8
commit 8647537f2f
6 files changed
+516 -390

No files matched your search

+193 -43
View File
@@ -7,6 +7,9 @@ backend/app/api/chat.py
"""
import io
import ipaddress
import tempfile
import os
import subprocess
from urllib.parse import urlparse
import requests
@@ -66,69 +69,111 @@ def _fetch_preview_source_bytes(file_url: str):
返回: (content_bytes, content_type, error_tuple)
其中 error_tuple = (message, status_code);成功时为 None。
"""
import base64
import json
import time
import sqlalchemy as sa
from urllib.parse import parse_qs
headers = {}
base_url = current_app.config.get('INTEGRATION_API_BASE', '')
api_key = current_app.config.get('INTEGRATION_API_KEY', '')
# 尝试解析 token 并续期
if base_url and file_url.startswith(base_url) and 'token=' in file_url:
def _resolve_latest_integration_url(raw_url: str):
dataset_id = ''
remote_document_id = ''
try:
import base64
import json
from urllib.parse import urlparse, parse_qs
parsed = urlparse(file_url)
parsed = urlparse(raw_url)
qs = parse_qs(parsed.query)
if 'token' in qs:
token = qs['token'][0]
token = (qs.get('token') or [''])[0]
if token:
parts = token.split('.')
if len(parts) >= 2:
payload_b64 = parts[1]
payload_b64 += '=' * (-len(payload_b64) % 4)
payload_str = base64.urlsafe_b64decode(payload_b64).decode('utf-8')
payload_data = json.loads(payload_str)
# 检查是否过期,或者直接重新获取
import time
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
dataset_id = str(payload_data.get('dataset_id') or '').strip()
remote_document_id = str(payload_data.get('remote_document_id') or '').strip()
except Exception:
pass
if not dataset_id or not remote_document_id:
try:
stmt = sa.text("CAST(retriever_resources AS TEXT) LIKE :url")
log = db.session.query(ChatLog).filter(stmt).params(url=f'%{raw_url}%').order_by(ChatLog.created_at.desc()).first()
if log and log.retriever_resources:
for r in log.retriever_resources:
source_url = str(r.get('source_download_url') or '')
if source_url == raw_url or (source_url and source_url.split('&token=')[0] == raw_url.split('&token=')[0]):
dataset_id = dataset_id or str(r.get('dataset_id') or r.get('metadata', {}).get('dataset_id') or '').strip()
remote_document_id = remote_document_id or str(
r.get('remote_document_id') or r.get('metadata', {}).get('remote_document_id') or r.get('document_id') or ''
).strip()
if dataset_id and remote_document_id:
break
except Exception as e:
current_app.logger.warning("[file-preview] failed to find IDs in ChatLog: %s", e)
if dataset_id and remote_document_id:
new_info = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
if new_info and new_info.get('source_download_url'):
current_app.logger.info("[file-preview] refreshed integration url for dataset=%s doc=%s", dataset_id, remote_document_id)
return new_info['source_download_url']
return raw_url
def _build_headers(raw_url: str):
next_headers = {}
if base_url and raw_url.startswith(base_url) and api_key:
next_headers['X-Integration-Key'] = api_key
return next_headers
def _should_refresh_from_response(resp) -> bool:
ctype = (resp.headers.get('content-type') or '').split(';')[0].strip().lower()
if resp.status_code == 401:
return True
if ctype == 'application/json':
body = (resp.content or b'')[:512].decode('utf-8', errors='ignore').lower()
if 'unauthorized' in body or '"error"' in body:
return True
return False
if base_url and file_url.startswith(base_url) and 'token=' in file_url:
try:
parsed = urlparse(file_url)
qs = parse_qs(parsed.query)
token = (qs.get('token') or [''])[0]
if token:
parts = token.split('.')
if len(parts) >= 2:
payload_b64 = parts[1]
payload_b64 += '=' * (-len(payload_b64) % 4)
payload_data = json.loads(base64.urlsafe_b64decode(payload_b64).decode('utf-8'))
exp = payload_data.get('exp', 0)
if exp and exp < time.time() + 300: # 如果已经过期或者即将在 5 分钟内过期
dataset_id = payload_data.get('dataset_id')
remote_document_id = payload_data.get('remote_document_id')
# 如果旧版本的 token 里没有这俩 ID,尝试从聊天记录反查
if not dataset_id or not remote_document_id:
from app.models import ChatLog
from app import db
import sqlalchemy as sa
try:
stmt = sa.text("CAST(retriever_resources AS TEXT) LIKE :url")
log = db.session.query(ChatLog).filter(stmt).params(url=f'%{file_url}%').order_by(ChatLog.created_at.desc()).first()
if log and log.retriever_resources:
for r in log.retriever_resources:
if r.get('source_download_url') == file_url:
dataset_id = dataset_id or r.get('dataset_id') or r.get('metadata', {}).get('dataset_id')
remote_document_id = remote_document_id or r.get('remote_document_id') or r.get('metadata', {}).get('remote_document_id') or r.get('document_id')
if dataset_id and remote_document_id:
break
except Exception as e:
current_app.logger.warning("[file-preview] failed to find IDs in ChatLog: %s", e)
if dataset_id and remote_document_id:
new_info = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
if new_info and new_info.get('source_download_url'):
file_url = new_info['source_download_url']
current_app.logger.info("[file-preview] refreshed expired integration url for dataset=%s doc=%s", dataset_id, remote_document_id)
if exp and exp < time.time() + 300:
file_url = _resolve_latest_integration_url(file_url)
except Exception as e:
current_app.logger.warning("[file-preview] failed to refresh expired integration token: %s", e)
if base_url and file_url.startswith(base_url) and api_key:
headers['X-Integration-Key'] = api_key
headers = _build_headers(file_url)
try:
upstream = requests.get(file_url, headers=headers, timeout=(5, 20))
except requests.RequestException as e:
current_app.logger.warning("[file-preview] upstream request failed: %s", e)
return None, None, ('failed to fetch source file', 502)
# 某些旧历史记录中的 source_download_url 已过期,但上游可能返回 200 + JSON 错误体。
# 这里统一视为“坏链接”,刷新最新下载地址后重试一次。
if base_url and file_url.startswith(base_url) and 'token=' in file_url and _should_refresh_from_response(upstream):
refreshed_url = _resolve_latest_integration_url(file_url)
if refreshed_url != file_url:
headers = _build_headers(refreshed_url)
try:
upstream = requests.get(refreshed_url, headers=headers, timeout=(5, 20))
file_url = refreshed_url
except requests.RequestException as e:
current_app.logger.warning("[file-preview] refreshed upstream request failed: %s", e)
return None, None, ('failed to fetch source file', 502)
if upstream.status_code != 200:
return None, None, (f'upstream returned status {upstream.status_code}', 502)
@@ -138,8 +183,103 @@ def _fetch_preview_source_bytes(file_url: str):
return None, None, ('file too large for online preview', 413)
content_type = (upstream.headers.get('content-type') or '').split(';')[0].strip().lower()
if content_type == 'application/json':
body = content[:512].decode('utf-8', errors='ignore')
current_app.logger.warning("[file-preview] upstream returned json instead of binary url=%s body=%s", file_url, body)
return None, None, ('upstream returned invalid preview payload', 502)
return content, content_type, None
def _convert_office_to_pdf(content: bytes, ext: str) -> bytes:
"""
使用 LibreOffice 将 office 文件转为 PDF
"""
with tempfile.TemporaryDirectory() as temp_dir:
input_path = os.path.join(temp_dir, f"input.{ext}")
with open(input_path, 'wb') as f:
f.write(content)
commands = [
'soffice',
'libreoffice',
r'C:\Program Files\LibreOffice\program\soffice.exe',
r'C:\Program Files (x86)\LibreOffice\program\soffice.exe'
]
success = False
for cmd in commands:
try:
process = subprocess.run(
[cmd, '--headless', '--convert-to', 'pdf', '--outdir', temp_dir, input_path],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
timeout=60
)
if process.returncode == 0:
success = True
break
else:
current_app.logger.warning(f"LibreOffice command {cmd} failed: {process.stderr.decode('utf-8', errors='ignore')}")
except (FileNotFoundError, subprocess.TimeoutExpired):
continue
# 如果 LibreOffice 失败,且是在 Windows 系统下,尝试调用本地安装的 WPS 或 MS Office
if not success and os.name == 'nt':
try:
import win32com.client
import pythoncom
pythoncom.CoInitialize()
output_path = os.path.join(temp_dir, "input.pdf")
if ext in ('doc', 'docx'):
try:
app = win32com.client.Dispatch("KWPS.Application") # 尝试 WPS Word
except Exception:
app = win32com.client.Dispatch("Word.Application") # 回退 MS Word
app.Visible = False
doc = app.Documents.Open(os.path.abspath(input_path))
doc.SaveAs(os.path.abspath(output_path), FileFormat=17) # 17 = wdFormatPDF
doc.Close()
app.Quit()
success = True
elif ext in ('ppt', 'pptx'):
try:
app = win32com.client.Dispatch("KWPP.Application") # 尝试 WPS PPT
except Exception:
app = win32com.client.Dispatch("PowerPoint.Application") # 回退 MS PPT
app.Visible = False
presentation = app.Presentations.Open(os.path.abspath(input_path), WithWindow=False)
presentation.SaveAs(os.path.abspath(output_path), 32) # 32 = ppSaveAsPDF
presentation.Close()
app.Quit()
success = True
elif ext in ('xls', 'xlsx'):
try:
app = win32com.client.Dispatch("KET.Application") # 尝试 WPS Excel
except Exception:
app = win32com.client.Dispatch("Excel.Application") # 回退 MS Excel
app.Visible = False
wb = app.Workbooks.Open(os.path.abspath(input_path))
wb.ExportAsFixedFormat(0, os.path.abspath(output_path)) # 0 = xlTypePDF
wb.Close(False)
app.Quit()
success = True
except ImportError:
current_app.logger.warning("pywin32 not installed, cannot fallback to WPS/MS Office COM API.")
except Exception as e:
current_app.logger.warning(f"WPS/MS Office COM conversion failed: {e}")
if not success:
raise Exception("Failed to convert document to PDF using LibreOffice or WPS/MS Office")
output_path = os.path.join(temp_dir, "input.pdf")
if os.path.exists(output_path):
with open(output_path, 'rb') as f:
return f.read()
else:
raise Exception("PDF output not found after conversion")
@chat_bp.route('/sessions', methods=['GET'])
@require_agent_permission
@@ -571,6 +711,16 @@ def preview_file_raw():
msg, code = err
return jsonify({'error': msg}), code
# 如果是无法纯前端渲染的旧版 Office 或 PPT 格式,尝试转为 PDF 供前端统一渲染
if ext in ('doc', 'ppt', 'pptx') and request.args.get('download') != '1':
try:
content = _convert_office_to_pdf(content, ext)
ext = 'pdf'
content_type = 'application/pdf'
except Exception as e:
current_app.logger.error("[file-preview] LibreOffice conversion failed: %s", e)
# 转换失败则回退到原始格式
fallback_types = {
'pdf': 'application/pdf',
'doc': 'application/msword',
+1
View File
@@ -14,3 +14,4 @@ openpyxl
pycryptodome
PyJWT
cryptography
pywin32
+19 -20
View File
@@ -1,20 +1,19 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#0284c7" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
<meta name="apple-mobile-web-app-title" content="AI工作台" />
<link rel="manifest" href="/manifest.webmanifest" />
<title>AI工作台</title>
<script type="module" crossorigin src="/assets/index-DNiQ9nKy.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-DDtKBb2t.css">
</head>
<body>
<div id="app"></div>
</body>
</html>
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover" />
<meta name="theme-color" content="#0284c7" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
<meta name="apple-mobile-web-app-title" content="AI工作台" />
<link rel="manifest" href="/manifest.webmanifest" />
<title>AI工作台</title>
<script type="module" crossorigin src="/assets/index-Cl-3HaxQ.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-Ci0e0qmM.css">
</head>
<body>
<div id="app"></div>␍
</body>
</html>
+48 -87
View File
@@ -64,67 +64,26 @@ const getExt = (raw: string) => {
};
const ext = computed(() => {
// URL extension has higher priority than display name.
const byUrl = getExt(props.file?.url || '');
if (byUrl) return byUrl;
return getExt(props.file?.name || '');
// Display name extension has higher priority than URL.
const byName = getExt(props.file?.name || '');
if (byName) return byName;
return getExt(props.file?.url || '');
});
const preferredMode = computed<'markdown' | 'image' | 'iframe' | 'sheet' | 'office'>(() => {
if (['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp'].includes(ext.value)) return 'image';
if (['md', 'markdown', 'txt', 'csv', 'vtt', 'properties', 'html', 'htm'].includes(ext.value)) return 'markdown';
if (['xlsx', 'xls'].includes(ext.value)) return 'office';
if (['docx', 'doc', 'pdf'].includes(ext.value)) return 'iframe';
if (['xlsx', 'xls'].includes(ext.value)) return 'sheet';
if (['docx'].includes(ext.value)) return 'office';
if (['doc', 'ppt', 'pptx', 'pdf'].includes(ext.value)) return 'iframe';
return 'iframe';
});
const resolvedMode = ref<'markdown' | 'image' | 'iframe' | 'sheet' | 'office'>('iframe');
const isOfficeDoc = computed(() => ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'].includes(ext.value));
/**
* 判断当前文件是否可使用微软 Office 在线预览。
* 实际条件:
* - 必须是 Office 文档类型;
* - 必须是 HTTPS;
* - 主机必须公网可达(非 localhost/私网网段)。
*/
const canUseOfficeOnlineViewer = computed(() => {
const raw = props.file?.url || '';
if (!raw || !isOfficeDoc.value) return false;
try {
const u = new URL(raw, window.location.origin);
// Office online viewer usually requires a publicly reachable HTTPS URL.
// Private-network or local addresses typically render as blank pages.
if (u.protocol !== 'https:') return false;
const host = u.hostname;
if (
host === 'localhost' ||
host === '127.0.0.1' ||
host === '::1' ||
/^10\./.test(host) ||
/^192\.168\./.test(host) ||
/^172\.(1[6-9]|2\d|3[0-1])\./.test(host)
) {
return false;
}
return true;
} catch {
return false;
}
});
const needsOfficeFallback = computed(
() => ['ppt', 'pptx'].includes(ext.value) && !canUseOfficeOnlineViewer.value
);
const previewRawUrl = computed(() => {
if (!props.file?.url || !props.agentId) return '';
const params = new URLSearchParams({
agent_id: String(props.agentId),
url: props.file.url,
name: props.file.name || '',
});
return `/api/chat/preview-file-raw?${params.toString()}`;
const needsOfficeFallback = computed(() => {
// We no longer need fallback for doc/ppt/pptx because they are converted to PDF by the backend
return false;
});
/**
@@ -135,16 +94,11 @@ const previewRawUrl = computed(() => {
*/
const iframeSrc = computed(() => {
if (!props.file?.url || !props.agentId) return '';
if (ext.value === 'pdf') {
// PDF must use authenticated fetched blob URL; do not fallback to raw URL.
if (['pdf', 'doc', 'ppt', 'pptx'].includes(ext.value)) {
// These formats must use the authenticated fetch -> blob flow only.
// Never fallback to a protected iframe URL, otherwise it returns Unauthorized.
return officeObjectUrl.value;
}
if (isOfficeDoc.value && canUseOfficeOnlineViewer.value) {
return `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(previewRawUrl.value)}`;
}
if (['doc', 'docx'].includes(ext.value)) {
return previewRawUrl.value;
}
return props.file.url;
});
@@ -244,13 +198,18 @@ const loadPdfContent = async () => {
}
const buf = await res.arrayBuffer();
const head = new TextDecoder().decode(buf.slice(0, 5));
if (head !== '%PDF-') {
throw new Error('Invalid PDF binary from preview API');
}
// const head = new TextDecoder().decode(buf.slice(0, 5));
// 暂时取消对 PDF header 的强校验,因为 docx 等文件也会调用该函数生成 Blob 并渲染在 iframe 或下载中
// if (head !== '%PDF-') {
// throw new Error('Invalid PDF binary from preview API');
// }
clearOfficeObjectUrl();
const blob = new Blob([buf], { type: 'application/pdf' });
let type = 'application/octet-stream';
if (ext.value === 'pdf' || ['doc', 'ppt', 'pptx'].includes(ext.value)) type = 'application/pdf';
else if (ext.value === 'docx') type = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
const blob = new Blob([buf], { type });
officeObjectUrl.value = URL.createObjectURL(blob);
};
@@ -272,13 +231,17 @@ const loadContent = async () => {
if (!props.file?.url) return;
resolvedMode.value = preferredMode.value;
if (ext.value === 'pdf') {
if (['pdf', 'doc', 'docx', 'ppt', 'pptx'].includes(ext.value) && preferredMode.value === 'iframe') {
if (needsOfficeFallback.value) {
resolvedMode.value = 'iframe';
return;
}
isLoading.value = true;
try {
await loadPdfContent();
await loadPdfContent(); // This fetches as Blob, and sets officeObjectUrl which will be used in iframeSrc
resolvedMode.value = 'iframe';
} catch (e: any) {
error.value = e?.message || 'Failed to preview pdf';
error.value = e?.message || `Failed to preview ${ext.value}`;
resolvedMode.value = 'iframe';
} finally {
isLoading.value = false;
@@ -286,7 +249,7 @@ const loadContent = async () => {
return;
}
if (preferredMode.value === 'office') {
if (preferredMode.value === 'office' && !needsOfficeFallback.value) {
isLoading.value = true;
try {
await loadOfficeContent();
@@ -469,14 +432,14 @@ watch(
<img :src="file.url" :alt="file.name" class="max-w-full max-h-full object-contain" />
</div>
<div
v-else-if="ext === 'pdf' && officeObjectUrl"
v-else-if="['pdf', 'doc', 'ppt', 'pptx'].includes(ext) && officeObjectUrl"
class="h-full rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 overflow-hidden"
>
<embed
<iframe
:src="officeObjectUrl"
type="application/pdf"
class="w-full h-full min-h-[480px]"
/>
class="w-full h-full min-h-[480px] border-0"
allow="clipboard-read; clipboard-write"
></iframe>
</div>
<div
v-else-if="needsOfficeFallback"
@@ -489,20 +452,18 @@ watch(
This Office file uses a private or non-HTTPS link, so online preview cannot render it.
</div>
<div class="mt-4 flex gap-3">
<a
:href="previewRawUrl || file.url"
target="_blank"
class="px-3 py-2 rounded-lg bg-brand-600 text-white text-sm hover:bg-brand-700"
<button
type="button"
@click="downloadFile"
:disabled="isDownloading"
class="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center"
>
Open in new tab
</a>
<a
:href="previewRawUrl || file.url"
download
class="px-3 py-2 rounded-lg border border-slate-300 dark:border-slate-600 text-sm text-slate-700 dark:text-slate-200 hover:bg-slate-50 dark:hover:bg-slate-800"
>
Download file
</a>
<svg v-if="isDownloading" class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{{ isDownloading ? '下载中...' : '下载文件' }}
</button>
</div>
</div>
<iframe
+250 -230
View File
@@ -10,21 +10,36 @@
* - 支持从首页携带预设问题快速发起对话
* - 在回答结束后允许用户对本次回答进行评分与意见反馈
*/
import { ref, onMounted, computed } from 'vue';
import { ref, onMounted, onBeforeUnmount, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useChat } from '../composables/useChat';
import { Send, Bot, Loader2, ArrowLeft, Plus, Menu, Star, Copy, Edit2, RotateCw, Check, X, Trash2 } from 'lucide-vue-next';
import { Send, Bot, Loader2, Plus, Copy, Edit2, RotateCw, Check, X, PanelLeftClose, PanelLeftOpen, Heart, Bell, Mail, Settings, Crown, ChevronDown, Sparkles, User, Database, Mic, LogOut, MessageSquareText } from 'lucide-vue-next';
import { marked } from 'marked';
import { useRoute, useRouter } from 'vue-router';
import { config } from '../config';
import FilePreviewModal from '../components/FilePreviewModal.vue';
import ThemeToggleButton from '../components/ThemeToggleButton.vue';
import GeneralFeedbackDialog from '../components/GeneralFeedbackDialog.vue';
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
import { getAuthHeaders } from '../utils/auth';
import { getAuthHeaders, getStoredAuthUser, clearAuthUser } from '../utils/auth';
const { t, locale } = useI18n();
const { t } = useI18n();
const { showMessageDialog } = useGlobalMessageDialog();
const currentUser = ref(getStoredAuthUser());
const showUserDropdown = ref(false);
const userMenuRef = ref<HTMLElement | null>(null);
const handleDocumentPointerDown = (event: MouseEvent | TouchEvent) => {
if (!showUserDropdown.value) return;
const target = event.target as Node | null;
if (!target) return;
if (userMenuRef.value?.contains(target)) return;
showUserDropdown.value = false;
};
const handleLogout = () => {
clearAuthUser();
router.push('/');
};
const stripReasoningPrelude = (text: string) => {
if (!text) return '';
@@ -373,6 +388,7 @@ const agentId = Number(route.params.agentId);
// Sidebar state for mobile
const isSidebarOpen = ref(false);
const isSidebarCollapsed = ref(false);
const copiedIndex = ref<number | null>(null);
// 从 useChat 中解构出消息列表、思考状态、会话 ID 与发送函数
@@ -380,7 +396,20 @@ const { messages, isThinking, conversationId, sendMessage } = useChat();
const input = ref('');
const currentAgent = ref<any>(null);
const showGeneralFeedbackDialog = ref(false);
const activeFeedbackMessageIndex = ref<number | null>(null);
const handleOpenFeedback = (index: number) => {
activeFeedbackMessageIndex.value = index;
showGeneralFeedbackDialog.value = true;
};
const currentGeneralFeedbackChatLogId = computed(() => {
if (activeFeedbackMessageIndex.value !== null) {
const msg = messages.value[activeFeedbackMessageIndex.value];
const id = Number(msg?.chat_log_id);
if (Number.isInteger(id) && id > 0) return id;
}
for (let i = messages.value.length - 1; i >= 0; i--) {
const msg: any = messages.value[i];
if (msg?.role === 'assistant') {
@@ -507,9 +536,6 @@ const loadConversation = async (id: string) => {
conversationId.value = id;
// Reset feedback state
rating.value = null;
feedbackComment.value = '';
feedbackSubmitted.value = false;
}
} catch (e) {
console.error('Failed to load conversation', e);
@@ -519,9 +545,6 @@ const loadConversation = async (id: string) => {
const startNewChat = () => {
messages.value = [];
conversationId.value = null;
rating.value = null;
feedbackComment.value = '';
feedbackSubmitted.value = false;
};
const loadAgent = async () => {
@@ -532,7 +555,7 @@ const loadAgent = async () => {
} else {
if (res.status === 403) {
showMessageDialog('error', t('workspace.permission.denied') || 'Access denied');
router.push('/');
router.push('/workspace?no_redirect=1');
return;
}
currentAgent.value = { name: t('workspace.unknownAgent') };
@@ -544,6 +567,8 @@ const loadAgent = async () => {
// 组件挂载时,如果存在预设问题,则自动触发一次发送
onMounted(async () => {
document.addEventListener('mousedown', handleDocumentPointerDown);
document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true });
await loadAgent();
await loadHistory();
@@ -553,55 +578,23 @@ onMounted(async () => {
handleSend();
}
// Use config from config.ts instead of API
showChatRating.value = config.workspace.showChatRating;
showChatRating.value = config.workspace?.showChatRating ?? true;
});
onBeforeUnmount(() => {
document.removeEventListener('mousedown', handleDocumentPointerDown);
document.removeEventListener('touchstart', handleDocumentPointerDown);
});
/**
* 反馈相关状态
* showChatRating:是否启用评分功能(后续可接入配置)
* rating:用户选择的评分(1-5)
* feedbackComment:用户输入的文字意见
* feedbackSubmitted:是否已经提交反馈
*/
const showChatRating = ref(false);
const rating = ref<number | null>(null);
const feedbackComment = ref('');
const feedbackSubmitted = ref(false);
/**
* submitFeedback
* 用途:将评分与评论提交到后端 /api/chat/feedback
*/
const submitFeedback = async () => {
if (!showChatRating.value || feedbackSubmitted.value) return;
if (!rating.value) {
showMessageDialog('warning', t('chat.feedback.selectRating'));
return;
}
const res = await fetch('/api/chat/feedback', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
agent_id: agentId,
score: rating.value,
comment: feedbackComment.value,
conversation_id: conversationId.value,
}),
});
if (res.ok) {
feedbackSubmitted.value = true;
}
};
</script>
<template>
<div class="relative flex h-screen overflow-hidden bg-slate-50 text-slate-800 dark:bg-slate-950 dark:text-slate-100">
<div class="pointer-events-none absolute inset-0">
<div class="absolute -top-24 -left-20 h-80 w-80 rounded-full bg-cyan-300/30 blur-3xl dark:bg-cyan-500/18"></div>
<div class="absolute right-0 top-20 h-72 w-72 rounded-full bg-blue-300/25 blur-3xl dark:bg-indigo-500/20"></div>
<div class="absolute bottom-0 left-1/3 h-64 w-64 rounded-full bg-sky-200/25 blur-3xl dark:bg-blue-600/18"></div>
</div>
<div
v-if="isSidebarOpen"
class="fixed inset-0 z-40 bg-slate-900/55 backdrop-blur-sm transition-opacity md:hidden"
@@ -609,102 +602,143 @@ const submitFeedback = async () => {
></div>
<aside
class="glass-panel fixed inset-y-0 left-0 z-50 flex w-[86vw] max-w-[300px] flex-col border-r transition-transform duration-300 ease-in-out md:relative md:w-80 md:max-w-none md:translate-x-0"
:class="isSidebarOpen ? 'translate-x-0' : '-translate-x-full'"
class="glass-panel fixed inset-y-0 left-0 z-50 flex h-full flex-col border-r bg-white transition-all duration-300 ease-in-out dark:bg-slate-950 md:relative md:translate-x-0"
:class="[
isSidebarOpen ? 'translate-x-0 w-[86vw] max-w-[300px]' : '-translate-x-full w-[86vw] max-w-[300px]',
isSidebarCollapsed ? 'md:w-[72px]' : 'md:w-80'
]"
>
<div class="border-b border-slate-200/70 p-3 dark:border-slate-700/70 md:p-4">
<div class="flex items-center justify-between">
<button @click="router.push('/workspace')" class="rounded-xl p-2 text-slate-500 transition-all hover:bg-white/80 hover:text-slate-900 dark:text-slate-300 dark:hover:bg-slate-800/80 dark:hover:text-slate-100" title="Back to Workspace">
<ArrowLeft class="h-5 w-5" />
<template v-if="isSidebarCollapsed">
<div class="flex h-full w-full flex-col items-center py-4">
<button @click="isSidebarCollapsed = false" class="mb-6 text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200">
<PanelLeftOpen class="h-5 w-5" />
</button>
<span class="text-sm font-semibold uppercase tracking-[0.14em] text-slate-500 dark:text-slate-300">{{ $t('chat.history') }}</span>
<ThemeToggleButton />
</div>
<div class="mt-3 flex items-center gap-2 md:mt-4">
<button @click="startNewChat(); isSidebarOpen = false;" class="flex-1 inline-flex items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-cyan-500 to-blue-500 px-4 py-2.5 text-sm font-semibold text-white shadow-sm shadow-cyan-500/20 transition-all hover:from-cyan-400 hover:to-blue-400 hover:shadow-md hover:shadow-cyan-500/25 md:py-3">
<Plus class="h-4 w-4" /> {{ $t('chat.newChat') }}
</button>
<button v-if="history.length > 0" @click="clearAllHistory" class="inline-flex items-center justify-center gap-1 rounded-xl border border-red-200 bg-red-50 px-2 py-2.5 text-xs font-semibold text-red-600 transition-all hover:bg-red-100 hover:text-red-700 dark:border-red-900/30 dark:bg-red-900/20 dark:text-red-400 dark:hover:bg-red-900/40 md:px-3 md:py-3" title="全部清除">
<Trash2 class="h-4 w-4" /> <span class="hidden md:inline">全部清除</span>
</button>
</div>
</div>
<div class="mb-4 flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-purple-500 to-indigo-500 text-white shadow-sm">
<Sparkles class="h-5 w-5" />
</div>
<div class="flex-1 overflow-y-auto px-2.5 py-2.5 scrollbar-thin md:px-3 md:py-3">
<div v-if="history.length === 0" class="py-8 text-center text-sm italic text-slate-400 md:py-10">{{ $t('chat.noHistory') }}</div>
<div v-else class="divide-y divide-slate-200/70 dark:divide-slate-700/70">
<div
v-for="item in history"
:key="item.conversation_id"
class="group relative flex w-full items-center justify-between transition-colors"
:class="conversationId === item.conversation_id ? 'bg-slate-100/50 dark:bg-slate-800/30' : 'hover:bg-slate-100/70 dark:hover:bg-slate-800/60'"
>
<button
class="flex-1 truncate px-2 py-3 text-left text-sm md:px-3 pr-8"
:class="conversationId === item.conversation_id
? 'font-semibold text-cyan-700 dark:text-cyan-200'
: 'text-slate-600 hover:text-slate-900 dark:text-slate-300 dark:hover:text-slate-100'"
@click="loadConversation(item.conversation_id); isSidebarOpen = false;"
>
{{ item.title || $t('chat.newChat') }}
</button>
<button
@click="deleteHistoryItem(item.conversation_id, $event)"
class="absolute right-2 p-1.5 text-slate-400 opacity-0 transition-opacity hover:text-red-500 group-hover:opacity-100 dark:hover:text-red-400"
title="清除该记录"
>
<X class="h-4 w-4" />
</button>
<button @click="startNewChat(); isSidebarOpen = false;" class="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-slate-50 text-slate-700 shadow-sm transition-colors hover:bg-slate-100 dark:bg-slate-800 dark:text-slate-200 dark:hover:bg-slate-700" title="创建新对话">
<Plus class="h-5 w-5" />
</button>
<div class="mt-auto flex flex-col items-center gap-6 pb-2 text-slate-400">
<button class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Sparkles class="h-5 w-5" /></button>
<div class="flex h-8 w-8 items-center justify-center rounded-full bg-purple-600 text-sm font-bold text-white shadow-sm">
{{ (currentUser?.username || 'I').charAt(0).toUpperCase() }}
</div>
<button @click="showGeneralFeedbackDialog = true" class="transition-colors hover:text-slate-600 dark:hover:text-slate-200" title="意见反馈"><Mail class="h-5 w-5" /></button>
<button @click="router.push('/workspace?no_redirect=1')" class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Settings class="h-5 w-5" /></button>
</div>
</div>
</div>
</template>
<div class="space-y-2.5 border-t border-slate-200/70 bg-white/35 p-3 dark:border-slate-700/70 dark:bg-slate-900/35 md:space-y-3 md:p-4">
<select
v-model="locale"
class="w-full rounded-xl border border-slate-200 bg-white/90 px-3 py-1.5 text-sm shadow-sm outline-none transition-all focus:border-cyan-500 focus:ring-2 focus:ring-cyan-500/20 dark:border-slate-700 dark:bg-slate-900/80 md:py-2"
>
<option value="en">English</option>
<option value="zh-CN">简体中文</option>
<option value="zh-TW">繁體中文</option>
<option value="th">ไทย</option>
</select>
</div>
<template v-else>
<div class="flex items-center justify-between p-4">
<div class="flex items-center gap-2">
<div class="flex h-8 w-8 items-center justify-center rounded bg-gradient-to-br from-purple-500 to-indigo-500 text-sm font-bold text-white shadow-sm">AI</div>
<span class="font-bold text-slate-800 dark:text-slate-100">Hxops Alagent</span>
</div>
<button @click="isSidebarCollapsed = true" class="text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200">
<PanelLeftClose class="h-5 w-5" />
</button>
</div>
<div class="px-4 pb-4">
<button @click="startNewChat(); isSidebarOpen = false;" class="flex w-full items-center justify-center gap-2 rounded-xl border border-slate-200 bg-slate-50 py-3 text-sm font-medium text-slate-700 shadow-sm transition-colors hover:bg-slate-100 dark:border-slate-700 dark:bg-slate-800 dark:text-slate-200 dark:hover:bg-slate-700">
<Plus class="h-4 w-4" /> 创建新对话
</button>
</div>
<div class="flex items-center justify-between px-4 py-2">
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">聊天记录</span>
<button v-if="history.length > 0" @click="clearAllHistory" class="text-xs text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200">
清空全部
</button>
</div>
<div class="flex-1 overflow-y-auto px-2 scrollbar-thin">
<div v-if="history.length === 0" class="py-8 text-center text-sm italic text-slate-400">{{ $t('chat.noHistory') }}</div>
<div v-else class="space-y-0.5">
<div
v-for="item in history"
:key="item.conversation_id"
class="group relative flex w-full items-center justify-between rounded-lg transition-colors"
:class="conversationId === item.conversation_id ? 'bg-blue-50 dark:bg-blue-900/20' : 'hover:bg-slate-50 dark:hover:bg-slate-800/50'"
>
<button
class="flex-1 truncate px-3 py-2.5 text-left text-sm pr-8"
:class="conversationId === item.conversation_id
? 'font-medium text-blue-600 dark:text-blue-400'
: 'text-slate-600 dark:text-slate-300'"
@click="loadConversation(item.conversation_id); isSidebarOpen = false;"
>
{{ item.title || $t('chat.newChat') }}
</button>
<button
@click="deleteHistoryItem(item.conversation_id, $event)"
class="absolute right-2 p-1.5 text-slate-400 opacity-0 transition-opacity hover:text-red-500 group-hover:opacity-100 dark:hover:text-red-400"
title="清除该记录"
>
<X class="h-4 w-4" />
</button>
</div>
</div>
</div>
<div class="mt-auto flex flex-col p-4">
<!-- Ad Card -->
<div class="mb-4 rounded-2xl bg-purple-50 p-4 dark:bg-purple-900/20">
<div class="mb-2 flex items-center gap-1 font-bold text-purple-700 dark:text-purple-400">
<Crown class="h-4 w-4" /> 专业版
</div>
<ul class="mb-3 space-y-1 text-[11px] text-slate-600 dark:text-slate-300">
<li class="flex items-center gap-1.5"><div class="h-1 w-1 rounded-full bg-purple-400"></div> 统一Agent知识库入口</li>
<li class="flex items-center gap-1.5"><div class="h-1 w-1 rounded-full bg-purple-400"></div> 优化Chat界面及交互</li>
<li class="flex items-center gap-1.5"><div class="h-1 w-1 rounded-full bg-purple-400"></div> 修改文档预览bug等</li>
</ul>
<button class="w-full rounded-xl bg-slate-900 py-2 text-xs font-medium text-white shadow-md transition-colors hover:bg-slate-800 dark:bg-white dark:text-slate-900 dark:hover:bg-slate-200">
🚀 升级说明
</button>
</div>
<!-- Bottom Icons -->
<div class="flex items-center justify-between text-slate-400 relative" ref="userMenuRef">
<button @click="showUserDropdown = !showUserDropdown" class="flex h-8 w-8 items-center justify-center rounded-full bg-purple-600 text-sm font-bold text-white shadow-sm hover:bg-purple-700 transition-colors">
{{ (currentUser?.username || 'I').charAt(0).toUpperCase() }}
</button>
<!-- User Dropdown Menu -->
<div v-if="showUserDropdown" class="absolute bottom-full left-0 mb-2 w-56 bg-white dark:bg-slate-900 rounded-xl shadow-xl border border-slate-100 dark:border-slate-700 py-1 z-50 animate-fade-in">
<div class="px-4 py-3 border-b border-slate-50 dark:border-slate-700 flex items-center gap-3">
<div class="w-10 h-10 bg-purple-600 rounded-full flex items-center justify-center text-white font-bold text-lg shrink-0 shadow-sm">
{{ (currentUser?.username || 'U').charAt(0).toUpperCase() }}
</div>
<div class="overflow-hidden">
<div class="text-sm font-bold text-slate-900 dark:text-slate-100 truncate">{{ currentUser?.username || 'User' }}</div>
<div v-if="(currentUser as any)?.employee_id" class="text-xs text-slate-500 dark:text-slate-400 truncate">工号: {{ (currentUser as any).employee_id }}</div>
<div v-else class="text-xs text-slate-500 dark:text-slate-400 truncate">{{ currentUser?.role }}</div>
</div>
</div>
<button @click="handleLogout" class="w-full text-left px-4 py-2 text-sm text-red-600 hover:bg-red-50 flex items-center gap-2 transition-colors mt-1">
<LogOut class="w-4 h-4" />
退出登录
</button>
</div>
<div class="flex gap-3">
<button class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Heart class="h-4 w-4" /></button>
<button class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Bell class="h-4 w-4" /></button>
<button @click="showGeneralFeedbackDialog = true" class="transition-colors hover:text-slate-600 dark:hover:text-slate-200" title="意见反馈"><Mail class="h-4 w-4" /></button>
<button @click="router.push('/workspace?no_redirect=1')" class="transition-colors hover:text-slate-600 dark:hover:text-slate-200"><Settings class="h-4 w-4" /></button>
</div>
</div>
</div>
</template>
</aside>
<div class="relative z-10 flex h-full w-full flex-1 flex-col overflow-hidden">
<header class="sticky top-0 z-30 flex shrink-0 items-center justify-between border-b border-slate-200/70 bg-white/70 pl-1 pr-2 py-3 backdrop-blur-xl dark:border-slate-700/70 dark:bg-slate-950/65 md:px-6">
<div class="flex min-w-0 items-center gap-1">
<div class="mr-1 flex items-center gap-0 md:mr-0">
<button @click="router.push('/workspace')" class="rounded-lg p-1.5 transition-colors hover:bg-slate-100 dark:hover:bg-slate-800 md:hidden">
<ArrowLeft class="h-5 w-5 text-slate-600 dark:text-slate-300" />
</button>
<button @click="isSidebarOpen = !isSidebarOpen" class="rounded-lg p-1.5 transition-colors hover:bg-slate-100 dark:hover:bg-slate-800 md:hidden">
<Menu class="h-5 w-5 text-slate-600 dark:text-slate-300" />
</button>
</div>
<button @click="router.push('/workspace')" class="hidden rounded-lg p-2 transition-colors hover:bg-slate-100 dark:hover:bg-slate-800 md:inline-flex">
<ArrowLeft class="h-5 w-5 text-slate-600 dark:text-slate-300" />
</button>
<div class="min-w-0">
<p class="font-semibold tracking-tight text-slate-900 dark:text-slate-100">{{ currentAgent?.name || $t('chat.defaultTitle') }}</p>
<p class="text-xs text-slate-500 dark:text-slate-400">{{ $t('chat.assistantLabel') }}</p>
</div>
</div>
<div class="ml-3 flex shrink-0 items-center gap-2">
<button @click="startNewChat" class="inline-flex items-center gap-1 rounded-xl border border-slate-200 bg-white/80 px-2 py-1.5 text-[11px] font-semibold text-slate-600 transition-colors hover:border-cyan-300 hover:text-cyan-700 dark:border-slate-700 dark:bg-slate-900/70 dark:text-slate-200 dark:hover:border-cyan-500/40 dark:hover:text-cyan-200 md:px-3 md:py-2 md:text-xs">
<Plus class="h-4 w-4" />
{{ $t('chat.newChat') }}
</button>
<button
@click="showGeneralFeedbackDialog = true"
class="inline-flex items-center gap-1 rounded-xl border border-[#8cbce8] bg-[#eef6ff] px-2 py-1.5 text-[11px] font-semibold text-[#2f73b2] transition-colors hover:bg-[#e3f1ff] md:px-3 md:py-2 md:text-xs"
>
{{ '\u610f\u89c1\u53cd\u9988' }}
</button>
<ThemeToggleButton />
</div>
</header>
<div class="relative z-10 flex h-full w-full flex-1 flex-col overflow-hidden bg-white dark:bg-slate-950">
<div v-if="!currentAgent" class="flex flex-1 flex-col items-center justify-center space-y-4">
<Loader2 class="h-10 w-10 animate-spin text-cyan-500" />
@@ -724,52 +758,45 @@ const submitFeedback = async () => {
class="flex-1 p-3 md:p-8"
:class="messages.length === 0 ? 'overflow-hidden md:overflow-y-auto' : 'space-y-2 overflow-y-auto scrollbar-thin md:space-y-6'"
>
<div v-if="messages.length === 0" class="flex h-full flex-col items-center justify-center py-2 text-slate-400 md:pb-16">
<h2 class="mb-2 text-center text-lg font-semibold tracking-tight text-slate-700 dark:text-slate-200 md:text-3xl md:font-bold md:text-slate-900 md:dark:text-slate-100">{{ $t('chat.welcome.title') }}</h2>
<p class="max-w-xl text-center text-sm leading-relaxed text-slate-500 dark:text-slate-300 md:text-base">{{ $t('chat.welcome.subtitle') }}</p>
<div class="mt-5 hidden w-full max-w-md grid-cols-1 justify-items-center gap-3 md:mt-10 md:grid md:max-w-3xl md:gap-4 md:grid-cols-2 md:justify-items-stretch">
<button v-for="suggestion in (currentAgent.suggested_questions && currentAgent.suggested_questions.length > 0 ? currentAgent.suggested_questions : [
$t('chat.suggestions.whatCanYouDo'),
$t('chat.suggestions.helpWriteReport'),
$t('chat.suggestions.analyzeData'),
$t('chat.suggestions.creativeWriting')
])"
:key="suggestion"
@click="input = suggestion; handleSend()"
class="w-full max-w-[320px] rounded-xl border border-slate-200 bg-white/90 px-4 py-3 text-left text-sm font-semibold text-slate-600 shadow-sm transition-all hover:-translate-y-0.5 hover:border-cyan-300 hover:text-cyan-700 hover:shadow-lg dark:border-slate-700 dark:bg-slate-900/70 dark:text-slate-200 dark:hover:border-cyan-500/40 dark:hover:text-cyan-200 md:max-w-none"
>
{{ suggestion }}
</button>
<div v-if="messages.length === 0" class="flex h-full flex-col items-center justify-center py-2 md:pb-16">
<div class="mb-6 flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-purple-400 to-indigo-500 text-2xl font-bold text-white shadow-lg shadow-purple-500/20">
AI
</div>
<h2 class="text-center text-xl font-medium text-slate-800 dark:text-slate-100 md:text-2xl">我今天可以怎么帮助你?</h2>
</div>
<template v-for="(msg, index) in messages" :key="index">
<div
v-if="shouldRenderMessage(msg)"
class="group mx-auto flex max-w-5xl gap-0 animate-slide-up"
:class="msg.role === 'user' ? 'justify-end' : ''"
>
<div
class="flex flex-col"
:class="msg.role === 'user' ? 'max-w-[88%] md:max-w-[74%]' : 'w-full'"
v-if="shouldRenderMessage(msg)"
class="group mx-auto flex max-w-4xl gap-4 animate-slide-up mb-6"
:class="msg.role === 'user' ? 'justify-end' : 'justify-start'"
>
<div
class="text-[15px] leading-relaxed shadow-md"
:class="msg.role === 'user'
? 'rounded-xl rounded-tr-md bg-gradient-to-r from-cyan-500 to-blue-500 px-5 py-2.5 text-white shadow-sm shadow-cyan-500/20'
: 'rounded-2xl rounded-tl-md border border-slate-200 bg-white/95 px-6 py-4 text-slate-800 shadow-slate-300/30 dark:border-slate-700 dark:bg-slate-900/85 dark:text-slate-100'"
<!-- AI Avatar -->
<div v-if="msg.role === 'assistant'" class="mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-purple-400 to-indigo-500 text-white shadow-sm">
<Sparkles class="h-4 w-4" />
</div>
<div
class="flex flex-col"
:class="msg.role === 'user' ? 'max-w-[88%] md:max-w-[74%] items-end' : 'w-full'"
>
<div
v-if="msg.role === 'user'"
class="prose prose-sm max-w-none whitespace-pre-wrap text-white prose-invert"
>{{ msg.content }}</div>
<div
v-else
class="prose prose-sm max-w-none leading-7 text-slate-800 dark:text-slate-100 prose-a:text-cyan-600 dark:prose-a:text-cyan-300 prose-p:my-1 prose-li:my-0.5 prose-ol:my-2 prose-ul:my-2 prose-headings:my-2 prose-hr:my-3 prose-code:rounded prose-code:bg-slate-100 prose-code:px-1 prose-code:text-cyan-700 dark:prose-code:bg-slate-800 dark:prose-code:text-cyan-300 prose-pre:my-3 prose-pre:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100"
v-html="renderMarkdown(msg.content)"
></div>
</div>
class="text-[15px] leading-relaxed"
:class="msg.role === 'user'
? 'rounded-2xl rounded-tr-sm bg-[#165DFF] px-5 py-2.5 text-white shadow-sm'
: 'w-full rounded-2xl border border-slate-100 bg-white px-6 py-4 shadow-sm dark:border-slate-800 dark:bg-slate-900 dark:text-slate-100'"
>
<div
v-if="msg.role === 'user'"
class="whitespace-pre-wrap"
>{{ msg.content }}</div>
<div v-else>
<div
class="prose prose-sm max-w-none leading-7 text-slate-800 dark:text-slate-100 prose-a:text-blue-600 dark:prose-a:text-blue-400 prose-p:my-1 prose-li:my-0.5 prose-ol:my-2 prose-ul:my-2 prose-headings:my-2 prose-hr:my-3 prose-code:rounded prose-code:bg-slate-100 prose-code:px-1 prose-code:text-blue-700 dark:prose-code:bg-slate-800 dark:prose-code:text-blue-300 prose-pre:my-3 prose-pre:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100"
v-html="renderMarkdown(msg.content)"
></div>
</div>
</div>
<div
v-if=" msg.role === 'assistant' && ((getDisplayRetrieverResources(msg).length > 0) || (msg.attribution_parts && msg.attribution_parts.length > 0) || getMessageLinks(msg).length > 0)"
@@ -867,10 +894,23 @@ const submitFeedback = async () => {
>
<RotateCw class="h-3.5 w-3.5" />
</button>
<button
v-if="showChatRating && !isThinking && !(msg as any).rated"
@click="handleOpenFeedback(index)"
class="rounded-md p-1.5 text-xs transition-colors hover:bg-slate-100 dark:hover:bg-slate-800"
title="评价回答"
>
<MessageSquareText class="h-3.5 w-3.5" />
</button>
</template>
</div>
</div>
<!-- User Avatar -->
<div v-if="msg.role === 'user'" class="mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-purple-600 text-white shadow-sm">
<User class="h-4 w-4" />
</div>
</div>
</template>
@@ -887,72 +927,46 @@ const submitFeedback = async () => {
<span class="text-sm font-medium text-slate-500 dark:text-slate-300">{{ $t('chat.thinking') }}</span>
</div>
</div>
<div
v-if="showChatRating && messages.length > 0 && !isThinking"
class="mx-auto mt-8 max-w-5xl border-t border-slate-200/80 pt-8 dark:border-slate-700/70"
>
<div class="glass-panel flex flex-col items-center gap-4 rounded-2xl p-6">
<span class="text-sm font-medium text-slate-600 dark:text-slate-300">{{ $t('chat.rate') }}</span>
<div class="flex gap-3">
<button
v-for="n in 5"
:key="n"
class="flex h-10 w-10 items-center justify-center rounded-full border transition-all duration-200"
:class="rating && n <= rating
? 'scale-110 border-yellow-300 bg-yellow-400 text-white shadow-lg shadow-yellow-400/35'
: 'border-slate-200 bg-white text-slate-500 hover:border-yellow-400 hover:text-yellow-500 dark:border-slate-700 dark:bg-slate-900 dark:text-slate-300'"
@click="rating = n"
>
<Star v-if="rating && n <= rating" class="h-5 w-5 fill-current" />
<span v-else class="text-sm font-bold">{{ n }}</span>
</button>
</div>
<div v-if="rating" class="mt-2 flex w-full max-w-lg gap-3 animate-fade-in">
<input
v-model="feedbackComment"
type="text"
class="input-field flex-1 py-2 text-sm"
:placeholder="$t('chat.feedback.commentPlaceholder')"
/>
<button
class="rounded-xl bg-gradient-to-r from-cyan-600 to-blue-600 px-6 py-2 text-sm font-bold text-white shadow-lg shadow-cyan-500/35 transition-opacity hover:opacity-90 disabled:opacity-50"
:disabled="feedbackSubmitted"
@click="submitFeedback"
>
{{ feedbackSubmitted ? $t('chat.feedback.sent') : $t('chat.send') }}
</button>
</div>
</div>
</div>
<div v-if="messages.length > 0" class="h-6 md:h-8"></div>
</main>
<footer class="safe-bottom sticky bottom-0 z-20 border-t border-slate-200/80 bg-white/70 p-3 backdrop-blur-xl dark:border-slate-700/70 dark:bg-slate-950/65 md:p-6">
<div class="relative mx-auto max-w-5xl">
<div class="chat-composer-shell relative overflow-hidden rounded-2xl border border-slate-200 bg-white/95 shadow-xl shadow-slate-300/25 transition-all duration-300 focus-within:border-cyan-500 dark:border-slate-700 dark:bg-slate-900/88 dark:shadow-none">
<footer class="safe-bottom sticky bottom-0 z-20 bg-transparent p-3 md:p-6">
<div class="relative mx-auto max-w-4xl">
<div class="flex flex-col rounded-2xl bg-white p-2 shadow-[0_0_15px_rgba(0,0,0,0.05)] transition-all dark:bg-slate-900">
<textarea
v-model="input"
@keydown.enter.prevent="handleSend"
rows="1"
:placeholder="$t('chat.placeholder')"
class="chat-composer-textarea w-full resize-none bg-transparent py-4 pl-5 pr-14 text-[15px] leading-relaxed text-slate-800 placeholder-slate-400 focus:outline-none dark:text-slate-100 dark:placeholder-slate-500"
style="min-height: 56px; max-height: 220px;"
placeholder="问我任何事..."
class="w-full resize-none border-none bg-transparent px-3 py-2 text-[15px] leading-relaxed text-slate-800 placeholder-slate-400 focus:outline-none focus:ring-0 focus:border-transparent dark:text-slate-100"
style="min-height: 44px; max-height: 220px;"
:disabled="isThinking"
spellcheck="false"
autocorrect="off"
autocapitalize="off"
></textarea>
<button
@click="handleSend"
:disabled="!input.trim() || isThinking"
class="absolute bottom-2 right-2 rounded-xl bg-gradient-to-r from-cyan-600 to-blue-600 p-2.5 text-white shadow-lg shadow-cyan-500/30 transition-all hover:opacity-90 disabled:cursor-not-allowed disabled:opacity-50 active:scale-95"
>
<Send class="h-5 w-5" />
</button>
<div class="mt-2 flex items-center justify-between px-2 pb-1">
<div class="flex items-center gap-3">
<button class="text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200">
<Mic class="h-5 w-5" />
</button>
<button class="flex items-center gap-1 rounded-lg border border-slate-200 px-3 py-1.5 text-xs font-medium text-slate-600 transition-colors hover:bg-slate-50 dark:border-slate-700 dark:text-slate-300 dark:hover:bg-slate-800">
<Database class="h-3.5 w-3.5 text-blue-500" />
企业知识库 <ChevronDown class="h-3 w-3" />
</button>
</div>
<button
@click="handleSend"
:disabled="!input.trim() || isThinking"
class="flex h-8 w-8 items-center justify-center rounded-full bg-slate-100 text-slate-400 transition-colors hover:bg-slate-200 hover:text-slate-600 disabled:opacity-50 dark:bg-slate-800 dark:hover:bg-slate-700"
>
<Send class="h-4 w-4" />
</button>
</div>
</div>
<div class="mt-3 text-center text-xs font-medium text-slate-500 dark:text-slate-400">
{{ $t('chat.disclaimer') }}
<div class="mt-3 text-center text-[11px] text-slate-400">
AI 可能会犯错,请核实重要信息。
</div>
</div>
</footer>
@@ -971,6 +985,12 @@ const submitFeedback = async () => {
:auth-headers="getAuthHeaders()"
source-page="chat"
:chat-log-id="currentGeneralFeedbackChatLogId"
@submitted="showMessageDialog('success', '\u53cd\u9988\u63d0\u4ea4\u6210\u529f')"
@submitted="() => {
if (activeFeedbackMessageIndex !== null && messages[activeFeedbackMessageIndex]) {
(messages[activeFeedbackMessageIndex] as any).rated = true;
}
showMessageDialog('success', '\u53cd\u9988\u63d0\u4ea4\u6210\u529f');
showGeneralFeedbackDialog = false;
}"
/>
</template>
+5 -10
View File
@@ -385,6 +385,8 @@ const persistLoginUser = (user: any) => {
saveAuthUser({ ...(user || {}) }, rememberMe.value);
};
const DEFAULT_POST_LOGIN_AGENT_ID = 16;
const handleLogin = async () => {
if (!loginUsername.value.trim()) {
showMessageDialog('warning', t('login.usernameRequired'));
@@ -420,16 +422,9 @@ const handleLogin = async () => {
persistLoginUser(user);
await fetchHome();
if (pendingAgentId.value) {
const targetId = pendingAgentId.value;
pendingAgentId.value = null;
if (agents.value.some(a => a.id === targetId)) {
navigateToChat(targetId);
} else {
showMessageDialog('error', t('workspace.permission.denied'));
}
}
pendingAgentId.value = null;
await router.replace(`/chat/${DEFAULT_POST_LOGIN_AGENT_ID}`);
} catch (e) {
console.error(e);
showMessageDialog('error', t('login.requestFailed'));