Skip to content

Comments

general fixes#1784

Merged
MrgSub merged 1 commit intostagingfrom
ZERO07-21-general_fixes
Jul 21, 2025
Merged

general fixes#1784
MrgSub merged 1 commit intostagingfrom
ZERO07-21-general_fixes

Conversation

@MrgSub
Copy link
Collaborator

@MrgSub MrgSub commented Jul 21, 2025

READ CAREFULLY THEN REMOVE

Remove bullet points that are not relevant.

PLEASE REFRAIN FROM USING AI TO WRITE YOUR CODE AND PR DESCRIPTION. IF YOU DO USE AI TO WRITE YOUR CODE PLEASE PROVIDE A DESCRIPTION AND REVIEW IT CAREFULLY. MAKE SURE YOU UNDERSTAND THE CODE YOU ARE SUBMITTING USING AI.

  • Pull requests that do not follow these guidelines will be closed without review or comment.
  • If you use AI to write your PR description your pr will be close without review or comment.
  • If you are unsure about anything, feel free to ask for clarification.

Description

Please provide a clear description of your changes.


Type of Change

Please delete options that are not relevant.

  • 🐛 Bug fix (non-breaking change which fixes an issue)
  • ✨ New feature (non-breaking change which adds functionality)
  • 💥 Breaking change (fix or feature with breaking changes)
  • 📝 Documentation update
  • 🎨 UI/UX improvement
  • 🔒 Security enhancement
  • ⚡ Performance improvement

Areas Affected

Please check all that apply:

  • Email Integration (Gmail, IMAP, etc.)
  • User Interface/Experience
  • Authentication/Authorization
  • Data Storage/Management
  • API Endpoints
  • Documentation
  • Testing Infrastructure
  • Development Workflow
  • Deployment/Infrastructure

Testing Done

Describe the tests you've done:

  • Unit tests added/updated
  • Integration tests added/updated
  • Manual testing performed
  • Cross-browser testing (if UI changes)
  • Mobile responsiveness verified (if UI changes)

Security Considerations

For changes involving data or authentication:

  • No sensitive data is exposed
  • Authentication checks are in place
  • Input validation is implemented
  • Rate limiting is considered (if applicable)

Checklist

  • I have read the CONTRIBUTING document
  • My code follows the project's style guidelines
  • I have performed a self-review of my code
  • I have commented my code, particularly in complex areas
  • I have updated the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix/feature works
  • All tests pass locally
  • Any dependent changes are merged and published

Additional Notes

Add any other context about the pull request here.

Screenshots/Recordings

Add screenshots or recordings here if applicable.


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


Summary by cubic

Replaced all synchronous getZeroDB calls with await getZeroDB to ensure proper async database access and prevent potential race conditions.

  • Bug Fixes
    • Fixed async handling in database calls across server, routes, and utilities.
    • Improved thread sync logic and debug logging in mail and agent routes.

Summary by CodeRabbit

  • New Features

    • Added folder-specific thread count tracking and conditional syncing for improved performance and data consistency.
    • Introduced a new method to retrieve thread counts for specific folders.
  • Improvements

    • Enhanced agent initialization and sync control flow for better reliability.
    • Strengthened type safety in internal queue handling.
  • Bug Fixes

    • Ensured all database connections are properly awaited, improving data integrity across authentication, notes, connections, settings, and shortcuts.
  • Developer Experience

    • Added detailed debug logging for mail thread listing and snooze operations to aid troubleshooting.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 21, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

All usages of the getZeroDB function across the server codebase were updated from synchronous to asynchronous, reflecting its conversion to an async function. Additional logic was introduced in the agent driver for folder thread counting and sync control. Type safety was improved in the agent RPC queue method, and debug logging was enhanced in mail routing.

Changes

