Open History to see the last commit
1import { msg, useGT, useMessages, type Msg } from "gt-react-native";
2import { ScreenScrollView as ScrollView } from "../../components/ui/ScreenScrollView";
3import { useAtomSet, useAtomValue } from "@effect/atom-react";
4import { AsyncResult } from "effect/reactivity";
5import { getRecordingPermissionsAsync, requestRecordingPermissionsAsync } from "expo-audio";
6import { useState } from "react";
7import { Linking, Platform, useWindowDimensions, View } from "react-native";
8import Reanimated, { ReduceMotion, useAnimatedStyle, withTiming } from "react-native-reanimated";
9import { useSafeAreaInsets } from "react-native-safe-area-context";
10
11import { type AppSymbolName } from "../../components/ui/AppSymbol";
12import { AppText as Text } from "../../components/ui/AppText";
13import { cn } from "../../lib/cn";
14import { m } from "../../i18n/messages";
15import { makePermissionStatusAtom } from "../../lib/permissionStatusAtom";
16import {
17 isMicrophoneDevice,
18 type MicrophoneEntry,
19 type MicrophoneKind,
20 microphoneEntryKey,
21} from "../../lib/microphonePriority";
22import { mobilePreferencesAtom, saveMobilePreferences } from "../../state/preferences";
23import { useAtomCommand } from "../../state/use-atom-command";
24import { ListRowLayout } from "../../components/ui/ListRowLayout";
25import { ListChoiceRow } from "../../components/ui/ListChoiceRow";
26import * as Dialog from "../../components/ui/Dialog";
27import { useEnvironments, type EnvironmentPresentation } from "../../state/environments";
28import {
29 chooseVoiceDestination,
30 cloudVoiceConnectionAtom,
31 voiceConnectionAtom,
32 voiceGrantAtom,
33 hasEnvironmentVoiceCapture,
34} from "../voice-input/voiceDestination";
35import { LocalModelChoice } from "./VoiceModelSection";
36import { CloudVoiceChoice } from "./CloudVoiceSection";
37import type { VoiceGrant } from "../voice-input/voiceGrantStorage";
38import type { EnvironmentId } from "@t3tools/contracts";
39import { ThreadSwipeable } from "../home/thread-swipe-actions";
40import { ListActionRow as SettingsActionRow } from "../../components/ui/ListActionRow";
41import { SettingsDragHandle } from "./components/SettingsDragHandle";
42import { SettingsScreen } from "./components/SettingsScreen";
43import { SettingsSection } from "./components/SettingsSection";
44import {
45 deviceMicrophoneOrder,
46 localVoiceTranscriberAtom,
47} from "../voice-input/VoiceInputProvider";
48
49type MicrophonePermission = "checking" | "granted" | "ask" | "denied";
50
51function toMicrophonePermission(response: {
52 readonly granted: boolean;
53 readonly canAskAgain: boolean;
54}): MicrophonePermission {
55 return response.granted ? "granted" : response.canAskAgain ? "ask" : "denied";
56}
57
58const readMicrophonePermission = () =>
59 getRecordingPermissionsAsync().then(toMicrophonePermission, (): MicrophonePermission => "ask");
60
61const microphonePermissionAtom = makePermissionStatusAtom<MicrophonePermission>({
62 label: "mobile:microphone-permission",
63 initial: "checking",
64 read: readMicrophonePermission,
65});
66
67function useMicrophonePermission() {
68 const permission = useAtomValue(microphonePermissionAtom);
69 const setPermission = useAtomSet(microphonePermissionAtom);
70 const request = () =>
71 void requestRecordingPermissionsAsync()
72 .then(toMicrophonePermission, readMicrophonePermission)
73 .then(setPermission);
74 return { permission, request };
75}
76
77const KINDS: Record<
78 MicrophoneKind,
79 {
80 readonly label: string | Msg;
81 readonly row: string;
82 readonly rowDescription: string;
83 readonly icon: AppSymbolName;
84 }
85> = {
86 wired: {
87 label: msg({ context: "microphone connection type" })`Wired`,
88 row: msg("Other wired"),
89 rowDescription: msg("Headsets and USB microphones not listed here"),
90 icon: "cable.connector",
91 },
92 bluetooth: {
93 label: msg("Bluetooth"),
94 row: msg("Other Bluetooth"),
95 rowDescription:
96 Platform.OS === "android"
97 ? msg("Earbuds, headsets, and cars, including Android Auto, not listed here")
98 : msg("AirPods, headsets, and cars not listed here"),
99 icon: "headphones",
100 },
101 builtIn: {
102 label: msg({ context: "microphone connection type" })`Built-in`,
103 row: msg("Built-in microphone"),
104 rowDescription: msg("The microphone on this device"),
105 icon: "iphone",
106 },
107 carPlay: {
108 label: "CarPlay",
109 row: "CarPlay",
110 rowDescription: msg("The car’s microphone"),
111 icon: "car",
112 },
113};
114
115const UNAVAILABLE_EXPLANATION =
116 Platform.OS === "android"
117 ? msg(
118 "Dictation on this device needs Android 12 or later and Google speech services that support your language. Your keyboard’s voice typing is separate.",
119 )
120 : msg(
121 "Dictation on this device needs iOS 26 or later, a supported device, and a supported language. Your keyboard’s dictation is separate.",
122 );
123
124function saveDestination(id: EnvironmentId | null) {
125 try {
126 chooseVoiceDestination(id);
127 } catch {
128 Dialog.alert(
129 m(msg("Could not save transcription choice")),
130 m(
131 msg(
132 "Dictation on an environment is off for this session. Save again before closing the app, or your previous choice may return when it restarts.",
133 ),
134 ),
135 );
136 }
137}
138
139function EnvironmentChoice({
140 environment,
141 selected,
142 onCloudOnly,
143}: {
144 environment: EnvironmentPresentation;
145 selected: boolean;
146 /** Called instead of a local grant when the environment only offers cloud transcription. */
147 onCloudOnly: () => void;
148}) {
149 const gt = useGT();
150 const local = useAtomValue(voiceConnectionAtom(environment.environmentId)) !== null;
151 const cloud = useAtomValue(cloudVoiceConnectionAtom(environment.environmentId)) !== null;
152 const usable = local || cloud;
153 return (
154 <ListChoiceRow
155 label={environment.label}
156 selected={selected}
157 disabled={!usable}
158 description={
159 environment.connection.phase !== "connected"
160 ? gt`Not connected`
161 : !usable
162 ? gt`Transcription unavailable`
163 : (environment.displayUrl ?? gt`Send finished recordings to this environment.`)
164 }
165 separated
166 onPress={() => {
167 if (selected) return;
168 if (!local) return onCloudOnly();
169 Dialog.confirm({
170 title: gt`Send microphone audio to ${{ environment: environment.label }}?`,
171 message: gt`Finished recordings will be sent to ${{ destination: environment.displayUrl ?? environment.label }} for transcription. You can switch back to This device at any time.`,
172 confirmText: gt`Use environment`,
173 onConfirm: () => saveDestination(environment.environmentId),
174 });
175 }}
176 />
177 );
178}
179
180/** How the selected environment transcribes: its own model or a cloud provider. */
181function EnvironmentMethodSection({
182 environment,
183 grant,
184 cloudOpen,
185 onCloudOpenChange,
186}: {
187 environment: EnvironmentPresentation;
188 grant: VoiceGrant | null;
189 cloudOpen: boolean;
190 onCloudOpenChange: (open: boolean) => void;
191}) {
192 const gt = useGT();
193 const id = environment.environmentId;
194 const destination = grant?.destination.environmentId === id ? grant.destination : null;
195 const cloudCapable =
196 environment.serverConfig?.environment.capabilities.cloudVoiceTranscription === true ||
197 destination?.kind === "cloud";
198 return (
199 <SettingsSection title={gt`Method on ${{ environment: environment.label }}`}>
200 <LocalModelChoice
201 environmentId={id}
202 label={environment.label}
203 selected={destination?.kind === "environment"}
204 // The user already agreed to send audio to this environment.
205 onSelect={() => saveDestination(id)}
206 />
207 {cloudCapable ? (
208 <CloudVoiceChoice
209 environment={environment}
210 active={destination?.kind === "cloud" ? destination : null}
211 open={cloudOpen}
212 onOpenChange={onCloudOpenChange}
213 />
214 ) : null}
215 </SettingsSection>
216 );
217}
218
219export function SettingsVoiceRouteScreen() {
220 const gt = useGT();
221 const m = useMessages();
222 const transcriber = useAtomValue(localVoiceTranscriberAtom);
223 const grant = useAtomValue(voiceGrantAtom);
224 const { environments, isReady } = useEnvironments();
225 const grantEnvironment = grant
226 ? environments.find(
227 (environment) => environment.environmentId === grant.destination.environmentId,
228 )
229 : undefined;
230 // An environment whose cloud sheet is open; it may not hold the grant yet.
231 const [cloudSheet, setCloudSheet] = useState<EnvironmentId | null>(null);
232 // A sheet whose environment lost cloud transcription is gone, so its pending choice is too.
233 const sheetEnvironment = environments.find(
234 (environment) =>
235 environment.environmentId === cloudSheet &&
236 environment.serverConfig?.environment.capabilities.cloudVoiceTranscription === true,
237 );
238 const methodEnvironment = sheetEnvironment ?? grantEnvironment;
239 const insets = useSafeAreaInsets();
240 const preferencesResult = useAtomValue(mobilePreferencesAtom);
241 const savePreferences = useAtomCommand(saveMobilePreferences);
242 const ready = AsyncResult.isSuccess(preferencesResult) && !preferencesResult.waiting;
243 const entries = deviceMicrophoneOrder(
244 AsyncResult.isSuccess(preferencesResult) ? preferencesResult.value.microphones : undefined,
245 );
246 const { permission, request: requestPermission } = useMicrophonePermission();
247 const [drag, setDrag] = useState<{ readonly key: string; readonly translation: number } | null>(
248 null,
249 );
250 const [rowHeight, setRowHeight] = useState(0);
251 // Each drop remounts the rows so the new order and the cleared offsets land in one frame.
252 const [drops, setDrops] = useState(0);
253
254 // Transforms apply to the stored order, so a device recorded meanwhile is kept.
255 const move = (key: string, steps: number) => {
256 void savePreferences({
257 transform: (current) => {
258 const next = [...deviceMicrophoneOrder(current.microphones)];
259 const from = next.findIndex((entry) => microphoneEntryKey(entry) === key);
260 const to = Math.min(next.length - 1, Math.max(0, from + steps));
261 if (from === -1 || from === to) return {};
262 const [moved] = next.splice(from, 1);
263 next.splice(to, 0, moved!);
264 return { microphones: next };
265 },
266 });
267 };
268 const forget = (key: string) => {
269 void savePreferences({
270 transform: (current) => ({
271 microphones: deviceMicrophoneOrder(current.microphones).filter(
272 (entry) => microphoneEntryKey(entry) !== key,
273 ),
274 }),
275 });
276 };
277 const dropSteps = (from: number, translation: number) =>
278 rowHeight === 0
279 ? 0
280 : Math.min(entries.length - 1, Math.max(0, from + Math.round(translation / rowHeight))) -
281 from;
282
283 const dragFrom =
284 drag === null ? -1 : entries.findIndex((entry) => microphoneEntryKey(entry) === drag.key);
285 const dragTo = drag === null ? -1 : dragFrom + dropSteps(dragFrom, drag.translation);
286
287 return (
288 <SettingsScreen title={gt`Voice`}>
289 <ScrollView
290 contentInsetAdjustmentBehavior="automatic"
291 showsVerticalScrollIndicator={false}
292 className="flex-1"
293 contentContainerClassName="gap-3 px-5 pt-4"
294 contentContainerStyle={{ paddingBottom: Math.max(insets.bottom, 18) + 18 }}
295 >
296 <SettingsSection title={gt`Transcribe on`}>
297 <ListChoiceRow
298 label={gt`This device`}
299 description={gt`Audio stays on this device and is transcribed here.`}
300 selected={!grant && !sheetEnvironment}
301 onPress={() => {
302 setCloudSheet(null);
303 saveDestination(null);
304 }}
305 />
306 {hasEnvironmentVoiceCapture &&
307 environments.map((environment) => (
308 <EnvironmentChoice
309 key={environment.environmentId}
310 environment={environment}
311 selected={
312 sheetEnvironment
313 ? sheetEnvironment.environmentId === environment.environmentId
314 : grant?.destination.environmentId === environment.environmentId
315 }
316 onCloudOnly={() => setCloudSheet(environment.environmentId)}
317 />
318 ))}
319 {isReady && grant && !grantEnvironment ? (
320 <ListChoiceRow
321 label={gt`Previously selected environment`}
322 description={gt`No longer paired`}
323 separated
324 selected
325 disabled
326 onPress={() => {}}
327 />
328 ) : null}
329 </SettingsSection>
330 {hasEnvironmentVoiceCapture && methodEnvironment ? (
331 <EnvironmentMethodSection
332 environment={methodEnvironment}
333 grant={grant}
334 cloudOpen={cloudSheet === methodEnvironment.environmentId}
335 onCloudOpenChange={(open) =>
336 setCloudSheet(open ? methodEnvironment.environmentId : null)
337 }
338 />
339 ) : null}
340 {!grant && transcriber === null ? (
341 <Text className="px-2 text-sm text-foreground-muted">{m(UNAVAILABLE_EXPLANATION)}</Text>
342 ) : null}
343 {permission === "ask" || permission === "denied" ? (
344 <>
345 <SettingsSection title={gt`Microphone access`}>
346 <SettingsActionRow
347 icon="mic"
348 label={permission === "ask" ? gt`Allow microphone access` : gt`Open Settings`}
349 onPress={
350 permission === "ask" ? requestPermission : () => void Linking.openSettings()
351 }
352 />
353 </SettingsSection>
354 <Text className="px-2 text-sm text-foreground-muted">
355 {permission === "ask"
356 ? gt`Allow microphone access to record and to see your microphones.`
357 : gt`Turn on microphone access for ${{ product: "T3 Code" }} in Settings to use voice input.`}
358 </Text>
359 </>
360 ) : null}
361 <SettingsSection title={gt`Preferred order`}>
362 {entries.map((entry, index) => {
363 const key = microphoneEntryKey(entry);
364 const shift =
365 dragFrom === -1 || index === dragFrom
366 ? 0
367 : dragFrom < dragTo && index > dragFrom && index <= dragTo
368 ? -rowHeight
369 : dragFrom > dragTo && index < dragFrom && index >= dragTo
370 ? rowHeight
371 : 0;
372 return (
373 <MicrophoneRow
374 key={`${key}:${drops}`}
375 entry={entry}
376 position={index + 1}
377 count={entries.length}
378 reorderable={ready}
379 offset={index === dragFrom ? (drag?.translation ?? 0) : shift}
380 lifted={index === dragFrom}
381 onHeight={setRowHeight}
382 onDragStart={() => setDrag({ key, translation: 0 })}
383 onDragMove={(translation) => setDrag({ key, translation })}
384 onDragEnd={(translation, cancelled) => {
385 setDrag(null);
386 setDrops((count) => count + 1);
387 if (!cancelled) move(key, dropSteps(index, translation));
388 }}
389 onStep={(direction) => move(key, direction === "up" ? -1 : 1)}
390 onForget={isMicrophoneDevice(entry) ? () => forget(key) : undefined}
391 />
392 );
393 })}
394 </SettingsSection>
395 <Text className="px-2 text-sm text-foreground-muted">
396 {Platform.OS === "android"
397 ? gt`Voice input uses the first connected microphone in this list. A wired or Bluetooth microphone is added by name the first time you dictate with it connected; until then it falls under Other. Swipe left on a named microphone to forget it. Android may still use a different microphone if the preferred one can’t be routed.`
398 : gt`Voice input uses the first connected microphone in this list. A wired or Bluetooth microphone is added by name the first time you dictate with it connected; until then it falls under Other. Swipe left on a named microphone to forget it.`}
399 </Text>
400 </ScrollView>
401 </SettingsScreen>
402 );
403}
404
405function MicrophoneRow(props: {
406 readonly entry: MicrophoneEntry;
407 readonly position: number;
408 readonly count: number;
409 readonly reorderable: boolean;
410 readonly offset: number;
411 readonly lifted: boolean;
412 readonly onHeight: (height: number) => void;
413 readonly onDragStart: () => void;
414 readonly onDragMove: (translation: number) => void;
415 readonly onDragEnd: (translation: number, cancelled: boolean) => void;
416 readonly onStep: (direction: "up" | "down") => void;
417 readonly onForget: (() => void) | undefined;
418}) {
419 const gt = useGT();
420 const m = useMessages();
421 const { lifted, offset, entry, onForget } = props;
422 const kind = KINDS[entry.kind];
423 const title = isMicrophoneDevice(entry) ? entry.name : m(kind.row);
424 const { width: windowWidth } = useWindowDimensions();
425 const style = useAnimatedStyle(() => ({
426 transform: [
427 {
428 translateY: lifted
429 ? offset
430 : withTiming(offset, { duration: 160, reduceMotion: ReduceMotion.System }),
431 },
432 ],
433 zIndex: lifted ? 1 : 0,
434 }));
435 const row = (
436 // Opaque so the swipe actions stay hidden until the row slides over them.
437 <View className="flex-row items-center bg-grouped-card">
438 <View
439 accessible
440 accessibilityLabel={gt`${{ title }}, ${{ kind: m(kind.label) }}, ${{ position: props.position }} of ${{ count: props.count }}`}
441 accessibilityActions={
442 onForget
443 ? [{ name: "forget", label: gt({ context: "verb, forget a microphone" })`Forget` }]
444 : undefined
445 }
446 onAccessibilityAction={({ nativeEvent }) => {
447 if (nativeEvent.actionName === "forget") onForget?.();
448 }}
449 className="min-w-0 flex-1"
450 >
451 <ListRowLayout
452 icon={kind.icon}
453 label={title}
454 description={isMicrophoneDevice(entry) ? m(kind.label) : m(kind.rowDescription)}
455 />
456 </View>
457 {props.reorderable ? (
458 <SettingsDragHandle
459 title={title}
460 canMoveUp={props.position > 1}
461 canMoveDown={props.position < props.count}
462 onStart={props.onDragStart}
463 onMove={props.onDragMove}
464 onEnd={props.onDragEnd}
465 onStep={props.onStep}
466 />
467 ) : null}
468 </View>
469 );
470 return (
471 <Reanimated.View
472 style={style}
473 onLayout={(event) => props.onHeight(event.nativeEvent.layout.height)}
474 className={cn(
475 props.position > 1 && !lifted && "border-t border-border-subtle",
476 lifted && "bg-grouped-card shadow-md",
477 )}
478 >
479 {onForget ? (
480 <ThreadSwipeable
481 backgroundColor="transparent"
482 fullSwipeAction="primary"
483 fullSwipeWidth={windowWidth - 40}
484 onDelete={onForget}
485 primaryAction={{
486 accessibilityLabel: gt`Forget ${{ title }}`,
487 destructive: true,
488 icon: "trash",
489 label: gt({ context: "verb, forget a microphone" })`Forget`,
490 onPress: onForget,
491 }}
492 secondaryAction={null}
493 threadKey={`microphone:${microphoneEntryKey(entry)}`}
494 threadTitle={title}
495 >
496 {() => row}
497 </ThreadSwipeable>
498 ) : (
499 row
500 )}
501 </Reanimated.View>
502 );
503}