@xmanrui/dsh-im 4.13.0 → 4.15.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.
- package/README.en.md +8 -1
- package/README.md +8 -1
- package/lib/client.js +327 -3
- package/lib/index.js +249 -245
- package/package.json +1 -1
- package/plugin-src/client/channels/feishu/api.js +2 -0
- package/plugin-src/client/channels/feishu/index.js +58 -1
- package/plugin-src/client/i18n.js +6 -1
- package/plugin-src/client/index.js +3 -0
- package/plugin-src/client/session-channel-logos.js +241 -0
- package/plugin-src/host/channels/feishu/production.mjs +1 -0
- package/plugin-src/host/channels/feishu/rpc.mjs +16 -0
- package/plugin-src/host/index.mjs +14 -0
- package/plugin-src/host/session-title-prefix.mjs +122 -0
- package/scripts/verify-session-channel-logos.mjs +59 -0
- package/scripts/verify-session-title-prefix.mjs +149 -0
- package/src/channels/feishu/bridge.mjs +520 -6
- package/src/channels/feishu/feishu-runtime.mjs +9 -0
- package/src/channels/feishu/multi-bot-controller.mjs +16 -0
- package/src/channels/feishu/plugin-config-store.mjs +1 -0
- package/src/channels/feishu/plugin-controller.mjs +1 -0
- package/src/channels/feishu/repair-manager.mjs +3 -2
- package/src/channels/shared/bot-workspace-store.mjs +14 -1
- package/src/channels/shared/harness-client.mjs +21 -2
- package/src/channels/shared/i18n-en/feishu.mjs +4 -2
- package/src/channels/shared/semantic/artifact.mjs +3 -1
- package/src/channels/shared/session-channel-labels.mjs +26 -0
package/package.json
CHANGED
|
@@ -32,6 +32,7 @@ export const FEISHU_ENDPOINTS = Object.freeze({
|
|
|
32
32
|
setAccessPolicy: "bot.access-policy.set",
|
|
33
33
|
setGroupResponseMode: "bot.group-response-mode.set",
|
|
34
34
|
setGroupTopicReply: "bot.group-topic-reply.set",
|
|
35
|
+
setStepPush: "bot.step-push.set",
|
|
35
36
|
// Kept for rolling upgrades. The multi-bot UI never calls these endpoints.
|
|
36
37
|
testConnection: "connection.test",
|
|
37
38
|
disconnect: "connection.disconnect",
|
|
@@ -217,6 +218,7 @@ export function normalizeBotConnection(value, fallbackBotId) {
|
|
|
217
218
|
: {}),
|
|
218
219
|
groupResponseMode: normalizeGroupResponseMode(value.groupResponseMode),
|
|
219
220
|
groupTopicReply: value.groupTopicReply === true,
|
|
221
|
+
stepPush: value.stepPush === true,
|
|
220
222
|
groupMessagePermissionGranted: value.groupMessagePermissionGranted === true,
|
|
221
223
|
bot: normalizeBot(value.bot),
|
|
222
224
|
health: normalizeHealth(value.health, connected),
|
|
@@ -310,7 +310,7 @@ function QrPane({ provision, now, onRefresh, onCancel, busy }) {
|
|
|
310
310
|
? "使用飞书确认群消息权限"
|
|
311
311
|
: "使用飞书扫码创建机器人"),
|
|
312
312
|
h("p", null, repairing
|
|
313
|
-
? "扫码会更新现有飞书应用,增量补充当前缺少的卡片按钮回调、读取用户消息内图片或文件所需的 im:message:readonly(飞书显示为“获取单聊、群组消息”)、上传机器人图片或文件所需的 im:resource,以及原生命令面板所需的 application:app_slash_command:read / write;不会创建新应用。确认页只显示当前缺少项,完成后此机器人会短暂重连,其他机器人不受影响。"
|
|
313
|
+
? "扫码会更新现有飞书应用,增量补充当前缺少的卡片按钮回调、读取用户消息内图片或文件所需的 im:message:readonly(飞书显示为“获取单聊、群组消息”)、上传机器人图片或文件所需的 im:resource、接收群内其他机器人 @ 当前机器人所需的 im:message.group_at_msg.include_bot:readonly,以及原生命令面板所需的 application:app_slash_command:read / write;不会创建新应用。确认页只显示当前缺少项,完成后此机器人会短暂重连,其他机器人不受影响。"
|
|
314
314
|
: grantingGroupMessages
|
|
315
315
|
? "扫码会更新现有飞书应用,只增量开通“获取群组中所有消息”权限;不会创建新应用。确认后会自动启用“响应所有群消息”,其他机器人不受影响。"
|
|
316
316
|
: "扫码只会新增一个机器人,已接入的机器人会继续正常收发消息。"),
|
|
@@ -464,6 +464,53 @@ function RemoveConfirmation({ bot, busy, onConfirm, onCancel }) {
|
|
|
464
464
|
);
|
|
465
465
|
}
|
|
466
466
|
|
|
467
|
+
/** Toggle row for 分步直推, mirroring the group-topic reply toggle pattern. */
|
|
468
|
+
function StepPushEditor({ value = false, disabled = false, onSave }) {
|
|
469
|
+
const titleId = React.useId();
|
|
470
|
+
const current = value === true ? "on" : "off";
|
|
471
|
+
const [saving, setSaving] = React.useState(false);
|
|
472
|
+
const [error, setError] = React.useState(null);
|
|
473
|
+
|
|
474
|
+
const change = async (event) => {
|
|
475
|
+
const next = event.target.value === "on";
|
|
476
|
+
if ((next ? "on" : "off") === current || saving || disabled) return;
|
|
477
|
+
setSaving(true);
|
|
478
|
+
setError(null);
|
|
479
|
+
try {
|
|
480
|
+
await onSave?.(next);
|
|
481
|
+
} catch (cause) {
|
|
482
|
+
setError(cause?.message ?? "分步直推设置保存失败,请重试。");
|
|
483
|
+
} finally {
|
|
484
|
+
setSaving(false);
|
|
485
|
+
}
|
|
486
|
+
};
|
|
487
|
+
|
|
488
|
+
return h("section", {
|
|
489
|
+
className: "dim-feishuGroupControl",
|
|
490
|
+
"aria-labelledby": titleId,
|
|
491
|
+
},
|
|
492
|
+
h("div", { className: "dim-feishuGroupControlHeader" },
|
|
493
|
+
h("h3", { id: titleId }, "分步直推"),
|
|
494
|
+
saving
|
|
495
|
+
? h("span", { className: "dim-feishuGroupControlStatus", role: "status" }, "保存中…")
|
|
496
|
+
: null),
|
|
497
|
+
h("select", {
|
|
498
|
+
className: "dim-feishuGroupSelect",
|
|
499
|
+
value: current,
|
|
500
|
+
disabled: disabled || saving,
|
|
501
|
+
"aria-label": "分步直推",
|
|
502
|
+
onChange: (event) => { void change(event); },
|
|
503
|
+
},
|
|
504
|
+
h("option", { value: "off" }, "关闭(保持流式卡模式)"),
|
|
505
|
+
h("option", { value: "on" }, "开启(逐步推送工具调用与过程说明)")),
|
|
506
|
+
h("p", { className: "dim-feishuGroupHelp" },
|
|
507
|
+
"开启后逐步推送工具调用与过程说明"),
|
|
508
|
+
error ? h("p", {
|
|
509
|
+
className: "dim-feishuGroupError",
|
|
510
|
+
role: "alert",
|
|
511
|
+
}, error) : null);
|
|
512
|
+
}
|
|
513
|
+
|
|
467
514
|
export function BotCard({
|
|
468
515
|
connection,
|
|
469
516
|
busy,
|
|
@@ -479,6 +526,7 @@ export function BotCard({
|
|
|
479
526
|
onModelSave,
|
|
480
527
|
onAgentPresetSave,
|
|
481
528
|
onContextEnhancementSave,
|
|
529
|
+
onStepPushSave,
|
|
482
530
|
onRequestRemove,
|
|
483
531
|
onConfirmRemove,
|
|
484
532
|
onCancelRemove,
|
|
@@ -565,6 +613,11 @@ export function BotCard({
|
|
|
565
613
|
disabled: Boolean(busy),
|
|
566
614
|
onSave: onContextEnhancementSave,
|
|
567
615
|
}),
|
|
616
|
+
h(StepPushEditor, {
|
|
617
|
+
value: connection.stepPush,
|
|
618
|
+
disabled: Boolean(busy),
|
|
619
|
+
onSave: onStepPushSave,
|
|
620
|
+
}),
|
|
568
621
|
provisionContent
|
|
569
622
|
? h("section", {
|
|
570
623
|
className: "bxf-botProvision dim-botProvision",
|
|
@@ -657,6 +710,7 @@ function BotList(props) {
|
|
|
657
710
|
onModelSave: (model) => props.onModelSave(bot, model),
|
|
658
711
|
onAgentPresetSave: (agentPreset) => props.onAgentPresetSave(bot, agentPreset),
|
|
659
712
|
onContextEnhancementSave: (config) => props.onContextEnhancementSave(bot, config),
|
|
713
|
+
onStepPushSave: (stepPush) => props.onStepPushSave(bot, stepPush),
|
|
660
714
|
onRequestRemove: () => props.onRequestRemove(bot),
|
|
661
715
|
onConfirmRemove: () => props.onConfirmRemove(bot),
|
|
662
716
|
onCancelRemove: props.onCancelRemove,
|
|
@@ -1431,6 +1485,9 @@ export function FeishuSettingsTab({ rpcCall }) {
|
|
|
1431
1485
|
onContextEnhancementSave: (connection, config) => saveBotSetting(
|
|
1432
1486
|
connection, "context-enhancement", FEISHU_ENDPOINTS.setContextEnhancement, { config },
|
|
1433
1487
|
),
|
|
1488
|
+
onStepPushSave: (connection, stepPush) => saveBotSetting(
|
|
1489
|
+
connection, "step-push", FEISHU_ENDPOINTS.setStepPush, { stepPush },
|
|
1490
|
+
),
|
|
1434
1491
|
onRequestRemove: requestRemove,
|
|
1435
1492
|
onConfirmRemove: (bot) => void confirmRemove(bot),
|
|
1436
1493
|
onCancelRemove: cancelRemove,
|
|
@@ -220,6 +220,11 @@ const EN = Object.freeze({
|
|
|
220
220
|
'关闭(群内直接回复)': 'Off (reply in the group feed)',
|
|
221
221
|
'开启(自动开启独立飞书话题)': 'On (auto-open a dedicated Feishu topic)',
|
|
222
222
|
'开启后,群聊中向机器人提问会自动开启独立飞书话题,回复落在话题内;每个话题是 dsh 会话列表里一条独立会话,上下文互不串。私聊不受影响。': 'When enabled, questions to the bot in a group auto-open a dedicated Feishu topic and replies stay inside it. Each topic is an independent conversation in dsh with its own context. Private chats are unaffected.',
|
|
223
|
+
'分步直推': 'Step push',
|
|
224
|
+
'开启后逐步推送工具调用与过程说明': 'Push tool calls and process notes step by step',
|
|
225
|
+
'关闭(保持流式卡模式)': 'Off (keep the streaming card)',
|
|
226
|
+
'开启(逐步推送工具调用与过程说明)': 'On (push tool calls and process notes step by step)',
|
|
227
|
+
'分步直推设置保存失败,请重试。': 'Could not save the step push setting. Try again.',
|
|
223
228
|
'钉钉设置': 'DingTalk settings',
|
|
224
229
|
'企业微信设置': 'WeCom settings',
|
|
225
230
|
'扫码接入机器人': 'Scan QR code',
|
|
@@ -454,7 +459,7 @@ const EN = Object.freeze({
|
|
|
454
459
|
'权限配置已提交,正在启用全部消息模式并重连此机器人;此阶段无法取消,其他机器人不会中断。': 'The permission update was submitted. Enabling all-message mode and reconnecting this bot. This stage cannot be cancelled; other bots will not be interrupted.',
|
|
455
460
|
'正在为现有飞书应用申请群消息权限二维码,请稍候。': 'Requesting a group-message permission QR code for the existing Feishu app…',
|
|
456
461
|
'群消息权限没有开通完成': 'Group-message permission was not granted',
|
|
457
|
-
'扫码会更新现有飞书应用,增量补充当前缺少的卡片按钮回调、读取用户消息内图片或文件所需的 im:message:readonly(飞书显示为“获取单聊、群组消息”)、上传机器人图片或文件所需的 im:resource,以及原生命令面板所需的 application:app_slash_command:read / write;不会创建新应用。确认页只显示当前缺少项,完成后此机器人会短暂重连,其他机器人不受影响。': 'Scanning updates the existing Feishu app with the missing card-button callback, im:message:readonly for reading images or files in user messages (shown by Feishu as “Read direct and group messages”), im:resource for uploading images or files sent by the bot, and application:app_slash_command:read / write for the native command panel. It does not create a new app. The confirmation page shows only missing items; this bot reconnects briefly afterward, while other bots are unaffected.',
|
|
462
|
+
'扫码会更新现有飞书应用,增量补充当前缺少的卡片按钮回调、读取用户消息内图片或文件所需的 im:message:readonly(飞书显示为“获取单聊、群组消息”)、上传机器人图片或文件所需的 im:resource、接收群内其他机器人 @ 当前机器人所需的 im:message.group_at_msg.include_bot:readonly,以及原生命令面板所需的 application:app_slash_command:read / write;不会创建新应用。确认页只显示当前缺少项,完成后此机器人会短暂重连,其他机器人不受影响。': 'Scanning updates the existing Feishu app with the missing card-button callback, im:message:readonly for reading images or files in user messages (shown by Feishu as “Read direct and group messages”), im:resource for uploading images or files sent by the bot, im:message.group_at_msg.include_bot:readonly for receiving group messages from other bots that mention this bot, and application:app_slash_command:read / write for the native command panel. It does not create a new app. The confirmation page shows only missing items; this bot reconnects briefly afterward, while other bots are unaffected.',
|
|
458
463
|
'核对现有应用名称,并确认只新增当前缺少的上述配置': 'Review the existing app name and confirm that only the missing items described above are added',
|
|
459
464
|
'保持本页打开,等待权限与回调补全完成': 'Keep this page open until permissions and the callback are complete',
|
|
460
465
|
'取消补全': 'Cancel setup',
|
|
@@ -59,6 +59,7 @@ import {
|
|
|
59
59
|
replacePageLocation,
|
|
60
60
|
} from './loopback-recovery.js';
|
|
61
61
|
import { installImStyles } from './styles.js';
|
|
62
|
+
import { installSessionChannelLogos } from './session-channel-logos.js';
|
|
62
63
|
import { UpdatePanel, UPDATE_RPC_CHANNEL } from './update-panel.js';
|
|
63
64
|
import { WorkspaceDirectoryPickerContext } from './workspace-editor.js';
|
|
64
65
|
|
|
@@ -366,6 +367,8 @@ export function apply(ctx) {
|
|
|
366
367
|
const t = ctx.locale.bind(IM_LOCALE_NAMESPACE);
|
|
367
368
|
setImTranslator(t);
|
|
368
369
|
|
|
370
|
+
ctx.effect(() => installSessionChannelLogos(), 'im-settings: Session channel logos');
|
|
371
|
+
|
|
369
372
|
ctx.effect(() => {
|
|
370
373
|
const disposers = [
|
|
371
374
|
installFeishuStyles(),
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import { parseSessionChannelTitle } from '../../src/channels/shared/session-channel-labels.mjs';
|
|
2
|
+
import {
|
|
3
|
+
WeixinLogoGlyph, FeishuLogoGlyph, DingtalkLogoGlyph, WecomLogoGlyph, QqLogoGlyph,
|
|
4
|
+
SlackLogoGlyph, TelegramLogoGlyph, DiscordLogoGlyph, WhatsappLogoGlyph, OfficeLogoGlyph,
|
|
5
|
+
} from './channel-logos.js';
|
|
6
|
+
|
|
7
|
+
const GLYPHS = Object.freeze({
|
|
8
|
+
weixin: [WeixinLogoGlyph, '#07c160'],
|
|
9
|
+
feishu: [FeishuLogoGlyph, '#3370ff'],
|
|
10
|
+
dingtalk: [DingtalkLogoGlyph, '#1677ff'],
|
|
11
|
+
wecom: [WecomLogoGlyph, '#3370ff'],
|
|
12
|
+
qq: [QqLogoGlyph, '#12b7f5'],
|
|
13
|
+
slack: [SlackLogoGlyph, '#e01e5a'],
|
|
14
|
+
telegram: [TelegramLogoGlyph, '#229ed9'],
|
|
15
|
+
discord: [DiscordLogoGlyph, '#5865f2'],
|
|
16
|
+
whatsapp: [WhatsappLogoGlyph, '#25d366'],
|
|
17
|
+
office: [OfficeLogoGlyph, '#f97316'],
|
|
18
|
+
});
|
|
19
|
+
const CHANNEL_ATTR = 'data-dsh-im-session-channel';
|
|
20
|
+
const TITLE_ATTR = 'data-dsh-im-session-text';
|
|
21
|
+
const MARKED = `[${CHANNEL_ATTR}]`;
|
|
22
|
+
const ROW = '[role="treeitem"][aria-selected]';
|
|
23
|
+
const SVG_NS = 'http://www.w3.org/2000/svg';
|
|
24
|
+
const installations = new WeakMap();
|
|
25
|
+
|
|
26
|
+
function hasClassPart(element, part) {
|
|
27
|
+
const match = new RegExp(`(?:^|[_-])${part}(?:$|[_-])`, 'u');
|
|
28
|
+
return [...element.classList].some((token) => match.test(token));
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function titleOf(row) {
|
|
32
|
+
if (!row.matches(ROW) || row.closest('input, textarea, [contenteditable]:not([contenteditable="false"])')) return null;
|
|
33
|
+
let title;
|
|
34
|
+
if (row.tagName === 'DIV' && hasClassPart(row, 'sessionRow')) {
|
|
35
|
+
title = [...row.children].find((child) => child.tagName === 'SPAN' && hasClassPart(child, 'title'));
|
|
36
|
+
} else if (row.tagName === 'BUTTON' && hasClassPart(row, 'searchResultRow')) {
|
|
37
|
+
const heading = [...row.children].find((child) => hasClassPart(child, 'searchResultHeading'));
|
|
38
|
+
title = heading && [...heading.children].find((child) => child.tagName === 'SPAN' && hasClassPart(child, 'searchResultTitle'));
|
|
39
|
+
}
|
|
40
|
+
// Never cover inline rename inputs, highlighted search markup, or a future
|
|
41
|
+
// row structure that this adapter does not understand.
|
|
42
|
+
return title?.childNodes.length === 1 && title.firstChild.nodeType === 3 ? title : null;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** Serialize the existing, static SVG glyphs without mounting React nodes. */
|
|
46
|
+
function logoUri(document, channel) {
|
|
47
|
+
const [Glyph, color] = GLYPHS[channel];
|
|
48
|
+
const render = (node) => {
|
|
49
|
+
if (!['svg', 'path'].includes(node.type)) throw new Error('Unsupported channel logo element');
|
|
50
|
+
const element = document.createElementNS(SVG_NS, node.type);
|
|
51
|
+
for (const [name, value] of Object.entries(node.props)) {
|
|
52
|
+
if (name === 'children') continue;
|
|
53
|
+
const attribute = name.startsWith('stroke')
|
|
54
|
+
? name.replace(/[A-Z]/gu, (letter) => `-${letter.toLowerCase()}`)
|
|
55
|
+
: name;
|
|
56
|
+
element.setAttribute(attribute, String(value));
|
|
57
|
+
}
|
|
58
|
+
for (const child of [node.props.children].flat().filter(Boolean)) element.appendChild(render(child));
|
|
59
|
+
return element;
|
|
60
|
+
};
|
|
61
|
+
const svg = render(Glyph({ size: 16 }));
|
|
62
|
+
svg.setAttribute('xmlns', SVG_NS);
|
|
63
|
+
svg.setAttribute('color', color);
|
|
64
|
+
return `data:image/svg+xml,${encodeURIComponent(svg.outerHTML)}`;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function createInstallation(document) {
|
|
68
|
+
const view = document.defaultView;
|
|
69
|
+
const ready = new Set();
|
|
70
|
+
const owned = new Map();
|
|
71
|
+
const queued = new Set();
|
|
72
|
+
const images = [];
|
|
73
|
+
let closed = false;
|
|
74
|
+
let scheduled = false;
|
|
75
|
+
const style = document.createElement('style');
|
|
76
|
+
style.dataset.pluginCss = 'dsh-im-session-channel-logos';
|
|
77
|
+
const uris = Object.fromEntries(Object.keys(GLYPHS).map((channel) => [channel, logoUri(document, channel)]));
|
|
78
|
+
style.textContent = `
|
|
79
|
+
${MARKED}[${TITLE_ATTR}] {
|
|
80
|
+
position: relative;
|
|
81
|
+
-webkit-text-fill-color: transparent;
|
|
82
|
+
text-overflow: clip !important;
|
|
83
|
+
overflow: hidden;
|
|
84
|
+
}
|
|
85
|
+
${MARKED}[${TITLE_ATTR}]::before {
|
|
86
|
+
content: "";
|
|
87
|
+
position: absolute;
|
|
88
|
+
inset-inline-start: 0;
|
|
89
|
+
top: 50%;
|
|
90
|
+
transform: translateY(-50%);
|
|
91
|
+
width: 16px;
|
|
92
|
+
height: 16px;
|
|
93
|
+
background: var(--dsh-im-session-logo) center / contain no-repeat;
|
|
94
|
+
text-indent: 0;
|
|
95
|
+
pointer-events: none;
|
|
96
|
+
}
|
|
97
|
+
${MARKED}[${TITLE_ATTR}]::after {
|
|
98
|
+
content: attr(${TITLE_ATTR}) / "";
|
|
99
|
+
position: absolute;
|
|
100
|
+
inset: 0;
|
|
101
|
+
inset-inline-start: 22px;
|
|
102
|
+
-webkit-text-fill-color: currentColor;
|
|
103
|
+
text-indent: 0;
|
|
104
|
+
overflow: hidden;
|
|
105
|
+
white-space: nowrap;
|
|
106
|
+
text-overflow: ellipsis;
|
|
107
|
+
pointer-events: none;
|
|
108
|
+
}
|
|
109
|
+
${Object.entries(uris).map(([channel, uri]) => `[${CHANNEL_ATTR}="${channel}"] { --dsh-im-session-logo: url("${uri}"); }`).join('\n')}
|
|
110
|
+
`;
|
|
111
|
+
document.head.appendChild(style);
|
|
112
|
+
|
|
113
|
+
const restore = (title) => {
|
|
114
|
+
const previous = owned.get(title);
|
|
115
|
+
if (!previous) return;
|
|
116
|
+
owned.delete(title);
|
|
117
|
+
for (const [attribute, value] of previous) {
|
|
118
|
+
if (value === null) title.removeAttribute(attribute);
|
|
119
|
+
else title.setAttribute(attribute, value);
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
const update = (row) => {
|
|
123
|
+
const title = row.isConnected ? titleOf(row) : null;
|
|
124
|
+
for (const marked of row.querySelectorAll(MARKED)) {
|
|
125
|
+
if (marked !== title) restore(marked);
|
|
126
|
+
}
|
|
127
|
+
if (!title) return;
|
|
128
|
+
const parsed = parseSessionChannelTitle(title.textContent);
|
|
129
|
+
if (!parsed || !ready.has(parsed.channel)) {
|
|
130
|
+
restore(title);
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
if (!owned.has(title)) {
|
|
134
|
+
owned.set(title, [CHANNEL_ATTR, TITLE_ATTR].map((attribute) => [attribute, title.getAttribute(attribute)]));
|
|
135
|
+
}
|
|
136
|
+
// React retains its original text node, content, row, and handlers. Only
|
|
137
|
+
// plugin-owned attributes drive the visual replacement via pseudo-elements.
|
|
138
|
+
title.setAttribute(TITLE_ATTR, parsed.title);
|
|
139
|
+
title.setAttribute(CHANNEL_ATTR, parsed.channel);
|
|
140
|
+
};
|
|
141
|
+
const schedule = () => {
|
|
142
|
+
if (closed || scheduled || !queued.size) return;
|
|
143
|
+
scheduled = true;
|
|
144
|
+
queueMicrotask(() => {
|
|
145
|
+
scheduled = false;
|
|
146
|
+
if (closed) return;
|
|
147
|
+
const rows = [...queued];
|
|
148
|
+
queued.clear();
|
|
149
|
+
for (const row of rows) {
|
|
150
|
+
try {
|
|
151
|
+
update(row);
|
|
152
|
+
} catch {
|
|
153
|
+
for (const marked of row.querySelectorAll(MARKED)) restore(marked);
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
});
|
|
157
|
+
};
|
|
158
|
+
const collect = (node, descendants = false) => {
|
|
159
|
+
const element = node.nodeType === 1 ? node : node.parentElement;
|
|
160
|
+
if (!element) return;
|
|
161
|
+
const row = element.closest(ROW);
|
|
162
|
+
if (row) queued.add(row);
|
|
163
|
+
if (descendants) {
|
|
164
|
+
for (const child of element.querySelectorAll(ROW)) queued.add(child);
|
|
165
|
+
// Also restore an already decorated title moved outside a recognized row.
|
|
166
|
+
const marked = [...element.querySelectorAll(MARKED)];
|
|
167
|
+
if (owned.has(element)) marked.push(element);
|
|
168
|
+
for (const title of marked) {
|
|
169
|
+
const owner = title.closest(ROW);
|
|
170
|
+
if (owner) queued.add(owner);
|
|
171
|
+
else restore(title);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
schedule();
|
|
175
|
+
};
|
|
176
|
+
const observer = new view.MutationObserver((records) => {
|
|
177
|
+
if (closed) return;
|
|
178
|
+
for (const record of records) {
|
|
179
|
+
collect(record.target, record.type === 'attributes');
|
|
180
|
+
if (record.type !== 'childList') continue;
|
|
181
|
+
for (const node of record.addedNodes) collect(node, true);
|
|
182
|
+
for (const node of record.removedNodes) {
|
|
183
|
+
if (node.nodeType !== 1 || node.isConnected) continue;
|
|
184
|
+
if (owned.has(node)) restore(node);
|
|
185
|
+
for (const title of node.querySelectorAll(MARKED)) restore(title);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
observer.observe(document.body, {
|
|
190
|
+
subtree: true, childList: true, characterData: true,
|
|
191
|
+
attributes: true, attributeFilter: ['class', 'role', 'aria-selected', 'contenteditable'],
|
|
192
|
+
});
|
|
193
|
+
|
|
194
|
+
// A CSP or an image-loading failure leaves that channel's readable text
|
|
195
|
+
// prefix in place. No title is hidden until its actual SVG has loaded.
|
|
196
|
+
for (const [channel, uri] of Object.entries(uris)) {
|
|
197
|
+
const image = new view.Image();
|
|
198
|
+
images.push(image);
|
|
199
|
+
image.onload = () => {
|
|
200
|
+
if (closed) return;
|
|
201
|
+
ready.add(channel);
|
|
202
|
+
collect(document.body, true);
|
|
203
|
+
};
|
|
204
|
+
image.src = uri;
|
|
205
|
+
}
|
|
206
|
+
return () => {
|
|
207
|
+
closed = true;
|
|
208
|
+
observer.disconnect();
|
|
209
|
+
queued.clear();
|
|
210
|
+
for (const image of images) image.onload = null;
|
|
211
|
+
for (const title of [...owned.keys()]) restore(title);
|
|
212
|
+
style.remove();
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/** Browser-only enhancement; unknown/unsupported surfaces keep text prefixes. */
|
|
217
|
+
export function installSessionChannelLogos(document = globalThis.document) {
|
|
218
|
+
const view = document?.defaultView;
|
|
219
|
+
if (!document?.body || !document?.head || !view?.MutationObserver || !view?.Image
|
|
220
|
+
|| !view.CSS?.supports?.('content', `attr(${TITLE_ATTR}) / ""`)
|
|
221
|
+
|| !view.CSS.supports('-webkit-text-fill-color', 'transparent')) return () => {};
|
|
222
|
+
let entry = installations.get(document);
|
|
223
|
+
if (!entry) {
|
|
224
|
+
try {
|
|
225
|
+
entry = { references: 0, close: createInstallation(document) };
|
|
226
|
+
} catch {
|
|
227
|
+
return () => {};
|
|
228
|
+
}
|
|
229
|
+
installations.set(document, entry);
|
|
230
|
+
}
|
|
231
|
+
entry.references += 1;
|
|
232
|
+
let released = false;
|
|
233
|
+
return () => {
|
|
234
|
+
if (released) return;
|
|
235
|
+
released = true;
|
|
236
|
+
entry.references -= 1;
|
|
237
|
+
if (entry.references > 0) return;
|
|
238
|
+
entry.close();
|
|
239
|
+
installations.delete(document);
|
|
240
|
+
};
|
|
241
|
+
}
|
|
@@ -218,6 +218,7 @@ export async function createProductionController(ctx, config = {}, internals = {
|
|
|
218
218
|
botOpenId: botConfig.botOpenId,
|
|
219
219
|
groupResponseMode: botConfig.groupResponseMode,
|
|
220
220
|
groupTopicReply: botConfig.groupTopicReply,
|
|
221
|
+
stepPush: botConfig.stepPush,
|
|
221
222
|
ownerOpenIds: botConfig.ownerOpenIds ?? [botConfig.ownerOpenId],
|
|
222
223
|
harness: workspaceScope.harness,
|
|
223
224
|
state: workspaceScope.state,
|
|
@@ -294,6 +294,7 @@ function publicBotEntry(entry) {
|
|
|
294
294
|
accessPolicy: normalizeAccessPolicy(source.accessPolicy),
|
|
295
295
|
groupResponseMode: normalizeFeishuGroupResponseMode(source.groupResponseMode),
|
|
296
296
|
groupTopicReply: source.groupTopicReply === true,
|
|
297
|
+
stepPush: source.stepPush === true,
|
|
297
298
|
groupMessagePermissionGranted: source.groupMessagePermissionGranted === true,
|
|
298
299
|
bot: publicBot(source.bot),
|
|
299
300
|
health: publicHealth(source, connected),
|
|
@@ -458,6 +459,13 @@ function validPayload(endpoint, payload) {
|
|
|
458
459
|
? null
|
|
459
460
|
: '请选择是否以话题方式回复。';
|
|
460
461
|
}
|
|
462
|
+
if (endpoint === FEISHU_ENDPOINTS.setStepPush) {
|
|
463
|
+
return hasOnlyKeys(payload, new Set(['botId', 'stepPush']))
|
|
464
|
+
&& safeOpaqueId(payload.botId)
|
|
465
|
+
&& typeof payload.stepPush === 'boolean'
|
|
466
|
+
? null
|
|
467
|
+
: '请选择是否分步直推。';
|
|
468
|
+
}
|
|
461
469
|
return 'Unknown Feishu endpoint.';
|
|
462
470
|
}
|
|
463
471
|
|
|
@@ -742,6 +750,14 @@ export function createFeishuRpcHandler(controller, { encodeQr = qrCodeDataUrl }
|
|
|
742
750
|
await controller.updateGroupTopicReply(payload.botId, payload.groupTopicReply),
|
|
743
751
|
{ encodeQr: cachedEncodeQr },
|
|
744
752
|
);
|
|
753
|
+
} else if (endpoint === FEISHU_ENDPOINTS.setStepPush) {
|
|
754
|
+
if (typeof controller.updateStepPush !== 'function') {
|
|
755
|
+
throw new Error('Step push update is unavailable');
|
|
756
|
+
}
|
|
757
|
+
value = await toPublicFeishuStatus(
|
|
758
|
+
await controller.updateStepPush(payload.botId, payload.stepPush),
|
|
759
|
+
{ encodeQr: cachedEncodeQr },
|
|
760
|
+
);
|
|
745
761
|
} else {
|
|
746
762
|
if (typeof controller.deleteBot !== 'function') throw new Error('Multi-bot delete is unavailable');
|
|
747
763
|
value = await toPublicFeishuStatus(await controller.deleteBot(payload.botId), { encodeQr: cachedEncodeQr });
|
|
@@ -15,6 +15,7 @@ import { installDeliveryHttp } from './delivery-http.mjs';
|
|
|
15
15
|
import { createDeliveryService } from './delivery-service.mjs';
|
|
16
16
|
import { installInboundTtlRpc } from './inbound-ttl-rpc.mjs';
|
|
17
17
|
import { installSessionSyncCoordinator } from './session-sync-coordinator.mjs';
|
|
18
|
+
import { installSessionTitlePrefix } from './session-title-prefix.mjs';
|
|
18
19
|
import { installUpdateRpc } from './update-rpc.mjs';
|
|
19
20
|
|
|
20
21
|
export const name = 'dsh-im-host';
|
|
@@ -103,6 +104,19 @@ export function createImHostPlugin(internals = {}) {
|
|
|
103
104
|
|
|
104
105
|
async function activateChannels(ctx, config, deliveryService) {
|
|
105
106
|
setImHostLanguage(config.language ?? process.env.DSH_IM_LANGUAGE);
|
|
107
|
+
const startTitlePrefix = (titleCtx) => {
|
|
108
|
+
// The installer owns its cleanup through ctx.effect(). Cordis startup
|
|
109
|
+
// callbacks must not return its controller object as an effect.
|
|
110
|
+
installSessionTitlePrefix(titleCtx, {
|
|
111
|
+
logger: typeof titleCtx?.logger === 'function'
|
|
112
|
+
? titleCtx.logger('dsh-im:session-title') : (titleCtx?.logger ?? console),
|
|
113
|
+
});
|
|
114
|
+
};
|
|
115
|
+
if (typeof ctx?.inject === 'function') {
|
|
116
|
+
ctx.inject(['sessions'], startTitlePrefix);
|
|
117
|
+
} else if (ctx?.sessions && typeof ctx.on === 'function') {
|
|
118
|
+
startTitlePrefix(ctx);
|
|
119
|
+
}
|
|
106
120
|
if (typeof ctx?.inject === 'function') {
|
|
107
121
|
ctx.inject(['tools', 'systemPrompt'], (artifactCtx) => {
|
|
108
122
|
installOutboundArtifactTool(artifactCtx);
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import { getImHostLanguage } from '../../src/channels/shared/i18n.mjs';
|
|
2
|
+
import { SESSION_CHANNEL_LABELS as CHANNEL_LABELS } from '../../src/channels/shared/session-channel-labels.mjs';
|
|
3
|
+
const UUID = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}';
|
|
4
|
+
// HarnessClient uses these ids for prompts and steering, independently of
|
|
5
|
+
// context enhancement. Read the durable source, never the message's text.
|
|
6
|
+
const IM_RPC_ID = new RegExp(`^(${Object.keys(CHANNEL_LABELS).join('|')})-(?:steer-)?${UUID}$`, 'u');
|
|
7
|
+
const LEGACY_SESSION_ID = new RegExp(`^(${Object.keys(CHANNEL_LABELS).join('|')})-.+`, 'u');
|
|
8
|
+
|
|
9
|
+
function eventsOf(session) {
|
|
10
|
+
const events = typeof session?.snapshotEvents === 'function'
|
|
11
|
+
? session.snapshotEvents()
|
|
12
|
+
: session?.events;
|
|
13
|
+
return Array.isArray(events) ? events : [];
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function channelOf(session, events) {
|
|
17
|
+
// A Web-created fork must not acquire a channel just from its parent's
|
|
18
|
+
// messages. Both supported Session implementations expose this boundary.
|
|
19
|
+
const inherited = session.inheritedEventCount;
|
|
20
|
+
if (session.header?.parentSession && !Number.isSafeInteger(inherited)) return null;
|
|
21
|
+
for (const event of events) {
|
|
22
|
+
if (Number.isSafeInteger(inherited) && event.seq < inherited) continue;
|
|
23
|
+
if (event.type !== 'user/message' || event.data?.source?.kind !== 'user') continue;
|
|
24
|
+
const channel = IM_RPC_ID.exec(event.data.source.rpcId)?.[1];
|
|
25
|
+
if (channel) return channel;
|
|
26
|
+
}
|
|
27
|
+
if (session.header?.parentSession) return null;
|
|
28
|
+
return LEGACY_SESSION_ID.exec(session.id ?? session.sessionId)?.[1] ?? null;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function withSessionChannelPrefix(title, channel, language = getImHostLanguage()) {
|
|
32
|
+
const labels = CHANNEL_LABELS[channel];
|
|
33
|
+
if (!labels || typeof title !== 'string' || !title.trim()) return title;
|
|
34
|
+
// Keep the original title intact, including Unicode graphemes. The Host
|
|
35
|
+
// has already normalized and capped its generated text before this point.
|
|
36
|
+
if (labels.some((label) => title.startsWith(`${label} · `))) return title;
|
|
37
|
+
return `${labels[language === 'en' ? 1 : 0]} · ${title}`;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function validTitleData(data) {
|
|
41
|
+
if (typeof data?.title !== 'string' || !data.title.trim()
|
|
42
|
+
|| !Array.isArray(data.messageSeqs)) return false;
|
|
43
|
+
if (data.source?.kind === 'user') return data.messageSeqs.length === 0;
|
|
44
|
+
if (!['fallback', 'provider'].includes(data.source?.kind)
|
|
45
|
+
|| data.messageSeqs.length === 0
|
|
46
|
+
|| data.messageSeqs.some((seq) => !Number.isSafeInteger(seq) || seq < 0)) return false;
|
|
47
|
+
return data.source.kind !== 'provider'
|
|
48
|
+
|| (typeof data.source.provider === 'string' && Boolean(data.source.provider));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Decorate accepted titles without session.rename(): rename pins them as
|
|
53
|
+
* user-owned and supersedes automatic generation. Appending a log-only title
|
|
54
|
+
* with the same source and citations preserves the Host's scheduling and
|
|
55
|
+
* explicit-rename semantics. No provider, prompt, or stored event is changed.
|
|
56
|
+
*/
|
|
57
|
+
export function installSessionTitlePrefix(ctx, { logger = console } = {}) {
|
|
58
|
+
if (typeof ctx?.on !== 'function' || typeof ctx?.sessions?.get !== 'function'
|
|
59
|
+
|| typeof ctx?.sessions?.list !== 'function') {
|
|
60
|
+
throw new TypeError('Session title prefixes require Host sessions and events');
|
|
61
|
+
}
|
|
62
|
+
const pending = new Map();
|
|
63
|
+
let closed = false;
|
|
64
|
+
|
|
65
|
+
const decorate = (session) => {
|
|
66
|
+
if (closed || ctx.sessions.get(session.id ?? session.sessionId) !== session
|
|
67
|
+
|| typeof session.append !== 'function') return;
|
|
68
|
+
const events = eventsOf(session);
|
|
69
|
+
const channel = channelOf(session, events);
|
|
70
|
+
if (!channel) return;
|
|
71
|
+
const latest = events.findLast((event) => event.type === 'session/title');
|
|
72
|
+
if (!validTitleData(latest?.data)) return;
|
|
73
|
+
const title = withSessionChannelPrefix(latest.data.title, channel);
|
|
74
|
+
if (title === latest.data.title) return;
|
|
75
|
+
// There is no await between the latest-title read and this append. A
|
|
76
|
+
// queued old result can therefore never replace a newer/manual title.
|
|
77
|
+
session.append('session/title', {
|
|
78
|
+
...structuredClone(latest.data),
|
|
79
|
+
title,
|
|
80
|
+
});
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
const enqueue = (session) => {
|
|
84
|
+
if (closed || pending.has(session)) return;
|
|
85
|
+
// Leave the current append/notification stack before writing another
|
|
86
|
+
// event, so persistence and client projections observe monotonically
|
|
87
|
+
// ordered events. Read the newest title when the microtask runs.
|
|
88
|
+
const task = Promise.resolve().then(() => {
|
|
89
|
+
pending.delete(session);
|
|
90
|
+
decorate(session);
|
|
91
|
+
}).catch((error) => {
|
|
92
|
+
logger.warn?.('[dsh-im] unable to add Session channel prefix:', error?.message ?? error);
|
|
93
|
+
}).finally(() => {
|
|
94
|
+
if (pending.get(session) === task) pending.delete(session);
|
|
95
|
+
});
|
|
96
|
+
pending.set(session, task);
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
const disposeEvent = ctx.on('session/event', (session, event) => {
|
|
100
|
+
if (event?.type === 'session/title'
|
|
101
|
+
|| (event?.type === 'user/message' && IM_RPC_ID.test(event.data?.source?.rpcId))) {
|
|
102
|
+
enqueue(session);
|
|
103
|
+
}
|
|
104
|
+
}, { global: true });
|
|
105
|
+
const disposeCreated = ctx.on('session/created', enqueue, { global: true });
|
|
106
|
+
const close = () => {
|
|
107
|
+
if (closed) return;
|
|
108
|
+
closed = true;
|
|
109
|
+
disposeEvent?.();
|
|
110
|
+
disposeCreated?.();
|
|
111
|
+
};
|
|
112
|
+
if (typeof ctx.effect === 'function') {
|
|
113
|
+
ctx.effect(() => close, 'dsh-im: Session title channel prefixes');
|
|
114
|
+
}
|
|
115
|
+
for (const session of ctx.sessions.list()) enqueue(session);
|
|
116
|
+
return Object.freeze({
|
|
117
|
+
close,
|
|
118
|
+
async whenIdle() {
|
|
119
|
+
while (pending.size) await Promise.allSettled([...pending.values()]);
|
|
120
|
+
},
|
|
121
|
+
});
|
|
122
|
+
}
|