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,5 +1,6 @@
1
1
  import type {
2
2
  AnyInterval,
3
+ BasePaginatorConfig,
3
4
  CursorDerivator,
4
5
  CursorDeriveResult,
5
6
  Interval,
@@ -18,22 +19,17 @@ import {
18
19
  } from './BasePaginator';
19
20
  import type {
20
21
  LocalMessage,
21
- MessagePaginationOptions,
22
22
  MessagePaginationParams,
23
- MessageResponse,
24
23
  PinnedMessagePaginationOptions,
25
- ReactionResponse,
26
24
  SortParamRequest,
25
+ TimestampNS,
27
26
  UserResponse,
28
27
  } from '../../types';
29
28
  import type { Channel } from '../../channel';
30
- import { StateStore } from '../../store';
31
- import {
32
- computeOwnReactions,
33
- formatMessage,
34
- generateUUIDv4,
35
- toDeletedMessage,
36
- } from '../../utils';
29
+ import { ChannelWatchStatus } from '../../channel_state';
30
+ import { CORE_NOTIFICATION_TYPE } from '../../notifications';
31
+ import { StateStore } from '@stream-io/state-store';
32
+ import { formatMessage, generateUUIDv4, toDeletedMessage } from '../../utils';
37
33
  import { makeComparator } from '../sortCompiler';
38
34
  import type { FieldToDataResolver } from '../types.normalization';
39
35
  import { resolveDotPathValue } from '../utility.normalization';
@@ -78,6 +74,14 @@ export type JumpToMessageOptions = {
78
74
  * If true, suppresses focus signal emission after a successful jump.
79
75
  */
80
76
  suppressFocusSignal?: boolean;
77
+ /**
78
+ * Also watch the channel, so it receives its events, when it isn't watched yet: the request that
79
+ * loads the window around the message asks to watch too, so it takes one request. A message
80
+ * already loaded is then loaded again with that request. Ignored for a thread's reply list, which
81
+ * loads replies through a request that can't watch, and when the paginator's `doRequest` loads
82
+ * the messages.
83
+ */
84
+ watchChannel?: boolean;
81
85
  };
82
86
 
83
87
  export type MessagePaginatorSort = SortParamRequest[];
@@ -98,7 +102,7 @@ const DEFAULT_BACKEND_SORT: MessagePaginatorSort = [
98
102
  const DEFAULT_CHANNEL_MESSAGE_LIST_PAGE_SIZE = 100;
99
103
 
100
104
  export type MessagePaginatorState = PaginatorState<LocalMessage>;
101
- export type MessageQueryShape = MessagePaginationOptions | PinnedMessagePaginationOptions;
105
+ export type MessageQueryShape = MessagePaginationParams | PinnedMessagePaginationOptions;
102
106
 
103
107
  /**
104
108
  * At the moment all the pagination parameters are just different types of cursors, e.g.
@@ -115,10 +119,18 @@ const dataFieldFilterResolver: FieldToDataResolver<LocalMessage> = {
115
119
  resolve: (message, path) => resolveDotPathValue(message, path),
116
120
  };
117
121
 
118
- export const getMessageCreatedAtTimestamp = (message: LocalMessage): number | null => {
119
- if (!(message.created_at instanceof Date)) return null;
120
- const timestamp = message.created_at.getTime();
121
- return Number.isFinite(timestamp) ? timestamp : null;
122
+ /**
123
+ * A message's `created_at` as the comparable wire timestamp (unix nanoseconds), or `null` when it
124
+ * is absent or not a finite number.
125
+ *
126
+ * Accepts `null`/`undefined` so callers holding an optional message (e.g.
127
+ * `MessagePaginator.lastMessage`) do not each repeat the guard.
128
+ */
129
+ export const getMessageCreatedAtTimestamp = (
130
+ message: LocalMessage | null | undefined,
131
+ ): TimestampNS | null => {
132
+ const timestamp = message?.created_at;
133
+ return typeof timestamp === 'number' && Number.isFinite(timestamp) ? timestamp : null;
122
134
  };
123
135
 
124
136
  export type MessagePaginatorOptions = {
@@ -142,6 +154,66 @@ export type MessagePaginatorOptions = {
142
154
  paginatorOptions?: PaginatorOptions<LocalMessage, MessageQueryShape>;
143
155
  };
144
156
 
157
+ /**
158
+ * Options for {@link MessageIntervalPaginator.mergeNewestPage} that enable destructive
159
+ * reconciliation — removing messages that were hard-deleted (by anyone) while the client was
160
+ * offline. A hard delete emits no event to other clients, and the merge is otherwise additive, so
161
+ * without this such a message lingers as a ghost after reconnect.
162
+ *
163
+ * Throughout, `page` is the newest window the server returned for `mergeNewestPage`, and "`page`'s
164
+ * newest / oldest message" are its bounds by `created_at`. With NO options, `mergeNewestPage` prunes
165
+ * any loaded message that falls WITHIN `page`'s `created_at` span but is absent from it —
166
+ * unconditionally safe (a message that arrived live during the caller's fetch is always strictly
167
+ * newer than `page`'s newest message, so it can never fall in that span). `candidateIds` widens the
168
+ * reconcilable window at the TOP edge; `requestedLimit` only tunes the `hasMoreTail` affordance and
169
+ * can never remove a message:
170
+ */
171
+ export type MergeNewestPageOptions = {
172
+ /**
173
+ * The `limit` the caller passed to the query that produced `page`. Used ONLY to derive
174
+ * `hasMoreTail` — whether `page` reached the channel's own oldest message — by comparing it to
175
+ * `page.length`. It NEVER removes a message (reconciliation stays window-only regardless), so the
176
+ * worst a wrong value can do is show/hide the "load older" affordance for one settle. Trusted only
177
+ * when no larger than the paginator's own `pageSize` (see
178
+ * {@link MessageIntervalPaginator.pageReachedChannelStart}); a larger over-request — e.g.
179
+ * `channel.reload` re-fetching the whole loaded window to reconcile as much as possible — may have
180
+ * been silently server-capped, so its short page is ignored rather than mistaken for reaching the
181
+ * start.
182
+ */
183
+ requestedLimit?: number;
184
+ /**
185
+ * A snapshot of the loaded message ids taken BEFORE the caller's fetch await. Required to prune
186
+ * messages NEWER than `page`'s newest message (a hard-deleted newest message) and to reconcile an
187
+ * empty `page` (a fully-emptied channel): at/above that top edge a just-deleted message and a
188
+ * message that arrived live during the fetch are indistinguishable by timestamp — only the pre-fetch
189
+ * snapshot separates them (a live arrival is not in it). Must be captured before the await; the
190
+ * paginator's own items at merge time already include any live arrival.
191
+ */
192
+ candidateIds?: ReadonlySet<string>;
193
+ };
194
+
195
+ /**
196
+ * Options for {@link MessageIntervalPaginator.seedFirstPageSync}, the synchronous channel-open seed.
197
+ */
198
+ export type SeedFirstPageOptions = {
199
+ /**
200
+ * When true and the paginator has already been seeded once, fold the fresh page via
201
+ * {@link MessageIntervalPaginator.mergeNewestPage} — merge in place, reconcile offline hard-deletes,
202
+ * re-derive the tail cursor, rebuild on a disjoint window, and skip when jumped away from the head —
203
+ * instead of a plain first-page ingest. Lets callers (channel.reload, the channel-list hydrate,
204
+ * connection recovery) share one reconciling seed path. Left false for the differently-sorted
205
+ * pinned list, and a no-op on a cold open (nothing loaded to fold).
206
+ */
207
+ reconcile?: boolean;
208
+ /**
209
+ * Pre-fetch snapshot of loaded message ids (captured before the caller's network await), forwarded
210
+ * to {@link MergeNewestPageOptions.candidateIds} so a hard-deleted NEWEST message is reconciled
211
+ * without mistaking a message that arrived live during the fetch for a delete. Only consulted when
212
+ * {@link reconcile} is set and a window is already loaded.
213
+ */
214
+ candidateIds?: ReadonlySet<string>;
215
+ };
216
+
145
217
  /**
146
218
  * MessageIntervalPaginator allows configuring backend request sort, while keeping internal item ordering stable.
147
219
  * Filtering of ingested items is still limited to local predicates (`filterQueryResults`).
@@ -150,16 +222,28 @@ export class MessageIntervalPaginator extends BasePaginator<
150
222
  LocalMessage,
151
223
  MessageQueryShape
152
224
  > {
225
+ /**
226
+ * The name this list's index goes by as a holder in the message store. A prototype getter, so it
227
+ * is already the subclass's while the base constructor builds the index.
228
+ */
229
+ protected get holderName() {
230
+ return 'message-interval-paginator';
231
+ }
232
+
153
233
  declare state: StateStore<MessagePaginatorState>;
154
234
  private readonly _id: string;
155
- protected channel: Channel;
156
- protected parentMessageId?: string;
235
+ /** The channel this list belongs to. A thread's reply list holds its parent channel. */
236
+ readonly channel: Channel;
237
+ /** Set when this is a thread's reply list, to the parent message's id. */
238
+ readonly parentMessageId?: string;
157
239
  readonly messageFocusSignal: StateStore<MessageFocusSignalState>;
158
240
  private clearMessageFocusSignalTimeoutId: ReturnType<typeof setTimeout> | null = null;
159
241
  private messageFocusSignalToken = 0;
160
242
  protected _requestSort = DEFAULT_BACKEND_SORT;
161
243
  protected _itemOrder: MessagePaginatorSort = DEFAULT_BACKEND_SORT;
162
244
  protected _nextQueryShape: MessageQueryShape | undefined;
245
+ /** Pending below-window reached-start probe (exposed for deterministic test awaiting). */
246
+ private _belowWindowReconcile?: Promise<void>;
163
247
  sortComparator: (a: LocalMessage, b: LocalMessage) => number;
164
248
  /**
165
249
  * Single source of truth for whether a message should be included in paginator intervals/state.
@@ -180,6 +264,14 @@ export class MessageIntervalPaginator extends BasePaginator<
180
264
  this.reconcileChangedIds(changedIds);
181
265
  }
182
266
 
267
+ /**
268
+ * Entity-store subscriber: the store removed a message this paginator holds, so it drops it from
269
+ * its windows.
270
+ */
271
+ onEntityRemoved(id: string, message: unknown): void {
272
+ this.removeItem({ id, item: message as LocalMessage });
273
+ }
274
+
183
275
  /**
184
276
  * Entity-store subscriber flush (the optional `EntityStoreSubscriber.flushState`): the `EntityStore`
185
277
  * calls this after an optimistic (local-user) write so the change renders without throttle delay.
@@ -189,6 +281,39 @@ export class MessageIntervalPaginator extends BasePaginator<
189
281
  this.flushPendingPublishes();
190
282
  }
191
283
 
284
+ /**
285
+ * UI-driven "hold off on pruning" signal, set via {@link setPruningSuspended}. Defaults to not
286
+ * suspended, so a paginator with no UI attached still honours its configured cap.
287
+ */
288
+ protected get isPruningSuspended(): boolean {
289
+ return this._pruningSuspended;
290
+ }
291
+
292
+ private _pruningSuspended = false;
293
+
294
+ /**
295
+ * Tells the paginator to hold off on dropping the oldest loaded messages. The SDK calls this from
296
+ * its viewability tracking: while the user is reading near the oldest loaded message, pruning there
297
+ * would pull content out from under them, so the window is allowed to grow past its cap until they
298
+ * scroll back. Only meaningful alongside `maxLoadedItems`.
299
+ *
300
+ * Deliberately a plain field rather than a `StateStore` — nothing observes it, and a scroll-driven
301
+ * signal must not be able to cost a render.
302
+ */
303
+ setPruningSuspended = (suspended: boolean) => {
304
+ this._pruningSuspended = suspended;
305
+ };
306
+
307
+ /**
308
+ * A message can anchor pagination once the server has acknowledged it. Narrowing this is what keeps
309
+ * an unsent message out of both halves of a prune: it is skipped rather than dropped, and it can
310
+ * never become the window's tailward cursor (its id would go out as `id_lt` and mean nothing to the
311
+ * server).
312
+ */
313
+ protected isPaginationAnchorable(item: LocalMessage | undefined): boolean {
314
+ return !!item && this.isServerConfirmedMessage(item);
315
+ }
316
+
192
317
  protected get intervalItemIdsAreHeadFirst(): boolean {
193
318
  // Messages are stored in chronological order (created_at asc) within an interval.
194
319
  // Pagination "head" (newest side) is therefore at the END of the `itemIds` array.
@@ -201,40 +326,51 @@ export class MessageIntervalPaginator extends BasePaginator<
201
326
  return 'desc';
202
327
  }
203
328
 
204
- constructor({
205
- channel,
206
- id,
207
- itemIndex,
208
- parentMessageId,
209
- requestSort,
210
- sort,
211
- itemOrder,
212
- paginatorOptions,
213
- }: MessagePaginatorOptions) {
329
+ constructor(
330
+ {
331
+ channel,
332
+ id,
333
+ itemIndex,
334
+ parentMessageId,
335
+ requestSort,
336
+ sort,
337
+ itemOrder,
338
+ paginatorOptions,
339
+ }: MessagePaginatorOptions,
340
+ builtInDefaults: Partial<BasePaginatorConfig<LocalMessage, MessageQueryShape>> = {},
341
+ ) {
214
342
  const resolvedRequestSort = requestSort ?? sort ?? DEFAULT_BACKEND_SORT;
215
343
  const resolvedItemOrder = itemOrder ?? resolvedRequestSort;
216
- super({
217
- hasPaginationQueryShapeChanged,
218
- initialCursor: ZERO_PAGE_CURSOR,
219
- itemIndex,
220
- ...paginatorOptions,
221
- // Back every message-interval paginator (channel main list, thread reply list, pinned list)
222
- // with the client-global message store, so a message held in more than one of them has a
223
- // single canonical copy and updates (reactions/edits) fan out to all holders — no copy-to-copy
224
- // sync. When the store is unavailable (e.g. a detached paginator in a test) the index falls
225
- // back to a private store and behaves exactly like a plain per-instance index. Overridable per
226
- // instance via `paginatorOptions.createItemIndex` or an explicit `itemIndex`.
227
- createItemIndex:
228
- paginatorOptions?.createItemIndex ??
229
- ((owner) =>
230
- new StoreBackedItemIndex<LocalMessage>({
231
- store: channel.getClient?.().messageStore,
232
- owner: owner as MessageIntervalPaginator,
233
- getEntityId: owner.getItemId.bind(owner),
234
- })),
235
- pageSize: paginatorOptions?.pageSize ?? DEFAULT_CHANNEL_MESSAGE_LIST_PAGE_SIZE,
236
- });
237
- this.config.deriveCursor = makeDeriveCursor(this);
344
+ super(
345
+ {
346
+ itemIndex,
347
+ ...paginatorOptions,
348
+ // Back every message-interval paginator (channel main list, thread reply list, pinned list)
349
+ // with the client-global message store, so a message held in more than one of them has a
350
+ // single canonical copy and updates (reactions/edits) fan out to all holders — no copy-to-copy
351
+ // sync. When the store is unavailable (e.g. a detached paginator in a test) the index falls
352
+ // back to a private store and behaves exactly like a plain per-instance index. Overridable per
353
+ // instance via `paginatorOptions.createItemIndex` or an explicit `itemIndex`.
354
+ createItemIndex:
355
+ paginatorOptions?.createItemIndex ??
356
+ ((owner) =>
357
+ new StoreBackedItemIndex<LocalMessage>({
358
+ store: channel.getClient?.().messageStore,
359
+ owner: owner as MessageIntervalPaginator,
360
+ getEntityId: owner.getItemId.bind(owner),
361
+ holderName: (owner as MessageIntervalPaginator).holderName,
362
+ })),
363
+ },
364
+ // SDK-supplied, so a declarative registration overrides them. `hasPaginationQueryShapeChanged`
365
+ // and the zero cursor were previously spread into the caller's options, where they outranked
366
+ // every `client.config.set({ messagePaginator: … })`.
367
+ {
368
+ hasPaginationQueryShapeChanged,
369
+ initialCursor: ZERO_PAGE_CURSOR,
370
+ pageSize: DEFAULT_CHANNEL_MESSAGE_LIST_PAGE_SIZE,
371
+ ...builtInDefaults,
372
+ },
373
+ );
238
374
  this.channel = channel;
239
375
  this.parentMessageId = parentMessageId;
240
376
  this._id = id ?? `message-paginator-${generateUUIDv4()}`;
@@ -252,18 +388,65 @@ export class MessageIntervalPaginator extends BasePaginator<
252
388
  return leftId < rightId ? -1 : leftId > rightId ? 1 : 0;
253
389
  },
254
390
  });
255
- this.config.itemOrderComparator = makeComparator<LocalMessage>({
256
- sort: this._itemOrder,
257
- resolvePathValue: resolveDotPathValue,
258
- tiebreaker: (l, r) => {
259
- const leftId = this.getItemId(l);
260
- const rightId = this.getItemId(r);
261
- return leftId < rightId ? -1 : leftId > rightId ? 1 : 0;
262
- },
263
- });
391
+ this.installIntervalBehaviour();
264
392
  this.setFilterResolvers([dataFieldFilterResolver]);
265
393
  }
266
394
 
395
+ /**
396
+ * Memoized so every derivation sees the *same* two functions. `initializeConfig` folds this into the
397
+ * config it publishes and skips the publish when nothing moved — which only works if these references
398
+ * are stable.
399
+ *
400
+ * Safe to build once: both close over `this` and read `_itemOrder`, which is assigned in the
401
+ * constructor and has no setter.
402
+ */
403
+ private intervalBehaviour?: Partial<
404
+ BasePaginatorConfig<LocalMessage, MessageQueryShape>
405
+ >;
406
+
407
+ private buildIntervalBehaviour(): Partial<
408
+ BasePaginatorConfig<LocalMessage, MessageQueryShape>
409
+ > {
410
+ if (!this.intervalBehaviour) {
411
+ this.intervalBehaviour = {
412
+ deriveCursor: makeDeriveCursor(this),
413
+ itemOrderComparator: makeComparator<LocalMessage>({
414
+ sort: this._itemOrder,
415
+ resolvePathValue: resolveDotPathValue,
416
+ tiebreaker: (l, r) => {
417
+ const leftId = this.getItemId(l);
418
+ const rightId = this.getItemId(r);
419
+ return leftId < rightId ? -1 : leftId > rightId ? 1 : 0;
420
+ },
421
+ }),
422
+ };
423
+ }
424
+ return this.intervalBehaviour;
425
+ }
426
+
427
+ /**
428
+ * Cursor derivation and in-memory item ordering, which this class installs on `config` rather than
429
+ * passing as constructor options.
430
+ *
431
+ * Contributed to the base derivation rather than written after it — see
432
+ * {@link BasePaginator.getBehaviourOverrides}. That is what keeps one re-derivation to one publish,
433
+ * and stops the intermediate publish that had these two stripped.
434
+ */
435
+ protected override getBehaviourOverrides(): Partial<
436
+ BasePaginatorConfig<LocalMessage, MessageQueryShape>
437
+ > {
438
+ return this.buildIntervalBehaviour();
439
+ }
440
+
441
+ /**
442
+ * The constructor's route to the same overlay. Deliberately calls the private builder rather than the
443
+ * overridable hook: this runs inside the constructor, and a subclass override would execute before its
444
+ * own fields were initialized.
445
+ */
446
+ protected installIntervalBehaviour(): void {
447
+ this.updateConfig(this.buildIntervalBehaviour());
448
+ }
449
+
267
450
  get id() {
268
451
  return this._id;
269
452
  }
@@ -331,8 +514,13 @@ export class MessageIntervalPaginator extends BasePaginator<
331
514
  };
