@yuriai/web 0.2.27-beta.6 → 0.2.27
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.md +8 -0
- package/dist/assets/{AgentAvatar-Bi1vvWPC.js → AgentAvatar-DNm_jMna.js} +1 -1
- package/dist/assets/AssistantContactStatus-BPRpgMFh.js +3 -0
- package/dist/assets/{AssistantUnreadBadge-DdJyySwn.js → AssistantUnreadBadge-BssH-RvV.js} +1 -1
- package/dist/assets/AssistantView-CxQv-9Ms.js +1 -0
- package/dist/assets/{DiagramView-CI4bTtxy.js → DiagramView-DPpG0fwx.js} +1 -1
- package/dist/assets/{FadeInOnReveal-BB4qEnAn.js → FadeInOnReveal-S6UbimjB.js} +1 -1
- package/dist/assets/{GuiPluginSurface-CguxFUbM.js → GuiPluginSurface-BOf0JA1T.js} +1 -1
- package/dist/assets/{GuiPluginWindow-DOJ7wuRH.js → GuiPluginWindow-OrYkfQ4m.js} +1 -1
- package/dist/assets/{Icon-t2xvbAyN.js → Icon-BE4mEwzV.js} +1 -1
- package/dist/assets/{ImageLoadingPlaceholder-D1L13TK0.js → ImageLoadingPlaceholder-CBFJC_KD.js} +1 -1
- package/dist/assets/{LoadingImage-5rY_edNm.js → LoadingImage-NLq7_P-i.js} +1 -1
- package/dist/assets/MarkdownRenderer-BaMotAOQ.js +2 -0
- package/dist/assets/{MarkdownRendererImpl-cE-0AYRg.js → MarkdownRendererImpl-Cv6UnGG7.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-BZyqDl82.js → MarkstreamRendererImpl-Rb9O6wkW.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-tbfsMfB-.js → MobileDetailNavigation-CK4KbkeS.js} +1 -1
- package/dist/assets/{MobileResizableSheet-BeRmT6_x.js → MobileResizableSheet-Deidw1br.js} +1 -1
- package/dist/assets/{MobileShareBridge-C3Equ3P_.js → MobileShareBridge-CO_OWEfq.js} +2 -2
- package/dist/assets/MobileTabPageHeader-DbC8L6A4.js +2 -0
- package/dist/assets/{MultiRunWindow-CAM2XPII.js → MultiRunWindow-DtVW9NTV.js} +1 -1
- package/dist/assets/{OnboardingScreen-4ftRerP5.js → OnboardingScreen-C8ld4wO7.js} +1 -1
- package/dist/assets/{OverlayScrollbar-CF0PCvQz.js → OverlayScrollbar-B3auC2WH.js} +1 -1
- package/dist/assets/{SettingsView-2tk4WH7R.js → SettingsView-Cm7woZWl.js} +15 -15
- package/dist/assets/{SettingsWindow-B9zbeJaW.js → SettingsWindow-CdL4PFxW.js} +1 -1
- package/dist/assets/{TerminalView-DfxvTHye.js → TerminalView-CwRB6Yyr.js} +1 -1
- package/dist/assets/{ToolOutputDialog-CrjDIhru.js → ToolOutputDialog-B4BfmoVH.js} +1 -1
- package/dist/assets/{YuriLogo-QvS1ZEHi.js → YuriLogo-BOx0s0Ue.js} +1 -1
- package/dist/assets/{appThemeRegistry-Bb_DtiV9.js → appThemeRegistry-B6woJIX5.js} +1 -1
- package/dist/assets/{assistant-attachment-cache-B9iHLlm2.js → assistant-attachment-cache-B_qRvy-k.js} +1 -1
- package/dist/assets/{button-DinGM3tu.js → button-BXxwtxsG.js} +1 -1
- package/dist/assets/{capgoAdapter-DufzjXRs.js → capgoAdapter-C5HFS-rx.js} +1 -1
- package/dist/assets/{collapsible-Bh1GLNYV.js → collapsible-BEm0787p.js} +1 -1
- package/dist/assets/context-menu-DUwvVUDY.js +1 -0
- package/dist/assets/{desktopRelayRestore-CoLLVJw8.js → desktopRelayRestore-D1UX7HW2.js} +1 -1
- package/dist/assets/device-BcRP6Tjd.js +2 -0
- package/dist/assets/{diagram-BmG-7Jb4.js → diagram-DyY8dxjZ.js} +1 -1
- package/dist/assets/{dialog-BXssfGXA.js → dialog-CLca6ojn.js} +1 -1
- package/dist/assets/dropdown-menu.styles-DGaALKP0.js +1 -0
- package/dist/assets/{es-HP_Ise0X.js → es-CrsHvgue.js} +2 -2
- package/dist/assets/feishu-Ct1ZxlzQ.svg +6 -0
- package/dist/assets/fileMentionAutocompleteState-BZJqfgae.js +2 -0
- package/dist/assets/{fileMentionTouchSelection-DSl0tj2r.js → fileMentionTouchSelection-C4dvP8GY.js} +2 -2
- package/dist/assets/{fileQueries-5a1jkme2.js → fileQueries-BeXkd3o6.js} +1 -1
- package/dist/assets/{fileReferenceActions-CGpBSFq4.js → fileReferenceActions-CrIAce3K.js} +1 -1
- package/dist/assets/{fr-D0kJXJ6U.js → fr-CEgiRlfa.js} +2 -2
- package/dist/assets/{gitApi-Wo0IZow9.js → gitApi-D2G9ny2O.js} +1 -1
- package/dist/assets/{gitApiHttp-De9liKnG.js → gitApiHttp-B7vYwgBh.js} +4 -4
- package/dist/assets/{gui-9enrif_1.js → gui-CJjEj3l4.js} +1 -1
- package/dist/assets/host-CnVx34Dh.js +1 -0
- package/dist/assets/{image-loading-Dq1g_wpm.js → image-loading-D5UhMj7Z.js} +1 -1
- package/dist/assets/{input-v8-rVbo-.js → input-D59Q2pm8.js} +1 -1
- package/dist/assets/insertionBoundaries-CedfTSM5.js +1 -0
- package/dist/assets/{ja-BjHKXazE.js → ja-CX-_p9jZ.js} +2 -2
- package/dist/assets/{ko-Llwnl876.js → ko-D5xlLYJM.js} +2 -2
- package/dist/assets/main-CxpUooVS.js +2 -0
- package/dist/assets/main-Dpm4KxWX.js +169 -0
- package/dist/assets/{markdownHeightCache-BVV2dktw.js → markdownHeightCache-D2VWb_4E.js} +1 -1
- package/dist/assets/{mcpQueries-BoBrB4a4.js → mcpQueries-DQ3KthDF.js} +1 -1
- package/dist/assets/miniChat-CTdj8Ug9.js +2 -0
- package/dist/assets/mobile-ChbA3Q8j.js +2 -0
- package/dist/assets/{mobileBackNavigation-DMSzAvb6.js → mobileBackNavigation-BJqt3oHk.js} +1 -1
- package/dist/assets/{multirun-BhWttsRQ.js → multirun-BILeETbd.js} +1 -1
- package/dist/assets/{native-DSvNnKAm.js → native-BYMhr-xH.js} +1 -1
- package/dist/assets/{native-config-DjdrW_9n.js → native-config-BIY0Cr-l.js} +1 -1
- package/dist/assets/{persistence-CfrHIiIS.js → persistence-CWuLIq1J.js} +2 -2
- package/dist/assets/{pl-BOd_idqn.js → pl-BjH81A_q.js} +2 -2
- package/dist/assets/projectMeta-B9_Uh8YH.js +1 -0
- package/dist/assets/{pt-BR-B8djxMsl.js → pt-BR-Dp5oK2x3.js} +2 -2
- package/dist/assets/{queryRuntime-Dkpnq3Z1.js → queryRuntime-CTcigFdj.js} +1 -1
- package/dist/assets/queue-abort-optimistic-CS5jTJq-.js +1 -0
- package/dist/assets/react-DRe85o5s.js +1 -0
- package/dist/assets/readiness-BNIgH81X.js +1 -0
- package/dist/assets/renderElectronMiniChatApp-asOqV7FB.js +2 -0
- package/dist/assets/renderMobileApp-DAfque7-.js +28 -0
- package/dist/assets/runtime-fetch-D0YWp3FJ.js +1 -0
- package/dist/assets/{runtime-file-download-CcNIVp7u.js → runtime-file-download-Cf1WxfeW.js} +1 -1
- package/dist/assets/{runtime-file-resource-6np6lzoV.js → runtime-file-resource-UJjHUF2C.js} +1 -1
- package/dist/assets/runtimeConfig-BX8JirIc.js +2 -0
- package/dist/assets/runtimeEndpointReset-CFQgUiUr.js +149 -0
- package/dist/assets/scheduledTaskNavigation-EomDNVu2.js +1 -0
- package/dist/assets/sessionLookup-BxAaxPOw.js +1 -0
- package/dist/assets/{sortable-tabs-strip-yKyqsqut.js → sortable-tabs-strip-DpbW5MqX.js} +1 -1
- package/dist/assets/speechSettingsQueries-CC0fusUo.js +4 -0
- package/dist/assets/src-BMKjN2ip.css +2 -0
- package/dist/assets/{store-CUBymvAC.js → store-CkIHVrmT.js} +4 -3
- package/dist/assets/{terminalApi-BblSkqch.js → terminalApi-rl9mZAlB.js} +1 -1
- package/dist/assets/{textarea-B39OCNPV.js → textarea-7eTptEtD.js} +1 -1
- package/dist/assets/{tooltip-d8TNN4lx.js → tooltip-BPwoSTzO.js} +1 -1
- package/dist/assets/types-CUtSV1V8.js +2 -0
- package/dist/assets/{uk-BNd7CjVO.js → uk-BEfkaLtM.js} +2 -2
- package/dist/assets/{useAppFontEffects-BVoVpJYO.js → useAppFontEffects-Ck2PdQRx.js} +52 -52
- package/dist/assets/{useAssistantUIStore-Bp6TxG5E.js → useAssistantUIStore-CfaQV3ID.js} +1 -1
- package/dist/assets/useDesktopWindowControlsLayout-DxxOUZj1.js +1 -0
- package/dist/assets/useEffectiveDirectory-CNCQfN_x.js +1 -0
- package/dist/assets/{useFontPreferences-BFyBjtQ6.js → useFontPreferences-DeqW9nRx.js} +1 -1
- package/dist/assets/useMobileNavigationStore-BmVr5a5c.js +17 -0
- package/dist/assets/useUIStore-C6CE42oh.js +1 -0
- package/dist/assets/{useWorkerHighlightedLines-CPxG8Fya.js → useWorkerHighlightedLines-CN_RGaSw.js} +1 -1
- package/dist/assets/{vendor-effect-DV9F8PTZ.js → vendor-effect-X1Hqc7ba.js} +13 -13
- package/dist/assets/vendor-opencode-client-cQ47ywrT.js +23 -0
- package/dist/assets/{vendor-opencode-plugin-CgKz9Hcy.js → vendor-opencode-plugin-BmdTE4Te.js} +1 -1
- package/dist/assets/vendor-opencode-schema-DWT45VBX.js +1 -0
- package/dist/assets/vendor-solid-js-D98iXT7C.js +1 -0
- package/dist/assets/vendor-zod-DZzbCm1s.js +55 -0
- package/dist/assets/{zh-CN-BkTAEOZG.js → zh-CN-DipfA56P.js} +2 -2
- package/dist/assets/{zh-TW-x8SfMzfc.js → zh-TW-B7pXMVjt.js} +2 -2
- package/dist/index.html +18 -18
- package/dist/mini-chat.html +18 -18
- package/dist/mobile.html +18 -18
- package/package.json +6 -1
- package/server/index.js +2 -145
- package/server/lib/assistants/DOCUMENTATION.md +69 -11
- package/server/lib/assistants/cards.js +1 -1
- package/server/lib/assistants/channel-image.js +92 -0
- package/server/lib/assistants/channel-image.test.js +76 -0
- package/server/lib/assistants/channel-output-store.test.js +41 -0
- package/server/lib/assistants/channel-output.integration.test.js +114 -0
- package/server/lib/assistants/channel-output.js +90 -0
- package/server/lib/assistants/channel-output.test.js +79 -0
- package/server/lib/assistants/channels/DOCUMENTATION.md +329 -0
- package/server/lib/assistants/channels/PROTOCOLS.md +250 -0
- package/server/lib/assistants/channels/dingtalk-chat-adapter.js +645 -0
- package/server/lib/assistants/channels/dingtalk-chat-adapter.test.js +423 -0
- package/server/lib/assistants/channels/integration.test.js +44 -0
- package/server/lib/assistants/channels/routes.js +59 -0
- package/server/lib/assistants/channels/routes.test.js +139 -0
- package/server/lib/assistants/channels/runtime.js +958 -0
- package/server/lib/assistants/channels/runtime.test.js +897 -0
- package/server/lib/assistants/channels/sdk-adapters.js +383 -0
- package/server/lib/assistants/channels/sdk-adapters.test.js +384 -0
- package/server/lib/assistants/channels/store.js +249 -0
- package/server/lib/assistants/channels/store.test.js +296 -0
- package/server/lib/assistants/channels/transport.js +42 -0
- package/server/lib/assistants/channels/transport.test.js +23 -0
- package/server/lib/assistants/channels/wecom-chat-adapter.js +703 -0
- package/server/lib/assistants/channels/wecom-chat-adapter.test.js +130 -0
- package/server/lib/assistants/contact-store.js +9 -3
- package/server/lib/assistants/contact-store.test.js +27 -0
- package/server/lib/assistants/contact-tools.js +65 -75
- package/server/lib/assistants/contact-tools.test.js +114 -22
- package/server/lib/assistants/harness.js +79 -34
- package/server/lib/assistants/harness.test.js +52 -20
- package/server/lib/assistants/message-channel-origin.js +7 -0
- package/server/lib/assistants/resource-reference.integration.test.js +284 -0
- package/server/lib/assistants/routes.js +14 -4
- package/server/lib/assistants/service.js +116 -69
- package/server/lib/assistants/service.test.js +31 -17
- package/server/lib/assistants/weixin/DOCUMENTATION.md +121 -14
- package/server/lib/assistants/weixin/api.js +45 -1
- package/server/lib/assistants/weixin/api.test.js +28 -0
- package/server/lib/assistants/weixin/chat-adapter.js +113 -0
- package/server/lib/assistants/weixin/chat-adapter.test.js +62 -0
- package/server/lib/assistants/weixin/inbound.js +149 -0
- package/server/lib/assistants/weixin/inbound.test.js +141 -0
- package/server/lib/assistants/weixin/media.js +79 -0
- package/server/lib/assistants/weixin/media.test.js +66 -0
- package/server/lib/assistants/weixin/runtime.js +105 -74
- package/server/lib/assistants/weixin/runtime.test.js +192 -4
- package/server/lib/assistants/weixin/store.js +16 -8
- package/server/lib/assistants/weixin/store.test.js +93 -0
- package/server/lib/assistants/weixin/toon.js +49 -0
- package/server/lib/assistants/weixin/toon.test.js +25 -0
- package/server/lib/assistants/yuri-project.http.test.js +9 -3
- package/server/lib/github/DOCUMENTATION.md +9 -8
- package/server/lib/llm/bridge-plugin.bundle.js +188 -188
- package/server/lib/notifications/DOCUMENTATION.md +6 -0
- package/server/lib/notifications/runtime.js +26 -15
- package/server/lib/notifications/runtime.test.js +14 -13
- package/server/lib/opencode/DOCUMENTATION.md +10 -1
- package/server/lib/opencode/auth.d.ts +6 -2
- package/server/lib/opencode/core-routes.js +0 -1
- package/server/lib/opencode/feature-routes-runtime.js +0 -24
- package/server/lib/opencode/location-release.d.ts +5 -1
- package/server/lib/opencode/managed-capabilities/scheduled-task.js +1 -1
- package/server/lib/opencode/managed-capabilities-runtime.test.js +1 -1
- package/server/lib/opencode/native-goal.js +15 -0
- package/server/lib/opencode/native-goal.test.js +17 -0
- package/server/lib/opencode/settings-helpers.js +0 -6
- package/server/lib/opencode/shutdown-runtime.js +0 -2
- package/server/lib/projects/project-config.js +3 -6
- package/server/lib/scheduled-tasks/DOCUMENTATION.md +10 -35
- package/server/lib/scheduled-tasks/managed-tool-route.js +1 -30
- package/server/lib/scheduled-tasks/routes.js +0 -26
- package/server/lib/scheduled-tasks/runtime.js +33 -257
- package/server/lib/scheduled-tasks/runtime.test.js +24 -65
- package/server/lib/session-metadata/DOCUMENTATION.md +9 -12
- package/server/lib/session-metadata/routes.js +4 -38
- package/server/lib/session-metadata/routes.test.js +2 -2
- package/dist/assets/AssistantContactStatus-CWq-PDz6.js +0 -3
- package/dist/assets/AssistantView-Br1iETTs.js +0 -1
- package/dist/assets/MarkdownRenderer-BlGxjOei.js +0 -2
- package/dist/assets/MobileTabPageHeader-DQRqAAEf.js +0 -2
- package/dist/assets/context-menu-DpbkRkk1.js +0 -1
- package/dist/assets/device-BjRYYXNT.js +0 -2
- package/dist/assets/host-FR_grJxM.js +0 -1
- package/dist/assets/insertionBoundaries-CZz7TWJv.js +0 -1
- package/dist/assets/main-Bp9HHqTr.js +0 -2
- package/dist/assets/main-DOwAfmxJ.js +0 -169
- package/dist/assets/miniChat-BJDgCrfF.js +0 -2
- package/dist/assets/mobile-GM9931J_.js +0 -2
- package/dist/assets/projectMeta-31PobC-M.js +0 -1
- package/dist/assets/react-B9v0P7kT.js +0 -1
- package/dist/assets/readiness-CYNnsekT.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-N2r999Bf.js +0 -2
- package/dist/assets/renderMobileApp-CU1ec6Ak.js +0 -28
- package/dist/assets/runtime-fetch-D4ja813o.js +0 -1
- package/dist/assets/runtimeConfig-Db7yfo6L.js +0 -2
- package/dist/assets/runtimeEndpointReset-DO5WVetV.js +0 -149
- package/dist/assets/scheduledTaskNavigation-Bsrhv3Ow.js +0 -1
- package/dist/assets/sessionLookup-DRVy7LM1.js +0 -1
- package/dist/assets/speechSettingsQueries-DU25rmGc.js +0 -4
- package/dist/assets/src-Bckdo2XS.css +0 -2
- package/dist/assets/types-BqFQhQTt.js +0 -2
- package/dist/assets/useDesktopWindowControlsLayout-CYx1LNO5.js +0 -1
- package/dist/assets/useEffectiveDirectory-D8FFE5Yn.js +0 -1
- package/dist/assets/useMobileNavigationStore-BHMFeMjo.js +0 -23
- package/dist/assets/useUIStore-BbYD420L.js +0 -1
- package/dist/assets/vendor-opencode-client-UL_TecvQ.js +0 -12
- package/dist/assets/vendor-solid-js-0T254UHG.js +0 -1
- package/dist/assets/vendor-zod-Dzk5kdUU.js +0 -39
- package/server/lib/session-goal/DOCUMENTATION.md +0 -371
- package/server/lib/session-goal/capability.js +0 -57
- package/server/lib/session-goal/capability.test.js +0 -33
- package/server/lib/session-goal/objectives.js +0 -61
- package/server/lib/session-goal/routes.js +0 -274
- package/server/lib/session-goal/routes.test.js +0 -211
- package/server/lib/session-goal/runtime.js +0 -2452
- package/server/lib/session-goal/runtime.test.js +0 -2125
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
import { Message, NotImplementedError, parseMarkdown, stringifyMarkdown } from 'chat';
|
|
2
|
+
import { EventEmitter } from 'node:events';
|
|
3
|
+
import { DWClient } from 'dingtalk-stream';
|
|
4
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
5
|
+
import { createDingtalkSdkAdapter, DingTalkChatAdapter } from './dingtalk-chat-adapter.js';
|
|
6
|
+
|
|
7
|
+
const TOPIC = '/v1.0/im/bot/messages/get';
|
|
8
|
+
|
|
9
|
+
class FakeDingTalkClient extends EventEmitter {
|
|
10
|
+
constructor({ register = true, hangConnect = false } = {}) {
|
|
11
|
+
super();
|
|
12
|
+
this.connected = false;
|
|
13
|
+
this.registered = false;
|
|
14
|
+
this.registerOnConnect = register;
|
|
15
|
+
this.hangConnect = hangConnect;
|
|
16
|
+
this.acks = [];
|
|
17
|
+
this.disconnects = 0;
|
|
18
|
+
this.connectCalls = 0;
|
|
19
|
+
this.topics = new Map();
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
registerCallbackListener(topic, callback) {
|
|
23
|
+
this.topics.set(topic, callback);
|
|
24
|
+
return this;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async connect() {
|
|
28
|
+
this.connectCalls += 1;
|
|
29
|
+
if (this.hangConnect) return new Promise(() => {});
|
|
30
|
+
this.connected = true;
|
|
31
|
+
if (this.registerOnConnect) {
|
|
32
|
+
this.registered = true;
|
|
33
|
+
this.onSystem({ headers: { topic: 'REGISTERED' } });
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// Matches the SDK: instance-level wiring overrides this prototype method.
|
|
38
|
+
onSystem() {}
|
|
39
|
+
|
|
40
|
+
disconnect() {
|
|
41
|
+
this.disconnects += 1;
|
|
42
|
+
this.connected = false;
|
|
43
|
+
this.registered = false;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
socketCallBackResponse(messageId, payload) {
|
|
47
|
+
this.acks.push({ messageId, payload });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
deliver(frame) {
|
|
51
|
+
return this.topics.get(TOPIC)(frame);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function frame(body, messageId = 'm1') {
|
|
56
|
+
return { headers: { messageId, topic: TOPIC }, data: JSON.stringify(body) };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function textBody(overrides = {}) {
|
|
60
|
+
return {
|
|
61
|
+
conversationType: '1',
|
|
62
|
+
msgId: 'm1',
|
|
63
|
+
msgtype: 'text',
|
|
64
|
+
text: { content: '你好' },
|
|
65
|
+
senderStaffId: 'owner_1',
|
|
66
|
+
senderId: 'sender_1',
|
|
67
|
+
senderNick: 'Owner',
|
|
68
|
+
chatbotUserId: 'bot_1',
|
|
69
|
+
sessionWebhook: 'https://oapi.dingtalk.com/robot/sendBySession?session=secret',
|
|
70
|
+
...overrides,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function harness(options = {}) {
|
|
75
|
+
const clients = [];
|
|
76
|
+
const clientFactory = () => {
|
|
77
|
+
const client = new FakeDingTalkClient(options);
|
|
78
|
+
clients.push(client);
|
|
79
|
+
return client;
|
|
80
|
+
};
|
|
81
|
+
return { clients, clientFactory };
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function bridgeFor(value, extra = {}) {
|
|
85
|
+
return createDingtalkSdkAdapter({ clientFactory: value.clientFactory, ...extra });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
const config = { clientID: 'ding_client', clientSecret: 'ding_secret', ownerID: 'owner_1' };
|
|
89
|
+
|
|
90
|
+
afterEach(() => {
|
|
91
|
+
vi.useRealTimers();
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
describe('dingtalk Chat SDK adapter', () => {
|
|
95
|
+
it('uploads local image bytes and sends sampleImageMsg only to the original private user', async () => {
|
|
96
|
+
const fetchImpl = vi.fn(async (url) => Response.json(String(url).includes('accessToken') ? { accessToken: 'token', expireIn: 7200 }
|
|
97
|
+
: String(url).includes('/media/upload') ? { errcode: 0, media_id: '@uploaded' } : {}));
|
|
98
|
+
const bridge = createDingtalkSdkAdapter({ fetchImpl });
|
|
99
|
+
await bridge.send({ config, image: { buffer: Buffer.from('image'), mime: 'image/png', filename: 'image.png' } });
|
|
100
|
+
expect(fetchImpl.mock.calls[1][1].body).toBeInstanceOf(FormData);
|
|
101
|
+
expect(JSON.parse(fetchImpl.mock.calls[2][1].body)).toEqual({ robotCode: config.clientID, userIds: [config.ownerID], msgKey: 'sampleImageMsg', msgParam: JSON.stringify({ photoURL: '@uploaded' }) });
|
|
102
|
+
});
|
|
103
|
+
it('accepts platform-scoped private senders without a binding and replies to the persisted user', async () => {
|
|
104
|
+
const h = harness();
|
|
105
|
+
const controller = new AbortController();
|
|
106
|
+
const onReady = vi.fn();
|
|
107
|
+
const onMessage = vi.fn();
|
|
108
|
+
const fetchImpl = vi.fn(async (url) => new Response(JSON.stringify(String(url).includes('accessToken')
|
|
109
|
+
? { accessToken: 'token', expireIn: 7200 } : {}), { status: 200 }));
|
|
110
|
+
const bridge = bridgeFor(h, { fetchImpl });
|
|
111
|
+
const unbound = { ...config, ownerID: '' };
|
|
112
|
+
const running = bridge.connect({ config: unbound, signal: controller.signal, onReady, onMessage });
|
|
113
|
+
try {
|
|
114
|
+
await vi.waitFor(() => expect(onReady).toHaveBeenCalledOnce());
|
|
115
|
+
await h.clients[0].deliver(frame(textBody({ senderStaffId: 'alice' })));
|
|
116
|
+
await h.clients[0].deliver(frame(textBody({ senderStaffId: 'bob' })));
|
|
117
|
+
await h.clients[0].deliver(frame(textBody({ senderStaffId: 'bob', conversationType: '2' })));
|
|
118
|
+
expect(onMessage.mock.calls.map(([message]) => message.senderID)).toEqual(['alice', 'bob']);
|
|
119
|
+
await expect(bridge.send({ config: unbound, text: 'no recipient' })).rejects.toMatchObject({ code: 'invalid_response' });
|
|
120
|
+
await bridge.send({ config: unbound, target: { userID: 'alice' }, text: 'hello' });
|
|
121
|
+
expect(JSON.parse(fetchImpl.mock.calls[1][1].body).userIds).toEqual(['alice']);
|
|
122
|
+
} finally { controller.abort(); await running; }
|
|
123
|
+
});
|
|
124
|
+
|
|
125
|
+
it('reports ready only after REGISTERED and keeps the gateway ACK behind durable delivery', async () => {
|
|
126
|
+
const h = harness();
|
|
127
|
+
const controller = new AbortController();
|
|
128
|
+
const onReady = vi.fn();
|
|
129
|
+
const onMessage = vi.fn();
|
|
130
|
+
const running = bridgeFor(h).connect({ config, signal: controller.signal, onReady, onMessage });
|
|
131
|
+
|
|
132
|
+
await vi.waitFor(() => expect(h.clients).toHaveLength(1));
|
|
133
|
+
await vi.waitFor(() => expect(onReady).toHaveBeenCalledOnce());
|
|
134
|
+
expect(h.clients[0].registered).toBe(true);
|
|
135
|
+
|
|
136
|
+
let release;
|
|
137
|
+
onMessage.mockImplementationOnce(() => new Promise((resolve) => { release = resolve; }));
|
|
138
|
+
const delivered = h.clients[0].deliver(frame(textBody()));
|
|
139
|
+
await Promise.resolve();
|
|
140
|
+
expect(h.clients[0].acks).toHaveLength(0);
|
|
141
|
+
release();
|
|
142
|
+
await delivered;
|
|
143
|
+
expect(h.clients[0].acks).toEqual([{ messageId: 'm1', payload: {} }]);
|
|
144
|
+
|
|
145
|
+
controller.abort();
|
|
146
|
+
await running;
|
|
147
|
+
expect(h.clients[0].disconnects).toBe(1);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
it('runs an independent session per config and rejects a duplicate live connect', async () => {
|
|
151
|
+
const h = harness();
|
|
152
|
+
const first = new AbortController();
|
|
153
|
+
const second = new AbortController();
|
|
154
|
+
const onReady = vi.fn();
|
|
155
|
+
const bridge = bridgeFor(h);
|
|
156
|
+
const running1 = bridge.connect({ config, signal: first.signal, onReady, onMessage: vi.fn() });
|
|
157
|
+
await vi.waitFor(() => expect(onReady).toHaveBeenCalledTimes(1));
|
|
158
|
+
|
|
159
|
+
const otherConfig = { clientID: 'ding_client_b', clientSecret: 'ding_secret_b', ownerID: 'owner_2' };
|
|
160
|
+
const running2 = bridge.connect({ config: otherConfig, signal: second.signal, onReady, onMessage: vi.fn() });
|
|
161
|
+
await vi.waitFor(() => expect(onReady).toHaveBeenCalledTimes(2));
|
|
162
|
+
// One long connection per config, not a single shared adapter instance.
|
|
163
|
+
expect(h.clients).toHaveLength(2);
|
|
164
|
+
expect(h.clients[0]).not.toBe(h.clients[1]);
|
|
165
|
+
|
|
166
|
+
await expect(bridge.connect({ config, signal: new AbortController().signal, onMessage: vi.fn() }))
|
|
167
|
+
.rejects.toMatchObject({ code: 'channel_in_use' });
|
|
168
|
+
|
|
169
|
+
first.abort();
|
|
170
|
+
second.abort();
|
|
171
|
+
await Promise.all([running1, running2]);
|
|
172
|
+
expect(h.clients.every((client) => client.disconnects === 1)).toBe(true);
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
it('does not claim ready when the gateway never registers', async () => {
|
|
176
|
+
vi.useFakeTimers();
|
|
177
|
+
const h = harness({ register: false });
|
|
178
|
+
const controller = new AbortController();
|
|
179
|
+
const onReady = vi.fn();
|
|
180
|
+
const running = bridgeFor(h).connect({ config, signal: controller.signal, onReady, onMessage: vi.fn() });
|
|
181
|
+
const rejection = expect(running).rejects.toMatchObject({ code: 'network_error' });
|
|
182
|
+
await vi.advanceTimersByTimeAsync(21_000);
|
|
183
|
+
await rejection;
|
|
184
|
+
expect(onReady).not.toHaveBeenCalled();
|
|
185
|
+
expect(h.clients[0].disconnects).toBe(1);
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
it('aborts a connect that never settles and disconnects the SDK client', async () => {
|
|
189
|
+
const h = harness({ hangConnect: true });
|
|
190
|
+
const controller = new AbortController();
|
|
191
|
+
const onReady = vi.fn();
|
|
192
|
+
const running = bridgeFor(h).connect({ config, signal: controller.signal, onReady, onMessage: vi.fn() });
|
|
193
|
+
|
|
194
|
+
await vi.waitFor(() => expect(h.clients).toHaveLength(1));
|
|
195
|
+
expect(h.clients[0].connectCalls).toBe(1);
|
|
196
|
+
controller.abort();
|
|
197
|
+
await expect(running).rejects.toMatchObject({ code: 'cancelled' });
|
|
198
|
+
expect(onReady).not.toHaveBeenCalled();
|
|
199
|
+
expect(h.clients[0].disconnects).toBe(1);
|
|
200
|
+
});
|
|
201
|
+
|
|
202
|
+
it('acknowledges only authorized single-chat owner messages', async () => {
|
|
203
|
+
const h = harness();
|
|
204
|
+
const controller = new AbortController();
|
|
205
|
+
const onMessage = vi.fn();
|
|
206
|
+
const running = bridgeFor(h).connect({ config, signal: controller.signal, onMessage });
|
|
207
|
+
await vi.waitFor(() => expect(h.clients).toHaveLength(1));
|
|
208
|
+
await vi.waitFor(() => expect(h.clients[0].registered).toBe(true));
|
|
209
|
+
|
|
210
|
+
const client = h.clients[0];
|
|
211
|
+
await client.deliver(frame(textBody({ conversationType: '2', conversationId: 'group_1' }), 'm2'));
|
|
212
|
+
await client.deliver(frame(textBody({ senderStaffId: 'owner_2' }), 'm3'));
|
|
213
|
+
await client.deliver(frame(textBody({ senderStaffId: undefined, senderId: 'bot_1' }), 'm4'));
|
|
214
|
+
expect(onMessage).not.toHaveBeenCalled();
|
|
215
|
+
expect(client.acks.map((ack) => ack.messageId)).toEqual(['m2', 'm3', 'm4']);
|
|
216
|
+
|
|
217
|
+
await client.deliver(frame(textBody({ msgId: 'm5', msgtype: 'picture', text: undefined }), 'm5'));
|
|
218
|
+
expect(onMessage).toHaveBeenCalledOnce();
|
|
219
|
+
const [message] = onMessage.mock.calls[0];
|
|
220
|
+
expect(message).toMatchObject({ id: 'm5', senderID: 'owner_1', chatType: 'private', text: '', metadata: { platform: 'dingtalk', notDownloaded: true, mediaType: 'picture' } });
|
|
221
|
+
expect(JSON.stringify(message)).not.toContain('sessionWebhook');
|
|
222
|
+
expect(JSON.stringify(message)).not.toContain('bot_1');
|
|
223
|
+
|
|
224
|
+
controller.abort();
|
|
225
|
+
await running;
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
it('consumes platform speech recognition and rich text without inventing a transcript', async () => {
|
|
229
|
+
const h = harness();
|
|
230
|
+
const controller = new AbortController();
|
|
231
|
+
const onMessage = vi.fn();
|
|
232
|
+
const running = bridgeFor(h).connect({ config, signal: controller.signal, onMessage });
|
|
233
|
+
await vi.waitFor(() => expect(h.clients[0]?.registered).toBe(true));
|
|
234
|
+
|
|
235
|
+
await h.clients[0].deliver(frame(textBody({
|
|
236
|
+
msgId: 'a1',
|
|
237
|
+
msgtype: 'audio',
|
|
238
|
+
text: undefined,
|
|
239
|
+
content: { recognition: '明天上午开会', downloadCode: 'dc_secret' },
|
|
240
|
+
}), 'a1'));
|
|
241
|
+
expect(onMessage.mock.calls[0][0]).toMatchObject({
|
|
242
|
+
id: 'a1', text: '明天上午开会', metadata: { transcript: 'platform' },
|
|
243
|
+
});
|
|
244
|
+
expect(JSON.stringify(onMessage.mock.calls[0][0])).not.toContain('dc_secret');
|
|
245
|
+
|
|
246
|
+
await h.clients[0].deliver(frame(textBody({
|
|
247
|
+
msgId: 'a2',
|
|
248
|
+
msgtype: 'audio',
|
|
249
|
+
text: undefined,
|
|
250
|
+
content: { downloadCode: 'dc_secret' },
|
|
251
|
+
}), 'a2'));
|
|
252
|
+
expect(onMessage.mock.calls[1][0]).toMatchObject({
|
|
253
|
+
id: 'a2', text: '', metadata: { notDownloaded: true, mediaType: 'audio' },
|
|
254
|
+
});
|
|
255
|
+
expect(onMessage.mock.calls[1][0].metadata).not.toHaveProperty('transcript');
|
|
256
|
+
|
|
257
|
+
await h.clients[0].deliver(frame(textBody({
|
|
258
|
+
msgId: 'r1',
|
|
259
|
+
msgtype: 'richText',
|
|
260
|
+
text: undefined,
|
|
261
|
+
content: { richText: [{ text: '第一行' }, { type: 'picture', downloadCode: 'x' }, { text: '第二行' }] },
|
|
262
|
+
}), 'r1'));
|
|
263
|
+
expect(onMessage.mock.calls[2][0]).toMatchObject({
|
|
264
|
+
id: 'r1', text: '第一行\n第二行', metadata: { format: 'richText' },
|
|
265
|
+
});
|
|
266
|
+
|
|
267
|
+
controller.abort();
|
|
268
|
+
await running;
|
|
269
|
+
});
|
|
270
|
+
|
|
271
|
+
it('leaves failed deliveries unacknowledged so the platform can retry', async () => {
|
|
272
|
+
const h = harness();
|
|
273
|
+
const controller = new AbortController();
|
|
274
|
+
const onError = vi.fn();
|
|
275
|
+
const onMessage = vi.fn(async () => { throw new Error('sqlite busy'); });
|
|
276
|
+
const running = bridgeFor(h).connect({ config, signal: controller.signal, onMessage, onError });
|
|
277
|
+
await vi.waitFor(() => expect(h.clients[0]?.registered).toBe(true));
|
|
278
|
+
await h.clients[0].deliver(frame(textBody()));
|
|
279
|
+
expect(h.clients[0].acks).toHaveLength(0);
|
|
280
|
+
expect(onError).toHaveBeenCalledWith(expect.objectContaining({ code: 'network_error' }));
|
|
281
|
+
controller.abort();
|
|
282
|
+
await running;
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
it('keeps the standalone initialize deliver path owner-and-single-chat scoped', async () => {
|
|
286
|
+
const h = harness();
|
|
287
|
+
const adapter = new DingTalkChatAdapter({
|
|
288
|
+
clientId: 'ding_client',
|
|
289
|
+
clientSecret: 'ding_secret',
|
|
290
|
+
ownerId: 'owner_1',
|
|
291
|
+
clientFactory: h.clientFactory,
|
|
292
|
+
});
|
|
293
|
+
const processed = [];
|
|
294
|
+
await adapter.initialize({
|
|
295
|
+
processMessage: (_adapter, threadId, factory) => { processed.push({ threadId, factory }); },
|
|
296
|
+
});
|
|
297
|
+
const client = h.clients[0];
|
|
298
|
+
|
|
299
|
+
await client.deliver(frame(textBody({ msgId: 'g1', conversationType: '2', conversationId: 'group_1' }), 'g1'));
|
|
300
|
+
await client.deliver(frame(textBody({ msgId: 'u1', senderStaffId: 'owner_2' }), 'u1'));
|
|
301
|
+
expect(processed).toHaveLength(0);
|
|
302
|
+
|
|
303
|
+
await client.deliver(frame(textBody({ msgId: 'u2' }), 'u2'));
|
|
304
|
+
expect(processed).toHaveLength(1);
|
|
305
|
+
expect(processed[0].threadId).toBe('dingtalk:private:owner_1');
|
|
306
|
+
|
|
307
|
+
await adapter.disconnect();
|
|
308
|
+
expect(client.disconnects).toBe(1);
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
it('sends proactive direct messages to the configured owner with a cached token', async () => {
|
|
312
|
+
const calls = [];
|
|
313
|
+
const fetchImpl = vi.fn(async (url, init) => {
|
|
314
|
+
calls.push({ url, body: JSON.parse(init.body), headers: init.headers });
|
|
315
|
+
if (String(url).includes('/oauth2/accessToken')) {
|
|
316
|
+
return new Response(JSON.stringify({ accessToken: 'at_1', expireIn: 7200 }), { status: 200 });
|
|
317
|
+
}
|
|
318
|
+
return new Response(JSON.stringify({ processQueryKey: 'q1' }), { status: 200 });
|
|
319
|
+
});
|
|
320
|
+
const bridge = createDingtalkSdkAdapter({ clientFactory: harness().clientFactory, fetchImpl });
|
|
321
|
+
// A stray `target` must never redirect DingTalk outbound traffic.
|
|
322
|
+
await bridge.send({ config, target: 'someone_else', text: 'hello', id: 'r1' });
|
|
323
|
+
await bridge.send({ config, target: 'someone_else', text: 'again', id: 'r2' });
|
|
324
|
+
expect(calls.map((call) => new URL(call.url).pathname)).toEqual([
|
|
325
|
+
'/v1.0/oauth2/accessToken',
|
|
326
|
+
'/v1.0/robot/oToMessages/batchSend',
|
|
327
|
+
'/v1.0/robot/oToMessages/batchSend',
|
|
328
|
+
]);
|
|
329
|
+
expect(calls[0].body).toEqual({ appKey: 'ding_client', appSecret: 'ding_secret' });
|
|
330
|
+
expect(calls[1].body).toEqual({ robotCode: 'ding_client', userIds: ['owner_1'], msgKey: 'sampleText', msgParam: JSON.stringify({ content: 'hello' }) });
|
|
331
|
+
expect(calls[1].headers['x-acs-dingtalk-access-token']).toBe('at_1');
|
|
332
|
+
expect(fetchImpl.mock.calls[1][1]).toMatchObject({ method: 'POST', redirect: 'error' });
|
|
333
|
+
});
|
|
334
|
+
|
|
335
|
+
it('keeps send ambiguity and recipient throttling distinct', async () => {
|
|
336
|
+
const base = { clientID: 'ding_client_2', clientSecret: 'ding_secret_2', ownerID: 'owner_1' };
|
|
337
|
+
const bridge = createDingtalkSdkAdapter({
|
|
338
|
+
fetchImpl: async (url) => (String(url).includes('/oauth2/accessToken')
|
|
339
|
+
? new Response(JSON.stringify({ accessToken: 'at_2', expireIn: 7200 }), { status: 200 })
|
|
340
|
+
: new Response('', { status: 502 })),
|
|
341
|
+
});
|
|
342
|
+
await expect(bridge.send({ config: base, text: 'hi', id: 'r1' }))
|
|
343
|
+
.rejects.toMatchObject({ code: 'network_error', ambiguous: true });
|
|
344
|
+
|
|
345
|
+
for (const field of ['invalidStaffIdList', 'flowControlledStaffIdList', 'filteredStaffIdList']) {
|
|
346
|
+
const rejected = createDingtalkSdkAdapter({
|
|
347
|
+
fetchImpl: async (url) => (String(url).includes('/oauth2/accessToken')
|
|
348
|
+
? new Response(JSON.stringify({ accessToken: 'at_3', expireIn: 7200 }), { status: 200 })
|
|
349
|
+
: new Response(JSON.stringify({ [field]: ['owner_1'] }), { status: 200 })),
|
|
350
|
+
});
|
|
351
|
+
await expect(rejected.send({
|
|
352
|
+
config: { ...base, clientID: `ding_${field}`, clientSecret: `ding_${field}` },
|
|
353
|
+
text: 'hi',
|
|
354
|
+
id: 'r2',
|
|
355
|
+
})).rejects.toMatchObject({ code: 'network_error', ambiguous: false });
|
|
356
|
+
}
|
|
357
|
+
});
|
|
358
|
+
});
|
|
359
|
+
|
|
360
|
+
describe('dingtalk Chat SDK adapter contract', () => {
|
|
361
|
+
it('relies on the installed dingtalk-stream surface', () => {
|
|
362
|
+
const client = new DWClient({
|
|
363
|
+
clientId: 'ding_client',
|
|
364
|
+
clientSecret: 'ding_secret',
|
|
365
|
+
subscriptions: [{ type: 'CALLBACK', topic: TOPIC }],
|
|
366
|
+
});
|
|
367
|
+
expect(typeof client.connect).toBe('function');
|
|
368
|
+
expect(typeof client._connect).toBe('function');
|
|
369
|
+
expect(typeof client.onSystem).toBe('function');
|
|
370
|
+
expect(typeof client.registerCallbackListener).toBe('function');
|
|
371
|
+
expect(typeof client.socketCallBackResponse).toBe('function');
|
|
372
|
+
expect(typeof client.disconnect).toBe('function');
|
|
373
|
+
expect(client.connected).toBe(false);
|
|
374
|
+
expect(client.registered).toBe(false);
|
|
375
|
+
});
|
|
376
|
+
|
|
377
|
+
it('separates private from group threads and supports standard postables', async () => {
|
|
378
|
+
const adapter = new DingTalkChatAdapter({ clientId: 'ding_client', clientSecret: 'ding_secret', ownerId: 'owner_1' });
|
|
379
|
+
expect(adapter.name).toBe('dingtalk');
|
|
380
|
+
expect(adapter.openDM('owner_1')).toBe('dingtalk:private:owner_1');
|
|
381
|
+
expect(adapter.decodeThreadId('dingtalk:private:owner_1')).toEqual({ chatType: 'private', id: 'owner_1' });
|
|
382
|
+
expect(adapter.channelIdFromThreadId('dingtalk:private:owner_1')).toBe('owner_1');
|
|
383
|
+
expect(adapter.isDM('dingtalk:private:owner_1')).toBe(true);
|
|
384
|
+
expect(adapter.isDM('dingtalk:group:group_1')).toBe(false);
|
|
385
|
+
|
|
386
|
+
const message = adapter.parseMessage({
|
|
387
|
+
msgId: 'm1', conversationType: '1', senderStaffId: 'owner_1', msgtype: 'text', text: { content: 'hi' },
|
|
388
|
+
});
|
|
389
|
+
expect(message).toBeInstanceOf(Message);
|
|
390
|
+
expect(message.threadId).toBe('dingtalk:private:owner_1');
|
|
391
|
+
const group = adapter.parseMessage({
|
|
392
|
+
msgId: 'm2', conversationType: '2', conversationId: 'group_1', senderStaffId: 'owner_1', msgtype: 'text', text: { content: 'hi' },
|
|
393
|
+
});
|
|
394
|
+
expect(group.threadId).toBe('dingtalk:group:group_1');
|
|
395
|
+
expect(group).toBeInstanceOf(Message);
|
|
396
|
+
|
|
397
|
+
expect(adapter.renderFormatted(parseMarkdown('**hi** and *x*'))).toBe('**hi** and *x*\n');
|
|
398
|
+
expect(adapter.renderFormatted('plain')).toBe('plain');
|
|
399
|
+
|
|
400
|
+
await expect(adapter.postMessage('dingtalk:group:group_1', { raw: 'hi' }))
|
|
401
|
+
.rejects.toBeInstanceOf(NotImplementedError);
|
|
402
|
+
await expect(adapter.postMessage('dingtalk:private:someone_else', { raw: 'hi' }))
|
|
403
|
+
.rejects.toMatchObject({ code: 'invalid_response' });
|
|
404
|
+
|
|
405
|
+
await expect(adapter.editMessage()).rejects.toBeInstanceOf(NotImplementedError);
|
|
406
|
+
await expect(adapter.fetchMessages()).rejects.toBeInstanceOf(NotImplementedError);
|
|
407
|
+
await expect(adapter.addReaction()).rejects.toBeInstanceOf(NotImplementedError);
|
|
408
|
+
await expect(adapter.startTyping()).rejects.toBeInstanceOf(NotImplementedError);
|
|
409
|
+
const response = await adapter.handleWebhook();
|
|
410
|
+
expect(response.status).toBe(501);
|
|
411
|
+
expect(await response.text()).not.toContain('secret');
|
|
412
|
+
});
|
|
413
|
+
|
|
414
|
+
it('renders every standard postable shape through the same text projection', () => {
|
|
415
|
+
const adapter = new DingTalkChatAdapter({ clientId: 'ding_client', clientSecret: 'ding_secret', ownerId: 'owner_1' });
|
|
416
|
+
const ast = parseMarkdown('**bold**');
|
|
417
|
+
expect(adapter.renderFormatted(ast)).toBe(stringifyMarkdown(ast));
|
|
418
|
+
expect(adapter.renderFormatted({ raw: 'raw text' })).toBe('raw text');
|
|
419
|
+
expect(adapter.renderFormatted({ markdown: '**md**' })).toBe('**md**');
|
|
420
|
+
expect(adapter.renderFormatted({ ast })).toBe(stringifyMarkdown(ast));
|
|
421
|
+
expect(adapter.renderFormatted({ text: 'not-standard' })).toBe('');
|
|
422
|
+
});
|
|
423
|
+
});
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import fs from 'node:fs/promises';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import express from 'express';
|
|
5
|
+
import request from 'supertest';
|
|
6
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
7
|
+
import { registerAssistantRoutes } from '../routes.js';
|
|
8
|
+
|
|
9
|
+
describe('Host channel route integration', () => {
|
|
10
|
+
it('registers all enterprise channels and drains connections before closing contact storage', async () => {
|
|
11
|
+
const directory = await fs.mkdtemp(path.join(os.tmpdir(), 'yuri-channel-http-'));
|
|
12
|
+
const stops = [];
|
|
13
|
+
const adapters = Object.fromEntries(['wecom', 'feishu', 'dingtalk'].map((provider) => [provider, {
|
|
14
|
+
connect: vi.fn(async ({ signal, onReady }) => {
|
|
15
|
+
onReady();
|
|
16
|
+
await new Promise((resolve) => {
|
|
17
|
+
if (signal.aborted) resolve(); else signal.addEventListener('abort', resolve, { once: true });
|
|
18
|
+
});
|
|
19
|
+
stops.push(provider);
|
|
20
|
+
}), send: vi.fn(),
|
|
21
|
+
}]));
|
|
22
|
+
const app = express();
|
|
23
|
+
app.use(express.json());
|
|
24
|
+
const runtime = registerAssistantRoutes(app, {
|
|
25
|
+
dbPath: path.join(directory, 'assistants.sqlite'), yuriDataDir: directory,
|
|
26
|
+
buildOpenCodeUrl: () => 'http://upstream.invalid', getOpenCodeAuthHeaders: () => ({}),
|
|
27
|
+
assistantChannelAdapters: adapters, channelsEnv: { YURI_CHANNELS_ENABLED: '1' },
|
|
28
|
+
});
|
|
29
|
+
try {
|
|
30
|
+
const bot = runtime.service.createAssistant({ name: 'channel integration', providerID: 'p', modelID: 'm' });
|
|
31
|
+
for (const provider of Object.keys(adapters)) {
|
|
32
|
+
const root = `/api/yuri/assistants/${bot.id}/channels/${provider}`;
|
|
33
|
+
const saved = await request(app).put(root).send({ clientID: `test-${provider}`, clientSecret: 'test-only-secret', ownerID: 'owner' }).expect(200);
|
|
34
|
+
expect(saved.headers['cache-control']).toBe('no-store');
|
|
35
|
+
expect(JSON.stringify(saved.body)).not.toContain('test-only-secret');
|
|
36
|
+
await vi.waitFor(() => expect(adapters[provider].connect).toHaveBeenCalledOnce());
|
|
37
|
+
const status = await request(app).get(root).expect(200);
|
|
38
|
+
expect(status.body).toMatchObject({ provider, configured: true, hasSecret: true });
|
|
39
|
+
}
|
|
40
|
+
await runtime.close();
|
|
41
|
+
expect(stops.sort()).toEqual(['dingtalk', 'feishu', 'wecom']);
|
|
42
|
+
} finally { await runtime.close(); await fs.rm(directory, { recursive: true, force: true }); }
|
|
43
|
+
});
|
|
44
|
+
});
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
const SAFE_ERRORS = new Set([
|
|
2
|
+
'validation_error',
|
|
3
|
+
'not_found',
|
|
4
|
+
'account_in_use',
|
|
5
|
+
'channel_in_use',
|
|
6
|
+
'channel_disabled',
|
|
7
|
+
'unsupported_provider',
|
|
8
|
+
'auth_failed',
|
|
9
|
+
'auth_expired',
|
|
10
|
+
'network_error',
|
|
11
|
+
'upstream_error',
|
|
12
|
+
'invalid_response',
|
|
13
|
+
'rate_limited',
|
|
14
|
+
'delivery_failed',
|
|
15
|
+
'delivery_unknown',
|
|
16
|
+
'backlog_full',
|
|
17
|
+
'cancelled',
|
|
18
|
+
'binding_changed',
|
|
19
|
+
'connection_replaced',
|
|
20
|
+
'owner_required',
|
|
21
|
+
'discovery_timeout',
|
|
22
|
+
]);
|
|
23
|
+
|
|
24
|
+
const failureStatus = (code) => code === 'channel_disabled' ? 403
|
|
25
|
+
: code === 'not_found' ? 404
|
|
26
|
+
: ['account_in_use', 'channel_in_use', 'binding_changed', 'connection_replaced'].includes(code) ? 409
|
|
27
|
+
: ['network_error', 'upstream_error'].includes(code) ? 502
|
|
28
|
+
: 400;
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Runs behind the Host's existing authenticated Yuri route gate. There is no
|
|
32
|
+
* public webhook: every mutation is scoped to one Bot and one provider.
|
|
33
|
+
*/
|
|
34
|
+
export function registerAssistantChannelRoutes(app, runtime) {
|
|
35
|
+
const root = '/api/yuri/assistants/:assistantID/channels/:provider';
|
|
36
|
+
const respond = (res, work) => {
|
|
37
|
+
res.setHeader('Cache-Control', 'no-store');
|
|
38
|
+
Promise.resolve().then(work).then((body) => res.json(body)).catch((error) => {
|
|
39
|
+
// Never return upstream bodies, credentials or routing targets as errors.
|
|
40
|
+
const code = SAFE_ERRORS.has(error?.code) ? error.code : 'channel_error';
|
|
41
|
+
res.status(failureStatus(code)).json({ error: code });
|
|
42
|
+
});
|
|
43
|
+
};
|
|
44
|
+
app.get(root, (req, res) => respond(res, () => runtime.status(req.params.assistantID, req.params.provider)));
|
|
45
|
+
app.put(root, (req, res) => respond(res, () => runtime.save(req.params.assistantID, req.params.provider, req.body)));
|
|
46
|
+
app.post(`${root}/retry`, (req, res) => respond(res, () => runtime.retry(req.params.assistantID, req.params.provider)));
|
|
47
|
+
app.post(`${root}/transfer`, (req, res) => respond(res, () => runtime.transfer(req.params.assistantID, req.params.provider, req.body)));
|
|
48
|
+
app.post(`${root}/discover`, (req, res) => {
|
|
49
|
+
const controller = new AbortController();
|
|
50
|
+
const cancel = () => controller.abort();
|
|
51
|
+
res.once('close', cancel);
|
|
52
|
+
respond(res, async () => {
|
|
53
|
+
try {
|
|
54
|
+
return await runtime.discover(req.params.assistantID, req.params.provider, req.body, { signal: controller.signal });
|
|
55
|
+
} finally { res.off('close', cancel); }
|
|
56
|
+
});
|
|
57
|
+
});
|
|
58
|
+
app.delete(root, (req, res) => respond(res, () => runtime.disconnect(req.params.assistantID, req.params.provider)));
|
|
59
|
+
}
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
import express from 'express';
|
|
2
|
+
import request from 'supertest';
|
|
3
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
4
|
+
import { registerAssistantChannelRoutes } from './routes.js';
|
|
5
|
+
import { createAssistantChannelsRuntime } from './runtime.js';
|
|
6
|
+
|
|
7
|
+
describe('authenticated enterprise channel routes', () => {
|
|
8
|
+
it('reports a disabled channel and blocks every mutation, not only UI controls', async () => {
|
|
9
|
+
const app = express();
|
|
10
|
+
app.use(express.json());
|
|
11
|
+
const runtime = createAssistantChannelsRuntime({ env: { NODE_ENV: 'development' } });
|
|
12
|
+
registerAssistantChannelRoutes(app, runtime);
|
|
13
|
+
const root = '/api/yuri/assistants/bot/channels/wecom';
|
|
14
|
+
const response = await request(app).get(root).expect(200);
|
|
15
|
+
expect(response.headers['cache-control']).toBe('no-store');
|
|
16
|
+
expect(response.body).toEqual({
|
|
17
|
+
provider: 'wecom', status: 'disabled', error: null, configured: false,
|
|
18
|
+
hasSecret: false, transport: 'websocket',
|
|
19
|
+
});
|
|
20
|
+
await request(app).put(root).send({}).expect(403, { error: 'channel_disabled' });
|
|
21
|
+
await request(app).post(`${root}/retry`).send({}).expect(403, { error: 'channel_disabled' });
|
|
22
|
+
await request(app).post(`${root}/transfer`).send({}).expect(403, { error: 'channel_disabled' });
|
|
23
|
+
await request(app).post(`${root}/discover`).send({}).expect(403, { error: 'channel_disabled' });
|
|
24
|
+
await request(app).delete(root).expect(403, { error: 'channel_disabled' });
|
|
25
|
+
await runtime.close();
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
it('keeps the existing authentication boundary and forwards the save contract', async () => {
|
|
29
|
+
const app = express();
|
|
30
|
+
app.use(express.json());
|
|
31
|
+
app.use('/api/yuri', (req, res, next) => (
|
|
32
|
+
req.headers.authorization === 'Bearer test-owner' ? next() : res.sendStatus(401)
|
|
33
|
+
));
|
|
34
|
+
const runtime = {
|
|
35
|
+
status: vi.fn(() => ({
|
|
36
|
+
provider: 'feishu', status: 'disconnected', error: null, configured: false,
|
|
37
|
+
hasSecret: false, transport: 'websocket',
|
|
38
|
+
})),
|
|
39
|
+
save: vi.fn(async () => ({
|
|
40
|
+
provider: 'feishu', status: 'connecting', error: null, configured: true,
|
|
41
|
+
clientID: 'client', ownerID: 'owner', hasSecret: true, transport: 'websocket',
|
|
42
|
+
})),
|
|
43
|
+
retry: vi.fn(async () => ({ provider: 'feishu', status: 'reconnecting', error: null })),
|
|
44
|
+
transfer: vi.fn(async () => ({ provider: 'feishu', status: 'connecting', error: null })),
|
|
45
|
+
discover: vi.fn(async () => ({ ownerID: 'ou_user' })),
|
|
46
|
+
disconnect: vi.fn(async () => ({ provider: 'feishu', status: 'disconnected', error: null })),
|
|
47
|
+
};
|
|
48
|
+
registerAssistantChannelRoutes(app, runtime);
|
|
49
|
+
const root = '/api/yuri/assistants/bot/channels/feishu';
|
|
50
|
+
await request(app).put(root).send({}).expect(401);
|
|
51
|
+
expect(runtime.save).not.toHaveBeenCalled();
|
|
52
|
+
const saved = await request(app).put(root).auth('test-owner', { type: 'bearer' })
|
|
53
|
+
.send({ clientID: 'client', clientSecret: 'secret', ownerID: 'owner', language: 'zh-CN' })
|
|
54
|
+
.expect('Cache-Control', 'no-store').expect(200);
|
|
55
|
+
expect(saved.body).toMatchObject({ provider: 'feishu', configured: true, hasSecret: true });
|
|
56
|
+
expect(runtime.save).toHaveBeenCalledWith('bot', 'feishu', {
|
|
57
|
+
clientID: 'client', clientSecret: 'secret', ownerID: 'owner', language: 'zh-CN',
|
|
58
|
+
});
|
|
59
|
+
await request(app).post(`${root}/retry`).auth('test-owner', { type: 'bearer' }).expect(200);
|
|
60
|
+
expect(runtime.retry).toHaveBeenCalledWith('bot', 'feishu');
|
|
61
|
+
await request(app).post(`${root}/transfer`).send({ sourceAssistantID: 'old', revision: 'r1' }).expect(401);
|
|
62
|
+
expect(runtime.transfer).not.toHaveBeenCalled();
|
|
63
|
+
await request(app).post(`${root}/transfer`).auth('test-owner', { type: 'bearer' })
|
|
64
|
+
.send({ sourceAssistantID: 'old', revision: 'r1' }).expect(200);
|
|
65
|
+
expect(runtime.transfer).toHaveBeenCalledWith('bot', 'feishu', { sourceAssistantID: 'old', revision: 'r1' });
|
|
66
|
+
await request(app).post(`${root}/discover`).send({ clientID: 'client' }).expect(401);
|
|
67
|
+
expect(runtime.discover).not.toHaveBeenCalled();
|
|
68
|
+
await request(app).post(`${root}/discover`).auth('test-owner', { type: 'bearer' })
|
|
69
|
+
.send({ clientID: 'client', clientSecret: 'secret' }).expect('Cache-Control', 'no-store').expect(200, { ownerID: 'ou_user' });
|
|
70
|
+
expect(runtime.discover).toHaveBeenCalledWith('bot', 'feishu', { clientID: 'client', clientSecret: 'secret' }, { signal: expect.any(AbortSignal) });
|
|
71
|
+
await request(app).delete(root).auth('test-owner', { type: 'bearer' }).expect(200);
|
|
72
|
+
expect(runtime.disconnect).toHaveBeenCalledWith('bot', 'feishu');
|
|
73
|
+
});
|
|
74
|
+
|
|
75
|
+
it('redacts untrusted errors and maps safe codes to explicit statuses', async () => {
|
|
76
|
+
const app = express();
|
|
77
|
+
app.use(express.json());
|
|
78
|
+
const runtime = {
|
|
79
|
+
status: vi.fn(() => { throw new Error('client-secret=private-value'); }),
|
|
80
|
+
save: vi.fn(async () => { throw Object.assign(new Error('private upstream body'), { code: 'account_in_use' }); }),
|
|
81
|
+
retry: vi.fn(async () => { throw Object.assign(new Error('private'), { code: 'not_found' }); }),
|
|
82
|
+
disconnect: vi.fn(async () => { throw Object.assign(new Error('private'), { code: 'network_error' }); }),
|
|
83
|
+
};
|
|
84
|
+
registerAssistantChannelRoutes(app, runtime);
|
|
85
|
+
const root = '/api/yuri/assistants/bot/channels/dingtalk';
|
|
86
|
+
const redacted = await request(app).get(root).expect(400);
|
|
87
|
+
expect(redacted.body).toEqual({ error: 'channel_error' });
|
|
88
|
+
expect(JSON.stringify(redacted.body)).not.toContain('private-value');
|
|
89
|
+
await request(app).put(root).send({}).expect(409, { error: 'account_in_use' });
|
|
90
|
+
await request(app).post(`${root}/retry`).expect(404, { error: 'not_found' });
|
|
91
|
+
await request(app).delete(root).expect(502, { error: 'network_error' });
|
|
92
|
+
const validation = {
|
|
93
|
+
status: vi.fn(() => { throw Object.assign(new Error('private'), { code: 'channel_disabled' }); }),
|
|
94
|
+
};
|
|
95
|
+
const second = express();
|
|
96
|
+
registerAssistantChannelRoutes(second, validation);
|
|
97
|
+
await request(second).get(root).expect(403, { error: 'channel_disabled' });
|
|
98
|
+
});
|
|
99
|
+
|
|
100
|
+
it('maps sticky SDK conflicts to explicit conflicts without leaking messages', async () => {
|
|
101
|
+
const app = express();
|
|
102
|
+
app.use(express.json());
|
|
103
|
+
const runtime = {
|
|
104
|
+
save: async () => { throw Object.assign(new Error('private sdk detail'), { code: 'connection_replaced' }); },
|
|
105
|
+
retry: async () => { throw Object.assign(new Error('private epoch'), { code: 'binding_changed' }); },
|
|
106
|
+
};
|
|
107
|
+
registerAssistantChannelRoutes(app, runtime);
|
|
108
|
+
const root = '/api/yuri/assistants/bot/channels/wecom';
|
|
109
|
+
await request(app).put(root).send({}).expect(409, { error: 'connection_replaced' });
|
|
110
|
+
await request(app).post(`${root}/retry`).expect(409, { error: 'binding_changed' });
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
it('aborts discovery when the HTTP caller closes the request', async () => {
|
|
114
|
+
const app = express();
|
|
115
|
+
app.use(express.json());
|
|
116
|
+
let signal;
|
|
117
|
+
registerAssistantChannelRoutes(app, {
|
|
118
|
+
discover: async (_assistantID, _provider, _body, options) => {
|
|
119
|
+
signal = options.signal;
|
|
120
|
+
return new Promise((_, reject) => signal.addEventListener('abort', () => reject(Object.assign(new Error('cancelled'), { code: 'cancelled' })), { once: true }));
|
|
121
|
+
},
|
|
122
|
+
});
|
|
123
|
+
const server = app.listen(0, '127.0.0.1');
|
|
124
|
+
try {
|
|
125
|
+
await new Promise((resolve) => server.once('listening', resolve));
|
|
126
|
+
const controller = new AbortController();
|
|
127
|
+
const pending = fetch(`http://127.0.0.1:${server.address().port}/api/yuri/assistants/bot/channels/wecom/discover`, {
|
|
128
|
+
method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}', signal: controller.signal,
|
|
129
|
+
}).catch(() => {});
|
|
130
|
+
await vi.waitFor(() => expect(signal).toBeDefined());
|
|
131
|
+
controller.abort();
|
|
132
|
+
await pending;
|
|
133
|
+
await vi.waitFor(() => expect(signal.aborted).toBe(true));
|
|
134
|
+
} finally {
|
|
135
|
+
server.closeAllConnections();
|
|
136
|
+
await new Promise((resolve) => server.close(resolve));
|
|
137
|
+
}
|
|
138
|
+
});
|
|
139
|
+
});
|