Skip to content

Chats improvements#629

Merged
feruzm merged 2 commits into
developfrom
impr
Jan 24, 2026
Merged

Chats improvements#629
feruzm merged 2 commits into
developfrom
impr

Conversation

@feruzm
Copy link
Copy Markdown
Member

@feruzm feruzm commented Jan 24, 2026

Summary by CodeRabbit

  • New Features

    • Toggle to include online user statuses in channel post views and responses.
  • Performance

    • Targeted in-cache updates for posts, channels, reactions and unread counts to reduce full refetches.
    • Adjusted query caching/refetch intervals for more efficient data freshness.
  • UX

    • Data refresh when toggling online user display to ensure consistent results.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jan 24, 2026

📝 Walkthrough

Walkthrough

The PR adds optional online-user status fetching to Mattermost posts via an include_online query parameter, propagates that option through React Query hooks and the channel view toggle, and replaces broad WebSocket-driven cache invalidations with targeted in-cache updates for posts, reactions, and channel metadata.

Changes

Cohort / File(s) Summary
Backend API Route
apps/web/src/app/api/mattermost/channels/[channelId]/posts/route.ts
Adds include_online query parameter. When enabled, paginates channel-user fetches, issues a parallel status fetch, builds onlineUserIds, and includes it in the response; when disabled, omits online data.
React Query Hooks
apps/web/src/features/chat/mattermost-api.ts
Adds includeOnline option to useMattermostPosts and useMattermostPostsInfinite, appends include_online=1 to request URLs when set, and tweaks stale/refetch timing for related hooks.
Component Integration
apps/web/src/features/chat/mattermost-channel-view.tsx
Introduces showOnlineUsers local state, wires it to infinite posts query via includeOnline, and invalidates the posts-infinite cache when toggled to refresh data.
WebSocket Cache Optimization
apps/web/src/features/chat/mattermost-websocket.ts
Replaces broad invalidations with targeted in-cache operations: upsertPostInCaches, updatePostInCaches, removePostFromCaches, updateChannelLastPost, incrementUnreadCount, resetUnreadCount; implements optimistic updates for posted/edited/deleted/reaction events.

Sequence Diagram(s)

sequenceDiagram
    participant Component as Component
    participant ReactQuery as React Query
    participant API as API Route
    participant MM as Mattermost Backend

    Component->>ReactQuery: request posts (includeOnline?)
    ReactQuery->>API: GET /channels/[id]/posts?include_online=1
    API->>MM: Fetch posts
    MM-->>API: Posts
    alt include_online = true
        API->>MM: Paginated fetch channel users
        MM-->>API: Channel users (paged)
        par Parallel status fetch
            API->>MM: Fetch statuses for members
            MM-->>API: Statuses
        end
        API->>API: Build users map + onlineUserIds
    else
        API->>API: Build response without onlineUserIds
    end
    API-->>ReactQuery: Posts (+ optional onlineUserIds)
    ReactQuery-->>Component: Provide cached data
    Component->>Component: Render (optionally show online users)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

  • Improve chats #628: Modifies the same channels/[channelId]/posts/route.ts to add conditional parallel online-status fetching and the statusPromise integration.

Poem

🐰 I hopped to the channel, a toggle in paw,
Online friends revealed with a soft little awe,
Caches now nimble, sockets hum bright,
Posts and statuses dancing in light,
Hooray for the toggle — let presence take flight!

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (1 warning, 1 inconclusive)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Chats improvements' is overly vague and generic, using non-descriptive language that does not convey meaningful information about the specific changes in the pull request. Use a more specific title that highlights the main change, such as 'Add online user status fetching to posts API' or 'Optimize chat queries with online status support'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@apps/web/src/app/api/mattermost/channels/`[channelId]/posts/route.ts:
- Around line 137-168: The channel user fetch in the includeOnline branch
(inside route handler using mmUserFetch in apps/web/src/.../posts/route.ts) is
limited to per_page=200, which will miss members in large channels; update the
logic around the channelUsers fetch (the code that calls mmUserFetch for
`/users?in_channel=${channelId}&per_page=200&page=0`) to paginate: repeatedly
call mmUserFetch with increasing page numbers, accumulate results into the users
variable (used to build the users map), and stop when a page returns fewer than
the page size (or an empty array); ensure the same aggregated list is used when
posting to `/users/status/ids` for statusPromise and preserve the existing error
handling for status fetch.

