feat(mobile): choose the microphone order for voice input (#17896)

Co-authored-by: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Julius MarmingeandClaude Opus 5.5 authored and GitHub committed 2026-10-10 13:04:09 -07:00
1 parent 61eb4af69c
commit 2a4ee33982
14 files changed
+737 -66

No files matched your search

+8
View File
@@ -102,6 +102,7 @@ import {
import { ScheduledTaskEditorProvider } from "./features/settings/scheduled-task-editor";
import { SettingsKeyboardRouteScreen } from "./features/settings/SettingsKeyboardRouteScreen";
import { SettingsLegalRouteScreen } from "./features/settings/SettingsLegalRouteScreen";
import { SettingsMicrophoneRouteScreen } from "./features/settings/SettingsMicrophoneRouteScreen";
import {
SettingsOpenSourceLicenseRouteScreen,
SettingsOpenSourceLicensesRouteScreen,
@@ -310,6 +311,13 @@ const SettingsContentStack = createV5SheetStackNavigator({
title: "Keyboard",
},
}),
SettingsMicrophone: createNativeStackScreen({
screen: SettingsMicrophoneRouteScreen,
linking: "microphone",
options: {
title: "Microphone",
},
}),
SettingsFollowUp: createNativeStackScreen({
screen: SettingsFollowUpRouteScreen,
linking: "follow-ups",
+7
View File
@@ -28,6 +28,7 @@ import IconBolt from "@tabler/icons-react-native/IconBolt";
import IconBox from "@tabler/icons-react-native/IconBox";
import IconBrain from "@tabler/icons-react-native/IconBrain";
import IconCamera from "@tabler/icons-react-native/IconCamera";
import IconCar from "@tabler/icons-react-native/IconCar";
import IconChartBar from "@tabler/icons-react-native/IconChartBar";
import IconCheck from "@tabler/icons-react-native/IconCheck";
import IconCloud from "@tabler/icons-react-native/IconCloud";
@@ -58,6 +59,7 @@ import IconFilter from "@tabler/icons-react-native/IconFilter";
import IconFilterFilled from "@tabler/icons-react-native/IconFilterFilled";
import IconFolder from "@tabler/icons-react-native/IconFolder";
import IconFolderOpen from "@tabler/icons-react-native/IconFolderOpen";
import IconHeadphones from "@tabler/icons-react-native/IconHeadphones";
import IconFolderPlus from "@tabler/icons-react-native/IconFolderPlus";
import IconGitBranch from "@tabler/icons-react-native/IconGitBranch";
import IconGitMerge from "@tabler/icons-react-native/IconGitMerge";
@@ -83,6 +85,7 @@ import IconMoon from "@tabler/icons-react-native/IconMoon";
import IconNetwork from "@tabler/icons-react-native/IconNetwork";
import IconPalette from "@tabler/icons-react-native/IconPalette";
import IconPencil from "@tabler/icons-react-native/IconPencil";
import IconPlug from "@tabler/icons-react-native/IconPlug";
import IconPhoto from "@tabler/icons-react-native/IconPhoto";
import IconPin from "@tabler/icons-react-native/IconPin";
import IconPinnedOff from "@tabler/icons-react-native/IconPinnedOff";
@@ -146,7 +149,9 @@ const ANDROID_ICON_BY_SF_SYMBOL = {
"bolt.circle": IconBolt,
"bolt.horizontal.circle": IconBolt,
brain: IconBrain,
"cable.connector": IconPlug,
camera: IconCamera,
car: IconCar,
"chart.bar.xaxis": IconChartBar,
checkmark: IconCheck,
"checkmark.circle": IconCircleCheck,
@@ -178,9 +183,11 @@ const ANDROID_ICON_BY_SF_SYMBOL = {
gearshape: IconSettings,
globe: IconWorld,
hammer: IconHammer,
headphones: IconHeadphones,
house: IconHome,
"info.circle": IconInfoCircle,
internaldrive: IconDatabase,
iphone: IconDeviceMobile,
keyboard: IconKeyboard,
laptopcomputer: IconDeviceLaptop,
link: IconLink,
@@ -13,9 +13,8 @@ import { type EnvironmentId, sessionGrantsScope } from "@t3tools/contracts";
import { AUTH_SCOPE_OPTIONS } from "@t3tools/shared/authScopeOptions";
import { AsyncResult } from "effect/reactivity";
import * as Option from "effect/Option";
import { useEffect, useMemo, useRef, useState } from "react";
import { useState } from "react";
import { Alert, Platform, Pressable, View } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated";
import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";
@@ -27,6 +26,7 @@ import { environmentSession } from "../../state/session";
import { useAtomCommand } from "../../state/use-atom-command";
import { connectionTone } from "../connection/connectionTone";
import { SettingsActionRow } from "./components/SettingsActionRow";
import { SettingsDragHandle } from "./components/SettingsDragHandle";
import { SettingsSection } from "./components/SettingsSection";
const ICON_SIZE = Platform.OS === "android" ? 24 : 22;
@@ -324,7 +324,7 @@ function RouteRow(props: {
</View>
</View>
{props.editing ? (
<DragHandle
<SettingsDragHandle
title={label}
canMoveUp={props.position > 1}
canMoveDown={props.position < props.count}
@@ -337,62 +337,3 @@ function RouteRow(props: {
</Reanimated.View>
);
}
/** Pan recognition wins over the settings scroll view only inside the handle. */
function DragHandle(props: {
readonly title: string;
readonly canMoveUp: boolean;
readonly canMoveDown: boolean;
readonly onStart: () => void;
readonly onMove: (translation: number) => void;
readonly onEnd: (translation: number, cancelled: boolean) => void;
readonly onStep: (direction: "up" | "down") => void;
}) {
const latest = useRef(props);
useEffect(() => {
latest.current = props;
});
const translation = useRef(0);
const gesture = useMemo(
() =>
Gesture.Pan()
.minDistance(0)
.shouldCancelWhenOutside(false)
.runOnJS(true)
.onStart(() => {
translation.current = 0;
latest.current.onStart();
})
.onUpdate((event) => {
translation.current = event.translationY;
latest.current.onMove(event.translationY);
})
.onFinalize((_, success) => latest.current.onEnd(translation.current, !success)),
[],
);
return (
<GestureDetector gesture={gesture}>
<View
collapsable={false}
accessible
accessibilityRole="adjustable"
accessibilityLabel={`Reorder ${props.title}`}
accessibilityActions={[
...(props.canMoveUp ? [{ name: "decrement", label: "Move up" }] : []),
...(props.canMoveDown ? [{ name: "increment", label: "Move down" }] : []),
]}
onAccessibilityAction={({ nativeEvent }) => {
if (nativeEvent.actionName === "decrement" && props.canMoveUp) props.onStep("up");
if (nativeEvent.actionName === "increment" && props.canMoveDown) props.onStep("down");
}}
style={{ width: 48, alignSelf: "stretch", alignItems: "center", justifyContent: "center" }}
>
<SymbolView
name="line.3.horizontal"
size={20}
tintColorClassName="accent-foreground-muted"
/>
</View>
</GestureDetector>
);
}
@@ -0,0 +1,323 @@
import { useAtomSet, useAtomValue } from "@effect/atom-react";
import { AsyncResult } from "effect/reactivity";
import { getRecordingPermissionsAsync, requestRecordingPermissionsAsync } from "expo-audio";
import { useCallback, useEffect, useState } from "react";
import { AppState, Linking, Pressable, ScrollView, View } from "react-native";
import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated";
import { useSafeAreaInsets } from "react-native-safe-area-context";
import { type AppSymbolName, SymbolView } from "../../components/AppSymbol";
import { AppText as Text } from "../../components/AppText";
import { cn } from "../../lib/cn";
import {
isMicrophoneDevice,
type MicrophoneEntry,
type MicrophoneKind,
microphoneEntryKey,
microphoneOrder,
} from "../../lib/microphonePriority";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { SettingsActionRow } from "./components/SettingsActionRow";
import { SettingsDragHandle } from "./components/SettingsDragHandle";
import { SettingsSection } from "./components/SettingsSection";
const REMOVE_SIZE = 20;
type MicrophonePermission = "checking" | "granted" | "ask" | "denied";
/** Re-reads microphone access whenever the app returns from system Settings. */
function useMicrophonePermission() {
const [permission, setPermission] = useState<MicrophonePermission>("checking");
const apply = useCallback(
(response: { readonly granted: boolean; readonly canAskAgain: boolean }) =>
setPermission(response.granted ? "granted" : response.canAskAgain ? "ask" : "denied"),
[],
);
const refresh = useCallback(
() => void getRecordingPermissionsAsync().then(apply, () => setPermission("ask")),
[apply],
);
useEffect(() => {
refresh();
const subscription = AppState.addEventListener("change", (state) => {
if (state === "active") refresh();
});
return () => subscription.remove();
}, [refresh]);
const request = useCallback(
() => void requestRecordingPermissionsAsync().then(apply, refresh),
[apply, refresh],
);
return { permission, request };
}
const KINDS: Record<
MicrophoneKind,
{
/** Shown under a remembered device's name. */
readonly label: string;
readonly row: string;
readonly rowDescription: string;
readonly icon: AppSymbolName;
}
> = {
wired: {
label: "Wired",
row: "Other wired",
rowDescription: "Headsets and USB microphones not listed",
icon: "cable.connector",
},
bluetooth: {
label: "Bluetooth",
row: "Other Bluetooth",
rowDescription: "AirPods, headsets, and cars not listed",
icon: "headphones",
},
builtIn: {
label: "Built-in",
row: "Built-in microphone",
rowDescription: "The microphone on this device",
icon: "iphone",
},
carPlay: {
label: "CarPlay",
row: "CarPlay",
rowDescription: "The car’s microphone",
icon: "car",
},
};
/**
* Microphone kinds and remembered devices, in the order voice input prefers
* them. iOS only. A device joins the list the first time it is connected
* during dictation; until then its kind's row ranks it.
*/
export function SettingsMicrophoneRouteScreen() {
const insets = useSafeAreaInsets();
const preferencesResult = useAtomValue(mobilePreferencesAtom);
const savePreferences = useAtomSet(updateMobilePreferencesAtom);
const ready = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting;
const entries = microphoneOrder(
AsyncResult.isSuccess(preferencesResult) ? preferencesResult.value.microphones : undefined,
);
const hasDevices = entries.some(isMicrophoneDevice);
const { permission, request: requestPermission } = useMicrophonePermission();
const [editing, setEditing] = useState(false);
const [drag, setDrag] = useState<{ readonly key: string; readonly translation: number } | null>(
null,
);
const [rowHeight, setRowHeight] = useState(0);
// Each drop remounts the rows so the new order and the cleared offsets land in one frame.
const [drops, setDrops] = useState(0);
// Transforms apply to the stored order, so a device recorded meanwhile is kept.
const move = (key: string, steps: number) =>
savePreferences({
transform: (current) => {
const next = [...microphoneOrder(current.microphones)];
const from = next.findIndex((entry) => microphoneEntryKey(entry) === key);
const to = Math.min(next.length - 1, Math.max(0, from + steps));
if (from === -1 || from === to) return {};
const [moved] = next.splice(from, 1);
next.splice(to, 0, moved!);
return { microphones: next };
},
});
const forget = (key: string) =>
savePreferences({
transform: (current) => ({
microphones: microphoneOrder(current.microphones).filter(
(entry) => microphoneEntryKey(entry) !== key,
),
}),
});
// A lifted row takes a neighbour's slot once it has moved past half of that row.
const dropSteps = (from: number, translation: number) =>
rowHeight === 0
? 0
: Math.min(entries.length - 1, Math.max(0, from + Math.round(translation / rowHeight))) -
from;
const dragFrom =
drag === null ? -1 : entries.findIndex((entry) => microphoneEntryKey(entry) === drag.key);
const dragTo = drag === null ? -1 : dragFrom + dropSteps(dragFrom, drag.translation);
return (
<View collapsable={false} className="flex-1 bg-sheet">
<ScrollView
contentInsetAdjustmentBehavior="automatic"
showsVerticalScrollIndicator={false}
className="flex-1"
contentContainerClassName="gap-3 px-5 pt-4"
contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
>
{permission === "ask" || permission === "denied" ? (
<>
<SettingsSection title="Microphone access">
<SettingsActionRow
icon="mic"
label={permission === "ask" ? "Allow microphone access" : "Open Settings"}
onPress={
permission === "ask" ? requestPermission : () => void Linking.openSettings()
}
/>
</SettingsSection>
<Text className="px-2 text-sm text-foreground-muted">
{permission === "ask"
? "Voice input needs microphone access before it can record or list your microphones."
: "Microphone access is off for T3 Code. Turn it on in Settings to use voice input."}
</Text>
</>
) : null}
<SettingsSection
title="Preferred order"
trailing={
hasDevices ? (
<Pressable
accessibilityRole="button"
onPress={() => setEditing((value) => !value)}
className="px-2 py-1 active:opacity-70"
>
<Text className="text-sm font-t3-medium text-foreground">
{editing ? "Done" : "Edit"}
</Text>
</Pressable>
) : undefined
}
>
{entries.map((entry, index) => {
const key = microphoneEntryKey(entry);
const shift =
dragFrom === -1 || index === dragFrom
? 0
: dragFrom < dragTo && index > dragFrom && index <= dragTo
? -rowHeight
: dragFrom > dragTo && index < dragFrom && index >= dragTo
? rowHeight
: 0;
return (
<MicrophoneRow
key={`${key}:${drops}`}
entry={entry}
position={index + 1}
count={entries.length}
reorderable={ready}
editing={editing && hasDevices}
offset={index === dragFrom ? (drag?.translation ?? 0) : shift}
lifted={index === dragFrom}
onHeight={setRowHeight}
onDragStart={() => setDrag({ key, translation: 0 })}
onDragMove={(translation) => setDrag({ key, translation })}
onDragEnd={(translation, cancelled) => {
setDrag(null);
setDrops((count) => count + 1);
if (!cancelled) move(key, dropSteps(index, translation));
}}
onStep={(direction) => move(key, direction === "up" ? -1 : 1)}
onForget={isMicrophoneDevice(entry) ? () => forget(key) : undefined}
/>
);
})}
</SettingsSection>
<Text className="px-2 text-sm text-foreground-muted">
Voice input records from the first connected microphone in this list. Wired and Bluetooth
devices are added by name after you use voice input with them connected; until then, the
Other row ranks them.
</Text>
</ScrollView>
</View>
);
}
function MicrophoneRow(props: {
readonly entry: MicrophoneEntry;
readonly position: number;
readonly count: number;
readonly reorderable: boolean;
readonly editing: boolean;
readonly offset: number;
readonly lifted: boolean;
readonly onHeight: (height: number) => void;
readonly onDragStart: () => void;
readonly onDragMove: (translation: number) => void;
readonly onDragEnd: (translation: number, cancelled: boolean) => void;
readonly onStep: (direction: "up" | "down") => void;
readonly onForget: (() => void) | undefined;
}) {
const { lifted, offset, entry } = props;
const kind = KINDS[entry.kind];
const title = isMicrophoneDevice(entry) ? entry.name : kind.row;
const style = useAnimatedStyle(() => ({
transform: [
{
translateY: lifted
? offset
: withTiming(offset, { duration: 160, reduceMotion: ReduceMotion.System }),
},
],
zIndex: lifted ? 1 : 0,
}));
return (
<Reanimated.View
style={style}
onLayout={(event) => props.onHeight(event.nativeEvent.layout.height)}
className={cn(
"flex-row items-center gap-4 pl-4",
props.position > 1 && !lifted && "border-t border-border-subtle",
lifted && "bg-grouped-card shadow-md",
!props.reorderable && "pr-4",
)}
>
{props.editing && props.onForget ? (
<Pressable
accessibilityRole="button"
accessibilityLabel={`Forget ${title}`}
hitSlop={8}
onPress={props.onForget}
className="active:opacity-70"
>
<SymbolView
name="xmark.circle.fill"
size={REMOVE_SIZE}
tintColorClassName="accent-danger-foreground"
type="monochrome"
/>
</Pressable>
) : props.editing ? (
<View style={{ width: REMOVE_SIZE }} />
) : null}
<View
accessible
accessibilityLabel={`${title}, ${kind.label}, ${props.position} of ${props.count}`}
className="min-w-0 flex-1 flex-row items-center gap-4 py-4"
>
<SymbolView
name={kind.icon}
size={22}
tintColorClassName="accent-icon"
type="monochrome"
weight="regular"
/>
<View className="min-w-0 flex-1 gap-0.5">
<Text numberOfLines={1} className="text-lg text-foreground">
{title}
</Text>
<Text numberOfLines={1} className="text-sm text-foreground-muted">
{isMicrophoneDevice(entry) ? kind.label : kind.rowDescription}
</Text>
</View>
</View>
{props.reorderable ? (
<SettingsDragHandle
title={title}
canMoveUp={props.position > 1}
canMoveDown={props.position < props.count}
onStart={props.onDragStart}
onMove={props.onDragMove}
onEnd={props.onDragEnd}
onStep={props.onStep}
/>
) : null}
</Reanimated.View>
);
}
@@ -154,7 +154,10 @@ function SettingsIndexSections() {
<SettingsSection title="Interface">
<SettingsRow icon="paintbrush" label="Appearance" target="SettingsAppearance" />
{Platform.OS === "ios" ? (
<SettingsRow icon="keyboard" label="Keyboard" target="SettingsKeyboard" />
<>
<SettingsRow icon="keyboard" label="Keyboard" target="SettingsKeyboard" />
<SettingsRow icon="mic" label="Microphone" target="SettingsMicrophone" />
</>
) : null}
</SettingsSection>
@@ -0,0 +1,64 @@
import { useEffect, useMemo, useRef } from "react";
import { View } from "react-native";
import { Gesture, GestureDetector } from "react-native-gesture-handler";
import { SymbolView } from "../../../components/AppSymbol";
/** Pan recognition wins over the settings scroll view only inside the handle. */
export function SettingsDragHandle(props: {
readonly title: string;
readonly canMoveUp: boolean;
readonly canMoveDown: boolean;
readonly onStart: () => void;
readonly onMove: (translation: number) => void;
readonly onEnd: (translation: number, cancelled: boolean) => void;
readonly onStep: (direction: "up" | "down") => void;
}) {
const latest = useRef(props);
useEffect(() => {
latest.current = props;
});
const translation = useRef(0);
const gesture = useMemo(
() =>
Gesture.Pan()
.minDistance(0)
.shouldCancelWhenOutside(false)
.runOnJS(true)
.onStart(() => {
translation.current = 0;
latest.current.onStart();
})
.onUpdate((event) => {
translation.current = event.translationY;
latest.current.onMove(event.translationY);
})
.onFinalize((_, success) => latest.current.onEnd(translation.current, !success)),
[],
);
return (
<GestureDetector gesture={gesture}>
<View
collapsable={false}
accessible
accessibilityRole="adjustable"
accessibilityLabel={`Reorder ${props.title}`}
accessibilityActions={[
...(props.canMoveUp ? [{ name: "decrement", label: "Move up" }] : []),
...(props.canMoveDown ? [{ name: "increment", label: "Move down" }] : []),
]}
onAccessibilityAction={({ nativeEvent }) => {
if (nativeEvent.actionName === "decrement" && props.canMoveUp) props.onStep("up");
if (nativeEvent.actionName === "increment" && props.canMoveDown) props.onStep("down");
}}
style={{ width: 48, alignSelf: "stretch", alignItems: "center", justifyContent: "center" }}
>
<SymbolView
name="line.3.horizontal"
size={20}
tintColorClassName="accent-foreground-muted"
/>
</View>
</GestureDetector>
);
}
@@ -13,6 +13,7 @@ export type SettingsSheetTarget =
| "SettingsEnvironmentMaintenance"
| "SettingsProviderAccounts"
| "SettingsKeyboard"
| "SettingsMicrophone"
| "SettingsFollowUp"
| "SettingsScheduledTasks"
| "SettingsProjectGrouping"
@@ -1,3 +1,4 @@
import { RegistryContext, useAtomMount } from "@effect/atom-react";
import {
AudioModule,
RecordingPresets,
@@ -20,9 +21,16 @@ import {
type ReactNode,
} from "react";
import { AppState, Platform } from "react-native";
import { AsyncResult } from "effect/reactivity";
import { useSharedValue } from "react-native-reanimated";
import {
microphoneOrder,
preferredMicrophoneInput,
rememberMicrophones,
} from "../../lib/microphonePriority";
import { getLocalVoiceTranscriber } from "../../native/voiceTranscription";
import { mobilePreferencesAtom, updateMobilePreferencesAtom } from "../../state/preferences";
import { getNativeShowcaseScene } from "../showcase/nativeShowcaseScene";
import {
VOICE_RECORDING_LIMIT_SECONDS,
@@ -91,6 +99,10 @@ export function useGlobalVoiceInput() {
}
function useVoiceInputRuntime() {
const registry = use(RegistryContext);
// Dictation reads and records microphones without subscribing the provider to preferences.
useAtomMount(mobilePreferencesAtom);
useAtomMount(updateMobilePreferencesAtom);
const [{ state, ownerKey, label }, setState] = useState({
state: INITIAL_STATE,
ownerKey: null as string | null,
@@ -126,6 +138,21 @@ function useVoiceInputRuntime() {
url: status.url,
});
},
// Read when recording starts so preference changes do not re-render every composer.
selectInput: (inputs) => {
const preferences = registry.get(mobilePreferencesAtom);
if (!AsyncResult.isSuccess(preferences)) return null;
const known = microphoneOrder(preferences.value.microphones);
const order = rememberMicrophones(known, inputs);
if (order !== known) {
registry.set(updateMobilePreferencesAtom, {
transform: (current) => ({
microphones: rememberMicrophones(microphoneOrder(current.microphones), inputs),
}),
});
}
return preferredMicrophoneInput(inputs, order);
},
});
recorderRef.current = recorder;
sessionRef.current = new VoiceInputSession({
@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vite-plus/test";
import { VoiceInputController } from "@t3tools/client-runtime/voice-input";
import { createLazyVoiceRecorder } from "./lazyVoiceRecorder";
import { createLazyVoiceRecorder, type VoiceRecordingInput } from "./lazyVoiceRecorder";
type Status = { readonly isFinished: boolean };
type State = { readonly isRecording: boolean };
@@ -30,12 +30,19 @@ function createNativeRecorder(uri: string) {
listeners.add(listener);
return { remove: () => listeners.delete(listener) };
}),
getAvailableInputs: vi.fn((): ReadonlyArray<VoiceRecordingInput> => [
{ uid: "car", name: "CarPlay", type: "CarAudio" },
{ uid: "built-in", name: "iPhone Microphone", type: "MicrophoneBuiltIn" },
]),
setInput: vi.fn((_uid: string) => undefined),
release: vi.fn(),
emit: (status: Status) => listeners.forEach((listener) => listener(status)),
};
}
function createHarness() {
function createHarness(
selectInput?: (inputs: ReadonlyArray<VoiceRecordingInput>) => VoiceRecordingInput | null,
) {
const created: Array<ReturnType<typeof createNativeRecorder>> = [];
const statuses: Status[] = [];
const recorder = createLazyVoiceRecorder({
@@ -45,6 +52,7 @@ function createHarness() {
return native;
},
onStatus: (status) => statuses.push(status),
...(selectInput ? { selectInput } : {}),
});
return { recorder, created, statuses };
}
@@ -79,6 +87,29 @@ describe("createLazyVoiceRecorder", () => {
expect(created[0]!.prepareToRecordAsync).toHaveBeenCalledTimes(2);
});
it("selects the preferred input after preparing, when the session lists inputs", async () => {
const { recorder, created } = createHarness(
(inputs) => inputs.find((input) => input.type === "MicrophoneBuiltIn") ?? null,
);
await recorder.prepareToRecordAsync();
expect(created[0]!.setInput).toHaveBeenCalledWith("built-in");
});
it("keeps the system input when none is preferred or the preferred one disconnects", async () => {
const unpreferred = createHarness(() => null);
await unpreferred.recorder.prepareToRecordAsync();
expect(unpreferred.created[0]!.setInput).not.toHaveBeenCalled();
const disconnected = createHarness((inputs) => inputs[1] ?? null);
await disconnected.recorder.prepareToRecordAsync();
disconnected.created[0]!.setInput.mockImplementationOnce(() => {
throw new Error("Preferred input not found");
});
await expect(disconnected.recorder.prepareToRecordAsync()).resolves.toBeUndefined();
});
it("forwards status events until the recorder is released", async () => {
const { recorder, created, statuses } = createHarness();
await recorder.prepareToRecordAsync();
@@ -2,6 +2,12 @@ import type { VoiceRecorder } from "@t3tools/client-runtime/voice-input";
type Subscription = { remove(): void };
export interface VoiceRecordingInput {
readonly uid: string;
readonly name: string;
readonly type: string;
}
// The subset of expo-audio's native `AudioRecorder` the voice input hook uses.
export interface NativeVoiceRecorder<TStatus, TRecorderState> {
readonly uri: string | null;
@@ -13,6 +19,8 @@ export interface NativeVoiceRecorder<TStatus, TRecorderState> {
eventName: "recordingStatusUpdate",
listener: (status: TStatus) => void,
): Subscription;
getAvailableInputs(): ReadonlyArray<VoiceRecordingInput>;
setInput(uid: string): void;
release(): void;
}
@@ -34,6 +42,8 @@ export interface LazyVoiceRecorder<TRecorderState> extends VoiceRecorder {
export function createLazyVoiceRecorder<TStatus, TRecorderState>(input: {
readonly create: () => NativeVoiceRecorder<TStatus, TRecorderState>;
readonly onStatus: (status: TStatus) => void;
/** Picks the input to record from once the session lists them, or null to keep the system's. */
readonly selectInput?: (inputs: ReadonlyArray<VoiceRecordingInput>) => VoiceRecordingInput | null;
}): LazyVoiceRecorder<TRecorderState> {
let recorder: NativeVoiceRecorder<TStatus, TRecorderState> | null = null;
let subscription: Subscription | null = null;
@@ -57,7 +67,18 @@ export function createLazyVoiceRecorder<TStatus, TRecorderState>(input: {
recorder = input.create();
subscription = recorder.addListener("recordingStatusUpdate", input.onStatus);
}
return track(recorder.prepareToRecordAsync());
const prepared = recorder;
return track(
prepared.prepareToRecordAsync().then(() => {
if (!input.selectInput) return;
try {
const selected = input.selectInput(prepared.getAvailableInputs());
if (selected) prepared.setInput(selected.uid);
} catch {
// The input can disconnect in between. The system's route still records.
}
}),
);
},
record(options) {
if (!recorder) throw new Error("Voice recorder is not prepared.");
@@ -0,0 +1,93 @@
import { describe, expect, it } from "vite-plus/test";
import {
type MicrophoneEntry,
microphoneEntryKey,
microphoneOrder,
preferredMicrophoneInput,
rememberMicrophones,
} from "./microphonePriority";
const iPhone = { uid: "Built-In Microphone", name: "iPhone Microphone", type: "MicrophoneBuiltIn" };
const airPods = { uid: "airpods", name: "Julius’s AirPods Pro", type: "BluetoothHFP" };
const bose = { uid: "bose", name: "Julius’s Bose QC", type: "BluetoothHFP" };
const civic = { uid: "civic", name: "Honda Civic", type: "BluetoothHFP" };
const carPlay = { uid: "carplay", name: "CarPlay", type: "CarAudio" };
const usb = { uid: "usb", name: "Shure MV7", type: "USBAudio" };
const keys = (order: ReadonlyArray<MicrophoneEntry>) => order.map(microphoneEntryKey);
describe("microphoneOrder", () => {
it("lists every kind once, CarPlay below the built-in microphone by default", () => {
expect(keys(microphoneOrder())).toEqual([
"kind:wired",
"kind:bluetooth",
"kind:builtIn",
"kind:carPlay",
]);
});
it("keeps a saved order and files missing kinds after their devices", () => {
const saved: MicrophoneEntry[] = [
{ kind: "builtIn" },
{ kind: "bluetooth", uid: "airpods", name: "AirPods" },
{ kind: "builtIn" },
];
expect(keys(microphoneOrder(saved))).toEqual([
"kind:wired",
"kind:builtIn",
"airpods",
"kind:bluetooth",
"kind:carPlay",
]);
});
});
describe("rememberMicrophones", () => {
it("lists a new device just above its kind and leaves built-in and CarPlay as kinds", () => {
const order = microphoneOrder();
expect(keys(rememberMicrophones(order, [iPhone, carPlay, airPods]))).toEqual([
"kind:wired",
"airpods",
"kind:bluetooth",
"kind:builtIn",
"kind:carPlay",
]);
});
it("refreshes renamed devices and returns the same order when nothing changed", () => {
const order = rememberMicrophones(microphoneOrder(), [airPods]);
expect(rememberMicrophones(order, [airPods, iPhone])).toBe(order);
const renamed = rememberMicrophones(order, [{ ...airPods, name: "AirPods Max" }]);
expect(renamed.find((entry) => microphoneEntryKey(entry) === "airpods")).toEqual({
kind: "bluetooth",
uid: "airpods",
name: "AirPods Max",
});
});
});
describe("preferredMicrophoneInput", () => {
// Built-in, Bose, Wired, other Bluetooth, AirPods, CarPlay.
const order: MicrophoneEntry[] = [
{ kind: "builtIn" },
{ kind: "bluetooth", uid: "bose", name: bose.name },
{ kind: "wired" },
{ kind: "bluetooth" },
{ kind: "bluetooth", uid: "airpods", name: airPods.name },
{ kind: "carPlay" },
];
it("ranks unlisted devices of a kind at that kind, ahead of a device listed below it", () => {
expect(preferredMicrophoneInput([airPods, civic], order)).toBe(civic);
expect(preferredMicrophoneInput([airPods, bose], order)).toBe(bose);
expect(preferredMicrophoneInput([airPods, usb], order)).toBe(usb);
expect(preferredMicrophoneInput([airPods, carPlay], order)).toBe(airPods);
expect(preferredMicrophoneInput([airPods, iPhone], order)).toBe(iPhone);
});
it("leaves inputs of unknown kinds to iOS", () => {
expect(preferredMicrophoneInput([{ uid: "x", name: "x", type: "Virtual" }], order)).toBeNull();
});
});
+132
View File
@@ -0,0 +1,132 @@
/**
* The order voice input picks a microphone in. An entry is either a kind,
* which covers every connected microphone of that kind not listed by name, or
* a device remembered the first time dictation saw it connected. iOS lists
* only connected inputs, and only while a recording session is set up, so a
* device cannot be listed before then.
*/
export const MICROPHONE_KINDS = ["wired", "bluetooth", "builtIn", "carPlay"] as const;
export type MicrophoneKind = (typeof MICROPHONE_KINDS)[number];
export interface MicrophoneDevice {
readonly kind: MicrophoneKind;
/** iOS's port identifier, stable across reconnects of the same device. */
readonly uid: string;
readonly name: string;
}
export type MicrophoneEntry = { readonly kind: MicrophoneKind } | MicrophoneDevice;
interface MicrophoneInput {
readonly uid: string;
readonly name: string;
readonly type: string;
}
// Raw values of AVAudioSession.Port. A car without CarPlay connects as a
// Bluetooth headset, so it is a Bluetooth device.
const KIND_BY_PORT_TYPE: Readonly<Record<string, MicrophoneKind>> = {
MicrophoneWired: "wired",
USBAudio: "wired",
LineIn: "wired",
BluetoothHFP: "bluetooth",
BluetoothLE: "bluetooth",
MicrophoneBuiltIn: "builtIn",
CarAudio: "carPlay",
};
// Built-in and CarPlay are listed only as kinds: a phone has one built-in
// microphone, and CarPlay is the car.
const DEVICE_KINDS: ReadonlySet<MicrophoneKind> = new Set(["wired", "bluetooth"]);
const rank = (kind: MicrophoneKind) => MICROPHONE_KINDS.indexOf(kind);
export function isMicrophoneKind(value: unknown): value is MicrophoneKind {
return (MICROPHONE_KINDS as ReadonlyArray<unknown>).includes(value);
}
export function isMicrophoneDevice(entry: MicrophoneEntry): entry is MicrophoneDevice {
return "uid" in entry;
}
export function microphoneEntryKey(entry: MicrophoneEntry): string {
return isMicrophoneDevice(entry) ? entry.uid : `kind:${entry.kind}`;
}
/**
* The saved order with each kind listed once. A missing kind goes after the
* devices of that kind, else above the first kind ranked below it by default,
* which puts CarPlay below the built-in microphone.
*/
export function microphoneOrder(
saved: ReadonlyArray<MicrophoneEntry> = [],
): ReadonlyArray<MicrophoneEntry> {
const order: MicrophoneEntry[] = [];
const keys = new Set<string>();
for (const entry of saved) {
const row =
isMicrophoneDevice(entry) && DEVICE_KINDS.has(entry.kind) ? entry : { kind: entry.kind };
const key = microphoneEntryKey(row);
if (keys.has(key)) continue;
keys.add(key);
order.push(row);
}
for (const kind of MICROPHONE_KINDS) {
if (keys.has(`kind:${kind}`)) continue;
const lastDevice = order.map((entry) => entry.kind).lastIndexOf(kind);
const below = order.findIndex(
(entry) => !isMicrophoneDevice(entry) && rank(entry.kind) > rank(kind),
);
order.splice(lastDevice !== -1 ? lastDevice + 1 : below !== -1 ? below : order.length, 0, {
kind,
});
}
return order;
}
/**
* Lists connected wired and Bluetooth microphones by name and refreshes
* renamed ones. A new device goes just above its kind, keeping the rank it had
* while unlisted. Returns `order` itself when nothing changed.
*/
export function rememberMicrophones(
order: ReadonlyArray<MicrophoneEntry>,
inputs: ReadonlyArray<MicrophoneInput>,
): ReadonlyArray<MicrophoneEntry> {
let next: MicrophoneEntry[] | null = null;
for (const input of inputs) {
const kind = KIND_BY_PORT_TYPE[input.type];
if (!kind || !DEVICE_KINDS.has(kind)) continue;
const current = next ?? order;
const index = current.findIndex((entry) => microphoneEntryKey(entry) === input.uid);
const existing = current[index];
if (existing && isMicrophoneDevice(existing) && existing.name === input.name) continue;
next ??= [...order];
const device = { kind, uid: input.uid, name: input.name };
if (index !== -1) {
next[index] = device;
continue;
}
const kindRow = next.findIndex((entry) => microphoneEntryKey(entry) === `kind:${kind}`);
next.splice(kindRow === -1 ? next.length : kindRow, 0, device);
}
return next ?? order;
}
/** The connected input of the first entry that has one, or null to leave the route to iOS. */
export function preferredMicrophoneInput<Input extends MicrophoneInput>(
inputs: ReadonlyArray<Input>,
order: ReadonlyArray<MicrophoneEntry>,
): Input | null {
const listed = new Set(order.filter(isMicrophoneDevice).map((device) => device.uid));
for (const entry of order) {
const input = inputs.find((candidate) =>
isMicrophoneDevice(entry)
? candidate.uid === entry.uid
: KIND_BY_PORT_TYPE[candidate.type] === entry.kind && !listed.has(candidate.uid),
);
if (input) return input;
}
return null;
}
@@ -8,6 +8,7 @@ import * as Semaphore from "effect/Semaphore";
import type { ProviderInstanceId, SidebarProjectGroupingMode } from "@t3tools/contracts";
import type { ComposerEnterBehavior } from "../lib/composerEnterBehavior";
import type { FollowUpBehavior } from "../lib/followUpBehavior";
import { isMicrophoneKind, type MicrophoneEntry } from "../lib/microphonePriority";
import { MOBILE_THEME_IDS, type MobileThemeId, type MobileThemeMode } from "../lib/mobileTheme";
import * as MobileDatabase from "./mobile-database";
import * as MobileSecureStorage from "./mobile-secure-storage";
@@ -36,6 +37,8 @@ export interface Preferences {
* message sent during a running turn queues behind it or steers it.
*/
readonly followUpBehavior?: FollowUpBehavior;
/** Microphone kinds and remembered devices, most preferred first. iOS only. */
readonly microphones?: ReadonlyArray<MicrophoneEntry>;
/** @deprecated Kept temporarily so older OTA bundles retain the selected mode. */
readonly projectGroupingEnabled?: boolean;
readonly projectGroupingMode?: SidebarProjectGroupingMode;
@@ -107,6 +110,7 @@ function sanitizePreferences(parsed: Preferences): Preferences {
collapsedProjectGroups?: readonly string[];
composerEnterBehavior?: ComposerEnterBehavior;
followUpBehavior?: FollowUpBehavior;
microphones?: ReadonlyArray<MicrophoneEntry>;
projectGroupingEnabled?: boolean;
projectGroupingMode?: SidebarProjectGroupingMode;
planModeEnabled?: boolean;
@@ -172,6 +176,15 @@ function sanitizePreferences(parsed: Preferences): Preferences {
if (parsed.followUpBehavior === "queue" || parsed.followUpBehavior === "steer") {
preferences.followUpBehavior = parsed.followUpBehavior;
}
if (Array.isArray(parsed.microphones)) {
preferences.microphones = parsed.microphones.flatMap((entry): MicrophoneEntry[] => {
if (typeof entry !== "object" || entry === null || !isMicrophoneKind(entry.kind)) return [];
if (!("uid" in entry)) return [{ kind: entry.kind }];
return typeof entry.uid === "string" && typeof entry.name === "string"
? [{ kind: entry.kind, uid: entry.uid, name: entry.name }]
: [];
});
}
if (typeof parsed.projectGroupingEnabled === "boolean") {
preferences.projectGroupingEnabled = parsed.projectGroupingEnabled;
}
+7
View File
@@ -164,6 +164,13 @@ minutes long. Canceling, leaving the screen, or an audio interruption discards t
recording and preserves your existing draft. While recording, the screen stays
awake; it can sleep normally once recording stops.
Voice input records from the first connected microphone in **Settings → Microphone**.
The list mixes kinds (built-in, other wired, other Bluetooth, CarPlay) with wired and
Bluetooth devices you have dictated with, listed by name. Drag to rank them together:
for example, put **Other Bluetooth** above your AirPods so a new headset is preferred
while the AirPods microphone stays low. By default, CarPlay comes after the built-in
microphone.
Transcription runs on your device. T3 Code deletes the temporary audio after
transcription or cancellation; only the message text is sent when you submit.