@yuriai/web 0.2.27-beta.6 → 0.2.27-beta.8

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 (161) hide show
  1. package/README.md +8 -0
  2. package/dist/assets/{AgentAvatar-Bi1vvWPC.js → AgentAvatar-BJ42lGZD.js} +1 -1
  3. package/dist/assets/AssistantContactStatus-dtkObamV.js +3 -0
  4. package/dist/assets/{AssistantUnreadBadge-DdJyySwn.js → AssistantUnreadBadge-QwhBfXpC.js} +1 -1
  5. package/dist/assets/AssistantView-D7ryIKL0.js +1 -0
  6. package/dist/assets/{DiagramView-CI4bTtxy.js → DiagramView-ERrGEBDp.js} +1 -1
  7. package/dist/assets/{FadeInOnReveal-BB4qEnAn.js → FadeInOnReveal-Bu2GvaM9.js} +1 -1
  8. package/dist/assets/{GuiPluginSurface-CguxFUbM.js → GuiPluginSurface-MzQgEZNr.js} +1 -1
  9. package/dist/assets/{GuiPluginWindow-DOJ7wuRH.js → GuiPluginWindow-DZMmlQzx.js} +1 -1
  10. package/dist/assets/{Icon-t2xvbAyN.js → Icon-Dj4CCqCP.js} +1 -1
  11. package/dist/assets/{ImageLoadingPlaceholder-D1L13TK0.js → ImageLoadingPlaceholder-BnFXgUuO.js} +1 -1
  12. package/dist/assets/{LoadingImage-5rY_edNm.js → LoadingImage-PBnivDKv.js} +1 -1
  13. package/dist/assets/{MarkdownRenderer-BlGxjOei.js → MarkdownRenderer-BajF4gUU.js} +2 -2
  14. package/dist/assets/{MarkdownRendererImpl-cE-0AYRg.js → MarkdownRendererImpl-CfyXL4rg.js} +1 -1
  15. package/dist/assets/{MarkstreamRendererImpl-BZyqDl82.js → MarkstreamRendererImpl-BGadklK1.js} +1 -1
  16. package/dist/assets/{MobileDetailNavigation-tbfsMfB-.js → MobileDetailNavigation-DqajQdB4.js} +1 -1
  17. package/dist/assets/{MobileResizableSheet-BeRmT6_x.js → MobileResizableSheet-BvdUgwA3.js} +1 -1
  18. package/dist/assets/{MobileShareBridge-C3Equ3P_.js → MobileShareBridge-3oPoYnry.js} +2 -2
  19. package/dist/assets/{MobileTabPageHeader-DQRqAAEf.js → MobileTabPageHeader-B6cRyIRH.js} +1 -1
  20. package/dist/assets/{MultiRunWindow-CAM2XPII.js → MultiRunWindow-yhs0Ih5_.js} +1 -1
  21. package/dist/assets/{OnboardingScreen-4ftRerP5.js → OnboardingScreen-Bi1VWFQC.js} +1 -1
  22. package/dist/assets/{OverlayScrollbar-CF0PCvQz.js → OverlayScrollbar-BBDwGvGO.js} +1 -1
  23. package/dist/assets/{SettingsView-2tk4WH7R.js → SettingsView-BSf-SJUA.js} +15 -15
  24. package/dist/assets/{SettingsWindow-B9zbeJaW.js → SettingsWindow-BvSXVMTm.js} +1 -1
  25. package/dist/assets/{TerminalView-DfxvTHye.js → TerminalView-DhL01N7e.js} +1 -1
  26. package/dist/assets/{ToolOutputDialog-CrjDIhru.js → ToolOutputDialog-C8lnH4Ky.js} +1 -1
  27. package/dist/assets/{YuriLogo-QvS1ZEHi.js → YuriLogo-D8asj1CS.js} +1 -1
  28. package/dist/assets/{appThemeRegistry-Bb_DtiV9.js → appThemeRegistry-C-maYSdv.js} +1 -1
  29. package/dist/assets/{assistant-attachment-cache-B9iHLlm2.js → assistant-attachment-cache-B_qRvy-k.js} +1 -1
  30. package/dist/assets/{button-DinGM3tu.js → button-vXOdzd8x.js} +1 -1
  31. package/dist/assets/{capgoAdapter-DufzjXRs.js → capgoAdapter-DJ_h2x5D.js} +1 -1
  32. package/dist/assets/{collapsible-Bh1GLNYV.js → collapsible-DwDQs3Wa.js} +1 -1
  33. package/dist/assets/context-menu-BabBujQ-.js +1 -0
  34. package/dist/assets/{desktopRelayRestore-CoLLVJw8.js → desktopRelayRestore-D1UX7HW2.js} +1 -1
  35. package/dist/assets/{diagram-BmG-7Jb4.js → diagram-HwgrQxY5.js} +1 -1
  36. package/dist/assets/{dialog-BXssfGXA.js → dialog-Dnf626tb.js} +1 -1
  37. package/dist/assets/dropdown-menu.styles-CBc_a-Nv.js +1 -0
  38. package/dist/assets/{es-HP_Ise0X.js → es-BQkO-Odr.js} +1 -1
  39. package/dist/assets/feishu-Ct1ZxlzQ.svg +6 -0
  40. package/dist/assets/{fileMentionTouchSelection-DSl0tj2r.js → fileMentionTouchSelection-CKPnEetl.js} +1 -1
  41. package/dist/assets/{fileQueries-5a1jkme2.js → fileQueries-BeXkd3o6.js} +1 -1
  42. package/dist/assets/{fileReferenceActions-CGpBSFq4.js → fileReferenceActions-g7KZLi_G.js} +1 -1
  43. package/dist/assets/{fr-D0kJXJ6U.js → fr-C852roK5.js} +1 -1
  44. package/dist/assets/{gitApi-Wo0IZow9.js → gitApi-CVq5oKCd.js} +1 -1
  45. package/dist/assets/{gitApiHttp-De9liKnG.js → gitApiHttp-BYOIbYIh.js} +2 -2
  46. package/dist/assets/{gui-9enrif_1.js → gui-M_Rbwkyu.js} +1 -1
  47. package/dist/assets/host-BW3FEJdU.js +1 -0
  48. package/dist/assets/{image-loading-Dq1g_wpm.js → image-loading-D5UhMj7Z.js} +1 -1
  49. package/dist/assets/{input-v8-rVbo-.js → input-BtM712b1.js} +1 -1
  50. package/dist/assets/{insertionBoundaries-CZz7TWJv.js → insertionBoundaries-Dx3WAY6i.js} +1 -1
  51. package/dist/assets/{ja-BjHKXazE.js → ja-BqC39qK6.js} +1 -1
  52. package/dist/assets/{ko-Llwnl876.js → ko-BMaChAWh.js} +1 -1
  53. package/dist/assets/main-9uP2z1qT.js +2 -0
  54. package/dist/assets/main-Mey7bCWf.js +169 -0
  55. package/dist/assets/{markdownHeightCache-BVV2dktw.js → markdownHeightCache-Bf8iisO4.js} +1 -1
  56. package/dist/assets/{mcpQueries-BoBrB4a4.js → mcpQueries-DpXqegX5.js} +1 -1
  57. package/dist/assets/miniChat-DqZvVkme.js +2 -0
  58. package/dist/assets/mobile-DXAWjYcN.js +2 -0
  59. package/dist/assets/{mobileBackNavigation-DMSzAvb6.js → mobileBackNavigation-DZcI7aZg.js} +1 -1
  60. package/dist/assets/{multirun-BhWttsRQ.js → multirun-hzspPepd.js} +1 -1
  61. package/dist/assets/{native-DSvNnKAm.js → native-H7K64Ulc.js} +1 -1
  62. package/dist/assets/{native-config-DjdrW_9n.js → native-config-CddZtLQ1.js} +1 -1
  63. package/dist/assets/{persistence-CfrHIiIS.js → persistence-BT8045Ue.js} +1 -1
  64. package/dist/assets/{pl-BOd_idqn.js → pl-Ubs8p28T.js} +1 -1
  65. package/dist/assets/projectMeta-CEf0QPmD.js +1 -0
  66. package/dist/assets/{pt-BR-B8djxMsl.js → pt-BR-8rAOjJrs.js} +1 -1
  67. package/dist/assets/{queryRuntime-Dkpnq3Z1.js → queryRuntime-CTcigFdj.js} +1 -1
  68. package/dist/assets/react-DRe85o5s.js +1 -0
  69. package/dist/assets/readiness-Dyr7314z.js +1 -0
  70. package/dist/assets/{renderElectronMiniChatApp-N2r999Bf.js → renderElectronMiniChatApp-DoOq8Cuo.js} +2 -2
  71. package/dist/assets/{renderMobileApp-CU1ec6Ak.js → renderMobileApp-TTxtOb8b.js} +7 -7
  72. package/dist/assets/runtime-fetch-D0YWp3FJ.js +1 -0
  73. package/dist/assets/{runtime-file-download-CcNIVp7u.js → runtime-file-download-Cf1WxfeW.js} +1 -1
  74. package/dist/assets/{runtime-file-resource-6np6lzoV.js → runtime-file-resource-UJjHUF2C.js} +1 -1
  75. package/dist/assets/runtimeConfig-B8VHHNxj.js +2 -0
  76. package/dist/assets/runtimeEndpointReset-BC6XWntz.js +149 -0
  77. package/dist/assets/scheduledTaskNavigation-Zm87Nydi.js +1 -0
  78. package/dist/assets/sessionLookup-De53jDwM.js +1 -0
  79. package/dist/assets/{sortable-tabs-strip-yKyqsqut.js → sortable-tabs-strip-D4pVoodN.js} +1 -1
  80. package/dist/assets/speechSettingsQueries-RlCLMBtr.js +4 -0
  81. package/dist/assets/src-lE4uqaHS.css +2 -0
  82. package/dist/assets/{store-CUBymvAC.js → store-ME7oHni1.js} +2 -2
  83. package/dist/assets/{terminalApi-BblSkqch.js → terminalApi-BSaclMDJ.js} +1 -1
  84. package/dist/assets/{textarea-B39OCNPV.js → textarea-B98rsLs7.js} +1 -1
  85. package/dist/assets/{tooltip-d8TNN4lx.js → tooltip-B9810jbK.js} +1 -1
  86. package/dist/assets/{types-BqFQhQTt.js → types-DFf9vd1b.js} +1 -1
  87. package/dist/assets/{uk-BNd7CjVO.js → uk-LzwzUApL.js} +1 -1
  88. package/dist/assets/{useAppFontEffects-BVoVpJYO.js → useAppFontEffects-D2C1sBYM.js} +43 -43
  89. package/dist/assets/{useAssistantUIStore-Bp6TxG5E.js → useAssistantUIStore-TUN_ycy5.js} +1 -1
  90. package/dist/assets/{useDesktopWindowControlsLayout-CYx1LNO5.js → useDesktopWindowControlsLayout-BjKaHN0x.js} +1 -1
  91. package/dist/assets/{useEffectiveDirectory-D8FFE5Yn.js → useEffectiveDirectory-TEvyiQSC.js} +1 -1
  92. package/dist/assets/{useFontPreferences-BFyBjtQ6.js → useFontPreferences-BlhlCJCX.js} +1 -1
  93. package/dist/assets/{useMobileNavigationStore-BHMFeMjo.js → useMobileNavigationStore-DTvJV9s-.js} +6 -6
  94. package/dist/assets/useUIStore-DRx6OgCp.js +1 -0
  95. package/dist/assets/{useWorkerHighlightedLines-CPxG8Fya.js → useWorkerHighlightedLines-D093jNsH.js} +1 -1
  96. package/dist/assets/vendor-opencode-client-ZeOZ4Efz.js +23 -0
  97. package/dist/assets/{vendor-opencode-plugin-CgKz9Hcy.js → vendor-opencode-plugin-BBOP6WNx.js} +1 -1
  98. package/dist/assets/{vendor-solid-js-0T254UHG.js → vendor-solid-js-9wmPZH9g.js} +1 -1
  99. package/dist/assets/{zh-CN-BkTAEOZG.js → zh-CN-D-FVCeks.js} +1 -1
  100. package/dist/assets/{zh-TW-x8SfMzfc.js → zh-TW-B9iH_NXL.js} +1 -1
  101. package/dist/index.html +17 -17
  102. package/dist/mini-chat.html +17 -17
  103. package/dist/mobile.html +17 -17
  104. package/package.json +6 -1
  105. package/server/lib/assistants/DOCUMENTATION.md +13 -1
  106. package/server/lib/assistants/channels/DOCUMENTATION.md +291 -0
  107. package/server/lib/assistants/channels/PROTOCOLS.md +228 -0
  108. package/server/lib/assistants/channels/dingtalk-chat-adapter.js +633 -0
  109. package/server/lib/assistants/channels/dingtalk-chat-adapter.test.js +415 -0
  110. package/server/lib/assistants/channels/integration.test.js +44 -0
  111. package/server/lib/assistants/channels/routes.js +47 -0
  112. package/server/lib/assistants/channels/routes.test.js +105 -0
  113. package/server/lib/assistants/channels/runtime.js +867 -0
  114. package/server/lib/assistants/channels/runtime.test.js +723 -0
  115. package/server/lib/assistants/channels/sdk-adapters.js +371 -0
  116. package/server/lib/assistants/channels/sdk-adapters.test.js +367 -0
  117. package/server/lib/assistants/channels/store.js +246 -0
  118. package/server/lib/assistants/channels/store.test.js +286 -0
  119. package/server/lib/assistants/channels/transport.js +41 -0
  120. package/server/lib/assistants/channels/transport.test.js +23 -0
  121. package/server/lib/assistants/channels/wecom-chat-adapter.js +689 -0
  122. package/server/lib/assistants/channels/wecom-chat-adapter.test.js +109 -0
  123. package/server/lib/assistants/message-channel-origin.js +7 -0
  124. package/server/lib/assistants/routes.js +14 -1
  125. package/server/lib/assistants/weixin/DOCUMENTATION.md +89 -7
  126. package/server/lib/assistants/weixin/api.js +2 -0
  127. package/server/lib/assistants/weixin/chat-adapter.js +107 -0
  128. package/server/lib/assistants/weixin/chat-adapter.test.js +62 -0
  129. package/server/lib/assistants/weixin/inbound.js +147 -0
  130. package/server/lib/assistants/weixin/inbound.test.js +121 -0
  131. package/server/lib/assistants/weixin/media.js +79 -0
  132. package/server/lib/assistants/weixin/media.test.js +66 -0
  133. package/server/lib/assistants/weixin/runtime.js +89 -67
  134. package/server/lib/assistants/weixin/runtime.test.js +156 -4
  135. package/server/lib/assistants/weixin/store.js +8 -4
  136. package/server/lib/assistants/weixin/store.test.js +72 -0
  137. package/server/lib/assistants/weixin/toon.js +49 -0
  138. package/server/lib/assistants/weixin/toon.test.js +25 -0
  139. package/server/lib/github/DOCUMENTATION.md +9 -8
  140. package/server/lib/llm/bridge-plugin.bundle.js +188 -188
  141. package/server/lib/opencode/DOCUMENTATION.md +1 -1
  142. package/dist/assets/AssistantContactStatus-CWq-PDz6.js +0 -3
  143. package/dist/assets/AssistantView-Br1iETTs.js +0 -1
  144. package/dist/assets/context-menu-DpbkRkk1.js +0 -1
  145. package/dist/assets/host-FR_grJxM.js +0 -1
  146. package/dist/assets/main-Bp9HHqTr.js +0 -2
  147. package/dist/assets/main-DOwAfmxJ.js +0 -169
  148. package/dist/assets/miniChat-BJDgCrfF.js +0 -2
  149. package/dist/assets/mobile-GM9931J_.js +0 -2
  150. package/dist/assets/projectMeta-31PobC-M.js +0 -1
  151. package/dist/assets/react-B9v0P7kT.js +0 -1
  152. package/dist/assets/readiness-CYNnsekT.js +0 -1
  153. package/dist/assets/runtime-fetch-D4ja813o.js +0 -1
  154. package/dist/assets/runtimeConfig-Db7yfo6L.js +0 -2
  155. package/dist/assets/runtimeEndpointReset-DO5WVetV.js +0 -149
  156. package/dist/assets/scheduledTaskNavigation-Bsrhv3Ow.js +0 -1
  157. package/dist/assets/sessionLookup-DRVy7LM1.js +0 -1
  158. package/dist/assets/speechSettingsQueries-DU25rmGc.js +0 -4
  159. package/dist/assets/src-Bckdo2XS.css +0 -2
  160. package/dist/assets/useUIStore-BbYD420L.js +0 -1
  161. package/dist/assets/vendor-opencode-client-UL_TecvQ.js +0 -12