In `@apps/web/src/features/chat/mattermost-websocket.ts`:
- Around line 478-496: handlePostEdited currently calls upsertPostInCaches which
only checks the first page and causes duplicates when edited posts live on later
pages; change handlePostEdited to call updatePostInCaches (the function that
scans all pages) for edits and keep upsertPostInCaches only for new posts.
Locate the handlePostEdited method and replace the upsertPostInCaches(channelId,
post) invocation with updatePostInCaches(channelId, post); retain the existing
error/invalidateQueries behavior for cases where post JSON is missing or parsing
fails.
🧹 Nitpick comments (4)
apps/web/src/features/chat/mattermost-channel-view.tsx (1)

266-269: Consider using a ref to track previous showOnlineUsers value to avoid redundant invalidations.

The current effect triggers invalidation whenever channelId changes while showOnlineUsers is true. However, when channelId changes, React Query already fetches fresh data for the new channel due to the query key change, making this invalidation redundant.

♻️ Suggested refinement
+const prevShowOnlineUsersRef = useRef(false);
+
 useEffect(() => {
-  if (!showOnlineUsers) return;
-  queryClient.invalidateQueries({ queryKey: ["mattermost-posts-infinite", channelId] });
-}, [showOnlineUsers, channelId, queryClient]);
+  const wasOff = !prevShowOnlineUsersRef.current;
+  prevShowOnlineUsersRef.current = showOnlineUsers;
+  
+  // Only invalidate when toggling from false to true
+  if (showOnlineUsers && wasOff) {
+    queryClient.invalidateQueries({ queryKey: ["mattermost-posts-infinite", channelId] });
+  }
+}, [showOnlineUsers, channelId, queryClient]);
apps/web/src/features/chat/mattermost-api.ts (2)

571-592: includeOnline option not included in query key could cause cache inconsistencies.

The includeOnline option changes the data returned by the API but isn't part of the query key. If multiple components use useMattermostPosts with the same channelId but different includeOnline values, they would incorrectly share the same cache entry.

While the current usage in mattermost-channel-view.tsx handles this via manual invalidation, consider including includeOnline in the query key for correctness and to prevent subtle bugs if other consumers are added.

♻️ Suggested fix
 export function useMattermostPosts(
   channelId: string | undefined,
   options?: { includeOnline?: boolean }
 ) {
   return useQuery({
-    queryKey: ["mattermost-posts", channelId],
+    queryKey: ["mattermost-posts", channelId, { includeOnline: options?.includeOnline ?? false }],
     enabled: Boolean(channelId),

594-624: Same concern: includeOnline should be in query key for useMattermostPostsInfinite.

For the same reasons as useMattermostPosts, consider adding includeOnline to the query key to ensure cache correctness when multiple consumers exist.

♻️ Suggested fix
 export function useMattermostPostsInfinite(
   channelId: string | undefined,
   options?: { refetchInterval?: number | false; includeOnline?: boolean }
 ) {
   return useInfiniteQuery({
-    queryKey: ["mattermost-posts-infinite", channelId],
+    queryKey: ["mattermost-posts-infinite", channelId, { includeOnline: options?.includeOnline ?? false }],
     enabled: Boolean(channelId),
apps/web/src/features/chat/mattermost-websocket.ts (1)

590-631: upsertPostInCaches only searches first page, which is correct for new posts but not for updates.

The method name suggests it handles both insert and update scenarios, but the implementation only searches firstPage for existing posts. This works for new posts (which belong in the first/newest page) but will cause issues if used for updates.

Consider either:

  1. Renaming to insertPostInCaches to clarify its purpose
  2. Or updating the implementation to search all pages
♻️ Option 1: Rename to clarify intent
-private upsertPostInCaches(channelId: string, post: MattermostPost): void {
+private insertNewPostInCaches(channelId: string, post: MattermostPost): void {

And update handlePosted to use the renamed method.

Comment thread apps/web/src/app/api/mattermost/channels/[channelId]/posts/route.ts
Comment thread apps/web/src/features/chat/mattermost-websocket.ts
@feruzm feruzm merged commit 955fcb6 into develop Jan 24, 2026
1 check passed
@feruzm feruzm deleted the impr branch January 24, 2026 09:56
@coderabbitai coderabbitai Bot mentioned this pull request Jan 25, 2026
@coderabbitai coderabbitai Bot mentioned this pull request Apr 9, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant