Skip to content

Comments

Uncomment and enable automatic draft generation in thread workflow#1771

Merged
MrgSub merged 1 commit intostagingfrom
_ZERO_Uncomment_and_enable_automatic_draft_generation_in_thread_workflow
Jul 20, 2025
Merged

Uncomment and enable automatic draft generation in thread workflow#1771
MrgSub merged 1 commit intostagingfrom
_ZERO_Uncomment_and_enable_automatic_draft_generation_in_thread_workflow

Conversation

@MrgSub
Copy link
Collaborator

@MrgSub MrgSub commented Jul 20, 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

Enabled automatic draft generation in the thread workflow by uncommenting and activating related logic.

  • New Features
    • Threads now automatically generate a draft reply when a response is needed, based on email intent analysis.

Summary by CodeRabbit

  • New Features

    • Automatic draft generation for certain email threads has been re-enabled, allowing drafts to be created based on message intent.
  • User Interface Updates

    • Redesigned mail list header for improved search, filter, and bulk selection controls with enhanced layout and shortcut hints.
    • Disabled the AutoLabelingSettings interface to streamline user experience.
  • Bug Fixes

    • Restored previously disabled functionality for generating and logging automatic drafts.

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.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Jul 20, 2025

Caution

Review failed

The pull request is closed.

Walkthrough

Previously commented-out code for automatic draft generation in the thread workflow was restored. This includes re-enabling imports and reintegrating logic that analyzes the latest email's intent, determines if a draft should be generated, and creates the draft if appropriate. No new logic or error handling was introduced.

Changes

File(s) Change Summary
apps/server/src/pipelines.effect.ts Uncommented imports and restored the automatic draft generation block within runThreadWorkflow.
apps/mail/components/context/command-palette-context.tsx Renamed command group label from "Search & Filter" to "Search".
apps/mail/components/mail/mail.tsx Disabled AutoLabelingSettings component by commenting it out; restructured mail list header layout to conditionally show search, filters, and bulk selection controls; minor style adjustments.

Sequence Diagram(s)

sequenceDiagram
    participant ThreadWorkflow
    participant ThreadWorkflowUtils
    participant Agent

    ThreadWorkflow->>ThreadWorkflowUtils: analyzeEmailIntent(latestMessage)
    ThreadWorkflowUtils-->>ThreadWorkflow: intent
    ThreadWorkflow->>ThreadWorkflowUtils: shouldGenerateDraft(intent)
    ThreadWorkflowUtils-->>ThreadWorkflow: shouldGenerate
    alt shouldGenerate
        ThreadWorkflow->>ThreadWorkflowUtils: generateAutomaticDraft(thread, intent)
        ThreadWorkflowUtils-->>ThreadWorkflow: draftContent
        ThreadWorkflow->>Agent: createDraft(draftContent, metadata)
        Agent-->>ThreadWorkflow: draftId or error
        ThreadWorkflow->>ThreadWorkflow: log draftId or error
    else do nothing
    end
Loading

Possibly related PRs

Suggested reviewers

  • needleXO

Poem

A draft in the warren, once hidden away,
Now hops back to work, no longer astray.
Intentions are checked, replies take their chance,
With code uncommented, drafts now advance.
🐇✨


📜 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 80e71aa and 2c8f729.

