@yuriai/web 0.2.27-beta.8 → 0.2.28

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 (198) hide show
  1. package/dist/assets/{AgentAvatar-BJ42lGZD.js → AgentAvatar-BybF1ayP.js} +1 -1
  2. package/dist/assets/AssistantContactStatus-BwpxTn0d.js +3 -0
  3. package/dist/assets/{AssistantUnreadBadge-QwhBfXpC.js → AssistantUnreadBadge-DqThZdCe.js} +1 -1
  4. package/dist/assets/{AssistantView-D7ryIKL0.js → AssistantView-DPUDCXoY.js} +1 -1
  5. package/dist/assets/{DiagramView-ERrGEBDp.js → DiagramView-CHVLoYrV.js} +1 -1
  6. package/dist/assets/{FadeInOnReveal-Bu2GvaM9.js → FadeInOnReveal-Cj3JXYvE.js} +1 -1
  7. package/dist/assets/{GuiPluginSurface-MzQgEZNr.js → GuiPluginSurface-CBZYeKHb.js} +1 -1
  8. package/dist/assets/{GuiPluginWindow-DZMmlQzx.js → GuiPluginWindow-_Z5wycnH.js} +1 -1
  9. package/dist/assets/{Icon-Dj4CCqCP.js → Icon-CeRMtJa8.js} +1 -1
  10. package/dist/assets/{ImageLoadingPlaceholder-BnFXgUuO.js → ImageLoadingPlaceholder-DjLaKB4o.js} +1 -1
  11. package/dist/assets/{LoadingImage-PBnivDKv.js → LoadingImage-DG3otL5V.js} +1 -1
  12. package/dist/assets/MarkdownRenderer-C8rv6z7p.js +2 -0
  13. package/dist/assets/{MarkdownRendererImpl-CfyXL4rg.js → MarkdownRendererImpl-_plqOlsV.js} +1 -1
  14. package/dist/assets/{MarkstreamRendererImpl-BGadklK1.js → MarkstreamRendererImpl-bs8HZ4Ra.js} +1 -1
  15. package/dist/assets/{MobileDetailNavigation-DqajQdB4.js → MobileDetailNavigation-SeT764Ps.js} +1 -1
  16. package/dist/assets/{MobileResizableSheet-BvdUgwA3.js → MobileResizableSheet-BY1-oo_E.js} +1 -1
  17. package/dist/assets/{MobileShareBridge-3oPoYnry.js → MobileShareBridge-Dw8gLtJD.js} +2 -2
  18. package/dist/assets/MobileTabPageHeader-EsrOCLyg.js +2 -0
  19. package/dist/assets/{MultiRunWindow-yhs0Ih5_.js → MultiRunWindow-C-Qw_g7N.js} +1 -1
  20. package/dist/assets/{OnboardingScreen-Bi1VWFQC.js → OnboardingScreen-CGqabMbp.js} +1 -1
  21. package/dist/assets/{OverlayScrollbar-BBDwGvGO.js → OverlayScrollbar-AGSWQKg-.js} +1 -1
  22. package/dist/assets/{SettingsView-BSf-SJUA.js → SettingsView-BLfFnnnX.js} +14 -14
  23. package/dist/assets/{SettingsWindow-BvSXVMTm.js → SettingsWindow-lyYO8Byy.js} +1 -1
  24. package/dist/assets/{TerminalView-DhL01N7e.js → TerminalView-OHqpkHzz.js} +1 -1
  25. package/dist/assets/{ToolOutputDialog-C8lnH4Ky.js → ToolOutputDialog-DU4Pb1s0.js} +1 -1
  26. package/dist/assets/{YuriLogo-D8asj1CS.js → YuriLogo-Bb6yHagP.js} +1 -1
  27. package/dist/assets/{appThemeRegistry-C-maYSdv.js → appThemeRegistry-9j-rCSlE.js} +1 -1
  28. package/dist/assets/{button-vXOdzd8x.js → button-Bjh2BSXh.js} +1 -1
  29. package/dist/assets/{capgoAdapter-DJ_h2x5D.js → capgoAdapter-DERfot6h.js} +1 -1
  30. package/dist/assets/{collapsible-DwDQs3Wa.js → collapsible-BEAHoxNi.js} +1 -1
  31. package/dist/assets/{context-menu-BabBujQ-.js → context-menu-BxLcot-3.js} +1 -1
  32. package/dist/assets/device-BcRP6Tjd.js +2 -0
  33. package/dist/assets/{diagram-HwgrQxY5.js → diagram-CXVm2vzI.js} +1 -1
  34. package/dist/assets/{dialog-Dnf626tb.js → dialog-nshKUSE5.js} +1 -1
  35. package/dist/assets/{dropdown-menu.styles-CBc_a-Nv.js → dropdown-menu.styles-M78xpvb2.js} +1 -1
  36. package/dist/assets/{es-BQkO-Odr.js → es-N9ZkQwG9.js} +2 -2
  37. package/dist/assets/fileMentionAutocompleteState-BZJqfgae.js +2 -0
  38. package/dist/assets/{fileMentionTouchSelection-CKPnEetl.js → fileMentionTouchSelection-B9NbPN9D.js} +2 -2
  39. package/dist/assets/{fileReferenceActions-g7KZLi_G.js → fileReferenceActions-CrIAce3K.js} +1 -1
  40. package/dist/assets/{fr-C852roK5.js → fr-CIGqV46N.js} +2 -2
  41. package/dist/assets/{gitApi-CVq5oKCd.js → gitApi-CY3D5CF0.js} +1 -1
  42. package/dist/assets/{gitApiHttp-BYOIbYIh.js → gitApiHttp-B7vYwgBh.js} +4 -4
  43. package/dist/assets/{gui-M_Rbwkyu.js → gui-CJjEj3l4.js} +1 -1
  44. package/dist/assets/host-CnVx34Dh.js +1 -0
  45. package/dist/assets/{image-loading-D5UhMj7Z.js → image-loading-D6kOgU4w.js} +1 -1
  46. package/dist/assets/{input-BtM712b1.js → input-3Re4pmHm.js} +1 -1
  47. package/dist/assets/insertionBoundaries-DK7XYF8d.js +1 -0
  48. package/dist/assets/{ja-BqC39qK6.js → ja-DAhnTq6V.js} +2 -2
  49. package/dist/assets/{ko-BMaChAWh.js → ko-FbMgNKcI.js} +2 -2
  50. package/dist/assets/main-B_THXYMs.js +2 -0
  51. package/dist/assets/main-CpcudEZb.js +169 -0
  52. package/dist/assets/{markdownHeightCache-Bf8iisO4.js → markdownHeightCache-DVWGXtAX.js} +1 -1
  53. package/dist/assets/{mcpQueries-DpXqegX5.js → mcpQueries-CdOYmUdO.js} +1 -1
  54. package/dist/assets/miniChat-DxZiTnAZ.js +2 -0
  55. package/dist/assets/mobile-BJuATiaC.js +2 -0
  56. package/dist/assets/{mobileBackNavigation-DZcI7aZg.js → mobileBackNavigation-CgZndzFA.js} +1 -1
  57. package/dist/assets/{multirun-hzspPepd.js → multirun-BlaYsQi2.js} +1 -1
  58. package/dist/assets/{native-H7K64Ulc.js → native-BYMhr-xH.js} +1 -1
  59. package/dist/assets/{native-config-CddZtLQ1.js → native-config-BpsFKLGl.js} +1 -1
  60. package/dist/assets/{persistence-BT8045Ue.js → persistence-CWuLIq1J.js} +2 -2
  61. package/dist/assets/{pl-Ubs8p28T.js → pl-DzX0cbiQ.js} +2 -2
  62. package/dist/assets/{projectMeta-CEf0QPmD.js → projectMeta-CnXHTolN.js} +1 -1
  63. package/dist/assets/{pt-BR-8rAOjJrs.js → pt-BR-C5yvwyDK.js} +2 -2
  64. package/dist/assets/queue-abort-optimistic-DCLBpirg.js +1 -0
  65. package/dist/assets/{readiness-Dyr7314z.js → readiness-U16Qor79.js} +1 -1
  66. package/dist/assets/renderElectronMiniChatApp-n-nhgy1V.js +2 -0
  67. package/dist/assets/renderMobileApp-DBj_7RlD.js +28 -0
  68. package/dist/assets/{runtimeConfig-B8VHHNxj.js → runtimeConfig-BBgkLVr_.js} +1 -1
  69. package/dist/assets/runtimeEndpointReset-BvSQVFfx.js +149 -0
  70. package/dist/assets/{scheduledTaskNavigation-Zm87Nydi.js → scheduledTaskNavigation-EomDNVu2.js} +1 -1
  71. package/dist/assets/sessionLookup-C_CCp7MJ.js +1 -0
  72. package/dist/assets/{sortable-tabs-strip-D4pVoodN.js → sortable-tabs-strip-p16Pn6Zz.js} +1 -1
  73. package/dist/assets/{speechSettingsQueries-RlCLMBtr.js → speechSettingsQueries-CBSEAKyj.js} +2 -2
  74. package/dist/assets/src-u-YDfCVw.css +2 -0
  75. package/dist/assets/{store-ME7oHni1.js → store-DVfZQktm.js} +4 -3
  76. package/dist/assets/{terminalApi-BSaclMDJ.js → terminalApi-rl9mZAlB.js} +1 -1
  77. package/dist/assets/{textarea-B98rsLs7.js → textarea-C6VQ7dHH.js} +1 -1
  78. package/dist/assets/{tooltip-B9810jbK.js → tooltip-Dnc6GA-X.js} +1 -1
  79. package/dist/assets/types-DnZw0gLD.js +2 -0
  80. package/dist/assets/{uk-LzwzUApL.js → uk-zbDcUpBy.js} +2 -2
  81. package/dist/assets/{useAppFontEffects-D2C1sBYM.js → useAppFontEffects-CEgDiZHu.js} +49 -49
  82. package/dist/assets/{useAssistantUIStore-TUN_ycy5.js → useAssistantUIStore-CfaQV3ID.js} +1 -1
  83. package/dist/assets/useDesktopWindowControlsLayout-B2o4IFmd.js +1 -0
  84. package/dist/assets/useEffectiveDirectory-BOYMJ6k7.js +1 -0
  85. package/dist/assets/{useFontPreferences-BlhlCJCX.js → useFontPreferences-DeqW9nRx.js} +1 -1
  86. package/dist/assets/useMobileNavigationStore-DlvrZQ49.js +17 -0
  87. package/dist/assets/{useUIStore-DRx6OgCp.js → useUIStore-C6CE42oh.js} +1 -1
  88. package/dist/assets/{useWorkerHighlightedLines-D093jNsH.js → useWorkerHighlightedLines-EcJThS4x.js} +1 -1
  89. package/dist/assets/{vendor-effect-DV9F8PTZ.js → vendor-effect-X1Hqc7ba.js} +13 -13
  90. package/dist/assets/vendor-opencode-client-cQ47ywrT.js +23 -0
  91. package/dist/assets/{vendor-opencode-plugin-BBOP6WNx.js → vendor-opencode-plugin-BmdTE4Te.js} +1 -1
  92. package/dist/assets/vendor-opencode-schema-DWT45VBX.js +1 -0
  93. package/dist/assets/vendor-solid-js-D98iXT7C.js +1 -0
  94. package/dist/assets/vendor-zod-DZzbCm1s.js +55 -0
  95. package/dist/assets/{zh-CN-D-FVCeks.js → zh-CN-BHRJ7CF3.js} +2 -2
  96. package/dist/assets/{zh-TW-B9iH_NXL.js → zh-TW-BFI_YFd-.js} +2 -2
  97. package/dist/index.html +12 -12
  98. package/dist/mini-chat.html +12 -12
  99. package/dist/mobile.html +12 -12
  100. package/package.json +1 -1
  101. package/server/index.js +2 -145
  102. package/server/lib/assistants/DOCUMENTATION.md +63 -10
  103. package/server/lib/assistants/cards.js +1 -1
  104. package/server/lib/assistants/channel-image.js +92 -0
  105. package/server/lib/assistants/channel-image.test.js +76 -0
  106. package/server/lib/assistants/channel-output-store.test.js +41 -0
  107. package/server/lib/assistants/channel-output.integration.test.js +128 -0
  108. package/server/lib/assistants/channel-output.js +90 -0
  109. package/server/lib/assistants/channel-output.test.js +79 -0
  110. package/server/lib/assistants/channels/DOCUMENTATION.md +52 -14
  111. package/server/lib/assistants/channels/PROTOCOLS.md +23 -1
  112. package/server/lib/assistants/channels/dingtalk-chat-adapter.js +19 -7
  113. package/server/lib/assistants/channels/dingtalk-chat-adapter.test.js +8 -0
  114. package/server/lib/assistants/channels/routes.js +12 -0
  115. package/server/lib/assistants/channels/routes.test.js +34 -0
  116. package/server/lib/assistants/channels/runtime.js +117 -26
  117. package/server/lib/assistants/channels/runtime.test.js +179 -5
  118. package/server/lib/assistants/channels/sdk-adapters.js +15 -3
  119. package/server/lib/assistants/channels/sdk-adapters.test.js +17 -0
  120. package/server/lib/assistants/channels/store.js +9 -6
  121. package/server/lib/assistants/channels/store.test.js +21 -11
  122. package/server/lib/assistants/channels/transport.js +2 -1
  123. package/server/lib/assistants/channels/wecom-chat-adapter.js +16 -2
  124. package/server/lib/assistants/channels/wecom-chat-adapter.test.js +21 -0
  125. package/server/lib/assistants/contact-store.js +9 -3
  126. package/server/lib/assistants/contact-store.test.js +27 -0
  127. package/server/lib/assistants/contact-tools.js +65 -75
  128. package/server/lib/assistants/contact-tools.test.js +114 -22
  129. package/server/lib/assistants/harness.js +80 -34
  130. package/server/lib/assistants/harness.test.js +68 -20
  131. package/server/lib/assistants/resource-reference.integration.test.js +284 -0
  132. package/server/lib/assistants/routes.js +0 -3
  133. package/server/lib/assistants/service.js +116 -69
  134. package/server/lib/assistants/service.test.js +31 -17
  135. package/server/lib/assistants/weixin/DOCUMENTATION.md +34 -9
  136. package/server/lib/assistants/weixin/api.js +43 -1
  137. package/server/lib/assistants/weixin/api.test.js +28 -0
  138. package/server/lib/assistants/weixin/chat-adapter.js +8 -2
  139. package/server/lib/assistants/weixin/inbound.js +5 -3
  140. package/server/lib/assistants/weixin/inbound.test.js +20 -0
  141. package/server/lib/assistants/weixin/runtime.js +27 -18
  142. package/server/lib/assistants/weixin/runtime.test.js +36 -0
  143. package/server/lib/assistants/weixin/store.js +8 -4
  144. package/server/lib/assistants/weixin/store.test.js +21 -0
  145. package/server/lib/assistants/yuri-project.http.test.js +9 -3
  146. package/server/lib/notifications/DOCUMENTATION.md +6 -0
  147. package/server/lib/notifications/runtime.js +26 -15
  148. package/server/lib/notifications/runtime.test.js +14 -13
  149. package/server/lib/opencode/DOCUMENTATION.md +9 -0
  150. package/server/lib/opencode/auth.d.ts +6 -2
  151. package/server/lib/opencode/core-routes.js +0 -1
  152. package/server/lib/opencode/feature-routes-runtime.js +0 -24
  153. package/server/lib/opencode/location-release.d.ts +5 -1
  154. package/server/lib/opencode/managed-capabilities/scheduled-task.js +1 -1
  155. package/server/lib/opencode/managed-capabilities-runtime.test.js +1 -1
  156. package/server/lib/opencode/native-goal.js +15 -0
  157. package/server/lib/opencode/native-goal.test.js +17 -0
  158. package/server/lib/opencode/settings-helpers.js +0 -6
  159. package/server/lib/opencode/shutdown-runtime.js +0 -2
  160. package/server/lib/projects/project-config.js +3 -6
  161. package/server/lib/scheduled-tasks/DOCUMENTATION.md +10 -35
  162. package/server/lib/scheduled-tasks/managed-tool-route.js +1 -30
  163. package/server/lib/scheduled-tasks/routes.js +0 -26
  164. package/server/lib/scheduled-tasks/runtime.js +33 -257
  165. package/server/lib/scheduled-tasks/runtime.test.js +24 -65
  166. package/server/lib/session-metadata/DOCUMENTATION.md +9 -12
  167. package/server/lib/session-metadata/routes.js +4 -38
  168. package/server/lib/session-metadata/routes.test.js +2 -2
  169. package/dist/assets/AssistantContactStatus-dtkObamV.js +0 -3
  170. package/dist/assets/MarkdownRenderer-BajF4gUU.js +0 -2
  171. package/dist/assets/MobileTabPageHeader-B6cRyIRH.js +0 -2
  172. package/dist/assets/device-BjRYYXNT.js +0 -2
  173. package/dist/assets/host-BW3FEJdU.js +0 -1
  174. package/dist/assets/insertionBoundaries-Dx3WAY6i.js +0 -1
  175. package/dist/assets/main-9uP2z1qT.js +0 -2
  176. package/dist/assets/main-Mey7bCWf.js +0 -169
  177. package/dist/assets/miniChat-DqZvVkme.js +0 -2
  178. package/dist/assets/mobile-DXAWjYcN.js +0 -2
  179. package/dist/assets/renderElectronMiniChatApp-DoOq8Cuo.js +0 -2
  180. package/dist/assets/renderMobileApp-TTxtOb8b.js +0 -28
  181. package/dist/assets/runtimeEndpointReset-BC6XWntz.js +0 -149
  182. package/dist/assets/sessionLookup-De53jDwM.js +0 -1
  183. package/dist/assets/src-lE4uqaHS.css +0 -2
  184. package/dist/assets/types-DFf9vd1b.js +0 -2
  185. package/dist/assets/useDesktopWindowControlsLayout-BjKaHN0x.js +0 -1
  186. package/dist/assets/useEffectiveDirectory-TEvyiQSC.js +0 -1
  187. package/dist/assets/useMobileNavigationStore-DTvJV9s-.js +0 -23
  188. package/dist/assets/vendor-opencode-client-ZeOZ4Efz.js +0 -23
  189. package/dist/assets/vendor-solid-js-9wmPZH9g.js +0 -1
  190. package/dist/assets/vendor-zod-Dzk5kdUU.js +0 -39
  191. package/server/lib/session-goal/DOCUMENTATION.md +0 -371
  192. package/server/lib/session-goal/capability.js +0 -57
  193. package/server/lib/session-goal/capability.test.js +0 -33
  194. package/server/lib/session-goal/objectives.js +0 -61
  195. package/server/lib/session-goal/routes.js +0 -274
  196. package/server/lib/session-goal/routes.test.js +0 -211
  197. package/server/lib/session-goal/runtime.js +0 -2452
  198. package/server/lib/session-goal/runtime.test.js +0 -2125
