Skip to content

Remove console logs and simplify AI chat prompt#1769

Merged
MrgSub merged 1 commit intostagingfrom
Remove_console_logs_and_simplify_AI_chat_prompt
Jul 20, 2025
Merged

Remove console logs and simplify AI chat prompt#1769
MrgSub merged 1 commit intostagingfrom
Remove_console_logs_and_simplify_AI_chat_prompt

Conversation

@MrgSub
Copy link
Collaborator

@MrgSub MrgSub commented Jul 20, 2025

Cleanup: Remove console logs and refactor AI chat prompt

Description

This PR removes unnecessary console logs from the codebase and refactors the AI chat prompt to be more concise and structured. The changes include:

  1. Removing debug console.log statements from notification settings and hot key handling
  2. Adding error handling to the AI sidebar component
  3. Streamlining the AI chat prompt structure for better readability and maintenance
  4. Improving the inboxRag function with better error handling and logging

Type of Change

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ⚡ Performance improvement

Areas Affected

  • User Interface/Experience
  • API Endpoints

Testing Done

  • Manual testing performed

Checklist

  • I have performed a self-review of my code
  • My changes generate no new warnings
  • All tests pass locally

Additional Notes

The AI chat prompt refactoring significantly improves readability while maintaining the same functionality. The removal of console logs helps keep the browser console clean in production.


By submitting this pull request, I confirm that my contribution is made under the terms of the project's license.

Summary by CodeRabbit

  • New Features

    • Enhanced email search with improved AI-generated query refinement for more accurate results.
  • Bug Fixes

    • Improved error handling and fallback messaging during AI-powered searches to prevent disruptions.
  • Refactor

    • Streamlined and restructured the AI assistant’s internal prompt for clearer, more direct responses and safer actions.
    • Refined tool orchestration for chat streaming to improve reliability.
  • Chores

    • Removed unused tools and related features to simplify the system.
    • Eliminated unnecessary console logging for cleaner operation.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 20, 2025

Walkthrough

This update removes the AI-powered Gmail search query builder tool and its registrations, rewrites the AI assistant system prompt to a concise XML-like format, adds error handling and logging to agent logic, and eliminates debugging console logs from several frontend and hook files. Minor import order changes and explicit output options are also introduced.

Changes

File(s) Change Summary
apps/mail/app/(routes)/settings/notifications/page.tsx Removed a console.log from form submission; reordered imports.
apps/mail/components/ui/ai-sidebar.tsx Added onError callback to useAgent hook for error logging.
apps/mail/hooks/use-hot-key.ts Removed all console.log debugging statements from event handlers.
apps/server/src/lib/prompts.ts Completely rewrote and restructured the AiChatPrompt system prompt to a concise XML-like format.
apps/server/src/routes/agent/index.ts Enhanced error handling/logging in inboxRag; added AI-powered query refinement in searchThreads; adjusted tool orchestration in ZeroAgent.
apps/server/src/routes/agent/mcp.ts Removed buildGmailSearchQuery tool registration and related imports.
apps/server/src/routes/agent/tools.ts Deleted buildGmailSearchQuery tool and its export; removed related imports and commented-out code.
apps/server/src/trpc/routes/ai/search.ts Moved env import earlier; added output: 'object' to generateObject call.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ZeroDriver
    participant OpenAI
    participant Orchestrator

    User->>ZeroDriver: searchThreads(query)
    ZeroDriver->>OpenAI: generateText (refine query)
    OpenAI-->>ZeroDriver: refined query
    par
        ZeroDriver->>ZeroDriver: inboxRag(refined query)
        ZeroDriver->>ZeroDriver: listThreads(refined query)
    end
    ZeroDriver-->>User: thread IDs (from RAG or fallback to list)

    User->>ZeroAgent: start chat session
    ZeroAgent->>Orchestrator: processTools(rawTools)
    Orchestrator-->>ZeroAgent: tools
    ZeroAgent->>OpenAI: streamText (with tools)
    OpenAI-->>ZeroAgent: AI response
    ZeroAgent-->>User: streamed response
Loading

