@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.
Files changed (228) hide show
  1. package/README.md +8 -0
  2. package/dist/assets/{AgentAvatar-Bi1vvWPC.js → AgentAvatar-DNm_jMna.js} +1 -1
  3. package/dist/assets/AssistantContactStatus-BPRpgMFh.js +3 -0
  4. package/dist/assets/{AssistantUnreadBadge-DdJyySwn.js → AssistantUnreadBadge-BssH-RvV.js} +1 -1
  5. package/dist/assets/AssistantView-CxQv-9Ms.js +1 -0
  6. package/dist/assets/{DiagramView-CI4bTtxy.js → DiagramView-DPpG0fwx.js} +1 -1
  7. package/dist/assets/{FadeInOnReveal-BB4qEnAn.js → FadeInOnReveal-S6UbimjB.js} +1 -1
  8. package/dist/assets/{GuiPluginSurface-CguxFUbM.js → GuiPluginSurface-BOf0JA1T.js} +1 -1
  9. package/dist/assets/{GuiPluginWindow-DOJ7wuRH.js → GuiPluginWindow-OrYkfQ4m.js} +1 -1
  10. package/dist/assets/{Icon-t2xvbAyN.js → Icon-BE4mEwzV.js} +1 -1
  11. package/dist/assets/{ImageLoadingPlaceholder-D1L13TK0.js → ImageLoadingPlaceholder-CBFJC_KD.js} +1 -1
  12. package/dist/assets/{LoadingImage-5rY_edNm.js → LoadingImage-NLq7_P-i.js} +1 -1
  13. package/dist/assets/MarkdownRenderer-BaMotAOQ.js +2 -0
  14. package/dist/assets/{MarkdownRendererImpl-cE-0AYRg.js → MarkdownRendererImpl-Cv6UnGG7.js} +1 -1
  15. package/dist/assets/{MarkstreamRendererImpl-BZyqDl82.js → MarkstreamRendererImpl-Rb9O6wkW.js} +1 -1
  16. package/dist/assets/{MobileDetailNavigation-tbfsMfB-.js → MobileDetailNavigation-CK4KbkeS.js} +1 -1
  17. package/dist/assets/{MobileResizableSheet-BeRmT6_x.js → MobileResizableSheet-Deidw1br.js} +1 -1
  18. package/dist/assets/{MobileShareBridge-C3Equ3P_.js → MobileShareBridge-CO_OWEfq.js} +2 -2
  19. package/dist/assets/MobileTabPageHeader-DbC8L6A4.js +2 -0
  20. package/dist/assets/{MultiRunWindow-CAM2XPII.js → MultiRunWindow-DtVW9NTV.js} +1 -1
  21. package/dist/assets/{OnboardingScreen-4ftRerP5.js → OnboardingScreen-C8ld4wO7.js} +1 -1
  22. package/dist/assets/{OverlayScrollbar-CF0PCvQz.js → OverlayScrollbar-B3auC2WH.js} +1 -1
  23. package/dist/assets/{SettingsView-2tk4WH7R.js → SettingsView-Cm7woZWl.js} +15 -15
  24. package/dist/assets/{SettingsWindow-B9zbeJaW.js → SettingsWindow-CdL4PFxW.js} +1 -1
  25. package/dist/assets/{TerminalView-DfxvTHye.js → TerminalView-CwRB6Yyr.js} +1 -1
  26. package/dist/assets/{ToolOutputDialog-CrjDIhru.js → ToolOutputDialog-B4BfmoVH.js} +1 -1
  27. package/dist/assets/{YuriLogo-QvS1ZEHi.js → YuriLogo-BOx0s0Ue.js} +1 -1
  28. package/dist/assets/{appThemeRegistry-Bb_DtiV9.js → appThemeRegistry-B6woJIX5.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-BXxwtxsG.js} +1 -1
  31. package/dist/assets/{capgoAdapter-DufzjXRs.js → capgoAdapter-C5HFS-rx.js} +1 -1
  32. package/dist/assets/{collapsible-Bh1GLNYV.js → collapsible-BEm0787p.js} +1 -1
  33. package/dist/assets/context-menu-DUwvVUDY.js +1 -0
  34. package/dist/assets/{desktopRelayRestore-CoLLVJw8.js → desktopRelayRestore-D1UX7HW2.js} +1 -1
  35. package/dist/assets/device-BcRP6Tjd.js +2 -0
  36. package/dist/assets/{diagram-BmG-7Jb4.js → diagram-DyY8dxjZ.js} +1 -1
  37. package/dist/assets/{dialog-BXssfGXA.js → dialog-CLca6ojn.js} +1 -1
  38. package/dist/assets/dropdown-menu.styles-DGaALKP0.js +1 -0
  39. package/dist/assets/{es-HP_Ise0X.js → es-CrsHvgue.js} +2 -2
  40. package/dist/assets/feishu-Ct1ZxlzQ.svg +6 -0
  41. package/dist/assets/fileMentionAutocompleteState-BZJqfgae.js +2 -0
  42. package/dist/assets/{fileMentionTouchSelection-DSl0tj2r.js → fileMentionTouchSelection-C4dvP8GY.js} +2 -2
  43. package/dist/assets/{fileQueries-5a1jkme2.js → fileQueries-BeXkd3o6.js} +1 -1
  44. package/dist/assets/{fileReferenceActions-CGpBSFq4.js → fileReferenceActions-CrIAce3K.js} +1 -1
  45. package/dist/assets/{fr-D0kJXJ6U.js → fr-CEgiRlfa.js} +2 -2
  46. package/dist/assets/{gitApi-Wo0IZow9.js → gitApi-D2G9ny2O.js} +1 -1
  47. package/dist/assets/{gitApiHttp-De9liKnG.js → gitApiHttp-B7vYwgBh.js} +4 -4
  48. package/dist/assets/{gui-9enrif_1.js → gui-CJjEj3l4.js} +1 -1
  49. package/dist/assets/host-CnVx34Dh.js +1 -0
  50. package/dist/assets/{image-loading-Dq1g_wpm.js → image-loading-D5UhMj7Z.js} +1 -1
  51. package/dist/assets/{input-v8-rVbo-.js → input-D59Q2pm8.js} +1 -1
  52. package/dist/assets/insertionBoundaries-CedfTSM5.js +1 -0
  53. package/dist/assets/{ja-BjHKXazE.js → ja-CX-_p9jZ.js} +2 -2
  54. package/dist/assets/{ko-Llwnl876.js → ko-D5xlLYJM.js} +2 -2
  55. package/dist/assets/main-CxpUooVS.js +2 -0
  56. package/dist/assets/main-Dpm4KxWX.js +169 -0
  57. package/dist/assets/{markdownHeightCache-BVV2dktw.js → markdownHeightCache-D2VWb_4E.js} +1 -1
  58. package/dist/assets/{mcpQueries-BoBrB4a4.js → mcpQueries-DQ3KthDF.js} +1 -1
  59. package/dist/assets/miniChat-CTdj8Ug9.js +2 -0
  60. package/dist/assets/mobile-ChbA3Q8j.js +2 -0
  61. package/dist/assets/{mobileBackNavigation-DMSzAvb6.js → mobileBackNavigation-BJqt3oHk.js} +1 -1
  62. package/dist/assets/{multirun-BhWttsRQ.js → multirun-BILeETbd.js} +1 -1
  63. package/dist/assets/{native-DSvNnKAm.js → native-BYMhr-xH.js} +1 -1
  64. package/dist/assets/{native-config-DjdrW_9n.js → native-config-BIY0Cr-l.js} +1 -1
  65. package/dist/assets/{persistence-CfrHIiIS.js → persistence-CWuLIq1J.js} +2 -2
  66. package/dist/assets/{pl-BOd_idqn.js → pl-BjH81A_q.js} +2 -2
  67. package/dist/assets/projectMeta-B9_Uh8YH.js +1 -0
  68. package/dist/assets/{pt-BR-B8djxMsl.js → pt-BR-Dp5oK2x3.js} +2 -2
  69. package/dist/assets/{queryRuntime-Dkpnq3Z1.js → queryRuntime-CTcigFdj.js} +1 -1
  70. package/dist/assets/queue-abort-optimistic-CS5jTJq-.js +1 -0
  71. package/dist/assets/react-DRe85o5s.js +1 -0
  72. package/dist/assets/readiness-BNIgH81X.js +1 -0
  73. package/dist/assets/renderElectronMiniChatApp-asOqV7FB.js +2 -0
  74. package/dist/assets/renderMobileApp-DAfque7-.js +28 -0
  75. package/dist/assets/runtime-fetch-D0YWp3FJ.js +1 -0
  76. package/dist/assets/{runtime-file-download-CcNIVp7u.js → runtime-file-download-Cf1WxfeW.js} +1 -1
  77. package/dist/assets/{runtime-file-resource-6np6lzoV.js → runtime-file-resource-UJjHUF2C.js} +1 -1
  78. package/dist/assets/runtimeConfig-BX8JirIc.js +2 -0
  79. package/dist/assets/runtimeEndpointReset-CFQgUiUr.js +149 -0
  80. package/dist/assets/scheduledTaskNavigation-EomDNVu2.js +1 -0
  81. package/dist/assets/sessionLookup-BxAaxPOw.js +1 -0
  82. package/dist/assets/{sortable-tabs-strip-yKyqsqut.js → sortable-tabs-strip-DpbW5MqX.js} +1 -1
  83. package/dist/assets/speechSettingsQueries-CC0fusUo.js +4 -0
  84. package/dist/assets/src-BMKjN2ip.css +2 -0
  85. package/dist/assets/{store-CUBymvAC.js → store-CkIHVrmT.js} +4 -3
  86. package/dist/assets/{terminalApi-BblSkqch.js → terminalApi-rl9mZAlB.js} +1 -1
  87. package/dist/assets/{textarea-B39OCNPV.js → textarea-7eTptEtD.js} +1 -1
  88. package/dist/assets/{tooltip-d8TNN4lx.js → tooltip-BPwoSTzO.js} +1 -1
  89. package/dist/assets/types-CUtSV1V8.js +2 -0
  90. package/dist/assets/{uk-BNd7CjVO.js → uk-BEfkaLtM.js} +2 -2
  91. package/dist/assets/{useAppFontEffects-BVoVpJYO.js → useAppFontEffects-Ck2PdQRx.js} +52 -52
  92. package/dist/assets/{useAssistantUIStore-Bp6TxG5E.js → useAssistantUIStore-CfaQV3ID.js} +1 -1
  93. package/dist/assets/useDesktopWindowControlsLayout-DxxOUZj1.js +1 -0
  94. package/dist/assets/useEffectiveDirectory-CNCQfN_x.js +1 -0
  95. package/dist/assets/{useFontPreferences-BFyBjtQ6.js → useFontPreferences-DeqW9nRx.js} +1 -1
  96. package/dist/assets/useMobileNavigationStore-BmVr5a5c.js +17 -0
  97. package/dist/assets/useUIStore-C6CE42oh.js +1 -0
  98. package/dist/assets/{useWorkerHighlightedLines-CPxG8Fya.js → useWorkerHighlightedLines-CN_RGaSw.js} +1 -1
  99. package/dist/assets/{vendor-effect-DV9F8PTZ.js → vendor-effect-X1Hqc7ba.js} +13 -13
  100. package/dist/assets/vendor-opencode-client-cQ47ywrT.js +23 -0
  101. package/dist/assets/{vendor-opencode-plugin-CgKz9Hcy.js → vendor-opencode-plugin-BmdTE4Te.js} +1 -1
  102. package/dist/assets/vendor-opencode-schema-DWT45VBX.js +1 -0
  103. package/dist/assets/vendor-solid-js-D98iXT7C.js +1 -0
  104. package/dist/assets/vendor-zod-DZzbCm1s.js +55 -0
  105. package/dist/assets/{zh-CN-BkTAEOZG.js → zh-CN-DipfA56P.js} +2 -2
  106. package/dist/assets/{zh-TW-x8SfMzfc.js → zh-TW-B7pXMVjt.js} +2 -2
  107. package/dist/index.html +18 -18
  108. package/dist/mini-chat.html +18 -18
  109. package/dist/mobile.html +18 -18
  110. package/package.json +6 -1
  111. package/server/index.js +2 -145
  112. package/server/lib/assistants/DOCUMENTATION.md +69 -11
  113. package/server/lib/assistants/cards.js +1 -1
  114. package/server/lib/assistants/channel-image.js +92 -0
  115. package/server/lib/assistants/channel-image.test.js +76 -0
  116. package/server/lib/assistants/channel-output-store.test.js +41 -0
  117. package/server/lib/assistants/channel-output.integration.test.js +114 -0
  118. package/server/lib/assistants/channel-output.js +90 -0
  119. package/server/lib/assistants/channel-output.test.js +79 -0
  120. package/server/lib/assistants/channels/DOCUMENTATION.md +329 -0
  121. package/server/lib/assistants/channels/PROTOCOLS.md +250 -0
  122. package/server/lib/assistants/channels/dingtalk-chat-adapter.js +645 -0
  123. package/server/lib/assistants/channels/dingtalk-chat-adapter.test.js +423 -0
  124. package/server/lib/assistants/channels/integration.test.js +44 -0
  125. package/server/lib/assistants/channels/routes.js +59 -0
  126. package/server/lib/assistants/channels/routes.test.js +139 -0
  127. package/server/lib/assistants/channels/runtime.js +958 -0
  128. package/server/lib/assistants/channels/runtime.test.js +897 -0
  129. package/server/lib/assistants/channels/sdk-adapters.js +383 -0
  130. package/server/lib/assistants/channels/sdk-adapters.test.js +384 -0
  131. package/server/lib/assistants/channels/store.js +249 -0
  132. package/server/lib/assistants/channels/store.test.js +296 -0
  133. package/server/lib/assistants/channels/transport.js +42 -0
  134. package/server/lib/assistants/channels/transport.test.js +23 -0
  135. package/server/lib/assistants/channels/wecom-chat-adapter.js +703 -0
  136. package/server/lib/assistants/channels/wecom-chat-adapter.test.js +130 -0
  137. package/server/lib/assistants/contact-store.js +9 -3
  138. package/server/lib/assistants/contact-store.test.js +27 -0
  139. package/server/lib/assistants/contact-tools.js +65 -75
  140. package/server/lib/assistants/contact-tools.test.js +114 -22
  141. package/server/lib/assistants/harness.js +79 -34
  142. package/server/lib/assistants/harness.test.js +52 -20
  143. package/server/lib/assistants/message-channel-origin.js +7 -0
  144. package/server/lib/assistants/resource-reference.integration.test.js +284 -0
  145. package/server/lib/assistants/routes.js +14 -4
  146. package/server/lib/assistants/service.js +116 -69
  147. package/server/lib/assistants/service.test.js +31 -17
  148. package/server/lib/assistants/weixin/DOCUMENTATION.md +121 -14
  149. package/server/lib/assistants/weixin/api.js +45 -1
  150. package/server/lib/assistants/weixin/api.test.js +28 -0
  151. package/server/lib/assistants/weixin/chat-adapter.js +113 -0
  152. package/server/lib/assistants/weixin/chat-adapter.test.js +62 -0
  153. package/server/lib/assistants/weixin/inbound.js +149 -0
  154. package/server/lib/assistants/weixin/inbound.test.js +141 -0
  155. package/server/lib/assistants/weixin/media.js +79 -0
  156. package/server/lib/assistants/weixin/media.test.js +66 -0
  157. package/server/lib/assistants/weixin/runtime.js +105 -74
  158. package/server/lib/assistants/weixin/runtime.test.js +192 -4
  159. package/server/lib/assistants/weixin/store.js +16 -8
  160. package/server/lib/assistants/weixin/store.test.js +93 -0
  161. package/server/lib/assistants/weixin/toon.js +49 -0
  162. package/server/lib/assistants/weixin/toon.test.js +25 -0
  163. package/server/lib/assistants/yuri-project.http.test.js +9 -3
  164. package/server/lib/github/DOCUMENTATION.md +9 -8
  165. package/server/lib/llm/bridge-plugin.bundle.js +188 -188
  166. package/server/lib/notifications/DOCUMENTATION.md +6 -0
  167. package/server/lib/notifications/runtime.js +26 -15
  168. package/server/lib/notifications/runtime.test.js +14 -13
  169. package/server/lib/opencode/DOCUMENTATION.md +10 -1
  170. package/server/lib/opencode/auth.d.ts +6 -2
  171. package/server/lib/opencode/core-routes.js +0 -1
  172. package/server/lib/opencode/feature-routes-runtime.js +0 -24
  173. package/server/lib/opencode/location-release.d.ts +5 -1
  174. package/server/lib/opencode/managed-capabilities/scheduled-task.js +1 -1
  175. package/server/lib/opencode/managed-capabilities-runtime.test.js +1 -1
  176. package/server/lib/opencode/native-goal.js +15 -0
  177. package/server/lib/opencode/native-goal.test.js +17 -0
  178. package/server/lib/opencode/settings-helpers.js +0 -6
  179. package/server/lib/opencode/shutdown-runtime.js +0 -2
  180. package/server/lib/projects/project-config.js +3 -6
  181. package/server/lib/scheduled-tasks/DOCUMENTATION.md +10 -35
  182. package/server/lib/scheduled-tasks/managed-tool-route.js +1 -30
  183. package/server/lib/scheduled-tasks/routes.js +0 -26
  184. package/server/lib/scheduled-tasks/runtime.js +33 -257
  185. package/server/lib/scheduled-tasks/runtime.test.js +24 -65
  186. package/server/lib/session-metadata/DOCUMENTATION.md +9 -12
  187. package/server/lib/session-metadata/routes.js +4 -38
  188. package/server/lib/session-metadata/routes.test.js +2 -2
  189. package/dist/assets/AssistantContactStatus-CWq-PDz6.js +0 -3
  190. package/dist/assets/AssistantView-Br1iETTs.js +0 -1
  191. package/dist/assets/MarkdownRenderer-BlGxjOei.js +0 -2
  192. package/dist/assets/MobileTabPageHeader-DQRqAAEf.js +0 -2
  193. package/dist/assets/context-menu-DpbkRkk1.js +0 -1
  194. package/dist/assets/device-BjRYYXNT.js +0 -2
  195. package/dist/assets/host-FR_grJxM.js +0 -1
  196. package/dist/assets/insertionBoundaries-CZz7TWJv.js +0 -1
  197. package/dist/assets/main-Bp9HHqTr.js +0 -2
  198. package/dist/assets/main-DOwAfmxJ.js +0 -169
  199. package/dist/assets/miniChat-BJDgCrfF.js +0 -2
  200. package/dist/assets/mobile-GM9931J_.js +0 -2
  201. package/dist/assets/projectMeta-31PobC-M.js +0 -1
  202. package/dist/assets/react-B9v0P7kT.js +0 -1
  203. package/dist/assets/readiness-CYNnsekT.js +0 -1
  204. package/dist/assets/renderElectronMiniChatApp-N2r999Bf.js +0 -2
  205. package/dist/assets/renderMobileApp-CU1ec6Ak.js +0 -28
  206. package/dist/assets/runtime-fetch-D4ja813o.js +0 -1
  207. package/dist/assets/runtimeConfig-Db7yfo6L.js +0 -2
  208. package/dist/assets/runtimeEndpointReset-DO5WVetV.js +0 -149
  209. package/dist/assets/scheduledTaskNavigation-Bsrhv3Ow.js +0 -1
  210. package/dist/assets/sessionLookup-DRVy7LM1.js +0 -1
  211. package/dist/assets/speechSettingsQueries-DU25rmGc.js +0 -4
  212. package/dist/assets/src-Bckdo2XS.css +0 -2
  213. package/dist/assets/types-BqFQhQTt.js +0 -2
  214. package/dist/assets/useDesktopWindowControlsLayout-CYx1LNO5.js +0 -1
  215. package/dist/assets/useEffectiveDirectory-D8FFE5Yn.js +0 -1
  216. package/dist/assets/useMobileNavigationStore-BHMFeMjo.js +0 -23
  217. package/dist/assets/useUIStore-BbYD420L.js +0 -1
  218. package/dist/assets/vendor-opencode-client-UL_TecvQ.js +0 -12
  219. package/dist/assets/vendor-solid-js-0T254UHG.js +0 -1
  220. package/dist/assets/vendor-zod-Dzk5kdUU.js +0 -39
  221. package/server/lib/session-goal/DOCUMENTATION.md +0 -371
  222. package/server/lib/session-goal/capability.js +0 -57
  223. package/server/lib/session-goal/capability.test.js +0 -33
  224. package/server/lib/session-goal/objectives.js +0 -61
  225. package/server/lib/session-goal/routes.js +0 -274
  226. package/server/lib/session-goal/routes.test.js +0 -211
  227. package/server/lib/session-goal/runtime.js +0 -2452
  228. package/server/lib/session-goal/runtime.test.js +0 -2125
