Skip to content
Open
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
1 change: 1 addition & 0 deletions ARCHITECTURE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
3 changes: 3 additions & 0 deletions src/renderer/__helpers__/hook-mocks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ function buildNotificationsDefaults(): NotificationsState {
globalError: undefined,

isFetching: false,
isPaused: false,
isError: false,
dataUpdatedAt: 0,

notifications: [],
notificationCount: 0,
Expand Down
8 changes: 7 additions & 1 deletion src/renderer/__helpers__/vitest.setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
Expand Down
8 changes: 6 additions & 2 deletions src/renderer/components/GlobalEffects.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
18 changes: 17 additions & 1 deletion src/renderer/components/GlobalEffects.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -73,6 +88,7 @@ export function GlobalEffects() {
resetSettings();
resetFilters();
queryClient.clear();
useConnectionStore.getState().settle();
useShortcutRegistrationStore.getState().reset();
window.gitify.nativeNotifications.removeAll();
});
Expand Down
8 changes: 8 additions & 0 deletions src/renderer/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
33 changes: 29 additions & 4 deletions src/renderer/hooks/notifications/useNotificationsQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { Constants } from '../../constants';

import {
useAccountsStore,
useConnectionStore,
useFiltersStore,
usePowerStateStore,
useSettingsStore,
Expand All @@ -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';
Expand All @@ -33,6 +35,8 @@ export interface NotificationsQueryResult {
isLoading: boolean;
isError: boolean;
isFetching: boolean;
isPaused: boolean;
dataUpdatedAt: number;
notificationCount: number;
unreadNotificationCount: number;
hasNotifications: boolean;
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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.
Expand All @@ -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,
Expand All @@ -219,6 +242,8 @@ export const useNotificationsQuery = ({ poll }: { poll: boolean }): Notification
isLoading,
isError,
isFetching,
isPaused,
dataUpdatedAt,
notificationCount,
unreadNotificationCount,
hasNotifications,
Expand Down
Loading
Loading