@yuriai/web 0.2.27-beta.6 → 0.2.27-beta.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (161) hide show
  1. package/README.md +8 -0
  2. package/dist/assets/{AgentAvatar-Bi1vvWPC.js → AgentAvatar-BJ42lGZD.js} +1 -1
  3. package/dist/assets/AssistantContactStatus-dtkObamV.js +3 -0
  4. package/dist/assets/{AssistantUnreadBadge-DdJyySwn.js → AssistantUnreadBadge-QwhBfXpC.js} +1 -1
  5. package/dist/assets/AssistantView-D7ryIKL0.js +1 -0
  6. package/dist/assets/{DiagramView-CI4bTtxy.js → DiagramView-ERrGEBDp.js} +1 -1
  7. package/dist/assets/{FadeInOnReveal-BB4qEnAn.js → FadeInOnReveal-Bu2GvaM9.js} +1 -1
  8. package/dist/assets/{GuiPluginSurface-CguxFUbM.js → GuiPluginSurface-MzQgEZNr.js} +1 -1
  9. package/dist/assets/{GuiPluginWindow-DOJ7wuRH.js → GuiPluginWindow-DZMmlQzx.js} +1 -1
  10. package/dist/assets/{Icon-t2xvbAyN.js → Icon-Dj4CCqCP.js} +1 -1
  11. package/dist/assets/{ImageLoadingPlaceholder-D1L13TK0.js → ImageLoadingPlaceholder-BnFXgUuO.js} +1 -1
  12. package/dist/assets/{LoadingImage-5rY_edNm.js → LoadingImage-PBnivDKv.js} +1 -1
  13. package/dist/assets/{MarkdownRenderer-BlGxjOei.js → MarkdownRenderer-BajF4gUU.js} +2 -2
  14. package/dist/assets/{MarkdownRendererImpl-cE-0AYRg.js → MarkdownRendererImpl-CfyXL4rg.js} +1 -1
  15. package/dist/assets/{MarkstreamRendererImpl-BZyqDl82.js → MarkstreamRendererImpl-BGadklK1.js} +1 -1
  16. package/dist/assets/{MobileDetailNavigation-tbfsMfB-.js → MobileDetailNavigation-DqajQdB4.js} +1 -1
  17. package/dist/assets/{MobileResizableSheet-BeRmT6_x.js → MobileResizableSheet-BvdUgwA3.js} +1 -1
  18. package/dist/assets/{MobileShareBridge-C3Equ3P_.js → MobileShareBridge-3oPoYnry.js} +2 -2
  19. package/dist/assets/{MobileTabPageHeader-DQRqAAEf.js → MobileTabPageHeader-B6cRyIRH.js} +1 -1
  20. package/dist/assets/{MultiRunWindow-CAM2XPII.js → MultiRunWindow-yhs0Ih5_.js} +1 -1
  21. package/dist/assets/{OnboardingScreen-4ftRerP5.js → OnboardingScreen-Bi1VWFQC.js} +1 -1
  22. package/dist/assets/{OverlayScrollbar-CF0PCvQz.js → OverlayScrollbar-BBDwGvGO.js} +1 -1
  23. package/dist/assets/{SettingsView-2tk4WH7R.js → SettingsView-BSf-SJUA.js} +15 -15
  24. package/dist/assets/{SettingsWindow-B9zbeJaW.js → SettingsWindow-BvSXVMTm.js} +1 -1
  25. package/dist/assets/{TerminalView-DfxvTHye.js → TerminalView-DhL01N7e.js} +1 -1
  26. package/dist/assets/{ToolOutputDialog-CrjDIhru.js → ToolOutputDialog-C8lnH4Ky.js} +1 -1
  27. package/dist/assets/{YuriLogo-QvS1ZEHi.js → YuriLogo-D8asj1CS.js} +1 -1
  28. package/dist/assets/{appThemeRegistry-Bb_DtiV9.js → appThemeRegistry-C-maYSdv.js} +1 -1
  29. package/dist/assets/{assistant-attachment-cache-B9iHLlm2.js → assistant-attachment-cache-B_qRvy-k.js} +1 -1
  30. package/dist/assets/{button-DinGM3tu.js → button-vXOdzd8x.js} +1 -1
  31. package/dist/assets/{capgoAdapter-DufzjXRs.js → capgoAdapter-DJ_h2x5D.js} +1 -1
  32. package/dist/assets/{collapsible-Bh1GLNYV.js → collapsible-DwDQs3Wa.js} +1 -1
  33. package/dist/assets/context-menu-BabBujQ-.js +1 -0
  34. package/dist/assets/{desktopRelayRestore-CoLLVJw8.js → desktopRelayRestore-D1UX7HW2.js} +1 -1
  35. package/dist/assets/{diagram-BmG-7Jb4.js → diagram-HwgrQxY5.js} +1 -1
  36. package/dist/assets/{dialog-BXssfGXA.js → dialog-Dnf626tb.js} +1 -1
  37. package/dist/assets/dropdown-menu.styles-CBc_a-Nv.js +1 -0
  38. package/dist/assets/{es-HP_Ise0X.js → es-BQkO-Odr.js} +1 -1
  39. package/dist/assets/feishu-Ct1ZxlzQ.svg +6 -0
  40. package/dist/assets/{fileMentionTouchSelection-DSl0tj2r.js → fileMentionTouchSelection-CKPnEetl.js} +1 -1
  41. package/dist/assets/{fileQueries-5a1jkme2.js → fileQueries-BeXkd3o6.js} +1 -1
  42. package/dist/assets/{fileReferenceActions-CGpBSFq4.js → fileReferenceActions-g7KZLi_G.js} +1 -1
  43. package/dist/assets/{fr-D0kJXJ6U.js → fr-C852roK5.js} +1 -1
  44. package/dist/assets/{gitApi-Wo0IZow9.js → gitApi-CVq5oKCd.js} +1 -1
  45. package/dist/assets/{gitApiHttp-De9liKnG.js → gitApiHttp-BYOIbYIh.js} +2 -2
  46. package/dist/assets/{gui-9enrif_1.js → gui-M_Rbwkyu.js} +1 -1
  47. package/dist/assets/host-BW3FEJdU.js +1 -0
  48. package/dist/assets/{image-loading-Dq1g_wpm.js → image-loading-D5UhMj7Z.js} +1 -1
  49. package/dist/assets/{input-v8-rVbo-.js → input-BtM712b1.js} +1 -1
  50. package/dist/assets/{insertionBoundaries-CZz7TWJv.js → insertionBoundaries-Dx3WAY6i.js} +1 -1
  51. package/dist/assets/{ja-BjHKXazE.js → ja-BqC39qK6.js} +1 -1
  52. package/dist/assets/{ko-Llwnl876.js → ko-BMaChAWh.js} +1 -1
  53. package/dist/assets/main-9uP2z1qT.js +2 -0
  54. package/dist/assets/main-Mey7bCWf.js +169 -0
  55. package/dist/assets/{markdownHeightCache-BVV2dktw.js → markdownHeightCache-Bf8iisO4.js} +1 -1
  56. package/dist/assets/{mcpQueries-BoBrB4a4.js → mcpQueries-DpXqegX5.js} +1 -1
  57. package/dist/assets/miniChat-DqZvVkme.js +2 -0
  58. package/dist/assets/mobile-DXAWjYcN.js +2 -0
  59. package/dist/assets/{mobileBackNavigation-DMSzAvb6.js → mobileBackNavigation-DZcI7aZg.js} +1 -1
  60. package/dist/assets/{multirun-BhWttsRQ.js → multirun-hzspPepd.js} +1 -1
  61. package/dist/assets/{native-DSvNnKAm.js → native-H7K64Ulc.js} +1 -1
  62. package/dist/assets/{native-config-DjdrW_9n.js → native-config-CddZtLQ1.js} +1 -1
  63. package/dist/assets/{persistence-CfrHIiIS.js → persistence-BT8045Ue.js} +1 -1
  64. package/dist/assets/{pl-BOd_idqn.js → pl-Ubs8p28T.js} +1 -1
  65. package/dist/assets/projectMeta-CEf0QPmD.js +1 -0
  66. package/dist/assets/{pt-BR-B8djxMsl.js → pt-BR-8rAOjJrs.js} +1 -1
  67. package/dist/assets/{queryRuntime-Dkpnq3Z1.js → queryRuntime-CTcigFdj.js} +1 -1
  68. package/dist/assets/react-DRe85o5s.js +1 -0
  69. package/dist/assets/readiness-Dyr7314z.js +1 -0
  70. package/dist/assets/{renderElectronMiniChatApp-N2r999Bf.js → renderElectronMiniChatApp-DoOq8Cuo.js} +2 -2
  71. package/dist/assets/{renderMobileApp-CU1ec6Ak.js → renderMobileApp-TTxtOb8b.js} +7 -7
  72. package/dist/assets/runtime-fetch-D0YWp3FJ.js +1 -0
  73. package/dist/assets/{runtime-file-download-CcNIVp7u.js → runtime-file-download-Cf1WxfeW.js} +1 -1
  74. package/dist/assets/{runtime-file-resource-6np6lzoV.js → runtime-file-resource-UJjHUF2C.js} +1 -1
  75. package/dist/assets/runtimeConfig-B8VHHNxj.js +2 -0
  76. package/dist/assets/runtimeEndpointReset-BC6XWntz.js +149 -0
  77. package/dist/assets/scheduledTaskNavigation-Zm87Nydi.js +1 -0
  78. package/dist/assets/sessionLookup-De53jDwM.js +1 -0
  79. package/dist/assets/{sortable-tabs-strip-yKyqsqut.js → sortable-tabs-strip-D4pVoodN.js} +1 -1
  80. package/dist/assets/speechSettingsQueries-RlCLMBtr.js +4 -0
  81. package/dist/assets/src-lE4uqaHS.css +2 -0
  82. package/dist/assets/{store-CUBymvAC.js → store-ME7oHni1.js} +2 -2
  83. package/dist/assets/{terminalApi-BblSkqch.js → terminalApi-BSaclMDJ.js} +1 -1
  84. package/dist/assets/{textarea-B39OCNPV.js → textarea-B98rsLs7.js} +1 -1
  85. package/dist/assets/{tooltip-d8TNN4lx.js → tooltip-B9810jbK.js} +1 -1
  86. package/dist/assets/{types-BqFQhQTt.js → types-DFf9vd1b.js} +1 -1
  87. package/dist/assets/{uk-BNd7CjVO.js → uk-LzwzUApL.js} +1 -1
  88. package/dist/assets/{useAppFontEffects-BVoVpJYO.js → useAppFontEffects-D2C1sBYM.js} +43 -43
  89. package/dist/assets/{useAssistantUIStore-Bp6TxG5E.js → useAssistantUIStore-TUN_ycy5.js} +1 -1
  90. package/dist/assets/{useDesktopWindowControlsLayout-CYx1LNO5.js → useDesktopWindowControlsLayout-BjKaHN0x.js} +1 -1
  91. package/dist/assets/{useEffectiveDirectory-D8FFE5Yn.js → useEffectiveDirectory-TEvyiQSC.js} +1 -1
  92. package/dist/assets/{useFontPreferences-BFyBjtQ6.js → useFontPreferences-BlhlCJCX.js} +1 -1
  93. package/dist/assets/{useMobileNavigationStore-BHMFeMjo.js → useMobileNavigationStore-DTvJV9s-.js} +6 -6
  94. package/dist/assets/useUIStore-DRx6OgCp.js +1 -0
  95. package/dist/assets/{useWorkerHighlightedLines-CPxG8Fya.js → useWorkerHighlightedLines-D093jNsH.js} +1 -1
  96. package/dist/assets/vendor-opencode-client-ZeOZ4Efz.js +23 -0
  97. package/dist/assets/{vendor-opencode-plugin-CgKz9Hcy.js → vendor-opencode-plugin-BBOP6WNx.js} +1 -1
  98. package/dist/assets/{vendor-solid-js-0T254UHG.js → vendor-solid-js-9wmPZH9g.js} +1 -1
  99. package/dist/assets/{zh-CN-BkTAEOZG.js → zh-CN-D-FVCeks.js} +1 -1
  100. package/dist/assets/{zh-TW-x8SfMzfc.js → zh-TW-B9iH_NXL.js} +1 -1
  101. package/dist/index.html +17 -17
  102. package/dist/mini-chat.html +17 -17
  103. package/dist/mobile.html +17 -17
  104. package/package.json +6 -1
  105. package/server/lib/assistants/DOCUMENTATION.md +13 -1
  106. package/server/lib/assistants/channels/DOCUMENTATION.md +291 -0
  107. package/server/lib/assistants/channels/PROTOCOLS.md +228 -0
  108. package/server/lib/assistants/channels/dingtalk-chat-adapter.js +633 -0
  109. package/server/lib/assistants/channels/dingtalk-chat-adapter.test.js +415 -0
  110. package/server/lib/assistants/channels/integration.test.js +44 -0
  111. package/server/lib/assistants/channels/routes.js +47 -0
  112. package/server/lib/assistants/channels/routes.test.js +105 -0
  113. package/server/lib/assistants/channels/runtime.js +867 -0
  114. package/server/lib/assistants/channels/runtime.test.js +723 -0
  115. package/server/lib/assistants/channels/sdk-adapters.js +371 -0
  116. package/server/lib/assistants/channels/sdk-adapters.test.js +367 -0
  117. package/server/lib/assistants/channels/store.js +246 -0
  118. package/server/lib/assistants/channels/store.test.js +286 -0
  119. package/server/lib/assistants/channels/transport.js +41 -0
  120. package/server/lib/assistants/channels/transport.test.js +23 -0
  121. package/server/lib/assistants/channels/wecom-chat-adapter.js +689 -0
  122. package/server/lib/assistants/channels/wecom-chat-adapter.test.js +109 -0
  123. package/server/lib/assistants/message-channel-origin.js +7 -0
  124. package/server/lib/assistants/routes.js +14 -1
  125. package/server/lib/assistants/weixin/DOCUMENTATION.md +89 -7
  126. package/server/lib/assistants/weixin/api.js +2 -0
  127. package/server/lib/assistants/weixin/chat-adapter.js +107 -0
  128. package/server/lib/assistants/weixin/chat-adapter.test.js +62 -0
  129. package/server/lib/assistants/weixin/inbound.js +147 -0
  130. package/server/lib/assistants/weixin/inbound.test.js +121 -0
  131. package/server/lib/assistants/weixin/media.js +79 -0
  132. package/server/lib/assistants/weixin/media.test.js +66 -0
  133. package/server/lib/assistants/weixin/runtime.js +89 -67
  134. package/server/lib/assistants/weixin/runtime.test.js +156 -4
  135. package/server/lib/assistants/weixin/store.js +8 -4
  136. package/server/lib/assistants/weixin/store.test.js +72 -0
  137. package/server/lib/assistants/weixin/toon.js +49 -0
  138. package/server/lib/assistants/weixin/toon.test.js +25 -0
  139. package/server/lib/github/DOCUMENTATION.md +9 -8
  140. package/server/lib/llm/bridge-plugin.bundle.js +188 -188
  141. package/server/lib/opencode/DOCUMENTATION.md +1 -1
  142. package/dist/assets/AssistantContactStatus-CWq-PDz6.js +0 -3
  143. package/dist/assets/AssistantView-Br1iETTs.js +0 -1
  144. package/dist/assets/context-menu-DpbkRkk1.js +0 -1
  145. package/dist/assets/host-FR_grJxM.js +0 -1
  146. package/dist/assets/main-Bp9HHqTr.js +0 -2
  147. package/dist/assets/main-DOwAfmxJ.js +0 -169
  148. package/dist/assets/miniChat-BJDgCrfF.js +0 -2
  149. package/dist/assets/mobile-GM9931J_.js +0 -2
  150. package/dist/assets/projectMeta-31PobC-M.js +0 -1
  151. package/dist/assets/react-B9v0P7kT.js +0 -1
  152. package/dist/assets/readiness-CYNnsekT.js +0 -1
  153. package/dist/assets/runtime-fetch-D4ja813o.js +0 -1
  154. package/dist/assets/runtimeConfig-Db7yfo6L.js +0 -2
  155. package/dist/assets/runtimeEndpointReset-DO5WVetV.js +0 -149
  156. package/dist/assets/scheduledTaskNavigation-Bsrhv3Ow.js +0 -1
  157. package/dist/assets/sessionLookup-DRVy7LM1.js +0 -1
  158. package/dist/assets/speechSettingsQueries-DU25rmGc.js +0 -4
  159. package/dist/assets/src-Bckdo2XS.css +0 -2
  160. package/dist/assets/useUIStore-BbYD420L.js +0 -1
  161. package/dist/assets/vendor-opencode-client-UL_TecvQ.js +0 -12
