Compare commits

...

14 Commits

Author SHA1 Message Date
Supra4E8C
ceddf7925f feat(api-keys): enhance API key display with new layout and styling 2025-11-23 12:31:17 +08:00
Supra4E8C
55c1cd84b3 feat(i18n): add support for 'antigravity' file type and update UI elements 2025-11-21 20:59:05 +08:00
Supra4E8C
111a1fe4ba Merge branch 'main' of https://github.com/router-for-me/Cli-Proxy-API-Management-Center 2025-11-21 17:54:05 +08:00
Supra4E8C
958b0b4e4b fix(i18n): update API endpoint references from /v1/model to /v1/models 2025-11-21 17:44:15 +08:00
hkfires
71d1436590 fix(api-keys): delegate key actions and safely encode values 2025-11-21 12:50:14 +08:00
Supra4E8C
d088be8e65 feat(openai): implement model discovery UI and functionality for fetching models 2025-11-21 12:35:46 +08:00
Supra4E8C
c8dc446268 style: update file-type badge colors for improved visibility 2025-11-21 12:04:15 +08:00
hkfires
1edafc637a feat: centralize config refresh handling and prevent races 2025-11-21 11:34:12 +08:00
hkfires
608be95020 feat(logs): refresh on reconnect and section activation 2025-11-21 10:59:21 +08:00
hkfires
323485445d refactor(config): reload editor and auth files via events 2025-11-21 10:36:04 +08:00
hkfires
e58d462153 refactor(api): add raw request helper and centralize headers 2025-11-21 10:16:06 +08:00
hkfires
a6344a6a61 refactor(usage): load stats via config events 2025-11-21 09:57:56 +08:00
hkfires
d2fc784116 refactor(settings): delegate config UI updates to module 2025-11-21 09:48:50 +08:00
hkfires
a8b8bdc11c refactor: centralize API client and config caching 2025-11-21 09:42:16 +08:00
18 changed files with 1173 additions and 260 deletions

69
app.js
View File

