Skip to content

Comments

Add email syncing status indicators and optimize folder synchronization#1915

Merged
MrgSub merged 1 commit intostagingfrom
ZEROAdd_email_syncing_status_indicators_and_optimize_folder_synchronization
Aug 4, 2025
Merged

Add email syncing status indicators and optimize folder synchronization#1915
MrgSub merged 1 commit intostagingfrom
ZEROAdd_email_syncing_status_indicators_and_optimize_folder_synchronization

Conversation

@MrgSub
Copy link
Collaborator

@MrgSub MrgSub commented Aug 4, 2025

Email Syncing Status Indicators

Description

Added real-time email syncing status indicators to the mail UI that show when emails are being synchronized, which folders are currently syncing, and the current storage size. This provides users with better visibility into background processes.

Type of Change

  • ✨ New feature (non-breaking change which adds functionality)
  • ⚡ Performance improvement

Areas Affected

  • Email Integration (Gmail, IMAP, etc.)
  • User Interface/Experience

Testing Done

  • Manual testing performed

Checklist

  • I have performed a self-review of my code
  • My changes generate no new warnings

Additional Notes

This PR implements a state management system for email synchronization status using Jotai atoms. The server now broadcasts syncing status through Party, and the UI displays this information in a non-intrusive way at the top of the mail interface.

Key changes:

  • Created a new useDoState hook to manage syncing state
  • Added status indicators in the mail layout component
  • Modified the server to track and broadcast syncing status
  • Improved folder synchronization logic to be more efficient
  • Removed unnecessary delays in the synchronization process

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

Summary by CodeRabbit

  • New Features

    • Added a real-time syncing status indicator in the mail interface, displaying current sync progress, folders being synced, and storage usage.
    • Introduced live syncing state updates communicated between server and client for improved sync transparency.
  • Improvements

    • Enhanced background synchronization logic to provide clearer feedback on syncing activity.
    • Real-time updates now reflect the latest syncing state without delays.
    • Removed artificial delays in syncing processes for faster synchronization.
    • Triggered folder syncing asynchronously when fetching threads from the database.
  • Bug Fixes

    • Removed unused and obsolete code related to database table management and sync rate-limiting.

@jazzberry-ai
Copy link

jazzberry-ai bot commented Aug 4, 2025

Bug Report

Name Severity Example test case Description
Incorrect email sync status Medium 1. Start syncing a folder with a large number of emails. 2. Observe that the UI shows "Synced your emails" relatively quickly after starting the sync. 3. Check for new emails in the folder. If new emails are present on the server but not in the client, then this confirms that the folder is not yet fully synced when the UI indicates that it is. The sendDoState function is called prematurely in syncThreads, before the actual thread syncing is complete. This gives the user a false impression that the folder is synced when it's still in progress.

Comments? Email us.

Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

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

Your free trial has ended. If you'd like to continue receiving code reviews, you can add a payment method here.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 4, 2025

Walkthrough

This update introduces a state management system for mail synchronization, enabling real-time tracking and UI display of sync status, syncing folders, and storage size. The server now broadcasts sync state changes, and the client consumes and renders this information. Several unused fields and artificial sync delays are removed for efficiency.

Changes

Cohort / File(s) Change Summary
Mail Client State & UI
apps/mail/components/mail/mail.tsx, apps/mail/components/mail/use-do-state.ts
Adds a Jotai-based state module and hook to track mail sync status, syncing folders, and storage size. Updates the mail layout to display this state in a new UI element, reflecting real-time sync information.
Notification Handling
apps/mail/components/party.tsx
Extends notification handling to process new Do_State messages, updating the mail sync state in response to server broadcasts.
Server Sync State Tracking & Messaging
apps/server/src/routes/agent/index.ts, apps/server/src/routes/agent/types.ts
Implements explicit sync state tracking and broadcasting in ZeroDriver, adds sendDoState() and isSyncing() methods, updates the outgoing message types, and removes unused code and artificial delays.
Server Utility Change
apps/server/src/lib/server-utils.ts
Removes background folder sync scheduling from getZeroClient, returning the agent immediately after authentication setup.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant MailUI
    participant useDoState
    participant NotificationProvider
    participant Server

    Server->>NotificationProvider: Sends Do_State message (isSyncing, syncingFolders, storageSize)
    NotificationProvider->>useDoState: Update sync state
    useDoState-->>MailUI: Exposes updated state
    MailUI->>User: Displays sync status, folders, and storage size
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

