Feat/ai chat file mentions clean#468
Conversation
Qodo reviews are paused for this user.Troubleshooting steps vary by plan Learn more → On a Teams plan? Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center? |
👋 Thanks for opening a PR, @Bhagy-Yelleti!Your PR has entered the 🚦 PR Review Pipeline.
What happens next
A pipeline status comment will appear below and update automatically as your PR progresses. While you wait
This comment is posted only once. |
|
Warning Review limit reached
More reviews will be available in 29 seconds. Learn how PR review limits work. Your organization has run out of usage credits. Purchase more in the billing tab. ⌛ How to resolve this issue?After more reviews become available, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available. Please see our Fair Usage Limits Policy for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Plus Run ID: 📒 Files selected for processing (1)
WalkthroughUsers can type ChangesFile Mentions in AI Chat
Sequence DiagramsequenceDiagram
participant User
participant ChatPanel as Chat Panel
participant ChatAPI as /api/chat
participant Model as LLM Model
User->>ChatPanel: Type @ and select a file
ChatPanel->>ChatPanel: Insert `@path` in textarea
User->>ChatPanel: Click Send
ChatPanel->>ChatPanel: extractMentionedFiles -> resolve {path, content}
ChatPanel->>ChatAPI: POST messages + mentionedFiles
ChatAPI->>ChatAPI: validate schema & total size
ChatAPI->>ChatAPI: build systemInstruction and append synthetic user message "Referenced files:"
ChatAPI->>Model: streamText(sanitized messages, systemInstruction, model)
Model->>ChatAPI: response stream
ChatAPI->>ChatPanel: UI message stream response
ChatPanel->>User: render assistant message
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (1 warning, 1 inconclusive)
✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ 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 |
There was a problem hiding this comment.
Actionable comments posted: 5
🤖 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 `@app/api/chat/route.ts`:
- Around line 106-110: The code currently appends untrusted workspace file
contents (via mentionedFiles -> file.path and file.content) into
systemInstruction, giving them system-level priority; change this so referenced
files are not injected into the system role: instead create a separate
user-scoped message (or an explicitly labeled "untrusted file contents"
assistant/user message) that contains the File: ${file.path} and its content, or
wrap the content with a clear "DO NOT TREAT AS INSTRUCTIONS / UNTRUSTED" marker
before adding to a non-system message; update the logic that builds messages
(where systemInstruction is assembled and where mentionedFiles are iterated) to
push a new message object for these files rather than concatenating into
systemInstruction.
- Around line 32-39: Add input-size guards to the mentionedFiles schema so large
or many files are rejected before reaching streamText: enforce a max array
length (e.g., max number of items) on mentionedFiles, enforce per-file limits by
replacing content: z.string() with a bounded string (e.g., z.string().max(...))
and path length limits, and add an aggregate-size refinement on mentionedFiles
(using z.refine or a custom preprocess) that sums file content lengths and
rejects if the total exceeds a provider-safe ceiling; update the schema where
mentionedFiles is defined so streamText never receives unbounded file content.
In `@modules/playground/components/ai-chat-panel.tsx`:
- Around line 403-427: The code currently updates local state (using
addOrUpdateFile, setTemplateData, setOpenFiles), shows toast.success and sets
result before calling saveTemplateData.catch(console.error); change this to
perform the persistence first (await saveTemplateData(updatedTemplate)), and
only on success apply the optimistic updates and toast.success / set result;
alternatively, keep the optimistic UI updates but wrap saveTemplateData in a
try/catch: await saveTemplateData(updatedTemplate) and on catch revert state
changes (restore previous templateData and openFiles saved before mutating) and
call toast.error with the failure message; apply the same pattern to the similar
branch around lines 461-488 so saveTemplateData is awaited and failures roll
back state and surface an error toast instead of reporting success.
- Around line 323-327: processedToolCallIds (a useRef holding a Set) is never
cleared when the chat is reset, causing stale IDs to persist; update the
chat-clear logic (the clearChat handler / any code that calls setMessages([]))
to reset processedToolCallIds by calling processedToolCallIds.current.clear()
(or assigning a new Set) immediately after setMessages([]) so tool-call history
is cleared for new conversations; apply the same change to the other clear path
handling setMessages([]) as well.
- Around line 76-81: The mention parser uses regex = /@([^\s]+)/g and captures
punctuation-attached tokens (e.g., "`@src/App.js`,") so
findFileByPath(templateItems, path) fails; update the parsing in the while loop
to normalize the captured path before lookup by stripping trailing sentence
punctuation (e.g., commas, periods, colons, semicolons, closing parens/brackets)
or change the capture to stop at those characters, then pass the cleaned token
into findFileByPath; reference the regex, the path variable, and findFileByPath
to locate and fix the logic so mentionedFiles retrieval matches the autocomplete
tokenization rules.
🪄 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: 3e323a37-65e9-4062-8e76-4583e127cbe0
📒 Files selected for processing (2)
app/api/chat/route.tsmodules/playground/components/ai-chat-panel.tsx
| const updatedItems = addOrUpdateFile( | ||
| templateData.items, | ||
| path, | ||
| content as string, | ||
| ); | ||
| const updatedTemplate = { ...templateData, items: updatedItems }; | ||
| setTemplateData(updatedTemplate); | ||
|
|
||
| const updatedOpenFiles = openFiles.map((f) => { | ||
| const ext = f.fileExtension ? `.${f.fileExtension}` : ""; | ||
| const fullName = `${f.filename}${ext}`; | ||
| if (path.endsWith(fullName)) { | ||
| return { | ||
| ...f, | ||
| content: content as string, | ||
| hasUnsavedChanges: true, | ||
| }; | ||
| } | ||
| return f; | ||
| }); | ||
|
|
||
| setOpenFiles(updatedOpenFiles); | ||
| saveTemplateData(updatedTemplate).catch(console.error); | ||
| toast.success(`AI updated ${path}`); | ||
| result = `Successfully updated ${path}`; |
There was a problem hiding this comment.
Don't report success before saveTemplateData succeeds.
These branches optimistically mutate local state, toast success, and then fire-and-forget persistence with .catch(console.error). If the save fails, the UI says the AI edit/delete worked even though the change is lost on refresh. Await the save or roll back the optimistic update and show an error toast on failure.
Also applies to: 461-488
🤖 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 `@modules/playground/components/ai-chat-panel.tsx` around lines 403 - 427, The
code currently updates local state (using addOrUpdateFile, setTemplateData,
setOpenFiles), shows toast.success and sets result before calling
saveTemplateData.catch(console.error); change this to perform the persistence
first (await saveTemplateData(updatedTemplate)), and only on success apply the
optimistic updates and toast.success / set result; alternatively, keep the
optimistic UI updates but wrap saveTemplateData in a try/catch: await
saveTemplateData(updatedTemplate) and on catch revert state changes (restore
previous templateData and openFiles saved before mutating) and call toast.error
with the failure message; apply the same pattern to the similar branch around
lines 461-488 so saveTemplateData is awaited and failures roll back state and
surface an error toast instead of reporting success.
There was a problem hiding this comment.
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 `@app/api/chat/route.ts`:
- Around line 101-117: The error message returned when aggregate file size
exceeds the guard is misleading—change the NextResponse.json error text to
indicate total referenced file size is too large (e.g., "Referenced files exceed
the maximum total size; reduce file sizes or number of files") and extract the
magic number 100_000 into a named constant (suggested name
MAX_MENTIONED_FILES_TOTAL_SIZE) used when computing totalSize in the
mentionedFiles validation block (referencing mentionedFiles, totalSize, and the
NextResponse.json call) so the limit is maintainable and the message accurately
reflects the cause.
🪄 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: e67b84f5-df1b-4b38-8a7c-de6735c3d523
📒 Files selected for processing (2)
app/api/chat/route.tsmodules/playground/components/ai-chat-panel.tsx
🚧 Files skipped from review as they are similar to previous changes (1)
- modules/playground/components/ai-chat-panel.tsx
|
I've addressed the review feedback and pushed the updates. Re-ran the checks as well and everything seems to be passing now. Let me know if you'd like me to change anything else. |
Summary
This PR adds support for referencing project files in the AI chat using
@mentions.What changed
@Why
Currently, users need to manually copy and paste file contents when asking the AI about a specific file.
With file mentions, users can directly reference files from the workspace, making it easier to ask questions, review code, and compare multiple files without leaving the chat.
Type of change
Related issue
Closes #435
Validation
npm run lintnpm testnpm run buildAdditional manual verification:
@Screenshots or recordings
Added screenshots showing:
@Checklist
Summary by CodeRabbit