mirror of
https://gitee.com/JavaLionLi/plus-ui.git
synced 2026-09-13 07:43:43 +08:00
add 增加 snail-ai-server 控制台访问菜单
update 优化将自行实现的ai聊天室页面改为内嵌 snail-ai 自带的聊天室页面
This commit is contained in:
parent
d3027b6927
commit
6030831f55
@ -17,6 +17,9 @@ VITE_APP_MONITOR_ADMIN = 'http://localhost:9090/admin/applications'
|
||||
# SnailJob 控制台地址
|
||||
VITE_APP_SNAILJOB_ADMIN = 'http://localhost:8800/snail-job'
|
||||
|
||||
# SnailAI 控制台地址
|
||||
VITE_APP_SNAILAI_ADMIN = 'http://localhost:8900/snail-ai'
|
||||
|
||||
VITE_APP_PORT = 80
|
||||
|
||||
# 接口加密功能开关(如需关闭 后端也必须对应关闭)
|
||||
|
||||
@ -14,6 +14,9 @@ VITE_APP_MONITOR_ADMIN = '/admin/applications'
|
||||
# SnailJob 控制台地址
|
||||
VITE_APP_SNAILJOB_ADMIN = '/snail-job'
|
||||
|
||||
# SnailAI 控制台地址
|
||||
VITE_APP_SNAILAI_ADMIN = '/snail-ai'
|
||||
|
||||
# 生产环境
|
||||
VITE_APP_BASE_API = '/prod-api'
|
||||
|
||||
|
||||
@ -1,62 +1,6 @@
|
||||
import type { AxiosPromise } from '@/utils/api-types';
|
||||
import request, { globalHeaders } from '@/utils/request';
|
||||
import { getLanguage } from '@/lang';
|
||||
import type {
|
||||
AgentChatRequest,
|
||||
AgentChatSyncResponse,
|
||||
AgentItem,
|
||||
ConversationMessage,
|
||||
ConversationSummaryItem,
|
||||
ConversationSummaryList,
|
||||
SnailOpenApiUser
|
||||
} from './types';
|
||||
|
||||
export const fetchMyAgents = (): AxiosPromise<AgentItem[]> => {
|
||||
return request({
|
||||
url: '/snail-ai/agents',
|
||||
method: 'get'
|
||||
});
|
||||
};
|
||||
|
||||
export const fetchAgentDetail = (id: number): AxiosPromise<AgentItem> => {
|
||||
return request({
|
||||
url: `/snail-ai/agent/${id}`,
|
||||
method: 'get'
|
||||
});
|
||||
};
|
||||
|
||||
export const fetchAgentConversations = (
|
||||
id: number,
|
||||
params: { page?: number; size?: number; start?: string; end?: string }
|
||||
): AxiosPromise<ConversationSummaryList> => {
|
||||
return request({
|
||||
url: `/snail-ai/agent/${id}/conversations`,
|
||||
method: 'get',
|
||||
params
|
||||
});
|
||||
};
|
||||
|
||||
export const fetchConversationMessages = (agentId: number, conversationId: string): AxiosPromise<ConversationMessage[]> => {
|
||||
return request({
|
||||
url: `/snail-ai/agent/${agentId}/conversation/${conversationId}/messages`,
|
||||
method: 'get'
|
||||
});
|
||||
};
|
||||
|
||||
export const createConversation = (agentId: number, data: { title?: string }): AxiosPromise<ConversationSummaryItem> => {
|
||||
return request({
|
||||
url: `/snail-ai/agent/${agentId}/conversation`,
|
||||
method: 'post',
|
||||
data
|
||||
});
|
||||
};
|
||||
|
||||
export const deleteConversation = (agentId: number, conversationId: string): AxiosPromise<void> => {
|
||||
return request({
|
||||
url: `/snail-ai/agent/${agentId}/conversation/${conversationId}`,
|
||||
method: 'delete'
|
||||
});
|
||||
};
|
||||
import request from '@/utils/request';
|
||||
import type { SnailOpenApiUser } from './types';
|
||||
|
||||
export const registerCurrentSnailUser = (): AxiosPromise<SnailOpenApiUser> => {
|
||||
return request({
|
||||
@ -64,99 +8,3 @@ export const registerCurrentSnailUser = (): AxiosPromise<SnailOpenApiUser> => {
|
||||
method: 'post'
|
||||
});
|
||||
};
|
||||
|
||||
export const fetchChatMode = (): AxiosPromise<{ mode?: 'stream' | 'sync' }> => {
|
||||
return request({
|
||||
url: '/snail-ai/chat/mode',
|
||||
method: 'get'
|
||||
});
|
||||
};
|
||||
|
||||
export const fetchAgentChat = async (
|
||||
agentId: number,
|
||||
data: AgentChatRequest,
|
||||
options: {
|
||||
onMessage: (chunk: string) => void;
|
||||
onThinking?: (chunk: string) => void;
|
||||
onDone: () => void;
|
||||
onError: (error: Error) => void;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
): Promise<void> => {
|
||||
const baseURL = import.meta.env.VITE_APP_BASE_API;
|
||||
|
||||
await fetch(`${baseURL}/snail-ai/agent/${agentId}/chat/stream`, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
...globalHeaders(),
|
||||
'Content-Language': getLanguage(),
|
||||
Accept: 'text/event-stream',
|
||||
'Content-Type': 'application/json;charset=utf-8'
|
||||
},
|
||||
body: JSON.stringify(data),
|
||||
signal: options.signal
|
||||
})
|
||||
.then(async response => {
|
||||
if (!response.ok) {
|
||||
const text = await response.text();
|
||||
throw new Error(text || `HTTP ${response.status}`);
|
||||
}
|
||||
|
||||
const reader = response.body?.getReader();
|
||||
if (!reader) {
|
||||
throw new Error('ReadableStream not supported');
|
||||
}
|
||||
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
const eventBlocks = buffer.split(/\r?\n\r?\n/);
|
||||
buffer = eventBlocks.pop() || '';
|
||||
|
||||
for (const block of eventBlocks) {
|
||||
if (!block.trim()) continue;
|
||||
let eventName = 'message';
|
||||
let payload = '';
|
||||
for (const line of block.split(/\r?\n/)) {
|
||||
if (line.startsWith('event:')) {
|
||||
eventName = line.slice(6).trim();
|
||||
} else if (line.startsWith('data:')) {
|
||||
payload += line.slice(5).trim();
|
||||
}
|
||||
}
|
||||
if (!payload && eventName !== 'done') continue;
|
||||
if (eventName === 'thinking') {
|
||||
options.onThinking?.(payload);
|
||||
} else if (eventName === 'text') {
|
||||
options.onMessage(payload);
|
||||
} else if (eventName === 'done') {
|
||||
options.onDone();
|
||||
return;
|
||||
} else if (eventName === 'error') {
|
||||
throw new Error(payload || 'SSE stream error');
|
||||
} else {
|
||||
options.onMessage(payload);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
options.onDone();
|
||||
})
|
||||
.catch((error: Error) => {
|
||||
if (error.name !== 'AbortError') {
|
||||
options.onError(error);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const fetchAgentChatSync = (agentId: number, data: AgentChatRequest): AxiosPromise<AgentChatSyncResponse> => {
|
||||
return request({
|
||||
url: `/snail-ai/agent/${agentId}/chat/sync`,
|
||||
method: 'post',
|
||||
data
|
||||
});
|
||||
};
|
||||
|
||||
@ -1,46 +1,3 @@
|
||||
import type { PageResult } from '@/api/types';
|
||||
|
||||
export interface AgentItem {
|
||||
id: number;
|
||||
name: string;
|
||||
description?: string;
|
||||
avatar?: string;
|
||||
greeting?: string;
|
||||
status?: number;
|
||||
presetQuestions?: string[];
|
||||
}
|
||||
|
||||
export interface ConversationSummaryItem {
|
||||
conversationId: string;
|
||||
agentId?: number;
|
||||
title: string;
|
||||
lastMessageDt?: string;
|
||||
createDt?: string;
|
||||
updateDt?: string;
|
||||
}
|
||||
|
||||
export type ConversationSummaryList = PageResult<ConversationSummaryItem>;
|
||||
|
||||
export interface ConversationMessage {
|
||||
role?: string;
|
||||
content?: string;
|
||||
thinking?: string;
|
||||
}
|
||||
|
||||
export interface AgentChatRequest {
|
||||
conversationId?: string;
|
||||
content: string;
|
||||
disabledMcpServerIds?: number[];
|
||||
disabledSkillIds?: number[];
|
||||
}
|
||||
|
||||
export interface AgentChatSyncResponse {
|
||||
conversationId?: string;
|
||||
content?: string;
|
||||
traceId?: string;
|
||||
durationMs?: number;
|
||||
}
|
||||
|
||||
export interface SnailOpenApiUser {
|
||||
openId: string;
|
||||
nickname?: string;
|
||||
|
||||
1
src/types/env.d.ts
vendored
1
src/types/env.d.ts
vendored
@ -16,6 +16,7 @@ interface ImportMetaEnv {
|
||||
VITE_APP_CONTEXT_PATH: string;
|
||||
VITE_APP_MONITOR_ADMIN: string;
|
||||
VITE_APP_SNAILJOB_ADMIN: string;
|
||||
VITE_APP_SNAILAI_ADMIN: string;
|
||||
VITE_APP_ENV: string;
|
||||
VITE_APP_ENCRYPT: string;
|
||||
VITE_APP_RSA_PUBLIC_KEY: string;
|
||||
|
||||
@ -1,168 +1,58 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, ref } from 'vue';
|
||||
import { deleteConversation, fetchAgentConversations, fetchMyAgents, registerCurrentSnailUser } from '@/api/ai/agent';
|
||||
import type { AgentItem, ConversationSummaryItem } from '@/api/ai/agent/types';
|
||||
import { ElMessage, ElMessageBox } from 'element-plus';
|
||||
import ChatMain from './modules/chat-main.vue';
|
||||
import ChatSidebar from './modules/chat-sidebar.vue';
|
||||
import { registerCurrentSnailUser } from '@/api/ai/agent';
|
||||
import { getToken } from '@/utils/auth';
|
||||
|
||||
defineOptions({ name: 'AiChatPage' });
|
||||
|
||||
const agents = ref<AgentItem[]>([]);
|
||||
const conversations = ref<ConversationSummaryItem[]>([]);
|
||||
const currentAgent = ref<AgentItem | null>(null);
|
||||
const currentConversationId = ref('');
|
||||
const currentNickname = ref('');
|
||||
const chatUrl = ref('');
|
||||
const loadError = ref('');
|
||||
const loading = ref(false);
|
||||
const baseUrl = import.meta.env.VITE_APP_BASE_API;
|
||||
|
||||
function normalizeAgentList(payload: any): AgentItem[] {
|
||||
const container = payload?.data ?? payload;
|
||||
const source =
|
||||
(Array.isArray(container) && container) ||
|
||||
(Array.isArray(container?.rows) && container.rows) ||
|
||||
(Array.isArray(container?.list) && container.list) ||
|
||||
(Array.isArray(container?.records) && container.records) ||
|
||||
[];
|
||||
|
||||
return source
|
||||
.map((item: any) => ({
|
||||
id: Number(item?.id ?? item?.agentId),
|
||||
name: String(item?.name ?? item?.title ?? ''),
|
||||
description: item?.description,
|
||||
avatar: item?.avatar,
|
||||
greeting: item?.greeting,
|
||||
status: item?.status,
|
||||
presetQuestions: Array.isArray(item?.presetQuestions) ? item.presetQuestions : []
|
||||
}))
|
||||
.filter((item: AgentItem) => Number.isFinite(item.id) && !!item.name);
|
||||
function buildChatUrl(openId: string, trustedCredential: string) {
|
||||
const params = new URLSearchParams({ openId, trustedCredential });
|
||||
return `${baseUrl}/snail-chat/?${params.toString()}`;
|
||||
}
|
||||
|
||||
function normalizeConversationList(payload: any): ConversationSummaryItem[] {
|
||||
const container = payload?.data ?? payload;
|
||||
const source =
|
||||
(Array.isArray(container) && container) ||
|
||||
(Array.isArray(container?.rows) && container.rows) ||
|
||||
(Array.isArray(container?.list) && container.list) ||
|
||||
(Array.isArray(container?.records) && container.records) ||
|
||||
(Array.isArray(payload?.rows) && payload.rows) ||
|
||||
(Array.isArray(payload?.list) && payload.list) ||
|
||||
(Array.isArray(payload?.records) && payload.records) ||
|
||||
[];
|
||||
|
||||
return source
|
||||
.map((item: any) => ({
|
||||
conversationId: String(item?.conversationId ?? item?.id ?? ''),
|
||||
title: String(item?.title ?? item?.name ?? ''),
|
||||
lastMessageDt: item?.lastMessageDt ?? item?.updateDt ?? item?.updateTime,
|
||||
createDt: item?.createDt ?? item?.createTime,
|
||||
updateDt: item?.updateDt
|
||||
}))
|
||||
.filter((item: ConversationSummaryItem) => !!item.conversationId)
|
||||
.toSorted((a: ConversationSummaryItem, b: ConversationSummaryItem) => {
|
||||
const ta = new Date(a.lastMessageDt || a.createDt || 0).getTime();
|
||||
const tb = new Date(b.lastMessageDt || b.createDt || 0).getTime();
|
||||
return tb - ta;
|
||||
});
|
||||
}
|
||||
|
||||
async function loadAgents() {
|
||||
async function loadChat() {
|
||||
loading.value = true;
|
||||
loadError.value = '';
|
||||
try {
|
||||
const token = getToken();
|
||||
if (!token) {
|
||||
loadError.value = '登录凭证不存在,请重新登录后再试';
|
||||
return;
|
||||
}
|
||||
const { data: user } = await registerCurrentSnailUser();
|
||||
currentNickname.value = user?.nickname || '';
|
||||
const { data } = await fetchMyAgents();
|
||||
agents.value = normalizeAgentList(data);
|
||||
currentAgent.value = agents.value.find(item => item.id === currentAgent.value?.id) || agents.value[0] || null;
|
||||
if (!user?.openId) {
|
||||
loadError.value = '获取 AI 用户身份失败';
|
||||
return;
|
||||
}
|
||||
chatUrl.value = buildChatUrl(user.openId, token);
|
||||
} catch {
|
||||
loadError.value = '加载 AI 聊天失败,请稍后重试';
|
||||
} finally {
|
||||
loading.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadConversations(agentId: number) {
|
||||
try {
|
||||
const { data } = await fetchAgentConversations(agentId, { page: 1, size: 50 });
|
||||
conversations.value = normalizeConversationList(data);
|
||||
} catch {
|
||||
conversations.value = [];
|
||||
}
|
||||
}
|
||||
|
||||
async function onSelectAgent(agent: AgentItem) {
|
||||
currentAgent.value = agent;
|
||||
currentConversationId.value = '';
|
||||
await loadConversations(agent.id);
|
||||
}
|
||||
|
||||
async function handleNewChat() {
|
||||
if (!currentAgent.value && agents.value.length) {
|
||||
currentAgent.value = agents.value[0];
|
||||
await loadConversations(currentAgent.value.id);
|
||||
}
|
||||
currentConversationId.value = '';
|
||||
}
|
||||
|
||||
async function onDeleteConversation(conversationId: string) {
|
||||
if (!currentAgent.value) return;
|
||||
try {
|
||||
await ElMessageBox.confirm('确认删除该会话记录?', '系统提示', {
|
||||
confirmButtonText: '确定',
|
||||
cancelButtonText: '取消',
|
||||
type: 'warning'
|
||||
});
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
await deleteConversation(currentAgent.value.id, conversationId);
|
||||
if (currentConversationId.value === conversationId) {
|
||||
currentConversationId.value = '';
|
||||
}
|
||||
await loadConversations(currentAgent.value.id);
|
||||
ElMessage.success('删除成功');
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
loadAgents().then(async () => {
|
||||
if (currentAgent.value) {
|
||||
await loadConversations(currentAgent.value.id);
|
||||
}
|
||||
});
|
||||
loadChat();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="ai-chat-page">
|
||||
<header class="chat-header">
|
||||
<div class="brand">
|
||||
<div class="brand-dot" />
|
||||
<span>Snail AI</span>
|
||||
</div>
|
||||
</header>
|
||||
<div class="chat-body">
|
||||
<ChatSidebar
|
||||
v-loading="loading"
|
||||
:agents="agents"
|
||||
:conversations="conversations"
|
||||
:current-agent="currentAgent"
|
||||
:current-conversation-id="currentConversationId"
|
||||
:current-nickname="currentNickname"
|
||||
@select-agent="onSelectAgent"
|
||||
@select-conversation="currentConversationId = $event"
|
||||
@delete-conversation="onDeleteConversation"
|
||||
@new-chat="handleNewChat"
|
||||
/>
|
||||
<ChatMain
|
||||
:agent="currentAgent"
|
||||
:conversation-id="currentConversationId"
|
||||
@conversation-created="(id) => { currentConversationId = id; if (currentAgent) loadConversations(currentAgent.id); }"
|
||||
/>
|
||||
</div>
|
||||
<div v-loading="loading" class="ai-chat-page">
|
||||
<iframe v-if="chatUrl" class="chat-frame" :src="chatUrl" title="Snail AI" allow="clipboard-read; clipboard-write" />
|
||||
<el-empty v-else class="chat-empty" :description="loadError || '正在加载 Snail AI'">
|
||||
<el-button v-if="loadError" type="primary" @click="loadChat">重新加载</el-button>
|
||||
</el-empty>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.ai-chat-page {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: calc(100vh - 123px);
|
||||
min-height: 0;
|
||||
background: var(--el-bg-color-page);
|
||||
@ -170,48 +60,22 @@ onMounted(() => {
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.chat-header {
|
||||
flex: 0 0 38px;
|
||||
height: 38px;
|
||||
padding: 0 12px;
|
||||
border-bottom: 1px solid var(--app-surface-border);
|
||||
border-top-left-radius: var(--app-radius-base);
|
||||
border-top-right-radius: var(--app-radius-base);
|
||||
.chat-frame {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border: 0;
|
||||
background: var(--app-surface-bg);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.brand {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--app-text-title);
|
||||
font-size: 16px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.brand-dot {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border-radius: var(--app-radius-sm);
|
||||
background: var(--el-color-primary);
|
||||
}
|
||||
|
||||
.chat-body {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
overflow: hidden;
|
||||
min-height: 0;
|
||||
.chat-empty {
|
||||
height: 100%;
|
||||
background: var(--app-surface-bg);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.ai-chat-page {
|
||||
height: calc(100vh - 88px);
|
||||
}
|
||||
|
||||
.chat-body {
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@ -1,64 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { ref } from 'vue';
|
||||
|
||||
const emit = defineEmits<{
|
||||
send: [content: string];
|
||||
}>();
|
||||
defineProps<{
|
||||
sending?: boolean;
|
||||
}>();
|
||||
|
||||
const content = ref('');
|
||||
|
||||
function submit() {
|
||||
const val = content.value.trim();
|
||||
if (!val) return;
|
||||
emit('send', val);
|
||||
content.value = '';
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="chat-input-wrap">
|
||||
<div class="chat-input-box">
|
||||
<div class="input-row">
|
||||
<el-input
|
||||
v-model="content"
|
||||
type="textarea"
|
||||
:autosize="{ minRows: 1, maxRows: 4 }"
|
||||
placeholder="给智能体发消息"
|
||||
@keydown.enter.exact.prevent="submit"
|
||||
/>
|
||||
<el-button type="primary" circle :loading="sending" :disabled="sending" @click="submit">
|
||||
<el-icon><Promotion /></el-icon>
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.chat-input-wrap {
|
||||
padding: 8px 14px 10px;
|
||||
}
|
||||
|
||||
.chat-input-box {
|
||||
max-width: 920px;
|
||||
margin: 0 auto;
|
||||
border-radius: var(--app-radius-base);
|
||||
border: 1px solid var(--app-surface-border);
|
||||
background: var(--app-surface-bg);
|
||||
padding: 10px;
|
||||
box-shadow: var(--app-shadow-sm);
|
||||
}
|
||||
|
||||
.input-row {
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.input-row :deep(.el-textarea) {
|
||||
flex: 1;
|
||||
}
|
||||
</style>
|
||||
@ -1,437 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, ref, watch } from 'vue';
|
||||
import { createConversation, fetchAgentChat, fetchAgentChatSync, fetchChatMode, fetchConversationMessages } from '@/api/ai/agent';
|
||||
import type { AgentItem } from '@/api/ai/agent/types';
|
||||
import { ElMessage } from 'element-plus';
|
||||
import ChatInput from './chat-input.vue';
|
||||
|
||||
const props = defineProps<{
|
||||
agent: AgentItem | null;
|
||||
conversationId: string;
|
||||
}>();
|
||||
const emit = defineEmits<{
|
||||
conversationCreated: [conversationId: string];
|
||||
}>();
|
||||
|
||||
interface ChatMessage {
|
||||
role: 'user' | 'assistant';
|
||||
content: string;
|
||||
}
|
||||
|
||||
const messages = ref<ChatMessage[]>([]);
|
||||
const sending = ref(false);
|
||||
const sendMode = ref<'stream' | 'sync'>('stream');
|
||||
const streamTimeout = 300000;
|
||||
let sendingTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
let activeController: AbortController | null = null;
|
||||
|
||||
const showWelcome = computed(() => !!props.agent && !props.conversationId && !messages.value.length);
|
||||
const displayQuestions = computed(() => {
|
||||
return (props.agent?.presetQuestions || []).filter(Boolean);
|
||||
});
|
||||
|
||||
function normalizeMessageList(payload: any): ChatMessage[] {
|
||||
const container = payload?.data ?? payload;
|
||||
const source =
|
||||
(Array.isArray(container) && container) ||
|
||||
(Array.isArray(container?.rows) && container.rows) ||
|
||||
(Array.isArray(container?.list) && container.list) ||
|
||||
(Array.isArray(container?.records) && container.records) ||
|
||||
(Array.isArray(payload?.rows) && payload.rows) ||
|
||||
(Array.isArray(payload?.list) && payload.list) ||
|
||||
(Array.isArray(payload?.records) && payload.records) ||
|
||||
[];
|
||||
|
||||
return source
|
||||
.map((item: any) => {
|
||||
const role = String(item?.role || item?.messageType || item?.senderType || '').toLowerCase();
|
||||
return {
|
||||
role: role === 'user' ? 'user' : 'assistant',
|
||||
content: String(item?.content ?? item?.message ?? item?.text ?? '')
|
||||
} as ChatMessage;
|
||||
})
|
||||
.filter(item => !!item.content);
|
||||
}
|
||||
|
||||
function normalizeStreamChunk(chunk: string): string {
|
||||
const text = String(chunk ?? '');
|
||||
if (!text.trim()) return '';
|
||||
|
||||
const tryParseJsonContent = (raw: string): string | null => {
|
||||
try {
|
||||
const obj = JSON.parse(raw);
|
||||
if (obj && typeof obj === 'object' && typeof obj.content === 'string') {
|
||||
return obj.content;
|
||||
}
|
||||
} catch {}
|
||||
return null;
|
||||
};
|
||||
|
||||
const single = tryParseJsonContent(text);
|
||||
if (single !== null) return single;
|
||||
|
||||
const normalized = text.replace(/}\s*{/g, '}\n{');
|
||||
const lines = normalized
|
||||
.split('\n')
|
||||
.map(line => line.trim())
|
||||
.filter(Boolean);
|
||||
|
||||
if (!lines.length) return text;
|
||||
let merged = '';
|
||||
for (const line of lines) {
|
||||
const parsed = tryParseJsonContent(line);
|
||||
if (parsed === null) return text;
|
||||
merged += parsed;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
function extractSyncReply(payload: any): string {
|
||||
const container = payload?.data ?? payload;
|
||||
const normalizeChunkedJsonText = (raw: string): string => {
|
||||
const text = String(raw || '').trim();
|
||||
if (!text) return '';
|
||||
if (!text.includes('\n') && !(text.startsWith('{') && text.endsWith('}'))) {
|
||||
return text;
|
||||
}
|
||||
|
||||
const lines = text.split('\n').map(line => line.trim()).filter(Boolean);
|
||||
if (!lines.length) return text;
|
||||
|
||||
let merged = '';
|
||||
for (const line of lines) {
|
||||
try {
|
||||
const item = JSON.parse(line);
|
||||
if (item?.type === 'text' || typeof item?.content === 'string') {
|
||||
merged += String(item.content ?? '');
|
||||
}
|
||||
} catch {
|
||||
return text;
|
||||
}
|
||||
}
|
||||
return merged || text;
|
||||
};
|
||||
|
||||
const candidates = [
|
||||
container?.content,
|
||||
container?.text,
|
||||
container?.message,
|
||||
container?.answer,
|
||||
container?.reply,
|
||||
container?.outputText,
|
||||
container?.result
|
||||
];
|
||||
const hit = candidates.find(item => typeof item === 'string' && item.trim());
|
||||
if (hit) return normalizeChunkedJsonText(String(hit));
|
||||
if (Array.isArray(container?.messages)) {
|
||||
const list = normalizeMessageList(container.messages).filter(item => item.role === 'assistant');
|
||||
return list[list.length - 1]?.content || '';
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
async function loadSendMode() {
|
||||
try {
|
||||
const { data } = await fetchChatMode();
|
||||
sendMode.value = data?.mode === 'sync' ? 'sync' : 'stream';
|
||||
} catch {
|
||||
sendMode.value = 'stream';
|
||||
}
|
||||
}
|
||||
|
||||
async function loadMessages() {
|
||||
if (!props.agent || !props.conversationId) {
|
||||
messages.value = [];
|
||||
return;
|
||||
}
|
||||
const { data } = await fetchConversationMessages(props.agent.id, props.conversationId);
|
||||
messages.value = normalizeMessageList(data);
|
||||
}
|
||||
|
||||
function clearSendingTimer() {
|
||||
if (sendingTimer) {
|
||||
clearTimeout(sendingTimer);
|
||||
sendingTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
function finishSending() {
|
||||
sending.value = false;
|
||||
clearSendingTimer();
|
||||
activeController = null;
|
||||
}
|
||||
|
||||
async function onSend(content: string) {
|
||||
if (!props.agent || !content.trim() || sending.value) return;
|
||||
sending.value = true;
|
||||
clearSendingTimer();
|
||||
sendingTimer = setTimeout(() => {
|
||||
if (sending.value) {
|
||||
activeController?.abort();
|
||||
finishSending();
|
||||
ElMessage.warning('响应超时,已恢复发送按钮,请重试');
|
||||
}
|
||||
}, streamTimeout);
|
||||
let targetConversationId = props.conversationId;
|
||||
if (!targetConversationId) {
|
||||
messages.value = [];
|
||||
try {
|
||||
const { data } = await createConversation(props.agent.id, { title: content.slice(0, 20) });
|
||||
if (!data?.conversationId) {
|
||||
finishSending();
|
||||
ElMessage.error('创建会话失败,请稍后重试');
|
||||
return;
|
||||
}
|
||||
targetConversationId = data.conversationId;
|
||||
emit('conversationCreated', targetConversationId);
|
||||
} catch (error: any) {
|
||||
finishSending();
|
||||
ElMessage.error(error?.message || '创建会话失败,请稍后重试');
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
messages.value.push({ role: 'user', content });
|
||||
if (sendMode.value === 'sync') {
|
||||
try {
|
||||
const { data } = await fetchAgentChatSync(props.agent.id, {
|
||||
conversationId: targetConversationId,
|
||||
content
|
||||
});
|
||||
const reply = extractSyncReply(data) || '(后端已返回空消息)';
|
||||
messages.value.push({ role: 'assistant', content: reply });
|
||||
} catch (error: any) {
|
||||
ElMessage.error(error?.message || '对话失败,请稍后重试');
|
||||
} finally {
|
||||
finishSending();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
messages.value.push({ role: 'assistant', content: '' });
|
||||
const assistantIndex = messages.value.length - 1;
|
||||
activeController?.abort();
|
||||
activeController = new AbortController();
|
||||
void fetchAgentChat(
|
||||
props.agent.id,
|
||||
{
|
||||
conversationId: targetConversationId,
|
||||
content
|
||||
},
|
||||
{
|
||||
signal: activeController.signal,
|
||||
onMessage(chunk) {
|
||||
const msg = messages.value[assistantIndex];
|
||||
if (msg) msg.content += normalizeStreamChunk(chunk);
|
||||
},
|
||||
onThinking() {},
|
||||
onDone() {
|
||||
const msg = messages.value[assistantIndex];
|
||||
if (msg && !msg.content.trim()) {
|
||||
msg.content = '(后端已返回空消息)';
|
||||
}
|
||||
finishSending();
|
||||
},
|
||||
onError(error) {
|
||||
messages.value.splice(assistantIndex, 1);
|
||||
finishSending();
|
||||
ElMessage.error(error.message || '对话失败,请稍后重试');
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
watch(
|
||||
() => [props.agent?.id, props.conversationId] as const,
|
||||
async ([agentId, convId]) => {
|
||||
if (sending.value && convId) {
|
||||
return;
|
||||
}
|
||||
activeController?.abort();
|
||||
finishSending();
|
||||
if (agentId && convId) {
|
||||
await loadMessages();
|
||||
} else if (agentId && !convId) {
|
||||
messages.value = [];
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
|
||||
loadSendMode();
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
activeController?.abort();
|
||||
clearSendingTimer();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<main class="chat-main">
|
||||
<div v-if="!agent" class="empty-state">请先选择一个智能体开始对话</div>
|
||||
<template v-else>
|
||||
<el-scrollbar class="chat-scroll">
|
||||
<div class="chat-content">
|
||||
<div v-if="showWelcome" class="welcome-card">
|
||||
<div class="card-head">
|
||||
<el-avatar class="agent-avatar" :size="36" :src="agent.avatar">{{ agent.name.slice(0, 1) }}</el-avatar>
|
||||
<div class="title-block">
|
||||
<div class="agent-name">{{ agent.name }}</div>
|
||||
<div class="agent-desc">{{ agent.description || '暂无描述' }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="greeting">{{ agent.greeting || '你好,我是你的智能助手。' }}</div>
|
||||
<div v-if="displayQuestions.length" class="question-title">推荐问题</div>
|
||||
<div v-if="displayQuestions.length" class="question-list">
|
||||
<button v-for="q in displayQuestions" :key="q" class="question-pill" @click="onSend(q)">
|
||||
{{ q }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-for="(msg, idx) in messages" :key="idx" class="msg-row" :class="{ user: msg.role === 'user' }">
|
||||
<div class="msg-bubble" :class="{ pending: msg.role === 'assistant' && !msg.content }">{{ msg.content || '正在生成...' }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</el-scrollbar>
|
||||
<ChatInput :sending="sending" @send="onSend" />
|
||||
</template>
|
||||
</main>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.chat-main {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.empty-state {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--app-text-muted);
|
||||
}
|
||||
|
||||
.chat-scroll {
|
||||
flex: 1;
|
||||
padding: 10px 14px 0;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.chat-content {
|
||||
max-width: 920px;
|
||||
margin: 0 auto;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.welcome-card {
|
||||
background: var(--app-surface-bg);
|
||||
border: 1px solid var(--app-surface-border);
|
||||
border-radius: var(--app-radius-base);
|
||||
padding: 12px;
|
||||
margin-bottom: 10px;
|
||||
box-shadow: var(--app-shadow-sm);
|
||||
}
|
||||
|
||||
.card-head {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.agent-avatar {
|
||||
flex-shrink: 0;
|
||||
background: var(--el-color-primary);
|
||||
}
|
||||
|
||||
.agent-name {
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
color: var(--app-text-title);
|
||||
}
|
||||
|
||||
.agent-desc {
|
||||
margin-top: 2px;
|
||||
color: var(--app-text-muted);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.greeting {
|
||||
margin-top: 8px;
|
||||
color: var(--app-text-title);
|
||||
}
|
||||
|
||||
.question-title {
|
||||
margin-top: 10px;
|
||||
padding-top: 8px;
|
||||
border-top: 1px solid var(--app-surface-border);
|
||||
color: var(--app-text-muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.question-list {
|
||||
margin-top: 6px;
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.question-pill {
|
||||
border: 1px solid var(--app-surface-border);
|
||||
background: var(--app-surface-bg);
|
||||
color: var(--app-text-title);
|
||||
border-radius: var(--app-radius-md);
|
||||
padding: 5px 10px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.question-pill:hover {
|
||||
border-color: var(--el-color-primary);
|
||||
color: var(--el-color-primary);
|
||||
}
|
||||
|
||||
.msg-row {
|
||||
display: flex;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.msg-row.user {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.msg-bubble {
|
||||
max-width: 80%;
|
||||
white-space: pre-wrap;
|
||||
line-height: 1.6;
|
||||
background: var(--app-surface-bg);
|
||||
border: 1px solid var(--app-surface-border);
|
||||
border-radius: var(--app-radius-base);
|
||||
padding: 8px 10px;
|
||||
color: var(--app-text-title);
|
||||
box-shadow: var(--app-shadow-sm);
|
||||
}
|
||||
|
||||
.msg-row.user .msg-bubble {
|
||||
background: var(--el-color-primary-light-9);
|
||||
border-color: var(--el-color-primary-light-7);
|
||||
color: var(--el-color-primary);
|
||||
}
|
||||
|
||||
.msg-bubble.pending {
|
||||
color: var(--app-text-muted);
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chat-scroll {
|
||||
padding: 12px 12px 0;
|
||||
}
|
||||
|
||||
.msg-bubble {
|
||||
max-width: 92%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@ -1,228 +0,0 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue';
|
||||
|
||||
interface AgentItem {
|
||||
id: number;
|
||||
name: string;
|
||||
}
|
||||
|
||||
interface ConversationItem {
|
||||
conversationId: string;
|
||||
title: string;
|
||||
lastMessageDt?: string;
|
||||
createDt?: string;
|
||||
}
|
||||
|
||||
const emit = defineEmits<{
|
||||
selectAgent: [agent: AgentItem];
|
||||
selectConversation: [conversationId: string];
|
||||
deleteConversation: [conversationId: string];
|
||||
newChat: [];
|
||||
}>();
|
||||
|
||||
const props = defineProps<{
|
||||
agents: AgentItem[];
|
||||
conversations: ConversationItem[];
|
||||
currentAgent: AgentItem | null;
|
||||
currentConversationId: string;
|
||||
currentNickname?: string;
|
||||
}>();
|
||||
|
||||
const displayNickname = computed(() => props.currentNickname || '已登录用户');
|
||||
const avatarText = computed(() => (displayNickname.value ? displayNickname.value.slice(0, 1) : 'U'));
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<aside class="chat-sidebar">
|
||||
<div class="sidebar-block sidebar-head">
|
||||
<el-button class="new-btn" type="primary" plain :disabled="!agents.length" @click="emit('newChat')">
|
||||
<el-icon><Plus /></el-icon>
|
||||
<span>新对话</span>
|
||||
</el-button>
|
||||
</div>
|
||||
|
||||
<el-scrollbar class="sidebar-scroll">
|
||||
<div class="sidebar-block">
|
||||
<div class="block-title">我的智能体</div>
|
||||
<el-empty v-if="!agents.length" :image-size="54" description="暂无智能体" />
|
||||
<div
|
||||
v-for="agent in agents"
|
||||
:key="agent.id"
|
||||
class="agent-item"
|
||||
:class="{ active: currentAgent?.id === agent.id }"
|
||||
@click="emit('selectAgent', agent)"
|
||||
>
|
||||
<span class="avatar-dot" />
|
||||
<span class="name">{{ agent.name }}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="sidebar-block">
|
||||
<div class="block-title">对话记录</div>
|
||||
<el-empty v-if="!conversations.length" :image-size="54" description="暂无会话" />
|
||||
<div
|
||||
v-for="conv in conversations"
|
||||
:key="conv.conversationId"
|
||||
class="conv-item"
|
||||
:class="{ active: currentConversationId === conv.conversationId }"
|
||||
@click="emit('selectConversation', conv.conversationId)"
|
||||
>
|
||||
<span class="conv-title">{{ conv.title || '未命名会话' }}</span>
|
||||
<el-button class="delete-btn" link type="danger" circle @click.stop="emit('deleteConversation', conv.conversationId)">
|
||||
<el-icon><Delete /></el-icon>
|
||||
</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</el-scrollbar>
|
||||
|
||||
<div class="sidebar-foot">
|
||||
<div class="user-avatar">{{ avatarText }}</div>
|
||||
<div>
|
||||
<div class="user-name">{{ displayNickname }}</div>
|
||||
<div class="user-status">已登录</div>
|
||||
</div>
|
||||
</div>
|
||||
</aside>
|
||||
</template>
|
||||
|
||||
<style scoped lang="scss">
|
||||
.chat-sidebar {
|
||||
width: 234px;
|
||||
border-right: 1px solid var(--app-surface-border);
|
||||
background: var(--app-elevated-soft-bg);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.sidebar-head {
|
||||
padding-bottom: 6px;
|
||||
}
|
||||
|
||||
.new-btn {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.sidebar-scroll {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.sidebar-block {
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
.block-title {
|
||||
margin-bottom: 8px;
|
||||
color: var(--app-text-muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.agent-item,
|
||||
.conv-item {
|
||||
height: 32px;
|
||||
border-radius: var(--app-radius-md);
|
||||
padding: 0 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
color: var(--app-text-title);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.agent-item:hover,
|
||||
.conv-item:hover {
|
||||
background: var(--el-fill-color-light);
|
||||
}
|
||||
|
||||
.agent-item.active,
|
||||
.conv-item.active {
|
||||
background: var(--el-color-primary-light-9);
|
||||
color: var(--el-color-primary);
|
||||
}
|
||||
|
||||
.avatar-dot {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border-radius: var(--el-border-radius-round);
|
||||
background: var(--el-color-primary);
|
||||
}
|
||||
|
||||
.name {
|
||||
font-size: 14px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.conv-item {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.conv-title {
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.delete-btn {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
visibility: hidden;
|
||||
}
|
||||
|
||||
.conv-item:hover .delete-btn,
|
||||
.conv-item.active .delete-btn {
|
||||
visibility: visible;
|
||||
}
|
||||
|
||||
.sidebar-foot {
|
||||
border-top: 1px solid var(--app-surface-border);
|
||||
padding: 8px 12px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
background: var(--app-surface-bg);
|
||||
}
|
||||
|
||||
.user-avatar {
|
||||
width: 30px;
|
||||
height: 30px;
|
||||
border-radius: var(--el-border-radius-round);
|
||||
background: var(--el-color-success);
|
||||
color: var(--el-color-white);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.user-name {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--app-text-title);
|
||||
}
|
||||
|
||||
.user-status {
|
||||
color: var(--app-text-muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
:deep(.el-empty) {
|
||||
--el-empty-padding: 8px 0 12px;
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.chat-sidebar {
|
||||
width: 100%;
|
||||
height: 224px;
|
||||
border-right: 0;
|
||||
border-bottom: 1px solid var(--app-surface-border);
|
||||
}
|
||||
|
||||
.sidebar-foot {
|
||||
display: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
20
src/views/monitor/snailai/index.vue
Normal file
20
src/views/monitor/snailai/index.vue
Normal file
@ -0,0 +1,20 @@
|
||||
<template>
|
||||
<div class="p-2 app-container iframe-page">
|
||||
<div class="iframe-page__inner">
|
||||
<i-frame v-model:src="url"></i-frame>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
const url = ref(import.meta.env.VITE_APP_SNAILAI_ADMIN);
|
||||
</script>
|
||||
|
||||
<style lang="scss" scoped>
|
||||
.iframe-page__inner {
|
||||
overflow: hidden;
|
||||
border-radius: 14px;
|
||||
background: var(--app-surface-bg);
|
||||
box-shadow: var(--app-shadow-sm);
|
||||
}
|
||||
</style>
|
||||
@ -252,9 +252,12 @@ const handleUpdate = async (row?: Partial<ConfigVO>) => {
|
||||
showDialog('修改参数');
|
||||
};
|
||||
/** 内联保存参数值 */
|
||||
const handleInlineSave = async (row: ConfigVO) => {
|
||||
const handleInlineSave = async (row: Partial<ConfigVO>) => {
|
||||
if (!row.configKey) {
|
||||
return;
|
||||
}
|
||||
await modal.confirm('确认要保存对参数"' + row.configKey + '"的修改吗?');
|
||||
await updateConfigByKey(row.configKey, row.configValue);
|
||||
await updateConfigByKey(row.configKey, row.configValue ?? '');
|
||||
modal.msgSuccess('修改成功');
|
||||
};
|
||||
/** 提交按钮 */
|
||||
|
||||
Loading…
Reference in New Issue
Block a user