package store import ( "context" "database/sql" "errors" "fmt" "time" ) // AISession is one chat conversation owned by a panel user. type AISession struct { ID string `json:"id"` UserID int64 `json:"-"` Title string `json:"title"` CreatedAt int64 `json:"created_at"` UpdatedAt int64 `json:"updated_at"` MessageCount int `json:"message_count"` } // AIMessage is one message in a conversation. Assistant messages may carry the // raw OpenAI tool_calls JSON; tool results are stored as separate rows so the // history can be replayed verbatim to the provider. type AIMessage struct { ID int64 `json:"id"` SessionID string `json:"session_id"` Role string `json:"role"` Content string `json:"content"` ToolCalls string `json:"tool_calls,omitempty"` ToolCallID string `json:"tool_call_id,omitempty"` Name string `json:"name,omitempty"` Status string `json:"status"` CreatedAt int64 `json:"created_at"` } // AIAction is a mutating tool call waiting for (or carrying) user approval. type AIAction struct { ID string `json:"id"` SessionID string `json:"session_id"` MessageID int64 `json:"message_id"` ToolCallID string `json:"tool_call_id"` ToolName string `json:"tool_name"` Arguments string `json:"arguments"` Summary string `json:"summary"` Risk string `json:"risk"` Status string `json:"status"` Result string `json:"result"` UserID int64 `json:"-"` CreatedAt int64 `json:"created_at"` ExpiresAt int64 `json:"expires_at"` DecidedAt int64 `json:"decided_at"` ExecutedAt int64 `json:"executed_at"` } const aiSessionColumns = `id, user_id, title, created_at, updated_at, message_count` const aiMessageColumns = `id, session_id, role, content, tool_calls, tool_call_id, name, status, created_at` const aiActionColumns = `id, session_id, message_id, tool_call_id, tool_name, arguments, summary, risk, status, result, user_id, created_at, expires_at, decided_at, executed_at` // CreateAISession inserts a conversation. func (s *Store) CreateAISession(ctx context.Context, sess *AISession) error { now := time.Now().Unix() if sess.CreatedAt == 0 { sess.CreatedAt = now } if sess.UpdatedAt == 0 { sess.UpdatedAt = now } _, err := s.db.ExecContext(ctx, `INSERT INTO ai_sessions(id, user_id, title, created_at, updated_at, message_count) VALUES(?,?,?,?,?,?)`, sess.ID, sess.UserID, sess.Title, sess.CreatedAt, sess.UpdatedAt, sess.MessageCount) return err } func scanAISession(row interface{ Scan(...any) error }) (*AISession, error) { var v AISession err := row.Scan(&v.ID, &v.UserID, &v.Title, &v.CreatedAt, &v.UpdatedAt, &v.MessageCount) if errors.Is(err, sql.ErrNoRows) { return nil, ErrNotFound } if err != nil { return nil, err } return &v, nil } // ListAISessions returns the newest conversations of one user. func (s *Store) ListAISessions(ctx context.Context, userID int64, limit int) ([]*AISession, error) { if limit <= 0 || limit > 100 { limit = 50 } rows, err := s.db.QueryContext(ctx, `SELECT `+aiSessionColumns+` FROM ai_sessions WHERE user_id = ? ORDER BY updated_at DESC, created_at DESC LIMIT ?`, userID, limit) if err != nil { return nil, err } defer rows.Close() out := make([]*AISession, 0, limit) for rows.Next() { v, err := scanAISession(rows) if err != nil { return nil, err } out = append(out, v) } return out, rows.Err() } // AISessionByID loads one conversation owned by userID. func (s *Store) AISessionByID(ctx context.Context, id string, userID int64) (*AISession, error) { row := s.db.QueryRowContext(ctx, `SELECT `+aiSessionColumns+` FROM ai_sessions WHERE id = ? AND user_id = ?`, id, userID) return scanAISession(row) } // RenameAISession updates the sidebar title. func (s *Store) RenameAISession(ctx context.Context, id string, userID int64, title string) error { res, err := s.db.ExecContext(ctx, `UPDATE ai_sessions SET title = ?, updated_at = ? WHERE id = ? AND user_id = ?`, title, time.Now().Unix(), id, userID) if err != nil { return err } if n, _ := res.RowsAffected(); n == 0 { return ErrNotFound } return nil } // DeleteAISession removes a conversation; messages and actions cascade. func (s *Store) DeleteAISession(ctx context.Context, id string, userID int64) error { res, err := s.db.ExecContext(ctx, `DELETE FROM ai_sessions WHERE id = ? AND user_id = ?`, id, userID) if err != nil { return err } if n, _ := res.RowsAffected(); n == 0 { return ErrNotFound } return nil } // AppendAIMessage stores one message and bumps the conversation counters. func (s *Store) AppendAIMessage(ctx context.Context, m *AIMessage) (int64, error) { now := time.Now().Unix() if m.CreatedAt == 0 { m.CreatedAt = now } if m.Status == "" { m.Status = "ok" } tx, err := s.db.BeginTx(ctx, nil) if err != nil { return 0, err } defer tx.Rollback() res, err := tx.ExecContext(ctx, `INSERT INTO ai_messages(session_id, role, content, tool_calls, tool_call_id, name, status, created_at) VALUES(?,?,?,?,?,?,?,?)`, m.SessionID, m.Role, m.Content, m.ToolCalls, m.ToolCallID, m.Name, m.Status, m.CreatedAt) if err != nil { return 0, err } id, err := res.LastInsertId() if err != nil { return 0, err } if _, err := tx.ExecContext(ctx, `UPDATE ai_sessions SET updated_at = ?, message_count = message_count + 1 WHERE id = ?`, now, m.SessionID); err != nil { return 0, err } if err := tx.Commit(); err != nil { return 0, err } m.ID = id return id, nil } func scanAIMessage(row interface{ Scan(...any) error }) (*AIMessage, error) { var v AIMessage err := row.Scan(&v.ID, &v.SessionID, &v.Role, &v.Content, &v.ToolCalls, &v.ToolCallID, &v.Name, &v.Status, &v.CreatedAt) if errors.Is(err, sql.ErrNoRows) { return nil, ErrNotFound } if err != nil { return nil, err } return &v, nil } // ListAIMessages returns messages after afterID in display order. func (s *Store) ListAIMessages(ctx context.Context, sessionID string, afterID int64, limit int) ([]*AIMessage, error) { if limit <= 0 || limit > 200 { limit = 100 } rows, err := s.db.QueryContext(ctx, `SELECT `+aiMessageColumns+` FROM ai_messages WHERE session_id = ? AND id > ? ORDER BY id ASC LIMIT ?`, sessionID, afterID, limit) if err != nil { return nil, err } defer rows.Close() out := make([]*AIMessage, 0, limit) for rows.Next() { v, err := scanAIMessage(rows) if err != nil { return nil, err } out = append(out, v) } return out, rows.Err() } // RecentAIMessages returns the newest limit messages in ascending order. func (s *Store) RecentAIMessages(ctx context.Context, sessionID string, limit int) ([]*AIMessage, error) { if limit <= 0 || limit > 200 { limit = 30 } rows, err := s.db.QueryContext(ctx, `SELECT `+aiMessageColumns+` FROM ai_messages WHERE session_id = ? ORDER BY id DESC LIMIT ?`, sessionID, limit) if err != nil { return nil, err } defer rows.Close() rev := make([]*AIMessage, 0, limit) for rows.Next() { v, err := scanAIMessage(rows) if err != nil { return nil, err } rev = append(rev, v) } out := make([]*AIMessage, 0, len(rev)) for i := len(rev) - 1; i >= 0; i-- { out = append(out, rev[i]) } return out, rows.Err() } // UpdateAIMessageStatus applies a message state such as error or aborted. func (s *Store) UpdateAIMessageStatus(ctx context.Context, id int64, status string) error { _, err := s.db.ExecContext(ctx, `UPDATE ai_messages SET status = ? WHERE id = ?`, status, id) return err } // CreateAIAction stores a tool call that needs human approval. func (s *Store) CreateAIAction(ctx context.Context, a *AIAction) error { now := time.Now().Unix() if a.CreatedAt == 0 { a.CreatedAt = now } if a.ExpiresAt == 0 { a.ExpiresAt = now + 600 } if a.Status == "" { a.Status = "pending" } _, err := s.db.ExecContext(ctx, `INSERT INTO ai_actions(id, session_id, message_id, tool_call_id, tool_name, arguments, summary, risk, status, result, user_id, created_at, expires_at, decided_at, executed_at) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, a.ID, a.SessionID, a.MessageID, a.ToolCallID, a.ToolName, a.Arguments, a.Summary, a.Risk, a.Status, a.Result, a.UserID, a.CreatedAt, a.ExpiresAt, a.DecidedAt, a.ExecutedAt) return err } func scanAIAction(row interface{ Scan(...any) error }) (*AIAction, error) { var v AIAction err := row.Scan(&v.ID, &v.SessionID, &v.MessageID, &v.ToolCallID, &v.ToolName, &v.Arguments, &v.Summary, &v.Risk, &v.Status, &v.Result, &v.UserID, &v.CreatedAt, &v.ExpiresAt, &v.DecidedAt, &v.ExecutedAt) if errors.Is(err, sql.ErrNoRows) { return nil, ErrNotFound } if err != nil { return nil, err } return &v, nil } // AIActionByID loads one pending or historical action. func (s *Store) AIActionByID(ctx context.Context, id string) (*AIAction, error) { row := s.db.QueryRowContext(ctx, `SELECT `+aiActionColumns+` FROM ai_actions WHERE id = ?`, id) return scanAIAction(row) } // PendingAIActions lists the approvals still blocking one conversation. func (s *Store) PendingAIActions(ctx context.Context, sessionID string) ([]*AIAction, error) { rows, err := s.db.QueryContext(ctx, `SELECT `+aiActionColumns+` FROM ai_actions WHERE session_id = ? AND status = 'pending' ORDER BY created_at ASC, id ASC`, sessionID) if err != nil { return nil, err } defer rows.Close() out := []*AIAction{} for rows.Next() { v, err := scanAIAction(rows) if err != nil { return nil, err } out = append(out, v) } return out, rows.Err() } // ResolveAIAction atomically claims a pending action for the given user. // It returns false when the action is missing, expired or already decided. func (s *Store) ResolveAIAction(ctx context.Context, id string, userID int64, status string) (bool, error) { now := time.Now().Unix() res, err := s.db.ExecContext(ctx, `UPDATE ai_actions SET status = ?, decided_at = ? WHERE id = ? AND user_id = ? AND status = 'pending' AND expires_at >= ?`, status, now, id, userID, now) if err != nil { return false, err } n, err := res.RowsAffected() if err != nil { return false, err } return n > 0, nil } // FinishAIAction records the execution result. func (s *Store) FinishAIAction(ctx context.Context, id, status, result string) error { _, err := s.db.ExecContext(ctx, `UPDATE ai_actions SET status = ?, result = ?, executed_at = ? WHERE id = ?`, status, result, time.Now().Unix(), id) return err } // ExpireAIActions closes approvals that were left untouched for too long. func (s *Store) ExpireAIActions(ctx context.Context, now int64) (int64, error) { res, err := s.db.ExecContext(ctx, `UPDATE ai_actions SET status = 'expired' WHERE status = 'pending' AND expires_at < ?`, now) if err != nil { return 0, err } return res.RowsAffected() } // DeleteOldAISessions keeps the database bounded by removing old conversations. func (s *Store) DeleteOldAISessions(ctx context.Context, before int64) (int64, error) { if before <= 0 { return 0, fmt.Errorf("缺少时间边界") } res, err := s.db.ExecContext(ctx, `DELETE FROM ai_sessions WHERE updated_at < ?`, before) if err != nil { return 0, err } return res.RowsAffected() }