Merge pull request 'feat:前端修改(最后一次)' (#28) from develop_qianduan into develop

Reviewed-on: #28
This commit was merged in pull request #28.
This commit is contained in:
2026-09-14 21:00:43 +08:00
6 changed files with 395 additions and 90 deletions
+36 -9
View File
@@ -354,16 +354,19 @@
<div class="ca-head">
<div class="row" style="gap:10px">
<div class="brand-logo" style="width:34px;height:34px;font-size:15px">🤖</div>
<div><div class="t">华夏基金智能助手</div><div class="s">在线为您提供基金信息服务</div></div>
<div><div class="t">华夏基金智能助手</div><div class="s" id="ca-state">在线为您提供基金信息服务</div></div>
</div>
<button class="btn btn-ghost btn-sm" style="color:#bfdbfe" onclick="toggleCA()">✕</button>
<button class="btn btn-ghost btn-sm" style="color:#bfdbfe" onclick="closeCA()">✕</button>
</div>
<div class="ca-body">
<div class="m bot"><div class="bl">您好,我是华夏基金智能助手。您可以咨询基金产品、风险等级和净值信息。</div></div>
<div class="m usr"><div class="bl">稳健型的我能买股票型基金吗?</div></div>
<div class="m bot"><div class="bl">风险等级 C2(保守型)通常不建议购买 R4 股票型基金,
两者风险等级不匹配。您可以关注 R2 债券型或 R3 混合型产品。<br><br>
<span class="faint xs">以上信息仅供参考,不构成投资建议。</span></div></div>
<div id="ca-connecting" class="xs" style="color:#94a3b8;padding:6px 0">正在建立会话...</div>
<div id="ca-messages" style="display:none">
<div class="m bot"><div class="bl">您好,我是华夏基金智能助手。您可以咨询基金产品、风险等级和净值信息。</div></div>
<div class="m usr"><div class="bl">稳健型的我能买股票型基金吗?</div></div>
<div class="m bot"><div class="bl">风险等级 C2(保守型)通常不建议购买 R4 股票型基金,
两者风险等级不匹配。您可以关注 R2 债券型或 R3 混合型产品。<br><br>
<span class="faint xs">以上信息仅供参考,不构成投资建议。</span></div></div>
</div>
</div>
<div class="ca-foot">
<input class="input" placeholder="输入您的问题">
@@ -1020,11 +1023,35 @@ function showScreen(id){
/* 客户/游客助手挂在全局 layout,后台不显示(后台用投顾助手悬浮球) */
document.getElementById("client-agent").style.display =
NO_CLIENT_AGENT.includes(id) ? "none" : "block";
document.getElementById("ca-win").style.display = "none";
closeCA();
}
/* 打开面板 = 先建会话(session/create),拿到会话号后才允许对话 */
function openCA(){
const w = document.getElementById("ca-win");
if (w.style.display !== "none") return;
w.style.display = "flex";
const state = document.getElementById("ca-state");
document.getElementById("ca-connecting").style.display = "block";
document.getElementById("ca-messages").style.display = "none";
state.textContent = "正在建立会话...";
clearTimeout(window.__caTimer);
window.__caTimer = setTimeout(()=>{
state.textContent = "会话 #" + Math.random().toString(16).slice(2,8) + " · 已接入您的账户数据";
document.getElementById("ca-connecting").style.display = "none";
document.getElementById("ca-messages").style.display = "block";
}, 700);
}
/* 关闭面板 = 结束会话(session/end),丢弃服务端上下文 */
function closeCA(){
const w = document.getElementById("ca-win");
if (w.style.display === "none") return;
w.style.display = "none";
clearTimeout(window.__caTimer);
document.getElementById("ca-state").textContent = "会话已结束";
}
function toggleCA(){
const w = document.getElementById("ca-win");
w.style.display = w.style.display==="none" ? "flex" : "none";
w.style.display === "none" ? openCA() : closeCA();
}
function go(id){
const sec = ADMIN_SECTIONS.find(s=>s.id===id);
@@ -58,7 +58,8 @@ export function AssistantLauncher() {
const [open, setOpen] = useState(false);
const [tab, setTab] = useState<"chat" | "drafts">("chat");
const [sessionId, setSessionId] = useState(() => newSessionId());
/* 会话在「打开抽屉」时才建立(见 openAssistant),关闭时丢弃,不在挂载时就占用上下文 */
const [sessionId, setSessionId] = useState<string | null>(null);
const [customers, setCustomers] = useState<Customer[]>([]);
const [customerId, setCustomerId] = useState<number | null>(null);
const [messages, setMessages] = useState<ChatMessage[]>([]);
@@ -87,7 +88,7 @@ export function AssistantLauncher() {
return () => clearInterval(timer);
}, [streaming]);
const sessionTag = useMemo(() => sessionId.slice(-6), [sessionId]);
const sessionTag = useMemo(() => (sessionId ? sessionId.slice(-6) : "--------"), [sessionId]);
/* 客户列表只用于会话上下文选择,失败不阻断助手 */
useEffect(() => {
@@ -101,8 +102,18 @@ export function AssistantLauncher() {
})();
}, []);
/* 会话 ID 变化时恢复该会话的历史;新会话为空属正常,不报错。 */
/*
* 会话握手:打开抽屉(sessionId 就绪)后拉一次该会话的记录。
* 投顾 Agent 没有独立的 session/create,后端按 (advisor_id, session_id) 惰性建立上下文,
* 所以这个请求就是「打开助手时发出的会话请求」;关闭抽屉会把 sessionId 置空、丢弃上下文。
*/
useEffect(() => {
if (!sessionId) {
setMessages([]);
setHistoryError(null);
setHistoryLoading(false);
return;
}
let alive = true;
void (async () => {
setHistoryLoading(true);
@@ -182,7 +193,7 @@ export function AssistantLauncher() {
const result = await assistantApi.chatOnce(
{
query,
session_id: sessionId,
session_id: sessionId ?? undefined,
scope: customerId ? "customer" : "advisor",
customer_id: customerId,
},
@@ -241,7 +252,7 @@ export function AssistantLauncher() {
setStreaming(true);
try {
if (tool === "data-query") {
const result = await assistantApi.dataQuery({ query, session_id: sessionId });
const result = await assistantApi.dataQuery({ query, session_id: sessionId ?? undefined });
pushPair(query, result.answer ?? result.summary ?? "查询完成,无文本摘要。", "data_query");
} else if (tool === "fund-analysis") {
const result = await assistantApi.fundAnalysis(query);
@@ -272,7 +283,30 @@ export function AssistantLauncher() {
[customerId, input, loadDrafts, pushPair, sessionId, toast]
);
/** 结束会话:中止生成、清空上下文并启用新的 session_id。 */
/**
* 打开抽屉 = 建立会话。
* 投顾 Agent 后端只有 chat/stream 与 session/{id}/history,没有独立的 session/create,
* 所以这里生成会话键,由上面的 useEffect 调 history 完成握手(后端按需建立上下文)。
*/
const openAssistant = useCallback(() => {
setOpen(true);
setSessionId((current) => current ?? newSessionId());
}, []);
/**
* 关闭抽屉 = 结束会话:中止生成、清空消息并丢弃上下文。
* 投顾侧后端未提供 session/end,因此结束只能在前端完成(下次打开是新的 session_id)。
*/
const closeAssistant = useCallback(() => {
abortRef.current?.abort();
setOpen(false);
setMessages([]);
setInput("");
setStreaming(false);
setSessionId(null);
}, []);
/** 抽屉内「结束会话」:不等关闭,立即换一个全新会话并重新握手。 */
const endSession = useCallback(() => {
abortRef.current?.abort();
setMessages([]);
@@ -328,7 +362,7 @@ export function AssistantLauncher() {
<>
{!open && (
<button
onClick={() => setOpen(true)}
onClick={openAssistant}
aria-label="打开投顾助手"
className="fixed bottom-6 right-6 z-40 flex h-14 w-14 items-center justify-center rounded-full bg-indigo-600 text-white shadow-lg shadow-indigo-600/30 transition-transform hover:scale-105 hover:bg-indigo-700"
>
@@ -345,7 +379,7 @@ export function AssistantLauncher() {
<>
<div
className="fixed inset-0 z-40 bg-slate-900/10"
onClick={() => setOpen(false)}
onClick={closeAssistant}
aria-hidden
/>
<aside className="fixed inset-y-0 right-0 z-50 flex w-full max-w-[560px] flex-col bg-white shadow-2xl">
@@ -370,7 +404,7 @@ export function AssistantLauncher() {
结束会话
</Button>
<button
onClick={() => setOpen(false)}
onClick={closeAssistant}
aria-label="收起助手"
className="rounded-lg p-2 text-slate-400 transition-colors hover:bg-slate-100 hover:text-slate-600"
>
@@ -414,7 +448,7 @@ export function AssistantLauncher() {
<>
<div ref={scrollRef} className="flex-1 space-y-4 overflow-y-auto px-5 py-4">
{historyLoading && messages.length === 0 && (
<p className="py-8 text-center text-sm text-slate-400">正在恢复会话...</p>
<p className="py-8 text-center text-sm text-slate-400">正在建立会话...</p>
)}
{historyError && (
<p className="rounded-lg bg-red-50 px-3 py-2 text-xs text-red-600">{historyError}</p>
+207 -47
View File
@@ -1,12 +1,11 @@
"use client";
import { Bot, MessageCircle, Send, X } from "lucide-react";
import { useState } from "react";
import { apiFetch, apiStream } from "@/lib/api";
interface AgentChatProps {
employeeMode?: boolean;
}
import { Bot, MessageCircle, RotateCw, Send, X } from "lucide-react";
import { useCallback, useEffect, useRef, useState } from "react";
import { apiFetch } from "@/lib/api";
import { getToken } from "@/lib/auth";
import { chatAgentApi, type ChatAgentMode } from "@/lib/chat-agent-api";
import { USER_TYPE } from "@/lib/roles";
interface ChatMessage {
id: number;
@@ -14,72 +13,233 @@ interface ChatMessage {
content: string;
}
export function AgentChat({ employeeMode = false }: AgentChatProps) {
const GREETING = "您好,我是华夏基金智能助手。您可以咨询基金产品、风险等级和净值信息。";
/**
* 选择用哪个 Agent:
* - 已登录客户 → /agent/client/*(能读本人持仓与交易)
* - 游客 / 员工 → /agent/customer/*(匿名客服,不需要 token)
* 探测失败一律退回匿名客服,不阻断用户。
*/
async function resolveMode(): Promise<ChatAgentMode> {
if (!getToken()) return "customer";
try {
const result = await apiFetch<{ user?: { user_type?: string | null } }>("/auth/me");
return result?.user?.user_type === USER_TYPE.CUSTOMER ? "client" : "customer";
} catch {
return "customer";
}
}
export function AgentChat() {
const [open, setOpen] = useState(false);
const [input, setInput] = useState("");
const [loading, setLoading] = useState(false);
const [sending, setSending] = useState(false);
const [connecting, setConnecting] = useState(false);
const [sessionId, setSessionId] = useState<string | null>(null);
const [mode, setMode] = useState<ChatAgentMode>("customer");
const [error, setError] = useState<string | null>(null);
const [messages, setMessages] = useState<ChatMessage[]>([
{ id: 1, role: "agent", content: "您好,我是华夏基金智能助手。您可以咨询基金产品、风险等级和净值信息。" },
{ id: 1, role: "agent", content: GREETING },
]);
async function ensureSession() {
if (employeeMode) return "";
if (sessionId) return sessionId;
const result = await apiFetch<{ session_id: string }>("/agent/customer/session/create", { method: "POST" });
setSessionId(result.session_id);
return result.session_id;
}
const abortRef = useRef<AbortController | null>(null);
const listRef = useRef<HTMLDivElement | null>(null);
async function sendMessage() {
const content = input.trim();
if (!content || loading) return;
setInput("");
setMessages((current) => [...current, { id: Date.now(), role: "user", content }]);
setLoading(true);
useEffect(() => () => abortRef.current?.abort(), []);
useEffect(() => {
listRef.current?.scrollTo({ top: listRef.current.scrollHeight, behavior: "smooth" });
}, [messages, connecting]);
/** 建立会话:探测 Agent 类型 → session/create 换取后端签发的 session_id。 */
const connect = useCallback(async () => {
setConnecting(true);
setError(null);
try {
const activeSessionId = await ensureSession();
const response = employeeMode
? await apiStream("/advisor-agent/chat/stream", { query: content })
: await apiStream("/agent/customer/chat", { session_id: activeSessionId, query: content });
setMessages((current) => [...current, { id: Date.now() + 1, role: "agent", content: response || "暂时没有找到合适的回答,请稍后再试。" }]);
} catch {
setMessages((current) => [...current, { id: Date.now() + 1, role: "agent", content: "当前服务暂时不可用,请稍后再试。" }]);
const resolved = await resolveMode();
const session = await chatAgentApi.createSession(resolved);
setMode(resolved);
setSessionId(session.session_id);
} catch (err) {
setError(err instanceof Error ? err.message : "会话建立失败,请重试");
} finally {
setLoading(false);
setConnecting(false);
}
}
}, []);
async function closeChat() {
/** 打开面板即建立会话(不是等用户第一次提问才建)。 */
const openChat = useCallback(() => {
setOpen(true);
if (!sessionId && !connecting) void connect();
}, [connect, connecting, sessionId]);
/** 关闭面板即结束会话:通知后端清理上下文与限流键,本地一并重置。 */
const closeChat = useCallback(async () => {
abortRef.current?.abort();
setOpen(false);
if (!sessionId || employeeMode) return;
try { await apiFetch("/agent/customer/session/end", { method: "POST", body: JSON.stringify({ session_id: sessionId }) }); } catch { /* session cleanup is best effort */ }
setInput("");
setError(null);
setMessages([{ id: Date.now(), role: "agent", content: GREETING }]);
const current = sessionId;
setSessionId(null);
}
if (!current) return;
try {
await chatAgentApi.endSession(mode, current);
} catch {
/* 会话清理失败不阻断用户 */
}
}, [mode, sessionId]);
const sendMessage = useCallback(async () => {
const content = input.trim();
if (!content || sending || connecting) return;
if (!sessionId) {
setError("会话尚未建立,请点击重试。");
return;
}
setInput("");
setError(null);
setMessages((prev) => [...prev, { id: Date.now(), role: "user", content }]);
setSending(true);
const controller = new AbortController();
abortRef.current = controller;
try {
const result = await chatAgentApi.chat(
mode,
{ session_id: sessionId, query: content },
controller.signal
);
setMessages((prev) => [
...prev,
{
id: Date.now() + 1,
role: "agent",
content: result.error || result.text || "暂时没有找到合适的回答,请稍后再试。",
},
]);
} catch (err) {
if ((err as Error)?.name === "AbortError") return;
setMessages((prev) => [
...prev,
{
id: Date.now() + 1,
role: "agent",
content: err instanceof Error ? err.message : "当前服务暂时不可用,请稍后再试。",
},
]);
} finally {
setSending(false);
abortRef.current = null;
}
}, [connecting, input, mode, sending, sessionId]);
const ready = !!sessionId;
return (
<div className="fixed bottom-3 right-7 z-50">
{open && (
<div role="dialog" aria-label="华夏基金智能助手" className="mb-4 flex h-[520px] w-[380px] flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-2xl">
<div
role="dialog"
aria-label="华夏基金智能助手"
className="mb-4 flex h-[520px] w-[380px] flex-col overflow-hidden rounded-2xl border border-slate-200 bg-white shadow-2xl"
>
<div className="flex items-center justify-between bg-[var(--brand-navy)] px-5 py-4 text-white">
<div className="flex items-center gap-3">
<div className="flex h-9 w-9 items-center justify-center rounded-xl bg-[var(--brand-primary)]"><Bot className="h-5 w-5" /></div>
<div><p className="text-sm font-semibold">华夏基金智能助手</p><p className="mt-0.5 text-xs text-blue-100">在线为您提供基金信息服务</p></div>
<div className="flex h-9 w-9 items-center justify-center rounded-xl bg-[var(--brand-primary)]">
<Bot className="h-5 w-5" />
</div>
<div>
<p className="text-sm font-semibold">华夏基金智能助手</p>
<p className="mt-0.5 text-xs text-blue-100">
{mode === "client" ? "已接入您的账户数据" : "在线为您提供基金信息服务"}
</p>
</div>
</div>
<button aria-label="关闭聊天框" onClick={() => void closeChat()} className="rounded-lg p-2 text-blue-100 transition hover:bg-white/10 hover:text-white"><X className="h-4 w-4" /></button>
<button
aria-label="关闭聊天框"
onClick={() => void closeChat()}
className="rounded-lg p-2 text-blue-100 transition hover:bg-white/10 hover:text-white"
>
<X className="h-4 w-4" />
</button>
</div>
<div className="flex-1 space-y-4 overflow-y-auto bg-slate-50 p-4">
{messages.map((message) => <div key={message.id} className={`flex ${message.role === "user" ? "justify-end" : "justify-start"}`}><div className={`max-w-[82%] rounded-2xl px-4 py-3 text-sm leading-6 ${message.role === "user" ? "rounded-br-md bg-[var(--brand-primary)] text-white" : "rounded-bl-md border border-slate-200 bg-white text-slate-700"}`}>{message.content}</div></div>)}
{loading && <div className="text-xs text-slate-400">正在整理信息...</div>}
<div ref={listRef} className="flex-1 space-y-4 overflow-y-auto bg-slate-50 p-4">
{messages.map((message) => (
<div
key={message.id}
className={`flex ${message.role === "user" ? "justify-end" : "justify-start"}`}
>
<div
className={`max-w-[82%] rounded-2xl px-4 py-3 text-sm leading-6 ${
message.role === "user"
? "rounded-br-md bg-[var(--brand-primary)] text-white"
: "rounded-bl-md border border-slate-200 bg-white text-slate-700"
}`}
>
{message.content}
</div>
</div>
))}
{connecting && (
<div className="flex items-center gap-2 text-xs text-slate-400">
<RotateCw className="h-3 w-3 animate-spin" />
正在建立会话...
</div>
)}
{sending && !connecting && <div className="text-xs text-slate-400">正在整理信息...</div>}
</div>
<form onSubmit={(event) => { event.preventDefault(); void sendMessage(); }} className="flex gap-2 border-t border-slate-200 bg-white p-3">
<input value={input} onChange={(event) => setInput(event.target.value)} placeholder="输入您的问题" className="min-w-0 flex-1 rounded-xl border border-slate-200 px-3 py-2.5 text-sm outline-none transition focus:border-[var(--brand-primary)]" />
<button type="submit" aria-label="发送消息" className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-[var(--brand-primary)] text-white transition hover:bg-[var(--brand-primary-dark)] disabled:cursor-not-allowed disabled:opacity-50" disabled={loading || !input.trim()}><Send className="h-4 w-4" /></button>
{error && (
<div className="flex items-center justify-between gap-3 border-t border-rose-100 bg-rose-50 px-4 py-2.5">
<span className="text-xs text-rose-600">{error}</span>
{!ready && (
<button
onClick={() => void connect()}
disabled={connecting}
className="shrink-0 rounded-lg border border-rose-200 bg-white px-2.5 py-1 text-xs text-rose-600 transition hover:bg-rose-100 disabled:opacity-50"
>
重试
</button>
)}
</div>
)}
<form
onSubmit={(event) => {
event.preventDefault();
void sendMessage();
}}
className="flex gap-2 border-t border-slate-200 bg-white p-3"
>
<input
value={input}
onChange={(event) => setInput(event.target.value)}
placeholder={ready ? "输入您的问题" : "正在准备会话..."}
disabled={connecting}
className="min-w-0 flex-1 rounded-xl border border-slate-200 px-3 py-2.5 text-sm outline-none transition focus:border-[var(--brand-primary)] disabled:bg-slate-50"
/>
<button
type="submit"
aria-label="发送消息"
className="flex h-10 w-10 shrink-0 items-center justify-center rounded-xl bg-[var(--brand-primary)] text-white transition hover:bg-[var(--brand-primary-dark)] disabled:cursor-not-allowed disabled:opacity-50"
disabled={sending || connecting || !input.trim()}
>
<Send className="h-4 w-4" />
</button>
</form>
</div>
)}
<button aria-label={open ? "收起智能助手" : "打开智能助手"} onClick={() => setOpen((value) => !value)} className="flex h-14 w-14 items-center justify-center rounded-full bg-[var(--brand-primary)] text-white shadow-lg shadow-indigo-900/25 transition hover:-translate-y-0.5 hover:bg-[var(--brand-primary-dark)]">{open ? <X className="h-5 w-5" /> : <MessageCircle className="h-5 w-5" />}</button>
<button
aria-label={open ? "收起智能助手" : "打开智能助手"}
onClick={() => (open ? void closeChat() : openChat())}
className="flex h-14 w-14 items-center justify-center rounded-full bg-[var(--brand-primary)] text-white shadow-lg shadow-indigo-900/25 transition hover:-translate-y-0.5 hover:bg-[var(--brand-primary-dark)]"
>
{open ? <X className="h-5 w-5" /> : <MessageCircle className="h-5 w-5" />}
</button>
</div>
);
}
+62 -22
View File
@@ -29,6 +29,22 @@ function handleUnauthorized(status: number) {
if (!window.location.pathname.startsWith("/login")) window.location.href = "/login";
}
/**
* 从错误响应体里取后端给的原因(如「会话不存在或已过期」)。
* 非 2xx 时后端返回的是 JSON(utils/response.fail),部分场景也会包成 SSE。
*/
function extractErrorMessage(body: string): string | undefined {
const text = body.trim();
if (!text) return undefined;
const jsonText = text.startsWith("data:") ? text.split("\n")[0].slice(5).trim() : text;
try {
const payload = JSON.parse(jsonText) as { message?: string; error?: string };
return payload?.message ?? payload?.error;
} catch {
return undefined;
}
}
/**
* 后端存在两套成功码,必须都认:
* - utils/response.success → code 200(工作台、风控、工单等)
@@ -126,6 +142,8 @@ export interface SSESummary {
traceId?: string;
/** error 事件里的提示文案。 */
error?: string;
/** 客服 Agent 命中的知识来源(裸 JSON 响应里的 sources)。 */
sources?: unknown[];
}
/**
@@ -152,7 +170,13 @@ export async function readSSE(
});
handleUnauthorized(response.status);
if (!response.ok) throw new ApiError("请求失败,请稍后重试", response.status);
if (!response.ok) {
const body = await response.text();
throw new ApiError(
extractErrorMessage(body) ?? "请求失败,请稍后重试",
response.status
);
}
const summary: SSESummary = { text: "" };
const raw = await response.text();
@@ -170,29 +194,45 @@ export async function readSSE(
continue; /* 忽略心跳与非 JSON 块 */
}
if (event.type === "text") {
summary.text += event.content ?? "";
} else if (event.type === "meta") {
summary.intent = event.intent;
summary.draftId = event.draft_id;
summary.queryId = event.query_id;
summary.traceId = event.trace_id;
} else if (event.type === "done") {
if (event.draft_id) summary.draftId = event.draft_id;
if (event.query_id) summary.queryId = event.query_id;
} else if (event.type === "error") {
summary.error = event.message ?? "助手返回错误,请稍后重试";
const record = event as Record<string, unknown>;
const type = typeof record.type === "string" ? record.type : undefined;
if (type === "text") {
summary.text += (record.content as string) ?? "";
} else if (type === "meta") {
summary.intent = record.intent as string | undefined;
summary.draftId = record.draft_id as string | undefined;
summary.queryId = record.query_id as string | undefined;
summary.traceId = record.trace_id as string | undefined;
} else if (type === "done") {
if (record.draft_id) summary.draftId = record.draft_id as string;
if (record.query_id) summary.queryId = record.query_id as string;
} else if (type === "error") {
summary.error = (record.message as string) ?? "助手返回错误,请稍后重试";
} else if (!type) {
/*
* 无 type 的响应——客服 Agent / 客户 Agent 不用事件包装,直接 dump 业务对象:
* service/customer_agent/chat.py → {answer, sources, intent, rewritten_query, trace_id}
* 另兼容 success() 包装的 {code, message, data}(取值时自动下钻一层 data)。
* 旧实现只认 type=text,导致这两个 Agent 的回复恒为空串(聊天框永远回「暂时没有找到合适的回答」)。
*/
const node =
record.data && typeof record.data === "object"
? (record.data as Record<string, unknown>)
: record;
const answer = node.answer ?? node.content ?? node.summary;
if (typeof answer === "string" && answer) {
summary.text += answer;
} else if (typeof record.message === "string" && record.message) {
summary.error = record.message;
}
if (typeof node.intent === "string") summary.intent = node.intent;
if (typeof node.query_id === "string") summary.queryId = node.query_id;
const trace = node.trace_id ?? record.trace_id;
if (typeof trace === "string") summary.traceId = trace;
if (Array.isArray(node.sources)) summary.sources = node.sources;
}
}
return summary;
}
/**
* 取 SSE 响应的正文文本(客服/客户 Agent 聊天用)。
* 旧实现只取第一个 data 行,命中 meta 事件时会拿到空串,这里改为聚合全部 text 事件。
*/
export async function apiStream(path: string, body: unknown): Promise<string> {
const summary = await readSSE(path, body);
return summary.error || summary.text;
}
+44
View File
@@ -0,0 +1,44 @@
import { apiFetch, readSSE, type SSESummary } from "@/lib/api";
/**
* 客户端两个 Agent 的会话适配层。
*
* 两者都是「打开建会话 → 带 session_id 对话 → 关闭结束会话」的三段式,
* 后端的会话归属校验会拒绝未创建或不属于自己的 session_id(SessionOwnershipError),
* 所以 session_id 必须来自 session/create,不能在前端自己造。
*
* - customer:匿名客服 Agent(/api/agent/customer/*),游客与登录用户都可用,无需 token
* - client :登录客户 Agent(/api/agent/client/*),需 require_customer,
* 能读到本人持仓 / 交易(匿名版没有 customer_id,数据查询会被引导去登录)
*/
export type ChatAgentMode = "customer" | "client";
const PREFIX: Record<ChatAgentMode, string> = {
customer: "/agent/customer",
client: "/agent/client",
};
export interface AgentSession {
session_id: string;
customer_id: number | null;
}
export const chatAgentApi = {
/** POST /session/create —— 建立会话,返回后端签发的 session_id。 */
createSession: (mode: ChatAgentMode) =>
apiFetch<AgentSession>(`${PREFIX[mode]}/session/create`, { method: "POST" }),
/** POST /chat —— 响应是 SSE 包装,但内容为 {answer, sources, intent...}。 */
chat: (
mode: ChatAgentMode,
body: { session_id: string; query: string },
signal?: AbortSignal
): Promise<SSESummary> => readSSE(`${PREFIX[mode]}/chat`, body, signal),
/** POST /session/end —— 关闭会话并清理服务端上下文与限流键。 */
endSession: (mode: ChatAgentMode, sessionId: string) =>
apiFetch<{ session_id: string; archived?: boolean }>(`${PREFIX[mode]}/session/end`, {
method: "POST",
body: JSON.stringify({ session_id: sessionId }),
}),
};
+2 -2
View File
@@ -1,7 +1,7 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
import "./.next/dev/types/routes.d.ts";
import "./.next/dev/types/root-params.d.ts";
import "./.next/types/routes.d.ts";
import "./.next/types/root-params.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.