The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { useAtomRefresh, useAtomValue } from "@effect/atom-react"; |
| 2 | import { cloudSpeechDisclosure } from "@t3tools/shared/speechCopy"; |
| 3 | import type { PreparedConnection } from "@t3tools/client-runtime/connection"; |
| 4 | import { |
| 5 | configuredSecretSources, |
| 6 | secretRequestReference, |
| 7 | } from "@t3tools/client-runtime/secret-request"; |
| 8 | import { |
| 9 | getCloudSpeechKeys, |
| 10 | getCloudSpeechModels, |
| 11 | setCloudSpeechKey, |
| 12 | } from "@t3tools/client-runtime/voice-input"; |
| 13 | import { |
| 14 | AuthOrchestrationOperateScope, |
| 15 | AuthSettingsWriteScope, |
| 16 | CloudSpeechApiKey, |
| 17 | CloudSpeechModelId, |
| 18 | CLOUD_SPEECH_LABELS, |
| 19 | CLOUD_SPEECH_PROVIDER_NAMES, |
| 20 | isSecretReference, |
| 21 | type CloudSpeechModel, |
| 22 | type CloudSpeechProvider, |
| 23 | type SecretProviderId, |
| 24 | type SettingsSecretValue, |
| 25 | type VoiceTranscriptionDestination, |
| 26 | } from "@t3tools/contracts"; |
| 27 | import * as Effect from "effect/Effect"; |
| 28 | import * as Option from "effect/Option"; |
| 29 | import * as Schema from "effect/Schema"; |
| 30 | import type { HttpClient } from "effect/http"; |
| 31 | import { Atom, AsyncResult } from "effect/reactivity"; |
| 32 | import { useId, useState } from "react"; |
| 33 | import { T, useGT, useMessages, Var } from "gt-react"; |
| 34 | import { isSecretsFeatureEnabled } from "../../env"; |
| 35 | import { |
| 36 | inEnvironmentSpeechRuntime, |
| 37 | runEnvironmentSpeech, |
| 38 | } from "../../speech/runEnvironmentSpeech"; |
| 39 | import { |
| 40 | chooseAudioDestination, |
| 41 | pendingCloudAudioChoice, |
| 42 | useAudioChoice, |
| 43 | } from "../../speech/voiceConsent"; |
| 44 | import type { EnvironmentPresentation } from "../../state/environments"; |
| 45 | import { useEnvironmentScope, usePreparedConnection } from "../../state/session"; |
| 46 | import { Button } from "../ui/button"; |
| 47 | import { |
| 48 | Combobox, |
| 49 | ComboboxEmpty, |
| 50 | ComboboxInput, |
| 51 | ComboboxItem, |
| 52 | ComboboxList, |
| 53 | ComboboxPopup, |
| 54 | useComboboxFilter, |
| 55 | } from "../ui/combobox"; |
| 56 | import { |
| 57 | Dialog, |
| 58 | DialogDescription, |
| 59 | DialogFooter, |
| 60 | DialogHeader, |
| 61 | DialogPanel, |
| 62 | DialogPopup, |
| 63 | DialogTitle, |
| 64 | } from "../ui/dialog"; |
| 65 | import { Input } from "../ui/input"; |
| 66 | import { Label } from "../ui/label"; |
| 67 | import { SecretInput } from "./SecretInput"; |
| 68 | import { SecretSourceSelect } from "./SecretSourceInput"; |
| 69 | |
| 70 | // Per dialog instance, not an Atom.family: key presence must be read fresh each time it opens. |
| 71 | function 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; |
| 84 | } |
| 85 | const isApiKey = Schema.is(CloudSpeechApiKey); |
| 86 | const isModelId = Schema.is(CloudSpeechModelId); |
| 87 | type CloudDestination = Extract<VoiceTranscriptionDestination, { kind: "cloud" }>; |
| 88 | |
| 89 | function 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 | ); |
| 156 | } |
| 157 | |
| 158 | export 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 | isSecretsFeatureEnabled && environment.serverConfig?.secretReferences |
| 198 | ? configuredSecretSources(environment.serverConfig.settings?.secretProviders ?? {}, messages) |
| 199 | : []; |
| 200 | const reference = |
| 201 | isSecretReference(existing) && sources.some((s) => s.id === existing.provider) |
| 202 | ? existing |
| 203 | : null; |
| 204 | const [sourceId, setSourceId] = useState<SecretProviderId | null>(reference?.provider ?? null); |
| 205 | const [draft, setDraft] = useState(reference?.reference ?? ""); |
| 206 | const source = sources.find((s) => s.id === sourceId); |
| 207 | const credential = |
| 208 | sourceId !== null |
| 209 | ? source && secretRequestReference(source, draft) |
| 210 | : isApiKey(draft.trim()) |
| 211 | ? draft.trim() |
| 212 | : undefined; |
| 213 | const keyChanged = |
| 214 | credential !== undefined && |
| 215 | !( |
| 216 | isSecretReference(credential) && |
| 217 | reference?.provider === credential.provider && |
| 218 | reference.reference === credential.reference |
| 219 | ); |
| 220 | const connected = canUse && prepared !== null; |
| 221 | // Fixed providers edit the key only when nothing is saved or the device already uses them. |
| 222 | const editingKey = canManage && saved !== undefined && (routed || active || !saved); |
| 223 | const listedModels = AsyncResult.isSuccess(models) ? (models.value?.models ?? null) : null; |
| 224 | const modelChosen = isModelId(model) && (listedModels?.some((m) => m.id === model) ?? false); |
| 225 | const keyReady = draft.trim() ? credential !== undefined : Boolean(saved); |
| 226 | const modelChanged = model !== (currentModel ?? ""); |
| 227 | const destination = (): CloudDestination => |
| 228 | routed && isModelId(model) |
| 229 | ? { kind: "cloud", provider: "openrouter", environmentId: id, model } |
| 230 | : { kind: "cloud", provider: provider as "openai" | "xai", environmentId: id }; |
| 231 | const enable = () => chooseAudioDestination(destination()); |
| 232 | const canSubmit = routed |
| 233 | ? modelChosen && keyReady && (!active || modelChanged || keyChanged) |
| 234 | : credential !== undefined; |
| 235 | |
| 236 | const saveKey = async (value: SettingsSecretValue | null, thenEnable: boolean) => { |
| 237 | if (!connected || !canManage || busy) return; |
| 238 | setError(""); |
| 239 | setBusy(true); |
| 240 | try { |
| 241 | const commit = thenEnable ? pendingCloudAudioChoice(destination()) : null; |
| 242 | await runEnvironmentSpeech(setCloudSpeechKey(prepared, provider, value)); |
| 243 | refresh(); |
| 244 | commit?.(); |
| 245 | close(); |
| 246 | } catch { |
| 247 | setError(gt("Couldn’t save this change. Check your connection and try again.")); |
| 248 | } |
| 249 | setBusy(false); |
| 250 | }; |
| 251 | const submit = () => { |
| 252 | if (!canSubmit || busy) return; |
| 253 | const grantChanges = !active || modelChanged; |
| 254 | if (credential !== undefined && (!routed || keyChanged)) |
| 255 | return void saveKey(credential, grantChanges); |
| 256 | // Model-only changes never write to the environment. |
| 257 | if (grantChanges) enable(); |
| 258 | close(); |
| 259 | }; |
| 260 | |
| 261 | const keyField = ( |
| 262 | <> |
| 263 | <Label htmlFor="voice-cloud-key"> |
| 264 | {routed && saved ? gt("Replace API key") : gt("API key")} |
| 265 | </Label> |
| 266 | <div className="flex min-w-0 items-start gap-2"> |
| 267 | {sources.length > 0 && ( |
| 268 | <SecretSourceSelect |
| 269 | value={sourceId} |
| 270 | sources={sources} |
| 271 | label={gt("{company} API key", { company })} |
| 272 | disabled={busy} |
| 273 | onValueChange={(next) => { |
| 274 | setSourceId(next); |
| 275 | setDraft(""); |
| 276 | setError(""); |
| 277 | }} |
| 278 | /> |
| 279 | )} |
| 280 | <div className="min-w-0 flex-1"> |
| 281 | {sourceId !== null ? ( |
| 282 | <Input |
| 283 | key={sourceId} |
| 284 | id="voice-cloud-key" |
| 285 | name="reference" |
| 286 | aria-label={gt("{company} API key reference", { company })} |
| 287 | autoFocus={!routed} |
| 288 | placeholder={source?.referencePlaceholder} |
| 289 | value={draft} |
| 290 | disabled={busy} |
| 291 | autoComplete="off" |
| 292 | spellCheck={false} |
| 293 | onChange={(event) => setDraft(event.target.value)} |
| 294 | /> |
| 295 | ) : ( |
| 296 | <SecretInput |
| 297 | id="voice-cloud-key" |
| 298 | name="key" |
| 299 | aria-label={gt("{company} API key", { company })} |
| 300 | autoFocus={!routed} |
| 301 | placeholder={gt("Enter API key")} |
| 302 | value={draft} |
| 303 | configured={saved === true} |
| 304 | disabled={busy} |
| 305 | maxLength={4096} |
| 306 | onChange={(event) => setDraft(event.target.value)} |
| 307 | /> |
| 308 | )} |
| 309 | </div> |
| 310 | </div> |
| 311 | <p className="text-sm text-muted-foreground"> |
| 312 | {draft.trim() && !credential |
| 313 | ? (source?.invalidReferenceMessage ?? |
| 314 | gt("Enter an API key, not a URL or secret reference.")) |
| 315 | : active && !routed |
| 316 | ? gt("Updating the key keeps dictation enabled.") |
| 317 | : routed && saved |
| 318 | ? gt("Leave blank to keep the saved key.") |
| 319 | : gt("Anyone with dictation access to {environment} can bill this key.", { |
| 320 | environment: environment.label, |
| 321 | })} |
| 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?", { company }) |
| 338 | : active |
| 339 | ? routed |
| 340 | ? gt("Manage OpenRouter dictation") |
| 341 | : gt("Manage {company} key", { company }) |
| 342 | : gt("Use {name} for dictation?", { name })} |
| 343 | </DialogTitle> |
| 344 | <DialogDescription> |
| 345 | {remove |
| 346 | ? gt("Everyone using {name} for dictation on {environment} will lose access.", { |
| 347 | name, |
| 348 | environment: environment.label, |
| 349 | }) |
| 350 | : active && !routed |
| 351 | ? gt("Anyone with dictation access to {environment} can use this API key.", { |
| 352 | environment: environment.label, |
| 353 | }) |
| 354 | : cloudSpeechDisclosure(provider, environment.label, messages)} |
| 355 | </DialogDescription> |
| 356 | </DialogHeader> |
| 357 | {!remove && ( |
| 358 | <DialogPanel> |
| 359 | {!connected ? ( |
| 360 | <p> |
| 361 | <T> |
| 362 | Connect to <Var>{environment.label}</Var> with dictation access to continue. |
| 363 | </T> |
| 364 | </p> |
| 365 | ) : AsyncResult.isFailure(presence) && saved === undefined ? ( |
| 366 | <Button size="sm" variant="outline" onClick={refresh}> |
| 367 | <T>Retry loading API key</T> |
| 368 | </Button> |
| 369 | ) : routed && |
| 370 | AsyncResult.isSuccess(presence) && |
| 371 | presence.value && |
| 372 | saved === undefined ? ( |
| 373 | <p> |
| 374 | <T> |
| 375 | Update <Var>{environment.label}</Var> to use OpenRouter dictation. |
| 376 | </T> |
| 377 | </p> |
| 378 | ) : saved === undefined ? ( |
| 379 | <p role="status"> |
| 380 | <T>Checking for an API key…</T> |
| 381 | </p> |
| 382 | ) : routed ? ( |
| 383 | <form |
| 384 | id={formId} |
| 385 | className="grid gap-3" |
| 386 | onSubmit={(event) => { |
| 387 | event.preventDefault(); |
| 388 | submit(); |
| 389 | }} |
| 390 | > |
| 391 | <div className="grid gap-2"> |
| 392 | <Label htmlFor="voice-cloud-model"> |
| 393 | <T>Model</T> |
| 394 | </Label> |
| 395 | {listedModels ? ( |
| 396 | <ModelPicker |
| 397 | models={listedModels} |
| 398 | value={model} |
| 399 | onChange={setModel} |
| 400 | disabled={busy} |
| 401 | current={currentModel} |
| 402 | /> |
| 403 | ) : AsyncResult.isFailure(models) ? ( |
| 404 | <Button size="sm" variant="outline" type="button" onClick={refreshModels}> |
| 405 | <T>Retry loading models</T> |
| 406 | </Button> |
| 407 | ) : ( |
| 408 | <p role="status" className="text-sm text-muted-foreground"> |
| 409 | <T>Loading transcription models…</T> |
| 410 | </p> |
| 411 | )} |
| 412 | </div> |
| 413 | {editingKey ? ( |
| 414 | <div className="grid gap-2">{keyField}</div> |
| 415 | ) : !saved ? ( |
| 416 | <p> |
| 417 | <T> |
| 418 | Ask an administrator on <Var>{environment.label}</Var> to add an API key. |
| 419 | </T> |
| 420 | </p> |
| 421 | ) : ( |
| 422 | <p className="text-sm text-muted-foreground"> |
| 423 | <T> |
| 424 | Uses the API key saved on <Var>{environment.label}</Var>. This choice applies |
| 425 | only to this device. |
| 426 | </T> |
| 427 | </p> |
| 428 | )} |
| 429 | </form> |
| 430 | ) : editingKey ? ( |
| 431 | <form |
| 432 | id={formId} |
| 433 | className="grid gap-2" |
| 434 | onSubmit={(event) => { |
| 435 | event.preventDefault(); |
| 436 | submit(); |
| 437 | }} |
| 438 | > |
| 439 | {keyField} |
| 440 | </form> |
| 441 | ) : !saved ? ( |
| 442 | <p> |
| 443 | <T> |
| 444 | Ask an administrator on <Var>{environment.label}</Var> to add an API key. |
| 445 | </T> |
| 446 | </p> |
| 447 | ) : ( |
| 448 | <p className="text-sm text-muted-foreground"> |
| 449 | <T>This choice applies only to this device. Choose Off to stop sharing.</T> |
| 450 | </p> |
| 451 | )} |
| 452 | </DialogPanel> |
| 453 | )} |
| 454 | {error && ( |
| 455 | <p className="px-6 text-sm text-destructive" role="alert"> |
| 456 | {error} |
| 457 | </p> |
| 458 | )} |
| 459 | <DialogFooter> |
| 460 | {connected && canManage && saved && (active || routed) && !remove && ( |
| 461 | <div className="sm:mr-auto"> |
| 462 | <Button |
| 463 | type="button" |
| 464 | size="sm" |
| 465 | variant="ghost" |
| 466 | disabled={busy} |
| 467 | onClick={() => setRemove(true)} |
| 468 | > |
| 469 | <T>Remove key…</T> |
| 470 | </Button> |
| 471 | </div> |
| 472 | )} |
| 473 | <Button type="button" size="sm" variant="outline" disabled={busy} onClick={close}> |
| 474 | <T>Cancel</T> |
| 475 | </Button> |
| 476 | {connected && |
| 477 | (remove ? ( |
| 478 | <Button |
| 479 | type="button" |
| 480 | size="sm" |
| 481 | variant="destructive" |
| 482 | disabled={busy} |
| 483 | onClick={() => void saveKey(null, false)} |
| 484 | > |
| 485 | <T>Remove key</T> |
| 486 | </Button> |
| 487 | ) : routed ? ( |
| 488 | saved !== undefined && (saved || canManage) ? ( |
| 489 | <Button type="submit" form={formId} size="sm" disabled={busy || !canSubmit}> |
| 490 | {active ? gt("Save", { $context: "verb" }) : gt("Save and enable")} |
| 491 | </Button> |
| 492 | ) : null |
| 493 | ) : editingKey ? ( |
| 494 | <Button type="submit" form={formId} size="sm" disabled={busy || !credential}> |
| 495 | {active ? gt("Save key") : gt("Save and enable")} |
| 496 | </Button> |
| 497 | ) : saved && !active ? ( |
| 498 | <Button |
| 499 | type="button" |
| 500 | size="sm" |
| 501 | onClick={() => { |
| 502 | enable(); |
| 503 | close(); |
| 504 | }} |
| 505 | > |
| 506 | <T> |
| 507 | Use <Var>{name}</Var> |
| 508 | </T> |
| 509 | </Button> |
| 510 | ) : null)} |
| 511 | </DialogFooter> |
| 512 | </DialogPopup> |
| 513 | </Dialog> |
| 514 | ); |
| 515 | } |