## 别名替换(让 .new 邮件可寻址)
repo/autoalias.go: AutoAliasFor + EnsureSessionAlias
- .new 建完会话立刻给别名(形如 dsh-重构导入路径)
- 名字与主题都要:只用主题跨 Agent 撞名,只用名字看不出聊什么
- sanitizeAliasPart 只留 unicode.IsLetter/IsDigit,其余折 -
- 撞名追加 -2/-3,全占用退 session-<uuid前8位>
- 不复用 SyncSessionAlias:那个假定已存在且跳过 manual
- 条件写入 WHERE alias IS NULL OR '',并发安全
- resolveTarget 的 .new 与默认会话两条路径都调
notifyRecipients 加三个字段(每个收件方拿到自己那个地址的版本):
- session_alias / reply_address / self_address
- 别名为空时退回省略 session 位,绝不写 new
FormatAddress(name,path,session) 空 path 也必须留 @ 与 .
## Agent 侧寻址发现(五个只读端点)
handler/agent_discovery.go:
- /agent/contacts + /agent/contacts/suggest(三段式补全)
- /agent/mail/{id} + /agent/mail/{id}/thread
- /agent/sessions/{id}/participants
- 不复用人类路由:scope 不同、审计需求不同
- 一律只读:归档/改名/权限决策仍只有人能做
repo/participants.go: SessionParticipants 逐封扫 from/to/cc
- Roles 用集合、MailCount 只数发信(0=还没开口的人)
- 发件人 path 不取 from_workspace(那列存的是 Agent 名)
repo.SuggestPaths 重写:mails.to_workspace(按 MAX(created_at) 倒序)
+ agents.workspaces 并集。原只读 workspaces,官方插件传 [] 永远空
## 共用模块(三插件逐字节相同)
lib/addressing.js: formatAddress/roleOf/replyAddressFor/selfAddressFor/participantsOfMail
lib/discovery.js: renderNameSuggestions/renderPathSuggestions/renderSessionSuggestions/
renderParticipants/renderContacts/renderThread
lib/inbox-format.js: renderMail 新增收件人/身份/可投递地址三段
- selfName 参数(兼容旧调用不传的情况)
check-shared-libs.sh 纳入 addressing + discovery
## 插件侧
opencode: suggest_address + list_contacts + session_participants + read_thread + read_mail
dsh: 同上 + forward_mail(此前只有 opencode 有)+ upload_attachment 改真 multipart
pi: 同上(createMailTools 加 agentName 参数)
dsh: ctx.agents.create id collision 改为 readSession 探测后 resume
dsh: 关键路径日志改 console.error(ctx.logger 不进 journalctl)
## 测试
repo: autoalias_test.go 11 + participants_test.go 7 = 18 例
plugins: addressing.test 17 + discovery.test 23 + inbox-format.test 31 = 71 例
go test ./... + npm test(opencode 155 + dsh 173 + pi 199)全绿
端到端验证:admin 发 dsh@....new 抄送 opencode@....new
→ dsh 用 session_participants 取到地址 → send_mail 给 opencode
→ 地址取自工具返回值(.crisp-planet),未手工拼写
213 lines
7.3 KiB
Go
213 lines
7.3 KiB
Go
package handler
|
||
|
||
import (
|
||
"net/http"
|
||
"strconv"
|
||
|
||
"github.com/agentmail/gateway/internal/middleware"
|
||
"github.com/agentmail/gateway/internal/repo"
|
||
"github.com/google/uuid"
|
||
)
|
||
|
||
// ---------- 对话树(从线索根整树展开,分块加载) ----------
|
||
|
||
// 分页参数。上限存在的意义是防止 ?limit=100000 一次把整条线索拉走 ——
|
||
// 那就等于绕过了分块加载。
|
||
const (
|
||
threadDefaultLimit = 60
|
||
threadMaxLimit = 200
|
||
// anchorPathBudget 是「补齐根到锚点这条路径」时最多回填的层数。
|
||
// 只在锚点没落进 BFS 首页时才用得上(几百封的巨型线索)。
|
||
anchorPathBudget = 60
|
||
)
|
||
|
||
// threadNode 是返回给前端的树节点。
|
||
//
|
||
// Detached 表示「这封的父邮件当前不在返回集里」,两种原因:
|
||
// - 父邮件不可见(转发把线索引到别处,下游往来不回流给上游参与者)
|
||
// - 父邮件还没加载(分块加载的边界,往下翻会补上)
|
||
//
|
||
// 前端据此画出断点,而不是因为找不到父节点就把它悄悄丢掉。
|
||
// 两种原因用 ParentHidden 区分:不可见是永久的,未加载是暂时的。
|
||
type threadNode struct {
|
||
repo.TreeMail
|
||
Detached bool `json:"detached,omitempty"`
|
||
// ParentHidden 为真表示父邮件确实存在但无权查看(不是尚未加载)
|
||
ParentHidden bool `json:"parent_hidden,omitempty"`
|
||
}
|
||
|
||
// GET /api/v1/mail/{id}/thread
|
||
//
|
||
// 以给定邮件所在**线索的根**为起点,BFS 展开整棵树:
|
||
//
|
||
// ?offset=0(默认) 从根开始的第一块
|
||
// ?offset=N 继续往后取(下滑加载)
|
||
//
|
||
// 曾经的实现是「锚点的祖先链 + 锚点的子树」两个方向各自分页,问题是
|
||
// **兄弟节点整条分支都在盲区里**:一封抄送给两个 Agent 的邮件会收到两个回复,
|
||
// 它们互为兄弟;从其中一个回复看树,另一个回复既不是它的祖先也不是它的子孙,
|
||
// 于是永远不显示。挂在原件上的转发分支同理。改成从根整树 BFS 后,
|
||
// 兄弟、抄送产生的平行回复、转发分支都是根的子孙,一次覆盖。
|
||
//
|
||
// 树可跨会话(转发是新线索但仍指向原件),因此**逐个会话鉴权**,
|
||
// 只返回当前用户有权访问的节点。被过滤掉的计入 hidden。
|
||
func GetMailThread(w http.ResponseWriter, r *http.Request) {
|
||
user := middleware.GetUser(r)
|
||
if user == nil {
|
||
Error(w, http.StatusUnauthorized, "not authenticated")
|
||
return
|
||
}
|
||
serveMailThread(w, r, func(sid uuid.UUID) (bool, error) {
|
||
return repo.UserCanAccessSession(r.Context(), user, sid)
|
||
})
|
||
}
|
||
|
||
// serveMailThread 是人类与 Agent 两条对话树路径的公共实现。
|
||
//
|
||
// 差别只在**会话可见性判据**:人类走 UserCanAccessSession(管理员全可见、
|
||
// 其余看参与过的会话),Agent 走 AgentCanAccessSession(只看自己参与过的)。
|
||
// 其余全部逻辑——上溯线索根、BFS 分页、锚点路径回填、detached 标记——两侧必须
|
||
// 完全一致:让 Agent 看到一棵与人类不同形状的树,只会让双方对「谁回了谁」
|
||
// 产生分歧,而这正是抄送协作要靠对话树解决的问题。
|
||
func serveMailThread(w http.ResponseWriter, r *http.Request, canAccess func(uuid.UUID) (bool, error)) {
|
||
mailID, ok := pathUUID(w, r, "id")
|
||
if !ok {
|
||
return
|
||
}
|
||
|
||
// 先确认调用者确实看得到作为锚点的这封邮件,否则等于给了一个
|
||
// 「随便报 mail_id 就能探测线索存在性」的接口
|
||
mail, err := repo.GetMailByID(r.Context(), mailID)
|
||
if err != nil {
|
||
Error(w, http.StatusNotFound, "Mail not found")
|
||
return
|
||
}
|
||
allowed, err := canAccess(mail.SessionID)
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "Failed to check permission")
|
||
return
|
||
}
|
||
if !allowed {
|
||
Error(w, http.StatusForbidden, "无权访问该邮件")
|
||
return
|
||
}
|
||
|
||
limit := intQuery(r, "limit", threadDefaultLimit, 1, threadMaxLimit)
|
||
offset := intQuery(r, "offset", 0, 0, 1<<20)
|
||
|
||
// 上溯到线索根:整棵树都是它的子孙。
|
||
rootID, anchorDepth, err := repo.ThreadRootOf(r.Context(), mailID)
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "Failed to locate thread root")
|
||
return
|
||
}
|
||
|
||
raw, hasMore, err := repo.DescendantsRaw(r.Context(), rootID, offset, limit)
|
||
if err != nil {
|
||
Error(w, http.StatusInternalServerError, "Failed to load thread")
|
||
return
|
||
}
|
||
|
||
// 锚点必须可见 —— 用户点开的就是它。巨型线索里 BFS 首页可能还没到锚点那一层,
|
||
// 此时单独把「根 → 锚点」这条路径补进来,否则用户点开一封邮件却在树里找不到它。
|
||
if offset == 0 && anchorDepth > 0 && !containsMail(raw, mailID) {
|
||
path, _, pErr := repo.AncestorsRaw(r.Context(), mailID, 0, anchorPathBudget)
|
||
if pErr == nil {
|
||
// AncestorsRaw 给的是相对锚点的负 depth,换算成距根的绝对深度
|
||
for i := range path {
|
||
path[i].Depth += anchorDepth
|
||
}
|
||
raw = append(raw, path...)
|
||
}
|
||
// 锚点自己(AncestorsRaw 从父开始,不含锚点)
|
||
if anchor, aErr := repo.TreeMailByID(r.Context(), mailID, anchorDepth); aErr == nil {
|
||
raw = append(raw, *anchor)
|
||
}
|
||
}
|
||
|
||
// 会话鉴权结果按会话缓存:一条线索里同一会话通常有多封,逐封查是浪费
|
||
seen := map[uuid.UUID]bool{}
|
||
canSee := func(sid uuid.UUID) bool {
|
||
if v, ok := seen[sid]; ok {
|
||
return v
|
||
}
|
||
v, err := canAccess(sid)
|
||
if err != nil {
|
||
v = false // 查不出来就当看不到:宁可少给,不可多给
|
||
}
|
||
seen[sid] = v
|
||
return v
|
||
}
|
||
|
||
// 可见性过滤。父节点是否在**本次返回集**里决定 detached;
|
||
// 父存在却不在集里,再判断是「无权看」还是「没加载」。
|
||
visible := map[uuid.UUID]bool{}
|
||
present := map[uuid.UUID]bool{}
|
||
for _, m := range raw {
|
||
present[m.ID] = true
|
||
if canSee(m.SessionID) {
|
||
visible[m.ID] = true
|
||
}
|
||
}
|
||
|
||
nodes := []threadNode{}
|
||
emitted := map[uuid.UUID]bool{}
|
||
for _, m := range raw {
|
||
if !visible[m.ID] || emitted[m.ID] {
|
||
// 补齐锚点路径时可能与 BFS 结果重叠,去重
|
||
continue
|
||
}
|
||
emitted[m.ID] = true
|
||
n := threadNode{TreeMail: m}
|
||
if m.ParentMailID != nil && !visible[*m.ParentMailID] {
|
||
n.Detached = true
|
||
// 父邮件在本次结果里出现过但被过滤掉 = 确实无权查看;
|
||
// 完全没出现过 = 只是还没加载到,往下翻会补上
|
||
n.ParentHidden = present[*m.ParentMailID]
|
||
}
|
||
nodes = append(nodes, n)
|
||
}
|
||
|
||
JSON(w, http.StatusOK, map[string]interface{}{
|
||
"anchor_mail_id": mailID,
|
||
"root_mail_id": rootID,
|
||
"anchor_depth": anchorDepth,
|
||
"nodes": nodes,
|
||
"total": len(nodes),
|
||
"hidden": len(raw) - len(nodes),
|
||
"has_more": hasMore,
|
||
// 下一页的 offset。前端把它原样回传即可,不必自己算已加载数量。
|
||
"next_offset": offset + limit,
|
||
})
|
||
}
|
||
|
||
// containsMail 判断某封邮件是否已在结果集里。
|
||
func containsMail(list []repo.TreeMail, id uuid.UUID) bool {
|
||
for i := range list {
|
||
if list[i].ID == id {
|
||
return true
|
||
}
|
||
}
|
||
return false
|
||
}
|
||
|
||
// intQuery 读取整数 query 参数并夹到 [min, max]。
|
||
// 非法值一律回落到默认值 —— 分页参数不该因为一个笔误就让整个请求失败。
|
||
func intQuery(r *http.Request, key string, def, min, max int) int {
|
||
s := r.URL.Query().Get(key)
|
||
if s == "" {
|
||
return def
|
||
}
|
||
v, err := strconv.Atoi(s)
|
||
if err != nil {
|
||
return def
|
||
}
|
||
if v < min {
|
||
return min
|
||
}
|
||
if v > max {
|
||
return max
|
||
}
|
||
return v
|
||
}
|