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 { useAtomValue } from "@effect/atom-react"; |
| 2 | import { sourceControlInstallHintText } from "@t3tools/client-runtime/contract-labels"; |
| 3 | import { isSourceControlProviderOffered } from "@t3tools/client-runtime/operations/projects"; |
| 4 | import { squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; |
| 5 | import { |
| 6 | readHostCredentialSettings, |
| 7 | sourceControlClients, |
| 8 | type SourceControlDefinition, |
| 9 | type SourceControlHostCredentials, |
| 10 | } from "@t3tools/client-runtime/source-control-clients"; |
| 11 | import type { |
| 12 | EnvironmentId, |
| 13 | SettingsSecretValue, |
| 14 | SourceControlProviderDiscoveryItem, |
| 15 | } from "@t3tools/contracts"; |
| 16 | import * as Option from "effect/Option"; |
| 17 | import * as Schema from "effect/Schema"; |
| 18 | import { useNavigation } from "@react-navigation/native"; |
| 19 | import { msg, useGT, useMessages } from "gt-react-native"; |
| 20 | import { useState } from "react"; |
| 21 | import { Platform, View } from "react-native"; |
| 22 | import { tryOpenExternalUrl } from "../../../lib/openExternalUrl"; |
| 23 | |
| 24 | import { AppText as Text } from "../../../components/ui/AppText"; |
| 25 | import { Button } from "../../../components/ui/Button"; |
| 26 | import { SecretTextInput } from "../../../components/ui/SecretTextInput"; |
| 27 | import { m, type MessageResolver } from "../../../i18n/messages"; |
| 28 | import { useEnvironmentQuery } from "../../../state/query"; |
| 29 | import { serverEnvironment } from "../../../state/server"; |
| 30 | import { sourceControlEnvironment } from "../../../state/sourceControl"; |
| 31 | import { useAtomCommand } from "../../../state/use-atom-command"; |
| 32 | import { ConnectionFormField } from "../../connection/ConnectionFormField"; |
| 33 | import { SourceControlIcon } from "../../projects/SourceControlIcon"; |
| 34 | import type { SettingsTarget } from "../settings-environment-filter"; |
| 35 | import { SettingsProviderRow } from "./SettingsProviderRow"; |
| 36 | import { SettingsSection } from "./SettingsSection"; |
| 37 | |
| 38 | const saveFailure = (result: Parameters<typeof squashAtomCommandFailure>[0]) => { |
| 39 | const error = squashAtomCommandFailure(result); |
| 40 | return error instanceof Error ? error.message : m(msg("The settings could not be saved.")); |
| 41 | }; |
| 42 | |
| 43 | const hasToken = (token: SettingsSecretValue | undefined) => |
| 44 | typeof token === "string" ? token.length > 0 : token !== undefined; |
| 45 | |
| 46 | export const sourceControlProviderReady = (item: SourceControlProviderDiscoveryItem) => |
| 47 | item.status === "available" && item.auth.status === "authenticated"; |
| 48 | |
| 49 | /** The line under a provider's name: whether it works on this server, and what to do if not. */ |
| 50 | export function sourceControlProviderSummary( |
| 51 | item: SourceControlProviderDiscoveryItem, |
| 52 | resolve: MessageResolver = m, |
| 53 | ): string { |
| 54 | const installHint = sourceControlInstallHintText(item.installHint, resolve); |
| 55 | if (item.status !== "available") |
| 56 | return resolve(msg("Not available on this server: {hint}", { hint: installHint })); |
| 57 | const { auth } = item; |
| 58 | const detail = Option.getOrNull(auth.detail); |
| 59 | if (auth.status === "authenticated") { |
| 60 | const account = Option.getOrNull(auth.account); |
| 61 | if (account && detail) |
| 62 | return resolve(msg("Authenticated as {account} · {detail}", { account, detail })); |
| 63 | if (account) return resolve(msg("Authenticated as {account}", { account })); |
| 64 | if (detail) return resolve(msg("Authenticated · {detail}", { detail })); |
| 65 | return resolve(msg("Authenticated")); |
| 66 | } |
| 67 | if (auth.status === "unauthenticated") { |
| 68 | if (!item.executable) return resolve(msg("Available. {hint}", { hint: installHint })); |
| 69 | if (auth.accounts?.some((entry) => entry.authenticated)) |
| 70 | return ( |
| 71 | detail ?? resolve(msg("Every {provider} host is turned off.", { provider: item.label })) |
| 72 | ); |
| 73 | return resolve( |
| 74 | msg( |
| 75 | "Not authenticated on this server. Sign in with the {tool} tool on the server host, or save a token here.", |
| 76 | { tool: item.executable }, |
| 77 | ), |
| 78 | ); |
| 79 | } |
| 80 | return resolve( |
| 81 | msg("Could not verify {provider}. {detail}", { |
| 82 | provider: item.label, |
| 83 | detail: detail ?? installHint, |
| 84 | }), |
| 85 | ); |
| 86 | } |
| 87 | |
| 88 | /** |
| 89 | * Every hosting integration each selected environment knows: whether it works there, whether |
| 90 | * the project pickers offer it, and its credentials where the app can set them. |
| 91 | */ |
| 92 | export function SourceControlProvidersSection(props: { |
| 93 | readonly environments: readonly SettingsTarget[]; |
| 94 | readonly canWrite: (environmentId: EnvironmentId) => boolean; |
| 95 | }) { |
| 96 | const gt = useGT(); |
| 97 | return ( |
| 98 | <> |
| 99 | {props.environments.map((environment) => ( |
| 100 | <EnvironmentProviders |
| 101 | key={environment.environmentId} |
| 102 | environment={environment} |
| 103 | title={ |
| 104 | props.environments.length > 1 |
| 105 | ? gt("Source control providers · {environment}", { environment: environment.label }) |
| 106 | : gt("Source control providers") |
| 107 | } |
| 108 | disabled={!props.canWrite(environment.environmentId)} |
| 109 | /> |
| 110 | ))} |
| 111 | </> |
| 112 | ); |
| 113 | } |
| 114 | |
| 115 | function EnvironmentProviders(props: { |
| 116 | readonly environment: SettingsTarget; |
| 117 | readonly title: string; |
| 118 | readonly disabled: boolean; |
| 119 | }) { |
| 120 | const gt = useGT(); |
| 121 | const messages = useMessages(); |
| 122 | const { environment } = props; |
| 123 | const { environmentId } = environment; |
| 124 | const discovery = useEnvironmentQuery( |
| 125 | sourceControlEnvironment.discovery({ environmentId, input: {} }), |
| 126 | ); |
| 127 | const canUpdate = useAtomValue(serverEnvironment.updateSettings.permissionAtom(environmentId)); |
| 128 | const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { |
| 129 | label: "save source control providers", |
| 130 | }); |
| 131 | const navigation = useNavigation(); |
| 132 | const items = discovery.data?.sourceControlProviders ?? []; |
| 133 | const offered = environment.serverConfig.settings.offeredSourceControlProviders; |
| 134 | const disabled = props.disabled || !canUpdate; |
| 135 | if (items.length === 0) { |
| 136 | return discovery.error ? ( |
| 137 | <SettingsSection title={props.title} footer={discovery.error}> |
| 138 | <View className="p-4"> |
| 139 | <Button label={gt("Scan again")} tone="secondary" onPress={discovery.refresh} /> |
| 140 | </View> |
| 141 | </SettingsSection> |
| 142 | ) : null; |
| 143 | } |
| 144 | return ( |
| 145 | <SettingsSection title={props.title}> |
| 146 | {items.map((item, index) => { |
| 147 | const definition = sourceControlClients.find(item.kind); |
| 148 | return ( |
| 149 | <SettingsProviderRow |
| 150 | key={item.kind} |
| 151 | icon={ |
| 152 | <SourceControlIcon |
| 153 | icon={definition?.icon ?? null} |
| 154 | size={Platform.OS === "android" ? 20 : 18} |
| 155 | colorClassName="accent-icon" |
| 156 | /> |
| 157 | } |
| 158 | label={item.label} |
| 159 | detail={Option.getOrNull(item.version)} |
| 160 | description={sourceControlProviderSummary(item, messages)} |
| 161 | ready={sourceControlProviderReady(item)} |
| 162 | separated={index > 0} |
| 163 | {...(definition?.credentials || definition?.settings |
| 164 | ? { |
| 165 | onPress: () => |
| 166 | navigation.navigate("SettingsSourceControlProvider", { |
| 167 | environmentId, |
| 168 | kind: item.kind, |
| 169 | }), |
| 170 | } |
| 171 | : {})} |
| 172 | toggle={{ |
| 173 | accessibilityLabel: gt("Offer {provider} when adding or publishing a project", { |
| 174 | provider: item.label, |
| 175 | }), |
| 176 | value: isSourceControlProviderOffered(offered, item.kind), |
| 177 | disabled, |
| 178 | onValueChange: (value) => |
| 179 | void updateSettings({ |
| 180 | environmentId, |
| 181 | input: { patch: { offeredSourceControlProviders: { [item.kind]: value } } }, |
| 182 | }), |
| 183 | }} |
| 184 | /> |
| 185 | ); |
| 186 | })} |
| 187 | </SettingsSection> |
| 188 | ); |
| 189 | } |
| 190 | |
| 191 | export function SourceControlTokenForm(props: { |
| 192 | readonly environment: SettingsTarget; |
| 193 | readonly definition: SourceControlDefinition; |
| 194 | readonly credentials: SourceControlHostCredentials; |
| 195 | readonly disabled: boolean; |
| 196 | readonly onSaved: () => void; |
| 197 | }) { |
| 198 | const gt = useGT(); |
| 199 | const { definition, credentials } = props; |
| 200 | const { environmentId } = props.environment; |
| 201 | // Translates the GitHub definition's English `tokenAccess`, as the web settings do. |
| 202 | const tokenAccess = |
| 203 | definition.kind === "github" |
| 204 | ? gt("read and write access to pull requests and contents") |
| 205 | : credentials.tokenAccess; |
| 206 | const { tokens } = readHostCredentialSettings( |
| 207 | props.environment.serverConfig.settings, |
| 208 | definition.kind, |
| 209 | ); |
| 210 | const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { |
| 211 | label: `save ${definition.label} token`, |
| 212 | }); |
| 213 | const defaultHost = definition.publicHost ?? ""; |
| 214 | const [host, setHost] = useState(defaultHost); |
| 215 | const [draft, setDraft] = useState(""); |
| 216 | const [saving, setSaving] = useState(false); |
| 217 | const [failure, setFailure] = useState<string | null>(null); |
| 218 | const target = host.trim().toLowerCase(); |
| 219 | const saved = hasToken(tokens[target]); |
| 220 | const savedHosts = Object.entries(tokens) |
| 221 | .filter(([, value]) => hasToken(value)) |
| 222 | .map(([name]) => name); |
| 223 | |
| 224 | const save = async (token: string) => { |
| 225 | if (!target) return; |
| 226 | setSaving(true); |
| 227 | setFailure(null); |
| 228 | const result = await updateSettings({ |
| 229 | environmentId, |
| 230 | // Send the whole map; other tokens' redaction markers preserve their values. |
| 231 | input: { |
| 232 | patch: { |
| 233 | sourceControlHosts: { [definition.kind]: { tokens: { ...tokens, [target]: token } } }, |
| 234 | }, |
| 235 | }, |
| 236 | }); |
| 237 | setSaving(false); |
| 238 | if (result._tag !== "Success") { |
| 239 | setFailure(saveFailure(result)); |
| 240 | return; |
| 241 | } |
| 242 | setDraft(""); |
| 243 | props.onSaved(); |
| 244 | }; |
| 245 | const locked = props.disabled || saving; |
| 246 | return ( |
| 247 | <View className="gap-3 p-4"> |
| 248 | <Text className="text-xs leading-relaxed text-foreground-muted"> |
| 249 | {gt( |
| 250 | "A token saved here is used before {envVar} and the {cliName} login, so {provider} works without the {cliLabel}. Give it {access}.", |
| 251 | { |
| 252 | envVar: credentials.tokenEnvVar, |
| 253 | cliName: credentials.cliName, |
| 254 | provider: definition.label, |
| 255 | cliLabel: credentials.cliLabel, |
| 256 | access: tokenAccess, |
| 257 | }, |
| 258 | )} |
| 259 | </Text> |
| 260 | <ConnectionFormField |
| 261 | label={gt("Host", { $context: "source control host name field" })} |
| 262 | autoCapitalize="none" |
| 263 | autoCorrect={false} |
| 264 | keyboardType="url" |
| 265 | placeholder={defaultHost} |
| 266 | editable={!locked} |
| 267 | value={host} |
| 268 | onChangeText={setHost} |
| 269 | /> |
| 270 | <SecretTextInput |
| 271 | accessibilityLabel={gt("{provider} token", { provider: definition.label })} |
| 272 | placeholder={ |
| 273 | saved |
| 274 | ? gt("Saved. Enter a new token to replace it") |
| 275 | : gt("Token", { $context: "access token field" }) |
| 276 | } |
| 277 | value={draft} |
| 278 | onChangeText={setDraft} |
| 279 | onSubmitEditing={(value) => { |
| 280 | if (value.trim()) void save(value.trim()); |
| 281 | }} |
| 282 | editable={!locked} |
| 283 | /> |
| 284 | <Text className="text-xs text-foreground-muted"> |
| 285 | {savedHosts.length === 0 |
| 286 | ? gt("No token saved; the server uses {envVar} or the {cliName} login.", { |
| 287 | envVar: credentials.tokenEnvVar, |
| 288 | cliName: credentials.cliName, |
| 289 | }) |
| 290 | : gt("Saved for {hosts}.", { hosts: savedHosts.join(", ") })} |
| 291 | </Text> |
| 292 | {failure ? ( |
| 293 | <Text selectable className="text-xs text-danger-foreground"> |
| 294 | {failure} |
| 295 | </Text> |
| 296 | ) : null} |
| 297 | <View className="flex-row flex-wrap justify-end gap-2"> |
| 298 | {target || defaultHost ? ( |
| 299 | <Button |
| 300 | label={gt("Create a token")} |
| 301 | tone="text" |
| 302 | size="compact" |
| 303 | onPress={() => |
| 304 | void tryOpenExternalUrl( |
| 305 | credentials.newTokenUrl(target || defaultHost), |
| 306 | "provider-auth", |
| 307 | ) |
| 308 | } |
| 309 | /> |
| 310 | ) : null} |
| 311 | {saved ? ( |
| 312 | <Button |
| 313 | label={gt("Remove", { $context: "verb, removes a saved token" })} |
| 314 | tone="secondary" |
| 315 | size="compact" |
| 316 | disabled={locked} |
| 317 | onPress={() => void save("")} |
| 318 | /> |
| 319 | ) : null} |
| 320 | <Button |
| 321 | label={gt("Save")} |
| 322 | tone="primary" |
| 323 | size="compact" |
| 324 | loading={saving} |
| 325 | disabled={locked || !target || !draft.trim()} |
| 326 | onPress={() => void save(draft.trim())} |
| 327 | /> |
| 328 | </View> |
| 329 | </View> |
| 330 | ); |
| 331 | } |
| 332 | |
| 333 | type HostSettings = NonNullable<SourceControlDefinition["settings"]>; |
| 334 | |
| 335 | /** The fields a host declares, in its own order, with what its schema says about each. */ |
| 336 | function hostSettingsFields(settings: HostSettings) { |
| 337 | const order = Schema.resolveAnnotations(settings)?.providerSettingsFormSchema?.order ?? []; |
| 338 | const position = (key: string) => (order.includes(key) ? order.indexOf(key) : order.length); |
| 339 | return Object.keys(settings.fields) |
| 340 | .sort((left, right) => position(left) - position(right)) |
| 341 | .flatMap((key) => { |
| 342 | const field = settings.fields[key]!; |
| 343 | const annotations = Schema.resolveAnnotationsKey(field) ?? Schema.resolveAnnotations(field); |
| 344 | const form = annotations?.providerSettingsForm ?? {}; |
| 345 | if (form.hidden) return []; |
| 346 | return [ |
| 347 | { |
| 348 | key, |
| 349 | label: typeof annotations?.title === "string" ? annotations.title : key, |
| 350 | description: |
| 351 | typeof annotations?.description === "string" ? annotations.description : undefined, |
| 352 | placeholder: form.placeholder, |
| 353 | secret: form.control === "password", |
| 354 | }, |
| 355 | ]; |
| 356 | }); |
| 357 | } |
| 358 | |
| 359 | /** Credentials for a host that names its own fields rather than one token per host. */ |
| 360 | export function SourceControlHostFieldsForm(props: { |
| 361 | readonly environment: SettingsTarget; |
| 362 | readonly definition: SourceControlDefinition; |
| 363 | readonly settings: HostSettings; |
| 364 | readonly disabled: boolean; |
| 365 | readonly onSaved: () => void; |
| 366 | }) { |
| 367 | const gt = useGT(); |
| 368 | const { definition } = props; |
| 369 | const { environmentId } = props.environment; |
| 370 | const saved: Readonly<Record<string, unknown>> = |
| 371 | props.environment.serverConfig.settings.sourceControlHosts[definition.kind] ?? {}; |
| 372 | const updateSettings = useAtomCommand(serverEnvironment.updateSettings, { |
| 373 | label: `save ${definition.label} settings`, |
| 374 | }); |
| 375 | const [drafts, setDrafts] = useState<Readonly<Record<string, string>>>({}); |
| 376 | const [saving, setSaving] = useState(false); |
| 377 | const [failure, setFailure] = useState<string | null>(null); |
| 378 | const fields = hostSettingsFields(props.settings); |
| 379 | const isSet = (key: string) => { |
| 380 | const value = saved[key]; |
| 381 | return typeof value === "string" ? value.length > 0 : value !== undefined; |
| 382 | }; |
| 383 | const changed = Object.fromEntries( |
| 384 | Object.entries(drafts).flatMap(([key, value]) => (value.trim() ? [[key, value.trim()]] : [])), |
| 385 | ); |
| 386 | const save = async (patch: Record<string, string>) => { |
| 387 | setSaving(true); |
| 388 | setFailure(null); |
| 389 | const result = await updateSettings({ |
| 390 | environmentId, |
| 391 | input: { patch: { sourceControlHosts: { [definition.kind]: patch } } }, |
| 392 | }); |
| 393 | setSaving(false); |
| 394 | if (result._tag !== "Success") { |
| 395 | setFailure(saveFailure(result)); |
| 396 | return; |
| 397 | } |
| 398 | setDrafts({}); |
| 399 | props.onSaved(); |
| 400 | }; |
| 401 | const locked = props.disabled || saving; |
| 402 | const submit = () => { |
| 403 | if (Object.keys(changed).length > 0) void save(changed); |
| 404 | }; |
| 405 | return ( |
| 406 | <View className="gap-4 p-4"> |
| 407 | {fields.map((field) => ( |
| 408 | <View key={field.key} className="gap-1.5"> |
| 409 | {field.secret ? ( |
| 410 | <> |
| 411 | <Text className="text-2xs font-t3-bold tracking-[0.8px] uppercase text-foreground-muted"> |
| 412 | {field.label} |
| 413 | </Text> |
| 414 | <SecretTextInput |
| 415 | accessibilityLabel={field.label} |
| 416 | placeholder={ |
| 417 | isSet(field.key) ? gt("Saved. Enter a new value to replace it") : field.label |
| 418 | } |
| 419 | value={drafts[field.key] ?? ""} |
| 420 | onChangeText={(value) => setDrafts({ ...drafts, [field.key]: value })} |
| 421 | onSubmitEditing={submit} |
| 422 | editable={!locked} |
| 423 | /> |
| 424 | </> |
| 425 | ) : ( |
| 426 | <ConnectionFormField |
| 427 | label={field.label} |
| 428 | autoCapitalize="none" |
| 429 | autoCorrect={false} |
| 430 | placeholder={ |
| 431 | typeof saved[field.key] === "string" && saved[field.key] !== "" |
| 432 | ? String(saved[field.key]) |
| 433 | : field.placeholder |
| 434 | } |
| 435 | editable={!locked} |
| 436 | value={drafts[field.key] ?? ""} |
| 437 | onChangeText={(value) => setDrafts({ ...drafts, [field.key]: value })} |
| 438 | onSubmitEditing={submit} |
| 439 | /> |
| 440 | )} |
| 441 | {field.description ? ( |
| 442 | <Text className="text-xs text-foreground-muted">{field.description}</Text> |
| 443 | ) : null} |
| 444 | </View> |
| 445 | ))} |
| 446 | {failure ? ( |
| 447 | <Text selectable className="text-xs text-danger-foreground"> |
| 448 | {failure} |
| 449 | </Text> |
| 450 | ) : null} |
| 451 | <View className="flex-row flex-wrap justify-end gap-2"> |
| 452 | {fields.some((field) => isSet(field.key)) ? ( |
| 453 | <Button |
| 454 | label={gt("Remove", { $context: "verb, removes saved credentials" })} |
| 455 | tone="secondary" |
| 456 | size="compact" |
| 457 | disabled={locked} |
| 458 | onPress={() => void save(Object.fromEntries(fields.map((field) => [field.key, ""])))} |
| 459 | /> |
| 460 | ) : null} |
| 461 | <Button |
| 462 | label={gt("Save")} |
| 463 | tone="primary" |
| 464 | size="compact" |
| 465 | loading={saving} |
| 466 | disabled={locked || Object.keys(changed).length === 0} |
| 467 | onPress={submit} |
| 468 | /> |
| 469 | </View> |
| 470 | </View> |
| 471 | ); |
| 472 | } |