fix: 发布助手改为首次发消息再建会话,避免空草稿刷会话

This commit is contained in:
2026-10-20 16:00:25 +08:00
parent e667871c58
commit b8005db2dc
@@ -15,6 +15,7 @@ import {
createAgentSessionApi,
listAgentEnabledLlmModelsApi,
listAgentMessagesApi,
listAgentSessionsApi,
patchAgentSessionApi,
streamAgentChat,
submitAgentClientToolResultApi,
@@ -265,9 +266,29 @@ async function loadEnabledModels() {
}
}
/** 复用或创建本草稿的发布场景会话 */
/** 仅查找已有会话,不创建(打开草稿时恢复历史用) */
async function findExistingSession(): Promise<string | null> {
if (session.value?.threadId) return session.value.threadId;
const ref = sceneRef.value;
// 临时键不会落库关联,不必查
if (!ref || ref.startsWith('local-')) return null;
try {
const res = await listAgentSessionsApi({ scene: SCENE });
const hit = (res.items || []).find((s) => s.sceneRef === ref);
if (!hit?.threadId) return null;
session.value = hit;
syncSelectedFromSession();
return hit.threadId;
} catch {
return null;
}
}
/** 首次发消息时创建或复用;打开页面不调用,避免空会话堆积 */
async function ensureSession(): Promise<string | null> {
if (session.value?.threadId) return session.value.threadId;
const existing = await findExistingSession();
if (existing) return existing;
const parsed = parseModelKey(selectedModelKey.value);
const ref = sceneRef.value;
const s = await createAgentSessionApi({
@@ -310,26 +331,19 @@ async function loadMessages(threadId: string) {
}
/**
* 草稿首次落库:把 local-* 会话改绑到草稿 ID。
* 草稿首次落库:把已存在的 local-* 会话改绑到草稿 ID。
* 用户未发过消息则没有会话,直接返回 true(无需改绑)。
* 须在路由 replace 之前调用:new→id 常会整页重挂,内存会话会丢。
*/
async function rebindSessionToDraft(draftId: number): Promise<boolean> {
let threadId = session.value?.threadId || peekPendingLocalThread();
if (!threadId) {
// 尚未 ensure 时先建临时会话再改绑
if (props.draftId == null) {
threadId = (await ensureSession()) ?? null;
}
}
if (!threadId) return false;
const threadId = session.value?.threadId || peekPendingLocalThread();
if (!threadId) return true;
try {
const s = await patchAgentSessionApi(threadId, {
sceneRef: String(draftId),
title: `发布草稿 #${draftId}`,
});
session.value = session.value
? { ...session.value, ...s }
: s;
session.value = session.value ? { ...session.value, ...s } : s;
clearPendingLocalThread();
return true;
} catch (e: any) {
@@ -351,7 +365,8 @@ async function bootstrap() {
if (props.draftId != null && props.draftId > 0 && peekPendingLocalThread()) {
await rebindSessionToDraft(props.draftId);
}
const threadId = await ensureSession();
// 只恢复已有会话,绝不在打开页时新建(避免空草稿刷会话)
const threadId = await findExistingSession();
if (threadId) await loadMessages(threadId);
} catch (e: any) {
message.error(e?.message || '初始化发布助手失败');