-
Notifications
You must be signed in to change notification settings - Fork 3.8k
refactor(voice): load STT availability through React Query #6224
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+216
−24
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,143 @@ | ||
| /** | ||
| * @vitest-environment jsdom | ||
| */ | ||
| import { act, type ReactNode } from 'react' | ||
| import { sleep } from '@sim/utils/helpers' | ||
| import { QueryClient, QueryClientProvider } from '@tanstack/react-query' | ||
| import { createRoot, type Root } from 'react-dom/client' | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' | ||
|
|
||
| const { mockRequestJson } = vi.hoisted(() => ({ mockRequestJson: vi.fn() })) | ||
|
|
||
| vi.mock('@/lib/api/client/request', () => ({ requestJson: mockRequestJson })) | ||
|
|
||
| import { useVoiceSettings, voiceSettingsKeys } from '@/hooks/queries/voice' | ||
|
|
||
| /** Trees rendered by a test, torn down in afterEach so observers do not leak across tests. */ | ||
| const mountedRoots: Root[] = [] | ||
|
|
||
| function renderHookWithClient<T>( | ||
| useHook: () => T, | ||
| queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }) | ||
| ): { getResult: () => T } { | ||
| ;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true | ||
| const container = document.createElement('div') | ||
| const root: Root = createRoot(container) | ||
| mountedRoots.push(root) | ||
| let result: T | undefined | ||
|
|
||
| function Probe() { | ||
| result = useHook() | ||
| return null | ||
| } | ||
|
|
||
| act(() => { | ||
| root.render( | ||
| <QueryClientProvider client={queryClient}>{(<Probe />) as ReactNode}</QueryClientProvider> | ||
| ) | ||
| }) | ||
|
|
||
| return { | ||
| getResult: () => { | ||
| if (result === undefined) throw new Error('Hook result is not ready') | ||
| return result | ||
| }, | ||
| } | ||
| } | ||
|
|
||
| async function flush() { | ||
| await act(async () => { | ||
| for (let i = 0; i < 5; i++) { | ||
| await Promise.resolve() | ||
| await sleep(1) | ||
| } | ||
| }) | ||
| } | ||
|
|
||
| afterEach(() => { | ||
| act(() => { | ||
| for (const root of mountedRoots.splice(0)) root.unmount() | ||
| }) | ||
| }) | ||
|
|
||
| beforeEach(() => { | ||
| vi.clearAllMocks() | ||
| }) | ||
|
|
||
| describe('useVoiceSettings', () => { | ||
| it('keys the query under the voiceSettings namespace', () => { | ||
| expect(voiceSettingsKeys.settings()).toEqual(['voiceSettings', 'settings']) | ||
| }) | ||
|
|
||
| it('reports availability from the server response', async () => { | ||
| mockRequestJson.mockResolvedValue({ sttAvailable: true }) | ||
|
|
||
| const { getResult } = renderHookWithClient(() => useVoiceSettings()) | ||
| await flush() | ||
|
|
||
| expect(getResult().data).toBe(true) | ||
| expect(mockRequestJson).toHaveBeenCalledTimes(1) | ||
| }) | ||
|
|
||
| /** | ||
| * Consumers gate on a browser capability; a client that cannot stream audio | ||
| * should never issue the request at all. | ||
| */ | ||
| it('issues no request when disabled', async () => { | ||
| mockRequestJson.mockResolvedValue({ sttAvailable: true }) | ||
|
|
||
| const { getResult } = renderHookWithClient(() => useVoiceSettings({ enabled: false })) | ||
| await flush() | ||
|
|
||
| expect(mockRequestJson).not.toHaveBeenCalled() | ||
| expect(getResult().data).toBeUndefined() | ||
| }) | ||
|
|
||
| /** A failed capability probe must read as unavailable, not throw. */ | ||
| it('leaves data undefined when the request fails', async () => { | ||
| mockRequestJson.mockRejectedValue(new Error('offline')) | ||
|
|
||
| const { getResult } = renderHookWithClient(() => useVoiceSettings()) | ||
| await flush() | ||
|
|
||
| expect(getResult().data).toBeUndefined() | ||
| expect(getResult().isError).toBe(true) | ||
| }) | ||
|
|
||
| /** | ||
| * The app's QueryClient sets `retryOnMount: false`, and an infinite staleTime | ||
| * never goes stale, so without an explicit override a single transient | ||
| * failure would cache the error for the life of the client and keep the mic | ||
| * hidden until a full reload. | ||
| */ | ||
| it('recovers on a later mount after a failed probe, under the app query defaults', async () => { | ||
| const appDefaults = new QueryClient({ | ||
| defaultOptions: { queries: { retry: false, retryOnMount: false, staleTime: 30 * 1000 } }, | ||
| }) | ||
|
|
||
| mockRequestJson.mockRejectedValueOnce(new Error('offline')) | ||
| renderHookWithClient(() => useVoiceSettings(), appDefaults) | ||
| await flush() | ||
| expect(mockRequestJson).toHaveBeenCalledTimes(1) | ||
|
|
||
| mockRequestJson.mockResolvedValue({ sttAvailable: true }) | ||
| const second = renderHookWithClient(() => useVoiceSettings(), appDefaults) | ||
| await flush() | ||
|
|
||
| expect(mockRequestJson).toHaveBeenCalledTimes(2) | ||
| expect(second.getResult().data).toBe(true) | ||
| }) | ||
|
|
||
| it('dedupes across simultaneous consumers', async () => { | ||
| mockRequestJson.mockResolvedValue({ sttAvailable: true }) | ||
|
|
||
| renderHookWithClient(() => { | ||
| useVoiceSettings() | ||
| useVoiceSettings() | ||
| return null | ||
| }) | ||
| await flush() | ||
|
|
||
| expect(mockRequestJson).toHaveBeenCalledTimes(1) | ||
| }) | ||
| }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| import { useQuery } from '@tanstack/react-query' | ||
| import { requestJson } from '@/lib/api/client/request' | ||
| import { getVoiceSettingsContract } from '@/lib/api/contracts' | ||
|
|
||
| /** | ||
| * Query key factory for voice capability queries | ||
| */ | ||
| export const voiceSettingsKeys = { | ||
| all: ['voiceSettings'] as const, | ||
| settings: () => [...voiceSettingsKeys.all, 'settings'] as const, | ||
| } | ||
|
|
||
| /** | ||
| * `/api/settings/voice` reports whether the server has an STT provider | ||
| * configured, which is read from env at request time and so cannot change | ||
| * within a session. | ||
| */ | ||
| export const VOICE_SETTINGS_STALE_TIME = Number.POSITIVE_INFINITY | ||
|
|
||
| async function fetchSttAvailable(signal?: AbortSignal): Promise<boolean> { | ||
| const data = await requestJson(getVoiceSettingsContract, { signal }) | ||
| return data.sttAvailable === true | ||
| } | ||
|
|
||
| /** | ||
| * Loads whether server-side speech-to-text is configured. | ||
| * | ||
| * `enabled` is caller-controlled so consumers gated on a browser capability | ||
| * skip the request entirely on clients that could not use STT anyway. | ||
| * | ||
| * Deliberately no `initialData`: consumers derive their support flag from | ||
| * `data === true`, so the first client render matches the server render | ||
| * (unavailable) until the fetch resolves. | ||
| * | ||
| * `retryOnMount` overrides the app default of `false`. An infinite staleTime | ||
| * never goes stale, and `refetchOnWindowFocus` only refetches stale queries, so | ||
| * without this a single transient failure would cache the error for the life of | ||
| * the QueryClient and hide the mic until a full reload. Retrying per mount | ||
| * matches the effect this replaced, which refetched every time it ran. | ||
| */ | ||
| export function useVoiceSettings(options?: { enabled?: boolean }) { | ||
| return useQuery({ | ||
| queryKey: voiceSettingsKeys.settings(), | ||
| queryFn: ({ signal }) => fetchSttAvailable(signal), | ||
| enabled: options?.enabled ?? true, | ||
| staleTime: VOICE_SETTINGS_STALE_TIME, | ||
| retryOnMount: true, | ||
| }) | ||
| } | ||
|
waleedlatif1 marked this conversation as resolved.
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.