diff --git a/docs/content/docs/en/reference/api/clients.mdx b/docs/content/docs/en/reference/api/clients.mdx
index 86194e023..1b2c360cd 100644
--- a/docs/content/docs/en/reference/api/clients.mdx
+++ b/docs/content/docs/en/reference/api/clients.mdx
@@ -20,6 +20,9 @@ _openapi:
the eligible IDs that match the given search and group for the chosen
source and targets.
url: '#list-up-to-100-clients-for-the-inbound-attachment-picker-counts-distinguish-filtered-rows-and-all-eligible-clients-a-freeze-request-returns-only-the-eligible-count-maximum-id-and-a-scope-token-covering-the-eligible-ids-that-match-the-given-search-and-group-for-the-chosen-source-and-targets'
+ - depth: 2
+ title: Return up to 50 client emails for the routing rule user picker.
+ url: '#return-up-to-50-client-emails-for-the-routing-rule-user-picker'
- depth: 2
title: 'Filter, sort, and paginate clients on the server. Each item is a slim
row (no uuid/password/auth/flow/security/reverse/tgId) so the clients
@@ -412,6 +415,8 @@ _openapi:
the eligible IDs that match the given search and group for the chosen
source and targets.
id: list-up-to-100-clients-for-the-inbound-attachment-picker-counts-distinguish-filtered-rows-and-all-eligible-clients-a-freeze-request-returns-only-the-eligible-count-maximum-id-and-a-scope-token-covering-the-eligible-ids-that-match-the-given-search-and-group-for-the-chosen-source-and-targets
+ - content: Return up to 50 client emails for the routing rule user picker.
+ id: return-up-to-50-client-emails-for-the-routing-rule-user-picker
- content: 'Filter, sort, and paginate clients on the server. Each item is a slim
row (no uuid/password/auth/flow/security/reverse/tgId) so the clients
page can ship 25-ish rows in a few KB instead of the full table. The
@@ -1031,7 +1036,7 @@ export default function Layout(props) {
return (
<>
{props.children}
-
+
>
);
}
\ No newline at end of file
diff --git a/docs/public/openapi.json b/docs/public/openapi.json
index 6774178eb..b42ed07e1 100644
--- a/docs/public/openapi.json
+++ b/docs/public/openapi.json
@@ -2611,6 +2611,24 @@
],
"type": "object"
},
+ "ClientEmailSuggestions": {
+ "properties": {
+ "emails": {
+ "example": [
+ "alice@example.com",
+ "bob@example.com"
+ ],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "emails"
+ ],
+ "type": "object"
+ },
"ClientInbound": {
"properties": {
"clientId": {
@@ -10645,6 +10663,58 @@
}
}
},
+ "/panel/api/clients/userSuggestions": {
+ "get": {
+ "tags": [
+ "Clients"
+ ],
+ "summary": "Return up to 50 client emails for the routing rule user picker.",
+ "operationId": "get_panel_api_clients_userSuggestions",
+ "parameters": [
+ {
+ "name": "search",
+ "in": "query",
+ "required": false,
+ "description": "Optional case-insensitive substring. Percent and underscore are literal.",
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "success": {
+ "type": "boolean"
+ },
+ "msg": {
+ "type": "string"
+ },
+ "obj": {
+ "$ref": "#/components/schemas/ClientEmailSuggestions"
+ }
+ }
+ },
+ "example": {
+ "success": true,
+ "obj": {
+ "emails": [
+ "alice@example.com",
+ "bob@example.com"
+ ]
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/panel/api/clients/list/paged": {
"get": {
"tags": [
diff --git a/frontend/public/openapi.json b/frontend/public/openapi.json
index 6774178eb..b42ed07e1 100644
--- a/frontend/public/openapi.json
+++ b/frontend/public/openapi.json
@@ -2611,6 +2611,24 @@
],
"type": "object"
},
+ "ClientEmailSuggestions": {
+ "properties": {
+ "emails": {
+ "example": [
+ "alice@example.com",
+ "bob@example.com"
+ ],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "emails"
+ ],
+ "type": "object"
+ },
"ClientInbound": {
"properties": {
"clientId": {
@@ -10645,6 +10663,58 @@
}
}
},
+ "/panel/api/clients/userSuggestions": {
+ "get": {
+ "tags": [
+ "Clients"
+ ],
+ "summary": "Return up to 50 client emails for the routing rule user picker.",
+ "operationId": "get_panel_api_clients_userSuggestions",
+ "parameters": [
+ {
+ "name": "search",
+ "in": "query",
+ "required": false,
+ "description": "Optional case-insensitive substring. Percent and underscore are literal.",
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Successful response",
+ "content": {
+ "application/json": {
+ "schema": {
+ "type": "object",
+ "properties": {
+ "success": {
+ "type": "boolean"
+ },
+ "msg": {
+ "type": "string"
+ },
+ "obj": {
+ "$ref": "#/components/schemas/ClientEmailSuggestions"
+ }
+ }
+ },
+ "example": {
+ "success": true,
+ "obj": {
+ "emails": [
+ "alice@example.com",
+ "bob@example.com"
+ ]
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ },
"/panel/api/clients/list/paged": {
"get": {
"tags": [
diff --git a/frontend/src/api/queries/useClientOptions.ts b/frontend/src/api/queries/useClientOptions.ts
index 26968a724..861d9f2d3 100644
--- a/frontend/src/api/queries/useClientOptions.ts
+++ b/frontend/src/api/queries/useClientOptions.ts
@@ -1,33 +1,49 @@
-import { useQuery } from '@tanstack/react-query';
-import { z } from 'zod';
+import { skipToken, useQuery } from '@tanstack/react-query';
import { HttpUtil } from '@/utils';
import { parseMsg } from '@/utils/zodValidate';
import { keys } from '@/api/queryKeys';
-import { ClientRecordSchema, type ClientRecord } from '@/schemas/client';
+import { ClientEmailSuggestionsSchema } from '@/generated/zod';
-const ClientRecordListSchema = z
- .array(ClientRecordSchema)
- .nullable()
- .transform((value) => value ?? []);
+const suggestionsSchema = ClientEmailSuggestionsSchema.extend({
+ emails: ClientEmailSuggestionsSchema.shape.emails.max(50),
+});
-async function fetchClients(): Promise {
- const msg = await HttpUtil.get('/panel/api/clients/list', undefined, { silent: true });
- if (!msg?.success) throw new Error(msg?.msg || 'Failed to load clients');
- const validated = parseMsg(msg, ClientRecordListSchema, 'clients/list');
- return validated.obj ?? [];
-}
-
-export function useClientOptions(enabled = true) {
- return useQuery({
- queryKey: keys.clients.all(),
- queryFn: fetchClients,
- enabled,
- staleTime: 30_000,
- select: (clients) =>
- clients
- .map((client) => client.email.trim())
- .filter(Boolean)
- .sort((a, b) => a.localeCompare(b)),
+function waitForTyping(signal: AbortSignal) {
+ return new Promise((resolve, reject) => {
+ signal.throwIfAborted();
+ function cancel() {
+ clearTimeout(timer);
+ reject(signal.reason);
+ }
+ const timer = setTimeout(() => {
+ signal.removeEventListener('abort', cancel);
+ resolve();
+ }, 250);
+ signal.addEventListener('abort', cancel, { once: true });
+ });
+}
+
+async function fetchClientOptions(search: string, signal: AbortSignal): Promise {
+ if (search) await waitForTyping(signal);
+ const msg = await HttpUtil.get(
+ '/panel/api/clients/userSuggestions',
+ { search },
+ { signal, silent: true },
+ );
+ if (!msg.success || msg.obj == null)
+ throw new Error(msg.msg || 'Failed to load user suggestions');
+ return (
+ parseMsg(msg, suggestionsSchema, 'clients/userSuggestions', { strict: true }).obj?.emails ?? []
+ );
+}
+
+export function useClientOptions(search: string | null) {
+ return useQuery({
+ queryKey: keys.clients.userSuggestions(search),
+ queryFn: search === null ? skipToken : ({ signal }) => fetchClientOptions(search, signal),
+ staleTime: 30_000,
+ gcTime: 60_000,
+ retry: false,
});
}
diff --git a/frontend/src/api/queryKeys.ts b/frontend/src/api/queryKeys.ts
index e8448b04b..be9441760 100644
--- a/frontend/src/api/queryKeys.ts
+++ b/frontend/src/api/queryKeys.ts
@@ -37,6 +37,7 @@ export const keys = {
root: () => ['clients'] as const,
list: (params: unknown) => ['clients', 'list', params] as const,
all: () => ['clients', 'all'] as const,
+ userSuggestions: (search: string | null) => ['clients', 'userSuggestions', search] as const,
onlines: () => ['clients', 'onlines'] as const,
onlinesByGuid: () => ['clients', 'onlinesByGuid'] as const,
activeInbounds: () => ['clients', 'activeInbounds'] as const,
diff --git a/frontend/src/generated/examples.ts b/frontend/src/generated/examples.ts
index 1a2cd19d9..0621685d8 100644
--- a/frontend/src/generated/examples.ts
+++ b/frontend/src/generated/examples.ts
@@ -688,6 +688,12 @@ export const EXAMPLES: Record = {
"oldValue": "10737418240",
"source": "panel"
},
+ "ClientEmailSuggestions": {
+ "emails": [
+ "alice@example.com",
+ "bob@example.com"
+ ]
+ },
"ClientInbound": {
"clientId": 0,
"createdAt": 0,
diff --git a/frontend/src/generated/schemas.ts b/frontend/src/generated/schemas.ts
index 2b7872427..a66b9e3e6 100644
--- a/frontend/src/generated/schemas.ts
+++ b/frontend/src/generated/schemas.ts
@@ -2585,6 +2585,24 @@ export const SCHEMAS: Record = {
],
"type": "object"
},
+ "ClientEmailSuggestions": {
+ "properties": {
+ "emails": {
+ "example": [
+ "alice@example.com",
+ "bob@example.com"
+ ],
+ "items": {
+ "type": "string"
+ },
+ "type": "array"
+ }
+ },
+ "required": [
+ "emails"
+ ],
+ "type": "object"
+ },
"ClientInbound": {
"properties": {
"clientId": {
diff --git a/frontend/src/generated/types.ts b/frontend/src/generated/types.ts
index e97cad010..c636321ae 100644
--- a/frontend/src/generated/types.ts
+++ b/frontend/src/generated/types.ts
@@ -610,6 +610,10 @@ export interface ClientChangeLog {
source: string;
}
+export interface ClientEmailSuggestions {
+ emails: string[];
+}
+
export interface ClientInbound {
clientId: number;
createdAt: number;
diff --git a/frontend/src/generated/zod.ts b/frontend/src/generated/zod.ts
index cab871448..26d90be55 100644
--- a/frontend/src/generated/zod.ts
+++ b/frontend/src/generated/zod.ts
@@ -645,6 +645,11 @@ export const ClientChangeLogSchema = z.object({
});
export type ClientChangeLog = z.infer;
+export const ClientEmailSuggestionsSchema = z.object({
+ emails: z.array(z.string()),
+});
+export type ClientEmailSuggestions = z.infer;
+
export const ClientInboundSchema = z.object({
clientId: z.number().int(),
createdAt: z.number().int(),
diff --git a/frontend/src/pages/api-docs/endpoints.ts b/frontend/src/pages/api-docs/endpoints.ts
index 5dcc424f0..19b2663d6 100644
--- a/frontend/src/pages/api-docs/endpoints.ts
+++ b/frontend/src/pages/api-docs/endpoints.ts
@@ -1123,6 +1123,21 @@ export const sections: readonly Section[] = [
],
responseSchema: 'AttachCandidatePage',
},
+ {
+ method: 'GET',
+ path: '/panel/api/clients/userSuggestions',
+ summary: 'Return up to 50 client emails for the routing rule user picker.',
+ params: [
+ {
+ name: 'search',
+ in: 'query',
+ type: 'string',
+ desc: 'Optional case-insensitive substring. Percent and underscore are literal.',
+ optional: true,
+ },
+ ],
+ responseSchema: 'ClientEmailSuggestions',
+ },
{
method: 'GET',
path: '/panel/api/clients/list/paged',
diff --git a/frontend/src/pages/xray/routing/RuleFormModal.stories.tsx b/frontend/src/pages/xray/routing/RuleFormModal.stories.tsx
new file mode 100644
index 000000000..c07972ea3
--- /dev/null
+++ b/frontend/src/pages/xray/routing/RuleFormModal.stories.tsx
@@ -0,0 +1,134 @@
+import type { Meta, StoryObj } from '@storybook/react-vite';
+import { expect, fn, waitFor, within } from 'storybook/test';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { useState } from 'react';
+import type { ComponentProps, ReactNode } from 'react';
+import { ThemeProvider } from '@/hooks/useTheme';
+import { AntdRootConfig } from '@/i18n/AntdRootConfig';
+
+import { HttpUtil, Msg } from '@/utils';
+import RuleFormModal from './RuleFormModal';
+
+function QueryFixture({ children }: { children: ReactNode }) {
+ const [client] = useState(
+ () => new QueryClient({ defaultOptions: { queries: { retry: false } } }),
+ );
+ return (
+
+
+ {children}
+
+
+ );
+}
+
+function RoutingRuleFixture(props: ComponentProps) {
+ const [open, setOpen] = useState(props.open);
+ return (
+ {
+ props.onClose();
+ setOpen(false);
+ }}
+ onConfirm={(rule) => {
+ props.onConfirm(rule);
+ setOpen(false);
+ }}
+ />
+ );
+}
+
+const meta = {
+ title: 'Xray/Routing Rule',
+ component: RuleFormModal,
+ render: (args) => ,
+ decorators: [
+ (Story) => (
+
+
+
+ ),
+ ],
+ args: {
+ open: true,
+ rule: { user: ['existing@test'], outboundTag: 'direct' },
+ inboundTags: [],
+ outboundTags: ['direct'],
+ balancerTags: [],
+ onClose: fn(),
+ onConfirm: fn(),
+ },
+} satisfies Meta;
+export default meta;
+type Story = StoryObj;
+
+function largeCatalog(size: number): Story {
+ const requests: Array<{ path: string; search: string; count: number }> = [];
+ const target = `client-${size}@test`;
+ const legacyList = '/panel/api/clients/list';
+ const suggestionsPath = '/panel/api/clients/userSuggestions';
+
+ return {
+ beforeEach: () => {
+ requests.length = 0;
+ const get = HttpUtil.get;
+ const fixture = Array.from({ length: size }, (_, index) => `client-${index + 1}@test`);
+ HttpUtil.get = async (path: string, params?: unknown) => {
+ if (path === legacyList) {
+ requests.push({ path, search: '', count: size });
+ return new Msg(true, '', fixture.map((email) => ({ email })) as T);
+ }
+ if (path === suggestionsPath) {
+ const { search } = params as { search: string };
+ const emails = fixture.filter((email) => email.includes(search)).slice(0, 50);
+ requests.push({ path, search, count: emails.length });
+ return new Msg(true, '', { emails } as T);
+ }
+ return new Msg(true, '', [] as T);
+ };
+ return () => {
+ HttpUtil.get = get;
+ };
+ },
+ play: async ({ args, canvasElement, userEvent }) => {
+ const screen = within(canvasElement.ownerDocument.body);
+ const dialog = await screen.findByRole('dialog');
+ const picker = within(dialog).getByRole('combobox', { name: 'User' });
+ await expect(requests).toEqual([]);
+ await userEvent.click(picker);
+ await waitFor(() =>
+ expect(requests).toEqual([{ path: suggestionsPath, search: '', count: 50 }]),
+ );
+
+ const search = target.replace('client-', '');
+ await userEvent.type(picker, search);
+ const option = await screen.findByText(target, {
+ selector: '.ant-select-item-option-content',
+ });
+ await userEvent.click(option);
+ await userEvent.type(picker, 'manual@test,existing@test,');
+ await expect(screen.getByRole('button', { name: 'Remove existing@test' })).toBeVisible();
+ await expect(screen.getByRole('button', { name: `Remove ${target}` })).toBeVisible();
+ await userEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
+ await expect(args.onConfirm).toHaveBeenCalledWith(
+ expect.objectContaining({
+ user: ['existing@test', target, 'manual@test'],
+ outboundTag: 'direct',
+ }),
+ );
+ await expect(requests.filter(({ search }) => search)).toEqual([
+ { path: suggestionsPath, search, count: 1 },
+ ]);
+ await expect(
+ requests.every(({ path, count }) => path === suggestionsPath && count <= 50),
+ ).toBe(true);
+ await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
+ },
+ };
+}
+
+export const Thousand = largeCatalog(1_000);
+export const TenThousand = largeCatalog(10_000);
+export const FiftyThousand = largeCatalog(50_000);
diff --git a/frontend/src/pages/xray/routing/RuleFormModal.tsx b/frontend/src/pages/xray/routing/RuleFormModal.tsx
index 00881894e..a85b8ef0e 100644
--- a/frontend/src/pages/xray/routing/RuleFormModal.tsx
+++ b/frontend/src/pages/xray/routing/RuleFormModal.tsx
@@ -1,4 +1,4 @@
-import { useEffect, useMemo } from 'react';
+import { useEffect, useMemo, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Form, Input, Modal, Select, Space, Switch } from 'antd';
import { PlusOutlined, MinusOutlined } from '@ant-design/icons';
@@ -71,6 +71,73 @@ function csv(value: string): string[] {
.filter(Boolean);
}
+function RoutingUserField({ active }: { active: boolean }) {
+ const { t } = useTranslation();
+ const [pickerOpen, setPickerOpen] = useState(false);
+ const [search, setSearch] = useState('');
+ const { data, isFetching, isError } = useClientOptions(
+ active && pickerOpen ? search.trim() : null,
+ );
+ const user = useWatch({ name: 'user' }) ?? '';
+ const selectedUsers = useMemo(() => csv(user), [user]);
+ const options = useMemo(
+ () =>
+ [...new Set([...(data ?? []), ...selectedUsers])].map((email) => ({
+ value: email,
+ label: email,
+ })),
+ [data, selectedUsers],
+ );
+ const status = isFetching
+ ? t('loading')
+ : isError
+ ? t('pages.xray.ruleForm.userLoadError')
+ : !data?.length
+ ? t('pages.xray.ruleForm.userEmpty')
+ : undefined;
+ const showStatusInMenu = Boolean(search || options.length);
+
+ return (
+ csv(typeof value === 'string' ? value : ''),
+ output: (value) => (Array.isArray(value) ? value.join(',') : ''),
+ }}
+ onAfterChange={() => setSearch('')}
+ >
+
+ );
+}
+
export default function RuleFormModal({
open,
rule,
@@ -86,21 +153,6 @@ export default function RuleFormModal({
const { data: inboundOptions } = useInboundOptions();
const remarkByTag = useMemo(() => buildRemarkByTag(inboundOptions || []), [inboundOptions]);
- const {
- data: clientEmails = [],
- isFetching: clientsLoading,
- isError: clientsError,
- } = useClientOptions(open);
- const user = useWatch({ control: methods.control, name: 'user' }) ?? '';
- const selectedUsers = useMemo(() => csv(user), [user]);
- const userOptions = useMemo(
- () =>
- [...new Set([...clientEmails, ...selectedUsers])].map((email) => ({
- value: email,
- label: email,
- })),
- [clientEmails, selectedUsers],
- );
useEffect(() => {
if (!open) return;
@@ -286,33 +338,7 @@ export default function RuleFormModal({
- csv(typeof value === 'string' ? value : ''),
- output: (value) => (Array.isArray(value) ? value.join(',') : ''),
- }}
- >
-
-
+
,
+ );
+ const input = screen.getByRole('combobox', { name: 'User' });
+ return { input, onConfirm };
+}
+
+afterEach(() => vi.restoreAllMocks());
+
+it('defers requests until the picker opens, debounces, and discards a late response', async () => {
+ let respondToOldSearch: ((value: Msg) => void) | undefined;
+ const get = vi.spyOn(HttpUtil, 'get').mockImplementation(async (url, params) => {
+ if (url !== suggestionsURL) return new Msg(true, '', []);
+ const { search } = params as { search: string };
+ if (search === 'old') return new Promise((resolve) => (respondToOldSearch = resolve));
+ return new Msg(true, '', { emails: search === 'new' ? ['new-user@test'] : [] });
+ });
+ const requests = () => get.mock.calls.filter(([url]) => url.startsWith('/panel/api/clients/'));
+
+ const { input } = renderRule();
+ expect(requests()).toEqual([]);
+ fireEvent.change(input, { target: { value: 'old' } });
+ await waitFor(() => expect(respondToOldSearch).toBeTypeOf('function'));
+ await act(async () => {
+ fireEvent.change(input, { target: { value: 'n' } });
+ fireEvent.change(input, { target: { value: 'ne' } });
+ fireEvent.change(input, { target: { value: 'new' } });
+ });
+ expect(requests()).toHaveLength(1);
+ expect(requests()[0][2]?.signal?.aborted).toBe(true);
+ await screen.findByRole('option', { name: 'new-user@test' });
+ await act(async () => {
+ respondToOldSearch?.(new Msg(true, '', { emails: ['old-user@test'] }));
+ });
+ expect(screen.queryByRole('option', { name: 'old-user@test' })).toBeNull();
+ expect(requests().map(([, params]) => params)).toEqual([{ search: 'old' }, { search: 'new' }]);
+});
+
+it('preserves selected users and saves comma-delimited tags even when suggestions fail', async () => {
+ vi.spyOn(HttpUtil, 'get').mockImplementation(async (url) =>
+ url === suggestionsURL ? new Msg(false, 'offline') : new Msg(true, '', []),
+ );
+ const { input, onConfirm } = renderRule({ user: 'saved@test,remove@test' });
+ fireEvent.change(input, { target: { value: 'typed' } });
+ await screen.findByText('Could not load users');
+ expect(screen.getByRole('button', { name: 'Remove saved@test' })).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'Remove remove@test' }));
+ fireEvent.change(input, { target: { value: 'manual@test,saved@test,manual@test,' } });
+ fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));
+ expect(onConfirm).toHaveBeenCalledWith(
+ expect.objectContaining({ user: ['saved@test', 'manual@test'] }),
+ );
+});
diff --git a/frontend/src/test/rule-form-preserve-fields.test.tsx b/frontend/src/test/rule-form-preserve-fields.test.tsx
index 07656a5e4..59370f277 100644
--- a/frontend/src/test/rule-form-preserve-fields.test.tsx
+++ b/frontend/src/test/rule-form-preserve-fields.test.tsx
@@ -3,10 +3,18 @@ import { fireEvent, screen, waitFor } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import RuleFormModal from '@/pages/xray/routing/RuleFormModal';
-import { keys } from '@/api/queryKeys';
import { HttpUtil, Msg } from '@/utils';
-import { chooseSelectOption, renderWithProviders } from './test-utils';
+import { renderWithProviders } from './test-utils';
+
+function mockUserSuggestions(...emails: string[]) {
+ return vi
+ .spyOn(HttpUtil, 'get')
+ .mockImplementation(
+ async (path) =>
+ new Msg(true, '', path === '/panel/api/clients/userSuggestions' ? { emails } : []),
+ );
+}
describe('RuleFormModal edit preserves unsurfaced fields', () => {
afterEach(() => vi.restoreAllMocks());
@@ -37,12 +45,7 @@ describe('RuleFormModal edit preserves unsurfaced fields', () => {
});
it('selects existing clients for the user criterion', async () => {
- vi.spyOn(HttpUtil, 'get').mockResolvedValue(
- new Msg(true, '', [
- { id: 1, email: 'alice@example.com' },
- { id: 2, email: 'bob@example.com' },
- ]),
- );
+ const get = mockUserSuggestions('alice@example.com', 'bob@example.com');
const onConfirm = vi.fn();
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
@@ -59,16 +62,19 @@ describe('RuleFormModal edit preserves unsurfaced fields', () => {
{ queryClient },
);
- await waitFor(() =>
- expect(HttpUtil.get).toHaveBeenCalledWith('/panel/api/clients/list', undefined, {
- silent: true,
- }),
- );
- await waitFor(() => expect(queryClient.getQueryData(keys.clients.all())).toHaveLength(2));
- const userField = screen.getByLabelText('User');
+ const userField = screen.getByRole('combobox', { name: 'User' });
expect(screen.getByText('Select users')).toBeTruthy();
- chooseSelectOption(userField.id, 'alice@example.com');
- chooseSelectOption(userField.id, 'bob@example.com');
+ fireEvent.mouseDown(userField);
+ for (const email of ['alice@example.com', 'bob@example.com']) {
+ fireEvent.click(
+ await screen.findByText(email, { selector: '.ant-select-item-option-content' }),
+ );
+ }
+ expect(get).toHaveBeenCalledWith(
+ '/panel/api/clients/userSuggestions',
+ { search: '' },
+ expect.objectContaining({ silent: true }),
+ );
fireEvent.click(screen.getByRole('button', { name: 'Create' }));
expect(onConfirm).toHaveBeenCalledWith(
@@ -77,9 +83,7 @@ describe('RuleFormModal edit preserves unsurfaced fields', () => {
});
it('preserves a saved user that is no longer in the client list', async () => {
- vi.spyOn(HttpUtil, 'get').mockResolvedValue(
- new Msg(true, '', [{ id: 1, email: 'alice@example.com' }]),
- );
+ mockUserSuggestions('alice@example.com');
const onConfirm = vi.fn();
renderWithProviders(
@@ -103,9 +107,7 @@ describe('RuleFormModal edit preserves unsurfaced fields', () => {
});
it('accepts a custom user identifier that is not a client record', async () => {
- vi.spyOn(HttpUtil, 'get').mockResolvedValue(
- new Msg(true, '', [{ id: 1, email: 'alice@example.com' }]),
- );
+ mockUserSuggestions('alice@example.com');
const onConfirm = vi.fn();
renderWithProviders(
diff --git a/internal/web/controller/client.go b/internal/web/controller/client.go
index b2b5c43d7..2c3534df8 100644
--- a/internal/web/controller/client.go
+++ b/internal/web/controller/client.go
@@ -54,6 +54,7 @@ func NewClientController(g *gin.RouterGroup) *ClientController {
func (a *ClientController) initRouter(g *gin.RouterGroup) {
g.GET("/list", a.list)
g.GET("/list/paged", a.listPaged)
+ g.GET("/userSuggestions", a.userSuggestions)
g.GET("/attachCandidates", a.attachCandidates)
g.GET("/get", a.get)
g.GET("/get/:email", a.get)
@@ -155,6 +156,11 @@ func (a *ClientController) attachCandidates(c *gin.Context) {
jsonObj(c, result, nil)
}
+func (a *ClientController) userSuggestions(c *gin.Context) {
+ result, err := a.clientService.ListUserSuggestions(c.Request.Context(), c.Query("search"))
+ jsonObj(c, result, err)
+}
+
func (a *ClientController) buildClientPayload(rec *model.ClientRecord) (gin.H, error) {
inboundIds, err := a.clientService.GetInboundIdsForRecord(rec.Id)
if err != nil {
diff --git a/internal/web/controller/client_user_suggestions_test.go b/internal/web/controller/client_user_suggestions_test.go
new file mode 100644
index 000000000..ce017a829
--- /dev/null
+++ b/internal/web/controller/client_user_suggestions_test.go
@@ -0,0 +1,97 @@
+package controller
+
+import (
+ "encoding/json"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "slices"
+ "testing"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+ "github.com/mhsanaei/3x-ui/v3/internal/testpg"
+ "github.com/mhsanaei/3x-ui/v3/internal/util/crypto"
+)
+
+func TestClientUserSuggestionsHTTP(t *testing.T) {
+ cleanup, err := testpg.IsolatePackage("routing_user_suggestions")
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(cleanup)
+ router, api := newAPIAuthTestEngine(t)
+ NewClientController(router.Group("/base/panel/api/clients", api.checkAPIAuth, api.enforceTokenScope))
+ db := database.GetDB()
+ for _, scope := range []string{model.ApiScopeAdmin, model.ApiScopeMonitor, model.ApiScopeNodeSync, model.ApiScopeNodeAdmin} {
+ token := model.ApiToken{Name: scope, Token: crypto.HashTokenSHA256(scope), Enabled: true, Scope: scope}
+ if err := db.Create(&token).Error; err != nil {
+ t.Fatal(err)
+ }
+ }
+ seeds := []model.ClientRecord{
+ {Email: "literal_%@test", Password: "private", Group: "ignored"},
+ {Email: "literal_ab@test", Comment: "only-in-a-comment"},
+ }
+ if err := db.Create(&seeds).Error; err != nil {
+ t.Fatal(err)
+ }
+ clients := make([]model.ClientRecord, 50000)
+ for i := range clients {
+ clients[i] = model.ClientRecord{Email: fmt.Sprintf("fixture-%05d@test", i)}
+ }
+ if err := db.CreateInBatches(&clients, 100).Error; err != nil {
+ t.Fatal(err)
+ }
+ request := func(scope, search string) *httptest.ResponseRecorder {
+ req := httptest.NewRequest(http.MethodGet, "/base/panel/api/clients/userSuggestions?search="+url.QueryEscape(search)+"&pageSize=50000", nil)
+ req.Header.Set("X-Requested-With", "XMLHttpRequest")
+ if scope != "" {
+ req.Header.Set("Authorization", "Bearer "+scope)
+ }
+ w := httptest.NewRecorder()
+ router.ServeHTTP(w, req)
+ return w
+ }
+ for _, scope := range []string{"", model.ApiScopeMonitor, model.ApiScopeNodeSync, model.ApiScopeNodeAdmin} {
+ want := http.StatusForbidden
+ if scope == "" {
+ want = http.StatusUnauthorized
+ }
+ if got := request(scope, "fixture"); got.Code != want {
+ t.Errorf("scope %q: status = %d, want %d", scope, got.Code, want)
+ }
+ }
+ for _, tt := range []struct {
+ search string
+ count int
+ first string
+ }{
+ {"", 50, "fixture-00000@test"},
+ {"FIXTURE-", 50, "fixture-00000@test"},
+ {"49999@", 1, "fixture-49999@test"},
+ {" LITERAL_% ", 1, "literal_%@test"},
+ {"only-in-a-comment", 0, ""},
+ } {
+ t.Run(tt.search, func(t *testing.T) {
+ w := request(model.ApiScopeAdmin, tt.search)
+ var body struct {
+ Success bool `json:"success"`
+ Msg string `json:"msg"`
+ Obj struct {
+ Emails []string `json:"emails"`
+ } `json:"obj"`
+ }
+ decoder := json.NewDecoder(w.Body)
+ decoder.DisallowUnknownFields()
+ if err := decoder.Decode(&body); w.Code != http.StatusOK || err != nil || !body.Success {
+ t.Fatalf("status = %d, response = %+v, error = %v", w.Code, body, err)
+ }
+ emails := body.Obj.Emails
+ if emails == nil || len(emails) != tt.count || !slices.IsSorted(emails) || (tt.count > 0 && emails[0] != tt.first) {
+ t.Fatalf("search %q: emails = %v, want %d starting with %q", tt.search, emails, tt.count, tt.first)
+ }
+ })
+ }
+}
diff --git a/internal/web/service/client_user_suggestions.go b/internal/web/service/client_user_suggestions.go
new file mode 100644
index 000000000..978b96965
--- /dev/null
+++ b/internal/web/service/client_user_suggestions.go
@@ -0,0 +1,33 @@
+package service
+
+import (
+ "context"
+ "strings"
+
+ "github.com/mhsanaei/3x-ui/v3/internal/database"
+ "github.com/mhsanaei/3x-ui/v3/internal/database/model"
+)
+
+const clientEmailSuggestionLimit = 50
+
+type ClientEmailSuggestions struct {
+ Emails []string `json:"emails" example:"[\"alice@example.com\",\"bob@example.com\"]"`
+}
+
+func (s *ClientService) ListUserSuggestions(ctx context.Context, search string) (ClientEmailSuggestions, error) {
+ query := database.GetDB().WithContext(ctx).Model(&model.ClientRecord{}).Where("email <> ''")
+ if search = strings.TrimSpace(search); search != "" {
+ like := func(value string) string { return "%" + escapeLikeLiteral(value) + "%" }
+ variants := caseVariants(search)
+ conditions := []string{"LOWER(email) LIKE ? ESCAPE '\\'"}
+ args := []any{like(variants[0])}
+ for _, variant := range variants {
+ conditions = append(conditions, "email LIKE ? ESCAPE '\\'")
+ args = append(args, like(variant))
+ }
+ query = query.Where("("+strings.Join(conditions, " OR ")+")", args...)
+ }
+ result := ClientEmailSuggestions{Emails: make([]string, 0, clientEmailSuggestionLimit)}
+ err := query.Order("email").Limit(clientEmailSuggestionLimit).Pluck("email", &result.Emails).Error
+ return result, err
+}
diff --git a/tools/openapigen/main.go b/tools/openapigen/main.go
index 5381b41a2..721082525 100644
--- a/tools/openapigen/main.go
+++ b/tools/openapigen/main.go
@@ -115,6 +115,7 @@ func run(root, outDir string) error {
"ClientRenewalPreviewRequest",
"ClientRenewalPreview",
"ClientPageResponse",
+ "ClientEmailSuggestions",
"AttachCandidate",
"AttachCandidatePage",
"AttachSelectionResult",