Skip to content

Comments

Redirect User to Reconnect if credentials become invalid#945

Merged
MrgSub merged 9 commits intostagingfrom
dakdevs/staging/broken-connections
May 12, 2025
Merged

Redirect User to Reconnect if credentials become invalid#945
MrgSub merged 9 commits intostagingfrom
dakdevs/staging/broken-connections

Conversation

@dakdevs
Copy link
Contributor

@dakdevs dakdevs commented May 12, 2025

Description

Updated error logic to translate the invalid_grant error into nulling out the connection.accessToken and connection.refreshToken. Once it is nulled out it will redirect the user to the /settings/connections page and display disconnected.

image

When clicking to reconnect the user will be directed through the correct provider connection flow.


Type of Change

  • ✨ New feature (non-breaking change which adds functionality)
  • 🎨 UI/UX improvement

Areas Affected

Please check all that apply:

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

Testing Done

Describe the tests you've done:

  • Manual testing performed

Security Considerations

For changes involving data or authentication:

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

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
  • My changes generate no new warnings

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 CodeRabbit

  • New Features

    • Added AI-powered email subject generation with a dedicated button in the email composer.
    • Introduced "Disconnected" badge and "Reconnect" button for disconnected accounts in settings, enabling direct reconnection.
    • Enhanced thread navigation by automatically moving to the next thread after certain actions.
  • Bug Fixes

    • Fixed visibility of the message length control button in the email composer.
  • Localization

    • Added new English strings for "reconnect" and "disconnected" in connection settings.
  • Error Handling

    • Improved handling of invalid or missing tokens, providing clearer feedback and redirecting users when necessary.
  • Database

    • Updated the schema to allow nullable access tokens and improved provider ID typing for connections.

dakdevs added 2 commits May 11, 2025 22:35
Upgraded `drizzle-kit` to version 0.31.1 for improved functionality. Updated the schema to refine token fields and added logic to handle invalid tokens by nullifying them and redirecting users to reconnect. Enhanced connections API to identify and return disconnected connections for better user experience.
This migration allows the "access_token" column in the "mail0_connection" table to accept null values. Updated meta files reflect this schema change, including the snapshot and migration journal.
@vercel
Copy link

vercel bot commented May 12, 2025

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

Name Status Preview Comments Updated (UTC)
0 ✅ Ready (Inspect) Visit Preview 💬 Add feedback May 12, 2025 5:45pm

@coderabbitai
Copy link
Contributor

coderabbitai bot commented May 12, 2025

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Walkthrough

This update introduces the ability to detect and handle disconnected email account connections in the UI, including a "Reconnect" feature. It adds an AI-powered email subject generation function, updates localization and error handling, and modifies the database schema and API to support nullable access tokens and track disconnected states. Minor UI and code improvements are also included.

Changes

File(s) Change Summary
apps/mail/app/(routes)/settings/connections/page.tsx
apps/mail/locales/en.json
Refactored connections UI to show "Disconnected" badge and "Reconnect" button for disconnected accounts; added new localization keys for "reconnect" and "disconnected".
apps/mail/components/create/email-composer.tsx Added AI-powered subject generation feature, new UI button, loading state, and logic to auto-generate subject if missing; minor UI fixes and style tweaks.
apps/mail/components/mail/mail-list.tsx Enhanced thread navigation logic with new state hooks and a callback to move to the next thread after an action; minor class name adjustment.
apps/mail/providers/query-provider.tsx Extended error handling to redirect users to settings when tokens are invalid, using the disconnected connection ID.
apps/server/src/trpc/routes/ai/compose.ts
apps/server/src/trpc/routes/ai/index.ts
Added new generateEmailSubject mutation for generating email subjects via AI; updated router to expose the new endpoint.
apps/server/src/trpc/routes/connections.ts Modified connections API to include provider ID and tokens, and to return a list of disconnected connection IDs based on missing tokens.
apps/server/src/trpc/trpc.ts Updated middleware to clear tokens and throw a specific error when the driver returns 'invalid_grant', marking connections as disconnected.
apps/server/src/lib/driver/google.ts Minor formatting and whitespace cleanup; no functional changes.
packages/db/migrations/0026_smooth_norrin_radd.sql
packages/db/migrations/meta/0026_snapshot.json
packages/db/migrations/meta/_journal.json
Database migration to allow nullable access tokens in the mail0_connection table; updated schema snapshot and migration journal.
packages/db/src/schema.ts Changed connection table: made accessToken nullable and restricted providerId to 'google' or 'microsoft'.
packages/db/package.json Updated drizzle-kit dev dependency from 0.30.5 to 0.31.1.

