Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/renderer/components/GlobalEffects.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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(<GlobalEffects />, { 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(<GlobalEffects />, {
Expand Down
6 changes: 3 additions & 3 deletions src/renderer/components/GlobalEffects.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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(() => {
Expand Down
70 changes: 54 additions & 16 deletions src/renderer/hooks/notifications/useNotificationsQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {

import type { AccountNotifications, GitifyError, GitifyNotification, Status } from '../../types';

import { doesAllAccountsHaveErrors } from '../../utils/core/errors';
import {
filterBaseNotifications,
filterDetailedNotifications,
Expand All @@ -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 {
Expand Down Expand Up @@ -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
Expand All @@ -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);
Expand Down Expand Up @@ -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<AccountNotifications[], Error>({
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
Expand All @@ -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
Expand All @@ -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,
});

Expand All @@ -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 {
Expand Down
156 changes: 152 additions & 4 deletions src/renderer/hooks/useNotifications.test.tsx
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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';
Expand Down Expand Up @@ -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,
},
Expand Down Expand Up @@ -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<AccountNotifications[]>();
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<AccountNotifications[]>();
const retry = Promise.withResolvers<AccountNotifications[]>();
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: [] });
Expand Down
Loading
Loading