🚀 As emails sync and folders spin,
The state is tracked, the data flows in.
With Jotai’s might and UI’s new light,
Server and client now sync just right.
No more delays, no code to waste—
This is how you optimize at rocket pace!
🌌📧✨

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch ZEROAdd_email_syncing_status_indicators_and_optimize_folder_synchronization

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.
  • 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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Collaborator Author

MrgSub commented Aug 4, 2025

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

@coderabbitai coderabbitai bot added content design Improvements & changes to design & UX labels Aug 4, 2025
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: 4

🔭 Outside diff range comments (1)
apps/mail/components/mail/use-do-state.ts (1)

1-35: This state management is way more complex than it needs to be! 🤔

We can simplify this significantly. Individual setter atoms are overkill here.

 import { atom, useAtom } from 'jotai';
 
 export type State = {
   isSyncing: boolean;
   syncingFolders: string[];
   storageSize: number;
 };
 
 const stateAtom = atom<State>({
   isSyncing: false,
   syncingFolders: [],
   storageSize: 0,
 });
 
-function useDoState() {
-  return useAtom(stateAtom);
-}
-
-const setIsSyncingAtom = atom(null, (get, set, isSyncing: boolean) => {
-  const current = get(stateAtom);
-  set(stateAtom, { ...current, isSyncing });
-});
-
-const setSyncingFoldersAtom = atom(null, (get, set, syncingFolders: string[]) => {
-  const current = get(stateAtom);
-  set(stateAtom, { ...current, syncingFolders });
-});
-
-const setStorageSizeAtom = atom(null, (get, set, storageSize: number) => {
-  const current = get(stateAtom);
-  set(stateAtom, { ...current, storageSize });
-});
-
-export { setIsSyncingAtom, setSyncingFoldersAtom, setStorageSizeAtom, useDoState };
+export function useDoState() {
+  return useAtom(stateAtom);
+}

The hook already returns a setter that can handle partial updates. No need for individual setter atoms!

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 01e2adf and f8af7d4.

📒 Files selected for processing (6)
  • apps/mail/components/mail/mail.tsx (3 hunks)
  • apps/mail/components/mail/use-do-state.ts (1 hunks)
  • apps/mail/components/party.tsx (4 hunks)
  • apps/server/src/lib/server-utils.ts (0 hunks)
  • apps/server/src/routes/agent/index.ts (9 hunks)
  • apps/server/src/routes/agent/types.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • apps/server/src/lib/server-utils.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (AGENT.md)

**/*.{js,jsx,ts,tsx}: Use 2-space indentation
Use single quotes for strings
Limit lines to 100 characters in length
Semicolons are required at the end of statements

Files:

  • apps/mail/components/party.tsx
  • apps/mail/components/mail/use-do-state.ts
  • apps/server/src/routes/agent/types.ts
  • apps/mail/components/mail/mail.tsx
  • apps/server/src/routes/agent/index.ts
**/*.{js,jsx,ts,tsx,css,scss}

📄 CodeRabbit Inference Engine (AGENT.md)

Use Prettier with sort-imports and Tailwind plugins for code formatting

Files:

  • apps/mail/components/party.tsx
  • apps/mail/components/mail/use-do-state.ts
  • apps/server/src/routes/agent/types.ts
  • apps/mail/components/mail/mail.tsx
  • apps/server/src/routes/agent/index.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (AGENT.md)

Enable TypeScript strict mode

Files:

  • apps/mail/components/party.tsx
  • apps/mail/components/mail/use-do-state.ts
  • apps/server/src/routes/agent/types.ts
  • apps/mail/components/mail/mail.tsx
  • apps/server/src/routes/agent/index.ts
