diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index dedbb7740..fd82819dd 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -73,6 +73,7 @@ App-level side effects are owned by a single host. `GlobalEffects` mounts exactl - **Hidden or unfocused window:** polling continues; `refetchIntervalInBackground` keeps the timers running. - **Offline:** notification and account queries pause (`networkMode: 'online'`), and the notifications screen shows the offline state; on reconnect they resume, and the online state is re-probed on wake. - **Locked or suspended:** `SYSTEM_SLEEP` disables the query intervals; `SYSTEM_WAKE` re-enables them and triggers an immediate refetch of the notification and account queries (`cancelRefetch: false`) before the normal intervals resume. +- **Wake and reconnect recovery:** a wake or an offline-to-online transition opens a session-local recovery window (`RECOVERY_WINDOW_MS`, 30s) even when the device never reported offline. While the window is open and the latest notification fetch is a retryable all-account connection failure, `refetchInterval` retries on `RECOVERY_RETRY_INTERVAL_MS` (5s) and the derived status stays `loading` rather than presenting the stale error. Recovery ends on a clean or partial success, a definitive failure, or window expiry; the normal user/server interval then applies. Consumers read the shared query cache and stores, and **do not register their own** polling, alerts, wake, or focus listeners. This keeps background work (for example, firing one poll per interval) from multiplying with the number of mounted components. When you add a new background effect, add it to the host, not to a leaf component. diff --git a/src/renderer/__helpers__/hook-mocks.ts b/src/renderer/__helpers__/hook-mocks.ts index dd83812b0..8c29a06be 100644 --- a/src/renderer/__helpers__/hook-mocks.ts +++ b/src/renderer/__helpers__/hook-mocks.ts @@ -32,6 +32,9 @@ function buildNotificationsDefaults(): NotificationsState { globalError: undefined, isFetching: false, + isPaused: false, + isError: false, + dataUpdatedAt: 0, notifications: [], notificationCount: 0, diff --git a/src/renderer/__helpers__/vitest.setup.ts b/src/renderer/__helpers__/vitest.setup.ts index bce6d1677..207e48be1 100644 --- a/src/renderer/__helpers__/vitest.setup.ts +++ b/src/renderer/__helpers__/vitest.setup.ts @@ -139,7 +139,13 @@ beforeEach(async () => { const { resetHookMocks } = await import('./hook-mocks'); resetHookMocks(); - const { usePowerStateStore, useShortcutRegistrationStore } = await import('../stores'); + const { useConnectionStore, usePowerStateStore, useShortcutRegistrationStore } = + await import('../stores'); + useConnectionStore.setState({ + state: 'online', + recoveringSince: null, + baselineDataUpdatedAt: 0, + }); usePowerStateStore.setState({ isActive: true }); useShortcutRegistrationStore.getState().reset(); }); diff --git a/src/renderer/components/GlobalEffects.test.tsx b/src/renderer/components/GlobalEffects.test.tsx index bdcbc346e..78bc273f2 100644 --- a/src/renderer/components/GlobalEffects.test.tsx +++ b/src/renderer/components/GlobalEffects.test.tsx @@ -135,9 +135,13 @@ describe('renderer/components/GlobalEffects.tsx', () => { const callCountAfterMount = refreshAccountSpy.mock.calls.length; - const wakeCallback = vi.mocked(window.gitify.onSystemWake).mock.calls[0][0]; + const wakeCallbacks = vi + .mocked(window.gitify.onSystemWake) + .mock.calls.map(([callback]) => callback); await act(async () => { - wakeCallback(); + for (const wakeCallback of wakeCallbacks) { + wakeCallback(); + } }); expect(refreshAccountSpy.mock.calls.length).toBeGreaterThan(callCountAfterMount); diff --git a/src/renderer/components/GlobalEffects.tsx b/src/renderer/components/GlobalEffects.tsx index 3d2f7eed8..a8f603e21 100644 --- a/src/renderer/components/GlobalEffects.tsx +++ b/src/renderer/components/GlobalEffects.tsx @@ -5,11 +5,13 @@ import { useQueryClient } from '@tanstack/react-query'; import { useNotificationsHost } from '../hooks/notifications/useNotificationsHost'; import { useAccounts } from '../hooks/useAccounts'; import { useAppearance } from '../hooks/useAppearance'; +import { useConnectionRecovery } from '../hooks/useConnectionRecovery'; import { useOnlineStatus } from '../hooks/useOnlineStatus'; import { usePowerState } from '../hooks/usePowerState'; import { useShortcutRegistration } from '../hooks/useShortcutRegistration'; import { useAccountsStore, + useConnectionStore, useFiltersStore, useSettingsStore, useShortcutRegistrationStore, @@ -43,7 +45,20 @@ export function GlobalEffects() { // Notification fetching side effects (sound / native alerts, interval/focus/reconnect // polling, and the system-wake refetch) - const { status, notificationCount } = useNotificationsHost(); + const { status, notificationCount, notifications, isFetching, isPaused, isError, dataUpdatedAt } = + useNotificationsHost(); + + // Recovery side effects (offline/recovering/online lifecycle). This adds a + // wake-aware window on top of TanStack's reconnect handling: a wake can start + // recovery even when the device never reported offline. + useConnectionRecovery({ + isOnline: isNetworkOnline, + isFetching, + isPaused, + isError, + dataUpdatedAt, + notifications, + }); // Periodic account refreshes (startup + hourly interval) useAccounts(); @@ -73,6 +88,7 @@ export function GlobalEffects() { resetSettings(); resetFilters(); queryClient.clear(); + useConnectionStore.getState().settle(); useShortcutRegistrationStore.getState().reset(); window.gitify.nativeNotifications.removeAll(); }); diff --git a/src/renderer/constants.ts b/src/renderer/constants.ts index 839f42ba2..a461e0380 100644 --- a/src/renderer/constants.ts +++ b/src/renderer/constants.ts @@ -82,6 +82,14 @@ export const Constants = { REFRESH_ACCOUNTS_INTERVAL_MS: 60 * 60 * 1000, // 1 hour + // How long the app holds recovery after connectivity returns or the system + // wakes, waiting for a notification fetch to settle before presenting a + // failure. Long enough to cover Wi-Fi/DNS reconvergence after resume. + RECOVERY_WINDOW_MS: 30 * 1000, // 30 seconds + + // Short cadence for a notification retry while the recovery window is open. + RECOVERY_RETRY_INTERVAL_MS: 5 * 1000, // 5 seconds + // Cooldown before retrying a failed query, used by TanStack Query client QUERY_RETRY_DELAY_MS: 30 * 1000, // 30 seconds diff --git a/src/renderer/hooks/notifications/useNotificationsQuery.ts b/src/renderer/hooks/notifications/useNotificationsQuery.ts index 9e7f544f5..21adba197 100644 --- a/src/renderer/hooks/notifications/useNotificationsQuery.ts +++ b/src/renderer/hooks/notifications/useNotificationsQuery.ts @@ -6,6 +6,7 @@ import { Constants } from '../../constants'; import { useAccountsStore, + useConnectionStore, useFiltersStore, usePowerStateStore, useSettingsStore, @@ -23,7 +24,8 @@ import { getNotificationCount, getUnreadNotificationCount, } from '../../utils/notifications/notifications'; -import { computeRefetchIntervalMs } from '../../utils/notifications/pollInterval'; +import { computeNotificationRefetchIntervalMs } from '../../utils/notifications/pollInterval'; +import { shouldUseRecoveryRetry } from '../../utils/notifications/recovery'; import { deriveGlobalError, deriveStatus } from '../../utils/notifications/status'; import { getNetworkStatus, useNetworkStatus } from '../useOnlineStatus'; import { useNotificationsQueryKey } from './useNotificationsQueryKey'; @@ -33,6 +35,8 @@ export interface NotificationsQueryResult { isLoading: boolean; isError: boolean; isFetching: boolean; + isPaused: boolean; + dataUpdatedAt: number; notificationCount: number; unreadNotificationCount: number; hasNotifications: boolean; @@ -96,6 +100,7 @@ export const useNotificationsQuery = ({ poll }: { poll: boolean }): Notification // Account store values const accounts = useAccountsStore((s) => s.accounts); const isPowerActive = usePowerStateStore((s) => s.isActive); + const connectionState = useConnectionStore((s) => s.state); // Filter store values const includeSearchTokens = useFiltersStore((s) => s.includeSearchTokens); @@ -171,9 +176,22 @@ export const useNotificationsQuery = ({ poll }: { poll: boolean }): Notification // Only the singleton host observer polls. Other consumers share the cached // data and would otherwise each schedule their own refetch timer. The // interval is re-evaluated after each fetch so it stretches to the latest - // server-recommended minimum (`X-Poll-Interval`) when required. + // server-recommended minimum (`X-Poll-Interval`) when required. While the + // recovery window is open and the latest settled fetch is a retryable + // connection failure, retry on the short recovery cadence instead. refetchInterval: - poll && isPowerActive ? () => computeRefetchIntervalMs(fetchIntervalMs, accounts) : false, + poll && isPowerActive + ? (query) => + computeNotificationRefetchIntervalMs({ + userIntervalMs: fetchIntervalMs, + accounts, + recoveryRetry: shouldUseRecoveryRetry( + useConnectionStore.getState().state, + query.state.data ?? [], + ), + recoveryRetryIntervalMs: Constants.RECOVERY_RETRY_INTERVAL_MS, + }) + : false, refetchOnMount: poll, // Retry an errored result on reconnect even if it's still fresh. Successful // results retain the usual stale-time guard. @@ -197,8 +215,13 @@ export const useNotificationsQuery = ({ poll }: { poll: boolean }): Notification // Query keeps the previous result during a refetch. Use the same timestamps // for every observer, including one mounted halfway through the reconnect. + // The connection store adds a wake-aware recovery window: a wake can start + // recovery even when the device never reported offline, so there is no + // `reconnectedAt` transition to rely on. const lastResultAt = isError ? errorUpdatedAt : dataUpdatedAt; - const isRecovering = reconnectedAt !== undefined && lastResultAt < reconnectedAt; + const isRecovering = + connectionState === 'recovering' || + (reconnectedAt !== undefined && lastResultAt < reconnectedAt); const status = deriveStatus({ isNetworkOnline, isLoading, @@ -219,6 +242,8 @@ export const useNotificationsQuery = ({ poll }: { poll: boolean }): Notification isLoading, isError, isFetching, + isPaused, + dataUpdatedAt, notificationCount, unreadNotificationCount, hasNotifications, diff --git a/src/renderer/hooks/useConnectionRecovery.test.tsx b/src/renderer/hooks/useConnectionRecovery.test.tsx new file mode 100644 index 000000000..209305969 --- /dev/null +++ b/src/renderer/hooks/useConnectionRecovery.test.tsx @@ -0,0 +1,287 @@ +import { act, renderHook } from '@testing-library/react'; + +import { + mockGitHubCloudAccount, + mockGitHubEnterpriseServerAccount, +} from '../__mocks__/account-mocks'; + +import useConnectionStore from '../stores/useConnectionStore'; + +import type { AccountNotifications, ErrorType } from '../types'; + +import { getErrorDetails } from '../utils/core/errors'; +import { useConnectionRecovery, type ConnectionRecoveryInput } from './useConnectionRecovery'; + +function group(errorType: ErrorType | null = null, account = mockGitHubCloudAccount) { + return { + account, + notifications: [], + error: errorType ? getErrorDetails(errorType) : null, + } as AccountNotifications; +} + +const baseInput: ConnectionRecoveryInput = { + isOnline: true, + isFetching: false, + isPaused: false, + isError: false, + dataUpdatedAt: 0, + notifications: [group()], +}; + +describe('renderer/hooks/useConnectionRecovery.ts', () => { + beforeEach(() => { + useConnectionStore.setState({ + state: 'online', + recoveringSince: null, + baselineDataUpdatedAt: 0, + }); + Object.defineProperty(navigator, 'onLine', { value: true, configurable: true }); + }); + + afterEach(() => { + Object.defineProperty(navigator, 'onLine', { value: true, configurable: true }); + }); + + it('stays online on mount while the device is online', () => { + renderHook(() => useConnectionRecovery(baseInput)); + + expect(useConnectionStore.getState().state).toBe('online'); + }); + + it('goes offline when connectivity is lost', () => { + const { rerender } = renderHook( + (props: ConnectionRecoveryInput) => useConnectionRecovery(props), + { + initialProps: baseInput, + }, + ); + + rerender({ ...baseInput, isOnline: false }); + + expect(useConnectionStore.getState().state).toBe('offline'); + }); + + it('starts recovery when connectivity returns', () => { + const { rerender } = renderHook( + (props: ConnectionRecoveryInput) => useConnectionRecovery(props), + { + initialProps: baseInput, + }, + ); + + rerender({ ...baseInput, isOnline: false }); + rerender({ ...baseInput, isOnline: true }); + + expect(useConnectionStore.getState()).toMatchObject({ + state: 'recovering', + baselineDataUpdatedAt: 0, + }); + }); + + it('starts recovery when the system wakes while online', () => { + renderHook(() => useConnectionRecovery(baseInput)); + + const wake = vi.mocked(window.gitify.onSystemWake).mock.calls[0][0]; + act(() => { + wake(); + }); + + expect(useConnectionStore.getState().state).toBe('recovering'); + }); + + it('stays offline when the system wakes while offline', () => { + renderHook(() => useConnectionRecovery(baseInput)); + + const wake = vi.mocked(window.gitify.onSystemWake).mock.calls[0][0]; + act(() => { + Object.defineProperty(navigator, 'onLine', { value: false, configurable: true }); + wake(); + }); + + expect(useConnectionStore.getState().state).toBe('offline'); + }); + + it('settles online when a clean fetch lands after recovery begins', () => { + const { rerender } = renderHook( + (props: ConnectionRecoveryInput) => useConnectionRecovery(props), + { + initialProps: baseInput, + }, + ); + + rerender({ ...baseInput, isOnline: false }); + rerender({ ...baseInput, isOnline: true }); + rerender({ ...baseInput, dataUpdatedAt: 1 }); + + expect(useConnectionStore.getState().state).toBe('online'); + }); + + it('settles online on a partial success', () => { + const { rerender } = renderHook( + (props: ConnectionRecoveryInput) => useConnectionRecovery(props), + { + initialProps: baseInput, + }, + ); + + rerender({ ...baseInput, isOnline: false }); + rerender({ ...baseInput, isOnline: true }); + rerender({ + ...baseInput, + dataUpdatedAt: 1, + notifications: [group(), group('BAD_CREDENTIALS', mockGitHubEnterpriseServerAccount)], + }); + + expect(useConnectionStore.getState().state).toBe('online'); + }); + + it('stays recovering on a retryable connection failure', () => { + const { rerender } = renderHook( + (props: ConnectionRecoveryInput) => useConnectionRecovery(props), + { + initialProps: baseInput, + }, + ); + + rerender({ ...baseInput, isOnline: false }); + rerender({ ...baseInput, isOnline: true }); + rerender({ + ...baseInput, + dataUpdatedAt: 1, + notifications: [group('NETWORK'), group('UNKNOWN', mockGitHubEnterpriseServerAccount)], + }); + + expect(useConnectionStore.getState().state).toBe('recovering'); + }); + + it('settles online on a definitive failure', () => { + const { rerender } = renderHook( + (props: ConnectionRecoveryInput) => useConnectionRecovery(props), + { + initialProps: baseInput, + }, + ); + + rerender({ ...baseInput, isOnline: false }); + rerender({ ...baseInput, isOnline: true }); + rerender({ + ...baseInput, + dataUpdatedAt: 1, + notifications: [ + group('BAD_CREDENTIALS'), + group('MISSING_SCOPES', mockGitHubEnterpriseServerAccount), + ], + }); + + expect(useConnectionStore.getState().state).toBe('online'); + }); + + it('does not settle while a fetch is in flight', () => { + const { rerender } = renderHook( + (props: ConnectionRecoveryInput) => useConnectionRecovery(props), + { + initialProps: baseInput, + }, + ); + + rerender({ ...baseInput, isOnline: false }); + rerender({ ...baseInput, isOnline: true }); + rerender({ ...baseInput, isFetching: true, dataUpdatedAt: 1 }); + + expect(useConnectionStore.getState().state).toBe('recovering'); + }); + + it('settles online on an outright query error', () => { + const { rerender } = renderHook( + (props: ConnectionRecoveryInput) => useConnectionRecovery(props), + { + initialProps: baseInput, + }, + ); + + rerender({ ...baseInput, isOnline: false }); + rerender({ ...baseInput, isOnline: true }); + rerender({ ...baseInput, isError: true }); + + expect(useConnectionStore.getState().state).toBe('online'); + }); + + it('ends recovery when the bounded window expires', () => { + vi.useFakeTimers(); + + const { rerender } = renderHook( + (props: ConnectionRecoveryInput) => useConnectionRecovery(props), + { + initialProps: baseInput, + }, + ); + + rerender({ ...baseInput, isOnline: false }); + rerender({ ...baseInput, isOnline: true }); + + expect(useConnectionStore.getState().state).toBe('recovering'); + + act(() => { + vi.advanceTimersByTime(30_000); + }); + + expect(useConnectionStore.getState().state).toBe('online'); + }); + + it('does not extend the window on duplicate wake events', () => { + vi.useFakeTimers(); + + renderHook(() => useConnectionRecovery(baseInput)); + + const wake = vi.mocked(window.gitify.onSystemWake).mock.calls[0][0]; + act(() => { + wake(); + }); + + act(() => { + vi.advanceTimersByTime(20_000); + }); + + act(() => { + wake(); + }); + + act(() => { + vi.advanceTimersByTime(9_999); + }); + + expect(useConnectionStore.getState().state).toBe('recovering'); + + act(() => { + vi.advanceTimersByTime(1); + }); + + expect(useConnectionStore.getState().state).toBe('online'); + }); + + it('goes offline immediately when connectivity is lost during recovery', () => { + const { rerender } = renderHook( + (props: ConnectionRecoveryInput) => useConnectionRecovery(props), + { + initialProps: baseInput, + }, + ); + + rerender({ ...baseInput, isOnline: false }); + rerender({ ...baseInput, isOnline: true }); + rerender({ ...baseInput, isOnline: false }); + + expect(useConnectionStore.getState().state).toBe('offline'); + }); + + it('removes the wake listener on unmount', () => { + const unsubscribe = vi.fn(); + vi.mocked(window.gitify.onSystemWake).mockReturnValueOnce(unsubscribe); + + const { unmount } = renderHook(() => useConnectionRecovery(baseInput)); + unmount(); + + expect(unsubscribe).toHaveBeenCalledTimes(1); + }); +}); diff --git a/src/renderer/hooks/useConnectionRecovery.ts b/src/renderer/hooks/useConnectionRecovery.ts new file mode 100644 index 000000000..c53803f97 --- /dev/null +++ b/src/renderer/hooks/useConnectionRecovery.ts @@ -0,0 +1,127 @@ +import { useEffect, useRef } from 'react'; + +import { Constants } from '../constants'; + +import { useConnectionStore } from '../stores'; + +import type { AccountNotifications } from '../types'; + +import { hasCleanAccount, isRetryableConnectionError } from '../utils/notifications/recovery'; + +export interface ConnectionRecoveryInput { + /** The device's online status from `useOnlineStatus`. */ + isOnline: boolean; + /** A notification fetch is in flight. */ + isFetching: boolean; + /** TanStack Query paused the notification fetch. */ + isPaused: boolean; + /** The notification query failed outright. */ + isError: boolean; + /** When the cached notification data last settled. */ + dataUpdatedAt: number; + /** The current notification groups, including per-account errors. */ + notifications: AccountNotifications[]; +} + +/** + * Drive the session-local connection lifecycle from online transitions, system + * wake events, and notification fetch outcomes. + * + * Mount exactly once from the app-level effects host. + * + * Recovery starts when connectivity returns or the system wakes while online. + * It holds until the first notification fetch settles after recovery began, a + * definitive (non-retryable) failure is observed, or the bounded window + * expires. Duplicate wake or online events do not extend the window. + */ +export function useConnectionRecovery({ + isOnline, + isFetching, + isPaused, + isError, + dataUpdatedAt, + notifications, +}: ConnectionRecoveryInput): void { + const state = useConnectionStore((s) => s.state); + const recoveringSince = useConnectionStore((s) => s.recoveringSince); + const baselineDataUpdatedAt = useConnectionStore((s) => s.baselineDataUpdatedAt); + const setOffline = useConnectionStore((s) => s.setOffline); + const startRecovery = useConnectionStore((s) => s.startRecovery); + const settle = useConnectionStore((s) => s.settle); + + // Keep the latest data timestamp available to the wake listener without + // re-subscribing on every notification update. + const dataUpdatedAtRef = useRef(dataUpdatedAt); + useEffect(() => { + dataUpdatedAtRef.current = dataUpdatedAt; + }, [dataUpdatedAt]); + + const previousOnlineRef = useRef(isOnline); + + useEffect(() => { + const previousOnline = previousOnlineRef.current; + previousOnlineRef.current = isOnline; + + if (!isOnline) { + setOffline(); + return; + } + + if (!previousOnline) { + startRecovery(dataUpdatedAt); + } + }, [isOnline, dataUpdatedAt, setOffline, startRecovery]); + + useEffect(() => { + return window.gitify.onSystemWake(() => { + if (navigator.onLine) { + startRecovery(dataUpdatedAtRef.current); + } else { + setOffline(); + } + }); + }, [setOffline, startRecovery]); + + useEffect(() => { + if (state !== 'recovering' || isPaused || isFetching) { + return; + } + + // An outright query error is not a connectivity outcome we can wait out. + if (isError) { + settle(); + return; + } + + // No fetch has settled since recovery began. + if (dataUpdatedAt <= baselineDataUpdatedAt) { + return; + } + + // A clean or partial success means the connection works. A settled failure + // that is not retryable (auth, scope, rate limit, forbidden) is definitive. + if (hasCleanAccount(notifications) || !isRetryableConnectionError(notifications)) { + settle(); + } + }, [ + state, + isPaused, + isFetching, + isError, + dataUpdatedAt, + baselineDataUpdatedAt, + notifications, + settle, + ]); + + useEffect(() => { + if (state !== 'recovering' || recoveringSince === null) { + return; + } + + const remaining = Math.max(0, Constants.RECOVERY_WINDOW_MS - (Date.now() - recoveringSince)); + + const timer = setTimeout(settle, remaining); + return () => clearTimeout(timer); + }, [state, recoveringSince, settle]); +} diff --git a/src/renderer/hooks/useNotifications.test.tsx b/src/renderer/hooks/useNotifications.test.tsx index fe050a8dc..fee319168 100644 --- a/src/renderer/hooks/useNotifications.test.tsx +++ b/src/renderer/hooks/useNotifications.test.tsx @@ -29,6 +29,7 @@ import { Constants } from '../constants'; import { getNotificationFailureKey, useAccountsStore, + useConnectionStore, useFiltersStore, useNotificationActionFailuresStore, usePowerStateStore, @@ -50,6 +51,7 @@ import * as audio from '../utils/system/audio'; import * as links from '../utils/system/links'; import * as native from '../utils/system/native'; import { useNotificationsHost } from './notifications/useNotificationsHost'; +import { useConnectionRecovery } from './useConnectionRecovery'; import { useNotifications } from './useNotifications'; // Exercise the real hook implementation (globally mocked in vitest.setup) @@ -91,6 +93,35 @@ const createWrapper = (retry: number | false = false) => { const renderNotificationsHook = () => renderHook(() => useNotificationsHost(), { wrapper: createWrapper() }); +/** + * Mount the singleton notification host together with the recovery hook, so + * wake events drive both the refetch and the session-local recovery window. + */ +const renderNotificationsHookWithRecovery = () => + renderHook( + () => { + const state = useNotificationsHost(); + useConnectionRecovery({ + isOnline: true, + isFetching: state.isFetching, + isPaused: state.isPaused, + isError: state.isError, + dataUpdatedAt: state.dataUpdatedAt, + notifications: state.notifications, + }); + return state; + }, + { wrapper: createWrapper() }, + ); + +const networkFailure = (): AccountNotifications[] => [ + { + account: mockGitHubCloudAccount, + notifications: [], + error: getErrorDetails('NETWORK'), + }, +]; + describe('renderer/hooks/useNotifications.ts', () => { const githubAdapter = getAdapter('github'); @@ -1257,6 +1288,95 @@ describe('renderer/hooks/useNotifications.ts', () => { await waitFor(() => expect(getAllNotificationsMock).toHaveBeenCalledTimes(2)); }); + it('holds loading and retries soon when a wake fetch fails while online', async () => { + vi.useFakeTimers(); + try { + useAccountsStore.setState({ accounts: [mockGitHubCloudAccount] }); + getAllNotificationsMock + .mockResolvedValueOnce(mockSingleAccountNotifications) + .mockResolvedValueOnce(networkFailure()) + .mockResolvedValueOnce(mockSingleAccountNotifications); + + const { result } = renderNotificationsHookWithRecovery(); + + await act(async () => { + await vi.advanceTimersByTimeAsync(0); + }); + expect(result.current.status).toBe('success'); + + const wakeCallbacks = vi + .mocked(window.gitify.onSystemWake) + .mock.calls.map(([callback]) => callback); + act(() => { + for (const callback of wakeCallbacks) { + callback(); + } + }); + + await act(async () => { + await vi.advanceTimersByTimeAsync(0); + }); + expect(getAllNotificationsMock).toHaveBeenCalledTimes(2); + expect(result.current.status).toBe('loading'); + expect(result.current.globalError).toBeUndefined(); + + await act(async () => { + await vi.advanceTimersByTimeAsync(Constants.RECOVERY_RETRY_INTERVAL_MS); + }); + // Flush TanStack's notification timer after the retry resolves. + await act(async () => { + await vi.advanceTimersByTimeAsync(1); + }); + + expect(getAllNotificationsMock).toHaveBeenCalledTimes(3); + expect(useConnectionStore.getState().state).toBe('online'); + expect(result.current.notifications).toEqual(mockSingleAccountNotifications); + expect(result.current.status).toBe('success'); + } finally { + vi.useRealTimers(); + } + }); + + it('presents the failure once the recovery window expires', async () => { + vi.useFakeTimers(); + try { + useAccountsStore.setState({ accounts: [mockGitHubCloudAccount] }); + getAllNotificationsMock + .mockResolvedValueOnce(mockSingleAccountNotifications) + .mockResolvedValue(networkFailure()); + + const { result } = renderNotificationsHookWithRecovery(); + + await act(async () => { + await vi.advanceTimersByTimeAsync(0); + }); + expect(result.current.status).toBe('success'); + + const wakeCallbacks = vi + .mocked(window.gitify.onSystemWake) + .mock.calls.map(([callback]) => callback); + act(() => { + for (const callback of wakeCallbacks) { + callback(); + } + }); + + await act(async () => { + await vi.advanceTimersByTimeAsync(0); + }); + expect(result.current.status).toBe('loading'); + + await act(async () => { + await vi.advanceTimersByTimeAsync(Constants.RECOVERY_WINDOW_MS); + }); + + expect(result.current.status).toBe('error'); + expect(result.current.globalError?.type).toBe('NETWORK'); + } finally { + vi.useRealTimers(); + } + }); + it('does not poll while the system is inactive and resumes when active', async () => { vi.useFakeTimers(); try { diff --git a/src/renderer/hooks/useNotifications.ts b/src/renderer/hooks/useNotifications.ts index a567c42aa..0bd968061 100644 --- a/src/renderer/hooks/useNotifications.ts +++ b/src/renderer/hooks/useNotifications.ts @@ -21,6 +21,12 @@ export interface NotificationsState { /** Whether a fetch (initial, background poll, or manual refetch) is currently in flight. */ isFetching: boolean; + /** Whether TanStack Query paused the fetch (offline or hidden window). */ + isPaused: boolean; + /** Whether the notification query failed outright. */ + isError: boolean; + /** When the cached notification data last settled. */ + dataUpdatedAt: number; notifications: AccountNotifications[]; notificationCount: number; @@ -49,6 +55,9 @@ export const buildNotificationsState = ( globalError: query.globalError, isFetching: query.isFetching, + isPaused: query.isPaused, + isError: query.isError, + dataUpdatedAt: query.dataUpdatedAt, notifications: query.notifications, notificationCount: query.notificationCount, diff --git a/src/renderer/stores/index.ts b/src/renderer/stores/index.ts index a0eaac638..3b3145f84 100644 --- a/src/renderer/stores/index.ts +++ b/src/renderer/stores/index.ts @@ -2,6 +2,7 @@ export * from './types'; export * from './defaults'; export { default as useAccountsStore } from './useAccountsStore'; +export { default as useConnectionStore } from './useConnectionStore'; export { default as useFiltersStore } from './useFiltersStore'; export { default as useNotificationActionFailuresStore, diff --git a/src/renderer/stores/types.ts b/src/renderer/stores/types.ts index f401ebaaf..f9957d8a6 100644 --- a/src/renderer/stores/types.ts +++ b/src/renderer/stores/types.ts @@ -4,6 +4,7 @@ import type { Account, AccountUUID, ClientID, + ConnectionState, FilterStateType, Forge, GitifyError, @@ -324,3 +325,37 @@ export interface PowerStateStore { setActive: (active: boolean) => void; } + +// ============================================================================ +// Connection Store Types +// ============================================================================ + +/** + * Session-local connectivity lifecycle. + * + * `offline` while the device reports no connection, `recovering` after + * connectivity returns or the system wakes until the first notification fetch + * settles, and `online` once a settled fetch shows at least one reachable + * account. + */ +export interface ConnectionStore { + state: ConnectionState; + + /** When recovery began, or `null` when the connection is not recovering. */ + recoveringSince: number | null; + + /** Notification `dataUpdatedAt` when recovery began, used to detect a settle. */ + baselineDataUpdatedAt: number; + + /** Mark the connection offline and clear any in-progress recovery. */ + setOffline: () => void; + + /** + * Begin recovery unless one is already in progress. Duplicate wake or online + * events must not extend the recovery window. + */ + startRecovery: (baselineDataUpdatedAt: number) => void; + + /** Finish recovery and mark the connection online. */ + settle: () => void; +} diff --git a/src/renderer/stores/useConnectionStore.test.ts b/src/renderer/stores/useConnectionStore.test.ts new file mode 100644 index 000000000..8418b9d15 --- /dev/null +++ b/src/renderer/stores/useConnectionStore.test.ts @@ -0,0 +1,67 @@ +import useConnectionStore from './useConnectionStore'; + +describe('renderer/stores/useConnectionStore.ts', () => { + beforeEach(() => { + useConnectionStore.setState({ + state: 'online', + recoveringSince: null, + baselineDataUpdatedAt: 0, + }); + }); + + it('starts online', () => { + expect(useConnectionStore.getInitialState().state).toBe('online'); + }); + + it('starts recovery with a baseline and timestamp', () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-01-01T00:00:00Z')); + + useConnectionStore.getState().startRecovery(1234); + + expect(useConnectionStore.getState()).toMatchObject({ + state: 'recovering', + baselineDataUpdatedAt: 1234, + }); + expect(useConnectionStore.getState().recoveringSince).toBe(Date.now()); + }); + + it('does not extend an in-progress recovery on duplicate entry', () => { + vi.useFakeTimers(); + vi.setSystemTime(new Date('2026-01-01T00:00:00Z')); + + useConnectionStore.getState().startRecovery(1234); + const startedAt = useConnectionStore.getState().recoveringSince; + + vi.advanceTimersByTime(5_000); + useConnectionStore.getState().startRecovery(9999); + + expect(useConnectionStore.getState()).toMatchObject({ + state: 'recovering', + recoveringSince: startedAt, + baselineDataUpdatedAt: 1234, + }); + }); + + it('settles online and clears the recovery metadata', () => { + useConnectionStore.getState().startRecovery(1234); + useConnectionStore.getState().settle(); + + expect(useConnectionStore.getState()).toMatchObject({ + state: 'online', + recoveringSince: null, + baselineDataUpdatedAt: 0, + }); + }); + + it('goes offline immediately and clears recovery', () => { + useConnectionStore.getState().startRecovery(1234); + useConnectionStore.getState().setOffline(); + + expect(useConnectionStore.getState()).toMatchObject({ + state: 'offline', + recoveringSince: null, + baselineDataUpdatedAt: 0, + }); + }); +}); diff --git a/src/renderer/stores/useConnectionStore.ts b/src/renderer/stores/useConnectionStore.ts new file mode 100644 index 000000000..dff9e8408 --- /dev/null +++ b/src/renderer/stores/useConnectionStore.ts @@ -0,0 +1,38 @@ +import { create } from 'zustand'; + +import type { ConnectionStore } from './types'; + +/** + * Session-local connection lifecycle. + * + * Not persisted: a fresh process starts online and the first network event or + * notification fetch corrects it. Polling code reads `state` via `getState()` + * to decide whether a short recovery retry applies. + */ +const useConnectionStore = create()((set, get) => ({ + state: 'online', + recoveringSince: null, + baselineDataUpdatedAt: 0, + + setOffline: () => { + set({ state: 'offline', recoveringSince: null, baselineDataUpdatedAt: 0 }); + }, + + startRecovery: (baselineDataUpdatedAt) => { + if (get().state === 'recovering') { + return; + } + + set({ + state: 'recovering', + recoveringSince: Date.now(), + baselineDataUpdatedAt, + }); + }, + + settle: () => { + set({ state: 'online', recoveringSince: null, baselineDataUpdatedAt: 0 }); + }, +})); + +export default useConnectionStore; diff --git a/src/renderer/types.ts b/src/renderer/types.ts index 82951f1da..74e36a4ea 100644 --- a/src/renderer/types.ts +++ b/src/renderer/types.ts @@ -54,6 +54,9 @@ export type SearchToken = Branded; export type Status = 'loading' | 'offline' | 'paused' | 'success' | 'error'; +/** Session-local connectivity lifecycle used by the recovery window. */ +export type ConnectionState = 'offline' | 'recovering' | 'online'; + export type Percentage = Branded; export type AccountUUID = Branded; diff --git a/src/renderer/utils/notifications/pollInterval.test.ts b/src/renderer/utils/notifications/pollInterval.test.ts index 724e8f93b..607c2926e 100644 --- a/src/renderer/utils/notifications/pollInterval.test.ts +++ b/src/renderer/utils/notifications/pollInterval.test.ts @@ -5,6 +5,7 @@ import { import { clearServerPollIntervals, + computeNotificationRefetchIntervalMs, computeRefetchIntervalMs, reportServerPollInterval, } from './pollInterval'; @@ -59,4 +60,32 @@ describe('renderer/utils/notifications/pollInterval.ts', () => { expect(computeRefetchIntervalMs(60000, [])).toBe(60000); }); + + describe('computeNotificationRefetchIntervalMs', () => { + it('lets a recovery retry undercut a known server interval', () => { + reportServerPollInterval(mockGitHubCloudAccount, 300); + + expect( + computeNotificationRefetchIntervalMs({ + userIntervalMs: 60000, + accounts: [mockGitHubCloudAccount], + recoveryRetry: true, + recoveryRetryIntervalMs: 5000, + }), + ).toBe(5000); + }); + + it('keeps the server interval as a floor for normal polls', () => { + reportServerPollInterval(mockGitHubCloudAccount, 300); + + expect( + computeNotificationRefetchIntervalMs({ + userIntervalMs: 60000, + accounts: [mockGitHubCloudAccount], + recoveryRetry: false, + recoveryRetryIntervalMs: 5000, + }), + ).toBe(300000); + }); + }); }); diff --git a/src/renderer/utils/notifications/pollInterval.ts b/src/renderer/utils/notifications/pollInterval.ts index 30ae47fef..f2d7740db 100644 --- a/src/renderer/utils/notifications/pollInterval.ts +++ b/src/renderer/utils/notifications/pollInterval.ts @@ -52,6 +52,38 @@ export function computeRefetchIntervalMs(userIntervalMs: number, accounts: Accou return Math.max(userIntervalMs, ...serverIntervalsMs); } +export interface NotificationRefetchIntervalInput { + /** The user-configured fetch interval in milliseconds. */ + userIntervalMs: number; + /** The accounts currently being polled. */ + accounts: Account[]; + /** Whether the next fetch is a recovery retry after a failed attempt. */ + recoveryRetry: boolean; + /** The short cadence to use for a recovery retry. */ + recoveryRetryIntervalMs: number; +} + +/** + * Compute the next notifications refresh interval. + * + * A recovery retry may run sooner than the user/server cadence because the + * previous attempt failed and received no fresh server guidance. Normal polls + * still use {@link computeRefetchIntervalMs}, which keeps the server-recommended + * interval as a floor. + */ +export function computeNotificationRefetchIntervalMs({ + userIntervalMs, + accounts, + recoveryRetry, + recoveryRetryIntervalMs, +}: NotificationRefetchIntervalInput): number { + if (recoveryRetry) { + return recoveryRetryIntervalMs; + } + + return computeRefetchIntervalMs(userIntervalMs, accounts); +} + /** * Clear all reported poll intervals. Intended for use in tests to keep the * module-level state from leaking across cases. diff --git a/src/renderer/utils/notifications/recovery.test.ts b/src/renderer/utils/notifications/recovery.test.ts new file mode 100644 index 000000000..1d544fcff --- /dev/null +++ b/src/renderer/utils/notifications/recovery.test.ts @@ -0,0 +1,98 @@ +import { + mockGitHubCloudAccount, + mockGitHubEnterpriseServerAccount, +} from '../../__mocks__/account-mocks'; + +import type { AccountNotifications, ErrorType } from '../../types'; + +import { getErrorDetails } from '../core/errors'; +import { hasCleanAccount, isRetryableConnectionError, shouldUseRecoveryRetry } from './recovery'; + +function group(errorType: ErrorType | null = null, account = mockGitHubCloudAccount) { + return { + account, + notifications: [], + error: errorType ? getErrorDetails(errorType) : null, + } as AccountNotifications; +} + +describe('renderer/utils/notifications/recovery.ts', () => { + describe('hasCleanAccount', () => { + it('is true when at least one account has no error', () => { + expect(hasCleanAccount([group(), group('BAD_CREDENTIALS')])).toBe(true); + }); + + it('is false when every account has an error', () => { + expect(hasCleanAccount([group('NETWORK'), group('UNKNOWN')])).toBe(false); + }); + + it('is false with no accounts', () => { + expect(hasCleanAccount([])).toBe(false); + }); + }); + + describe('isRetryableConnectionError', () => { + it('is true for all-account network failures', () => { + expect( + isRetryableConnectionError([ + group('NETWORK'), + group('NETWORK', mockGitHubEnterpriseServerAccount), + ]), + ).toBe(true); + }); + + it('is true for unknown classifications during recovery', () => { + expect( + isRetryableConnectionError([ + group('UNKNOWN'), + group('UNKNOWN', mockGitHubEnterpriseServerAccount), + ]), + ).toBe(true); + }); + + it('is false when any definitive error is present', () => { + expect( + isRetryableConnectionError([ + group('NETWORK'), + group('BAD_CREDENTIALS', mockGitHubEnterpriseServerAccount), + ]), + ).toBe(false); + }); + + it('is false for partial success', () => { + expect(isRetryableConnectionError([group(), group('NETWORK')])).toBe(false); + }); + + it('is false with no accounts', () => { + expect(isRetryableConnectionError([])).toBe(false); + }); + }); + + describe('shouldUseRecoveryRetry', () => { + const networkFailures = [group('NETWORK'), group('UNKNOWN', mockGitHubEnterpriseServerAccount)]; + + it('is true while recovering with a retryable failure', () => { + expect(shouldUseRecoveryRetry('recovering', networkFailures)).toBe(true); + }); + + it('is false once recovery ends', () => { + expect(shouldUseRecoveryRetry('online', networkFailures)).toBe(false); + }); + + it('is false while offline', () => { + expect(shouldUseRecoveryRetry('offline', networkFailures)).toBe(false); + }); + + it('is false after a clean success', () => { + expect(shouldUseRecoveryRetry('recovering', [group()])).toBe(false); + }); + + it('is false after a partial success', () => { + expect(shouldUseRecoveryRetry('recovering', [group(), group('NETWORK')])).toBe(false); + }); + + it('is false after a definitive failure', () => { + expect(shouldUseRecoveryRetry('recovering', [group('BAD_CREDENTIALS')])).toBe(false); + }); + }); +}); diff --git a/src/renderer/utils/notifications/recovery.ts b/src/renderer/utils/notifications/recovery.ts new file mode 100644 index 000000000..1a406ab7c --- /dev/null +++ b/src/renderer/utils/notifications/recovery.ts @@ -0,0 +1,56 @@ +import type { AccountNotifications, ConnectionState, ErrorType } from '../../types'; + +import { doesAllAccountsHaveErrors } from '../core/errors'; + +/** + * Error classifications that retrying cannot resolve: they need the user to + * change credentials, scopes, or wait out a rate limit. + */ +const DEFINITIVE_ERROR_TYPES: ReadonlySet = new Set([ + 'ACTION_FORBIDDEN', + 'BAD_CREDENTIALS', + 'MISSING_SCOPES', + 'RATE_LIMITED', +]); + +/** + * Whether at least one account settled without an error. + * + * A single reachable account is enough to treat the connection as online, even + * when other accounts still fail (partial failure). + */ +export function hasCleanAccount(notifications: AccountNotifications[]): boolean { + return notifications.some((accountNotifications) => accountNotifications.error === null); +} + +/** + * Whether a settled all-account failure is likely a connectivity problem worth + * retrying during recovery. + * + * Only GitHub transport failures classify as `NETWORK`; other forges and some + * transport errors fall through to `UNKNOWN`. Treating `UNKNOWN` as retryable + * keeps recovery forge-neutral, while definitive errors (auth, scope, rate + * limit, forbidden) end recovery immediately. + */ +export function isRetryableConnectionError(notifications: AccountNotifications[]): boolean { + return ( + doesAllAccountsHaveErrors(notifications) && + !notifications.some((accountNotifications) => { + const errorType = accountNotifications.error?.type; + return errorType !== undefined && DEFINITIVE_ERROR_TYPES.has(errorType); + }) + ); +} + +/** + * Whether the next notification fetch should use the short recovery retry + * cadence: only while recovering and the latest settled fetch was a retryable + * connection failure. A clean, partial, or definitive outcome returns to the + * normal user/server interval. + */ +export function shouldUseRecoveryRetry( + connectionState: ConnectionState, + notifications: AccountNotifications[], +): boolean { + return connectionState === 'recovering' && isRetryableConnectionError(notifications); +}