Skip to content

Comments

refactor durable objects#1764

Merged
MrgSub merged 1 commit intostagingfrom
07-19-refactor_durable_objects
Jul 20, 2025
Merged

refactor durable objects#1764
MrgSub merged 1 commit intostagingfrom
07-19-refactor_durable_objects

Conversation

@MrgSub
Copy link
Collaborator

@MrgSub MrgSub commented Jul 20, 2025

Refactor Agent Architecture with Driver/Agent Split

Description

This PR refactors the agent architecture by splitting the ZeroAgent class into two separate classes: ZeroDriver and ZeroAgent. The ZeroDriver handles mail operations and database interactions, while ZeroAgent focuses on chat functionality. This separation of concerns improves code organization and maintainability.

Key changes:

  • Created a new ZeroDriver class to handle mail operations and database interactions
  • Modified ZeroAgent to focus on chat functionality
  • Updated RPC target from AgentRpcDO to DriverRpcDO
  • Fixed variable declarations from let to const in mail-display.tsx
  • Updated environment configuration in wrangler.jsonc to include the new ZeroDriver class

Type of Change

  • ⚡ Performance improvement
  • 🎨 UI/UX improvement

Areas Affected

  • Email Integration (Gmail, IMAP, etc.)
  • Data Storage/Management
  • API Endpoints
  • Development Workflow

Testing Done

  • Manual testing performed

Security Considerations

  • No sensitive data is exposed
  • Authentication checks are in place

Checklist

  • I have performed a self-review of my code
  • I have commented my code, particularly in complex areas
  • My changes generate no new warnings

Additional Notes

This architectural change improves separation of concerns and should make the codebase more maintainable. The ZeroDriver handles all mail-related operations while ZeroAgent focuses on chat functionality, creating a cleaner division of responsibilities.

Summary by CodeRabbit

  • New Features

    • Introduced a new system component to handle mail operations and synchronization, improving modularity and reliability.
    • Added support for enhanced chat message streaming and improved error handling in messaging features.
  • Refactor

    • Separated responsibilities between mail operations and chat handling for better maintainability and clarity.
    • Updated internal naming and structure to reflect the new modular design.
    • Streamlined tool integrations to use a new connection-based approach.
  • Chores

    • Updated configuration to support new system components across all environments.
    • Removed unused imports and simplified type annotations for improved code clarity.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 20, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

This change splits the responsibilities of the ZeroAgent class into two separate classes: ZeroDriver for mail operations and database sync, and a refactored ZeroAgent for chat message handling and communication. Durable object bindings, imports/exports, and related tool and RPC logic are updated to support this modularization.

Changes

File(s) Change Summary
apps/mail/components/mail/mail-display.tsx Changed let to const for attachmentData in two async functions; no logic changes.
apps/server/src/lib/server-utils.ts getZeroAgent now retrieves stub from ZERO_DRIVER and calls setupAuth without arguments.
apps/server/src/main.ts Imports and exports updated to include ZeroDriver alongside ZeroAgent.
apps/server/src/pipelines.effect.ts Removed unused summary import.
apps/server/src/routes/agent/index.ts Refactored: Split ZeroAgent into new ZeroAgent (chat) and ZeroDriver (mail/db); updated exported entities.
apps/server/src/routes/agent/mcp.ts Removed type annotation from map callback parameter in listThreads tool.
apps/server/src/routes/agent/rpc.ts Renamed AgentRpcDODriverRpcDO, ZeroAgentZeroDriver, and updated method signatures accordingly.
apps/server/src/routes/agent/tools.ts Tools now accept connectionId and obtain agent via getZeroAgent(connectionId) instead of direct agent parameter.
apps/server/wrangler.jsonc Added "ZERO_DRIVER" durable object binding and migration entries for all environments.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant ZeroAgent
    participant ZeroDriver
    participant DB

    Client->>ZeroAgent: Send chat or mail operation request
    alt Chat message
        ZeroAgent->>ZeroAgent: Handle chat, stream AI response
    else Mail operation
        ZeroAgent->>ZeroDriver: Forward mail-related request
        ZeroDriver->>DB: Query/update mail threads, labels, etc.
        ZeroDriver->>ZeroAgent: Broadcast updates (if needed)
        ZeroDriver-->>ZeroAgent: Return result
    end
    ZeroAgent-->>Client: Respond with result or stream
Loading

Possibly related PRs

  • fix agent rpc creation #1679: Refactors how the ZeroAgent is obtained and initialized asynchronously, directly related to agent acquisition and setup logic.
  • hotfixes #1753: Changes the syncThread method signature in a similar area, indicating a direct connection in thread sync logic.
  • Typo #1608: Moves thread database methods from ZeroAgent to ZeroDriver, directly related to the main PR's class split and method relocation.

Poem

In the warren of code, two agents arise,
ZeroDriver for mail, with database ties.
ZeroAgent now chats, streams thoughts with delight,
Durable objects connect through the digital night.
Splitting their duties, each rabbit is keen—
Hopping through refactors, the codebase is clean!
🐇✨


📜 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 6637cb9 and 4d65deb.

