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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +8 -0
  2. package/dist/assets/{AgentAvatar-Bi1vvWPC.js → AgentAvatar-BJ42lGZD.js} +1 -1
  3. package/dist/assets/AssistantContactStatus-dtkObamV.js +3 -0
  4. package/dist/assets/{AssistantUnreadBadge-DdJyySwn.js → AssistantUnreadBadge-QwhBfXpC.js} +1 -1
  5. package/dist/assets/AssistantView-D7ryIKL0.js +1 -0
  6. package/dist/assets/{DiagramView-CI4bTtxy.js → DiagramView-ERrGEBDp.js} +1 -1
  7. package/dist/assets/{FadeInOnReveal-BB4qEnAn.js → FadeInOnReveal-Bu2GvaM9.js} +1 -1
  8. package/dist/assets/{GuiPluginSurface-CguxFUbM.js → GuiPluginSurface-MzQgEZNr.js} +1 -1
  9. package/dist/assets/{GuiPluginWindow-DOJ7wuRH.js → GuiPluginWindow-DZMmlQzx.js} +1 -1
  10. package/dist/assets/{Icon-t2xvbAyN.js → Icon-Dj4CCqCP.js} +1 -1
  11. package/dist/assets/{ImageLoadingPlaceholder-D1L13TK0.js → ImageLoadingPlaceholder-BnFXgUuO.js} +1 -1
  12. package/dist/assets/{LoadingImage-5rY_edNm.js → LoadingImage-PBnivDKv.js} +1 -1
  13. package/dist/assets/{MarkdownRenderer-BlGxjOei.js → MarkdownRenderer-BajF4gUU.js} +2 -2
  14. package/dist/assets/{MarkdownRendererImpl-cE-0AYRg.js → MarkdownRendererImpl-CfyXL4rg.js} +1 -1
  15. package/dist/assets/{MarkstreamRendererImpl-BZyqDl82.js → MarkstreamRendererImpl-BGadklK1.js} +1 -1
  16. package/dist/assets/{MobileDetailNavigation-tbfsMfB-.js → MobileDetailNavigation-DqajQdB4.js} +1 -1
  17. package/dist/assets/{MobileResizableSheet-BeRmT6_x.js → MobileResizableSheet-BvdUgwA3.js} +1 -1
  18. package/dist/assets/{MobileShareBridge-C3Equ3P_.js → MobileShareBridge-3oPoYnry.js} +2 -2
  19. package/dist/assets/{MobileTabPageHeader-DQRqAAEf.js → MobileTabPageHeader-B6cRyIRH.js} +1 -1
  20. package/dist/assets/{MultiRunWindow-CAM2XPII.js → MultiRunWindow-yhs0Ih5_.js} +1 -1
  21. package/dist/assets/{OnboardingScreen-4ftRerP5.js → OnboardingScreen-Bi1VWFQC.js} +1 -1
  22. package/dist/assets/{OverlayScrollbar-CF0PCvQz.js → OverlayScrollbar-BBDwGvGO.js} +1 -1
  23. package/dist/assets/{SettingsView-2tk4WH7R.js → SettingsView-BSf-SJUA.js} +15 -15
  24. package/dist/assets/{SettingsWindow-B9zbeJaW.js → SettingsWindow-BvSXVMTm.js} +1 -1
  25. package/dist/assets/{TerminalView-DfxvTHye.js → TerminalView-DhL01N7e.js} +1 -1
  26. package/dist/assets/{ToolOutputDialog-CrjDIhru.js → ToolOutputDialog-C8lnH4Ky.js} +1 -1
  27. package/dist/assets/{YuriLogo-QvS1ZEHi.js → YuriLogo-D8asj1CS.js} +1 -1
  28. package/dist/assets/{appThemeRegistry-Bb_DtiV9.js → appThemeRegistry-C-maYSdv.js} +1 -1
  29. package/dist/assets/{assistant-attachment-cache-B9iHLlm2.js → assistant-attachment-cache-B_qRvy-k.js} +1 -1
  30. package/dist/assets/{button-DinGM3tu.js → button-vXOdzd8x.js} +1 -1
  31. package/dist/assets/{capgoAdapter-DufzjXRs.js → capgoAdapter-DJ_h2x5D.js} +1 -1
  32. package/dist/assets/{collapsible-Bh1GLNYV.js → collapsible-DwDQs3Wa.js} +1 -1
  33. package/dist/assets/context-menu-BabBujQ-.js +1 -0
  34. package/dist/assets/{desktopRelayRestore-CoLLVJw8.js → desktopRelayRestore-D1UX7HW2.js} +1 -1
  35. package/dist/assets/{diagram-BmG-7Jb4.js → diagram-HwgrQxY5.js} +1 -1
  36. package/dist/assets/{dialog-BXssfGXA.js → dialog-Dnf626tb.js} +1 -1
  37. package/dist/assets/dropdown-menu.styles-CBc_a-Nv.js +1 -0
  38. package/dist/assets/{es-HP_Ise0X.js → es-BQkO-Odr.js} +1 -1
  39. package/dist/assets/feishu-Ct1ZxlzQ.svg +6 -0
  40. package/dist/assets/{fileMentionTouchSelection-DSl0tj2r.js → fileMentionTouchSelection-CKPnEetl.js} +1 -1
  41. package/dist/assets/{fileQueries-5a1jkme2.js → fileQueries-BeXkd3o6.js} +1 -1
  42. package/dist/assets/{fileReferenceActions-CGpBSFq4.js → fileReferenceActions-g7KZLi_G.js} +1 -1
  43. package/dist/assets/{fr-D0kJXJ6U.js → fr-C852roK5.js} +1 -1
  44. package/dist/assets/{gitApi-Wo0IZow9.js → gitApi-CVq5oKCd.js} +1 -1
  45. package/dist/assets/{gitApiHttp-De9liKnG.js → gitApiHttp-BYOIbYIh.js} +2 -2
  46. package/dist/assets/{gui-9enrif_1.js → gui-M_Rbwkyu.js} +1 -1
  47. package/dist/assets/host-BW3FEJdU.js +1 -0
  48. package/dist/assets/{image-loading-Dq1g_wpm.js → image-loading-D5UhMj7Z.js} +1 -1
  49. package/dist/assets/{input-v8-rVbo-.js → input-BtM712b1.js} +1 -1
  50. package/dist/assets/{insertionBoundaries-CZz7TWJv.js → insertionBoundaries-Dx3WAY6i.js} +1 -1
  51. package/dist/assets/{ja-BjHKXazE.js → ja-BqC39qK6.js} +1 -1
  52. package/dist/assets/{ko-Llwnl876.js → ko-BMaChAWh.js} +1 -1
  53. package/dist/assets/main-9uP2z1qT.js +2 -0
  54. package/dist/assets/main-Mey7bCWf.js +169 -0
  55. package/dist/assets/{markdownHeightCache-BVV2dktw.js → markdownHeightCache-Bf8iisO4.js} +1 -1
  56. package/dist/assets/{mcpQueries-BoBrB4a4.js → mcpQueries-DpXqegX5.js} +1 -1
  57. package/dist/assets/miniChat-DqZvVkme.js +2 -0
  58. package/dist/assets/mobile-DXAWjYcN.js +2 -0
  59. package/dist/assets/{mobileBackNavigation-DMSzAvb6.js → mobileBackNavigation-DZcI7aZg.js} +1 -1
  60. package/dist/assets/{multirun-BhWttsRQ.js → multirun-hzspPepd.js} +1 -1
  61. package/dist/assets/{native-DSvNnKAm.js → native-H7K64Ulc.js} +1 -1
  62. package/dist/assets/{native-config-DjdrW_9n.js → native-config-CddZtLQ1.js} +1 -1
  63. package/dist/assets/{persistence-CfrHIiIS.js → persistence-BT8045Ue.js} +1 -1
  64. package/dist/assets/{pl-BOd_idqn.js → pl-Ubs8p28T.js} +1 -1
  65. package/dist/assets/projectMeta-CEf0QPmD.js +1 -0
  66. package/dist/assets/{pt-BR-B8djxMsl.js → pt-BR-8rAOjJrs.js} +1 -1
  67. package/dist/assets/{queryRuntime-Dkpnq3Z1.js → queryRuntime-CTcigFdj.js} +1 -1
  68. package/dist/assets/react-DRe85o5s.js +1 -0
  69. package/dist/assets/readiness-Dyr7314z.js +1 -0
  70. package/dist/assets/{renderElectronMiniChatApp-N2r999Bf.js → renderElectronMiniChatApp-DoOq8Cuo.js} +2 -2
  71. package/dist/assets/{renderMobileApp-CU1ec6Ak.js → renderMobileApp-TTxtOb8b.js} +7 -7
  72. package/dist/assets/runtime-fetch-D0YWp3FJ.js +1 -0
  73. package/dist/assets/{runtime-file-download-CcNIVp7u.js → runtime-file-download-Cf1WxfeW.js} +1 -1
  74. package/dist/assets/{runtime-file-resource-6np6lzoV.js → runtime-file-resource-UJjHUF2C.js} +1 -1
  75. package/dist/assets/runtimeConfig-B8VHHNxj.js +2 -0
  76. package/dist/assets/runtimeEndpointReset-BC6XWntz.js +149 -0
  77. package/dist/assets/scheduledTaskNavigation-Zm87Nydi.js +1 -0
  78. package/dist/assets/sessionLookup-De53jDwM.js +1 -0
  79. package/dist/assets/{sortable-tabs-strip-yKyqsqut.js → sortable-tabs-strip-D4pVoodN.js} +1 -1
  80. package/dist/assets/speechSettingsQueries-RlCLMBtr.js +4 -0
  81. package/dist/assets/src-lE4uqaHS.css +2 -0
  82. package/dist/assets/{store-CUBymvAC.js → store-ME7oHni1.js} +2 -2
  83. package/dist/assets/{terminalApi-BblSkqch.js → terminalApi-BSaclMDJ.js} +1 -1
  84. package/dist/assets/{textarea-B39OCNPV.js → textarea-B98rsLs7.js} +1 -1
  85. package/dist/assets/{tooltip-d8TNN4lx.js → tooltip-B9810jbK.js} +1 -1
  86. package/dist/assets/{types-BqFQhQTt.js → types-DFf9vd1b.js} +1 -1
  87. package/dist/assets/{uk-BNd7CjVO.js → uk-LzwzUApL.js} +1 -1
  88. package/dist/assets/{useAppFontEffects-BVoVpJYO.js → useAppFontEffects-D2C1sBYM.js} +43 -43
  89. package/dist/assets/{useAssistantUIStore-Bp6TxG5E.js → useAssistantUIStore-TUN_ycy5.js} +1 -1
  90. package/dist/assets/{useDesktopWindowControlsLayout-CYx1LNO5.js → useDesktopWindowControlsLayout-BjKaHN0x.js} +1 -1
  91. package/dist/assets/{useEffectiveDirectory-D8FFE5Yn.js → useEffectiveDirectory-TEvyiQSC.js} +1 -1
  92. package/dist/assets/{useFontPreferences-BFyBjtQ6.js → useFontPreferences-BlhlCJCX.js} +1 -1
  93. package/dist/assets/{useMobileNavigationStore-BHMFeMjo.js → useMobileNavigationStore-DTvJV9s-.js} +6 -6
  94. package/dist/assets/useUIStore-DRx6OgCp.js +1 -0
  95. package/dist/assets/{useWorkerHighlightedLines-CPxG8Fya.js → useWorkerHighlightedLines-D093jNsH.js} +1 -1
  96. package/dist/assets/vendor-opencode-client-ZeOZ4Efz.js +23 -0
  97. package/dist/assets/{vendor-opencode-plugin-CgKz9Hcy.js → vendor-opencode-plugin-BBOP6WNx.js} +1 -1
  98. package/dist/assets/{vendor-solid-js-0T254UHG.js → vendor-solid-js-9wmPZH9g.js} +1 -1
  99. package/dist/assets/{zh-CN-BkTAEOZG.js → zh-CN-D-FVCeks.js} +1 -1
  100. package/dist/assets/{zh-TW-x8SfMzfc.js → zh-TW-B9iH_NXL.js} +1 -1
  101. package/dist/index.html +17 -17
  102. package/dist/mini-chat.html +17 -17
  103. package/dist/mobile.html +17 -17
  104. package/package.json +6 -1
  105. package/server/lib/assistants/DOCUMENTATION.md +13 -1
  106. package/server/lib/assistants/channels/DOCUMENTATION.md +291 -0
  107. package/server/lib/assistants/channels/PROTOCOLS.md +228 -0
  108. package/server/lib/assistants/channels/dingtalk-chat-adapter.js +633 -0
  109. package/server/lib/assistants/channels/dingtalk-chat-adapter.test.js +415 -0
  110. package/server/lib/assistants/channels/integration.test.js +44 -0
  111. package/server/lib/assistants/channels/routes.js +47 -0
  112. package/server/lib/assistants/channels/routes.test.js +105 -0
  113. package/server/lib/assistants/channels/runtime.js +867 -0
  114. package/server/lib/assistants/channels/runtime.test.js +723 -0
  115. package/server/lib/assistants/channels/sdk-adapters.js +371 -0
  116. package/server/lib/assistants/channels/sdk-adapters.test.js +367 -0
  117. package/server/lib/assistants/channels/store.js +246 -0
  118. package/server/lib/assistants/channels/store.test.js +286 -0
  119. package/server/lib/assistants/channels/transport.js +41 -0
  120. package/server/lib/assistants/channels/transport.test.js +23 -0
  121. package/server/lib/assistants/channels/wecom-chat-adapter.js +689 -0
  122. package/server/lib/assistants/channels/wecom-chat-adapter.test.js +109 -0
  123. package/server/lib/assistants/message-channel-origin.js +7 -0
  124. package/server/lib/assistants/routes.js +14 -1
  125. package/server/lib/assistants/weixin/DOCUMENTATION.md +89 -7
  126. package/server/lib/assistants/weixin/api.js +2 -0
  127. package/server/lib/assistants/weixin/chat-adapter.js +107 -0
  128. package/server/lib/assistants/weixin/chat-adapter.test.js +62 -0
  129. package/server/lib/assistants/weixin/inbound.js +147 -0
  130. package/server/lib/assistants/weixin/inbound.test.js +121 -0
  131. package/server/lib/assistants/weixin/media.js +79 -0
  132. package/server/lib/assistants/weixin/media.test.js +66 -0
  133. package/server/lib/assistants/weixin/runtime.js +89 -67
  134. package/server/lib/assistants/weixin/runtime.test.js +156 -4
  135. package/server/lib/assistants/weixin/store.js +8 -4
  136. package/server/lib/assistants/weixin/store.test.js +72 -0
  137. package/server/lib/assistants/weixin/toon.js +49 -0
  138. package/server/lib/assistants/weixin/toon.test.js +25 -0
  139. package/server/lib/github/DOCUMENTATION.md +9 -8
  140. package/server/lib/llm/bridge-plugin.bundle.js +188 -188
  141. package/server/lib/opencode/DOCUMENTATION.md +1 -1
  142. package/dist/assets/AssistantContactStatus-CWq-PDz6.js +0 -3
  143. package/dist/assets/AssistantView-Br1iETTs.js +0 -1
  144. package/dist/assets/context-menu-DpbkRkk1.js +0 -1
  145. package/dist/assets/host-FR_grJxM.js +0 -1
  146. package/dist/assets/main-Bp9HHqTr.js +0 -2
  147. package/dist/assets/main-DOwAfmxJ.js +0 -169
  148. package/dist/assets/miniChat-BJDgCrfF.js +0 -2
  149. package/dist/assets/mobile-GM9931J_.js +0 -2
  150. package/dist/assets/projectMeta-31PobC-M.js +0 -1
  151. package/dist/assets/react-B9v0P7kT.js +0 -1
  152. package/dist/assets/readiness-CYNnsekT.js +0 -1
  153. package/dist/assets/runtime-fetch-D4ja813o.js +0 -1
  154. package/dist/assets/runtimeConfig-Db7yfo6L.js +0 -2
  155. package/dist/assets/runtimeEndpointReset-DO5WVetV.js +0 -149
  156. package/dist/assets/scheduledTaskNavigation-Bsrhv3Ow.js +0 -1
  157. package/dist/assets/sessionLookup-DRVy7LM1.js +0 -1
  158. package/dist/assets/speechSettingsQueries-DU25rmGc.js +0 -4
  159. package/dist/assets/src-Bckdo2XS.css +0 -2
  160. package/dist/assets/useUIStore-BbYD420L.js +0 -1
  161. package/dist/assets/vendor-opencode-client-UL_TecvQ.js +0 -12
