@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
@@ -2,7 +2,7 @@ import fs from 'node:fs';
2
2
  import os from 'node:os';
3
3
  import path from 'node:path';
4
4
  import crypto from 'node:crypto';
5
- import { describe, expect, it, vi } from 'vitest';
5
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
6
6
  import { createRequire } from 'node:module';
7
7
  import { assignedSessionResumeMessageID, createAssistantsService } from './service.js';
8
8
  import { assistantContractFixtures } from './contracts.js';
@@ -12,6 +12,9 @@ import {
12
12
  } from './contact-tools.js';
13
13
  import { runContactTurn as realRunContactTurn } from './harness.js';
14
14
  import { AVATAR_COLORS, resolveAssistantAvatar } from '../../../../ui/src/lib/assistant-avatar/recipe.ts';
15
+ vi.mock('../opencode/native-goal.js', () => ({ getNativeSessionGoal: vi.fn(async () => null) }));
16
+ import { getNativeSessionGoal } from '../opencode/native-goal.js';
17
+ beforeEach(() => { getNativeSessionGoal.mockReset().mockResolvedValue(null); });
15
18
 
16
19
  const require = createRequire(import.meta.url);
17
20
  const root = () => fs.mkdtempSync(path.join(os.tmpdir(), 'assistants-'));
@@ -121,6 +124,11 @@ const assistantInput = { name: 'A', providerID: 'p', modelID: 'm' };
121
124
  const greetingText = "Hi, I'm A. How can I help you?";
122
125
  const toolBatch = (calls, content = '') => ({ completion: { choices: [{ message: { content, tool_calls: calls.map(([name, args, id = `call_${name}`]) => ({ id, type: 'function', function: { name, arguments: JSON.stringify(args) } })) } }] } });
123
126
  const sayThen = (text, name, args) => toolBatch([['notify_user', { text }], [name, args]]);
127
+ const referenceResult = async (tools, result) => {
128
+ const reference = await tools.find((tool) => tool.name === 'reference_resource').execute('reference', JSON.parse(result.content[0].text).reference);
129
+ expect(reference.isError).not.toBe(true);
130
+ return reference.details.card;
131
+ };
124
132
 
