stream-chat 10.0.0-rc.9 → 10.0.1

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 (361) hide show
  1. package/README.md +7 -6
  2. package/dist/cjs/index.browser.js +21653 -19788
  3. package/dist/cjs/index.browser.js.map +4 -4
  4. package/dist/cjs/index.node.js +21693 -19796
  5. package/dist/cjs/index.node.js.map +4 -4
  6. package/dist/esm/index.mjs +21651 -19786
  7. package/dist/esm/index.mjs.map +4 -4
  8. package/dist/types/ChannelManager.d.ts +216 -135
  9. package/dist/types/CooldownTimer.d.ts +13 -27
  10. package/dist/types/EventHandlerPipeline.d.ts +18 -38
  11. package/dist/types/LiveLocationManager.d.ts +24 -52
  12. package/dist/types/api-client.d.ts +17 -5
  13. package/dist/types/channel.d.ts +432 -470
  14. package/dist/types/channel_state.d.ts +68 -112
  15. package/dist/types/client.d.ts +321 -435
  16. package/dist/types/client_state.d.ts +1 -3
  17. package/dist/types/configuration/ConfigController.d.ts +31 -125
  18. package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +32 -124
  19. package/dist/types/configuration/keys.d.ts +5 -19
  20. package/dist/types/configuration/shape.d.ts +12 -29
  21. package/dist/types/configuration/types.d.ts +64 -79
  22. package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +14 -36
  23. package/dist/types/configuration/utils/copyConfigPatch.d.ts +8 -0
  24. package/dist/types/configuration/utils/declarativeSlices.d.ts +5 -16
  25. package/dist/types/configuration/utils/deepFreezeConfig.d.ts +3 -17
  26. package/dist/types/configuration/utils/serverAuthority.d.ts +9 -29
  27. package/dist/types/connection/ConnectionIdManager.d.ts +45 -0
  28. package/dist/types/connection/ConnectionRecoveryManager.d.ts +84 -0
  29. package/dist/types/connection/index.d.ts +4 -0
  30. package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +82 -0
  31. package/dist/types/connection/networkConnection/index.d.ts +3 -0
  32. package/dist/types/connection/networkConnection/reporters.d.ts +20 -0
  33. package/dist/types/connection/networkConnection/types.d.ts +40 -0
  34. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +137 -0
  35. package/dist/types/connection/wsConnection/WSConnection.d.ts +105 -0
  36. package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +47 -0
  37. package/dist/types/connection/wsConnection/config.d.ts +31 -0
  38. package/dist/types/connection/wsConnection/index.d.ts +4 -0
  39. package/dist/types/connection/wsConnection/types.d.ts +46 -0
  40. package/dist/types/constants.d.ts +2 -0
  41. package/dist/types/custom_types.d.ts +0 -2
  42. package/dist/types/entityStore/EntityStore.d.ts +226 -65
  43. package/dist/types/entityStore/StoreBackedItemIndex.d.ts +19 -33
  44. package/dist/types/entityStore/index.d.ts +0 -1
  45. package/dist/types/errors.d.ts +16 -19
  46. package/dist/types/formatMessageMemo.d.ts +5 -0
  47. package/dist/types/gen/chat/ChannelApi.d.ts +5 -1
  48. package/dist/types/gen/chat/ChatApi.d.ts +149 -105
  49. package/dist/types/gen/models/index.d.ts +2528 -690
  50. package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
  51. package/dist/types/gen/moderation/ModerationApi.d.ts +33 -14
  52. package/dist/types/index.d.ts +10 -6
  53. package/dist/types/{i18n/languageNames.d.ts → languageNames.d.ts} +9 -24
  54. package/dist/types/logger.d.ts +1 -3
  55. package/dist/types/messageComposer/CustomDataManager.d.ts +7 -1
  56. package/dist/types/messageComposer/LocationComposer.d.ts +7 -1
  57. package/dist/types/messageComposer/attachmentIdentity.d.ts +24 -0
  58. package/dist/types/messageComposer/attachmentManager.d.ts +52 -24
  59. package/dist/types/messageComposer/attachmentUtils.d.ts +23 -0
  60. package/dist/types/messageComposer/configuration/configuration.d.ts +2 -5
  61. package/dist/types/messageComposer/configuration/types.d.ts +38 -50
  62. package/dist/types/messageComposer/index.d.ts +1 -0
  63. package/dist/types/messageComposer/linkPreviewsManager.d.ts +12 -9
  64. package/dist/types/messageComposer/messageComposer.d.ts +60 -128
  65. package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +10 -1
  66. package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +4 -0
  67. package/dist/types/messageComposer/middleware/messageComposer/commandInjection.d.ts +5 -0
  68. package/dist/types/messageComposer/middleware/messageComposer/index.d.ts +2 -0
  69. package/dist/types/messageComposer/middleware/messageComposer/pollOnly.d.ts +6 -0
  70. package/dist/types/messageComposer/middleware/messageComposer/userDataInjection.d.ts +5 -0
  71. package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +2 -4
  72. package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +7 -19
  73. package/dist/types/messageComposer/middleware/textComposer/commandUtils.d.ts +4 -0
  74. package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +11 -2
  75. package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +19 -18
  76. package/dist/types/messageComposer/middleware/textComposer/textMiddlewareUtils.d.ts +9 -3
  77. package/dist/types/messageComposer/middleware/textComposer/types.d.ts +1 -6
  78. package/dist/types/messageComposer/pollComposer.d.ts +15 -5
  79. package/dist/types/messageComposer/textComposer.d.ts +14 -7
  80. package/dist/types/messageComposer/types.d.ts +27 -7
  81. package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +27 -80
  82. package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +40 -73
  83. package/dist/types/messageOperations/FailedSendCache.d.ts +29 -0
  84. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +16 -22
  85. package/dist/types/messageOperations/MessageOperations.d.ts +63 -34
  86. package/dist/types/messageOperations/applyReactionLocally.d.ts +15 -0
  87. package/dist/types/messageOperations/createMessageOperations.d.ts +9 -0
  88. package/dist/types/messageOperations/index.d.ts +6 -4
  89. package/dist/types/messageOperations/reflectReactionEvent.d.ts +16 -0
  90. package/dist/types/messageOperations/sendOrdering.d.ts +14 -0
  91. package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +20 -0
  92. package/dist/types/messageOperations/types.d.ts +43 -14
  93. package/dist/types/middleware.d.ts +10 -0
  94. package/dist/types/moderation.d.ts +21 -14
  95. package/dist/types/notifications/NotificationManager.d.ts +10 -23
  96. package/dist/types/notifications/types.d.ts +21 -57
  97. package/dist/types/offline-support/offline_support_api.d.ts +150 -528
  98. package/dist/types/offline-support/offline_sync_manager.d.ts +21 -42
  99. package/dist/types/offline-support/queueableOperations.d.ts +35 -37
  100. package/dist/types/offline-support/types.d.ts +40 -186
  101. package/dist/types/pagination/FilterBuilder.d.ts +1 -18
  102. package/dist/types/pagination/ItemIndex.d.ts +4 -12
  103. package/dist/types/pagination/cursorDerivation/aroundPaginationFlags.d.ts +13 -0
  104. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +4 -5
  105. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +19 -5
  106. package/dist/types/pagination/index.d.ts +1 -0
  107. package/dist/types/pagination/paginators/BasePaginator.d.ts +604 -550
  108. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +123 -106
  109. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +576 -334
  110. package/dist/types/pagination/paginators/MessagePaginator.d.ts +239 -131
  111. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +15 -26
  112. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +4 -3
  113. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +44 -0
  114. package/dist/types/pagination/paginators/UserGroupPaginator.d.ts +5 -8
  115. package/dist/types/pagination/paginators/index.d.ts +1 -0
  116. package/dist/types/pagination/sortCompiler.d.ts +11 -22
  117. package/dist/types/pagination/utility.normalization.d.ts +5 -23
  118. package/dist/types/pagination/utility.search.d.ts +3 -8
  119. package/dist/types/poll.d.ts +34 -8
  120. package/dist/types/poll_manager.d.ts +12 -2
  121. package/dist/types/poll_optimistic_votes.d.ts +57 -0
  122. package/dist/types/reminders/Reminder.d.ts +11 -11
  123. package/dist/types/reminders/ReminderManager.d.ts +13 -25
  124. package/dist/types/search/BaseSearchSource.d.ts +10 -8
  125. package/dist/types/search/ChannelSearchSource.d.ts +16 -0
  126. package/dist/types/search/MessageSearchSource.d.ts +17 -0
  127. package/dist/types/search/SearchController.d.ts +26 -28
  128. package/dist/types/search/types.d.ts +6 -10
  129. package/dist/types/signing.d.ts +12 -3
  130. package/dist/types/thread.d.ts +63 -129
  131. package/dist/types/thread_manager.d.ts +95 -66
  132. package/dist/types/token_manager.d.ts +8 -13
  133. package/dist/types/types.d.ts +81 -199
  134. package/dist/types/types.utility.d.ts +3 -3
  135. package/dist/types/upload-utils.d.ts +5 -10
  136. package/dist/types/uploadManager.d.ts +31 -11
  137. package/dist/types/utils/FixedSizeQueueCache.d.ts +8 -11
  138. package/dist/types/utils/WithSubscriptions.d.ts +6 -16
  139. package/dist/types/utils/abort.d.ts +17 -0
  140. package/dist/types/utils/concurrency.d.ts +12 -20
  141. package/dist/types/utils/mergeWith/mergeWith.d.ts +8 -11
  142. package/dist/types/utils/mergeWith/mergeWithCore.d.ts +5 -13
  143. package/dist/types/utils/mergeWith/mergeWithDiff.d.ts +22 -0
  144. package/dist/types/utils/objectPath.d.ts +6 -41
  145. package/dist/types/utils/retryable.d.ts +8 -12
  146. package/dist/types/utils/throttling/throttle.d.ts +8 -23
  147. package/dist/types/utils/time.d.ts +33 -57
  148. package/dist/types/utils.d.ts +72 -91
  149. package/package.json +14 -40
  150. package/src/ChannelManager.ts +494 -303
  151. package/src/CooldownTimer.ts +28 -38
  152. package/src/EventHandlerPipeline.ts +22 -45
  153. package/src/LiveLocationManager.ts +37 -76
  154. package/src/api-client.ts +113 -50
  155. package/src/campaign.ts +1 -1
  156. package/src/channel.ts +1067 -1276
  157. package/src/channel_batch_updater.ts +1 -1
  158. package/src/channel_state.ts +73 -168
  159. package/src/client.ts +744 -974
  160. package/src/client_state.ts +3 -8
  161. package/src/configuration/ConfigController.ts +42 -158
  162. package/src/configuration/InstanceConfigurationRegistry.ts +43 -172
  163. package/src/configuration/index.ts +1 -1
  164. package/src/configuration/keys.ts +13 -32
  165. package/src/configuration/shape.ts +169 -59
  166. package/src/configuration/types.ts +69 -92
  167. package/src/configuration/utils/applyInstanceConfiguration.ts +22 -54
  168. package/src/configuration/utils/copyConfigPatch.ts +11 -32
  169. package/src/configuration/utils/declarativeSlices.ts +9 -39
  170. package/src/configuration/utils/deepFreezeConfig.ts +3 -17
  171. package/src/configuration/utils/index.ts +2 -4
  172. package/src/configuration/utils/serverAuthority.ts +20 -68
  173. package/src/connection/ConnectionIdManager.ts +111 -0
  174. package/src/connection/ConnectionRecoveryManager.ts +257 -0
  175. package/src/connection/index.ts +4 -0
  176. package/src/connection/networkConnection/NetworkConnectionObserver.ts +204 -0
  177. package/src/connection/networkConnection/index.ts +3 -0
  178. package/src/connection/networkConnection/reporters.ts +58 -0
  179. package/src/connection/networkConnection/types.ts +45 -0
  180. package/src/{connection.ts → connection/wsConnection/StableWSConnection.ts} +230 -232
  181. package/src/connection/wsConnection/WSConnection.ts +270 -0
  182. package/src/connection/wsConnection/WSConnectionFallback.ts +250 -0
  183. package/src/connection/wsConnection/config.ts +73 -0
  184. package/src/connection/wsConnection/index.ts +4 -0
  185. package/src/connection/wsConnection/types.ts +48 -0
  186. package/src/constants.ts +6 -5
  187. package/src/custom_types.ts +0 -1
  188. package/src/entityStore/EntityStore.ts +415 -79
  189. package/src/entityStore/StoreBackedItemIndex.ts +37 -41
  190. package/src/entityStore/index.ts +0 -1
  191. package/src/errors.ts +39 -20
  192. package/src/formatMessageMemo.ts +17 -0
  193. package/src/gen/chat/ChannelApi.ts +122 -36
  194. package/src/gen/chat/ChatApi.ts +578 -1540
  195. package/src/gen/models/index.ts +2498 -3383
  196. package/src/gen/models/timestamp-guard.ts +27 -0
  197. package/src/gen/moderation/ModerationApi.ts +170 -367
  198. package/src/index.ts +22 -10
  199. package/src/languageNames.ts +88 -0
  200. package/src/logger.ts +1 -3
  201. package/src/messageComposer/CustomDataManager.ts +19 -6
  202. package/src/messageComposer/LocationComposer.ts +19 -23
  203. package/src/messageComposer/MessageComposerEffectHandlers.ts +1 -2
  204. package/src/messageComposer/attachmentIdentity.ts +54 -0
  205. package/src/messageComposer/attachmentManager.ts +170 -185
  206. package/src/messageComposer/attachmentUtils.ts +44 -0
  207. package/src/messageComposer/configuration/configuration.ts +15 -8
  208. package/src/messageComposer/configuration/types.ts +38 -50
  209. package/src/messageComposer/fileUtils.ts +1 -1
  210. package/src/messageComposer/index.ts +1 -0
  211. package/src/messageComposer/linkPreviewsManager.ts +18 -21
  212. package/src/messageComposer/messageComposer.ts +223 -174
  213. package/src/messageComposer/middleware/attachmentManager/postUpload/AttachmentPostUploadMiddlewareExecutor.ts +1 -1
  214. package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +46 -33
  215. package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +4 -1
  216. package/src/messageComposer/middleware/attachmentManager/preUpload/blockedUploadNotification.ts +1 -1
  217. package/src/messageComposer/middleware/messageComposer/MessageComposerMiddlewareExecutor.ts +6 -0
  218. package/src/messageComposer/middleware/messageComposer/attachments.ts +76 -5
  219. package/src/messageComposer/middleware/messageComposer/commandInjection.ts +10 -4
  220. package/src/messageComposer/middleware/messageComposer/customData.ts +17 -5
  221. package/src/messageComposer/middleware/messageComposer/index.ts +2 -0
  222. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +22 -12
  223. package/src/messageComposer/middleware/messageComposer/pollOnly.ts +9 -1
  224. package/src/messageComposer/middleware/messageComposer/textComposer.ts +1 -1
  225. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +12 -12
  226. package/src/messageComposer/middleware/pollComposer/state.ts +2 -2
  227. package/src/messageComposer/middleware/pollComposer/types.ts +2 -4
  228. package/src/messageComposer/middleware/pollComposer/validation.ts +8 -26
  229. package/src/messageComposer/middleware/textComposer/TextComposerMiddlewareExecutor.ts +8 -6
  230. package/src/messageComposer/middleware/textComposer/commandUtils.ts +10 -3
  231. package/src/messageComposer/middleware/textComposer/commands.ts +11 -16
  232. package/src/messageComposer/middleware/textComposer/mentions.ts +32 -70
  233. package/src/messageComposer/middleware/textComposer/textMiddlewareUtils.ts +10 -4
  234. package/src/messageComposer/middleware/textComposer/types.ts +1 -6
  235. package/src/messageComposer/pollComposer.ts +21 -9
  236. package/src/messageComposer/textComposer.ts +37 -57
  237. package/src/messageComposer/types.ts +39 -11
  238. package/src/messageDelivery/MessageDeliveryReporter.ts +86 -125
  239. package/src/messageDelivery/MessageReceiptsTracker.ts +88 -101
  240. package/src/messageOperations/FailedSendCache.ts +85 -0
  241. package/src/messageOperations/MessageOperationStatePolicy.ts +121 -112
  242. package/src/messageOperations/MessageOperations.ts +297 -175
  243. package/src/{entityStore → messageOperations}/applyReactionLocally.ts +9 -28
  244. package/src/messageOperations/createMessageOperations.ts +176 -0
  245. package/src/messageOperations/index.ts +6 -14
  246. package/src/messageOperations/reflectReactionEvent.ts +43 -0
  247. package/src/messageOperations/sendOrdering.ts +25 -0
  248. package/src/messageOperations/settlePendingAttachmentUploads.ts +98 -0
  249. package/src/messageOperations/types.ts +51 -13
  250. package/src/middleware.ts +13 -5
  251. package/src/moderation.ts +25 -21
  252. package/src/notifications/NotificationManager.ts +19 -28
  253. package/src/notifications/types.ts +21 -57
  254. package/src/offline-support/offline_support_api.ts +226 -669
  255. package/src/offline-support/offline_sync_manager.ts +51 -80
  256. package/src/offline-support/queueableOperations.ts +98 -73
  257. package/src/offline-support/types.ts +43 -186
  258. package/src/pagination/FilterBuilder.ts +1 -22
  259. package/src/pagination/ItemIndex.ts +4 -12
  260. package/src/pagination/cursorDerivation/aroundPaginationFlags.ts +29 -0
  261. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +15 -63
  262. package/src/pagination/cursorDerivation/idAroundPaginationFlags.ts +11 -39
  263. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +53 -33
  264. package/src/pagination/filterCompiler.ts +11 -25
  265. package/src/pagination/index.ts +1 -0
  266. package/src/pagination/paginators/BasePaginator.ts +1415 -1041
  267. package/src/pagination/paginators/ChannelPaginator.ts +479 -217
  268. package/src/pagination/paginators/MessageIntervalPaginator.ts +1351 -772
  269. package/src/pagination/paginators/MessagePaginator.ts +518 -233
  270. package/src/pagination/paginators/PinnedMessagePaginator.ts +32 -40
  271. package/src/pagination/paginators/ReminderPaginator.ts +21 -16
  272. package/src/pagination/paginators/ThreadPaginator.ts +170 -0
  273. package/src/pagination/paginators/UserGroupPaginator.ts +16 -19
  274. package/src/pagination/paginators/index.ts +1 -0
  275. package/src/pagination/paginators/stateThrottling.ts +5 -10
  276. package/src/pagination/sortCompiler.ts +23 -50
  277. package/src/pagination/utility.normalization.ts +8 -30
  278. package/src/pagination/utility.search.ts +4 -11
  279. package/src/poll.ts +177 -98
  280. package/src/poll_manager.ts +24 -22
  281. package/src/poll_optimistic_votes.ts +335 -0
  282. package/src/reminders/Reminder.ts +16 -12
  283. package/src/reminders/ReminderManager.ts +22 -55
  284. package/src/reminders/ReminderTimer.ts +1 -2
  285. package/src/search/BaseSearchSource.ts +19 -25
  286. package/src/search/ChannelSearchSource.ts +43 -1
  287. package/src/search/MessageSearchSource.ts +77 -13
  288. package/src/search/SearchController.ts +39 -36
  289. package/src/search/types.ts +6 -10
  290. package/src/segment.ts +1 -1
  291. package/src/signing.ts +23 -3
  292. package/src/thread.ts +418 -703
  293. package/src/thread_manager.ts +300 -234
  294. package/src/token_manager.ts +12 -22
  295. package/src/types.ts +102 -216
  296. package/src/types.utility.ts +3 -3
  297. package/src/upload-utils.ts +5 -10
  298. package/src/uploadManager.ts +64 -18
  299. package/src/utils/FixedSizeQueueCache.ts +18 -21
  300. package/src/utils/WithSubscriptions.ts +6 -16
  301. package/src/utils/abort.ts +45 -0
  302. package/src/utils/concurrency.ts +16 -55
  303. package/src/utils/mergeWith/mergeWith.ts +10 -13
  304. package/src/utils/mergeWith/mergeWithCore.ts +24 -81
  305. package/src/utils/mergeWith/mergeWithDiff.ts +15 -33
  306. package/src/utils/objectPath.ts +6 -41
  307. package/src/utils/retryable.ts +10 -14
  308. package/src/utils/throttling/throttle.ts +9 -25
  309. package/src/utils/time.ts +40 -60
  310. package/src/utils.ts +181 -174
  311. package/codegen/i18n/callSites.ts +0 -126
  312. package/codegen/i18n/generate.ts +0 -226
  313. package/codegen/i18n/guards.ts +0 -178
  314. package/codegen/i18n/index.ts +0 -29
  315. package/codegen/i18n/stringMaps.ts +0 -91
  316. package/codegen/i18n/types.ts +0 -100
  317. package/dist/cjs/i18n.browser.js +0 -1131
  318. package/dist/cjs/i18n.browser.js.map +0 -7
  319. package/dist/cjs/i18n.node.js +0 -1160
  320. package/dist/cjs/i18n.node.js.map +0 -7
  321. package/dist/esm/i18n-codegen.mjs +0 -409
  322. package/dist/esm/i18n-codegen.mjs.map +0 -7
  323. package/dist/esm/i18n.mjs +0 -1098
  324. package/dist/esm/i18n.mjs.map +0 -7
  325. package/dist/types/ConnectionRecoveryManager.d.ts +0 -156
  326. package/dist/types/connection.d.ts +0 -139
  327. package/dist/types/entityStore/applyReactionLocally.d.ts +0 -32
  328. package/dist/types/i18n/Streami18n.d.ts +0 -168
  329. package/dist/types/i18n/TranslationBuilder.d.ts +0 -70
  330. package/dist/types/i18n/TranslationStore.d.ts +0 -57
  331. package/dist/types/i18n/dayjs.d.ts +0 -104
  332. package/dist/types/i18n/formatters.d.ts +0 -91
  333. package/dist/types/i18n/index.d.ts +0 -15
  334. package/dist/types/i18n/translator.d.ts +0 -29
  335. package/dist/types/i18n/types.d.ts +0 -262
  336. package/dist/types/i18n-codegen/callSites.d.ts +0 -10
  337. package/dist/types/i18n-codegen/generate.d.ts +0 -15
  338. package/dist/types/i18n-codegen/guards.d.ts +0 -61
  339. package/dist/types/i18n-codegen/index.d.ts +0 -29
  340. package/dist/types/i18n-codegen/stringMaps.d.ts +0 -14
  341. package/dist/types/i18n-codegen/types.d.ts +0 -94
  342. package/dist/types/insights.d.ts +0 -56
  343. package/dist/types/messageOperations/optimistic.d.ts +0 -118
  344. package/dist/types/messageOperations/persistence.d.ts +0 -21
  345. package/dist/types/pagination/utility.queryChannel.d.ts +0 -26
  346. package/dist/types/store.d.ts +0 -125
  347. package/src/ConnectionRecoveryManager.ts +0 -293
  348. package/src/i18n/Streami18n.ts +0 -520
  349. package/src/i18n/TranslationBuilder.ts +0 -176
  350. package/src/i18n/TranslationStore.ts +0 -96
  351. package/src/i18n/dayjs.ts +0 -228
  352. package/src/i18n/formatters.ts +0 -461
  353. package/src/i18n/index.ts +0 -15
  354. package/src/i18n/languageNames.ts +0 -103
  355. package/src/i18n/translator.ts +0 -76
  356. package/src/i18n/types.ts +0 -375
  357. package/src/insights.ts +0 -82
  358. package/src/messageOperations/optimistic.ts +0 -257
  359. package/src/messageOperations/persistence.ts +0 -40
  360. package/src/pagination/utility.queryChannel.ts +0 -84
  361. package/src/store.ts +0 -304