**/*.{css,js,ts,jsx,tsx,mdx}

📄 CodeRabbit Inference Engine (.cursor/rules/tailwind-css-v4.mdc)

**/*.{css,js,ts,jsx,tsx,mdx}: Chain variants together for composable variants (e.g., group-has-data-potato:opacity-100).
Use new variants such as starting, not-*, inert, nth-*, in-*, open (for :popover-open), and ** for all descendants.
Do not use deprecated utilities like bg-opacity-*, text-opacity-*, border-opacity-*, and divide-opacity-*; use the new syntax (e.g., bg-black/50).
Use renamed utilities: shadow-sm is now shadow-xs, shadow is now shadow-sm, drop-shadow-sm is now drop-shadow-xs, drop-shadow is now drop-shadow-sm, blur-sm is now blur-xs, blur is now blur-sm, rounded-sm is now rounded-xs, rounded is now rounded-sm, outline-none is now outline-hidden.
Use bg-(--brand-color) syntax for CSS variables in arbitrary values instead of bg-[--brand-color].
Stacked variants now apply left-to-right instead of right-to-left.

Files:

  • apps/mail/components/party.tsx
  • apps/mail/components/mail/use-do-state.ts
  • apps/server/src/routes/agent/types.ts
  • apps/mail/components/mail/mail.tsx
  • apps/server/src/routes/agent/index.ts
🧠 Learnings (3)
📚 Learning: in apps/server/src/lib/driver/google.ts, the normalization of "draft" to "drafts" in the count() met...
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.

Applied to files:

  • apps/mail/components/party.tsx
  • apps/mail/components/mail/mail.tsx
  • apps/server/src/routes/agent/index.ts
📚 Learning: in apps/mail/lib/hotkeys/mail-list-hotkeys.tsx, the switchcategorybyindex function using hardcoded i...
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.

Applied to files:

  • apps/mail/components/party.tsx
  • apps/mail/components/mail/mail.tsx
📚 Learning: in react hook form, avoid using useeffect for form state synchronization when the values prop can ha...
Learnt from: retrogtx
PR: Mail-0/Zero#1354
File: apps/mail/components/ui/prompts-dialog.tsx:85-88
Timestamp: 2025-06-20T05:03:16.944Z
Learning: In React Hook Form, avoid using useEffect for form state synchronization when the values prop can handle reactive updates automatically. The values prop is specifically designed for this purpose and is more optimal than manual useEffect-based synchronization.

Applied to files:

  • apps/mail/components/mail/mail.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (2)
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (9)
apps/mail/components/party.tsx (2)

7-7: Import looks solid! 🚀

Clean import following the single quote convention. No issues here.


19-19: Enum addition is perfect! 💯

The naming convention matches the existing pattern. Good alignment with server-side message types.

apps/mail/components/mail/mail.tsx (2)

33-33: Import is good to go! ✅

Follows the coding standards perfectly.


329-329: State hook usage is spot on! 🎯

Clean destructuring of the sync state.

apps/server/src/routes/agent/types.ts (1)

19-19: Enum addition is clean! 🚀

Perfect symmetry with the client-side message type.

apps/server/src/routes/agent/index.ts (4)

319-324: Clean implementation of sync status tracking! ✨

Efficient use of Map filtering and array transformation.


1104-1104: Perfect placement of state broadcasts! 🎯

Broadcasting at all the right lifecycle points - when sync starts, when it's already in progress, and when it completes. Effect handling is spot on.

Also applies to: 1150-1150, 1266-1266, 1293-1293


1576-1576: Smart background sync trigger! 🚀

Great optimization - triggering folder sync in the background when threads are accessed keeps the data fresh without blocking the request.


1469-1485: Excellent defensive programming! 🛡️

Smart move capping labels at 5 and deduplicating. This prevents potential resource exhaustion from malicious requests with excessive labels.

Comment on lines +399 to +407
<div className="fixed right-1 top-1 z-10 flex w-full justify-end">
<p className="w-fit rounded bg-purple-800 p-1 text-xs">
{isSyncing ? 'Syncing your emails...' : 'Synced your emails'}
</p>
{storageSize && <p className="w-fit rounded bg-purple-800 p-1 text-xs">{storageSize}</p>}
{syncingFolders.length > 0 && (
<p className="w-fit rounded bg-purple-800 p-1 text-xs">{syncingFolders.join(', ')}</p>
)}
</div>
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

This UI needs some serious refactoring! 🔧

Multiple issues here that need addressing for production quality.

