diff --git a/src/renderer/components/GlobalEffects.test.tsx b/src/renderer/components/GlobalEffects.test.tsx
index 1c25503a7..bdcbc346e 100644
--- a/src/renderer/components/GlobalEffects.test.tsx
+++ b/src/renderer/components/GlobalEffects.test.tsx
@@ -38,6 +38,15 @@ describe('renderer/components/GlobalEffects.tsx', () => {
expect(setTrayIconColorAndTitleSpy).toHaveBeenCalledWith(-1, true);
});
+ it('does not report an error to the tray while an online query is paused', async () => {
+ await act(async () => {
+ renderWithProviders(, { status: 'paused', notificationCount: 3 });
+ });
+
+ expect(setTrayIconColorAndTitleSpy).toHaveBeenCalledWith(3, true);
+ expect(setTrayIconColorAndTitleSpy).not.toHaveBeenCalledWith(-1, true);
+ });
+
it('resets all stores when the app is reset', async () => {
await act(async () => {
renderWithProviders(, {
diff --git a/src/renderer/components/GlobalEffects.tsx b/src/renderer/components/GlobalEffects.tsx
index 5aee33442..3d2f7eed8 100644
--- a/src/renderer/components/GlobalEffects.tsx
+++ b/src/renderer/components/GlobalEffects.tsx
@@ -36,7 +36,7 @@ export function GlobalEffects() {
const useUnreadActiveIcon = useSettingsStore((s) => s.useUnreadActiveIcon);
const trayIconAppearance = useSettingsStore((s) => s.trayIconAppearance);
- const isOnline = useOnlineStatus();
+ const isNetworkOnline = useOnlineStatus();
// Appearance side effects: color mode/scheme + design-language/material attributes
useAppearance();
@@ -57,14 +57,14 @@ export function GlobalEffects() {
// oxlint-disable-next-line react/exhaustive-deps -- We want to update the tray on setting or notification changes
useEffect(() => {
const trayCount = status === 'error' ? -1 : notificationCount;
- setTrayIconColorAndTitle(trayCount, isOnline);
+ setTrayIconColorAndTitle(trayCount, isNetworkOnline);
}, [
showNotificationsCountInTray,
useUnreadActiveIcon,
trayIconAppearance,
status,
notificationCount,
- isOnline,
+ isNetworkOnline,
]);
useEffect(() => {
diff --git a/src/renderer/hooks/notifications/useNotificationsQuery.ts b/src/renderer/hooks/notifications/useNotificationsQuery.ts
index 2d0a13cd0..9e7f544f5 100644
--- a/src/renderer/hooks/notifications/useNotificationsQuery.ts
+++ b/src/renderer/hooks/notifications/useNotificationsQuery.ts
@@ -13,6 +13,7 @@ import {
import type { AccountNotifications, GitifyError, GitifyNotification, Status } from '../../types';
+import { doesAllAccountsHaveErrors } from '../../utils/core/errors';
import {
filterBaseNotifications,
filterDetailedNotifications,
@@ -24,6 +25,7 @@ import {
} from '../../utils/notifications/notifications';
import { computeRefetchIntervalMs } from '../../utils/notifications/pollInterval';
import { deriveGlobalError, deriveStatus } from '../../utils/notifications/status';
+import { getNetworkStatus, useNetworkStatus } from '../useOnlineStatus';
import { useNotificationsQueryKey } from './useNotificationsQueryKey';
export interface NotificationsQueryResult {
@@ -56,6 +58,29 @@ function keepNonEmptyPreviousData(
: undefined;
}
+async function fetchNotificationsWithReconnect() {
+ const connectionAtStart = getNetworkStatus();
+ const hasReconnected = () => {
+ const currentConnection = getNetworkStatus();
+ return currentConnection.isOnline && currentConnection !== connectionAtStart;
+ };
+
+ try {
+ const notifications = await getAllNotifications();
+ if (!doesAllAccountsHaveErrors(notifications) || !hasReconnected()) {
+ return notifications;
+ }
+ } catch (error) {
+ if (!hasReconnected()) {
+ throw error;
+ }
+ }
+
+ // TanStack reuses the in-flight request on reconnect. If that request failed,
+ // make one fresh attempt before committing a failed result to the cache.
+ return getAllNotifications();
+}
+
/**
* The read side of notification state: the TanStack Query observer (optionally
* polling), the filter projection, derived counts, and the derived status and
@@ -66,6 +91,8 @@ function keepNonEmptyPreviousData(
* entry but schedule nothing. See `useNotificationsHost`.
*/
export const useNotificationsQuery = ({ poll }: { poll: boolean }): NotificationsQueryResult => {
+ const { isOnline: isNetworkOnline, reconnectedAt } = useNetworkStatus();
+
// Account store values
const accounts = useAccountsStore((s) => s.accounts);
const isPowerActive = usePowerStateStore((s) => s.isActive);
@@ -113,17 +140,18 @@ export const useNotificationsQuery = ({ poll }: { poll: boolean }): Notification
// Query for fetching notifications - TanStack Query handles polling and refetching
const {
data: notifications = [],
+ dataUpdatedAt,
+ errorUpdatedAt,
isLoading,
isFetching,
isError,
+ isPending,
isPaused,
refetch,
} = useQuery({
queryKey: notificationsQueryKey,
- queryFn: async () => {
- return await getAllNotifications();
- },
+ queryFn: fetchNotificationsWithReconnect,
// Apply filters as a transformation on the cached data
// This allows filter changes to instantly update without refetching
@@ -136,8 +164,8 @@ export const useNotificationsQuery = ({ poll }: { poll: boolean }): Notification
// occurred. Uses the static floor rather than the live interval because
// the latter stretches with `X-Poll-Interval`; pinning staleTime to it
// would suppress mount/focus/reconnect refetches for as long as a forge
- // asks Gitify to back off. Only those refetches are stale-gated - the
- // poll itself fires on `refetchInterval` regardless.
+ // asks Gitify to back off. The poll itself fires on `refetchInterval`
+ // regardless; reconnect also bypasses this guard for failed results.
staleTime: Constants.MIN_FETCH_NOTIFICATIONS_INTERVAL_MS,
// Only the singleton host observer polls. Other consumers share the cached
@@ -147,7 +175,12 @@ export const useNotificationsQuery = ({ poll }: { poll: boolean }): Notification
refetchInterval:
poll && isPowerActive ? () => computeRefetchIntervalMs(fetchIntervalMs, accounts) : false,
refetchOnMount: poll,
- refetchOnReconnect: poll,
+ // Retry an errored result on reconnect even if it's still fresh. Successful
+ // results retain the usual stale-time guard.
+ refetchOnReconnect:
+ poll &&
+ (({ state }) =>
+ state.status === 'error' || doesAllAccountsHaveErrors(state.data ?? []) ? 'always' : true),
refetchOnWindowFocus: poll,
});
@@ -162,18 +195,23 @@ export const useNotificationsQuery = ({ poll }: { poll: boolean }): Notification
[unreadNotificationCount],
);
- // Determine status and globalError from query state. Only the initial
- // fetch (no settled success or error yet) reports 'loading' - background
- // refetches of already-settled data keep their settled status so
- // consumers like the tray icon don't flicker on every poll/retry.
- const status: Status = useMemo(
- () => deriveStatus({ isLoading, isPaused, isError, notifications }),
- [isLoading, isPaused, isError, notifications],
- );
+ // Query keeps the previous result during a refetch. Use the same timestamps
+ // for every observer, including one mounted halfway through the reconnect.
+ const lastResultAt = isError ? errorUpdatedAt : dataUpdatedAt;
+ const isRecovering = reconnectedAt !== undefined && lastResultAt < reconnectedAt;
+ const status = deriveStatus({
+ isNetworkOnline,
+ isLoading,
+ isPending,
+ isPaused,
+ isRecovering,
+ isError,
+ notifications,
+ });
const globalError: GitifyError | undefined = useMemo(
- () => deriveGlobalError({ isPaused, notifications }),
- [isPaused, notifications],
+ () => deriveGlobalError({ status, notifications }),
+ [status, notifications],
);
return {
diff --git a/src/renderer/hooks/useNotifications.test.tsx b/src/renderer/hooks/useNotifications.test.tsx
index d871c43af..fe050a8dc 100644
--- a/src/renderer/hooks/useNotifications.test.tsx
+++ b/src/renderer/hooks/useNotifications.test.tsx
@@ -1,7 +1,12 @@
import { act, renderHook, waitFor } from '@testing-library/react';
import type { ReactNode } from 'react';
-import { focusManager, QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import {
+ focusManager,
+ onlineManager,
+ QueryClient,
+ QueryClientProvider,
+} from '@tanstack/react-query';
import {
mockGitHubCloudAccount,
@@ -30,7 +35,7 @@ import {
useSettingsStore,
} from '../stores';
-import type { AccountNotifications, Percentage } from '../types';
+import type { AccountNotifications, Percentage, Status } from '../types';
import { getAccountUUID } from '../utils/auth/utils';
import { getErrorDetails } from '../utils/core/errors';
@@ -66,11 +71,12 @@ vi.mock('../utils/notifications/notifications', async () => {
const getAllNotificationsMock = vi.mocked(notificationsUtils.getAllNotifications);
const refreshEnrichmentCacheMock = vi.mocked(notificationsUtils.refreshEnrichmentCache);
-const createWrapper = () => {
+const createWrapper = (retry: number | false = false) => {
const queryClient = new QueryClient({
defaultOptions: {
queries: {
- retry: false,
+ retry,
+ retryDelay: 0,
refetchOnWindowFocus: false,
refetchInterval: false,
},
@@ -208,6 +214,148 @@ describe('renderer/hooks/useNotifications.ts', () => {
});
});
+ describe('notification connectivity', () => {
+ const cachedFailure: AccountNotifications[] = [
+ {
+ account: mockGitHubCloudAccount,
+ notifications: [],
+ error: getErrorDetails('NETWORK'),
+ },
+ ];
+
+ afterEach(() => {
+ onlineManager.setOnline(true);
+ focusManager.setFocused(undefined);
+ });
+
+ it('does not report offline when a retry waits for a hidden window', async () => {
+ onlineManager.setOnline(true);
+ focusManager.setFocused(false);
+ getAllNotificationsMock
+ .mockRejectedValueOnce(new Error('first attempt failed'))
+ .mockResolvedValueOnce(mockSingleAccountNotifications);
+
+ const { result } = renderHook(() => useNotifications(), { wrapper: createWrapper(1) });
+
+ await waitFor(() => expect(result.current.status).toBe('paused'));
+ expect(result.current.globalError).toBeUndefined();
+ expect(getAllNotificationsMock).toHaveBeenCalledTimes(1);
+
+ act(() => focusManager.setFocused(true));
+
+ await waitFor(() => expect(result.current.status).toBe('success'));
+ expect(getAllNotificationsMock).toHaveBeenCalledTimes(2);
+ });
+
+ it.each([
+ { pauseBeforeReconnect: true, fails: false },
+ { pauseBeforeReconnect: false, fails: true },
+ ])(
+ 'hides stale failures during reconnect ($pauseBeforeReconnect paused, $fails fails)',
+ async ({ pauseBeforeReconnect, fails }) => {
+ onlineManager.setOnline(true);
+ getAllNotificationsMock.mockResolvedValueOnce(cachedFailure);
+ const renders: Status[] = [];
+ const { result } = renderHook(
+ () => {
+ const state = useNotificationsHost();
+ renders.push(state.status);
+ return state;
+ },
+ { wrapper: createWrapper() },
+ );
+
+ await waitFor(() => expect(result.current.status).toBe('error'));
+ expect(result.current.globalError?.type).toBe('NETWORK');
+
+ act(() => onlineManager.setOnline(false));
+ expect(result.current.status).toBe('offline');
+ if (pauseBeforeReconnect) {
+ act(() => void result.current.refetchNotifications());
+ }
+ expect(getAllNotificationsMock).toHaveBeenCalledTimes(1);
+
+ const { promise, resolve } = Promise.withResolvers();
+ getAllNotificationsMock.mockReturnValueOnce(promise);
+ renders.length = 0;
+ act(() => onlineManager.setOnline(true));
+
+ await waitFor(() => expect(result.current.isFetching).toBe(true));
+ expect(result.current.status).toBe('loading');
+ expect(result.current.globalError).toBeUndefined();
+ expect(renders).not.toContain('error');
+ expect(getAllNotificationsMock).toHaveBeenCalledTimes(2);
+
+ await act(async () => {
+ resolve(fails ? cachedFailure : mockSingleAccountNotifications);
+ });
+ await waitFor(() => {
+ expect(result.current.status).toBe(fails ? 'error' : 'success');
+ });
+ expect(result.current.globalError?.type).toBe(fails ? 'NETWORK' : undefined);
+ },
+ );
+
+ it.each([
+ { outcome: 'account failure', retryFails: false },
+ { outcome: 'request rejection', retryFails: true },
+ { outcome: 'success', retryFails: false },
+ ])(
+ 'handles $outcome from a poll already in flight at reconnect',
+ async ({ outcome, retryFails }) => {
+ const shouldRetry = outcome !== 'success';
+ onlineManager.setOnline(true);
+ getAllNotificationsMock.mockResolvedValueOnce(cachedFailure);
+ const renders: Status[] = [];
+ const { result } = renderHook(
+ () => {
+ const state = useNotificationsHost();
+ renders.push(state.status);
+ return state;
+ },
+ { wrapper: createWrapper() },
+ );
+ await waitFor(() => expect(result.current.status).toBe('error'));
+
+ const poll = Promise.withResolvers();
+ const retry = Promise.withResolvers();
+ getAllNotificationsMock
+ .mockReturnValueOnce(poll.promise)
+ .mockReturnValueOnce(retry.promise);
+ act(() => void result.current.refetchNotifications());
+ await waitFor(() => expect(result.current.isFetching).toBe(true));
+
+ act(() => onlineManager.setOnline(false));
+ expect(result.current.status).toBe('offline');
+ renders.length = 0;
+ await act(async () => onlineManager.setOnline(true));
+ expect(getAllNotificationsMock).toHaveBeenCalledTimes(2);
+
+ await act(async () => {
+ if (outcome === 'request rejection') {
+ poll.reject(new Error('request dropped during outage'));
+ } else {
+ poll.resolve(outcome === 'success' ? mockSingleAccountNotifications : cachedFailure);
+ }
+ });
+
+ await waitFor(() =>
+ expect(result.current.status).toBe(shouldRetry ? 'loading' : 'success'),
+ );
+ expect(result.current.isFetching).toBe(shouldRetry);
+ expect(getAllNotificationsMock).toHaveBeenCalledTimes(shouldRetry ? 3 : 2);
+ expect(result.current.globalError).toBeUndefined();
+ expect(renders).not.toContain('error');
+
+ await act(async () =>
+ retry.resolve(retryFails ? cachedFailure : mockSingleAccountNotifications),
+ );
+ await waitFor(() => expect(result.current.status).toBe(retryFails ? 'error' : 'success'));
+ expect(getAllNotificationsMock).toHaveBeenCalledTimes(shouldRetry ? 3 : 2);
+ },
+ );
+ });
+
describe('account set changes', () => {
it('reports loading when a new account set starts from an empty settled result', async () => {
useAccountsStore.setState({ accounts: [] });
diff --git a/src/renderer/hooks/useOnlineStatus.ts b/src/renderer/hooks/useOnlineStatus.ts
index 2110ee37c..563d39b13 100644
--- a/src/renderer/hooks/useOnlineStatus.ts
+++ b/src/renderer/hooks/useOnlineStatus.ts
@@ -1,35 +1,40 @@
-import { useEffect, useState } from 'react';
+import { useEffect, useSyncExternalStore } from 'react';
import { onlineManager } from '@tanstack/react-query';
+// Record transitions once, even when no React observer is mounted yet.
+let networkStatus = {
+ isOnline: onlineManager.isOnline(),
+ reconnectedAt: undefined as number | undefined,
+};
+
+onlineManager.subscribe((isOnline) => {
+ networkStatus = {
+ isOnline,
+ reconnectedAt: isOnline ? Date.now() : networkStatus.reconnectedAt,
+ };
+});
+
+const subscribe = (onChange: () => void) => onlineManager.subscribe(onChange);
+export const getNetworkStatus = () => networkStatus;
+
+export function useNetworkStatus() {
+ return useSyncExternalStore(subscribe, getNetworkStatus);
+}
+
/**
* Hook exposing the application's online / offline status, backed by
* TanStack Query's onlineManager so it stays consistent with query
* pause/resume behaviour.
*/
export function useOnlineStatus(): boolean {
- const [isOnline, setIsOnline] = useState(() => onlineManager.isOnline());
+ const { isOnline } = useNetworkStatus();
useEffect(() => {
- const handle = () => {
- setIsOnline(onlineManager.isOnline());
- };
-
- // Subscribe and call immediately to set initial status
- const unsubscribe = onlineManager.subscribe(handle);
- handle();
-
// Re-probe network state when the system wakes from sleep or the user
// unlocks their screen. The browser's online/offline events may not have
// fired yet by the time the renderer runs after a sleep cycle.
- const unsubscribeWake = window.gitify.onSystemWake(() =>
- onlineManager.setOnline(navigator.onLine),
- );
-
- return () => {
- unsubscribe();
- unsubscribeWake();
- };
+ return window.gitify.onSystemWake(() => onlineManager.setOnline(navigator.onLine));
}, []);
return isOnline;
diff --git a/src/renderer/routes/Notifications.test.tsx b/src/renderer/routes/Notifications.test.tsx
index d006dda72..1885963e9 100644
--- a/src/renderer/routes/Notifications.test.tsx
+++ b/src/renderer/routes/Notifications.test.tsx
@@ -70,14 +70,14 @@ describe('renderer/routes/Notifications.tsx', () => {
expect(screen.queryByText('Loading')).not.toBeInTheDocument();
});
- it('prefers the offline state over loading', () => {
+ it('shows loading rather than an offline error for a paused online query', () => {
renderWithProviders(, {
- isOnline: false,
- status: 'loading',
+ status: 'paused',
});
- expect(screen.getByText('Oops')).toBeInTheDocument();
- expect(screen.queryByText('Loading')).not.toBeInTheDocument();
+ expect(screen.getByText('Loading')).toBeInTheDocument();
+ expect(screen.queryByText('Oops')).not.toBeInTheDocument();
+ expect(screen.queryByText('AllRead')).not.toBeInTheDocument();
});
it('prefers the error state over loading', () => {
@@ -101,7 +101,7 @@ describe('renderer/routes/Notifications.tsx', () => {
it('renders offline error when not online', () => {
renderWithProviders(, {
- isOnline: false,
+ status: 'offline',
});
expect(screen.getByText('Oops')).toBeInTheDocument();
diff --git a/src/renderer/routes/Notifications.tsx b/src/renderer/routes/Notifications.tsx
index 93441ddc5..87fc6f07a 100644
--- a/src/renderer/routes/Notifications.tsx
+++ b/src/renderer/routes/Notifications.tsx
@@ -1,7 +1,6 @@
import { useMemo } from 'react';
import { useNotifications } from '../hooks/useNotifications';
-import { useOnlineStatus } from '../hooks/useOnlineStatus';
import { useAccountsStore, useFiltersStore, useSettingsStore } from '../stores';
import { AllRead } from '../components/AllRead';
@@ -16,7 +15,6 @@ import { hasNoAccountErrors } from '../utils/notifications/status';
export function NotificationsRoute() {
const { notifications, status, globalError, hasNotifications } = useNotifications();
- const isOnline = useOnlineStatus();
const filteredAccounts = useFiltersStore((s) => s.accounts);
const showAccountHeader = useSettingsStore((s) => s.showAccountHeader);
@@ -35,7 +33,7 @@ export function NotificationsRoute() {
[visibleNotifications],
);
- if (!isOnline) {
+ if (status === 'offline') {
return ;
}
@@ -43,7 +41,7 @@ export function NotificationsRoute() {
return ;
}
- if (status === 'loading') {
+ if (status === 'loading' || status === 'paused') {
return ;
}
diff --git a/src/renderer/routes/NotificationsStates.visual.test.tsx b/src/renderer/routes/NotificationsStates.visual.test.tsx
index e63d605da..44b23f057 100644
--- a/src/renderer/routes/NotificationsStates.visual.test.tsx
+++ b/src/renderer/routes/NotificationsStates.visual.test.tsx
@@ -2,7 +2,7 @@ import { waitFor } from '@testing-library/react';
import { page } from 'vite-plus/test/browser';
-import { setIsOnlineOverride, setNotificationsOverrides } from '../__helpers__/hook-mocks';
+import { setNotificationsOverrides } from '../__helpers__/hook-mocks';
import { renderRoute } from '../__helpers__/visual-utils';
import { mockGitHubCloudAccount } from '../__mocks__/account-mocks';
@@ -34,7 +34,7 @@ const STATES = [
{
name: 'offline',
heading: 'Network Offline',
- prepare: () => setIsOnlineOverride(false),
+ prepare: () => setNotificationsOverrides({ status: 'offline' }),
},
{
name: 'error',
diff --git a/src/renderer/types.ts b/src/renderer/types.ts
index 2fb4c5d4e..05dc78ee7 100644
--- a/src/renderer/types.ts
+++ b/src/renderer/types.ts
@@ -52,7 +52,7 @@ export function toLinkOrNull(value: string | null | undefined): Link | null {
export type SearchToken = Branded;
-export type Status = 'loading' | 'success' | 'error';
+export type Status = 'loading' | 'offline' | 'paused' | 'success' | 'error';
export type Percentage = Branded;
diff --git a/src/renderer/utils/notifications/status.test.ts b/src/renderer/utils/notifications/status.test.ts
index c5abc40b6..3fd2a1927 100644
--- a/src/renderer/utils/notifications/status.test.ts
+++ b/src/renderer/utils/notifications/status.test.ts
@@ -18,7 +18,14 @@ const networkError = group(mockGitHubCloudAccount, getErrorDetails('NETWORK'));
const networkErrorSecond = group(mockGitHubEnterpriseServerAccount, getErrorDetails('NETWORK'));
const rateLimitedError = group(mockGitHubEnterpriseServerAccount, getErrorDetails('RATE_LIMITED'));
-const baseInput = { isLoading: false, isPaused: false, isError: false };
+const baseInput = {
+ isNetworkOnline: true,
+ isLoading: false,
+ isPending: false,
+ isPaused: false,
+ isRecovering: false,
+ isError: false,
+};
describe('renderer/utils/notifications/status.ts', () => {
describe('deriveStatus', () => {
@@ -26,8 +33,33 @@ describe('renderer/utils/notifications/status.ts', () => {
expect(deriveStatus({ ...baseInput, isLoading: true, notifications: [] })).toBe('loading');
});
- it('reports error when the query is paused (offline)', () => {
- expect(deriveStatus({ ...baseInput, isPaused: true, notifications: [clean] })).toBe('error');
+ it('reports offline even before the query pauses', () => {
+ expect(deriveStatus({ ...baseInput, isNetworkOnline: false, notifications: [clean] })).toBe(
+ 'offline',
+ );
+ });
+
+ it('reports paused, not offline or error, for an online pause with account errors', () => {
+ expect(deriveStatus({ ...baseInput, isPaused: true, notifications: [networkError] })).toBe(
+ 'paused',
+ );
+ });
+
+ it('keeps a successful result visible during an online pause', () => {
+ expect(deriveStatus({ ...baseInput, isPaused: true, notifications: [clean] })).toBe(
+ 'success',
+ );
+ });
+
+ it('does not present a paused initial fetch as an empty inbox', () => {
+ expect(
+ deriveStatus({
+ ...baseInput,
+ isPending: true,
+ isPaused: true,
+ notifications: [],
+ }),
+ ).toBe('paused');
});
it('reports error when the query failed', () => {
@@ -46,31 +78,37 @@ describe('renderer/utils/notifications/status.ts', () => {
});
describe('deriveGlobalError', () => {
- it('returns the offline error when paused', () => {
- expect(deriveGlobalError({ isPaused: true, notifications: [clean] })).toEqual(
+ it('returns the offline error when offline', () => {
+ expect(deriveGlobalError({ status: 'offline', notifications: [clean] })).toEqual(
getErrorDetails('OFFLINE'),
);
});
+ it('does not surface cached failures during recovery', () => {
+ expect(
+ deriveGlobalError({ status: 'loading', notifications: [networkError] }),
+ ).toBeUndefined();
+ });
+
it('returns undefined when there are no accounts', () => {
- expect(deriveGlobalError({ isPaused: false, notifications: [] })).toBeUndefined();
+ expect(deriveGlobalError({ status: 'error', notifications: [] })).toBeUndefined();
});
it('returns the shared error when all accounts have the same error', () => {
expect(
- deriveGlobalError({ isPaused: false, notifications: [networkError, networkErrorSecond] }),
+ deriveGlobalError({ status: 'error', notifications: [networkError, networkErrorSecond] }),
).toEqual(getErrorDetails('NETWORK'));
});
it('returns undefined when accounts have differing errors', () => {
expect(
- deriveGlobalError({ isPaused: false, notifications: [networkError, rateLimitedError] }),
+ deriveGlobalError({ status: 'error', notifications: [networkError, rateLimitedError] }),
).toBeUndefined();
});
it('returns undefined on partial failure', () => {
expect(
- deriveGlobalError({ isPaused: false, notifications: [clean, networkError] }),
+ deriveGlobalError({ status: 'success', notifications: [clean, networkError] }),
).toBeUndefined();
});
});
diff --git a/src/renderer/utils/notifications/status.ts b/src/renderer/utils/notifications/status.ts
index 07fad08ea..9130aed36 100644
--- a/src/renderer/utils/notifications/status.ts
+++ b/src/renderer/utils/notifications/status.ts
@@ -13,10 +13,15 @@ import {
* or the query layer.
*/
export interface NotificationStatusInput {
- /** The initial fetch has not settled yet. */
+ isNetworkOnline: boolean;
+ /** The initial fetch is in progress. */
isLoading: boolean;
- /** TanStack Query paused the request (e.g. offline). */
+ /** Neither success nor error has settled yet. */
+ isPending: boolean;
+ /** The query is waiting for connectivity or for the window to become visible. */
isPaused: boolean;
+ /** The previous result predates reconnection; a fresh result is still due. */
+ isRecovering: boolean;
/** The query failed outright. */
isError: boolean;
/** Per-account notification groups, each carrying its own error (or null). */
@@ -26,49 +31,53 @@ export interface NotificationStatusInput {
/**
* Derive the overall notifications status.
*
- * Only the initial fetch (no settled success or error yet) reports `loading` -
- * background refetches of already-settled data keep their settled status.
+ * Keep settled status during normal background refetches. During reconnect,
+ * don't report cached failures while waiting for the new fetch to settle.
*/
export function deriveStatus({
+ isNetworkOnline,
isLoading,
+ isPending,
isPaused,
+ isRecovering,
isError,
notifications,
}: NotificationStatusInput): Status {
- if (isLoading) {
- return 'loading';
+ if (!isNetworkOnline) {
+ return 'offline';
}
- // Paused (offline) and outright query errors both surface as error status.
- if (isPaused || isError) {
- return 'error';
+ const hasError = isError || doesAllAccountsHaveErrors(notifications);
+
+ if (isPaused) {
+ return isPending || hasError ? 'paused' : 'success';
}
- // All accounts failing is a total outage.
- if (doesAllAccountsHaveErrors(notifications)) {
- return 'error';
+ if (isLoading || (isRecovering && hasError)) {
+ return 'loading';
}
- return 'success';
+ return hasError ? 'error' : 'success';
}
/**
* Derive the single global error to show, if one applies.
*
- * A global error is only shown when every account failed with the *same*
- * error. When accounts fail with different errors (a partial failure), status
- * is `error` but no single global error is shown - the per-account rows carry
- * their own errors.
+ * Aside from being offline, there is only a shared error when every account
+ * failed with the same error. Suppress stale errors while reconnecting.
*/
export function deriveGlobalError({
- isPaused,
+ status,
notifications,
-}: Pick): GitifyError | undefined {
- if (isPaused) {
+}: {
+ status: Status;
+ notifications: AccountNotifications[];
+}): GitifyError | undefined {
+ if (status === 'offline') {
return getErrorDetails('OFFLINE');
}
- if (notifications.length === 0) {
+ if (status !== 'error' || notifications.length === 0) {
return undefined;
}