mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 19:09:19 +08:00
feat: 新增agent
This commit is contained in:
@@ -43,6 +43,8 @@
|
||||
"@vueuse/core": "catalog:",
|
||||
"ant-design-vue": "catalog:",
|
||||
"dayjs": "catalog:",
|
||||
"dompurify": "^3.4.15",
|
||||
"marked": "^18.0.13",
|
||||
"papaparse": "^5.4.1",
|
||||
"pinia": "catalog:",
|
||||
"spark-md5": "^3.0.2",
|
||||
@@ -51,6 +53,8 @@
|
||||
"vue-waterfall-plugin-next": "^3.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/dompurify": "^3.2.0",
|
||||
"@types/marked": "^6.0.0",
|
||||
"@types/papaparse": "^5.3.14",
|
||||
"@types/spark-md5": "^3.0.5"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,172 @@
|
||||
import { useAccessStore } from '@vben/stores';
|
||||
|
||||
import { requestClient } from '#/api/request';
|
||||
|
||||
/** Agent 服务走 /api/agent,开发态由 Vite 代理到 :8200 */
|
||||
|
||||
export namespace AgentVO {
|
||||
export interface Session {
|
||||
threadId: string;
|
||||
title: string;
|
||||
status: string;
|
||||
createdAt?: string;
|
||||
updatedAt?: string;
|
||||
lastMessageAt?: string | null;
|
||||
}
|
||||
|
||||
export interface Message {
|
||||
id?: string;
|
||||
seq: number;
|
||||
role: 'user' | 'assistant' | 'system' | 'tool';
|
||||
content: string;
|
||||
createdAt?: string;
|
||||
}
|
||||
|
||||
export interface LlmSettings {
|
||||
configured: boolean;
|
||||
baseUrl?: string | null;
|
||||
model?: string | null;
|
||||
apiKeyMasked?: string | null;
|
||||
/** Server 字段;兼容旧 updatedAt */
|
||||
updateTime?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface Memory {
|
||||
id: string;
|
||||
kind: string;
|
||||
key?: string | null;
|
||||
text: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
}
|
||||
export async function listAgentSessionsApi() {
|
||||
return requestClient.get<{ items: AgentVO.Session[] }>('/agent/sessions');
|
||||
}
|
||||
|
||||
export async function createAgentSessionApi(title?: string) {
|
||||
return requestClient.post<AgentVO.Session>('/agent/sessions', { title });
|
||||
}
|
||||
|
||||
export async function listAgentMessagesApi(threadId: string) {
|
||||
return requestClient.get<{ items: AgentVO.Message[] }>(
|
||||
`/agent/sessions/${threadId}/messages`,
|
||||
);
|
||||
}
|
||||
|
||||
export async function listAgentMemoriesApi() {
|
||||
return requestClient.get<{ items: AgentVO.Memory[] }>('/agent/memories');
|
||||
}
|
||||
|
||||
export async function deleteAgentMemoryApi(memoryId: string) {
|
||||
return requestClient.delete<{ ok: boolean }>(`/agent/memories/${memoryId}`);
|
||||
}
|
||||
|
||||
export async function getAgentLlmSettingsApi() {
|
||||
return requestClient.get<AgentVO.LlmSettings>(
|
||||
'/company/agent-llm-settings',
|
||||
);
|
||||
}
|
||||
|
||||
export async function updateAgentLlmSettingsApi(body: {
|
||||
baseUrl: string;
|
||||
model: string;
|
||||
apiKey?: string;
|
||||
}) {
|
||||
return requestClient.put<AgentVO.LlmSettings>(
|
||||
'/company/agent-llm-settings',
|
||||
body,
|
||||
);
|
||||
}
|
||||
|
||||
/** SSE 流式发消息 */
|
||||
export function streamAgentChat(options: {
|
||||
threadId: string;
|
||||
content: string;
|
||||
onToken: (text: string) => void;
|
||||
onDone?: () => void;
|
||||
onError?: (message: string) => void;
|
||||
}): AbortController {
|
||||
const controller = new AbortController();
|
||||
const accessStore = useAccessStore();
|
||||
const token = accessStore.accessToken;
|
||||
const url = `/api/agent/sessions/${options.threadId}/chat`;
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Accept: 'text/event-stream',
|
||||
...(token ? { Authorization: `Bearer ${token}` } : {}),
|
||||
},
|
||||
body: JSON.stringify({ content: options.content }),
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!res.ok || !res.body) {
|
||||
options.onError?.(`请求失败 HTTP ${res.status}`);
|
||||
return;
|
||||
}
|
||||
const reader = res.body.getReader();
|
||||
const decoder = new TextDecoder();
|
||||
let buffer = '';
|
||||
let finished = false;
|
||||
|
||||
const consumeBlock = (part: string) => {
|
||||
const lines = part.split('\n');
|
||||
let event = 'message';
|
||||
const dataLines: string[] = [];
|
||||
for (const rawLine of lines) {
|
||||
const line = rawLine.replace(/\r$/, '');
|
||||
if (!line || line.startsWith(':')) continue;
|
||||
if (line.startsWith('event:')) {
|
||||
event = line.slice(6).trim();
|
||||
} else if (line.startsWith('data:')) {
|
||||
dataLines.push(line.slice(5).replace(/^ /, ''));
|
||||
}
|
||||
}
|
||||
const data = dataLines.join('\n');
|
||||
if (!data && event !== 'done') return;
|
||||
if (event === 'token') {
|
||||
try {
|
||||
const parsed = JSON.parse(data) as { text?: string };
|
||||
if (parsed.text) options.onToken(parsed.text);
|
||||
} catch {
|
||||
options.onToken(data);
|
||||
}
|
||||
} else if (event === 'error') {
|
||||
try {
|
||||
const parsed = JSON.parse(data) as { message?: string };
|
||||
options.onError?.(parsed.message || data);
|
||||
} catch {
|
||||
options.onError?.(data);
|
||||
}
|
||||
} else if (event === 'done') {
|
||||
finished = true;
|
||||
options.onDone?.();
|
||||
}
|
||||
};
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
// 统一换行,按 SSE 事件块拆分
|
||||
buffer = buffer.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
|
||||
const parts = buffer.split('\n\n');
|
||||
buffer = parts.pop() || '';
|
||||
for (const part of parts) {
|
||||
if (part.trim()) consumeBlock(part);
|
||||
}
|
||||
}
|
||||
if (buffer.trim()) consumeBlock(buffer);
|
||||
if (!finished) options.onDone?.();
|
||||
} catch (e: any) {
|
||||
if (e?.name === 'AbortError') return;
|
||||
options.onError?.(e?.message || '流式连接失败');
|
||||
}
|
||||
})();
|
||||
|
||||
return controller;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
export type { AgentVO } from './apis';
|
||||
export {
|
||||
createAgentSessionApi,
|
||||
deleteAgentMemoryApi,
|
||||
getAgentLlmSettingsApi,
|
||||
listAgentMemoriesApi,
|
||||
listAgentMessagesApi,
|
||||
listAgentSessionsApi,
|
||||
streamAgentChat,
|
||||
updateAgentLlmSettingsApi,
|
||||
} from './apis';
|
||||
@@ -0,0 +1,489 @@
|
||||
<script lang="ts" setup>
|
||||
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue';
|
||||
|
||||
import { Page } from '@vben/common-ui';
|
||||
|
||||
import {
|
||||
Button,
|
||||
Empty,
|
||||
Form,
|
||||
FormItem,
|
||||
Input,
|
||||
InputPassword,
|
||||
Modal,
|
||||
Textarea,
|
||||
message,
|
||||
} from 'ant-design-vue';
|
||||
|
||||
import {
|
||||
createAgentSessionApi,
|
||||
deleteAgentMemoryApi,
|
||||
getAgentLlmSettingsApi,
|
||||
listAgentMemoriesApi,
|
||||
listAgentMessagesApi,
|
||||
listAgentSessionsApi,
|
||||
streamAgentChat,
|
||||
updateAgentLlmSettingsApi,
|
||||
type AgentVO,
|
||||
} from '#/api/agent';
|
||||
|
||||
import { renderAgentMarkdown } from './markdown';
|
||||
|
||||
defineOptions({ name: 'AgentChat' });
|
||||
|
||||
const loadingSessions = ref(false);
|
||||
const loadingMessages = ref(false);
|
||||
const sending = ref(false);
|
||||
const sessions = ref<AgentVO.Session[]>([]);
|
||||
const activeThreadId = ref<string | null>(null);
|
||||
const messages = ref<AgentVO.Message[]>([]);
|
||||
/** 当前流式助手正文(与 messages 末条同步,避免列表被 loading 遮挡时丢更新) */
|
||||
const streamingText = ref('');
|
||||
const draft = ref('');
|
||||
const settingsOpen = ref(false);
|
||||
const savingSettings = ref(false);
|
||||
const memories = ref<AgentVO.Memory[]>([]);
|
||||
const llmForm = ref({
|
||||
baseUrl: '',
|
||||
model: '',
|
||||
apiKey: '',
|
||||
apiKeyMasked: '' as string | null,
|
||||
configured: false,
|
||||
});
|
||||
const messagePaneRef = ref<HTMLElement | null>(null);
|
||||
let abort: AbortController | null = null;
|
||||
/** 丢弃过期的 loadMessages */
|
||||
let messagesLoadSeq = 0;
|
||||
|
||||
const activeSession = computed(() =>
|
||||
sessions.value.find((s) => s.threadId === activeThreadId.value),
|
||||
);
|
||||
|
||||
const showMessageLoading = computed(
|
||||
() => loadingMessages.value && !sending.value && messages.value.length === 0,
|
||||
);
|
||||
|
||||
function bubbleHtml(m: AgentVO.Message, idx: number): string {
|
||||
const isStreamingAssistant =
|
||||
sending.value &&
|
||||
idx === messages.value.length - 1 &&
|
||||
m.role === 'assistant';
|
||||
const text = isStreamingAssistant ? streamingText.value : m.content || '';
|
||||
if (!text) {
|
||||
return isStreamingAssistant ? '…' : '';
|
||||
}
|
||||
if (m.role === 'user') {
|
||||
return text
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/\n/g, '<br>');
|
||||
}
|
||||
return renderAgentMarkdown(text);
|
||||
}
|
||||
|
||||
async function refreshSessions() {
|
||||
loadingSessions.value = true;
|
||||
try {
|
||||
const res = await listAgentSessionsApi();
|
||||
sessions.value = res.items || [];
|
||||
if (!activeThreadId.value && sessions.value[0]) {
|
||||
activeThreadId.value = sessions.value[0].threadId;
|
||||
}
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '加载会话失败');
|
||||
} finally {
|
||||
loadingSessions.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function loadMessages(threadId: string) {
|
||||
const seq = ++messagesLoadSeq;
|
||||
loadingMessages.value = true;
|
||||
try {
|
||||
const res = await listAgentMessagesApi(threadId);
|
||||
if (seq !== messagesLoadSeq || sending.value || threadId !== activeThreadId.value) {
|
||||
return;
|
||||
}
|
||||
messages.value = res.items || [];
|
||||
streamingText.value = '';
|
||||
await nextTick();
|
||||
scrollToBottom();
|
||||
} catch (e: any) {
|
||||
if (seq === messagesLoadSeq && !sending.value) {
|
||||
message.error(e?.message || '加载消息失败');
|
||||
}
|
||||
} finally {
|
||||
if (seq === messagesLoadSeq) {
|
||||
loadingMessages.value = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function scrollToBottom() {
|
||||
const el = messagePaneRef.value;
|
||||
if (el) el.scrollTop = el.scrollHeight;
|
||||
}
|
||||
|
||||
watch(activeThreadId, (id) => {
|
||||
if (sending.value) return;
|
||||
if (id) void loadMessages(id);
|
||||
else {
|
||||
messages.value = [];
|
||||
streamingText.value = '';
|
||||
}
|
||||
});
|
||||
|
||||
async function createSession() {
|
||||
try {
|
||||
const s = await createAgentSessionApi();
|
||||
sessions.value = [s, ...sessions.value];
|
||||
messagesLoadSeq += 1;
|
||||
loadingMessages.value = false;
|
||||
messages.value = [];
|
||||
streamingText.value = '';
|
||||
activeThreadId.value = s.threadId;
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '新建会话失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function openSettings() {
|
||||
settingsOpen.value = true;
|
||||
try {
|
||||
const [s, mem] = await Promise.all([
|
||||
getAgentLlmSettingsApi(),
|
||||
listAgentMemoriesApi().catch(() => ({ items: [] as AgentVO.Memory[] })),
|
||||
]);
|
||||
llmForm.value = {
|
||||
baseUrl: s.baseUrl || '',
|
||||
model: s.model || '',
|
||||
apiKey: '',
|
||||
apiKeyMasked: s.apiKeyMasked || null,
|
||||
configured: !!s.configured,
|
||||
};
|
||||
memories.value = mem.items || [];
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '加载模型配置失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function removeMemory(id: string) {
|
||||
try {
|
||||
await deleteAgentMemoryApi(id);
|
||||
memories.value = memories.value.filter((m) => m.id !== id);
|
||||
message.success('已删除记忆');
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '删除失败');
|
||||
}
|
||||
}
|
||||
|
||||
async function saveSettings() {
|
||||
if (!llmForm.value.baseUrl.trim() || !llmForm.value.model.trim()) {
|
||||
message.warning('请填写 Base URL 与模型名');
|
||||
return;
|
||||
}
|
||||
savingSettings.value = true;
|
||||
try {
|
||||
const s = await updateAgentLlmSettingsApi({
|
||||
baseUrl: llmForm.value.baseUrl.trim(),
|
||||
model: llmForm.value.model.trim(),
|
||||
apiKey: llmForm.value.apiKey.trim() || undefined,
|
||||
});
|
||||
llmForm.value.configured = s.configured;
|
||||
llmForm.value.apiKeyMasked = s.apiKeyMasked || null;
|
||||
llmForm.value.apiKey = '';
|
||||
message.success('模型配置已保存');
|
||||
settingsOpen.value = false;
|
||||
} catch (e: any) {
|
||||
message.error(e?.message || '保存失败');
|
||||
} finally {
|
||||
savingSettings.value = false;
|
||||
}
|
||||
}
|
||||
|
||||
function appendStreamToken(t: string) {
|
||||
streamingText.value += t;
|
||||
const idx = messages.value.length - 1;
|
||||
const last = messages.value[idx];
|
||||
if (last?.role === 'assistant') {
|
||||
messages.value[idx] = { ...last, content: streamingText.value };
|
||||
}
|
||||
void nextTick().then(scrollToBottom);
|
||||
}
|
||||
|
||||
async function send() {
|
||||
const text = draft.value.trim();
|
||||
if (!text || sending.value) return;
|
||||
if (!activeThreadId.value) {
|
||||
await createSession();
|
||||
}
|
||||
const threadId = activeThreadId.value;
|
||||
if (!threadId) return;
|
||||
|
||||
messagesLoadSeq += 1;
|
||||
loadingMessages.value = false;
|
||||
sending.value = true;
|
||||
streamingText.value = '';
|
||||
draft.value = '';
|
||||
messages.value.push({
|
||||
seq: (messages.value.at(-1)?.seq || 0) + 1,
|
||||
role: 'user',
|
||||
content: text,
|
||||
});
|
||||
messages.value.push({
|
||||
seq: (messages.value.at(-1)?.seq || 0) + 1,
|
||||
role: 'assistant',
|
||||
content: '',
|
||||
});
|
||||
await nextTick();
|
||||
scrollToBottom();
|
||||
|
||||
abort?.abort();
|
||||
abort = streamAgentChat({
|
||||
threadId,
|
||||
content: text,
|
||||
onToken: appendStreamToken,
|
||||
onDone: () => {
|
||||
const finalText = streamingText.value;
|
||||
const idx = messages.value.length - 1;
|
||||
const last = messages.value[idx];
|
||||
if (last?.role === 'assistant') {
|
||||
messages.value[idx] = { ...last, content: finalText || last.content };
|
||||
}
|
||||
sending.value = false;
|
||||
streamingText.value = '';
|
||||
void refreshSessions();
|
||||
},
|
||||
onError: (msg) => {
|
||||
sending.value = false;
|
||||
const idx = messages.value.length - 1;
|
||||
const last = messages.value[idx];
|
||||
if (last?.role === 'assistant' && !last.content && !streamingText.value) {
|
||||
messages.value[idx] = { ...last, content: `错误:${msg}` };
|
||||
}
|
||||
streamingText.value = '';
|
||||
message.error(msg);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
onBeforeUnmount(() => abort?.abort());
|
||||
|
||||
void refreshSessions();
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<Page auto-content-height content-class="!p-0">
|
||||
<div class="flex h-full min-h-0 w-full overflow-hidden">
|
||||
<aside
|
||||
class="flex w-64 shrink-0 flex-col border-r border-border bg-card"
|
||||
>
|
||||
<div class="flex items-center gap-2 border-b border-border p-3">
|
||||
<Button type="primary" block @click="createSession">新对话</Button>
|
||||
</div>
|
||||
<div class="min-h-0 flex-1 overflow-y-auto p-2">
|
||||
<div
|
||||
v-if="loadingSessions"
|
||||
class="text-muted-foreground py-6 text-center text-sm"
|
||||
>
|
||||
加载中…
|
||||
</div>
|
||||
<template v-else>
|
||||
<button
|
||||
v-for="s in sessions"
|
||||
:key="s.threadId"
|
||||
type="button"
|
||||
class="mb-1 w-full rounded-md px-3 py-2 text-left text-sm transition-colors"
|
||||
:class="
|
||||
s.threadId === activeThreadId
|
||||
? 'bg-primary/10 text-primary'
|
||||
: 'hover:bg-muted'
|
||||
"
|
||||
@click="activeThreadId = s.threadId"
|
||||
>
|
||||
<div class="truncate font-medium">{{ s.title }}</div>
|
||||
<div class="text-muted-foreground mt-0.5 truncate text-xs">
|
||||
{{ s.updatedAt || '' }}
|
||||
</div>
|
||||
</button>
|
||||
<Empty
|
||||
v-if="sessions.length === 0"
|
||||
class="mt-8"
|
||||
description="暂无会话"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
<div class="border-t border-border p-3">
|
||||
<Button block @click="openSettings">模型 API 设置</Button>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section class="flex min-h-0 min-w-0 flex-1 flex-col">
|
||||
<header
|
||||
class="flex h-12 shrink-0 items-center border-b border-border px-4"
|
||||
>
|
||||
<span class="truncate font-medium">
|
||||
{{ activeSession?.title || '智能助手' }}
|
||||
</span>
|
||||
</header>
|
||||
<div
|
||||
ref="messagePaneRef"
|
||||
class="relative min-h-0 flex-1 space-y-3 overflow-y-auto px-4 py-4"
|
||||
>
|
||||
<div
|
||||
v-if="showMessageLoading"
|
||||
class="text-muted-foreground py-6 text-center text-sm"
|
||||
>
|
||||
加载消息…
|
||||
</div>
|
||||
<Empty
|
||||
v-else-if="messages.length === 0"
|
||||
description="开始提问吧(需先配置公司模型 API)"
|
||||
/>
|
||||
<div
|
||||
v-for="(m, idx) in messages"
|
||||
:key="`${m.seq}-${idx}`"
|
||||
class="flex"
|
||||
:class="m.role === 'user' ? 'justify-end' : 'justify-start'"
|
||||
>
|
||||
<div
|
||||
class="agent-md max-w-[75%] rounded-2xl px-3 py-2 text-sm leading-relaxed"
|
||||
:class="
|
||||
m.role === 'user'
|
||||
? 'bg-primary text-primary-foreground whitespace-pre-wrap'
|
||||
: 'bg-muted text-foreground'
|
||||
"
|
||||
v-html="bubbleHtml(m, idx)"
|
||||
></div>
|
||||
</div>
|
||||
</div>
|
||||
<footer class="shrink-0 border-t border-border p-3">
|
||||
<div class="flex gap-2">
|
||||
<Textarea
|
||||
v-model:value="draft"
|
||||
:rows="2"
|
||||
:disabled="sending"
|
||||
placeholder="输入问题,Enter 发送(Shift+Enter 换行)"
|
||||
class="flex-1"
|
||||
@keydown.enter.exact.prevent="send"
|
||||
/>
|
||||
<Button type="primary" :loading="sending" @click="send">
|
||||
发送
|
||||
</Button>
|
||||
</div>
|
||||
</footer>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<Modal
|
||||
v-model:open="settingsOpen"
|
||||
title="公司模型 API(OpenAI Compatible)"
|
||||
:confirm-loading="savingSettings"
|
||||
ok-text="保存"
|
||||
destroy-on-close
|
||||
@ok="saveSettings"
|
||||
>
|
||||
<p class="text-muted-foreground mb-3 text-sm">
|
||||
各租户自行填写 Base URL、API Key 与模型名。Key
|
||||
加密落库(MySQL),Agent 经内部接口/Redis 注入;界面仅显示掩码。
|
||||
</p>
|
||||
<Form layout="vertical">
|
||||
<FormItem label="Base URL" required>
|
||||
<Input
|
||||
v-model:value="llmForm.baseUrl"
|
||||
placeholder="https://api.deepseek.com/v1"
|
||||
/>
|
||||
</FormItem>
|
||||
<FormItem label="Model" required>
|
||||
<Input v-model:value="llmForm.model" placeholder="deepseek-chat" />
|
||||
</FormItem>
|
||||
<FormItem
|
||||
:label="
|
||||
llmForm.configured
|
||||
? `API Key(已配置 ${llmForm.apiKeyMasked || '****'},留空则不修改)`
|
||||
: 'API Key'
|
||||
"
|
||||
:required="!llmForm.configured"
|
||||
>
|
||||
<InputPassword
|
||||
v-model:value="llmForm.apiKey"
|
||||
placeholder="sk-..."
|
||||
/>
|
||||
</FormItem>
|
||||
</Form>
|
||||
<div class="mt-4 border-t border-border pt-3">
|
||||
<div class="mb-2 text-sm font-medium">我的记忆</div>
|
||||
<p class="text-muted-foreground mb-2 text-xs">
|
||||
对话中发送「记住:…」可写入;助手会注入最近条目。
|
||||
</p>
|
||||
<div v-if="memories.length === 0" class="text-muted-foreground text-xs">
|
||||
暂无记忆
|
||||
</div>
|
||||
<div
|
||||
v-for="m in memories"
|
||||
:key="m.id"
|
||||
class="mb-1 flex items-start gap-2 rounded-md bg-muted/50 px-2 py-1.5 text-xs"
|
||||
>
|
||||
<span class="min-w-0 flex-1 break-words">{{ m.text }}</span>
|
||||
<Button type="link" size="small" danger @click="removeMemory(m.id)">
|
||||
删
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</Modal>
|
||||
</Page>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
.agent-md :deep(p) {
|
||||
margin: 0.35em 0;
|
||||
}
|
||||
.agent-md :deep(p:first-child) {
|
||||
margin-top: 0;
|
||||
}
|
||||
.agent-md :deep(p:last-child) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
.agent-md :deep(ul),
|
||||
.agent-md :deep(ol) {
|
||||
margin: 0.35em 0;
|
||||
padding-left: 1.25em;
|
||||
}
|
||||
.agent-md :deep(pre) {
|
||||
margin: 0.5em 0;
|
||||
overflow-x: auto;
|
||||
border-radius: 0.5rem;
|
||||
background: rgba(0, 0, 0, 0.06);
|
||||
padding: 0.6em 0.75em;
|
||||
font-size: 0.85em;
|
||||
}
|
||||
.agent-md :deep(code) {
|
||||
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
.agent-md :deep(:not(pre) > code) {
|
||||
border-radius: 0.25rem;
|
||||
background: rgba(0, 0, 0, 0.06);
|
||||
padding: 0.1em 0.35em;
|
||||
}
|
||||
.agent-md :deep(a) {
|
||||
text-decoration: underline;
|
||||
}
|
||||
.agent-md :deep(blockquote) {
|
||||
margin: 0.4em 0;
|
||||
border-left: 3px solid rgba(0, 0, 0, 0.2);
|
||||
padding-left: 0.75em;
|
||||
opacity: 0.9;
|
||||
}
|
||||
.agent-md :deep(table) {
|
||||
margin: 0.5em 0;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
.agent-md :deep(th),
|
||||
.agent-md :deep(td) {
|
||||
border: 1px solid rgba(0, 0, 0, 0.12);
|
||||
padding: 0.25em 0.5em;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,21 @@
|
||||
/** 轻量 Markdown → 安全 HTML(流式场景下未闭合围栏也能尽量渲染)。 */
|
||||
import DOMPurify from 'dompurify';
|
||||
import { marked } from 'marked';
|
||||
|
||||
marked.setOptions({
|
||||
gfm: true,
|
||||
breaks: true,
|
||||
});
|
||||
|
||||
export function renderAgentMarkdown(source: string): string {
|
||||
const raw = source || '';
|
||||
if (!raw.trim()) return '';
|
||||
try {
|
||||
const html = marked.parse(raw, { async: false }) as string;
|
||||
return DOMPurify.sanitize(html, {
|
||||
USE_PROFILES: { html: true },
|
||||
});
|
||||
} catch {
|
||||
return DOMPurify.sanitize(raw.replace(/</g, '<').replace(/>/g, '>'));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { defineConfig } from '@vben/vite-config';
|
||||
|
||||
/** 开发环境 SSE 经 Vite 代理时禁止缓冲,否则只有首包 message+ping 后续心跳到不了浏览器 */
|
||||
/** 开发环境 SSE 经 Vite 代理时禁止缓冲 */
|
||||
function configureSseFriendlyProxy(proxyServer: {
|
||||
on: (
|
||||
event: 'proxyReq' | 'proxyRes',
|
||||
@@ -8,15 +8,18 @@ function configureSseFriendlyProxy(proxyServer: {
|
||||
) => void;
|
||||
}) {
|
||||
proxyServer.on('proxyReq', (proxyReq, req) => {
|
||||
if (req.url?.includes('/notify/sse/')) {
|
||||
const url = req.url || '';
|
||||
if (url.includes('/notify/sse/') || url.includes('/agent/sessions/')) {
|
||||
proxyReq.setHeader('Accept', 'text/event-stream');
|
||||
proxyReq.setHeader('Cache-Control', 'no-cache');
|
||||
}
|
||||
});
|
||||
proxyServer.on('proxyRes', (proxyRes, req, res) => {
|
||||
const contentType = proxyRes.headers['content-type'];
|
||||
const url = req.url || '';
|
||||
if (
|
||||
req.url?.includes('/notify/sse/') ||
|
||||
url.includes('/notify/sse/') ||
|
||||
url.includes('/chat') ||
|
||||
(typeof contentType === 'string' &&
|
||||
contentType.includes('text/event-stream'))
|
||||
) {
|
||||
@@ -38,6 +41,14 @@ export default defineConfig(async () => {
|
||||
vite: {
|
||||
server: {
|
||||
proxy: {
|
||||
// Agent 服务(须写在通用 /api 之前)
|
||||
'/api/agent': {
|
||||
changeOrigin: true,
|
||||
target: 'http://localhost:8200',
|
||||
timeout: 0,
|
||||
proxyTimeout: 0,
|
||||
configure: configureSseFriendlyProxy,
|
||||
},
|
||||
'/api': {
|
||||
changeOrigin: true,
|
||||
// 后端服务地址
|
||||
|
||||
Reference in New Issue
Block a user