@@ -23,7 +23,7 @@ const abortable = (signal) => new Promise((_, reject) => {
23
23
  signal.addEventListener('abort', () => reject(error), { once: true });
24
24
  });
25
25
 
26
- function fixture({ directory = root(), service: externalService, env = {}, intervalMs = 10, autoReady = true, includeDingtalk = false } = {}) {
26
+ function fixture({ directory = root(), service: externalService, env = {}, intervalMs = 10, autoReady = true, includeDingtalk = false, discoveryTimeoutMs } = {}) {
27
27
  const pages = new Map();
28
28
  const seen = new Set();
29
29
  const service = externalService ?? {
@@ -59,11 +59,18 @@ function fixture({ directory = root(), service: externalService, env = {}, inter
59
59
  adapters: { wecom: adapter, feishu: adapter, ...(includeDingtalk ? { dingtalk: adapter } : {}) },
60
60
  env,
61
61
  intervalMs,
62
+ discoveryTimeoutMs,
62
63
  });
63
64
  closers.push(() => runtime.close());
64
65
  const save = (assistantID = 'bot', provider = 'wecom', input = {}) => runtime.save(assistantID, provider, {
65
66
  clientID: 'client', clientSecret: 'secret', ownerID: 'owner', language: 'zh-CN', ...input,
66
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
+ };
67
74
  const connected = async (assistantID = 'bot', provider = 'wecom') => {
68
75
  await vi.waitFor(
69
76
  () => expect(runtime.status(assistantID, provider).status).toBe('connected'),
@@ -75,13 +82,142 @@ function fixture({ directory = root(), service: externalService, env = {}, inter
75
82
  generation,
76
83
  messages: [{ ordinal, messageID: `reply-${ordinal}`, text, cards: [], status: 'complete' }],
77
84
  });
78
- return { directory, runtime, service, adapter, connections, pages, save, connected, reply };
85
+ return { directory, runtime, service, adapter, connections, pages, save, connected, reply, seedLegacyUnrestricted };
79
86
  }
80
87
 
81
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
+
82
218
  it('replies only on the originating channel and to its original sender; source-less output is pushed', async () => {
83
219
  const f = fixture();
84
- await f.save('bot', 'wecom', { ownerID: '' });
220
+ f.seedLegacyUnrestricted();
85
221
  const wecom = await f.connected('bot', 'wecom');
86
222
  await f.save('bot', 'feishu');
87
223
  const feishu = await f.connected('bot', 'feishu');
@@ -182,9 +318,9 @@ describe('enterprise channel runtime', () => {
182
318
  expect(f.runtime.status('bot', 'wecom').configured).toBe(true);
183
319
  });
184
320
 
185
- it('accepts platform-scoped private senders without an owner and derives reply targets from their identities', async () => {
321
+ it('preserves legacy unrestricted bindings until explicitly restricted by a save', async () => {
186
322
  const f = fixture();
187
- await expect(f.save('bot', 'wecom', { ownerID: undefined })).resolves.toMatchObject({ ownerID: '' });
323
+ f.seedLegacyUnrestricted();
188
324
  const connection = await f.connected();
189
325
  f.reply('bot', 'no recipient yet', 1);
190
326
  await vi.waitFor(() => expect(f.service.channelPage).toHaveBeenCalled(), { interval: 10 });
@@ -379,6 +515,44 @@ describe('enterprise channel runtime', () => {
379
515
  expect(f.adapter.send.mock.calls[0][0].id).toBe(deliveryID);
380
516
  });
381
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
+
382
556
  it.each(['auth_failed', 'connection_replaced'])('keeps %s sticky instead of hot-looping reconnects', async (code) => {
383
557
  const f = fixture();
384
558
  f.adapter.connect.mockRejectedValue(Object.assign(new Error('rejected'), { code }));
@@ -323,17 +323,29 @@ export function createFeishuSdkAdapter({
323
323
  * `@larksuite/channel` exposes no `uuid`. The documented HTTP call keeps
324
324
  * `msg_type: text` and a stable `uuid` for one attempt.
325
325
  */
326
- async send({ config, target, text, id, signal } = {}) {
326
+ async send({ config, target, text, image, id, signal, beforeSend } = {}) {
327
327
  const { clientID, clientSecret, ownerID } = requireConfig(config);
328
328
  const userID = ownerID || target?.userID;
329
329
  if (!nonEmptyString(userID)) throw channelError('invalid_response');
330
330
  const token = await feishuAccessToken(tokens, { clientID, clientSecret, signal, fetchImpl });
331
+ let imageKey;
332
+ if (image) {
333
+ const form = new FormData();
334
+ form.set('image_type', 'message');
335
+ form.set('image', new Blob([image.buffer], { type: image.mime }), image.filename);
336
+ const uploaded = await requestJSON(`${FEISHU_ORIGIN}/open-apis/im/v1/images`, {
337
+ body: form, headers: { Authorization: `Bearer ${token}` }, signal, fetchImpl,
338
+ });
339
+ if (uploaded?.code !== 0 || !nonEmptyString(uploaded?.data?.image_key)) throw channelError('delivery_failed');
340
+ imageKey = uploaded.data.image_key;
341
+ }
331
342
  const uuid = outboundUuid(id);
343
+ beforeSend?.();
332
344
  const json = await requestJSON(`${FEISHU_ORIGIN}${FEISHU_MESSAGE_PATH}?receive_id_type=open_id`, {
333
345
  body: {
334
346
  receive_id: userID,
335
- msg_type: 'text',
336
- content: JSON.stringify({ text: typeof text === 'string' ? text : '' }),
347
+ msg_type: image ? 'image' : 'text',
348
+ content: JSON.stringify(image ? { image_key: imageKey } : { text: typeof text === 'string' ? text : '' }),
337
349
  ...(uuid ? { uuid } : {}),
338
350
  },
339
351
  headers: { Authorization: `Bearer ${token}` },
@@ -2,6 +2,23 @@ import { describe, expect, it, vi } from 'vitest';
2
2
  import { createLarkChannel } from '@larksuite/channel';
3
3
  import { createAssistantChannelAdapters, createFeishuSdkAdapter, outboundUuid } from './sdk-adapters.js';
4
4
 
5
+ describe('Feishu native image delivery', () => {
6
+ it('uploads multipart bytes and sends image_key with the same durable UUID', async () => {
7
+ const fetchImpl = vi.fn(async (url) => Response.json(String(url).includes('tenant_access_token')
8
+ ? { code: 0, tenant_access_token: 'token', expire: 7200 }
9
+ : String(url).endsWith('/images') ? { code: 0, data: { image_key: 'img_uploaded' } } : { code: 0 }));
10
+ const bridge = createFeishuSdkAdapter({ fetchImpl });
11
+ await bridge.send({ config: { clientID: 'app', clientSecret: 'secret', ownerID: 'owner' }, id: 'stable-image',
12
+ image: { buffer: Buffer.from('image'), mime: 'image/png', filename: 'image.png' } });
13
+ const form = fetchImpl.mock.calls[1][1].body;
14
+ expect(form).toBeInstanceOf(FormData);
15
+ expect(form.get('image_type')).toBe('message');
16
+ expect(Buffer.from(await form.get('image').arrayBuffer())).toEqual(Buffer.from('image'));
17
+ expect(fetchImpl.mock.calls[1][1].headers['Content-Type']).toBeUndefined();
18
+ expect(JSON.parse(fetchImpl.mock.calls[2][1].body)).toEqual({ receive_id: 'owner', msg_type: 'image', content: JSON.stringify({ image_key: 'img_uploaded' }), uuid: 'stable-image' });
19
+ });
20
+ });
21
+
5
22
  /**
6
23
  * Mimics the real `@larksuite/vercel-chat-adapter` lifecycle: it asks the
7
24
  * bridge for a channel through `channelFactory`, wires its own normalized
@@ -74,6 +74,9 @@ export function createAssistantChannelStore(directory) {
74
74
  `);
75
75
  const inboxColumns = db.prepare("SELECT name FROM pragma_table_info('inbox')").all();
76
76
  if (!inboxColumns.some((column) => column.name === 'target')) db.exec("ALTER TABLE inbox ADD COLUMN target TEXT NOT NULL DEFAULT ''");
77
+ if (!db.prepare("SELECT name FROM pragma_table_info('outbox')").all().some((column) => column.name === 'image')) {
78
+ db.exec("ALTER TABLE outbox ADD COLUMN image TEXT NOT NULL DEFAULT ''");
79
+ }
77
80
 
78
81
  const get = (assistantID, provider) => db.prepare(
79
82
  'SELECT * FROM channel WHERE assistant_id=? AND provider=?',
@@ -85,9 +88,9 @@ export function createAssistantChannelStore(directory) {
85
88
  db.prepare(`UPDATE channel SET ${keys.map((key) => `${key}=?`).join(',')} WHERE epoch=?`)
86
89
  .run(...keys.map((key) => values[key]), epoch);
87
90
  };
88
- const enqueue = (epoch, id, text, target = '') => db.prepare(
89
- 'INSERT OR IGNORE INTO outbox(id,epoch,target,text) VALUES (?,?,?,?)',
90
- ).run(id, epoch, target, text);
91
+ const enqueue = (epoch, id, text, target = '', image = '') => db.prepare(
92
+ 'INSERT OR IGNORE INTO outbox(id,epoch,target,text,image) VALUES (?,?,?,?,?)',
93
+ ).run(id, epoch, target, text, image);
91
94
  const dropChannelQueues = (epoch) => {
92
95
  db.prepare('DELETE FROM inbox WHERE epoch=?').run(epoch);
93
96
  db.prepare('DELETE FROM outbox WHERE epoch=?').run(epoch);
@@ -196,16 +199,16 @@ export function createAssistantChannelStore(directory) {
196
199
  db.prepare('DELETE FROM outbox WHERE epoch=?').run(binding.epoch);
197
200
  }
198
201
  for (const delivery of deliveries) {
199
- enqueue(binding.epoch, delivery.id, delivery.text, delivery.target ?? current.target ?? '');
202
+ enqueue(binding.epoch, delivery.id, delivery.text, delivery.target ?? current.target ?? '', delivery.image ? JSON.stringify(delivery.image) : '');
200
203
  }
201
204
  db.prepare('UPDATE channel SET generation=?,ordinal=?,updated_at=? WHERE epoch=?')
202
205
  .run(page.generation, page.ordinal, updatedAt, binding.epoch);
203
206
  }),
204
207
  nextDelivery: (epoch) => db.prepare(
205
- "SELECT * FROM outbox WHERE epoch=? AND state!='sent' ORDER BY sequence LIMIT 1",
208
+ "SELECT * FROM outbox WHERE epoch=? AND state='pending' ORDER BY sequence LIMIT 1",
206
209
  ).get(epoch),
207
210
  markDelivery: (id, state) => db.prepare('UPDATE outbox SET state=? WHERE id=?').run(state, id),
208
- sent: (id) => db.prepare("UPDATE outbox SET state='sent',text='',target='' WHERE id=?").run(id),
211
+ sent: (id) => db.prepare("UPDATE outbox SET state='sent',text='',target='',image='' WHERE id=?").run(id),
209
212
  failDelivery: (id, maxAttempts = 3) => {
210
213
  const row = db.prepare('SELECT attempts FROM outbox WHERE id=?').get(id);
211
214
  if (!row) return;
@@ -176,9 +176,9 @@ describe('enterprise channel private store', () => {
176
176
  store.markDelivery('out', 'sending');
177
177
  store.recover(binding.epoch, 'interrupted feedback');
178
178
  expect(store.pending(binding.epoch)).toEqual([expect.objectContaining({ id: 'pending', text: 'still pending' })]);
179
- // The earlier indeterminate send stays at the head and is never bypassed.
179
+ // An indeterminate send stays durable but does not block interruption feedback.
180
180
  expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({
181
- id: 'out', text: 'reply', state: 'unknown',
181
+ id: 'admitted:interrupted', text: 'interrupted feedback', state: 'pending',
182
182
  }));
183
183
  expect(store.hasUnknown(binding.epoch)).toBe(true);
184
184
  const db = new Database(path.join(dir, 'channel.sqlite'));
@@ -189,7 +189,8 @@ describe('enterprise channel private store', () => {
189
189
  expect(db.prepare("SELECT state FROM outbox WHERE id='out'").get().state).toBe('unknown');
190
190
  // retry re-queues definitively failed rows only; unknown stays unknown.
191
191
  store.retry(binding.epoch);
192
- expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'out', state: 'unknown' }));
192
+ expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'admitted:interrupted', state: 'pending' }));
193
+ expect(db.prepare("SELECT state FROM outbox WHERE id='out'").get().state).toBe('unknown');
193
194
  });
194
195
 
195
196
  it('drops queued output from an older transcript generation and keeps stable IDs idempotent', () => {
@@ -218,30 +219,39 @@ describe('enterprise channel private store', () => {
218
219
  store.markDelivery('out', 'sending');
219
220
  store.failDelivery('out');
220
221
  expect(store.hasBlocked(binding.epoch)).toBe(true);
221
- expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'out', state: 'blocked' }));
222
+ expect(store.nextDelivery(binding.epoch)).toBeUndefined();
222
223
  store.retry(binding.epoch);
223
224
  expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'out', state: 'pending' }));
224
225
  store.markDelivery('out', 'unknown');
225
226
  store.retry(binding.epoch);
226
227
  expect(store.hasUnknown(binding.epoch)).toBe(true);
227
- expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'out', state: 'unknown' }));
228
+ expect(store.nextDelivery(binding.epoch)).toBeUndefined();
228
229
  expect(store.hasReceipt('missing')).toBe(false);
229
230
  });
230
231
 
231
- it('preserves outbox order behind an unknown send until it is explicitly resolved', () => {
232
- const store = createAssistantChannelStore(directory());
232
+ it('preserves pending output order across restart while bypassing durable failed/unknown sends', () => {
233
+ const dir = directory();
234
+ let store = createAssistantChannelStore(dir);
233
235
  cleanup.push(() => store.close());
234
236
  const binding = bind(store);
235
237
  store.collect(binding, { generation: 0, ordinal: 0 }, [
236
238
  { id: 'first', text: 'first' },
239
+ { id: 'failed', text: 'failed' },
237
240
  { id: 'second', text: 'second' },
241
+ { id: 'third', text: 'third' },
238
242
  ], 1);
239
243
  store.markDelivery('first', 'unknown');
240
- expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'first', state: 'unknown' }));
241
- store.retry(binding.epoch);
242
- expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'first', state: 'unknown' }));
243
- store.sent('first');
244
+ store.markDelivery('failed', 'blocked');
245
+ store.close();
246
+ store = createAssistantChannelStore(dir);
244
247
  expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'second', state: 'pending' }));
248
+ store.sent('second');
249
+ expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'third', state: 'pending' }));
250
+ expect(store.hasUnknown(binding.epoch)).toBe(true);
251
+ expect(store.hasBlocked(binding.epoch)).toBe(true);
252
+ store.retry(binding.epoch);
253
+ expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'failed', state: 'pending' }));
254
+ expect(store.hasUnknown(binding.epoch)).toBe(true);
245
255
  });
246
256
 
247
257
  it('leases one process at a time and expires a dead owner', () => {
@@ -13,8 +13,9 @@ export async function requestJSON(url, { body, headers, signal, fetchImpl = fetc
13
13
  requestSignal.throwIfAborted();
14
14
  let response;
15
15
  try {
16
+ const multipart = body instanceof FormData;
16
17
  response = await fetchImpl(url, { method: 'POST', redirect: 'error', signal: requestSignal,
17
- headers: { 'Content-Type': 'application/json', ...headers }, body: JSON.stringify(body) });
18
+ headers: { ...(!multipart ? { 'Content-Type': 'application/json' } : {}), ...headers }, body: multipart ? body : JSON.stringify(body) });
18
19
  } catch { throw channelError(signal?.aborted ? 'cancelled' : 'network_error', sending); }
19
20
  if (!response.ok) {
20
21
  await response.body?.cancel().catch(() => {});
@@ -442,7 +442,7 @@ export class WecomChatAdapter {
442
442
  }
443
443
  }
444
444
 
445
- async send({ config, target, text, signal } = {}) {
445
+ async send({ config, target, text, image, signal, beforeSend } = {}) {
446
446
  const normalized = requireConfig(config);
447
447
  const chatId = this.ownerId || target?.userID;
448
448
  if (!nonEmptyString(chatId)) throw channelError('invalid_response');
@@ -455,10 +455,24 @@ export class WecomChatAdapter {
455
455
  if (!client || !client.isConnected || !this.ready) throw channelError('network_error');
456
456
 
457
457
  const content = typeof text === 'string' ? text : '';
458
+ let mediaID;
459
+ if (image) {
460
+ try {
461
+ const uploaded = await withAbort(client.uploadMedia(image.buffer, { type: 'image', filename: image.filename }), signal);
462
+ if (!nonEmptyString(uploaded?.media_id)) throw channelError('delivery_failed');
463
+ mediaID = uploaded.media_id;
464
+ } catch {
465
+ // Uploading a resource never delivers a chat message; a retry is safe.
466
+ throw channelError(signal?.aborted ? 'cancelled' : 'delivery_failed');
467
+ }
468
+ signal?.throwIfAborted();
469
+ if (this.client !== client || !client.isConnected || !this.ready) throw channelError('network_error');
470
+ }
458
471
  let frame;
472
+ beforeSend?.();
459
473
  try {
460
474
  // `sendMessage` resolves only after the platform ACK with errcode 0.
461
- frame = await withAbort(client.sendMessage(chatId, {
475
+ frame = await withAbort(image ? client.sendMediaMessage(chatId, 'image', mediaID) : client.sendMessage(chatId, {
462
476
  msgtype: 'markdown',
463
477
  markdown: { content },
464
478
  }), signal);
@@ -34,6 +34,27 @@ async function connect(overrides = {}) {
34
34
  }
35
35
 
36
36
  describe('official WeCom Chat adapter ACK boundary', () => {
37
+ it('uses official chunked media upload then waits for the native image send ACK', async () => {
38
+ const h = await connect();
39
+ let settled = false;
40
+ const buffer = Buffer.from('generated image bytes');
41
+ const sending = h.bridge.send({ config, image: { buffer, mime: 'image/png', filename: 'image.png' } }).then(() => { settled = true; });
42
+ await vi.waitFor(() => expect(h.frames).toHaveLength(1));
43
+ expect(h.frames[0]).toMatchObject({ cmd: 'aibot_upload_media_init', body: { type: 'image', filename: 'image.png', total_size: buffer.length } });
44
+ h.socket().send(JSON.stringify({ headers: h.frames[0].headers, errcode: 0, body: { upload_id: 'upload-one' } }));
45
+ await vi.waitFor(() => expect(h.frames).toHaveLength(2));
46
+ expect(Buffer.from(h.frames[1].body.base64_data, 'base64')).toEqual(buffer);
47
+ h.ack(1);
48
+ await vi.waitFor(() => expect(h.frames).toHaveLength(3));
49
+ expect(h.frames[2].cmd).toBe('aibot_upload_media_finish');
50
+ h.socket().send(JSON.stringify({ headers: h.frames[2].headers, errcode: 0, body: { media_id: 'media-one', type: 'image' } }));
51
+ await vi.waitFor(() => expect(h.frames).toHaveLength(4));
52
+ expect(h.frames[3]).toMatchObject({ cmd: 'aibot_send_msg', body: { chatid: 'owner', msgtype: 'image', image: { media_id: 'media-one' } } });
53
+ expect(settled).toBe(false);
54
+ h.ack(3);
55
+ await sending;
56
+ expect(settled).toBe(true);
57
+ });
37
58
  it('waits for real SDK ACKs and sends a second reply without blocking the lane', async () => {
38
59
  const h = await connect();
39
60
  let settled = false;
@@ -1,6 +1,7 @@
1
1
  import crypto from 'node:crypto';
2
2
  import { decodeDataUrlStrict } from '../fs/prompt-attachment-store.js';
3
3
  import { parseContactCard, parseContactPart, serializeContactPart } from './cards.js';
4
+ import { isMessageChannelTurn } from './message-channel-origin.js';
4
5
 
5
6
  /** Keep in sync with CONTACT_ATTACHMENT_HISTORICAL_MAX_BYTES in contact-attachments.js */
6
7
  const FINGERPRINT_DATA_URL_MAX_BYTES = 56 * 1024 * 1024;
@@ -736,13 +737,18 @@ export function readContactChannelPage(db, assistantID, { afterOrdinal = 0, gene
736
737
  return db.transaction(() => {
737
738
  const tip = getContactReadTip(db, assistantID);
738
739
  const after = generation === null || generation === tip.generation ? afterOrdinal : 0;
739
- const rows = tipOnly ? [] : db.prepare(`SELECT * FROM assistant_contact_message WHERE assistant_id=? AND ordinal>?
740
- ORDER BY ordinal ASC LIMIT 50`).all(assistantID, after);
740
+ const rows = tipOnly ? [] : db.prepare(`SELECT message.*, source.message_id AS source_user_message_id
741
+ FROM assistant_contact_message message
742
+ LEFT JOIN assistant_contact_message source ON source.message_id=message.turn_id
743
+ AND source.assistant_id=message.assistant_id AND source.role='user'
744
+ WHERE message.assistant_id=? AND message.ordinal>?
745
+ ORDER BY message.ordinal ASC LIMIT 50`).all(assistantID, after);
741
746
  return {
742
747
  generation: tip.generation,
743
748
  tipOrdinal: tip.ordinal,
744
749
  ordinal: rows.at(-1)?.ordinal ?? after,
745
- messages: rows.filter((row) => row.role === 'assistant').map((row) => hydrateMessage(db, row)),
750
+ messages: rows.filter((row) => row.role === 'assistant'
751
+ && (!row.source_user_message_id || isMessageChannelTurn(row.turn_id))).map((row) => hydrateMessage(db, row)),
746
752
  };
747
753
  })();
748
754
  }
@@ -80,6 +80,33 @@ it('channel output feed is ascending, bounded, generation-aware and isolated by
80
80
  } finally { db.close(); }
81
81
  });
82
82
 
83
+ it('keeps Yuri user-turn replies out of external feeds without filtering channel or proactive replies', () => {
84
+ const db = openDb();
85
+ try {
86
+ insert(db, 'a', { role: 'user', messageID: 'app', text: 'hello' });
87
+ insert(db, 'a', { role: 'user', messageID: 'channel:feishu:input', text: 'external' });
88
+ insert(db, 'a', { role: 'assistant', turnID: 'app', text: 'local streamed reply' });
89
+ insert(db, 'a', { role: 'assistant', turnID: 'app', text: 'local error', status: 'error' });
90
+ insert(db, 'a', { role: 'assistant', turnID: 'channel:feishu:input', text: 'external reply' });
91
+ insert(db, 'a', { role: 'assistant', turnID: 'scheduled_result', text: 'proactive result' });
92
+ insert(db, 'b', { role: 'assistant', turnID: 'app', text: 'different Bot' });
93
+ expect(readContactChannelPage(db, 'a').messages.map((message) => message.text)).toEqual(['external reply', 'proactive result']);
94
+ expect(readContactChannelPage(db, 'a', { afterOrdinal: 2 }).messages.map((message) => message.text)).toEqual(['external reply', 'proactive result']);
95
+ expect(readContactChannelPage(db, 'b').messages.map((message) => message.text)).toEqual(['different Bot']);
96
+ insert(db, 'a', { role: 'user', messageID: 'local-only', text: 'hello again' });
97
+ insert(db, 'a', { role: 'assistant', turnID: 'local-only', text: 'local final reply' });
98
+ const filtered = readContactChannelPage(db, 'a', { afterOrdinal: 6 });
99
+ expect(filtered.messages).toEqual([]);
100
+ expect(filtered.ordinal).toBe(8);
101
+ expect(filtered.tipOrdinal).toBe(8);
102
+ const reopened = new (require('better-sqlite3'))(db.name);
103
+ try {
104
+ ensureContactSchema(reopened);
105
+ expect(readContactChannelPage(reopened, 'a').messages.map((message) => message.text)).toEqual(['external reply', 'proactive result']);
106
+ } finally { reopened.close(); }
107
+ } finally { db.close(); }
108
+ });
109
+
83
110
  const insert = (db, assistantID, {
84
111
  role, text = '', parts, status = 'complete', fromAssistantID = null, fromAssistantName = null, turnID = null, messageID = null, createdAt = Date.now(),
85
112
  }) => {