feat(session,web): 会话角色不可变 — PATCH 拒 personaId + 移除前端换角色入口
CI / Backend (build / vet / test / cross-compile) (push) Has been cancelled
CI / Frontend (tsc + vite build) (push) Has been cancelled

design/22 §8-1(主人 2026-10-03 拍板):会话角色在创建时确定、之后不可变,
要换角色必须新开会话。

后端:
- PATCH /api/v1/sessions/{id} 的 personaId 改为 json.RawMessage 判「键出现」,
  出现即 400(null/""/未知 id 一律拒),且先于会话存在性检查;错误消息点名 personaId
- 删除 Server.setSessionPersona 与 PATCH 的 501 分支;title/pinned 行为逐字不变
- sessionPersonaWriter 接口与 history.Store.SetSessionPersona 保留(存储能力)

前端:
- 移除会话行「切换角色」入口与面板「挂角色」下拉(含 setSessionPersona action、
  lib/sessionPersona.ts);保留「新建会话选角色」;面板「角色」列改为只读展示

契约:Docs/api-client.md -> v0.46(破坏性:依赖 PATCH 换角色的客户端须改为新建会话)

验证:go build/vet ./... 绿;gateway+history 包测试绿(-count=1);前端 npm run build
(tsc --noEmit + vite build)绿;9 个前端逻辑测试全绿。
变异验证:改回「静默忽略」/「写绑定」两种反向实现,新断言均 FAIL。
This commit is contained in:
AskaEth committed 2026-10-03 21:24:51 +08:00
1 parent f9430dee81
commit c7ecc3a249
10 files changed
+193 -448

No files matched your search

