Skip to content

Comments

Add auto draft generation#1645

Merged
ahmetskilinc merged 2 commits intostagingfrom
07-04-add_auto_draft_generation
Jul 18, 2025
Merged

Add auto draft generation#1645
ahmetskilinc merged 2 commits intostagingfrom
07-04-add_auto_draft_generation

Conversation

@ahmetskilinc
Copy link
Contributor

@ahmetskilinc ahmetskilinc commented Jul 5, 2025

Automatic Email Draft Generation Feature

This PR implements an automatic email draft generation feature that creates AI-powered responses when new emails are received. The system analyzes incoming emails, determines their intent, and generates contextually appropriate draft replies.

The feature includes:

  • Smart filtering to skip newsletters, no-reply emails, user's own emails, and old messages
  • Intent analysis to categorize emails (questions, requests, meetings, urgent matters)
  • Context-aware responses using the full email thread history
  • Proper draft formatting with correct recipients and subjects
  • Integration with existing ThreadWorkflow after user notification
  • Storage of draft references in the summary table

Summary by CodeRabbit

  • New Features

    • Introduced automatic draft email generation for Google provider threads, creating suggested replies based on the intent of incoming messages.
    • Drafts are generated only for relevant, recent, and non-automated emails, ensuring responses are contextually appropriate.
  • Bug Fixes

    • Improved reliability by ensuring database connections remain open throughout the entire thread processing workflow.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 5, 2025

Walkthrough

This change adds automatic draft email generation to the thread processing workflow for Google provider threads. It introduces new utility functions to analyze email intent, determine draft necessity, and generate drafts. The workflow now conditionally creates and stores draft replies based on thread content, with improved database connection management and error handling.

Changes

File(s) Change Summary
apps/server/src/pipelines.effect.ts Enhanced runThreadWorkflow to include conditional automatic draft generation and improved DB connection handling.
apps/server/src/thread-workflow-utils/index.ts New module exporting utilities: shouldGenerateDraft, analyzeEmailIntent, and generateAutomaticDraft.

Sequence Diagram(s)

sequenceDiagram
    participant Workflow as runThreadWorkflow
    participant DB as Database
    participant Utils as thread-workflow-utils
    participant Agent as Agent (createDraft)
    participant Logger as Logger

    Workflow->>DB: Fetch thread and connection
    alt Thread has messages and is Google provider
        Workflow->>Utils: shouldGenerateDraft(thread, connection)
        alt Draft should be generated
            Workflow->>Utils: generateAutomaticDraft(connectionId, thread, connection)
            Utils->>Utils: analyzeEmailIntent(latest message)
            Utils->>Agent: composeEmail(...) (via composeEmail route)
            Agent-->>Utils: Draft content
            Utils-->>Workflow: Draft content
            Workflow->>Agent: createDraft(draft content)
            Agent-->>Workflow: Draft ID
            Workflow->>DB: Store draft ID in summary
            Workflow->>Logger: Log draft creation success
        else Draft not needed
            Workflow->>Logger: Log skipping draft generation
        end
    end
    Workflow->>DB: Close connection
    Workflow->>Logger: Log workflow completion
Loading

Possibly related PRs

Poem

A rabbit hopped through threads of mail,
With clever tools that never fail.
It sniffed for questions, urgent pleas,
And drafted answers with such ease!
Now inboxes are light and spry—
Thanks to this update, give it a try!
🐇💌


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 7022bc1 and 9c691b5.

📒 Files selected for processing (2)
  • apps/server/src/pipelines.effect.ts (3 hunks)
  • apps/server/src/thread-workflow-utils/index.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/server/src/pipelines.effect.ts
  • apps/server/src/thread-workflow-utils/index.ts
✨ 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
Contributor Author

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

@ahmetskilinc ahmetskilinc force-pushed the 07-04-add_auto_draft_generation branch from 57934ca to 48e4783 Compare July 5, 2025 13:49
@ahmetskilinc ahmetskilinc force-pushed the 07-04-add_auto_draft_generation branch from 48e4783 to 7022bc1 Compare July 15, 2025 14:14
@ahmetskilinc ahmetskilinc marked this pull request as ready for review July 15, 2025 14:17
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
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 found 1 issue across 2 files. Review it in cubic.dev

React with 👍 or 👎 to teach cubic. Tag @cubic-dev-ai to give specific feedback.

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: 0

♻️ Duplicate comments (1)
apps/server/src/pipelines.effect.ts (1)