Sequence Diagram(s)

1. Disconnected Connection Handling and Reconnect Flow

sequenceDiagram
    participant User
    participant UI
    participant API
    participant AuthClient

    User->>UI: Visit Connections Settings
    UI->>API: Fetch connections list
    API-->>UI: Return connections + disconnectedIds
    UI->>User: Show "Disconnected" badge and "Reconnect" button
    User->>UI: Click "Reconnect"
    UI->>AuthClient: linkSocial(providerId, callbackUrl)
    AuthClient-->>UI: Reconnection flow (OAuth, etc.)
    UI->>API: Refetch connections
Loading

2. AI-powered Email Subject Generation

sequenceDiagram
    participant User
    participant EmailComposer
    participant API

    User->>EmailComposer: Click "Generate Subject"
    EmailComposer->>API: generateEmailSubject(message)
    API-->>EmailComposer: Return generated subject
    EmailComposer->>User: Populate subject input with AI-generated subject
Loading

Suggested reviewers

  • MrgSub
  • ahmetskilinc

Poem

🐇✨
In fields of code where emails hop,
Disconnected links now get a pop—
A badge, a button, a second chance,
AI writes subjects in a glance!
Tokens nullable, flows refined,
The rabbit leaps ahead, aligned.
Hooray for features, so well-designed!


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.

@dakdevs dakdevs marked this pull request as ready for review May 12, 2025 05:40
@dakdevs dakdevs force-pushed the dakdevs/staging/broken-connections branch from 829f9f6 to f01a54e Compare May 12, 2025 05:42
@dakdevs dakdevs changed the base branch from main to staging May 12, 2025 05:42
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.

Caution

Inline review comments failed to post. This is likely due to GitHub's limits when posting large numbers of comments. If you are seeing this consistently it is likely a permissions issue. Please check "Moderation" -> "Code review limits" under your organization settings.

Actionable comments posted: 1

🛑 Comments failed to post (1)
apps/mail/components/create/email-composer.tsx (1)

361-366: 🛠️ Refactor suggestion

Consider adding error handling to the subject generation function.

The function handles the happy path well but doesn't have explicit error handling unlike other similar functions in this component.

 const handleGenerateSubject = async () => {
+  try {
     setIsGeneratingSubject(true);
     const { subject } = await generateEmailSubject({ message: editor.getText() });
     setValue('subject', subject);
+  } catch (error) {
+    console.error('Error generating subject:', error);
+    toast.error('Failed to generate subject');
+  } finally {
     setIsGeneratingSubject(false);
+  }
 };
📝 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.

  const handleGenerateSubject = async () => {
    try {
      setIsGeneratingSubject(true);
      const { subject } = await generateEmailSubject({ message: editor.getText() });
      setValue('subject', subject);
    } catch (error) {
      console.error('Error generating subject:', error);
      toast.error('Failed to generate subject');
    } finally {
      setIsGeneratingSubject(false);
    }
  };

Upgraded "drizzle-kit" to 0.31.1 and adjusted "drizzle-orm" versioning for consistency. Additionally, updated Radix dependencies to their latest versions to ensure compatibility and improvements.
Introduced the 'X-Zero-Redirect' header to streamline disconnection handling. Removed client-side redirection logic tied to "Invalid tokens" and updated the fetch interceptor to handle redirects based on the new header. This ensures a cleaner and more centralized redirection flow.
Added `X-Zero-Redirect` to both allowed and exposed headers in CORS configuration to ensure it can be utilized by the client. Removed an unnecessary TRPC error throw related to connection authorization for cleaner response handling.
dakdevs added 2 commits May 11, 2025 23:48
The X-Zero-Redirect header logic was unnecessary and has been removed to streamline error handling. Error messages and redirection logic are now handled solely through TRPCError.
The error message was unnecessary as the 'UNAUTHORIZED' code is sufficient to convey the issue. This simplifies the error handling and avoids potential redundancy or confusion in the system behavior.
@MrgSub MrgSub merged commit 0c3dc0f into staging May 12, 2025
5 checks passed
@MrgSub MrgSub deleted the dakdevs/staging/broken-connections branch May 12, 2025 18:05
@coderabbitai coderabbitai bot mentioned this pull request May 12, 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