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