Skip to content

When enabling reply tracker check if any old emails need replies#323

Merged
elie222 merged 4 commits intomainfrom
seed-reply-tracker
Feb 5, 2025
Merged

When enabling reply tracker check if any old emails need replies#323
elie222 merged 4 commits intomainfrom
seed-reply-tracker

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Feb 5, 2025

Summary by CodeRabbit

  • New Features
    • Enhanced reply tracking: The system now analyzes recent sent emails to improve the detection and logging of replies.
    • New functionality to retrieve reply tracking rules for users.
  • Chores
    • Introduced minor backend adjustments to support the enhanced email tracking functionality.

@vercel
Copy link

vercel bot commented Feb 5, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Updated (UTC)
inbox-zero 🛑 Canceled (Inspect) Feb 5, 2025 2:19pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 5, 2025

Warning

Rate limit exceeded

@elie222 has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 8 minutes and 34 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, 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 have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between e03a907 and 2000f59.

📒 Files selected for processing (1)
  • apps/web/utils/actions/reply-tracking.ts (3 hunks)

Walkthrough

This pull request introduces a new constant maxDuration (set to 300) in the Reply Tracker page component without altering its existing behavior. Additionally, the reply tracker action has been updated to retrieve a Gmail client and process the last 20 sent emails immediately after enabling reply tracking. A new asynchronous function, processPreviousSentEmails, is added to fetch, group, and process recent sent emails from a user's Gmail account. The user data retrieval is also enhanced by including an additional field, about. Several new functions are introduced to streamline reply tracking and processing.

Changes

File(s) Change Summary
apps/web/app/(app)/reply-tracker/page.tsx Added constant maxDuration = 300 without affecting the existing logic of the ReplyTrackerPage component.
apps/web/utils/actions/reply-tracking.ts
apps/web/utils/reply-tracker/check-previous-emails.ts
Updated enableReplyTrackerAction to obtain a Gmail client and process last sent emails. Introduced processPreviousSentEmails to retrieve, group, and process recent sent emails. User data now includes the about field.
apps/web/utils/reply-tracker/inbound.ts Added handleInboundReply function to process inbound replies based on user-defined rules.
apps/web/utils/reply-tracker/index.ts Introduced getReplyTrackingRule function to query the database for reply tracking rules.
apps/web/utils/reply-tracker/outbound.ts Removed isReplyTrackingEnabled function; replaced with a call to getReplyTrackingRule to simplify reply tracking checks.
apps/web/utils/ai/choose-rule/ai-choose-rule.ts Updated logging from console.warn to logger.warn in the aiChooseRule function.

Sequence Diagram(s)

sequenceDiagram
    participant U as User/Session
    participant A as enableReplyTrackerAction
    participant G as GmailClient (via getGmailClient)
    participant P as processPreviousSentEmails

    U->>A: Request to enable reply tracker
    A->>G: Retrieve Gmail Client (using access token)
    A->>P: Process previous sent emails (pass Gmail client & user data)
    P-->>A: Return completion status
Loading
sequenceDiagram
    participant P as processPreviousSentEmails
    participant M as getMessages
    participant H as handleOutboundReply

    P->>M: Fetch last 20 sent messages
    alt Messages Found
        P->>P: Group messages by thread
        P->>M: Retrieve thread messages & sort by internalDate
        alt Message labeled "SENT"
            P->>H: Process outbound reply
        else Other message labels
            P->>P: (Placeholder for inbound reply handling)
        end
    else No messages
        P->>P: Log informational message and exit
    end
    P->>P: Log completion of processing
Loading

Poem

I’m a bunny with a clever gaze,
Hopping through code in digital ways!
New constants bloom and functions sing,
Gmail and threads join in to bring
A garden of changes—bright and spry,
Carrots of code make my spirit fly! 🥕✨
Happy hops to every fix and tweak!


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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

@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: 3

🧹 Nitpick comments (1)
apps/web/utils/reply-tracker/check-previous-emails.ts (1)

54-59: Consider adding retry logic for failed message processing.

Currently, if processing a message fails, the error is logged but the function continues to the next message. Consider adding retry logic for transient failures.

+    const maxRetries = 3;
+    let retryCount = 0;
+    while (retryCount < maxRetries) {
       try {
         if (latestMessage.labelIds?.includes(GmailLabel.SENT)) {
           logger.info("Processing outbound reply", loggerOptions);
           await handleOutboundReply(user, latestMessage, gmail);
         } else {
           // TODO: inbound
         }
+        break;
       } catch (error) {
+        retryCount++;
+        if (retryCount === maxRetries) {
           logger.error("Error processing message for reply tracking", {
             ...loggerOptions,
             error,
+            retryCount,
           });
+        } else {
+          logger.warn("Retrying message processing", {
+            ...loggerOptions,
+            error,
+            retryCount,
+          });
+          await new Promise(resolve => setTimeout(resolve, 1000 * retryCount));
+        }
       }
+    }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5728216 and a3a170b.

📒 Files selected for processing (3)
  • apps/web/app/(app)/reply-tracker/page.tsx (1 hunks)
  • apps/web/utils/actions/reply-tracking.ts (3 hunks)
  • apps/web/utils/reply-tracker/check-previous-emails.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/web/app/(app)/reply-tracker/page.tsx
🔇 Additional comments (3)
apps/web/utils/reply-tracker/check-previous-emails.ts (3)

13-17: LGTM! Function signature is well-defined.

