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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (298) hide show
  1. package/README.md +11 -8
  2. package/dist/cjs/index.browser.js +15397 -12090
  3. package/dist/cjs/index.browser.js.map +4 -4
  4. package/dist/cjs/index.node.js +15349 -11991
  5. package/dist/cjs/index.node.js.map +4 -4
  6. package/dist/esm/index.mjs +15164 -11880
  7. package/dist/esm/index.mjs.map +4 -4
  8. package/dist/types/ChannelManager.d.ts +246 -6
  9. package/dist/types/CooldownTimer.d.ts +22 -8
  10. package/dist/types/EventHandlerPipeline.d.ts +12 -16
  11. package/dist/types/LiveLocationManager.d.ts +69 -6
  12. package/dist/types/api-client.d.ts +22 -9
  13. package/dist/types/channel.d.ts +550 -300
  14. package/dist/types/channel_state.d.ts +167 -22
  15. package/dist/types/client.d.ts +325 -305
  16. package/dist/types/configuration/ConfigController.d.ts +172 -0
  17. package/dist/types/configuration/InstanceConfigurationRegistry.d.ts +192 -0
  18. package/dist/types/configuration/index.d.ts +3 -0
  19. package/dist/types/configuration/keys.d.ts +31 -0
  20. package/dist/types/configuration/shape.d.ts +58 -0
  21. package/dist/types/configuration/types.d.ts +206 -50
  22. package/dist/types/configuration/utils/applyInstanceConfiguration.d.ts +59 -0
  23. package/dist/types/configuration/utils/copyConfigPatch.d.ts +1 -0
  24. package/dist/types/configuration/utils/declarativeSlices.d.ts +24 -0
  25. package/dist/types/configuration/utils/deepFreezeConfig.d.ts +22 -0
  26. package/dist/types/configuration/utils/index.d.ts +1 -0
  27. package/dist/types/configuration/utils/serverAuthority.d.ts +49 -0
  28. package/dist/types/connection/ConnectionIdManager.d.ts +67 -0
  29. package/dist/types/connection/ConnectionRecoveryManager.d.ts +164 -0
  30. package/dist/types/connection/index.d.ts +4 -0
  31. package/dist/types/connection/networkConnection/NetworkConnectionObserver.d.ts +153 -0
  32. package/dist/types/connection/networkConnection/index.d.ts +3 -0
  33. package/dist/types/connection/networkConnection/reporters.d.ts +43 -0
  34. package/dist/types/connection/networkConnection/types.d.ts +55 -0
  35. package/dist/types/connection/wsConnection/StableWSConnection.d.ts +204 -0
  36. package/dist/types/connection/wsConnection/WSConnection.d.ts +168 -0
  37. package/dist/types/connection/wsConnection/WSConnectionFallback.d.ts +55 -0
  38. package/dist/types/connection/wsConnection/config.d.ts +51 -0
  39. package/dist/types/connection/wsConnection/index.d.ts +4 -0
  40. package/dist/types/connection/wsConnection/types.d.ts +99 -0
  41. package/dist/types/constants.d.ts +3 -1
  42. package/dist/types/entityStore/EntityStore.d.ts +160 -40
  43. package/dist/types/entityStore/StoreBackedItemIndex.d.ts +48 -29
  44. package/dist/types/entityStore/index.d.ts +0 -1
  45. package/dist/types/errors.d.ts +24 -4
  46. package/dist/types/formatMessageMemo.d.ts +5 -0
  47. package/dist/types/gen/chat/ChannelApi.d.ts +51 -23
  48. package/dist/types/gen/chat/ChatApi.d.ts +215 -168
  49. package/dist/types/gen/models/index.d.ts +2164 -557
  50. package/dist/types/gen/models/timestamp-guard.d.ts +22 -0
  51. package/dist/types/gen/moderation/ModerationApi.d.ts +39 -32
  52. package/dist/types/gen-imports.d.ts +1 -0
  53. package/dist/types/index.d.ts +20 -7
  54. package/dist/types/languageNames.d.ts +97 -0
  55. package/dist/types/logger.d.ts +1 -1
  56. package/dist/types/messageComposer/CustomDataManager.d.ts +7 -1
  57. package/dist/types/messageComposer/LocationComposer.d.ts +10 -4
  58. package/dist/types/messageComposer/attachmentIdentity.d.ts +11 -0
  59. package/dist/types/messageComposer/attachmentManager.d.ts +48 -10
  60. package/dist/types/messageComposer/attachmentUtils.d.ts +34 -0
  61. package/dist/types/messageComposer/configuration/commands.configuration.d.ts +1 -3
  62. package/dist/types/messageComposer/configuration/configuration.d.ts +9 -1
  63. package/dist/types/messageComposer/configuration/index.d.ts +0 -1
  64. package/dist/types/messageComposer/configuration/types.d.ts +57 -1
  65. package/dist/types/messageComposer/index.d.ts +1 -0
  66. package/dist/types/messageComposer/linkPreviewsManager.d.ts +10 -4
  67. package/dist/types/messageComposer/messageComposer.d.ts +210 -14
  68. package/dist/types/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.d.ts +20 -1
  69. package/dist/types/messageComposer/middleware/messageComposer/attachments.d.ts +11 -0
  70. package/dist/types/messageComposer/middleware/messageComposer/types.d.ts +2 -2
  71. package/dist/types/messageComposer/middleware/pollComposer/index.d.ts +1 -0
  72. package/dist/types/messageComposer/middleware/pollComposer/state.d.ts +3 -2
  73. package/dist/types/messageComposer/middleware/pollComposer/types.d.ts +9 -2
  74. package/dist/types/messageComposer/middleware/pollComposer/validation.d.ts +44 -0
  75. package/dist/types/messageComposer/middleware/textComposer/commands.d.ts +2 -2
  76. package/dist/types/messageComposer/middleware/textComposer/mentions.d.ts +94 -229
  77. package/dist/types/messageComposer/pollComposer.d.ts +8 -3
  78. package/dist/types/messageComposer/textComposer.d.ts +9 -1
  79. package/dist/types/messageComposer/types.d.ts +7 -3
  80. package/dist/types/messageDelivery/MessageDeliveryReporter.d.ts +64 -8
  81. package/dist/types/messageDelivery/MessageReceiptsTracker.d.ts +48 -11
  82. package/dist/types/messageOperations/FailedSendCache.d.ts +34 -0
  83. package/dist/types/messageOperations/MessageOperationStatePolicy.d.ts +52 -6
  84. package/dist/types/messageOperations/MessageOperations.d.ts +94 -11
  85. package/dist/types/{entityStore → messageOperations}/applyReactionLocally.d.ts +8 -2
  86. package/dist/types/messageOperations/createMessageOperations.d.ts +11 -0
  87. package/dist/types/messageOperations/index.d.ts +7 -1
  88. package/dist/types/messageOperations/reflectReactionEvent.d.ts +24 -0
  89. package/dist/types/messageOperations/sendOrdering.d.ts +17 -0
  90. package/dist/types/messageOperations/settlePendingAttachmentUploads.d.ts +28 -0
  91. package/dist/types/messageOperations/types.d.ts +66 -1
  92. package/dist/types/middleware.d.ts +8 -0
  93. package/dist/types/moderation.d.ts +18 -4
  94. package/dist/types/notifications/NotificationManager.d.ts +43 -2
  95. package/dist/types/notifications/types.d.ts +55 -42
  96. package/dist/types/offline-support/offline_support_api.d.ts +128 -12
  97. package/dist/types/offline-support/offline_sync_manager.d.ts +26 -5
  98. package/dist/types/offline-support/queueableOperations.d.ts +106 -0
  99. package/dist/types/offline-support/types.d.ts +77 -28
  100. package/dist/types/pagination/FilterBuilder.d.ts +1 -18
  101. package/dist/types/pagination/cursorDerivation/createdAtAroundPaginationFlags.d.ts +2 -1
  102. package/dist/types/pagination/cursorDerivation/linearPaginationFlags.d.ts +21 -3
  103. package/dist/types/pagination/filterCompiler.d.ts +5 -0
  104. package/dist/types/pagination/paginators/BasePaginator.d.ts +331 -7
  105. package/dist/types/pagination/paginators/ChannelPaginator.d.ts +54 -11
  106. package/dist/types/pagination/paginators/MessageIntervalPaginator.d.ts +283 -66
  107. package/dist/types/pagination/paginators/MessagePaginator.d.ts +10 -9
  108. package/dist/types/pagination/paginators/PinnedMessagePaginator.d.ts +17 -1
  109. package/dist/types/pagination/paginators/ReminderPaginator.d.ts +8 -8
  110. package/dist/types/pagination/paginators/ThreadPaginator.d.ts +57 -0
  111. package/dist/types/pagination/paginators/index.d.ts +1 -0
  112. package/dist/types/pagination/utility.normalization.d.ts +29 -2
  113. package/dist/types/poll.d.ts +41 -14
  114. package/dist/types/poll_manager.d.ts +3 -2
  115. package/dist/types/poll_optimistic_votes.d.ts +61 -0
  116. package/dist/types/reminders/Reminder.d.ts +17 -7
  117. package/dist/types/reminders/ReminderManager.d.ts +34 -6
  118. package/dist/types/search/BaseSearchSource.d.ts +50 -25
  119. package/dist/types/search/ChannelMemberSearchSource.d.ts +11 -6
  120. package/dist/types/search/ChannelSearchSource.d.ts +27 -5
  121. package/dist/types/search/MessageSearchSource.d.ts +36 -6
  122. package/dist/types/search/SearchController.d.ts +44 -11
  123. package/dist/types/search/UserSearchSource.d.ts +11 -5
  124. package/dist/types/search/types.d.ts +14 -1
  125. package/dist/types/signing.d.ts +0 -157
  126. package/dist/types/thread.d.ts +118 -62
  127. package/dist/types/thread_manager.d.ts +124 -35
  128. package/dist/types/token_manager.d.ts +5 -8
  129. package/dist/types/types.d.ts +138 -562
  130. package/dist/types/types.utility.d.ts +8 -0
  131. package/dist/types/upload-utils.d.ts +20 -0
  132. package/dist/types/uploadManager.d.ts +50 -2
  133. package/dist/types/utils/FixedSizeQueueCache.d.ts +2 -0
  134. package/dist/types/utils/WithSubscriptions.d.ts +1 -1
  135. package/dist/types/utils/objectPath.d.ts +49 -0
  136. package/dist/types/utils/time.d.ts +85 -0
  137. package/dist/types/utils.d.ts +63 -40
  138. package/package.json +22 -33
  139. package/src/ChannelManager.ts +561 -109
  140. package/src/CooldownTimer.ts +55 -45
  141. package/src/EventHandlerPipeline.ts +13 -23
  142. package/src/LiveLocationManager.ts +191 -37
  143. package/src/api-client.ts +144 -53
  144. package/src/channel.ts +1573 -1050
  145. package/src/channel_state.ts +239 -129
  146. package/src/client.ts +843 -892
  147. package/src/client_state.ts +2 -2
  148. package/src/configuration/ConfigController.ts +298 -0
  149. package/src/configuration/InstanceConfigurationRegistry.ts +430 -0
  150. package/src/configuration/index.ts +7 -0
  151. package/src/configuration/keys.ts +86 -0
  152. package/src/configuration/shape.ts +776 -0
  153. package/src/configuration/types.ts +218 -60
  154. package/src/configuration/utils/applyInstanceConfiguration.ts +184 -0
  155. package/src/configuration/utils/copyConfigPatch.ts +61 -0
  156. package/src/configuration/utils/declarativeSlices.ts +81 -0
  157. package/src/configuration/utils/deepFreezeConfig.ts +33 -0
  158. package/src/configuration/utils/index.ts +5 -0
  159. package/src/configuration/utils/serverAuthority.ts +146 -0
  160. package/src/connection/ConnectionIdManager.ts +153 -0
  161. package/src/connection/ConnectionRecoveryManager.ts +371 -0
  162. package/src/connection/index.ts +4 -0
  163. package/src/connection/networkConnection/NetworkConnectionObserver.ts +281 -0
  164. package/src/connection/networkConnection/index.ts +3 -0
  165. package/src/connection/networkConnection/reporters.ts +85 -0
  166. package/src/connection/networkConnection/types.ts +60 -0
  167. package/src/{connection.ts → connection/wsConnection/StableWSConnection.ts} +242 -151
  168. package/src/connection/wsConnection/WSConnection.ts +345 -0
  169. package/src/connection/wsConnection/WSConnectionFallback.ts +259 -0
  170. package/src/connection/wsConnection/config.ts +108 -0
  171. package/src/connection/wsConnection/index.ts +4 -0
  172. package/src/connection/wsConnection/types.ts +101 -0
  173. package/src/constants.ts +5 -3
  174. package/src/entityStore/EntityStore.ts +350 -10
  175. package/src/entityStore/StoreBackedItemIndex.ts +66 -37
  176. package/src/entityStore/index.ts +0 -1
  177. package/src/errors.ts +40 -7
  178. package/src/formatMessageMemo.ts +23 -0
  179. package/src/gen/chat/ChannelApi.ts +230 -44
  180. package/src/gen/chat/ChatApi.ts +1047 -1745
  181. package/src/gen/models/index.ts +2378 -3721
  182. package/src/gen/models/timestamp-guard.ts +27 -0
  183. package/src/gen/moderation/ModerationApi.ts +218 -388
  184. package/src/gen-imports.ts +1 -0
  185. package/src/index.ts +82 -6
  186. package/src/languageNames.ts +103 -0
  187. package/src/logger.ts +1 -1
  188. package/src/messageComposer/CustomDataManager.ts +10 -1
  189. package/src/messageComposer/LocationComposer.ts +68 -20
  190. package/src/messageComposer/attachmentIdentity.ts +39 -0
  191. package/src/messageComposer/attachmentManager.ts +191 -68
  192. package/src/messageComposer/attachmentUtils.ts +58 -0
  193. package/src/messageComposer/configuration/commands.configuration.ts +1 -26
  194. package/src/messageComposer/configuration/configuration.ts +22 -3
  195. package/src/messageComposer/configuration/index.ts +0 -1
  196. package/src/messageComposer/configuration/types.ts +58 -1
  197. package/src/messageComposer/index.ts +1 -0
  198. package/src/messageComposer/linkPreviewsManager.ts +16 -10
  199. package/src/messageComposer/messageComposer.ts +487 -98
  200. package/src/messageComposer/middleware/attachmentManager/postUpload/AttachmentPostUploadMiddlewareExecutor.ts +1 -1
  201. package/src/messageComposer/middleware/attachmentManager/postUpload/attachmentEnrichment.ts +58 -33
  202. package/src/messageComposer/middleware/attachmentManager/postUpload/uploadErrorHandler.ts +7 -2
  203. package/src/messageComposer/middleware/attachmentManager/preUpload/blockedUploadNotification.ts +3 -2
  204. package/src/messageComposer/middleware/messageComposer/attachments.ts +98 -1
  205. package/src/messageComposer/middleware/messageComposer/linkPreviews.ts +20 -10
  206. package/src/messageComposer/middleware/messageComposer/sharedLocation.ts +7 -2
  207. package/src/messageComposer/middleware/messageComposer/types.ts +2 -7
  208. package/src/messageComposer/middleware/messageComposer/userDataInjection.ts +11 -6
  209. package/src/messageComposer/middleware/pollComposer/index.ts +1 -0
  210. package/src/messageComposer/middleware/pollComposer/state.ts +43 -11
  211. package/src/messageComposer/middleware/pollComposer/types.ts +9 -2
  212. package/src/messageComposer/middleware/pollComposer/validation.ts +76 -0
  213. package/src/messageComposer/middleware/textComposer/commandUtils.ts +3 -2
  214. package/src/messageComposer/middleware/textComposer/commands.ts +1 -2
  215. package/src/messageComposer/middleware/textComposer/mentions.ts +91 -39
  216. package/src/messageComposer/pollComposer.ts +11 -3
  217. package/src/messageComposer/textComposer.ts +36 -4
  218. package/src/messageComposer/types.ts +19 -14
  219. package/src/messageDelivery/MessageDeliveryReporter.ts +154 -53
  220. package/src/messageDelivery/MessageReceiptsTracker.ts +136 -64
  221. package/src/messageOperations/FailedSendCache.ts +90 -0
  222. package/src/messageOperations/MessageOperationStatePolicy.ts +269 -27
  223. package/src/messageOperations/MessageOperations.ts +340 -136
  224. package/src/{entityStore → messageOperations}/applyReactionLocally.ts +10 -3
  225. package/src/messageOperations/createMessageOperations.ts +192 -0
  226. package/src/messageOperations/index.ts +7 -0
  227. package/src/messageOperations/reflectReactionEvent.ts +51 -0
  228. package/src/messageOperations/sendOrdering.ts +28 -0
  229. package/src/messageOperations/settlePendingAttachmentUploads.ts +110 -0
  230. package/src/messageOperations/types.ts +74 -0
  231. package/src/middleware.ts +11 -0
  232. package/src/moderation.ts +47 -24
  233. package/src/notifications/NotificationManager.ts +73 -3
  234. package/src/notifications/configuration.ts +10 -8
  235. package/src/notifications/types.ts +58 -42
  236. package/src/offline-support/offline_support_api.ts +380 -197
  237. package/src/offline-support/offline_sync_manager.ts +105 -32
  238. package/src/offline-support/queueableOperations.ts +270 -0
  239. package/src/offline-support/types.ts +85 -39
  240. package/src/pagination/FilterBuilder.ts +1 -22
  241. package/src/pagination/cursorDerivation/createdAtAroundPaginationFlags.ts +11 -7
  242. package/src/pagination/cursorDerivation/linearPaginationFlags.ts +25 -7
  243. package/src/pagination/filterCompiler.ts +17 -0
  244. package/src/pagination/paginators/BasePaginator.ts +731 -81
  245. package/src/pagination/paginators/ChannelPaginator.ts +210 -102
  246. package/src/pagination/paginators/MessageIntervalPaginator.ts +703 -193
  247. package/src/pagination/paginators/MessagePaginator.ts +45 -36
  248. package/src/pagination/paginators/PinnedMessagePaginator.ts +74 -28
  249. package/src/pagination/paginators/ReminderPaginator.ts +15 -13
  250. package/src/pagination/paginators/ThreadPaginator.ts +181 -0
  251. package/src/pagination/paginators/UserGroupPaginator.ts +8 -1
  252. package/src/pagination/paginators/index.ts +1 -0
  253. package/src/pagination/utility.normalization.ts +37 -9
  254. package/src/poll.ts +189 -112
  255. package/src/poll_manager.ts +14 -8
  256. package/src/poll_optimistic_votes.ts +335 -0
  257. package/src/reminders/Reminder.ts +34 -16
  258. package/src/reminders/ReminderManager.ts +68 -41
  259. package/src/reminders/ReminderTimer.ts +7 -6
  260. package/src/search/BaseSearchSource.ts +133 -40
  261. package/src/search/ChannelMemberSearchSource.ts +27 -18
  262. package/src/search/ChannelSearchSource.ts +61 -7
  263. package/src/search/MessageSearchSource.ts +133 -28
  264. package/src/search/SearchController.ts +93 -16
  265. package/src/search/UserSearchSource.ts +27 -13
  266. package/src/search/types.ts +14 -1
  267. package/src/signing.ts +1 -315
  268. package/src/thread.ts +503 -511
  269. package/src/thread_manager.ts +339 -204
  270. package/src/token_manager.ts +12 -32
  271. package/src/types.ts +159 -780
  272. package/src/types.utility.ts +14 -0
  273. package/src/upload-utils.ts +53 -0
  274. package/src/uploadManager.ts +85 -7
  275. package/src/utils/FixedSizeQueueCache.ts +5 -0
  276. package/src/utils/WithSubscriptions.ts +1 -1
  277. package/src/utils/objectPath.ts +67 -0
  278. package/src/utils/time.ts +104 -0
  279. package/src/utils.ts +209 -157
  280. package/dist/types/base64.d.ts +0 -2
  281. package/dist/types/configuration/InstanceConfigurationService.d.ts +0 -26
  282. package/dist/types/connection.d.ts +0 -146
  283. package/dist/types/connection_fallback.d.ts +0 -42
  284. package/dist/types/gen/model-decoders/decoders.d.ts +0 -3
  285. package/dist/types/gen/model-decoders/event-decoder-mapping.d.ts +0 -6
  286. package/dist/types/insights.d.ts +0 -58
  287. package/dist/types/pagination/utility.queryChannel.d.ts +0 -26
  288. package/dist/types/permissions.d.ts +0 -55
  289. package/dist/types/store.d.ts +0 -125
  290. package/src/base64.ts +0 -78
  291. package/src/configuration/InstanceConfigurationService.ts +0 -73
  292. package/src/connection_fallback.ts +0 -215
  293. package/src/gen/model-decoders/decoders.ts +0 -2680
  294. package/src/gen/model-decoders/event-decoder-mapping.ts +0 -198
  295. package/src/insights.ts +0 -83
  296. package/src/pagination/utility.queryChannel.ts +0 -84
  297. package/src/permissions.ts +0 -102
  298. package/src/store.ts +0 -304
package/src/thread.ts CHANGED
@@ -1,39 +1,53 @@
1
- import { StateStore } from './store';
2
- import {
3
- computeOwnReactions,
4
- formatMessage,
5
- localMessageToNewMessagePayload,
6
- } from './utils';
7
- import { applyReactionLocally } from './entityStore';
1
+ import { StateStore } from '@stream-io/state-store';
2
+ import { formatMessage } from './utils';
8
3
  import type {
9
4
  DraftResponse,
10
- EventAPIResponse,
11
- EventType,
5
+ EventPayload,
12
6
  LocalMessage,
13
7
  MarkReadRequest,
8
+ MarkReadResponse,
14
9
  MessageResponse,
15
- ReactionRequest,
16
10
  ReadStateResponse,
17
- SendReactionRequest,
18
11
  SortParamRequest,
12
+ StreamResponse,
19
13
  ThreadStateResponse,
14
+ TimestampNS,
20
15
  UserResponse,
21
16
  } from './types';
22
- import { isEphemeral } from './errors';
23
- import type {
24
- Channel,
25
- DeleteMessageWithStateUpdateParams,
26
- SendMessageWithStateUpdateParams,
27
- UpdateMessageWithStateUpdateParams,
28
- } from './channel';
17
+ import { isDoesNotExistError } from './errors';
18
+ import type { Channel } from './channel';
19
+ import { ChannelWatchStatus } from './channel_state';
29
20
  import type { StreamChat } from './client';