File(s) Change Summary
apps/server/src/lib/auth.ts,
apps/server/src/lib/driver/utils.ts,
apps/server/src/lib/notes-manager.ts,
apps/server/src/lib/server-utils.ts,
apps/server/src/main.ts,
apps/server/src/trpc/routes/connections.ts,
apps/server/src/trpc/routes/settings.ts,
apps/server/src/trpc/routes/shortcut.ts,
apps/server/src/trpc/trpc.ts
All calls to getZeroDB updated from synchronous to asynchronous (await getZeroDB(...)); function signature updated to async.
apps/server/src/lib/server-utils.ts Added new async function getZeroSocketAgent.
apps/server/src/routes/agent/index.ts Added folder thread count tracking, conditional syncing, agent initialization logic, and improved sync control.
apps/server/src/routes/agent/rpc.ts Type of callbackName in DriverRpcDO.queue changed from string to keyof ZeroDriver for type safety.
apps/server/src/trpc/routes/mail.ts Added detailed debug logging throughout thread listing and unsnooze operations.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Server
    participant ZeroDB

    Client->>Server: Request (e.g., fetch notes, connections, settings)
    Server->>ZeroDB: await getZeroDB(userId)
    ZeroDB-->>Server: Returns DB instance (async)
    Server->>Server: Perform DB operations (e.g., fetch/update/delete)
    Server-->>Client: Respond with result
Loading
sequenceDiagram
    participant Agent
    participant ZeroDriver
    participant ZeroSocketAgent
    participant DB

    Agent->>ZeroDriver: setMetaData(connectionId)
    ZeroDriver->>ZeroSocketAgent: getZeroSocketAgent(connectionId)
    ZeroSocketAgent-->>ZeroDriver: Returns agent
    ZeroDriver->>DB: setMetaData(userId)
    DB-->>ZeroDriver: Updates metadata
Loading

Estimated code review effort

4 (~90 minutes)

Possibly related PRs

  • Mail-0/Zero#1345: Refactors NotesManager to use getZeroDB asynchronously, directly overlapping with this PR's async conversion.
  • Mail-0/Zero#1336: Centralizes database access via a new ZeroDB Durable Object, closely related to this PR's changes in database access patterns.

Poem

In the warren, code hops anew,
Awaiting the DB, as all rabbits do.
Threads and notes, now fetched with care,
Async calls bounding everywhere!
With logs that sparkle and types that delight,
This patch brings the backend to burrow-bright.
🐇✨


📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between f7db4d2 and 3f39be4.

📒 Files selected for processing (12)
  • apps/server/src/lib/auth.ts (3 hunks)
  • apps/server/src/lib/driver/utils.ts (1 hunks)
  • apps/server/src/lib/notes-manager.ts (5 hunks)
  • apps/server/src/lib/server-utils.ts (2 hunks)
  • apps/server/src/main.ts (1 hunks)
  • apps/server/src/routes/agent/index.ts (8 hunks)
  • apps/server/src/routes/agent/rpc.ts (1 hunks)
  • apps/server/src/trpc/routes/connections.ts (3 hunks)
  • apps/server/src/trpc/routes/mail.ts (6 hunks)
  • apps/server/src/trpc/routes/settings.ts (2 hunks)
  • apps/server/src/trpc/routes/shortcut.ts (1 hunks)
  • apps/server/src/trpc/trpc.ts (1 hunks)
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

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

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

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

Other keywords and placeholders

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

CodeRabbit Configuration File (.coderabbit.yaml)

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

Documentation and Community

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

Copy link
Collaborator Author

MrgSub commented Jul 21, 2025

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

@MrgSub MrgSub force-pushed the ZERO07-21-general_fixes branch from 259961d to 3f39be4 Compare July 21, 2025 23:08
@MrgSub MrgSub marked this pull request as ready for review July 21, 2025 23:09
Copy link
Collaborator Author

MrgSub commented Jul 21, 2025

Merge activity

  • Jul 21, 11:09 PM UTC: A user started a stack merge that includes this pull request via Graphite.
  • Jul 21, 11:09 PM UTC: @MrgSub merged this pull request with Graphite.

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.

