chore: paginated thread message list#40998
Conversation
|
Looks like this PR is not ready to merge, because of the following issues:
Please fix the issues and try again If you have any trouble, please check the PR guidelines |
|
WalkthroughAdds ChangesThread Message Infinite Pagination & Deep-Link Jump
Sequence Diagram(s)sequenceDiagram
participant User
participant ThreadMessageList
participant useThreadMessagesQuery
participant chat.getThreadMessages
participant Messages
User->>ThreadMessageList: opens thread with ?msg=targetId
ThreadMessageList->>useThreadMessagesQuery: loadMessageAround(targetId)
useThreadMessagesQuery->>chat.getThreadMessages: GET ?tmid&aroundId=targetId
chat.getThreadMessages->>Messages: findOne(targetId)
chat.getThreadMessages->>Messages: countDocuments({tmid, ts < target.ts})
chat.getThreadMessages->>Messages: findPaginated(skip: resolvedOffset)
Messages-->>chat.getThreadMessages: page
chat.getThreadMessages-->>useThreadMessagesQuery: {items, itemCount, offset}
useThreadMessagesQuery-->>ThreadMessageList: seeded infinite cache
User->>ThreadMessageList: scrolls near top/bottom
ThreadMessageList->>useThreadMessagesQuery: fetchPreviousPage / fetchNextPage
useThreadMessagesQuery->>chat.getThreadMessages: GET ?tmid&offset=pageOffset
chat.getThreadMessages-->>useThreadMessagesQuery: adjacent page
useThreadMessagesQuery-->>ThreadMessageList: prepend / append messages
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested labels
Suggested reviewers
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Warning Review ran into problems🔥 ProblemsErrors were encountered while retrieving linked issues. Errors (2)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## develop #40998 +/- ##
===========================================
+ Coverage 70.13% 70.14% +0.01%
===========================================
Files 3368 3368
Lines 130022 130112 +90
Branches 22582 22602 +20
===========================================
+ Hits 91191 91272 +81
+ Misses 35519 35509 -10
- Partials 3312 3331 +19
Flags with carried forward coverage won't be shown. Click here to find out more. 🚀 New features to boost your workflow:
|
64ed595 to
53210d1
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
apps/meteor/app/api/server/v1/chat.ts (1)
1157-1187: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winCount
beforefrom the same filtered dataset you paginate.Line 1166 ignores
query, but Lines 1172-1179 page over{ ...query, tmid }. With any caller-supplied filter,resolvedOffsetcan point past the target window, and theoffsetreturned on Line 1187 no longer matches the filteredtotal. Build the “before” count from the same base predicate used byfindPaginated.Suggested fix
- let resolvedOffset = offset; - let resolvedSort = sort || { ts: 1 }; + const threadQuery = { ...query, tmid }; + let resolvedOffset = offset; + let resolvedSort = sort || { ts: 1 }; if (aroundId) { resolvedSort = { ts: 1 }; if (aroundId === tmid) { resolvedOffset = 0; } else { const target = await Messages.findOneById(aroundId, { projection: { ts: 1, tmid: 1 } }); if (target?.tmid === tmid && target.ts) { - const before = await Messages.countDocuments({ tmid, ts: { $lt: target.ts } }); + const before = await Messages.countDocuments({ + $and: [threadQuery, { ts: { $lt: target.ts } }], + }); resolvedOffset = Math.max(0, before - Math.floor(count / 2)); } } } const { cursor, totalCount } = Messages.findPaginated( - { ...query, tmid }, + threadQuery,🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/meteor/app/api/server/v1/chat.ts` around lines 1157 - 1187, The offset calculation in the aroundId branch is using a different dataset than the pagination query, so `resolvedOffset` can become inconsistent with the returned window and total. Update the `before` count in `chat.ts` so it is computed from the same base predicate passed to `Messages.findPaginated` for the current `tmid` plus any caller-supplied `query` filters, keeping `resolvedOffset`, `messages`, and `totalCount` aligned. Use the existing `resolvedOffset`, `resolvedSort`, and `Messages.findPaginated` flow as the anchor when making this change.
🧹 Nitpick comments (1)
apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts (1)
39-41: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winRemove the implementation comment.
Please move this rationale to a helper name, PR notes, or documentation instead of inline implementation comments. As per coding guidelines,
**/*.{ts,tsx,js}should avoid code comments in the implementation.🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts` around lines 39 - 41, Remove the inline implementation comment from useThreadMessagesQuery and keep the rationale out of the code. If needed, preserve the explanation in a helper name, PR notes, or external documentation instead of the comment near the REST fallback to readThreads. Focus the change around the useThreadMessagesQuery hook and the fallback logic it documents.Source: Coding guidelines
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@apps/meteor/client/views/room/contextualBar/Threads/components/ThreadMessageList.tsx`:
- Around line 113-121: `isPrepend` is being cleared too early by the no-deps
`useLayoutEffect` in `ThreadMessageList`, so the commit that actually prepends
the previous page can lose the anchor shift. Update the reset logic so
`isPrepend.current` stays true through the fetching render and is only cleared
after the prepended messages have committed, using the existing
`onScroll`/commit flow and the `ThreadMessageList` rendering state rather than
an unconditional layout effect reset. Also remove the implementation comments in
this area to match the coding guideline.
- Around line 146-151: The deep-link load in ThreadMessageList’s jump handling
can fail silently and leave loadingWindowKeyRef stuck, blocking retries. Update
the logic around loadMessageAround(msgJumpParam) so failures are caught and
handled (for example by resetting loadingWindowKeyRef.current when the promise
rejects) and ensure the load can be attempted again on subsequent jumps; use the
jump-loading block in ThreadMessageList and the loadMessageAround call as the
key spots to fix.
In
`@apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts`:
- Line 49: The `count` value in `useThreadMessagesQuery` can become `NaN` or `0`
when `getConfig('threadMessagesSize', 50)` returns an invalid string, which
breaks pagination math. Update the `count` assignment to validate the parsed
value and fall back to a safe positive default when parsing fails or yields a
non-positive number. Make the fix in `useThreadMessagesQuery` so the values used
by `offset + count`, `getNextPageParam`, and `getPreviousPageParam` are always
valid.
---
Outside diff comments:
In `@apps/meteor/app/api/server/v1/chat.ts`:
- Around line 1157-1187: The offset calculation in the aroundId branch is using
a different dataset than the pagination query, so `resolvedOffset` can become
inconsistent with the returned window and total. Update the `before` count in
`chat.ts` so it is computed from the same base predicate passed to
`Messages.findPaginated` for the current `tmid` plus any caller-supplied `query`
filters, keeping `resolvedOffset`, `messages`, and `totalCount` aligned. Use the
existing `resolvedOffset`, `resolvedSort`, and `Messages.findPaginated` flow as
the anchor when making this change.
---
Nitpick comments:
In
`@apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts`:
- Around line 39-41: Remove the inline implementation comment from
useThreadMessagesQuery and keep the rationale out of the code. If needed,
preserve the explanation in a helper name, PR notes, or external documentation
instead of the comment near the REST fallback to readThreads. Focus the change
around the useThreadMessagesQuery hook and the fallback logic it documents.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: b462bba9-3603-4bd7-b932-c98a17807695
📒 Files selected for processing (5)
apps/meteor/app/api/server/v1/chat.tsapps/meteor/client/lib/utils/threadMessageUtils.tsapps/meteor/client/views/room/contextualBar/Threads/components/ThreadMessageList.tsxapps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.tspackages/rest-typings/src/v1/chat.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (2)
- GitHub Check: 📦 Build Packages
- GitHub Check: Hacktron Security Check
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}
📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)
**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation
Files:
packages/rest-typings/src/v1/chat.tsapps/meteor/app/api/server/v1/chat.tsapps/meteor/client/views/room/contextualBar/Threads/components/ThreadMessageList.tsxapps/meteor/client/lib/utils/threadMessageUtils.tsapps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
🧠 Learnings (9)
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.
Applied to files:
packages/rest-typings/src/v1/chat.tsapps/meteor/app/api/server/v1/chat.tsapps/meteor/client/lib/utils/threadMessageUtils.tsapps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.
Applied to files:
packages/rest-typings/src/v1/chat.tsapps/meteor/app/api/server/v1/chat.tsapps/meteor/client/lib/utils/threadMessageUtils.tsapps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
📚 Learning: 2026-05-06T12:21:44.083Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 40256
File: apps/meteor/client/components/CreateDiscussion/CreateDiscussion.tsx:121-149
Timestamp: 2026-05-06T12:21:44.083Z
Learning: Field wrappers in rocket.chat/fuselage-forms (Field, FieldLabel, FieldRow, FieldError, FieldHint) auto-create htmlFor/id associations, aria-describedby, and role="alert" for errors. Do not manually set htmlFor, id, aria-describedby, or role attributes when using these wrappers. This automatic wiring does not apply to plain rocket.chat/fuselage components, which require explicit ID wiring per the accessibility docs. In code reviews, prefer using fuselage-forms wrappers for form fields and verify there is no unnecessary manual ID/aria wiring in files that use these wrappers. If a component uses plain fuselage components, ensure proper id wiring as per docs.
Applied to files:
packages/rest-typings/src/v1/chat.tsapps/meteor/app/api/server/v1/chat.tsapps/meteor/client/views/room/contextualBar/Threads/components/ThreadMessageList.tsxapps/meteor/client/lib/utils/threadMessageUtils.tsapps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
📚 Learning: 2026-05-11T23:14:59.316Z
Learnt from: ricardogarim
Repo: RocketChat/Rocket.Chat PR: 40469
File: packages/rest-typings/src/v1/users.ts:337-337
Timestamp: 2026-05-11T23:14:59.316Z
Learning: In Rocket.Chat REST endpoint typings (e.g., packages/rest-typings/src/v1/users.ts and other rest-typings files), keep the established convention of deriving field types from the domain model (e.g., use IUser indexed access like IUser['statusExpiresAt']) rather than swapping individual fields to serialized primitives (like string) in an ad-hoc way. If a truly different “serialized” representation is needed, perform the refactor consistently across the codebase (not just a single endpoint/field) and ensure all related REST typings stay aligned with the shared serialization types.
Applied to files:
packages/rest-typings/src/v1/chat.ts
📚 Learning: 2026-02-23T17:53:06.802Z
Learnt from: ggazzo
Repo: RocketChat/Rocket.Chat PR: 35995
File: apps/meteor/app/api/server/v1/rooms.ts:1107-1112
Timestamp: 2026-02-23T17:53:06.802Z
Learning: During PR reviews that touch endpoint files under apps/meteor/app/api/server/v1, enforce strict scope: if a PR targets a specific endpoint (e.g., rooms.favorite), do not propose changes to unrelated endpoints (e.g., rooms.invite) unless maintainers explicitly request them. Focus feedback on the touched endpoint's behavior, API surface, and related tests; avoid broad cross-endpoint changes in the same PR unless requested.
Applied to files:
apps/meteor/app/api/server/v1/chat.ts
📚 Learning: 2026-02-24T19:09:01.522Z
Learnt from: ahmed-n-abdeltwab
Repo: RocketChat/Rocket.Chat PR: 38974
File: apps/meteor/app/api/server/v1/im.ts:220-221
Timestamp: 2026-02-24T19:09:01.522Z
Learning: In Rocket.Chat OpenAPI migration PRs for endpoints under apps/meteor/app/api/server/v1, avoid introducing logic changes. Only perform scope-tight changes that preserve behavior; style-only cleanups (e.g., removing inline comments) may be deferred to follow-ups to keep the migration PR focused.
Applied to files:
apps/meteor/app/api/server/v1/chat.ts
📚 Learning: 2026-03-27T14:52:56.865Z
Learnt from: dougfabris
Repo: RocketChat/Rocket.Chat PR: 39892
File: apps/meteor/client/views/room/contextualBar/Threads/Thread.tsx:150-155
Timestamp: 2026-03-27T14:52:56.865Z
Learning: In Rocket.Chat, there are two different `ModalBackdrop` components with different prop APIs. During review, confirm the import source: (1) `rocket.chat/fuselage` `ModalBackdrop` uses `ModalBackdropProps` based on `BoxProps` (so it supports `onClick` and other Box/DOM props) and does not have an `onDismiss` prop; (2) `rocket.chat/ui-client` `ModalBackdrop` uses a narrower props interface like `{ children?: ReactNode; onDismiss?: () => void }` and handles Escape keypress and outside mouse-up, and it does not forward arbitrary DOM props such as `onClick`. Flag mismatched props (e.g., `onDismiss` passed to the fuselage component or `onClick` passed to the ui-client component) and ensure the usage matches the correct component being imported.
Applied to files:
apps/meteor/client/views/room/contextualBar/Threads/components/ThreadMessageList.tsx
📚 Learning: 2026-02-10T16:32:42.586Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 38528
File: apps/meteor/client/startup/roles.ts:14-14
Timestamp: 2026-02-10T16:32:42.586Z
Learning: In Rocket.Chat's Meteor client code, DDP streams use EJSON and Date fields arrive as Date objects; do not manually construct new Date() in stream handlers (for example, in sdk.stream()). Only REST API responses return plain JSON where dates are strings, so implement explicit conversion there if needed. Apply this guidance to all TypeScript files under apps/meteor/client to ensure consistent date handling in DDP streams and REST responses.
Applied to files:
apps/meteor/client/lib/utils/threadMessageUtils.tsapps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
📚 Learning: 2026-05-11T20:30:35.265Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 40480
File: apps/meteor/client/meteor/startup/accounts.ts:59-61
Timestamp: 2026-05-11T20:30:35.265Z
Learning: In Rocket.Chat’s Meteor client code, when calling `dispatchToastMessage` with `{ type: 'error' }`, pass the raw caught error object as `message` without manual normalization. `dispatchToastMessage` is designed to accept `message: unknown` for error toasts, so avoid converting errors to strings (e.g., `String(error)`) or extracting `error.message` before passing them.
Applied to files:
apps/meteor/client/lib/utils/threadMessageUtils.tsapps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
🔇 Additional comments (5)
packages/rest-typings/src/v1/chat.ts (1)
686-700: LGTM!apps/meteor/app/api/server/v1/chat.ts (1)
1138-1138: LGTM!apps/meteor/client/lib/utils/threadMessageUtils.ts (1)
3-3: LGTM!Also applies to: 50-120
apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts (1)
26-30: LGTM!Also applies to: 64-87, 102-104, 116-196
apps/meteor/client/views/room/contextualBar/Threads/components/ThreadMessageList.tsx (1)
3-15: LGTM!Also applies to: 66-97, 134-152, 175-175, 326-339
| const windowKey = `${mainMessage._id}:${msgJumpParam}`; | ||
| if (loadingWindowKeyRef.current === windowKey) { | ||
| return; | ||
| } | ||
| loadingWindowKeyRef.current = windowKey; | ||
| void loadMessageAround(msgJumpParam); |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Handle failed deep-link loads and allow retry.
loadMessageAround is called outside React Query’s error state; if it rejects, the promise is unhandled and loadingWindowKeyRef stays set, so this target will not be retried.
Proposed fix
if (loadingWindowKeyRef.current === windowKey) {
return;
}
loadingWindowKeyRef.current = windowKey;
- void loadMessageAround(msgJumpParam);
+ void loadMessageAround(msgJumpParam).catch(() => {
+ if (loadingWindowKeyRef.current === windowKey) {
+ loadingWindowKeyRef.current = undefined;
+ }
+ });📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const windowKey = `${mainMessage._id}:${msgJumpParam}`; | |
| if (loadingWindowKeyRef.current === windowKey) { | |
| return; | |
| } | |
| loadingWindowKeyRef.current = windowKey; | |
| void loadMessageAround(msgJumpParam); | |
| const windowKey = `${mainMessage._id}:${msgJumpParam}`; | |
| if (loadingWindowKeyRef.current === windowKey) { | |
| return; | |
| } | |
| loadingWindowKeyRef.current = windowKey; | |
| void loadMessageAround(msgJumpParam).catch(() => { | |
| if (loadingWindowKeyRef.current === windowKey) { | |
| loadingWindowKeyRef.current = undefined; | |
| } | |
| }); |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@apps/meteor/client/views/room/contextualBar/Threads/components/ThreadMessageList.tsx`
around lines 146 - 151, The deep-link load in ThreadMessageList’s jump handling
can fail silently and leave loadingWindowKeyRef stuck, blocking retries. Update
the logic around loadMessageAround(msgJumpParam) so failures are caught and
handled (for example by resetting loadingWindowKeyRef.current when the promise
rejects) and ensure the load can be attempted again on subsequent jumps; use the
jump-loading block in ThreadMessageList and the loadMessageAround call as the
key spots to fix.
|
|
||
| const unprocessedReadMessagesEvent = useRef<{ tmid: string; until: Date } | null>(null); | ||
|
|
||
| const count = parseInt(`${getConfig('threadMessagesSize', 50)}`, 10); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Guard count against invalid config values.
getConfig can return URL/localStorage strings, so parseInt can produce NaN or 0; that breaks offset + count, getNextPageParam, and getPreviousPageParam.
Proposed fix
- const count = parseInt(`${getConfig('threadMessagesSize', 50)}`, 10);
+ const configuredCount = Number(getConfig('threadMessagesSize', 50));
+ const count = Number.isInteger(configuredCount) && configuredCount > 0 ? configuredCount : 50;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const count = parseInt(`${getConfig('threadMessagesSize', 50)}`, 10); | |
| const configuredCount = Number(getConfig('threadMessagesSize', 50)); | |
| const count = Number.isInteger(configuredCount) && configuredCount > 0 ? configuredCount : 50; |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts`
at line 49, The `count` value in `useThreadMessagesQuery` can become `NaN` or
`0` when `getConfig('threadMessagesSize', 50)` returns an invalid string, which
breaks pagination math. Update the `count` assignment to validate the parsed
value and fall back to a safe positive default when parsing fails or yields a
non-positive number. Make the fix in `useThreadMessagesQuery` so the values used
by `offset + count`, `getNextPageParam`, and `getPreviousPageParam` are always
valid.
There was a problem hiding this comment.
4 issues found and verified against the latest diff
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts">
<violation number="1" location="apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts:160">
P2: Check the pending read event’s `tmid` before applying it. Otherwise switching threads during a fetch can clear `unread` flags on messages from the wrong thread.</violation>
</file>
<file name="apps/meteor/client/lib/utils/threadMessageUtils.ts">
<violation number="1" location="apps/meteor/client/lib/utils/threadMessageUtils.ts:112">
P2: Update every cached copy of the message, not just the first match. Infinite pages can overlap, and a later stale duplicate can overwrite the updated one in the selected thread messages.</violation>
</file>
<file name="apps/meteor/app/api/server/v1/chat.ts">
<violation number="1" location="apps/meteor/app/api/server/v1/chat.ts:1166">
P2: Include the same query filter when calculating the `aroundId` offset. Otherwise filtered thread-message requests can return a page that is not centered around the requested message.</violation>
</file>
Tip: cubic used a learning from your PR history. Let your coding agent read cubic learnings directly with the cubic MCP.
Re-trigger cubic
| } else { | ||
| const target = await Messages.findOneById(aroundId, { projection: { ts: 1, tmid: 1 } }); | ||
| if (target?.tmid === tmid && target.ts) { | ||
| const before = await Messages.countDocuments({ tmid, ts: { $lt: target.ts } }); |
There was a problem hiding this comment.
P2: Include the same query filter when calculating the aroundId offset. Otherwise filtered thread-message requests can return a page that is not centered around the requested message.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/meteor/app/api/server/v1/chat.ts, line 1166:
<comment>Include the same query filter when calculating the `aroundId` offset. Otherwise filtered thread-message requests can return a page that is not centered around the requested message.</comment>
<file context>
@@ -1153,11 +1153,27 @@ const chatEndpoints = API.v1
+ } else {
+ const target = await Messages.findOneById(aroundId, { projection: { ts: 1, tmid: 1 } });
+ if (target?.tmid === tmid && target.ts) {
+ const before = await Messages.countDocuments({ tmid, ts: { $lt: target.ts } });
+ resolvedOffset = Math.max(0, before - Math.floor(count / 2));
+ }
</file context>
| const before = await Messages.countDocuments({ tmid, ts: { $lt: target.ts } }); | |
| const before = await Messages.countDocuments({ ...query, tmid, ts: { $lt: target.ts } }); |
| filtered = mergeThreadMessages(cachedMessages, filtered); | ||
| } | ||
|
|
||
| if (offset === 0 && unprocessedReadMessagesEvent.current) { |
There was a problem hiding this comment.
P2: Check the pending read event’s tmid before applying it. Otherwise switching threads during a fetch can clear unread flags on messages from the wrong thread.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts, line 160:
<comment>Check the pending read event’s `tmid` before applying it. Otherwise switching threads during a fetch can clear `unread` flags on messages from the wrong thread.</comment>
<file context>
@@ -100,23 +113,85 @@ export const useThreadMessagesQuery = (tmid: IThreadMainMessage['_id'], rid?: IR
+ filtered = mergeThreadMessages(cachedMessages, filtered);
+ }
+
+ if (offset === 0 && unprocessedReadMessagesEvent.current) {
const { until } = unprocessedReadMessagesEvent.current;
unprocessedReadMessagesEvent.current = null;
</file context>
| if (offset === 0 && unprocessedReadMessagesEvent.current) { | |
| if (offset === 0 && unprocessedReadMessagesEvent.current?.tmid === tmid) { |
| const idx = messages.findIndex((m) => m._id === message._id); | ||
| if (idx >= 0) { | ||
| const updated = [...old]; | ||
| updated[idx] = message; | ||
| return updated; | ||
| messages[idx] = message as IThreadMessage; | ||
| return; | ||
| } | ||
| return [...old, message].sort((a, b) => new Date(a.ts).getTime() - new Date(b.ts).getTime()); | ||
|
|
There was a problem hiding this comment.
P2: Update every cached copy of the message, not just the first match. Infinite pages can overlap, and a later stale duplicate can overwrite the updated one in the selected thread messages.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/meteor/client/lib/utils/threadMessageUtils.ts, line 112:
<comment>Update every cached copy of the message, not just the first match. Infinite pages can overlap, and a later stale duplicate can overwrite the updated one in the selected thread messages.</comment>
<file context>
@@ -47,24 +47,76 @@ export const createDeleteCriteria = (params: NotifyRoomRidDeleteBulkEvent): ((me
+ }
+
+ mutateThreadMessagesInfiniteData(client, queryKey, (messages) => {
+ const idx = messages.findIndex((m) => m._id === message._id);
if (idx >= 0) {
- const updated = [...old];
</file context>
| const idx = messages.findIndex((m) => m._id === message._id); | |
| if (idx >= 0) { | |
| const updated = [...old]; | |
| updated[idx] = message; | |
| return updated; | |
| messages[idx] = message as IThreadMessage; | |
| return; | |
| } | |
| return [...old, message].sort((a, b) => new Date(a.ts).getTime() - new Date(b.ts).getTime()); | |
| let updated = false; | |
| for (let index = 0; index < messages.length; index++) { | |
| if (messages[index]._id === message._id) { | |
| messages[index] = message as IThreadMessage; | |
| updated = true; | |
| } | |
| } | |
| if (updated) { | |
| return; | |
| } | |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts`:
- Around line 179-181: The pagination offset in useThreadMessagesQuery’s
getPreviousPageParam is advancing by the fixed count, which can skip older
messages after loadMessageAround seeds a partial newest page. Change the next
offset calculation to advance by the actual loaded page size from
firstPage.items.length instead of count, and keep the existing itemCount
boundary check so the older-page fetch continues from the correct position.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: ddef758b-08fe-4acb-b16b-c94de1ca1d18
📒 Files selected for processing (2)
apps/meteor/client/views/room/contextualBar/Threads/components/ThreadMessageList.tsxapps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
📜 Review details
⏰ Context from checks skipped due to timeout. (5)
- GitHub Check: 📦 Build Packages
- GitHub Check: cubic · AI code reviewer
- GitHub Check: CodeQL-Build
- GitHub Check: Hacktron Security Check
- GitHub Check: CodeQL-Build
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{ts,tsx,js}
📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)
**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation
Files:
apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.tsapps/meteor/client/views/room/contextualBar/Threads/components/ThreadMessageList.tsx
🧠 Learnings (6)
📚 Learning: 2026-02-10T16:32:42.586Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 38528
File: apps/meteor/client/startup/roles.ts:14-14
Timestamp: 2026-02-10T16:32:42.586Z
Learning: In Rocket.Chat's Meteor client code, DDP streams use EJSON and Date fields arrive as Date objects; do not manually construct new Date() in stream handlers (for example, in sdk.stream()). Only REST API responses return plain JSON where dates are strings, so implement explicit conversion there if needed. Apply this guidance to all TypeScript files under apps/meteor/client to ensure consistent date handling in DDP streams and REST responses.
Applied to files:
apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
📚 Learning: 2026-05-11T20:30:35.265Z
Learnt from: tassoevan
Repo: RocketChat/Rocket.Chat PR: 40480
File: apps/meteor/client/meteor/startup/accounts.ts:59-61
Timestamp: 2026-05-11T20:30:35.265Z
Learning: In Rocket.Chat’s Meteor client code, when calling `dispatchToastMessage` with `{ type: 'error' }`, pass the raw caught error object as `message` without manual normalization. `dispatchToastMessage` is designed to accept `message: unknown` for error toasts, so avoid converting errors to strings (e.g., `String(error)`) or extracting `error.message` before passing them.
Applied to files:
apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.
Applied to files:
apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.
Applied to files:
apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts
📚 Learning: 2026-05-06T12:21:44.083Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 40256
File: apps/meteor/client/components/CreateDiscussion/CreateDiscussion.tsx:121-149
Timestamp: 2026-05-06T12:21:44.083Z
Learning: Field wrappers in rocket.chat/fuselage-forms (Field, FieldLabel, FieldRow, FieldError, FieldHint) auto-create htmlFor/id associations, aria-describedby, and role="alert" for errors. Do not manually set htmlFor, id, aria-describedby, or role attributes when using these wrappers. This automatic wiring does not apply to plain rocket.chat/fuselage components, which require explicit ID wiring per the accessibility docs. In code reviews, prefer using fuselage-forms wrappers for form fields and verify there is no unnecessary manual ID/aria wiring in files that use these wrappers. If a component uses plain fuselage components, ensure proper id wiring as per docs.
Applied to files:
apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.tsapps/meteor/client/views/room/contextualBar/Threads/components/ThreadMessageList.tsx
📚 Learning: 2026-03-27T14:52:56.865Z
Learnt from: dougfabris
Repo: RocketChat/Rocket.Chat PR: 39892
File: apps/meteor/client/views/room/contextualBar/Threads/Thread.tsx:150-155
Timestamp: 2026-03-27T14:52:56.865Z
Learning: In Rocket.Chat, there are two different `ModalBackdrop` components with different prop APIs. During review, confirm the import source: (1) `rocket.chat/fuselage` `ModalBackdrop` uses `ModalBackdropProps` based on `BoxProps` (so it supports `onClick` and other Box/DOM props) and does not have an `onDismiss` prop; (2) `rocket.chat/ui-client` `ModalBackdrop` uses a narrower props interface like `{ children?: ReactNode; onDismiss?: () => void }` and handles Escape keypress and outside mouse-up, and it does not forward arbitrary DOM props such as `onClick`. Flag mismatched props (e.g., `onDismiss` passed to the fuselage component or `onClick` passed to the ui-client component) and ensure the usage matches the correct component being imported.
Applied to files:
apps/meteor/client/views/room/contextualBar/Threads/components/ThreadMessageList.tsx
🔇 Additional comments (3)
apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts (1)
49-49: Duplicate: guardcountagainst invalid config values.This still appears to match the existing review comment:
parseIntcan produceNaNor a non-positive value, which breaks the pagination math here.apps/meteor/client/views/room/contextualBar/Threads/components/ThreadMessageList.tsx (2)
138-143: Duplicate: handle failed deep-link loads and allow retry.This still appears to match the existing review comment: if
loadMessageAroundrejects, the promise is unhandled andloadingWindowKeyRefcan remain stuck for that target.
77-99: LGTM!Also applies to: 150-169, 179-191, 226-245, 296-309, 324-354
| getPreviousPageParam: (firstPage, _allPages, firstPageParam) => { | ||
| const next = firstPageParam + count; | ||
| return next < firstPage.itemCount ? next : undefined; |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Advance older-page offset by the loaded page size.
After loadMessageAround seeds a partial newest page, firstPageParam can be 0 while firstPage.items.length < count; adding count skips the gap between that partial page and the next older page. Use the loaded page size for the next older offset.
Proposed fix
getPreviousPageParam: (firstPage, _allPages, firstPageParam) => {
- const next = firstPageParam + count;
+ const pageSize = Math.min(firstPage.items.length, count);
+ if (pageSize <= 0) {
+ return undefined;
+ }
+ const next = firstPageParam + pageSize;
return next < firstPage.itemCount ? next : undefined;
},📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| getPreviousPageParam: (firstPage, _allPages, firstPageParam) => { | |
| const next = firstPageParam + count; | |
| return next < firstPage.itemCount ? next : undefined; | |
| getPreviousPageParam: (firstPage, _allPages, firstPageParam) => { | |
| const pageSize = Math.min(firstPage.items.length, count); | |
| if (pageSize <= 0) { | |
| return undefined; | |
| } | |
| const next = firstPageParam + pageSize; | |
| return next < firstPage.itemCount ? next : undefined; |
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts`
around lines 179 - 181, The pagination offset in useThreadMessagesQuery’s
getPreviousPageParam is advancing by the fixed count, which can skip older
messages after loadMessageAround seeds a partial newest page. Change the next
offset calculation to advance by the actual loaded page size from
firstPage.items.length instead of count, and keep the existing itemCount
boundary check so the older-page fetch continues from the correct position.
There was a problem hiding this comment.
3 issues found across 2 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="apps/meteor/client/views/room/contextualBar/Threads/components/ThreadMessageList.tsx">
<violation number="1" location="apps/meteor/client/views/room/contextualBar/Threads/components/ThreadMessageList.tsx:182">
P2: Jump-to-message is off by one when older thread pages exist. Account for the top loader child before calling `scrollToIndex`.</violation>
<violation number="2" location="apps/meteor/client/views/room/contextualBar/Threads/components/ThreadMessageList.tsx:326">
P3: Top date tracking becomes off by one while previous pages exist because the loader occupies VList index 0. Subtract the top-loader offset before indexing `items`.</violation>
</file>
<file name="apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts">
<violation number="1" location="apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts:180">
P2: After `loadMessageAround` seeds a partial page (e.g., when the offset is near the end of the thread), `firstPageParam` can be `0` while `firstPage.items.length < count`. Using the fixed `count` to compute the next older-page offset skips messages between the partial page boundary and the next fetch. Use `firstPage.items.length` (clamped to `count`) to advance the offset correctly.</violation>
</file>
Reply with feedback, questions, or to request a fix.
Re-trigger cubic
| if (replyIndex < 0) { | ||
| return -1; | ||
| } | ||
| return showMainMessage ? 1 + replyIndex : replyIndex; |
There was a problem hiding this comment.
P2: Jump-to-message is off by one when older thread pages exist. Account for the top loader child before calling scrollToIndex.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/meteor/client/views/room/contextualBar/Threads/components/ThreadMessageList.tsx, line 182:
<comment>Jump-to-message is off by one when older thread pages exist. Account for the top loader child before calling `scrollToIndex`.</comment>
<file context>
@@ -165,15 +176,19 @@ const ThreadMessageList = ({ mainMessage, shouldJumpToBottom, setShouldJumpToBot
+ if (replyIndex < 0) {
+ return -1;
+ }
+ return showMainMessage ? 1 + replyIndex : replyIndex;
+ }, [msgJumpParam, loading, mainMessage._id, messages, showMainMessage]);
</file context>
| return showMainMessage ? 1 + replyIndex : replyIndex; | |
| return 1 + replyIndex; |
| return lastPageParam > 0 ? Math.max(0, lastPageParam - count) : undefined; | ||
| }, | ||
| getPreviousPageParam: (firstPage, _allPages, firstPageParam) => { | ||
| const next = firstPageParam + count; |
There was a problem hiding this comment.
P2: After loadMessageAround seeds a partial page (e.g., when the offset is near the end of the thread), firstPageParam can be 0 while firstPage.items.length < count. Using the fixed count to compute the next older-page offset skips messages between the partial page boundary and the next fetch. Use firstPage.items.length (clamped to count) to advance the offset correctly.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/meteor/client/views/room/contextualBar/Threads/hooks/useThreadMessagesQuery.ts, line 180:
<comment>After `loadMessageAround` seeds a partial page (e.g., when the offset is near the end of the thread), `firstPageParam` can be `0` while `firstPage.items.length < count`. Using the fixed `count` to compute the next older-page offset skips messages between the partial page boundary and the next fetch. Use `firstPage.items.length` (clamped to `count`) to advance the offset correctly.</comment>
<file context>
@@ -171,12 +173,12 @@ export const useThreadMessagesQuery = (tmid: IThreadMainMessage['_id'], rid?: IR
- getPreviousPageParam: (_firstPage, _allPages, firstPageParam) => {
- return firstPageParam > 0 ? Math.max(0, firstPageParam - count) : undefined;
+ getPreviousPageParam: (firstPage, _allPages, firstPageParam) => {
+ const next = firstPageParam + count;
+ return next < firstPage.itemCount ? next : undefined;
},
</file context>
| const next = firstPageParam + count; | |
| const pageSize = Math.min(firstPage.items.length, count); | |
| if (pageSize <= 0) { | |
| return undefined; | |
| } | |
| const next = firstPageParam + pageSize; |
| ) : ( | ||
| ) : null} | ||
| {!loading && hasPreviousPage ? ( | ||
| <li className='load-more'>{isFetchingPreviousPage ? <LoadingMessagesIndicator /> : null}</li> |
There was a problem hiding this comment.
P3: Top date tracking becomes off by one while previous pages exist because the loader occupies VList index 0. Subtract the top-loader offset before indexing items.
Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/meteor/client/views/room/contextualBar/Threads/components/ThreadMessageList.tsx, line 326:
<comment>Top date tracking becomes off by one while previous pages exist because the loader occupies VList index 0. Subtract the top-loader offset before indexing `items`.</comment>
<file context>
@@ -304,7 +321,11 @@ const ThreadMessageList = ({ mainMessage, shouldJumpToBottom, setShouldJumpToBot
- ) : (
+ ) : null}
+ {!loading && hasPreviousPage ? (
+ <li className='load-more'>{isFetchingPreviousPage ? <LoadingMessagesIndicator /> : null}</li>
+ ) : null}
+ {!loading &&
</file context>
Proposed changes (including videos or screenshots)
Issue(s)
CORE-2292
Steps to test or reproduce
Further comments
Summary by CodeRabbit
Summary by CodeRabbit
New Features
Bug Fixes
Refactor