Merge remote-tracking branch 'origin/dev' into super

This commit is contained in:
super committed 2026-04-20 09:13:20 +08:00
commit 1d9f854ce4
23 files changed
+1034 -333

No files matched your search

+202 -145
View File
@@ -1,4 +1,4 @@
<script setup lang="ts">
/**
@@ -14,7 +14,9 @@ import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { config } from '../config';
import ThemeToggleButton from '../components/ThemeToggleButton.vue';
import DeleteConfirmDialog from '../components/DeleteConfirmDialog.vue';
import { loadReportLayoutPref, saveReportLayoutPref } from '../composables/useReportLayoutStorage';
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
import { buildWecomAuditMeta, formatWecomAuditReason } from '../utils/wecom';
import {
ArrowLeft,
@@ -45,6 +47,7 @@ import {
import * as XLSX from 'xlsx';
const { t, locale } = useI18n();
const { showMessageDialog } = useGlobalMessageDialog();
const sidebarItems = computed(() => {
const items = [
@@ -300,12 +303,12 @@ const openEditUserModal = (user: UserRow) => {
const saveUser = async () => {
if (!editingUser.value.username) {
alert(t('admin.user.msgs.usernameRequired'));
showMessageDialog('warning', t('admin.user.msgs.usernameRequired'));
return;
}
if (!editingUser.value.id && !editingUser.value.password) {
alert(t('admin.user.msgs.passwordRequired'));
showMessageDialog('warning', t('admin.user.msgs.passwordRequired'));
return;
}
@@ -353,7 +356,7 @@ const saveUser = async () => {
showUserModal.value = false;
} catch (e: any) {
console.error(e);
alert(e.message || t('admin.msg.failed'));
showMessageDialog('error', e.message || t('admin.msg.failed'));
} finally {
isSaving.value = false;
}
@@ -406,6 +409,11 @@ const wecomIntegrationManifest = ref<WecomIntegrationManifest | null>(null);
const selectedUserIds = ref<number[]>([]);
const showBatchEditModal = ref(false);
const showBatchPermissionModal = ref(false);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmTitle = ref('');
const deleteConfirmMessage = ref('');
const deleteConfirmLoading = ref(false);
let pendingDeleteAction: (() => Promise<void> | void) | null = null;
const batchEditForm = ref({
department: '',
@@ -418,6 +426,36 @@ const batchPermissionForm = ref({
action: 'add' as 'add' | 'remove' | 'set'
});
const openDeleteConfirmDialog = (
message: string,
onConfirm: () => Promise<void> | void,
title = ''
) => {
deleteConfirmTitle.value = title;
deleteConfirmMessage.value = message;
pendingDeleteAction = onConfirm;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirmDialog = () => {
showDeleteConfirmDialog.value = false;
deleteConfirmTitle.value = '';
deleteConfirmMessage.value = '';
pendingDeleteAction = null;
deleteConfirmLoading.value = false;
};
const handleDeleteConfirm = async () => {
if (!pendingDeleteAction) return;
deleteConfirmLoading.value = true;
try {
await pendingDeleteAction();
closeDeleteConfirmDialog();
} finally {
deleteConfirmLoading.value = false;
}
};
// Department Management
interface Department {
id: number;
@@ -440,7 +478,7 @@ const loadDepartments = async () => {
};
const saveDepartment = async () => {
if (!editingDept.value.name) return alert(t('admin.dept.msg.nameRequired'));
if (!editingDept.value.name) return showMessageDialog('warning', t('admin.dept.msg.nameRequired'));
try {
if (editingDept.value.id) {
const res = await fetch(`/api/admin/departments/${editingDept.value.id}`, {
@@ -466,7 +504,7 @@ const saveDepartment = async () => {
await loadDepartments();
editingDept.value = {};
} catch (e: any) {
alert(e.message);
showMessageDialog('error', e.message);
}
};
@@ -523,16 +561,17 @@ watch(activeReportTabId, (newId) => {
});
const deleteDepartment = async (id: number) => {
if (!confirm(t('admin.dept.confirmDelete'))) return;
try {
await fetch(`/api/admin/departments/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
await loadDepartments();
} catch (e) {
console.error(e);
}
openDeleteConfirmDialog(t('admin.dept.confirmDelete'), async () => {
try {
await fetch(`/api/admin/departments/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
await loadDepartments();
} catch (e) {
console.error(e);
}
});
};
// User Filters & Actions
@@ -565,47 +604,52 @@ const filteredUsers = computed(() => {
});
const cleanRejectedUsers = async () => {
if (!confirm(t('admin.user.confirmClean'))) return;
try {
const res = await fetch('/api/admin/users/cleanup-rejected', {
method: 'POST',
headers: getAuthHeaders()
});
const data = await res.json();
if (res.ok) {
alert(t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
loadUsers();
} else {
alert(data.error);
openDeleteConfirmDialog(t('admin.user.confirmClean'), async () => {
try {
const res = await fetch('/api/admin/users/cleanup-rejected', {
method: 'POST',
headers: getAuthHeaders()
});
const data = await res.json();
if (res.ok) {
showMessageDialog('success', t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
loadUsers();
} else {
showMessageDialog('error', data.error);
}
} catch (e) {
console.error(e);
showMessageDialog('error', t('admin.msg.requestFailed'));
}
} catch (e) {
console.error(e);
alert(t('admin.msg.requestFailed'));
}
});
};
const batchDeleteUsers = async () => {
if (selectedUserIds.value.length === 0) return;
if (!confirm(t('admin.user.confirmBatchDelete', { count: selectedUserIds.value.length }))) return;
try {
const res = await fetch('/api/admin/users/batch-delete', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ user_ids: selectedUserIds.value })
});
const data = await res.json();
if (res.ok) {
alert(t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
selectedUserIds.value = [];
loadUsers();
} else {
alert(data.error);
const targetUserIds = [...selectedUserIds.value];
openDeleteConfirmDialog(
t('admin.user.confirmBatchDelete', { count: targetUserIds.length }),
async () => {
try {
const res = await fetch('/api/admin/users/batch-delete', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ user_ids: targetUserIds })
});
const data = await res.json();
if (res.ok) {
showMessageDialog('success', t('admin.msg.batchDeleteResult', { count: data.deleted_count }));
selectedUserIds.value = [];
loadUsers();
} else {
showMessageDialog('error', data.error);
}
} catch (e) {
console.error(e);
showMessageDialog('error', t('admin.msg.requestFailed'));
}
}
} catch (e) {
console.error(e);
alert(t('admin.msg.requestFailed'));
}
);
};
const toggleUserSelection = (userId: number) => {
@@ -646,7 +690,7 @@ const submitBatchEdit = async () => {
if (batchEditForm.value.status) data.status = batchEditForm.value.status;
if (Object.keys(data).length === 0) {
alert(t('admin.msg.enterOneField'));
showMessageDialog('warning', t('admin.msg.enterOneField'));
return;
}
@@ -666,7 +710,7 @@ const submitBatchEdit = async () => {
selectedUserIds.value = [];
} catch (e: any) {
console.error(e);
alert(t('admin.msg.batchUpdateFailed'));
showMessageDialog('error', t('admin.msg.batchUpdateFailed'));
} finally {
isSaving.value = false;
}
@@ -674,7 +718,7 @@ const submitBatchEdit = async () => {
const submitBatchPermission = async () => {
if (batchPermissionForm.value.agent_ids.length === 0) {
alert(t('admin.perm.msg.selectAgent'));
showMessageDialog('warning', t('admin.perm.msg.selectAgent'));
return;
}
@@ -697,7 +741,7 @@ const submitBatchPermission = async () => {
selectedUserIds.value = [];
} catch (e: any) {
console.error(e);
alert(t('admin.msg.batchPermissionUpdateFailed'));
showMessageDialog('error', t('admin.msg.batchPermissionUpdateFailed'));
} finally {
isSaving.value = false;
}
@@ -1043,7 +1087,7 @@ const refreshWecomData = async () => {
const bindWecomUser = async () => {
if (!wecomBindForm.value.user_id || !wecomBindForm.value.wecom_userid.trim()) {
alert(t('admin.wecom.msg.bindInputRequired'));
showMessageDialog('warning', t('admin.wecom.msg.bindInputRequired'));
return;
}
isSaving.value = true;
@@ -1062,14 +1106,14 @@ const bindWecomUser = async () => {
wecomBindForm.value.wecom_userid = '';
wecomBindForm.value.wecom_unionid = '';
await refreshWecomData();
alert(t('admin.wecom.msg.bindSuccess'));
showMessageDialog('success', t('admin.wecom.msg.bindSuccess'));
} catch (e: any) {
console.error(e);
const errorMessage = e?.message || t('admin.wecom.msg.bindFailed');
if (String(errorMessage).includes('already bound to user')) {
alert(t('admin.wecom.msg.boundConflict', { detail: errorMessage }));
showMessageDialog('error', t('admin.wecom.msg.boundConflict', { detail: errorMessage }));
} else {
alert(errorMessage);
showMessageDialog('error', errorMessage);
}
} finally {
isSaving.value = false;
@@ -1090,7 +1134,7 @@ const unbindWecomUserByAdmin = async (userId: number) => {
await refreshWecomData();
} catch (e: any) {
console.error(e);
alert(e.message || t('admin.wecom.msg.unbindFailed'));
showMessageDialog('error', e.message || t('admin.wecom.msg.unbindFailed'));
} finally {
isSaving.value = false;
}
@@ -1098,7 +1142,7 @@ const unbindWecomUserByAdmin = async (userId: number) => {
const exportWecomAudits = () => {
if (filteredWecomLoginAudits.value.length === 0) {
alert(t('admin.wecom.noAuditData'));
showMessageDialog('warning', t('admin.wecom.noAuditData'));
return;
}
const rows = filteredWecomLoginAudits.value.map((row) => ({
@@ -1165,7 +1209,7 @@ const loadAnnouncementsAdmin = async () => {
const createAnnouncementAdmin = async () => {
if (!newAnnouncement.value.title.trim() || !newAnnouncement.value.content.trim()) {
alert(t('admin.announcement.msg.fillAll'));
showMessageDialog('warning', t('admin.announcement.msg.fillAll'));
return;
}
isSaving.value = true;
@@ -1186,28 +1230,29 @@ const createAnnouncementAdmin = async () => {
await loadAnnouncementsAdmin();
} catch (e: any) {
console.error(e);
alert(e.message || t('admin.msg.requestFailed'));
showMessageDialog('error', e.message || t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
};
const deleteAnnouncementAdmin = async (id: number) => {
if (!confirm(t('admin.announcement.confirmDelete'))) return;
try {
const res = await fetch(`/api/user/announcements/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.error || t('admin.msg.failed'));
openDeleteConfirmDialog(t('admin.announcement.confirmDelete'), async () => {
try {
const res = await fetch(`/api/user/announcements/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
if (!res.ok) {
const data = await res.json().catch(() => ({}));
throw new Error(data.error || t('admin.msg.failed'));
}
await loadAnnouncementsAdmin();
} catch (e: any) {
console.error(e);
showMessageDialog('error', e.message || t('admin.msg.requestFailed'));
}
await loadAnnouncementsAdmin();
} catch (e: any) {
console.error(e);
alert(e.message || t('admin.msg.requestFailed'));
}
});
};
const loadQuickQuestions = async () => {
@@ -1221,7 +1266,7 @@ const loadQuickQuestions = async () => {
const saveQuestion = async () => {
if (!newQuestion.value.title || !newQuestion.value.question || !newQuestion.value.agent_id) {
alert(t('admin.question.msg.fillAll'));
showMessageDialog('warning', t('admin.question.msg.fillAll'));
return;
}
@@ -1242,11 +1287,11 @@ const saveQuestion = async () => {
await loadQuickQuestions();
resetQuestionForm();
} else {
alert(t('admin.msg.failed'));
showMessageDialog('error', t('admin.msg.failed'));
}
} catch (e) {
console.error(e);
alert(t('admin.msg.requestFailed'));
showMessageDialog('error', t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
@@ -1258,16 +1303,17 @@ const editQuestion = (q: QuickQuestion) => {
};
const deleteQuestion = async (id: number) => {
if (!confirm(t('admin.question.confirmDelete'))) return;
try {
await fetch(`/api/admin/quick-questions/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
await loadQuickQuestions();
} catch (e) {
console.error(e);
}
openDeleteConfirmDialog(t('admin.question.confirmDelete'), async () => {
try {
await fetch(`/api/admin/quick-questions/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
await loadQuickQuestions();
} catch (e) {
console.error(e);
}
});
};
const resetQuestionForm = () => {
@@ -1325,7 +1371,7 @@ watch(activeModule, async (value) => {
* 用途:目前仅作为“保存成功”提示,核心配置变更在具体操作时已写入后台
*/
// const saveConfig = () => {
// alert(t('admin.msg.allSaved'));
// showMessageDialog('success', t('admin.msg.allSaved'));
// };
const pendingUsers = computed(() => users.value.filter(u => u.status === 'pending'));
@@ -1444,7 +1490,7 @@ const runAgentTest = async (agent?: AgentRow) => {
*/
const createAgent = async () => {
if (!newAgent.value.name) {
alert(t('admin.dept.msg.nameRequired'));
showMessageDialog('warning', t('admin.dept.msg.nameRequired'));
return;
}
@@ -1507,14 +1553,14 @@ const createAgent = async () => {
const text = await res.text();
try {
const err = JSON.parse(text);
alert(err.error || t('admin.msg.failed'));
showMessageDialog('error', err.error || t('admin.msg.failed'));
} catch {
alert(`${t('admin.msg.failed')}: ${res.status} ${res.statusText}`);
showMessageDialog('error', `${t('admin.msg.failed')}: ${res.status} ${res.statusText}`);
}
}
} catch (e) {
console.error(e);
alert(t('admin.msg.requestFailed'));
showMessageDialog('error', t('admin.msg.requestFailed'));
} finally {
isSaving.value = false;
}
@@ -1529,7 +1575,7 @@ const approveUser = async (userId: number) => {
if (res.ok) {
await loadUsers();
} else {
alert(t('admin.msg.failed'));
showMessageDialog('error', t('admin.msg.failed'));
}
};
@@ -1546,14 +1592,14 @@ const rejectUser = async (userId: number) => {
const text = await res.text();
try {
const err = JSON.parse(text);
alert(err.error || t('admin.msg.failed'));
showMessageDialog('error', err.error || t('admin.msg.failed'));
} catch {
alert(`${t('admin.msg.failed')}: ${res.status} ${res.statusText}`);
showMessageDialog('error', `${t('admin.msg.failed')}: ${res.status} ${res.statusText}`);
}
}
} catch (e) {
console.error(e);
alert(t('admin.msg.requestFailed'));
showMessageDialog('error', t('admin.msg.requestFailed'));
}
};
@@ -2005,29 +2051,30 @@ const toggleAllReportRows = () => {
const batchDeleteChatLogs = async () => {
if (!isChatLogsTable.value) return;
if (selectedReportRowIds.value.length === 0) return;
if (!confirm(`Delete ${selectedReportRowIds.value.length} selected chat logs?`)) return;
isDeletingChatLogs.value = true;
try {
const res = await fetch('/api/admin/database/chat_logs/batch-delete', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ ids: selectedReportRowIds.value })
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
throw new Error(data.error || t('admin.msg.failed'));
const targetRowIds = [...selectedReportRowIds.value];
openDeleteConfirmDialog(`Delete ${targetRowIds.length} selected chat logs?`, async () => {
isDeletingChatLogs.value = true;
try {
const res = await fetch('/api/admin/database/chat_logs/batch-delete', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ ids: targetRowIds })
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
throw new Error(data.error || t('admin.msg.failed'));
}
showMessageDialog('success', `Deleted ${data.deleted_count ?? 0} chat logs.`);
selectedReportRowIds.value = [];
await loadTableData();
chatLogsTotal.value = await loadTableCount('chat_logs');
} catch (e: any) {
console.error(e);
showMessageDialog('error', e.message || t('admin.msg.failed'));
} finally {
isDeletingChatLogs.value = false;
}
alert(`Deleted ${data.deleted_count ?? 0} chat logs.`);
selectedReportRowIds.value = [];
await loadTableData();
chatLogsTotal.value = await loadTableCount('chat_logs');
} catch (e: any) {
console.error(e);
alert(e.message || t('admin.msg.failed'));
} finally {
isDeletingChatLogs.value = false;
}
});
};
watch(currentTable, async () => {
@@ -2110,30 +2157,31 @@ watch([reportPageSize, sortedTableData], () => {
* 实现方式:调 DELETE /api/admin/agents/:id
*/
const deleteAgent = async (id: number) => {
if (!confirm(t('admin.agent.confirmDelete'))) return;
try {
const res = await fetch(`/api/admin/agents/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
if (res.ok) {
await loadAgents();
if (selectedAgentId.value === id) {
resetAgentForm();
}
} else {
const text = await res.text();
try {
const err = JSON.parse(text);
alert(err.error || t('admin.msg.failed'));
} catch {
alert(`${t('admin.msg.failed')}: ${res.status} ${res.statusText}`);
openDeleteConfirmDialog(t('admin.agent.confirmDelete'), async () => {
try {
const res = await fetch(`/api/admin/agents/${id}`, {
method: 'DELETE',
headers: getAuthHeaders()
});
if (res.ok) {
await loadAgents();
if (selectedAgentId.value === id) {
resetAgentForm();
}
} else {
const text = await res.text();
try {
const err = JSON.parse(text);
showMessageDialog('error', err.error || t('admin.msg.failed'));
} catch {
showMessageDialog('error', `${t('admin.msg.failed')}: ${res.status} ${res.statusText}`);
}
}
} catch (e) {
console.error(e);
showMessageDialog('error', t('admin.msg.requestFailed'));
}
} catch (e) {
console.error(e);
alert(t('admin.msg.requestFailed'));
}
});
};
const showAgentPermissionModal = ref(false);
@@ -2170,7 +2218,7 @@ const saveAgentPermissions = async () => {
showAgentPermissionModal.value = false;
} catch (e: any) {
console.error(e);
alert(e.message || t('admin.msg.failed'));
showMessageDialog('error', e.message || t('admin.msg.failed'));
} finally {
isSaving.value = false;
}
@@ -2207,7 +2255,7 @@ const toggleUserAgentPermission = async (user: UserRow, agentId: number) => {
} catch (e) {
console.error(e);
user.agent_ids = originalIds; // Revert on error
alert(t('admin.msg.failed'));
showMessageDialog('error', t('admin.msg.failed'));
}
};
@@ -4226,5 +4274,14 @@ const handlePermissionImport = async (event: Event) => {
</div>
</div>
</div>
<DeleteConfirmDialog
v-model="showDeleteConfirmDialog"
:title="deleteConfirmTitle"
:message="deleteConfirmMessage"
:confirm-loading="deleteConfirmLoading"
@confirm="handleDeleteConfirm"
@cancel="closeDeleteConfirmDialog"
/>
</div>
</template>
+135 -72
View File
@@ -13,22 +13,51 @@
import { ref, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { useChat } from '../composables/useChat';
import { Send, User, Bot, Loader2, ArrowLeft, Plus, Menu, Star, Copy, Edit2, RotateCw, Check } from 'lucide-vue-next';
import { Send, Bot, Loader2, ArrowLeft, Plus, Menu, Star, Copy, Edit2, RotateCw, Check } 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 { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
const { t, locale } = useI18n();
const { showMessageDialog } = useGlobalMessageDialog();
const stripReasoningPrelude = (text: string) => {
if (!text) return '';
let cleaned = text
.replace(/<think[\s\S]*?<\/think>/gi, '')
.replace(/<analysis[\s\S]*?<\/analysis>/gi, '')
.trim();
const reasoningMarkers = [
'让我分析',
'根据应答生成规则',
'分析知识库返回的内容',
'我需要直接给出答案',
'思考过程',
'推理过程',
];
const hasReasoningMarker = reasoningMarkers.some((marker) => cleaned.includes(marker));
if (!hasReasoningMarker) return cleaned;
const headingMatch = cleaned.match(/(^|\n)\s{0,3}#{1,6}\s+/);
if (headingMatch && typeof headingMatch.index === 'number') {
const start = headingMatch.index + (headingMatch[1] ? headingMatch[1].length : 0);
cleaned = cleaned.slice(start).trim();
}
return cleaned;
};
const renderMarkdown = (text: string) => {
if (!text) return '';
const displayText = stripReasoningPrelude(text);
try {
// 把 # 标题、代码块、[链接](url) 等 Markdown 解析成 HTML
return marked.parse(text);
return marked.parse(displayText);
} catch (e) {
return text;
return displayText;
}
};
@@ -65,14 +94,14 @@ interface SourceFileLink {
}
// 源文件展示配置(来自 config.ts)
const sourceFileConfig = {
// 是否显示整个“源文件”区域
showSourceFiles: config.workspace?.sourceFiles?.showSourceFiles !== false,
// 是否显示 MD 源文件(.md/.markdown)
showMdFiles: config.workspace?.sourceFiles?.showMdFiles !== false,
// MD 源文件是否默认展开“源文档”详情
expandMdByDefault: config.workspace?.sourceFiles?.expandMdByDefault === true,
};
// const sourceFileConfig = {
// // 是否显示整个“源文件”区域
// showSourceFiles: config.workspace?.sourceFiles?.showSourceFiles !== false,
// // 是否显示 MD 源文件(.md/.markdown)
// showMdFiles: config.workspace?.sourceFiles?.showMdFiles !== false,
// // MD 源文件是否默认展开“源文档”详情
// expandMdByDefault: config.workspace?.sourceFiles?.expandMdByDefault === true,
// };
const PREFERRED_SOURCE_EXTS = new Set([
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'csv',
@@ -232,7 +261,7 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
// Skip links whose display name itself is noisy.
if (isNoisySourceName(name)) continue;
// 根据配置决定是否显示 MD 文件
if (!sourceFileConfig.showMdFiles && (isMarkdownFileName(name) || isMarkdownByUrl(url))) continue;
if ( (isMarkdownFileName(name) || isMarkdownByUrl(url))) continue;
const key = `${name}|${url}`;
if (!map.has(key)) {
map.set(key, { name, url });
@@ -245,7 +274,10 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
};
const getMessageLinks = (msg: any): SourceFileLink[] => {
if (!sourceFileConfig.showSourceFiles) return [];
// if (!sourceFileConfig.showSourceFiles) {
// console.info('showSourceFiles is false');
// return [];
// }
const map = new Map<string, SourceFileLink>();
const merge = (links: SourceFileLink[]) => {
@@ -253,7 +285,7 @@ const getMessageLinks = (msg: any): SourceFileLink[] => {
if (isChunkLikeLink(link.url)) continue;
// 文件名有效时,保留文件按钮(即便 URL 是临时签名地址)。
if (isNoisySourceName(link.name)) continue;
if (!sourceFileConfig.showMdFiles && (isMarkdownFileName(link.name) || isMarkdownByUrl(link.url))) continue;
if ( (isMarkdownFileName(link.name) || isMarkdownByUrl(link.url))) continue;
if (isMarkdownFileName(link.name)) {
const key = `${link.name}|${link.url}`;
if (!map.has(key)) map.set(key, link);
@@ -277,9 +309,9 @@ const getMessageLinks = (msg: any): SourceFileLink[] => {
};
const getDisplayRetrieverResources = (msg: any): any[] => {
if (!sourceFileConfig.showSourceFiles) return [];
// if (!sourceFileConfig.showSourceFiles) return [];
const list = Array.isArray(msg?.retriever_resources) ? msg.retriever_resources : [];
if (sourceFileConfig.showMdFiles) return list;
// if (sourceFileConfig.showMdFiles) return list;
return list.filter((doc: any) => {
const name = doc?.source_filename || doc?.document_name || doc?.title || '';
const url = doc?.source_download_url || doc?.url || doc?.file_url || doc?.document_url || '';
@@ -288,11 +320,42 @@ const getDisplayRetrieverResources = (msg: any): any[] => {
};
const shouldExpandSourceDetails = (msg: any): boolean => {
if (!sourceFileConfig.showSourceFiles) return false;
if (!sourceFileConfig.showMdFiles || !sourceFileConfig.expandMdByDefault) return false;
// if (!sourceFileConfig.showSourceFiles) {
// console.info('showSourceFiles is false');
// return false;
// }
// if (!sourceFileConfig.showMdFiles || !sourceFileConfig.expandMdByDefault) return false;
return getMessageLinks(msg).some((link) => isMarkdownFileName(link.name) || isMarkdownByUrl(link.url));
};
const shouldRenderMessage = (msg: any): boolean => {
if (msg?.role === 'user') return true;
const content = (msg?.content || '').trim();
if (content) return true;
if (getMessageLinks(msg).length > 0) return true;
if (getDisplayRetrieverResources(msg).length > 0) return true;
return Array.isArray(msg?.attribution_parts) && msg.attribution_parts.length > 0;
};
// “正在生成回答...” 仅在当前轮次还没有任何可显示的 assistant 内容时显示。
// 一旦最后一条用户消息之后出现了可渲染的 assistant 内容(思考或答案文本等),
// 该 loading 气泡就会隐藏,避免与正文同时出现。
const shouldShowThinkingBubble = computed(() => {
if (!isThinking.value) return false;
let lastUserIndex = -1;
for (let i = messages.value.length - 1; i >= 0; i--) {
if (messages.value[i]?.role === 'user') {
lastUserIndex = i;
break;
}
}
if (lastUserIndex < 0) return true;
return !messages.value
.slice(lastUserIndex + 1)
.some((msg) => msg?.role === 'assistant' && shouldRenderMessage(msg));
});
const filePreviewVisible = ref(false);
const previewFile = ref<SourceFileLink | null>(null);
@@ -443,7 +506,7 @@ const loadAgent = async () => {
currentAgent.value = await res.json();
} else {
if (res.status === 403) {
alert(t('workspace.permission.denied') || 'Access denied');
showMessageDialog('error', t('workspace.permission.denied') || 'Access denied');
router.push('/');
return;
}
@@ -487,7 +550,7 @@ const feedbackSubmitted = ref(false);
const submitFeedback = async () => {
if (!enableFeedback.value || feedbackSubmitted.value) return;
if (!rating.value) {
alert(t('chat.feedback.selectRating'));
showMessageDialog('warning', t('chat.feedback.selectRating'));
return;
}
const res = await fetch('/api/chat/feedback', {
@@ -521,10 +584,10 @@ const submitFeedback = async () => {
></div>
<aside
class="glass-panel fixed inset-y-0 left-0 z-50 flex w-80 flex-col border-r transition-transform duration-300 ease-in-out md:relative md:translate-x-0"
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'"
>
<div class="border-b border-slate-200/70 p-4 dark:border-slate-700/70">
<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" />
@@ -532,59 +595,62 @@ const submitFeedback = async () => {
<span class="text-sm font-semibold uppercase tracking-[0.14em] text-slate-500 dark:text-slate-300">{{ $t('chat.history') }}</span>
<ThemeToggleButton />
</div>
<button @click="startNewChat(); isSidebarOpen = false;" class="mt-4 flex w-full items-center justify-center gap-2 rounded-2xl bg-gradient-to-r from-cyan-600 to-blue-600 px-4 py-3 text-sm font-semibold text-white shadow-lg shadow-cyan-500/30 transition-all hover:from-cyan-500 hover:to-blue-500">
<button @click="startNewChat(); isSidebarOpen = false;" class="mt-3 inline-flex w-[92%] max-w-[320px] self-center items-center justify-center gap-2 rounded-xl bg-gradient-to-r from-cyan-500 to-blue-500 px-5 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:mt-4 md:w-[88%] md:max-w-none md:py-3">
<Plus class="h-4 w-4" /> {{ $t('chat.newChat') }}
</button>
</div>
<div class="flex-1 space-y-1 overflow-y-auto px-3 py-3 scrollbar-thin">
<div v-if="history.length === 0" class="py-10 text-center text-sm italic text-slate-400">{{ $t('chat.noHistory') }}</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">
<button
v-for="item in history"
:key="item.conversation_id"
class="w-full truncate rounded-xl border px-4 py-3 text-left text-sm transition-all"
class="w-full truncate px-2 py-3 text-left text-sm transition-colors md:px-3"
:class="conversationId === item.conversation_id
? 'border-cyan-300/70 bg-cyan-50/80 font-semibold text-cyan-700 shadow-sm dark:border-cyan-500/30 dark:bg-cyan-500/10 dark:text-cyan-200'
: 'border-transparent bg-white/50 text-slate-600 hover:border-slate-200 hover:bg-white/90 hover:text-slate-900 dark:bg-slate-900/30 dark:text-slate-300 dark:hover:border-slate-700 dark:hover:bg-slate-800/70 dark:hover:text-slate-100'"
? 'font-semibold text-cyan-700 dark:text-cyan-200'
: 'text-slate-600 hover:bg-slate-100/70 hover:text-slate-900 dark:text-slate-300 dark:hover:bg-slate-800/60 dark:hover:text-slate-100'"
@click="loadConversation(item.conversation_id); isSidebarOpen = false;"
>
{{ item.title || $t('chat.newChat') }}
</button>
</div>
</div>
<div class="space-y-3 border-t border-slate-200/70 bg-white/35 p-4 dark:border-slate-700/70 dark:bg-slate-900/35">
<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-2 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"
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 class="flex items-center justify-center gap-2 rounded-lg bg-slate-100/90 py-1.5 font-mono text-xs text-slate-500 dark:bg-slate-800/85 dark:text-slate-300">
<span class="h-1.5 w-1.5 rounded-full bg-emerald-500"></span>
{{ $t('chat.agentId') }} {{ agentId }}
</div>
</div>
</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 px-4 py-3 backdrop-blur-xl dark:border-slate-700/70 dark:bg-slate-950/65 md:px-6">
<div class="flex items-center gap-3">
<button @click="isSidebarOpen = !isSidebarOpen" class="rounded-lg p-2 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>
<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>
<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="flex items-center gap-2">
<button @click="startNewChat" class="hidden items-center gap-1 rounded-xl border border-slate-200 bg-white/80 px-3 py-2 text-xs 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:flex">
<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>
@@ -606,15 +672,15 @@ const submitFeedback = async () => {
</div>
<template v-else>
<main class="flex-1 space-y-8 overflow-y-auto p-4 scrollbar-thin md:p-8">
<div v-if="messages.length === 0" class="flex h-full flex-col items-center justify-center pb-20 text-slate-400">
<div class="mb-8 flex h-24 w-24 items-center justify-center rounded-3xl bg-gradient-to-br from-cyan-500 via-blue-600 to-indigo-600 shadow-2xl shadow-cyan-500/30">
<Bot class="h-10 w-10 text-white" />
</div>
<h2 class="mb-3 text-center text-3xl font-bold tracking-tight text-slate-900 dark:text-slate-100">{{ $t('chat.welcome.title') }}</h2>
<p class="max-w-xl text-center text-base leading-relaxed text-slate-500 dark:text-slate-300">{{ $t('chat.welcome.subtitle') }}</p>
<main
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-12 grid w-full max-w-3xl grid-cols-1 gap-4 md:grid-cols-2">
<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'),
@@ -623,29 +689,28 @@ const submitFeedback = async () => {
])"
:key="suggestion"
@click="input = suggestion; handleSend()"
class="rounded-2xl border border-slate-200 bg-white/90 p-4 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"
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>
</div>
<template v-for="(msg, index) in messages" :key="index">
<div
v-for="(msg, index) in messages"
:key="index"
class="group mx-auto flex max-w-5xl gap-4 animate-slide-up"
v-if="shouldRenderMessage(msg)"
class="group mx-auto flex max-w-5xl gap-0 animate-slide-up"
:class="msg.role === 'user' ? 'justify-end' : ''"
>
<div v-if="msg.role === 'assistant'" class="mt-1 flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-cyan-500 to-blue-600 shadow-md shadow-cyan-500/30">
<Bot class="h-5 w-5 text-white" />
</div>
<div class="flex max-w-[88%] flex-col md:max-w-[74%]">
<div
class="rounded-2xl px-6 py-4 text-[15px] leading-relaxed shadow-md"
<div
class="flex flex-col"
:class="msg.role === 'user' ? 'max-w-[88%] md:max-w-[74%]' : 'w-full'"
>
<div
class="text-[15px] leading-relaxed shadow-md"
:class="msg.role === 'user'
? 'rounded-tr-md border border-cyan-400/20 bg-gradient-to-br from-cyan-600 via-blue-600 to-indigo-600 text-white shadow-cyan-500/35'
: 'rounded-tl-md border border-slate-200 bg-white/95 text-slate-800 shadow-slate-300/30 dark:border-slate-700 dark:bg-slate-900/85 dark:text-slate-100'"
? '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'"
>
<div
v-if="msg.role === 'user'"
@@ -653,13 +718,13 @@ const submitFeedback = async () => {
>{{ msg.content }}</div>
<div
v-else
class="prose prose-sm max-w-none text-slate-800 dark:text-slate-100 prose-a:text-cyan-600 dark:prose-a:text-cyan-300 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:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100"
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>
<div
v-if="sourceFileConfig.showSourceFiles && msg.role === 'assistant' && ((getDisplayRetrieverResources(msg).length > 0) || (msg.attribution_parts && msg.attribution_parts.length > 0) || getMessageLinks(msg).length > 0)"
v-if=" msg.role === 'assistant' && ((getDisplayRetrieverResources(msg).length > 0) || (msg.attribution_parts && msg.attribution_parts.length > 0) || getMessageLinks(msg).length > 0)"
class="mt-2 space-y-2"
>
<!-- 带有URL链接的源文件名称,支持预览 -->
@@ -758,12 +823,10 @@ const submitFeedback = async () => {
</div>
</div>
<div v-if="msg.role === 'user'" class="mt-1 flex h-10 w-10 shrink-0 items-center justify-center rounded-xl border border-slate-200 bg-white shadow-sm dark:border-slate-700 dark:bg-slate-900">
<User class="h-5 w-5 text-slate-500 dark:text-slate-300" />
</div>
</div>
</template>
<div v-if="isThinking" class="mx-auto flex max-w-5xl gap-4">
<div v-if="shouldShowThinkingBubble" class="mx-auto flex max-w-5xl gap-4">
<div class="mt-1 flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-cyan-500 to-blue-600 shadow-md shadow-cyan-500/30">
<Bot class="h-5 w-5 text-white" />
</div>
@@ -814,12 +877,12 @@ const submitFeedback = async () => {
</div>
</div>
</div>
<div class="h-6 md:h-8"></div>
<div v-if="messages.length > 0" class="h-6 md:h-8"></div>
</main>
<footer class="safe-bottom-lg sticky bottom-0 z-20 border-t border-slate-200/80 bg-white/70 p-4 backdrop-blur-xl dark:border-slate-700/70 dark:bg-slate-950/65 md:p-6">
<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 focus-within:ring-2 focus-within:ring-cyan-500/25 dark:border-slate-700 dark:bg-slate-900/88 dark:shadow-none">
<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">
<textarea
v-model="input"
@keydown.enter.prevent="handleSend"
+9 -7
View File
@@ -5,6 +5,7 @@ import { useRouter } from 'vue-router';
import { useTheme } from '../composables/useTheme';
import type { ThemePreference } from '../composables/useTheme';
import ThemeToggleButton from '../components/ThemeToggleButton.vue';
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
import {
User,
Mail,
@@ -20,6 +21,7 @@ import {
} from 'lucide-vue-next';
const { t, locale } = useI18n();
const { showMessageDialog } = useGlobalMessageDialog();
const router = useRouter();
const { setThemePreference } = useTheme();
@@ -199,16 +201,16 @@ const handleSaveProfile = async () => {
if (!res.ok) {
const message = await parseErrorMessage(res);
alert(message || 'Failed to save profile');
showMessageDialog('error', message || 'Failed to save profile');
return;
}
alert(t('profile.saveSuccess') || 'Profile saved successfully');
showMessageDialog('success', t('profile.saveSuccess') || 'Profile saved successfully');
captureOriginalProfile();
isEditing.value = false;
} catch (e) {
console.error(e);
alert('Failed to save profile');
showMessageDialog('error', 'Failed to save profile');
} finally {
isSaving.value = false;
}
@@ -216,7 +218,7 @@ const handleSaveProfile = async () => {
const handleChangePassword = async () => {
if (passwordForm.value.new !== passwordForm.value.confirm) {
alert(t('profile.passwordMismatch') || 'Passwords do not match');
showMessageDialog('warning', t('profile.passwordMismatch') || 'Passwords do not match');
return;
}
@@ -232,15 +234,15 @@ const handleChangePassword = async () => {
const data = await res.json();
if (res.ok) {
alert(t('profile.passwordChanged') || 'Password changed successfully');
showMessageDialog('success', t('profile.passwordChanged') || 'Password changed successfully');
passwordForm.value = { current: '', new: '', confirm: '' };
showPasswordModal.value = false;
} else {
alert(data.error || 'Failed to change password');
showMessageDialog('error', data.error || 'Failed to change password');
}
} catch (e) {
console.error(e);
alert('Error changing password');
showMessageDialog('error', 'Error changing password');
}
};
+122 -68
View File
@@ -1,14 +1,17 @@
<script setup lang="ts">
/**
* WorkspaceView.vue
* 鏂囦欢鐢ㄩ€旓細鐢ㄦ埛宸ヤ綔鍙帮紝鏀寔鑷畾涔夊竷灞€銆佹敹钘忋€佸祵鍏?Agent
* 寮曠敤鏂囦欢锛歷ue, vue-router, lucide-vue-next, 鍚庣 /api/user 鎺ュ彛
* 文件用途:用户工作台,支持自定义布局、收藏、嵌入 Agent
* 引用文件:vue, vue-router, lucide-vue-next, 后端 /api/user 接口
*/
import { ref, onMounted, computed, watch } from 'vue';
import { ref, onMounted, onBeforeUnmount, computed, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { config } from '../config';
import ThemeToggleButton from '../components/ThemeToggleButton.vue';
import DeleteConfirmDialog from '../components/DeleteConfirmDialog.vue';
import { useGlobalMessageDialog } from '../composables/useGlobalMessageDialog';
import {
import {
buildWecomLoginDialogContent,
formatWecomFieldLabel,
@@ -36,6 +39,7 @@ import {
} from 'lucide-vue-next';
const { t, locale } = useI18n();
const { showMessageDialog } = useGlobalMessageDialog();
const router = useRouter();
const loadLanguagePreference = () => {
@@ -135,6 +139,8 @@ const registerForm = ref({ username: '', password: '', email: '', real_name: '',
const forgotPasswordForm = ref({ email: '' });
const pendingAgentId = ref<number | null>(null);
const isWecomLoggingIn = ref(false);
const showDeleteQuickQuestionDialog = ref(false);
const pendingDeleteQuickQuestionId = ref<number | null>(null);
const wecomEntryHint = ref('');
const wecomLoginDialog = ref<WecomLoginDialogContent | null>(null);
const wecomBindPrompt = ref<WecomBindPromptState | null>(null);
@@ -146,7 +152,7 @@ const clearWecomCallbackQuery = () => {
const handleForgotPassword = async () => {
if (!forgotPasswordForm.value.email) {
alert(t('register.emailRequired'));
showMessageDialog('warning', t('register.emailRequired'));
return;
}
@@ -159,21 +165,21 @@ const handleForgotPassword = async () => {
const data = await res.json();
if (res.ok) {
alert(t('login.passwordResetEmailSent'));
showMessageDialog('success', t('login.passwordResetEmailSent'));
showForgotPasswordModal.value = false;
forgotPasswordForm.value = { email: '' };
} else {
alert(data.error || t('login.passwordResetRequestFailed'));
showMessageDialog('error', data.error || t('login.passwordResetRequestFailed'));
}
} catch (e) {
console.error('Password reset error', e);
alert(t('common.errorOccurred'));
showMessageDialog('error', t('common.errorOccurred'));
}
};
/*
const showLoginTip = () => {
alert(t('login.pleaseLoginFirst'));
showMessageDialog('warning', t('login.pleaseLoginFirst'));
};
*/
const userReport = ref<any>(null);
@@ -407,7 +413,7 @@ const persistLoginUser = (user: any) => {
const handleLogin = async () => {
if (!loginUsername.value.trim()) {
alert(t('login.usernameRequired'));
showMessageDialog('warning', t('login.usernameRequired'));
return;
}
@@ -431,7 +437,7 @@ const handleLogin = async () => {
if (err.error === 'Database connection failed') msg = t('login.dbConnectionFailed');
if (err.error === 'Internal server error') msg = t('login.internalError');
alert(msg);
showMessageDialog('error', msg);
return;
}
@@ -447,12 +453,12 @@ const handleLogin = async () => {
if (agents.value.some(a => a.id === targetId)) {
navigateToChat(targetId);
} else {
alert(t('workspace.permission.denied'));
showMessageDialog('error', t('workspace.permission.denied'));
}
}
} catch (e) {
console.error(e);
alert(t('login.requestFailed'));
showMessageDialog('error', t('login.requestFailed'));
}
};
@@ -464,7 +470,7 @@ const handleWecomLogin = async () => {
const res = await fetch(`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`);
const data = await res.json();
if (!res.ok || !data.url) {
alert(data.error || t('login.wecomStartFailed'));
showMessageDialog('error', data.error || t('login.wecomStartFailed'));
return;
}
if (data.state) {
@@ -473,7 +479,7 @@ const handleWecomLogin = async () => {
window.location.href = data.url;
} catch (e) {
console.error(e);
alert(t('login.wecomStartFailed'));
showMessageDialog('error', t('login.wecomStartFailed'));
}
};
@@ -566,6 +572,7 @@ const tryWecomCallbackLogin = async () => {
const expectedState = sessionStorage.getItem('hxops_wecom_state');
if (expectedState && state && state !== expectedState) {
showMessageDialog('error', t('login.wecomInvalidState'));
openWecomLoginDialog({ error: 'Invalid or expired WeCom state' });
clearWecomCallbackQuery();
return true;
@@ -581,6 +588,16 @@ const tryWecomCallbackLogin = async () => {
});
const data = await res.json();
if (!res.ok) {
const rawError = String(data.error || '');
let friendly = rawError || t('login.wecomLoginFailed');
if (rawError.includes('Invalid or expired WeCom state')) {
friendly = t('login.wecomStateExpired');
} else if (rawError.includes('bind WeCom account') || rawError.includes('No linked account found')) {
friendly = t('login.wecomBindRequired');
} else if (rawError.includes('Account is disabled')) {
friendly = t('login.wecomAccountDisabled');
}
showMessageDialog('error', friendly);
sessionStorage.removeItem('hxops_wecom_state');
if (String(data.error_code || '') === 'WECOM_BIND_INPUT_REQUIRED') {
openWecomBindPrompt(data);
@@ -600,6 +617,7 @@ const tryWecomCallbackLogin = async () => {
return true;
} catch (e) {
console.error(e);
showMessageDialog('error', t('login.wecomLoginFailed'));
sessionStorage.removeItem('hxops_wecom_state');
openWecomLoginDialog({ error: t('login.wecomLoginFailed') });
clearWecomCallbackQuery();
@@ -611,7 +629,7 @@ const tryWecomCallbackLogin = async () => {
const handleRegister = async () => {
if (!registerForm.value.username || !registerForm.value.password || !registerForm.value.real_name || !registerForm.value.employee_id || !registerForm.value.phone_number) {
alert(t('register.inputError'));
showMessageDialog('warning', t('register.inputError'));
return;
}
@@ -623,21 +641,30 @@ const handleRegister = async () => {
});
if (res.ok) {
alert(t('register.success'));
showMessageDialog('success', t('register.success'));
showRegisterModal.value = false;
registerForm.value = { username: '', password: '', email: '', real_name: '', employee_id: '', phone_number: '' };
} else {
const err = await res.json();
alert(err.error || t('register.failed'));
showMessageDialog('error', err.error || t('register.failed'));
}
} catch (e) {
console.error('Register error:', e);
alert(t('register.requestFailed'));
showMessageDialog('error', t('register.requestFailed'));
}
};
// Header Dropdown State
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 = () => {
localStorage.removeItem('hxops_user');
@@ -658,7 +685,7 @@ const navigateToProfile = () => {
const navigateToChat = (id: number) => {
if (!isLoggedIn.value) {
pendingAgentId.value = id;
alert(t('login.loginRequired'));
showMessageDialog('warning', t('login.loginRequired'));
return;
}
const url = router.resolve(`/chat/${id}`).href;
@@ -668,7 +695,7 @@ const navigateToChat = (id: number) => {
const navigateWithQuickQuestion = (agentId: number, question: string) => {
if (!isLoggedIn.value) {
pendingAgentId.value = agentId;
alert(t('login.loginRequired'));
showMessageDialog('warning', t('login.loginRequired'));
return;
}
const url = router.resolve({
@@ -760,7 +787,7 @@ const cancelAddQuestion = () => {
const saveQuickQuestion = async () => {
if (!newQuestion.value.title || !newQuestion.value.question || !newQuestion.value.agent_id) {
alert(t('workspace.quickQuestions.msg.fillAll'));
showMessageDialog('warning', t('workspace.quickQuestions.msg.fillAll'));
return;
}
@@ -781,14 +808,27 @@ const saveQuickQuestion = async () => {
isAddingQuestion.value = false;
editingQuestionId.value = null;
} else {
alert(t('workspace.quickQuestions.msg.saveFailed'));
showMessageDialog('error', t('workspace.quickQuestions.msg.saveFailed'));
}
};
const removeQuickQuestion = async (id: number) => {
if (!window.confirm(t('workspace.quickQuestions.confirmDelete'))) return;
await fetch(`/api/user/quick-questions/${id}`, { method: 'DELETE', headers: getAuthHeaders() });
// 删除动作分两步:先记录待删除 id 并打开公共弹框,真正删除在 confirm 回调中执行。
pendingDeleteQuickQuestionId.value = id;
showDeleteQuickQuestionDialog.value = true;
};
const confirmRemoveQuickQuestion = async () => {
if (pendingDeleteQuickQuestionId.value === null) return;
await fetch(`/api/user/quick-questions/${pendingDeleteQuickQuestionId.value}`, { method: 'DELETE', headers: getAuthHeaders() });
await fetchHome();
pendingDeleteQuickQuestionId.value = null;
showDeleteQuickQuestionDialog.value = false;
};
const cancelRemoveQuickQuestion = () => {
pendingDeleteQuickQuestionId.value = null;
showDeleteQuickQuestionDialog.value = false;
};
// Drag & Drop
@@ -833,6 +873,8 @@ const openAnnouncement = (ann: Announcement) => {
};
onMounted(async () => {
document.addEventListener('mousedown', handleDocumentPointerDown);
document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true });
loadLanguagePreference();
fetchAnnouncements();
const handledWecom = await tryWecomCallbackLogin();
@@ -848,6 +890,11 @@ onMounted(async () => {
isLoading.value = false;
}
});
onBeforeUnmount(() => {
document.removeEventListener('mousedown', handleDocumentPointerDown);
document.removeEventListener('touchstart', handleDocumentPointerDown);
});
</script>
<template>
@@ -864,47 +911,39 @@ onMounted(async () => {
</div>
<!-- Header (Logged In) -->
<header v-if="isLoggedIn" class="sticky top-0 z-30 bg-white/80 dark:bg-slate-900/80 backdrop-blur-md border-b border-gray-100 dark:border-slate-700 px-4 md:px-8 py-4 mb-8 transition-all duration-300">
<div class="max-w-7xl mx-auto flex flex-col md:flex-row justify-between items-center gap-4">
<div class="flex items-center gap-3">
<div class="w-10 h-10 bg-gradient-to-br from-brand-500 to-brand-700 rounded-xl flex items-center justify-center text-white shadow-lg shadow-brand-500/30">
<Bot class="w-6 h-6" />
<header v-if="isLoggedIn" class="sticky top-0 z-30 bg-white/80 dark:bg-slate-900/80 backdrop-blur-md border-b border-gray-100 dark:border-slate-700 page-shell-mobile py-2.5 md:py-4 section-gap-mobile transition-all duration-300">
<div class="max-w-7xl mx-auto flex flex-wrap md:flex-nowrap justify-between items-start md:items-center gap-2 md:gap-4">
<div class="flex items-center gap-2 md:gap-3 min-w-0 flex-1">
<div class="w-8 h-8 md:w-10 md:h-10 bg-gradient-to-br from-brand-500 to-brand-700 rounded-xl flex items-center justify-center text-white shadow-lg shadow-brand-500/30 shrink-0">
<Bot class="w-4 h-4 md:w-6 md:h-6" />
</div>
<div>
<h1 class="text-xl font-bold text-slate-900 dark:text-slate-100 tracking-tight">
{{ currentUser ? $t('workspace.userTitle', { username: currentUser.username }) : $t('workspace.title') }}
<div class="min-w-0">
<h1 class="text-lg md:text-xl font-bold text-[#1b2b49] dark:text-slate-100 tracking-tight leading-tight truncate">
{{ $t('workspace.brandTitle') }}
</h1>
<p class="text-slate-500 dark:text-slate-400 text-xs font-medium">{{ $t('workspace.subtitle') }}</p>
</div>
</div>
<div class="flex items-center gap-4">
<!-- 已登录页将主题与语言切换放入头部右侧,避免不同分辨率下被遮挡 -->
<div class="flex items-center gap-2 md:gap-4 shrink-0">
<!-- Keep header actions minimal on mobile; language switch is in the profile dropdown. -->
<div class="flex items-center gap-2">
<ThemeToggleButton />
<select v-model="locale" class="bg-white/80 dark:bg-slate-900/80 backdrop-blur-md shadow-sm border border-slate-200 dark:border-slate-700 text-xs font-medium text-slate-600 dark:text-slate-300 hover:text-slate-800 dark:hover:text-slate-100 cursor-pointer outline-none rounded-full px-3 py-1.5 transition-all hover:shadow-md">
<option value="en">English</option>
<option value="zh-CN">简体中文</option>
<option value="zh-TW">繁體中文</option>
<option value="th">ไทย</option>
</select>
</div>
<!-- User Profile Dropdown -->
<div class="relative">
<button @click="showUserDropdown = !showUserDropdown" class="flex items-center gap-3 pl-3 pr-2 py-1.5 rounded-full hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors border border-transparent hover:border-slate-200 dark:hover:border-slate-700">
<div ref="userMenuRef" class="relative">
<button @click="showUserDropdown = !showUserDropdown" class="flex items-center gap-2 md:gap-3 pl-2 md:pl-3 pr-1.5 md:pr-2 py-1 md:py-1.5 rounded-full hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors border border-transparent hover:border-slate-200 dark:hover:border-slate-700">
<div class="text-right hidden sm:block">
<div class="text-sm font-bold text-slate-900 dark:text-slate-100 leading-tight">{{ currentUser?.username }}</div>
<div class="text-[10px] font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wide">{{ currentUser?.role }}</div>
</div>
<div class="w-9 h-9 bg-brand-100 rounded-full flex items-center justify-center text-brand-600 font-bold border-2 border-white shadow-sm">
<div class="w-8 h-8 md:w-9 md:h-9 bg-brand-100 rounded-full flex items-center justify-center text-brand-600 font-bold border-2 border-white shadow-sm">
{{ (currentUser?.username || 'U').charAt(0).toUpperCase() }}
</div>
</button>
<!-- Dropdown Menu -->
<div v-if="showUserDropdown"
class="absolute right-0 top-full mt-2 w-48 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"
@click.away="showUserDropdown = false">
class="absolute right-0 top-full mt-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 md:hidden">
<div class="text-sm font-bold text-slate-900 dark:text-slate-100">{{ currentUser?.username }}</div>
<div class="text-xs text-slate-500 dark:text-slate-400">{{ currentUser?.role }}</div>
@@ -919,7 +958,16 @@ onMounted(async () => {
<Settings class="w-4 h-4" />
{{ $t('admin.title') }}
</button>
<div class="px-4 pt-2 pb-3 border-t border-slate-50 dark:border-slate-700 mt-1">
<label class="block text-[11px] font-semibold text-slate-500 dark:text-slate-400 mb-1.5 uppercase tracking-wide">{{ $t('workspace.languageLabel') }}</label>
<select v-model="locale" class="w-full bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 text-xs font-medium text-slate-700 dark:text-slate-300 rounded-lg px-2.5 py-2 outline-none focus:ring-2 focus:ring-brand-500/20 focus:border-brand-500">
<option value="en">English</option>
<option value="zh-CN">简体中文</option>
<option value="zh-TW">繁體中文</option>
<option value="th">ไทย</option>
</select>
</div>
<div class="border-t border-slate-50 dark:border-slate-700 my-1"></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">
@@ -932,7 +980,7 @@ onMounted(async () => {
</div>
</header>
<main class="max-w-7xl mx-auto px-4 md:px-8 pb-12">
<main class="max-w-7xl mx-auto page-shell-mobile pb-12">
<div v-if="isLoading" class="animate-pulse space-y-8">
<div class="h-48 bg-gray-200 rounded-2xl"></div>
<div class="grid grid-cols-1 md:grid-cols-3 gap-6">
@@ -1091,7 +1139,7 @@ onMounted(async () => {
<div class="md:pl-6">
<!-- Header -->
<div class="flex justify-between items-center mb-6">
<h2 class="text-xl font-bold text-slate-800 flex items-center gap-2.5 cursor-pointer select-none" @click="toggleSectionCollapse(section)">
<h2 class="text-lg md:text-xl font-semibold text-[#1b2b49] dark:text-slate-100 flex items-center gap-2.5 cursor-pointer select-none" @click="toggleSectionCollapse(section)">
<div class="p-2 rounded-lg" :class="{
'bg-emerald-50 text-emerald-600': section.id === 'announcements',
'bg-yellow-50 text-yellow-600': section.id === 'favorites',
@@ -1133,15 +1181,15 @@ onMounted(async () => {
<!-- Content: Favorites -->
<div v-if="section.id === 'favorites'">
<div v-if="favoriteAgents.length === 0" class="text-slate-400 text-sm italic py-4 bg-slate-50 rounded-xl text-center border border-dashed border-slate-200">{{ $t('workspace.noFavorites') }}</div>
<div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-6">
<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3 sm:gap-6">
<div v-for="agent in favoriteAgents" :key="agent.id" @click="navigateToChat(agent.id)"
class="card p-5 cursor-pointer relative group/card hover:-translate-y-1 hover:shadow-lg hover:border-brand-200 bg-gradient-to-br from-white to-slate-50/50">
<div class="w-12 h-12 bg-brand-100 rounded-xl flex items-center justify-center text-brand-600 mb-4 shadow-sm group-hover/card:scale-110 transition-transform duration-300">
<img v-if="agent.icon_url" :src="agent.icon_url" class="w-7 h-7" />
<Bot v-else class="w-7 h-7" />
class="card p-4 sm:p-5 cursor-pointer relative group/card hover:-translate-y-1 hover:shadow-lg hover:border-brand-200 bg-gradient-to-br from-white to-slate-50/50">
<div class="w-8 h-8 sm:w-12 sm:h-12 bg-brand-100 rounded-xl flex items-center justify-center text-brand-600 mb-3 sm:mb-4 shadow-sm group-hover/card:scale-110 transition-transform duration-300">
<img v-if="agent.icon_url" :src="agent.icon_url" class="w-5 h-5 sm:w-7 sm:h-7" />
<Bot v-else class="w-5 h-5 sm:w-7 sm:h-7" />
</div>
<div class="font-bold text-slate-900 mb-1 group-hover/card:text-brand-700 transition-colors">{{ agent.name }}</div>
<div class="text-xs text-slate-500 truncate">{{ agent.description }}</div>
<div class="text-[15px] sm:text-base font-semibold text-[#1b2b49] dark:text-slate-100 mb-1 group-hover/card:text-brand-700 dark:group-hover/card:text-brand-300 transition-colors truncate">{{ agent.name }}</div>
<div class="text-[13px] sm:text-xs text-[#8fa1b8] dark:text-slate-300 truncate">{{ agent.description }}</div>
<button @click.stop="toggleFavorite(agent.id)" class="absolute top-3 right-3 text-yellow-400 hover:text-yellow-500 hover:scale-110 transition-all opacity-0 group-hover/card:opacity-100">
<Star class="w-5 h-5 fill-current" />
</button>
@@ -1225,23 +1273,21 @@ onMounted(async () => {
<div class="mb-6">
<input v-model="searchQuery" type="text" :placeholder="$t('workspace.search')" class="input-field max-w-md shadow-sm" />
</div>
<div class="grid grid-cols-1 md:grid-cols-3 lg:grid-cols-4 gap-6">
<div v-for="agent in otherAgents" :key="agent.id"
class="card p-5 cursor-pointer relative group/card hover:-translate-y-1 hover:border-brand-200">
<div class="flex items-start justify-between mb-4">
<div class="w-10 h-10 bg-slate-50 rounded-xl flex items-center justify-center text-slate-500 group-hover/card:bg-brand-50 group-hover/card:text-brand-600 transition-colors">
<img v-if="agent.icon_url" :src="agent.icon_url" class="w-6 h-6" />
<Bot v-else class="w-6 h-6" />
<div class="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-3 sm:gap-6">
<div v-for="agent in otherAgents" :key="agent.id"
@click="navigateToChat(agent.id)"
class="card card-mobile-compact cursor-pointer relative group/card hover:-translate-y-1 hover:border-brand-200">
<div class="flex items-start justify-between mb-2 sm:mb-4">
<div class="w-8 h-8 sm:w-10 sm:h-10 bg-slate-50 rounded-xl flex items-center justify-center text-slate-500 group-hover/card:bg-brand-50 group-hover/card:text-brand-600 transition-colors">
<img v-if="agent.icon_url" :src="agent.icon_url" class="w-4 h-4 sm:w-6 sm:h-6" />
<Bot v-else class="w-4 h-4 sm:w-6 sm:h-6" />
</div>
<button @click.stop="toggleFavorite(agent.id)" class="text-slate-200 hover:text-yellow-400 transition-colors">
<Star class="w-5 h-5" :class="{ 'fill-yellow-400 text-yellow-400': favoriteAgentIds.includes(agent.id) }" />
</button>
</div>
<h3 class="font-bold text-slate-900 mb-1 group-hover/card:text-brand-700 transition-colors">{{ agent.name }}</h3>
<p class="text-xs text-slate-500 line-clamp-2 h-8 leading-relaxed">{{ agent.description }}</p>
<button @click="navigateToChat(agent.id)" class="mt-5 w-full py-2 bg-slate-50 text-slate-600 text-xs font-bold rounded-xl hover:bg-brand-600 hover:text-white transition-all duration-300">
{{ $t('workspace.startChatShort') }}
</button>
<h3 class="text-[15px] sm:text-base font-semibold text-[#1b2b49] dark:text-slate-100 mb-1 group-hover/card:text-brand-700 dark:group-hover/card:text-brand-300 transition-colors line-clamp-1 sm:line-clamp-2 leading-tight">{{ agent.name }}</h3>
<p class="text-[13px] sm:text-xs text-[#8fa1b8] dark:text-slate-300 line-clamp-1 sm:line-clamp-2 h-4 sm:h-8 leading-relaxed">{{ agent.description }}</p>
</div>
</div>
</div>
@@ -1392,9 +1438,17 @@ onMounted(async () => {
</div>
</div>
<DeleteConfirmDialog
v-model="showDeleteQuickQuestionDialog"
:title="$t('workspace.quickQuestions.deleteDialog.title')"
:message="$t('workspace.quickQuestions.deleteDialog.message')"
@confirm="confirmRemoveQuickQuestion"
@cancel="cancelRemoveQuickQuestion"
/>
</div>
</template>
<style scoped>
/* Scoped styles removed in favor of global utilities in style.css */
</style>