@xmanrui/dsh-im 5.6.0 → 5.8.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.
Files changed (41) hide show
  1. package/README.en.md +22 -6
  2. package/README.md +22 -6
  3. package/assets/sponsors/88api.jpg +0 -0
  4. package/lib/client.js +361 -159
  5. package/lib/index.js +323 -321
  6. package/package.json +1 -1
  7. package/plugin-src/client/channels/feishu/api.js +5 -0
  8. package/plugin-src/client/channels/feishu/conversation-directory-settings.js +73 -0
  9. package/plugin-src/client/channels/feishu/index.js +1 -0
  10. package/plugin-src/client/delivery-settings.js +13 -0
  11. package/plugin-src/client/i18n-ru.js +18 -0
  12. package/plugin-src/client/i18n.js +18 -0
  13. package/plugin-src/client/session-channel-logos.js +8 -0
  14. package/plugin-src/client/styles.js +6 -0
  15. package/plugin-src/client/workspace-editor.js +6 -5
  16. package/plugin-src/host/channels/feishu/rpc.mjs +25 -0
  17. package/plugin-src/host/channels/shared/workspace-rpc.mjs +2 -0
  18. package/plugin-src/host/delivery-suggestions.mjs +2 -0
  19. package/plugin-src/host/update-service.mjs +44 -13
  20. package/scripts/verify-package.mjs +17 -6
  21. package/src/channels/feishu/bridge.mjs +29 -12
  22. package/src/channels/feishu/feishu-runtime.mjs +13 -1
  23. package/src/channels/feishu/message-utils.mjs +1 -0
  24. package/src/channels/qq/markdown-reply.mjs +5 -2
  25. package/src/channels/qq/qq-bridge.mjs +41 -2
  26. package/src/channels/shared/bot-workspace-store.mjs +248 -0
  27. package/src/channels/shared/conversation-directory-ensure.mjs +46 -0
  28. package/src/channels/shared/conversation-directory.mjs +29 -0
  29. package/src/channels/shared/harness-client.mjs +72 -2
  30. package/src/channels/shared/i18n-en/diagnostics.mjs +2 -0
  31. package/src/channels/shared/i18n-en/shared-a.mjs +5 -0
  32. package/src/channels/shared/i18n-ru/diagnostics.mjs +2 -0
  33. package/src/channels/shared/i18n-ru/shared-a.mjs +5 -0
  34. package/src/channels/shared/message-failure.mjs +8 -0
  35. package/src/channels/shared/new-command.mjs +7 -0
  36. package/src/channels/shared/semantic/reply-reference.mjs +25 -5
  37. package/src/channels/shared/text-harness-bridge.mjs +3 -2
  38. package/src/channels/shared/workspace-command.mjs +22 -9
  39. package/src/channels/slack/slack-api.mjs +21 -5
  40. package/src/channels/slack/slack-runtime.mjs +69 -20
  41. package/src/channels/wecom/wecom-controller.mjs +89 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xmanrui/dsh-im",
3
- "version": "5.6.0",
3
+ "version": "5.8.0",
4
4
  "icon": "./assets/logo-plugin-message-link-gradient.webp",
5
5
  "description": "把微信、飞书、企微、钉钉、QQ、Telegram、WhatsApp、Slack、Discord、Matrix接入DSH。 Connect Telegram, WhatsApp, Slack, Discord, Matrix, WeChat, Feishu, WeCom, DingTalk, and QQ to DSH.",
