## 配额重构:废除 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 把插件测试也纳入部署前门禁
310 lines
10 KiB
Go
310 lines
10 KiB
Go
package main
|
||
|
||
import (
|
||
"context"
|
||
"fmt"
|
||
"log"
|
||
"net/http"
|
||
"os"
|
||
"os/signal"
|
||
"syscall"
|
||
"time"
|
||
|
||
"github.com/agentmail/gateway/internal/blob"
|
||
"github.com/agentmail/gateway/internal/config"
|
||
"github.com/agentmail/gateway/internal/db"
|
||
"github.com/agentmail/gateway/internal/handler"
|
||
"github.com/agentmail/gateway/internal/middleware"
|
||
"github.com/agentmail/gateway/internal/repo"
|
||
"github.com/agentmail/gateway/internal/static"
|
||
"github.com/go-chi/chi/v5"
|
||
chimw "github.com/go-chi/chi/v5/middleware"
|
||
"github.com/go-chi/cors"
|
||
)
|
||
|
||
func main() {
|
||
cfg := config.Load()
|
||
|
||
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||
defer cancel()
|
||
|
||
if err := db.Connect(ctx, cfg.DatabaseURL); err != nil {
|
||
log.Fatalf("Database connection failed: %v", err)
|
||
}
|
||
defer db.Close()
|
||
|
||
// 第一轮迁移:建表(users 必须先存在,'human' 数据迁移才能找到管理员)
|
||
if err := db.Migrate(ctx); err != nil {
|
||
log.Fatalf("Migration failed: %v", err)
|
||
}
|
||
|
||
// 确保存在默认管理员
|
||
bootstrapAdmin(ctx, cfg)
|
||
|
||
// 第二轮迁移:此时管理员已存在,历史 'human' 字面量得以重写
|
||
// (仅 PostgreSQL 有该历史包袹;SQLite 是新后端,这一轮是幂等的建表重跑)
|
||
if err := db.Migrate(ctx); err != nil {
|
||
log.Fatalf("Post-admin migration failed: %v", err)
|
||
}
|
||
|
||
// 附件存储:内容存盘,数据库只存元数据
|
||
blobs, err := blob.New(cfg.AttachmentDir)
|
||
if err != nil {
|
||
log.Fatalf("Attachment store failed: %v", err)
|
||
}
|
||
handler.Blobs = blobs
|
||
fmt.Printf("附件存储:%s(单个上限 %.0f MB)\n",
|
||
blobs.Root(), float64(cfg.MaxAttachmentBytes)/(1<<20))
|
||
|
||
// 后台 GC:清掉上传后未随邮件发出的孤立附件,
|
||
// 否则取消发信与 Agent 崩溃留下的文件会让磁盘单调增长。
|
||
go sweepOrphanAttachments(blobs)
|
||
|
||
r := chi.NewRouter()
|
||
|
||
r.Use(chimw.Logger)
|
||
r.Use(chimw.Recoverer)
|
||
r.Use(chimw.RequestID)
|
||
r.Use(chimw.RealIP)
|
||
r.Use(cors.Handler(cors.Options{
|
||
AllowedOrigins: cfg.CORSOrigins,
|
||
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE", "OPTIONS"},
|
||
AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-Agent-Name", "X-Agent-Secret"},
|
||
// 附件下载靠 Content-Disposition 拿文件名;不暂存就拿不到。
|
||
// Content-Length 给进度条用。
|
||
ExposedHeaders: []string{"Link", "Content-Disposition", "Content-Length"},
|
||
AllowCredentials: true,
|
||
MaxAge: 300,
|
||
}))
|
||
|
||
r.Get("/health", func(w http.ResponseWriter, r *http.Request) {
|
||
w.Header().Set("Content-Type", "application/json")
|
||
w.Write([]byte(`{"status":"ok"}`))
|
||
})
|
||
|
||
r.Route("/api/v1", func(r chi.Router) {
|
||
// ---- 首次初始化(公开;仅系统无用户时可用) ----
|
||
r.Get("/setup/status", handler.SetupStatus)
|
||
r.Post("/setup/admin", handler.SetupAdmin)
|
||
|
||
// ---- 认证(公开) ----
|
||
r.Post("/auth/login", handler.Login)
|
||
r.Post("/auth/logout", handler.Logout)
|
||
|
||
// ---- Agent 注册(凭 secret,非人类登录态) ----
|
||
r.Post("/agent/register", handler.RegisterAgent)
|
||
|
||
// ---- Agent 侧(X-Agent-Name + X-Agent-Secret) ----
|
||
r.Group(func(r chi.Router) {
|
||
r.Use(middleware.AgentAuth)
|
||
r.Post("/agent/heartbeat", handler.HeartbeatAgent)
|
||
r.Post("/mail/send", handler.SendMail)
|
||
r.Get("/mail/inbox", handler.GetInbox)
|
||
// 批量标记已读:不给 mail_ids 就把收件箱全部未读标掉。
|
||
// 没有它的话 Agent 每次拉收件箱都会重复捞同一批旧邮件。
|
||
r.Post("/mail/read", handler.MarkInboxRead)
|
||
r.Post("/mail/{id}/forward", handler.ForwardMail)
|
||
r.Post("/permission/request", handler.RequestPermission)
|
||
// 附件:先上传拿 id,再在发信时放进 attachment_ids
|
||
r.Post("/attachments", handler.UploadAttachment)
|
||
r.Get("/attachments/{id}", handler.DownloadAttachment)
|
||
// 平台侧会话标题/slug 回写本侧(平台叫什么,本侧就叫什么)
|
||
r.Post("/sessions/{id}/sync", handler.SyncSession)
|
||
})
|
||
|
||
// ---- 人类登录态 ----
|
||
r.Group(func(r chi.Router) {
|
||
r.Use(middleware.UserAuth)
|
||
|
||
r.Get("/auth/me", handler.Me)
|
||
r.Post("/auth/password", handler.ChangePassword)
|
||
|
||
// 自己的邮箱
|
||
r.Post("/me/mail/send", handler.MeSendMail)
|
||
r.Get("/me/mail/inbox", handler.MeGetInbox)
|
||
r.Get("/me/mail/sent", handler.MeGetSent)
|
||
r.Get("/me/sessions", handler.MeGetSessions)
|
||
r.Post("/me/mail/{id}/forward", handler.MeForwardMail)
|
||
|
||
// 附件
|
||
r.Post("/me/attachments", handler.MeUploadAttachment)
|
||
r.Delete("/me/attachments/{id}", handler.MeDeleteAttachment)
|
||
|
||
// 自己的客户端连接密钥(仅能用于 /me/* 与会话级接口,不可注册 Agent)
|
||
r.Post("/me/keys", handler.CreateMyKey)
|
||
r.Get("/me/keys", handler.ListMyKeys)
|
||
r.Delete("/me/keys/{id}", handler.DeleteMyKey)
|
||
|
||
// 邮件/会话(带会话级鉴权)
|
||
r.Get("/mail/{id}", handler.GetMail)
|
||
r.Get("/mail/{id}/thread", handler.GetMailThread)
|
||
r.Post("/mail/{id}/read", handler.MarkMailRead)
|
||
r.Get("/sessions/{id}", handler.GetSession)
|
||
r.Get("/sessions/{id}/mails", handler.GetSessionMails)
|
||
r.Put("/sessions/{id}/alias", handler.UpdateSessionAlias)
|
||
// 本任务的往返预算:在对话页里随时可改
|
||
r.Get("/sessions/{id}/budget", handler.GetSessionBudgetHandler)
|
||
r.Put("/sessions/{id}/budget", handler.UpdateSessionBudget)
|
||
// Agent 在正文里提的改名建议:读取与驳回(接受走上面的 PUT alias)
|
||
r.Get("/sessions/{id}/rename-proposal", handler.GetRenameProposal)
|
||
r.Post("/sessions/{id}/rename-proposal/dismiss", handler.DismissRenameProposal)
|
||
|
||
// 联系人 name@path.session
|
||
r.Get("/contacts", handler.ListContacts)
|
||
r.Get("/contacts/suggest", handler.SuggestAddress)
|
||
r.Post("/contacts/archive", handler.ArchiveContact)
|
||
|
||
// 权限决策
|
||
r.Post("/permission/decide", handler.DecidePermission)
|
||
r.Get("/permission/pending", handler.ListPendingPermissions)
|
||
|
||
// 在线 Agent 列表(补全用)
|
||
r.Get("/agents", handler.ListAgents)
|
||
|
||
// 管理员
|
||
r.Group(func(r chi.Router) {
|
||
r.Use(middleware.AdminOnly)
|
||
r.Get("/admin/users", handler.AdminListUsers)
|
||
r.Post("/admin/users", handler.AdminCreateUser)
|
||
r.Put("/admin/users/{id}", handler.AdminUpdateUser)
|
||
r.Delete("/admin/users/{id}", handler.AdminDisableUser)
|
||
r.Post("/admin/users/{id}/reset", handler.AdminResetPassword)
|
||
r.Get("/admin/scopes", handler.AdminListScopes)
|
||
|
||
// Agent 接入密钥
|
||
r.Post("/admin/agent-keys", handler.CreateAgentKey)
|
||
r.Get("/admin/agent-keys", handler.ListAgentKeys)
|
||
r.Delete("/admin/agent-keys/{id}", handler.DeleteAgentKey)
|
||
r.Post("/admin/agent-keys/{id}/bind", handler.BindAgentKey)
|
||
|
||
// Agent 发信配额
|
||
r.Get("/admin/quotas", handler.AdminListQuotas)
|
||
r.Put("/admin/quotas/{name}", handler.AdminSetQuota)
|
||
})
|
||
})
|
||
|
||
// ---- SSE:Agent 走 header,人类走 Cookie,内部自行分流 ----
|
||
r.Get("/events/stream", handler.SSEStream)
|
||
r.Get("/events/status", handler.SSEStatus)
|
||
|
||
// ---- 附件下载:由浏览器直接发起(<a download>),无法带 Authorization 头,
|
||
// 因此单独挂在允许 ?access_token= 的中间件下 ----
|
||
r.Group(func(r chi.Router) {
|
||
r.Use(middleware.UserAuthAllowQueryToken)
|
||
r.Get("/me/attachments/{id}", handler.MeDownloadAttachment)
|
||
})
|
||
})
|
||
|
||
// 静态前端
|
||
staticRoot := os.Getenv("STATIC_DIR")
|
||
var staticMux http.Handler
|
||
if staticRoot != "" {
|
||
staticMux = http.FileServer(http.Dir(staticRoot))
|
||
} else {
|
||
staticMux = static.Handler()
|
||
}
|
||
r.Handle("/assets/*", staticMux)
|
||
r.Get("/", func(w http.ResponseWriter, r *http.Request) {
|
||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||
w.Write(static.GetIndex())
|
||
})
|
||
|
||
addr := fmt.Sprintf(":%s", cfg.Port)
|
||
srv := &http.Server{
|
||
Addr: addr,
|
||
Handler: r,
|
||
ReadTimeout: 15 * time.Second,
|
||
WriteTimeout: 0, // SSE 长连接
|
||
IdleTimeout: 120 * time.Second,
|
||
}
|
||
|
||
go func() {
|
||
sigCh := make(chan os.Signal, 1)
|
||
signal.Notify(sigCh, syscall.SIGINT, syscall.SIGTERM)
|
||
<-sigCh
|
||
fmt.Println("\nShutting down...")
|
||
c, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||
defer cancel()
|
||
srv.Shutdown(c)
|
||
}()
|
||
|
||
fmt.Printf("AgentMail Gateway on %s\n", addr)
|
||
fmt.Printf(" Health: http://localhost%s/health\n", addr)
|
||
fmt.Printf(" API: http://localhost%s/api/v1\n", addr)
|
||
|
||
if err := srv.ListenAndServe(); err != http.ErrServerClosed {
|
||
log.Fatalf("Server error: %v", err)
|
||
}
|
||
fmt.Println("Server stopped")
|
||
}
|
||
|
||
// bootstrapAdmin 首次启动时创建默认管理员
|
||
func bootstrapAdmin(ctx context.Context, cfg *config.Config) {
|
||
n, err := repo.CountAdmins(ctx)
|
||
if err != nil {
|
||
log.Fatalf("Failed to count admins: %v", err)
|
||
}
|
||
if n > 0 {
|
||
return
|
||
}
|
||
|
||
pw := cfg.AdminPassword
|
||
generated := false
|
||
if pw == "" {
|
||
pw = repo.RandomPassword(16)
|
||
generated = true
|
||
}
|
||
|
||
u, created, err := repo.EnsureAdminUser(ctx, cfg.AdminUser, pw)
|
||
if err != nil {
|
||
log.Fatalf("Failed to create admin user: %v", err)
|
||
}
|
||
if created && u != nil {
|
||
fmt.Println("========================================")
|
||
fmt.Printf(" 已创建默认管理员: %s\n", u.Username)
|
||
if generated {
|
||
fmt.Printf(" 初始密码(仅本次显示): %s\n", pw)
|
||
fmt.Println(" 请登录后立即通过 /auth/password 修改")
|
||
} else {
|
||
fmt.Println(" 密码来自环境变量 ADMIN_PASSWORD")
|
||
}
|
||
fmt.Println("========================================")
|
||
}
|
||
}
|
||
|
||
// sweepOrphanAttachments 周期清理「已上传但从未随邮件发出」的附件。
|
||
//
|
||
// 上传与发信是两步,中间放弃(用户取消写信、Agent 崩溃)就会留下孤立记录与文件。
|
||
// 保留 24 小时再清:足以覆盖一次正常的写信过程,也不至于让废弃文件长期占盘。
|
||
func sweepOrphanAttachments(blobs *blob.Store) {
|
||
const (
|
||
interval = 1 * time.Hour
|
||
keepFor = 24 * time.Hour
|
||
)
|
||
|
||
sweep := func() {
|
||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||
defer cancel()
|
||
|
||
sums, err := repo.SweepOrphanAttachments(ctx, keepFor)
|
||
if err != nil {
|
||
log.Printf("附件 GC 失败: %v", err)
|
||
return
|
||
}
|
||
for _, sum := range sums {
|
||
if err := blobs.Remove(sum); err != nil {
|
||
log.Printf("附件 GC 删除 %s 失败: %v", sum[:8], err)
|
||
}
|
||
}
|
||
if len(sums) > 0 {
|
||
log.Printf("附件 GC 清理了 %d 个孤立文件", len(sums))
|
||
}
|
||
}
|
||
|
||
// 启动时先扫一遍:上次进程可能是被 kill 掉的,留下的孤立文件不该等一小时
|
||
sweep()
|
||
for range time.Tick(interval) {
|
||
sweep()
|
||
}
|
||
}
|