@yuriai/web 0.2.27-beta.6 → 0.2.27
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -0
- package/dist/assets/{AgentAvatar-Bi1vvWPC.js → AgentAvatar-DNm_jMna.js} +1 -1
- package/dist/assets/AssistantContactStatus-BPRpgMFh.js +3 -0
- package/dist/assets/{AssistantUnreadBadge-DdJyySwn.js → AssistantUnreadBadge-BssH-RvV.js} +1 -1
- package/dist/assets/AssistantView-CxQv-9Ms.js +1 -0
- package/dist/assets/{DiagramView-CI4bTtxy.js → DiagramView-DPpG0fwx.js} +1 -1
- package/dist/assets/{FadeInOnReveal-BB4qEnAn.js → FadeInOnReveal-S6UbimjB.js} +1 -1
- package/dist/assets/{GuiPluginSurface-CguxFUbM.js → GuiPluginSurface-BOf0JA1T.js} +1 -1
- package/dist/assets/{GuiPluginWindow-DOJ7wuRH.js → GuiPluginWindow-OrYkfQ4m.js} +1 -1
- package/dist/assets/{Icon-t2xvbAyN.js → Icon-BE4mEwzV.js} +1 -1
- package/dist/assets/{ImageLoadingPlaceholder-D1L13TK0.js → ImageLoadingPlaceholder-CBFJC_KD.js} +1 -1
- package/dist/assets/{LoadingImage-5rY_edNm.js → LoadingImage-NLq7_P-i.js} +1 -1
- package/dist/assets/MarkdownRenderer-BaMotAOQ.js +2 -0
- package/dist/assets/{MarkdownRendererImpl-cE-0AYRg.js → MarkdownRendererImpl-Cv6UnGG7.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-BZyqDl82.js → MarkstreamRendererImpl-Rb9O6wkW.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-tbfsMfB-.js → MobileDetailNavigation-CK4KbkeS.js} +1 -1
- package/dist/assets/{MobileResizableSheet-BeRmT6_x.js → MobileResizableSheet-Deidw1br.js} +1 -1
- package/dist/assets/{MobileShareBridge-C3Equ3P_.js → MobileShareBridge-CO_OWEfq.js} +2 -2
- package/dist/assets/MobileTabPageHeader-DbC8L6A4.js +2 -0
- package/dist/assets/{MultiRunWindow-CAM2XPII.js → MultiRunWindow-DtVW9NTV.js} +1 -1
- package/dist/assets/{OnboardingScreen-4ftRerP5.js → OnboardingScreen-C8ld4wO7.js} +1 -1
- package/dist/assets/{OverlayScrollbar-CF0PCvQz.js → OverlayScrollbar-B3auC2WH.js} +1 -1
- package/dist/assets/{SettingsView-2tk4WH7R.js → SettingsView-Cm7woZWl.js} +15 -15
- package/dist/assets/{SettingsWindow-B9zbeJaW.js → SettingsWindow-CdL4PFxW.js} +1 -1
- package/dist/assets/{TerminalView-DfxvTHye.js → TerminalView-CwRB6Yyr.js} +1 -1
- package/dist/assets/{ToolOutputDialog-CrjDIhru.js → ToolOutputDialog-B4BfmoVH.js} +1 -1
- package/dist/assets/{YuriLogo-QvS1ZEHi.js → YuriLogo-BOx0s0Ue.js} +1 -1
- package/dist/assets/{appThemeRegistry-Bb_DtiV9.js → appThemeRegistry-B6woJIX5.js} +1 -1
- package/dist/assets/{assistant-attachment-cache-B9iHLlm2.js → assistant-attachment-cache-B_qRvy-k.js} +1 -1
- package/dist/assets/{button-DinGM3tu.js → button-BXxwtxsG.js} +1 -1
- package/dist/assets/{capgoAdapter-DufzjXRs.js → capgoAdapter-C5HFS-rx.js} +1 -1
- package/dist/assets/{collapsible-Bh1GLNYV.js → collapsible-BEm0787p.js} +1 -1
- package/dist/assets/context-menu-DUwvVUDY.js +1 -0
- package/dist/assets/{desktopRelayRestore-CoLLVJw8.js → desktopRelayRestore-D1UX7HW2.js} +1 -1
- package/dist/assets/device-BcRP6Tjd.js +2 -0
- package/dist/assets/{diagram-BmG-7Jb4.js → diagram-DyY8dxjZ.js} +1 -1
- package/dist/assets/{dialog-BXssfGXA.js → dialog-CLca6ojn.js} +1 -1
- package/dist/assets/dropdown-menu.styles-DGaALKP0.js +1 -0
- package/dist/assets/{es-HP_Ise0X.js → es-CrsHvgue.js} +2 -2
- package/dist/assets/feishu-Ct1ZxlzQ.svg +6 -0
- package/dist/assets/fileMentionAutocompleteState-BZJqfgae.js +2 -0
- package/dist/assets/{fileMentionTouchSelection-DSl0tj2r.js → fileMentionTouchSelection-C4dvP8GY.js} +2 -2
- package/dist/assets/{fileQueries-5a1jkme2.js → fileQueries-BeXkd3o6.js} +1 -1
- package/dist/assets/{fileReferenceActions-CGpBSFq4.js → fileReferenceActions-CrIAce3K.js} +1 -1
- package/dist/assets/{fr-D0kJXJ6U.js → fr-CEgiRlfa.js} +2 -2
- package/dist/assets/{gitApi-Wo0IZow9.js → gitApi-D2G9ny2O.js} +1 -1
- package/dist/assets/{gitApiHttp-De9liKnG.js → gitApiHttp-B7vYwgBh.js} +4 -4
- package/dist/assets/{gui-9enrif_1.js → gui-CJjEj3l4.js} +1 -1
- package/dist/assets/host-CnVx34Dh.js +1 -0
- package/dist/assets/{image-loading-Dq1g_wpm.js → image-loading-D5UhMj7Z.js} +1 -1
- package/dist/assets/{input-v8-rVbo-.js → input-D59Q2pm8.js} +1 -1
- package/dist/assets/insertionBoundaries-CedfTSM5.js +1 -0
- package/dist/assets/{ja-BjHKXazE.js → ja-CX-_p9jZ.js} +2 -2
- package/dist/assets/{ko-Llwnl876.js → ko-D5xlLYJM.js} +2 -2
- package/dist/assets/main-CxpUooVS.js +2 -0
- package/dist/assets/main-Dpm4KxWX.js +169 -0
- package/dist/assets/{markdownHeightCache-BVV2dktw.js → markdownHeightCache-D2VWb_4E.js} +1 -1
- package/dist/assets/{mcpQueries-BoBrB4a4.js → mcpQueries-DQ3KthDF.js} +1 -1
- package/dist/assets/miniChat-CTdj8Ug9.js +2 -0
- package/dist/assets/mobile-ChbA3Q8j.js +2 -0
- package/dist/assets/{mobileBackNavigation-DMSzAvb6.js → mobileBackNavigation-BJqt3oHk.js} +1 -1
- package/dist/assets/{multirun-BhWttsRQ.js → multirun-BILeETbd.js} +1 -1
- package/dist/assets/{native-DSvNnKAm.js → native-BYMhr-xH.js} +1 -1
- package/dist/assets/{native-config-DjdrW_9n.js → native-config-BIY0Cr-l.js} +1 -1
- package/dist/assets/{persistence-CfrHIiIS.js → persistence-CWuLIq1J.js} +2 -2
- package/dist/assets/{pl-BOd_idqn.js → pl-BjH81A_q.js} +2 -2
- package/dist/assets/projectMeta-B9_Uh8YH.js +1 -0
- package/dist/assets/{pt-BR-B8djxMsl.js → pt-BR-Dp5oK2x3.js} +2 -2
- package/dist/assets/{queryRuntime-Dkpnq3Z1.js → queryRuntime-CTcigFdj.js} +1 -1
- package/dist/assets/queue-abort-optimistic-CS5jTJq-.js +1 -0
- package/dist/assets/react-DRe85o5s.js +1 -0
- package/dist/assets/readiness-BNIgH81X.js +1 -0
- package/dist/assets/renderElectronMiniChatApp-asOqV7FB.js +2 -0
- package/dist/assets/renderMobileApp-DAfque7-.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-BX8JirIc.js +2 -0
- package/dist/assets/runtimeEndpointReset-CFQgUiUr.js +149 -0
- package/dist/assets/scheduledTaskNavigation-EomDNVu2.js +1 -0
- package/dist/assets/sessionLookup-BxAaxPOw.js +1 -0
- package/dist/assets/{sortable-tabs-strip-yKyqsqut.js → sortable-tabs-strip-DpbW5MqX.js} +1 -1
- package/dist/assets/speechSettingsQueries-CC0fusUo.js +4 -0
- package/dist/assets/src-BMKjN2ip.css +2 -0
- package/dist/assets/{store-CUBymvAC.js → store-CkIHVrmT.js} +4 -3
- package/dist/assets/{terminalApi-BblSkqch.js → terminalApi-rl9mZAlB.js} +1 -1
- package/dist/assets/{textarea-B39OCNPV.js → textarea-7eTptEtD.js} +1 -1
- package/dist/assets/{tooltip-d8TNN4lx.js → tooltip-BPwoSTzO.js} +1 -1
- package/dist/assets/types-CUtSV1V8.js +2 -0
- package/dist/assets/{uk-BNd7CjVO.js → uk-BEfkaLtM.js} +2 -2
- package/dist/assets/{useAppFontEffects-BVoVpJYO.js → useAppFontEffects-Ck2PdQRx.js} +52 -52
- package/dist/assets/{useAssistantUIStore-Bp6TxG5E.js → useAssistantUIStore-CfaQV3ID.js} +1 -1
- package/dist/assets/useDesktopWindowControlsLayout-DxxOUZj1.js +1 -0
- package/dist/assets/useEffectiveDirectory-CNCQfN_x.js +1 -0
- package/dist/assets/{useFontPreferences-BFyBjtQ6.js → useFontPreferences-DeqW9nRx.js} +1 -1
- package/dist/assets/useMobileNavigationStore-BmVr5a5c.js +17 -0
- package/dist/assets/useUIStore-C6CE42oh.js +1 -0
- package/dist/assets/{useWorkerHighlightedLines-CPxG8Fya.js → useWorkerHighlightedLines-CN_RGaSw.js} +1 -1
- package/dist/assets/{vendor-effect-DV9F8PTZ.js → vendor-effect-X1Hqc7ba.js} +13 -13
- package/dist/assets/vendor-opencode-client-cQ47ywrT.js +23 -0
- package/dist/assets/{vendor-opencode-plugin-CgKz9Hcy.js → vendor-opencode-plugin-BmdTE4Te.js} +1 -1
- package/dist/assets/vendor-opencode-schema-DWT45VBX.js +1 -0
- package/dist/assets/vendor-solid-js-D98iXT7C.js +1 -0
- package/dist/assets/vendor-zod-DZzbCm1s.js +55 -0
- package/dist/assets/{zh-CN-BkTAEOZG.js → zh-CN-DipfA56P.js} +2 -2
- package/dist/assets/{zh-TW-x8SfMzfc.js → zh-TW-B7pXMVjt.js} +2 -2
- package/dist/index.html +18 -18
- package/dist/mini-chat.html +18 -18
- package/dist/mobile.html +18 -18
- package/package.json +6 -1
- package/server/index.js +2 -145
- package/server/lib/assistants/DOCUMENTATION.md +69 -11
- package/server/lib/assistants/cards.js +1 -1
- package/server/lib/assistants/channel-image.js +92 -0
- package/server/lib/assistants/channel-image.test.js +76 -0
- package/server/lib/assistants/channel-output-store.test.js +41 -0
- package/server/lib/assistants/channel-output.integration.test.js +114 -0
- package/server/lib/assistants/channel-output.js +90 -0
- package/server/lib/assistants/channel-output.test.js +79 -0
- package/server/lib/assistants/channels/DOCUMENTATION.md +329 -0
- package/server/lib/assistants/channels/PROTOCOLS.md +250 -0
- package/server/lib/assistants/channels/dingtalk-chat-adapter.js +645 -0
- package/server/lib/assistants/channels/dingtalk-chat-adapter.test.js +423 -0
- package/server/lib/assistants/channels/integration.test.js +44 -0
- package/server/lib/assistants/channels/routes.js +59 -0
- package/server/lib/assistants/channels/routes.test.js +139 -0
- package/server/lib/assistants/channels/runtime.js +958 -0
- package/server/lib/assistants/channels/runtime.test.js +897 -0
- package/server/lib/assistants/channels/sdk-adapters.js +383 -0
- package/server/lib/assistants/channels/sdk-adapters.test.js +384 -0
- package/server/lib/assistants/channels/store.js +249 -0
- package/server/lib/assistants/channels/store.test.js +296 -0
- package/server/lib/assistants/channels/transport.js +42 -0
- package/server/lib/assistants/channels/transport.test.js +23 -0
- package/server/lib/assistants/channels/wecom-chat-adapter.js +703 -0
- package/server/lib/assistants/channels/wecom-chat-adapter.test.js +130 -0
- package/server/lib/assistants/contact-store.js +9 -3
- package/server/lib/assistants/contact-store.test.js +27 -0
- package/server/lib/assistants/contact-tools.js +65 -75
- package/server/lib/assistants/contact-tools.test.js +114 -22
- package/server/lib/assistants/harness.js +79 -34
- package/server/lib/assistants/harness.test.js +52 -20
- package/server/lib/assistants/message-channel-origin.js +7 -0
- package/server/lib/assistants/resource-reference.integration.test.js +284 -0
- package/server/lib/assistants/routes.js +14 -4
- package/server/lib/assistants/service.js +116 -69
- package/server/lib/assistants/service.test.js +31 -17
- package/server/lib/assistants/weixin/DOCUMENTATION.md +121 -14
- package/server/lib/assistants/weixin/api.js +45 -1
- package/server/lib/assistants/weixin/api.test.js +28 -0
- package/server/lib/assistants/weixin/chat-adapter.js +113 -0
- package/server/lib/assistants/weixin/chat-adapter.test.js +62 -0
- package/server/lib/assistants/weixin/inbound.js +149 -0
- package/server/lib/assistants/weixin/inbound.test.js +141 -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/runtime.js +105 -74
- package/server/lib/assistants/weixin/runtime.test.js +192 -4
- package/server/lib/assistants/weixin/store.js +16 -8
- package/server/lib/assistants/weixin/store.test.js +93 -0
- package/server/lib/assistants/weixin/toon.js +49 -0
- package/server/lib/assistants/weixin/toon.test.js +25 -0
- package/server/lib/assistants/yuri-project.http.test.js +9 -3
- package/server/lib/github/DOCUMENTATION.md +9 -8
- package/server/lib/llm/bridge-plugin.bundle.js +188 -188
- package/server/lib/notifications/DOCUMENTATION.md +6 -0
- package/server/lib/notifications/runtime.js +26 -15
- package/server/lib/notifications/runtime.test.js +14 -13
- package/server/lib/opencode/DOCUMENTATION.md +10 -1
- package/server/lib/opencode/auth.d.ts +6 -2
- package/server/lib/opencode/core-routes.js +0 -1
- package/server/lib/opencode/feature-routes-runtime.js +0 -24
- package/server/lib/opencode/location-release.d.ts +5 -1
- package/server/lib/opencode/managed-capabilities/scheduled-task.js +1 -1
- package/server/lib/opencode/managed-capabilities-runtime.test.js +1 -1
- package/server/lib/opencode/native-goal.js +15 -0
- package/server/lib/opencode/native-goal.test.js +17 -0
- package/server/lib/opencode/settings-helpers.js +0 -6
- package/server/lib/opencode/shutdown-runtime.js +0 -2
- package/server/lib/projects/project-config.js +3 -6
- package/server/lib/scheduled-tasks/DOCUMENTATION.md +10 -35
- package/server/lib/scheduled-tasks/managed-tool-route.js +1 -30
- package/server/lib/scheduled-tasks/routes.js +0 -26
- package/server/lib/scheduled-tasks/runtime.js +33 -257
- package/server/lib/scheduled-tasks/runtime.test.js +24 -65
- package/server/lib/session-metadata/DOCUMENTATION.md +9 -12
- package/server/lib/session-metadata/routes.js +4 -38
- package/server/lib/session-metadata/routes.test.js +2 -2
- package/dist/assets/AssistantContactStatus-CWq-PDz6.js +0 -3
- package/dist/assets/AssistantView-Br1iETTs.js +0 -1
- package/dist/assets/MarkdownRenderer-BlGxjOei.js +0 -2
- package/dist/assets/MobileTabPageHeader-DQRqAAEf.js +0 -2
- package/dist/assets/context-menu-DpbkRkk1.js +0 -1
- package/dist/assets/device-BjRYYXNT.js +0 -2
- package/dist/assets/host-FR_grJxM.js +0 -1
- package/dist/assets/insertionBoundaries-CZz7TWJv.js +0 -1
- package/dist/assets/main-Bp9HHqTr.js +0 -2
- package/dist/assets/main-DOwAfmxJ.js +0 -169
- package/dist/assets/miniChat-BJDgCrfF.js +0 -2
- package/dist/assets/mobile-GM9931J_.js +0 -2
- package/dist/assets/projectMeta-31PobC-M.js +0 -1
- package/dist/assets/react-B9v0P7kT.js +0 -1
- package/dist/assets/readiness-CYNnsekT.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-N2r999Bf.js +0 -2
- package/dist/assets/renderMobileApp-CU1ec6Ak.js +0 -28
- package/dist/assets/runtime-fetch-D4ja813o.js +0 -1
- package/dist/assets/runtimeConfig-Db7yfo6L.js +0 -2
- package/dist/assets/runtimeEndpointReset-DO5WVetV.js +0 -149
- package/dist/assets/scheduledTaskNavigation-Bsrhv3Ow.js +0 -1
- package/dist/assets/sessionLookup-DRVy7LM1.js +0 -1
- package/dist/assets/speechSettingsQueries-DU25rmGc.js +0 -4
- package/dist/assets/src-Bckdo2XS.css +0 -2
- package/dist/assets/types-BqFQhQTt.js +0 -2
- package/dist/assets/useDesktopWindowControlsLayout-CYx1LNO5.js +0 -1
- package/dist/assets/useEffectiveDirectory-D8FFE5Yn.js +0 -1
- package/dist/assets/useMobileNavigationStore-BHMFeMjo.js +0 -23
- package/dist/assets/useUIStore-BbYD420L.js +0 -1
- package/dist/assets/vendor-opencode-client-UL_TecvQ.js +0 -12
- package/dist/assets/vendor-solid-js-0T254UHG.js +0 -1
- package/dist/assets/vendor-zod-Dzk5kdUU.js +0 -39
- package/server/lib/session-goal/DOCUMENTATION.md +0 -371
- package/server/lib/session-goal/capability.js +0 -57
- package/server/lib/session-goal/capability.test.js +0 -33
- package/server/lib/session-goal/objectives.js +0 -61
- package/server/lib/session-goal/routes.js +0 -274
- package/server/lib/session-goal/routes.test.js +0 -211
- package/server/lib/session-goal/runtime.js +0 -2452
- package/server/lib/session-goal/runtime.test.js +0 -2125
|
@@ -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,40 @@ function fixture({ directory = root(), configureAPI, service: externalService, c
|
|
|
57
58
|
}
|
|
58
59
|
|
|
59
60
|
describe('Weixin Host runtime', () => {
|
|
61
|
+
it('delivers a generated image natively, ordered with prose, only on its source channel', async () => {
|
|
62
|
+
const f = fixture();
|
|
63
|
+
f.api.sendImage = vi.fn(async () => ({ ret: 0 }));
|
|
64
|
+
f.service.prepareChannelImage = vi.fn(async () => ({ attachmentID: 'att_generated' }));
|
|
65
|
+
f.service.getAssistantContactAttachment = vi.fn(async () => ({ buffer: Buffer.from('image'), mime: 'image/png', filename: 'generated.png' }));
|
|
66
|
+
f.updates.push([inbound('draw')]);
|
|
67
|
+
await f.bind();
|
|
68
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledOnce());
|
|
69
|
+
const turnID = f.service.send.mock.calls[0][1].messageID;
|
|
70
|
+
f.pages.set('bot', { generation: 0, messages: [
|
|
71
|
+
{ ordinal: 1, messageID: 'foreign', turnID: 'channel:wecom:foreign', text: '', cards: [], status: 'complete' },
|
|
72
|
+
{ ordinal: 2, messageID: 'own', turnID, text: 'Before  after', cards: [], status: 'complete' },
|
|
73
|
+
] });
|
|
74
|
+
await vi.waitFor(() => expect(f.api.sendImage).toHaveBeenCalledOnce());
|
|
75
|
+
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(2));
|
|
76
|
+
expect(f.api.sendText.mock.calls.map(([, part]) => part.text)).toEqual(['Before', 'after']);
|
|
77
|
+
expect(f.api.sendImage.mock.calls[0][1]).toMatchObject({ image: { buffer: Buffer.from('image') } });
|
|
78
|
+
expect(f.service.prepareChannelImage).toHaveBeenCalledOnce();
|
|
79
|
+
});
|
|
80
|
+
it('does not broadcast other channel replies to WeChat but pushes source-less messages', async () => {
|
|
81
|
+
const f = fixture();
|
|
82
|
+
f.updates.push([inbound('own-turn')]);
|
|
83
|
+
await f.bind();
|
|
84
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledOnce());
|
|
85
|
+
const turnID = f.service.send.mock.calls[0][1].messageID;
|
|
86
|
+
f.pages.set('bot', { generation: 0, messages: [
|
|
87
|
+
{ ordinal: 1, messageID: 'enterprise-output', turnID: 'channel:feishu:some-turn', text: 'not for WeChat', cards: [], status: 'complete' },
|
|
88
|
+
{ ordinal: 2, messageID: 'own-output', turnID, text: 'WeChat reply', cards: [], status: 'complete' },
|
|
89
|
+
{ ordinal: 3, messageID: 'push-output', turnID: 'app-turn', text: 'proactive push', cards: [], status: 'complete' },
|
|
90
|
+
] });
|
|
91
|
+
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(2));
|
|
92
|
+
expect(f.api.sendText.mock.calls.map(([, delivery]) => delivery.text)).toEqual(['WeChat reply', 'proactive push']);
|
|
93
|
+
});
|
|
94
|
+
|
|
60
95
|
it.each([
|
|
61
96
|
{ NODE_ENV: 'development' },
|
|
62
97
|
{ YURI_ELECTRON_DEV: '1' },
|
|
@@ -118,6 +153,20 @@ describe('Weixin Host runtime', () => {
|
|
|
118
153
|
expect(fs.statSync(path.join(f.directory, 'channel.sqlite')).mode & 0o777).toBe(0o600);
|
|
119
154
|
});
|
|
120
155
|
|
|
156
|
+
it('uses the reference client item-level stable ID fallback and never fetches unauthorized media', async () => {
|
|
157
|
+
const f = fixture({ configureAPI: (api) => { api.downloadMedia = vi.fn(); } });
|
|
158
|
+
const media = { type: 2, image_item: { media: { encrypt_query_param: 'private-reference' } } };
|
|
159
|
+
f.updates.push([
|
|
160
|
+
{ ...inbound('stranger', 'other-owner'), item_list: [media] },
|
|
161
|
+
{ ...inbound('group'), group_id: 'group', item_list: [media] },
|
|
162
|
+
{ ...inbound(), message_id: undefined, item_list: [{ type: 1, msg_id: 'item-123', text_item: { text: 'item ID message' } }] },
|
|
163
|
+
{ ...inbound(), message_id: 'item-123', item_list: [{ type: 1, text_item: { text: 'item ID message' } }] },
|
|
164
|
+
]);
|
|
165
|
+
await f.bind();
|
|
166
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1));
|
|
167
|
+
expect(f.api.downloadMedia).not.toHaveBeenCalled();
|
|
168
|
+
});
|
|
169
|
+
|
|
121
170
|
it('restarts without another scan, keeps deduplication and does not replay admitted tool work', async () => {
|
|
122
171
|
const f = fixture();
|
|
123
172
|
f.updates.push([inbound()]);
|
|
@@ -159,6 +208,23 @@ describe('Weixin Host runtime', () => {
|
|
|
159
208
|
expect(f.api.sendText.mock.calls[1][1].id).toBe(originalId);
|
|
160
209
|
});
|
|
161
210
|
|
|
211
|
+
it.each([false, true])('a rejected or uncertain notification send does not block later text or Bot input (ambiguous=%s)', async (ambiguous) => {
|
|
212
|
+
const f = fixture({ configureAPI: (api) => api.sendText.mockRejectedValueOnce(new WeixinError('reply_unavailable', { ambiguous })) });
|
|
213
|
+
f.updates.push([inbound()]);
|
|
214
|
+
await f.bind();
|
|
215
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledOnce());
|
|
216
|
+
f.pages.set('bot', { generation: 0, messages: [
|
|
217
|
+
{ ordinal: 1, messageID: 'notification', text: 'Article notes', cards: [], status: 'complete' },
|
|
218
|
+
{ ordinal: 2, messageID: 'result', text: 'Note saved', cards: [], status: 'complete' },
|
|
219
|
+
] });
|
|
220
|
+
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(2));
|
|
221
|
+
expect(f.api.sendText.mock.calls.map(([, delivery]) => delivery.text)).toEqual(['Article notes', 'Note saved']);
|
|
222
|
+
expect(f.runtime.status('bot').error).toBe(ambiguous ? 'delivery_unknown' : 'reply_unavailable');
|
|
223
|
+
f.updates.push([inbound('next')]);
|
|
224
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(2));
|
|
225
|
+
expect(f.api.sendText.mock.calls.filter(([, delivery]) => delivery.text === 'Note saved')).toHaveLength(1);
|
|
226
|
+
});
|
|
227
|
+
|
|
162
228
|
it('shutdown cancels a hanging platform read before closing storage', async () => {
|
|
163
229
|
const f = fixture({ configureAPI: (api) => api.getUpdates.mockImplementation((_binding, signal) => abortable(signal)) });
|
|
164
230
|
await f.bind();
|
|
@@ -356,13 +422,13 @@ describe('Weixin Host runtime', () => {
|
|
|
356
422
|
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(2));
|
|
357
423
|
});
|
|
358
424
|
|
|
359
|
-
it('non-text
|
|
425
|
+
it('passes non-text metadata to the bot without pretending unavailable image bytes were read', async () => {
|
|
360
426
|
const f = fixture();
|
|
361
427
|
f.updates.push([{ ...inbound(), item_list: [null, { type: 2, image_item: { media: {} } }] }]);
|
|
362
428
|
await f.bind();
|
|
363
|
-
await vi.waitFor(() => expect(f.
|
|
364
|
-
expect(f.
|
|
365
|
-
expect(f.service.send).
|
|
429
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalled());
|
|
430
|
+
expect(f.service.send.mock.calls[0][1].parts[0].text).toContain('unavailable');
|
|
431
|
+
expect(f.service.send.mock.calls[0][1].parts[0].text).toContain('image');
|
|
366
432
|
});
|
|
367
433
|
|
|
368
434
|
it('reuses the actual Yuri contact pipeline for WeChat → bot → durable reply', async () => {
|
|
@@ -394,6 +460,128 @@ describe('Weixin Host runtime', () => {
|
|
|
394
460
|
await vi.waitFor(() => expect(f.api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1, 2]));
|
|
395
461
|
});
|
|
396
462
|
|
|
463
|
+
it('routes images, text documents, voice transcripts and share metadata through real contact storage and execution exactly once', async () => {
|
|
464
|
+
const directory = root();
|
|
465
|
+
let runtime;
|
|
466
|
+
const runContactTurn = vi.fn(async () => ({ bubbles: ['已收到图片、文档与分享信息'] }));
|
|
467
|
+
const service = createAssistantsService({
|
|
468
|
+
dbPath: path.join(directory, 'assistants.sqlite'), dataDir: directory,
|
|
469
|
+
buildOpenCodeUrl: () => 'http://127.0.0.1:1', getOpenCodeAuthHeaders: () => ({}),
|
|
470
|
+
getAllowedRoots: () => [directory], runContactTurn,
|
|
471
|
+
onContactTurnEvent: (event) => runtime?.onTurnEvent(event),
|
|
472
|
+
createChatCompletion: async () => ({ choices: [] }),
|
|
473
|
+
});
|
|
474
|
+
closers.push(() => service.close());
|
|
475
|
+
const bot = service.createAssistant({ name: '多模态测试', providerID: 'p', modelID: 'm' });
|
|
476
|
+
const png = Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAusB9Wl6D/8AAAAASUVORK5CYII=', 'base64');
|
|
477
|
+
const f = fixture({ directory: path.join(directory, 'weixin'), service, configureAPI: (api) => {
|
|
478
|
+
api.downloadMedia = vi.fn(async (source) => source.kind === 'image'
|
|
479
|
+
? { buffer: png, mime: 'image/png', filename: 'weixin.png' }
|
|
480
|
+
: { buffer: Buffer.from('文档正文'), mime: 'text/plain', filename: 'notes.txt' });
|
|
481
|
+
} });
|
|
482
|
+
runtime = f.runtime;
|
|
483
|
+
const message = { ...inbound(), item_list: [
|
|
484
|
+
{ type: 1, text_item: { text: '看看这些内容' } },
|
|
485
|
+
{ type: 2, image_item: { media: { encrypt_query_param: 'private-image', aes_key: 'private-key' } } },
|
|
486
|
+
{ type: 4, file_item: { file_name: 'notes.txt', media: { encrypt_query_param: 'private-document', aes_key: 'private-key' } } },
|
|
487
|
+
{ type: 3, voice_item: { text: '顺便读一下这篇公众号文章' } },
|
|
488
|
+
{ type: 99, share: { title: '文章标题', url: 'https://mp.weixin.qq.com/s/example', description: '摘要' } },
|
|
489
|
+
] };
|
|
490
|
+
f.updates.push([message, message]);
|
|
491
|
+
await f.bind(bot.id);
|
|
492
|
+
await vi.waitFor(() => expect(runContactTurn).toHaveBeenCalledTimes(1));
|
|
493
|
+
const parts = runContactTurn.mock.calls[0][0].userParts;
|
|
494
|
+
expect(parts.filter((part) => part.type === 'file')).toEqual([
|
|
495
|
+
expect.objectContaining({ mime: 'image/png', url: `data:image/png;base64,${png.toString('base64')}` }),
|
|
496
|
+
expect.objectContaining({ mime: 'text/plain', url: `data:text/plain;base64,${Buffer.from('文档正文').toString('base64')}` }),
|
|
497
|
+
]);
|
|
498
|
+
expect(parts.at(-1).text).toContain('文章标题');
|
|
499
|
+
expect(parts.at(-1).text).toContain('顺便读一下这篇公众号文章');
|
|
500
|
+
const history = service.contactMessages(bot.id, { limit: 20 });
|
|
501
|
+
const user = history.messages.find((message) => message.role === 'user');
|
|
502
|
+
expect(user.parts.filter((part) => part.type === 'file')).toHaveLength(2);
|
|
503
|
+
expect(JSON.stringify(history)).not.toMatch(/private-key|private-image|private-document|data:image/);
|
|
504
|
+
const attachment = user.parts.find((part) => part.mime === 'image/png');
|
|
505
|
+
expect((await service.getAssistantContactAttachment(bot.id, attachment.attachmentID)).buffer).toEqual(png);
|
|
506
|
+
expect(f.api.downloadMedia).toHaveBeenCalledTimes(2);
|
|
507
|
+
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalled());
|
|
508
|
+
});
|
|
509
|
+
|
|
510
|
+
it('resumes a durable pending media receipt after restart without polling the message again', async () => {
|
|
511
|
+
const directory = root();
|
|
512
|
+
const store = createWeixinStore(directory);
|
|
513
|
+
const binding = store.bind({ assistant_id: 'bot', account_id: 'account', peer_id: 'owner', token: 'test-token',
|
|
514
|
+
base_url: 'https://ilinkai.weixin.qq.com', language: 'en', generation: 0, ordinal: 0, updated_at: 0 });
|
|
515
|
+
const input = normalizeWeixinInput({ ...inbound(), item_list: [{ type: 2, image_item: { media: { encrypt_query_param: 'private-ref' } } }] });
|
|
516
|
+
store.accept(binding, 'persisted-cursor', [{ id: 'persisted-media-id', ...input }]);
|
|
517
|
+
store.close();
|
|
518
|
+
const f = fixture({ directory, configureAPI: (api) => { api.downloadMedia = vi.fn(async () => ({ buffer: Buffer.from('data'), mime: 'image/png', filename: 'image.png' })); } });
|
|
519
|
+
f.service.putAssistantContactAttachment = vi.fn(async () => ({ type: 'file', attachmentID: 'att_image', mime: 'image/png', size: 4 }));
|
|
520
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1));
|
|
521
|
+
expect(f.service.send.mock.calls[0][1]).toMatchObject({ messageID: 'persisted-media-id', parts: expect.arrayContaining([expect.objectContaining({ attachmentID: 'att_image' })]) });
|
|
522
|
+
expect(f.api.getQRCode).not.toHaveBeenCalled();
|
|
523
|
+
});
|
|
524
|
+
|
|
525
|
+
it('keeps sending replies while media downloads; isolates other bindings and fences late completion after disconnect', async () => {
|
|
526
|
+
let completeDownload;
|
|
527
|
+
const f = fixture({ configureAPI: (api) => {
|
|
528
|
+
api.downloadMedia = vi.fn(() => new Promise((resolve) => { completeDownload = resolve; }));
|
|
529
|
+
api.getQRStatus.mockImplementation(async (_origin, qr) => ({ status: 'confirmed', bot_token: 'test-token',
|
|
530
|
+
ilink_bot_id: qr, ilink_user_id: 'owner', baseurl: 'https://ilinkai.weixin.qq.com' }));
|
|
531
|
+
let qrNumber = 0;
|
|
532
|
+
api.getQRCode.mockImplementation(async () => ({ qrcode: `qr-${++qrNumber}`, qrcode_img_content: 'https://example.com/scan' }));
|
|
533
|
+
} });
|
|
534
|
+
f.service.putAssistantContactAttachment = vi.fn();
|
|
535
|
+
await f.bind();
|
|
536
|
+
await f.bind('other-bot');
|
|
537
|
+
let imageReceived = false;
|
|
538
|
+
let otherReceived = false;
|
|
539
|
+
closers.push(() => completeDownload?.({ buffer: Buffer.from('late'), mime: 'image/png', filename: 'late.png' }));
|
|
540
|
+
f.api.getUpdates.mockImplementation(async (binding, signal) => {
|
|
541
|
+
if (!imageReceived && binding.assistant_id === 'bot') {
|
|
542
|
+
imageReceived = true;
|
|
543
|
+
return { msgs: [{ ...inbound(), item_list: [{ type: 2, image_item: { media: { encrypt_query_param: 'private-ref' } } }] }], get_updates_buf: 'next' };
|
|
544
|
+
}
|
|
545
|
+
if (!otherReceived && binding.assistant_id === 'other-bot') {
|
|
546
|
+
otherReceived = true;
|
|
547
|
+
return { msgs: [inbound('other', 'owner', 'other bot request')], get_updates_buf: 'next' };
|
|
548
|
+
}
|
|
549
|
+
return abortable(signal);
|
|
550
|
+
});
|
|
551
|
+
await vi.waitFor(() => expect(completeDownload).toBeTypeOf('function'), { timeout: 3000 });
|
|
552
|
+
f.reply('bot', 'earlier task result');
|
|
553
|
+
f.reply('other-bot', 'another result');
|
|
554
|
+
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(2));
|
|
555
|
+
expect(f.api.downloadMedia).toHaveBeenCalledTimes(1);
|
|
556
|
+
await f.runtime.disconnect('bot');
|
|
557
|
+
completeDownload({ buffer: Buffer.from('late'), mime: 'image/png', filename: 'late.png' });
|
|
558
|
+
await new Promise((resolve) => setTimeout(resolve, 40));
|
|
559
|
+
expect(f.service.putAssistantContactAttachment).not.toHaveBeenCalled();
|
|
560
|
+
expect(f.service.send).toHaveBeenCalledTimes(1);
|
|
561
|
+
expect(f.service.send.mock.calls[0][0]).toBe('other-bot');
|
|
562
|
+
});
|
|
563
|
+
|
|
564
|
+
it.each(['history-reset', 'auth-expired'])('does not admit media prepared across %s', async (change) => {
|
|
565
|
+
let completeDownload;
|
|
566
|
+
const f = fixture({ configureAPI: (api) => {
|
|
567
|
+
api.downloadMedia = vi.fn(() => new Promise((resolve) => { completeDownload = resolve; }));
|
|
568
|
+
} });
|
|
569
|
+
f.service.putAssistantContactAttachment = vi.fn();
|
|
570
|
+
closers.push(() => completeDownload?.({ buffer: Buffer.from('late'), mime: 'image/png', filename: 'late.png' }));
|
|
571
|
+
f.updates.push([{ ...inbound(), item_list: [{ type: 2, image_item: { media: { encrypt_query_param: 'private-ref' } } }] }]);
|
|
572
|
+
await f.bind();
|
|
573
|
+
await vi.waitFor(() => expect(completeDownload).toBeTypeOf('function'));
|
|
574
|
+
if (change === 'history-reset') f.pages.set('bot', { generation: 1, messages: [] });
|
|
575
|
+
else {
|
|
576
|
+
f.api.getUpdates.mockRejectedValueOnce(new WeixinError('auth_expired'));
|
|
577
|
+
await vi.waitFor(() => expect(f.runtime.status('bot').status).toBe('expired'));
|
|
578
|
+
}
|
|
579
|
+
completeDownload({ buffer: Buffer.from('late'), mime: 'image/png', filename: 'late.png' });
|
|
580
|
+
await new Promise((resolve) => setTimeout(resolve, 40));
|
|
581
|
+
expect(f.service.putAssistantContactAttachment).not.toHaveBeenCalled();
|
|
582
|
+
expect(f.service.send).not.toHaveBeenCalled();
|
|
583
|
+
});
|
|
584
|
+
|
|
397
585
|
it.each(['error', 'cancelled'])('clears typing on a live %s terminal event without sending a placeholder text', async (status) => {
|
|
398
586
|
const f = fixture();
|
|
399
587
|
await f.bind();
|
|
@@ -34,6 +34,12 @@ 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
|
+
}
|
|
40
|
+
if (!db.prepare('PRAGMA table_info(outbox)').all().some((column) => column.name === 'image')) {
|
|
41
|
+
db.exec("ALTER TABLE outbox ADD COLUMN image TEXT NOT NULL DEFAULT ''");
|
|
42
|
+
}
|
|
37
43
|
const get = (assistantID) => db.prepare('SELECT * FROM binding WHERE assistant_id=?').get(assistantID) ?? null;
|
|
38
44
|
const patch = (epoch, values) => {
|
|
39
45
|
const allowed = new Set(['cursor', 'context_token', 'generation', 'ordinal', 'status', 'error', 'updated_at']);
|
|
@@ -41,7 +47,7 @@ export function createWeixinStore(directory) {
|
|
|
41
47
|
if (!keys.length) return;
|
|
42
48
|
db.prepare(`UPDATE binding SET ${keys.map((key) => `${key}=?`).join(',')} WHERE epoch=?`).run(...keys.map((key) => values[key]), epoch);
|
|
43
49
|
};
|
|
44
|
-
const enqueue = (epoch, id, text) => db.prepare('INSERT OR IGNORE INTO outbox(id,epoch,text) VALUES (
|
|
50
|
+
const enqueue = (epoch, id, text, image = '') => db.prepare('INSERT OR IGNORE INTO outbox(id,epoch,text,image) VALUES (?,?,?,?)').run(id, epoch, text, image);
|
|
45
51
|
const unlink = db.transaction((assistantID) => {
|
|
46
52
|
const binding = get(assistantID);
|
|
47
53
|
if (!binding) return;
|
|
@@ -68,7 +74,7 @@ export function createWeixinStore(directory) {
|
|
|
68
74
|
}
|
|
69
75
|
const epoch = randomUUID();
|
|
70
76
|
// 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);
|
|
77
|
+
db.prepare("UPDATE inbox SET epoch=?,state='done',text='',payload='' WHERE epoch=?").run(epoch, source.epoch);
|
|
72
78
|
db.prepare('DELETE FROM outbox WHERE epoch=?').run(source.epoch);
|
|
73
79
|
db.prepare(`UPDATE binding SET assistant_id=?,epoch=?,generation=?,ordinal=?,language=?,updated_at=?,status='connected',error=NULL WHERE epoch=?`)
|
|
74
80
|
.run(assistantID, epoch, generation, ordinal, language, updatedAt, source.epoch);
|
|
@@ -77,19 +83,20 @@ export function createWeixinStore(directory) {
|
|
|
77
83
|
accept: db.transaction((binding, cursor, messages) => {
|
|
78
84
|
if (get(binding.assistant_id)?.epoch !== binding.epoch) return;
|
|
79
85
|
for (const message of messages) {
|
|
80
|
-
db.prepare('INSERT OR IGNORE INTO inbox(id,epoch,text) VALUES (
|
|
86
|
+
db.prepare('INSERT OR IGNORE INTO inbox(id,epoch,text,payload) VALUES (?,?,?,?)').run(message.id, binding.epoch, message.text, message.payload || '');
|
|
81
87
|
if (message.context) patch(binding.epoch, { context_token: message.context });
|
|
82
88
|
}
|
|
83
89
|
patch(binding.epoch, { cursor });
|
|
84
90
|
}),
|
|
85
91
|
pending: (epoch) => db.prepare("SELECT * FROM inbox WHERE epoch=? AND state='pending' ORDER BY rowid LIMIT 20").all(epoch),
|
|
92
|
+
hasReceipt: (id, epoch) => typeof id === 'string' && Boolean(db.prepare('SELECT 1 FROM inbox WHERE id=? AND epoch=?').get(id, epoch)),
|
|
86
93
|
backlog: (epoch) => db.prepare("SELECT COUNT(*) AS count FROM inbox WHERE epoch=? AND state IN ('pending','admitted')").get(epoch).count,
|
|
87
94
|
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),
|
|
95
|
+
finishTurn: (id) => db.prepare("UPDATE inbox SET state='done',text='',payload='' WHERE id=?").run(id),
|
|
89
96
|
recover: db.transaction((epoch, text) => {
|
|
90
97
|
for (const row of db.prepare("SELECT id FROM inbox WHERE epoch=? AND state='admitted'").all(epoch)) {
|
|
91
98
|
enqueue(epoch, `${row.id}:interrupted`, text);
|
|
92
|
-
db.prepare("UPDATE inbox SET state='done',text='' WHERE id=?").run(row.id);
|
|
99
|
+
db.prepare("UPDATE inbox SET state='done',text='',payload='' WHERE id=?").run(row.id);
|
|
93
100
|
}
|
|
94
101
|
// A process exit during HTTP send cannot prove whether Weixin accepted it.
|
|
95
102
|
db.prepare("UPDATE outbox SET state='unknown' WHERE epoch=? AND state='sending'").run(epoch);
|
|
@@ -97,15 +104,16 @@ export function createWeixinStore(directory) {
|
|
|
97
104
|
collect: db.transaction((binding, page, deliveries) => {
|
|
98
105
|
if (get(binding.assistant_id)?.epoch !== binding.epoch) return;
|
|
99
106
|
if (binding.generation !== page.generation) db.prepare('DELETE FROM outbox WHERE epoch=?').run(binding.epoch);
|
|
100
|
-
for (const delivery of deliveries) enqueue(binding.epoch, delivery.id, delivery.text);
|
|
107
|
+
for (const delivery of deliveries) enqueue(binding.epoch, delivery.id, delivery.text, delivery.image ? JSON.stringify(delivery.image) : '');
|
|
101
108
|
patch(binding.epoch, { generation: page.generation, ordinal: page.ordinal });
|
|
102
109
|
}),
|
|
103
|
-
nextDelivery: (epoch) => db.prepare("SELECT * FROM outbox WHERE epoch=? AND state
|
|
110
|
+
nextDelivery: (epoch) => db.prepare("SELECT * FROM outbox WHERE epoch=? AND state='pending' ORDER BY sequence LIMIT 1").get(epoch),
|
|
104
111
|
markDelivery: (id, state) => db.prepare('UPDATE outbox SET state=? WHERE id=?').run(state, id),
|
|
105
|
-
sent: (id) => db.prepare("UPDATE outbox SET state='sent',text='' WHERE id=?").run(id),
|
|
112
|
+
sent: (id) => db.prepare("UPDATE outbox SET state='sent',text='',image='' WHERE id=?").run(id),
|
|
106
113
|
retry: (epoch) => db.prepare("UPDATE outbox SET state='pending' WHERE epoch=? AND state IN ('unknown','blocked')").run(epoch),
|
|
107
114
|
unblock: (epoch) => db.prepare("UPDATE outbox SET state='pending' WHERE epoch=? AND state='blocked'").run(epoch),
|
|
108
115
|
hasUnknown: (epoch) => Boolean(db.prepare("SELECT 1 FROM outbox WHERE epoch=? AND state='unknown' LIMIT 1").get(epoch)),
|
|
116
|
+
hasBlocked: (epoch) => Boolean(db.prepare("SELECT 1 FROM outbox WHERE epoch=? AND state='blocked' LIMIT 1").get(epoch)),
|
|
109
117
|
acquire: (owner, now) => Boolean(db.prepare(`INSERT INTO lease(id,owner,expires_at) VALUES (1,?,?)
|
|
110
118
|
ON CONFLICT(id) DO UPDATE SET owner=excluded.owner,expires_at=excluded.expires_at
|
|
111
119
|
WHERE lease.owner=excluded.owner OR lease.expires_at<=?`).run(owner, now + 60_000, now).changes),
|
|
@@ -0,0 +1,93 @@
|
|
|
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('bypasses failed/unknown sends across restart without dropping them or changing pending order', () => {
|
|
21
|
+
const dir = directory();
|
|
22
|
+
let store = createWeixinStore(dir);
|
|
23
|
+
cleanup.push(() => store.close());
|
|
24
|
+
const binding = bind(store);
|
|
25
|
+
for (const id of ['unknown', 'blocked', 'second', 'third']) store.enqueue(binding.epoch, id, id);
|
|
26
|
+
store.markDelivery('unknown', 'unknown');
|
|
27
|
+
store.markDelivery('blocked', 'blocked');
|
|
28
|
+
store.close();
|
|
29
|
+
store = createWeixinStore(dir);
|
|
30
|
+
expect(store.nextDelivery(binding.epoch)).toMatchObject({ id: 'second', state: 'pending' });
|
|
31
|
+
store.sent('second');
|
|
32
|
+
expect(store.nextDelivery(binding.epoch)).toMatchObject({ id: 'third', state: 'pending' });
|
|
33
|
+
expect(store.hasUnknown(binding.epoch)).toBe(true);
|
|
34
|
+
expect(store.hasBlocked(binding.epoch)).toBe(true);
|
|
35
|
+
store.retry(binding.epoch);
|
|
36
|
+
expect(store.nextDelivery(binding.epoch)).toMatchObject({ id: 'unknown', state: 'pending' });
|
|
37
|
+
store.sent('unknown');
|
|
38
|
+
expect(store.nextDelivery(binding.epoch)).toMatchObject({ id: 'blocked', state: 'pending' });
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
it('adds the payload column to an existing text-only database without losing cursor, receipts or binding', () => {
|
|
42
|
+
const dir = directory();
|
|
43
|
+
let store = createWeixinStore(dir);
|
|
44
|
+
const binding = bind(store);
|
|
45
|
+
store.accept(binding, 'old-cursor', [{ id: 'legacy', text: 'old message', context: 'old-context' }]);
|
|
46
|
+
store.close();
|
|
47
|
+
const db = new Database(path.join(dir, 'channel.sqlite'));
|
|
48
|
+
db.exec('ALTER TABLE inbox DROP COLUMN payload');
|
|
49
|
+
db.close();
|
|
50
|
+
store = createWeixinStore(dir);
|
|
51
|
+
cleanup.push(() => store.close());
|
|
52
|
+
expect(store.pending(binding.epoch)).toEqual([expect.objectContaining({ id: 'legacy', text: 'old message', payload: '' })]);
|
|
53
|
+
expect(store.get('bot')).toMatchObject({ epoch: binding.epoch, cursor: 'old-cursor', context_token: 'old-context' });
|
|
54
|
+
store.accept(binding, 'new-cursor', [{ id: 'legacy', text: 'duplicate', payload: 'duplicate' }]);
|
|
55
|
+
expect(store.pending(binding.epoch)[0].text).toBe('old message');
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
it('round-trips pending rich receipts across restart; completed/crash-recovered and transferred receipts clear private payloads', () => {
|
|
59
|
+
const dir = directory();
|
|
60
|
+
let store = createWeixinStore(dir);
|
|
61
|
+
const binding = bind(store);
|
|
62
|
+
const payload = '{"version":1,"media":[{"aes_key":"fake-private-key"}],"items":[]}';
|
|
63
|
+
store.accept(binding, 'cursor', ['pending', 'admitted', 'done'].map((id) => ({ id, text: '', payload })));
|
|
64
|
+
store.markInbox('admitted', 'admitted');
|
|
65
|
+
store.finishTurn('done');
|
|
66
|
+
store.close();
|
|
67
|
+
store = createWeixinStore(dir);
|
|
68
|
+
cleanup.push(() => store.close());
|
|
69
|
+
expect(store.pending(binding.epoch)).toEqual([expect.objectContaining({ id: 'pending', payload })]);
|
|
70
|
+
store.recover(binding.epoch, 'interrupted');
|
|
71
|
+
const db = new Database(path.join(dir, 'channel.sqlite'));
|
|
72
|
+
cleanup.push(() => db.close());
|
|
73
|
+
expect(db.prepare("SELECT payload FROM inbox WHERE id IN ('done','admitted')").all()).toEqual([{ payload: '' }, { payload: '' }]);
|
|
74
|
+
const moved = store.transfer({ sourceAssistantID: 'bot', expectedEpoch: binding.epoch, assistantID: 'other', generation: 0, ordinal: 0, language: 'en', updatedAt: 2 });
|
|
75
|
+
expect(store.pending(moved.epoch)).toEqual([]);
|
|
76
|
+
expect(db.prepare('SELECT payload,text,state FROM inbox').all()).toEqual(Array.from({ length: 3 }, () => ({ payload: '', text: '', state: 'done' })));
|
|
77
|
+
store.unlink('other');
|
|
78
|
+
expect(db.prepare('SELECT COUNT(*) AS count FROM inbox').get().count).toBe(0);
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
it('rolls back receipt payloads, context and cursor together when one receipt insert fails', () => {
|
|
82
|
+
const dir = directory();
|
|
83
|
+
const store = createWeixinStore(dir);
|
|
84
|
+
cleanup.push(() => store.close());
|
|
85
|
+
const binding = bind(store);
|
|
86
|
+
const db = new Database(path.join(dir, 'channel.sqlite'));
|
|
87
|
+
cleanup.push(() => db.close());
|
|
88
|
+
db.exec("CREATE TRIGGER reject_bad BEFORE INSERT ON inbox WHEN NEW.id='bad' BEGIN SELECT RAISE(ABORT,'test failure'); END");
|
|
89
|
+
expect(() => store.accept(binding, 'must-not-commit', [{ id: 'ok', text: 'good', payload: 'good', context: 'new-context' }, { id: 'bad', text: '', payload: 'bad' }])).toThrow();
|
|
90
|
+
expect(store.pending(binding.epoch)).toEqual([]);
|
|
91
|
+
expect(store.get('bot')).toMatchObject({ cursor: '', context_token: '' });
|
|
92
|
+
});
|
|
93
|
+
});
|
|
@@ -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
|
+
});
|
|
@@ -61,7 +61,7 @@ describe('HTTP → real contact Agent → project registry → worker admission'
|
|
|
61
61
|
expect(createWorker).not.toHaveBeenCalled();
|
|
62
62
|
expect(promptWorker).not.toHaveBeenCalled();
|
|
63
63
|
} finally {
|
|
64
|
-
runtime.close(); server.closeAllConnections();
|
|
64
|
+
await runtime.close(); server.closeAllConnections();
|
|
65
65
|
await new Promise((resolve) => server.close(resolve));
|
|
66
66
|
external.complete = null; external.client = null;
|
|
67
67
|
await fs.rm(directory, { recursive: true, force: true });
|
|
@@ -86,7 +86,7 @@ describe('HTTP → real contact Agent → project registry → worker admission'
|
|
|
86
86
|
provider: { list: async () => ({ data: [{ id: 'p' }] }) },
|
|
87
87
|
model: { list: async () => ({ data: [{ id: 'm', providerID: 'p' }] }) },
|
|
88
88
|
skill: { list: async () => ({ data: [] }) },
|
|
89
|
-
session: { create: creates, prompt: prompts, active: async () => ({}) },
|
|
89
|
+
session: { create: creates, prompt: prompts, active: async () => ({}), get: async ({ sessionID }) => ({ id: sessionID, directory: canonical, title: 'Hello', status: { type: 'busy' } }) },
|
|
90
90
|
};
|
|
91
91
|
const roots = [];
|
|
92
92
|
const refresh = async () => {
|
|
@@ -113,6 +113,12 @@ describe('HTTP → real contact Agent → project registry → worker admission'
|
|
|
113
113
|
expect(body.messages.find((message) => message.name === 'register_project')?.content).toContain(canonical);
|
|
114
114
|
return call('assign_session', { projectPath: canonical, prompt: 'hello' });
|
|
115
115
|
}
|
|
116
|
+
if (round === 5) {
|
|
117
|
+
expect(body.tools.map((tool) => tool.function.name)).toEqual(['reference_resource']);
|
|
118
|
+
expect(body.messages.find((message) => message.name === 'assign_session')?.content).toContain('ses_hello');
|
|
119
|
+
return call('reference_resource', { cardType: 'session', sessionID: 'ses_hello' });
|
|
120
|
+
}
|
|
121
|
+
expect(body.messages.find((message) => message.name === 'reference_resource')?.content).toContain('sent');
|
|
116
122
|
return { text: '已在这个项目里创建会话并发送 hello。' };
|
|
117
123
|
};
|
|
118
124
|
const app = express(); app.use(express.json());
|
|
@@ -164,7 +170,7 @@ describe('HTTP → real contact Agent → project registry → worker admission'
|
|
|
164
170
|
expect(prompts.mock.calls.at(-1)[0]).toEqual({ sessionID: 'ses_hello', id: 'ordinary-session', text: 'ordinary hello', delivery: 'steer' });
|
|
165
171
|
expect(round).toBe(modelRounds);
|
|
166
172
|
} finally {
|
|
167
|
-
runtime.close(); server.closeAllConnections();
|
|
173
|
+
await runtime.close(); server.closeAllConnections();
|
|
168
174
|
await new Promise((resolve) => server.close(resolve));
|
|
169
175
|
external.complete = null; external.client = null;
|
|
170
176
|
await fs.rm(directory, { recursive: true, force: true });
|
|
@@ -59,13 +59,14 @@
|
|
|
59
59
|
- The route calls `resolveGitHubPrStatus(...)` in `packages/web/server/lib/github/pr-status.js`.
|
|
60
60
|
- The resolver finds the most likely repo and PR for a local branch.
|
|
61
61
|
- The route then enriches that result with checks, mergeability, and permission-related fields.
|
|
62
|
-
- The client
|
|
62
|
+
- The client retains its explicit PR API and status-store capabilities. The session
|
|
63
|
+
sidebar no longer initiates PR discovery, auth reads, or background refreshes.
|
|
63
64
|
|
|
64
65
|
## Consumers of PR data
|
|
65
66
|
|
|
66
|
-
- `packages/ui/src/components/
|
|
67
|
-
|
|
68
|
-
|
|
67
|
+
- `packages/ui/src/components/views/git/PullRequestSection.tsx` retains the PR
|
|
68
|
+
workflow component, but the current Git view does not mount it. Do not use the
|
|
69
|
+
mere existence of this component as demand for background PR requests.
|
|
69
70
|
- `packages/ui/src/components/ui/MemoryDebugPanel.tsx` reads request counters for debugging.
|
|
70
71
|
|
|
71
72
|
## How PR resolution works
|
|
@@ -84,7 +85,7 @@
|
|
|
84
85
|
- Client key is effectively `directory::branch`.
|
|
85
86
|
- One entry stores last known status, loading state, error, timestamps, watcher count, identity, and resolved remote.
|
|
86
87
|
- Requests are deduplicated by branch signature, not by component instance.
|
|
87
|
-
-
|
|
88
|
+
- The session sidebar has no subscription to this store and does not create entries.
|
|
88
89
|
|
|
89
90
|
## Persistence
|
|
90
91
|
|
|
@@ -96,9 +97,9 @@
|
|
|
96
97
|
|
|
97
98
|
## Polling and refresh model
|
|
98
99
|
|
|
99
|
-
-
|
|
100
|
-
|
|
101
|
-
|
|
100
|
+
- Entry-level polling in `useGitHubPrStatusStore` runs only for actual mounted
|
|
101
|
+
watchers. There is no sidebar/background repo-scanning owner. Startup, session
|
|
102
|
+
changes, and project/worktree expansion do not constitute PR demand.
|
|
102
103
|
|
|
103
104
|
## Entry-level polling rules
|
|
104
105
|
|