Files
MailUI4Agents/plugins/dsh-mail-bridge/test/session-snapshot.test.mjs
JianFeeeee ca64d12057 feat: 工作区归属修复 + 平台会话同步 + 对话树整树展开 + DSH 插件
四个各自独立的生产缺陷,共同的根源都是「本该属于会话的属性没有存在会话上」。

## 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:插件重启丢了待决映射时要靠它定位会话
2026-09-02 20:05:51 +08:00

229 lines
8.2 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 平台会话快照的纯函数测试。
*
* 这些函数的产出直接决定「写信时能不能选到某条会话」slug 错了就填出一个
* 送不到的 session 位(三态语义下会 404workspace 错了就归到别的工作区去。
*
* node --test test/
*/
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
snapshotOpencodeSessions,
snapshotDshSessions,
slugFromTitle,
MAX_REPORTED,
} from '../lib/session-snapshot.js';
// ─── opencode ───
const ocSession = (over = {}) => ({
id: 'ses_abc',
slug: 'witty-planet',
title: '重构导入路径',
directory: '/home/program/agentmail',
path: '',
time: { created: 1788300000000, updated: 1788344476744 },
...over,
});
test('opencode 快照取 directory 作为 workspace', () => {
const [got] = snapshotOpencodeSessions([ocSession()]);
assert.equal(got.workspace, '/home/program/agentmail');
});
test('不变量workspace 取 directory 而不是 path', () => {
// opencode 的 path 是项目内的子路径通常是空串cwd 在 directory 上。
// 取错的后果是所有会话的 workspace 都变成空串,一条都匹配不上。
const [got] = snapshotOpencodeSessions([
ocSession({ directory: '/home/real/cwd', path: 'src/sub' }),
]);
assert.equal(got.workspace, '/home/real/cwd');
});
test('opencode 快照带出 slug 与标题', () => {
const [got] = snapshotOpencodeSessions([ocSession()]);
assert.equal(got.slug, 'witty-planet');
assert.equal(got.title, '重构导入路径');
assert.equal(got.platform_id, 'ses_abc');
});
test('不变量:无 slug 的会话不上报', () => {
// slug 是填进 session 位的值。没有它,这一项在补全里点下去
// 只能得到 `name@path.` —— 一个空的 session 段。
const got = snapshotOpencodeSessions([
ocSession({ id: 'a', slug: '' }),
ocSession({ id: 'b', slug: undefined }),
ocSession({ id: 'c', slug: 'good-name' }),
]);
assert.equal(got.length, 1);
assert.equal(got[0].slug, 'good-name');
});
test('无 id 的条目被跳过', () => {
const got = snapshotOpencodeSessions([ocSession({ id: '' }), ocSession({ id: undefined })]);
assert.equal(got.length, 0);
});
test('mail_driven 由回调判定', () => {
const got = snapshotOpencodeSessions(
[ocSession({ id: 'driven' }), ocSession({ id: 'manual' })],
id => id === 'driven'
);
assert.equal(got.find(s => s.platform_id === 'driven').mail_driven, true);
assert.equal(got.find(s => s.platform_id === 'manual').mail_driven, false);
});
test('updated_at 由毫秒时间戳转 ISO', () => {
const [got] = snapshotOpencodeSessions([ocSession()]);
assert.equal(got.updated_at, new Date(1788344476744).toISOString());
});
test('没有 updated 时退回 created', () => {
const [got] = snapshotOpencodeSessions([
ocSession({ time: { created: 1788300000000 } }),
]);
assert.equal(got.updated_at, new Date(1788300000000).toISOString());
});
test('时间完全缺失时 updated_at 为 undefined 而不是崩', () => {
const [got] = snapshotOpencodeSessions([ocSession({ time: undefined })]);
assert.equal(got.updated_at, undefined);
});
test('按最近活跃降序排列', () => {
const got = snapshotOpencodeSessions([
ocSession({ id: 'old', slug: 'old', time: { updated: 1000 } }),
ocSession({ id: 'new', slug: 'new', time: { updated: 9000 } }),
ocSession({ id: 'mid', slug: 'mid', time: { updated: 5000 } }),
]);
assert.deepEqual(got.map(s => s.platform_id), ['new', 'mid', 'old']);
});
test('截断到 MAX_REPORTED', () => {
const many = Array.from({ length: MAX_REPORTED + 50 }, (_, i) =>
ocSession({ id: `s${i}`, slug: `slug-${i}`, time: { updated: i } })
);
assert.equal(snapshotOpencodeSessions(many).length, MAX_REPORTED);
});
test('非数组输入不崩', () => {
assert.deepEqual(snapshotOpencodeSessions(undefined), []);
assert.deepEqual(snapshotOpencodeSessions(null), []);
assert.deepEqual(snapshotOpencodeSessions({}), []);
});
// ─── DSH ───
test('DSH 快照从标题派生 slug', () => {
const [got] = snapshotDshSessions([
{ id: 'mail-1', cwd: '/home/x', title: '缓存层选型评估', updatedAt: 1788344476744 },
]);
assert.equal(got.slug, '缓存层选型评估');
assert.equal(got.title, '缓存层选型评估');
assert.equal(got.workspace, '/home/x');
});
test('DSH 无标题时不上报(派生不出别名)', () => {
const got = snapshotDshSessions([
{ id: 'a', cwd: '/home/x', title: '' },
{ id: 'b', cwd: '/home/x' },
]);
assert.equal(got.length, 0);
});
// ─── slugFromTitle ───
test('slugFromTitle 空白转连字符', () => {
assert.equal(slugFromTitle('处理新邮件 任务'), '处理新邮件-任务');
assert.equal(slugFromTitle('a b c'), 'a-b-c');
});
test('不变量slug 不含寻址分隔符', () => {
// `.` 是 session 位的分隔符、`@` 是 path 位的分隔符。留在 slug 里
// 会让别名自己被解析器切开 —— 填进去的地址会指向一个完全不同的目标。
const slug = slugFromTitle('修 a.b@c/d 的问题');
for (const ch of ['.', '@', '/', '\\', ':']) {
assert.ok(!slug.includes(ch), `slug 里不该有 ${ch}${slug}`);
}
});
test('slugFromTitle 压缩连续连字符', () => {
assert.equal(slugFromTitle('a...b'), 'ab');
assert.equal(slugFromTitle('a - b'), 'a-b');
});
test('slugFromTitle 去掉首尾连字符', () => {
assert.equal(slugFromTitle(' 中间 '), '中间');
assert.equal(slugFromTitle('--x--'), 'x');
});
test('slugFromTitle 截断到 48 字符且不留尾部连字符', () => {
const long = 'a'.repeat(60);
assert.equal(slugFromTitle(long).length, 48);
// 第 48 个字符正好落在空格上时,截断后不该留下尾部 -
const tricky = `${'b'.repeat(47)} tail`;
const slug = slugFromTitle(tricky);
assert.ok(!slug.endsWith('-'), `尾部残留连字符:${slug}`);
});
test('slugFromTitle 保留中文', () => {
// 不转拼音huancunceng-xuanxing 既不好读也不好打,
// 而三维地址按最后一个 . 切分,中文不影响解析。
assert.equal(slugFromTitle('缓存选型'), '缓存选型');
});
test('slugFromTitle 纯符号标题返回空串', () => {
assert.equal(slugFromTitle('...'), '');
assert.equal(slugFromTitle('@@@'), '');
assert.equal(slugFromTitle(' '), '');
});
test('slugFromTitle 容错非字符串', () => {
assert.equal(slugFromTitle(undefined), '');
assert.equal(slugFromTitle(null), '');
assert.equal(slugFromTitle(42), '42');
});
// ─── DSHsubagent 过滤与 slug 去重 ───
test('不变量subagent 子会话不上报origin 判据)', () => {
// 它们是父 agent 内部的工作单元,人往里发邮件毫无意义。
const got = snapshotDshSessions([
{ id: 'child', cwd: '/w', title: 'You are auditing ONE file', origin: 'subagent' },
{ id: 'top', cwd: '/w', title: '正常会话' },
]);
assert.equal(got.length, 1);
assert.equal(got[0].platform_id, 'top');
});
test('不变量subagent 子会话不上报delegationDepth 判据)', () => {
const got = snapshotDshSessions([
{ id: 'child', cwd: '/w', title: '子任务', delegationDepth: 1 },
{ id: 'top', cwd: '/w', title: '顶层', delegationDepth: 0 },
]);
assert.equal(got.length, 1);
assert.equal(got[0].platform_id, 'top');
});
test('不变量slug 撞名只留最近那条', () => {
// 别名是寻址用的:同一个 slug 对应多条会话时服务端只能取其中一条,
// 上报一堆同名项只会让补全列表里出现几个点哪个都不确定的候选。
const got = snapshotDshSessions([
{ id: 'old', cwd: '/w', title: '同一个标题', updatedAt: 1000 },
{ id: 'new', cwd: '/w', title: '同一个标题', updatedAt: 9000 },
{ id: 'mid', cwd: '/w', title: '同一个标题', updatedAt: 5000 },
]);
assert.equal(got.length, 1, `应去重到 1 条,实际 ${got.length}`);
assert.equal(got[0].platform_id, 'new', '应保留最近活跃的那条');
});
test('不同标题不受去重影响', () => {
const got = snapshotDshSessions([
{ id: 'a', cwd: '/w', title: '标题一', updatedAt: 2000 },
{ id: 'b', cwd: '/w', title: '标题二', updatedAt: 1000 },
]);
assert.equal(got.length, 2);
});