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

CloudVoiceConfiguration.tsx

519 lines18.1 KB

1import { useAtomRefresh, useAtomValue } from "@effect/atom-react";
2import { cloudSpeechDisclosure } from "@t3tools/shared/speechCopy";
3import type { PreparedConnection } from "@t3tools/client-runtime/connection";
4import { hasFeatureFlag } from "@t3tools/client-runtime/state/server";
5import {
6 configuredSecretSources,
7 secretRequestReference,
8} from "@t3tools/client-runtime/secret-request";
9import {
10 getCloudSpeechKeys,
11 getCloudSpeechModels,
12 setCloudSpeechKey,
13} from "@t3tools/client-runtime/voice-input";
14import {
15 AuthOrchestrationOperateScope,
16 AuthProvidersManageScope,
17 AuthSettingsWriteScope,
18 CloudSpeechApiKey,
19 CloudSpeechModelId,
20 CLOUD_SPEECH_LABELS,
21 CLOUD_SPEECH_PROVIDER_NAMES,
22 isSecretReference,
23 type CloudSpeechModel,
24 type CloudSpeechProvider,
25 type SecretProviderId,
26 type SettingsSecretValue,
27 type VoiceTranscriptionDestination,
28} from "@t3tools/contracts";
29import * as Effect from "effect/Effect";
30import * as Option from "effect/Option";
31import * as Schema from "effect/Schema";
32import type { HttpClient } from "effect/http";
33import { Atom, AsyncResult } from "effect/reactivity";
34import { useId, useState } from "react";
35import { T, useGT, useMessages, Var } from "gt-react";
36import {
37 inEnvironmentSpeechRuntime,
38 runEnvironmentSpeech,
39} from "../../speech/runEnvironmentSpeech";
40import {
41 chooseAudioDestination,
42 pendingCloudAudioChoice,
43 useAudioChoice,
44} from "../../speech/voiceConsent";
45import type { EnvironmentPresentation } from "../../state/environments";
46import { useEnvironmentScope, usePreparedConnection } from "../../state/session";
47import { Button } from "../ui/button";
48import {
49 Combobox,
50 ComboboxEmpty,
51 ComboboxInput,
52 ComboboxItem,
53 ComboboxList,
54 ComboboxPopup,
55 useComboboxFilter,
56} from "../ui/combobox";
57import {
58 Dialog,
59 DialogDescription,
60 DialogFooter,
61 DialogHeader,
62 DialogPanel,
63 DialogPopup,
64 DialogTitle,
65} from "../ui/dialog";
66import { Input } from "../ui/input";
67import { Label } from "../ui/label";
68import { SecretInput } from "./SecretInput";
69import { SecretSourceSelect } from "./SecretSourceInput";
70​
71// Per dialog instance, not an Atom.family: key presence must be read fresh each time it opens.
72function useCloudRead<A, E>(
73 prepared: PreparedConnection | null,
74 read: (prepared: PreparedConnection) => Effect.Effect<A, E, HttpClient.HttpClient>,
75) {
76 const make = (connection: PreparedConnection | null) => ({
77 prepared: connection,
78 atom: Atom.make(
79 connection ? inEnvironmentSpeechRuntime(read(connection)) : Effect.succeed(null),
80 ),
81 });
82 const [current, setCurrent] = useState(() => make(prepared));
83 if (current.prepared !== prepared) setCurrent(make(prepared));
84 return [useAtomValue(current.atom), useAtomRefresh(current.atom)] as const;
86const isApiKey = Schema.is(CloudSpeechApiKey);
87const isModelId = Schema.is(CloudSpeechModelId);
88type CloudDestination = Extract<VoiceTranscriptionDestination, { kind: "cloud" }>;
89​
90function ModelPicker({
91 models,
92 value,
93 onChange,
94 disabled,
95 current,
96}: {
97 models: ReadonlyArray<CloudSpeechModel>;
98 value: string;
99 onChange: (next: string) => void;
100 disabled: boolean;
101 /** The grant's model, flagged when the catalog no longer lists it. */
102 current: string | undefined;
103}) {
104 const gt = useGT();
105 const { contains } = useComboboxFilter();
106 const selected = models.find((model) => model.id === value) ?? null;
107 const delisted = current !== undefined && !models.some((model) => model.id === current);
108 return (
109 <div className="grid gap-1">
110 <Combobox
111 items={models}
112 itemToStringLabel={(model: CloudSpeechModel) => model.name}
113 itemToStringValue={(model: CloudSpeechModel) => model.id}
114 filter={(model: CloudSpeechModel, query) =>
115 contains(model.name, query) || contains(model.id, query)
116 }
117 value={selected}
118 onValueChange={(model) => onChange(model?.id ?? "")}
119 autoHighlight
120 disabled={disabled}
121 >
122 <ComboboxInput
123 id="voice-cloud-model"
124 aria-label={gt("OpenRouter model")}
125 placeholder={gt("Search transcription models")}
126 autoFocus
127 size="sm"
128 />
129 <ComboboxPopup>
130 <ComboboxEmpty>
131 <T>No transcription model matches.</T>
132 </ComboboxEmpty>
133 <ComboboxList className="max-h-64">
134 {(model: CloudSpeechModel) => (
135 <ComboboxItem key={model.id} value={model}>
136 <span className="flex min-w-0 flex-col">
137 <span className="truncate">{model.name}</span>
138 <span className="truncate text-xs text-muted-foreground">{model.id}</span>
139 </span>
140 </ComboboxItem>
141 )}
142 </ComboboxList>
143 </ComboboxPopup>
144 </Combobox>
145 {delisted ? (
146 <p className="text-sm text-destructive" role="alert">
147 <T>
148 OpenRouter no longer lists <Var>{current}</Var>. Dictation stays off until you choose
149 another model.
150 </T>
151 </p>
152 ) : selected ? (
153 <p className="truncate text-xs text-muted-foreground">{selected.id}</p>
154 ) : null}
155 </div>
156 );
158​
159export function CloudVoiceConfiguration({
160 environment,
161 provider,
162 active,
163 close,
164}: {
165 environment: Pick<EnvironmentPresentation, "environmentId" | "label" | "serverConfig">;
166 provider: CloudSpeechProvider;
167 active: boolean;
168 close: () => void;
169}) {
170 const gt = useGT();
171 const messages = useMessages();
172 const id = environment.environmentId;
173 const name = CLOUD_SPEECH_LABELS[provider];
174 const company = CLOUD_SPEECH_PROVIDER_NAMES[provider];
175 const routed = provider === "openrouter";
176 const formId = useId();
177 const prepared = Option.getOrNull(usePreparedConnection(id));
178 const canUse = useEnvironmentScope(id, AuthOrchestrationOperateScope);
179 const canManage = useEnvironmentScope(id, AuthSettingsWriteScope);
180 const canUseReferences = useEnvironmentScope(id, AuthProvidersManageScope);
181 const [presence, refresh] = useCloudRead(canUse ? prepared : null, getCloudSpeechKeys);
182 const [models, refreshModels] = useCloudRead(
183 routed && canUse ? prepared : null,
184 getCloudSpeechModels,
185 );
186 const choice = useAudioChoice();
187 const grant = choice === "off" ? null : choice;
188 const currentModel =
189 active && grant?.destination.kind === "cloud" && grant.destination.provider === "openrouter"
190 ? grant.destination.model
191 : undefined;
192 const [remove, setRemove] = useState(false);
193 const [busy, setBusy] = useState(false);
194 const [error, setError] = useState("");
195 const [model, setModel] = useState(currentModel ?? "");
196 const saved = AsyncResult.isSuccess(presence) ? presence.value?.[provider] : undefined;
197 const existing = environment.serverConfig?.settings?.cloudSpeechCredentials?.[provider];
198 const sources =
199 canUseReferences &&
200 hasFeatureFlag(environment.serverConfig, "secretProviders") &&
201 environment.serverConfig?.secretReferences
202 ? configuredSecretSources(environment.serverConfig.settings?.secretProviders ?? {}, messages)
203 : [];
204 const reference =
205 isSecretReference(existing) && sources.some((s) => s.id === existing.provider)
206 ? existing
207 : null;
208 const [sourceId, setSourceId] = useState<SecretProviderId | null>(reference?.provider ?? null);
209 const [draft, setDraft] = useState(reference?.reference ?? "");
210 const source = sources.find((s) => s.id === sourceId);
211 const credential =
212 sourceId !== null
213 ? source && secretRequestReference(source, draft)
214 : isApiKey(draft.trim())
215 ? draft.trim()
216 : undefined;
217 const keyChanged =
218 credential !== undefined &&
219 !(
220 isSecretReference(credential) &&
221 reference?.provider === credential.provider &&
222 reference.reference === credential.reference
223 );
224 const connected = canUse && prepared !== null;
225 // Fixed providers edit the key only when nothing is saved or the device already uses them.
226 const editingKey = canManage && saved !== undefined && (routed || active || !saved);
227 const listedModels = AsyncResult.isSuccess(models) ? (models.value?.models ?? null) : null;
228 const modelChosen = isModelId(model) && (listedModels?.some((m) => m.id === model) ?? false);
229 const keyReady = draft.trim() ? credential !== undefined : Boolean(saved);
230 const modelChanged = model !== (currentModel ?? "");
231 const destination = (): CloudDestination =>
232 routed && isModelId(model)
233 ? { kind: "cloud", provider: "openrouter", environmentId: id, model }
234 : { kind: "cloud", provider: provider as "openai" | "xai", environmentId: id };
235 const enable = () => chooseAudioDestination(destination());
236 const canSubmit = routed
237 ? modelChosen && keyReady && (!active || modelChanged || keyChanged)
238 : credential !== undefined;
239​
240 const saveKey = async (value: SettingsSecretValue | null, thenEnable: boolean) => {
241 if (!connected || !canManage || busy) return;
242 setError("");
243 setBusy(true);
244 try {
245 const commit = thenEnable ? pendingCloudAudioChoice(destination()) : null;
246 await runEnvironmentSpeech(setCloudSpeechKey(prepared, provider, value));
247 refresh();
248 commit?.();
249 close();
250 } catch {
251 setError(gt("Couldn’t save this change. Check your connection and try again."));
252 }
253 setBusy(false);
254 };
255 const submit = () => {
256 if (!canSubmit || busy) return;
257 const grantChanges = !active || modelChanged;
258 if (credential !== undefined && (!routed || keyChanged))
259 return void saveKey(credential, grantChanges);
260 // Model-only changes never write to the environment.
261 if (grantChanges) enable();
262 close();
263 };
264​
265 const keyField = (
266 <>
267 <Label htmlFor="voice-cloud-key">
268 {routed && saved ? gt("Replace API key") : gt("API key")}
269 </Label>
270 <div className="flex min-w-0 items-start gap-2">
271 {sources.length > 0 && (
272 <SecretSourceSelect
273 value={sourceId}
274 sources={sources}
275 label={gt("{company} API key", { company })}
276 disabled={busy}
277 onValueChange={(next) => {
278 setSourceId(next);
279 setDraft("");
280 setError("");
281 }}
282 />
283 )}
284 <div className="min-w-0 flex-1">
285 {sourceId !== null ? (
286 <Input
287 key={sourceId}
288 id="voice-cloud-key"
289 name="reference"
290 aria-label={gt("{company} API key reference", { company })}
291 autoFocus={!routed}
292 placeholder={source?.referencePlaceholder}
293 value={draft}
294 disabled={busy}
295 autoComplete="off"
296 spellCheck={false}
297 onChange={(event) => setDraft(event.target.value)}
298 />
299 ) : (
300 <SecretInput
301 id="voice-cloud-key"
302 name="key"
303 aria-label={gt("{company} API key", { company })}
304 autoFocus={!routed}
305 placeholder={gt("Enter API key")}
306 value={draft}
307 configured={saved === true}
308 disabled={busy}
309 maxLength={4096}
310 onChange={(event) => setDraft(event.target.value)}
311 />
312 )}
313 </div>
314 </div>
315 <p className="text-sm text-muted-foreground">
316 {draft.trim() && !credential
317 ? (source?.invalidReferenceMessage ??
318 gt("Enter an API key, not a URL or secret reference."))
319 : active && !routed
320 ? gt("Updating the key keeps dictation enabled.")
321 : routed && saved
322 ? gt("Leave blank to keep the saved key.")
323 : gt("Anyone with dictation access to {environment} can bill this key.", {
324 environment: environment.label,
325 })}
326 </p>
327 </>
328 );
329​
330 return (
331 <Dialog
332 open
333 onOpenChange={(open) => {
334 if (!open && !busy) close();
335 }}
336 >
337 <DialogPopup className="max-w-md" showCloseButton={!busy}>
338 <DialogHeader>
339 <DialogTitle>
340 {remove
341 ? gt("Remove the {company} key?", { company })
342 : active
343 ? routed
344 ? gt("Manage OpenRouter dictation")
345 : gt("Manage {company} key", { company })
346 : gt("Use {name} for dictation?", { name })}
347 </DialogTitle>
348 <DialogDescription>
349 {remove
350 ? gt("Everyone using {name} for dictation on {environment} will lose access.", {
351 name,
352 environment: environment.label,
353 })
354 : active && !routed
355 ? gt("Anyone with dictation access to {environment} can use this API key.", {
356 environment: environment.label,
357 })
358 : cloudSpeechDisclosure(provider, environment.label, messages)}
359 </DialogDescription>
360 </DialogHeader>
361 {!remove && (
362 <DialogPanel>
363 {!connected ? (
364 <p>
365 <T>
366 Connect to <Var>{environment.label}</Var> with dictation access to continue.
367 </T>
368 </p>
369 ) : AsyncResult.isFailure(presence) && saved === undefined ? (
370 <Button size="sm" variant="outline" onClick={refresh}>
371 <T>Retry loading API key</T>
372 </Button>
373 ) : routed &&
374 AsyncResult.isSuccess(presence) &&
375 presence.value &&
376 saved === undefined ? (
377 <p>
378 <T>
379 Update <Var>{environment.label}</Var> to use OpenRouter dictation.
380 </T>
381 </p>
382 ) : saved === undefined ? (
383 <p role="status">
384 <T>Checking for an API key…</T>
385 </p>
386 ) : routed ? (
387 <form
388 id={formId}
389 className="grid gap-3"
390 onSubmit={(event) => {
391 event.preventDefault();
392 submit();
393 }}
394 >
395 <div className="grid gap-2">
396 <Label htmlFor="voice-cloud-model">
397 <T>Model</T>
398 </Label>
399 {listedModels ? (
400 <ModelPicker
401 models={listedModels}
402 value={model}
403 onChange={setModel}
404 disabled={busy}
405 current={currentModel}
406 />
407 ) : AsyncResult.isFailure(models) ? (
408 <Button size="sm" variant="outline" type="button" onClick={refreshModels}>
409 <T>Retry loading models</T>
410 </Button>
411 ) : (
412 <p role="status" className="text-sm text-muted-foreground">
413 <T>Loading transcription models…</T>
414 </p>
415 )}
416 </div>
417 {editingKey ? (
418 <div className="grid gap-2">{keyField}</div>
419 ) : !saved ? (
420 <p>
421 <T>
422 Ask an administrator on <Var>{environment.label}</Var> to add an API key.
423 </T>
424 </p>
425 ) : (
426 <p className="text-sm text-muted-foreground">
427 <T>
428 Uses the API key saved on <Var>{environment.label}</Var>. This choice applies
429 only to this device.
430 </T>
431 </p>
432 )}
433 </form>
434 ) : editingKey ? (
435 <form
436 id={formId}
437 className="grid gap-2"
438 onSubmit={(event) => {
439 event.preventDefault();
440 submit();
441 }}
442 >
443 {keyField}
444 </form>
445 ) : !saved ? (
446 <p>
447 <T>
448 Ask an administrator on <Var>{environment.label}</Var> to add an API key.
449 </T>
450 </p>
451 ) : (
452 <p className="text-sm text-muted-foreground">
453 <T>This choice applies only to this device. Choose Off to stop sharing.</T>
454 </p>
455 )}
456 </DialogPanel>
457 )}
458 {error && (
459 <p className="px-6 text-sm text-destructive" role="alert">
460 {error}
461 </p>
462 )}
463 <DialogFooter>
464 {connected && canManage && saved && (active || routed) && !remove && (
465 <div className="sm:mr-auto">
466 <Button
467 type="button"
468 size="sm"
469 variant="ghost"
470 disabled={busy}
471 onClick={() => setRemove(true)}
472 >
473 <T>Remove key…</T>
474 </Button>
475 </div>
476 )}
477 <Button type="button" size="sm" variant="outline" disabled={busy} onClick={close}>
478 <T>Cancel</T>
479 </Button>
480 {connected &&
481 (remove ? (
482 <Button
483 type="button"
484 size="sm"
485 variant="destructive"
486 disabled={busy}
487 onClick={() => void saveKey(null, false)}
488 >
489 <T>Remove key</T>
490 </Button>
491 ) : routed ? (
492 saved !== undefined && (saved || canManage) ? (
493 <Button type="submit" form={formId} size="sm" disabled={busy || !canSubmit}>
494 {active ? gt("Save", { $context: "verb" }) : gt("Save and enable")}
495 </Button>
496 ) : null
497 ) : editingKey ? (
498 <Button type="submit" form={formId} size="sm" disabled={busy || !credential}>
499 {active ? gt("Save key") : gt("Save and enable")}
500 </Button>
501 ) : saved && !active ? (
502 <Button
503 type="button"
504 size="sm"
505 onClick={() => {
506 enable();
507 close();
508 }}
509 >
510 <T>
511 Use <Var>{name}</Var>
512 </T>
513 </Button>
514 ) : null)}
515 </DialogFooter>
516 </DialogPopup>
517 </Dialog>
518 );