Skip to content

Only allow clean if active premium account#795

Merged
elie222 merged 3 commits intomainfrom
feat/clean-active-premium
Sep 17, 2025
Merged

Only allow clean if active premium account#795
elie222 merged 3 commits intomainfrom
feat/clean-active-premium

Conversation

@elie222
Copy link
Owner

@elie222 elie222 commented Sep 17, 2025

Summary by CodeRabbit

  • New Features

    • Enforces an active premium subscription to run Clean/Automation actions; trialing or inactive plans are blocked with clear messaging.
    • Adds a premium alert to the Clean intro screen, showing gating status and guidance.
  • Style

    • Increased spacing beneath the premium alert on the Automation page for improved readability.
  • Chores

    • Bumped version to v2.9.41.

@vercel
Copy link

vercel bot commented Sep 17, 2025

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

Project Deployment Preview Updated (UTC)
inbox-zero Ready Ready Preview Sep 17, 2025 7:19am

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.

1 issue found across 5 files

Prompt for AI agents (all 1 issues)

Understand the root cause of the following 1 issues and fix them.


<file name="apps/web/utils/user/get.ts">

<violation number="1" location="apps/web/utils/user/get.ts:111">
Using || here converts false to null; use nullish coalescing to preserve false.</violation>
</file>

React with 👍 or 👎 to teach cubic. Mention @cubic-dev-ai to give feedback, ask questions, or re-run the review.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Sep 17, 2025

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds active premium gating across clean flows. Introduces isActivePremium and getUserPremium utilities. Enforces premium checks in API route and server action before Gmail operations. Updates PremiumAlert to support activeOnly and trial handling. Adds PremiumAlert to Clean Intro UI and tweaks spacing in Automation page. Bumps version.

Changes

Cohort / File(s) Summary
Backend premium gating (clean flow)
apps/web/app/api/clean/route.ts, apps/web/utils/actions/clean.ts
Inserts premium validation (getUserPremium + isActivePremium) before Gmail logic; throws SafeError when missing/inactive. Server action signature updated to include userId.
Premium utilities
apps/web/utils/premium/index.ts, apps/web/utils/user/get.ts
Adds isActivePremium (Stripe active or active Lemon Squeezy) and getUserPremium({ userId }) (Prisma select).
Premium alert components and usage
apps/web/components/PremiumAlert.tsx, apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx, apps/web/app/(app)/[emailAccountId]/automation/page.tsx
PremiumAiAssistantAlert gains stripeSubscriptionStatus and activeOnly; early returns with “Active Subscription Required” when trialing and activeOnly. PremiumAlertWithData forwards activeOnly and subscription status. Added alert to Clean Intro (activeOnly, mb-20). Adjusted spacing in Automation page (mb-8).
Version
version.txt
Bump v2.9.40 → v2.9.41.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as User
  participant API as /api/clean
  participant DB as getUserPremium
  participant Prem as isActivePremium
  participant G as Gmail Client
  participant S as Cleaner

  U->>API: POST clean
  API->>DB: Fetch premium by userId
  DB-->>API: premium|null
  API->>Prem: Check active
  Prem-->>API: true/false
  alt Not premium or inactive
    API-->>U: SafeError("User not premium/active")
  else Active
    API->>G: Create client
    API->>S: Execute clean
    API-->>U: Success response
  end
Loading
sequenceDiagram
  autonumber
  participant UI as Client
  participant ACT as cleanInboxAction
  participant DB as getUserPremium
  participant Prem as isActivePremium
  participant G as Gmail Client
  participant L as Label Setup
  participant Q as Queue (Qstash)

  UI->>ACT: Invoke with { emailAccountId, provider, userId }
  ACT->>ACT: Validate provider=google
  ACT->>DB: Fetch premium
  DB-->>ACT: premium|null
  ACT->>Prem: isActivePremium(premium)
  Prem-->>ACT: true/false
  alt Not premium or inactive
    ACT-->>UI: SafeError
  else Active
    ACT->>G: Create client
    ACT->>L: Ensure labels
    ACT->>Q: Publish clean job
    ACT-->>UI: Job enqueued
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

A hop, a bop—no trials slide by,
Premium gates beneath the sky.
I twitch my nose at inbox grime,
Only actives pass this time.
With labels neat and queues that sing,
v2.9.41—spring! 🌱🐇

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title Check ✅ Passed The title succinctly and accurately captures the primary behavioral change in the changeset: the "clean" flow is now restricted to users with an active premium account (see added isActivePremium/getUserPremium checks, updated clean route and action), so it is directly related and specific to the main change. The phrasing is clear about intent and is concise enough for a teammate scanning PR history to understand the primary change.
✨ 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/clean-active-premium

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

Comment @coderabbitai help to get the list of available commands and usage tips.

@elie222 elie222 merged commit 9c65c57 into main Sep 17, 2025
11 of 12 checks passed
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

♻️ Duplicate comments (1)
apps/web/utils/user/get.ts (1)

111-111: Use nullish coalescing instead of || to preserve falsy-but-valid values.

Prevents accidental coercion.

Apply:

-  return user?.premium || null;
+  return user?.premium ?? null;
🧹 Nitpick comments (7)
apps/web/utils/user/get.ts (1)

1-4: Add explicit return type and type import for stronger typings.

Clarifies API and aids inference across call sites.

Apply:

 import prisma from "@/utils/prisma";
 import type { EmailAccountWithAI } from "@/utils/llms/types";
-import type { Prisma } from "@prisma/client";
+import type { Prisma, Premium } from "@prisma/client";
@@
-export async function getUserPremium({ userId }: { userId: string }) {
+export async function getUserPremium({
+  userId,
+}: {
+  userId: string;
+}): Promise<Premium | null> {
   const user = await prisma.user.findUnique({
     where: { id: userId },
     select: { premium: true },
   });
 
-  return user?.premium || null;
+  return user?.premium ?? null;
 }

Also applies to: 105-112

apps/web/utils/actions/clean.ts (2)

134-139: Log uses stale nextPageToken value.

You log before assigning; prefer logging pageToken to reflect the current fetch.

Apply:

-          logger.info("Fetched threads", {
-            emailAccountId,
-            threadCount: threads.length,
-            nextPageToken,
-          });
+          logger.info("Fetched threads", {
+            emailAccountId,
+            threadCount: threads.length,
+            nextPageToken: pageToken,
+          });

50-53: Consider returning 402 for premium gating for clearer client handling.

Optional, but SafeError("…", 402) can improve UI flows.

Apply:

-      if (!premium) throw new SafeError("User not premium");
-      if (!isActivePremium(premium)) throw new SafeError("Premium not active");
+      if (!premium) throw new SafeError("User not premium", 402);
+      if (!isActivePremium(premium)) throw new SafeError("Premium not active", 402);
apps/web/app/api/clean/route.ts (2)

74-77: Optionally include HTTP 402 for premium gating.

Improves downstream handling without exposing internals.

Apply:

-  if (!premium) throw new SafeError("User not premium");
-  if (!isActivePremium(premium)) throw new SafeError("Premium not active");
+  if (!premium) throw new SafeError("User not premium", 402);
+  if (!isActivePremium(premium)) throw new SafeError("Premium not active", 402);

74-77: Deduplicate premium gating via a small helper to reduce drift.

Extract assertActivePremium(userId) in utils and reuse here and in the server action.

Proposed helper:

// apps/web/utils/premium/assert.ts
import { getUserPremium } from "@/utils/user/get";
import { isActivePremium } from "@/utils/premium";
import { SafeError } from "@/utils/error";

export async function assertActivePremium(userId: string) {
  const premium = await getUserPremium({ userId });
  if (!premium) throw new SafeError("User not premium", 402);
  if (!isActivePremium(premium)) throw new SafeError("Premium not active", 402);
  return premium;
}

Then replace local checks with:

await assertActivePremium(emailAccount.userId);

Also applies to: 50-67, 31-47

apps/web/components/PremiumAlert.tsx (2)

48-56: Narrow the type of stripeSubscriptionStatus.

Avoid plain string; use a string union to encode known statuses for safer checks.

Example:

export type StripeSubscriptionStatus = "active" | "trialing" | "past_due" | "canceled" | "incomplete" | "incomplete_expired" | null;

export function PremiumAiAssistantAlert({
  showSetApiKey,
  className,
  tier,
  stripeSubscriptionStatus,
  activeOnly,
}: {
  showSetApiKey: boolean;
  className?: string;
  tier?: PremiumTier | null;
  stripeSubscriptionStatus?: StripeSubscriptionStatus;
  activeOnly?: boolean;
}) { /* ... */ }

62-75: Make the status check boolean and fix misleading copy.

The variable is not boolean and the description implies “trial” only, but the condition matches any non-active status.

-  const isStripeTrialing =
-    stripeSubscriptionStatus && stripeSubscriptionStatus !== "active";
-
-  if (activeOnly && isStripeTrialing) {
+  const isActiveSubscription = stripeSubscriptionStatus === "active";
+  if (activeOnly && !isActiveSubscription) {
     return (
       <div className={className}>
         <ActionCard
           icon={<CrownIcon className="h-5 w-5" />}
           title="Active Subscription Required"
-          description="This feature is not available on trial plans."
+          description="This feature requires an active subscription."
         />
       </div>
     );
   }
📜 Review details

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 0945327 and 5f48daa.

📒 Files selected for processing (8)
  • apps/web/app/(app)/[emailAccountId]/automation/page.tsx (1 hunks)
  • apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx (2 hunks)
  • apps/web/app/api/clean/route.ts (3 hunks)
  • apps/web/components/PremiumAlert.tsx (3 hunks)
  • apps/web/utils/actions/clean.ts (3 hunks)
  • apps/web/utils/premium/index.ts (1 hunks)
  • apps/web/utils/user/get.ts (1 hunks)
  • version.txt (1 hunks)
🧰 Additional context used
📓 Path-based instructions (23)
!{.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:

  • version.txt
  • apps/web/components/PremiumAlert.tsx
  • apps/web/utils/actions/clean.ts
  • apps/web/utils/user/get.ts
  • apps/web/app/(app)/[emailAccountId]/automation/page.tsx
  • apps/web/utils/premium/index.ts
  • apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx
  • apps/web/app/api/clean/route.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:

  • version.txt
  • apps/web/components/PremiumAlert.tsx
  • apps/web/utils/actions/clean.ts
  • apps/web/utils/user/get.ts
  • apps/web/app/(app)/[emailAccountId]/automation/page.tsx
  • apps/web/utils/premium/index.ts
  • apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx
  • apps/web/app/api/clean/route.ts
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/components/PremiumAlert.tsx
  • apps/web/utils/actions/clean.ts
  • apps/web/utils/user/get.ts
  • apps/web/app/(app)/[emailAccountId]/automation/page.tsx
  • apps/web/utils/premium/index.ts
  • apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx
  • apps/web/app/api/clean/route.ts
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/components/PremiumAlert.tsx
  • apps/web/app/(app)/[emailAccountId]/automation/page.tsx
  • apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx
apps/web/components/**/*.tsx

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

Use React Hook Form with Zod validation for form handling

Use the LoadingContent component to handle loading and error states consistently in data-fetching components.

Use PascalCase for components (e.g. components/Button.tsx)

Files:

  • apps/web/components/PremiumAlert.tsx
**/*.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/components/PremiumAlert.tsx
  • apps/web/app/(app)/[emailAccountId]/automation/page.tsx
  • apps/web/app/(app)/[emailAccountId]/clean/IntroStep.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/components/PremiumAlert.tsx
  • apps/web/utils/actions/clean.ts
  • apps/web/utils/user/get.ts
  • apps/web/app/(app)/[emailAccountId]/automation/page.tsx
  • apps/web/utils/premium/index.ts
  • apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx
  • apps/web/app/api/clean/route.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/components/PremiumAlert.tsx
  • apps/web/utils/actions/clean.ts
  • apps/web/utils/user/get.ts
  • apps/web/app/(app)/[emailAccountId]/automation/page.tsx
  • apps/web/utils/premium/index.ts
  • apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx
  • apps/web/app/api/clean/route.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/components/PremiumAlert.tsx
  • apps/web/app/(app)/[emailAccountId]/automation/page.tsx
  • apps/web/app/(app)/[emailAccountId]/clean/IntroStep.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/components/PremiumAlert.tsx
  • apps/web/app/(app)/[emailAccountId]/automation/page.tsx
  • apps/web/app/(app)/[emailAccountId]/clean/IntroStep.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/clean.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/clean.ts
  • apps/web/utils/user/get.ts
  • apps/web/utils/premium/index.ts
  • apps/web/app/api/clean/route.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/clean.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/clean.ts
  • apps/web/utils/user/get.ts
  • apps/web/utils/premium/index.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/clean.ts
  • apps/web/utils/user/get.ts
  • apps/web/utils/premium/index.ts
apps/web/app/**

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

NextJS app router structure with (app) directory

Files:

  • apps/web/app/(app)/[emailAccountId]/automation/page.tsx
  • apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx
  • apps/web/app/api/clean/route.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]/automation/page.tsx
  • apps/web/app/(app)/[emailAccountId]/clean/IntroStep.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]/automation/page.tsx
  • apps/web/app/(app)/[emailAccountId]/clean/IntroStep.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]/automation/page.tsx
  • apps/web/app/(app)/[emailAccountId]/clean/IntroStep.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]/automation/page.tsx
  • apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx
apps/web/app/api/**/route.ts

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

apps/web/app/api/**/route.ts: Use withAuth for user-level operations
Use withEmailAccount for email-account-level operations
Do NOT use POST API routes for mutations - use server actions instead
No need for try/catch in GET routes when using middleware
Export response types from GET routes

apps/web/app/api/**/route.ts: Wrap all GET API route handlers with withAuth or withEmailAccount middleware for authentication and authorization.
Export response types from GET API routes for type-safe client usage.
Do not use try/catch in GET API routes when using authentication middleware; rely on centralized error handling.

Files:

  • apps/web/app/api/clean/route.ts
**/api/**/route.ts

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

**/api/**/route.ts: ALL API routes that handle user data MUST use appropriate authentication and authorization middleware (withAuth or withEmailAccount).
ALL database queries in API routes MUST be scoped to the authenticated user/account (e.g., include userId or emailAccountId in query filters).
Always validate that resources belong to the authenticated user before performing operations (resource ownership validation).
Use withEmailAccount middleware for API routes that operate on a specific email account (i.e., use or require emailAccountId).
Use withAuth middleware for API routes that operate at the user level (i.e., use or require only userId).
Use withError middleware (with proper validation) for public endpoints, custom authentication, or cron endpoints.
Cron endpoints MUST use withError middleware and validate the cron secret using hasCronSecret(request) or hasPostCronSecret(request).
Cron endpoints MUST capture unauthorized attempts with captureException and return a 401 status for unauthorized requests.
All parameters in API routes MUST be validated for type, format, and length before use.
Request bodies in API routes MUST be validated using Zod schemas before use.
All Prisma queries in API routes MUST only return necessary fields and never expose sensitive data.
Error messages in API routes MUST not leak internal information or sensitive data; use generic error messages and SafeError where appropriate.
API routes MUST use a consistent error response format, returning JSON with an error message and status code.
All findUnique and findFirst Prisma calls in API routes MUST include ownership filters (e.g., userId or emailAccountId).
All findMany Prisma calls in API routes MUST be scoped to the authenticated user's data.
Never use direct object references in API routes without ownership checks (prevent IDOR vulnerabilities).
Prevent mass assignment vulnerabilities by only allowing explicitly whitelisted fields in update operations in AP...

Files:

  • apps/web/app/api/clean/route.ts
apps/web/app/api/**/*.{ts,js}

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

apps/web/app/api/**/*.{ts,js}: All API route handlers in 'apps/web/app/api/' must use authentication middleware: withAuth, withEmailAccount, or withError (with custom authentication logic).
All Prisma queries in API routes must include user/account filtering (e.g., emailAccountId or userId in WHERE clauses) to prevent unauthorized data access.
All parameters used in API routes must be validated before use; do not use parameters from 'params' or request bodies directly in queries without validation.
Request bodies in API routes should use Zod schemas for validation.
API routes should only return necessary fields using Prisma's 'select' and must not include sensitive data in error messages.
Error messages in API routes must not reveal internal details; use generic errors and SafeError for user-facing errors.
All QStash endpoints (API routes called via publishToQstash or publishToQstashQueue) must use verifySignatureAppRouter to verify request authenticity.
All cron endpoints in API routes must use hasCronSecret or hasPostCronSecret for authentication.
Do not hardcode weak or plaintext secrets in API route files; secrets must not be directly assigned as string literals.
Review all new withError usage in API routes to ensure custom authentication is implemented where required.

Files:

  • apps/web/app/api/clean/route.ts
🧠 Learnings (3)
📚 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 : Access necessary context (like `userId`, `emailAccountId`, etc.) provided by the safe action client via the `ctx` object in the `.action()` handler.

Applied to files:

  • apps/web/utils/actions/clean.ts
📚 Learning: 2025-07-08T13:14:07.449Z
Learnt from: elie222
PR: elie222/inbox-zero#537
File: apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx:30-34
Timestamp: 2025-07-08T13:14:07.449Z
Learning: The clean onboarding page in apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx is intentionally Gmail-specific and should show an error for non-Google email accounts rather than attempting to support multiple providers.

Applied to files:

  • apps/web/utils/actions/clean.ts
📚 Learning: 2025-07-19T17:50:28.270Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/utilities.mdc:0-0
Timestamp: 2025-07-19T17:50:28.270Z
Learning: The `utils` folder also contains core app logic such as Next.js Server Actions and Gmail API requests.

Applied to files:

  • apps/web/app/api/clean/route.ts
🧬 Code graph analysis (5)
apps/web/components/PremiumAlert.tsx (1)
apps/web/app/(app)/premium/PremiumModal.tsx (1)
  • usePremiumModal (5-25)
apps/web/utils/actions/clean.ts (3)
apps/web/utils/user/get.ts (1)
  • getUserPremium (105-112)
apps/web/utils/error.ts (1)
  • SafeError (86-96)
apps/web/utils/premium/index.ts (1)
  • isActivePremium (24-36)
apps/web/app/(app)/[emailAccountId]/automation/page.tsx (1)
apps/web/components/PremiumAlert.tsx (1)
  • PremiumAlertWithData (110-140)
apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx (1)
apps/web/components/PremiumAlert.tsx (1)
  • PremiumAlertWithData (110-140)
apps/web/app/api/clean/route.ts (3)
apps/web/utils/user/get.ts (1)
  • getUserPremium (105-112)
apps/web/utils/error.ts (1)
  • SafeError (86-96)
apps/web/utils/premium/index.ts (1)
  • isActivePremium (24-36)
🔇 Additional comments (9)
version.txt (1)

1-1: Version bump looks good.

No issues.

apps/web/utils/premium/index.ts (1)

24-36: Active premium gating logic is correct and aligned with objective.

Excludes Stripe “trialing” while honoring Lemon Squeezy renewals. Good separation from broader isPremium.

apps/web/utils/actions/clean.ts (3)

50-53: Premium checks in server action are in the right place (pre-Gmail).

Logic and ordering look good.


198-224: Confirm intent: undo/change actions not gated by active premium.

If the product should block all Gmail mutations when inactive, add the same checks here; if not, ignore.

Also applies to: 263-324


41-41: No change required — actionClient populates userId on ctx.
actionClient's middleware injects userId (along with userEmail, emailAccountId, provider, logger, session) into ctx before calling next, so ctx.userId will be defined at runtime.

apps/web/app/api/clean/route.ts (1)

74-77: Premium checks before Gmail client creation are correct.

Prevents unnecessary token refresh and Gmail calls.

apps/web/app/(app)/[emailAccountId]/automation/page.tsx (1)

89-89: Spacing tweak LGTM.

mb-8 reads better in this layout; no functional impact.

apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx (1)

22-23: Good placement, but depends on PremiumAlert fix to actually gate trials.

With activeOnly, the alert must not be short-circuited by AI access; see suggested fix in PremiumAlert.tsx.

apps/web/components/PremiumAlert.tsx (1)

117-135: I’ve requested the relevant snippet for verification. [pending_results]

Comment on lines +37 to +57
{unhandledCount === null ? (
<SectionDescription className="mx-auto mt-2 max-w-prose">
You have {unhandledCount.toLocaleString()}{" "}
{cleanAction === CleanAction.ARCHIVE ? "unarchived" : "unread"}{" "}
emails in your inbox.
Checking your inbox...
</SectionDescription>
<SectionDescription className="mx-auto mt-2 max-w-prose">
Let's clean up your inbox while keeping important emails safe.
</SectionDescription>
</>
)}
) : (
<>
<SectionDescription className="mx-auto mt-2 max-w-prose">
You have {unhandledCount.toLocaleString()}{" "}
{cleanAction === CleanAction.ARCHIVE ? "unarchived" : "unread"}{" "}
emails in your inbox.
</SectionDescription>
<SectionDescription className="mx-auto mt-2 max-w-prose">
Let's clean up your inbox while keeping important emails safe.
</SectionDescription>
</>
)}

<div className="mt-6">
<Button onClick={onNext} disabled={unhandledCount === null}>
Next
</Button>
<div className="mt-6">
<Button onClick={onNext} disabled={unhandledCount === null}>
Next
</Button>
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

🧩 Analysis chain

Type mismatch: unhandledCount compared to null but typed as number.

Either change the prop type to number | null or remove the null checks. Prefer widening the type.

Proposed signature (outside this hunk):

export function IntroStep({
  unhandledCount,
  cleanAction,
}: {
  unhandledCount: number | null;
  cleanAction: CleanAction;
}) { /* ... */ }

🏁 Script executed:

#!/bin/bash
# Verify the IntroStep prop type and all call sites expect number|null
rg -nC2 'IntroStep\(' apps/web | sed -n '1,200p'
rg -nP 'unhandledCount:\s*(number( \| null)?)' --type=ts --type=tsx

Length of output: 920


🏁 Script executed:

#!/bin/bash
set -euo pipefail
echo "---- locate export function IntroStep occurrences ----"
rg -n --hidden -S 'export function IntroStep' apps/web || true

echo
target='apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx'
echo "---- show: $target ----"
if [ -f "$target" ]; then
  sed -n '1,300p' "$target"
else
  echo "File not found: $target"
fi

echo
echo "---- search for other files mentioning IntroStep (usages/definitions) ----"
rg -n --hidden -S '\bIntroStep\b' apps/web || true

echo
echo "---- search for 'unhandledCount' usages across repo ----"
rg -n --hidden -S '\bunhandledCount\b' apps/web || true

echo
echo "---- search for Props/type declarations referencing unhandledCount or IntroStep props ----"
rg -n --hidden -S 'unhandledCount|IntroStepProps|Intro.*Props|interface .*Props|type .*Props' apps/web || true

Length of output: 17404


🏁 Script executed:

#!/bin/bash
set -euo pipefail
file='apps/web/app/(app)/[emailAccountId]/clean/onboarding/page.tsx'
echo "---- show: $file ----"
if [ -f "$file" ]; then
  sed -n '1,240p' "$file"
else
  echo "File not found: $file"
fi

Length of output: 3258


🏁 Script executed:

#!/bin/bash
set -euo pipefail
file='apps/web/utils/assess.ts'
echo "---- show: $file (lines 1-240) ----"
if [ -f "$file" ]; then
  sed -n '1,240p' "$file"
else
  echo "File not found: $file"
fi

Length of output: 5372


Make IntroStep.unhandledCount nullable (number | null)

IntroStep compares unhandledCount to null (e.g. unhandledCount === null and disabled={unhandledCount === null}) but the prop is declared as number — this produces a TypeScript "condition always false" error. Widen the prop to number | null.

File: apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx — change the prop signature:

export function IntroStep({
  unhandledCount,
  cleanAction,
}: {
  unhandledCount: number | null;
  cleanAction: CleanAction;
}) { /* ... */ }
🤖 Prompt for AI Agents
In apps/web/app/(app)/[emailAccountId]/clean/IntroStep.tsx around lines 37 to
57, the component treats unhandledCount as possibly null but its prop type is
declared as number, causing a TS "condition always false" error; change the prop
signature to widen unhandledCount to number | null (update the function props
type to accept unhandledCount: number | null) so the null checks and disabled
prop are valid, and run TypeScript to ensure no other call sites need updates.

@elie222 elie222 deleted the feat/clean-active-premium branch December 18, 2025 23:02
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

Comments