🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(ai-gateway): pick team recipients with member pills instead of a notify-all toggle (#19393)
Tobias Wochinger7526ede92399
diff --git a/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts b/web/src/__tests__/server/ai-gateway-control-plane.servertest.tsindex ee0916fce8..ff9e6c6d18 100644--- a/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts+++ b/web/src/__tests__/server/ai-gateway-control-plane.servertest.ts@@ -522,6 +522,77 @@ describe("AI gateway control plane", () => {).resolves.toEqual({ orgRole: Role.MEMBER });});+ it("tells which invitee addresses already belong to the organization and get notified", async () => {+ const owner = await prepare();+ await createCallerForOrganizationRole(owner, Role.MEMBER);+ await createCallerForOrganizationRole(owner, Role.VIEWER);+ const emailOf = async (role: Role) => {+ const membership = await prisma.organizationMembership.findFirstOrThrow({+ where: { orgId: owner.org.id, role },+ select: { user: { select: { email: true } } },+ });+ return membership.user.email!.toLowerCase();+ };+ const memberEmail = await emailOf(Role.MEMBER);+ const viewerEmail = await emailOf(Role.VIEWER);+ const ownerEmail = owner.user.email!.toLowerCase();+ const outsiderEmail = `gateway-outsider-${randomUUID()}@example.test`;++ const result = await owner.caller.aiGateway.getInviteeMembers({+ orgId: owner.org.id,+ emails: [+ memberEmail,+ viewerEmail.toUpperCase(),+ ownerEmail,+ outsiderEmail,+ ],+ });++ expect(result).toEqual([+ {+ email: memberEmail,+ member: { name: "Gateway member", isSelf: false, canUseGateway: true },+ },+ {+ email: viewerEmail,+ member: { name: "Gateway viewer", isSelf: false, canUseGateway: false },+ },+ {+ email: ownerEmail,+ member: { name: "Gateway tester", isSelf: true, canUseGateway: true },+ },+ { email: outsiderEmail, member: null },+ ]);+ });++ it("suggests other gateway members, skipping picked ones and narrowing by search", async () => {+ const owner = await prepare();+ for (let i = 0; i < 5; i++) {+ await createCallerForOrganizationRole(owner, Role.MEMBER);+ }+ await createCallerForOrganizationRole(owner, Role.VIEWER);+ const members = await prisma.organizationMembership.findMany({+ where: { orgId: owner.org.id, role: Role.MEMBER },+ orderBy: [{ createdAt: "asc" }, { userId: "asc" }],+ select: { user: { select: { email: true } } },+ });+ const memberEmails = members.map(({ user }) => user.email!);+ const suggest = (search: string, excludeEmails: string[] = []) =>+ owner.caller.aiGateway+ .getMemberSuggestions({ orgId: owner.org.id, search, excludeEmails })+ .then((suggestions) => suggestions.map(({ email }) => email));++ await expect(suggest("")).resolves.toEqual(memberEmails.slice(0, 4));+ await expect(+ suggest("", [memberEmails[0]!.toUpperCase()]),+ ).resolves.toEqual(memberEmails.slice(1, 5));+ await expect(suggest(memberEmails[4]!.toUpperCase())).resolves.toEqual([+ memberEmails[4],+ ]);+ await expect(suggest("GATEWAY MEMBER")).resolves.toHaveLength(4);+ await expect(suggest("gateway_role")).resolves.toEqual([]);+ });+it.each([false, true])("announces the gateway once to a typed address of a member (notifyMembers: %s)",async (notifyMembers) => {diff --git a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/GatewayApiKeysTable/GatewayApiKeysTable.tsx b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/GatewayApiKeysTable/GatewayApiKeysTable.tsxindex 4983e912cd..ee1d581a3c 100644--- a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/GatewayApiKeysTable/GatewayApiKeysTable.tsx+++ b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/GatewayApiKeysTable/GatewayApiKeysTable.tsx@@ -119,7 +119,7 @@ export function GatewayApiKeysTable({? [{id: "invite",- label: "Invite",+ label: "Notify team",variant: "outline" as const,icon: <UserPlus size="base" aria-hidden="true" />,onClick: inviteAction,diff --git a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/TeamInviteDialogController/TeamInviteDialogController.tsx b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/TeamInviteDialogController/TeamInviteDialogController.tsxindex b223286844..58c90c40b6 100644--- a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/TeamInviteDialogController/TeamInviteDialogController.tsx+++ b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/TeamInviteDialogController/TeamInviteDialogController.tsx@@ -24,25 +24,26 @@ export function TeamInviteDialogController({reportTrpcErrorWithoutToast(error, "ai-gateway-team-invite"),});- async function handleInvite(emails: string[]) {+ async function handleInvite(params: {+ emails: string[];+ notifyMembers: boolean;+ }) {try {const result = await invite.mutateAsync({orgId: organizationId,- emails,- notifyMembers: false,+ ...params,});capture("ai_gateway:team_invite_sent",toTeamInviteSentEvent({orgId: organizationId,surface: "api_keys_page",- emails,- notifyMembers: false,+ ...params,result,}),);if (result.failed.length === 0) showInviteOutcome(result);- return result.failed;+ return result;} catch (error) {reportNonTrpcError(error, "ai-gateway-team-invite");return null;@@ -54,6 +55,7 @@ export function TeamInviteDialogController({onBeforeClose={() => !invite.isPending}renderDialog={({ closeDialog }) => (<TeamInviteDialog+ organizationId={organizationId}isInviting={invite.isPending}errorMessage={invite.error?.message}onInvite={handleInvite}diff --git a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/TeamInviteDialogController/components/TeamInviteDialog.tsx b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/TeamInviteDialogController/components/TeamInviteDialog.tsxindex 5db7ad05f1..177972cd57 100644--- a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/TeamInviteDialogController/components/TeamInviteDialog.tsx+++ b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/TeamInviteDialogController/components/TeamInviteDialog.tsx@@ -1,69 +1,70 @@import { Alert } from "@/src/components/design-system/Alert/Alert";+import { Button } from "@/src/components/design-system/Button/Button";import { Dialog } from "@/src/components/design-system/Dialog/Dialog";import { TeamInviteFailuresAlert } from "@/src/features/ai-gateway/components/TeamInviteFailuresAlert";import { TeamInviteFields } from "@/src/features/ai-gateway/components/TeamInviteFields/TeamInviteFields";-import { useTeamInviteEmails } from "@/src/features/ai-gateway/hooks/useTeamInviteEmails";-import type { TeamInviteFailure } from "@/src/features/ai-gateway/types/teamInviteFailure";+import { TEAM_NOTIFY_COPY } from "@/src/features/ai-gateway/constants/gatewayTeamInvites";+import { useTeamNotifyForm } from "@/src/features/ai-gateway/hooks/useTeamNotifyForm";+import { useTeamRecipients } from "@/src/features/ai-gateway/hooks/useTeamRecipients";+import type { RouterOutputs } from "@/src/utils/api";export type TeamInviteDialogProps = {+ organizationId: string;isInviting: boolean;errorMessage: string | undefined;- /** Resolves to the addresses that were not invited, or null when the request failed. */- onInvite: (emails: string[]) => Promise<TeamInviteFailure[] | null>;+ /** Resolves to null when the request failed. */+ onInvite: (params: {+ emails: string[];+ notifyMembers: boolean;+ }) => Promise<RouterOutputs["aiGateway"]["inviteTeam"] | null>;/** Called once no address failed. */onInvited: () => void;};export function TeamInviteDialog({+ organizationId,isInviting,errorMessage,onInvite,onInvited,}: TeamInviteDialogProps) {- const invitees = useTeamInviteEmails();+ const form = useTeamNotifyForm(useTeamRecipients(organizationId));async function handleSend() {- invitees.startAttempt();- const failed = await onInvite(invitees.emails);- if (!failed) return;- if (failed.length === 0) {- onInvited();- return;- }- invitees.keepFailed(failed);+ if (await form.send(onInvite)) onInvited();}return (<Dialog- title="Invite people"+ title={TEAM_NOTIFY_COPY.title}actions={[{- label: "Send invites",+ label: form.sendLabel,loading: isInviting,- disabled:- isInviting || invitees.emails.length === 0 || !invitees.isValid,+ disabled: isInviting || !form.canSend,onClick: handleSend,},]}><Dialog.Body><p className="text-muted-foreground">- Invite people to the organization. They can create their own gateway- keys.+ {TEAM_NOTIFY_COPY.description}{" "}+ <Button+ variant="text"+ size="sm"+ text="About roles"+ href={TEAM_NOTIFY_COPY.rolesDocsUrl}+ /></p>- <TeamInviteFields- emails={invitees.emails}- onEmailsChange={invitees.setEmails}- errorMessage={invitees.errorMessage}- />+ <TeamInviteFields {...form.fieldsProps} />{errorMessage ? (<Alert variant="destructive">- <Alert.Title>Invitations could not be sent</Alert.Title>+ <Alert.Title>Notifications could not be sent</Alert.Title><Alert.Description>{errorMessage}</Alert.Description></Alert>) : null}- {invitees.failures.length > 0 ? (- <TeamInviteFailuresAlert failures={invitees.failures} />+ {form.failures.length > 0 ? (+ <TeamInviteFailuresAlert failures={form.failures} />) : null}</Dialog.Body></Dialog>diff --git a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/TeamInviteDialogController/fns/showInviteOutcome.ts b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/TeamInviteDialogController/fns/showInviteOutcome.tsindex 3915b622cd..6d087d308d 100644--- a/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/TeamInviteDialogController/fns/showInviteOutcome.ts+++ b/web/src/features/ai-gateway/components/GatewayApiKeysPage/components/TeamInviteDialogController/fns/showInviteOutcome.ts@@ -10,13 +10,16 @@ export function showInviteOutcome({showToast({type: "INFO",analytics: { operation: "aiGateway.inviteTeam" },- title: "No invitations sent: everyone you entered is already a member.",+ title: "Nobody was notified: the addresses you entered get no email.",});return;}showSuccessToast({operation: "aiGateway.inviteTeam",- title: "Invitations sent",- description: "Invited people can create gateway keys once they join.",+ title: "Team notified",+ description:+ invitedCount > 0+ ? "New people can create gateway keys once they join the organization."+ : "Members can now create their own gateway keys.",});}diff --git a/web/src/features/ai-gateway/components/GatewaySetupPage/components/ConnectedGatewaySetupGuide.tsx b/web/src/features/ai-gateway/components/GatewaySetupPage/components/ConnectedGatewaySetupGuide.tsxindex 298af9436e..5779cfe4e3 100644--- a/web/src/features/ai-gateway/components/GatewaySetupPage/components/ConnectedGatewaySetupGuide.tsx+++ b/web/src/features/ai-gateway/components/GatewaySetupPage/components/ConnectedGatewaySetupGuide.tsx@@ -34,7 +34,7 @@ export function ConnectedGatewaySetupGuide({organizationId,"setup_guide",);- const { notifiableMembers, inviteTeam, isInviting } =+ const { recipients, inviteTeam, isInviting } =useGatewayTeamInvite(organizationId);// Funnel entry for the setup steps; the ref keeps it to one event per visit.@@ -82,7 +82,7 @@ export function ConnectedGatewaySetupGuide({return isSaved;}}onAddCredential={openAddDialog}- notifiableMembers={notifiableMembers}+ recipients={recipients}isInviting={isInviting}onInvite={inviteTeam}onFinish={({ isSkipped }) => {diff --git a/web/src/features/ai-gateway/components/GatewaySetupPage/components/GatewaySetupGuide/GatewaySetupGuide.stories.tsx b/web/src/features/ai-gateway/components/GatewaySetupPage/components/GatewaySetupGuide/GatewaySetupGuide.stories.tsxindex 22f999902e..e50f1b3c65 100644--- a/web/src/features/ai-gateway/components/GatewaySetupPage/components/GatewaySetupGuide/GatewaySetupGuide.stories.tsx+++ b/web/src/features/ai-gateway/components/GatewaySetupPage/components/GatewaySetupGuide/GatewaySetupGuide.stories.tsx@@ -1,9 +1,65 @@-import { expect, fn, userEvent, within } from "storybook/test";+import { fn } from "storybook/test";import preview from "@/.storybook/preview";-import { GatewaySetupGuide } from "./GatewaySetupGuide";+import { useTeamInviteEmails } from "@/src/features/ai-gateway/hooks/useTeamInviteEmails";+import type { TeamInviteMember } from "@/src/features/ai-gateway/types/teamInviteMembers";+import {+ GatewaySetupGuide,+ type GatewaySetupGuideProps,+} from "./GatewaySetupGuide";-const meta = preview.meta({ component: GatewaySetupGuide });+const organizationMembers = [+ { id: "user-1", name: "Ada Lovelace", email: "[email protected]", image: null },+ {+ id: "user-2",+ name: "Grace Hopper",+ email: "[email protected]",+ image: null,+ },+ { id: "user-3", name: null, email: "[email protected]", image: null },+ {+ id: "user-4",+ name: "Edsger Dijkstra",+ email: "[email protected]",+ image: null,+ },+];++/**+ * Holds the invitee list like the connected page does. `organizationMembers`+ * are the organization; every other address counts as someone to invite.+ */+function GatewaySetupGuideWithInvitees({+ notifiableMembers,+ ...props+}: Omit<GatewaySetupGuideProps, "recipients"> & {+ notifiableMembers: GatewaySetupGuideProps["recipients"]["notifiableMembers"];+}) {+ const invitees = useTeamInviteEmails();+ const membersByEmail = new Map(+ organizationMembers.map((member) => [+ member.email,+ { name: member.name, isSelf: false, canUseGateway: true },+ ]),+ );+ const inviteeMembers = new Map<string, TeamInviteMember | null>(+ invitees.emails.map((email) => [email, membersByEmail.get(email) ?? null]),+ );++ return (+ <GatewaySetupGuide+ {...props}+ recipients={{+ notifiableMembers,+ suggestedMembers: organizationMembers,+ invitees,+ inviteeMembers,+ }}+ />+ );+}++const meta = preview.meta({ component: GatewaySetupGuideWithInvitees });const projects = [{ id: "project-production", name: "Production" },@@ -26,27 +82,6 @@ const savedConfig = {const notifiableMembers = {isEmailConfigured: true,count: 12,- preview: [- {- id: "user-1",- name: "Ada Lovelace",- email: "[email protected]",- image: null,- },- {- id: "user-2",- name: "Grace Hopper",- email: "[email protected]",- image: null,- },- { id: "user-3", name: null, email: "[email protected]", image: null },- {- id: "user-4",- name: "Edsger Dijkstra",- email: "[email protected]",- image: null,- },- ],};export const ChoosingIngestion = meta.story({@@ -87,35 +122,3 @@ export const InvitingTeamWithoutEmail = meta.story({notifiableMembers: { ...notifiableMembers, isEmailConfigured: false },},});--export const TestRetryDoesNotNotifyAgain = meta.story({- name: "(Test) Retrying failed invites does not notify members again",- args: {- ...InvitingTeam.input.args,- onInvite: fn(async () => ({- invitedCount: 0,- existingMemberCount: 1,- failed: [{ email: "[email protected]", message: "Already a member" }],- notifiedCount: 12,- })),- },- play: async ({ args, canvasElement }) => {- const canvas = within(canvasElement);- await userEvent.type(- canvas.getByRole("textbox", { name: "Email addresses" }),- "[email protected] ",- );- await userEvent.click(- canvas.getByRole("button", { name: "Send 1 invite" }),- );-- await expect(args.onInvite).toHaveBeenCalledWith({- emails: ["[email protected]"],- notifyMembers: true,- });- await expect(- await canvas.findByText("Some invitations were not sent"),- ).toBeVisible();- await expect(canvas.queryByRole("switch")).not.toBeInTheDocument();- },-});diff --git a/web/src/features/ai-gateway/components/GatewaySetupPage/components/GatewaySetupGuide/components/TeamInviteStep/TeamInviteStep.tsx b/web/src/features/ai-gateway/components/GatewaySetupPage/components/GatewaySetupGuide/components/TeamInviteStep/TeamInviteStep.tsxindex 50eae545ef..ac86817818 100644--- a/web/src/features/ai-gateway/components/GatewaySetupPage/components/GatewaySetupGuide/components/TeamInviteStep/TeamInviteStep.tsx+++ b/web/src/features/ai-gateway/components/GatewaySetupPage/components/GatewaySetupGuide/components/TeamInviteStep/TeamInviteStep.tsx@@ -1,10 +1,10 @@import { Button } from "@/src/components/design-system/Button/Button";import { Stepper } from "@/src/components/design-system/Stepper/Stepper";-import { GATEWAY_SETUP } from "@/src/features/ai-gateway/components/GatewaySetupPage/constants/gatewaySetup";import {TeamInviteForm,type TeamInviteFormProps,} from "@/src/features/ai-gateway/components/GatewaySetupPage/components/GatewaySetupGuide/components/TeamInviteStep/components/TeamInviteForm/TeamInviteForm";+import { TEAM_NOTIFY_COPY } from "@/src/features/ai-gateway/constants/gatewayTeamInvites";import type { getSetupStepStatus } from "@/src/features/ai-gateway/components/GatewaySetupPage/components/GatewaySetupGuide/fns/getSetupStepStatus";export type TeamInviteStepProps = TeamInviteFormProps & {@@ -15,22 +15,21 @@ export function TeamInviteStep({ status, ...formProps }: TeamInviteStepProps) {return (<Steppernumber={3}- title="Invite your team"+ title={TEAM_NOTIFY_COPY.title}size="sm"status={status}isCollapsible={false}description={<>- Members can create their own gateway keys and use the models you- enabled. New people join as Member.+ {TEAM_NOTIFY_COPY.description}{status === "current" ? (<>{" "}<Buttonvariant="text"size="sm"- text="How gateway keys work"- href={GATEWAY_SETUP.docsUrl}+ text="About roles"+ href={TEAM_NOTIFY_COPY.rolesDocsUrl}/></>) : null}diff --git a/web/src/features/ai-gateway/components/GatewaySetupPage/components/GatewaySetupGuide/components/TeamInviteStep/components/TeamInviteForm/TeamInviteForm.tsx b/web/src/features/ai-gateway/components/GatewaySetupPage/components/GatewaySetupGuide/components/TeamInviteStep/components/TeamInviteForm/TeamInviteForm.tsxindex 811a88beea..7f86c735f8 100644--- a/web/src/features/ai-gateway/components/GatewaySetupPage/components/GatewaySetupGuide/components/TeamInviteStep/components/TeamInviteForm/TeamInviteForm.tsx+++ b/web/src/features/ai-gateway/components/GatewaySetupPage/components/GatewaySetupGuide/components/TeamInviteStep/components/TeamInviteForm/TeamInviteForm.tsx@@ -1,17 +1,12 @@-import { useState } from "react";-import { Button } from "@/src/components/design-system/Button/Button";import { TeamInviteFailuresAlert } from "@/src/features/ai-gateway/components/TeamInviteFailuresAlert";import { TeamInviteFields } from "@/src/features/ai-gateway/components/TeamInviteFields/TeamInviteFields";-import type {- GatewayNotifiableMembers,- GatewayTeamInviteResult,-} from "@/src/features/ai-gateway/components/GatewaySetupPage/types/gatewaySetup";-import { useTeamInviteEmails } from "@/src/features/ai-gateway/hooks/useTeamInviteEmails";+import type { GatewayTeamInviteResult } from "@/src/features/ai-gateway/components/GatewaySetupPage/types/gatewaySetup";+import { useTeamNotifyForm } from "@/src/features/ai-gateway/hooks/useTeamNotifyForm";+import type { useTeamRecipients } from "@/src/features/ai-gateway/hooks/useTeamRecipients";export type TeamInviteFormProps = {- /** Undefined while loading. */- notifiableMembers: GatewayNotifiableMembers | undefined;+ recipients: ReturnType<typeof useTeamRecipients>;isInviting: boolean;/** Resolves to null when the request failed and was already reported. */onInvite: (params: {@@ -21,80 +16,36 @@ export type TeamInviteFormProps = {onFinish: (outcome: { isSkipped: boolean }) => void;};-function getSendLabel(emailCount: number) {- if (emailCount === 0) return "Notify members";- if (emailCount === 1) return "Send 1 invite";- return `Send ${emailCount} invites`;-}-export function TeamInviteForm({- notifiableMembers,+ recipients,isInviting,onInvite,onFinish,}: TeamInviteFormProps) {- const invitees = useTeamInviteEmails();- const [notifyMembers, setNotifyMembers] = useState(true);- // Retrying failed invites must not announce the gateway to every member again.- const [haveMembersBeenNotified, setHaveMembersBeenNotified] = useState(false);-- const canNotify =- !haveMembersBeenNotified &&- notifiableMembers !== undefined &&- notifiableMembers.isEmailConfigured &&- notifiableMembers.count > 0;- const willNotify = canNotify && notifyMembers;- const sendLabel = getSendLabel(invitees.emails.length);+ const form = useTeamNotifyForm(recipients);async function handleSend() {- invitees.startAttempt();- const result = await onInvite({- emails: invitees.emails,- notifyMembers: willNotify,- });- if (!result) return;- if (willNotify) setHaveMembersBeenNotified(true);- if (result.failed.length > 0) {- invitees.keepFailed(result.failed);- return;- }- onFinish({ isSkipped: false });+ if (await form.send(onInvite)) onFinish({ isSkipped: false });+ }++ function handleSkip() {+ onFinish({ isSkipped: true });}return (<div className="flex flex-col gap-4 pt-1">- <TeamInviteFields- emails={invitees.emails}- onEmailsChange={invitees.setEmails}- errorMessage={invitees.errorMessage}- notifyMembers={- canNotify- ? {- memberCount: notifiableMembers.count,- previewMembers: notifiableMembers.preview,- checked: notifyMembers,- onCheckedChange: setNotifyMembers,- }- : undefined- }- />- {invitees.failures.length > 0 ? (- <TeamInviteFailuresAlert failures={invitees.failures} />+ <TeamInviteFields {...form.fieldsProps} />+ {form.failures.length > 0 ? (+ <TeamInviteFailuresAlert failures={form.failures} />) : null}<div className="flex items-center gap-2"><Button- text={sendLabel}+ text={form.sendLabel}loading={isInviting}- disabled={- !invitees.isValid || (invitees.emails.length === 0 && !willNotify)- }+ disabled={!form.canSend}onClick={handleSend}/>- <Button- text="Skip for now"- variant="ghost"- onClick={() => onFinish({ isSkipped: true })}- />+ <Button text="Skip for now" variant="ghost" onClick={handleSkip} /></div></div>);diff --git a/web/src/features/ai-gateway/components/GatewaySetupPage/hooks/useGatewayTeamInvite.ts b/web/src/features/ai-gateway/components/GatewaySetupPage/hooks/useGatewayTeamInvite.tsindex 66f69d1756..cbb9625763 100644--- a/web/src/features/ai-gateway/components/GatewaySetupPage/hooks/useGatewayTeamInvite.ts+++ b/web/src/features/ai-gateway/components/GatewaySetupPage/hooks/useGatewayTeamInvite.ts@@ -1,13 +1,12 @@import { toTeamInviteSentEvent } from "@/src/features/ai-gateway/fns/toTeamInviteSentEvent";+import { useTeamRecipients } from "@/src/features/ai-gateway/hooks/useTeamRecipients";import { usePostHogClientCapture } from "@/src/features/posthog-analytics/usePostHogClientCapture";import { api, reportNonTrpcError } from "@/src/utils/api";export function useGatewayTeamInvite(organizationId: string) {const utils = api.useUtils();const capture = usePostHogClientCapture();- const notifiableMembersQuery = api.aiGateway.getNotifiableMembers.useQuery({- orgId: organizationId,- });+ const recipients = useTeamRecipients(organizationId);const mutation = api.aiGateway.inviteTeam.useMutation();async function inviteTeam(params: {@@ -39,7 +38,7 @@ export function useGatewayTeamInvite(organizationId: string) {}return {- notifiableMembers: notifiableMembersQuery.data,+ recipients,inviteTeam,isInviting: mutation.isPending,};diff --git a/web/src/features/ai-gateway/components/GatewaySetupPage/types/gatewaySetup.ts b/web/src/features/ai-gateway/components/GatewaySetupPage/types/gatewaySetup.tsindex 633b1d39c9..5010e5a3e6 100644--- a/web/src/features/ai-gateway/components/GatewaySetupPage/types/gatewaySetup.ts+++ b/web/src/features/ai-gateway/components/GatewaySetupPage/types/gatewaySetup.ts@@ -8,9 +8,6 @@ export type GatewayConfig = NonNullable<export type GatewayProject = { id: string; name: string };-export type GatewayNotifiableMembers =- RouterOutputs["aiGateway"]["getNotifiableMembers"];-export type GatewayTeamInviteResult = RouterOutputs["aiGateway"]["inviteTeam"];export type GatewayIngestionSettings = {diff --git a/web/src/features/ai-gateway/components/TeamInviteFields/TeamInviteFields.stories.tsx b/web/src/features/ai-gateway/components/TeamInviteFields/TeamInviteFields.stories.tsxindex 3d6a2e7051..03e2a00b96 100644--- a/web/src/features/ai-gateway/components/TeamInviteFields/TeamInviteFields.stories.tsx+++ b/web/src/features/ai-gateway/components/TeamInviteFields/TeamInviteFields.stories.tsx@@ -1,11 +1,22 @@import { expect, fn, userEvent, within } from "storybook/test";+import { useState } from "react";+import preview from "@/.storybook/preview";-import { TeamInviteFields } from "./TeamInviteFields";+import {+ TeamInviteFields,+ type TeamInviteFieldsProps,+} from "./TeamInviteFields";++/** Keeps the typed text in state so typing behaves like the real form. */+function TeamInviteFieldsWithDraft(props: TeamInviteFieldsProps) {+ const [draft, setDraft] = useState(props.draft);+ return <TeamInviteFields {...props} draft={draft} onDraftChange={setDraft} />;+}const meta = preview.meta({ component: TeamInviteFields });-const previewMembers = [+const suggestedMembers = [{ id: "user-1", name: "Ada Lovelace", email: "[email protected]", image: null },{id: "user-2",@@ -22,49 +33,142 @@ const previewMembers = [},];+const members = new Map([+ [+ "[email protected]",+ { name: "Ada Lovelace", isSelf: false, canUseGateway: true },+ ],+ ["[email protected]", { name: "Tobi", isSelf: true, canUseGateway: true }],+ [+ "[email protected]",+ { name: "Vera Viewer", isSelf: false, canUseGateway: false },+ ],+ ["[email protected]", null],+ ["[email protected]", null],+]);+export const Empty = meta.story({args: {emails: [],onEmailsChange: fn(),- notifyMembers: {+ draft: "",+ onDraftChange: fn(),+ members: new Map(),+ memberSuggestions: {memberCount: 12,- previewMembers,- checked: true,- onCheckedChange: fn(),+ suggestedMembers,+ onMemberAdd: fn(),+ isAllSelected: false,+ onAllSelectedChange: fn(),},},});-export const WithEmails = meta.story({+export const WithMemberAndExternal = meta.story({args: {...Empty.input.args,- emails: ["[email protected]", "[email protected]", "not-an-email"],+ emails: ["[email protected]", "[email protected]"],+ members,+ },+});++/** Two people to invite, and one address still being looked up. */+export const WithPendingLookup = meta.story({+ args: {+ ...Empty.input.args,+ members,+ },+});++/** The sender and a member whose role can't use the gateway get no email. */+export const WithMembersNotNotified = meta.story({+ args: {+ ...Empty.input.args,+ emails: ["[email protected]", "[email protected]"],+ members,+ },+});++export const AllMembersSelected = meta.story({+ args: {+ ...WithMemberAndExternal.input.args,+ memberSuggestions: {+ ...Empty.input.args.memberSuggestions,+ isAllSelected: true,+ },},});export const WithError = meta.story({args: {- ...WithEmails.input.args,+ ...WithMemberAndExternal.input.args,+ emails: [...WithMemberAndExternal.input.args.emails, "not-an-email"],errorMessage: "You can invite up to 50 people at once.",},});+/** While typing, only matching members are offered and "All existing members" steps aside. */+export const Searching = meta.story({+ args: {+ ...Empty.input.args,+ draft: "gra",+ memberSuggestions: {+ ...Empty.input.args.memberSuggestions,+ suggestedMembers: suggestedMembers.slice(1, 2),+ },+ },+});+export const WithoutMembersToNotify = meta.story({args: {- emails: [],+ emails: ["[email protected]"],onEmailsChange: fn(),+ draft: "",+ onDraftChange: fn(),+ members,},});-export const TestSpaceCommitsEmail = meta.story({- name: "(Test) Space commits an email",- args: { emails: [], onEmailsChange: fn() },+export const TestPickingSuggestions = meta.story({+ name: "(Test) Suggestions pick members by click or Enter, never the typed text",+ args: {+ ...Empty.input.args,+ memberSuggestions: {+ ...Empty.input.args.memberSuggestions,+ onMemberAdd: fn(),+ onAllSelectedChange: fn(),+ },+ },+ render: (args) => <TeamInviteFieldsWithDraft {...args} />,play: async ({ args, canvasElement }) => {- const input = within(canvasElement).getByRole("textbox", {- name: "Email addresses",- });- await userEvent.type(input, "[email protected] ");- await expect(args.onEmailsChange).toHaveBeenCalledWith(["[email protected]"]);- await expect(input).toHaveValue("");+ const canvas = within(canvasElement);+ const input = canvas.getByRole("textbox", { name: "Email addresses" });+ const onMemberAdd = args.memberSuggestions?.onMemberAdd;++ await userEvent.click(+ canvas.getByRole("button", { name: "All existing members (12)" }),+ );+ await expect(+ args.memberSuggestions?.onAllSelectedChange,+ ).toHaveBeenCalledWith(true);++ await userEvent.click(input);+ await userEvent.keyboard("{Enter}");+ await expect(onMemberAdd).not.toHaveBeenCalled();++ // Pressing a pill must not blur the input and commit the half-typed address.+ await userEvent.type(input, "grace@");+ await userEvent.click(canvas.getByRole("button", { name: "Grace Hopper" }));+ await expect(onMemberAdd).toHaveBeenLastCalledWith(+ expect.objectContaining({ email: "[email protected]" }),+ );+ await expect(args.onEmailsChange).not.toHaveBeenCalled();++ await userEvent.clear(input);+ await userEvent.type(input, "ada{Enter}");+ await expect(onMemberAdd).toHaveBeenLastCalledWith(+ expect.objectContaining({ email: "[email protected]" }),+ );},});diff --git a/web/src/features/ai-gateway/components/TeamInviteFields/TeamInviteFields.tsx b/web/src/features/ai-gateway/components/TeamInviteFields/TeamInviteFields.tsxindex 07b911ee4a..a46158a1b3 100644--- a/web/src/features/ai-gateway/components/TeamInviteFields/TeamInviteFields.tsx+++ b/web/src/features/ai-gateway/components/TeamInviteFields/TeamInviteFields.tsx@@ -1,60 +1,135 @@import { useId } from "react";-import { Mail } from "@langfuse/icons";+import { Plus, Users } from "@langfuse/icons";+import { Button } from "@/src/components/design-system/Button/Button";+import { Tag } from "@/src/components/design-system/Tag/Tag";import { EmailTagInput } from "@/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/EmailTagInput";+import { ExternalInviteeHint } from "@/src/features/ai-gateway/components/TeamInviteFields/components/ExternalInviteeHint";import {- NotifyMembersToggle,- type NotifyMembersToggleProps,-} from "@/src/features/ai-gateway/components/TeamInviteFields/components/NotifyMembersToggle";+ MemberSuggestion,+ type MemberSuggestionProps,+} from "@/src/features/ai-gateway/components/TeamInviteFields/components/MemberSuggestion";+import { MemberSuggestionRow } from "@/src/features/ai-gateway/components/TeamInviteFields/components/MemberSuggestionRow";+import { getInviteeKind } from "@/src/features/ai-gateway/fns/getInviteeKind";+import type { TeamInviteMembers } from "@/src/features/ai-gateway/types/teamInviteMembers";export type TeamInviteFieldsProps = {emails: string[];onEmailsChange: (emails: string[]) => void;- /** Replaces the input hint while set. */+ /** Text being typed; doubles as the member search. */+ draft: string;+ onDraftChange: (draft: string) => void;+ members: TeamInviteMembers;+ /** Shown below the input while set. */errorMessage?: string;/** Omit when there is nobody to notify or email is not configured. */- notifyMembers?: NotifyMembersToggleProps;+ memberSuggestions?: {+ memberCount: number;+ /** Members matching the draft that are not picked yet. */+ suggestedMembers: MemberSuggestionProps["member"][];+ onMemberAdd: MemberSuggestionProps["onAdd"];+ isAllSelected: boolean;+ onAllSelectedChange: (isSelected: boolean) => void;+ };};-/** One framed field: invitee emails on top, the member announcement below. */+/**+ * Recipient picker: typed addresses and picked members as chips, quick picks+ * for existing members below, and a note on who gets invited to the organization.+ */export function TeamInviteFields({emails,onEmailsChange,+ draft,+ onDraftChange,+ members,errorMessage,- notifyMembers,+ memberSuggestions,}: TeamInviteFieldsProps) {const inputId = useId();- const hintId = useId();+ const errorId = useId();+ const externalCount = emails.filter(+ (email) => getInviteeKind(email, members) === "external",+ ).length;+ const isAllSelected = memberSuggestions?.isAllSelected ?? false;+ const isSearching = draft.trim().length > 0;+ const suggestedMembers = memberSuggestions?.suggestedMembers ?? [];+ const showAllMembersSuggestion =+ memberSuggestions !== undefined && !isAllSelected && !isSearching;+ const showMemberSuggestions = !isAllSelected && suggestedMembers.length > 0;++ const topSuggestedMember = showMemberSuggestions+ ? suggestedMembers[0]+ : undefined;++ function handleAddMember(member: MemberSuggestionProps["member"]) {+ memberSuggestions?.onMemberAdd(member);+ }++ function handlePickTopSuggestion() {+ if (topSuggestedMember) handleAddMember(topSuggestedMember);+ }++ function handleSelectAll() {+ memberSuggestions?.onAllSelectedChange(true);+ }++ function handleDeselectAll() {+ memberSuggestions?.onAllSelectedChange(false);+ }return (- <div className="has-[input:focus]:border-ring flex max-w-xl flex-col rounded-md border">- <div className="flex items-start gap-2.5 px-3 py-2.5">- <span className="flex h-6 shrink-0 items-center">- <Mail size="base" color="tertiary" aria-hidden />- </span>- <div className="flex min-w-0 flex-1 flex-col gap-1">- <EmailTagInput- id={inputId}- value={emails}- onChange={onEmailsChange}- aria-describedby={hintId}- />- {errorMessage ? (- <p id={hintId} role="alert" className="text-destructive text-xs">- {errorMessage}- </p>- ) : (- <p id={hintId} className="text-muted-foreground text-xs">- Separate with a comma, space or Enter. They join as Member.- </p>- )}- </div>+ <div className="flex max-w-xl flex-col gap-2">+ <div className="has-[input:focus]:border-ring rounded-md border px-3 py-2">+ <EmailTagInput+ id={inputId}+ value={emails}+ onChange={onEmailsChange}+ draft={draft}+ onDraftChange={onDraftChange}+ onPickTopSuggestion={+ topSuggestedMember ? handlePickTopSuggestion : undefined+ }+ members={members}+ aria-describedby={errorMessage ? errorId : undefined}+ >+ {memberSuggestions && isAllSelected ? (+ <Tag+ text="All existing members"+ secondaryText={String(memberSuggestions.memberCount)}+ icon={Users}+ remove={{ onRemove: handleDeselectAll }}+ />+ ) : null}+ </EmailTagInput></div>- {notifyMembers ? (- <div className="border-t px-3 py-2.5">- <NotifyMembersToggle {...notifyMembers} />- </div>+ {errorMessage ? (+ <p id={errorId} role="alert" className="text-destructive text-xs">+ {errorMessage}+ </p>) : null}+ {(showAllMembersSuggestion || showMemberSuggestions) && (+ <MemberSuggestionRow>+ {showAllMembersSuggestion && (+ <Button+ variant="outline"+ size="sm"+ icon={Plus}+ text={`All existing members (${memberSuggestions.memberCount})`}+ onClick={handleSelectAll}+ />+ )}+ {showMemberSuggestions &&+ suggestedMembers.map((member) => (+ <MemberSuggestion+ key={member.id}+ member={member}+ onAdd={handleAddMember}+ />+ ))}+ </MemberSuggestionRow>+ )}+ {externalCount > 0 ? <ExternalInviteeHint count={externalCount} /> : null}</div>);}diff --git a/web/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/EmailTagInput.tsx b/web/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/EmailTagInput.tsxindex 71dd4f4b40..b4330fb886 100644--- a/web/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/EmailTagInput.tsx+++ b/web/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/EmailTagInput.tsx@@ -1,46 +1,60 @@-import { useState, type ChangeEvent, type KeyboardEvent } from "react";-import { z } from "zod/v4";+import { type ChangeEvent, type KeyboardEvent, type ReactNode } from "react";import { EmailTag } from "@/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/components/EmailTag";-import {- appendEmails,- splitEmailText,-} from "@/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/fns/emailText";+import { appendEmails } from "@/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/fns/emailText";+import { takeAddresses } from "@/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/fns/takeAddresses";+import { getInviteeKind } from "@/src/features/ai-gateway/fns/getInviteeKind";+import type { TeamInviteMembers } from "@/src/features/ai-gateway/types/teamInviteMembers";export type EmailTagInputProps = {id: string;value: string[];onChange: (emails: string[]) => void;+ /** Text not turned into a chip yet; without an `@` it is a member search. */+ draft: string;+ onDraftChange: (draft: string) => void;+ /** Called on Enter while the draft is a search, to pick the top match. A search is never turned into chips. */+ onPickTopSuggestion?: () => void;+ members: TeamInviteMembers;"aria-describedby"?: string;+ /** Chips shown before the addresses. */+ children?: ReactNode;};/**- * Turns typed or pasted addresses into removable chips on comma, space, Enter, or- * blur. Borderless: the surrounding field draws the frame.+ * Turns typed or pasted addresses into removable chips once a comma, space,+ * Enter, or blur ends them. Text without an `@` stays a search, and Enter picks+ * the top suggestion. Borderless: the surrounding field draws the frame.*/export function EmailTagInput({id,value,onChange,+ draft,+ onDraftChange,+ onPickTopSuggestion,+ members,"aria-describedby": ariaDescribedBy,+ children,}: EmailTagInputProps) {- const [draft, setDraft] = useState("");-- function commit(text: string) {- setDraft("");- if (text.trim().length > 0) onChange(appendEmails(value, text));+ /** Turns the addresses in `text` into chips; returns whether there were any. */+ function commitAddresses(text: string, { isTyping = false } = {}) {+ const { addresses, rest } = takeAddresses(text, { isTyping });+ if (addresses.length > 0)+ onChange(appendEmails(value, addresses.join(" ")));+ onDraftChange(rest);+ return addresses.length > 0;}function handleChange(event: ChangeEvent<HTMLInputElement>) {- const text = event.target.value;- if (splitEmailText(text).length > 1) commit(text);- else setDraft(text);+ commitAddresses(event.target.value, { isTyping: true });}function handleKeyDown(event: KeyboardEvent<HTMLInputElement>) {if (event.key === "Enter") {event.preventDefault();- commit(draft);+ const hasCommitted = commitAddresses(draft);+ if (!hasCommitted && draft.trim().length > 0) onPickTopSuggestion?.();return;}if (event.key === "Backspace" && draft.length === 0 && value.length > 0) {@@ -48,8 +62,9 @@ export function EmailTagInput({}}+ // Text without an `@` stays a search when the input loses focus.function handleBlur() {- commit(draft);+ commitAddresses(draft);}function handleRemove(email: string) {@@ -58,11 +73,13 @@ export function EmailTagInput({return (<div className="ph-no-capture flex min-h-6 min-w-0 flex-wrap items-center gap-1.5 text-sm">+ {children}{value.map((email) => (<EmailTagkey={email}email={email}- invalid={!z.email().safeParse(email).success}+ kind={getInviteeKind(email, members)}+ memberName={members.get(email)?.name}onRemove={handleRemove}/>))}@@ -72,7 +89,9 @@ export function EmailTagInput({inputMode="email"autoComplete="off"data-1p-ignore- placeholder={value.length === 0 ? "[email protected]" : undefined}+ placeholder={+ value.length === 0 && !children ? "[email protected]" : undefined+ }aria-label="Email addresses"aria-describedby={ariaDescribedBy}className="placeholder:text-muted-foreground h-6 min-w-24 flex-1 border-0 bg-transparent p-0 text-sm shadow-none outline-hidden focus:ring-0"diff --git a/web/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/components/EmailTag.tsx b/web/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/components/EmailTag.tsxindex 2772fac527..3347147db8 100644--- a/web/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/components/EmailTag.tsx+++ b/web/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/components/EmailTag.tsx@@ -1,20 +1,41 @@+import { Mail } from "@langfuse/icons";+import { Tag } from "@/src/components/design-system/Tag/Tag";+import type { getInviteeKind } from "@/src/features/ai-gateway/fns/getInviteeKind";++type InviteeKind = ReturnType<typeof getInviteeKind>;++/** Why an address gets no email, shown after its name. */+const NOT_NOTIFIED_REASON: Partial<Record<InviteeKind, string>> = {+ self: "(you)",+ memberWithoutAccess: "(role can't use the gateway)",+};++function getTagStatus(kind: InviteeKind) {+ if (kind === "invalid") return "error";+ if (kind === "memberWithoutAccess") return "warning";+ return "default";+}export type EmailTagProps = {email: string;- invalid: boolean;+ kind: InviteeKind;+ /** Shown instead of the address for members with a name. */+ memberName: string | null | undefined;onRemove: (email: string) => void;};-export function EmailTag({ email, invalid, onRemove }: EmailTagProps) {+export function EmailTag({ email, kind, memberName, onRemove }: EmailTagProps) {function handleRemove() {onRemove(email);}return (<Tag- text={email}- status={invalid ? "error" : "default"}+ text={memberName ?? email}+ secondaryText={NOT_NOTIFIED_REASON[kind]}+ icon={kind === "external" ? Mail : undefined}+ status={getTagStatus(kind)}remove={{ onRemove: handleRemove }}/>);diff --git a/web/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/fns/emailText.ts b/web/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/fns/emailText.tsindex 0026653f02..c2fa344574 100644--- a/web/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/fns/emailText.ts+++ b/web/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/fns/emailText.ts@@ -1,5 +1,5 @@/** Splits typed or pasted text on whitespace, commas, and semicolons. */-export function splitEmailText(text: string) {+function splitEmailText(text: string) {return text.split(/[\s,;]+/);}diff --git a/web/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/fns/takeAddresses.clienttest.ts b/web/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/fns/takeAddresses.clienttest.tsnew file mode 100644index 0000000000..4a1aefc63e--- /dev/null+++ b/web/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/fns/takeAddresses.clienttest.ts@@ -0,0 +1,74 @@+import { takeAddresses } from "@/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/fns/takeAddresses";++describe("takeAddresses while typing", () => {+ const typing = (text: string) => takeAddresses(text, { isTyping: true });++ it.each([+ "foo, test@",+ ", test@",+ " test@",+ "test@ company.com",+ "test @company.com",+ "David Kim",+ ])("keeps %j as typed", (text) => {+ expect(typing(text)).toEqual({ addresses: [], rest: text });+ });++ it("ends a valid address with a space or a comma", () => {+ expect(typing("[email protected] ")).toEqual({+ addresses: ["[email protected]"],+ rest: "",+ });+ expect(typing("foo, [email protected],")).toEqual({+ addresses: ["[email protected]"],+ rest: "foo ",+ });+ });++ it("joins an address split by stray spaces once a comma ends it", () => {+ expect(typing("test@ company.com,")).toEqual({+ addresses: ["[email protected]"],+ rest: "",+ });+ });++ it("keeps the word still being typed after a pasted list", () => {+ expect(typing("[email protected] [email protected], carl@comp")).toEqual({+ addresses: ["[email protected]", "[email protected]"],+ rest: "carl@comp",+ });+ });+});++describe("takeAddresses on Enter or blur", () => {+ const ending = (text: string) => takeAddresses(text, { isTyping: false });++ it("drops stray spaces inside a single address", () => {+ expect(ending(" test @ company.com ")).toEqual({+ addresses: ["[email protected]"],+ rest: "",+ });+ });++ it("repairs only the address next to a search word, not the search word", () => {+ expect(ending("John john@ company.com")).toEqual({+ addresses: ["[email protected]"],+ rest: "John",+ });+ });++ it("keeps words without an @ next to a valid address", () => {+ expect(ending("foo [email protected]")).toEqual({+ addresses: ["[email protected]"],+ rest: "foo",+ });+ });++ it("turns a malformed address into a chip, so it shows as invalid", () => {+ expect(ending("ada@")).toEqual({ addresses: ["ada@"], rest: "" });+ });++ it("leaves a search untouched", () => {+ expect(ending("ada love")).toEqual({ addresses: [], rest: "ada love" });+ });+});diff --git a/web/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/fns/takeAddresses.ts b/web/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/fns/takeAddresses.tsnew file mode 100644index 0000000000..1dc617fc6f--- /dev/null+++ b/web/src/features/ai-gateway/components/TeamInviteFields/components/EmailTagInput/fns/takeAddresses.ts@@ -0,0 +1,72 @@+import { z } from "zod/v4";++const EXPLICIT_SEPARATOR = /[,;]/;+const WHITESPACE = /\s+/;++function isValidEmail(text: string) {+ return z.email().safeParse(text).success;+}++/**+ * Addresses in a chunk the user ended with a comma, Enter, or blur. When no word+ * is an address on its own, the fragments touching the `@` are joined+ * (`ada@ x.com`, `ada @x.com`); other words stay, so a search word in front is+ * not glued into the address.+ */+function parseEndedChunk(chunk: string) {+ const words = chunk.split(WHITESPACE).filter((word) => word.length > 0);+ const atIndex = words.findIndex((word) => word.includes("@"));+ if (atIndex !== -1 && !words.some(isValidEmail)) {+ const atWord = words[atIndex]!;+ const start = atWord.startsWith("@") ? Math.max(atIndex - 1, 0) : atIndex;+ const end = atWord.endsWith("@") ? atIndex + 1 : atIndex;+ const joined = words.slice(start, end + 1).join("");+ if (isValidEmail(joined)) {+ return {+ addresses: [joined],+ leftover: [...words.slice(0, start), ...words.slice(end + 1)],+ };+ }+ }+ return {+ addresses: words.filter((word) => word.includes("@")),+ leftover: words.filter((word) => !word.includes("@")),+ };+}++/** Addresses a space already ended in the chunk still being typed. */+function parseTypingChunk(chunk: string) {+ const words = chunk.split(WHITESPACE);+ const typingWord = words.pop() ?? "";+ const endedWords = words.filter((word) => word.length > 0);+ return {+ addresses: endedWords.filter(isValidEmail),+ leftover: [...endedWords.filter((word) => !isValidEmail(word)), typingWord],+ };+}++/**+ * Splits the input's text into addresses to turn into chips and the text that+ * stays in the input, so stray commas and spaces never cut an address.+ *+ * While typing (`isTyping`), a comma or semicolon ends an address, and a space+ * ends it only once it is valid; the rest stays as typed. Otherwise (Enter,+ * blur) everything with an `@` becomes a chip. Text without an `@` always stays,+ * since it is a member search.+ */+export function takeAddresses(+ text: string,+ { isTyping }: { isTyping: boolean },+) {+ const chunks = text.split(EXPLICIT_SEPARATOR);+ const typingChunk = isTyping ? (chunks.pop() ?? "") : undefined;+ const parts = chunks.map(parseEndedChunk);+ if (typingChunk !== undefined) parts.push(parseTypingChunk(typingChunk));++ const addresses = parts.flatMap((part) => part.addresses);+ if (addresses.length === 0) return { addresses, rest: text };+ return {+ addresses,+ rest: parts.flatMap((part) => part.leftover).join(" "),+ };+}diff --git a/web/src/features/ai-gateway/components/TeamInviteFields/components/ExternalInviteeHint.tsx b/web/src/features/ai-gateway/components/TeamInviteFields/components/ExternalInviteeHint.tsxnew file mode 100644index 0000000000..9bfc52acc2--- /dev/null+++ b/web/src/features/ai-gateway/components/TeamInviteFields/components/ExternalInviteeHint.tsx@@ -0,0 +1,24 @@+import { Mail } from "@langfuse/icons";++export type ExternalInviteeHintProps = {+ count: number;+};++export function ExternalInviteeHint({ count }: ExternalInviteeHintProps) {+ const subject = count === 1 ? "1 person isn't" : `${count} people aren't`;++ return (+ <p className="text-muted-foreground flex items-start gap-1.5 text-xs">+ {/* One line tall, so a wrapping hint keeps the icon on its first line;+ nudged down to the lowercase text's middle rather than the line box's. */}+ <span className="flex h-4 shrink-0 translate-y-px items-center">+ <Mail size="sm" color="tertiary" aria-hidden />+ </span>+ <span>+ {subject} in the organization yet. They'll be invited to the+ organization and join as{" "}+ <strong className="text-foreground font-bold">Member</strong>.+ </span>+ </p>+ );+}diff --git a/web/src/features/ai-gateway/components/TeamInviteFields/components/MemberSuggestion.tsx b/web/src/features/ai-gateway/components/TeamInviteFields/components/MemberSuggestion.tsxnew file mode 100644index 0000000000..f6c8d45519--- /dev/null+++ b/web/src/features/ai-gateway/components/TeamInviteFields/components/MemberSuggestion.tsx@@ -0,0 +1,25 @@+import { Plus } from "@langfuse/icons";++import { Button } from "@/src/components/design-system/Button/Button";+import type { RouterOutputs } from "@/src/utils/api";++export type MemberSuggestionProps = {+ member: RouterOutputs["aiGateway"]["getMemberSuggestions"][number];+ onAdd: (member: MemberSuggestionProps["member"]) => void;+};++export function MemberSuggestion({ member, onAdd }: MemberSuggestionProps) {+ function handleClick() {+ onAdd(member);+ }++ return (+ <Button+ variant="outline"+ size="sm"+ icon={Plus}+ text={member.name ?? member.email}+ onClick={handleClick}+ />+ );+}diff --git a/web/src/features/ai-gateway/components/TeamInviteFields/components/MemberSuggestionRow.tsx b/web/src/features/ai-gateway/components/TeamInviteFields/components/MemberSuggestionRow.tsxnew file mode 100644index 0000000000..f05897a85b--- /dev/null+++ b/web/src/features/ai-gateway/components/TeamInviteFields/components/MemberSuggestionRow.tsx@@ -0,0 +1,24 @@+import type { MouseEvent, ReactNode } from "react";++export type MemberSuggestionRowProps = {+ children: ReactNode;+};++/**+ * Row of quick-pick pills. Pressing a pill keeps focus in the email input, so+ * its blur does not commit half-typed text before the click lands.+ */+export function MemberSuggestionRow({ children }: MemberSuggestionRowProps) {+ function handleMouseDown(event: MouseEvent<HTMLDivElement>) {+ event.preventDefault();+ }++ return (+ <div+ className="ph-no-capture flex flex-wrap gap-2"+ onMouseDown={handleMouseDown}+ >+ {children}+ </div>+ );+}diff --git a/web/src/features/ai-gateway/components/TeamInviteFields/components/NotifyMembersToggle.tsx b/web/src/features/ai-gateway/components/TeamInviteFields/components/NotifyMembersToggle.tsxdeleted file mode 100644index c8c78ca1e2..0000000000--- a/web/src/features/ai-gateway/components/TeamInviteFields/components/NotifyMembersToggle.tsx+++ /dev/null@@ -1,66 +0,0 @@-import { useId } from "react";--import { Avatar } from "@/src/components/design-system/Avatar/Avatar";-import { Switch } from "@/src/components/design-system/Switch/Switch";-import type { RouterOutputs } from "@/src/utils/api";--export type NotifyMembersToggleProps = {- memberCount: number;- previewMembers: RouterOutputs["aiGateway"]["getNotifiableMembers"]["preview"];- checked: boolean;- onCheckedChange: (checked: boolean) => void;-};--export function NotifyMembersToggle({- memberCount,- previewMembers,- checked,- onCheckedChange,-}: NotifyMembersToggleProps) {- const id = useId();- const overflowCount = memberCount - previewMembers.length;-- return (- <div className="flex items-center gap-3">- <div className="ph-no-capture flex shrink-0 items-center -space-x-1">- {previewMembers.map((member) => (- <span- key={member.id}- className="ring-background inline-flex rounded-full ring-2"- >- <Avatar- size="sm"- tone="tinted"- displayName={member.name ?? member.email ?? ""}- email={member.email ?? undefined}- src={member.image ?? undefined}- />- </span>- ))}- {overflowCount > 0 ? (- <span className="bg-muted text-foreground-secondary ring-background flex size-6 items-center justify-center rounded-full text-[10px] ring-2">- +{overflowCount}- </span>- ) : null}- </div>- <label- htmlFor={id}- className="flex min-w-0 flex-1 cursor-pointer flex-col"- >- <span className="text-sm">- Notify the {memberCount} existing member- {memberCount === 1 ? "" : "s"}- </span>- <span className="text-muted-foreground text-xs">- They get an email that the AI Gateway is available.- </span>- </label>- <Switch- id={id}- size="sm"- checked={checked}- onCheckedChange={onCheckedChange}- />- </div>- );-}diff --git a/web/src/features/ai-gateway/constants/gatewayTeamInvites.ts b/web/src/features/ai-gateway/constants/gatewayTeamInvites.tsindex 0aea625a0e..0ada5c6aa9 100644--- a/web/src/features/ai-gateway/constants/gatewayTeamInvites.ts+++ b/web/src/features/ai-gateway/constants/gatewayTeamInvites.ts@@ -1 +1,10 @@export const MAX_TEAM_INVITES = 50;++export const MAX_MEMBER_SEARCH_LENGTH = 320;++export const TEAM_NOTIFY_COPY = {+ title: "Notify your team",+ description:+ "Members can create their own gateway keys and use the models you enabled. New people join as Member.",+ rolesDocsUrl: "https://langfuse.com/docs/administration/rbac",+} as const;diff --git a/web/src/features/ai-gateway/fns/getInviteeKind.ts b/web/src/features/ai-gateway/fns/getInviteeKind.tsnew file mode 100644index 0000000000..7d36c9ed7b--- /dev/null+++ b/web/src/features/ai-gateway/fns/getInviteeKind.ts@@ -0,0 +1,18 @@+import { z } from "zod/v4";++import type { TeamInviteMembers } from "@/src/features/ai-gateway/types/teamInviteMembers";++/**+ * Whether an invitee address is a member to notify, someone to invite, an+ * address that gets no email (the sender, or a member whose role can't use the+ * gateway), or not known yet.+ */+export function getInviteeKind(email: string, members: TeamInviteMembers) {+ if (!z.email().safeParse(email).success) return "invalid";+ const member = members.get(email);+ if (member === undefined) return "pending";+ if (member === null) return "external";+ if (member.isSelf) return "self";+ if (!member.canUseGateway) return "memberWithoutAccess";+ return "member";+}diff --git a/web/src/features/ai-gateway/hooks/useTeamInviteEmails.ts b/web/src/features/ai-gateway/hooks/useTeamInviteEmails.tsindex 98b8bf7049..f3de5c7e05 100644--- a/web/src/features/ai-gateway/hooks/useTeamInviteEmails.ts+++ b/web/src/features/ai-gateway/hooks/useTeamInviteEmails.ts@@ -3,17 +3,38 @@ import { z } from "zod/v4";import { MAX_TEAM_INVITES } from "@/src/features/ai-gateway/constants/gatewayTeamInvites";import type { TeamInviteFailure } from "@/src/features/ai-gateway/types/teamInviteFailure";+import type { RouterOutputs } from "@/src/utils/api";-/** Invitee list for one invite attempt, keeping only failed addresses for a retry. */+type PickedMember = Pick<+ RouterOutputs["aiGateway"]["getMemberSuggestions"][number],+ "email" | "name"+>;++/**+ * Invitee list for one invite attempt, keeping only failed addresses for a+ * retry, plus the text still being typed, which doubles as the member search.+ * Picked members are kept so their chips show a name before any lookup returns.+ */export function useTeamInviteEmails() {const [emails, setEmails] = useState<string[]>([]);+ const [draft, setDraft] = useState("");const [failures, setFailures] = useState<TeamInviteFailure[]>([]);+ const [pickedMembers, setPickedMembers] = useState<PickedMember[]>([]);const hasInvalidEmail = emails.some((email) => !z.email().safeParse(email).success,);const hasTooManyEmails = emails.length > MAX_TEAM_INVITES;+ function addMember(member: PickedMember) {+ const email = member.email.toLowerCase();+ setDraft("");+ setPickedMembers((current) => [...current, member]);+ setEmails((current) =>+ current.includes(email) ? current : [...current, email],+ );+ }+function startAttempt() {setFailures([]);}@@ -26,6 +47,10 @@ export function useTeamInviteEmails() {return {emails,setEmails,+ draft,+ setDraft,+ pickedMembers,+ addMember,failures,isValid: !hasInvalidEmail && !hasTooManyEmails,errorMessage: hasTooManyEmailsdiff --git a/web/src/features/ai-gateway/hooks/useTeamInviteMemberSuggestions.ts b/web/src/features/ai-gateway/hooks/useTeamInviteMemberSuggestions.tsnew file mode 100644index 0000000000..6dde2be0bd--- /dev/null+++ b/web/src/features/ai-gateway/hooks/useTeamInviteMemberSuggestions.ts@@ -0,0 +1,30 @@+import { keepPreviousData } from "@tanstack/react-query";++import {+ MAX_MEMBER_SEARCH_LENGTH,+ MAX_TEAM_INVITES,+} from "@/src/features/ai-gateway/constants/gatewayTeamInvites";+import { api } from "@/src/utils/api";++/** Members to offer as quick picks, refilled as members are picked and narrowed by `search`. */+export function useTeamInviteMemberSuggestions({+ organizationId,+ search,+ excludeEmails,+ enabled,+}: {+ organizationId: string;+ search: string;+ excludeEmails: string[];+ enabled: boolean;+}) {+ const query = api.aiGateway.getMemberSuggestions.useQuery(+ {+ orgId: organizationId,+ search: search.trim().slice(0, MAX_MEMBER_SEARCH_LENGTH),+ excludeEmails: excludeEmails.slice(0, MAX_TEAM_INVITES),+ },+ { enabled, placeholderData: keepPreviousData },+ );+ return query.data ?? [];+}diff --git a/web/src/features/ai-gateway/hooks/useTeamInviteMembers.ts b/web/src/features/ai-gateway/hooks/useTeamInviteMembers.tsnew file mode 100644index 0000000000..f173157bb4--- /dev/null+++ b/web/src/features/ai-gateway/hooks/useTeamInviteMembers.ts@@ -0,0 +1,45 @@+import { keepPreviousData } from "@tanstack/react-query";+import { z } from "zod/v4";++import { MAX_TEAM_INVITES } from "@/src/features/ai-gateway/constants/gatewayTeamInvites";+import type {+ TeamInviteMember,+ TeamInviteMembers,+} from "@/src/features/ai-gateway/types/teamInviteMembers";+import { api } from "@/src/utils/api";++/**+ * Looks up which invitee addresses already belong to the organization.+ * `knownMembers` (e.g. the member preview) resolve immediately, so picking one+ * does not wait for the lookup.+ */+export function useTeamInviteMembers({+ organizationId,+ emails,+ knownMembers = [],+}: {+ organizationId: string;+ emails: string[];+ /** Other members who can use the gateway, like the notifiable member preview. */+ knownMembers?: Array<Pick<TeamInviteMember, "name"> & { email: string }>;+}): TeamInviteMembers {+ const lookupEmails = emails+ .filter((email) => z.email().safeParse(email).success)+ .slice(0, MAX_TEAM_INVITES);+ const query = api.aiGateway.getInviteeMembers.useQuery(+ { orgId: organizationId, emails: lookupEmails },+ { enabled: lookupEmails.length > 0, placeholderData: keepPreviousData },+ );++ const members = new Map<string, TeamInviteMember | null>(+ (query.data ?? []).map(({ email, member }) => [email, member]),+ );+ for (const { email, name } of knownMembers) {+ members.set(email.toLowerCase(), {+ name,+ isSelf: false,+ canUseGateway: true,+ });+ }+ return members;+}diff --git a/web/src/features/ai-gateway/hooks/useTeamNotifyForm.clienttest.ts b/web/src/features/ai-gateway/hooks/useTeamNotifyForm.clienttest.tsnew file mode 100644index 0000000000..01f8d5dbf3--- /dev/null+++ b/web/src/features/ai-gateway/hooks/useTeamNotifyForm.clienttest.ts@@ -0,0 +1,157 @@+import { act, renderHook } from "@testing-library/react";+import { describe, expect, it, vi } from "vitest";++import { useTeamInviteEmails } from "@/src/features/ai-gateway/hooks/useTeamInviteEmails";+import { useTeamNotifyForm } from "@/src/features/ai-gateway/hooks/useTeamNotifyForm";+import type { TeamInviteMember } from "@/src/features/ai-gateway/types/teamInviteMembers";++const suggestedMembers = [+ { id: "user-1", name: "Ada Lovelace", email: "[email protected]", image: null },+ {+ id: "user-2",+ name: "Grace Hopper",+ email: "[email protected]",+ image: null,+ },+ { id: "user-3", name: null, email: "[email protected]", image: null },+];++const notifiable = { isSelf: false, canUseGateway: true };+const organization = new Map<string, TeamInviteMember>([+ ["[email protected]", { name: "Ada Lovelace", ...notifiable }],+ ["[email protected]", { name: "Grace Hopper", ...notifiable }],+ ["[email protected]", { name: "Me", isSelf: true, canUseGateway: true }],+ [+ "[email protected]",+ { name: "Vera Viewer", isSelf: false, canUseGateway: false },+ ],+]);++/** The form over real invitee state; addresses outside `organization` are outsiders. */+function renderForm({ isEmailConfigured = true } = {}) {+ return renderHook(() => {+ const invitees = useTeamInviteEmails();+ const inviteeMembers = new Map(+ invitees.emails.map((email) => [email, organization.get(email) ?? null]),+ );+ const form = useTeamNotifyForm({+ notifiableMembers: { isEmailConfigured, count: 12 },+ suggestedMembers,+ invitees,+ inviteeMembers,+ });+ return { invitees, form };+ });+}++function suggestedEmails(form: ReturnType<typeof useTeamNotifyForm>) {+ return form.fieldsProps.memberSuggestions?.suggestedMembers.map(+ (member) => member.email,+ );+}++describe("useTeamNotifyForm", () => {+ it("offers members who are not picked yet and match the typed text, even before the next results arrive", () => {+ const { result } = renderForm();++ act(() => result.current.invitees.addMember(suggestedMembers[0]!));+ expect(suggestedEmails(result.current.form)).toEqual([+ "[email protected]",+ "[email protected]",+ ]);++ act(() => result.current.invitees.setDraft("ALAN"));+ expect(suggestedEmails(result.current.form)).toEqual(["[email protected]"]);+ });++ it("counts only the people who get an email", () => {+ const { result } = renderForm();++ act(() =>+ result.current.invitees.setEmails([+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ ]),+ );+ expect(result.current.form.sendLabel).toBe("Notify 2 people");++ act(() =>+ result.current.form.fieldsProps.memberSuggestions?.onAllSelectedChange(+ true,+ ),+ );+ expect(result.current.form.sendLabel).toBe("Notify 13 people");+ });++ it("counts members only when email is configured, while outsiders are still invited", () => {+ const { result } = renderForm({ isEmailConfigured: false });++ act(() =>+ result.current.invitees.setEmails([+ "[email protected]",+ "[email protected]",+ ]),+ );+ expect(result.current.form.sendLabel).toBe("Notify 1 person");+ expect(result.current.form.fieldsProps.memberSuggestions).toBeUndefined();+ });++ it("allows sending only with valid addresses and someone to notify", () => {+ const { result } = renderForm();+ expect(result.current.form.canSend).toBe(false);++ act(() => result.current.invitees.setEmails(["[email protected]"]));+ expect(result.current.form.canSend).toBe(false);++ act(() =>+ result.current.invitees.setEmails(["[email protected]", "not-an-email"]),+ );+ expect(result.current.form.canSend).toBe(false);++ act(() => result.current.invitees.setEmails(["[email protected]"]));+ expect(result.current.form.canSend).toBe(true);+ });++ it("notifies every member once and keeps only failed addresses for a retry", async () => {+ const { result } = renderForm();+ const failed = [+ { email: "[email protected]", message: "Invitation failed" },+ ];+ const invite = vi.fn().mockResolvedValue({ failed });++ act(() => {+ result.current.form.fieldsProps.memberSuggestions?.onAllSelectedChange(+ true,+ );+ result.current.invitees.setEmails([+ "[email protected]",+ "[email protected]",+ ]);+ });+ let isDone: boolean | undefined;+ await act(async () => {+ isDone = await result.current.form.send(invite);+ });++ expect(isDone).toBe(false);+ expect(invite).toHaveBeenLastCalledWith({+ emails: ["[email protected]", "[email protected]"],+ notifyMembers: true,+ });+ expect(result.current.invitees.emails).toEqual(["[email protected]"]);+ expect(result.current.form.failures).toEqual(failed);+ expect(result.current.form.fieldsProps.memberSuggestions).toBeUndefined();++ invite.mockResolvedValue({ failed: [] });+ await act(async () => {+ isDone = await result.current.form.send(invite);+ });+ expect(isDone).toBe(true);+ expect(invite).toHaveBeenLastCalledWith({+ emails: ["[email protected]"],+ notifyMembers: false,+ });+ });+});diff --git a/web/src/features/ai-gateway/hooks/useTeamNotifyForm.ts b/web/src/features/ai-gateway/hooks/useTeamNotifyForm.tsnew file mode 100644index 0000000000..e7c618a6a9--- /dev/null+++ b/web/src/features/ai-gateway/hooks/useTeamNotifyForm.ts@@ -0,0 +1,133 @@+import { useState } from "react";++import type { TeamInviteFieldsProps } from "@/src/features/ai-gateway/components/TeamInviteFields/TeamInviteFields";+import { getInviteeKind } from "@/src/features/ai-gateway/fns/getInviteeKind";+import type { useTeamRecipients } from "@/src/features/ai-gateway/hooks/useTeamRecipients";+import type { TeamInviteFailure } from "@/src/features/ai-gateway/types/teamInviteFailure";+import type { TeamInviteMembers } from "@/src/features/ai-gateway/types/teamInviteMembers";++/**+ * Picked addresses that get an email, or every member plus the picked people+ * outside the organization. People outside are invited even without email;+ * members only hear about it when email is configured.+ */+function getRecipientCount({+ emails,+ members,+ allMemberCount,+ isEmailConfigured,+}: {+ emails: string[];+ members: TeamInviteMembers;+ allMemberCount: number | undefined;+ isEmailConfigured: boolean;+}) {+ const kinds = emails.map((email) => getInviteeKind(email, members));+ const outsiderCount = kinds.filter(+ (kind) => kind === "external" || kind === "pending",+ ).length;+ if (allMemberCount !== undefined) return allMemberCount + outsiderCount;+ if (!isEmailConfigured) return outsiderCount;+ return outsiderCount + kinds.filter((kind) => kind === "member").length;+}++/**+ * Mirrors the server's name or email match, so results still showing for an+ * older search are neither offered nor picked by Enter.+ */+function matchesSearch(+ member: { name: string | null; email: string },+ search: string,+) {+ const term = search.trim().toLowerCase();+ return [member.name, member.email].some((value) =>+ value?.toLowerCase().includes(term),+ );+}++function getNotifyLabel(recipientCount: number) {+ if (recipientCount === 0) return "Notify people";+ if (recipientCount === 1) return "Notify 1 person";+ return `Notify ${recipientCount} people`;+}++/**+ * Notify-your-team form state shared by the setup step and the dialog: whether+ * every member is picked, the send label, and one send attempt that keeps only+ * failed addresses for a retry.+ */+export function useTeamNotifyForm({+ notifiableMembers,+ suggestedMembers,+ invitees,+ inviteeMembers,+}: ReturnType<typeof useTeamRecipients>) {+ const [isAllSelected, setIsAllSelected] = useState(false);+ // Retrying failed invites must not announce the gateway to every member again.+ const [haveMembersBeenNotified, setHaveMembersBeenNotified] = useState(false);++ const canNotify =+ !haveMembersBeenNotified &&+ notifiableMembers !== undefined &&+ notifiableMembers.isEmailConfigured &&+ notifiableMembers.count > 0;+ const notifyMembers = canNotify && isAllSelected;+ const recipientCount = getRecipientCount({+ emails: invitees.emails,+ members: inviteeMembers,+ allMemberCount: notifyMembers ? notifiableMembers.count : undefined,+ // Assume email works until the config loads, so the label does not flicker.+ isEmailConfigured: notifiableMembers?.isEmailConfigured ?? true,+ });++ // Suggestions lag picks and the typed text by one request, so they are re-checked here.+ const currentSuggestions = suggestedMembers.filter(+ (member) =>+ !invitees.emails.includes(member.email.toLowerCase()) &&+ matchesSearch(member, invitees.draft),+ );++ const fieldsProps: TeamInviteFieldsProps = {+ emails: invitees.emails,+ onEmailsChange: invitees.setEmails,+ draft: invitees.draft,+ onDraftChange: invitees.setDraft,+ members: inviteeMembers,+ errorMessage: invitees.errorMessage,+ memberSuggestions: canNotify+ ? {+ memberCount: notifiableMembers.count,+ suggestedMembers: currentSuggestions,+ onMemberAdd: invitees.addMember,+ isAllSelected,+ onAllSelectedChange: setIsAllSelected,+ }+ : undefined,+ };++ /** Resolves to true once every recipient was handled. */+ async function send(+ invite: (params: {+ emails: string[];+ notifyMembers: boolean;+ }) => Promise<{ failed: TeamInviteFailure[] } | null>,+ ) {+ invitees.startAttempt();+ const result = await invite({ emails: invitees.emails, notifyMembers });+ if (!result) return false;+ if (notifyMembers) setHaveMembersBeenNotified(true);+ if (result.failed.length > 0) {+ invitees.keepFailed(result.failed);+ return false;+ }+ return true;+ }++ return {+ fieldsProps,+ failures: invitees.failures,+ sendLabel: getNotifyLabel(recipientCount),+ canSend: invitees.isValid && recipientCount > 0,+ send,+ };+}diff --git a/web/src/features/ai-gateway/hooks/useTeamRecipients.ts b/web/src/features/ai-gateway/hooks/useTeamRecipients.tsnew file mode 100644index 0000000000..dbe46d34d4--- /dev/null+++ b/web/src/features/ai-gateway/hooks/useTeamRecipients.ts@@ -0,0 +1,32 @@+import { useTeamInviteEmails } from "@/src/features/ai-gateway/hooks/useTeamInviteEmails";+import { useTeamInviteMembers } from "@/src/features/ai-gateway/hooks/useTeamInviteMembers";+import { useTeamInviteMemberSuggestions } from "@/src/features/ai-gateway/hooks/useTeamInviteMemberSuggestions";+import { api } from "@/src/utils/api";++/**+ * Everything the team picker reads: the members who can be notified, quick+ * picks for the typed text, the picked addresses, and which of them are members.+ */+export function useTeamRecipients(organizationId: string) {+ const notifiableMembersQuery = api.aiGateway.getNotifiableMembers.useQuery({+ orgId: organizationId,+ });+ const notifiableMembers = notifiableMembersQuery.data;+ const invitees = useTeamInviteEmails();+ const suggestedMembers = useTeamInviteMemberSuggestions({+ organizationId,+ search: invitees.draft,+ excludeEmails: invitees.emails,+ enabled:+ notifiableMembers !== undefined &&+ notifiableMembers.isEmailConfigured &&+ notifiableMembers.count > 0,+ });+ const inviteeMembers = useTeamInviteMembers({+ organizationId,+ emails: invitees.emails,+ knownMembers: [...suggestedMembers, ...invitees.pickedMembers],+ });++ return { notifiableMembers, suggestedMembers, invitees, inviteeMembers };+}diff --git a/web/src/features/ai-gateway/server/router.ts b/web/src/features/ai-gateway/server/router.tsindex 89076e2857..798f492c43 100644--- a/web/src/features/ai-gateway/server/router.ts+++ b/web/src/features/ai-gateway/server/router.ts@@ -28,7 +28,10 @@ import {} from "./apiKey/gatewayApiKeyService";import { requireGatewayEnabledForOrganization } from "./availability";import { getGatewayBaseUrl } from "@/src/features/ai-gateway/fns/gatewayUrls/getGatewayBaseUrl";-import { MAX_TEAM_INVITES } from "@/src/features/ai-gateway/constants/gatewayTeamInvites";+import {+ MAX_MEMBER_SEARCH_LENGTH,+ MAX_TEAM_INVITES,+} from "@/src/features/ai-gateway/constants/gatewayTeamInvites";import { GatewayConfigService } from "./config/gatewayConfigService";import { GatewayTeamService } from "./team/gatewayTeamService";import {@@ -183,6 +186,38 @@ export const aiGatewayRouter = createTRPCRouter({});}),+ getMemberSuggestions: protectedOrganizationProcedure+ .input(+ organizationInput.extend({+ search: z.string().max(MAX_MEMBER_SEARCH_LENGTH),+ excludeEmails: z.array(z.string()).max(MAX_TEAM_INVITES),+ }),+ )+ .query(async ({ input, ctx }) => {+ requireGatewayAdmin({ session: ctx.session, orgId: input.orgId });+ return new GatewayTeamService(ctx.prisma).getMemberSuggestions({+ organizationId: input.orgId,+ currentUserId: ctx.session.user.id,+ search: input.search,+ excludeEmails: input.excludeEmails,+ });+ }),++ getInviteeMembers: protectedOrganizationProcedure+ .input(+ organizationInput.extend({+ emails: z.array(z.email()).max(MAX_TEAM_INVITES),+ }),+ )+ .query(async ({ input, ctx }) => {+ requireGatewayAdmin({ session: ctx.session, orgId: input.orgId });+ return new GatewayTeamService(ctx.prisma).getInviteeMembers({+ organizationId: input.orgId,+ currentUserId: ctx.session.user.id,+ emails: input.emails,+ });+ }),+/** Invites new people as members and optionally tells existing members. */inviteTeam: protectedOrganizationProcedure.input(diff --git a/web/src/features/ai-gateway/server/team/gatewayTeamService.ts b/web/src/features/ai-gateway/server/team/gatewayTeamService.tsindex 1c63f5ec8d..35f921e615 100644--- a/web/src/features/ai-gateway/server/team/gatewayTeamService.ts+++ b/web/src/features/ai-gateway/server/team/gatewayTeamService.ts@@ -18,7 +18,7 @@ import {} from "@/src/features/rbac/server";import type { OrgAuthedContext } from "@/src/server/api/trpc";-const MEMBER_PREVIEW_LIMIT = 4;+const MEMBER_SUGGESTION_LIMIT = 4;const GATEWAY_USER_SCOPE = "gateway:invoke";type GatewayInvitationEmail = Extract<@@ -45,6 +45,11 @@ function isEmailConfigured() {return Boolean(env.SMTP_CONNECTION_URL && env.EMAIL_FROM_ADDRESS);}+/** Addresses are stored lowercase, so lookups and dedupe compare lowercase. */+function normalizeEmails(emails: string[]) {+ return [...new Set(emails.map((email) => email.trim().toLowerCase()))];+}+type GatewayTeamContext = Pick<OrgAuthedContext, "session" | "prisma">;/**@@ -63,19 +68,67 @@ export class GatewayTeamService {organizationId: string;currentUserId: string;}) {- const query = {+ const count = await this.members.countMembersWithScope({organizationId: params.organizationId,scope: GATEWAY_USER_SCOPE,excludeUserId: params.currentUserId,- } as const;- const [count, preview] = await Promise.all([- this.members.countMembersWithScope(query),- this.members.findMembersWithScope({- ...query,- limit: MEMBER_PREVIEW_LIMIT,- }),- ]);- return { isEmailConfigured: isEmailConfigured(), count, preview };+ });+ return { isEmailConfigured: isEmailConfigured(), count };+ }++ /**+ * Members to offer as quick picks: others who can use the gateway, not+ * already picked, optionally narrowed by name or email.+ */+ getMemberSuggestions(params: {+ organizationId: string;+ currentUserId: string;+ search: string;+ excludeEmails: string[];+ }) {+ return this.members.findMembersWithScope({+ organizationId: params.organizationId,+ scope: GATEWAY_USER_SCOPE,+ excludeUserId: params.currentUserId,+ excludeEmails: normalizeEmails(params.excludeEmails),+ search: params.search,+ limit: MEMBER_SUGGESTION_LIMIT,+ });+ }++ /**+ * Pairs each address with its organization member, or null when it would be+ * invited. Mirrors `inviteTeam`: the sender and members whose role can't use+ * the gateway are not notified.+ */+ async getInviteeMembers(params: {+ organizationId: string;+ currentUserId: string;+ emails: string[];+ }) {+ const emails = normalizeEmails(params.emails);+ const members = new Map(+ (+ await this.members.findMembersByEmail({+ organizationId: params.organizationId,+ emails,+ scope: GATEWAY_USER_SCOPE,+ })+ ).map((member) => [member.email.toLowerCase(), member]),+ );+ return emails.map((email) => {+ const member = members.get(email);+ return {+ email,+ member: member+ ? {+ name: member.name,+ isSelf: member.id === params.currentUserId,+ canUseGateway: member.hasScope,+ }+ : null,+ };+ });}async inviteTeam(params: {@@ -105,9 +158,7 @@ export class GatewayTeamService {} as const;const emailJobs: GatewayInvitationEmail[] = [];- const emails = [- ...new Set(params.emails.map((email) => email.trim().toLowerCase())),- ];+ const emails = normalizeEmails(params.emails);const existingMembers = new Map((await this.members.findMembersByEmail({diff --git a/web/src/features/ai-gateway/types/teamInviteMembers.ts b/web/src/features/ai-gateway/types/teamInviteMembers.tsnew file mode 100644index 0000000000..2827db0ee8--- /dev/null+++ b/web/src/features/ai-gateway/types/teamInviteMembers.ts@@ -0,0 +1,12 @@+import type { RouterOutputs } from "@/src/utils/api";++export type TeamInviteMember = NonNullable<+ RouterOutputs["aiGateway"]["getInviteeMembers"][number]["member"]+>;++/**+ * Invitee address (lowercase) to its organization member, or null when the+ * address is not in the organization yet. Addresses missing from the map are+ * still being looked up.+ */+export type TeamInviteMembers = ReadonlyMap<string, TeamInviteMember | null>;diff --git a/web/src/features/rbac/server/organizationMembersService.ts b/web/src/features/rbac/server/organizationMembersService.tsindex 7376e3919a..a96acb9a7e 100644--- a/web/src/features/rbac/server/organizationMembersService.ts+++ b/web/src/features/rbac/server/organizationMembersService.ts@@ -3,11 +3,16 @@ import {type OrganizationScope,} from "@langfuse/shared/rbac";import { type PrismaClient, Role } from "@langfuse/shared/src/db";+import { escapeSqlLikePattern } from "@langfuse/shared/src/server";type MembersWithScopeParams = {organizationId: string;scope: OrganizationScope;excludeUserId?: string;+ /** Lowercase addresses to leave out. */+ excludeEmails?: string[];+ /** Case-insensitive match on name or email. */+ search?: string;};/** Reads organization members by what their organization role allows them to do. */@@ -35,7 +40,7 @@ export class OrganizationMembersService {) {const memberships = await this.prisma.organizationMembership.findMany({where: this.membersWithScopeWhere(params),- orderBy: { createdAt: "asc" },+ orderBy: [{ createdAt: "asc" }, { userId: "asc" }],take: params.limit,select: {user: { select: { id: true, name: true, email: true, image: true } },@@ -86,13 +91,32 @@ export class OrganizationMembersService {const roles = Object.values(Role).filter((role) =>organizationRoleAccessRights[role].includes(params.scope),);+ const search = params.search?.trim()+ ? escapeSqlLikePattern(params.search.trim())+ : undefined;return {orgId: params.organizationId,role: { in: roles },...(params.excludeUserId? { userId: { not: params.excludeUserId } }: {}),- user: { email: { not: null } },+ user: {+ email: {+ not: null,+ ...(params.excludeEmails !== undefined &&+ params.excludeEmails.length > 0+ ? { notIn: params.excludeEmails }+ : {}),+ },+ ...(search+ ? {+ OR: [+ { name: { contains: search, mode: "insensitive" as const } },+ { email: { contains: search, mode: "insensitive" as const } },+ ],+ }+ : {}),+ },};}}