📒 Files selected for processing (3)
  • apps/mail/components/context/command-palette-context.tsx (1 hunks)
  • apps/mail/components/mail/mail.tsx (6 hunks)
  • apps/server/src/pipelines.effect.ts (2 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.

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

1 issue found across 1 file • 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 replyTo = latestMessage.sender?.email || '';
const cc =
latestMessage.cc
Copy link
Contributor

Choose a reason for hiding this comment

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

Calling .filter on the result of an optional chain can throw when latestMessage.cc is undefined, crashing the workflow

Prompt for AI agents
Address the following comment on apps/server/src/pipelines.effect.ts at line 497:

<comment>Calling .filter on the result of an optional chain can throw when latestMessage.cc is undefined, crashing the workflow</comment>

<file context>
@@ -17,11 +17,11 @@ import {
   SummarizeThread,
   ThreadLabels,
 } from &#39;./lib/brain.fallback.prompts&#39;;
-// import {
-//   generateAutomaticDraft,
-//   shouldGenerateDraft,
-//   analyzeEmailIntent,
-// } from &#39;./thread-workflow-utils&#39;;
+import {
+  generateAutomaticDraft,
+  shouldGenerateDraft,
+  analyzeEmailIntent,
+} from &#39;./thread-workflow-utils&#39;;
 import { defaultLabels, EPrompts, EProviders, type ParsedMessage, type Sender } from &#39;./types&#39;;
 import { getZeroAgent } from &#39;./lib/server-utils&#39;;
 import { type gmail_v1 } from &#39;@googleapis/gmail&#39;;
@@ -452,89 +452,91 @@ export const runThreadWorkflow = (
         return &#39;Thread has no messages&#39;;
       }
 
-      // const autoDraftId = yield* Effect.tryPromise({
-      //   try: async () =&gt; {
-      //     if (!shouldGenerateDraft(thread, foundConnection)) {
-      //       console.log(&#39;[THREAD_WORKFLOW] Skipping draft generation for thread:&#39;, threadId);
-      //       return null;
-      //     }
-
-      //     const latestMessage = thread.messages[thread.messages.length - 1];
-      //     const emailIntent = analyzeEmailIntent(latestMessage);
-
-      //     console.log(&#39;[THREAD_WORKFLOW] Analyzed email intent:&#39;, {
-      //       threadId,
-      //       isQuestion: emailIntent.isQuestion,
-      //       isRequest: emailIntent.isRequest,
-      //       isMeeting: emailIntent.isMeeting,
-      //       isUrgent: emailIntent.isUrgent,
-      //     });
-
-      //     if (
-      //       !emailIntent.isQuestion &amp;&amp;
-      //       !emailIntent.isRequest &amp;&amp;
-      //       !emailIntent.isMeeting &amp;&amp;
-      //       !emailIntent.isUrgent
-      //     ) {
-      //       console.log(
-      //         &#39;[THREAD_WORKFLOW] Email does not require a response, skipping draft generation&#39;,
-      //       );
-      //       return null;
-      //     }
-
-      //     console.log(&#39;[THREAD_WORKFLOW] Generating automatic draft for thread:&#39;, threadId);
-      //     const draftContent = await generateAutomaticDraft(
-      //       connectionId.toString(),
-      //       thread,
-      //       foundConnection,
-      //     );
-
-      //     if (draftContent) {
-      //       const latestMessage = thread.messages[thread.messages.length - 1];
-
-      //       const replyTo = latestMessage.sender?.email || &#39;&#39;;
-      //       const cc =
-      //         latestMessage.cc
-      //           ?.map((r) =&gt; r.email)
-      //           .filter((email) =&gt; email &amp;&amp; email !== foundConnection.email) || [];
-
-      //       const originalSubject = latestMessage.subject || &#39;&#39;;
-      //       const replySubject = originalSubject.startsWith(&#39;Re: &#39;)
-      //         ? originalSubject
-      //         : `Re: ${originalSubject}`;
-
-      //       const draftData = {
-      //         to: replyTo,
-      //         cc: cc.join(&#39;, &#39;),
-      //         bcc: &#39;&#39;,
-      //         subject: replySubject,
-      //         message: draftContent,
-      //         attachments: [],
-      //         id: null,
-      //         threadId: threadId.toString(),
-      //         fromEmail: foundConnection.email,
-      //       };
-
-      //       try {
-      //         const createdDraft = await agent.createDraft(draftData);
-      //         console.log(&#39;[THREAD_WORKFLOW] Created automatic draft:&#39;, {
-      //           threadId,
-      //           draftId: createdDraft?.id,
-      //         });
-      //         return createdDraft?.id || null;
-      //       } catch (error) {
-      //         console.log(&#39;[THREAD_WORKFLOW] Failed to create automatic draft:&#39;, {
-      //           threadId,
-      //           error: error instanceof Error ? error.message : String(error),
-      //         });
-      //         return null;
-      //       }
-      //     }
-
-      //     return null;
-      //   },
-      //   catch: (error) =&gt; ({ _tag: &#39;DatabaseError&#39; as const, error }),
-      // });
+      const autoDraftId = yield* Effect.tryPromise({
+        try: async () =&gt; {
+          if (!shouldGenerateDraft(thread, foundConnection)) {
+            console.log(&#39;[THREAD_WORKFLOW] Skipping draft generation for thread:&#39;, threadId);
+            return null;
+          }
+
+          const latestMessage = thread.messages[thread.messages.length - 1];
+          const emailIntent = analyzeEmailIntent(latestMessage);
+
+          console.log(&#39;[THREAD_WORKFLOW] Analyzed email intent:&#39;, {
+            threadId,
+            isQuestion: emailIntent.isQuestion,
+            isRequest: emailIntent.isRequest,
+            isMeeting: emailIntent.isMeeting,
+            isUrgent: emailIntent.isUrgent,
+          });
+
+          if (
+            !emailIntent.isQuestion &amp;&amp;
+            !emailIntent.isRequest &amp;&amp;
+            !emailIntent.isMeeting &amp;&amp;
+            !emailIntent.isUrgent
+          ) {
+            console.log(
+              &#39;[THREAD_WORKFLOW] Email does not require a response, skipping draft generation&#39;,
+            );
+            return null;
+          }
+
+          console.log(&#39;[THREAD_WORKFLOW] Generating automatic draft for thread:&#39;, threadId);
+          const draftContent = await generateAutomaticDraft(
+            connectionId.toString(),
+            thread,
+            foundConnection,
+          );
+
+          if (draftContent) {
+            const latestMessage = thread.messages[thread.messages.length - 1];
+
+            const replyTo = latestMessage.sender?.email || &#39;&#39;;
+            const cc =
+              latestMessage.cc
+                ?.map((r) =&gt; r.email)
+                .filter((email) =&gt; email &amp;&amp; email !== foundConnection.email) || [];
+
+            const originalSubject = latestMessage.subject || &#39;&#39;;
+            const replySubject = originalSubject.startsWith(&#39;Re: &#39;)
+              ? originalSubject
+              : `Re: ${originalSubject}`;
+
+            const draftData = {
+              to: replyTo,
+              cc: cc.join(&#39;, &#39;),
+              bcc: &#39;&#39;,
+              subject: replySubject,
+              message: draftContent,
+              attachments: [],
+              id: null,
+              threadId: threadId.toString(),
+              fromEmail: foundConnection.email,
+            };
+
+            try {
+              const createdDraft = await agent.createDraft(draftData);
+              console.log(&#39;[THREAD_WORKFLOW] Created automatic draft:&#39;, {
+                threadId,
+                draftId: createdDraft?.id,
+              });
+              return createdDraft?.id || null;
+            } catch (error) {
+              console.log(&#39;[THREAD_WORKFLOW] Failed to create automatic draft:&#39;, {
+                threadId,
+                error: error instanceof Error ? error.message : String(error),
+              });
+              return null;
+            }
+          }
+
+          return null;
+        },
+        catch: (error) =&gt; ({ _tag: &#39;DatabaseError&#39; as const, error }),
+      });
+
+      yield* Console.log(&#39;[THREAD_WORKFLOW] &#39; + autoDraftId);
 
       yield* Console.log(&#39;[THREAD_WORKFLOW] Processing thread messages and vectorization&#39;);
 
</file context>

@MrgSub MrgSub force-pushed the _ZERO_Uncomment_and_enable_automatic_draft_generation_in_thread_workflow branch from 80e71aa to 2c8f729 Compare July 20, 2025 21:24
Copy link
Collaborator Author

MrgSub commented Jul 20, 2025

Merge activity

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

@MrgSub MrgSub merged commit 2e44025 into staging Jul 20, 2025
6 of 8 checks passed
@MrgSub MrgSub deleted the _ZERO_Uncomment_and_enable_automatic_draft_generation_in_thread_workflow branch July 20, 2025 21:25
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: Bulk Selection UI Removal Causes Grid Layout Issues

The SelectAllCheckbox component has been removed from the UI (its import is commented out), eliminating the "select all" functionality for bulk email operations. This also causes a grid layout issue in the mail list header: when bulk selection is active, the search section is removed, and the remaining elements (SidebarToggle, refresh button, bulk selection UI) lack explicit column spans, leading to improper spacing and unpredictable layout.

apps/mail/components/mail/mail.tsx#L35-L580

import { useHotkeysContext } from 'react-hotkeys-hook';
// import SelectAllCheckbox from './select-all-checkbox';
import { useNavigate, useParams } from 'react-router';
import { useMail } from '@/components/mail/use-mail';
import { SidebarToggle } from '../ui/sidebar-toggle';
import { PricingDialog } from '../ui/pricing-dialog';
// import { Textarea } from '@/components/ui/textarea';
// import { useBrainState } from '@/hooks/use-summary';
import { clearBulkSelectionAtom } from './use-mail';
import AISidebar from '@/components/ui/ai-sidebar';
import { useThreads } from '@/hooks/use-threads';
// import { useBilling } from '@/hooks/use-billing';
import AIToggleButton from '../ai-toggle-button';
import { useIsMobile } from '@/hooks/use-mobile';
// import { Switch } from '@/components/ui/switch';
import { Button } from '@/components/ui/button';
import { useLabels } from '@/hooks/use-labels';
import { useSession } from '@/lib/auth-client';
// import { ScrollArea } from '../ui/scroll-area';
// import { Label } from '@/components/ui/label';
// import { Input } from '@/components/ui/input';
import { cn } from '@/lib/utils';
import { m } from '@/paraglide/messages';
import { useQueryState } from 'nuqs';
import { useAtom } from 'jotai';
// import { toast } from 'sonner';
// interface ITag {
// id: string;
// name: string;
// usecase: string;
// text: string;
// }
export const defaultLabels = [
{
name: 'to respond',
usecase: 'emails you need to respond to. NOT sales, marketing, or promotions.',
},
{
name: 'FYI',
usecase:
'emails that are not important, but you should know about. NOT sales, marketing, or promotions.',
},
{
name: 'comment',
usecase:
'Team chats in tools like Google Docs, Slack, etc. NOT marketing, sales, or promotions.',
},
{
name: 'notification',
usecase: 'Automated updates from services you use. NOT sales, marketing, or promotions.',
},
{
name: 'promotion',
usecase: 'Sales, marketing, cold emails, special offers or promotions. NOT to respond to.',
},
{
name: 'meeting',
usecase: 'Calendar events, invites, etc. NOT sales, marketing, or promotions.',
},
{
name: 'billing',
usecase: 'Billing notifications. NOT sales, marketing, or promotions.',
},
];
// const AutoLabelingSettings = () => {
// const trpc = useTRPC();
// const [open, setOpen] = useState(false);
// const { data: storedLabels, refetch: refetchStoredLabels } = useQuery(
// trpc.brain.getLabels.queryOptions(void 0, {
// staleTime: 1000 * 60 * 60, // 1 hour
// }),
// );
// const { mutateAsync: updateLabels, isPending } = useMutation(
// trpc.brain.updateLabels.mutationOptions({
// onSuccess: () => {
// refetchStoredLabels();
// },
// }),
// );
// const [, setPricingDialog] = useQueryState('pricingDialog');
// const [labels, setLabels] = useState<ITag[]>([]);
// const [newLabel, setNewLabel] = useState({ name: '', usecase: '' });
// const { mutateAsync: EnableBrain, isPending: isEnablingBrain } = useMutation(
// trpc.brain.enableBrain.mutationOptions(),
// );
// const { mutateAsync: DisableBrain, isPending: isDisablingBrain } = useMutation(
// trpc.brain.disableBrain.mutationOptions(),
// );
// const { data: brainState, refetch: refetchBrainState } = useBrainState();
// const { isLoading, isPro } = useBilling();
// useEffect(() => {
// if (storedLabels) {
// setLabels(
// storedLabels.map((label) => ({
// id: label.name,
// name: label.name,
// text: label.name,
// usecase: label.usecase,
// })),
// );
// }
// }, [storedLabels]);
// const handleResetToDefault = useCallback(() => {
// setLabels(
// defaultLabels.map((label) => ({
// id: label.name,
// name: label.name,
// text: label.name,
// usecase: label.usecase,
// })),
// );
// }, [storedLabels]);
// const handleAddLabel = () => {
// if (!newLabel.name || !newLabel.usecase) return;
// setLabels([...labels, { id: newLabel.name, ...newLabel, text: newLabel.name }]);
// setNewLabel({ name: '', usecase: '' });
// };
// const handleDeleteLabel = (id: string) => {
// setLabels(labels.filter((label) => label.id !== id));
// };
// const handleUpdateLabel = (id: string, field: 'name' | 'usecase', value: string) => {
// setLabels(
// labels.map((label) =>
// label.id === id
// ? { ...label, [field]: value, text: field === 'name' ? value : label.text }
// : label,
// ),
// );
// };
// const handleSubmit = async () => {
// const updatedLabels = labels.map((label) => ({
// name: label.name,
// usecase: label.usecase,
// }));
// if (newLabel.name.trim() && newLabel.usecase.trim()) {
// updatedLabels.push({
// name: newLabel.name,
// usecase: newLabel.usecase,
// });
// }
// await updateLabels({ labels: updatedLabels });
// setOpen(false);
// toast.success('Labels updated successfully, Zero will start using them.');
// };
// const handleEnableBrain = useCallback(async () => {
// toast.promise(EnableBrain, {
// loading: 'Enabling autolabeling...',
// success: 'Autolabeling enabled successfully',
// error: 'Failed to enable autolabeling',
// finally: async () => {
// await refetchBrainState();
// },
// });
// }, []);
// const handleDisableBrain = useCallback(async () => {
// toast.promise(DisableBrain, {
// loading: 'Disabling autolabeling...',
// success: 'Autolabeling disabled successfully',
// error: 'Failed to disable autolabeling',
// finally: async () => {
// await refetchBrainState();
// },
// });
// }, []);
// const handleToggleAutolabeling = useCallback(() => {
// if (brainState?.enabled) {
// handleDisableBrain();
// } else {
// handleEnableBrain();
// }
// }, [brainState?.enabled]);
// return (
// <Dialog
// open={open}
// onOpenChange={(state) => {
// if (!isPro) {
// setPricingDialog('true');
// } else {
// setOpen(state);
// }
// }}
// >
// <DialogTrigger asChild>
// <div className="flex items-center gap-2">
// <Switch
// disabled={isEnablingBrain || isDisablingBrain || isLoading}
// checked={brainState?.enabled ?? false}
// />
// <span className="text-muted-foreground cursor-pointer text-xs font-medium">
// Auto label
// </span>
// </div>
// </DialogTrigger>
// <DialogContent showOverlay className="max-w-2xl">
// <DialogHeader>
// <div className="flex items-center justify-between">
// <DialogTitle>Label Settings</DialogTitle>
// <button
// onClick={handleToggleAutolabeling}
// className="bg-offsetLight dark:bg-offsetDark flex items-center gap-2 rounded-lg border px-1.5 py-1"
// >
// <span className="text-muted-foreground text-sm">
// {isEnablingBrain || isDisablingBrain
// ? 'Updating...'
// : brainState?.enabled
// ? 'Disable autolabeling'
// : 'Enable autolabeling'}
// </span>
// <Switch checked={brainState?.enabled} />
// </button>
// </div>
// <DialogDescription className="mt-2">
// Configure the labels that Zero uses to automatically organize your emails.
// </DialogDescription>
// </DialogHeader>
// <ScrollArea className="h-[400px]">
// <div className="space-y-3">
// {labels.map((label, index) => (
// <div
// key={label.id}
// className="bg-card group relative space-y-2 rounded-lg border p-4 shadow-sm transition-shadow hover:shadow-md"
// >
// <div className="flex items-center justify-between">
// <Label
// htmlFor={`label-name-${index}`}
// className="text-muted-foreground text-xs font-medium"
// >
// Label Name
// </Label>
// <Button
// variant="ghost"
// size="icon"
// className="h-6 w-6 transition-opacity group-hover:opacity-100"
// onClick={() => handleDeleteLabel(label.id)}
// >
// <Trash className="h-3 w-3 fill-[#F43F5E]" />
// </Button>
// </div>
// <Input
// id={`label-name-${index}`}
// type="text"
// value={label.name}
// onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
// handleUpdateLabel(label.id, 'name', e.target.value)
// }
// className="h-8"
// placeholder="e.g., Important, Follow-up, Archive"
// />
// <div className="space-y-2">
// <Label
// htmlFor={`label-usecase-${index}`}
// className="text-muted-foreground text-xs font-medium"
// >
// Use Case Description
// </Label>
// <Textarea
// id={`label-usecase-${index}`}
// value={label.usecase}
// onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) =>
// handleUpdateLabel(label.id, 'usecase', e.target.value)
// }
// className="min-h-[60px] resize-none"
// placeholder="Describe when this label should be applied..."
// />
// </div>
// </div>
// ))}
// <div className="bg-muted/50 mt-3 space-y-2 rounded-lg border border-dashed p-4">
// <div className="space-y-2">
// <Label
// htmlFor="new-label-name"
// className="text-muted-foreground text-xs font-medium"
// >
// New Label Name
// </Label>
// <Input
// id="new-label-name"
// type="text"
// value={newLabel.name}
// onChange={(e: React.ChangeEvent<HTMLInputElement>) =>
// setNewLabel({ ...newLabel, name: e.target.value })
// }
// className="h-8 dark:bg-[#141414]"
// placeholder="Enter a new label name"
// />
// </div>
// <div className="space-y-2">
// <Label
// htmlFor="new-label-usecase"
// className="text-muted-foreground text-xs font-medium"
// >
// Use Case Description
// </Label>
// <Textarea
// id="new-label-usecase"
// value={newLabel.usecase}
// onChange={(e: React.ChangeEvent<HTMLTextAreaElement>) =>
// setNewLabel({ ...newLabel, usecase: e.target.value })
// }
// className="min-h-[60px] resize-none dark:bg-[#141414]"
// placeholder="Describe when this label should be applied..."
// />
// </div>
// <Button
// className="mt-2 h-8 w-full"
// onClick={handleAddLabel}
// disabled={!newLabel.name || !newLabel.usecase}
// >
// Add New Label
// </Button>
// </div>
// </div>
// </ScrollArea>
// <DialogFooter className="mt-4">
// <div className="flex w-full justify-end gap-2">
// <Button size="xs" variant="outline" onClick={handleResetToDefault}>
// Default Labels
// </Button>
// <Button size="xs" onClick={handleSubmit} disabled={isPending}>
// Save Changes
// </Button>
// </div>
// </DialogFooter>
// </DialogContent>
// </Dialog>
// );
// };
export function MailLayout() {
const params = useParams<{ folder: string }>();
const folder = params?.folder ?? 'inbox';
const [mail, setMail] = useMail();
const [, clearBulkSelection] = useAtom(clearBulkSelectionAtom);
const isMobile = useIsMobile();
const navigate = useNavigate();
const { data: session, isPending } = useSession();
const prevFolderRef = useRef(folder);
const { enableScope, disableScope } = useHotkeysContext();
const { data: activeConnection } = useActiveConnection();
const { activeFilters, clearAllFilters } = useCommandPalette();
const [, setIsCommandPaletteOpen] = useQueryState('isCommandPaletteOpen');
useEffect(() => {
if (prevFolderRef.current !== folder && mail.bulkSelected.length > 0) {
clearBulkSelection();
}
prevFolderRef.current = folder;
}, [folder, mail.bulkSelected.length, clearBulkSelection]);
useEffect(() => {
if (!session?.user && !isPending) {
navigate('/login');
}
}, [session?.user, isPending]);
const [{ isFetching, refetch: refetchThreads }] = useThreads();
const isDesktop = useMediaQuery('(min-width: 768px)');
const [threadId] = useQueryState('threadId');
useEffect(() => {
if (threadId) {
console.log('Enabling thread-display scope, disabling mail-list');
enableScope('thread-display');
disableScope('mail-list');
} else {
console.log('Enabling mail-list scope, disabling thread-display');
enableScope('mail-list');
disableScope('thread-display');
}
return () => {
console.log('Cleaning up mail/thread scopes');
disableScope('thread-display');
disableScope('mail-list');
};
}, [threadId, enableScope, disableScope]);
const handleMailListMouseEnter = useCallback(() => {
enableScope('mail-list');
}, [enableScope]);
const handleMailListMouseLeave = useCallback(() => {
disableScope('mail-list');
}, [disableScope]);
// Add mailto protocol handler registration
useEffect(() => {
// Register as a mailto protocol handler if browser supports it
if (typeof window !== 'undefined' && 'registerProtocolHandler' in navigator) {
try {
// Register the mailto protocol handler
// When a user clicks a mailto: link, it will be passed to our dedicated handler
// which will:
// 1. Parse the mailto URL to extract email, subject and body
// 2. Create a draft with these values
// 3. Redirect to the compose page with just the draft ID
// This ensures we don't keep the email content in the URL
navigator.registerProtocolHandler('mailto', `/api/mailto-handler?mailto=%s`);
} catch (error) {
console.error('Failed to register protocol handler:', error);
}
}
}, []);
const defaultCategoryId = useDefaultCategoryId();
const [category] = useQueryState('category', { defaultValue: defaultCategoryId });
return (
<TooltipProvider delayDuration={0}>
<PricingDialog />
<div className="rounded-inherit relative z-[5] flex p-0 md:mr-0.5 md:mt-1">
<ResizablePanelGroup
direction="horizontal"
autoSaveId="mail-panel-layout"
className="rounded-inherit overflow-hidden"
>
<ResizablePanel
defaultSize={35}
minSize={35}
maxSize={35}
className={cn(
`bg-panelLight dark:bg-panelDark mb-1 w-fit shadow-sm md:mr-[3px] md:rounded-2xl lg:flex lg:h-[calc(100dvh-8px)] lg:shadow-sm`,
isDesktop && threadId && 'hidden lg:block',
)}
onMouseEnter={handleMailListMouseEnter}
onMouseLeave={handleMailListMouseLeave}
>
<div className="w-full md:h-[calc(100dvh-10px)]">
<div
className={cn(
'sticky top-0 z-[15] flex items-center justify-between gap-1.5 p-2 pb-0 transition-colors',
)}
>
<div className="w-full">
<div className="grid grid-cols-12 gap-2">
<SidebarToggle className="col-span-1 h-fit px-2" />
{mail.bulkSelected.length === 0 ? (
<div className="col-span-10 flex gap-2">
<Button
variant="outline"
className={cn(
'text-muted-foreground relative flex h-8 w-full select-none items-center justify-start overflow-hidden rounded-lg border bg-white pl-2 text-left text-sm font-normal shadow-none ring-0 focus-visible:ring-0 focus-visible:ring-offset-0 dark:border-none dark:bg-[#141414]',
)}
onClick={() => setIsCommandPaletteOpen('true')}
>
<Search className="fill-[#71717A] dark:fill-[#6F6F6F]" />
<span className="hidden truncate pr-20 lg:inline-block">
{activeFilters.length > 0
? activeFilters.map((f) => f.display).join(', ')
: 'Search'}
</span>
<span className="inline-block truncate pr-20 lg:hidden">
{activeFilters.length > 0
? `${activeFilters.length} filter${activeFilters.length > 1 ? 's' : ''}`
: 'Search'}
</span>
<span className="absolute right-[0rem] flex items-center gap-1">
{/* {activeFilters.length > 0 && (
<Badge variant="secondary" className="ml-2 h-5 rounded px-1">
{activeFilters.length}
</Badge>
)} */}
{activeFilters.length > 0 && (
<Button
variant="ghost"
size="sm"
className="my-auto h-5 rounded-xl px-1.5 text-xs"
onClick={(e) => {
e.stopPropagation();
clearAllFilters();
}}
>
Clear
</Button>
)}
<kbd className="bg-muted text-md pointer-events-none mr-0.5 hidden h-7 select-none flex-row items-center gap-1 rounded-md border-none px-2 font-medium !leading-[0] opacity-100 sm:flex dark:bg-[#262626] dark:text-[#929292]">
<span
className={cn(
'h-min !leading-[0.2]',
isMac ? 'mt-[1px] text-lg' : 'text-sm',
)}
>
{isMac ? '⌘' : 'Ctrl'}{' '}
</span>
<span className="h-min text-sm !leading-[0.2]"> K</span>
</kbd>
</span>
</Button>
{activeConnection?.providerId === 'google' && folder === 'inbox' && (
<CategoryDropdown isMultiSelectMode={mail.bulkSelected.length > 0} />
)}
</div>
) : null}
<Button
onClick={() => {
refetchThreads();
}}
variant="ghost"
className="md:h-fit md:px-2"
>
<RefreshCcw className="text-muted-foreground h-4 w-4 cursor-pointer" />
</Button>
{mail.bulkSelected.length > 0 ? (
<div className="flex items-center gap-2">
<Tooltip>
<TooltipTrigger asChild>
<button
onClick={() => {
setMail({ ...mail, bulkSelected: [] });
}}
className="flex h-6 items-center gap-1 rounded-md bg-[#313131] px-2 text-xs text-[#A0A0A0] hover:bg-[#252525]"
>
<X className="h-3 w-3 fill-[#A0A0A0]" />
<span>esc</span>
</button>
</TooltipTrigger>
<TooltipContent>
{m['common.actions.exitSelectionModeEsc']()}
</TooltipContent>
</Tooltip>
</div>
) : null}
</div>
</div>
</div>

Fix in CursorFix in Web


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

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

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