Skip to content

Comments

Streamline email assistant prompt and add server-side tool execution#1887

Merged
MrgSub merged 1 commit intostagingfrom
ZEROStreamline_email_assistant_prompt_and_add_server-side_tool_execution
Aug 1, 2025
Merged

Streamline email assistant prompt and add server-side tool execution#1887
MrgSub merged 1 commit intostagingfrom
ZEROStreamline_email_assistant_prompt_and_add_server-side_tool_execution

Conversation

@MrgSub
Copy link
Collaborator

@MrgSub MrgSub commented Aug 1, 2025

READ CAREFULLY THEN REMOVE

Remove bullet points that are not relevant.

PLEASE REFRAIN FROM USING AI TO WRITE YOUR CODE AND PR DESCRIPTION. IF YOU DO USE AI TO WRITE YOUR CODE PLEASE PROVIDE A DESCRIPTION AND REVIEW IT CAREFULLY. MAKE SURE YOU UNDERSTAND THE CODE YOU ARE SUBMITTING USING AI.

  • Pull requests that do not follow these guidelines will be closed without review or comment.
  • If you use AI to write your PR description your pr will be close without review or comment.
  • If you are unsure about anything, feel free to ask for clarification.

Description

Please provide a clear description of your changes.


Type of Change

Please delete options that are not relevant.

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature with breaking changes)
  • 📝 Documentation update
  • 🎨 UI/UX improvement
  • 🔒 Security enhancement
  • ⚡ Performance improvement

Areas Affected

Please check all that apply:

  • Email Integration (Gmail, IMAP, etc.)
  • User Interface/Experience
  • Authentication/Authorization
  • Data Storage/Management
  • API Endpoints
  • Documentation
  • Testing Infrastructure
  • Development Workflow
  • Deployment/Infrastructure

Testing Done

Describe the tests you've done:

  • Unit tests added/updated
  • Integration tests added/updated
  • Manual testing performed
  • Cross-browser testing (if UI changes)
  • Mobile responsiveness verified (if UI changes)

Security Considerations

For changes involving data or authentication:

  • No sensitive data is exposed
  • Authentication checks are in place
  • Input validation is implemented
  • Rate limiting is considered (if applicable)

Checklist

  • I have read the CONTRIBUTING document
  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in complex areas
  • I have updated the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix/feature works
  • All tests pass locally
  • Any dependent changes are merged and published

Additional Notes

Add any other context about the pull request here.

Screenshots/Recordings

Add screenshots or recordings here if applicable.


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


Summary by cubic

Simplified the email assistant system prompt for clarity and added server-side tool execution for voice and web integrations.

  • Refactors

    • Rewrote the assistant prompt to be shorter, more direct, and easier for models to follow.
    • Removed unused and verbose prompt sections.
  • New Features

    • Added a server-side tool execution endpoint and utility for handling tool calls from the client.
    • Introduced a script to register all tools with ElevenLabs for voice agent integration.

Summary by CodeRabbit

  • New Features

    • Added new tools for building Gmail search queries and retrieving the current date.
    • Introduced a script to automate bulk registration and updating of AI tools with ElevenLabs.
    • Added a new dependency for analytics in the mail app.
  • Improvements

    • Majorly restructured and simplified the AI assistant's system prompt for improved clarity and safety.
    • Unified and streamlined server-side tool management, enabling dynamic tool loading and execution.
    • Enhanced CORS support for AI tool endpoints.
  • Bug Fixes

    • Removed an obsolete server-sent events route and related authentication logic.
  • Chores

    • Updated and cleaned up dependencies across multiple packages.
    • Added new enum members for tools to support expanded functionality.

@jazzberry-ai
Copy link

jazzberry-ai bot commented Aug 1, 2025

Bug Report

