🙌 OpenHands: AI-Driven Development
feat: auto-accept invitation links instead of the confirm/cancel modal (#14786)
Alona251ac40ebf0e
diff --git a/enterprise/server/services/org_invitation_service.py b/enterprise/server/services/org_invitation_service.pyindex ed0d1def4a..b84a379860 100644--- a/enterprise/server/services/org_invitation_service.py+++ b/enterprise/server/services/org_invitation_service.py@@ -294,6 +294,17 @@ class OrgInvitationService:if invitation.status != OrgInvitation.STATUS_PENDING:if invitation.status == OrgInvitation.STATUS_ACCEPTED:+ # The invitation may have been accepted on this user's behalf+ # already (e.g. by email match during the sign-in that just+ # happened). For the invited user that is success, not an+ # invalid token.+ existing_member = await OrgMemberStore.get_org_member(+ invitation.org_id, user_id+ )+ if existing_member:+ raise UserAlreadyMemberError(+ 'You are already a member of this organization'+ )raise InvitationInvalidError('Invitation has already been accepted')elif invitation.status == OrgInvitation.STATUS_REVOKED:raise InvitationInvalidError('Invitation has been revoked')diff --git a/enterprise/tests/unit/test_org_invitation_service.py b/enterprise/tests/unit/test_org_invitation_service.pyindex c0926a9a13..26bfe25e88 100644--- a/enterprise/tests/unit/test_org_invitation_service.py+++ b/enterprise/tests/unit/test_org_invitation_service.py@@ -7,6 +7,8 @@ import pytestfrom pydantic import SecretStrfrom server.routes.org_invitation_models import (EmailMismatchError,+ InvitationInvalidError,+ UserAlreadyMemberError,)from server.services.org_invitation_service import OrgInvitationServicefrom storage.org_invitation import OrgInvitation@@ -666,3 +668,77 @@ class TestCreateInvitationsBatch:)assert 'Invalid role' in str(exc_info.value)+++class TestAcceptInvitationAlreadyAccepted:+ """Accepting an already-accepted invitation should be benign for members.++ The invitation may have been accepted on the user's behalf already (e.g.+ by verified-email match during sign-in), after which the frontend still+ submits the token. That must surface as "already a member", not as an+ invalid-token error.+ """++ def _invitation(self, status=OrgInvitation.STATUS_ACCEPTED):+ invitation = MagicMock(spec=OrgInvitation)+ invitation.id = 1+ invitation.email = '[email protected]'+ invitation.status = status+ invitation.org_id = UUID('12345678-1234-5678-1234-567812345678')+ invitation.role_id = 1+ return invitation++ @pytest.mark.asyncio+ async def test_already_accepted_and_member_raises_already_member(self):+ user_id = UUID('87654321-4321-8765-4321-876543218765')++ with (+ patch(+ 'server.services.org_invitation_service.OrgInvitationStore.get_invitation_by_token',+ new_callable=AsyncMock,+ ) as mock_get_invitation,+ patch(+ 'server.services.org_invitation_service.OrgMemberStore.get_org_member',+ new_callable=AsyncMock,+ ) as mock_get_member,+ ):+ mock_get_invitation.return_value = self._invitation()+ mock_get_member.return_value = MagicMock()++ with pytest.raises(UserAlreadyMemberError):+ await OrgInvitationService.accept_invitation('inv-token', user_id)++ @pytest.mark.asyncio+ async def test_already_accepted_but_not_member_raises_invalid(self):+ user_id = UUID('87654321-4321-8765-4321-876543218765')++ with (+ patch(+ 'server.services.org_invitation_service.OrgInvitationStore.get_invitation_by_token',+ new_callable=AsyncMock,+ ) as mock_get_invitation,+ patch(+ 'server.services.org_invitation_service.OrgMemberStore.get_org_member',+ new_callable=AsyncMock,+ ) as mock_get_member,+ ):+ mock_get_invitation.return_value = self._invitation()+ mock_get_member.return_value = None++ with pytest.raises(InvitationInvalidError):+ await OrgInvitationService.accept_invitation('inv-token', user_id)++ @pytest.mark.asyncio+ async def test_revoked_invitation_still_raises_invalid(self):+ user_id = UUID('87654321-4321-8765-4321-876543218765')++ with patch(+ 'server.services.org_invitation_service.OrgInvitationStore.get_invitation_by_token',+ new_callable=AsyncMock,+ ) as mock_get_invitation:+ mock_get_invitation.return_value = self._invitation(+ status=OrgInvitation.STATUS_REVOKED+ )++ with pytest.raises(InvitationInvalidError):+ await OrgInvitationService.accept_invitation('inv-token', user_id)diff --git a/frontend/__tests__/components/features/invitations/invitation-accept-modal.test.tsx b/frontend/__tests__/components/features/invitations/invitation-accept-modal.test.tsxdeleted file mode 100644index fc3973efd4..0000000000--- a/frontend/__tests__/components/features/invitations/invitation-accept-modal.test.tsx+++ /dev/null@@ -1,321 +0,0 @@-import { describe, it, expect, vi, beforeEach } from "vitest";-import { screen, waitFor } from "@testing-library/react";-import userEvent from "@testing-library/user-event";-import { renderWithProviders, createAxiosError } from "test-utils";-import { InvitationAcceptModal } from "#/components/features/invitations/invitation-accept-modal";-import { organizationService } from "#/api/organization-service/organization-service.api";-import * as toastHandlers from "#/utils/custom-toast-handlers";--// Mock the organization service-vi.mock("#/api/organization-service/organization-service.api", () => ({- organizationService: {- acceptInvitation: vi.fn(),- },-}));--// Mock toast handlers-vi.mock("#/utils/custom-toast-handlers", () => ({- displaySuccessToast: vi.fn(),- displayErrorToast: vi.fn(),-}));--describe("InvitationAcceptModal", () => {- const mockToken = "test-invitation-token-123";- const mockOnClose = vi.fn();- const mockOnSuccess = vi.fn();-- beforeEach(() => {- vi.clearAllMocks();- });-- it("should render the modal with title and description", () => {- renderWithProviders(- <InvitationAcceptModal- token={mockToken}- onClose={mockOnClose}- onSuccess={mockOnSuccess}- />,- );-- expect(screen.getByTestId("invitation-accept-modal")).toBeInTheDocument();- expect(- screen.getByText("ORG$INVITATION_ACCEPT_TITLE"),- ).toBeInTheDocument();- expect(- screen.getByText("ORG$INVITATION_ACCEPT_DESCRIPTION"),- ).toBeInTheDocument();- });-- it("should render accept and cancel buttons", () => {- renderWithProviders(- <InvitationAcceptModal- token={mockToken}- onClose={mockOnClose}- onSuccess={mockOnSuccess}- />,- );-- expect(screen.getByTestId("accept-invitation-button")).toBeInTheDocument();- expect(screen.getByTestId("cancel-invitation-button")).toBeInTheDocument();- });-- it("should call onClose when cancel button is clicked", async () => {- const user = userEvent.setup();-- renderWithProviders(- <InvitationAcceptModal- token={mockToken}- onClose={mockOnClose}- onSuccess={mockOnSuccess}- />,- );-- await user.click(screen.getByTestId("cancel-invitation-button"));-- expect(mockOnClose).toHaveBeenCalledOnce();- });-- it("should call acceptInvitation when accept button is clicked", async () => {- const user = userEvent.setup();- const mockResponse = {- success: true,- org_id: "org-123",- org_name: "Test Organization",- role: "member",- };-- vi.mocked(organizationService.acceptInvitation).mockResolvedValueOnce(- mockResponse,- );-- renderWithProviders(- <InvitationAcceptModal- token={mockToken}- onClose={mockOnClose}- onSuccess={mockOnSuccess}- />,- );-- await user.click(screen.getByTestId("accept-invitation-button"));-- await waitFor(() => {- expect(organizationService.acceptInvitation).toHaveBeenCalledWith({- token: mockToken,- });- });- });-- it("should call onSuccess with org_id and show success toast on successful acceptance", async () => {- const user = userEvent.setup();- const mockResponse = {- success: true,- org_id: "org-123",- org_name: "Test Organization",- role: "member",- };-- vi.mocked(organizationService.acceptInvitation).mockResolvedValueOnce(- mockResponse,- );-- renderWithProviders(- <InvitationAcceptModal- token={mockToken}- onClose={mockOnClose}- onSuccess={mockOnSuccess}- />,- );-- await user.click(screen.getByTestId("accept-invitation-button"));-- await waitFor(() => {- expect(mockOnSuccess).toHaveBeenCalledWith({- orgId: "org-123",- orgName: "Test Organization",- isPersonal: false,- });- });-- expect(toastHandlers.displaySuccessToast).toHaveBeenCalled();- });-- it("should show loading spinner and disable buttons while accepting", async () => {- const user = userEvent.setup();-- // Create a promise that we can control- let resolvePromise: (value: unknown) => void;- const pendingPromise = new Promise((resolve) => {- resolvePromise = resolve;- });-- vi.mocked(organizationService.acceptInvitation).mockReturnValueOnce(- pendingPromise as Promise<{- success: boolean;- org_id: string;- org_name: string;- role: string;- }>,- );-- renderWithProviders(- <InvitationAcceptModal- token={mockToken}- onClose={mockOnClose}- onSuccess={mockOnSuccess}- />,- );-- // Click accept to trigger loading state- await user.click(screen.getByTestId("accept-invitation-button"));-- // Check loading state- await waitFor(() => {- expect(screen.getByTestId("loading-spinner")).toBeInTheDocument();- });- expect(screen.getByTestId("accept-invitation-button")).toBeDisabled();- expect(screen.getByTestId("cancel-invitation-button")).toBeDisabled();-- // Resolve the promise to clean up- resolvePromise!({- success: true,- org_id: "org-123",- org_name: "Test Organization",- role: "member",- });- });-- describe("error handling", () => {- it("should show expired error toast and call onClose when invitation is expired", async () => {- const user = userEvent.setup();-- vi.mocked(organizationService.acceptInvitation).mockRejectedValueOnce(- createAxiosError(400, "Bad Request", { detail: "invitation_expired" }),- );-- renderWithProviders(- <InvitationAcceptModal- token={mockToken}- onClose={mockOnClose}- onSuccess={mockOnSuccess}- />,- );-- await user.click(screen.getByTestId("accept-invitation-button"));-- await waitFor(() => {- expect(toastHandlers.displayErrorToast).toHaveBeenCalledWith(- "ORG$INVITATION_EXPIRED",- );- });-- expect(mockOnClose).toHaveBeenCalledOnce();- expect(mockOnSuccess).not.toHaveBeenCalled();- });-- it("should show invalid error toast and call onClose when invitation is invalid", async () => {- const user = userEvent.setup();-- vi.mocked(organizationService.acceptInvitation).mockRejectedValueOnce(- createAxiosError(400, "Bad Request", { detail: "invitation_invalid" }),- );-- renderWithProviders(- <InvitationAcceptModal- token={mockToken}- onClose={mockOnClose}- onSuccess={mockOnSuccess}- />,- );-- await user.click(screen.getByTestId("accept-invitation-button"));-- await waitFor(() => {- expect(toastHandlers.displayErrorToast).toHaveBeenCalledWith(- "ORG$INVITATION_INVALID",- );- });-- expect(mockOnClose).toHaveBeenCalledOnce();- });-- it("should show already member error toast when user is already a member", async () => {- const user = userEvent.setup();-- vi.mocked(organizationService.acceptInvitation).mockRejectedValueOnce(- createAxiosError(409, "Conflict", { detail: "already_member" }),- );-- renderWithProviders(- <InvitationAcceptModal- token={mockToken}- onClose={mockOnClose}- onSuccess={mockOnSuccess}- />,- );-- await user.click(screen.getByTestId("accept-invitation-button"));-- await waitFor(() => {- expect(toastHandlers.displayErrorToast).toHaveBeenCalledWith(- "ORG$ALREADY_MEMBER",- );- });-- expect(mockOnClose).toHaveBeenCalledOnce();- });-- it("should show email mismatch error toast when email does not match", async () => {- const user = userEvent.setup();-- vi.mocked(organizationService.acceptInvitation).mockRejectedValueOnce(- createAxiosError(403, "Forbidden", { detail: "email_mismatch" }),- );-- renderWithProviders(- <InvitationAcceptModal- token={mockToken}- onClose={mockOnClose}- onSuccess={mockOnSuccess}- />,- );-- await user.click(screen.getByTestId("accept-invitation-button"));-- await waitFor(() => {- expect(toastHandlers.displayErrorToast).toHaveBeenCalledWith(- "ORG$INVITATION_EMAIL_MISMATCH",- );- });-- expect(mockOnClose).toHaveBeenCalledOnce();- });-- it("should show generic error toast for unknown errors", async () => {- const user = userEvent.setup();-- vi.mocked(organizationService.acceptInvitation).mockRejectedValueOnce(- createAxiosError(500, "Internal Server Error", {- detail: "unexpected_error",- }),- );-- renderWithProviders(- <InvitationAcceptModal- token={mockToken}- onClose={mockOnClose}- onSuccess={mockOnSuccess}- />,- );-- await user.click(screen.getByTestId("accept-invitation-button"));-- await waitFor(() => {- expect(toastHandlers.displayErrorToast).toHaveBeenCalledWith(- "ORG$INVITATION_ACCEPT_ERROR",- );- });-- expect(mockOnClose).toHaveBeenCalledOnce();- });- });-});diff --git a/frontend/__tests__/components/features/org/invite-organization-member-modal.test.tsx b/frontend/__tests__/components/features/org/invite-organization-member-modal.test.tsxindex 42e470420d..19d490a8a6 100644--- a/frontend/__tests__/components/features/org/invite-organization-member-modal.test.tsx+++ b/frontend/__tests__/components/features/org/invite-organization-member-modal.test.tsx@@ -73,11 +73,40 @@ describe("InviteOrganizationMemberModal", () => {expect(inviteMembersBatchSpy).toHaveBeenCalledExactlyOnceWith({orgId: "1",emails: ["[email protected]"],+ role: "member",});expect(onCloseMock).toHaveBeenCalledOnce();});+ it("should invite with the admin role when selected in the role dropdown", async () => {+ const inviteMembersBatchSpy = vi.spyOn(+ organizationService,+ "inviteMembers",+ );+ const onCloseMock = vi.fn();++ renderInviteOrganizationMemberModal({ onClose: onCloseMock });++ const modal = screen.getByTestId("invite-modal");+ const badgeInput = within(modal).getByTestId("emails-badge-input");+ await userEvent.type(badgeInput, "[email protected] ");++ const roleDropdown = within(modal).getByTestId("invite-role-dropdown");+ await userEvent.click(within(roleDropdown).getByTestId("dropdown-trigger"));+ const listbox = await screen.findByRole("listbox");+ await userEvent.click(within(listbox).getByText("ORG$ROLE_ADMIN"));++ const submitButton = within(modal).getByRole("button", { name: /add/i });+ await userEvent.click(submitButton);++ expect(inviteMembersBatchSpy).toHaveBeenCalledExactlyOnceWith({+ orgId: "1",+ emails: ["[email protected]"],+ role: "admin",+ });+ });+it("should allow adding multiple emails using badge input and make a batch POST request", async () => {const inviteMembersBatchSpy = vi.spyOn(organizationService,@@ -116,6 +145,7 @@ describe("InviteOrganizationMemberModal", () => {expect(inviteMembersBatchSpy).toHaveBeenCalledExactlyOnceWith({orgId: "1",+ role: "member",});expect(onCloseMock).toHaveBeenCalledOnce();diff --git a/frontend/__tests__/hooks/use-auto-accept-invitation.test.tsx b/frontend/__tests__/hooks/use-auto-accept-invitation.test.tsxnew file mode 100644index 0000000000..19cd98750c--- /dev/null+++ b/frontend/__tests__/hooks/use-auto-accept-invitation.test.tsx@@ -0,0 +1,142 @@+import { renderHook, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { AxiosError, AxiosHeaders } from "axios";++// Import after mocking+import { organizationService } from "#/api/organization-service/organization-service.api";+import * as ToastHandlers from "#/utils/custom-toast-handlers";+import { useAutoAcceptInvitation } from "#/hooks/use-auto-accept-invitation";++const INVITATION_TOKEN_KEY = "openhands_invitation_token";++// Mock react-router (useInvitation reads search params)+vi.mock("react-router", () => ({+ useSearchParams: () => [+ {+ get: () => null,+ has: () => false,+ },+ vi.fn(),+ ],+}));++vi.mock("#/hooks/query/use-is-authed", () => ({+ useIsAuthed: () => ({ data: true }),+}));++vi.mock("#/hooks/use-is-on-intermediate-page", () => ({+ useIsOnIntermediatePage: () => false,+}));++const mockSwitchOrganization = vi.fn();+vi.mock("#/hooks/mutation/use-switch-organization", () => ({+ useSwitchOrganization: () => ({ mutate: mockSwitchOrganization }),+}));++const wrapper = ({ children }: { children: React.ReactNode }) => (+ <QueryClientProvider client={new QueryClient()}>+ {children}+ </QueryClientProvider>+);++const makeAxiosError = (status: number, detail: string) =>+ new AxiosError("Request failed", String(status), undefined, undefined, {+ status,+ statusText: "",+ headers: {},+ config: { headers: new AxiosHeaders() },+ data: { detail },+ });++describe("useAutoAcceptInvitation", () => {+ beforeEach(() => {+ localStorage.setItem(INVITATION_TOKEN_KEY, "inv-test-token");+ });++ afterEach(() => {+ vi.clearAllMocks();+ localStorage.clear();+ });++ it("should accept the stored invitation token and switch to the org", async () => {+ const acceptSpy = vi+ .spyOn(organizationService, "acceptInvitation")+ .mockResolvedValue({+ success: true,+ org_id: "org-1",+ org_name: "Acme",+ role: "member",+ });+ const successToastSpy = vi.spyOn(ToastHandlers, "displaySuccessToast");++ renderHook(() => useAutoAcceptInvitation(), { wrapper });++ await waitFor(() =>+ expect(acceptSpy).toHaveBeenCalledExactlyOnceWith({+ token: "inv-test-token",+ }),+ );+ await waitFor(() => expect(successToastSpy).toHaveBeenCalled());+ expect(mockSwitchOrganization).toHaveBeenCalledWith({+ orgId: "org-1",+ orgName: "Acme",+ isPersonal: false,+ });+ // Token is cleared after the attempt+ await waitFor(() =>+ expect(localStorage.getItem(INVITATION_TOKEN_KEY)).toBeNull(),+ );+ });++ it("should treat already_member as success, not an error", async () => {+ vi.spyOn(organizationService, "acceptInvitation").mockRejectedValue(+ makeAxiosError(409, "already_member"),+ );+ const successToastSpy = vi.spyOn(ToastHandlers, "displaySuccessToast");+ const errorToastSpy = vi.spyOn(ToastHandlers, "displayErrorToast");++ renderHook(() => useAutoAcceptInvitation(), { wrapper });++ await waitFor(() => expect(successToastSpy).toHaveBeenCalled());+ expect(errorToastSpy).not.toHaveBeenCalled();+ expect(mockSwitchOrganization).not.toHaveBeenCalled();+ await waitFor(() =>+ expect(localStorage.getItem(INVITATION_TOKEN_KEY)).toBeNull(),+ );+ });++ it("should show an error toast for an expired invitation", async () => {+ vi.spyOn(organizationService, "acceptInvitation").mockRejectedValue(+ makeAxiosError(400, "invitation_expired"),+ );+ const errorToastSpy = vi.spyOn(ToastHandlers, "displayErrorToast");++ renderHook(() => useAutoAcceptInvitation(), { wrapper });++ await waitFor(() => expect(errorToastSpy).toHaveBeenCalled());+ expect(mockSwitchOrganization).not.toHaveBeenCalled();+ await waitFor(() =>+ expect(localStorage.getItem(INVITATION_TOKEN_KEY)).toBeNull(),+ );+ });++ it("should only attempt acceptance once per token", async () => {+ const acceptSpy = vi+ .spyOn(organizationService, "acceptInvitation")+ .mockResolvedValue({+ success: true,+ org_id: "org-1",+ org_name: "Acme",+ role: "member",+ });++ const { rerender } = renderHook(() => useAutoAcceptInvitation(), {+ wrapper,+ });+ rerender();+ rerender();++ await waitFor(() => expect(acceptSpy).toHaveBeenCalledTimes(1));+ });+});diff --git a/frontend/__tests__/query-client-config.test.ts b/frontend/__tests__/query-client-config.test.tsnew file mode 100644index 0000000000..0c0e09467b--- /dev/null+++ b/frontend/__tests__/query-client-config.test.ts@@ -0,0 +1,54 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { AxiosError, AxiosHeaders } from "axios";+import { queryClient } from "#/query-client-config";++const make429 = () =>+ new AxiosError("Too Many Requests", "429", undefined, undefined, {+ status: 429,+ statusText: "Too Many Requests",+ headers: { "retry-after": "0" },+ config: { headers: new AxiosHeaders() },+ data: { detail: "rate_limited" },+ });++describe("queryClient mutation defaults", () => {+ afterEach(() => {+ vi.restoreAllMocks();+ queryClient.clear();+ });++ it("should retry a mutation rejected with 429 (request was never processed)", async () => {+ const mutationFn = vi+ .fn()+ .mockRejectedValueOnce(make429())+ .mockResolvedValueOnce("ok");++ const result = await queryClient+ .getMutationCache()+ .build(queryClient, { mutationFn, meta: { disableToast: true } })+ .execute(undefined);++ expect(result).toBe("ok");+ expect(mutationFn).toHaveBeenCalledTimes(2);+ });++ it("should not retry a mutation rejected with a non-429 error", async () => {+ const error = new AxiosError("Server Error", "500", undefined, undefined, {+ status: 500,+ statusText: "",+ headers: {},+ config: { headers: new AxiosHeaders() },+ data: {},+ });+ const mutationFn = vi.fn().mockRejectedValue(error);++ await expect(+ queryClient+ .getMutationCache()+ .build(queryClient, { mutationFn, meta: { disableToast: true } })+ .execute(undefined),+ ).rejects.toBe(error);++ expect(mutationFn).toHaveBeenCalledTimes(1);+ });+});diff --git a/frontend/src/api/organization-service/organization-service.api.ts b/frontend/src/api/organization-service/organization-service.api.tsindex fe92233a4c..cdb4625a04 100644--- a/frontend/src/api/organization-service/organization-service.api.ts+++ b/frontend/src/api/organization-service/organization-service.api.ts@@ -3,6 +3,7 @@ import {Organization,OrganizationMember,OrganizationMembersPage,+ OrganizationUserRole,UpdateOrganizationMemberParams,} from "#/types/org";import { Settings } from "#/types/settings";@@ -139,14 +140,17 @@ export const organizationService = {inviteMembers: async ({orgId,emails,+ role = "member",}: {orgId: string;emails: string[];+ role?: OrganizationUserRole;}) => {const { data } = await openHands.post<OrganizationMember[]>(`/api/organizations/${orgId}/members/invite`,{emails,+ role,},);diff --git a/frontend/src/components/features/invitations/invitation-accept-modal.tsx b/frontend/src/components/features/invitations/invitation-accept-modal.tsxdeleted file mode 100644index d0e17dad06..0000000000--- a/frontend/src/components/features/invitations/invitation-accept-modal.tsx+++ /dev/null@@ -1,118 +0,0 @@-import { AxiosError } from "axios";-import { useTranslation } from "react-i18next";-import { I18nKey } from "#/i18n/declaration";-import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";-import { BrandButton } from "#/components/features/settings/brand-button";-import { LoadingSpinner } from "#/components/shared/loading-spinner";-import {- useAcceptInvitation,- getInvitationErrorCode,-} from "#/hooks/mutation/use-accept-invitation";-import {- displayErrorToast,- displaySuccessToast,-} from "#/utils/custom-toast-handlers";--interface InvitationAcceptModalProps {- token: string;- onClose: () => void;- onSuccess: (payload: {- orgId: string;- orgName: string;- isPersonal: boolean;- }) => void;-}--export function InvitationAcceptModal({- token,- onClose,- onSuccess,-}: InvitationAcceptModalProps) {- const { t } = useTranslation();- const { mutate: acceptInvitation, isPending } = useAcceptInvitation();-- const getErrorMessage = (errorCode: string | null): string => {- switch (errorCode) {- case "invitation_expired":- return t(I18nKey.ORG$INVITATION_EXPIRED);- case "invitation_invalid":- return t(I18nKey.ORG$INVITATION_INVALID);- case "already_member":- return t(I18nKey.ORG$ALREADY_MEMBER);- case "email_mismatch":- return t(I18nKey.ORG$INVITATION_EMAIL_MISMATCH);- default:- return t(I18nKey.ORG$INVITATION_ACCEPT_ERROR);- }- };-- const handleAccept = () => {- acceptInvitation(- { token },- {- onSuccess: (data) => {- displaySuccessToast(- t(I18nKey.ORG$INVITATION_ACCEPTED_SUCCESS, {- orgName: data.org_name,- }),- );- onSuccess({- orgId: data.org_id,- orgName: data.org_name,- isPersonal: false,- });- },- onError: (error) => {- const errorCode = getInvitationErrorCode(- error as AxiosError<{ detail: string }>,- );- displayErrorToast(getErrorMessage(errorCode));- onClose();- },- },- );- };-- return (- <ModalBackdrop onClose={onClose} aria-label="Accept invitation">- <div- data-testid="invitation-accept-modal"- className="bg-base-secondary p-6 rounded-xl flex flex-col gap-4 border border-tertiary"- style={{ width: "500px" }}- >- <h3 className="text-xl font-bold">- {t(I18nKey.ORG$INVITATION_ACCEPT_TITLE)}- </h3>- <p className="text-sm text-gray-300">- {t(I18nKey.ORG$INVITATION_ACCEPT_DESCRIPTION)}- </p>- <div className="w-full flex gap-2 mt-2">- <BrandButton- testId="accept-invitation-button"- type="button"- variant="primary"- className="grow flex items-center justify-center"- onClick={handleAccept}- isDisabled={isPending}- >- {isPending ? (- <LoadingSpinner size="small" />- ) : (- t(I18nKey.BUTTON$CONFIRM)- )}- </BrandButton>- <BrandButton- testId="cancel-invitation-button"- type="button"- variant="secondary"- className="grow"- onClick={onClose}- isDisabled={isPending}- >- {t(I18nKey.BUTTON$CANCEL)}- </BrandButton>- </div>- </div>- </ModalBackdrop>- );-}diff --git a/frontend/src/components/features/org/invite-organization-member-modal.tsx b/frontend/src/components/features/org/invite-organization-member-modal.tsxindex 37ce1338cc..3f982d7334 100644--- a/frontend/src/components/features/org/invite-organization-member-modal.tsx+++ b/frontend/src/components/features/org/invite-organization-member-modal.tsx@@ -6,6 +6,8 @@ import { BadgeInput } from "#/components/shared/inputs/badge-input";import { I18nKey } from "#/i18n/declaration";import { displayErrorToast } from "#/utils/custom-toast-handlers";import { areAllEmailsValid, hasDuplicates } from "#/utils/input-validation";+import { Dropdown } from "#/ui/dropdown/dropdown";+import { OrganizationUserRole } from "#/types/org";interface InviteOrganizationMemberModalProps {onClose: (event?: React.MouseEvent<HTMLButtonElement>) => void;@@ -17,6 +19,7 @@ export function InviteOrganizationMemberModal({const { t } = useTranslation();const { mutate: inviteMembers, isPending } = useInviteMembersBatch();const [emails, setEmails] = React.useState<string[]>([]);+ const [role, setRole] = React.useState<OrganizationUserRole>("member");const handleEmailsChange = (newEmails: string[]) => {const trimmedEmails = newEmails.map((email) => email.trim());@@ -40,13 +43,18 @@ export function InviteOrganizationMemberModal({}inviteMembers(- { emails },+ { emails, role },{onSuccess: () => onClose(),},);};+ const roleOptions = [+ { value: "member", label: t(I18nKey.ORG$ROLE_MEMBER) },+ { value: "admin", label: t(I18nKey.ORG$ROLE_ADMIN) },+ ];+return (<OrgModaltestId="invite-modal"@@ -63,6 +71,17 @@ export function InviteOrganizationMemberModal({placeholder={t(I18nKey.COMMON$TYPE_EMAIL_AND_PRESS_SPACE)}onChange={handleEmailsChange}/>+ <label className="flex flex-col gap-1 text-sm capitalize">+ {t(I18nKey.ORG$INVITE_ROLE_LABEL)}+ <Dropdown+ testId="invite-role-dropdown"+ options={roleOptions}+ defaultValue={roleOptions[0]}+ onChange={(option) =>+ setRole((option?.value as OrganizationUserRole) ?? "member")+ }+ />+ </label></OrgModal>);}diff --git a/frontend/src/hooks/mutation/use-invite-members-batch.ts b/frontend/src/hooks/mutation/use-invite-members-batch.tsindex d82287da2c..7a3af31ed4 100644--- a/frontend/src/hooks/mutation/use-invite-members-batch.ts+++ b/frontend/src/hooks/mutation/use-invite-members-batch.ts@@ -8,6 +8,7 @@ import {displaySuccessToast,} from "#/utils/custom-toast-handlers";import { retrieveAxiosErrorMessage } from "#/utils/retrieve-axios-error-message";+import { OrganizationUserRole } from "#/types/org";export const useInviteMembersBatch = () => {const queryClient = useQueryClient();@@ -15,13 +16,20 @@ export const useInviteMembersBatch = () => {const { t } = useTranslation();return useMutation({- mutationFn: ({ emails }: { emails: string[] }) => {+ mutationFn: ({+ emails,+ role,+ }: {+ emails: string[];+ role?: OrganizationUserRole;+ }) => {if (!organizationId) {throw new Error("Organization ID is required");}return organizationService.inviteMembers({orgId: organizationId,emails,+ role,});},onSuccess: () => {diff --git a/frontend/src/hooks/use-auto-accept-invitation.ts b/frontend/src/hooks/use-auto-accept-invitation.tsnew file mode 100644index 0000000000..1b2ddb49d4--- /dev/null+++ b/frontend/src/hooks/use-auto-accept-invitation.ts@@ -0,0 +1,94 @@+import React from "react";+import { AxiosError } from "axios";+import { useTranslation } from "react-i18next";+import { I18nKey } from "#/i18n/declaration";+import { useIsAuthed } from "#/hooks/query/use-is-authed";+import { useIsOnIntermediatePage } from "#/hooks/use-is-on-intermediate-page";+import { useInvitation } from "#/hooks/use-invitation";+import {+ useAcceptInvitation,+ getInvitationErrorCode,+} from "#/hooks/mutation/use-accept-invitation";+import { useSwitchOrganization } from "#/hooks/mutation/use-switch-organization";+import {+ displayErrorToast,+ displaySuccessToast,+} from "#/utils/custom-toast-handlers";++/**+ * Accept a pending invitation token automatically once the user is+ * authenticated.+ *+ * Clicking the invitation link is the user's consent — an extra+ * confirm/cancel dialog added no security (the token is bound to the+ * invited email) and its cancel didn't actually decline anything, so the+ * token is simply submitted as soon as a session exists and the outcome is+ * reported via a toast.+ */+export function useAutoAcceptInvitation() {+ const { t } = useTranslation();+ const { data: isAuthed } = useIsAuthed();+ const isOnIntermediatePage = useIsOnIntermediatePage();+ const { invitationToken, clearInvitation } = useInvitation();+ const { mutate: acceptInvitation } = useAcceptInvitation();+ const { mutate: switchOrganization } = useSwitchOrganization();+ const attemptedTokenRef = React.useRef<string | null>(null);++ React.useEffect(() => {+ if (!isAuthed || !invitationToken || isOnIntermediatePage) return;+ if (attemptedTokenRef.current === invitationToken) return;+ attemptedTokenRef.current = invitationToken;++ acceptInvitation(+ { token: invitationToken },+ {+ onSuccess: (data) => {+ displaySuccessToast(+ t(I18nKey.ORG$INVITATION_ACCEPTED_SUCCESS, {+ orgName: data.org_name,+ }),+ );+ switchOrganization({+ orgId: data.org_id,+ orgName: data.org_name,+ isPersonal: false,+ });+ },+ onError: (error) => {+ const errorCode = getInvitationErrorCode(+ error as AxiosError<{ detail: string }>,+ );+ switch (errorCode) {+ case "already_member":+ // The invitation was already applied (e.g. accepted on the+ // user's behalf at sign-in) — success from their perspective.+ displaySuccessToast(t(I18nKey.ORG$ALREADY_MEMBER));+ break;+ case "invitation_expired":+ displayErrorToast(t(I18nKey.ORG$INVITATION_EXPIRED));+ break;+ case "email_mismatch":+ displayErrorToast(t(I18nKey.ORG$INVITATION_EMAIL_MISMATCH));+ break;+ case "invitation_invalid":+ displayErrorToast(t(I18nKey.ORG$INVITATION_INVALID));+ break;+ default:+ displayErrorToast(t(I18nKey.ORG$INVITATION_ACCEPT_ERROR));+ }+ },+ onSettled: () => {+ clearInvitation();+ },+ },+ );+ }, [+ isAuthed,+ invitationToken,+ isOnIntermediatePage,+ acceptInvitation,+ switchOrganization,+ clearInvitation,+ t,+ ]);+}diff --git a/frontend/src/i18n/declaration.ts b/frontend/src/i18n/declaration.tsindex c338d42c38..be241fb797 100644--- a/frontend/src/i18n/declaration.ts+++ b/frontend/src/i18n/declaration.ts@@ -1568,4 +1568,5 @@ export enum I18nKey {SETTINGS$ACP_SECRET_GCP_PROJECT_HINT = "SETTINGS$ACP_SECRET_GCP_PROJECT_HINT",SETTINGS$ACP_SECRET_GCP_LOCATION_HINT = "SETTINGS$ACP_SECRET_GCP_LOCATION_HINT",SETTINGS$ACP_SECRET_VERTEXAI_FLAG_HINT = "SETTINGS$ACP_SECRET_VERTEXAI_FLAG_HINT",+ ORG$INVITE_ROLE_LABEL = "ORG$INVITE_ROLE_LABEL",}diff --git a/frontend/src/i18n/translation.json b/frontend/src/i18n/translation.jsonindex 3798c5a0e3..9dc2ffd35c 100644--- a/frontend/src/i18n/translation.json+++ b/frontend/src/i18n/translation.json@@ -26654,5 +26654,22 @@"ca": "Posa'l a true per encaminar Gemini a través de Vertex AI amb les credencials anteriors.","tr": "Yukarıdaki kimlik bilgilerini kullanarak Gemini'yi Vertex AI üzerinden yönlendirmek için true yapın.","uk": "Встановіть true, щоб спрямовувати Gemini через Vertex AI з наведеними вище обліковими даними."+ },+ "ORG$INVITE_ROLE_LABEL": {+ "ar": "دعوة بصفة",+ "ca": "Convida com a",+ "de": "Einladen als",+ "en": "Invite as",+ "es": "Invitar como",+ "fr": "Inviter en tant que",+ "it": "Invita come",+ "ja": "招待時のロール",+ "ko-KR": "초대 역할",+ "no": "Inviter som",+ "pt": "Convidar como",+ "tr": "Şu rolle davet et",+ "uk": "Запросити як",+ "zh-CN": "邀请身份",+ "zh-TW": "邀請身分"}}diff --git a/frontend/src/query-client-config.ts b/frontend/src/query-client-config.tsindex 8b30c10de0..bd3cd51a1c 100644--- a/frontend/src/query-client-config.ts+++ b/frontend/src/query-client-config.ts@@ -4,6 +4,10 @@ import { AxiosError } from "axios";import { I18nKey } from "./i18n/declaration";import { retrieveAxiosErrorMessage } from "./utils/retrieve-axios-error-message";import { displayErrorToast } from "./utils/custom-toast-handlers";+import {+ isRateLimitError,+ getRateLimitRetryDelayMs,+} from "./utils/rate-limit-retry";const handle401Error = (error: AxiosError, queryClient: QueryClient) => {if (error?.response?.status === 401 || error?.status === 401) {@@ -13,6 +17,17 @@ const handle401Error = (error: AxiosError, queryClient: QueryClient) => {const shownErrors = new Set<string>();export const queryClient = new QueryClient({+ defaultOptions: {+ mutations: {+ // A 429 means the request was rejected before being processed, so a+ // retry can't double-apply the mutation. Bursts (e.g. the post-login+ // query storm) can momentarily trip the per-user API rate limit and+ // would otherwise surface as a spurious error toast.+ retry: (failureCount, error) =>+ failureCount < 2 && isRateLimitError(error),+ retryDelay: (_, error) => getRateLimitRetryDelayMs(error),+ },+ },queryCache: new QueryCache({onError: (error, query) => {const isAuthQuery =diff --git a/frontend/src/routes/root-layout.tsx b/frontend/src/routes/root-layout.tsxindex 00f47a3aa4..dc365ffb70 100644--- a/frontend/src/routes/root-layout.tsx+++ b/frontend/src/routes/root-layout.tsx@@ -31,9 +31,7 @@ import { AlertBanner } from "#/components/features/alerts/alert-banner";import { cn } from "#/utils/utils";import { LoadingSpinner } from "#/components/shared/loading-spinner";import { useAppTitle } from "#/hooks/use-app-title";-import { useInvitation } from "#/hooks/use-invitation";-import { InvitationAcceptModal } from "#/components/features/invitations/invitation-accept-modal";-import { useSwitchOrganization } from "#/hooks/mutation/use-switch-organization";+import { useAutoAcceptInvitation } from "#/hooks/use-auto-accept-invitation";export function ErrorBoundary() {const error = useRouteError();@@ -88,10 +86,8 @@ export default function MainApp() {const [consentFormIsOpen, setConsentFormIsOpen] = React.useState(false);- // Invitation acceptance modal state- const { invitationToken, clearInvitation } = useInvitation();- const { mutate: switchOrganization } = useSwitchOrganization();- const [showInvitationModal, setShowInvitationModal] = React.useState(false);+ // Accept a pending invitation token once authenticated+ useAutoAcceptInvitation();// Auto-login if login method is stored in local storageuseAutoLogin();@@ -143,28 +139,6 @@ export default function MainApp() {}}, [settings?.is_new_user, config.data?.app_mode]);- // Show invitation modal when authenticated and has invitation token- React.useEffect(() => {- if (isAuthed && invitationToken && !isOnIntermediatePage) {- setShowInvitationModal(true);- }- }, [isAuthed, invitationToken, isOnIntermediatePage]);-- const handleInvitationClose = React.useCallback(() => {- setShowInvitationModal(false);- clearInvitation();- }, [clearInvitation]);-- const handleInvitationSuccess = React.useCallback(- (payload: { orgId: string; orgName: string; isPersonal: boolean }) => {- setShowInvitationModal(false);- clearInvitation();- // Switch to the newly joined organization- switchOrganization(payload);- },- [clearInvitation, switchOrganization],- );-// Function to check if login method exists in local storageconst checkLoginMethodExists = React.useCallback(() => {// Only check localStorage if we're in a browser environment@@ -295,13 +269,6 @@ export default function MainApp() {}}/>)}- {showInvitationModal && invitationToken && (- <InvitationAcceptModal- token={invitationToken}- onClose={handleInvitationClose}- onSuccess={handleInvitationSuccess}- />- )}</div>);}