diff --git a/gui/src/components/QuotaLiveRefreshSetting.tsx b/gui/src/components/QuotaLiveRefreshSetting.tsx new file mode 100644 index 00000000000..44406c891db --- /dev/null +++ b/gui/src/components/QuotaLiveRefreshSetting.tsx @@ -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 ( +
+
+ {t("quotaLive.title")} +
{t("quotaLive.hint")}
+
+
+ + + + +
+
+ ); +} diff --git a/gui/src/components/provider-workspace/ProviderAuthPanel.tsx b/gui/src/components/provider-workspace/ProviderAuthPanel.tsx index 418b7b0d117..560d2527032 100644 --- a/gui/src/components/provider-workspace/ProviderAuthPanel.tsx +++ b/gui/src/components/provider-workspace/ProviderAuthPanel.tsx @@ -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"; @@ -499,6 +500,10 @@ export default function ProviderAuthPanel({ )}
+ {/* 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") && ( + + )} {item.name === "xai" && ( { @@ -177,10 +178,13 @@ export function useProviderAccountPools(deps: { codexActiveNeedsReauth: boolean; invalidateOauthStatusReads?: (provider: string, blocked?: boolean) => boolean; setOauthStatus?: React.Dispatch>>; + /** 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. @@ -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 `"a=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)}"a=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)}"a=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], diff --git a/gui/src/hooks/useQuotaLiveRefresh.ts b/gui/src/hooks/useQuotaLiveRefresh.ts new file mode 100644 index 00000000000..36ad60de119 --- /dev/null +++ b/gui/src/hooks/useQuotaLiveRefresh.ts @@ -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]); +} diff --git a/gui/src/i18n/de.ts b/gui/src/i18n/de.ts index 6a981960719..a4bdefeab28 100644 --- a/gui/src/i18n/de.ts +++ b/gui/src/i18n/de.ts @@ -4379,6 +4379,13 @@ export const de: Record = { "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", diff --git a/gui/src/i18n/en.ts b/gui/src/i18n/en.ts index ee195119520..d0418b176cc 100644 --- a/gui/src/i18n/en.ts +++ b/gui/src/i18n/en.ts @@ -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", diff --git a/gui/src/i18n/fr.ts b/gui/src/i18n/fr.ts index 40c8dcc9c2a..66ac17df7c4 100644 --- a/gui/src/i18n/fr.ts +++ b/gui/src/i18n/fr.ts @@ -4368,6 +4368,13 @@ export const fr: Record = { "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", diff --git a/gui/src/i18n/ja.ts b/gui/src/i18n/ja.ts index da575530c86..f1cef8c56c9 100644 --- a/gui/src/i18n/ja.ts +++ b/gui/src/i18n/ja.ts @@ -4401,6 +4401,13 @@ export const ja: Record = { "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": "このプロバイダーが受け取るワイヤー形式", diff --git a/gui/src/i18n/ko.ts b/gui/src/i18n/ko.ts index b2e55a81d97..6fd178c1d75 100644 --- a/gui/src/i18n/ko.ts +++ b/gui/src/i18n/ko.ts @@ -4401,6 +4401,13 @@ export const ko: Record = { "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": "이 프로바이더가 받는 업스트림 와이어", diff --git a/gui/src/i18n/pt.ts b/gui/src/i18n/pt.ts index 38249454476..3d78b677f66 100644 --- a/gui/src/i18n/pt.ts +++ b/gui/src/i18n/pt.ts @@ -4374,6 +4374,13 @@ export const pt: Record = { "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", diff --git a/gui/src/i18n/ru.ts b/gui/src/i18n/ru.ts index c08fcdfe96e..6fd3a97a646 100644 --- a/gui/src/i18n/ru.ts +++ b/gui/src/i18n/ru.ts @@ -4402,6 +4402,13 @@ export const ru: Record = { "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": "Протокол, который получает этот провайдер", diff --git a/gui/src/i18n/tr.ts b/gui/src/i18n/tr.ts index 11a09f24f0a..98ff627c058 100644 --- a/gui/src/i18n/tr.ts +++ b/gui/src/i18n/tr.ts @@ -4402,6 +4402,13 @@ export const tr: Record = { "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ü", diff --git a/gui/src/i18n/vi.ts b/gui/src/i18n/vi.ts index d03d70f37ab..099a5618078 100644 --- a/gui/src/i18n/vi.ts +++ b/gui/src/i18n/vi.ts @@ -4371,6 +4371,13 @@ export const vi: Record = { "quotaSummary.perMonth": "mỗi tháng", "quotaSummary.remainingLimit": "Còn lại / giới hạn", "quotaSummary.openAccounts": "Mở quản lý tài khoản", + "quotaLive.title": "Cập nhật hạn mức trực tiếp", + "quotaLive.hint": "Định kỳ đọc lại hạn mức mà proxy đã lưu đệm. Nhà cung cấp chỉ được truy vấn lại sau khi bộ đệm đó hết hạn, không phải ở mỗi lần cập nhật.", + "quotaLive.interval": "Mỗi", + "quotaLive.intervalAria": "Khoảng cập nhật hạn mức trực tiếp, tính bằng giây ({min}–{max})", + "quotaLive.intervalInc": "Tăng khoảng cập nhật", + "quotaLive.intervalDec": "Giảm khoảng cập nhật", + "quotaLive.unit": "giây", "pws.protocol.title": "Giao thức upstream", "pws.protocol.note": "Định dạng API mà opencodex dùng để gọi nhà cung cấp này. Nó không bật hay tắt API phía client nào; các API đó nằm ở trang API.", "pws.protocol.adapterLabel": "Giao thức upstream mà nhà cung cấp này nhận", diff --git a/gui/src/i18n/zh-TW.ts b/gui/src/i18n/zh-TW.ts index 6132f762027..727b773bdbc 100644 --- a/gui/src/i18n/zh-TW.ts +++ b/gui/src/i18n/zh-TW.ts @@ -4365,6 +4365,13 @@ export const zhTW: Record = { "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": "此供應商接收的上游協定", diff --git a/gui/src/i18n/zh.ts b/gui/src/i18n/zh.ts index 6f5f584a2e9..b312e52c8e5 100644 --- a/gui/src/i18n/zh.ts +++ b/gui/src/i18n/zh.ts @@ -4400,6 +4400,13 @@ export const zh: Record = { "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": "此提供商接收的上游协议", diff --git a/gui/src/pages/Providers.tsx b/gui/src/pages/Providers.tsx index 929d5a7c6f5..c5d273abdc7 100644 --- a/gui/src/pages/Providers.tsx +++ b/gui/src/pages/Providers.tsx @@ -424,6 +424,7 @@ export default function Providers({ apiBase, targetKey, targetLabel }: { apiBase config, oauthStatus: oauthStatusWithCodex, aliveRef, notify, fetchConfig, fetchOauth, fetchProviderQuotas, codexActiveNeedsReauth, invalidateOauthStatusReads, setOauthStatus, + liveQuotaProvider: workspaceSelected, }); const { accountSets, setAccountSets, accountLoadStates, switchingAccounts, pausingAccounts, keyPools, fetchAccountSets, fetchKeyPools, beginAccountLogout, diff --git a/gui/src/quota-live-refresh-pref.ts b/gui/src/quota-live-refresh-pref.ts new file mode 100644 index 00000000000..e3687eece43 --- /dev/null +++ b/gui/src/quota-live-refresh-pref.ts @@ -0,0 +1,111 @@ +/** + * Whether this browser re-reads quota data on a timer ("Live quota updates"), and how often. + * + * Not to be confused with the Codex pool's `codexQuotaAutoRefresh`, a server setting that + * activates quota windows upstream. This one is never stored on the server: a live update is a + * plain re-read of what the proxy already holds (its TTL cache plus what live response headers + * report), never `refresh=1`. The interval therefore does not set how often a provider is asked: + * the proxy probes a credential again only once its cache entry has expired, so an open tab costs + * at most one probe per credential per cache window, however short the interval. + * + * That bound is why only the per-account reads tick (`/api/oauth/accounts?…"a=1` and + * `/api/providers/keys?…"a=1`, both served from per-credential TTL caches that also cache + * failures). The summary strip's `/api/provider-quotas` and the Codex pool's + * `/api/codex-auth/accounts` keep their fixed cadence: in some states a plain read of either + * reaches upstream without such a bound — the provider report cache key moves with live Codex + * pool usage, and a pool account answering 401/403 is neither cached nor backed off — so a + * faster timer there would mean provider traffic at the timer's rate. + * + * Client-side and remembered per browser, like the OAuth open-browser choice: how lively a + * dashboard should be belongs to whoever is looking at it, not to the machine running the proxy. + * + * Reads never throw. A browser with storage disabled gets the default, and a choice made there + * still applies to this tab until it reloads. + */ +import { useSyncExternalStore } from "react"; + +const KEY = "ocx.quota.liveRefresh"; + +export interface QuotaLiveRefreshPref { + enabled: boolean; + intervalSeconds: number; +} + +export const QUOTA_LIVE_REFRESH_MIN_SECONDS = 5; +export const QUOTA_LIVE_REFRESH_MAX_SECONDS = 600; +export const QUOTA_LIVE_REFRESH_DEFAULT: QuotaLiveRefreshPref = Object.freeze({ enabled: true, intervalSeconds: 15 }); + +/** Whole seconds inside the allowed range; anything that is not a finite number is the default. */ +export function clampQuotaLiveRefreshSeconds(value: number): number { + if (!Number.isFinite(value)) return QUOTA_LIVE_REFRESH_DEFAULT.intervalSeconds; + return Math.min(QUOTA_LIVE_REFRESH_MAX_SECONDS, Math.max(QUOTA_LIVE_REFRESH_MIN_SECONDS, Math.round(value))); +} + +/** Each field falls back on its own, so one bad field does not discard the other. */ +export function parseQuotaLiveRefreshPref(raw: string | null): QuotaLiveRefreshPref { + let value: unknown = null; + try { + if (raw !== null) value = JSON.parse(raw); + } catch { + value = null; + } + const record = value !== null && typeof value === "object" && !Array.isArray(value) ? value as Record : {}; + return { + enabled: typeof record.enabled === "boolean" ? record.enabled : QUOTA_LIVE_REFRESH_DEFAULT.enabled, + intervalSeconds: typeof record.intervalSeconds === "number" + ? clampQuotaLiveRefreshSeconds(record.intervalSeconds) + : QUOTA_LIVE_REFRESH_DEFAULT.intervalSeconds, + }; +} + +/** Set only when storage refused a write; a successful write or another tab's change clears it. */ +let unsaved: QuotaLiveRefreshPref | null = null; +/** useSyncExternalStore compares snapshots by identity, so one object per stored string. */ +let snapshot: { raw: string | null; pref: QuotaLiveRefreshPref } | null = null; +const listeners = new Set<() => void>(); + +export function readQuotaLiveRefreshPref(): QuotaLiveRefreshPref { + if (unsaved) return unsaved; + let raw: string | null; + try { + raw = window.localStorage.getItem(KEY); + } catch { + return QUOTA_LIVE_REFRESH_DEFAULT; + } + if (!snapshot || snapshot.raw !== raw) snapshot = { raw, pref: parseQuotaLiveRefreshPref(raw) }; + return snapshot.pref; +} + +/** Store the clamped value, tell this tab's subscribers, and return what was stored. */ +export function writeQuotaLiveRefreshPref(next: QuotaLiveRefreshPref): QuotaLiveRefreshPref { + const pref = { enabled: next.enabled, intervalSeconds: clampQuotaLiveRefreshSeconds(next.intervalSeconds) }; + try { + window.localStorage.setItem(KEY, JSON.stringify(pref)); + unsaved = null; + } catch { + // A rejected write only costs the user the memory of the choice, not the choice. + unsaved = pref; + } + for (const listener of listeners) listener(); + return pref; +} + +/** Notified by writes in this tab and, through the `storage` event, by writes in other tabs. */ +export function subscribeQuotaLiveRefreshPref(onChange: () => void): () => void { + listeners.add(onChange); + const onStorage = (event: StorageEvent) => { + // A null key is another tab clearing all of this origin's storage. + if (event.key !== null && event.key !== KEY) return; + unsaved = null; + onChange(); + }; + window.addEventListener("storage", onStorage); + return () => { + listeners.delete(onChange); + window.removeEventListener("storage", onStorage); + }; +} + +export function useQuotaLiveRefreshPref(): QuotaLiveRefreshPref { + return useSyncExternalStore(subscribeQuotaLiveRefreshPref, readQuotaLiveRefreshPref, () => QUOTA_LIVE_REFRESH_DEFAULT); +} diff --git a/gui/tests/fr-localization.test.ts b/gui/tests/fr-localization.test.ts index 9fef8da4d41..7cd6cdb6c24 100644 --- a/gui/tests/fr-localization.test.ts +++ b/gui/tests/fr-localization.test.ts @@ -45,6 +45,7 @@ const INTENTIONAL_ENGLISH = new Set([ "integrations.cursor.noControl", "uptime.hour", "uptime.second", + "quotaLive.unit", // The SI symbol for seconds, "s" in French too. // "auto" is the same word in French, and it labels a machine-derived alias source rather // than prose. Translating it would invent a difference the UI does not have. "models.aliasAuto", diff --git a/gui/tests/provider-account-live-quota.test.tsx b/gui/tests/provider-account-live-quota.test.tsx new file mode 100644 index 00000000000..cd1af25e1be --- /dev/null +++ b/gui/tests/provider-account-live-quota.test.tsx @@ -0,0 +1,175 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { Window } from "happy-dom"; +import { act, useLayoutEffect, useRef } from "react"; +import { createRoot, type Root } from "react-dom/client"; +import { useProviderAccountPools, type Config } from "../src/hooks/useProviderAccountPools"; +import { writeQuotaLiveRefreshPref } from "../src/quota-live-refresh-pref"; + +const globals = ["document", "window", "navigator", "fetch", "IS_REACT_ACT_ENVIRONMENT"] as const; +let previous: Record<(typeof globals)[number], PropertyDescriptor | undefined>; +let win: Window; +let root: Root | null; +let pools: ReturnType; +let requests: string[]; +let respond: (url: string) => Promise; +let intervals: Map void; delay: number }>; +const noop = async () => {}; +const before = { fiveHourPercent: 21, weeklyPercent: 34, updatedAt: 1_700_000_000_000 }; +const after = { fiveHourPercent: 40, weeklyPercent: 50, updatedAt: 1_700_000_060_000 }; +const config: Config = { + port: 0, + defaultProvider: "fixture", + providers: { + fixture: { adapter: "anthropic", baseUrl: "https://fixture.invalid", authMode: "oauth" }, + keyed: { adapter: "openai", baseUrl: "https://keyed.invalid", hasApiKey: true }, + }, +}; +const rows = (quota?: typeof before) => ["a", "b"].map(id => ({ id, masked: id, active: id === "a", quotaMode: "probe" as const, ...(quota ? { quota } : {}) })); +const roster = (quota?: typeof before) => Response.json({ activeAccountId: "a", activeId: "a", accounts: rows(quota), keys: rows(quota) }); + +function deferred() { + let resolve!: (value: T) => void; + const promise = new Promise(done => { resolve = done; }); + return { promise, resolve }; +} + +function Harness({ provider }: { provider: string | null }) { + const aliveRef = useRef(true); + const current = useProviderAccountPools({ apiBase: "/live", config, aliveRef, t: key => key, + oauthStatus: {}, notify: () => {}, fetchConfig: noop, fetchOauth: noop, + fetchProviderQuotas: noop, codexActiveNeedsReauth: false, liveQuotaProvider: provider }); + useLayoutEffect(() => { pools = current; }, [current]); + return null; +} + +async function settle() { + await act(async () => { await new Promise(resolve => setTimeout(resolve, 0)); }); +} + +async function mount(provider: string | null = "fixture") { + const host = win.document.createElement("div"); + win.document.body.appendChild(host); + await act(async () => { root = createRoot(host as unknown as HTMLElement); root.render(); }); + await settle(); + await settle(); + requests = []; +} + +/** Fire every armed interval once, as the browser would when its delay elapses. */ +async function fire() { + await act(async () => { for (const timer of [...intervals.values()]) timer.run(); }); + await settle(); +} + +function setVisibility(state: "visible" | "hidden") { + Object.defineProperty(win.document, "visibilityState", { configurable: true, get: () => state }); + win.document.dispatchEvent(new win.Event("visibilitychange")); +} + +beforeEach(() => { + previous = Object.fromEntries(globals.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])) as typeof previous; + win = new Window({ url: "http://localhost" }); + Object.defineProperties(globalThis, { + document: { configurable: true, value: win.document }, window: { configurable: true, value: win }, + navigator: { configurable: true, value: win.navigator }, IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true }, + }); + intervals = new Map(); + let nextId = 0; + win.setInterval = ((run: () => void, delay: number) => { intervals.set(++nextId, { run, delay }); return nextId; }) as typeof win.setInterval; + win.clearInterval = ((id: number) => { intervals.delete(id); }) as typeof win.clearInterval; + requests = []; + respond = async url => roster(url.includes("quota=1") ? before : undefined); + Object.defineProperty(globalThis, "fetch", { configurable: true, value: (input: RequestInfo | URL) => { + requests.push(String(input)); + return respond(String(input)); + } }); +}); + +afterEach(async () => { + await act(async () => { root?.unmount(); }); + root = null; + win.close(); + for (const key of globals) { + const descriptor = previous[key]; + if (descriptor) Object.defineProperty(globalThis, key, descriptor); + else Reflect.deleteProperty(globalThis, key); + } +}); + +test("a live tick re-reads the selected provider's account quota without forcing it or showing a load", async () => { + await mount(); + expect(pools.accountSets.fixture.accounts[0].quota).toEqual(before); + expect([...intervals.values()].map(timer => timer.delay)).toEqual([15_000]); + const quota = deferred(); + respond = async () => quota.promise; + await fire(); + expect(requests).toEqual(["/live/api/oauth/accounts?provider=fixture"a=1"]); + expect(requests[0]).not.toContain("refresh=1"); + // While the background read is out, the rows stay as they were: no skeleton, no pending bars. + expect(pools.accountLoadStates.fixture).toBe("ready"); + expect(pools.accountSets.fixture.accounts[0]).toMatchObject({ quota: before, quotaPending: false }); + await act(async () => { quota.resolve(roster(after)); }); + await settle(); + expect(pools.accountSets.fixture.accounts.map(row => row.quota)).toEqual([after, after]); + expect(pools.accountLoadStates.fixture).toBe("ready"); +}); + +test("an API-key pool ticks through its own non-forced quota read", async () => { + await mount("keyed"); + await fire(); + expect(requests).toEqual(["/live/api/providers/keys?name=keyed"a=1"]); +}); + +test("a tick never overlaps a read that is already in flight", async () => { + await mount(); + const manual = deferred(); + respond = async url => url.includes("quota=1") ? roster(after) : manual.promise; + let refreshed!: Promise; + await act(async () => { refreshed = pools.fetchAccountSets(["fixture"], true); }); + expect(requests).toEqual(["/live/api/oauth/accounts?provider=fixture"]); + await fire(); + expect(requests).toEqual(["/live/api/oauth/accounts?provider=fixture"]); + await act(async () => { manual.resolve(roster()); expect(await refreshed).toBe(true); }); + expect(requests).toEqual(["/live/api/oauth/accounts?provider=fixture", "/live/api/oauth/accounts?provider=fixture"a=1&refresh=1"]); + requests = []; + await fire(); + expect(requests).toEqual(["/live/api/oauth/accounts?provider=fixture"a=1"]); +}); + +test("a hidden dashboard holds no live timer, and showing it again makes up one tick", async () => { + await mount(); + setVisibility("hidden"); + expect(intervals.size).toBe(0); + await fire(); + expect(requests).toEqual([]); + await act(async () => { setVisibility("visible"); }); + await settle(); + expect(requests).toEqual(["/live/api/oauth/accounts?provider=fixture"a=1"]); + expect(intervals.size).toBe(1); +}); + +test("a failed tick keeps the bars on screen and raises no error", async () => { + await mount(); + respond = async () => new Response(null, { status: 503 }); + await fire(); + expect(requests).toHaveLength(1); + expect(pools.accountLoadStates.fixture).toBe("ready"); + expect(pools.accountSets.fixture.accounts[0]).toMatchObject({ quota: before, quotaPending: false, quotaUnavailable: false }); +}); + +test("off holds no timer, the cadence follows the preference, and unmount stops it", async () => { + await mount(); + await act(async () => { writeQuotaLiveRefreshPref({ enabled: false, intervalSeconds: 15 }); }); + expect(intervals.size).toBe(0); + await act(async () => { writeQuotaLiveRefreshPref({ enabled: true, intervalSeconds: 40 }); }); + expect([...intervals.values()].map(timer => timer.delay)).toEqual([40_000]); + await act(async () => { root?.unmount(); }); + root = null; + expect(intervals.size).toBe(0); +}); + +test("no provider on screen means no live read", async () => { + await mount(null); + await fire(); + expect(requests).toEqual([]); +}); diff --git a/gui/tests/quota-live-refresh-pref.test.ts b/gui/tests/quota-live-refresh-pref.test.ts new file mode 100644 index 00000000000..77a8e9c06dd --- /dev/null +++ b/gui/tests/quota-live-refresh-pref.test.ts @@ -0,0 +1,109 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { Window } from "happy-dom"; +import { + QUOTA_LIVE_REFRESH_DEFAULT, + clampQuotaLiveRefreshSeconds, + parseQuotaLiveRefreshPref, + readQuotaLiveRefreshPref, + subscribeQuotaLiveRefreshPref, + writeQuotaLiveRefreshPref, +} from "../src/quota-live-refresh-pref"; + +const KEY = "ocx.quota.liveRefresh"; +const globals = ["window"] as const; +let previous: Record<(typeof globals)[number], PropertyDescriptor | undefined>; +let win: Window; + +beforeEach(() => { + previous = Object.fromEntries(globals.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])) as typeof previous; + win = new Window({ url: "http://localhost/" }); + Object.defineProperty(globalThis, "window", { configurable: true, value: win }); +}); + +afterEach(() => { + win.close(); + for (const key of globals) { + const descriptor = previous[key]; + if (descriptor) Object.defineProperty(globalThis, key, descriptor); + else Reflect.deleteProperty(globalThis, key); + } +}); + +test("nothing stored means live updates are on at 15 seconds", () => { + expect(QUOTA_LIVE_REFRESH_DEFAULT).toEqual({ enabled: true, intervalSeconds: 15 }); + expect(readQuotaLiveRefreshPref()).toEqual({ enabled: true, intervalSeconds: 15 }); + // useSyncExternalStore needs one snapshot object per stored value. + expect(readQuotaLiveRefreshPref()).toBe(readQuotaLiveRefreshPref()); +}); + +test("a stored value that is not a preference falls back field by field", () => { + for (const raw of [null, "", "not json", "[]", "null", "42", "\"on\""]) { + expect(parseQuotaLiveRefreshPref(raw)).toEqual(QUOTA_LIVE_REFRESH_DEFAULT); + } + expect(parseQuotaLiveRefreshPref("{\"enabled\":\"yes\",\"intervalSeconds\":\"30\"}")).toEqual(QUOTA_LIVE_REFRESH_DEFAULT); + expect(parseQuotaLiveRefreshPref("{\"enabled\":false}")).toEqual({ enabled: false, intervalSeconds: 15 }); + expect(parseQuotaLiveRefreshPref("{\"enabled\":true,\"intervalSeconds\":2}")).toEqual({ enabled: true, intervalSeconds: 5 }); + expect(parseQuotaLiveRefreshPref("{\"enabled\":true,\"intervalSeconds\":86400}")).toEqual({ enabled: true, intervalSeconds: 600 }); + expect(parseQuotaLiveRefreshPref("{\"enabled\":false,\"intervalSeconds\":12.6}")).toEqual({ enabled: false, intervalSeconds: 13 }); + win.localStorage.setItem(KEY, "{\"enabled\":false,\"intervalSeconds\":-1}"); + expect(readQuotaLiveRefreshPref()).toEqual({ enabled: false, intervalSeconds: 5 }); +}); + +test("the interval is whole seconds from 5 to 600", () => { + expect(clampQuotaLiveRefreshSeconds(0)).toBe(5); + expect(clampQuotaLiveRefreshSeconds(4.4)).toBe(5); + expect(clampQuotaLiveRefreshSeconds(5)).toBe(5); + expect(clampQuotaLiveRefreshSeconds(30.5)).toBe(31); + expect(clampQuotaLiveRefreshSeconds(600)).toBe(600); + expect(clampQuotaLiveRefreshSeconds(601)).toBe(600); + expect(clampQuotaLiveRefreshSeconds(Number.NaN)).toBe(15); + expect(clampQuotaLiveRefreshSeconds(Number.POSITIVE_INFINITY)).toBe(15); +}); + +test("a write is clamped before it is stored and tells this tab's subscribers", () => { + let calls = 0; + const unsubscribe = subscribeQuotaLiveRefreshPref(() => { calls += 1; }); + expect(writeQuotaLiveRefreshPref({ enabled: false, intervalSeconds: 1 })).toEqual({ enabled: false, intervalSeconds: 5 }); + expect(JSON.parse(win.localStorage.getItem(KEY)!)).toEqual({ enabled: false, intervalSeconds: 5 }); + expect(readQuotaLiveRefreshPref()).toEqual({ enabled: false, intervalSeconds: 5 }); + expect(calls).toBe(1); + unsubscribe(); + writeQuotaLiveRefreshPref({ enabled: true, intervalSeconds: 20 }); + expect(calls).toBe(1); +}); + +test("a change made in another tab reaches subscribers through the storage event", () => { + let calls = 0; + const unsubscribe = subscribeQuotaLiveRefreshPref(() => { calls += 1; }); + win.localStorage.setItem(KEY, JSON.stringify({ enabled: false, intervalSeconds: 45 })); + win.dispatchEvent(new win.StorageEvent("storage", { key: "unrelated" })); + expect(calls).toBe(0); + win.dispatchEvent(new win.StorageEvent("storage", { key: KEY })); + expect(calls).toBe(1); + expect(readQuotaLiveRefreshPref()).toEqual({ enabled: false, intervalSeconds: 45 }); + // `key: null` is another tab clearing all of storage. + win.localStorage.clear(); + win.dispatchEvent(new win.StorageEvent("storage", { key: null })); + expect(calls).toBe(2); + expect(readQuotaLiveRefreshPref()).toEqual(QUOTA_LIVE_REFRESH_DEFAULT); + unsubscribe(); + win.dispatchEvent(new win.StorageEvent("storage", { key: KEY })); + expect(calls).toBe(2); +}); + +test("disabled storage reads as the default and keeps a choice for this tab", () => { + const storage = win.localStorage; + Object.defineProperty(win, "localStorage", { configurable: true, get: () => { throw new Error("storage disabled"); } }); + expect(readQuotaLiveRefreshPref()).toEqual(QUOTA_LIVE_REFRESH_DEFAULT); + let calls = 0; + const unsubscribe = subscribeQuotaLiveRefreshPref(() => { calls += 1; }); + expect(() => writeQuotaLiveRefreshPref({ enabled: false, intervalSeconds: 30 })).not.toThrow(); + expect(readQuotaLiveRefreshPref()).toEqual({ enabled: false, intervalSeconds: 30 }); + expect(calls).toBe(1); + // Storage coming back: the next successful write replaces the tab-only choice. + Object.defineProperty(win, "localStorage", { configurable: true, get: () => storage }); + writeQuotaLiveRefreshPref({ enabled: true, intervalSeconds: 20 }); + expect(JSON.parse(storage.getItem(KEY)!)).toEqual({ enabled: true, intervalSeconds: 20 }); + expect(readQuotaLiveRefreshPref()).toEqual({ enabled: true, intervalSeconds: 20 }); + unsubscribe(); +}); diff --git a/gui/tests/quota-live-refresh-setting.test.tsx b/gui/tests/quota-live-refresh-setting.test.tsx new file mode 100644 index 00000000000..0d8d02afc4f --- /dev/null +++ b/gui/tests/quota-live-refresh-setting.test.tsx @@ -0,0 +1,137 @@ +import { afterEach, beforeEach, expect, test } from "bun:test"; +import { Window } from "happy-dom"; +import { act } from "react"; +import type { Root } from "react-dom/client"; +import QuotaLiveRefreshSetting from "../src/components/QuotaLiveRefreshSetting"; +import { LanguageProvider } from "../src/i18n/provider"; +import { readQuotaLiveRefreshPref } from "../src/quota-live-refresh-pref"; + +const KEY = "ocx.quota.liveRefresh"; +const globals = ["document", "window", "navigator", "IS_REACT_ACT_ENVIRONMENT"] as const; +let previous: Record<(typeof globals)[number], PropertyDescriptor | undefined>; +let win: Window; +let root: Root | null; + +beforeEach(async () => { + previous = Object.fromEntries(globals.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])) as typeof previous; + win = new Window({ url: "http://localhost/" }); + Object.defineProperty(win.navigator, "language", { configurable: true, value: "en-US" }); + Object.defineProperties(globalThis, { + document: { configurable: true, value: win.document }, window: { configurable: true, value: win }, + navigator: { configurable: true, value: win.navigator }, IS_REACT_ACT_ENVIRONMENT: { configurable: true, value: true }, + }); + const host = win.document.createElement("div"); + win.document.body.appendChild(host); + // Loaded after the DOM globals exist: react-dom decides at import time whether it can use the + // DOM, and without that its keyboard handlers never see a dispatched keydown. + const { createRoot } = await import("react-dom/client"); + await act(async () => { + root = createRoot(host as unknown as HTMLElement); + root.render(); + }); +}); + +afterEach(async () => { + await act(async () => { root?.unmount(); }); + root = null; + win.close(); + for (const key of globals) { + const descriptor = previous[key]; + if (descriptor) Object.defineProperty(globalThis, key, descriptor); + else Reflect.deleteProperty(globalThis, key); + } +}); + +const toggle = () => win.document.querySelector("button.toggle") as unknown as HTMLButtonElement; +const input = () => win.document.querySelector("input[type=number]") as unknown as HTMLInputElement; +const stored = () => JSON.parse(win.localStorage.getItem(KEY) ?? "null") as unknown; + +async function type(value: string) { + await act(async () => { + Object.getOwnPropertyDescriptor(win.HTMLInputElement.prototype, "value")!.set!.call(input(), value); + input().dispatchEvent(new win.Event("input", { bubbles: true })); + }); +} + +async function press(key: string) { + await act(async () => { input().dispatchEvent(new win.KeyboardEvent("keydown", { key, bubbles: true })); }); +} + +test("the row names itself, explains it adds no provider queries, and shows the defaults", () => { + const text = win.document.body.textContent ?? ""; + expect(text).toContain("Live quota updates"); + expect(text).toContain("only after that cache expires"); + expect(toggle().getAttribute("aria-pressed")).toBe("true"); + expect(toggle().getAttribute("aria-label")).toBe("Live quota updates"); + expect(input().value).toBe("15"); + expect(input().getAttribute("aria-label")).toBe("Live quota update interval in seconds (5–600)"); + expect(input().getAttribute("min")).toBe("5"); + expect(input().getAttribute("max")).toBe("600"); +}); + +test("the toggle saves the choice in this browser", async () => { + await act(async () => { toggle().click(); }); + expect(stored()).toEqual({ enabled: false, intervalSeconds: 15 }); + expect(toggle().getAttribute("aria-pressed")).toBe("false"); + expect(input().disabled).toBe(true); + await act(async () => { toggle().click(); }); + expect(stored()).toEqual({ enabled: true, intervalSeconds: 15 }); + expect(toggle().getAttribute("aria-pressed")).toBe("true"); +}); + +test("Enter saves a valid interval", async () => { + await type("30"); + expect(stored()).toBeNull(); + await press("Enter"); + expect(stored()).toEqual({ enabled: true, intervalSeconds: 30 }); + expect(input().value).toBe("30"); +}); + +test("an interval outside the range is clamped, and the field shows what took effect", async () => { + await type("2"); + await act(async () => { input().dispatchEvent(new win.FocusEvent("focusout", { bubbles: true })); }); + expect(stored()).toEqual({ enabled: true, intervalSeconds: 5 }); + expect(input().value).toBe("5"); + await type("100000"); + await press("Enter"); + expect(stored()).toEqual({ enabled: true, intervalSeconds: 600 }); + expect(input().value).toBe("600"); + await type("12.4"); + await press("Enter"); + expect(readQuotaLiveRefreshPref().intervalSeconds).toBe(12); + expect(input().value).toBe("12"); +}); + +test("empty or non-numeric input keeps the saved interval, and Escape discards a draft", async () => { + await type("45"); + await press("Enter"); + await type(""); + await press("Enter"); + expect(stored()).toEqual({ enabled: true, intervalSeconds: 45 }); + expect(input().value).toBe("45"); + await type("abc"); + await act(async () => { input().dispatchEvent(new win.FocusEvent("focusout", { bubbles: true })); }); + expect(stored()).toEqual({ enabled: true, intervalSeconds: 45 }); + expect(input().value).toBe("45"); + await type("90"); + await press("Escape"); + expect(input().value).toBe("45"); + expect(stored()).toEqual({ enabled: true, intervalSeconds: 45 }); +}); + +test("the steppers save at once in whole steps inside the range", async () => { + const [up, down] = [...win.document.querySelectorAll(".ocx-stepper__btn")] as unknown as HTMLButtonElement[]; + await act(async () => { up.click(); }); + expect(stored()).toEqual({ enabled: true, intervalSeconds: 20 }); + expect(input().value).toBe("20"); + for (let index = 0; index < 5; index += 1) await act(async () => { down.click(); }); + expect(stored()).toEqual({ enabled: true, intervalSeconds: 5 }); + expect(input().value).toBe("5"); +}); + +test("a change made in another tab shows up in the row", async () => { + win.localStorage.setItem(KEY, JSON.stringify({ enabled: false, intervalSeconds: 120 })); + await act(async () => { win.dispatchEvent(new win.StorageEvent("storage", { key: KEY })); }); + expect(toggle().getAttribute("aria-pressed")).toBe("false"); + expect(input().value).toBe("120"); +});