Skip to content

feat: AI Code Review Panel for DSA Submissions (#857)#1418

Open
ChandanMeher4 wants to merge 7 commits into
Sachinchaurasiya360:mainfrom
ChandanMeher4:feat/dsa-ai-code-review
Open

feat: AI Code Review Panel for DSA Submissions (#857)#1418
ChandanMeher4 wants to merge 7 commits into
Sachinchaurasiya360:mainfrom
ChandanMeher4:feat/dsa-ai-code-review

Conversation

@ChandanMeher4
Copy link
Copy Markdown
Contributor

@ChandanMeher4 ChandanMeher4 commented Jun 4, 2026

Description

Adds a manual AI code review feature to the DSA problem-solving page. After running the code and seeing the test results, a new "AI Review" tab appears in the right panel. Clicking "Get AI Review" sends the submissionId to the backend, which fetches the submission and problem context from the DB and calls Gemini. The review renders time/space complexity, readability score, edge cases, and improvement suggestions.

The review is manually triggered rather than auto-firing after every run - this keeps API costs minimal. Only Premium users can execute code at all, so the endpoint is already naturally gated behind the existing Premium wall with zero extra logic needed.

Related Issue

Fixes #857

Type of Change

  • Bug Fix
  • Feature
  • Enhancement
  • Documentation

Testing

  1. Log in as a Premium user
  2. Open any DSA problem
  3. Write and run code against test cases
  4. Click the "AI Review" tab in the right panel
  5. Click "Get AI Review" button
  6. Verify the review renders with time/space complexity, readability score, edge cases, and suggestions
  7. Verify the loading spinner appears while Gemini processes
  8. Verify the error state and retry button work correctly
  9. Verify "Re-analyze" button triggers a fresh review

Screenshots

Screenshot 2026-06-05 023046 Screenshot 2026-06-05 023123

Checklist

  • Code follows project guidelines
  • No new compile/type errors
  • Tested manually (include steps above)
  • No .env, credentials, or node_modules committed
  • Docs updated (if needed)
  • Screenshot or video attached for every UI change

Summary by CodeRabbit

  • New Features
    • AI code review for DSA submissions (premium users): analyzes time/space complexity, provides a readability score with a visual meter, lists edge cases and improvement suggestions.
    • New "AI Review" right-side tab: shows loading, clear error states (including rate-limit feedback) with retry, an initial CTA disabled until a submission exists, and a Re-analyze action.

@github-actions github-actions Bot added quality:clean Clean and well-structured contribution gssoc:approved Approved for GSSoC scoring level:advanced Complex implementation or logic labels Jun 4, 2026
@github-actions
Copy link
Copy Markdown

github-actions Bot commented Jun 4, 2026

Hi @ChandanMeher4, thanks for contributing to InternHack! 🎉

I have automatically:

  • 👤 Assigned this PR to you.
  • 🏷️ Applied the gssoc:approved label.

Our workflows will now analyze your changes to classify:

  • 📈 PR Difficulty: level:*
  • 🧩 PR Type: type:*
  • 🌟 PR Quality: quality:*

Tip

Ensure your PR description references the issue it resolves (e.g. Closes #123). This allows the bot to inherit any additional labels from that issue!

Happy coding! 🚀

@github-actions github-actions Bot added type:feature New feature implementation scope:backend Changes to server-side / API code scope:database Database schema or migration changes scope:frontend Changes to client-side / UI code labels Jun 4, 2026
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Jun 4, 2026

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: de67b977-b950-4d41-b764-82c9f9894a68

📥 Commits

Reviewing files that changed from the base of the PR and between 835594e and 60b9d51.

📒 Files selected for processing (2)
  • server/src/module/admin/admin.validation.ts
  • server/src/module/dsa/dsa.service.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • server/src/module/admin/admin.validation.ts
  • server/src/module/dsa/dsa.service.ts

📝 Walkthrough

Walkthrough

Adds end-to-end AI code review: new type and Zod schema, Prisma enum and admin schema update, DsaService prompt/parse/logging, controller+route for POST review, and client UI (ai-review tab, mutation, DsaAiReviewPanel).

Changes

DSA AI Code Review

Layer / File(s) Summary
Data contracts and validation schema
server/src/module/dsa/dsa.validation.ts, client/src/lib/types/learning.types.ts, server/src/database/prisma/schema/base.prisma, server/src/module/admin/admin.validation.ts
codeReviewResponseSchema and CodeReviewResponse define the review shape; client DsaCodeReview mirrors it. Prisma AIServiceType gains DSA_CODE_REVIEW; admin schema accepts the new service.
Backend service and AI integration
server/src/module/dsa/dsa.service.ts
generateCodeReview(submissionId, studentId) loads submission+problem, gets DSA_CODE_REVIEW provider, builds structured prompt (buildCodeReviewPrompt), calls provider, logs request, records usage, and parses/validates output via parseCodeReviewResponse (markdown stripping, trailing-comma removal, JSON fallback, Zod validation, best-effort coercion/clamping).
Controller and route setup
server/src/module/dsa/dsa.controller.ts, server/src/module/dsa/dsa.routes.ts
Controller generateCodeReview checks auth and premium access, validates submissionId then delegates to service. Adds POST /submissions/:submissionId/review with student auth and CODE_RUN usage limit.
DSA problem detail page tab and mutation
client/src/module/student/dsa/DsaProblemDetailPage.tsx
Imports DsaCodeReview, Sparkles, and DsaAiReviewPanel; extends rightTab to include "ai-review"; defines aiReviewMutation POSTing to review endpoint with distinct 429 vs generic error toasts and a reset effect; adds tab entry and conditional rendering to mount DsaAiReviewPanel.
AI Review panel component
client/src/module/student/dsa/components/DsaAiReviewPanel.tsx
New exported component showing loading spinner, parsed error state with retry, initial CTA (disabled until submission exists), and completed review view (time/space complexity, readability score with progress bar and mapped label/color, conditional edge cases and suggestions lists, re-analyze button).

Sequence Diagram

sequenceDiagram
  participant Student as Student (Browser)
  participant DetailPage as DsaProblemDetailPage
  participant API as DsaController / Route
  participant Service as DsaService
  participant AIProvider as AI Provider (DSA_CODE_REVIEW)
  participant ReviewPanel as DsaAiReviewPanel

  Student->>DetailPage: Click "Run Code"
  DetailPage->>DetailPage: executeMutation runs (Judge0)
  DetailPage-->>Student: Test results (instant)
  DetailPage->>API: POST /dsa/submissions/{id}/review (aiReviewMutation)
  API->>Service: generateCodeReview(submissionId, userId)
  Service->>Service: Load submission, verify ownership, load problem context
  Service->>AIProvider: Call with buildCodeReviewPrompt(payload)
  AIProvider-->>Service: Raw AI response (text)
  Service->>Service: parseCodeReviewResponse(text)
  Service-->>API: CodeReviewResponse (validated/fallback)
  API-->>DetailPage: Review data
  DetailPage->>ReviewPanel: Provide review / isLoading / error
  ReviewPanel-->>Student: Render complexity, readability, edge cases, suggestions
  Student->>ReviewPanel: Click "Re-analyze"
  ReviewPanel->>API: POST /dsa/submissions/{id}/review (retry)
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Suggested labels

level:intermediate

Suggested reviewers

  • Sachinchaurasiya360

Poem

🐰 A little rabbit reads your code tonight,
Sparkles on the tab and feedback in sight.
Complexity ranked, readability scored,
Edge cases noted and suggestions stored.
Re-analyze, hop on—learn and code bright!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

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.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title accurately summarizes the main feature: adding an AI Code Review Panel for DSA Submissions, matching the changeset's primary objective.
Description check ✅ Passed The description covers the feature scope, testing steps, and includes required screenshots; however, the 'Docs updated' checklist is unchecked, which may require clarification.
Linked Issues check ✅ Passed The PR implements all core coding requirements from #857: adds DsaCodeReview interface, DsaAiReviewPanel component, controller/service methods with auth checks, Zod validation, and new schema enum value with route protection.
Out of Scope Changes check ✅ Passed All code changes align with #857 objectives; modifications to admin validation and schema enum are directly required for the feature implementation.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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: 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 `@server/src/module/dsa/dsa.service.ts`:
- Line 962: The logAIRequest call records success before parseCodeReviewResponse
validates the output; move or update logging so success is only set after
parseCodeReviewResponse completes without throwing. Wrap
parseCodeReviewResponse(response) in a try/catch (or await and check result) and
call logAIRequest("DSA_CODE_REVIEW", response, true, undefined, studentId) only
on successful validation, and call logAIRequest(..., false, error, studentId)
inside the catch to record failures; reference the existing logAIRequest and
parseCodeReviewResponse calls to locate where to adjust logging.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1c0586e6-3b7a-472e-84e5-7bfba1402c74

📥 Commits

Reviewing files that changed from the base of the PR and between e15a36c and 670b755.

📒 Files selected for processing (8)
  • client/src/lib/types/learning.types.ts
  • client/src/module/student/dsa/DsaProblemDetailPage.tsx
  • client/src/module/student/dsa/components/DsaAiReviewPanel.tsx
  • server/src/database/prisma/schema/base.prisma
  • server/src/module/dsa/dsa.controller.ts
  • server/src/module/dsa/dsa.routes.ts
  • server/src/module/dsa/dsa.service.ts
  • server/src/module/dsa/dsa.validation.ts

Comment thread server/src/module/dsa/dsa.service.ts Outdated
@Sachinchaurasiya360
Copy link
Copy Markdown
Owner

Code Review — PR #1418: AI Code Review Panel for DSA Submissions

Hi @ChandanMeher4, the panel UI is clean and the mutation error handling is solid. Found two issues to address.


🔴 Backend endpoint POST /dsa/submissions/:submissionId/review is not in this diff

The client calls:

api.post<DsaCodeReview>(`/dsa/submissions/${submissionId}/review`)

But this PR only adds the client-side DsaAiReviewPanel component and the mutation. There is no corresponding server-side route, controller, or service method in the diff. Without the backend, clicking "Get AI Review" will always return a 404 and show the error state.

Please include the server implementation in this PR:

  • Route: POST /dsa/submissions/:submissionId/review in dsa.routes.ts
  • Controller method to handle auth, ownership check, and usage limiting
  • Service method that calls Gemini and returns the DsaCodeReview shape
  • Zod validation for the response schema

Also confirm a UsageAction exists or document which existing one you're reusing (per project rules: do not fabricate new UsageAction enum values to avoid migrations).


🟡 aiReviewMutation resets to null when the user changes the problem — stale review shown

The aiReviewMutation state is tied to the component instance, not to problemId. If a user requests a review on Problem A, then navigates to Problem B, the Problem A review is still in aiReviewMutation.data. When the user switches back to "ai-review" tab on Problem B before requesting a new review, they'll see Problem A's review with no indication it's stale.

Reset the mutation when problemId changes:

useEffect(() => {
  aiReviewMutation.reset();
}, [problem?.id]);

Copy link
Copy Markdown
Owner

@Sachinchaurasiya360 Sachinchaurasiya360 left a comment

Choose a reason for hiding this comment

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

The module pattern, prompt engineering, client component structure, and error handling are all solid. However there are five issues that must be fixed before this can merge.

Issue 1 (Critical) - Missing Prisma migration for DSA_CODE_REVIEW enum value:

The PR adds DSA_CODE_REVIEW to the AIServiceType enum in base.prisma but ships no migration file. Every prior enum addition has a corresponding migration with ALTER TYPE "AIServiceType" ADD VALUE. Without it the production PostgreSQL type is never updated and the getProviderForService("DSA_CODE_REVIEW") call will fail at runtime. Add a migration file with:

ALTER TYPE "AIServiceType" ADD VALUE 'DSA_CODE_REVIEW';

Issue 2 (Critical) - No server-side premium gating:

The /submissions/:submissionId/review endpoint does not check premium status. A non-premium user with a submissionId can call it freely. The claim that "only premium users can run code so it is implicitly gated" is incorrect - the submissionId is not a secret and the endpoint has no isPremiumUser check. Add the same pattern used in latex-chat.controller.ts and ats.controller.ts: check subscriptionPlan (MONTHLY or YEARLY) and subscriptionStatus (ACTIVE), return 403 if not premium.

Issue 3 (Critical) - Usage not logged so the rate limit counter never increments:

The route applies usageLimit("CODE_RUN") as a guard but generateCodeReview in dsa.service.ts never writes a UsageLog entry after a successful review. Compare with executeCode which explicitly calls prisma.usageLog.create after execution. Without the write, the daily cap checks but never charges, allowing unlimited calls after the first one passes.

Issue 4 (Critical) - DSA_CODE_REVIEW missing from admin validation schema:

admin.validation.ts has a hardcoded z.enum([...]) of AIServiceType values for the admin AI config endpoint. DSA_CODE_REVIEW is not included. Admins cannot configure the model or provider for this service through the admin panel and any attempt returns a Zod 400.

Issue 5 (High) - No aiServiceConfig seed row documented or provided:

getProviderForService falls back silently to the default Gemini model if no row exists for DSA_CODE_REVIEW in aiServiceConfig. The PR needs to either add a seed entry or document the manual admin-panel step needed after deploy, so the service does not run silently on an unconfigured fallback.

Minor:

  • rounded-full on the loading spinner in DsaAiReviewPanel - confirm with the maintainer whether spinners are exempt from the no-rounded-full rule.
  • Raw Error throws in dsa.service.ts for "Submission not found" and "Not authorized" will surface as 500s. Handle them explicitly in the controller for proper 404/403 responses.

Fix the five critical issues and this is ready for another review pass. The AI prompt, Zod schema, client mutation handling, and ownership check are all well done.

@Sachinchaurasiya360
Copy link
Copy Markdown
Owner

Update on Issue 1: the project uses prisma db push instead of manual migration files, so no migration SQL file is needed. The schema change adding DSA_CODE_REVIEW to AIServiceType is sufficient on its own. Issue 1 is no longer blocking.

Issues 2-5 still need to be addressed before merge:

  • No server-side premium gating on the review endpoint
  • Usage never logged so the rate limit counter never increments
  • DSA_CODE_REVIEW missing from the admin validation z.enum
  • No aiServiceConfig row for the new service type

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: 1

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
server/src/module/dsa/dsa.service.ts (1)

1049-1059: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Return a fallback response when parsing fails completely.

Lines 1049-1059 still throw on unrecoverable parse failure, which can fail the endpoint instead of degrading safely with a default CodeReviewResponse.

💡 Minimal fallback patch
     let parsed: unknown;
     try {
       parsed = JSON.parse(jsonStr);
     } catch {
       // Try to extract just the JSON object if there's surrounding text
       const objMatch = jsonStr.match(/\{[\s\S]*\}/);
       if (objMatch) {
         const cleaned = objMatch[0].replace(/,\s*([\]}])/g, "$1");
         parsed = JSON.parse(cleaned);
       } else {
-        throw new Error("Failed to parse AI code review response");
+        return {
+          timeComplexity: "Unable to determine",
+          spaceComplexity: "Unable to determine",
+          readability: { score: 5, feedback: "No feedback available" },
+          edgeCases: [],
+          suggestions: [],
+        };
       }
     }

As per coding guidelines, "Always handle AI parse failures with fallbacks in Gemini responses".

🤖 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 `@server/src/module/dsa/dsa.service.ts` around lines 1049 - 1059, The JSON
parse catch currently throws on unrecoverable failures; instead, in the catch
branch where neither direct JSON.parse nor the object-extraction path succeeds,
construct and return a safe default CodeReviewResponse (e.g., an object matching
the CodeReviewResponse shape with empty/neutral fields like success: false,
summary: "Unable to parse AI response", comments: []) rather than throwing;
update the function around variables parsed and jsonStr (in dsa.service.ts) so
that when parsed remains undefined you return this fallback CodeReviewResponse
to degrade gracefully.
🤖 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 `@server/src/module/admin/admin.validation.ts`:
- Line 350: The validation enum for switchAIProviderSchema.service is missing
the "EMAIL_CHAT" value and thus is out of sync with the Prisma AIServiceType;
update the enum in admin.validation.ts (the switchAIProviderSchema.service
definition) to include "EMAIL_CHAT" so it matches AIServiceType and accepts
admin requests for that service.

---

Outside diff comments:
In `@server/src/module/dsa/dsa.service.ts`:
- Around line 1049-1059: The JSON parse catch currently throws on unrecoverable
failures; instead, in the catch branch where neither direct JSON.parse nor the
object-extraction path succeeds, construct and return a safe default
CodeReviewResponse (e.g., an object matching the CodeReviewResponse shape with
empty/neutral fields like success: false, summary: "Unable to parse AI
response", comments: []) rather than throwing; update the function around
variables parsed and jsonStr (in dsa.service.ts) so that when parsed remains
undefined you return this fallback CodeReviewResponse to degrade gracefully.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: 64091797-8512-494e-a623-8e6dd27abfa2

📥 Commits

Reviewing files that changed from the base of the PR and between 1ed21a4 and 835594e.

📒 Files selected for processing (6)
  • client/src/module/student/dsa/DsaProblemDetailPage.tsx
  • client/src/module/student/dsa/components/DsaAiReviewPanel.tsx
  • server/src/database/prisma/schema/base.prisma
  • server/src/module/admin/admin.validation.ts
  • server/src/module/dsa/dsa.controller.ts
  • server/src/module/dsa/dsa.service.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • client/src/module/student/dsa/DsaProblemDetailPage.tsx
  • client/src/module/student/dsa/components/DsaAiReviewPanel.tsx

Comment thread server/src/module/admin/admin.validation.ts Outdated
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gssoc:approved Approved for GSSoC scoring level:advanced Complex implementation or logic quality:clean Clean and well-structured contribution scope:backend Changes to server-side / API code scope:database Database schema or migration changes scope:frontend Changes to client-side / UI code type:feature New feature implementation

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[FEATURE]: AI Code Review Panel for DSA Submissions

2 participants