package gateway import ( "context" "encoding/json" "net/http" "strings" "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). Its role is fixed at // creation (§8-1), so the PATCH that used to unbind it is refused and the session // keeps answering as Y; the only way to get the default role is a session created // without a binding. 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) } } // Unbinding is refused (design/22 §8-1): a session's role is decided when it is // created, so this PATCH answers 400 and the very next turn still answers as Y. resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+sub, map[string]any{"personaId": ""}, tok) if resp.StatusCode != http.StatusBadRequest { t.Fatalf("unbind status = %d, want 400 (a session's role is immutable; 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("prompt after the refused unbind = %q, want role Y's prompt", got) } // The default role is reached by a session created WITHOUT a binding — the only // way to change role now. unbound, err := st.NewSubSession(ctx, "owner") if err != nil { t.Fatalf("NewSubSession: %v", err) } resp, body = doReq(t, http.MethodPost, ts.URL+"/api/v1/chat", map[string]any{"sessionId": unbound, "text": "你好"}, tok) if resp.StatusCode != http.StatusOK { t.Fatalf("default-role 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 as // amended by §8-1: create with a personaId binds it, the session list reports it, an // unknown personaId on create is rejected (400) instead of binding a role that cannot // answer, a PATCH with neither title nor pinned is a 400, and PATCH REFUSES the // personaId key for every value — a session's role is fixed at creation, so there is // no supported rebind and the refusal can never be mistaken for a silent no-op. 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 on create 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) } // 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) } // PATCH refuses the personaId key for EVERY value (design/22 §8-1): the role is // fixed when the session is created, so a rebind — to another role, to the bound // role, to "", or to null — is not a supported operation. Each refusal must name // personaId (so a client can tell it from "no field given") and must leave the // stored binding exactly as it was. for _, bad := range []any{"xilian", "yuki", "nobody", "", " ", nil} { resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+created.SessionID, map[string]any{"personaId": bad}, tok) if resp.StatusCode != http.StatusBadRequest { t.Fatalf("patch personaId=%#v status = %d, want 400 (body=%s)", bad, resp.StatusCode, body) } if !strings.Contains(string(body), "personaId") { t.Fatalf("patch personaId=%#v body = %s, want it to name personaId", bad, body) } if got := personaBindingOf(t, st, created.SessionID); got != "yuki" { t.Fatalf("patch personaId=%#v moved the binding to %q, want it left at yuki", bad, got) } } // The refusal beats a legal field in the same body: a client cannot smuggle a // rebind alongside a rename, and the rename must not land either. resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+created.SessionID, map[string]any{"title": "偷偷改名", "personaId": "xilian"}, tok) if resp.StatusCode != http.StatusBadRequest { t.Fatalf("rename+personaId status = %d, want 400 (body=%s)", resp.StatusCode, body) } if got := personaBindingOf(t, st, created.SessionID); got != "yuki" { t.Fatalf("rename+personaId moved the binding to %q, want yuki", got) } metas, err := st.ListSessions(context.Background()) if err != nil { t.Fatalf("ListSessions: %v", err) } for _, m := range metas { if m.ID == created.SessionID && m.Title != "" { t.Fatalf("the refused patch applied title %q, want the row untouched", m.Title) } } // The personaId check runs BEFORE the session lookup: an unknown session carrying // the key answers 400 (immutable role), not 404 — while a title-only patch for the // very same unknown id is still the store's 404, which is what proves the 400 above // comes from the persona rule rather than from a missing session. An empty body is // the third corner of the same table: 400 for a missing field, again without ever // looking the session up. resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/web:missing", map[string]any{"personaId": "xilian"}, tok) if resp.StatusCode != http.StatusBadRequest { t.Fatalf("unknown session + personaId status = %d, want 400 (body=%s)", resp.StatusCode, body) } resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/web:missing", map[string]any{}, tok) if resp.StatusCode != http.StatusBadRequest { t.Fatalf("unknown session + empty body status = %d, want 400 (body=%s)", resp.StatusCode, body) } resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/web:missing", map[string]any{"title": "x"}, tok) if resp.StatusCode != http.StatusNotFound { t.Fatalf("unknown session + title status = %d, want 404 (body=%s)", resp.StatusCode, body) } // title/pinned are untouched by the refusal. resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+created.SessionID, map[string]any{"title": "新名字"}, tok) if resp.StatusCode != http.StatusOK { t.Fatalf("title-only patch status = %d, want 200 (body=%s)", resp.StatusCode, body) } if got := personaBindingOf(t, st, created.SessionID); got != "yuki" { t.Fatalf("title-only patch moved the binding to %q, want yuki", 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) } }