@yuriai/web 0.2.27-beta.3 → 0.2.27-beta.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -0
- package/dist/assets/{AgentAvatar-kIN4sZMz.js → AgentAvatar-BJ42lGZD.js} +1 -1
- package/dist/assets/AssistantContactStatus-dtkObamV.js +3 -0
- package/dist/assets/AssistantUnreadBadge-QwhBfXpC.js +1 -0
- package/dist/assets/AssistantView-D7ryIKL0.js +1 -0
- package/dist/assets/{DiagramView-DK0iXm9b.js → DiagramView-ERrGEBDp.js} +1 -1
- package/dist/assets/{FadeInOnReveal-BJA9Za3T.js → FadeInOnReveal-Bu2GvaM9.js} +1 -1
- package/dist/assets/GuiPluginSurface-MzQgEZNr.js +1 -0
- package/dist/assets/{GuiPluginWindow-l4FYY6S-.js → GuiPluginWindow-DZMmlQzx.js} +1 -1
- package/dist/assets/Icon-Dj4CCqCP.js +1 -0
- package/dist/assets/{ImageLoadingPlaceholder-DCWssLJG.js → ImageLoadingPlaceholder-BnFXgUuO.js} +1 -1
- package/dist/assets/{LoadingImage-C_Hryaqe.js → LoadingImage-PBnivDKv.js} +1 -1
- package/dist/assets/{MarkdownRenderer-Y6uQXIFH.js → MarkdownRenderer-BajF4gUU.js} +2 -2
- package/dist/assets/{MarkdownRendererImpl-qKp1tQrP.js → MarkdownRendererImpl-CfyXL4rg.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-B_JTod0h.js → MarkstreamRendererImpl-BGadklK1.js} +1 -1
- package/dist/assets/MobileDetailNavigation-DqajQdB4.js +1 -0
- package/dist/assets/{MobileResizableSheet-F1zSUD1S.js → MobileResizableSheet-BvdUgwA3.js} +1 -1
- package/dist/assets/{MobileShareBridge-F70fkIfS.js → MobileShareBridge-3oPoYnry.js} +2 -2
- package/dist/assets/MobileTabPageHeader-B6cRyIRH.js +2 -0
- package/dist/assets/{MultiRunWindow-D8m6R_4x.js → MultiRunWindow-yhs0Ih5_.js} +1 -1
- package/dist/assets/{OnboardingScreen-BAsPVV_W.js → OnboardingScreen-Bi1VWFQC.js} +1 -1
- package/dist/assets/{OverlayScrollbar-wiRM4AGj.js → OverlayScrollbar-BBDwGvGO.js} +1 -1
- package/dist/assets/{SettingsView-izzjIckv.js → SettingsView-BSf-SJUA.js} +15 -15
- package/dist/assets/{SettingsWindow-CSuHDq_c.js → SettingsWindow-BvSXVMTm.js} +1 -1
- package/dist/assets/TerminalView-DhL01N7e.js +8 -0
- package/dist/assets/{ToolOutputDialog-DJs9w1_J.js → ToolOutputDialog-C8lnH4Ky.js} +1 -1
- package/dist/assets/{YuriLogo-aBS6wlYU.js → YuriLogo-D8asj1CS.js} +1 -1
- package/dist/assets/{appThemeRegistry-BY5rY9-W.js → appThemeRegistry-C-maYSdv.js} +1 -1
- package/dist/assets/{assistant-attachment-cache-B9iHLlm2.js → assistant-attachment-cache-B_qRvy-k.js} +1 -1
- package/dist/assets/{button-Dt6Ygbc7.js → button-vXOdzd8x.js} +1 -1
- package/dist/assets/{capgoAdapter-MQ1qpf60.js → capgoAdapter-DJ_h2x5D.js} +1 -1
- package/dist/assets/{collapsible-Dm7OHk7m.js → collapsible-DwDQs3Wa.js} +1 -1
- package/dist/assets/context-menu-BabBujQ-.js +1 -0
- package/dist/assets/{desktopRelayRestore-CoLLVJw8.js → desktopRelayRestore-D1UX7HW2.js} +1 -1
- package/dist/assets/{diagram-DWZaG3_v.js → diagram-HwgrQxY5.js} +1 -1
- package/dist/assets/{dialog-CjQeHVOc.js → dialog-Dnf626tb.js} +1 -1
- package/dist/assets/dropdown-menu.styles-CBc_a-Nv.js +1 -0
- package/dist/assets/es-BQkO-Odr.js +15 -0
- package/dist/assets/feishu-Ct1ZxlzQ.svg +6 -0
- package/dist/assets/{fileMentionTouchSelection-D7QtVxjI.js → fileMentionTouchSelection-CKPnEetl.js} +1 -1
- package/dist/assets/{fileQueries-5a1jkme2.js → fileQueries-BeXkd3o6.js} +1 -1
- package/dist/assets/{fileReferenceActions-BAoEu4z8.js → fileReferenceActions-g7KZLi_G.js} +1 -1
- package/dist/assets/fr-C852roK5.js +13 -0
- package/dist/assets/gitApi-CVq5oKCd.js +370 -0
- package/dist/assets/gitApiHttp-BYOIbYIh.js +7 -0
- package/dist/assets/{gui-9enrif_1.js → gui-M_Rbwkyu.js} +1 -1
- package/dist/assets/host-BW3FEJdU.js +1 -0
- package/dist/assets/{image-loading-Dq1g_wpm.js → image-loading-D5UhMj7Z.js} +1 -1
- package/dist/assets/{input-Dq4usRDa.js → input-BtM712b1.js} +1 -1
- package/dist/assets/insertionBoundaries-Dx3WAY6i.js +1 -0
- package/dist/assets/ja-BqC39qK6.js +15 -0
- package/dist/assets/ko-BMaChAWh.js +15 -0
- package/dist/assets/main-9uP2z1qT.js +2 -0
- package/dist/assets/main-Mey7bCWf.js +169 -0
- package/dist/assets/{markdownHeightCache-C1u0bWDL.js → markdownHeightCache-Bf8iisO4.js} +1 -1
- package/dist/assets/{mcpQueries-D2IxTr4k.js → mcpQueries-DpXqegX5.js} +1 -1
- package/dist/assets/miniChat-DqZvVkme.js +2 -0
- package/dist/assets/mobile-DXAWjYcN.js +2 -0
- package/dist/assets/{mobileBackNavigation-vpCg1S7j.js → mobileBackNavigation-DZcI7aZg.js} +1 -1
- package/dist/assets/{multirun-DT-dFXud.js → multirun-hzspPepd.js} +1 -1
- package/dist/assets/{native-De1DIkLZ.js → native-H7K64Ulc.js} +1 -1
- package/dist/assets/{native-config-ncdoz9Wl.js → native-config-CddZtLQ1.js} +1 -1
- package/dist/assets/{persistence-JyLTFv27.js → persistence-BT8045Ue.js} +1 -1
- package/dist/assets/pl-Ubs8p28T.js +15 -0
- package/dist/assets/projectMeta-CEf0QPmD.js +1 -0
- package/dist/assets/pt-BR-8rAOjJrs.js +15 -0
- package/dist/assets/{queryRuntime-Dkpnq3Z1.js → queryRuntime-CTcigFdj.js} +1 -1
- package/dist/assets/react-DRe85o5s.js +1 -0
- package/dist/assets/readiness-Dyr7314z.js +1 -0
- package/dist/assets/renderElectronMiniChatApp-DoOq8Cuo.js +2 -0
- package/dist/assets/renderMobileApp-TTxtOb8b.js +28 -0
- package/dist/assets/runtime-fetch-D0YWp3FJ.js +1 -0
- package/dist/assets/{runtime-file-download-CcNIVp7u.js → runtime-file-download-Cf1WxfeW.js} +1 -1
- package/dist/assets/{runtime-file-resource-6np6lzoV.js → runtime-file-resource-UJjHUF2C.js} +1 -1
- package/dist/assets/runtimeConfig-B8VHHNxj.js +2 -0
- package/dist/assets/runtimeEndpointReset-BC6XWntz.js +149 -0
- package/dist/assets/scheduledTaskNavigation-Zm87Nydi.js +1 -0
- package/dist/assets/sessionLookup-De53jDwM.js +1 -0
- package/dist/assets/sortable-tabs-strip-D4pVoodN.js +1 -0
- package/dist/assets/speechSettingsQueries-RlCLMBtr.js +4 -0
- package/dist/assets/src-lE4uqaHS.css +2 -0
- package/dist/assets/store-ME7oHni1.js +15 -0
- package/dist/assets/{terminalApi-B5o8UqWA.js → terminalApi-BSaclMDJ.js} +1 -1
- package/dist/assets/{textarea-vtIQM2iP.js → textarea-B98rsLs7.js} +1 -1
- package/dist/assets/{tooltip-BpG2mxrT.js → tooltip-B9810jbK.js} +1 -1
- package/dist/assets/{types-CNTgeeM1.js → types-DFf9vd1b.js} +1 -1
- package/dist/assets/{uk-B_JwElWz.js → uk-LzwzUApL.js} +4 -4
- package/dist/assets/{useAppFontEffects-BguV1Hfa.js → useAppFontEffects-D2C1sBYM.js} +59 -57
- package/dist/assets/{useAssistantUIStore-C9FPlYQz.js → useAssistantUIStore-TUN_ycy5.js} +1 -1
- package/dist/assets/useDesktopWindowControlsLayout-BjKaHN0x.js +1 -0
- package/dist/assets/{useEffectiveDirectory-Ci6Z13kj.js → useEffectiveDirectory-TEvyiQSC.js} +1 -1
- package/dist/assets/{useFontPreferences-DMiP_Yy-.js → useFontPreferences-BlhlCJCX.js} +1 -1
- package/dist/assets/useMobileNavigationStore-DTvJV9s-.js +23 -0
- package/dist/assets/useUIStore-DRx6OgCp.js +1 -0
- package/dist/assets/{useWorkerHighlightedLines-HKhuYGSj.js → useWorkerHighlightedLines-D093jNsH.js} +1 -1
- package/dist/assets/{vendor-codemirror-search-ZqtrPLjU.js → vendor-codemirror-search-DiPwvA-6.js} +2 -2
- package/dist/assets/vendor-opencode-client-ZeOZ4Efz.js +23 -0
- package/dist/assets/{vendor-opencode-plugin-Bw7Q6Nv9.js → vendor-opencode-plugin-BBOP6WNx.js} +1 -1
- package/dist/assets/{vendor-replit-codemirror-vim-DDj0dSVY.js → vendor-replit-codemirror-vim-DCdAdxvE.js} +3 -3
- package/dist/assets/{vendor-solid-js-0T254UHG.js → vendor-solid-js-9wmPZH9g.js} +1 -1
- package/dist/assets/zh-CN-D-FVCeks.js +15 -0
- package/dist/assets/zh-TW-B9iH_NXL.js +15 -0
- package/dist/index.html +17 -17
- package/dist/mini-chat.html +17 -17
- package/dist/mobile.html +17 -17
- package/package.json +8 -3
- package/server/lib/assistants/DOCUMENTATION.md +33 -1
- package/server/lib/assistants/channels/DOCUMENTATION.md +291 -0
- package/server/lib/assistants/channels/PROTOCOLS.md +228 -0
- package/server/lib/assistants/channels/dingtalk-chat-adapter.js +633 -0
- package/server/lib/assistants/channels/dingtalk-chat-adapter.test.js +415 -0
- package/server/lib/assistants/channels/integration.test.js +44 -0
- package/server/lib/assistants/channels/routes.js +47 -0
- package/server/lib/assistants/channels/routes.test.js +105 -0
- package/server/lib/assistants/channels/runtime.js +867 -0
- package/server/lib/assistants/channels/runtime.test.js +723 -0
- package/server/lib/assistants/channels/sdk-adapters.js +371 -0
- package/server/lib/assistants/channels/sdk-adapters.test.js +367 -0
- package/server/lib/assistants/channels/store.js +246 -0
- package/server/lib/assistants/channels/store.test.js +286 -0
- package/server/lib/assistants/channels/transport.js +41 -0
- package/server/lib/assistants/channels/transport.test.js +23 -0
- package/server/lib/assistants/channels/wecom-chat-adapter.js +689 -0
- package/server/lib/assistants/channels/wecom-chat-adapter.test.js +109 -0
- package/server/lib/assistants/contracts.js +1 -0
- package/server/lib/assistants/message-channel-origin.js +7 -0
- package/server/lib/assistants/routes.js +14 -1
- package/server/lib/assistants/service.js +23 -7
- package/server/lib/assistants/service.test.js +151 -0
- package/server/lib/assistants/weixin/DOCUMENTATION.md +147 -8
- package/server/lib/assistants/weixin/api.js +2 -0
- package/server/lib/assistants/weixin/chat-adapter.js +107 -0
- package/server/lib/assistants/weixin/chat-adapter.test.js +62 -0
- package/server/lib/assistants/weixin/inbound.js +147 -0
- package/server/lib/assistants/weixin/inbound.test.js +121 -0
- package/server/lib/assistants/weixin/media.js +79 -0
- package/server/lib/assistants/weixin/media.test.js +66 -0
- package/server/lib/assistants/weixin/routes.js +4 -3
- package/server/lib/assistants/weixin/routes.test.js +30 -0
- package/server/lib/assistants/weixin/runtime.js +157 -66
- package/server/lib/assistants/weixin/runtime.test.js +372 -6
- package/server/lib/assistants/weixin/store.js +20 -3
- package/server/lib/assistants/weixin/store.test.js +72 -0
- package/server/lib/assistants/weixin/toon.js +49 -0
- package/server/lib/assistants/weixin/toon.test.js +25 -0
- package/server/lib/github/DOCUMENTATION.md +9 -8
- package/server/lib/llm/bridge-plugin.bundle.js +188 -188
- package/server/lib/opencode/DOCUMENTATION.md +2 -1
- package/server/lib/opencode/npm-registry.js +7 -21
- package/server/lib/opencode/npm-registry.test.js +36 -5
- package/server/lib/opencode/plugin-icon.d.ts +2 -0
- package/server/lib/opencode/plugin-icon.js +43 -0
- package/server/lib/opencode/plugin-icon.test.js +41 -0
- package/server/lib/opencode/plugin-routes.js +3 -1
- package/server/lib/opencode/plugin-routes.test.js +13 -0
- package/dist/assets/AssistantView-C2KQZ6a4.js +0 -3
- package/dist/assets/GuiPluginSurface-Dz2CdSUA.js +0 -1
- package/dist/assets/Icon-BP1sfnHn.js +0 -1
- package/dist/assets/MobileDetailNavigation-B3rUx5Ve.js +0 -1
- package/dist/assets/MobileTabPageHeader-0esgB2TO.js +0 -2
- package/dist/assets/TerminalView-BtM5-BVx.js +0 -8
- package/dist/assets/dropdown-menu.styles-PdxueXzN.js +0 -1
- package/dist/assets/es-BjI1GHJ5.js +0 -15
- package/dist/assets/fr-Bs7ndHkb.js +0 -13
- package/dist/assets/gitApi-BxQmH8Wg.js +0 -10
- package/dist/assets/gitApiHttp-DHrRqnYh.js +0 -7
- package/dist/assets/host-D1EpSUMR.js +0 -1
- package/dist/assets/insertionBoundaries-CKQL85zy.js +0 -1
- package/dist/assets/ja-DkdV26EW.js +0 -15
- package/dist/assets/ko-B0qoC5da.js +0 -15
- package/dist/assets/main-CNwFqQQd.js +0 -2
- package/dist/assets/main-DPhcXanT.js +0 -169
- package/dist/assets/miniChat-CF2vb25D.js +0 -2
- package/dist/assets/mobile-C24qSj44.js +0 -2
- package/dist/assets/pl-D27Y_GBs.js +0 -15
- package/dist/assets/projectMeta-CG8NLahh.js +0 -1
- package/dist/assets/pt-BR-DbocEu4b.js +0 -15
- package/dist/assets/react-CURmDhtB.js +0 -1
- package/dist/assets/readiness-DSJs_3v4.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-ChZCxxH6.js +0 -2
- package/dist/assets/renderMobileApp-CRv3Il6P.js +0 -28
- package/dist/assets/runtime-fetch-D4ja813o.js +0 -1
- package/dist/assets/runtimeConfig-CZrflo-r.js +0 -2
- package/dist/assets/runtimeEndpointReset-Cx3RE97b.js +0 -149
- package/dist/assets/scheduledTaskNavigation-rhgnZaaj.js +0 -1
- package/dist/assets/sessionChangeSummary-CVUA1AFw.js +0 -1
- package/dist/assets/sessionLookup-C3_vQwLe.js +0 -1
- package/dist/assets/sortable-tabs-strip-C1QmKFdb.js +0 -1
- package/dist/assets/speechSettingsQueries-BSQ-2JTv.js +0 -4
- package/dist/assets/src-NKCZI3Lg.css +0 -2
- package/dist/assets/store-DvN2L3vf.js +0 -15
- package/dist/assets/useDesktopWindowControlsLayout-CwgkVw9f.js +0 -1
- package/dist/assets/useMobileNavigationStore-TCj7ZnhV.js +0 -418
- package/dist/assets/useUIStore-DI7va1HH.js +0 -1
- package/dist/assets/vendor-opencode-client-UL_TecvQ.js +0 -12
- package/dist/assets/zh-CN-DhFFdHQu.js +0 -15
- package/dist/assets/zh-TW-BvehppXO.js +0 -15
- /package/dist/assets/{sessionChangeSummary-8C8nv-EP.css → sessionLookup-8C8nv-EP.css} +0 -0
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
import { WebSocketServer } from 'ws';
|
|
2
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
3
|
+
import { createWecomSdkAdapter, WecomChatAdapter } from './wecom-chat-adapter.js';
|
|
4
|
+
|
|
5
|
+
const cleanups = [];
|
|
6
|
+
afterEach(async () => { while (cleanups.length) await cleanups.pop()(); });
|
|
7
|
+
const config = { clientID: 'test-bot', clientSecret: 'test-secret', ownerID: 'owner' };
|
|
8
|
+
|
|
9
|
+
async function connect(overrides = {}) {
|
|
10
|
+
const server = new WebSocketServer({ host: '127.0.0.1', port: 0 });
|
|
11
|
+
await new Promise((resolve) => server.once('listening', resolve));
|
|
12
|
+
cleanups.push(() => new Promise((resolve) => { for (const socket of server.clients) socket.terminate(); server.close(resolve); }));
|
|
13
|
+
const frames = [];
|
|
14
|
+
let socket;
|
|
15
|
+
server.on('connection', (value) => {
|
|
16
|
+
socket = value;
|
|
17
|
+
value.on('message', (bytes) => {
|
|
18
|
+
const frame = JSON.parse(bytes.toString());
|
|
19
|
+
if (frame.cmd === 'aibot_subscribe' || frame.cmd === 'ping') {
|
|
20
|
+
value.send(JSON.stringify({ headers: frame.headers, errcode: 0 }));
|
|
21
|
+
} else frames.push(frame);
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
const bridge = createWecomSdkAdapter({ wsUrl: `ws://127.0.0.1:${server.address().port}` });
|
|
25
|
+
const controller = new AbortController();
|
|
26
|
+
const onReady = vi.fn();
|
|
27
|
+
const onMessage = vi.fn();
|
|
28
|
+
const onError = vi.fn();
|
|
29
|
+
const running = bridge.connect({ config, signal: controller.signal, onReady, onMessage, onError, ...overrides });
|
|
30
|
+
cleanups.push(async () => { controller.abort(); await running.catch(() => {}); });
|
|
31
|
+
await vi.waitFor(() => expect(onReady).toHaveBeenCalledOnce());
|
|
32
|
+
return { bridge, controller, running, frames, socket: () => socket, onMessage, onError,
|
|
33
|
+
ack: (index, errcode = 0) => socket.send(JSON.stringify({ headers: frames[index].headers, errcode })) };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
describe('official WeCom Chat adapter ACK boundary', () => {
|
|
37
|
+
it('waits for real SDK ACKs and sends a second reply without blocking the lane', async () => {
|
|
38
|
+
const h = await connect();
|
|
39
|
+
let settled = false;
|
|
40
|
+
const first = h.bridge.send({ config, text: 'first' }).then(() => { settled = true; });
|
|
41
|
+
await vi.waitFor(() => expect(h.frames).toHaveLength(1));
|
|
42
|
+
expect(settled).toBe(false);
|
|
43
|
+
expect(h.frames[0].body).toMatchObject({ chatid: 'owner', markdown: { content: 'first' } });
|
|
44
|
+
h.ack(0);
|
|
45
|
+
await first;
|
|
46
|
+
const second = h.bridge.send({ config, text: 'second' });
|
|
47
|
+
await vi.waitFor(() => expect(h.frames).toHaveLength(2));
|
|
48
|
+
h.ack(1);
|
|
49
|
+
await expect(second).resolves.toBeUndefined();
|
|
50
|
+
});
|
|
51
|
+
|
|
52
|
+
it('treats a nonzero ACK as a definite safe failure', async () => {
|
|
53
|
+
const h = await connect();
|
|
54
|
+
const sending = expect(h.bridge.send({ config, text: 'rejected' })).rejects.toMatchObject({ code: 'delivery_failed', ambiguous: false });
|
|
55
|
+
await vi.waitFor(() => expect(h.frames).toHaveLength(1));
|
|
56
|
+
h.ack(0, 846605);
|
|
57
|
+
await sending;
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
it('preserves uncertainty on cancellation after sending', async () => {
|
|
61
|
+
const h = await connect();
|
|
62
|
+
const controller = new AbortController();
|
|
63
|
+
const sending = expect(h.bridge.send({ config, text: 'cancel', signal: controller.signal })).rejects.toMatchObject({ code: 'delivery_unknown', ambiguous: true });
|
|
64
|
+
await vi.waitFor(() => expect(h.frames).toHaveLength(1));
|
|
65
|
+
controller.abort();
|
|
66
|
+
await sending;
|
|
67
|
+
});
|
|
68
|
+
|
|
69
|
+
it('preserves platform IDs and only admits owner private messages', async () => {
|
|
70
|
+
const h = await connect();
|
|
71
|
+
const body = { msgid: 'message-one', from: { userid: 'owner' }, chattype: 'single', msgtype: 'voice', voice: { content: 'transcript' } };
|
|
72
|
+
const emit = (value) => h.socket().send(JSON.stringify({ cmd: 'aibot_msg_callback', headers: { req_id: 'incoming' }, body: value }));
|
|
73
|
+
emit({ ...body, chattype: 'group' });
|
|
74
|
+
emit({ ...body, from: { userid: 'stranger' } });
|
|
75
|
+
emit(body);
|
|
76
|
+
await vi.waitFor(() => expect(h.onMessage).toHaveBeenCalledOnce());
|
|
77
|
+
expect(h.onMessage.mock.calls[0][0]).toMatchObject({ id: 'message-one', senderID: 'owner', text: 'transcript', metadata: { transcript: 'platform' } });
|
|
78
|
+
const adapter = new WecomChatAdapter({ ownerId: 'owner' });
|
|
79
|
+
const parsed = adapter.parseMessage({ ...body, msgtype: 'image', image: { url: 'private-url', aeskey: 'private-key' } });
|
|
80
|
+
expect(parsed.id).toBe('message-one');
|
|
81
|
+
expect(JSON.stringify(parsed)).not.toMatch(/private-url|private-key/);
|
|
82
|
+
});
|
|
83
|
+
|
|
84
|
+
it.each(['timeout', 'disconnect'])('keeps %s after submission unknown, never a successful send', async (mode) => {
|
|
85
|
+
const h = await connect();
|
|
86
|
+
const sending = expect(h.bridge.send({ config, text: 'uncertain' })).rejects.toMatchObject({ code: 'delivery_unknown', ambiguous: true });
|
|
87
|
+
await vi.waitFor(() => expect(h.frames).toHaveLength(1));
|
|
88
|
+
if (mode === 'disconnect') h.socket().terminate();
|
|
89
|
+
await sending;
|
|
90
|
+
}, 10_000);
|
|
91
|
+
|
|
92
|
+
it('allows another enterprise Bot account to connect concurrently', async () => {
|
|
93
|
+
const h = await connect();
|
|
94
|
+
const controller = new AbortController();
|
|
95
|
+
const onReady = vi.fn();
|
|
96
|
+
const running = h.bridge.connect({ config: { ...config, clientID: 'second-bot' }, signal: controller.signal, onReady });
|
|
97
|
+
cleanups.push(async () => { controller.abort(); await running.catch(() => {}); });
|
|
98
|
+
await vi.waitFor(() => expect(onReady).toHaveBeenCalledOnce());
|
|
99
|
+
await expect(h.bridge.connect({ config })).rejects.toMatchObject({ code: 'channel_in_use' });
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it('reports missing sessions before writing and refuses duplicate live credentials', async () => {
|
|
103
|
+
const h = await connect();
|
|
104
|
+
await expect(h.bridge.connect({ config })).rejects.toMatchObject({ code: 'channel_in_use' });
|
|
105
|
+
await expect(h.bridge.send({ config: { ...config, clientID: 'another' }, text: 'no session' })).rejects.toMatchObject({ code: 'network_error', ambiguous: false });
|
|
106
|
+
h.controller.abort();
|
|
107
|
+
await h.running;
|
|
108
|
+
});
|
|
109
|
+
});
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Channel admission creates these reserved input IDs; contact turnID persists
|
|
3
|
+
* that exact ID on every reply. Never infer reply routing from the latest input.
|
|
4
|
+
*/
|
|
5
|
+
export function isMessageChannelTurn(turnID) {
|
|
6
|
+
return typeof turnID === 'string' && (turnID.startsWith('weixin:') || turnID.startsWith('channel:'));
|
|
7
|
+
}
|
|
@@ -6,12 +6,16 @@ import { makeOpenCodeV2Client } from '../opencode/v2-client.js';
|
|
|
6
6
|
import path from 'node:path';
|
|
7
7
|
import { createWeixinRuntime } from './weixin/runtime.js';
|
|
8
8
|
import { registerWeixinRoutes } from './weixin/routes.js';
|
|
9
|
+
import { createAssistantChannelsRuntime } from './channels/runtime.js';
|
|
10
|
+
import { registerAssistantChannelRoutes } from './channels/routes.js';
|
|
11
|
+
import { createAssistantChannelAdapters } from './channels/sdk-adapters.js';
|
|
9
12
|
|
|
10
13
|
const respond = (res, work, success = 200) => Promise.resolve().then(work).then((body) => res.status(success).json(body)).catch((error) => { const code = error instanceof AssistantError ? error.code : error?.code || 'internal_error'; const status = code === 'not_found' ? 404 : ['revision_conflict', 'idempotency_conflict', 'contact_generation_conflict'].includes(code) ? 409 : code === 'assistant_disabled' ? 403 : code === 'no_provider' ? 400 : code === 'upstream_error' || code === 'llm_attachment_generation_unavailable' ? 502 : 400; res.status(status).json({ ok: false, error: code, message: typeof error?.message === 'string' && error.message.trim() ? error.message : code }); });
|
|
11
14
|
const gone = (_req, res) => res.status(410).json({ ok: false, error: 'assistant_topics_retired' });
|
|
12
15
|
|
|
13
16
|
export const registerAssistantRoutes = (app, dependencies) => {
|
|
14
17
|
let weixin;
|
|
18
|
+
let channels;
|
|
15
19
|
const boundCompletion = (input) => createChatCompletion({
|
|
16
20
|
...input,
|
|
17
21
|
buildOpenCodeUrl: dependencies.buildOpenCodeUrl,
|
|
@@ -44,6 +48,7 @@ export const registerAssistantRoutes = (app, dependencies) => {
|
|
|
44
48
|
onRevisionTip: dependencies.onRevisionTip,
|
|
45
49
|
onContactTurnEvent: (event) => {
|
|
46
50
|
weixin?.onTurnEvent(event);
|
|
51
|
+
channels?.onTurnEvent(event);
|
|
47
52
|
dependencies.onContactTurnEvent?.(event);
|
|
48
53
|
},
|
|
49
54
|
onContactTurnComplete: dependencies.onContactTurnComplete,
|
|
@@ -62,6 +67,7 @@ export const registerAssistantRoutes = (app, dependencies) => {
|
|
|
62
67
|
app.post('/api/yuri/assistants', (req, res) => respond(res, () => service.createAssistant(req.body), 201)); app.patch('/api/yuri/assistants/:assistantID', (req, res) => respond(res, () => service.updateAssistant(req.params.assistantID, req.body))); app.delete('/api/yuri/assistants/:assistantID', (req, res) => respond(res, async () => {
|
|
63
68
|
const result = service.removeAssistant(req.params.assistantID, req.body?.expectedRevision);
|
|
64
69
|
await weixin.forget(req.params.assistantID);
|
|
70
|
+
await channels.forget(req.params.assistantID);
|
|
65
71
|
return result;
|
|
66
72
|
}));
|
|
67
73
|
app.post('/api/yuri/assistants/:assistantID/session/ensure', (req, res) => respond(res, () => service.ensure(req.params.assistantID))); app.post('/api/yuri/assistants/:assistantID/session/new', (req, res) => respond(res, () => service.createNew(req.params.assistantID))); app.post('/api/yuri/assistants/:assistantID/session/compact', (req, res) => respond(res, () => service.compact(req.params.assistantID, req.body))); app.post('/api/yuri/assistants/:assistantID/session/abort', (req, res) => respond(res, () => service.abort(req.params.assistantID, req.body)));
|
|
@@ -126,10 +132,17 @@ export const registerAssistantRoutes = (app, dependencies) => {
|
|
|
126
132
|
...(dependencies.weixinAPI ? { api: dependencies.weixinAPI } : {}),
|
|
127
133
|
});
|
|
128
134
|
registerWeixinRoutes(app, weixin);
|
|
135
|
+
channels = createAssistantChannelsRuntime({
|
|
136
|
+
directory: path.join(dependencies.yuriDataDir, 'channels'), service,
|
|
137
|
+
refreshAllowedRoots: dependencies.refreshAllowedRoots,
|
|
138
|
+
adapters: dependencies.assistantChannelAdapters ?? createAssistantChannelAdapters(),
|
|
139
|
+
...(dependencies.channelsEnv ? { env: dependencies.channelsEnv } : {}),
|
|
140
|
+
});
|
|
141
|
+
registerAssistantChannelRoutes(app, channels);
|
|
129
142
|
return { service, close: async () => {
|
|
130
143
|
unsubscribeTaskResults?.();
|
|
131
144
|
setAssignedSessionSettleHandler(null);
|
|
132
|
-
await weixin.close();
|
|
145
|
+
await Promise.all([weixin.close(), channels.close()]);
|
|
133
146
|
service.close();
|
|
134
147
|
} };
|
|
135
148
|
};
|
|
@@ -89,7 +89,7 @@ import { buildAssistantSessionMetadata } from '../session-metadata/system-sessio
|
|
|
89
89
|
import { completionEvent, createFamilyCompletionGate, readSessionFamilyActivity } from '../notifications/family-completion-gate.js';
|
|
90
90
|
|
|
91
91
|
const require = createRequire(import.meta.url);
|
|
92
|
-
const SCHEMA_VERSION =
|
|
92
|
+
const SCHEMA_VERSION = 16;
|
|
93
93
|
const normalizeSessionDirectory = (value) => {
|
|
94
94
|
if (typeof value !== 'string') return null;
|
|
95
95
|
const trimmed = value.trim();
|
|
@@ -413,6 +413,7 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
413
413
|
name: row.name,
|
|
414
414
|
defaultPrompt: row.default_prompt,
|
|
415
415
|
avatarSeed: row.avatar_seed ?? row.assistant_id,
|
|
416
|
+
pinnedAt: row.pinned_at ?? null,
|
|
416
417
|
workspacePath: row.workspace_path,
|
|
417
418
|
managedWorkspacePath: workspace(null, row.assistant_id, true),
|
|
418
419
|
effectiveWorkspacePath: effectiveWorkspace(row),
|
|
@@ -508,11 +509,13 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
508
509
|
if (!validAssistantDeliveryParts(parts, { allowAttachmentRefs: true })) fail('validation_error');
|
|
509
510
|
};
|
|
510
511
|
const migrate = () => {
|
|
511
|
-
|
|
512
|
+
const previousVersion = Number(db.prepare("SELECT value FROM assistant_meta WHERE key='schema_version'").get()?.value ?? 0);
|
|
513
|
+
if (previousVersion === SCHEMA_VERSION) return;
|
|
512
514
|
const v2Info = db.prepare("SELECT name,\"notnull\" AS required FROM pragma_table_info('assistant_v2')").all(); const v2Columns = new Set(v2Info.map((column) => column.name));
|
|
513
515
|
if (v2Columns.has('skill_roots') || v2Info.some((column) => column.name === 'workspace_path' && column.required)) db.exec(`CREATE TABLE assistant_v2_next (assistant_id TEXT PRIMARY KEY, revision INTEGER NOT NULL, enabled INTEGER NOT NULL, name TEXT NOT NULL, default_prompt TEXT NOT NULL, workspace_path TEXT, provider_id TEXT NOT NULL, model_id TEXT NOT NULL, agent TEXT, variant TEXT, current_session_id TEXT, session_generation INTEGER NOT NULL DEFAULT 0, created_at INTEGER NOT NULL, updated_at INTEGER NOT NULL, tombstone_at INTEGER); INSERT INTO assistant_v2_next (assistant_id,revision,enabled,name,default_prompt,workspace_path,provider_id,model_id,agent,variant,current_session_id,session_generation,created_at,updated_at,tombstone_at) SELECT assistant_id,revision,enabled,name,default_prompt,workspace_path,provider_id,model_id,agent,NULL,current_session_id,session_generation,created_at,updated_at,tombstone_at FROM assistant_v2; DROP TABLE assistant_v2; ALTER TABLE assistant_v2_next RENAME TO assistant_v2;`);
|
|
514
516
|
if (!new Set(db.prepare("SELECT name FROM pragma_table_info('assistant_v2')").all().map((column) => column.name)).has('variant')) db.exec('ALTER TABLE assistant_v2 ADD COLUMN variant TEXT');
|
|
515
517
|
if (!new Set(db.prepare("SELECT name FROM pragma_table_info('assistant_v2')").all().map((column) => column.name)).has('avatar_seed')) db.exec('ALTER TABLE assistant_v2 ADD COLUMN avatar_seed TEXT');
|
|
518
|
+
if (!new Set(db.prepare("SELECT name FROM pragma_table_info('assistant_v2')").all().map((column) => column.name)).has('pinned_at')) db.exec('ALTER TABLE assistant_v2 ADD COLUMN pinned_at INTEGER');
|
|
516
519
|
if (!new Set(db.prepare("SELECT name FROM pragma_table_info('assistant_v2')").all().map((column) => column.name)).has('mode')) db.exec("ALTER TABLE assistant_v2 ADD COLUMN mode TEXT NOT NULL DEFAULT 'continuous'");
|
|
517
520
|
const managedConfig = (workspacePath, assistantID) => workspacePath != null && path.resolve(workspacePath) === workspaceFor(assistantID) ? null : workspacePath;
|
|
518
521
|
const legacy = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name='assistant'").get();
|
|
@@ -520,11 +523,19 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
520
523
|
for (const row of db.prepare('SELECT assistant_id,workspace_path FROM assistant_v2 WHERE workspace_path IS NOT NULL').all()) { const workspacePath = managedConfig(row.workspace_path, row.assistant_id); if (workspacePath === null) db.prepare('UPDATE assistant_v2 SET workspace_path=NULL WHERE assistant_id=?').run(row.assistant_id); }
|
|
521
524
|
// v13: shared contact read watermark. Legacy transcripts default to fully read
|
|
522
525
|
// so existing installs do not flash unread on upgrade; later messages count.
|
|
523
|
-
migrateContactReadStateDefaultRead(db, { updatedAt: now() });
|
|
524
|
-
db.
|
|
526
|
+
if (previousVersion < 13) migrateContactReadStateDefaultRead(db, { updatedAt: now() });
|
|
527
|
+
db.transaction(() => {
|
|
528
|
+
const pinned = db.prepare('SELECT assistant_id FROM assistant_v2 WHERE pinned_at IS NOT NULL AND tombstone_at IS NULL ORDER BY pinned_at DESC, created_at, rowid LIMIT 1').get();
|
|
529
|
+
if (pinned) {
|
|
530
|
+
const cleared = db.prepare('UPDATE assistant_v2 SET pinned_at=NULL,revision=revision+1,updated_at=? WHERE pinned_at IS NOT NULL AND tombstone_at IS NULL AND assistant_id!=?').run(now(), pinned.assistant_id);
|
|
531
|
+
if (cleared.changes) bump();
|
|
532
|
+
}
|
|
533
|
+
db.exec('CREATE UNIQUE INDEX IF NOT EXISTS assistant_single_pin ON assistant_v2 ((1)) WHERE pinned_at IS NOT NULL AND tombstone_at IS NULL');
|
|
534
|
+
db.prepare("INSERT OR REPLACE INTO assistant_meta(key,value) VALUES ('schema_version',?)").run(String(SCHEMA_VERSION));
|
|
535
|
+
})();
|
|
525
536
|
};
|
|
526
|
-
migrate();
|
|
527
537
|
try {
|
|
538
|
+
migrate();
|
|
528
539
|
db.transaction(() => {
|
|
529
540
|
const restored = db.prepare('UPDATE assistant_v2 SET enabled=1, revision=revision+1, updated_at=? WHERE enabled!=1 AND tombstone_at IS NULL').run(now());
|
|
530
541
|
if (restored.changes) bump();
|
|
@@ -1487,10 +1498,12 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
1487
1498
|
};
|
|
1488
1499
|
const updateAssistant = async (assistantID, input) => {
|
|
1489
1500
|
const row = editable(assistantID);
|
|
1490
|
-
const allowed = new Set(['expectedRevision', 'enabled', 'name', 'avatarSeed', 'defaultPrompt', 'providerID', 'modelID', 'agent', 'variant', 'mode', 'workspacePath']);
|
|
1501
|
+
const allowed = new Set(['expectedRevision', 'enabled', 'name', 'avatarSeed', 'pinned', 'defaultPrompt', 'providerID', 'modelID', 'agent', 'variant', 'mode', 'workspacePath']);
|
|
1491
1502
|
if (!plainObject(input) || !Number.isInteger(input.expectedRevision) || Object.keys(input).some((key) => !allowed.has(key))) fail('validation_error');
|
|
1503
|
+
if (input.pinned !== undefined && typeof input.pinned !== 'boolean') fail('validation_error');
|
|
1492
1504
|
const next = {
|
|
1493
1505
|
avatarSeed: input.avatarSeed === undefined ? row.avatar_seed : string(input.avatarSeed, 256, true),
|
|
1506
|
+
pinnedAt: input.pinned === undefined ? row.pinned_at : input.pinned ? (row.pinned_at ?? now()) : null,
|
|
1494
1507
|
name: input.name === undefined ? row.name : string(input.name, 256, true),
|
|
1495
1508
|
prompt: input.defaultPrompt === undefined ? row.default_prompt : string(input.defaultPrompt, 200_000),
|
|
1496
1509
|
provider: input.providerID === undefined ? row.provider_id : string(input.providerID, 256, true),
|
|
@@ -1507,7 +1520,10 @@ export const createAssistantsService = ({ dbPath, dataDir, buildOpenCodeUrl, get
|
|
|
1507
1520
|
const created = workspaceChanged ? await createSession(nextRow) : null;
|
|
1508
1521
|
try {
|
|
1509
1522
|
db.transaction(() => {
|
|
1510
|
-
|
|
1523
|
+
if (input.pinned === true) {
|
|
1524
|
+
db.prepare('UPDATE assistant_v2 SET pinned_at=NULL,revision=revision+1,updated_at=? WHERE assistant_id!=? AND pinned_at IS NOT NULL AND tombstone_at IS NULL').run(now(), assistantID);
|
|
1525
|
+
}
|
|
1526
|
+
const result = db.prepare('UPDATE assistant_v2 SET avatar_seed=?,pinned_at=?,enabled=1,name=?,default_prompt=?,provider_id=?,model_id=?,agent=?,variant=?,mode=?,workspace_path=?,current_session_id=?,session_generation=session_generation+?,revision=revision+1,updated_at=? WHERE assistant_id=? AND revision=? AND session_generation=? AND tombstone_at IS NULL').run(next.avatarSeed, next.pinnedAt, next.name, next.prompt, next.provider, next.model, next.agent, next.variant, next.mode, next.workspacePath, created?.sessionID ?? row.current_session_id, workspaceChanged ? 1 : 0, now(), assistantID, input.expectedRevision, row.session_generation);
|
|
1511
1527
|
if (!result.changes) fail('revision_conflict');
|
|
1512
1528
|
if (workspaceChanged && row.current_session_id) archiveSession(assistantID, row.current_session_id, effectiveWorkspace(row));
|
|
1513
1529
|
bump();
|
|
@@ -123,6 +123,157 @@ const toolBatch = (calls, content = '') => ({ completion: { choices: [{ message:
|
|
|
123
123
|
const sayThen = (text, name, args) => toolBatch([['notify_user', { text }], [name, args]]);
|
|
124
124
|
|
|
125
125
|
describe('assistants service', () => {
|
|
126
|
+
it('persists pins across clients and restarts without changing catalog, session or share-default order', async () => {
|
|
127
|
+
const directory = root();
|
|
128
|
+
const create = vi.fn();
|
|
129
|
+
let at = 100;
|
|
130
|
+
let service = setup(directory, { create }, { clock: () => at });
|
|
131
|
+
let peer;
|
|
132
|
+
try {
|
|
133
|
+
const first = service.createAssistant(assistantInput);
|
|
134
|
+
const second = service.createAssistant({ ...assistantInput, name: 'B' });
|
|
135
|
+
expect(first.pinnedAt).toBeNull();
|
|
136
|
+
const pinned = await service.updateAssistant(second.id, { expectedRevision: second.revision, pinned: true });
|
|
137
|
+
expect(pinned).toMatchObject({ pinnedAt: 100, sessionID: second.sessionID, sessionGeneration: second.sessionGeneration, avatarSeed: second.avatarSeed });
|
|
138
|
+
at = 200;
|
|
139
|
+
const renamed = await service.updateAssistant(second.id, { expectedRevision: pinned.revision, name: 'Renamed' });
|
|
140
|
+
const repinned = await service.updateAssistant(second.id, { expectedRevision: renamed.revision, pinned: true });
|
|
141
|
+
expect(repinned.pinnedAt).toBe(100);
|
|
142
|
+
expect(service.snapshot().assistants.map(item => item.id)).toEqual([first.id, second.id]);
|
|
143
|
+
peer = setup(directory);
|
|
144
|
+
expect(peer.snapshot().assistants.find(item => item.id === second.id).pinnedAt).toBe(100);
|
|
145
|
+
peer.close(); peer = null;
|
|
146
|
+
service.close(); service = setup(directory);
|
|
147
|
+
const restored = service.snapshot().assistants.find(item => item.id === second.id);
|
|
148
|
+
expect(restored.pinnedAt).toBe(100);
|
|
149
|
+
const unpinned = await service.updateAssistant(second.id, { expectedRevision: restored.revision, pinned: false });
|
|
150
|
+
expect(unpinned.pinnedAt).toBeNull();
|
|
151
|
+
expect(create).not.toHaveBeenCalled();
|
|
152
|
+
} finally {
|
|
153
|
+
peer?.close(); service.close(); fs.rmSync(directory, { recursive: true, force: true });
|
|
154
|
+
}
|
|
155
|
+
});
|
|
156
|
+
it('rejects invalid pins and stale revisions, and rolls back pin changes when storage fails', async () => {
|
|
157
|
+
const directory = root();
|
|
158
|
+
const service = setup(directory);
|
|
159
|
+
const db = new (require('better-sqlite3'))(path.join(directory, 'assistants.sqlite'));
|
|
160
|
+
try {
|
|
161
|
+
const created = service.createAssistant(assistantInput);
|
|
162
|
+
const before = service.snapshot();
|
|
163
|
+
for (const pinned of [null, 1, 'true', {}]) {
|
|
164
|
+
await expect(service.updateAssistant(created.id, { expectedRevision: created.revision, pinned })).rejects.toThrow('validation_error');
|
|
165
|
+
}
|
|
166
|
+
await expect(service.updateAssistant(created.id, { expectedRevision: 999, pinned: true })).rejects.toThrow('revision_conflict');
|
|
167
|
+
db.exec("CREATE TRIGGER reject_pin BEFORE UPDATE OF pinned_at ON assistant_v2 BEGIN SELECT RAISE(ABORT, 'pin write failed'); END");
|
|
168
|
+
await expect(service.updateAssistant(created.id, { expectedRevision: created.revision, pinned: true })).rejects.toThrow('pin write failed');
|
|
169
|
+
expect(service.snapshot()).toEqual(before);
|
|
170
|
+
db.exec('DROP TRIGGER reject_pin');
|
|
171
|
+
const pinned = await service.updateAssistant(created.id, { expectedRevision: created.revision, pinned: true });
|
|
172
|
+
service.removeAssistant(created.id, pinned.revision);
|
|
173
|
+
expect(service.snapshot().assistants).toEqual([]);
|
|
174
|
+
} finally {
|
|
175
|
+
db.close(); service.close(); fs.rmSync(directory, { recursive: true, force: true });
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
it('upgrades existing schema-v14 contacts as unpinned without losing identity or history', () => {
|
|
179
|
+
const directory = root();
|
|
180
|
+
let service = setup(directory);
|
|
181
|
+
try {
|
|
182
|
+
const created = service.createAssistant(assistantInput);
|
|
183
|
+
const messages = service.contactMessages(created.id).messages;
|
|
184
|
+
service.close();
|
|
185
|
+
const db = new (require('better-sqlite3'))(path.join(directory, 'assistants.sqlite'));
|
|
186
|
+
db.exec('DROP INDEX IF EXISTS assistant_single_pin');
|
|
187
|
+
db.exec('ALTER TABLE assistant_v2 DROP COLUMN pinned_at');
|
|
188
|
+
db.prepare("UPDATE assistant_meta SET value='14' WHERE key='schema_version'").run();
|
|
189
|
+
db.close();
|
|
190
|
+
service = setup(directory);
|
|
191
|
+
expect(service.snapshot().assistants[0]).toEqual(created);
|
|
192
|
+
expect(service.contactMessages(created.id).messages).toEqual(messages);
|
|
193
|
+
} finally {
|
|
194
|
+
service.close(); fs.rmSync(directory, { recursive: true, force: true });
|
|
195
|
+
}
|
|
196
|
+
});
|
|
197
|
+
it('atomically replaces the pinned Bot across clients and rejects stale edits to the previous owner', async () => {
|
|
198
|
+
const directory = root();
|
|
199
|
+
const service = setup(directory);
|
|
200
|
+
const peer = setup(directory);
|
|
201
|
+
try {
|
|
202
|
+
const first = service.createAssistant(assistantInput);
|
|
203
|
+
const second = service.createAssistant({ ...assistantInput, name: 'B' });
|
|
204
|
+
const before = service.snapshot();
|
|
205
|
+
const old = await service.updateAssistant(first.id, { expectedRevision: first.revision, pinned: true });
|
|
206
|
+
await peer.updateAssistant(second.id, { expectedRevision: second.revision, pinned: true });
|
|
207
|
+
const after = service.snapshot();
|
|
208
|
+
expect(after.assistants.filter(item => item.pinnedAt !== null).map(item => item.id)).toEqual([second.id]);
|
|
209
|
+
expect(after.assistants[0]).toMatchObject({ pinnedAt: null, revision: old.revision + 1, unreadCount: first.unreadCount, readWatermark: first.readWatermark });
|
|
210
|
+
expect(after.assistants.map(item => item.id)).toEqual(before.assistants.map(item => item.id));
|
|
211
|
+
await expect(service.updateAssistant(first.id, { expectedRevision: old.revision, pinned: true })).rejects.toThrow('revision_conflict');
|
|
212
|
+
expect(service.snapshot()).toEqual(after);
|
|
213
|
+
} finally { peer.close(); service.close(); fs.rmSync(directory, { recursive: true, force: true }); }
|
|
214
|
+
});
|
|
215
|
+
it('rolls back clearing the old pin when writing the replacement fails', async () => {
|
|
216
|
+
const directory = root();
|
|
217
|
+
const service = setup(directory);
|
|
218
|
+
const db = new (require('better-sqlite3'))(path.join(directory, 'assistants.sqlite'));
|
|
219
|
+
try {
|
|
220
|
+
const first = service.createAssistant(assistantInput);
|
|
221
|
+
const second = service.createAssistant({ ...assistantInput, name: 'B' });
|
|
222
|
+
await service.updateAssistant(first.id, { expectedRevision: first.revision, pinned: true });
|
|
223
|
+
const before = service.snapshot();
|
|
224
|
+
db.exec("CREATE TRIGGER reject_replacement BEFORE UPDATE OF pinned_at ON assistant_v2 WHEN NEW.pinned_at IS NOT NULL BEGIN SELECT RAISE(ABORT, 'replacement failed'); END");
|
|
225
|
+
await expect(service.updateAssistant(second.id, { expectedRevision: second.revision, pinned: true })).rejects.toThrow('replacement failed');
|
|
226
|
+
expect(service.snapshot()).toEqual(before);
|
|
227
|
+
db.exec('DROP TRIGGER reject_replacement');
|
|
228
|
+
await service.updateAssistant(second.id, { expectedRevision: second.revision, pinned: true });
|
|
229
|
+
expect(service.snapshot().assistants.filter(item => item.pinnedAt !== null).map(item => item.id)).toEqual([second.id]);
|
|
230
|
+
} finally { db.close(); service.close(); fs.rmSync(directory, { recursive: true, force: true }); }
|
|
231
|
+
});
|
|
232
|
+
it('keeps a single pin under competing client writes and a database constraint rejects bypasses', async () => {
|
|
233
|
+
const directory = root();
|
|
234
|
+
const service = setup(directory);
|
|
235
|
+
const peer = setup(directory);
|
|
236
|
+
const db = new (require('better-sqlite3'))(path.join(directory, 'assistants.sqlite'));
|
|
237
|
+
try {
|
|
238
|
+
const first = service.createAssistant(assistantInput);
|
|
239
|
+
const second = service.createAssistant({ ...assistantInput, name: 'B' });
|
|
240
|
+
await Promise.all([
|
|
241
|
+
service.updateAssistant(first.id, { expectedRevision: first.revision, pinned: true }),
|
|
242
|
+
peer.updateAssistant(second.id, { expectedRevision: second.revision, pinned: true }),
|
|
243
|
+
]);
|
|
244
|
+
const snapshot = service.snapshot();
|
|
245
|
+
expect(snapshot.assistants.filter(item => item.pinnedAt !== null)).toHaveLength(1);
|
|
246
|
+
const unpinned = snapshot.assistants.find(item => item.pinnedAt === null);
|
|
247
|
+
expect(() => db.prepare('UPDATE assistant_v2 SET pinned_at=123 WHERE assistant_id=?').run(unpinned.id)).toThrow();
|
|
248
|
+
expect(service.snapshot()).toEqual(snapshot);
|
|
249
|
+
} finally { db.close(); peer.close(); service.close(); fs.rmSync(directory, { recursive: true, force: true }); }
|
|
250
|
+
});
|
|
251
|
+
it('migrates multiple v15 pins to the latest one, preserves unread and retries a failed migration atomically', async () => {
|
|
252
|
+
const directory = root();
|
|
253
|
+
let service = setup(directory);
|
|
254
|
+
const first = service.createAssistant(assistantInput);
|
|
255
|
+
const second = service.createAssistant({ ...assistantInput, name: 'B' });
|
|
256
|
+
service.close();
|
|
257
|
+
const db = new (require('better-sqlite3'))(path.join(directory, 'assistants.sqlite'));
|
|
258
|
+
try {
|
|
259
|
+
db.exec('DROP INDEX assistant_single_pin');
|
|
260
|
+
db.prepare('UPDATE assistant_v2 SET pinned_at=? WHERE assistant_id=?').run(10, first.id);
|
|
261
|
+
db.prepare('UPDATE assistant_v2 SET pinned_at=? WHERE assistant_id=?').run(20, second.id);
|
|
262
|
+
db.prepare("UPDATE assistant_meta SET value='15' WHERE key='schema_version'").run();
|
|
263
|
+
db.exec("CREATE TRIGGER reject_pin_migration BEFORE UPDATE OF pinned_at ON assistant_v2 BEGIN SELECT RAISE(ABORT, 'pin migration failed'); END");
|
|
264
|
+
expect(() => setup(directory)).toThrow('pin migration failed');
|
|
265
|
+
expect(db.prepare("SELECT value FROM assistant_meta WHERE key='schema_version'").get().value).toBe('15');
|
|
266
|
+
expect(db.prepare('SELECT COUNT(*) AS count FROM assistant_v2 WHERE pinned_at IS NOT NULL').get().count).toBe(2);
|
|
267
|
+
db.exec('DROP TRIGGER reject_pin_migration');
|
|
268
|
+
service = setup(directory);
|
|
269
|
+
const snapshot = service.snapshot();
|
|
270
|
+
expect(snapshot.assistants.filter(item => item.pinnedAt !== null).map(item => item.id)).toEqual([second.id]);
|
|
271
|
+
expect(snapshot.assistants[0]).toMatchObject({ pinnedAt: null, revision: first.revision + 1, unreadCount: first.unreadCount, readWatermark: first.readWatermark });
|
|
272
|
+
expect(snapshot.assistants[1]).toMatchObject({ pinnedAt: 20, revision: second.revision, unreadCount: second.unreadCount });
|
|
273
|
+
service.close(); service = setup(directory);
|
|
274
|
+
expect(service.snapshot()).toEqual(snapshot);
|
|
275
|
+
} finally { db.close(); service.close(); fs.rmSync(directory, { recursive: true, force: true }); }
|
|
276
|
+
});
|
|
126
277
|
it.each([
|
|
127
278
|
['en', "Hi, I'm A. How can I help you?"],
|
|
128
279
|
['zh-CN', '你好,我是A,有什么可以帮你的吗?'],
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# WeChat
|
|
1
|
+
# WeChat message channel
|
|
2
2
|
|
|
3
3
|
This Host-owned channel connects a QR-authorized personal WeChat account to one
|
|
4
4
|
existing Yuri Bot. It uses Tencent's public `openclaw-weixin` iLink wire reference,
|
|
@@ -13,19 +13,50 @@ service protocol. No OpenClaw runtime or new dependency is installed.
|
|
|
13
13
|
ordered outgoing deliveries and process-owner lease.
|
|
14
14
|
- `runtime.js`: QR lifecycle, owner-only admission, bounded output reconciliation,
|
|
15
15
|
retry/ambiguity and shutdown. `routes.js` exposes authenticated settings only.
|
|
16
|
+
- `chat-adapter.js`: the Chat SDK `Adapter` extension for personal-WeChat Bot.
|
|
17
|
+
Standard `Message`, thread identity, owner-only `openDM`, normalization and
|
|
18
|
+
`postMessage` are used by the running channel, not a separate demonstration path.
|
|
19
|
+
iLink-specific `poll`/`receipt` extensions preserve atomic cursor/receipt commits
|
|
20
|
+
and existing stable delivery IDs. Credentials and media capabilities remain in
|
|
21
|
+
private closures/receipts, not serialized Chat messages. Unsupported operations
|
|
22
|
+
throw `NotImplementedError`; HTTP webhook handling explicitly returns 501.
|
|
16
23
|
- `typing.js`: optional per-binding live typing state, ticket lifetime, bounded
|
|
17
24
|
refresh/backoff and serialized cancellation; no persisted presence or UI state.
|
|
25
|
+
- `inbound.js`: bounded inbound content projection, private media references,
|
|
26
|
+
partial-success attachment admission and TOON model/transcript context.
|
|
27
|
+
- `media.js`: deadline/byte-bounded official CDN downloads, AES-128-ECB decoding
|
|
28
|
+
and MIME identification; no arbitrary URL fetch or credential forwarding.
|
|
29
|
+
- `toon.js`: local JSON-only TOON encoder (objects, lists, primitive/tabular
|
|
30
|
+
arrays); no new dependency, key folding, raw-string emission or decoding API.
|
|
18
31
|
- `assistants/service.channelPage()` is an internal bounded, ascending durable
|
|
19
32
|
output seam. It validates the Bot and uses the contact-store generation. It does
|
|
20
33
|
not expose credentials or replace the contact execution engine.
|
|
21
34
|
- Shared `AssistantChannelsGroup` appears last in each **saved** Bot's settings,
|
|
22
35
|
after scheduled tasks. One labelled **Message channels** group owns its card;
|
|
23
|
-
WeChat
|
|
36
|
+
WeChat, WeCom, Feishu and DingTalk form a 2×2 set of colored brand entries;
|
|
37
|
+
configuration (including WeChat QR/verification/rebind) opens in a dialog.
|
|
38
|
+
It is not a global setting or one search entry per
|
|
24
39
|
dynamic Bot. Web, desktop, hosted mobile and Capacitor configure the active Host
|
|
25
40
|
through `runtimeFetch`; standalone VS Code explicitly returns 501.
|
|
26
41
|
|
|
27
42
|
## Authorization and persistence
|
|
28
43
|
|
|
44
|
+
Before opening storage or creating any timer, the runtime resolves the channel
|
|
45
|
+
policy from its environment. `NODE_ENV=development` or `YURI_ELECTRON_DEV=1/true`
|
|
46
|
+
disables WeChat by default; the web development server scripts explicitly set
|
|
47
|
+
`NODE_ENV=development`, including watch/HMR/full/mobile live-reload paths. An
|
|
48
|
+
explicit `YURI_WEIXIN_ENABLED=1/true` opts in; `0/false` or an unrecognized nonempty
|
|
49
|
+
value disables it in any environment. Production defaults remain enabled.
|
|
50
|
+
|
|
51
|
+
A disabled runtime does not open/create SQLite, acquire/release leases, poll,
|
|
52
|
+
send, infer live typing or mutate bindings. Status returns `disabled`; QR login,
|
|
53
|
+
verification, retry, disconnect and transfer fail with `channel_disabled` (403).
|
|
54
|
+
`forget` and shutdown are no-ops, so development does not erase production channel
|
|
55
|
+
credentials. Shared UI displays the disabled state without connection controls
|
|
56
|
+
and does not poll it. This gate is channel-specific, not general isolation of
|
|
57
|
+
assistant data; testing channels still requires an isolated data directory and
|
|
58
|
+
test account. Never copy production WeChat credentials into a second database.
|
|
59
|
+
|
|
29
60
|
The QR-confirmed `ilink_user_id` is the only accepted sender. Group messages,
|
|
30
61
|
other senders and messages without a stable platform ID never invoke tools. Each
|
|
31
62
|
bound account maps to exactly one Bot within the Host data directory. The account
|
|
@@ -47,13 +78,55 @@ revocation API, so this is not a promise to revoke the platform's authorization.
|
|
|
47
78
|
Deleting a Bot also forgets its local connection. Failed revision-checked Bot
|
|
48
79
|
deletion leaves the connection intact.
|
|
49
80
|
|
|
81
|
+
### Moving a connection between Yuri Bots
|
|
82
|
+
|
|
83
|
+
The current WeChat flow supports one Bot entry for a scanning WeChat user, not a
|
|
84
|
+
new independent entry on every scan. Multiple stored bindings represent separate
|
|
85
|
+
platform accounts, not evidence that one user can create multiple contacts. QR
|
|
86
|
+
`binded_redirect` and confirmed-account conflicts never silently steal a binding.
|
|
87
|
+
|
|
88
|
+
For an unbound target, authenticated status responses optionally list local
|
|
89
|
+
`transferSources` containing only the source Bot ID, display name and binding
|
|
90
|
+
revision (epoch). No platform account/user IDs, tokens or context tickets leave
|
|
91
|
+
the Host. The settings row offers an explicit two-step confirmation, including
|
|
92
|
+
the loss of unprocessed inbound messages and queued outgoing replies. No QR or
|
|
93
|
+
platform reauthorization is required to move an existing local authorization.
|
|
94
|
+
|
|
95
|
+
`POST /api/yuri/assistants/:assistantID/weixin/transfer` accepts `sourceAssistantID`,
|
|
96
|
+
`revision` and UI `language`. The Host requires the current lease, a live source
|
|
97
|
+
matching that exact epoch and an unbound target; it will not overwrite even an
|
|
98
|
+
expired target binding. Source/target are locked while receiving and sending are
|
|
99
|
+
aborted/drained, live typing is cancelled, and target QR attempts are invalidated.
|
|
100
|
+
Both Bots and the source epoch are revalidated after the wait. Concurrent moves,
|
|
101
|
+
disconnects and QR starts cannot race this boundary; stale confirmations return
|
|
102
|
+
`binding_changed` (409). Shutdown waits for the move before releasing storage.
|
|
103
|
+
|
|
104
|
+
One SQLite transaction moves credentials, paired owner, cursor and reply context,
|
|
105
|
+
assigns a new epoch, sets the target's current transcript tip and drops the source
|
|
106
|
+
outbox. Receipt IDs survive under the new epoch as done, with cleared text, so
|
|
107
|
+
platform replays cannot re-execute tools after a move or restart. Pending messages
|
|
108
|
+
are not reassigned to the new Bot. Histories stay with their original Bots; already
|
|
109
|
+
admitted tasks continue there without further WeChat synchronization. Already
|
|
110
|
+
submitted HTTP sends cannot be recalled. Failed validation or transaction writes
|
|
111
|
+
leave source credentials, cursor and queues intact and resume its receiver (an
|
|
112
|
+
interrupted in-flight send still has the normal uncertain-delivery semantics).
|
|
113
|
+
|
|
114
|
+
The UI invalidates the current Host's channel queries after mutations, including
|
|
115
|
+
the source and target, and rejects stale-runtime completions. Connection candidates
|
|
116
|
+
are dynamic entity rows, not global Settings search entries. A connection owned by
|
|
117
|
+
WorkBuddy or another Host cannot be imported: users must unlink in that application
|
|
118
|
+
and authorize Yuri through the platform flow. Local disconnect alone does not
|
|
119
|
+
promise to revoke a remote application's authorization.
|
|
120
|
+
|
|
50
121
|
## Delivery semantics
|
|
51
122
|
|
|
52
123
|
Incoming receipt, reply context and platform cursor commit together before calling
|
|
53
124
|
`service.send()`. Namespaced IDs keep admission idempotent across duplicates and
|
|
54
125
|
restarts. Incoming and outgoing work is separate from the long-poll receiver; pending
|
|
55
126
|
plus admitted receipt count applies backpressure at 100, with 20 admissions per pass.
|
|
56
|
-
Each active account has one receiver
|
|
127
|
+
Each active account has one receiver, one serial input-preparation worker and one
|
|
128
|
+
outbound scheduler. Media downloads do not block same-account replies or another
|
|
129
|
+
account's preparation/sending. The process lease
|
|
57
130
|
renews every 2 seconds and expires after 60 seconds; another process sharing this
|
|
58
131
|
data directory cannot steal a live account. After any network wait, epoch/lease
|
|
59
132
|
checks fence stale writes. Cross-machine copies of credentials/data are unsupported.
|
|
@@ -63,10 +136,66 @@ sent. Subsequent **public assistant replies**, including App-initiated and backg
|
|
|
63
136
|
task replies, sync to the paired owner. Plain text is sent as text; current cards
|
|
64
137
|
become title/name text, not interactive WeChat cards or deeplinks. Internal settle
|
|
65
138
|
markers are omitted and failures use a safe generic message, never raw tool errors.
|
|
66
|
-
|
|
67
|
-
drops queued output from the previous transcript. An already submitted HTTP request
|
|
139
|
+
Generation reset drops queued output from the previous transcript. An already submitted HTTP request
|
|
68
140
|
cannot be recalled, including during disconnect/reset.
|
|
69
141
|
|
|
142
|
+
### Rich inbound content
|
|
143
|
+
|
|
144
|
+
- Plain text retains the ordinary text path. Item protocol IDs (`msg_id`) and
|
|
145
|
+
envelope fields such as timestamps do not create a separate TOON text part.
|
|
146
|
+
Every recognized image, voice, file
|
|
147
|
+
and video item is represented; mixed items no longer silently lose media. An
|
|
148
|
+
item-level `msg_id` is accepted when the top-level message ID is absent, matching
|
|
149
|
+
the reference client. Sender/group/ID authorization runs before normalization
|
|
150
|
+
or media access.
|
|
151
|
+
- Images download/decrypt and enter the existing `putAssistantContactAttachment`
|
|
152
|
+
pipeline with deterministic receipt/item upload IDs. The transcript stores opaque
|
|
153
|
+
attachment descriptors, not data URLs, CDN capabilities or AES keys. Existing
|
|
154
|
+
contact materialization supplies bytes to vision-capable models; choosing a
|
|
155
|
+
non-vision model does not acquire image understanding through this channel.
|
|
156
|
+
Thumbnail-only references are labelled as thumbnails; URL-only image references
|
|
157
|
+
still pass the same fixed-CDN validation. Neither permits arbitrary web fetching.
|
|
158
|
+
- Voice uses platform `voice_item.text` when present, without a duplicate audio
|
|
159
|
+
download. Otherwise the original audio is retained as an attachment and marked
|
|
160
|
+
**not transcribed**. No SILK decoder, automatic ASR provider, guessed transcript
|
|
161
|
+
or new speech dependency is installed. Video similarly retains the original file,
|
|
162
|
+
not a claim of audiovisual understanding. Text files use the existing gateway's
|
|
163
|
+
bounded inline-text path; other document formats retain normal attachment/model
|
|
164
|
+
limitations rather than being represented as extracted text.
|
|
165
|
+
- Unknown item types and top-level content extensions retain bounded structured
|
|
166
|
+
data, including share titles, descriptions and article URLs **if supplied by the
|
|
167
|
+
platform**. JSON-valued strings are projected structurally; XML remains quoted
|
|
168
|
+
external text (no XML/entity expansion or URL fetching). Inline quote titles,
|
|
169
|
+
IDs, substring metadata and supplied content are retained; an ID-only quote does
|
|
170
|
+
not invent a cached body. This is not a guessed public article-item schema.
|
|
171
|
+
- Structure becomes TOON in an ordinary user text part, explicitly labelled as
|
|
172
|
+
external content. Transport/authentication fields, media references/keys, bearer
|
|
173
|
+
values and known sensitive URL parameters are excluded; raw upstream errors never
|
|
174
|
+
reach the model/transcript. Links or metadata are not evidence that article
|
|
175
|
+
contents were retrieved. The channel does not automatically fetch arbitrary
|
|
176
|
+
article links or bypass WeChat login/risk controls. If iLink never delivers a
|
|
177
|
+
share card, Yuri cannot recover it from the user's WeChat client.
|
|
178
|
+
- Bounds: 20 top-level items, eight downloads, nesting limits, a 24,000-character
|
|
179
|
+
metadata budget (8,000 per string), and 20,000 ordinary text characters per
|
|
180
|
+
message. Truncation is explicit. Each file is capped at 20 MiB to match the LLM
|
|
181
|
+
gateway, and each turn at 50 MiB. Downloads are serial per account, have a
|
|
182
|
+
20-second deadline, reject redirects, and only accept HTTPS at the known
|
|
183
|
+
`novac2c.cdn.weixin.qq.com/c2c/download` endpoint. Unknown CDN hosts degrade to
|
|
184
|
+
metadata with an unavailable marker rather than widening the fetch boundary.
|
|
185
|
+
- One failed download/storage operation does not discard text, transcripts,
|
|
186
|
+
share fields or successful attachments. Missing bytes and original-only media
|
|
187
|
+
have explicit status. Byte/metadata limits are degradation, not empty success.
|
|
188
|
+
|
|
189
|
+
The private inbox gains an additive `payload` column (old rows default to empty).
|
|
190
|
+
It stores normalized metadata and bounded media capabilities before advancing the
|
|
191
|
+
cursor, allowing pre-admission work to resume after restart with stable upload IDs.
|
|
192
|
+
After admission the existing no-tool-replay recovery rule applies. Completed,
|
|
193
|
+
recovered and transferred receipts clear both text and private payload; disconnect
|
|
194
|
+
deletes them. Download cancellation and post-await binding/lease/auth/generation
|
|
195
|
+
checks prevent stale preparation from admitting a message after disconnect, move,
|
|
196
|
+
expiry or transcript reset. Successfully staged attachments follow the existing
|
|
197
|
+
contact attachment lifecycle, including its normal unreferenced-object behavior.
|
|
198
|
+
|
|
70
199
|
Replies are split by Unicode code points into at most 3500-character segments;
|
|
71
200
|
stable client IDs and ordered outbox rows survive restart. This is not a server-side
|
|
72
201
|
exactly-once guarantee. An uncertain HTTP result is marked **delivery unknown** and
|
|
@@ -93,7 +222,11 @@ content and stale runtime mutations cannot overwrite a new Host's cache.
|
|
|
93
222
|
### Typing presence
|
|
94
223
|
|
|
95
224
|
Only live `yuri:contact-turn-start/end` events drive typing, including App-initiated
|
|
96
|
-
or background contact turns
|
|
225
|
+
or background contact turns without a channel source, which may push to WeChat.
|
|
226
|
+
Replies to channel-originated turns require an exact receipt in this binding:
|
|
227
|
+
WeChat inputs reply only here, and enterprise-channel inputs never broadcast here.
|
|
228
|
+
The persisted contact turn ID identifies the original admitted input across restart.
|
|
229
|
+
Binding or
|
|
97
230
|
restarting does not infer activity from persisted receipts/history, and historical
|
|
98
231
|
end events or streaming deltas never start an indicator. A turn already running
|
|
99
232
|
before binding is not backfilled. Overlapping live turn IDs share one indicator;
|
|
@@ -136,7 +269,13 @@ unlimited proactive notifications or arbitrary rich-card support.
|
|
|
136
269
|
|
|
137
270
|
Focused tests cover wire behavior, business errors, QR fencing, owner isolation,
|
|
138
271
|
dedup, restart, conflicting bindings, process lease, shutdown, generation changes,
|
|
139
|
-
unknown delivery, HTTP protection,
|
|
140
|
-
|
|
272
|
+
unknown delivery, HTTP protection, confirmed moves, failed-write rollback,
|
|
273
|
+
cursor/dedup preservation, concurrent/stale moves, typing cancellation/stale completions,
|
|
274
|
+
and real contact-pipeline execution with a fake WeChat service. Rich-input coverage
|
|
275
|
+
includes AES key encodings, SSRF/redirect/size boundaries, partial success,
|
|
276
|
+
TOON quoting, synthetic unknown share fields, voice transcripts, private-field
|
|
277
|
+
redaction, durable receipt migration/rollback/restart and real attachment storage.
|
|
278
|
+
Synthetic article extension fixtures are not evidence of a live platform schema.
|
|
279
|
+
Real-account
|
|
141
280
|
QR/verification, phone-visible delivery and typing presentation still require
|
|
142
281
|
manual testing; mocks and builds are not evidence of platform acceptance.
|