@yuriai/web 0.2.27-beta.2 → 0.2.27-beta.3

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.
Files changed (94) hide show
  1. package/dist/assets/{AgentAvatar-BW4Zg8bo.js → AgentAvatar-kIN4sZMz.js} +1 -1
  2. package/dist/assets/{AssistantView-Cl0ZeXwr.js → AssistantView-C2KQZ6a4.js} +3 -3
  3. package/dist/assets/{DiagramView-D6wdXRzu.js → DiagramView-DK0iXm9b.js} +1 -1
  4. package/dist/assets/{FadeInOnReveal-gOsILpSk.js → FadeInOnReveal-BJA9Za3T.js} +1 -1
  5. package/dist/assets/{GuiPluginSurface-DOZAQKX0.js → GuiPluginSurface-Dz2CdSUA.js} +1 -1
  6. package/dist/assets/{GuiPluginWindow-tGvc4_0g.js → GuiPluginWindow-l4FYY6S-.js} +1 -1
  7. package/dist/assets/{Icon-DvUDsV1z.js → Icon-BP1sfnHn.js} +1 -1
  8. package/dist/assets/{ImageLoadingPlaceholder-9xYbKqtf.js → ImageLoadingPlaceholder-DCWssLJG.js} +1 -1
  9. package/dist/assets/{LoadingImage-CiOcKPfb.js → LoadingImage-C_Hryaqe.js} +1 -1
  10. package/dist/assets/{MarkdownRenderer-DZkP4UNr.js → MarkdownRenderer-Y6uQXIFH.js} +2 -2
  11. package/dist/assets/{MarkdownRendererImpl-BXzPUEEo.js → MarkdownRendererImpl-qKp1tQrP.js} +1 -1
  12. package/dist/assets/{MarkstreamRendererImpl-B-NWd069.js → MarkstreamRendererImpl-B_JTod0h.js} +1 -1
  13. package/dist/assets/{MobileDetailNavigation-5U28hfYf.js → MobileDetailNavigation-B3rUx5Ve.js} +1 -1
  14. package/dist/assets/{MobileResizableSheet-ZL-zPa3W.js → MobileResizableSheet-F1zSUD1S.js} +1 -1
  15. package/dist/assets/{MobileShareBridge-JSH_Y8Ps.js → MobileShareBridge-F70fkIfS.js} +1 -1
  16. package/dist/assets/{MobileTabPageHeader-Bj9MIS38.js → MobileTabPageHeader-0esgB2TO.js} +1 -1
  17. package/dist/assets/{MultiRunWindow-ZPz62Aqg.js → MultiRunWindow-D8m6R_4x.js} +1 -1
  18. package/dist/assets/{OnboardingScreen-BQNoy9o1.js → OnboardingScreen-BAsPVV_W.js} +1 -1
  19. package/dist/assets/{OverlayScrollbar-BwCFalSw.js → OverlayScrollbar-wiRM4AGj.js} +1 -1
  20. package/dist/assets/{SettingsView-B17qt8dh.js → SettingsView-izzjIckv.js} +15 -15
  21. package/dist/assets/{SettingsWindow-CIFNHb-F.js → SettingsWindow-CSuHDq_c.js} +1 -1
  22. package/dist/assets/{TerminalView-BZZ8LW4d.js → TerminalView-BtM5-BVx.js} +1 -1
  23. package/dist/assets/{ToolOutputDialog-BKuVpgEu.js → ToolOutputDialog-DJs9w1_J.js} +1 -1
  24. package/dist/assets/{YuriLogo-C1Ty-RTB.js → YuriLogo-aBS6wlYU.js} +1 -1
  25. package/dist/assets/{appThemeRegistry-DqGuzMaH.js → appThemeRegistry-BY5rY9-W.js} +1 -1
  26. package/dist/assets/{button-DuHjvKJJ.js → button-Dt6Ygbc7.js} +1 -1
  27. package/dist/assets/{capgoAdapter-B-tddboe.js → capgoAdapter-MQ1qpf60.js} +1 -1
  28. package/dist/assets/{collapsible-B8eL5nLo.js → collapsible-Dm7OHk7m.js} +1 -1
  29. package/dist/assets/{diagram-ChoQDKzy.js → diagram-DWZaG3_v.js} +1 -1
  30. package/dist/assets/{dialog-CVhqZux0.js → dialog-CjQeHVOc.js} +1 -1
  31. package/dist/assets/{dropdown-menu.styles-DGvlOX_5.js → dropdown-menu.styles-PdxueXzN.js} +1 -1
  32. package/dist/assets/{es-B8sAsuo5.js → es-BjI1GHJ5.js} +1 -1
  33. package/dist/assets/{fileMentionTouchSelection-Dd-iSIe2.js → fileMentionTouchSelection-D7QtVxjI.js} +1 -1
  34. package/dist/assets/{fr-BPpW8T-l.js → fr-Bs7ndHkb.js} +1 -1
  35. package/dist/assets/{gitApi-D43bAQh1.js → gitApi-BxQmH8Wg.js} +1 -1
  36. package/dist/assets/{input-E_oYiXZT.js → input-Dq4usRDa.js} +1 -1
  37. package/dist/assets/{insertionBoundaries-BQjiZAmZ.js → insertionBoundaries-CKQL85zy.js} +1 -1
  38. package/dist/assets/{ja-DEoFDi7P.js → ja-DkdV26EW.js} +1 -1
  39. package/dist/assets/{ko-B45xHN6I.js → ko-B0qoC5da.js} +1 -1
  40. package/dist/assets/{main-C6MDfyZy.js → main-CNwFqQQd.js} +2 -2
  41. package/dist/assets/{main-u5iQScJs.js → main-DPhcXanT.js} +4 -4
  42. package/dist/assets/{markdownHeightCache-heNXHdzb.js → markdownHeightCache-C1u0bWDL.js} +1 -1
  43. package/dist/assets/{mcpQueries-BqKVe4Su.js → mcpQueries-D2IxTr4k.js} +1 -1
  44. package/dist/assets/{miniChat-Dhfn71Re.js → miniChat-CF2vb25D.js} +2 -2
  45. package/dist/assets/{mobile-DSVdPfcG.js → mobile-C24qSj44.js} +2 -2
  46. package/dist/assets/{mobileBackNavigation-DHxFQ7SY.js → mobileBackNavigation-vpCg1S7j.js} +1 -1
  47. package/dist/assets/{multirun-CPOzaEQj.js → multirun-DT-dFXud.js} +1 -1
  48. package/dist/assets/{native-config-oauL2ekt.js → native-config-ncdoz9Wl.js} +1 -1
  49. package/dist/assets/{pl-Bm3Je_AX.js → pl-D27Y_GBs.js} +1 -1
  50. package/dist/assets/{projectMeta-YDMdD3AP.js → projectMeta-CG8NLahh.js} +1 -1
  51. package/dist/assets/{pt-BR-BiQwFHhL.js → pt-BR-DbocEu4b.js} +1 -1
  52. package/dist/assets/{readiness-BveVUOIb.js → readiness-DSJs_3v4.js} +1 -1
  53. package/dist/assets/{renderElectronMiniChatApp-NC8iRPyy.js → renderElectronMiniChatApp-ChZCxxH6.js} +2 -2
  54. package/dist/assets/{renderMobileApp-D5ai1i6y.js → renderMobileApp-CRv3Il6P.js} +4 -4
  55. package/dist/assets/{runtimeConfig-BpcgdIV9.js → runtimeConfig-CZrflo-r.js} +1 -1
  56. package/dist/assets/{runtimeEndpointReset-ByKa_0nu.js → runtimeEndpointReset-Cx3RE97b.js} +3 -3
  57. package/dist/assets/{scheduledTaskNavigation-CZfAnPD-.js → scheduledTaskNavigation-rhgnZaaj.js} +1 -1
  58. package/dist/assets/{sessionChangeSummary-D6NlE_5k.js → sessionChangeSummary-CVUA1AFw.js} +1 -1
  59. package/dist/assets/{sessionLookup-C70EoX-V.js → sessionLookup-C3_vQwLe.js} +1 -1
  60. package/dist/assets/{sortable-tabs-strip-aKussO2c.js → sortable-tabs-strip-C1QmKFdb.js} +1 -1
  61. package/dist/assets/{speechSettingsQueries-B6qf-mCh.js → speechSettingsQueries-BSQ-2JTv.js} +1 -1
  62. package/dist/assets/{store-BeD2keas.js → store-DvN2L3vf.js} +2 -2
  63. package/dist/assets/{textarea-DmKaqHSb.js → textarea-vtIQM2iP.js} +1 -1
  64. package/dist/assets/{tooltip-DUKu4nC6.js → tooltip-BpG2mxrT.js} +1 -1
  65. package/dist/assets/{types-DRTMRW4R.js → types-CNTgeeM1.js} +1 -1
  66. package/dist/assets/{uk-CYZXWdd7.js → uk-B_JwElWz.js} +1 -1
  67. package/dist/assets/{useAppFontEffects-BiQf6tgZ.js → useAppFontEffects-BguV1Hfa.js} +5 -5
  68. package/dist/assets/{useDesktopWindowControlsLayout-DJxNmCWb.js → useDesktopWindowControlsLayout-CwgkVw9f.js} +1 -1
  69. package/dist/assets/{useEffectiveDirectory-B8q00InF.js → useEffectiveDirectory-Ci6Z13kj.js} +1 -1
  70. package/dist/assets/{useMobileNavigationStore-Bn4SaalY.js → useMobileNavigationStore-TCj7ZnhV.js} +6 -6
  71. package/dist/assets/{useWorkerHighlightedLines-B6lWNk01.js → useWorkerHighlightedLines-HKhuYGSj.js} +1 -1
  72. package/dist/assets/{zh-CN-CMLBHipA.js → zh-CN-DhFFdHQu.js} +1 -1
  73. package/dist/assets/{zh-TW-CJlmnnhK.js → zh-TW-BvehppXO.js} +1 -1
  74. package/dist/index.html +5 -5
  75. package/dist/mini-chat.html +5 -5
  76. package/dist/mobile.html +5 -5
  77. package/package.json +1 -1
  78. package/server/lib/assistants/DOCUMENTATION.md +10 -0
  79. package/server/lib/assistants/contact-store.js +16 -0
  80. package/server/lib/assistants/contact-store.test.js +19 -0
  81. package/server/lib/assistants/routes.js +25 -3
  82. package/server/lib/assistants/service.js +7 -1
  83. package/server/lib/assistants/weixin/DOCUMENTATION.md +142 -0
  84. package/server/lib/assistants/weixin/api.js +113 -0
  85. package/server/lib/assistants/weixin/api.test.js +80 -0
  86. package/server/lib/assistants/weixin/routes.js +23 -0
  87. package/server/lib/assistants/weixin/routes.test.js +41 -0
  88. package/server/lib/assistants/weixin/runtime.js +357 -0
  89. package/server/lib/assistants/weixin/runtime.test.js +286 -0
  90. package/server/lib/assistants/weixin/store.js +103 -0
  91. package/server/lib/assistants/weixin/typing.js +88 -0
  92. package/server/lib/assistants/weixin/typing.test.js +185 -0
  93. package/server/lib/opencode/shutdown-runtime.js +1 -1
  94. package/server/lib/opencode/shutdown-runtime.test.js +12 -0
