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

CloudVoiceSection.tsx

539 lines19.4 KB

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