The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { T, useGT, useMessages } from "gt-react-native"; |
| 2 | import { useAtomRefresh, useAtomValue } from "@effect/atom-react"; |
| 3 | import { cloudSpeechDisclosure } from "@t3tools/shared/speechCopy"; |
| 4 | import { setCloudSpeechKey } from "@t3tools/client-runtime/voice-input"; |
| 5 | import { |
| 6 | configuredSecretSources, |
| 7 | secretRequestReference, |
| 8 | } from "@t3tools/client-runtime/secret-request"; |
| 9 | import { |
| 10 | AuthSettingsWriteScope, |
| 11 | CLOUD_SPEECH_LABELS, |
| 12 | CLOUD_SPEECH_PROVIDER_NAMES, |
| 13 | CloudSpeechProvider, |
| 14 | CloudSpeechApiKey, |
| 15 | CloudSpeechModelId, |
| 16 | isSecretReference, |
| 17 | type CloudSpeechModel, |
| 18 | type SecretProviderId, |
| 19 | type SettingsSecretValue, |
| 20 | type VoiceTranscriptionDestination, |
| 21 | } from "@t3tools/contracts"; |
| 22 | import * as Schema from "effect/Schema"; |
| 23 | import Constants from "expo-constants"; |
| 24 | import { AsyncResult } from "effect/reactivity"; |
| 25 | import { type ReactNode, useState } from "react"; |
| 26 | import { ScrollView, TextInput, View } from "react-native"; |
| 27 | import { Sheet } from "../../components/ui/Sheet"; |
| 28 | import * as Dialog from "../../components/ui/Dialog"; |
| 29 | import { ProviderIcon } from "../../components/ProviderIcon"; |
| 30 | import { AppText as Text } from "../../components/ui/AppText"; |
| 31 | import { ListActionRow } from "../../components/ui/ListActionRow"; |
| 32 | import { ListChoiceRow } from "../../components/ui/ListChoiceRow"; |
| 33 | import { Chip } from "../../components/ui/Chip"; |
| 34 | import { ListSection } from "../../components/ui/ListSection"; |
| 35 | import type { EnvironmentPresentation } from "../../state/environments"; |
| 36 | import { useEnvironmentScope } from "../../state/session"; |
| 37 | import { |
| 38 | chooseVoiceDestination, |
| 39 | pendingCloudVoiceChoice, |
| 40 | cloudVoiceConnectionAtom, |
| 41 | cloudVoiceKeysAtom, |
| 42 | cloudVoiceModelsAtom, |
| 43 | runSpeech, |
| 44 | } from "../voice-input/voiceDestination"; |
| 45 | |
| 46 | type CloudDestination = Extract<VoiceTranscriptionDestination, { kind: "cloud" }>; |
| 47 | type Props = { environment: EnvironmentPresentation; active: CloudDestination | null }; |
| 48 | const isApiKey = Schema.is(CloudSpeechApiKey); |
| 49 | const isModelId = Schema.is(CloudSpeechModelId); |
| 50 | const MODEL_ROWS = 6; |
| 51 | |
| 52 | /** The cloud method row for one environment; opens the provider sheet. */ |
| 53 | export function CloudVoiceChoice({ |
| 54 | environment, |
| 55 | active, |
| 56 | open, |
| 57 | onOpenChange, |
| 58 | }: Props & { open: boolean; onOpenChange: (open: boolean) => void }) { |
| 59 | const gt = useGT(); |
| 60 | const usable = useAtomValue(cloudVoiceConnectionAtom(environment.environmentId)) !== null; |
| 61 | return ( |
| 62 | <> |
| 63 | <ListChoiceRow |
| 64 | label={gt("Cloud provider")} |
| 65 | description={ |
| 66 | active |
| 67 | ? `${CLOUD_SPEECH_LABELS[active.provider]}${active.provider === "openrouter" ? ` · ${active.model}` : ""}` |
| 68 | : usable |
| 69 | ? gt("Use your own API key") |
| 70 | : gt("Not connected") |
| 71 | } |
| 72 | selected={active !== null} |
| 73 | disabled={!usable} |
| 74 | separated |
| 75 | onPress={() => onOpenChange(true)} |
| 76 | /> |
| 77 | {open && ( |
| 78 | <CloudChoices |
| 79 | environment={environment} |
| 80 | active={active} |
| 81 | onClose={() => onOpenChange(false)} |
| 82 | /> |
| 83 | )} |
| 84 | </> |
| 85 | ); |
| 86 | } |
| 87 | |
| 88 | function ModelPicker({ |
| 89 | models, |
| 90 | value, |
| 91 | current, |
| 92 | disabled, |
| 93 | onChange, |
| 94 | }: { |
| 95 | models: ReadonlyArray<CloudSpeechModel>; |
| 96 | value: string; |
| 97 | /** The grant's model, flagged when the catalog no longer lists it. */ |
| 98 | current: string | undefined; |
| 99 | disabled: boolean; |
| 100 | onChange: (model: CloudSpeechModelId) => void; |
| 101 | }) { |
| 102 | const gt = useGT(); |
| 103 | const [query, setQuery] = useState(""); |
| 104 | const [showAll, setShowAll] = useState(false); |
| 105 | const needle = query.trim().toLowerCase(); |
| 106 | const selected = models.find((model) => model.id === value); |
| 107 | const matches = models.filter((model) => |
| 108 | `${model.name} ${model.id}`.toLowerCase().includes(needle), |
| 109 | ); |
| 110 | const shown = showAll ? matches : matches.slice(0, MODEL_ROWS); |
| 111 | const delisted = current !== undefined && !models.some((model) => model.id === current); |
| 112 | return ( |
| 113 | <ListSection |
| 114 | title={gt("Model")} |
| 115 | footer={ |
| 116 | delisted |
| 117 | ? gt( |
| 118 | "{provider} no longer lists {model}. Dictation stays off until you choose another model.", |
| 119 | { provider: "OpenRouter", model: current }, |
| 120 | ) |
| 121 | : undefined |
| 122 | } |
| 123 | > |
| 124 | <View className="px-4 py-3"> |
| 125 | <TextInput |
| 126 | accessibilityLabel={gt("Search {provider} models", { provider: "OpenRouter" })} |
| 127 | placeholder={gt("Search transcription models")} |
| 128 | autoCapitalize="none" |
| 129 | autoCorrect={false} |
| 130 | editable={!disabled} |
| 131 | value={query} |
| 132 | onChangeText={setQuery} |
| 133 | className="rounded-lg bg-background px-3 py-2 text-foreground" |
| 134 | /> |
| 135 | </View> |
| 136 | {selected && !shown.some((model) => model.id === selected.id) ? ( |
| 137 | <ListChoiceRow |
| 138 | label={selected.name} |
| 139 | description={selected.id} |
| 140 | selected |
| 141 | separated |
| 142 | disabled={disabled} |
| 143 | onPress={() => {}} |
| 144 | /> |
| 145 | ) : null} |
| 146 | {shown.map((model) => ( |
| 147 | <ListChoiceRow |
| 148 | key={model.id} |
| 149 | label={model.name} |
| 150 | description={model.id} |
| 151 | selected={model.id === value} |
| 152 | separated |
| 153 | disabled={disabled} |
| 154 | onPress={() => onChange(model.id)} |
| 155 | /> |
| 156 | ))} |
| 157 | {matches.length === 0 ? ( |
| 158 | <Separated> |
| 159 | <Text className="px-4 py-3 text-sm text-foreground-muted"> |
| 160 | <T>No transcription model matches.</T> |
| 161 | </Text> |
| 162 | </Separated> |
| 163 | ) : matches.length > shown.length ? ( |
| 164 | <Separated> |
| 165 | <ListActionRow |
| 166 | label={gt( |
| 167 | "{count, plural, one {Show all {count} models} other {Show all {count} models}}", |
| 168 | { count: matches.length }, |
| 169 | )} |
| 170 | onPress={() => setShowAll(true)} |
| 171 | /> |
| 172 | </Separated> |
| 173 | ) : null} |
| 174 | </ListSection> |
| 175 | ); |
| 176 | } |
| 177 | |
| 178 | /** A hairline above a row that has no `separated` prop of its own. */ |
| 179 | function Separated({ children }: { children: ReactNode }) { |
| 180 | return <View className="border-t border-border-subtle">{children}</View>; |
| 181 | } |
| 182 | |
| 183 | function CloudChoices({ environment, active, onClose }: Props & { onClose: () => void }) { |
| 184 | const gt = useGT(); |
| 185 | const messages = useMessages(); |
| 186 | const id = environment.environmentId; |
| 187 | const connection = useAtomValue(cloudVoiceConnectionAtom(id)); |
| 188 | const keys = useAtomValue(cloudVoiceKeysAtom(id)); |
| 189 | const reload = useAtomRefresh(cloudVoiceKeysAtom(id)); |
| 190 | const canManage = useEnvironmentScope(id, AuthSettingsWriteScope); |
| 191 | const [editing, setEditing] = useState<{ |
| 192 | provider: CloudSpeechProvider; |
| 193 | enable: boolean; |
| 194 | } | null>(null); |
| 195 | const catalogAtom = cloudVoiceModelsAtom(editing?.provider === "openrouter" ? id : null); |
| 196 | const models = useAtomValue(catalogAtom); |
| 197 | const reloadModels = useAtomRefresh(catalogAtom); |
| 198 | const [draft, setDraft] = useState(""); |
| 199 | const [model, setModel] = useState(""); |
| 200 | const [sourceId, setSourceId] = useState<SecretProviderId | null>(null); |
| 201 | const sources = |
| 202 | Constants.expoConfig?.extra?.secretsFeatureEnabled === true && |
| 203 | environment.serverConfig?.secretReferences |
| 204 | ? configuredSecretSources(environment.serverConfig.settings.secretProviders, messages) |
| 205 | : []; |
| 206 | const source = sources.find((candidate) => candidate.id === sourceId); |
| 207 | const credential = |
| 208 | sourceId !== null |
| 209 | ? source && secretRequestReference(source, draft) |
| 210 | : isApiKey(draft.trim()) |
| 211 | ? draft.trim() |
| 212 | : undefined; |
| 213 | const [saving, setSaving] = useState(false); |
| 214 | const activeModel = active?.provider === "openrouter" ? active.model : undefined; |
| 215 | const enable = (commit: () => void) => { |
| 216 | try { |
| 217 | commit(); |
| 218 | } catch { |
| 219 | Dialog.alert( |
| 220 | gt("Could not enable cloud dictation"), |
| 221 | gt("Check device storage and choose the provider again."), |
| 222 | ); |
| 223 | } |
| 224 | }; |
| 225 | const edit = (provider: CloudSpeechProvider, enable: boolean) => { |
| 226 | const stored = environment.serverConfig?.settings.cloudSpeechCredentials?.[provider]; |
| 227 | const ref = |
| 228 | isSecretReference(stored) && sources.some((candidate) => candidate.id === stored.provider) |
| 229 | ? stored |
| 230 | : null; |
| 231 | setSourceId(ref?.provider ?? null); |
| 232 | setDraft(ref?.reference ?? ""); |
| 233 | setModel(provider === "openrouter" ? (activeModel ?? "") : ""); |
| 234 | setEditing({ provider, enable }); |
| 235 | }; |
| 236 | const reset = () => { |
| 237 | setDraft(""); |
| 238 | setModel(""); |
| 239 | setEditing(null); |
| 240 | }; |
| 241 | const changeKey = async ( |
| 242 | provider: CloudSpeechProvider, |
| 243 | value: SettingsSecretValue | null, |
| 244 | chosen?: CloudSpeechModelId, |
| 245 | ) => { |
| 246 | if (!connection || !canManage || saving) return; |
| 247 | const commit = |
| 248 | value !== null && (editing?.enable || (chosen !== undefined && chosen !== activeModel)) |
| 249 | ? pendingCloudVoiceChoice(id, provider, chosen) |
| 250 | : null; |
| 251 | setSaving(true); |
| 252 | try { |
| 253 | await runSpeech(setCloudSpeechKey(connection, provider, value)); |
| 254 | } catch { |
| 255 | setSaving(false); |
| 256 | Dialog.alert( |
| 257 | gt("Could not update the API key"), |
| 258 | gt("Check the environment connection and your settings permissions."), |
| 259 | ); |
| 260 | return; |
| 261 | } |
| 262 | setSaving(false); |
| 263 | if (commit) enable(commit); |
| 264 | reload(); |
| 265 | onClose(); |
| 266 | }; |
| 267 | const catalog = AsyncResult.isSuccess(models) ? (models.value?.models ?? null) : null; |
| 268 | const content = (() => { |
| 269 | if (!AsyncResult.isSuccess(keys) || !keys.value || !connection) |
| 270 | return ( |
| 271 | <ListSection> |
| 272 | <ListActionRow |
| 273 | label={ |
| 274 | !connection |
| 275 | ? gt("Environment not connected") |
| 276 | : keys._tag === "Failure" |
| 277 | ? gt("Could not load keys · Retry") |
| 278 | : gt("Checking API keys…") |
| 279 | } |
| 280 | disabled={!connection || keys._tag !== "Failure"} |
| 281 | onPress={reload} |
| 282 | /> |
| 283 | </ListSection> |
| 284 | ); |
| 285 | const saved = keys.value; |
| 286 | if (!editing) |
| 287 | return ( |
| 288 | <ListSection |
| 289 | footer={gt("Audio is sent through {environment} using its API key.", { |
| 290 | environment: environment.label, |
| 291 | })} |
| 292 | > |
| 293 | {CloudSpeechProvider.literals.map((provider, index) => { |
| 294 | const label = CLOUD_SPEECH_LABELS[provider]; |
| 295 | const routed = provider === "openrouter"; |
| 296 | const key = saved[provider]; |
| 297 | const isActive = active?.provider === provider; |
| 298 | return ( |
| 299 | <ListChoiceRow |
| 300 | key={provider} |
| 301 | label={label} |
| 302 | leading={ |
| 303 | <ProviderIcon |
| 304 | provider={ |
| 305 | provider === "openai" ? "codex" : provider === "xai" ? "grok" : provider |
| 306 | } |
| 307 | size={20} |
| 308 | /> |
| 309 | } |
| 310 | selected={isActive} |
| 311 | separated={index > 0} |
| 312 | disabled={key === undefined || (!key && !canManage) || saving} |
| 313 | description={ |
| 314 | key === undefined |
| 315 | ? gt("Update the environment to use this provider") |
| 316 | : isActive && routed |
| 317 | ? canManage |
| 318 | ? gt("{model} · Tap to change model or key", { model: activeModel }) |
| 319 | : gt("{model} · Tap to change model", { model: activeModel }) |
| 320 | : isActive && key && canManage |
| 321 | ? gt("Tap to manage key") |
| 322 | : key |
| 323 | ? routed |
| 324 | ? gt("API key saved · choose a model to use it") |
| 325 | : gt("API key saved") |
| 326 | : canManage |
| 327 | ? gt("Add an API key to use this provider") |
| 328 | : gt("Ask an environment administrator to add an API key") |
| 329 | } |
| 330 | onPress={() => { |
| 331 | if (routed) return edit(provider, !isActive); |
| 332 | if (!key) return edit(provider, true); |
| 333 | if (isActive) { |
| 334 | if (canManage) edit(provider, false); |
| 335 | return; |
| 336 | } |
| 337 | Dialog.confirm({ |
| 338 | title: gt("Use {provider} for dictation?", { provider: label }), |
| 339 | message: gt("{disclosure} Select This device to stop sharing.", { |
| 340 | disclosure: cloudSpeechDisclosure(provider, environment.label, messages), |
| 341 | }), |
| 342 | confirmText: gt("Use {provider}", { provider: label }), |
| 343 | onConfirm: () => enable(pendingCloudVoiceChoice(id, provider)), |
| 344 | }); |
| 345 | }} |
| 346 | /> |
| 347 | ); |
| 348 | })} |
| 349 | </ListSection> |
| 350 | ); |
| 351 | |
| 352 | const provider = editing.provider; |
| 353 | const label = CLOUD_SPEECH_LABELS[provider]; |
| 354 | const company = CLOUD_SPEECH_PROVIDER_NAMES[provider]; |
| 355 | const routed = provider === "openrouter"; |
| 356 | const disclosure = cloudSpeechDisclosure(provider, environment.label, messages); |
| 357 | const key = saved[provider]; |
| 358 | const isActive = active?.provider === provider; |
| 359 | const modelChosen = isModelId(model) && (catalog?.some((entry) => entry.id === model) ?? false); |
| 360 | const modelChanged = model !== (activeModel ?? ""); |
| 361 | const original = environment.serverConfig?.settings.cloudSpeechCredentials?.[provider]; |
| 362 | const keyChanged = |
| 363 | credential !== undefined && |
| 364 | !( |
| 365 | isSecretReference(credential) && |
| 366 | isSecretReference(original) && |
| 367 | original.provider === credential.provider && |
| 368 | original.reference === credential.reference |
| 369 | ); |
| 370 | const routedReady = |
| 371 | modelChosen && |
| 372 | (draft.trim() ? credential !== undefined : Boolean(key)) && |
| 373 | (!isActive || modelChanged || keyChanged); |
| 374 | const saveRouted = () => { |
| 375 | if (!routedReady || !isModelId(model)) return; |
| 376 | const grantChanges = !isActive || modelChanged; |
| 377 | if (credential !== undefined && keyChanged) |
| 378 | return void changeKey(provider, credential, model); |
| 379 | // Model-only changes never write to the environment. |
| 380 | if (grantChanges) enable(() => chooseVoiceDestination(id, provider, model)); |
| 381 | onClose(); |
| 382 | }; |
| 383 | const submit = () => { |
| 384 | if (routed) saveRouted(); |
| 385 | else if (credential) void changeKey(provider, credential); |
| 386 | }; |
| 387 | const keyFooter = |
| 388 | draft && !credential |
| 389 | ? (source?.invalidReferenceMessage ?? gt("Enter a valid API key.")) |
| 390 | : routed |
| 391 | ? key && !credential |
| 392 | ? gt( |
| 393 | "Uses the API key saved on this environment. The model choice applies only to this device.", |
| 394 | ) |
| 395 | : gt("Anyone with dictation access to {environment} can bill this key.", { |
| 396 | environment: environment.label, |
| 397 | }) |
| 398 | : editing.enable |
| 399 | ? gt("Anyone with dictation access to {environment} can bill this key.", { |
| 400 | environment: environment.label, |
| 401 | }) |
| 402 | : gt( |
| 403 | "Updates the {company} key on {environment}. Your dictation destination stays the same.", |
| 404 | { company, environment: environment.label }, |
| 405 | ); |
| 406 | return ( |
| 407 | <> |
| 408 | <Text className="px-2 text-sm text-foreground-muted">{disclosure}</Text> |
| 409 | {routed ? ( |
| 410 | catalog ? ( |
| 411 | <ModelPicker |
| 412 | models={catalog} |
| 413 | value={model} |
| 414 | current={activeModel} |
| 415 | disabled={saving} |
| 416 | onChange={setModel} |
| 417 | /> |
| 418 | ) : ( |
| 419 | <ListSection title={gt("Model")}> |
| 420 | <ListActionRow |
| 421 | label={ |
| 422 | AsyncResult.isFailure(models) |
| 423 | ? gt("Could not load models · Retry") |
| 424 | : gt("Loading transcription models…") |
| 425 | } |
| 426 | disabled={!AsyncResult.isFailure(models)} |
| 427 | onPress={reloadModels} |
| 428 | /> |
| 429 | </ListSection> |
| 430 | ) |
| 431 | ) : null} |
| 432 | {canManage ? ( |
| 433 | <ListSection title={gt("API key")} footer={keyFooter}> |
| 434 | <View className="gap-3 px-4 py-3"> |
| 435 | {sources.length > 0 && ( |
| 436 | <View className="flex-row flex-wrap gap-2"> |
| 437 | <Chip |
| 438 | label={gt("Value", { $context: "enter the secret value directly" })} |
| 439 | size="small" |
| 440 | selected={sourceId === null} |
| 441 | disabled={saving} |
| 442 | onPress={() => { |
| 443 | setDraft(""); |
| 444 | setSourceId(null); |
| 445 | }} |
| 446 | /> |
| 447 | {sources.map((candidate) => ( |
| 448 | <Chip |
| 449 | key={candidate.id} |
| 450 | label={candidate.label} |
| 451 | size="small" |
| 452 | selected={sourceId === candidate.id} |
| 453 | disabled={saving} |
| 454 | onPress={() => { |
| 455 | setDraft(""); |
| 456 | setSourceId(candidate.id); |
| 457 | }} |
| 458 | /> |
| 459 | ))} |
| 460 | </View> |
| 461 | )} |
| 462 | <TextInput |
| 463 | key={sourceId ?? "literal"} |
| 464 | accessibilityLabel={ |
| 465 | sourceId |
| 466 | ? gt("{provider} API key reference", { provider: label }) |
| 467 | : gt("{provider} API key", { provider: label }) |
| 468 | } |
| 469 | placeholder={ |
| 470 | source?.referencePlaceholder ?? |
| 471 | (key ? gt("Saved key · enter a new one to replace") : gt("API key")) |
| 472 | } |
| 473 | secureTextEntry={sourceId === null} |
| 474 | autoCapitalize="none" |
| 475 | autoCorrect={false} |
| 476 | autoComplete="off" |
| 477 | importantForAutofill="no" |
| 478 | maxLength={4096} |
| 479 | editable={!saving} |
| 480 | returnKeyType="done" |
| 481 | onSubmitEditing={submit} |
| 482 | value={draft} |
| 483 | onChangeText={setDraft} |
| 484 | className="rounded-lg bg-background px-3 py-2 text-foreground" |
| 485 | /> |
| 486 | </View> |
| 487 | </ListSection> |
| 488 | ) : null} |
| 489 | {canManage || routed ? ( |
| 490 | <ListSection> |
| 491 | {routed && !key && !canManage ? ( |
| 492 | <ListActionRow |
| 493 | label={gt("Ask an administrator to add an {provider} key", { |
| 494 | provider: "OpenRouter", |
| 495 | })} |
| 496 | disabled |
| 497 | onPress={() => {}} |
| 498 | /> |
| 499 | ) : ( |
| 500 | <ListActionRow |
| 501 | label={ |
| 502 | routed |
| 503 | ? isActive |
| 504 | ? gt("Save") |
| 505 | : gt("Save and enable") |
| 506 | : editing.enable |
| 507 | ? gt("Save and enable") |
| 508 | : gt("Save key") |
| 509 | } |
| 510 | loading={saving} |
| 511 | disabled={routed ? !routedReady : !credential} |
| 512 | onPress={submit} |
| 513 | /> |
| 514 | )} |
| 515 | {key && canManage ? ( |
| 516 | <Separated> |
| 517 | <ListActionRow |
| 518 | tone="danger" |
| 519 | label={gt("Remove key from environment")} |
| 520 | disabled={saving} |
| 521 | onPress={() => |
| 522 | Dialog.confirm({ |
| 523 | title: gt("Remove the {provider} key from {environment}?", { |
| 524 | provider: label, |
| 525 | environment: environment.label, |
| 526 | }), |
| 527 | message: gt("Everyone using it for dictation will lose access."), |
| 528 | confirmText: gt("Remove key"), |
| 529 | destructive: true, |
| 530 | onConfirm: () => void changeKey(provider, null), |
| 531 | }) |
| 532 | } |
| 533 | /> |
| 534 | </Separated> |
| 535 | ) : null} |
| 536 | </ListSection> |
| 537 | ) : null} |
| 538 | <ListSection> |
| 539 | <ListActionRow label={gt("Back to providers")} disabled={saving} onPress={reset} /> |
| 540 | </ListSection> |
| 541 | </> |
| 542 | ); |
| 543 | })(); |
| 544 | return ( |
| 545 | <Sheet |
| 546 | title={editing ? CLOUD_SPEECH_LABELS[editing.provider] : gt("Cloud providers")} |
| 547 | onClose={onClose} |
| 548 | dismissDisabled={saving} |
| 549 | > |
| 550 | <ScrollView |
| 551 | contentInsetAdjustmentBehavior="automatic" |
| 552 | keyboardShouldPersistTaps="handled" |
| 553 | contentContainerClassName="gap-4 px-5 pt-2 pb-8" |
| 554 | > |
| 555 | {content} |
| 556 | </ScrollView> |
| 557 | </Sheet> |
| 558 | ); |
| 559 | } |