Conversation
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.
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.
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.
chore: invalidate query count on marking read/uread
Redirect User to Reconnect if credentials become invalid
|
The latest updates on your projects. Learn more about Vercel for Git ↗︎
|
|
Caution Review failedThe pull request is closed. WalkthroughThis update introduces UI and backend changes to better handle disconnected mail connections. It identifies connections missing tokens, marks them as disconnected, and provides a "Reconnect" option in the UI. The backend exposes disconnected IDs, and the database schema is updated to allow nullable access tokens. Additional improvements include cache invalidation after mail mutations, localization updates, and handling server-driven client redirects. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant SettingsPage
participant Server
participant Database
participant AuthClient
User->>SettingsPage: Visit connections settings
SettingsPage->>Server: Fetch connections list
Server->>Database: Query connections (with tokens)
Database-->>Server: Return connections data
Server-->>SettingsPage: Return { connections, disconnectedIds }
SettingsPage->>User: Display connections
alt Connection is in disconnectedIds
SettingsPage->>User: Show "Disconnected" badge and "Reconnect" button
User->>SettingsPage: Click "Reconnect"
SettingsPage->>AuthClient: linkSocial(providerId, callbackUrl)
end
sequenceDiagram
participant Client
participant Server
participant Database
Client->>Server: Mail action (e.g., mark as read)
Server->>Database: Update mail status
Database-->>Server: Ack
Server-->>Client: Success response
Client->>Client: Invalidate mail count query cache
Client->>Server: Refetch mail count
Server->>Database: Query mail count
Database-->>Server: Return count
Server-->>Client: Return updated count
sequenceDiagram
participant Client
participant Server
Client->>Server: API request (with credentials)
Server-->>Client: Response with X-Zero-Redirect header (if needed)
alt X-Zero-Redirect header present
Client->>Client: window.location.href = header value
end
Possibly related PRs
Suggested reviewers
Poem
Tip ⚡️ Faster reviews with caching
Enjoy the performance boost—your workflow just got faster. 📜 Recent review detailsConfiguration used: CodeRabbit UI 📒 Files selected for processing (8)
✨ Finishing Touches
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed 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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Actionable comments posted: 0
🔭 Outside diff range comments (1)
apps/mail/lib/hotkeys/mail-list-hotkeys.tsx (1)
139-146:⚠️ Potential issueFix incorrect mutation call in archiveEmail function
The
archiveEmailfunction callsmarkAsUnreadActionfor bulk operations instead ofbulkArchive, which would mark emails as unread rather than archiving them despite the success message saying "archived".Apply this fix:
- toast.promise(markAsUnreadAction({ ids: idsToMark }), { + toast.promise(bulkArchive({ ids: idsToMark }), { loading: t('common.actions.loading'), success: async () => { await Promise.all([refetch(), mutateStats()]); return t('common.mail.archived'); }, error: t('common.mail.failedToArchive'),
🧹 Nitpick comments (1)
apps/mail/app/(routes)/settings/connections/page.tsx (1)
50-52: Added void operator to async function calls.Using the void operator with async function calls explicitly indicates that the promise's resolution is intentionally ignored, which is good practice.
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
bun.lockis excluded by!**/*.lock
📒 Files selected for processing (21)
apps/mail/app/(routes)/settings/connections/page.tsx(3 hunks)apps/mail/components/context/thread-context.tsx(2 hunks)apps/mail/components/create/email-composer.tsx(1 hunks)apps/mail/components/mail/mail-quick-actions.tsx(2 hunks)apps/mail/components/mail/mail.tsx(1 hunks)apps/mail/components/mail/thread-display.tsx(2 hunks)apps/mail/components/ui/nav-user.tsx(1 hunks)apps/mail/lib/hotkeys/mail-list-hotkeys.tsx(1 hunks)apps/mail/locales/en.json(1 hunks)apps/mail/package.json(1 hunks)apps/mail/providers/query-provider.tsx(1 hunks)apps/server/package.json(1 hunks)apps/server/src/lib/driver/google.ts(3 hunks)apps/server/src/main.ts(1 hunks)apps/server/src/trpc/routes/connections.ts(1 hunks)apps/server/src/trpc/trpc.ts(3 hunks)packages/db/migrations/0026_smooth_norrin_radd.sql(1 hunks)packages/db/migrations/meta/0026_snapshot.json(1 hunks)packages/db/migrations/meta/_journal.json(1 hunks)packages/db/package.json(1 hunks)packages/db/src/schema.ts(1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (6)
apps/mail/providers/query-provider.tsx (1)
apps/server/src/main.ts (1)
fetch(81-88)
apps/mail/components/mail/mail.tsx (1)
apps/server/src/lib/driver/google.ts (1)
markAsRead(99-107)
apps/mail/components/mail/thread-display.tsx (1)
apps/server/src/lib/driver/google.ts (1)
markAsRead(99-107)
apps/server/src/trpc/trpc.ts (1)
packages/db/src/schema.ts (1)
connection(85-104)
apps/mail/components/context/thread-context.tsx (1)
apps/server/src/lib/driver/google.ts (2)
markAsRead(99-107)markAsUnread(109-117)
apps/server/src/trpc/routes/connections.ts (1)
packages/db/src/schema.ts (2)
connection(85-104)session(27-38)
🔇 Additional comments (35)
packages/db/package.json (1)
19-19: Consistent drizzle-kit upgrade
Bumpingdrizzle-kitfrom0.30.5to0.31.1aligns with the new schema migration. Ensure you’ve regenerated any migration snapshots (drizzle-kit generate) and validated the migration flow (drizzle-kit migrate --dry-run) with the updated version.apps/mail/package.json (1)
169-169: Align drizzle-kit version with DB package
Updateddrizzle-kitin devDependencies to0.31.1, matching the database package. No further build changes expected here.apps/server/package.json (1)
30-30: Pinningdrizzle-ormto an exact version
Switching from^0.43.1to"0.43.1"prevents automatic minor/patch upgrades. Confirm that this is intentional to avoid unplanned breakages, or consider reverting to a caret range to receive non-breaking fixes.packages/db/migrations/0026_smooth_norrin_radd.sql (1)
1-1: Allow nullableaccess_token
Dropping theNOT NULLconstraint is correct for handling disconnected connections without tokens. Verify that the schema snapshot (meta/0026_snapshot.json) is updated accordingly and that application logic gracefully handlesNULLtokens.apps/server/src/main.ts (1)
24-24: Expose custom redirect header in CORS
AddingexposeHeaders: ['X-Zero-Redirect']ensures the client can read the redirect URL. Confirm the client-side fetch logic checks this header and that no other necessary headers are missing fromallowHeaders.packages/db/migrations/meta/_journal.json (1)
186-193: LGTM: Migration addition follows established patternThe new migration entry is properly formatted and follows the established pattern for database migrations in the journal. This migration (0026_smooth_norrin_radd) will modify the "mail0_connection" table to allow NULL values for the "access_token" column, which is essential for handling disconnected mail connections.
apps/mail/locales/en.json (1)
370-372: LGTM: Localization strings added for disconnected connection UIThese new localization strings support the UI elements for disconnected mail connections, allowing for proper internationalization of the "Reconnect" button and "Disconnected" badge on the connections settings page.
apps/mail/lib/hotkeys/mail-list-hotkeys.tsx (1)
22-31: LGTM: Cache invalidation properly implemented for mail countGood implementation of cache invalidation for mail count queries after read/unread mutations. This ensures that the UI remains in sync with the actual mail state.
apps/mail/components/ui/nav-user.tsx (2)
102-104: LGTM: Brain labels cache invalidation properly implementedGood implementation of a callback to invalidate brain labels cache. The function is properly memoized with useCallback to prevent unnecessary re-renders.
113-114: LGTM: Account switching now properly refreshes brain dataThe account switching logic now correctly refreshes brain-related data (state and labels) in addition to other data types, ensuring consistent UI state after account changes.
apps/mail/components/create/email-composer.tsx (1)
886-889: Good validation check addedAdding validation to prevent AI generation when both subject and message are empty improves user experience by providing clear feedback instead of attempting to process empty content.
apps/mail/components/mail/thread-display.tsx (3)
31-31: Correctly updated import to include useQueryClientAdding useQueryClient alongside useMutation is necessary for the cache invalidation pattern implemented below.
171-173: Good addition of cache invalidation helperCreating a reusable invalidateCount function that targets the mail count query is a clean approach for ensuring the mail count stays in sync after mutations.
174-176: Improved mutation with cache invalidationAdding the onSuccess callback to the markAsRead mutation ensures the mail count is automatically refreshed after marking emails as read, maintaining UI consistency.
apps/server/src/lib/driver/google.ts (2)
296-298: Formatting improvementThis is a simple whitespace formatting change that improves code readability without changing functionality.
1037-1065: Consistent whitespace formatting in findAttachments methodThese changes standardize the whitespace formatting throughout the findAttachments method, making the code more consistent and easier to read.
apps/mail/components/mail/mail-quick-actions.tsx (3)
4-4: Correctly updated import to include useQueryClientAdding useQueryClient alongside useMutation is necessary for the cache invalidation pattern implemented below.
35-38: Good addition of cache invalidation helperCreating a reusable invalidateCount function that queries the mail count is a clean approach for maintaining consistency in the UI after mutations.
40-45: Improved mutations with cache invalidationBoth markAsRead and markAsUnread mutations now include onSuccess callbacks that invalidate the mail count cache, ensuring the UI reflects the current state after these operations.
apps/mail/providers/query-provider.tsx (1)
92-97: Great enhancement for handling redirection based on server responses!The addition of the redirect handling logic in the fetch function ensures smooth user experience when reconnection is needed. This setup correctly catches server-instructed redirects via the
X-Zero-Redirectheader and performs client-side navigation.packages/db/src/schema.ts (2)
95-95: Schema change correctly supports disconnected connections.Making the access token nullable is essential for the disconnected connections feature, allowing the system to track connections that have lost their authentication while preserving the connection record.
98-98: Good type restriction for provider ID.Explicitly typing the provider ID as a union of 'google' | 'microsoft' improves type safety and makes the code more self-documenting.
apps/mail/components/mail/mail.tsx (1)
427-435: Excellent addition of cache invalidation after mutations!The implementation properly ensures that mail counts are refreshed after marking emails as read or important. The pattern of defining an
invalidateCountfunction that's reused across mutation callbacks promotes code reuse and consistency.apps/server/src/trpc/trpc.ts (2)
20-25: Code style improvement with explicit block braces.Adding braces around the if statement body improves readability and helps prevent potential future bugs when additional statements are added.
56-73: Robust handling of invalid authentication tokens.This implementation properly handles the "invalid_grant" error case by:
- Clearing the tokens in the database
- Setting a redirect header to guide the user to reconnect
- Throwing an appropriate error with a clear message
This works well with the client-side redirect handling in query-provider.tsx to create a complete authentication recovery flow.
apps/mail/components/context/thread-context.tsx (2)
29-29: Updated imports to include useQueryClient.The import now includes both useMutation and useQueryClient from @tanstack/react-query, which is cleaner than having separate import statements.
135-143: Good cache invalidation implementation.Adding query invalidation on success callbacks ensures the mail count stays in sync with read/unread status changes. This is an important improvement for UI consistency.
The invalidateCount function is well-structured and reused for both mutations, adhering to the DRY principle. This will keep the mail count accurate after users mark threads as read or unread.
apps/mail/app/(routes)/settings/connections/page.tsx (3)
15-15: Updated auth client import.Import was updated to include both useSession and authClient, which are needed for the reconnection functionality.
20-21: Added necessary UI component imports.Added Unplug icon for the reconnect button and Badge component for the disconnected status indicator.
Also applies to: 24-24
136-192: Improved UI for disconnected connections.The implementation provides clear visual feedback and actions for disconnected accounts. This enhances user experience by:
- Showing a "Disconnected" badge with destructive styling
- Providing a "Reconnect" button that triggers the auth flow
- Maintaining the existing functionality for removing connections
The implementation follows best practices by:
- Using conditional rendering based on disconnectedIds
- Properly handling the reconnection flow with authClient.linkSocial
- Using appropriate UI components (Badge, Button) with consistent styling
apps/server/src/trpc/routes/connections.ts (3)
25-27: Added essential fields to connection query.The additional fields (providerId, accessToken, refreshToken) are needed to identify disconnected connections and provide necessary information for reconnection.
32-35: Added logic to identify disconnected connections.This code correctly identifies connections with missing tokens by checking for null/undefined accessToken or refreshToken. This is critical for the disconnection detection feature.
36-48: Enhanced API response structure.The response now includes two key properties:
- connections: Filtered connection data (excluding sensitive tokens)
- disconnectedIds: List of connection IDs missing tokens
This structure provides the frontend with exactly what it needs while maintaining security by not exposing sensitive token data.
packages/db/migrations/meta/0026_snapshot.json (2)
146-157: Database schema update for nullable tokens.The access_token and refresh_token columns are correctly configured with "notNull": false to support the concept of disconnected connections.
This schema change aligns with the application's need to handle connections that have lost their authentication tokens.
1-822: Database migration snapshot looks correct.The migration snapshot properly defines all tables with appropriate constraints, relationships, and default values. The main changes supporting disconnected connections are correctly implemented.
style(ui): increase max-width of email display in nav-user after gauge was removed
Removed redundant checks for connection tokens and streamlined error handling in server utilities. Enhanced redirect logic in the query provider to avoid unnecessary navigation when already on the target path.
Added console logs to inspect `redirectPath`, `currentPath`, and test their states. This will help diagnose issues and ensure the redirect logic is functioning correctly.
Eliminated unnecessary debugging logs to clean up the code and improve readability. This helps maintain a more production-ready codebase with fewer distractions during development.
…s-fix Fix redirection for Invalid Connections
Summary by CodeRabbit
New Features
Improvements
Bug Fixes
Localization
Chores