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())