stream-chat 10.0.0-rc.2 → 10.0.0-rc.21

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 (298) hide show
  1. package/README.md +11 -8
  2. package/dist/cjs/index.browser.js +15397 -12090
  3. package/dist/cjs/index.browser.js.map +4 -4
  4. package/dist/cjs/index.node.js +15349 -11991
  5. package/dist/cjs/index.node.js.map +4 -4
  6. package/dist/esm/index.mjs +15164 -11880
  7. package/dist/esm/index.mjs.map +4 -4
  8. package/dist/types/ChannelManager.d.ts +246 -6
  9. package/dist/types/CooldownTimer.d.ts +22 -8
  10. package/dist/types/EventHandlerPipeline.d.ts +12 -16
  11. package/dist/types/LiveLocationManager.d.ts +69 -6
  12. package/dist/types/api-client.d.ts +22 -9
  13. package/dist/types/channel.d.ts +550 -300
  14. package/dist/types/channel_state.d.ts +167 -22
  15. package/dist/types/client.d.ts +325 -305
  16. package/dist/types/configuration/ConfigController.d.ts +172 -0
  17. package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +192 -0
  18. package/dist/types/configuration/index.d.ts +3 -0
  19. package/dist/types/configuration/keys.d.ts +31 -0
  20. package/dist/types/configuration/shape.d.ts +58 -0
  21. package/dist/types/configuration/types.d.ts +206 -50
  22. package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +59 -0
  23. package/dist/types/configuration/utils/copyConfigPatch.d.ts +1 -0
  24. package/dist/types/configuration/utils/declarativeSlices.d.ts +24 -0
  25. package/dist/types/configuration/utils/deepFreezeConfig.d.ts +22 -0
  26. package/dist/types/configuration/utils/index.d.ts +1 -0
  27. package/dist/types/configuration/utils/serverAuthority.d.ts +49 -0
  28. package/dist/types/connection/ConnectionIdManager.d.ts +67 -0
  29. package/dist/types/connection/ConnectionRecoveryManager.d.ts +164 -0
  30. package/dist/types/connection/index.d.ts +4 -0
  31. package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +153 -0
  32. package/dist/types/connection/networkConnection/index.d.ts +3 -0
  33. package/dist/types/connection/networkConnection/reporters.d.ts +43 -0
  34. package/dist/types/connection/networkConnection/types.d.ts +55 -0
  35. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +204 -0
  36. package/dist/types/connection/wsConnection/WSConnection.d.ts +168 -0
  37. package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +55 -0
  38. package/dist/types/connection/wsConnection/config.d.ts +51 -0
  39. package/dist/types/connection/wsConnection/index.d.ts +4 -0
  40. package/dist/types/connection/wsConnection/types.d.ts +99 -0
  41. package/dist/types/constants.d.ts +3 -1
  42. package/dist/types/entityStore/EntityStore.d.ts +160 -40
  43. package/dist/types/entityStore/StoreBackedItemIndex.d.ts +48 -29
  44. package/dist/types/entityStore/index.d.ts +0 -1
  45. package/dist/types/errors.d.ts +24 -4
  46. package/dist/types/formatMessageMemo.d.ts +5 -0
  47. package/dist/types/gen/chat/ChannelApi.d.ts +51 -23
  48. package/dist/types/gen/chat/ChatApi.d.ts +215 -168
  49. package/dist/types/gen/models/index.d.ts +2164 -557
  50. package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
  51. package/dist/types/gen/moderation/ModerationApi.d.ts +39 -32
  52. package/dist/types/gen-imports.d.ts +1 -0
  53. package/dist/types/index.d.ts +20 -7
  54. package/dist/types/languageNames.d.ts +97 -0
  55. package/dist/types/logger.d.ts +1 -1
  56. package/dist/types/messageComposer/CustomDataManager.d.ts +7 -1
  57. package/dist/types/messageComposer/LocationComposer.d.ts +10 -4
  58. package/dist/types/messageComposer/attachmentIdentity.d.ts +11 -0
  59. package/dist/types/messageComposer/attachmentManager.d.ts +48 -10
  60. package/dist/types/messageComposer/attachmentUtils.d.ts +34 -0
  61. package/dist/types/messageComposer/configuration/commands.configuration.d.ts +1 -3
  62. package/dist/types/messageComposer/configuration/configuration.d.ts +9 -1
  63. package/dist/types/messageComposer/configuration/index.d.ts +0 -1
  64. package/dist/types/messageComposer/configuration/types.d.ts +57 -1
  65. package/dist/types/messageComposer/index.d.ts +1 -0
  66. package/dist/types/messageComposer/linkPreviewsManager.d.ts +10 -4
  67. package/dist/types/messageComposer/messageComposer.d.ts +210 -14
  68. package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +20 -1
  69. package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +11 -0
  70. package/dist/types/messageComposer/middleware/messageComposer/types.d.ts +2 -2
  71. package/dist/types/messageComposer/middleware/pollComposer/index.d.ts +1 -0
  72. package/dist/types/messageComposer/middleware/pollComposer/state.d.ts +3 -2
  73. package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +9 -2
  74. package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +44 -0
  75. package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +2 -2
  76. package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +94 -229
  77. package/dist/types/messageComposer/pollComposer.d.ts +8 -3
  78. package/dist/types/messageComposer/textComposer.d.ts +9 -1
  79. package/dist/types/messageComposer/types.d.ts +7 -3
  80. package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +64 -8
  81. package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +48 -11
  82. package/dist/types/messageOperations/FailedSendCache.d.ts +34 -0
  83. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +52 -6
  84. package/dist/types/messageOperations/MessageOperations.d.ts +94 -11
  85. package/dist/types/{entityStore → messageOperations}/applyReactionLocally.d.ts +8 -2
  86. package/dist/types/messageOperations/createMessageOperations.d.ts +11 -0
  87. package/dist/types/messageOperations/index.d.ts +7 -1
  88. package/dist/types/messageOperations/reflectReactionEvent.d.ts +24 -0
  89. package/dist/types/messageOperations/sendOrdering.d.ts +17 -0
  90. package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +28 -0
  91. package/dist/types/messageOperations/types.d.ts +66 -1
  92. package/dist/types/middleware.d.ts +8 -0
  93. package/dist/types/moderation.d.ts +18 -4
  94. package/dist/types/notifications/NotificationManager.d.ts +43 -2
  95. package/dist/types/notifications/types.d.ts +55 -42
  96. package/dist/types/offline-support/offline_support_api.d.ts +128 -12
  97. package/dist/types/offline-support/offline_sync_manager.d.ts +26 -5
  98. package/dist/types/offline-support/queueableOperations.d.ts +106 -0
  99. package/dist/types/offline-support/types.d.ts +77 -28
  100. package/dist/types/pagination/FilterBuilder.d.ts +1 -18
  101. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +2 -1
  102. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +21 -3
  103. package/dist/types/pagination/filterCompiler.d.ts +5 -0
  104. package/dist/types/pagination/paginators/BasePaginator.d.ts +331 -7
  105. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +54 -11
  106. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +283 -66
  107. package/dist/types/pagination/paginators/MessagePaginator.d.ts +10 -9
  108. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +17 -1
  109. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +8 -8
  110. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +57 -0
  111. package/dist/types/pagination/paginators/index.d.ts +1 -0
  112. package/dist/types/pagination/utility.normalization.d.ts +29 -2
  113. package/dist/types/poll.d.ts +41 -14
  114. package/dist/types/poll_manager.d.ts +3 -2
  115. package/dist/types/poll_optimistic_votes.d.ts +61 -0
  116. package/dist/types/reminders/Reminder.d.ts +17 -7
  117. package/dist/types/reminders/ReminderManager.d.ts +34 -6
  118. package/dist/types/search/BaseSearchSource.d.ts +50 -25
  119. package/dist/types/search/ChannelMemberSearchSource.d.ts +11 -6
  120. package/dist/types/search/ChannelSearchSource.d.ts +27 -5
  121. package/dist/types/search/MessageSearchSource.d.ts +36 -6
  122. package/dist/types/search/SearchController.d.ts +44 -11
  123. package/dist/types/search/UserSearchSource.d.ts +11 -5
  124. package/dist/types/search/types.d.ts +14 -1
  125. package/dist/types/signing.d.ts +0 -157
  126. package/dist/types/thread.d.ts +118 -62
  127. package/dist/types/thread_manager.d.ts +124 -35
  128. package/dist/types/token_manager.d.ts +5 -8
  129. package/dist/types/types.d.ts +138 -562
  130. package/dist/types/types.utility.d.ts +8 -0
  131. package/dist/types/upload-utils.d.ts +20 -0
  132. package/dist/types/uploadManager.d.ts +50 -2
  133. package/dist/types/utils/FixedSizeQueueCache.d.ts +2 -0
  134. package/dist/types/utils/WithSubscriptions.d.ts +1 -1
  135. package/dist/types/utils/objectPath.d.ts +49 -0
  136. package/dist/types/utils/time.d.ts +85 -0
  137. package/dist/types/utils.d.ts +63 -40
  138. package/package.json +22 -33
  139. package/src/ChannelManager.ts +561 -109
  140. package/src/CooldownTimer.ts +55 -45
  141. package/src/EventHandlerPipeline.ts +13 -23
  142. package/src/LiveLocationManager.ts +191 -37
  143. package/src/api-client.ts +144 -53
  144. package/src/channel.ts +1573 -1050
  145. package/src/channel_state.ts +239 -129
  146. package/src/client.ts +843 -892
  147. package/src/client_state.ts +2 -2
  148. package/src/configuration/ConfigController.ts +298 -0
  149. package/src/configuration/InstanceConfigurationRegistry.ts +430 -0
  150. package/src/configuration/index.ts +7 -0
  151. package/src/configuration/keys.ts +86 -0
  152. package/src/configuration/shape.ts +776 -0
  153. package/src/configuration/types.ts +218 -60
  154. package/src/configuration/utils/applyInstanceConfiguration.ts +184 -0
  155. package/src/configuration/utils/copyConfigPatch.ts +61 -0
  156. package/src/configuration/utils/declarativeSlices.ts +81 -0
  157. package/src/configuration/utils/deepFreezeConfig.ts +33 -0
  158. package/src/configuration/utils/index.ts +5 -0
  159. package/src/configuration/utils/serverAuthority.ts +146 -0
  160. package/src/connection/ConnectionIdManager.ts +153 -0
  161. package/src/connection/ConnectionRecoveryManager.ts +371 -0
  162. package/src/connection/index.ts +4 -0
  163. package/src/connection/networkConnection/NetworkConnectionObserver.ts +281 -0
  164. package/src/connection/networkConnection/index.ts +3 -0
  165. package/src/connection/networkConnection/reporters.ts +85 -0
  166. package/src/connection/networkConnection/types.ts +60 -0
  167. package/src/{connection.ts → connection/wsConnection/StableWSConnection.ts} +242 -151
  168. package/src/connection/wsConnection/WSConnection.ts +345 -0
  169. package/src/connection/wsConnection/WSConnectionFallback.ts +259 -0
  170. package/src/connection/wsConnection/config.ts +108 -0
  171. package/src/connection/wsConnection/index.ts +4 -0
  172. package/src/connection/wsConnection/types.ts +101 -0
  173. package/src/constants.ts +5 -3
  174. package/src/entityStore/EntityStore.ts +350 -10
  175. package/src/entityStore/StoreBackedItemIndex.ts +66 -37
  176. package/src/entityStore/index.ts +0 -1
  177. package/src/errors.ts +40 -7
  178. package/src/formatMessageMemo.ts +23 -0
  179. package/src/gen/chat/ChannelApi.ts +230 -44
  180. package/src/gen/chat/ChatApi.ts +1047 -1745
  181. package/src/gen/models/index.ts +2378 -3721
  182. package/src/gen/models/timestamp-guard.ts +27 -0
  183. package/src/gen/moderation/ModerationApi.ts +218 -388
  184. package/src/gen-imports.ts +1 -0
  185. package/src/index.ts +82 -6
  186. package/src/languageNames.ts +103 -0
  187. package/src/logger.ts +1 -1
  188. package/src/messageComposer/CustomDataManager.ts +10 -1
  189. package/src/messageComposer/LocationComposer.ts +68 -20
  190. package/src/messageComposer/attachmentIdentity.ts +39 -0
  191. package/src/messageComposer/attachmentManager.ts +191 -68
  192. package/src/messageComposer/attachmentUtils.ts +58 -0
  193. package/src/messageComposer/configuration/commands.configuration.ts +1 -26
  194. package/src/messageComposer/configuration/configuration.ts +22 -3
  195. package/src/messageComposer/configuration/index.ts +0 -1
  196. package/src/messageComposer/configuration/types.ts +58 -1
  197. package/src/messageComposer/index.ts +1 -0
  198. package/src/messageComposer/linkPreviewsManager.ts +16 -10
  199. package/src/messageComposer/messageComposer.ts +487 -98
  200. package/src/messageComposer/middleware/attachmentManager/postUpload/AttachmentPostUploadMiddlewareExecutor.ts +1 -1
  201. package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +58 -33
  202. package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +7 -2
  203. package/src/messageComposer/middleware/attachmentManager/preUpload/blockedUploadNotification.ts +3 -2
  204. package/src/messageComposer/middleware/messageComposer/attachments.ts +98 -1
  205. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +20 -10
  206. package/src/messageComposer/middleware/messageComposer/sharedLocation.ts +7 -2
  207. package/src/messageComposer/middleware/messageComposer/types.ts +2 -7
  208. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +11 -6
  209. package/src/messageComposer/middleware/pollComposer/index.ts +1 -0
  210. package/src/messageComposer/middleware/pollComposer/state.ts +43 -11
  211. package/src/messageComposer/middleware/pollComposer/types.ts +9 -2
  212. package/src/messageComposer/middleware/pollComposer/validation.ts +76 -0
  213. package/src/messageComposer/middleware/textComposer/commandUtils.ts +3 -2
  214. package/src/messageComposer/middleware/textComposer/commands.ts +1 -2
  215. package/src/messageComposer/middleware/textComposer/mentions.ts +91 -39
  216. package/src/messageComposer/pollComposer.ts +11 -3
  217. package/src/messageComposer/textComposer.ts +36 -4
  218. package/src/messageComposer/types.ts +19 -14
  219. package/src/messageDelivery/MessageDeliveryReporter.ts +154 -53
  220. package/src/messageDelivery/MessageReceiptsTracker.ts +136 -64
  221. package/src/messageOperations/FailedSendCache.ts +90 -0
  222. package/src/messageOperations/MessageOperationStatePolicy.ts +269 -27
  223. package/src/messageOperations/MessageOperations.ts +340 -136
  224. package/src/{entityStore → messageOperations}/applyReactionLocally.ts +10 -3
  225. package/src/messageOperations/createMessageOperations.ts +192 -0
  226. package/src/messageOperations/index.ts +7 -0
  227. package/src/messageOperations/reflectReactionEvent.ts +51 -0
  228. package/src/messageOperations/sendOrdering.ts +28 -0
  229. package/src/messageOperations/settlePendingAttachmentUploads.ts +110 -0
  230. package/src/messageOperations/types.ts +74 -0
  231. package/src/middleware.ts +11 -0
  232. package/src/moderation.ts +47 -24
  233. package/src/notifications/NotificationManager.ts +73 -3
  234. package/src/notifications/configuration.ts +10 -8
  235. package/src/notifications/types.ts +58 -42
  236. package/src/offline-support/offline_support_api.ts +380 -197
  237. package/src/offline-support/offline_sync_manager.ts +105 -32
  238. package/src/offline-support/queueableOperations.ts +270 -0
  239. package/src/offline-support/types.ts +85 -39
  240. package/src/pagination/FilterBuilder.ts +1 -22
  241. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +11 -7
  242. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +25 -7
  243. package/src/pagination/filterCompiler.ts +17 -0
  244. package/src/pagination/paginators/BasePaginator.ts +731 -81
  245. package/src/pagination/paginators/ChannelPaginator.ts +210 -102
  246. package/src/pagination/paginators/MessageIntervalPaginator.ts +703 -193
  247. package/src/pagination/paginators/MessagePaginator.ts +45 -36
  248. package/src/pagination/paginators/PinnedMessagePaginator.ts +74 -28
  249. package/src/pagination/paginators/ReminderPaginator.ts +15 -13
  250. package/src/pagination/paginators/ThreadPaginator.ts +181 -0
  251. package/src/pagination/paginators/UserGroupPaginator.ts +8 -1
  252. package/src/pagination/paginators/index.ts +1 -0
  253. package/src/pagination/utility.normalization.ts +37 -9
  254. package/src/poll.ts +189 -112
  255. package/src/poll_manager.ts +14 -8
  256. package/src/poll_optimistic_votes.ts +335 -0
  257. package/src/reminders/Reminder.ts +34 -16
  258. package/src/reminders/ReminderManager.ts +68 -41
  259. package/src/reminders/ReminderTimer.ts +7 -6
  260. package/src/search/BaseSearchSource.ts +133 -40
  261. package/src/search/ChannelMemberSearchSource.ts +27 -18
  262. package/src/search/ChannelSearchSource.ts +61 -7
  263. package/src/search/MessageSearchSource.ts +133 -28
  264. package/src/search/SearchController.ts +93 -16
  265. package/src/search/UserSearchSource.ts +27 -13
  266. package/src/search/types.ts +14 -1
  267. package/src/signing.ts +1 -315
  268. package/src/thread.ts +503 -511
  269. package/src/thread_manager.ts +339 -204
  270. package/src/token_manager.ts +12 -32
  271. package/src/types.ts +159 -780
  272. package/src/types.utility.ts +14 -0
  273. package/src/upload-utils.ts +53 -0
  274. package/src/uploadManager.ts +85 -7
  275. package/src/utils/FixedSizeQueueCache.ts +5 -0
  276. package/src/utils/WithSubscriptions.ts +1 -1
  277. package/src/utils/objectPath.ts +67 -0
  278. package/src/utils/time.ts +104 -0
  279. package/src/utils.ts +209 -157
  280. package/dist/types/base64.d.ts +0 -2
  281. package/dist/types/configuration/InstanceConfigurationService.d.ts +0 -26
  282. package/dist/types/connection.d.ts +0 -146
  283. package/dist/types/connection_fallback.d.ts +0 -42
  284. package/dist/types/gen/model-decoders/decoders.d.ts +0 -3
  285. package/dist/types/gen/model-decoders/event-decoder-mapping.d.ts +0 -6
  286. package/dist/types/insights.d.ts +0 -58
  287. package/dist/types/pagination/utility.queryChannel.d.ts +0 -26
  288. package/dist/types/permissions.d.ts +0 -55
  289. package/dist/types/store.d.ts +0 -125
  290. package/src/base64.ts +0 -78
  291. package/src/configuration/InstanceConfigurationService.ts +0 -73
  292. package/src/connection_fallback.ts +0 -215
  293. package/src/gen/model-decoders/decoders.ts +0 -2680
  294. package/src/gen/model-decoders/event-decoder-mapping.ts +0 -198
  295. package/src/insights.ts +0 -83
  296. package/src/pagination/utility.queryChannel.ts +0 -84
  297. package/src/permissions.ts +0 -102
  298. package/src/store.ts +0 -304
