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..21e29697f09 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,33 @@ 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'; +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 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(selectUsername); + const sipEnabled = useSelector(selectSipEnabled); + + const debouncedFetchOptions = useDebounce( + useCallback( + (value: string) => { + usePeerAutocompleteStore.getState().fetchOptions(value, { username, sipEnabled }); + }, + [username, sipEnabled] + ), + textInputDebounceTime + ); const handleChangeText = (value: string) => { - setFilter(value); - clearSelection(); + usePeerAutocompleteStore.getState().setFilter(value); 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/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 new file mode 100644 index 00000000000..4ff82674077 --- /dev/null +++ b/app/lib/services/voip/getPeerAutocompleteOptions.test.ts @@ -0,0 +1,246 @@ +import { usersAutoComplete } from '../restApi'; +import { getPeerAutocompleteOptions, type TPeerItem } from './getPeerAutocompleteOptions'; + +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 and skips API call when filter is empty', async () => { + await expect( + getPeerAutocompleteOptions({ + filter: '', + peerInfo: null, + username: 'me', + sipEnabled: false + }) + ).resolves.toEqual([]); + + expect(mockedUsersAutoComplete).not.toHaveBeenCalled(); + }); + + it('trims the filter before calling the API', async () => { + mockedUsersAutoComplete.mockResolvedValue(mockUsersAutoCompleteResponse()); + + await getPeerAutocompleteOptions({ + filter: ' alice ', + peerInfo: null, + username: 'me', + sipEnabled: false + }); + + expect(mockedUsersAutoComplete).toHaveBeenCalledWith({ + 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()); + + 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( + mockUsersAutoCompleteResponse([ + { _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 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(mockUsersAutoCompleteResponse()); + + 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(mockUsersAutoCompleteResponse()); + + 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(mockUsersAutoCompleteResponse()); + + 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 items', async () => { + mockedUsersAutoComplete.mockResolvedValue(mockUsersAutoCompleteResponse([], { success: false, error: 'error-not-allowed' })); + + 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..6e7bc57fa52 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 } @@ -7,6 +6,7 @@ export type TPeerItem = type TUserAutocompleteResponse = { success?: boolean; + error?: string | null; items?: Array<{ _id: string; name?: string; @@ -15,51 +15,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?.type === 'user' ? peerInfo.username : undefined; + const peerExtension = peerInfo?.type === 'user' ? 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..9ab6d60f368 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,6 +38,27 @@ describe('usePeerAutocompleteStore', () => { mockGetPeerAutocompleteOptions.mockResolvedValue(mockOptions); }); + 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.reset(); + }); + + expect(usePeerAutocompleteStore.getState()).toMatchObject({ + options: [], + selectedPeer: null, + filter: '' + }); + }); + }); + describe('setSelectedPeer', () => { it('should set selected peer', () => { const { result } = renderHook(() => usePeerAutocompleteStore()); @@ -47,8 +70,8 @@ describe('usePeerAutocompleteStore', () => { expect(usePeerAutocompleteStore.getState().selectedPeer).toEqual(userPeer); }); - it('should clear selected peer when null is passed', () => { - usePeerAutocompleteStore.setState({ selectedPeer: userPeer }); + 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(() => { @@ -56,31 +79,98 @@ describe('usePeerAutocompleteStore', () => { }); expect(usePeerAutocompleteStore.getState().selectedPeer).toBeNull(); + expect(usePeerAutocompleteStore.getState().filter).toBe('keep'); + expect(usePeerAutocompleteStore.getState().options).toEqual([]); }); - }); - describe('setFilter', () => { - it('should set filter value', () => { + 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.setFilter('alice'); + result.current.setSelectedPeer(userPeer); }); - expect(usePeerAutocompleteStore.getState().filter).toBe('alice'); + expect(usePeerAutocompleteStore.getState().selectedPeer).toEqual(userPeer); + 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('clearSelection', () => { - it('should clear selected peer', () => { - usePeerAutocompleteStore.setState({ selectedPeer: userPeer }); + 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.clearSelection(); + result.current.setFilter('new'); }); - expect(usePeerAutocompleteStore.getState().selectedPeer).toBeNull(); + 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'); }); }); @@ -89,7 +179,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 +190,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 +198,101 @@ 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 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 }); + 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..3ee3e3423d8 100644 --- a/app/lib/services/voip/usePeerAutocompleteStore.ts +++ b/app/lib/services/voip/usePeerAutocompleteStore.ts @@ -1,6 +1,6 @@ import { create } from 'zustand'; -import { getPeerAutocompleteOptions, type TPeerItem } from './getPeerAutocompleteOptions'; +import { getPeerAutocompleteOptions, type TPeerAutocompleteAuth, type TPeerItem } from './getPeerAutocompleteOptions'; type TPeerAutocompleteState = { options: TPeerItem[]; @@ -9,53 +9,70 @@ type TPeerAutocompleteState = { }; type TPeerAutocompleteActions = { - fetchOptions: (filter: string) => Promise; - setSelectedPeer: (peer: TPeerItem | null) => void; + fetchOptions: (filter: string, auth: TPeerAutocompleteAuth) => Promise; setFilter: (filter: string) => void; - clearSelection: () => void; + setSelectedPeer: (peer: TPeerItem | null) => void; reset: () => void; }; export type TPeerAutocompleteStore = TPeerAutocompleteState & TPeerAutocompleteActions; -export const usePeerAutocompleteStore = create((set, get) => ({ - options: [], - selectedPeer: null, - filter: '', +export const usePeerAutocompleteStore = create((set, get) => { + let seq = 0; - fetchOptions: async (filter: string) => { - const term = filter.trim(); - if (!term) { - set({ options: [] }); - return; - } + return { + options: [], + selectedPeer: null, + filter: '', - try { - const currentPeer = get().selectedPeer; - const options = await getPeerAutocompleteOptions({ - filter: term, - peerInfo: currentPeer - }); + fetchOptions: async (filter: string, auth: TPeerAutocompleteAuth) => { + const currentSeq = ++seq; + const term = filter.trim(); + if (!term) { + set({ options: [] }); + return; + } - set({ options }); - } catch { - set({ options: [] }); - } - }, + const peerSnapshot = get().selectedPeer; - setSelectedPeer: (peer: TPeerItem | null) => { - set({ selectedPeer: peer, filter: '', options: [] }); - }, + try { + const options = await getPeerAutocompleteOptions({ + filter: term, + peerInfo: peerSnapshot, + username: auth.username, + sipEnabled: auth.sipEnabled + }); - setFilter: (filter: string) => { - set({ filter }); - }, + if (currentSeq !== seq) { + return; + } - clearSelection: () => { - set({ selectedPeer: null }); - }, + set({ options }); + } catch { + if (currentSeq !== seq) { + return; + } + set({ options: [] }); + } + }, - reset: () => { - set({ options: [], selectedPeer: null, filter: '' }); - } -})); + setFilter: (filter: string) => { + seq++; + set({ filter, selectedPeer: null, options: [] }); + }, + + setSelectedPeer: (peer: TPeerItem | null) => { + seq++; + if (peer === null) { + set({ selectedPeer: null, options: [] }); + return; + } + set({ selectedPeer: peer, filter: '', options: [] }); + }, + + reset: () => { + seq++; + set({ options: [], selectedPeer: null, filter: '' }); + } + }; +});