@yuriai/web 0.2.27-beta.8 → 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/dist/assets/{AgentAvatar-BJ42lGZD.js → AgentAvatar-DNm_jMna.js} +1 -1
- package/dist/assets/AssistantContactStatus-BPRpgMFh.js +3 -0
- package/dist/assets/{AssistantUnreadBadge-QwhBfXpC.js → AssistantUnreadBadge-BssH-RvV.js} +1 -1
- package/dist/assets/{AssistantView-D7ryIKL0.js → AssistantView-CxQv-9Ms.js} +1 -1
- package/dist/assets/{DiagramView-ERrGEBDp.js → DiagramView-DPpG0fwx.js} +1 -1
- package/dist/assets/{FadeInOnReveal-Bu2GvaM9.js → FadeInOnReveal-S6UbimjB.js} +1 -1
- package/dist/assets/{GuiPluginSurface-MzQgEZNr.js → GuiPluginSurface-BOf0JA1T.js} +1 -1
- package/dist/assets/{GuiPluginWindow-DZMmlQzx.js → GuiPluginWindow-OrYkfQ4m.js} +1 -1
- package/dist/assets/{Icon-Dj4CCqCP.js → Icon-BE4mEwzV.js} +1 -1
- package/dist/assets/{ImageLoadingPlaceholder-BnFXgUuO.js → ImageLoadingPlaceholder-CBFJC_KD.js} +1 -1
- package/dist/assets/{LoadingImage-PBnivDKv.js → LoadingImage-NLq7_P-i.js} +1 -1
- package/dist/assets/MarkdownRenderer-BaMotAOQ.js +2 -0
- package/dist/assets/{MarkdownRendererImpl-CfyXL4rg.js → MarkdownRendererImpl-Cv6UnGG7.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-BGadklK1.js → MarkstreamRendererImpl-Rb9O6wkW.js} +1 -1
- package/dist/assets/{MobileDetailNavigation-DqajQdB4.js → MobileDetailNavigation-CK4KbkeS.js} +1 -1
- package/dist/assets/{MobileResizableSheet-BvdUgwA3.js → MobileResizableSheet-Deidw1br.js} +1 -1
- package/dist/assets/{MobileShareBridge-3oPoYnry.js → MobileShareBridge-CO_OWEfq.js} +2 -2
- package/dist/assets/MobileTabPageHeader-DbC8L6A4.js +2 -0
- package/dist/assets/{MultiRunWindow-yhs0Ih5_.js → MultiRunWindow-DtVW9NTV.js} +1 -1
- package/dist/assets/{OnboardingScreen-Bi1VWFQC.js → OnboardingScreen-C8ld4wO7.js} +1 -1
- package/dist/assets/{OverlayScrollbar-BBDwGvGO.js → OverlayScrollbar-B3auC2WH.js} +1 -1
- package/dist/assets/{SettingsView-BSf-SJUA.js → SettingsView-Cm7woZWl.js} +14 -14
- package/dist/assets/{SettingsWindow-BvSXVMTm.js → SettingsWindow-CdL4PFxW.js} +1 -1
- package/dist/assets/{TerminalView-DhL01N7e.js → TerminalView-CwRB6Yyr.js} +1 -1
- package/dist/assets/{ToolOutputDialog-C8lnH4Ky.js → ToolOutputDialog-B4BfmoVH.js} +1 -1
- package/dist/assets/{YuriLogo-D8asj1CS.js → YuriLogo-BOx0s0Ue.js} +1 -1
- package/dist/assets/{appThemeRegistry-C-maYSdv.js → appThemeRegistry-B6woJIX5.js} +1 -1
- package/dist/assets/{button-vXOdzd8x.js → button-BXxwtxsG.js} +1 -1
- package/dist/assets/{capgoAdapter-DJ_h2x5D.js → capgoAdapter-C5HFS-rx.js} +1 -1
- package/dist/assets/{collapsible-DwDQs3Wa.js → collapsible-BEm0787p.js} +1 -1
- package/dist/assets/{context-menu-BabBujQ-.js → context-menu-DUwvVUDY.js} +1 -1
- package/dist/assets/device-BcRP6Tjd.js +2 -0
- package/dist/assets/{diagram-HwgrQxY5.js → diagram-DyY8dxjZ.js} +1 -1
- package/dist/assets/{dialog-Dnf626tb.js → dialog-CLca6ojn.js} +1 -1
- package/dist/assets/{dropdown-menu.styles-CBc_a-Nv.js → dropdown-menu.styles-DGaALKP0.js} +1 -1
- package/dist/assets/{es-BQkO-Odr.js → es-CrsHvgue.js} +2 -2
- package/dist/assets/fileMentionAutocompleteState-BZJqfgae.js +2 -0
- package/dist/assets/{fileMentionTouchSelection-CKPnEetl.js → fileMentionTouchSelection-C4dvP8GY.js} +2 -2
- package/dist/assets/{fileReferenceActions-g7KZLi_G.js → fileReferenceActions-CrIAce3K.js} +1 -1
- package/dist/assets/{fr-C852roK5.js → fr-CEgiRlfa.js} +2 -2
- package/dist/assets/{gitApi-CVq5oKCd.js → gitApi-D2G9ny2O.js} +1 -1
- package/dist/assets/{gitApiHttp-BYOIbYIh.js → gitApiHttp-B7vYwgBh.js} +4 -4
- package/dist/assets/{gui-M_Rbwkyu.js → gui-CJjEj3l4.js} +1 -1
- package/dist/assets/host-CnVx34Dh.js +1 -0
- package/dist/assets/{input-BtM712b1.js → input-D59Q2pm8.js} +1 -1
- package/dist/assets/insertionBoundaries-CedfTSM5.js +1 -0
- package/dist/assets/{ja-BqC39qK6.js → ja-CX-_p9jZ.js} +2 -2
- package/dist/assets/{ko-BMaChAWh.js → ko-D5xlLYJM.js} +2 -2
- package/dist/assets/main-CxpUooVS.js +2 -0
- package/dist/assets/{main-Mey7bCWf.js → main-Dpm4KxWX.js} +12 -12
- package/dist/assets/{markdownHeightCache-Bf8iisO4.js → markdownHeightCache-D2VWb_4E.js} +1 -1
- package/dist/assets/{mcpQueries-DpXqegX5.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-DZcI7aZg.js → mobileBackNavigation-BJqt3oHk.js} +1 -1
- package/dist/assets/{multirun-hzspPepd.js → multirun-BILeETbd.js} +1 -1
- package/dist/assets/{native-H7K64Ulc.js → native-BYMhr-xH.js} +1 -1
- package/dist/assets/{native-config-CddZtLQ1.js → native-config-BIY0Cr-l.js} +1 -1
- package/dist/assets/{persistence-BT8045Ue.js → persistence-CWuLIq1J.js} +2 -2
- package/dist/assets/{pl-Ubs8p28T.js → pl-BjH81A_q.js} +2 -2
- package/dist/assets/{projectMeta-CEf0QPmD.js → projectMeta-B9_Uh8YH.js} +1 -1
- package/dist/assets/{pt-BR-8rAOjJrs.js → pt-BR-Dp5oK2x3.js} +2 -2
- package/dist/assets/queue-abort-optimistic-CS5jTJq-.js +1 -0
- package/dist/assets/{readiness-Dyr7314z.js → readiness-BNIgH81X.js} +1 -1
- package/dist/assets/renderElectronMiniChatApp-asOqV7FB.js +2 -0
- package/dist/assets/renderMobileApp-DAfque7-.js +28 -0
- package/dist/assets/{runtimeConfig-B8VHHNxj.js → runtimeConfig-BX8JirIc.js} +1 -1
- package/dist/assets/runtimeEndpointReset-CFQgUiUr.js +149 -0
- package/dist/assets/{scheduledTaskNavigation-Zm87Nydi.js → scheduledTaskNavigation-EomDNVu2.js} +1 -1
- package/dist/assets/sessionLookup-BxAaxPOw.js +1 -0
- package/dist/assets/{sortable-tabs-strip-D4pVoodN.js → sortable-tabs-strip-DpbW5MqX.js} +1 -1
- package/dist/assets/{speechSettingsQueries-RlCLMBtr.js → speechSettingsQueries-CC0fusUo.js} +2 -2
- package/dist/assets/src-BMKjN2ip.css +2 -0
- package/dist/assets/{store-ME7oHni1.js → store-CkIHVrmT.js} +4 -3
- package/dist/assets/{terminalApi-BSaclMDJ.js → terminalApi-rl9mZAlB.js} +1 -1
- package/dist/assets/{textarea-B98rsLs7.js → textarea-7eTptEtD.js} +1 -1
- package/dist/assets/{tooltip-B9810jbK.js → tooltip-BPwoSTzO.js} +1 -1
- package/dist/assets/types-CUtSV1V8.js +2 -0
- package/dist/assets/{uk-LzwzUApL.js → uk-BEfkaLtM.js} +2 -2
- package/dist/assets/{useAppFontEffects-D2C1sBYM.js → useAppFontEffects-Ck2PdQRx.js} +37 -37
- package/dist/assets/{useAssistantUIStore-TUN_ycy5.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-BlhlCJCX.js → useFontPreferences-DeqW9nRx.js} +1 -1
- package/dist/assets/useMobileNavigationStore-BmVr5a5c.js +17 -0
- package/dist/assets/{useUIStore-DRx6OgCp.js → useUIStore-C6CE42oh.js} +1 -1
- package/dist/assets/{useWorkerHighlightedLines-D093jNsH.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-BBOP6WNx.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-D-FVCeks.js → zh-CN-DipfA56P.js} +2 -2
- package/dist/assets/{zh-TW-B9iH_NXL.js → zh-TW-B7pXMVjt.js} +2 -2
- package/dist/index.html +12 -12
- package/dist/mini-chat.html +12 -12
- package/dist/mobile.html +12 -12
- package/package.json +1 -1
- package/server/index.js +2 -145
- package/server/lib/assistants/DOCUMENTATION.md +56 -10
- 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 +52 -14
- package/server/lib/assistants/channels/PROTOCOLS.md +23 -1
- package/server/lib/assistants/channels/dingtalk-chat-adapter.js +19 -7
- package/server/lib/assistants/channels/dingtalk-chat-adapter.test.js +8 -0
- package/server/lib/assistants/channels/routes.js +12 -0
- package/server/lib/assistants/channels/routes.test.js +34 -0
- package/server/lib/assistants/channels/runtime.js +117 -26
- package/server/lib/assistants/channels/runtime.test.js +179 -5
- package/server/lib/assistants/channels/sdk-adapters.js +15 -3
- package/server/lib/assistants/channels/sdk-adapters.test.js +17 -0
- package/server/lib/assistants/channels/store.js +9 -6
- package/server/lib/assistants/channels/store.test.js +21 -11
- package/server/lib/assistants/channels/transport.js +2 -1
- package/server/lib/assistants/channels/wecom-chat-adapter.js +16 -2
- package/server/lib/assistants/channels/wecom-chat-adapter.test.js +21 -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/resource-reference.integration.test.js +284 -0
- package/server/lib/assistants/routes.js +0 -3
- package/server/lib/assistants/service.js +116 -69
- package/server/lib/assistants/service.test.js +31 -17
- package/server/lib/assistants/weixin/DOCUMENTATION.md +34 -9
- package/server/lib/assistants/weixin/api.js +43 -1
- package/server/lib/assistants/weixin/api.test.js +28 -0
- package/server/lib/assistants/weixin/chat-adapter.js +8 -2
- package/server/lib/assistants/weixin/inbound.js +5 -3
- package/server/lib/assistants/weixin/inbound.test.js +20 -0
- package/server/lib/assistants/weixin/runtime.js +27 -18
- package/server/lib/assistants/weixin/runtime.test.js +36 -0
- package/server/lib/assistants/weixin/store.js +8 -4
- package/server/lib/assistants/weixin/store.test.js +21 -0
- package/server/lib/assistants/yuri-project.http.test.js +9 -3
- 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 +9 -0
- 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-dtkObamV.js +0 -3
- package/dist/assets/MarkdownRenderer-BajF4gUU.js +0 -2
- package/dist/assets/MobileTabPageHeader-B6cRyIRH.js +0 -2
- package/dist/assets/device-BjRYYXNT.js +0 -2
- package/dist/assets/host-BW3FEJdU.js +0 -1
- package/dist/assets/insertionBoundaries-Dx3WAY6i.js +0 -1
- package/dist/assets/main-9uP2z1qT.js +0 -2
- package/dist/assets/miniChat-DqZvVkme.js +0 -2
- package/dist/assets/mobile-DXAWjYcN.js +0 -2
- package/dist/assets/renderElectronMiniChatApp-DoOq8Cuo.js +0 -2
- package/dist/assets/renderMobileApp-TTxtOb8b.js +0 -28
- package/dist/assets/runtimeEndpointReset-BC6XWntz.js +0 -149
- package/dist/assets/sessionLookup-De53jDwM.js +0 -1
- package/dist/assets/src-lE4uqaHS.css +0 -2
- package/dist/assets/types-DFf9vd1b.js +0 -2
- package/dist/assets/useDesktopWindowControlsLayout-BjKaHN0x.js +0 -1
- package/dist/assets/useEffectiveDirectory-TEvyiQSC.js +0 -1
- package/dist/assets/useMobileNavigationStore-DTvJV9s-.js +0 -23
- package/dist/assets/vendor-opencode-client-ZeOZ4Efz.js +0 -23
- package/dist/assets/vendor-solid-js-9wmPZH9g.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
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { randomBytes } from 'node:crypto';
|
|
1
|
+
import { createHash, createCipheriv, randomBytes } from 'node:crypto';
|
|
2
2
|
import { downloadWeixinMedia } from './media.js';
|
|
3
3
|
|
|
4
4
|
// Wire-format reference: Tencent/openclaw-weixin (MIT), docs/protocol.md.
|
|
@@ -103,6 +103,48 @@ export function createWeixinAPI({ fetchImpl = fetch } = {}) {
|
|
|
103
103
|
token: binding.token, signal, timeoutMs: 5000, allowEmpty: true,
|
|
104
104
|
body: { ilink_user_id: binding.peer_id, typing_ticket: ticket, status },
|
|
105
105
|
}),
|
|
106
|
+
sendImage: async (binding, delivery, signal) => {
|
|
107
|
+
const buffer = delivery.image?.buffer;
|
|
108
|
+
if (!Buffer.isBuffer(buffer) || !buffer.length || buffer.length > 20 * 1024 * 1024) throw new WeixinError('validation_error');
|
|
109
|
+
const key = randomBytes(16);
|
|
110
|
+
const filekey = randomBytes(16).toString('hex');
|
|
111
|
+
const cipher = createCipheriv('aes-128-ecb', key, null);
|
|
112
|
+
const encrypted = Buffer.concat([cipher.update(buffer), cipher.final()]);
|
|
113
|
+
const uploaded = await request(binding.base_url, '/ilink/bot/getuploadurl', {
|
|
114
|
+
token: binding.token, signal,
|
|
115
|
+
body: { filekey, media_type: 1, to_user_id: binding.peer_id, rawsize: buffer.length,
|
|
116
|
+
rawfilemd5: createHash('md5').update(buffer).digest('hex'), filesize: encrypted.length,
|
|
117
|
+
no_need_thumb: true, aeskey: key.toString('hex') },
|
|
118
|
+
});
|
|
119
|
+
const url = new URL(uploaded.upload_full_url || 'https://novac2c.cdn.weixin.qq.com/c2c/upload');
|
|
120
|
+
if (!uploaded.upload_full_url) {
|
|
121
|
+
if (typeof uploaded.upload_param !== 'string' || !uploaded.upload_param) throw new WeixinError('invalid_response');
|
|
122
|
+
url.searchParams.set('encrypted_query_param', uploaded.upload_param);
|
|
123
|
+
url.searchParams.set('filekey', filekey);
|
|
124
|
+
}
|
|
125
|
+
if (url.protocol !== 'https:' || url.hostname !== 'novac2c.cdn.weixin.qq.com' || url.port
|
|
126
|
+
|| url.username || url.password || url.hash || url.pathname !== '/c2c/upload') throw new WeixinError('invalid_response');
|
|
127
|
+
const uploadSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(20_000)]) : AbortSignal.timeout(20_000);
|
|
128
|
+
uploadSignal.throwIfAborted();
|
|
129
|
+
let response;
|
|
130
|
+
try {
|
|
131
|
+
response = await fetchImpl(url.href, { method: 'POST', body: encrypted, redirect: 'error',
|
|
132
|
+
headers: { 'Content-Type': 'application/octet-stream' }, signal: uploadSignal });
|
|
133
|
+
} catch { throw new WeixinError(signal?.aborted ? 'cancelled' : 'network_error'); }
|
|
134
|
+
await response.body?.cancel().catch(() => {});
|
|
135
|
+
const param = response.headers.get('x-encrypted-param');
|
|
136
|
+
if (response.status !== 200 || !param || param.length > 65_536) throw new WeixinError('invalid_response');
|
|
137
|
+
uploadSignal.throwIfAborted();
|
|
138
|
+
delivery.beforeSend?.();
|
|
139
|
+
return request(binding.base_url, '/ilink/bot/sendmessage', {
|
|
140
|
+
token: binding.token, signal, sending: true,
|
|
141
|
+
body: { msg: { from_user_id: '', to_user_id: binding.peer_id, client_id: delivery.id,
|
|
142
|
+
message_type: 2, message_state: 2, context_token: binding.context_token || undefined,
|
|
143
|
+
item_list: [{ type: 2, image_item: { media: { encrypt_query_param: param,
|
|
144
|
+
aes_key: Buffer.from(key.toString('hex')).toString('base64'), encrypt_type: 1 }, mid_size: encrypted.length } }],
|
|
145
|
+
} },
|
|
146
|
+
});
|
|
147
|
+
},
|
|
106
148
|
sendText: (binding, delivery, signal) => request(binding.base_url, '/ilink/bot/sendmessage', {
|
|
107
149
|
token: binding.token, signal, sending: true,
|
|
108
150
|
body: { msg: {
|
|
@@ -1,9 +1,37 @@
|
|
|
1
1
|
import { describe, expect, it, vi } from 'vitest';
|
|
2
2
|
import { createWeixinAPI, weixinOrigin } from './api.js';
|
|
3
|
+
import { createDecipheriv, createHash } from 'node:crypto';
|
|
3
4
|
|
|
4
5
|
const binding = { base_url: 'https://ilinkai.weixin.qq.com', token: 'test-token', peer_id: 'owner', cursor: 'cursor', context_token: 'context' };
|
|
5
6
|
|
|
6
7
|
describe('Weixin wire transport', () => {
|
|
8
|
+
it('encrypts/uploads the image without bot credentials on CDN, then sends a native image with stable ID', async () => {
|
|
9
|
+
const buffer = Buffer.from('image bytes');
|
|
10
|
+
const fetchImpl = vi.fn(async (url) => String(url).includes('getuploadurl') ? Response.json({ ret: 0, upload_param: 'upload-capability' })
|
|
11
|
+
: String(url).includes('/c2c/upload') ? new Response(null, { headers: { 'x-encrypted-param': 'download-capability' } }) : Response.json({ ret: 0 }));
|
|
12
|
+
await createWeixinAPI({ fetchImpl }).sendImage(binding, { id: 'image-stable', image: { buffer } });
|
|
13
|
+
const uploadRequest = JSON.parse(fetchImpl.mock.calls[0][1].body);
|
|
14
|
+
expect(uploadRequest).toMatchObject({ media_type: 1, to_user_id: 'owner', rawsize: buffer.length, rawfilemd5: createHash('md5').update(buffer).digest('hex'), no_need_thumb: true });
|
|
15
|
+
const [cdnURL, cdn] = fetchImpl.mock.calls[1];
|
|
16
|
+
expect(new URL(cdnURL).searchParams.get('encrypted_query_param')).toBe('upload-capability');
|
|
17
|
+
expect(cdn.headers.Authorization).toBeUndefined();
|
|
18
|
+
expect(cdn.redirect).toBe('error');
|
|
19
|
+
const decrypt = createDecipheriv('aes-128-ecb', Buffer.from(uploadRequest.aeskey, 'hex'), null);
|
|
20
|
+
expect(Buffer.concat([decrypt.update(cdn.body), decrypt.final()])).toEqual(buffer);
|
|
21
|
+
expect(JSON.parse(fetchImpl.mock.calls[2][1].body).msg).toMatchObject({ client_id: 'image-stable', to_user_id: 'owner', context_token: 'context',
|
|
22
|
+
item_list: [{ type: 2, image_item: { media: { encrypt_query_param: 'download-capability', aes_key: Buffer.from(uploadRequest.aeskey).toString('base64'), encrypt_type: 1 }, mid_size: cdn.body.length } }] });
|
|
23
|
+
});
|
|
24
|
+
|
|
25
|
+
it('never sends an image after a rejected upload, unsafe CDN or stale generation', async () => {
|
|
26
|
+
for (const mode of ['unsafe', 'missing-header', 'stale']) {
|
|
27
|
+
const fetchImpl = vi.fn(async (url) => String(url).includes('getuploadurl')
|
|
28
|
+
? Response.json(mode === 'unsafe' ? { upload_full_url: 'https://127.0.0.1/c2c/upload' } : { upload_param: 'opaque' })
|
|
29
|
+
: new Response(null, { headers: mode === 'stale' ? { 'x-encrypted-param': 'download' } : {} }));
|
|
30
|
+
await expect(createWeixinAPI({ fetchImpl }).sendImage(binding, { id: 'id', image: { buffer: Buffer.from('image') },
|
|
31
|
+
beforeSend: () => { throw new Error('cancelled'); } })).rejects.toThrow();
|
|
32
|
+
expect(fetchImpl.mock.calls.some(([url]) => String(url).endsWith('sendmessage'))).toBe(false);
|
|
33
|
+
}
|
|
34
|
+
});
|
|
7
35
|
it('uses QR POST, app headers and private local-token hints without bot authorization', async () => {
|
|
8
36
|
const fetchImpl = vi.fn(async () => Response.json({ qrcode: 'opaque', qrcode_img_content: 'https://example.com/qr' }));
|
|
9
37
|
await createWeixinAPI({ fetchImpl }).getQRCode(undefined, ['existing']);
|
|
@@ -75,11 +75,17 @@ export function createWeixinChatAdapter({ api, getBinding, clock = Date.now }) {
|
|
|
75
75
|
return message;
|
|
76
76
|
},
|
|
77
77
|
renderFormatted: (content) => stringifyMarkdown(content),
|
|
78
|
-
postMessage: async (threadID, message, { id = `yuri_${randomUUID()}`, signal } = {}) => {
|
|
78
|
+
postMessage: async (threadID, message, { id = `yuri_${randomUUID()}`, signal, beforeSend } = {}) => {
|
|
79
79
|
const current = binding();
|
|
80
80
|
const target = decodeThreadId(threadID);
|
|
81
81
|
if (target.accountID !== current.account_id || target.peerID !== current.peer_id) throw new WeixinError('validation_error');
|
|
82
|
-
if (message?.files?.length
|
|
82
|
+
if (message?.files?.length) {
|
|
83
|
+
if (message.files.length !== 1 || !message.files[0]?.mimeType?.startsWith('image/') || !Buffer.isBuffer(message.files[0].data)) return unsupported();
|
|
84
|
+
const file = message.files[0];
|
|
85
|
+
await api.sendImage(current, { id, image: { buffer: file.data, mime: file.mimeType, filename: file.filename }, beforeSend }, signal);
|
|
86
|
+
return { id, raw: { id } };
|
|
87
|
+
}
|
|
88
|
+
if (message?.attachments?.length) return unsupported();
|
|
83
89
|
const text = typeof message === 'string' ? message : typeof message?.raw === 'string' ? message.raw
|
|
84
90
|
: typeof message?.markdown === 'string' ? message.markdown : message?.ast ? stringifyMarkdown(message.ast) : null;
|
|
85
91
|
if (text === null) return unsupported();
|
|
@@ -4,7 +4,7 @@ import { CONTACT_ATTACHMENT_TURN_BUDGET_BYTES } from '../contact-attachments.js'
|
|
|
4
4
|
|
|
5
5
|
const kinds = { 1: 'text', 2: 'image', 3: 'voice', 4: 'file', 5: 'video' };
|
|
6
6
|
const privateField = /token|ticket|aes|encrypt|authorization|cookie|password|secret|credential|signature|^sig$|(?:^|_)auth(?:_|$)|(?:^|_)key$|full_url|^media$|^thumb_media$|^base_info$|^__proto__$|^constructor$|^prototype$/i;
|
|
7
|
-
const envelope = new Set(['item_list', 'message_id', 'from_user_id', 'to_user_id', 'message_type', 'message_state', 'seq', 'session_id', 'client_id', 'create_time_ms', 'update_time_ms', 'delete_time_ms', 'group_id', 'run_id']);
|
|
7
|
+
const envelope = new Set(['item_list', 'message_id', 'msg_id', 'from_user_id', 'to_user_id', 'message_type', 'message_state', 'seq', 'session_id', 'client_id', 'create_time_ms', 'update_time_ms', 'delete_time_ms', 'group_id', 'run_id', 'root_id', 'parent_id', 'is_completed', 'at_bot_username_list']);
|
|
8
8
|
|
|
9
9
|
function contentProjection() {
|
|
10
10
|
let remaining = 24_000;
|
|
@@ -64,14 +64,16 @@ export function normalizeWeixinInput(message) {
|
|
|
64
64
|
const body = item[`${kind}_item`];
|
|
65
65
|
if (kind === 'text' && typeof body?.text === 'string' && !quoted) texts.push(body.text);
|
|
66
66
|
const index = items.length;
|
|
67
|
-
const details = Object.fromEntries(Object.entries(item).filter(([key]) => key !== 'ref_msg' &&
|
|
67
|
+
const details = Object.fromEntries(Object.entries(item).filter(([key, value]) => key !== 'ref_msg' && !envelope.has(key)
|
|
68
|
+
&& !(key === 'button_item_list' && Array.isArray(value) && value.length === 0)
|
|
69
|
+
&& !(kind === 'text' && key === 'text_item')));
|
|
68
70
|
if (kind === 'text' && body && typeof body === 'object') {
|
|
69
71
|
const extraTextFields = Object.fromEntries(Object.entries(body).filter(([key]) => key !== 'text'));
|
|
70
72
|
if (Object.keys(extraTextFields).length) details.text_item = extraTextFields;
|
|
71
73
|
}
|
|
72
74
|
const content = projection.visit(quoted ? { ...details, text_item: item.text_item } : details);
|
|
73
75
|
const entry = { ...content, kind, ...(quoted ? { quoted: true } : {}) };
|
|
74
|
-
if (kind !== 'text' || quoted || Object.keys(
|
|
76
|
+
if (kind !== 'text' || quoted || Object.keys(content || {}).some((key) => key !== 'type')) items.push(entry);
|
|
75
77
|
if (['image', 'voice', 'file', 'video'].includes(kind)) {
|
|
76
78
|
entry.mediaStatus = 'unavailable';
|
|
77
79
|
if (kind === 'voice') entry.transcription = typeof entry.voice_item?.text === 'string' && entry.voice_item.text.trim() ? 'provided' : 'unavailable';
|
|
@@ -12,6 +12,16 @@ const prepare = async (message, overrides = {}) => {
|
|
|
12
12
|
};
|
|
13
13
|
|
|
14
14
|
describe('WeChat rich input projection', () => {
|
|
15
|
+
it('keeps a real plain-text envelope as one text part without transport-only metadata', async () => {
|
|
16
|
+
const message = { message_id: 'message-id', root_id: 0, parent_id: 0,
|
|
17
|
+
item_list: [{ type: 1, create_time_ms: 123, update_time_ms: 123, is_completed: true,
|
|
18
|
+
msg_id: 'item-id', button_item_list: [], at_bot_username_list: [],
|
|
19
|
+
text_item: { text: 'https://mp.weixin.qq.com/s/example' } }] };
|
|
20
|
+
const result = await prepare(message);
|
|
21
|
+
expect(result.receipt.payload).toBe('');
|
|
22
|
+
expect(result.parts).toEqual([{ type: 'text', text: 'https://mp.weixin.qq.com/s/example' }]);
|
|
23
|
+
});
|
|
24
|
+
|
|
15
25
|
it('does not turn ordinary text item protocol IDs into a TOON message', async () => {
|
|
16
26
|
const message = { message_id: 'message-id', from_user_id: 'owner', create_time_ms: 123,
|
|
17
27
|
item_list: [{ type: 1, msg_id: 'item-id', create_time_ms: 123, text_item: { text: 'halo' } }] };
|
|
@@ -28,6 +38,16 @@ describe('WeChat rich input projection', () => {
|
|
|
28
38
|
expect(result.api.downloadMedia).not.toHaveBeenCalled();
|
|
29
39
|
});
|
|
30
40
|
|
|
41
|
+
it('omits private-only text fields but retains actual button and article content', async () => {
|
|
42
|
+
const plain = await prepare({ item_list: [{ type: 1, text_item: { text: 'hello' }, private_token: 'not-content' }] });
|
|
43
|
+
expect(plain.parts).toEqual([{ type: 'text', text: 'hello' }]);
|
|
44
|
+
const rich = await prepare({ root_id: 0, parent_id: 0, article: { title: 'Article', url: 'https://mp.weixin.qq.com/s/example' },
|
|
45
|
+
item_list: [{ type: 1, text_item: { text: 'hello' }, button_item_list: [{ title: 'Open article' }] }] });
|
|
46
|
+
expect(rich.parts.at(-1).text).toContain('Open article');
|
|
47
|
+
expect(rich.parts.at(-1).text).toContain('Article');
|
|
48
|
+
expect(rich.parts.at(-1).text).not.toMatch(/root_id|parent_id/);
|
|
49
|
+
});
|
|
50
|
+
|
|
31
51
|
it('keeps every mixed item, inline quote and article extension as data while stripping transport secrets', async () => {
|
|
32
52
|
const { parts } = await prepare({ context_token: 'private-context', bot_token: 'private-token', item_list: [
|
|
33
53
|
{ type: 1, text_item: { text: '看看这篇' }, ref_msg: { title: '原消息', svr_id: 'quoted-id', message_item: { type: 1, text_item: { text: '引用文字' } } } },
|
|
@@ -6,14 +6,9 @@ import { createWeixinTyping } from './typing.js';
|
|
|
6
6
|
import { prepareWeixinInput } from './inbound.js';
|
|
7
7
|
import { createWeixinChatAdapter } from './chat-adapter.js';
|
|
8
8
|
import { isMessageChannelTurn } from '../message-channel-origin.js';
|
|
9
|
+
import { prepareChannelOutput, readChannelDeliveryImage, channelImageFailure } from '../channel-output.js';
|
|
9
10
|
|
|
10
11
|
const digest = (value) => createHash('sha256').update(value).digest('hex');
|
|
11
|
-
const chunks = (text) => {
|
|
12
|
-
const chars = Array.from(text);
|
|
13
|
-
const result = [];
|
|
14
|
-
for (let index = 0; index < chars.length; index += 3500) result.push(chars.slice(index, index + 3500).join(''));
|
|
15
|
-
return result;
|
|
16
|
-
};
|
|
17
12
|
const feedback = (language, kind) => {
|
|
18
13
|
const messages = language.startsWith('zh') ? {
|
|
19
14
|
interrupted: 'Yuri 主机已重启,上一条请求可能未完成。请先检查任务状态,再决定是否重试。',
|
|
@@ -176,15 +171,21 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
|
|
|
176
171
|
throw error;
|
|
177
172
|
}
|
|
178
173
|
if (binding.status === 'expired') return;
|
|
179
|
-
const deliveries =
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
174
|
+
const deliveries = [];
|
|
175
|
+
const receiverSignal = receivers.get(binding.assistant_id)?.controller.signal;
|
|
176
|
+
const signal = receiverSignal ? AbortSignal.any([lifetime.signal, receiverSignal]) : lifetime.signal;
|
|
177
|
+
const assertCurrent = () => {
|
|
178
|
+
if (!isCurrent(binding) || service.channelPage(binding.assistant_id, { tipOnly: true }).generation !== page.generation) throw new WeixinError('cancelled');
|
|
179
|
+
};
|
|
180
|
+
for (const message of page.messages) {
|
|
181
|
+
if (isMessageChannelTurn(message.turnID) && !store.hasReceipt(message.turnID, binding.epoch)) continue;
|
|
182
|
+
const output = await prepareChannelOutput(message, { service, assistantID: binding.assistant_id,
|
|
183
|
+
generation: page.generation, language: binding.language, failureText: feedback(binding.language, 'failed'), signal, assertCurrent });
|
|
184
|
+
deliveries.push(...output.map((part, index) => ({
|
|
185
|
+
id: `yuri_${digest(`${binding.epoch}:${page.generation}:${message.messageID}:${index}`)}`, ...part,
|
|
186
|
+
})));
|
|
187
|
+
}
|
|
188
|
+
assertCurrent();
|
|
188
189
|
store.collect(binding, page, deliveries);
|
|
189
190
|
if (!inboundWork.has(binding.assistant_id)) {
|
|
190
191
|
const work = track(processIncoming(binding, page.generation)).catch((error) => setError(binding, error));
|
|
@@ -202,11 +203,16 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
|
|
|
202
203
|
const receiverSignal = receivers.get(binding.assistant_id)?.controller.signal;
|
|
203
204
|
const adapter = createWeixinChatAdapter({ api, clock, getBinding: () => isCurrent(binding) ? store.get(binding.assistant_id) : null });
|
|
204
205
|
const threadID = await adapter.openDM(current.peer_id);
|
|
205
|
-
|
|
206
|
-
|
|
206
|
+
const signal = receiverSignal ? AbortSignal.any([lifetime.signal, receiverSignal]) : lifetime.signal;
|
|
207
|
+
const image = await readChannelDeliveryImage(service, binding.assistant_id, delivery.image ? JSON.parse(delivery.image) : null, signal);
|
|
208
|
+
assertCurrent();
|
|
209
|
+
signal.throwIfAborted();
|
|
210
|
+
await adapter.postMessage(threadID, image ? { raw: '', files: [{ data: image.buffer, mimeType: image.mime, filename: image.filename }] } : delivery.text,
|
|
211
|
+
{ id: delivery.id, signal, beforeSend: assertCurrent });
|
|
207
212
|
if (!isCurrent(binding) && !(retiring.has(binding.assistant_id) && canControl(binding))) return;
|
|
208
213
|
store.sent(delivery.id);
|
|
209
|
-
store.patch(binding.epoch, { error:
|
|
214
|
+
store.patch(binding.epoch, { error: store.hasUnknown(binding.epoch) ? 'delivery_unknown'
|
|
215
|
+
: store.hasBlocked(binding.epoch) ? 'reply_unavailable' : null, updated_at: clock() });
|
|
210
216
|
} catch (error) {
|
|
211
217
|
if (!isCurrent(binding)) {
|
|
212
218
|
if (retiring.has(binding.assistant_id) && canControl(binding)) {
|
|
@@ -220,6 +226,9 @@ export function createWeixinRuntime({ directory, service, refreshAllowedRoots =
|
|
|
220
226
|
}
|
|
221
227
|
// Network ambiguity is user-retryable, not an automatic duplicate reply.
|
|
222
228
|
store.markDelivery(delivery.id, error?.ambiguous ? 'unknown' : 'blocked');
|
|
229
|
+
if (delivery.image && !error?.ambiguous) {
|
|
230
|
+
store.enqueue(binding.epoch, `${delivery.id}:image-failed`, channelImageFailure(binding.language));
|
|
231
|
+
}
|
|
223
232
|
setError(binding, error?.ambiguous ? new WeixinError('delivery_unknown') : error);
|
|
224
233
|
}
|
|
225
234
|
};
|
|
@@ -58,6 +58,25 @@ function fixture({ directory = root(), configureAPI, service: externalService, c
|
|
|
58
58
|
}
|
|
59
59
|
|
|
60
60
|
describe('Weixin Host runtime', () => {
|
|
61
|
+
it('delivers a generated image natively, ordered with prose, only on its source channel', async () => {
|
|
62
|
+
const f = fixture();
|
|
63
|
+
f.api.sendImage = vi.fn(async () => ({ ret: 0 }));
|
|
64
|
+
f.service.prepareChannelImage = vi.fn(async () => ({ attachmentID: 'att_generated' }));
|
|
65
|
+
f.service.getAssistantContactAttachment = vi.fn(async () => ({ buffer: Buffer.from('image'), mime: 'image/png', filename: 'generated.png' }));
|
|
66
|
+
f.updates.push([inbound('draw')]);
|
|
67
|
+
await f.bind();
|
|
68
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledOnce());
|
|
69
|
+
const turnID = f.service.send.mock.calls[0][1].messageID;
|
|
70
|
+
f.pages.set('bot', { generation: 0, messages: [
|
|
71
|
+
{ ordinal: 1, messageID: 'foreign', turnID: 'channel:wecom:foreign', text: '', 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
|
+
});
|
|
61
80
|
it('does not broadcast other channel replies to WeChat but pushes source-less messages', async () => {
|
|
62
81
|
const f = fixture();
|
|
63
82
|
f.updates.push([inbound('own-turn')]);
|
|
@@ -189,6 +208,23 @@ describe('Weixin Host runtime', () => {
|
|
|
189
208
|
expect(f.api.sendText.mock.calls[1][1].id).toBe(originalId);
|
|
190
209
|
});
|
|
191
210
|
|
|
211
|
+
it.each([false, true])('a rejected or uncertain notification send does not block later text or Bot input (ambiguous=%s)', async (ambiguous) => {
|
|
212
|
+
const f = fixture({ configureAPI: (api) => api.sendText.mockRejectedValueOnce(new WeixinError('reply_unavailable', { ambiguous })) });
|
|
213
|
+
f.updates.push([inbound()]);
|
|
214
|
+
await f.bind();
|
|
215
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledOnce());
|
|
216
|
+
f.pages.set('bot', { generation: 0, messages: [
|
|
217
|
+
{ ordinal: 1, messageID: 'notification', text: 'Article notes', cards: [], status: 'complete' },
|
|
218
|
+
{ ordinal: 2, messageID: 'result', text: 'Note saved', cards: [], status: 'complete' },
|
|
219
|
+
] });
|
|
220
|
+
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(2));
|
|
221
|
+
expect(f.api.sendText.mock.calls.map(([, delivery]) => delivery.text)).toEqual(['Article notes', 'Note saved']);
|
|
222
|
+
expect(f.runtime.status('bot').error).toBe(ambiguous ? 'delivery_unknown' : 'reply_unavailable');
|
|
223
|
+
f.updates.push([inbound('next')]);
|
|
224
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(2));
|
|
225
|
+
expect(f.api.sendText.mock.calls.filter(([, delivery]) => delivery.text === 'Note saved')).toHaveLength(1);
|
|
226
|
+
});
|
|
227
|
+
|
|
192
228
|
it('shutdown cancels a hanging platform read before closing storage', async () => {
|
|
193
229
|
const f = fixture({ configureAPI: (api) => api.getUpdates.mockImplementation((_binding, signal) => abortable(signal)) });
|
|
194
230
|
await f.bind();
|
|
@@ -37,6 +37,9 @@ export function createWeixinStore(directory) {
|
|
|
37
37
|
if (!db.prepare('PRAGMA table_info(inbox)').all().some((column) => column.name === 'payload')) {
|
|
38
38
|
db.exec("ALTER TABLE inbox ADD COLUMN payload TEXT NOT NULL DEFAULT ''");
|
|
39
39
|
}
|
|
40
|
+
if (!db.prepare('PRAGMA table_info(outbox)').all().some((column) => column.name === 'image')) {
|
|
41
|
+
db.exec("ALTER TABLE outbox ADD COLUMN image TEXT NOT NULL DEFAULT ''");
|
|
42
|
+
}
|
|
40
43
|
const get = (assistantID) => db.prepare('SELECT * FROM binding WHERE assistant_id=?').get(assistantID) ?? null;
|
|
41
44
|
const patch = (epoch, values) => {
|
|
42
45
|
const allowed = new Set(['cursor', 'context_token', 'generation', 'ordinal', 'status', 'error', 'updated_at']);
|
|
@@ -44,7 +47,7 @@ export function createWeixinStore(directory) {
|
|
|
44
47
|
if (!keys.length) return;
|
|
45
48
|
db.prepare(`UPDATE binding SET ${keys.map((key) => `${key}=?`).join(',')} WHERE epoch=?`).run(...keys.map((key) => values[key]), epoch);
|
|
46
49
|
};
|
|
47
|
-
const enqueue = (epoch, id, text) => db.prepare('INSERT OR IGNORE INTO outbox(id,epoch,text) VALUES (
|
|
50
|
+
const enqueue = (epoch, id, text, image = '') => db.prepare('INSERT OR IGNORE INTO outbox(id,epoch,text,image) VALUES (?,?,?,?)').run(id, epoch, text, image);
|
|
48
51
|
const unlink = db.transaction((assistantID) => {
|
|
49
52
|
const binding = get(assistantID);
|
|
50
53
|
if (!binding) return;
|
|
@@ -101,15 +104,16 @@ export function createWeixinStore(directory) {
|
|
|
101
104
|
collect: db.transaction((binding, page, deliveries) => {
|
|
102
105
|
if (get(binding.assistant_id)?.epoch !== binding.epoch) return;
|
|
103
106
|
if (binding.generation !== page.generation) db.prepare('DELETE FROM outbox WHERE epoch=?').run(binding.epoch);
|
|
104
|
-
for (const delivery of deliveries) enqueue(binding.epoch, delivery.id, delivery.text);
|
|
107
|
+
for (const delivery of deliveries) enqueue(binding.epoch, delivery.id, delivery.text, delivery.image ? JSON.stringify(delivery.image) : '');
|
|
105
108
|
patch(binding.epoch, { generation: page.generation, ordinal: page.ordinal });
|
|
106
109
|
}),
|
|
107
|
-
nextDelivery: (epoch) => db.prepare("SELECT * FROM outbox WHERE epoch=? AND state
|
|
110
|
+
nextDelivery: (epoch) => db.prepare("SELECT * FROM outbox WHERE epoch=? AND state='pending' ORDER BY sequence LIMIT 1").get(epoch),
|
|
108
111
|
markDelivery: (id, state) => db.prepare('UPDATE outbox SET state=? WHERE id=?').run(state, id),
|
|
109
|
-
sent: (id) => db.prepare("UPDATE outbox SET state='sent',text='' WHERE id=?").run(id),
|
|
112
|
+
sent: (id) => db.prepare("UPDATE outbox SET state='sent',text='',image='' WHERE id=?").run(id),
|
|
110
113
|
retry: (epoch) => db.prepare("UPDATE outbox SET state='pending' WHERE epoch=? AND state IN ('unknown','blocked')").run(epoch),
|
|
111
114
|
unblock: (epoch) => db.prepare("UPDATE outbox SET state='pending' WHERE epoch=? AND state='blocked'").run(epoch),
|
|
112
115
|
hasUnknown: (epoch) => Boolean(db.prepare("SELECT 1 FROM outbox WHERE epoch=? AND state='unknown' LIMIT 1").get(epoch)),
|
|
116
|
+
hasBlocked: (epoch) => Boolean(db.prepare("SELECT 1 FROM outbox WHERE epoch=? AND state='blocked' LIMIT 1").get(epoch)),
|
|
113
117
|
acquire: (owner, now) => Boolean(db.prepare(`INSERT INTO lease(id,owner,expires_at) VALUES (1,?,?)
|
|
114
118
|
ON CONFLICT(id) DO UPDATE SET owner=excluded.owner,expires_at=excluded.expires_at
|
|
115
119
|
WHERE lease.owner=excluded.owner OR lease.expires_at<=?`).run(owner, now + 60_000, now).changes),
|
|
@@ -17,6 +17,27 @@ const bind = (store, assistant_id = 'bot') => store.bind({ assistant_id, account
|
|
|
17
17
|
base_url: 'https://ilinkai.weixin.qq.com', language: 'zh-CN', generation: 0, ordinal: 0, updated_at: 1 });
|
|
18
18
|
|
|
19
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
|
+
|
|
20
41
|
it('adds the payload column to an existing text-only database without losing cursor, receipts or binding', () => {
|
|
21
42
|
const dir = directory();
|
|
22
43
|
let store = createWeixinStore(dir);
|
|
@@ -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,6 +59,12 @@ Android notification-only subscriptions send the App locale in `Accept-Language`
|
|
|
59
59
|
|
|
60
60
|
### Trigger runtime API (runtime.js)
|
|
61
61
|
|
|
62
|
+
Native Goal completion notifications consume `rpc.opencode.goal.changed` with the
|
|
63
|
+
official Goal schema. Only native `complete` triggers goal-completion push;
|
|
64
|
+
active/paused/cleared or malformed snapshots do not. Ordinary per-turn completion
|
|
65
|
+
suppression reads native Goal RPC, never legacy `yuri.goal` metadata. No Host Goal
|
|
66
|
+
auditor, token budget, objective file or continuation loop remains.
|
|
67
|
+
|
|
62
68
|
Ordinary completion means the whole root-session family has stopped. An assistant `finish: stop`, `session.idle`, or `session.execution.succeeded` is only a candidate. Before fanout, the barrier reads successful process-wide `session.active` membership and resolves active IDs' authoritative parent chains, including nested descendants and idle intermediate parents. It never depends on focused UI, loaded transcripts, or a cached tool's apparent completion. A candidate root remains pending while it or any descendant runs; child terminals recheck the pending root rather than sending a separate child notification. Metadata lookup concurrency is capped at four per check, with per-check parent-read deduplication and the Host's existing identity cache.
|
|
63
69
|
|
|
64
70
|
Failed/malformed activity or unknown/cyclic ancestry defers completion rather than treating it as empty. While candidates exist, a single two-second retry timer recovers failed reads and missed child terminal events; no candidates means no polling. Execution/retry/step starts invalidate in-flight eligibility, and a new root run cancels its older candidate. Parent failures, deletion and user interruption cancel success. Event revisions fence stale reads and notification-template enrichment. Successful handling deduplicates terminal events for that root until a new execution starts, replacing the old five-second cooldown so a legitimate short next task can notify. Pending/dedup state is in-memory for the runtime lifetime; historical completions are not replayed after Host restart. `dispose()` clears completion retries and question/permission timers; VS Code also resets its gate on runtime switches.
|
|
@@ -1,5 +1,9 @@
|
|
|
1
1
|
import { readNotificationSessionRecord } from './template-runtime.js';
|
|
2
2
|
import { completionEvent, createFamilyCompletionGate } from './family-completion-gate.js';
|
|
3
|
+
import { makeOpenCodeV2Client } from '../opencode/v2-client.js';
|
|
4
|
+
import { getNativeSessionGoal } from '../opencode/native-goal.js';
|
|
5
|
+
import { Goal } from '@opencode/schema/goal';
|
|
6
|
+
import { Schema } from 'effect';
|
|
3
7
|
|
|
4
8
|
const trimmedText = (value) => (typeof value === 'string' && value.trim() ? value.trim() : '');
|
|
5
9
|
|
|
@@ -445,22 +449,12 @@ export const createNotificationTriggerRuntime = (deps) => {
|
|
|
445
449
|
return trimmedText(meta?.title);
|
|
446
450
|
};
|
|
447
451
|
|
|
448
|
-
//
|
|
449
|
-
// the session-goal runtime sends its own notification when the goal
|
|
450
|
-
// settles. Fetch failures fall through to normal notification behavior.
|
|
452
|
+
// The native goal remains active until OpenCode's own reviewer settles it.
|
|
451
453
|
const hasActiveSessionGoal = async (sessionId, directory) => {
|
|
452
454
|
if (!sessionId) return false;
|
|
453
455
|
try {
|
|
454
|
-
const
|
|
455
|
-
const
|
|
456
|
-
const response = await fetch(url, {
|
|
457
|
-
method: 'GET',
|
|
458
|
-
headers: { Accept: 'application/json', ...getOpenCodeAuthHeaders() },
|
|
459
|
-
signal: AbortSignal.timeout(2000),
|
|
460
|
-
});
|
|
461
|
-
if (!response.ok) return false;
|
|
462
|
-
const session = readNotificationSessionRecord(await response.json().catch(() => null));
|
|
463
|
-
const goal = session?.metadata?.yuri?.goal;
|
|
456
|
+
const client = makeOpenCodeV2Client({ baseUrl: buildOpenCodeUrl('/', '').replace(/\/$/, ''), authHeaders: getOpenCodeAuthHeaders() });
|
|
457
|
+
const goal = await getNativeSessionGoal(client, sessionId, directory, AbortSignal.timeout(2000));
|
|
464
458
|
return Boolean(goal && typeof goal === 'object' && goal.status === 'active');
|
|
465
459
|
} catch {
|
|
466
460
|
return false;
|
|
@@ -555,7 +549,7 @@ export const createNotificationTriggerRuntime = (deps) => {
|
|
|
555
549
|
|
|
556
550
|
// While a goal drives the session, per-turn "ready" notifications are
|
|
557
551
|
// noise produced by the goal loop itself — the goal's own settle
|
|
558
|
-
// notification
|
|
552
|
+
// notification comes from OpenCode's native Goal changed event instead.
|
|
559
553
|
if (await hasActiveSessionGoal(sessionId, notificationDirectory)) {
|
|
560
554
|
return;
|
|
561
555
|
}
|
|
@@ -883,6 +877,18 @@ export const createNotificationTriggerRuntime = (deps) => {
|
|
|
883
877
|
const nativeFailures = new Map();
|
|
884
878
|
const maybeSendPushForTrigger = async (payload) => {
|
|
885
879
|
maybeCacheSessionMetaFromPayload(payload);
|
|
880
|
+
if (payload.type === 'rpc.opencode.goal.changed') {
|
|
881
|
+
const parsed = Schema.decodeUnknownExit(Goal.Definition.events.changed.schema)(payload.properties ?? payload.data);
|
|
882
|
+
if (parsed._tag === 'Failure' || parsed.value.goal?.status !== 'complete') return;
|
|
883
|
+
const { sessionID, goal } = parsed.value;
|
|
884
|
+
const directory = extractDirectoryFromPayload(payload);
|
|
885
|
+
if (await shouldSkipSystemSessionNotification(sessionID, directory)) return;
|
|
886
|
+
await sendGoalSettlePush({
|
|
887
|
+
sessionId: sessionID, directory, status: 'complete', title: 'Goal complete',
|
|
888
|
+
body: [goal.objective, goal.reason].filter(Boolean).join(' — ').slice(0, 240),
|
|
889
|
+
});
|
|
890
|
+
return;
|
|
891
|
+
}
|
|
886
892
|
const event = completionEvent(payload);
|
|
887
893
|
if (event) {
|
|
888
894
|
if (event.kind === 'running' || payload.type === 'session.deleted') nativeFailures.delete(event.sessionId);
|
|
@@ -920,6 +926,11 @@ export const createNotificationTriggerRuntime = (deps) => {
|
|
|
920
926
|
const sendGoalSettlePush = async ({ sessionId, directory, status, title, body }) => {
|
|
921
927
|
const settings = await readSettingsFromDisk();
|
|
922
928
|
if (settings.notifyOnGoals === false) return;
|
|
929
|
+
if (settings.nativeNotificationsEnabled && (settings.notificationMode === 'always' || !getIsWindowFocused?.())) {
|
|
930
|
+
const notification = { title, body, tag: `goal-${sessionId}`, kind: 'goal', sessionId, directory };
|
|
931
|
+
const desktopNotificationDelivered = emitDesktopNotification(notification);
|
|
932
|
+
broadcastUiNotification(notification, { desktopNotificationDelivered });
|
|
933
|
+
}
|
|
923
934
|
let sessionName = '';
|
|
924
935
|
try {
|
|
925
936
|
const base = buildOpenCodeUrl(`/session/${encodeURIComponent(sessionId)}`, '');
|
|
@@ -936,7 +947,7 @@ export const createNotificationTriggerRuntime = (deps) => {
|
|
|
936
947
|
} catch {
|
|
937
948
|
// Session name is presentation sugar for the mobile push — never block on it.
|
|
938
949
|
}
|
|
939
|
-
const type = status === 'complete' ? 'goal_complete' :
|
|
950
|
+
const type = status === 'complete' ? 'goal_complete' : 'goal_blocked';
|
|
940
951
|
await fanoutPush(
|
|
941
952
|
{
|
|
942
953
|
title,
|
|
@@ -51,6 +51,14 @@ const jsonResponse = (body, status = 200) => new Response(JSON.stringify(body),
|
|
|
51
51
|
headers: { 'Content-Type': 'application/json' },
|
|
52
52
|
});
|
|
53
53
|
|
|
54
|
+
const nativeGoalEvent = (status = 'complete') => ({
|
|
55
|
+
type: 'rpc.opencode.goal.changed', location: { directory: '/repo' },
|
|
56
|
+
data: { sessionID: 'ses_goal', goal: {
|
|
57
|
+
id: 'g1', objective: 'Verify native Goal', status, reason: 'Verified',
|
|
58
|
+
rounds: 1, maxRounds: 50, boot: 'boot', updatedAt: 1,
|
|
59
|
+
} },
|
|
60
|
+
});
|
|
61
|
+
|
|
54
62
|
afterEach(() => {
|
|
55
63
|
runtimes.splice(0).forEach(runtime => runtime.dispose());
|
|
56
64
|
vi.unstubAllGlobals();
|
|
@@ -718,12 +726,7 @@ describe('notification event toggles', () => {
|
|
|
718
726
|
const { runtime, sendPushToAllUiSessions } = createRuntime({
|
|
719
727
|
readSettingsFromDisk: vi.fn(async () => ({ ...defaultSettings, notifyOnGoals: false })),
|
|
720
728
|
});
|
|
721
|
-
await runtime.
|
|
722
|
-
sessionId: 'ses_goal',
|
|
723
|
-
status: 'complete',
|
|
724
|
-
title: 'Goal completed',
|
|
725
|
-
body: 'all done',
|
|
726
|
-
});
|
|
729
|
+
await runtime.maybeSendPushForTrigger(nativeGoalEvent());
|
|
727
730
|
expect(sendPushToAllUiSessions).not.toHaveBeenCalled();
|
|
728
731
|
});
|
|
729
732
|
|
|
@@ -818,15 +821,13 @@ describe('notification event toggles', () => {
|
|
|
818
821
|
);
|
|
819
822
|
});
|
|
820
823
|
|
|
821
|
-
it('
|
|
824
|
+
it('sends goal completion from the native changed event, not from Host metadata', async () => {
|
|
822
825
|
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ id: 'ses_goal', title: 'Goal run' })));
|
|
823
826
|
const { runtime, sendPushToAllUiSessions } = createRuntime();
|
|
824
|
-
await runtime.
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
body: 'all done',
|
|
829
|
-
});
|
|
827
|
+
await runtime.maybeSendPushForTrigger(nativeGoalEvent('active'));
|
|
828
|
+
await runtime.maybeSendPushForTrigger(nativeGoalEvent('paused'));
|
|
829
|
+
expect(sendPushToAllUiSessions).not.toHaveBeenCalled();
|
|
830
|
+
await runtime.maybeSendPushForTrigger(nativeGoalEvent());
|
|
830
831
|
expect(sendPushToAllUiSessions).toHaveBeenCalledTimes(1);
|
|
831
832
|
expect(sendPushToAllUiSessions.mock.calls[0][0]).toMatchObject({ tag: 'goal-ses_goal' });
|
|
832
833
|
expect(sendPushToAllUiSessions.mock.calls[0][0].data).toMatchObject({ sessionName: 'Goal run' });
|
|
@@ -10,6 +10,10 @@ diagnostics use provider/location/session-active V2 routes and location query
|
|
|
10
10
|
encoding, not removed V1 endpoints.
|
|
11
11
|
|
|
12
12
|
## Entrypoints and structure
|
|
13
|
+
- `native-goal.js`: official `@opencode/schema/goal` RPC read adapter shared by
|
|
14
|
+
scheduled tasks, Assistant reconciliation and notification suppression. It
|
|
15
|
+
validates native state and distinguishes an absent plugin from transport/auth
|
|
16
|
+
failure. It owns no Goal persistence, auditing, objective files or continuation.
|
|
13
17
|
- Pairing transport discovery includes the serving host's `serverName` (OS
|
|
14
18
|
hostname), not the browser's machine name. The pairing form uses it as an
|
|
15
19
|
editable default and preserves edits made while discovery is pending. The
|
|
@@ -90,6 +94,11 @@ encoding, not removed V1 endpoints.
|
|
|
90
94
|
- `packages/web/server/lib/ui-auth/ui-passkeys.js`: UI passkey storage and WebAuthn registration/authentication helpers (outside OpenCode module).
|
|
91
95
|
|
|
92
96
|
## Public exports (auth.js)
|
|
97
|
+
Shared credential and location-release declarations require only the SDK resources
|
|
98
|
+
they consume (`credential`, `config.get`, and `debug.location.evict`), not the entire
|
|
99
|
+
generated client. VS Code and Web may resolve compatible client patch versions;
|
|
100
|
+
unrelated new SDK resources must not invalidate these host integration seams.
|
|
101
|
+
|
|
93
102
|
- `configureOpenCodeCredentials(resolveClient)`: host composition injects a call-time SDK client resolver; `null` detaches it. Web/Electron share server wiring; VS Code wires its manager in extension activation. Mobile clients use their host.
|
|
94
103
|
- `currentClient()`: trusted host-only client resolver used by config-sync to retain full V2 credential account records instead of the active-account quota projection.
|
|
95
104
|
- `openCodeCredentialSource({ buildOpenCodeUrl, getOpenCodeAuthHeaders })`: resolves the current endpoint/auth at each read rather than capturing a previous runtime.
|
|
@@ -1,10 +1,14 @@
|
|
|
1
1
|
import type { OpenCodeClient } from '@opencode/client';
|
|
2
2
|
|
|
3
|
+
type CredentialClient = Pick<OpenCodeClient, 'credential'> & {
|
|
4
|
+
config: Pick<OpenCodeClient['config'], 'get'>;
|
|
5
|
+
};
|
|
6
|
+
|
|
3
7
|
export type ProviderCredential =
|
|
4
8
|
| { type: 'api'; key: string }
|
|
5
9
|
| { type: 'oauth'; access: string; refresh: string; expires: number; accountId?: string; enterpriseUrl?: string };
|
|
6
|
-
export function configureOpenCodeCredentials(resolveClient: (() =>
|
|
7
|
-
export function currentClient():
|
|
10
|
+
export function configureOpenCodeCredentials(resolveClient: (() => CredentialClient) | null): void;
|
|
11
|
+
export function currentClient(): CredentialClient;
|
|
8
12
|
export function openCodeCredentialSource(deps: {
|
|
9
13
|
buildOpenCodeUrl: (path: string, prefix?: string) => string;
|
|
10
14
|
getOpenCodeAuthHeaders: () => Record<string, string>;
|
|
@@ -1228,7 +1228,6 @@ export const registerCommonRequestMiddleware = (app, dependencies) => {
|
|
|
1228
1228
|
req.path.startsWith('/api/question') ||
|
|
1229
1229
|
req.path.startsWith('/api/session-folders') ||
|
|
1230
1230
|
req.path.startsWith('/api/small-model') ||
|
|
1231
|
-
req.path.startsWith('/api/goals') ||
|
|
1232
1231
|
req.path.startsWith('/api/text') ||
|
|
1233
1232
|
req.path.startsWith('/api/voice') ||
|
|
1234
1233
|
req.path.startsWith('/api/tts')
|