Skip to content

Comments

Add a setting for awaiting reply tracking#719

Merged
elie222 merged 3 commits intomainfrom
feat/awaiting-reply-setting
Aug 26, 2025
Merged

Add a setting for awaiting reply tracking#719
elie222 merged 3 commits intomainfrom
feat/awaiting-reply-setting

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Aug 26, 2025

Summary by CodeRabbit

  • New Features

    • Added “Awaiting Reply” setting in Assistant settings to enable/disable outbound-reply tracking per email account; appears after Draft Replies.
    • Toggle shows loading placeholders, provides instant optimistic feedback, and displays success/error toasts while persisting changes and refreshing data.
  • Tests

    • Updated scheduler behavior tests: Draft email and webhook actions are no longer considered delayable.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Aug 26, 2025

Walkthrough

Adds a new client React setting component AwaitingReplySetting with optimistic toggle for outbound reply tracking, a server action updateAwaitingReplyTrackingAction to persist the flag via Prisma, integrates the UI into SettingsTab, and updates scheduler tests to change delayable actions.

Changes

Cohort / File(s) Summary
Assistant Settings UI
apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx
New client component showing/loading email account, deriving enabled from outboundReplyTracking, performing optimistic mutate on toggle, calling updateAwaitingReplyTrackingAction, showing success/error toasts, and revalidating or reverting on error.
Assistant Settings Integration
apps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx
Imports and renders <AwaitingReplySetting /> after DraftReplies in the SettingsTab component tree.
Settings Server Action
apps/web/utils/actions/settings.ts
Adds updateAwaitingReplyTrackingAction (zod schema { enabled: boolean }) that updates prisma.emailAccount.update({ data: { outboundReplyTracking: enabled } }) and returns { success: true }.
Scheduler Tests
apps/web/utils/scheduled-actions/scheduler.test.ts
Adjusts canActionBeDelayed tests: removes DRAFT_EMAIL and CALL_WEBHOOK from delayable actions and asserts they are unsupported (false) instead.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  actor User
  participant UI as AwaitingReplySetting (Client)
  participant Cache as SWR Cache (mutate)
  participant Action as updateAwaitingReplyTrackingAction (Server)
  participant DB as Prisma / DB

  User->>UI: Toggle "Awaiting reply" on/off
  UI->>Cache: Optimistic mutate(enabled)
  UI->>Action: call updateAwaitingReplyTrackingAction(enabled)
  Action->>DB: update emailAccount.outboundReplyTracking
  DB-->>Action: OK
  Action-->>UI: { success: true }
  UI->>Cache: revalidate / refresh
  UI->>User: show success toast

  alt Action error
    Action-->>UI: error
    UI->>Cache: revert optimistic mutate
    UI->>User: show error toast
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested reviewers

  • edulelis

Poem

A toggle flipped with a thump and a hop,
I optimistically change — never stop!
If errors nibble, I tuck it right back,
Toasts shimmer carrots along the track.
A rabbit-approved setting, neat in its plot. 🐇✨

Tip

🔌 Remote MCP (Model Context Protocol) integration is now available!

Pro plan users can now connect to remote MCP servers from the Integrations page. Connect with popular remote MCPs such as Notion and Linear to add more context to your reviews and chats.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/awaiting-reply-setting

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.
    • 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.
  • 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 the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

CodeRabbit Commands (Invoked using PR/Issue comments)

Type @coderabbitai help to get the list of available commands.

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.

Status, Documentation and Community

  • Visit our Status Page to check the current availability of CodeRabbit.
  • 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.

@vercel
Copy link

vercel bot commented Aug 26, 2025

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Aug 26, 2025 0:26am

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

🧹 Nitpick comments (4)
apps/web/utils/actions/settings.ts (2)

82-91: Optional: add minimal structured logging.

Helpful for auditing toggles and debugging support issues; keep within action scope per guidelines.

Apply inside the action:

   .action(async ({ ctx: { emailAccountId }, parsedInput: { enabled } }) => {
+    const logger = createScopedLogger("updateAwaitingReplyTracking").with({ emailAccountId, enabled });
+    logger.info("Updating outboundReplyTracking");
     await prisma.emailAccount.update({
       where: { id: emailAccountId },
       data: { outboundReplyTracking: enabled },
     });
+    logger.info("Updated outboundReplyTracking");
     return { success: true };
   });

82-91: Review cache invalidation for email-account GET route

