Skip to content

fix: exclude test files from AI context window - #538

Open
Somil450 wants to merge 1 commit into
piyushdotcomm:mainfrom
Somil450:fix/528-exclude-test-files-from-ai-context
Open

fix: exclude test files from AI context window#538
Somil450 wants to merge 1 commit into
piyushdotcomm:mainfrom
Somil450:fix/528-exclude-test-files-from-ai-context

Conversation

@Somil450

Copy link
Copy Markdown

Summary

Closes #528

Modifies collectFilePaths() in useAI.ts to filter out files containing .test. or .spec..

Problem

The AI chat panel receives a fileTree string (a list of all files in the current template) as system context. Previously, this included test files. Test files (and their associated mock data) are often quite large and rarely useful for the AI's general context window unless explicitly asked for, leading to unnecessary token waste.

Change

// modules/playground/hooks/useAI.ts

 } else {
     const ext = item.fileExtension ? `.${item.fileExtension}` : "";
-    paths.push(prefix ? `${prefix}/${item.filename}${ext}` : `${item.filename}${ext}`);
- +    const fileName = `${item.filename}${ext}`;
- +    if (fileName.includes(".test.") || fileName.includes(".spec.")) continue;
- +    paths.push(prefix ? `${prefix}/${fileName}` : fileName);
-  }
- ```
## Files Changed

- `modules/playground/hooks/useAI.ts` - 3 lines added, 1 line removed

Closes piyushdotcomm#528

Test files (.test.*, .spec.*) can be very large and are rarely useful
in the general AI context window for code generation and Chat.
This commit excludes them in collectFilePaths(), saving tokens and
improving context relevance.
@Somil450
Somil450 requested a review from piyushdotcomm as a code owner July 31, 2026 09:31
@coderabbitai

coderabbitai Bot commented Jul 31, 2026

Copy link
Copy Markdown

Warning

Review limit reached

@Somil450, you've reached your PR review limit, so we couldn't start this review.

Next review available in: 10 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

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.

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 configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro Plus

Run ID: cd48241b-9966-4ce5-ac9d-667886f81d52

📥 Commits

Reviewing files that changed from the base of the PR and between 4ffe26f and ad76207.

📒 Files selected for processing (1)
  • modules/playground/hooks/useAI.ts

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

Copy link
Copy Markdown

👋 Thanks for opening a PR, @Somil450!

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.

@github-actions github-actions Bot added the bug Something isn't working label Jul 31, 2026
@qodo-code-review

Copy link
Copy Markdown

PR Summary by Qodo

Exclude .test/.spec files from AI fileTree context

🐞 Bug fix 🕐 Less than 10 minutes

Grey Divider

AI Description

• Filter out .test.* and .spec.* files when building the AI fileTree context.
• Reduce wasted tokens from large test/mocks in the default AI system context.
• Keep test files available only when explicitly requested via normal file access.
Diagram

graph TD
  UI["AI Chat Panel"] --> HOOK["useAI.ts"] --> CFP["collectFilePaths() (filters tests)"] --> CTX[("fileTree context string")] --> LLM["LLM prompt context"]
  FS[("Template file items")] --> CFP
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Configurable ignore patterns (gitignore-style or settings)
  • ➕ Lets teams tailor exclusions (e.g., mocks, fixtures, generated files) without code changes
  • ➕ Avoids hardcoding conventions that may differ across templates
  • ➖ Adds configuration surface area and UI/UX decisions
  • ➖ More code paths to test and document
2. Heuristic-based filtering (size/token budget aware)
  • ➕ Directly optimizes for context window constraints regardless of filename patterns
  • ➕ Can keep small, useful tests while excluding very large ones
  • ➖ More complex and potentially non-deterministic behavior
  • ➖ Requires estimating token counts / file sizes and tuning thresholds

Recommendation: The current approach (excluding .test./.spec. by name) is the best short-term fix: it’s deterministic, minimal risk, and directly addresses the reported token-waste issue. If more exclusions are needed later, consider graduating to configurable ignore patterns rather than expanding hardcoded rules.

Files changed (1) +3 / -1

Bug fix (1) +3 / -1
useAI.tsSkip .test/.spec paths when collecting AI fileTree +3/-1

Skip .test/.spec paths when collecting AI fileTree

• Updates 'collectFilePaths()' to build a 'fileName' and skip entries containing '.test.' or '.spec.' before adding them to the returned path list. This prevents test files from being included in the default AI context payload.

modules/playground/hooks/useAI.ts

@qodo-code-review

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (2) 📘 Rule violations (0) 📜 Skill insights (0)

Context used
✅ Compliance rules (platform): 22 rules

Grey Divider


Remediation recommended

1. Incomplete test filtering 🐞 Bug ≡ Correctness
Description
collectFilePaths() only skips files whose basename contains ".test." or ".spec.", so test-support
files in common locations like "tests/setup.ts" or "__mocks__/*" will still be included in the AI
fileTree and keep consuming context tokens. This can reduce the effectiveness of the PR’s goal for
projects that organize tests by directory rather than filename suffix.
Code

modules/playground/hooks/useAI.ts[R154-156]

+            const fileName = `${item.filename}${ext}`;
+            if (fileName.includes(".test.") || fileName.includes(".spec.")) continue;
+            paths.push(prefix ? `${prefix}/${fileName}` : fileName);
Relevance

●● Moderate

No prior reviews found about directory-based test filtering (__mocks__/tests/) for AI fileTree
context.

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The AI chat panel builds fileTree directly from collectFilePaths(templateData.items) and sends
it to the chat API; the new filter is filename-only. The repository also contains a test-support
file (tests/setup.ts) that demonstrates a common test-related path that would not match the new
“.test.”/“.spec.” substring rule if present in template data.

modules/playground/hooks/useAI.ts[145-158]
modules/playground/components/ai-chat-panel.tsx[83-134]
tests/setup.ts[1-1]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`collectFilePaths()` currently filters only by `fileName.includes(".test.")` / `fileName.includes(".spec.")`, which won’t exclude test-support files that don’t use those suffixes (e.g., `tests/setup.ts`, files under `__mocks__/`). Since `AIChatPanel` sends `collectFilePaths(...).join("\n")` as `fileTree` system context, these files will still be sent and waste tokens.

### Issue Context
The PR intends to exclude test files from the AI context window, but the current rule set is filename-only and does not consider common test directory conventions.

### Fix Focus Areas
- modules/playground/hooks/useAI.ts[145-157]
- modules/playground/components/ai-chat-panel.tsx[83-134]

### Implementation notes
- Compute `fullPath = prefix ? `${prefix}/${fileName}` : fileName` first, and filter using a single predicate against `fullPath.toLowerCase()`.
- Extend the predicate to exclude common test directory segments (e.g., `"/tests/"`, `"/__tests__/"`, `"/__mocks__/"`) and optionally handle suffixes like `.test` / `.spec` when there is no further extension.
- Keep the final returned format unchanged (folder entries still end with `/`).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Informational

2. Misleading helper contract 🐞 Bug ⚙ Maintainability
Description
The JSDoc for collectFilePaths() states it collects “all file paths,” but the implementation now
intentionally omits some files, which can cause future callers to silently miss paths. This is
especially risky because the helper is exported and used as a general-purpose utility.
Code

modules/playground/hooks/useAI.ts[155]

+            if (fileName.includes(".test.") || fileName.includes(".spec.")) continue;
Relevance

●●● Strong

Team has accepted adding/maintaining accurate JSDoc on helpers (e.g., normalizeJson comment changes
accepted).

PR-#256
PR-#222

ⓘ Recommendations generated based on similar findings in past PRs

Evidence
The documentation claims the helper collects all file paths, but the implementation now has an
early-continue that skips certain filenames, contradicting that contract.

modules/playground/hooks/useAI.ts[137-157]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

### Issue description
`collectFilePaths()` is documented as collecting all file paths, but it now filters out some entries. This makes the function contract misleading and can cause subtle bugs if the helper is reused elsewhere expecting a complete enumeration.

### Issue Context
Filtering was added for AI context optimization, but the function name/JSDoc still describes unfiltered behavior.

### Fix Focus Areas
- modules/playground/hooks/useAI.ts[137-157]

### Implementation notes
Choose one:
- Update the JSDoc to explicitly document the exclusions (e.g., excludes files matching `.test.`/`.spec.` and any other patterns you add).
- Or, split responsibilities: keep `collectFilePaths()` as a true “collect all paths” helper and apply filtering at the call site (e.g., in `ai-chat-panel.tsx`) or via a new wrapper like `collectFilePathsForAIContext()`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

To customize comments, go to the Qodo configuration screen, or learn more in the docs.

Qodo Logo

Comment on lines +154 to +156
const fileName = `${item.filename}${ext}`;
if (fileName.includes(".test.") || fileName.includes(".spec.")) continue;
paths.push(prefix ? `${prefix}/${fileName}` : fileName);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Remediation recommended

1. Incomplete test filtering 🐞 Bug ≡ Correctness

collectFilePaths() only skips files whose basename contains ".test." or ".spec.", so test-support
files in common locations like "tests/setup.ts" or "__mocks__/*" will still be included in the AI
fileTree and keep consuming context tokens. This can reduce the effectiveness of the PR’s goal for
projects that organize tests by directory rather than filename suffix.
Agent Prompt
### Issue description
`collectFilePaths()` currently filters only by `fileName.includes(".test.")` / `fileName.includes(".spec.")`, which won’t exclude test-support files that don’t use those suffixes (e.g., `tests/setup.ts`, files under `__mocks__/`). Since `AIChatPanel` sends `collectFilePaths(...).join("\n")` as `fileTree` system context, these files will still be sent and waste tokens.

### Issue Context
The PR intends to exclude test files from the AI context window, but the current rule set is filename-only and does not consider common test directory conventions.

### Fix Focus Areas
- modules/playground/hooks/useAI.ts[145-157]
- modules/playground/components/ai-chat-panel.tsx[83-134]

### Implementation notes
- Compute `fullPath = prefix ? `${prefix}/${fileName}` : fileName` first, and filter using a single predicate against `fullPath.toLowerCase()`.
- Extend the predicate to exclude common test directory segments (e.g., `"/tests/"`, `"/__tests__/"`, `"/__mocks__/"`) and optionally handle suffixes like `.test` / `.spec` when there is no further extension.
- Keep the final returned format unchanged (folder entries still end with `/`).

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

const ext = item.fileExtension ? `.${item.fileExtension}` : "";
paths.push(prefix ? `${prefix}/${item.filename}${ext}` : `${item.filename}${ext}`);
const fileName = `${item.filename}${ext}`;
if (fileName.includes(".test.") || fileName.includes(".spec.")) continue;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Informational

2. Misleading helper contract 🐞 Bug ⚙ Maintainability

The JSDoc for collectFilePaths() states it collects “all file paths,” but the implementation now
intentionally omits some files, which can cause future callers to silently miss paths. This is
especially risky because the helper is exported and used as a general-purpose utility.
Agent Prompt
### Issue description
`collectFilePaths()` is documented as collecting all file paths, but it now filters out some entries. This makes the function contract misleading and can cause subtle bugs if the helper is reused elsewhere expecting a complete enumeration.

### Issue Context
Filtering was added for AI context optimization, but the function name/JSDoc still describes unfiltered behavior.

### Fix Focus Areas
- modules/playground/hooks/useAI.ts[137-157]

### Implementation notes
Choose one:
- Update the JSDoc to explicitly document the exclusions (e.g., excludes files matching `.test.`/`.spec.` and any other patterns you add).
- Or, split responsibilities: keep `collectFilePaths()` as a true “collect all paths” helper and apply filtering at the call site (e.g., in `ai-chat-panel.tsx`) or via a new wrapper like `collectFilePathsForAIContext()`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools

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

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Performance] Use server-side filtering for template catalog instead of client-side

2 participants