The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { |
| 2 | getClientSettings, |
| 3 | isClientSettingsHydrated, |
| 4 | updateClientSettings, |
| 5 | } from "../hooks/useSettings"; |
| 6 | import { |
| 7 | type MicrophoneEntry, |
| 8 | microphoneOrder, |
| 9 | preferredMicrophoneId, |
| 10 | rememberMicrophones, |
| 11 | } from "./microphoneOrder"; |
| 12 | import { msg } from "gt-react"; |
| 13 | import { m } from "../i18n/messages"; |
| 14 | |
| 15 | export type BrowserMicrophone = Pick<MediaDeviceInfo, "deviceId" | "label">; |
| 16 | |
| 17 | /** Audio inputs as the browser reports them. Labels stay empty until microphone permission. */ |
| 18 | export async function listAudioInputs(): Promise<BrowserMicrophone[]> { |
| 19 | const devices = await navigator.mediaDevices.enumerateDevices(); |
| 20 | return devices |
| 21 | .filter((device) => device.kind === "audioinput") |
| 22 | .map(({ deviceId, label }) => ({ deviceId, label })); |
| 23 | } |
| 24 | |
| 25 | export async function listBrowserMicrophones(): Promise<BrowserMicrophone[]> { |
| 26 | return (await listAudioInputs()).map(({ deviceId, label }, index) => ({ |
| 27 | deviceId, |
| 28 | label: label || m(msg("Microphone {number}", { number: index + 1 })), |
| 29 | })); |
| 30 | } |
| 31 | |
| 32 | /** Applies a change to the saved order. Skipped before hydration so defaults never replace a saved order. */ |
| 33 | export function updateMicrophoneOrder( |
| 34 | change: (order: ReadonlyArray<MicrophoneEntry>) => ReadonlyArray<MicrophoneEntry>, |
| 35 | ): ReadonlyArray<MicrophoneEntry> { |
| 36 | const known = microphoneOrder(getClientSettings()); |
| 37 | if (!isClientSettingsHydrated()) return known; |
| 38 | const next = change(known); |
| 39 | if (next !== known) void updateClientSettings({ voiceMicrophones: [...next] }); |
| 40 | return next; |
| 41 | } |
| 42 | |
| 43 | /** Remembers newly seen microphones and returns the device id to record from, empty for System default. */ |
| 44 | export async function chooseRecordingMicrophone(): Promise<string> { |
| 45 | // Rejects where the browser has no media devices, such as plain HTTP. |
| 46 | const devices = await listAudioInputs().catch(() => []); |
| 47 | return preferredMicrophoneId( |
| 48 | updateMicrophoneOrder((order) => rememberMicrophones(order, devices)), |
| 49 | devices, |
| 50 | ); |
| 51 | } |