refactor(app): DRY pass — split large files, extract shared utils

S1: delete page.new.js (1724L abandoned) + remove dead getAntigravityProjectId
S2: split large files by natural seams
  - usage.js → usage/{github,google,claude,codex,kiro,minimax,misc,shared}.js
  - media-providers page → components/{Embedding,Tts,Generic,Stt}ExampleCard.js
  - EndpointPageClient → endpointConstants.js + endpointPing.js + components/
  - tokenRefresh.js → tokenRefresh/{dedup,providers}.js
  - ProviderLimits/index.js: 16 pure fn + 9 constants → utils.js
  - oauth/providers.js: 7 pure helpers → providerHelpers.js
S3: shared utils
  - getModelKind(m, fallback) → shared/constants/models.js (replaces 20× m.kind||m.type)
  - getStatusVariant → shared/utils/connectionStatus.js (dedup ConnectionRow/ConnectionsCard)
  - sseChunk → open-sse/utils/sse.js (dedup grok-web/perplexity-web)
  - fetchWithTimeout → usage/shared.js (replace 4× AbortController pattern in google.js)
fix: enableObservability2 field name in requestDetailsRepo
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
decolua
2026-06-14 19:31:09 +07:00
co-authored by Cursor
parent d3f61aac2f
commit fbf973f2e7
44 changed files with 4211 additions and 5875 deletions
@@ -4,222 +4,39 @@ import { useState, useEffect, useCallback, useRef, useMemo } from "react";
import ProviderIcon from "@/shared/components/ProviderIcon";
import QuotaTable from "./QuotaTable";
import Toggle from "@/shared/components/Toggle";
import { parseQuotaData, calculatePercentage } from "./utils";
import {
parseQuotaData,
calculatePercentage,
getConnectionLabel,
getConnectionQuotaRemaining,
sortVisibleConnections,
buildLoadingState,
filterQuotaStateByConnections,
getConnectionsEmptyMessage,
getPageSizeLabel,
getConnectionsPaginationSummary,
getSafePagination,
getSafeTotals,
shouldResetPage,
getPaginationPageValue,
getProviderOptions,
reconcileConnectionsPage,
getQuotaCache,
setQuotaCache,
QUOTA_CACHE_KEY,
REFRESH_INTERVAL_MS,
DEPLETED_QUOTA_THRESHOLD,
AUTO_REFRESH_STORAGE_KEY,
CONNECTIONS_PAGE_SIZE,
ACCOUNT_PAGE_SIZE_OPTIONS,
ACCOUNT_PAGE_SIZE_MAX,
ACCOUNT_FILTER_OPTIONS,
QUOTA_SORT_OPTIONS,
} from "./utils";
import Card from "@/shared/components/Card";
import { EditConnectionModal } from "@/shared/components";
import { USAGE_SUPPORTED_PROVIDERS } from "@/shared/constants/providers";
function getConnectionLabel(connection) {
const isEmail = (value) =>
typeof value === "string" && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
if (isEmail(connection.email)) return connection.email;
if (isEmail(connection.name)) return connection.name;
return connection.name;
}
function getConnectionQuotaRemaining(connection, quotaData) {
const quota = quotaData[connection.id]?.quotas?.[0];
if (!quota) return Number.POSITIVE_INFINITY;
if (typeof quota.remaining === "number") return quota.remaining;
return Number.POSITIVE_INFINITY;
}
function sortVisibleConnections(
connections,
quotaData,
expiringFirst,
providerFilter,
quotaSortMode,
) {
if (providerFilter === "codex" && quotaSortMode !== "default") {
return [...connections].sort((a, b) => {
const remainingA = getConnectionQuotaRemaining(a, quotaData);
const remainingB = getConnectionQuotaRemaining(b, quotaData);
const remainingDiff =
quotaSortMode === "remaining-asc"
? remainingA - remainingB
: remainingB - remainingA;
if (remainingDiff !== 0) return remainingDiff;
return (getConnectionLabel(a) || "").localeCompare(
getConnectionLabel(b) || "",
);
});
}
if (!expiringFirst) return connections;
const getEarliestResetTime = (connection) => {
const resetTimes = (quotaData[connection.id]?.quotas || [])
.map((quota) =>
quota.resetAt
? new Date(quota.resetAt).getTime()
: Number.POSITIVE_INFINITY,
)
.filter((time) => Number.isFinite(time));
return resetTimes.length > 0
? Math.min(...resetTimes)
: Number.POSITIVE_INFINITY;
};
return [...connections].sort((a, b) => {
const expiryDiff = getEarliestResetTime(a) - getEarliestResetTime(b);
if (expiryDiff !== 0) return expiryDiff;
return (
(a.provider || "").localeCompare(b.provider || "") ||
(getConnectionLabel(a) || "").localeCompare(getConnectionLabel(b) || "")
);
});
}
function buildLoadingState(connections) {
const nextLoadingState = {};
connections.forEach((connection) => {
nextLoadingState[connection.id] = true;
});
return nextLoadingState;
}
function filterQuotaStateByConnections(state, connections) {
const visibleIds = new Set(connections.map((connection) => connection.id));
return Object.fromEntries(
Object.entries(state).filter(([id]) => visibleIds.has(id)),
);
}
function getConnectionsPageRange(pagination) {
if (!pagination.total) {
return { start: 0, end: 0 };
}
const start = (pagination.page - 1) * pagination.pageSize + 1;
const end = Math.min(pagination.page * pagination.pageSize, pagination.total);
return { start, end };
}
function getConnectionsEmptyMessage(totals, providerFilter, accountFilter) {
if (!totals.eligibleConnections) {
return {
icon: "cloud_off",
title: "No Providers Connected",
description:
"Connect to providers with OAuth to track your API quota limits and usage.",
};
}
if (!totals.providerFilteredConnections) {
return {
icon: "filter_alt_off",
title: "No Accounts Match Current Filters",
description:
providerFilter === "all"
? "Try changing the account status filter to see more quota trackers."
: `No ${accountFilter === "inactive" ? "turned off" : accountFilter === "active" ? "active" : "matching"} accounts found for ${providerFilter}.`,
};
}
return {
icon: "filter_alt_off",
title: "No Accounts On This Page",
description:
"Try moving to another page or refreshing the current filters.",
};
}
function sortRequestFromExpiringFirst(expiringFirst) {
return expiringFirst ? "expiring" : "priority";
}
function getPageSizeLabel(pageSize, isCustomPageSize) {
return isCustomPageSize ? `Custom: ${pageSize} / page` : `${pageSize} / page`;
}
function getConnectionsPaginationSummary(pagination) {
const { start, end } = getConnectionsPageRange(pagination);
return `Showing ${start}-${end} of ${pagination.total}`;
}
function getSafePagination(pagination, fallbackPageSize) {
return (
pagination || {
page: 1,
pageSize: fallbackPageSize,
total: 0,
totalPages: 1,
}
);
}
function getSafeTotals(totals, fallbackTotal = 0) {
return (
totals || {
eligibleConnections: fallbackTotal,
providerFilteredConnections: fallbackTotal,
}
);
}
function shouldResetPage(previousValue, nextValue) {
return previousValue !== nextValue;
}
function getPaginationPageValue(dataPagination, fallbackPage) {
return dataPagination?.page || fallbackPage;
}
function getProviderOptions(dataProviderOptions) {
return dataProviderOptions || [];
}
async function reconcileConnectionsPage(fetchConnections, targetPage) {
const nextConnections = await fetchConnections(targetPage);
return nextConnections;
}
const QUOTA_CACHE_KEY = "quotaCacheData";
function getQuotaCache() {
if (typeof window === "undefined") return {};
try {
const cached = window.localStorage.getItem(QUOTA_CACHE_KEY);
return cached ? JSON.parse(cached) : {};
} catch (error) {
console.error("Error reading quota cache:", error);
return {};
}
}
function setQuotaCache(connectionId, quotaEntry) {
if (typeof window === "undefined") return;
try {
const cache = getQuotaCache();
cache[connectionId] = {
...quotaEntry,
cachedAt: new Date().toISOString(),
};
window.localStorage.setItem(QUOTA_CACHE_KEY, JSON.stringify(cache));
} catch (error) {
console.error("Error writing quota cache:", error);
}
}
const REFRESH_INTERVAL_MS = 60000; // 60 seconds
const DEPLETED_QUOTA_THRESHOLD = 5; // percent
const AUTO_REFRESH_STORAGE_KEY = "quotaAutoRefresh";
const ACCOUNT_FILTER_OPTIONS = [
{ value: "all", label: "All accounts" },
{ value: "active", label: "Active" },
{ value: "inactive", label: "Turned off" },
];
const QUOTA_SORT_OPTIONS = [
{ value: "default", label: "Default quota order" },
{ value: "remaining-asc", label: "% quota: low to high" },
{ value: "remaining-desc", label: "% quota: high to low" },
];
const CONNECTIONS_PAGE_SIZE = 20;
const ACCOUNT_PAGE_SIZE_OPTIONS = [10, 20, 50, 100];
const ACCOUNT_PAGE_SIZE_MAX = 500;
export default function ProviderLimits() {
const [connections, setConnections] = useState([]);
const [quotaData, setQuotaData] = useState({});
@@ -1,5 +1,212 @@
import { getModelsByProviderId } from "open-sse/config/providerModels.js";
// ─── Constants ───────────────────────────────────────────────────────────────
export const QUOTA_CACHE_KEY = "quotaCacheData";
export const REFRESH_INTERVAL_MS = 60000;
export const DEPLETED_QUOTA_THRESHOLD = 5;
export const AUTO_REFRESH_STORAGE_KEY = "quotaAutoRefresh";
export const CONNECTIONS_PAGE_SIZE = 20;
export const ACCOUNT_PAGE_SIZE_OPTIONS = [10, 20, 50, 100];
export const ACCOUNT_PAGE_SIZE_MAX = 500;
export const ACCOUNT_FILTER_OPTIONS = [
{ value: "all", label: "All accounts" },
{ value: "active", label: "Active" },
{ value: "inactive", label: "Turned off" },
];
export const QUOTA_SORT_OPTIONS = [
{ value: "default", label: "Default quota order" },
{ value: "remaining-asc", label: "% quota: low to high" },
{ value: "remaining-desc", label: "% quota: high to low" },
];
// ─── Pure helpers ─────────────────────────────────────────────────────────────
export function getConnectionLabel(connection) {
const isEmail = (value) =>
typeof value === "string" && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
if (isEmail(connection.email)) return connection.email;
if (isEmail(connection.name)) return connection.name;
return connection.name;
}
export function getConnectionQuotaRemaining(connection, quotaData) {
const quota = quotaData[connection.id]?.quotas?.[0];
if (!quota) return Number.POSITIVE_INFINITY;
if (typeof quota.remaining === "number") return quota.remaining;
return Number.POSITIVE_INFINITY;
}
export function sortVisibleConnections(
connections,
quotaData,
expiringFirst,
providerFilter,
quotaSortMode,
) {
if (providerFilter === "codex" && quotaSortMode !== "default") {
return [...connections].sort((a, b) => {
const remainingA = getConnectionQuotaRemaining(a, quotaData);
const remainingB = getConnectionQuotaRemaining(b, quotaData);
const remainingDiff =
quotaSortMode === "remaining-asc"
? remainingA - remainingB
: remainingB - remainingA;
if (remainingDiff !== 0) return remainingDiff;
return (getConnectionLabel(a) || "").localeCompare(
getConnectionLabel(b) || "",
);
});
}
if (!expiringFirst) return connections;
const getEarliestResetTime = (connection) => {
const resetTimes = (quotaData[connection.id]?.quotas || [])
.map((quota) =>
quota.resetAt
? new Date(quota.resetAt).getTime()
: Number.POSITIVE_INFINITY,
)
.filter((time) => Number.isFinite(time));
return resetTimes.length > 0
? Math.min(...resetTimes)
: Number.POSITIVE_INFINITY;
};
return [...connections].sort((a, b) => {
const expiryDiff = getEarliestResetTime(a) - getEarliestResetTime(b);
if (expiryDiff !== 0) return expiryDiff;
return (
(a.provider || "").localeCompare(b.provider || "") ||
(getConnectionLabel(a) || "").localeCompare(getConnectionLabel(b) || "")
);
});
}
export function buildLoadingState(connections) {
const nextLoadingState = {};
connections.forEach((connection) => {
nextLoadingState[connection.id] = true;
});
return nextLoadingState;
}
export function filterQuotaStateByConnections(state, connections) {
const visibleIds = new Set(connections.map((connection) => connection.id));
return Object.fromEntries(
Object.entries(state).filter(([id]) => visibleIds.has(id)),
);
}
export function getConnectionsPageRange(pagination) {
if (!pagination.total) {
return { start: 0, end: 0 };
}
const start = (pagination.page - 1) * pagination.pageSize + 1;
const end = Math.min(pagination.page * pagination.pageSize, pagination.total);
return { start, end };
}
export function getConnectionsEmptyMessage(totals, providerFilter, accountFilter) {
if (!totals.eligibleConnections) {
return {
icon: "cloud_off",
title: "No Providers Connected",
description:
"Connect to providers with OAuth to track your API quota limits and usage.",
};
}
if (!totals.providerFilteredConnections) {
return {
icon: "filter_alt_off",
title: "No Accounts Match Current Filters",
description:
providerFilter === "all"
? "Try changing the account status filter to see more quota trackers."
: `No ${accountFilter === "inactive" ? "turned off" : accountFilter === "active" ? "active" : "matching"} accounts found for ${providerFilter}.`,
};
}
return {
icon: "filter_alt_off",
title: "No Accounts On This Page",
description:
"Try moving to another page or refreshing the current filters.",
};
}
export function sortRequestFromExpiringFirst(expiringFirst) {
return expiringFirst ? "expiring" : "priority";
}
export function getPageSizeLabel(pageSize, isCustomPageSize) {
return isCustomPageSize ? `Custom: ${pageSize} / page` : `${pageSize} / page`;
}
export function getConnectionsPaginationSummary(pagination) {
const { start, end } = getConnectionsPageRange(pagination);
return `Showing ${start}-${end} of ${pagination.total}`;
}
export function getSafePagination(pagination, fallbackPageSize) {
return (
pagination || {
page: 1,
pageSize: fallbackPageSize,
total: 0,
totalPages: 1,
}
);
}
export function getSafeTotals(totals, fallbackTotal = 0) {
return (
totals || {
eligibleConnections: fallbackTotal,
providerFilteredConnections: fallbackTotal,
}
);
}
export function shouldResetPage(previousValue, nextValue) {
return previousValue !== nextValue;
}
export function getPaginationPageValue(dataPagination, fallbackPage) {
return dataPagination?.page || fallbackPage;
}
export function getProviderOptions(dataProviderOptions) {
return dataProviderOptions || [];
}
export async function reconcileConnectionsPage(fetchConnections, targetPage) {
return await fetchConnections(targetPage);
}
export function getQuotaCache() {
if (typeof window === "undefined") return {};
try {
const cached = window.localStorage.getItem(QUOTA_CACHE_KEY);
return cached ? JSON.parse(cached) : {};
} catch (error) {
console.error("Error reading quota cache:", error);
return {};
}
}
export function setQuotaCache(connectionId, quotaEntry) {
if (typeof window === "undefined") return;
try {
const cache = getQuotaCache();
cache[connectionId] = {
...quotaEntry,
cachedAt: new Date().toISOString(),
};
window.localStorage.setItem(QUOTA_CACHE_KEY, JSON.stringify(cache));
} catch (error) {
console.error("Error writing quota cache:", error);
}
}
/**
* Format ISO date string to countdown format (inspired by vscode-antigravity-cockpit)
* @param {string|Date} date - ISO date string or Date object