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
12 Commits
@@ -1,20 +0,0 @@
|
||||
module.exports = {
|
||||
root: true,
|
||||
env: { browser: true, es2020: true },
|
||||
extends: [
|
||||
'eslint:recommended',
|
||||
'plugin:@typescript-eslint/recommended',
|
||||
'plugin:react-hooks/recommended',
|
||||
],
|
||||
ignorePatterns: ['dist', '.eslintrc.cjs'],
|
||||
parser: '@typescript-eslint/parser',
|
||||
plugins: ['react-refresh'],
|
||||
rules: {
|
||||
'react-refresh/only-export-components': [
|
||||
'warn',
|
||||
{ allowConstantExport: true },
|
||||
],
|
||||
'@typescript-eslint/no-explicit-any': 'warn',
|
||||
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
|
||||
},
|
||||
};
|
||||
@@ -22,7 +22,7 @@ jobs:
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: '18'
|
||||
node-version: '20'
|
||||
cache: 'npm'
|
||||
|
||||
- name: Install dependencies
|
||||
|
||||
Generated
+14
@@ -9,6 +9,7 @@
|
||||
"version": "0.0.0",
|
||||
"dependencies": {
|
||||
"@codemirror/lang-yaml": "^6.1.2",
|
||||
"@codemirror/merge": "^6.12.0",
|
||||
"@uiw/react-codemirror": "^4.25.3",
|
||||
"axios": "^1.13.2",
|
||||
"chart.js": "^4.5.1",
|
||||
@@ -429,6 +430,19 @@
|
||||
"crelt": "^1.0.5"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/merge": {
|
||||
"version": "6.12.0",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/merge/-/merge-6.12.0.tgz",
|
||||
"integrity": "sha512-o+36bbapcEHf4Ux75pZ4CKjMBUd14parA0uozvWVlacaT+uxaA3DDefEvWYjngsKU+qsrDe/HOOfsw0Q72pLjA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@codemirror/language": "^6.0.0",
|
||||
"@codemirror/state": "^6.0.0",
|
||||
"@codemirror/view": "^6.17.0",
|
||||
"@lezer/highlight": "^1.0.0",
|
||||
"style-mod": "^4.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@codemirror/search": {
|
||||
"version": "6.5.11",
|
||||
"resolved": "https://registry.npmjs.org/@codemirror/search/-/search-6.5.11.tgz",
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@codemirror/lang-yaml": "^6.1.2",
|
||||
"@codemirror/merge": "^6.12.0",
|
||||
"@uiw/react-codemirror": "^4.25.3",
|
||||
"axios": "^1.13.2",
|
||||
"chart.js": "^4.5.1",
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
@use '../../styles/variables' as *;
|
||||
@use '../../styles/mixins' as *;
|
||||
|
||||
.diffModal {
|
||||
:global(.modal-body) {
|
||||
padding: $spacing-md $spacing-lg;
|
||||
max-height: none;
|
||||
overflow: hidden;
|
||||
}
|
||||
}
|
||||
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 70vh;
|
||||
min-height: 420px;
|
||||
}
|
||||
|
||||
.emptyState {
|
||||
flex: 1;
|
||||
border: 1px dashed var(--border-color);
|
||||
border-radius: $radius-md;
|
||||
background: var(--bg-secondary);
|
||||
color: var(--text-secondary);
|
||||
font-size: 14px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
.diffList {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: $spacing-sm;
|
||||
overflow: auto;
|
||||
padding-right: 2px;
|
||||
}
|
||||
|
||||
.diffCard {
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: $radius-md;
|
||||
background: var(--bg-secondary);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.diffCardHeader {
|
||||
padding: 8px 10px;
|
||||
border-bottom: 1px dashed var(--border-color);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--text-secondary);
|
||||
background: color-mix(in srgb, var(--bg-primary) 92%, transparent);
|
||||
}
|
||||
|
||||
.diffColumns {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: $spacing-sm;
|
||||
padding: $spacing-sm;
|
||||
}
|
||||
|
||||
.diffColumn {
|
||||
min-width: 0;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: $radius-sm;
|
||||
overflow: hidden;
|
||||
background: var(--bg-primary);
|
||||
}
|
||||
|
||||
.diffColumnHeader {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
justify-content: space-between;
|
||||
gap: $spacing-sm;
|
||||
padding: 8px 10px;
|
||||
border-bottom: 1px solid var(--border-color);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--text-secondary);
|
||||
background: var(--bg-secondary);
|
||||
}
|
||||
|
||||
.lineMeta {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.lineRange {
|
||||
font-size: 11px;
|
||||
color: var(--text-secondary);
|
||||
font-family: 'Consolas', 'Monaco', 'Menlo', monospace;
|
||||
}
|
||||
|
||||
.contextRange {
|
||||
font-size: 11px;
|
||||
color: var(--text-tertiary);
|
||||
font-family: 'Consolas', 'Monaco', 'Menlo', monospace;
|
||||
}
|
||||
|
||||
.codeList {
|
||||
overflow: auto;
|
||||
max-height: 280px;
|
||||
font-family: 'Consolas', 'Monaco', 'Menlo', monospace;
|
||||
}
|
||||
|
||||
.codeLine {
|
||||
display: grid;
|
||||
grid-template-columns: 52px minmax(0, 1fr);
|
||||
align-items: start;
|
||||
border-top: 1px solid color-mix(in srgb, var(--border-color) 55%, transparent);
|
||||
}
|
||||
|
||||
.codeLine:first-child {
|
||||
border-top: none;
|
||||
}
|
||||
|
||||
.codeLineChanged {
|
||||
background: color-mix(in srgb, var(--primary-color) 8%, transparent);
|
||||
}
|
||||
|
||||
.codeLineNumber {
|
||||
padding: 7px 10px 7px 8px;
|
||||
text-align: right;
|
||||
font-size: 11px;
|
||||
color: var(--text-tertiary);
|
||||
border-right: 1px solid color-mix(in srgb, var(--border-color) 55%, transparent);
|
||||
background: color-mix(in srgb, var(--bg-secondary) 90%, transparent);
|
||||
font-variant-numeric: tabular-nums;
|
||||
user-select: none;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.codeLineText {
|
||||
padding: 7px 10px;
|
||||
font-size: 12px;
|
||||
line-height: 1.45;
|
||||
color: var(--text-primary);
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
display: block;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
@include mobile {
|
||||
.content {
|
||||
height: 65vh;
|
||||
min-height: 360px;
|
||||
}
|
||||
|
||||
.diffColumns {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.lineMeta {
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 1px;
|
||||
}
|
||||
|
||||
.codeLine {
|
||||
grid-template-columns: 44px minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.codeLineNumber {
|
||||
padding: 6px 6px 6px 4px;
|
||||
font-size: 10px;
|
||||
}
|
||||
|
||||
.codeLineText {
|
||||
padding: 6px 8px;
|
||||
font-size: 11px;
|
||||
line-height: 1.4;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Text } from '@codemirror/state';
|
||||
import { Chunk } from '@codemirror/merge';
|
||||
import { Modal } from '@/components/ui/Modal';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import styles from './DiffModal.module.scss';
|
||||
|
||||
type DiffModalProps = {
|
||||
open: boolean;
|
||||
original: string;
|
||||
modified: string;
|
||||
onConfirm: () => void;
|
||||
onCancel: () => void;
|
||||
loading?: boolean;
|
||||
};
|
||||
|
||||
type DiffChunkCard = {
|
||||
id: string;
|
||||
current: DiffSide;
|
||||
modified: DiffSide;
|
||||
};
|
||||
|
||||
type LineRange = {
|
||||
start: number;
|
||||
end: number;
|
||||
};
|
||||
|
||||
type DiffSideLine = {
|
||||
lineNumber: number;
|
||||
text: string;
|
||||
changed: boolean;
|
||||
};
|
||||
|
||||
type DiffSide = {
|
||||
changedRangeLabel: string;
|
||||
contextRangeLabel: string;
|
||||
lines: DiffSideLine[];
|
||||
};
|
||||
|
||||
const DIFF_CONTEXT_LINES = 2;
|
||||
|
||||
const clampPos = (doc: Text, pos: number) => Math.max(0, Math.min(pos, doc.length));
|
||||
|
||||
const getLineRangeLabel = (range: LineRange): string => {
|
||||
return range.start === range.end ? String(range.start) : `${range.start}-${range.end}`;
|
||||
};
|
||||
|
||||
const getChangedLineRange = (doc: Text, from: number, to: number): LineRange => {
|
||||
const start = clampPos(doc, from);
|
||||
const end = clampPos(doc, to);
|
||||
if (start === end) {
|
||||
const linePos = Math.min(start, doc.length);
|
||||
const anchorLine = doc.lineAt(linePos).number;
|
||||
return { start: anchorLine, end: anchorLine };
|
||||
}
|
||||
const startLine = doc.lineAt(start).number;
|
||||
const endLine = doc.lineAt(Math.max(start, end - 1)).number;
|
||||
return { start: startLine, end: endLine };
|
||||
};
|
||||
|
||||
const expandContextRange = (doc: Text, range: LineRange): LineRange => ({
|
||||
start: Math.max(1, range.start - DIFF_CONTEXT_LINES),
|
||||
end: Math.min(doc.lines, range.end + DIFF_CONTEXT_LINES)
|
||||
});
|
||||
|
||||
const buildSideLines = (doc: Text, contextRange: LineRange, changedRange: LineRange): DiffSideLine[] => {
|
||||
const lines: DiffSideLine[] = [];
|
||||
for (let lineNumber = contextRange.start; lineNumber <= contextRange.end; lineNumber += 1) {
|
||||
lines.push({
|
||||
lineNumber,
|
||||
text: doc.line(lineNumber).text,
|
||||
changed: lineNumber >= changedRange.start && lineNumber <= changedRange.end
|
||||
});
|
||||
}
|
||||
return lines;
|
||||
};
|
||||
|
||||
export function DiffModal({
|
||||
open,
|
||||
original,
|
||||
modified,
|
||||
onConfirm,
|
||||
onCancel,
|
||||
loading = false
|
||||
}: DiffModalProps) {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const diffCards = useMemo<DiffChunkCard[]>(() => {
|
||||
const currentDoc = Text.of(original.split('\n'));
|
||||
const modifiedDoc = Text.of(modified.split('\n'));
|
||||
const chunks = Chunk.build(currentDoc, modifiedDoc);
|
||||
|
||||
return chunks.map((chunk, index) => {
|
||||
const currentChangedRange = getChangedLineRange(currentDoc, chunk.fromA, chunk.toA);
|
||||
const modifiedChangedRange = getChangedLineRange(modifiedDoc, chunk.fromB, chunk.toB);
|
||||
const currentContextRange = expandContextRange(currentDoc, currentChangedRange);
|
||||
const modifiedContextRange = expandContextRange(modifiedDoc, modifiedChangedRange);
|
||||
|
||||
return {
|
||||
id: `${index}-${chunk.fromA}-${chunk.toA}-${chunk.fromB}-${chunk.toB}`,
|
||||
current: {
|
||||
changedRangeLabel: getLineRangeLabel(currentChangedRange),
|
||||
contextRangeLabel: getLineRangeLabel(currentContextRange),
|
||||
lines: buildSideLines(currentDoc, currentContextRange, currentChangedRange)
|
||||
},
|
||||
modified: {
|
||||
changedRangeLabel: getLineRangeLabel(modifiedChangedRange),
|
||||
contextRangeLabel: getLineRangeLabel(modifiedContextRange),
|
||||
lines: buildSideLines(modifiedDoc, modifiedContextRange, modifiedChangedRange)
|
||||
}
|
||||
};
|
||||
});
|
||||
}, [modified, original]);
|
||||
|
||||
return (
|
||||
<Modal
|
||||
open={open}
|
||||
title={t('config_management.diff.title')}
|
||||
onClose={onCancel}
|
||||
width="min(1200px, 90vw)"
|
||||
className={styles.diffModal}
|
||||
closeDisabled={loading}
|
||||
footer={
|
||||
<>
|
||||
<Button variant="secondary" onClick={onCancel} disabled={loading}>
|
||||
{t('common.cancel')}
|
||||
</Button>
|
||||
<Button onClick={onConfirm} loading={loading} disabled={loading}>
|
||||
{t('config_management.diff.confirm')}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className={styles.content}>
|
||||
{diffCards.length === 0 ? (
|
||||
<div className={styles.emptyState}>{t('config_management.diff.no_changes')}</div>
|
||||
) : (
|
||||
<div className={styles.diffList}>
|
||||
{diffCards.map((card, index) => (
|
||||
<article key={card.id} className={styles.diffCard}>
|
||||
<div className={styles.diffCardHeader}>#{index + 1}</div>
|
||||
<div className={styles.diffColumns}>
|
||||
<section className={styles.diffColumn}>
|
||||
<header className={styles.diffColumnHeader}>
|
||||
<span>{t('config_management.diff.current')}</span>
|
||||
<span className={styles.lineMeta}>
|
||||
<span className={styles.lineRange}>L{card.current.changedRangeLabel}</span>
|
||||
<span className={styles.contextRange}>
|
||||
±{DIFF_CONTEXT_LINES}: L{card.current.contextRangeLabel}
|
||||
</span>
|
||||
</span>
|
||||
</header>
|
||||
<div className={styles.codeList}>
|
||||
{card.current.lines.map((line) => (
|
||||
<div
|
||||
key={`${card.id}-a-${line.lineNumber}`}
|
||||
className={`${styles.codeLine} ${line.changed ? styles.codeLineChanged : ''}`}
|
||||
>
|
||||
<span className={styles.codeLineNumber}>{line.lineNumber}</span>
|
||||
<code className={styles.codeLineText}>{line.text || ' '}</code>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
<section className={styles.diffColumn}>
|
||||
<header className={styles.diffColumnHeader}>
|
||||
<span>{t('config_management.diff.modified')}</span>
|
||||
<span className={styles.lineMeta}>
|
||||
<span className={styles.lineRange}>L{card.modified.changedRangeLabel}</span>
|
||||
<span className={styles.contextRange}>
|
||||
±{DIFF_CONTEXT_LINES}: L{card.modified.contextRangeLabel}
|
||||
</span>
|
||||
</span>
|
||||
</header>
|
||||
<div className={styles.codeList}>
|
||||
{card.modified.lines.map((line) => (
|
||||
<div
|
||||
key={`${card.id}-b-${line.lineNumber}`}
|
||||
className={`${styles.codeLine} ${line.changed ? styles.codeLineChanged : ''}`}
|
||||
>
|
||||
<span className={styles.codeLineNumber}>{line.lineNumber}</span>
|
||||
<code className={styles.codeLineText}>{line.text || ' '}</code>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</article>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Modal>
|
||||
);
|
||||
}
|
||||
@@ -106,6 +106,13 @@ function ApiKeysCardEditor({
|
||||
const [inputValue, setInputValue] = useState('');
|
||||
const [formError, setFormError] = useState('');
|
||||
|
||||
function generateSecureApiKey(): string {
|
||||
const charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
|
||||
const array = new Uint8Array(17);
|
||||
crypto.getRandomValues(array);
|
||||
return 'sk-' + Array.from(array, (b) => charset[b % charset.length]).join('');
|
||||
}
|
||||
|
||||
const openAddModal = () => {
|
||||
setEditingIndex(null);
|
||||
setInputValue('');
|
||||
@@ -162,6 +169,11 @@ function ApiKeysCardEditor({
|
||||
);
|
||||
};
|
||||
|
||||
const handleGenerate = () => {
|
||||
setInputValue(generateSecureApiKey());
|
||||
setFormError('');
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="form-group" style={{ marginBottom: 0 }}>
|
||||
<div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
|
||||
@@ -233,6 +245,18 @@ function ApiKeysCardEditor({
|
||||
disabled={disabled}
|
||||
error={formError || undefined}
|
||||
hint={t('config_management.visual.api_keys.input_hint')}
|
||||
style={{ paddingRight: 148 }}
|
||||
rightElement={
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={handleGenerate}
|
||||
disabled={disabled}
|
||||
>
|
||||
{t('config_management.visual.api_keys.generate')}
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
</Modal>
|
||||
</div>
|
||||
|
||||
@@ -43,6 +43,19 @@ export const normalizeOpenAIBaseUrl = (baseUrl: string): string => {
|
||||
return trimmed;
|
||||
};
|
||||
|
||||
export const normalizeClaudeBaseUrl = (baseUrl: string): string => {
|
||||
let trimmed = String(baseUrl || '').trim();
|
||||
if (!trimmed) {
|
||||
return 'https://api.anthropic.com';
|
||||
}
|
||||
trimmed = trimmed.replace(/\/?v0\/management\/?$/i, '');
|
||||
trimmed = trimmed.replace(/\/+$/g, '');
|
||||
if (!/^https?:\/\//i.test(trimmed)) {
|
||||
trimmed = `http://${trimmed}`;
|
||||
}
|
||||
return trimmed;
|
||||
};
|
||||
|
||||
export const buildOpenAIModelsEndpoint = (baseUrl: string): string => {
|
||||
const trimmed = normalizeOpenAIBaseUrl(baseUrl);
|
||||
if (!trimmed) return '';
|
||||
@@ -58,6 +71,18 @@ export const buildOpenAIChatCompletionsEndpoint = (baseUrl: string): string => {
|
||||
return `${trimmed}/chat/completions`;
|
||||
};
|
||||
|
||||
export const buildClaudeMessagesEndpoint = (baseUrl: string): string => {
|
||||
const trimmed = normalizeClaudeBaseUrl(baseUrl);
|
||||
if (!trimmed) return '';
|
||||
if (trimmed.endsWith('/v1/messages')) {
|
||||
return trimmed;
|
||||
}
|
||||
if (trimmed.endsWith('/v1')) {
|
||||
return `${trimmed}/messages`;
|
||||
}
|
||||
return `${trimmed}/v1/messages`;
|
||||
};
|
||||
|
||||
// 根据 source (apiKey) 获取统计数据 - 与旧版逻辑一致
|
||||
export const getStatsBySource = (
|
||||
apiKey: string,
|
||||
|
||||
@@ -24,7 +24,7 @@ type QuotaSetter<T> = (updater: QuotaUpdater<T>) => void;
|
||||
|
||||
type ViewMode = 'paged' | 'all';
|
||||
|
||||
const MAX_ITEMS_PER_PAGE = 14;
|
||||
const MAX_ITEMS_PER_PAGE = 25;
|
||||
const MAX_SHOW_ALL_THRESHOLD = 30;
|
||||
|
||||
interface QuotaPaginationState<T> {
|
||||
|
||||
@@ -2,7 +2,7 @@ import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { LoadingSpinner } from '@/components/ui/LoadingSpinner';
|
||||
import { ToggleSwitch } from '@/components/ui/ToggleSwitch';
|
||||
import { IconBot, IconCode, IconDownload, IconInfo, IconTrash2 } from '@/components/ui/icons';
|
||||
import { IconBot, IconCheck, IconCode, IconDownload, IconInfo, IconTrash2 } from '@/components/ui/icons';
|
||||
import { ProviderStatusBar } from '@/components/providers/ProviderStatusBar';
|
||||
import type { AuthFileItem } from '@/types';
|
||||
import { resolveAuthProvider } from '@/utils/quota';
|
||||
@@ -25,6 +25,7 @@ import styles from '@/pages/AuthFilesPage.module.scss';
|
||||
|
||||
export type AuthFileCardProps = {
|
||||
file: AuthFileItem;
|
||||
selected: boolean;
|
||||
resolvedTheme: ResolvedTheme;
|
||||
disableControls: boolean;
|
||||
deleting: string | null;
|
||||
@@ -38,6 +39,7 @@ export type AuthFileCardProps = {
|
||||
onOpenPrefixProxyEditor: (name: string) => void;
|
||||
onDelete: (name: string) => void;
|
||||
onToggleStatus: (file: AuthFileItem, enabled: boolean) => void;
|
||||
onToggleSelect: (name: string) => void;
|
||||
};
|
||||
|
||||
const resolveQuotaType = (file: AuthFileItem): QuotaProviderType | null => {
|
||||
@@ -50,6 +52,7 @@ export function AuthFileCard(props: AuthFileCardProps) {
|
||||
const { t } = useTranslation();
|
||||
const {
|
||||
file,
|
||||
selected,
|
||||
resolvedTheme,
|
||||
disableControls,
|
||||
deleting,
|
||||
@@ -62,7 +65,8 @@ export function AuthFileCard(props: AuthFileCardProps) {
|
||||
onDownload,
|
||||
onOpenPrefixProxyEditor,
|
||||
onDelete,
|
||||
onToggleStatus
|
||||
onToggleStatus,
|
||||
onToggleSelect
|
||||
} = props;
|
||||
|
||||
const fileStats = resolveAuthFileStats(file, keyStats);
|
||||
@@ -92,11 +96,23 @@ export function AuthFileCard(props: AuthFileCardProps) {
|
||||
|
||||
return (
|
||||
<div
|
||||
className={`${styles.fileCard} ${providerCardClass} ${file.disabled ? styles.fileCardDisabled : ''}`}
|
||||
className={`${styles.fileCard} ${providerCardClass} ${selected ? styles.fileCardSelected : ''} ${file.disabled ? styles.fileCardDisabled : ''}`}
|
||||
>
|
||||
<div className={styles.fileCardLayout}>
|
||||
<div className={styles.fileCardMain}>
|
||||
<div className={styles.cardHeader}>
|
||||
{!isRuntimeOnly && (
|
||||
<button
|
||||
type="button"
|
||||
className={`${styles.selectionToggle} ${selected ? styles.selectionToggleActive : ''}`}
|
||||
onClick={() => onToggleSelect(file.name)}
|
||||
aria-label={selected ? t('auth_files.batch_deselect') : t('auth_files.batch_select_all')}
|
||||
aria-pressed={selected}
|
||||
title={selected ? t('auth_files.batch_deselect') : t('auth_files.batch_select_all')}
|
||||
>
|
||||
{selected && <IconCheck size={12} />}
|
||||
</button>
|
||||
)}
|
||||
<span
|
||||
className={styles.typeBadge}
|
||||
style={{
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useCallback, useRef, useState, type ChangeEvent, type RefObject } from 'react';
|
||||
import { useCallback, useEffect, useRef, useState, type ChangeEvent, type RefObject } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { authFilesApi } from '@/services/api';
|
||||
import { apiClient } from '@/services/api/client';
|
||||
@@ -15,6 +15,8 @@ type DeleteAllOptions = {
|
||||
|
||||
export type UseAuthFilesDataResult = {
|
||||
files: AuthFileItem[];
|
||||
selectedFiles: Set<string>;
|
||||
selectionCount: number;
|
||||
loading: boolean;
|
||||
error: string;
|
||||
uploading: boolean;
|
||||
@@ -29,6 +31,11 @@ export type UseAuthFilesDataResult = {
|
||||
handleDeleteAll: (options: DeleteAllOptions) => void;
|
||||
handleDownload: (name: string) => Promise<void>;
|
||||
handleStatusToggle: (item: AuthFileItem, enabled: boolean) => Promise<void>;
|
||||
toggleSelect: (name: string) => void;
|
||||
selectAllVisible: (visibleFiles: AuthFileItem[]) => void;
|
||||
deselectAll: () => void;
|
||||
batchSetStatus: (names: string[], enabled: boolean) => Promise<void>;
|
||||
batchDelete: (names: string[]) => void;
|
||||
};
|
||||
|
||||
export type UseAuthFilesDataOptions = {
|
||||
@@ -47,8 +54,50 @@ export function useAuthFilesData(options: UseAuthFilesDataOptions): UseAuthFiles
|
||||
const [deleting, setDeleting] = useState<string | null>(null);
|
||||
const [deletingAll, setDeletingAll] = useState(false);
|
||||
const [statusUpdating, setStatusUpdating] = useState<Record<string, boolean>>({});
|
||||
const [selectedFiles, setSelectedFiles] = useState<Set<string>>(new Set());
|
||||
|
||||
const fileInputRef = useRef<HTMLInputElement | null>(null);
|
||||
const selectionCount = selectedFiles.size;
|
||||
|
||||
const toggleSelect = useCallback((name: string) => {
|
||||
setSelectedFiles((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(name)) {
|
||||
next.delete(name);
|
||||
} else {
|
||||
next.add(name);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}, []);
|
||||
|
||||
const selectAllVisible = useCallback((visibleFiles: AuthFileItem[]) => {
|
||||
const nextSelected = visibleFiles
|
||||
.filter((file) => !isRuntimeOnlyAuthFile(file))
|
||||
.map((file) => file.name);
|
||||
setSelectedFiles(new Set(nextSelected));
|
||||
}, []);
|
||||
|
||||
const deselectAll = useCallback(() => {
|
||||
setSelectedFiles(new Set());
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedFiles.size === 0) return;
|
||||
const existingNames = new Set(files.map((file) => file.name));
|
||||
setSelectedFiles((prev) => {
|
||||
let changed = false;
|
||||
const next = new Set<string>();
|
||||
prev.forEach((name) => {
|
||||
if (existingNames.has(name)) {
|
||||
next.add(name);
|
||||
} else {
|
||||
changed = true;
|
||||
}
|
||||
});
|
||||
return changed ? next : prev;
|
||||
});
|
||||
}, [files, selectedFiles.size]);
|
||||
|
||||
const loadFiles = useCallback(async () => {
|
||||
setLoading(true);
|
||||
@@ -153,6 +202,12 @@ export function useAuthFilesData(options: UseAuthFilesDataOptions): UseAuthFiles
|
||||
await authFilesApi.deleteFile(name);
|
||||
showNotification(t('auth_files.delete_success'), 'success');
|
||||
setFiles((prev) => prev.filter((item) => item.name !== name));
|
||||
setSelectedFiles((prev) => {
|
||||
if (!prev.has(name)) return prev;
|
||||
const next = new Set(prev);
|
||||
next.delete(name);
|
||||
return next;
|
||||
});
|
||||
} catch (err: unknown) {
|
||||
const errorMessage = err instanceof Error ? err.message : '';
|
||||
showNotification(`${t('notification.delete_failed')}: ${errorMessage}`, 'error');
|
||||
@@ -186,6 +241,7 @@ export function useAuthFilesData(options: UseAuthFilesDataOptions): UseAuthFiles
|
||||
await authFilesApi.deleteAll();
|
||||
showNotification(t('auth_files.delete_all_success'), 'success');
|
||||
setFiles((prev) => prev.filter((file) => isRuntimeOnlyAuthFile(file)));
|
||||
deselectAll();
|
||||
} else {
|
||||
const filesToDelete = files.filter(
|
||||
(f) => f.type === filter && !isRuntimeOnlyAuthFile(f)
|
||||
@@ -212,6 +268,20 @@ export function useAuthFilesData(options: UseAuthFilesDataOptions): UseAuthFiles
|
||||
}
|
||||
|
||||
setFiles((prev) => prev.filter((f) => !deletedNames.includes(f.name)));
|
||||
setSelectedFiles((prev) => {
|
||||
if (prev.size === 0) return prev;
|
||||
const deletedSet = new Set(deletedNames);
|
||||
let changed = false;
|
||||
const next = new Set<string>();
|
||||
prev.forEach((name) => {
|
||||
if (deletedSet.has(name)) {
|
||||
changed = true;
|
||||
} else {
|
||||
next.add(name);
|
||||
}
|
||||
});
|
||||
return changed ? next : prev;
|
||||
});
|
||||
|
||||
if (failed === 0) {
|
||||
showNotification(
|
||||
@@ -235,7 +305,7 @@ export function useAuthFilesData(options: UseAuthFilesDataOptions): UseAuthFiles
|
||||
}
|
||||
});
|
||||
},
|
||||
[files, showConfirmation, showNotification, t]
|
||||
[deselectAll, files, showConfirmation, showNotification, t]
|
||||
);
|
||||
|
||||
const handleDownload = useCallback(
|
||||
@@ -299,8 +369,133 @@ export function useAuthFilesData(options: UseAuthFilesDataOptions): UseAuthFiles
|
||||
[showNotification, t]
|
||||
);
|
||||
|
||||
const batchSetStatus = useCallback(
|
||||
async (names: string[], enabled: boolean) => {
|
||||
const uniqueNames = Array.from(new Set(names));
|
||||
if (uniqueNames.length === 0) return;
|
||||
|
||||
const targetNames = new Set(uniqueNames);
|
||||
const nextDisabled = !enabled;
|
||||
|
||||
setFiles((prev) =>
|
||||
prev.map((file) =>
|
||||
targetNames.has(file.name) ? { ...file, disabled: nextDisabled } : file
|
||||
)
|
||||
);
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
uniqueNames.map((name) => authFilesApi.setStatus(name, nextDisabled))
|
||||
);
|
||||
|
||||
let successCount = 0;
|
||||
let failCount = 0;
|
||||
const failedNames = new Set<string>();
|
||||
const confirmedDisabled = new Map<string, boolean>();
|
||||
|
||||
results.forEach((result, index) => {
|
||||
const name = uniqueNames[index];
|
||||
if (result.status === 'fulfilled') {
|
||||
successCount++;
|
||||
confirmedDisabled.set(name, result.value.disabled);
|
||||
} else {
|
||||
failCount++;
|
||||
failedNames.add(name);
|
||||
}
|
||||
});
|
||||
|
||||
setFiles((prev) =>
|
||||
prev.map((file) => {
|
||||
if (failedNames.has(file.name)) {
|
||||
return { ...file, disabled: !nextDisabled };
|
||||
}
|
||||
if (confirmedDisabled.has(file.name)) {
|
||||
return { ...file, disabled: confirmedDisabled.get(file.name) };
|
||||
}
|
||||
return file;
|
||||
})
|
||||
);
|
||||
|
||||
if (failCount === 0) {
|
||||
showNotification(t('auth_files.batch_status_success', { count: successCount }), 'success');
|
||||
} else {
|
||||
showNotification(
|
||||
t('auth_files.batch_status_partial', { success: successCount, failed: failCount }),
|
||||
'warning'
|
||||
);
|
||||
}
|
||||
|
||||
deselectAll();
|
||||
},
|
||||
[deselectAll, showNotification, t]
|
||||
);
|
||||
|
||||
const batchDelete = useCallback(
|
||||
(names: string[]) => {
|
||||
const uniqueNames = Array.from(new Set(names));
|
||||
if (uniqueNames.length === 0) return;
|
||||
|
||||
showConfirmation({
|
||||
title: t('auth_files.batch_delete_title'),
|
||||
message: t('auth_files.batch_delete_confirm', { count: uniqueNames.length }),
|
||||
variant: 'danger',
|
||||
confirmText: t('common.confirm'),
|
||||
onConfirm: async () => {
|
||||
const results = await Promise.allSettled(
|
||||
uniqueNames.map((name) => authFilesApi.deleteFile(name))
|
||||
);
|
||||
|
||||
const deleted: string[] = [];
|
||||
let failCount = 0;
|
||||
results.forEach((result, index) => {
|
||||
if (result.status === 'fulfilled') {
|
||||
deleted.push(uniqueNames[index]);
|
||||
} else {
|
||||
failCount++;
|
||||
}
|
||||
});
|
||||
|
||||
if (deleted.length > 0) {
|
||||
const deletedSet = new Set(deleted);
|
||||
setFiles((prev) => prev.filter((file) => !deletedSet.has(file.name)));
|
||||
}
|
||||
|
||||
setSelectedFiles((prev) => {
|
||||
if (prev.size === 0) return prev;
|
||||
const deletedSet = new Set(deleted);
|
||||
let changed = false;
|
||||
const next = new Set<string>();
|
||||
prev.forEach((name) => {
|
||||
if (deletedSet.has(name)) {
|
||||
changed = true;
|
||||
} else {
|
||||
next.add(name);
|
||||
}
|
||||
});
|
||||
return changed ? next : prev;
|
||||
});
|
||||
|
||||
if (failCount === 0) {
|
||||
showNotification(`${t('auth_files.delete_all_success')} (${deleted.length})`, 'success');
|
||||
} else {
|
||||
showNotification(
|
||||
t('auth_files.delete_filtered_partial', {
|
||||
success: deleted.length,
|
||||
failed: failCount,
|
||||
type: t('auth_files.filter_all')
|
||||
}),
|
||||
'warning'
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
},
|
||||
[showConfirmation, showNotification, t]
|
||||
);
|
||||
|
||||
return {
|
||||
files,
|
||||
selectedFiles,
|
||||
selectionCount,
|
||||
loading,
|
||||
error,
|
||||
uploading,
|
||||
@@ -314,6 +509,11 @@ export function useAuthFilesData(options: UseAuthFilesDataOptions): UseAuthFiles
|
||||
handleDelete,
|
||||
handleDeleteAll,
|
||||
handleDownload,
|
||||
handleStatusToggle
|
||||
handleStatusToggle,
|
||||
toggleSelect,
|
||||
selectAllVisible,
|
||||
deselectAll,
|
||||
batchSetStatus,
|
||||
batchDelete
|
||||
};
|
||||
}
|
||||
|
||||
@@ -250,6 +250,31 @@
|
||||
"claude_models_hint": "Leave empty to allow all models, or add name[, alias] entries to limit/alias them.",
|
||||
"claude_models_add_btn": "Add Model",
|
||||
"claude_models_count": "Models Count",
|
||||
"claude_models_fetch_button": "Fetch via /v1/models",
|
||||
"claude_models_fetch_title": "Pick Models from Claude /v1/models",
|
||||
"claude_models_fetch_hint": "Call GET /v1/models with Anthropic headers. By default, this sends x-api-key and anthropic-version: 2023-06-01, merged with your custom headers.",
|
||||
"claude_models_fetch_url_label": "Request URL",
|
||||
"claude_models_fetch_refresh": "Refresh",
|
||||
"claude_models_fetch_loading": "Fetching models from Claude /v1/models...",
|
||||
"claude_models_fetch_empty": "No models returned. Please check Base URL, API key, or headers.",
|
||||
"claude_models_fetch_error": "Failed to fetch Claude models",
|
||||
"claude_models_fetch_apply": "Add selected models",
|
||||
"claude_models_search_label": "Search models",
|
||||
"claude_models_search_placeholder": "Filter by name, alias, or description",
|
||||
"claude_models_search_empty": "No models match your search. Try a different keyword.",
|
||||
"claude_models_fetch_added": "{{count}} new models added",
|
||||
"claude_test_title": "Connection Test",
|
||||
"claude_test_hint": "Send a test request to /v1/messages using Anthropic headers to verify this configuration.",
|
||||
"claude_test_select_placeholder": "Choose from current models",
|
||||
"claude_test_select_empty": "No models configured. Add models first",
|
||||
"claude_test_action": "Test",
|
||||
"claude_test_running": "Sending Claude test request...",
|
||||
"claude_test_timeout": "Test request timed out after {{seconds}} seconds.",
|
||||
"claude_test_success": "Test succeeded. Claude model responded.",
|
||||
"claude_test_failed": "Test failed",
|
||||
"claude_test_key_required": "Please provide a Claude API key or set x-api-key in custom headers",
|
||||
"claude_test_model_required": "Please select a model to test",
|
||||
"claude_test_endpoint_invalid": "Unable to build a valid Claude /v1/messages endpoint",
|
||||
"vertex_title": "Vertex API Configuration",
|
||||
"vertex_add_button": "Add Configuration",
|
||||
"vertex_empty_title": "No Vertex Configuration",
|
||||
@@ -425,6 +450,15 @@
|
||||
"status_toggle_label": "Enabled",
|
||||
"status_enabled_success": "\"{{name}}\" enabled",
|
||||
"status_disabled_success": "\"{{name}}\" disabled",
|
||||
"batch_status_success": "{{count}} files updated successfully",
|
||||
"batch_status_partial": "{{success}} updated, {{failed}} failed",
|
||||
"batch_delete_title": "Delete Selected Files",
|
||||
"batch_delete_confirm": "Are you sure you want to delete {{count}} files?",
|
||||
"batch_selected": "{{count}} selected",
|
||||
"batch_select_all": "Select All",
|
||||
"batch_deselect": "Deselect",
|
||||
"batch_enable": "Enable",
|
||||
"batch_disable": "Disable",
|
||||
"prefix_proxy_button": "Edit Auth Fields",
|
||||
"auth_field_editor_title": "Edit Auth Fields - {{name}}",
|
||||
"prefix_proxy_loading": "Loading auth file...",
|
||||
@@ -913,6 +947,13 @@
|
||||
"search_no_results": "No results",
|
||||
"search_prev": "Previous",
|
||||
"search_next": "Next",
|
||||
"diff": {
|
||||
"title": "Review Changes",
|
||||
"current": "Current",
|
||||
"modified": "Modified",
|
||||
"confirm": "Confirm Save",
|
||||
"no_changes": "No changes detected"
|
||||
},
|
||||
"tabs": {
|
||||
"visual": "Visual Editor",
|
||||
"source": "Source File Editor"
|
||||
@@ -1011,6 +1052,7 @@
|
||||
"api_keys": {
|
||||
"label": "API Keys List (api-keys)",
|
||||
"add": "Add API Key",
|
||||
"generate": "Generate",
|
||||
"empty": "No API keys",
|
||||
"hint": "Each entry represents an API key (consistent with 'API Key Management' page style)",
|
||||
"edit_title": "Edit API Key",
|
||||
|
||||
@@ -250,6 +250,31 @@
|
||||
"claude_models_hint": "Оставьте пустым, чтобы разрешить все модели, или добавьте записи name[, alias], чтобы ограничить/переименовать их.",
|
||||
"claude_models_add_btn": "Добавить модель",
|
||||
"claude_models_count": "Количество моделей",
|
||||
"claude_models_fetch_button": "Получить через /v1/models",
|
||||
"claude_models_fetch_title": "Выбор моделей из Claude /v1/models",
|
||||
"claude_models_fetch_hint": "Вызывает GET /v1/models по спецификации Anthropic. По умолчанию отправляются x-api-key и anthropic-version: 2023-06-01, объединённые с вашими пользовательскими заголовками.",
|
||||
"claude_models_fetch_url_label": "URL запроса",
|
||||
"claude_models_fetch_refresh": "Обновить",
|
||||
"claude_models_fetch_loading": "Получение моделей из Claude /v1/models...",
|
||||
"claude_models_fetch_empty": "Модели не вернулись. Проверьте Base URL, API-ключ или заголовки.",
|
||||
"claude_models_fetch_error": "Не удалось получить модели Claude",
|
||||
"claude_models_fetch_apply": "Добавить выбранные модели",
|
||||
"claude_models_search_label": "Поиск моделей",
|
||||
"claude_models_search_placeholder": "Фильтр по имени, псевдониму или описанию",
|
||||
"claude_models_search_empty": "Модели по запросу не найдены. Попробуйте другой ключ.",
|
||||
"claude_models_fetch_added": "Добавлено новых моделей: {{count}}",
|
||||
"claude_test_title": "Тест подключения",
|
||||
"claude_test_hint": "Отправляет тестовый запрос в /v1/messages по спецификации Anthropic, чтобы проверить текущую конфигурацию.",
|
||||
"claude_test_select_placeholder": "Выберите из текущих моделей",
|
||||
"claude_test_select_empty": "Модели не настроены. Сначала добавьте модели",
|
||||
"claude_test_action": "Тест",
|
||||
"claude_test_running": "Отправка тестового запроса Claude...",
|
||||
"claude_test_timeout": "Тестовый запрос превысил тайм-аут {{seconds}} с",
|
||||
"claude_test_success": "Тест выполнен успешно. Модель Claude ответила.",
|
||||
"claude_test_failed": "Тест не выполнен",
|
||||
"claude_test_key_required": "Укажите Claude API-ключ или задайте x-api-key в пользовательских заголовках",
|
||||
"claude_test_model_required": "Выберите модель для теста",
|
||||
"claude_test_endpoint_invalid": "Не удалось сформировать корректный endpoint Claude /v1/messages",
|
||||
"vertex_title": "Конфигурация Vertex API",
|
||||
"vertex_add_button": "Добавить конфигурацию",
|
||||
"vertex_empty_title": "Конфигурации Vertex отсутствуют",
|
||||
@@ -425,6 +450,15 @@
|
||||
"status_toggle_label": "Включено",
|
||||
"status_enabled_success": "\"{{name}}\" включён",
|
||||
"status_disabled_success": "\"{{name}}\" отключён",
|
||||
"batch_status_success": "{{count}} файлов обновлено",
|
||||
"batch_status_partial": "{{success}} обновлено, {{failed}} не удалось",
|
||||
"batch_delete_title": "Удалить выбранные файлы",
|
||||
"batch_delete_confirm": "Удалить {{count}} файлов?",
|
||||
"batch_selected": "{{count}} выбрано",
|
||||
"batch_select_all": "Выбрать все",
|
||||
"batch_deselect": "Отменить",
|
||||
"batch_enable": "Включить",
|
||||
"batch_disable": "Отключить",
|
||||
"prefix_proxy_button": "Редактировать поля файла авторизации",
|
||||
"auth_field_editor_title": "Редактировать поля файла авторизации - {{name}}",
|
||||
"prefix_proxy_loading": "Загрузка файла авторизации...",
|
||||
@@ -916,6 +950,13 @@
|
||||
"search_no_results": "Нет результатов",
|
||||
"search_prev": "Назад",
|
||||
"search_next": "Вперёд",
|
||||
"diff": {
|
||||
"title": "Обзор изменений",
|
||||
"current": "Текущая",
|
||||
"modified": "Изменённая",
|
||||
"confirm": "Подтвердить",
|
||||
"no_changes": "Изменений не обнаружено"
|
||||
},
|
||||
"tabs": {
|
||||
"visual": "Визуальный редактор",
|
||||
"source": "Редактор файла"
|
||||
@@ -1016,6 +1057,7 @@
|
||||
"api_keys": {
|
||||
"label": "Список API-ключей (api-keys)",
|
||||
"add": "Добавить API-ключ",
|
||||
"generate": "Сгенерировать",
|
||||
"empty": "API-ключи отсутствуют",
|
||||
"hint": "Каждая запись — это API-ключ (в том же стиле, что и на странице управления API-ключами)",
|
||||
"edit_title": "Редактирование API-ключа",
|
||||
|
||||
@@ -250,6 +250,31 @@
|
||||
"claude_models_hint": "为空表示使用全部模型;可填写 name[, alias] 以限制或重命名模型。",
|
||||
"claude_models_add_btn": "添加模型",
|
||||
"claude_models_count": "模型数量",
|
||||
"claude_models_fetch_button": "从 /v1/models 获取",
|
||||
"claude_models_fetch_title": "从 Claude /v1/models 选择模型",
|
||||
"claude_models_fetch_hint": "按 Anthropic 规范请求 GET /v1/models,默认附带 x-api-key 与 anthropic-version: 2023-06-01;也会合并你配置的自定义请求头。",
|
||||
"claude_models_fetch_url_label": "请求地址",
|
||||
"claude_models_fetch_refresh": "重新获取",
|
||||
"claude_models_fetch_loading": "正在从 Claude /v1/models 获取模型列表...",
|
||||
"claude_models_fetch_empty": "未获取到模型,请检查 Base URL、API Key 或请求头。",
|
||||
"claude_models_fetch_error": "获取 Claude 模型失败",
|
||||
"claude_models_fetch_apply": "添加所选模型",
|
||||
"claude_models_search_label": "搜索模型",
|
||||
"claude_models_search_placeholder": "按名称、别名或描述筛选",
|
||||
"claude_models_search_empty": "没有匹配的模型,请更换关键字试试。",
|
||||
"claude_models_fetch_added": "已添加 {{count}} 个新模型",
|
||||
"claude_test_title": "连通性测试",
|
||||
"claude_test_hint": "按 Anthropic 规范向 /v1/messages 发送测试请求,验证当前配置是否可用。",
|
||||
"claude_test_select_placeholder": "从当前模型列表选择",
|
||||
"claude_test_select_empty": "当前未配置模型,请先添加模型",
|
||||
"claude_test_action": "测试",
|
||||
"claude_test_running": "正在发送 Claude 测试请求...",
|
||||
"claude_test_timeout": "测试请求超时({{seconds}}秒)。",
|
||||
"claude_test_success": "测试成功,Claude 模型可用。",
|
||||
"claude_test_failed": "测试失败",
|
||||
"claude_test_key_required": "请先填写 Claude API Key 或在自定义请求头中设置 x-api-key",
|
||||
"claude_test_model_required": "请选择要测试的模型",
|
||||
"claude_test_endpoint_invalid": "无法构造有效的 Claude /v1/messages 请求地址",
|
||||
"vertex_title": "Vertex API 配置",
|
||||
"vertex_add_button": "添加配置",
|
||||
"vertex_empty_title": "暂无Vertex配置",
|
||||
@@ -425,6 +450,15 @@
|
||||
"status_toggle_label": "启用",
|
||||
"status_enabled_success": "已启用 \"{{name}}\"",
|
||||
"status_disabled_success": "已停用 \"{{name}}\"",
|
||||
"batch_status_success": "已成功更新 {{count}} 个文件",
|
||||
"batch_status_partial": "成功 {{success}} 个,失败 {{failed}} 个",
|
||||
"batch_delete_title": "删除选中文件",
|
||||
"batch_delete_confirm": "确定要删除 {{count}} 个文件吗?",
|
||||
"batch_selected": "已选 {{count}} 项",
|
||||
"batch_select_all": "全选",
|
||||
"batch_deselect": "取消选择",
|
||||
"batch_enable": "启用",
|
||||
"batch_disable": "禁用",
|
||||
"prefix_proxy_button": "编辑认证文件字段",
|
||||
"auth_field_editor_title": "编辑认证文件字段 - {{name}}",
|
||||
"prefix_proxy_loading": "正在加载认证文件...",
|
||||
@@ -913,6 +947,13 @@
|
||||
"search_no_results": "无结果",
|
||||
"search_prev": "上一个",
|
||||
"search_next": "下一个",
|
||||
"diff": {
|
||||
"title": "确认变更",
|
||||
"current": "当前配置",
|
||||
"modified": "修改后",
|
||||
"confirm": "确认保存",
|
||||
"no_changes": "未检测到变更"
|
||||
},
|
||||
"tabs": {
|
||||
"visual": "可视化编辑",
|
||||
"source": "源文件编辑"
|
||||
@@ -1011,6 +1052,7 @@
|
||||
"api_keys": {
|
||||
"label": "API 密钥列表 (api-keys)",
|
||||
"add": "添加 API 密钥",
|
||||
"generate": "生成",
|
||||
"empty": "暂无 API 密钥",
|
||||
"hint": "每个条目代表一个 API 密钥(与 「API 密钥管理」 页面样式一致)",
|
||||
"edit_title": "编辑 API 密钥",
|
||||
|
||||
@@ -254,17 +254,8 @@ export function AiProvidersAmpcodeEditPage() {
|
||||
disabled={loading || saving || disableControls}
|
||||
hint={t('ai_providers.ampcode_upstream_api_key_hint')}
|
||||
/>
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
gap: 8,
|
||||
alignItems: 'center',
|
||||
marginTop: -8,
|
||||
marginBottom: 12,
|
||||
flexWrap: 'wrap',
|
||||
}}
|
||||
>
|
||||
<div className="hint" style={{ margin: 0 }}>
|
||||
<div className={layoutStyles.upstreamApiKeyRow}>
|
||||
<div className={layoutStyles.upstreamApiKeyHint}>
|
||||
{t('ai_providers.ampcode_upstream_api_key_current', {
|
||||
key: config?.ampcode?.upstreamApiKey
|
||||
? maskApiKey(config.ampcode.upstreamApiKey)
|
||||
|
||||
@@ -0,0 +1,357 @@
|
||||
import type { Dispatch, SetStateAction } from 'react';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { Outlet, useLocation, useNavigate, useParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { providersApi } from '@/services/api';
|
||||
import { useAuthStore, useClaudeEditDraftStore, useConfigStore, useNotificationStore } from '@/stores';
|
||||
import type { ProviderKeyConfig } from '@/types';
|
||||
import type { ModelInfo } from '@/utils/models';
|
||||
import type { ModelEntry, ProviderFormState } from '@/components/providers/types';
|
||||
import { buildHeaderObject, headersToEntries } from '@/utils/headers';
|
||||
import { excludedModelsToText, parseExcludedModels } from '@/components/providers/utils';
|
||||
import { modelsToEntries } from '@/components/ui/modelInputListUtils';
|
||||
|
||||
type LocationState = { fromAiProviders?: boolean } | null;
|
||||
|
||||
type TestStatus = 'idle' | 'loading' | 'success' | 'error';
|
||||
|
||||
export type ClaudeEditOutletContext = {
|
||||
hasIndexParam: boolean;
|
||||
editIndex: number | null;
|
||||
invalidIndexParam: boolean;
|
||||
invalidIndex: boolean;
|
||||
disableControls: boolean;
|
||||
loading: boolean;
|
||||
saving: boolean;
|
||||
form: ProviderFormState;
|
||||
setForm: Dispatch<SetStateAction<ProviderFormState>>;
|
||||
testModel: string;
|
||||
setTestModel: Dispatch<SetStateAction<string>>;
|
||||
testStatus: TestStatus;
|
||||
setTestStatus: Dispatch<SetStateAction<TestStatus>>;
|
||||
testMessage: string;
|
||||
setTestMessage: Dispatch<SetStateAction<string>>;
|
||||
availableModels: string[];
|
||||
handleBack: () => void;
|
||||
handleSave: () => Promise<void>;
|
||||
mergeDiscoveredModels: (selectedModels: ModelInfo[]) => void;
|
||||
};
|
||||
|
||||
const buildEmptyForm = (): ProviderFormState => ({
|
||||
apiKey: '',
|
||||
prefix: '',
|
||||
baseUrl: '',
|
||||
proxyUrl: '',
|
||||
headers: [],
|
||||
models: [],
|
||||
excludedModels: [],
|
||||
modelEntries: [{ name: '', alias: '' }],
|
||||
excludedText: '',
|
||||
});
|
||||
|
||||
const parseIndexParam = (value: string | undefined) => {
|
||||
if (!value) return null;
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
};
|
||||
|
||||
const getErrorMessage = (err: unknown) => {
|
||||
if (err instanceof Error) return err.message;
|
||||
if (typeof err === 'string') return err;
|
||||
return '';
|
||||
};
|
||||
|
||||
export function AiProvidersClaudeEditLayout() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const { showNotification } = useNotificationStore();
|
||||
|
||||
const params = useParams<{ index?: string }>();
|
||||
const hasIndexParam = typeof params.index === 'string';
|
||||
const editIndex = useMemo(() => parseIndexParam(params.index), [params.index]);
|
||||
const invalidIndexParam = hasIndexParam && editIndex === null;
|
||||
|
||||
const connectionStatus = useAuthStore((state) => state.connectionStatus);
|
||||
const disableControls = connectionStatus !== 'connected';
|
||||
|
||||
const config = useConfigStore((state) => state.config);
|
||||
const fetchConfig = useConfigStore((state) => state.fetchConfig);
|
||||
const isCacheValid = useConfigStore((state) => state.isCacheValid);
|
||||
const updateConfigValue = useConfigStore((state) => state.updateConfigValue);
|
||||
const clearCache = useConfigStore((state) => state.clearCache);
|
||||
|
||||
const [configs, setConfigs] = useState<ProviderKeyConfig[]>(() => config?.claudeApiKeys ?? []);
|
||||
const [loading, setLoading] = useState(() => !isCacheValid('claude-api-key'));
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
const draftKey = useMemo(() => {
|
||||
if (invalidIndexParam) return `claude:invalid:${params.index ?? 'unknown'}`;
|
||||
if (editIndex === null) return 'claude:new';
|
||||
return `claude:${editIndex}`;
|
||||
}, [editIndex, invalidIndexParam, params.index]);
|
||||
|
||||
const draft = useClaudeEditDraftStore((state) => state.drafts[draftKey]);
|
||||
const ensureDraft = useClaudeEditDraftStore((state) => state.ensureDraft);
|
||||
const initDraft = useClaudeEditDraftStore((state) => state.initDraft);
|
||||
const clearDraft = useClaudeEditDraftStore((state) => state.clearDraft);
|
||||
const setDraftForm = useClaudeEditDraftStore((state) => state.setDraftForm);
|
||||
const setDraftTestModel = useClaudeEditDraftStore((state) => state.setDraftTestModel);
|
||||
const setDraftTestStatus = useClaudeEditDraftStore((state) => state.setDraftTestStatus);
|
||||
const setDraftTestMessage = useClaudeEditDraftStore((state) => state.setDraftTestMessage);
|
||||
|
||||
const form = draft?.form ?? buildEmptyForm();
|
||||
const testModel = draft?.testModel ?? '';
|
||||
const testStatus = draft?.testStatus ?? 'idle';
|
||||
const testMessage = draft?.testMessage ?? '';
|
||||
|
||||
const setForm: Dispatch<SetStateAction<ProviderFormState>> = useCallback(
|
||||
(action) => {
|
||||
setDraftForm(draftKey, action);
|
||||
},
|
||||
[draftKey, setDraftForm]
|
||||
);
|
||||
|
||||
const setTestModel: Dispatch<SetStateAction<string>> = useCallback(
|
||||
(action) => {
|
||||
setDraftTestModel(draftKey, action);
|
||||
},
|
||||
[draftKey, setDraftTestModel]
|
||||
);
|
||||
|
||||
const setTestStatus: Dispatch<SetStateAction<TestStatus>> = useCallback(
|
||||
(action) => {
|
||||
setDraftTestStatus(draftKey, action);
|
||||
},
|
||||
[draftKey, setDraftTestStatus]
|
||||
);
|
||||
|
||||
const setTestMessage: Dispatch<SetStateAction<string>> = useCallback(
|
||||
(action) => {
|
||||
setDraftTestMessage(draftKey, action);
|
||||
},
|
||||
[draftKey, setDraftTestMessage]
|
||||
);
|
||||
|
||||
const initialData = useMemo(() => {
|
||||
if (editIndex === null) return undefined;
|
||||
return configs[editIndex];
|
||||
}, [configs, editIndex]);
|
||||
|
||||
const invalidIndex = editIndex !== null && !initialData;
|
||||
|
||||
const availableModels = useMemo(
|
||||
() => form.modelEntries.map((entry) => entry.name.trim()).filter(Boolean),
|
||||
[form.modelEntries]
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
ensureDraft(draftKey);
|
||||
}, [draftKey, ensureDraft]);
|
||||
|
||||
const handleBack = useCallback(() => {
|
||||
clearDraft(draftKey);
|
||||
const state = location.state as LocationState;
|
||||
if (state?.fromAiProviders) {
|
||||
navigate(-1);
|
||||
return;
|
||||
}
|
||||
navigate('/ai-providers', { replace: true });
|
||||
}, [clearDraft, draftKey, location.state, navigate]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const hasValidCache = isCacheValid('claude-api-key');
|
||||
if (!hasValidCache) {
|
||||
setLoading(true);
|
||||
}
|
||||
|
||||
fetchConfig('claude-api-key')
|
||||
.then((value) => {
|
||||
if (cancelled) return;
|
||||
setConfigs(Array.isArray(value) ? (value as ProviderKeyConfig[]) : []);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (cancelled) return;
|
||||
const message = getErrorMessage(err) || t('notification.refresh_failed');
|
||||
showNotification(`${t('notification.load_failed')}: ${message}`, 'error');
|
||||
})
|
||||
.finally(() => {
|
||||
if (cancelled) return;
|
||||
setLoading(false);
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [fetchConfig, isCacheValid, showNotification, t]);
|
||||
|
||||
useEffect(() => {
|
||||
if (loading) return;
|
||||
if (draft?.initialized) return;
|
||||
|
||||
if (initialData) {
|
||||
const seededForm: ProviderFormState = {
|
||||
...initialData,
|
||||
headers: headersToEntries(initialData.headers),
|
||||
modelEntries: modelsToEntries(initialData.models),
|
||||
excludedText: excludedModelsToText(initialData.excludedModels),
|
||||
};
|
||||
const available = seededForm.modelEntries.map((entry) => entry.name.trim()).filter(Boolean);
|
||||
initDraft(draftKey, {
|
||||
form: seededForm,
|
||||
testModel: available[0] || '',
|
||||
testStatus: 'idle',
|
||||
testMessage: '',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
initDraft(draftKey, {
|
||||
form: buildEmptyForm(),
|
||||
testModel: '',
|
||||
testStatus: 'idle',
|
||||
testMessage: '',
|
||||
});
|
||||
}, [draft?.initialized, draftKey, initDraft, initialData, loading]);
|
||||
|
||||
const resolvedLoading = !draft?.initialized;
|
||||
|
||||
useEffect(() => {
|
||||
if (resolvedLoading) return;
|
||||
|
||||
if (availableModels.length === 0) {
|
||||
if (testModel) {
|
||||
setTestModel('');
|
||||
setTestStatus('idle');
|
||||
setTestMessage('');
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!testModel || !availableModels.includes(testModel)) {
|
||||
setTestModel(availableModels[0]);
|
||||
setTestStatus('idle');
|
||||
setTestMessage('');
|
||||
}
|
||||
}, [availableModels, resolvedLoading, setTestMessage, setTestModel, setTestStatus, testModel]);
|
||||
|
||||
const mergeDiscoveredModels = useCallback(
|
||||
(selectedModels: ModelInfo[]) => {
|
||||
if (!selectedModels.length) return;
|
||||
|
||||
let addedCount = 0;
|
||||
setForm((prev) => {
|
||||
const mergedMap = new Map<string, ModelEntry>();
|
||||
prev.modelEntries.forEach((entry) => {
|
||||
const name = entry.name.trim();
|
||||
if (!name) return;
|
||||
mergedMap.set(name, { name, alias: entry.alias?.trim() || '' });
|
||||
});
|
||||
|
||||
selectedModels.forEach((model) => {
|
||||
const name = model.name.trim();
|
||||
if (!name || mergedMap.has(name)) return;
|
||||
mergedMap.set(name, { name, alias: model.alias ?? '' });
|
||||
addedCount += 1;
|
||||
});
|
||||
|
||||
const mergedEntries = Array.from(mergedMap.values());
|
||||
return {
|
||||
...prev,
|
||||
modelEntries: mergedEntries.length ? mergedEntries : [{ name: '', alias: '' }],
|
||||
};
|
||||
});
|
||||
|
||||
if (addedCount > 0) {
|
||||
showNotification(t('ai_providers.claude_models_fetch_added', { count: addedCount }), 'success');
|
||||
}
|
||||
},
|
||||
[setForm, showNotification, t]
|
||||
);
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
const canSave =
|
||||
!disableControls && !saving && !resolvedLoading && !invalidIndexParam && !invalidIndex;
|
||||
if (!canSave) return;
|
||||
|
||||
setSaving(true);
|
||||
try {
|
||||
const payload: ProviderKeyConfig = {
|
||||
apiKey: form.apiKey.trim(),
|
||||
prefix: form.prefix?.trim() || undefined,
|
||||
baseUrl: (form.baseUrl ?? '').trim() || undefined,
|
||||
proxyUrl: form.proxyUrl?.trim() || undefined,
|
||||
headers: buildHeaderObject(form.headers),
|
||||
models: form.modelEntries
|
||||
.map((entry) => {
|
||||
const name = entry.name.trim();
|
||||
if (!name) return null;
|
||||
const alias = entry.alias.trim();
|
||||
return { name, alias: alias || name };
|
||||
})
|
||||
.filter(Boolean) as ProviderKeyConfig['models'],
|
||||
excludedModels: parseExcludedModels(form.excludedText),
|
||||
};
|
||||
|
||||
const nextList =
|
||||
editIndex !== null
|
||||
? configs.map((item, idx) => (idx === editIndex ? payload : item))
|
||||
: [...configs, payload];
|
||||
|
||||
await providersApi.saveClaudeConfigs(nextList);
|
||||
setConfigs(nextList);
|
||||
updateConfigValue('claude-api-key', nextList);
|
||||
clearCache('claude-api-key');
|
||||
showNotification(
|
||||
editIndex !== null ? t('notification.claude_config_updated') : t('notification.claude_config_added'),
|
||||
'success'
|
||||
);
|
||||
handleBack();
|
||||
} catch (err: unknown) {
|
||||
showNotification(`${t('notification.update_failed')}: ${getErrorMessage(err)}`, 'error');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}, [
|
||||
clearCache,
|
||||
configs,
|
||||
disableControls,
|
||||
editIndex,
|
||||
form,
|
||||
handleBack,
|
||||
invalidIndex,
|
||||
invalidIndexParam,
|
||||
resolvedLoading,
|
||||
saving,
|
||||
showNotification,
|
||||
t,
|
||||
updateConfigValue,
|
||||
]);
|
||||
|
||||
return (
|
||||
<Outlet
|
||||
context={{
|
||||
hasIndexParam,
|
||||
editIndex,
|
||||
invalidIndexParam,
|
||||
invalidIndex,
|
||||
disableControls,
|
||||
loading: resolvedLoading,
|
||||
saving,
|
||||
form,
|
||||
setForm,
|
||||
testModel,
|
||||
setTestModel,
|
||||
testStatus,
|
||||
setTestStatus,
|
||||
testMessage,
|
||||
setTestMessage,
|
||||
availableModels,
|
||||
handleBack,
|
||||
handleSave,
|
||||
mergeDiscoveredModels,
|
||||
} satisfies ClaudeEditOutletContext}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -1,88 +1,75 @@
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useLocation, useNavigate, useParams } from 'react-router-dom';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useNavigate, useOutletContext } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Card } from '@/components/ui/Card';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { Select } from '@/components/ui/Select';
|
||||
import { HeaderInputList } from '@/components/ui/HeaderInputList';
|
||||
import { ModelInputList } from '@/components/ui/ModelInputList';
|
||||
import { modelsToEntries } from '@/components/ui/modelInputListUtils';
|
||||
import { useEdgeSwipeBack } from '@/hooks/useEdgeSwipeBack';
|
||||
import { SecondaryScreenShell } from '@/components/common/SecondaryScreenShell';
|
||||
import { providersApi } from '@/services/api';
|
||||
import { useAuthStore, useConfigStore, useNotificationStore } from '@/stores';
|
||||
import type { ProviderKeyConfig } from '@/types';
|
||||
import { buildHeaderObject, headersToEntries } from '@/utils/headers';
|
||||
import { excludedModelsToText, parseExcludedModels } from '@/components/providers/utils';
|
||||
import type { ProviderFormState } from '@/components/providers';
|
||||
import { apiCallApi, getApiCallErrorMessage } from '@/services/api';
|
||||
import { useNotificationStore } from '@/stores';
|
||||
import { buildHeaderObject } from '@/utils/headers';
|
||||
import { buildClaudeMessagesEndpoint } from '@/components/providers/utils';
|
||||
import type { ClaudeEditOutletContext } from './AiProvidersClaudeEditLayout';
|
||||
import styles from './AiProvidersPage.module.scss';
|
||||
import layoutStyles from './AiProvidersEditLayout.module.scss';
|
||||
|
||||
type LocationState = { fromAiProviders?: boolean } | null;
|
||||
const CLAUDE_TEST_TIMEOUT_MS = 30_000;
|
||||
const DEFAULT_ANTHROPIC_VERSION = '2023-06-01';
|
||||
|
||||
const buildEmptyForm = (): ProviderFormState => ({
|
||||
apiKey: '',
|
||||
prefix: '',
|
||||
baseUrl: '',
|
||||
proxyUrl: '',
|
||||
headers: [],
|
||||
models: [],
|
||||
excludedModels: [],
|
||||
modelEntries: [{ name: '', alias: '' }],
|
||||
excludedText: '',
|
||||
});
|
||||
const getErrorMessage = (err: unknown) => {
|
||||
if (err instanceof Error) return err.message;
|
||||
if (typeof err === 'string') return err;
|
||||
return '';
|
||||
};
|
||||
|
||||
const parseIndexParam = (value: string | undefined) => {
|
||||
if (!value) return null;
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isFinite(parsed) ? parsed : null;
|
||||
const hasHeader = (headers: Record<string, string>, name: string) => {
|
||||
const target = name.toLowerCase();
|
||||
return Object.keys(headers).some((key) => key.toLowerCase() === target);
|
||||
};
|
||||
|
||||
const resolveBearerTokenFromAuthorization = (headers: Record<string, string>): string => {
|
||||
const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === 'authorization');
|
||||
if (!entry) return '';
|
||||
const value = String(entry[1] ?? '').trim();
|
||||
if (!value) return '';
|
||||
const match = value.match(/^Bearer\s+(.+)$/i);
|
||||
return match?.[1]?.trim() || '';
|
||||
};
|
||||
|
||||
export function AiProvidersClaudeEditPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const params = useParams<{ index?: string }>();
|
||||
|
||||
const { showNotification } = useNotificationStore();
|
||||
const connectionStatus = useAuthStore((state) => state.connectionStatus);
|
||||
const disableControls = connectionStatus !== 'connected';
|
||||
const {
|
||||
hasIndexParam,
|
||||
invalidIndexParam,
|
||||
invalidIndex,
|
||||
disableControls,
|
||||
loading,
|
||||
saving,
|
||||
form,
|
||||
setForm,
|
||||
testModel,
|
||||
setTestModel,
|
||||
testStatus,
|
||||
setTestStatus,
|
||||
testMessage,
|
||||
setTestMessage,
|
||||
availableModels,
|
||||
handleBack,
|
||||
handleSave,
|
||||
} = useOutletContext<ClaudeEditOutletContext>();
|
||||
|
||||
const fetchConfig = useConfigStore((state) => state.fetchConfig);
|
||||
const updateConfigValue = useConfigStore((state) => state.updateConfigValue);
|
||||
const clearCache = useConfigStore((state) => state.clearCache);
|
||||
|
||||
const [configs, setConfigs] = useState<ProviderKeyConfig[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [form, setForm] = useState<ProviderFormState>(() => buildEmptyForm());
|
||||
|
||||
const hasIndexParam = typeof params.index === 'string';
|
||||
const editIndex = useMemo(() => parseIndexParam(params.index), [params.index]);
|
||||
const invalidIndexParam = hasIndexParam && editIndex === null;
|
||||
|
||||
const initialData = useMemo(() => {
|
||||
if (editIndex === null) return undefined;
|
||||
return configs[editIndex];
|
||||
}, [configs, editIndex]);
|
||||
|
||||
const invalidIndex = editIndex !== null && !initialData;
|
||||
|
||||
const title =
|
||||
editIndex !== null
|
||||
? t('ai_providers.claude_edit_modal_title')
|
||||
: t('ai_providers.claude_add_modal_title');
|
||||
|
||||
const handleBack = useCallback(() => {
|
||||
const state = location.state as LocationState;
|
||||
if (state?.fromAiProviders) {
|
||||
navigate(-1);
|
||||
return;
|
||||
}
|
||||
navigate('/ai-providers', { replace: true });
|
||||
}, [location.state, navigate]);
|
||||
const title = hasIndexParam
|
||||
? t('ai_providers.claude_edit_modal_title')
|
||||
: t('ai_providers.claude_add_modal_title');
|
||||
|
||||
const swipeRef = useEdgeSwipeBack({ onBack: handleBack });
|
||||
const [isTesting, setIsTesting] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
@@ -94,101 +81,163 @@ export function AiProvidersClaudeEditPage() {
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [handleBack]);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setLoading(true);
|
||||
setError('');
|
||||
const canSave =
|
||||
!disableControls && !loading && !saving && !invalidIndexParam && !invalidIndex && !isTesting;
|
||||
|
||||
fetchConfig('claude-api-key')
|
||||
.then((value) => {
|
||||
if (cancelled) return;
|
||||
setConfigs(Array.isArray(value) ? (value as ProviderKeyConfig[]) : []);
|
||||
})
|
||||
.catch((err: unknown) => {
|
||||
if (cancelled) return;
|
||||
const message = err instanceof Error ? err.message : '';
|
||||
setError(message || t('notification.refresh_failed'));
|
||||
})
|
||||
.finally(() => {
|
||||
if (cancelled) return;
|
||||
setLoading(false);
|
||||
const modelSelectOptions = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
return form.modelEntries.reduce<Array<{ value: string; label: string }>>((acc, entry) => {
|
||||
const name = entry.name.trim();
|
||||
if (!name || seen.has(name)) return acc;
|
||||
seen.add(name);
|
||||
const alias = entry.alias.trim();
|
||||
acc.push({
|
||||
value: name,
|
||||
label: alias && alias !== name ? `${name} (${alias})` : name,
|
||||
});
|
||||
return acc;
|
||||
}, []);
|
||||
}, [form.modelEntries]);
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [fetchConfig, t]);
|
||||
const connectivityConfigSignature = useMemo(() => {
|
||||
const headersSignature = form.headers
|
||||
.map((entry) => `${entry.key.trim()}:${entry.value.trim()}`)
|
||||
.join('|');
|
||||
const modelsSignature = form.modelEntries
|
||||
.map((entry) => `${entry.name.trim()}:${entry.alias.trim()}`)
|
||||
.join('|');
|
||||
return [
|
||||
form.apiKey.trim(),
|
||||
form.baseUrl?.trim() ?? '',
|
||||
testModel.trim(),
|
||||
headersSignature,
|
||||
modelsSignature,
|
||||
].join('||');
|
||||
}, [form.apiKey, form.baseUrl, form.headers, form.modelEntries, testModel]);
|
||||
|
||||
const previousConnectivityConfigRef = useRef(connectivityConfigSignature);
|
||||
|
||||
useEffect(() => {
|
||||
if (loading) return;
|
||||
|
||||
if (initialData) {
|
||||
setForm({
|
||||
...initialData,
|
||||
headers: headersToEntries(initialData.headers),
|
||||
modelEntries: modelsToEntries(initialData.models),
|
||||
excludedText: excludedModelsToText(initialData.excludedModels),
|
||||
});
|
||||
if (previousConnectivityConfigRef.current === connectivityConfigSignature) {
|
||||
return;
|
||||
}
|
||||
setForm(buildEmptyForm());
|
||||
}, [initialData, loading]);
|
||||
previousConnectivityConfigRef.current = connectivityConfigSignature;
|
||||
setTestStatus('idle');
|
||||
setTestMessage('');
|
||||
}, [connectivityConfigSignature, setTestMessage, setTestStatus]);
|
||||
|
||||
const canSave = !disableControls && !saving && !loading && !invalidIndexParam && !invalidIndex;
|
||||
const openClaudeModelDiscovery = () => {
|
||||
navigate('models');
|
||||
};
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
if (!canSave) return;
|
||||
const runClaudeConnectivityTest = useCallback(async () => {
|
||||
if (isTesting) return;
|
||||
|
||||
const modelName = testModel.trim() || availableModels[0] || '';
|
||||
if (!modelName) {
|
||||
const message = t('ai_providers.claude_test_model_required');
|
||||
setTestStatus('error');
|
||||
setTestMessage(message);
|
||||
showNotification(message, 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const customHeaders = buildHeaderObject(form.headers);
|
||||
const apiKey = form.apiKey.trim();
|
||||
const hasApiKeyHeader = hasHeader(customHeaders, 'x-api-key');
|
||||
const apiKeyFromAuthorization = resolveBearerTokenFromAuthorization(customHeaders);
|
||||
const resolvedApiKey = apiKey || apiKeyFromAuthorization;
|
||||
|
||||
if (!resolvedApiKey && !hasApiKeyHeader) {
|
||||
const message = t('ai_providers.claude_test_key_required');
|
||||
setTestStatus('error');
|
||||
setTestMessage(message);
|
||||
showNotification(message, 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const endpoint = buildClaudeMessagesEndpoint(form.baseUrl ?? '');
|
||||
if (!endpoint) {
|
||||
const message = t('ai_providers.claude_test_endpoint_invalid');
|
||||
setTestStatus('error');
|
||||
setTestMessage(message);
|
||||
showNotification(message, 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
...customHeaders,
|
||||
};
|
||||
|
||||
if (!hasHeader(headers, 'anthropic-version')) {
|
||||
headers['anthropic-version'] = DEFAULT_ANTHROPIC_VERSION;
|
||||
}
|
||||
if (!Object.prototype.hasOwnProperty.call(headers, 'Anthropic-Version')) {
|
||||
headers['Anthropic-Version'] = headers['anthropic-version'] ?? DEFAULT_ANTHROPIC_VERSION;
|
||||
}
|
||||
|
||||
if (!hasApiKeyHeader && resolvedApiKey) {
|
||||
headers['x-api-key'] = resolvedApiKey;
|
||||
}
|
||||
if (!Object.prototype.hasOwnProperty.call(headers, 'X-Api-Key') && resolvedApiKey) {
|
||||
headers['X-Api-Key'] = resolvedApiKey;
|
||||
}
|
||||
|
||||
setIsTesting(true);
|
||||
setTestStatus('loading');
|
||||
setTestMessage(t('ai_providers.claude_test_running'));
|
||||
|
||||
setSaving(true);
|
||||
setError('');
|
||||
try {
|
||||
const payload: ProviderKeyConfig = {
|
||||
apiKey: form.apiKey.trim(),
|
||||
prefix: form.prefix?.trim() || undefined,
|
||||
baseUrl: (form.baseUrl ?? '').trim() || undefined,
|
||||
proxyUrl: form.proxyUrl?.trim() || undefined,
|
||||
headers: buildHeaderObject(form.headers),
|
||||
models: form.modelEntries
|
||||
.map((entry) => {
|
||||
const name = entry.name.trim();
|
||||
if (!name) return null;
|
||||
const alias = entry.alias.trim();
|
||||
return { name, alias: alias || name };
|
||||
})
|
||||
.filter(Boolean) as ProviderKeyConfig['models'],
|
||||
excludedModels: parseExcludedModels(form.excludedText),
|
||||
};
|
||||
|
||||
const nextList =
|
||||
editIndex !== null
|
||||
? configs.map((item, idx) => (idx === editIndex ? payload : item))
|
||||
: [...configs, payload];
|
||||
|
||||
await providersApi.saveClaudeConfigs(nextList);
|
||||
updateConfigValue('claude-api-key', nextList);
|
||||
clearCache('claude-api-key');
|
||||
showNotification(
|
||||
editIndex !== null ? t('notification.claude_config_updated') : t('notification.claude_config_added'),
|
||||
'success'
|
||||
const result = await apiCallApi.request(
|
||||
{
|
||||
method: 'POST',
|
||||
url: endpoint,
|
||||
header: headers,
|
||||
data: JSON.stringify({
|
||||
model: modelName,
|
||||
max_tokens: 8,
|
||||
messages: [{ role: 'user', content: 'Hi' }],
|
||||
}),
|
||||
},
|
||||
{ timeout: CLAUDE_TEST_TIMEOUT_MS }
|
||||
);
|
||||
handleBack();
|
||||
|
||||
if (result.statusCode < 200 || result.statusCode >= 300) {
|
||||
throw new Error(getApiCallErrorMessage(result));
|
||||
}
|
||||
|
||||
const message = t('ai_providers.claude_test_success');
|
||||
setTestStatus('success');
|
||||
setTestMessage(message);
|
||||
showNotification(message, 'success');
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : '';
|
||||
setError(message);
|
||||
showNotification(`${t('notification.update_failed')}: ${message}`, 'error');
|
||||
const message = getErrorMessage(err);
|
||||
const errorCode =
|
||||
typeof err === 'object' && err !== null && 'code' in err
|
||||
? String((err as { code?: string }).code)
|
||||
: '';
|
||||
const isTimeout = errorCode === 'ECONNABORTED' || message.toLowerCase().includes('timeout');
|
||||
const resolvedMessage = isTimeout
|
||||
? t('ai_providers.claude_test_timeout', { seconds: CLAUDE_TEST_TIMEOUT_MS / 1000 })
|
||||
: `${t('ai_providers.claude_test_failed')}: ${message || t('common.unknown_error')}`;
|
||||
setTestStatus('error');
|
||||
setTestMessage(resolvedMessage);
|
||||
showNotification(resolvedMessage, 'error');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
setIsTesting(false);
|
||||
}
|
||||
}, [
|
||||
canSave,
|
||||
clearCache,
|
||||
configs,
|
||||
editIndex,
|
||||
form,
|
||||
handleBack,
|
||||
availableModels,
|
||||
form.apiKey,
|
||||
form.baseUrl,
|
||||
form.headers,
|
||||
isTesting,
|
||||
setTestMessage,
|
||||
setTestStatus,
|
||||
showNotification,
|
||||
t,
|
||||
updateConfigValue,
|
||||
testModel,
|
||||
]);
|
||||
|
||||
return (
|
||||
@@ -200,7 +249,7 @@ export function AiProvidersClaudeEditPage() {
|
||||
backLabel={t('common.back')}
|
||||
backAriaLabel={t('common.back')}
|
||||
rightAction={
|
||||
<Button size="sm" onClick={handleSave} loading={saving} disabled={!canSave}>
|
||||
<Button size="sm" onClick={() => void handleSave()} loading={saving} disabled={!canSave}>
|
||||
{t('common.save')}
|
||||
</Button>
|
||||
}
|
||||
@@ -208,16 +257,15 @@ export function AiProvidersClaudeEditPage() {
|
||||
loadingLabel={t('common.loading')}
|
||||
>
|
||||
<Card>
|
||||
{error && <div className="error-box">{error}</div>}
|
||||
{invalidIndexParam || invalidIndex ? (
|
||||
<div className="hint">{t('common.invalid_provider_index')}</div>
|
||||
<div className={styles.sectionHint}>{t('common.invalid_provider_index')}</div>
|
||||
) : (
|
||||
<>
|
||||
<div className={styles.openaiEditForm}>
|
||||
<Input
|
||||
label={t('ai_providers.claude_add_modal_key_label')}
|
||||
value={form.apiKey}
|
||||
onChange={(e) => setForm((prev) => ({ ...prev, apiKey: e.target.value }))}
|
||||
disabled={disableControls || saving}
|
||||
disabled={saving || disableControls || isTesting}
|
||||
/>
|
||||
<Input
|
||||
label={t('ai_providers.prefix_label')}
|
||||
@@ -225,19 +273,19 @@ export function AiProvidersClaudeEditPage() {
|
||||
value={form.prefix ?? ''}
|
||||
onChange={(e) => setForm((prev) => ({ ...prev, prefix: e.target.value }))}
|
||||
hint={t('ai_providers.prefix_hint')}
|
||||
disabled={disableControls || saving}
|
||||
disabled={saving || disableControls || isTesting}
|
||||
/>
|
||||
<Input
|
||||
label={t('ai_providers.claude_add_modal_url_label')}
|
||||
value={form.baseUrl ?? ''}
|
||||
onChange={(e) => setForm((prev) => ({ ...prev, baseUrl: e.target.value }))}
|
||||
disabled={disableControls || saving}
|
||||
disabled={saving || disableControls || isTesting}
|
||||
/>
|
||||
<Input
|
||||
label={t('ai_providers.claude_add_modal_proxy_label')}
|
||||
value={form.proxyUrl ?? ''}
|
||||
onChange={(e) => setForm((prev) => ({ ...prev, proxyUrl: e.target.value }))}
|
||||
disabled={disableControls || saving}
|
||||
disabled={saving || disableControls || isTesting}
|
||||
/>
|
||||
<HeaderInputList
|
||||
entries={form.headers}
|
||||
@@ -247,21 +295,117 @@ export function AiProvidersClaudeEditPage() {
|
||||
valuePlaceholder={t('common.custom_headers_value_placeholder')}
|
||||
removeButtonTitle={t('common.delete')}
|
||||
removeButtonAriaLabel={t('common.delete')}
|
||||
disabled={disableControls || saving}
|
||||
disabled={saving || disableControls || isTesting}
|
||||
/>
|
||||
<div className="form-group">
|
||||
<label>{t('ai_providers.claude_models_label')}</label>
|
||||
|
||||
<div className={styles.modelConfigSection}>
|
||||
<div className={styles.modelConfigHeader}>
|
||||
<label className={styles.modelConfigTitle}>{t('ai_providers.claude_models_label')}</label>
|
||||
<div className={styles.modelConfigToolbar}>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() =>
|
||||
setForm((prev) => ({
|
||||
...prev,
|
||||
modelEntries: [...prev.modelEntries, { name: '', alias: '' }],
|
||||
}))
|
||||
}
|
||||
disabled={saving || disableControls || isTesting}
|
||||
>
|
||||
{t('ai_providers.claude_models_add_btn')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={openClaudeModelDiscovery}
|
||||
disabled={saving || disableControls || isTesting}
|
||||
>
|
||||
{t('ai_providers.claude_models_fetch_button')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className={styles.sectionHint}>{t('ai_providers.claude_models_hint')}</div>
|
||||
|
||||
<ModelInputList
|
||||
entries={form.modelEntries}
|
||||
onChange={(entries) => setForm((prev) => ({ ...prev, modelEntries: entries }))}
|
||||
addLabel={t('ai_providers.claude_models_add_btn')}
|
||||
namePlaceholder={t('common.model_name_placeholder')}
|
||||
aliasPlaceholder={t('common.model_alias_placeholder')}
|
||||
disabled={saving || disableControls || isTesting}
|
||||
hideAddButton
|
||||
className={styles.modelInputList}
|
||||
rowClassName={styles.modelInputRow}
|
||||
inputClassName={styles.modelInputField}
|
||||
removeButtonClassName={styles.modelRowRemoveButton}
|
||||
removeButtonTitle={t('common.delete')}
|
||||
removeButtonAriaLabel={t('common.delete')}
|
||||
disabled={disableControls || saving}
|
||||
/>
|
||||
|
||||
<div className={styles.modelTestPanel}>
|
||||
<div className={styles.modelTestMeta}>
|
||||
<label className={styles.modelTestLabel}>{t('ai_providers.claude_test_title')}</label>
|
||||
<span className={styles.modelTestHint}>{t('ai_providers.claude_test_hint')}</span>
|
||||
</div>
|
||||
<div className={styles.modelTestControls}>
|
||||
<Select
|
||||
value={testModel}
|
||||
options={modelSelectOptions}
|
||||
onChange={(value) => {
|
||||
setTestModel(value);
|
||||
setTestStatus('idle');
|
||||
setTestMessage('');
|
||||
}}
|
||||
placeholder={
|
||||
availableModels.length
|
||||
? t('ai_providers.claude_test_select_placeholder')
|
||||
: t('ai_providers.claude_test_select_empty')
|
||||
}
|
||||
className={styles.openaiTestSelect}
|
||||
ariaLabel={t('ai_providers.claude_test_title')}
|
||||
disabled={
|
||||
saving ||
|
||||
disableControls ||
|
||||
isTesting ||
|
||||
testStatus === 'loading' ||
|
||||
availableModels.length === 0
|
||||
}
|
||||
/>
|
||||
<Button
|
||||
variant={testStatus === 'error' ? 'danger' : 'secondary'}
|
||||
size="sm"
|
||||
onClick={() => void runClaudeConnectivityTest()}
|
||||
loading={testStatus === 'loading'}
|
||||
disabled={
|
||||
saving ||
|
||||
disableControls ||
|
||||
isTesting ||
|
||||
testStatus === 'loading' ||
|
||||
availableModels.length === 0
|
||||
}
|
||||
className={styles.modelTestAllButton}
|
||||
>
|
||||
{t('ai_providers.claude_test_action')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{testMessage && (
|
||||
<div
|
||||
className={`status-badge ${
|
||||
testStatus === 'error'
|
||||
? 'error'
|
||||
: testStatus === 'success'
|
||||
? 'success'
|
||||
: 'muted'
|
||||
}`}
|
||||
>
|
||||
{testMessage}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="form-group">
|
||||
<label>{t('ai_providers.excluded_models_label')}</label>
|
||||
<textarea
|
||||
@@ -270,11 +414,11 @@ export function AiProvidersClaudeEditPage() {
|
||||
value={form.excludedText}
|
||||
onChange={(e) => setForm((prev) => ({ ...prev, excludedText: e.target.value }))}
|
||||
rows={4}
|
||||
disabled={disableControls || saving}
|
||||
disabled={saving || disableControls || isTesting}
|
||||
/>
|
||||
<div className="hint">{t('ai_providers.excluded_models_hint')}</div>
|
||||
</div>
|
||||
</>
|
||||
</div>
|
||||
)}
|
||||
</Card>
|
||||
</SecondaryScreenShell>
|
||||
|
||||
@@ -0,0 +1,248 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useNavigate, useOutletContext } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { Card } from '@/components/ui/Card';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { SecondaryScreenShell } from '@/components/common/SecondaryScreenShell';
|
||||
import { useEdgeSwipeBack } from '@/hooks/useEdgeSwipeBack';
|
||||
import { modelsApi } from '@/services/api';
|
||||
import type { ModelInfo } from '@/utils/models';
|
||||
import { buildHeaderObject } from '@/utils/headers';
|
||||
import type { ClaudeEditOutletContext } from './AiProvidersClaudeEditLayout';
|
||||
import styles from './AiProvidersPage.module.scss';
|
||||
import layoutStyles from './AiProvidersEditLayout.module.scss';
|
||||
|
||||
const getErrorMessage = (err: unknown) => {
|
||||
if (err instanceof Error) return err.message;
|
||||
if (typeof err === 'string') return err;
|
||||
return '';
|
||||
};
|
||||
|
||||
export function AiProvidersClaudeModelsPage() {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const {
|
||||
disableControls,
|
||||
loading: initialLoading,
|
||||
saving,
|
||||
form,
|
||||
mergeDiscoveredModels,
|
||||
} = useOutletContext<ClaudeEditOutletContext>();
|
||||
|
||||
const [endpoint, setEndpoint] = useState('');
|
||||
const [models, setModels] = useState<ModelInfo[]>([]);
|
||||
const [fetching, setFetching] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [search, setSearch] = useState('');
|
||||
const [selected, setSelected] = useState<Set<string>>(new Set());
|
||||
const autoFetchSignatureRef = useRef<string>('');
|
||||
|
||||
const filteredModels = useMemo(() => {
|
||||
const filter = search.trim().toLowerCase();
|
||||
if (!filter) return models;
|
||||
return models.filter((model) => {
|
||||
const name = (model.name || '').toLowerCase();
|
||||
const alias = (model.alias || '').toLowerCase();
|
||||
const desc = (model.description || '').toLowerCase();
|
||||
return name.includes(filter) || alias.includes(filter) || desc.includes(filter);
|
||||
});
|
||||
}, [models, search]);
|
||||
|
||||
const fetchClaudeModelDiscovery = useCallback(async () => {
|
||||
setFetching(true);
|
||||
setError('');
|
||||
const headerObject = buildHeaderObject(form.headers);
|
||||
try {
|
||||
const list = await modelsApi.fetchClaudeModelsViaApiCall(
|
||||
form.baseUrl ?? '',
|
||||
form.apiKey.trim() || undefined,
|
||||
headerObject
|
||||
);
|
||||
setModels(list);
|
||||
} catch (err: unknown) {
|
||||
setModels([]);
|
||||
const message = getErrorMessage(err);
|
||||
const hasCustomXApiKey = Object.keys(headerObject).some(
|
||||
(key) => key.toLowerCase() === 'x-api-key'
|
||||
);
|
||||
const hasAuthorization = Object.keys(headerObject).some(
|
||||
(key) => key.toLowerCase() === 'authorization'
|
||||
);
|
||||
const shouldAttachDiag =
|
||||
message.toLowerCase().includes('x-api-key') || message.includes('401');
|
||||
const diag = shouldAttachDiag
|
||||
? ` [diag: apiKeyField=${form.apiKey.trim() ? 'yes' : 'no'}, customXApiKey=${
|
||||
hasCustomXApiKey ? 'yes' : 'no'
|
||||
}, customAuthorization=${hasAuthorization ? 'yes' : 'no'}]`
|
||||
: '';
|
||||
setError(`${t('ai_providers.claude_models_fetch_error')}: ${message}${diag}`);
|
||||
} finally {
|
||||
setFetching(false);
|
||||
}
|
||||
}, [form.apiKey, form.baseUrl, form.headers, t]);
|
||||
|
||||
useEffect(() => {
|
||||
if (initialLoading) return;
|
||||
|
||||
const nextEndpoint = modelsApi.buildClaudeModelsEndpoint(form.baseUrl ?? '');
|
||||
setEndpoint(nextEndpoint);
|
||||
setModels([]);
|
||||
setSearch('');
|
||||
setSelected(new Set());
|
||||
setError('');
|
||||
|
||||
const headerObject = buildHeaderObject(form.headers);
|
||||
const hasCustomXApiKey = Object.keys(headerObject).some(
|
||||
(key) => key.toLowerCase() === 'x-api-key'
|
||||
);
|
||||
const hasAuthorization = Object.keys(headerObject).some(
|
||||
(key) => key.toLowerCase() === 'authorization'
|
||||
);
|
||||
const hasApiKeyField = Boolean(form.apiKey.trim());
|
||||
const canAutoFetch = hasApiKeyField || hasCustomXApiKey || hasAuthorization;
|
||||
|
||||
// Avoid firing a guaranteed 401 on initial render (common while the parent form is still
|
||||
// initializing), and avoid duplicate auto-fetches (e.g. React StrictMode in dev).
|
||||
if (!canAutoFetch) return;
|
||||
|
||||
const headerSignature = Object.entries(headerObject)
|
||||
.sort(([a], [b]) => a.toLowerCase().localeCompare(b.toLowerCase()))
|
||||
.map(([key, value]) => `${key}:${value}`)
|
||||
.join('|');
|
||||
const signature = `${nextEndpoint}||${form.apiKey.trim()}||${headerSignature}`;
|
||||
if (autoFetchSignatureRef.current === signature) return;
|
||||
autoFetchSignatureRef.current = signature;
|
||||
|
||||
void fetchClaudeModelDiscovery();
|
||||
}, [fetchClaudeModelDiscovery, form.apiKey, form.baseUrl, form.headers, initialLoading]);
|
||||
|
||||
const handleBack = useCallback(() => {
|
||||
navigate(-1);
|
||||
}, [navigate]);
|
||||
|
||||
const swipeRef = useEdgeSwipeBack({ onBack: handleBack });
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === 'Escape') {
|
||||
handleBack();
|
||||
}
|
||||
};
|
||||
window.addEventListener('keydown', handleKeyDown);
|
||||
return () => window.removeEventListener('keydown', handleKeyDown);
|
||||
}, [handleBack]);
|
||||
|
||||
const toggleSelection = (name: string) => {
|
||||
setSelected((prev) => {
|
||||
const next = new Set(prev);
|
||||
if (next.has(name)) {
|
||||
next.delete(name);
|
||||
} else {
|
||||
next.add(name);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const handleApply = () => {
|
||||
const selectedModels = models.filter((model) => selected.has(model.name));
|
||||
if (selectedModels.length) {
|
||||
mergeDiscoveredModels(selectedModels);
|
||||
}
|
||||
handleBack();
|
||||
};
|
||||
|
||||
const canApply = !disableControls && !saving && !fetching;
|
||||
|
||||
return (
|
||||
<SecondaryScreenShell
|
||||
ref={swipeRef}
|
||||
contentClassName={layoutStyles.content}
|
||||
title={t('ai_providers.claude_models_fetch_title')}
|
||||
onBack={handleBack}
|
||||
backLabel={t('common.back')}
|
||||
backAriaLabel={t('common.back')}
|
||||
rightAction={
|
||||
<Button size="sm" onClick={handleApply} disabled={!canApply}>
|
||||
{t('ai_providers.claude_models_fetch_apply')}
|
||||
</Button>
|
||||
}
|
||||
isLoading={initialLoading}
|
||||
loadingLabel={t('common.loading')}
|
||||
>
|
||||
<Card>
|
||||
<div className={styles.openaiModelsContent}>
|
||||
<div className={styles.sectionHint}>{t('ai_providers.claude_models_fetch_hint')}</div>
|
||||
<div className={styles.openaiModelsEndpointSection}>
|
||||
<label className={styles.openaiModelsEndpointLabel}>
|
||||
{t('ai_providers.claude_models_fetch_url_label')}
|
||||
</label>
|
||||
<div className={styles.openaiModelsEndpointControls}>
|
||||
<input
|
||||
className={`input ${styles.openaiModelsEndpointInput}`}
|
||||
readOnly
|
||||
value={endpoint}
|
||||
/>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => void fetchClaudeModelDiscovery()}
|
||||
loading={fetching}
|
||||
disabled={disableControls || saving}
|
||||
>
|
||||
{t('ai_providers.claude_models_fetch_refresh')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
<Input
|
||||
label={t('ai_providers.claude_models_search_label')}
|
||||
placeholder={t('ai_providers.claude_models_search_placeholder')}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
disabled={fetching}
|
||||
/>
|
||||
{error && <div className="error-box">{error}</div>}
|
||||
{fetching ? (
|
||||
<div className={styles.sectionHint}>{t('ai_providers.claude_models_fetch_loading')}</div>
|
||||
) : models.length === 0 ? (
|
||||
<div className={styles.sectionHint}>{t('ai_providers.claude_models_fetch_empty')}</div>
|
||||
) : filteredModels.length === 0 ? (
|
||||
<div className={styles.sectionHint}>{t('ai_providers.claude_models_search_empty')}</div>
|
||||
) : (
|
||||
<div className={styles.modelDiscoveryList}>
|
||||
{filteredModels.map((model) => {
|
||||
const checked = selected.has(model.name);
|
||||
return (
|
||||
<label
|
||||
key={model.name}
|
||||
className={`${styles.modelDiscoveryRow} ${
|
||||
checked ? styles.modelDiscoveryRowSelected : ''
|
||||
}`}
|
||||
>
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={checked}
|
||||
onChange={() => toggleSelection(model.name)}
|
||||
/>
|
||||
<div className={styles.modelDiscoveryMeta}>
|
||||
<div className={styles.modelDiscoveryName}>
|
||||
{model.name}
|
||||
{model.alias && (
|
||||
<span className={styles.modelDiscoveryAlias}>{model.alias}</span>
|
||||
)}
|
||||
</div>
|
||||
{model.description && (
|
||||
<div className={styles.modelDiscoveryDesc}>{model.description}</div>
|
||||
)}
|
||||
</div>
|
||||
</label>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
</SecondaryScreenShell>
|
||||
);
|
||||
}
|
||||
@@ -3,3 +3,17 @@
|
||||
max-width: 960px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.upstreamApiKeyRow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.upstreamApiKeyHint {
|
||||
margin: 0;
|
||||
color: var(--text-secondary);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: $spacing-lg;
|
||||
padding-bottom: calc(var(--auth-files-action-bar-height, 0px) + 16px + env(safe-area-inset-bottom));
|
||||
}
|
||||
|
||||
.pageHeader {
|
||||
@@ -497,6 +498,15 @@
|
||||
}
|
||||
}
|
||||
|
||||
.fileCardSelected {
|
||||
border-color: var(--primary-color);
|
||||
box-shadow: 0 0 0 1px color-mix(in srgb, var(--primary-color) 70%, transparent);
|
||||
|
||||
&:hover {
|
||||
border-color: var(--primary-color);
|
||||
}
|
||||
}
|
||||
|
||||
.fileCardDisabled {
|
||||
opacity: 0.6;
|
||||
|
||||
@@ -528,6 +538,45 @@
|
||||
min-height: 28px;
|
||||
}
|
||||
|
||||
.selectionToggle {
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
margin: 0;
|
||||
flex-shrink: 0;
|
||||
border-radius: 7px;
|
||||
border: 1px solid var(--border-color);
|
||||
background: color-mix(in srgb, var(--bg-secondary) 92%, transparent);
|
||||
color: var(--primary-contrast, #fff);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
transition:
|
||||
border-color $transition-fast,
|
||||
background-color $transition-fast,
|
||||
box-shadow $transition-fast,
|
||||
transform $transition-fast;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--primary-color);
|
||||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--primary-color) 16%, transparent);
|
||||
}
|
||||
|
||||
&:active {
|
||||
transform: scale(0.95);
|
||||
}
|
||||
}
|
||||
|
||||
.selectionToggleActive {
|
||||
border-color: var(--primary-color);
|
||||
background: var(--primary-color);
|
||||
}
|
||||
|
||||
.selectionToggleActive svg {
|
||||
display: block;
|
||||
stroke-width: 2.4;
|
||||
}
|
||||
|
||||
.typeBadge {
|
||||
padding: 4px 10px;
|
||||
border-radius: 12px;
|
||||
@@ -878,6 +927,66 @@
|
||||
border-top: 1px solid var(--border-color);
|
||||
}
|
||||
|
||||
.batchActionContainer {
|
||||
position: fixed;
|
||||
left: var(--content-center-x, 50%);
|
||||
bottom: calc(16px + env(safe-area-inset-bottom));
|
||||
transform: translateX(-50%);
|
||||
z-index: 50;
|
||||
width: min(960px, calc(100vw - 24px));
|
||||
will-change: transform, opacity;
|
||||
}
|
||||
|
||||
.batchActionBar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: $spacing-sm;
|
||||
padding: 10px 12px;
|
||||
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);
|
||||
box-shadow: var(--shadow-lg);
|
||||
}
|
||||
|
||||
.batchActionLeft,
|
||||
.batchActionRight {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: $spacing-xs;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.batchActionRight {
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.batchSelectionText {
|
||||
font-size: 13px;
|
||||
font-weight: 600;
|
||||
color: var(--text-primary);
|
||||
margin-right: 2px;
|
||||
}
|
||||
|
||||
@include mobile {
|
||||
.batchActionContainer {
|
||||
width: calc(100vw - 16px);
|
||||
bottom: calc(12px + env(safe-area-inset-bottom));
|
||||
}
|
||||
|
||||
.batchActionBar {
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
}
|
||||
|
||||
.batchActionLeft,
|
||||
.batchActionRight {
|
||||
justify-content: center;
|
||||
}
|
||||
}
|
||||
|
||||
.pageInfo {
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
|
||||
+140
-2
@@ -1,6 +1,8 @@
|
||||
import { useCallback, useEffect, useMemo, useState, type ChangeEvent } from 'react';
|
||||
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ChangeEvent } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import gsap from 'gsap';
|
||||
import { useInterval } from '@/hooks/useInterval';
|
||||
import { useHeaderRefresh } from '@/hooks/useHeaderRefresh';
|
||||
import { usePageTransitionLayer } from '@/components/common/PageTransitionLayer';
|
||||
@@ -16,6 +18,7 @@ import {
|
||||
clampCardPageSize,
|
||||
getTypeColor,
|
||||
getTypeLabel,
|
||||
isRuntimeOnlyAuthFile,
|
||||
normalizeProviderKey,
|
||||
type QuotaProviderType,
|
||||
type ResolvedTheme
|
||||
@@ -54,10 +57,16 @@ export function AuthFilesPage() {
|
||||
const [detailModalOpen, setDetailModalOpen] = useState(false);
|
||||
const [selectedFile, setSelectedFile] = useState<AuthFileItem | null>(null);
|
||||
const [viewMode, setViewMode] = useState<'diagram' | 'list'>('list');
|
||||
const [batchActionBarVisible, setBatchActionBarVisible] = useState(false);
|
||||
const floatingBatchActionsRef = useRef<HTMLDivElement>(null);
|
||||
const previousSelectionCountRef = useRef(0);
|
||||
const selectionCountRef = useRef(0);
|
||||
|
||||
const { keyStats, usageDetails, loadKeyStats } = useAuthFilesStats();
|
||||
const {
|
||||
files,
|
||||
selectedFiles,
|
||||
selectionCount,
|
||||
loading,
|
||||
error,
|
||||
uploading,
|
||||
@@ -71,7 +80,12 @@ export function AuthFilesPage() {
|
||||
handleDelete,
|
||||
handleDeleteAll,
|
||||
handleDownload,
|
||||
handleStatusToggle
|
||||
handleStatusToggle,
|
||||
toggleSelect,
|
||||
selectAllVisible,
|
||||
deselectAll,
|
||||
batchSetStatus,
|
||||
batchDelete
|
||||
} = useAuthFilesData({ refreshKeyStats: loadKeyStats });
|
||||
|
||||
const statusBarCache = useAuthFilesStatusBarCache(files, usageDetails);
|
||||
@@ -240,6 +254,11 @@ export function AuthFilesPage() {
|
||||
const currentPage = Math.min(page, totalPages);
|
||||
const start = (currentPage - 1) * pageSize;
|
||||
const pageItems = filtered.slice(start, start + pageSize);
|
||||
const selectablePageItems = useMemo(
|
||||
() => pageItems.filter((file) => !isRuntimeOnlyAuthFile(file)),
|
||||
[pageItems]
|
||||
);
|
||||
const selectedNames = useMemo(() => Array.from(selectedFiles), [selectedFiles]);
|
||||
|
||||
const showDetails = (file: AuthFileItem) => {
|
||||
setSelectedFile(file);
|
||||
@@ -289,6 +308,72 @@ export function AuthFilesPage() {
|
||||
[filter, navigate]
|
||||
);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (typeof window === 'undefined') return;
|
||||
|
||||
const actionsEl = floatingBatchActionsRef.current;
|
||||
if (!actionsEl) {
|
||||
document.documentElement.style.removeProperty('--auth-files-action-bar-height');
|
||||
return;
|
||||
}
|
||||
|
||||
const updatePadding = () => {
|
||||
const height = actionsEl.getBoundingClientRect().height;
|
||||
document.documentElement.style.setProperty('--auth-files-action-bar-height', `${height}px`);
|
||||
};
|
||||
|
||||
updatePadding();
|
||||
window.addEventListener('resize', updatePadding);
|
||||
|
||||
const ro = typeof ResizeObserver === 'undefined' ? null : new ResizeObserver(updatePadding);
|
||||
ro?.observe(actionsEl);
|
||||
|
||||
return () => {
|
||||
ro?.disconnect();
|
||||
window.removeEventListener('resize', updatePadding);
|
||||
document.documentElement.style.removeProperty('--auth-files-action-bar-height');
|
||||
};
|
||||
}, [batchActionBarVisible, selectionCount]);
|
||||
|
||||
useEffect(() => {
|
||||
selectionCountRef.current = selectionCount;
|
||||
if (selectionCount > 0) {
|
||||
setBatchActionBarVisible(true);
|
||||
}
|
||||
}, [selectionCount]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
if (!batchActionBarVisible) return;
|
||||
const currentCount = selectionCount;
|
||||
const previousCount = previousSelectionCountRef.current;
|
||||
const actionsEl = floatingBatchActionsRef.current;
|
||||
if (!actionsEl) return;
|
||||
|
||||
gsap.killTweensOf(actionsEl);
|
||||
|
||||
if (currentCount > 0 && previousCount === 0) {
|
||||
gsap.fromTo(
|
||||
actionsEl,
|
||||
{ y: 56, autoAlpha: 0 },
|
||||
{ y: 0, autoAlpha: 1, duration: 0.28, ease: 'power3.out' }
|
||||
);
|
||||
} else if (currentCount === 0 && previousCount > 0) {
|
||||
gsap.to(actionsEl, {
|
||||
y: 56,
|
||||
autoAlpha: 0,
|
||||
duration: 0.22,
|
||||
ease: 'power2.in',
|
||||
onComplete: () => {
|
||||
if (selectionCountRef.current === 0) {
|
||||
setBatchActionBarVisible(false);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
previousSelectionCountRef.current = currentCount;
|
||||
}, [batchActionBarVisible, selectionCount]);
|
||||
|
||||
const renderFilterTags = () => (
|
||||
<div className={styles.filterTags}>
|
||||
{existingTypes.map((type) => {
|
||||
@@ -419,6 +504,7 @@ export function AuthFilesPage() {
|
||||
<AuthFileCard
|
||||
key={file.name}
|
||||
file={file}
|
||||
selected={selectedFiles.has(file.name)}
|
||||
resolvedTheme={resolvedTheme}
|
||||
disableControls={disableControls}
|
||||
deleting={deleting}
|
||||
@@ -432,6 +518,7 @@ export function AuthFilesPage() {
|
||||
onOpenPrefixProxyEditor={openPrefixProxyEditor}
|
||||
onDelete={handleDelete}
|
||||
onToggleStatus={handleStatusToggle}
|
||||
onToggleSelect={toggleSelect}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
@@ -520,6 +607,57 @@ export function AuthFilesPage() {
|
||||
onSave={handlePrefixProxySave}
|
||||
onChange={handlePrefixProxyChange}
|
||||
/>
|
||||
|
||||
{batchActionBarVisible && typeof document !== 'undefined'
|
||||
? createPortal(
|
||||
<div className={styles.batchActionContainer} ref={floatingBatchActionsRef}>
|
||||
<div className={styles.batchActionBar}>
|
||||
<div className={styles.batchActionLeft}>
|
||||
<span className={styles.batchSelectionText}>
|
||||
{t('auth_files.batch_selected', { count: selectionCount })}
|
||||
</span>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => selectAllVisible(pageItems)}
|
||||
disabled={selectablePageItems.length === 0}
|
||||
>
|
||||
{t('auth_files.batch_select_all')}
|
||||
</Button>
|
||||
<Button variant="ghost" size="sm" onClick={deselectAll}>
|
||||
{t('auth_files.batch_deselect')}
|
||||
</Button>
|
||||
</div>
|
||||
<div className={styles.batchActionRight}>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={() => batchSetStatus(selectedNames, true)}
|
||||
disabled={disableControls || selectedNames.length === 0}
|
||||
>
|
||||
{t('auth_files.batch_enable')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
onClick={() => batchSetStatus(selectedNames, false)}
|
||||
disabled={disableControls || selectedNames.length === 0}
|
||||
>
|
||||
{t('auth_files.batch_disable')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="danger"
|
||||
size="sm"
|
||||
onClick={() => batchDelete(selectedNames)}
|
||||
disabled={disableControls || selectedNames.length === 0}
|
||||
>
|
||||
{t('common.delete')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>,
|
||||
document.body
|
||||
)
|
||||
: null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ import { Button } from '@/components/ui/Button';
|
||||
import { Input } from '@/components/ui/Input';
|
||||
import { IconCheck, IconChevronDown, IconChevronUp, IconRefreshCw, IconSearch } from '@/components/ui/icons';
|
||||
import { VisualConfigEditor } from '@/components/config/VisualConfigEditor';
|
||||
import { DiffModal } from '@/components/config/DiffModal';
|
||||
import { useVisualConfig } from '@/hooks/useVisualConfig';
|
||||
import { useNotificationStore, useAuthStore, useThemeStore } from '@/stores';
|
||||
import { configFileApi } from '@/services/api/configFile';
|
||||
@@ -53,6 +54,9 @@ export function ConfigPage() {
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const [dirty, setDirty] = useState(false);
|
||||
const [diffModalOpen, setDiffModalOpen] = useState(false);
|
||||
const [serverYaml, setServerYaml] = useState('');
|
||||
const [mergedYaml, setMergedYaml] = useState('');
|
||||
|
||||
// Search state
|
||||
const [searchQuery, setSearchQuery] = useState('');
|
||||
@@ -73,6 +77,9 @@ export function ConfigPage() {
|
||||
const data = await configFileApi.fetchConfigYaml();
|
||||
setContent(data);
|
||||
setDirty(false);
|
||||
setDiffModalOpen(false);
|
||||
setServerYaml(data);
|
||||
setMergedYaml(data);
|
||||
loadVisualValuesFromYaml(data);
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : t('notification.refresh_failed');
|
||||
@@ -86,17 +93,20 @@ export function ConfigPage() {
|
||||
loadConfig();
|
||||
}, [loadConfig]);
|
||||
|
||||
const handleSave = async () => {
|
||||
const handleConfirmSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const previousCommercialMode = readCommercialModeFromYaml(content);
|
||||
const nextContent = activeTab === 'visual' ? applyVisualChangesToYaml(content) : content;
|
||||
const nextCommercialMode = readCommercialModeFromYaml(nextContent);
|
||||
const previousCommercialMode = readCommercialModeFromYaml(serverYaml);
|
||||
const nextCommercialMode = readCommercialModeFromYaml(mergedYaml);
|
||||
const commercialModeChanged = previousCommercialMode !== nextCommercialMode;
|
||||
await configFileApi.saveConfigYaml(nextContent);
|
||||
|
||||
await configFileApi.saveConfigYaml(mergedYaml);
|
||||
const latestContent = await configFileApi.fetchConfigYaml();
|
||||
setDirty(false);
|
||||
setDiffModalOpen(false);
|
||||
setContent(latestContent);
|
||||
setServerYaml(latestContent);
|
||||
setMergedYaml(latestContent);
|
||||
loadVisualValuesFromYaml(latestContent);
|
||||
showNotification(t('config_management.save_success'), 'success');
|
||||
if (commercialModeChanged) {
|
||||
@@ -110,6 +120,33 @@ export function ConfigPage() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaving(true);
|
||||
try {
|
||||
const nextMergedYaml = applyVisualChangesToYaml(content);
|
||||
const latestServerYaml = await configFileApi.fetchConfigYaml();
|
||||
|
||||
if (latestServerYaml === nextMergedYaml) {
|
||||
setDirty(false);
|
||||
setContent(latestServerYaml);
|
||||
setServerYaml(latestServerYaml);
|
||||
setMergedYaml(nextMergedYaml);
|
||||
loadVisualValuesFromYaml(latestServerYaml);
|
||||
showNotification(t('config_management.diff.no_changes'), 'info');
|
||||
return;
|
||||
}
|
||||
|
||||
setServerYaml(latestServerYaml);
|
||||
setMergedYaml(nextMergedYaml);
|
||||
setDiffModalOpen(true);
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : '';
|
||||
showNotification(`${t('notification.save_failed')}: ${message}`, 'error');
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleChange = useCallback((value: string) => {
|
||||
setContent(value);
|
||||
setDirty(true);
|
||||
@@ -326,7 +363,7 @@ export function ConfigPage() {
|
||||
type="button"
|
||||
className={styles.floatingActionButton}
|
||||
onClick={handleSave}
|
||||
disabled={disableControls || loading || saving || !isDirty}
|
||||
disabled={disableControls || loading || saving || !isDirty || diffModalOpen}
|
||||
title={t('config_management.save')}
|
||||
aria-label={t('config_management.save')}
|
||||
>
|
||||
@@ -474,6 +511,14 @@ export function ConfigPage() {
|
||||
</Card>
|
||||
|
||||
{typeof document !== 'undefined' ? createPortal(floatingActions, document.body) : null}
|
||||
<DiffModal
|
||||
open={diffModalOpen}
|
||||
original={serverYaml}
|
||||
modified={mergedYaml}
|
||||
onConfirm={handleConfirmSave}
|
||||
onCancel={() => setDiffModalOpen(false)}
|
||||
loading={saving}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,9 @@ import { Navigate, useRoutes, type Location } from 'react-router-dom';
|
||||
import { DashboardPage } from '@/pages/DashboardPage';
|
||||
import { AiProvidersPage } from '@/pages/AiProvidersPage';
|
||||
import { AiProvidersAmpcodeEditPage } from '@/pages/AiProvidersAmpcodeEditPage';
|
||||
import { AiProvidersClaudeEditLayout } from '@/pages/AiProvidersClaudeEditLayout';
|
||||
import { AiProvidersClaudeEditPage } from '@/pages/AiProvidersClaudeEditPage';
|
||||
import { AiProvidersClaudeModelsPage } from '@/pages/AiProvidersClaudeModelsPage';
|
||||
import { AiProvidersCodexEditPage } from '@/pages/AiProvidersCodexEditPage';
|
||||
import { AiProvidersGeminiEditPage } from '@/pages/AiProvidersGeminiEditPage';
|
||||
import { AiProvidersOpenAIEditLayout } from '@/pages/AiProvidersOpenAIEditLayout';
|
||||
@@ -28,8 +30,22 @@ const mainRoutes = [
|
||||
{ path: '/ai-providers/gemini/:index', element: <AiProvidersGeminiEditPage /> },
|
||||
{ path: '/ai-providers/codex/new', element: <AiProvidersCodexEditPage /> },
|
||||
{ path: '/ai-providers/codex/:index', element: <AiProvidersCodexEditPage /> },
|
||||
{ path: '/ai-providers/claude/new', element: <AiProvidersClaudeEditPage /> },
|
||||
{ path: '/ai-providers/claude/:index', element: <AiProvidersClaudeEditPage /> },
|
||||
{
|
||||
path: '/ai-providers/claude/new',
|
||||
element: <AiProvidersClaudeEditLayout />,
|
||||
children: [
|
||||
{ index: true, element: <AiProvidersClaudeEditPage /> },
|
||||
{ path: 'models', element: <AiProvidersClaudeModelsPage /> },
|
||||
],
|
||||
},
|
||||
{
|
||||
path: '/ai-providers/claude/:index',
|
||||
element: <AiProvidersClaudeEditLayout />,
|
||||
children: [
|
||||
{ index: true, element: <AiProvidersClaudeEditPage /> },
|
||||
{ path: 'models', element: <AiProvidersClaudeModelsPage /> },
|
||||
],
|
||||
},
|
||||
{ path: '/ai-providers/vertex/new', element: <AiProvidersVertexEditPage /> },
|
||||
{ path: '/ai-providers/vertex/:index', element: <AiProvidersVertexEditPage /> },
|
||||
{
|
||||
|
||||
+101
-3
@@ -7,16 +7,56 @@ import { normalizeModelList } from '@/utils/models';
|
||||
import { normalizeApiBase } from '@/utils/connection';
|
||||
import { apiCallApi, getApiCallErrorMessage } from './apiCall';
|
||||
|
||||
const DEFAULT_CLAUDE_BASE_URL = 'https://api.anthropic.com';
|
||||
const DEFAULT_ANTHROPIC_VERSION = '2023-06-01';
|
||||
const CLAUDE_MODELS_IN_FLIGHT = new Map<string, Promise<ReturnType<typeof normalizeModelList>>>();
|
||||
|
||||
const buildRequestSignature = (url: string, headers: Record<string, string>) => {
|
||||
const headerSignature = Object.entries(headers)
|
||||
.sort(([a], [b]) => a.toLowerCase().localeCompare(b.toLowerCase()))
|
||||
.map(([key, value]) => `${key}:${value}`)
|
||||
.join('|');
|
||||
return `${url}||${headerSignature}`;
|
||||
};
|
||||
|
||||
const buildModelsEndpoint = (baseUrl: string): string => {
|
||||
const normalized = normalizeApiBase(baseUrl);
|
||||
if (!normalized) return '';
|
||||
return `${normalized}/models`;
|
||||
const trimmed = normalized.replace(/\/+$/g, '');
|
||||
if (/\/models$/i.test(trimmed)) return trimmed;
|
||||
return `${trimmed}/models`;
|
||||
};
|
||||
|
||||
const buildV1ModelsEndpoint = (baseUrl: string): string => {
|
||||
const normalized = normalizeApiBase(baseUrl);
|
||||
if (!normalized) return '';
|
||||
return `${normalized}/v1/models`;
|
||||
const trimmed = normalized.replace(/\/+$/g, '');
|
||||
if (/\/v1\/models$/i.test(trimmed)) return trimmed;
|
||||
if (/\/v1$/i.test(trimmed)) return `${trimmed}/models`;
|
||||
return `${trimmed}/v1/models`;
|
||||
};
|
||||
|
||||
const buildClaudeModelsEndpoint = (baseUrl: string): string => {
|
||||
const normalized = normalizeApiBase(baseUrl);
|
||||
const fallback = normalized || DEFAULT_CLAUDE_BASE_URL;
|
||||
let trimmed = fallback.replace(/\/+$/g, '');
|
||||
trimmed = trimmed.replace(/\/v1\/models$/i, '');
|
||||
trimmed = trimmed.replace(/\/v1(?:\/.*)?$/i, '');
|
||||
return `${trimmed}/v1/models`;
|
||||
};
|
||||
|
||||
const hasHeader = (headers: Record<string, string>, name: string) => {
|
||||
const target = name.toLowerCase();
|
||||
return Object.keys(headers).some((key) => key.toLowerCase() === target);
|
||||
};
|
||||
|
||||
const resolveBearerTokenFromAuthorization = (headers: Record<string, string>): string => {
|
||||
const entry = Object.entries(headers).find(([key]) => key.toLowerCase() === 'authorization');
|
||||
if (!entry) return '';
|
||||
const value = String(entry[1] ?? '').trim();
|
||||
if (!value) return '';
|
||||
const match = value.match(/^Bearer\s+(.+)$/i);
|
||||
return match?.[1]?.trim() || '';
|
||||
};
|
||||
|
||||
export const modelsApi = {
|
||||
@@ -72,5 +112,63 @@ export const modelsApi = {
|
||||
|
||||
const payload = result.body ?? result.bodyText;
|
||||
return normalizeModelList(payload, { dedupe: true });
|
||||
}
|
||||
},
|
||||
|
||||
buildClaudeModelsEndpoint(baseUrl: string) {
|
||||
return buildClaudeModelsEndpoint(baseUrl);
|
||||
},
|
||||
|
||||
/**
|
||||
* Fetch Claude models from /v1/models via api-call.
|
||||
* Anthropic requires `x-api-key` and `anthropic-version` headers.
|
||||
*/
|
||||
async fetchClaudeModelsViaApiCall(
|
||||
baseUrl: string,
|
||||
apiKey?: string,
|
||||
headers: Record<string, string> = {}
|
||||
) {
|
||||
const endpoint = buildClaudeModelsEndpoint(baseUrl);
|
||||
if (!endpoint) {
|
||||
throw new Error('Invalid base url');
|
||||
}
|
||||
|
||||
const resolvedHeaders = { ...headers };
|
||||
let resolvedApiKey = String(apiKey ?? '').trim();
|
||||
if (!resolvedApiKey && !hasHeader(resolvedHeaders, 'x-api-key')) {
|
||||
resolvedApiKey = resolveBearerTokenFromAuthorization(resolvedHeaders);
|
||||
}
|
||||
|
||||
if (resolvedApiKey && !hasHeader(resolvedHeaders, 'x-api-key')) {
|
||||
resolvedHeaders['x-api-key'] = resolvedApiKey;
|
||||
}
|
||||
if (!hasHeader(resolvedHeaders, 'anthropic-version')) {
|
||||
resolvedHeaders['anthropic-version'] = DEFAULT_ANTHROPIC_VERSION;
|
||||
}
|
||||
|
||||
const signature = buildRequestSignature(endpoint, resolvedHeaders);
|
||||
const existing = CLAUDE_MODELS_IN_FLIGHT.get(signature);
|
||||
if (existing) return existing;
|
||||
|
||||
const request = (async () => {
|
||||
const result = await apiCallApi.request({
|
||||
method: 'GET',
|
||||
url: endpoint,
|
||||
header: Object.keys(resolvedHeaders).length ? resolvedHeaders : undefined
|
||||
});
|
||||
|
||||
if (result.statusCode < 200 || result.statusCode >= 300) {
|
||||
throw new Error(getApiCallErrorMessage(result));
|
||||
}
|
||||
|
||||
const payload = result.body ?? result.bodyText;
|
||||
return normalizeModelList(payload, { dedupe: true });
|
||||
})();
|
||||
|
||||
CLAUDE_MODELS_IN_FLIGHT.set(signature, request);
|
||||
try {
|
||||
return await request;
|
||||
} finally {
|
||||
CLAUDE_MODELS_IN_FLIGHT.delete(signature);
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
@@ -10,3 +10,4 @@ export { useConfigStore } from './useConfigStore';
|
||||
export { useModelsStore } from './useModelsStore';
|
||||
export { useQuotaStore } from './useQuotaStore';
|
||||
export { useOpenAIEditDraftStore } from './useOpenAIEditDraftStore';
|
||||
export { useClaudeEditDraftStore } from './useClaudeEditDraftStore';
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
/**
|
||||
* Claude provider editor draft state.
|
||||
*
|
||||
* Why this exists:
|
||||
* - The app uses `PageTransition` with iOS-style stacked routes for `/ai-providers/*`.
|
||||
* - Entering `/ai-providers/claude/.../models` creates a new route layer, so component-local state
|
||||
* inside the Claude edit layout is not shared between the edit screen and the model picker screen.
|
||||
* - This store makes the Claude edit draft shared across route layers keyed by provider index/new.
|
||||
*/
|
||||
|
||||
import type { SetStateAction } from 'react';
|
||||
import { create } from 'zustand';
|
||||
import type { ProviderFormState } from '@/components/providers/types';
|
||||
|
||||
export type ClaudeTestStatus = 'idle' | 'loading' | 'success' | 'error';
|
||||
|
||||
type ClaudeEditDraft = {
|
||||
initialized: boolean;
|
||||
form: ProviderFormState;
|
||||
testModel: string;
|
||||
testStatus: ClaudeTestStatus;
|
||||
testMessage: string;
|
||||
};
|
||||
|
||||
interface ClaudeEditDraftState {
|
||||
drafts: Record<string, ClaudeEditDraft>;
|
||||
ensureDraft: (key: string) => void;
|
||||
initDraft: (
|
||||
key: string,
|
||||
draft: Omit<ClaudeEditDraft, 'initialized'>
|
||||
) => void;
|
||||
setDraftForm: (
|
||||
key: string,
|
||||
action: SetStateAction<ProviderFormState>
|
||||
) => void;
|
||||
setDraftTestModel: (key: string, action: SetStateAction<string>) => void;
|
||||
setDraftTestStatus: (
|
||||
key: string,
|
||||
action: SetStateAction<ClaudeTestStatus>
|
||||
) => void;
|
||||
setDraftTestMessage: (key: string, action: SetStateAction<string>) => void;
|
||||
clearDraft: (key: string) => void;
|
||||
}
|
||||
|
||||
const resolveAction = <T,>(action: SetStateAction<T>, prev: T): T =>
|
||||
typeof action === 'function' ? (action as (previous: T) => T)(prev) : action;
|
||||
|
||||
const buildEmptyForm = (): ProviderFormState => ({
|
||||
apiKey: '',
|
||||
prefix: '',
|
||||
baseUrl: '',
|
||||
proxyUrl: '',
|
||||
headers: [],
|
||||
models: [],
|
||||
excludedModels: [],
|
||||
modelEntries: [{ name: '', alias: '' }],
|
||||
excludedText: '',
|
||||
});
|
||||
|
||||
const buildEmptyDraft = (): ClaudeEditDraft => ({
|
||||
initialized: false,
|
||||
form: buildEmptyForm(),
|
||||
testModel: '',
|
||||
testStatus: 'idle',
|
||||
testMessage: '',
|
||||
});
|
||||
|
||||
export const useClaudeEditDraftStore = create<ClaudeEditDraftState>((set, get) => ({
|
||||
drafts: {},
|
||||
|
||||
ensureDraft: (key) => {
|
||||
if (!key) return;
|
||||
const existing = get().drafts[key];
|
||||
if (existing) return;
|
||||
set((state) => ({
|
||||
drafts: { ...state.drafts, [key]: buildEmptyDraft() },
|
||||
}));
|
||||
},
|
||||
|
||||
initDraft: (key, draft) => {
|
||||
if (!key) return;
|
||||
const existing = get().drafts[key];
|
||||
if (existing?.initialized) return;
|
||||
set((state) => ({
|
||||
drafts: {
|
||||
...state.drafts,
|
||||
[key]: { ...draft, initialized: true },
|
||||
},
|
||||
}));
|
||||
},
|
||||
|
||||
setDraftForm: (key, action) => {
|
||||
if (!key) return;
|
||||
set((state) => {
|
||||
const existing = state.drafts[key] ?? buildEmptyDraft();
|
||||
const nextForm = resolveAction(action, existing.form);
|
||||
return {
|
||||
drafts: {
|
||||
...state.drafts,
|
||||
[key]: { ...existing, initialized: true, form: nextForm },
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
setDraftTestModel: (key, action) => {
|
||||
if (!key) return;
|
||||
set((state) => {
|
||||
const existing = state.drafts[key] ?? buildEmptyDraft();
|
||||
const nextValue = resolveAction(action, existing.testModel);
|
||||
return {
|
||||
drafts: {
|
||||
...state.drafts,
|
||||
[key]: { ...existing, initialized: true, testModel: nextValue },
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
setDraftTestStatus: (key, action) => {
|
||||
if (!key) return;
|
||||
set((state) => {
|
||||
const existing = state.drafts[key] ?? buildEmptyDraft();
|
||||
const nextValue = resolveAction(action, existing.testStatus);
|
||||
return {
|
||||
drafts: {
|
||||
...state.drafts,
|
||||
[key]: { ...existing, initialized: true, testStatus: nextValue },
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
setDraftTestMessage: (key, action) => {
|
||||
if (!key) return;
|
||||
set((state) => {
|
||||
const existing = state.drafts[key] ?? buildEmptyDraft();
|
||||
const nextValue = resolveAction(action, existing.testMessage);
|
||||
return {
|
||||
drafts: {
|
||||
...state.drafts,
|
||||
[key]: { ...existing, initialized: true, testMessage: nextValue },
|
||||
},
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
clearDraft: (key) => {
|
||||
if (!key) return;
|
||||
set((state) => {
|
||||
if (!state.drafts[key]) return state;
|
||||
const next = { ...state.drafts };
|
||||
delete next[key];
|
||||
return { drafts: next };
|
||||
});
|
||||
},
|
||||
}));
|
||||
@@ -134,8 +134,8 @@ export const GEMINI_CLI_QUOTA_GROUPS: GeminiCliQuotaGroupDefinition[] = [
|
||||
{
|
||||
id: 'gemini-pro-series',
|
||||
label: 'Gemini Pro Series',
|
||||
preferredModelId: 'gemini-3-pro-preview',
|
||||
modelIds: ['gemini-3-pro-preview', 'gemini-2.5-pro'],
|
||||
preferredModelId: 'gemini-3-1-pro-preview',
|
||||
modelIds: ['gemini-3-1-pro-preview', 'gemini-3-pro-preview', 'gemini-2.5-pro'],
|
||||
},
|
||||
];
|
||||
|
||||
|
||||
Reference in New Issue
Block a user