Skip to content

Comments

Staging#941

Merged
MrgSub merged 20 commits intomainfrom
staging
May 11, 2025
Merged

Staging#941
MrgSub merged 20 commits intomainfrom
staging

Conversation

@MrgSub
Copy link
Collaborator

@MrgSub MrgSub commented May 11, 2025

Summary by CodeRabbit

  • New Features

    • Added a new environment variable for setting a default brain limit.
  • Bug Fixes

    • Corrected an environment flag in the server type generation script to ensure proper execution.
  • Refactor

    • Improved attachment extraction logic in email handling for better maintainability.
    • Updated summary data access in mail display for consistency with backend changes.
    • Reworked notification logic to use connection and thread identifiers, with enhanced logging.
    • Simplified summary generation by using a direct method call instead of a manual fetch.
    • Updated label management to include descriptive metadata and export default labels for reuse.
    • Switched thread management in party component to use React Query and improved socket handling.
  • Chores

    • Updated example environment file and removed certain variables from deployment configuration.
    • Enabled passing request headers to notification provider for improved integration.
    • Adjusted class and formatting order in pricing and layout components for style consistency.

BlankParticle and others added 20 commits May 11, 2025 10:55
fix: local dev mode for zero backend
fix: use different cookie based on NODE_ENV
fix(thread): attachment rendering
@vercel
Copy link

vercel bot commented May 11, 2025

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
0 🔄 Building (Inspect) Visit Preview 💬 Add feedback May 11, 2025 10:56pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 11, 2025

Walkthrough

This update introduces a new environment variable and modifies the .env.example file, restructures default label data in the mail component, and refactors attachment handling in the Google mail driver. It also updates notification and summary generation logic, adjusts CSS class order in the pricing page, and changes how headers and notification providers are handled in the mail app layout.

Changes

File(s) Change Summary
.env.example Enclosed COOKIE_DOMAIN in double quotes and added DEFAULT_BRAIN_LIMIT="500".
apps/server/wrangler.jsonc Removed DEFAULT_BRAIN_LIMIT, NEXT_PUBLIC_BACKEND_URL, NEXT_PUBLIC_APP_URL, and COOKIE_DOMAIN from both "staging" and "production" environments.
apps/server/package.json Fixed script flag from --e staging to --env staging for the wrangler types command.
apps/server/src/lib/auth.ts Added type imports, set cookiePrefix in advanced config based on environment, and asserted return type as BetterAuthOptions.
apps/server/src/lib/driver/google.ts Refactored attachment extraction logic into a new private method findAttachments for recursive and centralized attachment filtering.
apps/server/src/main.ts Changed notifyUser to async, updated signature to accept connectionId, threadId, and type; changed durable object ID derivation, added logging, and updated message format.
apps/server/src/trpc/routes/brain.ts Replaced manual fetch with direct call to env.zero.getSummary, changed returned data structure, and simplified control flow.
apps/mail/app/(full-width)/pricing/page.tsx Adjusted JSX formatting and CSS class order for layout and styling consistency; removed onClick handler from Free plan button.
apps/mail/app/(routes)/mail/layout.tsx Uncommented and activated header extraction and passed headers as props to NotificationProvider.
apps/mail/components/mail/mail.tsx Changed defaultLabels from a string array to an exported array of objects with name and usecase; updated logic to handle new structure.
apps/mail/components/mail/mail-display.tsx Updated summary access path from summary.short to summary.data.short for conditional rendering and display.
apps/mail/components/party.tsx Switched from Jotai atoms to React Query and a custom hook for thread management; updated socket room logic, message handling, and added logging.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Layout
    participant NotificationProvider

    Client->>Layout: Request mail layout
    Layout->>Layout: Extract headers
    Layout->>NotificationProvider: Pass headers as props
    NotificationProvider-->>Client: Render with notifications
Loading
sequenceDiagram
    participant Server
    participant DurableObject
    participant User

    Server->>DurableObject: notifyUser({connectionId, threadId, type})
    DurableObject->>User: Broadcast message (threadId:type)
    User-->>Server: (Optional) Acknowledge receipt
Loading

Possibly related PRs

  • Mail-0/Zero#929: Implements the pricing page component with subscription logic; related as both PRs modify the pricing page file, though this PR focuses on styling and button handler adjustments.

Suggested reviewers

  • ahmetskilinc
  • needleXO

Poem

In the warren of code, a bunny hops,
Tweaking envs and styling crops.
Attachments are sorted, summaries bright,
Notifications now handled just right.
With labels anew and headers in tow,
This patch brings a gentle, springtime glow!
🐇✨

Tip

⚡️ Faster reviews with caching
  • CodeRabbit now supports caching for code and dependencies, helping speed up reviews. This means quicker feedback, reduced wait times, and a smoother review experience overall. Cached data is encrypted and stored securely. This feature will be automatically enabled for all accounts on May 16th. To opt out, configure Review - Disable Cache at either the organization or repository level. If you prefer to disable all data retention across your organization, simply turn off the Data Retention setting under your Organization Settings.

