import { anthropicSubscriptionLabel } from "../../../../src/providers/anthropic-subscription"; import { anthropicInstanceRowShapeMatches, isAnthropicInstanceId } from "../../../../src/providers/anthropic-instance-id"; /** * ProviderAuthPanel — OAuth accounts, API-key pool, and forward-auth * embedding for the workspace Settings tab (WP091). Consumes WP040+WP060 * handlers via props-down; no internal auth machinery. */ import { useEffect, useMemo, useRef, useState } from "react"; import { useT, useI18n } from "../../i18n/shared"; import { formatAccountPauseTooltip } from "../../account-pause-display"; import { IconLock, IconRefresh, IconTrash } from "../../icons"; import type { WorkspaceItem } from "../../provider-workspace/catalog"; import { oauthAccountDisplayLabel, providerAuthSurface } from "../../provider-workspace/auth"; import { oauthCredentialSlot } from "../../../../src/oauth/credential-siblings"; import { oauthLabel } from "../../pages/providers-shared"; import { displayAccountId } from "../../lib/privacy"; import AccountAutoSwitchControl from "../AccountAutoSwitchControl"; import { formatOAuthHealthLabel, formatOAuthHealthSummary, oauthHealthBadgeClass, oauthHealthIsCooldown, oauthHealthShowsReauth, } from "../../oauth-health-display"; import CodexAccountPool from "../CodexAccountPool"; import AnthropicAccountPoolSettings from "./AnthropicAccountPoolSettings"; import { LoginHint as LoginHintView } from "../login-url-block"; import { OpenBrowserPrefToggle } from "../open-browser-pref-toggle"; import ProviderAccountQuota from "./ProviderAccountQuota"; import { GrokCouponBadge, GrokResetCouponModal } from "./GrokResetCoupons"; import { AnthropicGrantBadge, AnthropicResetGrantModal } from "./AnthropicResetGrants"; import type { CodexAccountPoolController } from "../../hooks/useCodexAccountPool"; import { useGrokResetCoupons } from "../../hooks/useGrokResetCoupons"; import { useAnthropicResetGrants } from "../../hooks/useAnthropicResetGrants"; import { Switch } from "../../ui"; import { kiroSkipReasonKey } from "../../kiro-device-login-helpers"; import { isApiTargetCaptureCurrent, targetFetch, type ApiTargetCapture } from "../../api"; import { useRenderTargetCapture } from "../../use-render-target-capture"; import KiroDeviceLoginDialog from "../KiroDeviceLoginDialog"; import OAuthTosWarningModal from "../OAuthTosWarningModal"; import { oauthRiskAcknowledgementBody } from "../../oauth-tos-risk"; import type { AccountLoadState, OAuthAccountRow, ApiKeyRow, LoginHint, ProviderAuthHandlers, ProviderUpdateCallback, } from "./types"; const COCKPIT_IMPORT_MAX_BYTES = 256 * 1024; const EMPTY_OAUTH_ACCOUNTS: OAuthAccountRow[] = []; const EMPTY_API_KEYS: ApiKeyRow[] = []; /** * One predicate for "this row cannot spend a coupon right now". The read set and * the badge must agree: a row fetched here and hidden there is a billing RPC * spent on a 401. */ function accountShowsReauth(account: OAuthAccountRow): boolean { return Boolean(account.needsReauth) || oauthHealthShowsReauth(account.health?.status); } function XaiChatOptInControl({ initialState, onUpdateProvider, }: { initialState: NonNullable; onUpdateProvider?: ProviderUpdateCallback; }) { const t = useT(); const [state, setState] = useState(initialState); const [seenInitialState, setSeenInitialState] = useState(initialState); const [saving, setSaving] = useState(false); const [error, setError] = useState(""); if (initialState !== seenInitialState) { setSeenInitialState(initialState); setState(initialState); } const mixed = state === "mixed"; const toggle = async () => { if (!onUpdateProvider || saving) return; const next = state === false; setSaving(true); setError(""); try { const result = await onUpdateProvider("xai", { xaiResponsesOptIn: next }); if (!result.ok) { setError(result.error ?? t("prov.updateFail")); return; } setState(result.xaiResponsesOptInState ?? next); } catch { setError(t("prov.networkError")); } finally { setSaving(false); } }; return (
{t("pws.xaiChatOptIn")} {t("pws.xaiChatOptInDesc")} {mixed && {t("pws.xaiChatOptInMixed")}} {error && {error}}
{ void toggle(); }} disabled={!onUpdateProvider || saving} label={t("pws.xaiChatOptIn")} />
); } type CockpitImportResult = { importedCount: number; updatedCount: number; failedCount: number; unsupportedCount: number; }; const COCKPIT_RESULT_KEYS = new Set([ "totalCount", "importedCount", "updatedCount", "failedCount", "unsupportedCount", "results", ]); const COCKPIT_RESULT_STATUSES = new Set(["imported", "updated", "failed", "unsupported"]); const COCKPIT_STATUS_CODES: Record> = { imported: new Set(["imported"]), updated: new Set(["updated"]), failed: new Set([ "invalid_record", "credential_rejected", "identity_mismatch", "missing_project", "persist_failed", ]), unsupported: new Set(["unsupported_provider", "unsupported_format"]), }; function isPlainObject(value: unknown): value is Record { if (!value || typeof value !== "object" || Array.isArray(value)) return false; const prototype = Object.getPrototypeOf(value); return prototype === Object.prototype || prototype === null; } function isSafeCount(value: unknown): value is number { return typeof value === "number" && Number.isSafeInteger(value) && value >= 0; } function safeCockpitImportResult(value: unknown): CockpitImportResult | null { if (!isPlainObject(value) || Object.keys(value).some(key => !COCKPIT_RESULT_KEYS.has(key))) return null; const { totalCount, importedCount, updatedCount, failedCount, unsupportedCount, results } = value; if ( !isSafeCount(totalCount) || !isSafeCount(importedCount) || !isSafeCount(updatedCount) || !isSafeCount(failedCount) || !isSafeCount(unsupportedCount) || !Array.isArray(results) || results.length !== totalCount || importedCount + updatedCount + failedCount + unsupportedCount !== totalCount ) return null; const observed = { imported: 0, updated: 0, failed: 0, unsupported: 0 }; for (const [index, result] of results.entries()) { if (!isPlainObject(result) || Object.keys(result).some(key => !["index", "status", "code"].includes(key))) return null; const status = String(result.status); const code = String(result.code); if (result.index !== index || !COCKPIT_RESULT_STATUSES.has(status)) return null; const allowedCodes = COCKPIT_STATUS_CODES[status]; if (!allowedCodes?.has(code)) return null; observed[status as keyof typeof observed] += 1; } if ( observed.imported !== importedCount || observed.updated !== updatedCount || observed.failed !== failedCount || observed.unsupported !== unsupportedCount ) return null; return { importedCount, updatedCount, failedCount, unsupportedCount }; } export default function ProviderAuthPanel({ item, apiBase, targetKey, oauth, accounts = EMPTY_OAUTH_ACCOUNTS, keys = EMPTY_API_KEYS, accountLoadState = "ready", switchingAccountId = null, pausingAccountId = null, busy = false, loginHint, loginCapture, authHandlers, onCodexActiveNeedsReauthChange, codexController, onUpdateProvider, }: { item: WorkspaceItem; apiBase: string; /** Logical dashboard target; the panel's rows and actions belong to it. */ targetKey?: string; oauth?: { loggedIn: boolean; email?: string; error?: string }; accounts?: OAuthAccountRow[]; keys?: ApiKeyRow[]; accountLoadState?: AccountLoadState; switchingAccountId?: string | null; pausingAccountId?: string | null; busy?: boolean; loginHint?: LoginHint | null; loginCapture?: ApiTargetCapture; authHandlers?: ProviderAuthHandlers; onCodexActiveNeedsReauthChange?: (needs: boolean) => void; onUpdateProvider?: ProviderUpdateCallback; /** Shared Codex account state owned by Providers (WP3). */ codexController?: CodexAccountPoolController; }) { const t = useT(); // The panel's render owns the target for its own import action. const renderCapture = useRenderTargetCapture(apiBase, targetKey); const { locale } = useI18n(); const [addingKey, setAddingKey] = useState(false); const [kiroChooser, setKiroChooser] = useState<{ addAccount: boolean } | null>(null); const kiroLoginTriggerRef = useRef(null); const kiroAddTriggerRef = useRef(null); const openLogin = (addAccount: boolean) => { if (item.name === "kiro") setKiroChooser({ addAccount }); else void authHandlers?.onLogin(item.name, addAccount); }; const [newKey, setNewKey] = useState(""); const [keyBusy, setKeyBusy] = useState(false); const [importBusy, setImportBusy] = useState(false); const [importStatus, setImportStatus] = useState<"idle" | "invalid" | "failed" | "complete">("idle"); const [importResult, setImportResult] = useState(null); const importFileRef = useRef(null); // An imported Antigravity credential carries the same Google account-ban risk as a login, so // the import goes through the same warning dialog. The acknowledgement is never armed ahead of // a pick: every chosen file, whether through the button or the input reached directly, is held // here and imported only from that file's own Continue. Nothing can carry an earlier acceptance // over to a later selection, whatever the engine does with the picker's cancel and focus events. const [importWarning, setImportWarning] = useState<{ file: File } | null>(null); const [manualCode, setManualCode] = useState(""); const [manualCodeBusy, setManualCodeBusy] = useState(false); const [manualCodeMsg, setManualCodeMsg] = useState(""); const [manualCodeOk, setManualCodeOk] = useState(true); const connectionIdentity = JSON.stringify([apiBase, item.name, accounts.find(account => account.active)?.id, keys.find(key => key.active)?.id]); const [quotaRefreshState, setQuotaRefreshState] = useState<{ identity: string; refreshing: boolean; result: { ok: boolean; text: string } | null; }>({ identity: connectionIdentity, refreshing: false, result: null }); const refreshingQuota = quotaRefreshState.identity === connectionIdentity && quotaRefreshState.refreshing; const quotaRefreshResult = quotaRefreshState.identity === connectionIdentity ? quotaRefreshState.result : null; const quotaRefreshGeneration = useRef(0); useEffect(() => { quotaRefreshGeneration.current += 1; return () => { quotaRefreshGeneration.current += 1; }; }, [connectionIdentity]); const onRefreshQuota = authHandlers?.onRefreshQuota; const surface = providerAuthSurface({ ...item, hasApiKey: item.hasApiKey || keys.length > 0 }); const isOauth = surface === "oauth-accounts"; const isKeyAuth = surface === "api-keys"; // Grok reset coupons live behind a billing RPC rather than the quota payload, // so the xAI rows read them once per roster instead of riding the quota probe. // The gate names the OAuth surface here rather than relying on the roster // loader three files away to leave `accounts` empty for key-auth xAI. const grokCouponsEnabled = isOauth && item.name === "xai" && accounts.length > 0; const grokAccountIds = useMemo( () => (grokCouponsEnabled ? accounts.filter(account => !accountShowsReauth(account)).map(account => account.id) : []), [grokCouponsEnabled, accounts], ); const grokCoupons = useGrokResetCoupons({ apiBase, accountIds: grokAccountIds, enabled: grokCouponsEnabled }); const [couponAccount, setCouponAccount] = useState(null); // Claude usage resets ride a separate usage read, like the Grok coupons above. const isAnthropicPool = isAnthropicInstanceId(item.name) && anthropicInstanceRowShapeMatches(item.name, item); const claudeGrantsEnabled = isOauth && isAnthropicPool && accounts.length > 0; const claudeAccountIds = useMemo( () => (claudeGrantsEnabled ? accounts.filter(account => !accountShowsReauth(account)).map(account => account.id) : []), [claudeGrantsEnabled, accounts], ); const claudeGrants = useAnthropicResetGrants({ apiBase, provider: isAnthropicInstanceId(item.name) ? item.name : "anthropic", accountIds: claudeAccountIds, enabled: claudeGrantsEnabled }); // The open reset dialog belongs to the pool it was opened in. Switching server or pool // hides it during render rather than resetting it from an effect. const grantScope = `${apiBase}\0${item.name}`; const [grantSelection, setGrantSelection] = useState<{ scope: string; account: OAuthAccountRow } | null>(null); const grantAccount = grantSelection?.scope === grantScope ? grantSelection.account : null; const setGrantAccount = (account: OAuthAccountRow | null) => { setGrantSelection(account ? { scope: grantScope, account } : null); }; const refreshQuota = async () => { if (!onRefreshQuota || refreshingQuota) return; const generation = ++quotaRefreshGeneration.current; // Cleared on click so a previous "refreshed" cannot sit under a later failure. setQuotaRefreshState({ identity: connectionIdentity, refreshing: true, result: null }); try { const ok = await onRefreshQuota(item.name); if (quotaRefreshGeneration.current === generation) setQuotaRefreshState({ identity: connectionIdentity, refreshing: false, result: { ok, text: t(ok ? "pws.quotaCheckCompleted" : "codexAuth.quotaRefreshFailed") } }); } catch { if (quotaRefreshGeneration.current === generation) setQuotaRefreshState({ identity: connectionIdentity, refreshing: false, result: { ok: false, text: t("codexAuth.quotaRefreshFailed") } }); } }; if (surface === "codex-accounts") { return (

{t("pws.availableAccounts")}

); } if (!surface || !authHandlers) return null; // A shared-login row (Kimi (Responses)) signs in through its owner, so its flow is keyed by the owner. const loginOwner = oauthCredentialSlot(item.name); const hintForThis = loginHint?.provider === loginOwner ? loginHint : null; // Paste fallback for when the browser cannot reach the loopback callback // (remote dashboard, SSH, blocked localhost). A rejected paste reports why and // leaves the flow running, so the user can correct it and try again. const submitManualCode = async () => { const input = manualCode.trim(); if (!input || manualCodeBusy) return; if (!loginCapture) { setManualCodeOk(false); setManualCodeMsg(t("prov.targetChanged")); return; } setManualCodeBusy(true); setManualCodeMsg(""); try { const res = await targetFetch(loginCapture, `${apiBase}/api/oauth/login/code`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ provider: loginOwner, input }), }); if (!isApiTargetCaptureCurrent(loginCapture)) { setManualCodeOk(false); setManualCodeMsg(t("prov.targetChanged")); return; } if (!res.ok) { const data = await res.json().catch(() => ({})) as { error?: string }; setManualCodeOk(false); setManualCodeMsg(data.error === "target_changed" ? t("prov.targetChanged") : t("prov.pasteFail", { error: data.error || res.statusText })); return; } setManualCode(""); setManualCodeOk(true); setManualCodeMsg(t("prov.pasteOk")); } catch { setManualCodeOk(false); setManualCodeMsg(t("modal.networkError")); } finally { setManualCodeBusy(false); } }; const loggedIn = (accountLoadState === "ready" && accounts.length > 0) || oauth?.loggedIn === true; const canLogout = loggedIn || (accountLoadState === "error" && oauth?.loggedIn !== false); const activeReauthAccount = accounts.find(a => a.active && a.needsReauth); const activeNeedsReauth = Boolean(activeReauthAccount); const quotaRows = isOauth ? accounts : keys; const canRefreshQuota = Boolean(onRefreshQuota) && !(quotaRows.length > 0 && quotaRows.every(row => row.quotaMode === "unsupported")); const submitKey = async () => { const key = newKey.trim(); if (!key) return; setKeyBusy(true); try { const ok = await authHandlers.onAddApiKey(item.name, key); if (ok) { setNewKey(""); setAddingKey(false); } } finally { setKeyBusy(false); } }; const importCockpitFile = async (file: File | undefined, acknowledged: boolean) => { if (!file || importBusy) return; if (!acknowledged) { setImportWarning({ file }); return; } setImportBusy(true); setImportStatus("idle"); setImportResult(null); const capture = renderCapture; try { if (!file.name.toLowerCase().endsWith(".json") || file.size > COCKPIT_IMPORT_MAX_BYTES) { setImportStatus("invalid"); return; } let document: unknown; try { document = JSON.parse(await file.text()) as unknown; } catch { setImportStatus("invalid"); return; } const response = await targetFetch(capture, `${apiBase}/api/oauth/accounts/import`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ provider: "google-antigravity", format: "cockpit-tools", document, ...oauthRiskAcknowledgementBody("google-antigravity", acknowledged) }), }); if (!response.ok) { setImportStatus("failed"); return; } const result = safeCockpitImportResult(await response.json().catch(() => null)); if (!result) { setImportStatus("failed"); return; } setImportResult(result); setImportStatus("complete"); // The validated import is complete independently of the best-effort list refresh. // The account-pool owner reports refresh failure through accountLoadState, which // remains visible beside this completed import result. try { await authHandlers.onRetryAccounts?.(item.name); } catch { /* Preserve the completed import state; accountLoadState owns refresh errors. */ } } catch { setImportStatus("failed"); } finally { if (importFileRef.current) importFileRef.current.value = ""; setImportBusy(false); } }; return (
{/* The refresh control is in the section HEAD, not only at the foot of the list. Every account renders a stack of 5-hour/weekly/Fable bars, so with two accounts the footer copy sits well below the fold: an operator looking straight at stale bars had to scroll past all of them to find the button that re-reads them. The header keeps it beside the numbers it refreshes; the footer copy stays where it is, next to "Add account", because that is the account-management cluster. */}

{isOauth ? t("pws.availableAccounts") : t("pws.apiKeys")}

{((isOauth && loggedIn) || isKeyAuth) && canRefreshQuota && (
{quotaRefreshResult && ( {quotaRefreshResult.text} )}
)}
{item.name === "xai" && ( )} {isOauth && ( <> {isAnthropicPool && ( { void authHandlers?.onAccountPoolThreshold?.(item.name, threshold); }} /> )} {item.name === "google-antigravity" && (
{t("pws.cockpitImportDescription")}
{ void importCockpitFile(event.currentTarget.files?.[0], false); }} />
{importWarning && ( { setImportWarning(null); if (importFileRef.current) importFileRef.current.value = ""; }} onContinue={() => { const pending = importWarning; setImportWarning(null); void importCockpitFile(pending.file, true); }} /> )}
{importStatus === "invalid" && t("pws.cockpitImportInvalid")} {importStatus === "failed" && t("pws.cockpitImportFailed")} {importStatus === "complete" && importResult && t("pws.cockpitImportComplete", { imported: importResult.importedCount, updated: importResult.updatedCount, failed: importResult.failedCount, unsupported: importResult.unsupportedCount, })}
)}
{!busy && } {busy && hintForThis && (
)} {authHandlers.pendingAffinityResets?.[item.name] && (
{t("prov.affinityResetPending")} {authHandlers.onRetryAffinityReset && }
)} {accountLoadState === "loading" && accounts.length === 0 && (
)} {accountLoadState === "error" && (
{t("pws.accountsLoadFailed")} {authHandlers.onRetryAccounts && ( )}
)} {accounts.length > 0 && oauthCredentialSlot(item.name) !== item.name && ( // A shared-login row (Kimi (Responses)) lists its owner's accounts: every control below acts on them.
{t("pws.sharedAccountsNote", { provider: oauthLabel(oauthCredentialSlot(item.name)) })}
)} {accounts.length > 0 && (
    {accounts.map(account => { const label = oauthAccountDisplayLabel(accounts, account, t); const planLabel = isAnthropicPool ? anthropicSubscriptionLabel(account.plan) : item.name === "google-antigravity" ? account.plan : undefined; const switching = switchingAccountId === account.id; const pausing = pausingAccountId === account.id; const healthStatus = account.health?.status; const showReauth = accountShowsReauth(account); const inCooldown = oauthHealthIsCooldown(healthStatus); const maskedId = displayAccountId(account.id); const healthLabel = formatOAuthHealthLabel(t, account.health); const healthSummary = isAnthropicPool ? null : formatOAuthHealthSummary(t, item.name, account.id, account.health); return (
  • {typeof account.paused === "boolean" && authHandlers.onPauseAccount && ( )} {showReauth && ( )} {grokCouponsEnabled && !showReauth && ( setCouponAccount(account)} /> )} {claudeGrantsEnabled && !showReauth && ( setGrantAccount(account)} /> )}
    {isAnthropicPool && account.autoSwitchThresholdOverride !== undefined && account.autoSwitchThreshold !== undefined && authHandlers.onAccountThreshold && ( authHandlers.onAccountThreshold!(item.name, account, threshold)} /> )}
  • ); })}
)} {couponAccount && ( setCouponAccount(null)} /> )} {grantAccount && ( setGrantAccount(null)} /> )} {accountLoadState === "ready" && loggedIn && accounts.length === 0 && (
{t("pws.noAccounts")}
)} {loggedIn && (
{canRefreshQuota && ( )} {/* The result line lives in the section head only. Rendering it in both places would announce one refresh twice to a screen reader, since both spans carry role="status". */}
)} )} {item.name === "kiro" && kiroChooser && ( setKiroChooser(null)} onCli={addAccount => { void authHandlers.onLogin(item.name, addAccount); }} onSettled={authHandlers.onNativeLoginSettled} /> )} {isKeyAuth && ( <> {keys.length > 0 && (
    {keys.map(entry => { const switching = switchingAccountId === entry.id; const pausing = pausingAccountId === entry.id; return (
  • {authHandlers.onPauseApiKey && ( )}
  • );})}
)} {addingKey ? (
setNewKey(e.target.value)} placeholder={t("modal.apiKeyPlaceholder")} autoComplete="off" disabled={keyBusy} />
) : ( )} )}
); }