@@ -1,13 +1,15 @@
1
1
  import type {
2
2
  AnyInterval,
3
3
  BasePaginatorConfig,
4
- CursorDerivator,
4
+ CursorDeriveContext,
5
5
  CursorDeriveResult,
6
+ DoRequestResponse,
7
+ ExecuteQueryReturnValue,
6
8
  Interval,
7
9
  PaginationDirection,
8
10
  PaginationQueryParams,
9
- PaginatorCursor,
10
11
  PaginatorState,
12
+ QueryPagePlacement,
11
13
  } from './BasePaginator';
12
14
  import {
13
15
  BasePaginator,
@@ -18,21 +20,25 @@ import {
18
20
  ZERO_PAGE_CURSOR,
19
21
  } from './BasePaginator';
20
22
  import type {
23
+ ChannelStateResponse,
24
+ GetRepliesResponse,
21
25
  LocalMessage,
22
26
  MessagePaginationParams,
23
- MessageResponse,
24
27
  PinnedMessagePaginationOptions,
25
- ReactionResponse,
26
28
  SortParamRequest,
29
+ StreamResponse,
30
+ TimestampNS,
27
31
  UserResponse,
28
32
  } from '../../types';
29
33
  import type { Channel } from '../../channel';
34
+ import type { Thread } from '../../thread';
35
+ import { ChannelWatchStatus } from '../../channel_state';
30
36
  import { CORE_NOTIFICATION_TYPE } from '../../notifications';
31
- import { StateStore } from '../../store';
37
+ import { StateStore } from '@stream-io/state-store';
32
38
  import {
33
- computeOwnReactions,
34
39
  formatMessage,
35
40
  generateUUIDv4,
41
+ isThreadOnlyReply,
36
42
  toDeletedMessage,
37
43
  } from '../../utils';
38
44
  import { makeComparator } from '../sortCompiler';
@@ -44,7 +50,10 @@ import type { EntityStoreChangeBatch } from '../../entityStore/EntityStore';
44
50
  import { StoreBackedItemIndex } from '../../entityStore/StoreBackedItemIndex';
45
51
  import { deriveCreatedAtAroundPaginationFlags } from '../cursorDerivation';
46
52
  import { deriveIdAroundPaginationFlags } from '../cursorDerivation/idAroundPaginationFlags';
47
- import { deriveLinearPaginationFlags } from '../cursorDerivation/linearPaginationFlags';
53
+ import {
54
+ deriveLinearPaginationFlags,
55
+ getLinearQueryDirection,
56
+ } from '../cursorDerivation/linearPaginationFlags';
48
57
 
49
58
  export type MessageFocusReason =
50
59
  | 'jump-to-message'
@@ -65,20 +74,19 @@ export type MessageFocusSignalState = {
65
74
 
66
75
  export type JumpToMessageOptions = {
67
76
  pageSize?: number;
68
- /**
69
- * Optional reason attached to emitted focus signal.
70
- * Defaults to `jump-to-message`.
71
- */
77
+ /** Reason attached to the emitted focus signal. Defaults to `jump-to-message`. */
72
78
  focusReason?: MessageFocusReason;
73
- /**
74
- * TTL for the emitted focus signal in milliseconds.
75
- * Defaults to `3000`.
76
- */
79
+ /** TTL of the emitted focus signal in milliseconds. Defaults to `3000`. */
77
80
  focusSignalTtlMs?: number;
81
+ /** Suppresses the focus signal after a successful jump. */
82
+ suppressFocusSignal?: boolean;
78
83
  /**
79
- * If true, suppresses focus signal emission after a successful jump.
84
+ * Also watches the channel (so it receives events) when it is not watched yet. The request that
85
+ * loads the interval around the message asks to watch too, so it stays one request, and a message
86
+ * already loaded is loaded again. Ignored for a thread's reply list (its request cannot watch)
87
+ * and when the paginator's `doRequest` loads the messages.
80
88
  */
81
- suppressFocusSignal?: boolean;
89
+ watchChannel?: boolean;
82
90
  };
83
91
 
84
92
  export type MessagePaginatorSort = SortParamRequest[];
@@ -102,11 +110,12 @@ export type MessagePaginatorState = PaginatorState<LocalMessage>;
102
110
  export type MessageQueryShape = MessagePaginationParams | PinnedMessagePaginationOptions;
103
111
 
104
112
  /**
105
- * At the moment all the pagination parameters are just different types of cursors, e.g.
106
- * id_lt, id_gt, ...
107
- * But we always paginate within the same list without changing the sorting params.
108
- * It is currently not possible to change the sorting params.
113
+ * Whether a query asks for no messages (`limit: 0`). Its empty page says nothing about the channel,
114
+ * so it must not be read as an empty one.
109
115
  */
116
+ const isQueryForNoMessages = (limit: number) => limit === 0;
117
+
118
+ /** Query shapes are cursors within one list (the sort cannot change), so a change never resets it. */
110
119
  const hasPaginationQueryShapeChanged: PaginationQueryShapeChangeIdentifier<
111
120
  MessageQueryShape
112
121
  > = () => false;
@@ -116,16 +125,10 @@ const dataFieldFilterResolver: FieldToDataResolver<LocalMessage> = {
116
125
  resolve: (message, path) => resolveDotPathValue(message, path),
117
126
  };
118
127
 
119
- /**
120
- * A message's `created_at` as the comparable wire timestamp (unix nanoseconds), or `null` when it
121
- * is absent or not a finite number.
122
- *
123
- * Accepts `null`/`undefined` so callers holding an optional message (e.g.
124
- * `MessagePaginator.lastMessage`) do not each repeat the guard.
125
- */
128
+ /** A message's `created_at` (unix nanoseconds), or `null` when absent or not finite. */
126
129
  export const getMessageCreatedAtTimestamp = (
127
130
  message: LocalMessage | null | undefined,
128
- ): number | null => {
131
+ ): TimestampNS | null => {
129
132
  const timestamp = message?.created_at;
130
133
  return typeof timestamp === 'number' && Number.isFinite(timestamp) ? timestamp : null;
131
134
  };
@@ -135,140 +138,189 @@ export type MessagePaginatorOptions = {
135
138
  id?: string;
136
139
  itemIndex?: ItemIndexApi<LocalMessage>;
137
140
  parentMessageId?: string;
138
- /**
139
- * Sort passed to backend message/replies query.
140
- * Does not affect in-memory item ordering.
141
- */
141
+ /** Sort sent to the backend messages/replies query. Does not affect in-memory ordering. */
142
142
  requestSort?: MessagePaginatorSort;
143
143
  /**
144
144
  * @deprecated Use `requestSort` instead.
145
145
  */
146
146
  sort?: MessagePaginatorSort;
147
- /**
148
- * In-memory ordering for items exposed by paginator state.
149
- */
147
+ /** In-memory ordering of the items exposed by paginator state. */
150
148
  itemOrder?: MessagePaginatorSort;
149
+ /** The thread whose replies this paginator lists; without it, it lists the channel's messages. */
150
+ thread?: Thread;
151
151
  paginatorOptions?: PaginatorOptions<LocalMessage, MessageQueryShape>;
152
152
  };
153
153
 
154
154
  /**
155
- * Options for {@link MessageIntervalPaginator.mergeNewestPage} that enable destructive
156
- * reconciliation — removing messages that were hard-deleted (by anyone) while the client was
157
- * offline. A hard delete emits no event to other clients, and the merge is otherwise additive, so
158
- * without this such a message lingers as a ghost after reconnect.
159
- *
160
- * Throughout, `page` is the newest window the server returned for `mergeNewestPage`, and "`page`'s
161
- * newest / oldest message" are its bounds by `created_at`. With NO options, `mergeNewestPage` prunes
162
- * any loaded message that falls WITHIN `page`'s `created_at` span but is absent from it —
163
- * unconditionally safe (a message that arrived live during the caller's fetch is always strictly
164
- * newer than `page`'s newest message, so it can never fall in that span). `candidateIds` widens the
165
- * reconcilable window at the TOP edge; `requestedLimit` only tunes the `hasMoreTail` affordance and
166
- * can never remove a message:
155
+ * Options for {@link MessageIntervalPaginator.reconcileNewestMessages} that enable reconciling
156
+ * messages hard-deleted while the client received no events (no event reaches other clients). With
157
+ * no options it prunes loaded messages inside `page`'s `created_at` span that are absent from it,
158
+ * which is always safe: a live arrival is newer than `page`'s newest message.
159
+ * `headIntervalItemIdsAtRequest` widens reconciliation at the top edge; `requestedLimit` says
160
+ * whether the page reached the channel start.
167
161
  */
168
- export type MergeNewestPageOptions = {
162
+ export type ReconcileNewestMessagesOptions = {
169
163
  /**
170
- * The `limit` the caller passed to the query that produced `page`. Used ONLY to derive
171
- * `hasMoreTail` — whether `page` reached the channel's own oldest message — by comparing it to
172
- * `page.length`. It NEVER removes a message (reconciliation stays window-only regardless), so the
173
- * worst a wrong value can do is show/hide the "load older" affordance for one settle. Trusted only
174
- * when no larger than the paginator's own `pageSize` (see
175
- * {@link MessageIntervalPaginator.pageReachedChannelStart}); a larger over-request — e.g.
176
- * `channel.reload` re-fetching the whole loaded window to reconcile as much as possible — may have
177
- * been silently server-capped, so its short page is ignored rather than mistaken for reaching the
178
- * start.
164
+ * The `limit` the caller passed to the query that produced `page`. Compared to `page.length`, it
165
+ * says whether `page` reached the channel start (see
166
+ * {@link MessageIntervalPaginator.pageReachedChannelStart}, which ignores a limit above
167
+ * `pageSize`), deciding `hasMoreTail`, whether `page` can be separated from the head interval by
168
+ * a gap, and whether a reload asks the server about messages deleted below the page (see
169
+ * {@link MessageIntervalPaginator.removeIdsTailwardOfPageIfNothingOlder}). On its own it never
170
+ * removes a message. Pass the limit actually sent: a larger one makes a short page look like the
171
+ * channel start, welding it to the head interval across a real gap.
179
172
  */
180
173
  requestedLimit?: number;
181
174
  /**
182
- * A snapshot of the loaded message ids taken BEFORE the caller's fetch await. Required to prune
183
- * messages NEWER than `page`'s newest message (a hard-deleted newest message) and to reconcile an
184
- * empty `page` (a fully-emptied channel): at/above that top edge a just-deleted message and a
185
- * message that arrived live during the fetch are indistinguishable by timestamp — only the pre-fetch
186
- * snapshot separates them (a live arrival is not in it). Must be captured before the await; the
187
- * paginator's own items at merge time already include any live arrival.
175
+ * The IDs of the head interval's server-confirmed items when the request for `page` went out,
176
+ * taken with {@link MessageIntervalPaginator.getHeadIntervalItemIdsAtRequest} before the request
177
+ * is awaited. Only these prove what `page` says about the head interval:
178
+ *
179
+ * - deletion: at or above `page`'s newest message, and for an empty `page`, only this snapshot
180
+ * tells a just-deleted message from one that arrived live, or was sent, during the request;
181
+ * - contiguity: `page` starts inside the head interval only if its oldest message the head
182
+ * interval could hold is in this snapshot (see `isSeparatedFromHeadByGap`).
183
+ *
184
+ * Only the head interval receives live messages, so only its IDs are needed.
188
185
  */
189
- candidateIds?: ReadonlySet<string>;
186
+ headIntervalItemIdsAtRequest?: ReadonlySet<string>;
187
+ };
188
+
189
+ /** An external query prepared by {@link MessageIntervalPaginator.prepareExternalQuery}. */
190
+ export type PreparedExternalQuery = {
191
+ messagePaginationParams: MessagePaginationParams;
192
+ isNewestPage: boolean;
193
+ placePage: (page: LocalMessage[]) => boolean;
190
194
  };
191
195
 
192
196
  /**
193
- * Options for {@link MessageIntervalPaginator.seedFirstPageSync}, the synchronous channel-open seed.
197
+ * What one of the message paginator's own queries got back, before its page is extracted (see
198
+ * {@link MessageIntervalPaginator.fetchQueryResponse}), by where it came from.
194
199
  */
195
- export type SeedFirstPageOptions = {
196
- /**
197
- * When true and the paginator has already been seeded once, fold the fresh page via
198
- * {@link MessageIntervalPaginator.mergeNewestPage} — merge in place, reconcile offline hard-deletes,
199
- * re-derive the tail cursor, rebuild on a disjoint window, and skip when jumped away from the head —
200
- * instead of a plain first-page ingest. Lets callers (channel.reload, the channel-list hydrate,
201
- * connection recovery) share one reconciling seed path. Left false for the differently-sorted
202
- * pinned list, and a no-op on a cold open (nothing loaded to fold).
203
- */
204
- reconcile?: boolean;
205
- /**
206
- * Pre-fetch snapshot of loaded message ids (captured before the caller's network await), forwarded
207
- * to {@link MergeNewestPageOptions.candidateIds} so a hard-deleted NEWEST message is reconciled
208
- * without mistaking a message that arrived live during the fetch for a delete. Only consulted when
209
- * {@link reconcile} is set and a window is already loaded.
210
- */
211
- candidateIds?: ReadonlySet<string>;
212
- };
200
+ export type MessageQueryResponse =
201
+ | {
202
+ /** what a custom `doRequest` returned: the page, used as is */
203
+ doRequestResponse: DoRequestResponse<LocalMessage>;
204
+ source: 'doRequest';
205
+ }
206
+ | {
207
+ /** the replies endpoint's response for a thread's reply list */
208
+ repliesResponse: GetRepliesResponse;
209
+ source: 'replies';
210
+ }
211
+ | {
212
+ /** the response of a channel query: its messages, and the rest, applied once they are placed */
213
+ channelResponse: StreamResponse<ChannelStateResponse>;
214
+ source: 'channel';
215
+ /** whether the query watched the channel, which applying the response records */
216
+ watch: boolean;
217
+ };
213
218
 
214
219
  /**
215
- * MessageIntervalPaginator allows configuring backend request sort, while keeping internal item ordering stable.
216
- * Filtering of ingested items is still limited to local predicates (`filterQueryResults`).
220
+ * A message list with a configurable backend request sort and a stable in-memory item order.
221
+ * Ingested items are filtered only by local predicates (`filterQueryResults`).
217
222
  */
218
223
  export class MessageIntervalPaginator extends BasePaginator<
219
224
  LocalMessage,
220
- MessageQueryShape
225
+ MessageQueryShape,
226
+ MessageQueryResponse
221
227
  > {
228
+ /**
229
+ * Holder name of this list's index in the message store. A getter, so a subclass's value is in
230
+ * place while the base constructor builds the index.
231
+ */
232
+ protected get holderName() {
233
+ return 'message-interval-paginator';
234
+ }
235
+
222
236
  declare state: StateStore<MessagePaginatorState>;
223
237
  private readonly _id: string;
224
- protected channel: Channel;
225
- protected parentMessageId?: string;
238
+ /** The channel this list belongs to. A thread's reply list holds its parent channel. */
239
+ readonly channel: Channel;
240
+ /** See {@link MessagePaginatorOptions.thread}. */
241
+ readonly thread?: Thread;
242
+ /** Set when this is a thread's reply list, to the parent message's ID. */
243
+ readonly parentMessageId?: string;
226
244
  readonly messageFocusSignal: StateStore<MessageFocusSignalState>;
227
245
  private clearMessageFocusSignalTimeoutId: ReturnType<typeof setTimeout> | null = null;
228
246
  private messageFocusSignalToken = 0;
229
247
  protected _requestSort = DEFAULT_BACKEND_SORT;
230
248
  protected _itemOrder: MessagePaginatorSort = DEFAULT_BACKEND_SORT;
231
- protected _nextQueryShape: MessageQueryShape | undefined;
232
- /** Pending below-window reached-start probe (exposed for deterministic test awaiting). */
233
- private _belowWindowReconcile?: Promise<void>;
249
+ /** The pending {@link removeIdsTailwardOfPageIfNothingOlder} (kept so tests can await it). */
250
+ private _pendingTailwardOfPageRemoval?: Promise<void>;
251
+ /**
252
+ * The ID of the newest server-confirmed message of the interval whose head mark was cleared last
253
+ * (see {@link unmarkedHeadInterval}). Forgotten once a newest page is reconciled with no head
254
+ * interval loaded, and when the loaded intervals are cleared.
255
+ */
256
+ private unmarkedHeadEdgeId: string | undefined;
234
257
  sortComparator: (a: LocalMessage, b: LocalMessage) => number;
235
258
  /**
236
- * Single source of truth for whether a message should be included in paginator intervals/state.
237
- * Keep this consistent with `filterQueryResults` AND cursor flag derivation.
259
+ * Whether a message belongs in intervals and state. Keep it consistent with `filterQueryResults`
260
+ * and with the page the linear cursor flag derivation reads (see {@link deriveCursorFromPage}).
238
261
  */
239
262
  shouldIncludeMessageInInterval(message: LocalMessage): boolean {
240
263
  return !message.shadowed;
241
264
  }
242
265
 
243
266
  /**
244
- * Entity-store adapter (this paginator is an `EntityStoreSubscriber`): the `EntityStore` calls this
245
- * on each holder with the subset of its watched ids that changed. Unwraps the batch and delegates to
246
- * the base's store-agnostic {@link BasePaginator.reconcileChangedIds}. Lives here, not on the generic
247
- * `BasePaginator`, so the base stays free of `EntityStore` types — only message paginators are
248
- * store-backed.
267
+ * Reconciles the held messages that changed in the entity store.
268
+ *
269
+ * @internal
270
+ * @param batch - The change batch from the store.
271
+ * @param batch.changedIds - IDs of the watched messages that changed.
249
272
  */
250
273
  onEntitiesChanged({ changedIds }: EntityStoreChangeBatch): void {
251
274
  this.reconcileChangedIds(changedIds);
252
275
  }
253
276
 
254
277
  /**
255
- * Entity-store subscriber flush (the optional `EntityStoreSubscriber.flushState`): the `EntityStore`
256
- * calls this after an optimistic (local-user) write so the change renders without throttle delay.
257
- * Delegates to the base's generic {@link BasePaginator.flushPendingPublishes}.
278
+ * Drops a message from this paginator's intervals after the entity store removed it.
279
+ *
280
+ * @internal
281
+ * @param id - ID of the removed message.
282
+ * @param message - The removed message.
258
283
  */
284
+ onEntityRemoved(id: string, message: unknown): void {
285
+ this.removeItem({ id, item: message as LocalMessage });
286
+ }
287
+
288
+ /** Entity-store subscriber flush after an optimistic (local-user) write: skips the throttle. */
259
289
  flushState(): void {
260
290
  this.flushPendingPublishes();
261
291
  }
262
292
 
293
+ /** UI-driven "hold off on pruning" signal ({@link setPruningSuspended}). Off by default. */
294
+ protected get isPruningSuspended(): boolean {
295
+ return this._pruningSuspended;
296
+ }
297
+
298
+ private _pruningSuspended = false;
299
+
300
+ /**
301
+ * Holds off dropping the oldest loaded messages, so pruning does not pull content from under a user
302
+ * reading near them: the interval may grow past `maxLoadedItems` until they scroll back. A plain
303
+ * field, not a `StateStore`: nothing observes it and a scroll-driven signal must not cost a render.
304
+ */
305
+ setPruningSuspended = (suspended: boolean) => {
306
+ this._pruningSuspended = suspended;
307
+ };
308
+
309
+ /**
310
+ * A message anchors pagination once the server has acknowledged it. This keeps an unsent message
311
+ * out of both halves of a prune and stops its ID from becoming the tailward cursor (`id_lt`).
312
+ */
313
+ protected isPaginationAnchorable(item: LocalMessage | undefined): boolean {
314
+ return !!item && this.isServerConfirmedMessage(item);
315
+ }
316
+
263
317
  protected get intervalItemIdsAreHeadFirst(): boolean {
264
- // Messages are stored in chronological order (created_at asc) within an interval.
265
- // Pagination "head" (newest side) is therefore at the END of the `itemIds` array.
318
+ // Intervals hold messages in `created_at` ascending order: the head (newest) is at the END.
266
319
  return false;
267
320
  }
268
321
 
269
322
  protected get intervalSortDirection(): 'asc' | 'desc' {
270
- // Head edge is newest, but sortComparator is created_at asc => newer head edges
271
- // should come first => reverse interval ordering.
323
+ // `itemOrderComparator` is `created_at` ascending but newer head edges must come first.
272
324
  return 'desc';
273
325
  }
274
326
 
@@ -282,6 +334,7 @@ export class MessageIntervalPaginator extends BasePaginator<
282
334
  sort,
283
335
  itemOrder,
284
336
  paginatorOptions,
337
+ thread,
285
338
  }: MessagePaginatorOptions,
286
339
  builtInDefaults: Partial<BasePaginatorConfig<LocalMessage, MessageQueryShape>> = {},
287
340
  ) {
@@ -291,12 +344,9 @@ export class MessageIntervalPaginator extends BasePaginator<
291
344
  {
292
345
  itemIndex,
293
346
  ...paginatorOptions,
294
- // Back every message-interval paginator (channel main list, thread reply list, pinned list)
295
- // with the client-global message store, so a message held in more than one of them has a
296
- // single canonical copy and updates (reactions/edits) fan out to all holders — no copy-to-copy
297
- // sync. When the store is unavailable (e.g. a detached paginator in a test) the index falls
298
- // back to a private store and behaves exactly like a plain per-instance index. Overridable per
299
- // instance via `paginatorOptions.createItemIndex` or an explicit `itemIndex`.
347
+ // Backed by the client's message store: a message held in several lists has one canonical
348
+ // copy and updates fan out to all holders. Without a store (e.g. a detached paginator in a
349
+ // test) the index is private. Overridable via `paginatorOptions.createItemIndex`/`itemIndex`.
300
350
  createItemIndex:
301
351
  paginatorOptions?.createItemIndex ??
302
352
  ((owner) =>
@@ -304,11 +354,10 @@ export class MessageIntervalPaginator extends BasePaginator<
304
354
  store: channel.getClient?.().messageStore,
305
355
  owner: owner as MessageIntervalPaginator,
306
356
  getEntityId: owner.getItemId.bind(owner),
357
+ holderName: (owner as MessageIntervalPaginator).holderName,
307
358
  })),
308
359
  },
309
- // SDK-supplied, so a declarative registration overrides them. `hasPaginationQueryShapeChanged`
310
- // and the zero cursor were previously spread into the caller's options, where they outranked
311
- // every `client.config.set({ messagePaginator: … })`.
360
+ // SDK defaults: a declarative registration (`client.config.set({ messagePaginator })`) wins.
312
361
  {
313
362
  hasPaginationQueryShapeChanged,
314
363
  initialCursor: ZERO_PAGE_CURSOR,
@@ -317,6 +366,7 @@ export class MessageIntervalPaginator extends BasePaginator<
317
366
  },
318
367
  );
