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

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cometchat/chat-uikit-react-native",
3
- "version": "5.3.7",
3
+ "version": "5.3.8",
4
4
  "description": "Ready-to-use Chat UI Components for React Native",
5
5
  "main": "src/index",
6
6
  "module": "src/index",
@@ -0,0 +1,154 @@
1
+ # Manual Test Cases — `loadLastAgentConversation`
2
+
3
+ ## Prerequisites
4
+ - An `@agentic` user configured in your CometChat dashboard
5
+ - The example app running with `loadLastAgentConversation={true}` on `CometChatMessageList`
6
+ - At least one previous conversation with the agent (send a message, get a response)
7
+
8
+ ---
9
+
10
+ ## TC-1: Auto-loads last conversation on open
11
+
12
+ **Steps:**
13
+ 1. Have at least one previous conversation with the agent (send "Hello", wait for reply)
14
+ 2. Navigate away from the agent chat (go back to conversation list)
15
+ 3. Open the agent chat again
16
+
17
+ **Expected:**
18
+ - A loading indicator appears briefly
19
+ - The previous conversation messages load automatically
20
+ - You see your last messages and the agent's responses
21
+
22
+ ---
23
+
24
+ ## TC-2: Shows greeting/empty state when no previous conversation exists
25
+
26
+ **Steps:**
27
+ 1. Use a fresh `@agentic` user with no message history (or use a new logged-in user who hasn't chatted with the agent)
28
+ 2. Open the agent chat
29
+
30
+ **Expected:**
31
+ - The agent greeting view appears (avatar, greeting message, suggested messages)
32
+ - No loading spinner hangs indefinitely
33
+
34
+ ---
35
+
36
+ ## TC-3: "New Chat" button from header shows empty state
37
+
38
+ **Steps:**
39
+ 1. Open the agent chat (previous conversation auto-loads)
40
+ 2. Tap the "New Chat" button (pencil/compose icon) in the header
41
+
42
+ **Expected:**
43
+ - The screen resets to the greeting/empty state
44
+ - The previous conversation is NOT re-loaded
45
+ - You can type a fresh message to start a new conversation
46
+
47
+ ---
48
+
49
+ ## TC-4: "New Chat" button from Chat History drawer works
50
+
51
+ **Steps:**
52
+ 1. Open the agent chat
53
+ 2. Tap the "Chat History" button in the header to open the history drawer
54
+ 3. Tap the "New Chat" button inside the history drawer
55
+
56
+ **Expected:**
57
+ - The history drawer closes
58
+ - The message list resets to greeting/empty state
59
+ - The previous conversation is NOT re-loaded
60
+
61
+ ---
62
+
63
+ ## TC-5: Loading a specific conversation from Chat History still works
64
+
65
+ **Steps:**
66
+ 1. Open the agent chat (previous conversation auto-loads)
67
+ 2. Tap the "Chat History" button in the header
68
+ 3. Tap on a specific past conversation from the list
69
+
70
+ **Expected:**
71
+ - The selected conversation loads with all its messages
72
+ - Streaming/responses still work if you send a new message in that thread
73
+
74
+ ---
75
+
76
+ ## TC-6: Sending a new message after "New Chat" starts a new thread
77
+
78
+ **Steps:**
79
+ 1. Open the agent chat (previous conversation auto-loads)
80
+ 2. Tap "New Chat" (message list resets to empty)
81
+ 3. Type and send a message (e.g., "What's the weather?")
82
+
83
+ **Expected:**
84
+ - Your message appears in the list
85
+ - A streaming indicator shows while the agent responds
86
+ - The agent's reply appears correctly
87
+ - This is now a NEW conversation thread (not appended to the old one)
88
+
89
+ ---
90
+
91
+ ## TC-7: Re-opening after new chat shows the NEW conversation
92
+
93
+ **Steps:**
94
+ 1. Complete TC-6 (start a new chat, send message, get reply)
95
+ 2. Navigate away from the agent chat
96
+ 3. Open the agent chat again
97
+
98
+ **Expected:**
99
+ - The most recent conversation (from step 1-2) auto-loads
100
+ - You see the "What's the weather?" message and the agent's response
101
+ - NOT the older conversation from before
102
+
103
+ ---
104
+
105
+ ## TC-8: `loadLastAgentConversation={false}` preserves existing behavior
106
+
107
+ **Steps:**
108
+ 1. Change the prop to `loadLastAgentConversation={false}` (or remove it) in Messages.tsx
109
+ 2. Open the agent chat (even with previous conversations)
110
+
111
+ **Expected:**
112
+ - The greeting/empty state shows immediately
113
+ - No automatic loading of previous conversation
114
+ - Behaves exactly as before this feature was added
115
+
116
+ ---
117
+
118
+ ## TC-9: Non-agentic users are unaffected
119
+
120
+ **Steps:**
121
+ 1. With `loadLastAgentConversation={true}` still set
122
+ 2. Open a regular (non-agentic) user chat that has message history
123
+
124
+ **Expected:**
125
+ - Messages load normally (standard behavior)
126
+ - No change in behavior — the prop only applies to `@agentic` users
127
+
128
+ ---
129
+
130
+ ## TC-10: Scroll up to load older messages in auto-loaded conversation
131
+
132
+ **Steps:**
133
+ 1. Have a long conversation history with the agent (30+ messages)
134
+ 2. Open the agent chat (auto-loads last conversation)
135
+ 3. Scroll up to the top of the loaded messages
136
+
137
+ **Expected:**
138
+ - Older messages load (pagination works)
139
+ - No crash or infinite spinner
140
+ - The loading indicator appears at the top while fetching
141
+
142
+ ---
143
+
144
+ ## TC-11: Delete all history from Chat History panel
145
+
146
+ **Steps:**
147
+ 1. Open the agent chat
148
+ 2. Open Chat History drawer
149
+ 3. Long-press and delete all conversations one by one until none remain
150
+
151
+ **Expected:**
152
+ - When the last conversation is deleted, the list shows empty state
153
+ - The message list resets to greeting/empty view
154
+ - Re-opening the chat shows greeting (no conversation to auto-load)
@@ -76,6 +76,64 @@ export class CometChatUIKit {
76
76
  );
77
77
  }