332
515
  };
333
516
 
517
+ /**
518
+ * Reads `requestOptions.watch`: `true` also watches the channel with the request. Ignored for a
519
+ * thread's reply list and with `doRequest`.
520
+ */
334
521
  query = async ({
335
522
  direction,
523
+ requestOptions,
336
524
  }: PaginationQueryParams<MessageQueryShape>): Promise<
337
525
  PaginationQueryReturnValue<LocalMessage>
338
526
  > => {
@@ -359,13 +547,15 @@ export class MessageIntervalPaginator extends BasePaginator<
359
547
  : undefined;
360
548
  } else {
361
549
  const { messages } = this.parentMessageId
362
- ? await this.channel.getReplies({
363
- parent_id: this.parentMessageId,
364
- ...options,
365
- sort: this.requestSort,
366
- })
550
+ ? await this.channel
551
+ .getClient()
552
+ .getReplies(
553
+ { parent_id: this.parentMessageId },
554
+ { ...options, sort: this.requestSort },
555
+ )
367
556
  : await this.channel.query({
368
557
  messages: options as MessagePaginationParams,
558
+ ...(requestOptions?.watch === true && { watch: true }),
369
559
  // todo: why do we query for watchers?
370
560
  // watchers: { limit: this.pageSize },
371
561
  });
@@ -380,7 +570,7 @@ export class MessageIntervalPaginator extends BasePaginator<
380
570
 
381
571
  /**
382
572
  * Seed the paginator with the page a channel-open query just fetched (`Channel.query` for
383
- * `watch`/`create`, and `client.hydrateActiveChannels`).
573
+ * `watch`/`create`, and `client.hydrateChannels`).
384
574
  *
385
575
  * These paths hydrate the channel read state in the SAME synchronous tick they add messages
386
576
  * (`Channel._initializeState`), and the read patch drives `MessageReceiptsTracker`, which resolves
@@ -398,13 +588,38 @@ export class MessageIntervalPaginator extends BasePaginator<
398
588
  seedFirstPageSync(
399
589
  messages: LocalMessage[],
400
590
  requestedPageSize: number,
401
- messagePaginationOptions?: MessagePaginationOptions,
591
+ messagePaginationOptions?: MessagePaginationParams,
592
+ options?: SeedFirstPageOptions,
402
593
  ) {
403
594
  const queryShape: MessageQueryShape = {
404
595
  ...messagePaginationOptions,
405
596
  limit: requestedPageSize,
406
597
  };
407
598
  const isJump = this.isJumpQueryShape(queryShape);
599
+
600
+ // A re-seed reconciles against the loaded windows. A list loaded empty has none (no interval,
601
+ // not even live messages in a logical head), so the page seeds it as a first open would; the
602
+ // merge would find nothing to merge into and drop the page.
603
+ if (
604
+ options?.reconcile &&
605
+ !isJump &&
606
+ typeof this.items !== 'undefined' &&
607
+ this.itemIntervals.length > 0
608
+ ) {
609
+ // The page came back, so whatever the last query failure was, it is no longer the truth. The
610
+ // branch below inherits this from `postQueryReconcile`, which this one deliberately skips —
611
+ // without it a failed "load older" would keep a UI's error surface latched through an
612
+ // otherwise successful reconnect refresh.
613
+ if (this.state.getLatestValue().lastQueryError) {
614
+ this.state.partialNext({ lastQueryError: undefined });
615
+ }
616
+ this.mergeNewestPage(messages, {
617
+ candidateIds: options.candidateIds,
618
+ requestedLimit: requestedPageSize,
619
+ });
620
+ return;
621
+ }
622
+
408
623
  this.postQueryReconcile({
409
624
  // A jump/around page spans both directions; a plain latest page paginates tailward (older).
410
625
  direction: isJump ? undefined : 'tailward',
@@ -422,7 +637,7 @@ export class MessageIntervalPaginator extends BasePaginator<
422
637
  isJumpQueryShape(queryShape: MessageQueryShape): boolean {
423
638
  return (
424
639
  !!queryShape?.id_around ||
425
- !!(queryShape as MessagePaginationOptions)?.created_at_around
640
+ !!(queryShape as MessagePaginationParams)?.created_at_around
426
641
  );
427
642
  }
428
643
 
@@ -433,8 +648,14 @@ export class MessageIntervalPaginator extends BasePaginator<
433
648
  focusSignalTtlMs,
434
649
  pageSize,
435
650
  suppressFocusSignal,
651
+ watchChannel,
436
652
  }: JumpToMessageOptions = {},
437
653
  ): Promise<boolean> => {
654
+ const watch =
655
+ !!watchChannel &&
656
+ !this.parentMessageId &&
657
+ !this.config.doRequest &&
658
+ this.channel.watchStatus !== ChannelWatchStatus.Watching;
438
659
  let localMessage = this.getItem(messageId);
439
660
  let interval: AnyInterval | undefined;
440
661
  let state: Partial<PaginatorState<LocalMessage>> | undefined;
@@ -457,16 +678,18 @@ export class MessageIntervalPaginator extends BasePaginator<
457
678
  }
458
679
  }
459
680
 
460
- if (localMessage && interval && !isLogicalInterval(interval)) {
681
+ // a loaded message needs no request, unless the jump is also to watch the channel
682
+ if (!watch && localMessage && interval && !isLogicalInterval(interval)) {
461
683
  state = {
462
684
  hasMoreHead: interval.hasMoreHead,
463
685
  hasMoreTail: interval.hasMoreTail,
464
686
  cursor: this.getCursorFromInterval(interval),
465
687
  items: this.intervalToItems(interval),
466
688
  };
467
- } else if (!localMessage || !interval || isLogicalInterval(interval)) {
689
+ } else {
468
690
  const result = await this.executeQuery({
469
691
  queryShape: { id_around: messageId, limit: pageSize },
692
+ ...(watch && { requestOptions: { watch: true } }),
470
693
  updateState: false,
471
694
  });
472
695
  localMessage = this.getItem(messageId);
@@ -474,7 +697,7 @@ export class MessageIntervalPaginator extends BasePaginator<
474
697
  this.channel.getClient().notifications.addError({
475
698
  message: 'Jump to message unsuccessful',
476
699
  origin: { emitter: 'MessagePaginator.jumpToMessage', context: { messageId } },
477
- options: { type: 'api:messages:query:failed' },
700
+ options: { type: CORE_NOTIFICATION_TYPE.messageJumpFailed },
478
701
  });
479
702
  return false;
480
703
  }
@@ -526,7 +749,7 @@ export class MessageIntervalPaginator extends BasePaginator<
526
749
  this.channel.getClient().notifications.addError({
527
750
  message: 'Jump to latest message unsuccessful',
528
751
  origin: { emitter: 'MessagePaginator.jumpToTheLatestMessage' },
529
- options: { type: 'api:message:query:failed' },
752
+ options: { type: CORE_NOTIFICATION_TYPE.messageJumpToLatestFailed },
530
753
  });
531
754
  return false;
532
755
  }
@@ -548,31 +771,107 @@ export class MessageIntervalPaginator extends BasePaginator<
548
771
  * 1. OVERLAP - the incoming page shares at least one id with the loaded head (fewer than a full
549
772
  * page is new). Merge in place: existing items are reconciled by id (edits, soft deletes), new
550
773
  * items are appended and every already loaded item (including older pages already paged in) is
551
- * kept. `hasMoreTail`/`cursor.tailward` are left as-is so the page can be any size, so deriving
552
- * "has older items" from its length would wrongly clear it while older items remain.
774
+ * kept. The tail boundary (`hasMoreTail`/`cursor.tailward`) is set from whether the page reached
775
+ * the channel start ({@link pageReachedChannelStart}): a bounded page that came back short means
776
+ * no more older, otherwise "load older" stays enabled and the cursor re-anchors to the true loaded
777
+ * oldest (which also clears a stale offline-DB cursor). Then destructive reconciliation
778
+ * ({@link reconcileHeadAgainstPage}) removes any loaded message
779
+ * that the authoritative page proves was hard-deleted while offline (see that method + the
780
+ * {@link MergeNewestPageOptions} for the exact, safe window).
553
781
  *
554
782
  * 2. DISJOINT - the incoming page shares no id with the loaded head (at least a full page is new).
555
783
  * Merging would weld the two across the gap (the interval merge treats two head intervals as
556
784
  * overlapping when one reaches further headward), hiding the items in between with no way to
557
785
  * reach them. Instead the loaded set is discarded and rebuilt from the incoming page as a fresh
558
786
  * contiguous head (`hasMoreTail: true`, cursor reanchored to the page's oldest item) so the
559
- * gap and older history load again when paginating older.
787
+ * gap and older history load again when paginating older. No separate reconciliation is needed:
788
+ * the rebuilt window IS the server truth, so any hard-deleted message is simply absent from it.
789
+ *
790
+ * Never blanks the loaded set. Noop unless the newest slice is both loaded AND the interval
791
+ * currently in view (the head interval is anchored at the head and active); when the caller has
792
+ * jumped to a separate older window the merge is skipped so their position is preserved, and the
793
+ * incoming page is picked up on a later load. An empty page never wipes the list on its own, but
794
+ * — given a pre-fetch snapshot via `options.candidateIds` — is reconciled as "the channel has no
795
+ * messages" (every server-confirmed loaded message removed).
560
796
  *
561
- * Both paths emit exactly once and never blank the loaded set. Noop unless the page is non empty
562
- * and the newest slice is both loaded AND the interval currently in view (the head interval is
563
- * anchored at the head and active); when the caller has jumped to a separate older window the
564
- * merge is skipped so their position is preserved, and the incoming page is picked up on a later
565
- * load.
797
+ * @param page - The fetched newest window (may be empty). `created_at` order is normalized on ingest.
798
+ * @param options - See {@link MergeNewestPageOptions}. Omit to prune only within the page's own span.
566
799
  */
567
- mergeNewestPage = (page: LocalMessage[]) => {
568
- if (!page?.length) return;
800
+ /**
801
+ * Merges a freshly fetched newest page into the loaded window (the hydrate path). Wraps the
802
+ * implementation so the query shape is recorded on EVERY exit — the body returns early in
803
+ * several places, and a window left without a shape loses itself on the next pagination (see
804
+ * `recordLoadedWindowQueryShape`).
805
+ */
806
+ mergeNewestPage = (page: LocalMessage[], options?: MergeNewestPageOptions) => {
807
+ this._mergeNewestPage(page, options);
808
+ this.recordLoadedWindowQueryShape();
809
+ };
810
+
811
+ private _mergeNewestPage = (page: LocalMessage[], options?: MergeNewestPageOptions) => {
569
812
  const headInterval = this.itemIntervals[0] as Interval | undefined;
570
- if (!headInterval?.isHead) return;
571
- // Only reconcile when the head is the interval currently in view. If the caller jumped to a
572
- // separate (older) window, that window is active and the head is merely still-loaded underneath;
573
- // reconciling would switch the view to the head and yank them to the newest. Skip to preserve
574
- // their position (the newest page is picked up on scroll / a later load).
575
- if (!this.isActiveInterval(headInterval)) return;
813
+ if (!headInterval?.isHead) {
814
+ // Live content no page has anchored yet, the first query came back empty and the reply the
815
+ // user then sent went to the logical head (a thread/channel creation for example). Returning would
816
+ // discard the fetched page, so the window could never catch up. We anchor it, so `ingestPage` folds
817
+ // overlapping logical intervals in, absorbing those items.
818
+ //
819
+ // It's narrow on purpose, `liveHeadLogical` rather than `itemIntervals[0]`, which is only the head
820
+ // by convention and could be a logical tail and no anchored head, whose presence would mean
821
+ // this window is anchored with an older island merely in view. Keeps both neighbouring no-op
822
+ // contracts, so nothing loaded has no logical head (seeding is `postQueryReconcile`'s job).
823
+ const logicalHead = this.liveHeadLogical;
824
+ const hasAnchoredHead = this.itemIntervals.some(
825
+ (interval) => !isLogicalInterval(interval) && interval.isHead,
826
+ );
827
+ if (!logicalHead || hasAnchoredHead || !page?.length) return;
828
+
829
+ // Take over the view only if the reader is on the live content being absorbed, so if they jumped
830
+ // to another interval, anchor for their return and leave them there (the rule the jumped away
831
+ // branch below enforces).
832
+ const takeOverView = this.isActiveInterval(logicalHead);
833
+
834
+ const anchored = this.ingestPage({ page, isHead: true, setActive: false });
835
+ if (!anchored || !takeOverView) return;
836
+
837
+ const hasMoreTail = !this.pageReachedChannelStart(page, options);
838
+ anchored.hasMoreTail = hasMoreTail;
839
+ anchored.isTail = !hasMoreTail;
840
+
841
+ this.setActiveInterval(anchored, { updateState: false });
842
+ this.state.partialNext({
843
+ items: this.intervalToItems(anchored),
844
+ hasMoreHead: false,
845
+ hasMoreTail,
846
+ cursor: {
847
+ headward: null,
848
+ tailward: hasMoreTail ? (anchored.itemIds[0] ?? null) : null,
849
+ },
850
+ });
851
+ return;
852
+ }
853
+ // Captured BEFORE the merge overwrites state — inputs for the below-window reached-start probe
854
+ // (overlap branch only): did we believe we were at the channel start, and how much was loaded.
855
+ const wasAtChannelStart = !this.state.getLatestValue().hasMoreTail;
856
+ const preMergeLoadedCount = headInterval.itemIds.length;
857
+ // If the caller jumped to a separate (older) window, that window is active and the head is merely
858
+ // still-loaded underneath. Don't MERGE the fresh page or switch the view (that would yank them to
859
+ // the newest) — but STILL prune offline hard-deletes out of the hidden head, otherwise returning to
860
+ // it later (scroll-to-latest) surfaces ghosts that were deleted while jumped away. Reconciliation
861
+ // targets the head interval regardless of which interval is active, and removing a hidden-head ghost
862
+ // leaves the active island's items untouched.
863
+ if (!this.isActiveInterval(headInterval)) {
864
+ this.reconcileHeadAgainstPage(page, options);
865
+ return;
866
+ }
867
+
868
+ if (!page?.length) {
869
+ // Empty page: never blanks the list by itself. Only when the caller supplied a pre-fetch
870
+ // snapshot do we treat it as authoritative "channel emptied" and remove ghosts (a message that
871
+ // arrived live during the fetch is excluded by the snapshot).
872
+ this.reconcileHeadAgainstPage([], options);
873
+ return;
874
+ }
576
875
 
577
876
  const loadedIds = new Set(headInterval.itemIds);
578
877
  const overlapsLoadedHead = page.some((item) => loadedIds.has(this.getItemId(item)));
@@ -603,24 +902,288 @@ export class MessageIntervalPaginator extends BasePaginator<
603
902
  return;
604
903
  }
605
904
 
606
- // Overlapping window: merge in place, preserving the older boundary.
905
+ // Overlapping window: merge in place, keeping every already-loaded (incl. older) item.
607
906
  const interval = this.ingestPage({ page, isHead: true, setActive: false });
608
907
  if (!interval) return;
609
908
 
909
+ // hasMoreTail: does the fetched page prove it reached the channel's own oldest message? Only a
910
+ // request bounded by our OWN pageSize gives that proof (a short page); an over-request may have
911
+ // been server-capped, so it biases to `true` — never asserting "no more older" from a page that
912
+ // may be truncated. See {@link pageReachedChannelStart} (no hardcoded max page size, per-paginator).
913
+ // This decides only the "load older" AFFORDANCE — it never removes a message (reconciliation stays
914
+ // window-only below). isTail mirrors it: `true` only when we RELIABLY reached the start, which also
915
+ // clears a stale offline-DB `isTail:true` and stops `intervalsOverlap` welding a far page across a
916
+ // gap. The tail cursor anchors to the oldest loaded id so "load older" stays contiguous.
917
+ const hasMoreTail = !this.pageReachedChannelStart(page, options);
918
+ interval.hasMoreTail = hasMoreTail;
919
+ interval.isTail = !hasMoreTail;
920
+
610
921
  this.setActiveInterval(interval, { updateState: false });
611
922
  this.state.partialNext({
612
923
  items: this.intervalToItems(interval),
613
- // The newest slice is loaded (head anchored), so after merging the head window there is
614
- // nothing newer to load. hasMoreTail / cursor are deliberately preserved (see above).
924
+ // The newest slice is loaded (head anchored), so there is nothing newer to load.
615
925
  hasMoreHead: false,
926
+ hasMoreTail,
927
+ // Tailward = the oldest loaded id (interval item ids are created_at asc), null once we reached
928
+ // the channel start.
929
+ cursor: {
930
+ headward: null,
931
+ tailward: hasMoreTail ? (interval.itemIds[0] ?? null) : null,
932
+ },
616
933
  });
934
+
935
+ // With the newest page merged in, drop any loaded message the page proves was hard-deleted, and
936
+ // collect the below-window leftovers it cannot decide from the page alone.
937
+ const belowWindow = this.reconcileHeadAgainstPage(page, options);
938
+
939
+ // The leftovers are ambiguous (hard-deleted oldest vs server-capped over-request). Only a
940
+ // full-window reload (`requestedLimit >= loaded`, so NOT the small list hydrate) that we believed
941
+ // reached the start could have reached it — probe to settle them there; anything else can't, so skip.
942
+ const requestedLimit = options?.requestedLimit;
943
+ if (
944
+ belowWindow.length &&
945
+ wasAtChannelStart &&
946
+ typeof requestedLimit === 'number' &&
947
+ requestedLimit >= preMergeLoadedCount
948
+ ) {
949
+ this._belowWindowReconcile = this.pruneBelowWindowIfReachedStart(
950
+ belowWindow,
951
+ this.getItemId(page[0]),
952
+ );
953
+ }
617
954
  };
618
955
 
956
+ /**
957
+ * Whether `page` proves it reached the channel's own oldest message: the caller's request was
958
+ * bounded by this paginator's OWN `pageSize` AND `page` came back shorter than that request.
959
+ *
960
+ * `pageSize <= the server's max page size` is already the invariant normal pagination
961
+ * (`executeQuery`) relies on — `page.length < pageSize` ⟹ reached the end — so a request no larger
962
+ * than `pageSize` returns exactly what was asked unless the channel ended. This needs no hardcoded
963
+ * max page size and is per-paginator, so a thread reply paginator uses its own `pageSize`.
964
+ *
965
+ * An OVER-request (larger than `pageSize`, e.g. `channel.reload` re-fetching the whole loaded window
966
+ * to reconcile as much as possible) may have been silently capped by the server, so a short page
967
+ * there is NOT proof of reaching the start — return `false` and stay conservative. This only ever
968
+ * gates the `hasMoreTail` affordance; it never removes a message.
969
+ */
970
+ private pageReachedChannelStart(
971
+ page: LocalMessage[],
972
+ options?: MergeNewestPageOptions,
973
+ ): boolean {
974
+ const requestedLimit = options?.requestedLimit;
975
+ return (
976
+ typeof requestedLimit === 'number' &&
977
+ requestedLimit <= this.pageSize &&
978
+ page.length < requestedLimit
979
+ );
980
+ }
981
+
982
+ /**
983
+ * Settle the below-window leftovers {@link reconcileHeadAgainstPage} handed back (loaded messages
984
+ * older than `anchorId` — the returned page's oldest — and absent from the page). From the page alone
985
+ * they're ambiguous: a hard-deleted oldest vs a server-capped over-request. Ask the server "anything
986
+ * older than `anchorId`?" — the only cap-free way to tell. Nothing older ⇒ genuine deletes ⇒ remove
987
+ * them and settle the tail. A probe failure or a head change across the await keeps them (never a false
988
+ * delete). The caller decides WHEN this runs.
989
+ */
990
+ private async pruneBelowWindowIfReachedStart(
991
+ belowWindow: string[],
992
+ anchorId: string,
993
+ ): Promise<void> {
994
+ const headId = (this.itemIntervals[0] as Interval | undefined)?.id;
995
+ // older exists (or the probe failed), we we're not provably the start, so
996
+ // keep the leftovers
997
+ if (await this.hasMessagesOlderThan(anchorId).catch(() => true)) return;
998
+ // revalidate the head across the await (a jump/reset/newer merge aborts), then remove the leftovers
999
+ const head = this.itemIntervals[0] as Interval | undefined;
1000
+ if (!head?.isHead || head.id !== headId) return;
1001
+ this.removeReconciledItems(belowWindow);
1002
+ head.hasMoreTail = false; // we now KNOW we reached the start, so settle the "load older" affordance
1003
+ head.isTail = true;
1004
+ if (this.isActiveInterval(head)) {
1005
+ this.state.partialNext({
1006
+ hasMoreTail: false,
1007
+ cursor: { headward: null, tailward: null },
1008
+ });
1009
+ }
1010
+ }
1011
+
1012
+ /** One `limit: 1` fetch of messages older than `id` (channel main list or thread replies). */
1013
+ private async hasMessagesOlderThan(id: string): Promise<boolean> {
1014
+ const pagination = { limit: 1, id_lt: id } as MessagePaginationParams;
1015
+ const { messages } = this.parentMessageId
1016
+ ? await this.channel
1017
+ .getClient()
1018
+ .getReplies({ parent_id: this.parentMessageId }, pagination)
1019
+ : await this.channel.query({ messages: pagination });
1020
+ return Array.isArray(messages) && messages.length > 0;
1021
+ }
1022
+
1023
+ /**
1024
+ * Whether a loaded message is server-confirmed and therefore eligible to be reconciled away when
1025
+ * absent from an authoritative page. Excludes local-only messages the server has never
1026
+ * acknowledged — optimistic (`sending`) and `failed` sends, and client-side `error` placeholders —
1027
+ * so a legitimately-unsent message is never mistaken for a hard delete.
1028
+ */
1029
+ protected isServerConfirmedMessage(message: LocalMessage): boolean {
1030
+ return (
1031
+ message.status !== 'sending' &&
1032
+ message.status !== 'failed' &&
1033
+ message.type !== 'error'
1034
+ );
1035
+ }
1036
+
1037
+ /**
1038
+ * Destructive half of {@link mergeNewestPage}: remove messages in the loaded head interval that
1039
+ * `page` proves were hard-deleted while offline (a hard delete emits no event to other clients, and
1040
+ * the merge is additive, so they would otherwise linger forever).
1041
+ *
1042
+ * Here `page` is the freshly-fetched newest window the server returned for the query that produced
1043
+ * it. Its two bounds are its NEWEST message (`page`'s last item by `created_at`) and its OLDEST
1044
+ * message (`page`'s first item). Reconciliation removes ONLY messages `page` actually covers — no
1045
+ * hardcoded page size is involved — in two regions, by a loaded message's `created_at`:
1046
+ *
1047
+ * - WITHIN `page` (strictly between `page`'s oldest and newest message): a server-confirmed loaded
1048
+ * message absent from `page` was hard-deleted. Safe with no snapshot — a message that arrived live
1049
+ * during the caller's fetch is always strictly newer than `page`'s newest message, so it can never
1050
+ * fall in this span.
1051
+ * - AT/ABOVE `page`'s newest message (a hard-deleted newest message), and the empty-`page` case:
1052
+ * only reconcilable with a pre-fetch `candidateIds` snapshot, which alone tells a just-deleted
1053
+ * message from one that arrived live during the fetch at that top edge.
1054
+ *
1055
+ * A loaded message BELOW `page`'s oldest is NOT removed here (window-only) — from the page alone a
1056
+ * hard-deleted oldest is indistinguishable from a server-capped over-request. Those messages are
1057
+ * instead RETURNED (the below-window leftovers) so {@link pruneBelowWindowIfReachedStart} can settle
1058
+ * them with a `limit: 1` "anything older?" probe — the only cap-free proof — and remove them only if
1059
+ * the server confirms nothing older exists. Absent that proof they are kept (a later cold/fresh query
1060
+ * omits any real delete).
1061
+ *
1062
+ * Removal goes through {@link removeItem} (batched) so the item index, intervals, shared message
1063
+ * store and — via the {@link MessagePaginator} override — the tracked last message all stay correct;
1064
+ * the active window is then re-emitted once.
1065
+ *
1066
+ * @returns the below-window leftover ids (loaded, server-confirmed, older than `page`'s oldest, absent
1067
+ * from it) for the caller's reached-start probe. Empty for the no-head / empty-page paths.
1068
+ */
1069
+ protected reconcileHeadAgainstPage(
1070
+ page: LocalMessage[],
1071
+ options?: MergeNewestPageOptions,
1072
+ ): string[] {
1073
+ const headInterval = this.itemIntervals[0] as Interval | undefined;
1074
+ if (!headInterval?.isHead) return [];
1075
+
1076
+ const loadedIds = headInterval.itemIds;
1077
+ const candidateIds = options?.candidateIds;
1078
+
1079
+ // Empty page → the channel has no messages. Every server-confirmed loaded message is gone, but
1080
+ // only remove ids from the pre-fetch snapshot so a message that landed during the fetch survives.
1081
+ if (!page.length) {
1082
+ if (!candidateIds) return [];
1083
+ const toRemove = loadedIds.filter((id) => {
1084
+ if (!candidateIds.has(id)) return false;
1085
+ const message = this.getItem(id);
1086
+ return !!message && this.isServerConfirmedMessage(message);
1087
+ });
1088
+ this.removeReconciledItems(toRemove);
1089
+ return [];
1090
+ }
1091
+
1092
+ const pageIds = new Set(page.map((message) => this.getItemId(message)));
1093
+ const newestReturnedTs = getMessageCreatedAtTimestamp(page[page.length - 1]);
1094
+ const oldestReturnedTs = getMessageCreatedAtTimestamp(page[0]);
1095
+
1096
+ // Window-only: never remove below the returned page's oldest here, because from the page alone a
1097
+ // hard-deleted oldest is indistinguishable from a server-capped over-request. Below-window messages
1098
+ // are collected into `belowWindow` and returned instead, for the reached-start probe to settle.
1099
+ const windowLowTs = oldestReturnedTs ?? Number.POSITIVE_INFINITY;
1100
+
1101
+ const toRemove: string[] = [];
1102
+ const belowWindow: string[] = [];
1103
+ for (const id of loadedIds) {
1104
+ if (pageIds.has(id)) continue; // present on the server → keep
1105
+ const message = this.getItem(id);
1106
+ if (!message || !this.isServerConfirmedMessage(message)) continue; // local-only → keep
1107
+ const ts = getMessageCreatedAtTimestamp(message);
1108
+ if (ts === null) continue; // no server timestamp (optimistic) → keep
1109
+
1110
+ if (newestReturnedTs !== null && ts >= newestReturnedTs) {
1111
+ // At/above the newest returned message: a hard-deleted newest message and a message that
1112
+ // arrived live during the fetch are indistinguishable here. Only remove ids present in the
1113
+ // pre-fetch snapshot, which excludes live arrivals. (The newest returned message itself is
1114
+ // in the page, so it is already skipped above.)
1115
+ if (candidateIds?.has(id)) toRemove.push(id);
1116
+ continue;
1117
+ }
1118
+ // Below the newest returned message: within the page's span (a live arrival can never be here, so
1119
+ // absence = a hard delete) → remove; at/below the page's oldest → a below-window leftover the page
1120
+ // cannot decide, returned for the reached-start probe.
1121
+ if (ts > windowLowTs) toRemove.push(id);
1122
+ else belowWindow.push(id);
1123
+ }
1124
+
1125
+ this.removeReconciledItems(toRemove);
1126
+ return belowWindow;
1127
+ }
1128
+
1129
+ /**
1130
+ * Remove a set of reconciled (hard-deleted) ids from this paginator's loaded state in one coalesced
1131
+ * batch. Each id goes through {@link removeItem}, which drops it from THREE places — not a single
1132
+ * interval:
1133
+ *
1134
+ * 1. the item index — unlinks this paginator's membership from the shared entity store (GC'ing the
1135
+ * content if this was the last holder);
1136
+ * 2. the interval that holds it — located by id, so it is NOT head-specific in general; in practice
1137
+ * it is always the head interval, because the sole caller ({@link reconcileHeadAgainstPage})
1138
+ * sources these ids from `headInterval.itemIds` and an item has single-interval membership;
1139
+ * 3. the active window (`state.items`) if visible — blanking to `[]` when the window empties, per
1140
+ * {@link flushWindowPublish}.
1141
+ *
1142
+ * The coalesced batch collapses all of that into a single `state.items` publish. Then mirror the
1143
+ * removal into the offline DB (see {@link purgeReconciledFromOfflineDb}) so a cold start does not
1144
+ * re-seed the ghosts from SQLite. No-op for an empty set, so an unaffected merge does not touch
1145
+ * state a second time.
1146
+ */
1147
+ private removeReconciledItems(ids: string[]) {
1148
+ if (!ids.length) return;
1149
+ this.batch(
1150
+ () => {
1151
+ for (const id of ids) this.removeItem({ id });
1152
+ },
1153
+ { coalesce: true },
1154
+ );
1155
+ this.purgeReconciledFromOfflineDb(ids);
1156
+ }
1157
+
1158
+ /**
1159
+ * Mirror a destructive reconciliation into the offline DB. A hard delete performed while the client
1160
+ * was offline reaches it via no event, so the offline store never ran its own hard-delete for these
1161
+ * ids; the reconnect query re-hydrates the DB by UPSERT (which never removes what is absent from the
1162
+ * page), so without this the ghosts survive in SQLite and a cold start would re-seed them after the
1163
+ * in-memory list already dropped them.
1164
+ *
1165
+ * Owned by the state layer, NOT the SDK: the SDK only supplies the platform `offlineDb`
1166
+ * implementation and never orchestrates DB writes for reconciliation. Fire-and-forget and
1167
+ * best-effort — the in-memory removal is the source of truth for the live list, so a failed/absent
1168
+ * DB write is no worse than before (the ghost merely re-appears on a cold start until the next
1169
+ * reconcile). No-op when offline support is off (`client.offlineDb` undefined). The ids are already
1170
+ * server-confirmed (the reconcile excludes pending/failed/optimistic), so a plain hard delete —
1171
+ * without the pending-task teardown of a local failed message — is correct.
1172
+ */
1173
+ private purgeReconciledFromOfflineDb(ids: string[]) {
1174
+ const offlineDb = this.channel.getClient?.()?.offlineDb;
1175
+ if (!offlineDb) return;
1176
+ // The offline DB owns the batching (single transaction); we just hand it the reconciled ids.
1177
+ offlineDb.hardDeleteMessages({ ids }).catch(() => {
1178
+ // best-effort persistence cleanup — see doc comment; the live list is already correct.
1179
+ });
1180
+ }
1181
+
619
1182
  protected resolveUnreadBoundaryIdsByTimestamp = ({
620
1183
  lastReadAt,
621
1184
  messages,
622
1185
  }: {
623
- lastReadAt: Date;
1186
+ lastReadAt: TimestampNS;
624
1187
  messages: LocalMessage[];
625
1188
  }): { firstUnreadMessageId: string | null; lastReadMessageId: string | null } => {
626
1189
  // Messages are expected in chronological order. We find:
@@ -629,7 +1192,7 @@ export class MessageIntervalPaginator extends BasePaginator<
629
1192
  //
630
1193
  // If the page starts after lastReadAt, the entire page is unread and the first message is
631
1194
  // used as unread anchor (legacy "whole channel is unread" behavior for this queried window).
632
- const lastReadTimestamp = lastReadAt.getTime();
1195
+ const lastReadTimestamp = lastReadAt;
633
1196
  if (!Number.isFinite(lastReadTimestamp) || !messages.length) {
634
1197
  return { firstUnreadMessageId: null, lastReadMessageId: null };
635
1198
  }
@@ -758,13 +1321,13 @@ export class MessageIntervalPaginator extends BasePaginator<
758
1321
  * `isTail`/`hasMoreTail` are set; intervals entirely newer keep their flags (unloaded older
759
1322
  * messages may still sit between them and the cutoff). The active window is re-emitted once.
760
1323
  */
761
- truncate = ({ truncatedAt }: { truncatedAt: Date }) => {
762
- const cutoff = truncatedAt.getTime();
763
- if (Number.isNaN(cutoff)) return;
1324
+ truncate = ({ truncatedAt }: { truncatedAt: TimestampNS }) => {
1325
+ const cutoff = truncatedAt;
1326
+ if (!Number.isFinite(cutoff)) return;
764
1327
 
765
1328
  const isOld = (item: LocalMessage | undefined) => {
766
- const time = item?.created_at ? new Date(item.created_at).getTime() : undefined;
767
- return typeof time === 'number' && time < cutoff;
1329
+ const time = getMessageCreatedAtTimestamp(item);
1330
+ return time !== null && time < cutoff;
768
1331
  };
769
1332
 
770
1333
  const removedIds: string[] = [];
@@ -835,44 +1398,48 @@ export class MessageIntervalPaginator extends BasePaginator<
835
1398
  }: {
836
1399
  userId: string;
837
1400
  hardDelete?: boolean;
838
- deletedAt: Date;
1401
+ deletedAt: TimestampNS;
839
1402
  }) => {
840
1403
  const loadedMessages = this.items ?? [];
841
1404
 
842
- // Batch: one logical operation touches many messages; coalesce the shared-store fan-out to a
843
- // single flush (sibling holders are notified once) instead of once per affected message.
844
- this._itemIndex.batch(() => {
845
- for (const message of loadedMessages) {
846
- if (message.user?.id === userId) {
847
- if (hardDelete) {
848
- this.removeItem({ id: message.id });
849
- } else {
850
- this.ingestItem(
851
- toDeletedMessage({
852
- message,
1405
+ // One logical operation touching many messages so we `coalesce` so this paginator's own window
1406
+ // emits once at the end rather than per message, and the shared-store fan-out folds into a
1407
+ // single flush so sibling holders are notified once too.
1408
+ this.batch(
1409
+ () => {
1410
+ for (const message of loadedMessages) {
1411
+ if (message.user?.id === userId) {
1412
+ if (hardDelete) {
1413
+ this.removeItem({ id: message.id });
1414
+ } else {
1415
+ this.ingestItem(
1416
+ toDeletedMessage({
1417
+ message,
1418
+ hardDelete,
1419
+ deletedAt,
1420
+ }) as LocalMessage,
1421
+ );
1422
+ }
1423
+ continue;
1424
+ }
1425
+
1426
+ if (
1427
+ message.quoted_message?.user?.id === userId &&
1428
+ message.quoted_message.type !== 'deleted'
1429
+ ) {
1430
+ this.ingestItem({
1431
+ ...message,
1432
+ quoted_message: toDeletedMessage({
1433
+ message: formatMessage(message.quoted_message),
853
1434
  hardDelete,
854
1435
  deletedAt,
855
1436
  }) as LocalMessage,
856
- );
1437
+ });
857
1438
  }
858
- continue;
859
1439
  }
860
-
861
- if (
862
- message.quoted_message?.user?.id === userId &&
863
- message.quoted_message.type !== 'deleted'
864
- ) {
865
- this.ingestItem({
866
- ...message,
867
- quoted_message: toDeletedMessage({
868
- message: formatMessage(message.quoted_message),
869
- hardDelete,
870
- deletedAt,
871
- }) as LocalMessage,
872
- });
873
- }
874
- }
875
- });
1440
+ },
1441
+ { coalesce: true },
1442
+ );
876
1443
  };
877
1444
 
878
1445
  /**
@@ -887,7 +1454,7 @@ export class MessageIntervalPaginator extends BasePaginator<
887
1454
 
888
1455
  // Batch: several cached messages may quote the updated one; coalesce the shared-store fan-out
889
1456
  // to a single flush instead of one per re-ingested quoting message.
890
- this._itemIndex.batch(() => {
1457
+ this.batch(() => {
891
1458
  for (const cachedMessage of cachedMessages) {
892
1459
  if (cachedMessage.quoted_message_id !== message.id) continue;
893
1460
 
@@ -913,9 +1480,10 @@ export class MessageIntervalPaginator extends BasePaginator<
913
1480
  let activeAffected = false;
914
1481
  // Batch: a user rename can touch many messages; coalesce the shared-store fan-out to sibling
915
1482
  // holders into a single flush. This paginator's own active window is re-emitted once below.
916
- this._itemIndex.batch(() => {
1483
+ this.batch(() => {
917
1484
  for (const message of this._itemIndex.values()) {
918
1485
  if (message.user?.id !== user.id) continue;
1486
+ if (message.user === user) continue;
919
1487
  this._itemIndex.setOne({ ...message, user });
920
1488
  if (activeIds.has(this.getItemId(message))) activeAffected = true;
921
1489
  }
@@ -927,78 +1495,20 @@ export class MessageIntervalPaginator extends BasePaginator<
927
1495
  }
928
1496
  };
929
1497
 
930
- /**
931
- * Apply a reaction WS event (`reaction.new` / `reaction.updated` / `reaction.deleted`) to the
932
- * cached message. The event's `message` already carries the server-updated
933
- * `reaction_groups` / `latest_reactions`; only `own_reactions` needs local preservation so a
934
- * cross-user reaction does not wipe the current user's reactions. This re-homes what
935
- * `ChannelState.addReaction` / `removeReaction` used to do off the now-removed
936
- * `channel.state.messages` / `channel.state.threads` caches (the same logic backs the thread
937
- * paginator via `Thread.messagePaginator`).
938
- *
939
- * `own_reactions` is seeded from the currently cached item (so another user's reaction keeps ours),
940
- * falling back to the event's own_reactions when the message is not loaded — matching the legacy
941
- * behavior where `_updateMessage` only mutated a message that existed locally.
942
- *
943
- * @param params - The reaction event payload.
944
- * @param params.message - The reaction event's message, carrying the
945
- * server-computed `reaction_groups` / `latest_reactions`. Ingested as-is except for `own_reactions`.
946
- * @param params.reaction - The reaction from the event. Only added to/removed from
947
- * `own_reactions` when its `user_id` is the current user; otherwise the current user's
948
- * `own_reactions` are left untouched.
949
- * @param [params.removed=false] - `true` for `reaction.deleted` (remove the reaction from
950
- * `own_reactions`); `false` for `reaction.new` / `reaction.updated` (add it).
951
- * @param [params.enforceUnique=false] - When adding, first clear the current user's existing
952
- * `own_reactions` so only the incoming one remains (used by `reaction.updated`, where a user's
953
- * reaction replaces their previous one).
954
- *
955
- * TODO(reactive-store): reflect reactions ONCE at the store level, not per-paginator. Both the
956
- * channel handler (channel.ts) and the thread handler (thread.ts) call this on every reaction.*
957
- * event, so a message held in more than one collection (a show_in_channel reply, or the thread
958
- * parent) is reflected TWICE: two writes to the same canonical slot, each fanning out to the
959
- * other holder (double re-projection) and minting a fresh ref that defeats the reconcile
960
- * ref-equality bail. Idempotent (counts come wholesale from the event) so the result is correct,
961
- * just wasteful. The store already fans out to every holder, so reflect once (by id, if held) and
962
- * retire the per-collection reflect calls + parent path + enforce_unique branch.
963
- */
964
- reflectReaction = ({
965
- enforceUnique = false,
966
- message,
967
- reaction,
968
- removed = false,
969
- }: {
970
- message: MessageResponse | LocalMessage;
971
- reaction: ReactionResponse;
972
- enforceUnique?: boolean;
973
- removed?: boolean;
974
- }) => {
975
- const formatted = formatMessage(message);
976
- const existing = this.getItem(formatted.id);
977
- const baseOwnReactions = existing?.own_reactions ?? formatted.own_reactions ?? [];
978
- const own_reactions = computeOwnReactions({
979
- current: baseOwnReactions,
980
- enforceUnique,
981
- reaction,
982
- removed,
983
- userId: this.channel.getClient().userID,
984
- });
985
- this.ingestItem({ ...formatted, own_reactions });
986
- };
987
-
988
1498
  /**
989
1499
  * Map a timestamp to a loaded message — the first message in the latest (head) window whose
990
- * `created_at` is >= `timestampMs` (mirrors the legacy `ChannelState.findMessageByTimestamp`
1500
+ * `created_at` is >= `timestamp` (mirrors the legacy `ChannelState.findMessageByTimestamp`
991
1501
  * lower-bound search), or the newest loaded message when the timestamp is beyond it. Used by the
992
1502
  * receipts tracker to resolve read/delivered cursors. Searches the newest loaded window — where
993
1503
  * read cursors live — which is already sorted, so this is O(log n) with no re-sort.
994
1504
  */
995
1505
  findItemByTimestamp = (
996
- timestampMs: number,
1506
+ timestamp: TimestampNS,
997
1507
  exactTsMatch = false,
998
1508
  ): LocalMessage | null => {
999
1509
  const items = this.headItems; // ascending by created_at
1000
1510
  if (!items.length) return null;
1001
- // Resolve the last message created AT OR BEFORE `timestampMs` (floor). The sole caller is
1511
+ // Resolve the last message created AT OR BEFORE `timestamp` (floor). The sole caller is
1002
1512
  // read/delivered cursor resolution (MessageReceiptsTracker): the cursor carries the timestamp of
1003
1513
  // the last message a participant reached, so a message created strictly after the cursor has NOT
1004
1514
  // been reached. A ceil match (first message >= target) would over-count it — e.g. a participant
@@ -1007,7 +1517,7 @@ export class MessageIntervalPaginator extends BasePaginator<
1007
1517
  // the floor is the item immediately before it.
1008
1518
  const firstAfter = lowerBound(items.length, (i) => {
1009
1519
  const t = getMessageCreatedAtTimestamp(items[i]);
1010
- return t === null || t > timestampMs;
1520
+ return t === null || t > timestamp;
1011
1521
  });
1012
1522
  if (firstAfter === 0) return null; // target precedes every loaded message
1013
1523
  const found = items[firstAfter - 1];
@@ -1016,7 +1526,7 @@ export class MessageIntervalPaginator extends BasePaginator<
1016
1526
  // server timestamp) cannot be located by timestamp.
1017
1527
  if (foundTimestamp === null) return null;
1018
1528
  if (!exactTsMatch) return found;
1019
- return foundTimestamp === timestampMs ? found : null;
1529
+ return foundTimestamp === timestamp ? found : null;
1020
1530
  };
1021
1531
 
1022
1532
  filterQueryResults = (items: LocalMessage[]) =>
@@ -1083,11 +1593,11 @@ const makeDeriveCursor =
1083
1593
  return { cursor, hasMoreHead, hasMoreTail };
1084
1594
  };
1085
1595
 
1086
- if ((ctx.queryShape as MessagePaginationOptions)?.created_at_around) {
1596
+ if ((ctx.queryShape as MessagePaginationParams)?.created_at_around) {
1087
1597
  return injectCursor(
1088
1598
  deriveCreatedAtAroundPaginationFlags<
1089
1599
  LocalMessage,
1090
- MessagePaginationOptions,
1600
+ MessagePaginationParams,
1091
1601
  MessageIntervalPaginator
1092
1602
  >({
1093
1603
  ...ctx,