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

+1 -1
View File
@@ -5,7 +5,7 @@ docs/
venv/
backend/venv/
env/
.env
# .env
.venv
build/
develop-eggs/
+2
View File
@@ -0,0 +1,2 @@
INTEGRATION_API_BASE=http://192.168.100.230:8891
INTEGRATION_API_KEY=I76mSQZQEPYU6TubMhjh-xLsCgWC0gSIg5MncJFHFCvqvVlg-gZ_BvwO_UEL2nh
+3 -3
View File
@@ -253,12 +253,12 @@ def submit_feedback():
return jsonify({'error': 'Missing user or agent context'}), 500
# 构造查询:限定在当前用户和 Agent 范围内
query = ChatLog.query.filter_by(user_id=user.id, agent_id=agent.id)
chat_logs_query = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id)
if conversation_id:
query = query.filter_by(conversation_id=conversation_id)
chat_logs_query = chat_logs_query.filter_by(conversation_id=conversation_id)
# 取最新一条对话日志
chat_log = query.order_by(ChatLog.created_at.desc()).first()
chat_log = chat_logs_query.order_by(ChatLog.created_at.desc()).first()
if not chat_log:
return jsonify({'error': 'ChatLog not found'}), 404
+1
View File
@@ -72,6 +72,7 @@ class DevelopmentConfig(Config):
DEBUG = True
SQLALCHEMY_DATABASE_URI = os.getenv(
'DATABASE_URL',
# 'postgresql://postgres:123456@8.152.207.171:5432/hxops_db',
'postgresql://postgres:difyai123456@localhost:5432/hxops_db',
)
+3 -1
View File
@@ -129,7 +129,9 @@ class DifyService:
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
elif event in ('message_end', 'agent_message', 'workflow_finished'):
if data.get('answer'):
# Keep metadata from non-message events, but avoid appending
# intermediate workflow/agent outputs into final user answer.
if event == 'message_end' and data.get('answer'):
full_answer.append(data.get('answer', ''))
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
+5 -4
View File
@@ -7,13 +7,14 @@
<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="hxai" />
<meta name="apple-mobile-web-app-title" content="AI工作台" />
<link rel="manifest" href="/manifest.webmanifest" />
<title>hxai</title>
<script type="module" crossorigin src="/assets/index-DwR3-714.js"></script>
<link rel="stylesheet" crossorigin href="/assets/index-CAuT3De9.css">
<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>
+2 -2
View File
@@ -7,9 +7,9 @@
<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="hxai" />
<meta name="apple-mobile-web-app-title" content="AI工作台" />
<link rel="manifest" href="/manifest.webmanifest" />
<title>hxai</title>
<title>AI工作台</title>
</head>
<body>
<div id="app"></div>
+16
View File
@@ -3,9 +3,18 @@
import { useI18n } from 'vue-i18n';
import { watch, onMounted } from 'vue';
import { useTheme } from './composables/useTheme';
import LevelMessageDialog from './components/LevelMessageDialog.vue';
import { useGlobalMessageDialog } from './composables/useGlobalMessageDialog';
const { locale } = useI18n();
const { themePreference, initTheme, setThemePreference } = useTheme();
const {
messageDialogVisible,
messageDialogLevel,
messageDialogTitle,
messageDialogContent,
closeMessageDialog,
} = useGlobalMessageDialog();
const getAuthHeaders = () => {
const candidates = [
@@ -96,4 +105,11 @@ onMounted(async () => {
<template>
<router-view />
<LevelMessageDialog
v-model="messageDialogVisible"
:level="messageDialogLevel"
:title="messageDialogTitle"
:message="messageDialogContent"
@close="closeMessageDialog"
/>
</template>
@@ -0,0 +1,192 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, watch } from 'vue';
import { useI18n } from 'vue-i18n';
interface Props {
// 由父组件控制显隐,使用 v-model 统一管理弹框状态。
modelValue: boolean;
// title/message 支持外部按场景透传,不传时走 i18n 默认值。
title?: string;
message?: string;
confirmText?: string;
cancelText?: string;
confirmLoading?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
title: '',
message: '',
confirmText: '',
cancelText: '',
confirmLoading: false,
});
const emit = defineEmits<{
(e: 'update:modelValue', value: boolean): void;
(e: 'confirm'): void;
(e: 'cancel'): void;
}>();
const { t } = useI18n();
const resolvedTitle = computed(() => props.title || t('common.deleteDialog.defaultTitle'));
const resolvedMessage = computed(() => props.message || t('common.deleteDialog.defaultMessage'));
const resolvedCancelText = computed(() => props.cancelText || t('common.deleteDialog.cancel'));
const resolvedConfirmText = computed(() => props.confirmText || t('common.deleteDialog.confirm'));
const closeDialog = () => {
emit('update:modelValue', false);
};
const handleCancel = () => {
// 先抛出 cancel 事件,方便父组件做状态回滚,再关闭弹框。
emit('cancel');
closeDialog();
};
const handleConfirm = () => {
emit('confirm');
};
const handleEscKey = (event: KeyboardEvent) => {
if (event.key === 'Escape' && props.modelValue) {
handleCancel();
}
};
watch(
() => props.modelValue,
(visible) => {
// 关键点:弹框打开时监听 ESC,关闭后及时解绑,避免全局事件泄漏。
if (visible) {
document.addEventListener('keydown', handleEscKey);
return;
}
document.removeEventListener('keydown', handleEscKey);
},
{ immediate: true }
);
onBeforeUnmount(() => {
document.removeEventListener('keydown', handleEscKey);
});
</script>
<template>
<Transition name="delete-dialog-fade">
<div
v-if="modelValue"
class="fixed inset-0 z-[100] bg-black/45 flex items-center justify-center p-4"
@click.self="handleCancel"
>
<div class="delete-dialog-container w-full max-w-[416px] rounded-lg bg-white shadow-[0_6px_16px_0_rgba(0,0,0,0.08),0_3px_6px_-4px_rgba(0,0,0,0.12),0_9px_28px_8px_rgba(0,0,0,0.05)] px-6 pt-7 pb-5">
<div class="flex items-start gap-3">
<span class="delete-dialog-icon" aria-hidden="true">!</span>
<div class="min-w-0">
<h3 class="text-[16px] leading-6 font-semibold text-[rgba(0,0,0,0.88)]">
{{ resolvedTitle }}
</h3>
<p class="mt-3 text-[14px] leading-[22px] text-[rgba(0,0,0,0.65)] whitespace-pre-line">
{{ resolvedMessage }}
</p>
</div>
</div>
<div class="mt-6 flex justify-end gap-2">
<button type="button" class="delete-dialog-btn cancel" @click="handleCancel">
{{ resolvedCancelText }}
</button>
<button
type="button"
class="delete-dialog-btn confirm"
:disabled="confirmLoading"
@click="handleConfirm"
>
{{ resolvedConfirmText }}
</button>
</div>
</div>
</div>
</Transition>
</template>
<style scoped>
.delete-dialog-icon {
width: 22px;
height: 22px;
border-radius: 9999px;
background: #faad14;
color: #fff;
font-size: 14px;
line-height: 1;
font-weight: 600;
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
margin-top: 2px;
}
.delete-dialog-btn {
min-width: 66px;
height: 32px;
border-radius: 6px;
font-size: 14px;
line-height: 1;
font-weight: 400;
padding: 4px 15px;
transition: all 0.2s ease;
}
.delete-dialog-btn.cancel {
color: rgba(0, 0, 0, 0.88);
background: #fff;
border: 1px solid #d9d9d9;
}
.delete-dialog-btn.cancel:hover {
border-color: #4096ff;
color: #4096ff;
}
.delete-dialog-btn.confirm {
color: #fff;
background: #1677ff;
border: 1px solid #1677ff;
}
.delete-dialog-btn.confirm:hover {
background: #4096ff;
border-color: #4096ff;
}
.delete-dialog-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.delete-dialog-fade-enter-active,
.delete-dialog-fade-leave-active {
transition: opacity 0.18s ease;
}
.delete-dialog-fade-enter-from,
.delete-dialog-fade-leave-to {
opacity: 0;
}
@media (max-width: 768px) {
.delete-dialog-container {
max-width: 94vw;
padding: 20px 16px 16px;
}
.delete-dialog-icon {
margin-top: 1px;
}
.delete-dialog-btn {
min-width: 62px;
}
}
</style>
+5 -5
View File
@@ -345,13 +345,13 @@ watch(
<template>
<div v-if="modelValue && file" class="fixed inset-0 z-[80] flex items-center justify-center bg-black/50 dark:bg-slate-950/70 backdrop-blur-sm p-4">
<div class="bg-white dark:bg-slate-900 rounded-2xl shadow-xl w-full max-w-5xl h-[85vh] flex flex-col overflow-hidden border border-slate-200 dark:border-slate-700">
<div class="px-6 py-4 border-b border-slate-200 dark:border-slate-700 flex items-center justify-between gap-4">
<div class="px-6 py-4 border-b border-slate-200 dark:border-slate-700 flex items-start justify-between gap-4">
<div class="min-w-0">
<div class="text-sm text-slate-500 dark:text-slate-400 uppercase tracking-wide">文件预览</div>
<div class="font-semibold text-slate-900 dark:text-slate-100 truncate">{{ file.name }}</div>
<a :href="file.url" target="_blank" class="text-xs text-brand-600 hover:text-brand-700 break-all">{{ file.url }}</a>
<div class="text-sm font-medium text-slate-500 dark:text-slate-400 tracking-wide">文件预览</div>
<div class="mt-1 font-semibold text-slate-900 dark:text-slate-100 break-words">{{ file.name }}</div>
<a :href="file.url" target="_blank" class="mt-1 block text-xs text-brand-600 hover:text-brand-700 break-all leading-6">{{ file.url }}</a>
</div>
<button @click="close" class="px-3 py-1.5 rounded-lg text-slate-600 dark:text-slate-300 hover:bg-slate-100 dark:hover:bg-slate-800">关闭</button>
<button type="button" @click="close" class="shrink-0 whitespace-nowrap inline-flex items-center justify-center px-4 py-2 rounded-xl border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-300 bg-white/80 dark:bg-slate-900/80 hover:bg-slate-100 dark:hover:bg-slate-800">关闭</button>
</div>
<div class="flex-1 overflow-auto p-4 bg-slate-50 dark:bg-slate-950">
@@ -0,0 +1,170 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, watch } from 'vue';
import { Check, Info, AlertTriangle, XCircle, X } from 'lucide-vue-next';
type MessageLevel = 'success' | 'info' | 'warning' | 'error';
interface Props {
// 父组件通过 v-model 控制弹框显隐。
modelValue: boolean;
// 消息级别决定配色和图标。
level?: MessageLevel;
title?: string;
message?: string;
closeOnMask?: boolean;
closeOnEsc?: boolean;
}
const props = withDefaults(defineProps<Props>(), {
level: 'info',
title: '',
message: '',
closeOnMask: true,
closeOnEsc: true,
});
const emit = defineEmits<{
(e: 'update:modelValue', value: boolean): void;
(e: 'close'): void;
}>();
const STYLE_MAP: Record<MessageLevel, { panel: string; iconWrap: string; icon: string }> = {
success: {
panel: 'bg-[#eef8e8] border-[#b7e2a7]',
iconWrap: 'border-[#52c41a]',
icon: 'text-[#52c41a]',
},
info: {
panel: 'bg-[#eaf4ff] border-[#9fcbff]',
iconWrap: 'border-[#1677ff]',
icon: 'text-[#1677ff]',
},
warning: {
panel: 'bg-[#fff8e8] border-[#ffd88a]',
iconWrap: 'border-[#faad14]',
icon: 'text-[#faad14]',
},
error: {
panel: 'bg-[#fff1f0] border-[#ffb3b0]',
iconWrap: 'border-[#ff4d4f]',
icon: 'text-[#ff4d4f]',
},
};
const ICON_MAP: Record<MessageLevel, any> = {
success: Check,
info: Info,
warning: AlertTriangle,
error: XCircle,
};
const DEFAULT_TITLE_MAP: Record<MessageLevel, string> = {
success: 'Success',
info: 'Info',
warning: 'Warning',
error: 'Error',
};
const resolvedStyle = computed(() => STYLE_MAP[props.level]);
const resolvedIcon = computed(() => ICON_MAP[props.level]);
const resolvedTitle = computed(() => props.title || DEFAULT_TITLE_MAP[props.level]);
const resolvedMessage = computed(() => props.message || '');
const closeDialog = () => {
emit('update:modelValue', false);
emit('close');
};
const handleMaskClose = () => {
if (!props.closeOnMask) return;
closeDialog();
};
const handleEscKey = (event: KeyboardEvent) => {
if (!props.closeOnEsc) return;
if (event.key === 'Escape' && props.modelValue) {
closeDialog();
}
};
watch(
() => props.modelValue,
(visible) => {
if (!visible) {
document.removeEventListener('keydown', handleEscKey);
return;
}
document.addEventListener('keydown', handleEscKey);
},
{ immediate: true }
);
onBeforeUnmount(() => {
document.removeEventListener('keydown', handleEscKey);
});
</script>
<template>
<Transition name="level-dialog-fade">
<div
v-if="modelValue"
class="fixed inset-0 z-[110] bg-black/40 flex items-center justify-center p-4"
@click.self="handleMaskClose"
>
<div
class="level-dialog-panel w-full max-w-[430px] rounded-2xl border shadow-[0_14px_28px_rgba(0,0,0,0.14)] px-9 py-8 relative"
:class="resolvedStyle.panel"
>
<button
type="button"
class="absolute top-4 right-4 w-8 h-8 inline-flex items-center justify-center rounded-full text-slate-500 hover:text-slate-700 hover:bg-black/5 transition-colors"
@click="closeDialog"
aria-label="close dialog"
>
<X class="w-4 h-4" />
</button>
<div class="flex items-start gap-4 pr-8">
<span
class="w-8 h-8 rounded-full border-2 inline-flex items-center justify-center shrink-0 mt-0.5"
:class="resolvedStyle.iconWrap"
>
<component :is="resolvedIcon" class="w-4 h-4" :class="resolvedStyle.icon" />
</span>
<div class="min-w-0">
<h3 class="text-[16px] leading-6 font-semibold text-slate-800">
{{ resolvedTitle }}
</h3>
<p class="mt-3 text-[14px] leading-8 text-slate-700 whitespace-pre-line">
{{ resolvedMessage }}
</p>
</div>
</div>
</div>
</div>
</Transition>
</template>
<style scoped>
.level-dialog-fade-enter-active,
.level-dialog-fade-leave-active {
transition: opacity 0.2s ease;
}
.level-dialog-fade-enter-from,
.level-dialog-fade-leave-to {
opacity: 0;
}
@media (max-width: 768px) {
.level-dialog-panel {
max-width: 94vw;
padding: 20px 18px;
}
.level-dialog-panel p {
line-height: 1.75;
}
}
</style>
@@ -15,7 +15,7 @@ const isDarkTheme = computed(() => appliedTheme.value === 'dark');
const buttonClass = computed(() =>
props.floating
? 'fixed bottom-5 right-5 z-[70] h-11 w-11 rounded-full bg-white/90 dark:bg-slate-900/90 backdrop-blur-md shadow-lg border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-300 hover:text-slate-900 dark:hover:text-slate-100 hover:shadow-xl flex items-center justify-center transition-all'
: 'h-9 w-9 rounded-full bg-white/80 dark:bg-slate-900/80 backdrop-blur-md shadow-sm border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-300 hover:text-slate-900 dark:hover:text-slate-100 hover:shadow-md flex items-center justify-center transition-all'
: 'h-8 w-8 md:h-9 md:w-9 rounded-full bg-white/80 dark:bg-slate-900/80 backdrop-blur-md shadow-sm border border-slate-200 dark:border-slate-700 text-slate-600 dark:text-slate-300 hover:text-slate-900 dark:hover:text-slate-100 hover:shadow-md flex items-center justify-center transition-all'
);
</script>
@@ -26,7 +26,7 @@ const buttonClass = computed(() =>
:title="isDarkTheme ? (t('theme.switchToLight') || 'Switch to light mode') : (t('theme.switchToDark') || 'Switch to dark mode')"
:aria-label="isDarkTheme ? (t('theme.switchToLight') || 'Switch to light mode') : (t('theme.switchToDark') || 'Switch to dark mode')"
>
<Sun v-if="isDarkTheme" class="w-5 h-5" />
<Moon v-else class="w-5 h-5" />
<Sun v-if="isDarkTheme" class="w-4 h-4 md:w-5 md:h-5" />
<Moon v-else class="w-4 h-4 md:w-5 md:h-5" />
</button>
</template>
+35 -18
View File
@@ -149,7 +149,7 @@ export function useChat() {
* 用途:发送消息并处理 SSE 流式响应
* 核心逻辑:
* 1. 乐观更新 UI (立即显示用户消息)
* 2. 创建空的 AI 消息占位
* 2. Create assistant message lazily only after receiving real answer chunks.
* 3. 发起 Fetch POST 请求
* 4. 获取 Reader 流式读取
* 5. 逐块解码并追加到当前 AI 消息中
@@ -165,13 +165,19 @@ export function useChat() {
});
// 1. 乐观 UI 更新:立即将用户消息推入列表
messages.value.push({ role: 'user', content: query });
// 创建一个空的 Assistant 消息用于流式追加,并记录其索引
const botMsgIndex = messages.value.push({
role: 'assistant',
content: '',
retriever_resources: [],
attribution_parts: []
}) - 1;
// Lazily create assistant message only when answer/error arrives.
let botMsgIndex: number | null = null;
const ensureBotMessage = () => {
if (botMsgIndex === null) {
botMsgIndex = messages.value.push({
role: 'assistant',
content: '',
retriever_resources: [],
attribution_parts: []
}) - 1;
}
return messages.value[botMsgIndex] || null;
};
isThinking.value = true;
@@ -232,8 +238,6 @@ export function useChat() {
try {
const data = JSON.parse(payload);
const botMsg = messages.value[botMsgIndex];
if (!botMsg) continue;
console.debug('[chat][sse] event', {
event: data?.event,
answerLength: typeof data?.answer === 'string' ? data.answer.length : 0,
@@ -241,10 +245,10 @@ export function useChat() {
conversationId: data?.conversation_id || conversationId.value,
});
if (data.event === 'message' || data.event === 'agent_message') {
// event: message LLM 返回文本块事件,即:完整的文本以分块的方式输出。
if (data.event === 'message') {
if (typeof data.answer === 'string' && data.answer.length > 0) {
// answer: LLM 返回文本块内容
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += data.answer;
console.debug('[chat][sse] append answer chunk', {
event: data.event,
@@ -252,13 +256,19 @@ export function useChat() {
total: botMsg.content.length,
});
}
applyEventMetadata(botMsg, data);
} else if (data.event === 'message_end' || data.event === 'workflow_finished') {
if (botMsgIndex !== null) {
const currentBotMsg = messages.value[botMsgIndex];
if (currentBotMsg) {
applyEventMetadata(currentBotMsg, data);
}
}
} else if (data.event === 'message_end') {
if (data.conversation_id) {
conversationId.value = data.conversation_id;
}
// Some providers may put final answer on message_end/workflow events.
if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += data.answer;
console.debug('[chat][sse] append final answer', {
event: data.event,
@@ -266,8 +276,15 @@ export function useChat() {
total: botMsg.content.length,
});
}
applyEventMetadata(botMsg, data);
if (botMsgIndex !== null) {
const currentBotMsg = messages.value[botMsgIndex];
if (currentBotMsg) {
applyEventMetadata(currentBotMsg, data);
}
}
} else if (data.event === 'error') {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += `\n[Error: ${data.message}]`;
console.error('[chat][sse] backend error event', data);
}
@@ -279,7 +296,7 @@ export function useChat() {
}
} catch (e: any) {
console.error('[chat][send] failed', e);
const botMsg = messages.value[botMsgIndex];
const botMsg = ensureBotMessage();
if (botMsg) {
botMsg.content += `\n[Error: ${e.message || 'Network Issue'}]`;
}
@@ -0,0 +1,37 @@
import { readonly, ref } from 'vue';
export type MessageLevel = 'success' | 'info' | 'warning' | 'error';
// 全局单例状态:整个应用共享一套消息弹框。
const visible = ref(false);
const level = ref<MessageLevel>('info');
const title = ref('');
const message = ref('');
export const useGlobalMessageDialog = () => {
const showMessageDialog = (
nextLevel: MessageLevel,
nextMessage: string,
nextTitle = ''
) => {
level.value = nextLevel;
title.value = nextTitle;
message.value = nextMessage;
visible.value = true;
};
const closeMessageDialog = () => {
visible.value = false;
title.value = '';
message.value = '';
};
return {
messageDialogVisible: visible,
messageDialogLevel: readonly(level),
messageDialogTitle: readonly(title),
messageDialogContent: readonly(message),
showMessageDialog,
closeMessageDialog,
};
};
+1 -1
View File
@@ -1,5 +1,5 @@
export const config = {
appTitle: 'hxai',
appTitle: 'AI工作台',
auth: {
wecom: {
enabled: true,
+58 -1
View File
@@ -138,10 +138,18 @@ const messages = {
}
},
common: {
errorOccurred: 'An error occurred'
errorOccurred: 'An error occurred',
deleteDialog: {
defaultTitle: 'Are you sure you want to delete?',
defaultMessage: 'When clicked the OK button, this dialog will be closed after 1 second',
cancel: 'Cancel',
confirm: 'OK'
}
},
workspace: {
title: 'AI Workspace',
brandTitle: 'Hexin AI Workspace',
languageLabel: 'Language',
userTitle: '{username}\'s AI Workspace',
subtitle: 'Choose an agent or click a quick question to start',
search: 'Search agents...',
@@ -156,6 +164,10 @@ const messages = {
add: 'Add Quick Question',
edit: 'Edit Quick Question',
addNew: 'Add New Quick Question',
deleteDialog: {
title: 'Are you sure you want to delete?',
message: 'When clicked the OK button, this dialog will be closed after 1 second'
},
fields: {
title: 'Title',
titlePlaceholder: 'e.g. Daily Report',
@@ -988,8 +1000,19 @@ const messages = {
phone: '手机号'
}
},
common: {
errorOccurred: '发生错误',
deleteDialog: {
defaultTitle: '您确定要删除吗?',
defaultMessage: '点击“确定”按钮后,该对话框将在 1 秒后关闭',
cancel: '取消',
confirm: '确定'
}
},
workspace: {
title: 'AI 工作台',
brandTitle: 'AI工作台',
languageLabel: '语言',
userTitle: '{username} 的 AI 工作台',
subtitle: '选择一个助手,或点击常用问题快速开始',
search: '搜索应用...',
@@ -1004,6 +1027,10 @@ const messages = {
add: '添加问题',
edit: '编辑常用问题',
addNew: '添加新常用问题',
deleteDialog: {
title: '您确定要删除吗?',
message: '点击“确定”按钮后,该对话框将在 1 秒后关闭'
},
fields: {
title: '标题',
titlePlaceholder: '例如:写日报',
@@ -1821,8 +1848,19 @@ const messages = {
inputError: '請輸入用戶名和密碼',
requestFailed: '請求失敗'
},
common: {
errorOccurred: '發生錯誤',
deleteDialog: {
defaultTitle: '您確定要刪除嗎?',
defaultMessage: '點擊「確定」按鈕後,此對話框將在 1 秒後關閉',
cancel: '取消',
confirm: '確定'
}
},
workspace: {
title: 'AI 工作台',
brandTitle: 'AI工作台',
languageLabel: '語言',
userTitle: '{username} 的 AI 工作台',
subtitle: '選擇一個助手,或點擊常用問題快速開始',
search: '搜索應用...',
@@ -1837,6 +1875,10 @@ const messages = {
add: '添加問題',
edit: '編輯常用問題',
addNew: '添加新常用問題',
deleteDialog: {
title: '您確定要刪除嗎?',
message: '點擊「確定」按鈕後,此對話框將在 1 秒後關閉'
},
fields: {
title: '標題',
titlePlaceholder: '例如:寫日報',
@@ -2659,8 +2701,19 @@ const messages = {
inputError: 'กรุณากรอกชื่อผู้ใช้และรหัสผ่าน',
requestFailed: 'คำขอล้มเหลว'
},
common: {
errorOccurred: 'เกิดข้อผิดพลาด',
deleteDialog: {
defaultTitle: 'คุณแน่ใจหรือไม่ว่าต้องการลบ?',
defaultMessage: 'เมื่อกดปุ่มตกลง กล่องโต้ตอบนี้จะปิดหลังจาก 1 วินาที',
cancel: 'ยกเลิก',
confirm: 'ตกลง'
}
},
workspace: {
title: 'พื้นที่ทำงาน AI',
brandTitle: 'Hexin AI Workspace',
languageLabel: 'ภาษา',
userTitle: 'พื้นที่ทำงาน AI ของ {username}',
subtitle: 'เลือกผู้ช่วยหรือคลิกคำถามด่วนเพื่อเริ่ม',
search: 'ค้นหาตัวแทน...',
@@ -2675,6 +2728,10 @@ const messages = {
add: 'เพิ่มคำถามด่วน',
edit: 'แก้ไขคำถามด่วน',
addNew: 'เพิ่มคำถามด่วนใหม่',
deleteDialog: {
title: 'คุณแน่ใจหรือไม่ว่าต้องการลบ?',
message: 'เมื่อกดปุ่มตกลง กล่องโต้ตอบนี้จะปิดหลังจาก 1 วินาที'
},
fields: {
title: 'หัวข้อ',
titlePlaceholder: 'เช่น รายงานประจำวัน',
+1 -1
View File
@@ -7,7 +7,7 @@ import i18n from './i18n'
import { config } from './config'
// Set document title from config
document.title = config.appTitle || 'hxai';
document.title = config.appTitle || 'AI工作台';
createApp(App)
.use(router)
+1 -1
View File
@@ -48,7 +48,7 @@ const router = createRouter({
});
router.afterEach((to) => {
const baseTitle = config.appTitle || 'hxai';
const baseTitle = config.appTitle || 'AI工作台';
if (to.meta.title) {
document.title = `${to.meta.title} - ${baseTitle}`;
} else {
+30
View File
@@ -101,6 +101,27 @@
@apply bg-white rounded-2xl border border-slate-100 shadow-soft hover:shadow-lg transition-all duration-300;
}
/* Mobile-first layout tokens for consistent spacing and density. */
.page-shell-mobile {
@apply px-3 md:px-8;
}
.section-gap-mobile {
@apply mb-3 md:mb-8;
}
.card-mobile-compact {
@apply p-3 sm:p-5;
}
.icon-box-mobile {
@apply w-8 h-8 sm:w-10 sm:h-10;
}
.icon-glyph-mobile {
@apply w-4 h-4 sm:w-6 sm:h-6;
}
.badge {
@apply px-2.5 py-0.5 rounded-full text-xs font-medium border;
}
@@ -131,6 +152,15 @@
caret-color: #0891b2;
}
.chat-composer-textarea:focus,
.chat-composer-textarea:focus-visible {
outline: none !important;
box-shadow: none !important;
border: 0 !important;
-webkit-appearance: none;
appearance: none;
}
.chat-composer-textarea::selection {
background-color: rgba(14, 165, 233, 0.2);
}
+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>