Name Severity Example test case Description
Authentication Bypass Critical Set X-Voice-Secret header in a request to /api/ai/do/* with a valid secret to execute tools. Set X-Caller header to system__caller_id to bypass authentication. The X-Voice-Secret is exposed on the client-side, enabling unauthorized tool execution. The X-Caller can be spoofed with the value system__caller_id to bypass authentication entirely.
Missing Voice Tool Mapping High Try using a voice command that relies on tool execution. The voice assistant tool mapping is disabled, negating its functionality.
Lack of Input Validation High Send a request to /api/ai/do/* with a malicious action or payload parameter. The callServerTool function and apps/server/src/routes/ai.ts don't perform sufficient input validation, leading to potential injection vulnerabilities.
API Key Security Medium Compromise the ELEVENLABS_API_KEY and use it to register malicious tools or delete existing ones. The scripts/register-elevenlabs-tools.ts script doesn't protect the ELEVENLABS_API_KEY, which could be compromised.
Lack of Context Persistence Low Have a multi-turn conversation with the AI and observe if it "forgets" previous instructions or search results. The prompt in apps/mail/lib/prompts.ts doesn't address context persistence, which could lead to inconsistent AI behavior.
Limited Error Handling Low Execute a tool that fails and observe the error message returned to the client. The code doesn't handle tool execution errors gracefully, potentially exposing sensitive information.

Comments? Email us.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 1, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This update introduces a major refactor of the AI chat assistant's system prompt, focusing on clarity, safety, and streamlined tool usage. It adds new server tools, updates tool management to be dynamic, adjusts dependencies, removes the /vsse SSE route, and provides a script for bulk registering tools with ElevenLabs. Enum values and tool definitions are updated accordingly.

Changes

Cohort / File(s) Change Summary
AI Chat Prompt Refactor
apps/mail/lib/prompts.ts
Major rewrite and condensation of the AI chat system prompt, shifting focus from Inbox Zero to inbox understanding and control, simplifying tool descriptions, and updating safety and workflow guidance. Function signature changed to remove threadId parameter.
Server Tooling & Dynamic Tool Loading
apps/mail/lib/server-tool.ts, apps/server/src/routes/ai.ts, apps/server/src/routes/agent/tools.ts
Introduces a generic server tool caller, replaces hardcoded tool logic with dynamic tool loading, adds new tools (buildGmailSearchQuery, getCurrentDate), and updates toolset management in AI routes. Adds CORS support for /do/* routes.
Tool Type & Enum Updates
apps/mail/types/tools.ts, apps/server/src/types.ts
Adds new enum members for GetThreadSummary and GetCurrentDate to tool enums in both mail and server types.
Voice Provider Tool Handling
apps/mail/providers/voice-provider.tsx
Removes old client tool executor logic, introduces (commented-out) new tool execution pattern using the server tool caller and a static tool name list.
Dependency Updates
apps/mail/package.json, apps/server/package.json, package.json
Updates dependencies: adds/removes analytics/auth packages, introduces zod and zod-to-json-schema, aligns versions.
SSE Route Removal
apps/server/src/main.ts
Removes the /vsse SSE route and its associated authentication and context logic.
ElevenLabs Tool Registration Script
scripts/register-elevenlabs-tools.ts
Adds a new script to automate bulk registration and updating of tools with ElevenLabs, including schema conversion, API calls, and agent updates.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Client (Mail App)
    participant Server
    participant ElevenLabs

    User->>Client (Mail App): Sends request (e.g., "Summarize my inbox")
    Client->>Server: POST /do/:action with payload and headers
    Server->>Server: Load tools dynamically for user connection
    Server->>Server: Select tool by action, execute tool
    Server-->>Client (Mail App): Return tool result or error

    %% Tool registration flow
    Client (Script)->>ElevenLabs: Fetch existing tools
    Client (Script)->>ElevenLabs: Delete old tools, update agents
    Client (Script)->>ElevenLabs: Register new tools with schemas
    Client (Script)->>ElevenLabs: Update agent with new tool IDs
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Suggested labels

design, content

Poem

🚀
In the inbox jungle, Fred takes the wheel,
With tools now dynamic, responses surreal.
Prompts trimmed for clarity, enums on the rise,
Old routes retired, new scripts surprise.
ElevenLabs ready, schemas in tow—
Progress in code, to Mars we go!


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fd6a222 and 8b031c8.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (12)
  • apps/mail/lib/prompts.ts (1 hunks)
  • apps/mail/lib/server-tool.ts (1 hunks)
  • apps/mail/package.json (1 hunks)
  • apps/mail/providers/voice-provider.tsx (4 hunks)
  • apps/mail/types/tools.ts (1 hunks)
  • apps/server/package.json (2 hunks)
  • apps/server/src/main.ts (0 hunks)
  • apps/server/src/routes/agent/tools.ts (3 hunks)
  • apps/server/src/routes/ai.ts (3 hunks)
  • apps/server/src/types.ts (1 hunks)
  • package.json (1 hunks)
  • scripts/register-elevenlabs-tools.ts (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ZEROStreamline_email_assistant_prompt_and_add_server-side_tool_execution

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 generate unit tests to generate unit tests for 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.

@MrgSub MrgSub marked this pull request as ready for review August 1, 2025 21:13
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 Aug 1, 2025

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

Copy link
Collaborator Author

MrgSub commented Aug 1, 2025

Merge activity

  • Aug 1, 9:14 PM UTC: A user started a stack merge that includes this pull request via Graphite.
  • Aug 1, 9:14 PM UTC: @MrgSub merged this pull request with Graphite.

@MrgSub MrgSub merged commit a34028c into staging Aug 1, 2025
7 of 9 checks passed
@MrgSub MrgSub deleted the ZEROStreamline_email_assistant_prompt_and_add_server-side_tool_execution branch August 1, 2025 21:14
@coderabbitai coderabbitai bot added content design Improvements & changes to design & UX labels Aug 1, 2025
@cursor
Copy link

cursor bot commented Aug 1, 2025

Bugbot found 4 bugs

To see them, activate your membership in the Cursor dashboard.

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

3 issues found across 12 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.


async function main() {
const apiKey = process.env.ELEVENLABS_API_KEY;
const serverUrl = process.env.SERVER_URL || 'https://staging.0.email';
Copy link
Contributor

Choose a reason for hiding this comment

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

A hard-coded fallback URL points to the staging environment, yet the code immediately afterwards aborts when SERVER_URL is falsy. Because the fallback makes serverUrl always truthy, this validation can never trigger and the script may silently register tools against the unintended https://staging.0.email host in production. Remove the default or the redundant check to avoid misconfiguration.

Prompt for AI agents
Address the following comment on scripts/register-elevenlabs-tools.ts at line 480:

<comment>A hard-coded fallback URL points to the staging environment, yet the code immediately afterwards aborts when SERVER_URL is falsy. Because the fallback makes serverUrl always truthy, this validation can never trigger and the script may silently register tools against the unintended https://staging.0.email host in production. Remove the default or the redundant check to avoid misconfiguration.</comment>

<file context>
@@ -0,0 +1,630 @@
+#!/usr/bin/env tsx
+
+/**
+ * Bulk-register / update all ai-sdk tools as ElevenLabs tools.
+ * This version:
+ * 1. Lists existing tools
+ * 2. Deletes them all
+ * 3. Creates new ones
+ *
</file context>
Suggested change
const serverUrl = process.env.SERVER_URL || 'https://staging.0.email';
const serverUrl = process.env.SERVER_URL;

WebSearch = 'webSearch',
InboxRag = 'inboxRag',
BuildGmailSearchQuery = 'buildGmailSearchQuery',
GetCurrentDate = 'getCurrentDate',
Copy link
Contributor

Choose a reason for hiding this comment

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

The new enum member is added only in this server-side Tools enum while the parallel enum in apps/mail/types/tools.ts remains unchanged, causing the two enums to diverge and risking type mismatches between client and server code. (Based on your team's feedback about keeping shared enums synchronized across packages)

Prompt for AI agents
Address the following comment on apps/server/src/types.ts at line 238:

<comment>The new enum member is added only in this server-side Tools enum while the parallel enum in apps/mail/types/tools.ts remains unchanged, causing the two enums to diverge and risking type mismatches between client and server code. (Based on your team&#39;s feedback about keeping shared enums synchronized across packages)</comment>

<file context>
@@ -235,6 +235,7 @@ export enum Tools {
   WebSearch = &#39;webSearch&#39;,
   InboxRag = &#39;inboxRag&#39;,
   BuildGmailSearchQuery = &#39;buildGmailSearchQuery&#39;,
+  GetCurrentDate = &#39;getCurrentDate&#39;,
 }
 
</file context>

const [lastToolCall, setLastToolCall] = useState<string | null>(null);
const [isOpen, setOpen] = useState(false);
const [currentContext, setCurrentContext] = useState<any>(null);
const [, setCurrentContext] = useState<any>(null);
Copy link
Contributor

Choose a reason for hiding this comment

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

State getter is ignored; prefer useRef when only the setter-equivalent is required to avoid extra re-renders.

Prompt for AI agents
Address the following comment on apps/mail/providers/voice-provider.tsx at line 47:

<comment>State getter is ignored; prefer `useRef` when only the setter-equivalent is required to avoid extra re-renders.</comment>

<file context>
@@ -27,7 +44,7 @@ export function VoiceProvider({ children }: { children: ReactNode }) {
   const [isInitializing, setIsInitializing] = useState(false);
   const [lastToolCall, setLastToolCall] = useState&lt;string | null&gt;(null);
   const [isOpen, setOpen] = useState(false);
-  const [currentContext, setCurrentContext] = useState&lt;any&gt;(null);
+  const [, setCurrentContext] = useState&lt;any&gt;(null);
 
   const conversation = useConversation({
</file context>

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

Labels

content design Improvements & changes to design & UX

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant