## 配额重构:废除 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 把插件测试也纳入部署前门禁
306 lines
9.0 KiB
Go
306 lines
9.0 KiB
Go
package handler
|
||
|
||
import (
|
||
"net/http"
|
||
"time"
|
||
|
||
"github.com/agentmail/gateway/internal/middleware"
|
||
"github.com/agentmail/gateway/internal/models"
|
||
"github.com/agentmail/gateway/internal/repo"
|
||
"github.com/google/uuid"
|
||
)
|
||
|
||
// ---------- /me:当前登录人类用户的邮箱(全部路由需 UserAuth) ----------
|
||
|
||
type meSendMailRequest struct {
|
||
To string `json:"to"` // name@path.session
|
||
CC string `json:"cc"` // 多个 name@path.session
|
||
Subject string `json:"subject"`
|
||
Body string `json:"body"`
|
||
ReplyTo string `json:"reply_to"`
|
||
// SessionAlias 仅在本次投递【新建】会话时生效,为新会话命名
|
||
SessionAlias string `json:"session_alias"`
|
||
// AttachmentIDs 先用 POST /me/attachments 上传拿到的 id
|
||
AttachmentIDs []string `json:"attachment_ids"`
|
||
// MaxRounds 是本次任务的往返预算(0/省略 = 不限)。
|
||
//
|
||
// 配额的真实语义是「这件事值得多少个来回」——那是任务的属性,
|
||
// 所以在派活的这一刻给,而不是事后到管理员页面去调某个 Agent 的全局配额。
|
||
// 仅在本次投递【新建】会话时生效;续谈已有会话请用
|
||
// PUT /sessions/{id}/budget(对话页里可随时改)。
|
||
MaxRounds *int `json:"max_rounds"`
|
||
}
|
||
|
||
// POST /api/v1/me/mail/send
|
||
func MeSendMail(w http.ResponseWriter, r *http.Request) {
|
||
user := middleware.GetUser(r)
|
||
if user == nil {
|
||
Error(w, http.StatusUnauthorized, "not authenticated")
|
||
return
|
||
}
|
||
|
||
var req meSendMailRequest
|
||
if err := Decode(r, &req); err != nil {
|
||
Error(w, http.StatusBadRequest, "Invalid JSON")
|
||
return
|
||
}
|
||
if req.To == "" || req.Subject == "" || req.Body == "" {
|
||
Error(w, http.StatusBadRequest, "Missing to, subject, or body")
|
||
return
|
||
}
|
||
|
||
to, err := models.ParseAddress(req.To)
|
||
if err != nil {
|
||
Error(w, http.StatusBadRequest, "Invalid to address: "+err.Error())
|
||
return
|
||
}
|
||
ccList, err := models.ParseAddressList(req.CC)
|
||
if err != nil {
|
||
Error(w, http.StatusBadRequest, "Invalid cc address: "+err.Error())
|
||
return
|
||
}
|
||
attachIDs, err := parseAttachmentIDs(req.AttachmentIDs)
|
||
if err != nil {
|
||
Error(w, http.StatusBadRequest, err.Error())
|
||
return
|
||
}
|
||
|
||
// human@ 是兼容别名,人类发信时解析为自己
|
||
to = resolveHumanAlias(to, user.Username)
|
||
for i := range ccList {
|
||
ccList[i] = resolveHumanAlias(ccList[i], user.Username)
|
||
}
|
||
|
||
// 权限边界:校验可调用的 Agent 与可访问的目录
|
||
if msg := checkScope(r, user, append([]models.Address{to}, ccList...)); msg != "" {
|
||
Error(w, http.StatusForbidden, msg)
|
||
return
|
||
}
|
||
|
||
sessionID, parentMailID, err := resolveTarget(r, to, req.ReplyTo, user.Username, req.Subject, req.SessionAlias, "")
|
||
if err != nil {
|
||
writeErr(w, err, "Failed to resolve session")
|
||
return
|
||
}
|
||
// 人类发起的会话归属于该用户
|
||
_ = repo.SetSessionOwner(r.Context(), sessionID, user.ID)
|
||
|
||
// 新建会话时定往返预算。只在新建时设:续谈已有会话若也接受这个字段,
|
||
// 每封新信都会悄悄改掉对方正在遵守的预算,人却不一定意识到自己改了。
|
||
//
|
||
// 没显式给就用【收件 Agent 的默认值】。默认值挂在 Agent 上而不是全站一个数:
|
||
// 跑测试的小工具与重构整个模块的 Agent,合理来回数差一个量级。
|
||
if parentMailID == nil {
|
||
rounds := 0
|
||
if req.MaxRounds != nil {
|
||
if *req.MaxRounds < 0 {
|
||
Error(w, http.StatusBadRequest, "max_rounds 不能为负")
|
||
return
|
||
}
|
||
rounds = *req.MaxRounds
|
||
} else {
|
||
rounds = repo.DefaultRoundsFor(r.Context(), to.Name)
|
||
}
|
||
if _, err := repo.SetSessionBudget(r.Context(), sessionID, rounds); err != nil {
|
||
Error(w, http.StatusInternalServerError, "Failed to set session budget")
|
||
return
|
||
}
|
||
}
|
||
|
||
// 人类侧不产生改名提议(人直接有改名按钮,用不着向自己提议),
|
||
// 但仍然剥掉标记:粘贴进正文时它会被渲染成一行可见的转义文本。
|
||
_, body := extractRenameProposal(req.Body)
|
||
|
||
mailID, err := repo.CreateMail(r.Context(), sessionID, parentMailID,
|
||
user.Username, "", to.Name, to.Path, req.Subject, body, ccList)
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "Failed to create mail")
|
||
return
|
||
}
|
||
|
||
if !attachAll(w, r, mailID, attachIDs, user.Username) {
|
||
return
|
||
}
|
||
|
||
notifyRecipients(to, ccList, sessionID, mailID, user.Username, req.Subject)
|
||
|
||
resp := map[string]any{
|
||
"mail_id": mailID.String(),
|
||
"session_id": sessionID.String(),
|
||
"session_alias": repo.SessionAliasOf(r.Context(), sessionID),
|
||
}
|
||
// 回传预算,让前端不必再单独查一次就能显示「本任务还剩几个来回」
|
||
if b, err := repo.GetSessionBudget(r.Context(), sessionID); err == nil && !b.Unlimited {
|
||
resp["budget_max"] = b.Max
|
||
resp["budget_used"] = b.Used
|
||
resp["budget_remaining"] = b.Remaining
|
||
}
|
||
JSON(w, http.StatusOK, resp)
|
||
}
|
||
|
||
// GET /api/v1/me/mail/inbox
|
||
func MeGetInbox(w http.ResponseWriter, r *http.Request) {
|
||
user := middleware.GetUser(r)
|
||
if user == nil {
|
||
Error(w, http.StatusUnauthorized, "not authenticated")
|
||
return
|
||
}
|
||
|
||
status := r.URL.Query().Get("status")
|
||
if status == "" {
|
||
status = "all"
|
||
}
|
||
limit := 50
|
||
if l := r.URL.Query().Get("limit"); l != "" {
|
||
if n, err := parseInt(l); err == nil && n > 0 {
|
||
limit = n
|
||
}
|
||
}
|
||
|
||
mails, err := repo.ListInbox(r.Context(), user.Username, status, limit)
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "Failed to list inbox")
|
||
return
|
||
}
|
||
// 列表页要显示附件图标与下载入口
|
||
ptrs := make([]*models.Mail, len(mails))
|
||
for i := range mails {
|
||
ptrs[i] = &mails[i]
|
||
}
|
||
fillAttachments(r, ptrs...)
|
||
total, _ := repo.CountUnread(r.Context(), user.Username)
|
||
|
||
JSON(w, http.StatusOK, map[string]interface{}{
|
||
"mails": emptySlice(mails),
|
||
"total": total,
|
||
})
|
||
}
|
||
|
||
// GET /api/v1/me/mail/sent
|
||
func MeGetSent(w http.ResponseWriter, r *http.Request) {
|
||
user := middleware.GetUser(r)
|
||
if user == nil {
|
||
Error(w, http.StatusUnauthorized, "not authenticated")
|
||
return
|
||
}
|
||
|
||
limit := 50
|
||
if l := r.URL.Query().Get("limit"); l != "" {
|
||
if n, err := parseInt(l); err == nil && n > 0 {
|
||
limit = n
|
||
}
|
||
}
|
||
|
||
mails, err := repo.ListSentBy(r.Context(), user.Username, limit)
|
||
if err == nil {
|
||
ptrs := make([]*models.Mail, len(mails))
|
||
for i := range mails {
|
||
ptrs[i] = &mails[i]
|
||
}
|
||
fillAttachments(r, ptrs...)
|
||
}
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "Failed to list sent")
|
||
return
|
||
}
|
||
JSON(w, http.StatusOK, map[string]interface{}{
|
||
"mails": emptySlice(mails),
|
||
})
|
||
}
|
||
|
||
// GET /api/v1/me/sessions
|
||
func MeGetSessions(w http.ResponseWriter, r *http.Request) {
|
||
user := middleware.GetUser(r)
|
||
if user == nil {
|
||
Error(w, http.StatusUnauthorized, "not authenticated")
|
||
return
|
||
}
|
||
|
||
scope := user.Username
|
||
if user.IsAdmin() && r.URL.Query().Get("all") == "true" {
|
||
scope = ""
|
||
}
|
||
|
||
sessions, err := repo.ListSessionsFor(r.Context(), scope, 50)
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "Failed to list sessions")
|
||
return
|
||
}
|
||
|
||
type SessionOut struct {
|
||
SessionID uuid.UUID `json:"session_id"`
|
||
SessionAlias *string `json:"session_alias"`
|
||
FromAgent string `json:"from_agent"`
|
||
Subject string `json:"subject"`
|
||
Status string `json:"status"`
|
||
CreatedAt time.Time `json:"created_at"`
|
||
UpdatedAt time.Time `json:"updated_at"`
|
||
MailCount int `json:"mail_count"`
|
||
UnreadCount int `json:"unread_count"`
|
||
// 往返预算随列表一并返回:预算是【任务】的属性,
|
||
// 工作列表上就应当看得见哪些任务快跑满了,
|
||
// 而不是点进去一个一个查。
|
||
MaxRounds int `json:"max_rounds"`
|
||
UsedRounds int `json:"used_rounds"`
|
||
}
|
||
|
||
result := make([]SessionOut, 0, len(sessions))
|
||
for _, s := range sessions {
|
||
unread, _ := repo.CountUnreadInSession(r.Context(), user.Username, s.ID)
|
||
result = append(result, SessionOut{
|
||
SessionID: s.ID,
|
||
SessionAlias: s.Alias,
|
||
FromAgent: s.FromAgent,
|
||
Subject: s.Subject,
|
||
Status: s.Status,
|
||
CreatedAt: s.CreatedAt,
|
||
UpdatedAt: s.UpdatedAt,
|
||
MailCount: s.MailCount,
|
||
UnreadCount: unread,
|
||
MaxRounds: s.MaxRounds,
|
||
UsedRounds: s.UsedRounds,
|
||
})
|
||
}
|
||
|
||
JSON(w, http.StatusOK, map[string]interface{}{
|
||
"sessions": result,
|
||
})
|
||
}
|
||
|
||
// resolveHumanAlias 把兼容别名 human 解析为具体用户名
|
||
func resolveHumanAlias(a models.Address, username string) models.Address {
|
||
if a.Name != "human" {
|
||
return a
|
||
}
|
||
a.Name = username
|
||
a.Raw = username + "@" + a.Path
|
||
if a.Session != "" {
|
||
a.Raw += "." + a.Session
|
||
}
|
||
return a
|
||
}
|
||
|
||
// checkScope 校验用户的 Agent 白名单与目录白名单;返回空串表示通过。
|
||
// 收件方是人类用户时不受 Agent 白名单约束(人与人通信始终允许)。
|
||
func checkScope(r *http.Request, user *models.User, addrs []models.Address) string {
|
||
if user.IsAdmin() {
|
||
return ""
|
||
}
|
||
for _, a := range addrs {
|
||
if a.Name == "" || a.Name == user.Username {
|
||
continue
|
||
}
|
||
isHuman, err := repo.IsHumanUser(r.Context(), a.Name)
|
||
if err != nil {
|
||
return "无法校验收件人权限"
|
||
}
|
||
if !isHuman && !user.CanUseAgent(a.Name) {
|
||
return "无权调用 Agent: " + a.Name
|
||
}
|
||
if !user.CanUsePath(a.Path) {
|
||
return "无权访问目录: " + a.Path
|
||
}
|
||
}
|
||
return ""
|
||
}
|