@@ -0,0 +1,286 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import path from 'node:path';
4
+ import { createRequire } from 'node:module';
5
+ import { afterEach, describe, expect, it } from 'vitest';
6
+ import { createAssistantChannelStore } from './store.js';
7
+
8
+ const Database = createRequire(import.meta.url)('better-sqlite3');
9
+ const cleanup = [];
10
+ afterEach(() => { while (cleanup.length) cleanup.pop()(); });
11
+ const directory = () => {
12
+ const value = fs.mkdtempSync(path.join(os.tmpdir(), 'yuri-channels-store-'));
13
+ cleanup.push(() => fs.rmSync(value, { recursive: true, force: true }));
14
+ return value;
15
+ };
16
+ const bind = (store, assistantID = 'bot', overrides = {}) => store.bind({
17
+ assistant_id: assistantID,
18
+ provider: 'wecom',
19
+ client_id: 'client',
20
+ client_secret: 'fake-secret',
21
+ owner_id: 'owner',
22
+ language: 'zh-CN',
23
+ generation: 0,
24
+ ordinal: 0,
25
+ updated_at: 1,
26
+ ...overrides,
27
+ });
28
+
29
+ describe('enterprise channel private store', () => {
30
+ it('adds receipt routing to an existing database without losing receipts or bindings', () => {
31
+ const dir = directory();
32
+ const original = createAssistantChannelStore(dir);
33
+ const binding = bind(original);
34
+ original.accept(binding, [{ id: 'old-receipt', text: 'existing', payload: '' }]);
35
+ original.close();
36
+ const db = new Database(path.join(dir, 'channel.sqlite'));
37
+ db.exec('ALTER TABLE inbox DROP COLUMN target');
38
+ db.close();
39
+ const store = createAssistantChannelStore(dir);
40
+ cleanup.push(() => store.close());
41
+ expect(store.get('bot', 'wecom')).toMatchObject({ epoch: binding.epoch });
42
+ expect(store.receipt('old-receipt', binding.epoch)).toEqual({ id: 'old-receipt', target: '' });
43
+ store.accept(binding, [{ id: 'new-receipt', text: 'new', payload: '', target: '{"userID":"alice"}' }]);
44
+ expect(store.receipt('new-receipt', binding.epoch)).toEqual({ id: 'new-receipt', target: '{"userID":"alice"}' });
45
+ expect(store.receipt('new-receipt', 'other-epoch')).toBeUndefined();
46
+ });
47
+
48
+ it('atomically moves one account while keeping receipts and dropping old queued content', () => {
49
+ const store = createAssistantChannelStore(directory());
50
+ cleanup.push(() => store.close());
51
+ const source = bind(store, 'source');
52
+ store.accept(source, [{ id: 'receipt', text: 'old request', payload: '', target: '' }]);
53
+ store.collect(source, { generation: 0, ordinal: 1 }, [{ id: 'old-output', text: 'old reply' }], 1);
54
+ const input = { sourceAssistantID: 'source', assistantID: 'target', provider: 'wecom', revision: source.epoch, generation: 2, ordinal: 8, updatedAt: 2 };
55
+ expect(() => store.transfer({ ...input, revision: 'stale' })).toThrow('binding_changed');
56
+ expect(store.get('source', 'wecom')).toMatchObject({ epoch: source.epoch });
57
+ const moved = store.transfer(input);
58
+ expect(store.get('source', 'wecom')).toBeNull();
59
+ expect(moved).toMatchObject({ assistant_id: 'target', client_id: 'client', client_secret: 'fake-secret', generation: 2, ordinal: 8 });
60
+ expect(moved.epoch).not.toBe(source.epoch);
61
+ expect(store.hasReceipt('receipt')).toBe(true);
62
+ expect(store.pending(moved.epoch)).toEqual([]);
63
+ expect(store.nextDelivery(moved.epoch)).toBeUndefined();
64
+ expect(store.accept(moved, [{ id: 'receipt', text: 'replay' }])).toBe(false);
65
+ });
66
+
67
+ it('rolls back receipts, output and ownership when moving the binding fails', () => {
68
+ const dir = directory();
69
+ const store = createAssistantChannelStore(dir);
70
+ cleanup.push(() => store.close());
71
+ const source = bind(store, 'source');
72
+ store.accept(source, [{ id: 'pending', text: 'keep request', payload: '' }]);
73
+ store.collect(source, { generation: 0, ordinal: 1 }, [{ id: 'output', text: 'keep reply' }], 1);
74
+ const db = new Database(path.join(dir, 'channel.sqlite'));
75
+ try {
76
+ db.exec("CREATE TRIGGER fail_transfer BEFORE UPDATE OF assistant_id ON channel BEGIN SELECT RAISE(ABORT, 'move_failed'); END");
77
+ expect(() => store.transfer({ sourceAssistantID: 'source', assistantID: 'target', provider: 'wecom', revision: source.epoch, generation: 0, ordinal: 0, updatedAt: 2 })).toThrow('move_failed');
78
+ expect(store.get('source', 'wecom')).toMatchObject({ epoch: source.epoch });
79
+ expect(store.get('target', 'wecom')).toBeNull();
80
+ expect(store.pending(source.epoch)).toEqual([expect.objectContaining({ id: 'pending', text: 'keep request' })]);
81
+ expect(store.nextDelivery(source.epoch)).toMatchObject({ id: 'output', text: 'keep reply' });
82
+ } finally { db.close(); }
83
+ });
84
+
85
+ it('creates a 0700 directory and 0600 database and enforces account ownership', () => {
86
+ const dir = directory();
87
+ const store = createAssistantChannelStore(dir);
88
+ cleanup.push(() => store.close());
89
+ expect(fs.statSync(dir).mode & 0o777).toBe(0o700);
90
+ expect(fs.statSync(path.join(dir, 'channel.sqlite')).mode & 0o777).toBe(0o600);
91
+ bind(store);
92
+ expect(() => bind(store, 'other')).toThrow('account_in_use');
93
+ expect(store.get('bot', 'wecom')).toMatchObject({
94
+ client_id: 'client', owner_id: 'owner', client_secret: 'fake-secret', status: 'connecting',
95
+ });
96
+ expect(store.get('other', 'wecom')).toBeNull();
97
+ // Same client ID on another provider is a separate account.
98
+ expect(bind(store, 'other', { provider: 'feishu' })).toMatchObject({ provider: 'feishu' });
99
+ });
100
+
101
+ it.each(['wecom', 'feishu', 'dingtalk'])('allows independent %s accounts to bind different Bots', (provider) => {
102
+ const store = createAssistantChannelStore(directory());
103
+ cleanup.push(() => store.close());
104
+ bind(store, 'bot-one', { provider, client_id: 'account-one' });
105
+ bind(store, 'bot-two', { provider, client_id: 'account-two' });
106
+ expect(store.get('bot-one', provider)).toMatchObject({ client_id: 'account-one' });
107
+ expect(store.get('bot-two', provider)).toMatchObject({ client_id: 'account-two' });
108
+ expect(() => bind(store, 'bot-three', { provider, client_id: 'account-one' })).toThrow('account_in_use');
109
+ store.unlink('bot-two', provider);
110
+ expect(store.get('bot-one', provider)).toMatchObject({ client_id: 'account-one' });
111
+ });
112
+
113
+ it('deduplicates stable inbound IDs across restart and keeps private routing out of text', () => {
114
+ const dir = directory();
115
+ let store = createAssistantChannelStore(dir);
116
+ const binding = bind(store);
117
+ expect(store.accept(binding, [
118
+ { id: 'm1', text: 'hello', payload: 'meta', target: '{"reply":"opaque"}' },
119
+ { id: 'm1', text: 'duplicate', payload: 'changed', target: '{"reply":"hijack"}' },
120
+ ])).toBe(true);
121
+ expect(store.pending(binding.epoch)).toEqual([
122
+ expect.objectContaining({ id: 'm1', text: 'hello', payload: 'meta', state: 'pending' }),
123
+ ]);
124
+ expect(store.hasReceipt('m1')).toBe(true);
125
+ expect(store.get('bot', 'wecom').target).toBe('{"reply":"opaque"}');
126
+ store.close();
127
+ store = createAssistantChannelStore(dir);
128
+ cleanup.push(() => store.close());
129
+ const restarted = store.get('bot', 'wecom');
130
+ expect(store.accept(restarted, [{ id: 'm1', text: 'replay', payload: '', target: '' }])).toBe(false);
131
+ expect(store.pending(restarted.epoch)).toEqual([
132
+ expect.objectContaining({ id: 'm1', text: 'hello', payload: 'meta' }),
133
+ ]);
134
+ expect(store.get('bot', 'wecom').target).toBe('{"reply":"opaque"}');
135
+ });
136
+
137
+ it('rotates epoch on update but preserves pending work for the same identity', () => {
138
+ const store = createAssistantChannelStore(directory());
139
+ cleanup.push(() => store.close());
140
+ const binding = bind(store);
141
+ store.accept(binding, [{ id: 'm1', text: 'pending', target: '{"reply":"opaque"}' }]);
142
+ const updated = bind(store, 'bot', { client_secret: 'new-secret', language: 'en' });
143
+ expect(updated.epoch).not.toBe(binding.epoch);
144
+ expect(updated).toMatchObject({ client_secret: 'new-secret', language: 'en', status: 'connecting' });
145
+ expect(store.pending(updated.epoch)).toEqual([expect.objectContaining({ id: 'm1', text: 'pending' })]);
146
+ expect(store.get('bot', 'wecom').target).toBe('{"reply":"opaque"}');
147
+ });
148
+
149
+ it('drops the previous owner account queues and routing target on identity change', () => {
150
+ const store = createAssistantChannelStore(directory());
151
+ cleanup.push(() => store.close());
152
+ const binding = bind(store);
153
+ store.accept(binding, [{ id: 'm1', text: 'old owner', target: '{"reply":"old"}' }]);
154
+ store.collect(binding, { generation: 0, ordinal: 1 }, [{ id: 'out', text: 'old reply' }], 2);
155
+ const updated = bind(store, 'bot', {
156
+ client_id: 'new-client', owner_id: 'new-owner', generation: 7, ordinal: 50,
157
+ });
158
+ expect(store.pending(updated.epoch)).toEqual([]);
159
+ expect(store.nextDelivery(updated.epoch)).toBeUndefined();
160
+ expect(store.get('bot', 'wecom')).toMatchObject({
161
+ client_id: 'new-client', owner_id: 'new-owner', target: '', generation: 7, ordinal: 50,
162
+ });
163
+ });
164
+
165
+ it('recovers admitted receipts without replay, marks interrupted sends unknown and clears private text', () => {
166
+ const dir = directory();
167
+ const store = createAssistantChannelStore(dir);
168
+ cleanup.push(() => store.close());
169
+ const binding = bind(store);
170
+ store.accept(binding, [
171
+ { id: 'admitted', text: 'private text', payload: 'private meta', target: '{"reply":"opaque"}' },
172
+ { id: 'pending', text: 'still pending' },
173
+ ]);
174
+ store.markInbox('admitted', 'admitted');
175
+ store.collect(binding, { generation: 0, ordinal: 0 }, [{ id: 'out', text: 'reply' }], 2);
176
+ store.markDelivery('out', 'sending');
177
+ store.recover(binding.epoch, 'interrupted feedback');
178
+ expect(store.pending(binding.epoch)).toEqual([expect.objectContaining({ id: 'pending', text: 'still pending' })]);
179
+ // The earlier indeterminate send stays at the head and is never bypassed.
180
+ expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({
181
+ id: 'out', text: 'reply', state: 'unknown',
182
+ }));
183
+ expect(store.hasUnknown(binding.epoch)).toBe(true);
184
+ const db = new Database(path.join(dir, 'channel.sqlite'));
185
+ cleanup.push(() => db.close());
186
+ expect(db.prepare("SELECT text,payload,state FROM inbox WHERE id='admitted'").get())
187
+ .toEqual({ text: '', payload: '', state: 'done' });
188
+ expect(db.prepare("SELECT text FROM outbox WHERE id='admitted:interrupted'").get().text).toBe('interrupted feedback');
189
+ expect(db.prepare("SELECT state FROM outbox WHERE id='out'").get().state).toBe('unknown');
190
+ // retry re-queues definitively failed rows only; unknown stays unknown.
191
+ store.retry(binding.epoch);
192
+ expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'out', state: 'unknown' }));
193
+ });
194
+
195
+ it('drops queued output from an older transcript generation and keeps stable IDs idempotent', () => {
196
+ const store = createAssistantChannelStore(directory());
197
+ cleanup.push(() => store.close());
198
+ const binding = bind(store);
199
+ store.collect(binding, { generation: 0, ordinal: 1 }, [{ id: 'old', text: 'old' }], 2);
200
+ store.collect(binding, { generation: 1, ordinal: 2 }, [{ id: 'new', text: 'new' }], 3);
201
+ expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'new', text: 'new' }));
202
+ expect(store.get('bot', 'wecom')).toMatchObject({ generation: 1, ordinal: 2 });
203
+ // Replaying the same delivery ID after a restart must not duplicate output.
204
+ store.collect(binding, { generation: 1, ordinal: 2 }, [{ id: 'new', text: 'new' }], 4);
205
+ expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'new' }));
206
+ });
207
+
208
+ it('serializes delivery retries, blocks after repeated definite failure and never clears unknown', () => {
209
+ const store = createAssistantChannelStore(directory());
210
+ cleanup.push(() => store.close());
211
+ const binding = bind(store);
212
+ store.collect(binding, { generation: 0, ordinal: 0 }, [{ id: 'out', text: 'reply' }], 1);
213
+ store.markDelivery('out', 'sending');
214
+ store.failDelivery('out');
215
+ expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'out', state: 'pending' }));
216
+ store.markDelivery('out', 'sending');
217
+ store.failDelivery('out');
218
+ store.markDelivery('out', 'sending');
219
+ store.failDelivery('out');
220
+ expect(store.hasBlocked(binding.epoch)).toBe(true);
221
+ expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'out', state: 'blocked' }));
222
+ store.retry(binding.epoch);
223
+ expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'out', state: 'pending' }));
224
+ store.markDelivery('out', 'unknown');
225
+ store.retry(binding.epoch);
226
+ expect(store.hasUnknown(binding.epoch)).toBe(true);
227
+ expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'out', state: 'unknown' }));
228
+ expect(store.hasReceipt('missing')).toBe(false);
229
+ });
230
+
231
+ it('preserves outbox order behind an unknown send until it is explicitly resolved', () => {
232
+ const store = createAssistantChannelStore(directory());
233
+ cleanup.push(() => store.close());
234
+ const binding = bind(store);
235
+ store.collect(binding, { generation: 0, ordinal: 0 }, [
236
+ { id: 'first', text: 'first' },
237
+ { id: 'second', text: 'second' },
238
+ ], 1);
239
+ store.markDelivery('first', 'unknown');
240
+ expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'first', state: 'unknown' }));
241
+ store.retry(binding.epoch);
242
+ expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'first', state: 'unknown' }));
243
+ store.sent('first');
244
+ expect(store.nextDelivery(binding.epoch)).toEqual(expect.objectContaining({ id: 'second', state: 'pending' }));
245
+ });
246
+
247
+ it('leases one process at a time and expires a dead owner', () => {
248
+ const store = createAssistantChannelStore(directory());
249
+ cleanup.push(() => store.close());
250
+ expect(store.acquire('a', 1_000)).toBe(true);
251
+ expect(store.acquire('b', 1_000)).toBe(false);
252
+ expect(store.owns('a', 1_000)).toBe(true);
253
+ expect(store.owns('b', 1_000)).toBe(false);
254
+ expect(store.acquire('b', 61_000)).toBe(true);
255
+ expect(store.owns('a', 61_000)).toBe(false);
256
+ store.release('b');
257
+ expect(store.owns('b', 61_000)).toBe(false);
258
+ });
259
+
260
+ it('bounds each admission pass to 20 while backlog counts pending and admitted', () => {
261
+ const store = createAssistantChannelStore(directory());
262
+ cleanup.push(() => store.close());
263
+ const binding = bind(store);
264
+ store.accept(binding, Array.from({ length: 25 }, (_, index) => ({ id: `m${index}`, text: 'x' })));
265
+ expect(store.pending(binding.epoch)).toHaveLength(20);
266
+ expect(store.backlog(binding.epoch)).toBe(25);
267
+ store.markInbox('m0', 'admitted');
268
+ expect(store.backlog(binding.epoch)).toBe(25);
269
+ store.finishTurn('m0');
270
+ expect(store.backlog(binding.epoch)).toBe(24);
271
+ });
272
+
273
+ it('forgets every provider for one Bot in one transaction', () => {
274
+ const store = createAssistantChannelStore(directory());
275
+ cleanup.push(() => store.close());
276
+ const wecom = bind(store);
277
+ const feishu = bind(store, 'bot', { provider: 'feishu' });
278
+ store.accept(wecom, [{ id: 'm1', text: 'x' }]);
279
+ store.collect(feishu, { generation: 0, ordinal: 0 }, [{ id: 'out', text: 'y' }], 1);
280
+ store.forget('bot');
281
+ expect(store.get('bot', 'wecom')).toBeNull();
282
+ expect(store.get('bot', 'feishu')).toBeNull();
283
+ expect(store.pending(wecom.epoch)).toEqual([]);
284
+ expect(store.nextDelivery(feishu.epoch)).toBeUndefined();
285
+ });
286
+ });
@@ -0,0 +1,41 @@
1
+ export const channelError = (code, ambiguous = false) => Object.assign(new Error(code), { code, ambiguous });
2
+
3
+ export function officialURL(value, { protocol = 'https:', hosts, path } = {}) {
4
+ let url;
5
+ try { url = new URL(value); } catch { throw channelError('invalid_response'); }
6
+ if (url.protocol !== protocol || !hosts.includes(url.hostname) || url.port || url.username || url.password
7
+ || url.hash || (path && url.pathname !== path)) throw channelError('invalid_response');
8
+ return url.href;
9
+ }
10
+
11
+ export async function requestJSON(url, { body, headers, signal, fetchImpl = fetch, sending = false } = {}) {
12
+ const requestSignal = signal ? AbortSignal.any([signal, AbortSignal.timeout(20_000)]) : AbortSignal.timeout(20_000);
13
+ requestSignal.throwIfAborted();
14
+ let response;
15
+ try {
16
+ response = await fetchImpl(url, { method: 'POST', redirect: 'error', signal: requestSignal,
17
+ headers: { 'Content-Type': 'application/json', ...headers }, body: JSON.stringify(body) });
18
+ } catch { throw channelError(signal?.aborted ? 'cancelled' : 'network_error', sending); }
19
+ if (!response.ok) {
20
+ await response.body?.cancel().catch(() => {});
21
+ throw channelError([401, 403].includes(response.status) ? 'auth_expired' : 'network_error', sending && response.status >= 500);
22
+ }
23
+ if (!response.body) throw channelError('invalid_response', sending);
24
+ const reader = response.body.getReader();
25
+ const chunks = [];
26
+ let size = 0;
27
+ try {
28
+ while (true) {
29
+ requestSignal.throwIfAborted();
30
+ const { done, value } = await reader.read();
31
+ if (done) break;
32
+ size += value.byteLength;
33
+ if (size > 1024 * 1024) throw channelError('invalid_response', sending);
34
+ chunks.push(value);
35
+ }
36
+ return JSON.parse(Buffer.concat(chunks, size).toString('utf8'));
37
+ } catch (error) {
38
+ await reader.cancel().catch(() => {});
39
+ throw error?.code === 'invalid_response' ? error : channelError('invalid_response', sending);
40
+ } finally { reader.releaseLock(); }
41
+ }
@@ -0,0 +1,23 @@
1
+ import { describe, expect, it, vi } from 'vitest';
2
+ import { officialURL, requestJSON } from './transport.js';
3
+
4
+ describe('enterprise channel outbound boundaries', () => {
5
+ it('accepts only explicitly allowed TLS hosts and paths', () => {
6
+ const rules = { hosts: ['open.feishu.cn'], path: '/callback/ws/endpoint' };
7
+ expect(officialURL('https://open.feishu.cn/callback/ws/endpoint', rules)).toContain('open.feishu.cn');
8
+ for (const url of ['http://open.feishu.cn/callback/ws/endpoint', 'https://open.feishu.cn.evil.example/callback/ws/endpoint',
9
+ 'https://user:secret@open.feishu.cn/callback/ws/endpoint', 'https://open.feishu.cn:8443/callback/ws/endpoint',
10
+ 'https://open.feishu.cn/other', 'https://127.0.0.1/callback/ws/endpoint']) expect(() => officialURL(url, rules)).toThrow('invalid_response');
11
+ });
12
+
13
+ it('does not forward raw HTTP errors and bounds JSON bodies', async () => {
14
+ const fetchImpl = vi.fn(async () => new Response('private upstream secret', { status: 403 }));
15
+ await expect(requestJSON('https://example.com', { fetchImpl })).rejects.toMatchObject({ code: 'auth_expired' });
16
+ expect(fetchImpl.mock.calls[0][1].redirect).toBe('error');
17
+ await expect(requestJSON('https://example.com', { sending: true, fetchImpl: async () => { throw new Error('private-token'); } }))
18
+ .rejects.toMatchObject({ code: 'network_error', ambiguous: true });
19
+ await expect(requestJSON('https://example.com', { fetchImpl: async () => new Response('x'.repeat(1024 * 1024 + 1)) }))
20
+ .rejects.toMatchObject({ code: 'invalid_response' });
21
+ });
22
+
23
+ });