Skip to content

Comments

feat: ability to snooze emails#1477

Merged
MrgSub merged 20 commits intoMail-0:stagingfrom
retrogtx:snoozing
Jul 21, 2025
Merged

feat: ability to snooze emails#1477
MrgSub merged 20 commits intoMail-0:stagingfrom
retrogtx:snoozing

Conversation

@retrogtx
Copy link
Contributor

@retrogtx retrogtx commented Jun 25, 2025

you can now snooze emails

snoozing.mp4

Summary by CodeRabbit

  • New Features

    • Introduced "Snoozed" as a new mail folder, accessible from the sidebar with a dedicated icon and keyboard shortcut.
    • Added the ability to snooze email threads, selecting a wake-up date and time via a dialog.
    • Enabled unsnoozing of threads, automatically returning them to the inbox when the snooze period ends.
    • Snoozed emails are visually grouped and managed in their own folder.
    • Added context menu actions for snoozing and unsnoozing threads.
    • Automatic unsnoozing triggered on folder access and via background processing.
  • Bug Fixes

    • Improved label handling and state updates for snoozed and unsnoozed threads.
  • Style

    • Updated the clock icon appearance for better visual clarity.
  • Documentation

    • Added English localization for the "Snoozed" folder.
  • Chores

    • Updated configuration and background processing to support scheduled unsnoozing of emails.

retrogtx added 2 commits June 25, 2025 12:27
- Introduced a new 'Snoozed' folder to manage temporarily hidden emails.
- Implemented optimistic actions for snoozing and unsnoozing threads.
- Updated UI components to support snooze actions in the context menu.
- Enhanced mail manager to handle snoozed emails and their wake times.
- Added necessary translations and navigation updates for the new feature.
@retrogtx retrogtx marked this pull request as draft June 25, 2025 07:11
@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jun 25, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This change introduces comprehensive "snooze" functionality to the mail application. It adds a new "Snoozed" folder, updates navigation, thread actions, and optimistic state handling, and implements UI components and backend logic for snoozing and unsnoozing email threads. Associated storage, scheduling, and queueing infrastructure are also integrated.

Changes

File(s) Change Summary
apps/mail/app/(routes)/mail/[folder]/page.tsx Added "snoozed" to the set of allowed folders.
apps/mail/components/context/thread-context.tsx Added snooze/unsnooze actions and dialog to thread context menu; refactored label checks and handlers.
apps/mail/components/icons/icons.tsx Updated Clock icon SVG with fill color and opacity attributes.
apps/mail/components/mail/optimistic-thread-state.tsx Added handling for SNOOZE and UNSNOOZE optimistic actions in thread state hook.
apps/mail/components/mail/snooze-dialog.tsx Introduced new SnoozeDialog React component for selecting snooze date/time.
apps/mail/config/navigation.ts Added "Snoozed" folder to navigation with clock icon and shortcut.
apps/mail/hooks/use-optimistic-actions.ts Added optimistic snooze/unsnooze actions, mutations, and API to hook.
apps/mail/lib/optimistic-actions-manager.ts Extended BasePendingAction type to include SNOOZE and UNSNOOZE.
apps/mail/lib/thread-actions.ts Added "snoozed" to thread destinations and action logic.
apps/mail/lib/utils.ts
apps/server/src/lib/utils.ts
Added SNOOZED to FOLDERS, LABELS, FOLDER_NAMES, and FOLDER_TAGS constants.
apps/mail/store/optimistic-updates.ts Extended OptimisticAction type with SNOOZE and UNSNOOZE variants.
apps/server/src/lib/driver/google.ts Implemented label name-to-ID resolution with caching, improved label modification error handling, and added support for "snoozed" folder in search normalization.
apps/server/src/main.ts Added scheduled processing for snoozed emails: checks wake-up times, enqueues unsnooze tasks, and integrates with queue/agent system.
apps/server/src/overrides.d.ts Added snoozed_emails KV namespace and unsnooze_queue to Cloudflare Env interface.
apps/server/src/trpc/routes/mail.ts Refactored thread listing, added automatic unsnoozing for expired snoozed threads, and introduced snoozeThreads and unsnoozeThreads mutations.
apps/server/wrangler.jsonc Added cron trigger and snoozed_emails KV namespace binding to environments.
apps/mail/messages/en.json Added English translation key for "Snoozed" navigation.
apps/server/src/types.ts Added ISnoozeBatch interface for unsnooze batch queue payloads.
apps/server/src/routes/agent/index.ts Added unsnoozeThreadsHandler method, currentFolder property, and updated thread listing/return types.
apps/server/src/routes/agent/rpc.ts Added queue method to DriverRpcDO for queueing tasks.
apps/server/src/routes/agent/types.ts Added QueueFunc type alias for queue function signature.
apps/server/src/lib/driver/types.ts Added IGetThreadsResponse interface and Zod schema for thread list responses.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant UI
    participant SnoozeDialog
    participant OptimisticActions
    participant ServerAPI
    participant KVStore
    participant Scheduler
    participant Queue
    participant Agent

    User->>UI: Right-click thread, select "Snooze"
    UI->>SnoozeDialog: Open snooze dialog
    User->>SnoozeDialog: Select date/time, confirm
    SnoozeDialog->>OptimisticActions: optimisticSnooze(threadId, wakeAt)
    OptimisticActions->>UI: Update thread state (hide/move)
    OptimisticActions->>ServerAPI: snoozeThreads(threadId, wakeAt)
    ServerAPI->>KVStore: Store wakeAt for threadId
    ServerAPI->>Mail: Add SNOOZED label, remove INBOX
    loop Every minute (Scheduler)
        Scheduler->>KVStore: List snoozed threads with expired wakeAt
        Scheduler->>Queue: Enqueue unsnooze tasks per connection
        Queue->>Agent: unsnoozeThreadsHandler(threadIds)
        Agent->>Mail: Remove SNOOZED, add INBOX, delete KV entries
    end
    User->>UI: Open "Snoozed" folder
    UI->>ServerAPI: listThreads(folder="snoozed")
    ServerAPI->>KVStore: Check wakeAt for threads
    ServerAPI->>Mail: Auto-unsnooze expired threads
    ServerAPI->>UI: Return up-to-date snoozed threads
Loading

Possibly related PRs

  • keyboard navigation #521: Deletes the thread-context.tsx file, conflicting with this PR which adds snooze features to the same component.
  • context #595: Introduces the initial ThreadContextMenu component, which this PR extends with snooze-related actions.

Poem

In the warren of code, a new folder appears,
"Snoozed" for our threads, to rest with their peers.
With a click and a clock, your emails will nap,
Until wake-up time calls—then they leap from the gap!
🕰️🐇
Hop, hop, hooray—snooze dreams are here to stay!


📜 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 116a467 and cbc222d.

📒 Files selected for processing (2)
  • apps/server/src/lib/driver/google.ts (5 hunks)
  • apps/server/src/routes/agent/index.ts (7 hunks)
✨ 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.