-      <div className="fixed right-1 top-1 z-10 flex w-full justify-end">
-        <p className="w-fit rounded bg-purple-800 p-1 text-xs">
-          {isSyncing ? 'Syncing your emails...' : 'Synced your emails'}
-        </p>
-        {storageSize && <p className="w-fit rounded bg-purple-800 p-1 text-xs">{storageSize}</p>}
-        {syncingFolders.length > 0 && (
-          <p className="w-fit rounded bg-purple-800 p-1 text-xs">{syncingFolders.join(', ')}</p>
-        )}
-      </div>
+      {(isSyncing || storageSize > 0 || syncingFolders.length > 0) && (
+        <div className="fixed right-2 top-2 z-50 flex flex-col gap-1 md:flex-row md:gap-2" role="status" aria-live="polite">
+          <div className="flex items-center gap-1 rounded-md bg-purple-800/90 px-2 py-1 text-xs text-white shadow-sm">
+            {isSyncing ? (
+              <>
+                <RefreshCcw className="h-3 w-3 animate-spin" />
+                <span>Syncing emails...</span>
+              </>
+            ) : (
+              <span>✓ Synced</span>
+            )}
+          </div>
+          {storageSize > 0 && (
+            <div className="rounded-md bg-purple-800/90 px-2 py-1 text-xs text-white shadow-sm">
+              {formatBytes(storageSize)}
+            </div>
+          )}
+          {syncingFolders.length > 0 && (
+            <div className="max-w-[200px] truncate rounded-md bg-purple-800/90 px-2 py-1 text-xs text-white shadow-sm" 
+                 title={syncingFolders.join(', ')}>
+              {syncingFolders.join(', ')}
+            </div>
+          )}
+        </div>
+      )}

Also need to add a formatBytes utility function to properly display storage size.

Committable suggestion skipped: line range outside the PR's diff.

🤖 Prompt for AI Agents
In apps/mail/components/mail/mail.tsx around lines 399 to 407, the UI code for
displaying syncing status, storage size, and syncing folders is cluttered and
repetitive. Refactor by extracting repeated styles into reusable components or
variables to improve readability and maintainability. Additionally, implement a
formatBytes utility function to convert raw storage size values into
human-readable formats before displaying them in the UI.

Comment on lines +65 to 68
} else if (type === IncomingMessageType.Do_State) {
const { isSyncing, syncingFolders, storageSize } = JSON.parse(message.data);
setDoState({ isSyncing, syncingFolders, storageSize });
}
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add validation for parsed message data! ⚠️

We need to validate the parsed data structure before destructuring. If the server sends malformed data, this could throw and break the notification handler.

 } else if (type === IncomingMessageType.Do_State) {
-  const { isSyncing, syncingFolders, storageSize } = JSON.parse(message.data);
-  setDoState({ isSyncing, syncingFolders, storageSize });
+  const data = JSON.parse(message.data);
+  if (typeof data.isSyncing === 'boolean' && 
+      Array.isArray(data.syncingFolders) && 
+      typeof data.storageSize === 'number') {
+    setDoState({ 
+      isSyncing: data.isSyncing, 
+      syncingFolders: data.syncingFolders, 
+      storageSize: data.storageSize 
+    });
+  } else {
+    console.error('Invalid Do_State message format:', data);
+  }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
} else if (type === IncomingMessageType.Do_State) {
const { isSyncing, syncingFolders, storageSize } = JSON.parse(message.data);
setDoState({ isSyncing, syncingFolders, storageSize });
}
} else if (type === IncomingMessageType.Do_State) {
const data = JSON.parse(message.data);
if (
typeof data.isSyncing === 'boolean' &&
Array.isArray(data.syncingFolders) &&
typeof data.storageSize === 'number'
) {
setDoState({
isSyncing: data.isSyncing,
syncingFolders: data.syncingFolders,
storageSize: data.storageSize,
});
} else {
console.error('Invalid Do_State message format:', data);
}
}
🤖 Prompt for AI Agents
In apps/mail/components/party.tsx around lines 65 to 68, the code parses
message.data and destructures it without validation, which can cause runtime
errors if the data is malformed. Add validation to check that the parsed object
contains the expected keys (isSyncing, syncingFolders, storageSize) and their
types before destructuring and calling setDoState. If validation fails, handle
the error gracefully to prevent breaking the notification handler.

