@cometchat/chat-uikit-react-native 5.3.8 → 5.3.10

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 (45) hide show
  1. package/package.json +1 -1
  2. package/src/CometChatAIAssistantChatHistory/CometChatAIAssistantChatHistory.tsx +6 -3
  3. package/src/CometChatConversations/CometChatConversations.tsx +9 -0
  4. package/src/CometChatMessageList/CometChatMessageList.tsx +84 -5
  5. package/src/CometChatMessageList/PERFORMANCE_ARCHITECTURE.md +478 -0
  6. package/src/CometChatMessageList/SEARCH_NAV_PERF_PLAN.md +613 -0
  7. package/src/CometChatMessageList/components/MessageOptionsSheet.tsx +12 -4
  8. package/src/CometChatSearch/CometChatSearch.tsx +16 -0
  9. package/src/shared/CometChatUiKit/CometChatUIKit.changes.md +76 -0
  10. package/src/shared/CometChatUiKit/checkAuthSettings-review.md +211 -0
  11. package/src/shared/constants/UIKitConstants.ts +5 -1
  12. package/src/shared/events/CometChatUIEventHandler/CometChatUIEventHandler.ts +5 -0
  13. package/src/shared/events/CometChatUIEventHandler/Listener.ts +4 -0
  14. package/src/shared/events/CometChatUIEvents.ts +1 -0
  15. package/src/shared/events/ListenerInitializer.ts +3 -0
  16. package/src/shared/framework/DataSource.ts +10 -0
  17. package/src/shared/framework/DataSourceDecorator.tsx +13 -0
  18. package/src/shared/framework/MessageDataSource.tsx +70 -3
  19. package/src/shared/resources/CometChatLocalizeNew/resources/de/translation.json +502 -500
  20. package/src/shared/resources/CometChatLocalizeNew/resources/en/translation.json +2 -0
  21. package/src/shared/resources/CometChatLocalizeNew/resources/es/translation.json +522 -520
  22. package/src/shared/resources/CometChatLocalizeNew/resources/fr/translation.json +522 -520
  23. package/src/shared/resources/CometChatLocalizeNew/resources/hi/translation.json +522 -520
  24. package/src/shared/resources/CometChatLocalizeNew/resources/hu/translation.json +522 -520
  25. package/src/shared/resources/CometChatLocalizeNew/resources/it/translation.json +522 -520
  26. package/src/shared/resources/CometChatLocalizeNew/resources/ja/translation.json +522 -520
  27. package/src/shared/resources/CometChatLocalizeNew/resources/ko/translation.json +522 -520
  28. package/src/shared/resources/CometChatLocalizeNew/resources/lt/translation.json +522 -520
  29. package/src/shared/resources/CometChatLocalizeNew/resources/ms/translation.json +522 -520
  30. package/src/shared/resources/CometChatLocalizeNew/resources/nl/translation.json +522 -520
  31. package/src/shared/resources/CometChatLocalizeNew/resources/pt/translation.json +522 -520
  32. package/src/shared/resources/CometChatLocalizeNew/resources/ru/translation.json +522 -520
  33. package/src/shared/resources/CometChatLocalizeNew/resources/sv/translation.json +522 -520
  34. package/src/shared/resources/CometChatLocalizeNew/resources/tr/translation.json +522 -520
  35. package/src/shared/resources/CometChatLocalizeNew/resources/zh/translation.json +522 -520
  36. package/src/shared/resources/CometChatLocalizeNew/resources/zh-tw/translation.json +522 -520
  37. package/src/shared/utils/CometChatMessagePreview/CometChatMessagePreview.tsx +7 -0
  38. package/src/shared/utils/conversationUtils.ts +26 -0
  39. package/src/shared/utils/stripRichText.ts +41 -0
  40. package/src/shared/views/CometChatAIAssistantMessageBubble/CometChatAIAssistantMessageBubble.tsx +107 -48
  41. package/src/shared/views/CometChatCardBubble/CometChatCardBubble.tsx +118 -0
  42. package/src/shared/views/CometChatCardBubble/index.ts +2 -0
  43. package/src/shared/views/CometChatStreamMessageBubble/CometChatStreamMessageBubble.tsx +63 -0
  44. package/src/shared/views/index.ts +2 -0
  45. package/src/CometChatMessageList/MANUAL_TEST_CASES.md +0 -154
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cometchat/chat-uikit-react-native",
3
- "version": "5.3.8",
3
+ "version": "5.3.10",
4
4
  "description": "Ready-to-use Chat UI Components for React Native",
5
5
  "main": "src/index",
6
6
  "module": "src/index",
@@ -12,6 +12,7 @@ import { useTheme } from "../theme";
12
12
  import { Icon } from "../shared/icons/Icon";