Possibly related PRs

  • mcp-prep #1740: Removes the buildGmailSearchQuery tool and related registrations, directly connected to this PR’s removal of that tool.
  • Ai generate security #706: Introduces XML-like formatted prompts for AI email generation, closely related to this PR’s major rewrite of the AI assistant prompt in a similar format.
  • refactor durable objects #1764: Refactors ZeroAgent and ZeroDriver, directly relating to this PR’s enhancements and modifications in those classes.

Poem

A rabbit hops through lines of code,
Console logs and cluttered tools offload.
Prompts now crisp, in XML they sing,
Agents log errors, AI queries take wing.
With each refactor, the garden grows neat—
Inbox in order, changes complete!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Collaborator Author

MrgSub commented Jul 20, 2025

This stack of pull requests is managed by Graphite. Learn more about stacking.

@MrgSub MrgSub marked this pull request as ready for review July 20, 2025 20:00
Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

Copy link
Collaborator Author

MrgSub commented Jul 20, 2025

Merge activity

  • Jul 20, 8:01 PM UTC: A user started a stack merge that includes this pull request via Graphite.
  • Jul 20, 8:01 PM UTC: @MrgSub merged this pull request with Graphite.

@MrgSub MrgSub merged commit 364e90b into staging Jul 20, 2025
7 of 9 checks passed
@MrgSub MrgSub deleted the Remove_console_logs_and_simplify_AI_chat_prompt branch July 20, 2025 20:01
Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

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

Bug: Debug Logs Added Despite Removal Goal

Debug console.log, console.warn, and console.error statements were added, notably within the useAgent configuration's onError handler and the inboxRag function. This contradicts the PR's stated goal of removing debug logs and maintaining a clean browser console in production.

apps/mail/components/ui/ai-sidebar.tsx#L351-L352

host: `${import.meta.env.VITE_PUBLIC_BACKEND_URL}`,
onError: (e) => console.log(e),

apps/server/src/routes/agent/index.ts#L498-L510

