Skip to content

Feat/ai chat file mentions clean#468

Open
Bhagy-Yelleti wants to merge 4 commits into
piyushdotcomm:mainfrom
Bhagy-Yelleti:feat/ai-chat-file-mentions-clean
Open

Feat/ai chat file mentions clean#468
Bhagy-Yelleti wants to merge 4 commits into
piyushdotcomm:mainfrom
Bhagy-Yelleti:feat/ai-chat-file-mentions-clean

Conversation

@Bhagy-Yelleti

@Bhagy-Yelleti Bhagy-Yelleti commented Jun 4, 2026

Copy link
Copy Markdown

Summary

This PR adds support for referencing project files in the AI chat using @ mentions.

What changed

  • Added file mention support in the AI chat input
  • Shows file suggestions when typing @
  • Allows selecting files directly from the suggestion list
  • Supports multiple file mentions in a single prompt
  • Sends the contents of mentioned files to the AI so responses can use the referenced code

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

  • Bug fix
  • New feature
  • Refactor
  • Documentation
  • Test or CI improvement
  • Starter template change

Related issue

Closes #435

Validation

  • npm run lint
  • npm test
  • npm run build

Additional manual verification:

  • Verified file suggestions appear when typing @
  • Verified selecting a suggestion inserts the correct file path
  • Verified multiple file mentions work in the same prompt
  • Verified mentioned files are included in the chat request payload

Screenshots or recordings

Added screenshots showing:

  • File suggestion dropdown after typing @
  • Multiple file mentions being inserted into the chat input
editron12344 editron23456678

Checklist

  • I kept this PR focused on one primary change
  • I updated documentation if behavior changed
  • I did not commit secrets, local logs, or scratch files
  • I am requesting review on the correct scope

Summary by CodeRabbit

  • New Features
    • Typing @ in chat shows file autocomplete; selecting inserts the file path and includes referenced files with your message.
    • Mentioned files are sent as optional context with per-file and total size limits to keep responses efficient.
    • Groq model provider updated to a newer model version.
  • Bug Fixes / UX
    • Outside clicks close the provider picker and mention dropdown; sending resets mention state and textarea sizing.

@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@github-actions

github-actions Bot commented Jun 4, 2026

Copy link
Copy Markdown

👋 Thanks for opening a PR, @Bhagy-Yelleti!

Your PR has entered the 🚦 PR Review Pipeline.

Standard PR detected — your PR will follow the standard review pipeline.


What happens next

Stage Reviewer Checks
Stage 1 — Automated Validation 🤖 Bot DCO · Format · AI/Slop · Duplicate
Stage 2 — Human Review 👥 Maintainer Code + Quality Review
Stage 3 — PA / Maintainer Review 🔑 Project Admin Final Merge Decision

A pipeline status comment will appear below and update automatically as your PR progresses.


While you wait

  • Sign all commits (git commit -s)
  • Link your issue (Closes #123)
  • Use a feature branch (not main)
  • Avoid unrelated changes

This comment is posted only once.

@coderabbitai

coderabbitai Bot commented Jun 4, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

@Bhagy-Yelleti, we couldn't start this review because you've reached your PR review rate limit.

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 @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: 3b1e11aa-77aa-4c16-8bf3-fd681c117903

📥 Commits

Reviewing files that changed from the base of the PR and between ec33e65 and 71ca052.

📒 Files selected for processing (1)
  • app/api/chat/route.ts

Walkthrough

Users can type @ in the AI chat to mention workspace files. The UI offers file suggestions, inserts chosen paths into the composer, and the client sends resolved { path, content } as mentionedFiles. The server validates sizes, sanitizes messages, appends a synthetic user message with the referenced files, and streams model output.

Changes

File Mentions in AI Chat

Layer / File(s) Summary
Backend: API schema, validation, and message assembly
app/api/chat/route.ts
Request schema accepts optional mentionedFiles array with { path, content }. Server validates total referenced content size (≤100,000), refactors systemInstruction assembly to start from SYSTEM_PROMPT and conditionally include fileTree, updates Groq model to llama-3.3-70b-versatile, sanitizes messages (including parts entries having a type), and appends a synthetic user message titled "Referenced files:" containing paths and contents before calling streamText.
Frontend: imports, types, and utilities
modules/playground/components/ai-chat-panel.tsx
Add mention primitives and types (extractMentionedFiles, MessagePart, ExtendedMessage) and update imports to support mention UI (File icon).
Frontend: mention state, refs, and suggestion logic
modules/playground/components/ai-chat-panel.tsx
Extend component state/refs for mention dropdown, memoize template file path list, compute hasUnresolvedTools gating, and implement updateMentionSuggestions to find active @... token and filter candidate paths.
Frontend: insert mention, send flow, and outside-click
modules/playground/components/ai-chat-panel.tsx
Implement insertMention to replace the active @... token and set cursor; update textarea onChange to drive suggestions; sendMessage resolves mentioned file contents, includes mentionedFiles in the useChat request, resets mention UI and textarea height after send, and add outside-click listener that closes provider and mention dropdowns.
Frontend: tool execution effect & composer rendering
modules/playground/components/ai-chat-panel.tsx
Preserve assistant tool-part execution effect with processedToolCallIds guard to apply read_file, edit_file, edit_multiple_files, and delete_file mutations, persist via saveTemplateData, report via addToolResult; render mention suggestions dropdown and integrate mention-aware textarea behavior in the chat footer.

Sequence Diagram

sequenceDiagram
  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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

A rabbit hops across the thread,
I nibble code and ink it red.
Type @ and files will come along,
They hum the lines and sing the song. 🐇✨

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'Feat/ai chat file mentions clean' is vague and uses unclear terminology; 'clean' lacks specific meaning about the changeset. Clarify the title to specifically describe the main feature (e.g., 'Add @mention support for referencing files in AI chat').
✅ Passed checks (3 passed)
Check name Status Explanation
Description check ✅ Passed The PR description is comprehensive and complete, covering what changed, why it changed, proper type selection, related issue, and validation steps with screenshots.
Linked Issues check ✅ Passed The code changes fully implement all acceptance criteria from issue #435: @mention opens file picker, users can search and select files, mentioned files are included in AI context, and multiple mentions are supported.
Out of Scope Changes check ✅ Passed All changes are scoped to implementing file mention support: chat route validation for mentionedFiles, AI panel mention dropdown UI, and file content serialization. Minor model version update (Groq provider) appears to be incidental maintenance.

✏️ 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.

@github-actions github-actions Bot added the enhancement New feature or request label Jun 4, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between f12b223 and 24b36bb.

📒 Files selected for processing (2)
  • app/api/chat/route.ts
  • modules/playground/components/ai-chat-panel.tsx

Comment thread app/api/chat/route.ts
Comment thread app/api/chat/route.ts Outdated
Comment thread modules/playground/components/ai-chat-panel.tsx
Comment thread modules/playground/components/ai-chat-panel.tsx
Comment on lines +403 to +427
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}`;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

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 `@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

📥 Commits

Reviewing files that changed from the base of the PR and between 24b36bb and ec33e65.

📒 Files selected for processing (2)
  • app/api/chat/route.ts
  • modules/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

Comment thread app/api/chat/route.ts
@Bhagy-Yelleti

Copy link
Copy Markdown
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

enhancement New feature or request

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Add File Mentions in AI Chat Using @ Syntax

1 participant