@yuriai/web 0.2.27-beta.2 → 0.2.27-beta.6
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 +9 -0
- package/dist/assets/{AgentAvatar-BW4Zg8bo.js → AgentAvatar-Bi1vvWPC.js} +1 -1
- package/dist/assets/AssistantContactStatus-CWq-PDz6.js +3 -0
- package/dist/assets/AssistantUnreadBadge-DdJyySwn.js +1 -0
- package/dist/assets/AssistantView-Br1iETTs.js +1 -0
- package/dist/assets/{DiagramView-D6wdXRzu.js → DiagramView-CI4bTtxy.js} +1 -1
- package/dist/assets/{FadeInOnReveal-gOsILpSk.js → FadeInOnReveal-BB4qEnAn.js} +1 -1
- package/dist/assets/GuiPluginSurface-CguxFUbM.js +1 -0
- package/dist/assets/{GuiPluginWindow-tGvc4_0g.js → GuiPluginWindow-DOJ7wuRH.js} +1 -1
- package/dist/assets/Icon-t2xvbAyN.js +1 -0
- package/dist/assets/{ImageLoadingPlaceholder-9xYbKqtf.js → ImageLoadingPlaceholder-D1L13TK0.js} +1 -1
- package/dist/assets/{LoadingImage-CiOcKPfb.js → LoadingImage-5rY_edNm.js} +1 -1
- package/dist/assets/{MarkdownRenderer-DZkP4UNr.js → MarkdownRenderer-BlGxjOei.js} +2 -2
- package/dist/assets/{MarkdownRendererImpl-BXzPUEEo.js → MarkdownRendererImpl-cE-0AYRg.js} +1 -1
- package/dist/assets/{MarkstreamRendererImpl-B-NWd069.js → MarkstreamRendererImpl-BZyqDl82.js} +1 -1
- package/dist/assets/MobileDetailNavigation-tbfsMfB-.js +1 -0
- package/dist/assets/{MobileResizableSheet-ZL-zPa3W.js → MobileResizableSheet-BeRmT6_x.js} +1 -1
- package/dist/assets/{MobileShareBridge-JSH_Y8Ps.js → MobileShareBridge-C3Equ3P_.js} +2 -2
- package/dist/assets/MobileTabPageHeader-DQRqAAEf.js +2 -0
- package/dist/assets/{MultiRunWindow-ZPz62Aqg.js → MultiRunWindow-CAM2XPII.js} +1 -1
- package/dist/assets/{OnboardingScreen-BQNoy9o1.js → OnboardingScreen-4ftRerP5.js} +1 -1
- package/dist/assets/{OverlayScrollbar-BwCFalSw.js → OverlayScrollbar-CF0PCvQz.js} +1 -1
- package/dist/assets/{SettingsView-B17qt8dh.js → SettingsView-2tk4WH7R.js} +15 -15
- package/dist/assets/{SettingsWindow-CIFNHb-F.js → SettingsWindow-B9zbeJaW.js} +1 -1
- package/dist/assets/TerminalView-DfxvTHye.js +8 -0
- package/dist/assets/{ToolOutputDialog-BKuVpgEu.js → ToolOutputDialog-CrjDIhru.js} +1 -1
- package/dist/assets/{YuriLogo-C1Ty-RTB.js → YuriLogo-QvS1ZEHi.js} +1 -1
- package/dist/assets/{appThemeRegistry-DqGuzMaH.js → appThemeRegistry-Bb_DtiV9.js} +1 -1
- package/dist/assets/{button-DuHjvKJJ.js → button-DinGM3tu.js} +1 -1
- package/dist/assets/{capgoAdapter-B-tddboe.js → capgoAdapter-DufzjXRs.js} +1 -1
- package/dist/assets/{collapsible-B8eL5nLo.js → collapsible-Bh1GLNYV.js} +1 -1
- package/dist/assets/context-menu-DpbkRkk1.js +1 -0
- package/dist/assets/{diagram-ChoQDKzy.js → diagram-BmG-7Jb4.js} +1 -1
- package/dist/assets/{dialog-CVhqZux0.js → dialog-BXssfGXA.js} +1 -1
- package/dist/assets/es-HP_Ise0X.js +15 -0
- package/dist/assets/{fileMentionTouchSelection-Dd-iSIe2.js → fileMentionTouchSelection-DSl0tj2r.js} +1 -1
- package/dist/assets/{fileReferenceActions-BAoEu4z8.js → fileReferenceActions-CGpBSFq4.js} +1 -1
- package/dist/assets/fr-D0kJXJ6U.js +13 -0
- package/dist/assets/gitApi-Wo0IZow9.js +370 -0
- package/dist/assets/{gitApiHttp-DHrRqnYh.js → gitApiHttp-De9liKnG.js} +4 -4
- package/dist/assets/host-FR_grJxM.js +1 -0
- package/dist/assets/{input-E_oYiXZT.js → input-v8-rVbo-.js} +1 -1
- package/dist/assets/insertionBoundaries-CZz7TWJv.js +1 -0
- package/dist/assets/ja-BjHKXazE.js +15 -0
- package/dist/assets/ko-Llwnl876.js +15 -0
- package/dist/assets/main-Bp9HHqTr.js +2 -0
- package/dist/assets/main-DOwAfmxJ.js +169 -0
- package/dist/assets/{markdownHeightCache-heNXHdzb.js → markdownHeightCache-BVV2dktw.js} +1 -1
- package/dist/assets/{mcpQueries-BqKVe4Su.js → mcpQueries-BoBrB4a4.js} +1 -1
- package/dist/assets/miniChat-BJDgCrfF.js +2 -0
- package/dist/assets/mobile-GM9931J_.js +2 -0
- package/dist/assets/{mobileBackNavigation-DHxFQ7SY.js → mobileBackNavigation-DMSzAvb6.js} +1 -1
- package/dist/assets/{multirun-CPOzaEQj.js → multirun-BhWttsRQ.js} +1 -1
- package/dist/assets/{native-De1DIkLZ.js → native-DSvNnKAm.js} +1 -1
- package/dist/assets/{native-config-oauL2ekt.js → native-config-DjdrW_9n.js} +1 -1
- package/dist/assets/{persistence-JyLTFv27.js → persistence-CfrHIiIS.js} +1 -1
- package/dist/assets/pl-BOd_idqn.js +15 -0
- package/dist/assets/{projectMeta-YDMdD3AP.js → projectMeta-31PobC-M.js} +1 -1
- package/dist/assets/pt-BR-B8djxMsl.js +15 -0
- package/dist/assets/react-B9v0P7kT.js +1 -0
- package/dist/assets/{readiness-BveVUOIb.js → readiness-CYNnsekT.js} +1 -1
- package/dist/assets/renderElectronMiniChatApp-N2r999Bf.js +2 -0
- package/dist/assets/renderMobileApp-CU1ec6Ak.js +28 -0
- package/dist/assets/{runtimeConfig-BpcgdIV9.js → runtimeConfig-Db7yfo6L.js} +1 -1
- package/dist/assets/runtimeEndpointReset-DO5WVetV.js +149 -0
- package/dist/assets/scheduledTaskNavigation-Bsrhv3Ow.js +1 -0
- package/dist/assets/sessionLookup-DRVy7LM1.js +1 -0
- package/dist/assets/sortable-tabs-strip-yKyqsqut.js +1 -0
- package/dist/assets/speechSettingsQueries-DU25rmGc.js +4 -0
- package/dist/assets/src-Bckdo2XS.css +2 -0
- package/dist/assets/store-CUBymvAC.js +15 -0
- package/dist/assets/{terminalApi-B5o8UqWA.js → terminalApi-BblSkqch.js} +1 -1
- package/dist/assets/{textarea-DmKaqHSb.js → textarea-B39OCNPV.js} +1 -1
- package/dist/assets/{tooltip-DUKu4nC6.js → tooltip-d8TNN4lx.js} +1 -1
- package/dist/assets/{types-DRTMRW4R.js → types-BqFQhQTt.js} +1 -1
- package/dist/assets/{uk-CYZXWdd7.js → uk-BNd7CjVO.js} +4 -4
- package/dist/assets/{useAppFontEffects-BiQf6tgZ.js → useAppFontEffects-BVoVpJYO.js} +57 -55
- package/dist/assets/{useAssistantUIStore-C9FPlYQz.js → useAssistantUIStore-Bp6TxG5E.js} +1 -1
- package/dist/assets/useDesktopWindowControlsLayout-CYx1LNO5.js +1 -0
- package/dist/assets/{useEffectiveDirectory-B8q00InF.js → useEffectiveDirectory-D8FFE5Yn.js} +1 -1
- package/dist/assets/{useFontPreferences-DMiP_Yy-.js → useFontPreferences-BFyBjtQ6.js} +1 -1
- package/dist/assets/useMobileNavigationStore-BHMFeMjo.js +23 -0
- package/dist/assets/useUIStore-BbYD420L.js +1 -0
- package/dist/assets/{useWorkerHighlightedLines-B6lWNk01.js → useWorkerHighlightedLines-CPxG8Fya.js} +1 -1
- package/dist/assets/{vendor-codemirror-search-ZqtrPLjU.js → vendor-codemirror-search-DiPwvA-6.js} +2 -2
- package/dist/assets/{vendor-opencode-plugin-Bw7Q6Nv9.js → vendor-opencode-plugin-CgKz9Hcy.js} +1 -1
- package/dist/assets/{vendor-replit-codemirror-vim-DDj0dSVY.js → vendor-replit-codemirror-vim-DCdAdxvE.js} +3 -3
- package/dist/assets/zh-CN-BkTAEOZG.js +15 -0
- package/dist/assets/zh-TW-x8SfMzfc.js +15 -0
- package/dist/index.html +10 -10
- package/dist/mini-chat.html +10 -10
- package/dist/mobile.html +10 -10
- package/package.json +3 -3
- package/server/lib/assistants/DOCUMENTATION.md +30 -0
- package/server/lib/assistants/contact-store.js +16 -0
- package/server/lib/assistants/contact-store.test.js +19 -0
- package/server/lib/assistants/contracts.js +1 -0
- package/server/lib/assistants/routes.js +25 -3
- package/server/lib/assistants/service.js +30 -8
- package/server/lib/assistants/service.test.js +151 -0
- package/server/lib/assistants/weixin/DOCUMENTATION.md +199 -0
- package/server/lib/assistants/weixin/api.js +113 -0
- package/server/lib/assistants/weixin/api.test.js +80 -0
- package/server/lib/assistants/weixin/routes.js +24 -0
- package/server/lib/assistants/weixin/routes.test.js +71 -0
- package/server/lib/assistants/weixin/runtime.js +426 -0
- package/server/lib/assistants/weixin/runtime.test.js +500 -0
- package/server/lib/assistants/weixin/store.js +116 -0
- package/server/lib/assistants/weixin/typing.js +88 -0
- package/server/lib/assistants/weixin/typing.test.js +185 -0
- 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/server/lib/opencode/shutdown-runtime.js +1 -1
- package/server/lib/opencode/shutdown-runtime.test.js +12 -0
- package/dist/assets/AssistantView-Cl0ZeXwr.js +0 -3
- package/dist/assets/GuiPluginSurface-DOZAQKX0.js +0 -1
- package/dist/assets/Icon-DvUDsV1z.js +0 -1
- package/dist/assets/MobileDetailNavigation-5U28hfYf.js +0 -1
- package/dist/assets/MobileTabPageHeader-Bj9MIS38.js +0 -2
- package/dist/assets/TerminalView-BZZ8LW4d.js +0 -8
- package/dist/assets/dropdown-menu.styles-DGvlOX_5.js +0 -1
- package/dist/assets/es-B8sAsuo5.js +0 -15
- package/dist/assets/fr-BPpW8T-l.js +0 -13
- package/dist/assets/gitApi-D43bAQh1.js +0 -10
- package/dist/assets/host-D1EpSUMR.js +0 -1
- package/dist/assets/insertionBoundaries-BQjiZAmZ.js +0 -1
- package/dist/assets/ja-DEoFDi7P.js +0 -15
- package/dist/assets/ko-B45xHN6I.js +0 -15
- package/dist/assets/main-C6MDfyZy.js +0 -2
- package/dist/assets/main-u5iQScJs.js +0 -169
- package/dist/assets/miniChat-Dhfn71Re.js +0 -2
- package/dist/assets/mobile-DSVdPfcG.js +0 -2
- package/dist/assets/pl-Bm3Je_AX.js +0 -15
- package/dist/assets/pt-BR-BiQwFHhL.js +0 -15
- package/dist/assets/react-CURmDhtB.js +0 -1
- package/dist/assets/renderElectronMiniChatApp-NC8iRPyy.js +0 -2
- package/dist/assets/renderMobileApp-D5ai1i6y.js +0 -28
- package/dist/assets/runtimeEndpointReset-ByKa_0nu.js +0 -149
- package/dist/assets/scheduledTaskNavigation-CZfAnPD-.js +0 -1
- package/dist/assets/sessionChangeSummary-D6NlE_5k.js +0 -1
- package/dist/assets/sessionLookup-C70EoX-V.js +0 -1
- package/dist/assets/sortable-tabs-strip-aKussO2c.js +0 -1
- package/dist/assets/speechSettingsQueries-B6qf-mCh.js +0 -4
- package/dist/assets/src-NKCZI3Lg.css +0 -2
- package/dist/assets/store-BeD2keas.js +0 -15
- package/dist/assets/useDesktopWindowControlsLayout-DJxNmCWb.js +0 -1
- package/dist/assets/useMobileNavigationStore-Bn4SaalY.js +0 -418
- package/dist/assets/useUIStore-DI7va1HH.js +0 -1
- package/dist/assets/zh-CN-CMLBHipA.js +0 -15
- package/dist/assets/zh-TW-CJlmnnhK.js +0 -15
- /package/dist/assets/{sessionChangeSummary-8C8nv-EP.css → sessionLookup-8C8nv-EP.css} +0 -0
|
@@ -0,0 +1,500 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
import path from 'node:path';
|
|
4
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
5
|
+
import { createWeixinRuntime } from './runtime.js';
|
|
6
|
+
import { createWeixinStore } from './store.js';
|
|
7
|
+
import { WeixinError } from './api.js';
|
|
8
|
+
import { createAssistantsService } from '../service.js';
|
|
9
|
+
|
|
10
|
+
const closers = [];
|
|
11
|
+
afterEach(async () => { while (closers.length) await closers.pop()(); });
|
|
12
|
+
const root = () => {
|
|
13
|
+
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'yuri-weixin-'));
|
|
14
|
+
closers.push(() => fs.rmSync(directory, { recursive: true, force: true }));
|
|
15
|
+
return directory;
|
|
16
|
+
};
|
|
17
|
+
const abortable = (signal) => new Promise((_, reject) => {
|
|
18
|
+
if (signal.aborted) { reject(new WeixinError('cancelled')); return; }
|
|
19
|
+
signal.addEventListener('abort', () => reject(new WeixinError('cancelled')), { once: true });
|
|
20
|
+
});
|
|
21
|
+
const inbound = (id = '1', peer = 'owner', text = 'hello') => ({
|
|
22
|
+
message_id: id, from_user_id: peer, message_type: 1, context_token: `context-${id}`,
|
|
23
|
+
item_list: [{ type: 1, text_item: { text } }],
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
function fixture({ directory = root(), configureAPI, service: externalService, clock, env = {} } = {}) {
|
|
27
|
+
const pages = new Map();
|
|
28
|
+
const service = externalService ?? {
|
|
29
|
+
snapshot: () => ({ assistants: ['bot', 'other-bot', 'third-bot'].map((id) => ({ id, name: `Name ${id}` })) }),
|
|
30
|
+
channelPage: vi.fn((id, { afterOrdinal = 0, generation = null } = {}) => {
|
|
31
|
+
if (id === 'missing') throw Object.assign(new Error('not_found'), { code: 'not_found' });
|
|
32
|
+
const page = pages.get(id) ?? { generation: 0, messages: [] };
|
|
33
|
+
const after = generation === null || generation === page.generation ? afterOrdinal : 0;
|
|
34
|
+
const messages = page.messages.filter((message) => message.ordinal > after).slice(0, 50);
|
|
35
|
+
return { generation: page.generation, tipOrdinal: page.messages.at(-1)?.ordinal ?? 0, ordinal: messages.at(-1)?.ordinal ?? after, messages };
|
|
36
|
+
}),
|
|
37
|
+
send: vi.fn(async () => ({ admitted: true })),
|
|
38
|
+
};
|
|
39
|
+
const updates = [];
|
|
40
|
+
const api = {
|
|
41
|
+
getQRCode: vi.fn(async () => ({ qrcode: 'opaque-qr', qrcode_img_content: 'https://example.com/scan' })),
|
|
42
|
+
getQRStatus: vi.fn(async () => ({ status: 'confirmed', bot_token: 'test-token', ilink_bot_id: 'account', ilink_user_id: 'owner', baseurl: 'https://ilinkai.weixin.qq.com' })),
|
|
43
|
+
getUpdates: vi.fn(async () => ({ msgs: updates.shift() ?? [], get_updates_buf: 'next-cursor' })),
|
|
44
|
+
sendText: vi.fn(async () => ({ ret: 0 })),
|
|
45
|
+
getConfig: vi.fn(async () => ({ ret: 0, typing_ticket: 'test-ticket' })),
|
|
46
|
+
sendTyping: vi.fn(async () => ({})),
|
|
47
|
+
};
|
|
48
|
+
configureAPI?.(api);
|
|
49
|
+
const runtime = createWeixinRuntime({ directory, service, api, env, intervalMs: 15, ...(clock ? { clock } : {}) });
|
|
50
|
+
closers.push(() => runtime.close());
|
|
51
|
+
const bind = async (id = 'bot') => {
|
|
52
|
+
await runtime.startLogin(id, 'zh-CN');
|
|
53
|
+
await vi.waitFor(() => expect(runtime.status(id).status).toBe('connected'), { interval: 10 });
|
|
54
|
+
};
|
|
55
|
+
const reply = (id, text, ordinal = 1) => pages.set(id, { generation: 0, messages: [{ ordinal, messageID: `reply-${ordinal}`, text, cards: [], status: 'complete' }] });
|
|
56
|
+
return { directory, runtime, service, api, updates, pages, bind, reply };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
describe('Weixin Host runtime', () => {
|
|
60
|
+
it.each([
|
|
61
|
+
{ NODE_ENV: 'development' },
|
|
62
|
+
{ YURI_ELECTRON_DEV: '1' },
|
|
63
|
+
{ YURI_ELECTRON_DEV: 'true' },
|
|
64
|
+
{ NODE_ENV: 'production', YURI_WEIXIN_ENABLED: '0' },
|
|
65
|
+
{ YURI_WEIXIN_ENABLED: 'false' },
|
|
66
|
+
{ YURI_WEIXIN_ENABLED: 'invalid' },
|
|
67
|
+
])('disables channel startup and all mutations without opening storage for %j', async (env) => {
|
|
68
|
+
const directory = path.join(root(), 'must-not-open');
|
|
69
|
+
const api = { getQRCode: vi.fn(), getUpdates: vi.fn(), sendText: vi.fn(), getConfig: vi.fn(), sendTyping: vi.fn() };
|
|
70
|
+
const service = { channelPage: vi.fn(), send: vi.fn() };
|
|
71
|
+
const runtime = createWeixinRuntime({ directory, api, service, env });
|
|
72
|
+
closers.push(() => runtime.close());
|
|
73
|
+
expect(runtime.status('bot')).toEqual({ status: 'disabled', error: null });
|
|
74
|
+
for (const method of ['startLogin', 'verify', 'retry', 'disconnect', 'transfer']) {
|
|
75
|
+
expect(() => runtime[method]('bot', {})).toThrow('channel_disabled');
|
|
76
|
+
}
|
|
77
|
+
runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'turn' } });
|
|
78
|
+
await runtime.forget('bot');
|
|
79
|
+
await runtime.close();
|
|
80
|
+
expect(fs.existsSync(directory)).toBe(false);
|
|
81
|
+
for (const call of Object.values(api)) expect(call).not.toHaveBeenCalled();
|
|
82
|
+
expect(service.send).not.toHaveBeenCalled();
|
|
83
|
+
expect(service.channelPage).not.toHaveBeenCalled();
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
it('a disabled dev runtime cannot acquire the production lease or delete its binding', async () => {
|
|
87
|
+
const production = fixture();
|
|
88
|
+
await production.bind();
|
|
89
|
+
const dev = fixture({ directory: production.directory, env: { NODE_ENV: 'development' } });
|
|
90
|
+
expect(dev.runtime.status('bot')).toEqual({ status: 'disabled', error: null });
|
|
91
|
+
await dev.runtime.forget('bot');
|
|
92
|
+
await dev.runtime.close();
|
|
93
|
+
production.updates.push([inbound()]);
|
|
94
|
+
await vi.waitFor(() => expect(production.service.send).toHaveBeenCalledTimes(1));
|
|
95
|
+
expect(production.runtime.status('bot')).toEqual({ status: 'connected', error: null });
|
|
96
|
+
expect(dev.api.getUpdates).not.toHaveBeenCalled();
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
it.each(['1', 'true'])('requires an explicit %s override to enable WeChat in development', async (enabled) => {
|
|
100
|
+
const f = fixture({ env: { NODE_ENV: 'development', YURI_ELECTRON_DEV: '1', YURI_WEIXIN_ENABLED: enabled } });
|
|
101
|
+
await f.bind();
|
|
102
|
+
expect(f.runtime.status('bot').status).toBe('connected');
|
|
103
|
+
expect(f.api.getUpdates).toHaveBeenCalled();
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
it('QR binds one Bot, admits only the owner once, and sends persisted text with the latest context', async () => {
|
|
107
|
+
const f = fixture();
|
|
108
|
+
f.updates.push([inbound('1'), inbound('1'), inbound('2', 'stranger'), { ...inbound('3'), group_id: 'group' }]);
|
|
109
|
+
await f.bind();
|
|
110
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1));
|
|
111
|
+
expect(f.service.send.mock.calls[0]).toEqual(['bot', expect.objectContaining({ parts: [{ type: 'text', text: 'hello' }] })]);
|
|
112
|
+
f.reply('bot', '文字回复');
|
|
113
|
+
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(1));
|
|
114
|
+
expect(f.api.sendText.mock.calls[0][0]).toMatchObject({ peer_id: 'owner', context_token: 'context-1' });
|
|
115
|
+
expect(f.api.sendText.mock.calls[0][1].text).toBe('文字回复');
|
|
116
|
+
expect(JSON.stringify(f.runtime.status('bot'))).not.toMatch(/test-token|context-1|owner|account/);
|
|
117
|
+
expect(fs.statSync(f.directory).mode & 0o777).toBe(0o700);
|
|
118
|
+
expect(fs.statSync(path.join(f.directory, 'channel.sqlite')).mode & 0o777).toBe(0o600);
|
|
119
|
+
});
|
|
120
|
+
|
|
121
|
+
it('restarts without another scan, keeps deduplication and does not replay admitted tool work', async () => {
|
|
122
|
+
const f = fixture();
|
|
123
|
+
f.updates.push([inbound()]);
|
|
124
|
+
await f.bind();
|
|
125
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1));
|
|
126
|
+
await f.runtime.close();
|
|
127
|
+
const restarted = fixture({ directory: f.directory });
|
|
128
|
+
restarted.updates.push([inbound()]);
|
|
129
|
+
await vi.waitFor(() => expect(restarted.api.sendText).toHaveBeenCalled());
|
|
130
|
+
expect(restarted.api.getQRCode).not.toHaveBeenCalled();
|
|
131
|
+
expect(restarted.service.send).not.toHaveBeenCalled();
|
|
132
|
+
expect(restarted.api.sendText.mock.calls[0][1].text).toContain('主机已重启');
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it('does not replay old transcript rows on binding; resets the feed on transcript generation changes', async () => {
|
|
136
|
+
const f = fixture();
|
|
137
|
+
f.reply('bot', 'old', 50);
|
|
138
|
+
f.updates.push([inbound()]);
|
|
139
|
+
await f.bind();
|
|
140
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalled());
|
|
141
|
+
expect(f.api.sendText).not.toHaveBeenCalled();
|
|
142
|
+
f.pages.set('bot', { generation: 1, messages: [{ ordinal: 1, messageID: 'new', text: 'after reset', cards: [], status: 'complete' }] });
|
|
143
|
+
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(1));
|
|
144
|
+
expect(f.api.sendText.mock.calls[0][1].text).toBe('after reset');
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
it('uncertain delivery remains visible and is retried only by explicit action, even after new inbound', async () => {
|
|
148
|
+
const f = fixture({ configureAPI: (api) => api.sendText.mockRejectedValueOnce(new WeixinError('network_error', { ambiguous: true })) });
|
|
149
|
+
f.updates.push([inbound()]);
|
|
150
|
+
await f.bind();
|
|
151
|
+
f.reply('bot', 'reply');
|
|
152
|
+
await vi.waitFor(() => expect(f.runtime.status('bot').error).toBe('delivery_unknown'));
|
|
153
|
+
const originalId = f.api.sendText.mock.calls[0][1].id;
|
|
154
|
+
f.updates.push([inbound('2')]);
|
|
155
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(2));
|
|
156
|
+
expect(f.api.sendText).toHaveBeenCalledTimes(1);
|
|
157
|
+
f.runtime.retry('bot');
|
|
158
|
+
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(2));
|
|
159
|
+
expect(f.api.sendText.mock.calls[1][1].id).toBe(originalId);
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
it('shutdown cancels a hanging platform read before closing storage', async () => {
|
|
163
|
+
const f = fixture({ configureAPI: (api) => api.getUpdates.mockImplementation((_binding, signal) => abortable(signal)) });
|
|
164
|
+
await f.bind();
|
|
165
|
+
await vi.waitFor(() => expect(f.api.getUpdates).toHaveBeenCalled());
|
|
166
|
+
const signal = f.api.getUpdates.mock.calls[0][1];
|
|
167
|
+
await f.runtime.close();
|
|
168
|
+
expect(signal.aborted).toBe(true);
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
it('stale QR confirmation after disconnect cannot restore credentials or start polling', async () => {
|
|
172
|
+
let confirm;
|
|
173
|
+
const confirmed = new Promise((resolve) => { confirm = resolve; });
|
|
174
|
+
const f = fixture({ configureAPI: (api) => api.getQRStatus.mockImplementation(() => confirmed) });
|
|
175
|
+
expect((await f.runtime.startLogin('bot')).status).toBe('waiting');
|
|
176
|
+
await f.runtime.disconnect('bot');
|
|
177
|
+
confirm({ status: 'confirmed', bot_token: 'stale', ilink_bot_id: 'account', ilink_user_id: 'owner' });
|
|
178
|
+
await Promise.resolve();
|
|
179
|
+
await Promise.resolve();
|
|
180
|
+
expect(f.runtime.status('bot').status).toBe('disconnected');
|
|
181
|
+
expect(f.api.getUpdates).not.toHaveBeenCalled();
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
it('keeps authentication failure sticky until QR authorization is renewed', async () => {
|
|
185
|
+
const f = fixture({ configureAPI: (api) => api.getUpdates.mockRejectedValue(new WeixinError('auth_expired')) });
|
|
186
|
+
await f.runtime.startLogin('bot');
|
|
187
|
+
await vi.waitFor(() => expect(f.runtime.status('bot').status).toBe('expired'));
|
|
188
|
+
await new Promise((resolve) => setTimeout(resolve, 80));
|
|
189
|
+
expect(f.api.getUpdates).toHaveBeenCalledTimes(1);
|
|
190
|
+
});
|
|
191
|
+
|
|
192
|
+
it('a late receiver network failure cannot undo authorization expiry from sending', async () => {
|
|
193
|
+
let rejectRead;
|
|
194
|
+
const f = fixture({ configureAPI: (api) => {
|
|
195
|
+
api.getUpdates.mockImplementationOnce(async () => ({ msgs: [inbound()], get_updates_buf: 'cursor' }))
|
|
196
|
+
.mockImplementation(() => new Promise((_, reject) => { rejectRead = reject; }));
|
|
197
|
+
api.sendText.mockRejectedValue(new WeixinError('auth_expired'));
|
|
198
|
+
} });
|
|
199
|
+
await f.bind();
|
|
200
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalled());
|
|
201
|
+
f.reply('bot', 'reply');
|
|
202
|
+
await vi.waitFor(() => expect(f.runtime.status('bot').status).toBe('expired'));
|
|
203
|
+
await vi.waitFor(() => expect(rejectRead).toBeTypeOf('function'));
|
|
204
|
+
rejectRead(new WeixinError('network_error'));
|
|
205
|
+
await vi.waitFor(() => expect(f.runtime.status('bot')).toMatchObject({ status: 'expired', error: 'auth_expired' }));
|
|
206
|
+
});
|
|
207
|
+
|
|
208
|
+
it('enforces account exclusivity and process ownership without stealing a live receiver', async () => {
|
|
209
|
+
const f = fixture();
|
|
210
|
+
await f.bind();
|
|
211
|
+
await f.runtime.startLogin('other-bot');
|
|
212
|
+
await vi.waitFor(() => expect(f.runtime.status('other-bot').error).toBe('account_in_use'));
|
|
213
|
+
expect(f.runtime.status('bot').status).toBe('connected');
|
|
214
|
+
const second = fixture({ directory: f.directory });
|
|
215
|
+
await expect(second.runtime.startLogin('third-bot')).rejects.toMatchObject({ code: 'channel_in_use' });
|
|
216
|
+
expect(second.api.getUpdates).not.toHaveBeenCalled();
|
|
217
|
+
await second.runtime.close();
|
|
218
|
+
expect(f.runtime.status('bot').status).toBe('connected');
|
|
219
|
+
});
|
|
220
|
+
|
|
221
|
+
it('offers an explicit local move without scanning and preserves cursor/dedup across restart', async () => {
|
|
222
|
+
const f = fixture();
|
|
223
|
+
f.updates.push([inbound('1')]);
|
|
224
|
+
await f.bind();
|
|
225
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1));
|
|
226
|
+
f.reply('other-bot', 'old target history', 50);
|
|
227
|
+
const state = f.runtime.status('other-bot');
|
|
228
|
+
expect(state).toMatchObject({ status: 'disconnected', transferSources: [{ assistantID: 'bot', name: 'Name bot' }] });
|
|
229
|
+
expect(JSON.stringify(state)).not.toMatch(/test-token|context-1|peer_id|account_id/);
|
|
230
|
+
const revision = state.transferSources[0].revision;
|
|
231
|
+
const result = await f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision, language: 'zh-CN' });
|
|
232
|
+
expect(result).toEqual({ status: 'connected', error: null });
|
|
233
|
+
expect(f.runtime.status('bot').status).toBe('disconnected');
|
|
234
|
+
expect(f.api.getQRCode).toHaveBeenCalledTimes(1);
|
|
235
|
+
f.updates.push([inbound('1'), inbound('2')]);
|
|
236
|
+
f.reply('bot', 'late old bot reply');
|
|
237
|
+
f.reply('other-bot', 'new target reply', 51);
|
|
238
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(2));
|
|
239
|
+
expect(f.service.send.mock.calls[1][0]).toBe('other-bot');
|
|
240
|
+
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(1));
|
|
241
|
+
expect(f.api.sendText.mock.calls[0][1].text).toBe('new target reply');
|
|
242
|
+
expect(f.api.getUpdates.mock.calls.find(([binding]) => binding.assistant_id === 'other-bot')[0].cursor).toBe('next-cursor');
|
|
243
|
+
await f.runtime.close();
|
|
244
|
+
const restarted = fixture({ directory: f.directory });
|
|
245
|
+
restarted.updates.push([inbound('1'), inbound('2')]);
|
|
246
|
+
await vi.waitFor(() => expect(restarted.api.getUpdates).toHaveBeenCalled());
|
|
247
|
+
expect(restarted.api.getUpdates.mock.calls[0][0].assistant_id).toBe('other-bot');
|
|
248
|
+
await new Promise((resolve) => setTimeout(resolve, 60));
|
|
249
|
+
expect(restarted.service.send).not.toHaveBeenCalled();
|
|
250
|
+
});
|
|
251
|
+
|
|
252
|
+
it('rejects stale/occupied/missing/expired transfers without changing the original connection', async () => {
|
|
253
|
+
const f = fixture();
|
|
254
|
+
await f.bind();
|
|
255
|
+
const revision = f.runtime.status('other-bot').transferSources[0].revision;
|
|
256
|
+
await expect(f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision: 'stale' })).rejects.toMatchObject({ code: 'binding_changed' });
|
|
257
|
+
await expect(f.runtime.transfer('missing', { sourceAssistantID: 'bot', revision })).rejects.toMatchObject({ code: 'not_found' });
|
|
258
|
+
await expect(f.runtime.transfer('bot', { sourceAssistantID: 'bot', revision })).rejects.toMatchObject({ code: 'validation_error' });
|
|
259
|
+
const second = fixture({ directory: f.directory });
|
|
260
|
+
await expect(second.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision })).rejects.toMatchObject({ code: 'channel_in_use' });
|
|
261
|
+
await second.runtime.close();
|
|
262
|
+
await f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision });
|
|
263
|
+
await expect(f.runtime.transfer('third-bot', { sourceAssistantID: 'bot', revision })).rejects.toMatchObject({ code: 'binding_changed' });
|
|
264
|
+
expect(f.runtime.status('other-bot').status).toBe('connected');
|
|
265
|
+
f.api.getQRStatus.mockResolvedValue({ status: 'confirmed', bot_token: 'second-token', ilink_bot_id: 'second-account', ilink_user_id: 'second-owner' });
|
|
266
|
+
await f.bind('bot');
|
|
267
|
+
const source = f.runtime.status('third-bot').transferSources.find((entry) => entry.assistantID === 'bot');
|
|
268
|
+
await expect(f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision: source.revision })).rejects.toMatchObject({ code: 'binding_changed' });
|
|
269
|
+
f.api.getUpdates.mockRejectedValue(new WeixinError('auth_expired'));
|
|
270
|
+
await vi.waitFor(() => expect(f.runtime.status('bot').status).toBe('expired'));
|
|
271
|
+
await expect(f.runtime.transfer('third-bot', { sourceAssistantID: 'bot', revision: source.revision })).rejects.toMatchObject({ code: 'binding_changed' });
|
|
272
|
+
});
|
|
273
|
+
|
|
274
|
+
it('drains old sending/typing, blocks concurrent mutations and fences a cancelled QR confirmation', async () => {
|
|
275
|
+
const f = fixture();
|
|
276
|
+
f.updates.push([inbound()]);
|
|
277
|
+
await f.bind();
|
|
278
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalled());
|
|
279
|
+
let finishRead;
|
|
280
|
+
let oldSignal;
|
|
281
|
+
f.api.getUpdates.mockImplementationOnce((_binding, signal) => {
|
|
282
|
+
oldSignal = signal;
|
|
283
|
+
return new Promise((resolve) => { finishRead = resolve; });
|
|
284
|
+
});
|
|
285
|
+
let confirm;
|
|
286
|
+
f.api.getQRStatus.mockImplementation(() => new Promise((resolve) => { confirm = resolve; }));
|
|
287
|
+
await f.runtime.startLogin('other-bot');
|
|
288
|
+
await vi.waitFor(() => expect(finishRead).toBeTypeOf('function'));
|
|
289
|
+
f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'live' } });
|
|
290
|
+
await vi.waitFor(() => expect(f.api.sendTyping).toHaveBeenCalled());
|
|
291
|
+
let finishSend;
|
|
292
|
+
f.api.sendText.mockImplementationOnce((_binding, _delivery, signal) => {
|
|
293
|
+
expect(signal.aborted).toBe(false);
|
|
294
|
+
return new Promise((resolve) => { finishSend = resolve; });
|
|
295
|
+
});
|
|
296
|
+
f.reply('bot', 'in flight');
|
|
297
|
+
await vi.waitFor(() => expect(finishSend).toBeTypeOf('function'));
|
|
298
|
+
const revision = f.runtime.status('other-bot').transferSources[0].revision;
|
|
299
|
+
const moving = f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision });
|
|
300
|
+
expect(oldSignal.aborted).toBe(true);
|
|
301
|
+
await expect(f.runtime.transfer('third-bot', { sourceAssistantID: 'bot', revision })).rejects.toMatchObject({ code: 'channel_in_use' });
|
|
302
|
+
await expect(f.runtime.disconnect('bot')).rejects.toMatchObject({ code: 'channel_in_use' });
|
|
303
|
+
expect(() => f.runtime.retry('bot')).toThrow('channel_in_use');
|
|
304
|
+
await expect(f.runtime.startLogin('other-bot')).rejects.toMatchObject({ code: 'channel_in_use' });
|
|
305
|
+
confirm({ status: 'confirmed', bot_token: 'stale-token', ilink_bot_id: 'stale-account', ilink_user_id: 'owner' });
|
|
306
|
+
finishRead({ msgs: [inbound('stale')], get_updates_buf: 'stale-cursor' });
|
|
307
|
+
finishSend({ ret: 0 });
|
|
308
|
+
await moving;
|
|
309
|
+
expect(f.api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1, 2]);
|
|
310
|
+
expect(f.service.send).toHaveBeenCalledTimes(1);
|
|
311
|
+
expect(f.runtime.status('bot').status).toBe('disconnected');
|
|
312
|
+
expect(f.runtime.status('other-bot').status).toBe('connected');
|
|
313
|
+
await expect(f.runtime.transfer('third-bot', { sourceAssistantID: 'bot', revision })).rejects.toMatchObject({ code: 'binding_changed' });
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
it('preserves and resumes the source if the target disappears while draining', async () => {
|
|
317
|
+
const f = fixture();
|
|
318
|
+
await f.bind();
|
|
319
|
+
f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'live' } });
|
|
320
|
+
await vi.waitFor(() => expect(f.api.sendTyping).toHaveBeenCalled());
|
|
321
|
+
let finishCancel;
|
|
322
|
+
f.api.sendTyping.mockImplementationOnce(() => new Promise((resolve) => { finishCancel = resolve; }));
|
|
323
|
+
const revision = f.runtime.status('other-bot').transferSources[0].revision;
|
|
324
|
+
const moving = f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision }).catch((error) => error);
|
|
325
|
+
await vi.waitFor(() => expect(finishCancel).toBeTypeOf('function'));
|
|
326
|
+
f.service.channelPage.mockImplementationOnce(() => { throw Object.assign(new Error('not_found'), { code: 'not_found' }); });
|
|
327
|
+
finishCancel({});
|
|
328
|
+
expect(await moving).toMatchObject({ code: 'not_found' });
|
|
329
|
+
expect(f.runtime.status('bot').status).toBe('connected');
|
|
330
|
+
f.updates.push([inbound('after-failure')]);
|
|
331
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledWith('bot', expect.anything()));
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
it('a failed move leaves an aborted in-flight reply explicitly retryable, never stuck or automatically resent', async () => {
|
|
335
|
+
const f = fixture();
|
|
336
|
+
f.updates.push([inbound()]);
|
|
337
|
+
await f.bind();
|
|
338
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalled());
|
|
339
|
+
f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'live' } });
|
|
340
|
+
await vi.waitFor(() => expect(f.api.sendTyping).toHaveBeenCalled());
|
|
341
|
+
let finishCancel;
|
|
342
|
+
f.api.sendTyping.mockImplementationOnce(() => new Promise((resolve) => { finishCancel = resolve; }));
|
|
343
|
+
f.api.sendText.mockImplementationOnce((_binding, _delivery, signal) => abortable(signal));
|
|
344
|
+
f.reply('bot', 'possibly delivered');
|
|
345
|
+
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(1));
|
|
346
|
+
const revision = f.runtime.status('other-bot').transferSources[0].revision;
|
|
347
|
+
const moving = f.runtime.transfer('other-bot', { sourceAssistantID: 'bot', revision }).catch((error) => error);
|
|
348
|
+
await vi.waitFor(() => expect(finishCancel).toBeTypeOf('function'));
|
|
349
|
+
f.service.channelPage.mockImplementationOnce(() => { throw Object.assign(new Error('not_found'), { code: 'not_found' }); });
|
|
350
|
+
finishCancel({});
|
|
351
|
+
expect(await moving).toMatchObject({ code: 'not_found' });
|
|
352
|
+
expect(f.runtime.status('bot')).toEqual({ status: 'connected', error: 'delivery_unknown' });
|
|
353
|
+
await new Promise((resolve) => setTimeout(resolve, 60));
|
|
354
|
+
expect(f.api.sendText).toHaveBeenCalledTimes(1);
|
|
355
|
+
f.runtime.retry('bot');
|
|
356
|
+
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(2));
|
|
357
|
+
});
|
|
358
|
+
|
|
359
|
+
it('non-text input gives a text-only reply without invoking bot tools', async () => {
|
|
360
|
+
const f = fixture();
|
|
361
|
+
f.updates.push([{ ...inbound(), item_list: [null, { type: 2, image_item: { media: {} } }] }]);
|
|
362
|
+
await f.bind();
|
|
363
|
+
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalled());
|
|
364
|
+
expect(f.api.sendText.mock.calls[0][1].text).toContain('仅支持文字');
|
|
365
|
+
expect(f.service.send).not.toHaveBeenCalled();
|
|
366
|
+
});
|
|
367
|
+
|
|
368
|
+
it('reuses the actual Yuri contact pipeline for WeChat → bot → durable reply', async () => {
|
|
369
|
+
const directory = root();
|
|
370
|
+
let runtime;
|
|
371
|
+
let finish;
|
|
372
|
+
const turnGate = new Promise((resolve) => { finish = resolve; });
|
|
373
|
+
const service = createAssistantsService({
|
|
374
|
+
dbPath: path.join(directory, 'assistants.sqlite'), dataDir: directory,
|
|
375
|
+
buildOpenCodeUrl: () => 'http://127.0.0.1:1', getOpenCodeAuthHeaders: () => ({}),
|
|
376
|
+
getAllowedRoots: () => [directory],
|
|
377
|
+
runContactTurn: async ({ userParts }) => { await turnGate; return { bubbles: [`收到:${userParts[0].text}`] }; },
|
|
378
|
+
onContactTurnEvent: (event) => runtime?.onTurnEvent(event),
|
|
379
|
+
createChatCompletion: async () => ({ choices: [] }),
|
|
380
|
+
});
|
|
381
|
+
closers.push(() => service.close());
|
|
382
|
+
const bot = service.createAssistant({ name: '微信测试', providerID: 'p', modelID: 'm' });
|
|
383
|
+
const f = fixture({ directory: path.join(directory, 'weixin'), service });
|
|
384
|
+
runtime = f.runtime;
|
|
385
|
+
f.updates.push([inbound('1', 'owner', '测试文字')]);
|
|
386
|
+
await f.bind(bot.id);
|
|
387
|
+
await vi.waitFor(() => expect(f.api.sendTyping).toHaveBeenCalledWith(
|
|
388
|
+
expect.objectContaining({ assistant_id: bot.id, peer_id: 'owner' }), 'test-ticket', 1, expect.any(AbortSignal),
|
|
389
|
+
));
|
|
390
|
+
finish();
|
|
391
|
+
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalled(), { timeout: 4000 });
|
|
392
|
+
expect(f.api.sendText.mock.calls[0][1].text).toBe('收到:测试文字');
|
|
393
|
+
expect(service.contactMessages(bot.id, { limit: 20 }).messages.some((message) => message.text === '测试文字')).toBe(true);
|
|
394
|
+
await vi.waitFor(() => expect(f.api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1, 2]));
|
|
395
|
+
});
|
|
396
|
+
|
|
397
|
+
it.each(['error', 'cancelled'])('clears typing on a live %s terminal event without sending a placeholder text', async (status) => {
|
|
398
|
+
const f = fixture();
|
|
399
|
+
await f.bind();
|
|
400
|
+
f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'turn' } });
|
|
401
|
+
await vi.waitFor(() => expect(f.api.sendTyping).toHaveBeenCalledTimes(1));
|
|
402
|
+
f.runtime.onTurnEvent({ type: 'yuri:contact-turn-end', properties: { assistantID: 'bot', turnID: 'turn', status } });
|
|
403
|
+
await vi.waitFor(() => expect(f.api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1, 2]));
|
|
404
|
+
expect(f.api.sendText).not.toHaveBeenCalled();
|
|
405
|
+
});
|
|
406
|
+
|
|
407
|
+
it('disconnect waits for typing cancellation before forgetting the binding', async () => {
|
|
408
|
+
const f = fixture();
|
|
409
|
+
await f.bind();
|
|
410
|
+
f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'turn' } });
|
|
411
|
+
await vi.waitFor(() => expect(f.api.sendTyping).toHaveBeenCalledTimes(1));
|
|
412
|
+
let finishCancel;
|
|
413
|
+
f.api.sendTyping.mockImplementationOnce(() => new Promise((resolve) => { finishCancel = resolve; }));
|
|
414
|
+
const disconnected = f.runtime.disconnect('bot');
|
|
415
|
+
await vi.waitFor(() => expect(finishCancel).toBeTypeOf('function'));
|
|
416
|
+
f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'late' } });
|
|
417
|
+
finishCancel({});
|
|
418
|
+
expect(await disconnected).toMatchObject({ status: 'disconnected' });
|
|
419
|
+
expect(f.api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1, 2]);
|
|
420
|
+
});
|
|
421
|
+
|
|
422
|
+
it('typing API failure cannot block contact admission, replies or expose optional presence errors', async () => {
|
|
423
|
+
const f = fixture({ configureAPI: (api) => api.getConfig.mockRejectedValue(new Error('private-ticket-error')) });
|
|
424
|
+
f.updates.push([inbound()]);
|
|
425
|
+
await f.bind();
|
|
426
|
+
f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'turn' } });
|
|
427
|
+
await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1));
|
|
428
|
+
f.reply('bot', 'reply');
|
|
429
|
+
await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(1));
|
|
430
|
+
expect(f.api.sendTyping).not.toHaveBeenCalled();
|
|
431
|
+
expect(f.runtime.status('bot')).toEqual({ status: 'connected', error: null });
|
|
432
|
+
});
|
|
433
|
+
|
|
434
|
+
it('Host shutdown awaits an independent typing cancellation before closing storage', async () => {
|
|
435
|
+
const f = fixture();
|
|
436
|
+
await f.bind();
|
|
437
|
+
f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'turn' } });
|
|
438
|
+
await vi.waitFor(() => expect(f.api.sendTyping).toHaveBeenCalledTimes(1));
|
|
439
|
+
let finishCancel;
|
|
440
|
+
f.api.sendTyping.mockImplementationOnce(() => new Promise((resolve) => { finishCancel = resolve; }));
|
|
441
|
+
let stopped = false;
|
|
442
|
+
const closing = f.runtime.close().then(() => { stopped = true; });
|
|
443
|
+
await vi.waitFor(() => expect(finishCancel).toBeTypeOf('function'));
|
|
444
|
+
expect(stopped).toBe(false);
|
|
445
|
+
expect(f.api.sendTyping.mock.calls[0][3].aborted).toBe(true);
|
|
446
|
+
expect(f.api.sendTyping.mock.calls[1][3]).toBeUndefined();
|
|
447
|
+
finishCancel({});
|
|
448
|
+
await closing;
|
|
449
|
+
expect(stopped).toBe(true);
|
|
450
|
+
});
|
|
451
|
+
});
|
|
452
|
+
|
|
453
|
+
describe('Weixin durable store', () => {
|
|
454
|
+
it('moves atomically, preserves credentials/cursor/receipt IDs, drops old work, and rolls back failed writes', () => {
|
|
455
|
+
const store = createWeixinStore(root());
|
|
456
|
+
closers.push(() => store.close());
|
|
457
|
+
const initial = { token: 'test-token', peer_id: 'owner', base_url: 'https://ilinkai.weixin.qq.com', language: 'en', generation: 0, ordinal: 0, updated_at: 1 };
|
|
458
|
+
const a = store.bind({ ...initial, assistant_id: 'a', account_id: 'account-a' });
|
|
459
|
+
store.accept(a, 'cursor', [{ id: 'done', text: 'old', context: 'ctx' }, { id: 'pending', text: 'pending' }]);
|
|
460
|
+
store.markInbox('done', 'admitted');
|
|
461
|
+
store.enqueue(a.epoch, 'old-delivery', 'old reply');
|
|
462
|
+
const move = { sourceAssistantID: 'a', expectedEpoch: a.epoch, assistantID: 'b', generation: 5, ordinal: 42, language: 'zh-CN', updatedAt: 2 };
|
|
463
|
+
expect(() => store.transfer({ ...move, ordinal: null })).toThrow();
|
|
464
|
+
expect(store.get('a').epoch).toBe(a.epoch);
|
|
465
|
+
expect(store.pending(a.epoch)).toHaveLength(1);
|
|
466
|
+
expect(store.nextDelivery(a.epoch).text).toBe('old reply');
|
|
467
|
+
const b = store.transfer(move);
|
|
468
|
+
expect(store.get('a')).toBeNull();
|
|
469
|
+
expect(b).toMatchObject({ ...initial, assistant_id: 'b', language: 'zh-CN', generation: 5, ordinal: 42, updated_at: 2, cursor: 'cursor', context_token: 'ctx' });
|
|
470
|
+
expect(b.epoch).not.toBe(a.epoch);
|
|
471
|
+
expect(store.nextDelivery(b.epoch)).toBeUndefined();
|
|
472
|
+
store.accept(b, 'next', [{ id: 'done', text: 'replay' }, { id: 'pending', text: 'replay' }, { id: 'fresh', text: 'new' }]);
|
|
473
|
+
expect(store.pending(b.epoch).map((row) => row.id)).toEqual(['fresh']);
|
|
474
|
+
store.accept(a, 'stale', [{ id: 'stale', text: 'stale' }]);
|
|
475
|
+
expect(store.get('b').cursor).toBe('next');
|
|
476
|
+
expect(() => store.transfer(move)).toThrow('binding_changed');
|
|
477
|
+
store.bind({ ...initial, assistant_id: 'c', account_id: 'account-c' });
|
|
478
|
+
expect(() => store.transfer({ ...move, sourceAssistantID: 'b', expectedEpoch: b.epoch, assistantID: 'c' })).toThrow('binding_changed');
|
|
479
|
+
expect(store.get('b').epoch).toBe(b.epoch);
|
|
480
|
+
expect(store.get('c').account_id).toBe('account-c');
|
|
481
|
+
});
|
|
482
|
+
|
|
483
|
+
it('rolls back a conflicting rebind, persists cursor/receipt together, and fences old epochs', () => {
|
|
484
|
+
const store = createWeixinStore(root());
|
|
485
|
+
closers.push(() => store.close());
|
|
486
|
+
const initial = { token: 'test-token', peer_id: 'owner', base_url: 'https://ilinkai.weixin.qq.com', language: 'en', generation: 0, ordinal: 0, updated_at: 1 };
|
|
487
|
+
const a = store.bind({ ...initial, assistant_id: 'a', account_id: 'account-a' });
|
|
488
|
+
store.bind({ ...initial, assistant_id: 'b', account_id: 'account-b' });
|
|
489
|
+
expect(() => store.bind({ ...initial, assistant_id: 'a', account_id: 'account-b' })).toThrow('account_in_use');
|
|
490
|
+
expect(store.get('a').epoch).toBe(a.epoch);
|
|
491
|
+
store.accept(a, 'cursor-1', [{ id: 'one', text: 'hello', context: 'ctx' }]);
|
|
492
|
+
store.accept(a, 'cursor-2', [{ id: 'one', text: 'hello', context: 'ctx' }]);
|
|
493
|
+
expect(store.pending(a.epoch)).toHaveLength(1);
|
|
494
|
+
expect(store.get('a')).toMatchObject({ cursor: 'cursor-2', context_token: 'ctx' });
|
|
495
|
+
store.unlink('a');
|
|
496
|
+
store.accept(a, 'stale', [{ id: 'stale', text: 'stale' }]);
|
|
497
|
+
expect(store.pending(a.epoch)).toHaveLength(0);
|
|
498
|
+
expect(store.get('a')).toBeNull();
|
|
499
|
+
});
|
|
500
|
+
});
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { createRequire } from 'node:module';
|
|
4
|
+
import { randomUUID } from 'node:crypto';
|
|
5
|
+
|
|
6
|
+
const require = createRequire(import.meta.url);
|
|
7
|
+
|
|
8
|
+
export function createWeixinStore(directory) {
|
|
9
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
10
|
+
fs.chmodSync(directory, 0o700);
|
|
11
|
+
const filename = path.join(directory, 'channel.sqlite');
|
|
12
|
+
// Private directory protects the journal too. Do not use the shared settings
|
|
13
|
+
// response, contact transcript or model context as a credential store.
|
|
14
|
+
const db = new (require('better-sqlite3'))(filename);
|
|
15
|
+
fs.chmodSync(filename, 0o600);
|
|
16
|
+
db.pragma('busy_timeout = 5000');
|
|
17
|
+
db.pragma('secure_delete = ON');
|
|
18
|
+
db.exec(`
|
|
19
|
+
CREATE TABLE IF NOT EXISTS binding (
|
|
20
|
+
assistant_id TEXT PRIMARY KEY, epoch TEXT NOT NULL, account_id TEXT NOT NULL UNIQUE,
|
|
21
|
+
peer_id TEXT NOT NULL, token TEXT NOT NULL, base_url TEXT NOT NULL,
|
|
22
|
+
language TEXT NOT NULL, cursor TEXT NOT NULL DEFAULT '', context_token TEXT NOT NULL DEFAULT '',
|
|
23
|
+
generation INTEGER NOT NULL, ordinal INTEGER NOT NULL, status TEXT NOT NULL DEFAULT 'connected',
|
|
24
|
+
error TEXT, updated_at INTEGER NOT NULL
|
|
25
|
+
);
|
|
26
|
+
CREATE TABLE IF NOT EXISTS inbox (
|
|
27
|
+
id TEXT PRIMARY KEY, epoch TEXT NOT NULL, text TEXT NOT NULL, state TEXT NOT NULL DEFAULT 'pending'
|
|
28
|
+
);
|
|
29
|
+
CREATE INDEX IF NOT EXISTS inbox_pending ON inbox(epoch, state);
|
|
30
|
+
CREATE TABLE IF NOT EXISTS outbox (
|
|
31
|
+
id TEXT NOT NULL UNIQUE, epoch TEXT NOT NULL, text TEXT NOT NULL, state TEXT NOT NULL DEFAULT 'pending',
|
|
32
|
+
sequence INTEGER PRIMARY KEY AUTOINCREMENT
|
|
33
|
+
);
|
|
34
|
+
`);
|
|
35
|
+
db.exec(`CREATE INDEX IF NOT EXISTS outbox_pending ON outbox(epoch, state, sequence);
|
|
36
|
+
CREATE TABLE IF NOT EXISTS lease (id INTEGER PRIMARY KEY CHECK(id=1), owner TEXT NOT NULL, expires_at INTEGER NOT NULL);`);
|
|
37
|
+
const get = (assistantID) => db.prepare('SELECT * FROM binding WHERE assistant_id=?').get(assistantID) ?? null;
|
|
38
|
+
const patch = (epoch, values) => {
|
|
39
|
+
const allowed = new Set(['cursor', 'context_token', 'generation', 'ordinal', 'status', 'error', 'updated_at']);
|
|
40
|
+
const keys = Object.keys(values).filter((key) => allowed.has(key));
|
|
41
|
+
if (!keys.length) return;
|
|
42
|
+
db.prepare(`UPDATE binding SET ${keys.map((key) => `${key}=?`).join(',')} WHERE epoch=?`).run(...keys.map((key) => values[key]), epoch);
|
|
43
|
+
};
|
|
44
|
+
const enqueue = (epoch, id, text) => db.prepare('INSERT OR IGNORE INTO outbox(id,epoch,text) VALUES (?,?,?)').run(id, epoch, text);
|
|
45
|
+
const unlink = db.transaction((assistantID) => {
|
|
46
|
+
const binding = get(assistantID);
|
|
47
|
+
if (!binding) return;
|
|
48
|
+
db.prepare('DELETE FROM inbox WHERE epoch=?').run(binding.epoch);
|
|
49
|
+
db.prepare('DELETE FROM outbox WHERE epoch=?').run(binding.epoch);
|
|
50
|
+
db.prepare('DELETE FROM binding WHERE assistant_id=?').run(assistantID);
|
|
51
|
+
});
|
|
52
|
+
return {
|
|
53
|
+
get, patch, enqueue, unlink,
|
|
54
|
+
list: () => db.prepare('SELECT * FROM binding ORDER BY assistant_id').all(),
|
|
55
|
+
bind: db.transaction((value) => {
|
|
56
|
+
const existing = db.prepare('SELECT assistant_id FROM binding WHERE account_id=?').get(value.account_id);
|
|
57
|
+
if (existing && existing.assistant_id !== value.assistant_id) { const error = new Error('account_in_use'); error.code = 'account_in_use'; throw error; }
|
|
58
|
+
unlink(value.assistant_id);
|
|
59
|
+
db.prepare(`INSERT INTO binding(assistant_id,epoch,account_id,peer_id,token,base_url,language,generation,ordinal,updated_at)
|
|
60
|
+
VALUES (@assistant_id,@epoch,@account_id,@peer_id,@token,@base_url,@language,@generation,@ordinal,@updated_at)`)
|
|
61
|
+
.run({ ...value, epoch: randomUUID() });
|
|
62
|
+
return get(value.assistant_id);
|
|
63
|
+
}),
|
|
64
|
+
transfer: db.transaction(({ sourceAssistantID, expectedEpoch, assistantID, generation, ordinal, language, updatedAt }) => {
|
|
65
|
+
const source = get(sourceAssistantID);
|
|
66
|
+
if (!source || source.epoch !== expectedEpoch || source.status === 'expired' || get(assistantID)) {
|
|
67
|
+
const error = new Error('binding_changed'); error.code = 'binding_changed'; throw error;
|
|
68
|
+
}
|
|
69
|
+
const epoch = randomUUID();
|
|
70
|
+
// Keep receipt IDs across moves so a replay cannot execute tools in the new Bot.
|
|
71
|
+
db.prepare("UPDATE inbox SET epoch=?,state='done',text='' WHERE epoch=?").run(epoch, source.epoch);
|
|
72
|
+
db.prepare('DELETE FROM outbox WHERE epoch=?').run(source.epoch);
|
|
73
|
+
db.prepare(`UPDATE binding SET assistant_id=?,epoch=?,generation=?,ordinal=?,language=?,updated_at=?,status='connected',error=NULL WHERE epoch=?`)
|
|
74
|
+
.run(assistantID, epoch, generation, ordinal, language, updatedAt, source.epoch);
|
|
75
|
+
return get(assistantID);
|
|
76
|
+
}),
|
|
77
|
+
accept: db.transaction((binding, cursor, messages) => {
|
|
78
|
+
if (get(binding.assistant_id)?.epoch !== binding.epoch) return;
|
|
79
|
+
for (const message of messages) {
|
|
80
|
+
db.prepare('INSERT OR IGNORE INTO inbox(id,epoch,text) VALUES (?,?,?)').run(message.id, binding.epoch, message.text);
|
|
81
|
+
if (message.context) patch(binding.epoch, { context_token: message.context });
|
|
82
|
+
}
|
|
83
|
+
patch(binding.epoch, { cursor });
|
|
84
|
+
}),
|
|
85
|
+
pending: (epoch) => db.prepare("SELECT * FROM inbox WHERE epoch=? AND state='pending' ORDER BY rowid LIMIT 20").all(epoch),
|
|
86
|
+
backlog: (epoch) => db.prepare("SELECT COUNT(*) AS count FROM inbox WHERE epoch=? AND state IN ('pending','admitted')").get(epoch).count,
|
|
87
|
+
markInbox: (id, state) => db.prepare('UPDATE inbox SET state=? WHERE id=?').run(state, id),
|
|
88
|
+
finishTurn: (id) => db.prepare("UPDATE inbox SET state='done',text='' WHERE id=?").run(id),
|
|
89
|
+
recover: db.transaction((epoch, text) => {
|
|
90
|
+
for (const row of db.prepare("SELECT id FROM inbox WHERE epoch=? AND state='admitted'").all(epoch)) {
|
|
91
|
+
enqueue(epoch, `${row.id}:interrupted`, text);
|
|
92
|
+
db.prepare("UPDATE inbox SET state='done',text='' WHERE id=?").run(row.id);
|
|
93
|
+
}
|
|
94
|
+
// A process exit during HTTP send cannot prove whether Weixin accepted it.
|
|
95
|
+
db.prepare("UPDATE outbox SET state='unknown' WHERE epoch=? AND state='sending'").run(epoch);
|
|
96
|
+
}),
|
|
97
|
+
collect: db.transaction((binding, page, deliveries) => {
|
|
98
|
+
if (get(binding.assistant_id)?.epoch !== binding.epoch) return;
|
|
99
|
+
if (binding.generation !== page.generation) db.prepare('DELETE FROM outbox WHERE epoch=?').run(binding.epoch);
|
|
100
|
+
for (const delivery of deliveries) enqueue(binding.epoch, delivery.id, delivery.text);
|
|
101
|
+
patch(binding.epoch, { generation: page.generation, ordinal: page.ordinal });
|
|
102
|
+
}),
|
|
103
|
+
nextDelivery: (epoch) => db.prepare("SELECT * FROM outbox WHERE epoch=? AND state!='sent' ORDER BY sequence LIMIT 1").get(epoch),
|
|
104
|
+
markDelivery: (id, state) => db.prepare('UPDATE outbox SET state=? WHERE id=?').run(state, id),
|
|
105
|
+
sent: (id) => db.prepare("UPDATE outbox SET state='sent',text='' WHERE id=?").run(id),
|
|
106
|
+
retry: (epoch) => db.prepare("UPDATE outbox SET state='pending' WHERE epoch=? AND state IN ('unknown','blocked')").run(epoch),
|
|
107
|
+
unblock: (epoch) => db.prepare("UPDATE outbox SET state='pending' WHERE epoch=? AND state='blocked'").run(epoch),
|
|
108
|
+
hasUnknown: (epoch) => Boolean(db.prepare("SELECT 1 FROM outbox WHERE epoch=? AND state='unknown' LIMIT 1").get(epoch)),
|
|
109
|
+
acquire: (owner, now) => Boolean(db.prepare(`INSERT INTO lease(id,owner,expires_at) VALUES (1,?,?)
|
|
110
|
+
ON CONFLICT(id) DO UPDATE SET owner=excluded.owner,expires_at=excluded.expires_at
|
|
111
|
+
WHERE lease.owner=excluded.owner OR lease.expires_at<=?`).run(owner, now + 60_000, now).changes),
|
|
112
|
+
owns: (owner, now) => Boolean(db.prepare('SELECT 1 FROM lease WHERE id=1 AND owner=? AND expires_at>?').get(owner, now)),
|
|
113
|
+
release: (owner) => db.prepare('DELETE FROM lease WHERE owner=?').run(owner),
|
|
114
|
+
close: () => db.close(),
|
|
115
|
+
};
|
|
116
|
+
}
|