@@ -1,10 +1,10 @@
1
1
  import { EventHandlerPipeline } from './EventHandlerPipeline';
2
2
  import { WithSubscriptions } from './utils/WithSubscriptions';
3
- import type { EventType } from './types';
3
+ import type { ChannelInput, ChannelStateResponseFields, EventType } from './types';
4
4
  import type { ChannelPaginator } from './pagination';
5
5
  import type { StreamChat } from './client';
6
- import type { Unsubscribe } from './store';
7
- import { StateStore } from './store';
6
+ import type { Unsubscribe } from '@stream-io/state-store';
7
+ import { StateStore } from '@stream-io/state-store';
8
8
  import type {
9
9
  EventHandlerPipelineHandler,
10
10
  FindEventHandlerParams,
@@ -12,8 +12,14 @@ import type {
12
12
  LabeledEventHandler,
13
13
  PipelineEvent,
14
14
  } from './EventHandlerPipeline';
15
- import { getChannel } from './pagination/utility.queryChannel';
16
- import type { Channel } from './channel';
15
+ import { filterConstrainsField } from './pagination/filterCompiler';
16
+ import { Channel } from './channel';
17
+ import { ChannelWatchStatus } from './channel_state';
18
+ import { generateChannelTempId, getMemberUserId, runDetached } from './utils';
19
+ import { EntityStore } from './entityStore/EntityStore';
20
+ import { chatLoggerSystem } from './logger';
21
+
22
+ const logger = chatLoggerSystem.getLogger('channel-manager');
17
23
 
18
24
  export type ChannelManagerEventHandlerContext = {
19
25
  channelManager: ChannelManager;
@@ -84,28 +90,15 @@ const getCidFromEvent = (event: PipelineEvent): string | undefined => {
84
90
  return event.channel?.cid;
85
91
  };
86
92
 
93
+ // A channel the app disconnected counts as not stored: it stays in the store only until the next
94
+ // `releaseUnusedChannels()`, and an event that makes its cid relevant again gets a live instance.
87
95
  const getCachedChannelFromEvent = (
88
96
  event: PipelineEvent,
89
- cache: Record<string, Channel>,
97
+ channelManager: ChannelManager,
90
98
  ): Channel | undefined => {
91
99
  const cid = getCidFromEvent(event);
92
- return cid ? cache[cid] : undefined;
93
- };
94
-
95
- const reEmit: EventHandlerPipelineHandler<EventHandlerContext> = ({
96
- event,
97
- ctx: { channelManager },
98
- }) => {
99
- if (!event.cid) return;
100
- const channel = channelManager.client.activeChannels[event.cid];
101
- if (!channel) return;
102
- channelManager.paginators.forEach((paginator) => {
103
- const items = paginator.items;
104
- const { state } = paginator.locateByItem(channel);
105
- if ((state?.currentIndex ?? -1) > -1 && items) {
106
- paginator.state.partialNext({ items: [...items] });
107
- }
108
- });
100
+ const channel = cid ? channelManager.get(cid) : undefined;
101
+ return channel?.pendingDisposal ? undefined : channel;
109
102
  };
110
103
 
111
104
  const removeItem: EventHandlerPipelineHandler<EventHandlerContext> = ({
@@ -116,7 +109,7 @@ const removeItem: EventHandlerPipelineHandler<EventHandlerContext> = ({
116
109
  // `event.channel` only, and the legacy ChannelManager removed by `event.cid || event.channel?.cid`
117
110
  const cid = getCidFromEvent(event);
118
111
  if (!cid) return;
119
- const channel = channelManager.client.activeChannels[cid];
112
+ const channel = channelManager.get(cid);
120
113
  channelManager.paginators.forEach((paginator) => {
121
114
  paginator.removeItem({ id: cid, item: channel });
122
115
  });
@@ -127,81 +120,95 @@ const removeItem: EventHandlerPipelineHandler<EventHandlerContext> = ({
127
120
  export const ignoreEventsForUnknownChannels: EventHandlerPipelineHandler<
128
121
  EventHandlerContext
129
122
  > = ({ event, ctx: { channelManager } }) => {
130
- const channel: Channel | undefined = getCachedChannelFromEvent(
131
- event,
132
- channelManager.client.activeChannels,
133
- );
123
+ const channel = getCachedChannelFromEvent(event, channelManager);
134
124
  if (!channel) return { action: 'stop' };
135
125
  };
136
126
 
127
+ /**
128
+ * Restore a watch this client held and lost to a dropped socket.
129
+ *
130
+ * The server keys watches by connection ID, so a reconnect ends every watch the previous connection
131
+ * held. Reconnect recovery re-watches the first page of each list plus the active channel; everything
132
+ * else stays `WasWatching` — pages 2+ of a scrolled list, channels visited and navigated away from,
133
+ * channels matching no mounted list. Such a channel still receives member-level events (e.g.
134
+ * `notification.message_new`), which relocate its row but carry no message body, so its preview would
135
+ * sit frozen until the channel was opened. Re-watching it the moment an event proves it relevant is
136
+ * what closes that gap, without ever eagerly re-watching the whole cache.
137
+ *
138
+ * The request is idempotent, so a successful watch flips the status to `Watching`, and
139
+ * `ensureWatched()` joins a watch it already has in flight, so a burst of events cannot produce a
140
+ * burst of requests.
141
+ */
142
+ const restoreInterruptedWatch = (channel: Channel) => {
143
+ // a disposed channel refuses requests, and its `ensureWatched()` would reject
144
+ if (channel.pendingDisposal) return;
145
+ if (channel.watchStatus !== ChannelWatchStatus.WasWatching) return;
146
+
147
+ runDetached(channel.ensureWatched(), {
148
+ context: `restoreInterruptedWatch(${channel.cid})`,
149
+ });
150
+ };
151
+
137
152
  const updateLists: EventHandlerPipelineHandler<EventHandlerContext> = async ({
138
153
  event,
139
154
  ctx: { channelManager },
140
155
  }) => {
141
- let channel: Channel | undefined = getCachedChannelFromEvent(
142
- event,
143
- channelManager.client.activeChannels,
144
- );
156
+ let channel: Channel | undefined = getCachedChannelFromEvent(event, channelManager);
145
157
 
146
158
  if (!channel) {
147
159
  const [type, id] = getCidFromEvent(event)?.split(':') ?? [];
148
160
  if (!type) return;
149
161
 
150
- channel = await getChannel({
151
- client: channelManager.client,
152
- id,
153
- type,
154
- });
162
+ channel = await channelManager.ensure({ id, type }).ensureWatched();
155
163
  }
156
164
 
157
165
  if (!channel) return;
158
166
 
159
- const matchingPaginators = channelManager.paginators.filter((p) =>
160
- p.matchesFilter(channel),
161
- );
162
- const matchingIds = new Set(matchingPaginators.map((p) => p.id));
163
-
164
- const ownerIds = channelManager.resolveOwnership(channel, matchingPaginators);
165
-
166
- channelManager.paginators.forEach((paginator) => {
167
- if (!matchingIds.has(paginator.id)) {
168
- // remove if it does not match the filter anymore
169
- paginator.removeItem({ item: channel });
170
- return;
171
- }
167
+ routeToPaginators(channelManager, channel);
172
168
 
173
- // Only if owners are specified, the items is removed from the non-owner matching paginators
174
- if (ownerIds.size > 0 && !ownerIds.has(paginator.id)) {
175
- // matched, but not selected to own - remove to enforce exclusivity
176
- paginator.removeItem({ item: channel });
177
- return;
178
- }
169
+ // AFTER routing, and not awaited: the row relocates immediately off the event, and the watch (plus
170
+ // the state it hydrates) lands whenever it lands. `channel.hidden` is excluded — a channel being
171
+ // hidden is the one routed event that must not resurrect a watch.
172
+ if (event.type !== 'channel.hidden') {
173
+ restoreInterruptedWatch(channel);
174
+ }
175
+ };
179
176
 
180
- // Selected owner: ingest. The manager never boosts by default on any event — the sort is the
181
- // single source of truth for order, so a channel that just became relevant (new message, added,
182
- // unhidden) relocates via its updated sort key. Boosting remains a public per-paginator primitive
183
- // (`paginator.boost`) for integrators to opt into for specific channels (VIP/mention/deep-link).
184
- paginator.ingestItem(channel);
185
- });
177
+ /**
178
+ * Re-inserts a loaded channel whose data changed in place (`channel.updated`, `channel.truncated`), so
179
+ * a list sorted or filtered by a changed field moves or drops it. Channels that aren't loaded are
180
+ * ignored: these events don't make an unknown channel relevant.
181
+ */
182
+ const reinsertItem: EventHandlerPipelineHandler<EventHandlerContext> = ({
183
+ event,
184
+ ctx: { channelManager },
185
+ }) => {
186
+ const channel = getCachedChannelFromEvent(event, channelManager);
187
+ if (!channel) return;
188
+ routeToPaginators(channelManager, channel);
186
189
  };
187
190
 
188
- // we have to make sure that client.activeChannels is always up-to-date
191
+ /** Ingests `channel` into the lists that match and own it, and removes it from the rest. */
192
+ function routeToPaginators(channelManager: ChannelManager, channel: Channel) {
193
+ // The manager never boosts by default on any event — the sort is the single source of truth for
194
+ // order, so a channel that just became relevant (new message, added, unhidden) relocates via its
195
+ // updated sort key. Boosting remains a public per-paginator primitive (`paginator.boost`) for
196
+ // integrators to opt into for specific channels (VIP/mention/deep-link).
197
+ channelManager.ingestChannel(channel);
198
+ }
199
+
189
200
  const channelDeletedHandler: LabeledEventHandler<EventHandlerContext> = {
190
201
  handle: removeItem,
191
202
  id: 'ChannelManager:default-handler:channel.deleted',
192
203
  };
193
204
 
194
- // fixme: this handler should not be handled by the channel manager but as Channel does not have reactive state,
195
- // we need to re-emit the whole list to reflect the changes
196
205
  const channelUpdatedHandler: LabeledEventHandler<EventHandlerContext> = {
197
- handle: reEmit,
206
+ handle: reinsertItem,
198
207
  id: 'ChannelManager:default-handler:channel.updated',
199
208
  };
200
209
 
201
- // fixme: this handler should not be handled by the channel manager but as Channel does not have reactive state,
202
- // we need to re-emit the whole list to reflect the changes
203
210
  const channelTruncatedHandler: LabeledEventHandler<EventHandlerContext> = {
204
- handle: reEmit,
211
+ handle: reinsertItem,
205
212
  id: 'ChannelManager:default-handler:channel.truncated',
206
213
  };
207
214
 
@@ -227,6 +234,50 @@ const messageNewHandler: LabeledEventHandler<EventHandlerContext> = {
227
234
  id: 'ChannelManager:default-handler:message.new',
228
235
  };
229
236
 
237
+ /**
238
+ * Sort fields the channel list's sort resolver resolves from read state. `SortParamRequest.field` is an open
239
+ * string, so there is no type enumerating them.
240
+ */
241
+ const READ_STATE_SORT_FIELDS: string[] = ['has_unread', 'unread_count'];
242
+
243
+ /**
244
+ * Whether a read can change this list at all: its membership (`has_unread` filter) or its order
245
+ * (`has_unread` / `unread_count` sort). Unread badges read `channel.state` directly, so nothing else
246
+ * about the list depends on it.
247
+ */
248
+ const dependsOnReadState = (paginator: ChannelPaginator) =>
249
+ paginator.effectiveSort.some(
250
+ ({ field }) => !!field && READ_STATE_SORT_FIELDS.includes(field),
251
+ ) || filterConstrainsField(paginator.buildMatchFilters(), 'has_unread');
252
+
253
+ /**
254
+ * Re-routes a channel whose read state changed. `message.read` only reaches watchers, so
255
+ * `notification.mark_*` is the only signal for channels the user is not watching.
256
+ *
257
+ * Never fetches, unlike `updateLists`: a read cannot make an unknown channel belong to a list, and
258
+ * these events are far too frequent to query on.
259
+ */
260
+ const readStateChangedHandler: LabeledEventHandler<EventHandlerContext> = {
261
+ handle: ({ event, ctx: { channelManager } }) => {
262
+ const { client } = channelManager;
263
+ // another member's read receipt says nothing about this user's unread state
264
+ if (event.type === 'message.read' && event.user?.id !== client.userId) return;
265
+
266
+ // a thread read says nothing about the channel's own read state
267
+ if (event.thread_id) return;
268
+
269
+ // a mark-all-read names no channel, so there is no target to route
270
+ const channel = getCachedChannelFromEvent(event, channelManager);
271
+ if (!channel) return;
272
+
273
+ // hot path: `message.read` fires on every channel the user opens
274
+ if (!channelManager.paginators.some(dependsOnReadState)) return;
275
+
276
+ channelManager.ingestChannel(channel);
277
+ },
278
+ id: 'ChannelManager:default-handler:read-state-changed',
279
+ };
280
+
230
281
  const notificationAddedToChannelHandler: LabeledEventHandler<EventHandlerContext> = {
231
282
  handle: updateLists,
232
283
  id: 'ChannelManager:default-handler:notification.added_to_channel',
@@ -262,34 +313,6 @@ const notificationChannelMutesUpdatedHandler: LabeledEventHandler<EventHandlerCo
262
313
  id: 'ChannelManager:default-handler:notification.channel_mutes_updated',
263
314
  };
264
315
 
265
- // fixme: updates users for member object in all the channels which are loaded with that member - normalization would be beneficial
266
- const userPresenceChangedHandler: LabeledEventHandler<EventHandlerContext> = {
267
- handle: ({ event, ctx: { channelManager } }) => {
268
- const eventUser = event.user;
269
- if (!eventUser?.id) return;
270
- channelManager.paginators.forEach((paginator) => {
271
- const paginatorItems = paginator.items;
272
- if (!paginatorItems) return;
273
- let updated = false;
274
- paginatorItems.forEach((channel) => {
275
- if (channel.state.members[eventUser.id]) {
276
- channel.state.members[eventUser.id].user = event.user;
277
- updated = true;
278
- }
279
- if (channel.state.membership.user?.id === eventUser.id) {
280
- channel.state.membership.user = eventUser;
281
- updated = true;
282
- }
283
- });
284
- if (updated) {
285
- // fixme: user is not reactive and so the whole list has to be re-rendered
286
- paginator.state.partialNext({ items: [...paginatorItems] });
287
- }
288
- });
289
- },
290
- id: 'ChannelManager:default-handler:user.presence.changed',
291
- };
292
-
293
316
  export type ChannelManagerState = {
294
317
  paginators: ChannelPaginator[];
295
318
  };
@@ -318,14 +341,58 @@ export type ChannelManagerOptions = {
318
341
  ownershipResolver?: PaginatorOwnershipResolver | string[];
319
342
  };
320
343
 
344
+ /**
345
+ * A stored channel, the key it is stored under, and what keeps it: its own state (`'watched'`,
346
+ * `'active'`, `'querying-channel'`) and the names of its holders. None: a call to
347
+ * `releaseUnusedChannels()` would remove it.
348
+ */
349
+ export type ChannelUsage = {
350
+ channel: Channel;
351
+ key: string;
352
+ keptBy: string[];
353
+ };
354
+
355
+ /** What in the channel's own state keeps it in the channel store. */
356
+ const keptByOwnState = (channel: Channel) => {
357
+ const reasons: string[] = [];
358
+ if (channel.watchStatus !== ChannelWatchStatus.NotWatching) reasons.push('watched');
359
+ if (channel.active) reasons.push('active');
360
+ if (channel.isQueryingChannel) reasons.push('querying-channel');
361
+ return reasons;
362
+ };
363
+
321
364
  export class ChannelManager extends WithSubscriptions {
322
365
  client: StreamChat;
323
366
  state: StateStore<ChannelManagerState>;
367
+ /**
368
+ * Every `Channel` instance, one per cid. A channel created from members, before the server assigns
369
+ * its id, is stored under its temporary cid until {@link ChannelManager.changeChannelId} moves it.
370
+ * A channel stays until a known end (deleted, or the current user removed from it) or logout removes
371
+ * it, or the app calls {@link ChannelManager.releaseUnusedChannels} while it is disconnected, or
372
+ * neither watched nor held; each removes it and runs its {@link Channel.disconnect}. A channel
373
+ * list holds the channels it shows by linking them, which also tells it about removals and cid
374
+ * changes; other users hold theirs through claims.
375
+ *
376
+ * @internal
377
+ */
378
+ readonly channelStore = new EntityStore<Channel>({
379
+ getEntityId: (channel) => channel.cid,
380
+ onRelease: (channel) => channel.disconnect(),
381
+ releaseOnLastUnlink: false,
382
+ });
383
+
324
384
  protected _pipelines = new Map<
325
385
  SupportedEventType,
326
386
  EventHandlerPipeline<EventHandlerContext>
327
387
  >();
328
388
  protected ownershipResolver?: PaginatorOwnershipResolver;
389
+ /**
390
+ * Instances replaced by a stored one ({@link ChannelManager.supersedeChannel}). Not in the store, so
391
+ * they are tracked here to be disconnected ({@link Channel.disconnect}) at logout
392
+ * ({@link ChannelManager.clearChannels}). Nothing disconnects them earlier, as the app may still hold
393
+ * them.
394
+ */
395
+ private readonly supersededChannels = new Set<Channel>();
329
396
  /**
330
397
  * The `filterQueryResults` each registered paginator had before this manager wrapped it.
331
398
  *
@@ -351,11 +418,14 @@ export class ChannelManager extends WithSubscriptions {
351
418
  'channel.visible': [channelVisibleHandler],
352
419
  'member.updated': [memberUpdatedHandler],
353
420
  'message.new': [messageNewHandler],
421
+ 'message.read': [readStateChangedHandler],
422
+ 'message.read_locally': [readStateChangedHandler],
354
423
  'notification.added_to_channel': [notificationAddedToChannelHandler],
355
424
  'notification.channel_mutes_updated': [notificationChannelMutesUpdatedHandler],
425
+ 'notification.mark_read': [readStateChangedHandler],
426
+ 'notification.mark_unread': [readStateChangedHandler],
356
427
  'notification.message_new': [notificationMessageNewHandler],
357
428
  'notification.removed_from_channel': [notificationRemovedFromChannelHandler],
358
- 'user.presence.changed': [userPresenceChangedHandler],
359
429
  };
360
430
 
361
431
  constructor({
@@ -383,6 +453,341 @@ export class ChannelManager extends WithSubscriptions {
383
453
  return this.state.getLatestValue().paginators;
384
454
  }
385
455
 
456
+ /** The stored channel for `cid`, if any. */
457
+ get(cid: string): Channel | undefined {
458
+ return this.channelStore.get(cid);
459
+ }
460
+
461
+ /**
462
+ * The instance a channel list should show for `channel`: the one that superseded it, else the one
463
+ * stored under its cid, else `channel` itself. A list never puts another instance in place of the
464
+ * stored one, which would leave the stored one out of the store, unfinished and without events.
465
+ * `undefined` when that instance is disconnected (`pendingDisposal`), stored or not: it receives
466
+ * no events, and a list that already shows it drops it at the next `releaseUnusedChannels()`.
467
+ *
468
+ * @internal
469
+ */
470
+ resolveListedChannel(channel: Channel): Channel | undefined {
471
+ const candidate = channel.supersededBy ?? channel;
472
+ const stored = this.get(candidate.cid);
473
+ const resolved = stored ?? candidate;
474
+ if (resolved.pendingDisposal) return undefined;
475
+ if (resolved !== channel) {
476
+ logger
477
+ .withExtraTags('resolveListedChannel', channel.cid)
478
+ .warn(
479
+ 'A channel list was given an instance other than the stored one; listing the stored one.',
480
+ );
481
+ }
482
+ return resolved;
483
+ }
484
+
485
+ /** Every stored channel. */
486
+ values(): Channel[] {
487
+ return this.channelStore.values();
488
+ }
489
+
490
+ /**
491
+ * Returns the channel for `type` and `id`, creating it if it isn't stored yet. Use this to get a
492
+ * channel instead of calling `new Channel()`; there is one instance per cid. A stored channel
493
+ * already disconnected (`pendingDisposal`) is replaced by a fresh one.
494
+ *
495
+ * Leave out `id` and pass `data.members` for a distinct channel between those members (one channel
496
+ * per set of members). It is stored under a temporary cid built from the member IDs until
497
+ * `watch()`, `query()` or `create()` returns the real one; a stored distinct channel with the same
498
+ * loaded members is returned instead. If another instance holds the real cid by then (its members
499
+ * weren't loaded, or an event stored it meanwhile), that instance stays stored and this one is
500
+ * left unstored. A group with the same members as another needs its own `id` instead.
501
+ *
502
+ * A channel created from members is {@link Channel.isProvisional} until its query is answered: it
503
+ * has no id yet, so nothing but that query can be sent for it. A channel with an id is not, even one
504
+ * whose id the app generated and the server doesn't have yet: requests for it go to the server.
505
+ *
506
+ * A channel got this way stays stored until it is deleted, the current user is removed from it, or
507
+ * the user logs out. The SDK never releases it on its own; an app freeing memory calls
508
+ * {@link ChannelManager.releaseUnusedChannels}, which releases it only while nothing uses it.
509
+ *
510
+ * ```ts
511
+ * const general = client.channelManager.ensure({ type: 'messaging', id: 'general' });
512
+ * const dm = client.channelManager.ensure({
513
+ * type: 'messaging',
514
+ * data: { members: [{ user_id: 'ann' }, { user_id: 'bob' }] },
515
+ * });
516
+ * await dm.watch();
517
+ * ```
518
+ *
519
+ * @param params.type - The channel type.
520
+ * @param params.id - The channel ID; leave it out for a distinct channel created from members.
521
+ * @param params.data - Data for a new channel (members, custom fields). For a stored channel only
522
+ * `data.custom` is applied.
523
+ * @returns The channel; initialize it with `channel.watch()`.
524
+ */
525
+ ensure({
526
+ data = {},
527
+ id,
528
+ type,
529
+ }: {
530
+ type: string;
531
+ id?: string | null;
532
+ data?: ChannelInput;
533
+ }): Channel {
534
+ const { client } = this;
535
+ if (!client.userId) {
536
+ throw Error('Call connectUser or connectAnonymousUser before creating a channel');
537
+ }
538
+ if (type.includes(':')) {
539
+ throw new Error(`Invalid channel group ${type}, can't contain the : character`);
540
+ }
541
+ if (id) return this.ensureById(type, id, data);
542
+ if (data.members?.length) return this.ensureByMembers(type, data);
543
+ return new Channel(client, type, undefined, data);
544
+ }
545
+
546
+ private ensureById(type: string, id: string, data: ChannelInput): Channel {
547
+ if (id.includes(':')) {
548
+ throw Error(`Invalid channel id ${id}, can't contain the : character`);
549
+ }
550
+
551
+ const cid = `${type}:${id}`;
552
+ if (this.get(cid)?.pendingDisposal) this.removeChannel(cid);
553
+
554
+ return this.getOrCreateChannel(
555
+ cid,
556
+ () => new Channel(this.client, type, id, data),
557
+ (channel) => {
558
+ // Only `custom` is applied to a stored channel, and only when the caller passed it: other
559
+ // fields (e.g. `{ members }`) would otherwise wipe its existing custom data, such as its name.
560
+ if (data.custom !== undefined) {
561
+ channel.data = { ...channel.data, custom: data.custom };
562
+ channel._data = { ...channel._data, custom: data.custom };
563
+ }
564
+ },
565
+ );
566
+ }
567
+
568
+ private ensureByMembers(type: string, data: ChannelInput): Channel {
569
+ // the id `Channel` gives itself until the server answers, from the same members
570
+ const tempId = generateChannelTempId((data.members ?? []).map(getMemberUserId));
571
+ if (!tempId) {
572
+ throw Error('Please specify atleast one member when creating unique conversation');
573
+ }
574
+ const tempCid = `${type}:${tempId}`;
575
+
576
+ // Stored under the temporary cid until the server returns the real one, then under the real
577
+ // cid, whose id for a distinct channel starts with `!members-`. A loaded one with the same
578
+ // members is that conversation.
579
+ if (this.get(tempCid)?.pendingDisposal) this.removeChannel(tempCid);
580
+ if (!this.get(tempCid)) {
581
+ const existing = this.values().find(
582
+ (channel) =>
583
+ !channel.pendingDisposal &&
584
+ channel.type === type &&
585
+ channel.id?.startsWith('!members-') &&
586
+ generateChannelTempId(Object.keys(channel.state.members)) === tempId,
587
+ );
588
+ if (existing) return existing;
589
+ }
590
+
591
+ return this.getOrCreateChannel(
592
+ tempCid,
593
+ () => new Channel(this.client, type, undefined, data),
594
+ );
595
+ }
596
+
597
+ /**
598
+ * Returns the channel stored under `cid`, passing it to `hydrate`, or stores and returns the result
599
+ * of `create`.
600
+ *
601
+ * @internal
602
+ */
603
+ getOrCreateChannel(
604
+ cid: string,
605
+ create: () => Channel,
606
+ hydrate?: (stored: Channel) => void,
607
+ ): Channel {
608
+ return this.channelStore.getOrCreate(cid, create, hydrate);
609
+ }
610
+
611
+ /**
612
+ * Moves a channel from its temporary cid to the one the server assigned (see `Channel.query`).
613
+ * Returns `false` when `oldCid` isn't stored or `newCid` already holds another channel.
614
+ *
615
+ * @internal
616
+ */
617
+ changeChannelId(oldCid: string, newCid: string): boolean {
618
+ return this.channelStore.changeId(oldCid, newCid);
619
+ }
620
+
621
+ /**
622
+ * `previous`, created without an id, was answered with a cid `successor` already holds (stored by an
623
+ * event or a channel list while `previous` waited). `successor` stays the one instance for the cid
624
+ * and takes over, without losing anything of its own:
625
+ *
626
+ * - the server's response, as a `queryChannels` result for a stored channel is applied: its data
627
+ * and members, and its messages merged into the loaded ones (a local message, such as a failed
628
+ * one, is never removed; an open channel's or a scrolled-back one's window isn't re-seeded);
629
+ * - `previous`'s local messages (sending or failed), added by id; a message `successor` already has
630
+ * keeps `successor`'s copy;
631
+ * - `previous`'s composer, when `previous` is open and `successor` isn't: the user is typing in
632
+ * `previous`, and nobody in `successor`. When both are open, neither composer is overwritten.
633
+ *
634
+ * `successor` is marked watched only when the query asked to watch (`watch: true`): the server then
635
+ * watches the cid for this connection. A query without a watch leaves its watch status as it was.
636
+ *
637
+ * `previous`'s own entry (`storedUnder`, its temporary cid) is dropped first, without disconnecting
638
+ * it: its query is still being applied to it and it may be on screen. It is marked superseded
639
+ * (`state.supersededBy`) so its holders switch over, and tracked here until logout, so the SDK
640
+ * never loses track of it.
641
+ *
642
+ * @internal
643
+ */
644
+ supersedeChannel(
645
+ previous: Channel,
646
+ successor: Channel,
647
+ response: ChannelStateResponseFields,
648
+ { storedUnder, watch }: { storedUnder?: string; watch?: boolean } = {},
649
+ ) {
650
+ if (storedUnder && this.get(storedUnder) === previous) {
651
+ this.channelStore.detach(storedUnder);
652
+ }
653
+ // `false`, not `undefined`: `hydrateChannels` would take a missing `watch` as "watched if
654
+ // connected", and this query may not have asked the server to watch
655
+ this.client.hydrateChannels([response], {}, { watch: watch === true });
656
+ successor.messagePaginator.batch(
657
+ () => {
658
+ for (const message of previous.messagePaginator.items ?? []) {
659
+ if (message.status === 'received') continue;
660
+ if (successor.messagePaginator.getItem(message.id)) continue;
661
+ // composed in `previous`, it carries `previous`'s temporary cid
662
+ successor.messagePaginator.ingestItem({ ...message, cid: successor.cid });
663
+ }
664
+ },
665
+ { coalesce: true },
666
+ );
667
+ if (previous.active && !successor.active) {
668
+ previous.messageComposer.transferTo(successor.messageComposer);
669
+ }
670
+ previous.state.partialNext({ supersededBy: successor });
671
+ this.supersededChannels.add(previous);
672
+ }
673
+
674
+ /**
675
+ * Removes every stored channel the app disconnected ({@link Channel.disconnect}, so
676
+ * `pendingDisposal`), whatever still holds or uses it: disconnecting says the app is done with
677
+ * it.
678
+ * Every list showing it drops it, as the store's removal reaches each list's index. Objects that
679
+ * still refer to the instance keep it, finished.
680
+ *
681
+ * Then removes, and disconnects, every stored channel that is neither watched nor held. A watched
682
+ * channel (`watching`,
683
+ * or `wasWatching` until its watch is restored) stays, because its events keep it current; so does
684
+ * an active one ({@link Channel.activate}), one being loaded (`watch()`, `query()` or `create()` in flight), and
685
+ * one a holder holds in {@link ChannelManager.channelStore}: a channel list links each of its
686
+ * channels, while threads, the composer cache and an active channel search hold theirs through
687
+ * claims ({@link EntityStore.addClaim}).
688
+ *
689
+ * What remains is an unwatched snapshot nothing shows, which saves no request: using it again
690
+ * needs a query, which stores it again.
691
+ *
692
+ * The SDK never calls this: it can't see the channels an app keeps in its own state, such as a
693
+ * stopped watch kept for re-entry or search results held after the search ended. Call it when the
694
+ * app is done with what it held, for example after closing a search screen
695
+ * (`searchController.dispose()`, then this). A channel your code still uses but that none of the
696
+ * above keeps would be released, so keep it with {@link Channel.activate} first.
697
+ */
698
+ releaseUnusedChannels() {
699
+ for (const [key, channel] of this.channelStore.entries()) {
700
+ if (channel.pendingDisposal) this.removeChannel(key);
701
+ }
702
+ for (const [key, channel] of this.channelStore.unheldEntries()) {
703
+ if (!keptByOwnState(channel).length) this.removeChannel(key);
704
+ }
705
+ }
706
+
707
+ /**
708
+ * Every stored channel with what keeps it, by the same rule as
709
+ * {@link ChannelManager.releaseUnusedChannels}: a channel kept by nothing would be released by a
710
+ * call to it. For debugging tools.
711
+ *
712
+ * @internal
713
+ */
714
+ getChannelUsage(): ChannelUsage[] {
715
+ return this.channelStore.entries().map(([key, channel]) => ({
716
+ channel,
717
+ key,
718
+ keptBy: [...keptByOwnState(channel), ...this.channelStore.holderNames(key)],
719
+ }));
720
+ }
721
+
722
+ /**
723
+ * Removes the channel stored under `cid` whatever uses it, and disconnects it
724
+ * ({@link Channel.disconnect}).
725
+ * Every list showing it drops it too, as the store's removal reaches each list's index.
726
+ *
727
+ * @internal
728
+ */
729
+ removeChannel(cid: string) {
730
+ this.channelStore.remove(cid);
731
+ }
732
+
733
+ /**
734
+ * Removes and disconnects ({@link Channel.disconnect}) every stored channel, and every superseded
735
+ * one.
736
+ *
737
+ * @internal
738
+ */
739
+ clearChannels() {
740
+ this.channelStore.clear();
741
+ this.supersededChannels.forEach((channel) => channel.disconnect());
742
+ this.supersededChannels.clear();
743
+ }
744
+
745
+ /**
746
+ * Fans the client-owned `mutedChannels` out to every stored channel's reactive `state.muteStatus`.
747
+ * Each channel republishes only when its own mute status actually changed, so this stays cheap on
748
+ * the frequent `health.check` path.
749
+ *
750
+ * @internal
751
+ */
752
+ reflectMutedChannels() {
753
+ for (const channel of this.values()) channel._syncMuteStatus();
754
+ }
755
+
756
+ /**
757
+ * Resets the AI indicator state to `Idle` on every stored channel. Invoked from `closeConnection`
758
+ * as it's a deliberate shutdown and will not natively trigger a WS event.
759
+ *
760
+ * @internal
761
+ */
762
+ resetAIStateOnChannels() {
763
+ for (const channel of this.values()) channel.state.resetAIState();
764
+ }
765
+
766
+ /**
767
+ * Demotes every actively-watched channel to `WasWatching`. The server keys watches by connection
768
+ * ID, so losing the socket ends every watch this client held — a reconnect issues a NEW id and the
769
+ * channels have to be re-queried to watch again. `WasWatching` is what records that they should be.
770
+ *
771
+ * Only `Watching` is demoted: a channel the consumer stopped on purpose, or one already
772
+ * disconnected (`disconnect()`), stays `NotWatching` and must not be resurrected by a reconnect.
773
+ *
774
+ * Invoked from two places on the WebSocket, because neither covers the other:
775
+ * `StableWSConnection._setHealth(false)` for an abnormal close/error, and `closeConnection()` for a
776
+ * deliberate shutdown (e.g. mobile backgrounding), whose `disconnect()` writes the status through
777
+ * `_applyHealth` and so never reaches `_setHealth`. After an `enableWSFallback` switch the
778
+ * long-poll calls it too, from `WSConnectionFallback._setState()` whenever going closed or
779
+ * disconnected takes the status offline.
780
+ *
781
+ * @internal
782
+ */
783
+ markChannelsWatchInterrupted() {
784
+ for (const channel of this.values()) {
785
+ if (channel.watchStatus === ChannelWatchStatus.Watching) {
786
+ channel.watchStatus = ChannelWatchStatus.WasWatching;
787
+ }
788
+ }
789
+ }
790
+
386
791
  get pipelines(): Map<SupportedEventType, EventHandlerPipeline<EventHandlerContext>> {
387
792
  return this._pipelines;
388
793
  }
@@ -443,26 +848,42 @@ export class ChannelManager extends WithSubscriptions {
443
848
  *
444
849
  * Use this to surface a channel the app just opened — a search result, a freshly created DM —
445
850
  * in the list(s) without a full re-query. `ingestItem` dedupes by cid and inserts in sort
446
- * order, so calling this repeatedly is safe.
851
+ * order, so calling this repeatedly is safe. A channel created from members is ignored until its
852
+ * first query gives it an id: ingest it once `watch()` (or `ensureWatched()`) resolves.
447
853
  *
448
854
  * A channel that matches no paginator is not added anywhere. To have such channels still
449
855
  * appear, register a catch-all paginator (empty filter) with the lowest ownership priority as
450
856
  * a local fallback list.
451
857
  */
452
- ingestChannel(channel: Channel) {
858
+ ingestChannel(input: Channel) {
859
+ // not listed until it has its id (see `ChannelPaginator.ingestItem`)
860
+ if (input.isProvisional) return;
861
+ const channel = this.resolveListedChannel(input);
862
+ if (!channel) return;
453
863
  const matchingPaginators = this.paginators.filter((p) => p.matchesFilter(channel));
454
- const matchingIds = new Set(matchingPaginators.map((p) => p.id));
864
+ const matchingPaginatorIds = new Set(matchingPaginators.map((p) => p.id));
455
865
  const ownerIds = this.resolveOwnership(channel, matchingPaginators);
456
866
 
867
+ for (const paginator of this.paginators) {
868
+ const isOwner =
869
+ matchingPaginatorIds.has(paginator.id) &&
870
+ (ownerIds.size === 0 || ownerIds.has(paginator.id));
871
+ if (isOwner) paginator.ingestItem(channel);
872
+ else paginator.removeItem({ item: channel });
873
+ }
874
+ }
875
+
876
+ /**
877
+ * Drops a channel from the lists whose filters it no longer matches, adding it nowhere.
878
+ *
879
+ * For state the client changes without an event naming the channel — zeroing every unread count on a
880
+ * global read. Removal-only: the backend rejects `has_unread: false`, so becoming read can never make
881
+ * a channel belong to a list, and `ingestChannel` would pull unloaded channels into matching ones.
882
+ */
883
+ dropFromUnmatchedLists(channel: Channel) {
457
884
  this.paginators.forEach((paginator) => {
458
- const isMatch = matchingIds.has(paginator.id);
459
- const isOwner = ownerIds.size === 0 || ownerIds.has(paginator.id);
460
- if (isMatch && isOwner) {
461
- paginator.ingestItem(channel);
462
- } else {
463
- // Not a match, or matched but not the selected owner — enforce exclusivity.
464
- paginator.removeItem({ item: channel });
465
- }
885
+ if (paginator.matchesFilter(channel)) return;
886
+ paginator.removeItem({ item: channel });
466
887
  });
467
888
  }
468
889
 
@@ -721,4 +1142,35 @@ export class ChannelManager extends WithSubscriptions {
721
1142
  await paginator.reload();
722
1143
  }),
723
1144
  );
1145
+
1146
+ /**
1147
+ * Re-run every loaded list's own first-page query — the channel-list half of connection recovery,
1148
+ * driven by {@link ConnectionRecoveryManager}.
1149
+ *
1150
+ * Each list re-asserts its *own* `filters` / `sort` / `pageSize` rather than some substitute query,
1151
+ * and because `client.queryChannels` watches by default, that page's channels are re-watched as a
1152
+ * side effect. Channels below the first page are deliberately not touched — see
1153
+ * `restoreInterruptedWatch` for how they come back.
1154
+ *
1155
+ * `{ keepPreviousItems: true, reset: 'yes' }` is the non-destructive refresh: `reset` restarts the
1156
+ * window at page 1, while `keepPreviousItems` merges the fetched page into the loaded list instead
1157
+ * of replacing it and keeps the item index populated — the latter is what stops a concurrent
1158
+ * offline-replay ingest from rebuilding the list out of a cleared index. Notably NOT `silent`: the
1159
+ * `isLoading` transition it would suppress is the in-flight guard that keeps a second overlapping
1160
+ * query from being issued.
1161
+ *
1162
+ * Distinct from {@link ChannelManager.reload}, which is a destructive `reset` that blanks each list
1163
+ * to its loading state.
1164
+ *
1165
+ * Paginators that were never queried are skipped: they run their own first query when they mount,
1166
+ * and querying them here would race it.
1167
+ */
1168
+ recover = async () =>
1169
+ await Promise.allSettled(
1170
+ this.paginators
1171
+ .filter((paginator) => paginator.isInitialized)
1172
+ .map(async (paginator) => {
1173
+ await paginator.toTail({ keepPreviousItems: true, reset: 'yes' });
1174
+ }),
1175
+ );
724
1176
  }