Files
Cyrene_v2/internal/services/gateway/history_persona_test.go
T
AskaEth 0624d9ee36
CI / Backend (build / vet / test / cross-compile) (push) Has been cancelled
CI / Frontend (tsc + vite build) (push) Has been cancelled
feat(session,runtime): 多角色并存—按会话选角(迁移0011 + 按回合解析 + agent池 + 提取器修正)
按 DevDocs/design/22 批次 1 后端(§2/§3/§4.1-4.5/§4.7/§5 验收 1-6)。
- 迁移 0011:chat_sessions.persona_id + chat_messages.persona_id(均 DEFAULT '',无回填 → 升级零风险);同步包内幂等 DDL;**真实库升级验证**(拷贝 data/cyrene.db 到临时目录跑 MigrateUp:既有 1 会话/109 消息 persona 仍为 '',原库未被触碰)
- history:SessionMeta/Message 加 PersonaID + SetSessionPersona;ListSessions/List/scan/Append 带上
- runtime:SessionEnv.PersonaID + loop.personaFor(ctx) 替换固定 l.personaID(memory/request/turn)+ **agent 池**(Options.Agents,按角色取 instructions,未命中回落)+ **提取器不再把 persona 烤死在构造期**(多角色下记忆不再永远记在 cyrene 名下)+ **thinking 旋钮改为按会话角色解析**(否则角色 Y 会用角色 X 的预算/展示)
- gateway:会话 DTO/POST/PATCH 支持 personaId;ws/rest/voice 的 OwnerEnv 硬编改为**按会话解析角色**(actor 元数据语义不变);admin memories 搜索去掉硬编 cyrene
- Docs/api-client v0.42;**两处有意的行为收紧**已写明:POST /sessions body 非法 JSON → 400(原先完全忽略 body;空/null/{} 仍 201);POST /admin/memories/search 省略 personaId 且无默认角色 → 400(原先默认查 cyrene)
- 测试:design/22 §5 验收 1-6(记忆隔离/提示词首条 system/情绪按角色/提取 persona 归属/迁移兼容)+ 进程内 e2e(断言 adapter 收到的 model.Request.Messages[0] 即该角色的 systemPrompt)
- **已知未做(留批次 2 / 待确认)**:① IM 与渠道级未做 → **§7-3「owner 私聊镜像随主会话角色」尚未生效**;② 请求级覆盖未实现(本批只做会话级);③ **§7-5 的「上下文发送角色标记」只完成存储+DTO 半边**——消息 persona 已落库且 DTO 已带,但模型上下文不从 chat_messages 重建,「第 N 条是谁说的」尚未进上下文(需确认是否属批次 2);④「切角色重建摘要」当前是空操作(压缩未接线);⑤ thinking 旋钮仅在流式路径生效(非流式 agent.RunStep 不带,A 批次既有性质)
- 验收:go build/vet/test 全绿 + linux/amd64 与 darwin/arm64 交叉编译(既有 flake 本轮未触发;同批 session_orchestrator.go 一度 501 行 → 抽出 session_tail.go)
2026-10-03 20:12:29 +08:00

315 lines
12 KiB
Go