Comment on lines +77 to 82
| {
type: OutgoingMessageType.Do_State;
isSyncing: boolean;
syncingFolders: string[];
storageSize: number;
};
Copy link
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick (assertive)

Type definition is solid! 💪

The structure is clean and well-typed. Consider adding JSDoc comments to document what storageSize represents (bytes, KB, MB?).

   | {
       type: OutgoingMessageType.Do_State;
       isSyncing: boolean;
       syncingFolders: string[];
+      /** Storage size in bytes */
       storageSize: number;
     };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
| {
type: OutgoingMessageType.Do_State;
isSyncing: boolean;
syncingFolders: string[];
storageSize: number;
};
| {
type: OutgoingMessageType.Do_State;
isSyncing: boolean;
syncingFolders: string[];
/** Storage size in bytes */
storageSize: number;
};
🤖 Prompt for AI Agents
In apps/server/src/routes/agent/types.ts around lines 77 to 82, the type
definition for the object includes a storageSize property but lacks
documentation on its unit of measurement. Add JSDoc comments above the type
definition or the storageSize property specifically to clarify what unit
storageSize represents, such as bytes, KB, or MB, to improve code readability
and maintainability.

@MrgSub MrgSub force-pushed the ZEROAdd_email_syncing_status_indicators_and_optimize_folder_synchronization branch from f8af7d4 to 6d6b8a5 Compare August 4, 2025 19:33
@jazzberry-ai
Copy link

jazzberry-ai bot commented Aug 4, 2025

Bug Report

Name Severity Example test case Description
Race condition in syncThreads with foldersInSync map Medium Simultaneously call syncThreads with the same folder from different contexts. Observe if two syncs run concurrently for the same folder, potentially causing data inconsistencies. There's a small window of time between the has check and the set call on the foldersInSync map where another call to syncThreads with the same folder could slip in. This could lead to two syncs running concurrently for the same folder. A more robust solution would be to use a locking mechanism or a more atomic operation to check and set the foldersInSync map.
Incorrect Batching Logic in syncThreads High Call syncThreads. Verify that the threads being synced match the thread IDs obtained when listing thread IDs. The current code lists thread IDs, creates batches of those thread IDs, but then fetches batches of threads using driver.list. The threads being synced are therefore likely unrelated to the initially fetched thread IDs. The code fetches a batch of threads using driver.list, but then syncs the threads in a different batch defined by threadIdBatches using syncSingleThread. This is likely unintended and could lead to incorrect/inconsistent results. Ideally, the code should fetch only the thread IDs and then use those batched thread IDs to fetch and sync the thread content.

Comments? Email us.

Copy link
Collaborator Author

MrgSub commented Aug 4, 2025

Merge activity

  • Aug 4, 7:35 PM UTC: A user started a stack merge that includes this pull request via Graphite.
  • Aug 4, 7:36 PM UTC: @MrgSub merged this pull request with Graphite.

@MrgSub MrgSub merged commit cc8d3f7 into staging Aug 4, 2025
7 of 8 checks passed
@MrgSub MrgSub deleted the ZEROAdd_email_syncing_status_indicators_and_optimize_folder_synchronization branch August 4, 2025 19:36
@cursor
Copy link

cursor bot commented Aug 4, 2025

Bugbot found 1 bug

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

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/mail/components/party.tsx (1)

65-68: Add validation for parsed message data - this is mission critical! 🚀

We need bulletproof validation here. If the server sends malformed data, this could cause a catastrophic failure in our notification system. We can't have our Mars colony emails crashing because of bad data!

 } else if (type === IncomingMessageType.Do_State) {
-  const { isSyncing, syncingFolders, storageSize } = JSON.parse(message.data);
-  setDoState({ isSyncing, syncingFolders, storageSize });
+  try {
+    const data = JSON.parse(message.data);
+    if (typeof data.isSyncing === 'boolean' && 
+        Array.isArray(data.syncingFolders) && 
+        typeof data.storageSize === 'number') {
+      setDoState({ 
+        isSyncing: data.isSyncing, 
+        syncingFolders: data.syncingFolders, 
+        storageSize: data.storageSize 
+      });
+    } else {
+      console.error('Invalid Do_State message format:', data);
+    }
+  } catch (error) {
+    console.error('Failed to parse Do_State message:', error);
+  }
 }