@@ -3,9 +3,11 @@ import { setTimeout as delay } from 'node:timers/promises';
3
3
  import { createWeixinAPI, WeixinError, weixinOrigin } from './api.js';
4
4
  import { createWeixinStore } from './store.js';
5
5
  import { createWeixinTyping } from './typing.js';
6
+ import { prepareWeixinInput } from './inbound.js';
7
+ import { createWeixinChatAdapter } from './chat-adapter.js';
8
+ import { isMessageChannelTurn } from '../message-channel-origin.js';
6
9
 
7
10
  const digest = (value) => createHash('sha256').update(value).digest('hex');
8
- const messageID = (account, peer, id) => `weixin:${digest(JSON.stringify([account, peer, id]))}`;
9
11
  const chunks = (text) => {
10
12
  const chars = Array.from(text);
11
13
  const result = [];
@@ -16,11 +18,11 @@ const feedback = (language, kind) => {
16
18
  const messages = language.startsWith('zh') ? {
17
19
  interrupted: 'Yuri 主机已重启,上一条请求可能未完成。请先检查任务状态,再决定是否重试。',
18
20
  failed: '助理未能完成这条请求,请在 Yuri 中查看具体错误后重试。',
19
- textOnly: '当前微信通道仅支持文字,请发送文字消息。',
21
+ empty: '这条微信消息没有可读取的内容,请重发文字、图片或文章链接。',
20
22
  } : {
21
23
  interrupted: 'The Yuri host restarted. The previous request may be incomplete. Check its status before retrying.',
22
24
  failed: 'The bot could not complete this request. Check the error in Yuri before retrying.',
23
- textOnly: 'This WeChat connection currently accepts text messages only. Please send a text message.',
25
+ empty: 'This WeChat message has no readable content. Please resend text, an image, or an article link.',
24
26
  };
25
27
  return messages[kind];
26
28
  };
@@ -45,12 +47,12 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
45
47
  const logins = new Map();
46
48
  const receivers = new Map();
47
49
  const bindingWork = new Map();
50
+ const inboundWork = new Map();
48
51
  const operations = new Set();
49
52
  const recovered = new Set();
50
53
  const retiring = new Set();
51
54
  const lifetime = new AbortController();
52
55
  let closed = false;
53
- let ticking = false;
54
56
  let ownsLease = false;
55
57
  let closePromise;
56
58
  const track = (promise) => {
@@ -85,29 +87,32 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
85
87
 
86
88
  const receive = async (initial, signal) => {
87
89
  let failures = 0;
90
+ let messages = [];
91
+ const adapter = createWeixinChatAdapter({ api, clock, getBinding: () => isCurrent(initial) ? store.get(initial.assistant_id) : null });
92
+ await adapter.initialize({ processMessage: async (_adapter, _threadID, message) => { messages.push(adapter.receipt(message)); } });
88
93
  while (!signal.aborted && isCurrent(initial)) {
89
94
  const binding = store.get(initial.assistant_id);
90
95
  if (!binding || binding.status === 'expired') return;
91
96
  if (store.backlog(binding.epoch) >= 100) { await pause(2000, signal); continue; }
92
97
  try {
93
- const response = await api.getUpdates(binding, signal);
98
+ const response = await adapter.poll(signal);
94
99
  if (signal.aborted || !isCurrent(binding)) return;
95
100
  if (store.get(binding.assistant_id)?.status === 'expired') return;
96
101
  const incoming = response.msgs ?? [];
97
102
  const cursor = response.get_updates_buf ?? binding.cursor;
98
103
  if (!Array.isArray(incoming) || incoming.length > 500 || typeof cursor !== 'string'
99
104
  || cursor.length > 512_000) throw new WeixinError('invalid_response');
100
- const messages = [];
105
+ messages = [];
101
106
  for (const msg of incoming) {
102
107
  if (!msg || typeof msg !== 'object') continue;
103
108
  // The QR-confirmed owner is the only principal allowed to execute tools.
104
109
  if (msg.message_type !== 1 || msg.from_user_id !== binding.peer_id || msg.group_id) continue;
105
- if (typeof msg.message_id !== 'string' || !msg.message_id || msg.message_id.length > 256) continue;
106
- const text = Array.isArray(msg.item_list) ? msg.item_list.filter((item) => item?.type === 1)
107
- .map((item) => typeof item.text_item?.text === 'string' ? item.text_item.text : '').join('\n').trim() : '';
108
- const context = typeof msg.context_token === 'string' && msg.context_token.length <= 65_536 ? msg.context_token : '';
109
- messages.push({ id: messageID(binding.account_id, binding.peer_id, msg.message_id), text: text.length <= 20_000 ? text : '', context });
110
+ const platformID = typeof msg.message_id === 'string' && msg.message_id ? msg.message_id
111
+ : Array.isArray(msg.item_list) ? msg.item_list.find((item) => typeof item?.msg_id === 'string' && item.msg_id)?.msg_id : '';
112
+ if (!platformID || platformID.length > 256) continue;
113
+ await adapter.dispatch(msg);
110
114
  }
115
+ if (signal.aborted || !isCurrent(binding)) return;
111
116
  // Persist receipt and context before acknowledging the platform cursor.
112
117
  store.accept(binding, cursor || binding.cursor, messages);
113
118
  if (messages.some((message) => message.context)) store.unblock(binding.epoch);
@@ -127,39 +132,28 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
127
132
  }
128
133
  };
129
134
 
130
- const processBinding = async (binding) => {
131
- if (!isCurrent(binding)) return;
132
- let page;
133
- try { page = service.channelPage(binding.assistant_id, { afterOrdinal: binding.ordinal, generation: binding.generation }); }
134
- catch (error) {
135
- if (error?.code === 'not_found') { await forget(binding.assistant_id); return; }
136
- throw error;
137
- }
138
- if (binding.status === 'expired') return;
139
- const deliveries = page.messages.flatMap((message) => {
140
- const text = message.status === 'error' ? feedback(binding.language, 'failed')
141
- : message.text?.trim() && !message.text.trim().startsWith('oc.settle.') ? message.text.trim()
142
- : message.cards.map((card) => card.title || card.name || '').filter(Boolean).join('\n');
143
- return chunks(text).map((chunk, index) => ({
144
- id: `yuri_${digest(`${binding.epoch}:${page.generation}:${message.messageID}:${index}`)}`, text: chunk,
145
- }));
146
- });
147
- store.collect(binding, page, deliveries);
148
-
135
+ const processIncoming = async (binding, generation) => {
149
136
  for (const receipt of store.pending(binding.epoch)) {
150
137
  if (!isCurrent(binding)) return;
151
- if (!receipt.text) {
152
- store.enqueue(binding.epoch, `${receipt.id}:text-only`, feedback(binding.language, 'textOnly'));
138
+ if (!receipt.text && !receipt.payload) {
139
+ store.enqueue(binding.epoch, `${receipt.id}:empty`, feedback(binding.language, 'empty'));
153
140
  store.finishTurn(receipt.id);
154
141
  continue;
155
142
  }
156
- // Fence the crash gap. Never replay admitted tool side effects on restart.
157
- store.markInbox(receipt.id, 'admitted');
158
143
  try {
144
+ const receiverSignal = receivers.get(binding.assistant_id)?.controller.signal;
145
+ const signal = receiverSignal ? AbortSignal.any([lifetime.signal, receiverSignal]) : lifetime.signal;
146
+ const assertCurrent = () => {
147
+ if (!isCurrent(binding) || signal.aborted || store.get(binding.assistant_id)?.status === 'expired'
148
+ || service.channelPage(binding.assistant_id, { tipOnly: true }).generation !== generation) throw new WeixinError('cancelled');
149
+ };
150
+ const parts = await prepareWeixinInput(receipt, { api, service, assistantID: binding.assistant_id, signal, assertCurrent });
159
151
  await refreshAllowedRoots();
160
- if (!isCurrent(binding)) return;
152
+ assertCurrent();
153
+ // Fence the crash gap. Never replay admitted tool side effects on restart.
154
+ store.markInbox(receipt.id, 'admitted');
161
155
  const result = await service.send(binding.assistant_id, {
162
- messageID: receipt.id, parts: [{ type: 'text', text: receipt.text }], language: binding.language,
156
+ messageID: receipt.id, parts, language: binding.language,
163
157
  });
164
158
  if (isCurrent(binding) && result.replayed) {
165
159
  store.enqueue(binding.epoch, `${receipt.id}:interrupted`, feedback(binding.language, 'interrupted'));
@@ -171,6 +165,34 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
171
165
  store.finishTurn(receipt.id);
172
166
  }
173
167
  }
168
+ };
169
+
170
+ const processBinding = async (binding) => {
171
+ if (!isCurrent(binding)) return;
172
+ let page;
173
+ try { page = service.channelPage(binding.assistant_id, { afterOrdinal: binding.ordinal, generation: binding.generation }); }
174
+ catch (error) {
175
+ if (error?.code === 'not_found') { await forget(binding.assistant_id); return; }
176
+ throw error;
177
+ }
178
+ 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
+ });
188
+ store.collect(binding, page, deliveries);
189
+ if (!inboundWork.has(binding.assistant_id)) {
190
+ const work = track(processIncoming(binding, page.generation)).catch((error) => setError(binding, error));
191
+ inboundWork.set(binding.assistant_id, work);
192
+ void work.finally(() => {
193
+ if (inboundWork.get(binding.assistant_id) === work) inboundWork.delete(binding.assistant_id);
194
+ }).catch(() => {});
195
+ }
174
196
  const current = store.get(binding.assistant_id);
175
197
  if (!isCurrent(binding) || current.status === 'expired' || !current.context_token) return;
176
198
  const delivery = store.nextDelivery(binding.epoch);
@@ -178,7 +200,10 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
178
200
  store.markDelivery(delivery.id, 'sending');
179
201
  try {
180
202
  const receiverSignal = receivers.get(binding.assistant_id)?.controller.signal;
181
- await api.sendText(current, delivery, receiverSignal ? AbortSignal.any([lifetime.signal, receiverSignal]) : lifetime.signal);
203
+ const adapter = createWeixinChatAdapter({ api, clock, getBinding: () => isCurrent(binding) ? store.get(binding.assistant_id) : null });
204
+ 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 });
182
207
  if (!isCurrent(binding) && !(retiring.has(binding.assistant_id) && canControl(binding))) return;
183
208
  store.sent(delivery.id);
184
209
  store.patch(binding.epoch, { error: null, updated_at: clock() });
@@ -209,36 +234,33 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
209
234
  void track(typing.clear());
210
235
  return;
211
236
  }
212
- if (ticking) return;
213
- ticking = true;
214
- try {
215
- const bindings = store.list();
216
- const ids = new Set(bindings.map((binding) => binding.assistant_id));
217
- for (const id of receivers.keys()) if (!ids.has(id)) stopReceiver(id);
218
- for (const binding of bindings) {
219
- if (!recovered.has(binding.epoch)) {
220
- store.recover(binding.epoch, feedback(binding.language, 'interrupted'));
221
- if (store.hasUnknown(binding.epoch)) store.patch(binding.epoch, { error: 'delivery_unknown' });
222
- recovered.add(binding.epoch);
223
- }
224
- if (binding.status !== 'expired' && !retiring.has(binding.assistant_id) && !receivers.has(binding.assistant_id)) {
225
- const controller = new AbortController();
226
- const entry = { controller };
227
- receivers.set(binding.assistant_id, entry);
228
- entry.done = track(receive(binding, controller.signal)).finally(() => {
229
- if (receivers.get(binding.assistant_id) === entry) receivers.delete(binding.assistant_id);
230
- }).catch(() => {});
231
- }
237
+ const bindings = store.list();
238
+ const ids = new Set(bindings.map((binding) => binding.assistant_id));
239
+ for (const id of receivers.keys()) if (!ids.has(id)) stopReceiver(id);
240
+ for (const binding of bindings) {
241
+ if (!recovered.has(binding.epoch)) {
242
+ store.recover(binding.epoch, feedback(binding.language, 'interrupted'));
243
+ if (store.hasUnknown(binding.epoch)) store.patch(binding.epoch, { error: 'delivery_unknown' });
244
+ recovered.add(binding.epoch);
232
245
  }
233
- // One slow Bot cannot prevent another account receiving or replying.
234
- await Promise.allSettled(bindings.map((binding) => {
235
- const work = processBinding(binding).catch((error) => setError(binding, error));
236
- bindingWork.set(binding.assistant_id, work);
237
- return work.finally(() => {
238
- if (bindingWork.get(binding.assistant_id) === work) bindingWork.delete(binding.assistant_id);
239
- });
240
- }));
241
- } finally { ticking = false; }
246
+ if (binding.status !== 'expired' && !retiring.has(binding.assistant_id) && !receivers.has(binding.assistant_id)) {
247
+ const controller = new AbortController();
248
+ const entry = { controller };
249
+ receivers.set(binding.assistant_id, entry);
250
+ entry.done = track(receive(binding, controller.signal)).finally(() => {
251
+ if (receivers.get(binding.assistant_id) === entry) receivers.delete(binding.assistant_id);
252
+ }).catch(() => {});
253
+ }
254
+ }
255
+ // One slow Bot cannot prevent another account receiving or replying.
256
+ await Promise.allSettled(bindings.map((binding) => {
257
+ if (bindingWork.has(binding.assistant_id) || retiring.has(binding.assistant_id)) return;
258
+ const work = processBinding(binding).catch((error) => setError(binding, error));
259
+ bindingWork.set(binding.assistant_id, work);
260
+ return work.finally(() => {
261
+ if (bindingWork.get(binding.assistant_id) === work) bindingWork.delete(binding.assistant_id);
262
+ });
263
+ }));
242
264
  };
243
265
 
244
266
  const status = (assistantID) => {
@@ -369,7 +391,7 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
369
391
  logins.get(assistantID)?.controller.abort();
370
392
  logins.delete(assistantID);
371
393
  try {
372
- await Promise.allSettled([stopReceiver(sourceAssistantID), bindingWork.get(sourceAssistantID), typing.forget(sourceAssistantID)]);
394
+ await Promise.allSettled([stopReceiver(sourceAssistantID), bindingWork.get(sourceAssistantID), inboundWork.get(sourceAssistantID), typing.forget(sourceAssistantID)]);
373
395
  assertOwner();
374
396
  // Revalidate after draining: deletion or a stale confirmation must not move credentials.
375
397
  service.channelPage(sourceAssistantID, { tipOnly: true });
@@ -6,6 +6,7 @@ import { createWeixinRuntime } from './runtime.js';
6
6
  import { createWeixinStore } from './store.js';
7
7
  import { WeixinError } from './api.js';
8
8
  import { createAssistantsService } from '../service.js';
9
+ import { normalizeWeixinInput } from './inbound.js';
9
10
 
10
11
  const closers = [];
11
12
  afterEach(async () => { while (closers.length) await closers.pop()(); });
@@ -57,6 +58,21 @@ function fixture({ directory = root(), configureAPI, service: externalService, c
57
58
  }
58
59
 
59
60
  describe('Weixin Host runtime', () => {
61
+ it('does not broadcast other channel replies to WeChat but pushes source-less messages', async () => {
62
+ const f = fixture();
63
+ f.updates.push([inbound('own-turn')]);
64
+ await f.bind();
65
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledOnce());
66
+ const turnID = f.service.send.mock.calls[0][1].messageID;
67
+ f.pages.set('bot', { generation: 0, messages: [
68
+ { ordinal: 1, messageID: 'enterprise-output', turnID: 'channel:feishu:some-turn', text: 'not for WeChat', cards: [], status: 'complete' },
69
+ { ordinal: 2, messageID: 'own-output', turnID, text: 'WeChat reply', cards: [], status: 'complete' },
70
+ { ordinal: 3, messageID: 'push-output', turnID: 'app-turn', text: 'proactive push', cards: [], status: 'complete' },
71
+ ] });
72
+ await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(2));
73
+ expect(f.api.sendText.mock.calls.map(([, delivery]) => delivery.text)).toEqual(['WeChat reply', 'proactive push']);
74
+ });
75
+
60
76
  it.each([
61
77
  { NODE_ENV: 'development' },
62
78
  { YURI_ELECTRON_DEV: '1' },
@@ -118,6 +134,20 @@ describe('Weixin Host runtime', () => {
118
134
  expect(fs.statSync(path.join(f.directory, 'channel.sqlite')).mode & 0o777).toBe(0o600);
119
135
  });
120
136
 
137
+ it('uses the reference client item-level stable ID fallback and never fetches unauthorized media', async () => {
138
+ const f = fixture({ configureAPI: (api) => { api.downloadMedia = vi.fn(); } });
139
+ const media = { type: 2, image_item: { media: { encrypt_query_param: 'private-reference' } } };
140
+ f.updates.push([
141
+ { ...inbound('stranger', 'other-owner'), item_list: [media] },
142
+ { ...inbound('group'), group_id: 'group', item_list: [media] },
143
+ { ...inbound(), message_id: undefined, item_list: [{ type: 1, msg_id: 'item-123', text_item: { text: 'item ID message' } }] },
144
+ { ...inbound(), message_id: 'item-123', item_list: [{ type: 1, text_item: { text: 'item ID message' } }] },
145
+ ]);
146
+ await f.bind();
147
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1));
148
+ expect(f.api.downloadMedia).not.toHaveBeenCalled();
149
+ });
150
+
121
151
  it('restarts without another scan, keeps deduplication and does not replay admitted tool work', async () => {
122
152
  const f = fixture();
123
153
  f.updates.push([inbound()]);
@@ -356,13 +386,13 @@ describe('Weixin Host runtime', () => {
356
386
  await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(2));
357
387
  });
358
388
 
359
- it('non-text input gives a text-only reply without invoking bot tools', async () => {
389
+ it('passes non-text metadata to the bot without pretending unavailable image bytes were read', async () => {
360
390
  const f = fixture();
361
391
  f.updates.push([{ ...inbound(), item_list: [null, { type: 2, image_item: { media: {} } }] }]);
362
392
  await f.bind();
363
- await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalled());
364
- expect(f.api.sendText.mock.calls[0][1].text).toContain('仅支持文字');
365
- expect(f.service.send).not.toHaveBeenCalled();
393
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalled());
394
+ expect(f.service.send.mock.calls[0][1].parts[0].text).toContain('unavailable');
395
+ expect(f.service.send.mock.calls[0][1].parts[0].text).toContain('image');
366
396
  });
367
397
 
368
398
  it('reuses the actual Yuri contact pipeline for WeChat → bot → durable reply', async () => {
@@ -394,6 +424,128 @@ describe('Weixin Host runtime', () => {
394
424
  await vi.waitFor(() => expect(f.api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1, 2]));
395
425
  });
396
426
 
427
+ it('routes images, text documents, voice transcripts and share metadata through real contact storage and execution exactly once', async () => {
428
+ const directory = root();
429
+ let runtime;
430
+ const runContactTurn = vi.fn(async () => ({ bubbles: ['已收到图片、文档与分享信息'] }));
431
+ const service = createAssistantsService({
432
+ dbPath: path.join(directory, 'assistants.sqlite'), dataDir: directory,
433
+ buildOpenCodeUrl: () => 'http://127.0.0.1:1', getOpenCodeAuthHeaders: () => ({}),
434
+ getAllowedRoots: () => [directory], runContactTurn,
435
+ onContactTurnEvent: (event) => runtime?.onTurnEvent(event),
436
+ createChatCompletion: async () => ({ choices: [] }),
437
+ });
438
+ closers.push(() => service.close());
439
+ const bot = service.createAssistant({ name: '多模态测试', providerID: 'p', modelID: 'm' });
440
+ const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6D/8AAAAASUVORK5CYII=', 'base64');
441
+ const f = fixture({ directory: path.join(directory, 'weixin'), service, configureAPI: (api) => {
442
+ api.downloadMedia = vi.fn(async (source) => source.kind === 'image'
443
+ ? { buffer: png, mime: 'image/png', filename: 'weixin.png' }
444
+ : { buffer: Buffer.from('文档正文'), mime: 'text/plain', filename: 'notes.txt' });
445
+ } });
446
+ runtime = f.runtime;
447
+ const message = { ...inbound(), item_list: [
448
+ { type: 1, text_item: { text: '看看这些内容' } },
449
+ { type: 2, image_item: { media: { encrypt_query_param: 'private-image', aes_key: 'private-key' } } },
450
+ { type: 4, file_item: { file_name: 'notes.txt', media: { encrypt_query_param: 'private-document', aes_key: 'private-key' } } },
451
+ { type: 3, voice_item: { text: '顺便读一下这篇公众号文章' } },
452
+ { type: 99, share: { title: '文章标题', url: 'https://mp.weixin.qq.com/s/example', description: '摘要' } },
453
+ ] };
454
+ f.updates.push([message, message]);
455
+ await f.bind(bot.id);
456
+ await vi.waitFor(() => expect(runContactTurn).toHaveBeenCalledTimes(1));
457
+ const parts = runContactTurn.mock.calls[0][0].userParts;
458
+ expect(parts.filter((part) => part.type === 'file')).toEqual([
459
+ expect.objectContaining({ mime: 'image/png', url: `data:image/png;base64,${png.toString('base64')}` }),
460
+ expect.objectContaining({ mime: 'text/plain', url: `data:text/plain;base64,${Buffer.from('文档正文').toString('base64')}` }),
461
+ ]);
462
+ expect(parts.at(-1).text).toContain('文章标题');
463
+ expect(parts.at(-1).text).toContain('顺便读一下这篇公众号文章');
464
+ const history = service.contactMessages(bot.id, { limit: 20 });
465
+ const user = history.messages.find((message) => message.role === 'user');
466
+ expect(user.parts.filter((part) => part.type === 'file')).toHaveLength(2);
467
+ expect(JSON.stringify(history)).not.toMatch(/private-key|private-image|private-document|data:image/);
468
+ const attachment = user.parts.find((part) => part.mime === 'image/png');
469
+ expect((await service.getAssistantContactAttachment(bot.id, attachment.attachmentID)).buffer).toEqual(png);
470
+ expect(f.api.downloadMedia).toHaveBeenCalledTimes(2);
471
+ await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalled());
472
+ });
473
+
474
+ it('resumes a durable pending media receipt after restart without polling the message again', async () => {
475
+ const directory = root();
476
+ const store = createWeixinStore(directory);
477
+ const binding = store.bind({ assistant_id: 'bot', account_id: 'account', peer_id: 'owner', token: 'test-token',
478
+ base_url: 'https://ilinkai.weixin.qq.com', language: 'en', generation: 0, ordinal: 0, updated_at: 0 });
479
+ const input = normalizeWeixinInput({ ...inbound(), item_list: [{ type: 2, image_item: { media: { encrypt_query_param: 'private-ref' } } }] });
480
+ store.accept(binding, 'persisted-cursor', [{ id: 'persisted-media-id', ...input }]);
481
+ store.close();
482
+ const f = fixture({ directory, configureAPI: (api) => { api.downloadMedia = vi.fn(async () => ({ buffer: Buffer.from('data'), mime: 'image/png', filename: 'image.png' })); } });
483
+ f.service.putAssistantContactAttachment = vi.fn(async () => ({ type: 'file', attachmentID: 'att_image', mime: 'image/png', size: 4 }));
484
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1));
485
+ expect(f.service.send.mock.calls[0][1]).toMatchObject({ messageID: 'persisted-media-id', parts: expect.arrayContaining([expect.objectContaining({ attachmentID: 'att_image' })]) });
486
+ expect(f.api.getQRCode).not.toHaveBeenCalled();
487
+ });
488
+
489
+ it('keeps sending replies while media downloads; isolates other bindings and fences late completion after disconnect', async () => {
490
+ let completeDownload;
491
+ const f = fixture({ configureAPI: (api) => {
492
+ api.downloadMedia = vi.fn(() => new Promise((resolve) => { completeDownload = resolve; }));
493
+ api.getQRStatus.mockImplementation(async (_origin, qr) => ({ status: 'confirmed', bot_token: 'test-token',
494
+ ilink_bot_id: qr, ilink_user_id: 'owner', baseurl: 'https://ilinkai.weixin.qq.com' }));
495
+ let qrNumber = 0;
496
+ api.getQRCode.mockImplementation(async () => ({ qrcode: `qr-${++qrNumber}`, qrcode_img_content: 'https://example.com/scan' }));
497
+ } });
498
+ f.service.putAssistantContactAttachment = vi.fn();
499
+ await f.bind();
500
+ await f.bind('other-bot');
501
+ let imageReceived = false;
502
+ let otherReceived = false;
503
+ closers.push(() => completeDownload?.({ buffer: Buffer.from('late'), mime: 'image/png', filename: 'late.png' }));
504
+ f.api.getUpdates.mockImplementation(async (binding, signal) => {
505
+ if (!imageReceived && binding.assistant_id === 'bot') {
506
+ imageReceived = true;
507
+ return { msgs: [{ ...inbound(), item_list: [{ type: 2, image_item: { media: { encrypt_query_param: 'private-ref' } } }] }], get_updates_buf: 'next' };
508
+ }
509
+ if (!otherReceived && binding.assistant_id === 'other-bot') {
510
+ otherReceived = true;
511
+ return { msgs: [inbound('other', 'owner', 'other bot request')], get_updates_buf: 'next' };
512
+ }
513
+ return abortable(signal);
514
+ });
515
+ await vi.waitFor(() => expect(completeDownload).toBeTypeOf('function'), { timeout: 3000 });
516
+ f.reply('bot', 'earlier task result');
517
+ f.reply('other-bot', 'another result');
518
+ await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(2));
519
+ expect(f.api.downloadMedia).toHaveBeenCalledTimes(1);
520
+ await f.runtime.disconnect('bot');
521
+ completeDownload({ buffer: Buffer.from('late'), mime: 'image/png', filename: 'late.png' });
522
+ await new Promise((resolve) => setTimeout(resolve, 40));
523
+ expect(f.service.putAssistantContactAttachment).not.toHaveBeenCalled();
524
+ expect(f.service.send).toHaveBeenCalledTimes(1);
525
+ expect(f.service.send.mock.calls[0][0]).toBe('other-bot');
526
+ });
527
+
528
+ it.each(['history-reset', 'auth-expired'])('does not admit media prepared across %s', async (change) => {
529
+ let completeDownload;
530
+ const f = fixture({ configureAPI: (api) => {
531
+ api.downloadMedia = vi.fn(() => new Promise((resolve) => { completeDownload = resolve; }));
532
+ } });
533
+ f.service.putAssistantContactAttachment = vi.fn();
534
+ closers.push(() => completeDownload?.({ buffer: Buffer.from('late'), mime: 'image/png', filename: 'late.png' }));
535
+ f.updates.push([{ ...inbound(), item_list: [{ type: 2, image_item: { media: { encrypt_query_param: 'private-ref' } } }] }]);
536
+ await f.bind();
537
+ await vi.waitFor(() => expect(completeDownload).toBeTypeOf('function'));
538
+ if (change === 'history-reset') f.pages.set('bot', { generation: 1, messages: [] });
539
+ else {
540
+ f.api.getUpdates.mockRejectedValueOnce(new WeixinError('auth_expired'));
541
+ await vi.waitFor(() => expect(f.runtime.status('bot').status).toBe('expired'));
542
+ }
543
+ completeDownload({ buffer: Buffer.from('late'), mime: 'image/png', filename: 'late.png' });
544
+ await new Promise((resolve) => setTimeout(resolve, 40));
545
+ expect(f.service.putAssistantContactAttachment).not.toHaveBeenCalled();
546
+ expect(f.service.send).not.toHaveBeenCalled();
547
+ });
548
+
397
549
  it.each(['error', 'cancelled'])('clears typing on a live %s terminal event without sending a placeholder text', async (status) => {
398
550
  const f = fixture();
399
551
  await f.bind();
@@ -34,6 +34,9 @@ export function createWeixinStore(directory) {
34
34
  `);
35
35
  db.exec(`CREATE INDEX IF NOT EXISTS outbox_pending ON outbox(epoch, state, sequence);
36
36
  CREATE TABLE IF NOT EXISTS lease (id INTEGER PRIMARY KEY CHECK(id=1), owner TEXT NOT NULL, expires_at INTEGER NOT NULL);`);
37
+ if (!db.prepare('PRAGMA table_info(inbox)').all().some((column) => column.name === 'payload')) {
38
+ db.exec("ALTER TABLE inbox ADD COLUMN payload TEXT NOT NULL DEFAULT ''");
39
+ }
37
40
  const get = (assistantID) => db.prepare('SELECT * FROM binding WHERE assistant_id=?').get(assistantID) ?? null;
38
41
  const patch = (epoch, values) => {
39
42
  const allowed = new Set(['cursor', 'context_token', 'generation', 'ordinal', 'status', 'error', 'updated_at']);
@@ -68,7 +71,7 @@ export function createWeixinStore(directory) {
68
71
  }
69
72
  const epoch = randomUUID();
70
73
  // Keep receipt IDs across moves so a replay cannot execute tools in the new Bot.
71
- db.prepare("UPDATE inbox SET epoch=?,state='done',text='' WHERE epoch=?").run(epoch, source.epoch);
74
+ db.prepare("UPDATE inbox SET epoch=?,state='done',text='',payload='' WHERE epoch=?").run(epoch, source.epoch);
72
75
  db.prepare('DELETE FROM outbox WHERE epoch=?').run(source.epoch);
73
76
  db.prepare(`UPDATE binding SET assistant_id=?,epoch=?,generation=?,ordinal=?,language=?,updated_at=?,status='connected',error=NULL WHERE epoch=?`)
74
77
  .run(assistantID, epoch, generation, ordinal, language, updatedAt, source.epoch);
@@ -77,19 +80,20 @@ export function createWeixinStore(directory) {
77
80
  accept: db.transaction((binding, cursor, messages) => {
78
81
  if (get(binding.assistant_id)?.epoch !== binding.epoch) return;
79
82
  for (const message of messages) {
80
- db.prepare('INSERT OR IGNORE INTO inbox(id,epoch,text) VALUES (?,?,?)').run(message.id, binding.epoch, message.text);
83
+ db.prepare('INSERT OR IGNORE INTO inbox(id,epoch,text,payload) VALUES (?,?,?,?)').run(message.id, binding.epoch, message.text, message.payload || '');
81
84
  if (message.context) patch(binding.epoch, { context_token: message.context });
82
85
  }
83
86
  patch(binding.epoch, { cursor });
84
87
  }),
85
88
  pending: (epoch) => db.prepare("SELECT * FROM inbox WHERE epoch=? AND state='pending' ORDER BY rowid LIMIT 20").all(epoch),
89
+ hasReceipt: (id, epoch) => typeof id === 'string' && Boolean(db.prepare('SELECT 1 FROM inbox WHERE id=? AND epoch=?').get(id, epoch)),
86
90
  backlog: (epoch) => db.prepare("SELECT COUNT(*) AS count FROM inbox WHERE epoch=? AND state IN ('pending','admitted')").get(epoch).count,
87
91
  markInbox: (id, state) => db.prepare('UPDATE inbox SET state=? WHERE id=?').run(state, id),
88
- finishTurn: (id) => db.prepare("UPDATE inbox SET state='done',text='' WHERE id=?").run(id),
92
+ finishTurn: (id) => db.prepare("UPDATE inbox SET state='done',text='',payload='' WHERE id=?").run(id),
89
93
  recover: db.transaction((epoch, text) => {
90
94
  for (const row of db.prepare("SELECT id FROM inbox WHERE epoch=? AND state='admitted'").all(epoch)) {
91
95
  enqueue(epoch, `${row.id}:interrupted`, text);
92
- db.prepare("UPDATE inbox SET state='done',text='' WHERE id=?").run(row.id);
96
+ db.prepare("UPDATE inbox SET state='done',text='',payload='' WHERE id=?").run(row.id);
93
97
  }
94
98
  // A process exit during HTTP send cannot prove whether Weixin accepted it.
95
99
  db.prepare("UPDATE outbox SET state='unknown' WHERE epoch=? AND state='sending'").run(epoch);
@@ -0,0 +1,72 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { createRequire } from 'node:module';
5
+ import { afterEach, describe, expect, it } from 'vitest';
6
+ import { createWeixinStore } from './store.js';
7
+
8
+ const Database = createRequire(import.meta.url)('better-sqlite3');
9
+ const cleanup = [];
10
+ afterEach(() => { while (cleanup.length) cleanup.pop()(); });
11
+ const directory = () => {
12
+ const value = fs.mkdtempSync(path.join(os.tmpdir(), 'yuri-weixin-store-'));
13
+ cleanup.push(() => fs.rmSync(value, { recursive: true, force: true }));
14
+ return value;
15
+ };
16
+ const bind = (store, assistant_id = 'bot') => store.bind({ assistant_id, account_id: 'account', peer_id: 'owner', token: 'fake-token',
17
+ base_url: 'https://ilinkai.weixin.qq.com', language: 'zh-CN', generation: 0, ordinal: 0, updated_at: 1 });
18
+
19
+ describe('WeChat structured receipt persistence', () => {
20
+ it('adds the payload column to an existing text-only database without losing cursor, receipts or binding', () => {
21
+ const dir = directory();
22
+ let store = createWeixinStore(dir);
23
+ const binding = bind(store);
24
+ store.accept(binding, 'old-cursor', [{ id: 'legacy', text: 'old message', context: 'old-context' }]);
25
+ store.close();
26
+ const db = new Database(path.join(dir, 'channel.sqlite'));
27
+ db.exec('ALTER TABLE inbox DROP COLUMN payload');
28
+ db.close();
29
+ store = createWeixinStore(dir);
30
+ cleanup.push(() => store.close());
31
+ expect(store.pending(binding.epoch)).toEqual([expect.objectContaining({ id: 'legacy', text: 'old message', payload: '' })]);
32
+ expect(store.get('bot')).toMatchObject({ epoch: binding.epoch, cursor: 'old-cursor', context_token: 'old-context' });
33
+ store.accept(binding, 'new-cursor', [{ id: 'legacy', text: 'duplicate', payload: 'duplicate' }]);
34
+ expect(store.pending(binding.epoch)[0].text).toBe('old message');
35
+ });
36
+
37
+ it('round-trips pending rich receipts across restart; completed/crash-recovered and transferred receipts clear private payloads', () => {
38
+ const dir = directory();
39
+ let store = createWeixinStore(dir);
40
+ const binding = bind(store);
41
+ const payload = '{"version":1,"media":[{"aes_key":"fake-private-key"}],"items":[]}';
42
+ store.accept(binding, 'cursor', ['pending', 'admitted', 'done'].map((id) => ({ id, text: '', payload })));
43
+ store.markInbox('admitted', 'admitted');
44
+ store.finishTurn('done');
45
+ store.close();
46
+ store = createWeixinStore(dir);
47
+ cleanup.push(() => store.close());
48
+ expect(store.pending(binding.epoch)).toEqual([expect.objectContaining({ id: 'pending', payload })]);
49
+ store.recover(binding.epoch, 'interrupted');
50
+ const db = new Database(path.join(dir, 'channel.sqlite'));
51
+ cleanup.push(() => db.close());
52
+ expect(db.prepare("SELECT payload FROM inbox WHERE id IN ('done','admitted')").all()).toEqual([{ payload: '' }, { payload: '' }]);
53
+ const moved = store.transfer({ sourceAssistantID: 'bot', expectedEpoch: binding.epoch, assistantID: 'other', generation: 0, ordinal: 0, language: 'en', updatedAt: 2 });
54
+ expect(store.pending(moved.epoch)).toEqual([]);
55
+ expect(db.prepare('SELECT payload,text,state FROM inbox').all()).toEqual(Array.from({ length: 3 }, () => ({ payload: '', text: '', state: 'done' })));
56
+ store.unlink('other');
57
+ expect(db.prepare('SELECT COUNT(*) AS count FROM inbox').get().count).toBe(0);
58
+ });
59
+
60
+ it('rolls back receipt payloads, context and cursor together when one receipt insert fails', () => {
61
+ const dir = directory();
62
+ const store = createWeixinStore(dir);
63
+ cleanup.push(() => store.close());
64
+ const binding = bind(store);
65
+ const db = new Database(path.join(dir, 'channel.sqlite'));
66
+ cleanup.push(() => db.close());
67
+ db.exec("CREATE TRIGGER reject_bad BEFORE INSERT ON inbox WHEN NEW.id='bad' BEGIN SELECT RAISE(ABORT,'test failure'); END");
68
+ expect(() => store.accept(binding, 'must-not-commit', [{ id: 'ok', text: 'good', payload: 'good', context: 'new-context' }, { id: 'bad', text: '', payload: 'bad' }])).toThrow();
69
+ expect(store.pending(binding.epoch)).toEqual([]);
70
+ expect(store.get('bot')).toMatchObject({ cursor: '', context_token: '' });
71
+ });
72
+ });
@@ -0,0 +1,49 @@
1
+ // Small JSON-only TOON encoder for bounded channel metadata. No key folding or
2
+ // type coercion: external strings must never become structure or literal values.
3
+ const primitive = (value) => value === null || typeof value !== 'object';
4
+ const scalar = (value) => {
5
+ if (typeof value !== 'string') return JSON.stringify(value);
6
+ value = value.toWellFormed();
7
+ if (value && value.trim() === value && !/^(?:true|false|null)$/.test(value)
8
+ && !/^[+-]?(?:\d|\.\d)/.test(value) && !/^[-#\uFEFF]/.test(value)
9
+ && !/[:,"\\\[\]{}\x00-\x1f]/.test(value)) return value;
10
+ return `"${value.replace(/["\\\x00-\x1f]/g, (char) => ({ '"': '\\"', '\\': '\\\\', '\n': '\\n', '\r': '\\r', '\t': '\\t' })[char]
11
+ || `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`)}"`;
12
+ };
13
+ const keyName = (key) => /^[A-Za-z_][\w.-]*$/.test(key) ? key : `"${key.toWellFormed().replace(/["\\\x00-\x1f]/g, (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, '0')}`)}"`;
14
+
15
+ export function encodeWeixinTOON(value) {
16
+ const lines = [];
17
+ const emit = (key, data, depth) => {
18
+ const pad = ' '.repeat(depth);
19
+ if (Array.isArray(data)) {
20
+ if (!data.length) { lines.push(`${pad}${key ? `${key}: []` : '[0]:'}`); return; }
21
+ if (data.every(primitive)) { lines.push(`${pad}${key}[${data.length}]: ${data.map(scalar).join(',')}`); return; }
22
+ const fields = data[0] && !Array.isArray(data[0]) && !primitive(data[0]) ? Object.keys(data[0]) : [];
23
+ if (fields.length && data.every((row) => row && !Array.isArray(row) && !primitive(row)
24
+ && Object.keys(row).length === fields.length && fields.every((field) => Object.hasOwn(row, field) && primitive(row[field])))) {
25
+ lines.push(`${pad}${key}[${data.length}]{${fields.map(keyName).join(',')}}:`);
26
+ for (const row of data) lines.push(`${pad} ${fields.map((field) => scalar(row[field])).join(',')}`);
27
+ return;
28
+ }
29
+ lines.push(`${pad}${key}[${data.length}]:`);
30
+ for (const item of data) {
31
+ const start = lines.length;
32
+ if (primitive(item)) lines.push(`${pad} - ${scalar(item)}`);
33
+ else if (Array.isArray(item)) {
34
+ emit('', item, depth + 2);
35
+ lines[start] = `${pad} - ${lines[start].trimStart()}`;
36
+ } else {
37
+ for (const [field, child] of Object.entries(item)) emit(keyName(field), child, depth + 2);
38
+ if (lines.length === start) lines.push(`${pad} -`);
39
+ else lines[start] = `${pad} - ${lines[start].trimStart()}`;
40
+ }
41
+ }
42
+ } else if (!primitive(data)) {
43
+ lines.push(`${pad}${key}:`);
44
+ for (const [field, child] of Object.entries(data)) emit(keyName(field), child, depth + 1);
45
+ } else lines.push(`${pad}${key}: ${scalar(data)}`);
46
+ };
47
+ for (const [key, child] of Object.entries(value)) emit(keyName(key), child, 0);
48
+ return lines.join('\n');
49
+ }