The function parameters are properly typed with sensible defaults.


44-54: Consider implementing inbound reply processing.

There's a TODO comment for inbound reply processing, but no implementation yet.

Would you like me to help implement the inbound reply processing logic or create an issue to track this task?


32-34: Potential issue with sorting messages.

The sort function assumes internalDate is always present. While the fallback to 0 prevents crashes, it could lead to incorrect sorting.

Consider validating that messages have valid dates before sorting:

-    const latestMessage = threadMessages.sort(
-      (a, b) => (Number(b.internalDate) || 0) - (Number(a.internalDate) || 0),
-    )[0];
+    const validMessages = threadMessages.filter(msg => msg.internalDate);
+    if (validMessages.length === 0) continue;
+    const latestMessage = validMessages.sort(
+      (a, b) => Number(b.internalDate!) - Number(a.internalDate!),
+    )[0];
✅ Verification successful

Error: No shell scripts or web queries found


Review: Sorting by internalDate may yield incorrect ordering if any emails lack valid dates

After reviewing the code and considering the potential implications of falling back to a 0 value, it appears that messages without a valid internalDate could be mistakenly treated as having an epoch timestamp. This can lead to them being incorrectly prioritized in the sorted array. Filtering out messages without a valid date—like the proposed change—ensures that only meaningful timestamps are used for determining the "latest" message.

  • The current fallback (|| 0) prevents runtime errors but might result in inaccurate sorting.
  • The suggested update, which filters out messages lacking internalDate, would address the risk of misordering.
  • Please verify that skipping messages with invalid or missing dates aligns with the intended behavior in this workflow.

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

🧹 Nitpick comments (1)
apps/web/utils/reply-tracker/check-previous-emails.ts (1)

29-61: Consider batch processing and rate limiting.

The sequential processing of messages could be slow for users with many emails. Additionally, rapid Gmail API calls might hit rate limits.

Consider these improvements:

  1. Process messages in parallel with controlled concurrency
  2. Add rate limiting for Gmail API calls
-  for (const threadId of Object.keys(messagesByThreadId)) {
+  const batchSize = 5; // Process 5 threads at a time
+  const threadIds = Object.keys(messagesByThreadId);
+  for (let i = 0; i < threadIds.length; i += batchSize) {
+    const batch = threadIds.slice(i, i + batchSize);
+    await Promise.all(
+      batch.map(async (threadId) => {
         const threadMessages = await getThreadMessages(threadId, gmail);
         // ... rest of the processing logic
+      })
+    );
+    // Add delay between batches to respect rate limits
+    if (i + batchSize < threadIds.length) {
+      await new Promise(resolve => setTimeout(resolve, 1000));
+    }
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between a3a170b and e03a907.

📒 Files selected for processing (5)
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts (1 hunks)
  • apps/web/utils/reply-tracker/check-previous-emails.ts (1 hunks)
  • apps/web/utils/reply-tracker/inbound.ts (2 hunks)
  • apps/web/utils/reply-tracker/index.ts (1 hunks)
  • apps/web/utils/reply-tracker/outbound.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/web/utils/ai/choose-rule/ai-choose-rule.ts
🔇 Additional comments (1)
apps/web/utils/reply-tracker/outbound.ts (1)

142-167: Consider potential race condition in resolveReplyTrackers.

The database update and label removal operations are independent, which could lead to inconsistency if one operation fails.

Consider using a transaction or implementing a retry mechanism:

 async function resolveReplyTrackers(
   gmail: gmail_v1.Gmail,
   userId: string,
   threadId: string,
   needsReplyLabelId: string,
 ) {
-  const updateDbPromise = prisma.threadTracker.updateMany({
-    where: {
-      userId,
-      threadId,
-      resolved: false,
-      type: ThreadTrackerType.NEEDS_REPLY,
-    },
-    data: {
-      resolved: true,
-    },
-  });
-
-  const labelPromise = removeNeedsReplyLabel(
-    gmail,
-    threadId,
-    needsReplyLabelId,
-  );
-
-  await Promise.allSettled([updateDbPromise, labelPromise]);
+  const maxRetries = 3;
+  let retries = 0;
+  
+  while (retries < maxRetries) {
+    try {
+      await prisma.$transaction(async (tx) => {
+        await tx.threadTracker.updateMany({
+          where: {
+            userId,
+            threadId,
+            resolved: false,
+            type: ThreadTrackerType.NEEDS_REPLY,
+          },
+          data: {
+            resolved: true,
+          },
+        });
+        
+        await removeNeedsReplyLabel(gmail, threadId, needsReplyLabelId);
+      });
+      break;
+    } catch (error) {
+      retries++;
+      if (retries === maxRetries) {
+        logger.error("Failed to resolve reply trackers after retries", {
+          userId,
+          threadId,
+          error,
+        });
+        throw error;
+      }
+      await new Promise(resolve => setTimeout(resolve, 1000 * retries));
+    }
+  }
 }

@elie222 elie222 merged commit b6bab82 into main Feb 5, 2025
3 of 4 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Feb 25, 2025
@coderabbitai coderabbitai bot mentioned this pull request Apr 7, 2025
@coderabbitai coderabbitai bot mentioned this pull request Aug 28, 2025
@coderabbitai coderabbitai bot mentioned this pull request Sep 16, 2025
@elie222 elie222 deleted the seed-reply-tracker branch December 18, 2025 23:08
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

Comments