@yuriai/web 0.2.27-beta.3 → 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.
- package/README.md +17 -0
- package/dist/assets/{AgentAvatar-kIN4sZMz.js → AgentAvatar-BJ42lGZD.js} +1 -1
- package/dist/assets/AssistantContactStatus-dtkObamV.js +3 -0
- package/dist/assets/AssistantUnreadBadge-QwhBfXpC.js +1 -0
- package/dist/assets/AssistantView-D7ryIKL0.js +1 -0
- package/dist/assets/{DiagramView-DK0iXm9b.js → DiagramView-ERrGEBDp.js} +1 -1
- package/dist/assets/{FadeInOnReveal-BJA9Za3T.js → FadeInOnReveal-Bu2GvaM9.js} +1 -1
- package/dist/assets/GuiPluginSurface-MzQgEZNr.js +1 -0
- package/dist/assets/{GuiPluginWindow-l4FYY6S-.js → GuiPluginWindow-DZMmlQzx.js} +1 -1
- package/dist/assets/Icon-Dj4CCqCP.js +1 -0
- package/dist/assets/{ImageLoadingPlaceholder-DCWssLJG.js → ImageLoadingPlaceholder-BnFXgUuO.js} +1 -1
- package/dist/assets/{LoadingImage-C_Hryaqe.js → LoadingImage-PBnivDKv.js} +1 -1
- package/dist/assets/{MarkdownRenderer-Y6uQXIFH.js → MarkdownRenderer-BajF4gUU.js} +2 -2
- package/dist/assets/{MarkdownRendererImpl-qKp1tQrP.js → MarkdownRendererImpl-CfyXL4rg.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-B_JTod0h.js → MarkstreamRendererImpl-BGadklK1.js} +1 -1
- package/dist/assets/MobileDetailNavigation-DqajQdB4.js +1 -0
- package/dist/assets/{MobileResizableSheet-F1zSUD1S.js → MobileResizableSheet-BvdUgwA3.js} +1 -1
- package/dist/assets/{MobileShareBridge-F70fkIfS.js → MobileShareBridge-3oPoYnry.js} +2 -2
- package/dist/assets/MobileTabPageHeader-B6cRyIRH.js +2 -0
- package/dist/assets/{MultiRunWindow-D8m6R_4x.js → MultiRunWindow-yhs0Ih5_.js} +1 -1
- package/dist/assets/{OnboardingScreen-BAsPVV_W.js → OnboardingScreen-Bi1VWFQC.js} +1 -1
- package/dist/assets/{OverlayScrollbar-wiRM4AGj.js → OverlayScrollbar-BBDwGvGO.js} +1 -1
- package/dist/assets/{SettingsView-izzjIckv.js → SettingsView-BSf-SJUA.js} +15 -15
- package/dist/assets/{SettingsWindow-CSuHDq_c.js → SettingsWindow-BvSXVMTm.js} +1 -1
- package/dist/assets/TerminalView-DhL01N7e.js +8 -0
- package/dist/assets/{ToolOutputDialog-DJs9w1_J.js → ToolOutputDialog-C8lnH4Ky.js} +1 -1
- package/dist/assets/{YuriLogo-aBS6wlYU.js → YuriLogo-D8asj1CS.js} +1 -1
- package/dist/assets/{appThemeRegistry-BY5rY9-W.js → appThemeRegistry-C-maYSdv.js} +1 -1
- package/dist/assets/{assistant-attachment-cache-B9iHLlm2.js → assistant-attachment-cache-B_qRvy-k.js} +1 -1
- package/dist/assets/{button-Dt6Ygbc7.js → button-vXOdzd8x.js} +1 -1
- package/dist/assets/{capgoAdapter-MQ1qpf60.js → capgoAdapter-DJ_h2x5D.js} +1 -1
- package/dist/assets/{collapsible-Dm7OHk7m.js → collapsible-DwDQs3Wa.js} +1 -1
- package/dist/assets/context-menu-BabBujQ-.js +1 -0
- package/dist/assets/{desktopRelayRestore-CoLLVJw8.js → desktopRelayRestore-D1UX7HW2.js} +1 -1
- package/dist/assets/{diagram-DWZaG3_v.js → diagram-HwgrQxY5.js} +1 -1
- package/dist/assets/{dialog-CjQeHVOc.js → dialog-Dnf626tb.js} +1 -1
- package/dist/assets/dropdown-menu.styles-CBc_a-Nv.js +1 -0
- package/dist/assets/es-BQkO-Odr.js +15 -0
- package/dist/assets/feishu-Ct1ZxlzQ.svg +6 -0
- package/dist/assets/{fileMentionTouchSelection-D7QtVxjI.js → fileMentionTouchSelection-CKPnEetl.js} +1 -1
- package/dist/assets/{fileQueries-5a1jkme2.js → fileQueries-BeXkd3o6.js} +1 -1
- package/dist/assets/{fileReferenceActions-BAoEu4z8.js → fileReferenceActions-g7KZLi_G.js} +1 -1
- package/dist/assets/fr-C852roK5.js +13 -0
- package/dist/assets/gitApi-CVq5oKCd.js +370 -0
- package/dist/assets/gitApiHttp-BYOIbYIh.js +7 -0
- package/dist/assets/{gui-9enrif_1.js → gui-M_Rbwkyu.js} +1 -1
- package/dist/assets/host-BW3FEJdU.js +1 -0
- package/dist/assets/{image-loading-Dq1g_wpm.js → image-loading-D5UhMj7Z.js} +1 -1
- package/dist/assets/{input-Dq4usRDa.js → input-BtM712b1.js} +1 -1
- package/dist/assets/insertionBoundaries-Dx3WAY6i.js +1 -0
- package/dist/assets/ja-BqC39qK6.js +15 -0
- package/dist/assets/ko-BMaChAWh.js +15 -0
- package/dist/assets/main-9uP2z1qT.js +2 -0
- package/dist/assets/main-Mey7bCWf.js +169 -0
- package/dist/assets/{markdownHeightCache-C1u0bWDL.js → markdownHeightCache-Bf8iisO4.js} +1 -1
- package/dist/assets/{mcpQueries-D2IxTr4k.js → mcpQueries-DpXqegX5.js} +1 -1
- package/dist/assets/miniChat-DqZvVkme.js +2 -0
- package/dist/assets/mobile-DXAWjYcN.js +2 -0
- package/dist/assets/{mobileBackNavigation-vpCg1S7j.js → mobileBackNavigation-DZcI7aZg.js} +1 -1
- package/dist/assets/{multirun-DT-dFXud.js → multirun-hzspPepd.js} +1 -1
- package/dist/assets/{native-De1DIkLZ.js → native-H7K64Ulc.js} +1 -1
- package/dist/assets/{native-config-ncdoz9Wl.js → native-config-CddZtLQ1.js} +1 -1
- package/dist/assets/{persistence-JyLTFv27.js → persistence-BT8045Ue.js} +1 -1
- package/dist/assets/pl-Ubs8p28T.js +15 -0
- package/dist/assets/projectMeta-CEf0QPmD.js +1 -0
- package/dist/assets/pt-BR-8rAOjJrs.js +15 -0
- package/dist/assets/{queryRuntime-Dkpnq3Z1.js → queryRuntime-CTcigFdj.js} +1 -1
- package/dist/assets/react-DRe85o5s.js +1 -0
- package/dist/assets/readiness-Dyr7314z.js +1 -0
- package/dist/assets/renderElectronMiniChatApp-DoOq8Cuo.js +2 -0
- package/dist/assets/renderMobileApp-TTxtOb8b.js +28 -0
- package/dist/assets/runtime-fetch-D0YWp3FJ.js +1 -0
- package/dist/assets/{runtime-file-download-CcNIVp7u.js → runtime-file-download-Cf1WxfeW.js} +1 -1
- package/dist/assets/{runtime-file-resource-6np6lzoV.js → runtime-file-resource-UJjHUF2C.js} +1 -1
- package/dist/assets/runtimeConfig-B8VHHNxj.js +2 -0
- package/dist/assets/runtimeEndpointReset-BC6XWntz.js +149 -0
- package/dist/assets/scheduledTaskNavigation-Zm87Nydi.js +1 -0
- package/dist/assets/sessionLookup-De53jDwM.js +1 -0
- package/dist/assets/sortable-tabs-strip-D4pVoodN.js +1 -0
- package/dist/assets/speechSettingsQueries-RlCLMBtr.js +4 -0
- package/dist/assets/src-lE4uqaHS.css +2 -0
- package/dist/assets/store-ME7oHni1.js +15 -0
- package/dist/assets/{terminalApi-B5o8UqWA.js → terminalApi-BSaclMDJ.js} +1 -1
- package/dist/assets/{textarea-vtIQM2iP.js → textarea-B98rsLs7.js} +1 -1
- package/dist/assets/{tooltip-BpG2mxrT.js → tooltip-B9810jbK.js} +1 -1
- package/dist/assets/{types-CNTgeeM1.js → types-DFf9vd1b.js} +1 -1
- package/dist/assets/{uk-B_JwElWz.js → uk-LzwzUApL.js} +4 -4
- package/dist/assets/{useAppFontEffects-BguV1Hfa.js → useAppFontEffects-D2C1sBYM.js} +59 -57
- package/dist/assets/{useAssistantUIStore-C9FPlYQz.js → useAssistantUIStore-TUN_ycy5.js} +1 -1
- package/dist/assets/useDesktopWindowControlsLayout-BjKaHN0x.js +1 -0
- package/dist/assets/{useEffectiveDirectory-Ci6Z13kj.js → useEffectiveDirectory-TEvyiQSC.js} +1 -1
- package/dist/assets/{useFontPreferences-DMiP_Yy-.js → useFontPreferences-BlhlCJCX.js} +1 -1
- package/dist/assets/useMobileNavigationStore-DTvJV9s-.js +23 -0
- package/dist/assets/useUIStore-DRx6OgCp.js +1 -0
- package/dist/assets/{useWorkerHighlightedLines-HKhuYGSj.js → useWorkerHighlightedLines-D093jNsH.js} +1 -1
- package/dist/assets/{vendor-codemirror-search-ZqtrPLjU.js → vendor-codemirror-search-DiPwvA-6.js} +2 -2
- package/dist/assets/vendor-opencode-client-ZeOZ4Efz.js +23 -0
- package/dist/assets/{vendor-opencode-plugin-Bw7Q6Nv9.js → vendor-opencode-plugin-BBOP6WNx.js} +1 -1
- package/dist/assets/{vendor-replit-codemirror-vim-DDj0dSVY.js → vendor-replit-codemirror-vim-DCdAdxvE.js} +3 -3
- package/dist/assets/{vendor-solid-js-0T254UHG.js → vendor-solid-js-9wmPZH9g.js} +1 -1
- package/dist/assets/zh-CN-D-FVCeks.js +15 -0
- package/dist/assets/zh-TW-B9iH_NXL.js +15 -0
- package/dist/index.html +17 -17
- package/dist/mini-chat.html +17 -17
- package/dist/mobile.html +17 -17
- package/package.json +8 -3
- package/server/lib/assistants/DOCUMENTATION.md +33 -1
- package/server/lib/assistants/channels/DOCUMENTATION.md +291 -0
- package/server/lib/assistants/channels/PROTOCOLS.md +228 -0
- package/server/lib/assistants/channels/dingtalk-chat-adapter.js +633 -0
- package/server/lib/assistants/channels/dingtalk-chat-adapter.test.js +415 -0
- package/server/lib/assistants/channels/integration.test.js +44 -0
- package/server/lib/assistants/channels/routes.js +47 -0
- package/server/lib/assistants/channels/routes.test.js +105 -0
- package/server/lib/assistants/channels/runtime.js +867 -0
- package/server/lib/assistants/channels/runtime.test.js +723 -0
- package/server/lib/assistants/channels/sdk-adapters.js +371 -0
- package/server/lib/assistants/channels/sdk-adapters.test.js +367 -0
- package/server/lib/assistants/channels/store.js +246 -0
- package/server/lib/assistants/channels/store.test.js +286 -0
- package/server/lib/assistants/channels/transport.js +41 -0
- package/server/lib/assistants/channels/transport.test.js +23 -0
- package/server/lib/assistants/channels/wecom-chat-adapter.js +689 -0
- package/server/lib/assistants/channels/wecom-chat-adapter.test.js +109 -0
- package/server/lib/assistants/contracts.js +1 -0
- package/server/lib/assistants/message-channel-origin.js +7 -0
- package/server/lib/assistants/routes.js +14 -1
- package/server/lib/assistants/service.js +23 -7
- package/server/lib/assistants/service.test.js +151 -0
- package/server/lib/assistants/weixin/DOCUMENTATION.md +147 -8
- package/server/lib/assistants/weixin/api.js +2 -0
- package/server/lib/assistants/weixin/chat-adapter.js +107 -0
- package/server/lib/assistants/weixin/chat-adapter.test.js +62 -0
- package/server/lib/assistants/weixin/inbound.js +147 -0
- package/server/lib/assistants/weixin/inbound.test.js +121 -0
- package/server/lib/assistants/weixin/media.js +79 -0
- package/server/lib/assistants/weixin/media.test.js +66 -0
- package/server/lib/assistants/weixin/routes.js +4 -3
- package/server/lib/assistants/weixin/routes.test.js +30 -0
- package/server/lib/assistants/weixin/runtime.js +157 -66
- package/server/lib/assistants/weixin/runtime.test.js +372 -6
- package/server/lib/assistants/weixin/store.js +20 -3
- package/server/lib/assistants/weixin/store.test.js +72 -0
- package/server/lib/assistants/weixin/toon.js +49 -0
- package/server/lib/assistants/weixin/toon.test.js +25 -0
- package/server/lib/github/DOCUMENTATION.md +9 -8
- package/server/lib/llm/bridge-plugin.bundle.js +188 -188
- package/server/lib/opencode/DOCUMENTATION.md +2 -1
- package/server/lib/opencode/npm-registry.js +7 -21
- package/server/lib/opencode/npm-registry.test.js +36 -5
- package/server/lib/opencode/plugin-icon.d.ts +2 -0
- package/server/lib/opencode/plugin-icon.js +43 -0
- package/server/lib/opencode/plugin-icon.test.js +41 -0
- package/server/lib/opencode/plugin-routes.js +3 -1
- package/server/lib/opencode/plugin-routes.test.js +13 -0
- package/dist/assets/AssistantView-C2KQZ6a4.js +0 -3
- package/dist/assets/GuiPluginSurface-Dz2CdSUA.js +0 -1
- package/dist/assets/Icon-BP1sfnHn.js +0 -1
- package/dist/assets/MobileDetailNavigation-B3rUx5Ve.js +0 -1
- package/dist/assets/MobileTabPageHeader-0esgB2TO.js +0 -2
- package/dist/assets/TerminalView-BtM5-BVx.js +0 -8
- package/dist/assets/dropdown-menu.styles-PdxueXzN.js +0 -1
- package/dist/assets/es-BjI1GHJ5.js +0 -15
- package/dist/assets/fr-Bs7ndHkb.js +0 -13
- package/dist/assets/gitApi-BxQmH8Wg.js +0 -10
- package/dist/assets/gitApiHttp-DHrRqnYh.js +0 -7
- package/dist/assets/host-D1EpSUMR.js +0 -1
- package/dist/assets/insertionBoundaries-CKQL85zy.js +0 -1
- package/dist/assets/ja-DkdV26EW.js +0 -15
- package/dist/assets/ko-B0qoC5da.js +0 -15
- package/dist/assets/main-CNwFqQQd.js +0 -2
- package/dist/assets/main-DPhcXanT.js +0 -169
- package/dist/assets/miniChat-CF2vb25D.js +0 -2
- package/dist/assets/mobile-C24qSj44.js +0 -2
- package/dist/assets/pl-D27Y_GBs.js +0 -15
- package/dist/assets/projectMeta-CG8NLahh.js +0 -1
- package/dist/assets/pt-BR-DbocEu4b.js +0 -15
- package/dist/assets/react-CURmDhtB.js +0 -1
- package/dist/assets/readiness-DSJs_3v4.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-ChZCxxH6.js +0 -2
- package/dist/assets/renderMobileApp-CRv3Il6P.js +0 -28
- package/dist/assets/runtime-fetch-D4ja813o.js +0 -1
- package/dist/assets/runtimeConfig-CZrflo-r.js +0 -2
- package/dist/assets/runtimeEndpointReset-Cx3RE97b.js +0 -149
- package/dist/assets/scheduledTaskNavigation-rhgnZaaj.js +0 -1
- package/dist/assets/sessionChangeSummary-CVUA1AFw.js +0 -1
- package/dist/assets/sessionLookup-C3_vQwLe.js +0 -1
- package/dist/assets/sortable-tabs-strip-C1QmKFdb.js +0 -1
- package/dist/assets/speechSettingsQueries-BSQ-2JTv.js +0 -4
- package/dist/assets/src-NKCZI3Lg.css +0 -2
- package/dist/assets/store-DvN2L3vf.js +0 -15
- package/dist/assets/useDesktopWindowControlsLayout-CwgkVw9f.js +0 -1
- package/dist/assets/useMobileNavigationStore-TCj7ZnhV.js +0 -418
- package/dist/assets/useUIStore-DI7va1HH.js +0 -1
- package/dist/assets/vendor-opencode-client-UL_TecvQ.js +0 -12
- package/dist/assets/zh-CN-DhFFdHQu.js +0 -15
- package/dist/assets/zh-TW-BvehppXO.js +0 -15
- /package/dist/assets/{sessionChangeSummary-8C8nv-EP.css → sessionLookup-8C8nv-EP.css} +0 -0
|
@@ -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()(); });
|
|
@@ -23,9 +24,10 @@ const inbound = (id = '1', peer = 'owner', text = 'hello') => ({
|
|
|
23
24
|
item_list: [{ type: 1, text_item: { text } }],
|
|
24
25
|
});
|
|
25
26
|
|
|
26
|
-
function fixture({ directory = root(), configureAPI, service: externalService, clock } = {}) {
|
|
27
|
+
function fixture({ directory = root(), configureAPI, service: externalService, clock, env = {} } = {}) {
|
|
27
28
|
const pages = new Map();
|
|
28
29
|
const service = externalService ?? {
|
|
30
|
+
snapshot: () => ({ assistants: ['bot', 'other-bot', 'third-bot'].map((id) => ({ id, name: `Name ${id}` })) }),
|
|
29
31
|
channelPage: vi.fn((id, { afterOrdinal = 0, generation = null } = {}) => {
|
|
30
32
|
if (id === 'missing') throw Object.assign(new Error('not_found'), { code: 'not_found' });
|
|
31
33
|
const page = pages.get(id) ?? { generation: 0, messages: [] };
|
|
@@ -45,7 +47,7 @@ function fixture({ directory = root(), configureAPI, service: externalService, c
|
|
|
45
47
|
sendTyping: vi.fn(async () => ({})),
|
|
46
48
|
};
|
|
47
49
|
configureAPI?.(api);
|
|
48
|
-
const runtime = createWeixinRuntime({ directory, service, api, intervalMs: 15, ...(clock ? { clock } : {}) });
|
|
50
|
+
const runtime = createWeixinRuntime({ directory, service, api, env, intervalMs: 15, ...(clock ? { clock } : {}) });
|
|
49
51
|
closers.push(() => runtime.close());
|
|
50
52
|
const bind = async (id = 'bot') => {
|
|
51
53
|
await runtime.startLogin(id, 'zh-CN');
|
|
@@ -56,6 +58,67 @@ function fixture({ directory = root(), configureAPI, service: externalService, c
|
|
|
56
58
|
}
|
|
57
59
|
|
|
58
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
|
+
|
|
76
|
+
it.each([
|
|
77
|
+
{ NODE_ENV: 'development' },
|
|
78
|
+
{ YURI_ELECTRON_DEV: '1' },
|
|
79
|
+
{ YURI_ELECTRON_DEV: 'true' },
|
|
80
|
+
{ NODE_ENV: 'production', YURI_WEIXIN_ENABLED: '0' },
|
|
81
|
+
{ YURI_WEIXIN_ENABLED: 'false' },
|
|
82
|
+
{ YURI_WEIXIN_ENABLED: 'invalid' },
|
|
83
|
+
])('disables channel startup and all mutations without opening storage for %j', async (env) => {
|
|
84
|
+
const directory = path.join(root(), 'must-not-open');
|
|
85
|
+
const api = { getQRCode: vi.fn(), getUpdates: vi.fn(), sendText: vi.fn(), getConfig: vi.fn(), sendTyping: vi.fn() };
|
|
86
|
+
const service = { channelPage: vi.fn(), send: vi.fn() };
|
|
87
|
+
const runtime = createWeixinRuntime({ directory, api, service, env });
|
|
88
|
+
closers.push(() => runtime.close());
|
|
89
|
+
expect(runtime.status('bot')).toEqual({ status: 'disabled', error: null });
|
|
90
|
+
for (const method of ['startLogin', 'verify', 'retry', 'disconnect', 'transfer']) {
|
|
91
|
+
expect(() => runtime[method]('bot', {})).toThrow('channel_disabled');
|
|
92
|
+
}
|
|
93
|
+
runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'turn' } });
|
|
94
|
+
await runtime.forget('bot');
|
|
95
|
+
await runtime.close();
|
|
96
|
+
expect(fs.existsSync(directory)).toBe(false);
|
|
97
|
+
for (const call of Object.values(api)) expect(call).not.toHaveBeenCalled();
|
|
98
|
+
expect(service.send).not.toHaveBeenCalled();
|
|
99
|
+
expect(service.channelPage).not.toHaveBeenCalled();
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it('a disabled dev runtime cannot acquire the production lease or delete its binding', async () => {
|
|
103
|
+
const production = fixture();
|
|
104
|
+
await production.bind();
|
|
105
|
+
const dev = fixture({ directory: production.directory, env: { NODE_ENV: 'development' } });
|
|
106
|
+
expect(dev.runtime.status('bot')).toEqual({ status: 'disabled', error: null });
|
|
107
|
+
await dev.runtime.forget('bot');
|
|
108
|
+
await dev.runtime.close();
|
|
109
|
+
production.updates.push([inbound()]);
|
|
110
|
+
await vi.waitFor(() => expect(production.service.send).toHaveBeenCalledTimes(1));
|
|
111
|
+
expect(production.runtime.status('bot')).toEqual({ status: 'connected', error: null });
|
|
112
|
+
expect(dev.api.getUpdates).not.toHaveBeenCalled();
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
it.each(['1', 'true'])('requires an explicit %s override to enable WeChat in development', async (enabled) => {
|
|
116
|
+
const f = fixture({ env: { NODE_ENV: 'development', YURI_ELECTRON_DEV: '1', YURI_WEIXIN_ENABLED: enabled } });
|
|
117
|
+
await f.bind();
|
|
118
|
+
expect(f.runtime.status('bot').status).toBe('connected');
|
|
119
|
+
expect(f.api.getUpdates).toHaveBeenCalled();
|
|
120
|
+
});
|
|
121
|
+
|
|
59
122
|
it('QR binds one Bot, admits only the owner once, and sends persisted text with the latest context', async () => {
|
|
60
123
|
const f = fixture();
|
|
61
124
|
f.updates.push([inbound('1'), inbound('1'), inbound('2', 'stranger'), { ...inbound('3'), group_id: 'group' }]);
|
|
@@ -71,6 +134,20 @@ describe('Weixin Host runtime', () => {
|
|
|
71
134
|
expect(fs.statSync(path.join(f.directory, 'channel.sqlite')).mode & 0o777).toBe(0o600);
|
|
72
135
|
});
|
|
73
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
|
+
|
|
74
151
|
it('restarts without another scan, keeps deduplication and does not replay admitted tool work', async () => {
|
|
75
152
|
const f = fixture();
|
|
76
153
|
f.updates.push([inbound()]);
|
|
@@ -171,13 +248,151 @@ describe('Weixin Host runtime', () => {
|
|
|
171
248
|
expect(f.runtime.status('bot').status).toBe('connected');
|
|
172
249
|
});
|
|
173
250
|
|
|
174
|
-
it('
|
|
251
|
+
it('offers an explicit local move without scanning and preserves cursor/dedup across restart', async () => {
|
|
252
|
+
const f = fixture();
|
|
253
|
+
f.updates.push([inbound('1')]);
|
|
254
|
+
await f.bind();
|
|
255
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1));
|
|
256
|
+
f.reply('other-bot', 'old target history', 50);
|
|
257
|
+
const state = f.runtime.status('other-bot');
|
|
258
|
+
expect(state).toMatchObject({ status: 'disconnected', transferSources: [{ assistantID: 'bot', name: 'Name bot' }] });
|
|
259
|
+
expect(JSON.stringify(state)).not.toMatch(/test-token|context-1|peer_id|account_id/);
|
|
260
|
+
const revision = state.transferSources[0].revision;
|
|
261
|
+
const result = await f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision, language: 'zh-CN' });
|
|
262
|
+
expect(result).toEqual({ status: 'connected', error: null });
|
|
263
|
+
expect(f.runtime.status('bot').status).toBe('disconnected');
|
|
264
|
+
expect(f.api.getQRCode).toHaveBeenCalledTimes(1);
|
|
265
|
+
f.updates.push([inbound('1'), inbound('2')]);
|
|
266
|
+
f.reply('bot', 'late old bot reply');
|
|
267
|
+
f.reply('other-bot', 'new target reply', 51);
|
|
268
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(2));
|
|
269
|
+
expect(f.service.send.mock.calls[1][0]).toBe('other-bot');
|
|
270
|
+
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(1));
|
|
271
|
+
expect(f.api.sendText.mock.calls[0][1].text).toBe('new target reply');
|
|
272
|
+
expect(f.api.getUpdates.mock.calls.find(([binding]) => binding.assistant_id === 'other-bot')[0].cursor).toBe('next-cursor');
|
|
273
|
+
await f.runtime.close();
|
|
274
|
+
const restarted = fixture({ directory: f.directory });
|
|
275
|
+
restarted.updates.push([inbound('1'), inbound('2')]);
|
|
276
|
+
await vi.waitFor(() => expect(restarted.api.getUpdates).toHaveBeenCalled());
|
|
277
|
+
expect(restarted.api.getUpdates.mock.calls[0][0].assistant_id).toBe('other-bot');
|
|
278
|
+
await new Promise((resolve) => setTimeout(resolve, 60));
|
|
279
|
+
expect(restarted.service.send).not.toHaveBeenCalled();
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
it('rejects stale/occupied/missing/expired transfers without changing the original connection', async () => {
|
|
283
|
+
const f = fixture();
|
|
284
|
+
await f.bind();
|
|
285
|
+
const revision = f.runtime.status('other-bot').transferSources[0].revision;
|
|
286
|
+
await expect(f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision: 'stale' })).rejects.toMatchObject({ code: 'binding_changed' });
|
|
287
|
+
await expect(f.runtime.transfer('missing', { sourceAssistantID: 'bot', revision })).rejects.toMatchObject({ code: 'not_found' });
|
|
288
|
+
await expect(f.runtime.transfer('bot', { sourceAssistantID: 'bot', revision })).rejects.toMatchObject({ code: 'validation_error' });
|
|
289
|
+
const second = fixture({ directory: f.directory });
|
|
290
|
+
await expect(second.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision })).rejects.toMatchObject({ code: 'channel_in_use' });
|
|
291
|
+
await second.runtime.close();
|
|
292
|
+
await f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision });
|
|
293
|
+
await expect(f.runtime.transfer('third-bot', { sourceAssistantID: 'bot', revision })).rejects.toMatchObject({ code: 'binding_changed' });
|
|
294
|
+
expect(f.runtime.status('other-bot').status).toBe('connected');
|
|
295
|
+
f.api.getQRStatus.mockResolvedValue({ status: 'confirmed', bot_token: 'second-token', ilink_bot_id: 'second-account', ilink_user_id: 'second-owner' });
|
|
296
|
+
await f.bind('bot');
|
|
297
|
+
const source = f.runtime.status('third-bot').transferSources.find((entry) => entry.assistantID === 'bot');
|
|
298
|
+
await expect(f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision: source.revision })).rejects.toMatchObject({ code: 'binding_changed' });
|
|
299
|
+
f.api.getUpdates.mockRejectedValue(new WeixinError('auth_expired'));
|
|
300
|
+
await vi.waitFor(() => expect(f.runtime.status('bot').status).toBe('expired'));
|
|
301
|
+
await expect(f.runtime.transfer('third-bot', { sourceAssistantID: 'bot', revision: source.revision })).rejects.toMatchObject({ code: 'binding_changed' });
|
|
302
|
+
});
|
|
303
|
+
|
|
304
|
+
it('drains old sending/typing, blocks concurrent mutations and fences a cancelled QR confirmation', async () => {
|
|
305
|
+
const f = fixture();
|
|
306
|
+
f.updates.push([inbound()]);
|
|
307
|
+
await f.bind();
|
|
308
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalled());
|
|
309
|
+
let finishRead;
|
|
310
|
+
let oldSignal;
|
|
311
|
+
f.api.getUpdates.mockImplementationOnce((_binding, signal) => {
|
|
312
|
+
oldSignal = signal;
|
|
313
|
+
return new Promise((resolve) => { finishRead = resolve; });
|
|
314
|
+
});
|
|
315
|
+
let confirm;
|
|
316
|
+
f.api.getQRStatus.mockImplementation(() => new Promise((resolve) => { confirm = resolve; }));
|
|
317
|
+
await f.runtime.startLogin('other-bot');
|
|
318
|
+
await vi.waitFor(() => expect(finishRead).toBeTypeOf('function'));
|
|
319
|
+
f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'live' } });
|
|
320
|
+
await vi.waitFor(() => expect(f.api.sendTyping).toHaveBeenCalled());
|
|
321
|
+
let finishSend;
|
|
322
|
+
f.api.sendText.mockImplementationOnce((_binding, _delivery, signal) => {
|
|
323
|
+
expect(signal.aborted).toBe(false);
|
|
324
|
+
return new Promise((resolve) => { finishSend = resolve; });
|
|
325
|
+
});
|
|
326
|
+
f.reply('bot', 'in flight');
|
|
327
|
+
await vi.waitFor(() => expect(finishSend).toBeTypeOf('function'));
|
|
328
|
+
const revision = f.runtime.status('other-bot').transferSources[0].revision;
|
|
329
|
+
const moving = f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision });
|
|
330
|
+
expect(oldSignal.aborted).toBe(true);
|
|
331
|
+
await expect(f.runtime.transfer('third-bot', { sourceAssistantID: 'bot', revision })).rejects.toMatchObject({ code: 'channel_in_use' });
|
|
332
|
+
await expect(f.runtime.disconnect('bot')).rejects.toMatchObject({ code: 'channel_in_use' });
|
|
333
|
+
expect(() => f.runtime.retry('bot')).toThrow('channel_in_use');
|
|
334
|
+
await expect(f.runtime.startLogin('other-bot')).rejects.toMatchObject({ code: 'channel_in_use' });
|
|
335
|
+
confirm({ status: 'confirmed', bot_token: 'stale-token', ilink_bot_id: 'stale-account', ilink_user_id: 'owner' });
|
|
336
|
+
finishRead({ msgs: [inbound('stale')], get_updates_buf: 'stale-cursor' });
|
|
337
|
+
finishSend({ ret: 0 });
|
|
338
|
+
await moving;
|
|
339
|
+
expect(f.api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1, 2]);
|
|
340
|
+
expect(f.service.send).toHaveBeenCalledTimes(1);
|
|
341
|
+
expect(f.runtime.status('bot').status).toBe('disconnected');
|
|
342
|
+
expect(f.runtime.status('other-bot').status).toBe('connected');
|
|
343
|
+
await expect(f.runtime.transfer('third-bot', { sourceAssistantID: 'bot', revision })).rejects.toMatchObject({ code: 'binding_changed' });
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
it('preserves and resumes the source if the target disappears while draining', async () => {
|
|
347
|
+
const f = fixture();
|
|
348
|
+
await f.bind();
|
|
349
|
+
f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'live' } });
|
|
350
|
+
await vi.waitFor(() => expect(f.api.sendTyping).toHaveBeenCalled());
|
|
351
|
+
let finishCancel;
|
|
352
|
+
f.api.sendTyping.mockImplementationOnce(() => new Promise((resolve) => { finishCancel = resolve; }));
|
|
353
|
+
const revision = f.runtime.status('other-bot').transferSources[0].revision;
|
|
354
|
+
const moving = f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision }).catch((error) => error);
|
|
355
|
+
await vi.waitFor(() => expect(finishCancel).toBeTypeOf('function'));
|
|
356
|
+
f.service.channelPage.mockImplementationOnce(() => { throw Object.assign(new Error('not_found'), { code: 'not_found' }); });
|
|
357
|
+
finishCancel({});
|
|
358
|
+
expect(await moving).toMatchObject({ code: 'not_found' });
|
|
359
|
+
expect(f.runtime.status('bot').status).toBe('connected');
|
|
360
|
+
f.updates.push([inbound('after-failure')]);
|
|
361
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledWith('bot', expect.anything()));
|
|
362
|
+
});
|
|
363
|
+
|
|
364
|
+
it('a failed move leaves an aborted in-flight reply explicitly retryable, never stuck or automatically resent', async () => {
|
|
365
|
+
const f = fixture();
|
|
366
|
+
f.updates.push([inbound()]);
|
|
367
|
+
await f.bind();
|
|
368
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalled());
|
|
369
|
+
f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'live' } });
|
|
370
|
+
await vi.waitFor(() => expect(f.api.sendTyping).toHaveBeenCalled());
|
|
371
|
+
let finishCancel;
|
|
372
|
+
f.api.sendTyping.mockImplementationOnce(() => new Promise((resolve) => { finishCancel = resolve; }));
|
|
373
|
+
f.api.sendText.mockImplementationOnce((_binding, _delivery, signal) => abortable(signal));
|
|
374
|
+
f.reply('bot', 'possibly delivered');
|
|
375
|
+
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(1));
|
|
376
|
+
const revision = f.runtime.status('other-bot').transferSources[0].revision;
|
|
377
|
+
const moving = f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision }).catch((error) => error);
|
|
378
|
+
await vi.waitFor(() => expect(finishCancel).toBeTypeOf('function'));
|
|
379
|
+
f.service.channelPage.mockImplementationOnce(() => { throw Object.assign(new Error('not_found'), { code: 'not_found' }); });
|
|
380
|
+
finishCancel({});
|
|
381
|
+
expect(await moving).toMatchObject({ code: 'not_found' });
|
|
382
|
+
expect(f.runtime.status('bot')).toEqual({ status: 'connected', error: 'delivery_unknown' });
|
|
383
|
+
await new Promise((resolve) => setTimeout(resolve, 60));
|
|
384
|
+
expect(f.api.sendText).toHaveBeenCalledTimes(1);
|
|
385
|
+
f.runtime.retry('bot');
|
|
386
|
+
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(2));
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
it('passes non-text metadata to the bot without pretending unavailable image bytes were read', async () => {
|
|
175
390
|
const f = fixture();
|
|
176
391
|
f.updates.push([{ ...inbound(), item_list: [null, { type: 2, image_item: { media: {} } }] }]);
|
|
177
392
|
await f.bind();
|
|
178
|
-
await vi.waitFor(() => expect(f.
|
|
179
|
-
expect(f.
|
|
180
|
-
expect(f.service.send).
|
|
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');
|
|
181
396
|
});
|
|
182
397
|
|
|
183
398
|
it('reuses the actual Yuri contact pipeline for WeChat → bot → durable reply', async () => {
|
|
@@ -209,6 +424,128 @@ describe('Weixin Host runtime', () => {
|
|
|
209
424
|
await vi.waitFor(() => expect(f.api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1, 2]));
|
|
210
425
|
});
|
|
211
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
|
+
|
|
212
549
|
it.each(['error', 'cancelled'])('clears typing on a live %s terminal event without sending a placeholder text', async (status) => {
|
|
213
550
|
const f = fixture();
|
|
214
551
|
await f.bind();
|
|
@@ -266,6 +603,35 @@ describe('Weixin Host runtime', () => {
|
|
|
266
603
|
});
|
|
267
604
|
|
|
268
605
|
describe('Weixin durable store', () => {
|
|
606
|
+
it('moves atomically, preserves credentials/cursor/receipt IDs, drops old work, and rolls back failed writes', () => {
|
|
607
|
+
const store = createWeixinStore(root());
|
|
608
|
+
closers.push(() => store.close());
|
|
609
|
+
const initial = { token: 'test-token', peer_id: 'owner', base_url: 'https://ilinkai.weixin.qq.com', language: 'en', generation: 0, ordinal: 0, updated_at: 1 };
|
|
610
|
+
const a = store.bind({ ...initial, assistant_id: 'a', account_id: 'account-a' });
|
|
611
|
+
store.accept(a, 'cursor', [{ id: 'done', text: 'old', context: 'ctx' }, { id: 'pending', text: 'pending' }]);
|
|
612
|
+
store.markInbox('done', 'admitted');
|
|
613
|
+
store.enqueue(a.epoch, 'old-delivery', 'old reply');
|
|
614
|
+
const move = { sourceAssistantID: 'a', expectedEpoch: a.epoch, assistantID: 'b', generation: 5, ordinal: 42, language: 'zh-CN', updatedAt: 2 };
|
|
615
|
+
expect(() => store.transfer({ ...move, ordinal: null })).toThrow();
|
|
616
|
+
expect(store.get('a').epoch).toBe(a.epoch);
|
|
617
|
+
expect(store.pending(a.epoch)).toHaveLength(1);
|
|
618
|
+
expect(store.nextDelivery(a.epoch).text).toBe('old reply');
|
|
619
|
+
const b = store.transfer(move);
|
|
620
|
+
expect(store.get('a')).toBeNull();
|
|
621
|
+
expect(b).toMatchObject({ ...initial, assistant_id: 'b', language: 'zh-CN', generation: 5, ordinal: 42, updated_at: 2, cursor: 'cursor', context_token: 'ctx' });
|
|
622
|
+
expect(b.epoch).not.toBe(a.epoch);
|
|
623
|
+
expect(store.nextDelivery(b.epoch)).toBeUndefined();
|
|
624
|
+
store.accept(b, 'next', [{ id: 'done', text: 'replay' }, { id: 'pending', text: 'replay' }, { id: 'fresh', text: 'new' }]);
|
|
625
|
+
expect(store.pending(b.epoch).map((row) => row.id)).toEqual(['fresh']);
|
|
626
|
+
store.accept(a, 'stale', [{ id: 'stale', text: 'stale' }]);
|
|
627
|
+
expect(store.get('b').cursor).toBe('next');
|
|
628
|
+
expect(() => store.transfer(move)).toThrow('binding_changed');
|
|
629
|
+
store.bind({ ...initial, assistant_id: 'c', account_id: 'account-c' });
|
|
630
|
+
expect(() => store.transfer({ ...move, sourceAssistantID: 'b', expectedEpoch: b.epoch, assistantID: 'c' })).toThrow('binding_changed');
|
|
631
|
+
expect(store.get('b').epoch).toBe(b.epoch);
|
|
632
|
+
expect(store.get('c').account_id).toBe('account-c');
|
|
633
|
+
});
|
|
634
|
+
|
|
269
635
|
it('rolls back a conflicting rebind, persists cursor/receipt together, and fences old epochs', () => {
|
|
270
636
|
const store = createWeixinStore(root());
|
|
271
637
|
closers.push(() => store.close());
|
|
@@ -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']);
|
|
@@ -61,22 +64,36 @@ export function createWeixinStore(directory) {
|
|
|
61
64
|
.run({ ...value, epoch: randomUUID() });
|
|
62
65
|
return get(value.assistant_id);
|
|
63
66
|
}),
|
|
67
|
+
transfer: db.transaction(({ sourceAssistantID, expectedEpoch, assistantID, generation, ordinal, language, updatedAt }) => {
|
|
68
|
+
const source = get(sourceAssistantID);
|
|
69
|
+
if (!source || source.epoch !== expectedEpoch || source.status === 'expired' || get(assistantID)) {
|
|
70
|
+
const error = new Error('binding_changed'); error.code = 'binding_changed'; throw error;
|
|
71
|
+
}
|
|
72
|
+
const epoch = randomUUID();
|
|
73
|
+
// Keep receipt IDs across moves so a replay cannot execute tools in the new Bot.
|
|
74
|
+
db.prepare("UPDATE inbox SET epoch=?,state='done',text='',payload='' WHERE epoch=?").run(epoch, source.epoch);
|
|
75
|
+
db.prepare('DELETE FROM outbox WHERE epoch=?').run(source.epoch);
|
|
76
|
+
db.prepare(`UPDATE binding SET assistant_id=?,epoch=?,generation=?,ordinal=?,language=?,updated_at=?,status='connected',error=NULL WHERE epoch=?`)
|
|
77
|
+
.run(assistantID, epoch, generation, ordinal, language, updatedAt, source.epoch);
|
|
78
|
+
return get(assistantID);
|
|
79
|
+
}),
|
|
64
80
|
accept: db.transaction((binding, cursor, messages) => {
|
|
65
81
|
if (get(binding.assistant_id)?.epoch !== binding.epoch) return;
|
|
66
82
|
for (const message of messages) {
|
|
67
|
-
db.prepare('INSERT OR IGNORE INTO inbox(id,epoch,text) VALUES (
|
|
83
|
+
db.prepare('INSERT OR IGNORE INTO inbox(id,epoch,text,payload) VALUES (?,?,?,?)').run(message.id, binding.epoch, message.text, message.payload || '');
|
|
68
84
|
if (message.context) patch(binding.epoch, { context_token: message.context });
|
|
69
85
|
}
|
|
70
86
|
patch(binding.epoch, { cursor });
|
|
71
87
|
}),
|
|
72
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)),
|
|
73
90
|
backlog: (epoch) => db.prepare("SELECT COUNT(*) AS count FROM inbox WHERE epoch=? AND state IN ('pending','admitted')").get(epoch).count,
|
|
74
91
|
markInbox: (id, state) => db.prepare('UPDATE inbox SET state=? WHERE id=?').run(state, id),
|
|
75
|
-
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),
|
|
76
93
|
recover: db.transaction((epoch, text) => {
|
|
77
94
|
for (const row of db.prepare("SELECT id FROM inbox WHERE epoch=? AND state='admitted'").all(epoch)) {
|
|
78
95
|
enqueue(epoch, `${row.id}:interrupted`, text);
|
|
79
|
-
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);
|
|
80
97
|
}
|
|
81
98
|
// A process exit during HTTP send cannot prove whether Weixin accepted it.
|
|
82
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
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest';
|
|
2
|
+
import { encodeWeixinTOON } from './toon.js';
|
|
3
|
+
|
|
4
|
+
describe('WeChat bounded TOON metadata', () => {
|
|
5
|
+
it('encodes objects, primitive arrays, tables and nested mixed lists using TOON syntax', () => {
|
|
6
|
+
expect(encodeWeixinTOON({ title: '中文文章', tags: ['微信', 'AI'], rows: [{ id: 1, title: 'a' }, { id: 2, title: 'b' }] }))
|
|
7
|
+
.toBe('title: 中文文章\ntags[2]: 微信,AI\nrows[2]{id,title}:\n 1,a\n 2,b');
|
|
8
|
+
expect(encodeWeixinTOON({ items: [1, { meta: { title: '文章' }, url: 'https://example.com' }, ['a', 'b']] }))
|
|
9
|
+
.toBe('items[3]:\n - 1\n - meta:\n title: 文章\n url: "https://example.com"\n - [2]: a,b');
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
it('quotes literal-like strings, hostile keys, delimiters, controls and backslashes without changing their values', () => {
|
|
13
|
+
expect(encodeWeixinTOON({ values: ['true', '05', '-x', '#comment', 'hello, world', '', ' padded ', 'a\nb', '\\bar', '\b\f'] }))
|
|
14
|
+
.toBe('values[10]: "true","05","-x","#comment","hello, world",""," padded ","a\\nb","\\\\bar","\\u0008\\u000c"');
|
|
15
|
+
expect(encodeWeixinTOON({ 'field name': 'value', 'items[9]:\n#': 'payload' }))
|
|
16
|
+
.toBe('"field name": value\n"items[9]:\\u000a#": payload');
|
|
17
|
+
expect(encodeWeixinTOON({ empty: [], obj: {} })).toBe('empty: []\nobj:');
|
|
18
|
+
expect(encodeWeixinTOON({ items: [[], {}] })).toBe('items[2]:\n - [0]:\n -');
|
|
19
|
+
});
|
|
20
|
+
|
|
21
|
+
it('does not claim universal savings; avoids repeated keys in a representative flat card list', () => {
|
|
22
|
+
const data = { articles: Array.from({ length: 20 }, (_, i) => ({ title: `文章${i}`, description: '分享内容摘要', source: '公众号' })) };
|
|
23
|
+
expect(encodeWeixinTOON(data).length).toBeLessThan(JSON.stringify(data).length);
|
|
24
|
+
});
|
|
25
|
+
});
|