@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"net/http"
"strings"
"testing"
"git.yeij.top/AskaEth/Cyrene_v2/internal/auth"
@@ -91,8 +92,10 @@ func gatewayAgentFor(t *testing.T, instructions string, ad model.Adapter) *agent
// 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.
// 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()
@@ -140,16 +143,30 @@ func TestChatTurnAnswersAsTheBoundRole(t *testing.T) {
}
}
// Unbind the role: the session inherits the global default, so the next turn is
// the default role's again.
// 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.StatusOK {
t.Fatalf("unbind status = %d, want 200 (body=%s)", resp.StatusCode, body)
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)
}
@@ -170,10 +187,12 @@ func firstSystemText(req model.Request) string {
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.
// 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)
@@ -210,15 +229,11 @@ func TestSessionPersonaHTTPContract(t *testing.T) {
t.Fatalf("listed persona_id = %q, want yuki (sessions=%+v)", found, sessions)
}
// An unknown role is refused rather than silently ignored.
// 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)
}
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)
@@ -226,20 +241,69 @@ func TestSessionPersonaHTTPContract(t *testing.T) {
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)
// 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("rebind status = %d, want 200 (body=%s)", resp.StatusCode, body)
t.Fatalf("title-only patch 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)
if got := personaBindingOf(t, st, created.SessionID); got != "yuki" {
t.Fatalf("title-only patch moved the binding to %q, want yuki", got)
}
}
+32 -46
View File
@@ -19,15 +19,20 @@ import (
// broadcast their outcome over the WS hub (message_edited / message_deleted, see
// ws_hub.go) so the account's other browsers stay in sync without a manual re-read.
// patchSessionRequest is the PATCH /api/v1/sessions/{id} body. All fields are
// patchSessionRequest is the PATCH /api/v1/sessions/{id} body. Both fields are
// pointers so an absent field is distinguishable from an explicit zero value:
// title renames the session (A4), pinned sets/unets the pin (D5), personaId
// rebinds the session's role (design/22 §4.5, an explicit "" clears the binding
// back to "inherit the global default"), and at least one must be present.
// title renames the session (A4), pinned sets/unets the pin (D5), and at least one
// must be present.
//
// personaId is deliberately NOT a settable field: a session's role is fixed when the
// session is created (design/22 §8-1), so the key is rejected outright instead of
// being ignored. It stays in the struct as the raw JSON so the handler can tell
// "the key is absent" from "the key is present with any value" — `"yuki"`, `""` and
// `null` are all refused, and only a body without the key is accepted.
type patchSessionRequest struct {
Title *string `json:"title"`
Pinned *bool `json:"pinned"`
PersonaID *string `json:"personaId"`
Title *string `json:"title"`
Pinned *bool `json:"pinned"`
PersonaID json.RawMessage `json:"personaId"`
}
// maxSessionTitleRunes bounds a client-supplied session title so a display row never
@@ -36,14 +41,17 @@ type patchSessionRequest struct {
const maxSessionTitleRunes = 80
// handlePatchSession updates a persistent session's display metadata — its title
// (A4), its pinned flag (D5) — and/or its role binding (design/22 §4.5). All three
// are metadata: unlike DELETE they are allowed on the fixed main session. A request
// carrying none of the fields answers 400, as do an empty/whitespace or over-long
// title and an unknown personaId; an unknown session id answers 404. Rebinding a
// role does not touch the stored conversation — the messages keep the role that
// spoke them (design/22 §7-5) — it only changes which role answers from the next
// turn on. It is owner/admin-gated like the other history writes. The response
// echoes only the fields that were changed, so a title-only PATCH keeps its pre-D5
// (A4) and its pinned flag (D5). Both are metadata: unlike DELETE they are allowed
// on the fixed main session. A request carrying neither field answers 400, as do an
// empty/whitespace or over-long title and an unknown session id (404/500 as usual).
//
// A body carrying the personaId key answers 400 for EVERY value, and that check runs
// before the session is looked up: a session's role is fixed at creation (design/22
// §8-1), so switching the role of an existing conversation — including clearing it —
// is not a supported operation; create a new session instead. Refusing explicitly
// (rather than ignoring the key) is what keeps a client from believing a rebind
// landed. It is owner/admin-gated like the other history writes. The response echoes
// only the fields that were changed, so a title-only PATCH keeps its pre-D5
// {id,title} shape.
func (s *Server) handlePatchSession(w http.ResponseWriter, r *http.Request) {
if s.history == nil {
@@ -60,8 +68,13 @@ func (s *Server) handlePatchSession(w http.ResponseWriter, r *http.Request) {
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "invalid request body"))
return
}
if req.Title == nil && req.Pinned == nil && req.PersonaID == nil {
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "title, pinned or personaId is required"))
if req.PersonaID != nil {
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request",
"personaId cannot be changed: 会话角色在创建时确定,之后不可变,要换角色请新开会话 (design/22 §8-1)"))
return
}
if req.Title == nil && req.Pinned == nil {
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "title or pinned is required"))
return
}
resp := map[string]any{"id": id}
@@ -88,43 +101,16 @@ func (s *Server) handlePatchSession(w http.ResponseWriter, r *http.Request) {
}
resp["pinned"] = *req.Pinned
}
if req.PersonaID != nil {
personaID := strings.TrimSpace(*req.PersonaID)
if !s.requireKnownPersona(w, personaID) {
return
}
if err := s.setSessionPersona(r.Context(), id, personaID); err != nil {
s.writeSessionPatchError(w, err, id, "set session persona")
return
}
resp["personaId"] = personaID
}
writeJSON(w, http.StatusOK, resp)
}
// setSessionPersona rebinds a session's role through the store's optional
// role-writer. A store without it answers 501 rather than reporting a binding that
// was never written.
func (s *Server) setSessionPersona(ctx context.Context, sessionID, personaID string) error {
writer, ok := s.history.(sessionPersonaWriter)
if !ok {
return errPersonaBindingUnsupported
}
return writer.SetSessionPersona(ctx, sessionID, personaID)
}
// writeSessionPatchError maps a RenameSession/SetPinned/SetSessionPersona failure to
// its response: ErrSessionNotFound → 404, a store that cannot bind roles → 501,
// anything else → 500 (logged under op).
// writeSessionPatchError maps a RenameSession/SetPinned failure to its response:
// ErrSessionNotFound → 404, anything else → 500 (logged under op).
func (s *Server) writeSessionPatchError(w http.ResponseWriter, err error, id, op string) {
if errors.Is(err, history.ErrSessionNotFound) {
writeError(w, apperr.Wrap(apperr.ErrNotFound, "not_found", "session %q not found", id))
return
}
if errors.Is(err, errPersonaBindingUnsupported) {
writeError(w, &apperr.AppError{Code: "not_implemented", Message: "会话角色绑定需要支持 personaId 的 HistoryStore", HTTPCode: http.StatusNotImplemented})
return
}
s.log.Error(op, "err", err, "session", id)
writeError(w, apperr.Wrap(apperr.ErrInternal, "session_failed", "failed to update session"))
}
+7 -4
View File
@@ -43,10 +43,13 @@ type sessionPersonaReader interface {
SessionPersona(ctx context.Context, sessionID string) (string, error)
}
// sessionPersonaWriter is the optional narrower view of HistoryStore used to rebind
// a session's role (PATCH /sessions/{id}, design/22 §4.5). *history.Store
// implements it; a store without it answers 501 on a persona write rather than
// pretending the binding landed.
// sessionPersonaWriter is the optional narrower view of HistoryStore for writing a
// session's role binding. A session's role is decided at creation (design/22 §8-1),
// so no request path rebinds one any more — creation goes through subSessionCreator —
// and the gateway no longer type-asserts this interface. It stays next to the reader
// and the creator so the store's role-binding surface is documented in one place:
// *history.Store still implements SetSessionPersona (design/22 §4.1) and the
// admin/owner write path that would use it is a separate endpoint, not a PATCH.
type sessionPersonaWriter interface {
SetSessionPersona(ctx context.Context, sessionID, personaID string) error
}