📒 Files selected for processing (9)
  • apps/mail/components/mail/mail-display.tsx (2 hunks)
  • apps/server/src/lib/server-utils.ts (1 hunks)
  • apps/server/src/main.ts (2 hunks)
  • apps/server/src/pipelines.effect.ts (1 hunks)
  • apps/server/src/routes/agent/index.ts (18 hunks)
  • apps/server/src/routes/agent/mcp.ts (1 hunks)
  • apps/server/src/routes/agent/rpc.ts (2 hunks)
  • apps/server/src/routes/agent/tools.ts (10 hunks)
  • apps/server/wrangler.jsonc (6 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 20, 2025

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

@MrgSub MrgSub marked this pull request as ready for review July 20, 2025 02:07
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.

Copy link
Collaborator Author

MrgSub commented Jul 20, 2025

Merge activity

  • Jul 20, 2:07 AM UTC: A user started a stack merge that includes this pull request via Graphite.
  • Jul 20, 2:07 AM UTC: @MrgSub merged this pull request with Graphite.

@MrgSub MrgSub merged commit e4148d3 into staging Jul 20, 2025
7 of 9 checks passed
@MrgSub MrgSub deleted the 07-19-refactor_durable_objects branch July 20, 2025 02:07
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 9 files. Review in cubic

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: ZeroDriver Fails to Await RPC Call

The ZeroDriver attempts to call this.agent.broadcastChatMessage() on a DurableObjectStub<ZeroAgent>. This method is not exposed for RPC, and even if it were, the call is not awaited, leading to runtime errors during mail synchronization broadcasts.

apps/server/src/routes/agent/index.ts#L421-L425

`;
this.agent.broadcastChatMessage({
type: OutgoingMessageType.Mail_Get,
threadId,
});

apps/server/src/routes/agent/index.ts#L494-L498

this.foldersInSync.delete(folder);
this.agent.broadcastChatMessage({
type: OutgoingMessageType.Mail_List,
folder,
});

Fix in CursorFix in Web


Bug: Async Method Missing Await Keywords

The getThreadsFromDB method is missing await keywords for multiple this.sql SELECT queries. This causes the asynchronous database operations to return Promises instead of their results, leading to runtime errors when the code attempts to synchronously access array properties like length or map on these Promise objects.

apps/server/src/routes/agent/index.ts#L631-L711

// No conditions
result = this.sql`
SELECT id, latest_received_on
FROM threads
ORDER BY latest_received_on DESC
LIMIT ${maxResults}
`;
} else if (whereConditions.length === 1) {
// Single condition
const condition = whereConditions[0];
if (condition.includes('latest_received_on <')) {
const cursorValue = pageToken!;
result = this.sql`
SELECT id, latest_received_on
FROM threads
WHERE latest_received_on < ${cursorValue}
ORDER BY latest_received_on DESC
LIMIT ${maxResults}
`;
} else if (folder) {
// Folder condition
const folderLabel = folder.toUpperCase();
result = this.sql`
SELECT id, latest_received_on
FROM threads
WHERE EXISTS (
SELECT 1 FROM json_each(latest_label_ids) WHERE value = ${folderLabel}
)
ORDER BY latest_received_on DESC
LIMIT ${maxResults}
`;
} else {
// Single label condition
const labelId = labelIds[0];
result = this.sql`
SELECT id, latest_received_on
FROM threads
WHERE EXISTS (
SELECT 1 FROM json_each(latest_label_ids) WHERE value = ${labelId}
)
ORDER BY latest_received_on DESC
LIMIT ${maxResults}
`;
}
} else {
// Multiple conditions - handle combinations
if (folder && labelIds.length === 0 && pageToken) {
// Folder + cursor
const folderLabel = folder.toUpperCase();
result = this.sql`
SELECT id, latest_received_on
FROM threads
WHERE EXISTS (
SELECT 1 FROM json_each(latest_label_ids) WHERE value = ${folderLabel}
) AND latest_received_on < ${pageToken}
ORDER BY latest_received_on DESC
LIMIT ${maxResults}
`;
} else if (labelIds.length === 1 && pageToken && !folder) {
// Single label + cursor
const labelId = labelIds[0];
result = this.sql`
SELECT id, latest_received_on
FROM threads
WHERE EXISTS (
SELECT 1 FROM json_each(latest_label_ids) WHERE value = ${labelId}
) AND latest_received_on < ${pageToken}
ORDER BY latest_received_on DESC
LIMIT ${maxResults}
`;
} else {
// For now, fallback to just cursor if complex combinations
const cursorValue = pageToken || '';
result = this.sql`
SELECT id, latest_received_on
FROM threads
WHERE latest_received_on < ${cursorValue}
ORDER BY latest_received_on DESC
LIMIT ${maxResults}
`;
}

Fix in CursorFix in Web


Bug: Initialization Timing Issue Causes Undefined Name

The agent property in ZeroDriver and driver property in ZeroAgent are initialized using this.name in their class field declarations. As this.name is only set later (e.g., via setName() in ZeroDriver's setMetaData()), the DurableObjectStub instances are created with an undefined name, leading to runtime errors.

apps/server/src/routes/agent/index.ts#L63-L66

private driver: MailManager | null = null;
private agent: DurableObjectStub<ZeroAgent> = env.ZERO_AGENT.get(
env.ZERO_AGENT.idFromName(this.name),
);

apps/server/src/routes/agent/index.ts#L823-L824

private chatMessageAbortControllers: Map<string, AbortController> = new Map();
private driver: DurableObjectStub<ZeroDriver> = getZeroDriver(this.name);

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 👎

super(ctx, env);
if (shouldDropTables) this.dropTables();
this.sql`
void this.sql`
Copy link
Contributor

Choose a reason for hiding this comment

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

The void operator is correctly used here to explicitly indicate this is a fire-and-forget promise. This pattern follows the Google TypeScript Style Guide recommendation for promises whose results are intentionally ignored. Using void this.sql rather than just this.sql makes the intent clear and prevents linting warnings about unhandled promises.

Spotted by Diamond (based on custom rules)

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

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