@@ -0,0 +1,286 @@
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 } = {}) {
27
+ const pages = new Map();
28
+ const service = externalService ?? {
29
+ channelPage: vi.fn((id, { afterOrdinal = 0, generation = null } = {}) => {
30
+ if (id === 'missing') throw Object.assign(new Error('not_found'), { code: 'not_found' });
31
+ const page = pages.get(id) ?? { generation: 0, messages: [] };
32
+ const after = generation === null || generation === page.generation ? afterOrdinal : 0;
33
+ const messages = page.messages.filter((message) => message.ordinal > after).slice(0, 50);
34
+ return { generation: page.generation, tipOrdinal: page.messages.at(-1)?.ordinal ?? 0, ordinal: messages.at(-1)?.ordinal ?? after, messages };
35
+ }),
36
+ send: vi.fn(async () => ({ admitted: true })),
37
+ };
38
+ const updates = [];
39
+ const api = {
40
+ getQRCode: vi.fn(async () => ({ qrcode: 'opaque-qr', qrcode_img_content: 'https://example.com/scan' })),
41
+ getQRStatus: vi.fn(async () => ({ status: 'confirmed', bot_token: 'test-token', ilink_bot_id: 'account', ilink_user_id: 'owner', baseurl: 'https://ilinkai.weixin.qq.com' })),
42
+ getUpdates: vi.fn(async () => ({ msgs: updates.shift() ?? [], get_updates_buf: 'next-cursor' })),
43
+ sendText: vi.fn(async () => ({ ret: 0 })),
44
+ getConfig: vi.fn(async () => ({ ret: 0, typing_ticket: 'test-ticket' })),
45
+ sendTyping: vi.fn(async () => ({})),
46
+ };
47
+ configureAPI?.(api);
48
+ const runtime = createWeixinRuntime({ directory, service, api, intervalMs: 15, ...(clock ? { clock } : {}) });
49
+ closers.push(() => runtime.close());
50
+ const bind = async (id = 'bot') => {
51
+ await runtime.startLogin(id, 'zh-CN');
52
+ await vi.waitFor(() => expect(runtime.status(id).status).toBe('connected'), { interval: 10 });
53
+ };
54
+ const reply = (id, text, ordinal = 1) => pages.set(id, { generation: 0, messages: [{ ordinal, messageID: `reply-${ordinal}`, text, cards: [], status: 'complete' }] });
55
+ return { directory, runtime, service, api, updates, pages, bind, reply };
56
+ }
57
+
58
+ describe('Weixin Host runtime', () => {
59
+ it('QR binds one Bot, admits only the owner once, and sends persisted text with the latest context', async () => {
60
+ const f = fixture();
61
+ f.updates.push([inbound('1'), inbound('1'), inbound('2', 'stranger'), { ...inbound('3'), group_id: 'group' }]);
62
+ await f.bind();
63
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1));
64
+ expect(f.service.send.mock.calls[0]).toEqual(['bot', expect.objectContaining({ parts: [{ type: 'text', text: 'hello' }] })]);
65
+ f.reply('bot', '文字回复');
66
+ await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(1));
67
+ expect(f.api.sendText.mock.calls[0][0]).toMatchObject({ peer_id: 'owner', context_token: 'context-1' });
68
+ expect(f.api.sendText.mock.calls[0][1].text).toBe('文字回复');
69
+ expect(JSON.stringify(f.runtime.status('bot'))).not.toMatch(/test-token|context-1|owner|account/);
70
+ expect(fs.statSync(f.directory).mode & 0o777).toBe(0o700);
71
+ expect(fs.statSync(path.join(f.directory, 'channel.sqlite')).mode & 0o777).toBe(0o600);
72
+ });
73
+
74
+ it('restarts without another scan, keeps deduplication and does not replay admitted tool work', async () => {
75
+ const f = fixture();
76
+ f.updates.push([inbound()]);
77
+ await f.bind();
78
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1));
79
+ await f.runtime.close();
80
+ const restarted = fixture({ directory: f.directory });
81
+ restarted.updates.push([inbound()]);
82
+ await vi.waitFor(() => expect(restarted.api.sendText).toHaveBeenCalled());
83
+ expect(restarted.api.getQRCode).not.toHaveBeenCalled();
84
+ expect(restarted.service.send).not.toHaveBeenCalled();
85
+ expect(restarted.api.sendText.mock.calls[0][1].text).toContain('主机已重启');
86
+ });
87
+
88
+ it('does not replay old transcript rows on binding; resets the feed on transcript generation changes', async () => {
89
+ const f = fixture();
90
+ f.reply('bot', 'old', 50);
91
+ f.updates.push([inbound()]);
92
+ await f.bind();
93
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalled());
94
+ expect(f.api.sendText).not.toHaveBeenCalled();
95
+ f.pages.set('bot', { generation: 1, messages: [{ ordinal: 1, messageID: 'new', text: 'after reset', cards: [], status: 'complete' }] });
96
+ await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(1));
97
+ expect(f.api.sendText.mock.calls[0][1].text).toBe('after reset');
98
+ });
99
+
100
+ it('uncertain delivery remains visible and is retried only by explicit action, even after new inbound', async () => {
101
+ const f = fixture({ configureAPI: (api) => api.sendText.mockRejectedValueOnce(new WeixinError('network_error', { ambiguous: true })) });
102
+ f.updates.push([inbound()]);
103
+ await f.bind();
104
+ f.reply('bot', 'reply');
105
+ await vi.waitFor(() => expect(f.runtime.status('bot').error).toBe('delivery_unknown'));
106
+ const originalId = f.api.sendText.mock.calls[0][1].id;
107
+ f.updates.push([inbound('2')]);
108
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(2));
109
+ expect(f.api.sendText).toHaveBeenCalledTimes(1);
110
+ f.runtime.retry('bot');
111
+ await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(2));
112
+ expect(f.api.sendText.mock.calls[1][1].id).toBe(originalId);
113
+ });
114
+
115
+ it('shutdown cancels a hanging platform read before closing storage', async () => {
116
+ const f = fixture({ configureAPI: (api) => api.getUpdates.mockImplementation((_binding, signal) => abortable(signal)) });
117
+ await f.bind();
118
+ await vi.waitFor(() => expect(f.api.getUpdates).toHaveBeenCalled());
119
+ const signal = f.api.getUpdates.mock.calls[0][1];
120
+ await f.runtime.close();
121
+ expect(signal.aborted).toBe(true);
122
+ });
123
+
124
+ it('stale QR confirmation after disconnect cannot restore credentials or start polling', async () => {
125
+ let confirm;
126
+ const confirmed = new Promise((resolve) => { confirm = resolve; });
127
+ const f = fixture({ configureAPI: (api) => api.getQRStatus.mockImplementation(() => confirmed) });
128
+ expect((await f.runtime.startLogin('bot')).status).toBe('waiting');
129
+ await f.runtime.disconnect('bot');
130
+ confirm({ status: 'confirmed', bot_token: 'stale', ilink_bot_id: 'account', ilink_user_id: 'owner' });
131
+ await Promise.resolve();
132
+ await Promise.resolve();
133
+ expect(f.runtime.status('bot').status).toBe('disconnected');
134
+ expect(f.api.getUpdates).not.toHaveBeenCalled();
135
+ });
136
+
137
+ it('keeps authentication failure sticky until QR authorization is renewed', async () => {
138
+ const f = fixture({ configureAPI: (api) => api.getUpdates.mockRejectedValue(new WeixinError('auth_expired')) });
139
+ await f.runtime.startLogin('bot');
140
+ await vi.waitFor(() => expect(f.runtime.status('bot').status).toBe('expired'));
141
+ await new Promise((resolve) => setTimeout(resolve, 80));
142
+ expect(f.api.getUpdates).toHaveBeenCalledTimes(1);
143
+ });
144
+
145
+ it('a late receiver network failure cannot undo authorization expiry from sending', async () => {
146
+ let rejectRead;
147
+ const f = fixture({ configureAPI: (api) => {
148
+ api.getUpdates.mockImplementationOnce(async () => ({ msgs: [inbound()], get_updates_buf: 'cursor' }))
149
+ .mockImplementation(() => new Promise((_, reject) => { rejectRead = reject; }));
150
+ api.sendText.mockRejectedValue(new WeixinError('auth_expired'));
151
+ } });
152
+ await f.bind();
153
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalled());
154
+ f.reply('bot', 'reply');
155
+ await vi.waitFor(() => expect(f.runtime.status('bot').status).toBe('expired'));
156
+ await vi.waitFor(() => expect(rejectRead).toBeTypeOf('function'));
157
+ rejectRead(new WeixinError('network_error'));
158
+ await vi.waitFor(() => expect(f.runtime.status('bot')).toMatchObject({ status: 'expired', error: 'auth_expired' }));
159
+ });
160
+
161
+ it('enforces account exclusivity and process ownership without stealing a live receiver', async () => {
162
+ const f = fixture();
163
+ await f.bind();
164
+ await f.runtime.startLogin('other-bot');
165
+ await vi.waitFor(() => expect(f.runtime.status('other-bot').error).toBe('account_in_use'));
166
+ expect(f.runtime.status('bot').status).toBe('connected');
167
+ const second = fixture({ directory: f.directory });
168
+ await expect(second.runtime.startLogin('third-bot')).rejects.toMatchObject({ code: 'channel_in_use' });
169
+ expect(second.api.getUpdates).not.toHaveBeenCalled();
170
+ await second.runtime.close();
171
+ expect(f.runtime.status('bot').status).toBe('connected');
172
+ });
173
+
174
+ it('non-text input gives a text-only reply without invoking bot tools', async () => {
175
+ const f = fixture();
176
+ f.updates.push([{ ...inbound(), item_list: [null, { type: 2, image_item: { media: {} } }] }]);
177
+ await f.bind();
178
+ await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalled());
179
+ expect(f.api.sendText.mock.calls[0][1].text).toContain('仅支持文字');
180
+ expect(f.service.send).not.toHaveBeenCalled();
181
+ });
182
+
183
+ it('reuses the actual Yuri contact pipeline for WeChat → bot → durable reply', async () => {
184
+ const directory = root();
185
+ let runtime;
186
+ let finish;
187
+ const turnGate = new Promise((resolve) => { finish = resolve; });
188
+ const service = createAssistantsService({
189
+ dbPath: path.join(directory, 'assistants.sqlite'), dataDir: directory,
190
+ buildOpenCodeUrl: () => 'http://127.0.0.1:1', getOpenCodeAuthHeaders: () => ({}),
191
+ getAllowedRoots: () => [directory],
192
+ runContactTurn: async ({ userParts }) => { await turnGate; return { bubbles: [`收到:${userParts[0].text}`] }; },
193
+ onContactTurnEvent: (event) => runtime?.onTurnEvent(event),
194
+ createChatCompletion: async () => ({ choices: [] }),
195
+ });
196
+ closers.push(() => service.close());
197
+ const bot = service.createAssistant({ name: '微信测试', providerID: 'p', modelID: 'm' });
198
+ const f = fixture({ directory: path.join(directory, 'weixin'), service });
199
+ runtime = f.runtime;
200
+ f.updates.push([inbound('1', 'owner', '测试文字')]);
201
+ await f.bind(bot.id);
202
+ await vi.waitFor(() => expect(f.api.sendTyping).toHaveBeenCalledWith(
203
+ expect.objectContaining({ assistant_id: bot.id, peer_id: 'owner' }), 'test-ticket', 1, expect.any(AbortSignal),
204
+ ));
205
+ finish();
206
+ await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalled(), { timeout: 4000 });
207
+ expect(f.api.sendText.mock.calls[0][1].text).toBe('收到:测试文字');
208
+ expect(service.contactMessages(bot.id, { limit: 20 }).messages.some((message) => message.text === '测试文字')).toBe(true);
209
+ await vi.waitFor(() => expect(f.api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1, 2]));
210
+ });
211
+
212
+ it.each(['error', 'cancelled'])('clears typing on a live %s terminal event without sending a placeholder text', async (status) => {
213
+ const f = fixture();
214
+ await f.bind();
215
+ f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'turn' } });
216
+ await vi.waitFor(() => expect(f.api.sendTyping).toHaveBeenCalledTimes(1));
217
+ f.runtime.onTurnEvent({ type: 'yuri:contact-turn-end', properties: { assistantID: 'bot', turnID: 'turn', status } });
218
+ await vi.waitFor(() => expect(f.api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1, 2]));
219
+ expect(f.api.sendText).not.toHaveBeenCalled();
220
+ });
221
+
222
+ it('disconnect waits for typing cancellation before forgetting the binding', async () => {
223
+ const f = fixture();
224
+ await f.bind();
225
+ f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'turn' } });
226
+ await vi.waitFor(() => expect(f.api.sendTyping).toHaveBeenCalledTimes(1));
227
+ let finishCancel;
228
+ f.api.sendTyping.mockImplementationOnce(() => new Promise((resolve) => { finishCancel = resolve; }));
229
+ const disconnected = f.runtime.disconnect('bot');
230
+ await vi.waitFor(() => expect(finishCancel).toBeTypeOf('function'));
231
+ f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'late' } });
232
+ finishCancel({});
233
+ expect(await disconnected).toMatchObject({ status: 'disconnected' });
234
+ expect(f.api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1, 2]);
235
+ });
236
+
237
+ it('typing API failure cannot block contact admission, replies or expose optional presence errors', async () => {
238
+ const f = fixture({ configureAPI: (api) => api.getConfig.mockRejectedValue(new Error('private-ticket-error')) });
239
+ f.updates.push([inbound()]);
240
+ await f.bind();
241
+ f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'turn' } });
242
+ await vi.waitFor(() => expect(f.service.send).toHaveBeenCalledTimes(1));
243
+ f.reply('bot', 'reply');
244
+ await vi.waitFor(() => expect(f.api.sendText).toHaveBeenCalledTimes(1));
245
+ expect(f.api.sendTyping).not.toHaveBeenCalled();
246
+ expect(f.runtime.status('bot')).toEqual({ status: 'connected', error: null });
247
+ });
248
+
249
+ it('Host shutdown awaits an independent typing cancellation before closing storage', async () => {
250
+ const f = fixture();
251
+ await f.bind();
252
+ f.runtime.onTurnEvent({ type: 'yuri:contact-turn-start', properties: { assistantID: 'bot', turnID: 'turn' } });
253
+ await vi.waitFor(() => expect(f.api.sendTyping).toHaveBeenCalledTimes(1));
254
+ let finishCancel;
255
+ f.api.sendTyping.mockImplementationOnce(() => new Promise((resolve) => { finishCancel = resolve; }));
256
+ let stopped = false;
257
+ const closing = f.runtime.close().then(() => { stopped = true; });
258
+ await vi.waitFor(() => expect(finishCancel).toBeTypeOf('function'));
259
+ expect(stopped).toBe(false);
260
+ expect(f.api.sendTyping.mock.calls[0][3].aborted).toBe(true);
261
+ expect(f.api.sendTyping.mock.calls[1][3]).toBeUndefined();
262
+ finishCancel({});
263
+ await closing;
264
+ expect(stopped).toBe(true);
265
+ });
266
+ });
267
+
268
+ describe('Weixin durable store', () => {
269
+ it('rolls back a conflicting rebind, persists cursor/receipt together, and fences old epochs', () => {
270
+ const store = createWeixinStore(root());
271
+ closers.push(() => store.close());
272
+ const initial = { token: 'test-token', peer_id: 'owner', base_url: 'https://ilinkai.weixin.qq.com', language: 'en', generation: 0, ordinal: 0, updated_at: 1 };
273
+ const a = store.bind({ ...initial, assistant_id: 'a', account_id: 'account-a' });
274
+ store.bind({ ...initial, assistant_id: 'b', account_id: 'account-b' });
275
+ expect(() => store.bind({ ...initial, assistant_id: 'a', account_id: 'account-b' })).toThrow('account_in_use');
276
+ expect(store.get('a').epoch).toBe(a.epoch);
277
+ store.accept(a, 'cursor-1', [{ id: 'one', text: 'hello', context: 'ctx' }]);
278
+ store.accept(a, 'cursor-2', [{ id: 'one', text: 'hello', context: 'ctx' }]);
279
+ expect(store.pending(a.epoch)).toHaveLength(1);
280
+ expect(store.get('a')).toMatchObject({ cursor: 'cursor-2', context_token: 'ctx' });
281
+ store.unlink('a');
282
+ store.accept(a, 'stale', [{ id: 'stale', text: 'stale' }]);
283
+ expect(store.pending(a.epoch)).toHaveLength(0);
284
+ expect(store.get('a')).toBeNull();
285
+ });
286
+ });
@@ -0,0 +1,103 @@
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
+ accept: db.transaction((binding, cursor, messages) => {
65
+ if (get(binding.assistant_id)?.epoch !== binding.epoch) return;
66
+ for (const message of messages) {
67
+ db.prepare('INSERT OR IGNORE INTO inbox(id,epoch,text) VALUES (?,?,?)').run(message.id, binding.epoch, message.text);
68
+ if (message.context) patch(binding.epoch, { context_token: message.context });
69
+ }
70
+ patch(binding.epoch, { cursor });
71
+ }),
72
+ pending: (epoch) => db.prepare("SELECT * FROM inbox WHERE epoch=? AND state='pending' ORDER BY rowid LIMIT 20").all(epoch),
73
+ backlog: (epoch) => db.prepare("SELECT COUNT(*) AS count FROM inbox WHERE epoch=? AND state IN ('pending','admitted')").get(epoch).count,
74
+ markInbox: (id, state) => db.prepare('UPDATE inbox SET state=? WHERE id=?').run(state, id),
75
+ finishTurn: (id) => db.prepare("UPDATE inbox SET state='done',text='' WHERE id=?").run(id),
76
+ recover: db.transaction((epoch, text) => {
77
+ for (const row of db.prepare("SELECT id FROM inbox WHERE epoch=? AND state='admitted'").all(epoch)) {
78
+ enqueue(epoch, `${row.id}:interrupted`, text);
79
+ db.prepare("UPDATE inbox SET state='done',text='' WHERE id=?").run(row.id);
80
+ }
81
+ // A process exit during HTTP send cannot prove whether Weixin accepted it.
82
+ db.prepare("UPDATE outbox SET state='unknown' WHERE epoch=? AND state='sending'").run(epoch);
83
+ }),
84
+ collect: db.transaction((binding, page, deliveries) => {
85
+ if (get(binding.assistant_id)?.epoch !== binding.epoch) return;
86
+ if (binding.generation !== page.generation) db.prepare('DELETE FROM outbox WHERE epoch=?').run(binding.epoch);
87
+ for (const delivery of deliveries) enqueue(binding.epoch, delivery.id, delivery.text);
88
+ patch(binding.epoch, { generation: page.generation, ordinal: page.ordinal });
89
+ }),
90
+ nextDelivery: (epoch) => db.prepare("SELECT * FROM outbox WHERE epoch=? AND state!='sent' ORDER BY sequence LIMIT 1").get(epoch),
91
+ markDelivery: (id, state) => db.prepare('UPDATE outbox SET state=? WHERE id=?').run(state, id),
92
+ sent: (id) => db.prepare("UPDATE outbox SET state='sent',text='' WHERE id=?").run(id),
93
+ retry: (epoch) => db.prepare("UPDATE outbox SET state='pending' WHERE epoch=? AND state IN ('unknown','blocked')").run(epoch),
94
+ unblock: (epoch) => db.prepare("UPDATE outbox SET state='pending' WHERE epoch=? AND state='blocked'").run(epoch),
95
+ hasUnknown: (epoch) => Boolean(db.prepare("SELECT 1 FROM outbox WHERE epoch=? AND state='unknown' LIMIT 1").get(epoch)),
96
+ acquire: (owner, now) => Boolean(db.prepare(`INSERT INTO lease(id,owner,expires_at) VALUES (1,?,?)
97
+ ON CONFLICT(id) DO UPDATE SET owner=excluded.owner,expires_at=excluded.expires_at
98
+ WHERE lease.owner=excluded.owner OR lease.expires_at<=?`).run(owner, now + 60_000, now).changes),
99
+ owns: (owner, now) => Boolean(db.prepare('SELECT 1 FROM lease WHERE id=1 AND owner=? AND expires_at>?').get(owner, now)),
100
+ release: (owner) => db.prepare('DELETE FROM lease WHERE owner=?').run(owner),
101
+ close: () => db.close(),
102
+ };
103
+ }
@@ -0,0 +1,88 @@
1
+ import { setTimeout as delay } from 'node:timers/promises';
2
+
3
+ const REFRESH_MS = 8000;
4
+ const TICKET_TTL_MS = 24 * 60 * 60 * 1000;
5
+
6
+ /** Optional, live-only presence. Never gate contact admission or message delivery. */
7
+ export function createWeixinTyping({ api, getBinding, isCurrent, canCancel, clock = Date.now }) {
8
+ const entries = new Map();
9
+ let closed = false;
10
+ const pause = (ms, signal) => delay(ms, undefined, { signal }).catch(() => {});
11
+ const launch = (entry) => {
12
+ if (entry.running || entry.disposed || closed) return;
13
+ const controller = new AbortController();
14
+ entry.controller = controller;
15
+ entry.running = (async () => {
16
+ let lastTicket = '';
17
+ let retryMs = 2000;
18
+ try {
19
+ while (!controller.signal.aborted && entry.turns.size && isCurrent(entry.binding)) {
20
+ const binding = getBinding(entry.binding.assistant_id);
21
+ try {
22
+ if (!entry.ticket || clock() >= entry.ticketExpiresAt) {
23
+ const config = await api.getConfig(binding, controller.signal);
24
+ if (config.ret !== 0 || typeof config.typing_ticket !== 'string'
25
+ || !config.typing_ticket || config.typing_ticket.length > 65_536) throw new Error('typing_unavailable');
26
+ entry.ticket = config.typing_ticket;
27
+ entry.ticketExpiresAt = clock() + TICKET_TTL_MS;
28
+ }
29
+ if (controller.signal.aborted || !entry.turns.size || !isCurrent(entry.binding)) break;
30
+ // Record attempts too: a failed HTTP response may still have set presence.
31
+ lastTicket = entry.ticket;
32
+ await api.sendTyping(binding, entry.ticket, 1, controller.signal);
33
+ retryMs = 2000;
34
+ await pause(REFRESH_MS, controller.signal);
35
+ } catch {
36
+ if (controller.signal.aborted) break;
37
+ entry.ticket = '';
38
+ await pause(retryMs, controller.signal);
39
+ retryMs = Math.min(60_000, retryMs * 2);
40
+ }
41
+ }
42
+ } finally {
43
+ if (lastTicket && canCancel(entry.binding)) {
44
+ // Do not reuse the aborted start signal. Serialize cancellation before a
45
+ // newer turn can publish typing, including during disconnect/shutdown.
46
+ try { await api.sendTyping(entry.binding, lastTicket, 2); } catch { /* Presence is best-effort. */ }
47
+ }
48
+ }
49
+ })().finally(() => {
50
+ entry.running = null;
51
+ if (!entry.disposed && !closed && entry.turns.size && isCurrent(entry.binding)) launch(entry);
52
+ });
53
+ };
54
+ const forget = async (assistantID) => {
55
+ const entry = entries.get(assistantID);
56
+ if (!entry) return;
57
+ entry.disposed = true;
58
+ entry.turns.clear();
59
+ entry.controller?.abort();
60
+ await entry.running;
61
+ if (entries.get(assistantID) === entry) entries.delete(assistantID);
62
+ };
63
+ const clear = () => Promise.allSettled([...entries.keys()].map(forget));
64
+ return {
65
+ onTurnEvent: (event) => {
66
+ if (closed || !['yuri:contact-turn-start', 'yuri:contact-turn-end'].includes(event.type)) return;
67
+ const { assistantID, turnID } = event.properties ?? {};
68
+ if (typeof assistantID !== 'string' || typeof turnID !== 'string' || !turnID) return;
69
+ const binding = getBinding(assistantID);
70
+ if (!binding || binding.status === 'expired' || !isCurrent(binding)) return;
71
+ let entry = entries.get(assistantID);
72
+ if (event.type === 'yuri:contact-turn-start') {
73
+ if (!entry) {
74
+ entry = { binding, turns: new Set(), ticket: '', ticketExpiresAt: 0, running: null, disposed: false };
75
+ entries.set(assistantID, entry);
76
+ }
77
+ if (entry.disposed || entry.binding.epoch !== binding.epoch) return;
78
+ entry.turns.add(turnID);
79
+ launch(entry);
80
+ } else if (entry?.binding.epoch === binding.epoch) {
81
+ entry.turns.delete(turnID);
82
+ if (!entry.turns.size) entry.controller?.abort();
83
+ }
84
+ },
85
+ forget, clear,
86
+ close: () => { closed = true; return clear(); },
87
+ };
88
+ }
@@ -0,0 +1,185 @@
1
+ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2
+
3
+ // Node's promise timers capture native timers before Vitest's fake clock installs.
4
+ vi.mock('node:timers/promises', () => ({
5
+ setTimeout: (ms, value, { signal }) => new Promise((resolve, reject) => {
6
+ const abort = () => { clearTimeout(timer); reject(new Error('cancelled')); };
7
+ const timer = setTimeout(() => { signal.removeEventListener('abort', abort); resolve(value); }, ms);
8
+ if (signal.aborted) abort();
9
+ else signal.addEventListener('abort', abort, { once: true });
10
+ }),
11
+ }));
12
+ import { createWeixinTyping } from './typing.js';
13
+
14
+ let typing;
15
+ beforeEach(() => vi.useFakeTimers({ toFake: ['Date', 'setTimeout', 'clearTimeout'] }));
16
+ afterEach(async () => { await typing?.close(); typing = null; vi.useRealTimers(); });
17
+ const turn = (assistantID, turnID, phase = 'start') => ({
18
+ type: `yuri:contact-turn-${phase}`, properties: { assistantID, turnID },
19
+ });
20
+ const flush = async () => { await vi.advanceTimersByTimeAsync(0); };
21
+ const deferred = () => {
22
+ let resolve;
23
+ const promise = new Promise((done) => { resolve = done; });
24
+ return { promise, resolve };
25
+ };
26
+ const fixture = () => {
27
+ const bindings = new Map(['a', 'b'].map((id) => [id, {
28
+ assistant_id: id, epoch: `epoch-${id}`, peer_id: `owner-${id}`, context_token: `context-${id}`, status: 'connected',
29
+ }]));
30
+ const api = {
31
+ getConfig: vi.fn(async (binding) => ({ ret: 0, typing_ticket: `ticket-${binding.assistant_id}` })),
32
+ sendTyping: vi.fn(async () => ({})),
33
+ };
34
+ const current = (binding) => bindings.get(binding.assistant_id)?.epoch === binding.epoch;
35
+ typing = createWeixinTyping({ api, getBinding: (id) => bindings.get(id), isCurrent: current, canCancel: current });
36
+ return { api, bindings };
37
+ };
38
+
39
+ describe('live WeChat typing lifecycle', () => {
40
+ it('stays idle without a live start and coalesces duplicate starts and streaming deltas', async () => {
41
+ const { api } = fixture();
42
+ for (let index = 0; index < 50; index++) {
43
+ typing.onTurnEvent({ type: 'yuri:contact-bubble-delta', properties: { assistantID: 'a', turnID: 'old', delta: 'text' } });
44
+ typing.onTurnEvent(turn('a', 'old', 'end'));
45
+ }
46
+ await flush();
47
+ expect(api.getConfig).not.toHaveBeenCalled();
48
+ typing.onTurnEvent(turn('a', 'one'));
49
+ await flush();
50
+ for (let index = 0; index < 50; index++) typing.onTurnEvent(turn('a', 'one'));
51
+ await flush();
52
+ expect(api.getConfig).toHaveBeenCalledTimes(1);
53
+ expect(api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1]);
54
+ typing.onTurnEvent(turn('a', 'one', 'end'));
55
+ await flush();
56
+ expect(api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1, 2]);
57
+ await vi.advanceTimersByTimeAsync(60_000);
58
+ expect(api.sendTyping).toHaveBeenCalledTimes(2);
59
+ });
60
+
61
+ it('refreshes at a bounded cadence, keeps overlapping turns active, and reuses an idle ticket', async () => {
62
+ const { api } = fixture();
63
+ typing.onTurnEvent(turn('a', 'one'));
64
+ typing.onTurnEvent(turn('a', 'two'));
65
+ await flush();
66
+ await vi.advanceTimersByTimeAsync(7999);
67
+ expect(api.sendTyping).toHaveBeenCalledTimes(1);
68
+ await vi.advanceTimersByTimeAsync(1);
69
+ expect(api.sendTyping).toHaveBeenCalledTimes(2);
70
+ typing.onTurnEvent(turn('a', 'one', 'end'));
71
+ await flush();
72
+ expect(api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1, 1]);
73
+ typing.onTurnEvent(turn('a', 'two', 'end'));
74
+ await flush();
75
+ typing.onTurnEvent(turn('a', 'three'));
76
+ await flush();
77
+ expect(api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1, 1, 2, 1]);
78
+ expect(api.getConfig).toHaveBeenCalledTimes(1);
79
+ });
80
+
81
+ it('never starts typing from a ticket that arrives after completion or disconnect', async () => {
82
+ const { api } = fixture();
83
+ const ticket = deferred();
84
+ api.getConfig.mockImplementation(() => ticket.promise);
85
+ typing.onTurnEvent(turn('a', 'one'));
86
+ typing.onTurnEvent(turn('a', 'one', 'end'));
87
+ ticket.resolve({ ret: 0, typing_ticket: 'late' });
88
+ await flush();
89
+ expect(api.sendTyping).not.toHaveBeenCalled();
90
+
91
+ const other = deferred();
92
+ api.getConfig.mockImplementation(() => other.promise);
93
+ typing.onTurnEvent(turn('b', 'two'));
94
+ const disconnected = typing.forget('b');
95
+ other.resolve({ ret: 0, typing_ticket: 'late-b' });
96
+ await disconnected;
97
+ expect(api.sendTyping).not.toHaveBeenCalled();
98
+ });
99
+
100
+ it('serializes late start completion, cancellation and the next live turn', async () => {
101
+ const { api } = fixture();
102
+ const start = deferred();
103
+ api.sendTyping.mockImplementationOnce(() => start.promise);
104
+ typing.onTurnEvent(turn('a', 'one'));
105
+ await flush();
106
+ typing.onTurnEvent(turn('a', 'one', 'end'));
107
+ typing.onTurnEvent(turn('a', 'two'));
108
+ await flush();
109
+ expect(api.sendTyping).toHaveBeenCalledTimes(1);
110
+ start.resolve({});
111
+ await flush();
112
+ expect(api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1, 2, 1]);
113
+ });
114
+
115
+ it('isolates accounts and backs off missing/failed tickets without aborting other typing', async () => {
116
+ const { api } = fixture();
117
+ api.getConfig.mockImplementation(async (binding) => binding.assistant_id === 'a'
118
+ ? { ret: 0 } : { ret: 0, typing_ticket: 'ticket-b' });
119
+ typing.onTurnEvent(turn('a', 'one'));
120
+ typing.onTurnEvent(turn('b', 'two'));
121
+ await flush();
122
+ expect(api.sendTyping.mock.calls.map((call) => [call[0].assistant_id, call[2]])).toEqual([['b', 1]]);
123
+ await vi.advanceTimersByTimeAsync(1999);
124
+ expect(api.getConfig).toHaveBeenCalledTimes(2);
125
+ await vi.advanceTimersByTimeAsync(1);
126
+ expect(api.getConfig).toHaveBeenCalledTimes(3);
127
+ await vi.advanceTimersByTimeAsync(4000);
128
+ expect(api.getConfig).toHaveBeenCalledTimes(4);
129
+ typing.onTurnEvent(turn('a', 'one', 'end'));
130
+ await flush();
131
+ expect(api.sendTyping).toHaveBeenCalledTimes(1);
132
+ });
133
+
134
+ it('cancels on forget/shutdown with a fresh signal and drops the per-binding ticket cache', async () => {
135
+ const { api, bindings } = fixture();
136
+ typing.onTurnEvent(turn('a', 'one'));
137
+ await flush();
138
+ const signal = api.sendTyping.mock.calls[0][3];
139
+ await typing.forget('a');
140
+ expect(signal.aborted).toBe(true);
141
+ expect(api.sendTyping.mock.calls.at(-1).slice(1, 3)).toEqual(['ticket-a', 2]);
142
+ expect(api.sendTyping.mock.calls.at(-1)[3]).toBeUndefined();
143
+ bindings.set('a', { ...bindings.get('a'), epoch: 'new-epoch' });
144
+ typing.onTurnEvent(turn('a', 'two'));
145
+ await flush();
146
+ expect(api.getConfig).toHaveBeenCalledTimes(2);
147
+ await typing.close();
148
+ expect(api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1, 2, 1, 2]);
149
+ });
150
+
151
+ it('fences a ticket completion after lease/epoch changes without cancelling another owner', async () => {
152
+ const { api, bindings } = fixture();
153
+ const ticket = deferred();
154
+ api.getConfig.mockImplementationOnce(() => ticket.promise);
155
+ typing.onTurnEvent(turn('a', 'one'));
156
+ bindings.set('a', { ...bindings.get('a'), epoch: 'rebound' });
157
+ ticket.resolve({ ret: 0, typing_ticket: 'old-ticket' });
158
+ await flush();
159
+ expect(api.sendTyping).not.toHaveBeenCalled();
160
+ });
161
+
162
+ it('refreshes an expired ticket using the latest conversation context', async () => {
163
+ const { api, bindings } = fixture();
164
+ typing.onTurnEvent(turn('a', 'one'));
165
+ await flush();
166
+ typing.onTurnEvent(turn('a', 'one', 'end'));
167
+ await flush();
168
+ vi.setSystemTime(Date.now() + 24 * 60 * 60 * 1000);
169
+ bindings.set('a', { ...bindings.get('a'), context_token: 'new-context' });
170
+ typing.onTurnEvent(turn('a', 'two'));
171
+ await flush();
172
+ expect(api.getConfig).toHaveBeenCalledTimes(2);
173
+ expect(api.getConfig.mock.calls[1][0].context_token).toBe('new-context');
174
+ });
175
+
176
+ it('stops refreshing on ownership loss and does not cancel the replacement owner', async () => {
177
+ const { api, bindings } = fixture();
178
+ typing.onTurnEvent(turn('a', 'one'));
179
+ await flush();
180
+ bindings.set('a', { ...bindings.get('a'), epoch: 'replacement-owner' });
181
+ await vi.advanceTimersByTimeAsync(8000);
182
+ await typing.clear();
183
+ expect(api.sendTyping.mock.calls.map((call) => call[2])).toEqual([1]);
184
+ });
185
+ });