@@ -31,14 +31,24 @@ import {
// 核心服务导入
import { createErrorHandler } from './src/core/error-handler.js';
import { connectionModule } from './src/core/connection.js';
import { ApiClient } from './src/core/api-client.js';
import { ConfigService } from './src/core/config-service.js';
import { createEventBus } from './src/core/event-bus.js';
// CLI Proxy API 管理界面 JavaScript
class CLIProxyManager {
constructor() {
// 仅保存基础地址(不含 /v0/management请求时自动补齐
// 事件总线
this.events = createEventBus();
// API 客户端(规范化基础地址、封装请求)
this.apiClient = new ApiClient({
onVersionUpdate: (headers) => this.updateVersionFromHeaders(headers)
});
const detectedBase = this.detectApiBaseFromLocation();
this.apiBase = detectedBase;
this.apiUrl = this.computeApiUrl(this.apiBase);
this.apiClient.setApiBase(detectedBase);
this.apiBase = this.apiClient.apiBase;
this.apiUrl = this.apiClient.apiUrl;
this.managementKey = '';
this.isConnected = false;
this.isLoggedIn = false;
@@ -46,13 +56,21 @@ class CLIProxyManager {
this.serverVersion = null;
this.serverBuildDate = null;
// 配置缓存 - 改为分段缓存
this.configCache = {}; // 改为对象,按配置段缓存
this.cacheTimestamps = {}; // 每个配置段的时间戳
// 配置缓存 - 改为分段缓存(交由 ConfigService 管理)
this.cacheExpiry = CACHE_EXPIRY_MS;
this.configService = new ConfigService({
apiClient: this.apiClient,
cacheExpiry: this.cacheExpiry
});
this.configCache = this.configService.cache;
this.cacheTimestamps = this.configService.cacheTimestamps;
// 状态更新定时器
this.statusUpdateTimer = null;
this.lastConnectionStatusEmitted = null;
this.isGlobalRefreshInProgress = false;
this.registerCoreEventHandlers();
// 日志自动刷新定时器
this.logsRefreshTimer = null;
@@ -134,6 +152,15 @@ class CLIProxyManager {
init() {
this.initUiVersion();
this.initializeTheme();
this.registerCoreEventHandlers();
this.registerSettingsListeners();
this.registerUsageListeners();
if (typeof this.registerLogsListeners === 'function') {
this.registerLogsListeners();
}
if (typeof this.registerConfigEditorListeners === 'function') {
this.registerConfigEditorListeners();
}
this.checkLoginStatus();
this.bindEvents();
this.setupNavigation();
@@ -145,6 +172,33 @@ class CLIProxyManager {
this.updateLoginConnectionInfo();
// 检查主机名,如果不是 localhost 或 127.0.0.1,则隐藏 OAuth 登录框
this.checkHostAndHideOAuth();
if (typeof this.registerAuthFilesListeners === 'function') {
this.registerAuthFilesListeners();
}
}
registerCoreEventHandlers() {
if (!this.events || typeof this.events.on !== 'function') {
return;
}
this.events.on('config:refresh-requested', async (event) => {
const detail = event?.detail || {};
const forceRefresh = detail.forceRefresh !== false;
// 避免并发触发导致重复请求
if (this.isGlobalRefreshInProgress) {
return;
}
await this.runGlobalRefresh(forceRefresh);
});
}
async runGlobalRefresh(forceRefresh = false) {
this.isGlobalRefreshInProgress = true;
try {
await this.loadAllData(forceRefresh);
} finally {
this.isGlobalRefreshInProgress = false;
}
}
// 检查主机名并隐藏 OAuth 登录框
@@ -560,6 +614,9 @@ class CLIProxyManager {
// 关闭模态框
closeModal() {
document.getElementById('modal').style.display = 'none';
if (typeof this.closeOpenAIModelDiscovery === 'function') {
this.closeOpenAIModelDiscovery();
}
}
}

28
i18n.js
View File

@@ -210,6 +210,18 @@ const i18n = {
'ai_providers.openai_model_name_placeholder': '模型名称,如 moonshotai/kimi-k2:free',
'ai_providers.openai_model_alias_placeholder': '模型别名 (可选)',
'ai_providers.openai_models_add_btn': '添加模型',
'ai_providers.openai_models_fetch_button': '从 /v1/models 获取',
'ai_providers.openai_models_fetch_title': '从 /v1/models 选择模型',
'ai_providers.openai_models_fetch_hint': '使用上方 Base URL 调用 /v1/models 端点,附带首个 API KeyBearer与自定义请求头。',
'ai_providers.openai_models_fetch_url_label': '请求地址',
'ai_providers.openai_models_fetch_refresh': '重新获取',
'ai_providers.openai_models_fetch_loading': '正在从 /v1/models 获取模型列表...',
'ai_providers.openai_models_fetch_empty': '未获取到模型,请检查端点或鉴权信息。',
'ai_providers.openai_models_fetch_error': '获取模型失败',
'ai_providers.openai_models_fetch_back': '返回编辑',
'ai_providers.openai_models_fetch_apply': '添加所选模型',
'ai_providers.openai_models_fetch_invalid_url': '请先填写有效的 Base URL',
'ai_providers.openai_models_fetch_added': '已添加 {count} 个新模型',
'ai_providers.openai_edit_modal_title': '编辑OpenAI兼容提供商',
'ai_providers.openai_edit_modal_name_label': '提供商名称:',
'ai_providers.openai_edit_modal_url_label': 'Base URL:',
@@ -260,6 +272,7 @@ const i18n = {
'auth_files.filter_aistudio': 'AIStudio',
'auth_files.filter_claude': 'Claude',
'auth_files.filter_codex': 'Codex',
'auth_files.filter_antigravity': 'Antigravity',
'auth_files.filter_iflow': 'iFlow',
'auth_files.filter_vertex': 'Vertex',
'auth_files.filter_empty': '空文件',
@@ -270,6 +283,7 @@ const i18n = {
'auth_files.type_aistudio': 'AIStudio',
'auth_files.type_claude': 'Claude',
'auth_files.type_codex': 'Codex',
'auth_files.type_antigravity': 'Antigravity',
'auth_files.type_iflow': 'iFlow',
'auth_files.type_vertex': 'Vertex',
'auth_files.type_empty': '空文件',
@@ -718,6 +732,18 @@ const i18n = {
'ai_providers.openai_model_name_placeholder': 'Model name, e.g. moonshotai/kimi-k2:free',
'ai_providers.openai_model_alias_placeholder': 'Model alias (optional)',
'ai_providers.openai_models_add_btn': 'Add Model',
'ai_providers.openai_models_fetch_button': 'Fetch via /v1/models',
'ai_providers.openai_models_fetch_title': 'Pick Models from /v1/models',
'ai_providers.openai_models_fetch_hint': 'Call the /v1/models endpoint using the Base URL above, sending the first API key as Bearer plus custom headers.',
'ai_providers.openai_models_fetch_url_label': 'Request URL',
'ai_providers.openai_models_fetch_refresh': 'Refresh',
'ai_providers.openai_models_fetch_loading': 'Fetching models from /v1/models...',
'ai_providers.openai_models_fetch_empty': 'No models returned. Please check the endpoint or auth.',
'ai_providers.openai_models_fetch_error': 'Failed to fetch models',
'ai_providers.openai_models_fetch_back': 'Back to edit',
'ai_providers.openai_models_fetch_apply': 'Add selected models',
'ai_providers.openai_models_fetch_invalid_url': 'Please enter a valid Base URL first',
'ai_providers.openai_models_fetch_added': '{count} new models added',
'ai_providers.openai_edit_modal_title': 'Edit OpenAI Compatible Provider',
'ai_providers.openai_edit_modal_name_label': 'Provider Name:',
'ai_providers.openai_edit_modal_url_label': 'Base URL:',
@@ -768,6 +794,7 @@ const i18n = {
'auth_files.filter_aistudio': 'AIStudio',
'auth_files.filter_claude': 'Claude',
'auth_files.filter_codex': 'Codex',
'auth_files.filter_antigravity': 'Antigravity',
'auth_files.filter_iflow': 'iFlow',
'auth_files.filter_vertex': 'Vertex',
'auth_files.filter_empty': 'Empty',
@@ -778,6 +805,7 @@ const i18n = {
'auth_files.type_aistudio': 'AIStudio',
'auth_files.type_claude': 'Claude',
'auth_files.type_codex': 'Codex',
'auth_files.type_antigravity': 'Antigravity',
'auth_files.type_iflow': 'iFlow',
'auth_files.type_vertex': 'Vertex',
'auth_files.type_empty': 'Empty',

View File

@@ -502,6 +502,7 @@
<button class="filter-btn" data-type="aistudio" data-i18n-text="auth_files.filter_aistudio">AIStudio</button>
<button class="filter-btn" data-type="claude" data-i18n-text="auth_files.filter_claude">Claude</button>
<button class="filter-btn" data-type="codex" data-i18n-text="auth_files.filter_codex">Codex</button>
<button class="filter-btn" data-type="antigravity" data-i18n-text="auth_files.filter_antigravity">Antigravity</button>
<button class="filter-btn" data-type="iflow" data-i18n-text="auth_files.filter_iflow">iFlow</button>
<button class="filter-btn" data-type="vertex" data-i18n-text="auth_files.filter_vertex">Vertex</button>
<button class="filter-btn" data-type="empty" data-i18n-text="auth_files.filter_empty">Empty</button>

87
src/core/api-client.js Normal file
View File

@@ -0,0 +1,87 @@
// API 客户端:负责规范化基础地址、构造完整 URL、发送请求并回传版本信息
export class ApiClient {
constructor({ apiBase = '', managementKey = '', onVersionUpdate = null } = {}) {
this.apiBase = '';
this.apiUrl = '';
this.managementKey = managementKey || '';
this.onVersionUpdate = onVersionUpdate;
this.setApiBase(apiBase);
}
buildHeaders(options = {}) {
const customHeaders = options.headers || {};
const headers = {
'Authorization': `Bearer ${this.managementKey}`,
...customHeaders
};
const hasContentType = Object.keys(headers).some(key => key.toLowerCase() === 'content-type');
const body = options.body;
const isFormData = typeof FormData !== 'undefined' && body instanceof FormData;
if (!hasContentType && !isFormData) {
headers['Content-Type'] = 'application/json';
}
return headers;
}
normalizeBase(input) {
let base = (input || '').trim();
if (!base) return '';
base = base.replace(/\/?v0\/management\/?$/i, '');
base = base.replace(/\/+$/i, '');
if (!/^https?:\/\//i.test(base)) {
base = 'http://' + base;
}
return base;
}
computeApiUrl(base) {
const normalized = this.normalizeBase(base);
if (!normalized) return '';
return normalized.replace(/\/$/, '') + '/v0/management';
}
setApiBase(newBase) {
this.apiBase = this.normalizeBase(newBase);
this.apiUrl = this.computeApiUrl(this.apiBase);
return this.apiUrl;
}
setManagementKey(key) {
this.managementKey = key || '';
}
async request(endpoint, options = {}) {
const url = `${this.apiUrl}${endpoint}`;
const headers = this.buildHeaders(options);
const response = await fetch(url, {
...options,
headers
});
if (typeof this.onVersionUpdate === 'function') {
this.onVersionUpdate(response.headers);
}
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error || `HTTP ${response.status}`);
}
return await response.json();
}
// 返回原始 Response供下载/自定义解析使用
async requestRaw(endpoint, options = {}) {
const url = `${this.apiUrl}${endpoint}`;
const headers = this.buildHeaders(options);
const response = await fetch(url, {
...options,
headers
});
if (typeof this.onVersionUpdate === 'function') {
this.onVersionUpdate(response.headers);
}
return response;
}
}

View File

@@ -0,0 +1,70 @@
// 配置缓存服务:负责分段/全量读取配置与缓存控制,不涉及任何 DOM
export class ConfigService {
constructor({ apiClient, cacheExpiry }) {
this.apiClient = apiClient;
this.cacheExpiry = cacheExpiry;
this.cache = {};
this.cacheTimestamps = {};
}
isCacheValid(section = null) {
if (section) {
if (!(section in this.cache) || !(section in this.cacheTimestamps)) {
return false;
}
return (Date.now() - this.cacheTimestamps[section]) < this.cacheExpiry;
}
if (!this.cache['__full__'] || !this.cacheTimestamps['__full__']) {
return false;
}
return (Date.now() - this.cacheTimestamps['__full__']) < this.cacheExpiry;
}
clearCache(section = null) {
if (section) {
delete this.cache[section];
delete this.cacheTimestamps[section];
if (this.cache['__full__']) {
delete this.cache['__full__'][section];
}
return;
}
Object.keys(this.cache).forEach(key => delete this.cache[key]);
Object.keys(this.cacheTimestamps).forEach(key => delete this.cacheTimestamps[key]);
}
async getConfig(section = null, forceRefresh = false) {
const now = Date.now();
if (section && !forceRefresh && this.isCacheValid(section)) {
return this.cache[section];
}
if (!section && !forceRefresh && this.isCacheValid()) {
return this.cache['__full__'];
}
const config = await this.apiClient.request('/config');
if (section) {
this.cache[section] = config[section];
this.cacheTimestamps[section] = now;
if (this.cache['__full__']) {
this.cache['__full__'][section] = config[section];
} else {
this.cache['__full__'] = config;
this.cacheTimestamps['__full__'] = now;
}
return config[section];
}
this.cache['__full__'] = config;
this.cacheTimestamps['__full__'] = now;
Object.keys(config).forEach(key => {
this.cache[key] = config[key];
this.cacheTimestamps[key] = now;
});
return config;
}
}

View File

@@ -7,33 +7,31 @@ import { secureStorage } from '../utils/secure-storage.js';
export const connectionModule = {
// 规范化基础地址,移除尾部斜杠与 /v0/management
normalizeBase(input) {
let base = (input || '').trim();
if (!base) return '';
// 若用户粘贴了完整地址,剥离后缀
base = base.replace(/\/?v0\/management\/?$/i, '');
base = base.replace(/\/+$/i, '');
// 自动补 http://
if (!/^https?:\/\//i.test(base)) {
base = 'http://' + base;
}
return base;
return this.apiClient.normalizeBase(input);
},
// 由基础地址生成完整管理 API 地址
computeApiUrl(base) {
const b = this.normalizeBase(base);
if (!b) return '';
return b.replace(/\/$/, '') + '/v0/management';
return this.apiClient.computeApiUrl(base);
},
setApiBase(newBase) {
this.apiBase = this.normalizeBase(newBase);
this.apiUrl = this.computeApiUrl(this.apiBase);
this.apiClient.setApiBase(newBase);
this.apiBase = this.apiClient.apiBase;
this.apiUrl = this.apiClient.apiUrl;
secureStorage.setItem('apiBase', this.apiBase);
secureStorage.setItem('apiUrl', this.apiUrl); // 兼容旧字段
this.updateLoginConnectionInfo();
},
setManagementKey(key, { persist = true } = {}) {
this.managementKey = key || '';
this.apiClient.setManagementKey(this.managementKey);
if (persist) {
secureStorage.setItem('managementKey', this.managementKey);
}
},
// 加载设置(简化版,仅加载内部状态)
loadSettings() {
secureStorage.migratePlaintextKeys(['apiBase', 'apiUrl', 'managementKey']);
@@ -51,9 +49,7 @@ export const connectionModule = {
this.setApiBase(this.detectApiBaseFromLocation());
}
if (savedKey) {
this.managementKey = savedKey;
}
this.setManagementKey(savedKey || '', { persist: false });
this.updateLoginConnectionInfo();
},
@@ -149,27 +145,8 @@ export const connectionModule = {
// API 请求方法
async makeRequest(endpoint, options = {}) {
const url = `${this.apiUrl}${endpoint}`;
const headers = {
'Authorization': `Bearer ${this.managementKey}`,
'Content-Type': 'application/json',
...options.headers
};
try {
const response = await fetch(url, {
...options,
headers
});
this.updateVersionFromHeaders(response.headers);
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error || `HTTP ${response.status}`);
}
return await response.json();
return await this.apiClient.request(endpoint, options);
} catch (error) {
console.error('API请求失败:', error);
throw error;
@@ -236,6 +213,17 @@ export const connectionModule = {
// 更新连接信息显示
this.updateConnectionInfo();
if (this.events && typeof this.events.emit === 'function') {
const shouldEmit = this.lastConnectionStatusEmitted !== this.isConnected;
if (shouldEmit) {
this.events.emit('connection:status-changed', {
isConnected: this.isConnected,
apiBase: this.apiBase
});
this.lastConnectionStatusEmitted = this.isConnected;
}
}
},
// 检查连接状态
@@ -270,66 +258,15 @@ export const connectionModule = {
// 检查缓存是否有效
isCacheValid(section = null) {
if (section) {
// 检查特定配置段的缓存
// 注意:配置值可能是 false、0、'' 等 falsy 值,不能用 ! 判断
if (!(section in this.configCache) || !(section in this.cacheTimestamps)) {
return false;
}
return (Date.now() - this.cacheTimestamps[section]) < this.cacheExpiry;
}
// 检查全局缓存(兼容旧代码)
if (!this.configCache['__full__'] || !this.cacheTimestamps['__full__']) {
return false;
}
return (Date.now() - this.cacheTimestamps['__full__']) < this.cacheExpiry;
return this.configService.isCacheValid(section);
},
// 获取配置(优先使用缓存,支持按段获取)
async getConfig(section = null, forceRefresh = false) {
const now = Date.now();
// 如果请求特定配置段且该段缓存有效
if (section && !forceRefresh && this.isCacheValid(section)) {
this.updateConnectionStatus();
return this.configCache[section];
}
// 如果请求全部配置且全局缓存有效
if (!section && !forceRefresh && this.isCacheValid()) {
this.updateConnectionStatus();
return this.configCache['__full__'];
}
try {
const config = await this.makeRequest('/config');
if (section) {
// 缓存特定配置段
this.configCache[section] = config[section];
this.cacheTimestamps[section] = now;
// 同时更新全局缓存中的这一段
if (this.configCache['__full__']) {
this.configCache['__full__'][section] = config[section];
} else {
// 如果全局缓存不存在,也创建它
this.configCache['__full__'] = config;
this.cacheTimestamps['__full__'] = now;
}
this.updateConnectionStatus();
return config[section];
}
// 缓存全部配置
this.configCache['__full__'] = config;
this.cacheTimestamps['__full__'] = now;
// 同时缓存各个配置段
Object.keys(config).forEach(key => {
this.configCache[key] = config[key];
this.cacheTimestamps[key] = now;
});
const config = await this.configService.getConfig(section, forceRefresh);
this.configCache = this.configService.cache;
this.cacheTimestamps = this.configService.cacheTimestamps;
this.updateConnectionStatus();
return config;
} catch (error) {
@@ -340,18 +277,10 @@ export const connectionModule = {
// 清除缓存(支持清除特定配置段)
clearCache(section = null) {
if (section) {
// 清除特定配置段的缓存
delete this.configCache[section];
delete this.cacheTimestamps[section];
// 同时清除全局缓存中的这一段
if (this.configCache['__full__']) {
delete this.configCache['__full__'][section];
}
} else {
// 清除所有缓存
this.configCache = {};
this.cacheTimestamps = {};
this.configService.clearCache(section);
this.configCache = this.configService.cache;
this.cacheTimestamps = this.configService.cacheTimestamps;
if (!section) {
this.configYamlCache = '';
}
},
@@ -400,15 +329,14 @@ export const connectionModule = {
// 从配置中提取并设置各个设置项现在传递keyStats
await this.updateSettingsFromConfig(config, keyStats);
// 认证文件需要单独加载,因为不在配置中
await this.loadAuthFiles(keyStats);
// 使用统计需要单独加载复用已获取的usage数据
await this.loadUsageStats(usageData);
// 加载配置文件编辑器内容
await this.loadConfigFileEditor(forceRefresh);
this.refreshConfigEditor();
if (this.events && typeof this.events.emit === 'function') {
this.events.emit('data:config-loaded', {
config,
usageData,
keyStats,
forceRefresh
});
}
console.log('配置加载完成,使用缓存:', !forceRefresh && this.isCacheValid());
} catch (error) {
@@ -416,78 +344,11 @@ export const connectionModule = {
}
},
// 从配置对象更新所有设置
// 从配置对象更新所有设置 —— 委派给 settings 模块,保持兼容旧调用
async updateSettingsFromConfig(config, keyStats = null) {
// 调试设置
if (config.debug !== undefined) {
document.getElementById('debug-toggle').checked = config.debug;
if (typeof this.applySettingsFromConfig === 'function') {
return this.applySettingsFromConfig(config, keyStats);
}
// 代理设置
if (config['proxy-url'] !== undefined) {
document.getElementById('proxy-url').value = config['proxy-url'] || '';
}
// 请求重试设置
if (config['request-retry'] !== undefined) {
document.getElementById('request-retry').value = config['request-retry'];
}
// 配额超出行为
if (config['quota-exceeded']) {
if (config['quota-exceeded']['switch-project'] !== undefined) {
document.getElementById('switch-project-toggle').checked = config['quota-exceeded']['switch-project'];
}
if (config['quota-exceeded']['switch-preview-model'] !== undefined) {
document.getElementById('switch-preview-model-toggle').checked = config['quota-exceeded']['switch-preview-model'];
}
}
if (config['usage-statistics-enabled'] !== undefined) {
const usageToggle = document.getElementById('usage-statistics-enabled-toggle');
if (usageToggle) {
usageToggle.checked = config['usage-statistics-enabled'];
}
}
// 日志记录设置
if (config['logging-to-file'] !== undefined) {
const loggingToggle = document.getElementById('logging-to-file-toggle');
if (loggingToggle) {
loggingToggle.checked = config['logging-to-file'];
}
// 显示或隐藏日志查看栏目
this.toggleLogsNavItem(config['logging-to-file']);
}
if (config['request-log'] !== undefined) {
const requestLogToggle = document.getElementById('request-log-toggle');
if (requestLogToggle) {
requestLogToggle.checked = config['request-log'];
}
}
if (config['ws-auth'] !== undefined) {
const wsAuthToggle = document.getElementById('ws-auth-toggle');
if (wsAuthToggle) {
wsAuthToggle.checked = config['ws-auth'];
}
}
// API 密钥
if (config['api-keys']) {
this.renderApiKeys(config['api-keys']);
}
// Gemini keys
await this.renderGeminiKeys(this.getGeminiKeysFromConfig(config), keyStats);
// Codex 密钥
await this.renderCodexKeys(Array.isArray(config['codex-api-key']) ? config['codex-api-key'] : [], keyStats);
// Claude 密钥
await this.renderClaudeKeys(Array.isArray(config['claude-api-key']) ? config['claude-api-key'] : [], keyStats);
// OpenAI 兼容提供商
await this.renderOpenAIProviders(Array.isArray(config['openai-compatibility']) ? config['openai-compatibility'] : [], keyStats);
},
detectApiBaseFromLocation() {

10
src/core/event-bus.js Normal file
View File

@@ -0,0 +1,10 @@
// 轻量事件总线,避免模块之间的直接耦合
export function createEventBus() {
const target = new EventTarget();
const on = (type, listener) => target.addEventListener(type, listener);
const off = (type, listener) => target.removeEventListener(type, listener);
const emit = (type, detail = {}) => target.dispatchEvent(new CustomEvent(type, { detail }));
return { on, off, emit };
}

View File

@@ -9,6 +9,56 @@ const getStatsBySource = (stats) => {
return stats || {};
};
const buildModelEndpoint = (baseUrl) => {
if (!baseUrl) return '';
const trimmed = String(baseUrl).trim().replace(/\/+$/g, '');
if (!trimmed) return '';
// 如果 base 已以 /v1 结尾,直接拼 /models否则拼 /v1/models避免丢失中间路径
if (trimmed.endsWith('/v1')) {
return `${trimmed}/models`;
}
return `${trimmed}/v1/models`;
};
const normalizeModelList = (payload) => {
const toModel = (entry) => {
if (typeof entry === 'string') {
return { name: entry };
}
if (!entry || typeof entry !== 'object') {
return null;
}
const name = entry.id || entry.name || entry.model || entry.value;
if (!name) return null;
const alias = entry.alias || entry.display_name || entry.displayName;
const description = entry.description || entry.note || entry.comment;
const model = { name: String(name) };
if (alias && alias !== name) {
model.alias = String(alias);
}
if (description) {
model.description = String(description);
}
return model;
};
if (Array.isArray(payload)) {
return payload.map(toModel).filter(Boolean);
}
if (payload && typeof payload === 'object') {
if (Array.isArray(payload.data)) {
return payload.data.map(toModel).filter(Boolean);
}
if (Array.isArray(payload.models)) {
return payload.models.map(toModel).filter(Boolean);
}
}
return [];
};
export async function loadGeminiKeys() {
try {
const config = await this.getConfig();
@@ -979,6 +1029,251 @@ export async function renderOpenAIProviders(providers, keyStats = null) {
}).join('');
}
const getOpenAIContext = (mode = 'new') => {
const isEdit = mode === 'edit';
return {
mode: isEdit ? 'edit' : 'new',
baseUrlInputId: isEdit ? 'edit-provider-url' : 'new-provider-url',
apiKeyWrapperId: isEdit ? 'edit-openai-keys-wrapper' : 'new-openai-keys-wrapper',
headerWrapperId: isEdit ? 'edit-openai-headers-wrapper' : 'new-openai-headers-wrapper',
modelWrapperId: isEdit ? 'edit-provider-models-wrapper' : 'new-provider-models-wrapper'
};
};
function ensureOpenAIModelDiscoveryCard(manager) {
let overlay = document.getElementById('openai-model-discovery');
if (overlay) {
return overlay;
}
overlay = document.createElement('div');
overlay.id = 'openai-model-discovery';
overlay.className = 'model-discovery-overlay';
overlay.innerHTML = `
<div class="model-discovery-card">
<div class="model-discovery-header">
<div class="model-discovery-title">
<h3>${i18n.t('ai_providers.openai_models_fetch_title')}</h3>
<p class="form-hint">${i18n.t('ai_providers.openai_models_fetch_hint')}</p>
</div>
<button type="button" class="btn btn-secondary" id="openai-model-discovery-back">${i18n.t('ai_providers.openai_models_fetch_back')}</button>
</div>
<div class="form-group">
<label>${i18n.t('ai_providers.openai_models_fetch_url_label')}</label>
<div class="input-group">
<input type="text" id="openai-model-discovery-url" readonly>
<button type="button" class="btn btn-secondary" id="openai-model-discovery-refresh">${i18n.t('ai_providers.openai_models_fetch_refresh')}</button>
</div>
</div>
<div id="openai-model-discovery-status" class="model-discovery-status"></div>
<div id="openai-model-discovery-list" class="model-discovery-list"></div>
<div class="modal-actions">
<button class="btn btn-secondary" id="openai-model-discovery-cancel">${i18n.t('common.cancel')}</button>
<button class="btn btn-primary" id="openai-model-discovery-apply">${i18n.t('ai_providers.openai_models_fetch_apply')}</button>
</div>
</div>
`;
document.body.appendChild(overlay);
const bind = (id, handler) => {
const el = document.getElementById(id);
if (el) {
el.addEventListener('click', handler);
}
};
bind('openai-model-discovery-back', () => manager.closeOpenAIModelDiscovery());
bind('openai-model-discovery-cancel', () => manager.closeOpenAIModelDiscovery());
bind('openai-model-discovery-refresh', () => manager.refreshOpenAIModelDiscovery());
bind('openai-model-discovery-apply', () => manager.applyOpenAIModelDiscoverySelection());
return overlay;
}
export function setOpenAIModelDiscoveryStatus(message = '', type = 'info') {
const status = document.getElementById('openai-model-discovery-status');
if (!status) return;
status.textContent = message;
status.className = `model-discovery-status ${type}`;
}
export function renderOpenAIModelDiscoveryList(models = []) {
const list = document.getElementById('openai-model-discovery-list');
if (!list) return;
if (!models.length) {
list.innerHTML = `
<div class="model-discovery-empty">
<i class="fas fa-box-open"></i>
<span>${i18n.t('ai_providers.openai_models_fetch_empty')}</span>
</div>
`;
return;
}
list.innerHTML = models.map((model, index) => {
const name = this.escapeHtml(model.name || '');
const alias = model.alias ? `<span class="model-discovery-alias">${this.escapeHtml(model.alias)}</span>` : '';
const desc = model.description ? `<div class="model-discovery-desc">${this.escapeHtml(model.description)}</div>` : '';
return `
<label class="model-discovery-row">
<input type="checkbox" class="model-discovery-checkbox" data-model-index="${index}">
<div class="model-discovery-meta">
<div class="model-discovery-name">${name} ${alias}</div>
${desc}
</div>
</label>
`;
}).join('');
}
export function openOpenAIModelDiscovery(mode = 'new') {
const context = getOpenAIContext(mode);
const baseInput = document.getElementById(context.baseUrlInputId);
const baseUrl = baseInput ? baseInput.value.trim() : '';
if (!baseUrl) {
this.showNotification(i18n.t('ai_providers.openai_models_fetch_invalid_url'), 'error');
return;
}
const endpoint = buildModelEndpoint(baseUrl);
if (!endpoint) {
this.showNotification(i18n.t('ai_providers.openai_models_fetch_invalid_url'), 'error');
return;
}
const apiKeyEntries = this.collectApiKeyEntryInputs(context.apiKeyWrapperId);
const firstKey = Array.isArray(apiKeyEntries) ? apiKeyEntries.find(entry => entry && entry['api-key']) : null;
const headers = this.collectHeaderInputs(context.headerWrapperId) || {};
if (firstKey && !headers.Authorization && !headers.authorization) {
headers.Authorization = `Bearer ${firstKey['api-key']}`;
}
ensureOpenAIModelDiscoveryCard(this).classList.add('active');
this.openAIModelDiscoveryContext = {
...context,
endpoint,
headers,
discoveredModels: []
};
const urlInput = document.getElementById('openai-model-discovery-url');
if (urlInput) {
urlInput.value = endpoint;
}
this.renderOpenAIModelDiscoveryList([]);
this.setOpenAIModelDiscoveryStatus(i18n.t('ai_providers.openai_models_fetch_loading'), 'info');
this.refreshOpenAIModelDiscovery();
}
export async function refreshOpenAIModelDiscovery() {
const context = this.openAIModelDiscoveryContext;
if (!context || !context.endpoint) {
return;
}
this.setOpenAIModelDiscoveryStatus(i18n.t('ai_providers.openai_models_fetch_loading'), 'info');
const list = document.getElementById('openai-model-discovery-list');
if (list) {
list.innerHTML = '<div class="model-discovery-empty"><i class="fas fa-spinner fa-spin"></i></div>';
}
try {
const response = await fetch(context.endpoint, {
headers: context.headers || {}
});
if (!response.ok) {
throw new Error(`${response.status} ${response.statusText}`);
}
let data;
try {
data = await response.json();
} catch (err) {
const text = await response.text();
throw new Error(text || err.message || 'Invalid JSON');
}
const models = normalizeModelList(data);
context.discoveredModels = models;
this.renderOpenAIModelDiscoveryList(models);
if (!models.length) {
this.setOpenAIModelDiscoveryStatus(i18n.t('ai_providers.openai_models_fetch_empty'), 'warning');
} else {
this.setOpenAIModelDiscoveryStatus('', 'info');
}
} catch (error) {
context.discoveredModels = [];
this.renderOpenAIModelDiscoveryList([]);
this.setOpenAIModelDiscoveryStatus(`${i18n.t('ai_providers.openai_models_fetch_error')}: ${error.message}`, 'error');
}
}
export function applyOpenAIModelDiscoverySelection() {
const context = this.openAIModelDiscoveryContext;
if (!context || !Array.isArray(context.discoveredModels) || !context.discoveredModels.length) {
this.closeOpenAIModelDiscovery();
return;
}
const list = document.getElementById('openai-model-discovery-list');
if (!list) {
this.closeOpenAIModelDiscovery();
return;
}
const selectedIndices = Array.from(list.querySelectorAll('.model-discovery-checkbox:checked'))
.map(input => Number.parseInt(input.getAttribute('data-model-index') || '-1', 10))
.filter(index => Number.isFinite(index) && index >= 0 && index < context.discoveredModels.length);
const selectedModels = selectedIndices.map(index => context.discoveredModels[index]);
if (!selectedModels.length) {
this.closeOpenAIModelDiscovery();
return;
}
const existing = this.collectModelInputs(context.modelWrapperId);
const mergedMap = new Map();
existing.forEach(model => {
if (model && model.name) {
mergedMap.set(model.name, { ...model });
}
});
let addedCount = 0;
selectedModels.forEach(model => {
const name = model && model.name;
if (!name) return;
if (!mergedMap.has(name)) {
mergedMap.set(name, { name, ...(model.alias ? { alias: model.alias } : {}) });
addedCount++;
}
});
this.populateModelFields(context.modelWrapperId, Array.from(mergedMap.values()));
this.closeOpenAIModelDiscovery();
if (addedCount > 0) {
const template = i18n.t('ai_providers.openai_models_fetch_added');
const message = template.replace('{count}', addedCount);
this.showNotification(message, 'success');
}
}
export function closeOpenAIModelDiscovery() {
const overlay = document.getElementById('openai-model-discovery');
if (overlay) {
overlay.classList.remove('active');
}
this.openAIModelDiscoveryContext = null;
}
export function showAddOpenAIProviderModal() {
const modal = document.getElementById('modal');
const modalBody = document.getElementById('modal-body');
@@ -1009,7 +1304,12 @@ export function showAddOpenAIProviderModal() {
<label>${i18n.t('ai_providers.openai_add_modal_models_label')}</label>
<p class="form-hint">${i18n.t('ai_providers.openai_models_hint')}</p>
<div id="new-provider-models-wrapper" class="model-input-list"></div>
<button type="button" class="btn btn-secondary" onclick="manager.addModelField('new-provider-models-wrapper')">${i18n.t('ai_providers.openai_models_add_btn')}</button>
<div class="model-actions-inline">
<button type="button" class="btn btn-secondary" onclick="manager.addModelField('new-provider-models-wrapper')">${i18n.t('ai_providers.openai_models_add_btn')}</button>
<button type="button" class="btn btn-secondary" onclick="manager.openOpenAIModelDiscovery('new')">
<i class="fas fa-download"></i> ${i18n.t('ai_providers.openai_models_fetch_button')}
</button>
</div>
</div>
<div class="modal-actions">
<button class="btn btn-secondary" onclick="manager.closeModal()">${i18n.t('common.cancel')}</button>
@@ -1104,7 +1404,12 @@ export function editOpenAIProvider(index, provider) {
<label>${i18n.t('ai_providers.openai_edit_modal_models_label')}</label>
<p class="form-hint">${i18n.t('ai_providers.openai_models_hint')}</p>
<div id="edit-provider-models-wrapper" class="model-input-list"></div>
<button type="button" class="btn btn-secondary" onclick="manager.addModelField('edit-provider-models-wrapper')">${i18n.t('ai_providers.openai_models_add_btn')}</button>
<div class="model-actions-inline">
<button type="button" class="btn btn-secondary" onclick="manager.addModelField('edit-provider-models-wrapper')">${i18n.t('ai_providers.openai_models_add_btn')}</button>
<button type="button" class="btn btn-secondary" onclick="manager.openOpenAIModelDiscovery('edit')">
<i class="fas fa-download"></i> ${i18n.t('ai_providers.openai_models_fetch_button')}
</button>
</div>
</div>
<div class="modal-actions">
<button class="btn btn-secondary" onclick="manager.closeModal()">${i18n.t('common.cancel')}</button>
@@ -1292,6 +1597,12 @@ export const aiProvidersModule = {
editOpenAIProvider,
updateOpenAIProvider,
deleteOpenAIProvider,
openOpenAIModelDiscovery,
refreshOpenAIModelDiscovery,
renderOpenAIModelDiscoveryList,
setOpenAIModelDiscoveryStatus,
applyOpenAIModelDiscoverySelection,
closeOpenAIModelDiscovery,
addModelField,
populateModelFields,
collectModelInputs,

View File

@@ -26,27 +26,36 @@ export const apiKeysModule = {
return;
}
container.innerHTML = keys.map((key, index) => {
const rows = keys.map((key, index) => {
const normalizedKey = typeof key === 'string' ? key : String(key ?? '');
const maskedDisplay = this.escapeHtml(this.maskApiKey(normalizedKey));
const keyArgument = JSON.stringify(normalizedKey).replace(/"/g, '&quot;');
const keyArgument = encodeURIComponent(normalizedKey);
return `
<div class="key-item">
<div class="item-content">
<div class="item-title">${i18n.t('api_keys.item_title')} #${index + 1}</div>
<div class="item-value">${maskedDisplay}</div>
</div>
<div class="item-actions">
<button class="btn btn-secondary" onclick="manager.editApiKey(${index}, ${keyArgument})">
<i class="fas fa-edit"></i>
</button>
<button class="btn btn-danger" onclick="manager.deleteApiKey(${index})">
<i class="fas fa-trash"></i>
</button>
<div class="key-table-row">
<div class="key-badge">#${index + 1}</div>
<div class="key-table-value">
<div class="item-title">${i18n.t('api_keys.item_title')}</div>
<div class="key-value">${maskedDisplay}</div>
</div>
<div class="item-actions compact">
<button class="btn btn-secondary" data-action="edit-api-key" data-index="${index}" data-key="${keyArgument}">
<i class="fas fa-edit"></i>
</button>
<button class="btn btn-danger" data-action="delete-api-key" data-index="${index}">
<i class="fas fa-trash"></i>
</button>
</div>
</div>
`;
}).join('');
container.innerHTML = `
<div class="key-table">
${rows}
</div>
`;
}).join('');
this.bindApiKeyListEvents(container);
},
// 注意: escapeHtml, maskApiKey, normalizeArrayResponse
@@ -336,5 +345,43 @@ export const apiKeysModule = {
} catch (error) {
this.showNotification(`${i18n.t('notification.delete_failed')}: ${error.message}`, 'error');
}
},
bindApiKeyListEvents(container = null) {
if (this.apiKeyListEventsBound) {
return;
}
const listContainer = container || document.getElementById('api-keys-list');
if (!listContainer) return;
listContainer.addEventListener('click', (event) => {
const button = event.target.closest('[data-action][data-index]');
if (!button || !listContainer.contains(button)) return;
const action = button.dataset.action;
const index = Number(button.dataset.index);
if (!Number.isFinite(index)) return;
switch (action) {
case 'edit-api-key': {
const rawKey = button.dataset.key || '';
let decodedKey = '';
try {
decodedKey = decodeURIComponent(rawKey);
} catch (e) {
decodedKey = rawKey;
}
this.editApiKey(index, decodedKey);
break;
}
case 'delete-api-key':
this.deleteApiKey(index);
break;
default:
break;
}
});
this.apiKeyListEventsBound = true;
}
};

View File

@@ -172,6 +172,9 @@ export const authFilesModule = {
case 'codex':
typeDisplayKey = 'auth_files.type_codex';
break;
case 'antigravity':
typeDisplayKey = 'auth_files.type_antigravity';
break;
case 'iflow':
typeDisplayKey = 'auth_files.type_iflow';
break;
@@ -467,6 +470,7 @@ export const authFilesModule = {
{ type: 'aistudio', labelKey: 'auth_files.filter_aistudio' },
{ type: 'claude', labelKey: 'auth_files.filter_claude' },
{ type: 'codex', labelKey: 'auth_files.filter_codex' },
{ type: 'antigravity', labelKey: 'auth_files.filter_antigravity' },
{ type: 'iflow', labelKey: 'auth_files.filter_iflow' },
{ type: 'vertex', labelKey: 'auth_files.filter_vertex' },
{ type: 'empty', labelKey: 'auth_files.filter_empty' }
@@ -724,16 +728,11 @@ export const authFilesModule = {
this.vertexImportState.loading = true;
this.updateVertexImportButtonState();
const response = await fetch(`${this.apiUrl}/vertex/import`, {
const response = await this.apiClient.requestRaw('/vertex/import', {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.managementKey}`
},
body: formData
});
this.updateVersionFromHeaders(response.headers);
if (!response.ok) {
let errorMessage = `HTTP ${response.status}`;
try {
@@ -879,13 +878,7 @@ export const authFilesModule = {
async downloadAuthFile(filename) {
try {
const response = await fetch(`${this.apiUrl}/auth-files/download?name=${encodeURIComponent(filename)}`, {
headers: {
'Authorization': `Bearer ${this.managementKey}`
}
});
this.updateVersionFromHeaders(response.headers);
const response = await this.apiClient.requestRaw(`/auth-files/download?name=${encodeURIComponent(filename)}`);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
@@ -1017,16 +1010,11 @@ export const authFilesModule = {
const formData = new FormData();
formData.append('file', file, file.name);
const response = await fetch(`${this.apiUrl}/auth-files`, {
const response = await this.apiClient.requestRaw('/auth-files', {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.managementKey}`
},
body: formData
});
this.updateVersionFromHeaders(response.headers);
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(errorData.error || `HTTP ${response.status}`);
@@ -1041,5 +1029,20 @@ export const authFilesModule = {
// 清空文件输入框,允许重复上传同一文件
event.target.value = '';
}
},
registerAuthFilesListeners() {
if (!this.events || typeof this.events.on !== 'function') {
return;
}
this.events.on('data:config-loaded', async (event) => {
const detail = event?.detail || {};
const keyStats = detail.keyStats || null;
try {
await this.loadAuthFiles(keyStats);
} catch (error) {
console.error('加载认证文件失败:', error);
}
});
}
};

View File

@@ -152,16 +152,13 @@ export const configEditorModule = {
const requestUrl = '/config.yaml';
try {
const response = await fetch(`${this.apiUrl}${requestUrl}`, {
const response = await this.apiClient.requestRaw(requestUrl, {
method: 'GET',
headers: {
'Authorization': `Bearer ${this.managementKey}`,
'Accept': 'application/yaml'
}
});
this.updateVersionFromHeaders(response.headers);
if (!response.ok) {
const errorText = await response.text().catch(() => '');
const message = errorText || `HTTP ${response.status}`;
@@ -212,7 +209,9 @@ export const configEditorModule = {
this.showNotification(i18n.t('config_management.save_success'), 'success');
this.updateConfigEditorStatus('success', i18n.t('config_management.status_saved'));
this.clearCache();
await this.loadAllData(true);
if (this.events && typeof this.events.emit === 'function') {
this.events.emit('config:refresh-requested', { forceRefresh: true });
}
} catch (error) {
const errorMessage = `${i18n.t('config_management.status_save_failed')}: ${error.message}`;
this.updateConfigEditorStatus('error', errorMessage);
@@ -227,18 +226,15 @@ export const configEditorModule = {
},
async writeConfigFile(endpoint, yamlText) {
const response = await fetch(`${this.apiUrl}${endpoint}`, {
const response = await this.apiClient.requestRaw(endpoint, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${this.managementKey}`,
'Content-Type': 'application/yaml',
'Accept': 'application/json, text/plain, */*'
},
body: yamlText
});
this.updateVersionFromHeaders(response.headers);
if (!response.ok) {
const contentType = response.headers.get('content-type') || '';
let errorText = '';
@@ -258,5 +254,20 @@ export const configEditorModule = {
throw new Error(data.message || data.error || 'Server rejected the update');
}
}
},
registerConfigEditorListeners() {
if (!this.events || typeof this.events.on !== 'function') {
return;
}
this.events.on('data:config-loaded', async (event) => {
const detail = event?.detail || {};
try {
await this.loadConfigFileEditor(detail.forceRefresh || false);
this.refreshConfigEditor();
} catch (error) {
console.error('加载配置文件失败:', error);
}
});
}
};

View File

@@ -12,6 +12,11 @@ export const languageModule = {
},
toggleLanguage() {
if (this.isLanguageRefreshInProgress) {
return;
}
this.isLanguageRefreshInProgress = true;
const currentLang = i18n.currentLanguage;
const newLang = currentLang === 'zh-CN' ? 'en-US' : 'zh-CN';
i18n.setLanguage(newLang);
@@ -19,8 +24,13 @@ export const languageModule = {
this.updateThemeButtons();
this.updateConnectionStatus();
if (this.isLoggedIn && this.isConnected) {
this.loadAllData(true);
if (this.isLoggedIn && this.isConnected && this.events && typeof this.events.emit === 'function') {
this.events.emit('config:refresh-requested', { forceRefresh: true });
}
// 简单释放锁,避免短时间内的重复触发
setTimeout(() => {
this.isLanguageRefreshInProgress = false;
}, 500);
}
};

View File

@@ -39,7 +39,7 @@ export const loginModule = {
async attemptAutoLogin(apiBase, managementKey) {
try {
this.setApiBase(apiBase);
this.managementKey = managementKey;
this.setManagementKey(managementKey);
const savedProxy = localStorage.getItem('proxyUrl');
if (savedProxy) {
@@ -79,8 +79,7 @@ export const loginModule = {
async login(apiBase, managementKey) {
try {
this.setApiBase(apiBase);
this.managementKey = managementKey;
secureStorage.setItem('managementKey', this.managementKey);
this.setManagementKey(managementKey);
await this.testConnection();
@@ -101,6 +100,7 @@ export const loginModule = {
this.clearCache();
this.stopStatusUpdateTimer();
this.resetVersionInfo();
this.setManagementKey('', { persist: false });
localStorage.removeItem('isLoggedIn');
secureStorage.removeItem('managementKey');
@@ -132,8 +132,7 @@ export const loginModule = {
}
this.hideLoginError();
this.managementKey = managementKey;
secureStorage.setItem('managementKey', this.managementKey);
this.setManagementKey(managementKey);
await this.login(this.apiBase, this.managementKey);
} catch (error) {
@@ -210,6 +209,7 @@ export const loginModule = {
if (loginKeyInput && savedKey) {
loginKeyInput.value = savedKey;
}
this.setManagementKey(savedKey || '', { persist: false });
this.setupLoginAutoSave();
},
@@ -220,9 +220,9 @@ export const loginModule = {
const resetButton = document.getElementById('login-reset-api-base');
const saveKey = (val) => {
if (val.trim()) {
this.managementKey = val;
secureStorage.setItem('managementKey', this.managementKey);
const trimmed = val.trim();
if (trimmed) {
this.setManagementKey(trimmed);
}
};
const saveKeyDebounced = this.debounce(saveKey, 500);

View File

@@ -406,5 +406,29 @@ export const logsModule = {
}
this.showNotification(i18n.t('logs.auto_refresh_disabled'), 'info');
}
},
registerLogsListeners() {
if (!this.events || typeof this.events.on !== 'function') {
return;
}
this.events.on('connection:status-changed', (event) => {
const detail = event?.detail || {};
if (detail.isConnected) {
// 仅在日志页激活时刷新,避免非日志页面触发请求
const logsSection = document.getElementById('logs');
if (logsSection && logsSection.classList.contains('active')) {
this.refreshLogs(false);
}
} else {
this.latestLogTimestamp = null;
}
});
this.events.on('navigation:section-activated', (event) => {
const detail = event?.detail || {};
if (detail.sectionId === 'logs' && this.isConnected) {
this.refreshLogs(false);
}
});
}
};

View File

@@ -15,12 +15,13 @@ export const navigationModule = {
section.classList.add('active');
}
if (sectionId === 'logs') {
this.refreshLogs(false);
} else if (sectionId === 'config-management') {
if (sectionId === 'config-management') {
this.loadConfigFileEditor();
this.refreshConfigEditor();
}
if (this.events && typeof this.events.emit === 'function') {
this.events.emit('navigation:section-activated', { sectionId });
}
});
});
},

View File

@@ -275,6 +275,119 @@ export async function updateSwitchPreviewModel(enabled) {
}
}
// 统一应用配置到界面,供 connection 模块或事件总线调用
export async function applySettingsFromConfig(config = {}, keyStats = null) {
if (!config || typeof config !== 'object') {
return;
}
// 调试设置
if (config.debug !== undefined) {
const toggle = document.getElementById('debug-toggle');
if (toggle) {
toggle.checked = config.debug;
}
}
// 代理设置
if (config['proxy-url'] !== undefined) {
const proxyInput = document.getElementById('proxy-url');
if (proxyInput) {
proxyInput.value = config['proxy-url'] || '';
}
}
// 请求重试设置
if (config['request-retry'] !== undefined) {
const retryInput = document.getElementById('request-retry');
if (retryInput) {
retryInput.value = config['request-retry'];
}
}
// 配额超出行为
if (config['quota-exceeded']) {
if (config['quota-exceeded']['switch-project'] !== undefined) {
const toggle = document.getElementById('switch-project-toggle');
if (toggle) {
toggle.checked = config['quota-exceeded']['switch-project'];
}
}
if (config['quota-exceeded']['switch-preview-model'] !== undefined) {
const toggle = document.getElementById('switch-preview-model-toggle');
if (toggle) {
toggle.checked = config['quota-exceeded']['switch-preview-model'];
}
}
}
if (config['usage-statistics-enabled'] !== undefined) {
const usageToggle = document.getElementById('usage-statistics-enabled-toggle');
if (usageToggle) {
usageToggle.checked = config['usage-statistics-enabled'];
}
}
// 日志记录设置
if (config['logging-to-file'] !== undefined) {
const loggingToggle = document.getElementById('logging-to-file-toggle');
if (loggingToggle) {
loggingToggle.checked = config['logging-to-file'];
}
if (typeof this.toggleLogsNavItem === 'function') {
this.toggleLogsNavItem(config['logging-to-file']);
}
}
if (config['request-log'] !== undefined) {
const requestLogToggle = document.getElementById('request-log-toggle');
if (requestLogToggle) {
requestLogToggle.checked = config['request-log'];
}
}
if (config['ws-auth'] !== undefined) {
const wsAuthToggle = document.getElementById('ws-auth-toggle');
if (wsAuthToggle) {
wsAuthToggle.checked = config['ws-auth'];
}
}
// API 密钥
if (config['api-keys'] && typeof this.renderApiKeys === 'function') {
this.renderApiKeys(config['api-keys']);
}
// Gemini keys
if (typeof this.renderGeminiKeys === 'function') {
await this.renderGeminiKeys(this.getGeminiKeysFromConfig(config), keyStats);
}
// Codex 密钥
if (typeof this.renderCodexKeys === 'function') {
await this.renderCodexKeys(Array.isArray(config['codex-api-key']) ? config['codex-api-key'] : [], keyStats);
}
// Claude 密钥
if (typeof this.renderClaudeKeys === 'function') {
await this.renderClaudeKeys(Array.isArray(config['claude-api-key']) ? config['claude-api-key'] : [], keyStats);
}
// OpenAI 兼容提供商
if (typeof this.renderOpenAIProviders === 'function') {
await this.renderOpenAIProviders(Array.isArray(config['openai-compatibility']) ? config['openai-compatibility'] : [], keyStats);
}
}
// 设置模块订阅全局事件,减少与连接层耦合
export function registerSettingsListeners() {
if (!this.events || typeof this.events.on !== 'function') {
return;
}
this.events.on('data:config-loaded', (event) => {
const detail = event?.detail || {};
this.applySettingsFromConfig(detail.config || {}, detail.keyStats || null);
});
}
export const settingsModule = {
updateDebug,
updateProxyUrl,
@@ -292,5 +405,7 @@ export const settingsModule = {
updateWsAuth,
updateLoggingToFile,
updateSwitchProject,
updateSwitchPreviewModel
updateSwitchPreviewModel,
applySettingsFromConfig,
registerSettingsListeners
};

View File

@@ -741,5 +741,18 @@ export const usageModule = {
getTokensChartData,
switchRequestsPeriod,
switchTokensPeriod,
updateApiStatsTable
updateApiStatsTable,
registerUsageListeners
};
// 订阅全局事件,基于配置加载结果渲染使用统计
export function registerUsageListeners() {
if (!this.events || typeof this.events.on !== 'function') {
return;
}
this.events.on('data:config-loaded', (event) => {
const detail = event?.detail || {};
const usageData = detail.usageData || null;
this.loadUsageStats(usageData);
});
}

View File

@@ -1552,6 +1552,118 @@ input:checked+.slider:before {
overflow-y: auto;
}
/* API 密钥列表压缩布局 */
.key-table {
display: flex;
flex-direction: column;
gap: 8px;
}
.key-table-row {
display: grid;
grid-template-columns: 72px 1fr auto;
align-items: center;
background: var(--bg-quaternary);
border: 1px solid var(--border-primary);
border-radius: 10px;
padding: 10px 12px;
transition: all 0.2s ease;
}
.key-table-row:hover {
background: var(--bg-tertiary);
border-color: var(--border-secondary);
transform: translateY(-1px);
}
.key-badge {
display: inline-flex;
align-items: center;
justify-content: center;
height: 32px;
min-width: 52px;
padding: 0 10px;
border-radius: 10px;
background: var(--bg-secondary);
color: var(--primary-color);
font-weight: 700;
font-size: 14px;
border: 1px solid var(--border-primary);
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.06);
}
.key-table-value {
display: flex;
flex-direction: column;
gap: 4px;
min-width: 0;
}
.key-table .item-title {
margin: 0;
font-size: 13px;
color: var(--text-secondary);
}
.key-value {
background: var(--bg-secondary);
border-radius: 8px;
padding: 7px 10px;
font-family: "SFMono-Regular", Menlo, Consolas, "Liberation Mono", monospace;
font-size: 13px;
color: var(--text-primary);
font-weight: 600;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
line-height: 1.4;
}
.item-actions.compact {
position: static;
transform: none;
gap: 6px;
justify-content: flex-end;
}
.item-actions.compact .btn {
min-width: 34px;
height: 34px;
padding: 0;
border-radius: 6px;
box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
}
.item-actions.compact .btn:hover {
transform: translateY(-1px);
box-shadow: 0 3px 6px rgba(0, 0, 0, 0.12);
}
.item-actions.compact .btn i {
font-size: 14px;
}
@media (max-width: 768px) {
.key-table-row {
grid-template-columns: 1fr;
row-gap: 10px;
}
.item-actions.compact {
justify-content: flex-start;
}
.key-badge {
width: fit-content;
}
.key-value {
white-space: normal;
word-break: break-all;
}
}
.file-list {
/* 认证文件列表填满页面,保留版本信息空间 */
max-height: calc(100vh - 300px); /* 减去导航栏、padding和版本信息的高度 */
@@ -1777,23 +1889,23 @@ input:checked+.slider:before {
}
.file-type-badge.gemini-cli {
background: #4f8de2;
color: #ffffff;
background: #e7efff;
color: #1e4fa3;
}
[data-theme="dark"] .file-type-badge.gemini-cli {
background: #4f8de2;
color: #eaf1fb;
background: #1c3f73;
color: #a8c7ff;
}
.file-type-badge.aistudio {
background: #2a2b2e;
color: #f1f1f3;
background: #f0f2f5;
color: #2f343c;
}
[data-theme="dark"] .file-type-badge.aistudio {
background: #2a2b2e;
color: #d8dbe1;
background: #373c42;
color: #cfd3db;
}
.file-type-badge.claude {
@@ -1816,6 +1928,16 @@ input:checked+.slider:before {
color: #ffb74d;
}
.file-type-badge.antigravity {
background: #e0f7fa;
color: #006064;
}
[data-theme="dark"] .file-type-badge.antigravity {
background: #004d40;
color: #80deea;
}
.file-type-badge.iflow {
background: #f3e5f5;
color: #7b1fa2;
@@ -1837,13 +1959,13 @@ input:checked+.slider:before {
}
/* 未知类型通用样式 */
.file-type-badge:not(.qwen):not(.gemini):not(.gemini-cli):not(.aistudio):not(.claude):not(.codex):not(.iflow):not(.empty) {
.file-type-badge:not(.qwen):not(.gemini):not(.gemini-cli):not(.aistudio):not(.claude):not(.codex):not(.antigravity):not(.iflow):not(.empty) {
background: #f0f0f0;
color: #666666;
border: 1px dashed #999999;
}
[data-theme="dark"] .file-type-badge:not(.qwen):not(.gemini):not(.gemini-cli):not(.aistudio):not(.claude):not(.codex):not(.iflow):not(.empty) {
[data-theme="dark"] .file-type-badge:not(.qwen):not(.gemini):not(.gemini-cli):not(.aistudio):not(.claude):not(.codex):not(.antigravity):not(.iflow):not(.empty) {
background: #3a3a3a;
color: #aaaaaa;
border: 1px dashed #666666;
@@ -2251,6 +2373,148 @@ input:checked+.slider:before {
overflow: hidden;
}
.model-actions-inline {
display: flex;
gap: 10px;
flex-wrap: wrap;
margin-top: 10px;
}
.model-discovery-overlay {
position: fixed;
inset: 0;
background: rgba(0, 0, 0, 0.4);
display: none;
align-items: center;
justify-content: center;
z-index: 1100;
padding: 18px;
}
.model-discovery-overlay.active {
display: flex;
}
.model-discovery-card {
background: var(--bg-secondary);
color: var(--text-primary);
width: 95%;
max-width: 760px;
max-height: 90vh;
border-radius: 14px;
box-shadow: var(--shadow-modal);
padding: 18px;
display: flex;
flex-direction: column;
gap: 14px;
overflow: hidden;
}
.model-discovery-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.model-discovery-header h3 {
margin: 0 0 6px 0;
}
.model-discovery-status {
min-height: 22px;
font-size: 0.95rem;
color: var(--text-secondary);
}
.model-discovery-status.error {
color: #dc2626;
}
.model-discovery-status.warning {
color: #d97706;
}
.model-discovery-list {
background: var(--bg-primary);
border: 1px solid var(--border-color);
border-radius: 10px;
padding: 8px;
overflow-y: auto;
max-height: 46vh;
}
.model-discovery-row {
display: flex;
gap: 12px;
padding: 10px;
border-radius: 8px;
cursor: pointer;
transition: background 0.15s ease;
}
.model-discovery-row:hover {
background: rgba(59, 130, 246, 0.08);
}
.model-discovery-checkbox {
margin-top: 4px;
}
.model-discovery-meta {
display: flex;
flex-direction: column;
gap: 4px;
}
.model-discovery-name {
font-weight: 700;
color: var(--text-primary);
}
.model-discovery-alias {
margin-left: 6px;
padding: 2px 8px;
border-radius: 999px;
background: #eef2ff;
color: #4338ca;
font-size: 0.85rem;
font-weight: 600;
}
.model-discovery-desc {
color: var(--text-secondary);
font-size: 0.9rem;
}
.model-discovery-empty {
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
padding: 18px 12px;
color: var(--text-secondary);
}
[data-theme="dark"] .model-discovery-card {
background: var(--bg-secondary);
box-shadow: 0 12px 30px rgba(0, 0, 0, 0.35);
}
[data-theme="dark"] .model-discovery-list {
background: var(--bg-secondary);
border-color: var(--border-color);
}
[data-theme="dark"] .model-discovery-row:hover {
background: rgba(96, 165, 250, 0.18);
}
[data-theme="dark"] .model-discovery-alias {
background: #312e81;
color: #c7d2fe;
}
@keyframes modalSlideIn {
from {
opacity: 0;