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

CloudVoiceConfiguration.tsx

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