6
6
  "keywords": [
@@ -17,6 +17,7 @@ import { normalizeContextEnhancementConfig } from "../../../../src/channels/shar
17
17
  import { normalizeFeishuStepPushMode, normalizeFeishuStepCardPanels } from "../../../../src/channels/feishu/step-push-mode.mjs";
18
18
  import { normalizeFeishuVoiceConfig } from "../../../../src/channels/feishu/voice-config.mjs";
19
19
  import { normalizeSlashPanelConfig } from "../../../../src/channels/feishu/slash-command-panel.mjs";
20
+ import { normalizeConversationDirectory } from "../../../../src/channels/shared/conversation-directory.mjs";
20
21
 
21
22
  export const FEISHU_RPC_CHANNEL = "/feishu";
22
23
 
@@ -32,6 +33,8 @@ export const FEISHU_ENDPOINTS = Object.freeze({
32
33
  disconnectBot: "bot.disconnect",
33
34
  deleteBot: "bot.delete",
34
35
  setWorkspace: "bot.workspace.set",
36
+ setConversationDirectory: "bot.conversation-directory.set",
37
+ setConversationDirectoryDefault: "bot.conversation-directory.default.set",
35
38
  setModel: SET_MODEL_ENDPOINT,
36
39
  setAgentPreset: "bot.preset.set",
37
40
  setContextEnhancement: "bot.context-enhancement.set",
@@ -224,6 +227,8 @@ export function normalizeBotConnection(value, fallbackBotId) {
224
227
  connected,
225
228
  configured: value.configured !== false,
226
229
  workspace: optionalString(value.workspace)?.slice(0, 4_096) ?? "",
230
+ conversationDirectory: normalizeConversationDirectory(value.conversationDirectory),
231
+ conversationDirectoryOverride: normalizeConversationDirectory(value.conversationDirectoryOverride),
227
232
  model: normalizeModelSelection(value.model),
228
233
  agentPreset: normalizeAgentPresetId(value.agentPreset),
229
234
  busyMessageMode: normalizeBusyMessageMode(value.busyMessageMode), contextEnhancement: normalizeContextEnhancementConfig(value.contextEnhancement),
@@ -0,0 +1,73 @@
1
+ import * as React from 'react';
2
+ import { h } from '../../i18n.js';
3
+ import { FEISHU_ENDPOINTS } from './api.js';
4
+ import { normalizeConversationDirectory, validateConversationDirectory } from '../../../../src/channels/shared/conversation-directory.mjs';
5
+
6
+ function ConfigForm({ title, value, inherited, busy, onSave, onClear }) {
7
+ const id = React.useId();
8
+ const [draft, setDraft] = React.useState(() => normalizeConversationDirectory(value) ?? { enabled: false, strategy: 'per-conversation', prefix: 'conv-' });
9
+ const [error, setError] = React.useState(null);
10
+ React.useEffect(() => {
11
+ setDraft(normalizeConversationDirectory(value) ?? { enabled: false, strategy: 'per-conversation', prefix: 'conv-' });
12
+ setError(null);
13
+ }, [value]);
14
+ const update = (key, next) => { setDraft((current) => ({ ...current, [key]: next })); setError(null); };
15
+ const save = async (event) => {
16
+ event.preventDefault();
17
+ try { setError(null); await onSave(validateConversationDirectory(draft)); }
18
+ catch (cause) { setError(cause.message); }
19
+ };
20
+ return h('form', { className: 'dim-conversationDirectoryForm', onSubmit: save, 'aria-label': title },
21
+ h('h3', null, title),
22
+ inherited ? h('p', { className: 'dim-botGeneralHelp' }, '继承渠道默认;保存后仅覆盖当前机器人。') : null,
23
+ h('label', { className: 'dim-botGeneralRow', htmlFor: `${id}-enabled` },
24
+ h('span', { className: 'dim-botGeneralTitle' }, '启用会话目录隔离'),
25
+ h('input', { id: `${id}-enabled`, type: 'checkbox', role: 'switch', className: 'dim-contextSwitch', checked: draft.enabled, disabled: busy, onChange: (event) => update('enabled', event.target.checked) })),
26
+ h('label', { className: 'dim-conversationDirectoryField', htmlFor: `${id}-strategy` },
27
+ h('span', null, '目录策略'),
28
+ h('select', { id: `${id}-strategy`, value: draft.strategy, disabled: busy, onChange: (event) => update('strategy', event.target.value) },
29
+ h('option', { value: 'per-conversation' }, '每个对话固定一个目录'),
30
+ h('option', { value: 'per-session' }, '每次新建会话使用新目录'))),
31
+ h('label', { className: 'dim-conversationDirectoryField', htmlFor: `${id}-prefix` },
32
+ h('span', null, '目录前缀'),
33
+ h('input', { id: `${id}-prefix`, value: draft.prefix, maxLength: 32, pattern: '[A-Za-z0-9_-]{1,32}', disabled: busy, onChange: (event) => update('prefix', event.target.value) })),
34
+ h('p', { className: 'dim-botGeneralHelp' }, '1–32 位字母、数字、下划线或连字符,默认为 conv-。'),
35
+ error ? h('p', { role: 'alert', className: 'dim-accessFeedback', 'data-tone': 'error' }, error) : null,
36
+ h('div', { className: 'dim-targetFormActions' },
37
+ h('button', { type: 'submit', className: 'dim-deliveryButton', disabled: busy }, '保存设置'),
38
+ onClear ? h('button', { type: 'button', className: 'dim-deliveryButton', disabled: busy, onClick: () => void onClear() }, title === '当前机器人' ? '恢复继承渠道默认' : '清除渠道默认') : null));
39
+ }
40
+
41
+ export function FeishuConversationDirectorySettingsPage({ account, rpcCall }) {
42
+ const [snapshot, setSnapshot] = React.useState(null);
43
+ const [busy, setBusy] = React.useState(false);
44
+ const [error, setError] = React.useState(null);
45
+ const load = React.useCallback(async () => {
46
+ setBusy(true); setError(null);
47
+ try {
48
+ const result = await rpcCall(FEISHU_ENDPOINTS.status, {});
49
+ if (result?.ok !== true) throw new Error(result?.error?.message ?? '无法读取会话目录设置。');
50
+ setSnapshot(result.value);
51
+ } catch (cause) { setError(cause.message); }
52
+ finally { setBusy(false); }
53
+ }, [rpcCall]);
54
+ React.useEffect(() => { void load(); }, [load]);
55
+ const save = async (endpoint, config) => {
56
+ setBusy(true); setError(null);
57
+ try {
58
+ const payload = endpoint === FEISHU_ENDPOINTS.setConversationDirectoryDefault ? { config } : { botId: account.botId, config };
59
+ const result = await rpcCall(endpoint, payload);
60
+ if (result?.ok !== true) throw new Error(result?.error?.message ?? '保存会话目录设置失败。');
61
+ setSnapshot(result.value);
62
+ } catch (cause) { setError(cause.message); }
63
+ finally { setBusy(false); }
64
+ };
65
+ const bot = snapshot?.bots?.find((item) => item.botId === account.botId);
66
+ return h('section', { className: 'dim-conversationDirectorySettings', 'aria-label': '会话目录隔离', 'aria-busy': busy },
67
+ h('p', { className: 'dim-botGeneralHelp' }, '让每个对话在自己的目录里工作,避免多人使用同一机器人时互相覆盖文件。默认关闭。'),
68
+ h('p', { className: 'dim-botGeneralHelp' }, '设置保存后对新会话生效。发送 /new 使用新设置;已有会话和旧目录中的文件保留。开启后无法手动修改工作区。'),
69
+ error ? h('p', { role: 'alert' }, error) : null,
70
+ bot ? h(React.Fragment, null,
71
+ h(ConfigForm, { key: `bot-${account.botId}`, title: '当前机器人', value: bot.conversationDirectoryOverride ?? bot.conversationDirectory, inherited: bot.conversationDirectoryOverride == null, busy, onSave: (config) => save(FEISHU_ENDPOINTS.setConversationDirectory, config), onClear: () => save(FEISHU_ENDPOINTS.setConversationDirectory, null) }),
72
+ h(ConfigForm, { key: `default-${JSON.stringify(snapshot.conversationDirectory)}`, title: '当前类型全部机器人会话目录隔离', value: snapshot.conversationDirectory, busy, onSave: (config) => save(FEISHU_ENDPOINTS.setConversationDirectoryDefault, config), onClear: () => save(FEISHU_ENDPOINTS.setConversationDirectoryDefault, null) })) : null);
73
+ }
@@ -649,6 +649,7 @@ export function BotCard({
649
649
  },
650
650
  h(WorkspaceEditor, {
651
651
  workspace: connection.workspace,
652
+ locked: connection.conversationDirectory?.enabled === true,
652
653
  disabled: Boolean(busy),
653
654
  onSave: onWorkspaceSave,
654
655
  }),
@@ -7,6 +7,7 @@ import { DsBotSettingsPage } from './ds-bot-settings.js';
7
7
  import { FeishuGroupSettingsPage } from './channels/feishu/group-settings.js';
8
8
  import { FeishuVoiceSettingsPage } from './channels/feishu/voice-settings.js';
9
9
  import { FeishuSlashPanelSettingsPage } from './channels/feishu/slash-panel-settings.js';
10
+ import { FeishuConversationDirectorySettingsPage } from './channels/feishu/conversation-directory-settings.js';
10
11
  import { TelegramGroupTriggersSettings } from './channels/telegram/group-triggers-settings.js';
11
12
  import { h, imLocale, localizeTemplate, localizeText } from './i18n.js';
12
13
 
@@ -36,6 +37,7 @@ export const BOT_SETTINGS_TABS = Object.freeze([
36
37
 
37
38
  export const FEISHU_BOT_SETTINGS_TABS = Object.freeze([
38
39
  ...BOT_SETTINGS_TABS,
40
+ Object.freeze({ id: 'conversation-directory', label: '会话目录' }),
39
41
  Object.freeze({ id: 'group', label: '群聊' }),
40
42
  Object.freeze({ id: 'slash', label: '指令面板' }),
41
43
  Object.freeze({ id: 'voice', label: '语音交互' }),
@@ -137,6 +139,15 @@ const CHANNEL_DEFINITIONS = Object.freeze({
137
139
  kinds: [{ value: 'user', label: '私聊' }],
138
140
  fields: { user: [{ key: 'chatGuid', label: 'Chat GUID', placeholder: 'iMessage;+;chat123' }] },
139
141
  },
142
+ // 邮箱渠道在 Host 侧(delivery-adapter 的 case 'email')早于投递设置页面支持,
143
+ // route 只有 address 一个字段,kind 固定为 user,这里补齐表单定义让投递目标可选。
144
+ email: {
145
+ label: '邮箱',
146
+ kinds: [{ value: 'user', label: '收件人' }],
147
+ fields: {
148
+ user: [{ key: 'address', label: '邮箱地址', placeholder: 'name@example.com', inputMode: 'email' }],
149
+ },
150
+ },
140
151
  });
141
152
 
142
153
  export const DELIVERY_CHANNEL_DEFINITIONS = CHANNEL_DEFINITIONS;
@@ -803,6 +814,8 @@ export function DeliveryTargetSettingsPage({
803
814
  rpcCall: accessRpcCall,
804
815
  onSaved: setAccessPolicy,
805
816
  })
817
+ : activeTab.id === 'conversation-directory' && channel === 'feishu'
818
+ ? h(FeishuConversationDirectorySettingsPage, { account, rpcCall: accessRpcCall })
806
819
  : activeTab.id === 'groups' && channel === 'telegram'
807
820
  ? h(TelegramGroupTriggersSettings, {
808
821
  key: `${channel}:${account.botId}:groups`,
@@ -25,6 +25,23 @@ import weixinDiagnostics from '../../src/channels/shared/i18n-ru/weixin.mjs';
25
25
  // Sentences the settings UI composes itself, as `{name}` templates: the key is the
26
26
  // Chinese template and the value keeps the placeholders of the English one.
27
27
  const COMPOSED = Object.freeze({
28
+ '会话目录': 'Каталоги бесед',
29
+ '会话目录隔离': 'Изоляция каталогов бесед',
30
+ '会话目录隔离已开启,工作区由对话自动分配。': 'Изоляция каталогов бесед включена. Рабочая область назначается автоматически для каждой беседы.',
31
+ '无法读取会话目录设置。': 'Не удалось загрузить настройки каталогов бесед.',
32
+ '保存会话目录设置失败。': 'Не удалось сохранить настройки каталогов бесед.',
33
+ '让每个对话在自己的目录里工作,避免多人使用同一机器人时互相覆盖文件。默认关闭。': 'Каждая беседа работает в собственном каталоге, чтобы пользователи одного бота не перезаписывали файлы друг друга. По умолчанию отключено.',
34
+ '设置保存后对新会话生效。发送 /new 使用新设置;已有会话和旧目录中的文件保留。开启后无法手动修改工作区。': 'Сохранённые настройки применяются к новым сеансам. Отправьте /new, чтобы использовать их. Существующие сеансы и файлы в прежних каталогах сохраняются. При включённой изоляции нельзя менять рабочую область вручную.',
35
+ '当前类型全部机器人会话目录隔离': 'Изоляция каталогов бесед по умолчанию для всех ботов этого канала',
36
+ '继承渠道默认;保存后仅覆盖当前机器人。': 'Наследуются настройки канала. Сохранение переопределит их только для текущего бота.',
37
+ '启用会话目录隔离': 'Включить изоляцию каталогов бесед',
38
+ '目录策略': 'Правило создания каталогов',
39
+ '每个对话固定一个目录': 'Один постоянный каталог для каждой беседы',
40
+ '每次新建会话使用新目录': 'Новый каталог для каждого нового сеанса',
41
+ '目录前缀': 'Префикс каталога',
42
+ '恢复继承渠道默认': 'Восстановить настройки канала по умолчанию',
43
+ '清除渠道默认': 'Сбросить настройки канала по умолчанию',
44
+ '1–32 位字母、数字、下划线或连字符,默认为 conv-。': 'От 1 до 32 латинских букв, цифр, знаков подчёркивания или дефисов. По умолчанию: conv-.',
28
45
  '使用 Bot Token 接入 {channel} 机器人': 'Подключить бота {channel} по Bot Token',
29
46
  '已接入的 {channel} 机器人': 'Подключённые боты {channel}',
30
47
  '正在读取 {channel} 机器人状态…': 'Читаю состояние ботов {channel}…',
@@ -1400,6 +1417,7 @@ const CLIENT = Object.freeze({
1400
1417
  'DeepSeek Harness читает новые письма в этом ящике как команды и отвечает результатом в той же цепочке писем.',
1401
1418
  '邮箱服务商': 'Почтовый провайдер',
1402
1419
  '邮箱地址': 'Адрес почты',
1420
+ '收件人': 'Получатель',
1403
1421
  '应用密码 / 授权码': 'Пароль приложения / код авторизации',
1404
1422
  'IMAP/SMTP 授权码': 'Код авторизации IMAP/SMTP',
1405
1423
  '不是邮箱登录密码;请在邮箱设置中单独生成。':
@@ -154,6 +154,23 @@ const EN = Object.freeze({
154
154
  'IM 面板加载失败': 'Could not load the IM panel',
155
155
  '更多机器人设置': 'More bot settings',
156
156
  '更多设置': 'More settings',
157
+ '会话目录': 'Conversation directories',
158
+ '会话目录隔离': 'Conversation directory isolation',
159
+ '会话目录隔离已开启,工作区由对话自动分配。': 'Conversation directory isolation is enabled. Workspaces are assigned automatically.',
160
+ '无法读取会话目录设置。': 'Could not load conversation directory settings.',
161
+ '保存会话目录设置失败。': 'Could not save conversation directory settings.',
162
+ '让每个对话在自己的目录里工作,避免多人使用同一机器人时互相覆盖文件。默认关闭。': 'Give each conversation its own directory to prevent users sharing a bot from overwriting files. Off by default.',
163
+ '设置保存后对新会话生效。发送 /new 使用新设置;已有会话和旧目录中的文件保留。开启后无法手动修改工作区。': 'New settings apply to new sessions. Send /new to use them. Existing sessions and files remain. Workspaces cannot be changed manually while isolation is enabled.',
164
+ '当前类型全部机器人会话目录隔离': 'Channel default · Conversation directory isolation',
165
+ '继承渠道默认;保存后仅覆盖当前机器人。': 'Inherits the channel default. Saving overrides it for this bot only.',
166
+ '启用会话目录隔离': 'Enable conversation directory isolation',
167
+ '目录策略': 'Directory strategy',
168
+ '每个对话固定一个目录': 'One directory per conversation',
169
+ '每次新建会话使用新目录': 'A new directory for every session',
170
+ '目录前缀': 'Directory prefix',
171
+ '恢复继承渠道默认': 'Restore channel default',
172
+ '清除渠道默认': 'Clear channel default',
173
+ '1–32 位字母、数字、下划线或连字符,默认为 conv-。': '1–32 letters, digits, underscores or hyphens. Default: conv-.',
157
174
  '向左滚动设置页签': 'Scroll settings tabs left',
158
175
  '向右滚动设置页签': 'Scroll settings tabs right',
159
176
  '常用配置': 'Common settings',
@@ -1254,6 +1271,7 @@ const EN = Object.freeze({
1254
1271
  'DeepSeek Harness 会读取该邮箱的新邮件作为指令,并在同一邮件线程内回复处理结果。': 'DeepSeek Harness reads new mail in this mailbox as instructions and replies with the result inside the same mail thread.',
1255
1272
  '邮箱服务商': 'Mail provider',
1256
1273
  '邮箱地址': 'Email address',
1274
+ '收件人': 'Recipient',
1257
1275
  '应用密码 / 授权码': 'App password / authorization code',
1258
1276
  'IMAP/SMTP 授权码': 'IMAP/SMTP authorization code',
1259
1277
  '不是邮箱登录密码;请在邮箱设置中单独生成。': 'This is not your login password; generate it separately in your mailbox settings.',
@@ -108,6 +108,14 @@ ${MARKED}[${TITLE_ATTR}]::after {
108
108
  text-overflow: ellipsis;
109
109
  pointer-events: none;
110
110
  }
111
+ /* The Host scrolls the original span and publishes these marquee fade hooks.
112
+ Let the replacement travel as complete text, not a pre-clipped viewport. */
113
+ ${MARKED}[${TITLE_ATTR}]:is([data-scrolled], [data-clipped])::after {
114
+ inset-inline-end: auto;
115
+ width: max-content;
116
+ overflow: visible;
117
+ text-overflow: clip;
118
+ }
111
119
  ${Object.entries(uris).map(([channel, uri]) => `[${CHANNEL_ATTR}="${channel}"] { --dsh-im-session-logo: url("${uri}"); }`).join('\n')}
112
120
  `;
113
121
  document.head.appendChild(style);
@@ -1,6 +1,12 @@
1
1
  export const IM_STYLE_ID = 'xmanrui-dsh-im-settings';
2
2
 
3
3
  const CSS = String.raw`
4
+ .dim-conversationDirectorySettings { max-width: 720px; }
5
+ .dim-conversationDirectoryForm { margin: 18px 0; padding: 16px; border: 1px solid var(--dsw-alias-border-l2, #dfe1e5); border-radius: 8px; }
6
+ .dim-conversationDirectoryForm h3 { margin: 0 0 12px; font-size: 15px; }
7
+ .dim-conversationDirectoryField { display: flex; align-items: center; gap: 12px; margin: 12px 0; font-size: 13px; }
8
+ .dim-conversationDirectoryField > span { min-width: 72px; }
9
+ .dim-conversationDirectoryField input, .dim-conversationDirectoryField select { max-width: 100%; min-width: 0; padding: 7px 9px; border: 1px solid var(--dsw-alias-border-l2, #dfe1e5); border-radius: 6px; font: inherit; color: inherit; background: var(--dsw-alias-bg-layer-1, #fff); }
4
10
  .dim-sidebarIcon { display: block; flex: none; }
5
11
  .dim-pluginOpen { display: inline-flex; align-items: center; justify-content: center; min-height: 36px; padding: 7px 14px; border: 1px solid var(--dsw-alias-border-l2, #dfe1e5); border-radius: 8px; color: var(--dsw-alias-label-primary, #1f2329); background: var(--dsw-alias-bg-layer-1, #fff); font: inherit; font-size: 13px; line-height: 20px; cursor: pointer; }
6
12
  .dim-pluginOpen:hover { background: var(--dsw-alias-interactive-bg-hover, #f7f8fa); }
@@ -5,7 +5,7 @@ import { WorkspaceDirectoryPicker } from './workspace-directory-picker.js';
5
5
 
6
6
  export const WorkspaceDirectoryPickerContext = React.createContext(null);
7
7
 
8
- export function WorkspaceEditor({ workspace, directoryPicker, disabled = false, onSave }) {
8
+ export function WorkspaceEditor({ workspace, directoryPicker, disabled = false, locked = false, onSave }) {
9
9
  const sharedDirectoryPicker = React.useContext(WorkspaceDirectoryPickerContext);
10
10
  const activeDirectoryPicker = directoryPicker ?? sharedDirectoryPicker;
11
11
  const [open, setOpen] = React.useState(false);
@@ -21,7 +21,7 @@ export function WorkspaceEditor({ workspace, directoryPicker, disabled = false,
21
21
  }, []);
22
22
 
23
23
  const pick = React.useCallback(async (value) => {
24
- if (!value || savingRef.current || disabled) return;
24
+ if (!value || savingRef.current || disabled || locked) return;
25
25
  if (value === workspace) {
26
26
  close();
27
27
  return;
@@ -38,7 +38,7 @@ export function WorkspaceEditor({ workspace, directoryPicker, disabled = false,
38
38
  savingRef.current = false;
39
39
  setSaving(false);
40
40
  }
41
- }, [close, disabled, onSave, workspace]);
41
+ }, [close, disabled, locked, onSave, workspace]);
42
42
 
43
43
  return h('div', { className: 'dim-workspace' },
44
44
  h('div', { className: 'dim-workspaceHeader' },
@@ -48,7 +48,8 @@ export function WorkspaceEditor({ workspace, directoryPicker, disabled = false,
48
48
  ref: editButtonRef,
49
49
  className: 'dim-workspaceEdit',
50
50
  onClick: () => { setOpen(true); setError(null); },
51
- disabled: disabled || !activeDirectoryPicker,
51
+ disabled: disabled || locked || !activeDirectoryPicker,
52
+ title: locked ? '会话目录隔离已开启,工作区由对话自动分配。' : undefined,
52
53
  }, '选择目录')),
53
54
  workspace
54
55
  ? React.createElement('code', {
@@ -60,7 +61,7 @@ export function WorkspaceEditor({ workspace, directoryPicker, disabled = false,
60
61
  open,
61
62
  startPath: workspace,
62
63
  picker: activeDirectoryPicker,
63
- busy: saving || disabled,
64
+ busy: saving || disabled || locked,
64
65
  saveError: error,
65
66
  onPicked: pick,
66
67
  onCancel: close,
@@ -17,6 +17,7 @@ import {
17
17
  normalizeModelSelection,
18
18
  } from '../../../../src/channels/shared/model-setting.mjs';
19
19
  import { normalizeAccessPolicy } from '../../../../src/channels/shared/access-policy.mjs';
20
+ import { normalizeConversationDirectory, validateConversationDirectory } from '../../../../src/channels/shared/conversation-directory.mjs';
20
21
  import { resolveRpcAuthority } from '../../rpc-authority.mjs';
21
22
  import { publicWorkspaceError, validWorkspacePayload } from '../shared/workspace-rpc.mjs';
22
23
  import { validAgentPresetPayload } from '../shared/agent-preset-rpc.mjs';
@@ -49,6 +50,8 @@ export const FEISHU_ENDPOINTS = Object.freeze({
49
50
  setBusyMessageMode: SET_MESSAGE_MODE_ENDPOINT,
50
51
  setAccessPolicy: SET_ACCESS_POLICY_ENDPOINT,
51
52
  setAlias: SET_ALIAS_ENDPOINT,
53
+ setConversationDirectory: FEISHU_CLIENT_ENDPOINTS.setConversationDirectory,
54
+ setConversationDirectoryDefault: FEISHU_CLIENT_ENDPOINTS.setConversationDirectoryDefault,
52
55
  });
53
56
  export { FEISHU_RPC_CHANNEL };
54
57
  export const FEISHU_MULTI_ENDPOINTS = Object.freeze({
@@ -315,6 +318,8 @@ function publicBotEntry(entry) {
315
318
  contextEnhancement: normalizeContextEnhancementConfig(source.contextEnhancement),
316
319
  busyMessageMode: normalizeBusyMessageMode(source.busyMessageMode),
317
320
  accessPolicy: normalizeAccessPolicy(source.accessPolicy),
321
+ conversationDirectory: normalizeConversationDirectory(source.conversationDirectory),
322
+ conversationDirectoryOverride: normalizeConversationDirectory(source.conversationDirectoryOverride),
318
323
  groupResponseMode: normalizeFeishuGroupResponseMode(source.groupResponseMode),
319
324
  mentionTopicReply: source.mentionTopicReply !== false,
320
325
  stepPush: source.stepPush === true,
@@ -366,6 +371,7 @@ export async function toPublicFeishuStatus(status, { encodeQr = qrCodeDataUrl }
366
371
  bot: publicBot(source.bot),
367
372
  health: publicHealth(source, connected),
368
373
  bots,
374
+ conversationDirectory: normalizeConversationDirectory(source.conversationDirectory),
369
375
  agentPresetCatalog: normalizeAgentPresetCatalog(source.agentPresetCatalog),
370
376
  modelCatalog: normalizeModelCatalog(source.modelCatalog),
371
377
  totals: {
@@ -458,6 +464,18 @@ function validPayload(endpoint, payload) {
458
464
  return validWorkspacePayload(payload)
459
465
  ? null : '请输入工作区绝对路径。';
460
466
  }
467
+ if (endpoint === FEISHU_ENDPOINTS.setConversationDirectory
468
+ || endpoint === FEISHU_ENDPOINTS.setConversationDirectoryDefault) {
469
+ const isDefault = endpoint === FEISHU_ENDPOINTS.setConversationDirectoryDefault;
470
+ const allowed = isDefault ? new Set(['config']) : new Set(['botId', 'config']);
471
+ if (!hasOnlyKeys(payload, allowed) || (!isDefault && !safeOpaqueId(payload.botId))) {
472
+ return '请提交有效的会话目录设置。';
473
+ }
474
+ if (payload.config !== null) {
475
+ try { validateConversationDirectory(payload.config); } catch (error) { return error.message; }
476
+ }
477
+ return null;
478
+ }
461
479
  if (endpoint === FEISHU_ENDPOINTS.setModel) {
462
480
  return validModelPayload(payload) ? null : '请选择有效模型。';
463
481
  }
@@ -776,6 +794,13 @@ export function createFeishuRpcHandler(controller, { encodeQr = qrCodeDataUrl }
776
794
  } else if (endpoint === FEISHU_MULTI_ENDPOINTS.disconnectBot) {
777
795
  if (typeof controller.disconnectBot !== 'function') throw new Error('Multi-bot disconnect is unavailable');
778
796
  value = await toPublicFeishuStatus(await controller.disconnectBot(payload.botId), { encodeQr: cachedEncodeQr });
797
+ } else if (endpoint === FEISHU_ENDPOINTS.setConversationDirectory
798
+ || endpoint === FEISHU_ENDPOINTS.setConversationDirectoryDefault) {
799
+ if (typeof controller.updateConversationDirectory !== 'function') throw new Error('Conversation directory update is unavailable');
800
+ value = await toPublicFeishuStatus(await controller.updateConversationDirectory(
801
+ endpoint === FEISHU_ENDPOINTS.setConversationDirectoryDefault ? null : payload.botId,
802
+ payload.config,
803
+ ), { encodeQr: cachedEncodeQr });
779
804
  } else if (endpoint === FEISHU_ENDPOINTS.setWorkspace) {
780
805
  if (typeof controller.updateWorkspace !== 'function') throw new Error('Workspace update is unavailable');
781
806
  value = await toPublicFeishuStatus(
@@ -16,6 +16,8 @@ export function validWorkspacePayload(payload) {
16
16
 
17
17
  export function publicWorkspaceError(error) {
18
18
  if (![
19
+ 'workspace-manual-edit-disabled',
20
+ 'conversation-directory-invalid',
19
21
  'workspace-not-absolute',
20
22
  'workspace-not-found',
21
23
  'workspace-not-directory',
@@ -1,3 +1,5 @@
1
+ // Email conversation keys contain Message-IDs or bound Session IDs, not
2
+ // recipient addresses. Keep email targets explicit until a mapping is stored.
1
3
  const CHANNELS = new Set([
2
4
  'weixin',
3
5
  'feishu',
@@ -1,6 +1,7 @@
1
1
  import { createHash, randomUUID } from 'node:crypto';
2
2
  import { mkdir, open, readFile, rename, stat, unlink, writeFile } from 'node:fs/promises';
3
- import { isAbsolute, join } from 'node:path';
3
+ import { isAbsolute, join, resolve } from 'node:path';
4
+ import { setTimeout as delay } from 'node:timers/promises';
4
5
  import semver from 'semver';
5
6
 
6
7
  import manifest from '../../package.json' with { type: 'json' };
@@ -12,6 +13,8 @@ const JOB_STATES = new Set([...ACTIVE_STATES, 'restart-required', 'completed', '
12
13
  const MAX_METADATA_BYTES = 256 * 1024;
13
14
  const SNAPSHOT_FILES = ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml'];
14
15
  const NO_LOCK = Symbol('no update lock');
16
+ // Shared across Host instances; keep network and installer work outside these transactions.
17
+ const stateIoQueue = {};
15
18
 
16
19
  export function updateError(code) {
17
20
  return Object.assign(new Error(code), { code });
@@ -76,7 +79,17 @@ function pathsFor(environment) {
76
79
  };
77
80
  }
78
81
 
79
- async function readJson(path, missing = null) {
82
+ function withStateIo(path, operation) {
83
+ const absolute = resolve(path);
84
+ const key = process.platform === 'win32' ? absolute.toLowerCase() : absolute;
85
+ return withSessionBindingLock(stateIoQueue, key, operation);
86
+ }
87
+
88
+ function readJson(path, missing = null) {
89
+ return withStateIo(path, () => readJsonUnlocked(path, missing));
90
+ }
91
+
92
+ async function readJsonUnlocked(path, missing = null) {
80
93
  try {
81
94
  if ((await stat(path)).size > 10 * 1024 * 1024) throw updateError('state-unavailable');
82
95
  return JSON.parse(await readFile(path, 'utf8'));
@@ -86,11 +99,25 @@ async function readJson(path, missing = null) {
86
99
  }
87
100
  }
88
101
 
89
- async function writeJson(path, value) {
102
+ function writeJson(path, value) {
103
+ return withStateIo(path, () => writeJsonUnlocked(path, value));
104
+ }
105
+
106
+ async function writeJsonUnlocked(path, value) {
90
107
  const temporary = `${path}.${randomUUID()}.tmp`;
91
108
  try {
92
109
  await writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
93
- await rename(temporary, path);
110
+ for (let retry = 0; ; retry++) {
111
+ try {
112
+ await rename(temporary, path);
113
+ break;
114
+ } catch (error) {
115
+ // Windows readers can temporarily deny replacement. Keep the old journal
116
+ // and retry the same atomic rename; never remove the destination first.
117
+ if (process.platform !== 'win32' || error.code !== 'EPERM' || retry >= 5) throw error;
118
+ await delay(10 * 2 ** retry);
119
+ }
120
+ }
94
121
  } catch {
95
122
  throw updateError('state-unavailable');
96
123
  } finally {
@@ -255,8 +282,10 @@ export function createUpdateService({
255
282
  }
256
283
 
257
284
  async function releaseLock(paths, id) {
258
- const lock = await readJson(paths.lock);
259
- if (lock?.id === id) await unlink(paths.lock);
285
+ await withStateIo(paths.lock, async () => {
286
+ const lock = await readJsonUnlocked(paths.lock);
287
+ if (lock?.id === id) await unlink(paths.lock);
288
+ });
260
289
  }
261
290
 
262
291
  async function backupProfile(environment, paths, job) {
@@ -348,13 +377,15 @@ export function createUpdateService({
348
377
  let locked = false;
349
378
  try {
350
379
  await mkdir(paths.directory, { recursive: true, mode: 0o700 });
351
- const lock = await open(paths.lock, 'wx', 0o600);
352
- locked = true;
353
- try {
354
- await lock.writeFile(JSON.stringify({ id: job.id, pid: process.pid, startedAt: now() }));
355
- } finally {
356
- await lock.close();
357
- }
380
+ await withStateIo(paths.lock, async () => {
381
+ const lock = await open(paths.lock, 'wx', 0o600);
382
+ locked = true;
383
+ try {
384
+ await lock.writeFile(JSON.stringify({ id: job.id, pid: process.pid, startedAt: now() }));
385
+ } finally {
386
+ await lock.close();
387
+ }
388
+ });
358
389
  const currentRelease = await fetchNpmRelease(fetchImpl, checkTimeoutMs);
359
390
  if (JSON.stringify(currentRelease) !== JSON.stringify(confirmation.release)) throw updateError('check-expired');
360
391
  environment = await runtime.inspect({ preflight: true });
@@ -148,23 +148,27 @@ if (client.includes('settings.plugins.tab') || clientSources.includes('settings.
148
148
  }
149
149
  // Connections still have no channel-enable toggle. Checkable inputs are owned
150
150
  // only by the shared context editor, the saved-target Session sync row, the
151
- // email settings, the Telegram thinking-traces block, and Feishu panel settings.
151
+ // email settings, the Telegram thinking-traces block, Feishu panel settings,
152
+ // and the conversation-directory settings form.
152
153
  // The context editor contains one switch template and one mapped field-input
153
154
  // template; the delivery target adds one ordinary checkbox template; the
154
155
  // Telegram thinking-traces block adds two ordinary checkbox templates (traces
155
156
  // and frame numbering). General settings adds one mapped switch template for
156
- // the two Feishu panel preferences.
157
+ // the two Feishu panel preferences. Conversation-directory settings adds one
158
+ // switch template reused for the bot override and channel default.
157
159
  const contextEditorSource = await readFile(resolve(root, 'plugin-src/client/context-enhancement.js'), 'utf8');
158
160
  const deliverySettingsSource = await readFile(resolve(root, 'plugin-src/client/delivery-settings.js'), 'utf8');
159
161
  const emailSettingsSource = await readFile(resolve(root, 'plugin-src/client/channels/email/index.js'), 'utf8');
160
162
  const thinkingTracesSource = await readFile(resolve(root, 'plugin-src/client/channels/telegram/thinking-traces.js'), 'utf8');
161
163
  const botGeneralSettingsSource = await readFile(resolve(root, 'plugin-src/client/bot-general-settings.js'), 'utf8');
164
+ const conversationDirectorySettingsSource = await readFile(resolve(root, 'plugin-src/client/channels/feishu/conversation-directory-settings.js'), 'utf8');
162
165
  const otherClientSources = clientSources
163
166
  .replace(contextEditorSource, '')
164
167
  .replace(deliverySettingsSource, '')
165
168
  .replace(emailSettingsSource, '')
166
169
  .replace(thinkingTracesSource, '')
167
- .replace(botGeneralSettingsSource, '');
170
+ .replace(botGeneralSettingsSource, '')
171
+ .replace(conversationDirectorySettingsSource, '');
168
172
  if (/role:\s*["']switch|type:\s*["']checkbox/.test(otherClientSources)
169
173
  || (deliverySettingsSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
170
174
  || /role:\s*["']switch["']/u.test(deliverySettingsSource)
@@ -172,9 +176,16 @@ if (/role:\s*["']switch|type:\s*["']checkbox/.test(otherClientSources)
172
176
  || /role:\s*["']switch["']/u.test(thinkingTracesSource)
173
177
  || (botGeneralSettingsSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
174
178
  || (botGeneralSettingsSource.match(/role:\s*["']switch["']/g) ?? []).length !== 1
175
- || (client.match(/role:\s*["']switch["']/g) ?? []).length !== 2
176
- || (client.match(/type:\s*["']checkbox["']/g) ?? []).length !== 6) {
177
- throw new Error('checkable inputs must be limited to context enhancement, Session sync, email settings, Telegram thinking traces, and Feishu panel settings');
179
+ || (conversationDirectorySettingsSource.match(/type:\s*["']checkbox["']/g) ?? []).length !== 1
180
+ || (conversationDirectorySettingsSource.match(/role:\s*["']switch["']/g) ?? []).length !== 1
181
+ || (client.match(/role:\s*["']switch["']/g) ?? []).length !== 3
182
+ || (client.match(/type:\s*["']checkbox["']/g) ?? []).length !== 7) {
183
+ throw new Error('checkable inputs must be limited to context enhancement, Session sync, email settings, Telegram thinking traces, Feishu panel settings, and conversation-directory settings');
184
+ }
185
+ for (const marker of ['bot.conversation-directory.set', 'bot.conversation-directory.default.set']) {
186
+ if (!host.includes(marker) || !client.includes(marker)) {
187
+ throw new Error(`conversation-directory RPC endpoint missing from Host or Client bundle: ${marker}`);
188
+ }
178
189
  }
179
190
  for (const marker of ['bot.context-enhancement.set', '<dsh_im_source>', '<dsh_im_source_guidance>']) {
180
191
  if (!host.includes(marker) || !client.includes(marker)) {