@MrgSub MrgSub merged commit 27e96a6 into staging Jul 21, 2025
8 of 9 checks passed
@MrgSub MrgSub deleted the ZERO07-21-general_fixes branch July 21, 2025 23:09
): Promise<typeof note.$inferSelect> {
try{
const db = getZeroDB(userId);
try {
Copy link
Contributor

Choose a reason for hiding this comment

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

The spacing in the try block has been fixed in this PR, adding a space between the try keyword and the opening brace. This aligns with standard TypeScript style conventions where control structure keywords should be followed by a space before the opening brace.

Spotted by Diamond (based on custom rules)

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

Copy link

@cursor cursor bot left a comment

Choose a reason for hiding this comment

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

Bug: Configuration Overridden by Hardcoded Values

The environment variables DROP_AGENT_TABLES and THREAD_SYNC_MAX_COUNT are no longer respected. shouldDropTables is now hardcoded to false, preventing table drops, and maxCount is hardcoded to 20, overriding the previous default of 10 and any configured value. This removes critical runtime configurability.

apps/server/src/routes/agent/index.ts#L60-L62

const shouldDropTables = false;
const maxCount = 20;

Fix in CursorFix in Web


Bug: Debug Logs Clutter Production Output

Multiple console.debug statements were accidentally committed to the listThreads function. These temporary debugging statements create excessive log noise and clutter production logs, potentially impacting performance.

apps/server/src/trpc/routes/mail.ts#L77-L159

console.debug('[listThreads] input:', { folder, maxResults, cursor, q, labelIds });
if (folder === FOLDERS.DRAFT) {
console.debug('[listThreads] Listing drafts');
const drafts = await agent.listDrafts({
q,
maxResults,
pageToken: cursor,
});
console.debug('[listThreads] Drafts result:', drafts);
return drafts;
}
type ThreadItem = { id: string; historyId: string | null; $raw?: unknown };
let threadsResponse: IGetThreadsResponse;
if (q) {
console.debug('[listThreads] Performing search with query:', q);
threadsResponse = await agent.rawListThreads({
folder,
query: q,
maxResults,
labelIds,
pageToken: cursor,
});
console.debug('[listThreads] Search result:', threadsResponse);
} else {
const folderLabelId = getFolderLabelId(folder);
const labelIdsToUse = folderLabelId ? [...labelIds, folderLabelId] : labelIds;
console.debug('[listThreads] Listing with labelIds:', labelIdsToUse, 'for folder:', folder);
threadsResponse = await agent.listThreads({
folder,
labelIds: labelIdsToUse,
maxResults,
pageToken: cursor,
});
console.debug('[listThreads] List result:', threadsResponse);
}
if (folder === FOLDERS.SNOOZED) {
const nowTs = Date.now();
const filtered: ThreadItem[] = [];
console.debug('[listThreads] Filtering snoozed threads at', new Date(nowTs).toISOString());
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);
return;
}
const wakeAt = new Date(wakeAtIso).getTime();
if (wakeAt > nowTs) {
filtered.push(t);
return;
}
console.debug('[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);
}
}),
);
threadsResponse.threads = filtered;
console.debug('[listThreads] Snoozed threads after filtering:', filtered);
}
console.debug('[listThreads] Returning threadsResponse:', threadsResponse);
return threadsResponse;

Fix in CursorFix in Web


BugBot free trial expires on July 29, 2025
Learn more in the Cursor dashboard.

Was this report helpful? Give feedback by reacting with 👍 or 👎

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

4 issues found across 12 files • Review in cubic

React with 👍 or 👎 to teach cubic. You can also tag @cubic-dev-ai to give feedback, ask questions, or re-run the review.

const { labelIds = [], folder, q, maxResults = 50, pageToken } = params;

