Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat(agent-vault): add a members/available endpoint so the add dialogs offer only unassigned actors

Scott Wilsonbd7b95cb63c9
diff --git a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-membership-router.ts b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-membership-router.ts
index c87991868a..aefbb366a8 100644
--- a/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-membership-router.ts
+++ b/backend/src/ee/routes/v1/agent-vault-routers/agent-vault-membership-router.ts
@@ -13,6 +13,7 @@ import { PostHogEventTypes } from "@app/services/telemetry/telemetry-types";
import { actorContext, auditActorFields } from "./agent-vault-router-fns";
import {
agentVaultListQuery,
+ AgentVaultProductActorSchema,
AgentVaultProductMemberAddSchema,
AgentVaultProductMemberIdsSchema,
AgentVaultProductMemberRefSchema,
@@ -62,6 +63,32 @@ export const registerAgentVaultMembershipRouter = async (server: FastifyZodProvi
})
});
+ server.route({
+ method: "GET",
+ url: "/available",
+ config: { rateLimit: readLimit },
+ schema: {
+ hide: false,
+ operationId: "listAvailableAgentVaultMembers",
+ description: "List the users, groups and machine identities in the organization that can be added to Agent Vault",
+ tags: [ApiDocsTags.AgentVaultMembers],
+ querystring: z.object({
+ actorType: z.nativeEnum(AgentVaultMemberType).optional().describe(AGENT_VAULT.AVAILABLE_MEMBER.actorTypeFilter),
+ ...agentVaultListQuery(AGENT_VAULT.AVAILABLE_MEMBER)
+ }),
+ response: {
+ 200: z.object({ actors: AgentVaultProductActorSchema.array(), totalCount: z.number() })
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN, AuthMode.OAUTH]),
+ handler: async (req) =>
+ server.services.agentVaultMembership.listAvailableProductMembers({
+ projectId: req.internalAgentVaultProjectId,
+ ...req.query,
+ ctx: actorContext(req)
+ })
+ });
+
server.route({
method: "POST",
url: "/",
diff --git a/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.ts b/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.ts
index 9cfca02828..d116653d61 100644
--- a/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.ts
+++ b/backend/src/ee/services/agent-vault-member/agent-vault-member-dal.ts
@@ -42,6 +42,45 @@ const ACTOR_COLUMN: Record<AgentVaultMemberType, "actorUserId" | "actorIdentityI
[AgentVaultMemberType.Group]: "actorGroupId"
};
+type TActorRow = {
+ userId: string | null;
+ machineIdentityId: string | null;
+ groupId: string | null;
+ userUsername: string | null;
+ userEmail: string | null;
+ userFirstName: string | null;
+ userLastName: string | null;
+ machineIdentityName: string | null;
+ machineIdentityProjectId: string | null;
+ machineIdentityOrgId: string | null;
+ groupName: string | null;
+ isOrgMembershipPending: boolean;
+};
+
+const actorOf = (row: TActorRow, projectId: string): TAgentVaultProductActor => {
+ if (row.machineIdentityId) {
+ return {
+ type: AgentVaultMemberType.MachineIdentity,
+ id: row.machineIdentityId,
+ name: row.machineIdentityName ?? "",
+ isManagedByAgentVault: row.machineIdentityProjectId === projectId,
+ orgId: row.machineIdentityOrgId
+ };
+ }
+ if (row.groupId) {
+ return { type: AgentVaultMemberType.Group, id: row.groupId, name: row.groupName ?? "" };
+ }
+ return {
+ type: AgentVaultMemberType.User,
+ id: row.userId ?? "",
+ username: row.userUsername ?? "",
+ email: row.userEmail,
+ firstName: row.userFirstName,
+ lastName: row.userLastName,
+ isOrgMembershipPending: row.isOrgMembershipPending
+ };
+};
+
type TFindProductMembersDTO = {
projectId: string;
orgId: string;
@@ -51,6 +90,8 @@ type TFindProductMembersDTO = {
offset: number;
};
+type TFindAvailableActorsDTO = TFindProductMembersDTO;
+
export const agentVaultMemberDALFactory = (db: TDbClient) => {
const findProductMembers = async (
{ projectId, orgId, actorTypes, search, limit, offset }: TFindProductMembersDTO,
@@ -153,37 +194,13 @@ export const agentVaultMemberDALFactory = (db: TDbClient) => {
isOrgMembershipPending: boolean;
}[];
- const actorOf = (row: (typeof rows)[number]): TAgentVaultProductActor => {
- if (row.machineIdentityId) {
- return {
- type: AgentVaultMemberType.MachineIdentity,
- id: row.machineIdentityId,
- name: row.machineIdentityName ?? "",
- isManagedByAgentVault: row.machineIdentityProjectId === projectId,
- orgId: row.machineIdentityOrgId
- };
- }
- if (row.groupId) {
- return { type: AgentVaultMemberType.Group, id: row.groupId, name: row.groupName ?? "" };
- }
- return {
- type: AgentVaultMemberType.User,
- id: row.userId ?? "",
- username: row.userUsername ?? "",
- email: row.userEmail,
- firstName: row.userFirstName,
- lastName: row.userLastName,
- isOrgMembershipPending: row.isOrgMembershipPending
- };
- };
-
return {
members: rows.map((row) => ({
id: row.id,
role: row.role ?? ProjectMembershipRole.Member,
isActive: row.isActive,
createdAt: row.createdAt,
- actor: actorOf(row)
+ actor: actorOf(row, projectId)
})),
totalCount
};
@@ -192,5 +209,109 @@ export const agentVaultMemberDALFactory = (db: TDbClient) => {
}
};
- return { findProductMembers };
+ // Every rule here mirrors one in assertActorsAreAddable, so the picker cannot offer an actor the add
+ // path would then refuse.
+ const findAvailableActors = async (
+ { projectId, orgId, actorTypes, search, limit, offset }: TFindAvailableActorsDTO,
+ tx?: Knex
+ ): Promise<{ actors: TAgentVaultProductActor[]; totalCount: number }> => {
+ if (!actorTypes.length) return { actors: [], totalCount: 0 };
+
+ try {
+ const conn = tx || db.replicaNode();
+
+ const alreadyMembers = (column: (typeof ACTOR_COLUMN)[AgentVaultMemberType]) =>
+ conn(TableName.Membership)
+ .where(`${TableName.Membership}.scope`, AccessScope.Project)
+ .where(`${TableName.Membership}.scopeProjectId`, projectId)
+ .whereNotNull(`${TableName.Membership}.${column}`)
+ .select(column);
+
+ const applyFilters = (query: Knex.QueryBuilder) => {
+ void query
+ .where(`${TableName.Membership}.scope`, AccessScope.Organization)
+ .where(`${TableName.Membership}.scopeOrgId`, orgId)
+ // A deactivated org member is refused by the add path.
+ .where(`${TableName.Membership}.isActive`, true)
+ .leftJoin(TableName.Users, `${TableName.Membership}.actorUserId`, `${TableName.Users}.id`)
+ .leftJoin(TableName.Identity, `${TableName.Membership}.actorIdentityId`, `${TableName.Identity}.id`)
+ .leftJoin(TableName.Groups, `${TableName.Membership}.actorGroupId`, `${TableName.Groups}.id`);
+
+ void query.where((qb) => {
+ actorTypes.forEach((type) => {
+ void qb.orWhere((typeQb) => {
+ const column = ACTOR_COLUMN[type];
+ void typeQb
+ .whereNotNull(`${TableName.Membership}.${column}`)
+ .whereNotIn(`${TableName.Membership}.${column}`, alreadyMembers(column));
+
+ // A ghost user backs a legacy E2EE project, not a person.
+ if (type === AgentVaultMemberType.User) {
+ void typeQb.where(`${TableName.Users}.isGhost`, false);
+ }
+
+ // A project-scoped identity belongs to one product. Another product's is refused by the add
+ // path, and Agent Vault's own is already a member, since the only way to remove one is to
+ // delete it.
+ if (type === AgentVaultMemberType.MachineIdentity) {
+ void typeQb.whereNull(`${TableName.Identity}.projectId`);
+ }
+ });
+ });
+ });
+
+ if (search) {
+ const term = `%${sanitizeSqlLikeString(search)}%`;
+ void query.where((qb) => {
+ void qb
+ .orWhereILike(`${TableName.Users}.username`, term)
+ .orWhereILike(`${TableName.Users}.email`, term)
+ .orWhereRaw(`CONCAT_WS(' ', ??, ??) ILIKE ?`, [
+ `${TableName.Users}.firstName`,
+ `${TableName.Users}.lastName`,
+ term
+ ])
+ .orWhereILike(`${TableName.Identity}.name`, term)
+ .orWhereILike(`${TableName.Groups}.name`, term);
+ });
+ }
+ return query;
+ };
+
+ const countResult = (await applyFilters(conn(TableName.Membership))
+ .count(`${TableName.Membership}.id as count`)
+ .first()) as { count: string } | undefined;
+ const totalCount = parseInt(countResult?.count || "0", 10);
+
+ const rows = (await applyFilters(conn(TableName.Membership))
+ .select(
+ db.ref("actorUserId").withSchema(TableName.Membership).as("userId"),
+ db.ref("actorIdentityId").withSchema(TableName.Membership).as("machineIdentityId"),
+ db.ref("actorGroupId").withSchema(TableName.Membership).as("groupId"),
+ db.ref("username").withSchema(TableName.Users).as("userUsername"),
+ db.ref("email").withSchema(TableName.Users).as("userEmail"),
+ db.ref("firstName").withSchema(TableName.Users).as("userFirstName"),
+ db.ref("lastName").withSchema(TableName.Users).as("userLastName"),
+ db.ref("name").withSchema(TableName.Identity).as("machineIdentityName"),
+ db.ref("projectId").withSchema(TableName.Identity).as("machineIdentityProjectId"),
+ db.ref("orgId").withSchema(TableName.Identity).as("machineIdentityOrgId"),
+ db.ref("name").withSchema(TableName.Groups).as("groupName"),
+ db.raw(`(??."status" = ?) as "isOrgMembershipPending"`, [TableName.Membership, OrgMembershipStatus.Invited])
+ )
+ .orderByRaw(`COALESCE(??, ??, ??, '') ASC`, [
+ `${TableName.Users}.username`,
+ `${TableName.Identity}.name`,
+ `${TableName.Groups}.name`
+ ])
+ .orderBy(`${TableName.Membership}.id`, "asc")
+ .limit(limit)
+ .offset(offset)) as TActorRow[];
+
+ return { actors: rows.map((row) => actorOf(row, projectId)), totalCount };
+ } catch (error) {
+ throw new DatabaseError({ error, name: "Find available agent vault actors" });
+ }
+ };
+
+ return { findProductMembers, findAvailableActors };
};
diff --git a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts
index 81eac9aac0..72eab7a2f8 100644
--- a/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts
+++ b/backend/src/ee/services/agent-vault-member/agent-vault-membership-service.ts
@@ -36,7 +36,7 @@ import { AgentVaultMemberType } from "../agent-vault/agent-vault-enums";
import { TAgentVaultMemberDALFactory } from "./agent-vault-member-dal";
type TAgentVaultMembershipServiceFactoryDep = {
- agentVaultMemberDAL: Pick<TAgentVaultMemberDALFactory, "findProductMembers">;
+ agentVaultMemberDAL: Pick<TAgentVaultMemberDALFactory, "findProductMembers" | "findAvailableActors">;
membershipDAL: Pick<TMembershipDALFactory, "insertMany" | "find" | "transaction" | "delete">;
identityDAL: Pick<TIdentityDALFactory, "find">;
membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create" | "insertMany" | "delete">;
@@ -213,6 +213,33 @@ export const agentVaultMembershipServiceFactory = ({
});
};
+ const listAvailableProductMembers = async ({
+ projectId,
+ actorType,
+ search,
+ limit,
+ offset,
+ ctx
+ }: TListAgentVaultMembersDTO) => {
+ await checkProductAdmin(projectId, ctx);
+
+ // checkProductAdmin reads hasRole, which does not intersect a delegated token's scopes. The CASL
+ // check below is what narrows an OAuth token holding less than the admin it acts for.
+ const { permission } = await getActorPermission(projectId, ctx);
+ const asked = actorType ? [actorType] : ALL_ACTOR_TYPES;
+ const readable = asked.filter((type) => canReadActorType(permission, type));
+ if (!readable.length) assertCanReadActorType(permission, asked[0]);
+
+ return agentVaultMemberDAL.findAvailableActors({
+ projectId,
+ orgId: ctx.actorOrgId,
+ actorTypes: readable,
+ search,
+ limit,
+ offset
+ });
+ };
+
const assertValidRole = (role: string) => {
if (!VALID_PRODUCT_ROLES.includes(role)) {
throw new BadRequestError({
@@ -591,6 +618,7 @@ export const agentVaultMembershipServiceFactory = ({
};
return {
listProductMembers,
+ listAvailableProductMembers,
addProductMembers,
updateProductMemberRole,
revokeProductMembers
diff --git a/backend/src/lib/api-docs/constants.ts b/backend/src/lib/api-docs/constants.ts
index 5bb96903ae..06c7d35d4e 100644
--- a/backend/src/lib/api-docs/constants.ts
+++ b/backend/src/lib/api-docs/constants.ts
@@ -4320,6 +4320,12 @@ export const AGENT_VAULT = {
limit: "The maximum number of members to return.",
offset: "How many members to skip."
},
+ AVAILABLE_MEMBER: {
+ actorTypeFilter: "List only users, only groups or only machine identities.",
+ search: "Match candidates by name, username or email address.",
+ limit: "The maximum number of candidates to return.",
+ offset: "How many candidates to skip."
+ },
PROXY: {
proxyId: "The ID of the proxy.",
name: "The name of the proxy.",
diff --git a/frontend/src/hooks/api/agentVault/queries.tsx b/frontend/src/hooks/api/agentVault/queries.tsx
index 6d9579fad3..eac1816291 100644
--- a/frontend/src/hooks/api/agentVault/queries.tsx
+++ b/frontend/src/hooks/api/agentVault/queries.tsx
@@ -8,6 +8,7 @@ import {
TAgentVaultAccessBundleDetails,
TAgentVaultAccessBundleListItem,
TAgentVaultMember,
+ TAgentVaultProductActor,
TAgentVaultProductMemberOf,
TAgentVaultProxy,
TAgentVaultSession,
@@ -48,7 +49,11 @@ export const agentVaultKeys = {
) => [...agentVaultKeys.accessBundleMembers(orgId, accessBundleId), params] as const,
members: (orgId: string) => [...agentVaultKeys.all(orgId), "members"] as const,
memberList: (orgId: string, params?: TListAgentVaultMembersDTO) =>
- [...agentVaultKeys.members(orgId), params] as const
+ [...agentVaultKeys.members(orgId), params] as const,
+ // Nested under members() so adding a member invalidates the candidate list too.
+ availableMembers: (orgId: string) => [...agentVaultKeys.members(orgId), "available"] as const,
+ availableMemberList: (orgId: string, params?: TListAgentVaultMembersDTO) =>
+ [...agentVaultKeys.availableMembers(orgId), params] as const
};
export const useListAgentVaultMembers = <T extends AgentVaultMemberType = AgentVaultMemberType>(
@@ -71,6 +76,28 @@ export const useListAgentVaultMembers = <T extends AgentVaultMemberType = AgentV
});
};
+export const useListAvailableAgentVaultMembers = <
+ T extends AgentVaultMemberType = AgentVaultMemberType
+>(
+ params: TListAgentVaultMembersDTO & { actorType?: T } = {},
+ enabled = true
+) => {
+ const { currentOrg } = useOrganization();
+
+ return useQuery({
+ queryKey: agentVaultKeys.availableMemberList(currentOrg.id, params),
+ queryFn: async () => {
+ const { data } = await apiRequest.get<{
+ actors: Extract<TAgentVaultProductActor, { type: T }>[];
+ totalCount: number;
+ }>("/api/v1/agent-vault/members/available", { params });
+ return data;
+ },
+ enabled,
+ placeholderData: (prev) => prev
+ });
+};
+
export const useListAgentVaultAccessBundleMembers = (
accessBundleId: string,
params: Omit<TListAgentVaultMembersDTO, "actorType"> = {}
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/AddGroupDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/AddGroupDialog.tsx
index 8f6d5c812a..1c7a84488b 100644
--- a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/AddGroupDialog.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/AddGroupDialog.tsx
@@ -11,16 +11,22 @@ import {
DialogTitle,
Field,
FieldContent,
+ FieldDescription,
FieldLabel,
FilterableSelect
} from "@app/components/v3";
-import { useOrganization } from "@app/context";
-import { useGetOrganizationGroups } from "@app/hooks/api";
-import { useAddAgentVaultMembers } from "@app/hooks/api/agentVault";
+import { useDebounce } from "@app/hooks";
+import {
+ useAddAgentVaultMembers,
+ useListAvailableAgentVaultMembers
+} from "@app/hooks/api/agentVault";
+import { AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
import { ProductRoleField } from "./ProductRoleField";
+const CANDIDATE_LIMIT = 50;
+
type TOption = { value: string; label: string };
type Props = {
@@ -29,18 +35,36 @@ type Props = {
};
export const AddGroupDialog = ({ isOpen, onOpenChange }: Props) => {
- const { currentOrg } = useOrganization();
- const { data: orgGroups = [] } = useGetOrganizationGroups(currentOrg.id);
const addMembers = useAddAgentVaultMembers();
const [group, setGroup] = useState<TOption | null>(null);
const [role, setRole] = useState<string>(ProjectMembershipRole.Member);
+ const [search, setSearch] = useState("");
+ const [debouncedSearch] = useDebounce(search);
+
+ const { data, isFetching } = useListAvailableAgentVaultMembers(
+ {
+ actorType: AgentVaultMemberType.Group,
+ search: debouncedSearch.trim() || undefined,
+ limit: CANDIDATE_LIMIT
+ },
+ isOpen
+ );
- const options = useMemo(
- () => orgGroups.map((orgGroup) => ({ value: orgGroup.id, label: orgGroup.name })),
- [orgGroups]
+ const options = useMemo<TOption[]>(
+ () => (data?.actors ?? []).map((actor) => ({ value: actor.id, label: actor.name })),
+ [data]
);
+ const isListTruncated = (data?.totalCount ?? 0) > options.length;
+
+ const handleClose = () => {
+ setGroup(null);
+ setRole(ProjectMembershipRole.Member);
+ setSearch("");
+ onOpenChange(false);
+ };
+
const handleAdd = async () => {
try {
if (!group) return;
@@ -51,15 +75,23 @@ export const AddGroupDialog = ({ isOpen, onOpenChange }: Props) => {
: `"${group.label}" added`,
type: skipped.length ? "info" : "success"
});
- setGroup(null);
- onOpenChange(false);
+ handleClose();
} catch {
// A failed request returns a 4xx that the global request handler surfaces as a toast
}
};
return (
- <Dialog open={isOpen} onOpenChange={onOpenChange}>
+ <Dialog
+ open={isOpen}
+ onOpenChange={(open) => {
+ if (!open) {
+ handleClose();
+ return;
+ }
+ onOpenChange(open);
+ }}
+ >
<DialogContent>
<DialogHeader>
<DialogTitle>Add Group</DialogTitle>
@@ -78,7 +110,22 @@ export const AddGroupDialog = ({ isOpen, onOpenChange }: Props) => {
placeholder="Search groups..."
getOptionLabel={(option) => option.label}
getOptionValue={(option) => option.value}
+ isLoading={isFetching || search !== debouncedSearch}
+ onInputChange={(value, actionMeta) => {
+ if (actionMeta.action === "input-change") setSearch(value);
+ }}
+ filterOption={() => true}
+ noOptionsMessage={() =>
+ search
+ ? "No group matches that is not already a member"
+ : "Every group in the organization is already a member"
+ }
/>
+ {isListTruncated && (
+ <FieldDescription>
+ Search by name to find groups that are not listed.
+ </FieldDescription>
+ )}
</FieldContent>
</Field>
@@ -90,7 +137,7 @@ export const AddGroupDialog = ({ isOpen, onOpenChange }: Props) => {
</Field>
<DialogFooter>
- <Button variant="outline" onClick={() => onOpenChange(false)}>
+ <Button variant="outline" onClick={handleClose}>
Cancel
</Button>
<Button
diff --git a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/InviteMembersDialog.tsx b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/InviteMembersDialog.tsx
index 2337ac153b..20e5e125db 100644
--- a/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/InviteMembersDialog.tsx
+++ b/frontend/src/pages/agent-vault/AgentVaultAccessControlPage/components/InviteMembersDialog.tsx
@@ -14,18 +14,26 @@ import {
DialogTitle,
Field,
FieldContent,
+ FieldDescription,
FieldLabel,
FilterableSelect
} from "@app/components/v3";
import { useOrganization } from "@app/context";
+import { useDebounce } from "@app/hooks";
import { useGetOrgUsers } from "@app/hooks/api";
-import { useAddAgentVaultMembers, useListAgentVaultMembers } from "@app/hooks/api/agentVault";
+import {
+ useAddAgentVaultMembers,
+ useListAgentVaultMembers,
+ useListAvailableAgentVaultMembers
+} from "@app/hooks/api/agentVault";
import { AgentVaultMemberType } from "@app/hooks/api/agentVault/enums";
import { ProjectMembershipRole } from "@app/hooks/api/roles/types";
import { getRequesterStatus } from "@app/lib/fn/requesterStatus";
import { ProductRoleField } from "./ProductRoleField";
+const CANDIDATE_LIMIT = 50;
+
type TCandidate = { value: string; label: string; email: string };
type Props = {
@@ -35,7 +43,6 @@ type Props = {
export const InviteMembersDialog = ({ isOpen, onOpenChange }: Props) => {
const { currentOrg } = useOrganization();
- const { data: orgUsers = [] } = useGetOrgUsers(currentOrg.id);
const addMembers = useAddAgentVaultMembers();
const navigate = useNavigate({ from: "" });
const requesterEmail = useSearch({
@@ -52,14 +59,31 @@ export const InviteMembersDialog = ({ isOpen, onOpenChange }: Props) => {
const [selected, setSelected] = useState<TCandidate[]>([]);
const [role, setRole] = useState<string>(ProjectMembershipRole.Member);
+ const [search, setSearch] = useState("");
+ const [debouncedSearch] = useDebounce(search);
- const candidates = useMemo(() => {
- return orgUsers.map((orgUser) => {
- const name = `${orgUser.user.firstName ?? ""} ${orgUser.user.lastName ?? ""}`.trim();
- const email = orgUser.user.email || orgUser.user.username || "";
- return { value: orgUser.user.id, label: name || email, email };
+ const { data: availableData, isFetching: isCandidatesFetching } =
+ useListAvailableAgentVaultMembers(
+ {
+ actorType: AgentVaultMemberType.User,
+ search: debouncedSearch.trim() || undefined,
+ limit: CANDIDATE_LIMIT
+ },
+ isOpen
+ );
+ // Only the ?requesterEmail= deep link needs the whole roster: it resolves an address the candidate
+ // list legitimately may not hold, because that user may already be a member.
+ const { data: orgUsers = [] } = useGetOrgUsers(requesterEmail ? currentOrg.id : "");
+
+ const candidates = useMemo<TCandidate[]>(() => {
+ return (availableData?.actors ?? []).map((actor) => {
+ const name = `${actor.firstName ?? ""} ${actor.lastName ?? ""}`.trim();
+ const email = actor.email || actor.username || "";
+ return { value: actor.id, label: name || email, email };
});
- }, [orgUsers]);
+ }, [availableData]);
+
+ const isCandidateListTruncated = (availableData?.totalCount ?? 0) > candidates.length;
const memberUsernames = useMemo(
() => new Set((requesterMatch?.members ?? []).map((member) => member.actor.username)),
@@ -100,6 +124,7 @@ export const InviteMembersDialog = ({ isOpen, onOpenChange }: Props) => {
const handleClose = () => {
setSelected([]);
setRole(ProjectMembershipRole.Member);
+ setSearch("");
clearRequesterEmail();
onOpenChange(false);
};
@@ -153,7 +178,23 @@ export const InviteMembersDialog = ({ isOpen, onOpenChange }: Props) => {
placeholder="Search by name or email..."
getOptionLabel={(option) => option.label}
getOptionValue={(option) => option.value}
+ isLoading={isCandidatesFetching || search !== debouncedSearch}
+ onInputChange={(value, actionMeta) => {
+ if (actionMeta.action === "input-change") setSearch(value);
+ }}
+ // The server already matched the term, against fields the label does not show.
+ filterOption={() => true}
+ noOptionsMessage={() =>
+ search
+ ? "No one matches who is not already a member"
+ : "Everyone in the organization is already a member"
+ }
/>
+ {isCandidateListTruncated && (
+ <FieldDescription>
+ Search by name or email to find users that are not listed.
+ </FieldDescription>
+ )}
</FieldContent>
</Field>