docs: 插件适配指南 + 共用模块提取(为接入更多平台做准备)

两次适配(opencode、DeepSeek Harness)里的方法与坑此前散落在提交信息和
代码注释里,接第三个平台时要重新翻。这次固化成文档,并把与平台 SDK 无关的
逻辑提到共用模块。

## docs/PLUGIN-GUIDE.md

八节:职责边界、必须实现的六件事、会话命名回写、平台会话快照上报、
平台差异对照表、踩过的坑(按排查成本降序)、新平台适配清单、共用模块清单。

三条设计原则贯穿全文,后面每一节都是它们的推论:

1. **平台原生信号才是真相来源**,不要求模型「记得」调工具 —— 因此不提供
   request_permission(改挂权限钩子)、不要求模型主动回信(改在「一轮结束」
   的平台信号上自动转发)
2. **插件代劳的转发不消耗配额** —— 因此这两类转发带 relay + relay_key
3. **平台命名优先** —— 因此创建会话时不传占位标题(那会掐掉平台自己的命名机制)

「踩过的坑」一节按排查成本排序,头一条是花了一下午的 followup() 参数形状。

## 共用模块提取

`lib/inbox-format.js`(新):收件箱渲染与已读策略。三条规则各对应一次错误行为,
而它们与平台 SDK 无关:

- 附件必须带 attachment_id(只说「有附件」模型无从下载)
- 抄送人要显示(不显示模型以为是私信,回信时漏掉其他参与方)
- 只标本次列出的、status=all 时不标(limit 之外的还没看过;把历史邮件标成已读
  会让下一轮的新邮件混在里面认不出来)

顺带修好两处不一致:DSH 的 read_inbox 此前**完全没有标记已读**(每轮重复捞同一批),
且默认 status=all(同上);附件大小两边一个显示字节数一个显示 KB/MB。

`lib/workspace.js`:提到两侧共用。签名从 (workspace, fallbackKey) 改为
(workspace, fallback) —— 各平台的兜底不同:opencode 有插件启动时的 directory,
DSH 只能落到 ~/.dsh/mail-sessions/<会话>(mailSessionFallback)。
opencode 侧此前是内联的三行判断,没有「目录不存在时不创建」与「拒绝相对路径」
这两条保护。

## deploy/check-shared-libs.sh

`lib/` 与 `test/` 下的共用文件必须逐字节相同,纳入 install.sh 门禁。

一侧改了另一侧没改,两个平台的行为就会悄悄分叉:同一封邮件在 opencode 那边
标了已读、在 DSH 那边没标,而两处代码看起来都「对」。这类分叉没有测试能发现,
只能靠 diff。

## 文档同步

- PLAN.md §7.7 从「待做」改为已完成,补 7.7.1(工作目录归属)与
  7.7.2(平台会话快照)两节,记录根因而非只记改法
- API.md 加「心跳与平台会话快照」章节;SSE 章节补 new_mail 与
  permission_decision 的 payload 说明(to_workspace 的语义、relay_key 的用途)
- PHASE7-REMAINING.md 移除已完成的 7.7,新增「每平台可用模型范围」的进展
  (repo 层已就绪,handler/插件/前端待做)
- README 文档索引与项目结构

验证:两插件共 136 个测试通过,同源校验通过,Go/前端全绿;
端到端发信 → DSH 用新的 read_inbox 渲染读取 → 自动回信 213 字节。
This commit is contained in:
2026-09-02 20:28:19 +08:00
parent ca64d12057
commit 7c9be9fd58
20 changed files with 1482 additions and 100 deletions

View File

@ -0,0 +1,7 @@
export declare const DEFAULT_INBOX_STATUS: string;
export declare const DEFAULT_INBOX_LIMIT: number;
export function formatSize(n: number | undefined): string;
export function renderMail(mail: any, bodyLimit?: number): string;
export function renderInbox(mails: readonly any[], bodyLimit?: number): string;
export function idsToMarkRead(status: string | undefined, mails: readonly any[]): string[];

View File

