feat(history): 消息搜索/编辑/删除 + 会话置顶(D2/D3/D5)
- history/message_ops.go(新): Search(会话内, q/after互斥, LIKE参数化+%/_转义+大小写不敏感, 严格限定会话doc) / UpdateMessage(返回更新后Message) / DeleteMessage / messageByID / escapeLike
- history/session_pin.go(新): SetPinned; 迁移0009 chat_sessions加pinned INTEGER DEFAULT 0; store.go SessionMeta.Pinned + createSessionsTable加列
- session_preview.go: 查询加s.pinned + ORDER BY pinned DESC,(type=main) DESC,created_at ASC
- gateway history_write.go(新,保持history.go≤500): handlePatchSession(pinned+title) / handlePatchMessage / handleDeleteMessage; server.go加PATCH/DELETE /api/v1/messages/{id} + /sessions/{id}置顶
- history.go: handleListMessages读q分流Search; 契约PATCH title/置顶
- D2会话内搜索(不做跨会话,隔离会话不外泄红线); D3不做重发端点(客户端编辑后再发); D5用pinned bool
- 测试(message_ops/history_messages/migrate_pinned), build/vet/test绿+3平台交叉编译; Docs/api-client v0.30
- 未做: 编辑/删除WS实时广播(message_edited/deleted), 下批
This commit is contained in:
1 parent
c7b2cd8ae0
commit
844b2a74c1
15 files changed
+1091
-73
No files matched your search
@@ -279,9 +279,17 @@ func (c *captureHistory) ListAllLog(context.Context, int64, int) ([]history.Mess
|
||||
return nil, nil
|
||||
}
|
||||
func (c *captureHistory) DeleteSession(context.Context, string) error { return nil }
|
||||
func (c *captureHistory) Search(context.Context, string, string, int64, int) ([]history.Message, error) {
|
||||
return nil, nil
|
||||
}
|
||||
func (c *captureHistory) UpdateMessage(_ context.Context, id, content string) (history.Message, error) {
|
||||
return history.Message{ID: id, Content: content}, nil
|
||||
}
|
||||
func (c *captureHistory) DeleteMessage(context.Context, string) error { return nil }
|
||||
func (c *captureHistory) RenameSession(context.Context, string, string) error {
|
||||
return nil
|
||||
}
|
||||
func (c *captureHistory) SetPinned(context.Context, string, bool) error { return nil }
|
||||
func (c *captureHistory) NewSubSession(context.Context, string) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/auth"
|
||||
apperr "git.yeij.top/AskaEth/Cyrene_v2/internal/errors"
|
||||
@@ -20,6 +18,9 @@ type historySessionSummary struct {
|
||||
Type string `json:"type"` // "main" | "sub"
|
||||
Title string `json:"title,omitempty"`
|
||||
CreatedAt int64 `json:"createdAt"`
|
||||
// Pinned floats the session to the top of the list (D5). It is order metadata
|
||||
// only and is always present so a client can render/sort without a second call.
|
||||
Pinned bool `json:"pinned"`
|
||||
// LastMessage is a display-only preview of the session's newest message, so the
|
||||
// client can render a conversation row (e.g. the Android session list) without a
|
||||
// per-session request. It is omitted for a session with no messages. Content is
|
||||
@@ -76,6 +77,7 @@ func (s *Server) handleHistorySessions(w http.ResponseWriter, r *http.Request) {
|
||||
Type: m.Type,
|
||||
Title: m.Title,
|
||||
CreatedAt: m.CreatedAt,
|
||||
Pinned: m.Pinned,
|
||||
LastMessage: toHistoryLastMessage(m.LastMessage),
|
||||
})
|
||||
}
|
||||
@@ -122,8 +124,11 @@ func (s *Server) handleCreateSubSession(w http.ResponseWriter, r *http.Request)
|
||||
// one-page limit of a backward walk.
|
||||
//
|
||||
// limit defaults to 50 (clamped to 200) for both directions. platform filters the page
|
||||
// by source platform in either direction. Supplying both before and after (both > 0)
|
||||
// answers 400, as does a non-numeric/negative after or an invalid limit/before.
|
||||
// by source platform in either direction. An optional q switches the page to a
|
||||
// session-scoped content search (newest first, still honoring before/limit); q is
|
||||
// mutually exclusive with after, and an empty q is ignored so plain paging is
|
||||
// unchanged. Supplying both before and after (both > 0) answers 400, as does a
|
||||
// non-numeric/negative after or an invalid limit/before.
|
||||
func (s *Server) handleListMessages(w http.ResponseWriter, r *http.Request) {
|
||||
if s.history == nil {
|
||||
writeError(w, &apperr.AppError{Code: "not_implemented", Message: "会话历史服务未配置(未注入 HistoryStore)", HTTPCode: http.StatusNotImplemented})
|
||||
@@ -163,12 +168,20 @@ func (s *Server) handleListMessages(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
platform := r.URL.Query().Get("platform")
|
||||
query := strings.TrimSpace(r.URL.Query().Get("q"))
|
||||
if query != "" && after > 0 {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "q and after are mutually exclusive"))
|
||||
return
|
||||
}
|
||||
|
||||
var msgs []history.Message
|
||||
var err error
|
||||
if after > 0 {
|
||||
switch {
|
||||
case query != "":
|
||||
msgs, err = s.history.Search(r.Context(), id, query, before, limit)
|
||||
case after > 0:
|
||||
msgs, err = s.history.ListAfter(r.Context(), id, after, limit, platform)
|
||||
} else {
|
||||
default:
|
||||
msgs, err = s.history.List(r.Context(), id, before, limit, platform)
|
||||
}
|
||||
if err != nil {
|
||||
@@ -322,57 +335,6 @@ func (s *Server) handleDeleteSession(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"deleted": id})
|
||||
}
|
||||
|
||||
// renameSessionRequest is the PATCH /api/v1/sessions/{id} body.
|
||||
type renameSessionRequest struct {
|
||||
Title string `json:"title"`
|
||||
}
|
||||
|
||||
// maxSessionTitleRunes bounds a client-supplied session title so a display row never
|
||||
// overflows. It is a display-only bound: identity and permissions never derive from
|
||||
// the title (project red line).
|
||||
const maxSessionTitleRunes = 80
|
||||
|
||||
// handleRenameSession renames a persistent session (main or sub). The title is
|
||||
// display-only metadata, so unlike DELETE it is allowed on the fixed main session. An
|
||||
// empty/whitespace title or one longer than maxSessionTitleRunes answers 400; an
|
||||
// unknown session id answers 404. It is owner/admin-gated like the other history
|
||||
// writes.
|
||||
func (s *Server) handleRenameSession(w http.ResponseWriter, r *http.Request) {
|
||||
if s.history == nil {
|
||||
writeError(w, &apperr.AppError{Code: "not_implemented", Message: "会话历史服务未配置(未注入 HistoryStore)", HTTPCode: http.StatusNotImplemented})
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "session id is required"))
|
||||
return
|
||||
}
|
||||
var req renameSessionRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "invalid request body"))
|
||||
return
|
||||
}
|
||||
title := strings.TrimSpace(req.Title)
|
||||
if title == "" {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "title is required"))
|
||||
return
|
||||
}
|
||||
if utf8.RuneCountInString(title) > maxSessionTitleRunes {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "title is too long (max 80 characters)"))
|
||||
return
|
||||
}
|
||||
if err := s.history.RenameSession(r.Context(), id, title); err != nil {
|
||||
if errors.Is(err, history.ErrSessionNotFound) {
|
||||
writeError(w, apperr.Wrap(apperr.ErrNotFound, "not_found", "session %q not found", id))
|
||||
return
|
||||
}
|
||||
s.log.Error("history rename session", "err", err, "session", id)
|
||||
writeError(w, apperr.Wrap(apperr.ErrInternal, "session_failed", "failed to rename session"))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"id": id, "title": title})
|
||||
}
|
||||
|
||||
// toHistoryMessage maps a stored history.Message to its wire shape.
|
||||
func toHistoryMessage(m history.Message) historyMessage {
|
||||
return historyMessage{
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
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/runtime/history"
|
||||
)
|
||||
|
||||
// seedFullMessage appends m through the real store and returns the stored message
|
||||
// (with its generated id), so HTTP tests can address a specific message.
|
||||
func seedFullMessage(t *testing.T, st *history.Store, m history.Message) history.Message {
|
||||
t.Helper()
|
||||
got, err := st.AppendFull(context.Background(), m)
|
||||
if err != nil {
|
||||
t.Fatalf("append %q: %v", m.Content, err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
|
||||
// TestHistorySearchMessagesHTTP covers D2: session-scoped ?q= search hits, paging,
|
||||
// the empty-q fallback, input validation and isolation from another session.
|
||||
func TestHistorySearchMessagesHTTP(t *testing.T) {
|
||||
t.Parallel()
|
||||
_, ts, jwt, st := newHistoryEnv(t)
|
||||
ctx := context.Background()
|
||||
for _, m := range []history.Message{
|
||||
{SessionID: history.MainSessionID, Role: history.RoleUser, Content: "今天天气不错", CreatedAt: 1000},
|
||||
{SessionID: history.MainSessionID, Role: history.RoleAssistant, Content: "嗯,适合出门", CreatedAt: 1500},
|
||||
{SessionID: history.MainSessionID, Role: history.RoleUser, Content: "天气要变凉了", CreatedAt: 2000},
|
||||
{SessionID: history.MainSessionID, Role: history.RoleUser, Content: "天气又热了", CreatedAt: 3000},
|
||||
{SessionID: history.MainSessionID, Role: history.RoleUser, Content: "天气终于晴了", CreatedAt: 4000},
|
||||
} {
|
||||
if err := st.Append(ctx, m); err != nil {
|
||||
t.Fatalf("seed %q: %v", m.Content, err)
|
||||
}
|
||||
}
|
||||
// A matching message in another (sub) session must never surface in the main search.
|
||||
sub, err := st.NewSubSession(ctx, "owner")
|
||||
if err != nil {
|
||||
t.Fatalf("new sub: %v", err)
|
||||
}
|
||||
if err := st.Append(ctx, history.Message{SessionID: sub, Role: history.RoleUser, Content: "天气 sub", CreatedAt: 5000}); err != nil {
|
||||
t.Fatalf("seed sub: %v", err)
|
||||
}
|
||||
tok := signAny(t, jwt, "acct", auth.RoleOwner)
|
||||
|
||||
// Newest-first page of 2 matching hits.
|
||||
resp, body := doReq(t, http.MethodGet, ts.URL+"/api/v1/sessions/"+history.MainSessionID+"/messages?q=天气&limit=2", nil, tok)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("search status = %d, want 200 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
var page []historyMessage
|
||||
decodeDataSlice(t, body, &page)
|
||||
if len(page) != 2 || page[0].CreatedAt != 4000 || page[1].CreatedAt != 3000 {
|
||||
t.Fatalf("search page = %+v, want [4000 3000]", page)
|
||||
}
|
||||
if page[0].SessionID != history.MainSessionID {
|
||||
t.Fatalf("search leaked session %q", page[0].SessionID)
|
||||
}
|
||||
|
||||
// before cursor pages to the older hits.
|
||||
resp, body = doReq(t, http.MethodGet, ts.URL+"/api/v1/sessions/"+history.MainSessionID+"/messages?q=天气&before=3000&limit=2", nil, tok)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("search older status = %d, want 200 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
var older []historyMessage
|
||||
decodeDataSlice(t, body, &older)
|
||||
if len(older) != 2 || older[0].CreatedAt != 2000 || older[1].CreatedAt != 1000 {
|
||||
t.Fatalf("search older = %+v, want [2000 1000]", older)
|
||||
}
|
||||
|
||||
// The sub session's search sees only its own hit.
|
||||
resp, body = doReq(t, http.MethodGet, ts.URL+"/api/v1/sessions/"+sub+"/messages?q=天气", nil, tok)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("sub search status = %d, want 200 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
var subHits []historyMessage
|
||||
decodeDataSlice(t, body, &subHits)
|
||||
if len(subHits) != 1 || subHits[0].SessionID != sub {
|
||||
t.Fatalf("sub search = %+v, want only the sub hit", subHits)
|
||||
}
|
||||
|
||||
// An empty q falls back to plain paging (all messages).
|
||||
resp, body = doReq(t, http.MethodGet, ts.URL+"/api/v1/sessions/"+history.MainSessionID+"/messages?q=&limit=10", nil, tok)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("empty q status = %d, want 200 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
var all []historyMessage
|
||||
decodeDataSlice(t, body, &all)
|
||||
if len(all) != 5 {
|
||||
t.Fatalf("empty q = %d messages, want 5", len(all))
|
||||
}
|
||||
|
||||
// q is mutually exclusive with after, and invalid limit still 400.
|
||||
resp, body = doReq(t, http.MethodGet, ts.URL+"/api/v1/sessions/"+history.MainSessionID+"/messages?q=天气&after=1000", nil, tok)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("q+after status = %d, want 400 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
resp, body = doReq(t, http.MethodGet, ts.URL+"/api/v1/sessions/"+history.MainSessionID+"/messages?q=天气&limit=abc", nil, tok)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("bad limit status = %d, want 400 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
}
|
||||
|
||||
// TestHistoryPatchAndDeleteMessageHTTP covers D3: editing and deleting one message,
|
||||
// the input bounds, 404 and RBAC.
|
||||
func TestHistoryPatchAndDeleteMessageHTTP(t *testing.T) {
|
||||
t.Parallel()
|
||||
_, ts, jwt, st := newHistoryEnv(t)
|
||||
msg := seedFullMessage(t, st, history.Message{SessionID: history.MainSessionID, Role: history.RoleUser, Content: "原文", CreatedAt: 1000})
|
||||
tok := signAny(t, jwt, "acct", auth.RoleOwner)
|
||||
base := ts.URL + "/api/v1/messages/" + msg.ID
|
||||
|
||||
// Edit the content; role/timestamp/session are preserved and echoed back.
|
||||
resp, body := doReq(t, http.MethodPatch, base, map[string]any{"content": "改后的正文"}, tok)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("patch status = %d, want 200 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
var updated historyMessage
|
||||
if err := json.Unmarshal(decodeBody(t, body)["data"], &updated); err != nil {
|
||||
t.Fatalf("decode patch data: %v (body=%s)", err, body)
|
||||
}
|
||||
if updated.ID != msg.ID || updated.Content != "改后的正文" || updated.Role != history.RoleUser || updated.CreatedAt != 1000 {
|
||||
t.Fatalf("updated = %+v, want content edited with role/ts preserved", updated)
|
||||
}
|
||||
|
||||
// The edit is persisted.
|
||||
resp, body = doReq(t, http.MethodGet, ts.URL+"/api/v1/sessions/"+history.MainSessionID+"/messages", nil, tok)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("list status = %d, want 200 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
var listed []historyMessage
|
||||
decodeDataSlice(t, body, &listed)
|
||||
if len(listed) != 1 || listed[0].Content != "改后的正文" {
|
||||
t.Fatalf("listed = %+v, want the edited content", listed)
|
||||
}
|
||||
|
||||
// Invalid edits: empty/whitespace, missing field, over-long, unknown id.
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
body any
|
||||
want int
|
||||
}{
|
||||
{"empty", map[string]any{"content": ""}, http.StatusBadRequest},
|
||||
{"blank", map[string]any{"content": " "}, http.StatusBadRequest},
|
||||
{"missing", map[string]any{}, http.StatusBadRequest},
|
||||
{"too-long", map[string]any{"content": strings.Repeat("字", maxMessageContentRunes+1)}, http.StatusBadRequest},
|
||||
} {
|
||||
resp, body = doReq(t, http.MethodPatch, base, tc.body, tok)
|
||||
if resp.StatusCode != tc.want {
|
||||
t.Fatalf("patch %s status = %d, want %d (body=%s)", tc.name, resp.StatusCode, tc.want, body)
|
||||
}
|
||||
wantErrorShape(t, body)
|
||||
}
|
||||
resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/messages/missing", map[string]any{"content": "x"}, tok)
|
||||
if resp.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("patch unknown status = %d, want 404 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
// Delete the message, then deleting again is 404.
|
||||
resp, body = doReq(t, http.MethodDelete, base, nil, tok)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("delete status = %d, want 200 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
var deleted struct {
|
||||
Deleted string `json:"deleted"`
|
||||
}
|
||||
if err := json.Unmarshal(decodeBody(t, body)["data"], &deleted); err != nil {
|
||||
t.Fatalf("decode delete data: %v (body=%s)", err, body)
|
||||
}
|
||||
if deleted.Deleted != msg.ID {
|
||||
t.Fatalf("deleted = %q, want %q", deleted.Deleted, msg.ID)
|
||||
}
|
||||
resp, body = doReq(t, http.MethodDelete, base, nil, tok)
|
||||
if resp.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("delete again status = %d, want 404 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
// A viewer cannot edit or delete (owner/admin write).
|
||||
other := seedFullMessage(t, st, history.Message{SessionID: history.MainSessionID, Role: history.RoleUser, Content: "x", CreatedAt: 2000})
|
||||
viewer := signAny(t, jwt, "acct", auth.RoleViewer)
|
||||
for _, method := range []string{http.MethodPatch, http.MethodDelete} {
|
||||
resp, body = doReq(t, method, ts.URL+"/api/v1/messages/"+other.ID, map[string]any{"content": "nope"}, viewer)
|
||||
if resp.StatusCode != http.StatusForbidden {
|
||||
t.Fatalf("viewer %s status = %d, want 403 (body=%s)", method, resp.StatusCode, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestHistoryMessagesNotWiredHTTP asserts the D2/D3 endpoints answer a clear 501 when
|
||||
// no HistoryStore is injected.
|
||||
func TestHistoryMessagesNotWiredHTTP(t *testing.T) {
|
||||
t.Parallel()
|
||||
_, ts, jwt := buildEnv(t, cfgDefault(), Deps{})
|
||||
tok := signAny(t, jwt, "acct", auth.RoleOwner)
|
||||
for _, tc := range []struct {
|
||||
method, url string
|
||||
}{
|
||||
{http.MethodGet, "/api/v1/sessions/web/messages?q=x"},
|
||||
{http.MethodPatch, "/api/v1/messages/x"},
|
||||
{http.MethodDelete, "/api/v1/messages/x"},
|
||||
} {
|
||||
resp, body := doReq(t, tc.method, ts.URL+tc.url, map[string]any{"content": "x"}, tok)
|
||||
if resp.StatusCode != http.StatusNotImplemented {
|
||||
t.Fatalf("%s %s status = %d, want 501 (body=%s)", tc.method, tc.url, resp.StatusCode, body)
|
||||
}
|
||||
if !strings.Contains(string(body), "not_implemented") {
|
||||
t.Fatalf("%s %s body = %s, want not_implemented", tc.method, tc.url, body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestHistoryPatchSessionPinnedHTTP covers D5: pin/unpin changes GET /sessions order,
|
||||
// the response echoes only the changed field, and the A4 title PATCH still works.
|
||||
func TestHistoryPatchSessionPinnedHTTP(t *testing.T) {
|
||||
t.Parallel()
|
||||
_, ts, jwt, _ := newHistoryEnv(t)
|
||||
tok := signAny(t, jwt, "acct", auth.RoleOwner)
|
||||
|
||||
newSub := func() string {
|
||||
resp, body := doReq(t, http.MethodPost, ts.URL+"/api/v1/sessions", nil, 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"`
|
||||
}
|
||||
if err := json.Unmarshal(decodeBody(t, body)["data"], &created); err != nil {
|
||||
t.Fatalf("decode create: %v (body=%s)", err, body)
|
||||
}
|
||||
return created.SessionID
|
||||
}
|
||||
first, second := newSub(), newSub()
|
||||
|
||||
sessionOrder := func() []string {
|
||||
resp, body := doReq(t, http.MethodGet, ts.URL+"/api/v1/sessions", nil, tok)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("list status = %d, want 200 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
var sessions []historySessionSummary
|
||||
decodeDataSlice(t, body, &sessions)
|
||||
ids := make([]string, 0, len(sessions))
|
||||
for _, s := range sessions {
|
||||
ids = append(ids, s.ID)
|
||||
}
|
||||
return ids
|
||||
}
|
||||
assertOrder := func(want []string) {
|
||||
t.Helper()
|
||||
got := sessionOrder()
|
||||
if len(got) != len(want) {
|
||||
t.Fatalf("order = %v, want %v", got, want)
|
||||
}
|
||||
for i := range want {
|
||||
if got[i] != want[i] {
|
||||
t.Fatalf("order = %v, want %v", got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assertOrder([]string{history.MainSessionID, first, second})
|
||||
|
||||
// Pin the newest sub: it floats above the main session, and the response echoes
|
||||
// only the pinned field.
|
||||
resp, body := doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+second, map[string]any{"pinned": true}, tok)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("pin status = %d, want 200 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
var pinned struct {
|
||||
ID string `json:"id"`
|
||||
Pinned *bool `json:"pinned"`
|
||||
Title string `json:"title"`
|
||||
}
|
||||
if err := json.Unmarshal(decodeBody(t, body)["data"], &pinned); err != nil {
|
||||
t.Fatalf("decode pin: %v (body=%s)", err, body)
|
||||
}
|
||||
if pinned.ID != second || pinned.Pinned == nil || !*pinned.Pinned || pinned.Title != "" {
|
||||
t.Fatalf("pin data = %+v, want id+pinned:true only", pinned)
|
||||
}
|
||||
assertOrder([]string{second, history.MainSessionID, first})
|
||||
|
||||
// GET /sessions reports the pin flag.
|
||||
resp, body = doReq(t, http.MethodGet, ts.URL+"/api/v1/sessions", nil, tok)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("list status = %d, want 200 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
var sessions []historySessionSummary
|
||||
decodeDataSlice(t, body, &sessions)
|
||||
if !sessions[0].Pinned || sessions[0].ID != second {
|
||||
t.Fatalf("sessions[0] = %+v, want pinned sub %s", sessions[0], second)
|
||||
}
|
||||
|
||||
// A title PATCH still works and keeps its {id,title} response shape.
|
||||
resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+second, map[string]any{"title": " 置顶会话 "}, tok)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("title patch status = %d, want 200 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
var renamed struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
}
|
||||
if err := json.Unmarshal(decodeBody(t, body)["data"], &renamed); err != nil {
|
||||
t.Fatalf("decode title patch: %v (body=%s)", err, body)
|
||||
}
|
||||
if renamed.ID != second || renamed.Title != "置顶会话" {
|
||||
t.Fatalf("title patch = %+v, want 置顶会话", renamed)
|
||||
}
|
||||
|
||||
// Unpin restores the baseline order.
|
||||
resp, _ = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+second, map[string]any{"pinned": false}, tok)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("unpin status = %d, want 200", resp.StatusCode)
|
||||
}
|
||||
assertOrder([]string{history.MainSessionID, first, second})
|
||||
|
||||
// Neither field → 400; unknown id → 404; viewer → 403.
|
||||
resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+second, map[string]any{}, tok)
|
||||
if resp.StatusCode != http.StatusBadRequest {
|
||||
t.Fatalf("empty patch 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{"pinned": true}, tok)
|
||||
if resp.StatusCode != http.StatusNotFound {
|
||||
t.Fatalf("unknown pin status = %d, want 404 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
viewer := signAny(t, jwt, "acct", auth.RoleViewer)
|
||||
resp, body = doReq(t, http.MethodPatch, ts.URL+"/api/v1/sessions/"+second, map[string]any{"pinned": true}, viewer)
|
||||
if resp.StatusCode != http.StatusForbidden {
|
||||
t.Fatalf("viewer pin status = %d, want 403 (body=%s)", resp.StatusCode, body)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
apperr "git.yeij.top/AskaEth/Cyrene_v2/internal/errors"
|
||||
"git.yeij.top/AskaEth/Cyrene_v2/internal/runtime/history"
|
||||
)
|
||||
|
||||
// This file owns the session/message write endpoints added for the Android
|
||||
// collaboration batch ③a: PATCH /sessions/{id} (A4 rename + D5 pin), PATCH
|
||||
// /messages/{id} (D3 edit) and DELETE /messages/{id} (D3 delete). All are owner/admin
|
||||
// history writes; the reads and DTOs live in history.go.
|
||||
|
||||
// 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), and at least one must be present.
|
||||
type patchSessionRequest struct {
|
||||
Title *string `json:"title"`
|
||||
Pinned *bool `json:"pinned"`
|
||||
}
|
||||
|
||||
// maxSessionTitleRunes bounds a client-supplied session title so a display row never
|
||||
// overflows. It is a display-only bound: identity and permissions never derive from
|
||||
// the title (project red line).
|
||||
const maxSessionTitleRunes = 80
|
||||
|
||||
// handlePatchSession updates a persistent session's display metadata: its title (A4)
|
||||
// and/or its pinned flag (D5). Both are display/order-only, so 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; an unknown session id answers 404. 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 {
|
||||
writeError(w, &apperr.AppError{Code: "not_implemented", Message: "会话历史服务未配置(未注入 HistoryStore)", HTTPCode: http.StatusNotImplemented})
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "session id is required"))
|
||||
return
|
||||
}
|
||||
var req patchSessionRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "invalid request body"))
|
||||
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}
|
||||
if req.Title != nil {
|
||||
title := strings.TrimSpace(*req.Title)
|
||||
if title == "" {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "title is required"))
|
||||
return
|
||||
}
|
||||
if utf8.RuneCountInString(title) > maxSessionTitleRunes {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "title is too long (max 80 characters)"))
|
||||
return
|
||||
}
|
||||
if err := s.history.RenameSession(r.Context(), id, title); err != nil {
|
||||
s.writeSessionPatchError(w, err, id, "rename session")
|
||||
return
|
||||
}
|
||||
resp["title"] = title
|
||||
}
|
||||
if req.Pinned != nil {
|
||||
if err := s.history.SetPinned(r.Context(), id, *req.Pinned); err != nil {
|
||||
s.writeSessionPatchError(w, err, id, "pin session")
|
||||
return
|
||||
}
|
||||
resp["pinned"] = *req.Pinned
|
||||
}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
s.log.Error(op, "err", err, "session", id)
|
||||
writeError(w, apperr.Wrap(apperr.ErrInternal, "session_failed", "failed to update session"))
|
||||
}
|
||||
|
||||
// patchMessageRequest is the PATCH /api/v1/messages/{id} body. Content is a pointer so
|
||||
// an absent field is rejected rather than treated as an empty edit.
|
||||
type patchMessageRequest struct {
|
||||
Content *string `json:"content"`
|
||||
}
|
||||
|
||||
// maxMessageContentRunes bounds an edited message body. It is a storage/display bound
|
||||
// on the edit path only; inbound chat messages are not subject to it.
|
||||
const maxMessageContentRunes = 4000
|
||||
|
||||
// handlePatchMessage edits a single message's content (Android collaboration batch ③a,
|
||||
// D3). Only content changes — role/timestamp/platform stay as stored — and the response
|
||||
// returns the updated message so the client can upsert it by id without a re-read. An
|
||||
// empty/whitespace or over-long content answers 400, an unknown id answers 404, and a
|
||||
// missing HistoryStore answers 501. It is owner/admin-gated.
|
||||
func (s *Server) handlePatchMessage(w http.ResponseWriter, r *http.Request) {
|
||||
if s.history == nil {
|
||||
writeError(w, &apperr.AppError{Code: "not_implemented", Message: "会话历史服务未配置(未注入 HistoryStore)", HTTPCode: http.StatusNotImplemented})
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "message id is required"))
|
||||
return
|
||||
}
|
||||
var req patchMessageRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "invalid request body"))
|
||||
return
|
||||
}
|
||||
if req.Content == nil {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "content is required"))
|
||||
return
|
||||
}
|
||||
content := *req.Content
|
||||
if strings.TrimSpace(content) == "" {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "content is required"))
|
||||
return
|
||||
}
|
||||
if utf8.RuneCountInString(content) > maxMessageContentRunes {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "content is too long (max 4000 characters)"))
|
||||
return
|
||||
}
|
||||
msg, err := s.history.UpdateMessage(r.Context(), id, content)
|
||||
if err != nil {
|
||||
if errors.Is(err, history.ErrMessageNotFound) {
|
||||
writeError(w, apperr.Wrap(apperr.ErrNotFound, "not_found", "message %q not found", id))
|
||||
return
|
||||
}
|
||||
s.log.Error("history update message", "err", err, "message", id)
|
||||
writeError(w, apperr.Wrap(apperr.ErrInternal, "message_failed", "failed to update message"))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, toHistoryMessage(msg))
|
||||
}
|
||||
|
||||
// handleDeleteMessage removes a single message (D3). An unknown id answers 404, a
|
||||
// missing HistoryStore 501. It is owner/admin-gated.
|
||||
func (s *Server) handleDeleteMessage(w http.ResponseWriter, r *http.Request) {
|
||||
if s.history == nil {
|
||||
writeError(w, &apperr.AppError{Code: "not_implemented", Message: "会话历史服务未配置(未注入 HistoryStore)", HTTPCode: http.StatusNotImplemented})
|
||||
return
|
||||
}
|
||||
id := r.PathValue("id")
|
||||
if id == "" {
|
||||
writeError(w, apperr.Wrap(apperr.ErrBadRequest, "bad_request", "message id is required"))
|
||||
return
|
||||
}
|
||||
if err := s.history.DeleteMessage(r.Context(), id); err != nil {
|
||||
if errors.Is(err, history.ErrMessageNotFound) {
|
||||
writeError(w, apperr.Wrap(apperr.ErrNotFound, "not_found", "message %q not found", id))
|
||||
return
|
||||
}
|
||||
s.log.Error("history delete message", "err", err, "message", id)
|
||||
writeError(w, apperr.Wrap(apperr.ErrInternal, "message_failed", "failed to delete message"))
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{"deleted": id})
|
||||
}
|
||||
@@ -124,9 +124,21 @@ type HistoryStore interface {
|
||||
ListAdapterLog(ctx context.Context, adapterID string, before int64, limit int) ([]history.Message, error)
|
||||
ListAllLog(ctx context.Context, before int64, limit int) ([]history.Message, error)
|
||||
DeleteSession(ctx context.Context, sessionID string) error
|
||||
// Search returns session-scoped content matches (newest first) for the
|
||||
// ?q= message-search path. An empty query yields an empty slice.
|
||||
Search(ctx context.Context, sessionID, query string, before int64, limit int) ([]history.Message, error)
|
||||
// UpdateMessage edits a single message's content and returns the updated
|
||||
// message. An unknown id returns history.ErrMessageNotFound.
|
||||
UpdateMessage(ctx context.Context, id, content string) (history.Message, error)
|
||||
// DeleteMessage removes a single message. An unknown id returns
|
||||
// history.ErrMessageNotFound.
|
||||
DeleteMessage(ctx context.Context, id string) error
|
||||
// RenameSession sets a session's display title (main or sub). An unknown id
|
||||
// returns history.ErrSessionNotFound.
|
||||
RenameSession(ctx context.Context, sessionID, title string) error
|
||||
// SetPinned pins/unpins a session (main or sub). An unknown id returns
|
||||
// history.ErrSessionNotFound.
|
||||
SetPinned(ctx context.Context, sessionID string, pinned bool) error
|
||||
NewSubSession(ctx context.Context, ownerID string) (string, error)
|
||||
ListSessions(ctx context.Context) ([]history.SessionMeta, error)
|
||||
}
|
||||
@@ -471,7 +483,11 @@ func (s *Server) Handler() http.Handler {
|
||||
mux.Handle("GET /api/v1/sessions/{id}/messages", historyAuth(http.HandlerFunc(s.handleListMessages)))
|
||||
mux.Handle("POST /api/v1/sessions", historyAuth(http.HandlerFunc(s.handleCreateSubSession)))
|
||||
mux.Handle("DELETE /api/v1/sessions/{id}", historyAuth(http.HandlerFunc(s.handleDeleteSession)))
|
||||
mux.Handle("PATCH /api/v1/sessions/{id}", historyAuth(http.HandlerFunc(s.handleRenameSession)))
|
||||
mux.Handle("PATCH /api/v1/sessions/{id}", historyAuth(http.HandlerFunc(s.handlePatchSession)))
|
||||
// Single-message edit/delete (Android collaboration batch ③a, D3). A message is
|
||||
// addressed by its own opaque id; both are owner/admin-gated history writes.
|
||||
mux.Handle("PATCH /api/v1/messages/{id}", historyAuth(http.HandlerFunc(s.handlePatchMessage)))
|
||||
mux.Handle("DELETE /api/v1/messages/{id}", historyAuth(http.HandlerFunc(s.handleDeleteMessage)))
|
||||
|
||||
// Realtime.
|
||||
mux.HandleFunc("/ws/chat", s.handleWS)
|
||||
|
||||
@@ -203,10 +203,26 @@ func (f *fakeHistory) DeleteSession(context.Context, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeHistory) Search(context.Context, string, string, int64, int) ([]history.Message, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *fakeHistory) UpdateMessage(_ context.Context, id, content string) (history.Message, error) {
|
||||
return history.Message{ID: id, Content: content}, nil
|
||||
}
|
||||
|
||||
func (f *fakeHistory) DeleteMessage(context.Context, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeHistory) RenameSession(context.Context, string, string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeHistory) SetPinned(context.Context, string, bool) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeHistory) NewSubSession(context.Context, string) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user