fix: put linked comments in natural order with a "Linked comment" section#4970
fix: put linked comments in natural order with a "Linked comment" section#4970aseckin wants to merge 1 commit into
Conversation
…comment" section
Previously, when arriving via a `#comment-N` URL hash, the focused comment thread was bumped to the top of the feed via a backend annotation. That broke the user's chosen sort order ("Recent" etc.) and stripped the comment of its context, with only the date as a clue that it was out of place.
This change:
- Backend: adds a `focus_thread_only` flag to the comments feed endpoint. When set alongside `focus_comment_id`, the response is restricted to just the focused thread (the comment plus its root/siblings) so the frontend can render it standalone. Without the flag, the existing behavior is preserved.
- Frontend: stops sending `focus_comment_id` for the regular paginated fetch, so the natural sort is preserved. When a `#comment-N` hash is present and the target comment isn't in the natural feed, a separate fetch retrieves just that thread and renders it below the "Load more" button under a "Linked comment" divider. When the user loads more pages and the target enters the natural feed, the linked section disappears automatically.
Co-authored-by: Sylvain <SylvainChevalier@users.noreply.github.com>
📝 WalkthroughWalkthroughAdds a ChangesFocused comment thread feature
Estimated code review effort: 3 (Moderate) | ~25 minutes Sequence Diagram(s)sequenceDiagram
participant Browser
participant CommentFeed
participant CommentsFeedProvider
participant ClientCommentsApi
participant Backend
Browser->>CommentFeed: navigate with `#comment-`<id>
CommentFeed->>CommentFeed: check if comment exists in loaded list
alt not loaded
CommentFeed->>CommentsFeedProvider: fetchFocusedCommentThread(id)
CommentsFeedProvider->>ClientCommentsApi: getComments(focus_comment_id, focus_thread_only=true)
ClientCommentsApi->>Backend: GET /api/comments/
Backend->>Backend: filter queryset to focused thread subset
Backend-->>ClientCommentsApi: focused thread comments
ClientCommentsApi-->>CommentsFeedProvider: raw comments
CommentsFeedProvider-->>CommentFeed: parsed focused comment or null
CommentFeed->>CommentFeed: render linkedComment section with CommentWrapper
else already loaded
CommentFeed->>CommentFeed: clear linkedFocusedThread, scroll to comment
end
Poem
🚥 Pre-merge checks | ✅ 4✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 oasdiff (1.21.0)docs/openapi.ymlError: failed to load base spec from "/tmp/coderabbit-oasdiff-base.qn9ha0": failed to unmarshal data: json error: invalid character 'o' looking for beginning of value, yaml error: error unmarshaling JSON: while decoding JSON: json: cannot unmarshal bool into field Schema.required of type []string 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 |
🚀 Preview EnvironmentYour preview environment is ready!
Details
ℹ️ Preview Environment InfoIsolation:
Limitations:
Cleanup:
|
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (2)
docs/openapi.yml (1)
2471-2476: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueConsider documenting the default value.
Unlike
is_private(Line 2450,default: false), the newfocus_thread_onlyschema omitsdefault: false, even though the serializer defaults it toFalse. Adding it keeps generated client/schema docs consistent.📝 Proposed fix
- name: focus_thread_only in: query required: false schema: type: boolean + default: false description: When used alongside `focus_comment_id`, restricts the response to only the focused comment thread (the comment plus its root/siblings if it has a parent).🤖 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 `@docs/openapi.yml` around lines 2471 - 2476, The new focus_thread_only query parameter in the OpenAPI schema is missing its documented default even though the serializer defaults it to false. Update the query parameter definition for focus_thread_only in the openapi spec to include default: false, matching the existing is_private pattern so generated clients and docs stay consistent.front_end/src/app/(main)/components/comments_feed_provider.tsx (1)
365-386: 🚀 Performance & Scalability | 🔵 Trivial | ⚡ Quick winConsider bounding the focused-thread fetch with a
limit.Unlike
fetchComments/ensureCommentLoaded/refreshComment, this call omitslimit. For a popular thread with many nested replies, this could return an unbounded payload just to render one linked comment section.♻️ Suggested addition
const response = await ClientCommentsApi.getComments({ post: postData?.id, author: profileId, focus_comment_id: String(id), focus_thread_only: true, + limit: COMMENTS_PER_PAGE, use_root_comments_pagination: rootCommentStructure, });Please confirm what the backend does by default for
focus_thread_only=truewhen nolimitis supplied (unbounded vs. default page size), since that governs whether this is actually needed.🤖 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 `@front_end/src/app/`(main)/components/comments_feed_provider.tsx around lines 365 - 386, The focused-thread fetch in fetchFocusedCommentThread omits a limit, so verify the backend default for focus_thread_only=true and, if it is not already bounded, pass an explicit limit to ClientCommentsApi.getComments alongside focus_comment_id and focus_thread_only. Keep the change localized to fetchFocusedCommentThread in comments_feed_provider.tsx and align the bound with the existing pagination-aware callers like fetchComments, ensureCommentLoaded, and refreshComment.
🤖 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 `@front_end/src/components/comment_feed/index.tsx`:
- Around line 213-246: The hash-handling effect in comment_feed/index.tsx leaves
stale linked-comment state behind when the hash is missing or malformed. Update
the effect that parses `hash`, `match`, and `loadLinkedFocusedThread` so it also
clears `linkedFocusedThread` before returning on `!hash` and on invalid
`numericId`/non-matching hashes, while preserving the existing behavior for
`findById` and the `comments` scroll workaround.
- Around line 152-167: The loadLinkedFocusedThread callback can be overwritten
by stale async results, causing the wrong linked thread to display after rapid
navigation. Add a request-sequence guard in CommentFeed (for example with a ref
alongside useCallback) so each invocation records the latest id/token and only
the newest fetchFocusedCommentThread result is allowed to update
setLinkedFocusedThread and setIsLinkedLoading; discard older responses in the
async completion path.
---
Nitpick comments:
In `@docs/openapi.yml`:
- Around line 2471-2476: The new focus_thread_only query parameter in the
OpenAPI schema is missing its documented default even though the serializer
defaults it to false. Update the query parameter definition for
focus_thread_only in the openapi spec to include default: false, matching the
existing is_private pattern so generated clients and docs stay consistent.
In `@front_end/src/app/`(main)/components/comments_feed_provider.tsx:
- Around line 365-386: The focused-thread fetch in fetchFocusedCommentThread
omits a limit, so verify the backend default for focus_thread_only=true and, if
it is not already bounded, pass an explicit limit to
ClientCommentsApi.getComments alongside focus_comment_id and focus_thread_only.
Keep the change localized to fetchFocusedCommentThread in
comments_feed_provider.tsx and align the bound with the existing
pagination-aware callers like fetchComments, ensureCommentLoaded, and
refreshComment.
🪄 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: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 336cb5c0-e061-42a7-b9b7-4c5ea44fdd91
📒 Files selected for processing (15)
comments/serializers/common.pycomments/services/feed.pydocs/openapi.ymlfront_end/messages/cs.jsonfront_end/messages/en.jsonfront_end/messages/es.jsonfront_end/messages/pt.jsonfront_end/messages/zh-TW.jsonfront_end/messages/zh.jsonfront_end/src/app/(main)/components/comments_feed_provider.tsxfront_end/src/components/comment_feed/index.tsxfront_end/src/services/api/comments/comments.shared.tsfront_end/src/stories/utils/mocks/mock_comments_feed_provider.tsxfront_end/src/utils/comments.tstests/unit/test_comments/test_views.py
💤 Files with no reviewable changes (1)
- front_end/src/utils/comments.ts
| const loadLinkedFocusedThread = useCallback( | ||
| async (id: number) => { | ||
| setIsLinkedLoading(true); | ||
| try { | ||
| const thread = await fetchFocusedCommentThread(id); | ||
| if (thread) { | ||
| setLinkedFocusedThread({ focusedId: id, thread }); | ||
| } else { | ||
| setLinkedFocusedThread(null); | ||
| } | ||
| } finally { | ||
| setIsLinkedLoading(false); | ||
| } | ||
| }, | ||
| [fetchFocusedCommentThread] | ||
| ); |
There was a problem hiding this comment.
🩺 Stability & Availability | 🟠 Major | ⚡ Quick win
Race condition: out-of-order responses can show the wrong linked thread.
loadLinkedFocusedThread has no guard against stale responses. If a user rapidly follows two different #comment-N links, a slower earlier request can resolve after a newer one and overwrite linkedFocusedThread with the wrong thread/loading state.
🔒 Suggested fix using a ref to discard stale responses
+ const latestRequestedIdRef = useRef<number | null>(null);
+
const loadLinkedFocusedThread = useCallback(
async (id: number) => {
+ latestRequestedIdRef.current = id;
setIsLinkedLoading(true);
try {
const thread = await fetchFocusedCommentThread(id);
+ if (latestRequestedIdRef.current !== id) return;
if (thread) {
setLinkedFocusedThread({ focusedId: id, thread });
} else {
setLinkedFocusedThread(null);
}
} finally {
- setIsLinkedLoading(false);
+ if (latestRequestedIdRef.current === id) {
+ setIsLinkedLoading(false);
+ }
}
},
[fetchFocusedCommentThread]
);📝 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 loadLinkedFocusedThread = useCallback( | |
| async (id: number) => { | |
| setIsLinkedLoading(true); | |
| try { | |
| const thread = await fetchFocusedCommentThread(id); | |
| if (thread) { | |
| setLinkedFocusedThread({ focusedId: id, thread }); | |
| } else { | |
| setLinkedFocusedThread(null); | |
| } | |
| } finally { | |
| setIsLinkedLoading(false); | |
| } | |
| }, | |
| [fetchFocusedCommentThread] | |
| ); | |
| const latestRequestedIdRef = useRef<number | null>(null); | |
| const loadLinkedFocusedThread = useCallback( | |
| async (id: number) => { | |
| latestRequestedIdRef.current = id; | |
| setIsLinkedLoading(true); | |
| try { | |
| const thread = await fetchFocusedCommentThread(id); | |
| if (latestRequestedIdRef.current !== id) return; | |
| if (thread) { | |
| setLinkedFocusedThread({ focusedId: id, thread }); | |
| } else { | |
| setLinkedFocusedThread(null); | |
| } | |
| } finally { | |
| if (latestRequestedIdRef.current === id) { | |
| setIsLinkedLoading(false); | |
| } | |
| } | |
| }, | |
| [fetchFocusedCommentThread] | |
| ); |
🤖 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 `@front_end/src/components/comment_feed/index.tsx` around lines 152 - 167, The
loadLinkedFocusedThread callback can be overwritten by stale async results,
causing the wrong linked thread to display after rapid navigation. Add a
request-sequence guard in CommentFeed (for example with a ref alongside
useCallback) so each invocation records the latest id/token and only the newest
fetchFocusedCommentThread result is allowed to update setLinkedFocusedThread and
setIsLinkedLoading; discard older responses in the async completion path.
| if (isLoading) return; | ||
| if (!hash) return; | ||
|
|
||
| const match = hash.match(/comment-(\d+)/); | ||
| if (match?.[1]) { | ||
| const numericId = Number(match[1]); | ||
| if (Number.isNaN(numericId)) return; | ||
|
|
||
| // Comment already in the natural feed — comment.tsx handles scrolling. | ||
| if (findById(comments, numericId)) { | ||
| if (linkedFocusedThread) setLinkedFocusedThread(null); | ||
| return; | ||
| } | ||
|
|
||
| if (linkedFocusedThread?.focusedId === numericId) { | ||
| return; | ||
| } | ||
|
|
||
| void loadLinkedFocusedThread(numericId); | ||
| } else if (hash === "comments" && isFirstRender.current) { | ||
| isFirstRender.current = false; | ||
| // same workaround as in comment.tsx | ||
| const timeoutId = setTimeout(() => { | ||
| if (commentsRef.current) { | ||
| scrollTo(commentsRef.current.getBoundingClientRect().top); | ||
| } | ||
| }, 1000); | ||
|
|
||
| return () => { | ||
| clearTimeout(timeoutId); | ||
| }; | ||
| } | ||
| // eslint-disable-next-line react-hooks/exhaustive-deps | ||
| }, [hash, isLoading]); | ||
| }, [hash, isLoading, comments]); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟠 Major | ⚡ Quick win
Stale linked-comment section not cleared when hash is removed or invalid.
The effect returns early on !hash (line 214) and on Number.isNaN(numericId) (line 219) without clearing an existing linkedFocusedThread. If the hash disappears or becomes malformed after a linked thread was already loaded, the "Linked comment" section keeps rendering stale content.
🐛 Suggested fix
useEffect(() => {
if (isLoading) return;
- if (!hash) return;
+ if (!hash) {
+ if (linkedFocusedThread) setLinkedFocusedThread(null);
+ return;
+ }
const match = hash.match(/comment-(\d+)/);
if (match?.[1]) {
const numericId = Number(match[1]);
- if (Number.isNaN(numericId)) return;
+ if (Number.isNaN(numericId)) {
+ if (linkedFocusedThread) setLinkedFocusedThread(null);
+ return;
+ }🤖 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 `@front_end/src/components/comment_feed/index.tsx` around lines 213 - 246, The
hash-handling effect in comment_feed/index.tsx leaves stale linked-comment state
behind when the hash is missing or malformed. Update the effect that parses
`hash`, `match`, and `loadLinkedFocusedThread` so it also clears
`linkedFocusedThread` before returning on `!hash` and on invalid
`numericId`/non-matching hashes, while preserving the existing behavior for
`findById` and the `comments` scroll workaround.
Closes #1609
Summary
Linked comments (
#comment-NURL hashes) no longer get bumped to the top of the comments feed out of context. Instead:Changes
focus_thread_onlyquery param that, alongsidefocus_comment_id, restricts the feed to just the focused thread (comment + root + siblings). The pre-existing bump-to-top behavior (without the flag) is preserved, since it's still used by reply flows.focus_comment_idon the regular paginated fetch; uses a newfetchFocusedCommentThreadcontext method to fetch the thread separately when needed; renders it under a "Linked comment" divider below Load more. Cleans uplinkedFocusedThreadstate when the target appears in the natural feed.focus_thread_onlybehavior for root and child focus targets.Test plan
#comment-Nfor a comment that would naturally appear on the first page → comment stays in its proper sorted position and page scrolls to it.#comment-Nfor a comment beyond the first page → natural list renders normally, "Linked comment" section appears below Load more with that thread.ensureCommentLoadedflow still works (old focus_comment_id behavior).Generated with Claude Code
Summary by CodeRabbit
New Features
Bug Fixes