30
21
  import type { CustomThreadData } from './custom_types';
31
22
  import { MessageComposer } from './messageComposer';
32
- import { MessageOperations } from './messageOperations';
23
+ import { createMessageOperations } from './messageOperations';
24
+ import type { MessageOperations } from './messageOperations';
25
+ import { nowNs } from './utils/time';
33
26
  import { WithSubscriptions } from './utils/WithSubscriptions';
34
27
  import { MessagePaginator } from './pagination';
28
+ import type { MergeNewestPageOptions, PaginatorCursor } from './pagination';
29
+ import { applyInstanceConfiguration } from './configuration/utils/applyInstanceConfiguration';
30
+ import { ConfigController } from './configuration/ConfigController';
31
+ import { deepFreezeConfig } from './configuration/utils/deepFreezeConfig';
32
+ import type { ThreadDeclarativeConfig } from './configuration/types';
33
+ import {
34
+ mergeDeclarativeMessageOperationsConfig,
35
+ mergeDeclarativePaginatorConfig,
36
+ toDeclarativePaginatorConfig,
37
+ } from './configuration/utils/declarativeSlices';
35
38
  import type { PipelineEvent } from './EventHandlerPipeline';
36
39
 
40
+ const getCursorFromReplies = (
41
+ replies: LocalMessage[],
42
+ reachesTail: boolean,
43
+ ): PaginatorCursor => {
44
+ const oldest = replies.reduce<LocalMessage | undefined>(
45
+ (acc, reply) => (!acc || reply.created_at < acc.created_at ? reply : acc),
46
+ undefined,
47
+ );
48
+ return { headward: null, tailward: reachesTail ? null : (oldest?.id ?? null) };
49
+ };
50
+
37
51
  export type ThreadState = {
38
52
  /**
39
53
  * Determines if the thread is currently opened and on-screen. When the thread is active,
@@ -41,9 +55,11 @@ export type ThreadState = {
41
55
  */
42
56
  active: boolean;
43
57
  channel: Channel;
44
- createdAt: Date;
58
+ /** Unix nanoseconds, as the API sends it. */
59
+ createdAt: TimestampNS;
45
60
  custom: CustomThreadData;
46
- deletedAt: Date | null;
61
+ /** Unix nanoseconds, as the API sends it. */
62
+ deletedAt: TimestampNS | null;
47
63
  isLoading: boolean;
48
64
  isStateStale: boolean;
49
65
  /**
@@ -55,11 +71,13 @@ export type ThreadState = {
55
71
  read: ThreadReadState;
56
72
  replyCount: number;
57
73
  title: string;
58
- updatedAt: Date | null;
74
+ /** Unix nanoseconds, as the API sends it. */
75
+ updatedAt: TimestampNS | null;
59
76
  };
60
77
 
