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