Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
93 changes: 93 additions & 0 deletions gui/src/components/QuotaLiveRefreshSetting.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { useId, useState } from "react";
import { useT } from "../i18n/shared";
import { clampNumberDraft } from "../clamp-draft";
import {
QUOTA_LIVE_REFRESH_MAX_SECONDS as MAX_SECONDS,
QUOTA_LIVE_REFRESH_MIN_SECONDS as MIN_SECONDS,
useQuotaLiveRefreshPref,
writeQuotaLiveRefreshPref,
} from "../quota-live-refresh-pref";
import { NumberStepper } from "./NumberStepper";

/** "Live quota updates": this browser's switch and interval for re-reading quota bars. */
export default function QuotaLiveRefreshSetting() {
const t = useT();
const descId = useId();
const pref = useQuotaLiveRefreshPref();
const [draft, setDraft] = useState(String(pref.intervalSeconds));
// Follow a change saved elsewhere (another tab, or this row's own commit).
const [shownSeconds, setShownSeconds] = useState(pref.intervalSeconds);
if (shownSeconds !== pref.intervalSeconds) {
setShownSeconds(pref.intervalSeconds);
setDraft(String(pref.intervalSeconds));
}

// Empty or non-numeric input keeps the saved interval and a number outside the range is
// clamped; either way the field then shows the interval actually in effect.
const commit = (value: string) => {
const seconds = value.trim() === "" ? Number.NaN : Number(value);
const saved = Number.isFinite(seconds) ? writeQuotaLiveRefreshPref({ ...pref, intervalSeconds: seconds }) : pref;
setDraft(String(saved.intervalSeconds));
};

return (
<div className="card card-row codex-auto-switch-card">
<div className="codex-auto-switch-copy">
<strong>{t("quotaLive.title")}</strong>
<div id={descId} className="card-sub">{t("quotaLive.hint")}</div>
</div>
<div className="codex-auto-switch-controls">
<label className="codex-auto-switch-threshold">
<span className="field-label">{t("quotaLive.interval")}</span>
<span className="codex-auto-switch-input-wrap">
<input
className="input mono codex-auto-switch-input"
type="number"
min={MIN_SECONDS}
max={MAX_SECONDS}
step={1}
inputMode="numeric"
value={draft}
disabled={!pref.enabled}
aria-label={t("quotaLive.intervalAria", { min: MIN_SECONDS, max: MAX_SECONDS })}
aria-describedby={descId}
onChange={(event) => setDraft(event.target.value)}
onBlur={(event) => commit(event.target.value)}
onKeyDown={(event) => {
if (event.nativeEvent.isComposing) return;
if (event.key === "Enter") {
event.preventDefault();
commit(event.currentTarget.value);
} else if (event.key === "Escape") {
event.preventDefault();
setDraft(String(pref.intervalSeconds));
}
}}
/>
<span className="codex-auto-switch-unit" aria-hidden="true">{t("quotaLive.unit")}</span>
<NumberStepper
disabled={!pref.enabled}
incrementLabel={t("quotaLive.intervalInc")}
decrementLabel={t("quotaLive.intervalDec")}
onIncrement={() => commit(clampNumberDraft(draft, 5, MIN_SECONDS, MAX_SECONDS))}
onDecrement={() => commit(clampNumberDraft(draft, -5, MIN_SECONDS, MAX_SECONDS))}
/>
</span>
</label>
<span className="codex-auto-switch-toggle-slot">
<button
type="button"
className={`toggle ${pref.enabled ? "on" : ""}`}
onClick={() => { writeQuotaLiveRefreshPref({ ...pref, enabled: !pref.enabled }); }}
aria-pressed={pref.enabled}
aria-label={t("quotaLive.title")}
aria-describedby={descId}
title={t("quotaLive.title")}
>
<span className="toggle-knob" />
</button>
</span>
</div>
</div>
);
}
5 changes: 5 additions & 0 deletions gui/src/components/provider-workspace/ProviderAuthPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ import ProviderAccountQuota from "./ProviderAccountQuota";
import { AccountProbeButton, AccountProbeResultLine } from "./AccountProbe";
import { ACCOUNT_PROBE_PROVIDERS, useAccountProbe } from "../../hooks/useAccountProbe";
import { AccountQuotaTable } from "./AccountQuotaTable";
import QuotaLiveRefreshSetting from "../QuotaLiveRefreshSetting";
import { accountQuotaFromReport } from "../../provider-workspace/report";
import { uncoveredWindows } from "../../provider-workspace/account-quota-table";
import { GrokCouponBadge, GrokResetCouponModal } from "./GrokResetCoupons";
Expand Down Expand Up @@ -499,6 +500,10 @@ export default function ProviderAuthPanel({
)}
</div>
<div className="pwi-auth-body">
{/* Shown only where live updates act: the account and key rows that carry a quota reading. */}
{((isOauth && loggedIn) || isKeyAuth) && quotaRows.some(row => row.quotaMode === "probe" || row.quotaMode === "passive") && (
<QuotaLiveRefreshSetting />
)}
{item.name === "xai" && (
<XaiChatOptInControl
initialState={item.xaiResponsesOptInState ?? true}
Expand Down
48 changes: 48 additions & 0 deletions gui/src/hooks/useProviderAccountPools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ 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";
import { useQuotaLiveRefresh } from "./useQuotaLiveRefresh";

/** The owner whose accounts a shared-login row (Kimi (Responses)) acts on, else undefined. */
const sharedAccountsOwner = (provider: string): string | undefined => {
Expand Down Expand Up @@ -177,10 +178,13 @@ export function useProviderAccountPools(deps: {
codexActiveNeedsReauth: boolean;
invalidateOauthStatusReads?: (provider: string, blocked?: boolean) => boolean;
setOauthStatus?: React.Dispatch<React.SetStateAction<Record<string, OAuthStatus>>>;
/** The provider whose account bars are on screen; live quota updates re-read only that one. */
liveQuotaProvider?: string | null;
}) {
const {
apiBase, targetKey = apiBase, t, config, aliveRef, notify,
fetchConfig, fetchOauth, fetchProviderQuotas, codexActiveNeedsReauth, invalidateOauthStatusReads, setOauthStatus,
liveQuotaProvider,
} = deps;
// Keep the historical apiBase key for standalone callers; only a logical target that
// differs from the request base needs the additional discriminator.
Expand Down Expand Up @@ -1115,6 +1119,50 @@ export function useProviderAccountPools(deps: {
void Promise.resolve().then(() => { void fetchKeyPools(keyCardProviders); });
}, [apiBase, fetchKeyPools, keyCardProviders, serverIdentity]);

/**
* Live quota updates for the provider on screen: the plain `&quota=1` read, never `&refresh=1`,
* so the server answers from its TTL cache and the readings live response headers keep current,
* and probes a credential again only after that cache entry expires.
* A tick waits out any read or mutation already in flight, sets no loading or pending state,
* writes quota fields onto surviving rows only (membership and selection stay with their own
* reads), and drops a failure, so a missed tick never replaces good bars with an error.
*/
const readLiveQuota = async (provider: string, kind: AccountSelectionTarget["kind"]) => {
const key = `${kind === "oauth" ? "oauth" : "key"}:${provider}`;
if (!aliveRef.current || !mountedRef.current || serverRef.current !== serverIdentity || !captureIsCurrent(renderCapture)
|| requestsRef.current.size > 0 || selectionMutationsRef.current.has(key)
|| switchingAccountRef.current.has(provider) || pausingAccountRef.current.has(provider)) return;
// Any later quota read, a manual refresh included, takes this generation over and wins.
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 {
if (kind === "oauth") {
const data = await readRoster<{ accounts?: OAuthAccount[] }>(`${apiBase}/api/oauth/accounts?provider=${encodeURIComponent(provider)}&quota=1`);
const enriched = data.accounts;
if (!Array.isArray(enriched) || !currentQuota()) return;
setAccountSets(current => currentQuota() && current[provider]
? { ...current, [provider]: { ...current[provider], accounts: mergeLateQuotaRows(current[provider].accounts, enriched) } } : current);
} else {
const data = await readRoster<{ keys?: ApiKeyEntry[] }>(`${apiBase}/api/providers/keys?name=${encodeURIComponent(provider)}&quota=1`);
const enriched = data.keys;
if (!Array.isArray(enriched) || !currentQuota()) return;
setKeyPools(current => currentQuota() && current[provider]
? { ...current, [provider]: mergeLateQuotaRows(current[provider], enriched) } : current);
}
} catch {
// The rows on screen stay as they are; the next tick or a manual refresh reads again.
}
};
useQuotaLiveRefresh(() => {
const provider = liveQuotaProvider;
if (!provider) return;
const kind = oauthCardProviders.includes(provider) ? "oauth" : keyCardProviders.includes(provider) ? "api-key" : null;
const rows = kind === "oauth" ? accountSets[provider]?.accounts : kind === "api-key" ? keyPools[provider] : undefined;
if (kind && rows?.some(supportsQuotaRead)) void readLiveQuota(provider, kind);
});

const activeAccountNeedsReauth = useMemo(
() => buildActiveAccountNeedsReauthMap(accountSets, codexActiveNeedsReauth),
[accountSets, codexActiveNeedsReauth],
Expand Down
21 changes: 21 additions & 0 deletions gui/src/hooks/useQuotaLiveRefresh.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { useEffect, useLayoutEffect, useRef } from "react";
import { useQuotaLiveRefreshPref } from "../quota-live-refresh-pref";
import { startVisibilityPoll } from "../visibility-poll";

/**
* Run `tick` on the viewer's "Live quota updates" cadence (quota-live-refresh-pref.ts).
*
* Off holds no timer at all, so a surface keeps exactly the refresh behavior it had before.
* The visibility poll owns the hidden rule: no timer while the dashboard is hidden, one make-up
* tick when it is shown again. The tick itself must be a non-forced re-read and must decide
* whether it may run now (a read or mutation already in flight); this hook only schedules it.
*/
export function useQuotaLiveRefresh(tick: () => void): void {
const { enabled, intervalSeconds } = useQuotaLiveRefreshPref();
const tickRef = useRef(tick);
useLayoutEffect(() => { tickRef.current = tick; });
useEffect(() => {
if (!enabled) return;
return startVisibilityPoll(() => tickRef.current(), intervalSeconds * 1000);
}, [enabled, intervalSeconds]);
}
7 changes: 7 additions & 0 deletions gui/src/i18n/de.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4379,6 +4379,13 @@ export const de: Record<TKey, string> = {
"quotaSummary.perMonth": "pro Monat",
"quotaSummary.remainingLimit": "Verbleibend / Limit",
"quotaSummary.openAccounts": "Kontoverwaltung öffnen",
"quotaLive.title": "Kontingente live aktualisieren",
"quotaLive.hint": "Liest regelmäßig die im Proxy zwischengespeicherten Kontingente neu. Ein Anbieter wird erst nach Ablauf dieses Caches erneut abgefragt, nicht bei jeder Aktualisierung.",
"quotaLive.interval": "Alle",
"quotaLive.intervalAria": "Intervall der Live-Kontingentaktualisierung in Sekunden ({min}–{max})",
"quotaLive.intervalInc": "Intervall verlängern",
"quotaLive.intervalDec": "Intervall verkürzen",
"quotaLive.unit": "s",
"pws.protocol.title": "Upstream-Protokoll",
"pws.protocol.note": "Das API-Format, das opencodex mit diesem Anbieter spricht. Es schaltet keine Client-API ein oder aus; das steuert die API-Seite.",
"pws.protocol.adapterLabel": "Upstream-Protokoll, das dieser Anbieter empfängt",
Expand Down
7 changes: 7 additions & 0 deletions gui/src/i18n/en.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4413,6 +4413,13 @@ export const en = {
"quotaSummary.perMonth": "per month",
"quotaSummary.remainingLimit": "Remaining / limit",
"quotaSummary.openAccounts": "Open account management",
"quotaLive.title": "Live quota updates",
"quotaLive.hint": "Re-reads the proxy's cached quota on a timer. A provider is asked again only after that cache expires, not on every update.",
"quotaLive.interval": "Every",
"quotaLive.intervalAria": "Live quota update interval in seconds ({min}–{max})",
"quotaLive.intervalInc": "Increase interval",
"quotaLive.intervalDec": "Decrease interval",
"quotaLive.unit": "s",
"pws.protocol.title": "Upstream wire",
"pws.protocol.note": "The API format opencodex speaks to this provider. It does not turn any client API on or off; the API page controls those.",
"pws.protocol.adapterLabel": "Upstream wire this provider receives",
Expand Down
7 changes: 7 additions & 0 deletions gui/src/i18n/fr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4368,6 +4368,13 @@ export const fr: Record<TKey, string> = {
"quotaSummary.perMonth": "par mois",
"quotaSummary.remainingLimit": "Restant / limite",
"quotaSummary.openAccounts": "Ouvrir la gestion des comptes",
"quotaLive.title": "Mises à jour des quotas en direct",
"quotaLive.hint": "Relit à intervalle régulier les quotas mis en cache par le proxy. Un fournisseur n'est réinterrogé qu'après l'expiration de ce cache, pas à chaque mise à jour.",
"quotaLive.interval": "Toutes les",
"quotaLive.intervalAria": "Intervalle des mises à jour des quotas en direct, en secondes ({min}–{max})",
"quotaLive.intervalInc": "Allonger l’intervalle",
"quotaLive.intervalDec": "Raccourcir l’intervalle",
"quotaLive.unit": "s",
"pws.protocol.title": "Protocole amont",
"pws.protocol.note": "Le format d'API qu'opencodex utilise avec ce fournisseur. Il n'active ni ne désactive aucune API cliente ; c'est la page API qui les contrôle.",
"pws.protocol.adapterLabel": "Protocole amont reçu par ce fournisseur",
Expand Down
7 changes: 7 additions & 0 deletions gui/src/i18n/ja.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4401,6 +4401,13 @@ export const ja: Record<TKey, string> = {
"quotaSummary.perMonth": "毎月",
"quotaSummary.remainingLimit": "残り / 上限",
"quotaSummary.openAccounts": "アカウント管理を開く",
"quotaLive.title": "クォータのライブ更新",
"quotaLive.hint": "プロキシにキャッシュされたクォータを定期的に読み直します。プロバイダーへの再問い合わせはキャッシュの期限切れ後のみで、更新のたびには行いません。",
"quotaLive.interval": "間隔",
"quotaLive.intervalAria": "クォータのライブ更新間隔(秒、{min}〜{max})",
"quotaLive.intervalInc": "間隔を長くする",
"quotaLive.intervalDec": "間隔を短くする",
"quotaLive.unit": "秒",
"pws.protocol.title": "アップストリームのワイヤー形式",
"pws.protocol.note": "opencodex がこのプロバイダーと通信する API 形式です。クライアント API のオン/オフは切り替えません。それは API ページで設定します。",
"pws.protocol.adapterLabel": "このプロバイダーが受け取るワイヤー形式",
Expand Down
7 changes: 7 additions & 0 deletions gui/src/i18n/ko.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4401,6 +4401,13 @@ export const ko: Record<TKey, string> = {
"quotaSummary.perMonth": "월별",
"quotaSummary.remainingLimit": "남은 수 / 한도",
"quotaSummary.openAccounts": "계정 관리 열기",
"quotaLive.title": "할당량 실시간 업데이트",
"quotaLive.hint": "프록시에 캐시된 할당량을 주기적으로 다시 읽습니다. 프로바이더에는 캐시가 만료된 뒤에만 다시 조회하며, 업데이트마다 조회하지 않습니다.",
"quotaLive.interval": "간격",
"quotaLive.intervalAria": "할당량 실시간 업데이트 간격(초, {min}~{max})",
"quotaLive.intervalInc": "간격 늘리기",
"quotaLive.intervalDec": "간격 줄이기",
"quotaLive.unit": "초",
"pws.protocol.title": "업스트림 와이어",
"pws.protocol.note": "opencodex가 이 프로바이더에 보내는 API 형식입니다. 클라이언트 API를 켜거나 끄지 않으며, 그 설정은 API 페이지에 있습니다.",
"pws.protocol.adapterLabel": "이 프로바이더가 받는 업스트림 와이어",
Expand Down
7 changes: 7 additions & 0 deletions gui/src/i18n/pt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4374,6 +4374,13 @@ export const pt: Record<TKey, string> = {
"quotaSummary.perMonth": "por mês",
"quotaSummary.remainingLimit": "Restante / limite",
"quotaSummary.openAccounts": "Abrir gerenciamento de contas",
"quotaLive.title": "Atualização de cotas em tempo real",
"quotaLive.hint": "Relê periodicamente as cotas em cache no proxy. Um provedor só é consultado de novo depois que esse cache expira, não a cada atualização.",
"quotaLive.interval": "A cada",
"quotaLive.intervalAria": "Intervalo da atualização de cotas em tempo real, em segundos ({min}–{max})",
"quotaLive.intervalInc": "Aumentar intervalo",
"quotaLive.intervalDec": "Diminuir intervalo",
"quotaLive.unit": "s",
"pws.protocol.title": "Wire upstream",
"pws.protocol.note": "O formato de API que o opencodex usa para falar com este provedor. Ele não ativa nem desativa nenhuma API de cliente; a página de API controla isso.",
"pws.protocol.adapterLabel": "Wire upstream que este provedor recebe",
Expand Down
7 changes: 7 additions & 0 deletions gui/src/i18n/ru.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4402,6 +4402,13 @@ export const ru: Record<TKey, string> = {
"quotaSummary.perMonth": "в месяц",
"quotaSummary.remainingLimit": "Осталось / лимит",
"quotaSummary.openAccounts": "Открыть управление аккаунтами",
"quotaLive.title": "Обновление квот в реальном времени",
"quotaLive.hint": "Периодически перечитывает квоты из кэша прокси. Провайдер опрашивается снова только после истечения этого кэша, а не при каждом обновлении.",
"quotaLive.interval": "Каждые",
"quotaLive.intervalAria": "Интервал обновления квот в реальном времени, в секундах ({min}–{max})",
"quotaLive.intervalInc": "Увеличить интервал",
"quotaLive.intervalDec": "Уменьшить интервал",
"quotaLive.unit": "с",
"pws.protocol.title": "Протокол к провайдеру",
"pws.protocol.note": "Формат API, которым opencodex обращается к этому провайдеру. Он не включает и не выключает клиентские API — это настраивается на странице API.",
"pws.protocol.adapterLabel": "Протокол, который получает этот провайдер",
Expand Down
7 changes: 7 additions & 0 deletions gui/src/i18n/tr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4402,6 +4402,13 @@ export const tr: Record<TKey, string> = {
"quotaSummary.perMonth": "ay başına",
"quotaSummary.remainingLimit": "Kalan / limit",
"quotaSummary.openAccounts": "Hesap yönetimini aç",
"quotaLive.title": "Canlı kota güncellemeleri",
"quotaLive.hint": "Proxy'nin önbelleğindeki kotaları düzenli aralıklarla yeniden okur. Bir sağlayıcı her güncellemede değil, yalnızca bu önbelleğin süresi dolduktan sonra yeniden sorgulanır.",
"quotaLive.interval": "Her",
"quotaLive.intervalAria": "Canlı kota güncelleme aralığı, saniye cinsinden ({min}–{max})",
"quotaLive.intervalInc": "Aralığı uzat",
"quotaLive.intervalDec": "Aralığı kısalt",
"quotaLive.unit": "sn",
"pws.protocol.title": "Yukarı akış protokolü",
"pws.protocol.note": "opencodex'in bu sağlayıcıyla konuştuğu API biçimi. Hiçbir istemci API'sini açıp kapatmaz; bunlar API sayfasından yönetilir.",
"pws.protocol.adapterLabel": "Bu sağlayıcının aldığı yukarı akış protokolü",
Expand Down
Loading
Loading