From 816649414d0408088dbd0ba8e19743ab1b7d02b1 Mon Sep 17 00:00:00 2001 From: Diego Mello Date: Fri, 17 Apr 2026 18:42:31 -0300 Subject: [PATCH 1/6] refactor(voip): peer autocomplete slice + NewMediaCall trims - Pass username/sipEnabled into getPeerAutocompleteOptions (remove auxStore) - Thread auth from FilterHeader via useSelector into fetchOptions - Remove setFilter/clearSelection; use setState/setSelectedPeer(null) - Async fetch: filter+peer snapshot + monotonic seq; reset invalidates in-flight - Inline NewMediaCall screen chrome; remove Container + Container story - PeerList passes option directly; composite FlatList keys - Add getPeerAutocompleteOptions tests; extend store tests (reset, stale, seq) Made-with: Cursor --- .../NewMediaCall/Container.stories.tsx | 40 ----- app/containers/NewMediaCall/Container.tsx | 18 -- .../NewMediaCall/FilterHeader.test.tsx | 16 +- app/containers/NewMediaCall/FilterHeader.tsx | 27 ++- app/containers/NewMediaCall/NewMediaCall.tsx | 17 +- app/containers/NewMediaCall/PeerList.tsx | 15 +- .../NewMediaCall/SelectedPeer.test.tsx | 7 +- app/containers/NewMediaCall/SelectedPeer.tsx | 4 +- .../__snapshots__/SelectedPeer.test.tsx.snap | 84 +-------- .../voip/getPeerAutocompleteOptions.test.ts | 162 ++++++++++++++++++ .../voip/getPeerAutocompleteOptions.ts | 37 ++-- .../voip/usePeerAutocompleteStore.test.ts | 99 +++++++---- .../services/voip/usePeerAutocompleteStore.ts | 45 +++-- 13 files changed, 326 insertions(+), 245 deletions(-) delete mode 100644 app/containers/NewMediaCall/Container.stories.tsx delete mode 100644 app/containers/NewMediaCall/Container.tsx create mode 100644 app/lib/services/voip/getPeerAutocompleteOptions.test.ts diff --git a/app/containers/NewMediaCall/Container.stories.tsx b/app/containers/NewMediaCall/Container.stories.tsx deleted file mode 100644 index 41bfa9ef676..00000000000 --- a/app/containers/NewMediaCall/Container.stories.tsx +++ /dev/null @@ -1,40 +0,0 @@ -import React from 'react'; -import { StyleSheet, Text, View } from 'react-native'; - -import { Container } from './Container'; - -const styles = StyleSheet.create({ - root: { - flex: 1 - }, - placeholder: { - marginTop: 8, - padding: 12, - borderRadius: 6, - backgroundColor: '#efefef' - } -}); - -const PlaceholderChildren = () => ( - - Mock children placeholder - -); - -export default { - title: 'NewMediaCall/Container', - component: Container, - decorators: [ - (Story: React.ComponentType) => ( - - - - ) - ] -}; - -export const Default = () => ( - - - -); diff --git a/app/containers/NewMediaCall/Container.tsx b/app/containers/NewMediaCall/Container.tsx deleted file mode 100644 index 94724e34b2f..00000000000 --- a/app/containers/NewMediaCall/Container.tsx +++ /dev/null @@ -1,18 +0,0 @@ -import React from 'react'; -import { StyleSheet, View } from 'react-native'; - -import { useTheme } from '../../theme'; - -export const Container = ({ children }: { children: React.ReactElement[] | React.ReactElement }) => { - const { colors } = useTheme(); - - return {children}; -}; - -const styles = StyleSheet.create({ - container: { - flex: 1, - paddingHorizontal: 16, - paddingTop: 16 - } -}); diff --git a/app/containers/NewMediaCall/FilterHeader.test.tsx b/app/containers/NewMediaCall/FilterHeader.test.tsx index 434a90a548d..aaafe68a1ab 100644 --- a/app/containers/NewMediaCall/FilterHeader.test.tsx +++ b/app/containers/NewMediaCall/FilterHeader.test.tsx @@ -37,15 +37,11 @@ describe('FilterHeader', () => { }); it('should update filter, clear selection and fetch options after debounce', () => { - const setFilter = jest.fn(); - const clearSelection = jest.fn(); const fetchOptions = jest.fn(); usePeerAutocompleteStore.setState({ filter: '', selectedPeer: null, options: [], - setFilter, - clearSelection, fetchOptions }); @@ -57,15 +53,21 @@ describe('FilterHeader', () => { fireEvent.changeText(getByTestId('new-media-call-search-input'), 'alice'); - expect(setFilter).toHaveBeenCalledWith('alice'); - expect(clearSelection).toHaveBeenCalledTimes(1); + expect(usePeerAutocompleteStore.getState().filter).toBe('alice'); + expect(usePeerAutocompleteStore.getState().selectedPeer).toBeNull(); expect(fetchOptions).not.toHaveBeenCalled(); act(() => { jest.advanceTimersByTime(textInputDebounceTime); }); - expect(fetchOptions).toHaveBeenCalledWith('alice'); + expect(fetchOptions).toHaveBeenCalledTimes(1); + expect(fetchOptions.mock.calls[0][0]).toBe('alice'); + expect(fetchOptions.mock.calls[0][1]).toEqual( + expect.objectContaining({ + sipEnabled: expect.any(Boolean) + }) + ); }); }); diff --git a/app/containers/NewMediaCall/FilterHeader.tsx b/app/containers/NewMediaCall/FilterHeader.tsx index aac8b29018d..ba25ef60377 100644 --- a/app/containers/NewMediaCall/FilterHeader.tsx +++ b/app/containers/NewMediaCall/FilterHeader.tsx @@ -1,5 +1,6 @@ -import React from 'react'; +import React, { useCallback } from 'react'; import { StyleSheet, Text, View } from 'react-native'; +import { useSelector } from 'react-redux'; import I18n from '../../i18n'; import { useTheme } from '../../theme'; @@ -7,23 +8,31 @@ import { FormTextInput } from '../TextInput'; import sharedStyles from '../../views/Styles'; import { textInputDebounceTime } from '../../lib/constants/debounceConfig'; import { useDebounce } from '../../lib/methods/helpers'; +import type { IApplicationState } from '../../definitions'; import { usePeerAutocompleteStore } from '../../lib/services/voip/usePeerAutocompleteStore'; export const FilterHeader = (): React.ReactElement => { const { colors } = useTheme(); const filter = usePeerAutocompleteStore(state => state.filter); - const setFilter = usePeerAutocompleteStore(state => state.setFilter); - const fetchOptions = usePeerAutocompleteStore(state => state.fetchOptions); - const clearSelection = usePeerAutocompleteStore(state => state.clearSelection); - const debouncedFetchOptions = useDebounce((value: string) => { - fetchOptions(value); - }, textInputDebounceTime); + const username = useSelector((state: IApplicationState) => state.login.user?.username); + const sipEnabled = useSelector((state: IApplicationState) => + Boolean(state.settings.VoIP_TeamCollab_SIP_Integration_For_Internal_Calls) + ); + + const debouncedFetchOptions = useDebounce( + useCallback( + (value: string) => { + usePeerAutocompleteStore.getState().fetchOptions(value, { username, sipEnabled }); + }, + [username, sipEnabled] + ), + textInputDebounceTime + ); const handleChangeText = (value: string) => { - setFilter(value); - clearSelection(); + usePeerAutocompleteStore.setState({ filter: value, selectedPeer: null }); debouncedFetchOptions(value); }; diff --git a/app/containers/NewMediaCall/NewMediaCall.tsx b/app/containers/NewMediaCall/NewMediaCall.tsx index d4da5e70db7..f19a92d80fb 100644 --- a/app/containers/NewMediaCall/NewMediaCall.tsx +++ b/app/containers/NewMediaCall/NewMediaCall.tsx @@ -1,23 +1,32 @@ import React, { useEffect } from 'react'; +import { StyleSheet, View } from 'react-native'; import { PeerList } from './PeerList'; import { SelectedPeer } from './SelectedPeer'; -import { Container } from './Container'; import { CreateCall } from './CreateCall'; import { FilterHeader } from './FilterHeader'; import { usePeerAutocompleteStore } from '../../lib/services/voip/usePeerAutocompleteStore'; +import { useTheme } from '../../theme'; export const NewMediaCall = (): React.ReactElement => { - // reset the store when the action sheet is closed + const { colors } = useTheme(); const reset = usePeerAutocompleteStore(state => state.reset); useEffect(() => () => reset(), [reset]); return ( - + - + ); }; + +const styles = StyleSheet.create({ + screen: { + flex: 1, + paddingHorizontal: 16, + paddingTop: 16 + } +}); diff --git a/app/containers/NewMediaCall/PeerList.tsx b/app/containers/NewMediaCall/PeerList.tsx index 68470b8903f..9c28dd3ada3 100644 --- a/app/containers/NewMediaCall/PeerList.tsx +++ b/app/containers/NewMediaCall/PeerList.tsx @@ -13,18 +13,7 @@ export const PeerList = () => { if (selectedPeer) return null; const handleSelectOption = (option: TPeerItem) => { - const peerItem: TPeerItem = - option.type === 'sip' - ? { type: 'sip', value: option.value, label: option.label } - : { - type: 'user', - value: option.value, - label: option.label, - username: option.username, - callerId: option.callerId - }; - - setSelectedPeer(peerItem); + setSelectedPeer(option); }; const renderItem = ({ item }: { item: TPeerItem }) => ; @@ -33,7 +22,7 @@ export const PeerList = () => { item.value} + keyExtractor={item => `${item.type}:${item.value}`} keyboardShouldPersistTaps='always' renderItem={renderItem} ItemSeparatorComponent={List.Separator} diff --git a/app/containers/NewMediaCall/SelectedPeer.test.tsx b/app/containers/NewMediaCall/SelectedPeer.test.tsx index 2b58fffae8c..767f36b8b51 100644 --- a/app/containers/NewMediaCall/SelectedPeer.test.tsx +++ b/app/containers/NewMediaCall/SelectedPeer.test.tsx @@ -69,9 +69,8 @@ describe('SelectedPeer', () => { expect(getByText('+55 11 99999-9999')).toBeTruthy(); }); - it('should call clearSelection when clear button is pressed', () => { - const clearSelection = jest.fn(); - usePeerAutocompleteStore.setState({ selectedPeer: userPeer, clearSelection }); + it('should clear selected peer when clear button is pressed', () => { + usePeerAutocompleteStore.setState({ selectedPeer: userPeer }); const { getByTestId } = render( @@ -80,7 +79,7 @@ describe('SelectedPeer', () => { ); fireEvent.press(getByTestId('new-media-call-clear-selected-peer')); - expect(clearSelection).toHaveBeenCalledTimes(1); + expect(usePeerAutocompleteStore.getState().selectedPeer).toBeNull(); }); }); diff --git a/app/containers/NewMediaCall/SelectedPeer.tsx b/app/containers/NewMediaCall/SelectedPeer.tsx index e3faee6caa9..c60851d527b 100644 --- a/app/containers/NewMediaCall/SelectedPeer.tsx +++ b/app/containers/NewMediaCall/SelectedPeer.tsx @@ -15,7 +15,7 @@ export const SelectedPeer = () => { export const SelectedPeerInner = ({ selectedPeer }: { selectedPeer: TPeerItem | null }) => { const { colors } = useTheme(); - const clearSelection = usePeerAutocompleteStore(state => state.clearSelection); + const setSelectedPeer = usePeerAutocompleteStore(state => state.setSelectedPeer); if (!selectedPeer) return null; @@ -24,7 +24,7 @@ export const SelectedPeerInner = ({ selectedPeer }: { selectedPeer: TPeerItem | setSelectedPeer(null)} testID='new-media-call-clear-selected-peer' rippleColor={colors.buttonBackgroundSecondaryPress} foreground diff --git a/app/containers/NewMediaCall/__snapshots__/SelectedPeer.test.tsx.snap b/app/containers/NewMediaCall/__snapshots__/SelectedPeer.test.tsx.snap index 316c128f715..1ee4385af09 100644 --- a/app/containers/NewMediaCall/__snapshots__/SelectedPeer.test.tsx.snap +++ b/app/containers/NewMediaCall/__snapshots__/SelectedPeer.test.tsx.snap @@ -201,19 +201,7 @@ exports[`Story Snapshots: All should match snapshot 1`] = ` onActiveStateChange={[Function]} onGestureHandlerEvent={[Function]} onGestureHandlerStateChange={[Function]} - onPress={ - [MockFunction] { - "calls": [ - [], - ], - "results": [ - { - "type": "return", - "value": undefined, - }, - ], - } - } + onPress={[Function]} rippleColor="#9EA2A8" style={ [ @@ -386,19 +374,7 @@ exports[`Story Snapshots: All should match snapshot 1`] = ` onActiveStateChange={[Function]} onGestureHandlerEvent={[Function]} onGestureHandlerStateChange={[Function]} - onPress={ - [MockFunction] { - "calls": [ - [], - ], - "results": [ - { - "type": "return", - "value": undefined, - }, - ], - } - } + onPress={[Function]} rippleColor="#9EA2A8" style={ [ @@ -633,19 +609,7 @@ exports[`Story Snapshots: All should match snapshot 1`] = ` onActiveStateChange={[Function]} onGestureHandlerEvent={[Function]} onGestureHandlerStateChange={[Function]} - onPress={ - [MockFunction] { - "calls": [ - [], - ], - "results": [ - { - "type": "return", - "value": undefined, - }, - ], - } - } + onPress={[Function]} rippleColor="#9EA2A8" style={ [ @@ -893,19 +857,7 @@ exports[`Story Snapshots: LongUsername should match snapshot 1`] = ` onActiveStateChange={[Function]} onGestureHandlerEvent={[Function]} onGestureHandlerStateChange={[Function]} - onPress={ - [MockFunction] { - "calls": [ - [], - ], - "results": [ - { - "type": "return", - "value": undefined, - }, - ], - } - } + onPress={[Function]} rippleColor="#9EA2A8" style={ [ @@ -1091,19 +1043,7 @@ exports[`Story Snapshots: Sip should match snapshot 1`] = ` onActiveStateChange={[Function]} onGestureHandlerEvent={[Function]} onGestureHandlerStateChange={[Function]} - onPress={ - [MockFunction] { - "calls": [ - [], - ], - "results": [ - { - "type": "return", - "value": undefined, - }, - ], - } - } + onPress={[Function]} rippleColor="#9EA2A8" style={ [ @@ -1351,19 +1291,7 @@ exports[`Story Snapshots: User should match snapshot 1`] = ` onActiveStateChange={[Function]} onGestureHandlerEvent={[Function]} onGestureHandlerStateChange={[Function]} - onPress={ - [MockFunction] { - "calls": [ - [], - ], - "results": [ - { - "type": "return", - "value": undefined, - }, - ], - } - } + onPress={[Function]} rippleColor="#9EA2A8" style={ [ diff --git a/app/lib/services/voip/getPeerAutocompleteOptions.test.ts b/app/lib/services/voip/getPeerAutocompleteOptions.test.ts new file mode 100644 index 00000000000..4ee5fd3764c --- /dev/null +++ b/app/lib/services/voip/getPeerAutocompleteOptions.test.ts @@ -0,0 +1,162 @@ +import { usersAutoComplete } from '../restApi'; +import { getPeerAutocompleteOptions, type TPeerItem } from './getPeerAutocompleteOptions'; + +jest.mock('../restApi', () => ({ + usersAutoComplete: jest.fn() +})); + +const mockedUsersAutoComplete = usersAutoComplete as jest.MockedFunction; + +describe('getPeerAutocompleteOptions', () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + it('returns empty array when filter is empty or whitespace', async () => { + await expect( + getPeerAutocompleteOptions({ + filter: '', + peerInfo: null, + username: 'me', + sipEnabled: false + }) + ).resolves.toEqual([]); + + await expect( + getPeerAutocompleteOptions({ + filter: ' ', + peerInfo: null, + username: 'me', + sipEnabled: false + }) + ).resolves.toEqual([]); + + expect(mockedUsersAutoComplete).not.toHaveBeenCalled(); + }); + + it('returns SIP option first then mapped user options (user branch)', async () => { + mockedUsersAutoComplete.mockResolvedValue({ + success: true, + items: [ + { _id: 'u1', name: 'Alice', username: 'alice', freeSwitchExtension: '1001' }, + { _id: 'u2', name: '', username: 'bob', freeSwitchExtension: undefined } + ] + }); + + const result = await getPeerAutocompleteOptions({ + filter: 'ali', + peerInfo: null, + username: 'current.user', + sipEnabled: false + }); + + expect(mockedUsersAutoComplete).toHaveBeenCalledWith({ + term: 'ali', + exceptions: ['current.user'] + }); + + expect(result).toEqual([ + { type: 'sip', value: 'ali', label: 'ali' }, + { + type: 'user', + value: 'u1', + label: 'Alice', + username: 'alice', + callerId: '1001' + }, + { + type: 'user', + value: 'u2', + label: 'bob', + username: 'bob', + callerId: undefined + } + ] satisfies TPeerItem[]); + }); + + it('SIP branch: when sipEnabled, adds freeSwitchExtension exists condition', async () => { + mockedUsersAutoComplete.mockResolvedValue({ success: true, items: [] }); + + await getPeerAutocompleteOptions({ + filter: '123', + peerInfo: null, + username: 'me', + sipEnabled: true + }); + + expect(mockedUsersAutoComplete).toHaveBeenCalledWith({ + term: '123', + exceptions: ['me'], + conditions: { + $and: [{ freeSwitchExtension: { $exists: true } }] + } + }); + }); + + it('SIP branch: when selected peer has callerId, excludes matching extension and adds peer username to exceptions', async () => { + mockedUsersAutoComplete.mockResolvedValue({ success: true, items: [] }); + + const peerInfo: TPeerItem = { + type: 'user', + value: 'other', + label: 'Other', + username: 'other.user', + callerId: '2002' + }; + + await getPeerAutocompleteOptions({ + filter: '99', + peerInfo, + username: 'me', + sipEnabled: true + }); + + expect(mockedUsersAutoComplete).toHaveBeenCalledWith({ + term: '99', + exceptions: ['me', 'other.user'], + conditions: { + $and: [{ freeSwitchExtension: { $exists: true } }, { freeSwitchExtension: { $ne: '2002' } }] + } + }); + }); + + it('when sipEnabled is false but peer has callerId, still applies extension exclusion only', async () => { + mockedUsersAutoComplete.mockResolvedValue({ success: true, items: [] }); + + const peerInfo: TPeerItem = { + type: 'user', + value: 'other', + label: 'Other', + username: 'peer', + callerId: '3003' + }; + + await getPeerAutocompleteOptions({ + filter: 'x', + peerInfo, + username: undefined, + sipEnabled: false + }); + + expect(mockedUsersAutoComplete).toHaveBeenCalledWith({ + term: 'x', + exceptions: ['peer'], + conditions: { + $and: [{ freeSwitchExtension: { $ne: '3003' } }] + } + }); + }); + + it('returns only SIP option when API returns success false with no items', async () => { + mockedUsersAutoComplete.mockResolvedValue({ success: false, items: [] }); + + const result = await getPeerAutocompleteOptions({ + filter: 'solo', + peerInfo: null, + username: 'me', + sipEnabled: false + }); + + expect(result).toEqual([{ type: 'sip', value: 'solo', label: 'solo' }]); + }); +}); diff --git a/app/lib/services/voip/getPeerAutocompleteOptions.ts b/app/lib/services/voip/getPeerAutocompleteOptions.ts index e54d2c78efc..5c2cd5d5ab1 100644 --- a/app/lib/services/voip/getPeerAutocompleteOptions.ts +++ b/app/lib/services/voip/getPeerAutocompleteOptions.ts @@ -1,5 +1,4 @@ import { usersAutoComplete } from '../restApi'; -import { store as reduxStore } from '../../store/auxStore'; export type TPeerItem = | { type: 'user'; value: string; label: string; username?: string; callerId?: string } @@ -15,51 +14,39 @@ type TUserAutocompleteResponse = { }>; }; -const getExtensionFromPeerInfo = (peerInfo?: TPeerItem | null): string | undefined => { - if (!peerInfo || !('callerId' in peerInfo)) { - return undefined; - } - - return peerInfo.callerId; -}; - -const getPeerUsername = (peerInfo?: TPeerItem | null): string | undefined => { - if (!peerInfo || !('username' in peerInfo)) { - return undefined; - } - - return peerInfo.username; +export type TPeerAutocompleteAuth = { + username?: string; + sipEnabled: boolean; }; -// TODO: hook? export const getPeerAutocompleteOptions = async ({ filter, - peerInfo + peerInfo, + username, + sipEnabled }: { filter: string; peerInfo?: TPeerItem | null; -}): Promise => { +} & TPeerAutocompleteAuth): Promise => { const term = filter.trim(); if (!term) { return []; } - const currentUsername = reduxStore.getState().login.user.username as string | undefined; - const peerUsername = getPeerUsername(peerInfo); - const peerExtension = getExtensionFromPeerInfo(peerInfo); - const forceSIPRouting = Boolean(reduxStore.getState().settings.VoIP_TeamCollab_SIP_Integration_For_Internal_Calls); + const peerUsername = peerInfo && 'username' in peerInfo ? peerInfo.username : undefined; + const peerExtension = peerInfo && 'callerId' in peerInfo ? peerInfo.callerId : undefined; const conditions = - peerExtension || forceSIPRouting + peerExtension || sipEnabled ? { $and: [ - forceSIPRouting ? { freeSwitchExtension: { $exists: true } } : null, + sipEnabled ? { freeSwitchExtension: { $exists: true } } : null, peerExtension ? { freeSwitchExtension: { $ne: peerExtension } } : null ].filter(Boolean) } : undefined; - const exceptions = [currentUsername, peerUsername].filter(Boolean); + const exceptions = [username, peerUsername].filter(Boolean); const selector = { term, exceptions, diff --git a/app/lib/services/voip/usePeerAutocompleteStore.test.ts b/app/lib/services/voip/usePeerAutocompleteStore.test.ts index b0e2e6e01bd..c0c6722f135 100644 --- a/app/lib/services/voip/usePeerAutocompleteStore.test.ts +++ b/app/lib/services/voip/usePeerAutocompleteStore.test.ts @@ -16,6 +16,8 @@ const userPeer: TPeerItem = { username: 'alice.johnson' }; +const auth = { username: 'me', sipEnabled: false }; + const mockOptions: TPeerItem[] = [ userPeer, { @@ -36,51 +38,62 @@ describe('usePeerAutocompleteStore', () => { mockGetPeerAutocompleteOptions.mockResolvedValue(mockOptions); }); - describe('setSelectedPeer', () => { - it('should set selected peer', () => { + describe('reset', () => { + it('should clear options, selected peer and filter', () => { + usePeerAutocompleteStore.setState({ + filter: 'x', + options: mockOptions, + selectedPeer: userPeer + }); const { result } = renderHook(() => usePeerAutocompleteStore()); act(() => { - result.current.setSelectedPeer(userPeer); + result.current.reset(); }); - expect(usePeerAutocompleteStore.getState().selectedPeer).toEqual(userPeer); + expect(usePeerAutocompleteStore.getState()).toMatchObject({ + options: [], + selectedPeer: null, + filter: '' + }); }); + }); - it('should clear selected peer when null is passed', () => { - usePeerAutocompleteStore.setState({ selectedPeer: userPeer }); + describe('setSelectedPeer', () => { + it('should set selected peer', () => { const { result } = renderHook(() => usePeerAutocompleteStore()); act(() => { - result.current.setSelectedPeer(null); + result.current.setSelectedPeer(userPeer); }); - expect(usePeerAutocompleteStore.getState().selectedPeer).toBeNull(); + expect(usePeerAutocompleteStore.getState().selectedPeer).toEqual(userPeer); }); - }); - describe('setFilter', () => { - it('should set filter value', () => { + it('should clear selected peer and options when null is passed without clearing filter', () => { + usePeerAutocompleteStore.setState({ selectedPeer: userPeer, filter: 'keep', options: mockOptions }); const { result } = renderHook(() => usePeerAutocompleteStore()); act(() => { - result.current.setFilter('alice'); + result.current.setSelectedPeer(null); }); - expect(usePeerAutocompleteStore.getState().filter).toBe('alice'); + expect(usePeerAutocompleteStore.getState().selectedPeer).toBeNull(); + expect(usePeerAutocompleteStore.getState().filter).toBe('keep'); + expect(usePeerAutocompleteStore.getState().options).toEqual([]); }); - }); - describe('clearSelection', () => { - it('should clear selected peer', () => { - usePeerAutocompleteStore.setState({ selectedPeer: userPeer }); + it('should clear filter and options when selecting a peer', () => { + usePeerAutocompleteStore.setState({ filter: 'q', options: mockOptions, selectedPeer: null }); const { result } = renderHook(() => usePeerAutocompleteStore()); act(() => { - result.current.clearSelection(); + result.current.setSelectedPeer(userPeer); }); - expect(usePeerAutocompleteStore.getState().selectedPeer).toBeNull(); + expect(usePeerAutocompleteStore.getState().selectedPeer).toEqual(userPeer); + expect(usePeerAutocompleteStore.getState().filter).toBe(''); + expect(usePeerAutocompleteStore.getState().options).toEqual([]); }); }); @@ -89,7 +102,7 @@ describe('usePeerAutocompleteStore', () => { const { result } = renderHook(() => usePeerAutocompleteStore()); await act(async () => { - await result.current.fetchOptions(''); + await result.current.fetchOptions('', auth); }); expect(usePeerAutocompleteStore.getState().options).toEqual([]); @@ -100,7 +113,7 @@ describe('usePeerAutocompleteStore', () => { const { result } = renderHook(() => usePeerAutocompleteStore()); await act(async () => { - await result.current.fetchOptions(' '); + await result.current.fetchOptions(' ', auth); }); expect(usePeerAutocompleteStore.getState().options).toEqual([]); @@ -108,43 +121,71 @@ describe('usePeerAutocompleteStore', () => { }); it('should fetch and set options when filter has value', async () => { + usePeerAutocompleteStore.setState({ filter: 'alice' }); const { result } = renderHook(() => usePeerAutocompleteStore()); await act(async () => { - await result.current.fetchOptions('alice'); + await result.current.fetchOptions('alice', auth); }); expect(mockGetPeerAutocompleteOptions).toHaveBeenCalledWith({ filter: 'alice', - peerInfo: null + peerInfo: null, + username: 'me', + sipEnabled: false }); expect(usePeerAutocompleteStore.getState().options).toEqual(mockOptions); }); it('should pass selected peer to getPeerAutocompleteOptions', async () => { - usePeerAutocompleteStore.setState({ selectedPeer: userPeer }); + usePeerAutocompleteStore.setState({ selectedPeer: userPeer, filter: 'bob' }); const { result } = renderHook(() => usePeerAutocompleteStore()); await act(async () => { - await result.current.fetchOptions('bob'); + await result.current.fetchOptions('bob', { username: 'x', sipEnabled: true }); }); expect(mockGetPeerAutocompleteOptions).toHaveBeenCalledWith({ filter: 'bob', - peerInfo: userPeer + peerInfo: userPeer, + username: 'x', + sipEnabled: true }); }); - it('should set empty options on fetch error', async () => { + it('should set empty options on fetch error when filter unchanged', async () => { mockGetPeerAutocompleteOptions.mockRejectedValue(new Error('API error')); - + usePeerAutocompleteStore.setState({ filter: 'alice' }); const { result } = renderHook(() => usePeerAutocompleteStore()); await act(async () => { - await result.current.fetchOptions('alice'); + await result.current.fetchOptions('alice', auth); }); expect(usePeerAutocompleteStore.getState().options).toEqual([]); }); + + it('should not apply stale results when filter changes before response resolves', async () => { + let resolveSlow!: (value: TPeerItem[]) => void; + const slowPromise = new Promise(res => { + resolveSlow = res; + }); + + mockGetPeerAutocompleteOptions.mockReturnValueOnce(slowPromise); + mockGetPeerAutocompleteOptions.mockResolvedValueOnce([{ type: 'sip', value: 'fast', label: 'fast' }]); + + const { result } = renderHook(() => usePeerAutocompleteStore()); + + await act(async () => { + usePeerAutocompleteStore.setState({ filter: 'slow', selectedPeer: null }); + const slowReq = result.current.fetchOptions('slow', auth); + usePeerAutocompleteStore.setState({ filter: 'fast' }); + await result.current.fetchOptions('fast', auth); + resolveSlow([{ type: 'sip', value: 'stale', label: 'stale' }]); + await slowReq; + }); + + expect(usePeerAutocompleteStore.getState().options).toEqual([{ type: 'sip', value: 'fast', label: 'fast' }]); + }); }); }); diff --git a/app/lib/services/voip/usePeerAutocompleteStore.ts b/app/lib/services/voip/usePeerAutocompleteStore.ts index e34ead9f56d..841933084f2 100644 --- a/app/lib/services/voip/usePeerAutocompleteStore.ts +++ b/app/lib/services/voip/usePeerAutocompleteStore.ts @@ -1,6 +1,8 @@ import { create } from 'zustand'; -import { getPeerAutocompleteOptions, type TPeerItem } from './getPeerAutocompleteOptions'; +import { getPeerAutocompleteOptions, type TPeerAutocompleteAuth, type TPeerItem } from './getPeerAutocompleteOptions'; + +let peerAutocompleteFetchSeq = 0; type TPeerAutocompleteState = { options: TPeerItem[]; @@ -9,10 +11,8 @@ type TPeerAutocompleteState = { }; type TPeerAutocompleteActions = { - fetchOptions: (filter: string) => Promise; + fetchOptions: (filter: string, auth: TPeerAutocompleteAuth) => Promise; setSelectedPeer: (peer: TPeerItem | null) => void; - setFilter: (filter: string) => void; - clearSelection: () => void; reset: () => void; }; @@ -23,39 +23,52 @@ export const usePeerAutocompleteStore = create((set, get selectedPeer: null, filter: '', - fetchOptions: async (filter: string) => { + fetchOptions: async (filter: string, auth: TPeerAutocompleteAuth) => { const term = filter.trim(); if (!term) { set({ options: [] }); return; } + const peerSnapshot = get().selectedPeer; + const seq = ++peerAutocompleteFetchSeq; + try { - const currentPeer = get().selectedPeer; const options = await getPeerAutocompleteOptions({ filter: term, - peerInfo: currentPeer + peerInfo: peerSnapshot, + username: auth.username, + sipEnabled: auth.sipEnabled }); + if (seq !== peerAutocompleteFetchSeq) { + return; + } + if (get().filter.trim() !== term || get().selectedPeer !== peerSnapshot) { + return; + } + set({ options }); } catch { - set({ options: [] }); + if (seq !== peerAutocompleteFetchSeq) { + return; + } + if (get().filter.trim() === term && get().selectedPeer === peerSnapshot) { + set({ options: [] }); + } } }, setSelectedPeer: (peer: TPeerItem | null) => { + if (peer === null) { + set({ selectedPeer: null, options: [] }); + return; + } set({ selectedPeer: peer, filter: '', options: [] }); }, - setFilter: (filter: string) => { - set({ filter }); - }, - - clearSelection: () => { - set({ selectedPeer: null }); - }, - reset: () => { + peerAutocompleteFetchSeq++; set({ options: [], selectedPeer: null, filter: '' }); } })); From 25573d34479ea3ddd40ad0fb6e4628c50c4e98f3 Mon Sep 17 00:00:00 2001 From: Diego Mello Date: Mon, 20 Apr 2026 16:24:58 -0300 Subject: [PATCH 2/6] refactor(voip): address PR review on peer autocomplete slice Apply review feedback from PR #7175: - Move fetchSeq increment above empty-filter early return so every invocation invalidates in-flight requests; scope seq to store closure. - Drop redundant filter/selectedPeer post-await stale guards; rely on seq alone. - Keep service pure: getPeerAutocompleteOptions takes username/sipEnabled via TPeerAutocompleteAuth instead of reading Redux. - Trim filter once at the store boundary. - Narrow peerInfo via discriminated-union on type. - Add tests for service trimming, current-username exclusion, SIP-disabled routing, and store-boundary trim. - FilterHeader: named selectSipEnabled/selectUsername, drop useCallback wrapper around useDebounce. - Typed mocks: canonical mockUsersAutoCompleteResponse helper; failure shape carries error. - Drop dead commented setIceServers line in MediaSessionInstance. --- app/containers/NewMediaCall/FilterHeader.tsx | 24 ++-- app/lib/services/voip/MediaSessionInstance.ts | 1 - .../voip/getPeerAutocompleteOptions.test.ts | 111 ++++++++++++++---- .../voip/getPeerAutocompleteOptions.ts | 14 +-- .../voip/usePeerAutocompleteStore.test.ts | 30 +++++ .../services/voip/usePeerAutocompleteStore.ts | 89 +++++++------- 6 files changed, 181 insertions(+), 88 deletions(-) diff --git a/app/containers/NewMediaCall/FilterHeader.tsx b/app/containers/NewMediaCall/FilterHeader.tsx index ba25ef60377..1cb563aff15 100644 --- a/app/containers/NewMediaCall/FilterHeader.tsx +++ b/app/containers/NewMediaCall/FilterHeader.tsx @@ -1,4 +1,4 @@ -import React, { useCallback } from 'react'; +import React from 'react'; import { StyleSheet, Text, View } from 'react-native'; import { useSelector } from 'react-redux'; @@ -11,25 +11,21 @@ import { useDebounce } from '../../lib/methods/helpers'; import type { IApplicationState } from '../../definitions'; import { usePeerAutocompleteStore } from '../../lib/services/voip/usePeerAutocompleteStore'; +const selectSipEnabled = (state: IApplicationState) => Boolean(state.settings.VoIP_TeamCollab_SIP_Integration_For_Internal_Calls); + +const selectUsername = (state: IApplicationState) => state.login.user?.username; + export const FilterHeader = (): React.ReactElement => { const { colors } = useTheme(); const filter = usePeerAutocompleteStore(state => state.filter); - const username = useSelector((state: IApplicationState) => state.login.user?.username); - const sipEnabled = useSelector((state: IApplicationState) => - Boolean(state.settings.VoIP_TeamCollab_SIP_Integration_For_Internal_Calls) - ); + const username = useSelector(selectUsername); + const sipEnabled = useSelector(selectSipEnabled); - const debouncedFetchOptions = useDebounce( - useCallback( - (value: string) => { - usePeerAutocompleteStore.getState().fetchOptions(value, { username, sipEnabled }); - }, - [username, sipEnabled] - ), - textInputDebounceTime - ); + const debouncedFetchOptions = useDebounce((value: string) => { + usePeerAutocompleteStore.getState().fetchOptions(value, { username, sipEnabled }); + }, textInputDebounceTime); const handleChangeText = (value: string) => { usePeerAutocompleteStore.setState({ filter: value, selectedPeer: null }); diff --git a/app/lib/services/voip/MediaSessionInstance.ts b/app/lib/services/voip/MediaSessionInstance.ts index d58d7aba1a0..432af37bc9c 100644 --- a/app/lib/services/voip/MediaSessionInstance.ts +++ b/app/lib/services/voip/MediaSessionInstance.ts @@ -236,7 +236,6 @@ class MediaSessionInstance { const currentIceServers = this.getIceServers(); if (currentIceServers !== this.iceServers) { this.iceServers = currentIceServers; - // this.instance?.setIceServers(this.iceServers); } }); } diff --git a/app/lib/services/voip/getPeerAutocompleteOptions.test.ts b/app/lib/services/voip/getPeerAutocompleteOptions.test.ts index 4ee5fd3764c..ba63aa6dcb9 100644 --- a/app/lib/services/voip/getPeerAutocompleteOptions.test.ts +++ b/app/lib/services/voip/getPeerAutocompleteOptions.test.ts @@ -5,14 +5,31 @@ jest.mock('../restApi', () => ({ usersAutoComplete: jest.fn() })); +type TUsersAutoCompleteResponse = Awaited>; + const mockedUsersAutoComplete = usersAutoComplete as jest.MockedFunction; +type TAutoCompleteItem = { + _id: string; + name?: string; + username?: string; + freeSwitchExtension?: string; +}; + +const mockUsersAutoCompleteResponse = ( + items: TAutoCompleteItem[] = [], + overrides: { success?: boolean; error?: string | null } = {} +): TUsersAutoCompleteResponse => { + const { success = true, error = null } = overrides; + return { items, success, error } as unknown as TUsersAutoCompleteResponse; +}; + describe('getPeerAutocompleteOptions', () => { beforeEach(() => { jest.clearAllMocks(); }); - it('returns empty array when filter is empty or whitespace', async () => { + it('returns empty array and skips API call when filter is empty', async () => { await expect( getPeerAutocompleteOptions({ filter: '', @@ -22,26 +39,64 @@ describe('getPeerAutocompleteOptions', () => { }) ).resolves.toEqual([]); - await expect( - getPeerAutocompleteOptions({ - filter: ' ', - peerInfo: null, - username: 'me', - sipEnabled: false - }) - ).resolves.toEqual([]); - expect(mockedUsersAutoComplete).not.toHaveBeenCalled(); }); + it('does not trim the filter (trimming is the store boundary responsibility)', async () => { + mockedUsersAutoComplete.mockResolvedValue(mockUsersAutoCompleteResponse()); + + await getPeerAutocompleteOptions({ + filter: ' alice ', + peerInfo: null, + username: 'me', + sipEnabled: false + }); + + expect(mockedUsersAutoComplete).toHaveBeenCalledWith({ + term: ' alice ', + exceptions: ['me'] + }); + }); + + it('excludes the current username from results', async () => { + mockedUsersAutoComplete.mockResolvedValue(mockUsersAutoCompleteResponse()); + + await getPeerAutocompleteOptions({ + filter: 'ali', + peerInfo: null, + username: 'current.user', + sipEnabled: false + }); + + expect(mockedUsersAutoComplete).toHaveBeenCalledWith({ + term: 'ali', + exceptions: ['current.user'] + }); + }); + + it('omits current username from exceptions when it is not provided', async () => { + mockedUsersAutoComplete.mockResolvedValue(mockUsersAutoCompleteResponse()); + + await getPeerAutocompleteOptions({ + filter: 'ali', + peerInfo: null, + username: undefined, + sipEnabled: false + }); + + expect(mockedUsersAutoComplete).toHaveBeenCalledWith({ + term: 'ali', + exceptions: [] + }); + }); + it('returns SIP option first then mapped user options (user branch)', async () => { - mockedUsersAutoComplete.mockResolvedValue({ - success: true, - items: [ + mockedUsersAutoComplete.mockResolvedValue( + mockUsersAutoCompleteResponse([ { _id: 'u1', name: 'Alice', username: 'alice', freeSwitchExtension: '1001' }, { _id: 'u2', name: '', username: 'bob', freeSwitchExtension: undefined } - ] - }); + ]) + ); const result = await getPeerAutocompleteOptions({ filter: 'ali', @@ -74,8 +129,24 @@ describe('getPeerAutocompleteOptions', () => { ] satisfies TPeerItem[]); }); + it('SIP disabled: omits the freeSwitchExtension conditions entirely', async () => { + mockedUsersAutoComplete.mockResolvedValue(mockUsersAutoCompleteResponse()); + + await getPeerAutocompleteOptions({ + filter: 'alice', + peerInfo: null, + username: 'me', + sipEnabled: false + }); + + expect(mockedUsersAutoComplete).toHaveBeenCalledWith({ + term: 'alice', + exceptions: ['me'] + }); + }); + it('SIP branch: when sipEnabled, adds freeSwitchExtension exists condition', async () => { - mockedUsersAutoComplete.mockResolvedValue({ success: true, items: [] }); + mockedUsersAutoComplete.mockResolvedValue(mockUsersAutoCompleteResponse()); await getPeerAutocompleteOptions({ filter: '123', @@ -94,7 +165,7 @@ describe('getPeerAutocompleteOptions', () => { }); it('SIP branch: when selected peer has callerId, excludes matching extension and adds peer username to exceptions', async () => { - mockedUsersAutoComplete.mockResolvedValue({ success: true, items: [] }); + mockedUsersAutoComplete.mockResolvedValue(mockUsersAutoCompleteResponse()); const peerInfo: TPeerItem = { type: 'user', @@ -121,7 +192,7 @@ describe('getPeerAutocompleteOptions', () => { }); it('when sipEnabled is false but peer has callerId, still applies extension exclusion only', async () => { - mockedUsersAutoComplete.mockResolvedValue({ success: true, items: [] }); + mockedUsersAutoComplete.mockResolvedValue(mockUsersAutoCompleteResponse()); const peerInfo: TPeerItem = { type: 'user', @@ -147,8 +218,8 @@ describe('getPeerAutocompleteOptions', () => { }); }); - it('returns only SIP option when API returns success false with no items', async () => { - mockedUsersAutoComplete.mockResolvedValue({ success: false, items: [] }); + it('returns only SIP option when API returns success false with items', async () => { + mockedUsersAutoComplete.mockResolvedValue(mockUsersAutoCompleteResponse([], { success: false, error: 'error-not-allowed' })); const result = await getPeerAutocompleteOptions({ filter: 'solo', diff --git a/app/lib/services/voip/getPeerAutocompleteOptions.ts b/app/lib/services/voip/getPeerAutocompleteOptions.ts index 5c2cd5d5ab1..0161f320e49 100644 --- a/app/lib/services/voip/getPeerAutocompleteOptions.ts +++ b/app/lib/services/voip/getPeerAutocompleteOptions.ts @@ -6,6 +6,7 @@ export type TPeerItem = type TUserAutocompleteResponse = { success?: boolean; + error?: string | null; items?: Array<{ _id: string; name?: string; @@ -28,13 +29,12 @@ export const getPeerAutocompleteOptions = async ({ filter: string; peerInfo?: TPeerItem | null; } & TPeerAutocompleteAuth): Promise => { - const term = filter.trim(); - if (!term) { + if (!filter) { return []; } - const peerUsername = peerInfo && 'username' in peerInfo ? peerInfo.username : undefined; - const peerExtension = peerInfo && 'callerId' in peerInfo ? peerInfo.callerId : undefined; + const peerUsername = peerInfo?.type === 'user' ? peerInfo.username : undefined; + const peerExtension = peerInfo?.type === 'user' ? peerInfo.callerId : undefined; const conditions = peerExtension || sipEnabled @@ -48,7 +48,7 @@ export const getPeerAutocompleteOptions = async ({ const exceptions = [username, peerUsername].filter(Boolean); const selector = { - term, + term: filter, exceptions, ...(conditions && { conditions }) }; @@ -70,8 +70,8 @@ export const getPeerAutocompleteOptions = async ({ const sipOption: TPeerItem = { type: 'sip', - value: term, - label: term + value: filter, + label: filter }; return [sipOption, ...userOptions]; diff --git a/app/lib/services/voip/usePeerAutocompleteStore.test.ts b/app/lib/services/voip/usePeerAutocompleteStore.test.ts index c0c6722f135..0127db0db96 100644 --- a/app/lib/services/voip/usePeerAutocompleteStore.test.ts +++ b/app/lib/services/voip/usePeerAutocompleteStore.test.ts @@ -137,6 +137,36 @@ describe('usePeerAutocompleteStore', () => { expect(usePeerAutocompleteStore.getState().options).toEqual(mockOptions); }); + it('should forward the current username so the service can exclude self', async () => { + const { result } = renderHook(() => usePeerAutocompleteStore()); + + await act(async () => { + await result.current.fetchOptions('bob', { username: 'current.user', sipEnabled: false }); + }); + + expect(mockGetPeerAutocompleteOptions).toHaveBeenCalledWith({ + filter: 'bob', + peerInfo: null, + username: 'current.user', + sipEnabled: false + }); + }); + + it('should trim the filter before passing to the service', async () => { + const { result } = renderHook(() => usePeerAutocompleteStore()); + + await act(async () => { + await result.current.fetchOptions(' alice ', auth); + }); + + expect(mockGetPeerAutocompleteOptions).toHaveBeenCalledWith({ + filter: 'alice', + peerInfo: null, + username: 'me', + sipEnabled: false + }); + }); + it('should pass selected peer to getPeerAutocompleteOptions', async () => { usePeerAutocompleteStore.setState({ selectedPeer: userPeer, filter: 'bob' }); const { result } = renderHook(() => usePeerAutocompleteStore()); diff --git a/app/lib/services/voip/usePeerAutocompleteStore.ts b/app/lib/services/voip/usePeerAutocompleteStore.ts index 841933084f2..eda29c25075 100644 --- a/app/lib/services/voip/usePeerAutocompleteStore.ts +++ b/app/lib/services/voip/usePeerAutocompleteStore.ts @@ -2,8 +2,6 @@ import { create } from 'zustand'; import { getPeerAutocompleteOptions, type TPeerAutocompleteAuth, type TPeerItem } from './getPeerAutocompleteOptions'; -let peerAutocompleteFetchSeq = 0; - type TPeerAutocompleteState = { options: TPeerItem[]; selectedPeer: TPeerItem | null; @@ -18,57 +16,56 @@ type TPeerAutocompleteActions = { export type TPeerAutocompleteStore = TPeerAutocompleteState & TPeerAutocompleteActions; -export const usePeerAutocompleteStore = create((set, get) => ({ - options: [], - selectedPeer: null, - filter: '', - - fetchOptions: async (filter: string, auth: TPeerAutocompleteAuth) => { - const term = filter.trim(); - if (!term) { - set({ options: [] }); - return; - } - - const peerSnapshot = get().selectedPeer; - const seq = ++peerAutocompleteFetchSeq; +export const usePeerAutocompleteStore = create((set, get) => { + let seq = 0; - try { - const options = await getPeerAutocompleteOptions({ - filter: term, - peerInfo: peerSnapshot, - username: auth.username, - sipEnabled: auth.sipEnabled - }); + return { + options: [], + selectedPeer: null, + filter: '', - if (seq !== peerAutocompleteFetchSeq) { + fetchOptions: async (filter: string, auth: TPeerAutocompleteAuth) => { + const currentSeq = ++seq; + const term = filter.trim(); + if (!term) { + set({ options: [] }); return; } - if (get().filter.trim() !== term || get().selectedPeer !== peerSnapshot) { - return; + + const peerSnapshot = get().selectedPeer; + + try { + const options = await getPeerAutocompleteOptions({ + filter: term, + peerInfo: peerSnapshot, + username: auth.username, + sipEnabled: auth.sipEnabled + }); + + if (currentSeq !== seq) { + return; + } + + set({ options }); + } catch { + if (currentSeq !== seq) { + return; + } + set({ options: [] }); } + }, - set({ options }); - } catch { - if (seq !== peerAutocompleteFetchSeq) { + setSelectedPeer: (peer: TPeerItem | null) => { + if (peer === null) { + set({ selectedPeer: null, options: [] }); return; } - if (get().filter.trim() === term && get().selectedPeer === peerSnapshot) { - set({ options: [] }); - } - } - }, + set({ selectedPeer: peer, filter: '', options: [] }); + }, - setSelectedPeer: (peer: TPeerItem | null) => { - if (peer === null) { - set({ selectedPeer: null, options: [] }); - return; + reset: () => { + seq++; + set({ options: [], selectedPeer: null, filter: '' }); } - set({ selectedPeer: peer, filter: '', options: [] }); - }, - - reset: () => { - peerAutocompleteFetchSeq++; - set({ options: [], selectedPeer: null, filter: '' }); - } -})); + }; +}); From 48219e1b166a5ff3aa7ebf06cd6196ded5d11aff Mon Sep 17 00:00:00 2001 From: Diego Mello Date: Mon, 20 Apr 2026 16:35:54 -0300 Subject: [PATCH 3/6] refactor(voip): clear stale autocomplete options on keystroke - Clear `options: []` in `handleChangeText` so old peer options do not linger during the debounce window. - Wrap the debounced `fetchOptions` callback in `useCallback` with [username, sipEnabled] deps for explicit closure guarantees. --- app/containers/NewMediaCall/FilterHeader.tsx | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) diff --git a/app/containers/NewMediaCall/FilterHeader.tsx b/app/containers/NewMediaCall/FilterHeader.tsx index 1cb563aff15..dcc0fb5bc3f 100644 --- a/app/containers/NewMediaCall/FilterHeader.tsx +++ b/app/containers/NewMediaCall/FilterHeader.tsx @@ -1,4 +1,4 @@ -import React from 'react'; +import React, { useCallback } from 'react'; import { StyleSheet, Text, View } from 'react-native'; import { useSelector } from 'react-redux'; @@ -23,12 +23,18 @@ export const FilterHeader = (): React.ReactElement => { const username = useSelector(selectUsername); const sipEnabled = useSelector(selectSipEnabled); - const debouncedFetchOptions = useDebounce((value: string) => { - usePeerAutocompleteStore.getState().fetchOptions(value, { username, sipEnabled }); - }, textInputDebounceTime); + const debouncedFetchOptions = useDebounce( + useCallback( + (value: string) => { + usePeerAutocompleteStore.getState().fetchOptions(value, { username, sipEnabled }); + }, + [username, sipEnabled] + ), + textInputDebounceTime + ); const handleChangeText = (value: string) => { - usePeerAutocompleteStore.setState({ filter: value, selectedPeer: null }); + usePeerAutocompleteStore.setState({ filter: value, selectedPeer: null, options: [] }); debouncedFetchOptions(value); }; From 61c896fba410c2585e64531771c9dc730b22b5ca Mon Sep 17 00:00:00 2001 From: Diego Mello Date: Mon, 20 Apr 2026 16:42:49 -0300 Subject: [PATCH 4/6] refactor(voip): invalidate in-flight autocomplete on filter change Add `setFilter` store action that bumps the autocomplete sequence atomically with the filter/options/selectedPeer reset, so an in-flight `fetchOptions` response from a previous keystroke cannot repopulate stale options during the debounce window before the next fetch runs. `FilterHeader` now calls `setFilter` instead of `setState`. --- app/containers/NewMediaCall/FilterHeader.tsx | 2 +- .../voip/usePeerAutocompleteStore.test.ts | 37 +++++++++++++++++++ .../services/voip/usePeerAutocompleteStore.ts | 6 +++ 3 files changed, 44 insertions(+), 1 deletion(-) diff --git a/app/containers/NewMediaCall/FilterHeader.tsx b/app/containers/NewMediaCall/FilterHeader.tsx index dcc0fb5bc3f..21e29697f09 100644 --- a/app/containers/NewMediaCall/FilterHeader.tsx +++ b/app/containers/NewMediaCall/FilterHeader.tsx @@ -34,7 +34,7 @@ export const FilterHeader = (): React.ReactElement => { ); const handleChangeText = (value: string) => { - usePeerAutocompleteStore.setState({ filter: value, selectedPeer: null, options: [] }); + usePeerAutocompleteStore.getState().setFilter(value); debouncedFetchOptions(value); }; diff --git a/app/lib/services/voip/usePeerAutocompleteStore.test.ts b/app/lib/services/voip/usePeerAutocompleteStore.test.ts index 0127db0db96..ec3ddddec43 100644 --- a/app/lib/services/voip/usePeerAutocompleteStore.test.ts +++ b/app/lib/services/voip/usePeerAutocompleteStore.test.ts @@ -97,6 +97,43 @@ describe('usePeerAutocompleteStore', () => { }); }); + describe('setFilter', () => { + it('should update filter and clear selectedPeer and options', () => { + usePeerAutocompleteStore.setState({ filter: 'old', selectedPeer: userPeer, options: mockOptions }); + const { result } = renderHook(() => usePeerAutocompleteStore()); + + act(() => { + result.current.setFilter('new'); + }); + + expect(usePeerAutocompleteStore.getState()).toMatchObject({ + filter: 'new', + selectedPeer: null, + options: [] + }); + }); + + it('should invalidate in-flight fetchOptions so stale responses cannot repopulate', async () => { + let resolveSlow: (options: TPeerItem[]) => void = () => {}; + const slowPromise = new Promise(res => { + resolveSlow = res; + }); + mockGetPeerAutocompleteOptions.mockReturnValueOnce(slowPromise); + + const { result } = renderHook(() => usePeerAutocompleteStore()); + + await act(async () => { + const inFlight = result.current.fetchOptions('slow', auth); + result.current.setFilter('fast'); + resolveSlow([{ type: 'sip', value: 'stale', label: 'stale' }]); + await inFlight; + }); + + expect(usePeerAutocompleteStore.getState().options).toEqual([]); + expect(usePeerAutocompleteStore.getState().filter).toBe('fast'); + }); + }); + describe('fetchOptions', () => { it('should set empty options when filter is empty', async () => { const { result } = renderHook(() => usePeerAutocompleteStore()); diff --git a/app/lib/services/voip/usePeerAutocompleteStore.ts b/app/lib/services/voip/usePeerAutocompleteStore.ts index eda29c25075..86ef9947a7f 100644 --- a/app/lib/services/voip/usePeerAutocompleteStore.ts +++ b/app/lib/services/voip/usePeerAutocompleteStore.ts @@ -10,6 +10,7 @@ type TPeerAutocompleteState = { type TPeerAutocompleteActions = { fetchOptions: (filter: string, auth: TPeerAutocompleteAuth) => Promise; + setFilter: (filter: string) => void; setSelectedPeer: (peer: TPeerItem | null) => void; reset: () => void; }; @@ -55,6 +56,11 @@ export const usePeerAutocompleteStore = create((set, get } }, + setFilter: (filter: string) => { + seq++; + set({ filter, selectedPeer: null, options: [] }); + }, + setSelectedPeer: (peer: TPeerItem | null) => { if (peer === null) { set({ selectedPeer: null, options: [] }); From 3c77edec9b24084d56dfb825ccb80f20de154921 Mon Sep 17 00:00:00 2001 From: Diego Mello Date: Mon, 20 Apr 2026 17:22:18 -0300 Subject: [PATCH 5/6] fix(voip): invalidate in-flight autocomplete when selection changes Increment the peer-autocomplete sequence in setSelectedPeer so late fetchOptions completions cannot repopulate options after the user picks or clears a peer. Add store tests for both paths. Made-with: Cursor --- .../voip/usePeerAutocompleteStore.test.ts | 40 +++++++++++++++++++ .../services/voip/usePeerAutocompleteStore.ts | 1 + 2 files changed, 41 insertions(+) diff --git a/app/lib/services/voip/usePeerAutocompleteStore.test.ts b/app/lib/services/voip/usePeerAutocompleteStore.test.ts index ec3ddddec43..9ab6d60f368 100644 --- a/app/lib/services/voip/usePeerAutocompleteStore.test.ts +++ b/app/lib/services/voip/usePeerAutocompleteStore.test.ts @@ -95,6 +95,46 @@ describe('usePeerAutocompleteStore', () => { expect(usePeerAutocompleteStore.getState().filter).toBe(''); expect(usePeerAutocompleteStore.getState().options).toEqual([]); }); + + it('should invalidate in-flight fetchOptions when a peer is selected', async () => { + let resolveSlow: (options: TPeerItem[]) => void = () => {}; + const slowPromise = new Promise(res => { + resolveSlow = res; + }); + mockGetPeerAutocompleteOptions.mockReturnValueOnce(slowPromise); + + const { result } = renderHook(() => usePeerAutocompleteStore()); + + await act(async () => { + const inFlight = result.current.fetchOptions('slow', auth); + result.current.setSelectedPeer(userPeer); + resolveSlow([{ type: 'sip', value: 'stale', label: 'stale' }]); + await inFlight; + }); + + expect(usePeerAutocompleteStore.getState().options).toEqual([]); + expect(usePeerAutocompleteStore.getState().selectedPeer).toEqual(userPeer); + }); + + it('should invalidate in-flight fetchOptions when selection is cleared', async () => { + let resolveSlow: (options: TPeerItem[]) => void = () => {}; + const slowPromise = new Promise(res => { + resolveSlow = res; + }); + mockGetPeerAutocompleteOptions.mockReturnValueOnce(slowPromise); + + const { result } = renderHook(() => usePeerAutocompleteStore()); + + await act(async () => { + const inFlight = result.current.fetchOptions('slow', auth); + result.current.setSelectedPeer(null); + resolveSlow([{ type: 'sip', value: 'stale', label: 'stale' }]); + await inFlight; + }); + + expect(usePeerAutocompleteStore.getState().options).toEqual([]); + expect(usePeerAutocompleteStore.getState().selectedPeer).toBeNull(); + }); }); describe('setFilter', () => { diff --git a/app/lib/services/voip/usePeerAutocompleteStore.ts b/app/lib/services/voip/usePeerAutocompleteStore.ts index 86ef9947a7f..3ee3e3423d8 100644 --- a/app/lib/services/voip/usePeerAutocompleteStore.ts +++ b/app/lib/services/voip/usePeerAutocompleteStore.ts @@ -62,6 +62,7 @@ export const usePeerAutocompleteStore = create((set, get }, setSelectedPeer: (peer: TPeerItem | null) => { + seq++; if (peer === null) { set({ selectedPeer: null, options: [] }); return; From 683b717648e1ca8e2674ea3bf3a46b7c2553e23f Mon Sep 17 00:00:00 2001 From: Diego Mello Date: Mon, 20 Apr 2026 17:29:49 -0300 Subject: [PATCH 6/6] refactor(voip): trim peer autocomplete filter in getPeerAutocompleteOptions Normalize with filter.trim() inside the service so callers get consistent behavior; add whitespace-only coverage and align unit expectations. Made-with: Cursor --- .../voip/getPeerAutocompleteOptions.test.ts | 17 +++++++++++++++-- .../services/voip/getPeerAutocompleteOptions.ts | 9 +++++---- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/app/lib/services/voip/getPeerAutocompleteOptions.test.ts b/app/lib/services/voip/getPeerAutocompleteOptions.test.ts index ba63aa6dcb9..4ff82674077 100644 --- a/app/lib/services/voip/getPeerAutocompleteOptions.test.ts +++ b/app/lib/services/voip/getPeerAutocompleteOptions.test.ts @@ -42,7 +42,7 @@ describe('getPeerAutocompleteOptions', () => { expect(mockedUsersAutoComplete).not.toHaveBeenCalled(); }); - it('does not trim the filter (trimming is the store boundary responsibility)', async () => { + it('trims the filter before calling the API', async () => { mockedUsersAutoComplete.mockResolvedValue(mockUsersAutoCompleteResponse()); await getPeerAutocompleteOptions({ @@ -53,11 +53,24 @@ describe('getPeerAutocompleteOptions', () => { }); expect(mockedUsersAutoComplete).toHaveBeenCalledWith({ - term: ' alice ', + term: 'alice', exceptions: ['me'] }); }); + it('returns empty array and skips API call when filter is only whitespace', async () => { + await expect( + getPeerAutocompleteOptions({ + filter: ' ', + peerInfo: null, + username: 'me', + sipEnabled: false + }) + ).resolves.toEqual([]); + + expect(mockedUsersAutoComplete).not.toHaveBeenCalled(); + }); + it('excludes the current username from results', async () => { mockedUsersAutoComplete.mockResolvedValue(mockUsersAutoCompleteResponse()); diff --git a/app/lib/services/voip/getPeerAutocompleteOptions.ts b/app/lib/services/voip/getPeerAutocompleteOptions.ts index 0161f320e49..6e7bc57fa52 100644 --- a/app/lib/services/voip/getPeerAutocompleteOptions.ts +++ b/app/lib/services/voip/getPeerAutocompleteOptions.ts @@ -29,7 +29,8 @@ export const getPeerAutocompleteOptions = async ({ filter: string; peerInfo?: TPeerItem | null; } & TPeerAutocompleteAuth): Promise => { - if (!filter) { + const term = filter.trim(); + if (!term) { return []; } @@ -48,7 +49,7 @@ export const getPeerAutocompleteOptions = async ({ const exceptions = [username, peerUsername].filter(Boolean); const selector = { - term: filter, + term, exceptions, ...(conditions && { conditions }) }; @@ -70,8 +71,8 @@ export const getPeerAutocompleteOptions = async ({ const sipOption: TPeerItem = { type: 'sip', - value: filter, - label: filter + value: term, + label: term }; return [sipOption, ...userOptions];