fix: 草稿首次落库前先改绑发布助手会话,避免路由重挂新建空会话

This commit is contained in:
2026-10-20 15:57:49 +08:00
parent 9bbb01fdee
commit e667871c58
6 changed files with 263 additions and 8 deletions
+16 -2
View File
@@ -27,6 +27,8 @@ class PatchSessionBody(BaseModel):
title: str | None = Field(default=None, min_length=1, max_length=200)
llmProviderId: int | None = None
llmModel: str | None = None
# 未落库会话(local-*)改绑到稳定业务键,如系统草稿 ID
sceneRef: str | None = Field(default=None, min_length=1, max_length=200)
def _session_vo(s) -> dict:
@@ -84,11 +86,23 @@ async def patch_session(
actor: Actor = Depends(current_actor),
svc: SessionService = Depends(session_service),
):
if body.title is None and body.llmModel is None and body.llmProviderId is None:
if (
body.title is None
and body.llmModel is None
and body.llmProviderId is None
and body.sceneRef is None
):
raise HTTPException(status_code=400, detail="无有效更新字段")
try:
s = None
if body.title is not None:
if body.sceneRef is not None:
s = await svc.rebind_scene_ref(
actor,
thread_id,
scene_ref=body.sceneRef,
title=body.title,
)
elif body.title is not None:
s = await svc.rename(actor, thread_id, body.title)
if body.llmModel is not None or body.llmProviderId is not None:
if body.llmModel is None or body.llmProviderId is None:
+37
View File
@@ -91,6 +91,43 @@ class SessionService:
session.title = title.strip() or session.title
return await self._sessions.update(session)
async def rebind_scene_ref(
self,
actor: Actor,
thread_id: str,
*,
scene_ref: str,
title: str | None = None,
) -> Session:
"""把未落库会话(scene_ref=local-*)改绑到稳定业务键(如系统草稿 ID)。"""
new_ref = (scene_ref or "").strip()
if not new_ref:
raise ValueError("scene_ref 不能为空")
if new_ref.startswith("local-"):
raise ValueError("不能改绑到临时 local 键")
session = await self.require_owned(actor, thread_id)
if session.scene_ref == new_ref:
if title is not None:
session.title = title.strip() or session.title
return await self._sessions.update(session)
return session
current = (session.scene_ref or "").strip()
if current and not current.startswith("local-"):
raise ValueError("仅未落库会话可改绑 scene_ref")
existing = await self.find_by_scene_ref(
actor, scene=session.scene or "general", scene_ref=new_ref
)
if existing is not None and existing.thread_id != thread_id:
raise ValueError("该业务对象已有关联会话")
session.scene_ref = new_ref
if title is not None:
session.title = title.strip() or session.title
return await self._sessions.update(session)
async def update_llm_selection(
self,
actor: Actor,
+119
View File
@@ -0,0 +1,119 @@
"""未落库会话 scene_ref 改绑规则。"""
from __future__ import annotations
import asyncio
from datetime import datetime
from typing import Any
from application.session_service import SessionService
from domain.models import Actor, Session, SessionStatus
class _MemSessions:
def __init__(self) -> None:
self.rows: dict[str, Session] = {}
async def create(self, session: Session) -> Session:
self.rows[session.thread_id] = session
return session
async def get(self, company_id: int, user_id: str, thread_id: str) -> Session | None:
s = self.rows.get(thread_id)
if s is None:
return None
if s.company_id != company_id or s.user_id != user_id:
return None
return s
async def list_active(self, *args: Any, **kwargs: Any) -> list[Session]:
return []
async def find_active_by_scene_ref(
self,
company_id: int,
user_id: str,
*,
scene: str,
scene_ref: str,
) -> Session | None:
for s in self.rows.values():
if (
s.company_id == company_id
and s.user_id == user_id
and s.status == SessionStatus.ACTIVE
and (s.scene or "general") == scene
and s.scene_ref == scene_ref
):
return s
return None
async def update(self, session: Session) -> Session:
self.rows[session.thread_id] = session
return session
def _actor() -> Actor:
return Actor(company_id=1, user_id="u1")
def _session(*, thread_id: str, scene_ref: str | None) -> Session:
now = datetime.utcnow()
return Session(
thread_id=thread_id,
company_id=1,
user_id="u1",
title="发布草稿(未保存)",
status=SessionStatus.ACTIVE,
scene="ecom_goods_publish",
scene_ref=scene_ref,
created_at=now,
updated_at=now,
)
def test_rebind_local_to_draft_id():
repo = _MemSessions()
svc = SessionService(repo)
async def scenario():
local = _session(thread_id="t1", scene_ref="local-abc")
await repo.create(local)
out = await svc.rebind_scene_ref(
_actor(), "t1", scene_ref="42", title="发布草稿 #42"
)
assert out.scene_ref == "42"
assert out.title == "发布草稿 #42"
asyncio.run(scenario())
def test_rebind_rejects_non_local():
repo = _MemSessions()
svc = SessionService(repo)
async def scenario():
await repo.create(_session(thread_id="t1", scene_ref="7"))
try:
await svc.rebind_scene_ref(_actor(), "t1", scene_ref="8")
raise AssertionError("expected ValueError")
except ValueError as e:
assert "未落库" in str(e)
asyncio.run(scenario())
def test_rebind_rejects_occupied_draft():
repo = _MemSessions()
svc = SessionService(repo)
async def scenario():
await repo.create(_session(thread_id="t-old", scene_ref="9"))
await repo.create(_session(thread_id="t-local", scene_ref="local-x"))
try:
await svc.rebind_scene_ref(_actor(), "t-local", scene_ref="9")
raise AssertionError("expected ValueError")
except ValueError as e:
assert "已有关联会话" in str(e)
asyncio.run(scenario())
+7 -1
View File
@@ -115,7 +115,13 @@ export async function submitAgentClientToolResultApi(
export async function patchAgentSessionApi(
threadId: string,
body: { title?: string; llmProviderId?: number; llmModel?: string },
body: {
title?: string;
llmProviderId?: number;
llmModel?: string;
/** 未落库会话(local-*)改绑到系统草稿 ID */
sceneRef?: string;
},
) {
return requestClient.patch<AgentVO.Session>(
`/agent/sessions/${threadId}`,
@@ -50,6 +50,8 @@ const emit = defineEmits<{
}>();
const SCENE = 'ecom_goods_publish' as const;
/** 跨路由重挂:记住未落库会话 threadId,保存草稿后改绑用 */
const PENDING_LOCAL_THREAD_KEY = 'pdd-publish-agent-pending-thread';
/** 未落库时用本地 sceneRef,落库后切到草稿 ID */
const localSceneKey = `local-${
@@ -64,6 +66,30 @@ const sceneRef = computed(() =>
: localSceneKey,
);
function rememberPendingLocalThread(threadId: string) {
try {
sessionStorage.setItem(PENDING_LOCAL_THREAD_KEY, threadId);
} catch {
/* ignore quota / private mode */
}
}
function peekPendingLocalThread(): string | null {
try {
return sessionStorage.getItem(PENDING_LOCAL_THREAD_KEY);
} catch {
return null;
}
}
function clearPendingLocalThread() {
try {
sessionStorage.removeItem(PENDING_LOCAL_THREAD_KEY);
} catch {
/* ignore */
}
}
const sessionTitle = computed(() =>
props.draftId != null && props.draftId > 0
? `发布草稿 #${props.draftId}`
@@ -243,16 +269,21 @@ async function loadEnabledModels() {
async function ensureSession(): Promise<string | null> {
if (session.value?.threadId) return session.value.threadId;
const parsed = parseModelKey(selectedModelKey.value);
const ref = sceneRef.value;
const s = await createAgentSessionApi({
title: sessionTitle.value,
llmProviderId: parsed?.providerId,
llmModel: parsed?.model,
scene: SCENE,
sceneRef: sceneRef.value,
sceneRef: ref,
reuseBySceneRef: true,
});
session.value = s;
syncSelectedFromSession();
// 未落库会话写入 pending,供 new→真实 ID 路由重挂后改绑
if (ref.startsWith('local-') && s.threadId) {
rememberPendingLocalThread(s.threadId);
}
return s.threadId;
}
@@ -278,6 +309,36 @@ async function loadMessages(threadId: string) {
}
}
/**
* 草稿首次落库:把 local-* 会话改绑到草稿 ID。
* 须在路由 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;
try {
const s = await patchAgentSessionApi(threadId, {
sceneRef: String(draftId),
title: `发布草稿 #${draftId}`,
});
session.value = session.value
? { ...session.value, ...s }
: s;
clearPendingLocalThread();
return true;
} catch (e: any) {
// 该草稿已有别的会话等冲突:不打断当前编辑
console.warn(e?.message || '发布助手会话改绑失败');
return false;
}
}
async function bootstrap() {
loadingSession.value = true;
messages.value = [];
@@ -286,6 +347,10 @@ async function bootstrap() {
citations.value = [];
try {
await loadEnabledModels();
// 路由重挂后 draftId 已是真实 ID:先尝试把 pending 的 local 会话改绑过来
if (props.draftId != null && props.draftId > 0 && peekPendingLocalThread()) {
await rebindSessionToDraft(props.draftId);
}
const threadId = await ensureSession();
if (threadId) await loadMessages(threadId);
} catch (e: any) {
@@ -298,8 +363,9 @@ async function bootstrap() {
watch(
() => props.draftId,
(id, prev) => {
// 新建落库后仅 URL 从 new→id:沿用当前会话,避免打断
// 同页内 new→id 且会话仍在:改绑后不重建(父级也会在 replace 前主动改绑)
if (prev == null && id != null && id > 0 && session.value?.threadId) {
void rebindSessionToDraft(id);
return;
}
abort?.abort();
@@ -308,6 +374,10 @@ watch(
{ immediate: true },
);
defineExpose({
rebindSessionToDraft,
});
async function onModelChange(key: string) {
if (!key || !key.includes('::')) return;
selectedModelKey.value = key;
@@ -37,6 +37,9 @@ const presetPddShopId = computed(() => {
});
const editorRef = ref<PublishEditorAgentApi | null>(null);
const agentPanelRef = ref<{
rebindSessionToDraft: (draftId: number) => Promise<boolean>;
} | null>(null);
/** 显式取 .value,避免把组件 ref 本体传给子组件导致偶发取不到命令面 */
const editorApi = computed(() => editorRef.value);
const { width: agentWidthPct, collapsed: agentCollapsed } =
@@ -59,10 +62,15 @@ function goBack() {
void router.push('/pdd/goods/publish');
}
/** 首次落库后把 URL 换成真实草稿 ID,便于刷新续编与 Agent 绑定 */
function onDraftSaved(id: number) {
/** 首次落库:先把发布助手 local 会话改绑到草稿 ID,再改 URL(避免路由重挂丢掉临时会话) */
async function onDraftSaved(id: number) {
if (!id || draftId.value === id) return;
void router.replace({
try {
await agentPanelRef.value?.rebindSessionToDraft(id);
} catch {
/* 改绑失败仍替换 URL,bootstrap 会再试 pending */
}
await router.replace({
path: `/pdd/goods/publish/editor/${id}`,
query: {},
});
@@ -103,6 +111,7 @@ function onDraftSaved(id: number) {
:style="agentPaneStyle"
>
<PddPublishAgentPanel
ref="agentPanelRef"
class="h-full min-h-0"
:draft-id="draftId"
:collapsed="agentCollapsed"