feat: ability to snooze emails#1477
Conversation
- 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.
|
Caution Review failedThe pull request is closed. WalkthroughThis 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
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
Possibly related PRs
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (2)
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
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
📒 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 syncThe
snoozed_emailsKVNamespace entry is well-typed.
Just make sure every environment section inwrangler.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 updatedIncluding
'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 – niceAdding
fill="var(--icon-color)"&fillOpacity="0.5"to theClockpath 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:
SNOOZEincludes boththreadIdsandwakeAttimestamp for schedulingUNSNOOZEincludes onlythreadIdsas expected for the simpler operationapps/server/src/lib/schemas.ts (2)
124-124: LGTM: Improved user settings schema with sensible default.Adding a default empty string for
customPromptmakes the field optional while maintaining backward compatibility. This aligns well with thedefaultUserSettingsobject.
31-31: ```shell
#!/bin/bashCheck 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/driverecho; echo "Searching for attachment usage in Google driver..."
rg -n "attachment" -C 5 apps/server/src/lib/driver/google.tsecho; 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"
There was a problem hiding this comment.
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_emailsdirectly 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:
- Use optional chaining as suggested by static analysis
- Add 'SNOOZED' to system labels
- 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
📒 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.listThreadssimplifies 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
modifyLabelsmethod 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.
There was a problem hiding this comment.
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_emailsdirectly 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:
- Use optional chaining as suggested by static analysis
- Add 'SNOOZED' to system labels
- 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
📒 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.
🚨 BugBot couldn't runSomething went wrong. Try again by commenting "bugbot run", or contact support (requestId: serverGenReqId_afd9af9b-56b9-49e0-ba82-1c3748845e32). |
…atched label updates for scale
|
hey @retrogtx can we use the new this.queue? they released it yesterday cloudflare/agents@e48e5f9#diff-75013b5dc015c5b00a1bebcd93e7c62ac825fe7d590f7ce5e3176399986cd92fR900-R920 |
There was a problem hiding this comment.
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
📒 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
modifyLabelsmethod 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 duplicatelabelIdsissues.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.
There was a problem hiding this comment.
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
unsnoozeThreadsHandlerimplementation looks solid with proper async/await usage and error logging. However, consider the following improvements:
- Input validation: The method doesn't validate that
connectionIdis provided or non-empty- Partial failure handling: If
modifyLabelssucceeds but KV deletion fails, the threads will be unnoozed but cleanup won't complete- Authentication timing:
setupAuthis called even when there are nothreadIdsto processConsider 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
📒 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
ISnoozeBatchtype is correctly added alongside other type imports from the types module.
There was a problem hiding this comment.
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.queuefeature 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
📒 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>
There was a problem hiding this comment.
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:
- KV namespace validation: Check if
env.snoozed_emailsexists before using it- 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
📒 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
There was a problem hiding this comment.
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
tryCatchChatthrows an exception to ensure clients always receive a response.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 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
listThreadsare 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
getAbortSignalis a good practice.- Verified that
chatMessageAbortControllersis declared as a class property inZeroDriverat line 1034:private chatMessageAbortControllers: Map<string, AbortController> = new Map();All concerns addressed—approving these changes.
64-66: Verify Durable Object queue binding and implementationThe
queueproperty inZeroDriveris 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 yourZeroAgentDurable Object.Update the implementation in
apps/server/src/routes/agent/index.ts(lines 64–66) to usestate.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
nameparameter 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( |
There was a problem hiding this comment.
do we need to do this on every listThreads?
There was a problem hiding this comment.
this check opens up only when you open the snooze folder not the core mailbox request
Merge activity
|
There was a problem hiding this comment.
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
Zero/apps/server/src/lib/driver/google.ts
Lines 960 to 966 in cbc222d
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
Zero/apps/server/src/trpc/routes/mail.ts
Lines 120 to 124 in cbc222d
BugBot free trial expires on July 31, 2025
Learn more in the Cursor dashboard.
Was this report helpful? Give feedback by reacting with 👍 or 👎
you can now snooze emails
snoozing.mp4
Summary by CodeRabbit
New Features
Bug Fixes
Style
Documentation
Chores