Conversation
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Caution Review failedThe pull request is closed. Note Other AI code review bot(s) detectedCodeRabbit 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. WalkthroughMembers passes Changes
Sequence Diagram(s)sequenceDiagram
autonumber
actor User
participant Members UI as Members UI
participant Modal as InviteMemberModal
participant Action as inviteMemberAction (actionClientUser)
participant DB as Prisma
participant Mail as Email Service
User->>Members UI: Open Members page (organizationId)
Members UI->>Modal: Render with organizationId
User->>Modal: Fill email & role, submit
Modal->>Action: submit { email, role, organizationId }
Note over Action: Context from actionClientUser provides userId
Action->>DB: Verify inviter is org member with required role
alt Duplicate pending invite exists
Action-->>Modal: Error (invitation exists)
else Valid invitation
Action->>DB: Create invitation (expires in 14 days)
Action->>Mail: Send invitation email
Action-->>Modal: Success
end
Modal-->>Members UI: Close / refresh list
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
📜 Recent review detailsConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro 📒 Files selected for processing (2)
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 (1)
apps/web/utils/actions/__tests__/invitation-actions.test.ts (1)
28-31: Fix incomplete Prisma mock (prevents runtime errors).
inviteMemberActionreadsemailAccountIdandemailAccountfrom the inviter member. The mock omits these and can cause undefined access or an invalidinviterId.Update the mock:
prisma.member.findFirst.mockResolvedValueOnce({ organizationId: "org_1", role: "owner", + emailAccountId: "ea_inviter", + emailAccount: { name: "Inviter", email: "inviter@test.com" }, } as any);
🧹 Nitpick comments (12)
apps/web/utils/actions/__tests__/invitation-actions.test.ts (3)
36-40: Call shape update looks correct; consider asserting side effects.Good switch to object-arg for
inviteMemberAction. Add an assertion thatsendOrganizationInvitationwas called with the right args to fully validate behavior.Example:
vi.mock("@/utils/organizations/invitations", () => ({ sendOrganizationInvitation: vi.fn(), })); // later expect(require("@/utils/organizations/invitations").sendOrganizationInvitation) .toHaveBeenCalledWith( expect.objectContaining({ email: "user@test.com", invitationId: "inv_1", }), );
22-27: Remove stale mock (no longer used).
prisma.emailAccount.findUniqueisn’t used by the current action; keeping it increases noise.- prisma.emailAccount.findUnique.mockResolvedValue({ - id: "ea_inviter", - email: "inviter@test.com", - name: "Inviter", - account: { userId: "u1", provider: "google" }, - } as any);
12-20: Add negative-path tests for authz and membership.Cover cases where:
- Caller isn’t a member of the org
- Caller is a member but not admin/owner
- Caller attempts to invite an owner without being an owner
I can add tests stubbing Prisma returns to validate
SafeErrormessages and ensure no invitation is created. Want me to push a test patch?apps/web/utils/actions/invite-member.validation.ts (2)
6-6: Harden validation fororganizationId.Ensure it’s non-empty to avoid accidental empty string submission.
- organizationId: z.string(), + organizationId: z.string().min(1, "Organization is required"),
3-7: Normalize email at validation layer.Lowercasing and trimming at schema keeps client/server consistent.
export const inviteMemberBody = z.object({ - email: z.string().email("Please enter a valid email address"), + email: z + .string() + .trim() + .toLowerCase() + .email("Please enter a valid email address"), role: z.enum(["owner", "admin", "member"]), organizationId: z.string().min(1, "Organization is required"), });apps/web/utils/actions/invite-member.ts (5)
28-31: Clarify membership error message.If membership is checked against a specific
organizationId, prefer a precise message.- throw new SafeError("You are not a member of any organization."); + throw new SafeError("You are not a member of this organization.");
44-54: Normalize email once; avoid duplicate pending invites race.
- Normalize
normalizedEmail.- Consider guarding against concurrent duplicate invitations (unique index or transactional check).
- const existing = await prisma.invitation.findFirst({ + const normalizedEmail = email.trim().toLowerCase(); + const existing = await prisma.invitation.findFirst({ where: { organizationId: inviterMember.organizationId, - email: email.trim(), + email: normalizedEmail, status: "pending", }, select: { id: true }, }); if (existing) { return; }
56-66: Use normalized email for creation.Keeps stored values consistent.
- email: email.trim(), + email: normalizedEmail,
73-80: Consider cache invalidation after mutation.If any page lists members or pending invites, revalidate it here.
Please confirm which path/tag should be revalidated (e.g., members page). If applicable, add:
import { revalidatePath } from "next/cache"; // ... revalidatePath(`/organization/${inviterMember.organizationId}`);
10-17: Optional: add minimal structured logging via ctx.logger.Helpful for auditing invite attempts and outcomes.
Example:
const { logger } = ctx; logger.info("Inviting member", { organizationId, email: normalizedEmail, role });apps/web/components/InviteMemberModal.tsx (2)
113-118: Register role to guarantee inclusion in payload.You’re using
setValue("role", ...)with a custom Select; register it to avoid edge cases.Covered in the previous diff via
register("role"). If you prefer Controller:// import { Controller } from "react-hook-form"; <Controller name="role" render={({ field: { value, onChange } }) => ( <Select value={value} onValueChange={(v) => onChange(v)}> ... </Select> )} />
58-61: Use action result helpers in UI as per guidelines.Handling
result?.serverErroris correct; optionally surface validation errors next to fields using RHFerrors.Example:
{errors.role && <p className="text-sm text-destructive">{errors.role.message}</p>}
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (6)
apps/web/app/(app)/organization/[organizationId]/Members.tsx(2 hunks)apps/web/components/InviteMemberModal.tsx(4 hunks)apps/web/utils/actions/__tests__/invitation-actions.test.ts(1 hunks)apps/web/utils/actions/invite-member.ts(1 hunks)apps/web/utils/actions/invite-member.validation.ts(1 hunks)version.txt(1 hunks)
🧰 Additional context used
📓 Path-based instructions (25)
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/InviteMemberModal.tsxapps/web/utils/actions/invite-member.validation.tsapps/web/utils/actions/invite-member.tsapps/web/utils/actions/__tests__/invitation-actions.test.tsapps/web/app/(app)/organization/[organizationId]/Members.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/components/InviteMemberModal.tsxapps/web/app/(app)/organization/[organizationId]/Members.tsx
apps/web/components/**/*.tsx
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
Use React Hook Form with Zod validation for form handling
Use the
LoadingContentcomponent to handle loading and error states consistently in data-fetching components.Use PascalCase for components (e.g.
components/Button.tsx)
Files:
apps/web/components/InviteMemberModal.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/components/InviteMemberModal.tsxversion.txtapps/web/utils/actions/invite-member.validation.tsapps/web/utils/actions/invite-member.tsapps/web/utils/actions/__tests__/invitation-actions.test.tsapps/web/app/(app)/organization/[organizationId]/Members.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/InviteMemberModal.tsxapps/web/app/(app)/organization/[organizationId]/Members.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/components/InviteMemberModal.tsxapps/web/utils/actions/invite-member.validation.tsapps/web/utils/actions/invite-member.tsapps/web/utils/actions/__tests__/invitation-actions.test.tsapps/web/app/(app)/organization/[organizationId]/Members.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/components/InviteMemberModal.tsxapps/web/utils/actions/invite-member.validation.tsapps/web/utils/actions/invite-member.tsapps/web/utils/actions/__tests__/invitation-actions.test.tsapps/web/app/(app)/organization/[organizationId]/Members.tsx
!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/components/InviteMemberModal.tsxversion.txtapps/web/utils/actions/invite-member.validation.tsapps/web/utils/actions/invite-member.tsapps/web/utils/actions/__tests__/invitation-actions.test.tsapps/web/app/(app)/organization/[organizationId]/Members.tsx
**/*.{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/InviteMemberModal.tsxapps/web/app/(app)/organization/[organizationId]/Members.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/InviteMemberModal.tsxapps/web/app/(app)/organization/[organizationId]/Members.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/invite-member.validation.tsapps/web/utils/actions/invite-member.tsapps/web/utils/actions/__tests__/invitation-actions.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 ZodFiles:
apps/web/utils/actions/invite-member.validation.tsapps/web/utils/actions/invite-member.tsapps/web/utils/actions/__tests__/invitation-actions.test.tsapps/web/utils/actions/*.validation.ts
📄 CodeRabbit inference engine (.cursor/rules/fullstack-workflow.mdc)
Define Zod schemas for validation in dedicated files and use them for both client and server validation.
Define input validation schemas using Zod in the corresponding
.validation.tsfile. These schemas are used bynext-safe-action(.schema()) and can also be reused on the client for form validation.Files:
apps/web/utils/actions/invite-member.validation.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/invite-member.validation.tsapps/web/utils/actions/invite-member.tsapps/web/utils/**
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
Create utility functions in
utils/folder for reusable logicFiles:
apps/web/utils/actions/invite-member.validation.tsapps/web/utils/actions/invite-member.tsapps/web/utils/actions/__tests__/invitation-actions.test.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/invite-member.validation.tsapps/web/utils/actions/invite-member.tsapps/web/utils/actions/__tests__/invitation-actions.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/actions/__tests__/invitation-actions.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/actions/__tests__/invitation-actions.test.ts**/*.test.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)
**/*.test.{ts,tsx}: Use Vitest (vitest) as the testing framework
Colocate tests next to the file under test (e.g., dir/format.ts with dir/format.test.ts)
In tests, mock theserver-onlymodule withvi.mock("server-only", () => ({}));
When testing code that uses Prisma, mock it withvi.mock("@/utils/prisma")and use the mock from@/utils/__mocks__/prisma
Use provided helpers for mocks: import{ getEmail, getEmailAccount, getRule }from@/__tests__/helpers
Each test should be independent
Use descriptive test names
Mock external dependencies in tests
Clean up mocks between tests (e.g.,vi.clearAllMocks()inbeforeEach)
Avoid testing implementation details; focus on observable behavior
Do not mock the LoggerFiles:
apps/web/utils/actions/__tests__/invitation-actions.test.ts**/__tests__/**
📄 CodeRabbit inference engine (.cursor/rules/testing.mdc)
Place AI tests in the
__tests__directory and exclude them from the default test run (they use a real LLM)Files:
apps/web/utils/actions/__tests__/invitation-actions.test.tsapps/web/app/**
📄 CodeRabbit inference engine (apps/web/CLAUDE.md)
NextJS app router structure with (app) directory
Files:
apps/web/app/(app)/organization/[organizationId]/Members.tsxapps/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)/organization/[organizationId]/Members.tsxapps/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)/organization/[organizationId]/Members.tsxapps/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)/organization/[organizationId]/Members.tsxapps/web/app/**/*.tsx
📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)
Components with
onClickmust be client components withuse clientdirectiveFiles:
apps/web/app/(app)/organization/[organizationId]/Members.tsx🧠 Learnings (9)
📚 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/components/**/*Form.tsx : Use React Hook Form with Zod resolver for form handling and validation.Applied to files:
apps/web/components/InviteMemberModal.tsx📚 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/components/**/*.tsx : Use React Hook Form with Zod validation for form handlingApplied to files:
apps/web/components/InviteMemberModal.tsx📚 Learning: 2025-07-18T15:04:57.115Z
Learnt from: CR PR: elie222/inbox-zero#0 File: .cursor/rules/form-handling.mdc:0-0 Timestamp: 2025-07-18T15:04:57.115Z Learning: Applies to **/*.tsx : Use React Hook Form with Zod for validationApplied to files:
apps/web/components/InviteMemberModal.tsx📚 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/*.validation.ts : Define Zod schemas for validation in dedicated files and use them for both client and server validation.Applied to files:
apps/web/utils/actions/invite-member.validation.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 `actionClientUser` when only authenticated user context (`userId`) is needed.Applied to files:
apps/web/utils/actions/invite-member.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/invite-member.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/invite-member.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/invite-member.ts📚 Learning: 2025-08-31T12:17:19.419Z
Learnt from: CR PR: elie222/inbox-zero#0 File: .cursor/rules/llm-test.mdc:0-0 Timestamp: 2025-08-31T12:17:19.419Z Learning: Applies to apps/web/__tests__/**/*.test.ts : Test both AI and non-AI code paths (e.g., return unchanged when no AI processing is needed)Applied to files:
apps/web/utils/actions/__tests__/invitation-actions.test.ts🧬 Code graph analysis (4)
apps/web/components/InviteMemberModal.tsx (1)
apps/web/utils/actions/invite-member.ts (1)
inviteMemberAction(10-81)apps/web/utils/actions/invite-member.ts (5)
apps/web/utils/actions/safe-action.ts (1)
actionClientUser(116-140)apps/web/utils/actions/invite-member.validation.ts (1)
inviteMemberBody(3-7)apps/web/utils/error.ts (1)
SafeError(86-96)apps/web/utils/organizations/roles.ts (1)
hasOrganizationAdminRole(3-5)apps/web/utils/organizations/invitations.ts (1)
sendOrganizationInvitation(5-29)apps/web/utils/actions/__tests__/invitation-actions.test.ts (1)
apps/web/utils/actions/invite-member.ts (1)
inviteMemberAction(10-81)apps/web/app/(app)/organization/[organizationId]/Members.tsx (1)
apps/web/components/InviteMemberModal.tsx (1)
InviteMemberModal(34-141)⏰ 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). (2)
- GitHub Check: Vercel Agent Review
- GitHub Check: cubic · AI code reviewer
🔇 Additional comments (4)
version.txt (1)
1-1: Version bump LGTM.apps/web/utils/actions/invite-member.ts (1)
10-17: Switch toactionClientUserand object-arg: good move.Aligns with safe-action ctx usage and the updated schema.
apps/web/app/(app)/organization/[organizationId]/Members.tsx (2)
93-93: Invite modal now has the required org context ✅Passing
organizationIdthrough keeps the modal in sync with the updated action requirements—nice catch keeping the data flow consistent.
172-173: Localized count copy reads greatFormatting the usage metric with
toLocaleString()and the refreshed label make the stat clearer without extra logic. Looks good.
| organizationId, | ||
| role: "member", | ||
| }, | ||
| }); |
There was a problem hiding this comment.
organizationId is not registered; it won’t be submitted.
RHF only submits registered fields; organizationId is in defaultValues but never registered, so server will reject missing organizationId.
Apply this diff:
-import { useCallback } from "react";
+import { useCallback, useEffect } from "react";
@@
} = useForm<InviteMemberBody>({
resolver: zodResolver(inviteMemberBody),
defaultValues: {
organizationId,
role: "member",
},
});
+
+ useEffect(() => {
+ // Ensure hidden fields are part of form submission
+ // (register + setValue is sufficient; no need for a visible input)
+ // Also register role to guarantee inclusion.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ const unregisterOrg = register("organizationId");
+ const unregisterRole = register("role");
+ setValue("organizationId", organizationId);
+ return () => {
+ unregisterOrg?.();
+ unregisterRole?.();
+ };
+ }, [organizationId, register, setValue]);Alternatively, add a hidden input inside the form:
<input type="hidden" {...register("organizationId")} value={organizationId} />🤖 Prompt for AI Agents
In apps/web/components/InviteMemberModal.tsx around lines 49 to 52,
organizationId is included in defaultValues but never registered with React Hook
Form so it won’t be submitted; fix by registering it in the form (e.g., add a
hidden input inside the form that uses {...register("organizationId")} and sets
value={organizationId}) or call register("organizationId", { value:
organizationId }) when initializing so the organizationId is part of the
submitted form data.
There was a problem hiding this comment.
4 issues found across 6 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/invite-member.validation.ts">
<violation number="1" location="apps/web/utils/actions/invite-member.validation.ts:6">
organizationId is validated as a plain string, allowing empty values; enforce non-empty to prevent invalid requests.</violation>
</file>
<file name="apps/web/app/(app)/organization/[organizationId]/Members.tsx">
<violation number="1" location="apps/web/app/(app)/organization/[organizationId]/Members.tsx:172">
Label likely misrepresents the metric. The value is the count of executed rules from the API, but the text says "assistant processed emails". Consider aligning the copy with the actual metric or updating the metric accordingly.</violation>
</file>
<file name="apps/web/utils/actions/invite-member.ts">
<violation number="1" location="apps/web/utils/actions/invite-member.ts:29">
Misleading error message: check is org-specific but message says “any organization”.</violation>
<violation number="2" location="apps/web/utils/actions/invite-member.ts:47">
Email not normalized to lowercase when creating invitation; can cause duplicate or inconsistent records.</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
New Features
Style
Chores