13
13
  import { deepMerge } from "../shared/helper/helperFunctions";
14
14
  import { DeepPartial } from "../shared/helper/types";
15
+ import { stripRichText } from "../shared/utils/stripRichText";
15
16
  import { ChatHistoryStyle, getChatHistoryStyleLight } from "./style";
16
17
  import { Skeleton } from "./Skeleton";
17
18
  import { CometChatTooltipMenu } from "../shared/views/CometChatTooltipMenu";
@@ -225,7 +226,9 @@ const CometChatAIAssistantChatHistory: React.FC<CometChatAIAssistantChatHistoryP
225
226
  const getMessageText = useCallback((message: CometChat.BaseMessage): string => {
226
227
  try {
227
228
  if (message instanceof CometChat.TextMessage) {
228
- return message.getText();
229
+ // Plain text only in the history list — strip rich-text markup (e.g. <u>…</u>,
230
+ // **bold**) so titles read cleanly instead of showing raw tags/markers.
231
+ return stripRichText(message.getText());
229
232
  } else if (message instanceof CometChat.MediaMessage) {
230
233
  return `${message.getType()} message`;
231
234
  } else if (message instanceof CometChat.CustomMessage) {
@@ -233,9 +236,9 @@ const CometChatAIAssistantChatHistory: React.FC<CometChatAIAssistantChatHistoryP
233
236
  if (message.getType() === 'assistant' && message.getData()) {
234
237
  const data = message.getData();
235
238
  if (data.assistantMessageData?.getText) {
236
- return data.assistantMessageData.getText();
239
+ return stripRichText(data.assistantMessageData.getText());
237
240
  } else if (data.text) {
238
- return data.text;
241
+ return stripRichText(data.text);
239
242
  }
240
243
  }
241
244
  return 'Custom message';
@@ -1558,6 +1558,15 @@ export const CometChatConversations = (props: ConversationInterface) => {
1558
1558
  messageEventHandler(customInteractiveMessage);
1559
1559
  !disableSoundForMessages && CometChatSoundManager.play("incomingMessage");
1560
1560
  },
1561
+ // Agent (agentic/assistant) reply — update the conversation's last message + unread
1562
+ // count in real time, otherwise the subtitle only refreshes after a re-fetch.
1563
+ onAIAssistantMessageReceived: (aiAssistantMessage: any) => {
1564
+ if (!shouldUpdateLastMessageAndUnreadCount(aiAssistantMessage)) {
1565
+ return;
1566
+ }
1567
+ messageEventHandler(aiAssistantMessage);
1568
+ !disableSoundForMessages && CometChatSoundManager.play("incomingMessage");
1569
+ },
1561
1570
  onMessageModerated: (moderatedMessage: CometChat.BaseMessage) => {
1562
1571
  checkAndUpdateLastMessage(moderatedMessage);
1563
1572
  },
@@ -708,9 +708,11 @@ export const CometChatMessageList = memo(
708
708
  .setGUID(group.getGuid());
709
709
  }
710
710
 
711
+
711
712
  _defaultRequestBuilder.setTypes(ChatConfigurator.dataSource.getAllMessageTypes());
712
713
  _defaultRequestBuilder.setCategories(ChatConfigurator.dataSource.getAllMessageCategories());
713
714
 
715
+
714
716
  //updating users request builder
715
717
  let _updatedCustomRequestBuilder = _defaultRequestBuilder;
716
718
  if (messageRequestBuilder) {
@@ -1961,9 +1963,23 @@ export const CometChatMessageList = memo(
1961
1963
  }
1962
1964
 
1963
1965
  if (isAgenticUser) {
1966
+ // A 1:1 agent conversation only ever contains user-receiver messages. Reject
1967
+ // anything addressed to a group (e.g. a group agent reply that reached this
1968
+ // listener) — otherwise a top-level group message matches the parent-id check
1969
+ // below (String(undefined) === String(undefined)) and leaks into the 1:1 chat.
1970
+ //
1971
+ // In a 1:1 agent chat the `parentMessageId` prop is undefined, but messages
1972
+ // from the 2nd onward are stamped with the first message's id (the thread
1973
+ // root), tracked in agenticParentMessageIdRef. Accept those too, otherwise
1974
+ // every message after the first is filtered out until a remount refetch.
1975
+ const agenticParentId = agenticParentMessageIdRef.current;
1964
1976
  if (
1965
- String(baseMessage.getParentMessageId()) === String(parentMessageId) ||
1966
- String(baseMessage.getId()) === String(parentMessageId)
1977
+ baseMessage.getReceiverType?.() === ReceiverTypeConstants.user &&
1978
+ (String(baseMessage.getParentMessageId()) === String(parentMessageId) ||
1979
+ String(baseMessage.getId()) === String(parentMessageId) ||
1980
+ (agenticParentId !== undefined &&
1981
+ (String(baseMessage.getParentMessageId()) === String(agenticParentId) ||
1982
+ String(baseMessage.getId()) === String(agenticParentId))))
1967
1983
  ) {
1968
1984
  CometChat.markAsDelivered(newMessage);
1969
1985
  bottomHandler(newMessage, isReceived);
@@ -2033,8 +2049,22 @@ export const CometChatMessageList = memo(
2033
2049
  // Thread mismatch check — must run BEFORE the sender check to prevent
2034
2050
  // messages from appearing in the wrong context (main list vs thread)
2035
2051
  // when the same user is logged in on multiple devices.
2052
+ //
2053
+ // Exception: in a 1:1 agent chat the `parentMessageId` prop is undefined,
2054
+ // but messages from the 2nd onward carry the agent thread-root id (tracked
2055
+ // in agenticParentMessageIdRef). Those belong in this list, so don't treat
2056
+ // them as a thread mismatch — otherwise every message after the first is
2057
+ // dropped here until a remount refetch.
2058
+ const isAgenticThreadRootMessage =
2059
+ isAgenticUser &&
2060
+ !parentMessageId &&
2061
+ agenticParentMessageIdRef.current !== undefined &&
2062
+ String(newMessage.getParentMessageId()) ===
2063
+ String(agenticParentMessageIdRef.current);
2036
2064
  if (
2037
- (!parentMessageId && newMessage.getParentMessageId()) ||
2065
+ (!parentMessageId &&
2066
+ newMessage.getParentMessageId() &&
2067
+ !isAgenticThreadRootMessage) ||
2038
2068
  (parentMessageId && !newMessage.getParentMessageId()) ||
2039
2069
  (parentMessageId &&
2040
2070
  newMessage.getParentMessageId() &&
@@ -2914,7 +2944,18 @@ export const CometChatMessageList = memo(
2914
2944
  newMessage(formMessage);
2915
2945
  },
2916
2946
  onCardMessageReceived: (cardMessage: any) => {
2917
- newMessage(cardMessage);
2947
+ if (isAgenticUser) {
2948
+ if (
2949
+ cardMessage.getSender?.()?.getRole?.() === "@agentic" ||
2950
+ cardMessage.getCategory?.() === MessageCategoryConstants.agentic ||
2951
+ cardMessage.getCategory?.() ===
2952
+ CometChatUiKitConstants.MessageCategoryConstants.stream
2953
+ ) {
2954
+ newMessage(cardMessage);
2955
+ }
2956
+ } else {
2957
+ newMessage(cardMessage);
2958
+ }
2918
2959
  },
2919
2960
  onSchedulerMessageReceived: (schedulerMessage: any) => {
2920
2961
  newMessage(schedulerMessage);
@@ -2938,6 +2979,26 @@ export const CometChatMessageList = memo(
2938
2979
  ) {
2939
2980
  return;
2940
2981
  }
2982
+ // Group agent reply belongs ONLY to its own group conversation. In a 1:1
2983
+ // agent chat `group` is undefined, and a different group won't match the
2984
+ // guid — so the reply can never leak outside its own group list.
2985
+ if (
2986
+ aiAssistantMessage.getReceiverType?.() === ReceiverTypeConstants.group
2987
+ ) {
2988
+ if (group && aiAssistantMessage.getReceiverId?.() === group.getGuid()) {
2989
+ newMessage(aiAssistantMessage);
2990
+ }
2991
+ return;
2992
+ }
2993
+ // 1:1 agent reply belongs ONLY to the matching 1:1 agent conversation — its
2994
+ // sender is the agent represented by `user`. Anything else (a group list, or
2995
+ // a different agent's chat) ignores it so it can't leak across conversations.
2996
+ if (
2997
+ !user ||
2998
+ aiAssistantMessage.getSender?.()?.getUid?.() !== user.getUid()
2999
+ ) {
3000
+ return;
3001
+ }
2941
3002
  if (runId) {
2942
3003
  storeAIAssistantMessage(String(runId), aiAssistantMessage);
2943
3004
  }
@@ -3232,6 +3293,12 @@ export const CometChatMessageList = memo(
3232
3293
  })();
3233
3294
 
3234
3295
  if (item.getSender()?.getUid() != loggedInUser.current?.getUid()) {
3296
+ // Agent (assistant) replies use the normal incoming bubble — which has a
3297
+ // background container and no negative top margin — so the reply is visually
3298
+ // contained like other messages. Applies to both group and 1:1 AI chat.
3299
+ if (type === MessageTypeConstants.assistant) {
3300
+ return mergedTheme.messageListStyles.incomingMessageBubbleStyles as BubbleStyles;
3301
+ }
3235
3302
  return (
3236
3303
  overridenBubbleStyles.get(type)?.incoming ??
3237
3304
  mergedTheme.messageListStyles.incomingMessageBubbleStyles
@@ -3830,6 +3897,9 @@ export const CometChatMessageList = memo(
3830
3897
              // (from mergeObjects during history fetch dedup) overwrote `category` and `type`
3831
3898
              let lookupCategory: string = message.getCategory();
3832
3899
              let lookupType: string = message.getType();
3900
+ if (lookupCategory === MessageCategoryConstants.card) {
3901
+ lookupType = MessageTypeConstants.card;
3902
+ }
3833
3903
 
3834
3904
              const hasInteractiveData =
3835
3905
                typeof (message as any).getInteractiveData === 'function' &&
@@ -4039,8 +4109,17 @@ export const CometChatMessageList = memo(
4039
4109
  }
4040
4110
  }, [onReply, message]);
4041
4111
 
4112
+ // Disable swipe-to-reply for agent ("@agentic") messages. Covers both the
4113
+ // 1:1 AI chat (isAgenticUser, whole conversation) and agent messages inside a
4114
+ // group — where the reply context-menu option is already removed, so the swipe
4115
+ // gesture is suppressed to match (otherwise mobile users could still swipe-reply).
4116
+ const isAgenticMessage =
4117
+ isAgenticUser ||
4118
+ message.getSender?.()?.getRole?.() === "@agentic" ||
4119
+ message.getCategory?.() === MessageCategoryConstants.agentic;
4120
+
4042
4121
  return (
4043
- message.getCategory() === MessageCategoryConstants.action || isAgenticUser ? (
4122
+ message.getCategory() === MessageCategoryConstants.action || isAgenticMessage ? (
4044
4123
  <View style={staticStyles.positionRelative}>
4045
4124
  <TouchableOpacity
4046
4125
  activeOpacity={1}
@@ -0,0 +1,478 @@
1
+ # CometChatMessageList — Performance & Crash Fix Architecture
2
+
3
+ **Ticket:** ENG-35194
4
+ **Platform:** React Native (Android physical devices — Hermes engine)
5
+ **Component:** `CometChatMessageList.tsx` (~4800 lines)
6
+ **Constraint:** Zero public API/prop changes. All existing props remain identical.
7
+
8
+ ---
9
+
10
+ ## 1. Problem Statement
11
+
12
+ When opening a group or user conversation via search results (links or messages), the app crashes or freezes on physical Android devices. The issue occurs specifically when the conversation has a large message history (1000+ messages).
13
+
14
+ ### Reproduction Steps
15
+ 1. Go to conversation list
16
+ 2. Open Search → Click "Links" section
17
+ 3. Tap any link result from a large group
18
+ 4. Observe: screen stuck / app crashes
19
+
20
+ ### Root Cause Summary
21
+
22
+ The crash is caused by a **cascade of expensive operations** triggered simultaneously on the single JS thread (Hermes, no JIT):
23
+
24
+ | Operation | Frequency | Cost on Hermes |
25
+ |-----------|-----------|----------------|
26
+ | `setItemPositions` (state update per message layout) | N per render batch | Re-render entire FlatList |
27
+ | `onEndReached` → `getPreviousMessages` | Fires immediately (16 msgs don't fill screen) | 30 more messages + all associated operations |
28
+ | `[...array]` spread copies | Every mutation | O(n) allocation |
29
+ | `onLoad([...list].reverse())` | Every mutation | O(n) copy + O(n) reverse |
30
+ | `rebuildMessageIndex()` | Every mutation | O(n) iteration |
31
+ | `CommonUtils.clone()` (deep clone) | Every message update | Expensive on Hermes (Reflect.ownKeys + descriptors) |
32
+
33
+ On iOS (JSC with JIT), these complete in ~200ms total. On Android (Hermes), they take 800-2000ms, exceeding the ANR threshold and causing OOM crashes.
34
+
35
+ ---
36
+
37
+ ## 2. Current Architecture (Before Fix)
38
+
39
+ ```
40
+ Search tap → CommonActions.reset → Messages screen mounts
41
+ → CometChatMessageList mounts
42
+ → useEffect[] fires
43
+ → getMessagesAroundId(messageId)
44
+ → Fetches 1 target + 15 next = 16 messages
45
+ → setMessagesList(16 messages) → FlatList renders
46
+ → Each message: onLayout → setItemPositions (STATE UPDATE × 16)
47
+ → setScrollTargetId → scrollToMessage (with retries)
48
+ → onEndReached fires (16 messages don't fill screen)
49
+ → getPreviousMessages() → fetches 30 more
50
+ → [...current, ...30new] spread
51
+ → rebuildMessageIndex() — iterates 46 items
52
+ → setMessagesList(46 messages) → FlatList re-renders
53
+ → onLayout × 30 → setItemPositions (STATE UPDATE × 30)
54
+ → onLoad([...46items].reverse()) — copy + reverse
55
+ → onEndReached fires AGAIN
56
+ → Cycle repeats until 500-cap or crash
57
+ ```
58
+
59
+ **Total state updates in first 2 seconds:** ~50-80
60
+ **Total array copies:** ~10-15 (each O(n))
61
+ **Result on Android:** OOM crash or ANR
62
+
63
+ ---
64
+
65
+ ## 3. Proposed Architecture (After Fix)
66
+
67
+ ```
68
+ Search tap → CommonActions.reset → Messages screen mounts
69
+ → CometChatMessageList mounts
70
+ → useEffect[] fires
71
+ → getMessagesAroundId(messageId)
72
+ → navigationInProgressRef = true (GATE CLOSED)
73
+ → Fetches 30 prev + 1 target + 15 next = 46 messages
74
+ → messagesContentListRef.current = allMessages (ref mutation)
75
+ → setMessagesList(allMessages) → FlatList renders (SINGLE render)
76
+ → Each message: onLayout → itemPositionsRef.set() (NO state update)
77
+ → scrollToMessage completes
78
+ → navigationInProgressRef = false (GATE OPEN)
79
+ → onEndReached fires? → blocked by gate → no-op
80
+ → User scrolls up manually → onEndReached fires → normal pagination
81
+ ```
82
+
83
+ **Total state updates in first 2 seconds:** 3 (setMessagesList, setNavigationLoading×2)
84
+ **Total array copies:** 1 (initial setMessagesList)
85
+ **Result on Android:** Smooth, no crash
86
+
87
+ ---
88
+
89
+ ## 4. Detailed Changes
90
+
91
+ ### Phase 1: Stop the Crash (Critical Priority)
92
+
93
+ #### 1.1 — Navigation Pagination Gate
94
+
95
+ **File:** `CometChatMessageList.tsx`
96
+ **Location:** Near refs declaration (~line 974)
97
+
98
+ Add a ref that blocks pagination during initial navigation:
99
+
100
+ ```typescript
101
+ const navigationInProgressRef = useRef(false);
102
+ ```
103
+
104
+ **In `getMessagesAroundId`** — set at the start:
105
+ ```typescript
106
+ navigationInProgressRef.current = true;
107
+ ```
108
+
109
+ **In `scrollToMessage`** — clear after scroll completes (in all completion paths):
110
+ ```typescript
111
+ navigationInProgressRef.current = false;
112
+ ```
113
+
114
+ **In `getPreviousMessages`** — add early return at top:
115
+ ```typescript
116
+ if (navigationInProgressRef.current) {
117
+ loadingPrevMessagesRef.current = false;
118
+ return;
119
+ }
120
+ ```
121
+
122
+ **In `fetchNextMessages`** — add early return at top:
123
+ ```typescript
124
+ if (navigationInProgressRef.current) return;
125
+ ```
126
+
127
+ **Risk:** Very Low — only affects the search navigation flow
128
+ **Testing:** Navigate from search to message in large group. Verify messages load, scroll works, no crash.
129
+
130
+ ---
131
+
132
+ #### 1.2 — Fetch More Messages in `getMessagesAroundId`
133
+
134
+ **File:** `CometChatMessageList.tsx`
135
+ **Location:** Inside `getMessagesAroundId` function (~line 1280)
136
+
137
+ Currently fetches: 1 target + 15 next = 16 messages (doesn't fill screen).
138
+
139
+ Change to fetch: 30 previous + 1 target + 15 next = 46 messages (fills screen).
140
+
141
+ ```typescript
142
+ // Add BEFORE the existing nextMessagesRequest:
143
+ let prevMessagesRequest = new CometChat.MessagesRequestBuilder()
144
+ .setLimit(30)
145
+ .setMessageId(targetMessageId);
146
+
147
+ if (user) prevMessagesRequest = prevMessagesRequest.setUID(user.getUid());
148
+ if (group) prevMessagesRequest = prevMessagesRequest.setGUID(group.getGuid());
149
+ if (!parentMessageId) {
150
+ prevMessagesRequest = prevMessagesRequest.hideReplies(true);
151
+ } else {
152
+ prevMessagesRequest = prevMessagesRequest
153
+ .setParentMessageId(Number(parentMessageId))
154
+ .hideReplies(false);
155
+ }
156
+
157
+ const previousMessages = await prevMessagesRequest.build().fetchPrevious();
158
+
159
+ // Update allMessages combination:
160
+ const allMessages = [
161
+ ...previousMessages.reverse(), // oldest→newest, then reverse for inverted list
162
+ targetMessage,
163
+ ...nextMessages
164
+ ].reverse(); // newest first for inverted FlatList
165
+ ```
166
+
167
+ **Risk:** Low — fetches more data upfront but prevents cascade
168
+ **Testing:** Verify target message is visible and centered after navigation. Verify older messages are above it.
169
+
170
+ ---
171
+
172
+ #### 1.3 — ErrorBoundary per Message Row
173
+
174
+ **File:** New file `CometChatMessageList/components/MessageErrorBoundary.tsx`
175
+
176
+ ```typescript
177
+ import React from 'react';
178
+ import { View } from 'react-native';
179
+
180
+ interface Props {
181
+ children: React.ReactNode;
182
+ messageId: string;
183
+ }
184
+
185
+ interface State {
186
+ hasError: boolean;
187
+ }
188
+
189
+ export class MessageErrorBoundary extends React.Component<Props, State> {
190
+ state: State = { hasError: false };
191
+
192
+ static getDerivedStateFromError(): State {
193
+ return { hasError: true };
194
+ }
195
+
196
+ componentDidCatch(error: Error) {
197
+ console.warn(
198
+ `[CometChatMessageList] Message ${this.props.messageId} render failed:`,
199
+ error.message
200
+ );
201
+ }
202
+
203
+ render() {
204
+ if (this.state.hasError) {
205
+ return <View style={{ height: 1 }} />;
206
+ }
207
+ return this.props.children;
208
+ }
209
+ }
210
+ ```
211
+
212
+ **Usage in `MessageListItem.tsx`:**
213
+ ```typescript
214
+ import { MessageErrorBoundary } from './MessageErrorBoundary';
215
+
216
+ // Wrap the entire return:
217
+ return (
218
+ <MessageErrorBoundary messageId={String(item.getId())}>
219
+ <View style={staticStyles.container} onLayout={handleLayout}>
220
+ {/* ... existing content ... */}
221
+ </View>
222
+ </MessageErrorBoundary>
223
+ );
224
+ ```
225
+
226
+ **Risk:** Very Low — only catches errors, doesn't change behavior
227
+ **Testing:** Intentionally corrupt a message object in dev. Verify list doesn't crash, shows placeholder.
228
+
229
+ ---
230
+
231
+ ### Phase 2: Eliminate State Update Storms
232
+
233
+ #### 2.1 — Move `itemPositions` from State to Ref
234
+
235
+ **File:** `CometChatMessageList.tsx`
236
+
237
+ **Current:**
238
+ ```typescript
239
+ const [itemPositions, setItemPositions] = useState<Map<string, { y: number; height: number }>>(new Map());
240
+ ```
241
+
242
+ **Proposed:**
243
+ ```typescript
244
+ const itemPositionsRef = useRef<Map<string, { y: number; height: number }>>(new Map());
245
+ ```
246
+
247
+ **Update all consumers:**
248
+ - `handleItemLayout`: Write to `itemPositionsRef.current.set(...)` directly (no state update)
249
+ - `scrollToMessage`: Read from `itemPositionsRef.current.get(...)`
250
+ - `onScrollToIndexFailed`: Read from `itemPositionsRef.current.values()`
251
+ - Remove the `pendingPositionsRef` and `layoutBatchTimerRef` (no longer needed)
252
+
253
+ **Remove from `useCallback` dependencies** where `itemPositions` was listed.
254
+
255
+ **Risk:** Low — `itemPositions` was never used for rendering, only for imperative scroll calculations
256
+ **Testing:** Navigate from search → verify scroll-to-target still works. Verify highlight animation still works.
257
+
258
+ ---
259
+
260
+ #### 2.2 — Debounced `commitMessages` Helper
261
+
262
+ **File:** `CometChatMessageList.tsx`
263
+
264
+ ```typescript
265
+ const commitTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
266
+
267
+ const commitMessages = useCallback((immediate = false) => {
268
+ if (immediate) {
269
+ if (commitTimerRef.current) {
270
+ clearTimeout(commitTimerRef.current);
271
+ commitTimerRef.current = null;
272
+ }
273
+ setMessagesList([...messagesContentListRef.current]);
274
+ return;
275
+ }
276
+
277
+ if (commitTimerRef.current) return; // Already scheduled
278
+ commitTimerRef.current = setTimeout(() => {
279
+ setMessagesList([...messagesContentListRef.current]);
280
+ commitTimerRef.current = null;
281
+ }, 16); // One frame
282
+ }, []);
283
+ ```
284
+
285
+ **Replace direct `setMessagesList` calls with `commitMessages()`** in:
286
+ - `addToMessageList` (use debounced)
287
+ - `messageEdited` (use debounced)
288
+ - `removeMessage` (use debounced)
289
+
290
+ **Keep `immediate = true`** for:
291
+ - `getPreviousMessages` (user expects to see messages)
292
+ - `getMessagesAroundId` (initial load)
293
+ - `scrollToBottom` merge
294
+
295
+ **Risk:** Medium — rapid message arrivals batch into single render
296
+ **Testing:** Send multiple messages rapidly. Verify all appear. Verify no visual delay > 16ms.
297
+
298
+ ---
299
+
300
+ #### 2.3 — Debounce `onLoad` Callback
301
+
302
+ **File:** `CometChatMessageList.tsx`
303
+
304
+ ```typescript
305
+ const onLoadTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
306
+
307
+ const notifyOnLoad = useCallback(() => {
308
+ if (!onLoad) return;
309
+ if (onLoadTimerRef.current) clearTimeout(onLoadTimerRef.current);
310
+ onLoadTimerRef.current = setTimeout(() => {
311
+ onLoad([...messagesContentListRef.current].reverse());
312
+ onLoadTimerRef.current = null;
313
+ }, 100); // 100ms debounce
314
+ }, [onLoad]);
315
+ ```
316
+
317
+ Replace all `onLoad && onLoad([...messagesContentListRef.current].reverse())` with `notifyOnLoad()`.
318
+
319
+ **Risk:** Low — `onLoad` is informational, 100ms delay is imperceptible
320
+ **Testing:** Verify `onLoad` still fires with correct data. Verify no duplicate calls.
321
+
322
+ ---
323
+
324
+ ### Phase 3: Memory Management
325
+
326
+ #### 3.1 — Sliding Window (300 Message Cap)
327
+
328
+ **File:** `CometChatMessageList.tsx`
329
+
330
+ **In `getPreviousMessages`** — after appending messages:
331
+ ```typescript
332
+ const MAX_MESSAGES_IN_MEMORY = 300;
333
+
334
+ if (messagesContentListRef.current.length > MAX_MESSAGES_IN_MEMORY) {
335
+ // Trim oldest messages (end of array in inverted list = oldest)
336
+ messagesContentListRef.current = messagesContentListRef.current.slice(0, MAX_MESSAGES_IN_MEMORY);
337
+ reachedFirstMessage.current = false; // Allow re-fetch if user scrolls back
338
+ rebuildMessageIndex();
339
+ }
340
+ ```
341
+
342
+ **In `fetchNextMessages`** — after prepending newer messages:
343
+ ```typescript
344
+ if (messagesContentListRef.current.length > MAX_MESSAGES_IN_MEMORY) {
345
+ // Trim oldest messages from the end
346
+ messagesContentListRef.current = messagesContentListRef.current.slice(0, MAX_MESSAGES_IN_MEMORY);
347
+ rebuildMessageIndex();
348
+ }
349
+ ```
350
+
351
+ **Risk:** Medium — user loses access to very old messages (must scroll to re-fetch)
352
+ **Testing:** Load 300+ messages. Verify oldest are trimmed. Verify scrolling up re-fetches them.
353
+
354
+ ---
355
+
356
+ ### Phase 4: Reduce Allocations
357
+
358
+ #### 4.1 — Lazy Index Rebuild
359
+
360
+ **File:** `CometChatMessageList.tsx`
361
+
362
+ ```typescript
363
+ const indexDirtyRef = useRef(false);
364
+
365
+ const markIndexDirty = () => { indexDirtyRef.current = true; };
366
+
367
+ const ensureIndexFresh = () => {
368
+ if (indexDirtyRef.current) {
369
+ rebuildMessageIndex();
370
+ indexDirtyRef.current = false;
371
+ }
372
+ };
373
+ ```
374
+
375
+ **Replace `rebuildMessageIndex()` with `markIndexDirty()`** in:
376
+ - `addToMessageList` (after prepend)
377
+ - `messageEdited` (after update)
378
+ - `removeMessage` (after splice)
379
+
380
+ **Call `ensureIndexFresh()`** at the start of:
381
+ - `addToMessageList` dedup check (before Map lookup)
382
+ - `messageEdited` lookup (before Map lookup)
383
+
384
+ **Keep direct `rebuildMessageIndex()`** for bulk operations:
385
+ - `getPreviousMessages` (after appending 30 messages)
386
+ - `getMessagesAroundId` (after setting initial list)
387
+ - `fetchNextMessages` (after prepending batch)
388
+ - `scrollToBottom` merge
389
+
390
+ **Risk:** Low — index is always fresh before any lookup
391
+ **Testing:** Send message → verify dedup works. Edit message → verify update works.
392
+
393
+ ---
394
+
395
+ #### 4.2 — Shallow Clone for Message Updates
396
+
397
+ **File:** `CommonUtils.ts`
398
+
399
+ Add a new method:
400
+ ```typescript
401
+ static shallowCloneMessage<T>(msg: T): T {
402
+ if (typeof msg !== "object" || !msg) return msg;
403
+ const clone = Object.create(Object.getPrototypeOf(msg));
404
+ Object.assign(clone, msg);
405
+ return clone;
406
+ }
407
+ ```
408
+
409
+ **Replace `CommonUtils.clone(editedMessage)` with `CommonUtils.shallowCloneMessage(editedMessage)`** in:
410
+ - `messageEdited` function
411
+ - `addToMessageList` dedup update path
412
+
413
+ **Keep `CommonUtils.clone()`** (deep clone) for:
414
+ - Conversation objects (have nested user/group objects that need independence)
415
+ - Cases where nested mutation would cause bugs
416
+
417
+ **Risk:** Medium — shallow clone means nested objects share references
418
+ **Testing:** Edit a message → verify UI updates. Delete a message → verify it disappears. Verify no stale data in reactions/threads.
419
+
420
+ ---
421
+
422
+ ## 5. Implementation Order
423
+
424
+ | Priority | Change | Files Modified | Est. Time |
425
+ |----------|--------|----------------|-----------|
426
+ | P0 | 1.1 Navigation gate | CometChatMessageList.tsx | 15 min |
427
+ | P0 | 2.1 itemPositions → ref | CometChatMessageList.tsx | 30 min |
428
+ | P0 | 1.3 ErrorBoundary | New file + MessageListItem.tsx | 20 min |
429
+ | P1 | 1.2 Fetch more in getMessagesAroundId | CometChatMessageList.tsx | 30 min |
430
+ | P1 | 2.3 Debounce onLoad | CometChatMessageList.tsx | 15 min |
431
+ | P1 | 4.1 Lazy index rebuild | CometChatMessageList.tsx | 20 min |
432
+ | P2 | 4.2 Shallow clone | CommonUtils.ts + CometChatMessageList.tsx | 30 min |
433
+ | P2 | 2.2 Debounced commitMessages | CometChatMessageList.tsx | 45 min |
434
+ | P2 | 3.1 Sliding window trim | CometChatMessageList.tsx | 30 min |
435
+
436
+ **Total estimated time:** ~4 hours
437
+
438
+ ---
439
+
440
+ ## 6. Testing Matrix
441
+
442
+ | Scenario | Expected Result |
443
+ |----------|-----------------|
444
+ | Search → tap link in large group (Android) | No crash, messages load in < 1s |
445
+ | Search → tap link in large group (iOS) | Same behavior as before (no regression) |
446
+ | Normal conversation open (no search) | No change in behavior |
447
+ | Send message in large group (Android) | Clock icon disappears within 500ms |
448
+ | Receive messages while scrolled up | Unread count increments, no crash |
449
+ | Scroll to very old messages | Pagination works, newer messages trimmed |
450
+ | Scroll back to bottom after deep scroll | Messages re-fetch correctly |
451
+ | Message with malformed metadata | ErrorBoundary catches, list continues |
452
+ | Thread navigation from search | Thread messages load correctly |
453
+ | Agentic user chat | No regression in streaming behavior |
454
+
455
+ ---
456
+
457
+ ## 7. Metrics to Track
458
+
459
+ | Metric | Before | Target |
460
+ |--------|--------|--------|
461
+ | Time to first message visible (search nav, Android) | 2-5s or crash | < 800ms |
462
+ | State updates during search navigation | 50-80 | 3-5 |
463
+ | Peak memory (300-msg conversation) | Unbounded | ~300 objects max |
464
+ | `messageEdited` lookup time | O(n) | O(1) |
465
+ | `addToMessageList` dedup time | O(n) | O(1) |
466
+ | Array copies per message send | 3-4 | 1 |
467
+
468
+ ---
469
+
470
+ ## 8. Rollback Plan
471
+
472
+ Each phase is independent. If any phase causes regression:
473
+ - Phase 1: Remove `navigationInProgressRef` checks → reverts to current cascade behavior
474
+ - Phase 2: Revert `itemPositionsRef` to state, remove debounce helpers
475
+ - Phase 3: Remove trim logic, increase cap back to 500
476
+ - Phase 4: Revert to `CommonUtils.clone()` and direct `rebuildMessageIndex()`
477
+
478
+ No database migrations, no API changes, no prop changes. Pure internal refactor.