@xmanrui/dsh-im 5.8.0 → 5.9.1

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.
Files changed (66) hide show
  1. package/README.en.md +45 -8
  2. package/README.md +56 -8
  3. package/docs/preset-workspaces.md +37 -0
  4. package/lib/client.js +66 -7
  5. package/lib/index.js +329 -326
  6. package/package.json +3 -1
  7. package/plugin-src/client/connection-error.js +1 -1
  8. package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
  9. package/plugin-src/host/channels/feishu/production.mjs +2 -1
  10. package/plugin-src/host/channels/matrix/production.mjs +2 -1
  11. package/plugin-src/host/channels/qq/production.mjs +2 -1
  12. package/plugin-src/host/channels/shared/binding-events.mjs +130 -0
  13. package/plugin-src/host/channels/shared/production.mjs +32 -3
  14. package/plugin-src/host/channels/slack/production.mjs +2 -1
  15. package/plugin-src/host/channels/wecom/production.mjs +2 -1
  16. package/plugin-src/host/channels/wecom-app/production.mjs +2 -1
  17. package/plugin-src/host/channels/weixin/production.mjs +2 -1
  18. package/plugin-src/host/channels/whatsapp/production.mjs +2 -1
  19. package/plugin-src/host/delivery-adapter.mjs +122 -1
  20. package/plugin-src/host/delivery-service.mjs +40 -0
  21. package/plugin-src/host/ds-bot-client.mjs +28 -2
  22. package/plugin-src/host/inbound-ttl-rpc.mjs +1 -1
  23. package/plugin-src/host/index.mjs +25 -2
  24. package/plugin-src/host/modern-harness-api.mjs +3 -0
  25. package/plugin-src/host/sidebar-settings.mjs +1 -2
  26. package/plugin-src/host/update-rpc.mjs +1 -1
  27. package/plugin-src/management-rpc.mjs +25 -3
  28. package/scripts/telegram-menu-scopes.mjs +57 -0
  29. package/scripts/verify-interface-language.mjs +60 -15
  30. package/scripts/verify-lan-management.mjs +58 -5
  31. package/src/channels/dingtalk/dingtalk-bridge.mjs +2 -3
  32. package/src/channels/dingtalk/dingtalk-menu.mjs +4 -5
  33. package/src/channels/email/email-runtime.mjs +27 -8
  34. package/src/channels/email/transports/imap-smtp.mjs +21 -11
  35. package/src/channels/feishu/bridge.mjs +296 -13
  36. package/src/channels/feishu/feishu-cards.mjs +96 -25
  37. package/src/channels/qq/qq-menu.mjs +3 -4
  38. package/src/channels/shared/action-card.mjs +331 -0
  39. package/src/channels/shared/bot-workspace-store.mjs +123 -8
  40. package/src/channels/shared/command-catalog.mjs +20 -5
  41. package/src/channels/shared/conversation/describe.mjs +116 -0
  42. package/src/channels/shared/conversation-state-store.mjs +62 -0
  43. package/src/channels/shared/diagnostic-details.mjs +38 -0
  44. package/src/channels/shared/harness-approval.mjs +58 -13
  45. package/src/channels/shared/harness-client.mjs +13 -0
  46. package/src/channels/shared/harness-session-binding.mjs +13 -1
  47. package/src/channels/shared/i18n-en/diagnostics.mjs +6 -1
  48. package/src/channels/shared/i18n-en/feishu.mjs +9 -0
  49. package/src/channels/shared/i18n-en/shared-a.mjs +9 -0
  50. package/src/channels/shared/i18n-en/telegram.mjs +14 -0
  51. package/src/channels/shared/i18n-ru/diagnostics.mjs +10 -0
  52. package/src/channels/shared/i18n-ru/feishu.mjs +8 -0
  53. package/src/channels/shared/i18n-ru/shared-a.mjs +9 -0
  54. package/src/channels/shared/i18n-ru/telegram.mjs +14 -0
  55. package/src/channels/shared/model-command.mjs +5 -0
  56. package/src/channels/shared/preset-workspaces.mjs +48 -0
  57. package/src/channels/shared/qr-encoding-error.mjs +8 -2
  58. package/src/channels/shared/status-command.mjs +159 -0
  59. package/src/channels/shared/text-harness-bridge.mjs +86 -4
  60. package/src/channels/shared/workspace-command.mjs +20 -12
  61. package/src/channels/shared/workspace-session.mjs +30 -5
  62. package/src/channels/telegram/approval-card.mjs +379 -0
  63. package/src/channels/telegram/telegram-api.mjs +10 -1
  64. package/src/channels/telegram/telegram-bridge.mjs +7 -0
  65. package/src/channels/telegram/telegram-runtime.mjs +125 -13
  66. package/src/channels/wecom/wecom-bridge.mjs +5 -3
@@ -36,7 +36,11 @@ export const inject = [
36
36
  ];
37
37
 
