Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
fix(mobile): Keep the pull-to-refresh spinner from sticking on screen (#2355)
Chad Pihaba2385888259
diff --git a/openwhispr-mobile/src/hooks/__tests__/useManualSyncRefresh.test.ts b/openwhispr-mobile/src/hooks/__tests__/useManualSyncRefresh.test.tsnew file mode 100644index 000000000..79f29a90b--- /dev/null+++ b/openwhispr-mobile/src/hooks/__tests__/useManualSyncRefresh.test.ts@@ -0,0 +1,60 @@+import { act, renderHook } from '@testing-library/react-native';+import { useSyncStore } from '@/sync/useSyncStore';++let mockIsFocused = true;+jest.mock('@react-navigation/native', () => ({+ useIsFocused: () => mockIsFocused,+}));++let mockSettleSync: () => void = () => {};+const mockRequestSync = jest.fn(() => new Promise<void>((resolve) => (mockSettleSync = resolve)));+jest.mock('@/sync/syncEngine', () => ({+ requestSync: (...args: unknown[]) => mockRequestSync(...(args as [])),+}));++import { useManualSyncRefresh } from '../useManualSyncRefresh';++beforeEach(() => {+ mockIsFocused = true;+ mockRequestSync.mockClear();+ useSyncStore.setState({ status: 'idle' });+});++describe('useManualSyncRefresh', () => {+ // Driving the spinner from every sync is what left it stuck: background syncs+ // (after a dictation, on foreground) flip it while the screen is off-window.+ it('ignores syncs the user did not pull for', () => {+ const { result } = renderHook(() => useManualSyncRefresh());++ act(() => useSyncStore.setState({ status: 'running' }));++ expect(result.current.refreshing).toBe(false);+ });++ it('shows the spinner from the pull until that sync settles', async () => {+ const { result } = renderHook(() => useManualSyncRefresh());++ act(() => result.current.onRefresh());+ expect(mockRequestSync).toHaveBeenCalledWith('manual');+ expect(result.current.refreshing).toBe(true);++ await act(async () => mockSettleSync());+ expect(result.current.refreshing).toBe(false);+ });++ // Ending a UIRefreshControl on an off-window scroll view is the same stuck+ // state, so a sync that settles after the user navigated away ends it on return.+ it('holds the spinner while the screen is unfocused and ends it once focused again', async () => {+ const { result, rerender } = renderHook(() => useManualSyncRefresh());+ act(() => result.current.onRefresh());++ mockIsFocused = false;+ rerender({});+ await act(async () => mockSettleSync());+ expect(result.current.refreshing).toBe(true);++ mockIsFocused = true;+ rerender({});+ expect(result.current.refreshing).toBe(false);+ });+});diff --git a/openwhispr-mobile/src/hooks/useManualSyncRefresh.ts b/openwhispr-mobile/src/hooks/useManualSyncRefresh.tsnew file mode 100644index 000000000..808617daf--- /dev/null+++ b/openwhispr-mobile/src/hooks/useManualSyncRefresh.ts@@ -0,0 +1,33 @@+import { useCallback, useState } from 'react';+import { useIsFocused } from '@react-navigation/native';+import { requestSync } from '@/sync/syncEngine';++interface ManualSyncRefresh {+ refreshing: boolean;+ onRefresh: () => void;+}++// Pull-to-refresh state for a screen that syncs on pull.+//+// The spinner follows only the sync the user pulled for, never the global sync+// status: background syncs (after a dictation, on foreground) would otherwise+// begin and end the UIRefreshControl while its screen sits off-window behind a+// tab or a pushed screen, and iOS leaves it stuck on screen when that happens.+// For the same reason, a pulled sync that settles while the screen is unfocused+// keeps the spinner until the screen is focused again.+export function useManualSyncRefresh(): ManualSyncRefresh {+ const isFocused = useIsFocused();+ const [syncing, setSyncing] = useState(false);+ const [refreshingWhenBlurred, setRefreshingWhenBlurred] = useState(false);++ if (isFocused && refreshingWhenBlurred !== syncing) {+ setRefreshingWhenBlurred(syncing);+ }++ const onRefresh = useCallback((): void => {+ setSyncing(true);+ requestSync('manual').finally(() => setSyncing(false));+ }, []);++ return { refreshing: isFocused ? syncing : refreshingWhenBlurred, onRefresh };+}diff --git a/openwhispr-mobile/src/screens/FoldersScreen.tsx b/openwhispr-mobile/src/screens/FoldersScreen.tsxindex b6bd93eb0..baa05a2f0 100644--- a/openwhispr-mobile/src/screens/FoldersScreen.tsx+++ b/openwhispr-mobile/src/screens/FoldersScreen.tsx@@ -18,8 +18,7 @@ import { groupNotesByDate } from '@/lib/groupNotesByDate';import { safeHaptics } from '@/lib/utils';import { confirmDestructive } from '@/lib/alerts';import { SyncStatusLabel } from '@/components/notes/SyncStatusLabel';-import { useSyncStore } from '@/sync/useSyncStore';-import { requestSync } from '@/sync/syncEngine';+import { useManualSyncRefresh } from '@/hooks/useManualSyncRefresh';import { Fab, FAB_BOTTOM_PADDING, type FabAction } from '@/components/ui/Fab';const FAB_ACTIONS: FabAction[] = [@@ -66,10 +65,7 @@ export default function FoldersScreen() {const teamSpaces = useMemo(() => spaces.filter((s) => s.kind === 'team'), [spaces]);- const syncStatus = useSyncStore((s) => s.status);- const onRefresh = useCallback(() => {- requestSync('manual');- }, []);+ const { refreshing, onRefresh } = useManualSyncRefresh();const goToFolder = useCallback((folderId: number) => {@@ -189,9 +185,7 @@ export default function FoldersScreen() {}}keyboardShouldPersistTaps="handled"keyboardDismissMode="interactive"- refreshControl={- <RefreshControl refreshing={syncStatus === 'running'} onRefresh={onRefresh} />- }+ refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />}><SyncStatusLabel />diff --git a/openwhispr-mobile/src/screens/NotesListScreen.tsx b/openwhispr-mobile/src/screens/NotesListScreen.tsxindex 6293ff2f7..db12c3131 100644--- a/openwhispr-mobile/src/screens/NotesListScreen.tsx+++ b/openwhispr-mobile/src/screens/NotesListScreen.tsx@@ -20,8 +20,7 @@ import { safeHaptics } from '@/lib/utils';import { confirmDestructive } from '@/lib/alerts';import { SyncStatusLabel } from '@/components/notes/SyncStatusLabel';import { VoiceProfilePromptCard } from '@/components/notes/VoiceProfilePromptCard';-import { useSyncStore } from '@/sync/useSyncStore';-import { requestSync } from '@/sync/syncEngine';+import { useManualSyncRefresh } from '@/hooks/useManualSyncRefresh';import { useConfigStore } from '@/store/useConfigStore';export default function NotesListScreen() {@@ -124,10 +123,7 @@ export default function NotesListScreen() {// still be able to report "no results".const showSpaceFolders = spaceId != null && spaceFolders.length > 0 && !searchQuery;- const syncStatus = useSyncStore((s) => s.status);- const onRefresh = useCallback(() => {- requestSync('manual');- }, []);+ const { refreshing, onRefresh } = useManualSyncRefresh();const handleNotePress = useCallback((id: number) => {@@ -313,9 +309,7 @@ export default function NotesListScreen() {}}keyboardShouldPersistTaps="handled"keyboardDismissMode="interactive"- refreshControl={- <RefreshControl refreshing={syncStatus === 'running'} onRefresh={onRefresh} />- }+ refreshControl={<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />}><Text className="mb-2 text-[15px] text-tertiaryLabel">{`${totalCount} ${totalCount === 1 ? 'Note' : 'Notes'}`}</Text><SyncStatusLabel />diff --git a/openwhispr-mobile/src/screens/__tests__/personalFolderScope.test.tsx b/openwhispr-mobile/src/screens/__tests__/personalFolderScope.test.tsxindex 84cc921ce..52cb6f6dc 100644--- a/openwhispr-mobile/src/screens/__tests__/personalFolderScope.test.tsx+++ b/openwhispr-mobile/src/screens/__tests__/personalFolderScope.test.tsx@@ -79,8 +79,8 @@ jest.mock('@/components/ui/Fab', () => ({FAB_BOTTOM_PADDING: 0,}));jest.mock('@/sync/syncEngine', () => ({ requestSync: jest.fn() }));-jest.mock('@/sync/useSyncStore', () => ({- useSyncStore: (selector: (state: { status: string }) => unknown) => selector({ status: 'idle' }),+jest.mock('@/hooks/useManualSyncRefresh', () => ({+ useManualSyncRefresh: () => ({ refreshing: false, onRefresh: jest.fn() }),}));jest.mock('@/components/notes/NoteRow', () => ({ NoteRow: () => null }));jest.mock('@/components/notes/NewFolderSheet', () => ({ NewFolderSheet: () => null }));diff --git a/openwhispr-mobile/src/sync/__tests__/syncEngine.test.ts b/openwhispr-mobile/src/sync/__tests__/syncEngine.test.tsindex 98fb4ec1b..ae0b1f3fb 100644--- a/openwhispr-mobile/src/sync/__tests__/syncEngine.test.ts+++ b/openwhispr-mobile/src/sync/__tests__/syncEngine.test.ts@@ -736,3 +736,51 @@ describe('in-flight cancellation', () => {expect(mockPushSnippets).not.toHaveBeenCalled();});});++// Pull-to-refresh holds its spinner on this promise, so it has to settle once the+// run the request caused is over — including a run that was queued behind another,+// one that failed, and a request that never started a run at all.+describe('requestSync completion promise', () => {+ it('resolves after the run it started has finished', async () => {+ await requestSync('manual');++ const state = useSyncStore.getState();+ expect(state.status).toBe('idle');+ expect(state.lastSyncAt).not.toBeNull();+ });++ it('resolves a request queued behind an in-flight run only once the queued run finishes', async () => {+ let releaseFirstRun: () => void = () => {};+ mockPullNotes.mockImplementationOnce(+ () => new Promise<void>((resolve) => (releaseFirstRun = resolve)),+ );+ const firstRun = requestSync('sign-in');+ await flush();++ let queuedSettled = false;+ const queued = requestSync('manual').then(() => {+ queuedSettled = true;+ });+ await flush();+ expect(queuedSettled).toBe(false);++ releaseFirstRun();+ await firstRun;+ await queued;+ expect(mockPullNotes).toHaveBeenCalledTimes(2);+ });++ it('resolves without rejecting when the run fails', async () => {+ mockPullNotes.mockRejectedValueOnce(new ApiError('server down', 500));++ await expect(requestSync('manual')).resolves.toBeUndefined();+ expect(useSyncStore.getState().status).toBe('error');+ });++ it('resolves when there is nothing to sync', async () => {+ mockAuthState.isGuest = true;++ await expect(requestSync('manual')).resolves.toBeUndefined();+ expect(mockPullNotes).not.toHaveBeenCalled();+ });+});diff --git a/openwhispr-mobile/src/sync/syncEngine.ts b/openwhispr-mobile/src/sync/syncEngine.tsindex f004515ff..28bc58739 100644--- a/openwhispr-mobile/src/sync/syncEngine.ts+++ b/openwhispr-mobile/src/sync/syncEngine.ts@@ -37,6 +37,8 @@ export type SyncReason = 'after-write' | 'foreground' | 'sign-in' | 'manual';let inFlight = false;let pendingTrigger: SyncReason | null = null;+// Callers waiting on the queued run (see requestSync); settled once it ends.+let pendingTriggerWaiters: Array<() => void> = [];let postWriteTimer: ReturnType<typeof setTimeout> | null = null;// The snippets endpoints (/api/snippets/*) may not be deployed yet on the@@ -203,7 +205,7 @@ async function runSyncNow(reason: SyncReason): Promise<void> {if (!auth.user || auth.isGuest) return;if (inFlight) {pendingTrigger = reason;- return;+ return new Promise((resolve) => pendingTriggerWaiters.push(resolve));}const cloudBackupEnabled = useConfigStore.getState().config?.cloudBackupEnabled ?? true;@@ -460,22 +462,30 @@ async function runSyncNow(reason: SyncReason): Promise<void> {inFlight = false;if (pendingTrigger) {const next = pendingTrigger;+ const waiters = pendingTriggerWaiters;pendingTrigger = null;- runSyncNow(next).catch(() => {});+ pendingTriggerWaiters = [];+ runSyncNow(next)+ .catch(() => {})+ .finally(() => waiters.forEach((resolve) => resolve()));}}}-export function requestSync(reason: SyncReason): void {+// Resolves once the run this request started, or was queued behind, has ended —+// success, failure or an early return alike — and never rejects. Pull-to-refresh+// holds its spinner on it. An 'after-write' request only arms the debounce, so+// it resolves right away.+export function requestSync(reason: SyncReason): Promise<void> {if (reason === 'after-write') {if (postWriteTimer) clearTimeout(postWriteTimer);postWriteTimer = setTimeout(() => {postWriteTimer = null;runSyncNow('after-write').catch(() => {});}, POST_WRITE_DEBOUNCE_MS);- return;+ return Promise.resolve();}- runSyncNow(reason).catch(() => {});+ return runSyncNow(reason).catch(() => {});}let unsubscribeAuth: (() => void) | null = null;