## 配额重构:废除 Agent 终身额度
原实现在 agents 上放一个 max_rounds/used_rounds 计数器,used_rounds 单调递增、
永不重置 —— 跑满就要管理员手工重置才能再干活。那是把一次性资源模型套在长期
在线的服务上,且并行任务互相抢额度。
改为:
- 唯一被强制的预算是【会话】的往返预算(sessions.max_rounds/used_rounds),
写信时给、对话页里随时改 —— 配额的语义是「这件事值得多少个来回」,
那是任务的属性而不是 Agent 的属性
- agents.default_rounds 只作为「派给这个 Agent 的新任务」的默认值(默认 20)
- agents.used_rounds 降级为纯统计
- 新建会话速率限制(1h/20 条)堵住用 .new 开一串新会话绕过预算;
人类不受限(agentLimiterKey 返回空串即不计量)
## 窄屏适配(用户反馈「窄屏基本不可用」)
原先只有三栏并排:60(导航)+320(列表)+详情,375px 屏上详情被挤到 0。
第一版做成「一次只显示一栏」,用户纠正应当是新页面覆盖老页面并带动画,
于是重做为覆盖式:
- NarrowStack:底层列表始终挂载,详情绝对定位盖在上面。两个好处 ——
列表滚动位置与选中态天然保留;退出动画有东西可播(直接卸载再渲染另一个
组件的话,没有任何一帧能让旧页面往右滑出去)
- 因此必须区分「逻辑上是否打开」与「是否还在 DOM 里」:关闭时先播 200ms
滑出,动画结束才卸载
- 入场用双层 requestAnimationFrame:必须让浏览器至少绘制一帧「在右侧之外」
的状态,否则挂载与 translate-x-0 在同一帧内完成,transition 不触发
- 窄屏专属控件用 useIsNarrow() 条件渲染而非 md:hidden —— 后者只是视觉隐藏,
宽屏用户按 Tab 会聚焦到看不见的返回按钮
- 底部导航 + 抽屉侧栏 + env(safe-area-inset-bottom)
## 工作列表卡片视图(Phase 7.1 最后一项)
中间栏可切列表/卡片。列表答「跟谁在聊」,卡片答「在聊什么、进展如何」:
主题 + 最新一封的发件人与摘要 + 往返预算徽标。
- 两种视图共用同一份数据与同一套动作;归档确认框也共用 —— 归档是破坏性操作,
换个视图就换套确认 UI 只会让人对「自己点了什么」更没底
- 预算徽标在「不限」时不显示(对每张卡片都成立的「0/0」是纯噪声)
- 数据一次取回,不让卡片为每条会话再打一次库
## 修掉的缺陷
- GET /me/sessions 一直 500:ListSessionsFor 的 SELECT 加了预算两列却没加进
Scan,列数不匹配。联系人栏一条数据都拉不到,而错误只是「Failed to list sessions」
- GET /sessions/{id} 忘了填充附件:前端会话视图走的是这个端点,于是 Agent
回信里的附件在 UI 上完全不存在(另一个端点填了但没人调用)
- 插件曾完全没在加载:为了可测在 index.js 里 export 了辅助函数与一个 Map,
而 opencode 把入口模块的每一个导出都当成插件工厂逐个检查,多导出一个 Map
就 "Plugin export is not a function",插件静默失效、邮件全投不进去。
逻辑挪到 lib/relay-dedup.js,并加断言钉住「入口只有 default 导出」
- 同一件事发两封邮件:模型带附件主动回信后,session.idle 又把它最后那段话
自动转了一遍(生产实测 311 与 342 字节各一封)。explicitSends 记录本轮
主动发信,自动转发据此让位;relay_key 幂等管不了这个 —— 那个键保证的是
「同一条消息不转两次」
- SQLite 时间戳只有秒精度:同秒插入的多封邮件排序不确定(实测同秒插 5 封,
顺序由随机 UUID 决定)。「会话里最早那封」(决定联系人身份)与「最后那封」
(决定最新进展)都会取错。NOW() 升到微秒 + mails 的 INSERT 显式传它
(改 schema 默认值只对新库生效,SQLite 没有 ALTER COLUMN)+ 所有
ORDER BY created_at 补 mail_id 兜底
- fillAttachments 从逐封查询改成一次 IN(...):原来是 N+1,200 封的会话打开
要打 200 次库
- repo 层 5 处 rows.Next() 循环补 rows.Err():没有它,读到一半连接断掉会
静默返回部分结果,UI 上表现为「邮件凭空少了几封」
- go:embed 占位页改名 placeholder.html:叫 index.html 会被 Vite 产物覆盖并
提交进去,而它引用的 assets/ 是被忽略的 —— 新克隆打开是白屏
## 回复/转发栏
- 两处都加抄送(可折叠);原邮件带抄送时多一个「回复全部」,回填用
cc_list[].raw 而非重拼 name@path(后者会丢掉会话段)
- 会话视图每张卡片加转发入口:转发之前只存在于单封邮件视图,而人多数时间
待在会话视图里,等于功能在 UI 上找不到
- ReplyBar 的错误从 console.error 改为显示出来:预算耗尽、地址不存在、
速率限制都走这条路,之前点发送毫无反应
## 测试
- repo: 列顺序(三个 SQL 分支)、卡片字段、previewRunes 边界、时间戳亚秒精度、
批量附件查询、速率限制(80 goroutine 断言恰好 20 条通过)
- web: 窄屏布局 16 条结构性断言(覆盖而非分栏、延迟卸载、双层 rAF、
条件渲染而非 md:hidden)
- 插件: 自动转发去重 17 条(含「入口只有 default 导出」不变量)
- install.sh 把插件测试也纳入部署前门禁
304 lines
11 KiB
Go
304 lines
11 KiB
Go
package repo
|
||
|
||
import (
|
||
"context"
|
||
"database/sql"
|
||
"errors"
|
||
"fmt"
|
||
|
||
"github.com/agentmail/gateway/internal/db"
|
||
"github.com/agentmail/gateway/internal/models"
|
||
"github.com/google/uuid"
|
||
)
|
||
|
||
// ---------- 配额 ----------
|
||
//
|
||
// **配额是任务的属性,不是 Agent 的属性。**
|
||
//
|
||
// 真正的约束在 `sessions.max_rounds`(见本文件末尾的「会话级往返预算」):
|
||
// 每条会话独立计数,人在派活时给、在对话页里随时调。
|
||
//
|
||
// `agents` 表这边只剩两样东西:
|
||
//
|
||
// default_rounds —— 派给这个 Agent 的**新任务**默认多少个来回。
|
||
// 不同 Agent 能力不同(跑测试的小工具 vs 重构整个模块),
|
||
// 默认值分开设才合理。
|
||
//
|
||
// used_rounds —— 纯统计,累计发信数。**不再拦任何请求。**
|
||
// 它原本是「终身额度」:跑满就得管理员手工重置才能再干活,
|
||
// 而 Agent 是长期在线的 —— 终身额度是错的工具。
|
||
// 保留是因为「这个 Agent 一共发了多少信」本身有观测价值。
|
||
//
|
||
// 防止 Agent 用 `.new` 开一串新会话绕过预算,靠的是**新建会话速率限制**
|
||
// (见 sessionRateLimiter),而不是终身额度。
|
||
// AgentStats 是一个 Agent 的配额默认值与累计统计。
|
||
//
|
||
// 没有 Remaining / Unlimited 字段:这里不再有「剩余额度」的概念 ——
|
||
// 额度属于会话(SessionBudget),这里只有「新任务默认多少来回」与「一共发了多少信」。
|
||
type AgentStats struct {
|
||
AgentName string `json:"agent_name"`
|
||
// DefaultRounds 派给该 Agent 的新任务默认多少个来回(0 = 不限)
|
||
DefaultRounds int `json:"default_rounds"`
|
||
// SentTotal 累计发信数(纯统计,不拦请求)
|
||
SentTotal int `json:"sent_total"`
|
||
// ActiveSessions 该 Agent 参与的未归档会话数,配合默认值判断设多少合适
|
||
ActiveSessions int `json:"active_sessions"`
|
||
}
|
||
|
||
// DefaultRoundsFor 读取该 Agent 的新任务默认预算。
|
||
//
|
||
// Agent 不存在时返回全局兜底值而非报错:派活的人不该因为「对方还没注册」
|
||
// 就拿不到一个合理的默认预算 —— 邮件本来就支持发给尚未上线的收件人。
|
||
func DefaultRoundsFor(ctx context.Context, agentName string) int {
|
||
var n int
|
||
err := db.DB.QueryRowContext(ctx,
|
||
`SELECT COALESCE(default_rounds, 0) FROM agents WHERE agent_name = $1`,
|
||
agentName).Scan(&n)
|
||
if err != nil || n < 0 {
|
||
return fallbackDefaultRounds
|
||
}
|
||
return n
|
||
}
|
||
|
||
// fallbackDefaultRounds 是 Agent 未注册时的兜底默认预算。
|
||
// 与建表默认值保持一致;改这里要同时改两份 schema。
|
||
const fallbackDefaultRounds = 20
|
||
|
||
// SetDefaultRounds 设置该 Agent 的新任务默认预算(0 = 不限)。
|
||
func SetDefaultRounds(ctx context.Context, agentName string, n int) (AgentStats, error) {
|
||
if n < 0 {
|
||
n = 0
|
||
}
|
||
tag, err := db.DB.ExecContext(ctx,
|
||
`UPDATE agents SET default_rounds = $2 WHERE agent_name = $1`, agentName, n)
|
||
if err != nil {
|
||
return AgentStats{}, err
|
||
}
|
||
if k, _ := tag.RowsAffected(); k == 0 {
|
||
return AgentStats{}, fmt.Errorf("agent %q 不存在", agentName)
|
||
}
|
||
return GetAgentStats(ctx, agentName)
|
||
}
|
||
|
||
// GetAgentStats 读取某 Agent 的默认预算与累计统计。
|
||
func GetAgentStats(ctx context.Context, agentName string) (AgentStats, error) {
|
||
var st AgentStats
|
||
st.AgentName = agentName
|
||
err := db.DB.QueryRowContext(ctx, `
|
||
SELECT COALESCE(default_rounds, 0), COALESCE(used_rounds, 0)
|
||
FROM agents WHERE agent_name = $1`, agentName,
|
||
).Scan(&st.DefaultRounds, &st.SentTotal)
|
||
if errors.Is(err, sql.ErrNoRows) {
|
||
return AgentStats{}, fmt.Errorf("agent %q 不存在", agentName)
|
||
}
|
||
if err != nil {
|
||
return AgentStats{}, err
|
||
}
|
||
st.ActiveSessions = countActiveSessionsFor(ctx, agentName)
|
||
return st, nil
|
||
}
|
||
|
||
// countActiveSessionsFor 统计该 Agent 参与的未归档会话数。
|
||
// 查不出来返回 0:这只是个展示用的数字,不该让整个统计接口失败。
|
||
func countActiveSessionsFor(ctx context.Context, agentName string) int {
|
||
var n int
|
||
err := db.DB.QueryRowContext(ctx, `
|
||
SELECT COUNT(DISTINCT s.session_id)
|
||
FROM sessions s
|
||
JOIN mails m ON m.session_id = s.session_id
|
||
WHERE s.status <> 'archived'
|
||
AND (m.from_name = $1 OR m.to_name = $1 OR `+db.CCHas("m.cc_list", 1)+`)
|
||
`, agentName).Scan(&n)
|
||
if err != nil {
|
||
return 0
|
||
}
|
||
return n
|
||
}
|
||
|
||
// BumpSentCount 累加发信统计。
|
||
//
|
||
// **绝不拦请求**:它是观测数据,不是额度。返回值只有 error,
|
||
// 而且调用方应当忽略它 —— 统计写失败不该让一封已经该发出的邮件失败。
|
||
func BumpSentCount(ctx context.Context, agentName string) {
|
||
_, _ = db.DB.ExecContext(ctx,
|
||
`UPDATE agents SET used_rounds = COALESCE(used_rounds, 0) + 1 WHERE agent_name = $1`,
|
||
agentName)
|
||
}
|
||
|
||
// ListAgentStats 列出所有 Agent 的默认预算与统计(管理员视图)。
|
||
func ListAgentStats(ctx context.Context) ([]AgentStats, error) {
|
||
rows, err := db.DB.QueryContext(ctx,
|
||
`SELECT agent_name, COALESCE(default_rounds, 0), COALESCE(used_rounds, 0)
|
||
FROM agents ORDER BY agent_name`)
|
||
if err != nil {
|
||
return nil, err
|
||
}
|
||
defer rows.Close()
|
||
|
||
out := []AgentStats{}
|
||
for rows.Next() {
|
||
var st AgentStats
|
||
if err := rows.Scan(&st.AgentName, &st.DefaultRounds, &st.SentTotal); err != nil {
|
||
return nil, err
|
||
}
|
||
out = append(out, st)
|
||
}
|
||
if err := rows.Err(); err != nil {
|
||
return nil, err
|
||
}
|
||
// 会话数逐个查:Agent 数量是个位数到几十,不值得为它写一个 GROUP BY 的联合查询
|
||
for i := range out {
|
||
out[i].ActiveSessions = countActiveSessionsFor(ctx, out[i].AgentName)
|
||
}
|
||
return out, nil
|
||
}
|
||
|
||
// ---------- 转发 ----------
|
||
|
||
// ForwardSource 是被转发邮件的必要信息。
|
||
type ForwardSource struct {
|
||
Mail *models.Mail
|
||
Session uuid.UUID
|
||
}
|
||
|
||
// LoadForwardSource 读取待转发的邮件,并校验转发者确实参与过该邮件
|
||
//(收件人、发件人或被抄送方之一)。防止凭 mail_id 转发别人的邮件。
|
||
func LoadForwardSource(ctx context.Context, mailID uuid.UUID, actor string) (*models.Mail, error) {
|
||
m, err := GetMailByID(ctx, mailID)
|
||
if err != nil {
|
||
return nil, ErrMailNotFound
|
||
}
|
||
|
||
if m.FromName == actor || m.ToName == actor {
|
||
return m, nil
|
||
}
|
||
for _, cc := range m.CCList {
|
||
if cc.Name == actor {
|
||
return m, nil
|
||
}
|
||
}
|
||
return nil, ErrForwardNotAllowed
|
||
}
|
||
|
||
var (
|
||
// ErrMailNotFound 待转发的邮件不存在
|
||
ErrMailNotFound = errors.New("mail not found")
|
||
// ErrForwardNotAllowed 转发者未参与该邮件
|
||
ErrForwardNotAllowed = errors.New("not a participant of that mail")
|
||
)
|
||
|
||
// ---------- 会话级往返预算 ----------
|
||
//
|
||
// 配额的真实语义是「这件事值得多少个来回」——那是**任务**的属性,不是 Agent 的属性。
|
||
// 只有 agents.max_rounds 一个全局计数器时有两个问题:
|
||
// 1. 两个并行任务互相抢额度:给紧急任务留的份被另一条线索吃掉
|
||
// 2. used_rounds 单调递增,跑满就得管理员手工重置才能再干活
|
||
// 因此预算下沉到会话,由人在写信时给、在对话页里随时调。
|
||
//
|
||
// **两层都要过**:会话预算 + Agent 全局配额。少了后者,Agent 自己 `.new` 开一串会话
|
||
// 每条都是全新预算,全局上限形同虚设;少了前者,就回到抢额度的老问题。
|
||
|
||
// SessionBudget 是一个会话的往返预算快照。
|
||
type SessionBudget struct {
|
||
SessionID uuid.UUID `json:"session_id"`
|
||
Max int `json:"max_rounds"` // 0 = 本会话不限
|
||
Used int `json:"used_rounds"`
|
||
Remaining int `json:"remaining"` // 不限时为 -1
|
||
Unlimited bool `json:"unlimited"`
|
||
}
|
||
|
||
func makeSessionBudget(id uuid.UUID, max, used int) SessionBudget {
|
||
b := SessionBudget{SessionID: id, Max: max, Used: used, Unlimited: max <= 0}
|
||
if b.Unlimited {
|
||
b.Remaining = -1
|
||
return b
|
||
}
|
||
if r := max - used; r > 0 {
|
||
b.Remaining = r
|
||
}
|
||
return b
|
||
}
|
||
|
||
// ErrSessionBudgetExhausted 表示该会话的往返预算已用尽。
|
||
var ErrSessionBudgetExhausted = errors.New("session budget exhausted")
|
||
|
||
// GetSessionBudget 读取会话预算。
|
||
func GetSessionBudget(ctx context.Context, id uuid.UUID) (SessionBudget, error) {
|
||
var max, used int
|
||
err := db.DB.QueryRowContext(ctx,
|
||
`SELECT COALESCE(max_rounds,0), COALESCE(used_rounds,0) FROM sessions WHERE session_id = $1`,
|
||
id).Scan(&max, &used)
|
||
if errors.Is(err, sql.ErrNoRows) {
|
||
return SessionBudget{}, fmt.Errorf("会话 %s 不存在", id)
|
||
}
|
||
if err != nil {
|
||
return SessionBudget{}, err
|
||
}
|
||
return makeSessionBudget(id, max, used), nil
|
||
}
|
||
|
||
// ConsumeSessionBudget 原子地占用会话的一次往返。
|
||
//
|
||
// 与 ConsumeQuota 同理:判断与自增必须在同一条 UPDATE 里(WHERE used_rounds < max_rounds),
|
||
// 否则并发发信会双双通过检查再各自 +1,把预算刷穿。
|
||
func ConsumeSessionBudget(ctx context.Context, id uuid.UUID) (SessionBudget, error) {
|
||
tag, err := db.DB.ExecContext(ctx, `
|
||
UPDATE sessions SET used_rounds = COALESCE(used_rounds,0) + 1
|
||
WHERE session_id = $1
|
||
AND (COALESCE(max_rounds,0) <= 0 OR COALESCE(used_rounds,0) < max_rounds)
|
||
`, id)
|
||
if err != nil {
|
||
return SessionBudget{}, err
|
||
}
|
||
if n, _ := tag.RowsAffected(); n == 0 {
|
||
b, bErr := GetSessionBudget(ctx, id)
|
||
if bErr != nil {
|
||
return SessionBudget{}, bErr
|
||
}
|
||
return b, ErrSessionBudgetExhausted
|
||
}
|
||
return GetSessionBudget(ctx, id)
|
||
}
|
||
|
||
// SetSessionBudget 设置会话预算上限(0 = 不限)。
|
||
//
|
||
// 允许把上限调到低于已用次数:那表示「就到这里为止」,是人的合法意图,
|
||
// 不该因为算不出正的剩余量就拒绝。此时 Remaining 为 0,下次发信即被拦。
|
||
func SetSessionBudget(ctx context.Context, id uuid.UUID, max int) (SessionBudget, error) {
|
||
if max < 0 {
|
||
max = 0
|
||
}
|
||
tag, err := db.DB.ExecContext(ctx,
|
||
`UPDATE sessions SET max_rounds = $2, updated_at = NOW() WHERE session_id = $1`, id, max)
|
||
if err != nil {
|
||
return SessionBudget{}, err
|
||
}
|
||
if n, _ := tag.RowsAffected(); n == 0 {
|
||
return SessionBudget{}, fmt.Errorf("会话 %s 不存在", id)
|
||
}
|
||
return GetSessionBudget(ctx, id)
|
||
}
|
||
|
||
// ResetSessionBudget 把该会话的已用次数归零(上限不变)。
|
||
func ResetSessionBudget(ctx context.Context, id uuid.UUID) (SessionBudget, error) {
|
||
tag, err := db.DB.ExecContext(ctx,
|
||
`UPDATE sessions SET used_rounds = 0, updated_at = NOW() WHERE session_id = $1`, id)
|
||
if err != nil {
|
||
return SessionBudget{}, err
|
||
}
|
||
if n, _ := tag.RowsAffected(); n == 0 {
|
||
return SessionBudget{}, fmt.Errorf("会话 %s 不存在", id)
|
||
}
|
||
return GetSessionBudget(ctx, id)
|
||
}
|
||
|
||
// RefundSessionBudget 退还一次往返。
|
||
//
|
||
// 会话预算先扣、Agent 全局配额后扣,全局那层拦下时必须把会话这次还回去,
|
||
// 否则会话预算白掉一格 —— 那次往返实际上没有发生。
|
||
func RefundSessionBudget(ctx context.Context, id uuid.UUID) {
|
||
_, _ = db.DB.ExecContext(ctx,
|
||
`UPDATE sessions SET used_rounds = COALESCE(used_rounds,0) - 1
|
||
WHERE session_id = $1 AND COALESCE(used_rounds,0) > 0`, id)
|
||
}
|