@ -0,0 +1,90 @@
/**
* 收件箱渲染与已读策略 —— 所有平台插件共用。
*
* 提到 lib/ 是因为这几条规则每一条都对应过一次真实的错误行为,而它们与
* 平台 SDK 无关:无论 opencode 的 zod 工具还是 DSH 的 defineTool
* 渲染出的文本与标记已读的时机都该一致。新接一个平台时直接复用这里。
*/
/** 人类可读的字节数,用于附件清单展示。 */
export function formatSize(n) {
if (typeof n !== 'number' || !Number.isFinite(n)) return '?';
if (n < 1024) return `${n} B`;
if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KB`;
return `${(n / 1024 / 1024).toFixed(1)} MB`;
}
/**
* 把一封邮件渲染成模型可读的文本块。
*
* @param {any} m `/mail/inbox` 返回的一封邮件
* @param {number} bodyLimit 正文截断长度
* @returns {string}
*/
export function renderMail(m, bodyLimit = 200) {
const lines = [
`[${m?.status ?? 'unknown'}] ${m?.from_name ?? 'unknown'}: ${m?.subject ?? '(无主题)'}`,
`邮件 ID: ${m?.mail_id ?? 'unknown'}`,
`会话: #${m?.session_alias || '未命名'}`,
];
// 抄送要显示:一封邮件为什么同时到了几个人手上,只有抄送能解释。
// 不显示的话模型会以为这是私下发给它一个人的,回信时漏掉其他参与方。
if (Array.isArray(m?.cc_list) && m.cc_list.length > 0) {
lines.push('抄送: ' + m.cc_list.map(c => c?.raw || c?.name || '?').join('、'));
}
// **必须给出 attachment_id**:只说「有附件」模型就无从下载。
if (Array.isArray(m?.attachments) && m.attachments.length > 0) {
lines.push(
'附件: ' +
m.attachments
.map(a => `${a?.filename ?? '?'}${formatSize(a?.size_bytes)}, id=${a?.attachment_id ?? '?'}`)
.join('、')
);
lines.push('下载附件请用 download_attachment 工具。');
}
// 列表接口只给 body_preview省带宽单封接口才有 body。两者都兜住。
const body = m?.body_preview || m?.body || '';
lines.push(`内容: ${String(body).slice(0, bodyLimit)}`);
return lines.join('\n');
}
/**
* 渲染整个收件箱。
* @param {any[]} mails
* @param {number} bodyLimit
* @returns {string}
*/
export function renderInbox(mails, bodyLimit = 200) {
const list = Array.isArray(mails) ? mails : [];
if (list.length === 0) return '收件箱为空。';
return list.map(m => renderMail(m, bodyLimit)).join('\n\n');
}
/**
* 判断本次读取该标记哪些邮件为已读。
*
* 两条规则:
*
* 1. **只标本次真正列出来的**,不是全部未读。`limit` 之外的还没看过,
* 一并标掉等于让它们凭空消失。
* 2. **`status=all` 时不标**。那是「回顾历史」的读法,把历史邮件标成已读
* 会让下一轮真正的新邮件混在里面认不出来。
*
* 不标的后果是每次拉收件箱都重复捞同一批,处理过的和新来的混在一起,
* 模型分不清哪封该回。
*
* @param {string|undefined} status 本次查询用的过滤条件
* @param {any[]} mails 本次返回的邮件
* @returns {string[]} 待标记的 mail_id空数组表示不需要标记
*/
export function idsToMarkRead(status, mails) {
if (status === 'all') return [];
const list = Array.isArray(mails) ? mails : [];
return list.map(m => m?.mail_id).filter(id => typeof id === 'string' && id);
}
/** 收件箱默认过滤条件。默认只看未读 —— 默认 all 会让模型每轮重读旧邮件。 */
export const DEFAULT_INBOX_STATUS = 'unread';
/** 收件箱默认返回条数。 */
export const DEFAULT_INBOX_LIMIT = 5;

View File

@ -1,6 +1,7 @@
export function resolveWorkspaceCwd(
workspace: string | undefined,
fallbackKey: string
fallback: string
): { cwd: string; grouped: boolean };
export function mailSessionFallback(sessionKey: string): string;
export function ensureCwd(cwd: string, grouped: boolean): void;

View File

@ -14,12 +14,12 @@ import { homedir } from 'node:os';
import { isAbsolute, join, resolve } from 'node:path';
/**
* 把 new_mail 事件里的 to_workspace 解析成一个可用的 cwd
* 校验寻址里的工作目录,不可用时返回调用方给的兜底
*
* 决策顺序:
* 1. path 位是一个已存在的目录 → 直接用它(同 path 的多封邮件天然同组)
* 2. path 位非空但目录不存在 → **不创建**回退到兜底目录
* 3. path 位为空(地址写成 `dsh` 而不带 `@/path`)→ 兜底目录
* 2. path 位非空但目录不存在 → **不创建**返回兜底
* 3. path 位为空(地址写成 `dsh` 而不带 `@/path`)→ 兜底
*
* 为什么不给不存在的 path 建目录:那等于让一个笔误(`/home/porgram/x`
* 在磁盘上落下一个真目录,而 Agent 会在里面一无所获地干活 ——
@ -28,15 +28,18 @@ import { isAbsolute, join, resolve } from 'node:path';
* 为什么拒绝相对路径cwd 的相对基准是 harness 进程的启动目录,
* 那是个与邮件语义无关的量systemd 下通常是 `/`)。
*
* 兜底由调用方给因为各平台的兜底不同opencode 有插件启动时的 directory
* 可用DSH 没有、只能落到 `~/.dsh/mail-sessions/<会话>`(见 mailSessionFallback
*
* @param {string} workspace 事件里的 to_workspace
* @param {string} fallbackKey 兜底目录名(通常是会话 id
* @param {string} fallback 不可用时的兜底目录(可为空串 = 交给平台自己决定
* @returns {{cwd: string, grouped: boolean}} grouped 为真表示落在了寻址指定的目录里
*/
export function resolveWorkspaceCwd(workspace, fallbackKey) {
export function resolveWorkspaceCwd(workspace, fallback) {
const raw = typeof workspace === 'string' ? workspace.trim() : '';
const fallback = join(homedir(), '.dsh', 'mail-sessions', String(fallbackKey || 'default'));
const fb = typeof fallback === 'string' ? fallback : '';
if (!raw || !isAbsolute(raw)) return { cwd: fallback, grouped: false };
if (!raw || !isAbsolute(raw)) return { cwd: fb, grouped: false };
const abs = resolve(raw);
try {
@ -46,7 +49,16 @@ export function resolveWorkspaceCwd(workspace, fallbackKey) {
} catch {
// 权限不足等:当作不可用
}
return { cwd: fallback, grouped: false };
return { cwd: fb, grouped: false };
}
/**
* 没有天然兜底的平台DSH用这个`~/.dsh/mail-sessions/<会话 id>`。
* @param {string} sessionKey 会话标识
* @returns {string}
*/
export function mailSessionFallback(sessionKey) {
return join(homedir(), '.dsh', 'mail-sessions', String(sessionKey || 'default'));
}
/**
@ -56,7 +68,7 @@ export function resolveWorkspaceCwd(workspace, fallbackKey) {
* @param {boolean} grouped 是否落在寻址指定的目录里
*/
export function ensureCwd(cwd, grouped) {
if (grouped) return;
if (grouped || !cwd) return;
try {
mkdirSync(cwd, { recursive: true });
} catch {

View File

@ -28,7 +28,14 @@ import {
modelTitle,
} from '../lib/message.js';
import { snapshotDshSessions, slugFromTitle } from '../lib/session-snapshot.js';
import { resolveWorkspaceCwd, ensureCwd } from '../lib/workspace.js';
import { resolveWorkspaceCwd, ensureCwd, mailSessionFallback } from '../lib/workspace.js';
import {
renderInbox,
idsToMarkRead,
formatSize,
DEFAULT_INBOX_STATUS,
DEFAULT_INBOX_LIMIT,
} from '../lib/inbox-format.js';
// ─── 凭证管理 ───
@ -320,7 +327,8 @@ export function apply(ctx: any, config: PluginConfig): void {
// 之前这里硬拼 `~/.dsh/mail-sessions/mail-<uuid>` —— 每封邮件一个全新的空目录。
// DSH 按 cwd 给会话分组,于是所有邮件会话既不属于任何项目、彼此也不同组,
// 界面上全落进「未分组」。path 位本来就是「希望它在哪儿干活」。
const { cwd, grouped } = resolveWorkspaceCwd(data.to_workspace, sessionId);
const { cwd, grouped } = resolveWorkspaceCwd(
data.to_workspace, mailSessionFallback(sessionId));
ensureCwd(cwd, grouped);
if (!grouped && data.to_workspace) {
ctx.logger.warn(
@ -456,25 +464,35 @@ export function apply(ctx: any, config: PluginConfig): void {
// read_inbox
ctx.tools.register(defineTool({
name: 'read_inbox',
description: '读取收件箱邮件列表。返回最新的邮件,每封含 mail_id、发件人、主题、正文附件清单。',
description: '查阅收件箱中的邮件。收到新邮件通知后应立即调用此工具。每封含 mail_id、发件人、主题、正文附件清单(带 attachment_id。',
parameters: {
status: { type: 'string', description: '过滤状态all/unread/read' },
limit: { type: 'number', description: '返回数量上限' },
status: { type: 'string', description: '过滤条件 unread|all默认 unread' },
limit: { type: 'number', description: '返回数量,默认 5' },
},
output: {
schema: { type: 'string' },
render: (_args: any, value: string) => [{ type: 'text', text: value }],
},
async execute(args: any): Promise<string> {
const status = args.status || DEFAULT_INBOX_STATUS;
const { mails } = await client.get(
`/mail/inbox?status=${args.status || 'all'}&limit=${args.limit || 20}`
`/mail/inbox?status=${status}&limit=${args.limit || DEFAULT_INBOX_LIMIT}`
);
if (!mails?.length) return '收件箱为空。';
return mails.map((m: any) => {
const att = m.attachments?.length
? ` [附件: ${m.attachments.map((a: any) => a.filename).join(', ')}]` : '';
return `- ID: ${m.mail_id} | ${m.from_name} | ${m.subject}${att}\n ${m.body.slice(0, 200)}`;
}).join('\n');
// 渲染与已读策略放 lib/inbox-format.js它们与平台 SDK 无关,
// 各平台插件必须一致(见该文件里每条规则对应的错误行为)。
const listed = renderInbox(mails);
// 读过就标掉,否则每次拉收件箱都重复捞同一批,
// 处理过的和新来的混在一起,模型分不清哪封该回。
const ids = idsToMarkRead(args.status, mails);
if (ids.length) {
// 标记失败不该让 read_inbox 失败:正文已经取到了,
// 代价只是下次重复看到,比丢掉这次读取轻。
client.post('/mail/read', { mail_ids: ids }).catch((e: any) =>
ctx.logger.error(`[dsh-mail-bridge] 标记已读失败: ${e?.message || e}`));
}
return listed;
},
}));
@ -500,7 +518,7 @@ export function apply(ctx: any, config: PluginConfig): void {
const json = await res.json() as any;
if (!res.ok) throw new Error(json?.error || `HTTP ${res.status}`);
const a = json.attachment;
return `已上传 ${a.filename}${a.size_bytes} 字节。attachment_id: ${a.attachment_id}`;
return `已上传 ${a.filename}${formatSize(a.size_bytes)}。attachment_id: ${a.attachment_id}`;
},
}));
@ -523,7 +541,7 @@ export function apply(ctx: any, config: PluginConfig): void {
if (!res.ok) throw new Error(`下载失败: HTTP ${res.status}`);
const buf = Buffer.from(await res.arrayBuffer());
await writeFile(args.save_path, buf);
return `已保存到 ${args.save_path}${buf.length} 字节`;
return `已保存到 ${args.save_path}${formatSize(buf.length)}`;
},
}));

View File

@ -0,0 +1,176 @@
/**
* 收件箱渲染与已读策略的测试。
*
* 每条断言都对应一次真实的错误行为(见 lib/inbox-format.js 里的注释):
* 漏掉 attachment_id 模型就无从下载附件;漏掉抄送它会以为这是私信;
* status=all 时标记已读会让下一轮的新邮件混在历史里认不出来。
*
* node --test 'test/*.test.mjs'
*/
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
formatSize,
renderMail,
renderInbox,
idsToMarkRead,
DEFAULT_INBOX_STATUS,
DEFAULT_INBOX_LIMIT,
} from '../lib/inbox-format.js';
const mail = (over = {}) => ({
mail_id: 'm-1',
from_name: 'admin',
subject: '缓存选型',
status: 'unread',
session_alias: 'brisk-harbor',
body_preview: '我们需要评估一下缓存层',
...over,
});
// ─── formatSize ───
test('formatSize 分档', () => {
assert.equal(formatSize(512), '512 B');
assert.equal(formatSize(2048), '2.0 KB');
assert.equal(formatSize(3 * 1024 * 1024), '3.0 MB');
});
test('formatSize 容错', () => {
assert.equal(formatSize(undefined), '?');
assert.equal(formatSize(NaN), '?');
assert.equal(formatSize('x'), '?');
});
// ─── renderMail ───
test('renderMail 带出 mail_id 与会话别名', () => {
const got = renderMail(mail());
assert.match(got, /邮件 ID: m-1/);
assert.match(got, /#brisk-harbor/);
assert.match(got, /admin: 缓存选型/);
});
test('无别名时显示「未命名」而不是空', () => {
const got = renderMail(mail({ session_alias: '' }));
assert.match(got, /#未命名/);
});
test('不变量:附件必须带 attachment_id', () => {
// 只说「有附件」模型就无从下载 —— download_attachment 要的正是这个 id。
const got = renderMail(mail({
attachments: [{ filename: 'report.md', size_bytes: 2048, attachment_id: 'att-9' }],
}));
assert.match(got, /id=att-9/, `附件行缺 id${got}`);
assert.match(got, /report\.md/);
assert.match(got, /2\.0 KB/);
assert.match(got, /download_attachment/, '要提示模型用哪个工具下载');
});
test('多个附件都列出来', () => {
const got = renderMail(mail({
attachments: [
{ filename: 'a.md', size_bytes: 10, attachment_id: 'att-1' },
{ filename: 'b.md', size_bytes: 20, attachment_id: 'att-2' },
],
}));
assert.match(got, /att-1/);
assert.match(got, /att-2/);
});
test('不变量:抄送人要显示出来', () => {
// 不显示的话模型会以为这是私下发给它一个人的,回信时漏掉其他参与方。
const got = renderMail(mail({
cc_list: [{ name: 'opencode', raw: 'opencode@/home.new' }],
}));
assert.match(got, /抄送/);
assert.match(got, /opencode@\/home\.new/, '应优先用 raw带路径与会话段');
});
test('无抄送时不出现抄送行', () => {
assert.ok(!renderMail(mail()).includes('抄送'));
assert.ok(!renderMail(mail({ cc_list: [] })).includes('抄送'));
});
test('正文优先取 body_preview缺失时退回 body', () => {
assert.match(renderMail(mail({ body_preview: '预览', body: '全文' })), /内容: 预览/);
assert.match(renderMail(mail({ body_preview: '', body: '全文' })), /内容: 全文/);
});
test('正文按 bodyLimit 截断', () => {
const got = renderMail(mail({ body_preview: 'x'.repeat(500) }), 50);
const line = got.split('\n').find(l => l.startsWith('内容: '));
assert.equal(line.length, '内容: '.length + 50);
});
test('renderMail 容错:字段全缺不崩', () => {
const got = renderMail({});
assert.match(got, /unknown/);
const got2 = renderMail(undefined);
assert.equal(typeof got2, 'string');
});
test('附件字段不是数组时忽略', () => {
const got = renderMail(mail({ attachments: 'oops', cc_list: 'oops' }));
assert.ok(!got.includes('附件:'));
assert.ok(!got.includes('抄送'));
});
// ─── renderInbox ───
test('renderInbox 空收件箱给明确文案', () => {
assert.equal(renderInbox([]), '收件箱为空。');
assert.equal(renderInbox(undefined), '收件箱为空。');
assert.equal(renderInbox(null), '收件箱为空。');
});
test('renderInbox 用空行分隔多封', () => {
const got = renderInbox([mail({ mail_id: 'a' }), mail({ mail_id: 'b' })]);
assert.match(got, /邮件 ID: a[\s\S]*\n\n[\s\S]*邮件 ID: b/);
});
// ─── idsToMarkRead ───
test('不变量:只标本次列出的那些', () => {
// limit 之外的还没看过,一并标掉等于让它们凭空消失。
const ids = idsToMarkRead('unread', [mail({ mail_id: 'a' }), mail({ mail_id: 'b' })]);
assert.deepEqual(ids, ['a', 'b']);
});
test('不变量status=all 时不标记', () => {
// 那是「回顾历史」的读法。把历史邮件标成已读会让下一轮真正的新邮件
// 混在里面认不出来。
assert.deepEqual(idsToMarkRead('all', [mail({ mail_id: 'a' })]), []);
});
test('status 省略时按默认unread标记', () => {
assert.deepEqual(idsToMarkRead(undefined, [mail({ mail_id: 'a' })]), ['a']);
});
test('idsToMarkRead 过滤掉无 id 的条目', () => {
const ids = idsToMarkRead('unread', [
mail({ mail_id: 'a' }),
mail({ mail_id: '' }),
mail({ mail_id: undefined }),
{ },
]);
assert.deepEqual(ids, ['a']);
});
test('idsToMarkRead 容错非数组', () => {
assert.deepEqual(idsToMarkRead('unread', undefined), []);
assert.deepEqual(idsToMarkRead('unread', 'oops'), []);
});
// ─── 默认值 ───
test('默认只看未读', () => {
// 默认 all 会让模型每轮重读旧邮件,把处理过的和新来的混在一起。
assert.equal(DEFAULT_INBOX_STATUS, 'unread');
});
test('默认条数是个小数字', () => {
// 收件箱一次给几十封会把上下文塞满,而模型一轮通常只处理一两封。
assert.ok(DEFAULT_INBOX_LIMIT > 0 && DEFAULT_INBOX_LIMIT <= 10);
});

View File

@ -13,14 +13,16 @@ import assert from 'node:assert/strict';
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir, homedir } from 'node:os';
import { join } from 'node:path';
import { resolveWorkspaceCwd, ensureCwd } from '../lib/workspace.js';
import { resolveWorkspaceCwd, ensureCwd, mailSessionFallback } from '../lib/workspace.js';
const fallbackOf = key => join(homedir(), '.dsh', 'mail-sessions', key);
// 兜底目录现在由调用方给各平台不同。DSH 用 mailSessionFallback
// opencode 用插件启动时的 directory。
const fallbackOf = key => mailSessionFallback(key);
test('存在的绝对路径直接用作 cwd', () => {
const dir = mkdtempSync(join(tmpdir(), 'ws-test-'));
try {
const got = resolveWorkspaceCwd(dir, 'mail-1');
const got = resolveWorkspaceCwd(dir, fallbackOf('mail-1'));
assert.equal(got.cwd, dir);
assert.equal(got.grouped, true);
} finally {
@ -31,8 +33,8 @@ test('存在的绝对路径直接用作 cwd', () => {
test('不变量:同一 path 的多封邮件得到同一个 cwd这才能同组', () => {
const dir = mkdtempSync(join(tmpdir(), 'ws-test-'));
try {
const a = resolveWorkspaceCwd(dir, 'mail-aaa');
const b = resolveWorkspaceCwd(dir, 'mail-bbb');
const a = resolveWorkspaceCwd(dir, fallbackOf('mail-aaa'));
const b = resolveWorkspaceCwd(dir, fallbackOf('mail-bbb'));
assert.equal(a.cwd, b.cwd, 'fallbackKey 不同却应得到同一个 cwd');
} finally {
rmSync(dir, { recursive: true, force: true });
@ -40,14 +42,14 @@ test('不变量:同一 path 的多封邮件得到同一个 cwd这才能同
});
test('path 为空时回退到兜底目录', () => {
const got = resolveWorkspaceCwd('', 'mail-2');
const got = resolveWorkspaceCwd('', fallbackOf('mail-2'));
assert.equal(got.cwd, fallbackOf('mail-2'));
assert.equal(got.grouped, false);
});
test('path 缺失/非字符串时回退', () => {
for (const v of [undefined, null, 42, {}]) {
const got = resolveWorkspaceCwd(v, 'mail-3');
const got = resolveWorkspaceCwd(v, fallbackOf('mail-3'));
assert.equal(got.grouped, false);
assert.equal(got.cwd, fallbackOf('mail-3'));
}
@ -56,7 +58,7 @@ test('path 缺失/非字符串时回退', () => {
test('不变量:不存在的目录不创建,回退到兜底', () => {
// 一个笔误(/home/porgram/x不该在磁盘上落下真目录 ——
// Agent 会在里面一无所获地干活,比明确回退更难排查。
const got = resolveWorkspaceCwd('/nonexistent/path/xyz-should-not-exist', 'mail-4');
const got = resolveWorkspaceCwd('/nonexistent/path/xyz-should-not-exist', fallbackOf('mail-4'));
assert.equal(got.grouped, false);
assert.equal(got.cwd, fallbackOf('mail-4'));
});
@ -65,7 +67,7 @@ test('不变量:相对路径被拒绝', () => {
// cwd 的相对基准是 harness 进程的启动目录systemd 下通常是 /
// 那是个与邮件语义完全无关的量。
for (const rel of ['relative/path', './x', '../y', 'src']) {
const got = resolveWorkspaceCwd(rel, 'mail-5');
const got = resolveWorkspaceCwd(rel, fallbackOf('mail-5'));
assert.equal(got.grouped, false, `${rel} 不该被当作工作目录`);
}
});
@ -75,7 +77,7 @@ test('指向文件而非目录时回退', () => {
const file = join(dir, 'a-file');
writeFileSync(file, 'x');
try {
const got = resolveWorkspaceCwd(file, 'mail-6');
const got = resolveWorkspaceCwd(file, fallbackOf('mail-6'));
assert.equal(got.grouped, false);
} finally {
rmSync(dir, { recursive: true, force: true });
@ -85,7 +87,7 @@ test('指向文件而非目录时回退', () => {
test('两端空白被修掉', () => {
const dir = mkdtempSync(join(tmpdir(), 'ws-test-'));
try {
const got = resolveWorkspaceCwd(` ${dir} `, 'mail-7');
const got = resolveWorkspaceCwd(` ${dir} `, fallbackOf('mail-7'));
assert.equal(got.cwd, dir);
assert.equal(got.grouped, true);
} finally {
@ -99,14 +101,28 @@ test('ensureCwd 只建兜底目录,不碰寻址指定的目录', () => {
const target = join(base, 'made-by-ensure');
ensureCwd(target, false);
// 建出来了
const got = resolveWorkspaceCwd(target, 'x');
const got = resolveWorkspaceCwd(target, '');
assert.equal(got.grouped, true, 'ensureCwd 应已创建该目录');
// grouped=true 时不该创建(那种目录本来就存在)
const never = join(base, 'should-not-exist');
ensureCwd(never, true);
assert.equal(resolveWorkspaceCwd(never, 'x').grouped, false);
assert.equal(resolveWorkspaceCwd(never, '').grouped, false);
} finally {
rmSync(base, { recursive: true, force: true });
}
});
test('兜底为空串时返回空 cwd交给平台自己决定', () => {
// opencode 没配 directory 时就是这种情况session.create 不带 query.directory
// 由平台按自己的默认规则选目录。比硬塞一个我们猜的路径好。
const got = resolveWorkspaceCwd('', '');
assert.equal(got.cwd, '');
assert.equal(got.grouped, false);
});
test('mailSessionFallback 同一 key 稳定、不同 key 不同', () => {
assert.equal(mailSessionFallback('a'), mailSessionFallback('a'));
assert.notEqual(mailSessionFallback('a'), mailSessionFallback('b'));
assert.match(mailSessionFallback('a'), /mail-sessions/);
});