@@ -0,0 +1,897 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { createRequire } from 'node:module';
5
+ import { afterEach, describe, expect, it, vi } from 'vitest';
6
+ import { createAssistantChannelsRuntime } from './runtime.js';
7
+ import { createAssistantChannelStore } from './store.js';
8
+ import { createAssistantsService } from '../service.js';
9
+
10
+ const Database = createRequire(import.meta.url)('better-sqlite3');
11
+
12
+ const closers = [];
13
+ afterEach(async () => { while (closers.length) await closers.pop()(); });
14
+ const root = () => {
15
+ const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'yuri-channels-'));
16
+ closers.push(() => fs.rmSync(directory, { recursive: true, force: true }));
17
+ return directory;
18
+ };
19
+
20
+ const abortable = (signal) => new Promise((_, reject) => {
21
+ const error = Object.assign(new Error('cancelled'), { code: 'cancelled' });
22
+ if (signal.aborted) { reject(error); return; }
23
+ signal.addEventListener('abort', () => reject(error), { once: true });
24
+ });
25
+
26
+ function fixture({ directory = root(), service: externalService, env = {}, intervalMs = 10, autoReady = true, includeDingtalk = false, discoveryTimeoutMs } = {}) {
27
+ const pages = new Map();
28
+ const seen = new Set();
29
+ const service = externalService ?? {
30
+ snapshot: () => ({ assistants: [...seen].map((id) => ({ id, name: id })) }),
31
+ channelPage: vi.fn((id, { afterOrdinal = 0, generation = null, tipOnly = false } = {}) => {
32
+ if (id === 'missing') throw Object.assign(new Error('not_found'), { code: 'not_found' });
33
+ seen.add(id);
34
+ const page = pages.get(id) ?? { generation: 0, messages: [] };
35
+ const after = generation === null || generation === page.generation ? afterOrdinal : 0;
36
+ const messages = tipOnly ? [] : page.messages.filter((message) => message.ordinal > after).slice(0, 50);
37
+ return {
38
+ generation: page.generation,
39
+ tipOrdinal: page.messages.at(-1)?.ordinal ?? 0,
40
+ ordinal: messages.at(-1)?.ordinal ?? after,
41
+ messages,
42
+ };
43
+ }),
44
+ send: vi.fn(async () => ({ admitted: true })),
45
+ };
46
+ const connections = [];
47
+ const adapter = {
48
+ connect: vi.fn(async (input) => {
49
+ const connection = { ...input };
50
+ connections.push(connection);
51
+ if (autoReady) input.onReady();
52
+ await abortable(input.signal);
53
+ }),
54
+ send: vi.fn(async () => {}),
55
+ };
56
+ const runtime = createAssistantChannelsRuntime({
57
+ directory,
58
+ service,
59
+ adapters: { wecom: adapter, feishu: adapter, ...(includeDingtalk ? { dingtalk: adapter } : {}) },
60
+ env,
61
+ intervalMs,
62
+ discoveryTimeoutMs,
63
+ });
64
+ closers.push(() => runtime.close());
65
+ const save = (assistantID = 'bot', provider = 'wecom', input = {}) => runtime.save(assistantID, provider, {
66
+ clientID: 'client', clientSecret: 'secret', ownerID: 'owner', language: 'zh-CN', ...input,
67
+ });
68
+ const seedLegacyUnrestricted = () => {
69
+ const store = createAssistantChannelStore(directory);
70
+ try {
71
+ store.bind({ assistant_id: 'bot', provider: 'wecom', client_id: 'client', client_secret: 'secret', owner_id: '', language: 'zh-CN', generation: 0, ordinal: 0, updated_at: 1 });
72
+ } finally { store.close(); }
73
+ };
74
+ const connected = async (assistantID = 'bot', provider = 'wecom') => {
75
+ await vi.waitFor(
76
+ () => expect(runtime.status(assistantID, provider).status).toBe('connected'),
77
+ { interval: 10, timeout: 3000 },
78
+ );
79
+ return connections.at(-1);
80
+ };
81
+ const reply = (assistantID = 'bot', text = 'reply', ordinal = 1, generation = 0) => pages.set(assistantID, {
82
+ generation,
83
+ messages: [{ ordinal, messageID: `reply-${ordinal}`, text, cards: [], status: 'complete' }],
84
+ });
85
+ return { directory, runtime, service, adapter, connections, pages, save, connected, reply, seedLegacyUnrestricted };
86
+ }
87
+
88
+ describe('enterprise channel runtime', () => {
89
+ it.each(['wecom', 'feishu', 'dingtalk'])('routes text and generated images through %s without broadcasting another channel output', async (provider) => {
90
+ const f = fixture({ includeDingtalk: true });
91
+ const buffer = Buffer.from('image');
92
+ f.service.prepareChannelImage = vi.fn(async () => ({ attachmentID: 'att_generated' }));
93
+ f.service.getAssistantContactAttachment = vi.fn(async () => ({ buffer, mime: 'image/png', filename: 'generated.png' }));
94
+ await f.save('bot', provider);
95
+ const connection = await f.connected('bot', provider);
96
+ await connection.onMessage({ id: 'image-turn', senderID: 'owner', chatType: 'private', text: 'draw' });
97
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledOnce());
98
+ const turnID = f.service.send.mock.calls[0][1].messageID;
99
+ f.pages.set('bot', { generation: 0, messages: [
100
+ { ordinal: 1, messageID: 'other-image', turnID: 'weixin:not-this-channel', text: '![private](/private.png)', cards: [], status: 'complete' },
101
+ { ordinal: 2, messageID: 'own-image', turnID, text: 'Here\n\n![generated](/generated.png)\n\nDone', cards: [], status: 'complete' },
102
+ ] });
103
+ await vi.waitFor(() => expect(f.adapter.send).toHaveBeenCalledTimes(3));
104
+ expect(f.adapter.send.mock.calls.map(([part]) => part.image ? 'image' : part.text)).toEqual(['Here', 'image', 'Done']);
105
+ expect(f.adapter.send.mock.calls[1][0]).toMatchObject({ image: { buffer }, target: { userID: 'owner' } });
106
+ expect(f.service.prepareChannelImage).toHaveBeenCalledOnce();
107
+ const db = new Database(path.join(f.directory, 'channel.sqlite'));
108
+ try { expect(db.prepare("SELECT text,image FROM outbox WHERE state='sent'").all()).toEqual(Array(3).fill({ text: '', image: '' })); }
109
+ finally { db.close(); }
110
+ });
111
+
112
+ it('does not deliver an image prepared across a transcript reset', async () => {
113
+ const f = fixture();
114
+ let release;
115
+ f.service.prepareChannelImage = vi.fn(() => new Promise((resolve) => { release = resolve; }));
116
+ await f.save();
117
+ await f.connected();
118
+ f.reply('bot', '![generated](/generated.png)');
119
+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));
120
+ f.pages.set('bot', { generation: 1, messages: [] });
121
+ release({ attachmentID: 'old-image' });
122
+ await new Promise((resolve) => setTimeout(resolve, 60));
123
+ expect(f.adapter.send).not.toHaveBeenCalled();
124
+ });
125
+ it.each(['wecom', 'feishu', 'dingtalk'])('discovers %s from a private message without saving credentials or executing tasks', async (provider) => {
126
+ const f = fixture({ includeDingtalk: true });
127
+ const probe = f.runtime.discover('bot', provider, { clientID: 'client', clientSecret: 'secret' });
128
+ await vi.waitFor(() => expect(f.connections).toHaveLength(1));
129
+ const connection = f.connections[0];
130
+ expect(f.runtime.status('bot', provider).configured).toBe(false);
131
+ expect(await connection.onMessage({ senderID: 'group-user', chatType: 'group' })).toBe(false);
132
+ expect(await connection.onMessage({ senderID: '', chatType: 'private' })).toBe(false);
133
+ expect(await connection.onMessage({ senderID: 'user_1', chatType: 'private', text: 'detect me' })).toBe(true);
134
+ await expect(probe).resolves.toEqual({ ownerID: 'user_1' });
135
+ expect(connection.signal.aborted).toBe(true);
136
+ expect(f.service.send).not.toHaveBeenCalled();
137
+ expect(f.runtime.status('bot', provider).configured).toBe(false);
138
+ await f.save('bot', provider, { ownerID: 'user_1' });
139
+ expect(f.runtime.status('bot', provider)).toMatchObject({ configured: true, ownerID: 'user_1' });
140
+ });
141
+
142
+ it('rejects empty owner IDs at the save boundary, including existing bindings', async () => {
143
+ const f = fixture();
144
+ await expect(f.save('bot', 'wecom', { ownerID: '' })).rejects.toMatchObject({ code: 'owner_required' });
145
+ await f.save();
146
+ await expect(f.save('bot', 'wecom', { ownerID: undefined })).rejects.toMatchObject({ code: 'owner_required' });
147
+ expect(f.runtime.status('bot', 'wecom').ownerID).toBe('owner');
148
+ });
149
+
150
+ it('cancels discovery and resumes the untouched saved connection, without reusing secrets across accounts', async () => {
151
+ const f = fixture();
152
+ await f.save();
153
+ const original = await f.connected();
154
+ const controller = new AbortController();
155
+ const probe = f.runtime.discover('bot', 'wecom', { clientID: 'client' }, { signal: controller.signal });
156
+ const result = expect(probe).rejects.toMatchObject({ code: 'cancelled' });
157
+ await vi.waitFor(() => expect(f.connections).toHaveLength(2));
158
+ expect(original.signal.aborted).toBe(true);
159
+ expect(f.connections[1].config.clientSecret).toBe('secret');
160
+ controller.abort();
161
+ await result;
162
+ await vi.waitFor(() => expect(f.connections).toHaveLength(3));
163
+ expect(f.connections[2].signal.aborted).toBe(false);
164
+ expect(f.runtime.status('bot', 'wecom')).toMatchObject({ clientID: 'client', ownerID: 'owner', configured: true });
165
+ await expect(f.runtime.discover('bot', 'wecom', { clientID: 'new-account' })).rejects.toMatchObject({ code: 'validation_error' });
166
+ });
167
+
168
+ it('expires a probe and cleans up its lane so it can be retried', async () => {
169
+ const f = fixture({ discoveryTimeoutMs: 50 });
170
+ await expect(f.runtime.discover('bot', 'wecom', { clientID: 'client', clientSecret: 'secret' })).rejects.toMatchObject({ code: 'discovery_timeout' });
171
+ expect(f.connections[0].signal.aborted).toBe(true);
172
+ expect(f.runtime.status('bot', 'wecom').configured).toBe(false);
173
+ await f.save();
174
+ });
175
+
176
+ it('fences competing discovery/save lanes and does not take an account from another Bot', async () => {
177
+ const f = fixture();
178
+ const controller = new AbortController();
179
+ const input = { clientID: 'client', clientSecret: 'secret' };
180
+ const probe = f.runtime.discover('bot', 'wecom', input, { signal: controller.signal });
181
+ const result = expect(probe).rejects.toMatchObject({ code: 'cancelled' });
182
+ await vi.waitFor(() => expect(f.connections).toHaveLength(1));
183
+ await expect(f.runtime.discover('other', 'wecom', input)).rejects.toMatchObject({ code: 'account_in_use' });
184
+ await expect(f.save('other')).rejects.toMatchObject({ code: 'account_in_use' });
185
+ await expect(f.save()).rejects.toMatchObject({ code: 'channel_in_use' });
186
+ controller.abort();
187
+ await result;
188
+ await f.save();
189
+ await expect(f.runtime.discover('other', 'wecom', input)).rejects.toMatchObject({ code: 'account_in_use' });
190
+ });
191
+
192
+ it('redacts discovery authentication failures and cancels an unsaved probe on shutdown', async () => {
193
+ const f = fixture();
194
+ const probe = f.runtime.discover('bot', 'wecom', { clientID: 'client', clientSecret: 'secret' });
195
+ const failed = expect(probe).rejects.toMatchObject({ code: 'auth_failed', message: 'auth_failed' });
196
+ await vi.waitFor(() => expect(f.connections).toHaveLength(1));
197
+ f.connections[0].onError(Object.assign(new Error('private upstream payload'), { code: 'auth_failed' }));
198
+ await failed;
199
+ const next = f.runtime.discover('bot', 'wecom', { clientID: 'client', clientSecret: 'secret' });
200
+ const cancelled = expect(next).rejects.toMatchObject({ code: 'cancelled' });
201
+ await vi.waitFor(() => expect(f.connections).toHaveLength(2));
202
+ await f.runtime.close();
203
+ await cancelled;
204
+ expect(f.connections[1].signal.aborted).toBe(true);
205
+ });
206
+
207
+ it('cancels discovery when its Bot is forgotten, including probes with no saved binding', async () => {
208
+ const f = fixture();
209
+ const probe = f.runtime.discover('bot', 'wecom', { clientID: 'client', clientSecret: 'secret' });
210
+ const cancelled = expect(probe).rejects.toMatchObject({ code: 'cancelled' });
211
+ await vi.waitFor(() => expect(f.connections).toHaveLength(1));
212
+ await f.runtime.forget('bot');
213
+ await cancelled;
214
+ expect(f.connections[0].signal.aborted).toBe(true);
215
+ expect(f.runtime.status('bot', 'wecom').configured).toBe(false);
216
+ });
217
+
218
+ it('replies only on the originating channel and to its original sender; source-less output is pushed', async () => {
219
+ const f = fixture();
220
+ f.seedLegacyUnrestricted();
221
+ const wecom = await f.connected('bot', 'wecom');
222
+ await f.save('bot', 'feishu');
223
+ const feishu = await f.connected('bot', 'feishu');
224
+ await wecom.onMessage({ id: 'alice-message', senderID: 'alice', chatType: 'private', text: 'a' });
225
+ await wecom.onMessage({ id: 'bob-message', senderID: 'bob', chatType: 'private', text: 'b' });
226
+ await feishu.onMessage({ id: 'feishu-message', senderID: 'owner', chatType: 'private', text: 'f' });
227
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(3));
228
+ const turnFor = (text) => f.service.send.mock.calls.find(([, input]) => input.parts.some((part) => part.text === text))[1].messageID;
229
+ const aliceTurn = turnFor('a');
230
+ f.pages.set('bot', { generation: 0, messages: [
231
+ { ordinal: 1, messageID: 'r-a', turnID: aliceTurn, text: 'alice reply', cards: [], status: 'complete' },
232
+ { ordinal: 2, messageID: 'r-b', turnID: turnFor('b'), text: 'bob reply', cards: [], status: 'complete' },
233
+ { ordinal: 3, messageID: 'r-f', turnID: turnFor('f'), text: 'feishu reply', cards: [], status: 'complete' },
234
+ { ordinal: 4, messageID: 'r-w', turnID: 'weixin:other-turn', text: 'wechat only', cards: [], status: 'complete' },
235
+ { ordinal: 5, messageID: 'push', turnID: 'app-turn', text: 'proactive push', cards: [], status: 'complete' },
236
+ ] });
237
+ await vi.waitFor(() => expect(f.adapter.send).toHaveBeenCalledTimes(5));
238
+ const deliveries = f.adapter.send.mock.calls.map(([input]) => input);
239
+ expect(deliveries.filter((input) => input.config.clientID === 'client' && input.config.ownerID === '').map((input) => [input.text, input.target.userID]))
240
+ .toEqual([['alice reply', 'alice'], ['bob reply', 'bob'], ['proactive push', 'bob']]);
241
+ expect(deliveries.filter((input) => input.config.ownerID === 'owner').map((input) => input.text))
242
+ .toEqual(['feishu reply', 'proactive push']);
243
+ for (const [, input] of f.service.send.mock.calls) f.runtime.onTurnEvent({ type: 'yuri:contact-turn-end', properties: { turnID: input.messageID } });
244
+ await f.runtime.close();
245
+ const restarted = fixture({ directory: f.directory });
246
+ restarted.pages.set('bot', { generation: 0, messages: [
247
+ { ordinal: 6, messageID: 'late-r-a', turnID: aliceTurn, text: 'late alice reply', cards: [], status: 'complete' },
248
+ ] });
249
+ await vi.waitFor(() => expect(restarted.adapter.send).toHaveBeenCalledOnce());
250
+ expect(restarted.adapter.send.mock.calls[0][0]).toMatchObject({ text: 'late alice reply', target: { userID: 'alice' } });
251
+ });
252
+
253
+ it.each(['wecom', 'feishu', 'dingtalk'])('keeps ordinary %s text as exactly one original text part', async (provider) => {
254
+ const f = fixture({ includeDingtalk: true });
255
+ await f.save('bot', provider);
256
+ const connection = await f.connected('bot', provider);
257
+ await connection.onMessage({ id: 'plain', senderID: 'owner', chatType: 'private', text: 'halo', metadata: { platform: provider, chatType: 'private' } });
258
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledOnce());
259
+ expect(f.service.send.mock.calls[0][1].parts).toEqual([{ type: 'text', text: 'halo' }]);
260
+ });
261
+
262
+ it('retains actual media metadata without leaking internal routing labels', async () => {
263
+ const f = fixture();
264
+ await f.save();
265
+ const connection = await f.connected();
266
+ await connection.onMessage({ id: 'image', senderID: 'owner', chatType: 'private', text: '', metadata: { platform: 'wecom', chatType: 'private', notDownloaded: true, resources: [{ type: 'image' }] } });
267
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledOnce());
268
+ const parts = f.service.send.mock.calls[0][1].parts;
269
+ expect(parts).toHaveLength(1);
270
+ expect(parts[0].text).toContain('notDownloaded: true');
271
+ expect(parts[0].text).toContain('image');
272
+ expect(parts[0].text).not.toMatch(/platform:|chatType:/);
273
+ });
274
+
275
+ it.each(['wecom', 'feishu'])('moves %s to the selected Bot without forwarding old work or moving other providers', async (provider) => {
276
+ const f = fixture();
277
+ await f.save('bot', provider);
278
+ const previous = await f.connected('bot', provider);
279
+ await previous.onMessage({ id: 'one', senderID: 'owner', chatType: 'private', text: 'old request' });
280
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledOnce());
281
+ const otherProvider = provider === 'wecom' ? 'feishu' : 'wecom';
282
+ await f.save('bot', otherProvider);
283
+ const source = f.runtime.status('other', provider).transferSources[0];
284
+ expect(source).toMatchObject({ assistantID: 'bot', name: 'bot', clientID: 'client' });
285
+ expect(JSON.stringify(source)).not.toContain('secret');
286
+ await expect(f.runtime.transfer('other', provider, { sourceAssistantID: 'bot', revision: 'stale' })).rejects.toMatchObject({ code: 'binding_changed' });
287
+ expect(previous.signal.aborted).toBe(false);
288
+ f.reply('other', 'existing target history', 10);
289
+ await f.runtime.transfer('other', provider, { sourceAssistantID: 'bot', revision: source.revision });
290
+ expect(previous.signal.aborted).toBe(true);
291
+ expect(f.runtime.status('bot', provider).configured).toBe(false);
292
+ expect(f.runtime.status('bot', otherProvider).configured).toBe(true);
293
+ const moved = await f.connected('other', provider);
294
+ await moved.onMessage({ id: 'one', senderID: 'owner', chatType: 'private', text: 'replay' });
295
+ expect(f.service.send).toHaveBeenCalledOnce();
296
+ await moved.onMessage({ id: 'two', senderID: 'owner', chatType: 'private', text: 'new request' });
297
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(2));
298
+ expect(f.service.send.mock.calls[1][0]).toBe('other');
299
+ expect(f.adapter.send).not.toHaveBeenCalled();
300
+ });
301
+
302
+ it('resumes the source binding when the target disappears while a transfer drains', async () => {
303
+ const f = fixture();
304
+ await f.save();
305
+ const connection = await f.connected();
306
+ const source = f.runtime.status('other', 'wecom').transferSources[0];
307
+ const original = f.service.channelPage.getMockImplementation();
308
+ let deleted = false;
309
+ f.service.channelPage.mockImplementation((id, options) => {
310
+ if (id === 'other' && deleted) throw Object.assign(new Error('not_found'), { code: 'not_found' });
311
+ return original(id, options);
312
+ });
313
+ connection.signal.addEventListener('abort', () => { deleted = true; }, { once: true });
314
+ await expect(f.runtime.transfer('other', 'wecom', { sourceAssistantID: 'bot', revision: source.revision })).rejects.toMatchObject({ code: 'not_found' });
315
+ await vi.waitFor(() => expect(f.connections.length).toBeGreaterThan(1));
316
+ const resumed = await f.connected();
317
+ expect(resumed.signal.aborted).toBe(false);
318
+ expect(f.runtime.status('bot', 'wecom').configured).toBe(true);
319
+ });
320
+
321
+ it('preserves legacy unrestricted bindings until explicitly restricted by a save', async () => {
322
+ const f = fixture();
323
+ f.seedLegacyUnrestricted();
324
+ const connection = await f.connected();
325
+ f.reply('bot', 'no recipient yet', 1);
326
+ await vi.waitFor(() => expect(f.service.channelPage).toHaveBeenCalled(), { interval: 10 });
327
+ await new Promise((resolve) => setTimeout(resolve, 40));
328
+ expect(f.adapter.send).not.toHaveBeenCalled();
329
+ await connection.onMessage({ id: 'same-platform-id', senderID: 'alice', chatType: 'private', text: 'hello', target: { userID: 'forged' } });
330
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1), { interval: 10 });
331
+ f.reply('bot', 'reply to alice', 2);
332
+ await vi.waitFor(() => expect(f.adapter.send).toHaveBeenCalledTimes(1), { interval: 10 });
333
+ expect(f.adapter.send.mock.calls[0][0]).toMatchObject({ target: { userID: 'alice' } });
334
+ await connection.onMessage({ id: 'same-platform-id', senderID: 'bob', chatType: 'private', text: 'hello again' });
335
+ await connection.onMessage({ id: 'group', senderID: 'bob', chatType: 'group', text: 'ignored' });
336
+ await connection.onMessage({ id: 'missing-sender', senderID: '', chatType: 'private', text: 'ignored' });
337
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(2), { interval: 10 });
338
+ f.reply('bot', 'reply to bob', 3);
339
+ await vi.waitFor(() => expect(f.adapter.send).toHaveBeenCalledTimes(2), { interval: 10 });
340
+ expect(f.adapter.send.mock.calls[1][0]).toMatchObject({ target: { userID: 'bob' } });
341
+ expect(f.service.send.mock.calls[0][1].messageID).not.toBe(f.service.send.mock.calls[1][1].messageID);
342
+ await f.save('bot', 'wecom', { ownerID: 'alice' });
343
+ const restricted = await f.connected();
344
+ await restricted.onMessage({ id: 'blocked', senderID: 'bob', chatType: 'private', text: 'ignored' });
345
+ expect(f.service.send).toHaveBeenCalledTimes(2);
346
+ });
347
+
348
+ it.each([
349
+ { NODE_ENV: 'development' },
350
+ { YURI_ELECTRON_DEV: '1' },
351
+ { YURI_ELECTRON_DEV: 'true' },
352
+ { NODE_ENV: 'production', YURI_CHANNELS_ENABLED: '0' },
353
+ { YURI_CHANNELS_ENABLED: 'false' },
354
+ { YURI_CHANNELS_ENABLED: 'invalid' },
355
+ ])('disables startup and every mutation without opening private storage for %j', async (env) => {
356
+ const directory = path.join(root(), 'must-not-open');
357
+ const adapter = { connect: vi.fn(), send: vi.fn() };
358
+ const service = { channelPage: vi.fn(), send: vi.fn() };
359
+ const runtime = createAssistantChannelsRuntime({ directory, service, adapters: { wecom: adapter }, env });
360
+ closers.push(() => runtime.close());
361
+ expect(runtime.status('bot', 'wecom')).toEqual({
362
+ provider: 'wecom', status: 'disabled', error: null, configured: false,
363
+ hasSecret: false, transport: 'websocket',
364
+ });
365
+ await expect(runtime.save('bot', 'wecom', {})).rejects.toMatchObject({ code: 'channel_disabled' });
366
+ await expect(runtime.retry('bot', 'wecom')).rejects.toMatchObject({ code: 'channel_disabled' });
367
+ await expect(runtime.disconnect('bot', 'wecom')).rejects.toMatchObject({ code: 'channel_disabled' });
368
+ runtime.onTurnEvent({ type: 'yuri:contact-turn-end', properties: { turnID: 'turn' } });
369
+ await runtime.forget('bot');
370
+ await runtime.close();
371
+ expect(fs.existsSync(directory)).toBe(false);
372
+ expect(adapter.connect).not.toHaveBeenCalled();
373
+ expect(adapter.send).not.toHaveBeenCalled();
374
+ expect(service.channelPage).not.toHaveBeenCalled();
375
+ expect(service.send).not.toHaveBeenCalled();
376
+ });
377
+
378
+ it.each(['1', 'true'])('requires an explicit %s opt-in to run channels in development', async (enabled) => {
379
+ const f = fixture({ env: { NODE_ENV: 'development', YURI_ELECTRON_DEV: '1', YURI_CHANNELS_ENABLED: enabled } });
380
+ await f.save();
381
+ await f.connected();
382
+ expect(f.connections[0].config).toEqual({
383
+ clientID: 'client', clientSecret: 'secret', ownerID: 'owner', language: 'zh-CN',
384
+ });
385
+ });
386
+
387
+ it('requires a secret on first save, keeps the old one on blank update and never serializes it', async () => {
388
+ const f = fixture();
389
+ await expect(f.save('bot', 'wecom', { clientSecret: '' }))
390
+ .rejects.toMatchObject({ code: 'validation_error' });
391
+ const saved = await f.save();
392
+ expect(saved).toMatchObject({
393
+ provider: 'wecom', configured: true, clientID: 'client', ownerID: 'owner',
394
+ hasSecret: true, transport: 'websocket',
395
+ });
396
+ expect(JSON.stringify(saved)).not.toContain('secret');
397
+ const first = await f.connected();
398
+ expect(first.config.clientSecret).toBe('secret');
399
+ const updated = await f.save('bot', 'wecom', { clientSecret: '' });
400
+ expect(updated).toMatchObject({ configured: true, hasSecret: true, clientID: 'client' });
401
+ await vi.waitFor(() => expect(f.connections).toHaveLength(2), { interval: 10, timeout: 3000 });
402
+ expect(f.connections[1].config.clientSecret).toBe('secret');
403
+ });
404
+
405
+ it('rejects unsupported providers and invalid provider names without opening a connection', async () => {
406
+ const f = fixture();
407
+ expect(() => f.runtime.status('bot', 'not a provider')).toThrow('validation_error');
408
+ await expect(f.save('bot', 'dingtalk')).rejects.toMatchObject({ code: 'unsupported_provider' });
409
+ await expect(f.save('missing', 'wecom')).rejects.toMatchObject({ code: 'not_found' });
410
+ expect(f.connections).toHaveLength(0);
411
+ });
412
+
413
+ it('keeps one provider account assigned to one Bot', async () => {
414
+ const f = fixture();
415
+ await f.save('bot');
416
+ await expect(f.save('other', 'wecom', { clientID: 'client', clientSecret: 'other' }))
417
+ .rejects.toMatchObject({ code: 'account_in_use' });
418
+ // Another provider may reuse the same account string.
419
+ await expect(f.save('other', 'feishu', { clientID: 'client', clientSecret: 'other' })).resolves.toBeTruthy();
420
+ });
421
+
422
+ it('admits only one explicit private owner once, projects metadata and keeps targets out of context', async () => {
423
+ const f = fixture();
424
+ await f.save();
425
+ const connection = await f.connected();
426
+ const message = {
427
+ id: 'platform-1',
428
+ senderID: 'owner',
429
+ chatType: 'private',
430
+ text: 'hello',
431
+ metadata: {
432
+ chatName: 'Team',
433
+ note: 'see https://private.example/media',
434
+ token: 'private-token',
435
+ url: 'https://private.example/hook',
436
+ media: { full_url: 'https://cdn.example/file' },
437
+ },
438
+ target: { sessionWebhook: 'https://private.example/reply' },
439
+ };
440
+ await connection.onMessage(message);
441
+ await connection.onMessage(message);
442
+ await connection.onMessage({ ...message, id: 'platform-2', senderID: 'stranger' });
443
+ await connection.onMessage({ ...message, id: 'platform-3', chatType: 'group' });
444
+ await connection.onMessage({ ...message, id: undefined });
445
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1), { interval: 10 });
446
+ const parts = f.service.send.mock.calls[0][1].parts;
447
+ expect(parts[0]).toEqual({ type: 'text', text: 'hello' });
448
+ expect(parts[1].text).toContain('chatName');
449
+ expect(parts[1].text).toContain('[link omitted]');
450
+ const serialized = JSON.stringify(parts);
451
+ expect(serialized).not.toContain('private-token');
452
+ expect(serialized).not.toContain('sessionWebhook');
453
+ expect(serialized).not.toContain('private.example');
454
+ expect(JSON.stringify(f.runtime.status('bot', 'wecom'))).not.toContain('secret');
455
+
456
+ f.reply('bot', 'answer', 1);
457
+ await vi.waitFor(() => expect(f.adapter.send).toHaveBeenCalledTimes(1), { interval: 10 });
458
+ expect(f.adapter.send.mock.calls[0][0]).toMatchObject({
459
+ text: 'answer',
460
+ target: { sessionWebhook: 'https://private.example/reply' },
461
+ config: { clientID: 'client', ownerID: 'owner', language: 'zh-CN' },
462
+ });
463
+ expect(f.adapter.send.mock.calls[0][0].id).toMatch(/^yuri_/);
464
+ });
465
+
466
+ it('starts from the current contact tip so pre-binding history is not delivered', async () => {
467
+ const f = fixture();
468
+ f.pages.set('bot', {
469
+ generation: 0,
470
+ messages: [{ ordinal: 50, messageID: 'old', text: 'old history', cards: [], status: 'complete' }],
471
+ });
472
+ await f.save();
473
+ await f.connected();
474
+ await new Promise((resolve) => setTimeout(resolve, 80));
475
+ expect(f.adapter.send).not.toHaveBeenCalled();
476
+ });
477
+
478
+ it('drops queued output from a previous transcript generation', async () => {
479
+ const f = fixture();
480
+ await f.save();
481
+ await f.connected();
482
+ let finish;
483
+ f.adapter.send.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));
484
+ f.reply('bot', 'old generation', 1, 0);
485
+ await vi.waitFor(() => expect(f.adapter.send).toHaveBeenCalledTimes(1), { interval: 10 });
486
+ f.pages.set('bot', {
487
+ generation: 1,
488
+ messages: [{ ordinal: 1, messageID: 'new', text: 'after reset', cards: [], status: 'complete' }],
489
+ });
490
+ finish();
491
+ await vi.waitFor(() => expect(f.adapter.send).toHaveBeenCalledTimes(2), { interval: 10 });
492
+ expect(f.adapter.send.mock.calls[1][0].text).toBe('after reset');
493
+ await new Promise((resolve) => setTimeout(resolve, 60));
494
+ expect(f.adapter.send.mock.calls.filter((call) => call[0].text === 'old generation')).toHaveLength(1);
495
+ });
496
+
497
+ it('never automatically resends an uncertain delivery; retry only reconnects and keeps it visible', async () => {
498
+ const f = fixture();
499
+ f.adapter.send.mockRejectedValueOnce(Object.assign(new Error('timeout'), { ambiguous: true }));
500
+ await f.save();
501
+ await f.connected();
502
+ f.reply('bot', 'possibly delivered', 1);
503
+ await vi.waitFor(() => expect(f.runtime.status('bot', 'wecom').error).toBe('delivery_unknown'), { interval: 10 });
504
+ const deliveryID = f.adapter.send.mock.calls[0][0].id;
505
+ const before = f.connections.length;
506
+ const retried = await f.runtime.retry('bot', 'wecom');
507
+ expect(retried).toMatchObject({ error: 'delivery_unknown' });
508
+ expect(['reconnecting', 'connected']).toContain(retried.status);
509
+ await vi.waitFor(() => expect(f.connections.length).toBe(before + 1), { interval: 10, timeout: 3000 });
510
+ await vi.waitFor(() => expect(f.runtime.status('bot', 'wecom')).toMatchObject({
511
+ status: 'connected', error: 'delivery_unknown',
512
+ }), { interval: 10, timeout: 3000 });
513
+ await new Promise((resolve) => setTimeout(resolve, 80));
514
+ expect(f.adapter.send).toHaveBeenCalledTimes(1);
515
+ expect(f.adapter.send.mock.calls[0][0].id).toBe(deliveryID);
516
+ });
517
+
518
+ it.each(['wecom', 'feishu', 'dingtalk'])('a failed %s notification does not block later text or Bot input', async (provider) => {
519
+ const f = fixture({ includeDingtalk: true });
520
+ f.adapter.send.mockImplementation(async ({ text }) => {
521
+ if (text === 'Article notes') throw Object.assign(new Error('rejected'), { code: 'validation_error' });
522
+ });
523
+ await f.save('bot', provider);
524
+ const connection = await f.connected('bot', provider);
525
+ f.pages.set('bot', { generation: 0, messages: [
526
+ { ordinal: 1, messageID: 'notification', text: 'Article notes', cards: [], status: 'complete' },
527
+ { ordinal: 2, messageID: 'result', text: 'Note saved', cards: [], status: 'complete' },
528
+ ] });
529
+ await vi.waitFor(() => expect(f.adapter.send.mock.calls.some(([input]) => input.text === 'Note saved')).toBe(true));
530
+ expect(f.runtime.status('bot', provider)).toMatchObject({ status: 'connected', error: 'delivery_failed' });
531
+ await connection.onMessage({ id: 'next', senderID: 'owner', chatType: 'private', text: 'Next task' });
532
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledOnce());
533
+ expect(f.adapter.send.mock.calls.filter(([input]) => input.text === 'Note saved')).toHaveLength(1);
534
+ });
535
+
536
+ it('continues later output after an uncertain notification send, including after restart, without resending it', async () => {
537
+ const f = fixture();
538
+ f.adapter.send.mockRejectedValueOnce(Object.assign(new Error('timeout'), { ambiguous: true }));
539
+ await f.save();
540
+ await f.connected();
541
+ f.pages.set('bot', { generation: 0, messages: [
542
+ { ordinal: 1, messageID: 'notification', text: 'Article notes', cards: [], status: 'complete' },
543
+ { ordinal: 2, messageID: 'result', text: 'Note saved', cards: [], status: 'complete' },
544
+ ] });
545
+ await vi.waitFor(() => expect(f.adapter.send).toHaveBeenCalledTimes(2));
546
+ expect(f.adapter.send.mock.calls.map(([input]) => input.text)).toEqual(['Article notes', 'Note saved']);
547
+ expect(f.runtime.status('bot', 'wecom').error).toBe('delivery_unknown');
548
+ await f.runtime.close();
549
+ const restarted = fixture({ directory: f.directory });
550
+ restarted.reply('bot', 'Later result', 3);
551
+ await vi.waitFor(() => expect(restarted.adapter.send).toHaveBeenCalledOnce());
552
+ expect(restarted.adapter.send.mock.calls[0][0].text).toBe('Later result');
553
+ expect(restarted.runtime.status('bot', 'wecom').error).toBe('delivery_unknown');
554
+ });
555
+
556
+ it.each(['auth_failed', 'connection_replaced'])('keeps %s sticky instead of hot-looping reconnects', async (code) => {
557
+ const f = fixture();
558
+ f.adapter.connect.mockRejectedValue(Object.assign(new Error('rejected'), { code }));
559
+ await f.save();
560
+ await vi.waitFor(
561
+ () => expect(f.runtime.status('bot', 'wecom')).toMatchObject({ status: 'error', error: code }),
562
+ { interval: 10, timeout: 3000 },
563
+ );
564
+ await new Promise((resolve) => setTimeout(resolve, 1200));
565
+ expect(f.adapter.connect).toHaveBeenCalledTimes(1);
566
+ });
567
+
568
+ it('starts a changed owner at the current transcript tip instead of replaying the old owner watermark', async () => {
569
+ const f = fixture({ autoReady: false, intervalMs: 10_000 });
570
+ await f.save('bot', 'wecom', { ownerID: 'old-owner' });
571
+ f.pages.set('bot', {
572
+ generation: 0,
573
+ messages: [
574
+ { ordinal: 10, messageID: 'old-10', text: 'old owner reply', cards: [], status: 'complete' },
575
+ { ordinal: 20, messageID: 'old-20', text: 'old owner reply 2', cards: [], status: 'complete' },
576
+ ],
577
+ });
578
+ await f.runtime.save('bot', 'wecom', { clientID: 'client', ownerID: 'new-owner' });
579
+ const raw = createAssistantChannelStore(f.directory);
580
+ expect(raw.get('bot', 'wecom')).toMatchObject({ owner_id: 'new-owner', generation: 0, ordinal: 20 });
581
+ raw.close();
582
+ f.pages.set('bot', {
583
+ generation: 0,
584
+ messages: [
585
+ { ordinal: 10, messageID: 'old-10', text: 'old owner reply', cards: [], status: 'complete' },
586
+ { ordinal: 20, messageID: 'old-20', text: 'old owner reply 2', cards: [], status: 'complete' },
587
+ { ordinal: 21, messageID: 'new-21', text: 'new owner reply', cards: [], status: 'complete' },
588
+ ],
589
+ });
590
+ f.connections.at(-1).onReady();
591
+ await vi.waitFor(() => expect(f.adapter.send).toHaveBeenCalledTimes(1), { interval: 10 });
592
+ expect(f.adapter.send.mock.calls[0][0].text).toBe('new owner reply');
593
+ });
594
+
595
+ it('does not send before the adapter authenticates and resumes durable output on ready', async () => {
596
+ const f = fixture({ autoReady: false, intervalMs: 10 });
597
+ await f.save();
598
+ f.pages.set('bot', {
599
+ generation: 0,
600
+ messages: [{ ordinal: 1, messageID: 'r1', text: 'queued reply', cards: [], status: 'complete' }],
601
+ });
602
+ await new Promise((resolve) => setTimeout(resolve, 60));
603
+ expect(f.adapter.send).not.toHaveBeenCalled();
604
+ expect(f.runtime.status('bot', 'wecom').status).toBe('connecting');
605
+ f.connections.at(-1).onReady();
606
+ await vi.waitFor(() => expect(f.adapter.send).toHaveBeenCalledTimes(1), { interval: 10 });
607
+ expect(f.adapter.send.mock.calls[0][0].text).toBe('queued reply');
608
+ });
609
+
610
+ it('acknowledges a durable duplicate at the backlog limit instead of rejecting it', async () => {
611
+ const f = fixture();
612
+ await f.save();
613
+ const connection = await f.connected();
614
+ let release;
615
+ const gate = new Promise((resolve) => { release = resolve; });
616
+ f.service.send.mockImplementation(() => gate.then(() => ({ admitted: true })));
617
+ for (let index = 0; index < 100; index += 1) {
618
+ await connection.onMessage({
619
+ id: `bulk-${index}`, senderID: 'owner', chatType: 'private', text: `message ${index}`,
620
+ });
621
+ }
622
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1), { interval: 10 });
623
+ await expect(connection.onMessage({
624
+ id: 'bulk-overflow', senderID: 'owner', chatType: 'private', text: 'overflow',
625
+ })).rejects.toMatchObject({ code: 'backlog_full' });
626
+ await expect(connection.onMessage({
627
+ id: 'bulk-0', senderID: 'owner', chatType: 'private', text: 'duplicate',
628
+ })).resolves.toBe(true);
629
+ release({ admitted: true });
630
+ await new Promise((resolve) => setTimeout(resolve, 50));
631
+ });
632
+
633
+ it('stops admitting new work after a sticky connection error and never sends on a dead lane', async () => {
634
+ const f = fixture();
635
+ await f.save();
636
+ const connection = await f.connected();
637
+ connection.onError({ code: 'auth_expired' });
638
+ await vi.waitFor(
639
+ () => expect(f.runtime.status('bot', 'wecom')).toMatchObject({ status: 'error', error: 'auth_expired' }),
640
+ { interval: 10 },
641
+ );
642
+ await expect(connection.onMessage({
643
+ id: 'blocked', senderID: 'owner', chatType: 'private', text: 'should not admit',
644
+ })).rejects.toMatchObject({ code: 'cancelled' });
645
+ await new Promise((resolve) => setTimeout(resolve, 40));
646
+ expect(f.service.send).not.toHaveBeenCalled();
647
+ expect(f.adapter.send).not.toHaveBeenCalled();
648
+ });
649
+
650
+ it('rejects overlong identities and secrets instead of truncating them', async () => {
651
+ const f = fixture();
652
+ await expect(f.save('bot', 'wecom', { clientID: 'c'.repeat(513) }))
653
+ .rejects.toMatchObject({ code: 'validation_error' });
654
+ await expect(f.save('bot', 'wecom', { ownerID: 'o'.repeat(513) }))
655
+ .rejects.toMatchObject({ code: 'validation_error' });
656
+ await expect(f.save('bot', 'wecom', { clientSecret: 's'.repeat(4097) }))
657
+ .rejects.toMatchObject({ code: 'validation_error' });
658
+ await f.save();
659
+ // A new account cannot silently reuse the previous account's secret.
660
+ await expect(f.runtime.save('bot', 'wecom', { clientID: 'other-client', ownerID: 'owner' }))
661
+ .rejects.toMatchObject({ code: 'validation_error' });
662
+ const connection = await f.connected();
663
+ await connection.onMessage({
664
+ id: 'm'.repeat(300), senderID: 'owner', chatType: 'private', text: 'too long id',
665
+ });
666
+ await connection.onMessage({
667
+ id: 'valid-id', senderID: `owner${'x'.repeat(600)}`, chatType: 'private', text: 'too long sender',
668
+ });
669
+ await new Promise((resolve) => setTimeout(resolve, 60));
670
+ expect(f.service.send).not.toHaveBeenCalled();
671
+ });
672
+
673
+ it('drains admitted inbound work before rotating a save and keeps the receipt durable', async () => {
674
+ const f = fixture();
675
+ await f.save();
676
+ const connection = await f.connected();
677
+ let release;
678
+ const gate = new Promise((resolve) => { release = resolve; });
679
+ f.service.send.mockImplementationOnce(() => gate.then(() => ({ admitted: true })));
680
+ await connection.onMessage({ id: 'm1', senderID: 'owner', chatType: 'private', text: 'do work' });
681
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1), { interval: 10 });
682
+ let settled = false;
683
+ const saving = f.runtime.save('bot', 'wecom', {
684
+ clientID: 'client', clientSecret: 'secret2', ownerID: 'owner',
685
+ }).then((value) => { settled = true; return value; });
686
+ await new Promise((resolve) => setTimeout(resolve, 60));
687
+ expect(settled).toBe(false);
688
+ release({ admitted: true });
689
+ await saving;
690
+ const db = new Database(path.join(f.directory, 'channel.sqlite'));
691
+ expect(db.prepare('SELECT state FROM inbox').all()).toEqual([{ state: 'admitted' }]);
692
+ db.close();
693
+ await new Promise((resolve) => setTimeout(resolve, 40));
694
+ expect(f.service.send).toHaveBeenCalledTimes(1);
695
+ });
696
+
697
+ it('locks retry against concurrent mutations until the old lane drains', async () => {
698
+ const f = fixture();
699
+ await f.save();
700
+ const connection = await f.connected();
701
+ let release;
702
+ const pending = new Promise((_, reject) => {
703
+ release = () => reject(Object.assign(new Error('network'), { code: 'network_error' }));
704
+ });
705
+ f.adapter.send.mockImplementationOnce(() => pending);
706
+ f.reply('bot', 'in flight', 1);
707
+ await vi.waitFor(() => expect(f.adapter.send).toHaveBeenCalledTimes(1), { interval: 10 });
708
+ const retrying = f.runtime.retry('bot', 'wecom');
709
+ await expect(f.runtime.save('bot', 'wecom', {
710
+ clientID: 'client', clientSecret: 'secret', ownerID: 'owner',
711
+ })).rejects.toMatchObject({ code: 'channel_in_use' });
712
+ await expect(f.runtime.disconnect('bot', 'wecom')).rejects.toMatchObject({ code: 'channel_in_use' });
713
+ release();
714
+ await retrying;
715
+ });
716
+
717
+ it('restarts without replaying admitted tools or duplicate receipts and reports interruption', async () => {
718
+ const f = fixture();
719
+ await f.save();
720
+ const connection = await f.connected();
721
+ await connection.onMessage({ id: 'm1', senderID: 'owner', chatType: 'private', text: 'do work' });
722
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1), { interval: 10 });
723
+ // No turn-end event: the receipt stays admitted, like a process crash mid-turn.
724
+ await f.runtime.close();
725
+ f.service.send.mockClear();
726
+ const restarted = fixture({ directory: f.directory, service: f.service });
727
+ await vi.waitFor(() => expect(restarted.adapter.send).toHaveBeenCalledTimes(1), { interval: 10, timeout: 3000 });
728
+ expect(restarted.adapter.send.mock.calls[0][0].text).toMatch(/主机已重启|host restarted/);
729
+ expect(restarted.service.send).not.toHaveBeenCalled();
730
+ const second = await restarted.connected();
731
+ await second.onMessage({ id: 'm1', senderID: 'owner', chatType: 'private', text: 'do work' });
732
+ await new Promise((resolve) => setTimeout(resolve, 60));
733
+ expect(restarted.service.send).not.toHaveBeenCalled();
734
+ });
735
+
736
+ it('disconnect removes local credentials and queues without cancelling admitted work', async () => {
737
+ const f = fixture();
738
+ await f.save();
739
+ const connection = await f.connected();
740
+ await connection.onMessage({ id: 'm1', senderID: 'owner', chatType: 'private', text: 'do work' });
741
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1), { interval: 10 });
742
+ const result = await f.runtime.disconnect('bot', 'wecom');
743
+ expect(result).toMatchObject({ status: 'disconnected', configured: false, hasSecret: false });
744
+ const raw = createAssistantChannelStore(f.directory);
745
+ expect(raw.get('bot', 'wecom')).toBeNull();
746
+ raw.close();
747
+ f.reply('bot', 'late reply', 1);
748
+ await new Promise((resolve) => setTimeout(resolve, 80));
749
+ expect(f.adapter.send).not.toHaveBeenCalled();
750
+ await expect(f.save('bot', 'wecom', { clientSecret: '' }))
751
+ .rejects.toMatchObject({ code: 'validation_error' });
752
+ });
753
+
754
+ it('forgets every provider when the Bot is deleted', async () => {
755
+ const f = fixture();
756
+ await f.save('bot', 'wecom');
757
+ await f.save('bot', 'feishu');
758
+ await f.connected('bot', 'wecom');
759
+ await f.runtime.forget('bot');
760
+ await vi.waitFor(() => {
761
+ expect(f.runtime.status('bot', 'wecom').status).toBe('disconnected');
762
+ expect(f.runtime.status('bot', 'feishu').status).toBe('disconnected');
763
+ }, { interval: 10 });
764
+ });
765
+
766
+ it('uses a process lease so another runtime cannot steal a live account', async () => {
767
+ const f = fixture();
768
+ await f.save();
769
+ await f.connected();
770
+ const second = fixture({ directory: f.directory });
771
+ await expect(second.save('other', 'wecom', { clientID: 'other-client', clientSecret: 'other' }))
772
+ .rejects.toMatchObject({ code: 'channel_in_use' });
773
+ await second.runtime.close();
774
+ expect(f.runtime.status('bot', 'wecom').status).toBe('connected');
775
+ });
776
+
777
+ it('aborts platform reads on close and releases the lease for the next runtime', async () => {
778
+ const f = fixture();
779
+ await f.save();
780
+ const connection = await f.connected();
781
+ await f.runtime.close();
782
+ expect(connection.signal.aborted).toBe(true);
783
+ const next = fixture({ directory: f.directory });
784
+ await next.save('bot', 'wecom', { clientID: 'client', clientSecret: 'replacement', ownerID: 'owner' });
785
+ await next.connected();
786
+ });
787
+
788
+ it('shares one store, lease and lifecycle across the three enterprise providers without mixing queues', async () => {
789
+ const providers = ['wecom', 'feishu', 'dingtalk'];
790
+ const service = {
791
+ channelPage: vi.fn((id, { afterOrdinal = 0, generation = null, tipOnly = false } = {}) => {
792
+ const page = service.pages?.get(id) ?? { generation: 0, messages: [] };
793
+ const after = generation === null || generation === page.generation ? afterOrdinal : 0;
794
+ const messages = tipOnly ? [] : page.messages.filter((message) => message.ordinal > after).slice(0, 50);
795
+ return {
796
+ generation: page.generation,
797
+ tipOrdinal: page.messages.at(-1)?.ordinal ?? 0,
798
+ ordinal: messages.at(-1)?.ordinal ?? after,
799
+ messages,
800
+ };
801
+ }),
802
+ send: vi.fn(async () => ({ admitted: true })),
803
+ pages: new Map(),
804
+ };
805
+ const connections = {};
806
+ const sends = { wecom: [], feishu: [], dingtalk: [] };
807
+ const adapters = Object.fromEntries(providers.map((provider) => [provider, {
808
+ connect: vi.fn(async (input) => {
809
+ connections[provider] = input;
810
+ input.onReady();
811
+ await abortable(input.signal);
812
+ }),
813
+ send: vi.fn(async (input) => { sends[provider].push(input); }),
814
+ }]));
815
+ const directory = root();
816
+ const runtime = createAssistantChannelsRuntime({ directory, service, adapters, env: {}, intervalMs: 10 });
817
+ closers.push(() => runtime.close());
818
+ for (const provider of providers) {
819
+ await runtime.save('bot', provider, {
820
+ clientID: `client-${provider}`,
821
+ clientSecret: `secret-${provider}`,
822
+ ownerID: 'owner',
823
+ language: 'zh-CN',
824
+ });
825
+ }
826
+ await vi.waitFor(() => {
827
+ for (const provider of providers) expect(runtime.status('bot', provider).status).toBe('connected');
828
+ }, { interval: 10, timeout: 3000 });
829
+ expect(Object.keys(connections).sort()).toEqual([...providers].sort());
830
+
831
+ for (const provider of providers) {
832
+ await connections[provider].onMessage({
833
+ id: 'shared-message-id',
834
+ senderID: 'owner',
835
+ chatType: 'private',
836
+ text: `hello ${provider}`,
837
+ target: { reply: `target-${provider}` },
838
+ });
839
+ }
840
+ await vi.waitFor(() => expect(service.send).toHaveBeenCalledTimes(3), { interval: 10 });
841
+ // The per-account dedup namespace is not shared across providers, and each
842
+ // account keeps its own original text.
843
+ expect(new Set(service.send.mock.calls.map((call) => call[1].parts[0].text)))
844
+ .toEqual(new Set(providers.map((provider) => `hello ${provider}`)));
845
+
846
+ service.pages.set('bot', {
847
+ generation: 0,
848
+ messages: [{ ordinal: 1, messageID: 'reply-1', text: 'common reply', cards: [], status: 'complete' }],
849
+ });
850
+ await vi.waitFor(() => {
851
+ for (const provider of providers) expect(sends[provider]).toHaveLength(1);
852
+ }, { interval: 10, timeout: 3000 });
853
+ for (const provider of providers) {
854
+ expect(sends[provider][0]).toMatchObject({
855
+ text: 'common reply',
856
+ target: { reply: `target-${provider}` },
857
+ config: { clientID: `client-${provider}`, ownerID: 'owner', language: 'zh-CN' },
858
+ });
859
+ }
860
+
861
+ await runtime.forget('bot');
862
+ await vi.waitFor(() => {
863
+ for (const provider of providers) expect(runtime.status('bot', provider).status).toBe('disconnected');
864
+ }, { interval: 10 });
865
+ const raw = createAssistantChannelStore(directory);
866
+ for (const provider of providers) expect(raw.get('bot', provider)).toBeNull();
867
+ raw.close();
868
+ });
869
+
870
+ it('reuses the real Yuri contact pipeline for channel → bot → durable reply', async () => {
871
+ const directory = root();
872
+ let runtime;
873
+ const service = createAssistantsService({
874
+ dbPath: path.join(directory, 'assistants.sqlite'),
875
+ dataDir: directory,
876
+ buildOpenCodeUrl: () => 'http://127.0.0.1:1',
877
+ getOpenCodeAuthHeaders: () => ({}),
878
+ getAllowedRoots: () => [directory],
879
+ runContactTurn: async ({ userParts }) => ({ bubbles: [`收到:${userParts[0].text}`] }),
880
+ onContactTurnEvent: (event) => runtime?.onTurnEvent(event),
881
+ createChatCompletion: async () => ({ choices: [] }),
882
+ });
883
+ closers.push(() => service.close());
884
+ const bot = service.createAssistant({ name: 'Channel test', providerID: 'p', modelID: 'm' });
885
+ const f = fixture({ directory: path.join(directory, 'channels'), service });
886
+ runtime = f.runtime;
887
+ await f.runtime.save(bot.id, 'wecom', {
888
+ clientID: 'client', clientSecret: 'secret', ownerID: 'owner', language: 'zh-CN',
889
+ });
890
+ const connection = await f.connected(bot.id);
891
+ await connection.onMessage({ id: 'm1', senderID: 'owner', chatType: 'private', text: '测试文字' });
892
+ await vi.waitFor(() => expect(f.adapter.send).toHaveBeenCalled(), { interval: 10, timeout: 4000 });
893
+ expect(f.adapter.send.mock.calls[0][0].text).toBe('收到:测试文字');
894
+ expect(service.contactMessages(bot.id, { limit: 20 }).messages
895
+ .some((message) => message.text === '测试文字')).toBe(true);
896
+ });
897
+ });