260304调整

This commit is contained in:
super committed 2026-03-04 22:48:05 +08:00
1 parent b48f1e592a
commit a0c8721fbb
16 files changed
+1382 -291

No files matched your search

+143 -40
View File
@@ -13,16 +13,28 @@
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 { Send, User, 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';
const { t, locale } = useI18n();
const renderMarkdown = (text: string) => {
if (!text) return '';
try {
return marked.parse(text);
} catch (e) {
return text;
}
};
const route = useRoute();
const router = useRouter();
const agentId = Number(route.params.agentId);
// Sidebar state for mobile
const isSidebarOpen = ref(false);
const copiedIndex = ref<number | null>(null);
// 从 useChat 中解构出消息列表、思考状态、会话 ID 与发送函数
const { messages, isThinking, conversationId, sendMessage } = useChat();
@@ -44,34 +56,41 @@ const presetQuestion = computed(() => {
});
const getAuthHeaders = () => {
const stored = localStorage.getItem('hxops_user');
let stored = localStorage.getItem('hxops_user');
if (!stored) stored = sessionStorage.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);
try {
const data = JSON.parse(stored);
const user = data.user || data;
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;
} catch (e) {
return {};
}
return headers;
};
/**
* handleSend
* 用途:将输入框内容发送给当前 Agent
* 核心逻辑:
* 1. 校验输入非空且当前不在思考状态
* 2. 调用 sendMessage
* 3. 清空输入框
*/
const handleSend = async () => {
if (!input.value.trim() || isThinking.value) return;
const userInput = input.value;
input.value = '';
const handleSend = async (textOrEvent?: string | Event) => {
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || input.value;
if (!content.trim() || isThinking.value) return;
await sendMessage(userInput, agentId);
// Clear input if sending from input box (not resending/regenerating)
if (typeof textOrEvent !== 'string') input.value = '';
await sendMessage(content, agentId);
// 发送完成后刷新历史记录,确保新会话出现
if (!conversationId.value && history.value.length === 0) {
@@ -83,10 +102,29 @@ const handleSend = async () => {
}
};
const copyToClipboard = async (text: string, index: number) => {
try {
await navigator.clipboard.writeText(text);
copiedIndex.value = index;
setTimeout(() => {
copiedIndex.value = null;
}, 2000);
} catch (err) {
console.error('Failed to copy:', err);
}
};
const regenerate = () => {
const lastUserMsg = [...messages.value].reverse().find(m => m.role === 'user');
if (lastUserMsg) {
handleSend(lastUserMsg.content);
}
};
// 加载历史记录
const loadHistory = async () => {
try {
const res = await fetch(`/api/chat/sessions`, { headers: getAuthHeaders() });
const res = await fetch(`/api/chat/sessions?agent_id=${agentId}`, { headers: getAuthHeaders() });
if (res.ok) {
history.value = await res.json();
}
@@ -99,7 +137,7 @@ const loadConversation = async (id: string) => {
if (conversationId.value === id) return;
try {
const res = await fetch(`/api/chat/messages?conversation_id=${id}`, { headers: getAuthHeaders() });
const res = await fetch(`/api/chat/messages?conversation_id=${id}&agent_id=${agentId}`, { headers: getAuthHeaders() });
if (res.ok) {
messages.value = await res.json();
conversationId.value = id;
@@ -122,17 +160,27 @@ const startNewChat = () => {
feedbackSubmitted.value = false;
};
// 组件挂载时,如果存在预设问题,则自动触发一次发送
onMounted(async () => {
// Fetch Agent Details
const loadAgent = async () => {
try {
const agentRes = await fetch(`/api/user/agents/${agentId}`, { headers: getAuthHeaders() });
if (agentRes.ok) {
currentAgent.value = await agentRes.json();
const res = await fetch(`/api/user/agents/${agentId}`, { headers: getAuthHeaders() });
if (res.ok) {
currentAgent.value = await res.json();
} else {
if (res.status === 403) {
alert(t('workspace.permission.denied') || 'Access denied');
router.push('/');
return;
}
currentAgent.value = { name: t('workspace.unknownAgent') };
}
} catch (e) {
console.error('Failed to load agent details', e);
console.error('Failed to load agent', e);
}
};
// 组件挂载时,如果存在预设问题,则自动触发一次发送
onMounted(async () => {
await loadAgent();
await loadHistory();
@@ -140,11 +188,8 @@ onMounted(async () => {
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;
}
// Use config from config.ts instead of API
enableFeedback.value = config.workspace.enableFeedback;
});
/**
@@ -264,7 +309,7 @@ const submitFeedback = async () => {
<!-- 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>
<p class="text-slate-400 text-sm animate-pulse">{{ $t('chat.loadingAgent') }}</p>
</div>
<div v-else-if="currentAgent.type === 'iframe'" class="flex-1 w-full h-full bg-white relative">
@@ -285,7 +330,12 @@ const submitFeedback = async () => {
<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']"
<button v-for="suggestion in (currentAgent.suggested_questions && currentAgent.suggested_questions.length > 0 ? currentAgent.suggested_questions : [
$t('chat.suggestions.whatCanYouDo'),
$t('chat.suggestions.helpWriteReport'),
$t('chat.suggestions.analyzeData'),
$t('chat.suggestions.creativeWriting')
])"
:key="suggestion"
@click="input = suggestion; handleSend()"
class="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">
@@ -306,11 +356,64 @@ const submitFeedback = async () => {
</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 class="flex flex-col max-w-[85%] md:max-w-[75%]">
<div
class="py-3.5 px-6 rounded-2xl shadow-sm 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
v-if="msg.role === 'user'"
class="whitespace-pre-wrap prose prose-sm max-w-none text-white prose-invert"
>{{ msg.content }}</div>
<div
v-else
class="prose prose-sm max-w-none text-slate-800 prose-headings:font-bold prose-a:text-brand-600 prose-code:bg-slate-100 prose-code:text-brand-600 prose-code:px-1 prose-code:rounded prose-pre:bg-slate-800 prose-pre:text-slate-100"
v-html="renderMarkdown(msg.content)"
></div>
</div>
<!-- Message Actions -->
<div
class="flex items-center gap-1 mt-1 opacity-0 group-hover:opacity-100 transition-opacity"
:class="msg.role === 'user' ? 'justify-end text-slate-400' : 'justify-start text-slate-400'"
>
<button
@click="copyToClipboard(msg.content, index)"
class="p-1 hover:bg-slate-100 rounded text-xs flex items-center gap-1 transition-colors"
:title="$t('chat.actions.copy')"
>
<Check v-if="copiedIndex === index" class="w-3.5 h-3.5 text-green-500" />
<Copy v-else class="w-3.5 h-3.5" />
</button>
<template v-if="msg.role === 'user'">
<button
@click="input = msg.content"
class="p-1 hover:bg-slate-100 rounded text-xs transition-colors"
:title="$t('chat.actions.edit')"
>
<Edit2 class="w-3.5 h-3.5" />
</button>
<button
@click="handleSend(msg.content)"
class="p-1 hover:bg-slate-100 rounded text-xs transition-colors"
:title="$t('chat.actions.resend')"
>
<RotateCw class="w-3.5 h-3.5" />
</button>
</template>
<template v-else>
<button
v-if="index === messages.length - 1 && !isThinking"
@click="regenerate"
class="p-1 hover:bg-slate-100 rounded text-xs transition-colors"
:title="$t('chat.actions.regenerate')"
>
<RotateCw class="w-3.5 h-3.5" />
</button>
</template>
</div>
</div>
<!-- User Avatar -->