@@ -0,0 +1,109 @@
1
+ import { WebSocketServer } from 'ws';
2
+ import { afterEach, describe, expect, it, vi } from 'vitest';
3
+ import { createWecomSdkAdapter, WecomChatAdapter } from './wecom-chat-adapter.js';
4
+
5
+ const cleanups = [];
6
+ afterEach(async () => { while (cleanups.length) await cleanups.pop()(); });
7
+ const config = { clientID: 'test-bot', clientSecret: 'test-secret', ownerID: 'owner' };
8
+
9
+ async function connect(overrides = {}) {
10
+ const server = new WebSocketServer({ host: '127.0.0.1', port: 0 });
11
+ await new Promise((resolve) => server.once('listening', resolve));
12
+ cleanups.push(() => new Promise((resolve) => { for (const socket of server.clients) socket.terminate(); server.close(resolve); }));
13
+ const frames = [];
14
+ let socket;
15
+ server.on('connection', (value) => {
16
+ socket = value;
17
+ value.on('message', (bytes) => {
18
+ const frame = JSON.parse(bytes.toString());
19
+ if (frame.cmd === 'aibot_subscribe' || frame.cmd === 'ping') {
20
+ value.send(JSON.stringify({ headers: frame.headers, errcode: 0 }));
21
+ } else frames.push(frame);
22
+ });
23
+ });
24
+ const bridge = createWecomSdkAdapter({ wsUrl: `ws://127.0.0.1:${server.address().port}` });
25
+ const controller = new AbortController();
26
+ const onReady = vi.fn();
27
+ const onMessage = vi.fn();
28
+ const onError = vi.fn();
29
+ const running = bridge.connect({ config, signal: controller.signal, onReady, onMessage, onError, ...overrides });
30
+ cleanups.push(async () => { controller.abort(); await running.catch(() => {}); });
31
+ await vi.waitFor(() => expect(onReady).toHaveBeenCalledOnce());
32
+ return { bridge, controller, running, frames, socket: () => socket, onMessage, onError,
33
+ ack: (index, errcode = 0) => socket.send(JSON.stringify({ headers: frames[index].headers, errcode })) };
34
+ }
35
+
36
+ describe('official WeCom Chat adapter ACK boundary', () => {
37
+ it('waits for real SDK ACKs and sends a second reply without blocking the lane', async () => {
38
+ const h = await connect();
39
+ let settled = false;
40
+ const first = h.bridge.send({ config, text: 'first' }).then(() => { settled = true; });
41
+ await vi.waitFor(() => expect(h.frames).toHaveLength(1));
42
+ expect(settled).toBe(false);
43
+ expect(h.frames[0].body).toMatchObject({ chatid: 'owner', markdown: { content: 'first' } });
44
+ h.ack(0);
45
+ await first;
46
+ const second = h.bridge.send({ config, text: 'second' });
47
+ await vi.waitFor(() => expect(h.frames).toHaveLength(2));
48
+ h.ack(1);
49
+ await expect(second).resolves.toBeUndefined();
50
+ });
51
+
52
+ it('treats a nonzero ACK as a definite safe failure', async () => {
53
+ const h = await connect();
54
+ const sending = expect(h.bridge.send({ config, text: 'rejected' })).rejects.toMatchObject({ code: 'delivery_failed', ambiguous: false });
55
+ await vi.waitFor(() => expect(h.frames).toHaveLength(1));
56
+ h.ack(0, 846605);
57
+ await sending;
58
+ });
59
+
60
+ it('preserves uncertainty on cancellation after sending', async () => {
61
+ const h = await connect();
62
+ const controller = new AbortController();
63
+ const sending = expect(h.bridge.send({ config, text: 'cancel', signal: controller.signal })).rejects.toMatchObject({ code: 'delivery_unknown', ambiguous: true });
64
+ await vi.waitFor(() => expect(h.frames).toHaveLength(1));
65
+ controller.abort();
66
+ await sending;
67
+ });
68
+
69
+ it('preserves platform IDs and only admits owner private messages', async () => {
70
+ const h = await connect();
71
+ const body = { msgid: 'message-one', from: { userid: 'owner' }, chattype: 'single', msgtype: 'voice', voice: { content: 'transcript' } };
72
+ const emit = (value) => h.socket().send(JSON.stringify({ cmd: 'aibot_msg_callback', headers: { req_id: 'incoming' }, body: value }));
73
+ emit({ ...body, chattype: 'group' });
74
+ emit({ ...body, from: { userid: 'stranger' } });
75
+ emit(body);
76
+ await vi.waitFor(() => expect(h.onMessage).toHaveBeenCalledOnce());
77
+ expect(h.onMessage.mock.calls[0][0]).toMatchObject({ id: 'message-one', senderID: 'owner', text: 'transcript', metadata: { transcript: 'platform' } });
78
+ const adapter = new WecomChatAdapter({ ownerId: 'owner' });
79
+ const parsed = adapter.parseMessage({ ...body, msgtype: 'image', image: { url: 'private-url', aeskey: 'private-key' } });
80
+ expect(parsed.id).toBe('message-one');
81
+ expect(JSON.stringify(parsed)).not.toMatch(/private-url|private-key/);
82
+ });
83
+
84
+ it.each(['timeout', 'disconnect'])('keeps %s after submission unknown, never a successful send', async (mode) => {
85
+ const h = await connect();
86
+ const sending = expect(h.bridge.send({ config, text: 'uncertain' })).rejects.toMatchObject({ code: 'delivery_unknown', ambiguous: true });
87
+ await vi.waitFor(() => expect(h.frames).toHaveLength(1));
88
+ if (mode === 'disconnect') h.socket().terminate();
89
+ await sending;
90
+ }, 10_000);
91
+
92
+ it('allows another enterprise Bot account to connect concurrently', async () => {
93
+ const h = await connect();
94
+ const controller = new AbortController();
95
+ const onReady = vi.fn();
96
+ const running = h.bridge.connect({ config: { ...config, clientID: 'second-bot' }, signal: controller.signal, onReady });
97
+ cleanups.push(async () => { controller.abort(); await running.catch(() => {}); });
98
+ await vi.waitFor(() => expect(onReady).toHaveBeenCalledOnce());
99
+ await expect(h.bridge.connect({ config })).rejects.toMatchObject({ code: 'channel_in_use' });
100
+ });
101
+
102
+ it('reports missing sessions before writing and refuses duplicate live credentials', async () => {
103
+ const h = await connect();
104
+ await expect(h.bridge.connect({ config })).rejects.toMatchObject({ code: 'channel_in_use' });
105
+ await expect(h.bridge.send({ config: { ...config, clientID: 'another' }, text: 'no session' })).rejects.toMatchObject({ code: 'network_error', ambiguous: false });
106
+ h.controller.abort();
107
+ await h.running;
108
+ });
109
+ });
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Channel admission creates these reserved input IDs; contact turnID persists
3
+ * that exact ID on every reply. Never infer reply routing from the latest input.
4
+ */
5
+ export function isMessageChannelTurn(turnID) {
6
+ return typeof turnID === 'string' && (turnID.startsWith('weixin:') || turnID.startsWith('channel:'));
7
+ }
@@ -6,12 +6,16 @@ import { makeOpenCodeV2Client } from '../opencode/v2-client.js';
6
6
  import path from 'node:path';