Enjoy the performance boost—your workflow just got faster.

✨ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

@MrgSub MrgSub merged commit 1bf2bcf into main May 11, 2025
3 of 5 checks passed
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

🔭 Outside diff range comments (1)
apps/mail/app/(full-width)/pricing/page.tsx (1)

347-347: 🛠️ Refactor suggestion

Verify the onClick handler on Enterprise contact button

The Enterprise plan's "Contact us" button still has an onClick={handleUpgrade} handler, but this doesn't seem appropriate since the button already has a direct link to the contact calendar page.

 <Link href="https://cal.com/team/0/chat" target="_blank">
-  <Button className="h-8 w-full" onClick={handleUpgrade}>
+  <Button className="h-8 w-full">
     Contact us
   </Button>
 </Link>
🧹 Nitpick comments (2)
apps/server/src/lib/driver/google.ts (1)

1037-1067: Well-structured helper method for attachment extraction

The new findAttachments method effectively:

  1. Recursively traverses message parts to find all attachments
  2. Properly filters inline attachments with content IDs (which are handled separately)
  3. Handles nested message structures and RFC822 message attachments
  4. Simplifies the main code flow in the get method

This is a good example of the Single Responsibility Principle, extracting complex logic into a focused helper method.

However, there are a few potential improvements:

 private findAttachments(parts: any[]): any[] {
+  // Consider adding type definitions instead of using 'any'
   let results: any[] = [];
   
   for (const part of parts) {
     if (part.filename && part.filename.length > 0) {
apps/server/src/main.ts (1)

89-111: Improved notification method with better type safety and logging

The refactoring of the notifyUser method is well-executed. The changes include:

  1. Converting to an async function with a properly typed parameter object
  2. Adding comprehensive logging for better debugging and traceability
  3. Using connectionId instead of email for deriving the durable object ID
  4. Changing the message format to include thread ID and notification type
  5. Properly awaiting the broadcast call

However, there is an opportunity to make error handling more robust:

 public async notifyUser({
   connectionId,
   threadId,
   type,
 }: {
   connectionId: string;
   threadId: string;
   type: 'start' | 'end';
 }) {
   console.log(`Notifying user ${connectionId} for thread ${threadId} with type ${type}`);
   const durableObject = env.DURABLE_MAILBOX.idFromName(`${connectionId}`);
   if (env.DURABLE_MAILBOX.get(durableObject)) {
     const stub = env.DURABLE_MAILBOX.get(durableObject);
     if (stub) {
       console.log(`Broadcasting message for thread ${threadId} with type ${type}`);
-      await stub.broadcast(threadId + ':' + type);
+      try {
+        await stub.broadcast(threadId + ':' + type);
+        console.log(`Successfully broadcasted message for thread ${threadId}`);
+      } catch (error) {
+        console.error(`Failed to broadcast message for thread ${threadId}:`, error);
+      }
-      console.log(`Successfully broadcasted message for thread ${threadId}`);
     } else {
       console.log(`No stub found for connection ${connectionId}`);
     }
   } else {
     console.log(`No durable object found for connection ${connectionId}`);
   }
 }
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 35a10b0 and 6ff91ef.

📒 Files selected for processing (12)
  • .env.example (2 hunks)
  • apps/mail/app/(full-width)/pricing/page.tsx (4 hunks)
  • apps/mail/app/(routes)/mail/layout.tsx (1 hunks)
  • apps/mail/components/mail/mail-display.tsx (2 hunks)
  • apps/mail/components/mail/mail.tsx (2 hunks)
  • apps/mail/components/party.tsx (1 hunks)
  • apps/server/package.json (1 hunks)
  • apps/server/src/lib/auth.ts (3 hunks)
  • apps/server/src/lib/driver/google.ts (2 hunks)
  • apps/server/src/main.ts (1 hunks)
  • apps/server/src/trpc/routes/brain.ts (1 hunks)
  • apps/server/wrangler.jsonc (0 hunks)
💤 Files with no reviewable changes (1)
  • apps/server/wrangler.jsonc
🧰 Additional context used
🧬 Code Graph Analysis (1)
apps/mail/app/(full-width)/pricing/page.tsx (1)
apps/mail/components/icons/icons.tsx (1)
  • CircleCheck (145-160)
🔇 Additional comments (21)
.env.example (2)

11-11: Properly formatted environment variable with quotes

Using quotes for string values in environment variables is a good practice for consistency and to avoid issues with special characters.


32-32:

Details

✅ Verification successful

New environment variable added for brain limit

This variable defines a default limit for the number of items that can be processed by the brain function, referenced in the getConnectionLimit function in the brain router.


🏁 Script executed:

#!/bin/bash
# Check where the DEFAULT_BRAIN_LIMIT is used
rg "DEFAULT_BRAIN_LIMIT" --type ts

Length of output: 139


DEFAULT_BRAIN_LIMIT Verified and Approved

I’ve confirmed that DEFAULT_BRAIN_LIMIT is referenced in apps/server/src/trpc/routes/brain.ts within the getConnectionLimit function:

  • apps/server/src/trpc/routes/brain.ts:
    return limit
      ? Number(limit)
      : Number(env.DEFAULT_BRAIN_LIMIT);

No further changes needed—this new environment variable is correctly defined and used.

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

66-71: Simplified summary generation by using direct method call

The code has been improved by replacing an external fetch call with a direct method call to env.zero.getSummary. This change:

  1. Reduces complexity by eliminating the HTTP request construction
  2. Updates the return type to match the new data structure with long and short summary fields
  3. Simplifies error handling by leveraging the existing TRPC infrastructure

This is a good refactoring that will likely improve performance and maintainability.

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

296-324: Improved attachment handling with dedicated helper method

The code now uses a dedicated helper method findAttachments to locate all attachment parts before processing them. This is a good refactoring that centralizes the attachment finding logic.

apps/mail/app/(routes)/mail/layout.tsx (2)

7-7: Header retrieval activated for notification system

The code now properly retrieves the current request headers using Next.js' headers() function, which will be passed to the NotificationProvider.


13-13: NotificationProvider integration complete

The previously commented out NotificationProvider is now active in the layout, with proper header forwarding, which enables the socket-based notification system for mail updates.

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

253-253: Updated summary data structure access path

The code now correctly accesses the summary data through the nested data.short path, reflecting changes in the underlying API response structure.


270-270: Consistent data structure update for Markdown rendering

This line properly updates the same data structure change as line 253, maintaining consistency in how summary data is accessed throughout the component.

apps/server/src/lib/auth.ts (3)

9-9: Enhanced type imports for authentication

Added proper type imports for Account and BetterAuthOptions from better-auth package for improved type checking and consistency.


208-208: Environment-aware cookie prefix implementation

Added environment-specific cookie prefix handling, which helps prevent cookie conflicts between development and production environments.


324-324: Type assertion for auth configuration

Added type assertion using satisfies BetterAuthOptions to ensure the configuration object adheres to the expected type structure, improving type safety and preventing potential configuration errors.

apps/mail/components/party.tsx (4)

2-2: Switched from Jotai to React Query

Replaced Jotai atoms with React Query's useQueryClient and a custom useThreads hook for thread management, providing better integration with the TRPC API layer and more consistent state management.

Also applies to: 5-5


9-12: Enhanced state management for thread updates

Implemented React Query for thread state management with the TRPC client and refetch capabilities, providing better integration with the server-side notifications.


15-15: Updated socket room identification

Changed the socket room identifier to use connection ID instead of email with suffix, which aligns with server-side changes in how users are notified of updates.


23-35: Improved notification message handling

Implemented a more robust message handling system that:

  1. Properly parses message format with threadId and type
  2. Invalidates specific thread queries when receiving 'end' notifications
  3. Explicitly refetches threads to ensure UI updates
  4. Includes logging for better debugging and traceability

This change aligns with server-side notification format updates and ensures proper thread data refreshing.

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

69-100: Good enhancement to label data structure

The change from a simple array of strings to an array of objects with name and usecase properties provides more context and clarity for each label. Exporting this constant allows reuse in other components, which improves code modularity.


119-121: Update correctly handles new label structure

The handleResetToDefault function has been properly updated to work with the new label structure, mapping each label object to extract the name property and construct the appropriate tag object structure.

apps/mail/app/(full-width)/pricing/page.tsx (4)

224-227: CSS class ordering improved for consistency

The reordering of CSS classes follows a consistent pattern, improving code readability and maintainability.


229-229: Consistent styling across all pricing tiers

The plan container CSS classes have been reordered consistently across all three pricing tiers (Free, Pro, and Enterprise), making the code more maintainable.

Also applies to: 275-275, 310-310


240-242: Improved readability of feature limitations

The feature limitations for free tier are now more consistently formatted, with <span> elements properly used for the usage limits and appropriate spacing between elements.

Also applies to: 248-250, 253-256


270-270: Removed upgrade handler from Free plan button

The onClick={handleUpgrade} handler has been removed from the Free plan's "Get Started" button, which is appropriate since free plan users should simply be directed to sign up rather than going through an upgrade flow.

"build": "wrangler deploy --minify --dry-run",
"deploy": "wrangler deploy --minify",
"types": "wrangler types --e staging"
"types": "wrangler types --env staging"
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

Fixed incorrect flag in wrangler command

Corrected the flag from --e staging to --env staging in the types script. This ensures the proper environment is specified when generating types.

@coderabbitai coderabbitai bot mentioned this pull request May 22, 2025
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.

3 participants