@xmanrui/dsh-im 5.3.0 → 5.5.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 (112) hide show
  1. package/PROACTIVE_DELIVERY.en.md +15 -0
  2. package/PROACTIVE_DELIVERY.md +15 -0
  3. package/README.en.md +44 -3
  4. package/README.md +44 -3
  5. package/THIRD_PARTY_NOTICES.md +209 -0
  6. package/docs/client-integration.md +2 -2
  7. package/lib/client.js +3737 -433
  8. package/lib/index.js +415 -344
  9. package/package.json +1 -1
  10. package/plugin-src/client/channel-card-meta.js +6 -2
  11. package/plugin-src/client/channels/shared/token-api.js +13 -0
  12. package/plugin-src/client/channels/telegram/group-triggers-settings.js +393 -0
  13. package/plugin-src/client/channels/telegram/styles.js +4 -0
  14. package/plugin-src/client/channels/telegram/thinking-traces.js +138 -5
  15. package/plugin-src/client/delivery-settings.js +23 -3
  16. package/plugin-src/client/ds-bot-avatar-data.js +537 -0
  17. package/plugin-src/client/ds-bot-avatar.js +55 -0
  18. package/plugin-src/client/ds-bot-session-avatars.js +77 -0
  19. package/plugin-src/client/ds-bot-settings.js +194 -0
  20. package/plugin-src/client/i18n-ru.js +1615 -0
  21. package/plugin-src/client/i18n.js +130 -1
  22. package/plugin-src/client/index.js +20 -2
  23. package/plugin-src/client/plugin-page.js +3 -8
  24. package/plugin-src/client/styles.js +25 -5
  25. package/plugin-src/host/channels/dingtalk/production.mjs +2 -1
  26. package/plugin-src/host/channels/feishu/production.mjs +13 -5
  27. package/plugin-src/host/channels/qq/production.mjs +2 -1
  28. package/plugin-src/host/channels/shared/group-triggers-rpc.mjs +110 -0
  29. package/plugin-src/host/channels/shared/production.mjs +12 -1
  30. package/plugin-src/host/channels/shared/rpc.mjs +21 -0
  31. package/plugin-src/host/channels/shared/send-limit-rpc.mjs +13 -0
  32. package/plugin-src/host/channels/shared/thinking-cadence-rpc.mjs +16 -0
  33. package/plugin-src/host/channels/slack/production.mjs +2 -1
  34. package/plugin-src/host/channels/telegram/index.mjs +1 -0
  35. package/plugin-src/host/channels/telegram/production.mjs +9 -0
  36. package/plugin-src/host/channels/telegram/rpc.mjs +17 -2
  37. package/plugin-src/host/channels/wecom/production.mjs +4 -1
  38. package/plugin-src/host/channels/wecom-app/production.mjs +2 -1
  39. package/plugin-src/host/channels/weixin/production.mjs +2 -1
  40. package/plugin-src/host/channels/whatsapp/production.mjs +2 -1
  41. package/plugin-src/host/delivery-adapter.mjs +129 -41
  42. package/plugin-src/host/delivery-rpc.mjs +33 -1
  43. package/plugin-src/host/delivery-service.mjs +112 -1
  44. package/plugin-src/host/delivery-suggestions.mjs +11 -0
  45. package/plugin-src/host/ds-bot-client.mjs +87 -0
  46. package/plugin-src/host/ds-bot-question-sync.mjs +78 -0
  47. package/plugin-src/host/index.mjs +8 -1
  48. package/plugin-src/host/modern-harness-api.mjs +53 -8
  49. package/plugin-src/host/session-sync-coordinator.mjs +5 -5
  50. package/scripts/verify-package.mjs +17 -5
  51. package/src/channels/feishu/bridge.mjs +83 -5
  52. package/src/channels/feishu/feishu-cards.mjs +11 -7
  53. package/src/channels/feishu/feishu-runtime.mjs +10 -0
  54. package/src/channels/feishu/multi-bot-controller.mjs +12 -0
  55. package/src/channels/shared/AGENTS.md +19 -0
  56. package/src/channels/shared/bot-workspace-store.mjs +136 -7
  57. package/src/channels/shared/clear-command.mjs +2 -1
  58. package/src/channels/shared/compact-command.mjs +2 -1
  59. package/src/channels/shared/conversation-queue.mjs +49 -0
  60. package/src/channels/shared/deferred-delivery-coordinator.mjs +2 -1
  61. package/src/channels/shared/group-history-store.mjs +26 -0
  62. package/src/channels/shared/harness-client.mjs +5 -4
  63. package/src/channels/shared/history-command.mjs +2 -1
  64. package/src/channels/shared/i18n-en/feishu.mjs +1 -0
  65. package/src/channels/shared/i18n-en/shared-a.mjs +2 -2
  66. package/src/channels/shared/i18n-en/shared-b.mjs +2 -2
  67. package/src/channels/shared/i18n-en/shared-c.mjs +3 -2
  68. package/src/channels/shared/i18n-en/wecom.mjs +4 -0
  69. package/src/channels/shared/i18n-ru/diagnostics.mjs +104 -0
  70. package/src/channels/shared/i18n-ru/dingtalk.mjs +96 -0
  71. package/src/channels/shared/i18n-ru/discord.mjs +10 -0
  72. package/src/channels/shared/i18n-ru/email.mjs +23 -0
  73. package/src/channels/shared/i18n-ru/feishu.mjs +374 -0
  74. package/src/channels/shared/i18n-ru/image-input.mjs +25 -0
  75. package/src/channels/shared/i18n-ru/matrix.mjs +73 -0
  76. package/src/channels/shared/i18n-ru/office.mjs +27 -0
  77. package/src/channels/shared/i18n-ru/permission.mjs +45 -0
  78. package/src/channels/shared/i18n-ru/qq.mjs +88 -0
  79. package/src/channels/shared/i18n-ru/shared-a.mjs +236 -0
  80. package/src/channels/shared/i18n-ru/shared-b.mjs +257 -0
  81. package/src/channels/shared/i18n-ru/shared-c.mjs +173 -0
  82. package/src/channels/shared/i18n-ru/slack.mjs +22 -0
  83. package/src/channels/shared/i18n-ru/telegram.mjs +25 -0
  84. package/src/channels/shared/i18n-ru/wecom-app.mjs +43 -0
  85. package/src/channels/shared/i18n-ru/wecom.mjs +79 -0
  86. package/src/channels/shared/i18n-ru/weixin.mjs +275 -0
  87. package/src/channels/shared/i18n-ru/whatsapp.mjs +18 -0
  88. package/src/channels/shared/i18n-ru.mjs +48 -0
  89. package/src/channels/shared/i18n.mjs +47 -12
  90. package/src/channels/shared/inbound-access.mjs +1 -1
  91. package/src/channels/shared/interface-language.mjs +3 -3
  92. package/src/channels/shared/message-failure.mjs +3 -2
  93. package/src/channels/shared/model-command.mjs +2 -1
  94. package/src/channels/shared/permission-command.mjs +2 -1
  95. package/src/channels/shared/send-limit.mjs +38 -0
  96. package/src/channels/shared/session-binding-lock.mjs +2 -0
  97. package/src/channels/shared/session-error.mjs +3 -0
  98. package/src/channels/shared/status-reaction.mjs +2 -0
  99. package/src/channels/shared/text-harness-bridge.mjs +4 -0
  100. package/src/channels/shared/thinking-cadence.mjs +36 -0
  101. package/src/channels/shared/workspace-command.mjs +2 -1
  102. package/src/channels/shared/workspace-session.mjs +5 -1
  103. package/src/channels/telegram/config-store.mjs +38 -1
  104. package/src/channels/telegram/group-triggers.mjs +229 -0
  105. package/src/channels/telegram/telegram-api.mjs +223 -32
  106. package/src/channels/telegram/telegram-bridge.mjs +4 -1
  107. package/src/channels/telegram/telegram-controller.mjs +139 -1
  108. package/src/channels/telegram/telegram-runtime.mjs +522 -178
  109. package/src/channels/telegram/voice.mjs +250 -0
  110. package/src/channels/wecom/stream-supervisor.mjs +184 -0
  111. package/src/channels/wecom/wecom-bridge.mjs +25 -11
  112. package/src/channels/wecom/wecom-runtime.mjs +12 -1
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@xmanrui/dsh-im",
3
- "version": "5.3.0",
3
+ "version": "5.5.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": [
@@ -1,7 +1,7 @@
1
1
  import { ConnectionError } from './connection-error.js';
2
2
  import * as React from 'react';
3
3
 
4
- import { h, isEnglish } from './i18n.js';
4
+ import { h, imLocale } from './i18n.js';
5
5
 
6
6
  export const BotSettingsContext = React.createContext(Object.freeze({
7
7
  openBotSettings() {},
@@ -50,9 +50,13 @@ export function BotSettingsButton({
50
50
  h('span', { className: 'dim-moreSettingsChevron', 'aria-hidden': 'true' })));
51
51
  }
52
52
 
53
+ // Date formatting follows the interface language, not English-vs-not: a
54
+ // Russian reader is served ru-RU numerals and month names, not Chinese ones.
55
+ const INTL_LOCALES = Object.freeze({ zh: 'zh-CN', en: 'en-US', ru: 'ru-RU' });
56
+
53
57
  function messageErrorTime(value) {
54
58
  try {
55
- return new Intl.DateTimeFormat(isEnglish() ? 'en-US' : 'zh-CN', {
59
+ return new Intl.DateTimeFormat(INTL_LOCALES[imLocale()] ?? 'en-US', {
56
60
  year: 'numeric',
57
61
  month: '2-digit',
58
62
  day: '2-digit',
@@ -6,6 +6,12 @@ import { normalizeModelCatalog, normalizeModelSelection, SET_MODEL_ENDPOINT } fr
6
6
  import { normalizeLastMessageError } from '../../last-message-error.js';
7
7
  import { normalizeAccessPolicy } from '../../../../src/channels/shared/access-policy.mjs';
8
8
  import { normalizeContextEnhancementConfig } from '../../../../src/channels/shared/context-enhancement.mjs';
9
+ import {
10
+ normalizeThinkingIntervalSeconds,
11
+ normalizeThinkingNumbering,
12
+ SET_THINKING_CADENCE_ENDPOINT,
13
+ } from '../../../../src/channels/shared/thinking-cadence.mjs';
14
+ import { normalizeSendLimitPerMinute, SET_SEND_LIMIT_ENDPOINT } from '../../../../src/channels/shared/send-limit.mjs';
9
15
 
10
16
  const ACCOUNT_STATES = new Set(['connected', 'connecting', 'offline', 'error']);
11
17
 
@@ -41,6 +47,8 @@ export const TOKEN_BOT_ENDPOINTS = Object.freeze({
41
47
  setAccessPolicy: 'bot.access-policy.set',
42
48
  setAlias: 'bot.alias.set',
43
49
  setThinkingTraces: 'bot.thinking-traces.set',
50
+ setThinkingCadence: SET_THINKING_CADENCE_ENDPOINT,
51
+ setSendLimit: SET_SEND_LIMIT_ENDPOINT,
44
52
  });
45
53
 
46
54
  export function createTokenChannelApi(channel, connectionSummary, {
@@ -74,6 +82,11 @@ export function createTokenChannelApi(channel, connectionSummary, {
74
82
  busyMessageMode: normalizeBusyMessageMode(value.busyMessageMode), contextEnhancement: normalizeContextEnhancementConfig(value.contextEnhancement),
75
83
  // Absent from the backend means ON; only an explicit false opts out.
76
84
  thinkingTraces: value.thinkingTraces !== false,
85
+ // Absent or unusable falls back to the same defaults the backend applies.
86
+ thinkingNumbering: normalizeThinkingNumbering(value.thinkingNumbering),
87
+ thinkingIntervalSeconds: normalizeThinkingIntervalSeconds(value.thinkingIntervalSeconds),
88
+ // Absent or unusable falls back to the same default the backend applies.
89
+ sendLimitPerMinute: normalizeSendLimitPerMinute(value.sendLimitPerMinute),
77
90
  ...(Object.hasOwn(value, 'accessPolicy')
78
91
  ? { accessPolicy: normalizeAccessPolicy(value.accessPolicy) }
79
92
  : {}),
@@ -0,0 +1,393 @@
1
+ /**
2
+ * Bot in groups: per-chat reply rules for the Telegram channel.
3
+ *
4
+ * Each rule answers one question — which group messages should wake the bot:
5
+ * never, only when it is mentioned or replied to, or every message; and whether
6
+ * that applies to anyone or only to a list of member IDs.
7
+ *
8
+ * The rule set lives in the bot config, so saving restarts the runtime and the
9
+ * new behaviour applies to the next incoming message.
10
+ */
11
+ import * as React from 'react';
12
+
13
+ import { h } from '../../i18n.js';
14
+
15
+ export const GROUP_TRIGGERS_ENDPOINTS = Object.freeze({
16
+ get: 'bot.group-triggers.get',
17
+ set: 'bot.group-triggers.set',
18
+ resolve: 'bot.group-triggers.resolve',
19
+ });
20
+
21
+ export const GROUP_TRIGGER_MODE_OPTIONS = Object.freeze([
22
+ Object.freeze({ value: 'off', label: '不响应' }),
23
+ Object.freeze({ value: 'mention', label: '被 @ 或回复时(任何人)' }),
24
+ Object.freeze({ value: 'mention-list', label: '被 @ 或回复时(仅名单成员)' }),
25
+ Object.freeze({ value: 'all', label: '所有消息(任何人)' }),
26
+ Object.freeze({ value: 'all-list', label: '所有消息(仅名单成员)' }),
27
+ ]);
28
+
29
+ const LIST_MODES = new Set(['mention-list', 'all-list']);
30
+ const DEFAULT_ENTRY = Object.freeze({ mode: 'off', sendersText: '' });
31
+
32
+ function isListMode(mode) {
33
+ return LIST_MODES.has(mode);
34
+ }
35
+
36
+ function modeLabel(value) {
37
+ return GROUP_TRIGGER_MODE_OPTIONS.find((option) => option.value === value)?.label
38
+ ?? GROUP_TRIGGER_MODE_OPTIONS[0].label;
39
+ }
40
+
41
+ export function splitMemberIds(text) {
42
+ return String(text ?? '').split(/[\s,;]+/).map((item) => item.trim()).filter(Boolean);
43
+ }
44
+
45
+ /** One stored rule → editor state (members stay as the owner typed them). */
46
+ export function entryFromConfig(value) {
47
+ const mode = GROUP_TRIGGER_MODE_OPTIONS.some((option) => option.value === value?.mode)
48
+ ? value.mode : 'off';
49
+ const senders = Array.isArray(value?.senders) ? value.senders.map((id) => String(id)) : [];
50
+ return { mode, sendersText: senders.join('\n') };
51
+ }
52
+
53
+ /** RPC snapshot → editor state. */
54
+ export function stateFromSnapshot(value) {
55
+ const source = value && typeof value === 'object' ? value : {};
56
+ const groups = {};
57
+ for (const [chatId, entry] of Object.entries(source.groups ?? {})) {
58
+ groups[String(chatId)] = entryFromConfig(entry);
59
+ }
60
+ const seen = {};
61
+ for (const entry of Array.isArray(source.seen) ? source.seen : []) {
62
+ const chatId = typeof entry?.chatId === 'string' ? entry.chatId : '';
63
+ if (!chatId) continue;
64
+ seen[chatId] = {
65
+ title: typeof entry.title === 'string' ? entry.title : null,
66
+ type: typeof entry.type === 'string' ? entry.type : null,
67
+ lastSeenAt: typeof entry.lastSeenAt === 'string' ? entry.lastSeenAt : null,
68
+ lastSenderName: typeof entry.lastSenderName === 'string' ? entry.lastSenderName : null,
69
+ };
70
+ }
71
+ return { defaults: entryFromConfig(source.defaults), groups, seen, removed: [] };
72
+ }
73
+
74
+ function unwrapRpcResult(result) {
75
+ if (result?.ok === false) {
76
+ const error = new Error(result.error?.message || '无法读取或保存群聊设置,请稍后重试。');
77
+ error.code = result.error?.code;
78
+ throw error;
79
+ }
80
+ return result?.ok === true ? result.value : result;
81
+ }
82
+
83
+ function formatMoment(value) {
84
+ if (typeof value !== 'string' || !value) return '—';
85
+ return value.slice(0, 16).replace('T', ' ');
86
+ }
87
+
88
+ function memberHelp(entry) {
89
+ if (splitMemberIds(entry.sendersText).length > 0) return null;
90
+ return isListMode(entry.mode)
91
+ ? '名单为空:该模式不会响应任何成员。'
92
+ : '当前模式不使用名单。';
93
+ }
94
+
95
+ function ModeField({ entry, onChange, disabled }) {
96
+ return h('label', { className: 'dim-accessField' },
97
+ h('span', null, '响应条件'),
98
+ h('select', {
99
+ value: entry.mode,
100
+ disabled,
101
+ onChange: (event) => onChange(event.target.value),
102
+ }, GROUP_TRIGGER_MODE_OPTIONS.map((option) => h('option', {
103
+ key: option.value,
104
+ value: option.value,
105
+ }, option.label))));
106
+ }
107
+
108
+ function MembersField({ entry, onChange, disabled }) {
109
+ const help = memberHelp(entry);
110
+ return h('label', { className: 'dim-accessField' },
111
+ h('span', null, '成员名单'),
112
+ h('textarea', {
113
+ ...AUTOFILL_GUARD,
114
+ value: entry.sendersText,
115
+ rows: 2,
116
+ disabled,
117
+ spellCheck: false,
118
+ placeholder: '123456789',
119
+ onChange: (event) => onChange(event.target.value),
120
+ }),
121
+ help ? h('span', { className: 'dim-channelHelp' }, help) : null);
122
+ }
123
+
124
+ function ValueRow({ label, value, suffix }) {
125
+ return h('div', { className: 'dim-accessField' },
126
+ h('span', null, label),
127
+ h('code', { className: 'dim-groupTriggerValue' }, value, suffix ?? null));
128
+ }
129
+
130
+ /** Keeps browser password managers from treating these fields as logins. */
131
+ const AUTOFILL_GUARD = Object.freeze({
132
+ autoComplete: 'off',
133
+ autoCapitalize: 'none',
134
+ autoCorrect: 'off',
135
+ 'data-1p-ignore': 'true',
136
+ 'data-lpignore': 'true',
137
+ 'data-bwignore': 'true',
138
+ 'data-form-type': 'other',
139
+ });
140
+
141
+ export function TelegramGroupTriggersSettings({ account, rpcCall }) {
142
+ const [state, setState] = React.useState(null);
143
+ const [addDraft, setAddDraft] = React.useState(null);
144
+ const [manualId, setManualId] = React.useState('');
145
+ const [phase, setPhase] = React.useState('loading');
146
+ const [saving, setSaving] = React.useState(false);
147
+ const [resolving, setResolving] = React.useState(false);
148
+ const [feedback, setFeedback] = React.useState(null);
149
+
150
+ const botId = account?.botId;
151
+
152
+ const load = React.useCallback(async () => {
153
+ setPhase('loading');
154
+ setFeedback(null);
155
+ try {
156
+ const value = unwrapRpcResult(await rpcCall(GROUP_TRIGGERS_ENDPOINTS.get, { botId }));
157
+ setState(stateFromSnapshot(value));
158
+ // The add form always starts blank: it is a new rule, not a copy of the
159
+ // defaults, so the owner never edits the wrong card by accident.
160
+ setAddDraft(null);
161
+ setPhase('ready');
162
+ } catch (error) {
163
+ setPhase('error');
164
+ setFeedback({ tone: 'error', message: error?.message || '无法读取群聊设置,请稍后重试。' });
165
+ }
166
+ }, [botId, rpcCall]);
167
+
168
+ React.useEffect(() => { void load(); }, [load]);
169
+
170
+ if (phase === 'loading') {
171
+ return h('div', { className: 'dim-accessState', 'aria-busy': 'true' }, '正在读取群聊设置…');
172
+ }
173
+ if (phase === 'error' || !state) {
174
+ return h('div', { className: 'dim-accessState', role: 'alert' },
175
+ h('p', null, feedback?.message || '无法读取群聊设置,请稍后重试。'),
176
+ h('button', { type: 'button', className: 'dim-deliveryButton', onClick: () => void load() },
177
+ '重试'));
178
+ }
179
+
180
+ const removed = new Set(state.removed);
181
+ const chatIds = [...new Set([...Object.keys(state.groups), ...Object.keys(state.seen)])]
182
+ .filter((chatId) => !removed.has(chatId));
183
+ const addEntry = addDraft ?? DEFAULT_ENTRY;
184
+
185
+ const updateDefault = (patch) => {
186
+ setState((current) => ({ ...current, defaults: { ...current.defaults, ...patch } }));
187
+ setFeedback(null);
188
+ };
189
+ const updateGroup = (chatId, patch) => {
190
+ setState((current) => ({
191
+ ...current,
192
+ groups: { ...current.groups, [chatId]: { ...(current.groups[chatId] ?? current.defaults), ...patch } },
193
+ }));
194
+ setFeedback(null);
195
+ };
196
+ const removeGroup = (chatId) => {
197
+ setState((current) => {
198
+ const groups = { ...current.groups };
199
+ delete groups[chatId];
200
+ return { ...current, groups, removed: [...current.removed, chatId] };
201
+ });
202
+ setFeedback({ tone: 'success', message: '已从列表移除,保存后生效。' });
203
+ };
204
+ const addGroup = async () => {
205
+ const raw = manualId.replace(/[\s\u00a0]+/g, '');
206
+ if (!raw) return;
207
+ setResolving(true);
208
+ setFeedback(null);
209
+ try {
210
+ const resolved = unwrapRpcResult(await rpcCall(GROUP_TRIGGERS_ENDPOINTS.resolve, { botId, input: raw }));
211
+ const chatId = typeof resolved?.chatId === 'string' ? resolved.chatId : '';
212
+ if (!chatId) throw new Error('无法解析该群聊,请重试或填写数字群 ID。');
213
+ // A chat already carrying a rule cannot be added twice; a chat that is
214
+ // only known from the archive is configurable, so it is not a duplicate.
215
+ if (Object.hasOwn(state.groups, chatId)) {
216
+ setFeedback({
217
+ tone: 'error',
218
+ message: '该群已在列表中,请编辑上方的卡片。',
219
+ detail: chatId,
220
+ });
221
+ return;
222
+ }
223
+ setState((current) => ({
224
+ ...current,
225
+ groups: { ...current.groups, [chatId]: { ...addEntry } },
226
+ // Re-adding a hidden chat must undo the previous removal.
227
+ removed: current.removed.filter((entry) => entry !== chatId),
228
+ seen: resolved?.title
229
+ ? { ...current.seen, [chatId]: { ...(current.seen[chatId] ?? {}), title: resolved.title } }
230
+ : current.seen,
231
+ }));
232
+ setManualId('');
233
+ setAddDraft(null);
234
+ setFeedback({
235
+ tone: 'success',
236
+ message: resolved?.verified === false
237
+ ? '已添加。Telegram 未确认该群(机器人可能还不在群里),保存后生效。'
238
+ : '已添加,保存后生效。',
239
+ });
240
+ } catch (error) {
241
+ setFeedback({ tone: 'error', message: error?.message || '无法解析该群聊,请重试或填写数字群 ID。' });
242
+ } finally {
243
+ setResolving(false);
244
+ }
245
+ };
246
+ const save = async (event) => {
247
+ event.preventDefault();
248
+ setSaving(true);
249
+ setFeedback(null);
250
+ try {
251
+ const groups = {};
252
+ for (const [chatId, entry] of Object.entries(state.groups)) {
253
+ groups[chatId] = { mode: entry.mode, senders: splitMemberIds(entry.sendersText) };
254
+ }
255
+ const value = unwrapRpcResult(await rpcCall(GROUP_TRIGGERS_ENDPOINTS.set, {
256
+ botId,
257
+ config: {
258
+ defaults: { mode: state.defaults.mode, senders: splitMemberIds(state.defaults.sendersText) },
259
+ groups,
260
+ },
261
+ removed: state.removed,
262
+ }));
263
+ setState(stateFromSnapshot(value));
264
+ setAddDraft(null);
265
+ setFeedback({ tone: 'success', message: '群聊设置已保存。' });
266
+ } catch (error) {
267
+ setFeedback({ tone: 'error', message: error?.message || '无法保存群聊设置,请稍后重试。' });
268
+ } finally {
269
+ setSaving(false);
270
+ }
271
+ };
272
+
273
+ return h('form', { className: 'dim-accessPage', onSubmit: (event) => void save(event) },
274
+ h('fieldset', { className: 'dim-accessScene' },
275
+ h('legend', null, '新群聊默认设置'),
276
+ h('div', { className: 'dim-accessControls' },
277
+ h(ModeField, {
278
+ entry: state.defaults,
279
+ disabled: saving,
280
+ onChange: (mode) => updateDefault({ mode }),
281
+ })),
282
+ h(MembersField, {
283
+ entry: state.defaults,
284
+ disabled: saving,
285
+ onChange: (sendersText) => updateDefault({ sendersText }),
286
+ })),
287
+
288
+ chatIds.map((chatId) => {
289
+ const configured = Object.hasOwn(state.groups, chatId);
290
+ const entry = state.groups[chatId] ?? state.defaults;
291
+ const info = state.seen[chatId] ?? {};
292
+ return h('fieldset', { key: chatId, className: 'dim-accessScene' },
293
+ h('legend', null, info.title || chatId),
294
+ h(ValueRow, { label: '群 ID', value: chatId }),
295
+ info.title ? h(ValueRow, { label: '标题', value: info.title }) : null,
296
+ h(ValueRow, {
297
+ label: '最近活动',
298
+ value: `${formatMoment(info.lastSeenAt)}${info.lastSenderName ? ` · ${info.lastSenderName}` : ''}`,
299
+ }),
300
+ configured
301
+ ? h(ModeField, {
302
+ entry,
303
+ disabled: saving,
304
+ onChange: (mode) => updateGroup(chatId, { mode }),
305
+ })
306
+ : h(ValueRow, {
307
+ label: '响应条件',
308
+ value: modeLabel(state.defaults.mode),
309
+ suffix: '(默认)',
310
+ }),
311
+ configured
312
+ ? h(MembersField, {
313
+ entry,
314
+ disabled: saving,
315
+ onChange: (sendersText) => updateGroup(chatId, { sendersText }),
316
+ })
317
+ : null,
318
+ h('div', { className: 'dim-accessActions' },
319
+ configured
320
+ ? null
321
+ : h('button', {
322
+ type: 'button',
323
+ className: 'dim-deliveryButton',
324
+ 'data-kind': 'primary',
325
+ disabled: saving,
326
+ onClick: () => updateGroup(chatId, {}),
327
+ }, '自定义'),
328
+ h('button', {
329
+ type: 'button',
330
+ className: 'dim-deliveryButton',
331
+ 'data-kind': 'danger',
332
+ disabled: saving,
333
+ onClick: () => removeGroup(chatId),
334
+ }, '× 移除')));
335
+ }),
336
+
337
+ h('fieldset', { className: 'dim-accessScene' },
338
+ h('legend', null, '添加群聊'),
339
+ h('label', { className: 'dim-accessField' },
340
+ h('span', null, '群 ID、@用户名或消息链接'),
341
+ h('textarea', {
342
+ ...AUTOFILL_GUARD,
343
+ value: manualId,
344
+ rows: 1,
345
+ spellCheck: false,
346
+ placeholder: '-1001234567890',
347
+ style: { resize: 'none', minHeight: '2.4em', overflow: 'hidden' },
348
+ onChange: (event) => setManualId(event.target.value.replace(/[\s\u00a0]+/g, '')),
349
+ onKeyDown: (event) => {
350
+ if (event.key !== 'Enter') return;
351
+ event.preventDefault();
352
+ if (!saving && !resolving && manualId) void addGroup();
353
+ },
354
+ }),
355
+ h('span', { className: 'dim-channelHelp' },
356
+ '支持数字 ID、@用户名、t.me/<name> 或 t.me/c/<id>/<msg>;真实 ID 通过 getChat 解析。')),
357
+ h('div', { className: 'dim-accessControls' },
358
+ h(ModeField, {
359
+ entry: addEntry,
360
+ disabled: saving,
361
+ onChange: (mode) => setAddDraft({ ...addEntry, mode }),
362
+ })),
363
+ h(MembersField, {
364
+ entry: addEntry,
365
+ disabled: saving,
366
+ onChange: (sendersText) => setAddDraft({ ...addEntry, sendersText }),
367
+ }),
368
+ h('div', { className: 'dim-accessActions' },
369
+ h('button', {
370
+ type: 'button',
371
+ className: 'dim-deliveryButton',
372
+ 'data-kind': 'primary',
373
+ disabled: saving || resolving || !manualId,
374
+ onClick: () => void addGroup(),
375
+ }, resolving ? '…' : '+ 添加'))),
376
+
377
+ feedback
378
+ ? h('p', {
379
+ className: 'dim-accessFeedback',
380
+ 'data-tone': feedback.tone,
381
+ role: feedback.tone === 'error' ? 'alert' : 'status',
382
+ 'aria-live': 'polite',
383
+ }, feedback.message, feedback.detail ? h('code', { className: 'dim-groupTriggerValue' }, feedback.detail) : null)
384
+ : null,
385
+
386
+ h('div', { className: 'dim-accessActions' },
387
+ h('button', {
388
+ type: 'submit',
389
+ className: 'dim-deliveryButton',
390
+ 'data-kind': 'primary',
391
+ disabled: saving,
392
+ }, saving ? '正在保存…' : '保存群聊设置')));
393
+ }
@@ -15,6 +15,10 @@ const CSS = String.raw`
15
15
  .dim-accountSettingsSwitch:checked { border-color: #229ed9; background: #229ed9; }
16
16
  .dim-accountSettingsSwitch:checked::before { transform: translateX(13px); background: #fff; }
17
17
  .dim-accountSettingsSwitch:disabled { opacity: 0.5; cursor: not-allowed; }
18
+ .dim-accountSettingsSelect { flex: none; min-width: 0; max-width: 60%; margin: 0; padding: 4px 6px; border: 1px solid var(--dsw-alias-border-l2, #dfe1e5); border-radius: 6px; background: var(--dsw-alias-bg-layer-1, #fff); color: var(--dsw-alias-label-primary, #1f2329); font: inherit; font-size: 13px; line-height: 20px; }
19
+ .dim-accountSettingsSelect:disabled { opacity: 0.5; cursor: not-allowed; }
20
+ .dim-accountSettingsNumber { appearance: textfield; flex: none; width: 64px; margin: 0; padding: 4px 6px; border: 1px solid var(--dsw-alias-border-l2, #dfe1e5); border-radius: 6px; background: var(--dsw-alias-bg-layer-1, #fff); color: var(--dsw-alias-label-primary, #1f2329); font: inherit; font-size: 13px; line-height: 20px; text-align: center; }
21
+ .dim-accountSettingsNumber:disabled { opacity: 0.5; cursor: not-allowed; }
18
22
  @media (prefers-reduced-motion: reduce) { .dim-accountSettingsSwitch::before { transition: none; } }
19
23
  `;
20
24
 
@@ -1,13 +1,112 @@
1
1
  /**
2
- * 会话行为设置块:思考过程留痕开关(Telegram 专属)。
2
+ * 会话行为设置块:思考过程留痕、帧编号、帧节奏与消息发送上限(Telegram 专属)。
3
3
  *
4
- * 开启后,机器人把 agent 的推理与工具调用作为独立的 💭/🔧 消息实时发出来,
5
- * 最终答案单独成条;关闭则回到「占位符被最终答案覆盖」的原有单消息行为。
4
+ * 开启留痕后,机器人把 agent 的推理与工具调用作为独立的 💭/🔧 消息实时发出来,
5
+ * 最终答案单独成条;关闭留痕后使用常规占位符进度,完成时删除占位符并发送答案。
6
+ * 一轮里可能产生几十帧,所以另外两个设置决定这串消息的样子:编号让顺序可见,
7
+ * 节奏把突发合并成最新一帧,而不是排一队过期的消息。
6
8
  */
9
+ import { normalizeThinkingIntervalSeconds } from '../../../../src/channels/shared/thinking-cadence.mjs';
10
+ import { DEFAULT_SEND_LIMIT_PER_MINUTE } from '../../../../src/channels/shared/send-limit.mjs';
7
11
  import { h } from '../../i18n.js';
12
+ import * as React from 'react';
8
13
 
9
- export function ThinkingTracesSettings({ account, busy, onSave }) {
14
+ /** 0 表示不限制;其余是常见的步长,最大一分钟。 */
15
+ export const THINKING_INTERVAL_OPTIONS = Object.freeze([
16
+ 0, 1, 2, 3, 5, 7, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60,
17
+ ]);
18
+
19
+ /** 配置里可能存着列表外的值(旧配置或手工编辑),补一个选项而不是静默改成 0。 */
20
+ function intervalValues(saved) {
21
+ if (THINKING_INTERVAL_OPTIONS.includes(saved)) return THINKING_INTERVAL_OPTIONS;
22
+ return [...THINKING_INTERVAL_OPTIONS, saved].sort((left, right) => left - right);
23
+ }
24
+
25
+ function SendLimitField({ account, busy, saving, onCommit }) {
26
+ const saved = Number.isInteger(account.sendLimitPerMinute)
27
+ ? account.sendLimitPerMinute
28
+ : DEFAULT_SEND_LIMIT_PER_MINUTE;
29
+ const [value, setValue] = React.useState(String(saved));
30
+ // A save from another tab, or a reconnect, rewrites the stored value.
31
+ React.useEffect(() => { setValue(String(saved)); }, [saved]);
32
+ const commit = () => {
33
+ const numeric = Number(value.trim());
34
+ if (!value.trim() || !Number.isFinite(numeric) || Math.round(numeric) === saved) {
35
+ setValue(String(saved));
36
+ return;
37
+ }
38
+ onCommit?.(Math.round(numeric));
39
+ };
40
+ return h('label', { className: 'dim-accountSettingsRow' },
41
+ h('span', { className: 'dim-accountSettingsText' },
42
+ h('span', { className: 'dim-accountSettingsLabel' }, '消息发送上限'),
43
+ h('span', { className: 'dim-accountSettingsHelp' },
44
+ '每个聊天每分钟的消息数;机器人会等待而不是丢弃')),
45
+ h('input', {
46
+ type: 'number',
47
+ min: 1,
48
+ max: 30,
49
+ step: 1,
50
+ className: 'dim-accountSettingsNumber',
51
+ value,
52
+ disabled: Boolean(busy) || saving,
53
+ onChange: (event) => { setValue(event.target.value); },
54
+ onBlur: commit,
55
+ onKeyDown: (event) => {
56
+ if (event.key !== 'Enter') return;
57
+ event.preventDefault();
58
+ commit();
59
+ },
60
+ }));
61
+ }
62
+
63
+ export function ThinkingTracesSettings({
64
+ account, busy, onSave, rpcCall, endpoints, onChanged,
65
+ }) {
10
66
  const checked = account.thinkingTraces !== false;
67
+ const storedNumbering = account.thinkingNumbering === true;
68
+ const storedInterval = normalizeThinkingIntervalSeconds(account.thinkingIntervalSeconds);
69
+ // 两个新控件共用一个 RPC,所以各自提交时都要带上对方的当前值。
70
+ const [draft, setDraft] = React.useState({
71
+ thinkingNumbering: storedNumbering,
72
+ thinkingIntervalSeconds: storedInterval,
73
+ });
74
+ // 另一个标签页保存过、或重连之后,服务端存的值才是准的。
75
+ React.useEffect(() => {
76
+ setDraft({ thinkingNumbering: storedNumbering, thinkingIntervalSeconds: storedInterval });
77
+ }, [storedNumbering, storedInterval]);
78
+ const [saving, setSaving] = React.useState(false);
79
+ const endpoint = endpoints?.setThinkingCadence;
80
+ const commit = async (patch) => {
81
+ if (typeof rpcCall !== 'function' || !endpoint) return;
82
+ const next = { ...draft, ...patch };
83
+ setDraft(next);
84
+ setSaving(true);
85
+ try {
86
+ const response = await rpcCall(endpoint, { botId: account.botId, ...next });
87
+ if (response && response.ok === false) throw new Error(response.error?.message ?? '请求失败');
88
+ await onChanged?.({ silent: true });
89
+ } catch {
90
+ // 服务端存的值仍然作准:界面回到它,免得显示一个没保存的节奏。
91
+ setDraft({ thinkingNumbering: storedNumbering, thinkingIntervalSeconds: storedInterval });
92
+ } finally {
93
+ setSaving(false);
94
+ }
95
+ };
96
+ const sendLimitEndpoint = endpoints?.setSendLimit;
97
+ const commitSendLimit = async (sendLimitPerMinute) => {
98
+ if (typeof rpcCall !== 'function' || !sendLimitEndpoint) return;
99
+ setSaving(true);
100
+ try {
101
+ const response = await rpcCall(sendLimitEndpoint, { botId: account.botId, sendLimitPerMinute });
102
+ if (response && response.ok === false) throw new Error(response.error?.message ?? '请求失败');
103
+ await onChanged?.({ silent: true });
104
+ } catch {
105
+ // The stored value stays authoritative; the next reload shows it again.
106
+ } finally {
107
+ setSaving(false);
108
+ }
109
+ };
11
110
  return h('div', { className: 'dim-accountSettings' },
12
111
  h('h4', { className: 'dim-accountSettingsTitle' }, '会话行为'),
13
112
  h('label', { className: 'dim-accountSettingsRow' },
@@ -21,5 +120,39 @@ export function ThinkingTracesSettings({ account, busy, onSave }) {
21
120
  checked,
22
121
  disabled: Boolean(busy),
23
122
  onChange: (event) => { onSave?.({ thinkingTraces: event.target.checked }); },
24
- })));
123
+ })),
124
+ h('label', { className: 'dim-accountSettingsRow' },
125
+ h('span', { className: 'dim-accountSettingsText' },
126
+ h('span', { className: 'dim-accountSettingsLabel' }, '编号思考帧'),
127
+ h('span', { className: 'dim-accountSettingsHelp' },
128
+ '在每帧前加上本轮序号;被节奏跳过的帧也计数,所以编号会跳号(需先打开思考过程留痕)')),
129
+ h('input', {
130
+ type: 'checkbox',
131
+ className: 'dim-accountSettingsSwitch',
132
+ checked: draft.thinkingNumbering,
133
+ disabled: Boolean(busy) || saving,
134
+ onChange: (event) => { void commit({ thinkingNumbering: event.target.checked }); },
135
+ })),
136
+ h('label', { className: 'dim-accountSettingsRow' },
137
+ h('span', { className: 'dim-accountSettingsText' },
138
+ h('span', { className: 'dim-accountSettingsLabel' }, '最多每隔多久发送一帧(秒)'),
139
+ h('span', { className: 'dim-accountSettingsHelp' },
140
+ '突发时只发送窗口里最新的一帧,过期的帧丢弃,不排队也不重发')),
141
+ h('select', {
142
+ className: 'dim-accountSettingsSelect',
143
+ value: String(draft.thinkingIntervalSeconds),
144
+ disabled: Boolean(busy) || saving,
145
+ onChange: (event) => {
146
+ void commit({ thinkingIntervalSeconds: Number(event.target.value) });
147
+ },
148
+ }, intervalValues(draft.thinkingIntervalSeconds).map((value) => h('option', {
149
+ key: value,
150
+ value: String(value),
151
+ }, value === 0 ? '不限制(0)' : String(value))))),
152
+ h(SendLimitField, {
153
+ account,
154
+ busy: Boolean(busy),
155
+ saving,
156
+ onCommit: commitSendLimit,
157
+ }));
25
158
  }