7
7
  import { createWeixinRuntime } from './weixin/runtime.js';
8
8
  import { registerWeixinRoutes } from './weixin/routes.js';
9
+ import { createAssistantChannelsRuntime } from './channels/runtime.js';
10
+ import { registerAssistantChannelRoutes } from './channels/routes.js';
11
+ import { createAssistantChannelAdapters } from './channels/sdk-adapters.js';
9
12
 
10
13
  const respond = (res, work, success = 200) => Promise.resolve().then(work).then((body) => res.status(success).json(body)).catch((error) => { const code = error instanceof AssistantError ? error.code : error?.code || 'internal_error'; const status = code === 'not_found' ? 404 : ['revision_conflict', 'idempotency_conflict', 'contact_generation_conflict'].includes(code) ? 409 : code === 'assistant_disabled' ? 403 : code === 'no_provider' ? 400 : code === 'upstream_error' || code === 'llm_attachment_generation_unavailable' ? 502 : 400; res.status(status).json({ ok: false, error: code, message: typeof error?.message === 'string' && error.message.trim() ? error.message : code }); });
11
14
  const gone = (_req, res) => res.status(410).json({ ok: false, error: 'assistant_topics_retired' });
12
15
 
13
16
  export const registerAssistantRoutes = (app, dependencies) => {
14
17
  let weixin;
18
+ let channels;
15
19
  const boundCompletion = (input) => createChatCompletion({
16
20
  ...input,
17
21
  buildOpenCodeUrl: dependencies.buildOpenCodeUrl,
@@ -44,6 +48,7 @@ export const registerAssistantRoutes = (app, dependencies) => {
44
48
  onRevisionTip: dependencies.onRevisionTip,
45
49
  onContactTurnEvent: (event) => {
46
50
  weixin?.onTurnEvent(event);
51
+ channels?.onTurnEvent(event);
47
52
  dependencies.onContactTurnEvent?.(event);
48
53
  },
49
54
  onContactTurnComplete: dependencies.onContactTurnComplete,
@@ -62,6 +67,7 @@ export const registerAssistantRoutes = (app, dependencies) => {
62
67
  app.post('/api/yuri/assistants', (req, res) => respond(res, () => service.createAssistant(req.body), 201)); app.patch('/api/yuri/assistants/:assistantID', (req, res) => respond(res, () => service.updateAssistant(req.params.assistantID, req.body))); app.delete('/api/yuri/assistants/:assistantID', (req, res) => respond(res, async () => {
63
68
  const result = service.removeAssistant(req.params.assistantID, req.body?.expectedRevision);
64
69
  await weixin.forget(req.params.assistantID);
70
+ await channels.forget(req.params.assistantID);
65
71
  return result;
66
72
  }));
67
73
  app.post('/api/yuri/assistants/:assistantID/session/ensure', (req, res) => respond(res, () => service.ensure(req.params.assistantID))); app.post('/api/yuri/assistants/:assistantID/session/new', (req, res) => respond(res, () => service.createNew(req.params.assistantID))); app.post('/api/yuri/assistants/:assistantID/session/compact', (req, res) => respond(res, () => service.compact(req.params.assistantID, req.body))); app.post('/api/yuri/assistants/:assistantID/session/abort', (req, res) => respond(res, () => service.abort(req.params.assistantID, req.body)));
@@ -126,10 +132,17 @@ export const registerAssistantRoutes = (app, dependencies) => {
126
132
  ...(dependencies.weixinAPI ? { api: dependencies.weixinAPI } : {}),
127
133
  });
128
134
  registerWeixinRoutes(app, weixin);
135
+ channels = createAssistantChannelsRuntime({
136
+ directory: path.join(dependencies.yuriDataDir, 'channels'), service,
137
+ refreshAllowedRoots: dependencies.refreshAllowedRoots,
138
+ adapters: dependencies.assistantChannelAdapters ?? createAssistantChannelAdapters(),
139
+ ...(dependencies.channelsEnv ? { env: dependencies.channelsEnv } : {}),
140
+ });
141
+ registerAssistantChannelRoutes(app, channels);
129
142
  return { service, close: async () => {
130
143
  unsubscribeTaskResults?.();
131
144
  setAssignedSessionSettleHandler(null);
132
- await weixin.close();
145
+ await Promise.all([weixin.close(), channels.close()]);
133
146
  service.close();
134
147
  } };
135
148
  };
@@ -1,4 +1,4 @@
1
- # WeChat text channel
1
+ # WeChat message channel
2
2
 
3
3
  This Host-owned channel connects a QR-authorized personal WeChat account to one
4
4
  existing Yuri Bot. It uses Tencent's public `openclaw-weixin` iLink wire reference,
@@ -13,14 +13,29 @@ service protocol. No OpenClaw runtime or new dependency is installed.
13
13
  ordered outgoing deliveries and process-owner lease.
14
14
  - `runtime.js`: QR lifecycle, owner-only admission, bounded output reconciliation,
15
15
  retry/ambiguity and shutdown. `routes.js` exposes authenticated settings only.
16
+ - `chat-adapter.js`: the Chat SDK `Adapter` extension for personal-WeChat Bot.
17
+ Standard `Message`, thread identity, owner-only `openDM`, normalization and
18
+ `postMessage` are used by the running channel, not a separate demonstration path.
19
+ iLink-specific `poll`/`receipt` extensions preserve atomic cursor/receipt commits
20
+ and existing stable delivery IDs. Credentials and media capabilities remain in
21
+ private closures/receipts, not serialized Chat messages. Unsupported operations
22
+ throw `NotImplementedError`; HTTP webhook handling explicitly returns 501.
16
23
  - `typing.js`: optional per-binding live typing state, ticket lifetime, bounded
17
24
  refresh/backoff and serialized cancellation; no persisted presence or UI state.
25
+ - `inbound.js`: bounded inbound content projection, private media references,
26
+ partial-success attachment admission and TOON model/transcript context.
27
+ - `media.js`: deadline/byte-bounded official CDN downloads, AES-128-ECB decoding
28
+ and MIME identification; no arbitrary URL fetch or credential forwarding.
29
+ - `toon.js`: local JSON-only TOON encoder (objects, lists, primitive/tabular
30
+ arrays); no new dependency, key folding, raw-string emission or decoding API.
18
31
  - `assistants/service.channelPage()` is an internal bounded, ascending durable
19
32
  output seam. It validates the Bot and uses the contact-store generation. It does
20
33
  not expose credentials or replace the contact execution engine.
21
34
  - Shared `AssistantChannelsGroup` appears last in each **saved** Bot's settings,
22
35
  after scheduled tasks. One labelled **Message channels** group owns its card;
23
- WeChat is its first channel. It is not a global setting or one search entry per
36
+ WeChat, WeCom, Feishu and DingTalk form a 2×2 set of colored brand entries;
37
+ configuration (including WeChat QR/verification/rebind) opens in a dialog.
38
+ It is not a global setting or one search entry per
24
39
  dynamic Bot. Web, desktop, hosted mobile and Capacitor configure the active Host
25
40
  through `runtimeFetch`; standalone VS Code explicitly returns 501.
26
41
 
@@ -109,7 +124,9 @@ Incoming receipt, reply context and platform cursor commit together before calli
109
124
  `service.send()`. Namespaced IDs keep admission idempotent across duplicates and
110
125
  restarts. Incoming and outgoing work is separate from the long-poll receiver; pending
111
126
  plus admitted receipt count applies backpressure at 100, with 20 admissions per pass.
112
- Each active account has one receiver and one outbound scheduler. The process lease
127
+ Each active account has one receiver, one serial input-preparation worker and one
128
+ outbound scheduler. Media downloads do not block same-account replies or another
129
+ account's preparation/sending. The process lease
113
130
  renews every 2 seconds and expires after 60 seconds; another process sharing this
114
131
  data directory cannot steal a live account. After any network wait, epoch/lease
115
132
  checks fence stale writes. Cross-machine copies of credentials/data are unsupported.
@@ -119,10 +136,66 @@ sent. Subsequent **public assistant replies**, including App-initiated and backg
119
136
  task replies, sync to the paired owner. Plain text is sent as text; current cards
120
137
  become title/name text, not interactive WeChat cards or deeplinks. Internal settle
121
138
  markers are omitted and failures use a safe generic message, never raw tool errors.
122
- Media input gets a text-only explanation and never invokes tools. Generation reset
123
- drops queued output from the previous transcript. An already submitted HTTP request
139
+ Generation reset drops queued output from the previous transcript. An already submitted HTTP request
124
140
  cannot be recalled, including during disconnect/reset.
125
141
 
142
+ ### Rich inbound content
143
+
144
+ - Plain text retains the ordinary text path. Item protocol IDs (`msg_id`) and
145
+ envelope fields such as timestamps do not create a separate TOON text part.
146
+ Every recognized image, voice, file
147
+ and video item is represented; mixed items no longer silently lose media. An
148
+ item-level `msg_id` is accepted when the top-level message ID is absent, matching
149
+ the reference client. Sender/group/ID authorization runs before normalization
150
+ or media access.
151
+ - Images download/decrypt and enter the existing `putAssistantContactAttachment`
152
+ pipeline with deterministic receipt/item upload IDs. The transcript stores opaque
153
+ attachment descriptors, not data URLs, CDN capabilities or AES keys. Existing
154
+ contact materialization supplies bytes to vision-capable models; choosing a
155
+ non-vision model does not acquire image understanding through this channel.
156
+ Thumbnail-only references are labelled as thumbnails; URL-only image references
157
+ still pass the same fixed-CDN validation. Neither permits arbitrary web fetching.
158
+ - Voice uses platform `voice_item.text` when present, without a duplicate audio
159
+ download. Otherwise the original audio is retained as an attachment and marked
160
+ **not transcribed**. No SILK decoder, automatic ASR provider, guessed transcript
161
+ or new speech dependency is installed. Video similarly retains the original file,
162
+ not a claim of audiovisual understanding. Text files use the existing gateway's
163
+ bounded inline-text path; other document formats retain normal attachment/model
164
+ limitations rather than being represented as extracted text.
165
+ - Unknown item types and top-level content extensions retain bounded structured
166
+ data, including share titles, descriptions and article URLs **if supplied by the
167
+ platform**. JSON-valued strings are projected structurally; XML remains quoted
168
+ external text (no XML/entity expansion or URL fetching). Inline quote titles,
169
+ IDs, substring metadata and supplied content are retained; an ID-only quote does
170
+ not invent a cached body. This is not a guessed public article-item schema.
171
+ - Structure becomes TOON in an ordinary user text part, explicitly labelled as
172
+ external content. Transport/authentication fields, media references/keys, bearer
173
+ values and known sensitive URL parameters are excluded; raw upstream errors never
174
+ reach the model/transcript. Links or metadata are not evidence that article
175
+ contents were retrieved. The channel does not automatically fetch arbitrary
176
+ article links or bypass WeChat login/risk controls. If iLink never delivers a
177
+ share card, Yuri cannot recover it from the user's WeChat client.
178
+ - Bounds: 20 top-level items, eight downloads, nesting limits, a 24,000-character
179
+ metadata budget (8,000 per string), and 20,000 ordinary text characters per
180
+ message. Truncation is explicit. Each file is capped at 20 MiB to match the LLM
181
+ gateway, and each turn at 50 MiB. Downloads are serial per account, have a
182
+ 20-second deadline, reject redirects, and only accept HTTPS at the known
183
+ `novac2c.cdn.weixin.qq.com/c2c/download` endpoint. Unknown CDN hosts degrade to
184
+ metadata with an unavailable marker rather than widening the fetch boundary.
185
+ - One failed download/storage operation does not discard text, transcripts,
186
+ share fields or successful attachments. Missing bytes and original-only media
187
+ have explicit status. Byte/metadata limits are degradation, not empty success.
188
+
189
+ The private inbox gains an additive `payload` column (old rows default to empty).
190
+ It stores normalized metadata and bounded media capabilities before advancing the
191
+ cursor, allowing pre-admission work to resume after restart with stable upload IDs.
192
+ After admission the existing no-tool-replay recovery rule applies. Completed,
193
+ recovered and transferred receipts clear both text and private payload; disconnect
194
+ deletes them. Download cancellation and post-await binding/lease/auth/generation
195
+ checks prevent stale preparation from admitting a message after disconnect, move,
196
+ expiry or transcript reset. Successfully staged attachments follow the existing
197
+ contact attachment lifecycle, including its normal unreferenced-object behavior.
198
+
126
199
  Replies are split by Unicode code points into at most 3500-character segments;
127
200
  stable client IDs and ordered outbox rows survive restart. This is not a server-side
128
201
  exactly-once guarantee. An uncertain HTTP result is marked **delivery unknown** and
@@ -149,7 +222,11 @@ content and stale runtime mutations cannot overwrite a new Host's cache.
149
222
  ### Typing presence
150
223
 
151
224
  Only live `yuri:contact-turn-start/end` events drive typing, including App-initiated
152
- or background contact turns whose public replies also sync to WeChat. Binding or
225
+ or background contact turns without a channel source, which may push to WeChat.
226
+ Replies to channel-originated turns require an exact receipt in this binding:
227
+ WeChat inputs reply only here, and enterprise-channel inputs never broadcast here.
228
+ The persisted contact turn ID identifies the original admitted input across restart.
229
+ Binding or
153
230
  restarting does not infer activity from persisted receipts/history, and historical
154
231
  end events or streaming deltas never start an indicator. A turn already running
155
232
  before binding is not backfilled. Overlapping live turn IDs share one indicator;
@@ -194,6 +271,11 @@ Focused tests cover wire behavior, business errors, QR fencing, owner isolation,
194
271
  dedup, restart, conflicting bindings, process lease, shutdown, generation changes,
195
272
  unknown delivery, HTTP protection, confirmed moves, failed-write rollback,
196
273
  cursor/dedup preservation, concurrent/stale moves, typing cancellation/stale completions,
197
- and real contact-pipeline execution with a fake WeChat service. Real-account
274
+ and real contact-pipeline execution with a fake WeChat service. Rich-input coverage
275
+ includes AES key encodings, SSRF/redirect/size boundaries, partial success,
276
+ TOON quoting, synthetic unknown share fields, voice transcripts, private-field
277
+ redaction, durable receipt migration/rollback/restart and real attachment storage.
278
+ Synthetic article extension fixtures are not evidence of a live platform schema.
279
+ Real-account
198
280
  QR/verification, phone-visible delivery and typing presentation still require
199
281
  manual testing; mocks and builds are not evidence of platform acceptance.
@@ -1,4 +1,5 @@
1
1
  import { randomBytes } from 'node:crypto';
2
+ import { downloadWeixinMedia } from './media.js';
2
3
 
3
4
  // Wire-format reference: Tencent/openclaw-weixin (MIT), docs/protocol.md.
4
5
  // This is a Yuri transport, not an OpenClaw runtime or a WorkBuddy login client.
@@ -84,6 +85,7 @@ export function createWeixinAPI({ fetchImpl = fetch } = {}) {
84
85
  }
85
86
  };
86
87
  return {
88
+ downloadMedia: (source, signal) => downloadWeixinMedia(source, { fetchImpl, signal }),
87
89
  getQRCode: (signal, localTokens = []) => request(API_ORIGIN, '/ilink/bot/get_bot_qrcode?bot_type=3', {
88
90
  body: { local_token_list: localTokens.slice(0, 10) }, signal,
89
91
  }),
@@ -0,0 +1,107 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { Message, NotImplementedError, stringifyMarkdown } from 'chat';
3
+ import { WeixinError } from './api.js';
4
+ import { normalizeWeixinInput } from './inbound.js';
5
+ import { encodeWeixinTOON } from './toon.js';
6
+
7
+ const digest = (value) => createHash('sha256').update(value).digest('hex');
8
+ const unsupported = async () => { throw new NotImplementedError('WeChat iLink does not expose this operation'); };
9
+
10
+ /**
11
+ * Chat SDK Adapter extension for the QR-authorized iLink Bot protocol.
12
+ * Durable receipt/cursor transactions and tool execution remain Yuri-owned.
13
+ */
14
+ export function createWeixinChatAdapter({ api, getBinding, clock = Date.now }) {
15
+ const receipts = new WeakMap();
16
+ let chat;
17
+ let closed = false;
18
+ const binding = () => {
19
+ const value = !closed && getBinding();
20
+ if (!value) throw new WeixinError('cancelled');
21
+ return value;
22
+ };
23
+ const encodeThreadId = ({ accountID, peerID }) => `weixin:${encodeURIComponent(accountID)}:${encodeURIComponent(peerID)}`;
24
+ const decodeThreadId = (threadID) => {
25
+ const pieces = threadID.split(':');
26
+ if (pieces.length !== 3 || pieces[0] !== 'weixin') throw new WeixinError('validation_error');
27
+ try { return { accountID: decodeURIComponent(pieces[1]), peerID: decodeURIComponent(pieces[2]) }; }
28
+ catch { throw new WeixinError('validation_error'); }
29
+ };
30
+ const adapter = {
31
+ name: 'weixin', userName: 'Yuri',
32
+ initialize: async (instance) => { chat = instance; },
33
+ disconnect: async () => { closed = true; chat = undefined; },
34
+ encodeThreadId, decodeThreadId,
35
+ channelIdFromThreadId: (threadID) => { decodeThreadId(threadID); return threadID; },
36
+ isDM: (threadID) => { decodeThreadId(threadID); return true; },
37
+ openDM: async (userID) => {
38
+ const current = binding();
39
+ if (userID !== current.peer_id) throw new WeixinError('validation_error');
40
+ return encodeThreadId({ accountID: current.account_id, peerID: userID });
41
+ },
42
+ handleWebhook: async () => new Response(JSON.stringify({ error: 'weixin_long_poll_only' }),
43
+ { status: 501, headers: { 'Content-Type': 'application/json' } }),
44
+ parseMessage: (raw) => {
45
+ const current = binding();
46
+ if (raw?.message_type !== 1 || raw.from_user_id !== current.peer_id || raw.group_id) throw new WeixinError('validation_error');
47
+ const platformID = typeof raw.message_id === 'string' && raw.message_id ? raw.message_id
48
+ : Array.isArray(raw.item_list) ? raw.item_list.find((item) => typeof item?.msg_id === 'string' && item.msg_id)?.msg_id : '';
49
+ if (!platformID || platformID.length > 256) throw new WeixinError('validation_error');
50
+ const normalized = normalizeWeixinInput(raw);
51
+ const payload = normalized.payload ? JSON.parse(normalized.payload) : null;
52
+ const context = typeof raw.context_token === 'string' && raw.context_token.length <= 65_536 ? raw.context_token : '';
53
+ const text = [normalized.text, payload ? encodeWeixinTOON({ items: payload.items, truncated: payload.truncated }) : ''].filter(Boolean).join('\n');
54
+ const message = new Message({
55
+ id: `weixin:${digest(JSON.stringify([current.account_id, current.peer_id, platformID]))}`,
56
+ threadId: encodeThreadId({ accountID: current.account_id, peerID: current.peer_id }), text,
57
+ formatted: { type: 'root', children: [{ type: 'paragraph', children: [{ type: 'text', value: text }] }] },
58
+ raw: { items: payload?.items ?? [], truncated: payload?.truncated ?? false },
59
+ author: { userId: current.peer_id, userName: current.peer_id, fullName: '', isBot: false, isMe: false },
60
+ metadata: { dateSent: new Date(clock()), edited: false },
61
+ attachments: (payload?.media ?? []).map((source) => ({
62
+ type: source.kind === 'voice' ? 'audio' : source.kind,
63
+ ...(source.filename ? { name: source.filename } : {}),
64
+ // Capability references stay in this private closure, never serialized.
65
+ fetchData: async () => {
66
+ const active = binding();
67
+ if (active.epoch !== current.epoch) throw new WeixinError('cancelled');
68
+ const media = await api.downloadMedia(source);
69
+ if (binding().epoch !== current.epoch) throw new WeixinError('cancelled');
70
+ return media.buffer;
71
+ },
72
+ })),
73
+ });
74
+ receipts.set(message, { id: message.id, ...normalized, context });
75
+ return message;
76
+ },
77
+ renderFormatted: (content) => stringifyMarkdown(content),
78
+ postMessage: async (threadID, message, { id = `yuri_${randomUUID()}`, signal } = {}) => {
79
+ const current = binding();
80
+ const target = decodeThreadId(threadID);
81
+ if (target.accountID !== current.account_id || target.peerID !== current.peer_id) throw new WeixinError('validation_error');
82
+ if (message?.files?.length || message?.attachments?.length) return unsupported();
83
+ const text = typeof message === 'string' ? message : typeof message?.raw === 'string' ? message.raw
84
+ : typeof message?.markdown === 'string' ? message.markdown : message?.ast ? stringifyMarkdown(message.ast) : null;
85
+ if (text === null) return unsupported();
86
+ if (!text || Array.from(text).length > 3500) throw new WeixinError('validation_error');
87
+ await api.sendText(current, { id, text }, signal);
88
+ return { id, raw: { id } };
89
+ },
90
+ fetchThread: async (threadID) => { decodeThreadId(threadID); return { id: threadID, channelId: threadID, isDM: true, metadata: {} }; },
91
+ fetchMessages: unsupported, editMessage: unsupported, deleteMessage: unsupported,
92
+ addReaction: unsupported, removeReaction: unsupported, startTyping: unsupported,
93
+ // iLink-specific extensions: preserve cursor-atomic batch admission and IDs.
94
+ poll: (signal) => api.getUpdates(binding(), signal),
95
+ dispatch: async (raw) => {
96
+ if (!chat) throw new WeixinError('cancelled');
97
+ const message = adapter.parseMessage(raw);
98
+ await chat.processMessage(adapter, message.threadId, message);
99
+ },
100
+ receipt: (message) => {
101
+ const receipt = receipts.get(message);
102
+ if (!receipt) throw new WeixinError('validation_error');
103
+ return receipt;
104
+ },
105
+ };
106
+ return adapter;
107
+ }
@@ -0,0 +1,62 @@
1
+ import { Message } from 'chat';
2
+ import { describe, expect, it, vi } from 'vitest';
3
+ import { createWeixinChatAdapter } from './chat-adapter.js';
4
+
5
+ const binding = { epoch: 'epoch', account_id: 'account:one', peer_id: 'owner', token: 'test-secret', context_token: 'private-context' };
6
+ const textMessage = { message_id: 'one', message_type: 1, from_user_id: 'owner', context_token: 'private-context',
7
+ item_list: [{ type: 1, text_item: { text: '你好' } }] };
8
+
9
+ describe('Chat SDK WeChat Bot adapter', () => {
10
+ it('uses the standard Message and dispatch seam while keeping credentials and cursor capabilities private', async () => {
11
+ const api = { getUpdates: vi.fn(async () => ({ msgs: [textMessage] })), sendText: vi.fn() };
12
+ const adapter = createWeixinChatAdapter({ api, getBinding: () => binding, clock: () => 1000 });
13
+ const processMessage = vi.fn();
14
+ await adapter.initialize({ processMessage });
15
+ await adapter.dispatch(textMessage);
16
+ const [source, threadID, message] = processMessage.mock.calls[0];
17
+ expect(source).toBe(adapter);
18
+ expect(message).toBeInstanceOf(Message);
19
+ expect(message.text).toBe('你好');
20
+ expect(message.author).toMatchObject({ userId: 'owner', isMe: false });
21
+ expect(adapter.decodeThreadId(threadID)).toEqual({ accountID: 'account:one', peerID: 'owner' });
22
+ expect(adapter.receipt(message)).toMatchObject({ id: message.id, text: '你好', context: 'private-context', payload: '' });
23
+ expect(JSON.stringify(message.toJSON())).not.toMatch(/test-secret|private-context/);
24
+ expect(await adapter.poll()).toEqual({ msgs: [textMessage] });
25
+ });
26
+
27
+ it('retains rich-input receipts and exposes lazy standard attachments without serializing media keys', async () => {
28
+ const api = { downloadMedia: vi.fn(async () => ({ buffer: Buffer.from('image') })) };
29
+ const adapter = createWeixinChatAdapter({ api, getBinding: () => binding });
30
+ const message = adapter.parseMessage({ ...textMessage, item_list: [
31
+ { type: 2, image_item: { media: { aes_key: 'private-key', encrypt_query_param: 'private-capability' } } },
32
+ { type: 99, article_item: { title: '文章标题', url: 'https://mp.weixin.qq.com/s/example' } },
33
+ ] });
34
+ expect(message.text).toContain('文章标题');
35
+ expect(message.attachments[0].type).toBe('image');
36
+ expect(JSON.stringify(message.toJSON())).not.toMatch(/private-key|private-capability/);
37
+ expect(adapter.receipt(message).payload).toContain('private-key');
38
+ await expect(message.attachments[0].fetchData()).resolves.toEqual(Buffer.from('image'));
39
+ });
40
+
41
+ it('keeps stable delivery IDs and latest reply context, and disallows sending to another owner', async () => {
42
+ const api = { sendText: vi.fn(async () => {}) };
43
+ const adapter = createWeixinChatAdapter({ api, getBinding: () => binding });
44
+ const threadID = await adapter.openDM('owner');
45
+ const controller = new AbortController();
46
+ await adapter.postMessage(threadID, { markdown: '**result**' }, { id: 'stable-outbox-id', signal: controller.signal });
47
+ expect(api.sendText).toHaveBeenCalledWith(binding, { id: 'stable-outbox-id', text: '**result**' }, controller.signal);
48
+ await expect(adapter.openDM('stranger')).rejects.toMatchObject({ code: 'validation_error' });
49
+ await expect(adapter.postMessage('weixin:other:owner', 'no')).rejects.toMatchObject({ code: 'validation_error' });
50
+ await expect(adapter.postMessage(threadID, { files: [{ data: Buffer.from('file') }], raw: 'file' })).rejects.toThrow();
51
+ expect((await adapter.handleWebhook(new Request('https://example.com'))).status).toBe(501);
52
+ await adapter.disconnect();
53
+ await expect(adapter.postMessage(threadID, 'late')).rejects.toMatchObject({ code: 'cancelled' });
54
+ });
55
+
56
+ it('rejects unauthorized, group and ID-less input before constructing a Chat message', () => {
57
+ const adapter = createWeixinChatAdapter({ api: {}, getBinding: () => binding });
58
+ for (const changes of [{ from_user_id: 'stranger' }, { group_id: 'group' }, { message_id: '' }]) {
59
+ expect(() => adapter.parseMessage({ ...textMessage, ...changes })).toThrow('validation_error');
60
+ }
61
+ });
62
+ });