package gateway
import (
"context"
"encoding/json"
"net/http"
"testing"
"git.yeij.top/AskaEth/Cyrene_v2/internal/auth"
"git.yeij.top/AskaEth/Cyrene_v2/internal/db"
"git.yeij.top/AskaEth/Cyrene_v2/internal/persona/loader"
personareg "git.yeij.top/AskaEth/Cyrene_v2/internal/persona/registry"
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/agent"
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/history"
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/loop"
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/model"
)
// This file covers the gateway half of design/22 (多角色并存 + 按会话选角): the REST
// contract for binding a session to a role, and the resolver that turns a
// sessionID into the loop environment the turn runs under. The chain asserted end to
// end is: sessionID → chat_sessions.persona_id → turnEnvResolver → loop.SessionEnv →
// per-role agent (system prompt), so a regression at any hop shows up as the wrong
// role answering.
// personaAdapter records every request the loop built, so a test can assert which
// role's system prompt actually reached the model.
type personaAdapter struct {
reqs []model.Request
}
func (p *personaAdapter) Name() string { return "persona-test" }
func (p *personaAdapter) Chat(_ context.Context, req model.Request, _ model.Options) (model.Response, error) {
p.reqs = append(p.reqs, req)
return model.Response{Content: "好呀"}, nil
}
func (p *personaAdapter) ChatStream(ctx context.Context, req model.Request, _ func(model.StreamEvent)) (model.Response, error) {
return p.Chat(ctx, req, model.Options{})
}
// personaTestRegistry registers two roles (one default) so the gateway can validate
// personaId values and resolve the default role.
func personaTestRegistry(t *testing.T) *personareg.Registry {
t.Helper()
reg := personareg.New()
for _, p := range []*loader.Persona{
{ID: "xilian", Name: "昔涟"},
{ID: "yuki", Name: "由纪"},
} {
if err := reg.RegisterPersona(p); err != nil {
t.Fatalf("RegisterPersona(%s): %v", p.ID, err)
}
}
if err := reg.RegisterCharacter(&personareg.Character{ID: "xilian", Name: "昔涟", Default: true, PersonaID: "xilian"}); err != nil {
t.Fatalf("RegisterCharacter(xilian): %v", err)
}
if err := reg.RegisterCharacter(&personareg.Character{ID: "yuki", Name: "由纪", PersonaID: "yuki"}); err != nil {
t.Fatalf("RegisterCharacter(yuki): %v", err)
}
return reg
}
// personaTestStore opens an in-memory chat-history store.
func personaTestStore(t *testing.T) *history.Store {
t.Helper()
ctx := context.Background()
conn, err := db.Open(ctx, ":memory:", testLogger())
if err != nil {
t.Fatalf("db.Open: %v", err)
}
t.Cleanup(func() { _ = conn.Close() })
st, err := history.NewStore(ctx, conn, testLogger())
if err != nil {
t.Fatalf("history.NewStore: %v", err)
}
return st
}
// gatewayAgentFor builds the per-role agent the composition root would build: the
// same adapter, a role-specific instruction string.
func gatewayAgentFor(t *testing.T, instructions string, ad model.Adapter) *agent.Agent {
t.Helper()
ag, err := agent.New(instructions, nil, nil, agent.WithModel(ad, nil))
if err != nil {
t.Fatalf("agent.New(%q): %v", instructions, err)
}
return ag
}
// TestChatTurnAnswersAsTheBoundRole is design/22 acceptance 3 seen from the process
// boundary: a sub session created and bound to role Y answers as Y (the first system
// message is Y's prompt and the persisted messages carry Y), and once the session is
// rebound to "inherit the default" the next turn answers as the default role again.
func TestChatTurnAnswersAsTheBoundRole(t *testing.T) {
t.Parallel()
ctx := context.Background()
st := personaTestStore(t)
reg := personaTestRegistry(t)
sub, err := st.NewSubSessionFor(ctx, "owner", "yuki")
if err != nil {
t.Fatalf("NewSubSessionFor: %v", err)
}
ad := &personaAdapter{}
xilian := gatewayAgentFor(t, "你是昔涟。", ad)
yuki := gatewayAgentFor(t, "你是由纪。", ad)
l := loop.New(loop.Options{
Agent: xilian,
Agents: map[string]*agent.Agent{"xilian": xilian, "yuki": yuki},
PersonaID: "xilian",
})
_, ts, jwt := buildEnv(t, cfgDefault(), Deps{History: st, Personas: reg, Loop: l})
tok := signAny(t, jwt, "acct", auth.RoleOwner)
resp, body := doReq(t, http.MethodPost, ts.URL+"/api/v1/chat", map[string]any{"sessionId": sub, "text": "你好呀"}, tok)
if resp.StatusCode != http.StatusOK {
t.Fatalf("chat status = %d, want 200 (body=%s)", resp.StatusCode, body)
}
if len(ad.reqs) == 0 {
t.Fatal("the model adapter saw no request")
}
if got := firstSystemText(ad.reqs[len(ad.reqs)-1]); got != "你是由纪。" {
t.Fatalf("bound session prompt = %q, want role Y's prompt", got)
}
// The orchestrator files both the user turn and the reply under the turn's role,
// which is what makes the stored transcript readable role-by-role (design/22 §7-5).
msgs, err := st.List(ctx, sub, 0, 10, "")
if err != nil {
t.Fatalf("list messages: %v", err)
}
if len(msgs) != 2 {
t.Fatalf("persisted %d messages, want 2 (user + assistant)", len(msgs))
}
for _, m := range msgs {
if m.PersonaID != "yuki" {
t.Fatalf("%s message persona_id = %q, want yuki", m.Role, m.PersonaID)
}
}
// Unbind the role: the session inherits the global default, so the next turn is
// the default role's again.
resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+sub, map[string]any{"personaId": ""}, tok)
if resp.StatusCode != http.StatusOK {
t.Fatalf("unbind status = %d, want 200 (body=%s)", resp.StatusCode, body)
}
resp, body = doReq(t, http.MethodPost, ts.URL+"/api/v1/chat", map[string]any{"sessionId": sub, "text": "再说一句"}, tok)
if resp.StatusCode != http.StatusOK {
t.Fatalf("second chat status = %d, want 200 (body=%s)", resp.StatusCode, body)
}
if got := firstSystemText(ad.reqs[len(ad.reqs)-1]); got != "你是昔涟。" {
t.Fatalf("unbound session prompt = %q, want the default role's prompt", got)
}
}
// firstSystemText returns the text of the first system message of req.
func firstSystemText(req model.Request) string {
for _, m := range req.Messages {
if m.Role != model.RoleSystem {
continue
}
text := ""
for _, part := range m.Content {
text += part.Text
}
return text
}
return ""
}
// TestSessionPersonaHTTPContract covers the REST contract of design/22 §4.5: create
// with a personaId binds it, the session list reports it, PATCH rebinds and clears
// it, an unknown personaId is rejected (400) instead of binding a role that cannot
// answer, and a PATCH with none of title/pinned/personaId is still a 400.
func TestSessionPersonaHTTPContract(t *testing.T) {
t.Parallel()
st := personaTestStore(t)
reg := personaTestRegistry(t)
_, ts, jwt := buildEnv(t, cfgDefault(), Deps{History: st, Personas: reg})
tok := signAny(t, jwt, "acct", auth.RoleOwner)
resp, body := doReq(t, http.MethodPost, ts.URL+"/api/v1/sessions", map[string]any{"personaId": "yuki"}, tok)
if resp.StatusCode != http.StatusCreated {
t.Fatalf("create status = %d, want 201 (body=%s)", resp.StatusCode, body)
}
var created struct {
SessionID string `json:"sessionId"`
PersonaID string `json:"personaId"`
}
if err := json.Unmarshal(decodeBody(t, body)["data"], &created); err != nil {
t.Fatalf("decode create: %v (body=%s)", err, body)
}
if created.PersonaID != "yuki" {
t.Fatalf("create echoed personaId = %q, want yuki", created.PersonaID)
}
// The session list surfaces the binding (the client renders the active role from it).
var sessions []historySessionSummary
_, body = doReq(t, http.MethodGet, ts.URL+"/api/v1/sessions", nil, tok)
decodeDataSlice(t, body, &sessions)
found := ""
for _, s := range sessions {
if s.ID == created.SessionID {
found = s.PersonaID
}
}
if found != "yuki" {
t.Fatalf("listed persona_id = %q, want yuki (sessions=%+v)", found, sessions)
}
// An unknown role is refused rather than silently ignored.
resp, body = doReq(t, http.MethodPost, ts.URL+"/api/v1/sessions", map[string]any{"personaId": "nobody"}, tok)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("create with unknown personaId status = %d, want 400 (body=%s)", resp.StatusCode, body)
}
resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+created.SessionID, map[string]any{"personaId": "nobody"}, tok)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("patch with unknown personaId status = %d, want 400 (body=%s)", resp.StatusCode, body)
}
// A body with none of the supported fields stays a 400.
resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+created.SessionID, map[string]any{}, tok)
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("empty patch status = %d, want 400 (body=%s)", resp.StatusCode, body)
}
// Rebind to the other role, then clear the binding; both echo only the changed field.
resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+created.SessionID, map[string]any{"personaId": "xilian"}, tok)
if resp.StatusCode != http.StatusOK {
t.Fatalf("rebind status = %d, want 200 (body=%s)", resp.StatusCode, body)
}
if got := personaBindingOf(t, st, created.SessionID); got != "xilian" {
t.Fatalf("after rebind persona_id = %q, want xilian", got)
}
resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+created.SessionID, map[string]any{"personaId": ""}, tok)
if resp.StatusCode != http.StatusOK {
t.Fatalf("unbind status = %d, want 200 (body=%s)", resp.StatusCode, body)
}
if got := personaBindingOf(t, st, created.SessionID); got != "" {
t.Fatalf("after unbind persona_id = %q, want '' (inherit the default)", got)
}
}
// personaBindingOf reads a session's bound role straight from the store, so the test
// asserts the persisted state rather than only the response echo.
func personaBindingOf(t *testing.T, st *history.Store, sessionID string) string {
t.Helper()
personaID, err := st.SessionPersona(context.Background(), sessionID)
if err != nil {
t.Fatalf("SessionPersona(%s): %v", sessionID, err)
}
return personaID
}
// TestTurnEnvResolver covers the resolver itself (design/22 §4.5): the session's
// binding wins, an unknown/unbound session yields "" (so the loop falls back to the
// global default), and the identity/memory fields stay the owner-full ones — the
// role never changes what a turn is allowed to do.
func TestTurnEnvResolver(t *testing.T) {
t.Parallel()
ctx := context.Background()
st := personaTestStore(t)
bound, err := st.NewSubSessionFor(ctx, "owner", "yuki")
if err != nil {
t.Fatalf("NewSubSessionFor: %v", err)
}
r := turnEnvResolver{history: st, personas: personaTestRegistry(t), log: testLogger()}
env := r.owner(ctx, bound)
if env.PersonaID != "yuki" {
t.Fatalf("bound session env persona = %q, want yuki", env.PersonaID)
}
if env.ActorEnv != loop.OwnerEnv().ActorEnv || !env.MemWritable {
t.Fatalf("resolver changed the identity lane: %+v", env)
}
unbound, err := st.NewSubSession(ctx, "owner")
if err != nil {
t.Fatalf("NewSubSession: %v", err)
}
if got := r.owner(ctx, unbound).PersonaID; got != "" {
t.Fatalf("unbound session env persona = %q, want '' (inherit the default)", got)
}
if got := r.owner(ctx, "sess-unknown").PersonaID; got != "" {
t.Fatalf("unknown session env persona = %q, want '' (inherit the default)", got)
}
// A gateway without a history store cannot resolve a binding and must not fail.
bare := turnEnvResolver{log: testLogger()}
if got := bare.owner(ctx, "web").PersonaID; got != "" {
t.Fatalf("no-store env persona = %q, want ''", got)
}
if !bare.owner(ctx, "web").MemWritable {
t.Fatal("no-store env lost the owner memory lane")
}
}
// TestDefaultPersonaIDFromRegistry locks the admin fallback design/22 §4.5 asks for:
// the default role is read from the library's default character instead of a
// hardcoded "cyrene", and an unwired registry reports none.
func TestDefaultPersonaIDFromRegistry(t *testing.T) {
t.Parallel()
srv, _, _ := buildEnv(t, cfgDefault(), Deps{Personas: personaTestRegistry(t)})
if got := srv.defaultPersonaID(); got != "xilian" {
t.Fatalf("defaultPersonaID = %q, want xilian (the default character's persona)", got)
}
bare, _, _ := buildEnv(t, cfgDefault(), Deps{})
if got := bare.defaultPersonaID(); got != "" {
t.Fatalf("defaultPersonaID without a registry = %q, want ''", got)
}
}