if (!env.AUTORAG_ID) {
console.warn('[inboxRag] AUTORAG_ID not configured - RAG search disabled');
return { result: 'Not enabled', data: [] };
}
try {
const startTime = Date.now();
console.log(`[inboxRag] Executing AI search with parameters:`, {
query,
max_num_results: 3,
score_threshold: 0.3,
folder_filter: `${this.name}/`,
});

Fix in CursorFix in Web


BugBot free trial expires on July 31, 2025
Learn more in the Cursor dashboard.

Was this report helpful? Give feedback by reacting with 👍 or 👎

agent: 'ZeroAgent',
name: activeConnection?.id ? String(activeConnection.id) : 'general',
host: `${import.meta.env.VITE_PUBLIC_BACKEND_URL}`,
onError: (e) => console.log(e),
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider replacing console.log(e) with a more structured error handling approach. Directly logging error objects can expose sensitive information in production environments. A better pattern would be to log specific error properties or use a dedicated error logging service that properly sanitizes sensitive data:

onError: (e) => {
  console.error('AI agent error:', e.message || 'Unknown error');
  // Or use a structured logging approach
  // errorLoggingService.captureError(e);
}

This maintains the error tracking functionality while reducing security risks from exposing raw error objects.

Suggested change
onError: (e) => console.log(e),
onError: (e) => {
console.error('AI agent error:', e.message || 'Unknown error');
// Or use a structured logging approach
// errorLoggingService.captureError(e);
},

Spotted by Diamond (based on custom rules)

Is this helpful? React 👍 or 👎 to let us know.

max_num_results: 3,
ranking_options: {
if (!env.AUTORAG_ID) {
console.warn('[inboxRag] AUTORAG_ID not configured - RAG search disabled');
Copy link
Contributor

Choose a reason for hiding this comment

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

Consider replacing the console.warn() with a more generic log message that doesn't expose configuration details. While this warning helps with debugging, it reveals internal system configuration status (AUTORAG_ID) which could potentially provide information useful in an attack. A better approach would be to log that "Search functionality is unavailable" without specifying which configuration parameter is missing, or implement proper application monitoring for configuration issues.

Suggested change
console.warn('[inboxRag] AUTORAG_ID not configured - RAG search disabled');
console.warn('[inboxRag] Search functionality unavailable - missing configuration');

Spotted by Diamond (based on custom rules)

Is this helpful? React 👍 or 👎 to let us know.

Comment on lines +531 to +536
console.error(`[inboxRag] Search failed for query: "${query}"`, {
error: error instanceof Error ? error.message : 'Unknown error',
stack: error instanceof Error ? error.stack : undefined,
user: this.name,
});

Copy link
Contributor

Choose a reason for hiding this comment

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

Consider sanitizing the error logging to avoid exposing sensitive information. The current implementation logs raw user queries and detailed error information including stack traces, which could potentially expose sensitive data or internal application structure.

A more secure approach would be to:

  1. Sanitize or redact the query parameter before logging
  2. Limit stack trace information in production environments
  3. Use a structured logging format that allows for easier filtering of sensitive fields

For example:

console.error(`[inboxRag] Search failed`, {
  queryLength: query.length,
  errorType: error instanceof Error ? error.constructor.name : 'Unknown',
  errorMessage: error instanceof Error ? error.message : 'Unknown error',
  user: this.name,
});
Suggested change
console.error(`[inboxRag] Search failed for query: "${query}"`, {
error: error instanceof Error ? error.message : 'Unknown error',
stack: error instanceof Error ? error.stack : undefined,
user: this.name,
});
console.error(`[inboxRag] Search failed`, {
queryLength: query.length,
errorType: error instanceof Error ? error.constructor.name : 'Unknown',
errorMessage: error instanceof Error ? error.message : 'Unknown error',
user: this.name,
});

Spotted by Diamond (based on custom rules)

Is this helpful? React 👍 or 👎 to let us know.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

cubic analysis

2 issues found across 8 files • Review in cubic

React with 👍 or 👎 to teach cubic. You can also tag @cubic-dev-ai to give feedback, ask questions, or re-run the review.

agent: 'ZeroAgent',
name: activeConnection?.id ? String(activeConnection.id) : 'general',
host: `${import.meta.env.VITE_PUBLIC_BACKEND_URL}`,
onError: (e) => console.log(e),
Copy link
Contributor

Choose a reason for hiding this comment

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

Using console.log for error handling here is inconsistent with the PR's stated goal of removing console logs and is not suitable for production error handling.

Prompt for AI agents
Address the following comment on apps/mail/components/ui/ai-sidebar.tsx at line 352:

<comment>Using console.log for error handling here is inconsistent with the PR&#39;s stated goal of removing console logs and is not suitable for production error handling.</comment>

<file context>
@@ -349,6 +349,7 @@ function AISidebar({ className }: AISidebarProps) {
     agent: &#39;ZeroAgent&#39;,
     name: activeConnection?.id ? String(activeConnection.id) : &#39;general&#39;,
     host: `${import.meta.env.VITE_PUBLIC_BACKEND_URL}`,
+    onError: (e) =&gt; console.log(e),
   });
 
   const chatState = useAgentChat({
</file context>

agent: 'ZeroAgent',
name: activeConnection?.id ? String(activeConnection.id) : 'general',
host: `${import.meta.env.VITE_PUBLIC_BACKEND_URL}`,
onError: (e) => console.log(e),
Copy link
Contributor

Choose a reason for hiding this comment

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

Rule violated: Detect React performance bottlenecks and rule breaking

  Defining an anonymous function inline for the onError prop breaks the rule against inline function expressions in React props, which can cause unnecessary re-renders and performance issues. Move the function definition outside and pass a reference, or memoize it with useCallback.
Prompt for AI agents
Address the following comment on apps/mail/components/ui/ai-sidebar.tsx at line 352:

<comment>Defining an anonymous function inline for the onError prop breaks the rule against inline function expressions in React props, which can cause unnecessary re-renders and performance issues. Move the function definition outside and pass a reference, or memoize it with useCallback.</comment>

<file context>
@@ -349,6 +349,7 @@ function AISidebar({ className }: AISidebarProps) {
     agent: &#39;ZeroAgent&#39;,
     name: activeConnection?.id ? String(activeConnection.id) : &#39;general&#39;,
     host: `${import.meta.env.VITE_PUBLIC_BACKEND_URL}`,
+    onError: (e) =&gt; console.log(e),
   });
 
   const chatState = useAgentChat({
</file context>

Copy link
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

🔭 Outside diff range comments (1)
apps/server/src/lib/prompts.ts (1)

5-5: Remove or rename unused variable.

The CATEGORY_IDS variable is declared but never used. Either remove it or prefix with underscore if intended for future use.

-const CATEGORY_IDS = ['Important', 'All Mail', 'Personal', 'Updates', 'Promotions', 'Unread'];
+const _CATEGORY_IDS = ['Important', 'All Mail', 'Personal', 'Updates', 'Promotions', 'Unread'];

Or simply remove it if not needed:

-const CATEGORY_IDS = ['Important', 'All Mail', 'Personal', 'Updates', 'Promotions', 'Unread'];
-
🧹 Nitpick comments (3)
apps/mail/app/(routes)/settings/notifications/page.tsx (1)

41-46: Fix the unused parameter warning.

The values parameter is no longer used after removing the console.log statement. Follow the ESLint suggestion to prefix unused parameters with underscore.

-  function onSubmit(values: z.infer<typeof formSchema>) {
+  function onSubmit(_values: z.infer<typeof formSchema>) {
apps/mail/components/ui/ai-sidebar.tsx (1)

352-352: Good error handling addition, but consider structured logging.

Adding the onError callback improves error handling. However, consider using a structured logging approach instead of console.log for production environments.

-    onError: (e) => console.log(e),
+    onError: (e) => {
+      console.error('Agent error:', e);
+      // Consider integrating with your logging service
+    },
apps/server/src/routes/agent/mcp.ts (1)

26-26: Remove unused import.

The generateText import is no longer used after removing the Gmail search query tool.

-import { generateText } from 'ai';
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between bf2c8f3 and 815901b.

📒 Files selected for processing (8)
  • apps/mail/app/(routes)/settings/notifications/page.tsx (1 hunks)
  • apps/mail/components/ui/ai-sidebar.tsx (1 hunks)
  • apps/mail/hooks/use-hot-key.ts (1 hunks)
  • apps/server/src/lib/prompts.ts (1 hunks)
  • apps/server/src/routes/agent/index.ts (7 hunks)
  • apps/server/src/routes/agent/mcp.ts (1 hunks)
  • apps/server/src/routes/agent/tools.ts (1 hunks)
  • apps/server/src/trpc/routes/ai/search.ts (2 hunks)
🧰 Additional context used
🧠 Learnings (4)
apps/mail/app/(routes)/settings/notifications/page.tsx (3)
Learnt from: retrogtx
PR: Mail-0/Zero#1328
File: apps/mail/lib/hotkeys/mail-list-hotkeys.tsx:202-209
Timestamp: 2025-06-18T17:26:50.918Z
Learning: In apps/mail/lib/hotkeys/mail-list-hotkeys.tsx, the switchCategoryByIndex function using hardcoded indices for category hotkeys does not break when users reorder categories, contrary to the theoretical index-shifting issue. The actual implementation has constraints or mechanisms that prevent hotkey targeting issues.
Learnt from: retrogtx
PR: Mail-0/Zero#1468
File: apps/server/src/trpc/routes/mail.ts:331-331
Timestamp: 2025-06-28T03:56:09.376Z
Learning: In apps/server/src/trpc/routes/mail.ts, the user indicated they are not using ISO format for the scheduleAt parameter, despite the frontend code showing toISOString() usage in the ScheduleSendPicker component.
Learnt from: retrogtx
PR: Mail-0/Zero#1354
File: apps/mail/components/ui/prompts-dialog.tsx:85-88
Timestamp: 2025-06-20T05:03:16.944Z
Learning: In React Hook Form, avoid using useEffect for form state synchronization when the values prop can handle reactive updates automatically. The values prop is specifically designed for this purpose and is more optimal than manual useEffect-based synchronization.
apps/mail/hooks/use-hot-key.ts (1)
Learnt from: retrogtx
PR: Mail-0/Zero#1328
File: apps/mail/lib/hotkeys/mail-list-hotkeys.tsx:202-209
Timestamp: 2025-06-18T17:26:50.918Z
Learning: In apps/mail/lib/hotkeys/mail-list-hotkeys.tsx, the switchCategoryByIndex function using hardcoded indices for category hotkeys does not break when users reorder categories, contrary to the theoretical index-shifting issue. The actual implementation has constraints or mechanisms that prevent hotkey targeting issues.
apps/server/src/lib/prompts.ts (1)
Learnt from: retrogtx
PR: Mail-0/Zero#1354
File: apps/mail/components/ui/prompts-dialog.tsx:148-159
Timestamp: 2025-06-20T05:34:41.297Z
Learning: In the prompt management system, users should be allowed to save empty prompts as this gives them the choice to disable certain AI functionality or start fresh. Validation should not prevent empty prompts from being saved.
apps/server/src/routes/agent/index.ts (1)
Learnt from: retrogtx
PR: Mail-0/Zero#1734
File: apps/server/src/lib/driver/google.ts:211-221
Timestamp: 2025-07-15T06:46:33.349Z
Learning: In apps/server/src/lib/driver/google.ts, the normalization of "draft" to "drafts" in the count() method is necessary because the navigation item in apps/mail/config/navigation.ts has id: 'drafts' (plural) while the Google API returns "draft" (singular). The nav-main.tsx component matches stats by comparing stat.label with item.id, so the backend must return "drafts" for the draft counter badge to appear in the sidebar.
🧬 Code Graph Analysis (1)
apps/server/src/lib/prompts.ts (1)
apps/mail/lib/prompts.ts (1)
  • getCurrentDateContext (112-112)
🪛 GitHub Actions: autofix.ci
apps/mail/app/(routes)/settings/notifications/page.tsx

[warning] 41-41: ESLint(no-unused-vars): Parameter 'values' is declared but never used. Unused parameters should start with a '_'.

apps/server/src/routes/agent/mcp.ts

[warning] 26-26: ESLint(no-unused-vars): Identifier 'generateText' is imported but never used.

apps/server/src/lib/prompts.ts

[warning] 5-5: ESLint(no-unused-vars): Variable 'CATEGORY_IDS' is declared but never used. Unused variables should start with a '_'.

apps/server/src/routes/agent/index.ts

[warning] 527-527: ESLint(no-unused-vars): Variable 'duration' is declared but never used. Unused variables should start with a '_'.

⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Cursor BugBot
🔇 Additional comments (11)
apps/mail/app/(routes)/settings/notifications/page.tsx (1)

19-19: LGTM!

The import reordering is a minor cleanup and doesn't affect functionality.

apps/server/src/trpc/routes/ai/search.ts (2)

6-6: LGTM!

Import reordering improves code organization without functional impact.


31-31: Good practice to make output format explicit.

Adding the output: 'object' option makes the expected return format clear and improves API robustness.

apps/mail/hooks/use-hot-key.ts (1)

12-12: Excellent cleanup of debug logging.

Removing the console.log statements from key event handlers eliminates debugging noise while preserving all functionality. This aligns perfectly with the PR objective of cleaning up console logs.

Also applies to: 19-19, 30-30, 37-37

apps/server/src/routes/agent/mcp.ts (1)

18-18: LGTM on import cleanup.

Removing unused imports related to the deleted Gmail search query tool is good cleanup.

apps/server/src/routes/agent/tools.ts (1)

6-6: LGTM!

The import cleanup is appropriate after removing the Gmail search query builder tool and its dependencies.

apps/server/src/lib/prompts.ts (1)

329-506: Excellent prompt restructuring!

The rewrite from narrative to structured XML format significantly improves:

  • Clarity with explicit sections for role, criteria, and guidelines
  • Safety with confirmation rules for bulk operations
  • Maintainability with well-organized tool definitions
  • User experience with concise, action-oriented responses

The emphasis on plain text output and internal reasoning is particularly well done.

apps/server/src/routes/agent/index.ts (4)

498-502: Good defensive programming!

The environment variable check with early return and warning is a robust pattern that prevents runtime errors when RAG is not configured.


530-539: Excellent error handling implementation!

The comprehensive error handling with detailed logging and graceful fallback ensures the application remains stable even when the AI search fails. The structured error object with stack trace aids debugging while the empty result prevents breaking the flow.


563-571: Smart query refinement approach!

Using AI to refine natural language queries into proper Gmail search syntax before executing the search is a clever enhancement. The error handling with fallback to the original query ensures robustness.


888-903: Clean tool orchestration integration!

The separation of raw tools and processed tools through the orchestrator provides better control over tool availability and processing. This architectural improvement enhances maintainability.

Comment on lines 497 to 540
async inboxRag(query: string) {
if (!env.AUTORAG_ID) return { result: 'Not enabled', data: [] };
const answer = await env.AI.autorag(env.AUTORAG_ID).aiSearch({
query: query,
// rewrite_query: true,
max_num_results: 3,
ranking_options: {
if (!env.AUTORAG_ID) {
console.warn('[inboxRag] AUTORAG_ID not configured - RAG search disabled');
return { result: 'Not enabled', data: [] };
}

try {
const startTime = Date.now();
console.log(`[inboxRag] Executing AI search with parameters:`, {
query,
max_num_results: 3,
score_threshold: 0.3,
},
// stream: true,
filters: {
type: 'eq',
key: 'folder',
value: `${this.name}/`,
},
});
return { result: answer.response, data: answer.data };
folder_filter: `${this.name}/`,
});

const answer = await env.AI.autorag(env.AUTORAG_ID).aiSearch({
query: query,
// rewrite_query: true,
max_num_results: 3,
ranking_options: {
score_threshold: 0.3,
},
// stream: true,
filters: {
type: 'eq',
key: 'folder',
value: `${this.name}/`,
},
});

const duration = Date.now() - startTime;

return { result: answer.response, data: answer.data };
} catch (error) {
console.error(`[inboxRag] Search failed for query: "${query}"`, {
error: error instanceof Error ? error.message : 'Unknown error',
stack: error instanceof Error ? error.stack : undefined,
user: this.name,
});

// Return empty result on error to prevent breaking the flow
return { result: 'Search failed', data: [] };
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Remove unused duration variable.

The duration variable is calculated but never used. Either remove it or use it for logging/metrics.

-      const duration = Date.now() - startTime;
-
-      return { result: answer.response, data: answer.data };
+      const duration = Date.now() - startTime;
+      console.log(`[inboxRag] Search completed in ${duration}ms`);
+
+      return { result: answer.response, data: answer.data };

Or remove if not needed:

-      const startTime = Date.now();
       console.log(`[inboxRag] Executing AI search with parameters:`, {
         query,
         max_num_results: 3,
         score_threshold: 0.3,
         folder_filter: `${this.name}/`,
       });

       const answer = await env.AI.autorag(env.AUTORAG_ID).aiSearch({
         query: query,
         //   rewrite_query: true,
         max_num_results: 3,
         ranking_options: {
           score_threshold: 0.3,
         },
         //   stream: true,
         filters: {
           type: 'eq',
           key: 'folder',
           value: `${this.name}/`,
         },
       });

-      const duration = Date.now() - startTime;
-
       return { result: answer.response, data: answer.data };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async inboxRag(query: string) {
if (!env.AUTORAG_ID) return { result: 'Not enabled', data: [] };
const answer = await env.AI.autorag(env.AUTORAG_ID).aiSearch({
query: query,
// rewrite_query: true,
max_num_results: 3,
ranking_options: {
if (!env.AUTORAG_ID) {
console.warn('[inboxRag] AUTORAG_ID not configured - RAG search disabled');
return { result: 'Not enabled', data: [] };
}
try {
const startTime = Date.now();
console.log(`[inboxRag] Executing AI search with parameters:`, {
query,
max_num_results: 3,
score_threshold: 0.3,
},
// stream: true,
filters: {
type: 'eq',
key: 'folder',
value: `${this.name}/`,
},
});
return { result: answer.response, data: answer.data };
folder_filter: `${this.name}/`,
});
const answer = await env.AI.autorag(env.AUTORAG_ID).aiSearch({
query: query,
// rewrite_query: true,
max_num_results: 3,
ranking_options: {
score_threshold: 0.3,
},
// stream: true,
filters: {
type: 'eq',
key: 'folder',
value: `${this.name}/`,
},
});
const duration = Date.now() - startTime;
return { result: answer.response, data: answer.data };
} catch (error) {
console.error(`[inboxRag] Search failed for query: "${query}"`, {
error: error instanceof Error ? error.message : 'Unknown error',
stack: error instanceof Error ? error.stack : undefined,
user: this.name,
});
// Return empty result on error to prevent breaking the flow
return { result: 'Search failed', data: [] };
}
}
async inboxRag(query: string) {
if (!env.AUTORAG_ID) {
console.warn('[inboxRag] AUTORAG_ID not configured - RAG search disabled');
return { result: 'Not enabled', data: [] };
}
try {
const startTime = Date.now();
console.log(`[inboxRag] Executing AI search with parameters:`, {
query,
max_num_results: 3,
score_threshold: 0.3,
folder_filter: `${this.name}/`,
});
const answer = await env.AI.autorag(env.AUTORAG_ID).aiSearch({
query: query,
// rewrite_query: true,
max_num_results: 3,
ranking_options: {
score_threshold: 0.3,
},
// stream: true,
filters: {
type: 'eq',
key: 'folder',
value: `${this.name}/`,
},
});
const duration = Date.now() - startTime;
console.log(`[inboxRag] Search completed in ${duration}ms`);
return { result: answer.response, data: answer.data };
} catch (error) {
console.error(`[inboxRag] Search failed for query: "${query}"`, {
error: error instanceof Error ? error.message : 'Unknown error',
stack: error instanceof Error ? error.stack : undefined,
user: this.name,
});
return { result: 'Search failed', data: [] };
}
}
Suggested change
async inboxRag(query: string) {
if (!env.AUTORAG_ID) return { result: 'Not enabled', data: [] };
const answer = await env.AI.autorag(env.AUTORAG_ID).aiSearch({
query: query,
// rewrite_query: true,
max_num_results: 3,
ranking_options: {
if (!env.AUTORAG_ID) {
console.warn('[inboxRag] AUTORAG_ID not configured - RAG search disabled');
return { result: 'Not enabled', data: [] };
}
try {
const startTime = Date.now();
console.log(`[inboxRag] Executing AI search with parameters:`, {
query,
max_num_results: 3,
score_threshold: 0.3,
},
// stream: true,
filters: {
type: 'eq',
key: 'folder',
value: `${this.name}/`,
},
});
return { result: answer.response, data: answer.data };
folder_filter: `${this.name}/`,
});
const answer = await env.AI.autorag(env.AUTORAG_ID).aiSearch({
query: query,
// rewrite_query: true,
max_num_results: 3,
ranking_options: {
score_threshold: 0.3,
},
// stream: true,
filters: {
type: 'eq',
key: 'folder',
value: `${this.name}/`,
},
});
const duration = Date.now() - startTime;
return { result: answer.response, data: answer.data };
} catch (error) {
console.error(`[inboxRag] Search failed for query: "${query}"`, {
error: error instanceof Error ? error.message : 'Unknown error',
stack: error instanceof Error ? error.stack : undefined,
user: this.name,
});
// Return empty result on error to prevent breaking the flow
return { result: 'Search failed', data: [] };
}
}
async inboxRag(query: string) {
if (!env.AUTORAG_ID) {
console.warn('[inboxRag] AUTORAG_ID not configured - RAG search disabled');
return { result: 'Not enabled', data: [] };
}
try {
console.log(`[inboxRag] Executing AI search with parameters:`, {
query,
max_num_results: 3,
score_threshold: 0.3,
folder_filter: `${this.name}/`,
});
const answer = await env.AI.autorag(env.AUTORAG_ID).aiSearch({
query: query,
// rewrite_query: true,
max_num_results: 3,
ranking_options: {
score_threshold: 0.3,
},
// stream: true,
filters: {
type: 'eq',
key: 'folder',
value: `${this.name}/`,
},
});
return { result: answer.response, data: answer.data };
} catch (error) {
console.error(`[inboxRag] Search failed for query: "${query}"`, {
error: error instanceof Error ? error.message : 'Unknown error',
stack: error instanceof Error ? error.stack : undefined,
user: this.name,
});
return { result: 'Search failed', data: [] };
}
}
🧰 Tools
🪛 GitHub Actions: autofix.ci

[warning] 527-527: ESLint(no-unused-vars): Variable 'duration' is declared but never used. Unused variables should start with a '_'.

🤖 Prompt for AI Agents
In apps/server/src/routes/agent/index.ts around lines 497 to 540, the variable
'duration' is calculated but never used. Remove the declaration and assignment
of 'duration' since it serves no purpose, or alternatively, add a log statement
to output the duration for performance monitoring if desired.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant