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 { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 2 | import { m } from "~/i18n/messages"; |
| 3 | import { |
| 4 | isAtomCommandInterrupted, |
| 5 | squashAtomCommandFailure, |
| 6 | type AtomCommandResult, |
| 7 | } from "@t3tools/client-runtime/state/runtime"; |
| 8 | import type { |
| 9 | EnvironmentId, |
| 10 | ProviderAuthRespondInput, |
| 11 | ProviderAuthResponse, |
| 12 | ProviderInstanceId, |
| 13 | ServerProvider, |
| 14 | } from "@t3tools/contracts"; |
| 15 | import { msg, T, useGT, useMessages, Var } from "gt-react"; |
| 16 | import { lazy, Suspense, useRef, useState } from "react"; |
| 17 | import { CopyIcon } from "lucide-react"; |
| 18 | |
| 19 | import { writeTextToClipboard } from "../../hooks/useCopyToClipboard"; |
| 20 | import { isWebUrl } from "../../browser/webUrl"; |
| 21 | import { ensureLocalApi } from "../../localApi"; |
| 22 | import { useEnvironmentQuery } from "../../state/query"; |
| 23 | import { serverEnvironment } from "../../state/server"; |
| 24 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 25 | import { Button } from "../ui/button"; |
| 26 | import { Input } from "../ui/input"; |
| 27 | import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select"; |
| 28 | import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip"; |
| 29 | import { SettingsRow } from "./settingsLayout"; |
| 30 | import { RedactedSensitiveText } from "./RedactedSensitiveText"; |
| 31 | |
| 32 | const ProviderAuthTerminal = lazy(() => import("./ProviderAuthTerminal")); |
| 33 | |
| 34 | export function ProviderAuthenticationSection({ |
| 35 | environmentId, |
| 36 | environmentLabel, |
| 37 | instanceId, |
| 38 | provider, |
| 39 | readOnly, |
| 40 | }: { |
| 41 | readonly environmentId: EnvironmentId; |
| 42 | readonly environmentLabel: string; |
| 43 | readonly instanceId: ProviderInstanceId; |
| 44 | readonly provider: ServerProvider; |
| 45 | readonly readOnly: boolean; |
| 46 | }) { |
| 47 | const gt = useGT(); |
| 48 | const target = { environmentId, input: { instanceId } }; |
| 49 | const query = useEnvironmentQuery(serverEnvironment.providerAuthState(target), useMessages()); |
| 50 | const commands = { reportFailure: false, reportDefect: false }; |
| 51 | const start = useAtomCommand(serverEnvironment.startProviderAuth, commands); |
| 52 | const respond = useAtomCommand(serverEnvironment.respondProviderAuth, commands); |
| 53 | const complete = useAtomCommand(serverEnvironment.completeProviderAuth, commands); |
| 54 | const cancel = useAtomCommand(serverEnvironment.cancelProviderAuth, commands); |
| 55 | const logout = useAtomCommand(serverEnvironment.logoutProviderAuth, commands); |
| 56 | const [methodId, setMethodId] = useState(""); |
| 57 | const [draft, setDraft] = useState({ id: "", values: {} as Record<string, string> }); |
| 58 | const [error, setError] = useState<string | null>(null); |
| 59 | const [pending, setPending] = useState(false); |
| 60 | const pendingRef = useRef(false); |
| 61 | const terminalQueue = useRef<ProviderAuthRespondInput[]>([]); |
| 62 | const terminalSending = useRef(false); |
| 63 | const auth = query.data; |
| 64 | const interaction = auth?.interaction; |
| 65 | const active = |
| 66 | auth?.phase === "starting" || auth?.phase === "waiting" || auth?.phase === "verifying"; |
| 67 | const signedIn = |
| 68 | provider.auth.status === "authenticated" || |
| 69 | (provider.auth.status === "unknown" && auth?.phase === "succeeded"); |
| 70 | const isDiscovering = |
| 71 | provider.driver === "acpRegistry" && |
| 72 | !active && |
| 73 | !signedIn && |
| 74 | !query.error && |
| 75 | auth?.methods === undefined; |
| 76 | const needsExternalSetup = |
| 77 | !active && |
| 78 | !signedIn && |
| 79 | (provider.setup?.canAuthenticate === false || |
| 80 | (provider.driver === "acpRegistry" && auth?.methods?.length === 0)); |
| 81 | const usesCredentials = |
| 82 | provider.driver === "antigravity" && |
| 83 | (provider.auth.type === "gemini-api-key" || provider.auth.type === "agent-platform"); |
| 84 | const accountDescription = active |
| 85 | ? auth?.phase === "starting" |
| 86 | ? (auth.message ?? (usesCredentials ? gt("Connecting…") : gt("Starting sign-in…"))) |
| 87 | : auth?.phase === "verifying" |
| 88 | ? usesCredentials |
| 89 | ? gt("Checking credentials and loading models…") |
| 90 | : gt("Checking your account…") |
| 91 | : interaction?.type === "terminal" |
| 92 | ? gt("Complete sign-in in the terminal below.") |
| 93 | : interaction?.type === "credentials" |
| 94 | ? gt("Enter your credentials below.") |
| 95 | : gt("Finish signing in in your browser.") |
| 96 | : signedIn |
| 97 | ? gt("Signed in.") |
| 98 | : isDiscovering |
| 99 | ? gt("Discovering sign-in methods…") |
| 100 | : needsExternalSetup |
| 101 | ? gt("No in-app sign-in advertised. Follow the provider's docs to finish setup.") |
| 102 | : usesCredentials |
| 103 | ? gt("Connect on {environment} to load models.", { environment: environmentLabel }) |
| 104 | : gt("Sign in on {environment}.", { environment: environmentLabel }); |
| 105 | const statusMessage = auth?.phase === "failed" ? auth.message : null; |
| 106 | const disabled = readOnly || pending || query.error !== null || isDiscovering; |
| 107 | const draftId = `${auth?.flowId ?? ""}:${interaction?.id ?? ""}`; |
| 108 | const values = draft.id === draftId ? draft.values : {}; |
| 109 | const url = |
| 110 | interaction?.type === "browser" || interaction?.type === "deviceCode" |
| 111 | ? interaction.url |
| 112 | : auth?.authorizationUrl; |
| 113 | |
| 114 | async function run(command: () => Promise<AtomCommandResult<unknown, unknown>>) { |
| 115 | if (pendingRef.current) return false; |
| 116 | pendingRef.current = true; |
| 117 | setPending(true); |
| 118 | setError(null); |
| 119 | let succeeded = false; |
| 120 | try { |
| 121 | const result = await command(); |
| 122 | if (result._tag === "Success") succeeded = true; |
| 123 | else if (!isAtomCommandInterrupted(result)) { |
| 124 | const failure = squashAtomCommandFailure(result); |
| 125 | setError( |
| 126 | failure instanceof Error |
| 127 | ? (thrownErrorMessage(failure, m) ?? failure.message) |
| 128 | : gt("Provider sign-in failed. Try again."), |
| 129 | ); |
| 130 | } |
| 131 | } catch { |
| 132 | setError(gt("Provider sign-in failed. Try again.")); |
| 133 | } |
| 134 | pendingRef.current = false; |
| 135 | setPending(false); |
| 136 | return succeeded; |
| 137 | } |
| 138 | |
| 139 | async function send(response: ProviderAuthResponse) { |
| 140 | if (!auth?.flowId || !interaction) return false; |
| 141 | return run(() => |
| 142 | respond({ |
| 143 | environmentId, |
| 144 | input: { instanceId, flowId: auth.flowId!, interactionId: interaction.id, response }, |
| 145 | }), |
| 146 | ); |
| 147 | } |
| 148 | |
| 149 | async function openBrowser() { |
| 150 | if (!url || readOnly) return; |
| 151 | if (!isWebUrl(url)) { |
| 152 | setError(gt("This sign-in link is not a web address, so it was not opened.")); |
| 153 | return; |
| 154 | } |
| 155 | const requiresConsent = interaction?.type === "browser" && interaction.requiresConsent; |
| 156 | // Reserve tabs before awaiting consent; browsers block later opens. |
| 157 | const pending = requiresConsent && !window.desktopBridge ? window.open("", "_blank") : null; |
| 158 | if (pending) pending.opener = null; |
| 159 | try { |
| 160 | if (requiresConsent && !(await send({ type: "browser", action: "accept" }))) { |
| 161 | pending?.close(); |
| 162 | return; |
| 163 | } |
| 164 | if (pending) pending.location.href = url; |
| 165 | else await ensureLocalApi().shell.openExternal(url); |
| 166 | setError(null); |
| 167 | } catch { |
| 168 | pending?.close(); |
| 169 | setError(gt("Could not open the sign-in page. Copy the link and open it in your browser.")); |
| 170 | } |
| 171 | } |
| 172 | |
| 173 | function updateDraft(name: string, value: string) { |
| 174 | setDraft({ id: draftId, values: { ...values, [name]: value } }); |
| 175 | } |
| 176 | |
| 177 | return ( |
| 178 | <SettingsRow |
| 179 | title={gt("Account")} |
| 180 | description={ |
| 181 | signedIn && !active && provider.auth.email?.trim() ? ( |
| 182 | <span> |
| 183 | <T> |
| 184 | Signed in as{" "} |
| 185 | <RedactedSensitiveText |
| 186 | key={provider.auth.email} |
| 187 | value={provider.auth.email} |
| 188 | ariaLabel={gt("Toggle account email visibility")} |
| 189 | revealTooltip={gt("Click to reveal email")} |
| 190 | hideTooltip={gt("Click to hide email")} |
| 191 | className="max-w-full truncate" |
| 192 | /> |
| 193 | </T> |
| 194 | </span> |
| 195 | ) : ( |
| 196 | <span role="status">{accountDescription}</span> |
| 197 | ) |
| 198 | } |
| 199 | status={ |
| 200 | statusMessage ? ( |
| 201 | <p role="status" className="[overflow-wrap:anywhere]"> |
| 202 | {statusMessage} |
| 203 | </p> |
| 204 | ) : undefined |
| 205 | } |
| 206 | control={ |
| 207 | <div className="flex min-w-0 flex-wrap items-center gap-1.5"> |
| 208 | {!active && (auth?.methods?.length ?? 0) > 1 ? ( |
| 209 | <Select |
| 210 | value={auth?.methods?.some((method) => method.id === methodId) ? methodId : ""} |
| 211 | disabled={disabled} |
| 212 | onValueChange={(value) => setMethodId(value ?? "")} |
| 213 | > |
| 214 | <SelectTrigger size="sm" aria-label={gt("Sign-in method")} className="w-44"> |
| 215 | <SelectValue> |
| 216 | {auth?.methods?.find((method) => method.id === methodId)?.name ?? |
| 217 | gt("Provider default")} |
| 218 | </SelectValue> |
| 219 | </SelectTrigger> |
| 220 | <SelectPopup> |
| 221 | <SelectItem value=""> |
| 222 | <T>Provider default</T> |
| 223 | </SelectItem> |
| 224 | {auth?.methods?.map((method) => ( |
| 225 | <SelectItem key={method.id} value={method.id}> |
| 226 | {method.name} |
| 227 | </SelectItem> |
| 228 | ))} |
| 229 | </SelectPopup> |
| 230 | </Select> |
| 231 | ) : null} |
| 232 | {url ? ( |
| 233 | <> |
| 234 | <Button |
| 235 | size="sm" |
| 236 | variant="outline" |
| 237 | disabled={disabled} |
| 238 | onClick={() => void openBrowser()} |
| 239 | > |
| 240 | <T>Open browser</T> |
| 241 | </Button> |
| 242 | <Tooltip> |
| 243 | <TooltipTrigger |
| 244 | render={ |
| 245 | <Button |
| 246 | aria-label={gt("Copy sign-in link")} |
| 247 | size="icon-sm" |
| 248 | variant="ghost-muted" |
| 249 | disabled={disabled} |
| 250 | onClick={() => { |
| 251 | // Copy during the click to retain clipboard activation; consent must still be |
| 252 | // recorded before use. |
| 253 | const copied = writeTextToClipboard(url, { |
| 254 | target: "Provider sign-in link", |
| 255 | unavailableMessage: msg( |
| 256 | "Clipboard API is unavailable while copying Provider sign-in link.", |
| 257 | ), |
| 258 | failureMessage: msg( |
| 259 | "Failed to copy Provider sign-in link to the clipboard.", |
| 260 | ), |
| 261 | }); |
| 262 | void (async () => { |
| 263 | await copied; |
| 264 | if (interaction?.type === "browser" && interaction.requiresConsent) |
| 265 | await send({ type: "browser", action: "accept" }); |
| 266 | })().catch(() => setError(gt("Could not copy the sign-in link."))); |
| 267 | }} |
| 268 | > |
| 269 | <CopyIcon /> |
| 270 | </Button> |
| 271 | } |
| 272 | /> |
| 273 | <TooltipPopup> |
| 274 | <T>Copy sign-in link</T> |
| 275 | </TooltipPopup> |
| 276 | </Tooltip> |
| 277 | </> |
| 278 | ) : null} |
| 279 | <> |
| 280 | {needsExternalSetup && provider.setup?.documentationUrl ? ( |
| 281 | <Button |
| 282 | size="sm" |
| 283 | variant="outline" |
| 284 | render={ |
| 285 | <a href={provider.setup.documentationUrl} target="_blank" rel="noreferrer" /> |
| 286 | } |
| 287 | > |
| 288 | <T>Open docs</T> |
| 289 | </Button> |
| 290 | ) : active && auth?.flowId ? ( |
| 291 | <Button |
| 292 | size="sm" |
| 293 | variant="ghost-muted" |
| 294 | aria-label={gt("Cancel sign-in")} |
| 295 | disabled={disabled} |
| 296 | onClick={() => |
| 297 | void run(() => |
| 298 | cancel({ environmentId, input: { instanceId, flowId: auth.flowId! } }), |
| 299 | ) |
| 300 | } |
| 301 | > |
| 302 | <T>Cancel</T> |
| 303 | </Button> |
| 304 | ) : !active && !needsExternalSetup && provider.setup?.canAuthenticate !== false ? ( |
| 305 | <Button |
| 306 | size="sm" |
| 307 | variant="outline" |
| 308 | disabled={disabled || !provider.enabled || !provider.installed || !auth} |
| 309 | onClick={() => |
| 310 | void run(() => |
| 311 | start({ |
| 312 | environmentId, |
| 313 | input: { |
| 314 | instanceId, |
| 315 | ...(methodId && auth?.methods?.some((method) => method.id === methodId) |
| 316 | ? { methodId } |
| 317 | : {}), |
| 318 | }, |
| 319 | }), |
| 320 | ) |
| 321 | } |
| 322 | > |
| 323 | {signedIn |
| 324 | ? gt("Change account") |
| 325 | : auth?.phase === "failed" || auth?.phase === "cancelled" |
| 326 | ? usesCredentials |
| 327 | ? gt("Retry connection") |
| 328 | : gt("Retry sign-in") |
| 329 | : usesCredentials |
| 330 | ? gt("Connect") |
| 331 | : gt("Sign in")} |
| 332 | </Button> |
| 333 | ) : null} |
| 334 | {!active && signedIn && (provider.auth.canLogout ?? provider.setup?.canAuthenticate) ? ( |
| 335 | <Button |
| 336 | size="sm" |
| 337 | variant="ghost" |
| 338 | disabled={disabled || !auth} |
| 339 | onClick={() => { |
| 340 | void ensureLocalApi() |
| 341 | .dialogs.confirm( |
| 342 | gt( |
| 343 | "Sign out of {provider} on {environment}? This stops running threads that share this sign-in. Thread history is kept.", |
| 344 | { |
| 345 | provider: provider.displayName ?? provider.driver, |
| 346 | environment: environmentLabel, |
| 347 | }, |
| 348 | ), |
| 349 | ) |
| 350 | .then((confirmed) => { |
| 351 | if (confirmed) void run(() => logout(target)); |
| 352 | }); |
| 353 | }} |
| 354 | > |
| 355 | <T>Sign out</T> |
| 356 | </Button> |
| 357 | ) : null} |
| 358 | </> |
| 359 | </div> |
| 360 | } |
| 361 | > |
| 362 | {interaction?.type === "terminal" || |
| 363 | interaction?.type === "credentials" || |
| 364 | interaction?.type === "deviceCode" || |
| 365 | (url && (interaction?.type === "browser" ? interaction.acceptsCallback : !interaction)) || |
| 366 | error || |
| 367 | query.error ? ( |
| 368 | <> |
| 369 | {interaction?.type === "deviceCode" ? ( |
| 370 | <p className="py-2 text-sm text-muted-foreground"> |
| 371 | <T> |
| 372 | Enter code{" "} |
| 373 | <code className="select-all font-mono text-foreground"> |
| 374 | <Var>{interaction.userCode}</Var> |
| 375 | </code>{" "} |
| 376 | in your browser. |
| 377 | </T> |
| 378 | </p> |
| 379 | ) : null} |
| 380 | {interaction?.type === "terminal" ? ( |
| 381 | <div className="py-2"> |
| 382 | <Suspense |
| 383 | fallback={ |
| 384 | <p className="text-xs text-muted-foreground"> |
| 385 | <T>Loading sign-in terminal…</T> |
| 386 | </p> |
| 387 | } |
| 388 | > |
| 389 | <ProviderAuthTerminal |
| 390 | key={`${auth?.flowId}:${interaction.id}`} |
| 391 | output={interaction.output} |
| 392 | outputOffset={interaction.outputOffset} |
| 393 | onResponse={(response) => { |
| 394 | if (readOnly || !auth?.flowId) return; |
| 395 | for ( |
| 396 | let offset = 0; |
| 397 | offset < Math.max(1, response.data.length); |
| 398 | offset += 4_096 |
| 399 | ) { |
| 400 | terminalQueue.current.push({ |
| 401 | instanceId, |
| 402 | flowId: auth.flowId, |
| 403 | interactionId: interaction.id, |
| 404 | response: { |
| 405 | ...response, |
| 406 | data: response.data.slice(offset, offset + 4_096), |
| 407 | }, |
| 408 | }); |
| 409 | } |
| 410 | if (terminalSending.current) return; |
| 411 | terminalSending.current = true; |
| 412 | void (async () => { |
| 413 | while (terminalQueue.current.length > 0) { |
| 414 | const input = terminalQueue.current.shift()!; |
| 415 | const result = await respond({ environmentId, input }); |
| 416 | if (result._tag !== "Success") { |
| 417 | terminalQueue.current = []; |
| 418 | if (!isAtomCommandInterrupted(result)) |
| 419 | setError(gt("The provider sign-in terminal is no longer available.")); |
| 420 | break; |
| 421 | } |
| 422 | } |
| 423 | })() |
| 424 | .catch(() => { |
| 425 | terminalQueue.current = []; |
| 426 | setError(gt("Could not send input to the provider sign-in terminal.")); |
| 427 | }) |
| 428 | .finally(() => { |
| 429 | terminalSending.current = false; |
| 430 | }); |
| 431 | }} |
| 432 | /> |
| 433 | </Suspense> |
| 434 | </div> |
| 435 | ) : null} |
| 436 | {interaction?.type === "credentials" ? ( |
| 437 | <form |
| 438 | className="grid gap-2 py-2 text-sm leading-normal" |
| 439 | onSubmit={(event) => { |
| 440 | event.preventDefault(); |
| 441 | void send({ type: "credentials", values }).then((sent) => { |
| 442 | if (sent) setDraft({ id: "", values: {} }); |
| 443 | }); |
| 444 | }} |
| 445 | > |
| 446 | {interaction.fields.map((field) => ( |
| 447 | <label key={field.name} className="grid gap-1"> |
| 448 | {field.label} |
| 449 | <Input |
| 450 | size="sm" |
| 451 | type={field.secret ? "password" : "text"} |
| 452 | autoComplete="off" |
| 453 | value={values[field.name] ?? ""} |
| 454 | disabled={disabled} |
| 455 | maxLength={16_384} |
| 456 | onChange={(event) => updateDraft(field.name, event.target.value)} |
| 457 | /> |
| 458 | </label> |
| 459 | ))} |
| 460 | <Button |
| 461 | type="submit" |
| 462 | size="sm" |
| 463 | variant="outline" |
| 464 | className="w-fit" |
| 465 | disabled={disabled} |
| 466 | > |
| 467 | <T>Connect</T> |
| 468 | </Button> |
| 469 | </form> |
| 470 | ) : null} |
| 471 | {url && (interaction?.type === "browser" ? interaction.acceptsCallback : !interaction) ? ( |
| 472 | <form |
| 473 | className="grid gap-2 py-2 text-sm leading-normal" |
| 474 | onSubmit={(event) => { |
| 475 | event.preventDefault(); |
| 476 | if (!auth?.flowId || !values.callback?.trim()) return; |
| 477 | void run(() => |
| 478 | complete({ |
| 479 | environmentId, |
| 480 | input: { instanceId, flowId: auth.flowId!, callbackUrl: values.callback! }, |
| 481 | }), |
| 482 | ).then((sent) => { |
| 483 | if (sent) setDraft({ id: "", values: {} }); |
| 484 | }); |
| 485 | }} |
| 486 | > |
| 487 | <label className="grid gap-1"> |
| 488 | <T>If the final localhost page does not load, paste its full URL here.</T> |
| 489 | <Input |
| 490 | size="sm" |
| 491 | id={`provider-callback-${instanceId}`} |
| 492 | type="url" |
| 493 | autoComplete="off" |
| 494 | value={values.callback ?? ""} |
| 495 | disabled={disabled} |
| 496 | maxLength={16_384} |
| 497 | onChange={(event) => updateDraft("callback", event.target.value)} |
| 498 | /> |
| 499 | </label> |
| 500 | <Button |
| 501 | type="submit" |
| 502 | size="sm" |
| 503 | variant="outline" |
| 504 | className="w-fit" |
| 505 | disabled={disabled || !values.callback?.trim()} |
| 506 | > |
| 507 | <T>Continue</T> |
| 508 | </Button> |
| 509 | </form> |
| 510 | ) : null} |
| 511 | {error || query.error ? ( |
| 512 | <p role="alert" className="py-2 text-xs text-destructive"> |
| 513 | {error ?? query.error} |
| 514 | </p> |
| 515 | ) : null} |
| 516 | </> |
| 517 | ) : null} |
| 518 | </SettingsRow> |
| 519 | ); |
| 520 | } |