Skip to content

fix: put linked comments in natural order with a "Linked comment" section#4970

Open
aseckin wants to merge 1 commit into
mainfrom
claude/issue-1609-put-linked-comments-into-the
Open

fix: put linked comments in natural order with a "Linked comment" section#4970
aseckin wants to merge 1 commit into
mainfrom
claude/issue-1609-put-linked-comments-into-the

Conversation

@aseckin

@aseckin aseckin commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Closes #1609

Summary

Linked comments (#comment-N URL hashes) no longer get bumped to the top of the comments feed out of context. Instead:

  • If the comment is already in the natural first page, it stays in its proper sorted position (existing scroll-to behavior kicks in).
  • If the comment is beyond the "Load more" cutoff, a separate "Linked comment" section is rendered below the Load more button. Clicking Load more auto-clears it once the target enters the natural feed.

Changes

  • Backend: new focus_thread_only query param that, alongside focus_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.
  • Frontend: stops sending focus_comment_id on the regular paginated fetch; uses a new fetchFocusedCommentThread context method to fetch the thread separately when needed; renders it under a "Linked comment" divider below Load more. Cleans up linkedFocusedThread state when the target appears in the natural feed.
  • I18n: "Linked comment" string added to all six language files.
  • Tests: added two backend tests covering the new focus_thread_only behavior for root and child focus targets.

Test plan

  • Open a question with many comments and navigate to #comment-N for a comment that would naturally appear on the first page → comment stays in its proper sorted position and page scrolls to it.
  • Navigate to #comment-N for a comment beyond the first page → natural list renders normally, "Linked comment" section appears below Load more with that thread.
  • Click "Load more" until the linked comment enters the natural feed → linked section disappears.
  • Change sort (Recent → Best) while a comment is linked → sort applies to the natural feed, linked section updates correctly.
  • Reply to a deep comment → existing ensureCommentLoaded flow still works (old focus_comment_id behavior).

Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Added a new comment-thread filter that lets the app show only the focused thread when viewing comments.
    • Improved linked comment handling so a focused thread can be loaded and displayed directly from the URL.
    • Added a new “linked comment” label in multiple languages.
  • Bug Fixes

    • Refined comment navigation so focused threads are handled more consistently when the target comment is already visible.

…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>
@coderabbitai

coderabbitai Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Adds a focus_thread_only filter to the comments API/serializer/feed service to restrict results to a focused thread subset, and reworks frontend comment feed logic to fetch a linked comment thread via a new provider method and render it in place, replacing prior hash-based top-of-list injection, plus adds linkedComment localization strings.

Changes

Focused comment thread feature

Layer / File(s) Summary
Backend focus_thread_only filter and feed service
comments/serializers/common.py, comments/services/feed.py, docs/openapi.yml, tests/unit/test_comments/test_views.py
Added focus_thread_only boolean field/parameter/query-param, restricting the queryset to the focused thread subset when true instead of annotating and reordering; documented in OpenAPI and validated by new root/child focused-thread tests.
Frontend API types and feed provider fetch method
front_end/src/services/api/comments/comments.shared.ts, front_end/src/app/(main)/components/comments_feed_provider.tsx, front_end/src/stories/utils/mocks/mock_comments_feed_provider.tsx
Added focus_thread_only to request params type, implemented fetchFocusedCommentThread in the feed provider (calls API with focus_thread_only: true, parses result, returns first comment or null), exposed via context, and stubbed in the story mock.
Comment feed UI: linked thread placement and hash handling
front_end/src/components/comment_feed/index.tsx, front_end/src/utils/comments.ts
Removed getCommentIdToFocusOn and prior focus_comment_id filter injection/reset; rewrote the hash-handling effect to check for an already-loaded comment via findById, otherwise fetch a linked focused thread with loading state, and render it in a labeled section with CommentWrapper.
linkedComment localization strings
front_end/messages/cs.json, en.json, es.json, pt.json, zh-TW.json, zh.json
Added the linkedComment translation key/value to each locale file.

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
Loading

Poem

A hop, a click, a hash in the air,
The linked comment now knows where to stay right there!
No more jumping to the top of the pile,
It settles in context, with a satisfied smile.
🐇 focus_thread_only whispers "just this thread, please,"
And six new languages say "linkedComment" with ease. 🌸

🚥 Pre-merge checks | ✅ 4
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: keeping linked comments in natural order with a linked-comment section.
Linked Issues check ✅ Passed The changes match #1609 by preserving natural placement for loaded comments and showing unloaded linked comments below Load more.
Out of Scope Changes check ✅ Passed The added i18n, API, frontend, and test updates all support the linked-comment behavior and do not appear unrelated.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch claude/issue-1609-put-linked-comments-into-the

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.yml

Error: 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.

❤️ Share

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

@github-actions

github-actions Bot commented Jul 1, 2026

Copy link
Copy Markdown
Contributor

🚀 Preview Environment

Your preview environment is ready!

Resource Details
🌐 Preview URL https://metaculus-pr-4970-claude-issue-1609-put-linked-c-preview.mtcl.cc
📦 Docker Image ghcr.io/metaculus/metaculus:claude-issue-1609-put-linked-comments-into-the-6a25232
🗄️ PostgreSQL NeonDB branch preview/pr-4970-claude-issue-1609-put-linked-c
Redis Fly Redis mtc-redis-pr-4970-claude-issue-1609-put-linked-c

Details

  • Commit: 6a25232b33ecae0399d79beac362e5494d328892
  • Branch: claude/issue-1609-put-linked-comments-into-the
  • Fly App: metaculus-pr-4970-claude-issue-1609-put-linked-c

ℹ️ Preview Environment Info

Isolation:

  • PostgreSQL and Redis are fully isolated from production
  • Each PR gets its own database branch and Redis instance
  • Changes pushed to this PR will trigger a new deployment

Limitations:

  • Background workers and cron jobs are not deployed in preview environments
  • If you need to test background jobs, use Heroku staging environments

Cleanup:

  • This preview will be automatically destroyed when the PR is closed

@aseckin

aseckin commented Jul 1, 2026

Copy link
Copy Markdown
Contributor Author

QA passed, pending code review @hlbmtc @ncarazon

@aseckin aseckin marked this pull request as ready for review July 1, 2026 13:21

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🧹 Nitpick comments (2)
docs/openapi.yml (1)

2471-2476: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider documenting the default value.

Unlike is_private (Line 2450, default: false), the new focus_thread_only schema omits default: false, even though the serializer defaults it to False. 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 win

Consider bounding the focused-thread fetch with a limit.

Unlike fetchComments/ensureCommentLoaded/refreshComment, this call omits limit. 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=true when no limit is 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

📥 Commits

Reviewing files that changed from the base of the PR and between 1d2fed3 and 6a25232.

📒 Files selected for processing (15)
  • comments/serializers/common.py
  • comments/services/feed.py
  • docs/openapi.yml
  • front_end/messages/cs.json
  • front_end/messages/en.json
  • front_end/messages/es.json
  • front_end/messages/pt.json
  • front_end/messages/zh-TW.json
  • front_end/messages/zh.json
  • front_end/src/app/(main)/components/comments_feed_provider.tsx
  • front_end/src/components/comment_feed/index.tsx
  • front_end/src/services/api/comments/comments.shared.ts
  • front_end/src/stories/utils/mocks/mock_comments_feed_provider.tsx
  • front_end/src/utils/comments.ts
  • tests/unit/test_comments/test_views.py
💤 Files with no reviewable changes (1)
  • front_end/src/utils/comments.ts

Comment on lines +152 to +167
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]
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🩺 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.

Suggested change
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.

Comment on lines +213 to +246
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]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

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.

Put linked comments into the right spot in comments feed

1 participant