@dsh-overdrive/gateway 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,138 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import {
3
+ buildNativeFlowButtons,
4
+ buildNumberedReply,
5
+ matchNumberedReply,
6
+ normalizeWhatsAppMessage,
7
+ parseNativeButtonResponse,
8
+ whatsappImageUrl,
9
+ type RawWhatsAppMessage,
10
+ } from '../src/adapters/whatsapp.js';
11
+
12
+ describe('normalizeWhatsAppMessage', () => {
13
+ it('文本消息 → NormalizedMessage(chatId=JID, userId=发送者)', () => {
14
+ const raw = {
15
+ key: { remoteJid: '60123@s.whatsapp.net', participant: undefined },
16
+ message: { conversation: 'hello' },
17
+ messageType: 'conversation',
18
+ };
19
+ const out = normalizeWhatsAppMessage(raw);
20
+ expect(out?.kind).toBe('message');
21
+ expect(out?.msg).toMatchObject({ chatId: '60123@s.whatsapp.net', userId: '60123@s.whatsapp.net', text: 'hello' });
22
+ });
23
+
24
+ it('群聊用 participant 作 userId', () => {
25
+ const raw = {
26
+ key: { remoteJid: 'group@g.us', participant: '60123@s.whatsapp.net' },
27
+ message: { extendedTextMessage: { text: 'hi' } },
28
+ messageType: 'extendedTextMessage',
29
+ };
30
+ const out = normalizeWhatsAppMessage(raw);
31
+ expect(out?.msg.userId).toBe('60123@s.whatsapp.net');
32
+ expect(out?.msg.chatId).toBe('group@g.us');
33
+ });
34
+
35
+ it('非文本消息返回 null', () => {
36
+ expect(normalizeWhatsAppMessage({ key: { remoteJid: 'x' }, message: { imageMessage: {} } })).toBeNull();
37
+ expect(normalizeWhatsAppMessage({ key: { remoteJid: 'x' }, message: {} })).toBeNull();
38
+ });
39
+ });
40
+
41
+ describe('whatsappImageUrl / 媒体消息捕获', () => {
42
+ it('imageMessage url + caption → media: { kind: "image", url };无 url 退 directPath', () => {
43
+ const raw = {
44
+ key: { remoteJid: '60123@s.whatsapp.net' },
45
+ message: { imageMessage: { url: 'https://mmg.whatsapp.net/f/x.jpg', caption: '看图' } },
46
+ messageType: 'imageMessage',
47
+ };
48
+ expect(whatsappImageUrl(raw)).toBe('https://mmg.whatsapp.net/f/x.jpg');
49
+ expect(normalizeWhatsAppMessage(raw)).toMatchObject({
50
+ kind: 'message',
51
+ msg: {
52
+ chatId: '60123@s.whatsapp.net',
53
+ userId: '60123@s.whatsapp.net',
54
+ text: '看图',
55
+ media: { kind: 'image', url: 'https://mmg.whatsapp.net/f/x.jpg' },
56
+ },
57
+ });
58
+ // directPath 兜底(M4 简化:URL 直接透传,认证头后续再补)
59
+ expect(whatsappImageUrl({ message: { imageMessage: { directPath: '/d/p.jpg' } } })).toBe('/d/p.jpg');
60
+ });
61
+ });
62
+
63
+ describe('buildNumberedReply / matchNumberedReply(审批按钮的编号文本方案)', () => {
64
+ it('生成 1/2 编号选项', () => {
65
+ const text = buildNumberedReply('⚠️ 需要批准:删除文件', [
66
+ { id: 'approve:r1', label: '✅ 同意' },
67
+ { id: 'reject:r1', label: '🚫 拒绝' },
68
+ ]);
69
+ expect(text).toContain('1) ✅ 同意');
70
+ expect(text).toContain('2) 🚫 拒绝');
71
+ });
72
+
73
+ it('回复数字能匹配回按钮 id', () => {
74
+ const buttons = [
75
+ { id: 'approve:r1', label: '✅ 同意' },
76
+ { id: 'reject:r1', label: '🚫 拒绝' },
77
+ ];
78
+ expect(matchNumberedReply('1', buttons)?.id).toBe('approve:r1');
79
+ expect(matchNumberedReply('2', buttons)?.id).toBe('reject:r1');
80
+ expect(matchNumberedReply('9', buttons)).toBeUndefined();
81
+ expect(matchNumberedReply('同意', buttons)).toBeUndefined();
82
+ });
83
+ });
84
+
85
+ describe('buildNativeFlowButtons(WhatsApp 原生交互按钮)', () => {
86
+ it('按钮 → nativeFlowMessage buttons 数组', () => {
87
+ const buttons = buildNativeFlowButtons([
88
+ { id: 'approve:r1', label: '✅ 同意' },
89
+ { id: 'reject:r1', label: '🚫 拒绝' },
90
+ ]);
91
+ expect(buttons).toHaveLength(2);
92
+ expect(buttons[0]).toMatchObject({
93
+ name: 'quick_reply',
94
+ buttonParamsJson: JSON.stringify({ id: 'approve:r1', display_text: '✅ 同意' }),
95
+ });
96
+ expect(buttons[1]).toMatchObject({
97
+ name: 'quick_reply',
98
+ buttonParamsJson: JSON.stringify({ id: 'reject:r1', display_text: '🚫 拒绝' }),
99
+ });
100
+ });
101
+
102
+ it('空数组 → 空 buttons', () => {
103
+ expect(buildNativeFlowButtons([])).toEqual([]);
104
+ });
105
+ });
106
+
107
+ describe('parseNativeButtonResponse(交互按钮响应解析)', () => {
108
+ it('解析 paramsJson 中的 id', () => {
109
+ const raw: RawWhatsAppMessage = {
110
+ key: { remoteJid: '60123@s.whatsapp.net' },
111
+ message: {
112
+ interactiveResponseMessage: {
113
+ nativeFlowResponseMessage: { paramsJson: JSON.stringify({ id: 'approve:r1' }) },
114
+ },
115
+ },
116
+ messageType: 'interactiveResponseMessage',
117
+ };
118
+ expect(parseNativeButtonResponse(raw)).toBe('approve:r1');
119
+ });
120
+
121
+ it('无交互响应 / 非法 JSON / 缺 id 均返回 null', () => {
122
+ expect(parseNativeButtonResponse({ key: { remoteJid: 'x' }, message: { conversation: 'hi' } })).toBeNull();
123
+ expect(parseNativeButtonResponse({ key: { remoteJid: 'x' }, message: {} })).toBeNull();
124
+ expect(parseNativeButtonResponse({ key: { remoteJid: 'x' } })).toBeNull();
125
+ expect(
126
+ parseNativeButtonResponse({
127
+ key: { remoteJid: 'x' },
128
+ message: { interactiveResponseMessage: { nativeFlowResponseMessage: { paramsJson: 'not-json' } } },
129
+ }),
130
+ ).toBeNull();
131
+ expect(
132
+ parseNativeButtonResponse({
133
+ key: { remoteJid: 'x' },
134
+ message: { interactiveResponseMessage: { nativeFlowResponseMessage: { paramsJson: JSON.stringify({ foo: 'bar' }) } } },
135
+ }),
136
+ ).toBeNull();
137
+ });
138
+ });
@@ -0,0 +1,18 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { parseCommand, type ParsedCommand } from '../src/commands.js';
3
+
4
+ describe('parseCommand', () => {
5
+ it('识别 /trace、/task、/cron、/agents、/new、/help', () => {
6
+ expect(parseCommand('/trace')).toEqual({ kind: 'trace' });
7
+ expect(parseCommand('/new')).toEqual({ kind: 'new' });
8
+ expect(parseCommand('/agents')).toEqual({ kind: 'agents' });
9
+ expect(parseCommand('/help')).toEqual({ kind: 'help' });
10
+ expect(parseCommand('/task 调研竞品')).toEqual({ kind: 'task', prompt: '调研竞品' });
11
+ expect(parseCommand('/cron 0 8 * * * 每日汇报')).toEqual({ kind: 'cron', schedule: '0 8 * * *', prompt: '每日汇报' });
12
+ });
13
+ it('非命令返回 null', () => {
14
+ expect(parseCommand('hello')).toBeNull();
15
+ expect(parseCommand('/unknown')).toBeNull();
16
+ expect(parseCommand('/task')).toBeNull(); // 缺参数
17
+ });
18
+ });
@@ -0,0 +1,30 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { createAdapter, parseAdapterIds, type AdapterEnv } from '../src/config.js';
3
+
4
+ describe('parseAdapterIds', () => {
5
+ it('逗号分隔 + 去空格 + 去空项', () => {
6
+ expect(parseAdapterIds('cli, whatsapp, telegram,')).toEqual(['cli', 'whatsapp', 'telegram']);
7
+ });
8
+ it('缺省为 cli', () => {
9
+ expect(parseAdapterIds('')).toEqual(['cli']);
10
+ });
11
+ });
12
+
13
+ describe('createAdapter 注册表', () => {
14
+ it('cli 恒可用', () => {
15
+ const a = createAdapter('cli', {});
16
+ expect(a.id).toBe('cli');
17
+ });
18
+ it('未知适配器抛错', () => {
19
+ expect(() => createAdapter('nope', {})).toThrow(/unknown adapter/);
20
+ });
21
+ it('feishu 缺凭据抛错', () => {
22
+ expect(() => createAdapter('feishu', {})).toThrow(/FEISHU_APP_ID/);
23
+ });
24
+ it('dingtalk 缺凭据抛错', () => {
25
+ expect(() => createAdapter('dingtalk', {})).toThrow(/DINGTALK_CLIENT_ID/);
26
+ });
27
+ it('wecom 缺凭据抛错', () => {
28
+ expect(() => createAdapter('wecom', {})).toThrow(/WECOM_CORP_ID/);
29
+ });
30
+ });
@@ -0,0 +1,86 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { wireAdapter } from '../src/index.js';
3
+ import { GatewayClient } from '@dsh-overdrive/sdk';
4
+ import type { Adapter, NormalizedMessage, OutboundPayload } from '../src/adapter.js';
5
+
6
+ /** 可编程 FakeAdapter:验证 wiring 逻辑(白名单/会话键/错误兜底)。 */
7
+ class FakeAdapter implements Adapter {
8
+ readonly id: string;
9
+ readonly sent: Array<{ chatId: string; payload: OutboundPayload }> = [];
10
+ private messageCb?: (msg: NormalizedMessage) => Promise<void> | void;
11
+ private replyCb?: (buttonId: string) => Promise<void> | void;
12
+ constructor(id: string) { this.id = id; }
13
+ async connect(): Promise<void> {}
14
+ async send(chatId: string, payload: OutboundPayload): Promise<void> { this.sent.push({ chatId, payload }); }
15
+ onMessage(cb: (msg: NormalizedMessage) => void): void { this.messageCb = cb; }
16
+ onReply(cb: (buttonId: string) => void): void { this.replyCb = cb; }
17
+ /** 测试助手:返回处理器 Promise,测试 await 以确保 async 接线(upsert→sendMessage / catch 兜底)跑完 */
18
+ emit(msg: NormalizedMessage): Promise<void> | void { return this.messageCb?.(msg); }
19
+ click(buttonId: string): Promise<void> | void { return this.replyCb?.(buttonId); }
20
+ }
21
+
22
+ /** 假 DSH:记录调用。 */
23
+ function fakeClient() {
24
+ const upserts: Array<{ platform: string; channel: string; user: string }> = [];
25
+ const messages: Array<{ sessionId: string; text: string }> = [];
26
+ const approvals: Array<{ reqId: string; decision: string }> = [];
27
+ const client = {
28
+ upsertSession: async (req: { platform: string; channel: string; user: string }) => {
29
+ upserts.push(req);
30
+ return { sessionId: `${req.platform}:${req.channel}:${req.user}` };
31
+ },
32
+ sendMessage: async (sessionId: string, req: { text: string }) => {
33
+ messages.push({ sessionId, text: req.text });
34
+ return { runId: 'r1' };
35
+ },
36
+ resolveApproval: async (reqId: string, decision: 'approve' | 'reject') => {
37
+ approvals.push({ reqId, decision });
38
+ return { ok: true };
39
+ },
40
+ // wireAdapter 末尾会订阅事件流(client.connect),假客户端需实现完整接口
41
+ connect: async () => () => undefined,
42
+ } as unknown as GatewayClient;
43
+ return { client, upserts, messages, approvals };
44
+ }
45
+
46
+ describe('wireAdapter(多适配器装配核心)', () => {
47
+ it('白名单拦截并回错误文本', async () => {
48
+ const adapter = new FakeAdapter('telegram');
49
+ const { client } = fakeClient();
50
+ await wireAdapter(adapter, client, { allowlist: ['telegram:111:222'] });
51
+
52
+ await adapter.emit({ chatId: '999', userId: '999', text: 'hi' });
53
+ expect(adapter.sent[0].payload.text).toContain('⛔');
54
+ });
55
+
56
+ it('白名单内消息 → upsert + sendMessage', async () => {
57
+ const adapter = new FakeAdapter('telegram');
58
+ const { client, upserts, messages } = fakeClient();
59
+ await wireAdapter(adapter, client, { allowlist: ['telegram:111:222'] });
60
+
61
+ await adapter.emit({ chatId: '111', userId: '222', text: 'hello' });
62
+ expect(upserts).toEqual([{ platform: 'telegram', channel: '111', user: '222' }]);
63
+ expect(messages).toEqual([{ sessionId: 'telegram:111:222', text: 'hello' }]);
64
+ });
65
+
66
+ it('按钮点击 → resolveApproval', async () => {
67
+ const adapter = new FakeAdapter('discord');
68
+ const { client, approvals } = fakeClient();
69
+ await wireAdapter(adapter, client, { allowlist: [] });
70
+
71
+ await adapter.click('approve:r1');
72
+ expect(approvals).toEqual([{ reqId: 'r1', decision: 'approve' }]);
73
+ });
74
+
75
+ it('DSH 调用失败 → 回错误文本(不崩溃)', async () => {
76
+ const adapter = new FakeAdapter('slack');
77
+ const client = {
78
+ upsertSession: async () => { throw new Error('dsh down'); },
79
+ connect: async () => () => undefined,
80
+ } as unknown as GatewayClient;
81
+ await wireAdapter(adapter, client, { allowlist: [] });
82
+
83
+ await adapter.emit({ chatId: 'C1', userId: 'U1', text: 'hi' });
84
+ expect(adapter.sent[0].payload.text).toContain('❌');
85
+ });
86
+ });
@@ -0,0 +1,29 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { planOutbound } from '../src/index.js';
3
+ import type { ServerEvent } from '@dsh-overdrive/sdk';
4
+
5
+ describe('planOutbound(事件 → 平台输出)', () => {
6
+ it('message.complete → 纯文本', () => {
7
+ const ev: ServerEvent = { type: 'message.complete', sessionId: 'cli:cli:local', ts: 1, text: '结果' };
8
+ expect(planOutbound(ev)?.payload).toEqual({ text: '结果' });
9
+ });
10
+
11
+ it('trajectory.step → 带图标的轨迹行', () => {
12
+ const ev: ServerEvent = { type: 'trajectory.step', sessionId: 'cli:cli:local', ts: 1, step: { kind: 'tool', label: 'grep' } };
13
+ expect(planOutbound(ev)?.payload.text).toBe('🛠️ grep');
14
+ });
15
+
16
+ it('approval.request → 文本 + 同意/拒绝两个按钮', () => {
17
+ const ev: ServerEvent = { type: 'approval.request', sessionId: 'cli:cli:local', ts: 1, reqId: 'r1', summary: '删除文件', timeoutMs: 60000 };
18
+ const out = planOutbound(ev)!;
19
+ expect(out.payload.text).toContain('删除文件');
20
+ expect(out.payload.buttons).toHaveLength(2);
21
+ expect(out.payload.buttons![0].id).toBe('approve:r1');
22
+ expect(out.payload.buttons![1].id).toBe('reject:r1');
23
+ });
24
+
25
+ it('message.delta 不输出(MVP 等 complete)', () => {
26
+ const ev: ServerEvent = { type: 'message.delta', sessionId: 'cli:cli:local', ts: 1, text: '…' };
27
+ expect(planOutbound(ev)).toBeNull();
28
+ });
29
+ });
@@ -0,0 +1,21 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { Allowlist, buildSessionKey } from '../src/session.js';
3
+
4
+ describe('buildSessionKey', () => {
5
+ it('用 adapterId + chatId + userId 拼会话键', () => {
6
+ expect(buildSessionKey('whatsapp', { chatId: '60123', userId: '60123' })).toBe('whatsapp:60123:60123');
7
+ });
8
+ });
9
+
10
+ describe('Allowlist', () => {
11
+ it('空列表放行所有(开发模式)', () => {
12
+ const allow = new Allowlist([]);
13
+ expect(allow.allows('anything:any:any')).toBe(true);
14
+ });
15
+
16
+ it('非空列表只放行白名单条目', () => {
17
+ const allow = new Allowlist(['whatsapp:60123:60123']);
18
+ expect(allow.allows('whatsapp:60123:60123')).toBe(true);
19
+ expect(allow.allows('whatsapp:99999:99999')).toBe(false);
20
+ });
21
+ });
@@ -0,0 +1,41 @@
1
+ import { afterEach, describe, expect, it } from 'vitest';
2
+ import { createStatusServer } from '../src/status.js';
3
+ import type { Adapter } from '../src/adapter.js';
4
+ import { GatewayClient } from '@dsh-overdrive/sdk';
5
+
6
+ describe('createStatusServer', () => {
7
+ let server: ReturnType<typeof createStatusServer> | undefined;
8
+ let port = 0;
9
+ afterEach(async () => { await server?.close(); server = undefined; });
10
+
11
+ async function start(fakeAdapters: Adapter[]): Promise<string> {
12
+ const client = {
13
+ health: async () => ({ status: 'ok' as const, version: '0.1.0' }),
14
+ } as unknown as GatewayClient;
15
+ server = createStatusServer({ adapters: fakeAdapters, client, version: '0.1.0' });
16
+ port = await server.listen(0);
17
+ return `http://127.0.0.1:${port}`;
18
+ }
19
+
20
+ it('/api/status 返回 dsh 健康与适配器状态', async () => {
21
+ const url = await start([
22
+ { id: 'telegram', status: () => ({ connected: true }) },
23
+ { id: 'whatsapp', status: () => ({ connected: false }) },
24
+ ] as unknown as Adapter[]);
25
+ const res = await fetch(`${url}/api/status`);
26
+ expect(res.status).toBe(200);
27
+ const body = await res.json();
28
+ expect(body.dsh.status).toBe('ok');
29
+ expect(body.adapters).toEqual([
30
+ { id: 'telegram', connected: true },
31
+ { id: 'whatsapp', connected: false },
32
+ ]);
33
+ });
34
+
35
+ it('GET / 返回 HTML 控制台页', async () => {
36
+ const url = await start([]);
37
+ const res = await fetch(`${url}/`);
38
+ expect(res.status).toBe(200);
39
+ expect((await res.text())).toContain('dsh-overdrive');
40
+ });
41
+ });
@@ -0,0 +1,162 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { DeltaTracker, planOutbound, wireAdapter } from '../src/index.js';
3
+ import { HELP_TEXT } from '../src/commands.js';
4
+ import { GatewayClient, type ServerEvent } from '@dsh-overdrive/sdk';
5
+ import type { Adapter, NormalizedMessage, OutboundPayload } from '../src/adapter.js';
6
+
7
+ describe('DeltaTracker(message.delta → 打字指示,complete → 终稿)', () => {
8
+ it('首个 delta 触发 typing,重复 delta 不重复触发', () => {
9
+ const t = new DeltaTracker();
10
+ const typings: string[] = [];
11
+ const outputs: string[] = [];
12
+ t.onDelta('s1', () => typings.push('s1'));
13
+ t.onDelta('s1', () => typings.push('s1'));
14
+ expect(typings).toEqual(['s1']);
15
+ void outputs;
16
+ });
17
+
18
+ it('complete 后同会话下一个 turn 的 delta 可再次触发 typing', () => {
19
+ const t = new DeltaTracker();
20
+ const typings: string[] = [];
21
+ t.onDelta('s1', () => typings.push('s1'));
22
+ t.onComplete('s1');
23
+ t.onDelta('s1', () => typings.push('s1'));
24
+ expect(typings).toEqual(['s1', 's1']);
25
+ });
26
+ });
27
+
28
+ describe('planOutbound(trajectory.summary 摘要卡片渲染)', () => {
29
+ it('trajectory.summary → formatTrajectorySummary 文本', () => {
30
+ const ev: ServerEvent = {
31
+ type: 'trajectory.summary', sessionId: 'cli:cli:local', ts: 1,
32
+ steps: [{ kind: 'thought', label: '分析' }, { kind: 'tool', label: 'bash' }],
33
+ };
34
+ const out = planOutbound(ev)!;
35
+ expect(out.payload.text).toContain('📋 轨迹(2 步)');
36
+ expect(out.payload.text).toContain('🧠 分析');
37
+ expect(out.payload.text).toContain('🛠️ bash');
38
+ });
39
+ });
40
+
41
+ /** 可编程 FakeAdapter(带 sendTyping 探测)。 */
42
+ class FakeAdapter implements Adapter {
43
+ readonly id: string;
44
+ readonly sent: Array<{ chatId: string; payload: OutboundPayload }> = [];
45
+ readonly typings: string[] = [];
46
+ private messageCb?: (msg: NormalizedMessage) => Promise<void> | void;
47
+ private replyCb?: (buttonId: string) => Promise<void> | void;
48
+ constructor(id: string) { this.id = id; }
49
+ async connect(): Promise<void> {}
50
+ async send(chatId: string, payload: OutboundPayload): Promise<void> { this.sent.push({ chatId, payload }); }
51
+ async sendTyping(chatId: string): Promise<void> { this.typings.push(chatId); }
52
+ onMessage(cb: (msg: NormalizedMessage) => void): void { this.messageCb = cb; }
53
+ onReply(cb: (buttonId: string) => void): void { this.replyCb = cb; }
54
+ emit(msg: NormalizedMessage): Promise<void> | void { return this.messageCb?.(msg); }
55
+ }
56
+
57
+ /** 假 DSH 客户端:可编程事件推流 + 记录调用。 */
58
+ function fakeClient() {
59
+ const createTasks: Array<{ sessionId: string; kind: string; prompt: string; schedule?: string }> = [];
60
+ const resets: string[] = [];
61
+ let eventCb: ((ev: ServerEvent) => void) | undefined;
62
+ const client = {
63
+ upsertSession: async (req: { platform: string; channel: string; user: string }) =>
64
+ ({ sessionId: `${req.platform}:${req.channel}:${req.user}` }),
65
+ sendMessage: async () => ({ runId: 'r1' }),
66
+ resolveApproval: async () => ({ ok: true }),
67
+ createTask: async (req: { sessionId: string; kind: 'subagent' | 'cron'; prompt: string; schedule?: string }) => {
68
+ createTasks.push(req);
69
+ return { taskId: 't1' };
70
+ },
71
+ resetSession: async (sessionId: string) => { resets.push(sessionId); return { ok: true }; },
72
+ connect: async (cb: (ev: ServerEvent) => void) => { eventCb = cb; return () => undefined; },
73
+ };
74
+ const push = (ev: ServerEvent): void => eventCb?.(ev);
75
+ return { client, createTasks, resets, push } as unknown as {
76
+ client: GatewayClient; createTasks: typeof createTasks; resets: string[];
77
+ push: (ev: ServerEvent) => void;
78
+ };
79
+ }
80
+
81
+ describe('wireAdapter(命令分发 + delta 打字指示 + 轨迹聚合接线)', () => {
82
+ it('message.delta → sendTyping 一次;complete 后下一 turn 再触发', async () => {
83
+ const adapter = new FakeAdapter('cli');
84
+ const { client, push } = fakeClient();
85
+ await wireAdapter(adapter, client, { allowlist: [] });
86
+
87
+ push({ type: 'message.delta', sessionId: 'cli:cli:local', ts: 1, text: '…' });
88
+ push({ type: 'message.delta', sessionId: 'cli:cli:local', ts: 2, text: '…' });
89
+ expect(adapter.typings).toEqual(['cli']); // sendTyping 目标是 chatId(无消息时回退到 channel)
90
+ expect(adapter.sent).toHaveLength(0); // delta 不产出文本
91
+
92
+ push({ type: 'message.complete', sessionId: 'cli:cli:local', ts: 3, text: '结果' });
93
+ push({ type: 'message.delta', sessionId: 'cli:cli:local', ts: 4, text: '…' });
94
+ expect(adapter.typings).toEqual(['cli', 'cli']);
95
+ });
96
+
97
+ it('trajectory.step 不实时输出,idle 时以 trajectory.summary 摘要输出', async () => {
98
+ const adapter = new FakeAdapter('cli');
99
+ const { client, push } = fakeClient();
100
+ await wireAdapter(adapter, client, { allowlist: [] });
101
+
102
+ push({ type: 'agent.status', sessionId: 'cli:cli:local', ts: 1, status: 'busy' });
103
+ push({ type: 'trajectory.step', sessionId: 'cli:cli:local', ts: 2, step: { kind: 'thought', label: '分析' } });
104
+ push({ type: 'trajectory.step', sessionId: 'cli:cli:local', ts: 3, step: { kind: 'tool', label: 'bash' } });
105
+ expect(adapter.sent).toHaveLength(0); // 单步不推
106
+
107
+ push({ type: 'agent.status', sessionId: 'cli:cli:local', ts: 4, status: 'idle' });
108
+ const summary = adapter.sent.find((s) => s.payload.text.includes('📋 轨迹'));
109
+ expect(summary?.payload.text).toContain('🧠 分析');
110
+ expect(summary?.payload.text).toContain('🛠️ bash');
111
+ });
112
+
113
+ it('/help → HELP_TEXT 原样输出', async () => {
114
+ const adapter = new FakeAdapter('cli');
115
+ const { client } = fakeClient();
116
+ await wireAdapter(adapter, client, { allowlist: [] });
117
+ await adapter.emit({ chatId: 'cli', userId: 'local', text: '/help' });
118
+ expect(adapter.sent[0].payload.text).toBe(HELP_TEXT);
119
+ });
120
+
121
+ it('/task 派子任务并回执;/cron 注册定时任务并回执', async () => {
122
+ const adapter = new FakeAdapter('cli');
123
+ const { client, createTasks } = fakeClient();
124
+ await wireAdapter(adapter, client, { allowlist: [] });
125
+
126
+ await adapter.emit({ chatId: 'cli', userId: 'local', text: '/task 调研竞品' });
127
+ expect(createTasks).toContainEqual({ sessionId: 'cli:cli:local', kind: 'subagent', prompt: '调研竞品' });
128
+ expect(adapter.sent.at(-1)!.payload.text).toContain('🤖 子任务已派出');
129
+
130
+ await adapter.emit({ chatId: 'cli', userId: 'local', text: '/cron 0 8 * * * 每日汇报' });
131
+ expect(createTasks).toContainEqual({ sessionId: 'cli:cli:local', kind: 'cron', prompt: '每日汇报', schedule: '0 8 * * *' });
132
+ expect(adapter.sent.at(-1)!.payload.text).toContain('⏰ 定时任务已注册');
133
+ });
134
+
135
+ it('/new 走 resetSession 端点并回执;/trace 显示最近摘要,无则提示', async () => {
136
+ const adapter = new FakeAdapter('cli');
137
+ const { client, resets, push } = fakeClient();
138
+ await wireAdapter(adapter, client, { allowlist: [] });
139
+
140
+ await adapter.emit({ chatId: 'cli', userId: 'local', text: '/trace' });
141
+ expect(adapter.sent.at(-1)!.payload.text).toContain('暂无轨迹');
142
+
143
+ push({ type: 'agent.status', sessionId: 'cli:cli:local', ts: 1, status: 'busy' });
144
+ push({ type: 'trajectory.step', sessionId: 'cli:cli:local', ts: 2, step: { kind: 'thought', label: '分析' } });
145
+ push({ type: 'agent.status', sessionId: 'cli:cli:local', ts: 3, status: 'idle' });
146
+
147
+ await adapter.emit({ chatId: 'cli', userId: 'local', text: '/trace' });
148
+ expect(adapter.sent.at(-1)!.payload.text).toContain('🧠 分析');
149
+
150
+ await adapter.emit({ chatId: 'cli', userId: 'local', text: '/new' });
151
+ expect(resets).toEqual(['cli:cli:local']);
152
+ expect(adapter.sent.at(-1)!.payload.text).toContain('🆕 会话已重置');
153
+ });
154
+
155
+ it('/agents 返回简化回执', async () => {
156
+ const adapter = new FakeAdapter('cli');
157
+ const { client } = fakeClient();
158
+ await wireAdapter(adapter, client, { allowlist: [] });
159
+ await adapter.emit({ chatId: 'cli', userId: 'local', text: '/agents' });
160
+ expect(adapter.sent[0].payload.text).toContain('/task 派发');
161
+ });
162
+ });
@@ -0,0 +1,58 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { TrajectoryAggregator, formatTrajectorySummary } from '../src/trajectory.js';
3
+ import type { ServerEvent, TrajectoryStep } from '@dsh-overdrive/sdk';
4
+
5
+ // 注意:ServerEvent 联合类型尚无 trajectory.summary(Task 2 协议修改才加入),
6
+ // 故本文件对 summary 事件统一用结构断言 + as 断言,不修改 sdk 协议。
7
+ describe('TrajectoryAggregator', () => {
8
+ it('聚合 turn 内轨迹,turn 结束产出摘要', () => {
9
+ const agg = new TrajectoryAggregator();
10
+ const events: ServerEvent[] = [];
11
+ agg.onEvent({ type: 'agent.status', sessionId: 'cli:cli:local', ts: 1, status: 'busy' }, (ev) => events.push(ev));
12
+ agg.onEvent({ type: 'trajectory.step', sessionId: 'cli:cli:local', ts: 2, step: { kind: 'thought', label: '分析' } }, (ev) => events.push(ev));
13
+ agg.onEvent({ type: 'trajectory.step', sessionId: 'cli:cli:local', ts: 3, step: { kind: 'tool', label: 'bash' } }, (ev) => events.push(ev));
14
+ agg.onEvent({ type: 'agent.status', sessionId: 'cli:cli:local', ts: 4, status: 'idle' }, (ev) => events.push(ev));
15
+
16
+ const summary = events.find((e) => (e as { type: string }).type === 'trajectory.summary') as
17
+ | { type: 'trajectory.summary'; steps: TrajectoryStep[] }
18
+ | undefined;
19
+ expect(summary).toBeDefined();
20
+ // 直接比较结构(Task 2 的协议变体含 steps,渲染由 formatTrajectorySummary 负责)
21
+ expect(summary!.steps).toEqual([
22
+ { kind: 'thought', label: '分析' },
23
+ { kind: 'tool', label: 'bash' },
24
+ ]);
25
+ });
26
+
27
+ it('busy 状态在摘要前透传,idle 后清空缓冲', () => {
28
+ const agg = new TrajectoryAggregator();
29
+ const events: ServerEvent[] = [];
30
+ agg.onEvent({ type: 'agent.status', sessionId: 'cli:cli:local', ts: 1, status: 'busy' }, (ev) => events.push(ev));
31
+ expect(events).toHaveLength(1);
32
+ expect(events[0].type).toBe('agent.status');
33
+
34
+ agg.onEvent({ type: 'agent.status', sessionId: 'cli:cli:local', ts: 2, status: 'idle' }, (ev) => events.push(ev));
35
+ expect(events).toHaveLength(2);
36
+ });
37
+
38
+ it('其他事件(message.complete 等)原样透传', () => {
39
+ const agg = new TrajectoryAggregator();
40
+ const events: ServerEvent[] = [];
41
+ agg.onEvent({ type: 'message.complete', sessionId: 's', ts: 1, text: '结果' }, (ev) => events.push(ev));
42
+ expect(events).toEqual([{ type: 'message.complete', sessionId: 's', ts: 1, text: '结果' }]);
43
+ });
44
+ });
45
+
46
+ describe('formatTrajectorySummary(摘要卡片渲染,Task 2 接线复用)', () => {
47
+ it('按 kind 渲染图标 + 标签,含步数标题', () => {
48
+ const text = formatTrajectorySummary([
49
+ { kind: 'thought', label: '分析' },
50
+ { kind: 'tool', label: 'bash' },
51
+ { kind: 'subagent', label: '子任务' },
52
+ ]);
53
+ expect(text).toContain('🧠 分析');
54
+ expect(text).toContain('🛠️ bash');
55
+ expect(text).toContain('🤖 子任务');
56
+ expect(text).toContain('📋 轨迹(3 步)');
57
+ });
58
+ });
package/tsconfig.json ADDED
@@ -0,0 +1,5 @@
1
+ {
2
+ "extends": "../../tsconfig.base.json",
3
+ "compilerOptions": { "outDir": "dist", "rootDir": "src" },
4
+ "include": ["src"]
5
+ }