Open History to see the last commit
1import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
2import { cloudSpeechDisclosure } from "@t3tools/shared/speech";
3import { setCloudSpeechKey } from "@t3tools/client-runtime/voice-input";
4import {
5 configuredSecretSources,
6 secretRequestReference,
7} from "@t3tools/client-runtime/secret-request";
8import {
9 AuthSettingsWriteScope,
10 CLOUD_SPEECH_LABELS,
11 CLOUD_SPEECH_PROVIDER_NAMES,
12 CloudSpeechProvider,
13 CloudSpeechApiKey,
14 CloudSpeechModelId,
15 isSecretReference,
16 type CloudSpeechModel,
17 type SecretProviderId,
18 type SettingsSecretValue,
19 type VoiceTranscriptionDestination,
20} from "@t3tools/contracts";
21import * as Schema from "effect/Schema";
22import Constants from "expo-constants";
23import { AsyncResult } from "effect/reactivity";
24import { useState } from "react";
25import { ScrollView, TextInput, View } from "react-native";
26import { Sheet } from "../../components/ui/Sheet";
27import * as Dialog from "../../components/ui/Dialog";
28import { ProviderIcon } from "../../components/ProviderIcon";
29import { AppText as Text } from "../../components/ui/AppText";
30import { ListActionRow } from "../../components/ui/ListActionRow";
31import { ListChoiceRow } from "../../components/ui/ListChoiceRow";
32import { Chip } from "../../components/ui/Chip";
33import type { EnvironmentPresentation } from "../../state/environments";
34import { useEnvironmentScope } from "../../state/session";
35import {
36 chooseVoiceDestination,
37 pendingCloudVoiceChoice,
38 cloudVoiceConnectionAtom,
39 cloudVoiceKeysAtom,
40 cloudVoiceModelsAtom,
41 runSpeech,
42} from "../voice-input/voiceDestination";
43import { SettingsSection } from "./components/SettingsSection";
44
45type CloudDestination = Extract<VoiceTranscriptionDestination, { kind: "cloud" }>;
46type Props = { environment: EnvironmentPresentation; active: CloudDestination | null };
47const isApiKey = Schema.is(CloudSpeechApiKey);
48const isModelId = Schema.is(CloudSpeechModelId);
49const MODEL_ROWS = 6;
50
51export function CloudVoiceSection({ environment, active }: Props) {
52 const [open, setOpen] = useState(false);
53 return (
54 <SettingsSection title={`Cloud via ${environment.label}`}>
55 <ListActionRow
56 label="Cloud providers"
57 description={
58 active
59 ? `Using ${CLOUD_SPEECH_LABELS[active.provider]}`
60 : "Optional · use your own API key"
61 }
62 onPress={() => setOpen(true)}
63 />
64 {open && (
65 <CloudChoices environment={environment} active={active} onClose={() => setOpen(false)} />
66 )}
67 </SettingsSection>
68 );
69}
70
71function ModelPicker({
72 models,
73 value,
74 current,
75 disabled,
76 onChange,
77}: {
78 models: ReadonlyArray<CloudSpeechModel>;
79 value: string;
80 /** The grant's model, flagged when the catalog no longer lists it. */
81 current: string | undefined;
82 disabled: boolean;
83 onChange: (model: CloudSpeechModelId) => void;
84}) {
85 const [query, setQuery] = useState("");
86 const [showAll, setShowAll] = useState(false);
87 const needle = query.trim().toLowerCase();
88 const selected = models.find((model) => model.id === value);
89 const matches = models.filter((model) =>
90 `${model.name} ${model.id}`.toLowerCase().includes(needle),
91 );
92 const shown = showAll ? matches : matches.slice(0, MODEL_ROWS);
93 const delisted = current !== undefined && !models.some((model) => model.id === current);
94 return (
95 <>
96 <TextInput
97 accessibilityLabel="Search OpenRouter models"
98 placeholder="Search transcription models"
99 autoCapitalize="none"
100 autoCorrect={false}
101 editable={!disabled}
102 value={query}
103 onChangeText={setQuery}
104 className="mx-4 rounded-lg bg-background px-3 py-2 text-foreground"
105 />
106 {delisted ? (
107 <Text className="mx-4 text-sm text-destructive">
108 OpenRouter no longer lists {current}. Dictation stays off until you choose another model.
109 </Text>
110 ) : null}
111 {selected && !shown.some((model) => model.id === selected.id) ? (
112 <ListChoiceRow
113 label={selected.name}
114 description={selected.id}
115 selected
116 disabled={disabled}
117 onPress={() => {}}
118 />
119 ) : null}
120 {shown.map((model, index) => (
121 <ListChoiceRow
122 key={model.id}
123 label={model.name}
124 description={model.id}
125 selected={model.id === value}
126 separated={index > 0}
127 disabled={disabled}
128 onPress={() => onChange(model.id)}
129 />
130 ))}
131 {matches.length === 0 ? (
132 <Text className="mx-4 text-sm text-foreground-muted">No transcription model matches.</Text>
133 ) : matches.length > shown.length ? (
134 <ListActionRow
135 label={`Show all ${matches.length} models`}
136 onPress={() => setShowAll(true)}
137 />
138 ) : null}
139 </>
140 );
141}
142
143function CloudChoices({ environment, active, onClose }: Props & { onClose: () => void }) {
144 const id = environment.environmentId;
145 const connection = useAtomValue(cloudVoiceConnectionAtom(id));
146 const keys = useAtomValue(cloudVoiceKeysAtom(id));
147 const reload = useAtomRefresh(cloudVoiceKeysAtom(id));
148 const canManage = useEnvironmentScope(id, AuthSettingsWriteScope);
149 const [editing, setEditing] = useState<{
150 provider: CloudSpeechProvider;
151 enable: boolean;
152 } | null>(null);
153 const catalogAtom = cloudVoiceModelsAtom(editing?.provider === "openrouter" ? id : null);
154 const models = useAtomValue(catalogAtom);
155 const reloadModels = useAtomRefresh(catalogAtom);
156 const [draft, setDraft] = useState("");
157 const [model, setModel] = useState("");
158 const [sourceId, setSourceId] = useState<SecretProviderId | null>(null);
159 const sources =
160 Constants.expoConfig?.extra?.secretsFeatureEnabled === true &&
161 environment.serverConfig?.secretReferences
162 ? configuredSecretSources(environment.serverConfig.settings.secretProviders)
163 : [];
164 const source = sources.find((candidate) => candidate.id === sourceId);
165 const credential =
166 sourceId !== null
167 ? source && secretRequestReference(source, draft)
168 : isApiKey(draft.trim())
169 ? draft.trim()
170 : undefined;
171 const [saving, setSaving] = useState(false);
172 const activeModel = active?.provider === "openrouter" ? active.model : undefined;
173 const enable = (commit: () => void) => {
174 try {
175 commit();
176 } catch {
177 Dialog.alert(
178 "Could not enable cloud dictation",
179 "Check device storage and choose the provider again.",
180 );
181 }
182 };
183 const edit = (provider: CloudSpeechProvider, enable: boolean) => {
184 const stored = environment.serverConfig?.settings.cloudSpeechCredentials?.[provider];
185 const ref =
186 isSecretReference(stored) && sources.some((candidate) => candidate.id === stored.provider)
187 ? stored
188 : null;
189 setSourceId(ref?.provider ?? null);
190 setDraft(ref?.reference ?? "");
191 setModel(provider === "openrouter" ? (activeModel ?? "") : "");
192 setEditing({ provider, enable });
193 };
194 const reset = () => {
195 setDraft("");
196 setModel("");
197 setEditing(null);
198 };
199 const changeKey = async (
200 provider: CloudSpeechProvider,
201 value: SettingsSecretValue | null,
202 chosen?: CloudSpeechModelId,
203 ) => {
204 if (!connection || !canManage || saving) return;
205 const commit =
206 value !== null && (editing?.enable || (chosen !== undefined && chosen !== activeModel))
207 ? pendingCloudVoiceChoice(id, provider, chosen)
208 : null;
209 setSaving(true);
210 try {
211 await runSpeech(setCloudSpeechKey(connection, provider, value));
212 } catch {
213 setSaving(false);
214 Dialog.alert(
215 "Could not update the API key",
216 "Check the environment connection and your settings permissions.",
217 );
218 return;
219 }
220 setSaving(false);
221 if (commit) enable(commit);
222 reload();
223 onClose();
224 };
225 const catalog = AsyncResult.isSuccess(models) ? (models.value?.models ?? null) : null;
226 const content =
227 !AsyncResult.isSuccess(keys) || !keys.value || !connection ? (
228 <ListActionRow
229 label={
230 !connection
231 ? "Environment not connected"
232 : keys._tag === "Failure"
233 ? "Could not load keys · Retry"
234 : "Checking API keys…"
235 }
236 disabled={!connection || keys._tag !== "Failure"}
237 onPress={reload}
238 />
239 ) : (
240 CloudSpeechProvider.literals.map((provider) => {
241 if (editing && provider !== editing.provider) return null;
242 const label = CLOUD_SPEECH_LABELS[provider];
243 const company = CLOUD_SPEECH_PROVIDER_NAMES[provider];
244 const routed = provider === "openrouter";
245 const disclosure = cloudSpeechDisclosure(provider, environment.label);
246 const saved = keys.value![provider];
247 const isActive = active?.provider === provider;
248 const isEditing = editing?.provider === provider;
249 const modelChosen =
250 isModelId(model) && (catalog?.some((entry) => entry.id === model) ?? false);
251 const modelChanged = model !== (activeModel ?? "");
252 const original = environment.serverConfig?.settings.cloudSpeechCredentials?.[provider];
253 const keyChanged =
254 credential !== undefined &&
255 !(
256 isSecretReference(credential) &&
257 isSecretReference(original) &&
258 original.provider === credential.provider &&
259 original.reference === credential.reference
260 );
261 const routedReady =
262 modelChosen &&
263 (draft.trim() ? credential !== undefined : Boolean(saved)) &&
264 (!isActive || modelChanged || keyChanged);
265 const saveRouted = () => {
266 if (!routedReady || !isModelId(model)) return;
267 const grantChanges = !isActive || modelChanged;
268 if (credential !== undefined && keyChanged)
269 return void changeKey(provider, credential, model);
270 // Model-only changes never write to the environment.
271 if (grantChanges) enable(() => chooseVoiceDestination(id, provider, model));
272 onClose();
273 };
274 return (
275 <View key={provider}>
276 {!isEditing && (
277 <ListChoiceRow
278 label={label}
279 leading={
280 <ProviderIcon
281 provider={
282 provider === "openai" ? "codex" : provider === "xai" ? "grok" : provider
283 }
284 size={20}
285 />
286 }
287 selected={isActive}
288 disabled={saved === undefined || (!saved && !canManage) || saving}
289 description={
290 saved === undefined
291 ? "Update the environment to use this provider"
292 : isActive && routed
293 ? `${activeModel} · Tap to change model${canManage ? " or key" : ""}`
294 : isActive && saved && canManage
295 ? "Tap to manage key"
296 : saved
297 ? routed
298 ? "API key saved · choose a model to use it"
299 : "API key saved on this environment"
300 : canManage
301 ? "Add an API key to use this provider"
302 : "Ask an environment administrator to add an API key"
303 }
304 onPress={() => {
305 if (routed) return edit(provider, !isActive);
306 if (!saved) return edit(provider, true);
307 if (isActive) {
308 if (canManage) edit(provider, false);
309 return;
310 }
311 Dialog.confirm({
312 title: `Use ${label} for dictation?`,
313 message: `${disclosure} Select This device to stop sharing.`,
314 confirmText: `Use ${label}`,
315 onConfirm: () => enable(pendingCloudVoiceChoice(id, provider)),
316 });
317 }}
318 />
319 )}
320 {isEditing && routed && (
321 <>
322 <Text className="mx-4 text-sm text-foreground-muted">{disclosure}</Text>
323 {catalog ? (
324 <ModelPicker
325 models={catalog}
326 value={model}
327 current={activeModel}
328 disabled={saving}
329 onChange={setModel}
330 />
331 ) : (
332 <ListActionRow
333 label={
334 AsyncResult.isFailure(models)
335 ? "Could not load models · Retry"
336 : "Loading transcription models…"
337 }
338 disabled={!AsyncResult.isFailure(models)}
339 onPress={reloadModels}
340 />
341 )}
342 </>
343 )}
344 {isEditing && (canManage || routed) && (
345 <>
346 {canManage && sources.length > 0 && (
347 <View className="mx-4 flex-row flex-wrap gap-2">
348 <Chip
349 label="Value"
350 size="small"
351 selected={sourceId === null}
352 disabled={saving}
353 onPress={() => {
354 setDraft("");
355 setSourceId(null);
356 }}
357 />
358 {sources.map((candidate) => (
359 <Chip
360 key={candidate.id}
361 label={candidate.label}
362 size="small"
363 selected={sourceId === candidate.id}
364 disabled={saving}
365 onPress={() => {
366 setDraft("");
367 setSourceId(candidate.id);
368 }}
369 />
370 ))}
371 </View>
372 )}
373 {canManage && (
374 <TextInput
375 key={sourceId ?? "literal"}
376 accessibilityLabel={
377 sourceId ? `${label} API key reference` : `${label} API key`
378 }
379 placeholder={
380 source?.referencePlaceholder ??
381 (routed && saved ? "Saved key · enter a new one to replace" : "API key")
382 }
383 secureTextEntry={sourceId === null}
384 autoCapitalize="none"
385 autoCorrect={false}
386 autoComplete="off"
387 importantForAutofill="no"
388 maxLength={4096}
389 editable={!saving}
390 returnKeyType="done"
391 onSubmitEditing={() => {
392 if (routed) saveRouted();
393 else if (credential) void changeKey(provider, credential);
394 }}
395 value={draft}
396 onChangeText={setDraft}
397 className="mx-4 rounded-lg bg-background px-3 py-2 text-foreground"
398 />
399 )}
400 {routed && !saved && !canManage ? (
401 <ListActionRow
402 label="Ask an administrator to add an OpenRouter key"
403 disabled
404 onPress={() => {}}
405 />
406 ) : (
407 <ListActionRow
408 label={
409 routed
410 ? isActive
411 ? "Save"
412 : "Save and enable"
413 : editing.enable
414 ? "Save and enable"
415 : "Save key"
416 }
417 description={
418 draft && !credential
419 ? (source?.invalidReferenceMessage ?? "Enter a valid API key.")
420 : routed
421 ? saved && !credential
422 ? "Uses the API key saved on this environment. The model choice applies only to this device."
423 : `Anyone with dictation access to ${environment.label} can bill this key.`
424 : editing.enable
425 ? `${disclosure} Anyone with dictation access to ${environment.label} can bill this key.`
426 : `Updates the ${company} key on ${environment.label}. Your dictation destination stays the same.`
427 }
428 disabled={(routed ? !routedReady : !credential) || saving}
429 onPress={() => {
430 if (routed) saveRouted();
431 else if (credential) void changeKey(provider, credential);
432 }}
433 />
434 )}
435 {saved && canManage && (
436 <ListActionRow
437 tone="danger"
438 label="Remove key from environment"
439 disabled={saving}
440 onPress={() =>
441 Dialog.confirm({
442 title: `Remove the ${label} key from ${environment.label}?`,
443 message: "Everyone using it for dictation will lose access.",
444 confirmText: "Remove key",
445 destructive: true,
446 onConfirm: () => void changeKey(provider, null),
447 })
448 }
449 />
450 )}
451 <ListActionRow label="Back to providers" disabled={saving} onPress={reset} />
452 </>
453 )}
454 </View>
455 );
456 })
457 );
458 return (
459 <Sheet
460 title={editing ? CLOUD_SPEECH_LABELS[editing.provider] : "Cloud providers"}
461 onClose={onClose}
462 dismissDisabled={saving}
463 >
464 <ScrollView
465 contentInsetAdjustmentBehavior="automatic"
466 keyboardShouldPersistTaps="handled"
467 contentContainerClassName="gap-2 pb-8"
468 >
469 {content}
470 </ScrollView>
471 </Sheet>
472 );
473}