feat: Implement AI-Powered Doubt De-duplication System - #1074
Conversation
|
@Yogender-verma is attempting to deploy a commit to the Karan Mani Tripathi 's projects Team on Vercel. A member of the Team first needs to authorize it. |
🤖 CodeAnt AI — Review Status
|
Thanks for using CodeAnt! 🎉We're free for open-source projects. if you're enjoying it, help us grow by sharing. Share on X · |
|
Warning Review limit reached
Next review available in: 41 minutes Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available. How can I continue?After more reviews become available, a review can be triggered using the To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews. How do review limits work?CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability. For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window. Please refer docs for additional details. Review details⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (4)
WalkthroughAdds a duplicate-check API route using embedding and Groq similarity workflows, connects ChangesDuplicate detection flow
Flag transaction maintenance
Estimated code review effort: 4 (Complex) | ~45 minutes Sequence Diagram(s)sequenceDiagram
participant AskDoubt
participant DuplicateRoute as POST /api/doubts/check-duplicate
participant Embeddings as findSemanticDuplicates
participant Database as db
participant Groq
AskDoubt->>DuplicateRoute: Submit content and classroomId
DuplicateRoute->>Embeddings: Search semantic duplicates
Embeddings->>Groq: Create embedding
Embeddings->>Database: Query vector matches
DuplicateRoute->>Database: Fetch recent doubts if needed
DuplicateRoute->>Groq: Classify similarity matches
DuplicateRoute-->>AskDoubt: Return similarDoubts
Possibly related issues
Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
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 |
|
@coderabbitai review |
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)
src/components/classroom/AskDoubt.tsx (1)
138-161: 🎯 Functional Correctness | 🟠 Major | ⚡ Quick winNo error/failure feedback when the duplicate check fails.
checkSimilarityonly updates state onres.ok(Line 151); on 401/429/503/5xx responses,isCheckingSimilarityresets butsimilarityCheckedstaysfalse, so neither the "no similar doubts" nor the "similar doubts found" panel renders, and the user gets no indication the check failed. Given this feature exists specifically to prevent duplicate submissions, a silent failure defeats the purpose without any visible fallback state.♻️ Proposed fix: surface an error state
setIsCheckingSimilarity(true); try { const res = await fetch("/api/doubts/check-duplicate", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ content: text, classroomId }), }); if (res.ok) { const data = await res.json(); setSimilarDoubts(data.similarDoubts || []); setSimilarityChecked(true); + } else { + setSimilarDoubts([]); + setSimilarityChecked(false); + // surface a non-blocking notice, e.g. toast or inline message } } catch (err) { console.error("Similarity check failed:", err); + setSimilarDoubts([]); + setSimilarityChecked(false); } finally { setIsCheckingSimilarity(false); }As per path instructions,
**/*.tsxfiles should be reviewed for "Missing loading/error states."🤖 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 `@src/components/classroom/AskDoubt.tsx` around lines 138 - 161, Update checkSimilarity in AskDoubt to track and expose a similarity-check error when the response is non-OK or the request throws, clearing any stale error before each new request. Add the corresponding visible fallback in the duplicate-check UI so users are informed that the check failed and can retry, while preserving the existing similar-doubts and no-results states for successful responses.Source: Path instructions
🧹 Nitpick comments (4)
src/__tests__/lib/embeddings.test.ts (1)
15-24: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value
createDbMockis dead code.Defined but never invoked; the actual
jest.mock("@/configs/db", ...)factory (Lines 26-35) duplicates its shape inline instead of calling it.🤖 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 `@src/__tests__/lib/embeddings.test.ts` around lines 15 - 24, Remove the unused createDbMock helper and update the jest.mock("`@/configs/db`", ...) factory to reuse it instead of duplicating the database mock shape inline.src/__tests__/api/doubts-check-duplicate.test.ts (2)
60-69: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUnnecessary
groq-sdkmock.
@/lib/ai/groq-clientis already fully mocked (Lines 6-17), so nothing in the tested code path touches the realgroq-sdkmodule; this mock appears to be leftover/unused.🤖 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 `@src/__tests__/api/doubts-check-duplicate.test.ts` around lines 60 - 69, Remove the redundant groq-sdk jest.mock declaration from the test, keeping the existing `@/lib/ai/groq-client` mock unchanged so the tested code path remains isolated.
71-135: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winNo coverage for the authenticated/membership success path.
All three tests cover anonymous, rate-limited, and unauthenticated-classroom flows, but none exercise a successful
classroomIdrequest with a valid member (Lines 50-71 ofroute.ts). That path contains the duplicate rate-limit bug flagged inroute.ts— a test hitting it would have caught it.🤖 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 `@src/__tests__/api/doubts-check-duplicate.test.ts` around lines 71 - 135, The test suite lacks coverage for the authenticated classroom success path. Add a test in the “Doubt check-duplicate API endpoint” suite that mocks currentUser as a valid classroom member, configures the database query needed by POST, submits a request with classroomId, and asserts the successful response and duplicate-check behavior, including the relevant rate-limit interaction so the bug in the classroom branch is detected.src/app/api/doubts/check-duplicate/route.ts (1)
23-30: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winDuplicate
SimilarDoubttype definitions across client and server. Both files independently declare the same shape for the API response; centralizing it avoids drift as the contract evolves.
src/app/api/doubts/check-duplicate/route.ts#L23-L30: keep this as the canonical exportedSimilarDoubttype.src/components/classroom/AskDoubt.tsx#L26-L33: remove the local interface and importSimilarDoubtfrom the route module (or a shared types file) instead of redeclaring it.🤖 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 `@src/app/api/doubts/check-duplicate/route.ts` around lines 23 - 30, Keep the exported SimilarDoubt interface in src/app/api/doubts/check-duplicate/route.ts as the canonical definition. In src/components/classroom/AskDoubt.tsx, remove the duplicate local interface and import and use SimilarDoubt from the route module or an appropriate shared types file.
🤖 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 `@src/app/api/doubts/check-duplicate/route.ts`:
- Around line 50-71: Remove the redundant direct aiLimiter.limit(email) block
from the classroom branch of the duplicate-check handler. Keep
enforceApiRateLimit(aiLimiter, email, "ai") as the sole rate-limit enforcement
before membership validation, preserving its response and error-handling
behavior.
- Around line 73-88: Move the enforceAiAvailability(aiQuotaIdentifier) guard to
execute before findSemanticDuplicates in the duplicate-check flow, ensuring
AI-disabled and quota-blocked requests cannot reach Groq embeddings. Keep the
existing guard behavior before the LLM fallback without duplicating the check
unnecessarily, and preserve the semantic-duplicate response and fallback
handling.
- Line 78: Raise the duplicate-matching threshold from 80 to 90 throughout the
check-duplicate flow: update the similarityThreshold value, LLM fallback
similarity comparison, related default threshold, and prompt text. Ensure
AskDoubt.tsx receives only matches meeting the 90% threshold.
---
Outside diff comments:
In `@src/components/classroom/AskDoubt.tsx`:
- Around line 138-161: Update checkSimilarity in AskDoubt to track and expose a
similarity-check error when the response is non-OK or the request throws,
clearing any stale error before each new request. Add the corresponding visible
fallback in the duplicate-check UI so users are informed that the check failed
and can retry, while preserving the existing similar-doubts and no-results
states for successful responses.
---
Nitpick comments:
In `@src/__tests__/api/doubts-check-duplicate.test.ts`:
- Around line 60-69: Remove the redundant groq-sdk jest.mock declaration from
the test, keeping the existing `@/lib/ai/groq-client` mock unchanged so the tested
code path remains isolated.
- Around line 71-135: The test suite lacks coverage for the authenticated
classroom success path. Add a test in the “Doubt check-duplicate API endpoint”
suite that mocks currentUser as a valid classroom member, configures the
database query needed by POST, submits a request with classroomId, and asserts
the successful response and duplicate-check behavior, including the relevant
rate-limit interaction so the bug in the classroom branch is detected.
In `@src/__tests__/lib/embeddings.test.ts`:
- Around line 15-24: Remove the unused createDbMock helper and update the
jest.mock("`@/configs/db`", ...) factory to reuse it instead of duplicating the
database mock shape inline.
In `@src/app/api/doubts/check-duplicate/route.ts`:
- Around line 23-30: Keep the exported SimilarDoubt interface in
src/app/api/doubts/check-duplicate/route.ts as the canonical definition. In
src/components/classroom/AskDoubt.tsx, remove the duplicate local interface and
import and use SimilarDoubt from the route module or an appropriate shared types
file.
🪄 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 Plus
Run ID: f736527e-5b82-4116-95f8-76224262fdc2
📒 Files selected for processing (5)
src/__tests__/api/doubts-check-duplicate.test.tssrc/__tests__/lib/embeddings.test.tssrc/app/api/doubts/check-duplicate/route.tssrc/app/api/doubts/flag/route.tssrc/components/classroom/AskDoubt.tsx
💤 Files with no reviewable changes (1)
- src/app/api/doubts/flag/route.ts
Description
This PR implements an AI-powered doubt de-duplication system using
pgvectorfor semantic similarity search. It intercepts duplicate questions as students type, providing immediate feedback of existing similar doubts, thereby improving user experience and saving AI/server resources.Related Issue
Closes #1066
Type of Change
Screenshots (if UI change)
How Has This Been Tested?
npm run dev/api/doubts/check-duplicateroute andembeddingsutility functions.npx tsc --noEmit.Checklist
npm run dev)mainSummary by CodeRabbit
New Features
Bug Fixes
Tests