feat: Initial commit with full deployment architecture and scripts

This commit is contained in:
super committed 2026-02-24 16:45:11 +08:00
commit abb3efe114
96 files changed
+16789

No files matched your search

+64
View File
@@ -0,0 +1,64 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { watch, onMounted } from 'vue';
const { locale } = useI18n();
const getAuthHeaders = () => {
const stored = localStorage.getItem('hxops_user');
if (!stored) return {};
const user = JSON.parse(stored) as { id?: number; username: string; role: string };
const headers: Record<string, string> = {
'X-Username': user.username,
'X-Role': user.role,
};
if (user.id) {
headers['X-User-Id'] = String(user.id);
}
return headers;
};
const updateLanguagePreference = async (lang: string) => {
const headers = getAuthHeaders();
if (Object.keys(headers).length === 0) return; // Not logged in
try {
await fetch('/api/user/profile', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...headers },
body: JSON.stringify({ language: lang })
});
} catch (e) {
console.error('Failed to update language preference', e);
}
};
watch(locale, (newLang) => {
updateLanguagePreference(newLang as string);
});
onMounted(async () => {
const headers = getAuthHeaders();
if (Object.keys(headers).length > 0) {
try {
// Try to fetch profile to get language, or rely on WorkspaceView to load it?
// Since WorkspaceView loads user home which includes language now, we might want to sync from there?
// Or just fetch home here quickly.
const res = await fetch('/api/user/home', { headers });
if (res.ok) {
const data = await res.json();
if (data.user && data.user.language) {
locale.value = data.user.language;
}
}
} catch (e) {
console.error('Failed to sync language', e);
}
}
});
</script>
<template>
<router-view />
</template>
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="37.07" height="36" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 198"><path fill="#41B883" d="M204.8 0H256L128 220.8L0 0h97.92L128 51.2L157.44 0h47.36Z"></path><path fill="#41B883" d="m0 0l128 220.8L256 0h-51.2L128 132.48L50.56 0H0Z"></path><path fill="#35495E" d="M50.56 0L128 133.12L204.8 0h-47.36L128 51.2L97.92 0H50.56Z"></path></svg>

After

Width:  |  Height:  |  Size: 496 B

