Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

CloudVoiceSection.tsx

522 lines18.4 KB

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