mirror of
https://github.com/router-for-me/Cli-Proxy-API-Management-Center.git
synced 2026-06-16 21:03:58 +08:00
Compare commits
39 Commits
+2
-1
@@ -1,7 +1,8 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<html lang="zh-CN" translate="no" class="notranslate">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="google" content="notranslate" />
|
||||
<link rel="icon" type="image/svg+xml" href="data:image/svg+xml,%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20xmlns%3Axlink%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxlink%22%20aria-hidden%3D%22true%22%20role%3D%22img%22%20class%3D%22iconify%20iconify--logos%22%20width%3D%2231.88%22%20height%3D%2232%22%20preserveAspectRatio%3D%22xMidYMid%20meet%22%20viewBox%3D%220%200%20256%20257%22%3E%3Cdefs%3E%3ClinearGradient%20id%3D%22IconifyId1813088fe1fbc01fb466%22%20x1%3D%22-.828%25%22%20x2%3D%2257.636%25%22%20y1%3D%227.652%25%22%20y2%3D%2278.411%25%22%3E%3Cstop%20offset%3D%220%25%22%20stop-color%3D%22%2341D1FF%22%3E%3C%2Fstop%3E%3Cstop%20offset%3D%22100%25%22%20stop-color%3D%22%23BD34FE%22%3E%3C%2Fstop%3E%3C%2FlinearGradient%3E%3ClinearGradient%20id%3D%22IconifyId1813088fe1fbc01fb467%22%20x1%3D%2243.376%25%22%20x2%3D%2250.316%25%22%20y1%3D%222.242%25%22%20y2%3D%2289.03%25%22%3E%3Cstop%20offset%3D%220%25%22%20stop-color%3D%22%23FFEA83%22%3E%3C%2Fstop%3E%3Cstop%20offset%3D%228.333%25%22%20stop-color%3D%22%23FFDD35%22%3E%3C%2Fstop%3E%3Cstop%20offset%3D%22100%25%22%20stop-color%3D%22%23FFA800%22%3E%3C%2Fstop%3E%3C%2FlinearGradient%3E%3C%2Fdefs%3E%3Cpath%20fill%3D%22url(%23IconifyId1813088fe1fbc01fb466)%22%20d%3D%22M255.153%2037.938L134.897%20252.976c-2.483%204.44-8.862%204.466-11.382.048L.875%2037.958c-2.746-4.814%201.371-10.646%206.827-9.67l120.385%2021.517a6.537%206.537%200%200%200%202.322-.004l117.867-21.483c5.438-.991%209.574%204.796%206.877%209.62Z%22%3E%3C%2Fpath%3E%3Cpath%20fill%3D%22url(%23IconifyId1813088fe1fbc01fb467)%22%20d%3D%22M185.432.063L96.44%2017.501a3.268%203.268%200%200%200-2.634%203.014l-5.474%2092.456a3.268%203.268%200%200%200%203.997%203.378l24.777-5.718c2.318-.535%204.413%201.507%203.936%203.838l-7.361%2036.047c-.495%202.426%201.782%204.5%204.151%203.78l15.304-4.649c2.372-.72%204.652%201.36%204.15%203.788l-11.698%2056.621c-.732%203.542%203.979%205.473%205.943%202.437l1.313-2.028l72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505%204.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z%22%3E%3C%2Fpath%3E%3C%2Fsvg%3E" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>CLI Proxy API Management Center</title>
|
||||
|
||||
@@ -2,7 +2,11 @@ import { ReactNode, useCallback, useLayoutEffect, useRef, useState } from 'react
|
||||
import { useLocation, type Location } from 'react-router-dom';
|
||||
import { animate } from 'motion/mini';
|
||||
import type { AnimationPlaybackControlsWithThen } from 'motion-dom';
|
||||
import { PageTransitionLayerContext, type LayerStatus } from './PageTransitionLayer';
|
||||
import {
|
||||
PAGE_TRANSITION_LAYER_CONTEXT_VALUES,
|
||||
PageTransitionLayerContext,
|
||||
type LayerStatus,
|
||||
} from './PageTransitionLayer';
|
||||
import './PageTransition.scss';
|
||||
|
||||
interface PageTransitionProps {
|
||||
@@ -386,7 +390,9 @@ export function PageTransition({
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<PageTransitionLayerContext.Provider value={{ status: layer.status }}>
|
||||
<PageTransitionLayerContext.Provider
|
||||
value={PAGE_TRANSITION_LAYER_CONTEXT_VALUES[layer.status]}
|
||||
>
|
||||
{render(layer.location)}
|
||||
</PageTransitionLayerContext.Provider>
|
||||
</div>
|
||||
|
||||
@@ -2,14 +2,20 @@ import { createContext, useContext } from 'react';
|
||||
|
||||
export type LayerStatus = 'current' | 'exiting' | 'stacked';
|
||||
|
||||
type PageTransitionLayerContextValue = {
|
||||
export type PageTransitionLayerContextValue = {
|
||||
status: LayerStatus;
|
||||
isCurrentLayer: boolean;
|
||||
};
|
||||
|
||||
export const PageTransitionLayerContext =
|
||||
createContext<PageTransitionLayerContextValue | null>(null);
|
||||
|
||||
export const PAGE_TRANSITION_LAYER_CONTEXT_VALUES: Record<LayerStatus, PageTransitionLayerContextValue> = {
|
||||
current: { status: 'current', isCurrentLayer: true },
|
||||
stacked: { status: 'stacked', isCurrentLayer: false },
|
||||
exiting: { status: 'exiting', isCurrentLayer: false },
|
||||
};
|
||||
|
||||
export function usePageTransitionLayer() {
|
||||
return useContext(PageTransitionLayerContext);
|
||||
}
|
||||
|
||||
|
||||
@@ -106,17 +106,16 @@
|
||||
gap: 8px;
|
||||
padding: 10px 12px;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--bg-primary) 82%, transparent);
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
border: 1px solid color-mix(in srgb, var(--border-color) 60%, transparent);
|
||||
--glass-blur: 12px;
|
||||
background: var(--glass-bg);
|
||||
backdrop-filter: var(--glass-backdrop-filter);
|
||||
-webkit-backdrop-filter: var(--glass-backdrop-filter);
|
||||
border: 1px solid var(--glass-border);
|
||||
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
|
||||
}
|
||||
|
||||
:global([data-theme='dark']) {
|
||||
.floatingActionSurface {
|
||||
background: color-mix(in srgb, var(--bg-primary) 82%, transparent);
|
||||
border-color: color-mix(in srgb, var(--border-color) 55%, transparent);
|
||||
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ export const SecondaryScreenShell = forwardRef<HTMLDivElement, SecondaryScreenSh
|
||||
const titleTooltip = typeof title === 'string' ? title : undefined;
|
||||
const resolvedBackAriaLabel = backAriaLabel ?? backLabel;
|
||||
const pageTransitionLayer = usePageTransitionLayer();
|
||||
const isCurrentLayer = pageTransitionLayer ? pageTransitionLayer.status === 'current' : true;
|
||||
const isCurrentLayer = pageTransitionLayer ? pageTransitionLayer.isCurrentLayer : true;
|
||||
const shouldRenderFloatingAction = Boolean(floatingAction) && isCurrentLayer;
|
||||
const floatingActionRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import { useMemo, type Ref } from 'react';
|
||||
import CodeMirror, { type ReactCodeMirrorRef } from '@uiw/react-codemirror';
|
||||
import { yaml } from '@codemirror/lang-yaml';
|
||||
import { search, searchKeymap, highlightSelectionMatches } from '@codemirror/search';
|
||||
import { keymap } from '@codemirror/view';
|
||||
|
||||
type ConfigSourceEditorProps = {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
editorRef?: Ref<ReactCodeMirrorRef>;
|
||||
theme: 'light' | 'dark';
|
||||
editable: boolean;
|
||||
placeholder: string;
|
||||
};
|
||||
|
||||
export default function ConfigSourceEditor({
|
||||
value,
|
||||
onChange,
|
||||
editorRef,
|
||||
theme,
|
||||
editable,
|
||||
placeholder,
|
||||
}: ConfigSourceEditorProps) {
|
||||
const extensions = useMemo(
|
||||
() => [yaml(), search(), highlightSelectionMatches(), keymap.of(searchKeymap)],
|
||||
[]
|
||||
);
|
||||
|
||||
return (
|
||||
<CodeMirror
|
||||
ref={editorRef}
|
||||
value={value}
|
||||
onChange={onChange}
|
||||
extensions={extensions}
|
||||
theme={theme}
|
||||
editable={editable}
|
||||
placeholder={placeholder}
|
||||
height="100%"
|
||||
style={{ height: '100%' }}
|
||||
basicSetup={{
|
||||
lineNumbers: true,
|
||||
highlightActiveLineGutter: true,
|
||||
highlightActiveLine: true,
|
||||
foldGutter: true,
|
||||
dropCursor: true,
|
||||
allowMultipleSelections: true,
|
||||
indentOnInput: true,
|
||||
bracketMatching: true,
|
||||
closeBrackets: true,
|
||||
autocompletion: false,
|
||||
rectangularSelection: true,
|
||||
crosshairCursor: false,
|
||||
highlightSelectionMatches: true,
|
||||
closeBracketsKeymap: true,
|
||||
searchKeymap: true,
|
||||
foldKeymap: true,
|
||||
completionKeymap: false,
|
||||
lintKeymap: true,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -395,8 +395,9 @@
|
||||
border-radius: 26px;
|
||||
border: 1px solid color-mix(in srgb, var(--border-color) 84%, transparent);
|
||||
background: color-mix(in srgb, var(--bg-primary) 76%, transparent);
|
||||
backdrop-filter: blur(14px);
|
||||
-webkit-backdrop-filter: blur(14px);
|
||||
--glass-blur: 14px;
|
||||
backdrop-filter: var(--glass-backdrop-filter);
|
||||
-webkit-backdrop-filter: var(--glass-backdrop-filter);
|
||||
box-shadow: 0 24px 56px -34px rgba(0, 0, 0, 0.42);
|
||||
-ms-overflow-style: none;
|
||||
scrollbar-width: none;
|
||||
@@ -408,10 +409,9 @@
|
||||
|
||||
.floatingSidebarContainer {
|
||||
position: fixed;
|
||||
left: var(--visual-config-floating-left, 16px);
|
||||
top: var(--visual-config-floating-top, 120px);
|
||||
width: var(--visual-config-floating-width, 280px);
|
||||
max-height: var(--visual-config-floating-max-height, calc(100vh - 136px));
|
||||
left: 0;
|
||||
top: 0;
|
||||
will-change: transform, width, max-height;
|
||||
z-index: 45;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
@@ -429,9 +429,7 @@
|
||||
padding: 12px;
|
||||
border-radius: 26px;
|
||||
border: 1px solid color-mix(in srgb, var(--border-color) 84%, transparent);
|
||||
background: color-mix(in srgb, var(--bg-primary) 76%, transparent);
|
||||
backdrop-filter: blur(14px);
|
||||
-webkit-backdrop-filter: blur(14px);
|
||||
background: color-mix(in srgb, var(--bg-primary) 96%, transparent);
|
||||
box-shadow: 0 24px 56px -34px rgba(0, 0, 0, 0.42);
|
||||
-ms-overflow-style: none;
|
||||
scrollbar-width: none;
|
||||
|
||||
@@ -179,7 +179,7 @@ export function VisualConfigEditor({
|
||||
}: VisualConfigEditorProps) {
|
||||
const { t } = useTranslation();
|
||||
const pageTransitionLayer = usePageTransitionLayer();
|
||||
const isCurrentLayer = pageTransitionLayer ? pageTransitionLayer.status === 'current' : true;
|
||||
const isCurrentLayer = pageTransitionLayer ? pageTransitionLayer.isCurrentLayer : true;
|
||||
const isMobile = useMediaQuery('(max-width: 768px)');
|
||||
const isFloatingSidebar = useMediaQuery('(min-width: 1025px)');
|
||||
const shouldRenderFloatingSidebar = !isMobile && isFloatingSidebar && isCurrentLayer;
|
||||
@@ -334,6 +334,7 @@ export function VisualConfigEditor({
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isCurrentLayer) return undefined;
|
||||
if (typeof IntersectionObserver === 'undefined') return undefined;
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
@@ -357,10 +358,10 @@ export function VisualConfigEditor({
|
||||
}
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, [sections]);
|
||||
}, [isCurrentLayer, sections]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isMobile) return;
|
||||
if (!isCurrentLayer || !isMobile) return;
|
||||
const scroller = mobileNavScrollerRef.current;
|
||||
const button = mobileNavButtonRefs.current[activeSectionId];
|
||||
if (!scroller || !button) return;
|
||||
@@ -378,7 +379,7 @@ export function VisualConfigEditor({
|
||||
left: targetLeft,
|
||||
behavior: 'smooth',
|
||||
});
|
||||
}, [activeSectionId, isMobile]);
|
||||
}, [activeSectionId, isCurrentLayer, isMobile]);
|
||||
|
||||
const handleSectionJump = useCallback((sectionId: VisualSectionId) => {
|
||||
setActiveSectionId(sectionId);
|
||||
@@ -392,10 +393,9 @@ export function VisualConfigEditor({
|
||||
if (!floatingElement) return undefined;
|
||||
|
||||
const clearFloatingStyles = () => {
|
||||
floatingElement.style.removeProperty('--visual-config-floating-left');
|
||||
floatingElement.style.removeProperty('--visual-config-floating-top');
|
||||
floatingElement.style.removeProperty('--visual-config-floating-width');
|
||||
floatingElement.style.removeProperty('--visual-config-floating-max-height');
|
||||
floatingElement.style.removeProperty('transform');
|
||||
floatingElement.style.removeProperty('width');
|
||||
floatingElement.style.removeProperty('max-height');
|
||||
floatingElement.style.removeProperty('opacity');
|
||||
floatingElement.style.removeProperty('pointer-events');
|
||||
};
|
||||
@@ -405,7 +405,8 @@ export function VisualConfigEditor({
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const getHeaderHeight = () => {
|
||||
/* ---- Cache header height – recomputed only on resize ---- */
|
||||
const computeHeaderHeight = () => {
|
||||
const header = document.querySelector('.main-header') as HTMLElement | null;
|
||||
if (header) return header.getBoundingClientRect().height;
|
||||
|
||||
@@ -413,8 +414,14 @@ export function VisualConfigEditor({
|
||||
const parsed = Number.parseFloat(raw);
|
||||
return Number.isFinite(parsed) ? parsed : 64;
|
||||
};
|
||||
let headerHeight = computeHeaderHeight();
|
||||
|
||||
/* ---- Cache content scroller – resolved once ---- */
|
||||
const contentScroller = document.querySelector('.content') as HTMLElement | null;
|
||||
|
||||
/* ---- Cache floating height from previous frame ---- */
|
||||
let cachedFloatingHeight = floatingElement.getBoundingClientRect().height || 200;
|
||||
|
||||
const getContentScroller = () => document.querySelector('.content') as HTMLElement | null;
|
||||
let frameId = 0;
|
||||
|
||||
const updateFloatingPosition = () => {
|
||||
@@ -422,10 +429,9 @@ export function VisualConfigEditor({
|
||||
|
||||
const anchorRect = anchorElement.getBoundingClientRect();
|
||||
const workspaceRect = workspaceElement.getBoundingClientRect();
|
||||
const floatingHeight = floatingElement.getBoundingClientRect().height;
|
||||
const stickyTop = getHeaderHeight() + 20;
|
||||
const stickyTop = headerHeight + 20;
|
||||
const viewportPadding = 16;
|
||||
const maxTop = workspaceRect.bottom - floatingHeight;
|
||||
const maxTop = workspaceRect.bottom - cachedFloatingHeight;
|
||||
const unclampedTop = Math.min(Math.max(anchorRect.top, stickyTop), maxTop);
|
||||
const top = Math.max(unclampedTop, viewportPadding);
|
||||
const left = Math.max(anchorRect.left, viewportPadding);
|
||||
@@ -436,10 +442,9 @@ export function VisualConfigEditor({
|
||||
const maxHeight = Math.max(window.innerHeight - top - viewportPadding, 160);
|
||||
const isVisible = workspaceRect.bottom > stickyTop + 24 && anchorRect.top < window.innerHeight;
|
||||
|
||||
floatingElement.style.setProperty('--visual-config-floating-left', `${left}px`);
|
||||
floatingElement.style.setProperty('--visual-config-floating-top', `${top}px`);
|
||||
floatingElement.style.setProperty('--visual-config-floating-width', `${width}px`);
|
||||
floatingElement.style.setProperty('--visual-config-floating-max-height', `${maxHeight}px`);
|
||||
floatingElement.style.transform = `translate3d(${left}px, ${top}px, 0)`;
|
||||
floatingElement.style.width = `${width}px`;
|
||||
floatingElement.style.maxHeight = `${maxHeight}px`;
|
||||
floatingElement.style.opacity = isVisible ? '1' : '0';
|
||||
floatingElement.style.pointerEvents = isVisible ? 'auto' : 'none';
|
||||
};
|
||||
@@ -449,10 +454,15 @@ export function VisualConfigEditor({
|
||||
frameId = requestAnimationFrame(updateFloatingPosition);
|
||||
};
|
||||
|
||||
const handleResize = () => {
|
||||
headerHeight = computeHeaderHeight();
|
||||
cachedFloatingHeight = floatingElement.getBoundingClientRect().height || cachedFloatingHeight;
|
||||
requestPositionUpdate();
|
||||
};
|
||||
|
||||
requestPositionUpdate();
|
||||
|
||||
const contentScroller = getContentScroller();
|
||||
window.addEventListener('resize', requestPositionUpdate);
|
||||
window.addEventListener('resize', handleResize);
|
||||
window.addEventListener('scroll', requestPositionUpdate, { passive: true });
|
||||
contentScroller?.addEventListener('scroll', requestPositionUpdate, { passive: true });
|
||||
|
||||
@@ -460,12 +470,11 @@ export function VisualConfigEditor({
|
||||
typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(requestPositionUpdate);
|
||||
resizeObserver?.observe(anchorElement);
|
||||
resizeObserver?.observe(workspaceElement);
|
||||
resizeObserver?.observe(floatingElement);
|
||||
|
||||
return () => {
|
||||
if (frameId) cancelAnimationFrame(frameId);
|
||||
resizeObserver?.disconnect();
|
||||
window.removeEventListener('resize', requestPositionUpdate);
|
||||
window.removeEventListener('resize', handleResize);
|
||||
window.removeEventListener('scroll', requestPositionUpdate);
|
||||
contentScroller?.removeEventListener('scroll', requestPositionUpdate);
|
||||
clearFloatingStyles();
|
||||
@@ -927,6 +936,15 @@ export function VisualConfigEditor({
|
||||
disabled={disabled}
|
||||
onChange={(quotaSwitchPreviewModel) => onChange({ quotaSwitchPreviewModel })}
|
||||
/>
|
||||
<ToggleRow
|
||||
title={t('config_management.visual.sections.quota.antigravity_credits')}
|
||||
description={t(
|
||||
'config_management.visual.sections.quota.antigravity_credits_desc'
|
||||
)}
|
||||
checked={values.quotaAntigravityCredits}
|
||||
disabled={disabled}
|
||||
onChange={(quotaAntigravityCredits) => onChange({ quotaAntigravityCredits })}
|
||||
/>
|
||||
</SectionGrid>
|
||||
</ConfigSection>
|
||||
|
||||
|
||||
@@ -10,8 +10,11 @@ import {
|
||||
buildCandidateUsageSourceIds,
|
||||
calculateStatusBarData,
|
||||
type KeyStats,
|
||||
type UsageDetail,
|
||||
} from '@/utils/usage';
|
||||
import {
|
||||
collectUsageDetailsForCandidates,
|
||||
type UsageDetailsBySource,
|
||||
} from '@/utils/usageIndex';
|
||||
import styles from '@/pages/AiProvidersPage.module.scss';
|
||||
import { ProviderList } from '../ProviderList';
|
||||
import { ProviderStatusBar } from '../ProviderStatusBar';
|
||||
@@ -20,7 +23,7 @@ import { getStatsBySource, hasDisableAllModelsRule } from '../utils';
|
||||
interface ClaudeSectionProps {
|
||||
configs: ProviderKeyConfig[];
|
||||
keyStats: KeyStats;
|
||||
usageDetails: UsageDetail[];
|
||||
usageDetailsBySource: UsageDetailsBySource;
|
||||
loading: boolean;
|
||||
disableControls: boolean;
|
||||
isSwitching: boolean;
|
||||
@@ -33,7 +36,7 @@ interface ClaudeSectionProps {
|
||||
export function ClaudeSection({
|
||||
configs,
|
||||
keyStats,
|
||||
usageDetails,
|
||||
usageDetailsBySource,
|
||||
loading,
|
||||
disableControls,
|
||||
isSwitching,
|
||||
@@ -56,13 +59,14 @@ export function ClaudeSection({
|
||||
prefix: config.prefix,
|
||||
});
|
||||
if (!candidates.length) return;
|
||||
const candidateSet = new Set(candidates);
|
||||
const filteredDetails = usageDetails.filter((detail) => candidateSet.has(detail.source));
|
||||
cache.set(config.apiKey, calculateStatusBarData(filteredDetails));
|
||||
cache.set(
|
||||
config.apiKey,
|
||||
calculateStatusBarData(collectUsageDetailsForCandidates(usageDetailsBySource, candidates))
|
||||
);
|
||||
});
|
||||
|
||||
return cache;
|
||||
}, [configs, usageDetails]);
|
||||
}, [configs, usageDetailsBySource]);
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -10,8 +10,11 @@ import {
|
||||
buildCandidateUsageSourceIds,
|
||||
calculateStatusBarData,
|
||||
type KeyStats,
|
||||
type UsageDetail,
|
||||
} from '@/utils/usage';
|
||||
import {
|
||||
collectUsageDetailsForCandidates,
|
||||
type UsageDetailsBySource,
|
||||
} from '@/utils/usageIndex';
|
||||
import styles from '@/pages/AiProvidersPage.module.scss';
|
||||
import { ProviderList } from '../ProviderList';
|
||||
import { ProviderStatusBar } from '../ProviderStatusBar';
|
||||
@@ -20,7 +23,7 @@ import { getStatsBySource, hasDisableAllModelsRule } from '../utils';
|
||||
interface CodexSectionProps {
|
||||
configs: ProviderKeyConfig[];
|
||||
keyStats: KeyStats;
|
||||
usageDetails: UsageDetail[];
|
||||
usageDetailsBySource: UsageDetailsBySource;
|
||||
loading: boolean;
|
||||
disableControls: boolean;
|
||||
isSwitching: boolean;
|
||||
@@ -33,7 +36,7 @@ interface CodexSectionProps {
|
||||
export function CodexSection({
|
||||
configs,
|
||||
keyStats,
|
||||
usageDetails,
|
||||
usageDetailsBySource,
|
||||
loading,
|
||||
disableControls,
|
||||
isSwitching,
|
||||
@@ -56,13 +59,14 @@ export function CodexSection({
|
||||
prefix: config.prefix,
|
||||
});
|
||||
if (!candidates.length) return;
|
||||
const candidateSet = new Set(candidates);
|
||||
const filteredDetails = usageDetails.filter((detail) => candidateSet.has(detail.source));
|
||||
cache.set(config.apiKey, calculateStatusBarData(filteredDetails));
|
||||
cache.set(
|
||||
config.apiKey,
|
||||
calculateStatusBarData(collectUsageDetailsForCandidates(usageDetailsBySource, candidates))
|
||||
);
|
||||
});
|
||||
|
||||
return cache;
|
||||
}, [configs, usageDetails]);
|
||||
}, [configs, usageDetailsBySource]);
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -10,8 +10,11 @@ import {
|
||||
buildCandidateUsageSourceIds,
|
||||
calculateStatusBarData,
|
||||
type KeyStats,
|
||||
type UsageDetail,
|
||||
} from '@/utils/usage';
|
||||
import {
|
||||
collectUsageDetailsForCandidates,
|
||||
type UsageDetailsBySource,
|
||||
} from '@/utils/usageIndex';
|
||||
import styles from '@/pages/AiProvidersPage.module.scss';
|
||||
import { ProviderList } from '../ProviderList';
|
||||
import { ProviderStatusBar } from '../ProviderStatusBar';
|
||||
@@ -20,7 +23,7 @@ import { getStatsBySource, hasDisableAllModelsRule } from '../utils';
|
||||
interface GeminiSectionProps {
|
||||
configs: GeminiKeyConfig[];
|
||||
keyStats: KeyStats;
|
||||
usageDetails: UsageDetail[];
|
||||
usageDetailsBySource: UsageDetailsBySource;
|
||||
loading: boolean;
|
||||
disableControls: boolean;
|
||||
isSwitching: boolean;
|
||||
@@ -33,7 +36,7 @@ interface GeminiSectionProps {
|
||||
export function GeminiSection({
|
||||
configs,
|
||||
keyStats,
|
||||
usageDetails,
|
||||
usageDetailsBySource,
|
||||
loading,
|
||||
disableControls,
|
||||
isSwitching,
|
||||
@@ -56,13 +59,14 @@ export function GeminiSection({
|
||||
prefix: config.prefix,
|
||||
});
|
||||
if (!candidates.length) return;
|
||||
const candidateSet = new Set(candidates);
|
||||
const filteredDetails = usageDetails.filter((detail) => candidateSet.has(detail.source));
|
||||
cache.set(config.apiKey, calculateStatusBarData(filteredDetails));
|
||||
cache.set(
|
||||
config.apiKey,
|
||||
calculateStatusBarData(collectUsageDetailsForCandidates(usageDetailsBySource, candidates))
|
||||
);
|
||||
});
|
||||
|
||||
return cache;
|
||||
}, [configs, usageDetails]);
|
||||
}, [configs, usageDetailsBySource]);
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -11,8 +11,8 @@ import {
|
||||
buildCandidateUsageSourceIds,
|
||||
calculateStatusBarData,
|
||||
type KeyStats,
|
||||
type UsageDetail,
|
||||
} from '@/utils/usage';
|
||||
import { collectUsageDetailsForCandidates, type UsageDetailsBySource } from '@/utils/usageIndex';
|
||||
import styles from '@/pages/AiProvidersPage.module.scss';
|
||||
import { ProviderList } from '../ProviderList';
|
||||
import { ProviderStatusBar } from '../ProviderStatusBar';
|
||||
@@ -21,7 +21,7 @@ import { getOpenAIProviderStats, getStatsBySource } from '../utils';
|
||||
interface OpenAISectionProps {
|
||||
configs: OpenAIProviderConfig[];
|
||||
keyStats: KeyStats;
|
||||
usageDetails: UsageDetail[];
|
||||
usageDetailsBySource: UsageDetailsBySource;
|
||||
loading: boolean;
|
||||
disableControls: boolean;
|
||||
isSwitching: boolean;
|
||||
@@ -34,7 +34,7 @@ interface OpenAISectionProps {
|
||||
export function OpenAISection({
|
||||
configs,
|
||||
keyStats,
|
||||
usageDetails,
|
||||
usageDetailsBySource,
|
||||
loading,
|
||||
disableControls,
|
||||
isSwitching,
|
||||
@@ -57,13 +57,13 @@ export function OpenAISection({
|
||||
});
|
||||
|
||||
const filteredDetails = sourceIds.size
|
||||
? usageDetails.filter((detail) => sourceIds.has(detail.source))
|
||||
? collectUsageDetailsForCandidates(usageDetailsBySource, sourceIds)
|
||||
: [];
|
||||
cache.set(provider.name, calculateStatusBarData(filteredDetails));
|
||||
});
|
||||
|
||||
return cache;
|
||||
}, [configs, usageDetails]);
|
||||
}, [configs, usageDetailsBySource]);
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -17,10 +17,11 @@
|
||||
flex-direction: row;
|
||||
gap: 6px;
|
||||
padding: 10px 12px;
|
||||
background: color-mix(in srgb, var(--bg-primary) 82%, transparent);
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
border: 1px solid color-mix(in srgb, var(--border-color) 60%, transparent);
|
||||
--glass-blur: 12px;
|
||||
background: var(--glass-bg);
|
||||
backdrop-filter: var(--glass-backdrop-filter);
|
||||
-webkit-backdrop-filter: var(--glass-backdrop-filter);
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: 999px;
|
||||
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.08);
|
||||
overflow-x: auto;
|
||||
@@ -104,8 +105,6 @@
|
||||
// 暗色主题适配
|
||||
:global([data-theme='dark']) {
|
||||
.navList {
|
||||
background: color-mix(in srgb, var(--bg-primary) 82%, transparent);
|
||||
border-color: color-mix(in srgb, var(--border-color) 55%, transparent);
|
||||
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.4);
|
||||
}
|
||||
|
||||
|
||||
@@ -10,8 +10,11 @@ import {
|
||||
buildCandidateUsageSourceIds,
|
||||
calculateStatusBarData,
|
||||
type KeyStats,
|
||||
type UsageDetail,
|
||||
} from '@/utils/usage';
|
||||
import {
|
||||
collectUsageDetailsForCandidates,
|
||||
type UsageDetailsBySource,
|
||||
} from '@/utils/usageIndex';
|
||||
import styles from '@/pages/AiProvidersPage.module.scss';
|
||||
import { ProviderList } from '../ProviderList';
|
||||
import { ProviderStatusBar } from '../ProviderStatusBar';
|
||||
@@ -20,7 +23,7 @@ import { getStatsBySource, hasDisableAllModelsRule } from '../utils';
|
||||
interface VertexSectionProps {
|
||||
configs: ProviderKeyConfig[];
|
||||
keyStats: KeyStats;
|
||||
usageDetails: UsageDetail[];
|
||||
usageDetailsBySource: UsageDetailsBySource;
|
||||
loading: boolean;
|
||||
disableControls: boolean;
|
||||
isSwitching: boolean;
|
||||
@@ -33,7 +36,7 @@ interface VertexSectionProps {
|
||||
export function VertexSection({
|
||||
configs,
|
||||
keyStats,
|
||||
usageDetails,
|
||||
usageDetailsBySource,
|
||||
loading,
|
||||
disableControls,
|
||||
isSwitching,
|
||||
@@ -56,13 +59,14 @@ export function VertexSection({
|
||||
prefix: config.prefix,
|
||||
});
|
||||
if (!candidates.length) return;
|
||||
const candidateSet = new Set(candidates);
|
||||
const filteredDetails = usageDetails.filter((detail) => candidateSet.has(detail.source));
|
||||
cache.set(config.apiKey, calculateStatusBarData(filteredDetails));
|
||||
cache.set(
|
||||
config.apiKey,
|
||||
calculateStatusBarData(collectUsageDetailsForCandidates(usageDetailsBySource, candidates))
|
||||
);
|
||||
});
|
||||
|
||||
return cache;
|
||||
}, [configs, usageDetails]);
|
||||
}, [configs, usageDetailsBySource]);
|
||||
|
||||
return (
|
||||
<>
|
||||
|
||||
@@ -1,11 +1,22 @@
|
||||
import { useCallback } from 'react';
|
||||
import { useInterval } from '@/hooks/useInterval';
|
||||
import { USAGE_STATS_STALE_TIME_MS, useUsageStatsStore } from '@/stores';
|
||||
import type { KeyStats, UsageDetail } from '@/utils/usage';
|
||||
|
||||
export const useProviderStats = () => {
|
||||
const keyStats = useUsageStatsStore((state) => state.keyStats);
|
||||
const usageDetails = useUsageStatsStore((state) => state.usageDetails);
|
||||
const isLoading = useUsageStatsStore((state) => state.loading);
|
||||
const EMPTY_KEY_STATS: KeyStats = { bySource: {}, byAuthIndex: {} };
|
||||
const EMPTY_USAGE_DETAILS: UsageDetail[] = [];
|
||||
|
||||
export type UseProviderStatsOptions = {
|
||||
enabled?: boolean;
|
||||
};
|
||||
|
||||
export const useProviderStats = (options: UseProviderStatsOptions = {}) => {
|
||||
const enabled = options.enabled ?? true;
|
||||
const keyStats = useUsageStatsStore((state) => (enabled ? state.keyStats : EMPTY_KEY_STATS));
|
||||
const usageDetails = useUsageStatsStore((state) =>
|
||||
enabled ? state.usageDetails : EMPTY_USAGE_DETAILS
|
||||
);
|
||||
const isLoading = useUsageStatsStore((state) => (enabled ? state.loading : false));
|
||||
const loadUsageStats = useUsageStatsStore((state) => state.loadUsageStats);
|
||||
|
||||
// 首次进入页面优先复用缓存,避免跨页面重复拉取 /usage。
|
||||
@@ -20,7 +31,7 @@ export const useProviderStats = () => {
|
||||
|
||||
useInterval(() => {
|
||||
void refreshKeyStats().catch(() => {});
|
||||
}, 240_000);
|
||||
}, enabled ? 240_000 : null);
|
||||
|
||||
return { keyStats, usageDetails, loadKeyStats, refreshKeyStats, isLoading };
|
||||
};
|
||||
|
||||
@@ -64,6 +64,8 @@ interface QuotaCardProps<TState extends QuotaStatusState> {
|
||||
cardIdleMessageKey?: string;
|
||||
cardClassName: string;
|
||||
defaultType: string;
|
||||
canRefresh?: boolean;
|
||||
onRefresh?: () => void;
|
||||
renderQuotaItems: (quota: TState, t: TFunction, helpers: QuotaRenderHelpers) => ReactNode;
|
||||
}
|
||||
|
||||
@@ -75,6 +77,8 @@ export function QuotaCard<TState extends QuotaStatusState>({
|
||||
cardIdleMessageKey,
|
||||
cardClassName,
|
||||
defaultType,
|
||||
canRefresh = false,
|
||||
onRefresh,
|
||||
renderQuotaItems
|
||||
}: QuotaCardProps<TState>) {
|
||||
const { t } = useTranslation();
|
||||
@@ -90,7 +94,7 @@ export function QuotaCard<TState extends QuotaStatusState>({
|
||||
quota?.errorStatus,
|
||||
quota?.error || t('common.unknown_error')
|
||||
);
|
||||
const idleMessageKey = cardIdleMessageKey ?? `${i18nPrefix}.idle`;
|
||||
const idleMessageKey = onRefresh ? `${i18nPrefix}.idle` : (cardIdleMessageKey ?? `${i18nPrefix}.idle`);
|
||||
|
||||
const getTypeLabel = (type: string): string => {
|
||||
const key = `auth_files.filter_${type}`;
|
||||
@@ -120,7 +124,18 @@ export function QuotaCard<TState extends QuotaStatusState>({
|
||||
{quotaStatus === 'loading' ? (
|
||||
<div className={styles.quotaMessage}>{t(`${i18nPrefix}.loading`)}</div>
|
||||
) : quotaStatus === 'idle' ? (
|
||||
<div className={styles.quotaMessage}>{t(idleMessageKey)}</div>
|
||||
onRefresh ? (
|
||||
<button
|
||||
type="button"
|
||||
className={`${styles.quotaMessage} ${styles.quotaMessageAction}`}
|
||||
onClick={onRefresh}
|
||||
disabled={!canRefresh}
|
||||
>
|
||||
{t(idleMessageKey)}
|
||||
</button>
|
||||
) : (
|
||||
<div className={styles.quotaMessage}>{t(idleMessageKey)}</div>
|
||||
)
|
||||
) : quotaStatus === 'error' ? (
|
||||
<div className={styles.quotaError}>
|
||||
{t(`${i18nPrefix}.load_failed`, {
|
||||
|
||||
@@ -8,8 +8,9 @@ import { Card } from '@/components/ui/Card';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { EmptyState } from '@/components/ui/EmptyState';
|
||||
import { triggerHeaderRefresh } from '@/hooks/useHeaderRefresh';
|
||||
import { useQuotaStore, useThemeStore } from '@/stores';
|
||||
import { useNotificationStore, useQuotaStore, useThemeStore } from '@/stores';
|
||||
import type { AuthFileItem, ResolvedTheme } from '@/types';
|
||||
import { getStatusFromError } from '@/utils/quota';
|
||||
import { QuotaCard } from './QuotaCard';
|
||||
import type { QuotaStatusState } from './QuotaCard';
|
||||
import { useQuotaLoader } from './useQuotaLoader';
|
||||
@@ -105,6 +106,7 @@ export function QuotaSection<TState extends QuotaStatusState, TData>({
|
||||
}: QuotaSectionProps<TState, TData>) {
|
||||
const { t } = useTranslation();
|
||||
const resolvedTheme: ResolvedTheme = useThemeStore((state) => state.resolvedTheme);
|
||||
const showNotification = useNotificationStore((state) => state.showNotification);
|
||||
const setQuota = useQuotaStore((state) => state[config.storeSetter]) as QuotaSetter<
|
||||
Record<string, TState>
|
||||
>;
|
||||
@@ -202,6 +204,39 @@ export function QuotaSection<TState extends QuotaStatusState, TData>({
|
||||
});
|
||||
}, [filteredFiles, loading, setQuota]);
|
||||
|
||||
const refreshQuotaForFile = useCallback(
|
||||
async (file: AuthFileItem) => {
|
||||
if (disabled || file.disabled) return;
|
||||
if (quota[file.name]?.status === 'loading') return;
|
||||
|
||||
setQuota((prev) => ({
|
||||
...prev,
|
||||
[file.name]: config.buildLoadingState()
|
||||
}));
|
||||
|
||||
try {
|
||||
const data = await config.fetchQuota(file, t);
|
||||
setQuota((prev) => ({
|
||||
...prev,
|
||||
[file.name]: config.buildSuccessState(data)
|
||||
}));
|
||||
showNotification(t('auth_files.quota_refresh_success', { name: file.name }), 'success');
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : t('common.unknown_error');
|
||||
const status = getStatusFromError(err);
|
||||
setQuota((prev) => ({
|
||||
...prev,
|
||||
[file.name]: config.buildErrorState(message, status)
|
||||
}));
|
||||
showNotification(
|
||||
t('auth_files.quota_refresh_failed', { name: file.name, message }),
|
||||
'error'
|
||||
);
|
||||
}
|
||||
},
|
||||
[config, disabled, quota, setQuota, showNotification, t]
|
||||
);
|
||||
|
||||
const titleNode = (
|
||||
<div className={styles.titleWrapper}>
|
||||
<span>{t(`${config.i18nPrefix}.title`)}</span>
|
||||
@@ -222,15 +257,21 @@ export function QuotaSection<TState extends QuotaStatusState, TData>({
|
||||
<div className={styles.headerActions}>
|
||||
<div className={styles.viewModeToggle}>
|
||||
<Button
|
||||
variant={effectiveViewMode === 'paged' ? 'primary' : 'secondary'}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className={`${styles.viewModeButton} ${
|
||||
effectiveViewMode === 'paged' ? styles.viewModeButtonActive : ''
|
||||
}`}
|
||||
onClick={() => setViewMode('paged')}
|
||||
>
|
||||
{t('auth_files.view_mode_paged')}
|
||||
</Button>
|
||||
<Button
|
||||
variant={effectiveViewMode === 'all' ? 'primary' : 'secondary'}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className={`${styles.viewModeButton} ${
|
||||
effectiveViewMode === 'all' ? styles.viewModeButtonActive : ''
|
||||
}`}
|
||||
onClick={() => {
|
||||
if (filteredFiles.length > MAX_SHOW_ALL_THRESHOLD) {
|
||||
setShowTooManyWarning(true);
|
||||
@@ -245,13 +286,15 @@ export function QuotaSection<TState extends QuotaStatusState, TData>({
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
className={styles.refreshAllButton}
|
||||
onClick={handleRefresh}
|
||||
disabled={disabled || isRefreshing}
|
||||
loading={isRefreshing}
|
||||
title={t('quota_management.refresh_files_and_quota')}
|
||||
aria-label={t('quota_management.refresh_files_and_quota')}
|
||||
title={t('quota_management.refresh_all_credentials')}
|
||||
aria-label={t('quota_management.refresh_all_credentials')}
|
||||
>
|
||||
{!isRefreshing && <IconRefreshCw size={16} />}
|
||||
{t('quota_management.refresh_all_credentials')}
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
@@ -274,6 +317,8 @@ export function QuotaSection<TState extends QuotaStatusState, TData>({
|
||||
cardIdleMessageKey={config.cardIdleMessageKey}
|
||||
cardClassName={config.cardClassName}
|
||||
defaultType={config.type}
|
||||
canRefresh={!disabled && !item.disabled}
|
||||
onRefresh={() => void refreshQuotaForFile(item)}
|
||||
renderQuotaItems={config.renderQuotaItems}
|
||||
/>
|
||||
))}
|
||||
|
||||
@@ -84,6 +84,8 @@ type QuotaUpdater<T> = T | ((prev: T) => T);
|
||||
type QuotaType = 'antigravity' | 'claude' | 'codex' | 'gemini-cli' | 'kimi';
|
||||
|
||||
const DEFAULT_ANTIGRAVITY_PROJECT_ID = 'bamboo-precept-lgxtn';
|
||||
const QUOTA_PROGRESS_HIGH_THRESHOLD = 70;
|
||||
const QUOTA_PROGRESS_MEDIUM_THRESHOLD = 30;
|
||||
const geminiCliSupplementaryRequestIds = new Map<string, number>();
|
||||
const geminiCliSupplementaryCache = new Map<
|
||||
string,
|
||||
@@ -721,12 +723,17 @@ const renderAntigravityItems = (
|
||||
h('span', { className: styleMap.quotaReset }, resetLabel)
|
||||
)
|
||||
),
|
||||
h(QuotaProgressBar, { percent, highThreshold: 60, mediumThreshold: 20 })
|
||||
h(QuotaProgressBar, {
|
||||
percent,
|
||||
highThreshold: QUOTA_PROGRESS_HIGH_THRESHOLD,
|
||||
mediumThreshold: QUOTA_PROGRESS_MEDIUM_THRESHOLD,
|
||||
})
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
const PREMIUM_GEMINI_CLI_TIER_IDS = new Set(['g1-ultra-tier']);
|
||||
const PREMIUM_CODEX_PLAN_TYPES = new Set(['pro', 'prolite', 'pro-lite', 'pro_lite']);
|
||||
|
||||
const renderCodexItems = (
|
||||
quota: CodexQuotaState,
|
||||
@@ -742,6 +749,9 @@ const renderCodexItems = (
|
||||
const normalized = normalizePlanType(pt);
|
||||
if (!normalized) return null;
|
||||
if (normalized === 'pro') return t('codex_quota.plan_pro');
|
||||
if (PREMIUM_CODEX_PLAN_TYPES.has(normalized) && normalized !== 'pro') {
|
||||
return t('codex_quota.plan_prolite');
|
||||
}
|
||||
if (normalized === 'plus') return t('codex_quota.plan_plus');
|
||||
if (normalized === 'team') return t('codex_quota.plan_team');
|
||||
if (normalized === 'free') return t('codex_quota.plan_free');
|
||||
@@ -749,7 +759,7 @@ const renderCodexItems = (
|
||||
};
|
||||
|
||||
const planLabel = getPlanLabel(planType);
|
||||
const isPremiumPlan = normalizePlanType(planType) === 'pro';
|
||||
const isPremiumPlan = PREMIUM_CODEX_PLAN_TYPES.has(normalizePlanType(planType) ?? '');
|
||||
const nodes: ReactNode[] = [];
|
||||
|
||||
if (planLabel) {
|
||||
@@ -795,7 +805,11 @@ const renderCodexItems = (
|
||||
h('span', { className: styleMap.quotaReset }, window.resetLabel)
|
||||
)
|
||||
),
|
||||
h(QuotaProgressBar, { percent: remaining, highThreshold: 80, mediumThreshold: 50 })
|
||||
h(QuotaProgressBar, {
|
||||
percent: remaining,
|
||||
highThreshold: QUOTA_PROGRESS_HIGH_THRESHOLD,
|
||||
mediumThreshold: QUOTA_PROGRESS_MEDIUM_THRESHOLD,
|
||||
})
|
||||
);
|
||||
})
|
||||
);
|
||||
@@ -886,7 +900,11 @@ const renderGeminiCliItems = (
|
||||
h('span', { className: styleMap.quotaReset }, resetLabel)
|
||||
)
|
||||
),
|
||||
h(QuotaProgressBar, { percent, highThreshold: 60, mediumThreshold: 20 })
|
||||
h(QuotaProgressBar, {
|
||||
percent,
|
||||
highThreshold: QUOTA_PROGRESS_HIGH_THRESHOLD,
|
||||
mediumThreshold: QUOTA_PROGRESS_MEDIUM_THRESHOLD,
|
||||
})
|
||||
);
|
||||
})
|
||||
);
|
||||
@@ -1078,7 +1096,11 @@ const renderClaudeItems = (
|
||||
h('span', { className: styleMap.quotaReset }, window.resetLabel)
|
||||
)
|
||||
),
|
||||
h(QuotaProgressBar, { percent: remaining, highThreshold: 80, mediumThreshold: 50 })
|
||||
h(QuotaProgressBar, {
|
||||
percent: remaining,
|
||||
highThreshold: QUOTA_PROGRESS_HIGH_THRESHOLD,
|
||||
mediumThreshold: QUOTA_PROGRESS_MEDIUM_THRESHOLD,
|
||||
})
|
||||
);
|
||||
})
|
||||
);
|
||||
@@ -1293,7 +1315,11 @@ const renderKimiItems = (
|
||||
: null
|
||||
)
|
||||
),
|
||||
h(QuotaProgressBar, { percent: remaining, highThreshold: 60, mediumThreshold: 20 })
|
||||
h(QuotaProgressBar, {
|
||||
percent: remaining,
|
||||
highThreshold: QUOTA_PROGRESS_HIGH_THRESHOLD,
|
||||
mediumThreshold: QUOTA_PROGRESS_MEDIUM_THRESHOLD,
|
||||
})
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,17 +1,16 @@
|
||||
import { useState, useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Card } from '@/components/ui/Card';
|
||||
import { formatCompactNumber, formatUsd } from '@/utils/usage';
|
||||
import {
|
||||
LATENCY_SOURCE_FIELD,
|
||||
formatCompactNumber,
|
||||
formatDurationMs,
|
||||
formatUsd,
|
||||
type ModelStatsSummary,
|
||||
} from '@/utils/usage';
|
||||
import styles from '@/pages/UsagePage.module.scss';
|
||||
|
||||
export interface ModelStat {
|
||||
model: string;
|
||||
requests: number;
|
||||
successCount: number;
|
||||
failureCount: number;
|
||||
tokens: number;
|
||||
cost: number;
|
||||
}
|
||||
export type ModelStat = ModelStatsSummary;
|
||||
|
||||
export interface ModelStatsCardProps {
|
||||
modelStats: ModelStat[];
|
||||
@@ -19,7 +18,14 @@ export interface ModelStatsCardProps {
|
||||
hasPrices: boolean;
|
||||
}
|
||||
|
||||
type SortKey = 'model' | 'requests' | 'tokens' | 'cost' | 'successRate';
|
||||
type SortKey =
|
||||
| 'model'
|
||||
| 'requests'
|
||||
| 'tokens'
|
||||
| 'cost'
|
||||
| 'successRate'
|
||||
| 'averageLatencyMs'
|
||||
| 'totalLatencyMs';
|
||||
type SortDir = 'asc' | 'desc';
|
||||
|
||||
interface ModelStatWithRate extends ModelStat {
|
||||
@@ -30,6 +36,10 @@ export function ModelStatsCard({ modelStats, loading, hasPrices }: ModelStatsCar
|
||||
const { t } = useTranslation();
|
||||
const [sortKey, setSortKey] = useState<SortKey>('requests');
|
||||
const [sortDir, setSortDir] = useState<SortDir>('desc');
|
||||
const latencyHint = t('usage_stats.latency_unit_hint', {
|
||||
field: LATENCY_SOURCE_FIELD,
|
||||
unit: t('usage_stats.duration_unit_ms'),
|
||||
});
|
||||
|
||||
const handleSort = (key: SortKey) => {
|
||||
if (sortKey === key) {
|
||||
@@ -48,109 +58,159 @@ export function ModelStatsCard({ modelStats, loading, hasPrices }: ModelStatsCar
|
||||
const dir = sortDir === 'asc' ? 1 : -1;
|
||||
list.sort((a, b) => {
|
||||
if (sortKey === 'model') return dir * a.model.localeCompare(b.model);
|
||||
return dir * ((a[sortKey] as number) - (b[sortKey] as number));
|
||||
const left = a[sortKey];
|
||||
const right = b[sortKey];
|
||||
const leftValid = typeof left === 'number' && Number.isFinite(left);
|
||||
const rightValid = typeof right === 'number' && Number.isFinite(right);
|
||||
|
||||
if (!leftValid && !rightValid) return 0;
|
||||
if (!leftValid) return 1;
|
||||
if (!rightValid) return -1;
|
||||
return dir * (left - right);
|
||||
});
|
||||
return list;
|
||||
}, [modelStats, sortKey, sortDir]);
|
||||
|
||||
const arrow = (key: SortKey) =>
|
||||
sortKey === key ? (sortDir === 'asc' ? ' ▲' : ' ▼') : '';
|
||||
const arrow = (key: SortKey) => (sortKey === key ? (sortDir === 'asc' ? ' ▲' : ' ▼') : '');
|
||||
const ariaSort = (key: SortKey): 'none' | 'ascending' | 'descending' =>
|
||||
sortKey === key ? (sortDir === 'asc' ? 'ascending' : 'descending') : 'none';
|
||||
const hasLatencyData = sorted.some((stat) => stat.latencySampleCount > 0);
|
||||
|
||||
return (
|
||||
<Card title={t('usage_stats.models')} className={styles.detailsFixedCard}>
|
||||
{loading ? (
|
||||
<div className={styles.hint}>{t('common.loading')}</div>
|
||||
) : sorted.length > 0 ? (
|
||||
<div className={styles.detailsScroll}>
|
||||
<div className={styles.tableWrapper}>
|
||||
<table className={styles.table}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className={styles.sortableHeader} aria-sort={ariaSort('model')}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.sortHeaderButton}
|
||||
onClick={() => handleSort('model')}
|
||||
>
|
||||
{t('usage_stats.model_name')}{arrow('model')}
|
||||
</button>
|
||||
</th>
|
||||
<th className={styles.sortableHeader} aria-sort={ariaSort('requests')}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.sortHeaderButton}
|
||||
onClick={() => handleSort('requests')}
|
||||
>
|
||||
{t('usage_stats.requests_count')}{arrow('requests')}
|
||||
</button>
|
||||
</th>
|
||||
<th className={styles.sortableHeader} aria-sort={ariaSort('tokens')}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.sortHeaderButton}
|
||||
onClick={() => handleSort('tokens')}
|
||||
>
|
||||
{t('usage_stats.tokens_count')}{arrow('tokens')}
|
||||
</button>
|
||||
</th>
|
||||
<th className={styles.sortableHeader} aria-sort={ariaSort('successRate')}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.sortHeaderButton}
|
||||
onClick={() => handleSort('successRate')}
|
||||
>
|
||||
{t('usage_stats.success_rate')}{arrow('successRate')}
|
||||
</button>
|
||||
</th>
|
||||
{hasPrices && (
|
||||
<th className={styles.sortableHeader} aria-sort={ariaSort('cost')}>
|
||||
<>
|
||||
{hasLatencyData && <div className={styles.detailsNote}>{latencyHint}</div>}
|
||||
<div className={styles.detailsScroll}>
|
||||
<div className={styles.tableWrapper}>
|
||||
<table className={styles.table}>
|
||||
<thead>
|
||||
<tr>
|
||||
<th className={styles.sortableHeader} aria-sort={ariaSort('model')}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.sortHeaderButton}
|
||||
onClick={() => handleSort('cost')}
|
||||
onClick={() => handleSort('model')}
|
||||
>
|
||||
{t('usage_stats.total_cost')}{arrow('cost')}
|
||||
{t('usage_stats.model_name')}
|
||||
{arrow('model')}
|
||||
</button>
|
||||
</th>
|
||||
)}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sorted.map((stat) => (
|
||||
<tr key={stat.model}>
|
||||
<td className={styles.modelCell}>{stat.model}</td>
|
||||
<td>
|
||||
<span className={styles.requestCountCell}>
|
||||
<span>{stat.requests.toLocaleString()}</span>
|
||||
<span className={styles.requestBreakdown}>
|
||||
(<span className={styles.statSuccess}>{stat.successCount.toLocaleString()}</span>{' '}
|
||||
<span className={styles.statFailure}>{stat.failureCount.toLocaleString()}</span>)
|
||||
</span>
|
||||
</span>
|
||||
</td>
|
||||
<td>{formatCompactNumber(stat.tokens)}</td>
|
||||
<td>
|
||||
<span
|
||||
className={
|
||||
stat.successRate >= 95
|
||||
? styles.statSuccess
|
||||
: stat.successRate >= 80
|
||||
? styles.statNeutral
|
||||
: styles.statFailure
|
||||
}
|
||||
<th className={styles.sortableHeader} aria-sort={ariaSort('requests')}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.sortHeaderButton}
|
||||
onClick={() => handleSort('requests')}
|
||||
>
|
||||
{stat.successRate.toFixed(1)}%
|
||||
</span>
|
||||
</td>
|
||||
{hasPrices && <td>{stat.cost > 0 ? formatUsd(stat.cost) : '--'}</td>}
|
||||
{t('usage_stats.requests_count')}
|
||||
{arrow('requests')}
|
||||
</button>
|
||||
</th>
|
||||
<th className={styles.sortableHeader} aria-sort={ariaSort('tokens')}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.sortHeaderButton}
|
||||
onClick={() => handleSort('tokens')}
|
||||
>
|
||||
{t('usage_stats.tokens_count')}
|
||||
{arrow('tokens')}
|
||||
</button>
|
||||
</th>
|
||||
<th className={styles.sortableHeader} aria-sort={ariaSort('averageLatencyMs')}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.sortHeaderButton}
|
||||
onClick={() => handleSort('averageLatencyMs')}
|
||||
title={latencyHint}
|
||||
>
|
||||
{t('usage_stats.avg_time')}
|
||||
{arrow('averageLatencyMs')}
|
||||
</button>
|
||||
</th>
|
||||
<th className={styles.sortableHeader} aria-sort={ariaSort('totalLatencyMs')}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.sortHeaderButton}
|
||||
onClick={() => handleSort('totalLatencyMs')}
|
||||
title={latencyHint}
|
||||
>
|
||||
{t('usage_stats.total_time')}
|
||||
{arrow('totalLatencyMs')}
|
||||
</button>
|
||||
</th>
|
||||
<th className={styles.sortableHeader} aria-sort={ariaSort('successRate')}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.sortHeaderButton}
|
||||
onClick={() => handleSort('successRate')}
|
||||
>
|
||||
{t('usage_stats.success_rate')}
|
||||
{arrow('successRate')}
|
||||
</button>
|
||||
</th>
|
||||
{hasPrices && (
|
||||
<th className={styles.sortableHeader} aria-sort={ariaSort('cost')}>
|
||||
<button
|
||||
type="button"
|
||||
className={styles.sortHeaderButton}
|
||||
onClick={() => handleSort('cost')}
|
||||
>
|
||||
{t('usage_stats.total_cost')}
|
||||
{arrow('cost')}
|
||||
</button>
|
||||
</th>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sorted.map((stat) => (
|
||||
<tr key={stat.model}>
|
||||
<td className={styles.modelCell}>{stat.model}</td>
|
||||
<td>
|
||||
<span className={styles.requestCountCell}>
|
||||
<span>{stat.requests.toLocaleString()}</span>
|
||||
<span className={styles.requestBreakdown}>
|
||||
(
|
||||
<span className={styles.statSuccess}>
|
||||
{stat.successCount.toLocaleString()}
|
||||
</span>{' '}
|
||||
<span className={styles.statFailure}>
|
||||
{stat.failureCount.toLocaleString()}
|
||||
</span>
|
||||
)
|
||||
</span>
|
||||
</span>
|
||||
</td>
|
||||
<td>{formatCompactNumber(stat.tokens)}</td>
|
||||
<td className={styles.durationCell}>
|
||||
{formatDurationMs(stat.averageLatencyMs)}
|
||||
</td>
|
||||
<td className={styles.durationCell}>
|
||||
{formatDurationMs(stat.totalLatencyMs)}
|
||||
</td>
|
||||
<td>
|
||||
<span
|
||||
className={
|
||||
stat.successRate >= 95
|
||||
? styles.statSuccess
|
||||
: stat.successRate >= 80
|
||||
? styles.statNeutral
|
||||
: styles.statFailure
|
||||
}
|
||||
>
|
||||
{stat.successRate.toFixed(1)}%
|
||||
</span>
|
||||
</td>
|
||||
{hasPrices && <td>{stat.cost > 0 ? formatUsd(stat.cost) : '--'}</td>}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className={styles.hint}>{t('usage_stats.no_data')}</div>
|
||||
)}
|
||||
|
||||
@@ -11,8 +11,11 @@ import type { CredentialInfo } from '@/types/sourceInfo';
|
||||
import { buildSourceInfoMap, resolveSourceDisplay } from '@/utils/sourceResolver';
|
||||
import {
|
||||
collectUsageDetails,
|
||||
extractLatencyMs,
|
||||
extractTotalTokens,
|
||||
normalizeAuthIndex
|
||||
formatDurationMs,
|
||||
LATENCY_SOURCE_FIELD,
|
||||
normalizeAuthIndex,
|
||||
} from '@/utils/usage';
|
||||
import { downloadBlob } from '@/utils/download';
|
||||
import styles from '@/pages/UsagePage.module.scss';
|
||||
@@ -31,6 +34,7 @@ type RequestEventRow = {
|
||||
sourceType: string;
|
||||
authIndex: string;
|
||||
failed: boolean;
|
||||
latencyMs: number | null;
|
||||
inputTokens: number;
|
||||
outputTokens: number;
|
||||
reasoningTokens: number;
|
||||
@@ -68,9 +72,13 @@ export function RequestEventsDetailsCard({
|
||||
claudeConfigs,
|
||||
codexConfigs,
|
||||
vertexConfigs,
|
||||
openaiProviders
|
||||
openaiProviders,
|
||||
}: RequestEventsDetailsCardProps) {
|
||||
const { t, i18n } = useTranslation();
|
||||
const latencyHint = t('usage_stats.latency_unit_hint', {
|
||||
field: LATENCY_SOURCE_FIELD,
|
||||
unit: t('usage_stats.duration_unit_ms'),
|
||||
});
|
||||
|
||||
const [modelFilter, setModelFilter] = useState(ALL_FILTER);
|
||||
const [sourceFilter, setSourceFilter] = useState(ALL_FILTER);
|
||||
@@ -91,7 +99,7 @@ export function RequestEventsDetailsCard({
|
||||
if (!key) return;
|
||||
map.set(key, {
|
||||
name: file.name || key,
|
||||
type: (file.type || file.provider || '').toString()
|
||||
type: (file.type || file.provider || '').toString(),
|
||||
});
|
||||
});
|
||||
setAuthFileMap(map);
|
||||
@@ -131,7 +139,12 @@ export function RequestEventsDetailsCard({
|
||||
authIndexRaw === null || authIndexRaw === undefined || authIndexRaw === ''
|
||||
? '-'
|
||||
: String(authIndexRaw);
|
||||
const sourceInfo = resolveSourceDisplay(sourceRaw, authIndexRaw, sourceInfoMap, authFileMap);
|
||||
const sourceInfo = resolveSourceDisplay(
|
||||
sourceRaw,
|
||||
authIndexRaw,
|
||||
sourceInfoMap,
|
||||
authFileMap
|
||||
);
|
||||
const source = sourceInfo.displayName;
|
||||
const sourceType = sourceInfo.type;
|
||||
const model = String(detail.__modelName ?? '').trim() || '-';
|
||||
@@ -146,6 +159,7 @@ export function RequestEventsDetailsCard({
|
||||
toNumber(detail.tokens?.total_tokens),
|
||||
extractTotalTokens(detail)
|
||||
);
|
||||
const latencyMs = extractLatencyMs(detail);
|
||||
|
||||
return {
|
||||
id: `${timestamp}-${model}-${sourceRaw || source}-${authIndex}-${index}`,
|
||||
@@ -158,23 +172,26 @@ export function RequestEventsDetailsCard({
|
||||
sourceType,
|
||||
authIndex,
|
||||
failed: detail.failed === true,
|
||||
latencyMs,
|
||||
inputTokens,
|
||||
outputTokens,
|
||||
reasoningTokens,
|
||||
cachedTokens,
|
||||
totalTokens
|
||||
totalTokens,
|
||||
};
|
||||
})
|
||||
.sort((a, b) => b.timestampMs - a.timestampMs);
|
||||
}, [authFileMap, i18n.language, sourceInfoMap, usage]);
|
||||
|
||||
const hasLatencyData = useMemo(() => rows.some((row) => row.latencyMs !== null), [rows]);
|
||||
|
||||
const modelOptions = useMemo(
|
||||
() => [
|
||||
{ value: ALL_FILTER, label: t('usage_stats.filter_all') },
|
||||
...Array.from(new Set(rows.map((row) => row.model))).map((model) => ({
|
||||
value: model,
|
||||
label: model
|
||||
}))
|
||||
label: model,
|
||||
})),
|
||||
],
|
||||
[rows, t]
|
||||
);
|
||||
@@ -184,8 +201,8 @@ export function RequestEventsDetailsCard({
|
||||
{ value: ALL_FILTER, label: t('usage_stats.filter_all') },
|
||||
...Array.from(new Set(rows.map((row) => row.source))).map((source) => ({
|
||||
value: source,
|
||||
label: source
|
||||
}))
|
||||
label: source,
|
||||
})),
|
||||
],
|
||||
[rows, t]
|
||||
);
|
||||
@@ -195,8 +212,8 @@ export function RequestEventsDetailsCard({
|
||||
{ value: ALL_FILTER, label: t('usage_stats.filter_all') },
|
||||
...Array.from(new Set(rows.map((row) => row.authIndex))).map((authIndex) => ({
|
||||
value: authIndex,
|
||||
label: authIndex
|
||||
}))
|
||||
label: authIndex,
|
||||
})),
|
||||
],
|
||||
[rows, t]
|
||||
);
|
||||
@@ -223,8 +240,10 @@ export function RequestEventsDetailsCard({
|
||||
const filteredRows = useMemo(
|
||||
() =>
|
||||
rows.filter((row) => {
|
||||
const modelMatched = effectiveModelFilter === ALL_FILTER || row.model === effectiveModelFilter;
|
||||
const sourceMatched = effectiveSourceFilter === ALL_FILTER || row.source === effectiveSourceFilter;
|
||||
const modelMatched =
|
||||
effectiveModelFilter === ALL_FILTER || row.model === effectiveModelFilter;
|
||||
const sourceMatched =
|
||||
effectiveSourceFilter === ALL_FILTER || row.source === effectiveSourceFilter;
|
||||
const authIndexMatched =
|
||||
effectiveAuthIndexFilter === ALL_FILTER || row.authIndex === effectiveAuthIndexFilter;
|
||||
return modelMatched && sourceMatched && authIndexMatched;
|
||||
@@ -232,10 +251,7 @@ export function RequestEventsDetailsCard({
|
||||
[effectiveAuthIndexFilter, effectiveModelFilter, effectiveSourceFilter, rows]
|
||||
);
|
||||
|
||||
const renderedRows = useMemo(
|
||||
() => filteredRows.slice(0, MAX_RENDERED_EVENTS),
|
||||
[filteredRows]
|
||||
);
|
||||
const renderedRows = useMemo(() => filteredRows.slice(0, MAX_RENDERED_EVENTS), [filteredRows]);
|
||||
|
||||
const hasActiveFilters =
|
||||
effectiveModelFilter !== ALL_FILTER ||
|
||||
@@ -258,11 +274,12 @@ export function RequestEventsDetailsCard({
|
||||
'source_raw',
|
||||
'auth_index',
|
||||
'result',
|
||||
...(hasLatencyData ? ['latency_ms'] : []),
|
||||
'input_tokens',
|
||||
'output_tokens',
|
||||
'reasoning_tokens',
|
||||
'cached_tokens',
|
||||
'total_tokens'
|
||||
'total_tokens',
|
||||
];
|
||||
|
||||
const csvRows = filteredRows.map((row) =>
|
||||
@@ -273,11 +290,12 @@ export function RequestEventsDetailsCard({
|
||||
row.sourceRaw,
|
||||
row.authIndex,
|
||||
row.failed ? 'failed' : 'success',
|
||||
...(hasLatencyData ? [row.latencyMs ?? ''] : []),
|
||||
row.inputTokens,
|
||||
row.outputTokens,
|
||||
row.reasoningTokens,
|
||||
row.cachedTokens,
|
||||
row.totalTokens
|
||||
row.totalTokens,
|
||||
]
|
||||
.map((value) => encodeCsv(value))
|
||||
.join(',')
|
||||
@@ -287,7 +305,7 @@ export function RequestEventsDetailsCard({
|
||||
const fileTime = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
downloadBlob({
|
||||
filename: `usage-events-${fileTime}.csv`,
|
||||
blob: new Blob([content], { type: 'text/csv;charset=utf-8' })
|
||||
blob: new Blob([content], { type: 'text/csv;charset=utf-8' }),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -301,20 +319,21 @@ export function RequestEventsDetailsCard({
|
||||
source_raw: row.sourceRaw,
|
||||
auth_index: row.authIndex,
|
||||
failed: row.failed,
|
||||
...(hasLatencyData && row.latencyMs !== null ? { latency_ms: row.latencyMs } : {}),
|
||||
tokens: {
|
||||
input_tokens: row.inputTokens,
|
||||
output_tokens: row.outputTokens,
|
||||
reasoning_tokens: row.reasoningTokens,
|
||||
cached_tokens: row.cachedTokens,
|
||||
total_tokens: row.totalTokens
|
||||
}
|
||||
total_tokens: row.totalTokens,
|
||||
},
|
||||
}));
|
||||
|
||||
const content = JSON.stringify(payload, null, 2);
|
||||
const fileTime = new Date().toISOString().replace(/[:.]/g, '-');
|
||||
downloadBlob({
|
||||
filename: `usage-events-${fileTime}.json`,
|
||||
blob: new Blob([content], { type: 'application/json;charset=utf-8' })
|
||||
blob: new Blob([content], { type: 'application/json;charset=utf-8' }),
|
||||
});
|
||||
};
|
||||
|
||||
@@ -408,11 +427,12 @@ export function RequestEventsDetailsCard({
|
||||
<>
|
||||
<div className={styles.requestEventsMeta}>
|
||||
<span>{t('usage_stats.request_events_count', { count: filteredRows.length })}</span>
|
||||
{hasLatencyData && <span className={styles.requestEventsLimitHint}>{latencyHint}</span>}
|
||||
{filteredRows.length > MAX_RENDERED_EVENTS && (
|
||||
<span className={styles.requestEventsLimitHint}>
|
||||
{t('usage_stats.request_events_limit_hint', {
|
||||
shown: MAX_RENDERED_EVENTS,
|
||||
total: filteredRows.length
|
||||
total: filteredRows.length,
|
||||
})}
|
||||
</span>
|
||||
)}
|
||||
@@ -427,6 +447,7 @@ export function RequestEventsDetailsCard({
|
||||
<th>{t('usage_stats.request_events_source')}</th>
|
||||
<th>{t('usage_stats.request_events_auth_index')}</th>
|
||||
<th>{t('usage_stats.request_events_result')}</th>
|
||||
{hasLatencyData && <th title={latencyHint}>{t('usage_stats.time')}</th>}
|
||||
<th>{t('usage_stats.input_tokens')}</th>
|
||||
<th>{t('usage_stats.output_tokens')}</th>
|
||||
<th>{t('usage_stats.reasoning_tokens')}</th>
|
||||
@@ -452,11 +473,18 @@ export function RequestEventsDetailsCard({
|
||||
</td>
|
||||
<td>
|
||||
<span
|
||||
className={row.failed ? styles.requestEventsResultFailed : styles.requestEventsResultSuccess}
|
||||
className={
|
||||
row.failed
|
||||
? styles.requestEventsResultFailed
|
||||
: styles.requestEventsResultSuccess
|
||||
}
|
||||
>
|
||||
{row.failed ? t('stats.failure') : t('stats.success')}
|
||||
</span>
|
||||
</td>
|
||||
{hasLatencyData && (
|
||||
<td className={styles.durationCell}>{formatDurationMs(row.latencyMs)}</td>
|
||||
)}
|
||||
<td>{row.inputTokens.toLocaleString()}</td>
|
||||
<td>{row.outputTokens.toLocaleString()}</td>
|
||||
<td>{row.reasoningTokens.toLocaleString()}</td>
|
||||
|
||||
@@ -83,7 +83,11 @@ export function ServiceHealthCard({ usage, loading }: ServiceHealthCardProps) {
|
||||
}, [activeTooltip]);
|
||||
|
||||
const buildTooltipState = useCallback(
|
||||
(idx: number, anchorEl: HTMLDivElement): ActiveTooltipState => {
|
||||
(idx: number, anchorEl: HTMLDivElement | null): ActiveTooltipState | null => {
|
||||
if (!anchorEl || !anchorEl.isConnected) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const rect = anchorEl.getBoundingClientRect();
|
||||
const centerX = rect.left + rect.width / 2;
|
||||
|
||||
@@ -161,9 +165,8 @@ export function ServiceHealthCard({ usage, loading }: ServiceHealthCardProps) {
|
||||
(e: React.PointerEvent<HTMLDivElement>, idx: number) => {
|
||||
if (e.pointerType === 'touch') {
|
||||
e.preventDefault();
|
||||
setActiveTooltip((prev) =>
|
||||
prev?.idx === idx ? null : buildTooltipState(idx, e.currentTarget)
|
||||
);
|
||||
const anchorEl = e.currentTarget;
|
||||
setActiveTooltip((prev) => (prev?.idx === idx ? null : buildTooltipState(idx, anchorEl)));
|
||||
}
|
||||
},
|
||||
[buildTooltipState]
|
||||
|
||||
@@ -1,15 +1,24 @@
|
||||
import { useMemo, type CSSProperties, type ReactNode } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Line } from 'react-chartjs-2';
|
||||
import { IconDiamond, IconDollarSign, IconSatellite, IconTimer, IconTrendingUp } from '@/components/ui/icons';
|
||||
import {
|
||||
IconDiamond,
|
||||
IconDollarSign,
|
||||
IconSatellite,
|
||||
IconTimer,
|
||||
IconTrendingUp,
|
||||
} from '@/components/ui/icons';
|
||||
import {
|
||||
LATENCY_SOURCE_FIELD,
|
||||
calculateLatencyStatsFromDetails,
|
||||
calculateCost,
|
||||
formatCompactNumber,
|
||||
formatDurationMs,
|
||||
formatPerMinuteValue,
|
||||
formatUsd,
|
||||
calculateCost,
|
||||
collectUsageDetails,
|
||||
extractTotalTokens,
|
||||
type ModelPrice
|
||||
type ModelPrice,
|
||||
} from '@/utils/usage';
|
||||
import { sparklineOptions } from '@/utils/usage/chartConfig';
|
||||
import type { UsagePayload } from './hooks/useUsageData';
|
||||
@@ -44,20 +53,31 @@ export interface StatCardsProps {
|
||||
|
||||
export function StatCards({ usage, loading, modelPrices, nowMs, sparklines }: StatCardsProps) {
|
||||
const { t } = useTranslation();
|
||||
const latencyHint = t('usage_stats.latency_unit_hint', {
|
||||
field: LATENCY_SOURCE_FIELD,
|
||||
unit: t('usage_stats.duration_unit_ms'),
|
||||
});
|
||||
|
||||
const hasPrices = Object.keys(modelPrices).length > 0;
|
||||
|
||||
const { tokenBreakdown, rateStats, totalCost } = useMemo(() => {
|
||||
const { tokenBreakdown, rateStats, totalCost, latencyStats } = useMemo(() => {
|
||||
const empty = {
|
||||
tokenBreakdown: { cachedTokens: 0, reasoningTokens: 0 },
|
||||
rateStats: { rpm: 0, tpm: 0, windowMinutes: 30, requestCount: 0, tokenCount: 0 },
|
||||
totalCost: 0
|
||||
totalCost: 0,
|
||||
latencyStats: {
|
||||
averageMs: null as number | null,
|
||||
totalMs: null as number | null,
|
||||
sampleCount: 0,
|
||||
},
|
||||
};
|
||||
|
||||
if (!usage) return empty;
|
||||
const details = collectUsageDetails(usage);
|
||||
if (!details.length) return empty;
|
||||
|
||||
const latencyStats = calculateLatencyStatsFromDetails(details);
|
||||
|
||||
let cachedTokens = 0;
|
||||
let reasoningTokens = 0;
|
||||
let totalCost = 0;
|
||||
@@ -80,7 +100,12 @@ export function StatCards({ usage, loading, modelPrices, nowMs, sparklines }: St
|
||||
}
|
||||
|
||||
const timestamp = detail.__timestampMs ?? 0;
|
||||
if (hasValidNow && Number.isFinite(timestamp) && timestamp >= windowStart && timestamp <= now) {
|
||||
if (
|
||||
hasValidNow &&
|
||||
Number.isFinite(timestamp) &&
|
||||
timestamp >= windowStart &&
|
||||
timestamp <= now
|
||||
) {
|
||||
requestCount += 1;
|
||||
tokenCount += extractTotalTokens(detail);
|
||||
}
|
||||
@@ -98,9 +123,10 @@ export function StatCards({ usage, loading, modelPrices, nowMs, sparklines }: St
|
||||
tpm: tokenCount / denominator,
|
||||
windowMinutes,
|
||||
requestCount,
|
||||
tokenCount
|
||||
tokenCount,
|
||||
},
|
||||
totalCost
|
||||
totalCost,
|
||||
latencyStats,
|
||||
};
|
||||
}, [hasPrices, modelPrices, nowMs, usage]);
|
||||
|
||||
@@ -123,9 +149,15 @@ export function StatCards({ usage, loading, modelPrices, nowMs, sparklines }: St
|
||||
<span className={styles.statMetaDot} style={{ backgroundColor: '#c65746' }} />
|
||||
{t('usage_stats.failed_requests')}: {loading ? '-' : (usage?.failure_count ?? 0)}
|
||||
</span>
|
||||
{latencyStats.sampleCount > 0 && (
|
||||
<span className={styles.statMetaItem} title={latencyHint}>
|
||||
{t('usage_stats.avg_time')}:{' '}
|
||||
{loading ? '-' : formatDurationMs(latencyStats.averageMs)}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
),
|
||||
trend: sparklines.requests
|
||||
trend: sparklines.requests,
|
||||
},
|
||||
{
|
||||
key: 'tokens',
|
||||
@@ -138,14 +170,16 @@ export function StatCards({ usage, loading, modelPrices, nowMs, sparklines }: St
|
||||
meta: (
|
||||
<>
|
||||
<span className={styles.statMetaItem}>
|
||||
{t('usage_stats.cached_tokens')}: {loading ? '-' : formatCompactNumber(tokenBreakdown.cachedTokens)}
|
||||
{t('usage_stats.cached_tokens')}:{' '}
|
||||
{loading ? '-' : formatCompactNumber(tokenBreakdown.cachedTokens)}
|
||||
</span>
|
||||
<span className={styles.statMetaItem}>
|
||||
{t('usage_stats.reasoning_tokens')}: {loading ? '-' : formatCompactNumber(tokenBreakdown.reasoningTokens)}
|
||||
{t('usage_stats.reasoning_tokens')}:{' '}
|
||||
{loading ? '-' : formatCompactNumber(tokenBreakdown.reasoningTokens)}
|
||||
</span>
|
||||
</>
|
||||
),
|
||||
trend: sparklines.tokens
|
||||
trend: sparklines.tokens,
|
||||
},
|
||||
{
|
||||
key: 'rpm',
|
||||
@@ -157,10 +191,11 @@ export function StatCards({ usage, loading, modelPrices, nowMs, sparklines }: St
|
||||
value: loading ? '-' : formatPerMinuteValue(rateStats.rpm),
|
||||
meta: (
|
||||
<span className={styles.statMetaItem}>
|
||||
{t('usage_stats.total_requests')}: {loading ? '-' : rateStats.requestCount.toLocaleString()}
|
||||
{t('usage_stats.total_requests')}:{' '}
|
||||
{loading ? '-' : rateStats.requestCount.toLocaleString()}
|
||||
</span>
|
||||
),
|
||||
trend: sparklines.rpm
|
||||
trend: sparklines.rpm,
|
||||
},
|
||||
{
|
||||
key: 'tpm',
|
||||
@@ -172,10 +207,11 @@ export function StatCards({ usage, loading, modelPrices, nowMs, sparklines }: St
|
||||
value: loading ? '-' : formatPerMinuteValue(rateStats.tpm),
|
||||
meta: (
|
||||
<span className={styles.statMetaItem}>
|
||||
{t('usage_stats.total_tokens')}: {loading ? '-' : formatCompactNumber(rateStats.tokenCount)}
|
||||
{t('usage_stats.total_tokens')}:{' '}
|
||||
{loading ? '-' : formatCompactNumber(rateStats.tokenCount)}
|
||||
</span>
|
||||
),
|
||||
trend: sparklines.tpm
|
||||
trend: sparklines.tpm,
|
||||
},
|
||||
{
|
||||
key: 'cost',
|
||||
@@ -188,7 +224,8 @@ export function StatCards({ usage, loading, modelPrices, nowMs, sparklines }: St
|
||||
meta: (
|
||||
<>
|
||||
<span className={styles.statMetaItem}>
|
||||
{t('usage_stats.total_tokens')}: {loading ? '-' : formatCompactNumber(usage?.total_tokens ?? 0)}
|
||||
{t('usage_stats.total_tokens')}:{' '}
|
||||
{loading ? '-' : formatCompactNumber(usage?.total_tokens ?? 0)}
|
||||
</span>
|
||||
{!hasPrices && (
|
||||
<span className={`${styles.statMetaItem} ${styles.statSubtle}`}>
|
||||
@@ -197,8 +234,8 @@ export function StatCards({ usage, loading, modelPrices, nowMs, sparklines }: St
|
||||
)}
|
||||
</>
|
||||
),
|
||||
trend: hasPrices ? sparklines.cost : null
|
||||
}
|
||||
trend: hasPrices ? sparklines.cost : null,
|
||||
},
|
||||
];
|
||||
|
||||
return (
|
||||
@@ -211,7 +248,7 @@ export function StatCards({ usage, loading, modelPrices, nowMs, sparklines }: St
|
||||
{
|
||||
'--accent': card.accent,
|
||||
'--accent-soft': card.accentSoft,
|
||||
'--accent-border': card.accentBorder
|
||||
'--accent-border': card.accentBorder,
|
||||
} as CSSProperties
|
||||
}
|
||||
>
|
||||
@@ -225,7 +262,11 @@ export function StatCards({ usage, loading, modelPrices, nowMs, sparklines }: St
|
||||
{card.meta && <div className={styles.statMetaRow}>{card.meta}</div>}
|
||||
<div className={styles.statTrend}>
|
||||
{card.trend ? (
|
||||
<Line className={styles.sparkline} data={card.trend.data} options={sparklineOptions} />
|
||||
<Line
|
||||
className={styles.sparkline}
|
||||
data={card.trend.data}
|
||||
options={sparklineOptions}
|
||||
/>
|
||||
) : (
|
||||
<div className={styles.statTrendPlaceholder}></div>
|
||||
)}
|
||||
|
||||
@@ -65,7 +65,13 @@ export function AuthFilesPrefixProxyEditorModal(props: AuthFilesPrefixProxyEdito
|
||||
<Button
|
||||
onClick={onSave}
|
||||
loading={editor?.saving === true}
|
||||
disabled={disableControls || editor?.saving === true || !dirty || !editor?.json}
|
||||
disabled={
|
||||
disableControls ||
|
||||
editor?.saving === true ||
|
||||
!dirty ||
|
||||
!editor?.json ||
|
||||
Boolean(editor?.headersTouched && editor.headersError)
|
||||
}
|
||||
>
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
@@ -138,6 +144,20 @@ export function AuthFilesPrefixProxyEditorModal(props: AuthFilesPrefixProxyEdito
|
||||
/>
|
||||
<div className="hint">{t('auth_files.excluded_models_hint')}</div>
|
||||
</div>
|
||||
<div className="form-group">
|
||||
<label>{t('auth_files.headers_label')}</label>
|
||||
<textarea
|
||||
className={`input ${editor.headersError ? styles.prefixProxyTextareaInvalid : ''}`}
|
||||
value={editor.headersText}
|
||||
placeholder={t('auth_files.headers_placeholder')}
|
||||
rows={4}
|
||||
aria-invalid={Boolean(editor.headersError)}
|
||||
disabled={disableControls || editor.saving || !editor.json}
|
||||
onChange={(e) => onChange('headersText', e.target.value)}
|
||||
/>
|
||||
{editor.headersError && <div className="error-box">{editor.headersError}</div>}
|
||||
<div className="hint">{t('auth_files.headers_hint')}</div>
|
||||
</div>
|
||||
<Input
|
||||
label={t('auth_files.disable_cooling_label')}
|
||||
value={editor.disableCooling}
|
||||
|
||||
@@ -14,6 +14,12 @@ import {
|
||||
readCodexAuthFileWebsockets,
|
||||
} from '@/features/authFiles/constants';
|
||||
|
||||
type AuthFileHeaders = Record<string, string>;
|
||||
type AuthFileHeadersErrorKey =
|
||||
| 'auth_files.headers_invalid_json'
|
||||
| 'auth_files.headers_invalid_object'
|
||||
| 'auth_files.headers_invalid_value';
|
||||
|
||||
export type PrefixProxyEditorField =
|
||||
| 'prefix'
|
||||
| 'proxyUrl'
|
||||
@@ -21,7 +27,8 @@ export type PrefixProxyEditorField =
|
||||
| 'excludedModelsText'
|
||||
| 'disableCooling'
|
||||
| 'websockets'
|
||||
| 'note';
|
||||
| 'note'
|
||||
| 'headersText';
|
||||
|
||||
export type PrefixProxyEditorFieldValue = string | boolean;
|
||||
|
||||
@@ -43,6 +50,9 @@ export type PrefixProxyEditorState = {
|
||||
websockets: boolean;
|
||||
note: string;
|
||||
noteTouched: boolean;
|
||||
headersText: string;
|
||||
headersTouched: boolean;
|
||||
headersError: string | null;
|
||||
};
|
||||
|
||||
export type UseAuthFilesPrefixProxyEditorOptions = {
|
||||
@@ -64,7 +74,45 @@ export type UseAuthFilesPrefixProxyEditorResult = {
|
||||
handlePrefixProxySave: () => Promise<void>;
|
||||
};
|
||||
|
||||
const buildPrefixProxyUpdatedText = (editor: PrefixProxyEditorState | null): string => {
|
||||
const isRecordObject = (value: unknown): value is Record<string, unknown> =>
|
||||
Boolean(value) && typeof value === 'object' && !Array.isArray(value);
|
||||
|
||||
const validateHeadersValue = (value: unknown): AuthFileHeadersErrorKey | null => {
|
||||
if (!isRecordObject(value)) {
|
||||
return 'auth_files.headers_invalid_object';
|
||||
}
|
||||
return Object.values(value).every((item) => typeof item === 'string')
|
||||
? null
|
||||
: 'auth_files.headers_invalid_value';
|
||||
};
|
||||
|
||||
const parseHeadersText = (
|
||||
text: string
|
||||
): { value: AuthFileHeaders | null; errorKey: AuthFileHeadersErrorKey | null } => {
|
||||
const trimmed = text.trim();
|
||||
if (!trimmed) {
|
||||
return { value: null, errorKey: null };
|
||||
}
|
||||
|
||||
let parsed: unknown;
|
||||
try {
|
||||
parsed = JSON.parse(text) as unknown;
|
||||
} catch {
|
||||
return { value: null, errorKey: 'auth_files.headers_invalid_json' };
|
||||
}
|
||||
|
||||
const errorKey = validateHeadersValue(parsed);
|
||||
if (errorKey) {
|
||||
return { value: null, errorKey };
|
||||
}
|
||||
|
||||
return { value: parsed as AuthFileHeaders, errorKey: null };
|
||||
};
|
||||
|
||||
const buildPrefixProxyUpdatedText = (
|
||||
editor: PrefixProxyEditorState | null,
|
||||
resolveHeadersError: (key: AuthFileHeadersErrorKey) => string
|
||||
): string => {
|
||||
if (!editor?.json) return editor?.rawText ?? '';
|
||||
const next: Record<string, unknown> = { ...editor.json };
|
||||
if ('prefix' in next || editor.prefix.trim()) {
|
||||
@@ -104,6 +152,18 @@ const buildPrefixProxyUpdatedText = (editor: PrefixProxyEditorState | null): str
|
||||
}
|
||||
}
|
||||
|
||||
if (editor.headersTouched) {
|
||||
const { value: parsedHeaders, errorKey } = parseHeadersText(editor.headersText);
|
||||
if (errorKey) {
|
||||
throw new Error(resolveHeadersError(errorKey));
|
||||
}
|
||||
if (parsedHeaders) {
|
||||
next.headers = parsedHeaders;
|
||||
} else {
|
||||
delete next.headers;
|
||||
}
|
||||
}
|
||||
|
||||
return JSON.stringify(
|
||||
editor.isCodexFile ? applyCodexAuthFileWebsockets(next, editor.websockets) : next
|
||||
);
|
||||
@@ -118,11 +178,18 @@ export function useAuthFilesPrefixProxyEditor(
|
||||
|
||||
const [prefixProxyEditor, setPrefixProxyEditor] = useState<PrefixProxyEditorState | null>(null);
|
||||
|
||||
const prefixProxyUpdatedText = buildPrefixProxyUpdatedText(prefixProxyEditor);
|
||||
const hasBlockingValidationError = Boolean(
|
||||
prefixProxyEditor?.headersTouched && prefixProxyEditor.headersError
|
||||
);
|
||||
const prefixProxyUpdatedText =
|
||||
prefixProxyEditor?.json && !hasBlockingValidationError
|
||||
? buildPrefixProxyUpdatedText(prefixProxyEditor, (key) => t(key))
|
||||
: '';
|
||||
|
||||
const prefixProxyDirty =
|
||||
Boolean(prefixProxyEditor?.json) &&
|
||||
Boolean(prefixProxyEditor?.originalText) &&
|
||||
prefixProxyUpdatedText !== prefixProxyEditor?.originalText;
|
||||
(prefixProxyUpdatedText === '' || prefixProxyUpdatedText !== prefixProxyEditor?.originalText);
|
||||
|
||||
const closePrefixProxyEditor = () => {
|
||||
setPrefixProxyEditor(null);
|
||||
@@ -162,6 +229,9 @@ export function useAuthFilesPrefixProxyEditor(
|
||||
websockets: false,
|
||||
note: '',
|
||||
noteTouched: false,
|
||||
headersText: '',
|
||||
headersTouched: false,
|
||||
headersError: null,
|
||||
});
|
||||
|
||||
try {
|
||||
@@ -213,6 +283,14 @@ export function useAuthFilesPrefixProxyEditor(
|
||||
const disableCoolingValue = parseDisableCoolingValue(json.disable_cooling);
|
||||
const websocketsValue = readCodexAuthFileWebsockets(json);
|
||||
const note = typeof json.note === 'string' ? json.note : '';
|
||||
const headers = json.headers;
|
||||
let headersText = '';
|
||||
let headersError: string | null = null;
|
||||
if (headers !== undefined) {
|
||||
headersText = JSON.stringify(headers, null, 2);
|
||||
const { errorKey } = parseHeadersText(headersText);
|
||||
headersError = errorKey ? t(errorKey) : null;
|
||||
}
|
||||
|
||||
setPrefixProxyEditor((prev) => {
|
||||
if (!prev || prev.fileName !== name) return prev;
|
||||
@@ -231,6 +309,9 @@ export function useAuthFilesPrefixProxyEditor(
|
||||
websockets: websocketsValue,
|
||||
note,
|
||||
noteTouched: false,
|
||||
headersText,
|
||||
headersTouched: false,
|
||||
headersError,
|
||||
error: null,
|
||||
};
|
||||
});
|
||||
@@ -256,6 +337,16 @@ export function useAuthFilesPrefixProxyEditor(
|
||||
if (field === 'excludedModelsText') return { ...prev, excludedModelsText: String(value) };
|
||||
if (field === 'disableCooling') return { ...prev, disableCooling: String(value) };
|
||||
if (field === 'note') return { ...prev, note: String(value), noteTouched: true };
|
||||
if (field === 'headersText') {
|
||||
const headersText = String(value);
|
||||
const { errorKey } = parseHeadersText(headersText);
|
||||
return {
|
||||
...prev,
|
||||
headersText,
|
||||
headersTouched: true,
|
||||
headersError: errorKey ? t(errorKey) : null,
|
||||
};
|
||||
}
|
||||
return { ...prev, websockets: Boolean(value) };
|
||||
});
|
||||
};
|
||||
@@ -265,7 +356,15 @@ export function useAuthFilesPrefixProxyEditor(
|
||||
if (!prefixProxyDirty) return;
|
||||
|
||||
const name = prefixProxyEditor.fileName;
|
||||
const payload = prefixProxyUpdatedText;
|
||||
let payload = '';
|
||||
try {
|
||||
payload = buildPrefixProxyUpdatedText(prefixProxyEditor, (key) => t(key));
|
||||
} catch (err: unknown) {
|
||||
const errorMessage = err instanceof Error ? err.message : 'Invalid format';
|
||||
showNotification(errorMessage, 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const fileSize = new Blob([payload]).size;
|
||||
if (fileSize > MAX_AUTH_FILE_SIZE) {
|
||||
showNotification(
|
||||
|
||||
@@ -8,17 +8,32 @@ export function useAuthFilesStatusBarCache(files: AuthFileItem[], usageDetails:
|
||||
return useMemo(() => {
|
||||
const cache = new Map<string, AuthFileStatusBarData>();
|
||||
|
||||
const usageDetailsByAuthIndex = new Map<string, UsageDetail[]>();
|
||||
usageDetails.forEach((detail) => {
|
||||
const authIndexKey = normalizeAuthIndex(detail.auth_index);
|
||||
if (!authIndexKey) return;
|
||||
|
||||
const list = usageDetailsByAuthIndex.get(authIndexKey);
|
||||
if (list) {
|
||||
list.push(detail);
|
||||
} else {
|
||||
usageDetailsByAuthIndex.set(authIndexKey, [detail]);
|
||||
}
|
||||
});
|
||||
|
||||
const uniqueAuthIndexKeys = new Set<string>();
|
||||
files.forEach((file) => {
|
||||
const rawAuthIndex = file['auth_index'] ?? file.authIndex;
|
||||
const authIndexKey = normalizeAuthIndex(rawAuthIndex);
|
||||
if (!authIndexKey) return;
|
||||
uniqueAuthIndexKeys.add(authIndexKey);
|
||||
});
|
||||
|
||||
if (authIndexKey) {
|
||||
const filteredDetails = usageDetails.filter((detail) => {
|
||||
const detailAuthIndex = normalizeAuthIndex(detail.auth_index);
|
||||
return detailAuthIndex !== null && detailAuthIndex === authIndexKey;
|
||||
});
|
||||
cache.set(authIndexKey, calculateStatusBarData(filteredDetails));
|
||||
}
|
||||
uniqueAuthIndexKeys.forEach((authIndexKey) => {
|
||||
cache.set(
|
||||
authIndexKey,
|
||||
calculateStatusBarData(usageDetailsByAuthIndex.get(authIndexKey) ?? [])
|
||||
);
|
||||
});
|
||||
|
||||
return cache;
|
||||
|
||||
@@ -7,7 +7,6 @@ export type AuthFilesUiState = {
|
||||
problemOnly?: boolean;
|
||||
compactMode?: boolean;
|
||||
search?: string;
|
||||
regexSearchMode?: boolean;
|
||||
page?: number;
|
||||
pageSize?: number;
|
||||
regularPageSize?: number;
|
||||
@@ -22,13 +21,23 @@ const AUTH_FILES_SORT_MODE_SET = new Set<AuthFilesSortMode>(AUTH_FILES_SORT_MODE
|
||||
export const isAuthFilesSortMode = (value: unknown): value is AuthFilesSortMode =>
|
||||
typeof value === 'string' && AUTH_FILES_SORT_MODE_SET.has(value as AuthFilesSortMode);
|
||||
|
||||
const readAuthFilesUiStateFromStorage = (
|
||||
storage: Pick<Storage, 'getItem'> | null | undefined
|
||||
): AuthFilesUiState | null => {
|
||||
if (!storage) return null;
|
||||
const raw = storage.getItem(AUTH_FILES_UI_STATE_KEY);
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw) as AuthFilesUiState;
|
||||
return parsed && typeof parsed === 'object' ? parsed : null;
|
||||
};
|
||||
|
||||
export const readAuthFilesUiState = (): AuthFilesUiState | null => {
|
||||
if (typeof window === 'undefined') return null;
|
||||
try {
|
||||
const raw = window.sessionStorage.getItem(AUTH_FILES_UI_STATE_KEY);
|
||||
if (!raw) return null;
|
||||
const parsed = JSON.parse(raw) as AuthFilesUiState;
|
||||
return parsed && typeof parsed === 'object' ? parsed : null;
|
||||
return (
|
||||
readAuthFilesUiStateFromStorage(window.localStorage) ??
|
||||
readAuthFilesUiStateFromStorage(window.sessionStorage)
|
||||
);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
@@ -37,7 +46,12 @@ export const readAuthFilesUiState = (): AuthFilesUiState | null => {
|
||||
export const writeAuthFilesUiState = (state: AuthFilesUiState) => {
|
||||
if (typeof window === 'undefined') return;
|
||||
try {
|
||||
window.sessionStorage.setItem(AUTH_FILES_UI_STATE_KEY, JSON.stringify(state));
|
||||
window.localStorage.setItem(AUTH_FILES_UI_STATE_KEY, JSON.stringify(state));
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
try {
|
||||
window.sessionStorage.removeItem(AUTH_FILES_UI_STATE_KEY);
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
export type HeaderRefreshHandler = () => void | Promise<void>;
|
||||
|
||||
@@ -9,9 +9,19 @@ export const triggerHeaderRefresh = async () => {
|
||||
await activeHeaderRefreshHandler();
|
||||
};
|
||||
|
||||
export const useHeaderRefresh = (handler?: HeaderRefreshHandler | null) => {
|
||||
export const useHeaderRefresh = (handler?: HeaderRefreshHandler | null, enabled = true) => {
|
||||
const lastHandlerRef = useRef<HeaderRefreshHandler | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!handler) return;
|
||||
const previousHandler = lastHandlerRef.current;
|
||||
lastHandlerRef.current = handler ?? null;
|
||||
|
||||
if (!enabled || !handler) {
|
||||
if (previousHandler && activeHeaderRefreshHandler === previousHandler) {
|
||||
activeHeaderRefreshHandler = null;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
activeHeaderRefreshHandler = handler;
|
||||
|
||||
@@ -20,5 +30,5 @@ export const useHeaderRefresh = (handler?: HeaderRefreshHandler | null) => {
|
||||
activeHeaderRefreshHandler = null;
|
||||
}
|
||||
};
|
||||
}, [handler]);
|
||||
}, [enabled, handler]);
|
||||
};
|
||||
|
||||
+357
-42
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { useCallback, useMemo, useReducer } from 'react';
|
||||
import { isMap, parse as parseYaml, parseDocument } from 'yaml';
|
||||
import type {
|
||||
PayloadFilterRule,
|
||||
@@ -189,7 +189,9 @@ export function getPayloadParamValidationError(
|
||||
}
|
||||
|
||||
function hasPayloadParamValidationErrors(rules: PayloadRule[]): boolean {
|
||||
return rules.some((rule) => rule.params.some((param) => Boolean(getPayloadParamValidationError(param))));
|
||||
return rules.some((rule) =>
|
||||
rule.params.some((param) => Boolean(getPayloadParamValidationError(param)))
|
||||
);
|
||||
}
|
||||
|
||||
function deepClone<T>(value: T): T {
|
||||
@@ -197,6 +199,72 @@ function deepClone<T>(value: T): T {
|
||||
return JSON.parse(JSON.stringify(value)) as T;
|
||||
}
|
||||
|
||||
function arePayloadModelEntriesEqual(
|
||||
left: PayloadRule['models'],
|
||||
right: PayloadRule['models']
|
||||
): boolean {
|
||||
if (left === right) return true;
|
||||
if (left.length !== right.length) return false;
|
||||
for (let i = 0; i < left.length; i += 1) {
|
||||
const a = left[i];
|
||||
const b = right[i];
|
||||
if (!a || !b) return false;
|
||||
if (a.id !== b.id || a.name !== b.name || a.protocol !== b.protocol) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function arePayloadParamEntriesEqual(
|
||||
left: PayloadRule['params'],
|
||||
right: PayloadRule['params']
|
||||
): boolean {
|
||||
if (left === right) return true;
|
||||
if (left.length !== right.length) return false;
|
||||
for (let i = 0; i < left.length; i += 1) {
|
||||
const a = left[i];
|
||||
const b = right[i];
|
||||
if (!a || !b) return false;
|
||||
if (a.id !== b.id || a.path !== b.path || a.valueType !== b.valueType || a.value !== b.value) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function arePayloadRulesEqual(left: PayloadRule[], right: PayloadRule[]): boolean {
|
||||
if (left === right) return true;
|
||||
if (left.length !== right.length) return false;
|
||||
for (let i = 0; i < left.length; i += 1) {
|
||||
const a = left[i];
|
||||
const b = right[i];
|
||||
if (!a || !b) return false;
|
||||
if (a.id !== b.id) return false;
|
||||
if (!arePayloadModelEntriesEqual(a.models, b.models)) return false;
|
||||
if (!arePayloadParamEntriesEqual(a.params, b.params)) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function arePayloadFilterRulesEqual(
|
||||
left: PayloadFilterRule[],
|
||||
right: PayloadFilterRule[]
|
||||
): boolean {
|
||||
if (left === right) return true;
|
||||
if (left.length !== right.length) return false;
|
||||
for (let i = 0; i < left.length; i += 1) {
|
||||
const a = left[i];
|
||||
const b = right[i];
|
||||
if (!a || !b) return false;
|
||||
if (a.id !== b.id) return false;
|
||||
if (!arePayloadModelEntriesEqual(a.models, b.models)) return false;
|
||||
if (a.params.length !== b.params.length) return false;
|
||||
for (let j = 0; j < a.params.length; j += 1) {
|
||||
if (a.params[j] !== b.params[j]) return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
function parsePayloadParamValue(raw: unknown): { valueType: PayloadParamValueType; value: string } {
|
||||
if (typeof raw === 'number') {
|
||||
return { valueType: 'number', value: String(raw) };
|
||||
@@ -426,15 +494,272 @@ function serializeRawPayloadRulesForYaml(rules: PayloadRule[]): Array<Record<str
|
||||
.filter((rule) => rule.models.length > 0);
|
||||
}
|
||||
|
||||
export function useVisualConfig() {
|
||||
const [visualValues, setVisualValuesState] = useState<VisualConfigValues>({
|
||||
...DEFAULT_VISUAL_VALUES,
|
||||
});
|
||||
type VisualConfigState = {
|
||||
visualValues: VisualConfigValues;
|
||||
baselineValues: VisualConfigValues;
|
||||
dirtyFields: Set<string>;
|
||||
visualParseError: string | null;
|
||||
};
|
||||
|
||||
const [baselineValues, setBaselineValues] = useState<VisualConfigValues>({
|
||||
...DEFAULT_VISUAL_VALUES,
|
||||
});
|
||||
const [visualParseError, setVisualParseError] = useState<string | null>(null);
|
||||
type VisualConfigAction =
|
||||
| {
|
||||
type: 'load_success';
|
||||
values: VisualConfigValues;
|
||||
}
|
||||
| {
|
||||
type: 'load_error';
|
||||
error: string;
|
||||
}
|
||||
| {
|
||||
type: 'set_values';
|
||||
values: Partial<VisualConfigValues>;
|
||||
};
|
||||
|
||||
function createInitialVisualConfigState(): VisualConfigState {
|
||||
const initialValues = deepClone(DEFAULT_VISUAL_VALUES);
|
||||
return {
|
||||
visualValues: initialValues,
|
||||
baselineValues: deepClone(initialValues),
|
||||
dirtyFields: new Set(),
|
||||
visualParseError: null,
|
||||
};
|
||||
}
|
||||
|
||||
function mergeVisualConfigValues(
|
||||
currentValues: VisualConfigValues,
|
||||
patch: Partial<VisualConfigValues>
|
||||
): VisualConfigValues {
|
||||
const nextValues: VisualConfigValues = { ...currentValues, ...patch } as VisualConfigValues;
|
||||
if (patch.streaming) {
|
||||
nextValues.streaming = { ...currentValues.streaming, ...patch.streaming };
|
||||
}
|
||||
return nextValues;
|
||||
}
|
||||
|
||||
function getNextDirtyFields(
|
||||
currentDirtyFields: Set<string>,
|
||||
patch: Partial<VisualConfigValues>,
|
||||
nextValues: VisualConfigValues,
|
||||
baselineValues: VisualConfigValues
|
||||
): Set<string> {
|
||||
const nextDirtyFields = new Set(currentDirtyFields);
|
||||
const updateDirty = (key: string, isEqual: boolean) => {
|
||||
if (isEqual) {
|
||||
nextDirtyFields.delete(key);
|
||||
} else {
|
||||
nextDirtyFields.add(key);
|
||||
}
|
||||
};
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'host')) {
|
||||
updateDirty('host', nextValues.host === baselineValues.host);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'port')) {
|
||||
updateDirty('port', nextValues.port === baselineValues.port);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'tlsEnable')) {
|
||||
updateDirty('tlsEnable', nextValues.tlsEnable === baselineValues.tlsEnable);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'tlsCert')) {
|
||||
updateDirty('tlsCert', nextValues.tlsCert === baselineValues.tlsCert);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'tlsKey')) {
|
||||
updateDirty('tlsKey', nextValues.tlsKey === baselineValues.tlsKey);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'rmAllowRemote')) {
|
||||
updateDirty('rmAllowRemote', nextValues.rmAllowRemote === baselineValues.rmAllowRemote);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'rmSecretKey')) {
|
||||
updateDirty('rmSecretKey', nextValues.rmSecretKey === baselineValues.rmSecretKey);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'rmDisableControlPanel')) {
|
||||
updateDirty(
|
||||
'rmDisableControlPanel',
|
||||
nextValues.rmDisableControlPanel === baselineValues.rmDisableControlPanel
|
||||
);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'rmPanelRepo')) {
|
||||
updateDirty('rmPanelRepo', nextValues.rmPanelRepo === baselineValues.rmPanelRepo);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'authDir')) {
|
||||
updateDirty('authDir', nextValues.authDir === baselineValues.authDir);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'apiKeysText')) {
|
||||
updateDirty('apiKeysText', nextValues.apiKeysText === baselineValues.apiKeysText);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'debug')) {
|
||||
updateDirty('debug', nextValues.debug === baselineValues.debug);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'commercialMode')) {
|
||||
updateDirty('commercialMode', nextValues.commercialMode === baselineValues.commercialMode);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'loggingToFile')) {
|
||||
updateDirty('loggingToFile', nextValues.loggingToFile === baselineValues.loggingToFile);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'logsMaxTotalSizeMb')) {
|
||||
updateDirty(
|
||||
'logsMaxTotalSizeMb',
|
||||
nextValues.logsMaxTotalSizeMb === baselineValues.logsMaxTotalSizeMb
|
||||
);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'usageStatisticsEnabled')) {
|
||||
updateDirty(
|
||||
'usageStatisticsEnabled',
|
||||
nextValues.usageStatisticsEnabled === baselineValues.usageStatisticsEnabled
|
||||
);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'proxyUrl')) {
|
||||
updateDirty('proxyUrl', nextValues.proxyUrl === baselineValues.proxyUrl);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'forceModelPrefix')) {
|
||||
updateDirty(
|
||||
'forceModelPrefix',
|
||||
nextValues.forceModelPrefix === baselineValues.forceModelPrefix
|
||||
);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'requestRetry')) {
|
||||
updateDirty('requestRetry', nextValues.requestRetry === baselineValues.requestRetry);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'maxRetryCredentials')) {
|
||||
updateDirty(
|
||||
'maxRetryCredentials',
|
||||
nextValues.maxRetryCredentials === baselineValues.maxRetryCredentials
|
||||
);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'maxRetryInterval')) {
|
||||
updateDirty(
|
||||
'maxRetryInterval',
|
||||
nextValues.maxRetryInterval === baselineValues.maxRetryInterval
|
||||
);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'wsAuth')) {
|
||||
updateDirty('wsAuth', nextValues.wsAuth === baselineValues.wsAuth);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'quotaSwitchProject')) {
|
||||
updateDirty(
|
||||
'quotaSwitchProject',
|
||||
nextValues.quotaSwitchProject === baselineValues.quotaSwitchProject
|
||||
);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'quotaSwitchPreviewModel')) {
|
||||
updateDirty(
|
||||
'quotaSwitchPreviewModel',
|
||||
nextValues.quotaSwitchPreviewModel === baselineValues.quotaSwitchPreviewModel
|
||||
);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'quotaAntigravityCredits')) {
|
||||
updateDirty(
|
||||
'quotaAntigravityCredits',
|
||||
nextValues.quotaAntigravityCredits === baselineValues.quotaAntigravityCredits
|
||||
);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'routingStrategy')) {
|
||||
updateDirty('routingStrategy', nextValues.routingStrategy === baselineValues.routingStrategy);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'payloadDefaultRules')) {
|
||||
updateDirty(
|
||||
'payloadDefaultRules',
|
||||
arePayloadRulesEqual(nextValues.payloadDefaultRules, baselineValues.payloadDefaultRules)
|
||||
);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'payloadDefaultRawRules')) {
|
||||
updateDirty(
|
||||
'payloadDefaultRawRules',
|
||||
arePayloadRulesEqual(nextValues.payloadDefaultRawRules, baselineValues.payloadDefaultRawRules)
|
||||
);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'payloadOverrideRules')) {
|
||||
updateDirty(
|
||||
'payloadOverrideRules',
|
||||
arePayloadRulesEqual(nextValues.payloadOverrideRules, baselineValues.payloadOverrideRules)
|
||||
);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'payloadOverrideRawRules')) {
|
||||
updateDirty(
|
||||
'payloadOverrideRawRules',
|
||||
arePayloadRulesEqual(
|
||||
nextValues.payloadOverrideRawRules,
|
||||
baselineValues.payloadOverrideRawRules
|
||||
)
|
||||
);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(patch, 'payloadFilterRules')) {
|
||||
updateDirty(
|
||||
'payloadFilterRules',
|
||||
arePayloadFilterRulesEqual(nextValues.payloadFilterRules, baselineValues.payloadFilterRules)
|
||||
);
|
||||
}
|
||||
if (patch.streaming) {
|
||||
const streamingPatch = patch.streaming;
|
||||
if (Object.prototype.hasOwnProperty.call(streamingPatch, 'keepaliveSeconds')) {
|
||||
updateDirty(
|
||||
'streaming.keepaliveSeconds',
|
||||
nextValues.streaming.keepaliveSeconds === baselineValues.streaming.keepaliveSeconds
|
||||
);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(streamingPatch, 'bootstrapRetries')) {
|
||||
updateDirty(
|
||||
'streaming.bootstrapRetries',
|
||||
nextValues.streaming.bootstrapRetries === baselineValues.streaming.bootstrapRetries
|
||||
);
|
||||
}
|
||||
if (Object.prototype.hasOwnProperty.call(streamingPatch, 'nonstreamKeepaliveInterval')) {
|
||||
updateDirty(
|
||||
'streaming.nonstreamKeepaliveInterval',
|
||||
nextValues.streaming.nonstreamKeepaliveInterval ===
|
||||
baselineValues.streaming.nonstreamKeepaliveInterval
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return nextDirtyFields;
|
||||
}
|
||||
|
||||
function visualConfigReducer(
|
||||
state: VisualConfigState,
|
||||
action: VisualConfigAction
|
||||
): VisualConfigState {
|
||||
switch (action.type) {
|
||||
case 'load_success':
|
||||
return {
|
||||
visualValues: action.values,
|
||||
baselineValues: deepClone(action.values),
|
||||
dirtyFields: new Set(),
|
||||
visualParseError: null,
|
||||
};
|
||||
case 'load_error':
|
||||
return {
|
||||
...state,
|
||||
visualParseError: action.error,
|
||||
};
|
||||
case 'set_values': {
|
||||
const nextValues = mergeVisualConfigValues(state.visualValues, action.values);
|
||||
const nextDirtyFields = getNextDirtyFields(
|
||||
state.dirtyFields,
|
||||
action.values,
|
||||
nextValues,
|
||||
state.baselineValues
|
||||
);
|
||||
|
||||
return {
|
||||
...state,
|
||||
visualValues: nextValues,
|
||||
dirtyFields: nextDirtyFields,
|
||||
};
|
||||
}
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
export function useVisualConfig() {
|
||||
const [state, dispatch] = useReducer(
|
||||
visualConfigReducer,
|
||||
undefined,
|
||||
createInitialVisualConfigState
|
||||
);
|
||||
const { visualValues, visualParseError } = state;
|
||||
const visualDirty = state.dirtyFields.size > 0;
|
||||
const visualValidationErrors = useMemo(
|
||||
() => getVisualConfigValidationErrors(visualValues),
|
||||
[visualValues]
|
||||
@@ -453,10 +778,6 @@ export function useVisualConfig() {
|
||||
]
|
||||
);
|
||||
|
||||
const visualDirty = useMemo(() => {
|
||||
return JSON.stringify(visualValues) !== JSON.stringify(baselineValues);
|
||||
}, [baselineValues, visualValues]);
|
||||
|
||||
const loadVisualValuesFromYaml = useCallback((yamlContent: string) => {
|
||||
try {
|
||||
const document = parseDocument(yamlContent);
|
||||
@@ -483,14 +804,16 @@ export function useVisualConfig() {
|
||||
|
||||
rmAllowRemote: Boolean(remoteManagement?.['allow-remote']),
|
||||
rmSecretKey:
|
||||
typeof remoteManagement?.['secret-key'] === 'string' ? remoteManagement['secret-key'] : '',
|
||||
typeof remoteManagement?.['secret-key'] === 'string'
|
||||
? remoteManagement['secret-key']
|
||||
: '',
|
||||
rmDisableControlPanel: Boolean(remoteManagement?.['disable-control-panel']),
|
||||
rmPanelRepo:
|
||||
typeof remoteManagement?.['panel-github-repository'] === 'string'
|
||||
? remoteManagement['panel-github-repository']
|
||||
: typeof remoteManagement?.['panel-repo'] === 'string'
|
||||
? remoteManagement['panel-repo']
|
||||
: '',
|
||||
: '',
|
||||
|
||||
authDir: typeof parsed['auth-dir'] === 'string' ? parsed['auth-dir'] : '',
|
||||
apiKeysText: resolveApiKeysText(parsed),
|
||||
@@ -509,12 +832,10 @@ export function useVisualConfig() {
|
||||
wsAuth: Boolean(parsed['ws-auth']),
|
||||
|
||||
quotaSwitchProject: Boolean(quotaExceeded?.['switch-project'] ?? true),
|
||||
quotaSwitchPreviewModel: Boolean(
|
||||
quotaExceeded?.['switch-preview-model'] ?? true
|
||||
),
|
||||
quotaSwitchPreviewModel: Boolean(quotaExceeded?.['switch-preview-model'] ?? true),
|
||||
quotaAntigravityCredits: Boolean(quotaExceeded?.['antigravity-credits'] ?? true),
|
||||
|
||||
routingStrategy:
|
||||
routing?.strategy === 'fill-first' ? 'fill-first' : 'round-robin',
|
||||
routingStrategy: routing?.strategy === 'fill-first' ? 'fill-first' : 'round-robin',
|
||||
|
||||
payloadDefaultRules: parsePayloadRules(payload?.default),
|
||||
payloadDefaultRawRules: parseRawPayloadRules(payload?.['default-raw']),
|
||||
@@ -529,13 +850,11 @@ export function useVisualConfig() {
|
||||
},
|
||||
};
|
||||
|
||||
setVisualValuesState(newValues);
|
||||
setBaselineValues(deepClone(newValues));
|
||||
setVisualParseError(null);
|
||||
dispatch({ type: 'load_success', values: newValues });
|
||||
return { ok: true as const };
|
||||
} catch (error: unknown) {
|
||||
const message = error instanceof Error ? error.message : 'Invalid YAML';
|
||||
setVisualParseError(message);
|
||||
dispatch({ type: 'load_error', error: message });
|
||||
return { ok: false as const, error: message };
|
||||
}
|
||||
}, []);
|
||||
@@ -617,13 +936,15 @@ export function useVisualConfig() {
|
||||
if (
|
||||
docHas(doc, ['quota-exceeded']) ||
|
||||
!values.quotaSwitchProject ||
|
||||
!values.quotaSwitchPreviewModel
|
||||
!values.quotaSwitchPreviewModel ||
|
||||
!values.quotaAntigravityCredits
|
||||
) {
|
||||
ensureMapInDoc(doc, ['quota-exceeded']);
|
||||
doc.setIn(['quota-exceeded', 'switch-project'], values.quotaSwitchProject);
|
||||
doc.setIn(['quota-exceeded', 'switch-preview-model'], values.quotaSwitchPreviewModel);
|
||||
doc.setIn(
|
||||
['quota-exceeded', 'switch-preview-model'],
|
||||
values.quotaSwitchPreviewModel
|
||||
['quota-exceeded', 'antigravity-credits'],
|
||||
values.quotaAntigravityCredits
|
||||
);
|
||||
deleteIfMapEmpty(doc, ['quota-exceeded']);
|
||||
}
|
||||
@@ -635,9 +956,13 @@ export function useVisualConfig() {
|
||||
}
|
||||
|
||||
const keepaliveSeconds =
|
||||
typeof values.streaming?.keepaliveSeconds === 'string' ? values.streaming.keepaliveSeconds : '';
|
||||
typeof values.streaming?.keepaliveSeconds === 'string'
|
||||
? values.streaming.keepaliveSeconds
|
||||
: '';
|
||||
const bootstrapRetries =
|
||||
typeof values.streaming?.bootstrapRetries === 'string' ? values.streaming.bootstrapRetries : '';
|
||||
typeof values.streaming?.bootstrapRetries === 'string'
|
||||
? values.streaming.bootstrapRetries
|
||||
: '';
|
||||
const nonstreamKeepaliveInterval =
|
||||
typeof values.streaming?.nonstreamKeepaliveInterval === 'string'
|
||||
? values.streaming.nonstreamKeepaliveInterval
|
||||
@@ -652,11 +977,7 @@ export function useVisualConfig() {
|
||||
deleteIfMapEmpty(doc, ['streaming']);
|
||||
}
|
||||
|
||||
setIntFromStringInDoc(
|
||||
doc,
|
||||
['nonstream-keepalive-interval'],
|
||||
nonstreamKeepaliveInterval
|
||||
);
|
||||
setIntFromStringInDoc(doc, ['nonstream-keepalive-interval'], nonstreamKeepaliveInterval);
|
||||
|
||||
if (
|
||||
docHas(doc, ['payload']) ||
|
||||
@@ -719,13 +1040,7 @@ export function useVisualConfig() {
|
||||
);
|
||||
|
||||
const setVisualValues = useCallback((newValues: Partial<VisualConfigValues>) => {
|
||||
setVisualValuesState((prev) => {
|
||||
const next: VisualConfigValues = { ...prev, ...newValues } as VisualConfigValues;
|
||||
if (newValues.streaming) {
|
||||
next.streaming = { ...prev.streaming, ...newValues.streaming };
|
||||
}
|
||||
return next;
|
||||
});
|
||||
dispatch({ type: 'set_values', values: newValues });
|
||||
}, []);
|
||||
|
||||
return {
|
||||
|
||||
@@ -140,7 +140,17 @@
|
||||
"edit_settings": "Edit Settings",
|
||||
"routing_strategy": "Routing Strategy",
|
||||
"available_models": "Available Models",
|
||||
"available_models_desc": "Total models from all providers"
|
||||
"available_models_desc": "Total models from all providers",
|
||||
"welcome_back": "Welcome Back",
|
||||
"greeting_morning": "Good Morning",
|
||||
"greeting_afternoon": "Good Afternoon",
|
||||
"greeting_evening": "Good Evening",
|
||||
"greeting_night": "Good Night",
|
||||
"caring_morning": "A fresh start — let's make today count.",
|
||||
"caring_afternoon": "Steady progress — you're doing great.",
|
||||
"caring_evening": "Wrapping up nicely — almost there.",
|
||||
"caring_night": "Burning the midnight oil? Don't forget to rest.",
|
||||
"system_overview": "System Overview"
|
||||
},
|
||||
"basic_settings": {
|
||||
"title": "Basic Settings",
|
||||
@@ -497,15 +507,11 @@
|
||||
"pagination_next": "Next",
|
||||
"pagination_info": "Page {{current}} / {{total}} · {{count}} files",
|
||||
"search_label": "Search configs",
|
||||
"search_placeholder": "Filter by name, type, or provider",
|
||||
"search_regex_placeholder": "Match name, type, or provider with a regex",
|
||||
"search_regex_invalid": "Enter a valid regex pattern (max {{max}} characters)",
|
||||
"search_regex_unsafe": "This regex may freeze the page and has been blocked (avoid nested quantifiers, alternation in repeated groups, or backreferences)",
|
||||
"search_placeholder": "Filter by name, type, or provider. Use * as a wildcard",
|
||||
"problem_filter_label": "Problem Filter",
|
||||
"problem_filter_only": "Only show problematic credentials",
|
||||
"display_options_label": "Display options",
|
||||
"compact_mode_label": "Compact mode",
|
||||
"regex_search_mode_label": "Regex mode",
|
||||
"sort_label": "Sort",
|
||||
"sort_default": "Default",
|
||||
"sort_az": "A-Z Name",
|
||||
@@ -591,6 +597,12 @@
|
||||
"note_placeholder": "Enter a note, e.g.: John's account",
|
||||
"note_hint": "Optional. Used to describe the purpose or owner of this credential; leave empty to omit.",
|
||||
"note_display": "Note",
|
||||
"headers_label": "Custom Headers (headers)",
|
||||
"headers_placeholder": "{\n \"Header-Name\": \"value\"\n}",
|
||||
"headers_hint": "Enter custom HTTP headers as a JSON object, e.g., {\"X-My-Header\": \"value\"}",
|
||||
"headers_invalid_json": "Custom headers must be valid JSON.",
|
||||
"headers_invalid_object": "Custom headers must be a JSON object.",
|
||||
"headers_invalid_value": "Each custom header value must be a string.",
|
||||
"prefix_proxy_invalid_json": "This auth file is not a JSON object, so fields cannot be edited.",
|
||||
"prefix_proxy_saved_success": "Updated auth file \"{{name}}\" successfully",
|
||||
"quota_refresh_success": "Quota refreshed for \"{{name}}\"",
|
||||
@@ -658,7 +670,8 @@
|
||||
"plan_plus": "Plus",
|
||||
"plan_team": "Team",
|
||||
"plan_free": "Free",
|
||||
"plan_pro": "Pro"
|
||||
"plan_pro": "Pro 20x",
|
||||
"plan_prolite": "Pro 5x"
|
||||
},
|
||||
"gemini_cli_quota": {
|
||||
"title": "Gemini CLI Quota",
|
||||
@@ -1017,6 +1030,15 @@
|
||||
"request_events_source": "Source",
|
||||
"request_events_auth_index": "Auth Index",
|
||||
"request_events_result": "Result",
|
||||
"time": "Latency",
|
||||
"avg_time": "Avg Latency",
|
||||
"total_time": "Total Latency",
|
||||
"latency_unit_hint": "Durations use backend field {{field}} and are interpreted as {{unit}} before formatting.",
|
||||
"duration_unit_d": "d",
|
||||
"duration_unit_h": "h",
|
||||
"duration_unit_m": "m",
|
||||
"duration_unit_s": "s",
|
||||
"duration_unit_ms": "ms",
|
||||
"request_events_empty_title": "No request events",
|
||||
"request_events_empty_desc": "No request details are available for the selected time range.",
|
||||
"request_events_no_result_title": "No matching events",
|
||||
@@ -1248,7 +1270,9 @@
|
||||
"switch_project": "Switch Project",
|
||||
"switch_project_desc": "Automatically switch to another project when quota is exceeded",
|
||||
"switch_preview_model": "Switch to Preview Model",
|
||||
"switch_preview_model_desc": "Switch to preview model version when quota is exceeded"
|
||||
"switch_preview_model_desc": "Switch to preview model version when quota is exceeded",
|
||||
"antigravity_credits": "Antigravity Credits Retry",
|
||||
"antigravity_credits_desc": "Retry once with enabledCreditTypes=[\"GOOGLE_ONE_AI\"] when Antigravity returns quota_exhausted 429"
|
||||
},
|
||||
"streaming": {
|
||||
"title": "Streaming Configuration",
|
||||
@@ -1347,7 +1371,8 @@
|
||||
"description": "Monitor OAuth quota status for Antigravity, Codex, and Gemini CLI credentials.",
|
||||
"refresh_files": "Refresh auth files",
|
||||
"refresh_files_and_quota": "Refresh files & quota",
|
||||
"card_idle_hint": "Use the top \"Refresh files & quota\" button to fetch the latest quota data."
|
||||
"refresh_all_credentials": "Refresh all credentials",
|
||||
"card_idle_hint": "Use the top \"Refresh all credentials\" button to fetch the latest quota data."
|
||||
},
|
||||
"system_info": {
|
||||
"title": "Management Center Info",
|
||||
|
||||
@@ -140,7 +140,17 @@
|
||||
"edit_settings": "Изменить настройки",
|
||||
"routing_strategy": "Стратегия маршрутизации",
|
||||
"available_models": "Доступные модели",
|
||||
"available_models_desc": "Всего моделей от всех провайдеров"
|
||||
"available_models_desc": "Всего моделей от всех провайдеров",
|
||||
"welcome_back": "С возвращением",
|
||||
"greeting_morning": "Доброе утро",
|
||||
"greeting_afternoon": "Добрый день",
|
||||
"greeting_evening": "Добрый вечер",
|
||||
"greeting_night": "Доброй ночи",
|
||||
"caring_morning": "Новый день — начнём продуктивно.",
|
||||
"caring_afternoon": "Уверенный прогресс — отличная работа.",
|
||||
"caring_evening": "День подходит к концу — финальный рывок.",
|
||||
"caring_night": "Поздняя работа? Не забудьте отдохнуть.",
|
||||
"system_overview": "Обзор системы"
|
||||
},
|
||||
"basic_settings": {
|
||||
"title": "Основные настройки",
|
||||
@@ -497,15 +507,11 @@
|
||||
"pagination_next": "Следующая",
|
||||
"pagination_info": "Страница {{current}} / {{total}} · {{count}} файлов",
|
||||
"search_label": "Поиск конфигов",
|
||||
"search_placeholder": "Фильтр по имени, типу или провайдеру",
|
||||
"search_regex_placeholder": "Сопоставление имени, типа или провайдера по regex",
|
||||
"search_regex_invalid": "Введите корректный regex-шаблон (не более {{max}} символов)",
|
||||
"search_regex_unsafe": "Этот regex может вызвать зависание страницы и был заблокирован (избегайте вложенных квантификаторов, альтернативы в повторяющихся группах или обратных ссылок)",
|
||||
"search_placeholder": "Фильтр по имени, типу или провайдеру, поддерживается wildcard *",
|
||||
"problem_filter_label": "Фильтр проблем",
|
||||
"problem_filter_only": "Показывать только проблемные учётные данные",
|
||||
"display_options_label": "Параметры отображения",
|
||||
"compact_mode_label": "Компактный режим",
|
||||
"regex_search_mode_label": "Режим regex",
|
||||
"sort_label": "Сортировка",
|
||||
"sort_default": "По умолчанию",
|
||||
"sort_az": "A-Z Имя",
|
||||
@@ -661,7 +667,8 @@
|
||||
"plan_plus": "Plus",
|
||||
"plan_team": "Team",
|
||||
"plan_free": "Free",
|
||||
"plan_pro": "Pro"
|
||||
"plan_pro": "Pro 20x",
|
||||
"plan_prolite": "Pro 5x"
|
||||
},
|
||||
"gemini_cli_quota": {
|
||||
"title": "Квота Gemini CLI",
|
||||
@@ -1020,6 +1027,15 @@
|
||||
"request_events_source": "Источник",
|
||||
"request_events_auth_index": "Auth Index",
|
||||
"request_events_result": "Результат",
|
||||
"time": "Задержка",
|
||||
"avg_time": "Средняя задержка",
|
||||
"total_time": "Суммарная задержка",
|
||||
"latency_unit_hint": "Длительность берётся из поля бэкенда {{field}} и интерпретируется как {{unit}} перед форматированием.",
|
||||
"duration_unit_d": "д",
|
||||
"duration_unit_h": "ч",
|
||||
"duration_unit_m": "мин",
|
||||
"duration_unit_s": "с",
|
||||
"duration_unit_ms": "мс",
|
||||
"request_events_empty_title": "События запросов отсутствуют",
|
||||
"request_events_empty_desc": "Нет деталей запросов для выбранного диапазона времени.",
|
||||
"request_events_no_result_title": "Совпадений не найдено",
|
||||
@@ -1253,7 +1269,9 @@
|
||||
"switch_project": "Переключить проект",
|
||||
"switch_project_desc": "Автоматически переходить на другой проект при превышении квоты",
|
||||
"switch_preview_model": "Переключить на preview-модель",
|
||||
"switch_preview_model_desc": "Переключаться на preview-версию модели при превышении квоты"
|
||||
"switch_preview_model_desc": "Переключаться на preview-версию модели при превышении квоты",
|
||||
"antigravity_credits": "Повтор Antigravity Credits",
|
||||
"antigravity_credits_desc": "При ответе Antigravity quota_exhausted 429 повторять запрос один раз с enabledCreditTypes=[\"GOOGLE_ONE_AI\"]"
|
||||
},
|
||||
"streaming": {
|
||||
"title": "Настройки стриминга",
|
||||
@@ -1352,7 +1370,8 @@
|
||||
"description": "Следите за статусом квот OAuth для учётных данных Antigravity, Codex и Gemini CLI.",
|
||||
"refresh_files": "Обновить файлы авторизации",
|
||||
"refresh_files_and_quota": "Обновить файлы и квоты",
|
||||
"card_idle_hint": "Используйте кнопку «Обновить файлы и квоты» сверху, чтобы загрузить актуальные данные по квотам."
|
||||
"refresh_all_credentials": "Обновить все учётные данные",
|
||||
"card_idle_hint": "Используйте кнопку «Обновить все учётные данные» сверху, чтобы загрузить актуальные данные по квотам."
|
||||
},
|
||||
"system_info": {
|
||||
"title": "Информация о центре управления",
|
||||
|
||||
@@ -140,7 +140,17 @@
|
||||
"edit_settings": "编辑设置",
|
||||
"routing_strategy": "路由策略",
|
||||
"available_models": "可用模型",
|
||||
"available_models_desc": "所有提供商的模型总数"
|
||||
"available_models_desc": "所有提供商的模型总数",
|
||||
"welcome_back": "欢迎回来",
|
||||
"greeting_morning": "早上好",
|
||||
"greeting_afternoon": "下午好",
|
||||
"greeting_evening": "晚上好",
|
||||
"greeting_night": "夜深了",
|
||||
"caring_morning": "新的一天,准备大展身手吧。",
|
||||
"caring_afternoon": "稳步推进中,继续加油。",
|
||||
"caring_evening": "今天辛苦了,收尾工作做好哦。",
|
||||
"caring_night": "夜深了,别忘了早些休息。",
|
||||
"system_overview": "系统概览"
|
||||
},
|
||||
"basic_settings": {
|
||||
"title": "基础设置",
|
||||
@@ -497,15 +507,11 @@
|
||||
"pagination_next": "下一页",
|
||||
"pagination_info": "第 {{current}} / {{total}} 页 · 共 {{count}} 个文件",
|
||||
"search_label": "搜索配置文件",
|
||||
"search_placeholder": "输入名称、类型或提供方关键字",
|
||||
"search_regex_placeholder": "输入正则表达式匹配名称、类型或提供方",
|
||||
"search_regex_invalid": "请输入有效的正则表达式(最多 {{max}} 个字符)",
|
||||
"search_regex_unsafe": "该正则表达式可能导致页面卡顿,已阻止执行(避免嵌套量词、重复分组中的 | 或反向引用)",
|
||||
"search_placeholder": "输入名称、类型或提供方关键字,支持 * 通配",
|
||||
"problem_filter_label": "问题筛选",
|
||||
"problem_filter_only": "仅显示有问题凭证",
|
||||
"display_options_label": "显示选项",
|
||||
"compact_mode_label": "简略模式",
|
||||
"regex_search_mode_label": "正则模式",
|
||||
"sort_label": "排序",
|
||||
"sort_default": "默认",
|
||||
"sort_az": "A-Z 名称",
|
||||
@@ -591,6 +597,12 @@
|
||||
"note_placeholder": "输入备注信息,例如:张三的账号",
|
||||
"note_hint": "可选,用于标记凭证用途或归属;留空则不写入。",
|
||||
"note_display": "备注",
|
||||
"headers_label": "自定义请求头(headers)",
|
||||
"headers_placeholder": "{\n \"Header-Name\": \"value\"\n}",
|
||||
"headers_hint": "以 JSON 对象格式输入自定义 HTTP 请求头,例如:{\"X-My-Header\": \"value\"}",
|
||||
"headers_invalid_json": "自定义请求头必须是有效的 JSON。",
|
||||
"headers_invalid_object": "自定义请求头必须是 JSON 对象。",
|
||||
"headers_invalid_value": "每个自定义请求头的值都必须是字符串。",
|
||||
"prefix_proxy_invalid_json": "该认证文件不是 JSON 对象,无法编辑字段。",
|
||||
"prefix_proxy_saved_success": "已更新认证文件 \"{{name}}\"",
|
||||
"quota_refresh_success": "已刷新 \"{{name}}\" 的额度",
|
||||
@@ -658,7 +670,8 @@
|
||||
"plan_plus": "Plus",
|
||||
"plan_team": "Team",
|
||||
"plan_free": "Free",
|
||||
"plan_pro": "Pro"
|
||||
"plan_pro": "Pro 20x",
|
||||
"plan_prolite": "Pro 5x"
|
||||
},
|
||||
"gemini_cli_quota": {
|
||||
"title": "Gemini CLI 额度",
|
||||
@@ -1017,6 +1030,15 @@
|
||||
"request_events_source": "来源",
|
||||
"request_events_auth_index": "认证索引",
|
||||
"request_events_result": "结果",
|
||||
"time": "延迟",
|
||||
"avg_time": "平均延迟",
|
||||
"total_time": "总延迟",
|
||||
"latency_unit_hint": "耗时取自后端字段 {{field}},按 {{unit}} 解释后再格式化显示。",
|
||||
"duration_unit_d": "天",
|
||||
"duration_unit_h": "时",
|
||||
"duration_unit_m": "分",
|
||||
"duration_unit_s": "秒",
|
||||
"duration_unit_ms": "毫秒",
|
||||
"request_events_empty_title": "暂无请求事件",
|
||||
"request_events_empty_desc": "当前时间范围内暂无可用的请求明细数据。",
|
||||
"request_events_no_result_title": "没有匹配结果",
|
||||
@@ -1248,7 +1270,9 @@
|
||||
"switch_project": "切换项目",
|
||||
"switch_project_desc": "配额耗尽时自动切换到其他项目",
|
||||
"switch_preview_model": "切换预览模型",
|
||||
"switch_preview_model_desc": "配额耗尽时切换到预览版本模型"
|
||||
"switch_preview_model_desc": "配额耗尽时切换到预览版本模型",
|
||||
"antigravity_credits": "Antigravity Credits 重试",
|
||||
"antigravity_credits_desc": "Antigravity 返回 quota_exhausted 429 时,使用 enabledCreditTypes=[\"GOOGLE_ONE_AI\"] 重试一次"
|
||||
},
|
||||
"streaming": {
|
||||
"title": "流式传输配置",
|
||||
@@ -1347,7 +1371,8 @@
|
||||
"description": "集中查看 OAuth 额度与剩余情况",
|
||||
"refresh_files": "刷新认证文件",
|
||||
"refresh_files_and_quota": "刷新认证文件&额度",
|
||||
"card_idle_hint": "请使用顶部“刷新认证文件&额度”按钮获取最新额度。"
|
||||
"refresh_all_credentials": "刷新全部凭证",
|
||||
"card_idle_hint": "请使用顶部“刷新全部凭证”按钮获取最新额度。"
|
||||
},
|
||||
"system_info": {
|
||||
"title": "管理中心信息",
|
||||
|
||||
@@ -5,6 +5,8 @@ import { INLINE_LOGO_JPEG } from '@/assets/logoInline';
|
||||
import App from './App.tsx';
|
||||
|
||||
document.title = 'CLI Proxy API Management Center';
|
||||
document.documentElement.setAttribute('translate', 'no');
|
||||
document.documentElement.classList.add('notranslate');
|
||||
|
||||
const faviconEl = document.querySelector<HTMLLinkElement>('link[rel="icon"]');
|
||||
if (faviconEl) {
|
||||
|
||||
@@ -13,6 +13,7 @@ import { ampcodeApi } from '@/services/api';
|
||||
import { useAuthStore, useConfigStore, useNotificationStore } from '@/stores';
|
||||
import type { AmpcodeConfig } from '@/types';
|
||||
import { maskApiKey } from '@/utils/format';
|
||||
import { areStringArraysEqual } from '@/utils/compare';
|
||||
import {
|
||||
buildAmpcodeFormState,
|
||||
entriesToAmpcodeMappings,
|
||||
@@ -38,20 +39,52 @@ const normalizeMappingEntries = (entries: Array<{ name: string; alias: string }>
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
const normalizeUpstreamApiKeyEntries = (form: AmpcodeFormState) =>
|
||||
entriesToAmpcodeUpstreamApiKeys(form.upstreamApiKeyEntries).map((entry) => ({
|
||||
upstreamApiKey: entry.upstreamApiKey,
|
||||
apiKeys: entry.apiKeys,
|
||||
}));
|
||||
type AmpcodeFormBaseline = {
|
||||
upstreamUrl: string;
|
||||
upstreamApiKey: string;
|
||||
forceModelMappings: boolean;
|
||||
upstreamApiKeys: ReturnType<typeof entriesToAmpcodeUpstreamApiKeys>;
|
||||
modelMappings: ReturnType<typeof normalizeMappingEntries>;
|
||||
};
|
||||
|
||||
const buildAmpcodeSignature = (form: AmpcodeFormState) =>
|
||||
JSON.stringify({
|
||||
upstreamUrl: String(form.upstreamUrl ?? '').trim(),
|
||||
upstreamApiKey: String(form.upstreamApiKey ?? '').trim(),
|
||||
forceModelMappings: Boolean(form.forceModelMappings),
|
||||
upstreamApiKeys: normalizeUpstreamApiKeyEntries(form),
|
||||
modelMappings: normalizeMappingEntries(form.mappingEntries),
|
||||
});
|
||||
const buildAmpcodeBaseline = (form: AmpcodeFormState): AmpcodeFormBaseline => ({
|
||||
upstreamUrl: String(form.upstreamUrl ?? '').trim(),
|
||||
upstreamApiKey: String(form.upstreamApiKey ?? '').trim(),
|
||||
forceModelMappings: Boolean(form.forceModelMappings),
|
||||
upstreamApiKeys: entriesToAmpcodeUpstreamApiKeys(form.upstreamApiKeyEntries),
|
||||
modelMappings: normalizeMappingEntries(form.mappingEntries),
|
||||
});
|
||||
|
||||
const areUpstreamApiKeysEqual = (
|
||||
a: readonly { upstreamApiKey: string; apiKeys: readonly string[] }[],
|
||||
b: readonly { upstreamApiKey: string; apiKeys: readonly string[] }[]
|
||||
) => {
|
||||
if (a === b) return true;
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i += 1) {
|
||||
const left = a[i];
|
||||
const right = b[i];
|
||||
if (!left || !right) return false;
|
||||
if (left.upstreamApiKey !== right.upstreamApiKey) return false;
|
||||
if (!areStringArraysEqual(left.apiKeys, right.apiKeys)) return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const areModelMappingsEqual = (
|
||||
a: readonly { from: string; to: string }[],
|
||||
b: readonly { from: string; to: string }[]
|
||||
) => {
|
||||
if (a === b) return true;
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i += 1) {
|
||||
const left = a[i];
|
||||
const right = b[i];
|
||||
if (!left || !right) return false;
|
||||
if (left.from !== right.from || left.to !== right.to) return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
export function AiProvidersAmpcodeEditPage() {
|
||||
const { t } = useTranslation();
|
||||
@@ -72,9 +105,7 @@ export function AiProvidersAmpcodeEditPage() {
|
||||
const [upstreamApiKeysDirty, setUpstreamApiKeysDirty] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [baselineSignature, setBaselineSignature] = useState(() =>
|
||||
buildAmpcodeSignature(buildAmpcodeFormState(null))
|
||||
);
|
||||
const [baseline, setBaseline] = useState(() => buildAmpcodeBaseline(buildAmpcodeFormState(null)));
|
||||
const initializedRef = useRef(false);
|
||||
const mountedRef = useRef(false);
|
||||
|
||||
@@ -119,7 +150,7 @@ export function AiProvidersAmpcodeEditPage() {
|
||||
setError('');
|
||||
const initialForm = buildAmpcodeFormState(useConfigStore.getState().config?.ampcode ?? null);
|
||||
setForm(initialForm);
|
||||
setBaselineSignature(buildAmpcodeSignature(initialForm));
|
||||
setBaseline(buildAmpcodeBaseline(initialForm));
|
||||
|
||||
void (async () => {
|
||||
try {
|
||||
@@ -131,7 +162,7 @@ export function AiProvidersAmpcodeEditPage() {
|
||||
clearCache('ampcode');
|
||||
const nextForm = buildAmpcodeFormState(ampcode);
|
||||
setForm(nextForm);
|
||||
setBaselineSignature(buildAmpcodeSignature(nextForm));
|
||||
setBaseline(buildAmpcodeBaseline(nextForm));
|
||||
} catch (err: unknown) {
|
||||
if (!mountedRef.current) return;
|
||||
setError(getErrorMessage(err) || t('notification.refresh_failed'));
|
||||
@@ -143,8 +174,28 @@ export function AiProvidersAmpcodeEditPage() {
|
||||
})();
|
||||
}, [clearCache, t, updateConfigValue]);
|
||||
|
||||
const currentSignature = useMemo(() => buildAmpcodeSignature(form), [form]);
|
||||
const isDirty = baselineSignature !== currentSignature;
|
||||
const normalizedUpstreamApiKeys = useMemo(
|
||||
() => entriesToAmpcodeUpstreamApiKeys(form.upstreamApiKeyEntries),
|
||||
[form.upstreamApiKeyEntries]
|
||||
);
|
||||
const normalizedModelMappings = useMemo(
|
||||
() => normalizeMappingEntries(form.mappingEntries),
|
||||
[form.mappingEntries]
|
||||
);
|
||||
const isUpstreamApiKeysDirty = useMemo(
|
||||
() => !areUpstreamApiKeysEqual(baseline.upstreamApiKeys, normalizedUpstreamApiKeys),
|
||||
[baseline.upstreamApiKeys, normalizedUpstreamApiKeys]
|
||||
);
|
||||
const isModelMappingsDirtyNormalized = useMemo(
|
||||
() => !areModelMappingsEqual(baseline.modelMappings, normalizedModelMappings),
|
||||
[baseline.modelMappings, normalizedModelMappings]
|
||||
);
|
||||
const isDirty =
|
||||
baseline.upstreamUrl !== form.upstreamUrl.trim() ||
|
||||
baseline.upstreamApiKey !== form.upstreamApiKey.trim() ||
|
||||
baseline.forceModelMappings !== Boolean(form.forceModelMappings) ||
|
||||
isUpstreamApiKeysDirty ||
|
||||
isModelMappingsDirtyNormalized;
|
||||
const canGuard = !loading && !saving;
|
||||
|
||||
const { allowNextNavigation } = useUnsavedChangesGuard({
|
||||
@@ -263,7 +314,7 @@ export function AiProvidersAmpcodeEditPage() {
|
||||
clearCache('ampcode');
|
||||
showNotification(t('notification.ampcode_updated'), 'success');
|
||||
allowNextNavigation();
|
||||
setBaselineSignature(buildAmpcodeSignature(form));
|
||||
setBaseline(buildAmpcodeBaseline(form));
|
||||
handleBack();
|
||||
} catch (err: unknown) {
|
||||
const message = getErrorMessage(err);
|
||||
|
||||
@@ -9,8 +9,10 @@ import type { ProviderKeyConfig } from '@/types';
|
||||
import type { ModelInfo } from '@/utils/models';
|
||||
import type { ModelEntry, ProviderFormState } from '@/components/providers/types';
|
||||
import { buildHeaderObject, headersToEntries, normalizeHeaderEntries } from '@/utils/headers';
|
||||
import { areKeyValueEntriesEqual, areModelEntriesEqual, areStringArraysEqual } from '@/utils/compare';
|
||||
import { excludedModelsToText, parseExcludedModels } from '@/components/providers/utils';
|
||||
import { modelsToEntries } from '@/components/ui/modelInputListUtils';
|
||||
import type { ClaudeEditBaseline } from '@/stores/useClaudeEditDraftStore';
|
||||
|
||||
type LocationState = { fromAiProviders?: boolean } | null;
|
||||
|
||||
@@ -89,19 +91,28 @@ const normalizeCloakConfig = (cloak: ProviderFormState['cloak']) => {
|
||||
};
|
||||
};
|
||||
|
||||
const buildClaudeSignature = (form: ProviderFormState) =>
|
||||
JSON.stringify({
|
||||
apiKey: String(form.apiKey ?? '').trim(),
|
||||
priority:
|
||||
form.priority !== undefined && Number.isFinite(form.priority) ? Math.trunc(form.priority) : null,
|
||||
prefix: String(form.prefix ?? '').trim(),
|
||||
baseUrl: String(form.baseUrl ?? '').trim(),
|
||||
proxyUrl: String(form.proxyUrl ?? '').trim(),
|
||||
headers: normalizeHeaderEntries(form.headers),
|
||||
models: normalizeClaudeModelEntries(form.modelEntries),
|
||||
excludedModels: parseExcludedModels(form.excludedText ?? ''),
|
||||
cloak: normalizeCloakConfig(form.cloak),
|
||||
});
|
||||
const buildClaudeBaseline = (form: ProviderFormState): ClaudeEditBaseline => ({
|
||||
apiKey: String(form.apiKey ?? '').trim(),
|
||||
priority:
|
||||
form.priority !== undefined && Number.isFinite(form.priority) ? Math.trunc(form.priority) : null,
|
||||
prefix: String(form.prefix ?? '').trim(),
|
||||
baseUrl: String(form.baseUrl ?? '').trim(),
|
||||
proxyUrl: String(form.proxyUrl ?? '').trim(),
|
||||
headers: normalizeHeaderEntries(form.headers),
|
||||
models: normalizeClaudeModelEntries(form.modelEntries),
|
||||
excludedModels: parseExcludedModels(form.excludedText ?? ''),
|
||||
cloak: normalizeCloakConfig(form.cloak),
|
||||
});
|
||||
|
||||
const areCloakConfigsEqual = (left: ClaudeEditBaseline['cloak'], right: ClaudeEditBaseline['cloak']) => {
|
||||
if (left === right) return true;
|
||||
if (!left || !right) return false;
|
||||
if (left.mode !== right.mode || left.strictMode !== right.strictMode) return false;
|
||||
if (left.sensitiveWords === null || right.sensitiveWords === null) {
|
||||
return left.sensitiveWords === right.sensitiveWords;
|
||||
}
|
||||
return areStringArraysEqual(left.sensitiveWords, right.sensitiveWords);
|
||||
};
|
||||
|
||||
export function AiProvidersClaudeEditLayout() {
|
||||
const { t } = useTranslation();
|
||||
@@ -137,7 +148,7 @@ export function AiProvidersClaudeEditLayout() {
|
||||
const acquireDraft = useClaudeEditDraftStore((state) => state.acquireDraft);
|
||||
const releaseDraft = useClaudeEditDraftStore((state) => state.releaseDraft);
|
||||
const initDraft = useClaudeEditDraftStore((state) => state.initDraft);
|
||||
const setDraftBaselineSignature = useClaudeEditDraftStore((state) => state.setDraftBaselineSignature);
|
||||
const setDraftBaseline = useClaudeEditDraftStore((state) => state.setDraftBaseline);
|
||||
const setDraftForm = useClaudeEditDraftStore((state) => state.setDraftForm);
|
||||
const setDraftTestModel = useClaudeEditDraftStore((state) => state.setDraftTestModel);
|
||||
const setDraftTestStatus = useClaudeEditDraftStore((state) => state.setDraftTestStatus);
|
||||
@@ -241,9 +252,9 @@ export function AiProvidersClaudeEditLayout() {
|
||||
excludedText: excludedModelsToText(initialData.excludedModels),
|
||||
};
|
||||
const available = seededForm.modelEntries.map((entry) => entry.name.trim()).filter(Boolean);
|
||||
const baselineSignature = buildClaudeSignature(seededForm);
|
||||
const baseline = buildClaudeBaseline(seededForm);
|
||||
initDraft(draftKey, {
|
||||
baselineSignature,
|
||||
baseline,
|
||||
form: seededForm,
|
||||
testModel: available[0] || '',
|
||||
testStatus: 'idle',
|
||||
@@ -254,7 +265,7 @@ export function AiProvidersClaudeEditLayout() {
|
||||
|
||||
const emptyForm = buildEmptyForm();
|
||||
initDraft(draftKey, {
|
||||
baselineSignature: buildClaudeSignature(emptyForm),
|
||||
baseline: buildClaudeBaseline(emptyForm),
|
||||
form: emptyForm,
|
||||
testModel: '',
|
||||
testStatus: 'idle',
|
||||
@@ -263,9 +274,50 @@ export function AiProvidersClaudeEditLayout() {
|
||||
}, [draft?.initialized, draftKey, initDraft, initialData, loading]);
|
||||
|
||||
const resolvedLoading = !draft?.initialized;
|
||||
const currentSignature = useMemo(() => buildClaudeSignature(form), [form]);
|
||||
const baselineSignature = draft?.baselineSignature ?? '';
|
||||
const isDirty = Boolean(draft?.initialized) && baselineSignature !== currentSignature;
|
||||
const baseline = draft?.baseline ?? null;
|
||||
const normalizedHeaders = useMemo(() => normalizeHeaderEntries(form.headers), [form.headers]);
|
||||
const normalizedModels = useMemo(
|
||||
() => normalizeClaudeModelEntries(form.modelEntries),
|
||||
[form.modelEntries]
|
||||
);
|
||||
const normalizedExcludedModels = useMemo(
|
||||
() => parseExcludedModels(form.excludedText ?? ''),
|
||||
[form.excludedText]
|
||||
);
|
||||
const normalizedCloak = useMemo(() => normalizeCloakConfig(form.cloak), [form.cloak]);
|
||||
const normalizedPriority = useMemo(() => {
|
||||
return form.priority !== undefined && Number.isFinite(form.priority)
|
||||
? Math.trunc(form.priority)
|
||||
: null;
|
||||
}, [form.priority]);
|
||||
const isHeadersDirty = useMemo(() => {
|
||||
if (!baseline) return false;
|
||||
return !areKeyValueEntriesEqual(baseline.headers, normalizedHeaders);
|
||||
}, [baseline, normalizedHeaders]);
|
||||
const isModelsDirty = useMemo(() => {
|
||||
if (!baseline) return false;
|
||||
return !areModelEntriesEqual(baseline.models, normalizedModels);
|
||||
}, [baseline, normalizedModels]);
|
||||
const isExcludedModelsDirty = useMemo(() => {
|
||||
if (!baseline) return false;
|
||||
return !areStringArraysEqual(baseline.excludedModels, normalizedExcludedModels);
|
||||
}, [baseline, normalizedExcludedModels]);
|
||||
const isCloakDirty = useMemo(() => {
|
||||
if (!baseline) return false;
|
||||
return !areCloakConfigsEqual(baseline.cloak, normalizedCloak);
|
||||
}, [baseline, normalizedCloak]);
|
||||
const isDirty =
|
||||
Boolean(draft?.initialized) &&
|
||||
baseline !== null &&
|
||||
(baseline.apiKey !== form.apiKey.trim() ||
|
||||
baseline.priority !== normalizedPriority ||
|
||||
baseline.prefix !== String(form.prefix ?? '').trim() ||
|
||||
baseline.baseUrl !== String(form.baseUrl ?? '').trim() ||
|
||||
baseline.proxyUrl !== String(form.proxyUrl ?? '').trim() ||
|
||||
isHeadersDirty ||
|
||||
isModelsDirty ||
|
||||
isExcludedModelsDirty ||
|
||||
isCloakDirty);
|
||||
const editorRootPath = useMemo(() => {
|
||||
if (hasIndexParam) {
|
||||
return `/ai-providers/claude/${params.index ?? ''}`;
|
||||
@@ -384,7 +436,7 @@ export function AiProvidersClaudeEditLayout() {
|
||||
'success'
|
||||
);
|
||||
allowNextNavigation();
|
||||
setDraftBaselineSignature(draftKey, buildClaudeSignature(form));
|
||||
setDraftBaseline(draftKey, buildClaudeBaseline(form));
|
||||
handleBack();
|
||||
} catch (err: unknown) {
|
||||
showNotification(`${t('notification.update_failed')}: ${getErrorMessage(err)}`, 'error');
|
||||
@@ -403,7 +455,7 @@ export function AiProvidersClaudeEditLayout() {
|
||||
invalidIndex,
|
||||
invalidIndexParam,
|
||||
resolvedLoading,
|
||||
setDraftBaselineSignature,
|
||||
setDraftBaseline,
|
||||
saving,
|
||||
showNotification,
|
||||
t,
|
||||
|
||||
@@ -16,6 +16,7 @@ import { modelsApi, providersApi } from '@/services/api';
|
||||
import { useAuthStore, useConfigStore, useNotificationStore } from '@/stores';
|
||||
import type { ProviderKeyConfig } from '@/types';
|
||||
import { buildHeaderObject, headersToEntries, normalizeHeaderEntries } from '@/utils/headers';
|
||||
import { areKeyValueEntriesEqual, areModelEntriesEqual, areStringArraysEqual } from '@/utils/compare';
|
||||
import { entriesToModels, modelsToEntries } from '@/components/ui/modelInputListUtils';
|
||||
import { excludedModelsToText, parseExcludedModels } from '@/components/providers/utils';
|
||||
import type { ProviderFormState } from '@/components/providers';
|
||||
@@ -63,21 +64,30 @@ const normalizeModelEntries = (entries: Array<{ name: string; alias: string }>)
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
const buildCodexSignature = (form: ProviderFormState) =>
|
||||
JSON.stringify({
|
||||
apiKey: String(form.apiKey ?? '').trim(),
|
||||
priority:
|
||||
form.priority !== undefined && Number.isFinite(form.priority)
|
||||
? Math.trunc(form.priority)
|
||||
: null,
|
||||
prefix: String(form.prefix ?? '').trim(),
|
||||
baseUrl: String(form.baseUrl ?? '').trim(),
|
||||
websockets: Boolean(form.websockets),
|
||||
proxyUrl: String(form.proxyUrl ?? '').trim(),
|
||||
headers: normalizeHeaderEntries(form.headers),
|
||||
models: normalizeModelEntries(form.modelEntries),
|
||||
excludedModels: parseExcludedModels(form.excludedText ?? ''),
|
||||
});
|
||||
type CodexFormBaseline = {
|
||||
apiKey: string;
|
||||
priority: number | null;
|
||||
prefix: string;
|
||||
baseUrl: string;
|
||||
websockets: boolean;
|
||||
proxyUrl: string;
|
||||
headers: ReturnType<typeof normalizeHeaderEntries>;
|
||||
models: ReturnType<typeof normalizeModelEntries>;
|
||||
excludedModels: string[];
|
||||
};
|
||||
|
||||
const buildCodexBaseline = (form: ProviderFormState): CodexFormBaseline => ({
|
||||
apiKey: String(form.apiKey ?? '').trim(),
|
||||
priority:
|
||||
form.priority !== undefined && Number.isFinite(form.priority) ? Math.trunc(form.priority) : null,
|
||||
prefix: String(form.prefix ?? '').trim(),
|
||||
baseUrl: String(form.baseUrl ?? '').trim(),
|
||||
websockets: Boolean(form.websockets),
|
||||
proxyUrl: String(form.proxyUrl ?? '').trim(),
|
||||
headers: normalizeHeaderEntries(form.headers),
|
||||
models: normalizeModelEntries(form.modelEntries),
|
||||
excludedModels: parseExcludedModels(form.excludedText ?? ''),
|
||||
});
|
||||
|
||||
export function AiProvidersCodexEditPage() {
|
||||
const { t } = useTranslation();
|
||||
@@ -98,9 +108,7 @@ export function AiProvidersCodexEditPage() {
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [form, setForm] = useState<ProviderFormState>(() => buildEmptyForm());
|
||||
const [baselineSignature, setBaselineSignature] = useState(() =>
|
||||
buildCodexSignature(buildEmptyForm())
|
||||
);
|
||||
const [baseline, setBaseline] = useState(() => buildCodexBaseline(buildEmptyForm()));
|
||||
|
||||
const [modelDiscoveryOpen, setModelDiscoveryOpen] = useState(false);
|
||||
const [modelDiscoveryEndpoint, setModelDiscoveryEndpoint] = useState('');
|
||||
@@ -186,16 +194,50 @@ export function AiProvidersCodexEditPage() {
|
||||
excludedText: excludedModelsToText(initialData.excludedModels),
|
||||
};
|
||||
setForm(nextForm);
|
||||
setBaselineSignature(buildCodexSignature(nextForm));
|
||||
setBaseline(buildCodexBaseline(nextForm));
|
||||
return;
|
||||
}
|
||||
const nextForm = buildEmptyForm();
|
||||
setForm(nextForm);
|
||||
setBaselineSignature(buildCodexSignature(nextForm));
|
||||
setBaseline(buildCodexBaseline(nextForm));
|
||||
}, [initialData, loading]);
|
||||
|
||||
const currentSignature = useMemo(() => buildCodexSignature(form), [form]);
|
||||
const isDirty = baselineSignature !== currentSignature;
|
||||
const normalizedHeaders = useMemo(() => normalizeHeaderEntries(form.headers), [form.headers]);
|
||||
const normalizedModels = useMemo(
|
||||
() => normalizeModelEntries(form.modelEntries),
|
||||
[form.modelEntries]
|
||||
);
|
||||
const normalizedExcludedModels = useMemo(
|
||||
() => parseExcludedModels(form.excludedText ?? ''),
|
||||
[form.excludedText]
|
||||
);
|
||||
const normalizedPriority = useMemo(() => {
|
||||
return form.priority !== undefined && Number.isFinite(form.priority)
|
||||
? Math.trunc(form.priority)
|
||||
: null;
|
||||
}, [form.priority]);
|
||||
const isHeadersDirty = useMemo(
|
||||
() => !areKeyValueEntriesEqual(baseline.headers, normalizedHeaders),
|
||||
[baseline.headers, normalizedHeaders]
|
||||
);
|
||||
const isModelsDirty = useMemo(
|
||||
() => !areModelEntriesEqual(baseline.models, normalizedModels),
|
||||
[baseline.models, normalizedModels]
|
||||
);
|
||||
const isExcludedModelsDirty = useMemo(
|
||||
() => !areStringArraysEqual(baseline.excludedModels, normalizedExcludedModels),
|
||||
[baseline.excludedModels, normalizedExcludedModels]
|
||||
);
|
||||
const isDirty =
|
||||
baseline.apiKey !== form.apiKey.trim() ||
|
||||
baseline.priority !== normalizedPriority ||
|
||||
baseline.prefix !== String(form.prefix ?? '').trim() ||
|
||||
baseline.baseUrl !== String(form.baseUrl ?? '').trim() ||
|
||||
baseline.websockets !== Boolean(form.websockets) ||
|
||||
baseline.proxyUrl !== String(form.proxyUrl ?? '').trim() ||
|
||||
isHeadersDirty ||
|
||||
isModelsDirty ||
|
||||
isExcludedModelsDirty;
|
||||
const canGuard = !loading && !saving && !invalidIndexParam && !invalidIndex;
|
||||
|
||||
const { allowNextNavigation } = useUnsavedChangesGuard({
|
||||
@@ -430,7 +472,7 @@ export function AiProvidersCodexEditPage() {
|
||||
'success'
|
||||
);
|
||||
allowNextNavigation();
|
||||
setBaselineSignature(buildCodexSignature(form));
|
||||
setBaseline(buildCodexBaseline(form));
|
||||
handleBack();
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : '';
|
||||
|
||||
@@ -15,6 +15,7 @@ import { modelsApi, providersApi } from '@/services/api';
|
||||
import { useAuthStore, useConfigStore, useNotificationStore } from '@/stores';
|
||||
import type { GeminiKeyConfig } from '@/types';
|
||||
import { buildHeaderObject, headersToEntries, normalizeHeaderEntries } from '@/utils/headers';
|
||||
import { areKeyValueEntriesEqual, areModelEntriesEqual, areStringArraysEqual } from '@/utils/compare';
|
||||
import type { ModelInfo } from '@/utils/models';
|
||||
import { entriesToModels, modelsToEntries } from '@/components/ui/modelInputListUtils';
|
||||
import { excludedModelsToText, parseExcludedModels } from '@/components/providers/utils';
|
||||
@@ -60,20 +61,28 @@ const normalizeModelEntries = (entries: Array<{ name: string; alias: string }>)
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
const buildGeminiSignature = (form: GeminiFormState) =>
|
||||
JSON.stringify({
|
||||
apiKey: String(form.apiKey ?? '').trim(),
|
||||
priority:
|
||||
form.priority !== undefined && Number.isFinite(form.priority)
|
||||
? Math.trunc(form.priority)
|
||||
: null,
|
||||
prefix: String(form.prefix ?? '').trim(),
|
||||
baseUrl: String(form.baseUrl ?? '').trim(),
|
||||
proxyUrl: String(form.proxyUrl ?? '').trim(),
|
||||
headers: normalizeHeaderEntries(form.headers),
|
||||
models: normalizeModelEntries(form.modelEntries),
|
||||
excludedModels: parseExcludedModels(form.excludedText ?? ''),
|
||||
});
|
||||
type GeminiFormBaseline = {
|
||||
apiKey: string;
|
||||
priority: number | null;
|
||||
prefix: string;
|
||||
baseUrl: string;
|
||||
proxyUrl: string;
|
||||
headers: ReturnType<typeof normalizeHeaderEntries>;
|
||||
models: ReturnType<typeof normalizeModelEntries>;
|
||||
excludedModels: string[];
|
||||
};
|
||||
|
||||
const buildGeminiBaseline = (form: GeminiFormState): GeminiFormBaseline => ({
|
||||
apiKey: String(form.apiKey ?? '').trim(),
|
||||
priority:
|
||||
form.priority !== undefined && Number.isFinite(form.priority) ? Math.trunc(form.priority) : null,
|
||||
prefix: String(form.prefix ?? '').trim(),
|
||||
baseUrl: String(form.baseUrl ?? '').trim(),
|
||||
proxyUrl: String(form.proxyUrl ?? '').trim(),
|
||||
headers: normalizeHeaderEntries(form.headers),
|
||||
models: normalizeModelEntries(form.modelEntries),
|
||||
excludedModels: parseExcludedModels(form.excludedText ?? ''),
|
||||
});
|
||||
|
||||
export function AiProvidersGeminiEditPage() {
|
||||
const { t } = useTranslation();
|
||||
@@ -94,9 +103,7 @@ export function AiProvidersGeminiEditPage() {
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [form, setForm] = useState<GeminiFormState>(() => buildEmptyForm());
|
||||
const [baselineSignature, setBaselineSignature] = useState(() =>
|
||||
buildGeminiSignature(buildEmptyForm())
|
||||
);
|
||||
const [baseline, setBaseline] = useState(() => buildGeminiBaseline(buildEmptyForm()));
|
||||
|
||||
const [modelDiscoveryOpen, setModelDiscoveryOpen] = useState(false);
|
||||
const [modelDiscoveryEndpoint, setModelDiscoveryEndpoint] = useState('');
|
||||
@@ -185,12 +192,12 @@ export function AiProvidersGeminiEditPage() {
|
||||
excludedText: excludedModelsToText(initialData.excludedModels),
|
||||
};
|
||||
setForm(nextForm);
|
||||
setBaselineSignature(buildGeminiSignature(nextForm));
|
||||
setBaseline(buildGeminiBaseline(nextForm));
|
||||
return;
|
||||
}
|
||||
const nextForm = buildEmptyForm();
|
||||
setForm(nextForm);
|
||||
setBaselineSignature(buildGeminiSignature(nextForm));
|
||||
setBaseline(buildGeminiBaseline(nextForm));
|
||||
}, [initialData, loading]);
|
||||
|
||||
const canSave = !disableControls && !saving && !loading && !invalidIndexParam && !invalidIndex;
|
||||
@@ -378,8 +385,41 @@ export function AiProvidersGeminiEditPage() {
|
||||
setModelDiscoveryOpen(false);
|
||||
};
|
||||
|
||||
const currentSignature = useMemo(() => buildGeminiSignature(form), [form]);
|
||||
const isDirty = baselineSignature !== currentSignature;
|
||||
const normalizedHeaders = useMemo(() => normalizeHeaderEntries(form.headers), [form.headers]);
|
||||
const normalizedModels = useMemo(
|
||||
() => normalizeModelEntries(form.modelEntries),
|
||||
[form.modelEntries]
|
||||
);
|
||||
const normalizedExcludedModels = useMemo(
|
||||
() => parseExcludedModels(form.excludedText ?? ''),
|
||||
[form.excludedText]
|
||||
);
|
||||
const normalizedPriority = useMemo(() => {
|
||||
return form.priority !== undefined && Number.isFinite(form.priority)
|
||||
? Math.trunc(form.priority)
|
||||
: null;
|
||||
}, [form.priority]);
|
||||
const isHeadersDirty = useMemo(
|
||||
() => !areKeyValueEntriesEqual(baseline.headers, normalizedHeaders),
|
||||
[baseline.headers, normalizedHeaders]
|
||||
);
|
||||
const isModelsDirty = useMemo(
|
||||
() => !areModelEntriesEqual(baseline.models, normalizedModels),
|
||||
[baseline.models, normalizedModels]
|
||||
);
|
||||
const isExcludedModelsDirty = useMemo(
|
||||
() => !areStringArraysEqual(baseline.excludedModels, normalizedExcludedModels),
|
||||
[baseline.excludedModels, normalizedExcludedModels]
|
||||
);
|
||||
const isDirty =
|
||||
baseline.apiKey !== form.apiKey.trim() ||
|
||||
baseline.priority !== normalizedPriority ||
|
||||
baseline.prefix !== String(form.prefix ?? '').trim() ||
|
||||
baseline.baseUrl !== String(form.baseUrl ?? '').trim() ||
|
||||
baseline.proxyUrl !== String(form.proxyUrl ?? '').trim() ||
|
||||
isHeadersDirty ||
|
||||
isModelsDirty ||
|
||||
isExcludedModelsDirty;
|
||||
const canGuard = !loading && !saving && !invalidIndexParam && !invalidIndex;
|
||||
|
||||
const { allowNextNavigation } = useUnsavedChangesGuard({
|
||||
@@ -432,7 +472,7 @@ export function AiProvidersGeminiEditPage() {
|
||||
'success'
|
||||
);
|
||||
allowNextNavigation();
|
||||
setBaselineSignature(buildGeminiSignature(form));
|
||||
setBaseline(buildGeminiBaseline(form));
|
||||
handleBack();
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : '';
|
||||
|
||||
@@ -9,9 +9,10 @@ import { entriesToModels, modelsToEntries } from '@/components/ui/modelInputList
|
||||
import type { ApiKeyEntry, OpenAIProviderConfig } from '@/types';
|
||||
import type { ModelInfo } from '@/utils/models';
|
||||
import { buildHeaderObject, headersToEntries, normalizeHeaderEntries } from '@/utils/headers';
|
||||
import { areKeyValueEntriesEqual, areModelEntriesEqual } from '@/utils/compare';
|
||||
import { buildApiKeyEntry } from '@/components/providers/utils';
|
||||
import type { ModelEntry, OpenAIFormState } from '@/components/providers/types';
|
||||
import type { KeyTestStatus } from '@/stores/useOpenAIEditDraftStore';
|
||||
import type { KeyTestStatus, OpenAIEditBaseline } from '@/stores/useOpenAIEditDraftStore';
|
||||
|
||||
type LocationState = { fromAiProviders?: boolean } | null;
|
||||
|
||||
@@ -103,18 +104,33 @@ const normalizeApiKeyEntries = (entries: ApiKeyEntry[]) =>
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
const buildOpenAISignature = (form: OpenAIFormState, testModel: string) =>
|
||||
JSON.stringify({
|
||||
name: String(form.name ?? '').trim(),
|
||||
priority:
|
||||
form.priority !== undefined && Number.isFinite(form.priority) ? Math.trunc(form.priority) : null,
|
||||
prefix: String(form.prefix ?? '').trim(),
|
||||
baseUrl: String(form.baseUrl ?? '').trim(),
|
||||
headers: normalizeHeaderEntries(form.headers),
|
||||
apiKeyEntries: normalizeApiKeyEntries(form.apiKeyEntries),
|
||||
models: normalizeModelEntries(form.modelEntries),
|
||||
testModel: String(testModel ?? '').trim(),
|
||||
});
|
||||
const buildOpenAIBaseline = (form: OpenAIFormState, testModel: string): OpenAIEditBaseline => ({
|
||||
name: String(form.name ?? '').trim(),
|
||||
priority:
|
||||
form.priority !== undefined && Number.isFinite(form.priority) ? Math.trunc(form.priority) : null,
|
||||
prefix: String(form.prefix ?? '').trim(),
|
||||
baseUrl: String(form.baseUrl ?? '').trim(),
|
||||
headers: normalizeHeaderEntries(form.headers),
|
||||
apiKeyEntries: normalizeApiKeyEntries(form.apiKeyEntries),
|
||||
models: normalizeModelEntries(form.modelEntries),
|
||||
testModel: String(testModel ?? '').trim(),
|
||||
});
|
||||
|
||||
const areNormalizedApiKeyEntriesEqual = (
|
||||
a: OpenAIEditBaseline['apiKeyEntries'],
|
||||
b: ReturnType<typeof normalizeApiKeyEntries>
|
||||
) => {
|
||||
if (a === b) return true;
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i += 1) {
|
||||
const left = a[i];
|
||||
const right = b[i];
|
||||
if (!left || !right) return false;
|
||||
if (left.apiKey !== right.apiKey || left.proxyUrl !== right.proxyUrl) return false;
|
||||
if (!areKeyValueEntriesEqual(left.headers, right.headers)) return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
export function AiProvidersOpenAIEditLayout() {
|
||||
const { t } = useTranslation();
|
||||
@@ -152,7 +168,7 @@ export function AiProvidersOpenAIEditLayout() {
|
||||
const acquireDraft = useOpenAIEditDraftStore((state) => state.acquireDraft);
|
||||
const releaseDraft = useOpenAIEditDraftStore((state) => state.releaseDraft);
|
||||
const initDraft = useOpenAIEditDraftStore((state) => state.initDraft);
|
||||
const setDraftBaselineSignature = useOpenAIEditDraftStore((state) => state.setDraftBaselineSignature);
|
||||
const setDraftBaseline = useOpenAIEditDraftStore((state) => state.setDraftBaseline);
|
||||
const setDraftForm = useOpenAIEditDraftStore((state) => state.setDraftForm);
|
||||
const setDraftTestModel = useOpenAIEditDraftStore((state) => state.setDraftTestModel);
|
||||
const setDraftTestStatus = useOpenAIEditDraftStore((state) => state.setDraftTestStatus);
|
||||
@@ -286,9 +302,9 @@ export function AiProvidersOpenAIEditLayout() {
|
||||
initialData.testModel && available.includes(initialData.testModel)
|
||||
? initialData.testModel
|
||||
: available[0] || '';
|
||||
const baselineSignature = buildOpenAISignature(seededForm, initialTestModel);
|
||||
const baseline = buildOpenAIBaseline(seededForm, initialTestModel);
|
||||
initDraft(draftKey, {
|
||||
baselineSignature,
|
||||
baseline,
|
||||
form: seededForm,
|
||||
testModel: initialTestModel,
|
||||
testStatus: 'idle',
|
||||
@@ -298,7 +314,7 @@ export function AiProvidersOpenAIEditLayout() {
|
||||
} else {
|
||||
const emptyForm = buildEmptyForm();
|
||||
initDraft(draftKey, {
|
||||
baselineSignature: buildOpenAISignature(emptyForm, ''),
|
||||
baseline: buildOpenAIBaseline(emptyForm, ''),
|
||||
form: emptyForm,
|
||||
testModel: '',
|
||||
testStatus: 'idle',
|
||||
@@ -362,9 +378,45 @@ export function AiProvidersOpenAIEditLayout() {
|
||||
);
|
||||
|
||||
const resolvedLoading = !draft?.initialized;
|
||||
const currentSignature = useMemo(() => buildOpenAISignature(form, testModel), [form, testModel]);
|
||||
const baselineSignature = draft?.baselineSignature ?? '';
|
||||
const isDirty = Boolean(draft?.initialized) && baselineSignature !== currentSignature;
|
||||
const baseline = draft?.baseline ?? null;
|
||||
const normalizedHeaders = useMemo(() => normalizeHeaderEntries(form.headers), [form.headers]);
|
||||
const normalizedModels = useMemo(
|
||||
() => normalizeModelEntries(form.modelEntries),
|
||||
[form.modelEntries]
|
||||
);
|
||||
const normalizedApiKeyEntries = useMemo(
|
||||
() => normalizeApiKeyEntries(form.apiKeyEntries),
|
||||
[form.apiKeyEntries]
|
||||
);
|
||||
const normalizedPriority = useMemo(() => {
|
||||
return form.priority !== undefined && Number.isFinite(form.priority)
|
||||
? Math.trunc(form.priority)
|
||||
: null;
|
||||
}, [form.priority]);
|
||||
const normalizedTestModel = useMemo(() => String(testModel ?? '').trim(), [testModel]);
|
||||
const isHeadersDirty = useMemo(() => {
|
||||
if (!baseline) return false;
|
||||
return !areKeyValueEntriesEqual(baseline.headers, normalizedHeaders);
|
||||
}, [baseline, normalizedHeaders]);
|
||||
const isModelsDirty = useMemo(() => {
|
||||
if (!baseline) return false;
|
||||
return !areModelEntriesEqual(baseline.models, normalizedModels);
|
||||
}, [baseline, normalizedModels]);
|
||||
const isApiKeyEntriesDirty = useMemo(() => {
|
||||
if (!baseline) return false;
|
||||
return !areNormalizedApiKeyEntriesEqual(baseline.apiKeyEntries, normalizedApiKeyEntries);
|
||||
}, [baseline, normalizedApiKeyEntries]);
|
||||
const isDirty =
|
||||
Boolean(draft?.initialized) &&
|
||||
baseline !== null &&
|
||||
(baseline.name !== form.name.trim() ||
|
||||
baseline.priority !== normalizedPriority ||
|
||||
baseline.prefix !== form.prefix.trim() ||
|
||||
baseline.baseUrl !== form.baseUrl.trim() ||
|
||||
baseline.testModel !== normalizedTestModel ||
|
||||
isHeadersDirty ||
|
||||
isApiKeyEntriesDirty ||
|
||||
isModelsDirty);
|
||||
const editorRootPath = useMemo(() => {
|
||||
if (hasIndexParam) {
|
||||
return `/ai-providers/openai/${params.index ?? ''}`;
|
||||
@@ -445,7 +497,7 @@ export function AiProvidersOpenAIEditLayout() {
|
||||
'success'
|
||||
);
|
||||
allowNextNavigation();
|
||||
setDraftBaselineSignature(draftKey, buildOpenAISignature(form, testModel));
|
||||
setDraftBaseline(draftKey, buildOpenAIBaseline(form, testModel));
|
||||
handleBack();
|
||||
} catch (err: unknown) {
|
||||
showNotification(`${t('notification.update_failed')}: ${getErrorMessage(err)}`, 'error');
|
||||
@@ -460,7 +512,7 @@ export function AiProvidersOpenAIEditLayout() {
|
||||
form,
|
||||
handleBack,
|
||||
providers,
|
||||
setDraftBaselineSignature,
|
||||
setDraftBaseline,
|
||||
showNotification,
|
||||
t,
|
||||
testModel,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
@@ -15,10 +15,12 @@ import {
|
||||
withDisableAllModelsRule,
|
||||
withoutDisableAllModelsRule,
|
||||
} from '@/components/providers/utils';
|
||||
import { usePageTransitionLayer } from '@/components/common/PageTransitionLayer';
|
||||
import { useHeaderRefresh } from '@/hooks/useHeaderRefresh';
|
||||
import { ampcodeApi, providersApi } from '@/services/api';
|
||||
import { useAuthStore, useConfigStore, useNotificationStore, useThemeStore } from '@/stores';
|
||||
import type { GeminiKeyConfig, OpenAIProviderConfig, ProviderKeyConfig } from '@/types';
|
||||
import { indexUsageDetailsBySource } from '@/utils/usageIndex';
|
||||
import styles from './AiProvidersPage.module.scss';
|
||||
|
||||
export function AiProvidersPage() {
|
||||
@@ -59,7 +61,16 @@ export function AiProvidersPage() {
|
||||
const disableControls = connectionStatus !== 'connected';
|
||||
const isSwitching = Boolean(configSwitchingKey);
|
||||
|
||||
const { keyStats, usageDetails, loadKeyStats, refreshKeyStats } = useProviderStats();
|
||||
const pageTransitionLayer = usePageTransitionLayer();
|
||||
const isCurrentLayer = pageTransitionLayer ? pageTransitionLayer.status === 'current' : true;
|
||||
|
||||
const { keyStats, usageDetails, loadKeyStats, refreshKeyStats } = useProviderStats({
|
||||
enabled: isCurrentLayer,
|
||||
});
|
||||
const usageDetailsBySource = useMemo(
|
||||
() => indexUsageDetailsBySource(usageDetails),
|
||||
[usageDetails]
|
||||
);
|
||||
|
||||
const getErrorMessage = (err: unknown) => {
|
||||
if (err instanceof Error) return err.message;
|
||||
@@ -113,8 +124,12 @@ export function AiProvidersPage() {
|
||||
if (hasMounted.current) return;
|
||||
hasMounted.current = true;
|
||||
loadConfigs();
|
||||
}, [loadConfigs]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isCurrentLayer) return;
|
||||
void loadKeyStats().catch(() => {});
|
||||
}, [loadConfigs, loadKeyStats]);
|
||||
}, [isCurrentLayer, loadKeyStats]);
|
||||
|
||||
useEffect(() => {
|
||||
if (config?.geminiApiKeys) setGeminiKeys(config.geminiApiKeys);
|
||||
@@ -130,7 +145,7 @@ export function AiProvidersPage() {
|
||||
config?.openaiCompatibility,
|
||||
]);
|
||||
|
||||
useHeaderRefresh(refreshKeyStats);
|
||||
useHeaderRefresh(refreshKeyStats, isCurrentLayer);
|
||||
|
||||
const openEditor = useCallback(
|
||||
(path: string) => {
|
||||
@@ -149,7 +164,7 @@ export function AiProvidersPage() {
|
||||
confirmText: t('common.confirm'),
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
await providersApi.deleteGeminiKey(entry.apiKey);
|
||||
await providersApi.deleteGeminiKey(entry.apiKey, entry.baseUrl);
|
||||
const next = geminiKeys.filter((_, idx) => idx !== index);
|
||||
setGeminiKeys(next);
|
||||
updateConfigValue('gemini-api-key', next);
|
||||
@@ -282,14 +297,14 @@ export function AiProvidersPage() {
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
if (type === 'codex') {
|
||||
await providersApi.deleteCodexConfig(entry.apiKey);
|
||||
await providersApi.deleteCodexConfig(entry.apiKey, entry.baseUrl);
|
||||
const next = codexConfigs.filter((_, idx) => idx !== index);
|
||||
setCodexConfigs(next);
|
||||
updateConfigValue('codex-api-key', next);
|
||||
clearCache('codex-api-key');
|
||||
showNotification(t('notification.codex_config_deleted'), 'success');
|
||||
} else {
|
||||
await providersApi.deleteClaudeConfig(entry.apiKey);
|
||||
await providersApi.deleteClaudeConfig(entry.apiKey, entry.baseUrl);
|
||||
const next = claudeConfigs.filter((_, idx) => idx !== index);
|
||||
setClaudeConfigs(next);
|
||||
updateConfigValue('claude-api-key', next);
|
||||
@@ -314,7 +329,7 @@ export function AiProvidersPage() {
|
||||
confirmText: t('common.confirm'),
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
await providersApi.deleteVertexConfig(entry.apiKey);
|
||||
await providersApi.deleteVertexConfig(entry.apiKey, entry.baseUrl);
|
||||
const next = vertexConfigs.filter((_, idx) => idx !== index);
|
||||
setVertexConfigs(next);
|
||||
updateConfigValue('vertex-api-key', next);
|
||||
@@ -362,7 +377,7 @@ export function AiProvidersPage() {
|
||||
<GeminiSection
|
||||
configs={geminiKeys}
|
||||
keyStats={keyStats}
|
||||
usageDetails={usageDetails}
|
||||
usageDetailsBySource={usageDetailsBySource}
|
||||
loading={loading}
|
||||
disableControls={disableControls}
|
||||
isSwitching={isSwitching}
|
||||
@@ -377,7 +392,7 @@ export function AiProvidersPage() {
|
||||
<CodexSection
|
||||
configs={codexConfigs}
|
||||
keyStats={keyStats}
|
||||
usageDetails={usageDetails}
|
||||
usageDetailsBySource={usageDetailsBySource}
|
||||
loading={loading}
|
||||
disableControls={disableControls}
|
||||
isSwitching={isSwitching}
|
||||
@@ -392,7 +407,7 @@ export function AiProvidersPage() {
|
||||
<ClaudeSection
|
||||
configs={claudeConfigs}
|
||||
keyStats={keyStats}
|
||||
usageDetails={usageDetails}
|
||||
usageDetailsBySource={usageDetailsBySource}
|
||||
loading={loading}
|
||||
disableControls={disableControls}
|
||||
isSwitching={isSwitching}
|
||||
@@ -407,7 +422,7 @@ export function AiProvidersPage() {
|
||||
<VertexSection
|
||||
configs={vertexConfigs}
|
||||
keyStats={keyStats}
|
||||
usageDetails={usageDetails}
|
||||
usageDetailsBySource={usageDetailsBySource}
|
||||
loading={loading}
|
||||
disableControls={disableControls}
|
||||
isSwitching={isSwitching}
|
||||
@@ -432,7 +447,7 @@ export function AiProvidersPage() {
|
||||
<OpenAISection
|
||||
configs={openaiProviders}
|
||||
keyStats={keyStats}
|
||||
usageDetails={usageDetails}
|
||||
usageDetailsBySource={usageDetailsBySource}
|
||||
loading={loading}
|
||||
disableControls={disableControls}
|
||||
isSwitching={isSwitching}
|
||||
|
||||
@@ -15,6 +15,7 @@ import { useAuthStore, useConfigStore, useNotificationStore } from '@/stores';
|
||||
import type { ProviderKeyConfig } from '@/types';
|
||||
import { excludedModelsToText, parseExcludedModels } from '@/components/providers/utils';
|
||||
import { buildHeaderObject, headersToEntries, normalizeHeaderEntries } from '@/utils/headers';
|
||||
import { areKeyValueEntriesEqual, areModelEntriesEqual, areStringArraysEqual } from '@/utils/compare';
|
||||
import type { VertexFormState } from '@/components/providers';
|
||||
import layoutStyles from './AiProvidersEditLayout.module.scss';
|
||||
|
||||
@@ -47,18 +48,28 @@ const normalizeModelEntries = (entries: Array<{ name: string; alias: string }>)
|
||||
return acc;
|
||||
}, []);
|
||||
|
||||
const buildVertexSignature = (form: VertexFormState) =>
|
||||
JSON.stringify({
|
||||
apiKey: String(form.apiKey ?? '').trim(),
|
||||
priority:
|
||||
form.priority !== undefined && Number.isFinite(form.priority) ? Math.trunc(form.priority) : null,
|
||||
prefix: String(form.prefix ?? '').trim(),
|
||||
baseUrl: String(form.baseUrl ?? '').trim(),
|
||||
proxyUrl: String(form.proxyUrl ?? '').trim(),
|
||||
headers: normalizeHeaderEntries(form.headers),
|
||||
models: normalizeModelEntries(form.modelEntries),
|
||||
excludedModels: parseExcludedModels(form.excludedText ?? ''),
|
||||
});
|
||||
type VertexFormBaseline = {
|
||||
apiKey: string;
|
||||
priority: number | null;
|
||||
prefix: string;
|
||||
baseUrl: string;
|
||||
proxyUrl: string;
|
||||
headers: ReturnType<typeof normalizeHeaderEntries>;
|
||||
models: ReturnType<typeof normalizeModelEntries>;
|
||||
excludedModels: string[];
|
||||
};
|
||||
|
||||
const buildVertexBaseline = (form: VertexFormState): VertexFormBaseline => ({
|
||||
apiKey: String(form.apiKey ?? '').trim(),
|
||||
priority:
|
||||
form.priority !== undefined && Number.isFinite(form.priority) ? Math.trunc(form.priority) : null,
|
||||
prefix: String(form.prefix ?? '').trim(),
|
||||
baseUrl: String(form.baseUrl ?? '').trim(),
|
||||
proxyUrl: String(form.proxyUrl ?? '').trim(),
|
||||
headers: normalizeHeaderEntries(form.headers),
|
||||
models: normalizeModelEntries(form.modelEntries),
|
||||
excludedModels: parseExcludedModels(form.excludedText ?? ''),
|
||||
});
|
||||
|
||||
export function AiProvidersVertexEditPage() {
|
||||
const { t } = useTranslation();
|
||||
@@ -79,7 +90,7 @@ export function AiProvidersVertexEditPage() {
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [form, setForm] = useState<VertexFormState>(() => buildEmptyForm());
|
||||
const [baselineSignature, setBaselineSignature] = useState(() => buildVertexSignature(buildEmptyForm()));
|
||||
const [baseline, setBaseline] = useState(() => buildVertexBaseline(buildEmptyForm()));
|
||||
|
||||
const hasIndexParam = typeof params.index === 'string';
|
||||
const editIndex = useMemo(() => parseIndexParam(params.index), [params.index]);
|
||||
@@ -160,18 +171,51 @@ export function AiProvidersVertexEditPage() {
|
||||
excludedText: excludedModelsToText(initialData.excludedModels),
|
||||
};
|
||||
setForm(nextForm);
|
||||
setBaselineSignature(buildVertexSignature(nextForm));
|
||||
setBaseline(buildVertexBaseline(nextForm));
|
||||
return;
|
||||
}
|
||||
const nextForm = buildEmptyForm();
|
||||
setForm(nextForm);
|
||||
setBaselineSignature(buildVertexSignature(nextForm));
|
||||
setBaseline(buildVertexBaseline(nextForm));
|
||||
}, [initialData, loading]);
|
||||
|
||||
const canSave = !disableControls && !saving && !loading && !invalidIndexParam && !invalidIndex;
|
||||
|
||||
const currentSignature = useMemo(() => buildVertexSignature(form), [form]);
|
||||
const isDirty = baselineSignature !== currentSignature;
|
||||
const normalizedHeaders = useMemo(() => normalizeHeaderEntries(form.headers), [form.headers]);
|
||||
const normalizedModels = useMemo(
|
||||
() => normalizeModelEntries(form.modelEntries),
|
||||
[form.modelEntries]
|
||||
);
|
||||
const normalizedExcludedModels = useMemo(
|
||||
() => parseExcludedModels(form.excludedText ?? ''),
|
||||
[form.excludedText]
|
||||
);
|
||||
const normalizedPriority = useMemo(() => {
|
||||
return form.priority !== undefined && Number.isFinite(form.priority)
|
||||
? Math.trunc(form.priority)
|
||||
: null;
|
||||
}, [form.priority]);
|
||||
const isHeadersDirty = useMemo(
|
||||
() => !areKeyValueEntriesEqual(baseline.headers, normalizedHeaders),
|
||||
[baseline.headers, normalizedHeaders]
|
||||
);
|
||||
const isModelsDirty = useMemo(
|
||||
() => !areModelEntriesEqual(baseline.models, normalizedModels),
|
||||
[baseline.models, normalizedModels]
|
||||
);
|
||||
const isExcludedModelsDirty = useMemo(
|
||||
() => !areStringArraysEqual(baseline.excludedModels, normalizedExcludedModels),
|
||||
[baseline.excludedModels, normalizedExcludedModels]
|
||||
);
|
||||
const isDirty =
|
||||
baseline.apiKey !== form.apiKey.trim() ||
|
||||
baseline.priority !== normalizedPriority ||
|
||||
baseline.prefix !== String(form.prefix ?? '').trim() ||
|
||||
baseline.baseUrl !== String(form.baseUrl ?? '').trim() ||
|
||||
baseline.proxyUrl !== String(form.proxyUrl ?? '').trim() ||
|
||||
isHeadersDirty ||
|
||||
isModelsDirty ||
|
||||
isExcludedModelsDirty;
|
||||
const canGuard = !loading && !saving && !invalidIndexParam && !invalidIndex;
|
||||
|
||||
const { allowNextNavigation } = useUnsavedChangesGuard({
|
||||
@@ -230,7 +274,7 @@ export function AiProvidersVertexEditPage() {
|
||||
'success'
|
||||
);
|
||||
allowNextNavigation();
|
||||
setBaselineSignature(buildVertexSignature(form));
|
||||
setBaseline(buildVertexBaseline(form));
|
||||
handleBack();
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : '';
|
||||
|
||||
@@ -541,7 +541,7 @@
|
||||
}
|
||||
|
||||
.quotaBarFillMedium {
|
||||
background-color: var(--warning-color);
|
||||
background-color: var(--quota-medium-color, #e0aa14);
|
||||
}
|
||||
|
||||
.quotaBarFillLow {
|
||||
@@ -659,8 +659,9 @@
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
background-color: color-mix(in srgb, var(--bg-primary) 85%, transparent);
|
||||
backdrop-filter: blur(8px);
|
||||
-webkit-backdrop-filter: blur(8px);
|
||||
--glass-blur: 8px;
|
||||
backdrop-filter: var(--glass-backdrop-filter);
|
||||
-webkit-backdrop-filter: var(--glass-backdrop-filter);
|
||||
border: 1px solid color-mix(in srgb, var(--border-color) 70%, transparent);
|
||||
border-radius: 12px;
|
||||
padding: 16px;
|
||||
@@ -1383,6 +1384,11 @@
|
||||
}
|
||||
}
|
||||
|
||||
.prefixProxyTextareaInvalid {
|
||||
border-color: var(--danger-color);
|
||||
box-shadow: 0 0 0 3px rgba($error-color, 0.12);
|
||||
}
|
||||
|
||||
.cardActions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -1529,8 +1535,9 @@
|
||||
border-radius: $radius-lg;
|
||||
border: 1px solid color-mix(in srgb, var(--border-color) 70%, transparent);
|
||||
background: color-mix(in srgb, var(--bg-primary) 84%, transparent);
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
--glass-blur: 12px;
|
||||
backdrop-filter: var(--glass-backdrop-filter);
|
||||
-webkit-backdrop-filter: var(--glass-backdrop-filter);
|
||||
box-shadow: var(--shadow-lg);
|
||||
}
|
||||
|
||||
|
||||
+22
-79
@@ -24,7 +24,6 @@ import { IconFilterAll } from '@/components/ui/icons';
|
||||
import { EmptyState } from '@/components/ui/EmptyState';
|
||||
import { ToggleSwitch } from '@/components/ui/ToggleSwitch';
|
||||
import { copyToClipboard } from '@/utils/clipboard';
|
||||
import { isLikelyUnsafeJsRegex } from '@/utils/regexSafety';
|
||||
import {
|
||||
MAX_CARD_PAGE_SIZE,
|
||||
MIN_CARD_PAGE_SIZE,
|
||||
@@ -68,7 +67,15 @@ const BATCH_BAR_BASE_TRANSFORM = 'translateX(-50%)';
|
||||
const BATCH_BAR_HIDDEN_TRANSFORM = 'translateX(-50%) translateY(56px)';
|
||||
const DEFAULT_REGULAR_PAGE_SIZE = 9;
|
||||
const DEFAULT_COMPACT_PAGE_SIZE = 12;
|
||||
const MAX_REGEX_SEARCH_PATTERN_LENGTH = 120;
|
||||
|
||||
const escapeWildcardSearchSegment = (value: string) =>
|
||||
value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
|
||||
const buildWildcardSearch = (value: string): RegExp | null => {
|
||||
if (!value.includes('*')) return null;
|
||||
const pattern = value.split('*').map(escapeWildcardSearchSegment).join('.*');
|
||||
return new RegExp(pattern, 'i');
|
||||
};
|
||||
|
||||
export function AuthFilesPage() {
|
||||
const { t } = useTranslation();
|
||||
@@ -83,7 +90,6 @@ export function AuthFilesPage() {
|
||||
const [problemOnly, setProblemOnly] = useState(false);
|
||||
const [compactMode, setCompactMode] = useState(false);
|
||||
const [search, setSearch] = useState('');
|
||||
const [regexSearchMode, setRegexSearchMode] = useState(false);
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSizeByMode, setPageSizeByMode] = useState({
|
||||
regular: DEFAULT_REGULAR_PAGE_SIZE,
|
||||
@@ -204,9 +210,6 @@ export function AuthFilesPage() {
|
||||
if (typeof persisted.search === 'string') {
|
||||
setSearch(persisted.search);
|
||||
}
|
||||
if (typeof persisted.regexSearchMode === 'boolean') {
|
||||
setRegexSearchMode(persisted.regexSearchMode);
|
||||
}
|
||||
if (typeof persisted.page === 'number' && Number.isFinite(persisted.page)) {
|
||||
setPage(Math.max(1, Math.round(persisted.page)));
|
||||
}
|
||||
@@ -242,7 +245,6 @@ export function AuthFilesPage() {
|
||||
problemOnly,
|
||||
compactMode,
|
||||
search,
|
||||
regexSearchMode,
|
||||
page,
|
||||
pageSize,
|
||||
regularPageSize: pageSizeByMode.regular,
|
||||
@@ -257,7 +259,6 @@ export function AuthFilesPage() {
|
||||
pageSize,
|
||||
pageSizeByMode,
|
||||
problemOnly,
|
||||
regexSearchMode,
|
||||
search,
|
||||
sortMode,
|
||||
uiStateHydrated,
|
||||
@@ -377,62 +378,24 @@ export function AuthFilesPage() {
|
||||
}, [filesMatchingProblemFilter]);
|
||||
|
||||
const normalizedSearch = search.trim();
|
||||
const { regexSearch, regexSearchErrorKey } = useMemo(() => {
|
||||
if (!regexSearchMode || !normalizedSearch) {
|
||||
return { regexSearch: null as RegExp | null, regexSearchErrorKey: undefined as string | undefined };
|
||||
}
|
||||
|
||||
if (normalizedSearch.length > MAX_REGEX_SEARCH_PATTERN_LENGTH) {
|
||||
return {
|
||||
regexSearch: null,
|
||||
regexSearchErrorKey: 'auth_files.search_regex_invalid',
|
||||
};
|
||||
}
|
||||
|
||||
if (isLikelyUnsafeJsRegex(normalizedSearch)) {
|
||||
return {
|
||||
regexSearch: null,
|
||||
regexSearchErrorKey: 'auth_files.search_regex_unsafe',
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
return { regexSearch: new RegExp(normalizedSearch, 'i'), regexSearchErrorKey: undefined };
|
||||
} catch {
|
||||
return {
|
||||
regexSearch: null,
|
||||
regexSearchErrorKey: 'auth_files.search_regex_invalid',
|
||||
};
|
||||
}
|
||||
}, [normalizedSearch, regexSearchMode]);
|
||||
|
||||
const searchError = regexSearchErrorKey
|
||||
? t(regexSearchErrorKey, { max: MAX_REGEX_SEARCH_PATTERN_LENGTH })
|
||||
: undefined;
|
||||
const wildcardSearch = useMemo(() => buildWildcardSearch(normalizedSearch), [normalizedSearch]);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const normalizedTerm = normalizedSearch.toLowerCase();
|
||||
|
||||
return filesMatchingProblemFilter.filter((item) => {
|
||||
const matchType = filter === 'all' || item.type === filter;
|
||||
const matchSearch = (() => {
|
||||
if (!normalizedSearch) return true;
|
||||
if (!regexSearchMode) {
|
||||
const term = normalizedSearch.toLowerCase();
|
||||
return (
|
||||
item.name.toLowerCase().includes(term) ||
|
||||
(item.type || '').toString().toLowerCase().includes(term) ||
|
||||
(item.provider || '').toString().toLowerCase().includes(term)
|
||||
);
|
||||
}
|
||||
|
||||
if (!regexSearch) return false;
|
||||
|
||||
return [item.name, item.type, item.provider].some((value) =>
|
||||
regexSearch.test((value || '').toString())
|
||||
);
|
||||
})();
|
||||
const matchSearch =
|
||||
!normalizedSearch ||
|
||||
[item.name, item.type, item.provider].some((value) => {
|
||||
const content = (value || '').toString();
|
||||
return wildcardSearch
|
||||
? wildcardSearch.test(content)
|
||||
: content.toLowerCase().includes(normalizedTerm);
|
||||
});
|
||||
return matchType && matchSearch;
|
||||
});
|
||||
}, [filesMatchingProblemFilter, filter, normalizedSearch, regexSearch, regexSearchMode]);
|
||||
}, [filesMatchingProblemFilter, filter, normalizedSearch, wildcardSearch]);
|
||||
|
||||
const sorted = useMemo(() => {
|
||||
const copy = [...filtered];
|
||||
@@ -744,12 +707,7 @@ export function AuthFilesPage() {
|
||||
setSearch(e.target.value);
|
||||
setPage(1);
|
||||
}}
|
||||
placeholder={
|
||||
regexSearchMode
|
||||
? t('auth_files.search_regex_placeholder')
|
||||
: t('auth_files.search_placeholder')
|
||||
}
|
||||
error={searchError}
|
||||
placeholder={t('auth_files.search_placeholder')}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.filterItem}>
|
||||
@@ -811,21 +769,6 @@ export function AuthFilesPage() {
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className={styles.filterToggleCard}>
|
||||
<ToggleSwitch
|
||||
checked={regexSearchMode}
|
||||
onChange={(value) => {
|
||||
setRegexSearchMode(value);
|
||||
setPage(1);
|
||||
}}
|
||||
ariaLabel={t('auth_files.regex_search_mode_label')}
|
||||
label={
|
||||
<span className={styles.filterToggleLabel}>
|
||||
{t('auth_files.regex_search_mode_label')}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -422,10 +422,11 @@
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 10px;
|
||||
background: color-mix(in srgb, var(--bg-primary) 82%, transparent);
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
border: 1px solid color-mix(in srgb, var(--border-color) 60%, transparent);
|
||||
--glass-blur: 12px;
|
||||
background: var(--glass-bg);
|
||||
backdrop-filter: var(--glass-backdrop-filter);
|
||||
-webkit-backdrop-filter: var(--glass-backdrop-filter);
|
||||
border: 1px solid var(--glass-border);
|
||||
border-radius: 999px;
|
||||
box-shadow: var(--shadow-lg);
|
||||
max-width: inherit;
|
||||
|
||||
+16
-44
@@ -1,10 +1,7 @@
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Suspense, lazy, useCallback, useEffect, useLayoutEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { createPortal } from 'react-dom';
|
||||
import CodeMirror, { ReactCodeMirrorRef } from '@uiw/react-codemirror';
|
||||
import { yaml } from '@codemirror/lang-yaml';
|
||||
import { search, searchKeymap, highlightSelectionMatches } from '@codemirror/search';
|
||||
import { keymap } from '@codemirror/view';
|
||||
import type { ReactCodeMirrorRef } from '@uiw/react-codemirror';
|
||||
import { parse as parseYaml, parseDocument } from 'yaml';
|
||||
import { usePageTransitionLayer } from '@/components/common/PageTransitionLayer';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
@@ -26,6 +23,8 @@ import styles from './ConfigPage.module.scss';
|
||||
|
||||
type ConfigEditorTab = 'visual' | 'source';
|
||||
|
||||
const LazyConfigSourceEditor = lazy(() => import('@/components/config/ConfigSourceEditor'));
|
||||
|
||||
function readCommercialModeFromYaml(yamlContent: string): boolean {
|
||||
try {
|
||||
const parsed = parseYaml(yamlContent);
|
||||
@@ -39,7 +38,7 @@ function readCommercialModeFromYaml(yamlContent: string): boolean {
|
||||
export function ConfigPage() {
|
||||
const { t } = useTranslation();
|
||||
const pageTransitionLayer = usePageTransitionLayer();
|
||||
const isCurrentLayer = pageTransitionLayer ? pageTransitionLayer.status === 'current' : true;
|
||||
const isCurrentLayer = pageTransitionLayer ? pageTransitionLayer.isCurrentLayer : true;
|
||||
const showNotification = useNotificationStore((state) => state.showNotification);
|
||||
const showConfirmation = useNotificationStore((state) => state.showConfirmation);
|
||||
const connectionStatus = useAuthStore((state) => state.connectionStatus);
|
||||
@@ -79,7 +78,7 @@ export function ConfigPage() {
|
||||
total: 0,
|
||||
});
|
||||
const [lastSearchedQuery, setLastSearchedQuery] = useState('');
|
||||
const editorRef = useRef<ReactCodeMirrorRef>(null);
|
||||
const editorRef = useRef<ReactCodeMirrorRef | null>(null);
|
||||
const floatingActionsRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const disableControls = connectionStatus !== 'connected';
|
||||
@@ -405,12 +404,6 @@ export function ConfigPage() {
|
||||
};
|
||||
}, [shouldRenderFloatingActions]);
|
||||
|
||||
// CodeMirror extensions
|
||||
const extensions = useMemo(
|
||||
() => [yaml(), search(), highlightSelectionMatches(), keymap.of(searchKeymap)],
|
||||
[]
|
||||
);
|
||||
|
||||
// Status text
|
||||
const getStatusText = () => {
|
||||
if (disableControls) return t('config_management.status_disconnected');
|
||||
@@ -630,37 +623,16 @@ export function ConfigPage() {
|
||||
</div>
|
||||
|
||||
<div className={styles.editorWrapper}>
|
||||
<CodeMirror
|
||||
ref={editorRef}
|
||||
value={content}
|
||||
onChange={handleChange}
|
||||
extensions={extensions}
|
||||
theme={resolvedTheme}
|
||||
editable={!disableControls && !loading}
|
||||
placeholder={t('config_management.editor_placeholder')}
|
||||
height="100%"
|
||||
style={{ height: '100%' }}
|
||||
basicSetup={{
|
||||
lineNumbers: true,
|
||||
highlightActiveLineGutter: true,
|
||||
highlightActiveLine: true,
|
||||
foldGutter: true,
|
||||
dropCursor: true,
|
||||
allowMultipleSelections: true,
|
||||
indentOnInput: true,
|
||||
bracketMatching: true,
|
||||
closeBrackets: true,
|
||||
autocompletion: false,
|
||||
rectangularSelection: true,
|
||||
crosshairCursor: false,
|
||||
highlightSelectionMatches: true,
|
||||
closeBracketsKeymap: true,
|
||||
searchKeymap: true,
|
||||
foldKeymap: true,
|
||||
completionKeymap: false,
|
||||
lintKeymap: true,
|
||||
}}
|
||||
/>
|
||||
<Suspense fallback={null}>
|
||||
<LazyConfigSourceEditor
|
||||
editorRef={editorRef}
|
||||
value={content}
|
||||
onChange={handleChange}
|
||||
theme={resolvedTheme}
|
||||
editable={!disableControls && !loading}
|
||||
placeholder={t('config_management.editor_placeholder')}
|
||||
/>
|
||||
</Suspense>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
+366
-173
@@ -1,59 +1,236 @@
|
||||
@use 'sass:color';
|
||||
@use '../styles/variables.scss' as *;
|
||||
|
||||
// ─── Container ──────────────────────────────────────────
|
||||
|
||||
.dashboard {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: $spacing-lg;
|
||||
gap: $spacing-xl;
|
||||
max-width: 1000px;
|
||||
margin: 0 auto;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.header {
|
||||
margin-bottom: $spacing-sm;
|
||||
// ─── Decorative Background Orbs ─────────────────────────
|
||||
|
||||
.backgroundOrbs {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
z-index: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.title {
|
||||
font-size: 26px;
|
||||
font-weight: 800;
|
||||
.orb1 {
|
||||
position: absolute;
|
||||
width: 420px;
|
||||
height: 420px;
|
||||
border-radius: 50%;
|
||||
background: radial-gradient(
|
||||
circle,
|
||||
color-mix(in srgb, var(--primary-color) 8%, transparent),
|
||||
transparent 70%
|
||||
);
|
||||
top: -140px;
|
||||
right: -80px;
|
||||
animation: orbFloat 22s ease-in-out infinite alternate;
|
||||
}
|
||||
|
||||
.orb2 {
|
||||
position: absolute;
|
||||
width: 320px;
|
||||
height: 320px;
|
||||
border-radius: 50%;
|
||||
background: radial-gradient(
|
||||
circle,
|
||||
color-mix(in srgb, var(--success-color) 6%, transparent),
|
||||
transparent 70%
|
||||
);
|
||||
bottom: 18%;
|
||||
left: -100px;
|
||||
animation: orbFloat 28s ease-in-out infinite alternate-reverse;
|
||||
}
|
||||
|
||||
@keyframes orbFloat {
|
||||
0% {
|
||||
transform: translate(0, 0) scale(1);
|
||||
}
|
||||
100% {
|
||||
transform: translate(30px, -20px) scale(1.1);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Hero Welcome Section ───────────────────────────────
|
||||
|
||||
.hero {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: flex;
|
||||
align-items: flex-end;
|
||||
justify-content: space-between;
|
||||
gap: $spacing-lg;
|
||||
padding: $spacing-2xl $spacing-xl;
|
||||
border-radius: $radius-lg;
|
||||
--glass-blur: 12px;
|
||||
background: linear-gradient(
|
||||
135deg,
|
||||
color-mix(in srgb, var(--bg-primary) 92%, transparent),
|
||||
color-mix(in srgb, var(--bg-secondary) 80%, transparent)
|
||||
);
|
||||
border: 1px solid color-mix(in srgb, var(--border-color) 60%, transparent);
|
||||
backdrop-filter: var(--glass-backdrop-filter);
|
||||
-webkit-backdrop-filter: var(--glass-backdrop-filter);
|
||||
overflow: hidden;
|
||||
animation: heroEnter 0.6s ease-out both;
|
||||
|
||||
@media (max-width: $breakpoint-mobile) {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
padding: $spacing-xl $spacing-lg;
|
||||
}
|
||||
}
|
||||
|
||||
// Large watermark text behind hero content
|
||||
.heroWatermark {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: $spacing-xl;
|
||||
transform: translateY(-50%);
|
||||
font-size: clamp(64px, 12vw, 120px);
|
||||
font-weight: 900;
|
||||
line-height: 1;
|
||||
letter-spacing: -0.04em;
|
||||
text-transform: uppercase;
|
||||
color: var(--text-primary);
|
||||
margin: 0;
|
||||
line-height: 1.4;
|
||||
opacity: 0.04;
|
||||
white-space: nowrap;
|
||||
pointer-events: none;
|
||||
user-select: none;
|
||||
animation: watermarkEnter 0.8s ease-out 0.1s both;
|
||||
|
||||
@media (max-width: $breakpoint-mobile) {
|
||||
font-size: clamp(48px, 14vw, 80px);
|
||||
left: $spacing-lg;
|
||||
}
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
@keyframes watermarkEnter {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(-50%) translateX(-20px);
|
||||
}
|
||||
to {
|
||||
opacity: 0.04;
|
||||
transform: translateY(-50%) translateX(0);
|
||||
}
|
||||
}
|
||||
|
||||
.heroContent {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: $spacing-xs;
|
||||
}
|
||||
|
||||
.heroGreeting {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--primary-color);
|
||||
animation: fadeSlideUp 0.5s ease-out 0.1s both;
|
||||
}
|
||||
|
||||
.heroTitle {
|
||||
margin: 0;
|
||||
font-size: clamp(32px, 5vw, 48px);
|
||||
font-weight: 800;
|
||||
line-height: 1.1;
|
||||
letter-spacing: -0.03em;
|
||||
color: var(--text-primary);
|
||||
animation: fadeSlideUp 0.5s ease-out 0.2s both;
|
||||
}
|
||||
|
||||
.heroCaring {
|
||||
margin: $spacing-xs 0 0;
|
||||
font-size: 15px;
|
||||
color: var(--text-secondary);
|
||||
margin: $spacing-xs 0 0 0;
|
||||
line-height: 1.5;
|
||||
animation: fadeSlideUp 0.5s ease-out 0.3s both;
|
||||
}
|
||||
|
||||
.connectionCard {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: $spacing-md;
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: $radius-lg;
|
||||
padding: $spacing-md $spacing-lg;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
// ─── Hero Meta (right side) ─────────────────────────────
|
||||
|
||||
.connectionStatus {
|
||||
.heroMeta {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: $spacing-sm;
|
||||
flex-shrink: 0;
|
||||
animation: fadeSlideUp 0.5s ease-out 0.35s both;
|
||||
|
||||
@media (max-width: $breakpoint-mobile) {
|
||||
align-items: flex-start;
|
||||
flex-direction: row;
|
||||
flex-wrap: wrap;
|
||||
gap: $spacing-sm;
|
||||
}
|
||||
}
|
||||
|
||||
.dateTimeBlock {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 2px;
|
||||
|
||||
@media (max-width: $breakpoint-mobile) {
|
||||
align-items: flex-start;
|
||||
}
|
||||
}
|
||||
|
||||
.time {
|
||||
font-size: 22px;
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.date {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
// ─── Connection Pill ────────────────────────────────────
|
||||
|
||||
.connectionPill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 5px 12px;
|
||||
border-radius: $radius-full;
|
||||
--glass-blur: 8px;
|
||||
background: var(--glass-bg-secondary);
|
||||
border: 1px solid var(--glass-border);
|
||||
backdrop-filter: var(--glass-backdrop-filter);
|
||||
-webkit-backdrop-filter: var(--glass-backdrop-filter);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.statusDot {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: $gray-400;
|
||||
flex-shrink: 0;
|
||||
|
||||
&.connected {
|
||||
background: $success-color;
|
||||
box-shadow: 0 0 8px rgba($success-color, 0.5);
|
||||
box-shadow: 0 0 6px rgba($success-color, 0.5);
|
||||
}
|
||||
|
||||
&.connecting {
|
||||
@@ -66,54 +243,41 @@
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0%, 100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
.statusText {
|
||||
.pillText {
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.connectionInfo {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: $spacing-md;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.serverUrl {
|
||||
font-family: $font-mono;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
background: var(--bg-primary);
|
||||
padding: 4px 10px;
|
||||
border-radius: $radius-md;
|
||||
border: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.serverVersion {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--primary-color);
|
||||
background: rgba($primary-color, 0.1);
|
||||
padding: 4px 10px;
|
||||
border-radius: $radius-full;
|
||||
}
|
||||
|
||||
.buildDate {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 11px;
|
||||
color: var(--text-tertiary);
|
||||
text-align: right;
|
||||
|
||||
@media (max-width: $breakpoint-mobile) {
|
||||
text-align: left;
|
||||
}
|
||||
}
|
||||
|
||||
.statsGrid {
|
||||
// ─── Bento Stats Grid ───────────────────────────────────
|
||||
|
||||
.statsSection {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.sectionHeading {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
color: var(--text-tertiary);
|
||||
margin: 0 0 $spacing-md;
|
||||
}
|
||||
|
||||
.bentoGrid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, 1fr);
|
||||
grid-template-columns: repeat(3, 1fr);
|
||||
grid-template-rows: auto auto;
|
||||
gap: $spacing-md;
|
||||
|
||||
@media (max-width: 900px) {
|
||||
@@ -125,150 +289,175 @@
|
||||
}
|
||||
}
|
||||
|
||||
.statCard {
|
||||
.bentoCard {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-direction: column;
|
||||
gap: $spacing-md;
|
||||
padding: $spacing-lg;
|
||||
background: var(--bg-primary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: $radius-lg;
|
||||
text-decoration: none;
|
||||
transition: all $transition-fast;
|
||||
transition:
|
||||
border-color $transition-fast,
|
||||
box-shadow $transition-fast,
|
||||
transform $transition-fast;
|
||||
animation: cardEnter 0.4s ease-out both;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--primary-color);
|
||||
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
|
||||
transform: translateY(-2px);
|
||||
box-shadow: 0 8px 24px rgba(0, 0, 0, 0.08);
|
||||
transform: translateY(-3px);
|
||||
}
|
||||
}
|
||||
|
||||
.statIcon {
|
||||
// First card spans 2 rows — the "hero stat"
|
||||
.bentoLarge {
|
||||
grid-row: 1 / 3;
|
||||
justify-content: center;
|
||||
background: linear-gradient(
|
||||
160deg,
|
||||
color-mix(in srgb, var(--primary-color) 6%, var(--bg-primary)),
|
||||
var(--bg-primary)
|
||||
);
|
||||
|
||||
.bentoValue {
|
||||
font-size: 44px;
|
||||
}
|
||||
|
||||
.bentoIcon {
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
grid-row: auto;
|
||||
|
||||
.bentoValue {
|
||||
font-size: 32px;
|
||||
}
|
||||
|
||||
.bentoIcon {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.bentoIcon {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
border-radius: $radius-md;
|
||||
background: var(--bg-secondary);
|
||||
background: color-mix(in srgb, var(--primary-color) 10%, var(--bg-secondary));
|
||||
color: var(--primary-color);
|
||||
transition: background $transition-fast;
|
||||
}
|
||||
|
||||
.statContent {
|
||||
.bentoCard:hover .bentoIcon {
|
||||
background: color-mix(in srgb, var(--primary-color) 16%, var(--bg-secondary));
|
||||
}
|
||||
|
||||
.bentoContent {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.statValue {
|
||||
font-size: 24px;
|
||||
.bentoValue {
|
||||
font-size: 28px;
|
||||
font-weight: 800;
|
||||
color: var(--text-primary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
line-height: 1.2;
|
||||
}
|
||||
|
||||
.statLabel {
|
||||
.bentoLabel {
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.statSublabel {
|
||||
.bentoSublabel {
|
||||
font-size: 11px;
|
||||
color: var(--text-secondary);
|
||||
opacity: 0.8;
|
||||
opacity: 0.7;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.section {
|
||||
// ─── Config Pills Section ───────────────────────────────
|
||||
|
||||
.configSection {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: $spacing-md;
|
||||
animation: cardEnter 0.4s ease-out 0.5s both;
|
||||
}
|
||||
|
||||
.sectionTitle {
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.actionsGrid {
|
||||
.configPillGrid {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: $spacing-sm;
|
||||
|
||||
a {
|
||||
text-decoration: none;
|
||||
}
|
||||
}
|
||||
|
||||
.actionButton {
|
||||
.configPill {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: $spacing-sm;
|
||||
|
||||
// Button 内部的 span 需要 flex 对齐图标和文字
|
||||
> span {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: $spacing-sm;
|
||||
}
|
||||
|
||||
svg {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.configGrid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||
gap: $spacing-sm;
|
||||
}
|
||||
|
||||
.configItem {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: $spacing-sm;
|
||||
padding: $spacing-sm $spacing-md;
|
||||
padding: 6px 14px;
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: $radius-full;
|
||||
font-size: 13px;
|
||||
transition: border-color $transition-fast;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--border-hover);
|
||||
}
|
||||
}
|
||||
|
||||
.configPillWide {
|
||||
flex-basis: 100%;
|
||||
border-radius: $radius-md;
|
||||
}
|
||||
|
||||
.configLabel {
|
||||
font-size: 13px;
|
||||
.configPillLabel {
|
||||
color: var(--text-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.configValue {
|
||||
font-size: 13px;
|
||||
.configPillValue {
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
|
||||
&.enabled {
|
||||
&.on {
|
||||
color: $success-color;
|
||||
}
|
||||
|
||||
&.disabled {
|
||||
&.off {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
}
|
||||
|
||||
.configValueMono {
|
||||
.configPillMono {
|
||||
font-size: 12px;
|
||||
font-family: $font-mono;
|
||||
color: var(--text-secondary);
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
// Config badges (routing strategy)
|
||||
.configBadge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 4px 10px;
|
||||
padding: 2px 8px;
|
||||
border-radius: $radius-full;
|
||||
border: 1px solid var(--border-color);
|
||||
font-size: 12px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
line-height: 1.2;
|
||||
max-width: 100%;
|
||||
@@ -294,50 +483,7 @@
|
||||
background: var(--bg-primary);
|
||||
}
|
||||
|
||||
.configItemFull {
|
||||
grid-column: 1 / -1;
|
||||
}
|
||||
|
||||
// Usage stats section
|
||||
.usageGrid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
|
||||
gap: $spacing-sm;
|
||||
}
|
||||
|
||||
.usageCard {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: $spacing-md;
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: $radius-md;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.usageValue {
|
||||
font-size: 22px;
|
||||
font-weight: 800;
|
||||
color: var(--primary-color);
|
||||
}
|
||||
|
||||
.usageLabel {
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.usageLoading,
|
||||
.usageEmpty {
|
||||
padding: $spacing-lg;
|
||||
text-align: center;
|
||||
color: var(--text-secondary);
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: $radius-md;
|
||||
}
|
||||
// ─── View More Link ─────────────────────────────────────
|
||||
|
||||
.viewMoreLink {
|
||||
display: inline-flex;
|
||||
@@ -346,8 +492,55 @@
|
||||
color: var(--primary-color);
|
||||
text-decoration: none;
|
||||
margin-top: $spacing-xs;
|
||||
transition: color $transition-fast;
|
||||
|
||||
&:hover {
|
||||
text-decoration: underline;
|
||||
color: var(--primary-hover);
|
||||
}
|
||||
}
|
||||
|
||||
// ─── Animations ─────────────────────────────────────────
|
||||
|
||||
@keyframes heroEnter {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(12px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes fadeSlideUp {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(8px);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes cardEnter {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(16px) scale(0.98);
|
||||
}
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0) scale(1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0%,
|
||||
100% {
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
opacity: 0.5;
|
||||
}
|
||||
}
|
||||
|
||||
+129
-68
@@ -27,6 +27,16 @@ interface ProviderStats {
|
||||
openai: number | null;
|
||||
}
|
||||
|
||||
type TimeOfDay = 'morning' | 'afternoon' | 'evening' | 'night';
|
||||
|
||||
function getTimeOfDay(): TimeOfDay {
|
||||
const hour = new Date().getHours();
|
||||
if (hour >= 5 && hour < 12) return 'morning';
|
||||
if (hour >= 12 && hour < 17) return 'afternoon';
|
||||
if (hour >= 17 && hour < 21) return 'evening';
|
||||
return 'night';
|
||||
}
|
||||
|
||||
export function DashboardPage() {
|
||||
const { t, i18n } = useTranslation();
|
||||
const connectionStatus = useAuthStore((state) => state.connectionStatus);
|
||||
@@ -56,12 +66,25 @@ export function DashboardPage() {
|
||||
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
// Time-of-day state for dynamic greeting
|
||||
const [timeOfDay, setTimeOfDay] = useState<TimeOfDay>(getTimeOfDay);
|
||||
const [currentTime, setCurrentTime] = useState(() => new Date());
|
||||
|
||||
const apiKeysCache = useRef<string[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
apiKeysCache.current = [];
|
||||
}, [apiBase, config?.apiKeys]);
|
||||
|
||||
// Update time every 60 seconds
|
||||
useEffect(() => {
|
||||
const id = setInterval(() => {
|
||||
setTimeOfDay(getTimeOfDay());
|
||||
setCurrentTime(new Date());
|
||||
}, 60_000);
|
||||
return () => clearInterval(id);
|
||||
}, []);
|
||||
|
||||
const normalizeApiKeyList = (input: unknown): string[] => {
|
||||
if (!Array.isArray(input)) return [];
|
||||
const seen = new Set<string>();
|
||||
@@ -237,113 +260,151 @@ export function DashboardPage() {
|
||||
? styles.configBadgeFillFirst
|
||||
: styles.configBadgeUnknown;
|
||||
|
||||
// Derived time-based values
|
||||
const greetingKey = `dashboard.greeting_${timeOfDay}`;
|
||||
const caringKey = `dashboard.caring_${timeOfDay}`;
|
||||
|
||||
const formattedDate = currentTime.toLocaleDateString(i18n.language, {
|
||||
weekday: 'long',
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric'
|
||||
});
|
||||
|
||||
const formattedTime = currentTime.toLocaleTimeString(i18n.language, {
|
||||
hour: '2-digit',
|
||||
minute: '2-digit'
|
||||
});
|
||||
|
||||
return (
|
||||
<div className={styles.dashboard}>
|
||||
<div className={styles.header}>
|
||||
<h1 className={styles.title}>{t('dashboard.title')}</h1>
|
||||
<p className={styles.subtitle}>{t('dashboard.subtitle')}</p>
|
||||
{/* Decorative background orbs */}
|
||||
<div className={styles.backgroundOrbs} aria-hidden="true">
|
||||
<div className={styles.orb1} />
|
||||
<div className={styles.orb2} />
|
||||
</div>
|
||||
|
||||
<div className={styles.connectionCard}>
|
||||
<div className={styles.connectionStatus}>
|
||||
<span
|
||||
className={`${styles.statusDot} ${
|
||||
connectionStatus === 'connected'
|
||||
? styles.connected
|
||||
: connectionStatus === 'connecting'
|
||||
? styles.connecting
|
||||
: styles.disconnected
|
||||
}`}
|
||||
/>
|
||||
<span className={styles.statusText}>
|
||||
{t(
|
||||
connectionStatus === 'connected'
|
||||
? 'common.connected'
|
||||
: connectionStatus === 'connecting'
|
||||
? 'common.connecting'
|
||||
: 'common.disconnected'
|
||||
)}
|
||||
</span>
|
||||
{/* Hero welcome section */}
|
||||
<section className={styles.hero}>
|
||||
<span className={styles.heroWatermark} aria-hidden="true">
|
||||
OVERVIEW
|
||||
</span>
|
||||
<div className={styles.heroContent}>
|
||||
<span className={styles.heroGreeting}>{t(greetingKey)}</span>
|
||||
<h1 className={styles.heroTitle}>{t('dashboard.welcome_back')}</h1>
|
||||
<p className={styles.heroCaring}>{t(caringKey)}</p>
|
||||
</div>
|
||||
<div className={styles.connectionInfo}>
|
||||
<span className={styles.serverUrl}>{apiBase || '-'}</span>
|
||||
{serverVersion && (
|
||||
<span className={styles.serverVersion}>
|
||||
v{serverVersion.trim().replace(/^[vV]+/, '')}
|
||||
<div className={styles.heroMeta}>
|
||||
<div className={styles.dateTimeBlock}>
|
||||
<span className={styles.time}>{formattedTime}</span>
|
||||
<span className={styles.date}>{formattedDate}</span>
|
||||
</div>
|
||||
<div className={styles.connectionPill}>
|
||||
<span
|
||||
className={`${styles.statusDot} ${
|
||||
connectionStatus === 'connected'
|
||||
? styles.connected
|
||||
: connectionStatus === 'connecting'
|
||||
? styles.connecting
|
||||
: styles.disconnected
|
||||
}`}
|
||||
/>
|
||||
<span className={styles.pillText}>
|
||||
{serverVersion
|
||||
? `v${serverVersion.trim().replace(/^[vV]+/, '')}`
|
||||
: t(
|
||||
connectionStatus === 'connected'
|
||||
? 'common.connected'
|
||||
: connectionStatus === 'connecting'
|
||||
? 'common.connecting'
|
||||
: 'common.disconnected'
|
||||
)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{serverBuildDate && (
|
||||
<span className={styles.buildDate}>
|
||||
{new Date(serverBuildDate).toLocaleDateString(i18n.language)}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div className={styles.statsGrid}>
|
||||
{quickStats.map((stat) => (
|
||||
<Link key={stat.path} to={stat.path} className={styles.statCard}>
|
||||
<div className={styles.statIcon}>{stat.icon}</div>
|
||||
<div className={styles.statContent}>
|
||||
<span className={styles.statValue}>{stat.loading ? '...' : stat.value}</span>
|
||||
<span className={styles.statLabel}>{stat.label}</span>
|
||||
{stat.sublabel && !stat.loading && (
|
||||
<span className={styles.statSublabel}>{stat.sublabel}</span>
|
||||
)}
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
{/* Bento stats grid */}
|
||||
<section className={styles.statsSection}>
|
||||
<h2 className={styles.sectionHeading}>{t('dashboard.system_overview')}</h2>
|
||||
<div className={styles.bentoGrid}>
|
||||
{quickStats.map((stat, index) => (
|
||||
<Link
|
||||
key={stat.path}
|
||||
to={stat.path}
|
||||
className={`${styles.bentoCard} ${index === 0 ? styles.bentoLarge : ''}`}
|
||||
style={{ animationDelay: `${index * 80}ms` }}
|
||||
>
|
||||
<div className={styles.bentoIcon}>{stat.icon}</div>
|
||||
<div className={styles.bentoContent}>
|
||||
<span className={styles.bentoValue}>
|
||||
{stat.loading ? '...' : stat.value}
|
||||
</span>
|
||||
<span className={styles.bentoLabel}>{stat.label}</span>
|
||||
{stat.sublabel && !stat.loading && (
|
||||
<span className={styles.bentoSublabel}>{stat.sublabel}</span>
|
||||
)}
|
||||
</div>
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
|
||||
{/* Config pills section */}
|
||||
{config && (
|
||||
<div className={styles.section}>
|
||||
<h2 className={styles.sectionTitle}>{t('dashboard.current_config')}</h2>
|
||||
<div className={styles.configGrid}>
|
||||
<div className={styles.configItem}>
|
||||
<span className={styles.configLabel}>{t('basic_settings.debug_enable')}</span>
|
||||
<span className={`${styles.configValue} ${config.debug ? styles.enabled : styles.disabled}`}>
|
||||
<section className={styles.configSection}>
|
||||
<h2 className={styles.sectionHeading}>{t('dashboard.current_config')}</h2>
|
||||
<div className={styles.configPillGrid}>
|
||||
<div className={styles.configPill}>
|
||||
<span className={styles.configPillLabel}>{t('basic_settings.debug_enable')}</span>
|
||||
<span className={`${styles.configPillValue} ${config.debug ? styles.on : styles.off}`}>
|
||||
{config.debug ? t('common.yes') : t('common.no')}
|
||||
</span>
|
||||
</div>
|
||||
<div className={styles.configItem}>
|
||||
<span className={styles.configLabel}>{t('basic_settings.usage_statistics_enable')}</span>
|
||||
<span className={`${styles.configValue} ${config.usageStatisticsEnabled ? styles.enabled : styles.disabled}`}>
|
||||
<div className={styles.configPill}>
|
||||
<span className={styles.configPillLabel}>{t('basic_settings.usage_statistics_enable')}</span>
|
||||
<span className={`${styles.configPillValue} ${config.usageStatisticsEnabled ? styles.on : styles.off}`}>
|
||||
{config.usageStatisticsEnabled ? t('common.yes') : t('common.no')}
|
||||
</span>
|
||||
</div>
|
||||
<div className={styles.configItem}>
|
||||
<span className={styles.configLabel}>{t('basic_settings.logging_to_file_enable')}</span>
|
||||
<span className={`${styles.configValue} ${config.loggingToFile ? styles.enabled : styles.disabled}`}>
|
||||
<div className={styles.configPill}>
|
||||
<span className={styles.configPillLabel}>{t('basic_settings.logging_to_file_enable')}</span>
|
||||
<span className={`${styles.configPillValue} ${config.loggingToFile ? styles.on : styles.off}`}>
|
||||
{config.loggingToFile ? t('common.yes') : t('common.no')}
|
||||
</span>
|
||||
</div>
|
||||
<div className={styles.configItem}>
|
||||
<span className={styles.configLabel}>{t('basic_settings.retry_count_label')}</span>
|
||||
<span className={styles.configValue}>{config.requestRetry ?? 0}</span>
|
||||
<div className={styles.configPill}>
|
||||
<span className={styles.configPillLabel}>{t('basic_settings.retry_count_label')}</span>
|
||||
<span className={styles.configPillValue}>{config.requestRetry ?? 0}</span>
|
||||
</div>
|
||||
<div className={styles.configItem}>
|
||||
<span className={styles.configLabel}>{t('basic_settings.ws_auth_enable')}</span>
|
||||
<span className={`${styles.configValue} ${config.wsAuth ? styles.enabled : styles.disabled}`}>
|
||||
<div className={styles.configPill}>
|
||||
<span className={styles.configPillLabel}>{t('basic_settings.ws_auth_enable')}</span>
|
||||
<span className={`${styles.configPillValue} ${config.wsAuth ? styles.on : styles.off}`}>
|
||||
{config.wsAuth ? t('common.yes') : t('common.no')}
|
||||
</span>
|
||||
</div>
|
||||
<div className={styles.configItem}>
|
||||
<span className={styles.configLabel}>{t('dashboard.routing_strategy')}</span>
|
||||
<div className={styles.configPill}>
|
||||
<span className={styles.configPillLabel}>{t('dashboard.routing_strategy')}</span>
|
||||
<span className={`${styles.configBadge} ${routingStrategyBadgeClass}`}>
|
||||
{routingStrategyDisplay}
|
||||
</span>
|
||||
</div>
|
||||
{config.proxyUrl && (
|
||||
<div className={`${styles.configItem} ${styles.configItemFull}`}>
|
||||
<span className={styles.configLabel}>{t('basic_settings.proxy_url_label')}</span>
|
||||
<span className={styles.configValueMono}>{config.proxyUrl}</span>
|
||||
<div className={`${styles.configPill} ${styles.configPillWide}`}>
|
||||
<span className={styles.configPillLabel}>{t('basic_settings.proxy_url_label')}</span>
|
||||
<span className={styles.configPillMono}>{config.proxyUrl}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Link to="/config" className={styles.viewMoreLink}>
|
||||
{t('dashboard.edit_settings')} →
|
||||
</Link>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -31,14 +31,22 @@
|
||||
gap: $spacing-sm;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
min-width: 0;
|
||||
|
||||
:global(.btn-sm) {
|
||||
:global(.btn.btn-sm) {
|
||||
line-height: 16px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
:global(svg) {
|
||||
display: block;
|
||||
}
|
||||
|
||||
@include mobile {
|
||||
width: 100%;
|
||||
justify-content: stretch;
|
||||
}
|
||||
}
|
||||
|
||||
.titleWrapper {
|
||||
@@ -146,9 +154,95 @@
|
||||
}
|
||||
|
||||
.viewModeToggle {
|
||||
display: flex;
|
||||
display: inline-flex;
|
||||
gap: $spacing-xs;
|
||||
align-items: center;
|
||||
padding: 3px;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--bg-secondary) 92%, transparent);
|
||||
border: 1px solid color-mix(in srgb, var(--border-color) 88%, transparent);
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.16);
|
||||
|
||||
@include mobile {
|
||||
flex: 1 1 auto;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
.viewModeButton:global(.btn.btn-sm) {
|
||||
padding: 8px 14px;
|
||||
border-radius: 999px;
|
||||
border-color: transparent;
|
||||
background: transparent;
|
||||
color: var(--text-secondary);
|
||||
box-shadow: none;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
border-color: transparent;
|
||||
background: color-mix(in srgb, var(--bg-hover) 72%, transparent);
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
> span {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
@include mobile {
|
||||
flex: 1 1 0;
|
||||
}
|
||||
}
|
||||
|
||||
.viewModeButtonActive:global(.btn.btn-sm) {
|
||||
background: var(--primary-color);
|
||||
border-color: var(--primary-color);
|
||||
color: var(--primary-contrast, #fff);
|
||||
box-shadow: 0 8px 18px -14px rgba(0, 0, 0, 0.45);
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: var(--primary-hover);
|
||||
border-color: var(--primary-hover);
|
||||
color: var(--primary-contrast, #fff);
|
||||
}
|
||||
}
|
||||
|
||||
.refreshAllButton:global(.btn.btn-sm) {
|
||||
padding-inline: 14px;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--primary-color) 12%, var(--bg-secondary));
|
||||
border-color: color-mix(in srgb, var(--primary-color) 22%, var(--border-color));
|
||||
color: var(--text-primary);
|
||||
|
||||
> span {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
background: color-mix(in srgb, var(--primary-color) 16%, var(--bg-secondary));
|
||||
border-color: color-mix(in srgb, var(--primary-color) 34%, var(--border-color));
|
||||
}
|
||||
|
||||
@include mobile {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
|
||||
:global([data-theme='dark']) .viewModeToggle {
|
||||
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.04);
|
||||
}
|
||||
|
||||
:global([data-theme='dark']) .refreshAllButton:global(.btn.btn-sm) {
|
||||
background: color-mix(in srgb, var(--primary-color) 18%, var(--bg-secondary));
|
||||
border-color: color-mix(in srgb, var(--primary-color) 32%, var(--border-color));
|
||||
}
|
||||
|
||||
@include mobile {
|
||||
.headerActions {
|
||||
gap: $spacing-xs;
|
||||
}
|
||||
}
|
||||
|
||||
// 卡片渐变背景 — 基于 TYPE_COLORS light.bg 转 rgba
|
||||
@@ -243,7 +337,7 @@
|
||||
}
|
||||
|
||||
.quotaBarFillMedium {
|
||||
background-color: var(--warning-color);
|
||||
background-color: var(--quota-medium-color, #e0aa14);
|
||||
}
|
||||
|
||||
.quotaBarFillLow {
|
||||
@@ -283,6 +377,24 @@
|
||||
padding: $spacing-sm 0;
|
||||
}
|
||||
|
||||
.quotaMessageAction {
|
||||
width: 100%;
|
||||
border: none;
|
||||
background: none;
|
||||
cursor: pointer;
|
||||
text-decoration: underline;
|
||||
|
||||
&:hover:not(:disabled) {
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
&:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.6;
|
||||
text-decoration: none;
|
||||
}
|
||||
}
|
||||
|
||||
.quotaError {
|
||||
font-size: 12px;
|
||||
color: var(--danger-color);
|
||||
@@ -357,7 +469,8 @@
|
||||
rgba(255, 237, 158, 0.58) 32%,
|
||||
rgba(255, 215, 91, 0) 72%
|
||||
);
|
||||
filter: blur(9px);
|
||||
--glass-blur: 9px;
|
||||
filter: var(--glass-filter);
|
||||
opacity: 0.75;
|
||||
pointer-events: none;
|
||||
z-index: -1;
|
||||
|
||||
@@ -78,9 +78,10 @@
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: color-mix(in srgb, var(--bg-secondary) 78%, transparent);
|
||||
backdrop-filter: blur(6px);
|
||||
-webkit-backdrop-filter: blur(6px);
|
||||
--glass-blur: 6px;
|
||||
background: var(--glass-bg-secondary);
|
||||
backdrop-filter: var(--glass-backdrop-filter);
|
||||
-webkit-backdrop-filter: var(--glass-backdrop-filter);
|
||||
}
|
||||
|
||||
.loadingOverlayContent {
|
||||
@@ -127,8 +128,7 @@
|
||||
padding: 18px;
|
||||
background:
|
||||
radial-gradient(120% 140% at 12% 0%, var(--accent-soft) 0%, rgba(0, 0, 0, 0) 62%),
|
||||
linear-gradient(180deg, rgba(255, 255, 255, 0.06), rgba(255, 255, 255, 0)),
|
||||
var(--bg-primary);
|
||||
linear-gradient(180deg, rgba(255, 255, 255, 0.06), rgba(255, 255, 255, 0)), var(--bg-primary);
|
||||
border-radius: $radius-lg;
|
||||
border: 1px solid var(--border-color);
|
||||
display: flex;
|
||||
@@ -136,7 +136,10 @@
|
||||
gap: 10px;
|
||||
min-height: 176px;
|
||||
box-shadow: var(--shadow-lg);
|
||||
transition: transform $transition-fast, box-shadow $transition-fast, border-color $transition-fast;
|
||||
transition:
|
||||
transform $transition-fast,
|
||||
box-shadow $transition-fast,
|
||||
border-color $transition-fast;
|
||||
overflow: hidden;
|
||||
|
||||
&::before {
|
||||
@@ -349,7 +352,10 @@
|
||||
font-size: 11px;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.15s ease, border-color 0.15s ease, color 0.15s ease;
|
||||
transition:
|
||||
background-color 0.15s ease,
|
||||
border-color 0.15s ease,
|
||||
color 0.15s ease;
|
||||
|
||||
&:hover {
|
||||
background: var(--bg-tertiary);
|
||||
@@ -504,6 +510,12 @@
|
||||
overscroll-behavior: contain;
|
||||
}
|
||||
|
||||
.detailsNote {
|
||||
padding: 0 4px 10px;
|
||||
font-size: 12px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
// Table (80%比例)
|
||||
.tableWrapper {
|
||||
overflow-x: auto;
|
||||
@@ -514,7 +526,8 @@
|
||||
border-collapse: collapse;
|
||||
font-size: 12px;
|
||||
|
||||
th, td {
|
||||
th,
|
||||
td {
|
||||
padding: 10px 12px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
@@ -595,6 +608,11 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.durationCell {
|
||||
font-variant-numeric: tabular-nums;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
// Pricing Section (80%比例)
|
||||
.pricingSection {
|
||||
display: flex;
|
||||
@@ -1094,7 +1112,9 @@
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
border-radius: 2px;
|
||||
transition: transform 0.15s ease, opacity 0.15s ease;
|
||||
transition:
|
||||
transform 0.15s ease,
|
||||
opacity 0.15s ease;
|
||||
|
||||
.healthBlockWrapper:hover &,
|
||||
.healthBlockWrapper.healthBlockActive & {
|
||||
|
||||
@@ -28,6 +28,13 @@ const extractArrayPayload = (data: unknown, key: string): unknown[] => {
|
||||
return Array.isArray(candidate) ? candidate : [];
|
||||
};
|
||||
|
||||
const buildProviderDeleteQuery = (apiKey: string, baseUrl?: string) => {
|
||||
const params = new URLSearchParams();
|
||||
params.set('api-key', apiKey.trim());
|
||||
params.set('base-url', (baseUrl ?? '').trim());
|
||||
return `?${params.toString()}`;
|
||||
};
|
||||
|
||||
const serializeModelAliases = (models?: ModelAlias[]) =>
|
||||
Array.isArray(models)
|
||||
? models
|
||||
@@ -160,8 +167,8 @@ export const providersApi = {
|
||||
updateGeminiKey: (index: number, value: GeminiKeyConfig) =>
|
||||
apiClient.patch('/gemini-api-key', { index, value: serializeGeminiKey(value) }),
|
||||
|
||||
deleteGeminiKey: (apiKey: string) =>
|
||||
apiClient.delete(`/gemini-api-key?api-key=${encodeURIComponent(apiKey)}`),
|
||||
deleteGeminiKey: (apiKey: string, baseUrl?: string) =>
|
||||
apiClient.delete(`/gemini-api-key${buildProviderDeleteQuery(apiKey, baseUrl)}`),
|
||||
|
||||
async getCodexConfigs(): Promise<ProviderKeyConfig[]> {
|
||||
const data = await apiClient.get('/codex-api-key');
|
||||
@@ -175,8 +182,8 @@ export const providersApi = {
|
||||
updateCodexConfig: (index: number, value: ProviderKeyConfig) =>
|
||||
apiClient.patch('/codex-api-key', { index, value: serializeProviderKey(value) }),
|
||||
|
||||
deleteCodexConfig: (apiKey: string) =>
|
||||
apiClient.delete(`/codex-api-key?api-key=${encodeURIComponent(apiKey)}`),
|
||||
deleteCodexConfig: (apiKey: string, baseUrl?: string) =>
|
||||
apiClient.delete(`/codex-api-key${buildProviderDeleteQuery(apiKey, baseUrl)}`),
|
||||
|
||||
async getClaudeConfigs(): Promise<ProviderKeyConfig[]> {
|
||||
const data = await apiClient.get('/claude-api-key');
|
||||
@@ -190,8 +197,8 @@ export const providersApi = {
|
||||
updateClaudeConfig: (index: number, value: ProviderKeyConfig) =>
|
||||
apiClient.patch('/claude-api-key', { index, value: serializeProviderKey(value) }),
|
||||
|
||||
deleteClaudeConfig: (apiKey: string) =>
|
||||
apiClient.delete(`/claude-api-key?api-key=${encodeURIComponent(apiKey)}`),
|
||||
deleteClaudeConfig: (apiKey: string, baseUrl?: string) =>
|
||||
apiClient.delete(`/claude-api-key${buildProviderDeleteQuery(apiKey, baseUrl)}`),
|
||||
|
||||
async getVertexConfigs(): Promise<ProviderKeyConfig[]> {
|
||||
const data = await apiClient.get('/vertex-api-key');
|
||||
@@ -205,8 +212,8 @@ export const providersApi = {
|
||||
updateVertexConfig: (index: number, value: ProviderKeyConfig) =>
|
||||
apiClient.patch('/vertex-api-key', { index, value: serializeVertexKey(value) }),
|
||||
|
||||
deleteVertexConfig: (apiKey: string) =>
|
||||
apiClient.delete(`/vertex-api-key?api-key=${encodeURIComponent(apiKey)}`),
|
||||
deleteVertexConfig: (apiKey: string, baseUrl?: string) =>
|
||||
apiClient.delete(`/vertex-api-key${buildProviderDeleteQuery(apiKey, baseUrl)}`),
|
||||
|
||||
async getOpenAIProviders(): Promise<OpenAIProviderConfig[]> {
|
||||
const data = await apiClient.get('/openai-compatibility');
|
||||
|
||||
@@ -366,7 +366,12 @@ export const normalizeConfigResponse = (raw: unknown): Config => {
|
||||
if (isRecord(quota)) {
|
||||
config.quotaExceeded = {
|
||||
switchProject: normalizeBoolean(quota['switch-project'] ?? quota.switchProject),
|
||||
switchPreviewModel: normalizeBoolean(quota['switch-preview-model'] ?? quota.switchPreviewModel)
|
||||
switchPreviewModel: normalizeBoolean(
|
||||
quota['switch-preview-model'] ?? quota.switchPreviewModel
|
||||
),
|
||||
antigravityCredits: normalizeBoolean(
|
||||
quota['antigravity-credits'] ?? quota.antigravityCredits
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -14,9 +14,27 @@ import type { ProviderFormState } from '@/components/providers/types';
|
||||
|
||||
export type ClaudeTestStatus = 'idle' | 'loading' | 'success' | 'error';
|
||||
|
||||
export type ClaudeCloakBaseline = {
|
||||
mode: string;
|
||||
strictMode: boolean;
|
||||
sensitiveWords: string[] | null;
|
||||
} | null;
|
||||
|
||||
export type ClaudeEditBaseline = {
|
||||
apiKey: string;
|
||||
priority: number | null;
|
||||
prefix: string;
|
||||
baseUrl: string;
|
||||
proxyUrl: string;
|
||||
headers: Array<{ key: string; value: string }>;
|
||||
models: Array<{ name: string; alias: string }>;
|
||||
excludedModels: string[];
|
||||
cloak: ClaudeCloakBaseline;
|
||||
};
|
||||
|
||||
type ClaudeEditDraft = {
|
||||
initialized: boolean;
|
||||
baselineSignature: string;
|
||||
baseline: ClaudeEditBaseline | null;
|
||||
form: ProviderFormState;
|
||||
testModel: string;
|
||||
testStatus: ClaudeTestStatus;
|
||||
@@ -33,7 +51,7 @@ interface ClaudeEditDraftState {
|
||||
key: string,
|
||||
draft: Omit<ClaudeEditDraft, 'initialized'>
|
||||
) => void;
|
||||
setDraftBaselineSignature: (key: string, signature: string) => void;
|
||||
setDraftBaseline: (key: string, baseline: ClaudeEditBaseline) => void;
|
||||
setDraftForm: (
|
||||
key: string,
|
||||
action: SetStateAction<ProviderFormState>
|
||||
@@ -64,7 +82,7 @@ const buildEmptyForm = (): ProviderFormState => ({
|
||||
|
||||
const buildEmptyDraft = (): ClaudeEditDraft => ({
|
||||
initialized: false,
|
||||
baselineSignature: '',
|
||||
baseline: null,
|
||||
form: buildEmptyForm(),
|
||||
testModel: '',
|
||||
testStatus: 'idle',
|
||||
@@ -124,14 +142,14 @@ export const useClaudeEditDraftStore = create<ClaudeEditDraftState>((set, get) =
|
||||
}));
|
||||
},
|
||||
|
||||
setDraftBaselineSignature: (key, signature) => {
|
||||
setDraftBaseline: (key, baseline) => {
|
||||
if (!key) return;
|
||||
set((state) => {
|
||||
const existing = state.drafts[key] ?? buildEmptyDraft();
|
||||
return {
|
||||
drafts: {
|
||||
...state.drafts,
|
||||
[key]: { ...existing, initialized: true, baselineSignature: signature },
|
||||
[key]: { ...existing, initialized: true, baseline },
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
@@ -20,9 +20,24 @@ export type KeyTestStatus = {
|
||||
message: string;
|
||||
};
|
||||
|
||||
export type OpenAIEditBaseline = {
|
||||
name: string;
|
||||
priority: number | null;
|
||||
prefix: string;
|
||||
baseUrl: string;
|
||||
headers: Array<{ key: string; value: string }>;
|
||||
apiKeyEntries: Array<{
|
||||
apiKey: string;
|
||||
proxyUrl: string;
|
||||
headers: Array<{ key: string; value: string }>;
|
||||
}>;
|
||||
models: Array<{ name: string; alias: string }>;
|
||||
testModel: string;
|
||||
};
|
||||
|
||||
export type OpenAIEditDraft = {
|
||||
initialized: boolean;
|
||||
baselineSignature: string;
|
||||
baseline: OpenAIEditBaseline | null;
|
||||
form: OpenAIFormState;
|
||||
testModel: string;
|
||||
testStatus: OpenAITestStatus;
|
||||
@@ -37,7 +52,7 @@ interface OpenAIEditDraftState {
|
||||
releaseDraft: (key: string) => void;
|
||||
ensureDraft: (key: string) => void;
|
||||
initDraft: (key: string, draft: Omit<OpenAIEditDraft, 'initialized'>) => void;
|
||||
setDraftBaselineSignature: (key: string, signature: string) => void;
|
||||
setDraftBaseline: (key: string, baseline: OpenAIEditBaseline) => void;
|
||||
setDraftForm: (key: string, action: SetStateAction<OpenAIFormState>) => void;
|
||||
setDraftTestModel: (key: string, action: SetStateAction<string>) => void;
|
||||
setDraftTestStatus: (key: string, action: SetStateAction<OpenAITestStatus>) => void;
|
||||
@@ -62,7 +77,7 @@ const buildEmptyForm = (): OpenAIFormState => ({
|
||||
|
||||
const buildEmptyDraft = (): OpenAIEditDraft => ({
|
||||
initialized: false,
|
||||
baselineSignature: '',
|
||||
baseline: null,
|
||||
form: buildEmptyForm(),
|
||||
testModel: '',
|
||||
testStatus: 'idle',
|
||||
@@ -123,14 +138,14 @@ export const useOpenAIEditDraftStore = create<OpenAIEditDraftState>((set, get) =
|
||||
}));
|
||||
},
|
||||
|
||||
setDraftBaselineSignature: (key, signature) => {
|
||||
setDraftBaseline: (key, baseline) => {
|
||||
if (!key) return;
|
||||
set((state) => {
|
||||
const existing = state.drafts[key] ?? buildEmptyDraft();
|
||||
return {
|
||||
drafts: {
|
||||
...state.drafts,
|
||||
[key]: { ...existing, initialized: true, baselineSignature: signature },
|
||||
[key]: { ...existing, initialized: true, baseline },
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
--primary-contrast: #ffffff;
|
||||
|
||||
--success-color: #10b981;
|
||||
--quota-medium-color: #e0aa14;
|
||||
--warning-color: #c65746; // 错误/警告色
|
||||
--error-color: #c65746;
|
||||
--danger-color: var(--error-color);
|
||||
@@ -57,6 +58,14 @@
|
||||
|
||||
--radius-md: 8px;
|
||||
--accent-tertiary: var(--bg-tertiary);
|
||||
|
||||
// Glass effect (blurred surfaces)
|
||||
--glass-blur: 12px;
|
||||
--glass-backdrop-filter: blur(var(--glass-blur));
|
||||
--glass-filter: blur(var(--glass-blur));
|
||||
--glass-bg: color-mix(in srgb, var(--bg-primary) 82%, transparent);
|
||||
--glass-bg-secondary: color-mix(in srgb, var(--bg-secondary) 82%, transparent);
|
||||
--glass-border: color-mix(in srgb, var(--border-color) 60%, transparent);
|
||||
}
|
||||
|
||||
// 纯白主题
|
||||
@@ -88,6 +97,7 @@
|
||||
--primary-contrast: #ffffff;
|
||||
|
||||
--success-color: #10b981;
|
||||
--quota-medium-color: #e0aa14;
|
||||
--warning-color: #c65746;
|
||||
--error-color: #c65746;
|
||||
--danger-color: var(--error-color);
|
||||
@@ -145,6 +155,7 @@
|
||||
--primary-contrast: #ffffff;
|
||||
|
||||
--success-color: #10b981;
|
||||
--quota-medium-color: #ffd862;
|
||||
--warning-color: #c65746;
|
||||
--error-color: #c65746;
|
||||
--danger-color: var(--error-color);
|
||||
@@ -170,4 +181,16 @@
|
||||
|
||||
--radius-md: 8px;
|
||||
--accent-tertiary: var(--bg-tertiary);
|
||||
|
||||
--glass-border: color-mix(in srgb, var(--border-color) 55%, transparent);
|
||||
}
|
||||
|
||||
@media (max-width: 768px), (prefers-reduced-motion: reduce), (prefers-reduced-transparency: reduce) {
|
||||
:root {
|
||||
--glass-backdrop-filter: none;
|
||||
--glass-filter: none;
|
||||
--glass-bg: var(--bg-primary);
|
||||
--glass-bg-secondary: var(--bg-secondary);
|
||||
--glass-border: var(--border-color);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import type { AmpcodeConfig } from './ampcode';
|
||||
export interface QuotaExceededConfig {
|
||||
switchProject?: boolean;
|
||||
switchPreviewModel?: boolean;
|
||||
antigravityCredits?: boolean;
|
||||
}
|
||||
|
||||
export interface Config {
|
||||
|
||||
@@ -75,6 +75,7 @@ export type VisualConfigValues = {
|
||||
maxRetryInterval: string;
|
||||
quotaSwitchProject: boolean;
|
||||
quotaSwitchPreviewModel: boolean;
|
||||
quotaAntigravityCredits: boolean;
|
||||
routingStrategy: 'round-robin' | 'fill-first';
|
||||
wsAuth: boolean;
|
||||
payloadDefaultRules: PayloadRule[];
|
||||
@@ -114,6 +115,7 @@ export const DEFAULT_VISUAL_VALUES: VisualConfigValues = {
|
||||
maxRetryInterval: '',
|
||||
quotaSwitchProject: true,
|
||||
quotaSwitchPreviewModel: true,
|
||||
quotaAntigravityCredits: true,
|
||||
routingStrategy: 'round-robin',
|
||||
wsAuth: false,
|
||||
payloadDefaultRules: [],
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
export function areStringArraysEqual(a: readonly string[], b: readonly string[]): boolean {
|
||||
if (a === b) return true;
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i += 1) {
|
||||
if (a[i] !== b[i]) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function areKeyValueEntriesEqual(
|
||||
a: readonly { key: string; value: string }[],
|
||||
b: readonly { key: string; value: string }[]
|
||||
): boolean {
|
||||
if (a === b) return true;
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i += 1) {
|
||||
const left = a[i];
|
||||
const right = b[i];
|
||||
if (!left || !right) return false;
|
||||
if (left.key !== right.key || left.value !== right.value) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export function areModelEntriesEqual(
|
||||
a: readonly { name: string; alias: string }[],
|
||||
b: readonly { name: string; alias: string }[]
|
||||
): boolean {
|
||||
if (a === b) return true;
|
||||
if (a.length !== b.length) return false;
|
||||
for (let i = 0; i < a.length; i += 1) {
|
||||
const left = a[i];
|
||||
const right = b[i];
|
||||
if (!left || !right) return false;
|
||||
if (left.name !== right.name || left.alias !== right.alias) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1,166 +0,0 @@
|
||||
type GroupState = {
|
||||
hasInnerVariableQuantifier: boolean;
|
||||
hasAlternation: boolean;
|
||||
justOpened: boolean;
|
||||
};
|
||||
|
||||
type Quantifier = {
|
||||
length: number;
|
||||
min: number;
|
||||
max: number | null; // null means unbounded
|
||||
variable: boolean; // can match multiple lengths for the repeated token
|
||||
};
|
||||
|
||||
const OUTER_REPEAT_MAX_SAFE_UPPER_BOUND = 9;
|
||||
|
||||
const isDigit = (ch: string | undefined): ch is string => ch !== undefined && ch >= '0' && ch <= '9';
|
||||
|
||||
const readBraceQuantifier = (pattern: string, index: number): Quantifier | null => {
|
||||
if (pattern[index] !== '{') return null;
|
||||
|
||||
let i = index + 1;
|
||||
let minStr = '';
|
||||
while (isDigit(pattern[i])) {
|
||||
minStr += pattern[i];
|
||||
i += 1;
|
||||
}
|
||||
|
||||
if (minStr.length === 0) return null;
|
||||
const min = Number(minStr);
|
||||
|
||||
let max: number | null = min;
|
||||
if (pattern[i] === ',') {
|
||||
i += 1;
|
||||
let maxStr = '';
|
||||
while (isDigit(pattern[i])) {
|
||||
maxStr += pattern[i];
|
||||
i += 1;
|
||||
}
|
||||
max = maxStr.length === 0 ? null : Number(maxStr);
|
||||
}
|
||||
|
||||
if (pattern[i] !== '}') return null;
|
||||
|
||||
const variable = max === null || max !== min;
|
||||
return { length: i - index + 1, min, max, variable };
|
||||
};
|
||||
|
||||
const readQuantifier = (pattern: string, index: number): Quantifier | null => {
|
||||
const ch = pattern[index];
|
||||
if (ch === '*') return { length: 1, min: 0, max: null, variable: true };
|
||||
if (ch === '+') return { length: 1, min: 1, max: null, variable: true };
|
||||
if (ch === '?') return { length: 1, min: 0, max: 1, variable: true };
|
||||
if (ch !== '{') return null;
|
||||
return readBraceQuantifier(pattern, index);
|
||||
};
|
||||
|
||||
/**
|
||||
* Heuristic safety check for user-supplied JS regex patterns.
|
||||
*
|
||||
* Goal: prevent patterns that are very likely to cause catastrophic backtracking
|
||||
* (e.g. `^(a+)+$`) from running on the main thread.
|
||||
*
|
||||
* Notes:
|
||||
* - This is intentionally conservative but tries to avoid blocking common safe patterns.
|
||||
* - We do not execute the regex here; only scan the pattern string.
|
||||
*/
|
||||
export function isLikelyUnsafeJsRegex(pattern: string): boolean {
|
||||
let inCharClass = false;
|
||||
const groupStack: GroupState[] = [
|
||||
{ hasInnerVariableQuantifier: false, hasAlternation: false, justOpened: false },
|
||||
];
|
||||
|
||||
const markInnerVariableQuantifier = () => {
|
||||
for (let i = 0; i < groupStack.length; i += 1) {
|
||||
groupStack[i].hasInnerVariableQuantifier = true;
|
||||
}
|
||||
};
|
||||
|
||||
const markAlternation = () => {
|
||||
for (let i = 0; i < groupStack.length; i += 1) {
|
||||
groupStack[i].hasAlternation = true;
|
||||
}
|
||||
};
|
||||
|
||||
const isOuterRepeatRisky = (q: Quantifier): boolean => {
|
||||
// If it cannot repeat more than once, it's not a "repeat group" in the sense that
|
||||
// triggers catastrophic backtracking (e.g. `(a+)?`).
|
||||
const max = q.max ?? Number.POSITIVE_INFINITY;
|
||||
if (max <= 1) return false;
|
||||
|
||||
// Unbounded repetition is the main hazard: `*`, `+`, `{m,}`.
|
||||
if (q.max === null) return true;
|
||||
|
||||
// Large fixed/variable upper bounds also explode combinatorially with an inner variable quantifier.
|
||||
return q.max > OUTER_REPEAT_MAX_SAFE_UPPER_BOUND;
|
||||
};
|
||||
|
||||
for (let i = 0; i < pattern.length; i += 1) {
|
||||
const ch = pattern[i];
|
||||
|
||||
// Reset "justOpened" once we move past the first token inside the group.
|
||||
const top = groupStack[groupStack.length - 1];
|
||||
if (top.justOpened) {
|
||||
top.justOpened = false;
|
||||
// `(?...)` group prefixes use `?` immediately after `(` and are not quantifiers.
|
||||
if (ch === '?') continue;
|
||||
}
|
||||
|
||||
if (ch === '\\') {
|
||||
const next = pattern[i + 1];
|
||||
// Backreferences often make backtracking far worse.
|
||||
if (next && next >= '1' && next <= '9') return true;
|
||||
// Named backreference: \k<name>
|
||||
if (next === 'k' && pattern[i + 2] === '<') return true;
|
||||
|
||||
// Skip escaped character.
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (inCharClass) {
|
||||
if (ch === ']') inCharClass = false;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '[') {
|
||||
inCharClass = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '(') {
|
||||
groupStack.push({ hasInnerVariableQuantifier: false, hasAlternation: false, justOpened: true });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === ')') {
|
||||
const group = groupStack.pop();
|
||||
if (!group) return true; // unbalanced, treat as unsafe
|
||||
|
||||
const q = readQuantifier(pattern, i + 1);
|
||||
if (
|
||||
q &&
|
||||
isOuterRepeatRisky(q) &&
|
||||
(group.hasInnerVariableQuantifier || group.hasAlternation)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if (ch === '|') {
|
||||
// Alternation inside a repeated group is frequently a backtracking hotspot.
|
||||
markAlternation();
|
||||
continue;
|
||||
}
|
||||
|
||||
const q = readQuantifier(pattern, i);
|
||||
if (q) {
|
||||
if (q.variable) markInnerVariableQuantifier();
|
||||
i += q.length - 1;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
+227
-71
@@ -4,8 +4,25 @@
|
||||
*/
|
||||
|
||||
import type { ScriptableContext } from 'chart.js';
|
||||
import type { LatencyAccumulator, LatencyStats } from './usage/latency';
|
||||
import {
|
||||
addLatencySample,
|
||||
calculateLatencyStatsFromDetails,
|
||||
createLatencyAccumulator,
|
||||
extractLatencyMs,
|
||||
finalizeLatencyStats,
|
||||
} from './usage/latency';
|
||||
import { maskApiKey } from './format';
|
||||
|
||||
export type { DurationFormatOptions, LatencyStats } from './usage/latency';
|
||||
export {
|
||||
LATENCY_SOURCE_FIELD,
|
||||
LATENCY_SOURCE_UNIT,
|
||||
calculateLatencyStatsFromDetails,
|
||||
extractLatencyMs,
|
||||
formatDurationMs,
|
||||
} from './usage/latency';
|
||||
|
||||
export interface KeyStatBucket {
|
||||
success: number;
|
||||
failure: number;
|
||||
@@ -39,6 +56,7 @@ export interface UsageDetail {
|
||||
timestamp: string;
|
||||
source: string;
|
||||
auth_index: number;
|
||||
latency_ms?: number;
|
||||
tokens: {
|
||||
input_tokens: number;
|
||||
output_tokens: number;
|
||||
@@ -66,7 +84,22 @@ export interface ApiStats {
|
||||
failureCount: number;
|
||||
totalTokens: number;
|
||||
totalCost: number;
|
||||
models: Record<string, { requests: number; successCount: number; failureCount: number; tokens: number }>;
|
||||
models: Record<
|
||||
string,
|
||||
{ requests: number; successCount: number; failureCount: number; tokens: number }
|
||||
>;
|
||||
}
|
||||
|
||||
export interface ModelStatsSummary {
|
||||
model: string;
|
||||
requests: number;
|
||||
successCount: number;
|
||||
failureCount: number;
|
||||
tokens: number;
|
||||
cost: number;
|
||||
averageLatencyMs: number | null;
|
||||
totalLatencyMs: number | null;
|
||||
latencySampleCount: number;
|
||||
}
|
||||
|
||||
export type UsageTimeRange = '7h' | '24h' | '7d' | 'all';
|
||||
@@ -77,7 +110,7 @@ const USAGE_ENDPOINT_METHOD_REGEX = /^(GET|POST|PUT|PATCH|DELETE|OPTIONS|HEAD)\s
|
||||
const USAGE_TIME_RANGE_MS: Record<Exclude<UsageTimeRange, 'all'>, number> = {
|
||||
'7h': 7 * 60 * 60 * 1000,
|
||||
'24h': 24 * 60 * 60 * 1000,
|
||||
'7d': 7 * 24 * 60 * 60 * 1000
|
||||
'7d': 7 * 24 * 60 * 60 * 1000,
|
||||
};
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
@@ -100,17 +133,21 @@ const createUsageSummary = (): UsageSummary => ({
|
||||
totalRequests: 0,
|
||||
successCount: 0,
|
||||
failureCount: 0,
|
||||
totalTokens: 0
|
||||
totalTokens: 0,
|
||||
});
|
||||
|
||||
const toUsageSummaryFields = (summary: UsageSummary) => ({
|
||||
total_requests: summary.totalRequests,
|
||||
success_count: summary.successCount,
|
||||
failure_count: summary.failureCount,
|
||||
total_tokens: summary.totalTokens
|
||||
total_tokens: summary.totalTokens,
|
||||
});
|
||||
|
||||
export function filterUsageByTimeRange<T>(usageData: T, range: UsageTimeRange, nowMs: number = Date.now()): T {
|
||||
export function filterUsageByTimeRange<T>(
|
||||
usageData: T,
|
||||
range: UsageTimeRange,
|
||||
nowMs: number = Date.now()
|
||||
): T {
|
||||
if (range === 'all') {
|
||||
return usageData;
|
||||
}
|
||||
@@ -180,7 +217,7 @@ export function filterUsageByTimeRange<T>(usageData: T, range: UsageTimeRange, n
|
||||
filteredModels[modelName] = {
|
||||
...modelEntry,
|
||||
...toUsageSummaryFields(modelSummary),
|
||||
details: filteredDetails
|
||||
details: filteredDetails,
|
||||
};
|
||||
hasModelData = true;
|
||||
|
||||
@@ -197,7 +234,7 @@ export function filterUsageByTimeRange<T>(usageData: T, range: UsageTimeRange, n
|
||||
filteredApis[apiName] = {
|
||||
...apiEntry,
|
||||
...toUsageSummaryFields(apiSummary),
|
||||
models: filteredModels
|
||||
models: filteredModels,
|
||||
};
|
||||
|
||||
totalSummary.totalRequests += apiSummary.totalRequests;
|
||||
@@ -209,7 +246,7 @@ export function filterUsageByTimeRange<T>(usageData: T, range: UsageTimeRange, n
|
||||
return {
|
||||
...usageRecord,
|
||||
...toUsageSummaryFields(totalSummary),
|
||||
apis: filteredApis
|
||||
apis: filteredApis,
|
||||
} as T;
|
||||
}
|
||||
|
||||
@@ -309,7 +346,8 @@ export function normalizeUsageSourceId(
|
||||
value: unknown,
|
||||
masker: (val: string) => string = maskApiKey
|
||||
): string {
|
||||
const raw = typeof value === 'string' ? value : value === null || value === undefined ? '' : String(value);
|
||||
const raw =
|
||||
typeof value === 'string' ? value : value === null || value === undefined ? '' : String(value);
|
||||
const trimmed = raw.trim();
|
||||
if (!trimmed) return '';
|
||||
|
||||
@@ -325,7 +363,10 @@ export function normalizeUsageSourceId(
|
||||
return `${USAGE_SOURCE_PREFIX_TEXT}${trimmed}`;
|
||||
}
|
||||
|
||||
export function buildCandidateUsageSourceIds(input: { apiKey?: string; prefix?: string }): string[] {
|
||||
export function buildCandidateUsageSourceIds(input: {
|
||||
apiKey?: string;
|
||||
prefix?: string;
|
||||
}): string[] {
|
||||
const result: string[] = [];
|
||||
|
||||
const prefix = input.prefix?.trim();
|
||||
@@ -335,6 +376,10 @@ export function buildCandidateUsageSourceIds(input: { apiKey?: string; prefix?:
|
||||
|
||||
const apiKey = input.apiKey?.trim();
|
||||
if (apiKey) {
|
||||
// Include the normalised form first so that "non-standard" keys (e.g. short tokens,
|
||||
// keys containing '/' etc.) that are classified as text by normalizeUsageSourceId()
|
||||
// can still match usage details.
|
||||
result.push(normalizeUsageSourceId(apiKey));
|
||||
result.push(`${USAGE_SOURCE_PREFIX_KEY}${fnv1a64Hex(apiKey)}`);
|
||||
result.push(`${USAGE_SOURCE_PREFIX_MASKED}${maskApiKey(apiKey)}`);
|
||||
}
|
||||
@@ -345,7 +390,10 @@ export function buildCandidateUsageSourceIds(input: { apiKey?: string; prefix?:
|
||||
/**
|
||||
* 对使用数据中的敏感字段进行遮罩
|
||||
*/
|
||||
export function maskUsageSensitiveValue(value: unknown, masker: (val: string) => string = maskApiKey): string {
|
||||
export function maskUsageSensitiveValue(
|
||||
value: unknown,
|
||||
masker: (val: string) => string = maskApiKey
|
||||
): string {
|
||||
if (value === null || value === undefined) {
|
||||
return '';
|
||||
}
|
||||
@@ -357,12 +405,20 @@ export function maskUsageSensitiveValue(value: unknown, masker: (val: string) =>
|
||||
let masked = raw;
|
||||
|
||||
const queryRegex = /([?&])(api[-_]?key|key|token|access_token|authorization)=([^&#\s]+)/gi;
|
||||
masked = masked.replace(queryRegex, (_full, prefix, keyName, valuePart) => `${prefix}${keyName}=${masker(valuePart)}`);
|
||||
masked = masked.replace(
|
||||
queryRegex,
|
||||
(_full, prefix, keyName, valuePart) => `${prefix}${keyName}=${masker(valuePart)}`
|
||||
);
|
||||
|
||||
const headerRegex = /(api[-_]?key|key|token|access[-_]?token|authorization)\s*([:=])\s*([A-Za-z0-9._-]+)/gi;
|
||||
masked = masked.replace(headerRegex, (_full, keyName, separator, valuePart) => `${keyName}${separator}${masker(valuePart)}`);
|
||||
const headerRegex =
|
||||
/(api[-_]?key|key|token|access[-_]?token|authorization)\s*([:=])\s*([A-Za-z0-9._-]+)/gi;
|
||||
masked = masked.replace(
|
||||
headerRegex,
|
||||
(_full, keyName, separator, valuePart) => `${keyName}${separator}${masker(valuePart)}`
|
||||
);
|
||||
|
||||
const keyLikeRegex = /(sk-[A-Za-z0-9]{6,}|AI[a-zA-Z0-9_-]{6,}|AIza[0-9A-Za-z-_]{8,}|hf_[A-Za-z0-9]{6,}|pk_[A-Za-z0-9]{6,}|rk_[A-Za-z0-9]{6,})/g;
|
||||
const keyLikeRegex =
|
||||
/(sk-[A-Za-z0-9]{6,}|AI[a-zA-Z0-9_-]{6,}|AIza[0-9A-Za-z-_]{8,}|hf_[A-Za-z0-9]{6,}|pk_[A-Za-z0-9]{6,}|rk_[A-Za-z0-9]{6,})/g;
|
||||
masked = masked.replace(keyLikeRegex, (match) => masker(match));
|
||||
|
||||
if (masked === raw) {
|
||||
@@ -436,7 +492,7 @@ export function formatUsd(value: number): string {
|
||||
const fixed = num.toFixed(2);
|
||||
const parts = Number(fixed).toLocaleString(undefined, {
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2
|
||||
maximumFractionDigits: 2,
|
||||
});
|
||||
return `$${parts}`;
|
||||
}
|
||||
@@ -491,10 +547,12 @@ export function collectUsageDetails(usageData: unknown): UsageDetail[] {
|
||||
const timestamp = detailRaw.timestamp;
|
||||
const timestampMs = Date.parse(timestamp);
|
||||
const tokensRaw = isRecord(detailRaw.tokens) ? detailRaw.tokens : {};
|
||||
const latencyMs = extractLatencyMs(detailRaw);
|
||||
details.push({
|
||||
timestamp,
|
||||
source: normalizeSource(detailRaw.source),
|
||||
auth_index: detailRaw.auth_index as unknown as number,
|
||||
latency_ms: latencyMs ?? undefined,
|
||||
tokens: tokensRaw as unknown as UsageDetail['tokens'],
|
||||
failed: detailRaw.failed === true,
|
||||
__modelName: modelName,
|
||||
@@ -562,10 +620,12 @@ export function collectUsageDetailsWithEndpoint(usageData: unknown): UsageDetail
|
||||
const timestamp = detailRaw.timestamp;
|
||||
const timestampMs = Date.parse(timestamp);
|
||||
const tokensRaw = isRecord(detailRaw.tokens) ? detailRaw.tokens : {};
|
||||
const latencyMs = extractLatencyMs(detailRaw);
|
||||
details.push({
|
||||
timestamp,
|
||||
source: normalizeSource(detailRaw.source),
|
||||
auth_index: detailRaw.auth_index as unknown as number,
|
||||
latency_ms: latencyMs ?? undefined,
|
||||
tokens: tokensRaw as unknown as UsageDetail['tokens'],
|
||||
failed: detailRaw.failed === true,
|
||||
__modelName: modelName,
|
||||
@@ -605,6 +665,13 @@ export function extractTotalTokens(detail: unknown): number {
|
||||
return inputTokens + outputTokens + reasoningTokens + cachedTokens;
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算耗时统计
|
||||
*/
|
||||
export function calculateLatencyStats(usageData: unknown): LatencyStats {
|
||||
return calculateLatencyStatsFromDetails(collectUsageDetails(usageData));
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算 token 分类统计
|
||||
*/
|
||||
@@ -652,7 +719,9 @@ export function calculateRecentPerMinuteRates(
|
||||
|
||||
details.forEach((detail) => {
|
||||
const timestamp =
|
||||
typeof detail.__timestampMs === 'number' ? detail.__timestampMs : Date.parse(detail.timestamp);
|
||||
typeof detail.__timestampMs === 'number'
|
||||
? detail.__timestampMs
|
||||
: Date.parse(detail.timestamp);
|
||||
if (!Number.isFinite(timestamp) || timestamp < windowStart || timestamp > now) {
|
||||
return;
|
||||
}
|
||||
@@ -666,7 +735,7 @@ export function calculateRecentPerMinuteRates(
|
||||
tpm: tokenCount / denominator,
|
||||
windowMinutes: effectiveWindow,
|
||||
requestCount,
|
||||
tokenCount
|
||||
tokenCount,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -694,7 +763,10 @@ export function getModelNamesFromUsage(usageData: unknown): string[] {
|
||||
/**
|
||||
* 计算成本数据
|
||||
*/
|
||||
export function calculateCost(detail: UsageDetail, modelPrices: Record<string, ModelPrice>): number {
|
||||
export function calculateCost(
|
||||
detail: UsageDetail,
|
||||
modelPrices: Record<string, ModelPrice>
|
||||
): number {
|
||||
const modelName = detail.__modelName || '';
|
||||
const price = modelPrices[modelName];
|
||||
if (!price) {
|
||||
@@ -707,7 +779,9 @@ export function calculateCost(detail: UsageDetail, modelPrices: Record<string, M
|
||||
const rawCachedTokensAlternate = Number(tokens.cache_tokens);
|
||||
|
||||
const inputTokens = Number.isFinite(rawInputTokens) ? Math.max(rawInputTokens, 0) : 0;
|
||||
const completionTokens = Number.isFinite(rawCompletionTokens) ? Math.max(rawCompletionTokens, 0) : 0;
|
||||
const completionTokens = Number.isFinite(rawCompletionTokens)
|
||||
? Math.max(rawCompletionTokens, 0)
|
||||
: 0;
|
||||
const cachedTokens = Math.max(
|
||||
Number.isFinite(rawCachedTokensPrimary) ? Math.max(rawCachedTokensPrimary, 0) : 0,
|
||||
Number.isFinite(rawCachedTokensAlternate) ? Math.max(rawCachedTokensAlternate, 0) : 0
|
||||
@@ -716,7 +790,8 @@ export function calculateCost(detail: UsageDetail, modelPrices: Record<string, M
|
||||
|
||||
const promptCost = (promptTokens / TOKENS_PER_PRICE_UNIT) * (Number(price.prompt) || 0);
|
||||
const cachedCost = (cachedTokens / TOKENS_PER_PRICE_UNIT) * (Number(price.cache) || 0);
|
||||
const completionCost = (completionTokens / TOKENS_PER_PRICE_UNIT) * (Number(price.completion) || 0);
|
||||
const completionCost =
|
||||
(completionTokens / TOKENS_PER_PRICE_UNIT) * (Number(price.completion) || 0);
|
||||
const total = promptCost + cachedCost + completionCost;
|
||||
return Number.isFinite(total) && total > 0 ? total : 0;
|
||||
}
|
||||
@@ -724,7 +799,10 @@ export function calculateCost(detail: UsageDetail, modelPrices: Record<string, M
|
||||
/**
|
||||
* 计算总成本
|
||||
*/
|
||||
export function calculateTotalCost(usageData: unknown, modelPrices: Record<string, ModelPrice>): number {
|
||||
export function calculateTotalCost(
|
||||
usageData: unknown,
|
||||
modelPrices: Record<string, ModelPrice>
|
||||
): number {
|
||||
const details = collectUsageDetails(usageData);
|
||||
if (!details.length || !Object.keys(modelPrices).length) {
|
||||
return 0;
|
||||
@@ -756,7 +834,11 @@ export function loadModelPrices(): Record<string, ModelPrice> {
|
||||
const completionRaw = Number(priceRecord?.completion);
|
||||
const cacheRaw = Number(priceRecord?.cache);
|
||||
|
||||
if (!Number.isFinite(promptRaw) && !Number.isFinite(completionRaw) && !Number.isFinite(cacheRaw)) {
|
||||
if (
|
||||
!Number.isFinite(promptRaw) &&
|
||||
!Number.isFinite(completionRaw) &&
|
||||
!Number.isFinite(cacheRaw)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -772,7 +854,7 @@ export function loadModelPrices(): Record<string, ModelPrice> {
|
||||
normalized[model] = {
|
||||
prompt,
|
||||
completion,
|
||||
cache
|
||||
cache,
|
||||
};
|
||||
});
|
||||
return normalized;
|
||||
@@ -798,14 +880,20 @@ export function saveModelPrices(prices: Record<string, ModelPrice>): void {
|
||||
/**
|
||||
* 获取 API 统计数据
|
||||
*/
|
||||
export function getApiStats(usageData: unknown, modelPrices: Record<string, ModelPrice>): ApiStats[] {
|
||||
export function getApiStats(
|
||||
usageData: unknown,
|
||||
modelPrices: Record<string, ModelPrice>
|
||||
): ApiStats[] {
|
||||
const apis = getApisRecord(usageData);
|
||||
if (!apis) return [];
|
||||
const result: ApiStats[] = [];
|
||||
|
||||
Object.entries(apis).forEach(([endpoint, apiData]) => {
|
||||
if (!isRecord(apiData)) return;
|
||||
const models: Record<string, { requests: number; successCount: number; failureCount: number; tokens: number }> = {};
|
||||
const models: Record<
|
||||
string,
|
||||
{ requests: number; successCount: number; failureCount: number; tokens: number }
|
||||
> = {};
|
||||
let derivedSuccessCount = 0;
|
||||
let derivedFailureCount = 0;
|
||||
let totalCost = 0;
|
||||
@@ -849,7 +937,7 @@ export function getApiStats(usageData: unknown, modelPrices: Record<string, Mode
|
||||
requests: Number(modelData.total_requests) || 0,
|
||||
successCount,
|
||||
failureCount,
|
||||
tokens: Number(modelData.total_tokens) || 0
|
||||
tokens: Number(modelData.total_tokens) || 0,
|
||||
};
|
||||
derivedSuccessCount += successCount;
|
||||
derivedFailureCount += failureCount;
|
||||
@@ -858,10 +946,10 @@ export function getApiStats(usageData: unknown, modelPrices: Record<string, Mode
|
||||
const hasApiExplicitCounts =
|
||||
typeof apiData.success_count === 'number' || typeof apiData.failure_count === 'number';
|
||||
const successCount = hasApiExplicitCounts
|
||||
? (Number(apiData.success_count) || 0)
|
||||
? Number(apiData.success_count) || 0
|
||||
: derivedSuccessCount;
|
||||
const failureCount = hasApiExplicitCounts
|
||||
? (Number(apiData.failure_count) || 0)
|
||||
? Number(apiData.failure_count) || 0
|
||||
: derivedFailureCount;
|
||||
|
||||
result.push({
|
||||
@@ -871,7 +959,7 @@ export function getApiStats(usageData: unknown, modelPrices: Record<string, Mode
|
||||
failureCount,
|
||||
totalTokens: Number(apiData.total_tokens) || 0,
|
||||
totalCost,
|
||||
models
|
||||
models,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -881,18 +969,24 @@ export function getApiStats(usageData: unknown, modelPrices: Record<string, Mode
|
||||
/**
|
||||
* 获取模型统计数据
|
||||
*/
|
||||
export function getModelStats(usageData: unknown, modelPrices: Record<string, ModelPrice>): Array<{
|
||||
model: string;
|
||||
requests: number;
|
||||
successCount: number;
|
||||
failureCount: number;
|
||||
tokens: number;
|
||||
cost: number;
|
||||
}> {
|
||||
export function getModelStats(
|
||||
usageData: unknown,
|
||||
modelPrices: Record<string, ModelPrice>
|
||||
): ModelStatsSummary[] {
|
||||
const apis = getApisRecord(usageData);
|
||||
if (!apis) return [];
|
||||
|
||||
const modelMap = new Map<string, { requests: number; successCount: number; failureCount: number; tokens: number; cost: number }>();
|
||||
const modelMap = new Map<
|
||||
string,
|
||||
{
|
||||
requests: number;
|
||||
successCount: number;
|
||||
failureCount: number;
|
||||
tokens: number;
|
||||
cost: number;
|
||||
latency: LatencyAccumulator;
|
||||
}
|
||||
>();
|
||||
|
||||
Object.values(apis).forEach((apiData) => {
|
||||
if (!isRecord(apiData)) return;
|
||||
@@ -902,7 +996,14 @@ export function getModelStats(usageData: unknown, modelPrices: Record<string, Mo
|
||||
|
||||
Object.entries(models).forEach(([modelName, modelData]) => {
|
||||
if (!isRecord(modelData)) return;
|
||||
const existing = modelMap.get(modelName) || { requests: 0, successCount: 0, failureCount: 0, tokens: 0, cost: 0 };
|
||||
const existing = modelMap.get(modelName) || {
|
||||
requests: 0,
|
||||
successCount: 0,
|
||||
failureCount: 0,
|
||||
tokens: 0,
|
||||
cost: 0,
|
||||
latency: createLatencyAccumulator(),
|
||||
};
|
||||
existing.requests += Number(modelData.total_requests) || 0;
|
||||
existing.tokens += Number(modelData.total_tokens) || 0;
|
||||
|
||||
@@ -917,9 +1018,10 @@ export function getModelStats(usageData: unknown, modelPrices: Record<string, Mo
|
||||
existing.failureCount += Number(modelData.failure_count) || 0;
|
||||
}
|
||||
|
||||
if (details.length > 0 && (!hasExplicitCounts || price)) {
|
||||
if (details.length > 0) {
|
||||
details.forEach((detail) => {
|
||||
const detailRecord = isRecord(detail) ? detail : null;
|
||||
const latencyMs = extractLatencyMs(detailRecord);
|
||||
if (!hasExplicitCounts) {
|
||||
if (detailRecord?.failed === true) {
|
||||
existing.failureCount += 1;
|
||||
@@ -928,6 +1030,8 @@ export function getModelStats(usageData: unknown, modelPrices: Record<string, Mo
|
||||
}
|
||||
}
|
||||
|
||||
addLatencySample(existing.latency, latencyMs);
|
||||
|
||||
if (price && detailRecord) {
|
||||
existing.cost += calculateCost(
|
||||
{ ...(detailRecord as unknown as UsageDetail), __modelName: modelName },
|
||||
@@ -941,7 +1045,20 @@ export function getModelStats(usageData: unknown, modelPrices: Record<string, Mo
|
||||
});
|
||||
|
||||
return Array.from(modelMap.entries())
|
||||
.map(([model, stats]) => ({ model, ...stats }))
|
||||
.map(([model, stats]) => {
|
||||
const latencyStats = finalizeLatencyStats(stats.latency);
|
||||
return {
|
||||
model,
|
||||
requests: stats.requests,
|
||||
successCount: stats.successCount,
|
||||
failureCount: stats.failureCount,
|
||||
tokens: stats.tokens,
|
||||
cost: stats.cost,
|
||||
averageLatencyMs: latencyStats.averageMs,
|
||||
totalLatencyMs: latencyStats.totalMs,
|
||||
latencySampleCount: latencyStats.sampleCount,
|
||||
};
|
||||
})
|
||||
.sort((a, b) => b.requests - a.requests);
|
||||
}
|
||||
|
||||
@@ -1012,7 +1129,9 @@ export function buildHourlySeriesByModel(
|
||||
|
||||
details.forEach((detail) => {
|
||||
const timestamp =
|
||||
typeof detail.__timestampMs === 'number' ? detail.__timestampMs : Date.parse(detail.timestamp);
|
||||
typeof detail.__timestampMs === 'number'
|
||||
? detail.__timestampMs
|
||||
: Date.parse(detail.timestamp);
|
||||
if (!Number.isFinite(timestamp) || timestamp <= 0) {
|
||||
return;
|
||||
}
|
||||
@@ -1069,7 +1188,9 @@ export function buildDailySeriesByModel(
|
||||
|
||||
details.forEach((detail) => {
|
||||
const timestamp =
|
||||
typeof detail.__timestampMs === 'number' ? detail.__timestampMs : Date.parse(detail.timestamp);
|
||||
typeof detail.__timestampMs === 'number'
|
||||
? detail.__timestampMs
|
||||
: Date.parse(detail.timestamp);
|
||||
if (!Number.isFinite(timestamp) || timestamp <= 0) {
|
||||
return;
|
||||
}
|
||||
@@ -1092,7 +1213,7 @@ export function buildDailySeriesByModel(
|
||||
const labels = Array.from(labelsSet).sort();
|
||||
const dataByModel = new Map<string, number[]>();
|
||||
valuesByModel.forEach((dayMap, modelName) => {
|
||||
const series = labels.map(label => dayMap.get(label) || 0);
|
||||
const series = labels.map((label) => dayMap.get(label) || 0);
|
||||
dataByModel.set(modelName, series);
|
||||
});
|
||||
|
||||
@@ -1103,7 +1224,10 @@ export interface ChartDataset {
|
||||
label: string;
|
||||
data: number[];
|
||||
borderColor: string;
|
||||
backgroundColor: string | CanvasGradient | ((context: ScriptableContext<'line'>) => string | CanvasGradient);
|
||||
backgroundColor:
|
||||
| string
|
||||
| CanvasGradient
|
||||
| ((context: ScriptableContext<'line'>) => string | CanvasGradient);
|
||||
pointBackgroundColor?: string;
|
||||
pointBorderColor?: string;
|
||||
fill: boolean;
|
||||
@@ -1152,7 +1276,11 @@ const withAlpha = (hex: string, alpha: number) => {
|
||||
return `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, ${clamped})`;
|
||||
};
|
||||
|
||||
const buildAreaGradient = (context: ScriptableContext<'line'>, baseHex: string, fallback: string) => {
|
||||
const buildAreaGradient = (
|
||||
context: ScriptableContext<'line'>,
|
||||
baseHex: string,
|
||||
fallback: string
|
||||
) => {
|
||||
const chart = context.chart;
|
||||
const ctx = chart.ctx;
|
||||
const area = chart.chartArea;
|
||||
@@ -1178,16 +1306,17 @@ export function buildChartData(
|
||||
selectedModels: string[] = [],
|
||||
options: { hourWindowHours?: number } = {}
|
||||
): ChartData {
|
||||
const baseSeries = period === 'hour'
|
||||
? buildHourlySeriesByModel(usageData, metric, options.hourWindowHours)
|
||||
: buildDailySeriesByModel(usageData, metric);
|
||||
const baseSeries =
|
||||
period === 'hour'
|
||||
? buildHourlySeriesByModel(usageData, metric, options.hourWindowHours)
|
||||
: buildDailySeriesByModel(usageData, metric);
|
||||
|
||||
const { labels, dataByModel } = baseSeries;
|
||||
|
||||
// Build "All" series as sum of all models
|
||||
const getAllSeries = (): number[] => {
|
||||
const summed = new Array(labels.length).fill(0);
|
||||
dataByModel.forEach(values => {
|
||||
dataByModel.forEach((values) => {
|
||||
values.forEach((value, idx) => {
|
||||
summed[idx] = (summed[idx] || 0) + value;
|
||||
});
|
||||
@@ -1200,7 +1329,9 @@ export function buildChartData(
|
||||
|
||||
const datasets: ChartDataset[] = modelsToShow.map((model, index) => {
|
||||
const isAll = model === 'all';
|
||||
const data = isAll ? getAllSeries() : (dataByModel.get(model) || new Array(labels.length).fill(0));
|
||||
const data = isAll
|
||||
? getAllSeries()
|
||||
: dataByModel.get(model) || new Array(labels.length).fill(0);
|
||||
const colorIndex = index % CHART_COLORS.length;
|
||||
const style = CHART_COLORS[colorIndex];
|
||||
const shouldFill = modelsToShow.length === 1 || (isAll && modelsToShow.length > 1);
|
||||
@@ -1215,7 +1346,7 @@ export function buildChartData(
|
||||
pointBackgroundColor: style.borderColor,
|
||||
pointBorderColor: style.borderColor,
|
||||
fill: shouldFill,
|
||||
tension: 0.35
|
||||
tension: 0.35,
|
||||
};
|
||||
});
|
||||
|
||||
@@ -1283,8 +1414,15 @@ export function calculateStatusBarData(
|
||||
// Filter and bucket the usage details
|
||||
usageDetails.forEach((detail) => {
|
||||
const timestamp =
|
||||
typeof detail.__timestampMs === 'number' ? detail.__timestampMs : Date.parse(detail.timestamp);
|
||||
if (!Number.isFinite(timestamp) || timestamp <= 0 || timestamp < windowStart || timestamp > now) {
|
||||
typeof detail.__timestampMs === 'number'
|
||||
? detail.__timestampMs
|
||||
: Date.parse(detail.timestamp);
|
||||
if (
|
||||
!Number.isFinite(timestamp) ||
|
||||
timestamp <= 0 ||
|
||||
timestamp < windowStart ||
|
||||
timestamp > now
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1346,7 +1484,7 @@ export function calculateStatusBarData(
|
||||
blockDetails,
|
||||
successRate,
|
||||
totalSuccess,
|
||||
totalFailure
|
||||
totalFailure,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1364,9 +1502,7 @@ export interface ServiceHealthData {
|
||||
cols: number;
|
||||
}
|
||||
|
||||
export function calculateServiceHealthData(
|
||||
usageDetails: UsageDetail[]
|
||||
): ServiceHealthData {
|
||||
export function calculateServiceHealthData(usageDetails: UsageDetail[]): ServiceHealthData {
|
||||
const ROWS = 7;
|
||||
const COLS = 96;
|
||||
const BLOCK_COUNT = ROWS * COLS; // 672
|
||||
@@ -1386,8 +1522,15 @@ export function calculateServiceHealthData(
|
||||
|
||||
usageDetails.forEach((detail) => {
|
||||
const timestamp =
|
||||
typeof detail.__timestampMs === 'number' ? detail.__timestampMs : Date.parse(detail.timestamp);
|
||||
if (!Number.isFinite(timestamp) || timestamp <= 0 || timestamp < windowStart || timestamp > now) {
|
||||
typeof detail.__timestampMs === 'number'
|
||||
? detail.__timestampMs
|
||||
: Date.parse(detail.timestamp);
|
||||
if (
|
||||
!Number.isFinite(timestamp) ||
|
||||
timestamp <= 0 ||
|
||||
timestamp < windowStart ||
|
||||
timestamp > now
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1444,7 +1587,10 @@ export function calculateServiceHealthData(
|
||||
};
|
||||
}
|
||||
|
||||
export function computeKeyStats(usageData: unknown, masker: (val: string) => string = maskApiKey): KeyStats {
|
||||
export function computeKeyStats(
|
||||
usageData: unknown,
|
||||
masker: (val: string) => string = maskApiKey
|
||||
): KeyStats {
|
||||
const apis = getApisRecord(usageData);
|
||||
if (!apis) {
|
||||
return { bySource: {}, byAuthIndex: {} };
|
||||
@@ -1499,7 +1645,7 @@ export function computeKeyStats(usageData: unknown, masker: (val: string) => str
|
||||
|
||||
return {
|
||||
bySource: sourceStats,
|
||||
byAuthIndex: authIndexStats
|
||||
byAuthIndex: authIndexStats,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1586,7 +1732,9 @@ export function buildHourlyTokenBreakdown(
|
||||
|
||||
details.forEach((detail) => {
|
||||
const timestamp =
|
||||
typeof detail.__timestampMs === 'number' ? detail.__timestampMs : Date.parse(detail.timestamp);
|
||||
typeof detail.__timestampMs === 'number'
|
||||
? detail.__timestampMs
|
||||
: Date.parse(detail.timestamp);
|
||||
if (!Number.isFinite(timestamp) || timestamp <= 0) return;
|
||||
const normalized = new Date(timestamp);
|
||||
normalized.setMinutes(0, 0, 0);
|
||||
@@ -1601,9 +1749,10 @@ export function buildHourlyTokenBreakdown(
|
||||
const output = typeof tokens.output_tokens === 'number' ? Math.max(tokens.output_tokens, 0) : 0;
|
||||
const cached = Math.max(
|
||||
typeof tokens.cached_tokens === 'number' ? Math.max(tokens.cached_tokens, 0) : 0,
|
||||
typeof tokens.cache_tokens === 'number' ? Math.max(tokens.cache_tokens, 0) : 0,
|
||||
typeof tokens.cache_tokens === 'number' ? Math.max(tokens.cache_tokens, 0) : 0
|
||||
);
|
||||
const reasoning = typeof tokens.reasoning_tokens === 'number' ? Math.max(tokens.reasoning_tokens, 0) : 0;
|
||||
const reasoning =
|
||||
typeof tokens.reasoning_tokens === 'number' ? Math.max(tokens.reasoning_tokens, 0) : 0;
|
||||
|
||||
dataByCategory.input[bucketIndex] += input;
|
||||
dataByCategory.output[bucketIndex] += output;
|
||||
@@ -1625,7 +1774,9 @@ export function buildDailyTokenBreakdown(usageData: unknown): TokenBreakdownSeri
|
||||
|
||||
details.forEach((detail) => {
|
||||
const timestamp =
|
||||
typeof detail.__timestampMs === 'number' ? detail.__timestampMs : Date.parse(detail.timestamp);
|
||||
typeof detail.__timestampMs === 'number'
|
||||
? detail.__timestampMs
|
||||
: Date.parse(detail.timestamp);
|
||||
if (!Number.isFinite(timestamp) || timestamp <= 0) return;
|
||||
const dayLabel = formatDayLabel(new Date(timestamp));
|
||||
if (!dayLabel) return;
|
||||
@@ -1639,9 +1790,10 @@ export function buildDailyTokenBreakdown(usageData: unknown): TokenBreakdownSeri
|
||||
const output = typeof tokens.output_tokens === 'number' ? Math.max(tokens.output_tokens, 0) : 0;
|
||||
const cached = Math.max(
|
||||
typeof tokens.cached_tokens === 'number' ? Math.max(tokens.cached_tokens, 0) : 0,
|
||||
typeof tokens.cache_tokens === 'number' ? Math.max(tokens.cache_tokens, 0) : 0,
|
||||
typeof tokens.cache_tokens === 'number' ? Math.max(tokens.cache_tokens, 0) : 0
|
||||
);
|
||||
const reasoning = typeof tokens.reasoning_tokens === 'number' ? Math.max(tokens.reasoning_tokens, 0) : 0;
|
||||
const reasoning =
|
||||
typeof tokens.reasoning_tokens === 'number' ? Math.max(tokens.reasoning_tokens, 0) : 0;
|
||||
|
||||
dayMap[dayLabel].input += input;
|
||||
dayMap[dayLabel].output += output;
|
||||
@@ -1699,7 +1851,9 @@ export function buildHourlyCostSeries(
|
||||
|
||||
details.forEach((detail) => {
|
||||
const timestamp =
|
||||
typeof detail.__timestampMs === 'number' ? detail.__timestampMs : Date.parse(detail.timestamp);
|
||||
typeof detail.__timestampMs === 'number'
|
||||
? detail.__timestampMs
|
||||
: Date.parse(detail.timestamp);
|
||||
if (!Number.isFinite(timestamp) || timestamp <= 0) return;
|
||||
const normalized = new Date(timestamp);
|
||||
normalized.setMinutes(0, 0, 0);
|
||||
@@ -1732,7 +1886,9 @@ export function buildDailyCostSeries(
|
||||
|
||||
details.forEach((detail) => {
|
||||
const timestamp =
|
||||
typeof detail.__timestampMs === 'number' ? detail.__timestampMs : Date.parse(detail.timestamp);
|
||||
typeof detail.__timestampMs === 'number'
|
||||
? detail.__timestampMs
|
||||
: Date.parse(detail.timestamp);
|
||||
if (!Number.isFinite(timestamp) || timestamp <= 0) return;
|
||||
const dayLabel = formatDayLabel(new Date(timestamp));
|
||||
if (!dayLabel) return;
|
||||
|
||||
@@ -0,0 +1,199 @@
|
||||
import i18n from '@/i18n';
|
||||
|
||||
export const LATENCY_SOURCE_FIELD = 'latency_ms';
|
||||
export const LATENCY_SOURCE_UNIT = 'ms';
|
||||
|
||||
export interface LatencyStats {
|
||||
averageMs: number | null;
|
||||
totalMs: number | null;
|
||||
sampleCount: number;
|
||||
}
|
||||
|
||||
export interface DurationFormatOptions {
|
||||
maxUnits?: number;
|
||||
invalidText?: string;
|
||||
secondDecimals?: number | 'auto';
|
||||
locale?: string;
|
||||
}
|
||||
|
||||
export interface LatencyAccumulator {
|
||||
totalMs: number;
|
||||
sampleCount: number;
|
||||
}
|
||||
|
||||
const isRecord = (value: unknown): value is Record<string, unknown> =>
|
||||
value !== null && typeof value === 'object' && !Array.isArray(value);
|
||||
|
||||
const normalizeDurationMaxUnits = (value: number | undefined): number => {
|
||||
const parsed = Number(value);
|
||||
if (!Number.isFinite(parsed) || parsed <= 0) {
|
||||
return 2;
|
||||
}
|
||||
return Math.min(Math.floor(parsed), 4);
|
||||
};
|
||||
|
||||
const resolveSecondDecimalPlaces = (
|
||||
seconds: number,
|
||||
secondDecimals: number | 'auto' | undefined
|
||||
): number => {
|
||||
if (secondDecimals === 'auto' || secondDecimals === undefined) {
|
||||
return seconds < 10 ? 2 : 1;
|
||||
}
|
||||
|
||||
const parsed = Math.floor(Number(secondDecimals));
|
||||
if (!Number.isFinite(parsed) || parsed < 0) {
|
||||
return seconds < 10 ? 2 : 1;
|
||||
}
|
||||
return Math.min(parsed, 3);
|
||||
};
|
||||
|
||||
const resolveDurationLocale = (locale?: string): string | undefined =>
|
||||
locale?.trim() || i18n.resolvedLanguage || i18n.language || undefined;
|
||||
|
||||
const formatDurationNumber = (
|
||||
value: number,
|
||||
locale: string | undefined,
|
||||
options: Intl.NumberFormatOptions = {}
|
||||
): string => {
|
||||
try {
|
||||
return new Intl.NumberFormat(locale, {
|
||||
useGrouping: false,
|
||||
...options,
|
||||
}).format(value);
|
||||
} catch {
|
||||
return String(value);
|
||||
}
|
||||
};
|
||||
|
||||
const getDurationUnitLabel = (unit: 'd' | 'h' | 'm' | 's' | 'ms'): string =>
|
||||
i18n.t(`usage_stats.duration_unit_${unit}`, { defaultValue: unit });
|
||||
|
||||
const formatDurationPart = (
|
||||
value: number,
|
||||
unit: 'd' | 'h' | 'm' | 's' | 'ms',
|
||||
locale: string | undefined,
|
||||
options: Intl.NumberFormatOptions = {}
|
||||
): string => `${formatDurationNumber(value, locale, options)}${getDurationUnitLabel(unit)}`;
|
||||
|
||||
/**
|
||||
* 从后端字段 latency_ms 提取耗时,并按毫秒解释。
|
||||
*/
|
||||
export function extractLatencyMs(detail: unknown): number | null {
|
||||
const record = isRecord(detail) ? detail : null;
|
||||
const rawValue = record?.[LATENCY_SOURCE_FIELD];
|
||||
if (
|
||||
rawValue === null ||
|
||||
rawValue === undefined ||
|
||||
(typeof rawValue === 'string' && rawValue.trim() === '')
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const parsed = Number(rawValue);
|
||||
if (!Number.isFinite(parsed) || parsed < 0) {
|
||||
return null;
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
export const createLatencyAccumulator = (): LatencyAccumulator => ({
|
||||
totalMs: 0,
|
||||
sampleCount: 0,
|
||||
});
|
||||
|
||||
export const addLatencySample = (
|
||||
accumulator: LatencyAccumulator,
|
||||
latencyMs: number | null | undefined
|
||||
): void => {
|
||||
if (latencyMs === null || latencyMs === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
const parsed = Number(latencyMs);
|
||||
if (!Number.isFinite(parsed) || parsed < 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
accumulator.totalMs += parsed;
|
||||
accumulator.sampleCount += 1;
|
||||
};
|
||||
|
||||
export const finalizeLatencyStats = (accumulator: LatencyAccumulator): LatencyStats => ({
|
||||
averageMs: accumulator.sampleCount > 0 ? accumulator.totalMs / accumulator.sampleCount : null,
|
||||
totalMs: accumulator.sampleCount > 0 ? accumulator.totalMs : null,
|
||||
sampleCount: accumulator.sampleCount,
|
||||
});
|
||||
|
||||
/**
|
||||
* 从明细列表计算耗时统计
|
||||
*/
|
||||
export function calculateLatencyStatsFromDetails(details: Iterable<unknown>): LatencyStats {
|
||||
const accumulator = createLatencyAccumulator();
|
||||
for (const detail of details) {
|
||||
addLatencySample(accumulator, extractLatencyMs(detail));
|
||||
}
|
||||
return finalizeLatencyStats(accumulator);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按当前语言格式化耗时显示。
|
||||
*/
|
||||
export function formatDurationMs(
|
||||
value: number | null | undefined,
|
||||
options: DurationFormatOptions = {}
|
||||
): string {
|
||||
const invalidText = options.invalidText ?? '--';
|
||||
if (value === null || value === undefined) {
|
||||
return invalidText;
|
||||
}
|
||||
|
||||
const parsed = Number(value);
|
||||
if (!Number.isFinite(parsed) || parsed < 0) {
|
||||
return invalidText;
|
||||
}
|
||||
|
||||
const locale = resolveDurationLocale(options.locale);
|
||||
|
||||
if (parsed < 1000) {
|
||||
return formatDurationPart(Math.round(parsed), 'ms', locale);
|
||||
}
|
||||
|
||||
const seconds = parsed / 1000;
|
||||
if (seconds < 60) {
|
||||
const secondDecimalPlaces = resolveSecondDecimalPlaces(seconds, options.secondDecimals);
|
||||
return formatDurationPart(seconds, 's', locale, {
|
||||
minimumFractionDigits: 0,
|
||||
maximumFractionDigits: secondDecimalPlaces,
|
||||
});
|
||||
}
|
||||
|
||||
const totalSeconds = Math.floor(seconds);
|
||||
let remainingSeconds = totalSeconds;
|
||||
const days = Math.floor(remainingSeconds / 86_400);
|
||||
remainingSeconds -= days * 86_400;
|
||||
const hours = Math.floor(remainingSeconds / 3_600);
|
||||
remainingSeconds -= hours * 3_600;
|
||||
const minutes = Math.floor(remainingSeconds / 60);
|
||||
remainingSeconds -= minutes * 60;
|
||||
|
||||
const parts = [
|
||||
{ unit: 'd' as const, value: days },
|
||||
{ unit: 'h' as const, value: hours },
|
||||
{ unit: 'm' as const, value: minutes },
|
||||
{ unit: 's' as const, value: remainingSeconds },
|
||||
].filter((part) => part.value > 0);
|
||||
|
||||
if (!parts.length) {
|
||||
return formatDurationPart(0, 's', locale);
|
||||
}
|
||||
|
||||
return parts
|
||||
.slice(0, normalizeDurationMaxUnits(options.maxUnits))
|
||||
.map((part, index) =>
|
||||
formatDurationPart(part.value, part.unit, locale, {
|
||||
minimumIntegerDigits: index > 0 && (part.unit === 'm' || part.unit === 's') ? 2 : 1,
|
||||
maximumFractionDigits: 0,
|
||||
})
|
||||
)
|
||||
.join(' ');
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { UsageDetail } from '@/utils/usage';
|
||||
|
||||
export type UsageDetailsBySource = Map<string, UsageDetail[]>;
|
||||
|
||||
const EMPTY_USAGE_DETAILS: UsageDetail[] = [];
|
||||
|
||||
export function indexUsageDetailsBySource(usageDetails: UsageDetail[]): UsageDetailsBySource {
|
||||
const map: UsageDetailsBySource = new Map();
|
||||
|
||||
usageDetails.forEach((detail) => {
|
||||
const sourceId = detail.source;
|
||||
if (!sourceId) return;
|
||||
|
||||
const bucket = map.get(sourceId);
|
||||
if (bucket) {
|
||||
bucket.push(detail);
|
||||
} else {
|
||||
map.set(sourceId, [detail]);
|
||||
}
|
||||
});
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
export function collectUsageDetailsForCandidates(
|
||||
usageDetailsBySource: UsageDetailsBySource,
|
||||
candidates: Iterable<string>
|
||||
): UsageDetail[] {
|
||||
let firstDetails: UsageDetail[] | null = null;
|
||||
let merged: UsageDetail[] | null = null;
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const details = usageDetailsBySource.get(candidate);
|
||||
if (!details || details.length === 0) continue;
|
||||
|
||||
if (!firstDetails) {
|
||||
firstDetails = details;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!merged) {
|
||||
merged = [...firstDetails];
|
||||
}
|
||||
for (const detail of details) {
|
||||
merged.push(detail);
|
||||
}
|
||||
}
|
||||
|
||||
return merged ?? firstDetails ?? EMPTY_USAGE_DETAILS;
|
||||
}
|
||||
Reference in New Issue
Block a user