@retrogtx retrogtx marked this pull request as ready for review June 27, 2025 04:09
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: 12

🧹 Nitpick comments (1)
apps/mail/hooks/use-optimistic-actions.ts (1)

381-407: Optimize date conversion and improve toast message consistency.

The function has redundant date conversions and inconsistent date formatting in the toast message.

 function optimisticSnooze(threadIds: string[], currentFolder: string, wakeAt: Date) {
   if (!threadIds.length) return;
+  
+  const wakeAtIso = wakeAt.toISOString();

   const optimisticId = addOptimisticAction({
     type: 'SNOOZE',
     threadIds,
-    wakeAt: wakeAt.toISOString(),
+    wakeAt: wakeAtIso,
   });

   createPendingAction({
     type: 'SNOOZE',
     threadIds,
-    params: { currentFolder, wakeAt: wakeAt.toISOString() },
+    params: { currentFolder, wakeAt: wakeAtIso },
     optimisticId,
     execute: async () => {
-      await snoozeThreads({ ids: threadIds, wakeAt: wakeAt.toISOString() });
+      await snoozeThreads({ ids: threadIds, wakeAt: wakeAtIso });
       if (mail.bulkSelected.length > 0) {
         setMail({ ...mail, bulkSelected: [] });
       }
     },
     undo: () => {
       removeOptimisticAction(optimisticId);
     },
-    toastMessage: `Snoozed until ${wakeAt.toLocaleString()}`,
+    toastMessage: t('common.actions.snoozedUntil', { date: wakeAt.toLocaleDateString(), time: wakeAt.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' }) }),
     folders: [currentFolder, 'snoozed'],
   });
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 315b2fc and a2ef2a6.

📒 Files selected for processing (19)
  • apps/mail/app/(routes)/mail/[folder]/page.tsx (1 hunks)
  • apps/mail/components/context/thread-context.tsx (10 hunks)
  • apps/mail/components/icons/icons.tsx (1 hunks)
  • apps/mail/components/mail/optimistic-thread-state.tsx (1 hunks)
  • apps/mail/components/mail/snooze-dialog.tsx (1 hunks)
  • apps/mail/config/navigation.ts (2 hunks)
  • apps/mail/hooks/use-optimistic-actions.ts (4 hunks)
  • apps/mail/lib/optimistic-actions-manager.ts (1 hunks)
  • apps/mail/lib/thread-actions.ts (3 hunks)
  • apps/mail/lib/utils.ts (4 hunks)
  • apps/mail/locales/en.json (1 hunks)
  • apps/mail/store/optimistic-updates.ts (1 hunks)
  • apps/server/src/lib/driver/google.ts (5 hunks)
  • apps/server/src/lib/schemas.ts (2 hunks)
  • apps/server/src/lib/utils.ts (4 hunks)
  • apps/server/src/main.ts (1 hunks)
  • apps/server/src/overrides.d.ts (1 hunks)
  • apps/server/src/trpc/routes/mail.ts (2 hunks)
  • apps/server/wrangler.jsonc (4 hunks)
🧰 Additional context used
🧠 Learnings (7)
apps/mail/app/(routes)/mail/[folder]/page.tsx (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/mail/config/navigation.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/mail/components/mail/optimistic-thread-state.tsx (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/mail/lib/thread-actions.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/mail/lib/utils.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/mail/hooks/use-optimistic-actions.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/mail/components/context/thread-context.tsx (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.
🧬 Code Graph Analysis (6)
apps/mail/config/navigation.ts (1)
apps/mail/components/icons/icons.tsx (1)
  • Clock (1615-1632)
apps/mail/lib/thread-actions.ts (1)
apps/mail/lib/utils.ts (1)
  • LABELS (20-28)
apps/mail/lib/utils.ts (1)
apps/server/src/lib/utils.ts (2)
  • FOLDERS (43-51)
  • LABELS (53-61)
apps/server/src/lib/utils.ts (1)
apps/mail/lib/utils.ts (2)
  • FOLDERS (10-18)
  • LABELS (20-28)
apps/mail/components/mail/snooze-dialog.tsx (2)
apps/mail/components/ui/dialog.tsx (7)
  • Dialog (107-107)
  • DialogTrigger (111-111)
  • DialogContent (112-112)
  • DialogHeader (113-113)
  • DialogTitle (115-115)
  • DialogDescription (116-116)
  • DialogFooter (114-114)
apps/mail/components/ui/input.tsx (1)
  • Input (22-22)
apps/server/src/main.ts (1)
apps/server/src/lib/server-utils.ts (1)
  • getZeroAgent (13-18)
🪛 Biome (1.9.4)
apps/server/src/lib/driver/google.ts

[error] 1248-1248: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (24)
apps/server/src/overrides.d.ts (1)

3-3: KV binding addition looks correct – double-check wrangler.jsonc keeps them in sync

The snoozed_emails KVNamespace entry is well-typed.
Just make sure every environment section in wrangler.jsonc (local / staging / prod) actually declares the same binding name; mismatches silently break at runtime.

apps/mail/lib/optimistic-actions-manager.ts (1)

3-3: Good: optimistic action types updated

Including 'SNOOZE' | 'UNSNOOZE' keeps type-safety intact for the new feature.
No further issues spotted.

apps/mail/components/icons/icons.tsx (1)

1625-1630: SVG now respects dynamic theming – nice

Adding fill="var(--icon-color)" & fillOpacity="0.5" to the Clock path keeps it consistent with the other icons. 👍

apps/mail/locales/en.json (1)

363-364: LGTM: Clean localization addition for snoozed folder.

The addition follows the existing pattern and integrates well with the navigation structure.

apps/server/wrangler.jsonc (1)

96-98: LGTM: Appropriate cron configuration for snooze processing.

The every-minute trigger for local development enables effective testing of the snooze functionality.

apps/mail/config/navigation.ts (2)

20-20: LGTM: Proper icon import for snoozed functionality.

The Clock icon import aligns with the snoozed folder feature.


92-98: LGTM: Well-integrated navigation item for snoozed folder.

The navigation configuration follows established patterns:

  • Proper placement in the "Management" section alongside archive and spam
  • Consistent keyboard shortcut pattern ("g + z")
  • Appropriate Clock icon usage with styling support for opacity/fill
  • Correct localization key reference
apps/mail/store/optimistic-updates.ts (1)

10-11: LGTM: Well-designed optimistic action types for snooze functionality.

The action types follow the established pattern and include appropriate data:

  • SNOOZE includes both threadIds and wakeAt timestamp for scheduling
  • UNSNOOZE includes only threadIds as expected for the simpler operation
apps/server/src/lib/schemas.ts (2)

124-124: LGTM: Improved user settings schema with sensible default.

Adding a default empty string for customPrompt makes the field optional while maintaining backward compatibility. This aligns well with the defaultUserSettings object.


31-31: ```shell
#!/bin/bash

Check if drivers handle attachments in createDraft

echo "Searching for direct references to data.attachments in driver code..."
rg -n "data.attachments" -C 5 apps/server/src/lib/driver

echo; echo "Searching for attachment usage in Google driver..."
rg -n "attachment" -C 5 apps/server/src/lib/driver/google.ts

echo; echo "Searching for attachment usage in Microsoft driver..."
rg -n "attachment" -C 5 apps/server/src/lib/driver/microsoft.ts


</details>
<details>
<summary>apps/mail/components/mail/optimistic-thread-state.tsx (1)</summary>

`67-75`: **LGTM! Optimistic state handling for snooze actions is correctly implemented.**

The logic properly handles both snooze and unsnooze actions by hiding the thread from the current view and setting the appropriate destination folder. This ensures smooth UI transitions during async operations.

</details>
<details>
<summary>apps/mail/lib/utils.ts (4)</summary>

`17-17`: **SNOOZED folder constant is correctly added.**

The folder constant follows the established naming convention with lowercase value.

---

`27-27`: **SNOOZED label constant is correctly added.**

The label constant follows the established naming convention with uppercase value.

---

`39-39`: **Folder name properly added to FOLDER_NAMES array.**

The 'snoozed' folder name is correctly included in the array for consistent folder handling.

---

`48-48`: **Folder-to-label mapping is correctly configured.**

The FOLDER_TAGS mapping properly associates the SNOOZED folder with its corresponding label.

</details>
<details>
<summary>apps/server/src/main.ts (1)</summary>

`700-721`: **Scheduled task for auto-unsnoozing is well implemented.**

The logic correctly:
- Retrieves and processes all snoozed email keys
- Validates wake-up timestamps against current time
- Properly parses the key format to extract thread and connection IDs
- Uses the ZeroAgent to perform label modifications (remove SNOOZED, add INBOX)
- Includes proper error handling and cleanup
- Maintains good separation of concerns by processing before existing subscription logic

The implementation ensures snoozed emails automatically return to the inbox when their snooze period expires.

</details>
<details>
<summary>apps/server/src/lib/utils.ts (4)</summary>

`50-50`: **Server-side SNOOZED folder constant matches client implementation.**

The folder constant is consistent with the client-side utils, ensuring proper synchronization between frontend and backend.

---

`60-60`: **Server-side SNOOZED label constant matches client implementation.**

The label constant maintains consistency with the client-side utils for seamless integration.

---

`72-72`: **Folder name inclusion maintains client-server consistency.**

The 'snoozed' folder name is properly included in the server-side array, matching the client implementation.

---

`81-81`: **Server-side folder-to-label mapping is correctly configured.**

The FOLDER_TAGS mapping on the server side properly mirrors the client-side implementation, ensuring consistent behavior across the application.

</details>
<details>
<summary>apps/mail/components/context/thread-context.tsx (1)</summary>

`73-111`: **Good type safety improvements!**

The refactoring to use proper Label typing and filtering for labels with IDs improves code reliability.

</details>
<details>
<summary>apps/server/src/lib/driver/google.ts (1)</summary>

`454-479`: **Well-designed backward-compatible API!**

The flexible parameter handling maintains backward compatibility while supporting the new object format.

</details>
<details>
<summary>apps/mail/lib/thread-actions.ts (2)</summary>

`4-4`: **LGTM! Type extension is correct.**

The addition of `'snoozed'` to the `ThreadDestination` type is properly implemented and consistent with existing destinations.

---

`78-87`: **Implementation looks correct, but verify unsnoozing functionality.**

The snoozed case logic is well-implemented and follows the established pattern. However, I don't see cases in `isActionAvailable` for moving FROM snoozed to other folders (manual unsnoozing).



Please verify that manual unsnoozing functionality is properly supported. Run this script to check for unsnoozing patterns:

```shell
#!/bin/bash
# Description: Check for unsnoozing functionality in the codebase
# Expected: Find cases for moving from snoozed folder to other destinations

# Search for snoozed-related patterns in isActionAvailable or similar functions
rg -A 5 -B 5 "FOLDERS\.SNOOZED.*_to_|snoozed.*_to_" 

# Search for unsnooze-related functionality
rg -A 5 "unsnooze|unsnooz"

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 (4)
apps/server/src/trpc/routes/mail.ts (2)

91-126: Improve error handling for KV store operations.

The code accesses env.snoozed_emails directly without checking if it exists, and error handling keeps failed threads in the list which might show expired threads to users.


430-455: Add date validation and improve atomicity.

The mutation doesn't validate the wake date and performs multiple operations that could partially fail.

apps/server/src/lib/driver/google.ts (2)

31-46: Add SNOOZED to system label IDs.

The SNOOZED label is a Gmail system label and should be included in the set to avoid unnecessary API calls.


1268-1298: Improve label resolution logic and apply static analysis suggestion.

Several improvements needed:

  1. Use optional chaining as suggested by static analysis
  2. Add 'SNOOZED' to system labels
  3. Improve label name prettification
🧹 Nitpick comments (1)
apps/server/src/trpc/routes/mail.ts (1)

456-472: Add error handling and input validation for consistency.

While the basic logic is correct, consider adding validation similar to other mutations and ensure consistent error handling.

 unsnoozeThreads: activeDriverProcedure
   .input(
     z.object({
       ids: z.string().array(),
     }),
   )
   .mutation(async ({ input, ctx }) => {
     const { activeConnection } = ctx;
     const agent = await getZeroAgent(activeConnection.id);
-    if (!input.ids.length) return { success: false, error: 'No thread IDs' };
+    
+    if (!input.ids.length) {
+      return { success: false, error: 'No thread IDs provided' };
+    }
+    
+    try {
       await agent.modifyLabels(input.ids, ['INBOX'], ['SNOOZED']);

       await Promise.all(
         input.ids.map((threadId) => env.snoozed_emails.delete(`${threadId}__${activeConnection.id}`)),
       );
+    } catch (error) {
+      console.error('[UNSNOOZE] Failed to unsnooze threads:', error);
+      return { success: false, error: 'Failed to unsnooze threads' };
+    }
+    
     return { success: true };
   }),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 1d569c8 and 889c14d.

📒 Files selected for processing (4)
  • apps/server/src/lib/driver/google.ts (5 hunks)
  • apps/server/src/main.ts (1 hunks)
  • apps/server/src/trpc/routes/mail.ts (2 hunks)
  • apps/server/wrangler.jsonc (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • apps/server/src/main.ts
  • apps/server/wrangler.jsonc
🧰 Additional context used
🧠 Learnings (1)
apps/server/src/trpc/routes/mail.ts (2)
Learnt from: retrogtx
PR: Mail-0/Zero#1468
File: apps/server/src/trpc/routes/mail.ts:386-391
Timestamp: 2025-06-27T04:59:29.709Z
Learning: In apps/server/src/trpc/routes/mail.ts, the attachment processing logic conditionally handles mixed attachment types - it preserves existing File-like objects with arrayBuffer methods while only converting serialized attachments that need processing through toAttachmentFiles.
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.
🪛 Biome (1.9.4)
apps/server/src/lib/driver/google.ts

[error] 1281-1281: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (4)
apps/server/src/trpc/routes/mail.ts (1)

78-89: LGTM - Good unification of thread listing logic.

The refactoring to always use agent.listThreads simplifies the code path and the ThreadItem type provides clear structure for the response data.

apps/server/src/lib/driver/google.ts (3)

458-483: LGTM - Flexible method signature improvement.

The overloaded modifyLabels method signature provides backward compatibility while enabling more flexible usage patterns. The label resolution integration is well implemented.


867-871: Good improvement to error reporting.

The enhanced error handling provides more specific error messages that will help with debugging label modification failures.


887-889: LGTM - Correct snoozed folder mapping.

The folder normalization correctly maps "snoozed" to the Gmail "Snoozed" label query format.

Copy link
Collaborator

@MrgSub MrgSub left a comment

Choose a reason for hiding this comment

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

i resolved conflicts

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

♻️ Duplicate comments (6)
apps/server/src/trpc/routes/mail.ts (2)

102-137: Improve error handling for KV store operations.

The code accesses env.snoozed_emails directly without checking if it exists, and error handling keeps failed threads in the list which might show expired threads to users.


441-466: Add date validation and improve atomicity.

The mutation doesn't validate the wake date and performs multiple operations that could partially fail.

apps/server/src/lib/driver/google.ts (2)

32-47: Add SNOOZED to system label IDs.

The SNOOZED label is a Gmail system label and should be included in the set to avoid unnecessary API calls.


1354-1384: Improve label resolution logic and apply static analysis suggestion.

Several improvements needed:

  1. Use optional chaining as suggested by static analysis
  2. Add 'SNOOZED' to system labels
  3. Improve label name prettification
apps/mail/components/context/thread-context.tsx (2)

364-387: Localize the "Unsnooze" label for consistency.

The "Unsnooze" label is hardcoded while other labels use translations.


491-497: Localize the "Snooze" label.

The "Snooze" label should be localized for consistency with other menu items.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 889c14d and 7993290.

📒 Files selected for processing (13)
  • apps/mail/app/(routes)/mail/[folder]/page.tsx (1 hunks)
  • apps/mail/components/context/thread-context.tsx (9 hunks)
  • apps/mail/components/icons/icons.tsx (1 hunks)
  • apps/mail/components/mail/optimistic-thread-state.tsx (1 hunks)
  • apps/mail/config/navigation.ts (2 hunks)
  • apps/mail/hooks/use-optimistic-actions.ts (5 hunks)
  • apps/mail/lib/optimistic-actions-manager.ts (1 hunks)
  • apps/mail/lib/utils.ts (4 hunks)
  • apps/mail/messages/en.json (1 hunks)
  • apps/server/src/lib/driver/google.ts (5 hunks)
  • apps/server/src/main.ts (1 hunks)
  • apps/server/src/trpc/routes/mail.ts (2 hunks)
  • apps/server/wrangler.jsonc (4 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/mail/messages/en.json
🚧 Files skipped from review as they are similar to previous changes (9)
  • apps/mail/app/(routes)/mail/[folder]/page.tsx
  • apps/mail/config/navigation.ts
  • apps/mail/lib/optimistic-actions-manager.ts
  • apps/mail/components/mail/optimistic-thread-state.tsx
  • apps/server/wrangler.jsonc
  • apps/server/src/main.ts
  • apps/mail/components/icons/icons.tsx
  • apps/mail/lib/utils.ts
  • apps/mail/hooks/use-optimistic-actions.ts
🧰 Additional context used
🧠 Learnings (3)
apps/server/src/trpc/routes/mail.ts (5)
Learnt from: retrogtx
PR: Mail-0/Zero#1468
File: apps/server/src/trpc/routes/mail.ts:386-391
Timestamp: 2025-06-27T04:59:29.731Z
Learning: In apps/server/src/trpc/routes/mail.ts, the attachment processing logic conditionally handles mixed attachment types - it preserves existing File-like objects with arrayBuffer methods while only converting serialized attachments that need processing through toAttachmentFiles.
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#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.
Learnt from: retrogtx
PR: Mail-0/Zero#1622
File: apps/server/src/lib/email-verification.ts:189-189
Timestamp: 2025-07-05T05:27:24.623Z
Learning: During testing phases, debug logging should be kept active in apps/server/src/lib/email-verification.ts for BIMI validation and email verification debugging, even if it's verbose.
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/mail/components/context/thread-context.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#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/lib/driver/google.ts (2)
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.
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.
🧬 Code Graph Analysis (1)
apps/server/src/trpc/routes/mail.ts (3)
apps/mail/lib/utils.ts (1)
  • FOLDERS (10-18)
apps/server/src/trpc/trpc.ts (1)
  • activeDriverProcedure (43-77)
apps/server/src/lib/server-utils.ts (1)
  • getZeroAgent (13-18)
🪛 Biome (1.9.4)
apps/server/src/trpc/routes/mail.ts

[error] 97-97: Expected a semicolon or an implicit semicolon after a statement, but found none

An explicit or implicit semicolon is expected here...

...Which is required to end this statement

(parse)


[error] 98-98: Expected an expression but instead found ']'.

Expected an expression here.

(parse)


[error] 98-98: Unexpected label.

Only loops should be labeled.
The use of labels for other statements is suspicious and unfamiliar.

(lint/suspicious/noConfusingLabels)


[error] 99-99: Unexpected label.

Only loops should be labeled.
The use of labels for other statements is suspicious and unfamiliar.

(lint/suspicious/noConfusingLabels)


[error] 97-100: This block statement doesn't serve any purpose and can be safely removed.

Standalone block statements without any block-level declarations are redundant in JavaScript and can be removed to simplify the code.
Safe fix: Remove redundant block.

(lint/complexity/noUselessLoneBlockStatements)

apps/mail/components/context/thread-context.tsx

[error] 216-216: Shouldn't redeclare 'optimisticToggleImportant'. Consider to delete it or rename it.

'optimisticToggleImportant' is defined here:

(lint/suspicious/noRedeclare)

apps/server/src/lib/driver/google.ts

[error] 1367-1367: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🪛 GitHub Actions: autofix.ci
apps/server/src/trpc/routes/mail.ts

[error] 97-97: Expected a semicolon or an implicit semicolon after a statement, but found none. Try inserting a semicolon here.

apps/mail/components/context/thread-context.tsx

[error] 148-216: Identifier optimisticToggleImportant has already been declared. It cannot be redeclared here.

@cursor
Copy link

cursor bot commented Jul 15, 2025

🚨 BugBot couldn't run

Something went wrong. Try again by commenting "bugbot run", or contact support (requestId: serverGenReqId_afd9af9b-56b9-49e0-ba82-1c3748845e32).

Copy link
Collaborator

MrgSub commented Jul 17, 2025

hey @retrogtx can we use the new this.queue? they released it yesterday cloudflare/agents@e48e5f9#diff-75013b5dc015c5b00a1bebcd93e7c62ac825fe7d590f7ce5e3176399986cd92fR900-R920

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

♻️ Duplicate comments (4)
apps/server/src/lib/driver/google.ts (2)

32-47: Add 'SNOOZED' to system label IDs as previously suggested.

The system label IDs set is still missing 'SNOOZED', which was flagged in previous reviews. This omission will cause unnecessary API calls for the snoozed folder functionality.

Apply this diff to add the missing label:

 private readonly systemLabelIds = new Set<string>([
   'INBOX',
   'TRASH',
   'SPAM',
   'DRAFT',
   'SENT',
   'STARRED',
   'UNREAD',
   'IMPORTANT',
   'CATEGORY_PERSONAL',
   'CATEGORY_SOCIAL',
   'CATEGORY_UPDATES',
   'CATEGORY_FORUMS',
   'CATEGORY_PROMOTIONS',
   'MUTED',
+  'SNOOZED',
 ]);

1389-1419: Fix optional chaining issue and improve label resolution logic.

The static analysis correctly identifies an optional chaining issue. Additionally, the label name prettification could be enhanced to handle multi-word labels better.

Apply this diff to address the issues:

 private async resolveLabelId(labelName: string): Promise<string> {
-  if (this.systemLabelIds.has(labelName)) {
+  if (this.systemLabelIds.has(labelName) || labelName === 'SNOOZED') {
     return labelName;
   }

   if (this.labelIdCache[labelName]) {
     return this.labelIdCache[labelName];
   }

   const userLabels = await this.getUserLabels();
   const existing = userLabels.find(
-    (l) => l.name?.toLowerCase() === labelName.toLowerCase(),
+    (l) => l?.name?.toLowerCase() === labelName.toLowerCase(),
   );
   if (existing && existing.id) {
     this.labelIdCache[labelName] = existing.id;
     return existing.id;
   }
-  const prettifiedName = labelName.charAt(0).toUpperCase() + labelName.slice(1).toLowerCase();
+  const prettifiedName = labelName
+    .split(/[_-]/)
+    .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
+    .join(' ');
   await this.createLabel({ name: prettifiedName });

   const refreshedLabels = await this.getUserLabels();
   const created = refreshedLabels.find(
-    (l) => l.name?.toLowerCase() === prettifiedName.toLowerCase(),
+    (l) => l?.name?.toLowerCase() === prettifiedName.toLowerCase(),
   );
   if (!created || !created.id) {
     throw new Error(`Failed to create or retrieve Gmail label '${labelName}'.`);
   }

   this.labelIdCache[labelName] = created.id;
   return created.id;
 }
apps/server/src/trpc/routes/mail.ts (2)

108-143: Improve error handling for KV store operations and thread filtering.

The snoozed folder handling implementation needs better error handling as suggested in previous reviews. The current implementation keeps failed threads in the list and doesn't validate KV namespace existence.

Apply this diff to improve error handling:

 if (folder === FOLDERS.SNOOZED) {
+  if (!env.snoozed_emails) {
+    console.error('[SNOOZED] KV namespace not configured');
+    return threadsResponse;
+  }
+  
   const nowTs = Date.now();
   const filtered: ThreadItem[] = [];

   await Promise.all(
     threadsResponse.threads.map(async (t: ThreadItem) => {
       const keyName = `${t.id}__${activeConnection.id}`;
       try {
         const wakeAtIso = await env.snoozed_emails.get(keyName);
         if (!wakeAtIso) {
-          filtered.push(t);
+          console.warn('[SNOOZED] Thread without wake time:', t.id);
           return;
         }

         const wakeAt = new Date(wakeAtIso).getTime();
         if (wakeAt > nowTs) {
           filtered.push(t);
           return;
         }

         console.log('[UNSNOOZE_ON_ACCESS] Expired thread', t.id, {
           wakeAtIso,
           now: new Date(nowTs).toISOString(),
         });

         await agent.modifyLabels([t.id], ['INBOX'], ['SNOOZED']);
         await env.snoozed_emails.delete(keyName);
       } catch (error) {
         console.error('[UNSNOOZE_ON_ACCESS] Failed for', t.id, error);
-        filtered.push(t);
+        // Don't show threads that failed to process
       }
     }),
   );

446-473: Add date validation and improve atomicity for snooze operation.

The snooze mutation lacks input validation and could result in partial failures leaving the system in an inconsistent state.

Apply this diff to add validation and improve atomicity:

 snoozeThreads: activeDriverProcedure
   .input(
     z.object({
       ids: z.string().array(),
-      wakeAt: z.string(),
+      wakeAt: z.string().refine((val) => {
+        const date = new Date(val);
+        return !isNaN(date.getTime()) && date > new Date();
+      }, 'Wake time must be a valid future date'),
     }),
   )
   .mutation(async ({ input, ctx }) => {
     const { activeConnection } = ctx;
     const agent = await getZeroAgent(activeConnection.id);

     if (!input.ids.length) {
       return { success: false, error: 'No thread IDs provided' };
     }

-    await agent.modifyLabels(input.ids, ['SNOOZED'], ['INBOX']);
-
-    const wakeAtIso = new Date(input.wakeAt).toISOString();
-    await Promise.all(
-      input.ids.map((threadId) =>
-        env.snoozed_emails.put(`${threadId}__${activeConnection.id}`, wakeAtIso, {
-          metadata: { wakeAt: wakeAtIso },
-        }),
-      ),
-    );
+    try {
+      // First, store wake times in KV
+      const wakeAtIso = new Date(input.wakeAt).toISOString();
+      await Promise.all(
+        input.ids.map((threadId) =>
+          env.snoozed_emails.put(`${threadId}__${activeConnection.id}`, wakeAtIso, {
+            metadata: { wakeAt: wakeAtIso },
+          }),
+        ),
+      );
+      
+      // Then modify labels
+      await agent.modifyLabels(input.ids, ['SNOOZED'], ['INBOX']);
+    } catch (error) {
+      // Cleanup KV entries on failure
+      await Promise.allSettled(
+        input.ids.map((threadId) =>
+          env.snoozed_emails.delete(`${threadId}__${activeConnection.id}`),
+        ),
+      );
+      throw error;
+    }

     return { success: true };
   }),
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 66d59e4 and fc4412e.

📒 Files selected for processing (5)
  • apps/mail/messages/en.json (1 hunks)
  • apps/server/src/lib/driver/google.ts (5 hunks)
  • apps/server/src/main.ts (3 hunks)
  • apps/server/src/trpc/routes/mail.ts (3 hunks)
  • apps/server/wrangler.jsonc (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/mail/messages/en.json
  • apps/server/wrangler.jsonc
  • apps/server/src/main.ts
🧰 Additional context used
🧠 Learnings (2)
apps/server/src/trpc/routes/mail.ts (5)
Learnt from: retrogtx
PR: Mail-0/Zero#1468
File: apps/server/src/trpc/routes/mail.ts:386-391
Timestamp: 2025-06-27T04:59:29.731Z
Learning: In apps/server/src/trpc/routes/mail.ts, the attachment processing logic conditionally handles mixed attachment types - it preserves existing File-like objects with arrayBuffer methods while only converting serialized attachments that need processing through toAttachmentFiles.
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#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.
Learnt from: retrogtx
PR: Mail-0/Zero#1622
File: apps/server/src/lib/email-verification.ts:189-189
Timestamp: 2025-07-05T05:27:24.623Z
Learning: During testing phases, debug logging should be kept active in apps/server/src/lib/email-verification.ts for BIMI validation and email verification debugging, even if it's verbose.
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/driver/google.ts (2)
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.
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.
🧬 Code Graph Analysis (1)
apps/server/src/trpc/routes/mail.ts (3)
apps/mail/lib/utils.ts (1)
  • FOLDERS (10-18)
apps/server/src/trpc/trpc.ts (1)
  • activeDriverProcedure (43-77)
apps/server/src/lib/server-utils.ts (1)
  • getZeroAgent (13-18)
🪛 Biome (1.9.4)
apps/server/src/lib/driver/google.ts

[error] 1402-1402: Change to an optional chain.

Unsafe fix: Change to an optional chain.

(lint/complexity/useOptionalChain)

🔇 Additional comments (4)
apps/server/src/lib/driver/google.ts (3)

528-553: LGTM! Method signature flexibility enhances usability.

The refactored modifyLabels method signature now supports both object-based and array-based inputs, making it more flexible for different use cases while maintaining backward compatibility.


947-951: Improved error handling with detailed failure information.

The enhanced error handling now throws detailed error messages on label modification failures instead of silently continuing, which improves debugging and reliability.


967-970: Correct folder mapping for snoozed emails.

The addition of snoozed folder support with proper Gmail label mapping (label:Snoozed) aligns with the snooze feature requirements.

apps/server/src/trpc/routes/mail.ts (1)

82-106: Thread listing refactor is syntactically correct and introduces no duplicate labelIds issues.

No errors were found in the snippet at apps/server/src/trpc/routes/mail.ts (lines 82–106); the previous TypeScript errors stem from missing project-wide type declarations rather than this refactor.

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

🧹 Nitpick comments (1)
apps/server/src/routes/agent/index.ts (1)

1076-1092: Verify error handling completeness and consider adding validation.

The unsnoozeThreadsHandler implementation looks solid with proper async/await usage and error logging. However, consider the following improvements:

  1. Input validation: The method doesn't validate that connectionId is provided or non-empty
  2. Partial failure handling: If modifyLabels succeeds but KV deletion fails, the threads will be unnoozed but cleanup won't complete
  3. Authentication timing: setupAuth is called even when there are no threadIds to process

Consider adding input validation and improving error handling:

 async unsnoozeThreadsHandler(payload: ISnoozeBatch) {
   const { connectionId, threadIds, keyNames } = payload;
+  
+  if (!connectionId) {
+    throw new Error('connectionId is required');
+  }
+  
+  if (!threadIds.length && !keyNames.length) {
+    console.log('[AGENT][unsnoozeThreadsHandler] No threads or keys to process');
+    return;
+  }
+  
   try {
-    await this.setupAuth(connectionId);
+    if (threadIds.length) {
+      await this.setupAuth(connectionId);
+      await this.modifyLabels(threadIds, ['INBOX'], ['SNOOZED']);
+    }
 
-    if (threadIds.length) {
-      await this.modifyLabels(threadIds, ['INBOX'], ['SNOOZED']);
-    }
-
     if (keyNames.length) {
       await Promise.all(keyNames.map((k: string) => env.snoozed_emails.delete(k)));
     }
   } catch (error) {
     console.error('[AGENT][unsnoozeThreadsHandler] Failed', { connectionId, threadIds, error });
     throw error;
   }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between fc4412e and 8ef3c4e.

📒 Files selected for processing (3)
  • apps/server/src/main.ts (2 hunks)
  • apps/server/src/routes/agent/index.ts (2 hunks)
  • apps/server/src/routes/agent/rpc.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/server/src/main.ts
🧰 Additional context used
🧠 Learnings (1)
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/routes/agent/index.ts (1)
apps/server/src/types.ts (1)
  • ISnoozeBatch (21-25)
🔇 Additional comments (1)
apps/server/src/routes/agent/index.ts (1)

30-30: LGTM: Import addition is clean and well-placed.

The import of ISnoozeBatch type is correctly added alongside other type imports from the types module.

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

♻️ Duplicate comments (2)
apps/server/src/trpc/routes/mail.ts (2)

108-143: Add KV store validation and improve error handling for snoozed threads.

The snoozed folder logic lacks proper validation and has suboptimal error handling:

Apply this diff to address the issues:

       if (folder === FOLDERS.SNOOZED) {
+        if (!env.snoozed_emails) {
+          console.error('[SNOOZED] KV namespace not configured');
+          return threadsResponse;
+        }
+        
         const nowTs = Date.now();
         const filtered: ThreadItem[] = [];

         await Promise.all(
           threadsResponse.threads.map(async (t: ThreadItem) => {
             const keyName = `${t.id}__${activeConnection.id}`;
             try {
               const wakeAtIso = await env.snoozed_emails.get(keyName);
               if (!wakeAtIso) {
-                filtered.push(t);
+                // Thread without wake time shouldn't be in snoozed folder
+                console.warn('[SNOOZED] Thread without wake time:', t.id);
                 return;
               }

               const wakeAt = new Date(wakeAtIso).getTime();
               if (wakeAt > nowTs) {
                 filtered.push(t);
                 return;
               }

               console.log('[UNSNOOZE_ON_ACCESS] Expired thread', t.id, {
                 wakeAtIso,
                 now: new Date(nowTs).toISOString(),
               });

               await agent.modifyLabels([t.id], ['INBOX'], ['SNOOZED']);
               await env.snoozed_emails.delete(keyName);
             } catch (error) {
               console.error('[UNSNOOZE_ON_ACCESS] Failed for', t.id, error);
-              filtered.push(t);
+              // Don't show threads that failed to process
             }
           }),
         );

446-473: Add input validation and improve transaction atomicity.

The mutation has several critical issues that need to be addressed:

Apply this diff to add proper validation and improve atomicity:

 snoozeThreads: activeDriverProcedure
   .input(
     z.object({
       ids: z.string().array(),
-      wakeAt: z.string(),
+      wakeAt: z.string().refine((val) => {
+        const date = new Date(val);
+        return !isNaN(date.getTime()) && date > new Date();
+      }, 'Wake time must be a valid future date'),
     }),
   )
   .mutation(async ({ input, ctx }) => {
     const { activeConnection } = ctx;
     const agent = await getZeroAgent(activeConnection.id);

     if (!input.ids.length) {
       return { success: false, error: 'No thread IDs provided' };
     }

-    await agent.modifyLabels(input.ids, ['SNOOZED'], ['INBOX']);
-
-    const wakeAtIso = new Date(input.wakeAt).toISOString();
-    await Promise.all(
-      input.ids.map((threadId) =>
-        env.snoozed_emails.put(`${threadId}__${activeConnection.id}`, wakeAtIso, {
-          metadata: { wakeAt: wakeAtIso },
-        }),
-      ),
-    );
+    try {
+      // First, store wake times in KV
+      const wakeAtIso = new Date(input.wakeAt).toISOString();
+      await Promise.all(
+        input.ids.map((threadId) =>
+          env.snoozed_emails.put(`${threadId}__${activeConnection.id}`, wakeAtIso, {
+            metadata: { wakeAt: wakeAtIso },
+          }),
+        ),
+      );
+      
+      // Then modify labels
+      await agent.modifyLabels(input.ids, ['SNOOZED'], ['INBOX']);
+    } catch (error) {
+      // Cleanup KV entries on failure
+      await Promise.allSettled(
+        input.ids.map((threadId) =>
+          env.snoozed_emails.delete(`${threadId}__${activeConnection.id}`),
+        ),
+      );
+      throw error;
+    }

     return { success: true };
   }),
🧹 Nitpick comments (1)
apps/server/src/trpc/routes/mail.ts (1)

12-12: Consider using the Cloudflare queue feature for better reliability.

Based on the PR comment from MrgSub, consider leveraging the newly released this.queue feature for handling snooze operations, which could provide better reliability and error handling for the snooze/unsnooze workflow.

The current implementation directly manipulates labels and KV store, but using a queue-based approach could:

  • Provide better retry mechanisms for failed operations
  • Enable more robust transaction handling
  • Allow for better monitoring and debugging of snooze operations

Would you like to explore integrating the queue-based approach for this feature?

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 8ef3c4e and ac70745.

📒 Files selected for processing (5)
  • apps/mail/components/context/thread-context.tsx (10 hunks)
  • apps/server/src/routes/agent/index.ts (3 hunks)
  • apps/server/src/routes/agent/rpc.ts (2 hunks)
  • apps/server/src/routes/agent/types.ts (1 hunks)
  • apps/server/src/trpc/routes/mail.ts (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/server/src/routes/agent/types.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/server/src/routes/agent/rpc.ts
  • apps/mail/components/context/thread-context.tsx
  • apps/server/src/routes/agent/index.ts
🧰 Additional context used
🧠 Learnings (1)
apps/server/src/trpc/routes/mail.ts (5)
Learnt from: retrogtx
PR: Mail-0/Zero#1468
File: apps/server/src/trpc/routes/mail.ts:386-391
Timestamp: 2025-06-27T04:59:29.731Z
Learning: In apps/server/src/trpc/routes/mail.ts, the attachment processing logic conditionally handles mixed attachment types - it preserves existing File-like objects with arrayBuffer methods while only converting serialized attachments that need processing through toAttachmentFiles.
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#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.
Learnt from: retrogtx
PR: Mail-0/Zero#1622
File: apps/server/src/lib/email-verification.ts:189-189
Timestamp: 2025-07-05T05:27:24.623Z
Learning: During testing phases, debug logging should be kept active in apps/server/src/lib/email-verification.ts for BIMI validation and email verification debugging, even if it's verbose.
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.

Co-authored-by: graphite-app[bot] <96075541+graphite-app[bot]@users.noreply.github.com>
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

♻️ Duplicate comments (2)
apps/server/src/trpc/routes/mail.ts (2)

113-148: Add KV namespace validation and improve error handling.

The SNOOZED folder logic looks good, but consider these improvements:

  1. KV namespace validation: Check if env.snoozed_emails exists before using it
  2. Error handling: Currently on KV failures, threads remain in the filtered list which might show expired threads to users
 if (folder === FOLDERS.SNOOZED) {
+  if (!env.snoozed_emails) {
+    console.error('[SNOOZED] KV namespace not configured');
+    return threadsResponse;
+  }
+  
   const nowTs = Date.now();
   const filtered: ThreadItem[] = [];

   await Promise.all(
     threadsResponse.threads.map(async (t: ThreadItem) => {
       const keyName = `${t.id}__${activeConnection.id}`;
       try {
         const wakeAtIso = await env.snoozed_emails.get(keyName);
         if (!wakeAtIso) {
-          filtered.push(t);
+          // Thread without wake time shouldn't be in snoozed folder
+          console.warn('[SNOOZED] Thread without wake time:', t.id);
           return;
         }

         const wakeAt = new Date(wakeAtIso).getTime();
         if (wakeAt > nowTs) {
           filtered.push(t);
           return;
         }

         console.log('[UNSNOOZE_ON_ACCESS] Expired thread', t.id, {
           wakeAtIso,
           now: new Date(nowTs).toISOString(),
         });

         await agent.modifyLabels([t.id], ['INBOX'], ['SNOOZED']);
         await env.snoozed_emails.delete(keyName);
       } catch (error) {
         console.error('[UNSNOOZE_ON_ACCESS] Failed for', t.id, error);
-        filtered.push(t);
+        // Don't show threads that failed to process
       }
     }),
   );

484-500: Remove redundant validation and add KV namespace check.

The Zod schema already ensures a non-empty array, making the runtime check redundant. Also consider adding KV validation for consistency.

 unsnoozeThreads: activeDriverProcedure
   .input(
     z.object({
-      ids: z.array(z.string().min(1)).nonempty(),
+      ids: z.string().array().min(1, 'At least one thread ID is required'),
     }),
   )
   .mutation(async ({ input, ctx }) => {
     const { activeConnection } = ctx;
     const agent = await getZeroAgent(activeConnection.id);
-    if (!input.ids.length) return { success: false, error: 'No thread IDs' };
+    
+    if (!env.snoozed_emails) {
+      return { success: false, error: 'Snoozed emails KV store not configured' };
+    }
+    
     await agent.modifyLabels(input.ids, ['INBOX'], ['SNOOZED']);

     await Promise.all(
       input.ids.map((threadId) => env.snoozed_emails.delete(`${threadId}__${activeConnection.id}`)),
     );
     
     return { success: true };
   }),

The runtime length check is unnecessary since Zod's min(1) already prevents empty arrays from reaching the mutation handler.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between c8994d2 and 79219b2.

📒 Files selected for processing (1)
  • apps/server/src/trpc/routes/mail.ts (5 hunks)
🧰 Additional context used
🧠 Learnings (1)
apps/server/src/trpc/routes/mail.ts (6)
Learnt from: retrogtx
PR: Mail-0/Zero#1468
File: apps/server/src/trpc/routes/mail.ts:386-391
Timestamp: 2025-06-27T04:59:29.731Z
Learning: In apps/server/src/trpc/routes/mail.ts, the attachment processing logic conditionally handles mixed attachment types - it preserves existing File-like objects with arrayBuffer methods while only converting serialized attachments that need processing through toAttachmentFiles.
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#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.
Learnt from: retrogtx
PR: Mail-0/Zero#1622
File: apps/server/src/lib/email-verification.ts:189-189
Timestamp: 2025-07-05T05:27:24.623Z
Learning: During testing phases, debug logging should be kept active in apps/server/src/lib/email-verification.ts for BIMI validation and email verification debugging, even if it's verbose.
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: danteissaias
PR: Mail-0/Zero#618
File: apps/mail/components/mail/mail-iframe.tsx:12-12
Timestamp: 2025-04-07T20:46:11.697Z
Learning: In the Mail-0/Zero application, sender emails are guaranteed to be non-empty when passed to components that handle them, making additional empty string validation unnecessary.
🧬 Code Graph Analysis (1)
apps/server/src/trpc/routes/mail.ts (5)
apps/server/src/lib/driver/types.ts (2)
  • IGetThreadsResponseSchema (126-135)
  • IGetThreadsResponse (121-124)
apps/mail/lib/utils.ts (1)
  • FOLDERS (10-18)
apps/server/src/lib/utils.ts (1)
  • FOLDERS (43-51)
apps/server/src/trpc/trpc.ts (1)
  • activeDriverProcedure (43-77)
apps/server/src/lib/server-utils.ts (1)
  • getZeroAgent (13-18)
🔇 Additional comments (1)
apps/server/src/trpc/routes/mail.ts (1)

3-7: LGTM on import additions.

The new imports for thread response types and Cloudflare Workers environment are necessary for the snooze functionality and follow the existing import patterns.

Also applies to: 16-16

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

🧹 Nitpick comments (1)
apps/server/src/routes/agent/index.ts (1)

212-324: WebSocket message handling implementation is comprehensive.

The implementation properly handles various message types with good error handling and abort signal support. The commented-out code sections appear to be legacy handlers that have been moved elsewhere.

Consider adding a fallback error response in case tryCatchChat throws an exception to ensure clients always receive a response.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 5e0c09b and 049b168.

📒 Files selected for processing (5)
  • apps/server/src/main.ts (2 hunks)
  • apps/server/src/pipelines.effect.ts (1 hunks)
  • apps/server/src/routes/agent/index.ts (6 hunks)
  • apps/server/src/routes/agent/rpc.ts (1 hunks)
  • apps/server/wrangler.jsonc (4 hunks)
✅ Files skipped from review due to trivial changes (1)
  • apps/server/src/pipelines.effect.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • apps/server/wrangler.jsonc
  • apps/server/src/routes/agent/rpc.ts
  • apps/server/src/main.ts
🧰 Additional context used
🧠 Learnings (1)
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/routes/agent/index.ts (3)
apps/server/src/routes/agent/types.ts (3)
  • QueueFunc (73-73)
  • OutgoingMessage (50-71)
  • IncomingMessage (20-48)
apps/server/src/lib/driver/types.ts (1)
  • IGetThreadsResponse (121-124)
apps/server/src/types.ts (1)
  • ISnoozeBatch (21-25)
🪛 Biome (1.9.4)
apps/server/src/routes/agent/index.ts

[error] 357-357: Don't use '{}' as a type.

Prefer explicitly define the object shape. '{}' means "any non-nullable value".

(lint/complexity/noBannedTypes)

🔇 Additional comments (7)
apps/server/src/routes/agent/index.ts (7)

30-35: Import additions look good.

The new imports align with the snooze functionality and typed queue implementation.

Also applies to: 55-55


326-347: Streaming response implementation is correct.

The method properly handles streaming responses by decoding chunks and broadcasting them to clients, with appropriate completion signaling.


349-354: Proper cleanup of abort controllers.

The method correctly aborts all pending controllers and clears the map to prevent memory leaks.


365-389: Return type annotations improve type safety.

The explicit return type annotations and delegation pattern in listThreads are good improvements that enhance type safety and reduce code duplication.


994-1010: Unsnooze handler implementation is well-structured.

The method properly handles batch unsnoozing with appropriate label modifications and KV store cleanup. Good error handling and logging for debugging purposes.


173-210: Helper methods implementation looks solid.

  • The chat helper methods provide clear abstractions for error handling, request cancellation, and message broadcasting.
  • The defensive type check in getAbortSignal is a good practice.
  • Verified that chatMessageAbortControllers is declared as a class property in ZeroDriver at line 1034:
    private chatMessageAbortControllers: Map<string, AbortController> = new Map();

All concerns addressed—approving these changes.


64-66: Verify Durable Object queue binding and implementation

The queue property in ZeroDriver is still a placeholder that throws an error. To use Cloudflare’s new Durable Object queue feature, please:

  • Ensure you have a [[queues]] block in your Wrangler configuration targeting your ZeroAgent Durable Object.

  • Update the implementation in apps/server/src/routes/agent/index.ts (lines 64–66) to use state.queue:

    // before
    queue: QueueFunc = async () => {
      throw new Error('queue method not implemented');
    };
    
    // after
    queue: QueueFunc = async (name, payload) => {
      const q = this.state.queue(name);
      await q.send(payload);
    };
  • Verify that the name parameter matches the queue binding name in your Wrangler config.

Please confirm your Wrangler setup and that this implementation aligns with your queue binding.

const nowTs = Date.now();
const filtered: ThreadItem[] = [];

await Promise.all(
Copy link
Collaborator

Choose a reason for hiding this comment

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

do we need to do this on every listThreads?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

this check opens up only when you open the snooze folder not the core mailbox request

Copy link
Collaborator

MrgSub commented Jul 20, 2025

Merge activity

  • Jul 20, 7:47 PM UTC: A user started a stack merge that includes this pull request via Graphite.
  • Jul 20, 7:47 PM UTC: Graphite couldn't merge this PR because it failed for an unknown reason (Stack merges are not currently supported for forked repositories. Please create a branch in the target repository in order to merge).

@MrgSub MrgSub merged commit 4c3753e into Mail-0:staging Jul 21, 2025
1 of 2 checks passed
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: Error Handling Fails to Extract Thread ID

The error handling for modifyLabels incorrectly attempts to extract threadId from rejected Promise.allSettled results. These results only contain status: 'rejected' and reason, leading to threadId: undefined in the error message and hindering debugging.

apps/server/src/lib/driver/google.ts#L960-L966

if (failures.length > 0) {
const failureReasons = failures.map((f) => ({ threadId: f.threadId, reason: f.reason }));
const first = failureReasons[0];
throw new Error(
`Failed to modify labels for thread ${first.threadId}: ${JSON.stringify(first.reason)}`,
);
}

Fix in CursorFix in Web


Bug: Snoozed Emails Stored Inconsistently

Snoozed email wake times are stored inconsistently: the snoozeThreads mutation writes the wakeAt time to both the KV value and its metadata, but the listThreads query for the snoozed folder reads only from the KV value. This inconsistency causes threads with the SNOOZED label but a missing KV value to be incorrectly displayed in the snoozed folder.

apps/server/src/trpc/routes/mail.ts#L120-L124

try {
const wakeAtIso = await env.snoozed_emails.get(keyName);
if (!wakeAtIso) {
filtered.push(t);
return;

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 👎

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