125
133
  describe('assistants service', () => {
126
134
  it('persists pins across clients and restarts without changing catalog, session or share-default order', async () => {
@@ -2771,9 +2779,11 @@ describe('assistants service', () => {
2771
2779
  toolBatch([['load_tools', { domain: 'yuri.projects' }]]),
2772
2780
  toolBatch([['register_project', { path: workspace }]]),
2773
2781
  toolBatch([['assign_session', { projectPath: workspace, prompt: 'hello' }]]),
2782
+ toolBatch([['reference_resource', { cardType: 'session', sessionID: 'ses_registered' }]]),
2774
2783
  ];
2775
2784
  const service = setup(directory, {
2776
2785
  create: async (input) => { creates.push(input); return { id: 'ses_registered' }; },
2786
+ get: async ({ sessionID }) => ({ id: sessionID, directory: workspace, title: 'Hello', status: { type: 'busy' } }),
2777
2787
  prompt: async (input) => { prompts.push(input); return { id: 'inbox_hello', type: 'user' }; },
2778
2788
  }, {
2779
2789
  getAllowedRoots: () => projects.map((project) => project.path),
@@ -2827,6 +2837,7 @@ describe('assistants service', () => {
2827
2837
  const prompts = [];
2828
2838
  const archives = [];
2829
2839
  const service = setup(directory, {
2840
+ get: async ({ sessionID }) => ({ id: sessionID, directory: project, title: 'Login', status: { type: 'busy' } }),
2830
2841
  create: async (input) => {
2831
2842
  creates.push(input);
2832
2843
  return { data: { id: `ses_${creates.length}` } };
@@ -2846,7 +2857,7 @@ describe('assistants service', () => {
2846
2857
  return {
2847
2858
  text: 'Opened the login session.',
2848
2859
  bubbles: ['Opened the login session.'],
2849
- cards: result.details.card ? [result.details.card] : [],
2860
+ cards: [await referenceResult(tools, result)],
2850
2861
  tools,
2851
2862
  };
2852
2863
  },
@@ -2889,6 +2900,7 @@ describe('assistants service', () => {
2889
2900
  fs.mkdirSync(project, { recursive: true });
2890
2901
  const creates = [];
2891
2902
  const service = setup(directory, {
2903
+ get: async ({ sessionID }) => ({ id: sessionID, directory: project, title: 'Once', status: { type: 'busy' } }),
2892
2904
  create: async (input) => {
2893
2905
  creates.push(input);
2894
2906
  return { data: { id: `ses_${creates.length}` } };
@@ -2908,7 +2920,7 @@ describe('assistants service', () => {
2908
2920
  return {
2909
2921
  text: first.content[0].text,
2910
2922
  bubbles: [first.content[0].text],
2911
- cards: first.details.card ? [first.details.card, second.details.card].filter(Boolean) : [],
2923
+ cards: [await referenceResult(tools, first), await referenceResult(tools, second)],
2912
2924
  tools,
2913
2925
  };
2914
2926
  },
@@ -3449,7 +3461,7 @@ describe('assistants service', () => {
3449
3461
  return {
3450
3462
  text: '在听',
3451
3463
  bubbles: ['在听'],
3452
- cards: result.details.card ? [result.details.card] : [],
3464
+ cards: [await referenceResult(tools, result)],
3453
3465
  };
3454
3466
  },
3455
3467
  });
@@ -3493,7 +3505,7 @@ describe('assistants service', () => {
3493
3505
  return {
3494
3506
  text: '盯着',
3495
3507
  bubbles: ['盯着'],
3496
- cards: result.details.card ? [result.details.card] : [],
3508
+ cards: [await referenceResult(tools, result)],
3497
3509
  };
3498
3510
  },
3499
3511
  });
@@ -3532,7 +3544,7 @@ describe('assistants service', () => {
3532
3544
  }
3533
3545
  const result = await tools.find((tool) => tool.name === 'watch_session').execute('watch', { sessionID: 'ses_once' });
3534
3546
  expect(result.isError).not.toBe(true);
3535
- return { text: '在听', bubbles: ['在听'], cards: [result.details.card] };
3547
+ return { text: '在听', bubbles: ['在听'], cards: [await referenceResult(tools, result)] };
3536
3548
  },
3537
3549
  };
3538
3550
  const client = { get: async ({ sessionID }) => ({ data: { id: sessionID, directory, status: { type: 'busy' } } }) };
@@ -3796,7 +3808,7 @@ describe('assistants service', () => {
3796
3808
  return {
3797
3809
  text: 'Created FlowQA.',
3798
3810
  bubbles: ['Created FlowQA.'],
3799
- cards: result.details.card ? [result.details.card] : [],
3811
+ cards: [await referenceResult(tools, result)],
3800
3812
  tools,
3801
3813
  };
3802
3814
  },
@@ -4061,7 +4073,8 @@ describe('assistants service', () => {
4061
4073
  expect(missing.details.error).toBe('model_not_found');
4062
4074
  expect(patches).toEqual([{ projectID: 'proj_a', taskID: 'task_a', patch: { execution: { providerID: 'new-provider', modelID: 'new-model' } } }]);
4063
4075
  expect(synced).toEqual(['proj_a']);
4064
- expect(updated.details.card).toMatchObject({ taskID: 'task_a' });
4076
+ expect(updated.details.card).toBeUndefined();
4077
+ expect(JSON.parse(updated.content[0].text).reference).toEqual({ cardType: 'schedule', projectID: 'proj_a', taskID: 'task_a' });
4065
4078
  service.close();
4066
4079
  });
4067
4080
 
@@ -4070,6 +4083,7 @@ describe('assistants service', () => {
4070
4083
  const upserts = [];
4071
4084
  const service = setup(directory, {}, {
4072
4085
  listProjects: async () => [{ id: 'proj_app', path: directory }],
4086
+ listScheduledTasks: async () => upserts.map(({ task }) => ({ ...task, id: 'task_ping' })),
4073
4087
  upsertScheduledTask: async (projectID, task) => {
4074
4088
  upserts.push({ projectID, task });
4075
4089
  return {
@@ -4095,7 +4109,7 @@ describe('assistants service', () => {
4095
4109
  return {
4096
4110
  text: 'Scheduled the ping.',
4097
4111
  bubbles: ['Scheduled the ping.'],
4098
- cards: result.details.card ? [result.details.card] : [],
4112
+ cards: [await referenceResult(tools, result)],
4099
4113
  tools,
4100
4114
  };
4101
4115
  },
@@ -4132,7 +4146,7 @@ describe('assistants service', () => {
4132
4146
  assistantID: host.id,
4133
4147
  projectID: 'proj_app',
4134
4148
  taskID: 'task_ping',
4135
- task: null,
4149
+ task: expect.objectContaining({ id: 'task_ping' }),
4136
4150
  })]);
4137
4151
  service.close();
4138
4152
  });
@@ -6644,12 +6658,12 @@ describe('read_session referenced conversation', () => {
6644
6658
  if (userText === 'watch') {
6645
6659
  const watch = tools.find((tool) => tool.name === 'watch_session');
6646
6660
  const result = await watch.execute('call_w', { sessionID: 'ses_abort_race' });
6647
- return { text: '盯着', bubbles: ['盯着'], cards: result.details.card ? [result.details.card] : [] };
6661
+ return { text: '盯着', bubbles: ['盯着'], cards: [await referenceResult(tools, result)] };
6648
6662
  }
6649
6663
  if (userText === 'peer watch') {
6650
6664
  const watch = tools.find((tool) => tool.name === 'watch_session');
6651
6665
  const result = await watch.execute('call_peer_w', { sessionID: 'ses_abort_race' });
6652
- return { text: 'peer盯', bubbles: ['peer盯'], cards: result.details.card ? [result.details.card] : [] };
6666
+ return { text: 'peer盯', bubbles: ['peer盯'], cards: [await referenceResult(tools, result)] };
6653
6667
  }
6654
6668
  const stop = tools.find((tool) => tool.name === 'stop_session');
6655
6669
  const stopPromise = stop.execute('call_s', { sessionID: 'ses_abort_race' });
@@ -6721,13 +6735,13 @@ describe('read_session referenced conversation', () => {
6721
6735
  }
6722
6736
  if (userText === 'watch both') {
6723
6737
  const watch = tools.find((tool) => tool.name === 'watch_session');
6724
- await watch.execute('w1', { sessionID: 'ses_fail_abort' });
6725
- await watch.execute('w2', { sessionID: 'ses_other_worker' });
6738
+ await referenceResult(tools, await watch.execute('w1', { sessionID: 'ses_fail_abort' }));
6739
+ await referenceResult(tools, await watch.execute('w2', { sessionID: 'ses_other_worker' }));
6726
6740
  return { text: '双盯', bubbles: ['双盯'], cards: [] };
6727
6741
  }
6728
6742
  if (userText === 'peer watch fail') {
6729
6743
  const watch = tools.find((tool) => tool.name === 'watch_session');
6730
- await watch.execute('peer_w', { sessionID: 'ses_fail_abort' });
6744
+ await referenceResult(tools, await watch.execute('peer_w', { sessionID: 'ses_fail_abort' }));
6731
6745
  return { text: 'peer盯', bubbles: ['peer盯'], cards: [] };
6732
6746
  }
6733
6747
  const stop = tools.find((tool) => tool.name === 'stop_session');
@@ -6797,12 +6811,12 @@ describe('read_session referenced conversation', () => {
6797
6811
  if (userText === 'watch') {
6798
6812
  const watch = tools.find((tool) => tool.name === 'watch_session');
6799
6813
  const result = await watch.execute('w', { sessionID: 'ses_silent' });
6800
- return { text: '盯', bubbles: ['盯'], cards: result.details.card ? [result.details.card] : [] };
6814
+ return { text: '盯', bubbles: ['盯'], cards: [await referenceResult(tools, result)] };
6801
6815
  }
6802
6816
  if (userText === 'peer silent watch') {
6803
6817
  const watch = tools.find((tool) => tool.name === 'watch_session');
6804
6818
  const result = await watch.execute('peer_silent', { sessionID: 'ses_silent' });
6805
- return { text: 'peer盯', bubbles: ['peer盯'], cards: result.details.card ? [result.details.card] : [] };
6819
+ return { text: 'peer盯', bubbles: ['peer盯'], cards: [await referenceResult(tools, result)] };
6806
6820
  }
6807
6821
  const stop = tools.find((tool) => tool.name === 'stop_session');
6808
6822
  const result = await stop.execute('s', { sessionID: 'ses_silent' });
@@ -28,6 +28,9 @@ service protocol. No OpenClaw runtime or new dependency is installed.
28
28
  and MIME identification; no arbitrary URL fetch or credential forwarding.
29
29
  - `toon.js`: local JSON-only TOON encoder (objects, lists, primitive/tabular
30
30
  arrays); no new dependency, key folding, raw-string emission or decoding API.
31
+ - `../channel-output.js` / `../channel-image.js`: shared published-image projection
32
+ and bounded image materialization for all four channels; no WeChat-only output
33
+ parser or second attachment store.
31
34
  - `assistants/service.channelPage()` is an internal bounded, ascending durable
32
35
  output seam. It validates the Bot and uses the contact-store generation. It does
33
36
  not expose credentials or replace the contact execution engine.
@@ -132,17 +135,36 @@ data directory cannot steal a live account. After any network wait, epoch/lease
132
135
  checks fence stale writes. Cross-machine copies of credentials/data are unsupported.
133
136
 
134
137
  Binding starts at the current contact tip, so existing history/greetings are not
135
- sent. Subsequent **public assistant replies**, including App-initiated and background
136
- task replies, sync to the paired owner. Plain text is sent as text; current cards
137
- become title/name text, not interactive WeChat cards or deeplinks. Internal settle
138
+ sent. Subsequent **public assistant replies eligible for external delivery**,
139
+ including background task replies, sync to the paired owner. Built-in Yuri IM
140
+ replies are excluded by the shared contact feed and stay in their conversation.
141
+ Plain text is sent as text; internal cards
142
+ are unsupported output and silently skipped, with no title/link/deeplink fallback,
143
+ error notice or retry. They remain visible in Yuri. Internal settle
138
144
  markers are omitted and failures use a safe generic message, never raw tool errors.
145
+ Published Markdown images and image file parts are sent as native images, in order
146
+ with surrounding text, subject to the same original-channel routing. Images are
147
+ snapshotted to owned contact attachments before the feed watermark commits; the
148
+ additive outbox `image` column stores only opaque descriptors (legacy rows remain
149
+ text). Restart/retry reads immutable snapshot bytes, not a possibly deleted source
150
+ file. `api.sendImage()` obtains upload parameters, AES-128-ECB/PKCS#7 encrypts the
151
+ bytes, and POSTs only to the fixed official `/c2c/upload` CDN without bot credentials.
152
+ Only HTTP 200 plus `x-encrypted-param` permits the final `type: 2` image send with
153
+ the stable delivery client ID and reply context. Upload failure is not an ambiguous
154
+ chat send; a failed final send keeps the existing blocked/unknown semantics. A
155
+ definite failure produces a safe text notice and does not discard later output.
156
+ The adapter rechecks generation/ownership after upload before sending. Source,
157
+ size, SSRF and format bounds are documented in `../DOCUMENTATION.md`.
139
158
  Generation reset drops queued output from the previous transcript. An already submitted HTTP request
140
159
  cannot be recalled, including during disconnect/reset.
141
160
 
142
161
  ### Rich inbound content
143
162
 
144
163
  - Plain text retains the ordinary text path. Item protocol IDs (`msg_id`) and
145
- envelope fields such as timestamps do not create a separate TOON text part.
164
+ envelope fields such as timestamps, completion/routing fields, root/parent IDs,
165
+ and empty button lists do not create a separate TOON text part. Private-only
166
+ extensions are omitted after projection; actual share fields, quotes and
167
+ nonempty buttons still retain their content.
146
168
  Every recognized image, voice, file
147
169
  and video item is represented; mixed items no longer silently lose media. An
148
170
  item-level `msg_id` is accepted when the top-level message ID is absent, matching
@@ -197,10 +219,12 @@ expiry or transcript reset. Successfully staged attachments follow the existing
197
219
  contact attachment lifecycle, including its normal unreferenced-object behavior.
198
220
 
199
221
  Replies are split by Unicode code points into at most 3500-character segments;
200
- stable client IDs and ordered outbox rows survive restart. This is not a server-side
201
- exactly-once guarantee. An uncertain HTTP result is marked **delivery unknown** and
202
- blocks later output until the owner explicitly retries. New inbound context may
203
- unblock a known rejected reply but never automatically retries an unknown send.
222
+ stable client IDs and ordered pending outbox rows survive restart. This is not a server-side
223
+ exactly-once guarantee. An uncertain HTTP result is marked **delivery unknown**;
224
+ it and definitively blocked replies remain durable but do not block later pending
225
+ output, Bot execution or receiving. Later successful sends do not hide unresolved
226
+ delivery errors. New inbound context may unblock a known rejected reply but never
227
+ automatically retries an unknown send.
204
228
  Authentication expiry stays expired until new authorization; receiver network errors
205
229
  retry with 1–30 second capped backoff. Users can manually retry other blocked sends.
206
230
  The platform's reply-context lifetime and active-push quota are not specified here.
@@ -222,7 +246,8 @@ content and stale runtime mutations cannot overwrite a new Host's cache.
222
246
  ### Typing presence
223
247
 
224
248
  Only live `yuri:contact-turn-start/end` events drive typing, including App-initiated
225
- or background contact turns without a channel source, which may push to WeChat.
249
+ or background contact turns. Presence is separate from output routing: built-in
250
+ Yuri IM replies are never pushed to WeChat.
226
251
  Replies to channel-originated turns require an exact receipt in this binding:
227
252
  WeChat inputs reply only here, and enterprise-channel inputs never broadcast here.
228
253
  The persisted contact turn ID identifies the original admitted input across restart.
@@ -1,4 +1,4 @@
1
- import { randomBytes } from 'node:crypto';
1
+ import { createHash, createCipheriv, randomBytes } from 'node:crypto';
2
2
  import { downloadWeixinMedia } from './media.js';
3
3
 
4
4
  // Wire-format reference: Tencent/openclaw-weixin (MIT), docs/protocol.md.
@@ -103,6 +103,48 @@ export function createWeixinAPI({ fetchImpl = fetch } = {}) {
103
103
  token: binding.token, signal, timeoutMs: 5000, allowEmpty: true,
104
104
  body: { ilink_user_id: binding.peer_id, typing_ticket: ticket, status },
105
105
  }),
106
+ sendImage: async (binding, delivery, signal) => {
107
+ const buffer = delivery.image?.buffer;
108
+ if (!Buffer.isBuffer(buffer) || !buffer.length || buffer.length > 20 * 1024 * 1024) throw new WeixinError('validation_error');
109
+ const key = randomBytes(16);
110
+ const filekey = randomBytes(16).toString('hex');
111
+ const cipher = createCipheriv('aes-128-ecb', key, null);
112
+ const encrypted = Buffer.concat([cipher.update(buffer), cipher.final()]);
113
+ const uploaded = await request(binding.base_url, '/ilink/bot/getuploadurl', {
114
+ token: binding.token, signal,
115
+ body: { filekey, media_type: 1, to_user_id: binding.peer_id, rawsize: buffer.length,
116
+ rawfilemd5: createHash('md5').update(buffer).digest('hex'), filesize: encrypted.length,
117
+ no_need_thumb: true, aeskey: key.toString('hex') },
118
+ });
119
+ const url = new URL(uploaded.upload_full_url || 'https://novac2c.cdn.weixin.qq.com/c2c/upload');
120
+ if (!uploaded.upload_full_url) {
121
+ if (typeof uploaded.upload_param !== 'string' || !uploaded.upload_param) throw new WeixinError('invalid_response');
122
+ url.searchParams.set('encrypted_query_param', uploaded.upload_param);
123
+ url.searchParams.set('filekey', filekey);
124
+ }
125
+ if (url.protocol !== 'https:' || url.hostname !== 'novac2c.cdn.weixin.qq.com' || url.port
126
+ || url.username || url.password || url.hash || url.pathname !== '/c2c/upload') throw new WeixinError('invalid_response');
127
+ const uploadSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(20_000)]) : AbortSignal.timeout(20_000);
128
+ uploadSignal.throwIfAborted();
129
+ let response;
130
+ try {
131
+ response = await fetchImpl(url.href, { method: 'POST', body: encrypted, redirect: 'error',
132
+ headers: { 'Content-Type': 'application/octet-stream' }, signal: uploadSignal });
133
+ } catch { throw new WeixinError(signal?.aborted ? 'cancelled' : 'network_error'); }
134
+ await response.body?.cancel().catch(() => {});
135
+ const param = response.headers.get('x-encrypted-param');
136
+ if (response.status !== 200 || !param || param.length > 65_536) throw new WeixinError('invalid_response');
137
+ uploadSignal.throwIfAborted();
138
+ delivery.beforeSend?.();
139
+ return request(binding.base_url, '/ilink/bot/sendmessage', {
140
+ token: binding.token, signal, sending: true,
141
+ body: { msg: { from_user_id: '', to_user_id: binding.peer_id, client_id: delivery.id,
142
+ message_type: 2, message_state: 2, context_token: binding.context_token || undefined,
143
+ item_list: [{ type: 2, image_item: { media: { encrypt_query_param: param,
144
+ aes_key: Buffer.from(key.toString('hex')).toString('base64'), encrypt_type: 1 }, mid_size: encrypted.length } }],
145
+ } },
146
+ });
147
+ },
106
148
  sendText: (binding, delivery, signal) => request(binding.base_url, '/ilink/bot/sendmessage', {
107
149
  token: binding.token, signal, sending: true,
108
150
  body: { msg: {
@@ -1,9 +1,37 @@
1
1
  import { describe, expect, it, vi } from 'vitest';
2
2
  import { createWeixinAPI, weixinOrigin } from './api.js';
3
+ import { createDecipheriv, createHash } from 'node:crypto';
3
4
 
4
5
  const binding = { base_url: 'https://ilinkai.weixin.qq.com', token: 'test-token', peer_id: 'owner', cursor: 'cursor', context_token: 'context' };
5
6
 
6
7
  describe('Weixin wire transport', () => {
8
+ it('encrypts/uploads the image without bot credentials on CDN, then sends a native image with stable ID', async () => {
9
+ const buffer = Buffer.from('image bytes');
10
+ const fetchImpl = vi.fn(async (url) => String(url).includes('getuploadurl') ? Response.json({ ret: 0, upload_param: 'upload-capability' })
11
+ : String(url).includes('/c2c/upload') ? new Response(null, { headers: { 'x-encrypted-param': 'download-capability' } }) : Response.json({ ret: 0 }));
12
+ await createWeixinAPI({ fetchImpl }).sendImage(binding, { id: 'image-stable', image: { buffer } });
13
+ const uploadRequest = JSON.parse(fetchImpl.mock.calls[0][1].body);
14
+ expect(uploadRequest).toMatchObject({ media_type: 1, to_user_id: 'owner', rawsize: buffer.length, rawfilemd5: createHash('md5').update(buffer).digest('hex'), no_need_thumb: true });
15
+ const [cdnURL, cdn] = fetchImpl.mock.calls[1];
16
+ expect(new URL(cdnURL).searchParams.get('encrypted_query_param')).toBe('upload-capability');
17
+ expect(cdn.headers.Authorization).toBeUndefined();
18
+ expect(cdn.redirect).toBe('error');
19
+ const decrypt = createDecipheriv('aes-128-ecb', Buffer.from(uploadRequest.aeskey, 'hex'), null);
20
+ expect(Buffer.concat([decrypt.update(cdn.body), decrypt.final()])).toEqual(buffer);
21
+ expect(JSON.parse(fetchImpl.mock.calls[2][1].body).msg).toMatchObject({ client_id: 'image-stable', to_user_id: 'owner', context_token: 'context',
22
+ item_list: [{ type: 2, image_item: { media: { encrypt_query_param: 'download-capability', aes_key: Buffer.from(uploadRequest.aeskey).toString('base64'), encrypt_type: 1 }, mid_size: cdn.body.length } }] });
23
+ });
24
+
25
+ it('never sends an image after a rejected upload, unsafe CDN or stale generation', async () => {
26
+ for (const mode of ['unsafe', 'missing-header', 'stale']) {
27
+ const fetchImpl = vi.fn(async (url) => String(url).includes('getuploadurl')
28
+ ? Response.json(mode === 'unsafe' ? { upload_full_url: 'https://127.0.0.1/c2c/upload' } : { upload_param: 'opaque' })
29
+ : new Response(null, { headers: mode === 'stale' ? { 'x-encrypted-param': 'download' } : {} }));
30
+ await expect(createWeixinAPI({ fetchImpl }).sendImage(binding, { id: 'id', image: { buffer: Buffer.from('image') },
31
+ beforeSend: () => { throw new Error('cancelled'); } })).rejects.toThrow();
32
+ expect(fetchImpl.mock.calls.some(([url]) => String(url).endsWith('sendmessage'))).toBe(false);
33
+ }
34
+ });
7
35
  it('uses QR POST, app headers and private local-token hints without bot authorization', async () => {
8
36
  const fetchImpl = vi.fn(async () => Response.json({ qrcode: 'opaque', qrcode_img_content: 'https://example.com/qr' }));
9
37
  await createWeixinAPI({ fetchImpl }).getQRCode(undefined, ['existing']);
@@ -75,11 +75,17 @@ export function createWeixinChatAdapter({ api, getBinding, clock = Date.now }) {
75
75
  return message;
76
76
  },
77
77
  renderFormatted: (content) => stringifyMarkdown(content),
78
- postMessage: async (threadID, message, { id = `yuri_${randomUUID()}`, signal } = {}) => {
78
+ postMessage: async (threadID, message, { id = `yuri_${randomUUID()}`, signal, beforeSend } = {}) => {
79
79
  const current = binding();
80
80
  const target = decodeThreadId(threadID);
81
81
  if (target.accountID !== current.account_id || target.peerID !== current.peer_id) throw new WeixinError('validation_error');
82
- if (message?.files?.length || message?.attachments?.length) return unsupported();
82
+ if (message?.files?.length) {
83
+ if (message.files.length !== 1 || !message.files[0]?.mimeType?.startsWith('image/') || !Buffer.isBuffer(message.files[0].data)) return unsupported();
84
+ const file = message.files[0];
85
+ await api.sendImage(current, { id, image: { buffer: file.data, mime: file.mimeType, filename: file.filename }, beforeSend }, signal);
86
+ return { id, raw: { id } };
87
+ }
88
+ if (message?.attachments?.length) return unsupported();
83
89
  const text = typeof message === 'string' ? message : typeof message?.raw === 'string' ? message.raw
84
90
  : typeof message?.markdown === 'string' ? message.markdown : message?.ast ? stringifyMarkdown(message.ast) : null;
85
91
  if (text === null) return unsupported();
@@ -4,7 +4,7 @@ import { CONTACT_ATTACHMENT_TURN_BUDGET_BYTES } from '../contact-attachments.js'
4
4
 
5
5
  const kinds = { 1: 'text', 2: 'image', 3: 'voice', 4: 'file', 5: 'video' };
6
6
  const privateField = /token|ticket|aes|encrypt|authorization|cookie|password|secret|credential|signature|^sig$|(?:^|_)auth(?:_|$)|(?:^|_)key$|full_url|^media$|^thumb_media$|^base_info$|^__proto__$|^constructor$|^prototype$/i;
7
- const envelope = new Set(['item_list', 'message_id', 'from_user_id', 'to_user_id', 'message_type', 'message_state', 'seq', 'session_id', 'client_id', 'create_time_ms', 'update_time_ms', 'delete_time_ms', 'group_id', 'run_id']);
7
+ const envelope = new Set(['item_list', 'message_id', 'msg_id', 'from_user_id', 'to_user_id', 'message_type', 'message_state', 'seq', 'session_id', 'client_id', 'create_time_ms', 'update_time_ms', 'delete_time_ms', 'group_id', 'run_id', 'root_id', 'parent_id', 'is_completed', 'at_bot_username_list']);
8
8
 
9
9
  function contentProjection() {
10
10
  let remaining = 24_000;
@@ -64,14 +64,16 @@ export function normalizeWeixinInput(message) {
64
64
  const body = item[`${kind}_item`];
65
65
  if (kind === 'text' && typeof body?.text === 'string' && !quoted) texts.push(body.text);
66
66
  const index = items.length;
67
- const details = Object.fromEntries(Object.entries(item).filter(([key]) => key !== 'ref_msg' && key !== 'msg_id' && !envelope.has(key) && !(kind === 'text' && key === 'text_item')));
67
+ const details = Object.fromEntries(Object.entries(item).filter(([key, value]) => key !== 'ref_msg' && !envelope.has(key)
68
+ && !(key === 'button_item_list' && Array.isArray(value) && value.length === 0)
69
+ && !(kind === 'text' && key === 'text_item')));
68
70
  if (kind === 'text' && body && typeof body === 'object') {
69
71
  const extraTextFields = Object.fromEntries(Object.entries(body).filter(([key]) => key !== 'text'));
70
72
  if (Object.keys(extraTextFields).length) details.text_item = extraTextFields;
71
73
  }
72
74
  const content = projection.visit(quoted ? { ...details, text_item: item.text_item } : details);
73
75
  const entry = { ...content, kind, ...(quoted ? { quoted: true } : {}) };
74
- if (kind !== 'text' || quoted || Object.keys(details).some((key) => key !== 'type')) items.push(entry);
76
+ if (kind !== 'text' || quoted || Object.keys(content || {}).some((key) => key !== 'type')) items.push(entry);
75
77
  if (['image', 'voice', 'file', 'video'].includes(kind)) {
76
78
  entry.mediaStatus = 'unavailable';
77
79
  if (kind === 'voice') entry.transcription = typeof entry.voice_item?.text === 'string' && entry.voice_item.text.trim() ? 'provided' : 'unavailable';
@@ -12,6 +12,16 @@ const prepare = async (message, overrides = {}) => {
12
12
  };
13
13
 
14
14
  describe('WeChat rich input projection', () => {
15
+ it('keeps a real plain-text envelope as one text part without transport-only metadata', async () => {
16
+ const message = { message_id: 'message-id', root_id: 0, parent_id: 0,
17
+ item_list: [{ type: 1, create_time_ms: 123, update_time_ms: 123, is_completed: true,
18
+ msg_id: 'item-id', button_item_list: [], at_bot_username_list: [],
19
+ text_item: { text: 'https://mp.weixin.qq.com/s/example' } }] };
20
+ const result = await prepare(message);
21
+ expect(result.receipt.payload).toBe('');
22
+ expect(result.parts).toEqual([{ type: 'text', text: 'https://mp.weixin.qq.com/s/example' }]);
23
+ });
24
+
15
25
  it('does not turn ordinary text item protocol IDs into a TOON message', async () => {
16
26
  const message = { message_id: 'message-id', from_user_id: 'owner', create_time_ms: 123,
17
27
  item_list: [{ type: 1, msg_id: 'item-id', create_time_ms: 123, text_item: { text: 'halo' } }] };
@@ -28,6 +38,16 @@ describe('WeChat rich input projection', () => {
28
38
  expect(result.api.downloadMedia).not.toHaveBeenCalled();
29
39
  });
30
40
 
41
+ it('omits private-only text fields but retains actual button and article content', async () => {
42
+ const plain = await prepare({ item_list: [{ type: 1, text_item: { text: 'hello' }, private_token: 'not-content' }] });
43
+ expect(plain.parts).toEqual([{ type: 'text', text: 'hello' }]);
44
+ const rich = await prepare({ root_id: 0, parent_id: 0, article: { title: 'Article', url: 'https://mp.weixin.qq.com/s/example' },
45
+ item_list: [{ type: 1, text_item: { text: 'hello' }, button_item_list: [{ title: 'Open article' }] }] });
46
+ expect(rich.parts.at(-1).text).toContain('Open article');
47
+ expect(rich.parts.at(-1).text).toContain('Article');
48
+ expect(rich.parts.at(-1).text).not.toMatch(/root_id|parent_id/);
49
+ });
50
+
31
51
  it('keeps every mixed item, inline quote and article extension as data while stripping transport secrets', async () => {
32
52
  const { parts } = await prepare({ context_token: 'private-context', bot_token: 'private-token', item_list: [
33
53
  { type: 1, text_item: { text: '看看这篇' }, ref_msg: { title: '原消息', svr_id: 'quoted-id', message_item: { type: 1, text_item: { text: '引用文字' } } } },
@@ -6,14 +6,9 @@ import { createWeixinTyping } from './typing.js';
6
6
  import { prepareWeixinInput } from './inbound.js';
7
7
  import { createWeixinChatAdapter } from './chat-adapter.js';
8
8
  import { isMessageChannelTurn } from '../message-channel-origin.js';
9
+ import { prepareChannelOutput, readChannelDeliveryImage, channelImageFailure } from '../channel-output.js';
9
10
 
10
11
  const digest = (value) => createHash('sha256').update(value).digest('hex');
11
- const chunks = (text) => {
12
- const chars = Array.from(text);
13
- const result = [];
14
- for (let index = 0; index < chars.length; index += 3500) result.push(chars.slice(index, index + 3500).join(''));
15
- return result;
16
- };
17
12
  const feedback = (language, kind) => {
18
13
  const messages = language.startsWith('zh') ? {
19
14
  interrupted: 'Yuri 主机已重启,上一条请求可能未完成。请先检查任务状态,再决定是否重试。',
@@ -176,15 +171,21 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
176
171
  throw error;
177
172
  }
178
173
  if (binding.status === 'expired') return;
179
- const deliveries = page.messages.flatMap((message) => {
180
- if (isMessageChannelTurn(message.turnID) && !store.hasReceipt(message.turnID, binding.epoch)) return [];
181
- const text = message.status === 'error' ? feedback(binding.language, 'failed')
182
- : message.text?.trim() && !message.text.trim().startsWith('oc.settle.') ? message.text.trim()
183
- : message.cards.map((card) => card.title || card.name || '').filter(Boolean).join('\n');
184
- return chunks(text).map((chunk, index) => ({
185
- id: `yuri_${digest(`${binding.epoch}:${page.generation}:${message.messageID}:${index}`)}`, text: chunk,
186
- }));
187
- });
174
+ const deliveries = [];
175
+ const receiverSignal = receivers.get(binding.assistant_id)?.controller.signal;
176
+ const signal = receiverSignal ? AbortSignal.any([lifetime.signal, receiverSignal]) : lifetime.signal;
177
+ const assertCurrent = () => {
178
+ if (!isCurrent(binding) || service.channelPage(binding.assistant_id, { tipOnly: true }).generation !== page.generation) throw new WeixinError('cancelled');
179
+ };
180
+ for (const message of page.messages) {
181
+ if (isMessageChannelTurn(message.turnID) && !store.hasReceipt(message.turnID, binding.epoch)) continue;
182
+ const output = await prepareChannelOutput(message, { service, assistantID: binding.assistant_id,
183
+ generation: page.generation, language: binding.language, failureText: feedback(binding.language, 'failed'), signal, assertCurrent });
184
+ deliveries.push(...output.map((part, index) => ({
185
+ id: `yuri_${digest(`${binding.epoch}:${page.generation}:${message.messageID}:${index}`)}`, ...part,
186
+ })));
187
+ }
188
+ assertCurrent();
188
189
  store.collect(binding, page, deliveries);
189
190
  if (!inboundWork.has(binding.assistant_id)) {
190
191
  const work = track(processIncoming(binding, page.generation)).catch((error) => setError(binding, error));
@@ -202,11 +203,16 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
202
203
  const receiverSignal = receivers.get(binding.assistant_id)?.controller.signal;
203
204
  const adapter = createWeixinChatAdapter({ api, clock, getBinding: () => isCurrent(binding) ? store.get(binding.assistant_id) : null });
204
205
  const threadID = await adapter.openDM(current.peer_id);
205
- await adapter.postMessage(threadID, delivery.text, { id: delivery.id,
206
- signal: receiverSignal ? AbortSignal.any([lifetime.signal, receiverSignal]) : lifetime.signal });
206
+ const signal = receiverSignal ? AbortSignal.any([lifetime.signal, receiverSignal]) : lifetime.signal;
207
+ const image = await readChannelDeliveryImage(service, binding.assistant_id, delivery.image ? JSON.parse(delivery.image) : null, signal);
208
+ assertCurrent();
209
+ signal.throwIfAborted();
210
+ await adapter.postMessage(threadID, image ? { raw: '', files: [{ data: image.buffer, mimeType: image.mime, filename: image.filename }] } : delivery.text,
211
+ { id: delivery.id, signal, beforeSend: assertCurrent });
207
212
  if (!isCurrent(binding) && !(retiring.has(binding.assistant_id) && canControl(binding))) return;
208
213
  store.sent(delivery.id);
209
- store.patch(binding.epoch, { error: null, updated_at: clock() });
214
+ store.patch(binding.epoch, { error: store.hasUnknown(binding.epoch) ? 'delivery_unknown'
215
+ : store.hasBlocked(binding.epoch) ? 'reply_unavailable' : null, updated_at: clock() });
210
216
  } catch (error) {
211
217
  if (!isCurrent(binding)) {
212
218
  if (retiring.has(binding.assistant_id) && canControl(binding)) {
@@ -220,6 +226,9 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
220
226
  }
221
227
  // Network ambiguity is user-retryable, not an automatic duplicate reply.
222
228
  store.markDelivery(delivery.id, error?.ambiguous ? 'unknown' : 'blocked');
229
+ if (delivery.image && !error?.ambiguous) {
230
+ store.enqueue(binding.epoch, `${delivery.id}:image-failed`, channelImageFailure(binding.language));
231
+ }
223
232
  setError(binding, error?.ambiguous ? new WeixinError('delivery_unknown') : error);
224
233
  }
225
234
  };
@@ -58,6 +58,25 @@ function fixture({ directory = root(), configureAPI, service: externalService, c
58
58
  }
59
59
 
60
60
  describe('Weixin Host runtime', () => {
61
+ it('delivers a generated image natively, ordered with prose, only on its source channel', async () => {
62
+ const f = fixture();
63
+ f.api.sendImage = vi.fn(async () => ({ ret: 0 }));
64
+ f.service.prepareChannelImage = vi.fn(async () => ({ attachmentID: 'att_generated' }));
65
+ f.service.getAssistantContactAttachment = vi.fn(async () => ({ buffer: Buffer.from('image'), mime: 'image/png', filename: 'generated.png' }));
66
+ f.updates.push([inbound('draw')]);
67
+ await f.bind();
68
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledOnce());
69
+ const turnID = f.service.send.mock.calls[0][1].messageID;
70
+ f.pages.set('bot', { generation: 0, messages: [
71
+ { ordinal: 1, messageID: 'foreign', turnID: 'channel:wecom:foreign', text: '![foreign](/foreign.png)', cards: [], status: 'complete' },
72
+ { ordinal: 2, messageID: 'own', turnID, text: 'Before ![generated](/generated.png) after', cards: [], status: 'complete' },
73
+ ] });
74
+ await vi.waitFor(() => expect(f.api.sendImage).toHaveBeenCalledOnce());
75
+ await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(2));
76
+ expect(f.api.sendText.mock.calls.map(([, part]) => part.text)).toEqual(['Before', 'after']);
77
+ expect(f.api.sendImage.mock.calls[0][1]).toMatchObject({ image: { buffer: Buffer.from('image') } });
78
+ expect(f.service.prepareChannelImage).toHaveBeenCalledOnce();
79
+ });
61
80
  it('does not broadcast other channel replies to WeChat but pushes source-less messages', async () => {
62
81
  const f = fixture();
63
82
  f.updates.push([inbound('own-turn')]);
@@ -189,6 +208,23 @@ describe('Weixin Host runtime', () => {
189
208
  expect(f.api.sendText.mock.calls[1][1].id).toBe(originalId);
190
209
  });
191
210
 
211
+ it.each([false, true])('a rejected or uncertain notification send does not block later text or Bot input (ambiguous=%s)', async (ambiguous) => {
212
+ const f = fixture({ configureAPI: (api) => api.sendText.mockRejectedValueOnce(new WeixinError('reply_unavailable', { ambiguous })) });
213
+ f.updates.push([inbound()]);
214
+ await f.bind();
215
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledOnce());
216
+ f.pages.set('bot', { generation: 0, messages: [
217
+ { ordinal: 1, messageID: 'notification', text: 'Article notes', cards: [], status: 'complete' },
218
+ { ordinal: 2, messageID: 'result', text: 'Note saved', cards: [], status: 'complete' },
219
+ ] });
220
+ await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(2));
221
+ expect(f.api.sendText.mock.calls.map(([, delivery]) => delivery.text)).toEqual(['Article notes', 'Note saved']);
222
+ expect(f.runtime.status('bot').error).toBe(ambiguous ? 'delivery_unknown' : 'reply_unavailable');
223
+ f.updates.push([inbound('next')]);
224
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(2));
225
+ expect(f.api.sendText.mock.calls.filter(([, delivery]) => delivery.text === 'Note saved')).toHaveLength(1);
226
+ });
227
+
192
228
  it('shutdown cancels a hanging platform read before closing storage', async () => {
193
229
  const f = fixture({ configureAPI: (api) => api.getUpdates.mockImplementation((_binding, signal) => abortable(signal)) });
194
230
  await f.bind();
@@ -37,6 +37,9 @@ export function createWeixinStore(directory) {
37
37
  if (!db.prepare('PRAGMA table_info(inbox)').all().some((column) => column.name === 'payload')) {
38
38
  db.exec("ALTER TABLE inbox ADD COLUMN payload TEXT NOT NULL DEFAULT ''");
39
39
  }
40
+ if (!db.prepare('PRAGMA table_info(outbox)').all().some((column) => column.name === 'image')) {
41
+ db.exec("ALTER TABLE outbox ADD COLUMN image TEXT NOT NULL DEFAULT ''");
42
+ }
40
43
  const get = (assistantID) => db.prepare('SELECT * FROM binding WHERE assistant_id=?').get(assistantID) ?? null;
41
44
  const patch = (epoch, values) => {
42
45
  const allowed = new Set(['cursor', 'context_token', 'generation', 'ordinal', 'status', 'error', 'updated_at']);
@@ -44,7 +47,7 @@ export function createWeixinStore(directory) {
44
47
  if (!keys.length) return;
45
48
  db.prepare(`UPDATE binding SET ${keys.map((key) => `${key}=?`).join(',')} WHERE epoch=?`).run(...keys.map((key) => values[key]), epoch);
46
49
  };
47
- const enqueue = (epoch, id, text) => db.prepare('INSERT OR IGNORE INTO outbox(id,epoch,text) VALUES (?,?,?)').run(id, epoch, text);
50
+ const enqueue = (epoch, id, text, image = '') => db.prepare('INSERT OR IGNORE INTO outbox(id,epoch,text,image) VALUES (?,?,?,?)').run(id, epoch, text, image);
48
51
  const unlink = db.transaction((assistantID) => {
49
52
  const binding = get(assistantID);
50
53
  if (!binding) return;
@@ -101,15 +104,16 @@ export function createWeixinStore(directory) {
101
104
  collect: db.transaction((binding, page, deliveries) => {
102
105
  if (get(binding.assistant_id)?.epoch !== binding.epoch) return;
103
106
  if (binding.generation !== page.generation) db.prepare('DELETE FROM outbox WHERE epoch=?').run(binding.epoch);
104
- for (const delivery of deliveries) enqueue(binding.epoch, delivery.id, delivery.text);
107
+ for (const delivery of deliveries) enqueue(binding.epoch, delivery.id, delivery.text, delivery.image ? JSON.stringify(delivery.image) : '');
105
108
  patch(binding.epoch, { generation: page.generation, ordinal: page.ordinal });
106
109
  }),
107
- nextDelivery: (epoch) => db.prepare("SELECT * FROM outbox WHERE epoch=? AND state!='sent' ORDER BY sequence LIMIT 1").get(epoch),
110
+ nextDelivery: (epoch) => db.prepare("SELECT * FROM outbox WHERE epoch=? AND state='pending' ORDER BY sequence LIMIT 1").get(epoch),
108
111
  markDelivery: (id, state) => db.prepare('UPDATE outbox SET state=? WHERE id=?').run(state, id),
109
- sent: (id) => db.prepare("UPDATE outbox SET state='sent',text='' WHERE id=?").run(id),
112
+ sent: (id) => db.prepare("UPDATE outbox SET state='sent',text='',image='' WHERE id=?").run(id),
110
113
  retry: (epoch) => db.prepare("UPDATE outbox SET state='pending' WHERE epoch=? AND state IN ('unknown','blocked')").run(epoch),
111
114
  unblock: (epoch) => db.prepare("UPDATE outbox SET state='pending' WHERE epoch=? AND state='blocked'").run(epoch),
112
115
  hasUnknown: (epoch) => Boolean(db.prepare("SELECT 1 FROM outbox WHERE epoch=? AND state='unknown' LIMIT 1").get(epoch)),
116
+ hasBlocked: (epoch) => Boolean(db.prepare("SELECT 1 FROM outbox WHERE epoch=? AND state='blocked' LIMIT 1").get(epoch)),
113
117
  acquire: (owner, now) => Boolean(db.prepare(`INSERT INTO lease(id,owner,expires_at) VALUES (1,?,?)
114
118
  ON CONFLICT(id) DO UPDATE SET owner=excluded.owner,expires_at=excluded.expires_at
115
119
  WHERE lease.owner=excluded.owner OR lease.expires_at<=?`).run(owner, now + 60_000, now).changes),