493-493: Remove duplicate variable declaration

The latestMessage variable is already defined on line 462. This redeclaration shadows the existing variable.

-            const latestMessage = thread.messages[thread.messages.length - 1];
🧹 Nitpick comments (2)
apps/server/src/thread-workflow-utils/index.ts (2)

7-42: Consider making automated email patterns configurable

The function correctly identifies automated emails, but the hardcoded patterns could be moved to a configuration object for better maintainability and customization.

Example refactor:

const AUTOMATED_EMAIL_PATTERNS = {
  senderPatterns: ['no-reply', 'noreply', 'donotreply', 'do-not-reply'],
  subjectPatterns: ['newsletter', 'unsubscribe', 'notification'],
  bodyPatterns: ['do not reply', 'this is an automated']
};

// Then use:
if (AUTOMATED_EMAIL_PATTERNS.senderPatterns.some(pattern => 
  latestMessage.sender?.email?.toLowerCase().includes(pattern)) ||
  // ... rest of the checks

94-99: Include additional context in composeEmail call

Consider passing additional parameters to composeEmail for better draft generation context:

 const draftContent = await composeEmail({
   prompt,
   threadMessages,
   username: foundConnection.name || foundConnection.email || 'User',
   connectionId,
+  to: latestMessage.sender ? [{ email: latestMessage.sender.email, name: latestMessage.sender.name }] : [],
+  cc: latestMessage.cc || [],
+  emailSubject: latestMessage.subject || '',
 });
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 816279b and 7022bc1.

📒 Files selected for processing (2)
  • apps/server/src/pipelines.effect.ts (3 hunks)
  • apps/server/src/thread-workflow-utils/index.ts (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: retrogtx
PR: Mail-0/Zero#1734
File: apps/server/src/lib/driver/google.ts:211-221
Timestamp: 2025-07-15T06:46:33.321Z
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.
apps/server/src/pipelines.effect.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.321Z
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.
apps/server/src/thread-workflow-utils/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.321Z
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/thread-workflow-utils/index.ts (4)
apps/server/src/lib/driver/types.ts (1)
  • IGetThreadResponse (6-12)
apps/server/src/db/schema.ts (1)
  • connection (118-142)
apps/server/src/trpc/routes/ai/compose.ts (1)
  • composeEmail (32-112)
apps/server/src/pipelines.effect.ts (1)
  • log (38-44)
🔇 Additional comments (5)
apps/server/src/pipelines.effect.ts (4)

19-24: LGTM!

The new imports for thread workflow utilities are properly organized and follow the existing import structure.


38-38: Appropriate export for shared utility

Exporting the log function is necessary for the new thread-workflow-utils module to maintain consistent logging across the codebase.


539-569: Well-implemented draft reference storage

The upsert operation correctly stores the draft reference in the summary table, handling conflicts appropriately and maintaining audit timestamps.


928-935: Good database connection lifecycle management

Moving the connection close to the end of the workflow ensures the connection remains available throughout the draft generation process. The error handling with Effect.orElse provides graceful failure recovery.

apps/server/src/thread-workflow-utils/index.ts (1)

44-58: Well-designed intent analysis

The function efficiently analyzes email intent using appropriate regex patterns. Combining content and subject for meeting/urgent detection is a smart approach that improves accuracy.

@ahmetskilinc ahmetskilinc force-pushed the 07-04-add_auto_draft_generation branch from 7022bc1 to 9c691b5 Compare July 18, 2025 11:43
import { defaultLabels, EPrompts, EProviders, type ParsedMessage, type Sender } from './types';
import { getZeroAgent } from './lib/server-utils';
import { type gmail_v1 } from '@googleapis/gmail';
import { connection, summary } from './db/schema';
Copy link
Contributor

Choose a reason for hiding this comment

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

Remove the unused 'summary' import to fix the linting warning. Change to: import { connection } from './db/schema';

Spotted by Diamond (based on CI logs)

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

return 'Thread has no messages';
}

const autoDraftId = yield* Effect.tryPromise({
Copy link
Contributor

Choose a reason for hiding this comment

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

Rename 'autoDraftId' to '_autoDraftId' to indicate it's intentionally unused and fix the linting warning. Change to: const _autoDraftId = yield* Effect.tryPromise({

Spotted by Diamond (based on CI logs)

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

@ahmetskilinc ahmetskilinc merged commit ecb2126 into staging Jul 18, 2025
6 of 7 checks passed
Copy link
Contributor Author

Merge activity

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.

2 participants