feat: 实现API请求重试并改进UI/UX

主要变更:

1.  **API 请求重试机制:**
    *   在配置 (`.env.example`, `config.py`, `constants.py`) 中添加 `MAX_RETRIES` 设置,用于控制 API 请求失败后的最大重试次数 (默认为 3)。
    *   更新 `RetryHandler` (`retry_handler.py`) 以使用此配置。
    *   将 `RetryHandler` 应用于 Gemini 和 OpenAI 的内容生成路由 (`gemini_routes.py`, `openai_routes.py`),使其能够根据配置进行重试。
    *   在配置编辑器页面 (`config_editor.html`) 添加 `MAX_RETRIES` 的输入字段。

2.  **密钥状态页面 (Keys Status) UI/UX 改进:**
    *   默认隐藏 API 密钥的完整内容,仅显示部分字符 (`keys_status.html`),提高安全性。
    *   添加了切换按钮和相应的 JavaScript (`keys_status.js`) 及 CSS (`keys_status.css`),允许用户点击查看或隐藏完整的密钥。
    *   更新了“复制密钥”功能 (`keys_status.js`),确保复制的是完整的密钥而非掩码后的部分。

3.  **错误日志页面 (Error Logs) 重构与改进:**
    *   重构了 HTML 结构 (`error_logs.html`),使用更一致和语义化的 class(如 `config-section`, `controls-container`, `styled-table`, `status-indicator`),并移除了 Bootstrap 依赖。
    *   更新了 CSS (`error_logs.css`) 以匹配新的 HTML 结构,改进了页面布局和视觉样式。
    *   改进了 JavaScript (`error_logs.js`),优化了加载、无数据、错误状态的显示逻辑,改进了分页功能,并添加了通用的通知显示函数 (`showNotification`)。
    *   在错误日志表格和详情弹窗中添加了“错误类型”列/字段。

4.  **其他:**
    *   对聊天服务 (`gemini_chat_service.py`, `openai_chat_service.py`) 和密钥管理器 (`key_manager.py`) 进行了相关更新
This commit is contained in:
snaily
2025-04-10 18:32:21 +08:00
parent d94d24f96c
commit f05d67939f
16 changed files with 791 additions and 534 deletions
+315 -176
View File
@@ -1,258 +1,397 @@
// 错误日志页面JavaScript
// 错误日志页面JavaScript (Updated for new structure, no Bootstrap)
// 页面滚动功能
function scrollToTop() {
window.scrollTo({
top: 0,
behavior: 'smooth'
});
window.scrollTo({ top: 0, behavior: 'smooth' });
}
function scrollToBottom() {
window.scrollTo({
top: document.body.scrollHeight,
behavior: 'smooth'
});
window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
}
// 刷新页面功能
function refreshPage(button) {
if (button) {
button.classList.add('rotating');
// Use 'loading' class consistent with config_editor.css animation
button.classList.add('loading');
// Disable button while refreshing
button.disabled = true;
}
setTimeout(() => {
window.location.reload();
}, 500);
// Fetch new data instead of full reload for a smoother experience
loadErrorLogs().finally(() => {
if (button) {
// Remove loading class and re-enable button after fetch completes
button.classList.remove('loading');
button.disabled = false;
}
});
// Optional: Keep reload as fallback or if preferred
// setTimeout(() => {
// window.location.reload();
// }, 500);
}
// 全局变量
let currentPage = 1;
let pageSize = 20;
let totalPages = 1;
let errorLogs = [];
// let totalPages = 1; // totalPages will be calculated dynamically based on API response if available, or based on fetched data length
let errorLogs = []; // Store fetched logs for details view
// DOM Elements Cache
let pageSizeSelector;
let refreshBtn;
let tableBody;
let paginationElement;
let loadingIndicator;
let noDataMessage;
let errorMessage;
let logDetailModal;
let modalCloseBtns; // Collection of close buttons for the modal
// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
// 初始化页面大小选择器
const pageSizeSelector = document.getElementById('pageSize');
pageSizeSelector.value = pageSize;
pageSizeSelector.addEventListener('change', function() {
pageSize = parseInt(this.value);
currentPage = 1; // 重置到第一页
loadErrorLogs();
});
// 初始化刷新按钮
document.getElementById('refreshBtn').addEventListener('click', function() {
loadErrorLogs();
});
// 加载错误日志数据
// Cache DOM elements
pageSizeSelector = document.getElementById('pageSize');
refreshBtn = document.getElementById('refreshBtn');
tableBody = document.getElementById('errorLogsTable');
paginationElement = document.getElementById('pagination');
loadingIndicator = document.getElementById('loadingIndicator');
noDataMessage = document.getElementById('noDataMessage');
errorMessage = document.getElementById('errorMessage');
logDetailModal = document.getElementById('logDetailModal');
// Get all elements that should close the modal
modalCloseBtns = document.querySelectorAll('#closeLogDetailModalBtn, #closeModalFooterBtn');
// Initialize page size selector
if (pageSizeSelector) {
pageSizeSelector.value = pageSize;
pageSizeSelector.addEventListener('change', function() {
pageSize = parseInt(this.value);
currentPage = 1; // Reset to first page
loadErrorLogs();
});
}
// Initialize refresh button (using the one inside the controls container)
if (refreshBtn) {
refreshBtn.addEventListener('click', function() {
// Add loading state to the button itself
this.classList.add('loading');
this.disabled = true;
loadErrorLogs().finally(() => {
this.classList.remove('loading');
this.disabled = false;
});
});
}
// Initialize modal close buttons
if (logDetailModal && modalCloseBtns) {
modalCloseBtns.forEach(btn => {
btn.addEventListener('click', closeLogDetailModal);
});
// Optional: Close modal if clicking outside the content
logDetailModal.addEventListener('click', function(event) {
if (event.target === logDetailModal) {
closeLogDetailModal();
}
});
}
// Initial load of error logs
loadErrorLogs();
});
// 加载错误日志数据
function loadErrorLogs() {
async function loadErrorLogs() {
showLoading(true);
showError(false);
showNoData(false);
const offset = (currentPage - 1) * pageSize;
fetch(`/api/logs/errors?limit=${pageSize}&offset=${offset}`)
.then(response => {
if (!response.ok) {
throw new Error('网络响应异常');
try {
const response = await fetch(`/api/logs/errors?limit=${pageSize}&offset=${offset}`);
if (!response.ok) {
// Try to get error message from response body
let errorData;
try {
errorData = await response.json();
} catch (e) {
// Ignore if response is not JSON
}
return response.json();
})
.then(data => {
throw new Error(errorData?.detail || `网络响应异常: ${response.statusText}`);
}
const data = await response.json();
// Assuming the API returns an object like { logs: [], total: count }
// If it only returns an array, we can't get the total count accurately for pagination
if (Array.isArray(data)) {
errorLogs = data;
renderErrorLogs();
showLoading(false);
if (errorLogs.length === 0) {
showNoData(true);
}
})
.catch(error => {
console.error('获取错误日志失败:', error);
showLoading(false);
showError(true);
});
renderErrorLogs(errorLogs); // Pass data directly
updatePagination(errorLogs.length, -1); // Indicate unknown total
} else if (data && Array.isArray(data.logs)) {
errorLogs = data.logs;
renderErrorLogs(errorLogs); // Pass logs array
updatePagination(errorLogs.length, data.total || -1); // Pass total count if available
} else {
throw new Error('无法识别的API响应格式');
}
showLoading(false);
if (errorLogs.length === 0) {
showNoData(true);
}
} catch (error) {
console.error('获取错误日志失败:', error);
showLoading(false);
showError(true, error.message); // Show specific error message
}
}
// 渲染错误日志表格
function renderErrorLogs() {
const tableBody = document.getElementById('errorLogsTable');
tableBody.innerHTML = '';
errorLogs.forEach(log => {
function renderErrorLogs(logs) {
if (!tableBody) return;
tableBody.innerHTML = ''; // Clear previous entries
if (!logs || logs.length === 0) {
// Handled by showNoData
return;
}
logs.forEach(log => {
const row = document.createElement('tr');
// 格式化日期
const requestTime = new Date(log.request_time);
const formattedTime = requestTime.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
// 截断错误日志内容
// Format date
let formattedTime = 'N/A';
try {
const requestTime = new Date(log.request_time);
if (!isNaN(requestTime)) {
formattedTime = requestTime.toLocaleString('zh-CN', {
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false
});
}
} catch (e) { console.error("Error formatting date:", e); }
// Truncate error log content for display
const errorLogContent = log.error_log ? log.error_log.substring(0, 100) + (log.error_log.length > 100 ? '...' : '') : '无';
row.innerHTML = `
<td>${log.id}</td>
<td>${log.gemini_key || '无'}</td>
<td class="error-log-content">${errorLogContent}</td>
<td>${log.error_type || '未知'}</td>
<td class="error-log-content" title="${log.error_log || ''}">${errorLogContent}</td>
<td>${log.model_name || '未知'}</td>
<td>${formattedTime}</td>
<td>
<button class="btn btn-sm btn-primary btn-view-details" data-log-id="${log.id}">
<button class="btn-view-details" data-log-id="${log.id}">
查看详情
</button>
</td>
`;
tableBody.appendChild(row);
});
// 添加详情按钮事件监听
// Add event listeners to new 'View Details' buttons
document.querySelectorAll('.btn-view-details').forEach(button => {
button.addEventListener('click', function() {
const logId = parseInt(this.getAttribute('data-log-id'));
showLogDetails(logId);
});
});
// 更新分页
updatePagination();
}
// 显示错误日志详情
// 显示错误日志详情 (Custom Modal Logic)
function showLogDetails(logId) {
const log = errorLogs.find(log => log.id === logId);
if (!log) return;
// 格式化日期
const requestTime = new Date(log.request_time);
const formattedTime = requestTime.toLocaleString('zh-CN', {
year: 'numeric',
month: '2-digit',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
});
// 格式化请求消息
let formattedRequestMsg = '';
const log = errorLogs.find(l => l.id === logId);
if (!log || !logDetailModal) return;
// Format date
let formattedTime = 'N/A';
try {
const requestTime = new Date(log.request_time);
if (!isNaN(requestTime)) {
formattedTime = requestTime.toLocaleString('zh-CN', {
year: 'numeric', month: '2-digit', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false
});
}
} catch (e) { console.error("Error formatting date:", e); }
// Format request message (handle potential JSON)
let formattedRequestMsg = '无';
if (log.request_msg) {
try {
if (typeof log.request_msg === 'string') {
formattedRequestMsg = log.request_msg;
} else {
formattedRequestMsg = JSON.stringify(log.request_msg, null, 2);
// Check if it's already an object/array
if (typeof log.request_msg === 'object' && log.request_msg !== null) {
formattedRequestMsg = JSON.stringify(log.request_msg, null, 2);
}
// Check if it's a JSON string
else if (typeof log.request_msg === 'string' && log.request_msg.trim().startsWith('{') || log.request_msg.trim().startsWith('[')) {
formattedRequestMsg = JSON.stringify(JSON.parse(log.request_msg), null, 2);
}
else {
formattedRequestMsg = String(log.request_msg);
}
} catch (e) {
formattedRequestMsg = String(log.request_msg);
formattedRequestMsg = String(log.request_msg); // Fallback to string
console.warn("Could not parse request_msg as JSON:", e);
}
} else {
formattedRequestMsg = '无';
}
// 填充模态框内容
// Populate modal content
document.getElementById('modalGeminiKey').textContent = log.gemini_key || '无';
document.getElementById('modalErrorType').textContent = log.error_type || '未知';
document.getElementById('modalErrorLog').textContent = log.error_log || '无';
document.getElementById('modalRequestMsg').textContent = formattedRequestMsg;
// Add model name display logic here - assuming an element with id 'modalModelName' exists
document.getElementById('modalModelName').textContent = log.model_name || '未知';
document.getElementById('modalRequestTime').textContent = formattedTime;
// 显示模态框
const modal = new bootstrap.Modal(document.getElementById('logDetailModal'));
modal.show();
// Show the modal
logDetailModal.classList.add('show');
// Optional: Prevent body scrolling when modal is open
document.body.style.overflow = 'hidden';
}
// Close Log Detail Modal
function closeLogDetailModal() {
if (logDetailModal) {
logDetailModal.classList.remove('show');
// Optional: Restore body scrolling
document.body.style.overflow = '';
}
}
// 更新分页控件
function updatePagination() {
const paginationElement = document.getElementById('pagination');
paginationElement.innerHTML = '';
// 计算总页数
const totalCount = errorLogs.length;
totalPages = Math.max(1, Math.ceil(totalCount / pageSize));
// 上一页按钮
const prevItem = document.createElement('li');
prevItem.className = `page-item ${currentPage === 1 ? 'disabled' : ''}`;
prevItem.innerHTML = `<a class="page-link" href="#" aria-label="上一页"><span aria-hidden="true">&laquo;</span></a>`;
prevItem.addEventListener('click', function(e) {
e.preventDefault();
if (currentPage > 1) {
currentPage--;
loadErrorLogs();
function updatePagination(currentItemCount, totalItems) {
if (!paginationElement) return;
paginationElement.innerHTML = ''; // Clear existing pagination
// Calculate total pages only if totalItems is known and valid
let totalPages = 1;
if (totalItems >= 0) {
totalPages = Math.max(1, Math.ceil(totalItems / pageSize));
} else if (currentItemCount < pageSize && currentPage === 1) {
// If less items than page size fetched on page 1, assume it's the only page
totalPages = 1;
} else {
// If total is unknown and more items might exist, we can't build full pagination
// We can show Prev/Next based on current page and if items were returned
console.warn("Total item count unknown, pagination will be limited.");
// Basic Prev/Next for unknown total
addPaginationLink(paginationElement, '&laquo;', currentPage > 1, () => { currentPage--; loadErrorLogs(); });
addPaginationLink(paginationElement, currentPage.toString(), true, null, true); // Current page number (non-clickable)
addPaginationLink(paginationElement, '&raquo;', currentItemCount === pageSize, () => { currentPage++; loadErrorLogs(); }); // Next enabled if full page was returned
return; // Exit here for limited pagination
}
const maxPagesToShow = 5; // Max number of page links to show
let startPage = Math.max(1, currentPage - Math.floor(maxPagesToShow / 2));
let endPage = Math.min(totalPages, startPage + maxPagesToShow - 1);
// Adjust startPage if endPage reaches the limit first
if (endPage === totalPages) {
startPage = Math.max(1, endPage - maxPagesToShow + 1);
}
// Previous Button
addPaginationLink(paginationElement, '&laquo;', currentPage > 1, () => { currentPage--; loadErrorLogs(); });
// First Page Button
if (startPage > 1) {
addPaginationLink(paginationElement, '1', true, () => { currentPage = 1; loadErrorLogs(); });
if (startPage > 2) {
addPaginationLink(paginationElement, '...', false); // Ellipsis
}
});
paginationElement.appendChild(prevItem);
// 页码按钮
for (let i = 1; i <= totalPages; i++) {
const pageItem = document.createElement('li');
pageItem.className = `page-item ${i === currentPage ? 'active' : ''}`;
pageItem.innerHTML = `<a class="page-link" href="#">${i}</a>`;
pageItem.addEventListener('click', function(e) {
}
// Page Number Buttons
for (let i = startPage; i <= endPage; i++) {
addPaginationLink(paginationElement, i.toString(), true, () => { currentPage = i; loadErrorLogs(); }, i === currentPage);
}
// Last Page Button
if (endPage < totalPages) {
if (endPage < totalPages - 1) {
addPaginationLink(paginationElement, '...', false); // Ellipsis
}
addPaginationLink(paginationElement, totalPages.toString(), true, () => { currentPage = totalPages; loadErrorLogs(); });
}
// Next Button
addPaginationLink(paginationElement, '&raquo;', currentPage < totalPages, () => { currentPage++; loadErrorLogs(); });
}
// Helper function to add pagination links
function addPaginationLink(parentElement, text, enabled, clickHandler, isActive = false) {
const pageItem = document.createElement('li');
pageItem.className = `page-item ${!enabled ? 'disabled' : ''} ${isActive ? 'active' : ''}`;
const pageLink = document.createElement('a');
pageLink.className = 'page-link';
pageLink.href = '#'; // Prevent page jump
pageLink.innerHTML = text;
if (enabled && clickHandler) {
pageLink.addEventListener('click', function(e) {
e.preventDefault();
currentPage = i;
loadErrorLogs();
clickHandler();
});
paginationElement.appendChild(pageItem);
} else if (!enabled) {
pageLink.addEventListener('click', e => e.preventDefault()); // Prevent click on disabled
}
// 下一页按钮
const nextItem = document.createElement('li');
nextItem.className = `page-item ${currentPage === totalPages ? 'disabled' : ''}`;
nextItem.innerHTML = `<a class="page-link" href="#" aria-label="下一页"><span aria-hidden="true">&raquo;</span></a>`;
nextItem.addEventListener('click', function(e) {
e.preventDefault();
if (currentPage < totalPages) {
currentPage++;
loadErrorLogs();
}
});
paginationElement.appendChild(nextItem);
pageItem.appendChild(pageLink);
parentElement.appendChild(pageItem);
}
// 显示/隐藏加载指示器
// 显示/隐藏状态指示器 (using 'active' class)
function showLoading(show) {
const loadingIndicator = document.getElementById('loadingIndicator');
if (show) {
loadingIndicator.classList.remove('d-none');
} else {
loadingIndicator.classList.add('d-none');
}
if (loadingIndicator) loadingIndicator.style.display = show ? 'block' : 'none';
}
// 显示/隐藏错误消息
function showError(show) {
const errorMessage = document.getElementById('errorMessage');
if (show) {
errorMessage.classList.remove('d-none');
} else {
errorMessage.classList.add('d-none');
}
}
// 显示/隐藏无数据消息
function showNoData(show) {
const noDataMessage = document.getElementById('noDataMessage');
if (show) {
noDataMessage.classList.remove('d-none');
} else {
noDataMessage.classList.add('d-none');
if (noDataMessage) noDataMessage.style.display = show ? 'block' : 'none';
}
function showError(show, message = '加载错误日志失败,请稍后重试。') {
if (errorMessage) {
errorMessage.style.display = show ? 'block' : 'none';
if (show) {
// Update the error message content
const p = errorMessage.querySelector('p');
if (p) p.textContent = message;
}
}
}
// Function to show temporary status notifications (like copy success)
function showNotification(message, type = 'success', duration = 3000) {
const notificationElement = document.getElementById('copyStatus'); // Or a more generic ID if needed
if (!notificationElement) return;
notificationElement.textContent = message;
notificationElement.className = `notification ${type} show`; // Add 'show' class
// Hide after duration
setTimeout(() => {
notificationElement.classList.remove('show');
}, duration);
}
// Example Usage (if copy functionality is added later):
// showNotification('密钥已复制!', 'success');
// showNotification('复制失败!', 'error');