+41
View File
@@ -0,0 +1,41 @@
<script setup lang="ts">
import { ref } from 'vue'
defineProps<{ msg: string }>()
const count = ref(0)
</script>
<template>
<h1>{{ msg }}</h1>
<div class="card">
<button type="button" @click="count++">count is {{ count }}</button>
<p>
Edit
<code>components/HelloWorld.vue</code> to test HMR
</p>
</div>
<p>
Check out
<a href="https://vuejs.org/guide/quick-start.html#local" target="_blank"
>create-vue</a
>, the official Vue + Vite starter
</p>
<p>
Learn more about IDE Support for Vue in the
<a
href="https://vuejs.org/guide/scaling-up/tooling.html#ide-support"
target="_blank"
>Vue Docs Scaling up Guide</a
>.
</p>
<p class="read-the-docs">Click on the Vite and Vue logos to learn more</p>
</template>
<style scoped>
.read-the-docs {
color: #888;
}
</style>
+127
View File
@@ -0,0 +1,127 @@
/**
* frontend/src/composables/useChat.ts
* 文件用途:前端 SSE 聊天 Hook
* 引用文件:vue
* 逻辑关系:封装 Fetch API 处理流式响应,供 ChatView 组件使用
*/
import { ref } from 'vue';
export function useChat() {
/**
* messages: 响应式消息列表,用于 UI 渲染
* 结构: [{ role: 'user'|'assistant', content: string }]
*/
const messages = ref<any[]>([]);
/**
* isThinking: 标记 AI 是否正在生成回答,用于控制 Loading 状态和输入框禁用
*/
const isThinking = ref(false);
/**
* conversationId: 当前会话 ID
* 用于在多轮对话中关联上下文,并在反馈时找到对应 ChatLog
*/
const conversationId = ref<string | null>(null);
const getAuthHeaders = () => {
const stored = localStorage.getItem('hxops_user');
if (!stored) return {};
const user = JSON.parse(stored) as { id?: number; username: string; role: string };
const headers: Record<string, string> = {
'X-Username': user.username,
'X-Role': user.role,
};
if (user.id) {
headers['X-User-Id'] = String(user.id);
}
return headers;
};
/**
* sendMessage
* 用途:发送消息并处理 SSE 流式响应
* 核心逻辑:
* 1. 乐观更新 UI (立即显示用户消息)
* 2. 创建空的 AI 消息占位
* 3. 发起 Fetch POST 请求
* 4. 获取 Reader 流式读取
* 5. 逐块解码并追加到当前 AI 消息中
* 参数:
* query: 用户输入文本
* agentId: 目标 Agent ID
*/
const sendMessage = async (query: string, agentId: number) => {
// 1. 乐观 UI 更新:立即将用户消息推入列表
messages.value.push({ role: 'user', content: query });
// 创建一个空的 Assistant 消息用于流式追加,并记录其索引
const botMsgIndex = messages.value.push({ role: 'assistant', content: '' }) - 1;
isThinking.value = true;
try {
// 指向本地 Flask 端口 (需通过 Vite Proxy 转发到 5000)
const response = await fetch('/api/chat/completions', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
query,
agent_id: agentId,
conversation_id: conversationId.value,
})
});
if (!response.ok) {
const err = await response.json().catch(() => ({}));
throw new Error(err.error || `Request failed with status ${response.status}`);
}
// 获取 ReadableStream 读取器
const reader = response.body?.getReader();
const decoder = new TextDecoder();
if (!reader) throw new Error('No reader');
// 循环读取流数据
while (true) {
const { done, value } = await reader.read();
if (done) break;
// 解码二进制块为文本
const chunk = decoder.decode(value);
// SSE 数据可能包含多行,按双换行符分割
const lines = chunk.split('\n\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
try {
// 解析 JSON 数据
const data = JSON.parse(line.slice(6));
// 仅处理 message 事件,追加 answer 到当前消息
if (data.event === 'message') {
messages.value[botMsgIndex].content += data.answer;
} else if (data.event === 'message_end') {
// 记录会话 ID,便于后续发送反馈
if (data.conversation_id) {
conversationId.value = data.conversation_id;
}
} else if (data.event === 'error') {
messages.value[botMsgIndex].content += `\n[Error: ${data.message}]`;
}
} catch (e) {
// 忽略 JSON 解析错误 (可能是 keep-alive 或非完整 JSON)
}
}
}
}
} catch (e: any) {
console.error(e);
messages.value[botMsgIndex].content += `\n[Error: ${e.message || 'Network Issue'}]`;
} finally {
isThinking.value = false;
}
};
return { messages, isThinking, conversationId, sendMessage };
}
+1558
View File
File diff suppressed because it is too large. Load diff
+11
View File
@@ -0,0 +1,11 @@
import { createApp } from 'vue'
import './style.css'
import App from './App.vue'
import router from './router'
import i18n from './i18n'
createApp(App)
.use(router)
.use(i18n)
.mount('#app')
+37
View File
@@ -0,0 +1,37 @@
import { createRouter, createWebHistory } from 'vue-router';
import WorkspaceView from '../views/WorkspaceView.vue';
import ChatView from '../views/ChatView.vue';
import AdminView from '../views/AdminView.vue';
const routes = [
{
path: '/',
redirect: '/workspace'
},
{
path: '/workspace',
name: 'Workspace',
component: WorkspaceView
},
{
path: '/chat/:agentId',
name: 'Chat',
component: ChatView,
props: true
},
{
path: '/admin',
name: 'Admin',
component: AdminView
},
];
const router = createRouter({
history: createWebHistory(),
routes
});
export default router;
+71
View File
@@ -0,0 +1,71 @@
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap');
@tailwind base;
@tailwind components;
@tailwind utilities;
@layer base {
html {
font-family: 'Inter', system-ui, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
@apply bg-gray-50 text-slate-800;
}
h1, h2, h3, h4, h5, h6 {
@apply tracking-tight font-semibold text-slate-900;
}
}
@layer components {
.btn {
@apply px-4 py-2 rounded-xl font-medium transition-all duration-200 active:scale-95 flex items-center justify-center gap-2;
}
.btn-primary {
@apply btn bg-brand-600 text-white hover:bg-brand-700 shadow-lg shadow-brand-500/20 hover:shadow-brand-500/30;
}
.btn-secondary {
@apply btn bg-white text-slate-700 border border-slate-200 hover:bg-slate-50 hover:border-slate-300 shadow-sm;
}
.btn-ghost {
@apply btn bg-transparent text-slate-600 hover:bg-slate-100 hover:text-slate-900 shadow-none;
}
.btn-danger {
@apply btn bg-red-50 text-red-600 hover:bg-red-100 border border-transparent;
}
.input-field {
@apply w-full px-4 py-3 rounded-xl border border-slate-200 bg-white text-slate-900 placeholder-slate-400 focus:border-brand-500 focus:ring-2 focus:ring-brand-500/20 outline-none transition-all duration-200;
}
.card {
@apply bg-white rounded-2xl border border-slate-100 shadow-soft hover:shadow-lg transition-all duration-300;
}
.badge {
@apply px-2.5 py-0.5 rounded-full text-xs font-medium border;
}
}
/* Custom Scrollbar */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: transparent;
}
::-webkit-scrollbar-thumb {
@apply bg-slate-200 rounded-full;
}
::-webkit-scrollbar-thumb:hover {
@apply bg-slate-300;
}
File diff suppressed because it is too large. Load diff
+405
View File
@@ -0,0 +1,405 @@
<script setup lang="ts">
/**
* ChatView.vue
* 文件用途:单个 Agent 的对话界面
* 引用文件:vue, vue-router, lucide-vue-next, useChat 组合函数
* 逻辑关系:
* - 使用 useChat 发送消息并接收 SSE 流
* - 支持从首页携带预设问题快速发起对话
* - 在回答结束后允许用户对本次回答进行评分与意见反馈
*/
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 } from 'lucide-vue-next';
import { useRoute, useRouter } from 'vue-router';
const { t, locale } = useI18n();
const route = useRoute();
const router = useRouter();
const agentId = Number(route.params.agentId);
// Sidebar state for mobile
const isSidebarOpen = ref(false);
// 从 useChat 中解构出消息列表、思考状态、会话 ID 与发送函数
const { messages, isThinking, conversationId, sendMessage } = useChat();
const input = ref('');
const currentAgent = ref<any>(null);
interface ChatHistoryItem {
id: number;
conversation_id: string;
title: string;
created_at: string;
}
const history = ref<ChatHistoryItem[]>([]);
// 预设问题:从路由 query.preset 中读取(如果有)
const presetQuestion = computed(() => {
const q = route.query.preset;
return typeof q === 'string' ? q : '';
});
const getAuthHeaders = () => {
const stored = localStorage.getItem('hxops_user');
if (!stored) return {};
const user = JSON.parse(stored) as { id?: number; username: string; role: string };
const headers: Record<string, string> = {
'X-Username': user.username,
'X-Role': user.role,
};
if (user.id) {
headers['X-User-Id'] = String(user.id);
}
return headers;
};
/**
* handleSend
* 用途:将输入框内容发送给当前 Agent
* 核心逻辑:
* 1. 校验输入非空且当前不在思考状态
* 2. 调用 sendMessage
* 3. 清空输入框
*/
const handleSend = async () => {
if (!input.value.trim() || isThinking.value) return;
const userInput = input.value;
input.value = '';
await sendMessage(userInput, agentId);
// 发送完成后刷新历史记录,确保新会话出现
if (!conversationId.value && history.value.length === 0) {
await loadHistory();
} else if (conversationId.value) {
// Check if current conversation is in history, if not, reload
const exists = history.value.some(h => h.conversation_id === conversationId.value);
if (!exists) await loadHistory();
}
};
// 加载历史记录
const loadHistory = async () => {
try {
const res = await fetch(`/api/chat/sessions`, { headers: getAuthHeaders() });
if (res.ok) {
history.value = await res.json();
}
} catch (e) {
console.error('Failed to load history', e);
}
};
const loadConversation = async (id: string) => {
if (conversationId.value === id) return;
try {
const res = await fetch(`/api/chat/messages?conversation_id=${id}`, { headers: getAuthHeaders() });
if (res.ok) {
messages.value = await res.json();
conversationId.value = id;
// Reset feedback state
rating.value = null;
feedbackComment.value = '';
feedbackSubmitted.value = false;
}
} catch (e) {
console.error('Failed to load conversation', e);
}
};
const startNewChat = () => {
messages.value = [];
conversationId.value = null;
rating.value = null;
feedbackComment.value = '';
feedbackSubmitted.value = false;
};
// 组件挂载时,如果存在预设问题,则自动触发一次发送
onMounted(async () => {
// Fetch Agent Details
try {
const agentRes = await fetch(`/api/user/agents/${agentId}`, { headers: getAuthHeaders() });
if (agentRes.ok) {
currentAgent.value = await agentRes.json();
}
} catch (e) {
console.error('Failed to load agent details', e);
}
await loadHistory();
if (presetQuestion.value) {
input.value = presetQuestion.value;
handleSend();
}
const res = await fetch('/api/user/config', { headers: getAuthHeaders() });
if (res.ok) {
const data = await res.json();
enableFeedback.value = !!data.feedback_enabled;
}
});
/**
* 反馈相关状态
* enableFeedback:是否启用评分功能(后续可接入配置)
* rating:用户选择的评分(1-5)
* feedbackComment:用户输入的文字意见
* feedbackSubmitted:是否已经提交反馈
*/
const enableFeedback = ref(true);
const rating = ref<number | null>(null);
const feedbackComment = ref('');
const feedbackSubmitted = ref(false);
/**
* submitFeedback
* 用途:将评分与评论提交到后端 /api/chat/feedback
*/
const submitFeedback = async () => {
if (!enableFeedback.value || feedbackSubmitted.value) return;
if (!rating.value) {
alert(t('chat.feedback.selectRating'));
return;
}
const res = await fetch('/api/chat/feedback', {
method: 'POST',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({
agent_id: agentId,
score: rating.value,
comment: feedbackComment.value,
conversation_id: conversationId.value,
}),
});
if (res.ok) {
feedbackSubmitted.value = true;
}
};
</script>
<template>
<div class="flex h-screen bg-white font-sans text-slate-800">
<!-- Sidebar (History) -->
<!-- Mobile Overlay -->
<div
v-if="isSidebarOpen"
class="fixed inset-0 bg-slate-900/50 z-40 md:hidden backdrop-blur-sm transition-opacity"
@click="isSidebarOpen = false"
></div>
<aside
class="w-72 bg-slate-50 border-r border-slate-200 flex flex-col fixed inset-y-0 left-0 z-50 transition-transform duration-300 ease-in-out md:relative md:translate-x-0 shadow-xl md:shadow-none"
:class="isSidebarOpen ? 'translate-x-0' : '-translate-x-full'"
>
<div class="p-4 flex items-center justify-between">
<button @click="router.push('/workspace')" class="p-2 hover:bg-white hover:shadow-sm rounded-xl transition-all text-slate-500 hover:text-slate-900" title="Back to Workspace">
<ArrowLeft class="w-5 h-5" />
</button>
<span class="font-bold text-slate-700 tracking-tight">{{ $t('chat.history') }}</span>
<button class="p-2 hover:bg-brand-100 hover:text-brand-600 rounded-xl transition-all text-slate-500" title="New Chat" @click="startNewChat(); isSidebarOpen = false;">
<Plus class="w-5 h-5" />
</button>
</div>
<div class="px-3 pb-2">
<button @click="startNewChat(); isSidebarOpen = false;" class="w-full py-2.5 px-4 bg-brand-600 hover:bg-brand-700 text-white rounded-xl font-medium shadow-lg shadow-brand-500/20 transition-all flex items-center justify-center gap-2 mb-2">
<Plus class="w-4 h-4" /> {{ $t('chat.newChat') }}
</button>
</div>
<div class="flex-1 overflow-y-auto px-3 space-y-1 scrollbar-thin">
<div v-if="history.length === 0" class="text-center text-slate-400 text-sm py-8 italic">{{ $t('chat.noHistory') }}</div>
<button
v-for="item in history"
:key="item.id"
class="w-full text-left px-4 py-3 rounded-xl text-sm text-slate-600 hover:bg-white hover:shadow-sm truncate transition-all border border-transparent hover:border-slate-100"
:class="conversationId === item.conversation_id ? 'bg-white shadow-sm border-slate-100 text-brand-600 font-medium ring-1 ring-brand-500/10' : ''"
@click="loadConversation(item.conversation_id); isSidebarOpen = false;"
>
{{ item.title || $t('chat.newChat') }}
</button>
</div>
<!-- Language Selector & Agent Info -->
<div class="p-4 border-t border-slate-200 bg-slate-50 space-y-3">
<select
v-model="locale"
class="w-full bg-white border border-slate-200 rounded-xl px-3 py-2 text-sm shadow-sm outline-none focus:ring-2 focus:ring-brand-500/20 focus:border-brand-500 transition-all cursor-pointer"
>
<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 text-xs text-slate-400 font-mono bg-slate-100 py-1.5 rounded-lg">
<span class="w-1.5 h-1.5 rounded-full bg-green-500"></span>
{{ $t('chat.agentId') }} {{ agentId }}
</div>
</div>
</aside>
<!-- Main Chat Area -->
<div class="flex-1 flex flex-col h-full relative w-full md:w-auto overflow-hidden bg-white">
<!-- Mobile Header -->
<header class="md:hidden bg-white/80 backdrop-blur-md border-b border-slate-100 px-4 py-3 flex items-center justify-between shrink-0 z-30 sticky top-0">
<div class="flex items-center gap-3">
<button @click="router.push('/workspace')" class="p-2 hover:bg-slate-50 rounded-lg transition-colors">
<ArrowLeft class="w-5 h-5 text-slate-600" />
</button>
<span class="font-bold text-slate-900 truncate max-w-[200px]">{{ currentAgent?.name || $t('chat.defaultTitle') }}</span>
</div>
<button @click="isSidebarOpen = !isSidebarOpen" class="p-2 hover:bg-slate-50 rounded-lg transition-colors">
<Menu class="w-6 h-6 text-slate-600" />
</button>
</header>
<!-- Chat Content -->
<div v-if="!currentAgent" class="flex-1 flex flex-col items-center justify-center space-y-4">
<Loader2 class="w-10 h-10 animate-spin text-brand-500" />
<p class="text-slate-400 text-sm animate-pulse">Loading agent...</p>
</div>
<div v-else-if="currentAgent.type === 'iframe'" class="flex-1 w-full h-full bg-white relative">
<iframe
:src="currentAgent.extra_config?.iframe_url"
class="w-full h-full border-0"
allow="microphone; camera; clipboard-read; clipboard-write"
></iframe>
</div>
<template v-else>
<main class="flex-1 overflow-y-auto p-4 md:p-8 space-y-8 scroll-smooth scrollbar-thin">
<div v-if="messages.length === 0" class="flex flex-col items-center justify-center h-full text-slate-400 pb-20">
<div class="w-20 h-20 bg-gradient-to-br from-brand-500 to-brand-700 rounded-3xl flex items-center justify-center mb-8 shadow-xl shadow-brand-500/20 animate-fade-in">
<Bot class="text-white w-10 h-10" />
</div>
<h2 class="text-3xl font-bold text-slate-900 mb-3 tracking-tight">{{ $t('chat.welcome.title') }}</h2>
<p class="text-slate-500 text-lg max-w-md text-center leading-relaxed">{{ $t('chat.welcome.subtitle') }}</p>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 mt-12 w-full max-w-2xl">
<button v-for="suggestion in ['What can you do?', 'Help me write a report', 'Analyze this data', 'Creative writing']"
:key="suggestion"
@click="input = suggestion; handleSend()"
class="p-4 bg-white border border-slate-200 rounded-xl hover:border-brand-400 hover:shadow-md hover:text-brand-700 text-slate-600 text-sm font-medium transition-all text-left">
{{ suggestion }}
</button>
</div>
</div>
<div
v-for="(msg, index) in messages"
:key="index"
class="flex gap-4 max-w-4xl mx-auto group animate-slide-up"
:class="msg.role === 'user' ? 'justify-end' : ''"
>
<!-- Bot Avatar -->
<div v-if="msg.role === 'assistant'" class="w-10 h-10 rounded-xl bg-gradient-to-br from-brand-500 to-brand-700 flex items-center justify-center shrink-0 shadow-sm mt-1">
<Bot class="text-white w-6 h-6" />
</div>
<!-- Message Bubble -->
<div
class="py-3.5 px-6 rounded-2xl shadow-sm max-w-[85%] md:max-w-[75%] leading-relaxed text-[15px]"
:class="msg.role === 'user' ? 'bg-brand-600 text-white rounded-tr-sm shadow-brand-500/20' : 'bg-white border border-slate-100 text-slate-800 rounded-tl-sm shadow-slate-200/50'"
>
<div class="whitespace-pre-wrap prose prose-sm max-w-none" :class="msg.role === 'user' ? 'prose-invert' : 'prose-slate'">{{ msg.content }}</div>
</div>
<!-- User Avatar -->
<div v-if="msg.role === 'user'" class="w-10 h-10 rounded-xl bg-slate-200 flex items-center justify-center shrink-0 shadow-sm mt-1">
<User class="text-slate-500 w-6 h-6" />
</div>
</div>
<!-- Loading -->
<div v-if="isThinking" class="flex gap-4 max-w-4xl mx-auto animate-pulse">
<div class="w-10 h-10 rounded-xl bg-gradient-to-br from-brand-500 to-brand-700 flex items-center justify-center shrink-0 shadow-sm mt-1">
<Bot class="text-white w-6 h-6" />
</div>
<div class="py-3 px-5 bg-white border border-slate-100 rounded-2xl rounded-tl-sm shadow-sm flex items-center gap-3">
<div class="flex gap-1">
<span class="w-2 h-2 bg-brand-400 rounded-full animate-bounce"></span>
<span class="w-2 h-2 bg-brand-400 rounded-full animate-bounce delay-75"></span>
<span class="w-2 h-2 bg-brand-400 rounded-full animate-bounce delay-150"></span>
</div>
<span class="text-slate-400 text-sm font-medium">{{ $t('chat.thinking') }}</span>
</div>
</div>
<!-- Feedback -->
<div
v-if="enableFeedback && messages.length > 0 && !isThinking"
class="max-w-4xl mx-auto mt-8 pt-8 border-t border-slate-100"
>
<div class="flex flex-col items-center gap-4 bg-slate-50 p-6 rounded-2xl border border-slate-100">
<span class="text-sm font-medium text-slate-500">{{ $t('chat.rate') }}</span>
<div class="flex gap-3">
<button
v-for="n in 5"
:key="n"
class="w-10 h-10 rounded-full flex items-center justify-center transition-all duration-200"
:class="rating && n <= rating ? 'bg-yellow-400 text-white scale-110 shadow-md shadow-yellow-400/30' : 'bg-white border border-slate-200 text-slate-400 hover:border-yellow-400 hover:text-yellow-400'"
@click="rating = n"
>
<Star v-if="rating && n <= rating" class="w-5 h-5 fill-current" />
<span v-else class="text-sm font-bold">{{ n }}</span>
</button>
</div>
<div v-if="rating" class="w-full max-w-lg flex gap-3 mt-2 animate-fade-in">
<input
v-model="feedbackComment"
type="text"
class="flex-1 input-field py-2 text-sm"
:placeholder="$t('chat.feedback.commentPlaceholder')"
/>
<button
class="px-6 py-2 bg-brand-600 text-white text-sm font-bold rounded-xl hover:bg-brand-700 disabled:opacity-50 transition-colors shadow-lg shadow-brand-500/30"
:disabled="feedbackSubmitted"
@click="submitFeedback"
>
{{ feedbackSubmitted ? $t('chat.feedback.sent') : $t('chat.send') }}
</button>
</div>
</div>
</div>
<div class="h-24"></div> <!-- Spacer for fixed footer -->
</main>
<!-- Input Area -->
<footer class="p-4 md:p-6 bg-white/80 backdrop-blur-xl border-t border-slate-100 absolute bottom-0 left-0 right-0 z-20">
<div class="max-w-4xl mx-auto relative">
<div class="relative bg-white rounded-2xl border border-slate-200 shadow-lg shadow-slate-200/50 focus-within:ring-2 focus-within:ring-brand-500/20 focus-within:border-brand-500 transition-all duration-300">
<textarea
v-model="input"
@keydown.enter.prevent="handleSend"
rows="1"
:placeholder="$t('chat.placeholder')"
class="w-full pl-5 pr-14 py-4 bg-transparent resize-none focus:outline-none text-slate-800 placeholder-slate-400 text-[15px] leading-relaxed"
style="min-height: 56px; max-height: 200px;"
:disabled="isThinking"
></textarea>
<button
@click="handleSend"
:disabled="!input.trim() || isThinking"
class="absolute right-2 bottom-2 p-2.5 bg-brand-600 text-white rounded-xl hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed transition-all shadow-md shadow-brand-500/20 active:scale-95"
>
<Send class="w-5 h-5" />
</button>
</div>
<div class="text-center mt-3 text-xs font-medium text-slate-400">
{{ $t('chat.disclaimer') }}
</div>
</div>
</footer>
</template>
</div>
</div>
</template>
+728
View File
@@ -0,0 +1,728 @@
<script setup lang="ts">
/**
* WorkspaceView.vue
* 文件用途:用户工作台,支持自定义布局、收藏、嵌入 Agent
* 引用文件:vue, vue-router, lucide-vue-next, 后端 /api/user 接口
*/
import { ref, onMounted, computed } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import {
Settings,
LayoutGrid,
Star,
GripVertical,
Plus,
Trash2,
Edit,
ExternalLink,
Bot
} from 'lucide-vue-next';
const { t, locale } = useI18n();
const router = useRouter();
// Interfaces
interface Agent {
id: number;
name: string;
description: string;
icon_url?: string;
}
interface QuickQuestion {
id: number;
title: string;
question: string;
agent_id: number;
}
interface EmbeddedAgent {
id: number;
name: string;
iframe_url?: string;
}
interface LayoutSection {
id: string;
visible: boolean;
title?: string;
}
// State
const isLoading = ref(true);
const currentUser = ref<{ id: number; username: string; role: string; default_agent_id?: number | null } | null>(null);
const agents = ref<Agent[]>([]);
const publicAgents = ref<Agent[]>([]);
const quickQuestions = ref<QuickQuestion[]>([]);
const favoriteAgentIds = ref<number[]>([]);
const embeddedAgents = ref<EmbeddedAgent[]>([]);
const layoutSections = ref<LayoutSection[]>([
{ id: 'favorites', visible: true, title: 'workspace.favorites' },
{ id: 'quick_questions', visible: true, title: 'workspace.quickQuestions.title' },
{ id: 'embedded', visible: true, title: 'workspace.embedded' },
{ id: 'all_agents', visible: true, title: 'workspace.availableAgents' },
]);
const searchQuery = ref('');
const loginUsername = ref('');
const loginPassword = ref('');
const showRegisterModal = ref(false);
const registerForm = ref({ username: '', password: '', email: '', real_name: '', employee_id: '', phone_number: '' });
const pendingAgentId = ref<number | null>(null);
const userReport = ref<any>(null);
// Quick Question Form State
const isAddingQuestion = ref(false);
const editingQuestionId = ref<number | null>(null);
const newQuestion = ref({
title: '',
question: '',
agent_id: null as number | null
});
// Drag & Drop State
const draggedSectionIndex = ref<number | null>(null);
// Computed
const isLoggedIn = computed(() => !!currentUser.value && currentUser.value.role !== 'guest');
const favoriteAgents = computed(() => {
return agents.value.filter(a => favoriteAgentIds.value.includes(a.id));
});
const otherAgents = computed(() => {
// If we want to show ALL agents in the bottom list, just return filtered agents.
// Or if we want to exclude favorites, we can filter them out.
// Usually "All Applications" includes favorites too, or separates them.
// Let's keep all agents in the main list for completeness, or just non-favorites if preferred.
// For now, let's show all matching search.
if (!searchQuery.value.trim()) return agents.value;
const q = searchQuery.value.toLowerCase();
return agents.value.filter(
(a) => a.name.toLowerCase().includes(q) || a.description.toLowerCase().includes(q)
);
});
const filteredQuickQuestions = computed(() => {
if (!searchQuery.value.trim()) return quickQuestions.value;
const q = searchQuery.value.toLowerCase();
return quickQuestions.value.filter(
(qq) => qq.title.toLowerCase().includes(q) || qq.question.toLowerCase().includes(q)
);
});
// Methods
const getAuthHeaders = () => {
const stored = localStorage.getItem('hxops_user');
if (!stored) return {};
const user = JSON.parse(stored) as { id?: number; username: string; role: string };
const headers: Record<string, string> = {
'X-Username': user.username,
'X-Role': user.role,
};
if (user.id) {
headers['X-User-Id'] = String(user.id);
}
return headers;
};
const fetchHome = async () => {
try {
const res = await fetch('/api/user/home', { headers: getAuthHeaders() });
if (res.status === 401) {
handleLogout();
return;
}
const data = await res.json();
currentUser.value = {
id: data.user.id,
username: data.user.username,
role: data.user.role,
default_agent_id: data.user.default_agent_id
};
agents.value = data.agents || [];
quickQuestions.value = data.quick_questions || [];
favoriteAgentIds.value = data.favorite_agent_ids || [];
embeddedAgents.value = data.embedded_agents || [];
// Merge layout from backend if exists
if (data.layout && data.layout.sections) {
// Ensure all required sections exist even if backend layout is old
const backendSections = data.layout.sections as LayoutSection[];
const defaultSections = [
{ id: 'favorites', visible: true },
{ id: 'quick_questions', visible: true },
{ id: 'embedded', visible: true },
{ id: 'all_agents', visible: true },
];
// Update local layout, preserving order from backend but ensuring all keys exist
const merged: LayoutSection[] = [];
const backendIds = new Set(backendSections.map(s => s.id));
// Add backend sections
backendSections.forEach(s => {
const def = defaultSections.find(d => d.id === s.id);
merged.push({ ...def, ...s });
});
// Add missing sections
defaultSections.forEach(d => {
if (!backendIds.has(d.id)) {
merged.push(d);
}
});
layoutSections.value = merged;
}
} catch (e) {
console.error('Failed to load user home', e);
} finally {
isLoading.value = false;
}
};
const fetchPublicAgents = async () => {
try {
const res = await fetch('/api/user/public-agents');
publicAgents.value = await res.json();
} catch (e) {
console.error('Failed to load public agents', e);
}
};
const loadAuthUser = () => {
const stored = localStorage.getItem('hxops_user');
if (!stored) return;
try {
const user = JSON.parse(stored) as { id?: number; username: string; role: string };
currentUser.value = {
id: user.id || 0,
username: user.username,
role: user.role,
};
} catch (e) {
localStorage.removeItem('hxops_user');
}
};
const handleLogin = async () => {
if (!loginUsername.value.trim()) {
alert(t('login.usernameRequired'));
return;
}
try {
const res = await fetch('/api/user/login', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
username: loginUsername.value.trim(),
password: loginPassword.value
})
});
if (!res.ok) {
const err = await res.json();
alert(err.error || t('login.failed'));
return;
}
const user = await res.json();
localStorage.setItem('hxops_user', JSON.stringify(user));
await fetchHome();
if (pendingAgentId.value) {
const targetId = pendingAgentId.value;
pendingAgentId.value = null;
if (agents.value.some(a => a.id === targetId)) {
navigateToChat(targetId);
} else {
alert(t('workspace.permission.denied'));
}
}
} catch (e) {
console.error(e);
alert(t('login.requestFailed'));
}
};
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'));
return;
}
try {
const res = await fetch('/api/user/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(registerForm.value)
});
if (res.ok) {
alert(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'));
}
} catch (e) {
console.error('Register error:', e);
alert(t('register.requestFailed'));
}
};
const handleLogout = () => {
localStorage.removeItem('hxops_user');
currentUser.value = null;
agents.value = [];
quickQuestions.value = [];
favoriteAgentIds.value = [];
embeddedAgents.value = [];
userReport.value = null;
fetchPublicAgents();
};
const navigateToChat = (id: number) => {
if (!isLoggedIn.value) {
pendingAgentId.value = id;
alert(t('login.loginRequired'));
return;
}
const url = router.resolve(`/chat/${id}`).href;
window.open(url, '_blank');
};
const navigateWithQuickQuestion = (agentId: number, question: string) => {
if (!isLoggedIn.value) {
pendingAgentId.value = agentId;
alert(t('login.loginRequired'));
return;
}
const url = router.resolve({
path: `/chat/${agentId}`,
query: { preset: question },
}).href;
window.open(url, '_blank');
};
// Favorites
const toggleFavorite = async (agentId: number) => {
if (favoriteAgentIds.value.includes(agentId)) {
// Remove
await fetch(`/api/user/favorites/${agentId}`, { method: 'DELETE', headers: getAuthHeaders() });
favoriteAgentIds.value = favoriteAgentIds.value.filter(id => id !== agentId);
} else {
// Add
await fetch(`/api/user/favorites/${agentId}`, { method: 'POST', headers: getAuthHeaders() });
favoriteAgentIds.value.push(agentId);
}
};
// Quick Questions
const getAgentName = (agentId: number) => {
const agent = agents.value.find(a => a.id === agentId);
return agent ? agent.name : t('workspace.unknownAgent', 'Unknown Agent');
};
const openAddQuestionForm = () => {
isAddingQuestion.value = true;
editingQuestionId.value = null;
newQuestion.value = { title: '', question: '', agent_id: null };
};
const editQuickQuestion = (qq: QuickQuestion) => {
isAddingQuestion.value = true;
editingQuestionId.value = qq.id;
newQuestion.value = {
title: qq.title,
question: qq.question,
agent_id: qq.agent_id
};
};
const cancelAddQuestion = () => {
isAddingQuestion.value = false;
editingQuestionId.value = null;
newQuestion.value = { title: '', question: '', agent_id: null };
};
const saveQuickQuestion = async () => {
if (!newQuestion.value.title || !newQuestion.value.question || !newQuestion.value.agent_id) {
alert(t('workspace.quickQuestions.addTitle') + ' (Please fill all fields)');
return;
}
const url = editingQuestionId.value
? `/api/user/quick-questions/${editingQuestionId.value}`
: '/api/user/quick-questions';
const method = editingQuestionId.value ? 'PUT' : 'POST';
const res = await fetch(url, {
method: method,
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify(newQuestion.value),
});
if (res.ok) {
await fetchHome();
isAddingQuestion.value = false;
editingQuestionId.value = null;
} else {
alert(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() });
await fetchHome();
};
// Drag & Drop
const onDragStart = (index: number) => {
draggedSectionIndex.value = index;
};
const onDragOver = (event: DragEvent) => {
event.preventDefault();
};
const onDrop = async (index: number) => {
if (draggedSectionIndex.value === null) return;
const draggedItem = layoutSections.value[draggedSectionIndex.value];
if (!draggedItem) return;
layoutSections.value.splice(draggedSectionIndex.value, 1);
layoutSections.value.splice(index, 0, draggedItem);
draggedSectionIndex.value = null;
// Save layout
await fetch('/api/user/homepage-layout', {
method: 'PUT',
headers: { 'Content-Type': 'application/json', ...getAuthHeaders() },
body: JSON.stringify({ layout: { sections: layoutSections.value } })
});
};
onMounted(async () => {
loadAuthUser();
if (currentUser.value && currentUser.value.role !== 'guest') {
await fetchHome();
} else {
await fetchPublicAgents();
isLoading.value = false;
}
});
</script>
<template>
<div class="min-h-screen bg-gray-50 font-sans text-slate-800">
<!-- Header (Logged In) -->
<header v-if="isLoggedIn" class="sticky top-0 z-30 bg-white/80 backdrop-blur-md border-b border-gray-100 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" />
</div>
<div>
<h1 class="text-xl font-bold text-slate-900 tracking-tight">
{{ currentUser ? $t('workspace.userTitle', { username: currentUser.username }) : $t('workspace.title') }}
</h1>
<p class="text-slate-500 text-xs font-medium">{{ $t('workspace.subtitle') }}</p>
</div>
</div>
<div class="flex items-center gap-3">
<select v-model="locale" class="bg-white border border-slate-200 rounded-xl px-3 py-2 text-sm font-medium text-slate-600 outline-none focus:ring-2 focus:ring-brand-500/20 focus:border-brand-500 transition-all cursor-pointer hover:bg-slate-50">
<option value="en">English</option>
<option value="zh-CN">简体中文</option>
<option value="zh-TW">繁體中文</option>
<option value="th">ไทย</option>
</select>
<button v-if="currentUser?.role === 'admin'" @click="router.push('/admin')" class="btn-secondary">
<Settings class="w-4 h-4 mr-2" /> {{ $t('admin.title') }}
</button>
<button @click="handleLogout" class="btn-ghost hover:text-red-600 hover:bg-red-50">{{ $t('workspace.logout') }}</button>
</div>
</div>
</header>
<main class="max-w-7xl mx-auto px-4 md:px-8 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">
<div class="h-40 bg-gray-200 rounded-2xl"></div>
<div class="h-40 bg-gray-200 rounded-2xl"></div>
<div class="h-40 bg-gray-200 rounded-2xl"></div>
</div>
</div>
<!-- Not Logged In (Login Screen) -->
<div v-else-if="!isLoggedIn" class="min-h-[calc(100vh-4rem)] flex items-center justify-center -mt-16 md:-mt-20">
<div class="w-full max-w-6xl grid grid-cols-1 lg:grid-cols-2 gap-12 items-center p-4">
<!-- Hero Section -->
<div class="hidden lg:block space-y-8 animate-slide-up">
<div class="inline-flex items-center gap-2 px-3 py-1 rounded-full bg-brand-50 text-brand-600 text-sm font-medium border border-brand-100">
<span class="relative flex h-2 w-2">
<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-brand-400 opacity-75"></span>
<span class="relative inline-flex rounded-full h-2 w-2 bg-brand-500"></span>
</span>
Enterprise AI Gateway
</div>
<h1 class="text-5xl font-bold text-slate-900 leading-tight">
Unleash the Power of <br/>
<span class="text-transparent bg-clip-text bg-gradient-to-r from-brand-600 to-purple-600">Generative AI</span>
</h1>
<p class="text-lg text-slate-600 max-w-md leading-relaxed">
Access a suite of powerful AI agents tailored for your enterprise needs. Secure, scalable, and intelligent.
</p>
<div class="grid grid-cols-2 gap-4">
<div v-for="agent in publicAgents.slice(0, 4)" :key="agent.id"
class="bg-white p-4 rounded-xl border border-slate-100 shadow-sm flex items-center gap-3">
<div class="w-10 h-10 bg-brand-50 rounded-lg flex items-center justify-center text-brand-600 shrink-0">
<Bot class="w-5 h-5" />
</div>
<div class="truncate">
<div class="font-semibold text-slate-900 text-sm truncate">{{ agent.name }}</div>
<div class="text-xs text-slate-500 truncate">AI Assistant</div>
</div>
</div>
</div>
</div>
<!-- Login Card -->
<div class="w-full max-w-md mx-auto">
<div class="bg-white rounded-3xl border border-slate-100 shadow-xl shadow-brand-900/5 p-8 md:p-10 animate-fade-in">
<div class="text-center mb-8">
<div class="w-12 h-12 bg-brand-600 rounded-xl mx-auto flex items-center justify-center text-white shadow-lg shadow-brand-600/30 mb-4 lg:hidden">
<Bot class="w-7 h-7" />
</div>
<h2 class="text-2xl font-bold text-slate-900">{{ $t('login.submit') }}</h2>
<p class="text-slate-500 text-sm mt-2">Welcome back! Please enter your details.</p>
</div>
<div class="space-y-5">
<div class="space-y-1.5">
<label class="text-xs font-semibold text-slate-700 uppercase ml-1">{{ $t('login.username') }}</label>
<input v-model="loginUsername" type="text" class="input-field" placeholder="Enter your username" />
</div>
<div class="space-y-1.5">
<label class="text-xs font-semibold text-slate-700 uppercase ml-1">{{ $t('login.password') }}</label>
<input v-model="loginPassword" type="password" class="input-field" placeholder="••••••••" />
</div>
<button @click="handleLogin" class="btn-primary w-full py-3 text-base shadow-brand-500/40 hover:shadow-brand-500/50 transform hover:-translate-y-0.5 transition-all">
{{ $t('login.submit') }}
</button>
<div class="text-center pt-2">
<span class="text-sm text-slate-500">Don't have an account? </span>
<button @click="showRegisterModal = true" class="text-sm font-semibold text-brand-600 hover:text-brand-700 hover:underline transition-colors">{{ $t('login.register') }}</button>
</div>
</div>
<!-- Language Selector for Login -->
<div class="mt-8 pt-6 border-t border-slate-100 flex justify-center">
<select v-model="locale" class="bg-transparent text-xs font-medium text-slate-400 hover:text-slate-600 cursor-pointer outline-none text-center">
<option value="en">English</option>
<option value="zh-CN">简体中文</option>
<option value="zh-TW">繁體中文</option>
<option value="th">ไทย</option>
</select>
</div>
</div>
</div>
</div>
</div>
<!-- Logged In Layout -->
<div v-else class="space-y-8 animate-fade-in">
<!-- Draggable Sections -->
<div
v-for="(section, index) in layoutSections"
:key="section.id"
class="bg-transparent md:bg-white md:rounded-3xl md:border md:border-slate-100 md:p-8 md:shadow-soft relative group transition-all"
:class="{ 'opacity-50 border-brand-300 border-dashed': draggedSectionIndex === index }"
draggable="true"
@dragstart="onDragStart(index)"
@dragover="onDragOver"
@drop="onDrop(index)"
>
<!-- Drag Handle -->
<div class="absolute left-2 top-8 cursor-move opacity-0 group-hover:opacity-100 p-2 text-slate-300 hover:text-slate-500 transition-opacity hidden md:block">
<GripVertical class="w-5 h-5" />
</div>
<!-- Section Content -->
<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">
<div class="p-2 rounded-lg" :class="{
'bg-yellow-50 text-yellow-600': section.id === 'favorites',
'bg-brand-50 text-brand-600': section.id === 'quick_questions',
'bg-purple-50 text-purple-600': section.id === 'embedded',
'bg-slate-100 text-slate-600': section.id === 'all_agents'
}">
<component :is="section.id === 'favorites' ? Star : (section.id === 'embedded' ? Bot : LayoutGrid)" class="w-5 h-5" />
</div>
{{ $t(section.title || section.id) }}
</h2>
<!-- Actions for Quick Questions -->
<button v-if="section.id === 'quick_questions' && !isAddingQuestion" @click="openAddQuestionForm" class="btn-ghost text-sm text-brand-600 hover:text-brand-700 hover:bg-brand-50">
<Plus class="w-4 h-4" /> {{ $t('workspace.quickQuestions.add') }}
</button>
</div>
<!-- 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 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" />
</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>
<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>
</div>
</div>
</div>
<!-- Content: Quick Questions -->
<div v-if="section.id === 'quick_questions'">
<!-- Add Question Form -->
<div v-if="isAddingQuestion" class="mb-6 p-6 bg-slate-50 border border-slate-200 rounded-2xl space-y-4 animate-fade-in">
<h3 class="font-bold text-slate-800">{{ editingQuestionId ? $t('workspace.quickQuestions.edit') : $t('workspace.quickQuestions.addNew') }}</h3>
<div class="grid grid-cols-1 md:grid-cols-2 gap-5">
<div class="space-y-1.5">
<label class="text-xs font-semibold text-slate-500 uppercase">{{ $t('workspace.quickQuestions.fields.title') }}</label>
<input v-model="newQuestion.title" class="input-field" :placeholder="$t('workspace.quickQuestions.fields.titlePlaceholder')" />
</div>
<div class="space-y-1.5">
<label class="text-xs font-semibold text-slate-500 uppercase">{{ $t('workspace.quickQuestions.fields.targetAgent') }}</label>
<select v-model="newQuestion.agent_id" class="input-field" :disabled="agents.length === 0">
<option :value="null" disabled>{{ agents.length === 0 ? $t('workspace.noAgents') : $t('workspace.quickQuestions.fields.selectAgent') }}</option>
<option v-for="agent in agents" :key="agent.id" :value="agent.id">{{ agent.name }}</option>
</select>
</div>
<div class="col-span-1 md:col-span-2 space-y-1.5">
<label class="text-xs font-semibold text-slate-500 uppercase">{{ $t('workspace.quickQuestions.fields.content') }}</label>
<textarea v-model="newQuestion.question" rows="3" class="input-field" :placeholder="$t('workspace.quickQuestions.fields.contentPlaceholder')"></textarea>
</div>
</div>
<div class="flex justify-end gap-3 pt-2">
<button @click="cancelAddQuestion" class="btn-secondary">{{ $t('workspace.cancel') }}</button>
<button @click="saveQuickQuestion" class="btn-primary">{{ $t('workspace.save') }}</button>
</div>
</div>
<div v-if="filteredQuickQuestions.length === 0 && !isAddingQuestion" class="text-slate-400 text-sm italic py-8 text-center bg-slate-50 rounded-xl border border-dashed border-slate-200">{{ $t('workspace.quickQuestions.noDefined') }}</div>
<div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4">
<div v-for="qq in filteredQuickQuestions" :key="qq.id"
@click="navigateWithQuickQuestion(qq.agent_id, qq.question)"
class="group/item p-4 bg-white border border-slate-200 rounded-xl hover:border-brand-500 hover:shadow-md transition-all cursor-pointer flex flex-col gap-3 relative h-full">
<div class="flex justify-between items-start">
<h4 class="font-bold text-slate-900 group-hover/item:text-brand-600 transition-colors">{{ qq.title }}</h4>
<span class="text-[10px] font-bold px-2 py-0.5 bg-slate-100 text-slate-600 rounded-full uppercase tracking-wide">
{{ getAgentName(qq.agent_id) }}
</span>
</div>
<p class="text-sm text-slate-600 line-clamp-2 leading-relaxed">{{ qq.question }}</p>
<div class="absolute top-2 right-2 flex gap-1 opacity-0 group-hover/item:opacity-100 transition-opacity bg-white/90 backdrop-blur-sm p-1 rounded-lg">
<button @click.stop="editQuickQuestion(qq)" class="p-1.5 rounded-lg text-slate-400 hover:text-brand-600 hover:bg-brand-50 transition-colors">
<Edit class="w-4 h-4" />
</button>
<button @click.stop="removeQuickQuestion(qq.id)" class="p-1.5 rounded-lg text-slate-400 hover:text-red-600 hover:bg-red-50 transition-colors">
<Trash2 class="w-4 h-4" />
</button>
</div>
</div>
</div>
</div>
<!-- Content: Embedded Agents -->
<div v-if="section.id === 'embedded'">
<div v-if="embeddedAgents.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.embedded.noData') }}</div>
<div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
<div v-for="agent in embeddedAgents" :key="agent.id" class="border border-slate-200 rounded-2xl overflow-hidden bg-white shadow-sm hover:shadow-md transition-shadow h-[500px] flex flex-col">
<div class="bg-slate-50 px-4 py-3 text-sm font-bold text-slate-700 flex justify-between items-center border-b border-slate-100">
<span>{{ agent.name }}</span>
<a :href="`/chat/${agent.id}`" target="_blank" class="text-brand-600 hover:text-brand-700 hover:bg-brand-50 p-1.5 rounded-lg transition-colors"><ExternalLink class="w-4 h-4"/></a>
</div>
<iframe v-if="agent.iframe_url" :src="agent.iframe_url" class="w-full flex-1 border-none bg-white"></iframe>
<div v-else class="flex items-center justify-center flex-1 text-slate-400 bg-slate-50/50">{{ $t('workspace.embedded.noUrl') }}</div>
</div>
</div>
</div>
<!-- Content: All Agents -->
<div v-if="section.id === 'all_agents'">
<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>
<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>
</div>
</div>
</div>
</div>
</div>
</div>
</main>
<!-- Register Modal -->
<div v-if="showRegisterModal" class="fixed inset-0 bg-slate-900/40 backdrop-blur-sm flex items-center justify-center z-50 p-4 animate-fade-in">
<div class="bg-white rounded-3xl shadow-2xl w-full max-w-md p-8 animate-slide-up">
<h3 class="text-xl font-bold text-slate-900 mb-6 text-center">{{ $t('register.title') }}</h3>
<div class="space-y-4">
<input v-model="registerForm.real_name" :placeholder="$t('register.fields.realName')" class="input-field" />
<input v-model="registerForm.employee_id" :placeholder="$t('register.fields.employeeId')" class="input-field" />
<input v-model="registerForm.phone_number" :placeholder="$t('register.fields.phone')" class="input-field" />
<input v-model="registerForm.username" :placeholder="$t('register.username')" class="input-field" />
<input v-model="registerForm.email" :placeholder="$t('register.email')" class="input-field" />
<input v-model="registerForm.password" type="password" :placeholder="$t('register.password')" class="input-field" />
</div>
<div class="flex justify-end gap-3 mt-8">
<button @click="showRegisterModal = false" class="btn-secondary">{{ $t('register.cancel') }}</button>
<button @click="handleRegister" class="btn-primary">{{ $t('register.submit') }}</button>
</div>
</div>
</div>
</div>
</template>
<style scoped>
/* Scoped styles removed in favor of global utilities in style.css */
</style>
+6
View File
@@ -0,0 +1,6 @@
/// <reference types="vite/client" />
declare module "*.vue" {
import type { DefineComponent } from "vue"
const component: DefineComponent<{}, {}, any>
export default component
}