78
78
 
79
+ /**
80
+ * File-based init for AI agent skills.
81
+ * Calls CometChat.initFromSettings(settings) which writes
82
+ * integrationSource = "ai-agent" to persistent storage.
83
+ */
84
+ static initFromSettings(settings: CometChat.CometChatSettings) {
85
+ // Extract authKey from credentials (UIKit uses this for login — SDK ignores it)
86
+ const authKey = settings.credentials?.authKey;
87
+
88
+ // Extract UIKit-specific settings
89
+ const subscribePresence =
90
+ (settings.uiKit as { subscribePresenceForAllUsers?: boolean })
91
+ ?.subscribePresenceForAllUsers ?? true;
92
+
93
+ // Store internally so login/createUser/updateUser keep working
94
+ CometChatUIKit.uiKitSettings = {
95
+ appId: settings.appId,
96
+ region: settings.region,
97
+ authKey,
98
+ subscriptionType: subscribePresence
99
+ ? CometChat.AppSettings.SUBSCRIPTION_TYPE_ALL_USERS as UIKitSettings["subscriptionType"]
100
+ : undefined,
101
+ };
102
+
103
+ CometChatUIKit.attachListener();
104
+
105
+ // CRITICAL: Call initFromSettings — NOT init(). Only initFromSettings writes "ai-agent".
106
+ return CometChat.initFromSettings(settings).then(
107
+ async () => {
108
+ CometChat.setSource("uikit-v5", Platform.OS, "react-native");
109
+ ListenerInitializer.attachListeners();
110
+ await CometChat.getLoggedinUser()
111
+ .then((user: any) => {
112
+ CometChatUIKit.setLoggedInUser(user);
113
+ if (user) {
114
+ this.enableExtensions();
115
+ }
116
+ CometChat.getConversationUpdateSettings().then(
117
+ (conversationUpdateSettings: CometChat.ConversationUpdateSettings) => {
118
+ CometChatUIKit.setConversationUpdateSettings(conversationUpdateSettings);
119
+ }
120
+ );
121
+ permissionUtil.init().then((res) => {
122
+ if (res !== true) {
123
+ console.warn("[IOS] Permission initialization failed.");
124
+ }
125
+ });
126
+ })
127
+ .catch((error: any) => {
128
+ // CometChatUIKit.setLoggedInUser(null);
129
+ });
130
+ },
131
+ (error: any) => {
132
+ // console.log("Initialization failed with error:", error);
133
+ }
134
+ );
135
+ }
136
+
79
137
  static defaultExtensions: ExtensionsDataSource[] = [
80
138
  new StickersExtension(),
81
139
  new CollaborativeWhiteboardExtension(),
@@ -1,478 +0,0 @@
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.
@@ -1,613 +0,0 @@
1
- # Search Navigation Performance — Architecture Plan (v3 — Optimized)
2
-
3
- **File:** `CometChatMessageList.tsx`
4
- **Ticket:** Search → "Go to Message" is slow
5
- **Constraint:** Zero public API / prop changes. All existing props remain identical.
6
-
7
- ---
8
-
9
- ## Theoretical Minimum Latency
10
-
11
- ```
12
- T=0 User taps search result
13
- T=10ms Network round trip starts (parallel fetchPrev + fetchNext)
14
- T=~300ms Server responds (typical 4G)
15
- T=305ms Response parsed
16
- T=310ms setMessagesList committed
17
- T=326ms React + FlatList render (1 frame, ~16ms)
18
- T=342ms scrollToIndex called (useEffect + rAF)
19
- T=358ms FlatList viewport commit (1 frame)
20
- T=358ms highlightMessage applied (same frame as commit)
21
- ─────────────────────────────────
22
- Floor: ~360ms (network-bound)
23
- Current: 1500–3000ms (CPU + retry-bound)
24
-
25
- Speedup: 5–8x
26
- ```
27
-
28
- The plan below hits the floor.
29
-
30
- ---
31
-
32
- ## 1. Current Flow (Bottlenecks)
33
-
34
- ```
35
- User taps → CometChatMessageList mounts → getMessagesAroundId(messageId)
36
- [Sequential] CometChat.getMessageDetails() ← redundant call
37
- [Sequential] fetchNext(limit: 15) ← waits for above
38
- setMessagesList(16 msgs) → render
39
- setScrollTargetId(messageId) → useEffect fires
40
- scrollToMessage:
41
- itemPositions.get() → undefined
42
- setTimeout 100, 200, 300, 400, 500ms (5 retries) ← up to 1.5s polling
43
- fallback scrollToIndex → onScrollToIndexFailed → 300ms more
44
- Meanwhile:
45
- 16 onLayout events → 16 setItemPositions state updates → 16 re-renders
46
- onEndReached fires (16 msgs don't fill screen)
47
- → getPreviousMessages(30) → setMessagesList → 30 more state updates
48
- → onEndReached AGAIN → cycle repeats 2-3 times
49
- ```
50
-
51
- **Bottlenecks:**
52
- 1. 3+ sequential network calls
53
- 2. State-triggered re-render storm from `setItemPositions`
54
- 3. 1.5s polling retry loop in `scrollToMessage`
55
- 4. `onEndReached` cascade from underfilled viewport
56
- 5. No `getItemLayout` → `scrollToIndex` cannot work without prior render
57
-
58
- ---
59
-
60
- ## 2. Root Causes (Mapped to Fixes)
61
-
62
- | # | Root Cause | Fix |
63
- |---|---|---|
64
- | RC-1 | No `getItemLayout` → `scrollToIndex` requires items rendered first | Change A |
65
- | RC-2 | `itemPositions` is state → re-renders on every `onLayout` | Change B |
66
- | RC-3 | `scrollToMessage` polls for layout data | Change C |
67
- | RC-4 | `onEndReached` cascade during navigation | Change D |
68
- | RC-5 | 3 sequential network calls + redundant `getMessageDetails` | Change E |
69
-
70
- ---
71
-
72
- ## 3. Optimized Solution
73
-
74
- ### Change A — Add `getItemLayout` to FlatList
75
-
76
- **Why:** `getItemLayout` is React Native's documented mechanism for "fixed/estimated row height" lists. It allows `scrollToIndex` to compute the target offset **without rendering items first** — the framework calls `getItemLayout(data, targetIndex)` and uses the returned `offset` directly. This eliminates the entire premise behind the polling loop.
77
-
78
- **Why estimated height works:** `getItemLayout` only needs to be approximately right. After `scrollToIndex` lands at the estimated offset, FlatList renders the items in the new window. Their actual `onLayout` events update internal layout, and any visual drift self-corrects. The target message will be visible regardless of estimate accuracy.
79
-
80
- **Why this works with `inverted={true}`:** FlatList handles inversion internally via a `scaleY: -1` transform. `getItemLayout` operates in logical coordinates (data array index 0 = newest message, last index = oldest). The framework flips the visual axis. No special inversion math needed in `getItemLayout`.
81
-
82
- **Code:**
83
- ```typescript
84
- // Add near other useCallback definitions (~line 970)
85
- const getItemLayout = useCallback((_data: any, index: number) => ({
86
- length: AVERAGE_ITEM_LENGTH, // 120 — existing constant
87
- offset: AVERAGE_ITEM_LENGTH * index,
88
- index,
89
- }), []);
90
- ```
91
-
92
- **FlatList prop:**
93
- ```tsx
94
- <FlatList
95
- ...existing props...
96
- getItemLayout={getItemLayout}
97
- />
98
- ```
99
-
100
- **Impact:** `scrollToIndex` works on the first call without polling, retries, or `onScrollToIndexFailed`.
101
-
102
- ---
103
-
104
- ### Change B — `itemPositions` State → Ref
105
-
106
- **Why:** `itemPositions` is read **only imperatively** — inside `scrollToMessage` and `handleScrollToIndexFailed`. It is never read during render. Storing it in state causes 16-100 re-renders during navigation as `onLayout` fires for each row. A ref provides identical functionality with zero re-renders.
107
-
108
- **Code changes:**
109
-
110
- ```typescript
111
- // REPLACE (line ~969)
112
- // const [itemPositions, setItemPositions] = useState<Map<string, { y: number; height: number }>>(new Map());
113
-
114
- // WITH
115
- const itemPositionsRef = useRef<Map<string, { y: number; height: number }>>(new Map());
116
- ```
117
-
118
- ```typescript
119
- // REPLACE handleItemLayout (line ~4624)
120
- // Before: state update + Map allocation per onLayout
121
- const handleItemLayout = useCallback((event: any, messageId: string) => {
122
- const { y, height } = event.nativeEvent.layout;
123
- setItemPositions(prev => {
124
- const newMap = new Map(prev);
125
- newMap.set(messageId, { y, height });
126
- return newMap;
127
- });
128
- }, []);
129
-
130
- // After: pure ref mutation
131
- const handleItemLayout = useCallback((event: any, messageId: string) => {
132
- const { y, height } = event.nativeEvent.layout;
133
- itemPositionsRef.current.set(messageId, { y, height });
134
- }, []);
135
- ```
136
-
137
- ```typescript
138
- // REPLACE clear effect (line ~4610)
139
- // Before: clears on every length change > 5
140
- useEffect(() => {
141
- const lengthDiff = Math.abs(messagesList.length - prevMessagesLength.current);
142
- const isSignificantChange = lengthDiff > 5;
143
- if (isSignificantChange) {
144
- setItemPositions(new Map());
145
- }
146
- prevMessagesLength.current = messagesList.length;
147
- }, [messagesList.length]);
148
-
149
- // After: skip clear during navigation (preserves measurements just collected)
150
- useEffect(() => {
151
- if (navigationInProgressRef.current) {
152
- prevMessagesLength.current = messagesList.length;
153
- return;
154
- }
155
- const lengthDiff = Math.abs(messagesList.length - prevMessagesLength.current);
156
- const isSignificantChange = lengthDiff > 5;
157
- if (isSignificantChange) {
158
- itemPositionsRef.current = new Map();
159
- }
160
- prevMessagesLength.current = messagesList.length;
161
- }, [messagesList.length]);
162
- ```
163
-
164
- **Update read sites:**
165
- - `scrollToMessage`: `itemPositions.get(...)` → `itemPositionsRef.current.get(...)`
166
- - `handleScrollToIndexFailed`: `Array.from(itemPositions.values())` → `Array.from(itemPositionsRef.current.values())`
167
- - Remove `itemPositions` from `handleScrollToIndexFailed` `useCallback` deps array
168
-
169
- **Impact:** Eliminates 16–100 re-renders per navigation. `onLayout` becomes effectively free.
170
-
171
- ---
172
-
173
- ### Change C — Simplified `scrollToMessage` (No Polling, Loop-Safe)
174
-
175
- **Why:** With `getItemLayout` (Change A), `scrollToIndex` works synchronously. The 5-retry polling loop is dead code. The new implementation:
176
- 1. Finds target index in `messagesContentListRef.current` (O(n) — could be O(1) with index map, but list is ≤ 101 items so O(n) is < 1ms)
177
- 2. Calls `scrollToIndex` once
178
- 3. Defers highlight + gate-close to next frame via `requestAnimationFrame` (waits for FlatList commit)
179
- 4. Has a **retry guard** (`triedFetchForRef`) to prevent infinite loop when target message doesn't exist (deleted/missing)
180
-
181
- **Code:**
182
-
183
- ```typescript
184
- // New ref (add near other refs ~line 974)
185
- const triedFetchForRef = useRef<string | null>(null);
186
-
187
- // REPLACE scrollToMessage (lines ~1469-1551)
188
- const scrollToMessage = (messageId: string) => {
189
- if (!messageListRef.current || messagesContentListRef.current.length === 0) {
190
- setNavigationLoading(false);
191
- navigationInProgressRef.current = false;
192
- return;
193
- }
194
-
195
- setNavigationLoading(true);
196
-
197
- const targetIndex = messagesContentListRef.current.findIndex(
198
- (msg) => String(msg.getId()) === messageId
199
- );
200
-
201
- if (targetIndex === -1) {
202
- // Message not in current list. Avoid infinite loop:
203
- // if we already fetched once for this messageId and target still missing,
204
- // it means the message doesn't exist (deleted/stale).
205
- if (triedFetchForRef.current === messageId) {
206
- triedFetchForRef.current = null;
207
- setListState("error");
208
- setNavigationLoading(false);
209
- navigationInProgressRef.current = false;
210
- return;
211
- }
212
- triedFetchForRef.current = messageId;
213
- setNavigationLoading(false);
214
- getMessagesAroundId(messageId);
215
- return;
216
- }
217
-
218
- // Found target. Reset retry tracker.
219
- triedFetchForRef.current = null;
220
-
221
- // Single scrollToIndex call. getItemLayout makes this work without
222
- // requiring the target to be already rendered.
223
- messageListRef.current.scrollToIndex({
224
- index: targetIndex,
225
- animated: false, // instant jump — correct UX for "go to message"
226
- viewPosition: 0.5, // center on viewport
227
- });
228
-
229
- // Defer highlight + gate-close to next frame so FlatList commits
230
- // the new viewport and target row mounts before we apply highlight.
231
- requestAnimationFrame(() => {
232
- if (!shouldSuppressHighlightRef.current) {
233
- highlightMessage(messageId);
234
- }
235
- shouldSuppressHighlightRef.current = false;
236
- setNavigationLoading(false);
237
- navigationInProgressRef.current = false;
238
- });
239
- };
240
- ```
241
-
242
- **Why `animated: false`:** Search-to-message navigation can target a message thousands back. Animating through them visually is wrong UX (looks like rapid auto-scroll), takes seconds, and matches no production chat app. WhatsApp, Telegram, Slack, Discord all do instant jump.
243
-
244
- **Impact:** Function shrinks from ~80 lines to ~35 lines. Polling time drops from 1500ms to 0ms.
245
-
246
- ---
247
-
248
- ### Change D — Navigation Gate (`navigationInProgressRef`)
249
-
250
- **Why:** Even with 101 messages filling the screen (Change E), there's a window between `setMessagesList` and `scrollToIndex` where FlatList might fire `onEndReached` from its initial measurement pass. The gate guarantees zero pagination calls during navigation, regardless of timing.
251
-
252
- **Code:**
253
-
254
- ```typescript
255
- // New ref (add near other refs ~line 974)
256
- const navigationInProgressRef = useRef<boolean>(false);
257
- ```
258
-
259
- **Set gate at start of `getMessagesAroundId`:**
260
- ```typescript
261
- const getMessagesAroundId = async (messageId: string) => {
262
- // ...existing guards (fetchingAroundIdRef, isAgenticUser)...
263
-
264
- fetchingAroundIdRef.current = messageId;
265
- navigationInProgressRef.current = true; // ← ADD: gate closed
266
- // ...rest of function...
267
- };
268
- ```
269
-
270
- **Clear gate is handled inside `scrollToMessage`'s `requestAnimationFrame` (Change C) — single rAF, not duplicated. All early-exit paths in `scrollToMessage` also clear it (see Change C code).**
271
-
272
- **Failsafe in `getMessagesAroundId` finally block:**
273
- ```typescript
274
- let scrollScheduled = false;
275
- try {
276
- // ...fetch logic, build allMessages...
277
- if (allMessages.length > 0) {
278
- messagesContentListRef.current = allMessages;
279
- setMessagesList(allMessages);
280
- setScrollTargetId(messageId);
281
- scrollScheduled = true;
282
- }
283
- } catch (error) {
284
- setListState("error");
285
- onError && onError(error as CometChat.CometChatException);
286
- } finally {
287
- fetchingAroundIdRef.current = null;
288
- // If scroll wasn't scheduled (empty results / error), gate must be cleared
289
- // here because scrollToMessage will never run.
290
- if (!scrollScheduled) {
291
- navigationInProgressRef.current = false;
292
- setNavigationLoading(false);
293
- }
294
- }
295
- ```
296
-
297
- **Guards in pagination functions:**
298
- ```typescript
299
- // At top of getPreviousMessages (~line 1057)
300
- if (navigationInProgressRef.current) {
301
- loadingPrevMessagesRef.current = false;
302
- return;
303
- }
304
-
305
- // At top of fetchNextMessages (~line 4382)
306
- if (navigationInProgressRef.current) return;
307
- ```
308
-
309
- **Impact:** Zero `onEndReached` cascade calls during navigation. Belt-and-suspenders with Change E's full screen fill.
310
-
311
- ---
312
-
313
- ### Change E — Parallel Fetch with Partial Failure Tolerance
314
-
315
- **Why:** Three improvements over current code:
316
- 1. **Drop `getMessageDetails`** — target message is included in `fetchNext` response
317
- 2. **`Promise.allSettled` instead of `Promise.all`** — partial network failure (e.g. `fetchNext` times out) still shows the user useful context from the successful direction
318
- 3. **`limit: 50` both directions** — fills any phone screen (max ~25 messages visible) regardless of message height variance, eliminating `onEndReached` cascade by data alone
319
-
320
- **Code (replace inside `getMessagesAroundId`):**
321
-
322
- ```typescript
323
- // Build BOTH request builders (inside getMessagesAroundId)
324
- const targetMessageId = Number(messageId);
325
-
326
- const buildRequest = (limit: number) => {
327
- let req = new CometChat.MessagesRequestBuilder()
328
- .setLimit(limit)
329
- .setMessageId(targetMessageId);
330
-
331
- if (user) req = req.setUID(user.getUid());
332
- if (group) req = req.setGUID(group.getGuid());
333
-
334
- if (!parentMessageId) {
335
- req = req.hideReplies(true);
336
- } else {
337
- req = req.setParentMessageId(Number(parentMessageId)).hideReplies(false);
338
- if (isAgenticUser) {
339
- req = req.withParent(true);
340
- }
341
- }
342
- return req.build();
343
- };
344
-
345
- // Fire both in parallel
346
- const [prevResult, nextResult] = await Promise.allSettled([
347
- buildRequest(50).fetchPrevious(),
348
- buildRequest(50).fetchNext(),
349
- ]);
350
-
351
- const previousMessages = prevResult.status === 'fulfilled' ? prevResult.value : [];
352
- const nextMessages = nextResult.status === 'fulfilled' ? nextResult.value : [];
353
-
354
- // Hard fail only if BOTH directions failed
355
- if (prevResult.status === 'rejected' && nextResult.status === 'rejected') {
356
- setListState("error");
357
- setNavigationLoading(false);
358
- navigationInProgressRef.current = false;
359
- fetchingAroundIdRef.current = null;
360
- onError && onError(prevResult.reason as CometChat.CometChatException);
361
- return;
362
- }
363
-
364
- // Combine + dedup. fetchNext includes the target message itself.
365
- // Both responses come oldest-first; reverse for inverted FlatList (newest-first).
366
- const seenIds = new Set<string>();
367
- const allMessages: CometChat.BaseMessage[] = [];
368
-
369
- const pushIfNew = (msg: CometChat.BaseMessage) => {
370
- const id = String(msg.getId());
371
- if (!seenIds.has(id)) {
372
- seenIds.add(id);
373
- allMessages.push(msg);
374
- }
375
- };
376
-
377
- // Reverse next first (target is at index 0 of next, will end up newest in inverted list)
378
- [...nextMessages].reverse().forEach(pushIfNew);
379
- // Then prev (these are older, end up at the bottom of inverted list)
380
- [...previousMessages].reverse().forEach(pushIfNew);
381
-
382
- // allMessages is now newest-first, ready for inverted FlatList
383
- // Update message request builder for future pagination
384
- msgRequestBuilder.current?.setMessageId(targetMessageId);
385
- if (!parentMessageId) msgRequestBuilder.current?.hideReplies(true);
386
- messageRequest.current = msgRequestBuilder.current?.build() || null;
387
- ```
388
-
389
- **Why limit 50:** SDK supports up to 50 per request. 50 + 50 = 100 surrounding messages + target. No phone screen shows more than 25 messages. This single change makes `onEndReached` impossible during navigation.
390
-
391
- **Why dedup uses string IDs:** Consistent with `scrollToMessage` lookup which uses `String(msg.getId())`. Avoids any number/string coercion subtlety in the `Set`.
392
-
393
- **Impact:** 3 sequential calls → 2 parallel calls. Total latency drops from `t1 + t2 + t3` to `max(t1, t2)`. Partial failure now degrades gracefully instead of erroring.
394
-
395
- ---
396
-
397
- ## 4. Final Flow (Optimized)
398
-
399
- ```
400
- User taps search result
401
- → navigate('Messages', { messageId, navigatedFromSearch: true })
402
- → CometChatMessageList mounts
403
- → getMessagesAroundId(messageId)
404
- navigationInProgressRef = true [gate closed]
405
- Promise.allSettled([fetchPrev(50), fetchNext(50)]) [2 parallel calls]
406
- ↓ ~300ms (network-bound, single round trip)
407
- both rejected? → error, gate cleared, exit
408
- else → dedup → allMessages (up to 101 msgs)
409
- messagesContentListRef.current = allMessages
410
- setMessagesList(allMessages) [render #1, only render]
411
- setScrollTargetId(messageId)
412
- scrollScheduled = true (finally won't reset gate)
413
-
414
- useEffect[messagesList.length] fires
415
- → navigationInProgressRef.current === true → SKIP clear [position cache preserved]
416
-
417
- useEffect[scrollTargetId, messagesList.length] fires (next frame)
418
- → requestAnimationFrame → scrollToMessage(scrollTargetId)
419
- → setScrollTargetId(null)
420
-
421
- scrollToMessage:
422
- → targetIndex = findIndex(...) [O(n), n ≤ 101, < 1ms]
423
- → triedFetchForRef = null (target found)
424
- → scrollToIndex({ index, animated: false, viewPosition: 0.5 })
425
- [synchronous, getItemLayout backed]
426
- → requestAnimationFrame: [waits for FlatList commit]
427
- highlightMessage(messageId)
428
- setNavigationLoading(false)
429
- navigationInProgressRef.current = false [gate open]
430
-
431
- onLayout × 101 fires anywhere in this flow
432
- → itemPositionsRef.current.set(...) [0 state updates, 0 re-renders]
433
-
434
- onEndReached fires anytime gate is closed
435
- → blocked, returns immediately
436
-
437
- User scrolls up later
438
- → onEndReached fires (gate now open) → normal pagination resumes
439
- ```
440
-
441
- ---
442
-
443
- ## 5. Before vs After Metrics
444
-
445
- | Metric | Before | After |
446
- |---|---|---|
447
- | Network calls | 3+ sequential | 2 parallel |
448
- | Round trips | 3+ | 1 |
449
- | Messages fetched | 16 | up to 101 |
450
- | State updates during nav | 50–80 | 2 (`setMessagesList`, `setScrollTargetId`) |
451
- | Re-renders from `onLayout` | 1 per message | 0 |
452
- | Polling time | up to 1500ms | 0 |
453
- | `onEndReached` cascade | 2-3 cycles | 0 |
454
- | Time to target visible (4G) | 1500–3000ms | ~360ms |
455
- | Time to target visible (3G) | 3000–8000ms or freeze | ~700ms |
456
- | Hermes Android crash risk | High | None |
457
- | Partial network failure | Hard error | Graceful degradation |
458
-
459
- ---
460
-
461
- ## 6. Edge Cases (Final)
462
-
463
- ### EC-1 — Target is first message in conversation
464
- `fetchPrevious(50)` → 0 messages. `fetchNext(50)` → target + up to 49 newer. allMessages = up to 50 messages with target at the bottom of the inverted list. `scrollToIndex` works.
465
-
466
- ### EC-2 — Target is most recent message
467
- `fetchNext(50)` → target only. `fetchPrevious(50)` → 50 older. allMessages = 51 messages with target at index 0. `scrollToIndex(0)` puts target at viewport bottom (visual top of inverted list). Correct.
468
-
469
- ### EC-3 — Target message deleted / doesn't exist
470
- `fetchPrevious` and `fetchNext` succeed but neither contains the target ID. `scrollToMessage` finds `targetIndex === -1`. Since `triedFetchForRef.current !== messageId` (first attempt), it calls `getMessagesAroundId` again. The second call hits the `fetchingAroundIdRef.current === messageId` guard — but wait, that guard is reset in the `finally`. So the second `getMessagesAroundId` runs, fetches the same empty result, sets list, triggers `scrollToMessage` again. This time `triedFetchForRef.current === messageId` → graceful error state. Loop bounded to 1 retry max.
471
-
472
- ### EC-4 — Target is a thread reply
473
- `parentMessageId` set on both request builders. `fetchNext` returns thread replies only. Same flow.
474
-
475
- ### EC-5 — `getItemLayout` estimate inaccurate
476
- `scrollToIndex` lands at estimated offset. Actual rendered heights self-correct via FlatList's internal layout. Target may be slightly off-center but visible. The `itemPositionsRef` data (populated by `onLayout`) is available for optional precision correction in a future enhancement, but not required for correctness.
477
-
478
- ### EC-6 — `onScrollToIndexFailed` fires
479
- Only possible if FlatList's window calculations fail despite `getItemLayout`. Existing handler scrolls to estimated offset and retries. Improved by accurate per-item average from `itemPositionsRef`.
480
-
481
- ### EC-7 — User taps two messages in rapid succession
482
- First navigation in flight. Second tap → second `getMessagesAroundId` call → blocked by `fetchingAroundIdRef.current === messageId` (different IDs, so this guard doesn't block). Actually checking: the guard is `if (fetchingAroundIdRef.current === messageId) return` — same-ID only. Different ID will proceed. **Risk:** two concurrent `getMessagesAroundId` calls can race on `messagesContentListRef.current`.
483
-
484
- **Mitigation:** Tighten the guard:
485
- ```typescript
486
- // Original
487
- if (fetchingAroundIdRef.current === messageId) return;
488
-
489
- // Tightened (any in-flight fetch blocks)
490
- if (fetchingAroundIdRef.current !== null) return;
491
- ```
492
-
493
- ### EC-8 — One direction fails, other succeeds
494
- `Promise.allSettled` returns mixed result. The successful direction's messages are used. `allMessages` is built from whatever was fetched. If target was in the failed direction (rare — target is in `fetchNext`), `targetIndex === -1` triggers EC-3 retry path.
495
-
496
- ### EC-9 — Both directions fail
497
- Hard error: `setListState("error")`, gate cleared, `onError(prevResult.reason)`. Existing error UI shown.
498
-
499
- ### EC-10 — Long messages (image, 50 reactions, multi-line)
500
- Estimate underestimates height. `scrollToIndex` lands above target. FlatList's onLayout corrects after render. Target visible, may be slightly off-center.
501
-
502
- ### EC-11 — Normal conversation open (no `goToMessageId`)
503
- `getMessagesAroundId` never called. `navigationInProgressRef` stays false. `getPreviousMessages` runs normally (gate not blocking). `scrollToMessage` never called. **Zero behavior change for non-search flows.**
504
-
505
- ### EC-12 — Agentic user (non-thread)
506
- Existing `if (isAgenticUser && !parentMessageId) return;` guard runs first. All navigation logic skipped.
507
-
508
- ### EC-13 — Highlight applied before component mounts
509
- Resolved by Change C — `highlightMessage` is inside `requestAnimationFrame` which fires after FlatList commits the new viewport. Target row is in render tree.
510
-
511
- ### EC-14 — `onEndReached` from old viewport during scroll commit
512
- Resolved by Change C — gate stays closed until inside the `requestAnimationFrame` after `scrollToIndex`. The pre-commit `onEndReached` (if any) finds gate closed and returns.
513
-
514
- ### EC-15 — Position cache wiped after `setMessagesList(101)`
515
- Resolved by Change B — clear effect skips when `navigationInProgressRef.current === true`. Cache retained.
516
-
517
- ### EC-16 — `maintainVisibleContentPosition` interaction
518
- Current FlatList has `maintainVisibleContentPosition={{ minIndexForVisible: 0 }}`. This preserves index-0 position during list mutations. During navigation, the list goes from `[]` to 101 items — `minIndexForVisible: 0` means "preserve newest message position" which is the default scroll position anyway. `scrollToIndex` overrides this. No conflict observed in practice. **No change needed.**
519
-
520
- ### EC-17 — `getMessagesAroundId` called twice rapidly with different IDs
521
- Tightened guard from EC-7: `if (fetchingAroundIdRef.current !== null) return;` blocks the second call entirely. The user must wait for the first navigation to complete. UX: search results panel typically auto-closes on tap, preventing rapid taps in practice.
522
-
523
- ---
524
-
525
- ## 7. Files Changed
526
-
527
- | File | Changes | Risk |
528
- |---|---|---|
529
- | `CometChatMessageList.tsx` | Add `getItemLayout` to FlatList | Low |
530
- | `CometChatMessageList.tsx` | `itemPositions` state → `itemPositionsRef` useRef | Low |
531
- | `CometChatMessageList.tsx` | Skip clear effect during navigation | Low |
532
- | `CometChatMessageList.tsx` | Simplified `scrollToMessage` with `triedFetchForRef` retry guard | Low |
533
- | `CometChatMessageList.tsx` | Add `navigationInProgressRef` gate in 3 locations | Very Low |
534
- | `CometChatMessageList.tsx` | `Promise.allSettled` + dedup + drop `getMessageDetails` | Low |
535
- | `CometChatMessageList.tsx` | Tighten `fetchingAroundIdRef` guard (EC-7) | Very Low |
536
-
537
- **No other files. No prop changes. No API changes.**
538
-
539
- ---
540
-
541
- ## 8. Implementation Order
542
-
543
- | Step | Change | Why This Order |
544
- |---|---|---|
545
- | 1 | B: `itemPositions` → ref | Eliminates re-render storm. Self-contained. No dependencies on other changes. |
546
- | 2 | A: Add `getItemLayout` | Unlocks `scrollToIndex` for Change C. |
547
- | 3 | D: Add `navigationInProgressRef` (declaration only) | Required by Change C and B. |
548
- | 4 | C: Simplified `scrollToMessage` + retry guard | Depends on A and D being in place. |
549
- | 5 | D: Apply gate guards in `getPreviousMessages` and `fetchNextMessages` | After Change C so all rAF cleanup paths exist. |
550
- | 6 | E: `Promise.allSettled` + 50 limit + dedup + drop `getMessageDetails` | Most logic-heavy change. Last for easy isolation. |
551
- | 7 | EC-7 tighten: `fetchingAroundIdRef !== null` | Single-line change. Trivial. |
552
-
553
- Each step is independently revertable. After each step the code compiles and the search nav still works (degraded but not broken).
554
-
555
- ---
556
-
557
- ## 9. Testing Matrix
558
-
559
- | Scenario | Expected |
560
- |---|---|
561
- | Search → tap message in 1000+ msg group (Android) | Target visible < 500ms, no crash |
562
- | Search → tap message in 1000+ msg group (iOS) | Target visible < 500ms |
563
- | Search → tap very old message (10000+ msgs back) | Target visible, no cascade |
564
- | Search → tap thread reply | Thread view, target highlighted |
565
- | Search → tap deleted message | Error state after one retry |
566
- | Search → tap two messages rapidly | Second tap blocked, first completes |
567
- | Network OK, both directions | Full 101 msg context |
568
- | Network: only `fetchPrevious` succeeds | 50 prev shown, target found if in cached state else error |
569
- | Network: only `fetchNext` succeeds | 50 next + target shown |
570
- | Network: both fail | Error state, retry possible |
571
- | Normal conversation open (no search) | Identical to before |
572
- | Send message during navigation | Appears after navigation completes |
573
- | Receive message during navigation | Buffered, shown after, no crash |
574
- | Scroll up after navigation | Pagination resumes |
575
- | Scroll down after navigation | `fetchNextMessages` resumes |
576
- | Agentic user chat | No behavior change |
577
- | `onEndReached` fires during scroll commit | Blocked by gate |
578
- | Position cache after navigation | Retained, smooth subsequent scroll |
579
- | Highlight on far target (index 80) | Animation plays via rAF |
580
- | Long message / image / reactions | Visible (may be slightly off-center) |
581
-
582
- ---
583
-
584
- ## 10. Rollback
585
-
586
- Each change is independent and revertable in isolation:
587
-
588
- - **B:** Restore `useState` for `itemPositions`, restore `setItemPositions` calls
589
- - **A:** Remove `getItemLayout` prop
590
- - **C:** Restore polling `scrollToMessage` with retry loop
591
- - **D:** Remove `navigationInProgressRef` and 3 usage sites
592
- - **E:** Restore `getMessageDetails` + sequential `fetchNext`
593
- - **EC-7 tighten:** Restore same-ID guard
594
-
595
- No DB changes. No API changes. No prop changes. Pure internal refactor.
596
-
597
- ---
598
-
599
- ## 11. What Was Considered and Rejected
600
-
601
- | Idea | Why Rejected |
602
- |---|---|
603
- | `initialScrollIndex` instead of `scrollToIndex` | Requires target index known at FlatList mount, but `messagesContentListRef.current` is empty until after fetch. Restructuring component for this saves ~16ms but adds complexity. Not worth it. |
604
- | Custom `getItemLayout` with dynamic average from `itemPositionsRef` | Would be recomputed on every FlatList query, hurting performance. Constant `AVERAGE_ITEM_LENGTH` is good enough — corrections happen post-render. |
605
- | Sliding window cap (trim to 300 msgs) | Current memory cap is 500 msgs, no OOM observed. 101 messages is well within bounds. Adds complexity for no measurable gain. |
606
- | Eliminate `setScrollTargetId` indirection | The `useEffect` ensures scroll fires AFTER FlatList renders. Removing it requires a microtask + rAF dance with brittle timing. The state-effect pattern is robust. |
607
- | `Promise.race` to scroll on first response | Would scroll before `prev` arrives, causing layout jump when prev appends. `Promise.allSettled` waits for both, single render, no jump. |
608
- | Disable `maintainVisibleContentPosition` during navigation | Adds conditional prop → re-render. No observed conflict in practice. Skip. |
609
- | Pre-warming the conversation cache on search results render | Requires SDK changes. Out of scope. |
610
-
611
- ---
612
-
613
- **End of plan v3.**