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

CloudVoiceSection.tsx

562 lines20.1 KB

1import { T, useGT, useMessages } 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(
119 "{provider} no longer lists {model}. Dictation stays off until you choose another model.",
120 { provider: "OpenRouter", model: current },
121 )
122 : undefined
123 }
124 >
125 <View className="px-4 py-3">
126 <TextInput
127 accessibilityLabel={gt("Search {provider} models", { provider: "OpenRouter" })}
128 placeholder={gt("Search transcription models")}
129 autoCapitalize="none"
130 autoCorrect={false}
131 editable={!disabled}
132 value={query}
133 onChangeText={setQuery}
134 className="rounded-lg bg-background px-3 py-2 text-foreground"
135 />
136 </View>
137 {selected && !shown.some((model) => model.id === selected.id) ? (
138 <ListChoiceRow
139 label={selected.name}
140 description={selected.id}
141 selected
142 separated
143 disabled={disabled}
144 onPress={() => {}}
145 />
146 ) : null}
147 {shown.map((model) => (
148 <ListChoiceRow
149 key={model.id}
150 label={model.name}
151 description={model.id}
152 selected={model.id === value}
153 separated
154 disabled={disabled}
155 onPress={() => onChange(model.id)}
156 />
157 ))}
158 {matches.length === 0 ? (
159 <Separated>
160 <Text className="px-4 py-3 text-sm text-foreground-muted">
161 <T>No transcription model matches.</T>
162 </Text>
163 </Separated>
164 ) : matches.length > shown.length ? (
165 <Separated>
166 <ListActionRow
167 label={gt(
168 "{count, plural, one {Show all {count} models} other {Show all {count} models}}",
169 { count: matches.length },
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} using its API key.", {
293 environment: environment.label,
294 })}
295 >
296 {CloudSpeechProvider.literals.map((provider, index) => {
297 const label = CLOUD_SPEECH_LABELS[provider];
298 const routed = provider === "openrouter";
299 const key = saved[provider];
300 const isActive = active?.provider === provider;
301 return (
302 <ListChoiceRow
303 key={provider}
304 label={label}
305 leading={
306 <ProviderIcon
307 provider={
308 provider === "openai" ? "codex" : provider === "xai" ? "grok" : provider
309 }
310 size={20}
311 />
312 }
313 selected={isActive}
314 separated={index > 0}
315 disabled={key === undefined || (!key && !canManage) || saving}
316 description={
317 key === undefined
318 ? gt("Update the environment to use this provider")
319 : isActive && routed
320 ? canManage
321 ? gt("{model} · Tap to change model or key", { model: activeModel })
322 : gt("{model} · Tap to change model", { model: activeModel })
323 : isActive && key && canManage
324 ? gt("Tap to manage key")
325 : key
326 ? routed
327 ? gt("API key saved · choose a model to use it")
328 : gt("API key saved")
329 : canManage
330 ? gt("Add an API key to use this provider")
331 : gt("Ask an environment administrator to add an API key")
332 }
333 onPress={() => {
334 if (routed) return edit(provider, !isActive);
335 if (!key) return edit(provider, true);
336 if (isActive) {
337 if (canManage) edit(provider, false);
338 return;
339 }
340 Dialog.confirm({
341 title: gt("Use {provider} for dictation?", { provider: label }),
342 message: gt("{disclosure} Select This device to stop sharing.", {
343 disclosure: cloudSpeechDisclosure(provider, environment.label, messages),
344 }),
345 confirmText: gt("Use {provider}", { provider: label }),
346 onConfirm: () => enable(pendingCloudVoiceChoice(id, provider)),
347 });
348 }}
349 />
350 );
351 })}
352 </ListSection>
353 );
354​
355 const provider = editing.provider;
356 const label = CLOUD_SPEECH_LABELS[provider];
357 const company = CLOUD_SPEECH_PROVIDER_NAMES[provider];
358 const routed = provider === "openrouter";
359 const disclosure = cloudSpeechDisclosure(provider, environment.label, messages);
360 const key = saved[provider];
361 const isActive = active?.provider === provider;
362 const modelChosen = isModelId(model) && (catalog?.some((entry) => entry.id === model) ?? false);
363 const modelChanged = model !== (activeModel ?? "");
364 const original = environment.serverConfig?.settings.cloudSpeechCredentials?.[provider];
365 const keyChanged =
366 credential !== undefined &&
367 !(
368 isSecretReference(credential) &&
369 isSecretReference(original) &&
370 original.provider === credential.provider &&
371 original.reference === credential.reference
372 );
373 const routedReady =
374 modelChosen &&
375 (draft.trim() ? credential !== undefined : Boolean(key)) &&
376 (!isActive || modelChanged || keyChanged);
377 const saveRouted = () => {
378 if (!routedReady || !isModelId(model)) return;
379 const grantChanges = !isActive || modelChanged;
380 if (credential !== undefined && keyChanged)
381 return void changeKey(provider, credential, model);
382 // Model-only changes never write to the environment.
383 if (grantChanges) enable(() => chooseVoiceDestination(id, provider, model));
384 onClose();
385 };
386 const submit = () => {
387 if (routed) saveRouted();
388 else if (credential) void changeKey(provider, credential);
389 };
390 const keyFooter =
391 draft && !credential
392 ? (source?.invalidReferenceMessage ?? gt("Enter a valid API key."))
393 : routed
394 ? key && !credential
395 ? gt(
396 "Uses the API key saved on this environment. The model choice applies only to this device.",
397 )
398 : gt("Anyone with dictation access to {environment} can bill this key.", {
399 environment: environment.label,
400 })
401 : editing.enable
402 ? gt("Anyone with dictation access to {environment} can bill this key.", {
403 environment: environment.label,
404 })
405 : gt(
406 "Updates the {company} key on {environment}. Your dictation destination stays the same.",
407 { company, environment: environment.label },
408 );
409 return (
410 <>
411 <Text className="px-2 text-sm text-foreground-muted">{disclosure}</Text>
412 {routed ? (
413 catalog ? (
414 <ModelPicker
415 models={catalog}
416 value={model}
417 current={activeModel}
418 disabled={saving}
419 onChange={setModel}
420 />
421 ) : (
422 <ListSection title={gt("Model")}>
423 <ListActionRow
424 label={
425 AsyncResult.isFailure(models)
426 ? gt("Could not load models · Retry")
427 : gt("Loading transcription models…")
428 }
429 disabled={!AsyncResult.isFailure(models)}
430 onPress={reloadModels}
431 />
432 </ListSection>
433 )
434 ) : null}
435 {canManage ? (
436 <ListSection title={gt("API key")} footer={keyFooter}>
437 <View className="gap-3 px-4 py-3">
438 {sources.length > 0 && (
439 <View className="flex-row flex-wrap gap-2">
440 <Chip
441 label={gt("Value", { $context: "enter the secret value directly" })}
442 size="small"
443 selected={sourceId === null}
444 disabled={saving}
445 onPress={() => {
446 setDraft("");
447 setSourceId(null);
448 }}
449 />
450 {sources.map((candidate) => (
451 <Chip
452 key={candidate.id}
453 label={candidate.label}
454 size="small"
455 selected={sourceId === candidate.id}
456 disabled={saving}
457 onPress={() => {
458 setDraft("");
459 setSourceId(candidate.id);
460 }}
461 />
462 ))}
463 </View>
464 )}
465 <TextInput
466 key={sourceId ?? "literal"}
467 accessibilityLabel={
468 sourceId
469 ? gt("{provider} API key reference", { provider: label })
470 : gt("{provider} API key", { provider: label })
471 }
472 placeholder={
473 source?.referencePlaceholder ??
474 (key ? gt("Saved key · enter a new one to replace") : gt("API key"))
475 }
476 secureTextEntry={sourceId === null}
477 autoCapitalize="none"
478 autoCorrect={false}
479 autoComplete="off"
480 importantForAutofill="no"
481 maxLength={4096}
482 editable={!saving}
483 returnKeyType="done"
484 onSubmitEditing={submit}
485 value={draft}
486 onChangeText={setDraft}
487 className="rounded-lg bg-background px-3 py-2 text-foreground"
488 />
489 </View>
490 </ListSection>
491 ) : null}
492 {canManage || routed ? (
493 <ListSection>
494 {routed && !key && !canManage ? (
495 <ListActionRow
496 label={gt("Ask an administrator to add an {provider} key", {
497 provider: "OpenRouter",
498 })}
499 disabled
500 onPress={() => {}}
501 />
502 ) : (
503 <ListActionRow
504 label={
505 routed
506 ? isActive
507 ? gt("Save")
508 : gt("Save and enable")
509 : editing.enable
510 ? gt("Save and enable")
511 : gt("Save key")
512 }
513 loading={saving}
514 disabled={routed ? !routedReady : !credential}
515 onPress={submit}
516 />
517 )}
518 {key && canManage ? (
519 <Separated>
520 <ListActionRow
521 tone="danger"
522 label={gt("Remove key from environment")}
523 disabled={saving}
524 onPress={() =>
525 Dialog.confirm({
526 title: gt("Remove the {provider} key from {environment}?", {
527 provider: label,
528 environment: environment.label,
529 }),
530 message: gt("Everyone using it for dictation will lose access."),
531 confirmText: gt("Remove key"),
532 destructive: true,
533 onConfirm: () => void changeKey(provider, null),
534 })
535 }
536 />
537 </Separated>
538 ) : null}
539 </ListSection>
540 ) : null}
541 <ListSection>
542 <ListActionRow label={gt("Back to providers")} disabled={saving} onPress={reset} />
543 </ListSection>
544 </>
545 );
546 })();
547 return (
548 <Sheet
549 title={editing ? CLOUD_SPEECH_LABELS[editing.provider] : gt("Cloud providers")}
550 onClose={onClose}
551 dismissDisabled={saving}
552 >
553 <ScrollView
554 contentInsetAdjustmentBehavior="automatic"
555 keyboardShouldPersistTaps="handled"
556 contentContainerClassName="gap-4 px-5 pt-2 pb-8"
557 >
558 {content}
559 </ScrollView>
560 </Sheet>
561 );