apps/mail/components/mail/mail.tsx (1)

399-407: This UI needs to be 10x better - we're not building a hobby project here! 🎯

The current implementation looks like a prototype from 2005. We need production-grade UI that could work on Mars internet latency!

-      <div className="fixed right-1 top-1 z-10 flex w-full justify-end">
-        <p className="w-fit rounded bg-purple-800 p-1 text-xs">
-          {isSyncing ? 'Syncing your emails...' : 'Synced your emails'}
-        </p>
-        {storageSize && <p className="w-fit rounded bg-purple-800 p-1 text-xs">{storageSize}</p>}
-        {syncingFolders.length > 0 && (
-          <p className="w-fit rounded bg-purple-800 p-1 text-xs">{syncingFolders.join(', ')}</p>
-        )}
-      </div>
+      {(isSyncing || storageSize > 0 || syncingFolders.length > 0) && (
+        <div className="fixed right-2 top-2 z-50 flex flex-col gap-1 md:flex-row md:gap-2" role="status" aria-live="polite">
+          <div className="flex items-center gap-1 rounded-md bg-purple-800/90 px-2 py-1 text-xs text-white shadow-sm backdrop-blur-sm">
+            {isSyncing ? (
+              <>
+                <RefreshCcw className="h-3 w-3 animate-spin" />
+                <span>Syncing emails...</span>
+              </>
+            ) : (
+              <span className="flex items-center gap-1">
+                <Check className="h-3 w-3" />
+                Synced
+              </span>
+            )}
+          </div>
+          {storageSize > 0 && (
+            <div className="rounded-md bg-purple-800/90 px-2 py-1 text-xs text-white shadow-sm backdrop-blur-sm">
+              {formatBytes(storageSize)}
+            </div>
+          )}
+          {syncingFolders.length > 0 && (
+            <div className="max-w-[200px] truncate rounded-md bg-purple-800/90 px-2 py-1 text-xs text-white shadow-sm backdrop-blur-sm" 
+                 title={syncingFolders.join(', ')}>
+              Syncing: {syncingFolders.join(', ')}
+            </div>
+          )}
+        </div>
+      )}

Also add this utility function somewhere in your utils:

function formatBytes(bytes: number): string {
  if (bytes === 0) return '0 Bytes';
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
}
apps/server/src/routes/agent/types.ts (1)

77-82: Documentation is key - even rocket scientists need to know the units! 📐

We can't have ambiguity about whether this is bytes, kilobytes, or Dogecoin. Add proper documentation!

   | {
       type: OutgoingMessageType.Do_State;
       isSyncing: boolean;
       syncingFolders: string[];
+      /** Storage size in bytes */
       storageSize: number;
     };
apps/server/src/routes/agent/index.ts (1)

1063-1070: Make this properly async - we can't have fire-and-forget broadcasts! 🚀

Broadcasting without awaiting is like launching a rocket without tracking it. We need to know if our messages reach their destination!

