diff --git a/changes/54676-host-details-refetch-polling-stacks-on-tab-switch b/changes/54676-host-details-refetch-polling-stacks-on-tab-switch new file mode 100644 index 00000000000..5f8fff5c44d --- /dev/null +++ b/changes/54676-host-details-refetch-polling-stacks-on-tab-switch @@ -0,0 +1 @@ +- Fixed host details and the Welcome to Fleet card scheduling an extra polling loop on every tab switch during a refetch. diff --git a/changes/54677-host-details-refetch-timeout-restarts-on-tab-return b/changes/54677-host-details-refetch-timeout-restarts-on-tab-return new file mode 100644 index 00000000000..5c4337cbf9d --- /dev/null +++ b/changes/54677-host-details-refetch-timeout-restarts-on-tab-return @@ -0,0 +1 @@ +- Fixed host details and the Welcome to Fleet card restarting a refetch and repeating the timeout toast when the tab regained focus after a refetch had already timed out. diff --git a/frontend/pages/DashboardPage/cards/WelcomeHost/WelcomeHost.tests.tsx b/frontend/pages/DashboardPage/cards/WelcomeHost/WelcomeHost.tests.tsx index 324ab859940..9c5ae9f052e 100644 --- a/frontend/pages/DashboardPage/cards/WelcomeHost/WelcomeHost.tests.tsx +++ b/frontend/pages/DashboardPage/cards/WelcomeHost/WelcomeHost.tests.tsx @@ -112,4 +112,82 @@ describe("WelcomeHost - refetch give-up state", () => { // Still only the one call from the original give-up -- not a second one. expect(notify.error).toHaveBeenCalledTimes(1); }); + + // Each tab-focus re-entry into onSuccess used to schedule a fresh setTimeout + // next to the one already pending, so polling sped up. + it("does not stack polling loops when the tab regains focus mid-refetch", async () => { + jest.useFakeTimers({ doNotFake: ["queueMicrotask"] }); + let now = 1_700_000_000_000; + jest.spyOn(Date, "now").mockImplementation(() => now); + + (hostAPI.loadHostDetails as jest.Mock).mockResolvedValue({ + host: mockOnlineStuckRefetchHost(), + }); + + renderWelcomeHost(); + await screen.findByText("Antivirus healthy"); + + for (let i = 0; i < 3; i += 1) { + // eslint-disable-next-line no-await-in-loop + await act(async () => { + window.dispatchEvent(new Event("focus")); + window.dispatchEvent(new Event("visibilitychange")); + await jest.advanceTimersByTimeAsync(0); + }); + } + + const callsBeforeAdvance = (hostAPI.loadHostDetails as jest.Mock).mock.calls + .length; + + now += 1000; + await act(async () => { + await jest.advanceTimersByTimeAsync(1000); + }); + + const pollsInOneInterval = + (hostAPI.loadHostDetails as jest.Mock).mock.calls.length - + callsBeforeAdvance; + expect(pollsInOneInterval).toBe(1); + }); + + // After give-up, a focus-triggered onSuccess used to re-enter the "timer + // just started" branch, open a fresh 60s cycle, and fire the toast again + // 60s later. + it("doesn't restart the refetch window after a timeout when the tab regains focus", async () => { + jest.useFakeTimers({ doNotFake: ["queueMicrotask"] }); + let now = 1_700_000_000_000; + jest.spyOn(Date, "now").mockImplementation(() => now); + + (hostAPI.loadHostDetails as jest.Mock).mockResolvedValue({ + host: mockOnlineStuckRefetchHost(), + }); + + renderWelcomeHost(); + await screen.findByText("Antivirus healthy"); + + // Trip the give-up branch on the first polling tick. + now += 61000; + await act(async () => { + await jest.advanceTimersByTimeAsync(1000); + }); + + await waitFor(() => { + expect(notify.error).toHaveBeenCalledTimes(1); + }); + + // Tab switch, then let a full fresh 60s window elapse. Without the fix, + // the focus-triggered onSuccess restarts a new cycle and the toast fires + // a second time around now. + await act(async () => { + window.dispatchEvent(new Event("focus")); + window.dispatchEvent(new Event("visibilitychange")); + await jest.advanceTimersByTimeAsync(0); + }); + now += 65000; + await act(async () => { + await jest.advanceTimersByTimeAsync(1000); + }); + + expect(notify.error).toHaveBeenCalledTimes(1); + }); }); diff --git a/frontend/pages/DashboardPage/cards/WelcomeHost/WelcomeHost.tsx b/frontend/pages/DashboardPage/cards/WelcomeHost/WelcomeHost.tsx index 35f413472e5..30f4ed16c81 100644 --- a/frontend/pages/DashboardPage/cards/WelcomeHost/WelcomeHost.tsx +++ b/frontend/pages/DashboardPage/cards/WelcomeHost/WelcomeHost.tsx @@ -1,4 +1,4 @@ -import React, { useState } from "react"; +import React, { useRef, useState } from "react"; import { useQuery } from "react-query"; import Button from "components/buttons/Button"; @@ -37,6 +37,12 @@ const WelcomeHost = ({ const [showRefetchLoadingSpinner, setShowRefetchLoadingSpinner] = useState( false ); + // Pending next-poll timer; cleared before scheduling a new one so a focus-triggered + // onSuccess re-entry replaces the pending poll instead of stacking. + const pollingTimerRef = useRef(null); + // True once the current refetch cycle has given up; blocks the restart path in + // onSuccess when the server still reports refetch_requested: true. + const didTimeOutRef = useRef(false); /** * Hides refetch spinner and resets refetch timer, @@ -45,6 +51,20 @@ const WelcomeHost = ({ const resetHostRefetchStates = () => { setShowRefetchLoadingSpinner(false); setRefetchStartTime(null); + if (pollingTimerRef.current) { + clearTimeout(pollingTimerRef.current); + pollingTimerRef.current = null; + } + }; + + const scheduleNextPoll = (fn: () => void) => { + if (pollingTimerRef.current) { + clearTimeout(pollingTimerRef.current); + } + pollingTimerRef.current = setTimeout(() => { + pollingTimerRef.current = null; + fn(); + }, 1000); }; const { @@ -59,43 +79,51 @@ const WelcomeHost = ({ retry: false, select: (data: IHostResponse) => data.host, onSuccess: (returnedHost) => { - setShowRefetchLoadingSpinner(returnedHost.refetch_requested); - const anyPassingOrFailingPolicy = returnedHost?.policies?.find( (p) => p.response === POLICY_PASS || p.response === POLICY_FAIL ); setIsPoliciesEmpty(typeof anyPassingOrFailingPolicy === "undefined"); - if (returnedHost.refetch_requested) { - // Code duplicated from HostDetailsPage. See comments there. - if (!refetchStartTime) { - if (returnedHost.status === "online") { - setRefetchStartTime(Date.now()); - setTimeout(() => { - fullyReloadHost(); - }, 1000); - } else { - resetHostRefetchStates(); - } + if (!returnedHost.refetch_requested) { + didTimeOutRef.current = false; + resetHostRefetchStates(); + return; + } + + // Previous cycle gave up and server still reports refetch_requested: true. + // Skip the restart path so a focus-triggered re-entry doesn't open a fresh + // 60s window + repeat toast. + if (didTimeOutRef.current && !refetchStartTime) { + return; + } + + setShowRefetchLoadingSpinner(true); + + // Code duplicated from HostDetailsPage. See comments there. + if (!refetchStartTime) { + if (returnedHost.status === "online") { + setRefetchStartTime(Date.now()); + scheduleNextPoll(fullyReloadHost); } else { - const totalElapsedTime = Date.now() - refetchStartTime; - if (totalElapsedTime < 60000) { - if (returnedHost.status === "online") { - setTimeout(() => { - fullyReloadHost(); - }, 1000); - } else { - notify.error( - `This host is offline. Please try refetching host vitals later.` - ); - resetHostRefetchStates(); - } + resetHostRefetchStates(); + } + } else { + const totalElapsedTime = Date.now() - refetchStartTime; + if (totalElapsedTime < 60000) { + if (returnedHost.status === "online") { + scheduleNextPoll(fullyReloadHost); } else { notify.error( - `Refetch sent but vitals are taking longer than expected to load. You’ll see an update when the host responds.` + `This host is offline. Please try refetching host vitals later.` ); resetHostRefetchStates(); } + } else { + notify.error( + `Refetch sent but vitals are taking longer than expected to load. You’ll see an update when the host responds.` + ); + didTimeOutRef.current = true; + resetHostRefetchStates(); } } }, @@ -111,8 +139,9 @@ const WelcomeHost = ({ try { await hostAPI.refetch(host).then(() => { + didTimeOutRef.current = false; setRefetchStartTime(Date.now()); - setTimeout(() => fullyReloadHost(), 1000); + scheduleNextPoll(fullyReloadHost); }); } catch (error) { console.error(error); diff --git a/frontend/pages/hosts/details/HostDetailsPage/HostDetailsPage.tests.tsx b/frontend/pages/hosts/details/HostDetailsPage/HostDetailsPage.tests.tsx index 8f264eead12..c9bf5a9b382 100644 --- a/frontend/pages/hosts/details/HostDetailsPage/HostDetailsPage.tests.tsx +++ b/frontend/pages/hosts/details/HostDetailsPage/HostDetailsPage.tests.tsx @@ -479,6 +479,108 @@ describe("HostDetailsPage - disk encryption key rotation", () => { }); }); +describe("HostDetailsPage - refetch cycle on tab switch", () => { + const mockOnlineStuckHost = (): IHost => + createMockHost({ + id: 1, + platform: "darwin", + status: "online", + refetch_requested: true, + }); + + afterEach(() => { + jest.useRealTimers(); + jest.restoreAllMocks(); + jest.resetAllMocks(); + }); + + // Each tab-focus re-entry into onSuccess used to schedule a fresh setTimeout + // next to the one already pending, so polling sped up. + it("does not stack polling loops when the tab regains focus mid-refetch", async () => { + stubQueries(mockOnlineStuckHost()); + + jest.useFakeTimers({ doNotFake: ["queueMicrotask"] }); + const start = 1_700_000_000_000; + let now = start; + jest.spyOn(Date, "now").mockImplementation(() => now); + + renderHostDetails(); + await screen.findByText("Vitals"); + + // Dispatch three window-focus events (react-query's refetchOnWindowFocus + // trigger). Each one re-enters onSuccess. + for (let i = 0; i < 3; i += 1) { + // eslint-disable-next-line no-await-in-loop + await act(async () => { + window.dispatchEvent(new Event("focus")); + window.dispatchEvent(new Event("visibilitychange")); + await jest.advanceTimersByTimeAsync(0); + }); + } + + const callsBeforeAdvance = (hostAPI.loadHostDetails as jest.Mock).mock.calls + .length; + + // One polling interval. With the fix, exactly one scheduled poll fires in + // this window. Without it, each stacked timer fires an extra request. + now += 2000; + await act(async () => { + await jest.advanceTimersByTimeAsync(2000); + }); + + const pollsInOneInterval = + (hostAPI.loadHostDetails as jest.Mock).mock.calls.length - + callsBeforeAdvance; + expect(pollsInOneInterval).toBe(1); + }); + + // After give-up, the server still reports refetch_requested: true, so a + // focus-triggered onSuccess used to re-enter the "timer just started" branch + // and run a fresh 60s cycle (new toast 60s later). + it("doesn't restart the refetch window after a timeout when the tab regains focus", async () => { + jest.useFakeTimers({ doNotFake: ["queueMicrotask"] }); + const start = 1_700_000_000_000; + let now = start; + jest.spyOn(Date, "now").mockImplementation(() => now); + + stubQueries(mockOnlineStuckHost()); + (hostAPI.loadHostDetails as jest.Mock).mockResolvedValue({ + host: mockOnlineStuckHost(), + }); + + renderHostDetails(); + await screen.findByText("Vitals"); + + // Advance past the 60s give-up window so the next polling tick fires the toast. + now += 61000; + await act(async () => { + await jest.advanceTimersByTimeAsync(2000); + }); + + await waitFor(() => { + expect(notify.error).toHaveBeenCalledWith( + "Refetch sent but vitals are taking longer than expected to load. You’ll see an update when the host responds." + ); + }); + expect(notify.error).toHaveBeenCalledTimes(1); + + // Simulate a tab switch and let a full fresh 60s + 2s poll interval pass. + // Without the fix, this re-enters the "timer just started" branch, opens a + // new 60s cycle, and 60s later shows the toast a second time. + await act(async () => { + window.dispatchEvent(new Event("focus")); + window.dispatchEvent(new Event("visibilitychange")); + await jest.advanceTimersByTimeAsync(0); + }); + now += 65000; + await act(async () => { + await jest.advanceTimersByTimeAsync(2000); + }); + + expect(notify.error).toHaveBeenCalledTimes(1); + }); +}); + describe("HostDetailsPage - enrollment rejection details", () => { afterEach(() => { jest.resetAllMocks(); diff --git a/frontend/pages/hosts/details/HostDetailsPage/HostDetailsPage.tsx b/frontend/pages/hosts/details/HostDetailsPage/HostDetailsPage.tsx index ae43d22cb61..05952e9714d 100644 --- a/frontend/pages/hosts/details/HostDetailsPage/HostDetailsPage.tsx +++ b/frontend/pages/hosts/details/HostDetailsPage/HostDetailsPage.tsx @@ -5,6 +5,7 @@ import React, { useCallback, useMemo, useEffect, + useRef, } from "react"; import { useErrorHandler } from "react-error-boundary"; import { useQuery, useQueryClient } from "react-query"; @@ -378,6 +379,13 @@ const HostDetailsPage = ({ refetchStart?.hostId === hostIdFromURL ? refetchStart.at : null; const isUserRequestedRefetch = refetchStart?.hostId === hostIdFromURL && refetchStart.byUser; + // Holds the pending next-poll timer so a focus-triggered re-entry into + // `onSuccess` can replace it instead of stacking a second loop. + const pollingTimerRef = useRef(null); + // Last hostId whose refetch cycle timed out. Blocks the focus-triggered + // "timer just started" branch from restarting a cycle on a stale server + // `refetch_requested: true` after give-up. + const timedOutHostIdRef = useRef(null); const [showRefetchSpinner, setShowRefetchSpinner] = useState(false); const [usersState, setUsersState] = useState<{ username: string }[]>([]); const [usersSearchString, setUsersSearchString] = useState(""); @@ -489,6 +497,15 @@ const HostDetailsPage = ({ hostCertificates && refetchHostCertificates(); }; + // Clears any pending next-poll timer so re-entries into onSuccess (e.g. react-query's + // refetchOnWindowFocus) replace the existing timer instead of stacking. + const clearPollingTimer = () => { + if (pollingTimerRef.current) { + clearTimeout(pollingTimerRef.current); + pollingTimerRef.current = null; + } + }; + /** * Hides refetch spinner and resets refetch timer, * ensuring no stale timeout triggers on new requests. @@ -496,6 +513,20 @@ const HostDetailsPage = ({ const resetHostRefetchStates = () => { setShowRefetchSpinner(false); setRefetchStart(null); + clearPollingTimer(); + }; + + // Replaces any pending timer, then schedules the next poll. refetchHostDetails / + // refetchExtensions are bound at call time (always after mount), so the forward + // references are safe. + const scheduleNextPoll = () => { + clearPollingTimer(); + pollingTimerRef.current = setTimeout(() => { + pollingTimerRef.current = null; + // eslint-disable-next-line @typescript-eslint/no-use-before-define + refetchHostDetails(); + refetchExtensions(); + }, REFETCH_HOST_DETAILS_POLLING_INTERVAL); }; const { @@ -510,6 +541,22 @@ const HostDetailsPage = ({ retry: false, select: (data: IHostResponse) => data.host, onSuccess: (returnedHost) => { + // Server flipped THIS host's refetch_requested back to false, so a prior + // timeout for this host is no longer "sticky". Scope the clear to the + // current host so navigating A (timed out) -> B -> A doesn't forget A's + // timeout and restart its cycle. + if ( + !returnedHost.refetch_requested && + timedOutHostIdRef.current === hostIdFromURL + ) { + timedOutHostIdRef.current = null; + } + // If this host's previous refetch cycle gave up and the server still reports + // refetch_requested: true (common with slow hosts), skip the restart path so a + // focus-triggered re-entry doesn't open a fresh 60s window + repeat toast. + const alreadyTimedOut = + timedOutHostIdRef.current === hostIdFromURL && + refetchStartTime === null; // If API returns refetch_requested: true, // only set timer if *not* already set! // Pending hosts carry the flag from the moment they're created, so ignore it unless the host has enrolled and @@ -517,7 +564,8 @@ const HostDetailsPage = ({ // so an explicit request still gets its spinner and its feedback. if ( returnedHost.refetch_requested && - (hasEverEnrolled(returnedHost) || refetchStartTime !== null) + (hasEverEnrolled(returnedHost) || refetchStartTime !== null) && + !alreadyTimedOut ) { if (!refetchStartTime) { setRefetchStart({ @@ -543,10 +591,7 @@ const HostDetailsPage = ({ returnedHost.status === "online" || isIPadOrIPhone(returnedHost.platform) ) { - setTimeout(() => { - refetchHostDetails(); - refetchExtensions(); - }, REFETCH_HOST_DETAILS_POLLING_INTERVAL); + scheduleNextPoll(); } else { resetHostRefetchStates(); } @@ -556,10 +601,7 @@ const HostDetailsPage = ({ returnedHost.status === "online" || isIPadOrIPhone(returnedHost.platform) ) { - setTimeout(() => { - refetchHostDetails(); - refetchExtensions(); - }, REFETCH_HOST_DETAILS_POLLING_INTERVAL); + scheduleNextPoll(); } else { if (shouldNotify) { notify.error( @@ -575,6 +617,7 @@ const HostDetailsPage = ({ `Refetch sent but vitals are taking longer than expected to load. You’ll see an update when the host responds.` ); } + timedOutHostIdRef.current = hostIdFromURL; resetHostRefetchStates(); } } @@ -893,15 +936,13 @@ const HostDetailsPage = ({ try { await hostAPI.refetch(host).then(() => { + timedOutHostIdRef.current = null; setRefetchStart({ hostId: hostIdFromURL, at: Date.now(), byUser: true, }); - setTimeout(() => { - refetchHostDetails(); - refetchExtensions(); - }, REFETCH_HOST_DETAILS_POLLING_INTERVAL); + scheduleNextPoll(); }); } catch (error) { notify.error(getErrorMessage(error, host.display_name), {