It looks like the GET /api/user/email-account handler isn’t tagged for cache invalidation, so calling revalidateTag("email-account") in the action will have no effect. You have two options:

  • Add a fetch tag to the route handler so revalidateTag("email-account") works.
    In apps/web/app/api/user/email-account/route.ts, export the tag:
    export const GET = async (req: Request) => {
      // ...
      return NextResponse.json(data, {
        headers: { "x-nextjs-cache-tag": "email-account" },
      });
    }
  • Invalidate by path instead, e.g.:
       await prisma.emailAccount.update({ ... });
  • // revalidateTag won't work without a tag on the GET route
  • // Invalidate the settings page for this account
    revalidatePath(/[${emailAccountId}]/assistant/settings);

Pinpointed for action:
- apps/web/utils/actions/settings.ts: add either `revalidateTag("email-account")` _and_ tag the GET route, or use `revalidatePath(...)`  
- apps/web/app/api/user/email-account/route.ts: add `x-nextjs-cache-tag: "email-account"` or other appropriate `next: { tags: [...] }` config  

Please update accordingly to ensure other widgets/pages observe the change.

</blockquote></details>
<details>
<summary>apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx (2)</summary><blockquote>

`22-52`: **Prefer safe-action result handling and functional mutate to avoid stale closures.**

Align with the house pattern (result?.serverError) and use a functional updater so we don’t capture a stale emailAccountData reference.

Apply this diff:

