import { parseQuotaFailureCode } from "../../../src/providers/quota-types"; import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, type MutableRefObject } from "react"; import type { AccountLoadState, AccountQuotaReading } from "../components/provider-workspace/types"; import { createBoundedFetch } from "../bounded-fetch"; import { isApiTargetCaptureCurrent, targetFetch, type ApiTargetCapture } from "../api"; import { errorMessageFrom } from "../api-error"; import { useRenderTargetCapture } from "../use-render-target-capture"; import { confirmAction, requestTextValue } from "../action-dialogs"; import { credentialAliasRejection, CREDENTIAL_ALIAS_MAX_LENGTH } from "../credential-alias"; import { accountNeedsReauth } from "../oauth-health-display"; import { oauthAccountDisplayLabel } from "../provider-workspace/auth"; import { oauthCredentialSlot } from "../../../src/oauth/credential-siblings"; import { oauthLabel } from "../pages/providers-shared"; /** The owner whose accounts a shared-login row (Kimi (Responses)) acts on, else undefined. */ const sharedAccountsOwner = (provider: string): string | undefined => { const slot = oauthCredentialSlot(provider); return slot !== provider ? slot : undefined; }; import { affinityResetRetries, subscribeAffinityResetRetries, rememberAffinityResetRetry, beginAffinityResetOperation } from "../provider-affinity-reset-retries"; export interface Config { port: number; defaultProvider: string; providers: Record; } export interface OAuthStatus { loggedIn: boolean; email?: string; error?: string; done?: boolean; needsReauth?: boolean; activeAccountId?: string | null } export interface OAuthAccount extends AccountQuotaReading { id: string; alias?: string; email?: string; accountLabel?: string; maskedLabel?: string; active: boolean; needsReauth?: boolean; autoSelectable?: boolean; skipReason?: "needs_reauth" | "paused" | "suspended" | "cooldown" | "quota_exhausted"; paused?: boolean; pauseDetails?: { reason: string; pausedAt: number }; autoSwitchThresholdOverride?: number | null; autoSwitchThreshold?: number; effectiveAutoSwitchThreshold?: number; expiresAt?: number; plan?: string | null; health?: { status: "healthy" | "cooldown" | "reauth_required" | "warning"; reason?: string; until?: string }; healthLabel?: string; healthSummary?: string; healthAction?: string; } export interface ApiKeyEntry extends AccountQuotaReading { id: string; label?: string; masked: string; active: boolean; disabled?: boolean; pauseDetails?: { reason: string; pausedAt: number } } export interface AccountSelectionTarget { provider: string; kind: "oauth" | "api-key" } function selectionRows(rows: T[], id: string | null | undefined): T[] { return id === undefined ? rows : rows.map(row => ({ ...row, active: row.id === id })); } /** An invalidation read changes membership/selection, not quota probe state. */ function mergeRosterRows(rows: T[], previous: T[]): T[] { const prior = new Map(previous.map(row => [row.id, row])); return mergeQuotaRows(rows, previous, false).map(row => supportsQuotaRead(row) ? { ...row, quotaPending: prior.get(row.id)?.quotaPending ?? false, quotaUnavailable: prior.get(row.id)?.quotaMode === row.quotaMode ? prior.get(row.id)?.quotaUnavailable ?? false : false, // #8397: the roster read carries no read time; keep the last reading's reason and time. quotaReadAt: prior.get(row.id)?.quotaMode === row.quotaMode ? prior.get(row.id)?.quotaReadAt : undefined, quotaUnknownReason: prior.get(row.id)?.quotaMode === row.quotaMode ? prior.get(row.id)?.quotaUnknownReason : undefined, quotaFailure: row.quotaMode === "probe" && prior.get(row.id)?.quotaMode === row.quotaMode && prior.get(row.id)?.quotaUnavailable ? parseQuotaFailureCode(prior.get(row.id)?.quotaFailure) : undefined, } : row); } /** A probe started before a newer roster may update quota only on surviving IDs. */ function mergeLateQuotaRows(rows: T[], enriched: T[]): T[] { const byId = new Map(enriched.map(row => [row.id, row])); return rows.map(row => { const incoming = byId.get(row.id); if (!incoming || incoming.quotaMode !== row.quotaMode) return row; const quota = mergeQuotaRows([incoming], [row], true)[0]; return { ...row, quota: quota.quota, quotaPending: quota.quotaPending, quotaUnavailable: quota.quotaUnavailable, quotaFailure: quota.quotaFailure, quotaReadAt: quota.quotaReadAt, quotaUnknownReason: quota.quotaUnknownReason }; }); } type QuotaRow = AccountQuotaReading & { id: string }; const supportsQuotaRead = (row: AccountQuotaReading) => row.quotaMode === "probe" || row.quotaMode === "passive"; function mergeQuotaRows(rows: T[], previous: T[], enriched: boolean): T[] { const prior = new Map(previous.map(row => [row.id, row])); return rows.map(row => { const supported = supportsQuotaRead(row); // Legacy/unknown mode must not acquire synthetic flags that would override // a provider report or imply that a quota probe is supported. if (!supported && row.quotaMode !== "unsupported") return { ...row, quotaMode: undefined, quotaPending: undefined, quotaFailure: undefined }; // Only surviving credential IDs can retain omitted data. Explicit null is an // authoritative invalidation, including failed/expired credential readings. const retain = supported && (!enriched || row.quotaUnavailable === true); return { ...row, quota: row.quotaMode === "unsupported" ? null : row.quota !== undefined ? row.quota : retain ? prior.get(row.id)?.quota : undefined, quotaPending: !enriched && row.quotaMode === "probe", quotaUnavailable: enriched ? row.quotaUnavailable === true : false, quotaFailure: enriched && row.quotaMode === "probe" && row.quotaUnavailable === true ? parseQuotaFailureCode(row.quotaFailure) : undefined, }; }); } function unavailableQuotaRows(rows: T[], attempted?: T[]): T[] { const attemptedModes = attempted && new Map(attempted.map(row => [row.id, row.quotaMode])); return rows.map(row => supportsQuotaRead(row) && (!attemptedModes || attemptedModes.get(row.id) === row.quotaMode) ? { ...row, quotaUnavailable: true, quotaPending: false, quotaFailure: undefined } : row); } /** Pure aggregate map used by Providers overview / rail attention state. */ export function buildActiveAccountNeedsReauthMap( accountSets: Record, codexActiveNeedsReauth = false, ): Record { const map: Record = {}; for (const [provider, set] of Object.entries(accountSets)) { const active = set.accounts.find(a => a.active) ?? set.accounts.find(a => a.id === set.activeAccountId); if (accountNeedsReauth(active)) map[provider] = true; } if (codexActiveNeedsReauth) map.openai = true; return map; } /** * One bounded roster read, released on every path. * * This lives outside the hook on purpose: a `try`/`finally` inside the memoized callback * makes the compiler unable to infer its dependencies, so it reports the capture the read * actually uses as an extra dependency. The callback below stays a plain delegation. */ async function readRosterWithCleanup( capture: ApiTargetCapture, url: string, signal: AbortSignal | undefined, requests: Set, ): Promise { const bounded = createBoundedFetch(20_000); const abort = () => bounded.controller.abort(); if (signal?.aborted) abort(); signal?.addEventListener("abort", abort, { once: true }); requests.add(bounded.controller); try { const response = await targetFetch(capture, url, { signal: bounded.signal }); if (!response.ok) throw new Error(String(response.status)); const data = await response.json() as T; if (bounded.signal.aborted) throw new Error("Quota roster deadline exceeded"); return data; } finally { bounded.clear(); signal?.removeEventListener("abort", abort); requests.delete(bounded.controller); } } export function useProviderAccountPools(deps: { apiBase: string; /** Stable logical target; a relay apiBase can stay the same across a re-pair. */ targetKey?: string; t: (key: string, ...args: unknown[]) => string; config: Config | null; oauthStatus: Record; aliveRef: MutableRefObject; notify: (msg: string, ok?: boolean) => void; fetchConfig: () => Promise; fetchOauth: () => Promise; fetchProviderQuotas: (refresh?: boolean) => Promise; codexActiveNeedsReauth: boolean; invalidateOauthStatusReads?: (provider: string, blocked?: boolean) => boolean; setOauthStatus?: React.Dispatch>>; }) { const { apiBase, targetKey = apiBase, t, config, aliveRef, notify, fetchConfig, fetchOauth, fetchProviderQuotas, codexActiveNeedsReauth, invalidateOauthStatusReads, setOauthStatus, } = deps; // Keep the historical apiBase key for standalone callers; only a logical target that // differs from the request base needs the additional discriminator. const serverIdentity = targetKey === apiBase ? apiBase : `${apiBase}\u0000${targetKey}`; // This hook's render owns the target for its actions. A module target change that has // not re-rendered the hook cannot retarget a stale action. const renderCapture = useRenderTargetCapture(apiBase, targetKey); const accountTarget = useMemo(() => ({ apiBase, targetKey }), [apiBase, targetKey]); const [accountStateTarget, setAccountStateTarget] = useState(accountTarget); const [accountSets, setAccountSets] = useState>({}); const [accountLoadStates, setAccountLoadStates] = useState>({}); const [switchingAccounts, setSwitchingAccounts] = useState>({}); const switchingAccount = Object.values(switchingAccounts)[0] ?? null; const setSwitchingAccount = (target: { provider: string; accountId: string } | null) => setSwitchingAccounts(target ? { [target.provider]: target } : {}); const [pausingAccounts, setPausingAccounts] = useState>({}); const pendingAffinityResets = useSyncExternalStore(subscribeAffinityResetRetries, () => affinityResetRetries(serverIdentity), () => affinityResetRetries(serverIdentity)); const pausingAccount = Object.values(pausingAccounts)[0] ?? null; const [openAccounts, setOpenAccounts] = useState>({}); const [keyPools, setKeyPools] = useState>({}); const [addingKeyFor, setAddingKeyFor] = useState(null); const [newKeyValue, setNewKeyValue] = useState(""); // A key typed on one target must not be submittable on another. Clear the add-key form // when the logical target changes; it is not persisted anywhere. const [keyInputIdentity, setKeyInputIdentity] = useState(serverIdentity); if (keyInputIdentity !== serverIdentity) { setKeyInputIdentity(serverIdentity); setAddingKeyFor(null); setNewKeyValue(""); } const accountRequestGenerationRef = useRef>({}); const rosterGenerationRef = useRef>({}); const quotaGenerationRef = useRef>({}); const selectionMutationsRef = useRef(new Map()); const requestsRef = useRef(new Set()); const pausingAccountRef = useRef(new Map()); const switchingAccountRef = useRef(new Map()); const mountedRef = useRef(true); const serverRef = useRef(serverIdentity); // The target identity this render owns, readable by an in-flight read's continuation. // A layout effect is early enough: a superseded read settles in a microtask after the // commit's layout phase but before its passive effects, so a passive ref write would // still name the old target when the response lands. const apiBaseRef = useRef(apiBase); useLayoutEffect(() => { apiBaseRef.current = apiBase; }, [apiBase]); useLayoutEffect(() => { serverRef.current = serverIdentity; }, [serverIdentity]); /** May a completion still write the surface this render owns? */ const captureIsCurrent = useCallback((capture: ApiTargetCapture) => isApiTargetCaptureCurrent(capture) && capture.apiBase === apiBaseRef.current, []); // The rows clear while rendering, so the new target never paints the previous target's // accounts or keys for a frame. A passive-effect flush is too late for a read that settles // in the commit's microtask gap; a render-phase reset is the same shape as the Codex pool. const [syncedServerIdentity, setSyncedServerIdentity] = useState(serverIdentity); if (syncedServerIdentity !== serverIdentity) { setSyncedServerIdentity(serverIdentity); setAccountSets({}); setAccountLoadStates({}); setSwitchingAccounts({}); setPausingAccounts({}); setKeyPools({}); setAccountStateTarget(accountTarget); } useEffect(() => { const generations = accountRequestGenerationRef.current; const requests = requestsRef.current; const rosterGenerations = rosterGenerationRef.current; const quotaGenerations = quotaGenerationRef.current; const mutations = selectionMutationsRef.current; const pausingOwners = pausingAccountRef.current; const switchingOwners = switchingAccountRef.current; mountedRef.current = true; return () => { mountedRef.current = false; for (const key of Object.keys(generations)) generations[key] += 1; for (const key of Object.keys(rosterGenerations)) rosterGenerations[key] += 1; for (const key of Object.keys(quotaGenerations)) quotaGenerations[key] += 1; mutations.clear(); pausingOwners.clear(); switchingOwners.clear(); for (const controller of requests) controller.abort(); requests.clear(); }; }, [apiBase, accountTarget, serverIdentity]); // Provider lists this instance has already fetched for. The deferred loads below are deliberately // uncancellable, and StrictMode double-invokes their effects, so dedupe by list identity here. const accountSetsKeyRef = useRef(null); const keyPoolsKeyRef = useRef(null); // A read belongs to this render's target too. A stale capture is refused before // fetch, so a stale render cannot paint the new target's roster. const readRoster = useCallback(async (url: string, signal?: AbortSignal): Promise => await readRosterWithCleanup(renderCapture, url, signal, requestsRef.current), [renderCapture]); const fetchAccountSets = useCallback(async (providers: string[], refresh = false): Promise => { if (!aliveRef.current || !mountedRef.current || serverRef.current !== serverIdentity || !captureIsCurrent(renderCapture)) return false; const uniqueProviders = [...new Set(providers)]; setAccountLoadStates(current => { const next = { ...current }; for (const provider of uniqueProviders) next[provider] = "loading"; return next; }); const results = await Promise.all(uniqueProviders.map(async provider => { const key = `oauth:${provider}`; const generation = (accountRequestGenerationRef.current[key] ?? 0) + 1; accountRequestGenerationRef.current[key] = generation; const rosterGeneration = (rosterGenerationRef.current[key] ?? 0) + 1; rosterGenerationRef.current[key] = rosterGeneration; const currentRequest = () => aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(renderCapture) && accountRequestGenerationRef.current[key] === generation; const currentRoster = () => currentRequest() && rosterGenerationRef.current[key] === rosterGeneration; const url = `${apiBase}/api/oauth/accounts?provider=${encodeURIComponent(provider)}`; try { // Cheap local read first so account switch / reauth / remove controls appear // even when Anthropic's usage endpoint is slow or timing out. const data = await readRoster<{ activeAccountId?: string | null; accounts?: OAuthAccount[] }>(url); if (!Array.isArray(data.accounts)) throw new Error("Invalid account roster"); if (!currentRequest()) return false; const rows = selectionRows(data.accounts, data.activeAccountId); setAccountSets(current => currentRoster() ? { ...current, [provider]: { activeAccountId: data.activeAccountId ?? null, accounts: mergeQuotaRows(rows, current[provider]?.accounts ?? [], false), } } : current); setAccountLoadStates(current => currentRoster() ? { ...current, [provider]: selectionMutationsRef.current.has(key) ? "loading" : "ready" } : current); if (!rows.some(supportsQuotaRead)) return true; const enrich = async (): Promise => { // Manual selection invalidates roster reads, not a per-ID quota probe already sent. const quotaGeneration = (quotaGenerationRef.current[key] ?? 0) + 1; quotaGenerationRef.current[key] = quotaGeneration; const currentQuota = () => aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(renderCapture) && quotaGenerationRef.current[key] === quotaGeneration; try { const quotaData = await readRoster<{ activeAccountId?: string | null; accounts?: OAuthAccount[] }>(`${url}"a=1${refresh ? "&refresh=1" : ""}`); if (!Array.isArray(quotaData.accounts)) throw new Error("Invalid account quota roster"); if (!currentQuota()) return false; const enriched = selectionRows(quotaData.accounts, quotaData.activeAccountId); setAccountSets(current => !currentQuota() ? current : !currentRoster() ? { ...current, [provider]: { ...current[provider], accounts: mergeLateQuotaRows(current[provider]?.accounts ?? [], enriched) }, } : { ...current, [provider]: { activeAccountId: quotaData.activeAccountId === undefined ? data.activeAccountId ?? null : quotaData.activeAccountId, accounts: mergeQuotaRows(enriched, current[provider]?.accounts ?? [], true), }, }); // Paused accounts are intentionally skipped; keep their row state without // failing refreshes that successfully probed another quota-capable account. const refreshable = enriched.filter(row => row.paused !== true && supportsQuotaRead(row)); return !refreshable.some(row => row.quotaUnavailable === true); } catch { if (!currentQuota()) return false; setAccountSets(current => currentQuota() && current[provider] ? { ...current, [provider]: { ...current[provider], accounts: unavailableQuotaRows( current[provider].accounts, rows.filter(row => row.paused !== true), ), }, } : current); return false; } }; if (refresh) return await enrich(); void enrich(); return true; } catch { if (!currentRoster()) return false; setAccountLoadStates(current => currentRoster() ? { ...current, [provider]: "error" } : current); setAccountSets(current => currentRoster() && current[provider] ? { ...current, [provider]: { ...current[provider], accounts: unavailableQuotaRows(current[provider].accounts) }, } : current); return false; } })); return results.every(Boolean); }, [aliveRef, apiBase, captureIsCurrent, readRoster, renderCapture, serverIdentity]); const fetchKeyPools = useCallback(async (providers: string[], refresh = false): Promise => { if (!aliveRef.current || !mountedRef.current || serverRef.current !== serverIdentity || !captureIsCurrent(renderCapture)) return false; const results = await Promise.all([...new Set(providers)].map(async name => { const key = `key:${name}`; const generation = (accountRequestGenerationRef.current[key] ?? 0) + 1; accountRequestGenerationRef.current[key] = generation; const rosterGeneration = (rosterGenerationRef.current[key] ?? 0) + 1; rosterGenerationRef.current[key] = rosterGeneration; const currentRequest = () => aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(renderCapture) && accountRequestGenerationRef.current[key] === generation; const currentRoster = () => currentRequest() && rosterGenerationRef.current[key] === rosterGeneration; const url = `${apiBase}/api/providers/keys?name=${encodeURIComponent(name)}`; const failed = () => { if (currentRoster()) setKeyPools(current => currentRoster() ? { ...current, [name]: unavailableQuotaRows(current[name] ?? []) } : current); return false; }; try { const data = await readRoster<{ activeId?: string | null; keys?: ApiKeyEntry[] }>(url); if (!Array.isArray(data.keys)) throw new Error("Invalid key roster"); if (!currentRequest()) return false; const rows = selectionRows(data.keys, data.activeId); setKeyPools(current => currentRoster() ? { ...current, [name]: mergeQuotaRows(rows, current[name] ?? [], false) } : current); if (!rows.some(supportsQuotaRead)) return true; const enrich = async (): Promise => { const quotaGeneration = (quotaGenerationRef.current[key] ?? 0) + 1; quotaGenerationRef.current[key] = quotaGeneration; const currentQuota = () => aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(renderCapture) && quotaGenerationRef.current[key] === quotaGeneration; try { const data = await readRoster<{ activeId?: string | null; keys?: ApiKeyEntry[] }>(`${url}"a=1${refresh ? "&refresh=1" : ""}`); if (!Array.isArray(data.keys)) throw new Error("Invalid key quota roster"); if (!currentQuota()) return false; const enriched = selectionRows(data.keys, data.activeId); setKeyPools(current => currentQuota() ? { ...current, [name]: currentRoster() ? mergeQuotaRows(enriched, current[name] ?? [], true) : mergeLateQuotaRows(current[name] ?? [], enriched) } : current); const refreshable = enriched.filter(row => row.disabled !== true && supportsQuotaRead(row)); return !refreshable.some(row => row.quotaUnavailable === true); } catch { if (currentQuota()) setKeyPools(current => currentQuota() ? { ...current, [name]: unavailableQuotaRows(current[name] ?? [], rows.filter(row => row.disabled !== true && supportsQuotaRead(row))) } : current); return currentQuota() && !rows.some(row => row.disabled !== true && supportsQuotaRead(row)); } }; if (refresh) return await enrich(); void enrich(); return true; } catch { return failed(); } })); return results.every(Boolean); }, [apiBase, aliveRef, captureIsCurrent, readRoster, renderCapture, serverIdentity]); const refreshAccountRosters = useCallback(async (target?: AccountSelectionTarget, signal?: AbortSignal): Promise => { if (!aliveRef.current || !mountedRef.current || serverRef.current !== serverIdentity || !captureIsCurrent(renderCapture) || signal?.aborted) return false; const targets: AccountSelectionTarget[] = target ? [target] : Object.entries(config?.providers ?? {}).flatMap(([provider, p]) => p.authMode === "oauth" && provider !== "openai" ? [{ provider, kind: "oauth" as const }] : p.hasApiKey && p.authMode !== "oauth" && p.authMode !== "forward" ? [{ provider, kind: "api-key" as const }] : []); const results = await Promise.all(targets.map(async ({ provider, kind }) => { const key = `${kind === "oauth" ? "oauth" : "key"}:${provider}`; // PUT settlement always reconciles, including events received while it is pending. if (selectionMutationsRef.current.has(key)) return false; const generation = (rosterGenerationRef.current[key] ?? 0) + 1; rosterGenerationRef.current[key] = generation; const ownsRoster = () => aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(renderCapture) && rosterGenerationRef.current[key] === generation && !selectionMutationsRef.current.has(key); const currentRequest = () => ownsRoster() && !signal?.aborted; if (kind === "oauth") setAccountLoadStates(current => currentRequest() ? { ...current, [provider]: "loading" } : current); try { if (kind === "oauth") { const data = await readRoster<{ activeAccountId?: string | null; accounts?: OAuthAccount[] }>( `${apiBase}/api/oauth/accounts?provider=${encodeURIComponent(provider)}`, signal); if (!Array.isArray(data.accounts)) throw new Error("Invalid account roster"); if (!currentRequest()) return false; const rows = selectionRows(data.accounts, data.activeAccountId); setAccountSets(current => currentRequest() ? { ...current, [provider]: { activeAccountId: data.activeAccountId === undefined ? rows.find(row => row.active)?.id ?? null : data.activeAccountId, accounts: mergeRosterRows(rows, current[provider]?.accounts ?? []), } } : current); setAccountLoadStates(current => currentRequest() ? { ...current, [provider]: "ready" } : current); } else { const data = await readRoster<{ activeId?: string | null; keys?: ApiKeyEntry[] }>( `${apiBase}/api/providers/keys?name=${encodeURIComponent(provider)}`, signal); if (!Array.isArray(data.keys) || !currentRequest()) return false; const rows = selectionRows(data.keys, data.activeId); setKeyPools(current => currentRequest() ? { ...current, [provider]: mergeRosterRows(rows, current[provider] ?? []) } : current); } return true; } catch { // A missed invalidation read does not change quota health; recovery retries it. if (kind === "oauth") setAccountLoadStates(current => ownsRoster() ? { ...current, [provider]: "error" } : current); return false; } })); return results.every(Boolean); }, [aliveRef, apiBase, captureIsCurrent, config, readRoster, renderCapture, serverIdentity]); const invalidateSelectionReads = (provider: string, kind: AccountSelectionTarget["kind"]) => { const key = `${kind === "oauth" ? "oauth" : "key"}:${provider}`; accountRequestGenerationRef.current[key] = (accountRequestGenerationRef.current[key] ?? 0) + 1; rosterGenerationRef.current[key] = (rosterGenerationRef.current[key] ?? 0) + 1; if (kind === "oauth" && aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(renderCapture)) { setAccountLoadStates(current => ({ ...current, [provider]: "loading" })); } // The independent quota generation still owns pending/error flags for surviving IDs. return key; }; const beginAccountLogout = (provider: string): (() => void) | null => { const key = `oauth:${provider}`; if (!aliveRef.current || !mountedRef.current || serverRef.current !== serverIdentity || !captureIsCurrent(renderCapture) || selectionMutationsRef.current.has(key)) return null; invalidateSelectionReads(provider, "oauth"); const owner = Symbol(); selectionMutationsRef.current.set(key, owner); return () => { if (selectionMutationsRef.current.get(key) !== owner) return; invalidateSelectionReads(provider, "oauth"); selectionMutationsRef.current.delete(key); }; }; const setAccountPoolThreshold = async (provider: string, threshold: number): Promise => { if (!aliveRef.current || !mountedRef.current || serverRef.current !== serverIdentity || !captureIsCurrent(renderCapture)) return false; // Pool settings and roster reads describe one server value. Invalidate older reads before // publishing the confirmed save, then refresh so a concurrent external write can still win. invalidateSelectionReads(provider, "oauth"); setAccountSets(current => { const existing = current[provider]; return !existing ? current : { ...current, [provider]: { ...existing, accounts: existing.accounts.map(row => ({ ...row, autoSwitchThreshold: threshold, effectiveAutoSwitchThreshold: typeof row.autoSwitchThresholdOverride === "number" ? row.autoSwitchThresholdOverride : threshold, })) } }; }); // Restart the full roster path, not only the cheap membership read. The settings card can // resolve before the initial account load; cancelling that load without replacing its quota // enrichment would leave usage bars empty until a manual refresh or remount. return fetchAccountSets([provider]); }; const switchAccount = async (provider: string, account: OAuthAccount, retryPending = false) => { const capture = renderCapture; if (account.active && !retryPending || account.needsReauth || account.paused || switchingAccountRef.current.has(provider) || pausingAccountRef.current.has(provider) || selectionMutationsRef.current.has(`oauth:${provider}`)) return; const target = { provider, accountId: account.id }; switchingAccountRef.current.set(provider, target); setSwitchingAccounts(current => ({ ...current, [provider]: target })); const key = invalidateSelectionReads(provider, "oauth"); const mutation = Symbol(); selectionMutationsRef.current.set(key, mutation); const currentMutation = () => aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture) && selectionMutationsRef.current.get(key) === mutation; const label = accountLabel(provider, account); const receipt = beginAffinityResetOperation(serverIdentity, provider); try { const res = await targetFetch(capture, `${apiBase}/api/oauth/accounts/active`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ provider, accountId: account.id }) }); if (!res.ok) { const failure = await res.json().catch(() => ({})) as { activeAccountId?: string | null; code?: string; retryable?: boolean; selectionCommitted?: boolean }; if (failure.code === "affinity_reset_not_persisted" && failure.retryable === true && failure.selectionCommitted === true) { receipt(() => ({ kind: "active", accountId: account.id }), true, { kind: "unpersisted", accountId: account.id }); if (!currentMutation()) return; const selected = failure.activeAccountId ?? account.id; setAccountSets(current => current[provider] ? { ...current, [provider]: { ...current[provider], activeAccountId: selected, accounts: selectionRows(current[provider].accounts, selected), } } : current); notify(t("prov.affinityResetPending"), false); } else if (currentMutation()) notify(t("prov.accountSwitchFail"), false); return; } const result = await res.json().catch(() => ({})) as { activeAccountId?: string | null }; receipt(() => undefined, true, { kind: "confirmed" }); if (!currentMutation()) return; invalidateSelectionReads(provider, "oauth"); const selected = result.activeAccountId === undefined ? account.id : result.activeAccountId; setAccountSets(current => current[provider] ? { ...current, [provider]: { ...current[provider], activeAccountId: selected, accounts: selectionRows(current[provider].accounts, selected), } } : current); selectionMutationsRef.current.delete(key); const refreshed = await refreshAccountRosters({ provider, kind: "oauth" }); await Promise.all([fetchOauth(), fetchProviderQuotas(true)]); if (!refreshed) { notify(t("pws.accountsLoadFailed"), false); return; } notify(t("prov.accountSwitched", { email: label }), true); } catch { if (currentMutation()) notify(t("prov.accountSwitchFail"), false); } finally { receipt(); // An uncommitted failure contributes no retry-state change. if (currentMutation()) { invalidateSelectionReads(provider, "oauth"); selectionMutationsRef.current.delete(key); void refreshAccountRosters({ provider, kind: "oauth" }); } if (switchingAccountRef.current.get(provider) === target) { switchingAccountRef.current.delete(provider); if (aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture)) setSwitchingAccounts(current => { const next = { ...current }; delete next[provider]; return next; }); } } }; const setAccountThreshold = async (provider: string, account: OAuthAccount, threshold: number | null): Promise => { const capture = renderCapture; const key = `oauth:${provider}`; if (switchingAccountRef.current.has(provider) || pausingAccountRef.current.has(provider) || selectionMutationsRef.current.has(key)) return false; const mutationKey = invalidateSelectionReads(provider, "oauth"); const mutation = Symbol(); selectionMutationsRef.current.set(mutationKey, mutation); const currentMutation = () => aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture) && selectionMutationsRef.current.get(mutationKey) === mutation; const label = accountLabel(provider, account); try { const bounded = createBoundedFetch(20_000); requestsRef.current.add(bounded.controller); let result: Pick; try { const res = await targetFetch(capture, `${apiBase}/api/oauth/accounts/auto-switch`, { method: "PUT", headers: { "Content-Type": "application/json" }, signal: bounded.signal, body: JSON.stringify({ provider, accountId: account.id, threshold }), }); if (!res.ok) throw new Error("account threshold write failed"); result = await res.json() as typeof result; if (bounded.signal.aborted) throw new Error("account threshold deadline exceeded"); } finally { bounded.clear(); requestsRef.current.delete(bounded.controller); } const validPercent = (value: unknown) => typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 100; if (!result || (result.autoSwitchThresholdOverride !== null && !validPercent(result.autoSwitchThresholdOverride)) || !validPercent(result.autoSwitchThreshold) || !validPercent(result.effectiveAutoSwitchThreshold)) throw new Error("invalid threshold response"); if (!currentMutation()) return false; invalidateSelectionReads(provider, "oauth"); setAccountSets(current => { const existing = current[provider]; return !existing ? current : { ...current, [provider]: { ...existing, accounts: existing.accounts.map(row => row.id === account.id ? { ...row, autoSwitchThresholdOverride: result.autoSwitchThresholdOverride, autoSwitchThreshold: result.autoSwitchThreshold, effectiveAutoSwitchThreshold: result.effectiveAutoSwitchThreshold } : row) } }; }); return true; } catch { if (currentMutation()) notify(t("accountPool.autoSwitchUpdateFailed", { email: label }), false); return false; } finally { if (currentMutation()) { invalidateSelectionReads(provider, "oauth"); selectionMutationsRef.current.delete(mutationKey); void refreshAccountRosters({ provider, kind: "oauth" }); } } }; const pauseAccount = async (provider: string, account: OAuthAccount, paused: boolean, retryAffinityReset = false) => { const capture = renderCapture; // Pausing a shared account also stops the owner row (the Kimi Chat row) from using it: say so first. const owner = sharedAccountsOwner(provider); if (owner && paused && !retryAffinityReset) { const consented = await confirmAction({ message: t("prov.accountPauseConfirmShared", { email: accountLabel(provider, account), provider: oauthLabel(owner) }), confirmLabel: t("codexAuth.pause"), tone: "danger", }); if (!consented || !aliveRef.current || !mountedRef.current || serverRef.current !== serverIdentity || !captureIsCurrent(capture)) return; } if (switchingAccountRef.current.has(provider) || pausingAccountRef.current.has(provider) || selectionMutationsRef.current.has(`oauth:${provider}`)) return; const target = { provider, accountId: account.id }; pausingAccountRef.current.set(provider, target); setPausingAccounts(current => ({ ...current, [provider]: { ...target, paused } })); const key = invalidateSelectionReads(provider, "oauth"); const mutation = Symbol(); selectionMutationsRef.current.set(key, mutation); const currentMutation = () => aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture) && selectionMutationsRef.current.get(key) === mutation; const label = accountLabel(provider, account); const receipt = beginAffinityResetOperation(serverIdentity, provider); let result: { activeAccountId?: string | null; activeAccountChanged?: boolean; code?: string; retryable?: boolean; pauseCommitted?: boolean }; try { const res = await targetFetch(capture, `${apiBase}/api/oauth/accounts/pause`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ provider, accountId: account.id, paused, ...(retryAffinityReset ? { retryAffinityReset: true } : {}) }), }); if (res.ok) { result = await res.json().catch(() => ({})) as typeof result; } else { result = await res.json().catch(() => ({})) as typeof result; if (result.code !== "affinity_reset_not_persisted" || result.retryable !== true || result.pauseCommitted !== true) { if (currentMutation()) notify(t(paused ? "codexAuth.pauseFailed" : "codexAuth.resumeFailed", { email: label }), false); return; } } const committedResetFailure = !res.ok; if (committedResetFailure) receipt(() => ({ kind: "pause", accountId: account.id, paused }), true, { kind: "unpersisted", accountId: account.id }); else if (retryAffinityReset || result.activeAccountChanged) receipt(() => undefined, true, { kind: "confirmed" }); else receipt(pending => pending?.kind === "pause" && pending.accountId === account.id ? { ...pending, paused } : pending); if (!currentMutation()) return; invalidateSelectionReads(provider, "oauth"); const selected = result.activeAccountId === undefined ? accountSets[provider]?.activeAccountId ?? null : result.activeAccountId; setAccountSets(current => { const existing = current[provider]; if (!existing) return current; const accounts = existing.accounts.map(row => row.id === account.id ? { ...row, paused } : row); return { ...current, [provider]: { activeAccountId: selected, accounts: selectionRows(accounts, selected) } }; }); if (committedResetFailure) { notify(t("prov.affinityResetPending"), false); return; } selectionMutationsRef.current.delete(key); } catch { if (currentMutation()) notify(t(paused ? "codexAuth.pauseFailed" : "codexAuth.resumeFailed", { email: label }), false); return; } finally { receipt(); // Only an unconfirmed save still holds the registered mutation here. if (currentMutation()) { invalidateSelectionReads(provider, "oauth"); selectionMutationsRef.current.delete(key); void refreshAccountRosters({ provider, kind: "oauth" }); } if (pausingAccountRef.current.get(provider) === target) { pausingAccountRef.current.delete(provider); if (aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture)) setPausingAccounts(current => { const next = { ...current }; delete next[provider]; return next; }); } } // The server persisted the change. A failed follow-up read is not a failed pause: keep // the saved state visible and report only the refresh failure. if (!aliveRef.current || !mountedRef.current || serverRef.current !== serverIdentity || !captureIsCurrent(capture)) return; notify(t(paused ? "codexAuth.pauseSucceeded" : "codexAuth.resumeSucceeded", { email: label }), true); try { const refreshed = await refreshAccountRosters({ provider, kind: "oauth" }); if (result.activeAccountChanged) await Promise.all([fetchOauth(), fetchProviderQuotas(true)]); if (!refreshed) notify(t("pws.accountsLoadFailed"), false); } catch { if (aliveRef.current && mountedRef.current) notify(t("pws.accountsLoadFailed"), false); } }; const retryAffinityResetOnly = async (provider: string, accountId: string) => { const capture = renderCapture; const key = `oauth:${provider}`; if (selectionMutationsRef.current.has(key) || switchingAccountRef.current.has(provider) || pausingAccountRef.current.has(provider)) return; const retry = { kind: "reset" as const, accountId }; rememberAffinityResetRetry(serverIdentity, provider, retry); const rememberedRetry = affinityResetRetries(serverIdentity)[provider]; const target = { provider, accountId }; const mutation = Symbol(); invalidateSelectionReads(provider, "oauth"); selectionMutationsRef.current.set(key, mutation); switchingAccountRef.current.set(provider, target); setSwitchingAccounts(current => ({ ...current, [provider]: target })); const currentRetry = () => aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture) && selectionMutationsRef.current.get(key) === mutation && affinityResetRetries(serverIdentity)[provider] === rememberedRetry; const receipt = beginAffinityResetOperation(serverIdentity, provider); try { const res = await targetFetch(capture, `${apiBase}/api/oauth/accounts/affinity-reset`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ provider }) }); if (!res.ok) { const failure = (await res.json().catch(() => ({})) ?? {}) as { code?: string; retryable?: boolean }; if (failure.code === "affinity_reset_not_persisted" && failure.retryable === true) { receipt(undefined, false, { kind: "unpersisted", accountId }); } if (currentRetry()) notify(t("prov.affinityResetPending"), false); return; } const result = (await res.json().catch(() => ({})) ?? {}) as { affinityResetConfirmed?: boolean }; const showResult = currentRetry(); if (result.affinityResetConfirmed === true) { receipt(() => undefined, true, { kind: "confirmed" }); } if (showResult) { const complete = result.affinityResetConfirmed === true && !affinityResetRetries(serverIdentity)[provider]; notify(t(complete ? "prov.affinityResetComplete" : "prov.affinityResetPending"), complete); } } catch { if (currentRetry()) notify(t("prov.affinityResetPending"), false); } finally { receipt(); if (selectionMutationsRef.current.get(key) === mutation) { selectionMutationsRef.current.delete(key); if (aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture)) { invalidateSelectionReads(provider, "oauth"); void refreshAccountRosters({ provider, kind: "oauth" }); } } if (switchingAccountRef.current.get(provider) === target) { switchingAccountRef.current.delete(provider); if (aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture)) { setSwitchingAccounts(current => { const next = { ...current }; delete next[provider]; return next; }); } } } }; const retryAffinityReset = async (provider: string) => { const pending = pendingAffinityResets[provider]; if (!pending || !aliveRef.current || !mountedRef.current || serverRef.current !== serverIdentity || !captureIsCurrent(renderCapture)) return; if (pending.kind === "reset") return retryAffinityResetOnly(provider, pending.accountId); const account = accountSets[provider]?.accounts.find(row => row.id === pending.accountId); if (!account) { if (accountLoadStates[provider] === "ready") return retryAffinityResetOnly(provider, pending.accountId); notify(t("prov.affinityResetRetryUnavailable"), false); return; } if (pending.kind === "active" && (account.paused || account.needsReauth)) { notify(t("prov.affinityResetRetryUnavailable"), false); return; } if (pending.kind === "active") await switchAccount(provider, account, true); else await pauseAccount(provider, account, pending.paused, true); }; const switchApiKey = async (provider: string, entry: ApiKeyEntry) => { const capture = renderCapture; if (entry.active && !entry.disabled || switchingAccountRef.current.has(provider) || pausingAccountRef.current.has(provider) || selectionMutationsRef.current.has(`key:${provider}`)) return; const target = { provider, accountId: entry.id }; switchingAccountRef.current.set(provider, target); setSwitchingAccounts(current => ({ ...current, [provider]: target })); const key = invalidateSelectionReads(provider, "api-key"); const mutation = Symbol(); selectionMutationsRef.current.set(key, mutation); const currentMutation = () => aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture) && selectionMutationsRef.current.get(key) === mutation; let resumed = false; try { if (entry.disabled) { const resumeResponse = await targetFetch(capture, `${apiBase}/api/providers/keys/pause`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: provider, id: entry.id, paused: false }) }); if (!currentMutation()) return; if (!resumeResponse.ok) { notify(t("prov.keySwitchFail"), false); return; } resumed = true; } const res = await targetFetch(capture, `${apiBase}/api/providers/keys/active`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: provider, id: entry.id }) }); if (!currentMutation()) return; if (!res.ok) { const failure = await res.json().catch(() => ({})) as { error?: string }; if (currentMutation()) { notify(resumed ? t("prov.keyResumedSwitchFailed") : errorMessageFrom(failure, t("prov.keySwitchFail"), t("prov.targetChanged")), false); } return; } const data = await res.json().catch(() => ({})) as { activeId?: string | null }; if (!currentMutation()) return; invalidateSelectionReads(provider, "api-key"); const selected = data.activeId === undefined ? entry.id : data.activeId; setKeyPools(current => current[provider] ? { ...current, [provider]: selectionRows(current[provider], selected) } : current); notify(t("prov.keySwitched", { key: entry.label ?? entry.masked }), true); void fetchConfig(); void fetchProviderQuotas(true); } catch { if (currentMutation()) notify(t(resumed ? "prov.keyResumedSwitchFailed" : "prov.keySwitchFail"), false); } finally { if (switchingAccountRef.current.get(provider) === target) { switchingAccountRef.current.delete(provider); if (aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture)) { setSwitchingAccounts(current => { const next = { ...current }; delete next[provider]; return next; }); } } if (currentMutation()) { invalidateSelectionReads(provider, "api-key"); selectionMutationsRef.current.delete(key); void refreshAccountRosters({ provider, kind: "api-key" }); } } }; const pauseApiKey = async (provider: string, entry: ApiKeyEntry, paused: boolean) => { const capture = renderCapture; if (switchingAccountRef.current.has(provider) || pausingAccountRef.current.has(provider) || selectionMutationsRef.current.has(`key:${provider}`)) return; const target = { provider, accountId: entry.id }; pausingAccountRef.current.set(provider, target); setPausingAccounts(current => ({ ...current, [provider]: { ...target, paused } })); const key = invalidateSelectionReads(provider, "api-key"); const mutation = Symbol(); selectionMutationsRef.current.set(key, mutation); const currentMutation = () => aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture) && selectionMutationsRef.current.get(key) === mutation; const label = entry.label ?? entry.masked; let result: { activeId?: string | null; activeAccountId?: string | null; activeAccountChanged?: boolean }; try { const res = await targetFetch(capture, `${apiBase}/api/providers/keys/pause`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: provider, id: entry.id, paused }), }); if (!currentMutation()) return; if (!res.ok) { const failure = await res.json().catch(() => ({})) as { error?: string }; if (currentMutation()) { notify(errorMessageFrom(failure, t(paused ? "codexAuth.pauseFailed" : "codexAuth.resumeFailed", { email: label }), t("prov.targetChanged")), false); } return; } result = await res.json().catch(() => ({})) as { activeId?: string | null; activeAccountId?: string | null; activeAccountChanged?: boolean }; if (!currentMutation()) return; invalidateSelectionReads(provider, "api-key"); setKeyPools(current => { const existing = current[provider]; if (!existing) return current; const rows = existing.map(row => row.id === entry.id ? { ...row, disabled: paused, ...(paused ? {} : { pauseDetails: undefined }) } : row); const idx = rows.findIndex(row => row.id === entry.id); const ordered = idx >= 0 ? [...rows.slice(idx + 1), ...rows.slice(0, idx)] : rows; const fallbackSelected = paused && entry.active ? ordered.find(row => !row.disabled)?.id ?? null : !paused && !rows.some(row => row.active && !row.disabled) ? entry.id : rows.find(row => row.active)?.id ?? null; const selected = result.activeId !== undefined ? result.activeId : result.activeAccountId !== undefined ? result.activeAccountId : fallbackSelected; return { ...current, [provider]: selectionRows(rows, selected) }; }); selectionMutationsRef.current.delete(key); } catch { if (currentMutation()) notify(t(paused ? "codexAuth.pauseFailed" : "codexAuth.resumeFailed", { email: label }), false); return; } finally { if (currentMutation()) { invalidateSelectionReads(provider, "api-key"); selectionMutationsRef.current.delete(key); void refreshAccountRosters({ provider, kind: "api-key" }); } if (pausingAccountRef.current.get(provider) === target) { pausingAccountRef.current.delete(provider); if (aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture)) { setPausingAccounts(current => { const next = { ...current }; delete next[provider]; return next; }); } } } if (!aliveRef.current || !mountedRef.current || serverRef.current !== serverIdentity || !captureIsCurrent(capture)) return; notify(t(paused ? "codexAuth.pauseSucceeded" : "codexAuth.resumeSucceeded", { email: label }), true); try { const refreshed = await refreshAccountRosters({ provider, kind: "api-key" }); if (result.activeAccountChanged ?? true) await Promise.all([fetchConfig(), fetchProviderQuotas(true)]); if (!refreshed) notify(t("pws.accountsLoadFailed"), false); } catch { if (aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture)) { notify(t("pws.accountsLoadFailed"), false); } } }; const removeApiKey = async (provider: string, entry: ApiKeyEntry) => { const capture = renderCapture; const currentMutation = () => aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture); const consented = await confirmAction({ message: t("prov.keyRemoveConfirm", { key: entry.label ?? entry.masked }), confirmLabel: t("common.remove"), tone: "danger", }); if (!consented || !currentMutation()) return; const res = await targetFetch(capture, `${apiBase}/api/providers/keys?name=${encodeURIComponent(provider)}&id=${encodeURIComponent(entry.id)}`, { method: "DELETE" }); if (!currentMutation()) return; if (res.ok) { notify(t("prov.keyRemoved", { key: entry.label ?? entry.masked }), true); void fetchKeyPools(Object.keys(keyPools)); void fetchConfig(); void fetchProviderQuotas(true); } }; const addApiKeyValue = async (provider: string, rawKey: string): Promise => { const capture = renderCapture; const currentMutation = () => aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture); const key = rawKey.trim(); if (!key) return false; try { const res = await targetFetch(capture, `${apiBase}/api/providers/keys`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name: provider, key }) }); if (!currentMutation()) return false; if (!res.ok) { const data = await res.json().catch(() => ({})) as { error?: string }; notify(errorMessageFrom(data, t("prov.keyAddFail"), t("prov.targetChanged")), false); return false; } notify(t("prov.keyAdded", { name: provider }), true); setAddingKeyFor(null); await Promise.all([ fetchKeyPools(Object.keys(keyPools).includes(provider) ? Object.keys(keyPools) : [...Object.keys(keyPools), provider]), fetchConfig(), fetchProviderQuotas(true), ]); return true; } catch { notify(t("prov.keyAddFail"), false); return false; } }; const addApiKey = async (provider: string) => { const ok = await addApiKeyValue(provider, newKeyValue); if (ok) setNewKeyValue(""); }; const editCredentialAlias = async (provider: string, type: "oauth" | "api-key", id: string, current?: string) => { const capture = renderCapture; const currentMutation = () => aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture); const entered = await requestTextValue({ message: t("prov.aliasPrompt"), initialValue: current ?? "", maxLength: CREDENTIAL_ALIAS_MAX_LENGTH, validate: value => credentialAliasRejection(value, t), }); if (entered === null) return; const alias = entered.trim(); const response = await targetFetch(capture, type === "oauth" ? `${apiBase}/api/oauth/accounts/alias` : `${apiBase}/api/providers/keys/alias`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(type === "oauth" ? { provider, accountId: id, alias } : { name: provider, id, alias }), }); if (!currentMutation()) return; if (!response.ok) { const data = await response.json().catch(() => ({})) as { error?: string }; notify(errorMessageFrom(data, t("prov.aliasSaveFailed"), t("prov.targetChanged")), false); return; } if (type === "oauth") await fetchAccountSets([provider]); else await fetchKeyPools(Object.keys(keyPools).includes(provider) ? Object.keys(keyPools) : [...Object.keys(keyPools), provider]); notify(t("prov.aliasSaved"), true); }; const accountLabel = (provider: string, account: OAuthAccount) => oauthAccountDisplayLabel( accountSets[provider]?.accounts ?? [account], account, t, ); const removeAccount = async (provider: string, account: OAuthAccount) => { const capture = renderCapture; const label = accountLabel(provider, account); const owner = sharedAccountsOwner(provider); const consented = await confirmAction({ message: owner ? t("prov.accountRemoveConfirmShared", { email: label, provider: oauthLabel(owner) }) : t("prov.accountRemoveConfirm", { email: label }), confirmLabel: t("common.remove"), tone: "danger", }); const key = `oauth:${provider}`; if (!consented || !aliveRef.current || !mountedRef.current || serverRef.current !== serverIdentity || !captureIsCurrent(capture)) return; if (selectionMutationsRef.current.has(key) || switchingAccountRef.current.has(provider) || pausingAccountRef.current.has(provider)) return; invalidateSelectionReads(provider, "oauth"); const mutation = Symbol(); selectionMutationsRef.current.set(key, mutation); const statusBlocked = invalidateOauthStatusReads?.(provider, true) === true; const clearStatus = () => setOauthStatus?.(current => { if (!(provider in current)) return current; const next = { ...current }; delete next[provider]; return next; }); if (statusBlocked) clearStatus(); let statusSettled = false; const settleStatus = () => { if (statusSettled || !statusBlocked) return; statusSettled = true; if (invalidateOauthStatusReads?.(provider, false) !== true) return; clearStatus(); void fetchOauth().catch(() => {}); }; const pending = affinityResetRetries(serverIdentity)[provider]; const current = () => aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture) && selectionMutationsRef.current.get(key) === mutation; let committed = false; const receipt = beginAffinityResetOperation(serverIdentity, provider); try { const res = await targetFetch(capture, `${apiBase}/api/oauth/accounts?provider=${encodeURIComponent(provider)}&id=${encodeURIComponent(account.id)}${pending ? "&retryAffinityReset=true" : ""}`, { method: "DELETE" }); let result: { code?: string; retryable?: boolean; deletionCommitted?: boolean; affinityResetConfirmed?: boolean }; let partial = false; if (res.ok) result = (await res.json().catch(() => ({})) ?? {}) as typeof result; else { result = (await res.json().catch(() => ({})) ?? {}) as typeof result; partial = result.code === "affinity_reset_not_persisted" && result.retryable === true && result.deletionCommitted === true; if (!partial) { if (current()) { if (result.deletionCommitted === false) notify(t("prov.accountRemoveFail", { email: label }), false); else notify(t("prov.accountRemoveUnverified", { email: label }), false); } return; } } settleStatus(); committed = true; if (partial) receipt(() => ({ kind: "reset", accountId: account.id }), true, { kind: "unpersisted", accountId: account.id }); else if (result.affinityResetConfirmed === true) receipt(() => undefined, true, { kind: "confirmed" }); else receipt(latest => latest?.accountId === account.id ? { kind: "reset", accountId: account.id } : latest); if (!current()) return; if (partial) { notify(t("prov.affinityResetPending"), false); } else { notify(t("prov.accountRemoved", { email: label }), true); } await fetchAccountSets([provider]); if (!statusBlocked) void fetchOauth().catch(() => { if (aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture)) notify(t("pws.accountsLoadFailed"), false); }); await fetchProviderQuotas(true); } catch { if (current()) notify(t(committed ? "pws.accountsLoadFailed" : "prov.accountRemoveUnverified", { email: label }), false); } finally { settleStatus(); receipt(); if (selectionMutationsRef.current.get(key) === mutation) { selectionMutationsRef.current.delete(key); if (aliveRef.current && mountedRef.current && serverRef.current === serverIdentity && captureIsCurrent(capture)) { invalidateSelectionReads(provider, "oauth"); void refreshAccountRosters({ provider, kind: "oauth" }); } } } }; const oauthCardProviders = useMemo( () => config ? Object.entries(config.providers).filter(([, p]) => p.authMode === "oauth").map(([n]) => n) : [], [config], ); useEffect(() => { if (oauthCardProviders.length === 0) return; // Deferred by a microtask, not a timer: a timer had to be cancelled in cleanup, so a mount // followed by an immediate unmount (tab switch, provider list churn) issued no request and // never retried. A microtask keeps the state update out of the effect body while still // guaranteeing the request goes out. // Keyed on the provider list because this effect re-runs whenever that memo changes, and // StrictMode double-invokes it on mount; an uncancellable microtask would otherwise duplicate. const key = `${serverIdentity}:${apiBase}:${oauthCardProviders.join(",")}`; if (accountSetsKeyRef.current === key) return; accountSetsKeyRef.current = key; void Promise.resolve().then(() => { void fetchAccountSets(oauthCardProviders); }); }, [apiBase, fetchAccountSets, oauthCardProviders, serverIdentity]); const keyCardProviders = useMemo( () => config ? Object.entries(config.providers).filter(([, p]) => p.hasApiKey && p.authMode !== "oauth" && p.authMode !== "forward").map(([n]) => n) : [], [config], ); useEffect(() => { if (keyCardProviders.length === 0) return; const key = `${serverIdentity}:${apiBase}:${keyCardProviders.join(",")}`; if (keyPoolsKeyRef.current === key) return; keyPoolsKeyRef.current = key; void Promise.resolve().then(() => { void fetchKeyPools(keyCardProviders); }); }, [apiBase, fetchKeyPools, keyCardProviders, serverIdentity]); const activeAccountNeedsReauth = useMemo( () => buildActiveAccountNeedsReauthMap(accountSets, codexActiveNeedsReauth), [accountSets, codexActiveNeedsReauth], ); return { accountSets: accountStateTarget === accountTarget ? accountSets : {}, accountLoadStates: accountStateTarget === accountTarget ? accountLoadStates : {}, switchingAccount, pausingAccount, switchingAccounts, pausingAccounts, pendingAffinityResets, retryAffinityReset, openAccounts, keyPools: accountStateTarget === accountTarget ? keyPools : {}, addingKeyFor, newKeyValue, setAccountSets, setAccountLoadStates, setSwitchingAccount, setOpenAccounts, setKeyPools, setAddingKeyFor, setNewKeyValue, fetchAccountSets, fetchKeyPools, refreshAccountRosters, beginAccountLogout, switchAccount, pauseAccount, setAccountPoolThreshold, setAccountThreshold, switchApiKey, pauseApiKey, removeApiKey, addApiKeyValue, addApiKey, editCredentialAlias, removeAccount, oauthCardProviders, keyCardProviders, activeAccountNeedsReauth, }; }