38
38
  function channelConfig(config, name, deliveryService) {
39
- const channel = { ...(config.dshHome ? { dshHome: config.dshHome } : {}), ...config[name] };
39
+ const channel = {
40
+ ...(config.dshHome ? { dshHome: config.dshHome } : {}),
41
+ ...(config.groupByAgentPreset === undefined ? {} : { groupByAgentPreset: config.groupByAgentPreset }),
42
+ ...config[name],
43
+ };
40
44
  const withAuthority = config.rpcAuthority === undefined
41
45
  ? channel
42
46
  : { ...channel, rpcAuthority: config.rpcAuthority };
@@ -97,6 +101,21 @@ export function createImHostPlugin(internals = {}) {
97
101
  unavailableSessionSyncChannels: unavailableSessionSyncChannels.map((channel) => channel === 'wecomApp' ? 'wecom-app' : channel),
98
102
  dsBot: createDsBotClient(ctx),
99
103
  });
104
+ /** Sessions already reported, so the log stays one line per session. */
105
+ const describedSessions = new Set();
106
+ const describeConversationLogged = async (sessionId) => {
107
+ const described = await deliveryService.describeConversation(sessionId);
108
+ if (described && !describedSessions.has(sessionId)) {
109
+ describedSessions.add(sessionId);
110
+ const log = typeof ctx?.logger === 'function' ? ctx.logger(name) : (ctx?.logger ?? console);
111
+ try {
112
+ log?.info?.(`describeConversation session=${sessionId} chat=${described.conversationKey} sender=${described.senderId ?? '-'}`);
113
+ } catch {
114
+ // Logging must never break the lookup.
115
+ }
116
+ }
117
+ return described;
118
+ };
100
119
  if (typeof ctx?.provide === 'function') {
101
120
  ctx.provide('dshIm', Object.freeze({
102
121
  contractVersion: 1,
@@ -105,6 +124,10 @@ export function createImHostPlugin(internals = {}) {
105
124
  consumeInbound: (botId, options) => deliveryService.consumeInbound(botId, options),
106
125
  historyChecked: (botId, route, query, options) => deliveryService.historyChecked(botId, route, query, options),
107
126
  replyChecked: (botId, route, text, options) => deliveryService.replyChecked(botId, route, text, options),
127
+ describeConversation: (sessionId) => describeConversationLogged(sessionId),
128
+ // Prompt assembly is synchronous, so a caller that needs the identity
129
+ // before the first step cannot await the async variant.
130
+ describeConversationSync: (sessionId) => deliveryService.describeConversationSync(sessionId),
108
131
  describeBot: (botId) => deliveryService.describeBot(botId),
109
132
  sendChecked: (botId, targetId, text, options) => deliveryService.sendChecked(botId, targetId, text, options),
110
133
  send: (botId, targetId, text, options) => (
@@ -179,7 +202,7 @@ export function createImHostPlugin(internals = {}) {
179
202
  }
180
203
  }
181
204
  try {
182
- startUpdate(ctx);
205
+ startUpdate(ctx, { authority: config.rpcAuthority });
183
206
  } catch (error) {
184
207
  logger.error?.('[dsh-im] failed to activate update management; continuing with channels', error);
185
208
  }
@@ -225,6 +225,9 @@ class ModernHarnessApi {
225
225
  describe: (request) => rpcResult(request, () => ({ ready: true, transport: 'typert' })),
226
226
  });
227
227
  this.workspace = Object.freeze({
228
+ rename: (request, signal) => rpcResult(request, () => this.#invoke(
229
+ 'workspace', 'rename', { request: request.payload }, signal,
230
+ )),
228
231
  list: (request, signal) => rpcResult(request, () => this.#workspaceList(signal)),
229
232
  create: (request, signal) => rpcResult(request, () => this.#invoke(
230
233
  'workspace', 'create', { request: request.payload }, signal,
@@ -106,8 +106,7 @@ export function createSidebarSettingsRpcHandler({ config = {}, store, configured
106
106
  }
107
107
 
108
108
  export function installSidebarSettingsRpc(ctx, { config = {} } = {}) {
109
- // Visibility follows ordinary channel management authority. Keep it separate
110
- // from the general settings route, whose TTL operations remain loopback-only.
109
+ // Visibility follows the same authority as channels and general settings.
111
110
  return registerManagementRpc(ctx, SIDEBAR_SETTINGS_RPC_CHANNEL,
112
111
  createSidebarSettingsRpcHandler({ config }), { authority: config.rpcAuthority });
113
112
  }
@@ -44,7 +44,7 @@ export function installUpdateRpc(ctx, options = {}) {
44
44
  const runtime = options.runtime ?? createUpdateRuntime({ ctx, moduleUrl: import.meta.url });
45
45
  const service = options.service ?? createUpdateService({ runtime });
46
46
  const dispose = registerManagementRpc(ctx, UPDATE_RPC_CHANNEL, createUpdateRpcHandler(service), {
47
- authority: 'loopback',
47
+ authority: options.authority,
48
48
  });
49
49
  ctx.effect(() => () => service.close(), 'dsh-im: close update installer');
50
50
  return dispose;
@@ -71,16 +71,38 @@ export function registerManagementRpc(ctx, channel, handler, { authority } = {})
71
71
  });
72
72
  }
73
73
 
74
+ function managementHttpStatus(cause, endpoint) {
75
+ if (Number.isInteger(cause?.status) && cause.status >= 100 && cause.status <= 599) return cause.status;
76
+ // DSH 0.2.x throws a plain Error for HTTP failures. Accept only its exact
77
+ // transport message for this request, never an arbitrary embedded number.
78
+ const prefix = `transport failure for /api/${endpoint}: HTTP `;
79
+ if (!endpoint || typeof cause?.message !== 'string' || !cause.message.startsWith(prefix)) return undefined;
80
+ const status = Number(cause.message.slice(prefix.length));
81
+ return Number.isInteger(status) && status >= 100 && status <= 599 && cause.message === `${prefix}${status}`
82
+ ? status : undefined;
83
+ }
84
+
85
+ function managementErrorMessage(status) {
86
+ if (status === 401) return 'DSH 登录状态无效或已过期,请通过有效启动链接重新登录。';
87
+ if (status === 403) return 'DSH 拒绝了当前管理请求(HTTP 403)。请检查访问权限、可信地址配置及代理设置;若启用了仅本机访问,请按该限制访问。';
88
+ if (status === 404) return 'DSH 管理接口不存在(HTTP 404),请检查 Host 与插件版本及代理路径,重启后重试。';
89
+ if (status >= 500) return 'DSH 管理服务暂时异常,请检查服务状态或稍后重试。';
90
+ return 'DSH 管理请求失败,请检查服务状态和网络连接后重试。';
91
+ }
92
+
74
93
  /** Keep channel UI callers unchanged while using DSH's native correlation and response validation. */
75
94
  export async function callManagementRpc(connection, channel, method, payload, signal) {
95
+ let endpoint;
76
96
  try {
77
- return await connection.rpc.call('/api', rpcEndpoint(channel), { method, payload }, signal);
97
+ endpoint = rpcEndpoint(channel);
98
+ return await connection.rpc.call('/api', endpoint, { method, payload }, signal);
78
99
  } catch (cause) {
79
100
  if (signal?.aborted || cause?.name === 'AbortError') throw cause;
80
- const error = new Error('无法访问 DSH 管理接口,请检查 DSH 连接或重新登录后重试。', { cause });
101
+ const httpStatus = managementHttpStatus(cause, endpoint);
102
+ const error = new Error(managementErrorMessage(httpStatus), { cause });
81
103
  error.code = 'management-unreachable';
82
104
  error.details = { operation: method, stage: 'management.request', occurredAt: new Date().toISOString(),
83
- ...(Number.isInteger(cause?.status) && cause.status >= 100 && cause.status <= 599 ? { httpStatus: cause.status } : {}),
105
+ ...(httpStatus === undefined ? {} : { httpStatus }),
84
106
  };
85
107
  throw error;
86
108
  }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Scoped Telegram command-menu bookkeeping for the live acceptance script.
3
+ *
4
+ * The bot registers commands per BotCommandScope (see
5
+ * src/channels/telegram/telegram-runtime.mjs). An acceptance script that saved,
6
+ * polled and restored only the default scope would (a) never see the menu the
7
+ * plugin now writes into `all_private_chats`, and (b) restore an old default
8
+ * list that the plugin had already cleared. Both the save and the restore must
9
+ * therefore cover all three scopes.
10
+ *
11
+ * The helpers are pure wrappers around a `callTelegram(method, payload)`
12
+ * function so they can be unit-tested without any network access.
13
+ */
14
+ import { TELEGRAM_COMMAND_MENU_SCOPES } from '../src/channels/telegram/telegram-runtime.mjs';
15
+
16
+ export const DEFAULT_COMMAND_SCOPE = null;
17
+ export const PRIVATE_COMMAND_SCOPE = TELEGRAM_COMMAND_MENU_SCOPES.private;
18
+ export const GROUP_COMMAND_SCOPE = TELEGRAM_COMMAND_MENU_SCOPES.group;
19
+
20
+ /** Every scope the plugin may write, in registration order. */
21
+ export const VERIFY_COMMAND_SCOPES = Object.freeze([
22
+ Object.freeze({ name: 'default', scope: DEFAULT_COMMAND_SCOPE }),
23
+ Object.freeze({ name: 'private', scope: PRIVATE_COMMAND_SCOPE }),
24
+ Object.freeze({ name: 'group', scope: GROUP_COMMAND_SCOPE }),
25
+ ]);
26
+
27
+ export function commandPayloadFor(scope) {
28
+ return scope ? { scope } : {};
29
+ }
30
+
31
+ /** Snapshot every scope the plugin can touch, so the original state can be restored. */
32
+ export async function saveScopedMenus(callTelegram) {
33
+ const saved = new Map();
34
+ for (const { name, scope } of VERIFY_COMMAND_SCOPES) {
35
+ saved.set(name, await callTelegram('getMyCommands', commandPayloadFor(scope)));
36
+ }
37
+ return saved;
38
+ }
39
+
40
+ /**
41
+ * Restore a snapshot. Scoped lists go first and the default scope goes last:
42
+ * if a restore fails midway, a leftover scoped menu still wins over a partially
43
+ * restored default scope, which is the safer failure direction.
44
+ */
45
+ export async function restoreScopedMenus(callTelegram, saved) {
46
+ for (const { name, scope } of [...VERIFY_COMMAND_SCOPES].reverse()) {
47
+ const commands = saved.get(name) ?? [];
48
+ if (commands.length > 0) {
49
+ await callTelegram('setMyCommands', {
50
+ commands,
51
+ ...commandPayloadFor(scope),
52
+ });
53
+ } else {
54
+ await callTelegram('deleteMyCommands', commandPayloadFor(scope));
55
+ }
56
+ }
57
+ }
@@ -8,8 +8,13 @@
8
8
  * user-settings document.
9
9
  *
10
10
  * Set DSH_IM_TELEGRAM_TOKEN to additionally bind a real bot and assert the
11
- * command menu Telegram itself stores. That step is skipped without a token,
12
- * and it restores the bot's original menu when it finishes.
11
+ * command menu Telegram itself stores. That step is skipped without a token.
12
+ * The plugin registers its menu per BotCommandScope, so the live check saves,
13
+ * polls and restores all three scopes (default, all_private_chats,
14
+ * all_group_chats); polling only the default scope would wait forever.
15
+ *
16
+ * Offline: `node scripts/verify-interface-language.mjs --check-scopes` prints
17
+ * the scope plan and exits without a Harness checkout, network or token.
13
18
  */
14
19
  import assert from 'node:assert/strict';
15
20
  import { spawn } from 'node:child_process';
@@ -18,11 +23,34 @@ import { request as httpRequest } from 'node:http';
18
23
  import { tmpdir } from 'node:os';
19
24
  import { dirname, join, resolve } from 'node:path';
20
25
 
26
+ import {
27
+ GROUP_COMMAND_SCOPE,
28
+ PRIVATE_COMMAND_SCOPE,
29
+ VERIFY_COMMAND_SCOPES,
30
+ restoreScopedMenus,
31
+ saveScopedMenus,
32
+ } from './telegram-menu-scopes.mjs';
33
+
21
34
  const harnessRoot = process.argv[2];
22
- if (!harnessRoot || process.argv.includes('--help')) {
35
+ if (process.argv.includes('--help')) {
23
36
  console.log('Usage: node scripts/verify-interface-language.mjs /path/to/built/deepseek-harness');
37
+ console.log(' node scripts/verify-interface-language.mjs --check-scopes (offline scope self-check)');
24
38
  console.log(' DSH_IM_TELEGRAM_TOKEN=<token> node scripts/verify-interface-language.mjs ... (adds the live menu check)');
25
- process.exit(harnessRoot ? 0 : 1);
39
+ process.exit(0);
40
+ }
41
+ if (process.argv.includes('--check-scopes')) {
42
+ console.table(VERIFY_COMMAND_SCOPES.map(({ name, scope }) => ({
43
+ scope: name,
44
+ payload: JSON.stringify(scope ? { scope } : {}),
45
+ })));
46
+ console.log(`Offline self-check passed: ${VERIFY_COMMAND_SCOPES.length} Telegram command scopes`
47
+ + ' (default/private/group) are saved, polled and restored.');
48
+ process.exit(0);
49
+ }
50
+ if (!harnessRoot) {
51
+ console.log('Usage: node scripts/verify-interface-language.mjs /path/to/built/deepseek-harness');
52
+ console.log(' node scripts/verify-interface-language.mjs --check-scopes (offline scope self-check)');
53
+ process.exit(1);
26
54
  }
27
55
  const pluginRoot = resolve(import.meta.dirname, '..');
28
56
  await access(join(pluginRoot, 'lib/index.js'));
@@ -56,7 +84,7 @@ async function resolveHarness(root) {
56
84
  const harness = await resolveHarness(harnessRoot);
57
85
  const cli = harness.cli;
58
86
  const botToken = process.env.DSH_IM_TELEGRAM_TOKEN;
59
- let telegramMenu;
87
+ let savedMenus;
60
88
  const directory = await mkdtemp(join(tmpdir(), 'dsh-im-language-test-'));
61
89
  const home = join(directory, 'home');
62
90
  const profile = join(home, 'profiles/web');
@@ -264,7 +292,9 @@ try {
264
292
  record('the language route refuses malformed payloads', '4 cases');
265
293
 
266
294
  if (botToken) {
267
- telegramMenu = await telegram('getMyCommands');
295
+ // The plugin writes per scope; save every scope it may touch before binding
296
+ // so the original state can be restored exactly.
297
+ savedMenus = await saveScopedMenus(telegram);
268
298
  const bound = await rpc(browser, 'telegram', 'bot.bind-credentials', { token: botToken });
269
299
  assert.equal(bound.ok, true, 'the bot must bind');
270
300
  const botId = bound.value.bots.at(-1).botId;
@@ -272,16 +302,32 @@ try {
272
302
  const status = await rpc(browser, 'telegram', 'connection.status');
273
303
  return status.value?.bots?.find(item => item.botId === botId)?.connected ? true : null;
274
304
  });
275
- const english = await waitFor('Telegram stores the English menu', async () => {
276
- const commands = await telegram('getMyCommands');
305
+ const english = await waitFor('Telegram stores the English menu in the private-chat scope', async () => {
306
+ const commands = await telegram('getMyCommands', { scope: PRIVATE_COMMAND_SCOPE });
277
307
  const help = commands.find(item => item.command === 'help');
278
308
  return help && !HAN.test(help.description) ? commands : null;
279
309
  });
280
- record('Telegram stores the English command menu while DSH is English', `${english.length} commands`);
310
+ record('Telegram stores the English command menu in the private-chat scope',
311
+ `${english.length} commands`);
312
+
313
+ await waitFor('the legacy default-scope menu is cleared', async () => {
314
+ const commands = await telegram('getMyCommands');
315
+ return commands.length === 0 ? true : null;
316
+ });
317
+ record('the scoped registration clears the legacy default-scope menu', 'default scope empty');
318
+
319
+ const groupCommands = await telegram('getMyCommands', { scope: GROUP_COMMAND_SCOPE });
320
+ for (const directOnly of ['history', 'batch', 'send', 'cancel']) {
321
+ assert.equal(groupCommands.some(item => item.command === directOnly), false,
322
+ `the group menu must not advertise /${directOnly}`);
323
+ }
324
+ assert.equal(groupCommands.length, english.length - 4,
325
+ 'the group menu is the private menu without the four direct-chat-only commands');
326
+ record('the group scope omits direct-chat-only commands', `${groupCommands.length} commands`);
281
327
 
282
328
  await selectInterfaceLanguage('zh');
283
329
  const chinese = await waitFor('Telegram stores the Chinese menu after the switch', async () => {
284
- const commands = await telegram('getMyCommands');
330
+ const commands = await telegram('getMyCommands', { scope: PRIVATE_COMMAND_SCOPE });
285
331
  const help = commands.find(item => item.command === 'help');
286
332
  return help && HAN.test(help.description) ? commands : null;
287
333
  });
@@ -316,17 +362,16 @@ try {
316
362
  console.table(results);
317
363
  console.log(`Passed ${results.length} real HTTP checks against an unmodified DSH CLI (${harness.kind} layout).`);
318
364
  console.log(botToken
319
- ? 'The live Telegram menu was exercised and the bot\'s original menu was restored.'
365
+ ? 'The live Telegram menu was exercised; the bot\'s original menus were restored in all three scopes.'
320
366
  : 'Set DSH_IM_TELEGRAM_TOKEN to additionally assert the menu Telegram itself stores.');
321
367
  console.log('The temporary home contains no bot credentials and is removed after the server stops.');
322
368
  } finally {
323
369
  await stop();
324
- if (botToken && telegramMenu !== undefined) {
370
+ if (botToken && savedMenus !== undefined) {
325
371
  try {
326
- if (telegramMenu.length > 0) await telegram('setMyCommands', { commands: telegramMenu });
327
- else await telegram('deleteMyCommands');
372
+ await restoreScopedMenus(telegram, savedMenus);
328
373
  } catch {
329
- console.error('could not restore the bot\'s original command menu');
374
+ console.error('could not restore the bot\'s original command menus');
330
375
  }
331
376
  }
332
377
  await rm(directory, { recursive: true, force: true });
@@ -16,8 +16,8 @@ const pluginRoot = resolve(import.meta.dirname, '..');
16
16
  const cli = resolve(harnessRoot, 'apps/cli/lib/bin.js');
17
17
  await access(cli);
18
18
  await access(join(pluginRoot, 'lib/index.js'));
19
- // DSH 0.1.5 CLI intentionally permits only loopback listening. Exercise its
20
- // real HTTP carrier with a trusted LAN authority, while keeping TCP local.
19
+ // Exercise the original HTTP carrier with trusted LAN authorities while keeping
20
+ // TCP local. A second-device browser and a real proxy need separate validation.
21
21
  const lanIp = '192.168.1.100';
22
22
  const domain = 'dsh.example.test';
23
23
 
@@ -132,6 +132,47 @@ function expectStatus(name, response, expected, businessOk = false) {
132
132
  results.push({ check: name, status: response.status, result: 'PASS' });
133
133
  }
134
134
 
135
+ const settings = [
136
+ ['inbound-ttl', { ttlHours: 48 }],
137
+ ['image-input', { maxDownloadMb: 30, maxImageMb: 6, maxTotalMb: 20, maxImages: 20 }],
138
+ ['group-history', { groupHistoryRetentionDays: 21 }],
139
+ ];
140
+ const protectedMethods = [
141
+ ...settings.flatMap(([setting, value]) => [
142
+ ['dsh-im-settings', `settings.${setting}.get`, {}],
143
+ ['dsh-im-settings', `settings.${setting}.set`, value],
144
+ ]),
145
+ ['dsh-im-settings', 'settings.inbound-ttl.sweep', {}],
146
+ ['dsh-im', 'update.status', {}],
147
+ ['dsh-im', 'update.check', {}],
148
+ ['dsh-im', 'update.install', { checkId: 'not-confirmed', requestId: 'must-not-install' }],
149
+ ];
150
+
151
+ async function verifyDenied(name, browser, status, headers = {}) {
152
+ for (const [channel, method, payload] of protectedMethods) {
153
+ expectStatus(`${name}: ${method}`, await rpc(browser, channel, method, headers, payload), status);
154
+ }
155
+ }
156
+
157
+ async function verifySettings(name, browser, persisted = false) {
158
+ for (const [setting, value] of settings) {
159
+ const read = await rpc(browser, 'dsh-im-settings', `settings.${setting}.get`);
160
+ expectStatus(`${name}: ${setting} read`, read, 200, true);
161
+ if (persisted) assert.deepEqual(JSON.parse(read.body).result.value, value, `${name}: settings survive restart`);
162
+ const saved = await rpc(browser, 'dsh-im-settings', `settings.${setting}.set`, {}, value);
163
+ expectStatus(`${name}: ${setting} save`, saved, 200, true);
164
+ assert.deepEqual(JSON.parse(saved.body).result.value, value);
165
+ const reread = await rpc(browser, 'dsh-im-settings', `settings.${setting}.get`);
166
+ expectStatus(`${name}: ${setting} reread`, reread, 200, true);
167
+ assert.deepEqual(JSON.parse(reread.body).result.value, value);
168
+ }
169
+ expectStatus(`${name}: sweep empty test home`, await rpc(browser, 'dsh-im-settings', 'settings.inbound-ttl.sweep'), 200, true);
170
+ const update = await rpc(browser, 'dsh-im', 'update.status');
171
+ expectStatus(`${name}: update status`, update, 200, true);
172
+ assert.equal(JSON.parse(update.body).result.value.canInstall, false, 'status alone must never authorize installation');
173
+ expectStatus(`${name}: sidebar`, await rpc(browser, 'dsh-im-sidebar', 'settings.sidebar-entry.get'), 200, true);
174
+ }
175
+
135
176
  try {
136
177
  await mkdir(profile, { recursive: true });
137
178
  const packages = {
@@ -161,7 +202,7 @@ try {
161
202
  headers: { cookie: lan.cookie },
162
203
  }), 200);
163
204
  const channels = ['feishu', 'weixin', 'dingtalk', 'wecom', 'wecom-app', 'qq',
164
- 'slack', 'telegram', 'discord', 'whatsapp', 'imessage', 'matrix', 'office'];
205
+ 'slack', 'telegram', 'discord', 'whatsapp', 'imessage', 'email', 'matrix', 'office'];
165
206
  for (const channel of channels) {
166
207
  expectStatus(`LAN default: ${channel}`, await readyStatus(lan, channel), 200, true);
167
208
  }
@@ -171,8 +212,12 @@ try {
171
212
  expectStatus('LAN forged cookie', await rpc({ ...lan, cookie: 'invalid=invalid' }), 401);
172
213
  expectStatus('Untrusted Host', await rpc(lan, 'feishu', 'connection.status', { host: 'untrusted.invalid' }), 403);
173
214
  expectStatus('Cross-origin request', await rpc(lan, 'feishu', 'connection.status', { origin: 'https://untrusted.invalid' }), 403);
174
- expectStatus('LAN update remains local-only', await rpc(lan, 'dsh-im', 'update.status'), 403);
175
- expectStatus('LAN TTL remains local-only', await rpc(lan, 'dsh-im-settings', 'settings.inbound-ttl.get'), 403);
215
+ await verifyDenied('LAN anonymous management', anonymous, 401);
216
+ await verifyDenied('LAN forged cookie management', { ...lan, cookie: 'invalid=invalid' }, 401);
217
+ await verifyDenied('Untrusted management Host', lan, 403, { host: 'untrusted.invalid' });
218
+ await verifyDenied('Cross-origin management', lan, 403, { origin: 'https://untrusted.invalid' });
219
+ await verifyDenied('Cross-site management', lan, 403, { 'sec-fetch-site': 'cross-site' });
220
+ await verifySettings('LAN default', lan);
176
221
  const local = await login(launchUrl, '127.0.0.1');
177
222
  const localhost = await login(launchUrl, 'localhost');
178
223
  for (const browser of [local, localhost]) {
@@ -180,6 +225,7 @@ try {
180
225
  for (const channel of channels) {
181
226
  expectStatus(`${hostname} default: ${channel}`, await readyStatus(browser, channel), 200, true);
182
227
  }
228
+ await verifySettings(`${hostname} default`, browser);
183
229
  // Emulate a browser/proxy dropping the Origin port; this is a header-level
184
230
  // reproduction, not evidence that a particular browser emits that header.
185
231
  expectStatus(`${hostname} port-less Origin rejected`, await rpc(browser, 'dingtalk',
@@ -193,6 +239,7 @@ try {
193
239
  await rpc(await login(launchUrl, domain), 'dingtalk'), 403);
194
240
 
195
241
  await stop();
242
+ await writeFile(join(profile, 'cordis.patch.yml'), '- id: xmanrui-dsh-im\n config:\n rpcAuthority: trusted-host\n');
196
243
  const domainLaunchUrl = await start([lanIp, domain]);
197
244
  const trustedDomain = await login(domainLaunchUrl, domain);
198
245
  expectStatus('Trusted domain without login rejected',
@@ -200,17 +247,23 @@ try {
200
247
  for (const channel of channels) {
201
248
  expectStatus(`Domain with --trusted-host: ${channel}`, await readyStatus(trustedDomain, channel), 200, true);
202
249
  }
250
+ await verifySettings('Domain trusted-host', trustedDomain, true);
251
+ await verifyDenied('Domain anonymous management', { origin: trustedDomain.origin }, 401);
203
252
  const otherTrustedOrigin = new URL(trustedDomain.origin);
204
253
  otherTrustedOrigin.hostname = lanIp;
205
254
  expectStatus('Two trusted hosts still require matching Origin', await rpc(trustedDomain,
206
255
  'dingtalk', 'connection.status', { origin: otherTrustedOrigin.origin }), 403);
256
+ await verifyDenied('Trusted management hosts still require matching Origin', trustedDomain, 403, { origin: otherTrustedOrigin.origin });
207
257
 
208
258
  await stop();
209
259
  await writeFile(join(profile, 'cordis.patch.yml'), '- id: xmanrui-dsh-im\n config:\n rpcAuthority: loopback\n');
210
260
  const restrictedUrl = await start();
211
261
  expectStatus('Explicit loopback rejects LAN', await rpc(await login(restrictedUrl, lanIp)), 403);
262
+ await verifyDenied('Explicit loopback management rejects LAN', await login(restrictedUrl, lanIp), 403);
212
263
  expectStatus('Explicit loopback accepts 127.0.0.1', await readyStatus(await login(restrictedUrl, '127.0.0.1')), 200, true);
213
264
  expectStatus('Explicit loopback accepts localhost', await readyStatus(await login(restrictedUrl, 'localhost')), 200, true);
265
+ await verifySettings('Explicit loopback management 127.0.0.1', await login(restrictedUrl, '127.0.0.1'), true);
266
+ await verifySettings('Explicit loopback management localhost', await login(restrictedUrl, 'localhost'), true);
214
267
  console.table(results);
215
268
  console.log(`Passed ${results.length} real HTTP checks using loopback, LAN ${lanIp} and domain ${domain}.`);
216
269
  console.log('TCP connections stayed on loopback. This checks the original CLI, authentication and built plugin, not a second-device browser.');
@@ -30,7 +30,7 @@ import {
30
30
  isPresetCommand,
31
31
  runPresetCommand,
32
32
  } from '../shared/preset-command.mjs';
33
- import { runWorkspaceCommand } from '../shared/workspace-command.mjs';
33
+ import { conversationSessionWorkspace, runWorkspaceCommand } from '../shared/workspace-command.mjs';
34
34
  import { askInWorkspaceSession } from '../shared/workspace-session.mjs';
35
35
  import {
36
36
  captureContextEnhancement,
@@ -940,8 +940,7 @@ export class DingtalkHarnessBridge {
940
940
  });
941
941
  return;
942
942
  }
943
- const sessionWorkspace = typeof this.#harness.currentConversationWorkspace === 'function'
944
- ? this.#harness.currentConversationWorkspace(key) : this.#harness.currentWorkspace?.();
943
+ const sessionWorkspace = await conversationSessionWorkspace(this.#harness, key, { signal: this.#signal });
945
944
  if (entry.workspace !== this.#harness.currentWorkspace?.()
946
945
  || entry.sessionWorkspace !== sessionWorkspace
947
946
  || entry.sessionId !== this.#state.sessionFor(key)) {
@@ -1,5 +1,5 @@
1
1
  import { randomUUID } from 'node:crypto';
2
- import { workspacePathSnapshot } from '../shared/workspace-command.mjs';
2
+ import { conversationSessionWorkspace, workspacePathSnapshot } from '../shared/workspace-command.mjs';
3
3
  import { t } from '../shared/i18n.mjs';
4
4
 
5
5
  export const DINGTALK_MENU_TEMPLATE_ID = '9ca31362-e5b3-409c-a694-6993706a6004.schema';
@@ -19,9 +19,8 @@ const presetCommand = (id) => `/preset ${/^\d+$/u.test(id) ? 'id:' : ''}${id}`;
19
19
  // as a command supplied by the client or as a prompt for the model.
20
20
  export async function dingtalkMenuSnapshot(harness, state, key, signal) {
21
21
  const workspace = harness.currentWorkspace?.();
22
- const currentSessionWorkspace = () => typeof harness.currentConversationWorkspace === 'function'
23
- ? harness.currentConversationWorkspace(key) : harness.currentWorkspace?.();
24
- const sessionWorkspace = currentSessionWorkspace();
22
+ const currentSessionWorkspace = () => conversationSessionWorkspace(harness, key, { signal });
23
+ const sessionWorkspace = await currentSessionWorkspace();
25
24
  const sessionId = state.sessionFor(key);
26
25
  const options = { signal };
27
26
  const results = await Promise.allSettled([
@@ -36,7 +35,7 @@ export async function dingtalkMenuSnapshot(harness, state, key, signal) {
36
35
  ]);
37
36
  signal?.throwIfAborted();
38
37
  if (harness.currentWorkspace?.() !== workspace
39
- || currentSessionWorkspace() !== sessionWorkspace || state.sessionFor(key) !== sessionId) {
38
+ || await currentSessionWorkspace() !== sessionWorkspace || state.sessionFor(key) !== sessionId) {
40
39
  throw new Error(t('会话或工作区已变化,请重新发送 /m。'));
41
40
  }
42
41
  const [paths, listed, catalog, settings] = results.map((r) => r.status === 'fulfilled' ? r.value : null);
@@ -229,9 +229,28 @@ export function normalizeEmail(parsed, { address, state } = {}) {
229
229
  class EmailBotClient {
230
230
  #api;
231
231
  #signal;
232
- constructor(api, signal) {
232
+ #state;
233
+ constructor(api, signal, state = null) {
233
234
  this.#api = api;
234
235
  this.#signal = signal;
236
+ this.#state = state;
237
+ }
238
+
239
+ /**
240
+ * Record the RFC Message-ID of our own reply in the thread map.
241
+ *
242
+ * A client that quotes only the immediate parent (iOS Mail sends a
243
+ * one-entry References header) points its next reply at this id. Outgoing
244
+ * ids were never registered, so the resolver found nothing familiar and
245
+ * forked a brand-new session on every phone reply.
246
+ */
247
+ #rememberReply(target, sent) {
248
+ const parentId = parseMessageIds(target?.messageId)[0] ?? null;
249
+ const sentId = typeof sent?.messageId === 'string' ? sent.messageId : null;
250
+ if (!parentId || !sentId) return sent;
251
+ const conversation = this.#state?.conversationForThreadId?.(parentId) ?? null;
252
+ if (conversation) this.#state.rememberThreadId(sentId, conversation);
253
+ return sent;
235
254
  }
236
255
 
237
256
  async sendText(target, text) {
@@ -241,14 +260,14 @@ class EmailBotClient {
241
260
  error.code = 'invalid-target';
242
261
  throw error;
243
262
  }
244
- return this.#api.sendReply({
263
+ return this.#rememberReply(target, await this.#api.sendReply({
245
264
  to,
246
265
  subject: target.subject,
247
266
  text,
248
267
  inReplyTo: target.messageId,
249
268
  transportMessageId: target.transportMessageId,
250
269
  references: target.references,
251
- });
270
+ }));
252
271
  }
253
272
 
254
273
  sendTyping() {
@@ -271,7 +290,7 @@ class EmailBotClient {
271
290
  }
272
291
 
273
292
  async sendFile(target, file) {
274
- return this.#api.sendReply({
293
+ return this.#rememberReply(target, await this.#api.sendReply({
275
294
  to: target?.to,
276
295
  subject: target?.subject,
277
296
  text: '',
@@ -279,11 +298,11 @@ class EmailBotClient {
279
298
  transportMessageId: target?.transportMessageId,
280
299
  references: target?.references,
281
300
  attachments: [this.#attachmentFrom(file, 'attachment')],
282
- });
301
+ }));
283
302
  }
284
303
 
285
304
  async sendImage(target, image) {
286
- return this.#api.sendReply({
305
+ return this.#rememberReply(target, await this.#api.sendReply({
287
306
  to: target?.to,
288
307
  subject: target?.subject,
289
308
  text: '',
@@ -291,7 +310,7 @@ class EmailBotClient {
291
310
  transportMessageId: target?.transportMessageId,
292
311
  references: target?.references,
293
312
  attachments: [this.#attachmentFrom(image, 'image')],
294
- });
313
+ }));
295
314
  }
296
315
  }
297
316
 
@@ -460,7 +479,7 @@ export class EmailRuntime {
460
479
  await this.#state.setCursor(Math.max(0, tip - FIRST_CONNECT_WINDOW));
461
480
  }
462
481
  }
463
- const client = new EmailBotClient(api, this.#abortController.signal);
482
+ const client = new EmailBotClient(api, this.#abortController.signal, this.#state);
464
483
  this.#bridge = new EmailHarnessBridge({
465
484
  bot: client,
466
485
  harness: this.#harness,
@@ -34,7 +34,9 @@ export class ImapSmtpTransport {
34
34
 
35
35
  /** Open the IMAP connection and select the monitored mailbox. */
36
36
  async connect() {
37
- if (this.#imap) return;
37
+ if (this.#imap?.usable) return;
38
+ this.#imap?.close();
39
+ this.#imap = null;
38
40
  const client = new ImapFlow({
39
41
  host: this.#config.imapHost,
40
42
  port: this.#config.imapPort,
@@ -43,10 +45,20 @@ export class ImapSmtpTransport {
43
45
  logger: false,
44
46
  ...(this.#config.rejectUnauthorized === false ? { tls: { rejectUnauthorized: false } } : {}),
45
47
  });
46
- client.on('error', () => { /* surfaced by the caller's poll/connection state */ });
47
- await client.connect();
48
- await client.mailboxOpen(this.#config.mailbox ?? 'INBOX');
49
- this.#imap = client;
48
+ // The next poll reconnects after a socket closes. A late event from an
49
+ // old client must never discard its healthy replacement.
50
+ client.on('close', () => {
51
+ if (this.#imap === client) this.#imap = null;
52
+ });
53
+ client.on('error', () => client.close());
54
+ try {
55
+ await client.connect();
56
+ await client.mailboxOpen(this.#config.mailbox ?? 'INBOX');
57
+ this.#imap = client;
58
+ } catch (error) {
59
+ client.close();
60
+ throw error;
61
+ }
50
62
  }
51
63
 
52
64
  async disconnect() {
@@ -117,12 +129,10 @@ export class ImapSmtpTransport {
117
129
 
118
130
  /** Read one message's RFC822 source by UID. */
119
131
  async #fetchSource(uid) {
120
- try {
121
- const message = await this.#imap.fetchOne(String(uid), { source: true }, { uid: true });
122
- return message?.source ?? null;
123
- } catch {
124
- return null;
125
- }
132
+ // A failed read must fail the poll, otherwise a later message could move
133
+ // the cursor past this unread mail. A vanished message still returns null.
134
+ const message = await this.#imap.fetchOne(String(uid), { source: true }, { uid: true });
135
+ return message?.source ?? null;
126
136
  }
127
137
 
128
138
  /** Send a reply inside the originating thread. */