```diff
-  const handleToggle = useCallback(
-    async (enable: boolean) => {
-      if (!emailAccountData) return;
-      // Optimistically update the UI
-      mutate(
-        { ...emailAccountData, outboundReplyTracking: enable },
-        false,
-      );
-
-      try {
-        await updateAwaitingReplyTrackingAction(emailAccountData.id, {
-          enabled: enable,
-        });
-        toastSuccess({
-          description: `Awaiting reply labels ${enable ? "enabled" : "disabled"}`,
-        });
-        mutate();
-      } catch (error) {
-        // Revert optimistic update on error
-        mutate();
-        toastError({
-          description: `Failed to update awaiting reply labels: ${
-            error instanceof Error ? error.message : "Unknown error"
-          }`,
-        });
-      }
-    },
-    [emailAccountData, mutate],
-  );
+  const handleToggle = useCallback(
+    async (enable: boolean) => {
+      if (!emailAccountData) return;
+      // Optimistically update using functional form to avoid stale captures
+      mutate(
+        (prev) => (prev ? { ...prev, outboundReplyTracking: enable } : prev),
+        false,
+      );
+
+      const result = await updateAwaitingReplyTrackingAction(emailAccountData.id, {
+        enabled: enable,
+      });
+      if (result?.serverError) {
+        // Revert via revalidation and show error
+        mutate();
+        toastError({ description: `Failed to update awaiting reply labels: ${result.serverError}` });
+        return;
+      }
+      toastSuccess({
+        description: `Awaiting reply labels ${enable ? "enabled" : "disabled"}`,
+      });
+      mutate();
+    },
+    [emailAccountData, mutate],
+  );

If your action throws on failure (instead of returning serverError), keep try/catch but still prefer functional mutate for optimism.


60-70: Prevent double-submits while the action is in-flight.

Rapid toggles can race and leave the UI out of sync. Optionally gate the handler while a request is pending and pass a disabled state to Toggle (if supported).

Add a pending flag:

-import { useCallback } from "react";
+import { useCallback, useState } from "react";

Then:

 export function AwaitingReplySetting() {
+  const [isPending, setIsPending] = useState(false);
   // ...
   const handleToggle = useCallback(
     async (enable: boolean) => {
       if (!emailAccountData) return;
+      if (isPending) return;
+      setIsPending(true);
       // optimistic mutate...
-      const result = await updateAwaitingReplyTrackingAction(emailAccountData.id, { enabled: enable });
+      const result = await updateAwaitingReplyTrackingAction(emailAccountData.id, { enabled: enable });
       // handle result...
-      mutate();
+      mutate();
+      setIsPending(false);
     },
-    [emailAccountData, mutate],
+    [emailAccountData, mutate, isPending],
   );

And pass disabled state (if Toggle supports it):

-          <Toggle
+          <Toggle
             name="outbound-reply-tracking"
             enabled={enabled}
             onChange={handleToggle}
+            disabled={isPending}
           />
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 1f07980 and 502ffbb.

📒 Files selected for processing (3)
  • apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx (1 hunks)
  • apps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx (1 hunks)
  • apps/web/utils/actions/settings.ts (2 hunks)
🧰 Additional context used
📓 Path-based instructions (19)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx
  • apps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx
  • apps/web/utils/actions/settings.ts
apps/web/app/**

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

NextJS app router structure with (app) directory

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx
  • apps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx
apps/web/**/*.tsx

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.tsx: Follow tailwindcss patterns with prettier-plugin-tailwindcss
Prefer functional components with hooks
Use shadcn/ui components when available
Ensure responsive design with mobile-first approach
Follow consistent naming conventions (PascalCase for components)
Use LoadingContent component for async data
Use result?.serverError with toastError and toastSuccess
Use LoadingContent component to handle loading and error states consistently
Pass loading, error, and children props to LoadingContent

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx
  • apps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx
!{.cursor/rules/*.mdc}

📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx
  • apps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx
  • apps/web/utils/actions/settings.ts
**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.tsx: Use React Hook Form with Zod for validation
Validate form inputs before submission
Show validation errors inline next to form fields

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx
  • apps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx
  • apps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx
  • apps/web/utils/actions/settings.ts
apps/web/app/(app)/*/**

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

Components for the page are either put in page.tsx, or in the apps/web/app/(app)/PAGE_NAME folder

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx
  • apps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx
apps/web/app/(app)/*/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

If you need to use onClick in a component, that component is a client component and file must start with 'use client'

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx
  • apps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx
apps/web/app/(app)/*/**/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/page-structure.mdc)

If we're in a deeply nested component we will use swr to fetch via API

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx
  • apps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx
apps/web/app/**/*.tsx

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Components with onClick must be client components with use client directive

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx
  • apps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx
  • apps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx
  • apps/web/utils/actions/settings.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx
  • apps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx
  • apps/web/utils/actions/settings.ts
**/*.{jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{jsx,tsx}: Don't destructure props inside JSX components in Solid projects.
Don't use both children and dangerouslySetInnerHTML props on the same element.
Don't use Array index in keys.
Don't assign to React component props.
Don't define React components inside other components.
Don't use event handlers on non-interactive elements.
Don't assign JSX properties multiple times.
Don't add extra closing tags for components without children.
Use <>...</> instead of ....
Don't insert comments as text nodes.
Don't use the return value of React.render.
Make sure all dependencies are correctly specified in React hooks.
Make sure all React hooks are called from the top level of component functions.
Don't use unnecessary fragments.
Don't pass children as props.
Use semantic elements instead of role attributes in JSX.

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx
  • apps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx
**/*.{html,jsx,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{html,jsx,tsx}: Don't use or elements.
Don't use accessKey attribute on any HTML element.
Don't set aria-hidden="true" on focusable elements.
Don't add ARIA roles, states, and properties to elements that don't support them.
Only use the scope prop on elements.
Don't assign non-interactive ARIA roles to interactive HTML elements.
Make sure label elements have text content and are associated with an input.
Don't assign interactive ARIA roles to non-interactive HTML elements.
Don't assign tabIndex to non-interactive HTML elements.
Don't use positive integers for tabIndex property.
Don't include "image", "picture", or "photo" in img alt prop.
Don't use explicit role property that's the same as the implicit/default role.
Make static elements with click handlers use a valid role attribute.
Always include a title element for SVG elements.
Give all elements requiring alt text meaningful information for screen readers.
Make sure anchors have content that's accessible to screen readers.
Assign tabIndex to non-interactive HTML elements with aria-activedescendant.
Include all required ARIA attributes for elements with ARIA roles.
Make sure ARIA properties are valid for the element's supported roles.
Always include a type attribute for button elements.
Make elements with interactive roles and handlers focusable.
Give heading elements content that's accessible to screen readers (not hidden with aria-hidden).
Always include a lang attribute on the html element.
Always include a title attribute for iframe elements.
Accompany onClick with at least one of: onKeyUp, onKeyDown, or onKeyPress.
Accompany onMouseOver/onMouseOut with onFocus/onBlur.
Include caption tracks for audio and video elements.
Make sure all anchors are valid and navigable.
Ensure all ARIA properties (aria-*) are valid.
Use valid, non-abstract ARIA roles for elements with ARIA roles.
Use valid ARIA state and property values.
Use valid values for the autocomplete attribute on input eleme...

Files:

  • apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx
  • apps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx
apps/web/utils/actions/**/*.ts

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/utils/actions/**/*.ts: Use server actions for all mutations (create/update/delete operations)
next-safe-action provides centralized error handling
Use Zod schemas for validation on both client and server
Use revalidatePath in server actions for cache invalidation

apps/web/utils/actions/**/*.ts: Use server actions (with next-safe-action) for all mutations (create/update/delete operations); do NOT use POST API routes for mutations.
Use revalidatePath in server actions to invalidate cache after mutations.

Files:

  • apps/web/utils/actions/settings.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/utils/actions/settings.ts
apps/web/utils/actions/*.ts

📄 CodeRabbit inference engine (.cursor/rules/server-actions.mdc)

apps/web/utils/actions/*.ts: Implement all server actions using the next-safe-action library for type safety, input validation, context management, and error handling. Refer to apps/web/utils/actions/safe-action.ts for client definitions (actionClient, actionClientUser, adminActionClient).
Use actionClientUser when only authenticated user context (userId) is needed.
Use actionClient when both authenticated user context and a specific emailAccountId are needed. The emailAccountId must be bound when calling the action from the client.
Use adminActionClient for actions restricted to admin users.
Access necessary context (like userId, emailAccountId, etc.) provided by the safe action client via the ctx object in the .action() handler.
Server Actions are strictly for mutations (operations that change data, e.g., creating, updating, deleting). Do NOT use Server Actions for data fetching (GET operations). For data fetching, use dedicated GET API Routes combined with SWR Hooks.
Use SafeError for expected/handled errors within actions if needed. next-safe-action provides centralized error handling.
Use the .metadata({ name: "actionName" }) method to provide a meaningful name for monitoring. Sentry instrumentation is automatically applied via withServerActionInstrumentation within the safe action clients.
If an action modifies data displayed elsewhere, use revalidatePath or revalidateTag from next/cache within the action handler as needed.

Server action files must start with use server

Files:

  • apps/web/utils/actions/settings.ts
apps/web/utils/**

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Create utility functions in utils/ folder for reusable logic

Files:

  • apps/web/utils/actions/settings.ts
apps/web/utils/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size

Files:

  • apps/web/utils/actions/settings.ts
🧠 Learnings (4)
📚 Learning: 2025-07-18T15:04:30.467Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: apps/web/CLAUDE.md:0-0
Timestamp: 2025-07-18T15:04:30.467Z
Learning: Applies to apps/web/utils/actions/**/*.ts : Use Zod schemas for validation on both client and server

Applied to files:

  • apps/web/utils/actions/settings.ts
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-07-18T17:27:58.249Z
Learning: Applies to apps/web/utils/actions/*.ts : Implement all server actions using the `next-safe-action` library for type safety, input validation, context management, and error handling. Refer to `apps/web/utils/actions/safe-action.ts` for client definitions (`actionClient`, `actionClientUser`, `adminActionClient`).

Applied to files:

  • apps/web/utils/actions/settings.ts
📚 Learning: 2025-07-20T09:00:16.505Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/project-structure.mdc:0-0
Timestamp: 2025-07-20T09:00:16.505Z
Learning: Applies to apps/web/utils/actions/*.ts : Server action files must start with `use server`

Applied to files:

  • apps/web/utils/actions/settings.ts
📚 Learning: 2025-07-18T17:27:58.249Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/server-actions.mdc:0-0
Timestamp: 2025-07-18T17:27:58.249Z
Learning: Applies to apps/web/utils/actions/*.ts : Server Actions are strictly for mutations (operations that change data, e.g., creating, updating, deleting). Do NOT use Server Actions for data fetching (GET operations). For data fetching, use dedicated GET API Routes combined with SWR Hooks.

Applied to files:

  • apps/web/utils/actions/settings.ts
🧬 Code graph analysis (3)
apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx (4)
apps/web/hooks/useEmailAccountFull.ts (1)
  • useEmailAccountFull (5-10)
apps/web/utils/actions/settings.ts (1)
  • updateAwaitingReplyTrackingAction (82-91)
apps/web/components/SettingCard.tsx (1)
  • SettingCard (3-26)
apps/web/components/LoadingContent.tsx (1)
  • LoadingContent (13-27)
apps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx (1)
apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx (1)
  • AwaitingReplySetting (13-74)
apps/web/utils/actions/settings.ts (1)
apps/web/utils/actions/safe-action.ts (1)
  • actionClient (46-86)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: test
🔇 Additional comments (4)
apps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx (2)

5-5: Import of AwaitingReplySetting looks correct.

Good use of the "@/..." path alias and colocated component import.


12-12: Placement of AwaitingReplySetting in the tab order LGTM.

Rendering it after DraftReplies matches the summary and maintains a sensible flow.

apps/web/utils/actions/settings.ts (1)

3-3: Zod import added — OK.

Required for the new schema; no issues.

apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx (1)

20-21: Confirmed: outboundReplyTracking is included in the API response
The GET handler at apps/web/app/api/user/email-account/route.ts calls

prisma.emailAccount.findUnique({
  where: { id: emailAccountId },
  include: { digestSchedule: true },
});

Since there’s no explicit select, Prisma returns all scalar fields (including outboundReplyTracking) alongside the included relations. No code change needed here.

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: 0

🧹 Nitpick comments (7)
apps/web/utils/scheduled-actions/scheduler.test.ts (7)

22-38: Guard against drift: assert the exact allowlist across all ActionType values

To prevent future regressions when ActionType changes, add a single “exact allowlist” test that iterates over all enum values and checks membership. This complements the positive/negative tests and fails loudly if a new action is added without updating canActionBeDelayed.

Apply this addition inside the canActionBeDelayed describe block:

+    it("should match the exact allowlist", () => {
+      const allowlist = new Set([
+        ActionType.ARCHIVE,
+        ActionType.LABEL,
+        ActionType.MARK_READ,
+        ActionType.REPLY,
+        ActionType.SEND_EMAIL,
+        ActionType.FORWARD,
+      ]);
+      for (const a of Object.values(ActionType) as ActionType[]) {
+        expect(canActionBeDelayed(a)).toBe(allowlist.has(a));
+      }
+    });

44-48: Avoid ‘as any’ in test doubles

Per our TS guidelines, avoid any. Use a lightweight local type and the satisfies operator for better type-safety.

Apply this diff to the mock value:

-      prisma.scheduledAction.findMany.mockResolvedValue([
-        { id: "action-1", scheduledId: "qstash-msg-1" },
-        { id: "action-2", scheduledId: "qstash-msg-2" },
-      ] as any);
+      prisma.scheduledAction.findMany.mockResolvedValue([
+        { id: "action-1", scheduledId: "qstash-msg-1" },
+        { id: "action-2", scheduledId: "qstash-msg-2" },
+      ] satisfies ScheduledActionLite[]);

Add this supporting type near the top of the file (outside the selected range):

type ScheduledActionLite = { id: string; scheduledId: string };

96-99: Avoid ‘as any’ in test doubles (threadId case)

Mirror the type-safe approach here too.

-      prisma.scheduledAction.findMany.mockResolvedValue([
-        { id: "action-1", scheduledId: "qstash-msg-1" },
-      ] as any);
+      prisma.scheduledAction.findMany.mockResolvedValue([
+        { id: "action-1", scheduledId: "qstash-msg-1" },
+      ] satisfies ScheduledActionLite[]);

1-15: Import qstash to assert Upstash deletions

You mock qstash.messages.delete but never assert it. Import qstash so we can verify external side effects.

 import { describe, it, expect, vi, beforeEach } from "vitest";
 import { ActionType, ScheduledActionStatus } from "@prisma/client";
 import { cancelScheduledActions } from "./scheduler";
 import { canActionBeDelayed } from "@/utils/delayed-actions";
 import prisma from "@/utils/__mocks__/prisma";
+import { qstash } from "@/utils/upstash";

41-82: Assert Upstash cancellations are issued for each scheduledId

Strengthen this test by verifying how many times we attempt to delete scheduled messages and (ideally) with which IDs. This catches integration regressions between DB updates and QStash cleanup.

Apply the expectations below at the end of the test:

       expect(prisma.scheduledAction.updateMany).toHaveBeenCalledWith({
         where: {
           emailAccountId: "account-123",
           messageId: "msg-123",
           status: ScheduledActionStatus.PENDING,
         },
         data: {
           status: ScheduledActionStatus.CANCELLED,
         },
       });
 
       expect(result).toBe(2);
+
+      // Upstash deletions should be invoked for each scheduledId
+      expect(qstash.messages.delete).toHaveBeenCalledTimes(2);
+      // Adjust arguments if your delete signature differs
+      expect(qstash.messages.delete).toHaveBeenNthCalledWith(1, "qstash-msg-1");
+      expect(qstash.messages.delete).toHaveBeenNthCalledWith(2, "qstash-msg-2");

If the Upstash SDK expects an object or different params, tweak the toHaveBeenNthCalledWith accordingly.


83-93: Assert no Upstash deletions when nothing to cancel

Ensure we don’t call external services unnecessarily.

       const result = await cancelScheduledActions({
         messageId: "msg-456",
         emailAccountId: "account-123",
       });
 
       expect(result).toBe(0);
+      expect(qstash.messages.delete).not.toHaveBeenCalled();

95-132: Thread-scoped cancellation: also assert Upstash deletion count

For completeness, validate the Upstash side effect when threadId is included.

       expect(prisma.scheduledAction.updateMany).toHaveBeenCalledWith({
         where: {
           emailAccountId: "account-123",
           messageId: "msg-123",
           threadId: "thread-123",
           status: ScheduledActionStatus.PENDING,
         },
         data: {
           status: ScheduledActionStatus.CANCELLED,
         },
       });
+
+      expect(qstash.messages.delete).toHaveBeenCalledTimes(1);
+      expect(qstash.messages.delete).toHaveBeenCalledWith("qstash-msg-1");

If you intend to record the “reason” parameter anywhere (DB audit field or Upstash metadata), consider asserting that here as well.

📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

💡 Knowledge Base configuration:

  • MCP integration is disabled by default for public repositories
  • Jira integration is disabled by default for public repositories
  • Linear integration is disabled by default for public repositories

You can enable these sources in your CodeRabbit configuration.

📥 Commits

Reviewing files that changed from the base of the PR and between 502ffbb and 7c071d3.

📒 Files selected for processing (2)
  • apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx (1 hunks)
  • apps/web/utils/scheduled-actions/scheduler.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx
🧰 Additional context used
📓 Path-based instructions (11)
apps/web/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/web/CLAUDE.md)

apps/web/**/*.{ts,tsx}: Use TypeScript with strict null checks
Path aliases: Use @/ for imports from project root
Use proper error handling with try/catch blocks
Format code with Prettier
Leverage TypeScript inference for better DX

Files:

  • apps/web/utils/scheduled-actions/scheduler.test.ts
!{.cursor/rules/*.mdc}

📄 CodeRabbit inference engine (.cursor/rules/cursor-rules.mdc)

Never place rule files in the project root, in subdirectories outside .cursor/rules, or in any other location

Files:

  • apps/web/utils/scheduled-actions/scheduler.test.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/form-handling.mdc)

**/*.ts: The same validation should be done in the server action too
Define validation schemas using Zod

Files:

  • apps/web/utils/scheduled-actions/scheduler.test.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)

**/*.{ts,tsx}: Use createScopedLogger for logging in backend TypeScript files
Typically add the logger initialization at the top of the file when using createScopedLogger
Only use .with() on a logger instance within a specific function, not for a global logger

Import Prisma in the project using import prisma from "@/utils/prisma";

**/*.{ts,tsx}: Don't use TypeScript enums.
Don't use TypeScript const enum.
Don't use the TypeScript directive @ts-ignore.
Don't use primitive type aliases or misleading types.
Don't use empty type parameters in type aliases and interfaces.
Don't use any or unknown as type constraints.
Don't use implicit any type on variable declarations.
Don't let variables evolve into any type through reassignments.
Don't use non-null assertions with the ! postfix operator.
Don't misuse the non-null assertion operator (!) in TypeScript files.
Don't use user-defined types.
Use as const instead of literal types and type annotations.
Use export type for types.
Use import type for types.
Don't declare empty interfaces.
Don't merge interfaces and classes unsafely.
Don't use overload signatures that aren't next to each other.
Use the namespace keyword instead of the module keyword to declare TypeScript namespaces.
Don't use TypeScript namespaces.
Don't export imported variables.
Don't add type annotations to variables, parameters, and class properties that are initialized with literal expressions.
Don't use parameter properties in class constructors.
Use either T[] or Array consistently.
Initialize each enum member value explicitly.
Make sure all enum members are literal values.

Files:

  • apps/web/utils/scheduled-actions/scheduler.test.ts
**/*.test.{ts,js}

📄 CodeRabbit inference engine (.cursor/rules/security.mdc)

Include security tests in your test suites to verify authentication, authorization, and error handling.

Files:

  • apps/web/utils/scheduled-actions/scheduler.test.ts
**/*.test.{ts,js,tsx,jsx}

📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)

**/*.test.{ts,js,tsx,jsx}: Tests are colocated next to the tested file (e.g., dir/format.ts and dir/format.test.ts)
Use vi.mock("server-only", () => ({})); to mock the server-only module in tests
Mock @/utils/prisma in tests using vi.mock("@/utils/prisma") and use the provided prisma mock
Mock external dependencies in tests
Clean up mocks between tests
Do not mock the Logger

Files:

  • apps/web/utils/scheduled-actions/scheduler.test.ts
apps/web/utils/**

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Create utility functions in utils/ folder for reusable logic

Files:

  • apps/web/utils/scheduled-actions/scheduler.test.ts
apps/web/utils/**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

apps/web/utils/**/*.ts: Use lodash utilities for common operations (arrays, objects, strings)
Import specific lodash functions to minimize bundle size

Files:

  • apps/web/utils/scheduled-actions/scheduler.test.ts
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{js,jsx,ts,tsx}: Don't use elements in Next.js projects.
Don't use elements in Next.js projects.
Don't use namespace imports.
Don't access namespace imports dynamically.
Don't use global eval().
Don't use console.
Don't use debugger.
Don't use var.
Don't use with statements in non-strict contexts.
Don't use the arguments object.
Don't use consecutive spaces in regular expression literals.
Don't use the comma operator.
Don't use unnecessary boolean casts.
Don't use unnecessary callbacks with flatMap.
Use for...of statements instead of Array.forEach.
Don't create classes that only have static members (like a static namespace).
Don't use this and super in static contexts.
Don't use unnecessary catch clauses.
Don't use unnecessary constructors.
Don't use unnecessary continue statements.
Don't export empty modules that don't change anything.
Don't use unnecessary escape sequences in regular expression literals.
Don't use unnecessary labels.
Don't use unnecessary nested block statements.
Don't rename imports, exports, and destructured assignments to the same name.
Don't use unnecessary string or template literal concatenation.
Don't use String.raw in template literals when there are no escape sequences.
Don't use useless case statements in switch statements.
Don't use ternary operators when simpler alternatives exist.
Don't use useless this aliasing.
Don't initialize variables to undefined.
Don't use the void operators (they're not familiar).
Use arrow functions instead of function expressions.
Use Date.now() to get milliseconds since the Unix Epoch.
Use .flatMap() instead of map().flat() when possible.
Use literal property access instead of computed property access.
Don't use parseInt() or Number.parseInt() when binary, octal, or hexadecimal literals work.
Use concise optional chaining instead of chained logical expressions.
Use regular expression literals instead of the RegExp constructor when possible.
Don't use number literal object member names th...

Files:

  • apps/web/utils/scheduled-actions/scheduler.test.ts
!pages/_document.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

!pages/_document.{js,jsx,ts,tsx}: Don't import next/document outside of pages/_document.jsx in Next.js projects.
Don't import next/document outside of pages/_document.jsx in Next.js projects.

Files:

  • apps/web/utils/scheduled-actions/scheduler.test.ts
**/*.{test,spec}.{js,jsx,ts,tsx}

📄 CodeRabbit inference engine (.cursor/rules/ultracite.mdc)

**/*.{test,spec}.{js,jsx,ts,tsx}: Don't use export or module.exports in test files.
Don't use focused tests.
Don't use disabled tests.
Make sure the assertion function, like expect, is placed inside an it() function call.
Don't nest describe() blocks too deeply in test files.
Don't use focused tests.
Don't use disabled tests.
Don't use export or module.exports in test files.

Files:

  • apps/web/utils/scheduled-actions/scheduler.test.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Jit Security
🔇 Additional comments (1)
apps/web/utils/scheduled-actions/scheduler.test.ts (1)

33-34: Delayability change for CALL_WEBHOOK and DRAFT_EMAIL looks correct

These assertions reflect the updated policy: CALL_WEBHOOK and DRAFT_EMAIL are no longer delayable. Tests now align with the intended allowlist.

@elie222 elie222 merged commit db5af30 into main Aug 26, 2025
@coderabbitai coderabbitai bot mentioned this pull request Aug 26, 2025
@elie222 elie222 deleted the feat/awaiting-reply-setting branch December 18, 2025 23:01
@coderabbitai coderabbitai bot mentioned this pull request Jan 11, 2026
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