61
78
  export type ThreadUserReadState = {
62
- lastReadAt: Date;
79
+ /** Unix nanoseconds, as the API sends it. */
80
+ lastReadAt: TimestampNS;
63
81
  unreadMessageCount: number;
64
82
  user: UserResponse;
65
83
  lastReadMessageId?: string;
@@ -68,6 +86,12 @@ export type ThreadUserReadState = {
68
86
 
69
87
  export type ThreadReadState = Record<string, ThreadUserReadState | undefined>;
70
88
 
89
+ const timestampOr = (
90
+ value: TimestampNS | undefined,
91
+ fallback: TimestampNS,
92
+ ): TimestampNS =>
93
+ typeof value === 'number' && Number.isFinite(value) ? value : fallback;
94
+
71
95
  const DEFAULT_PAGE_LIMIT = 50;
72
96
  const DEFAULT_SORT: SortParamRequest[] = [{ field: 'created_at', direction: -1 }];
73
97
  const DEFAULT_ITEM_ORDER: SortParamRequest[] = [{ field: 'created_at', direction: 1 }];
@@ -75,24 +99,36 @@ const DEFAULT_ITEM_ORDER: SortParamRequest[] = [{ field: 'created_at', direction
75
99
  export type CustomThreadMarkReadRequestFn = (params: {
76
100
  thread: Thread;
77
101
  options?: MarkReadRequest;
78
- }) => Promise<EventAPIResponse | null> | void;
102
+ }) => Promise<Partial<StreamResponse<MarkReadResponse>> | null> | void;
79
103
 
80
- export type ThreadInstanceConfig = {
104
+ export type ThreadConfig = {
81
105
  requestHandlers?: {
82
106
  markReadRequest?: CustomThreadMarkReadRequestFn;
83
107
  };
84
108
  };
85
109
 
110
+ /**
111
+ * Empty because every field of `ThreadConfig` is optional — a thread's own configuration is one handler
112
+ * wide. Declared and frozen anyway, so the entity carries the same defaults layer as every other
113
+ * configurable class rather than a special case.
114
+ */
115
+ export const DEFAULT_THREAD_CONFIG: ThreadConfig = deepFreezeConfig({});
116
+
86
117
  export class Thread extends WithSubscriptions {
87
- public readonly configState = new StateStore<ThreadInstanceConfig>({});
118
+ /** The shared configuration machinery — see {@link ConfigController}. */
119
+ private readonly configController = new ConfigController<ThreadConfig>({
120
+ defaults: DEFAULT_THREAD_CONFIG,
121
+ });
88
122
  public readonly state: StateStore<ThreadState>;
89
123
  public readonly id: string;
90
124
  public readonly messageComposer: MessageComposer;
91
- public readonly messagePaginator: MessagePaginator;
92
125
  public readonly messageOperations: MessageOperations;
126
+ public readonly messagePaginator: MessagePaginator;
93
127
 
94
128
  private client: StreamChat;
95
129
  private failedRepliesMap: Map<string, LocalMessage> = new Map();
130
+ /** How many activations (`activate()` calls) have not been released yet. */
131
+ private _activeRefCount = 0;
96
132
 
97
133
  constructor({
98
134
  client,
@@ -115,11 +151,11 @@ export class Thread extends WithSubscriptions {
115
151
  if (!threadData.parent_message) {
116
152
  throw new Error('Thread parent_message is required when threadData is provided');
117
153
  }
118
- const threadChannel = client.channel(
119
- threadData.channel.type,
120
- threadData.channel.id,
121
- { custom: threadData.channel.custom },
122
- );
154
+ const threadChannel = client.channelManager.ensure({
155
+ type: threadData.channel.type,
156
+ id: threadData.channel.id,
157
+ data: { custom: threadData.channel.custom },
158
+ });
123
159
  threadChannel._hydrateMembers({
124
160
  members: threadData.channel.members ?? [],
125
161
  overrideCurrentState: false,
@@ -132,14 +168,14 @@ export class Thread extends WithSubscriptions {
132
168
  isStateStale: false,
133
169
  // 99.9% should never change
134
170
  channel: threadChannel,
135
- createdAt: new Date(threadData.created_at),
171
+ createdAt: threadData.created_at,
136
172
  // rest
137
- deletedAt: threadData.deleted_at ? new Date(threadData.deleted_at) : null,
173
+ deletedAt: threadData.deleted_at ?? null,
138
174
  parentMessage: formatMessage(threadData.parent_message),
139
175
  participants: threadData.thread_participants,
140
176
  read: formatReadState(
141
177
  !threadData.read || threadData.read.length === 0
142
- ? getPlaceholderReadResponse(client.userID)
178
+ ? getPlaceholderReadResponse(client.userId)
143
179
  : threadData.read,
144
180
  ),
145
181
  // Use the parent message's reply_count, not the top-level threadData.reply_count. The
@@ -148,7 +184,7 @@ export class Thread extends WithSubscriptions {
148
184
  // INCLUDE them so the top level value renders fewer replies than the channel badge shows.
149
185
  // parent_message.reply_count is the authoritative, channel consistent count.
150
186
  replyCount: threadData.parent_message.reply_count ?? 0,
151
- updatedAt: threadData.updated_at ? new Date(threadData.updated_at) : null,
187
+ updatedAt: threadData.updated_at ?? null,
152
188
  title: threadData.title,
153
189
  custom: threadData.custom ?? {},
154
190
  });
@@ -166,9 +202,8 @@ export class Thread extends WithSubscriptions {
166
202
  }
167
203
 
168
204
  const formattedParentMessage = formatMessage(parentMessage);
169
- const createdAt = parentMessage.created_at
170
- ? new Date(parentMessage.created_at)
171
- : new Date();
205
+ const createdAt = timestampOr(parentMessage.created_at, nowNs());
206
+ const replyCount = parentMessage.reply_count ?? 0;
172
207
 
173
208
  this.state = new StateStore<ThreadState>({
174
209
  active: false,
@@ -177,13 +212,19 @@ export class Thread extends WithSubscriptions {
177
212
  custom: {},
178
213
  deletedAt: formattedParentMessage.deleted_at ?? null,
179
214
  isLoading: false,
180
- isStateStale: false,
215
+ // Only the parent message is known, so the thread loads its data once when opened if it may
216
+ // have any: when the parent has replies, and when its channel isn't watched, as the parent's
217
+ // `reply_count` then misses the replies sent since the channel was loaded. A parent without
218
+ // replies in a watched channel has nothing on the server yet (`getThread` would answer 404):
219
+ // its first reply arrives as an event.
220
+ isStateStale:
221
+ replyCount > 0 || channel.watchStatus !== ChannelWatchStatus.Watching,
181
222
  parentMessage: formattedParentMessage,
182
223
  participants: [],
183
- read: formatReadState(getPlaceholderReadResponse(client.userID)),
184
- replyCount: parentMessage.reply_count ?? 0,
224
+ read: formatReadState(getPlaceholderReadResponse(client.userId)),
225
+ replyCount,
185
226
  title: '',
186
- updatedAt: parentMessage.updated_at ? new Date(parentMessage.updated_at) : null,
227
+ updatedAt: parentMessage.updated_at ?? null,
187
228
  });
188
229
 
189
230
  this.id = parentMessage.id;
@@ -191,15 +232,33 @@ export class Thread extends WithSubscriptions {
191
232
 
192
233
  this.client = client;
193
234
 
194
- this.messagePaginator = new MessagePaginator({
195
- channel: this.channel,
196
- parentMessageId: this.id,
197
- requestSort: DEFAULT_SORT,
198
- itemOrder: DEFAULT_ITEM_ORDER,
199
- paginatorOptions: {
200
- pageSize: DEFAULT_PAGE_LIMIT,
235
+ // Read the declarative configuration before the sub-objects exist, so it can go in as constructor
236
+ // options — the reply paginator's `unreadReferencePolicy` and initial cursor are read once.
237
+ const declarativeConfig = client.config.getConfig('thread') ?? undefined;
238
+ // Thread replies are backed by a MessagePaginator too, so the general key applies here as well;
239
+ // the per-parent slice overrides it (thread replies default to a smaller page than a channel).
240
+ const messagePaginatorConfig = mergeDeclarativePaginatorConfig(
241
+ client.config.getConfig('messagePaginator') ?? undefined,
242
+ declarativeConfig?.messagePaginator,
243
+ );
244
+
245
+ this.messagePaginator = new MessagePaginator(
246
+ {
247
+ channel: this.channel,
248
+ parentMessageId: this.id,
249
+ requestSort: DEFAULT_SORT,
250
+ itemOrder: DEFAULT_ITEM_ORDER,
251
+ // Split as in `Channel`: the policy is a constructor argument, not paginator configuration.
252
+ unreadReferencePolicy: messagePaginatorConfig?.unreadReferencePolicy,
253
+ paginatorOptions: {
254
+ declarativeConfig: toDeclarativePaginatorConfig(messagePaginatorConfig),
255
+ },
201
256
  },
202
- });
257
+ // Thread replies default to a smaller page than a channel list. Supplied by the SDK, not by the
258
+ // integrator, so it sits at stage 1 — `client.config.set({ messagePaginator: { pageSize } })`
259
+ // overrides it, which would not be true of a construction argument.
260
+ { pageSize: DEFAULT_PAGE_LIMIT },
261
+ );
203
262
 
204
263
  // Seed the reply paginator from the thread's `latest_replies` so a thread we already hold
205
264
  // data for (queried via the ThreadManager or hydrated from a ThreadResponse) renders its
@@ -208,10 +267,13 @@ export class Thread extends WithSubscriptions {
208
267
  // tail only when it already contains every reply. Threads built from a bare parent message
209
268
  // carry no replies to seed and fall back to a paginator fetch on first open.
210
269
  if (threadData?.latest_replies?.length) {
270
+ const replies = threadData.latest_replies.map(formatMessage);
271
+ const isLastPage = replies.length === (threadData.reply_count ?? 0);
211
272
  this.messagePaginator.setItems({
212
- valueOrFactory: threadData.latest_replies.map(formatMessage),
273
+ valueOrFactory: replies,
274
+ cursor: getCursorFromReplies(replies, isLastPage),
213
275
  isFirstPage: true,
214
- isLastPage: threadData.latest_replies.length === (threadData.reply_count ?? 0),
276
+ isLastPage,
215
277
  });
216
278
  }
217
279
 
@@ -226,74 +288,68 @@ export class Thread extends WithSubscriptions {
226
288
  compositionContext: this,
227
289
  });
228
290
 
229
- this.messageOperations = new MessageOperations({
230
- ingest: (m) => {
231
- this.messagePaginator.ingestItem(m);
232
- this.channel.getClient().messageStore.flushSubscribers(m.id);
233
- },
234
- get: (id) => this.messagePaginator.getItem(id),
235
- normalizeOutgoingMessage: (m) => ({
236
- ...m,
237
- parent_id: this.id,
238
- }),
239
- handlers: () => {
240
- const { requestHandlers } = this.channel.configState.getLatestValue();
241
- const deleteMessageRequest = requestHandlers?.deleteMessageRequest;
242
- const sendMessageRequest = requestHandlers?.sendMessageRequest;
243
- const retrySendMessageRequest = requestHandlers?.retrySendMessageRequest;
244
- const updateMessageRequest = requestHandlers?.updateMessageRequest;
245
- return {
246
- delete: deleteMessageRequest
247
- ? (p) =>
248
- deleteMessageRequest({
249
- localMessage: p.localMessage,
250
- options: p.options,
251
- })
252
- : undefined,
253
- send: sendMessageRequest
254
- ? (p) =>
255
- sendMessageRequest({
256
- localMessage: p.localMessage,
257
- message: p.message,
258
- options: p.options,
259
- })
260
- : undefined,
261
- retry: retrySendMessageRequest
262
- ? (p) =>
263
- retrySendMessageRequest({
264
- localMessage: p.localMessage,
265
- message: p.message,
266
- options: p.options,
267
- })
268
- : undefined,
269
- update: updateMessageRequest
270
- ? (p) =>
271
- updateMessageRequest({
272
- localMessage: p.localMessage,
273
- options: p.options,
274
- })
275
- : undefined,
276
- };
277
- },
278
- defaults: {
279
- delete: async (id, o) => {
280
- const result = await this.channel.getClient().deleteMessage({ id, ...o });
281
- return { message: result.message };
282
- },
283
- send: async (m, o) => {
284
- const result = await this.channel.sendMessage({ message: m, ...o });
285
- return { message: result.message };
286
- },
287
- update: async (m, o) => {
288
- const result = await this.channel.getClient().updateMessage({
289
- id: m.id,
290
- message: localMessageToNewMessagePayload(m),
291
- ...o,
292
- });
293
- return { message: result.message };
294
- },
295
- },
291
+ this.messageOperations = createMessageOperations(this);
292
+
293
+ // Share one derivation path with `config.reset()`. Idempotent — the paginator was already
294
+ // configured through its constructor above; this re-applies the mutable half the way a reset does.
295
+ this.initializeConfig(declarativeConfig);
296
+ }
297
+
298
+ /**
299
+ * Derives this thread's configuration — and its reply paginator's — from the declarative slice.
300
+ *
301
+ * Called by the constructor and by `client.config.reset()`. The thread owns only its own
302
+ * `requestHandlers`; the paginator derives its own configuration.
303
+ */
304
+ initializeConfig(declarativeConfig?: ThreadDeclarativeConfig): void {
305
+ // Only the thread's own slice goes in. The paginator and the operations keys are handed to those
306
+ // objects below, so putting them here too would publish them on `thread.config` as well.
307
+ //
308
+ // Replaces rather than merges: a handler dropped from the declarative tree must disappear. The
309
+ // controller skips a write that changes nothing, which matters because `alsoWatch` re-runs this for
310
+ // any of three keys and `useThreadRequestHandlers` subscribes to the store.
311
+ this.configController.initialize({
312
+ requestHandlers: declarativeConfig?.requestHandlers,
296
313
  });
314
+
315
+ this.messagePaginator.initializeConfig(
316
+ toDeclarativePaginatorConfig(
317
+ mergeDeclarativePaginatorConfig(
318
+ this.client.config.getConfig('messagePaginator') ?? undefined,
319
+ declarativeConfig?.messagePaginator,
320
+ ),
321
+ ),
322
+ );
323
+
324
+ // A thread sends messages too, so it owns a `MessageOperations` of its own and takes the same shared
325
+ // key the channel does, with its own per-parent override.
326
+ this.messageOperations.initializeConfig(
327
+ mergeDeclarativeMessageOperationsConfig(
328
+ this.client.config.getConfig('messageOperations') ?? undefined,
329
+ declarativeConfig?.messageOperations,
330
+ ),
331
+ );
332
+ }
333
+
334
+ /**
335
+ * Resolved configuration as a store, so consumers can react to it — the shape every configurable class
336
+ * exposes.
337
+ */
338
+ get configState(): StateStore<ThreadConfig> {
339
+ return this.configController.state;
340
+ }
341
+
342
+ /**
343
+ * This thread's resolved configuration. `Readonly` because the value is the store's live object —
344
+ * assigning to a field of it would change state without notifying anyone. Use {@link updateConfig}.
345
+ */
346
+ get config(): Readonly<ThreadConfig> {
347
+ return this.configController.value;
348
+ }
349
+
350
+ /** Merges a partial configuration into the resolved config and notifies subscribers. */
351
+ updateConfig(config: Partial<ThreadConfig>): void {
352
+ this.configController.patch(config);
297
353
  }
298
354
 
299
355
  get channel() {
@@ -305,17 +361,55 @@ export class Thread extends WithSubscriptions {
305
361
  }
306
362
 
307
363
  get ownUnreadCount() {
308
- return ownUnreadCountSelector(this.client.userID)(this.state.getLatestValue());
364
+ return ownUnreadCountSelector(this.client.userId)(this.state.getLatestValue());
309
365
  }
310
366
 
311
- public activate = () => {
312
- this.state.partialNext({ active: true });
313
- };
367
+ /**
368
+ * Declares that a consumer is displaying this thread, and returns the function that ends it, as
369
+ * `channel.activate()` does. Refcounted, as one `Thread` can be held by several consumers at once,
370
+ * so it stays active until the last one releases. Each call gets its own release, and calling a
371
+ * release again does nothing, so a consumer can't end another one's activation.
372
+ *
373
+ * `active` is also what {@link ConnectionRecoveryManager} filters on to decide which threads to
374
+ * reload on reconnect, so an activation that is never released costs more than a missed auto-read.
375
+ *
376
+ * The first activation also keeps the thread in `client.threads` for the rest of the session:
377
+ * it stays subscribed and resolvable through `client.threads.get(id)` after it is released,
378
+ * whether or not the thread list holds it. Reopening it therefore needs no fetch unless it went stale.
379
+ */
380
+ public activate = (): (() => void) => {
381
+ this._activeRefCount += 1;
382
+ if (this._activeRefCount === 1) {
383
+ this.client.threads.register(this);
384
+ this.state.partialNext({ active: true });
385
+ }
314
386
 
315
- public deactivate = () => {
316
- this.state.partialNext({ active: false });
387
+ let released = false;
388
+ return () => {
389
+ if (released) return;
390
+ released = true;
391
+ this._activeRefCount -= 1;
392
+ if (this._activeRefCount === 0) {
393
+ this.state.partialNext({ active: false });
394
+ }
395
+ };
317
396
  };
318
397
 
398
+ /**
399
+ * Re-queries this thread's replies, sized to the loaded window, and reconciles them in place — the
400
+ * thread analogue of {@link Channel.reload}, and what connection recovery calls for every active
401
+ * thread.
402
+ *
403
+ * Preserves failed (unsent) replies. They are read out of the reply paginator rather than out of
404
+ * `failedRepliesMap`, because that map is only written by `upsertReplyLocally`, whose callers are
405
+ * this thread's own subscriptions and the offline-DB path resolved through `client.threads.get` —
406
+ * neither of which covers a thread that was never activated or listed. Reading the paginator
407
+ * is true for registered and unregistered threads alike. An overlap merge keeps them anyway (the
408
+ * reconcile's provenance guard never prunes a non-server message); only a disjoint rebuild can drop
409
+ * them, so any that actually fell out are re-ingested below.
410
+ *
411
+ * Rethrows, except for a not-found answer on a thread that never had replies (see the catch).
412
+ */
319
413
  public reload = async () => {
320
414
  if (this.state.getLatestValue().isLoading) {
321
415
  return;
@@ -324,18 +418,57 @@ export class Thread extends WithSubscriptions {
324
418
  this.state.partialNext({ isLoading: true });
325
419
 
326
420
  try {
327
- const loadedReplyCount = this.messagePaginator.items?.length ?? 0;
421
+ const loadedReplies = this.messagePaginator.items ?? [];
422
+ const loadedReplyCount = loadedReplies.length;
423
+ const requestedReplyLimit =
424
+ Math.max(loadedReplyCount, this.messagePaginator.pageSize ?? 0) || undefined;
425
+ const reconcileCandidateIds = new Set(loadedReplies.map((reply) => reply.id));
426
+ const failedBefore = loadedReplies.filter((reply) => reply.status === 'failed');
328
427
  const thread = await this.client.getThreadAndHydrate(this.id, {
329
428
  watch: true,
330
- reply_limit: loadedReplyCount || this.messagePaginator.pageSize,
429
+ reply_limit: requestedReplyLimit,
331
430
  });
332
- this.hydrateState(thread);
431
+ this.hydrateState(thread, {
432
+ reconcile: {
433
+ requestedLimit: requestedReplyLimit,
434
+ candidateIds: reconcileCandidateIds,
435
+ },
436
+ });
437
+
438
+ if (failedBefore.length) {
439
+ // Membership is checked against the visible window, NOT `getItem`: that reads the item
440
+ // index, which can still hold a message the rebuild dropped from the loaded window — so an
441
+ // index-based guard skips the re-ingest on exactly the path that needs it.
442
+ const visible = new Set((this.messagePaginator.items ?? []).map((r) => r.id));
443
+ this.messagePaginator.batch(
444
+ () => {
445
+ for (const failed of failedBefore) {
446
+ if (!visible.has(failed.id)) this.messagePaginator.ingestItem(failed);
447
+ }
448
+ },
449
+ { coalesce: true },
450
+ );
451
+ }
452
+ } catch (error) {
453
+ const notFound =
454
+ isDoesNotExistError(error as Error) ||
455
+ (error as { status?: number })?.status === 404;
456
+ const neverExisted = notFound && this.state.getLatestValue().replyCount === 0;
457
+ // Do not throw an error if we haven't created the thread yet, the tiebreaker
458
+ // being whether the parent message has any replies or not. A thread with all hard
459
+ // deleted replies will simply not throw.
460
+ if (neverExisted) return;
461
+
462
+ throw error;
333
463
  } finally {
334
464
  this.state.partialNext({ isLoading: false });
335
465
  }
336
466
  };
337
467
 
338
- public hydrateState = (thread: Thread) => {
468
+ public hydrateState = (
469
+ thread: Thread,
470
+ options?: { reconcile?: MergeNewestPageOptions },
471
+ ) => {
339
472
  if (thread === this) {
340
473
  // skip if the instances are the same
341
474
  return;
@@ -381,9 +514,25 @@ export class Thread extends WithSubscriptions {
381
514
  this.client.messageStore.upsert(parentMessage);
382
515
  }
383
516
 
384
- this.messagePaginator.mergeNewestPage(
385
- thread.messagePaginator.state.getLatestValue().items ?? [],
386
- );
517
+ const incomingReplies = thread.messagePaginator.state.getLatestValue().items ?? [];
518
+
519
+ if (!options?.reconcile) this.messagePaginator.clearStateAndCache();
520
+ if (typeof this.messagePaginator.items === 'undefined') {
521
+ // Nothing loaded yet — the common case for a thread opened from a message, whose paginator
522
+ // has never held a window. `mergeNewestPage` deliberately no-ops there (it merges into an
523
+ // anchored head and leaves seeding to the query path), so hydrating through it would drop the
524
+ // replies this request just fetched and leave the panel empty until something else queried
525
+ // them. Seed instead, exactly as the constructor does for a thread response's `latest_replies`.
526
+ const isLastPage = incomingReplies.length === replyCount;
527
+ this.messagePaginator.setItems({
528
+ valueOrFactory: incomingReplies,
529
+ cursor: getCursorFromReplies(incomingReplies, isLastPage),
530
+ isFirstPage: true,
531
+ isLastPage,
532
+ });
533
+ } else {
534
+ this.messagePaginator.mergeNewestPage(incomingReplies, options?.reconcile);
535
+ }
387
536
  pendingReplies.forEach((reply) => this.messagePaginator.ingestItem(reply));
388
537
  // Carry the re-queried thread's last-activity floor so lastMessageAt stays fresh even when the
389
538
  // merged page does not include the newest reply. Monotonic, so an older value is a no-op.
@@ -396,40 +545,70 @@ export class Thread extends WithSubscriptions {
396
545
  return;
397
546
  }
398
547
 
548
+ this.addUnsubscribeFunction(this.subscribeThreadSetupStateChange());
399
549
  this.addUnsubscribeFunction(this.subscribeParentMessageFromStore());
400
- this.addUnsubscribeFunction(this.subscribeThreadUpdated());
401
550
  this.addUnsubscribeFunction(this.subscribeMarkActiveThreadRead());
402
551
  this.addUnsubscribeFunction(this.subscribeReloadActiveStaleThread());
403
- this.addUnsubscribeFunction(this.subscribeMarkThreadStale());
404
- this.addUnsubscribeFunction(this.subscribeNewReplies());
405
- this.addUnsubscribeFunction(this.subscribeRepliesRead());
406
- this.addUnsubscribeFunction(this.subscribeRepliesUnread());
407
- this.addUnsubscribeFunction(this.subscribeMessageDeleted());
408
- this.addUnsubscribeFunction(this.subscribeMessageUpdated());
409
- this.addUnsubscribeFunction(this.subscribeUserMessagesDeleted());
552
+ this.addUnsubscribeFunction(this.subscribeMarkStaleOnStopWatching());
410
553
  };
411
554
 
412
- private subscribeThreadUpdated = () =>
413
- this.client.on('thread.updated', (event) => {
414
- if (!event.thread || event.thread.parent_message_id !== this.id) {
415
- return;
416
- }
555
+ /**
556
+ * Subscribes this thread to the `'thread'` configuration key. Registered through
557
+ * `WithSubscriptions`, so `unregisterSubscriptions()` runs the setup function's teardown.
558
+ *
559
+ * **This is where `Thread` differs from `Channel`,** which subscribes from its constructor. Everything
560
+ * below follows from that, and applies to a thread that never calls `registerSubscriptions()`:
561
+ *
562
+ * - no *setup function* runs for it — matching how `MessageComposer` already behaves;
563
+ * - it sees the declarative slice **as it stood when the thread was constructed**, because the
564
+ * constructor applies it directly, but no *later* `client.config.set({ thread: … })` or
565
+ * `set({ messagePaginator: … })` reaches it;
566
+ * - it is absent from the registry's `liveInstances`, so `client.config.reset()` skips it, and
567
+ * `hasLiveInstances('thread')` does not count it when deciding whether to warn about a
568
+ * construction-only path registered too late.
569
+ *
570
+ * So read "declarative configuration is unaffected" as *at construction only*. A thread registered
571
+ * with a `ThreadManager` that has itself registered is covered — the manager calls
572
+ * `registerSubscriptions()` on every thread the list holds or that is active — so the common path
573
+ * is fine. A thread that is neither, or held by an unregistered manager, is not.
574
+ *
575
+ * The alternative — applying the setup function at construction — would break the teardown symmetry
576
+ * `WithSubscriptions` provides, which is why the asymmetry stands.
577
+ */
578
+ private subscribeThreadSetupStateChange = () =>
579
+ applyInstanceConfiguration({
580
+ args: { thread: this },
581
+ config: this.client.config,
582
+ key: 'thread',
583
+ applyConfig: (config) => this.initializeConfig(config),
584
+ // Read fresh: by the time reset calls this, the declarative store has been cleared.
585
+ reinitializeConfig: () =>
586
+ this.initializeConfig(this.client.config.getConfig('thread') ?? undefined),
587
+ // The reply paginator also derives from the shared `messagePaginator` key — run the full cycle
588
+ // on a change there, so the setup function's overrides survive.
589
+ alsoWatch: ['messagePaginator', 'messageOperations'],
590
+ });
417
591
 
418
- const threadData = event.thread;
592
+ public handleThreadUpdated = (event: EventPayload<'thread.updated'>) => {
593
+ if (!event.thread || event.thread.parent_message_id !== this.id) {
594
+ return;
595
+ }
419
596
 
420
- this.state.partialNext({
421
- title: threadData.title,
422
- updatedAt: new Date(threadData.updated_at),
423
- deletedAt: threadData.deleted_at ? new Date(threadData.deleted_at) : null,
424
- custom: threadData.custom ?? {},
425
- });
426
- }).unsubscribe;
597
+ const threadData = event.thread;
598
+
599
+ this.state.partialNext({
600
+ title: threadData.title,
601
+ updatedAt: threadData.updated_at,
602
+ deletedAt: threadData.deleted_at ?? null,
603
+ custom: threadData.custom ?? {},
604
+ });
605
+ };
427
606
 
428
607
  private subscribeMarkActiveThreadRead = () =>
429
608
  this.state.subscribeWithSelector(
430
609
  (nextValue) => ({
431
610
  active: nextValue.active,
432
- unreadMessageCount: ownUnreadCountSelector(this.client.userID)(nextValue),
611
+ unreadMessageCount: ownUnreadCountSelector(this.client.userId)(nextValue),
433
612
  }),
434
613
  ({ active, unreadMessageCount }) => {
435
614
  if (!active || !unreadMessageCount) return;
@@ -447,246 +626,188 @@ export class Thread extends WithSubscriptions {
447
626
  },
448
627
  );
449
628
 
450
- private subscribeMarkThreadStale = () =>
451
- this.client.on('user.watching.stop', (event: PipelineEvent) => {
452
- const { channel } = this.state.getLatestValue();
453
-
454
- if (
455
- !this.client.userID ||
456
- this.client.userID !== event.user?.id ||
457
- event.channel?.cid !== channel.cid
458
- ) {
459
- return;
460
- }
461
-
462
- this.state.partialNext({ isStateStale: true });
463
- }).unsubscribe;
629
+ /**
630
+ * A watch stopped while the connection stays up (`NotWatching`) ends the channel's events with no
631
+ * reconnect to catch it. A dropped connection (`WasWatching`) is left to recovery.
632
+ */
633
+ private subscribeMarkStaleOnStopWatching = () =>
634
+ this.channel.state.subscribeWithSelector(
635
+ ({ watchStatus }) => ({ watchStatus }),
636
+ ({ watchStatus }, previous) => {
637
+ if (
638
+ previous?.watchStatus === ChannelWatchStatus.Watching &&
639
+ watchStatus === ChannelWatchStatus.NotWatching
640
+ ) {
641
+ this.state.partialNext({ isStateStale: true });
642
+ }
643
+ },
644
+ );
464
645
 
465
- private subscribeRepliesUnread = () =>
466
- this.client.on('notification.mark_unread', (event) => {
467
- if (!event.user || !event.created_at || !event.thread_id) return;
468
- if (event.thread_id !== this.id) return;
646
+ public handleRepliesUnread = (event: EventPayload<'notification.mark_unread'>) => {
647
+ if (!event.user || event.created_at == null || !event.thread_id) return;
648
+ if (event.thread_id !== this.id) return;
649
+
650
+ const userId = event.user.id;
651
+ const createdAt = event.created_at;
652
+ const user = event.user;
653
+
654
+ this.state.next((current) => ({
655
+ ...current,
656
+ read: {
657
+ ...current.read,
658
+ [userId]: {
659
+ ...current.read[userId],
660
+ lastReadAt: timestampOr(event.last_read_at, createdAt),
661
+ user,
662
+ firstUnreadMessageId: event.first_unread_message_id,
663
+ unreadMessageCount: event.unread_messages ?? 0,
664
+ },
665
+ },
666
+ }));
667
+ };
469
668
 
470
- const userId = event.user.id;
471
- const createdAt = event.created_at;
472
- const user = event.user;
669
+ public handleNewReply = (event: EventPayload<'message.new'>) => {
670
+ if (!this.client.userId || event.message?.parent_id !== this.id) {
671
+ return;
672
+ }
473
673
 
474
- this.state.next((current) => ({
475
- ...current,
476
- read: {
477
- ...current.read,
478
- [userId]: {
479
- ...current.read[userId],
480
- lastReadAt:
481
- typeof event.last_read_at !== 'undefined'
482
- ? new Date(event.last_read_at)
483
- : new Date(createdAt),
484
- user,
485
- firstUnreadMessageId: event.first_unread_message_id,
486
- unreadMessageCount: event.unread_messages ?? 0,
487
- },
488
- },
489
- }));
490
- }).unsubscribe;
674
+ const isOwnMessage = event.message.user?.id === this.client.userId;
675
+ const { active, read } = this.state.getLatestValue();
491
676
 
492
- private subscribeNewReplies = () =>
493
- this.client.on('message.new', (event) => {
494
- if (!this.client.userID || event.message?.parent_id !== this.id) {
495
- return;
496
- }
677
+ this.upsertReplyLocally({
678
+ message: event.message,
679
+ // MessageRequest from current user could have been added optimistically,
680
+ // so the actual timestamp might differ in the event
681
+ timestampChanged: isOwnMessage,
682
+ });
497
683
 
498
- const isOwnMessage = event.message.user?.id === this.client.userID;
499
- const { active, read } = this.state.getLatestValue();
684
+ if (active) {
685
+ this.throttledMarkRead();
686
+ }
500
687
 
501
- this.upsertReplyLocally({
502
- message: event.message,
503
- // MessageRequest from current user could have been added optimistically,
504
- // so the actual timestamp might differ in the event
505
- timestampChanged: isOwnMessage,
506
- });
688
+ const nextRead: ThreadReadState = {};
507
689
 
508
- if (active) {
509
- this.throttledMarkRead();
510
- }
690
+ for (const userId of Object.keys(read)) {
691
+ const userRead = read[userId];
511
692
 
512
- const nextRead: ThreadReadState = {};
513
-
514
- for (const userId of Object.keys(read)) {
515
- const userRead = read[userId];
516
-
517
- if (userRead) {
518
- let nextUserRead: ThreadUserReadState = userRead;
519
-
520
- if (userId === event.user?.id) {
521
- // The user who just sent a message to the thread has no unread messages
522
- // in that thread
523
- nextUserRead = {
524
- ...nextUserRead,
525
- lastReadAt: event.created_at ? new Date(event.created_at) : new Date(),
526
- user: event.user,
527
- unreadMessageCount: 0,
528
- };
529
- } else if (active && userId === this.client.userID) {
530
- // Do not increment unread count for the current user in an active thread
531
- } else {
532
- // Increment unread count for all users except the author of the new message
533
- nextUserRead = {
534
- ...nextUserRead,
535
- unreadMessageCount: userRead.unreadMessageCount + 1,
536
- };
537
- }
693
+ if (userRead) {
694
+ let nextUserRead: ThreadUserReadState = userRead;
538
695
 
539
- nextRead[userId] = nextUserRead;
696
+ if (userId === event.user?.id) {
697
+ // The user who just sent a message to the thread has no unread messages
698
+ // in that thread
699
+ nextUserRead = {
700
+ ...nextUserRead,
701
+ lastReadAt: timestampOr(event.created_at, nowNs()),
702
+ user: event.user,
703
+ unreadMessageCount: 0,
704
+ };
705
+ } else if (active && userId === this.client.userId) {
706
+ // Do not increment unread count for the current user in an active thread
707
+ } else {
708
+ // Increment unread count for all users except the author of the new message
709
+ nextUserRead = {
710
+ ...nextUserRead,
711
+ unreadMessageCount: userRead.unreadMessageCount + 1,
712
+ };
540
713
  }
541
- }
542
-
543
- this.state.partialNext({ read: nextRead });
544
- }).unsubscribe;
545
714
 
546
- private subscribeRepliesRead = () =>
547
- this.client.on('message.read', (event) => {
548
- if (!event.user || !event.created_at || !event.thread) return;
549
- if (event.thread.parent_message_id !== this.id) return;
715
+ nextRead[userId] = nextUserRead;
716
+ }
717
+ }
550
718
 
551
- const userId = event.user.id;
552
- const createdAt = event.created_at;
553
- const user = event.user;
719
+ this.state.partialNext({ read: nextRead });
720
+ };
554
721
 
555
- this.state.next((current) => ({
556
- ...current,
557
- read: {
558
- ...current.read,
559
- [userId]: {
560
- lastReadAt: new Date(createdAt),
561
- user,
562
- lastReadMessageId: event.last_read_message_id,
563
- unreadMessageCount: 0,
564
- },
722
+ public handleRepliesRead = (event: EventPayload<'message.read'>) => {
723
+ if (!event.user || event.created_at == null || !event.thread) return;
724
+ if (event.thread.parent_message_id !== this.id) return;
725
+
726
+ const userId = event.user.id;
727
+ const createdAt = event.created_at;
728
+ const user = event.user;
729
+
730
+ this.state.next((current) => ({
731
+ ...current,
732
+ read: {
733
+ ...current.read,
734
+ [userId]: {
735
+ lastReadAt: createdAt,
736
+ user,
737
+ lastReadMessageId: event.last_read_message_id,
738
+ unreadMessageCount: 0,
565
739
  },
566
- }));
567
- }).unsubscribe;
568
-
569
- private subscribeMessageDeleted = () =>
570
- this.client.on('message.deleted', (event) => {
571
- if (!event.message) return;
572
- const formattedMessage = formatMessage(event.message);
740
+ },
741
+ }));
742
+ };
573
743
 
574
- // Deleted message is a reply of this thread
575
- if (event.message.parent_id === this.id) {
576
- if (event.hard_delete) {
577
- this.deleteReplyLocally({ message: event.message });
578
- } else {
579
- // Handle soft delete (updates deleted_at timestamp)
580
- this.upsertReplyLocally({ message: event.message });
581
- }
744
+ public handleMessageDeleted = (event: EventPayload<'message.deleted'>) => {
745
+ if (!event.message) return;
746
+ const formattedMessage = formatMessage(event.message);
747
+
748
+ // Deleted message is a reply of this thread
749
+ if (event.message.parent_id === this.id) {
750
+ if (event.hard_delete) {
751
+ this.deleteReplyLocally({ message: event.message });
752
+ } else {
753
+ // Handle soft delete (updates deleted_at timestamp)
754
+ this.upsertReplyLocally({ message: event.message });
582
755
  }
756
+ }
583
757
 
584
- // Deleted message is parent message of this thread
585
- if (event.message.id === this.id) {
586
- this.updateParentMessageLocally({ message: event.message });
587
- }
758
+ // Deleted message is parent message of this thread
759
+ if (event.message.id === this.id) {
760
+ this.updateParentMessageLocally({ message: event.message });
761
+ }
588
762
 
589
- this.messagePaginator.reflectQuotedMessageUpdate(formattedMessage);
590
- }).unsubscribe;
591
-
592
- private subscribeMessageUpdated = () => {
593
- const messageUpdateTypes: EventType[] = ['message.updated', 'message.undeleted'];
594
- const reactionTypes: EventType[] = [
595
- 'reaction.new',
596
- 'reaction.deleted',
597
- 'reaction.updated',
598
- ];
599
-
600
- const unsubscribeMessageUpdated = messageUpdateTypes.map(
601
- (eventType) =>
602
- this.client.on(eventType, (event: PipelineEvent) => {
603
- if (!event.message) return;
604
- // A `message.updated` WS event carries `own_reactions: []`; upserting it verbatim would
605
- // wipe the current user's reactions on an edit. Preserve them off the copy we already hold
606
- // — the reply paginator for a reply, `state.parentMessage` for the parent (the parent is
607
- // not held in any paginator, so it needs the same treatment directly).
608
- const message =
609
- event.message.parent_id === this.id
610
- ? {
611
- ...event.message,
612
- own_reactions:
613
- this.messagePaginator.getItem(event.message.id)?.own_reactions ??
614
- event.message.own_reactions,
615
- }
616
- : !event.message.parent_id && event.message.id === this.id
617
- ? {
618
- ...event.message,
619
- own_reactions:
620
- this.state.getLatestValue().parentMessage?.own_reactions ??
621
- event.message.own_reactions,
622
- }
623
- : event.message;
624
- this.updateParentMessageOrReplyLocally(message);
625
- this.messagePaginator.reflectQuotedMessageUpdate(formatMessage(event.message));
626
- }).unsubscribe,
627
- );
763
+ this.messagePaginator.reflectQuotedMessageUpdate(formattedMessage);
764
+ };
628
765
 
629
- const unsubscribeReactions = reactionTypes.map(
630
- (eventType) =>
631
- this.client.on(eventType, (event: PipelineEvent) => {
632
- if (!event.message || !event.reaction) return;
633
- const { message, reaction } = event;
634
- if (message.parent_id === this.id) {
635
- // Preserve/apply the current user's `own_reactions` off the reply paginator itself,
636
- // independently of the channel (mirrors the channel's main-list reflectReaction).
637
- this.messagePaginator.reflectReaction({
638
- enforceUnique: eventType === 'reaction.updated',
639
- message,
640
- reaction,
641
- removed: eventType === 'reaction.deleted',
642
- });
643
- } else if (!message.parent_id && message.id === this.id) {
644
- // Reaction on the PARENT. The parent isn't in a paginator, so apply the current user's
645
- // own_reactions delta here (mirroring the reply path's reflectReaction) rather than
646
- // copying the WS event verbatim — which would drop own_reactions the event omits.
647
- const own_reactions = computeOwnReactions({
648
- current:
649
- this.state.getLatestValue().parentMessage?.own_reactions ??
650
- message.own_reactions ??
651
- [],
652
- enforceUnique: eventType === 'reaction.updated',
653
- reaction,
654
- removed: eventType === 'reaction.deleted',
655
- userId: this.client.userID,
656
- });
657
- this.updateParentMessageLocally({ message: { ...message, own_reactions } });
766
+ public handleMessageUpdated = (event: PipelineEvent) => {
767
+ if (!event.message) return;
768
+ // A `message.updated` WS event carries `own_reactions: []`; upserting it verbatim would
769
+ // wipe the current user's reactions on an edit. Preserve them off the copy we already hold
770
+ // — the reply paginator for a reply, `state.parentMessage` for the parent (the parent is
771
+ // not held in any paginator, so it needs the same treatment directly).
772
+ const message =
773
+ event.message.parent_id === this.id
774
+ ? {
775
+ ...event.message,
776
+ own_reactions:
777
+ this.messagePaginator.getItem(event.message.id)?.own_reactions ??
778
+ event.message.own_reactions,
658
779
  }
659
- this.messagePaginator.reflectQuotedMessageUpdate(formatMessage(message));
660
- }).unsubscribe,
661
- );
662
-
663
- const unsubscribeFunctions = [...unsubscribeMessageUpdated, ...unsubscribeReactions];
664
-
665
- return () => unsubscribeFunctions.forEach((unsubscribe) => unsubscribe());
780
+ : !event.message.parent_id && event.message.id === this.id
781
+ ? {
782
+ ...event.message,
783
+ own_reactions:
784
+ this.state.getLatestValue().parentMessage?.own_reactions ??
785
+ event.message.own_reactions,
786
+ }
787
+ : event.message;
788
+ this.updateParentMessageOrReplyLocally(message);
789
+ this.messagePaginator.reflectQuotedMessageUpdate(formatMessage(event.message));
666
790
  };
667
791
 
668
- private subscribeUserMessagesDeleted = () => {
669
- // Apply a user ban / deletion to this thread's own reply list. Previously
670
- // channel.state.deleteUserMessages marked banned-user replies deleted in the (now removed)
671
- // channel.state.threads shadow; the reply paginator is the thread's source of truth now.
672
- const eventTypes: EventType[] = ['user.messages.deleted', 'user.deleted'];
673
-
674
- const unsubscribeFunctions = eventTypes.map(
675
- (eventType) =>
676
- this.client.on(eventType, (event: PipelineEvent) => {
677
- if (!event.user) return;
678
- // user.deleted carries the deletion time on the user; user.messages.deleted on the event.
679
- const deletedAtSource =
680
- eventType === 'user.deleted' ? event.user.deleted_at : event.created_at;
681
- this.messagePaginator.applyMessageDeletionForUser({
682
- userId: event.user.id,
683
- hardDelete: !!event.hard_delete,
684
- deletedAt: deletedAtSource ? new Date(deletedAtSource) : new Date(),
685
- });
686
- }).unsubscribe,
687
- );
792
+ public handleReactionChanged = (event: PipelineEvent) => {
793
+ if (!event.message || !event.reaction) return;
794
+ const { message } = event;
795
+ this.messagePaginator.reflectQuotedMessageUpdate(formatMessage(message));
796
+ };
688
797
 
689
- return () => unsubscribeFunctions.forEach((unsubscribe) => unsubscribe());
798
+ // Apply a user ban / deletion to this thread's own reply list. Previously
799
+ // channel.state.deleteUserMessages marked banned-user replies deleted in the (now removed)
800
+ // channel.state.threads shadow; the reply paginator is the thread's source of truth now.
801
+ public handleUserMessagesDeleted = (event: PipelineEvent) => {
802
+ if (!event.user) return;
803
+ // user.deleted carries the deletion time on the user; user.messages.deleted on the event.
804
+ const deletedAtSource =
805
+ event.type === 'user.deleted' ? event.user.deleted_at : event.created_at;
806
+ this.messagePaginator.applyMessageDeletionForUser({
807
+ userId: event.user.id,
808
+ hardDelete: !!event.hard_delete,
809
+ deletedAt: deletedAtSource ?? nowNs(),
810
+ });
690
811
  };
691
812
 
692
813
  // The parent message lives in the client-global message store (one canonical POJO per id);
@@ -756,6 +877,13 @@ export class Thread extends WithSubscriptions {
756
877
  this.failedRepliesMap.delete(message.id);
757
878
  }
758
879
 
880
+ // Already showing this exact snapshot because a holder sharing the store wrote it first and the
881
+ // fanout reprojected us. Ingesting would re-emit an identical window for nothing.
882
+ // TODO: This can probably be generalized as a safeguard up in ingestItem or maybe even EntityStore
883
+ // (so if a collection exists that holds this referential entity already, just use that or maybe
884
+ // even skip ingestion sometimes when it makes sense). But leaving that for a separate change.
885
+ if (this.messagePaginator.getItem(formattedMessage.id) === formattedMessage) return;
886
+
759
887
  // The reply messagePaginator is the reply list source.
760
888
  this.messagePaginator.ingestItem(formattedMessage);
761
889
  };
@@ -785,142 +913,6 @@ export class Thread extends WithSubscriptions {
785
913
  }
786
914
  };
787
915
 
788
- /**
789
- * Sends a message with optimistic local state update.
790
- */
791
- async sendMessageWithLocalUpdate({
792
- localMessage,
793
- message,
794
- options,
795
- sendMessageRequestFn,
796
- }: SendMessageWithStateUpdateParams): Promise<void> {
797
- await this.messageOperations.send(
798
- {
799
- localMessage,
800
- message,
801
- options,
802
- },
803
- sendMessageRequestFn,
804
- );
805
- }
806
-
807
- /**
808
- * Retry sending a failed message.
809
- */
810
- async retrySendMessageWithLocalUpdate(
811
- params: Omit<SendMessageWithStateUpdateParams, 'message'>,
812
- ) {
813
- await this.messageOperations.retry(
814
- {
815
- localMessage: { ...params.localMessage, type: 'regular' },
816
- options: params.options,
817
- },
818
- params.sendMessageRequestFn,
819
- );
820
- }
821
-
822
- /**
823
- * Updates a message with optimistic local state update.
824
- *
825
- * The update flows through `messagePaginator`, which is the sole reply source.
826
- */
827
- async updateMessageWithLocalUpdate(params: UpdateMessageWithStateUpdateParams) {
828
- await this.messageOperations.update(
829
- {
830
- localMessage: params.localMessage,
831
- options: params.options,
832
- },
833
- params.updateMessageRequestFn,
834
- );
835
- }
836
-
837
- /**
838
- * Deletes a message with local state update.
839
- */
840
- async deleteMessageWithLocalUpdate(params: DeleteMessageWithStateUpdateParams) {
841
- await this.messageOperations.delete(
842
- {
843
- localMessage: params.localMessage,
844
- options: params.options,
845
- },
846
- params.deleteMessageRequestFn,
847
- );
848
- }
849
-
850
- /**
851
- * Adds a reaction to a reply with an optimistic local state update, mirroring
852
- * {@link Channel.addReactionWithLocalUpdate}. The optimistic message is applied to THIS thread's
853
- * paginator (so pure replies get optimism the channel paginator can't give); the request routes
854
- * through the parent channel since reactions are channel-level.
855
- */
856
- async addReactionWithLocalUpdate({
857
- messageId,
858
- reaction,
859
- options,
860
- }: {
861
- messageId: string;
862
- reaction: ReactionRequest;
863
- options?: Pick<SendReactionRequest, 'enforce_unique' | 'skip_push'>;
864
- }) {
865
- const client = this.channel.getClient();
866
- const undo = applyReactionLocally(client, {
867
- enforceUnique: options?.enforce_unique ?? false,
868
- messageId,
869
- reaction,
870
- });
871
-
872
- try {
873
- const response = await this.channel.sendReaction({
874
- id: messageId,
875
- reaction,
876
- ...options,
877
- });
878
- // reconcile the server copy only if we still hold it — a bare upsert of an unheld id would
879
- // orphan it (the store's refcount GC only reclaims held ids).
880
- if (response?.message && client.messageStore.has(response.message.id)) {
881
- client.messageStore.upsert(formatMessage(response.message));
882
- }
883
- } catch (error) {
884
- if (undo && (!client.offlineDb || !isEphemeral(error as Error))) {
885
- undo();
886
- }
887
- throw error;
888
- }
889
- }
890
-
891
- /**
892
- * Removes the current user's reaction from a reply with an optimistic local state update,
893
- * mirroring {@link Thread.addReactionWithLocalUpdate}.
894
- */
895
- async deleteReactionWithLocalUpdate({
896
- messageId,
897
- type,
898
- }: {
899
- messageId: string;
900
- type: string;
901
- }) {
902
- const client = this.channel.getClient();
903
- const undo = applyReactionLocally(client, {
904
- messageId,
905
- reaction: { type },
906
- removed: true,
907
- });
908
-
909
- try {
910
- const response = await this.channel.deleteReaction({ id: messageId, type });
911
- // reconcile the server copy only if we still hold it — a bare upsert of an unheld id would
912
- // orphan it (the store's refcount GC only reclaims held ids).
913
- if (response?.message && client.messageStore.has(response.message.id)) {
914
- client.messageStore.upsert(formatMessage(response.message));
915
- }
916
- } catch (error) {
917
- if (undo && (!client.offlineDb || !isEphemeral(error as Error))) {
918
- undo();
919
- }
920
- throw error;
921
- }
922
- }
923
-
924
916
  public markRead = async ({ force = false }: { force?: boolean } = {}) => {
925
917
  if (this.ownUnreadCount === 0 && !force) {
926
918
  return null;
@@ -951,7 +943,7 @@ const normalizeThreadParticipants = (
951
943
  ): ThreadStateResponse['thread_participants'] | undefined => {
952
944
  if (!participants) return undefined;
953
945
 
954
- const now = new Date();
946
+ const now = nowNs();
955
947
 
956
948
  return participants.map(
957
949
  (participant: MessageThreadParticipant) =>
@@ -971,7 +963,7 @@ const formatReadState = (read: ReadStateResponse[]): ThreadReadState =>
971
963
  user: userRead.user,
972
964
  lastReadMessageId: userRead.last_read_message_id,
973
965
  unreadMessageCount: userRead.unread_messages ?? 0,
974
- lastReadAt: new Date(userRead.last_read),
966
+ lastReadAt: userRead.last_read,
975
967
  };
976
968
  return state;
977
969
  }, {});
@@ -982,7 +974,7 @@ const getPlaceholderReadResponse = (currentUserId?: string): ReadStateResponse[]
982
974
  {
983
975
  user: { id: currentUserId } as UserResponse,
984
976
  unread_messages: 0,
985
- last_read: new Date(),
977
+ last_read: nowNs(),
986
978
  },
987
979
  ]
988
980
  : [];