319
368
  this.channel = channel;
369
+ this.thread = thread;
320
370
  this.parentMessageId = parentMessageId;
321
371
  this._id = id ?? `message-paginator-${generateUUIDv4()}`;
322
372
  this._requestSort = resolvedRequestSort;
@@ -338,12 +388,8 @@ export class MessageIntervalPaginator extends BasePaginator<
338
388
  }
339
389
 
340
390
  /**
341
- * Memoized so every derivation sees the *same* two functions. `initializeConfig` folds this into the
342
- * config it publishes and skips the publish when nothing moved — which only works if these references
343
- * are stable.
344
- *
345
- * Safe to build once: both close over `this` and read `_itemOrder`, which is assigned in the
346
- * constructor and has no setter.
391
+ * Memoized: `initializeConfig` folds it in and skips the publish when nothing moved, which needs
392
+ * stable references. Safe to build once: `_itemOrder` is set in the constructor, with no setter.
347
393
  */
348
394
  private intervalBehaviour?: Partial<
349
395
  BasePaginatorConfig<LocalMessage, MessageQueryShape>
@@ -354,7 +400,7 @@ export class MessageIntervalPaginator extends BasePaginator<
354
400
  > {
355
401
  if (!this.intervalBehaviour) {
356
402
  this.intervalBehaviour = {
357
- deriveCursor: makeDeriveCursor(this),
403
+ deriveCursor: (ctx) => this.deriveCursorFromPage(ctx),
358
404
  itemOrderComparator: makeComparator<LocalMessage>({
359
405
  sort: this._itemOrder,
360
406
  resolvePathValue: resolveDotPathValue,
@@ -370,12 +416,8 @@ export class MessageIntervalPaginator extends BasePaginator<
370
416
  }
371
417
 
372
418
  /**
373
- * Cursor derivation and in-memory item ordering, which this class installs on `config` rather than
374
- * passing as constructor options.
375
- *
376
- * Contributed to the base derivation rather than written after it — see
377
- * {@link BasePaginator.getBehaviourOverrides}. That is what keeps one re-derivation to one publish,
378
- * and stops the intermediate publish that had these two stripped.
419
+ * Installs cursor derivation and item ordering on `config` through the base derivation
420
+ * ({@link BasePaginator.getBehaviourOverrides}), so one re-derivation is one publish.
379
421
  */
380
422
  protected override getBehaviourOverrides(): Partial<
381
423
  BasePaginatorConfig<LocalMessage, MessageQueryShape>
@@ -384,9 +426,8 @@ export class MessageIntervalPaginator extends BasePaginator<
384
426
  }
385
427
 
386
428
  /**
387
- * The constructor's route to the same overlay. Deliberately calls the private builder rather than the
388
- * overridable hook: this runs inside the constructor, and a subclass override would execute before its
389
- * own fields were initialized.
429
+ * The constructor's route to the same overlay. It calls the private builder, not the overridable
430
+ * hook, which would run a subclass override before its fields are initialized.
390
431
  */
391
432
  protected installIntervalBehaviour(): void {
392
433
  this.updateConfig(this.buildIntervalBehaviour());
@@ -408,25 +449,23 @@ export class MessageIntervalPaginator extends BasePaginator<
408
449
  return this._itemOrder ?? this._requestSort ?? DEFAULT_BACKEND_SORT;
409
450
  }
410
451
 
411
- /**
412
- * Even though we do not send filters object to the server, we need to have filters for client-side item ingestion logic.
413
- */
452
+ /** Not sent to the server: drives client-side item ingestion. */
414
453
  buildMatchFilters = (): MessagePaginatorFilter => ({
415
454
  cid: this.channel.cid,
416
455
  ...(this.parentMessageId ? { parent_id: this.parentMessageId } : {}),
417
456
  });
418
457
 
419
- // invoked inside BasePaginator.executeQuery() to keep it as a query descriptor;
420
458
  protected getNextQueryShape({
421
459
  direction,
422
460
  }: Omit<
423
461
  PaginationQueryParams<MessageQueryShape>,
424
462
  'isFirstPageQuery'
425
463
  >): MessageQueryShape {
464
+ // no server-known message at that edge: no cursor, so the query returns the newest page
465
+ const cursorId = direction ? this.cursor?.[direction] : undefined;
426
466
  return {
427
467
  limit: this.pageSize,
428
- [direction === 'tailward' ? 'id_lt' : 'id_gt']:
429
- direction && this.cursor?.[direction],
468
+ ...(cursorId && { [direction === 'tailward' ? 'id_lt' : 'id_gt']: cursorId }),
430
469
  };
431
470
  }
432
471
 
@@ -437,131 +476,334 @@ export class MessageIntervalPaginator extends BasePaginator<
437
476
  direction?: PaginationDirection;
438
477
  items: LocalMessage[];
439
478
  }) => {
440
- if (!items.length) {
479
+ // Newer side is the pagination head for messages.
480
+ const { head, tail } = this.getPagePaginationEdges(items);
481
+ if (!head || !tail) {
441
482
  return {
442
483
  tailward: undefined,
443
484
  headward: undefined,
444
485
  };
445
486
  }
446
487
 
447
- const start = items[0];
448
- const end = items[items.length - 1];
449
-
450
- // Newer side is the pagination head for messages. Which bound is considered "head"
451
- // is determined by intervalItemIdsAreHeadFirst (see BasePaginator.getIntervalPaginationEdges).
452
- const head = this.intervalItemIdsAreHeadFirst ? start : end;
453
- const tail = this.intervalItemIdsAreHeadFirst ? end : start;
454
-
455
- // if there is no direction, then we are jumping, and we want to set both directions in the cursor
488
+ // Without a direction this is a jump: set both cursors.
456
489
  return {
457
490
  tailward: !direction || direction === 'tailward' ? this.getItemId(tail) : undefined,
458
491
  headward: !direction || direction === 'headward' ? this.getItemId(head) : undefined,
459
492
  };
460
493
  };
461
494
 
462
- query = async ({
495
+ /**
496
+ * Runs the query pipeline (see `BasePaginator.executeQuery`). A query that goes to the channel —
497
+ * not a thread's reply list, not a custom `doRequest` — runs as a tracked query of the channel
498
+ * (`Channel.runTrackedQuery`), so the channel store keeps the channel until the query ends. A
499
+ * disposed channel's query is not tracked: its fetch step is refused, and fails as any failed
500
+ * request does.
501
+ */
502
+ override executeQuery(
503
+ params: PaginationQueryParams<MessageQueryShape> = {},
504
+ ): Promise<ExecuteQueryReturnValue<LocalMessage> | void> {
505
+ const queriesChannel =
506
+ !this.parentMessageId && !this.config.doRequest && !this.channel.pendingDisposal;
507
+ if (!queriesChannel) return super.executeQuery(params);
508
+ return this.channel.runTrackedQuery(() => super.executeQuery(params));
509
+ }
510
+
511
+ /**
512
+ * The fetching step of the query pipeline: requests a page through a custom `doRequest`, the
513
+ * replies endpoint for a thread's reply list, or the channel query otherwise, which takes in what
514
+ * the response says about the channel itself and leaves the rest for the last step (see
515
+ * `Channel.requestChannelState`). Reads `requestOptions.watch`: `true` also watches the channel
516
+ * with the request. Ignored for a thread's reply list and with `doRequest`.
517
+ */
518
+ protected override fetchQueryResponse = async ({
463
519
  direction,
464
- }: PaginationQueryParams<MessageQueryShape>): Promise<
465
- PaginationQueryReturnValue<LocalMessage>
466
- > => {
467
- // get the params only if they were not generated previously
468
- if (!this._nextQueryShape) {
469
- this._nextQueryShape = this.getNextQueryShape({ direction });
470
- }
520
+ queryShape,
521
+ requestOptions,
522
+ }: PaginationQueryParams<MessageQueryShape>): Promise<MessageQueryResponse> => {
523
+ const options = queryShape ?? this.getNextQueryShape({ direction });
471
524
 
472
- const options = this._nextQueryShape;
473
- let items: LocalMessage[];
474
- let tailward: string | undefined;
475
- let headward: string | undefined;
476
525
  if (this.config.doRequest) {
477
- const result = await this.config.doRequest(options);
478
- items = this.getCanonicalQueryItems(result?.items ?? []);
479
- // if there is no direction, then we are jumping, and we want to set both directions in the cursor
480
- tailward =
481
- !direction || direction === 'tailward'
482
- ? (result.cursor?.tailward ?? undefined)
483
- : undefined;
484
- headward =
485
- !direction || direction === 'headward'
486
- ? (result.cursor?.headward ?? undefined)
487
- : undefined;
488
- } else {
489
- const { messages } = this.parentMessageId
490
- ? await this.channel.getClient().getReplies({
491
- parent_id: this.parentMessageId,
492
- ...options,
493
- sort: this.requestSort,
494
- })
495
- : await this.channel.query({
496
- messages: options as MessagePaginationParams,
497
- // todo: why do we query for watchers?
498
- // watchers: { limit: this.pageSize },
499
- });
500
- items = this.getCanonicalQueryItems(messages.map(formatMessage));
501
- const cursor = this.getCursorFromQueryResults({ direction, items });
502
- tailward = cursor.tailward;
503
- headward = cursor.headward;
526
+ return {
527
+ doRequestResponse: await this.config.doRequest(options),
528
+ source: 'doRequest',
529
+ };
504
530
  }
505
-
506
- return { items, headward, tailward };
531
+ if (this.parentMessageId) {
532
+ const repliesResponse = await this.channel
533
+ .getClient()
534
+ .getReplies(
535
+ { parent_id: this.parentMessageId },
536
+ { ...options, sort: this.getRepliesRequestSort(options) },
537
+ );
538
+ return { repliesResponse, source: 'replies' };
539
+ }
540
+ const watch = requestOptions?.watch === true;
541
+ const channelResponse = await this.channel.requestChannelState(
542
+ {
543
+ messages: options as MessagePaginationParams,
544
+ ...(watch && { watch: true }),
545
+ // todo: why do we query for watchers?
546
+ // watchers: { limit: this.pageSize },
547
+ },
548
+ undefined,
549
+ );
550
+ return { channelResponse, source: 'channel', watch };
507
551
  };
508
552
 
509
553
  /**
510
- * Seed the paginator with the page a channel-open query just fetched (`Channel.query` for
511
- * `watch`/`create`, and `client.hydrateActiveChannels`).
554
+ * The extracting step of the query pipeline: the messages in item order and their cursors, which
555
+ * a custom `doRequest` reports and which are derived from the messages otherwise.
556
+ */
557
+ protected override extractQueryPage(
558
+ response: MessageQueryResponse,
559
+ { direction }: PaginationQueryParams<MessageQueryShape>,
560
+ ): PaginationQueryReturnValue<LocalMessage> {
561
+ if (response.source === 'doRequest') {
562
+ const { cursor, items } = response.doRequestResponse;
563
+ // Without a direction this is a jump: set both cursors.
564
+ return {
565
+ headward: !direction || direction === 'headward' ? cursor?.headward : undefined,
566
+ items: this.getCanonicalQueryItems(items),
567
+ tailward: !direction || direction === 'tailward' ? cursor?.tailward : undefined,
568
+ };
569
+ }
570
+ const messages =
571
+ response.source === 'replies'
572
+ ? response.repliesResponse.messages
573
+ : (response.channelResponse.messages ?? []);
574
+ const items = this.getCanonicalQueryItems(messages.map(formatMessage));
575
+ return { items, ...this.getCursorFromQueryResults({ direction, items }) };
576
+ }
577
+
578
+ /**
579
+ * The last step of the query pipeline: the rest of a channel query's response, applied once its
580
+ * page is placed (see `Channel.applyChannelStateFromResponse`). The other sources return nothing
581
+ * else.
582
+ */
583
+ protected override applyQueryResponseRest(
584
+ response: MessageQueryResponse,
585
+ _placeParams: QueryPagePlacement<MessageQueryShape>,
586
+ ) {
587
+ if (response.source === 'channel') {
588
+ // Not the latest message set the offline database stores: `watch()` and the channel list
589
+ // store that.
590
+ this.channel.applyChannelStateFromResponse(response.channelResponse, {
591
+ isLatestMessageSet: false,
592
+ watch: response.watch,
593
+ });
594
+ }
595
+ }
596
+
597
+ /**
598
+ * Whether this paginator is active: the thread it lists is active (see `Thread.activate()`), or,
599
+ * without a thread, its channel is (see `Channel.activate()`). A page from a query an active
600
+ * paginator did not run leaves its active interval active; an inactive paginator shows a fresh
601
+ * newest page instead, also one separated from the loaded messages by a gap (see
602
+ * {@link reconcileNewestMessages}).
603
+ */
604
+ private isActivePaginator(): boolean {
605
+ return (this.thread ?? this.channel).active;
606
+ }
607
+
608
+ /**
609
+ * Places a page from an external query — one this paginator did not run, whose page the caller
610
+ * chose — in the intervals it belongs to, never removing anything loaded. Bringing the loaded
611
+ * newest messages up to date with a fresh newest page, removals included, is
612
+ * {@link reconcileNewestMessages}'s job instead.
613
+ *
614
+ * External queries are a channel query (`watch()`, see {@link prepareExternalQuery}), the
615
+ * channel list's query (`client.hydrateChannels`), and the channel state the pinned list's first
616
+ * page comes with. `messagePaginationParams` are the
617
+ * options the page was queried with; they decide where it goes:
618
+ *
619
+ * - The newest page: when no interval is active yet (nothing loaded, or only live messages), its
620
+ * interval becomes the active one, as the channel's first page. When the active interval is the
621
+ * newest interval, the page lands in it.
622
+ * - Any other page — a page at a cursor or around a message, or the newest page while an older
623
+ * interval is active — is only stored, as a separate interval merged only with an interval it
624
+ * overlaps.
625
+ *
626
+ * The active interval stays active: changing it is this paginator's own methods' job
627
+ * (`jumpToMessage()` and the like). The exception is an inactive paginator (see
628
+ * {@link isActivePaginator}), where the newest page is shown as when no interval is
629
+ * active. A newest
630
+ * page for loaded messages goes to {@link reconcileNewestMessages} instead
631
+ * (`prepareExternalQuery`, the channel list's query). When a page lands in the active interval,
632
+ * overlaps it, or takes in an active interval of live messages only, that interval is shown again
633
+ * with the page. The paginator's own queries are left alone too: a running one keeps its loading
634
+ * flag, and its last query error and query shape stay.
512
635
  *
513
- * These paths hydrate the channel read state in the SAME synchronous tick they add messages
514
- * (`Channel._initializeState`), and the read patch drives `MessageReceiptsTracker`, which resolves
515
- * read/delivered cursors against this paginator (`findItemByTimestamp`) whenever the server omits
516
- * the `last_read_message_id` / `last_delivered_message_id`. `postQueryReconcile` is fully
517
- * synchronous (filtering is a local predicate), so seeding here guarantees the paginator is
518
- * populated before the reconcile runs. First-page reconciliation also takes the unread snapshot.
636
+ * It runs synchronously, so a caller can apply the rest of the response right after with the page
637
+ * in place, as it has to: read and delivery positions that come without a message id are looked
638
+ * up among the loaded messages.
519
639
  *
520
- * The fetched page is NOT always the latest window: a channel can be opened AROUND a message
521
- * (`messages: { id_around }` / `{ created_at_around }`), so the original pagination options are
522
- * threaded through as the query shape. For an around/jump open this lets `postQueryReconcile`
523
- * apply jump semantics (no forced head/tail; cursor flags derived from the around position)
524
- * instead of wrongly flagging the window as the head (newest) page.
640
+ * Returns whether it showed the page as a first page.
525
641
  */
526
- seedFirstPageSync(
527
- messages: LocalMessage[],
642
+ placeExternalQueryPage(
643
+ page: LocalMessage[],
528
644
  requestedPageSize: number,
529
- messagePaginationOptions?: MessagePaginationParams,
530
- options?: SeedFirstPageOptions,
531
- ) {
645
+ messagePaginationParams?: MessagePaginationParams,
646
+ ): boolean {
532
647
  const queryShape: MessageQueryShape = {
533
- ...messagePaginationOptions,
648
+ ...messagePaginationParams,
534
649
  limit: requestedPageSize,
535
650
  };
536
651
  const isJump = this.isJumpQueryShape(queryShape);
652
+ const isNewestPage = this.isHeadPageQueryShape(queryShape);
653
+ // In item order, as `extractQueryPage()` hands its pages over, so the page's edges are its
654
+ // first and last item.
655
+ const items = this.getCanonicalQueryItems(page);
656
+ const { head: headItem, tail: tailItem } = this.getPagePaginationEdges(items);
657
+ // the first page of a list not loaded yet, or the newest page
658
+ const isFirstPage = typeof this.items === 'undefined' || isNewestPage;
659
+ const activeInterval = this.itemIntervals.find((interval) =>
660
+ this.isActiveInterval(interval),
661
+ );
662
+ // only live messages, with no page loaded yet, count as no active interval, as does any
663
+ // interval of an inactive paginator
664
+ const hasActiveInterval =
665
+ !!activeInterval && !isLogicalInterval(activeInterval) && this.isActivePaginator();
666
+ // The newest page lands in the active interval when that is the newest interval; any other page
667
+ // has no known place relative to the active interval, so it is stored as a separate interval.
668
+ const landsInActiveInterval = isNewestPage && this.isActiveIntervalAtHead;
669
+ const showsPage = isNewestPage && (!hasActiveInterval || landsInActiveInterval);
670
+ const placed = this.placePage(
671
+ {
672
+ startsSeparateInterval: !landsInActiveInterval,
673
+ // A jump/around page spans both directions; a page at a cursor pages the way its cursor
674
+ // points, and a plain latest page paginates tailward (older).
675
+ direction: isJump
676
+ ? undefined
677
+ : (getLinearQueryDirection(queryShape) ?? 'tailward'),
678
+ isFirstPage,
679
+ queryShape,
680
+ requestedPageSize,
681
+ results: {
682
+ items,
683
+ headward: isJump ? headItem?.id : undefined,
684
+ tailward: tailItem?.id,
685
+ },
686
+ updateState: showsPage,
687
+ },
688
+ { endsQuery: false },
689
+ );
690
+ // A stored page that took in a live-only active interval (only live messages, no page) carries
691
+ // on as the active interval: its live messages are still shown, with what the page added.
692
+ const tookInActiveInterval =
693
+ !!activeInterval &&
694
+ !this.itemIntervals.some((interval) => this.isActiveInterval(interval));
695
+ const intervalTakingOver = tookInActiveInterval ? placed.targetInterval : null;
696
+ if (intervalTakingOver) {
697
+ this.setActiveInterval(intervalTakingOver, { updateState: false });
698
+ // placing did not publish it: the interval it took in becomes the active one only here
699
+ const { cursor, hasMoreHead, hasMoreTail } = placed.stateCandidate;
700
+ this.publishActiveInterval({ cursor, hasMoreHead, hasMoreTail });
701
+ }
702
+ if (showsPage) {
703
+ // shown without a query of this paginator, so its next query has to continue this interval
704
+ this.recordLoadedIntervalQueryShape();
705
+ }
706
+ return showsPage && isFirstPage;
707
+ }
537
708
 
538
- if (options?.reconcile && !isJump && typeof this.items !== 'undefined') {
539
- // The page came back, so whatever the last query failure was, it is no longer the truth. The
540
- // branch below inherits this from `postQueryReconcile`, which this one deliberately skips —
541
- // without it a failed "load older" would keep a UI's error surface latched through an
542
- // otherwise successful reconnect refresh.
543
- if (this.state.getLatestValue().lastQueryError) {
544
- this.state.partialNext({ lastQueryError: undefined });
545
- }
546
- this.mergeNewestPage(messages, {
547
- candidateIds: options.candidateIds,
548
- requestedLimit: requestedPageSize,
549
- });
550
- return;
709
+ /**
710
+ * Whether messages are loaded for {@link reconcileNewestMessages} to bring up to date. A list
711
+ * loaded empty has none (no interval, not even live messages), so a fresh newest page is placed
712
+ * as a first page instead ({@link placeExternalQueryPage}); reconciling would find nothing to
713
+ * merge it into and drop it.
714
+ */
715
+ get canReconcileNewestMessages(): boolean {
716
+ return typeof this.items !== 'undefined' && this.itemIntervals.length > 0;
717
+ }
718
+
719
+ /**
720
+ * The snapshot a newest page is reconciled against (see
721
+ * {@link ReconcileNewestMessagesOptions.headIntervalItemIdsAtRequest}): the IDs of the head
722
+ * interval's server-confirmed messages. Take it right before the request goes out. Unsent messages
723
+ * are left out: one confirmed during the request proves neither that the page connects to the
724
+ * head interval nor, when the page lacks it, that it was deleted. `undefined` while no head
725
+ * interval is loaded.
726
+ *
727
+ * @internal
728
+ */
729
+ getHeadIntervalItemIdsAtRequest(): ReadonlySet<string> | undefined {
730
+ const head = this.anchoredHeadInterval;
731
+ if (!head) return undefined;
732
+ return new Set(head.itemIds.filter((id) => this.isServerConfirmedItemId(id)));
733
+ }
734
+
735
+ /**
736
+ * Whether the loaded message with this ID is server-confirmed
737
+ * (see {@link isServerConfirmedMessage}).
738
+ */
739
+ private isServerConfirmedItemId(id: string): boolean {
740
+ const message = this.getItem(id);
741
+ return !!message && this.isServerConfirmedMessage(message);
742
+ }
743
+
744
+ /**
745
+ * Prepares an external query for a page of these messages: the watch query the channel sends
746
+ * (`channel.watch()`, `channel.reload()`) with the `messages` options its caller gave. Call it
747
+ * before sending the query, and place the returned page with `placePage` before the response's
748
+ * read state is applied: the read state is resolved against the loaded messages.
749
+ *
750
+ * - `messagePaginationParams`: the options to send as the query's `messages`, with `limit` set to
751
+ * the page size when not given.
752
+ * - `isNewestPage`: whether the query asks for the newest page — no cursor, not around a message,
753
+ * and some messages.
754
+ * - `placePage`: places the returned page. The newest page goes to
755
+ * {@link placeExternalNewestPage}, reconciled against the messages loaded when the query was
756
+ * prepared; any other page is placed by {@link placeExternalQueryPage}. A query for no messages
757
+ * (`limit: 0`) places nothing. Returns whether it showed a first page.
758
+ */
759
+ prepareExternalQuery(messages?: MessagePaginationParams): PreparedExternalQuery {
760
+ const messagePaginationParams: MessagePaginationParams = {
761
+ ...messages,
762
+ limit: messages?.limit ?? this.pageSize,
763
+ };
764
+ const limit = messagePaginationParams.limit ?? this.pageSize;
765
+ if (isQueryForNoMessages(limit)) {
766
+ return { messagePaginationParams, isNewestPage: false, placePage: () => false };
551
767
  }
552
768
 
553
- this.postQueryReconcile({
554
- // A jump/around page spans both directions; a plain latest page paginates tailward (older).
555
- direction: isJump ? undefined : 'tailward',
556
- isFirstPage: true,
557
- queryShape,
558
- requestedPageSize,
559
- results: {
560
- items: messages,
561
- headward: isJump ? messages[messages.length - 1]?.id : undefined,
562
- tailward: messages[0]?.id,
563
- },
564
- });
769
+ const isNewestPage = this.isHeadPageQueryShape(messagePaginationParams);
770
+ const headIntervalItemIdsAtRequest = isNewestPage
771
+ ? this.getHeadIntervalItemIdsAtRequest()
772
+ : undefined;
773
+ return {
774
+ messagePaginationParams,
775
+ isNewestPage,
776
+ placePage: (page) =>
777
+ isNewestPage
778
+ ? this.placeExternalNewestPage(page, {
779
+ headIntervalItemIdsAtRequest,
780
+ requestedLimit: limit,
781
+ })
782
+ : this.placeExternalQueryPage(page, limit, messagePaginationParams),
783
+ };
784
+ }
785
+
786
+ /**
787
+ * Places the newest page of an external query (a channel query, the channel list's query): it
788
+ * reconciles the loaded newest messages ({@link reconcileNewestMessages}), or is placed as a
789
+ * first page when none are loaded ({@link placeExternalQueryPage}). A query for no messages
790
+ * (`requestedLimit: 0`) places nothing. Returns whether it showed a first page.
791
+ *
792
+ * @internal
793
+ */
794
+ placeExternalNewestPage(
795
+ page: LocalMessage[],
796
+ {
797
+ headIntervalItemIdsAtRequest,
798
+ requestedLimit,
799
+ }: ReconcileNewestMessagesOptions & { requestedLimit: number },
800
+ ): boolean {
801
+ if (isQueryForNoMessages(requestedLimit)) return false;
802
+ if (!this.canReconcileNewestMessages) {
803
+ return this.placeExternalQueryPage(page, requestedLimit);
804
+ }
805
+ this.reconcileNewestMessages(page, { headIntervalItemIdsAtRequest, requestedLimit });
806
+ return false;
565
807
  }
566
808
 
567
809
  isJumpQueryShape(queryShape: MessageQueryShape): boolean {
@@ -571,6 +813,30 @@ export class MessageIntervalPaginator extends BasePaginator<
571
813
  );
572
814
  }
573
815
 
816
+ /** Only a query without a cursor and not around a message returns the newest page. */
817
+ protected override isHeadPageQueryShape(
818
+ queryShape: MessageQueryShape | undefined,
819
+ ): boolean {
820
+ return (
821
+ !queryShape ||
822
+ (!this.isJumpQueryShape(queryShape) && !getLinearQueryDirection(queryShape))
823
+ );
824
+ }
825
+
826
+ /** A jump sends its own `limit`: head/tail flags are derived against it, not `pageSize`. */
827
+ protected override getRequestedPageSize(
828
+ queryShape: MessageQueryShape | undefined,
829
+ ): number {
830
+ return queryShape && this.isJumpQueryShape(queryShape)
831
+ ? (queryShape.limit ?? this.pageSize)
832
+ : this.pageSize;
833
+ }
834
+
835
+ /**
836
+ * Makes the interval holding the message the active one, querying the page around it when it is
837
+ * not loaded. Resolves `false` when the message cannot be shown, or when a later claim on the
838
+ * active interval (see `claimActiveInterval`) was made before the page arrived.
839
+ */
574
840
  jumpToMessage = async (
575
841
  messageId: string,
576
842
  {
@@ -578,11 +844,16 @@ export class MessageIntervalPaginator extends BasePaginator<
578
844
  focusSignalTtlMs,
579
845
  pageSize,
580
846
  suppressFocusSignal,
847
+ watchChannel,
581
848
  }: JumpToMessageOptions = {},
582
849
  ): Promise<boolean> => {
850
+ const watch =
851
+ !!watchChannel &&
852
+ !this.parentMessageId &&
853
+ !this.config.doRequest &&
854
+ this.channel.watchStatus !== ChannelWatchStatus.Watching;
583
855
  let localMessage = this.getItem(messageId);
584
856
  let interval: AnyInterval | undefined;
585
- let state: Partial<PaginatorState<LocalMessage>> | undefined;
586
857
  if (localMessage) {
587
858
  interval = this.locateIntervalForItem(localMessage);
588
859
  if (
@@ -590,11 +861,8 @@ export class MessageIntervalPaginator extends BasePaginator<
590
861
  !isLogicalInterval(interval) &&
591
862
  !interval.itemIds.includes(messageId)
592
863
  ) {
593
- // locateIntervalForItem can match by created_at RANGE and return an interval whose range
594
- // spans the target while its loaded itemIds do NOT contain it (e.g. a neighbouring interval
595
- // grew across the target's position without merging). Prefer the interval that actually
596
- // holds the id so the jump activates the window the message really lives in - otherwise, if
597
- // the range-matched interval happens to be active, the jump becomes a no-op.
864
+ // The range match can return an interval that spans the target without holding it (a
865
+ // neighbour grew across its position): use the one that holds the ID, or the jump may no-op.
598
866
  interval = this.itemIntervals.find(
599
867
  (candidate) =>
600
868
  !isLogicalInterval(candidate) && candidate.itemIds.includes(messageId),
@@ -602,18 +870,21 @@ export class MessageIntervalPaginator extends BasePaginator<
602
870
  }
603
871
  }
604
872
 
605
- if (localMessage && interval && !isLogicalInterval(interval)) {
606
- state = {
607
- hasMoreHead: interval.hasMoreHead,
608
- hasMoreTail: interval.hasMoreTail,
609
- cursor: this.getCursorFromInterval(interval),
610
- items: this.intervalToItems(interval),
611
- };
612
- } else if (!localMessage || !interval || isLogicalInterval(interval)) {
873
+ // a loaded message needs no request, unless the jump is also to watch the channel
874
+ if (!watch && localMessage && interval && !isLogicalInterval(interval)) {
875
+ // showing a loaded interval claims the active interval, as a query for one does
876
+ this.claimActiveInterval();
877
+ this.showLoadedInterval(interval);
878
+ } else {
613
879
  const result = await this.executeQuery({
614
- queryShape: { id_around: messageId, limit: pageSize },
880
+ claimsActiveInterval: true,
881
+ // Always send a limit: the replies endpoint ignores `id_around` without one.
882
+ queryShape: { id_around: messageId, limit: pageSize ?? this.pageSize },
883
+ ...(watch && { requestOptions: { watch: true } }),
615
884
  updateState: false,
616
885
  });
886
+ // a later claim decides the active interval, and the page stays stored
887
+ if (result?.isSuperseded) return false;
617
888
  localMessage = this.getItem(messageId);
618
889
  if (!localMessage || !result || !result.targetInterval) {
619
890
  this.channel.getClient().notifications.addError({
@@ -624,24 +895,22 @@ export class MessageIntervalPaginator extends BasePaginator<
624
895
  return false;
625
896
  }
626
897
  interval = result.targetInterval;
627
- state = isLogicalInterval(interval)
628
- ? result.stateCandidate
629
- : {
630
- ...result.stateCandidate,
631
- hasMoreHead: interval.hasMoreHead,
632
- hasMoreTail: interval.hasMoreTail,
633
- // Prefer the cursor derived during postQueryReconcile, but fall back to
634
- // interval-derived cursor to keep jumps consistent if the stateCandidate
635
- // is partial.
636
- cursor: result.stateCandidate.cursor ?? this.getCursorFromInterval(interval),
637
- items: this.intervalToItems(interval),
638
- };
898
+ this.showInterval(
899
+ interval,
900
+ isLogicalInterval(interval)
901
+ ? result.stateCandidate
902
+ : {
903
+ ...result.stateCandidate,
904
+ hasMoreHead: interval.hasMoreHead,
905
+ hasMoreTail: interval.hasMoreTail,
906
+ // Falls back to the interval-derived cursor when the stateCandidate is partial.
907
+ cursor:
908
+ result.stateCandidate.cursor ?? this.getCursorFromInterval(interval),
909
+ items: this.intervalToItems(interval),
910
+ },
911
+ );
639
912
  }
640
913
 
641
- if (!this.isActiveInterval(interval)) {
642
- this.setActiveInterval(interval, { updateState: false });
643
- }
644
- if (state) this.state.partialNext(state);
645
914
  if (!suppressFocusSignal) {
646
915
  this.emitMessageFocusSignal({
647
916
  messageId,
@@ -652,21 +921,52 @@ export class MessageIntervalPaginator extends BasePaginator<
652
921
  return true;
653
922
  };
654
923
 
655
- jumpToTheLatestMessage = async (options?: JumpToMessageOptions): Promise<boolean> => {
656
- let latestMessageId: string | undefined;
657
- if (!(this.itemIntervals[0] as Interval)?.isHead) {
658
- // load the newest page in case pagination is currently on an older window (an empty/partial
659
- // headward response marks the interval as the head)
660
- await this.executeQuery({ direction: 'headward', updateState: false });
924
+ /**
925
+ * Shows a loaded interval as it is: its items, its own pagination flags and the cursor continuing
926
+ * it. Claiming the active interval is the caller's choice (see `claimActiveInterval`).
927
+ */
928
+ protected showLoadedInterval(interval: Interval) {
929
+ this.showInterval(interval, {
930
+ hasMoreHead: interval.hasMoreHead,
931
+ hasMoreTail: interval.hasMoreTail,
932
+ cursor: this.getCursorFromInterval(interval),
933
+ items: this.intervalToItems(interval),
934
+ });
935
+ }
936
+
937
+ /** Makes `interval` the active interval and publishes `state` for it in one update. */
938
+ private showInterval(
939
+ interval: AnyInterval,
940
+ state: Partial<PaginatorState<LocalMessage>>,
941
+ ) {
942
+ if (!this.isActiveInterval(interval)) {
943
+ this.setActiveInterval(interval, { updateState: false });
661
944
  }
945
+ this.state.partialNext(state);
946
+ // shown without a query of this paginator, so its next query has to continue this interval
947
+ this.recordLoadedIntervalQueryShape();
948
+ }
662
949
 
663
- // Re-read itemIntervals AFTER the query: the getter returns a fresh array each call, so a
664
- // reference captured before executeQuery would be stale and miss the head we just loaded.
665
- const headInterval = this.itemIntervals[0] as Interval | undefined;
666
- if (headInterval?.isHead) {
667
- latestMessageId = headInterval.itemIds.slice(-1)[0];
950
+ /**
951
+ * Shows the interval holding the latest message and jumps to that message. Without a loaded head
952
+ * interval (see {@link latestHeadInterval}), the newest page is queried first: no cursor, so it
953
+ * holds the latest message however many pages are missing. The page merges with an interval it
954
+ * overlaps and is an interval of its own otherwise, and is shown either way. Resolves `false` when
955
+ * the latest message cannot be shown, or when a later claim on the active interval (see
956
+ * `claimActiveInterval`) was made before the page arrived: that page is then only stored.
957
+ */
958
+ jumpToTheLatestMessage = async (options?: JumpToMessageOptions): Promise<boolean> => {
959
+ if (!this.latestHeadInterval) {
960
+ const result = await this.executeQuery({
961
+ claimsActiveInterval: true,
962
+ queryShape: { limit: this.pageSize },
963
+ updateState: false,
964
+ });
965
+ // a later claim decides the active interval, and the page stays stored
966
+ if (result?.isSuperseded) return false;
668
967
  }
669
968
 
969
+ const latestMessageId = this.latestHeadInterval?.itemIds.slice(-1)[0];
670
970
  if (!latestMessageId) {
671
971
  this.channel.getClient().notifications.addError({
672
972
  message: 'Jump to latest message unsuccessful',
@@ -684,203 +984,554 @@ export class MessageIntervalPaginator extends BasePaginator<
684
984
  };
685
985
 
686
986
  /**
687
- * Fold an already fetched newest (head) page into the currently loaded items without issuing a
688
- * query. The caller supplies a page it obtained on its own and this reconciles it against what is
689
- * loaded, instead of rerunning the first page query, so the loaded set is updated in place rather
690
- * than blanked and reloaded. Two cases, decided by whether the incoming page overlaps the loaded
691
- * head:
987
+ * The head interval when it is the newest loaded interval, so its newest message is the latest
988
+ * one; `undefined` while no head interval is loaded or live messages newer than it are.
989
+ */
990
+ private get latestHeadInterval(): Interval | undefined {
991
+ const newest = this.itemIntervals[0];
992
+ return newest && !isLogicalInterval(newest) && newest.isHead ? newest : undefined;
993
+ }
994
+
995
+ /**
996
+ * Reconciles the loaded newest messages with a fresh newest page, without issuing a query: they
997
+ * are brought up to date in place — messages added and updated, those the page proves were
998
+ * hard-deleted removed — rather than blanked and reloaded. The page comes from an external query
999
+ * (a reload, a channel-list query, connection recovery). In an active paginator (see
1000
+ * {@link isActivePaginator}) the active interval stays active, the head interval included
1001
+ * (changing it is `jumpToTheLatestMessage()`'s job); in an inactive one, the head interval is
1002
+ * shown.
692
1003
  *
693
- * 1. OVERLAP - the incoming page shares at least one id with the loaded head (fewer than a full
694
- * page is new). Merge in place: existing items are reconciled by id (edits, soft deletes), new
695
- * items are appended and every already loaded item (including older pages already paged in) is
696
- * kept. The tail boundary (`hasMoreTail`/`cursor.tailward`) is set from whether the page reached
697
- * the channel start ({@link pageReachedChannelStart}): a bounded page that came back short means
698
- * no more older, otherwise "load older" stays enabled and the cursor re-anchors to the true loaded
699
- * oldest (which also clears a stale offline-DB cursor). Then destructive reconciliation
700
- * ({@link reconcileHeadAgainstPage}) removes any loaded message
701
- * that the authoritative page proves was hard-deleted while offline (see that method + the
702
- * {@link MergeNewestPageOptions} for the exact, safe window).
1004
+ * Where the page goes depends on the head interval, the loaded interval reaching the newest
1005
+ * message:
703
1006
  *
704
- * 2. DISJOINT - the incoming page shares no id with the loaded head (at least a full page is new).
705
- * Merging would weld the two across the gap (the interval merge treats two head intervals as
706
- * overlapping when one reaches further headward), hiding the items in between with no way to
707
- * reach them. Instead the loaded set is discarded and rebuilt from the incoming page as a fresh
708
- * contiguous head (`hasMoreTail: true`, cursor reanchored to the page's oldest item) so the
709
- * gap and older history load again when paginating older. No separate reconciliation is needed:
710
- * the rebuilt window IS the server truth, so any hard-deleted message is simply absent from it.
1007
+ * 1. NO HEAD INTERVAL (only live messages, a jumped-to interval, or a cleared head mark, see
1008
+ * {@link unmarkHead}) - the page becomes the head interval, merging with the intervals it
1009
+ * overlaps, live messages included, minus what it proves was hard-deleted. It is shown if the
1010
+ * live messages it absorbed were active; an active interval that it overlaps grows. A
1011
+ * page separated by a gap from the interval whose head mark was cleared is placed as in 2.
711
1012
  *
712
- * Never blanks the loaded set. Noop unless the newest slice is both loaded AND the interval
713
- * currently in view (the head interval is anchored at the head and active); when the caller has
714
- * jumped to a separate older window the merge is skipped so their position is preserved, and the
715
- * incoming page is picked up on a later load. An empty page never wipes the list on its own, but
716
- * — given a pre-fetch snapshot via `options.candidateIds` — is reconciled as "the channel has no
717
- * messages" (every server-confirmed loaded message removed).
1013
+ * 2. SEPARATED BY A GAP (see {@link isSeparatedFromHeadByGap}) - merging would weld the two
1014
+ * across the gap, hiding the messages in between, so the page takes the place of the head
1015
+ * interval (see {@link placeNewestPageAcrossGap}): stored beside the active interval when that
1016
+ * is an older interval, shown in place of the loaded intervals otherwise.
718
1017
  *
719
- * @param page - The fetched newest window (may be empty). `created_at` order is normalized on ingest.
720
- * @param options - See {@link MergeNewestPageOptions}. Omit to prune only within the page's own span.
1018
+ * 3. OTHERWISE - the page merges into the head interval, which keeps every loaded message and
1019
+ * drops what the page proves was hard-deleted (see {@link reconcileHeadAgainstPage}). An
1020
+ * active head interval gets its tail boundary from the page (see {@link showHeadInterval});
1021
+ * otherwise the active interval stays active, and grows into the head interval if the page
1022
+ * overlaps it.
1023
+ *
1024
+ * Only a gap drops loaded intervals, never an older active interval, and with nothing loaded it
1025
+ * does nothing: placing a first page is {@link placeQueryPage}'s job. An empty page changes
1026
+ * nothing on its own but, given a pre-fetch snapshot (`options.headIntervalItemIdsAtRequest`), is
1027
+ * reconciled as "the channel has no messages": every server-confirmed message of the head interval
1028
+ * is removed.
1029
+ *
1030
+ * The query shape of the loaded interval is recorded on every exit (see
1031
+ * `recordLoadedIntervalQueryShape`): an interval left without one loses itself on the next
1032
+ * pagination.
1033
+ *
1034
+ * @param page - The fetched newest interval (may be empty). `created_at` order is normalized on
1035
+ * ingest.
1036
+ * @param options - See {@link ReconcileNewestMessagesOptions}. Omit to prune only within the
1037
+ * page's own span.
721
1038
  */
722
- mergeNewestPage = (page: LocalMessage[], options?: MergeNewestPageOptions) => {
1039
+ reconcileNewestMessages = (
1040
+ page: LocalMessage[],
1041
+ options?: ReconcileNewestMessagesOptions,
1042
+ ) => {
1043
+ // The page came back, so whatever the last query failure was, it is no longer the truth: a
1044
+ // failed "load older" would otherwise keep a UI's error surface latched through a successful
1045
+ // refresh. Placing a page clears it in `placeQueryPage`.
1046
+ if (this.state.getLatestValue().lastQueryError) {
1047
+ this.state.partialNext({ lastQueryError: undefined });
1048
+ }
1049
+ this._reconcileNewestMessages(page, options);
1050
+ this.recordLoadedIntervalQueryShape();
1051
+ };
1052
+
1053
+ private _reconcileNewestMessages = (
1054
+ page: LocalMessage[],
1055
+ options?: ReconcileNewestMessagesOptions,
1056
+ ) => {
723
1057
  const headInterval = this.itemIntervals[0] as Interval | undefined;
724
1058
  if (!headInterval?.isHead) {
725
- // Live content no page has anchored yet, the first query came back empty and the reply the
726
- // user then sent went to the logical head (a thread/channel creation for example). Returning would
727
- // discard the fetched page, so the window could never catch up. We anchor it, so `ingestPage` folds
728
- // overlapping logical intervals in, absorbing those items.
729
- //
730
- // It's narrow on purpose, `liveHeadLogical` rather than `itemIntervals[0]`, which is only the head
731
- // by convention and could be a logical tail and no anchored head, whose presence would mean
732
- // this window is anchored with an older island merely in view. Keeps both neighbouring no-op
733
- // contracts, so nothing loaded has no logical head (seeding is `postQueryReconcile`'s job).
1059
+ // The newest messages are not loaded as an interval: only live content arrived (e.g. the first
1060
+ // query came back empty and the user's reply went to the logical head), only a jumped-to
1061
+ // interval is loaded, or the head mark was cleared (see `unmarkHead`). The page becomes the
1062
+ // head interval, and `ingestPage` merges into it the intervals it overlaps, live messages
1063
+ // included, else the newest messages could never be reached. With nothing loaded, placing
1064
+ // a first page is `placeQueryPage`'s job.
734
1065
  const logicalHead = this.liveHeadLogical;
735
1066
  const hasAnchoredHead = this.itemIntervals.some(
736
1067
  (interval) => !isLogicalInterval(interval) && interval.isHead,
737
1068
  );
738
- if (!logicalHead || hasAnchoredHead || !page?.length) return;
1069
+ if (!this.itemIntervals.length || hasAnchoredHead || !page?.length) return;
1070
+
1071
+ // The interval that reached the newest message until its head mark was cleared is judged as
1072
+ // the head interval is, gap included. The page becomes the head interval either way, so that
1073
+ // interval is judged only once.
1074
+ const unmarkedHead = this.unmarkedHeadInterval;
1075
+ this.unmarkedHeadEdgeId = undefined;
1076
+ if (unmarkedHead && this.isSeparatedFromHeadByGap(unmarkedHead, page, options)) {
1077
+ this.placeNewestPageAcrossGap(page, unmarkedHead, options);
1078
+ return;
1079
+ }
739
1080
 
740
- // Take over the view only if the reader is on the live content being absorbed, so if they jumped
741
- // to another interval, anchor for their return and leave them there (the rule the jumped away
742
- // branch below enforces).
743
- const takeOverView = this.isActiveInterval(logicalHead);
1081
+ // Take over the view if the live content being absorbed is active, or the paginator is
1082
+ // inactive. An active interval elsewhere (an interval jumped to) stays active, with the
1083
+ // page anchored as the head interval (the rule the jumped away branch below enforces).
1084
+ const takeOverView =
1085
+ !this.isActivePaginator() ||
1086
+ (!!logicalHead && this.isActiveInterval(logicalHead));
744
1087
 
745
1088
  const anchored = this.ingestPage({ page, isHead: true, setActive: false });
746
- if (!anchored || !takeOverView) return;
747
-
748
- const hasMoreTail = !this.pageReachedChannelStart(page, options);
749
- anchored.hasMoreTail = hasMoreTail;
750
- anchored.isTail = !hasMoreTail;
751
-
752
- this.setActiveInterval(anchored, { updateState: false });
753
- this.state.partialNext({
754
- items: this.intervalToItems(anchored),
755
- hasMoreHead: false,
756
- hasMoreTail,
757
- cursor: {
758
- headward: null,
759
- tailward: hasMoreTail ? (anchored.itemIds[0] ?? null) : null,
760
- },
761
- });
1089
+ if (!anchored) return;
1090
+ // The page may have merged into an interval that stopped reaching the newest message (see
1091
+ // `unmarkHead`); remove from it, as from the head, what the page proves was hard-deleted.
1092
+ this.reconcileHeadAgainstPage(page, options);
1093
+ if (!takeOverView) {
1094
+ // The page merged into the active interval, which now reaches the head: show what it gained.
1095
+ if (this.isActiveInterval(anchored)) {
1096
+ this.publishActiveIntervalGrownIntoHead();
1097
+ }
1098
+ return;
1099
+ }
1100
+ this.showHeadInterval(page, options);
762
1101
  return;
763
1102
  }
764
- // Captured BEFORE the merge overwrites state — inputs for the below-window reached-start probe
765
- // (overlap branch only): did we believe we were at the channel start, and how much was loaded.
1103
+ // Inputs for removeIdsTailwardOfPageIfNothingOlder, captured before the merge overwrites state.
766
1104
  const wasAtChannelStart = !this.state.getLatestValue().hasMoreTail;
767
1105
  const preMergeLoadedCount = headInterval.itemIds.length;
768
- // If the caller jumped to a separate (older) window, that window is active and the head is merely
769
- // still-loaded underneath. Don't MERGE the fresh page or switch the view (that would yank them to
770
- // the newest) — but STILL prune offline hard-deletes out of the hidden head, otherwise returning to
771
- // it later (scroll-to-latest) surfaces ghosts that were deleted while jumped away. Reconciliation
772
- // targets the head interval regardless of which interval is active, and removing a hidden-head ghost
773
- // leaves the active island's items untouched.
774
- if (!this.isActiveInterval(headInterval)) {
775
- this.reconcileHeadAgainstPage(page, options);
776
- return;
777
- }
778
1106
 
779
1107
  if (!page?.length) {
780
- // Empty page: never blanks the list by itself. Only when the caller supplied a pre-fetch
781
- // snapshot do we treat it as authoritative "channel emptied" and remove ghosts (a message that
782
- // arrived live during the fetch is excluded by the snapshot).
1108
+ // An empty page never blanks the list: only with a pre-fetch snapshot is it read as "channel
1109
+ // emptied" (the snapshot excludes messages that arrived live during the fetch).
783
1110
  this.reconcileHeadAgainstPage([], options);
784
1111
  return;
785
1112
  }
786
1113
 
787
- const loadedIds = new Set(headInterval.itemIds);
788
- const overlapsLoadedHead = page.some((item) => loadedIds.has(this.getItemId(item)));
789
-
790
- if (!overlapsLoadedHead) {
791
- // Disjoint window: rebuild from the fetched page as a fresh newest slice. Clearing
792
- // the stale intervals first ensures `ingestPage` builds a single head interval instead of
793
- // merging across the gap so reanchoring the cursor to this page's oldest item keeps the next
794
- // "load older" contiguous.
795
- this.setIntervals([]);
796
- this.setActiveInterval(undefined);
797
- const resetInterval = this.ingestPage({
798
- page,
799
- isHead: true,
800
- // Disjoint means the previously loaded head was entirely OLDER than this newest window, so
801
- // there is always older data to load (the gap + the prior history) - keep hasMoreTail true.
802
- isTail: false,
803
- setActive: false,
804
- });
805
- if (!resetInterval) return;
806
- this.setActiveInterval(resetInterval, { updateState: false });
807
- this.state.partialNext({
808
- items: this.intervalToItems(resetInterval),
809
- cursor: this.getCursorFromInterval(resetInterval),
810
- hasMoreHead: resetInterval.hasMoreHead,
811
- hasMoreTail: resetInterval.hasMoreTail,
812
- });
1114
+ if (this.isSeparatedFromHeadByGap(headInterval, page, options)) {
1115
+ this.placeNewestPageAcrossGap(page, headInterval, options);
813
1116
  return;
814
1117
  }
815
1118
 
816
- // Overlapping window: merge in place, keeping every already-loaded (incl. older) item.
817
- const interval = this.ingestPage({ page, isHead: true, setActive: false });
818
- if (!interval) return;
819
-
820
- // hasMoreTail: does the fetched page prove it reached the channel's own oldest message? Only a
821
- // request bounded by our OWN pageSize gives that proof (a short page); an over-request may have
822
- // been server-capped, so it biases to `true` — never asserting "no more older" from a page that
823
- // may be truncated. See {@link pageReachedChannelStart} (no hardcoded max page size, per-paginator).
824
- // This decides only the "load older" AFFORDANCE — it never removes a message (reconciliation stays
825
- // window-only below). isTail mirrors it: `true` only when we RELIABLY reached the start, which also
826
- // clears a stale offline-DB `isTail:true` and stops `intervalsOverlap` welding a far page across a
827
- // gap. The tail cursor anchors to the oldest loaded id so "load older" stays contiguous.
828
- const hasMoreTail = !this.pageReachedChannelStart(page, options);
829
- interval.hasMoreTail = hasMoreTail;
830
- interval.isTail = !hasMoreTail;
1119
+ // Another interval is shown; the head interval is still reconciled, so returning to it
1120
+ // (scroll-to-latest) shows neither ghosts nor stale newest messages.
1121
+ if (!this.isActiveInterval(headInterval)) {
1122
+ this.reconcileHeadAgainstPage(page, options);
1123
+ this.mergePageIntoInactiveHead(page, options);
1124
+ return;
1125
+ }
831
1126
 
832
- this.setActiveInterval(interval, { updateState: false });
833
- this.state.partialNext({
834
- items: this.intervalToItems(interval),
835
- // The newest slice is loaded (head anchored), so there is nothing newer to load.
836
- hasMoreHead: false,
837
- hasMoreTail,
838
- // Tailward = the oldest loaded id (interval item ids are created_at asc), null once we reached
839
- // the channel start.
840
- cursor: {
841
- headward: null,
842
- tailward: hasMoreTail ? (interval.itemIds[0] ?? null) : null,
843
- },
1127
+ // the head interval is active: merge in place, keeping every loaded message
1128
+ const interval = this.ingestPage({
1129
+ page,
1130
+ isHead: true,
1131
+ setActive: false,
1132
+ targetIntervalId: headInterval.id,
844
1133
  });
1134
+ if (!interval) return;
1135
+ this.showHeadInterval(page, options);
845
1136
 
846
- // With the newest page merged in, drop any loaded message the page proves was hard-deleted, and
847
- // collect the below-window leftovers it cannot decide from the page alone.
848
- const belowWindow = this.reconcileHeadAgainstPage(page, options);
1137
+ const idsTailwardOfPage = this.reconcileHeadAgainstPage(page, options);
849
1138
 
850
- // The leftovers are ambiguous (hard-deleted oldest vs server-capped over-request). Only a
851
- // full-window reload (`requestedLimit >= loaded`, so NOT the small list hydrate) that we believed
852
- // reached the start could have reached it — probe to settle them there; anything else can't, so skip.
1139
+ // Messages tailward of the page may be deleted or just older than the page reached. Only a reload
1140
+ // of the whole head interval (`requestedLimit >= loaded`, not the small list hydrate) that was at
1141
+ // the channel start can settle them, by asking the server; otherwise they are kept.
853
1142
  const requestedLimit = options?.requestedLimit;
854
1143
  if (
855
- belowWindow.length &&
1144
+ idsTailwardOfPage.length &&
856
1145
  wasAtChannelStart &&
857
1146
  typeof requestedLimit === 'number' &&
858
1147
  requestedLimit >= preMergeLoadedCount
859
1148
  ) {
860
- this._belowWindowReconcile = this.pruneBelowWindowIfReachedStart(
861
- belowWindow,
1149
+ this._pendingTailwardOfPageRemoval = this.removeIdsTailwardOfPageIfNothingOlder(
1150
+ idsTailwardOfPage,
862
1151
  this.getItemId(page[0]),
863
1152
  );
864
1153
  }
865
1154
  };
866
1155
 
867
1156
  /**
868
- * Whether `page` proves it reached the channel's own oldest message: the caller's request was
869
- * bounded by this paginator's OWN `pageSize` AND `page` came back shorter than that request.
1157
+ * Shows the head interval a fresh newest page merged into, with no newer messages to load. It has
1158
+ * older ones unless the page reached the channel start (see {@link pageReachedChannelStart});
1159
+ * `isTail` follows, which also clears a stale offline-DB `isTail: true` that would let
1160
+ * `intervalsOverlap` weld a far page across a gap.
1161
+ */
1162
+ private showHeadInterval(
1163
+ page: LocalMessage[],
1164
+ options?: ReconcileNewestMessagesOptions,
1165
+ ) {
1166
+ // read here, as reconciling replaces the interval object a caller holds
1167
+ const interval = this.anchoredHeadInterval;
1168
+ if (!interval) return;
1169
+ const hasMoreTail = !this.pageReachedChannelStart(page, options);
1170
+ interval.hasMoreTail = hasMoreTail;
1171
+ interval.isTail = !hasMoreTail;
1172
+ this.setActiveInterval(interval, { updateState: false });
1173
+ const flags = { hasMoreHead: false, hasMoreTail };
1174
+ this.publishActiveInterval({
1175
+ ...flags,
1176
+ cursor: this.getCursorFromInterval(interval, flags),
1177
+ });
1178
+ }
1179
+
1180
+ /**
1181
+ * Whether a fresh newest page and the head interval (or the interval whose head mark was cleared,
1182
+ * see {@link unmarkedHeadInterval}) are separated by a gap, with messages between them possibly
1183
+ * not loaded. They are not when the two together form one unbroken stretch of the channel:
1184
+ *
1185
+ * - the page starts inside the head interval (see {@link pageStartsInsideHead});
1186
+ * - the page covers the head interval (see {@link pageCoversHead});
1187
+ * - the page reached the channel start (see {@link pageReachedChannelStart}), so nothing older
1188
+ * than it exists to be missing.
1189
+ *
1190
+ * Sharing a message is not enough on its own: a message the user sent while offline is confirmed
1191
+ * by the server before the reconnect's newest page is requested, so it sits at the top of the
1192
+ * head interval and in the page, with the messages missed below it in neither. For example, the
1193
+ * interval holds m1–m100 and the user's queued "hello"; the server got m101–m210 meanwhile. A page
1194
+ * of 25 holds m187–m210 and "hello": it does not start inside the interval (m187 was never loaded)
1195
+ * nor cover it (m1 is not in it), so it is past a gap. When the user wrote the last 10 loaded
1196
+ * messages and others sent 20 since, a page of 25 holds the user's last 5 and the 20 new ones:
1197
+ * its oldest was loaded, so it starts inside the interval.
1198
+ *
1199
+ * A message missed while the socket was down comes with connection recovery's newest page.
1200
+ */
1201
+ private isSeparatedFromHeadByGap(
1202
+ head: Interval,
1203
+ page: LocalMessage[],
1204
+ options?: ReconcileNewestMessagesOptions,
1205
+ ): boolean {
1206
+ if (this.pageStartsInsideHead(head, page, options)) return false;
1207
+ if (this.pageCoversHead(head, page)) return false;
1208
+ if (this.pageReachedChannelStart(page, options)) return false;
1209
+ return true;
1210
+ }
1211
+
1212
+ /**
1213
+ * Whether the page's oldest message the head interval could hold (see
1214
+ * {@link getPageOldestHoldableMessage}) was in the head interval when the request went out. The
1215
+ * page runs unbroken from that message to the newest and the interval is taken to run unbroken
1216
+ * below it, so nothing between them is missing.
1217
+ *
1218
+ * With a snapshot of the request (`options.headIntervalItemIdsAtRequest`), the message must be
1219
+ * in it and held by no interval other than the head interval: a message that reached the interval
1220
+ * during the request, live or as a send confirmed meanwhile, may sit above messages the interval
1221
+ * never loaded. One no longer loaded at all still counts: if the head interval holds messages
1222
+ * older than it, the interval ran unbroken through it and it was removed (e.g. hard-deleted);
1223
+ * if not, the page covers the interval anyway. Without a snapshot, the message must be in the
1224
+ * head interval and server-confirmed now.
870
1225
  *
871
- * `pageSize <= the server's max page size` is already the invariant normal pagination
872
- * (`executeQuery`) relies on — `page.length < pageSize` ⟹ reached the end — so a request no larger
873
- * than `pageSize` returns exactly what was asked unless the channel ended. This needs no hardcoded
874
- * max page size and is per-paginator, so a thread reply paginator uses its own `pageSize`.
1226
+ * The interval is not unbroken below a send the server confirmed while the channel received no
1227
+ * events, such as one replayed from the offline queue before the reconnect's newest page is
1228
+ * requested. If that send is exactly the page's oldest (as many newer messages as the page has
1229
+ * room for were sent after it), the page is taken to start inside the interval although messages
1230
+ * below the send were missed. The page and the interval cannot tell this apart from a send
1231
+ * confirmed while events were arriving.
1232
+ */
1233
+ private pageStartsInsideHead(
1234
+ head: Interval,
1235
+ page: LocalMessage[],
1236
+ options?: ReconcileNewestMessagesOptions,
1237
+ ): boolean {
1238
+ const pageOldest = this.getPageOldestHoldableMessage(page);
1239
+ if (!pageOldest) return false;
1240
+ const id = this.getItemId(pageOldest);
1241
+ const idsAtRequest = options?.headIntervalItemIdsAtRequest;
1242
+ if (!idsAtRequest) {
1243
+ return head.itemIds.includes(id) && this.isServerConfirmedItemId(id);
1244
+ }
1245
+ const heldByAnotherInterval = !head.itemIds.includes(id) && !!this.getItem(id);
1246
+ return idsAtRequest.has(id) && !heldByAnotherInterval;
1247
+ }
1248
+
1249
+ /**
1250
+ * Whether the page spans the whole head interval: the interval holds no server-confirmed message
1251
+ * older than the page. What the interval holds beyond the page is newer (it arrived as an event
1252
+ * after the page was produced) or unsent (it carries the device's clock).
1253
+ */
1254
+ private pageCoversHead(head: Interval, page: LocalMessage[]): boolean {
1255
+ const pageOldest = this.getPageOldestMessage(page);
1256
+ if (!pageOldest) return true;
1257
+ return !head.itemIds.some((id) => {
1258
+ const message = this.getItem(id);
1259
+ return (
1260
+ !!message &&
1261
+ this.isServerConfirmedMessage(message) &&
1262
+ this.aIsMoreTailwardThanB(message, pageOldest)
1263
+ );
1264
+ });
1265
+ }
1266
+
1267
+ /**
1268
+ * The page's oldest message that the head interval could have loaded: server-confirmed and kept
1269
+ * in intervals (see {@link filterQueryResults}). A message the interval filters out, such as a
1270
+ * shadowed one, would never be found in it. {@link pageCoversHead} compares with the page's
1271
+ * oldest message of any kind instead: it only needs the page's span.
1272
+ */
1273
+ private getPageOldestHoldableMessage(page: LocalMessage[]): LocalMessage | undefined {
1274
+ const holdable = this.filterQueryResults(page).filter((message) =>
1275
+ this.isServerConfirmedMessage(message),
1276
+ );
1277
+ return this.getPageOldestMessage(holdable);
1278
+ }
1279
+
1280
+ /**
1281
+ * The interval whose head mark was cleared last (see {@link unmarkHead}), while it is still
1282
+ * loaded. It reached the newest message until then, so a newest page is judged against it while
1283
+ * no head interval is loaded.
1284
+ */
1285
+ private get unmarkedHeadInterval(): Interval | undefined {
1286
+ const id = this.unmarkedHeadEdgeId;
1287
+ if (!id) return undefined;
1288
+ return this.itemIntervals.find(
1289
+ (interval): interval is Interval =>
1290
+ !isLogicalInterval(interval) && interval.itemIds.includes(id),
1291
+ );
1292
+ }
1293
+
1294
+ /**
1295
+ * Remembers the interval by a message that stays in it: a server-confirmed one, as an unsent one
1296
+ * may be deleted or retried; the raw newest item only when the interval holds none.
1297
+ */
1298
+ protected override unmarkHead(interval: Interval) {
1299
+ const edge =
1300
+ this.getServerKnownEdges(interval).head ??
1301
+ this.getIntervalPaginationEdges(interval)?.head;
1302
+ this.unmarkedHeadEdgeId = edge ? this.getItemId(edge) : undefined;
1303
+ super.unmarkHead(interval);
1304
+ }
1305
+
1306
+ protected override clearItemStorage() {
1307
+ this.unmarkedHeadEdgeId = undefined;
1308
+ super.clearItemStorage();
1309
+ }
1310
+
1311
+ override resetState() {
1312
+ this.unmarkedHeadEdgeId = undefined;
1313
+ super.resetState();
1314
+ }
1315
+
1316
+ private getPageOldestMessage(page: LocalMessage[]): LocalMessage | undefined {
1317
+ return this.getPagePaginationEdges(this.getCanonicalQueryItems(page)).tail;
1318
+ }
1319
+
1320
+ /**
1321
+ * Places a fresh newest page separated by a gap from `headInterval` (the head interval, or the
1322
+ * interval whose head mark was cleared, see {@link isSeparatedFromHeadByGap}). The page becomes
1323
+ * the head interval either way, and the intervals nothing brought up to date are dropped, as a
1324
+ * message deleted meanwhile would come back with them:
875
1325
  *
876
- * An OVER-request (larger than `pageSize`, e.g. `channel.reload` re-fetching the whole loaded window
877
- * to reconcile as much as possible) may have been silently capped by the server, so a short page
878
- * there is NOT proof of reaching the start — return `false` and stay conservative. This only ever
879
- * gates the `hasMoreTail` affordance; it never removes a message.
1326
+ * - an active interval other than the head interval (see {@link getActiveIntervalApartFromHead})
1327
+ * stays active, and the page is stored beside it (see
1328
+ * {@link storeNewestPageBesideActiveInterval});
1329
+ * - otherwise the page replaces the loaded intervals and is shown (see
1330
+ * {@link replaceIntervalsWithNewestPage}).
1331
+ */
1332
+ private placeNewestPageAcrossGap(
1333
+ page: LocalMessage[],
1334
+ headInterval: Interval,
1335
+ options?: ReconcileNewestMessagesOptions,
1336
+ ) {
1337
+ const activeInterval = this.getActiveIntervalApartFromHead(headInterval);
1338
+ if (activeInterval) {
1339
+ this.storeNewestPageBesideActiveInterval(page, activeInterval, options);
1340
+ } else {
1341
+ this.replaceIntervalsWithNewestPage(page, options);
1342
+ }
1343
+ }
1344
+
1345
+ /**
1346
+ * The active loaded interval when it is not `headInterval`, such as an interval jumped to;
1347
+ * `undefined` when `headInterval` or live messages only are active, and in an inactive paginator
1348
+ * (see {@link isActivePaginator}).
1349
+ */
1350
+ private getActiveIntervalApartFromHead(headInterval: Interval): Interval | undefined {
1351
+ if (!this.isActivePaginator()) return undefined;
1352
+ return this.itemIntervals.find(
1353
+ (interval): interval is Interval =>
1354
+ !isLogicalInterval(interval) &&
1355
+ this.isActiveInterval(interval) &&
1356
+ interval.id !== headInterval.id,
1357
+ );
1358
+ }
1359
+
1360
+ /**
1361
+ * Replaces the loaded intervals with a fresh newest page separated from the head interval by a gap
1362
+ * (see {@link placeNewestPageAcrossGap}) and shows it. The page's interval keeps the loaded
1363
+ * messages that must not be lost (see {@link getMessagesKeptAcrossGap}) and has older messages
1364
+ * to load.
1365
+ */
1366
+ private replaceIntervalsWithNewestPage(
1367
+ page: LocalMessage[],
1368
+ options?: ReconcileNewestMessagesOptions,
1369
+ ) {
1370
+ const keptMessages = this.getMessagesKeptAcrossGap(page, this.itemIntervals);
1371
+ // one publish, once the page's interval is in place and reconciled, so subscribers read it whole
1372
+ this.batch(
1373
+ () => {
1374
+ this.clearItemStorage();
1375
+ this.ingestPageAsHeadInterval(page, keptMessages, options);
1376
+ this.showHeadInterval(page, options);
1377
+ },
1378
+ { coalesce: true },
1379
+ );
1380
+ }
1381
+
1382
+ /**
1383
+ * Stores a fresh newest page separated from the head interval by a gap (see
1384
+ * {@link placeNewestPageAcrossGap}) as the head interval, beside `activeInterval`, which stays
1385
+ * active and shown as it is. Every other loaded interval is dropped and loads again on
1386
+ * demand. The page's interval keeps the messages of the dropped intervals that must not be lost
1387
+ * (see {@link getMessagesKeptAcrossGap}) and has older messages to load.
1388
+ *
1389
+ * The active interval keeps all its messages, unsent ones included, so nothing moves in the
1390
+ * shown list, and it is not brought up to date: a message deleted or edited meanwhile stays as it was
1391
+ * loaded. It can load newer messages, up to the head interval it then joins.
1392
+ */
1393
+ private storeNewestPageBesideActiveInterval(
1394
+ page: LocalMessage[],
1395
+ activeInterval: Interval,
1396
+ options?: ReconcileNewestMessagesOptions,
1397
+ ) {
1398
+ const droppedIntervals = this.itemIntervals.filter(
1399
+ (interval) => interval.id !== activeInterval.id,
1400
+ );
1401
+ const keptMessages = this.getMessagesKeptAcrossGap(page, droppedIntervals);
1402
+ const keepingIds = new Set(
1403
+ [...page, ...keptMessages].map((message) => this.getItemId(message)),
1404
+ );
1405
+ // one publish, once the page's interval is in place and reconciled, so subscribers read it whole
1406
+ this.batch(
1407
+ () => {
1408
+ this.dropIntervals(droppedIntervals, { keepingIds });
1409
+ this.unmarkedHeadEdgeId = undefined;
1410
+ // Not the head interval: a head mark would weld the page to it (`intervalsOverlap` joins
1411
+ // anything beyond a head interval's head edge).
1412
+ activeInterval.isHead = false;
1413
+ const pageInterval = this.ingestPageAsHeadInterval(page, keptMessages, options);
1414
+ if (pageInterval && this.isActiveInterval(pageInterval)) {
1415
+ // the page overlapped the active interval, which grew into the head interval
1416
+ this.publishActiveIntervalGrownIntoHead();
1417
+ return;
1418
+ }
1419
+ this.markActiveIntervalBelowHead(activeInterval);
1420
+ },
1421
+ { coalesce: true },
1422
+ );
1423
+ }
1424
+
1425
+ /**
1426
+ * Ingests a fresh newest page placed across a gap, with `keptMessages`, as the head interval,
1427
+ * which has older messages to load, and removes from it what the page proves was hard-deleted (see
1428
+ * {@link reconcileHeadAgainstPage}). Returns the interval the page landed in.
1429
+ */
1430
+ private ingestPageAsHeadInterval(
1431
+ page: LocalMessage[],
1432
+ keptMessages: LocalMessage[],
1433
+ options?: ReconcileNewestMessagesOptions,
1434
+ ): Interval | null {
1435
+ const pageInterval = this.ingestPage({
1436
+ page: [...page, ...keptMessages],
1437
+ isHead: true,
1438
+ isTail: false,
1439
+ setActive: false,
1440
+ });
1441
+ this.reconcileHeadAgainstPage(page, options);
1442
+ return pageInterval;
1443
+ }
1444
+
1445
+ /**
1446
+ * Drops `intervals` from storage and releases their messages, except those with `keepingIds`,
1447
+ * which the caller ingests again.
1448
+ */
1449
+ private dropIntervals(
1450
+ intervals: AnyInterval[],
1451
+ { keepingIds }: { keepingIds: ReadonlySet<string> },
1452
+ ) {
1453
+ for (const interval of intervals) {
1454
+ this.dropInterval(interval.id);
1455
+ for (const id of interval.itemIds) {
1456
+ if (!keepingIds.has(id)) this._itemIndex.remove(id);
1457
+ }
1458
+ }
1459
+ }
1460
+
1461
+ /**
1462
+ * Marks the active interval, which does not reach the newest message, as able to load newer
1463
+ * messages. Publishes the flag and cursor only when they changed, so the interval shown stays as
1464
+ * it is.
1465
+ */
1466
+ private markActiveIntervalBelowHead(interval: Interval) {
1467
+ interval.hasMoreHead = true;
1468
+ const cursor = this.getCursorFromInterval(interval);
1469
+ const shown = this.state.getLatestValue();
1470
+ if (shown.hasMoreHead && shown.cursor?.headward === cursor.headward) return;
1471
+ this.state.partialNext({ hasMoreHead: true, cursor });
1472
+ }
1473
+
1474
+ /**
1475
+ * The messages of `intervals`, missing from a newest page placed across a gap, that the page's
1476
+ * interval keeps:
1477
+ *
1478
+ * - unsent messages (see {@link isServerConfirmedMessage});
1479
+ * - messages from the page's oldest on: those that arrived during the request stay, and
1480
+ * reconciling removes those the page proves were hard-deleted.
1481
+ */
1482
+ private getMessagesKeptAcrossGap(
1483
+ page: LocalMessage[],
1484
+ intervals: AnyInterval[],
1485
+ ): LocalMessage[] {
1486
+ const pageIds = new Set(page.map((message) => this.getItemId(message)));
1487
+ const pageOldest = this.getPageOldestMessage(page);
1488
+ const isOlderThanPage = (message: LocalMessage) =>
1489
+ !!pageOldest && this.aIsMoreTailwardThanB(message, pageOldest);
1490
+ return intervals
1491
+ .flatMap((interval) => this.intervalToItems(interval))
1492
+ .filter(
1493
+ (message) =>
1494
+ !pageIds.has(this.getItemId(message)) &&
1495
+ (!this.isServerConfirmedMessage(message) || !isOlderThanPage(message)),
1496
+ );
1497
+ }
1498
+
1499
+ /**
1500
+ * Merges a fresh newest page, not separated by a gap, into the head interval while another
1501
+ * interval is shown. That interval stays active and grows into the head interval if the page
1502
+ * overlaps it. In an inactive paginator (see {@link isActivePaginator}), the head interval is
1503
+ * shown instead.
1504
+ */
1505
+ private mergePageIntoInactiveHead(
1506
+ page: LocalMessage[],
1507
+ options?: ReconcileNewestMessagesOptions,
1508
+ ) {
1509
+ const interval = this.ingestPage({ page, isHead: true, setActive: false });
1510
+ if (!interval) return;
1511
+ if (!this.isActivePaginator()) {
1512
+ this.showHeadInterval(page, options);
1513
+ } else if (this.isActiveInterval(interval)) {
1514
+ this.publishActiveIntervalGrownIntoHead();
1515
+ }
1516
+ }
1517
+
1518
+ /** Publishes the active interval once a newest page grew it into the head interval. */
1519
+ private publishActiveIntervalGrownIntoHead() {
1520
+ this.publishActiveInterval({
1521
+ hasMoreHead: false,
1522
+ cursor: { headward: null, tailward: this.cursor?.tailward ?? null },
1523
+ });
1524
+ }
1525
+
1526
+ /**
1527
+ * Whether `page` proves it reached the channel's oldest message: the request was bounded by this
1528
+ * paginator's own `pageSize` and `page` came back shorter. A larger over-request (e.g.
1529
+ * `channel.reload`) may have been server-capped and never proves it. Gates `hasMoreTail` and the
1530
+ * gap rule ({@link isSeparatedFromHeadByGap}), never removing a message.
880
1531
  */
881
1532
  private pageReachedChannelStart(
882
1533
  page: LocalMessage[],
883
- options?: MergeNewestPageOptions,
1534
+ options?: ReconcileNewestMessagesOptions,
884
1535
  ): boolean {
885
1536
  const requestedLimit = options?.requestedLimit;
886
1537
  return (
@@ -891,28 +1542,30 @@ export class MessageIntervalPaginator extends BasePaginator<
891
1542
  }
892
1543
 
893
1544
  /**
894
- * Settle the below-window leftovers {@link reconcileHeadAgainstPage} handed back (loaded messages
895
- * older than `anchorId` — the returned page's oldest — and absent from the page). From the page alone
896
- * they're ambiguous: a hard-deleted oldest vs a server-capped over-request. Ask the server "anything
897
- * older than `anchorId`?" — the only cap-free way to tell. Nothing older ⇒ genuine deletes ⇒ remove
898
- * them and settle the tail. A probe failure or a head change across the await keeps them (never a false
899
- * delete). The caller decides WHEN this runs.
1545
+ * Settles the loaded messages {@link reconcileHeadAgainstPage} found tailward of the page (older
1546
+ * than `pageTailId`, the page's oldest, and absent from it): from the page alone a hard-deleted
1547
+ * oldest message looks like one the page was too short to include. It asks the server whether
1548
+ * anything is older than `pageTailId`. When nothing is, those messages were deleted: they are
1549
+ * removed and the head interval becomes the tail. A failed request, or a head interval replaced
1550
+ * while waiting, keeps them. The caller decides when this runs.
900
1551
  */
901
- private async pruneBelowWindowIfReachedStart(
902
- belowWindow: string[],
903
- anchorId: string,
1552
+ private async removeIdsTailwardOfPageIfNothingOlder(
1553
+ idsTailwardOfPage: string[],
1554
+ pageTailId: string,
904
1555
  ): Promise<void> {
905
- const headId = (this.itemIntervals[0] as Interval | undefined)?.id;
906
- // older exists (or the probe failed), we we're not provably the start, so
907
- // keep the leftovers
908
- if (await this.hasMessagesOlderThan(anchorId).catch(() => true)) return;
909
- // revalidate the head across the await (a jump/reset/newer merge aborts), then remove the leftovers
910
- const head = this.itemIntervals[0] as Interval | undefined;
911
- if (!head?.isHead || head.id !== headId) return;
912
- this.removeReconciledItems(belowWindow);
913
- head.hasMoreTail = false; // we now KNOW we reached the start, so settle the "load older" affordance
914
- head.isTail = true;
915
- if (this.isActiveInterval(head)) {
1556
+ const headIdBeforeRequest = (this.itemIntervals[0] as Interval | undefined)?.id;
1557
+ // A failed request proves nothing, so it counts as "something older exists".
1558
+ const hasMessagesOlderThanPage = await this.hasMessagesOlderThan(pageTailId).catch(
1559
+ () => true,
1560
+ );
1561
+ if (hasMessagesOlderThanPage) return;
1562
+ // A jump, a reset or another newest page may have replaced the head interval meanwhile.
1563
+ const headAfterRequest = this.itemIntervals[0] as Interval | undefined;
1564
+ if (!headAfterRequest?.isHead || headAfterRequest.id !== headIdBeforeRequest) return;
1565
+ this.removeReconciledItems(idsTailwardOfPage);
1566
+ headAfterRequest.hasMoreTail = false;
1567
+ headAfterRequest.isTail = true;
1568
+ if (this.isActiveInterval(headAfterRequest)) {
916
1569
  this.state.partialNext({
917
1570
  hasMoreTail: false,
918
1571
  cursor: { headward: null, tailward: null },
@@ -926,16 +1579,15 @@ export class MessageIntervalPaginator extends BasePaginator<
926
1579
  const { messages } = this.parentMessageId
927
1580
  ? await this.channel
928
1581
  .getClient()
929
- .getReplies({ parent_id: this.parentMessageId, ...pagination })
1582
+ .getReplies({ parent_id: this.parentMessageId }, pagination)
930
1583
  : await this.channel.query({ messages: pagination });
931
1584
  return Array.isArray(messages) && messages.length > 0;
932
1585
  }
933
1586
 
934
1587
  /**
935
- * Whether a loaded message is server-confirmed and therefore eligible to be reconciled away when
936
- * absent from an authoritative page. Excludes local-only messages the server has never
937
- * acknowledged — optimistic (`sending`) and `failed` sends, and client-side `error` placeholders —
938
- * so a legitimately-unsent message is never mistaken for a hard delete.
1588
+ * Whether a loaded message is server-confirmed, so it may be reconciled away when absent from an
1589
+ * authoritative page. Optimistic (`sending`), `failed` and client-side `error` messages are not, so
1590
+ * an unsent message is never mistaken for a hard delete.
939
1591
  */
940
1592
  protected isServerConfirmedMessage(message: LocalMessage): boolean {
941
1593
  return (
@@ -946,56 +1598,87 @@ export class MessageIntervalPaginator extends BasePaginator<
946
1598
  }
947
1599
 
948
1600
  /**
949
- * Destructive half of {@link mergeNewestPage}: remove messages in the loaded head interval that
950
- * `page` proves were hard-deleted while offline (a hard delete emits no event to other clients, and
951
- * the merge is additive, so they would otherwise linger forever).
1601
+ * Whether this list holds `message`: it passes the filter and, in a channel's main list (no
1602
+ * `parentMessageId`), is not a reply only its thread lists (see `isThreadOnlyReply`).
1603
+ */
1604
+ private isListedMessage(message: LocalMessage): boolean {
1605
+ if (!this.matchesFilter(message)) return false;
1606
+ return !!this.parentMessageId || !isThreadOnlyReply(message);
1607
+ }
1608
+
1609
+ /**
1610
+ * The failed messages a reload restores with {@link restoreFailedMessages}: those of the shown
1611
+ * interval and the head interval, and those of `persisted` (e.g. the offline database's rows of
1612
+ * the channel) this list holds (see {@link isListedMessage}). The loaded copy wins, as it is at
1613
+ * least as fresh. Take them before the reload's request.
952
1614
  *
953
- * Here `page` is the freshly-fetched newest window the server returned for the query that produced
954
- * it. Its two bounds are its NEWEST message (`page`'s last item by `created_at`) and its OLDEST
955
- * message (`page`'s first item). Reconciliation removes ONLY messages `page` actually covers — no
956
- * hardcoded page size is involved — in two regions, by a loaded message's `created_at`:
1615
+ * @internal
1616
+ */
1617
+ getFailedMessagesToRestore(persisted: LocalMessage[] = []): LocalMessage[] {
1618
+ const failedById = new Map<string, LocalMessage>();
1619
+ const listed = persisted.filter((message) => this.isListedMessage(message));
1620
+ const loaded = [...(this.items ?? []), ...this.anchoredHeadItems];
1621
+ for (const message of [...listed, ...loaded]) {
1622
+ if (message.status === 'failed') failedById.set(this.getItemId(message), message);
1623
+ }
1624
+ return [...failedById.values()];
1625
+ }
1626
+
1627
+ /**
1628
+ * Ingests again each failed message taken before a reload (see
1629
+ * {@link getFailedMessagesToRestore}) that no interval holds after it, so a reload never loses the
1630
+ * user's unsent work. One an interval holds is left as it is: it may have been resent.
957
1631
  *
958
- * - WITHIN `page` (strictly between `page`'s oldest and newest message): a server-confirmed loaded
959
- * message absent from `page` was hard-deleted. Safe with no snapshot — a message that arrived live
960
- * during the caller's fetch is always strictly newer than `page`'s newest message, so it can never
961
- * fall in this span.
962
- * - AT/ABOVE `page`'s newest message (a hard-deleted newest message), and the empty-`page` case:
963
- * only reconcilable with a pre-fetch `candidateIds` snapshot, which alone tells a just-deleted
964
- * message from one that arrived live during the fetch at that top edge.
1632
+ * @internal
1633
+ */
1634
+ restoreFailedMessages(failedMessages: LocalMessage[]) {
1635
+ const isNoLongerLoaded = (message: LocalMessage) =>
1636
+ !this.findIntervalHoldingItem(message);
1637
+ const toRestore = failedMessages.filter(isNoLongerLoaded);
1638
+ if (!toRestore.length) return;
1639
+ this.batch(
1640
+ () => {
1641
+ for (const message of toRestore) this.ingestItem(message);
1642
+ },
1643
+ { coalesce: true },
1644
+ );
1645
+ }
1646
+
1647
+ /**
1648
+ * Destructive half of {@link reconcileNewestMessages}: removes loaded head-interval messages
1649
+ * that `page` (the fresh newest interval) proves were hard-deleted while the client received no
1650
+ * events, by `created_at`:
965
1651
  *
966
- * A loaded message BELOW `page`'s oldest is NOT removed here (window-only) — from the page alone a
967
- * hard-deleted oldest is indistinguishable from a server-capped over-request. Those messages are
968
- * instead RETURNED (the below-window leftovers) so {@link pruneBelowWindowIfReachedStart} can settle
969
- * them with a `limit: 1` "anything older?" probe — the only cap-free proof — and remove them only if
970
- * the server confirms nothing older exists. Absent that proof they are kept (a later cold/fresh query
971
- * omits any real delete).
1652
+ * - within `page`'s span: a server-confirmed message absent from `page` was deleted (a live
1653
+ * arrival is newer than `page`'s newest, so this needs no snapshot);
1654
+ * - at or above `page`'s newest, and for an empty `page`: only IDs in the pre-fetch
1655
+ * `headIntervalItemIdsAtRequest` snapshot, which tells a just-deleted message from a live
1656
+ * arrival or a send confirmed during the request.
972
1657
  *
973
- * Removal goes through {@link removeItem} (batched) so the item index, intervals, shared message
974
- * store and — via the {@link MessagePaginator} override — the tracked last message all stay correct;
975
- * the active window is then re-emitted once.
1658
+ * Messages below `page`'s oldest are kept (a hard-deleted oldest looks like a server-capped
1659
+ * over-request) and returned for {@link removeIdsTailwardOfPageIfNothingOlder}. Removal goes through
1660
+ * {@link removeItem}, so the index, intervals, message store and any subclass bookkeeping (e.g.
1661
+ * the latest message of {@link MessagePaginator}) stay correct.
976
1662
  *
977
- * @returns the below-window leftover ids (loaded, server-confirmed, older than `page`'s oldest, absent
978
- * from it) for the caller's reached-start probe. Empty for the no-head / empty-page paths.
1663
+ * @returns The below-interval leftover IDs. Empty for the no-head and empty-page paths.
979
1664
  */
980
1665
  protected reconcileHeadAgainstPage(
981
1666
  page: LocalMessage[],
982
- options?: MergeNewestPageOptions,
1667
+ options?: ReconcileNewestMessagesOptions,
983
1668
  ): string[] {
984
1669
  const headInterval = this.itemIntervals[0] as Interval | undefined;
985
1670
  if (!headInterval?.isHead) return [];
986
1671
 
987
1672
  const loadedIds = headInterval.itemIds;
988
- const candidateIds = options?.candidateIds;
1673
+ const headIntervalItemIdsAtRequest = options?.headIntervalItemIdsAtRequest;
989
1674
 
990
- // Empty page → the channel has no messages. Every server-confirmed loaded message is gone, but
991
- // only remove ids from the pre-fetch snapshot so a message that landed during the fetch survives.
1675
+ // Empty page: the channel has no messages. Only IDs from the pre-fetch snapshot are removed, so a
1676
+ // message that landed during the fetch survives.
992
1677
  if (!page.length) {
993
- if (!candidateIds) return [];
994
- const toRemove = loadedIds.filter((id) => {
995
- if (!candidateIds.has(id)) return false;
996
- const message = this.getItem(id);
997
- return !!message && this.isServerConfirmedMessage(message);
998
- });
1678
+ if (!headIntervalItemIdsAtRequest) return [];
1679
+ const toRemove = loadedIds.filter(
1680
+ (id) => headIntervalItemIdsAtRequest.has(id) && this.isServerConfirmedItemId(id),
1681
+ );
999
1682
  this.removeReconciledItems(toRemove);
1000
1683
  return [];
1001
1684
  }
@@ -1004,57 +1687,36 @@ export class MessageIntervalPaginator extends BasePaginator<
1004
1687
  const newestReturnedTs = getMessageCreatedAtTimestamp(page[page.length - 1]);
1005
1688
  const oldestReturnedTs = getMessageCreatedAtTimestamp(page[0]);
1006
1689
 
1007
- // Window-only: never remove below the returned page's oldest here, because from the page alone a
1008
- // hard-deleted oldest is indistinguishable from a server-capped over-request. Below-window messages
1009
- // are collected into `belowWindow` and returned instead, for the reached-start probe to settle.
1010
- const windowLowTs = oldestReturnedTs ?? Number.POSITIVE_INFINITY;
1690
+ // Nothing below the page's oldest is removed here: those go to `idsTailwardOfPage`.
1691
+ const pageTailTs = oldestReturnedTs ?? Number.POSITIVE_INFINITY;
1011
1692
 
1012
1693
  const toRemove: string[] = [];
1013
- const belowWindow: string[] = [];
1694
+ const idsTailwardOfPage: string[] = [];
1014
1695
  for (const id of loadedIds) {
1015
- if (pageIds.has(id)) continue; // present on the server → keep
1696
+ if (pageIds.has(id)) continue;
1016
1697
  const message = this.getItem(id);
1017
- if (!message || !this.isServerConfirmedMessage(message)) continue; // local-only → keep
1698
+ if (!message || !this.isServerConfirmedMessage(message)) continue;
1018
1699
  const ts = getMessageCreatedAtTimestamp(message);
1019
- if (ts === null) continue; // no server timestamp (optimistic) → keep
1700
+ if (ts === null) continue; // no server timestamp (optimistic)
1020
1701
 
1021
1702
  if (newestReturnedTs !== null && ts >= newestReturnedTs) {
1022
- // At/above the newest returned message: a hard-deleted newest message and a message that
1023
- // arrived live during the fetch are indistinguishable here. Only remove ids present in the
1024
- // pre-fetch snapshot, which excludes live arrivals. (The newest returned message itself is
1025
- // in the page, so it is already skipped above.)
1026
- if (candidateIds?.has(id)) toRemove.push(id);
1703
+ // At or above the page's newest, a hard-deleted newest message, a live arrival and a send
1704
+ // confirmed during the request look the same: remove only IDs from the pre-fetch snapshot,
1705
+ // which holds none of the latter two.
1706
+ if (headIntervalItemIdsAtRequest?.has(id)) toRemove.push(id);
1027
1707
  continue;
1028
1708
  }
1029
- // Below the newest returned message: within the page's span (a live arrival can never be here, so
1030
- // absence = a hard delete) → remove; at/below the page's oldest → a below-window leftover the page
1031
- // cannot decide, returned for the reached-start probe.
1032
- if (ts > windowLowTs) toRemove.push(id);
1033
- else belowWindow.push(id);
1709
+ // Within the page's span a live arrival cannot be here, so absence means a hard delete. At or
1710
+ // below the page's oldest the page cannot decide: return it for the caller to settle.
1711
+ if (ts > pageTailTs) toRemove.push(id);
1712
+ else idsTailwardOfPage.push(id);
1034
1713
  }
1035
1714
 
1036
1715
  this.removeReconciledItems(toRemove);
1037
- return belowWindow;
1716
+ return idsTailwardOfPage;
1038
1717
  }
1039
1718
 
1040
- /**
1041
- * Remove a set of reconciled (hard-deleted) ids from this paginator's loaded state in one coalesced
1042
- * batch. Each id goes through {@link removeItem}, which drops it from THREE places — not a single
1043
- * interval:
1044
- *
1045
- * 1. the item index — unlinks this paginator's membership from the shared entity store (GC'ing the
1046
- * content if this was the last holder);
1047
- * 2. the interval that holds it — located by id, so it is NOT head-specific in general; in practice
1048
- * it is always the head interval, because the sole caller ({@link reconcileHeadAgainstPage})
1049
- * sources these ids from `headInterval.itemIds` and an item has single-interval membership;
1050
- * 3. the active window (`state.items`) if visible — blanking to `[]` when the window empties, per
1051
- * {@link flushWindowPublish}.
1052
- *
1053
- * The coalesced batch collapses all of that into a single `state.items` publish. Then mirror the
1054
- * removal into the offline DB (see {@link purgeReconciledFromOfflineDb}) so a cold start does not
1055
- * re-seed the ghosts from SQLite. No-op for an empty set, so an unaffected merge does not touch
1056
- * state a second time.
1057
- */
1719
+ /** Removes reconciled IDs in one coalesced batch (one publish), then mirrors it offline. */
1058
1720
  private removeReconciledItems(ids: string[]) {
1059
1721
  if (!ids.length) return;
1060
1722
  this.batch(
@@ -1067,26 +1729,15 @@ export class MessageIntervalPaginator extends BasePaginator<
1067
1729
  }
1068
1730
 
1069
1731
  /**
1070
- * Mirror a destructive reconciliation into the offline DB. A hard delete performed while the client
1071
- * was offline reaches it via no event, so the offline store never ran its own hard-delete for these
1072
- * ids; the reconnect query re-hydrates the DB by UPSERT (which never removes what is absent from the
1073
- * page), so without this the ghosts survive in SQLite and a cold start would re-seed them after the
1074
- * in-memory list already dropped them.
1075
- *
1076
- * Owned by the state layer, NOT the SDK: the SDK only supplies the platform `offlineDb`
1077
- * implementation and never orchestrates DB writes for reconciliation. Fire-and-forget and
1078
- * best-effort — the in-memory removal is the source of truth for the live list, so a failed/absent
1079
- * DB write is no worse than before (the ghost merely re-appears on a cold start until the next
1080
- * reconcile). No-op when offline support is off (`client.offlineDb` undefined). The ids are already
1081
- * server-confirmed (the reconcile excludes pending/failed/optimistic), so a plain hard delete —
1082
- * without the pending-task teardown of a local failed message — is correct.
1732
+ * Mirrors a reconciliation into the offline DB: a hard delete done while offline reaches it via no
1733
+ * event and the reconnect query upserts (never removing absent rows), so a cold start would re-seed
1734
+ * the ghosts. Fire-and-forget, no-op without offline support.
1083
1735
  */
1084
1736
  private purgeReconciledFromOfflineDb(ids: string[]) {
1085
1737
  const offlineDb = this.channel.getClient?.()?.offlineDb;
1086
1738
  if (!offlineDb) return;
1087
- // The offline DB owns the batching (single transaction); we just hand it the reconciled ids.
1088
1739
  offlineDb.hardDeleteMessages({ ids }).catch(() => {
1089
- // best-effort persistence cleanup — see doc comment; the live list is already correct.
1740
+ // Best effort: the live list is already correct.
1090
1741
  });
1091
1742
  }
1092
1743
 
@@ -1094,15 +1745,12 @@ export class MessageIntervalPaginator extends BasePaginator<
1094
1745
  lastReadAt,
1095
1746
  messages,
1096
1747
  }: {
1097
- lastReadAt: number;
1748
+ lastReadAt: TimestampNS;
1098
1749
  messages: LocalMessage[];
1099
1750
  }): { firstUnreadMessageId: string | null; lastReadMessageId: string | null } => {
1100
- // Messages are expected in chronological order. We find:
1101
- // - lastReadMessageId: newest message with created_at <= lastReadAt
1102
- // - firstUnreadMessageId: first message with created_at > lastReadAt
1103
- //
1104
- // If the page starts after lastReadAt, the entire page is unread and the first message is
1105
- // used as unread anchor (legacy "whole channel is unread" behavior for this queried window).
1751
+ // Messages are chronological: `lastReadMessageId` is the newest with `created_at <= lastReadAt`,
1752
+ // `firstUnreadMessageId` the first with `created_at > lastReadAt`. If the page starts after
1753
+ // `lastReadAt`, the whole page is unread and its first message is the unread anchor.
1106
1754
  const lastReadTimestamp = lastReadAt;
1107
1755
  if (!Number.isFinite(lastReadTimestamp) || !messages.length) {
1108
1756
  return { firstUnreadMessageId: null, lastReadMessageId: null };
@@ -1167,20 +1815,15 @@ export class MessageIntervalPaginator extends BasePaginator<
1167
1815
 
1168
1816
  this.messageFocusSignal.next({ signal });
1169
1817
 
1170
- // NOTE: the auto-dismissal countdown is intentionally NOT started here. A focused message may
1171
- // be emitted while its message list is not yet visible (e.g. the channel is covered by a thread
1172
- // panel when a "view in channel" jump resolves), so measuring the highlight lifetime from the
1173
- // moment the jump resolved would burn it while the message is still off-screen. The consumer
1174
- // starts the countdown via `scheduleMessageFocusSignalClear` once the message is actually
1175
- // viewed.
1818
+ // The auto-dismiss countdown does not start here: the message list may not be visible yet (e.g.
1819
+ // covered by a thread panel), so the consumer starts it via `scheduleMessageFocusSignalClear`.
1176
1820
  return signal;
1177
1821
  };
1178
1822
 
1179
1823
  /**
1180
- * Starts the auto-dismissal countdown for the currently active focus signal. Call this once the
1181
- * focused message has been viewed (rendered and visible), so the highlight's lifetime is measured
1182
- * from when the user could actually see it rather than from when the jump resolved. No-op if the
1183
- * signal has already been cleared or superseded (guarded by `token`).
1824
+ * Starts the auto-dismiss countdown for the active focus signal. Call it once the focused message
1825
+ * is viewed, so the highlight lasts from when the user could see it. No-op if the signal was
1826
+ * cleared or superseded (guarded by `token`).
1184
1827
  */
1185
1828
  scheduleMessageFocusSignalClear = ({
1186
1829
  token,
@@ -1220,19 +1863,14 @@ export class MessageIntervalPaginator extends BasePaginator<
1220
1863
  }
1221
1864
 
1222
1865
  /**
1223
- * Partial truncation for `channel.truncated` carrying a `truncated_at`: drop every loaded
1224
- * message strictly older than the cutoff (keeping newer ones) across all loaded windows,
1225
- * mirroring the legacy per-message-set pruning. For a full truncation (no `truncated_at`) use
1226
- * {@link MessageIntervalPaginator.clearStateAndCache} instead.
1227
- *
1228
- * Batched and edge-classified: because messages are chronological, each interval is classified by
1229
- * its `tail` (oldest) and `head` (newest) edges, so only the single interval that *straddles* the
1230
- * cutoff is scanned member-by-member — the rest are kept or dropped wholesale. The straddling
1231
- * interval becomes the new global tail (nothing older than the cutoff exists anymore), so its
1232
- * `isTail`/`hasMoreTail` are set; intervals entirely newer keep their flags (unloaded older
1233
- * messages may still sit between them and the cutoff). The active window is re-emitted once.
1866
+ * Partial truncation for `channel.truncated` with a `truncated_at`: drops every loaded message
1867
+ * strictly older than the cutoff across all intervals (a full truncation uses
1868
+ * {@link MessageIntervalPaginator.clearStateAndCache}). Only the interval straddling the cutoff is
1869
+ * scanned member by member and becomes the new global tail; intervals entirely newer keep their
1870
+ * flags, since unloaded older messages may sit between them and the cutoff. The active interval is
1871
+ * re-emitted once.
1234
1872
  */
1235
- truncate = ({ truncatedAt }: { truncatedAt: number }) => {
1873
+ truncate({ truncatedAt }: { truncatedAt: TimestampNS }) {
1236
1874
  const cutoff = truncatedAt;
1237
1875
  if (!Number.isFinite(cutoff)) return;
1238
1876
 
@@ -1251,8 +1889,7 @@ export class MessageIntervalPaginator extends BasePaginator<
1251
1889
  } else if (isOld(edges.head)) {
1252
1890
  removedIds.push(...interval.itemIds); // newest edge < cutoff → whole interval is older
1253
1891
  } else {
1254
- // determines the cutoff. Items are chronological, so the old ones are at the beginning of the array,
1255
- // binary-search rather than scanning every member.
1892
+ // Items are chronological, so the old ones come first: binary-search the split.
1256
1893
  const ids = interval.itemIds;
1257
1894
  const splitIndex = lowerBound(
1258
1895
  ids.length,
@@ -1271,37 +1908,46 @@ export class MessageIntervalPaginator extends BasePaginator<
1271
1908
  if (!removedIds.length) return;
1272
1909
  for (const id of removedIds) this._itemIndex.remove(id);
1273
1910
 
1274
- // No re-sort needed: `survivingIntervals` preserves the order of the already-sorted
1275
- // `itemIntervals` (we only keep/prune/drop, never reorder), and truncation removes only
1276
- // tailward items — an interval's head edge (the intervalComparator sort key) never changes.
1911
+ // No re-sort: intervals keep their order and truncation only removes tailward items, so the head
1912
+ // edge (the interval sort key) never changes.
1277
1913
  this.setIntervals(survivingIntervals);
1278
1914
 
1279
- // Single re-emit of the active window (setIntervals does not emit).
1915
+ // `setIntervals` does not emit: re-emit the active interval once.
1280
1916
  const active = this._activeIntervalId
1281
1917
  ? this._itemIntervals.get(this._activeIntervalId)
1282
1918
  : undefined;
1283
- if (active && !isLogicalInterval(active)) {
1284
- this.setActiveInterval(active);
1919
+ if (active) {
1920
+ // `setActiveInterval` does not emit for a logical interval, so its survivors are emitted here.
1921
+ if (isLogicalInterval(active)) {
1922
+ this.state.partialNext({ items: this.intervalToItems(active) });
1923
+ } else {
1924
+ this.setActiveInterval(active);
1925
+ }
1285
1926
  return;
1286
1927
  }
1287
1928
 
1288
- // The active window was truncated away entirely. It sat below the cutoff, so it was older
1289
- // than every survivor — activate the nearest surviving window (the tail-most, i.e. oldest,
1290
- // anchored interval) rather than emitting an empty page, which would blank the message list.
1929
+ // The active interval was truncated away: activate the tail-most (oldest) surviving anchored
1930
+ // interval rather than blank the message list.
1291
1931
  const anchoredSurvivors = this.itemIntervals.filter(
1292
1932
  (itv): itv is Interval => !isLogicalInterval(itv),
1293
1933
  );
1294
1934
 
1295
- // If the active interval was truncated, we move to the neareast interval - which is the tail now
1296
1935
  const fallback = this.getTailIntervalFromSortedIntervals(anchoredSurvivors);
1297
1936
  if (fallback) {
1298
1937
  this.setActiveInterval(fallback);
1299
1938
  } else {
1300
- // Nothing loaded survived the truncation.
1301
- this.state.partialNext({ items: [] });
1939
+ // Nothing loaded survived the truncation. Drop the stale active id too: the next ingested
1940
+ // message lands in a logical head interval, which is only activated (and published) when no
1941
+ // interval is active.
1942
+ this.setActiveInterval(undefined);
1943
+ this.state.partialNext({ items: [], hasMoreTail: false });
1302
1944
  }
1303
- };
1945
+ }
1304
1946
 
1947
+ /**
1948
+ * Deletes `userId`'s loaded messages (removes them on a hard delete) and marks the quotes of them
1949
+ * as deleted. Returns the messages it deleted, as they were before.
1950
+ */
1305
1951
  applyMessageDeletionForUser = ({
1306
1952
  userId,
1307
1953
  hardDelete = false,
@@ -1309,58 +1955,56 @@ export class MessageIntervalPaginator extends BasePaginator<
1309
1955
  }: {
1310
1956
  userId: string;
1311
1957
  hardDelete?: boolean;
1312
- deletedAt: number;
1313
- }) => {
1314
- const loadedMessages = this.items ?? [];
1958
+ deletedAt: TimestampNS;
1959
+ }): LocalMessage[] => {
1960
+ const loadedMessages = this._itemIndex.values();
1961
+ const deletedMessages: LocalMessage[] = [];
1315
1962
 
1316
- // Batch: one logical operation touches many messages; coalesce the shared-store fan-out to a
1317
- // single flush (sibling holders are notified once) instead of once per affected message.
1318
- this.batch(() => {
1319
- for (const message of loadedMessages) {
1320
- if (message.user?.id === userId) {
1321
- if (hardDelete) {
1322
- this.removeItem({ id: message.id });
1323
- } else {
1324
- this.ingestItem(
1325
- toDeletedMessage({
1326
- message,
1963
+ // Coalesce: one emit for this interval and one shared-store flush for the sibling holders.
1964
+ this.batch(
1965
+ () => {
1966
+ for (const message of loadedMessages) {
1967
+ if (message.user?.id === userId) {
1968
+ deletedMessages.push(message);
1969
+ if (hardDelete) {
1970
+ this.removeItem({ id: message.id });
1971
+ } else {
1972
+ this.ingestItem(
1973
+ toDeletedMessage({
1974
+ message,
1975
+ hardDelete,
1976
+ deletedAt,
1977
+ }) as LocalMessage,
1978
+ );
1979
+ }
1980
+ continue;
1981
+ }
1982
+
1983
+ if (
1984
+ message.quoted_message?.user?.id === userId &&
1985
+ message.quoted_message.type !== 'deleted'
1986
+ ) {
1987
+ this.ingestItem({
1988
+ ...message,
1989
+ quoted_message: toDeletedMessage({
1990
+ message: formatMessage(message.quoted_message),
1327
1991
  hardDelete,
1328
1992
  deletedAt,
1329
1993
  }) as LocalMessage,
1330
- );
1994
+ });
1331
1995
  }
1332
- continue;
1333
- }
1334
-
1335
- if (
1336
- message.quoted_message?.user?.id === userId &&
1337
- message.quoted_message.type !== 'deleted'
1338
- ) {
1339
- this.ingestItem({
1340
- ...message,
1341
- quoted_message: toDeletedMessage({
1342
- message: formatMessage(message.quoted_message),
1343
- hardDelete,
1344
- deletedAt,
1345
- }) as LocalMessage,
1346
- });
1347
1996
  }
1348
- }
1349
- });
1997
+ },
1998
+ { coalesce: true },
1999
+ );
2000
+ return deletedMessages;
1350
2001
  };
1351
2002
 
1352
- /**
1353
- * Ensures quoted-message snapshots across loaded paginator cache are in sync
1354
- * with the provided message.
1355
- *
1356
- * Scans cached messages and updates any item where `quoted_message_id`
1357
- * matches `message.id`.
1358
- */
2003
+ /** Updates the quoted-message snapshot of every cached message that quotes `message`. */
1359
2004
  reflectQuotedMessageUpdate = (message: LocalMessage) => {
1360
2005
  const cachedMessages = this._itemIndex.values();
1361
2006
 
1362
- // Batch: several cached messages may quote the updated one; coalesce the shared-store fan-out
1363
- // to a single flush instead of one per re-ingested quoting message.
2007
+ // Several cached messages may quote it: coalesce the shared-store fan-out into one flush.
1364
2008
  this.batch(() => {
1365
2009
  for (const cachedMessage of cachedMessages) {
1366
2010
  if (cachedMessage.quoted_message_id !== message.id) continue;
@@ -1374,22 +2018,18 @@ export class MessageIntervalPaginator extends BasePaginator<
1374
2018
  };
1375
2019
 
1376
2020
  /**
1377
- * Reflect an updated `user` object onto every cached message authored by that user, mirroring
1378
- * the legacy `ChannelState.updateUserMessages` for the main message list (does not touch
1379
- * `quoted_message.user` — that is not part of the legacy behavior).
1380
- *
1381
- * Batched: a user rename can affect many messages, so this patches the shared item index and
1382
- * re-emits the active window a single time (if it held an affected message) rather than one
1383
- * `ingestItem` re-emit per message.
2021
+ * Reflects an updated `user` onto every cached message authored by that user (not
2022
+ * `quoted_message.user`). Patches the shared item index in one batch and re-emits the active
2023
+ * interval once, if it held an affected message.
1384
2024
  */
1385
- reflectUserUpdate = (user: UserResponse) => {
2025
+ reflectUserUpdate(user: UserResponse) {
1386
2026
  const activeIds = new Set((this.items ?? []).map((m) => this.getItemId(m)));
1387
2027
  let activeAffected = false;
1388
- // Batch: a user rename can touch many messages; coalesce the shared-store fan-out to sibling
1389
- // holders into a single flush. This paginator's own active window is re-emitted once below.
2028
+ // A rename can touch many messages: coalesce the shared-store fan-out into one flush.
1390
2029
  this.batch(() => {
1391
2030
  for (const message of this._itemIndex.values()) {
1392
2031
  if (message.user?.id !== user.id) continue;
2032
+ if (message.user === user) continue;
1393
2033
  this._itemIndex.setOne({ ...message, user });
1394
2034
  if (activeIds.has(this.getItemId(message))) activeAffected = true;
1395
2035
  }
@@ -1399,124 +2039,92 @@ export class MessageIntervalPaginator extends BasePaginator<
1399
2039
  items: (this.items ?? []).map((m) => this.getItem(this.getItemId(m)) ?? m),
1400
2040
  });
1401
2041
  }
1402
- };
2042
+ }
1403
2043
 
1404
2044
  /**
1405
- * Apply a reaction WS event (`reaction.new` / `reaction.updated` / `reaction.deleted`) to the
1406
- * cached message. The event's `message` already carries the server-updated
1407
- * `reaction_groups` / `latest_reactions`; only `own_reactions` needs local preservation so a
1408
- * cross-user reaction does not wipe the current user's reactions. This re-homes what
1409
- * `ChannelState.addReaction` / `removeReaction` used to do off the now-removed
1410
- * `channel.state.messages` / `channel.state.threads` caches (the same logic backs the thread
1411
- * paginator via `Thread.messagePaginator`).
1412
- *
1413
- * `own_reactions` is seeded from the currently cached item (so another user's reaction keeps ours),
1414
- * falling back to the event's own_reactions when the message is not loaded — matching the legacy
1415
- * behavior where `_updateMessage` only mutated a message that existed locally.
1416
- *
1417
- * @param params - The reaction event payload.
1418
- * @param params.message - The reaction event's message, carrying the
1419
- * server-computed `reaction_groups` / `latest_reactions`. Ingested as-is except for `own_reactions`.
1420
- * @param params.reaction - The reaction from the event. Only added to/removed from
1421
- * `own_reactions` when its `user_id` is the current user; otherwise the current user's
1422
- * `own_reactions` are left untouched.
1423
- * @param [params.removed=false] - `true` for `reaction.deleted` (remove the reaction from
1424
- * `own_reactions`); `false` for `reaction.new` / `reaction.updated` (add it).
1425
- * @param [params.enforceUnique=false] - When adding, first clear the current user's existing
1426
- * `own_reactions` so only the incoming one remains (used by `reaction.updated`, where a user's
1427
- * reaction replaces their previous one).
1428
- *
1429
- * TODO(reactive-store): reflect reactions ONCE at the store level, not per-paginator. Both the
1430
- * channel handler (channel.ts) and the thread handler (thread.ts) call this on every reaction.*
1431
- * event, so a message held in more than one collection (a show_in_channel reply, or the thread
1432
- * parent) is reflected TWICE: two writes to the same canonical slot, each fanning out to the
1433
- * other holder (double re-projection) and minting a fresh ref that defeats the reconcile
1434
- * ref-equality bail. Idempotent (counts come wholesale from the event) so the result is correct,
1435
- * just wasteful. The store already fans out to every holder, so reflect once (by id, if held) and
1436
- * retire the per-collection reflect calls + parent path + enforce_unique branch.
2045
+ * The last loaded message created at or before `timestamp` (a floor), or `null` when it precedes
2046
+ * every loaded message. With `exactTsMatch`, only a message created exactly at `timestamp` matches.
2047
+ * Searches the loaded intervals from the head down (each already sorted, O(log n) per interval):
2048
+ * the first holding a message at or before `timestamp` holds the answer. Used by the receipts
2049
+ * tracker to resolve read/delivered cursors.
1437
2050
  */
1438
- reflectReaction = ({
1439
- enforceUnique = false,
1440
- message,
1441
- reaction,
1442
- removed = false,
1443
- }: {
1444
- message: MessageResponse | LocalMessage;
1445
- reaction: ReactionResponse;
1446
- enforceUnique?: boolean;
1447
- removed?: boolean;
1448
- }) => {
1449
- const formatted = formatMessage(message);
1450
- const existing = this.getItem(formatted.id);
1451
- const baseOwnReactions = existing?.own_reactions ?? formatted.own_reactions ?? [];
1452
- const own_reactions = computeOwnReactions({
1453
- current: baseOwnReactions,
1454
- enforceUnique,
1455
- reaction,
1456
- removed,
1457
- userId: this.channel.getClient().userId,
1458
- });
1459
- this.ingestItem({ ...formatted, own_reactions });
2051
+ findItemByTimestamp = (
2052
+ timestamp: TimestampNS,
2053
+ exactTsMatch = false,
2054
+ ): LocalMessage | null => {
2055
+ for (const interval of this.sortIntervals(this.itemIntervals)) {
2056
+ const found = this.findItemByTimestampIn(
2057
+ this.intervalToItems(interval),
2058
+ timestamp,
2059
+ exactTsMatch,
2060
+ );
2061
+ if (found !== undefined) return found;
2062
+ }
2063
+ return null;
1460
2064
  };
1461
2065
 
1462
2066
  /**
1463
- * Map a timestamp to a loaded message — the first message in the latest (head) window whose
1464
- * `created_at` is >= `timestamp` (mirrors the legacy `ChannelState.findMessageByTimestamp`
1465
- * lower-bound search), or the newest loaded message when the timestamp is beyond it. Used by the
1466
- * receipts tracker to resolve read/delivered cursors. Searches the newest loaded window — where
1467
- * read cursors live — which is already sorted, so this is O(log n) with no re-sort.
2067
+ * {@link findItemByTimestamp} within one interval (`items` ascending by `created_at`). `undefined`
2068
+ * when every item is newer than `timestamp`, so an older interval has to be searched.
1468
2069
  */
1469
- findItemByTimestamp = (
1470
- timestamp: number,
1471
- exactTsMatch = false,
1472
- ): LocalMessage | null => {
1473
- const items = this.headItems; // ascending by created_at
1474
- if (!items.length) return null;
1475
- // Resolve the last message created AT OR BEFORE `timestamp` (floor). The sole caller is
1476
- // read/delivered cursor resolution (MessageReceiptsTracker): the cursor carries the timestamp of
1477
- // the last message a participant reached, so a message created strictly after the cursor has NOT
1478
- // been reached. A ceil match (first message >= target) would over-count it — e.g. a participant
1479
- // whose read cursor predates every loaded message would be reported as having read the oldest one.
1480
- // `lowerBound` returns the first index whose created_at is strictly greater than the target, so
1481
- // the floor is the item immediately before it.
2070
+ private findItemByTimestampIn(
2071
+ items: LocalMessage[],
2072
+ timestamp: TimestampNS,
2073
+ exactTsMatch: boolean,
2074
+ ): LocalMessage | null | undefined {
2075
+ if (!items.length) return undefined;
2076
+ // A floor, not a ceil: a cursor is the timestamp of the last message a participant reached, so a
2077
+ // ceil would count the oldest loaded message as read by a cursor that predates all of them.
2078
+ // `lowerBound` finds the first index strictly after the target.
1482
2079
  const firstAfter = lowerBound(items.length, (i) => {
1483
2080
  const t = getMessageCreatedAtTimestamp(items[i]);
1484
2081
  return t === null || t > timestamp;
1485
2082
  });
1486
- if (firstAfter === 0) return null; // target precedes every loaded message
2083
+ if (firstAfter === 0) return undefined; // target precedes every message in this interval
1487
2084
  const found = items[firstAfter - 1];
1488
2085
  const foundTimestamp = getMessageCreatedAtTimestamp(found);
1489
- // A message without a resolvable created_at (e.g. an optimistic message still missing its
1490
- // server timestamp) cannot be located by timestamp.
2086
+ // A message without a server timestamp (e.g. optimistic) cannot be located.
1491
2087
  if (foundTimestamp === null) return null;
1492
2088
  if (!exactTsMatch) return found;
1493
2089
  return foundTimestamp === timestamp ? found : null;
1494
- };
2090
+ }
1495
2091
 
1496
- filterQueryResults = (items: LocalMessage[]) =>
1497
- items.filter(this.shouldIncludeMessageInInterval.bind(this));
2092
+ override filterQueryResults(items: LocalMessage[]) {
2093
+ return items.filter(this.shouldIncludeMessageInInterval.bind(this));
2094
+ }
2095
+
2096
+ /**
2097
+ * The sort of a replies request. A page newer than a cursor (`id_gt`, `created_at_after`, ...)
2098
+ * must hold the replies right after the cursor, so it is requested oldest first: newest first
2099
+ * returns the newest replies and skips the ones in between. The page is put in item order
2100
+ * afterwards, so the request sort only decides which replies the page holds.
2101
+ */
2102
+ private getRepliesRequestSort(options: MessageQueryShape): MessagePaginatorSort {
2103
+ if (getLinearQueryDirection(options) !== 'headward') return this.requestSort;
2104
+ return this.requestSort.map((sort) => ({ ...sort, direction: 1 }));
2105
+ }
1498
2106
 
1499
2107
  private getCanonicalQueryItems(items: LocalMessage[]): LocalMessage[] {
1500
2108
  return [...items].sort(this.itemOrderComparator);
1501
2109
  }
1502
- }
1503
2110
 
1504
- const makeDeriveCursor =
1505
- (
1506
- paginator: MessageIntervalPaginator,
1507
- ): CursorDerivator<LocalMessage, MessageQueryShape> =>
1508
- (ctx) => {
1509
- // Not included in the interval (filtered out by MessageIntervalPaginator.filterQueryResults).
1510
- //
1511
- // IMPORTANT: We must keep cursor derivation consistent with the ingested interval.
1512
- // The interval is built from the filtered page, but ctx.page contains the raw response.
1513
- // Around/linear derivators compare page edges and lengths against interval.itemIds. If we
1514
- // pass a page that includes locally filtered messages (e.g. shadowed), those comparisons
1515
- // can incorrectly conclude that the page is not at the dataset bounds.
2111
+ /**
2112
+ * The cursor and more-messages flags after a page is placed (`deriveCursor`). A page around a
2113
+ * point counts the messages the server returned on each side of it. Any other page is compared
2114
+ * with the interval's outermost server-known messages (see {@link getServerKnownEdges}): a page
2115
+ * never holds an unsent message, so one at an edge must not hide that the page reached the edge.
2116
+ */
2117
+ private deriveCursorFromPage(
2118
+ ctx: CursorDeriveContext<LocalMessage, MessageQueryShape>,
2119
+ ): CursorDeriveResult {
2120
+ // The interval is built from the filtered page but `ctx.page` is the raw response. The linear
2121
+ // derivation compares the page's length with the requested size and its edges with the
2122
+ // interval's server-known edges, so the locally filtered messages (e.g. shadowed) are dropped for
2123
+ // it, or it would wrongly conclude the page is not at the bounds.
1516
2124
  const pageWithPermittedMessages: LocalMessage[] = [];
1517
2125
  let filteredLocallyCount = 0;
1518
2126
  for (const message of ctx.page) {
1519
- if (!paginator.shouldIncludeMessageInInterval(message)) {
2127
+ if (!this.shouldIncludeMessageInInterval(message)) {
1520
2128
  filteredLocallyCount++;
1521
2129
  } else {
1522
2130
  pageWithPermittedMessages.push(message);
@@ -1527,11 +2135,7 @@ const makeDeriveCursor =
1527
2135
  0,
1528
2136
  ctx.requestedPageSize - filteredLocallyCount,
1529
2137
  );
1530
-
1531
- if (
1532
- ctx.interval &&
1533
- ctx.interval.itemIds.length + filteredLocallyCount < ctx.page.length
1534
- ) {
2138
+ if (ctx.interval.itemIds.length + filteredLocallyCount < ctx.page.length) {
1535
2139
  console.error(
1536
2140
  'error',
1537
2141
  'Corrupted message set state: parent set size < returned page size',
@@ -1543,48 +2147,23 @@ const makeDeriveCursor =
1543
2147
  };
1544
2148
  }
1545
2149
 
1546
- const injectCursor = ({
1547
- hasMoreHead,
1548
- hasMoreTail,
1549
- }: {
1550
- hasMoreHead: boolean;
1551
- hasMoreTail: boolean;
1552
- }): CursorDeriveResult => {
1553
- const cursor: PaginatorCursor = {
1554
- headward: !hasMoreHead ? null : (ctx.interval?.itemIds.slice(-1)[0] ?? null),
1555
- tailward: !hasMoreTail ? null : (ctx.interval?.itemIds[0] ?? null),
1556
- };
1557
- return { cursor, hasMoreHead, hasMoreTail };
2150
+ // A page around a point is judged by how many messages the server returned on each side of it,
2151
+ // so it is read as returned: a message filtered locally, the target included, still shows the
2152
+ // server had it, and dropping it would make its side look exhausted.
2153
+ const aroundDerivationCtx = ctx;
2154
+ const linearDerivationCtx = {
2155
+ ...ctx,
2156
+ intervalEdges: this.getServerKnownEdges(ctx.interval),
2157
+ page: pageWithPermittedMessages,
2158
+ requestedPageSize: requestedPageSizeAfterAdjustment,
1558
2159
  };
1559
-
1560
- if ((ctx.queryShape as MessagePaginationParams)?.created_at_around) {
1561
- return injectCursor(
1562
- deriveCreatedAtAroundPaginationFlags<
1563
- LocalMessage,
1564
- MessagePaginationParams,
1565
- MessageIntervalPaginator
1566
- >({
1567
- ...ctx,
1568
- paginator,
1569
- page: pageWithPermittedMessages,
1570
- requestedPageSize: requestedPageSizeAfterAdjustment,
1571
- }),
1572
- );
1573
- } else if (ctx.queryShape?.id_around) {
1574
- return injectCursor(
1575
- deriveIdAroundPaginationFlags({
1576
- ...ctx,
1577
- page: pageWithPermittedMessages,
1578
- requestedPageSize: requestedPageSizeAfterAdjustment,
1579
- }),
1580
- );
1581
- } else {
1582
- return injectCursor(
1583
- deriveLinearPaginationFlags({
1584
- ...ctx,
1585
- page: pageWithPermittedMessages,
1586
- requestedPageSize: requestedPageSizeAfterAdjustment,
1587
- }),
1588
- );
1589
- }
1590
- };
2160
+ const flags = (ctx.queryShape as MessagePaginationParams)?.created_at_around
2161
+ ? deriveCreatedAtAroundPaginationFlags<LocalMessage, MessagePaginationParams>(
2162
+ aroundDerivationCtx,
2163
+ )
2164
+ : ctx.queryShape?.id_around
2165
+ ? deriveIdAroundPaginationFlags(aroundDerivationCtx)
2166
+ : deriveLinearPaginationFlags(linearDerivationCtx);
2167
+ return { ...flags, cursor: this.getCursorFromInterval(ctx.interval, flags) };
2168
+ }
2169
+ }