From af14291e2506525265cb3ab9ba1bc6ac5fc6f7f6 Mon Sep 17 00:00:00 2001 From: Adam Setch Date: Tue, 17 Nov 2026 17:49:12 +0000 Subject: [PATCH 1/5] fix(notifications): treat offline as a connection state, not an error A paused notification query means there is no connectivity, not that a fetch failed. Derive an explicit offline status so the tray and notifications view do not present the offline/reconnect transition as an error. --- .../components/GlobalEffects.test.tsx | 9 ++++++++ src/renderer/routes/Notifications.test.tsx | 11 +++++++++ src/renderer/routes/Notifications.tsx | 2 +- src/renderer/types.ts | 2 +- .../utils/notifications/status.test.ts | 23 +++++++++++++++++-- src/renderer/utils/notifications/status.ts | 11 +++++++-- 6 files changed, 52 insertions(+), 6 deletions(-) diff --git a/src/renderer/components/GlobalEffects.test.tsx b/src/renderer/components/GlobalEffects.test.tsx index 1c25503a7..6b64954dc 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 the query is offline', async () => { + await act(async () => { + renderWithProviders(, { status: 'offline', 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/routes/Notifications.test.tsx b/src/renderer/routes/Notifications.test.tsx index d006dda72..86210579b 100644 --- a/src/renderer/routes/Notifications.test.tsx +++ b/src/renderer/routes/Notifications.test.tsx @@ -80,6 +80,17 @@ describe('renderer/routes/Notifications.tsx', () => { expect(screen.queryByText('Loading')).not.toBeInTheDocument(); }); + it('prefers the offline status over loading while the device is online', () => { + renderWithProviders(, { + status: 'offline', + isOnline: true, + }); + + expect(screen.getByText('Oops')).toBeInTheDocument(); + expect(screen.queryByText('Loading')).not.toBeInTheDocument(); + expect(screen.queryByText('AllRead')).not.toBeInTheDocument(); + }); + it('prefers the error state over loading', () => { renderWithProviders(, { globalError: getErrorDetails('UNKNOWN'), diff --git a/src/renderer/routes/Notifications.tsx b/src/renderer/routes/Notifications.tsx index 93441ddc5..2972aa070 100644 --- a/src/renderer/routes/Notifications.tsx +++ b/src/renderer/routes/Notifications.tsx @@ -35,7 +35,7 @@ export function NotificationsRoute() { [visibleNotifications], ); - if (!isOnline) { + if (!isOnline || status === 'offline') { return ; } diff --git a/src/renderer/types.ts b/src/renderer/types.ts index 2fb4c5d4e..e40e21bbf 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' | '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..ff20a23e6 100644 --- a/src/renderer/utils/notifications/status.test.ts +++ b/src/renderer/utils/notifications/status.test.ts @@ -26,8 +26,27 @@ 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 when the query is paused', () => { + expect(deriveStatus({ ...baseInput, isPaused: true, notifications: [clean] })).toBe( + 'offline', + ); + }); + + it('reports offline rather than error when paused with account errors', () => { + expect( + deriveStatus({ ...baseInput, isPaused: true, notifications: [networkError, networkError] }), + ).toBe('offline'); + }); + + it('reports offline before the initial fetch settles when paused', () => { + expect( + deriveStatus({ + ...baseInput, + isLoading: true, + isPaused: true, + notifications: [], + }), + ).toBe('offline'); }); it('reports error when the query failed', () => { diff --git a/src/renderer/utils/notifications/status.ts b/src/renderer/utils/notifications/status.ts index 07fad08ea..66a17da31 100644 --- a/src/renderer/utils/notifications/status.ts +++ b/src/renderer/utils/notifications/status.ts @@ -28,6 +28,10 @@ export interface NotificationStatusInput { * * Only the initial fetch (no settled success or error yet) reports `loading` - * background refetches of already-settled data keep their settled status. + * + * A paused query means there is no connectivity, not that a fetch failed, so it + * reports `offline` rather than `error`. This keeps the tray and notifications + * view from showing a failure while the app is offline or reconnecting. */ export function deriveStatus({ isLoading, @@ -35,12 +39,15 @@ export function deriveStatus({ isError, notifications, }: NotificationStatusInput): Status { + if (isPaused) { + return 'offline'; + } + if (isLoading) { return 'loading'; } - // Paused (offline) and outright query errors both surface as error status. - if (isPaused || isError) { + if (isError) { return 'error'; } From 7d5915fa2848c230cdbaf56d1d5ff81f117b352d Mon Sep 17 00:00:00 2001 From: Adam Setch Date: Wed, 18 Nov 2026 06:15:57 +0000 Subject: [PATCH 2/5] refactor(notifications): clarify network vs notification offline state Name the device-level online flag separately from the paused-query presentation state, and document why the notifications view checks both. --- src/renderer/components/GlobalEffects.tsx | 6 +++--- src/renderer/routes/Notifications.tsx | 10 ++++++++-- 2 files changed, 11 insertions(+), 5 deletions(-) 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/routes/Notifications.tsx b/src/renderer/routes/Notifications.tsx index 2972aa070..68886da2a 100644 --- a/src/renderer/routes/Notifications.tsx +++ b/src/renderer/routes/Notifications.tsx @@ -16,7 +16,7 @@ import { hasNoAccountErrors } from '../utils/notifications/status'; export function NotificationsRoute() { const { notifications, status, globalError, hasNotifications } = useNotifications(); - const isOnline = useOnlineStatus(); + const isNetworkOnline = useOnlineStatus(); const filteredAccounts = useFiltersStore((s) => s.accounts); const showAccountHeader = useSettingsStore((s) => s.showAccountHeader); @@ -35,7 +35,13 @@ export function NotificationsRoute() { [visibleNotifications], ); - if (!isOnline || status === 'offline') { + // The two conditions cover different orderings of the same transition: + // `!isNetworkOnline` is the device state before the query pauses, while + // `isNotificationsOffline` is a paused query after the network flag has + // already flipped back online. Keep both so neither ordering flashes. + const isNotificationsOffline = status === 'offline'; + + if (!isNetworkOnline || isNotificationsOffline) { return ; } From 64fb0483254e30e8de28890ca9b3339624e91235 Mon Sep 17 00:00:00 2001 From: Adam Setch Date: Mon, 23 Nov 2026 15:56:40 -0500 Subject: [PATCH 3/5] fix(notifications): distinguish paused retries from reconnect failures --- .../components/GlobalEffects.test.tsx | 4 +- .../notifications/useNotificationsQuery.ts | 43 +++++--- src/renderer/hooks/useNotifications.test.tsx | 97 ++++++++++++++++++- src/renderer/hooks/useOnlineStatus.ts | 41 ++++---- src/renderer/routes/Notifications.test.tsx | 21 +--- src/renderer/routes/Notifications.tsx | 12 +-- src/renderer/types.ts | 2 +- .../utils/notifications/status.test.ts | 51 +++++++--- src/renderer/utils/notifications/status.ts | 54 ++++++----- 9 files changed, 219 insertions(+), 106 deletions(-) diff --git a/src/renderer/components/GlobalEffects.test.tsx b/src/renderer/components/GlobalEffects.test.tsx index 6b64954dc..bdcbc346e 100644 --- a/src/renderer/components/GlobalEffects.test.tsx +++ b/src/renderer/components/GlobalEffects.test.tsx @@ -38,9 +38,9 @@ describe('renderer/components/GlobalEffects.tsx', () => { expect(setTrayIconColorAndTitleSpy).toHaveBeenCalledWith(-1, true); }); - it('does not report an error to the tray while the query is offline', async () => { + it('does not report an error to the tray while an online query is paused', async () => { await act(async () => { - renderWithProviders(, { status: 'offline', notificationCount: 3 }); + renderWithProviders(, { status: 'paused', notificationCount: 3 }); }); expect(setTrayIconColorAndTitleSpy).toHaveBeenCalledWith(3, true); diff --git a/src/renderer/hooks/notifications/useNotificationsQuery.ts b/src/renderer/hooks/notifications/useNotificationsQuery.ts index 2d0a13cd0..c77937ada 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 { useNetworkStatus } from '../useOnlineStatus'; import { useNotificationsQueryKey } from './useNotificationsQueryKey'; export interface NotificationsQueryResult { @@ -66,6 +68,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,9 +117,12 @@ 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({ @@ -136,8 +143,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 +154,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 +174,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..9ffdee858 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,89 @@ 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); + }, + ); + }); + 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..cecb0bd4f 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); +const getSnapshot = () => networkStatus; + +export function useNetworkStatus() { + return useSyncExternalStore(subscribe, getSnapshot); +} + /** * 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 86210579b..1885963e9 100644 --- a/src/renderer/routes/Notifications.test.tsx +++ b/src/renderer/routes/Notifications.test.tsx @@ -70,24 +70,13 @@ 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(); - }); - - it('prefers the offline status over loading while the device is online', () => { - renderWithProviders(, { - status: 'offline', - isOnline: true, - }); - - 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(); }); @@ -112,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 68886da2a..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 isNetworkOnline = useOnlineStatus(); const filteredAccounts = useFiltersStore((s) => s.accounts); const showAccountHeader = useSettingsStore((s) => s.showAccountHeader); @@ -35,13 +33,7 @@ export function NotificationsRoute() { [visibleNotifications], ); - // The two conditions cover different orderings of the same transition: - // `!isNetworkOnline` is the device state before the query pauses, while - // `isNotificationsOffline` is a paused query after the network flag has - // already flipped back online. Keep both so neither ordering flashes. - const isNotificationsOffline = status === 'offline'; - - if (!isNetworkOnline || isNotificationsOffline) { + if (status === 'offline') { return ; } @@ -49,7 +41,7 @@ export function NotificationsRoute() { return ; } - if (status === 'loading') { + if (status === 'loading' || status === 'paused') { return ; } diff --git a/src/renderer/types.ts b/src/renderer/types.ts index e40e21bbf..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' | 'offline' | '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 ff20a23e6..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,27 +33,33 @@ describe('renderer/utils/notifications/status.ts', () => { expect(deriveStatus({ ...baseInput, isLoading: true, notifications: [] })).toBe('loading'); }); - it('reports offline when the query is paused', () => { - expect(deriveStatus({ ...baseInput, isPaused: true, notifications: [clean] })).toBe( + it('reports offline even before the query pauses', () => { + expect(deriveStatus({ ...baseInput, isNetworkOnline: false, notifications: [clean] })).toBe( 'offline', ); }); - it('reports offline rather than error when paused with account errors', () => { - expect( - deriveStatus({ ...baseInput, isPaused: true, notifications: [networkError, networkError] }), - ).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('reports offline before the initial fetch settles when 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, - isLoading: true, + isPending: true, isPaused: true, notifications: [], }), - ).toBe('offline'); + ).toBe('paused'); }); it('reports error when the query failed', () => { @@ -65,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 66a17da31..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,56 +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. - * - * A paused query means there is no connectivity, not that a fetch failed, so it - * reports `offline` rather than `error`. This keeps the tray and notifications - * view from showing a failure while the app is offline or reconnecting. + * 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 (isPaused) { + if (!isNetworkOnline) { return 'offline'; } - if (isLoading) { - return 'loading'; - } + const hasError = isError || doesAllAccountsHaveErrors(notifications); - if (isError) { - return 'error'; + 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; } From 6b91a74c0e66908b57646fb0cb5351df8b882247 Mon Sep 17 00:00:00 2001 From: Adam Setch Date: Mon, 23 Nov 2026 16:01:08 -0500 Subject: [PATCH 4/5] fix(notifications): retry failed polls that span reconnect --- .../notifications/useNotificationsQuery.ts | 29 +++++++-- src/renderer/hooks/useNotifications.test.tsx | 59 +++++++++++++++++++ src/renderer/hooks/useOnlineStatus.ts | 4 +- 3 files changed, 86 insertions(+), 6 deletions(-) diff --git a/src/renderer/hooks/notifications/useNotificationsQuery.ts b/src/renderer/hooks/notifications/useNotificationsQuery.ts index c77937ada..9e7f544f5 100644 --- a/src/renderer/hooks/notifications/useNotificationsQuery.ts +++ b/src/renderer/hooks/notifications/useNotificationsQuery.ts @@ -25,7 +25,7 @@ import { } from '../../utils/notifications/notifications'; import { computeRefetchIntervalMs } from '../../utils/notifications/pollInterval'; import { deriveGlobalError, deriveStatus } from '../../utils/notifications/status'; -import { useNetworkStatus } from '../useOnlineStatus'; +import { getNetworkStatus, useNetworkStatus } from '../useOnlineStatus'; import { useNotificationsQueryKey } from './useNotificationsQueryKey'; export interface NotificationsQueryResult { @@ -58,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 @@ -128,9 +151,7 @@ export const useNotificationsQuery = ({ poll }: { poll: boolean }): Notification } = 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 diff --git a/src/renderer/hooks/useNotifications.test.tsx b/src/renderer/hooks/useNotifications.test.tsx index 9ffdee858..fe050a8dc 100644 --- a/src/renderer/hooks/useNotifications.test.tsx +++ b/src/renderer/hooks/useNotifications.test.tsx @@ -295,6 +295,65 @@ describe('renderer/hooks/useNotifications.ts', () => { 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', () => { diff --git a/src/renderer/hooks/useOnlineStatus.ts b/src/renderer/hooks/useOnlineStatus.ts index cecb0bd4f..563d39b13 100644 --- a/src/renderer/hooks/useOnlineStatus.ts +++ b/src/renderer/hooks/useOnlineStatus.ts @@ -16,10 +16,10 @@ onlineManager.subscribe((isOnline) => { }); const subscribe = (onChange: () => void) => onlineManager.subscribe(onChange); -const getSnapshot = () => networkStatus; +export const getNetworkStatus = () => networkStatus; export function useNetworkStatus() { - return useSyncExternalStore(subscribe, getSnapshot); + return useSyncExternalStore(subscribe, getNetworkStatus); } /** From ca95cd3722738df27783d5b7778baa1a8f9cbb59 Mon Sep 17 00:00:00 2001 From: Adam Setch Date: Mon, 23 Nov 2026 16:56:45 -0500 Subject: [PATCH 5/5] test(notifications): use offline status in visual fixtures --- src/renderer/routes/NotificationsStates.visual.test.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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',