-  async sendDoState() {
-    return this.agent?.broadcastChatMessage({
+  async sendDoState() {
+    return await this.agent?.broadcastChatMessage({
       type: OutgoingMessageType.Do_State,
       isSyncing: this.isSyncing().length > 0,
       syncingFolders: this.isSyncing(),
       storageSize: this.getDatabaseSize(),
     });
   }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f8af7d4 and 6d6b8a5.

📒 Files selected for processing (6)
  • apps/mail/components/mail/mail.tsx (3 hunks)
  • apps/mail/components/mail/use-do-state.ts (1 hunks)
  • apps/mail/components/party.tsx (4 hunks)
  • apps/server/src/lib/server-utils.ts (0 hunks)
  • apps/server/src/routes/agent/index.ts (10 hunks)
  • apps/server/src/routes/agent/types.ts (2 hunks)
💤 Files with no reviewable changes (1)
  • apps/server/src/lib/server-utils.ts
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (AGENT.md)

**/*.{js,jsx,ts,tsx}: Use 2-space indentation
Use single quotes for strings
Limit lines to 100 characters in length
Semicolons are required at the end of statements

Files:

  • apps/mail/components/mail/mail.tsx
  • apps/mail/components/mail/use-do-state.ts
  • apps/mail/components/party.tsx
  • apps/server/src/routes/agent/index.ts
  • apps/server/src/routes/agent/types.ts
**/*.{js,jsx,ts,tsx,css,scss}

📄 CodeRabbit Inference Engine (AGENT.md)

Use Prettier with sort-imports and Tailwind plugins for code formatting

Files:

  • apps/mail/components/mail/mail.tsx
  • apps/mail/components/mail/use-do-state.ts
  • apps/mail/components/party.tsx
  • apps/server/src/routes/agent/index.ts
  • apps/server/src/routes/agent/types.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (AGENT.md)

Enable TypeScript strict mode

Files:

  • apps/mail/components/mail/mail.tsx
  • apps/mail/components/mail/use-do-state.ts
  • apps/mail/components/party.tsx
  • apps/server/src/routes/agent/index.ts
  • apps/server/src/routes/agent/types.ts
**/*.{css,js,ts,jsx,tsx,mdx}

📄 CodeRabbit Inference Engine (.cursor/rules/tailwind-css-v4.mdc)

**/*.{css,js,ts,jsx,tsx,mdx}: Chain variants together for composable variants (e.g., group-has-data-potato:opacity-100).
Use new variants such as starting, not-*, inert, nth-*, in-*, open (for :popover-open), and ** for all descendants.
Do not use deprecated utilities like bg-opacity-*, text-opacity-*, border-opacity-*, and divide-opacity-*; use the new syntax (e.g., bg-black/50).
Use renamed utilities: shadow-sm is now shadow-xs, shadow is now shadow-sm, drop-shadow-sm is now drop-shadow-xs, drop-shadow is now drop-shadow-sm, blur-sm is now blur-xs, blur is now blur-sm, rounded-sm is now rounded-xs, rounded is now rounded-sm, outline-none is now outline-hidden.
Use bg-(--brand-color) syntax for CSS variables in arbitrary values instead of bg-[--brand-color].
Stacked variants now apply left-to-right instead of right-to-left.

Files:

  • apps/mail/components/mail/mail.tsx
  • apps/mail/components/mail/use-do-state.ts
  • apps/mail/components/party.tsx
  • apps/server/src/routes/agent/index.ts
  • apps/server/src/routes/agent/types.ts
🧠 Learnings (6)
📚 Learning: in react hook form, avoid using useeffect for form state synchronization when the values prop can ha...
Learnt from: retrogtx
PR: Mail-0/Zero#1354
File: apps/mail/components/ui/prompts-dialog.tsx:85-88
Timestamp: 2025-06-20T05:03:16.944Z
Learning: In React Hook Form, avoid using useEffect for form state synchronization when the values prop can handle reactive updates automatically. The values prop is specifically designed for this purpose and is more optimal than manual useEffect-based synchronization.

Applied to files:

  • apps/mail/components/mail/mail.tsx
📚 Learning: in apps/mail/lib/hotkeys/mail-list-hotkeys.tsx, the switchcategorybyindex function using hardcoded i...
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.

Applied to files:

  • apps/mail/components/mail/mail.tsx
  • apps/mail/components/party.tsx
📚 Learning: in apps/server/src/lib/driver/google.ts, the normalization of "draft" to "drafts" in the count() met...
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.

Applied to files:

  • apps/mail/components/mail/mail.tsx
  • apps/mail/components/party.tsx
  • apps/server/src/routes/agent/index.ts
  • apps/server/src/routes/agent/types.ts
📚 Learning: applies to **/*.{css,js,ts,jsx,tsx,mdx} : do not use deprecated utilities like `bg-opacity-*`, `text...
Learnt from: CR
PR: Mail-0/Zero#0
File: .cursor/rules/tailwind-css-v4.mdc:0-0
Timestamp: 2025-08-03T20:42:04.207Z
Learning: Applies to **/*.{css,js,ts,jsx,tsx,mdx} : Do not use deprecated utilities like `bg-opacity-*`, `text-opacity-*`, `border-opacity-*`, and `divide-opacity-*`; use the new syntax (e.g., `bg-black/50`).

Applied to files:

  • apps/mail/components/mail/mail.tsx
📚 Learning: during testing phases, debug logging should be kept active in apps/server/src/lib/email-verification...
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.

Applied to files:

  • apps/mail/components/party.tsx
📚 Learning: in apps/server/src/trpc/routes/mail.ts, the attachment processing logic conditionally handles mixed ...
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.

Applied to files:

  • apps/mail/components/party.tsx
  • apps/server/src/routes/agent/types.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (3)
  • GitHub Check: Cursor Bugbot
  • GitHub Check: cubic · AI code reviewer
  • GitHub Check: Analyze (javascript-typescript)
🔇 Additional comments (4)
apps/server/src/routes/agent/index.ts (4)

319-324: Clean implementation of syncing state tracking! 🎯

This is exactly what we need - simple, efficient, and gets the job done. No over-engineering, just pure functionality.


1479-1484: Smart deduplication logic here! 🧠

Using Set to deduplicate and filtering out the folder label from labelIds prevents redundant filtering. This is the kind of optimization that makes databases sing!


1183-1183: Good UX thinking with the firstPageProcessed flag! 👍

Sending state updates after the first page gives users immediate feedback. This is how we build responsive systems that users love!

Also applies to: 1238-1242


1582-1582: Strategic placement of syncFolders() call! 🎯

Using waitUntil to trigger folder sync in the background when threads are requested is brilliant. Non-blocking, efficient, and ensures data freshness.

Comment on lines +19 to +34
const setIsSyncingAtom = atom(null, (get, set, isSyncing: boolean) => {
const current = get(stateAtom);
set(stateAtom, { ...current, isSyncing });
});

const setSyncingFoldersAtom = atom(null, (get, set, syncingFolders: string[]) => {
const current = get(stateAtom);
set(stateAtom, { ...current, syncingFolders });
});

const setStorageSizeAtom = atom(null, (get, set, storageSize: number) => {
const current = get(stateAtom);
set(stateAtom, { ...current, storageSize });
});

export { setIsSyncingAtom, setSyncingFoldersAtom, setStorageSizeAtom, useDoState };
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Dead code is like carrying extra weight to Mars - get rid of it! 🚮

These individual setter atoms are exported but never used anywhere in the codebase. We're not running a code museum here!

Either use these setter atoms or remove them entirely. Since setDoState from the hook already handles all updates, these seem redundant:

-const setIsSyncingAtom = atom(null, (get, set, isSyncing: boolean) => {
-  const current = get(stateAtom);
-  set(stateAtom, { ...current, isSyncing });
-});
-
-const setSyncingFoldersAtom = atom(null, (get, set, syncingFolders: string[]) => {
-  const current = get(stateAtom);
-  set(stateAtom, { ...current, syncingFolders });
-});
-
-const setStorageSizeAtom = atom(null, (get, set, storageSize: number) => {
-  const current = get(stateAtom);
-  set(stateAtom, { ...current, storageSize });
-});
-
-export { setIsSyncingAtom, setSyncingFoldersAtom, setStorageSizeAtom, useDoState };
+export { useDoState };
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const setIsSyncingAtom = atom(null, (get, set, isSyncing: boolean) => {
const current = get(stateAtom);
set(stateAtom, { ...current, isSyncing });
});
const setSyncingFoldersAtom = atom(null, (get, set, syncingFolders: string[]) => {
const current = get(stateAtom);
set(stateAtom, { ...current, syncingFolders });
});
const setStorageSizeAtom = atom(null, (get, set, storageSize: number) => {
const current = get(stateAtom);
set(stateAtom, { ...current, storageSize });
});
export { setIsSyncingAtom, setSyncingFoldersAtom, setStorageSizeAtom, useDoState };
export { useDoState };
🤖 Prompt for AI Agents
In apps/mail/components/mail/use-do-state.ts between lines 19 and 34, the setter
atoms setIsSyncingAtom, setSyncingFoldersAtom, and setStorageSizeAtom are
defined and exported but never used anywhere in the codebase, making them
redundant. Since the existing setDoState hook already manages all state updates,
remove these unused setter atoms entirely to clean up dead code and avoid
unnecessary exports.

Copy link
Contributor

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

cubic analysis

No issues found across 6 files. Review in cubic

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

Labels

content design Improvements & changes to design & UX

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant