Files
Cyrene_v2/internal/runtime/history/message_ops.go
T
AskaEth 2720d77331
CI / Backend (build / vet / test / cross-compile) (push) Has been cancelled
CI / Frontend (tsc + vite build) (push) Has been cancelled
feat(gateway+web): D 消息编辑/删除 WS 实时广播 — message_edited/message_deleted
- 后端: ws_hub.go broadcastMessageEdited(完整DTO,thinking剥离)/broadcastMessageDeleted(全广播+sessionId,前端过滤); history_write.go PATCH/DELETE成功后触发(404/400/501不广播); history/message_ops.go GetMessage(导出壳,取删除前sessionId)
- 前端: useAppStore.updateMessageById/removeMessageById + messageEventApplies(同会话过滤); ws.ts 消费两事件(缺content丢弃); dispatchFrame导出(可测)
- 真机e2e: PATCH/DELETE → WS收到 message_edited/message_deleted, 二次删404无帧
- Docs/api-client v0.34 §3.8; 测试 history_write_broadcast_test + messageSync.test(14 checks)
- 遗留: 前端编辑/删除UI入口+api客户端函数未接(lib/api 无 PATCH/DELETE messages); ws_hub.go 589行>500(既有)
2026-09-30 11:58:49 +08:00

123 lines
4.9 KiB
Go

package history
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
)
// This file owns the single-message operations behind the Android collaboration batch
// ③a (D2 search, D3 edit/delete) plus the id-scoped read the D delete broadcast needs.
// All are strictly session-scoped or id-scoped: a message is only ever reached through
// the session it belongs to (Search) or its own opaque id (GetMessage/UpdateMessage/
// DeleteMessage), so an isolated group/stranger session can never surface in another
// session's results (project red line).
// Search returns up to limit messages for sessionID whose content contains query,
// newest first. The match is a case-insensitive ASCII LIKE (SQLite's default for
// LIKE) with the query's %/_/\ escaped so they match literally; before is the same
// millisecond cursor as List (strictly older than before) and limit is clamped to
// [1, maxPageLimit]. rowid breaks created_at ties so same-millisecond messages keep a
// stable order. An empty query returns an empty (non-nil) slice — the caller uses
// List for plain paging instead. Search never crosses the session boundary.
func (s *Store) Search(ctx context.Context, sessionID, query string, before int64, limit int) ([]Message, error) {
limit = clampLimit(limit)
if query == "" {
return make([]Message, 0), nil
}
sqlText := `SELECT id, session_id, role, content, mode, mood, image, thinking, platform, device_id, sender_name, adapter_id, created_at
FROM chat_messages WHERE session_id = ? AND content LIKE ? ESCAPE '\'`
args := []any{sessionID, "%" + escapeLike(query) + "%"}
if before > 0 {
sqlText += ` AND created_at < ?`
args = append(args, before)
}
sqlText += ` ORDER BY created_at DESC, rowid DESC LIMIT ?`
args = append(args, limit)
rows, err := s.db.QueryContext(ctx, sqlText, args...)
if err != nil {
return nil, fmt.Errorf("history: search %s: %w", sessionID, err)
}
defer func() { _ = rows.Close() }()
msgs := make([]Message, 0)
for rows.Next() {
m, err := scanMessage(rows)
if err != nil {
return nil, fmt.Errorf("history: scan search %s: %w", sessionID, err)
}
msgs = append(msgs, m)
}
if err := rows.Err(); err != nil {
return nil, fmt.Errorf("history: iterate search %s: %w", sessionID, err)
}
return msgs, nil
}
// UpdateMessage replaces the content of the message with id and returns the updated
// message (like AppendFull, so the caller can return/broadcast it without a second
// read). Only content changes; role, platform, timestamps and the rest stay as stored.
// An unknown id returns ErrMessageNotFound.
func (s *Store) UpdateMessage(ctx context.Context, id, content string) (Message, error) {
res, err := s.db.ExecContext(ctx, `UPDATE chat_messages SET content = ? WHERE id = ?`, content, id)
if err != nil {
return Message{}, fmt.Errorf("history: update message %s: %w", id, err)
}
n, err := res.RowsAffected()
if err != nil {
return Message{}, fmt.Errorf("history: update message %s rows: %w", id, err)
}
if n == 0 {
return Message{}, fmt.Errorf("history: update message %s: %w", id, ErrMessageNotFound)
}
return s.messageByID(ctx, id)
}
// DeleteMessage removes a single message. An unknown id returns ErrMessageNotFound.
func (s *Store) DeleteMessage(ctx context.Context, id string) error {
res, err := s.db.ExecContext(ctx, `DELETE FROM chat_messages WHERE id = ?`, id)
if err != nil {
return fmt.Errorf("history: delete message %s: %w", id, err)
}
n, err := res.RowsAffected()
if err != nil {
return fmt.Errorf("history: delete message %s rows: %w", id, err)
}
if n == 0 {
return fmt.Errorf("history: delete message %s: %w", id, ErrMessageNotFound)
}
return nil
}
// GetMessage reads the message with id, returning ErrMessageNotFound when no such
// row exists. It is the id-scoped read the transport uses before removing a
// message: DeleteMessage leaves nothing to ask afterwards, yet the broadcast that
// tells other clients to drop the row is session-scoped.
func (s *Store) GetMessage(ctx context.Context, id string) (Message, error) {
return s.messageByID(ctx, id)
}
// messageByID reads one message by id, returning ErrMessageNotFound when the row is
// absent.
func (s *Store) messageByID(ctx context.Context, id string) (Message, error) {
row := s.db.QueryRowContext(ctx, `SELECT id, session_id, role, content, mode, mood, image, thinking, platform, device_id, sender_name, adapter_id, created_at
FROM chat_messages WHERE id = ?`, id)
m, err := scanMessage(row)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
return Message{}, fmt.Errorf("history: read message %s: %w", id, ErrMessageNotFound)
}
return Message{}, fmt.Errorf("history: read message %s: %w", id, err)
}
return m, nil
}
// escapeLike escapes the LIKE wildcards in a user query so %, _ and \ match literally
// (the caller pairs it with ESCAPE '\'). It is applied before the %...% wrapping.
func escapeLike(query string) string {
return strings.NewReplacer(`\`, `\\`, `%`, `\%`, `_`, `\_`).Replace(query)
}