From 36f462ca9415c50e6ee17417522b4dab2d4dce81 Mon Sep 17 00:00:00 2001 From: Hamed Date: Thu, 3 Dec 2026 21:43:34 +0330 Subject: [PATCH] fix(frontend): show inbound loading and retry states (#7286) Expose separate loading feedback for the inbound list and client rollups, and retry only failed online-attribution requests. Finish in-flight rollup snapshots during WebSocket churn and coalesce subsequent updates. Invalidate published counts on structural generation changes, including slim refetch and detail hydration, while keeping the table mounted and preserving operator context. Preserve the per-inbound cache and attribution semantics from #7288 and #7289. Add regression coverage for continuous live updates, structural refresh and hydration, and failed-then-successful attribution retries. Validation: CI 47166924945 passed all 12 jobs, including 2,394 frontend tests, 13 inbound identity tests and the 120,000-membership Chromium story. No backend, database or API changes. Fixes #7282. --- frontend/src/pages/inbounds/InboundsPage.tsx | 49 +++++-- frontend/src/pages/inbounds/useInbounds.ts | 59 ++++++-- .../src/test/inbounds-ws-identity.test.tsx | 130 ++++++++++++++++-- 3 files changed, 205 insertions(+), 33 deletions(-) diff --git a/frontend/src/pages/inbounds/InboundsPage.tsx b/frontend/src/pages/inbounds/InboundsPage.tsx index 568a59c5b..d380b01ae 100644 --- a/frontend/src/pages/inbounds/InboundsPage.tsx +++ b/frontend/src/pages/inbounds/InboundsPage.tsx @@ -1,6 +1,7 @@ import { lazy, useCallback, useEffect, useMemo, useState } from 'react'; import { useTranslation } from 'react-i18next'; import { + Alert, Button, Card, Col, @@ -9,6 +10,7 @@ import { Modal, Result, Row, + Skeleton, Spin, Statistic, message, @@ -84,6 +86,9 @@ export default function InboundsPage() { dbInbounds, clientCount, clientCountsPending, + onlineAttributionError, + retryingOnlineAttribution, + retryOnlineAttribution, onlineClients, lastOnlineMap, inboundSpeed, @@ -707,15 +712,12 @@ export default function InboundsPage() { - +
{!fetched || !hostsFetched ? ( -
+
+ {t('loading')} + +
) : fetchError || hostsError ? ( - + {(onlineAttributionError || retryingOnlineAttribution) && ( + + void retryOnlineAttribution()} + > + {t('refresh')} + + } + showIcon + /> + + )} + + {clientCountsPending && ( + +
+ {t('clients')} · {t('loading')} +
+ + )} + + )} - +
diff --git a/frontend/src/pages/inbounds/useInbounds.ts b/frontend/src/pages/inbounds/useInbounds.ts index 4cc55c11a..076a1e414 100644 --- a/frontend/src/pages/inbounds/useInbounds.ts +++ b/frontend/src/pages/inbounds/useInbounds.ts @@ -281,6 +281,20 @@ export function useInbounds() { () => new Map(), ); const onlinePending = onlinesByGuidQuery.isPending || activeInboundsQuery.isPending; + const onlineAttributionError = onlinesByGuidQuery.isError || activeInboundsQuery.isError; + const [retryingOnlineAttribution, setRetryingOnlineAttribution] = useState(false); + + async function retryOnlineAttribution() { + setRetryingOnlineAttribution(true); + try { + await Promise.all([ + onlinesByGuidQuery.isError && onlinesByGuidQuery.refetch({ cancelRefetch: false }), + activeInboundsQuery.isError && activeInboundsQuery.refetch({ cancelRefetch: false }), + ]); + } finally { + setRetryingOnlineAttribution(false); + } + } const [lastOnlineMap, setLastOnlineMap] = useState>({}); @@ -445,12 +459,34 @@ export function useInbounds() { 256 * 1024, [dbInbounds], ); - const [scheduled, setScheduled] = useState<{ + type RollupWork = { generation: number; + rows: DBInboundInstance[]; + collect: typeof rollupForInbound; + }; + const [scheduled, setScheduled] = useState(); + const [computed, setComputed] = useState<{ + work: RollupWork; counts: Record; }>(); + + // Finish live snapshots before coalescing queued pushes. Structural changes + // supersede in-flight work immediately and invalidate its published counts. + if (!largeList) { + if (scheduled) setScheduled(undefined); + if (computed) setComputed(undefined); + } else if ( + !scheduled || + scheduled.generation !== inboundGeneration || + (computed?.work === scheduled && + (scheduled.rows !== dbInbounds || scheduled.collect !== rollupForInbound)) + ) { + setScheduled({ generation: inboundGeneration, rows: dbInbounds, collect: rollupForInbound }); + } + useEffect(() => { - if (!largeList) return; + if (!scheduled) return; + const work = scheduled; const counts: Record = {}; const now = Date.now(); let index = 0; @@ -458,19 +494,19 @@ export function useInbounds() { function computeSlice() { const end = performance.now() + 8; do { - const row = dbInbounds[index++]; - const rollup = rollupForInbound(row, now); + const row = work.rows[index++]; + const rollup = work.collect(row, now); if (rollup) counts[row.id] = rollup; - } while (index < dbInbounds.length && performance.now() < end); - if (index < dbInbounds.length) { + } while (index < work.rows.length && performance.now() < end); + if (index < work.rows.length) { timer = setTimeout(computeSlice, 0); } else { - setScheduled({ generation: inboundGeneration, counts }); + setComputed({ work, counts }); } } timer = setTimeout(computeSlice, 0); return () => clearTimeout(timer); - }, [largeList, dbInbounds, inboundGeneration, rollupForInbound]); + }, [scheduled]); const syncCounts = useMemo(() => { if (largeList) return EMPTY_ROLLUPS; @@ -483,9 +519,9 @@ export function useInbounds() { }, [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 rollupsReady = !largeList || computed?.work.generation === inboundGeneration; const clientCount = largeList - ? ((rollupsReady ? scheduled?.counts : undefined) ?? EMPTY_ROLLUPS) + ? ((rollupsReady ? computed?.counts : undefined) ?? EMPTY_ROLLUPS) : syncCounts; // Adopting fetched data during render (rather than in an effect) keeps the @@ -750,6 +786,9 @@ export function useInbounds() { dbInbounds, clientCount, clientCountsPending: !rollupsReady, + onlineAttributionError, + retryingOnlineAttribution, + retryOnlineAttribution, onlineClients, lastOnlineMap, inboundSpeed, diff --git a/frontend/src/test/inbounds-ws-identity.test.tsx b/frontend/src/test/inbounds-ws-identity.test.tsx index 70118871f..bcacb6af8 100644 --- a/frontend/src/test/inbounds-ws-identity.test.tsx +++ b/frontend/src/test/inbounds-ws-identity.test.tsx @@ -175,7 +175,50 @@ it('loads inbounds whose clientStats is null in the slim response', () => { expect(result.current.clientCount[2].clients).toBe(0); }); -it('withholds large inbound rollups until they match the refetched structure', async () => { +it('finishes a large rollup during live pushes and coalesces updates in the background', () => { + vi.useFakeTimers(); + let now = 0; + const clock = vi.spyOn(performance, 'now').mockImplementation(() => (now += 10)); + const { queryClient, rows, wrapper } = seedInbounds(); + const settings = JSON.stringify({ + clients: [{ email: 'c1@x', enable: true, comment: 'x'.repeat(35_000) }], + }); + const currentRows = Array.from({ length: 12 }, (_, i) => ({ + ...rows[0], + id: i + 1, + tag: `large-${i}`, + originNodeGuid: 'node-a', + settings, + })); + queryClient.setQueryData(keys.inbounds.slim(), currentRows); + queryClient.setQueryData(keys.clients.activeInbounds(), { + 'node-a': currentRows.map((row) => row.tag), + }); + const { result, unmount } = renderHook(() => useInbounds(), { wrapper }); + try { + expect(result.current.clientCountsPending).toBe(true); + for (let i = 0; i < 15; i++) { + act(() => { + result.current.applyTrafficEvent({ onlineByGuid: { 'node-a': [`noise-${i}`] } }); + result.current.applyClientStatsEvent({ inbounds: [{ id: 1, up: 11 + i }] }); + }); + act(() => vi.advanceTimersByTime(1)); + } + expect(result.current.clientCountsPending).toBe(false); + expect(result.current.clientCount[12].clients).toBe(1); + + act(() => result.current.applyTrafficEvent({ onlineByGuid: { 'node-a': ['c1@x'] } })); + expect(result.current.clientCountsPending).toBe(false); + for (let i = 0; i < 30; i++) act(() => vi.advanceTimersByTime(1)); + expect(result.current.clientCount[12].online).toEqual(['c1@x']); + } finally { + unmount(); + clock.mockRestore(); + vi.useRealTimers(); + } +}); + +it('withholds large inbound rollups until they match the refetched or hydrated structure', async () => { const { queryClient, rows, wrapper } = seedInbounds(); const withClients = (count: number, remark: string) => ({ ...rows[0], @@ -208,21 +251,30 @@ it('withholds large inbound rollups until they match the refetched structure', a { 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)])); + const expectSnapshot = async (count: number, remark: string, large: boolean) => { 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)) { + const views = displayed.filter((view) => view.remark === remark); + expect(views).toContainEqual({ remark, fetched: true, pending: false, count }); + if (large) + expect(views).toContainEqual({ remark, fetched: true, pending: true, count: undefined }); + for (const view of views) { expect(view.fetched).toBe(true); expect(view.count).toBe(view.pending ? undefined : count); } + }; + for (const [count, remark, large] of [ + [8000, 'large refetch', true], + [1, 'small refetch', false], + [9000, 'large again', true], + ] as const) { + act(() => queryClient.setQueryData(keys.inbounds.slim(), [withClients(count, remark)])); + await expectSnapshot(count, remark, large); } + vi.mocked(HttpUtil.get).mockResolvedValueOnce(new Msg(true, '', withClients(10000, 'hydrated'))); + await act(async () => { + expect(await result.current.hydrateInbound(seed.id)).not.toBeNull(); + }); + await expectSnapshot(10000, 'hydrated', true); }); it('keeps the search, node filter and selection through large-list refetch and detail hydration', async () => { @@ -385,12 +437,64 @@ it('does not attribute shared online clients without matching inbound activity', it('keeps online status pending while the activity query is unresolved', async () => { const { queryClient, wrapper } = seedInbounds(); queryClient.removeQueries({ queryKey: keys.clients.activeInbounds() }); - const post = vi.spyOn(HttpUtil, 'post').mockImplementation(() => new Promise(() => {})); + const post = vi.mocked(HttpUtil.post); + const fallback = post.getMockImplementation(); + post.mockImplementation(() => new Promise(() => {})); try { const { result } = renderHook(() => useInbounds(), { wrapper }); await waitFor(() => expect(result.current.clientCount[1].onlineAttribution).toBe('pending')); expect(result.current.clientCount[1].online).toEqual([]); } finally { - post.mockRestore(); + if (fallback) post.mockImplementation(fallback); } }); + +it.each(['onlinesByGuid', 'activeInbounds'] as const)( + 'retries failed %s attribution without reloading successful queries', + async (source) => { + const { queryClient, rows } = seedInbounds(); + queryClient.setQueryData(keys.inbounds.slim(), [{ ...rows[0], remark: 'Retry inbound' }]); + queryClient.setQueryDefaults(keys.nodes.list(), { staleTime: Infinity }); + queryClient.setQueryData(keys.nodes.list(), []); + queryClient.setQueryData(keys.hosts.list(), []); + queryClient.setQueryData(keys.clients.onlinesByGuid(), { 'node-1': [] }); + queryClient.setQueryData(keys.clients.activeInbounds(), { 'node-1': [] }); + queryClient.removeQueries({ queryKey: keys.clients[source](), exact: true }); + + let finishRetry!: (message: Msg) => void; + const pending = new Promise((resolve) => (finishRetry = resolve)); + const post = vi.mocked(HttpUtil.post); + const fallback = post.getMockImplementation(); + const retryEndpoint = `/panel/api/clients/${source}`; + const request = vi + .fn() + .mockResolvedValueOnce(new Msg(false, 'Unavailable')) + .mockReturnValueOnce(pending); + const otherRequests = vi.fn(fallback); + post.mockImplementation((url, ...args) => + url === retryEndpoint ? request() : otherRequests(url, ...args), + ); + const view = renderWithProviders( + + + , + { queryClient }, + ); + try { + const alert = await screen.findByRole('alert'); + const row = () => screen.getByRole('row', { name: /Retry inbound/ }); + expect(within(row()).queryByText(/^Online: 0$/i)).toBeNull(); + fireEvent.click(within(alert).getByRole('button', { name: 'Refresh' })); + await waitFor(() => expect(request).toHaveBeenCalledTimes(2)); + expect(screen.getByRole('alert')).toBe(alert); + await act(async () => finishRetry(new Msg(true, '', { 'node-1': [] }))); + await within(row()).findByText(/^Online: 0$/i); + expect(screen.queryByRole('alert')).toBeNull(); + expect(otherRequests).not.toHaveBeenCalled(); + } finally { + view.unmount(); + getSharedWebSocketClient().disconnect(); + if (fallback) post.mockImplementation(fallback); + } + }, +);