diff --git a/frontend/src/pages/inbounds/ClientRollups.stories.tsx b/frontend/src/pages/inbounds/ClientRollups.stories.tsx
new file mode 100644
index 000000000..06b74132d
--- /dev/null
+++ b/frontend/src/pages/inbounds/ClientRollups.stories.tsx
@@ -0,0 +1,115 @@
+import { useState } from 'react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { Meta, StoryObj } from '@storybook/react-vite';
+import { expect } from 'storybook/test';
+
+import { keys } from '@/api/queryKeys';
+
+import { useInbounds } from './useInbounds';
+
+const meta = { title: 'Inbounds/Client rollup performance' } satisfies Meta;
+export default meta;
+
+function Rollups() {
+ const { dbInbounds, clientCount, applyTrafficEvent } = useInbounds();
+ const [input, setInput] = useState('');
+ return (
+ <>
+
+
+ {clientCount[30]
+ ? 'Rollups ready'
+ : dbInbounds.length
+ ? 'Calculating rollups'
+ : 'Waiting for inbounds'}
+
+
+ Last inbound online: {clientCount[30]?.online.length ?? '…'}
+ First inbound online: {clientCount[1]?.online.length ?? '…'}
+ >
+ );
+}
+
+function Fixture() {
+ const [queryClient] = useState(() => {
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ client.setQueryData(keys.settings.defaults(), {});
+ client.setQueryData(keys.inbounds.slim(), []);
+ client.setQueryData(keys.clients.onlines(), []);
+ client.setQueryData(keys.clients.onlinesByGuid(), {});
+ client.setQueryData(keys.clients.activeInbounds(), {});
+ client.setQueryData(keys.clients.lastOnline(), {});
+ return client;
+ });
+
+ return (
+
+
+
+
+ );
+}
+
+export const LargeDeployment: StoryObj = {
+ render: () => ,
+ play: async ({ canvas, userEvent }) => {
+ const start = performance.now();
+ await userEvent.click(canvas.getByRole('button', { name: 'Load 120,000 memberships' }));
+ await userEvent.type(canvas.getByRole('textbox', { name: 'Filter' }), 'a');
+ const responsiveAt = performance.now();
+ await canvas.findByText('Rollups ready');
+ const readyAt = performance.now();
+ const updateAt = performance.now();
+ await userEvent.click(canvas.getByRole('button', { name: 'Apply online update' }));
+ await canvas.findByText('Last inbound online: 1');
+ await expect(canvas.getByText('First inbound online: 0')).toBeVisible();
+ await expect(canvas.getByRole('textbox', { name: 'Filter' })).toHaveValue('a');
+ console.info('120,000 memberships (ms)', {
+ input: Math.round(responsiveAt - start),
+ initial: Math.round(readyAt - start),
+ update: Math.round(performance.now() - updateAt),
+ });
+ },
+};
diff --git a/frontend/src/pages/inbounds/InboundsPage.tsx b/frontend/src/pages/inbounds/InboundsPage.tsx
index 7ffaf5de0..6c062533f 100644
--- a/frontend/src/pages/inbounds/InboundsPage.tsx
+++ b/frontend/src/pages/inbounds/InboundsPage.tsx
@@ -89,6 +89,7 @@ export default function InboundsPage() {
fetchError,
dbInbounds,
clientCount,
+ clientCountsPending,
onlineClients,
lastOnlineMap,
inboundSpeed,
@@ -558,7 +559,8 @@ export default function InboundsPage() {
const confirmDelAllClients = useCallback(
(dbInbound: DBInbound) => {
- const count = clientCount[dbInbound.id]?.clients || 0;
+ const count = clientCount[dbInbound.id]?.clients;
+ if (count === undefined || count === 0) return;
modal.confirm({
title: t('pages.inbounds.delAllClientsConfirmTitle', { remark: dbInbound.remark, count }),
content: t('pages.inbounds.delAllClientsConfirmContent'),
@@ -796,6 +798,7 @@ export default function InboundsPage() {
;
+ clientCountsPending: boolean;
onlineClients: string[];
lastOnlineMap: Record;
inboundSpeed: Record;
diff --git a/frontend/src/pages/inbounds/list/useInboundColumns.tsx b/frontend/src/pages/inbounds/list/useInboundColumns.tsx
index fc1d10d05..63e42b33a 100644
--- a/frontend/src/pages/inbounds/list/useInboundColumns.tsx
+++ b/frontend/src/pages/inbounds/list/useInboundColumns.tsx
@@ -1,4 +1,4 @@
-import { useMemo, type ReactElement } from 'react';
+import { useMemo, useState, type ReactElement } from 'react';
import { useTranslation } from 'react-i18next';
import { onlineStatusLabel } from './onlineStatusLabel';
import { Popover, Switch, Tag, Tooltip, type TableColumnType } from 'antd';
@@ -28,6 +28,49 @@ import {
} from './helpers';
import type { ClientCountEntry, DBInboundRecord, InboundSpeedEntry, RowAction } from './types';
+function ClientEmailBadge({
+ emails,
+ title,
+ color,
+ suffix,
+}: {
+ emails: string[];
+ title: string;
+ color?: string;
+ suffix?: string;
+}) {
+ const [open, setOpen] = useState(false);
+ const badge = (
+
+ {emails.length}
+ {suffix && ` ${suffix}`}
+
+ );
+ if (!emails.length) return badge;
+ return (
+
+ {emails.map((email) => (
+ {email}
+ ))}
+
+ ) : null
+ }
+ >
+ {badge}
+
+ );
+}
+
interface UseInboundColumnsParams {
hasAnyRemark: boolean;
hasAnySubSortIndex: boolean;
@@ -35,6 +78,7 @@ interface UseInboundColumnsParams {
nodesById: Map;
hostRemarksByInboundId: Map;
clientCount: Record;
+ clientCountsPending: boolean;
inboundSpeed: Record;
subEnable: boolean;
expireDiff: number;
@@ -50,6 +94,7 @@ export function useInboundColumns({
nodesById,
hostRemarksByInboundId,
clientCount,
+ clientCountsPending,
inboundSpeed,
subEnable,
expireDiff,
@@ -70,7 +115,9 @@ export function useInboundColumns({
};
const clientTotal = (record: DBInboundRecord) =>
- (clientCount[record.id] || fallbackClientCount(record))?.clients ?? 0;
+ clientCountsPending
+ ? 0
+ : ((clientCount[record.id] || fallbackClientCount(record))?.clients ?? 0);
const speedTotal = (record: DBInboundRecord) => {
const speed = inboundSpeed[record.id];
@@ -290,8 +337,11 @@ export function useInboundColumns({
width: 200,
sorter: (a, b) => clientTotal(a) - clientTotal(b),
render: (_, record) => {
+ if (clientCountsPending) return t('loading');
const cc = clientCount[record.id] || fallbackClientCount(record);
if (!cc) return null;
+ const onlineScope =
+ cc.onlineAttribution === 'node' ? `(${t('pages.inbounds.node')})` : undefined;
return (
<>
{cc.clients}
- {cc.active.length > 0 ? (
-
- {cc.active.map((e) => (
- {e}
- ))}
-
- }
- >
-
- {cc.active.length}
-
-
- ) : (
-
- 0
-
- )}
+
{cc.deactive.length > 0 && (
-
- {cc.deactive.map((e) => (
- {e}
- ))}
-
- }
- >
-
- {cc.deactive.length}
-
-
+
)}
{cc.depleted.length > 0 && (
-
- {cc.depleted.map((e) => (
- {e}
- ))}
-
- }
- >
-
- {cc.depleted.length}
-
-
+
)}
{cc.onlineAttribution && cc.online.length === 0 && (
@@ -373,29 +363,12 @@ export function useInboundColumns({
)}
{cc.online.length > 0 && (
-
- {cc.online.map((e) => (
- {e}
- ))}
-
- }
- >
-
- {cc.online.length}
- {cc.onlineAttribution === 'node' && ` (${t('pages.inbounds.node')})`}
-
-
+
)}
>
);
@@ -488,6 +461,7 @@ export function useInboundColumns({
nodesById,
hostRemarksByInboundId,
clientCount,
+ clientCountsPending,
inboundSpeed,
subEnable,
expireDiff,
diff --git a/frontend/src/pages/inbounds/useInbounds.ts b/frontend/src/pages/inbounds/useInbounds.ts
index 8911c0ce6..4cc55c11a 100644
--- a/frontend/src/pages/inbounds/useInbounds.ts
+++ b/frontend/src/pages/inbounds/useInbounds.ts
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { useQuery, useQueryClient } from '@tanstack/react-query';
import { HttpUtil } from '@/utils';
@@ -58,6 +58,15 @@ interface ClientRollup {
comments: Map;
}
+interface CachedClientRollup {
+ base: ClientRollup;
+ refreshAt: number;
+ online?: { emails?: Set; result: ClientRollup };
+}
+
+const EMPTY_ONLINE: string[] = [];
+const EMPTY_ROLLUPS: Record = {};
+
const TRACKED_PROTOCOLS: readonly string[] = [
Protocols.VMESS,
Protocols.VLESS,
@@ -124,27 +133,37 @@ function toActiveInboundMap(
data: Record,
): Map | null> {
const map = new Map | null>();
- for (const [key, tags] of Object.entries(data)) {
- if (tags === null) map.set(key, null);
- else if (Array.isArray(tags)) map.set(key, new Set(tags));
+ for (const [guid, tags] of Object.entries(data)) {
+ if (tags === null) map.set(guid, null);
+ else if (Array.isArray(tags)) map.set(guid, new Set(tags));
}
return map;
}
-// Most pushes repeat the previous online sets; handing back a new Map anyway
-// re-ran the client rollup over every inbound on each traffic event.
-function sameGuidSets(
- a: ReadonlyMap | null>,
- b: ReadonlyMap | null>,
-): boolean {
- if (a.size !== b.size) return false;
- for (const [key, set] of b) {
- const prev = a.get(key);
- if (prev === set) continue;
- if (!prev || !set || prev.size !== set.size) return false;
- for (const value of set) if (!prev.has(value)) return false;
+function reuseGuidSets | null>(
+ previous: Map,
+ next: Map,
+): Map {
+ let changed = previous.size !== next.size;
+ for (const [guid, set] of next) {
+ const prior = previous.get(guid);
+ if (prior === set) continue;
+ let same = !!prior && !!set && prior.size === set.size;
+ if (same && prior && set) {
+ for (const value of set) {
+ if (!prior.has(value)) {
+ same = false;
+ break;
+ }
+ }
+ }
+ if (same && prior) {
+ next.set(guid, prior);
+ } else {
+ changed = true;
+ }
}
- return true;
+ return changed ? next : previous;
}
async function fetchLastOnlineMap(): Promise> {
@@ -237,6 +256,7 @@ export function useInbounds() {
// dbInbounds mirrors the slim query data wrapped as DBInbound instances. The
// WS handlers rebuild only the rows they touch, so no refetch is needed.
const [dbInbounds, setDbInbounds] = useState([]);
+ const [inboundGeneration, setInboundGeneration] = useState(0);
const dbInboundsRef = useRef([]);
useEffect(() => {
dbInboundsRef.current = dbInbounds;
@@ -265,10 +285,7 @@ export function useInbounds() {
const [lastOnlineMap, setLastOnlineMap] = useState>({});
const rollupClients = useCallback(
- (
- dbInbound: DBInboundInstance,
- inbound: { clients?: { email?: string; enable?: boolean; comment?: string }[] },
- ): ClientRollup => {
+ (dbInbound: DBInboundInstance, now: number): CachedClientRollup => {
const clientStats = Array.isArray((dbInbound as { clientStats?: unknown }).clientStats)
? (
dbInbound as unknown as {
@@ -282,37 +299,16 @@ export function useInbounds() {
}
).clientStats
: [];
- const clients = inbound?.clients || [];
+ const settings = coerceInboundJsonField(dbInbound.settings) as {
+ clients?: { email?: string; enable?: boolean; comment?: string }[];
+ };
+ const clients = Array.isArray(settings.clients) ? settings.clients : [];
const active: string[] = [];
const deactive: string[] = [];
const depleted: string[] = [];
const expiring: string[] = [];
- const online: string[] = [];
const comments = new Map();
- const now = Date.now();
-
- // Attribution key: the GUID of the node that physically hosts this
- // inbound. Local inbounds carry the panel's own GUID (filled server-side);
- // a node-managed inbound carries its origin node's GUID, or falls back to
- // the master-local synthetic id for an old-build node without one (#4983).
- const guid =
- dbInbound.originNodeGuid || (dbInbound.nodeId != null ? `node:${dbInbound.nodeId}` : '');
- const nodeOnline = onlineByGuid.get(guid);
- const activeForNode = activeByGuid.get(guid);
- let onlineAttribution: ClientRollup['onlineAttribution'] = onlinePending
- ? 'pending'
- : 'unavailable';
- let inboundActive = false;
- if (!dbInbound.enable) {
- onlineAttribution = 'inbound';
- } else if (activeForNode === null) {
- onlineAttribution = nodeOnline === undefined ? 'unsupported' : 'node';
- inboundActive = true;
- } else if (nodeOnline !== undefined && activeForNode !== undefined && dbInbound.tag) {
- inboundActive = activeForNode.has(dbInbound.tag);
- // A partial report only vouches for the listed sidecar inbounds.
- if (inboundActive || !activeForNode.has('\0')) onlineAttribution = 'inbound';
- }
+ let refreshAt = Infinity;
if (dbInbound.enable) {
const statsByEmail = new Map<
@@ -333,17 +329,20 @@ export function useInbounds() {
depleted.push(client.email);
continue;
}
+ if (stats && stats.expiryTime > now) refreshAt = Math.min(refreshAt, stats.expiryTime);
if (!client.enable) {
deactive.push(client.email);
continue;
}
active.push(client.email);
- if (inboundActive && nodeOnline?.has(client.email)) online.push(client.email);
if (stats) {
const expiringSoon =
(stats.expiryTime > 0 && stats.expiryTime - now < expireDiff) ||
(stats.total > 0 && stats.total - (stats.up + stats.down) < trafficDiff);
if (expiringSoon) expiring.push(client.email);
+ if (stats.expiryTime > now && !expiringSoon && expireDiff > 0) {
+ refreshAt = Math.min(refreshAt, Math.floor(stats.expiryTime - expireDiff) + 1);
+ }
}
}
} else {
@@ -353,39 +352,148 @@ export function useInbounds() {
}
return {
- clients: clients.length,
- active,
- deactive,
- depleted,
- expiring,
- online,
- onlineAttribution,
- comments,
+ base: {
+ clients: clients.length,
+ active,
+ deactive,
+ depleted,
+ expiring,
+ online: EMPTY_ONLINE,
+ onlineAttribution: 'inbound',
+ comments,
+ },
+ refreshAt,
};
},
- [onlineByGuid, activeByGuid, onlinePending, expireDiff, trafficDiff],
+ [expireDiff, trafficDiff],
);
- // Every write to a DBInbound row also replaces the dbInbounds array, so this
- // recomputes on both a refetch and a WS-merged stats update.
- const clientCount = useMemo(() => {
+ const rollupCache = useMemo(
+ () => ({ rows: new WeakMap(), compute: rollupClients }),
+ [rollupClients],
+ );
+
+ // The WebSocket subscription keeps the callback installed at mount.
+ const rollupCacheRef = useRef(rollupCache);
+ useLayoutEffect(() => {
+ rollupCacheRef.current = rollupCache;
+ }, [rollupCache]);
+
+ const rollupForInbound = useCallback(
+ (dbInbound: DBInboundInstance, now = Date.now()) => {
+ if (!TRACKED_PROTOCOLS.includes(dbInbound.protocol)) return undefined;
+ let rollup = rollupCache.rows.get(dbInbound);
+ if (rollup === undefined || now >= rollup.refreshAt) {
+ rollup = rollupCache.compute(dbInbound, now);
+ rollupCache.rows.set(dbInbound, rollup);
+ }
+
+ // Scope the report to the node that physically hosts this inbound.
+ const guid =
+ dbInbound.originNodeGuid || (dbInbound.nodeId != null ? `node:${dbInbound.nodeId}` : '');
+ const nodeOnline = onlineByGuid.get(guid);
+ const activeForNode = activeByGuid.get(guid);
+ let attribution: ClientRollup['onlineAttribution'] = onlinePending
+ ? 'pending'
+ : 'unavailable';
+ let inboundActive = false;
+ if (!dbInbound.enable) {
+ attribution = 'inbound';
+ } else if (activeForNode === null) {
+ attribution = nodeOnline === undefined ? 'unsupported' : 'node';
+ inboundActive = true;
+ } else if (nodeOnline !== undefined && activeForNode !== undefined && dbInbound.tag) {
+ inboundActive = activeForNode.has(dbInbound.tag);
+ // A partial report only vouches for the listed sidecar inbounds.
+ if (inboundActive || !activeForNode.has('\0')) attribution = 'inbound';
+ }
+
+ const emails = inboundActive && nodeOnline?.size ? nodeOnline : undefined;
+ const cached = rollup.online;
+ if (cached && cached.emails === emails && cached.result.onlineAttribution === attribution) {
+ return cached.result;
+ }
+
+ const matched = emails
+ ? rollup.base.active.filter((email) => emails.has(email))
+ : EMPTY_ONLINE;
+ const result =
+ matched.length || attribution !== rollup.base.onlineAttribution
+ ? { ...rollup.base, online: matched, onlineAttribution: attribution }
+ : rollup.base;
+ rollup.online = { emails, result };
+ return result;
+ },
+ [rollupCache, activeByGuid, onlineByGuid, onlinePending],
+ );
+
+ const largeList = useMemo(
+ () =>
+ dbInbounds.reduce((size, row) => {
+ const settings = row.settings;
+ const objectClients =
+ settings && typeof settings === 'object' && !Array.isArray(settings)
+ ? settings.clients
+ : undefined;
+ return (
+ size +
+ (typeof settings === 'string' ? settings.length : 0) +
+ (Array.isArray(objectClients) ? objectClients.length * 64 : 0) +
+ (Array.isArray(row.clientStats) ? row.clientStats.length * 100 : 0)
+ );
+ }, 0) >
+ 256 * 1024,
+ [dbInbounds],
+ );
+ const [scheduled, setScheduled] = useState<{
+ generation: number;
+ counts: Record;
+ }>();
+ useEffect(() => {
+ if (!largeList) return;
const counts: Record = {};
- for (const dbInbound of dbInbounds) {
- const protocol = dbInbound.protocol;
- if (!TRACKED_PROTOCOLS.includes(protocol)) continue;
- const settings = coerceInboundJsonField(dbInbound.settings) as {
- clients?: Array<{ email?: string; enable?: boolean; comment?: string }>;
- };
- counts[dbInbound.id] = rollupClients(dbInbound, { clients: settings.clients });
+ const now = Date.now();
+ let index = 0;
+ let timer: ReturnType;
+ function computeSlice() {
+ const end = performance.now() + 8;
+ do {
+ const row = dbInbounds[index++];
+ const rollup = rollupForInbound(row, now);
+ if (rollup) counts[row.id] = rollup;
+ } while (index < dbInbounds.length && performance.now() < end);
+ if (index < dbInbounds.length) {
+ timer = setTimeout(computeSlice, 0);
+ } else {
+ setScheduled({ generation: inboundGeneration, counts });
+ }
+ }
+ timer = setTimeout(computeSlice, 0);
+ return () => clearTimeout(timer);
+ }, [largeList, dbInbounds, inboundGeneration, rollupForInbound]);
+
+ const syncCounts = useMemo(() => {
+ if (largeList) return EMPTY_ROLLUPS;
+ const counts: Record = {};
+ for (const row of dbInbounds) {
+ const rollup = rollupForInbound(row);
+ if (rollup) counts[row.id] = rollup;
}
return counts;
- }, [dbInbounds, rollupClients]);
+ }, [largeList, dbInbounds, rollupForInbound]);
+ // Online and counter updates can reuse the last rollup while the next slice
+ // runs, but a refetch or hydration may have changed the client membership.
+ const rollupsReady = !largeList || scheduled?.generation === inboundGeneration;
+ const clientCount = largeList
+ ? ((rollupsReady ? scheduled?.counts : undefined) ?? EMPTY_ROLLUPS)
+ : syncCounts;
// Adopting fetched data during render (rather than in an effect) keeps the
// list from painting one frame of the previous data after a refetch.
const [syncedSlim, setSyncedSlim] = useState();
if (slimQuery.data && slimQuery.data !== syncedSlim) {
setSyncedSlim(slimQuery.data);
+ setInboundGeneration((generation) => generation + 1);
setDbInbounds(
(slimQuery.data as { protocol: string; id: number }[]).map(
(row) => new DBInbound(row) as DBInboundInstance,
@@ -450,6 +558,7 @@ export function useInbounds() {
const validated = parseMsg(msg, InboundDetailSchema, `inbounds/get/${id}`);
if (!validated.obj) return null;
const dbInbound = new DBInbound(validated.obj) as DBInboundInstance;
+ setInboundGeneration((generation) => generation + 1);
setDbInbounds((prev) => {
const next = prev.map((row) =>
(row as unknown as { id: number }).id === id ? dbInbound : row,
@@ -475,11 +584,11 @@ export function useInbounds() {
}
if (p.onlineByGuid && typeof p.onlineByGuid === 'object') {
const next = toGuidOnlineMap(p.onlineByGuid);
- setOnlineByGuid((prev) => (sameGuidSets(prev, next) ? prev : next));
+ setOnlineByGuid((prev) => reuseGuidSets(prev, next));
}
if (p.activeInbounds && typeof p.activeInbounds === 'object') {
const next = toActiveInboundMap(p.activeInbounds);
- setActiveByGuid((prev) => (sameGuidSets(prev, next) ? prev : next));
+ setActiveByGuid((prev) => reuseGuidSets(prev, next));
}
if (p.lastOnlineMap && typeof p.lastOnlineMap === 'object') {
setLastOnlineMap((prev) => ({ ...prev, ...p.lastOnlineMap! }));
@@ -611,6 +720,11 @@ export function useInbounds() {
if (typeof upd.enable === 'boolean') row.enable = upd.enable;
}
if (statsTouched && nextStats) row.clientStats = nextStats;
+ if (!statsTouched && ib.enable === row.enable) {
+ const cache = rollupCacheRef.current.rows;
+ const cached = cache.get(ib);
+ if (cached) cache.set(row, cached);
+ }
return row;
});
@@ -635,6 +749,7 @@ export function useInbounds() {
fetchError,
dbInbounds,
clientCount,
+ clientCountsPending: !rollupsReady,
onlineClients,
lastOnlineMap,
inboundSpeed,
diff --git a/frontend/src/test/inbounds-ws-identity.test.tsx b/frontend/src/test/inbounds-ws-identity.test.tsx
index d8b6fc34b..70118871f 100644
--- a/frontend/src/test/inbounds-ws-identity.test.tsx
+++ b/frontend/src/test/inbounds-ws-identity.test.tsx
@@ -1,19 +1,27 @@
-import type { ReactNode } from 'react';
-import { act, renderHook, waitFor } from '@testing-library/react';
+import { useLayoutEffect, type ReactNode } from 'react';
+import { act, fireEvent, renderHook, screen, waitFor, within } from '@testing-library/react';
import { QueryClientProvider } from '@tanstack/react-query';
import { describe, expect, it, vi } from 'vitest';
+import { MemoryRouter } from 'react-router';
-import { HttpUtil } from '@/utils';
import { keys } from '@/api/queryKeys';
+import { getSharedWebSocketClient } from '@/api/websocket';
+import { useWebSocket } from '@/hooks/useWebSocket';
+import InboundsPage from '@/pages/inbounds/InboundsPage';
+import { HttpUtil, Msg } from '@/utils';
import { useInbounds } from '@/pages/inbounds/useInbounds';
-import { makeTestQueryClient } from './test-utils';
+import { makeTestQueryClient, renderWithProviders } from './test-utils';
+
+vi.mock('@/layouts/AppSidebar', () => ({ default: () => null }));
+vi.mock('@/pages/inbounds/form/InboundFormModal', () => ({ default: () => null }));
function seedInbounds() {
const rows = [1, 2].map((id) => ({
id,
protocol: 'vless',
tag: `in-${id}`,
+ originNodeGuid: `node-${id}`,
enable: true,
up: 10,
down: 20,
@@ -72,6 +80,7 @@ describe('inbound websocket merges keep unchanged state', () => {
it('still rebuilds exactly the rows whose numbers moved', async () => {
const { result } = await renderInbounds();
const before = result.current.dbInbounds;
+ const countsBefore = result.current.clientCount;
act(() =>
result.current.applyClientStatsEvent({
@@ -86,8 +95,10 @@ describe('inbound websocket merges keep unchanged state', () => {
const [first, second] = result.current.dbInbounds;
expect(first).not.toBe(before[0]);
expect(first.up).toBe(99);
+ expect(result.current.clientCount[1]).toBe(countsBefore[1]);
expect(second).not.toBe(before[1]);
expect(second.clientStats?.[0]?.up).toBe(5);
+ expect(result.current.clientCount[2]).not.toBe(countsBefore[2]);
});
it('keeps the client rollup when a traffic push repeats the same online sets', async () => {
@@ -107,6 +118,230 @@ describe('inbound websocket merges keep unchanged state', () => {
});
});
+it('reuses unaffected rollups and client metadata on large online updates', async () => {
+ const { queryClient, rows, wrapper } = seedInbounds();
+ const clients = Array.from({ length: 4000 }, (_, i) => ({
+ email: `client-${i}@x`,
+ enable: true,
+ comment: 'shared subscription',
+ }));
+ const settings = JSON.stringify({ clients });
+ queryClient.setQueryData(
+ keys.inbounds.slim(),
+ Array.from({ length: 30 }, (_, i) => ({
+ ...rows[i % 2],
+ id: i + 1,
+ tag: `large-${i + 1}`,
+ settings,
+ })),
+ );
+ const { result } = renderHook(() => useInbounds(), { wrapper });
+ await waitFor(() => expect(result.current.clientCount[30]?.clients).toBe(4000));
+ const before = result.current.clientCount;
+ act(() =>
+ result.current.applyTrafficEvent({
+ onlineByGuid: { 'node-1': [clients[0].email], 'node-2': [clients[1].email] },
+ activeInbounds: { 'node-1': ['large-1'], 'node-2': ['large-2'] },
+ }),
+ );
+ await waitFor(() => expect(result.current.clientCount[1].online).toEqual([clients[0].email]));
+ const initial = result.current.clientCount;
+ expect(initial[1].active).toBe(before[1].active);
+ expect(initial[1].online).toEqual([clients[0].email]);
+
+ act(() =>
+ result.current.applyTrafficEvent({
+ onlineByGuid: { 'node-1': [clients[2].email], 'node-2': [clients[1].email] },
+ activeInbounds: { 'node-1': ['large-1'], 'node-2': ['large-2'] },
+ }),
+ );
+ await waitFor(() => expect(result.current.clientCount[1].online).toEqual([clients[2].email]));
+ expect(result.current.clientCount[1].active).toBe(initial[1].active);
+ for (let id = 2; id <= 30; id++) {
+ expect(result.current.clientCount[id]).toBe(initial[id]);
+ }
+});
+
+it('loads inbounds whose clientStats is null in the slim response', () => {
+ const { rows, queryClient, wrapper } = seedInbounds();
+ queryClient.setQueryData(keys.inbounds.slim(), [
+ { ...rows[0], protocol: 'mixed', settings: '{}', clientStats: null },
+ { ...rows[1], settings: '{"clients":[]}', clientStats: null },
+ ]);
+ const { result } = renderHook(() => useInbounds(), { wrapper });
+ expect(result.current.fetched).toBe(true);
+ expect(result.current.dbInbounds.map((row) => row.id)).toEqual([1, 2]);
+ expect(result.current.clientCount[1]).toBeUndefined();
+ expect(result.current.clientCount[2].clients).toBe(0);
+});
+
+it('withholds large inbound rollups until they match the refetched structure', async () => {
+ const { queryClient, rows, wrapper } = seedInbounds();
+ const withClients = (count: number, remark: string) => ({
+ ...rows[0],
+ remark,
+ settings: JSON.stringify({
+ clients: Array.from({ length: count }, (_, i) => ({
+ email: `member-${i}@example.test`,
+ enable: true,
+ })),
+ }),
+ });
+ const seed = withClients(7000, 'initial');
+ queryClient.setQueryData(keys.inbounds.slim(), [seed]);
+ const displayed: { remark: string; fetched: boolean; pending: boolean; count?: number }[] = [];
+ const { result } = renderHook(
+ () => {
+ const data = useInbounds();
+ useLayoutEffect(() => {
+ const row = data.dbInbounds[0];
+ if (row)
+ displayed.push({
+ remark: row.remark,
+ fetched: data.fetched,
+ pending: data.clientCountsPending,
+ count: data.clientCount[row.id]?.clients,
+ });
+ });
+ return data;
+ },
+ { wrapper },
+ );
+ await waitFor(() => expect(result.current.clientCount[seed.id]?.clients).toBe(7000));
+ for (const [count, remark] of [
+ [8000, 'large refetch'],
+ [1, 'small refetch'],
+ [9000, 'large again'],
+ ] as const) {
+ act(() => queryClient.setQueryData(keys.inbounds.slim(), [withClients(count, remark)]));
+ await waitFor(() => expect(result.current.clientCount[seed.id]?.clients).toBe(count));
+ expect(displayed.filter((view) => view.remark === remark)).toEqual(
+ expect.arrayContaining([{ remark, fetched: true, pending: false, count }]),
+ );
+ for (const view of displayed.filter((view) => view.remark === remark)) {
+ expect(view.fetched).toBe(true);
+ expect(view.count).toBe(view.pending ? undefined : count);
+ }
+ }
+});
+
+it('keeps the search, node filter and selection through large-list refetch and detail hydration', async () => {
+ const { queryClient, rows } = seedInbounds();
+ const clients = (count: number) =>
+ JSON.stringify({
+ clients: Array.from({ length: count }, (_, i) => ({
+ email: `member-${i}@example.test`,
+ enable: true,
+ })),
+ });
+ const local = { ...rows[0], remark: 'Kept local', settings: clients(7000) };
+ const remote = { ...rows[1], remark: 'Kept remote', nodeId: 7 };
+ queryClient.setQueryData(keys.inbounds.slim(), [local, remote]);
+ queryClient.setQueryDefaults(keys.nodes.list(), { staleTime: Infinity });
+ queryClient.setQueryData(keys.nodes.list(), [
+ { id: 7, name: 'Remote', enable: true, status: 'online' },
+ ]);
+ queryClient.setQueryData(keys.hosts.list(), []);
+ const get = vi.mocked(HttpUtil.get);
+ const fallback = get.getMockImplementation();
+ get.mockImplementation(async (url, ...args) =>
+ url === '/panel/api/inbounds/get/1'
+ ? new Msg(true, '', { ...local, remark: 'Kept hydrated', settings: clients(9000) })
+ : ((await fallback?.(url, ...args)) ?? new Msg(true, '', [])),
+ );
+
+ const view = renderWithProviders(
+
+
+ ,
+ { queryClient },
+ );
+ try {
+ await screen.findAllByText('7000');
+ const search = screen.getByRole('textbox', { name: 'Search' });
+ fireEvent.change(search, { target: { value: 'Kept' } });
+ fireEvent.mouseDown(screen.getByRole('combobox', { name: 'Nodes' }));
+ fireEvent.click(await screen.findByText('Local (this panel)'));
+ const row = () => screen.getByRole('row', { name: /Kept (local|refetched|hydrated)/ });
+ fireEvent.click(within(row()).getByRole('checkbox'));
+ const expectContext = () => {
+ expect(screen.getByRole('textbox', { name: 'Search' })).toBe(search);
+ expect((search as HTMLInputElement).value).toBe('Kept');
+ expect(screen.queryByText('Kept remote')).toBeNull();
+ expect((within(row()).getByRole('checkbox') as HTMLInputElement).checked).toBe(true);
+ };
+ expectContext();
+
+ act(() =>
+ queryClient.setQueryData(keys.inbounds.slim(), [
+ { ...local, remark: 'Kept refetched', settings: clients(8000) },
+ remote,
+ ]),
+ );
+ await screen.findAllByText('8000');
+ expectContext();
+
+ fireEvent.click(within(row()).getByRole('button', { name: 'Edit' }));
+ await screen.findAllByText('9000');
+ expectContext();
+ } finally {
+ view.unmount();
+ getSharedWebSocketClient().disconnect();
+ if (fallback) get.mockImplementation(fallback);
+ }
+});
+
+it('reuses the current rollup cache for subscribed websocket updates after defaults change', async () => {
+ const { queryClient, wrapper } = seedInbounds();
+ const sockets: EventTarget[] = [];
+ class FixtureSocket extends EventTarget {
+ static readonly CONNECTING = 0;
+ static readonly OPEN = 1;
+ readyState = FixtureSocket.CONNECTING;
+ constructor() {
+ super();
+ sockets.push(this);
+ }
+ close() {}
+ }
+ const socketClient = getSharedWebSocketClient();
+ socketClient.disconnect();
+ vi.stubGlobal('WebSocket', FixtureSocket);
+ const { result, unmount } = renderHook(
+ () => {
+ const data = useInbounds();
+ useWebSocket({ client_stats: data.applyClientStatsEvent });
+ return data;
+ },
+ { wrapper },
+ );
+
+ try {
+ await waitFor(() => expect(result.current.clientCount[1]?.clients).toBe(1));
+ act(() => queryClient.setQueryData(keys.settings.defaults(), { expireDiff: 3 }));
+ await waitFor(() => expect(result.current.expireDiff).toBe(3 * 86400000));
+ const afterDefaults = result.current.clientCount[1];
+ const [socket] = sockets;
+ if (!socket) throw new Error('WebSocket was not connected');
+ act(() =>
+ socket.dispatchEvent(
+ new MessageEvent('message', {
+ data: JSON.stringify({
+ type: 'client_stats',
+ payload: { inbounds: [{ id: 1, up: 99 }] },
+ }),
+ }),
+ ),
+ );
+ expect(result.current.dbInbounds[0].up).toBe(99);
+ expect(result.current.clientCount[1]).toBe(afterDefaults);
+ } finally {
+ unmount();
+ socketClient.disconnect();
+ vi.unstubAllGlobals();
+ }
+});
+
it('does not attribute shared online clients without matching inbound activity', async () => {
const { rows, queryClient, wrapper } = seedInbounds();
queryClient.setQueryData(
diff --git a/internal/amneziawgnet/relay_e2e_test.go b/internal/amneziawgnet/relay_e2e_test.go
index 2d5a5756c..753ff6545 100644
--- a/internal/amneziawgnet/relay_e2e_test.go
+++ b/internal/amneziawgnet/relay_e2e_test.go
@@ -152,7 +152,7 @@ func TestSocksRelayAgainstRealXray(t *testing.T) {
}
defer func() {
_ = cmd.Process.Kill()
- _, _ = cmd.Process.Wait()
+ _ = cmd.Wait()
}()
waitForPort(t, socksPort)
@@ -268,20 +268,10 @@ func TestSocksRelayAgainstRealXray(t *testing.T) {
t.Fatalf("UDP echo = %q, want %q (xray log follows)\n%s", gotUDP, udpMsg, xrayLog.String())
}
- // Real per-peer stats attribution: stop xray so its log is complete, then
- // look for both directions' counters keyed by the peer's real email --
- // the exact proof Finding 3 established manually in Phase 0.
- _ = cmd.Process.Kill()
- _, _ = cmd.Process.Wait()
- log := xrayLog.String()
- wantUp := fmt.Sprintf("user>>>%s>>>traffic>>>uplink", wantEmail)
- wantDown := fmt.Sprintf("user>>>%s>>>traffic>>>downlink", wantEmail)
- if !strings.Contains(log, wantUp) {
- t.Errorf("xray log missing uplink stats counter %q\nfull log:\n%s", wantUp, log)
- }
- if !strings.Contains(log, wantDown) {
- t.Errorf("xray log missing downlink stats counter %q\nfull log:\n%s", wantDown, log)
- }
+ waitForXrayCounters(t, &xrayLog,
+ fmt.Sprintf("user>>>%s>>>traffic>>>uplink", wantEmail),
+ fmt.Sprintf("user>>>%s>>>traffic>>>downlink", wantEmail),
+ )
}
// TestManagerEnsureAutomaticallyWiresRelay is Phase 3's own real proof: unlike
@@ -392,7 +382,7 @@ func TestManagerEnsureAutomaticallyWiresRelay(t *testing.T) {
}
defer func() {
_ = cmd.Process.Kill()
- _, _ = cmd.Process.Wait()
+ _ = cmd.Wait()
}()
waitForPort(t, socksPort)
@@ -462,12 +452,23 @@ func TestManagerEnsureAutomaticallyWiresRelay(t *testing.T) {
t.Errorf("TCP echo = %q, want %q", buf, tcpMsg)
}
- _ = cmd.Process.Kill()
- _, _ = cmd.Process.Wait()
- log := xrayLog.String()
- wantUp := fmt.Sprintf("user>>>%s>>>traffic>>>uplink", wantEmail)
- if !strings.Contains(log, wantUp) {
- t.Errorf("xray log missing uplink stats counter %q (Manager.Ensure's automatic relay wiring may not be attributing traffic correctly)\nfull log:\n%s", wantUp, log)
+ waitForXrayCounters(t, &xrayLog, fmt.Sprintf("user>>>%s>>>traffic>>>uplink", wantEmail))
+}
+
+func waitForXrayCounters(t *testing.T, log *syncBuffer, counters ...string) {
+ t.Helper()
+ deadline := time.Now().Add(3 * time.Second)
+ for _, counter := range counters {
+ for {
+ output := log.String()
+ if strings.Contains(output, counter) {
+ break
+ }
+ if time.Now().After(deadline) {
+ t.Fatalf("xray log missing stats counter %q\nfull log:\n%s", counter, output)
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
}
}
diff --git a/internal/web/service/tgbot/tgbot_send_test.go b/internal/web/service/tgbot/tgbot_send_test.go
index b86391725..b71112ae8 100644
--- a/internal/web/service/tgbot/tgbot_send_test.go
+++ b/internal/web/service/tgbot/tgbot_send_test.go
@@ -11,7 +11,6 @@ import (
"github.com/mhsanaei/3x-ui/v3/internal/logger"
- "github.com/mymmrac/telego"
tu "github.com/mymmrac/telego/telegoutil"
"github.com/nicksnyder/go-i18n/v2/i18n"
)
@@ -55,13 +54,7 @@ func TestEditMessageTgBotSkipsNotModified(t *testing.T) {
defer mock.Close()
// Point the package-level bot at the mock.
- origBot := liveBot()
- t.Cleanup(func() { setTestBot(origBot) })
- var err error
- bot, err = telego.NewBot(testBotToken, telego.WithAPIServer(mock.URL))
- if err != nil {
- t.Fatalf("NewBot: %v", err)
- }
+ swapTestBot(t, mock.URL)
// Snapshot warning count before the edit call.
before := logger.GetLogs(100, "warning")
@@ -87,13 +80,7 @@ func TestEditMessageCallbackTgBotSkipsNotModified(t *testing.T) {
}))
defer mock.Close()
- origBot := liveBot()
- t.Cleanup(func() { setTestBot(origBot) })
- var err error
- bot, err = telego.NewBot(testBotToken, telego.WithAPIServer(mock.URL))
- if err != nil {
- t.Fatalf("NewBot: %v", err)
- }
+ swapTestBot(t, mock.URL)
before := logger.GetLogs(100, "warning")
diff --git a/internal/web/service/tuic_relay_isolation_test.go b/internal/web/service/tuic_relay_isolation_test.go
index bc19cfc3c..f6caa4bdd 100644
--- a/internal/web/service/tuic_relay_isolation_test.go
+++ b/internal/web/service/tuic_relay_isolation_test.go
@@ -262,6 +262,9 @@ func TestTuicFailedRenameDefersDependentRoutingButAddsOtherInbound(t *testing.T)
dependent := ordinary
dependent.Tag = "dependent-ordinary"
dependent.Port = freeLoopbackPort(t)
+ for dependent.Port == ordinary.Port {
+ dependent.Port = freeLoopbackPort(t)
+ }
updatedSecond := isolationRelay(t, second.TuicInboundID, "new-second@test")
after.InboundConfigs = []xray.InboundConfig{before.InboundConfigs[0], next, updatedSecond, ordinary, dependent}
var policy map[string]any
@@ -278,6 +281,12 @@ func TestTuicFailedRenameDefersDependentRoutingButAddsOtherInbound(t *testing.T)
if applied, err := (&XrayService{}).tryHotApply(process, &after); applied || err == nil || !strings.Contains(err.Error(), "SOCKS5 bounds") {
t.Fatalf("failed rename result = %t, %v", applied, err)
}
+ // Reserve the deferred port before the relay probes start their own listeners.
+ reservation, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", dependent.Port))
+ if err != nil {
+ t.Fatalf("new inbound started before its dependent routing was applied: %v", err)
+ }
+ t.Cleanup(func() { _ = reservation.Close() })
assertIsolationRelay(t, previous, "original@test")
assertIsolationRelay(t, second, "old-second@test")
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
@@ -294,11 +303,6 @@ func TestTuicFailedRenameDefersDependentRoutingButAddsOtherInbound(t *testing.T)
t.Fatalf("new TUIC account escaped its deferred routing policy: %v", err)
}
assertIsolationRelay(t, ordinary, "other@test")
- reservation, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", dependent.Port))
- if err != nil {
- t.Fatalf("new inbound started before its dependent routing was applied: %v", err)
- }
- _ = reservation.Close()
route, err := api.TestRoute(xray.RouteTestRequest{InboundTag: next.Tag, IP: "203.0.113.1", Port: 6697})
if err != nil || route.Matched {
t.Fatalf("routing depending on an uninstalled relay was published: route=%+v err=%v", route, err)
@@ -306,6 +310,9 @@ func TestTuicFailedRenameDefersDependentRoutingButAddsOtherInbound(t *testing.T)
if string(process.GetConfig().RouterConfig) != string(before.RouterConfig) {
t.Fatal("snapshot recorded deferred routing as applied")
}
+ if err := reservation.Close(); err != nil {
+ t.Fatal(err)
+ }
after.InboundConfigs[1] = previous
after.InboundConfigs[1].Tag = next.Tag
if applied, err := (&XrayService{}).tryHotApply(process, &after); !applied || err != nil {