try {
const folderThreadCount = (await this.count()).find((c) => c.label === folder)?.count;
Copy link
Contributor

Choose a reason for hiding this comment

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

this.count() is assumed to return an array but that is not guaranteed; calling .find without a type-guard can crash the request when the driver fails or returns undefined.

Prompt for AI agents
Address the following comment on apps/server/src/routes/agent/index.ts at line 629:

<comment>`this.count()` is assumed to return an array but that is not guaranteed; calling `.find` without a type-guard can crash the request when the driver fails or returns `undefined`.</comment>

<file context>
@@ -618,6 +626,16 @@ export class ZeroDriver extends AIChatAgent&lt;typeof env&gt; {
     const { labelIds = [], folder, q, maxResults = 50, pageToken } = params;
 
     try {
+      const folderThreadCount = (await this.count()).find((c) =&gt; c.label === folder)?.count;
+      const currentThreadCount = await this.getThreadCount();
+
</file context>

}

async getFolderThreadCount(folder: string) {
const count = this.sql`SELECT COUNT(*) FROM threads WHERE EXISTS (
Copy link
Contributor

Choose a reason for hiding this comment

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

The database query result is not awaited, so count[0] will be undefined and the method will throw at runtime.

Prompt for AI agents
Address the following comment on apps/server/src/routes/agent/index.ts at line 454:

<comment>The database query result is not awaited, so `count[0]` will be undefined and the method will throw at runtime.</comment>

<file context>
@@ -449,6 +450,13 @@ export class ZeroDriver extends AIChatAgent&lt;typeof env&gt; {
     return count[0][&#39;COUNT(*)&#39;] as number;
   }
 
+  async getFolderThreadCount(folder: string) {
+    const count = this.sql`SELECT COUNT(*) FROM threads WHERE EXISTS (
+      SELECT 1 FROM json_each(latest_label_ids) WHERE value = ${folder}
+    )`;
</file context>
Suggested change
const count = this.sql`SELECT COUNT(*) FROM threads WHERE EXISTS (
const count = await this.sql`SELECT COUNT(*) FROM threads WHERE EXISTS (

const shouldDropTables = env.DROP_AGENT_TABLES === 'true';
const maxCount = parseInt(env.THREAD_SYNC_MAX_COUNT || '10', 10);
const shouldDropTables = false;
const maxCount = 20;
Copy link
Contributor

Choose a reason for hiding this comment

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

Thread sync batch size is hard-coded, removing the ability to control it via the THREAD_SYNC_MAX_COUNT environment variable.

Prompt for AI agents
Address the following comment on apps/server/src/routes/agent/index.ts at line 62:

<comment>Thread sync batch size is hard-coded, removing the ability to control it via the `THREAD_SYNC_MAX_COUNT` environment variable.</comment>

<file context>
@@ -58,8 +58,8 @@ import { Effect } from &#39;effect&#39;;
 
 const decoder = new TextDecoder();
 
-const shouldDropTables = env.DROP_AGENT_TABLES === &#39;true&#39;;
-const maxCount = parseInt(env.THREAD_SYNC_MAX_COUNT || &#39;10&#39;, 10);
+const shouldDropTables = false;
+const maxCount = 20;
 const shouldLoop = env.THREAD_SYNC_LOOP !== &#39;false&#39;;
 export class ZeroDriver extends AIChatAgent&lt;typeof env&gt; {
</file context>
Suggested change
const maxCount = 20;
const maxCount = parseInt(env.THREAD_SYNC_MAX_COUNT || '10', 10);

maxResults,
pageToken: cursor,
});
console.debug('[listThreads] Drafts result:', drafts);
Copy link
Contributor

Choose a reason for hiding this comment

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

Logging entire thread/draft objects can leak sensitive email content to application logs. Log only minimal metadata or remove these statements.

Prompt for AI agents
Address the following comment on apps/server/src/trpc/routes/mail.ts at line 87:

<comment>Logging entire thread/draft objects can leak sensitive email content to application logs. Log only minimal metadata or remove these statements.</comment>

<file context>
@@ -75,12 +75,16 @@ export const mailRouter = router({
       const { activeConnection } = ctx;
       const agent = await getZeroAgent(activeConnection.id);
 
+      console.debug(&#39;[listThreads] input:&#39;, { folder, maxResults, cursor, q, labelIds });
+
       if (folder === FOLDERS.DRAFT) {
+        console.debug(&#39;[listThreads] Listing drafts&#39;);
         const drafts = await agent.listDrafts({
           q,
</file context>
Suggested change
console.debug('[listThreads] Drafts result:', drafts);
console.debug('[listThreads] Drafts result count:', drafts?.threads?.length ?? 0);

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant