Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughMigrates module-scoped logging to per-action, context-provided loggers across many actions. Several actions’ signatures now accept ctx.logger. ai-rule and rule onboarding flows are refactored for diff-driven updates and modular, concurrent rule lifecycle handling. Reporting and stats functions thread logger through helpers; premium logging is sanitized. Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor User
participant Action as saveRulesPromptAction
participant DB as Database
participant AI as aiDiffRules / aiPromptToRulesOld
participant Logger as ctx.logger
User->>Action: Submit new rulesPrompt
Action->>DB: Fetch existing emailAccount.rulesPrompt
Action->>Logger: log start
alt Existing prompt present
Action->>AI: aiDiffRules(old, new)
AI-->>Action: {added, edited, removed}
else No existing prompt
Action->>Action: Treat all as additions
end
par Create new rules
Action->>AI: aiPromptToRulesOld(added)
AI-->>Action: rule specs
loop each new rule
Action->>DB: safeCreateRule(rule)
end
and Edit existing rules
loop each edited rule
Action->>DB: safeUpdateRule(rule)
end
and Remove/disable rules
loop each removed rule
Action->>DB: deleteRule/disable
end
end
Action->>DB: Update emailAccount.rulesPrompt
Action-->>User: {created, edited, removed counts}
Action->>Logger: log finish
sequenceDiagram
autonumber
actor User
participant Action as createRulesOnboardingAction
participant DB as Database
participant Util as getActionsFromCategoryAction
participant Logger as ctx.logger
User->>Action: Provide system/custom categories
Action->>DB: Fetch emailAccount(rulesPrompt)
Action->>Action: Partition systemCategoryMap vs custom
par For each system category
Action->>Util: Compute actions
alt Rule exists
Action->>DB: Update rule (name/instructions/actions)
else No rule
Action->>DB: Create rule
end
opt Category absent / disabled
Action->>DB: Delete rule
end
and For each custom category
Action->>Util: Compute actions
Action->>DB: Create/Update custom rule
end
Action->>DB: Update rulesPrompt summary
Action-->>User: Onboarding result
Action->>Logger: Log errors/success per step
sequenceDiagram
autonumber
actor User
participant Action as generateReportAction
participant Svc as getEmailReportData
participant Gmail as Gmail API
participant AI as aiSummarizeEmails
participant Logger as ctx.logger
User->>Action: Generate report
Action->>Svc: getEmailReportData(emailAccountId, logger)
Svc->>Gmail: fetchGmailLabels(logger)
Svc->>Gmail: fetchGmailSignature(logger)
par Summaries
Svc->>AI: aiSummarizeEmails(...)
AI-->>Svc: summaries or error (caught -> [])
end
Svc-->>Action: Report data
Action-->>User: Report
Svc->>Logger: Log progress/errors
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60–90 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ 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. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
apps/web/utils/actions/stats.ts (1)
204-208: Add composite unique on EmailMessage: (emailAccountId, messageId)apps/web/prisma/schema.prisma — EmailMessage currently has @@unique([digestId, threadId, messageId]) but no @@unique([emailAccountId, messageId]); add @@unique([emailAccountId, messageId]) (or change the createMany logic) so skipDuplicates: true is actually backed by a DB unique constraint. (createMany call: apps/web/utils/actions/stats.ts:204-208)
apps/web/utils/actions/admin.ts (2)
71-85: Avoid PII in logs, don’t surface internal errors, and normalize/validate email input
- Don’t log full email addresses or bubble raw error messages in SafeError.
- Normalize email to lowercase for lookup.
- Validate the input as an email with Zod.
.metadata({ name: "adminDeleteAccount" }) - .schema(z.object({ email: z.string() })) - .action(async ({ parsedInput: { email }, ctx: { logger } }) => { + .schema(z.object({ email: z.string().email() })) + .action(async ({ parsedInput: { email }, ctx: { logger } }) => { try { - const userToDelete = await prisma.user.findUnique({ where: { email } }); + const normalizedEmail = email.trim().toLowerCase(); + const userToDelete = await prisma.user.findUnique({ + where: { email: normalizedEmail }, + }); if (!userToDelete) throw new SafeError("User not found"); await deleteUser({ userId: userToDelete.id }); } catch (error) { - logger.error("Failed to delete user", { email, error }); - throw new SafeError( - `Failed to delete user: ${error instanceof Error ? error.message : String(error)}`, - ); + const redacted = + email.includes("@") + ? email.replace(/^(.).+(@.+)$/, "$1***$2") + : "***"; + logger.error("Failed to delete user", { + emailDomain: redacted.split("@")[1], + error: error instanceof Error ? error.message : String(error), + }); + throw new SafeError("Failed to delete user"); } return { success: "User deleted" }; });
106-191: Tighten “active” customer detection, lower-case emails for lookup, and avoid logging email PII
- Consider subscription status when determining “active”.
- Normalize email before DB lookup.
- Don’t log full emails; prefer domain or omit.
- Optional: stream-process pages instead of accumulating allCustomers to reduce memory.
.action(async ({ ctx: { logger } }) => { const stripe = getStripe(); logger.info("Starting sync of all Stripe customers to DB"); let hasMore = true; let startingAfter: string | undefined; const allCustomers: Stripe.Customer[] = []; while (hasMore) { const customers: Stripe.Response<Stripe.ApiList<Stripe.Customer>> = await stripe.customers.list({ limit: 100, starting_after: startingAfter, expand: ["data.subscriptions"], }); allCustomers.push(...customers.data); hasMore = customers.has_more; if (hasMore) { startingAfter = customers.data[customers.data.length - 1]?.id; } } - const activeCustomers = allCustomers.filter( - (c) => c.subscriptions && c.subscriptions.data.length > 0, - ); + const activeCustomers = allCustomers.filter((c) => { + const subs = c.subscriptions?.data ?? []; + return subs.some((s) => + ["trialing", "active", "past_due", "unpaid", "paused"].includes( + String(s.status), + ), + ); + }); logger.info("Found active customers in Stripe.", { activeCustomersLength: activeCustomers.length, }); for (const customer of activeCustomers) { if (!customer.email) { logger.warn("Customer in Stripe has no email", { customerId: customer.id, }); continue; } - const user = await prisma.user.findUnique({ - where: { email: customer.email }, + const normalizedEmail = customer.email.toLowerCase(); + const user = await prisma.user.findUnique({ + where: { email: normalizedEmail }, include: { premium: true }, }); if (!user) { - logger.warn("No user found in our DB for stripe customer", { - stripeCustomerId: customer.id, - stripeCustomerEmail: customer.email, - }); + logger.warn("No user found in our DB for stripe customer", { + stripeCustomerId: customer.id, + emailDomain: customer.email.split("@")[1], + }); continue; } if (user.premium) { if ( user.premium.stripeCustomerId && user.premium.stripeCustomerId !== customer.id ) { logger.warn("Stripe customer ID mismatch for user", { dbStripeCustomerId: user.premium.stripeCustomerId, stripeCustomerId: customer.id, }); } if (user.premium.stripeCustomerId !== customer.id) { await prisma.premium.update({ where: { id: user.premium.id }, data: { stripeCustomerId: customer.id }, }); logger.info("Updated stripe customer ID for user", { stripeCustomerId: customer.id, }); } } else { logger.warn( "User with stripe customer email exists, but has no premium account", { stripeCustomerId: customer.id, }, ); } }
- Optional streaming (illustrative, not a full diff): process each page and act immediately instead of pushing into allCustomers.
🧹 Nitpick comments (17)
apps/web/utils/actions/settings.ts (2)
156-195: Avoid N+1 rule lookups; batch fetch once.Fetching each rule within the loop increases DB round-trips. Prefer one findMany for all ruleIds, keyed by id, then operate in-memory.
208-210: Harden against partial failures with settled results.One failing promise currently rejects the whole batch mid-way. Consider logging failures but proceeding for the rest.
Apply this diff:
- await Promise.all(promises); + const results = await Promise.allSettled(promises); + results.forEach((r) => { + if (r.status === "rejected") { + logger.error("Failed to update digest item", { error: r.reason }); + } + });apps/web/utils/actions/sso.ts (1)
115-118: Include providerId in failure log for correlation.Adds useful context without leaking PII.
Apply this diff:
- logger.error("Failed to register SSO provider", { - error: err, - organizationId: organization.id, - }); + logger.error("Failed to register SSO provider", { + error: err, + organizationId: organization.id, + providerId, + });apps/web/utils/actions/clean.ts (1)
131-146: Fix logging of page tokens (currently misleading).You log nextPageToken before assigning it; the logged value is the previous token. Log the returned pageToken instead.
Apply this diff:
- logger.info("Fetched threads", { - threadCount: threads.length, - nextPageToken, - }); + logger.info("Fetched threads", { + threadCount: threads.length, + nextPageToken: pageToken, + }); ... - logger.info("Pushing to Qstash", { - threadCount: threads.length, - nextPageToken, - }); + logger.info("Pushing to Qstash", { + threadCount: threads.length, + nextPageToken: pageToken, + });apps/web/utils/actions/admin.ts (1)
89-101: Make per-customer syncing resilient to individual failuresWrap each sync in try/catch to avoid aborting the whole run on a single failure.
.action(async ({ ctx: { logger } }) => { const users = await prisma.premium.findMany({ where: { stripeCustomerId: { not: null } }, select: { stripeCustomerId: true }, orderBy: { updatedAt: "asc" }, }); for (const premium of users) { if (!premium.stripeCustomerId) continue; logger.info("Syncing Stripe", { stripeCustomerId: premium.stripeCustomerId, }); - await syncStripeDataToDb({ customerId: premium.stripeCustomerId }); + try { + await syncStripeDataToDb({ customerId: premium.stripeCustomerId }); + } catch (error) { + logger.warn("Stripe sync failed for customer", { + stripeCustomerId: premium.stripeCustomerId, + error: error instanceof Error ? error.message : String(error), + }); + } } });apps/web/utils/actions/ai-rule.ts (3)
268-499: Save‑prompt flow looks solid; consider bounded concurrency for edits/removalsThe removal and edit loops run sequentially. For large diffs this can be slow. Use bounded concurrency (e.g., p-limit 5) to improve throughput while staying friendly to the DB/LLM rate limits.
Example pattern:
import pLimit from "p-limit"; const limit = pLimit(5); // deletions await Promise.allSettled( existingRules.removedRules.map((r) => limit(async () => { /* current delete/disable logic */ }), ), ); // edits await Promise.allSettled( editedRules.map((r) => limit(async () => { /* current update logic */ }), ), );
268-300: Normalize whitespace before equality check to avoid no-op AI runsIf users tweak whitespace only, consider normalizing before comparing to prevent needless work.
- if (oldPromptFile === rulesPrompt) { + if (oldPromptFile?.trim() === rulesPrompt.trim()) { logger.info("No changes in rules prompt, returning early"); return { createdRules: 0, editedRules: 0, removedRules: 0 }; }
312-351: Minor: unify log keys for clarityUse consistent keys (e.g., addedCount) to distinguish between “diff.addedRules length” and “rules to be added” throughout logs.
apps/web/utils/actions/report.ts (4)
43-45: Use SafeError for expected “not found”Aligns with centralized action error handling.
- if (!emailAccount) { - logger.error("Email account not found"); - throw new Error("Email account not found"); - } + if (!emailAccount) { + logger.error("Email account not found"); + throw new SafeError("Email account not found"); + }
257-260: Avoid logging full email addressesLog only the domain (or hash) when confirming signature fetch.
- logger.info("Gmail signature fetched successfully", { - hasSignature: !!signature, - sendAsEmail: primarySendAs.sendAsEmail, - }); + logger.info("Gmail signature fetched successfully", { + hasSignature: !!signature, + emailDomain: primarySendAs.sendAsEmail?.split("@")[1], + });
73-75: Optional: add logging to template fetch pathIf failures there are useful to diagnose, thread logger through fetchGmailTemplates or wrap with a .catch that logs and returns [].
223-227: Severity level: consider error for total Gmail label fetch failureFirst-page failure likely merits error vs warn; keep warn for per-label details.
apps/web/utils/actions/rule.ts (5)
588-592: Broaden type guard for isSet to include folder actionsCurrent predicate narrows to label-only actions. Include move_folder variants for accurate typing.
- const isSet = ( - value: string | undefined | null, - ): value is "label" | "label_archive" | "label_archive_delayed" => + const isSet = ( + value: string | undefined | null, + ): value is + | "label" + | "label_archive" + | "label_archive_delayed" + | "move_folder" + | "move_folder_delayed" => value !== "none" && value !== undefined;
639-733: Rename shadowing helpers to avoid confusion with imported deleteRule and generic “createRule”Local helpers shadow the imported deleteRule and are easily confused with the general createRule util. Rename to upsertCategoryRule and deleteSystemRule; update call sites.
- async function createRule( + async function upsertCategoryRule( name: string, instructions: string, promptFileInstructions: string, runOnThreads: boolean, categoryAction: | "label" | "label_archive" | "label_archive_delayed" | "move_folder" | "move_folder_delayed", label: string, systemType: SystemType | null, emailAccountId: string, hasDigest: boolean, ) { @@ - async function deleteRule( + async function deleteSystemRule( systemType: SystemType, emailAccountId: string, ) { @@ - if (newsletter && isSet(newsletter.action)) { - createRule( + if (newsletter && isSet(newsletter.action)) { + upsertCategoryRule( @@ - } else { - deleteRule(SystemType.NEWSLETTER, emailAccountId); + } else { + deleteSystemRule(SystemType.NEWSLETTER, emailAccountId); } @@ - if (marketing && isSet(marketing.action)) { - createRule( + if (marketing && isSet(marketing.action)) { + upsertCategoryRule( @@ - } else { - deleteRule(SystemType.MARKETING, emailAccountId); + } else { + deleteSystemRule(SystemType.MARKETING, emailAccountId); } @@ - if (calendar && isSet(calendar.action)) { - createRule( + if (calendar && isSet(calendar.action)) { + upsertCategoryRule( @@ - } else { - deleteRule(SystemType.CALENDAR, emailAccountId); + } else { + deleteSystemRule(SystemType.CALENDAR, emailAccountId); } @@ - if (receipt && isSet(receipt.action)) { - createRule( + if (receipt && isSet(receipt.action)) { + upsertCategoryRule( @@ - } else { - deleteRule(SystemType.RECEIPT, emailAccountId); + } else { + deleteSystemRule(SystemType.RECEIPT, emailAccountId); } @@ - if (notification && isSet(notification.action)) { - createRule( + if (notification && isSet(notification.action)) { + upsertCategoryRule( @@ - } else { - deleteRule(SystemType.NOTIFICATION, emailAccountId); + } else { + deleteSystemRule(SystemType.NOTIFICATION, emailAccountId); } @@ - for (const customCategory of customCategories) { + for (const customCategory of customCategories) { if (customCategory.action && isSet(customCategory.action)) { - createRule( + upsertCategoryRule( customCategory.name, @@ ); } }Also applies to: 735-749, 751-852, 856-863
612-636: Fire‑and‑forget fetch should be guardedAdd a catch to log failures of the background backfill trigger.
}).then((res) => { if (res?.alreadyEnabled) return; // Load previous emails needing replies in background // This can take a while - fetch( + fetch( `${env.NEXT_PUBLIC_BASE_URL}/api/reply-tracker/process-previous`, { method: "POST", headers: { "Content-Type": "application/json", [INTERNAL_API_KEY_HEADER]: env.INTERNAL_API_KEY, }, body: JSON.stringify({ emailAccountId, } satisfies ProcessPreviousBody), }, - ); + ).catch((error) => + logger.warn("Failed to trigger reply-tracker backfill", { + error: error instanceof Error ? error.message : String(error), + }), + ); });
663-691: Prefer await over .then(() => {}) for the update pathReadability and correctness (no accidental swallow of results).
- return ( - prisma.rule - .update({ - where: { id: existingRule.id }, - data: { - instructions, - actions: { - deleteMany: {}, - createMany: { data: actions }, - }, - }, - }) - // NOTE: doesn't update without this line - .then(() => {}) - .catch((error) => { - logger.error("Error updating rule", { error }); - throw error; - }) - ); + try { + await prisma.rule.update({ + where: { id: existingRule.id }, + data: { + instructions, + actions: { + deleteMany: {}, + createMany: { data: actions }, + }, + }, + }); + } catch (error) { + logger.error("Error updating rule", { error }); + throw error; + }
822-831: Label name consistency: Notification vs NotificationsPrompt text uses @[Notifications] but system label name is singular. Align to avoid drift.
- "Label all notifications as @[Notifications]", + "Label all notifications as @[Notification]",
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (12)
apps/web/utils/actions/admin.ts(4 hunks)apps/web/utils/actions/ai-rule.ts(2 hunks)apps/web/utils/actions/categorize.ts(1 hunks)apps/web/utils/actions/clean.ts(3 hunks)apps/web/utils/actions/permissions.ts(4 hunks)apps/web/utils/actions/premium.ts(2 hunks)apps/web/utils/actions/reply-tracking.ts(2 hunks)apps/web/utils/actions/report.ts(6 hunks)apps/web/utils/actions/rule.ts(3 hunks)apps/web/utils/actions/settings.ts(1 hunks)apps/web/utils/actions/sso.ts(1 hunks)apps/web/utils/actions/stats.ts(4 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
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/actions/premium.tsapps/web/utils/actions/categorize.tsapps/web/utils/actions/permissions.tsapps/web/utils/actions/settings.tsapps/web/utils/actions/stats.tsapps/web/utils/actions/clean.tsapps/web/utils/actions/reply-tracking.tsapps/web/utils/actions/rule.tsapps/web/utils/actions/admin.tsapps/web/utils/actions/report.tsapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/sso.ts
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-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/premium.tsapps/web/utils/actions/categorize.tsapps/web/utils/actions/permissions.tsapps/web/utils/actions/settings.tsapps/web/utils/actions/stats.tsapps/web/utils/actions/clean.tsapps/web/utils/actions/reply-tracking.tsapps/web/utils/actions/rule.tsapps/web/utils/actions/admin.tsapps/web/utils/actions/report.tsapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/sso.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/actions/premium.tsapps/web/utils/actions/categorize.tsapps/web/utils/actions/permissions.tsapps/web/utils/actions/settings.tsapps/web/utils/actions/stats.tsapps/web/utils/actions/clean.tsapps/web/utils/actions/reply-tracking.tsapps/web/utils/actions/rule.tsapps/web/utils/actions/admin.tsapps/web/utils/actions/report.tsapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/sso.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/premium.tsapps/web/utils/actions/categorize.tsapps/web/utils/actions/permissions.tsapps/web/utils/actions/settings.tsapps/web/utils/actions/stats.tsapps/web/utils/actions/clean.tsapps/web/utils/actions/reply-tracking.tsapps/web/utils/actions/rule.tsapps/web/utils/actions/admin.tsapps/web/utils/actions/report.tsapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/sso.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/actions/premium.tsapps/web/utils/actions/categorize.tsapps/web/utils/actions/permissions.tsapps/web/utils/actions/settings.tsapps/web/utils/actions/stats.tsapps/web/utils/actions/clean.tsapps/web/utils/actions/reply-tracking.tsapps/web/utils/actions/rule.tsapps/web/utils/actions/admin.tsapps/web/utils/actions/report.tsapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/sso.ts
apps/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 server
Files:
apps/web/utils/actions/premium.tsapps/web/utils/actions/categorize.tsapps/web/utils/actions/permissions.tsapps/web/utils/actions/settings.tsapps/web/utils/actions/stats.tsapps/web/utils/actions/clean.tsapps/web/utils/actions/reply-tracking.tsapps/web/utils/actions/rule.tsapps/web/utils/actions/admin.tsapps/web/utils/actions/report.tsapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/sso.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/premium.tsapps/web/utils/actions/categorize.tsapps/web/utils/actions/permissions.tsapps/web/utils/actions/settings.tsapps/web/utils/actions/stats.tsapps/web/utils/actions/clean.tsapps/web/utils/actions/reply-tracking.tsapps/web/utils/actions/rule.tsapps/web/utils/actions/admin.tsapps/web/utils/actions/report.tsapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/sso.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/premium.tsapps/web/utils/actions/categorize.tsapps/web/utils/actions/permissions.tsapps/web/utils/actions/settings.tsapps/web/utils/actions/stats.tsapps/web/utils/actions/clean.tsapps/web/utils/actions/reply-tracking.tsapps/web/utils/actions/rule.tsapps/web/utils/actions/admin.tsapps/web/utils/actions/report.tsapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/sso.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/actions/premium.tsapps/web/utils/actions/categorize.tsapps/web/utils/actions/permissions.tsapps/web/utils/actions/settings.tsapps/web/utils/actions/stats.tsapps/web/utils/actions/clean.tsapps/web/utils/actions/reply-tracking.tsapps/web/utils/actions/rule.tsapps/web/utils/actions/admin.tsapps/web/utils/actions/report.tsapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/sso.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/actions/premium.tsapps/web/utils/actions/categorize.tsapps/web/utils/actions/permissions.tsapps/web/utils/actions/settings.tsapps/web/utils/actions/stats.tsapps/web/utils/actions/clean.tsapps/web/utils/actions/reply-tracking.tsapps/web/utils/actions/rule.tsapps/web/utils/actions/admin.tsapps/web/utils/actions/report.tsapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/sso.ts
🧠 Learnings (15)
📓 Common learnings
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.616Z
Learning: Applies to apps/web/utils/ai/**/*.{ts,tsx} : Use descriptive scoped loggers for each feature
📚 Learning: 2025-09-17T22:05:28.616Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.616Z
Learning: Applies to apps/web/utils/ai/**/*.{ts,tsx} : Use descriptive scoped loggers for each feature
Applied to files:
apps/web/utils/actions/permissions.tsapps/web/utils/actions/stats.tsapps/web/utils/actions/clean.tsapps/web/utils/actions/reply-tracking.tsapps/web/utils/actions/rule.tsapps/web/utils/actions/admin.tsapps/web/utils/actions/report.tsapps/web/utils/actions/ai-rule.tsapps/web/utils/actions/sso.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 : 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/permissions.tsapps/web/utils/actions/settings.tsapps/web/utils/actions/reply-tracking.tsapps/web/utils/actions/admin.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 : Use `adminActionClient` for actions restricted to admin users.
Applied to files:
apps/web/utils/actions/permissions.tsapps/web/utils/actions/admin.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 : 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.
Applied to files:
apps/web/utils/actions/permissions.tsapps/web/utils/actions/stats.tsapps/web/utils/actions/clean.tsapps/web/utils/actions/reply-tracking.tsapps/web/utils/actions/admin.ts
📚 Learning: 2025-07-17T04:19:57.099Z
Learnt from: edulelis
PR: elie222/inbox-zero#576
File: packages/resend/emails/digest.tsx:78-83
Timestamp: 2025-07-17T04:19:57.099Z
Learning: In packages/resend/emails/digest.tsx, the DigestEmailProps type uses `[key: string]: DigestItem[] | undefined | string | Date | undefined` instead of intersection types like `& Record<string, DigestItem[] | undefined>` due to implementation constraints. This was the initial implementation approach and cannot be changed to more restrictive typing.
Applied to files:
apps/web/utils/actions/settings.ts
📚 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 `revalidatePath` in server actions for cache invalidation
Applied to files:
apps/web/utils/actions/reply-tracking.ts
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to apps/web/utils/actions/**/*.ts : Use `revalidatePath` in server actions to invalidate cache after mutations.
Applied to files:
apps/web/utils/actions/reply-tracking.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 : If an action modifies data displayed elsewhere, use `revalidatePath` or `revalidateTag` from `next/cache` within the action handler as needed.
Applied to files:
apps/web/utils/actions/reply-tracking.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/admin.ts
📚 Learning: 2025-07-18T15:05:16.146Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/fullstack-workflow.mdc:0-0
Timestamp: 2025-07-18T15:05:16.146Z
Learning: Applies to 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.
Applied to files:
apps/web/utils/actions/admin.ts
📚 Learning: 2025-06-23T12:26:53.882Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/prisma.mdc:0-0
Timestamp: 2025-06-23T12:26:53.882Z
Learning: In this project, Prisma should be imported using 'import prisma from "@/utils/prisma";' in TypeScript files.
Applied to files:
apps/web/utils/actions/admin.ts
📚 Learning: 2025-09-17T22:05:28.616Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.616Z
Learning: Applies to apps/web/utils/{ai,llms}/**/*.{ts,tsx} : Keep related AI functions co-located and extract common patterns into utilities; document complex AI logic with clear comments
Applied to files:
apps/web/utils/actions/ai-rule.ts
📚 Learning: 2025-09-17T22:05:28.616Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.616Z
Learning: Applies to apps/web/utils/ai/**/*.{ts,tsx} : Log inputs and outputs with appropriate log levels and include relevant context
Applied to files:
apps/web/utils/actions/ai-rule.ts
📚 Learning: 2025-09-17T22:05:28.616Z
Learnt from: CR
PR: elie222/inbox-zero#0
File: .cursor/rules/llm.mdc:0-0
Timestamp: 2025-09-17T22:05:28.616Z
Learning: Applies to apps/web/utils/ai/**/*.{ts,tsx} : Use proper error types and logging for failures
Applied to files:
apps/web/utils/actions/ai-rule.ts
🧬 Code graph analysis (8)
apps/web/utils/actions/premium.ts (1)
apps/web/app/api/outlook/webhook/logger.ts (1)
logger(3-3)
apps/web/utils/actions/permissions.ts (1)
apps/web/app/api/outlook/webhook/logger.ts (1)
logger(3-3)
apps/web/utils/actions/stats.ts (4)
apps/web/utils/actions/safe-action.ts (1)
actionClient(62-113)apps/web/utils/error.ts (1)
SafeError(86-96)apps/web/utils/email/provider.ts (1)
createEmailProvider(13-28)apps/web/utils/logger.ts (1)
Logger(5-5)
apps/web/utils/actions/reply-tracking.ts (2)
apps/web/utils/email/provider-types.ts (1)
isGoogleProvider(1-3)apps/web/utils/user/get.ts (1)
getEmailAccountWithAi(35-62)
apps/web/utils/actions/rule.ts (9)
apps/web/utils/rule/consts.ts (3)
SystemRule(12-20)SystemRule(21-21)RuleName(2-10)apps/web/utils/actions/rule.validation.ts (1)
CategoryConfig(213-213)apps/web/utils/error.ts (1)
SafeError(86-96)apps/web/utils/reply-tracker/enable.ts (1)
enableReplyTracker(12-140)apps/web/env.ts (1)
env(16-242)apps/web/utils/internal-api.ts (1)
INTERNAL_API_KEY_HEADER(4-4)apps/web/app/api/reply-tracker/process-previous/route.ts (1)
ProcessPreviousBody(15-15)apps/web/utils/rule/rule.ts (2)
createRule(152-208)deleteRule(279-295)apps/web/utils/prisma-helpers.ts (1)
isDuplicateError(3-12)
apps/web/utils/actions/admin.ts (1)
apps/web/app/api/outlook/webhook/logger.ts (1)
logger(3-3)
apps/web/utils/actions/report.ts (3)
apps/web/utils/actions/safe-action.ts (1)
actionClient(62-113)apps/web/utils/logger.ts (1)
Logger(5-5)apps/web/utils/user/get.ts (1)
getEmailAccountWithAi(35-62)
apps/web/utils/actions/ai-rule.ts (9)
apps/web/utils/error.ts (1)
SafeError(86-96)apps/web/utils/ai/rule/prompt-to-rules.ts (1)
aiPromptToRules(15-70)apps/web/utils/ai/rule/diff-rules.ts (1)
aiDiffRules(7-90)apps/web/utils/ai/rule/prompt-to-rules-old.ts (1)
aiPromptToRulesOld(20-86)apps/web/utils/ai/rule/find-existing-rules.ts (1)
aiFindExistingRules(7-100)apps/web/utils/rule/rule.ts (3)
deleteRule(279-295)safeUpdateRule(102-150)safeCreateRule(34-100)apps/web/utils/prisma-helpers.ts (1)
isNotFoundError(14-19)apps/web/utils/category.server.ts (1)
getUserCategoriesForNames(44-65)apps/web/utils/actions/safe-action.ts (1)
actionClient(62-113)
⏰ 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: cubic · AI code reviewer
🔇 Additional comments (19)
apps/web/utils/actions/premium.ts (2)
421-424: PII reduction in error logs looks good.Using ctx.logger without userId in the payload aligns with the logging guidelines and reduces sensitive data exposure.
499-502: Good swap to contextual logger on missing user.Consistent with per-request logging; keeps logs clean and non-PII.
apps/web/utils/actions/settings.ts (1)
153-155: Correct: switch to ctx.logger in action context.Signature/destructuring is consistent with safe-action client behavior.
apps/web/utils/actions/sso.ts (1)
19-21: LGTM: per-request logger via ctx.Matches the PR-wide pattern; no functional changes.
apps/web/utils/actions/categorize.ts (1)
31-41: Good migration to ctx.logger with structured error logging.The trace/info logs are scoped and avoid PII; pattern is consistent.
apps/web/utils/actions/clean.ts (1)
38-40: Correct: action context now includes logger.Consistent with safe-action instrumentation.
apps/web/utils/actions/stats.ts (2)
21-56: LGTM: action now threads a typed logger and validates provider before proceeding.Solid guardrails with SafeError; keeps provider selection explicit.
58-67: Good: propagate logger through helpers with explicit typing.Keeps observability consistent across pagination/save flows.
apps/web/utils/actions/reply-tracking.ts (2)
30-39: LGTM: contextual logging on missing account, with SafeError.Behavior and messaging are appropriate; no PII in logs.
56-63: LGTM: start/stop analyzer errors are captured with ctx.logger.Non-fatal errors are logged and flow proceeds as intended.
apps/web/utils/actions/permissions.ts (3)
13-16: LGTM: ctx.logger added to user-facing permissions check.Error path now logs via contextual logger.
42-45: Reasonable fallback on errors.Returning { false, false } while logging the root cause keeps UX predictable without leaking details.
51-79: LGTM: admin action now logs via ctx.logger.Structured error logging with SafeError surface to client is consistent with policy.
apps/web/utils/actions/ai-rule.ts (2)
43-45: LGTM: logger threaded into runRulesActionGood use of ctx.logger with structured fields before early-return.
448-455: Downstream logging consistency checksafeUpdateRule and getUserCategoriesForNames (see referenced snippets) still use a module-scoped logger. Ensure they’re migrated to use ctx.logger or accept a logger param for consistency.
apps/web/utils/actions/report.ts (2)
27-29: LGTM: per-request logger is passed throughGood shift to ctx.logger → getEmailReportData.
20-20: Type import is correctType-only Logger import keeps bundle lean.
apps/web/utils/actions/rule.ts (2)
130-140: LGTM: logger threaded into createRuleActionStructured error logging with SafeError on failures looks good.
237-247: LGTM: logger threaded into updateRuleActionError handling remains consistent with duplicate-name checks.
| .action(async ({ ctx: { emailAccountId, logger } }) => { | ||
| return getEmailReportData({ emailAccountId, logger }); | ||
| }); |
There was a problem hiding this comment.
🧩 Analysis chain
Repo-wide check for email PII in logs
Run to catch other places logging complete emails.
Also applies to: 43-45, 257-260
🏁 Script executed:
#!/bin/bash
# Search likely logger PII patterns
rg -nP --type=ts '(logger\\.(info|warn|error)\\(.+?(email|userEmail|sendAsEmail|stripeCustomerEmail))' -C2Length of output: 72
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "1) logger.<level> calls mentioning common email-like field names (TypeScript files):"
rg -n --type=ts -C2 'logger\.(info|warn|error|debug|trace|fatal)\s*\(.*(email|userEmail|sendAsEmail|stripeCustomerEmail|recipientEmail|fromEmail|toEmail|replyTo).*' || true
echo
echo "2) logger/console calls containing 'email' (JS/TS files, excluding node_modules):"
rg -n -C2 '\b(?:logger|console)\.(?:log|info|warn|error|debug|trace|fatal)\s*\(.*email.*' --glob '!**/node_modules/**' || true
echo
echo "3) Any 'email' tokens in TypeScript files (context for multi-line/logged objects):"
rg -n --type=ts -C3 'email' || trueLength of output: 267201
Remove/redact raw email addresses from logs (PII)
File: apps/web/utils/actions/report.ts
Lines: 27-29
.action(async ({ ctx: { emailAccountId, logger } }) => {
return getEmailReportData({ emailAccountId, logger });
});
Comment
Confirmed — repo-wide logger calls are emitting email PII (fields like email, userEmail, emailAccount.email, etc.). Stop logging raw addresses or full email content. Replace with emailAccountId or a masked/hashed value and audit helpers that accept a logger (e.g., getEmailReportData) to ensure they never log complete emails.
Examples to fix (representative):
- apps/web/utils/outlook/label.ts:370 — logger.warn(..., { threadId, userEmail: ownerEmail })
- apps/web/utils/gmail/label.ts:116 — logger.warn(..., { threadId, userEmail: ownerEmail })
- apps/web/utils/auth.ts:206 / 236 / 251-257 — multiple logger.info/error with { email }
- apps/web/app/api/watch/all/route.ts:56-59 — logger.info("Watching email accounts", { email: emailAccount.email })
- apps/web/app/api/google/webhook/process-history.ts:75 / 130 — logger.error/trace with { email }
- apps/web/utils/ai/assistant/chat.ts:972 — logger.info("Tracking tool call", { tool, email })
- apps/web/ee/billing/stripe/loops-events.ts:46 / 85 — logger.info(..., { email })
Action items:
- Remove email/userEmail/emailAccount.email from structured log metadata.
- Use emailAccountId, or log a masked/hash (not the full address) if needed for debugging.
- Audit all functions that accept
logger(e.g., getEmailReportData) to ensure no downstream logging of full emails or bodies. - Run a repo-wide search for logger.* usages that include "email" and patch remaining occurrences.
🤖 Prompt for AI Agents
In apps/web/utils/actions/report.ts around lines 27-29, the code passes a logger
that may cause downstream functions (getEmailReportData) to log raw email
addresses; remove any structured metadata that contains
email/userEmail/emailAccount.email and instead pass only emailAccountId (or a
masked/hashed email) to logs, update getEmailReportData and any helper that
accepts logger to avoid logging full addresses or message bodies, and perform a
quick audit for logger.* calls across the repo that include "email" to replace
them with emailAccountId or a masked value.
There was a problem hiding this comment.
4 issues found across 12 files
Prompt for AI agents (all 4 issues)
Understand the root cause of the following 4 issues and fix them.
<file name="apps/web/utils/actions/clean.ts">
<violation number="1" location="apps/web/utils/actions/clean.ts:38">
Missing pageToken in pagination call causes infinite loop and duplicate processing</violation>
</file>
<file name="apps/web/utils/actions/permissions.ts">
<violation number="1" location="apps/web/utils/actions/permissions.ts:51">
adminActionClient wipes ctx, so ctx.logger is undefined; using logger in adminCheckPermissionsAction causes runtime error in catch</violation>
<violation number="2" location="apps/web/utils/actions/permissions.ts:77">
Error log omits the email identifier, reducing traceability; include { email } in the log context for adminCheckPermissionsAction.</violation>
</file>
<file name="apps/web/utils/actions/rule.ts">
<violation number="1" location="apps/web/utils/actions/rule.ts:590">
isSet type guard excludes move_folder variants while they are supported; widen the predicate union to include them.</violation>
</file>
React with 👍 or 👎 to teach cubic. Mention @cubic-dev-ai to give feedback, ask questions, or re-run the review.
Summary by CodeRabbit
Refactor
Bug Fixes