四个各自独立的生产缺陷,共同的根源都是「本该属于会话的属性没有存在会话上」。 ## 1. dsh 指定工作目录完全失效(所有会话落进「未分组」) 插件建会话时用的 cwd 是自己拼的 `~/.dsh/mail-sessions/mail-<uuid>` —— 每封邮件一个全新的空目录。DSH 与 opencode 都按 cwd 给会话分组,于是所有 邮件会话既不属于任何项目、彼此也不同组。 而 Gateway 从来没把地址里的 path 位发给插件:`notifyRecipients` 的 payload 只有 mail_id/session_id/from_name/subject,`to_workspace` 虽然入库了却不在 SSE 事件里,插件即使想用也拿不到。 - SSE `new_mail` 事件加 `to_workspace`。**每个收件方拿到自己那个地址的 path**, 不是主收件人的 —— 抄送给 opencode@/a 与主发给 dsh@/b 是两个工作区 - 两个插件的 cwd 都改为取寻址的 path 位;不存在的目录**不创建**而是回退到 兜底目录(一个笔误不该在磁盘上落下真目录,Agent 会在里面一无所获地干活) - 拒绝相对路径:cwd 的相对基准是 harness 进程的启动目录,systemd 下通常是 `/` ## 2. 会话别名列不出工作区下的历史会话(无法选择) workspace 只存在于 `mails.to_workspace` 上,「这个工作区下有哪些会话」必须 JOIN mails 再从收发双方的 workspace 里猜。而 Agent 回信时 from_workspace 填的是 **Agent 名**而不是路径,旧条件 `to_workspace = $p OR from_workspace = $p` 在只剩 Agent 回信可匹配时两边都对不上。 - `sessions.workspace` 新列,`CreateSession` 从地址的 path 位带入 - `SuggestSessionCandidates` 取代 `SuggestSessionsFor`:以会话自己的 workspace 为权威,历史会话(该列为空)回退到 mails 反推 —— 升级后老会话不该消失 - `FindOrCreateDefaultSession` 同步改用会话的 workspace ## 3. 平台侧会话在补全里根本不存在 人直接在 opencode/DSH 界面上开的会话,Gateway 一无所知。 新增 `agent_platform_sessions` 镜像表,插件在心跳里上报快照。 **上报而非 Gateway 反向拉取**:当前架构是单向的(Agent 持密钥主动连 Gateway, Gateway 从不外呼),反向拉取需要它保存各平台的地址与凭证,那是另一套信任模型。 - 与 sessions 表分开存:镜像里是别人家的会话,id 属于平台的 id 空间,没有 本侧的 owner/预算/邮件。混进 sessions 会让每一处「按会话鉴权」都要先判断 这条到底是不是真的本侧会话 - **整表替换而非增量合并**:平台侧删掉的会话必须从候选里消失 —— session 位是 三态语义,指向不存在的会话直接 404 - **nil 与空数组语义不同**:插件拉不到列表时省略该字段(保留镜像), 而不是传空数组把镜像抹掉 - **subagent 子会话不上报**:实测 DSH 的 list 里混着 49 条子会话,标题就是 派活的提示词前缀(九条都叫 "You are auditing ONE file"),slug 全撞名; 它们是父 agent 内部的工作单元,人往里发邮件毫无意义 - **slug 撞名只留最近那条**:服务端只能取其中一条,上报同名项只会让补全里 出现几个点哪个都不确定的候选 - DSH 插件此前**完全没有心跳** —— Gateway 靠 last_seen 判在线,一直靠注册撑着 补全候选带标题与来源:`suggestions` 保留纯字符串数组(不打破已部署的前端与 第三方客户端),新增同序的 `candidates`。过滤时标题也参与匹配 —— 人记得的是 「缓存选型」而不是 brisk-harbor 这种随机短名。 ## 4. 对话树看不见抄送与转发产生的分支 旧实现从锚点分「祖先链 + 子树」两路展开,而**兄弟节点既不是锚点的祖先也不是 它的子孙**:一封抄送给两个 Agent 的邮件收到两个回复,从其中一个看树永远看不到 另一个;挂在原件上的转发分支同理。 改为先 `ThreadRootOf` 上溯到线索根,再从根整树 BFS。只剩一个加载方向, 因此不再需要滚动位置补偿。前端补上抄送人列表与转发标记 —— 树上两个兄弟节点 为什么并列,唯一的解释就是父邮件抄送给了两个人。 ## 5. DSH 插件(Phase 7.7) 卡了一下午的 `Cannot read properties of undefined (reading 'kind')` 根因是 `followup()` 的参数形状:DSH 要完整的 UserMessage(content + source), 而我照抄了 opencode 的 parts 数组。错误抛在 agent-loop 内部,不指向调用点。 - `agent/status` → idle 时自动转发最后一条 assistant 消息(对应 opencode 的 session.idle),复用 relay-dedup 让位于模型的主动回信,走免配额通道 - `approval/request` 权限询问转邮件问人。与 opencode 的差异:那边的 permission.ask 是同步钩子只能立即返回 ask,DSH 这边是异步 waterfall, 可以真的等人 —— 拆插件时未决询问一律 fail closed,否则 await 永不返回 - 会话别名由模型标题派生(保留中文,去掉 `.` `@` `/` 等寻址分隔符 —— 留在别名里会让它自己被解析器切开) - 逻辑放 lib/ 下的纯函数并加测试:三类约定都是「错了不当场报错、只在深处 炸一个无关错误」 ## 其他 - `deploy/reset-demo.sh`:清空演示邮件数据,保留账号与密钥。备份用 `.backup` 而非 cp(WAL 下 cp 拿到的是缺尾巴的库);手工按依赖顺序删(SQLite 的 foreign_keys 默认关,声明了 REFERENCES 也不级联);只在目标是默认库时才碰 systemd(演练时误停过一次生产服务) - 插件 dist/ 不进版本库,install.sh 负责构建 - `permission_decision` 事件补 session_id:插件重启丢了待决映射时要靠它定位会话
200 lines
6.6 KiB
Go
200 lines
6.6 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
|
||
}
|
||
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 := repo.UserCanAccessSession(r.Context(), user, 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 := repo.UserCanAccessSession(r.Context(), user, 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
|
||
}
|