Add a setting for awaiting reply tracking#719
Conversation
WalkthroughAdds 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
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested reviewers
Poem
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 unit tests
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. CodeRabbit Commands (Invoked using PR/Issue comments)Type Other keywords and placeholders
Status, Documentation and Community
|
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
There was a problem hiding this comment.
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 routeIt looks like the
GET /api/user/email-accounthandler isn’t tagged for cache invalidation, so callingrevalidateTag("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.
Inapps/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.
📒 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.tsxapps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsxapps/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.tsxapps/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
Useresult?.serverErrorwithtoastErrorandtoastSuccess
UseLoadingContentcomponent to handle loading and error states consistently
Passloading,error, and children props toLoadingContent
Files:
apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsxapps/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.tsxapps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsxapps/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.tsxapps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/logging.mdc)
**/*.{ts,tsx}: UsecreateScopedLoggerfor logging in backend TypeScript files
Typically add the logger initialization at the top of the file when usingcreateScopedLogger
Only use.with()on a logger instance within a specific function, not for a global loggerImport 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.tsxapps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsxapps/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.tsxapps/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.tsxapps/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.tsxapps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsx
apps/web/app/**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
Components with
onClickmust be client components withuse clientdirective
Files:
apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsxapps/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 useelements 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.tsxapps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsxapps/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.tsxapps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsxapps/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.tsxapps/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.tsxapps/web/app/(app)/[emailAccountId]/assistant/settings/SettingsTab.tsxapps/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-actionprovides centralized error handling
Use Zod schemas for validation on both client and server
UserevalidatePathin server actions for cache invalidation
apps/web/utils/actions/**/*.ts: Use server actions (withnext-safe-action) for all mutations (create/update/delete operations); do NOT use POST API routes for mutations.
UserevalidatePathin 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 ZodFiles:
apps/web/utils/actions/settings.tsapps/web/utils/actions/*.ts
📄 CodeRabbit inference engine (.cursor/rules/server-actions.mdc)
apps/web/utils/actions/*.ts: Implement all server actions using thenext-safe-actionlibrary for type safety, input validation, context management, and error handling. Refer toapps/web/utils/actions/safe-action.tsfor client definitions (actionClient,actionClientUser,adminActionClient).
UseactionClientUserwhen only authenticated user context (userId) is needed.
UseactionClientwhen both authenticated user context and a specificemailAccountIdare needed. TheemailAccountIdmust be bound when calling the action from the client.
UseadminActionClientfor actions restricted to admin users.
Access necessary context (likeuserId,emailAccountId, etc.) provided by the safe action client via thectxobject 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.
UseSafeErrorfor expected/handled errors within actions if needed.next-safe-actionprovides centralized error handling.
Use the.metadata({ name: "actionName" })method to provide a meaningful name for monitoring. Sentry instrumentation is automatically applied viawithServerActionInstrumentationwithin the safe action clients.
If an action modifies data displayed elsewhere, userevalidatePathorrevalidateTagfromnext/cachewithin the action handler as needed.Server action files must start with
use serverFiles:
apps/web/utils/actions/settings.tsapps/web/utils/**
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
Create utility functions in
utils/folder for reusable logicFiles:
apps/web/utils/actions/settings.tsapps/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 sizeFiles:
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 serverApplied 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 atapps/web/app/api/user/email-account/route.tscallsprisma.emailAccount.findUnique({ where: { id: emailAccountId }, include: { digestSchedule: true }, });Since there’s no explicit
select, Prisma returns all scalar fields (includingoutboundReplyTracking) alongside the included relations. No code change needed here.
apps/web/app/(app)/[emailAccountId]/assistant/settings/AwaitingReplySetting.tsx
Outdated
Show resolved
Hide resolved
There was a problem hiding this comment.
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 valuesTo 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 doublesPer 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 deletionsYou 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 scheduledIdStrengthen 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 cancelEnsure 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 countFor 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.
📒 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}: UsecreateScopedLoggerfor logging in backend TypeScript files
Typically add the logger initialization at the top of the file when usingcreateScopedLogger
Only use.with()on a logger instance within a specific function, not for a global loggerImport 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.tsanddir/format.test.ts)
Usevi.mock("server-only", () => ({}));to mock theserver-onlymodule in tests
Mock@/utils/prismain tests usingvi.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 useelements 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 correctThese assertions reflect the updated policy: CALL_WEBHOOK and DRAFT_EMAIL are no longer delayable. Tests now align with the intended allowlist.
Summary by CodeRabbit
New Features
Tests