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

CloudVoiceConfiguration.tsx

510 lines17.9 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 scrollAreaClassName="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">{routed && saved ? gt`Replace API key` : gt`API key`}</Label>
268 <div className="flex min-w-0 items-start gap-2">
269 {sources.length > 0 && (
270 <SecretSourceSelect
271 value={sourceId}
272 sources={sources}
273 label={gt`${{ company }} API key`}
274 disabled={busy}
275 onValueChange={(next) => {
276 setSourceId(next);
277 setDraft("");
278 setError("");
279 }}
280 />
281 )}
282 <div className="min-w-0 flex-1">
283 {sourceId !== null ? (
284 <Input
285 key={sourceId}
286 id="voice-cloud-key"
287 name="reference"
288 aria-label={gt`${{ company }} API key reference`}
289 autoFocus={!routed}
290 placeholder={source?.referencePlaceholder}
291 value={draft}
292 disabled={busy}
293 autoComplete="off"
294 spellCheck={false}
295 onChange={(event) => setDraft(event.target.value)}
296 />
297 ) : (
298 <SecretInput
299 id="voice-cloud-key"
300 name="key"
301 aria-label={gt`${{ company }} API key`}
302 autoFocus={!routed}
303 placeholder={gt`Enter API key`}
304 value={draft}
305 configured={saved === true}
306 disabled={busy}
307 maxLength={4096}
308 onChange={(event) => setDraft(event.target.value)}
309 />
310 )}
311 </div>
312 </div>
313 <p className="text-sm text-muted-foreground">
314 {draft.trim() && !credential
315 ? (source?.invalidReferenceMessage ??
316 gt`Enter an API key, not a URL or secret reference.`)
317 : active && !routed
318 ? gt`Updating the key keeps dictation enabled.`
319 : routed && saved
320 ? gt`Leave blank to keep the saved key.`
321 : gt`Anyone with dictation access to ${{ environment: environment.label }} can bill this key.`}
322 </p>
323 </>
324 );
325​
326 return (
327 <Dialog
328 open
329 onOpenChange={(open) => {
330 if (!open && !busy) close();
331 }}
332 >
333 <DialogPopup className="max-w-md" showCloseButton={!busy}>
334 <DialogHeader>
335 <DialogTitle>
336 {remove
337 ? gt`Remove the ${{ company }} key?`
338 : active
339 ? routed
340 ? gt`Manage OpenRouter dictation`
341 : gt`Manage ${{ company }} key`
342 : gt`Use ${{ name }} for dictation?`}
343 </DialogTitle>
344 <DialogDescription>
345 {remove
346 ? gt`Everyone using ${{ name }} for dictation on ${{ environment: environment.label }} will lose access.`
347 : active && !routed
348 ? gt`Anyone with dictation access to ${{ environment: environment.label }} can use this API key.`
349 : cloudSpeechDisclosure(provider, environment.label, messages)}
350 </DialogDescription>
351 </DialogHeader>
352 {!remove && (
353 <DialogPanel>
354 {!connected ? (
355 <p>
356 <T>
357 Connect to <Var>{environment.label}</Var> with dictation access to continue.
358 </T>
359 </p>
360 ) : AsyncResult.isFailure(presence) && saved === undefined ? (
361 <Button size="sm" variant="outline" onClick={refresh}>
362 <T>Retry loading API key</T>
363 </Button>
364 ) : routed &&
365 AsyncResult.isSuccess(presence) &&
366 presence.value &&
367 saved === undefined ? (
368 <p>
369 <T>
370 Update <Var>{environment.label}</Var> to use OpenRouter dictation.
371 </T>
372 </p>
373 ) : saved === undefined ? (
374 <p role="status">
375 <T>Checking for an API key…</T>
376 </p>
377 ) : routed ? (
378 <form
379 id={formId}
380 className="grid gap-3"
381 onSubmit={(event) => {
382 event.preventDefault();
383 submit();
384 }}
385 >
386 <div className="grid gap-2">
387 <Label htmlFor="voice-cloud-model">
388 <T>Model</T>
389 </Label>
390 {listedModels ? (
391 <ModelPicker
392 models={listedModels}
393 value={model}
394 onChange={setModel}
395 disabled={busy}
396 current={currentModel}
397 />
398 ) : AsyncResult.isFailure(models) ? (
399 <Button size="sm" variant="outline" type="button" onClick={refreshModels}>
400 <T>Retry loading models</T>
401 </Button>
402 ) : (
403 <p role="status" className="text-sm text-muted-foreground">
404 <T>Loading transcription models…</T>
405 </p>
406 )}
407 </div>
408 {editingKey ? (
409 <div className="grid gap-2">{keyField}</div>
410 ) : !saved ? (
411 <p>
412 <T>
413 Ask an administrator on <Var>{environment.label}</Var> to add an API key.
414 </T>
415 </p>
416 ) : (
417 <p className="text-sm text-muted-foreground">
418 <T>
419 Uses the API key saved on <Var>{environment.label}</Var>. This choice applies
420 only to this device.
421 </T>
422 </p>
423 )}
424 </form>
425 ) : editingKey ? (
426 <form
427 id={formId}
428 className="grid gap-2"
429 onSubmit={(event) => {
430 event.preventDefault();
431 submit();
432 }}
433 >
434 {keyField}
435 </form>
436 ) : !saved ? (
437 <p>
438 <T>
439 Ask an administrator on <Var>{environment.label}</Var> to add an API key.
440 </T>
441 </p>
442 ) : (
443 <p className="text-sm text-muted-foreground">
444 <T>This choice applies only to this device. Choose Off to stop sharing.</T>
445 </p>
446 )}
447 </DialogPanel>
448 )}
449 {error && (
450 <p className="px-6 text-sm text-destructive" role="alert">
451 {error}
452 </p>
453 )}
454 <DialogFooter>
455 {connected && canManage && saved && (active || routed) && !remove && (
456 <div className="sm:mr-auto">
457 <Button
458 type="button"
459 size="sm"
460 variant="ghost"
461 disabled={busy}
462 onClick={() => setRemove(true)}
463 >
464 <T>Remove key…</T>
465 </Button>
466 </div>
467 )}
468 <Button type="button" size="sm" variant="outline" disabled={busy} onClick={close}>
469 <T>Cancel</T>
470 </Button>
471 {connected &&
472 (remove ? (
473 <Button
474 type="button"
475 size="sm"
476 variant="destructive"
477 disabled={busy}
478 onClick={() => void saveKey(null, false)}
479 >
480 <T>Remove key</T>
481 </Button>
482 ) : routed ? (
483 saved !== undefined && (saved || canManage) ? (
484 <Button type="submit" form={formId} size="sm" disabled={busy || !canSubmit}>
485 {active ? gt({ context: "verb" })`Save` : gt`Save and enable`}
486 </Button>
487 ) : null
488 ) : editingKey ? (
489 <Button type="submit" form={formId} size="sm" disabled={busy || !credential}>
490 {active ? gt`Save key` : gt`Save and enable`}
491 </Button>
492 ) : saved && !active ? (
493 <Button
494 type="button"
495 size="sm"
496 onClick={() => {
497 enable();
498 close();
499 }}
500 >
501 <T>
502 Use <Var>{name}</Var>
503 </T>
504 </Button>
505 ) : null)}
506 </DialogFooter>
507 </DialogPopup>
508 </Dialog>
509 );