## 配额重构:废除 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 把插件测试也纳入部署前门禁
388 lines
12 KiB
Go
388 lines
12 KiB
Go
package handler
|
||
|
||
import (
|
||
"errors"
|
||
"fmt"
|
||
"mime"
|
||
"net/http"
|
||
"path/filepath"
|
||
"strings"
|
||
"unicode/utf8"
|
||
|
||
"github.com/agentmail/gateway/internal/blob"
|
||
"github.com/agentmail/gateway/internal/config"
|
||
"github.com/agentmail/gateway/internal/middleware"
|
||
"github.com/agentmail/gateway/internal/models"
|
||
"github.com/agentmail/gateway/internal/repo"
|
||
"github.com/google/uuid"
|
||
)
|
||
|
||
// ---------- 附件 ----------
|
||
//
|
||
// 上传与发信是两步:
|
||
// 1. POST /attachments (multipart)→ 拿到 attachment_id
|
||
// 2. 发信时把 id 放进 attachment_ids
|
||
// 之所以不合成一步:Agent 侧的工具接口是 JSON,没法带 multipart;
|
||
// 而人类侧若只支持一步,就无法在写信过程中先传文件再改正文。
|
||
//
|
||
// 未挂载的附件是合法中间态,超时由 GC 清理(repo.SweepOrphanAttachments)。
|
||
|
||
// Blobs 是附件内容存储,由 main 在启动时注入。
|
||
var Blobs *blob.Store
|
||
|
||
// sanitizeFilename 清理用户提供的文件名。
|
||
//
|
||
// 文件名只用于展示与下载时的 Content-Disposition,磁盘路径完全由 sha256 派生,
|
||
// 因此这里的目的不是防路径穿越(那已由内容寻址杜绝),而是:
|
||
// - 去掉目录成分,避免下载时浏览器按 "a/b/c.txt" 解释
|
||
// - 去掉控制字符与换行,避免污染 HTTP 响应头
|
||
// - 限长,避免超出数据库列宽
|
||
func sanitizeFilename(name string) string {
|
||
name = strings.TrimSpace(name)
|
||
// 同时处理 / 与 \:上传方可能是 Windows 客户端
|
||
if i := strings.LastIndexAny(name, `/\`); i >= 0 {
|
||
name = name[i+1:]
|
||
}
|
||
|
||
var b strings.Builder
|
||
for _, r := range name {
|
||
if r < 0x20 || r == 0x7f {
|
||
continue // 控制字符一律丢弃
|
||
}
|
||
b.WriteRune(r)
|
||
}
|
||
name = strings.TrimSpace(b.String())
|
||
|
||
// "." 与 ".." 作为文件名毫无意义,且容易在各层被特殊解释
|
||
if name == "" || name == "." || name == ".." {
|
||
return "unnamed"
|
||
}
|
||
|
||
const maxBytes = 255
|
||
if len(name) > maxBytes {
|
||
cut := name[:maxBytes]
|
||
for len(cut) > 0 && !utf8.ValidString(cut) {
|
||
cut = cut[:len(cut)-1]
|
||
}
|
||
name = cut
|
||
}
|
||
return name
|
||
}
|
||
|
||
// detectContentType 优先用客户端声明的类型,缺失时按扩展名猜,兜底 octet-stream。
|
||
// 无论如何都不回显未经处理的客户端值到响应头(下载时统一用 octet-stream,见 DownloadAttachment)。
|
||
func detectContentType(declared, filename string) string {
|
||
if ct := strings.TrimSpace(declared); ct != "" && ct != "application/octet-stream" {
|
||
if parsed, _, err := mime.ParseMediaType(ct); err == nil {
|
||
return parsed
|
||
}
|
||
}
|
||
if ext := filepath.Ext(filename); ext != "" {
|
||
if byExt := mime.TypeByExtension(ext); byExt != "" {
|
||
if parsed, _, err := mime.ParseMediaType(byExt); err == nil {
|
||
return parsed
|
||
}
|
||
}
|
||
}
|
||
return "application/octet-stream"
|
||
}
|
||
|
||
// uploadAttachment 是 Agent 与人类两条上传路径的公共实现。
|
||
func uploadAttachment(w http.ResponseWriter, r *http.Request, uploader string) {
|
||
if Blobs == nil {
|
||
Error(w, http.StatusServiceUnavailable, "附件存储未初始化")
|
||
return
|
||
}
|
||
|
||
max := config.C.MaxAttachmentBytes
|
||
|
||
// 双层限制:MaxBytesReader 卡整个请求体(含 multipart 边界与其他字段),
|
||
// blob.Put 的 max 卡单个文件内容。少了外层,攻击者可以用超大 multipart 头拖死内存。
|
||
r.Body = http.MaxBytesReader(w, r.Body, max+1<<20)
|
||
|
||
// 32MB 内存缓冲上限,超出部分 multipart 会自动落临时文件
|
||
if err := r.ParseMultipartForm(32 << 20); err != nil {
|
||
Error(w, http.StatusBadRequest, "解析 multipart 失败(是否超过大小上限?)")
|
||
return
|
||
}
|
||
defer func() {
|
||
if r.MultipartForm != nil {
|
||
r.MultipartForm.RemoveAll()
|
||
}
|
||
}()
|
||
|
||
file, header, err := r.FormFile("file")
|
||
if err != nil {
|
||
Error(w, http.StatusBadRequest, "缺少 file 字段")
|
||
return
|
||
}
|
||
defer file.Close()
|
||
|
||
name := sanitizeFilename(header.Filename)
|
||
ctype := detectContentType(header.Header.Get("Content-Type"), name)
|
||
|
||
// 先落盘再入库:反过来会出现「库里有记录、磁盘没文件」的下载 500
|
||
sum, size, err := Blobs.Put(file, max)
|
||
if errors.Is(err, blob.ErrTooLarge) {
|
||
Error(w, http.StatusRequestEntityTooLarge,
|
||
fmt.Sprintf("附件超过上限 %.1f MB", float64(max)/(1<<20)))
|
||
return
|
||
}
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "保存附件失败")
|
||
return
|
||
}
|
||
|
||
a, err := repo.CreateAttachment(r.Context(), uploader, name, ctype, size, sum)
|
||
if err != nil {
|
||
// 落盘成功但入库失败:留下的孤立文件由 GC 回收,不影响正确性
|
||
Error(w, http.StatusInternalServerError, "登记附件失败")
|
||
return
|
||
}
|
||
|
||
JSON(w, http.StatusOK, map[string]any{"attachment": a})
|
||
}
|
||
|
||
// POST /api/v1/attachments —— Agent 侧上传
|
||
func UploadAttachment(w http.ResponseWriter, r *http.Request) {
|
||
agentName := middleware.GetAgentName(r)
|
||
if agentName == "" {
|
||
Error(w, http.StatusUnauthorized, "Unauthorized")
|
||
return
|
||
}
|
||
uploadAttachment(w, r, agentName)
|
||
}
|
||
|
||
// POST /api/v1/me/attachments —— 人类侧上传
|
||
func MeUploadAttachment(w http.ResponseWriter, r *http.Request) {
|
||
user := middleware.GetUser(r)
|
||
if user == nil {
|
||
Error(w, http.StatusUnauthorized, "not authenticated")
|
||
return
|
||
}
|
||
uploadAttachment(w, r, user.Username)
|
||
}
|
||
|
||
// downloadAttachment 是 Agent 与人类两条下载路径的公共实现。
|
||
func downloadAttachment(w http.ResponseWriter, r *http.Request, viewer string) {
|
||
if Blobs == nil {
|
||
Error(w, http.StatusServiceUnavailable, "附件存储未初始化")
|
||
return
|
||
}
|
||
id, ok := pathUUID(w, r, "id")
|
||
if !ok {
|
||
return
|
||
}
|
||
|
||
a, err := repo.GetAttachment(r.Context(), id)
|
||
if errors.Is(err, repo.ErrAttachmentNotFound) {
|
||
Error(w, http.StatusNotFound, "附件不存在")
|
||
return
|
||
}
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "读取附件失败")
|
||
return
|
||
}
|
||
|
||
allowed, err := repo.AttachmentAccessible(r.Context(), a, viewer)
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "校验权限失败")
|
||
return
|
||
}
|
||
if !allowed {
|
||
Error(w, http.StatusForbidden, "无权访问该附件")
|
||
return
|
||
}
|
||
|
||
f, err := Blobs.Open(a.SHA256)
|
||
if err != nil {
|
||
// 元数据在库但文件不在盘:说明存储被外部改动过,这是运维问题而非用户输入问题
|
||
Error(w, http.StatusInternalServerError, "附件内容缺失")
|
||
return
|
||
}
|
||
defer f.Close()
|
||
|
||
// 一律 octet-stream + attachment:绝不按声明的 MIME 内联渲染。
|
||
// 否则一个上传的 .html/.svg 就能在本站域下执行脚本,等于自带 XSS。
|
||
w.Header().Set("Content-Type", "application/octet-stream")
|
||
w.Header().Set("X-Content-Type-Options", "nosniff")
|
||
w.Header().Set("Content-Length", fmt.Sprintf("%d", a.SizeBytes))
|
||
w.Header().Set("Content-Disposition", contentDisposition(a.Filename))
|
||
|
||
http.ServeContent(w, r, a.Filename, a.CreatedAt, f)
|
||
}
|
||
|
||
// contentDisposition 构造下载头。
|
||
// filename* 用 RFC 5987 编码承载非 ASCII 名字,filename= 给只认 ASCII 的老客户端兜底;
|
||
// 兜底值里的引号与反斜杠必须去掉,否则能截断响应头。
|
||
func contentDisposition(name string) string {
|
||
var ascii strings.Builder
|
||
for _, r := range name {
|
||
switch {
|
||
case r == '"' || r == '\\':
|
||
ascii.WriteByte('_')
|
||
case r < 0x20 || r > 0x7e:
|
||
ascii.WriteByte('_')
|
||
default:
|
||
ascii.WriteRune(r)
|
||
}
|
||
}
|
||
fallback := ascii.String()
|
||
if fallback == "" {
|
||
fallback = "attachment"
|
||
}
|
||
return fmt.Sprintf(`attachment; filename="%s"; filename*=UTF-8''%s`,
|
||
fallback, urlEncodeRFC5987(name))
|
||
}
|
||
|
||
// urlEncodeRFC5987 按 RFC 5987 的 attr-char 集合做百分号编码。
|
||
func urlEncodeRFC5987(s string) string {
|
||
const safe = "!#$&+-.^_`|~" // attr-char 中除字母数字外允许的字符
|
||
var b strings.Builder
|
||
for i := 0; i < len(s); i++ {
|
||
c := s[i]
|
||
isAlnum := (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')
|
||
if isAlnum || strings.IndexByte(safe, c) >= 0 {
|
||
b.WriteByte(c)
|
||
} else {
|
||
fmt.Fprintf(&b, "%%%02X", c)
|
||
}
|
||
}
|
||
return b.String()
|
||
}
|
||
|
||
// GET /api/v1/attachments/{id} —— Agent 侧下载
|
||
func DownloadAttachment(w http.ResponseWriter, r *http.Request) {
|
||
agentName := middleware.GetAgentName(r)
|
||
if agentName == "" {
|
||
Error(w, http.StatusUnauthorized, "Unauthorized")
|
||
return
|
||
}
|
||
downloadAttachment(w, r, agentName)
|
||
}
|
||
|
||
// GET /api/v1/me/attachments/{id} —— 人类侧下载
|
||
func MeDownloadAttachment(w http.ResponseWriter, r *http.Request) {
|
||
user := middleware.GetUser(r)
|
||
if user == nil {
|
||
Error(w, http.StatusUnauthorized, "not authenticated")
|
||
return
|
||
}
|
||
downloadAttachment(w, r, user.Username)
|
||
}
|
||
|
||
// DELETE /api/v1/me/attachments/{id} —— 删除自己上传且尚未挂载的附件
|
||
//
|
||
// 已挂载的不允许删:邮件是不可篡改的历史记录,附件是它的一部分。
|
||
func MeDeleteAttachment(w http.ResponseWriter, r *http.Request) {
|
||
user := middleware.GetUser(r)
|
||
if user == nil {
|
||
Error(w, http.StatusUnauthorized, "not authenticated")
|
||
return
|
||
}
|
||
id, ok := pathUUID(w, r, "id")
|
||
if !ok {
|
||
return
|
||
}
|
||
|
||
a, err := repo.GetAttachment(r.Context(), id)
|
||
if errors.Is(err, repo.ErrAttachmentNotFound) {
|
||
Error(w, http.StatusNotFound, "附件不存在")
|
||
return
|
||
}
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "读取附件失败")
|
||
return
|
||
}
|
||
if a.Uploader != user.Username {
|
||
Error(w, http.StatusForbidden, "只能删除自己上传的附件")
|
||
return
|
||
}
|
||
if a.MailID != nil {
|
||
Error(w, http.StatusConflict, "附件已随邮件发出,不能删除")
|
||
return
|
||
}
|
||
|
||
sum, orphaned, err := repo.DeleteAttachment(r.Context(), id)
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "删除附件失败")
|
||
return
|
||
}
|
||
// 内容寻址下多条记录可能共享同一文件,只有最后一条引用消失才删磁盘
|
||
if orphaned && Blobs != nil {
|
||
_ = Blobs.Remove(sum)
|
||
}
|
||
JSON(w, http.StatusOK, map[string]string{"status": "deleted"})
|
||
}
|
||
|
||
// parseAttachmentIDs 把请求里的附件 id 列表解析为 UUID。
|
||
func parseAttachmentIDs(raw []string) ([]uuid.UUID, error) {
|
||
out := make([]uuid.UUID, 0, len(raw))
|
||
for _, s := range raw {
|
||
s = strings.TrimSpace(s)
|
||
if s == "" {
|
||
continue
|
||
}
|
||
id, err := uuid.Parse(s)
|
||
if err != nil {
|
||
return nil, fmt.Errorf("非法的 attachment_id %q", s)
|
||
}
|
||
out = append(out, id)
|
||
}
|
||
return out, nil
|
||
}
|
||
|
||
// attachAll 把附件挂到刚创建的邮件上,并把错误翻译成 HTTP 响应。
|
||
// 返回 false 表示已写出错误响应,调用方应立即返回。
|
||
func attachAll(w http.ResponseWriter, r *http.Request, mailID uuid.UUID, ids []uuid.UUID, uploader string) bool {
|
||
if len(ids) == 0 {
|
||
return true
|
||
}
|
||
err := repo.AttachToMail(r.Context(), mailID, ids, uploader)
|
||
switch {
|
||
case err == nil:
|
||
return true
|
||
case errors.Is(err, repo.ErrAttachmentNotFound):
|
||
Error(w, http.StatusNotFound, "附件不存在")
|
||
case errors.Is(err, repo.ErrAttachmentNotOwned):
|
||
Error(w, http.StatusForbidden, "只能附加自己上传的附件")
|
||
case errors.Is(err, repo.ErrAttachmentAlreadyAttached):
|
||
Error(w, http.StatusConflict, "附件已随其他邮件发出")
|
||
default:
|
||
Error(w, http.StatusInternalServerError, "附加附件失败")
|
||
}
|
||
return false
|
||
}
|
||
|
||
// fillAttachments 给邮件填充附件列表(读取单封/线程时用)。
|
||
// 读附件失败不该让整封邮件打不开,因此吞错只留空列表。
|
||
//
|
||
// 一批邮件走一次查询:逐封调 ListAttachmentsFor 是 N+1,
|
||
// 一个 200 封的会话打开一次要打 200 次库。
|
||
func fillAttachments(r *http.Request, mails ...*models.Mail) {
|
||
ids := make([]uuid.UUID, 0, len(mails))
|
||
for _, m := range mails {
|
||
if m != nil {
|
||
ids = append(ids, m.ID)
|
||
}
|
||
}
|
||
if len(ids) == 0 {
|
||
return
|
||
}
|
||
|
||
byMail, err := repo.ListAttachmentsForMails(r.Context(), ids)
|
||
if err != nil {
|
||
return
|
||
}
|
||
for _, m := range mails {
|
||
if m == nil {
|
||
continue
|
||
}
|
||
// 没有附件的邮件保持 nil:Attachments 带 omitempty,
|
||
// 填空切片只会给每封邮件的 JSON 加一个 "attachments":[]
|
||
if as := byMail[m.ID]; len(as) > 0 {
|
||
m.Attachments = as
|
||
}
|
||
}
|
||
}
|