Initial import of weiyuan frontend

This commit is contained in:
qiubaishen
2026-10-15 16:33:46 +08:00
commit d8f3aee261
774 changed files with 374914 additions and 0 deletions
@@ -0,0 +1,345 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { API, showError, showSuccess } from '../../helpers';
import { ITEMS_PER_PAGE } from '../../constants';
import { useTableCompactMode } from '../common/useTableCompactMode';
/**
* 管理员(超管)视角的全平台 Token 管理数据 hook
*/
export const useAdminTokensData = () => {
const { t } = useTranslation();
const [compactMode, setCompactMode] = useTableCompactMode('admin-tokens');
// 数据状态
const [tokens, setTokens] = useState([]);
const [loading, setLoading] = useState(true);
const [searching, setSearching] = useState(false);
const [activePage, setActivePage] = useState(1);
const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
const [tokenCount, setTokenCount] = useState(0);
const [groupOptions, setGroupOptions] = useState([]);
// 选中状态(用于批量操作)
const [selectedRowKeys, setSelectedRowKeys] = useState([]);
// 弹窗状态
const [showEdit, setShowEdit] = useState(false);
const [editingToken, setEditingToken] = useState(null);
const [showEnableDisable, setShowEnableDisable] = useState(false);
const [enableDisableAction, setEnableDisableAction] = useState('');
const [showDelete, setShowDelete] = useState(false);
const [showBatchAction, setShowBatchAction] = useState(false);
const [batchAction, setBatchAction] = useState('');
const [modalToken, setModalToken] = useState(null);
// 过滤表单
const formInitValues = {
keyword: '',
user_keyword: '',
user_id: '',
statuses: [],
group: '',
unlimited: '',
org_scope: 'all',
};
const [formApi, setFormApi] = useState(null);
// 用 ref 持有最新分页/过滤值,避免 useCallback 闭包陈旧
const pageSizeRef = useRef(pageSize);
const tokenCountRef = useRef(0);
useEffect(() => {
pageSizeRef.current = pageSize;
}, [pageSize]);
useEffect(() => {
tokenCountRef.current = tokenCount;
}, [tokenCount]);
const getFormValues = useCallback(() => {
const v = formApi ? formApi.getValues() : {};
return {
keyword: v.keyword || '',
user_keyword: v.user_keyword || '',
user_id: v.user_id || '',
statuses: Array.isArray(v.statuses) ? v.statuses : [],
group: v.group || '',
unlimited: v.unlimited === undefined ? '' : v.unlimited,
org_scope: v.org_scope || 'all',
};
}, [formApi]);
const buildQuery = (page, size, filters) => {
const params = new URLSearchParams();
params.set('p', page);
params.set('page_size', size);
if (filters.keyword) params.set('keyword', filters.keyword);
if (filters.user_keyword) params.set('user_keyword', filters.user_keyword);
if (filters.user_id) params.set('user_id', filters.user_id);
if (filters.statuses && filters.statuses.length > 0) {
params.set('statuses', filters.statuses.join(','));
}
if (filters.group) params.set('group', filters.group);
if (
filters.unlimited !== '' &&
filters.unlimited !== undefined &&
filters.unlimited !== null
) {
params.set('unlimited', filters.unlimited);
}
if (filters.org_scope && filters.org_scope !== 'all') {
params.set('org_scope', filters.org_scope);
}
return params.toString();
};
const hasAnyFilter = (filters) =>
!!(
filters.keyword ||
filters.user_keyword ||
filters.user_id ||
(filters.statuses && filters.statuses.length > 0) ||
filters.group ||
filters.unlimited !== '' ||
(filters.org_scope && filters.org_scope !== 'all')
);
// 注意:不能像 users hook 那样用 `list[i].key = list[i].id`,
// 因为 Token 的 key 字段本身有意义(脱敏后的秘钥),覆盖会破坏列表展示
// 改为在 Table 上用 rowKey='id'
const setListFormat = (list) => {
setTokens(list);
};
// 核心:唯一的列表加载函数(loadTokens 兼容 searchTokens 的所有调用方式)
const loadTokens = useCallback(
async (page = 1, size = pageSizeRef.current, filters = null) => {
const useFilters = filters || getFormValues();
const filtered = hasAnyFilter(useFilters);
if (filtered) {
setSearching(true);
} else {
setLoading(true);
}
try {
const qs = buildQuery(page, size, useFilters);
const res = await API.get(`/api/token/admin?${qs}`);
const { success, message, data } = res.data;
if (success) {
// 边界:删除最后一页的所有记录后,page 已超出有效范围
// 自动回退到上一页(如果 page > 1 且当前页无数据但 total > 0)
if (page > 1 && (data.items || []).length === 0 && data.total > 0) {
const lastPage = Math.max(1, Math.ceil(data.total / size));
if (lastPage !== page) {
// 递归回退到合法页码(最多回退一次)
return loadTokens(lastPage, size, useFilters);
}
}
setActivePage(data.page);
setTokenCount(data.total);
setListFormat(data.items || []);
} else {
showError(message);
}
} catch (e) {
console.error('[AdminTokens] loadTokens failed:', e);
showError(e.message || t('加载失败'));
} finally {
setLoading(false);
setSearching(false);
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
[getFormValues, t],
);
// searchTokens 保留作为对外语义清晰的别名(重置到第 1 页)
const searchTokens = useCallback(
(size = pageSizeRef.current) => loadTokens(1, size),
[loadTokens],
);
// 真正的 debounce 实现(300ms),用于 Filters onChange 联动
const debounceTimerRef = useRef(null);
const debouncedSearch = useCallback(() => {
if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);
debounceTimerRef.current = setTimeout(() => {
loadTokens(1, pageSizeRef.current);
}, 300);
}, [loadTokens]);
useEffect(() => {
return () => {
if (debounceTimerRef.current) clearTimeout(debounceTimerRef.current);
};
}, []);
const refresh = useCallback(
(page = activePage) => loadTokens(page, pageSizeRef.current),
[activePage, loadTokens],
);
// 单条管理:enable / disable / delete
const manageToken = async (id, action) => {
try {
const res = await API.post('/api/token/admin/manage', { id, action });
const { success, message } = res.data;
if (success) {
showSuccess(t('操作成功'));
// 删除时若当前页可能变空,refresh 会自动回退页码
await refresh();
} else {
showError(message);
}
} catch (e) {
console.error('[AdminTokens] manageToken failed:', e);
showError(e.message || t('操作失败'));
}
};
// 批量管理
const batchManageTokens = async (ids, action) => {
if (!ids || ids.length === 0) {
showError(t('请先选择秘钥'));
return;
}
try {
const res = await API.post('/api/token/admin/batch', { ids, action });
const { success, message, data } = res.data;
if (success) {
showSuccess(t('成功处理 {{count}} 条', { count: data }));
setSelectedRowKeys([]);
await refresh();
} else {
showError(message);
}
} catch (e) {
console.error('[AdminTokens] batchManageTokens failed:', e);
showError(e.message || t('操作失败'));
}
};
// 分组下拉
const fetchGroups = async () => {
try {
const res = await API.get('/api/group/');
if (res?.data?.data) {
setGroupOptions(res.data.data.map((g) => ({ label: g, value: g })));
}
} catch (e) {
console.error('[AdminTokens] fetchGroups failed:', e);
}
};
const handlePageChange = (page) => {
setActivePage(page);
loadTokens(page, pageSizeRef.current);
};
const handlePageSizeChange = (size) => {
localStorage.setItem('page-size', size + '');
setPageSize(size);
pageSizeRef.current = size;
setActivePage(1);
loadTokens(1, size);
};
const handleRow = (record) => {
if (record.DeletedAt !== null && record.DeletedAt !== undefined) {
return { style: { background: 'var(--semi-color-disabled-border)' } };
}
if (record.status !== 1) {
return { style: { background: 'var(--semi-color-fill-0)' } };
}
return {};
};
const closeEdit = () => {
setShowEdit(false);
setEditingToken(null);
};
// 初始化
useEffect(() => {
loadTokens(1, pageSize, formInitValues);
fetchGroups();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return {
// 数据
tokens,
loading,
searching,
activePage,
pageSize,
tokenCount,
groupOptions,
// 选择
selectedRowKeys,
setSelectedRowKeys,
// 弹窗
showEdit,
setShowEdit,
editingToken,
setEditingToken,
closeEdit,
showEnableDisable,
setShowEnableDisable,
enableDisableAction,
setEnableDisableAction,
showDelete,
setShowDelete,
showBatchAction,
setShowBatchAction,
batchAction,
setBatchAction,
modalToken,
setModalToken,
// 表单
formInitValues,
setFormApi,
// 操作
loadTokens,
searchTokens,
debouncedSearch,
refresh,
manageToken,
batchManageTokens,
handlePageChange,
handlePageSizeChange,
handleRow,
// UI
compactMode,
setCompactMode,
// 翻译
t,
};
};
export default useAdminTokensData;
+306
View File
@@ -0,0 +1,306 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useCallback, useEffect, useRef } from 'react';
import { API, showError } from '../../helpers';
/**
* 运营看板数据获取Hook
*
* 参数 active:是否激活。false 时不发起任何请求(用于 Tab 切换的懒加载)。
* 首次切换为 true 时自动加载一次;之后再切回保持现有数据,不重复拉。
*/
export const useAnalyticsData = (active = true) => {
const [loading, setLoading] = useState(false);
const [overview, setOverview] = useState(null);
const [userTrend, setUserTrend] = useState([]);
const [financeTrend, setFinanceTrend] = useState([]);
const [channelConsumption, setChannelConsumption] = useState([]);
const [userRanking, setUserRanking] = useState([]);
const [topupChannel, setTopupChannel] = useState([]);
const [dailyStats, setDailyStats] = useState([]);
const [userTopupRanking, setUserTopupRanking] = useState([]);
const [period, setPeriod] = useState('today'); // today, week, month, quarter, custom
const [dateRange, setDateRange] = useState([null, null]); // 自定义日期范围 [startDate, endDate]
// 将 DatePicker 选择的日期转换为 UTC+8 当天零点/末尾的 Unix 时间戳(秒)
// DatePicker 返回的 Date 对象,其本地日期分量即用户选的日期,直接当作 CST 日期处理
const toCST = useCallback((date, isEndOfDay = false) => {
const d = new Date(date);
// 取本地日期分量(即用户在日历上选择的日期)
const year = d.getFullYear();
const month = d.getMonth();
const day = d.getDate();
// 构造该日期在 CST (UTC+8) 零点的 UTC 时间戳
// CST 零点 = UTC 同日零点 - 8小时
const cstMidnightMs =
Date.UTC(year, month, day, 0, 0, 0, 0) - 8 * 3600 * 1000;
if (isEndOfDay) {
// 当天结束 → 次日零点 CST
return Math.floor((cstMidnightMs + 24 * 3600 * 1000) / 1000);
}
return Math.floor(cstMidnightMs / 1000);
}, []);
// 构建查询参数
const buildQueryParams = useCallback(
(currentPeriod, currentDateRange) => {
const params = new URLSearchParams();
const usePeriod = currentPeriod || period;
const useRange = currentDateRange || dateRange;
if (usePeriod === 'custom' && useRange[0] && useRange[1]) {
// 自定义日期范围:统一使用 UTC+8 时区的天边界
const startTime = toCST(useRange[0], false);
const endTime = toCST(useRange[1], true);
params.append('start_time', startTime);
params.append('end_time', endTime);
} else if (usePeriod !== 'custom') {
params.append('period', usePeriod);
}
return params.toString();
},
[period, dateRange, toCST],
);
// 获取概览数据。后端对概览结果做了 60s 缓存,force=true 时穿透(用户主动点刷新)
const fetchOverview = useCallback(async (force = false) => {
try {
const res = await API.get(
`/api/analytics/overview${force ? '?refresh=true' : ''}`,
);
if (res.data.success) {
setOverview(res.data.data);
} else {
showError(res.data.message);
}
} catch (error) {
console.error('获取概览数据失败:', error);
}
}, []);
// 获取用户趋势
const fetchUserTrend = useCallback(
async (currentPeriod, currentDateRange) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get(`/api/analytics/user-trend?${queryParams}`);
if (res.data.success) {
setUserTrend(res.data.data || []);
}
} catch (error) {
console.error('获取用户趋势失败:', error);
}
},
[buildQueryParams],
);
// 获取收支趋势
const fetchFinanceTrend = useCallback(
async (currentPeriod, currentDateRange) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get(
`/api/analytics/finance-trend?${queryParams}`,
);
if (res.data.success) {
setFinanceTrend(res.data.data || []);
}
} catch (error) {
console.error('获取收支趋势失败:', error);
}
},
[buildQueryParams],
);
// 获取渠道消耗排行
const fetchChannelConsumption = useCallback(
async (currentPeriod, currentDateRange) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const separator = queryParams ? '&' : '';
const res = await API.get(
`/api/analytics/channel-consumption?${queryParams}${separator}limit=30`,
);
if (res.data.success) {
setChannelConsumption(res.data.data || []);
}
} catch (error) {
console.error('获取渠道消耗排行失败:', error);
}
},
[buildQueryParams],
);
// 获取用户排行
const fetchUserRanking = useCallback(
async (currentPeriod, currentDateRange) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const separator = queryParams ? '&' : '';
const res = await API.get(
`/api/analytics/user-ranking?${queryParams}${separator}limit=100`,
);
if (res.data.success) {
setUserRanking(res.data.data || []);
}
} catch (error) {
console.error('获取用户排行失败:', error);
}
},
[buildQueryParams],
);
// 获取充值渠道分布
const fetchTopupChannel = useCallback(
async (currentPeriod, currentDateRange) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get(
`/api/analytics/topup-channel?${queryParams}`,
);
if (res.data.success) {
setTopupChannel(res.data.data || []);
}
} catch (error) {
console.error('获取充值渠道分布失败:', error);
}
},
[buildQueryParams],
);
// 获取每日统计
const fetchDailyStats = useCallback(
async (currentPeriod, currentDateRange) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get(`/api/analytics/daily-stats?${queryParams}`);
if (res.data.success) {
setDailyStats(res.data.data || []);
}
} catch (error) {
console.error('获取每日统计失败:', error);
}
},
[buildQueryParams],
);
// 获取用户充值排行
const fetchUserTopupRanking = useCallback(
async (currentPeriod, currentDateRange) => {
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const separator = queryParams ? '&' : '';
const res = await API.get(
`/api/analytics/user-topup-ranking?${queryParams}${separator}limit=50`,
);
if (res.data.success) {
setUserTopupRanking(res.data.data || []);
}
} catch (error) {
console.error('获取用户充值排行失败:', error);
}
},
[buildQueryParams],
);
// 刷新所有数据
const refreshAll = useCallback(
async (currentPeriod, currentDateRange, force = false) => {
setLoading(true);
try {
await Promise.all([
fetchOverview(force),
fetchUserTrend(currentPeriod, currentDateRange),
fetchFinanceTrend(currentPeriod, currentDateRange),
fetchChannelConsumption(currentPeriod, currentDateRange),
fetchUserRanking(currentPeriod, currentDateRange),
fetchTopupChannel(currentPeriod, currentDateRange),
fetchDailyStats(currentPeriod, currentDateRange),
fetchUserTopupRanking(currentPeriod, currentDateRange),
]);
} finally {
setLoading(false);
}
},
[
fetchOverview,
fetchUserTrend,
fetchFinanceTrend,
fetchChannelConsumption,
fetchUserRanking,
fetchTopupChannel,
fetchDailyStats,
fetchUserTopupRanking,
],
);
// 切换时间周期
const handlePeriodChange = useCallback(
(newPeriod) => {
setPeriod(newPeriod);
if (newPeriod !== 'custom') {
setDateRange([null, null]);
refreshAll(newPeriod, [null, null]);
}
},
[refreshAll],
);
// 更新自定义日期范围
const handleDateRangeChange = useCallback(
(newRange) => {
setDateRange(newRange);
if (newRange[0] && newRange[1]) {
setPeriod('custom');
refreshAll('custom', newRange);
}
},
[refreshAll],
);
// 懒加载:仅在 active 第一次为 true 时拉数据。
// 由调用方传入 activeTab === 'operations',避免在 audit / risk Tab 时白白发起 8 个 API。
const loadedRef = useRef(false);
useEffect(() => {
if (!active || loadedRef.current) return;
loadedRef.current = true;
refreshAll(period, dateRange);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active]);
return {
loading,
overview,
userTrend,
financeTrend,
channelConsumption,
userRanking,
topupChannel,
dailyStats,
userTopupRanking,
period,
dateRange,
setPeriod: handlePeriodChange,
setDateRange: handleDateRangeChange,
refreshAll,
};
};
export default useAnalyticsData;
@@ -0,0 +1,142 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useCallback, useEffect, useRef } from 'react';
import { API } from '../../helpers';
/**
* 企业经营决策报表数据 Hook(单接口 /api/analytics/org-consumption/report,服务端基于汇总表计算)
*
* 参数 active:是否激活。false 时不发起任何请求(用于 Tab 懒加载)。
* 首次切换为 true 时自动加载一次;之后切回保持现有数据,不重复拉。
*
* 自带 period / dateRange 状态,与运营看板(useAnalyticsData)相互独立。
*/
export const useOrgConsumptionData = (active = true) => {
const [loading, setLoading] = useState(false);
const [report, setReport] = useState(null);
const [error, setError] = useState(false);
const [period, setPeriodState] = useState('week');
const [dateRange, setDateRangeState] = useState([null, null]);
// 只采纳最后一次请求的结果,避免快速切换时间段时旧响应覆盖新数据
const requestSeq = useRef(0);
// 与 useAnalyticsData 保持一致:DatePicker 选的本地日期分量当作 CST 日期处理
const toCST = useCallback((date, isEndOfDay = false) => {
const d = new Date(date);
const cstMidnightMs =
Date.UTC(d.getFullYear(), d.getMonth(), d.getDate(), 0, 0, 0, 0) -
8 * 3600 * 1000;
if (isEndOfDay) {
return Math.floor((cstMidnightMs + 24 * 3600 * 1000) / 1000);
}
return Math.floor(cstMidnightMs / 1000);
}, []);
const buildQueryParams = useCallback(
(currentPeriod, currentDateRange) => {
const params = new URLSearchParams();
const usePeriod = currentPeriod || period;
const useRange = currentDateRange || dateRange;
if (usePeriod === 'custom' && useRange[0] && useRange[1]) {
params.append('start_time', toCST(useRange[0], false));
params.append('end_time', toCST(useRange[1], true));
} else if (usePeriod !== 'custom') {
params.append('period', usePeriod);
}
return params.toString();
},
[period, dateRange, toCST],
);
const refreshAll = useCallback(
async (currentPeriod, currentDateRange) => {
const seq = ++requestSeq.current;
setLoading(true);
try {
const queryParams = buildQueryParams(currentPeriod, currentDateRange);
const res = await API.get(
`/api/analytics/org-consumption/report?${queryParams}`,
{ skipErrorHandler: true },
);
if (seq !== requestSeq.current) return;
if (res.data?.success) {
setReport(res.data.data);
setError(false);
} else {
// 清掉旧时间段的数据,避免失败时把上一时段结果当成当前结果展示
setReport(null);
setError(true);
}
} catch (err) {
if (seq !== requestSeq.current) return;
console.error('获取企业经营报表失败:', err);
setReport(null);
setError(true);
} finally {
if (seq === requestSeq.current) setLoading(false);
}
},
[buildQueryParams],
);
const setPeriod = useCallback(
(newPeriod) => {
setPeriodState(newPeriod);
if (newPeriod !== 'custom') {
setDateRangeState([null, null]);
refreshAll(newPeriod, [null, null]);
}
},
[refreshAll],
);
const setDateRange = useCallback(
(newRange) => {
setDateRangeState(newRange);
if (newRange[0] && newRange[1]) {
setPeriodState('custom');
refreshAll('custom', newRange);
}
},
[refreshAll],
);
// 懒加载:仅在 active 首次为 true 时拉数据
const loadedRef = useRef(false);
useEffect(() => {
if (!active || loadedRef.current) return;
loadedRef.current = true;
refreshAll(period, dateRange);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active]);
return {
loading,
report,
error,
period,
dateRange,
setPeriod,
setDateRange,
refreshAll,
};
};
export default useOrgConsumptionData;
+228
View File
@@ -0,0 +1,228 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import React, { useState, useCallback, useEffect } from 'react';
import { API, showError, showSuccess } from '../../helpers';
/**
* 风控看板数据 Hook
*
* - 顶部筛选:windowMinutes / minRequests / maxAvgQuota / maxTotalQuota
* - 数据:高频低消耗用户列表 + 当前规则配置 + 自动封号历史
*
* 参数 active:是否激活。false 时不发起任何请求(用于 Tab 切换的懒加载)。
* 首次切换为 true 时自动加载所有数据。
*/
export const useRiskControlData = (active = true) => {
const [loading, setLoading] = useState(false);
const [items, setItems] = useState([]);
const [windowRange, setWindowRange] = useState({ start: 0, end: 0 });
// 默认筛选:24h、请求 ≥ 100、不限平均消耗(前端表格按平均升序)
const [filters, setFilters] = useState({
windowMinutes: 1440,
minRequests: 100,
maxAvgQuota: 0,
maxTotalQuota: 0,
limit: 100,
});
const [rules, setRules] = useState([]);
const [rulesLoading, setRulesLoading] = useState(false);
// 封号历史
const [banLogs, setBanLogs] = useState([]);
const [banLogTotal, setBanLogTotal] = useState(0);
const [banLogLoading, setBanLogLoading] = useState(false);
const [banLogStatus, setBanLogStatus] = useState(0); // 0=全部 1=已封号 2=已解封
const [banLogPage, setBanLogPage] = useState(1);
const fetchSuspects = useCallback(
async (override) => {
const f = { ...filters, ...(override || {}) };
const params = new URLSearchParams();
params.append('window_minutes', f.windowMinutes);
params.append('min_requests', f.minRequests);
if (f.maxAvgQuota > 0) params.append('max_avg_quota', f.maxAvgQuota);
if (f.maxTotalQuota > 0)
params.append('max_total_quota', f.maxTotalQuota);
params.append('limit', f.limit);
setLoading(true);
try {
const res = await API.get(
`/api/analytics/risk/high-freq-low-cost?${params.toString()}`,
);
if (res.data.success) {
const d = res.data.data || {};
setItems(d.items || []);
setWindowRange({
start: d.window_start || 0,
end: d.window_end || 0,
});
} else {
showError(res.data.message);
}
} catch (e) {
console.error('查询高频低消耗用户失败', e);
} finally {
setLoading(false);
}
},
[filters],
);
const fetchRules = useCallback(async () => {
setRulesLoading(true);
try {
const res = await API.get('/api/analytics/risk/rules');
if (res.data.success) {
setRules(res.data.data || []);
}
} catch (e) {
console.error('查询风控规则失败', e);
} finally {
setRulesLoading(false);
}
}, []);
const saveRule = useCallback(
async (rule) => {
try {
const res = await API.post('/api/analytics/risk/rules', rule);
if (res.data.success) {
showSuccess('保存成功');
// 阈值变化后,列表里"是否命中"的状态标签依赖新规则计算,需联动刷新
await Promise.all([fetchRules(), fetchSuspects()]);
return true;
}
showError(res.data.message || '保存失败');
return false;
} catch (e) {
showError(e?.message || '保存失败');
return false;
}
},
[fetchRules, fetchSuspects],
);
const triggerScanNow = useCallback(async () => {
try {
const res = await API.post('/api/analytics/risk/rules/run-now');
if (res.data.success) {
showSuccess('已触发后台扫描');
return true;
}
showError(res.data.message);
return false;
} catch (e) {
showError(e?.message || '触发失败');
return false;
}
}, []);
const fetchBanLogs = useCallback(
async (override) => {
const status =
override?.status !== undefined ? override.status : banLogStatus;
const page = override?.page || banLogPage;
const params = new URLSearchParams();
if (status > 0) params.append('status', status);
params.append('page', page);
params.append('page_size', 20);
setBanLogLoading(true);
try {
const res = await API.get(
`/api/analytics/risk/ban-logs?${params.toString()}`,
);
if (res.data.success) {
const d = res.data.data || {};
setBanLogs(d.items || []);
setBanLogTotal(d.total || 0);
if (override?.page) setBanLogPage(override.page);
}
} catch (e) {
console.error('查询封号日志失败', e);
} finally {
setBanLogLoading(false);
}
},
[banLogStatus, banLogPage],
);
const unbanUser = useCallback(
async ({ userId, banLogId, reason }) => {
try {
const res = await API.post('/api/analytics/risk/unban', {
user_id: userId,
ban_log_id: banLogId || 0,
reason: reason || '',
});
if (res.data.success) {
showSuccess('解封成功');
// 解封会改变两个数据集的状态,并发刷新
await Promise.all([fetchSuspects(), fetchBanLogs()]);
return true;
}
showError(res.data.message);
return false;
} catch (e) {
showError(e?.message || '解封失败');
return false;
}
},
[fetchSuspects, fetchBanLogs],
);
// 懒加载:仅在 active 第一次为 true 时拉数据。
// 由调用方传入 activeTab === 'risk',避免在运营 Tab 时白白发起 3 个 API。
const loadedRef = React.useRef(false);
useEffect(() => {
if (!active || loadedRef.current) return;
loadedRef.current = true;
fetchSuspects();
fetchRules();
fetchBanLogs();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [active]);
return {
loading,
items,
windowRange,
filters,
setFilters,
fetchSuspects,
rules,
rulesLoading,
fetchRules,
saveRule,
triggerScanNow,
unbanUser,
// 封号历史
banLogs,
banLogTotal,
banLogLoading,
banLogStatus,
setBanLogStatus,
banLogPage,
fetchBanLogs,
};
};
export default useRiskControlData;
File diff suppressed because it is too large Load Diff
+49
View File
@@ -0,0 +1,49 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffect, useState } from 'react';
import { fetchTokenKeys, getServerAddress } from '../../helpers/token';
import { showError } from '../../helpers';
export function useTokenKeys(id) {
const [keys, setKeys] = useState([]);
const [serverAddress, setServerAddress] = useState('');
const [isLoading, setIsLoading] = useState(true);
useEffect(() => {
const loadAllData = async () => {
const fetchedKeys = await fetchTokenKeys();
if (fetchedKeys.length === 0) {
showError('当前没有可用的启用令牌,请确认是否有令牌处于启用状态!');
setTimeout(() => {
window.location.href = '/console/token';
}, 1500); // 延迟 1.5 秒后跳转
}
setKeys(fetchedKeys);
setIsLoading(false);
const address = getServerAddress();
setServerAddress(address);
};
loadAllData();
}, []);
return { keys, serverAddress, isLoading };
}
+52
View File
@@ -0,0 +1,52 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect, useRef } from 'react';
/**
* 检测容器宽度的 Hook
* @returns {[ref, width]} 容器引用和当前宽度
*/
export const useContainerWidth = () => {
const [width, setWidth] = useState(0);
const ref = useRef(null);
useEffect(() => {
const element = ref.current;
if (!element) return;
const resizeObserver = new ResizeObserver((entries) => {
for (let entry of entries) {
const { width: newWidth } = entry.contentRect;
setWidth(newWidth);
}
});
resizeObserver.observe(element);
// 初始化宽度
setWidth(element.getBoundingClientRect().width);
return () => {
resizeObserver.disconnect();
};
}, []);
return [ref, width];
};
+90
View File
@@ -0,0 +1,90 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffect, useRef, useState } from 'react';
/**
* KPI 数字滚动(count-up)hook。rAF 实现,零依赖。
*
* 设计约束(见 docs/11-前端与体验中心/02-前端风格整体升级方案.md 冲击力护栏):
* - 尊重 prefers-reduced-motion:直接显示终值,不播动画;
* - 只在数值变化时播一次,不循环;
* - 非有限数值(NaN/Infinity)原样返回,不动画。
*
* @param {number} value 目标数值
* @param {object} [opts]
* @param {number} [opts.duration=800] 动画时长 ms
* @param {number} [opts.decimals=0] 保留小数位
* @returns {number} 当前帧应显示的数值(调用方自行格式化)
*/
const easeOutCubic = (t) => 1 - Math.pow(1 - t, 3);
const prefersReducedMotion = () =>
typeof window !== 'undefined' &&
window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches;
export function useCountUp(value, { duration = 800, decimals = 0 } = {}) {
const [display, setDisplay] = useState(() =>
Number.isFinite(value) ? 0 : value,
);
// 记录上一次的终值,数值更新时从旧值滚到新值而不是从 0 重来
const fromRef = useRef(0);
const rafRef = useRef(null);
useEffect(() => {
if (!Number.isFinite(value)) {
setDisplay(value);
return undefined;
}
if (prefersReducedMotion() || duration <= 0) {
fromRef.current = value;
setDisplay(value);
return undefined;
}
const from = fromRef.current;
const delta = value - from;
if (delta === 0) {
setDisplay(value);
return undefined;
}
let start = null;
const factor = Math.pow(10, decimals);
const tick = (ts) => {
if (start === null) start = ts;
const progress = Math.min((ts - start) / duration, 1);
const current = from + delta * easeOutCubic(progress);
setDisplay(Math.round(current * factor) / factor);
if (progress < 1) {
rafRef.current = requestAnimationFrame(tick);
} else {
fromRef.current = value;
}
};
rafRef.current = requestAnimationFrame(tick);
return () => {
if (rafRef.current) cancelAnimationFrame(rafRef.current);
fromRef.current = value;
};
}, [value, duration, decimals]);
return display;
}
export default useCountUp;
+236
View File
@@ -0,0 +1,236 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect, useContext, useCallback, useMemo } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { UserContext } from '../../context/User';
import { StatusContext } from '../../context/Status';
import { useSetTheme, useTheme, useActualTheme } from '../../context/Theme';
import {
getLogo,
getSystemName,
API,
clearUserData,
showSuccess,
} from '../../helpers';
import { rememberUserLanguage } from '../../i18n/bootstrap';
import { useIsMobile } from './useIsMobile';
import { useSidebarCollapsed } from './useSidebarCollapsed';
import { useMinimumLoadingTime } from './useMinimumLoadingTime';
import { useOrgMembership } from './useOrgMembership';
import {
normalizeHeaderNavModules,
normalizeOrgUserNavModules,
} from '../../constants/headerNavModules';
import {
hasEnabledOrgCenterModule,
normalizeSidebarModulesAdmin,
} from '../../constants/sidebarModules';
export const useHeaderBar = ({ onMobileMenuToggle, drawerOpen }) => {
const { t, i18n } = useTranslation();
const [userState, userDispatch] = useContext(UserContext);
const [statusState] = useContext(StatusContext);
const isMobile = useIsMobile();
const [collapsed, toggleCollapsed] = useSidebarCollapsed();
const [logoLoaded, setLogoLoaded] = useState(false);
const navigate = useNavigate();
const [currentLang, setCurrentLang] = useState(i18n.language);
const location = useLocation();
const loading = statusState?.status === undefined || userState?.authChecking;
const isLoading = useMinimumLoadingTime(loading, 200);
const systemName = getSystemName();
const logo = getLogo();
const currentDate = new Date();
const isNewYear = currentDate.getMonth() === 0 && currentDate.getDate() === 1;
const isSelfUseMode = statusState?.status?.self_use_mode_enabled || false;
const docsLink = statusState?.status?.docs_link || '';
const isDemoSiteMode = statusState?.status?.demo_site_enabled || false;
// 获取顶栏模块配置
const headerNavModulesConfig = statusState?.status?.HeaderNavModules;
// 企业员工(仅企业资源模式)专用顶栏配置:隐藏 C 端入口,只保留企业相关
const orgUserNavModulesConfig = statusState?.status?.HeaderNavModulesOrgUser;
const isOrgUser = userState?.user?.org_only_mode === true;
// 使用useMemo确保headerNavModules正确响应statusState变化
// 企业员工(org_only)硬性默认:以企业预设(隐藏 C 端入口)为基线,叠加管理员保存的覆盖配置。
// 即「开箱即生效」,无需管理员先配置;管理员可在运营设置里再放开个别项。
const headerNavModules = useMemo(() => {
if (isOrgUser) {
return normalizeOrgUserNavModules(orgUserNavModulesConfig);
}
return normalizeHeaderNavModules(headerNavModulesConfig);
}, [isOrgUser, headerNavModulesConfig, orgUserNavModulesConfig]);
const sidebarModulesAdmin = useMemo(
() =>
normalizeSidebarModulesAdmin(statusState?.status?.SidebarModulesAdmin),
[statusState?.status?.SidebarModulesAdmin],
);
// 企业中心一级入口:用户属于企业才展示,并跟随后台 orgCenter 模块开关
const orgCenterAvailable = useMemo(() => {
const section = sidebarModulesAdmin?.orgCenter;
return hasEnabledOrgCenterModule(section);
}, [sidebarModulesAdmin]);
// 仅当 orgCenter 功能可用时才拉取企业列表,避免无谓的接口请求
const { hasOrg, orgEntryPath } = useOrgMembership(
userState?.user?.id,
orgCenterAvailable,
);
const showOrgEntry = hasOrg && orgCenterAvailable;
// 获取模型广场权限配置
const pricingRequireAuth = useMemo(() => {
if (headerNavModules?.pricing) {
return typeof headerNavModules.pricing === 'object'
? headerNavModules.pricing.requireAuth
: false; // 默认不需要登录
}
return false; // 默认不需要登录
}, [headerNavModules]);
const isConsoleRoute = location.pathname.startsWith('/console');
const theme = useTheme();
const actualTheme = useActualTheme();
const setTheme = useSetTheme();
// Logo loading effect
useEffect(() => {
setLogoLoaded(false);
if (!logo) return;
const img = new Image();
img.src = logo;
img.onload = () => setLogoLoaded(true);
}, [logo]);
// Send theme to iframe
useEffect(() => {
try {
const iframe = document.querySelector('iframe');
const cw = iframe && iframe.contentWindow;
if (cw) {
cw.postMessage({ themeMode: actualTheme }, '*');
}
} catch (e) {
// Silently ignore cross-origin or access errors
}
}, [actualTheme]);
// Language change effect
useEffect(() => {
const handleLanguageChanged = (lng) => {
setCurrentLang(lng);
try {
const iframe = document.querySelector('iframe');
const cw = iframe && iframe.contentWindow;
if (cw) {
cw.postMessage({ lang: lng }, '*');
}
} catch (e) {
// Silently ignore cross-origin or access errors
}
};
i18n.on('languageChanged', handleLanguageChanged);
return () => {
i18n.off('languageChanged', handleLanguageChanged);
};
}, [i18n]);
// Actions
const logout = useCallback(async () => {
await API.get('/api/user/logout');
showSuccess(t('注销成功!'));
userDispatch({ type: 'logout' });
clearUserData();
navigate('/org/login');
}, [navigate, t, userDispatch]);
const handleLanguageChange = useCallback(
(lang) => {
// 记为显式选择:此后优先于 IP 国家判定(后台关闭顶栏切换时失效)
rememberUserLanguage(lang);
i18n.changeLanguage(lang);
},
[i18n],
);
const handleThemeToggle = useCallback(
(newTheme) => {
if (
!newTheme ||
(newTheme !== 'light' && newTheme !== 'dark' && newTheme !== 'auto')
) {
return;
}
setTheme(newTheme);
},
[setTheme],
);
const handleMobileMenuToggle = useCallback(() => {
if (isMobile) {
onMobileMenuToggle();
} else {
toggleCollapsed();
}
}, [isMobile, onMobileMenuToggle, toggleCollapsed]);
return {
// State
userState,
statusState,
isMobile,
collapsed,
logoLoaded,
currentLang,
location,
isLoading,
systemName,
logo,
isNewYear,
isSelfUseMode,
docsLink,
isDemoSiteMode,
isConsoleRoute,
theme,
drawerOpen,
headerNavModules,
sidebarModulesAdmin,
pricingRequireAuth,
showOrgEntry,
orgEntryPath,
isOrgUser,
// Actions
logout,
handleLanguageChange,
handleThemeToggle,
handleMobileMenuToggle,
navigate,
t,
};
};
+35
View File
@@ -0,0 +1,35 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
export const MOBILE_BREAKPOINT = 768;
import { useSyncExternalStore } from 'react';
export const useIsMobile = () => {
const query = `(max-width: ${MOBILE_BREAKPOINT - 1}px)`;
return useSyncExternalStore(
(callback) => {
const mql = window.matchMedia(query);
mql.addEventListener('change', callback);
return () => mql.removeEventListener('change', callback);
},
() => window.matchMedia(query).matches,
() => false,
);
};
+50
View File
@@ -0,0 +1,50 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect, useRef } from 'react';
/**
* 自定义 Hook:确保骨架屏至少显示指定的时间
* @param {boolean} loading - 实际的加载状态
* @param {number} minimumTime - 最小显示时间(毫秒),默认 1000ms
* @returns {boolean} showSkeleton - 是否显示骨架屏的状态
*/
export const useMinimumLoadingTime = (loading, minimumTime = 1000) => {
const [showSkeleton, setShowSkeleton] = useState(loading);
const loadingStartRef = useRef(Date.now());
useEffect(() => {
if (loading) {
loadingStartRef.current = Date.now();
setShowSkeleton(true);
} else {
const elapsed = Date.now() - loadingStartRef.current;
const remaining = Math.max(0, minimumTime - elapsed);
if (remaining === 0) {
setShowSkeleton(false);
} else {
const timer = setTimeout(() => setShowSkeleton(false), remaining);
return () => clearTimeout(timer);
}
}
}, [loading, minimumTime]);
return showSkeleton;
};
+201
View File
@@ -0,0 +1,201 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useMemo } from 'react';
import {
getConfigGroups,
isConfigEnabled,
isGroupAllowed,
} from '../../helpers/navigationVisibility';
import { getHeaderModuleRequireAuth } from '../../constants/headerNavModules';
import { useWeyAiWebEntry } from './useWeyAiWebEntry';
export const useNavigation = (
t,
docsLink,
headerNavModules,
userRole = 0,
userGroup = 'default',
orgEntry = {},
) => {
// 解构成基础类型,避免父组件每次渲染传入新对象字面量导致 useMemo 失效
const { showOrgEntry = false, orgEntryPath = '/org' } = orgEntry;
// WeyAi 网页端入口:按 /api/status 开关与 /api/client/v1/web/access 决定是否显示
const { visible: weyaiVisible, url: weyaiUrl } = useWeyAiWebEntry();
const mainNavLinks = useMemo(() => {
const isAdminUser = userRole >= 10;
// 默认配置,如果没有传入配置则显示所有模块
const defaultModules = {
home: { enabled: true, groups: [] },
console: { enabled: true, groups: [] },
experienceCenter: { enabled: true, requireAuth: false, groups: [] },
keyManagement: { enabled: true, requireAuth: false, groups: [] },
userCenter: { enabled: true, requireAuth: false, groups: [] },
pricing: { enabled: true, requireAuth: false, groups: [] },
docs: { enabled: true, requireAuth: false, groups: [] },
weyai: { enabled: true, groups: [] },
about: { enabled: true, groups: [] },
};
// 合并默认配置和传入配置,确保新增模块有默认值
const modules = headerNavModules
? { ...defaultModules, ...headerNavModules }
: defaultModules;
// 模块是否对当前用户可见:开关 + 「可见用户分组」。顶栏管理里每个模块都有
// 分组控件,过滤却一度只看开关,分组配了等于没配;右侧功能按钮
// (isHeaderActionButtonVisible)一直是看分组的,这里对齐
const isModuleVisible = (key) => {
const module = modules[key];
return (
isConfigEnabled(module) &&
isGroupAllowed(getConfigGroups(module), userGroup)
);
};
const isInternalDocsLink = (link) => {
if (!link) return false;
if (link === '/docs' || link === '/docs/') return true;
if (link.startsWith('/docs')) return true;
try {
const url = new URL(link, window.location.origin);
const currentOrigin = window.location.origin;
if (url.origin === currentOrigin && url.pathname.startsWith('/docs')) {
return true;
}
} catch (_e) {
return false;
}
return false;
};
const getDocsLinkConfig = () => {
const baseConfig = {
itemKey: 'docs',
requireAuth: getHeaderModuleRequireAuth(modules, 'docs'),
};
if (isInternalDocsLink(docsLink) || !docsLink) {
return {
...baseConfig,
text: t('文档'),
to: '/docs',
};
}
return {
...baseConfig,
text: t('文档'),
isExternal: true,
externalLink: docsLink,
};
};
const allLinks = [
{
text: t('秘钥管理'),
itemKey: 'keyManagement',
to: '/key-management',
requireAuth: getHeaderModuleRequireAuth(modules, 'keyManagement'),
},
{
text: t('体验中心'),
itemKey: 'experienceCenter',
to: '/experience-center',
requireAuth: getHeaderModuleRequireAuth(modules, 'experienceCenter'),
},
{
text: t('模型超市'),
itemKey: 'pricing',
to: '/market',
requireAuth: getHeaderModuleRequireAuth(modules, 'pricing'),
},
{
text: t('技能超市'),
itemKey: 'skillMarket',
to: '/skill-market',
requireAuth: getHeaderModuleRequireAuth(modules, 'skillMarket'),
},
getDocsLinkConfig(),
{
text: t('用户中心'),
itemKey: 'userCenter',
to: '/user-center',
requireAuth: getHeaderModuleRequireAuth(modules, 'userCenter'),
},
// WeyAi 网页端:外链到网关的 /sso/start(每次点击都重新走一遍免登录授权),
// 需要登录;管理员可在「顶栏管理」里关闭
...(weyaiVisible
? [
{
text: t('WeyAi'),
itemKey: 'weyai',
isExternal: true,
externalLink: weyaiUrl,
requireAuth: true,
},
]
: []),
// 企业中心:仅当用户属于某个企业时作为一级入口展示(不跟随 headerNavModules 配置,
// 由 showOrgEntry 统一控制可见性,故标记 alwaysShow 跳过模块开关过滤)
...(showOrgEntry
? [
{
text: t('企业中心'),
itemKey: 'orgCenter',
to: orgEntryPath || '/org',
activePrefix: '/org',
requireAuth: true,
alwaysShow: true,
},
]
: []),
{
text: t('控制台'),
itemKey: 'console',
to: '/console/analytics',
activePrefix: '/console',
adminOnly: true,
requireAuth: true,
},
];
return allLinks.filter((link) => {
if (link.adminOnly && !isAdminUser) {
return false;
}
if (link.alwaysShow) {
return true;
}
return isModuleVisible(link.itemKey);
});
}, [
t,
docsLink,
headerNavModules,
userRole,
userGroup,
showOrgEntry,
orgEntryPath,
weyaiVisible,
weyaiUrl,
]);
return {
mainNavLinks,
};
};
+94
View File
@@ -0,0 +1,94 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect } from 'react';
export const useNotifications = (statusState) => {
const [noticeVisible, setNoticeVisible] = useState(false);
const [unreadCount, setUnreadCount] = useState(0);
const announcements = statusState?.status?.announcements || [];
// Helper functions
const getAnnouncementKey = (a) =>
`${a?.publishDate || ''}-${(a?.content || '').slice(0, 30)}`;
const calculateUnreadCount = () => {
if (!announcements.length) return 0;
let readKeys = [];
try {
readKeys = JSON.parse(localStorage.getItem('notice_read_keys')) || [];
} catch (_) {
readKeys = [];
}
const readSet = new Set(readKeys);
return announcements.filter((a) => !readSet.has(getAnnouncementKey(a)))
.length;
};
const getUnreadKeys = () => {
if (!announcements.length) return [];
let readKeys = [];
try {
readKeys = JSON.parse(localStorage.getItem('notice_read_keys')) || [];
} catch (_) {
readKeys = [];
}
const readSet = new Set(readKeys);
return announcements
.filter((a) => !readSet.has(getAnnouncementKey(a)))
.map(getAnnouncementKey);
};
// Effects
useEffect(() => {
setUnreadCount(calculateUnreadCount());
}, [announcements]);
// Actions
const handleNoticeOpen = () => {
setNoticeVisible(true);
};
const handleNoticeClose = () => {
setNoticeVisible(false);
if (announcements.length) {
let readKeys = [];
try {
readKeys = JSON.parse(localStorage.getItem('notice_read_keys')) || [];
} catch (_) {
readKeys = [];
}
const mergedKeys = Array.from(
new Set([...readKeys, ...announcements.map(getAnnouncementKey)]),
);
localStorage.setItem('notice_read_keys', JSON.stringify(mergedKeys));
}
setUnreadCount(0);
};
return {
noticeVisible,
unreadCount,
announcements,
handleNoticeOpen,
handleNoticeClose,
getUnreadKeys,
};
};
+96
View File
@@ -0,0 +1,96 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect } from 'react';
import { API } from '../../helpers';
const ADMIN_ROLES = ['owner', 'admin', 'super_admin'];
/**
* 拉取当前用户所属企业,用于判断是否在顶部一级导航展示「企业中心」入口。
* 仅登录且 orgCenter 功能可用时拉取一次;否则返回 hasOrg=false 且不发请求。
*
* @param {number|undefined} userId 当前登录用户 id(未登录为 undefined)
* @param {boolean} enabled orgCenter 功能是否可用(关闭时跳过请求)
* @returns {{hasOrg: boolean, orgEntryPath: string, activeOrg: object|null,
* isOrgAdmin: boolean, loaded: boolean}}
* loaded 区分"确定不是管理员"与"还不知道":调用方若拿 isOrgAdmin 做重定向类
* 判定,必须等 loaded,否则会在企业列表回来之前就把人重定向走(不可逆)。
*/
export const useOrgMembership = (userId, enabled = true) => {
const [orgs, setOrgs] = useState([]);
// 记录"已完成加载的那组入参",而不是一个裸布尔。裸布尔在这里是不够的:
// App 首帧 user 还是 undefined(loadUser 异步 dispatch),enabled 为 false,
// effect 会立刻把它置 true;等 /api/user/self 回来那一帧 enabled 翻 true,
// 但已 commit 的布尔仍是 true,调用方当帧就按"已知"做了重定向判定——正是
// 本标志要防的那条路径。改成在渲染期比对 key,入参一变 loaded 立即为 false。
const [loadedKey, setLoadedKey] = useState(null);
const currentKey = `${userId || 0}:${enabled ? 1 : 0}`;
const loaded = loadedKey === currentKey;
useEffect(() => {
let cancelled = false;
if (!userId || !enabled) {
setOrgs([]);
// 不需要拉取时直接视为"已知",避免调用方永久等待一个不会发生的请求。
setLoadedKey(currentKey);
return undefined;
}
(async () => {
try {
const res = await API.get('/api/org/list');
if (!cancelled && res?.data?.success) {
setOrgs(res.data.data || []);
}
} catch {
// 静默失败:拿不到企业列表时不展示入口即可
} finally {
// 失败也置位:否则一次网络抖动会让依赖 loaded 的分支永久挂起。
if (!cancelled) setLoadedKey(currentKey);
}
})();
return () => {
cancelled = true;
};
}, [userId, enabled, currentKey]);
const hasOrg = orgs.length > 0;
// 选取当前企业:优先 localStorage 记录的,否则取第一个
let activeOrg = null;
if (hasOrg) {
const savedId = parseInt(localStorage.getItem('current_org_id') || '0', 10);
activeOrg = orgs.find((o) => o.id === savedId) || orgs[0];
}
const role = activeOrg?.role || 'member';
// 按角色决定落地页,保证入口层级最浅:管理员进数据看板,员工进工作台
const orgEntryPath = ADMIN_ROLES.includes(role)
? '/org/dashboard'
: '/org/workbench';
// activeOrg / isOrgAdmin 供平台级页面(如技能超市)按企业身份做渐进增强。
// 复用同一套"当前企业"选取规则,避免各页面各自实现后与顶栏入口指向不同的企业。
return {
hasOrg,
orgEntryPath,
activeOrg,
isOrgAdmin: ADMIN_ROLES.includes(role),
loaded,
};
};
+274
View File
@@ -0,0 +1,274 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { SecureVerificationService } from '../../services/secureVerification';
import { showError, showSuccess } from '../../helpers';
import { isVerificationRequiredError } from '../../helpers/secureApiCall';
/**
* 通用安全验证 Hook
* @param {Object} options - 配置选项
* @param {Function} options.onSuccess - 验证成功回调
* @param {Function} options.onError - 验证失败回调
* @param {string} options.successMessage - 成功提示消息
* @param {boolean} options.autoReset - 验证完成后是否自动重置状态,默认为 true
*/
export const useSecureVerification = ({
onSuccess,
onError,
successMessage,
autoReset = true,
} = {}) => {
const { t } = useTranslation();
// 验证方式可用性状态
const [verificationMethods, setVerificationMethods] = useState({
has2FA: false,
hasPasskey: false,
passkeySupported: false,
});
// 模态框状态
const [isModalVisible, setIsModalVisible] = useState(false);
// 当前验证状态
const [verificationState, setVerificationState] = useState({
method: null, // '2fa' | 'passkey'
loading: false,
code: '',
apiCall: null,
});
// 检查可用的验证方式
const checkVerificationMethods = useCallback(async () => {
const methods =
await SecureVerificationService.checkAvailableVerificationMethods();
setVerificationMethods(methods);
return methods;
}, []);
// 初始化时检查验证方式
useEffect(() => {
checkVerificationMethods();
}, [checkVerificationMethods]);
// 重置状态
const resetState = useCallback(() => {
setVerificationState({
method: null,
loading: false,
code: '',
apiCall: null,
});
setIsModalVisible(false);
}, []);
// 开始验证流程
const startVerification = useCallback(
async (apiCall, options = {}) => {
const { preferredMethod, title, description } = options;
// 检查验证方式
const methods = await checkVerificationMethods();
if (!methods.has2FA && !methods.hasPasskey) {
const errorMessage = t('您需要先启用两步验证或 Passkey 才能执行此操作');
showError(errorMessage);
onError?.(new Error(errorMessage));
return false;
}
// 设置默认验证方式
let defaultMethod = preferredMethod;
if (!defaultMethod) {
if (methods.hasPasskey && methods.passkeySupported) {
defaultMethod = 'passkey';
} else if (methods.has2FA) {
defaultMethod = '2fa';
}
}
setVerificationState((prev) => ({
...prev,
method: defaultMethod,
apiCall,
title,
description,
}));
setIsModalVisible(true);
return true;
},
[checkVerificationMethods, onError, t],
);
// 执行验证
const executeVerification = useCallback(
async (method, code = '') => {
if (!verificationState.apiCall) {
showError(t('验证配置错误'));
return;
}
setVerificationState((prev) => ({ ...prev, loading: true }));
try {
// 先调用验证 API,成功后后端会设置 session
await SecureVerificationService.verify(method, code);
// 验证成功,调用业务 API(此时中间件会通过)
const result = await verificationState.apiCall();
// 显示成功消息
if (successMessage) {
showSuccess(successMessage);
}
// 调用成功回调
onSuccess?.(result, method);
// 自动重置状态
if (autoReset) {
resetState();
}
return result;
} catch (error) {
showError(error.message || t('验证失败,请重试'));
onError?.(error);
throw error;
} finally {
setVerificationState((prev) => ({ ...prev, loading: false }));
}
},
[
verificationState.apiCall,
successMessage,
onSuccess,
onError,
autoReset,
resetState,
t,
],
);
// 设置验证码
const setVerificationCode = useCallback((code) => {
setVerificationState((prev) => ({ ...prev, code }));
}, []);
// 切换验证方式
const switchVerificationMethod = useCallback((method) => {
setVerificationState((prev) => ({ ...prev, method, code: '' }));
}, []);
// 取消验证
const cancelVerification = useCallback(() => {
resetState();
}, [resetState]);
// 检查是否可以使用某种验证方式
const canUseMethod = useCallback(
(method) => {
switch (method) {
case '2fa':
return verificationMethods.has2FA;
case 'passkey':
return (
verificationMethods.hasPasskey &&
verificationMethods.passkeySupported
);
default:
return false;
}
},
[verificationMethods],
);
// 获取推荐的验证方式
const getRecommendedMethod = useCallback(() => {
if (
verificationMethods.hasPasskey &&
verificationMethods.passkeySupported
) {
return 'passkey';
}
if (verificationMethods.has2FA) {
return '2fa';
}
return null;
}, [verificationMethods]);
/**
* 包装 API 调用,自动处理验证错误
* 当 API 返回需要验证的错误时,自动弹出验证模态框
* @param {Function} apiCall - API 调用函数
* @param {Object} options - 验证选项(同 startVerification)
* @returns {Promise<any>}
*/
const withVerification = useCallback(
async (apiCall, options = {}) => {
try {
// 直接尝试调用 API
return await apiCall();
} catch (error) {
// 检查是否是需要验证的错误
if (isVerificationRequiredError(error)) {
// 自动触发验证流程
await startVerification(apiCall, options);
// 不抛出错误,让验证模态框处理
return null;
}
// 其他错误继续抛出
throw error;
}
},
[startVerification],
);
return {
// 状态
isModalVisible,
verificationMethods,
verificationState,
// 方法
startVerification,
executeVerification,
cancelVerification,
resetState,
setVerificationCode,
switchVerificationMethod,
checkVerificationMethods,
// 辅助方法
canUseMethod,
getRecommendedMethod,
withVerification, // 新增:自动处理验证的包装函数
// 便捷属性
hasAnyVerificationMethod:
verificationMethods.has2FA || verificationMethods.hasPasskey,
isLoading: verificationState.loading,
currentMethod: verificationState.method,
code: verificationState.code,
};
};
+262
View File
@@ -0,0 +1,262 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect, useMemo, useContext, useRef } from 'react';
import { StatusContext } from '../../context/Status';
import { API } from '../../helpers';
import { isGroupAllowed } from '../../helpers/navigationVisibility';
import { getDefaultSidebarModulesAdmin } from '../../constants/sidebarModules';
const sidebarEventTarget = new EventTarget();
const SIDEBAR_REFRESH_EVENT = 'sidebar-refresh';
const SIDEBAR_META_KEYS = new Set(['enabled', 'groups', 'moduleGroups']);
// 默认配置从 constants/sidebarModules.js 单一事实源派生,仅补上分组过滤用的
// groups/moduleGroups 元字段。此前这里手工维护了一份副本,与 constants 漂移:
// admin 区缺 skill-platform key,导致「平台 Skill 中心」入口在未保存过
// SidebarModulesAdmin 的部署上凭空消失(finalConfig 只遍历此处存在的 key,
// isModuleVisible 对缺失 key 恒 false)。派生后两处不可能再漂移。
const defaultAdminConfig = Object.entries(
getDefaultSidebarModulesAdmin(),
).reduce((acc, [sectionKey, section]) => {
acc[sectionKey] = { groups: [], moduleGroups: {}, ...section };
return acc;
}, {});
const buildDefaultUserConfig = (adminConfig) => {
const defaultUserConfig = {};
Object.keys(adminConfig).forEach((sectionKey) => {
if (adminConfig[sectionKey]?.enabled) {
defaultUserConfig[sectionKey] = { enabled: true };
Object.keys(adminConfig[sectionKey]).forEach((moduleKey) => {
if (
!SIDEBAR_META_KEYS.has(moduleKey) &&
adminConfig[sectionKey][moduleKey]
) {
defaultUserConfig[sectionKey][moduleKey] = true;
}
});
}
});
return defaultUserConfig;
};
export const useSidebar = () => {
const [statusState] = useContext(StatusContext);
const [userConfig, setUserConfig] = useState(null);
const [userGroup, setUserGroup] = useState('default');
const [loading, setLoading] = useState(true);
const instanceIdRef = useRef(null);
const hasLoadedOnceRef = useRef(false);
if (!instanceIdRef.current) {
const randomPart = Math.random().toString(16).slice(2);
instanceIdRef.current = `sidebar-${Date.now()}-${randomPart}`;
}
const adminConfig = useMemo(() => {
if (statusState?.status?.SidebarModulesAdmin) {
try {
const savedConfig = JSON.parse(statusState.status.SidebarModulesAdmin);
const mergedConfig = {};
Object.keys(defaultAdminConfig).forEach((sectionKey) => {
mergedConfig[sectionKey] = {
...defaultAdminConfig[sectionKey],
...(savedConfig[sectionKey] || {}),
};
});
Object.keys(savedConfig).forEach((sectionKey) => {
if (!mergedConfig[sectionKey]) {
mergedConfig[sectionKey] = savedConfig[sectionKey];
}
});
return mergedConfig;
} catch (error) {
return defaultAdminConfig;
}
}
return defaultAdminConfig;
}, [statusState?.status?.SidebarModulesAdmin]);
const loadUserConfig = async ({ withLoading } = {}) => {
const shouldShowLoader =
typeof withLoading === 'boolean'
? withLoading
: !hasLoadedOnceRef.current;
try {
if (shouldShowLoader) {
setLoading(true);
}
const res = await API.get('/api/user/self');
if (res.data.success) {
setUserGroup(res.data.data?.group || 'default');
}
if (res.data.success && res.data.data.sidebar_modules) {
let config;
if (typeof res.data.data.sidebar_modules === 'string') {
config = JSON.parse(res.data.data.sidebar_modules);
} else {
config = res.data.data.sidebar_modules;
}
setUserConfig(config);
} else {
setUserConfig(buildDefaultUserConfig(adminConfig));
}
} catch (error) {
setUserConfig(buildDefaultUserConfig(adminConfig));
} finally {
if (shouldShowLoader) {
setLoading(false);
}
hasLoadedOnceRef.current = true;
}
};
const refreshUserConfig = async () => {
if (Object.keys(adminConfig).length > 0) {
await loadUserConfig({ withLoading: false });
}
sidebarEventTarget.dispatchEvent(
new CustomEvent(SIDEBAR_REFRESH_EVENT, {
detail: { sourceId: instanceIdRef.current, skipLoader: true },
}),
);
};
useEffect(() => {
if (Object.keys(adminConfig).length > 0) {
loadUserConfig();
}
}, [adminConfig]);
useEffect(() => {
const handleRefresh = (event) => {
if (event?.detail?.sourceId === instanceIdRef.current) {
return;
}
if (Object.keys(adminConfig).length > 0) {
loadUserConfig({
withLoading: event?.detail?.skipLoader ? false : undefined,
});
}
};
sidebarEventTarget.addEventListener(SIDEBAR_REFRESH_EVENT, handleRefresh);
return () => {
sidebarEventTarget.removeEventListener(
SIDEBAR_REFRESH_EVENT,
handleRefresh,
);
};
}, [adminConfig]);
const finalConfig = useMemo(() => {
const result = {};
if (!adminConfig || Object.keys(adminConfig).length === 0) {
return result;
}
if (!userConfig) {
return result;
}
Object.keys(adminConfig).forEach((sectionKey) => {
const adminSection = adminConfig[sectionKey];
const userSection = userConfig[sectionKey];
const sectionGroupAllowed = isGroupAllowed(
adminSection?.groups,
userGroup,
);
if (!adminSection?.enabled || !sectionGroupAllowed) {
result[sectionKey] = { enabled: false };
return;
}
const sectionEnabled = userSection ? userSection.enabled !== false : true;
result[sectionKey] = { enabled: sectionEnabled };
Object.keys(adminSection).forEach((moduleKey) => {
if (SIDEBAR_META_KEYS.has(moduleKey)) return;
const adminAllowed = adminSection[moduleKey] !== false;
const userAllowed = userSection
? userSection[moduleKey] !== false
: true;
const moduleGroupAllowed = isGroupAllowed(
adminSection.moduleGroups?.[moduleKey],
userGroup,
);
result[sectionKey][moduleKey] =
adminAllowed && userAllowed && moduleGroupAllowed && sectionEnabled;
});
});
return result;
}, [adminConfig, userConfig, userGroup]);
const isModuleVisible = (sectionKey, moduleKey = null) => {
if (moduleKey) {
return finalConfig[sectionKey]?.[moduleKey] === true;
}
return finalConfig[sectionKey]?.enabled === true;
};
const hasSectionVisibleModules = (sectionKey) => {
const section = finalConfig[sectionKey];
if (!section?.enabled) return false;
return Object.keys(section).some(
(key) => key !== 'enabled' && section[key] === true,
);
};
const getVisibleModules = (sectionKey) => {
const section = finalConfig[sectionKey];
if (!section?.enabled) return [];
return Object.keys(section).filter(
(key) => key !== 'enabled' && section[key] === true,
);
};
return {
loading,
adminConfig,
userConfig,
finalConfig,
isModuleVisible,
hasSectionVisibleModules,
getVisibleModules,
refreshUserConfig,
};
};
+95
View File
@@ -0,0 +1,95 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback, useSyncExternalStore } from 'react';
const KEY = 'default_collapse_sidebar';
/*
* 侧栏折叠态是「一份跨组件共享的状态」,不能用 useState——
* 本 hook 有 6 个调用方(PageLayout / SiderBar / useHeaderBar / ExperienceSidebar /
* OrgSidebar / UserCenterSidebar),useState 会让每个调用方各自持有一份副本,
* 只在挂载时读一次 localStorage,之后彼此不同步。
*
* 由此产生过一个真实故障:手机上打开控制台侧栏抽屉时,PageLayout 调
* setCollapsed(false) 想把抽屉展开,但只改到自己那份副本,SiderBar 那份仍是
* true,于是抽屉渲染成 60px 的纯图标窄条、看不到任何导航文字——表现为
* 「移动端看不到左侧 tab,只能停留在默认页面」。
*
* 改成模块级 store + useSyncExternalStore:一处写入,所有调用方同步重渲染。
*/
// 注意:这段在模块求值期执行,抛异常会直接中断 app-shell chunk(白屏,错误边界都够不着)。
// typeof window 只挡得住 SSR,挡不住「存储被拒绝」——Safari 全面禁用 Cookie、
// 三方/沙箱 iframe、部分企业策略下,光是访问 localStorage 就会抛 SecurityError。
// 与下方写入侧保持同样的 try/catch 保护。
const readPersisted = () => {
try {
return localStorage.getItem(KEY) === 'true';
} catch (e) {
return false;
}
};
let collapsedState = typeof window !== 'undefined' && readPersisted();
const listeners = new Set();
const emit = () => {
listeners.forEach((listener) => listener());
};
const subscribe = (listener) => {
listeners.add(listener);
return () => listeners.delete(listener);
};
const getSnapshot = () => collapsedState;
// SSR/首屏快照:与 useIsMobile 保持同一取值策略,返回稳定的默认值
const getServerSnapshot = () => false;
const setCollapsedState = (value) => {
const next = Boolean(value);
if (next === collapsedState) return;
collapsedState = next;
try {
localStorage.setItem(KEY, next.toString());
} catch (e) {
// 隐私模式下 localStorage 可能不可写,内存态仍然生效
}
emit();
};
export const useSidebarCollapsed = () => {
const collapsed = useSyncExternalStore(
subscribe,
getSnapshot,
getServerSnapshot,
);
const toggle = useCallback(() => {
setCollapsedState(!collapsedState);
}, []);
const set = useCallback((value) => {
setCollapsedState(value);
}, []);
return [collapsed, toggle, set];
};
+58
View File
@@ -0,0 +1,58 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect, useCallback } from 'react';
import { getTableCompactMode, setTableCompactMode } from '../../helpers';
import { TABLE_COMPACT_MODES_KEY } from '../../constants';
/**
* 自定义 Hook:管理表格紧凑/自适应模式
* 返回 [compactMode, setCompactMode]。
* 内部使用 localStorage 保存状态,并监听 storage 事件保持多标签页同步。
*/
export function useTableCompactMode(tableKey = 'global') {
const [compactMode, setCompactModeState] = useState(() =>
getTableCompactMode(tableKey),
);
const setCompactMode = useCallback(
(value) => {
setCompactModeState(value);
setTableCompactMode(value, tableKey);
},
[tableKey],
);
useEffect(() => {
const handleStorage = (e) => {
if (e.key === TABLE_COMPACT_MODES_KEY) {
try {
const modes = JSON.parse(e.newValue || '{}');
setCompactModeState(!!modes[tableKey]);
} catch {
// ignore parse error
}
}
};
window.addEventListener('storage', handleStorage);
return () => window.removeEventListener('storage', handleStorage);
}, [tableKey]);
return [compactMode, setCompactMode];
}
+119
View File
@@ -0,0 +1,119 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect } from 'react';
import { API } from '../../helpers';
/**
* 用户权限钩子 - 从后端获取用户权限,替代前端角色判断
* 确保权限控制的安全性,防止前端绕过
*/
export const useUserPermissions = () => {
const [permissions, setPermissions] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
// 加载用户权限(从用户信息接口获取)
const loadPermissions = async () => {
try {
setLoading(true);
setError(null);
const res = await API.get('/api/user/self');
if (res.data.success) {
const userPermissions = res.data.data.permissions;
setPermissions(userPermissions);
console.log('用户权限加载成功:', userPermissions);
} else {
setError(res.data.message || '获取权限失败');
console.error('获取权限失败:', res.data.message);
}
} catch (error) {
setError('网络错误,请重试');
console.error('加载用户权限异常:', error);
} finally {
setLoading(false);
}
};
useEffect(() => {
loadPermissions();
}, []);
// 检查是否有边栏设置权限
const hasSidebarSettingsPermission = () => {
return permissions?.sidebar_settings === true;
};
// 检查是否允许访问特定的边栏区域
const isSidebarSectionAllowed = (sectionKey) => {
if (!permissions?.sidebar_modules) return true;
const sectionPerms = permissions.sidebar_modules[sectionKey];
return sectionPerms !== false;
};
// 检查是否允许访问特定的边栏模块
const isSidebarModuleAllowed = (sectionKey, moduleKey) => {
if (!permissions?.sidebar_modules) return true;
const sectionPerms = permissions.sidebar_modules[sectionKey];
// 如果整个区域被禁用
if (sectionPerms === false) return false;
// 如果区域存在但模块被禁用
if (sectionPerms && sectionPerms[moduleKey] === false) return false;
return true;
};
// 获取允许的边栏区域列表
const getAllowedSidebarSections = () => {
if (!permissions?.sidebar_modules) return [];
return Object.keys(permissions.sidebar_modules).filter((sectionKey) =>
isSidebarSectionAllowed(sectionKey),
);
};
// 获取特定区域允许的模块列表
const getAllowedSidebarModules = (sectionKey) => {
if (!permissions?.sidebar_modules) return [];
const sectionPerms = permissions.sidebar_modules[sectionKey];
if (sectionPerms === false) return [];
if (!sectionPerms || typeof sectionPerms !== 'object') return [];
return Object.keys(sectionPerms).filter(
(moduleKey) =>
moduleKey !== 'enabled' && sectionPerms[moduleKey] === true,
);
};
return {
permissions,
loading,
error,
loadPermissions,
hasSidebarSettingsPermission,
isSidebarSectionAllowed,
isSidebarModuleAllowed,
getAllowedSidebarSections,
getAllowedSidebarModules,
};
};
export default useUserPermissions;
+169
View File
@@ -0,0 +1,169 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useContext, useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers/api';
import { normalizeLanguage } from '../../i18n/language';
import { StatusContext } from '../../context/Status';
import { UserContext } from '../../context/User';
import { toSafeHttpUrl } from '../../helpers/safeUrl';
// 同一用户的网页端开放结果缓存,避免每次顶栏重渲染都请求。
// 带 TTL:开放范围(分组/企业/黑名单)是管理员随时可改的,永不过期的缓存会
// 让"已被移出开放范围"的用户在整页刷新前一直看得到入口,点进去才被拒。
// 与后端 AccessCheckCacheTTL 取同一个 60 秒口径。
const ACCESS_CACHE_TTL = 60 * 1000;
const accessCache = new Map(); // userId -> { allowed, expires }
// 顶栏常驻,hook 的 effect 只在依赖变化时重跑:缓存过期或被清掉本身不会触发
// 任何实例重查,入口就一直停在页面加载时的判定上,直到整页刷新。这里用一个
// 模块级版本号把"该重查了"通知到每个实例:清缓存、每 60 秒一次、回到页面时各
// 推一版;缓存未过期的实例收到通知后不发请求
let accessVersion = 0;
const accessListeners = new Set();
function bumpAccessVersion() {
accessVersion += 1;
accessListeners.forEach((listener) => listener(accessVersion));
}
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'visible') bumpAccessVersion();
});
setInterval(() => {
if (document.visibilityState === 'visible' && accessListeners.size > 0) {
bumpAccessVersion();
}
}, ACCESS_CACHE_TTL);
}
// 管理员在系统设置里改了开放范围后调用,让顶栏入口立刻重新询问后端,而不是
// 等 60 秒缓存过期
export function invalidateWeyAiAccessCache() {
accessCache.clear();
bumpAccessVersion();
}
function cachedAllowed(userId) {
const cached = userId ? accessCache.get(userId) : undefined;
return !!cached && cached.expires > Date.now() && cached.allowed === true;
}
// 只接受 http(s) 绝对地址,其他协议一律当作未配置
function trimTrailingSlash(url) {
return toSafeHttpUrl(url).replace(/\/+$/, '');
}
/**
* 顶部导航「WeyAi」入口(方案 4.7):
* - /api/status 的 weyai_web_enabled 为真且配置了 weyai_web_url 才考虑显示;
* - 已登录时按 GET /api/client/v1/web/access 的 allowed 决定;
* - 未登录时照常显示,点击由导航按 requireAuth 引导去登录。
* 返回 { visible, url },url 为 `<weyai_web_url>/sso/start?lang=<当前界面语言>`。
*
* lang 是把本站当前的界面语言交给网关:网关的启动/提示页本来按浏览器语言显示,
* 两者不一致时(系统中文、在这里选了英文)跳过去就换了语言。网关支持
* zh / zh-TW / en / ja / ko / th(与 LANGUAGE_CATALOG 同码),其余忽略并回落到
* Accept-Language;它把这个值跟着 SSO state 带到登录完成才存,所以中途跳转、
* rel="noreferrer" 都不影响。
*/
export function useWeyAiWebEntry() {
const { i18n } = useTranslation();
const [statusState] = useContext(StatusContext);
const [userState] = useContext(UserContext);
const status = statusState?.status;
const enabled =
status?.weyai_web_enabled === true || status?.weyai_web_enabled === 'true';
const baseUrl = trimTrailingSlash(status?.weyai_web_url);
const userId = userState?.user?.id || 0;
// 初值必须取缓存里的布尔结果而不是缓存条目本身:条目对象永远为真,会让
// 被拒用户在每次顶栏重挂载时先闪一下 WeyAi 入口
const [allowed, setAllowed] = useState(() => cachedAllowed(userId));
const [version, setVersion] = useState(accessVersion);
useEffect(() => {
accessListeners.add(setVersion);
return () => {
accessListeners.delete(setVersion);
};
}, []);
useEffect(() => {
if (!enabled || !baseUrl || !userId) {
setAllowed(false);
return undefined;
}
const cached = accessCache.get(userId);
if (cached && cached.expires > Date.now()) {
setAllowed(cached.allowed);
return undefined;
}
let cancelled = false;
API.get('/api/client/v1/web/access', { skipErrorHandler: true })
.then((res) => {
const body = res?.data;
const data = body && 'data' in body ? body.data : body;
const ok = body?.success !== false && data?.allowed === true;
accessCache.set(userId, {
allowed: ok,
expires: Date.now() + ACCESS_CACHE_TTL,
});
if (!cancelled) setAllowed(ok);
})
.catch(() => {
// 接口不可用(例如后端尚未部署)时不显示入口,也不缓存;下一版通知
//(60 秒、回到页面、管理员改范围)再试
if (!cancelled) setAllowed(false);
});
return () => {
cancelled = true;
};
}, [enabled, baseUrl, userId, version]);
const visible = enabled && !!baseUrl && (!userId || allowed);
const lang = normalizeLanguage(i18n.language);
return {
visible,
url: baseUrl ? `${baseUrl}/sso/start?lang=${encodeURIComponent(lang)}` : '',
};
}
/**
* 桌面端下载入口(顶栏按钮 / 用户中心侧栏项共用一套判定):
* - 后台未开「桌面端下载页」→ 不显示;
* - 网页端未配置(开关/地址/密钥缺一)→ 桌面端没有独立的开放范围,登录即可用,只看下载开关;
* - 网页端已配置 → 沿用网页端开放范围(含黑名单):管理员没开放 WeyAi 的人不推送入口。
* 只对已登录用户为真;/weyai/download 本身是公开路由,未登录访客仍可直接访问。
*/
export function useWeyAiDownloadEntry() {
const [statusState] = useContext(StatusContext);
const [userState] = useContext(UserContext);
const status = statusState?.status;
const downloadEnabled =
status?.weyai_download_enabled === true ||
status?.weyai_download_enabled === 'true';
const webEnabled =
status?.weyai_web_enabled === true || status?.weyai_web_enabled === 'true';
const { visible: webVisible } = useWeyAiWebEntry();
const loggedIn = !!userState?.user?.id;
return {
visible: downloadEnabled && loggedIn && (!webEnabled || webVisible),
};
}
+906
View File
@@ -0,0 +1,906 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useCallback, useEffect } from 'react';
import { initVChartSemiTheme } from '@visactor/vchart-semi-theme';
import {
modelColorMap,
renderNumber,
renderQuota,
modelToColor,
getQuotaWithUnit,
} from '../../helpers';
import {
processRawData,
calculateTrendData,
aggregateDataByTimeAndModel,
generateChartTimePoints,
updateChartSpec,
updateMapValue,
initializeMaps,
} from '../../helpers/dashboard';
export const useDashboardCharts = (
dataExportDefaultTime,
setTrendData,
setConsumeQuota,
setTimes,
setConsumeTokens,
setPieData,
setLineData,
setModelColors,
t,
) => {
// ========== 图表规格状态 ==========
// 模型调用排行 - 水平柱状榜单(取代原 donut 饼图)
const [spec_pie, setSpecPie] = useState({
type: 'bar',
data: [
{
id: 'id0',
values: [],
},
],
xField: 'value',
yField: 'type',
seriesField: 'type',
direction: 'horizontal',
title: {
visible: true,
text: t('模型调用排行'),
subtext: `${t('总计')}:${renderNumber(0)}`,
textStyle: {
fontSize: 14,
fontWeight: 600,
},
subtextStyle: {
fontSize: 11,
fontWeight: 400,
fill: '#888',
},
},
bar: {
style: {
cornerRadius: [0, 8, 8, 0],
fillOpacity: 0.9,
},
state: {
hover: {
fillOpacity: 1,
shadowBlur: 12,
shadowColor: 'rgba(0, 0, 0, 0.18)',
shadowOffsetX: 2,
shadowOffsetY: 0,
},
selected: {
fillOpacity: 1,
},
},
},
label: {
visible: true,
position: 'right',
style: {
fontSize: 11,
fontWeight: 600,
fill: '#666',
},
formatMethod: (text, datum) => renderNumber(datum?.value || 0),
},
axes: [
{
orient: 'left',
label: {
style: {
fontSize: 11,
fontWeight: 500,
fill: '#888',
},
},
tick: { visible: false },
domainLine: { visible: false },
},
{
orient: 'bottom',
visible: false,
},
],
legends: { visible: false },
tooltip: {
mark: {
title: {
visible: true,
value: (datum) => String(datum['type'] || ''),
},
content: [
{
key: (datum) => String(datum['type'] || ''),
value: (datum) => renderNumber(datum['value'] || 0),
},
],
},
style: {
panel: {
shadow: {
blur: 12,
color: 'rgba(0, 0, 0, 0.12)',
},
},
},
},
color: [
'#6366f1', // 靛蓝
'#8b5cf6', // 紫色
'#ec4899', // 粉色
'#f43f5e', // 玫瑰色
'#f97316', // 橙色
'#eab308', // 黄色
'#22c55e', // 绿色
'#14b8a6', // 青色
'#06b6d4', // 天蓝
'#3b82f6', // 蓝色
],
animation: true,
animationAppear: {
bar: {
duration: 700,
easing: 'cubicOut',
oneByOne: 30,
},
},
});
// 消费时段走势 - 堆叠面积图(取代原堆叠柱图)
const [spec_line, setSpecLine] = useState({
type: 'area',
data: [
{
id: 'barData',
values: [],
},
],
xField: 'Time',
yField: 'Usage',
seriesField: 'Model',
stack: true,
legends: {
visible: true,
selectMode: 'single',
orient: 'right',
position: 'middle',
padding: { left: 16 },
item: {
shape: {
style: {
symbolType: 'circle',
size: 8,
},
},
label: {
style: {
fontSize: 11,
fontWeight: 500,
},
},
},
},
title: {
visible: true,
text: t('消费时段走势'),
subtext: `${t('总计')}:${renderQuota(0, 2)}`,
textStyle: {
fontSize: 14,
fontWeight: 600,
},
subtextStyle: {
fontSize: 11,
fontWeight: 400,
fill: '#888',
},
},
area: {
style: {
fillOpacity: 0.55,
curveType: 'monotone',
},
state: {
hover: {
fillOpacity: 0.85,
},
selected: {
fillOpacity: 0.95,
},
},
},
line: {
style: {
lineWidth: 2,
lineCap: 'round',
lineJoin: 'round',
curveType: 'monotone',
},
state: {
hover: {
lineWidth: 3,
},
},
},
// 平时隐藏数据点;保留 hover state 以便 VChart 在悬停时显示 symbol
point: {
visible: false,
},
axes: [
{
orient: 'bottom',
label: {
style: {
fontSize: 10,
fill: '#888',
},
},
tick: {
visible: false,
},
domainLine: {
visible: true,
style: {
stroke: '#e5e7eb',
lineWidth: 1,
},
},
grid: {
visible: false,
},
},
{
orient: 'left',
label: {
style: {
fontSize: 10,
fill: '#888',
},
},
tick: {
visible: false,
},
domainLine: {
visible: false,
},
grid: {
visible: true,
style: {
stroke: '#f0f0f0',
lineDash: [4, 4],
},
},
},
],
tooltip: {
mark: {
title: {
visible: true,
value: (datum) => String(datum['Model'] || ''),
style: {
fontWeight: 600,
},
},
content: [
{
key: (datum) => String(datum['Model'] || ''),
value: (datum) => renderQuota(datum['rawQuota'] || 0, 4),
},
],
},
dimension: {
content: [
{
key: (datum) => String(datum['Model'] || ''),
value: (datum) => datum['rawQuota'] || 0,
},
],
updateContent: (array) => {
array.sort((a, b) => b.value - a.value);
let sum = 0;
for (let i = 0; i < array.length; i++) {
// 注意:这里曾经有一条 `key == '其他' 就 continue` 的历史分支。
// dimension.content 的 value 取的是裸数字(rawQuota),格式化只发生在本循环里,
// 跳过就等于把该行渲染成未格式化的浮点数。移动端把长尾模型合并成「其他」系列后
// 这条分支会被真实命中(中文下 t('其他') 就是字面量 '其他'),故移除。
let value = parseFloat(array[i].value);
if (isNaN(value)) {
value = 0;
}
if (array[i].datum && array[i].datum.TimeSum) {
sum = array[i].datum.TimeSum;
}
array[i].value = renderQuota(value, 4);
}
array.unshift({
key: t('总计'),
value: renderQuota(sum, 4),
});
return array;
},
},
style: {
panel: {
shadow: {
blur: 12,
color: 'rgba(0, 0, 0, 0.12)',
},
},
},
},
// 使用更丰富的渐变调色板
color: [
'#6366f1', // 靛蓝
'#8b5cf6', // 紫色
'#ec4899', // 粉色
'#f43f5e', // 玫瑰色
'#f97316', // 橙色
'#eab308', // 黄色
'#22c55e', // 绿色
'#14b8a6', // 青色
'#06b6d4', // 天蓝
'#3b82f6', // 蓝色
'#a855f7', // 淡紫
'#d946ef', // 洋红
'#10b981', // 翠绿
'#84cc16', // 草绿
'#f59e0b', // 琥珀
'#ef4444', // 红色
],
// 动画配置
animation: true,
animationAppear: {
area: {
duration: 800,
easing: 'cubicOut',
},
line: {
duration: 800,
easing: 'cubicOut',
},
},
animationUpdate: {
area: {
duration: 400,
easing: 'linear',
},
line: {
duration: 400,
easing: 'linear',
},
},
});
// 模型消耗趋势折线图(已弃用,保留以兼容旧导出,UI 不再渲染)
const [spec_model_line, setSpecModelLine] = useState({
type: 'line',
data: [
{
id: 'lineData',
values: [],
},
],
xField: 'Time',
yField: 'Count',
seriesField: 'Model',
legends: {
visible: true,
selectMode: 'single',
orient: 'right',
position: 'middle',
padding: { left: 16 },
item: {
shape: {
style: {
symbolType: 'circle',
size: 10,
},
},
label: {
style: {
fontSize: 11,
fontWeight: 500,
},
},
},
},
title: {
visible: true,
text: t('模型消耗趋势'),
subtext: '',
textStyle: {
fontSize: 16,
fontWeight: 600,
},
subtextStyle: {
fontSize: 12,
fontWeight: 400,
fill: '#888',
},
},
line: {
style: {
lineWidth: 2.5,
lineCap: 'round',
lineJoin: 'round',
},
state: {
hover: {
lineWidth: 4,
},
},
},
point: {
visible: true,
style: {
size: 6,
fill: '#fff',
lineWidth: 2,
},
state: {
hover: {
size: 10,
lineWidth: 3,
},
},
},
axes: [
{
orient: 'bottom',
label: {
style: {
fontSize: 10,
fill: '#888',
},
},
tick: {
visible: false,
},
domainLine: {
visible: true,
style: {
stroke: '#e5e7eb',
lineWidth: 1,
},
},
grid: {
visible: false,
},
},
{
orient: 'left',
label: {
style: {
fontSize: 10,
fill: '#888',
},
},
tick: {
visible: false,
},
domainLine: {
visible: false,
},
grid: {
visible: true,
style: {
stroke: '#f0f0f0',
lineDash: [4, 4],
},
},
},
],
tooltip: {
mark: {
title: {
visible: true,
value: (datum) => String(datum['Model'] || ''),
},
content: [
{
key: (datum) => String(datum['Model'] || ''),
value: (datum) => renderNumber(datum['Count'] || 0),
},
],
},
style: {
panel: {
shadow: {
blur: 12,
color: 'rgba(0, 0, 0, 0.12)',
},
},
},
},
// 使用渐变色调色板
color: [
'#6366f1', // 靛蓝
'#8b5cf6', // 紫色
'#ec4899', // 粉色
'#f43f5e', // 玫瑰色
'#f97316', // 橙色
'#22c55e', // 绿色
'#06b6d4', // 天蓝
'#3b82f6', // 蓝色
],
// 动画配置
animation: true,
animationAppear: {
line: {
duration: 1000,
easing: 'cubicOut',
type: 'clipIn',
},
point: {
duration: 600,
easing: 'cubicOut',
delay: 400,
},
},
});
// 模型调用次数排行柱状图
const [spec_rank_bar, setSpecRankBar] = useState({
type: 'bar',
data: [
{
id: 'rankData',
values: [],
},
],
xField: 'Count',
yField: 'Model',
seriesField: 'Model',
direction: 'horizontal',
legends: {
visible: false,
},
title: {
visible: true,
text: t('模型调用次数排行'),
subtext: '',
textStyle: {
fontSize: 16,
fontWeight: 600,
},
subtextStyle: {
fontSize: 12,
fontWeight: 400,
fill: '#888',
},
},
bar: {
style: {
cornerRadius: [0, 6, 6, 0],
fillOpacity: 0.85,
},
state: {
hover: {
fillOpacity: 1,
stroke: 'rgba(255, 255, 255, 0.9)',
lineWidth: 2,
shadowBlur: 10,
shadowColor: 'rgba(0, 0, 0, 0.2)',
shadowOffsetX: 2,
shadowOffsetY: 2,
},
},
},
axes: [
{
orient: 'left',
type: 'band',
label: {
style: {
fontSize: 11,
fontWeight: 500,
fill: '#555',
},
},
tick: {
visible: false,
},
domainLine: {
visible: false,
},
grid: {
visible: false,
},
},
{
orient: 'bottom',
label: {
style: {
fontSize: 10,
fill: '#888',
},
},
tick: {
visible: false,
},
domainLine: {
visible: true,
style: {
stroke: '#e5e7eb',
lineWidth: 1,
},
},
grid: {
visible: true,
style: {
stroke: '#f5f5f5',
lineDash: [4, 4],
},
},
},
],
label: {
visible: true,
position: 'outside-right',
style: {
fontSize: 11,
fontWeight: 600,
fill: '#333',
},
formatter: (datum) => renderNumber(datum['Count'] || 0),
},
tooltip: {
mark: {
title: {
visible: true,
value: (datum) => String(datum['Model'] || ''),
},
content: [
{
key: (datum) => String(datum['Model'] || ''),
value: (datum) => renderNumber(datum['Count'] || 0),
},
],
},
style: {
panel: {
shadow: {
blur: 12,
color: 'rgba(0, 0, 0, 0.12)',
},
},
},
},
// 使用渐变色调色板
color: [
'#6366f1', // 靛蓝
'#8b5cf6', // 紫色
'#ec4899', // 粉色
'#f43f5e', // 玫瑰色
'#f97316', // 橙色
'#eab308', // 黄色
'#22c55e', // 绿色
'#14b8a6', // 青色
'#06b6d4', // 天蓝
'#3b82f6', // 蓝色
'#a855f7', // 淡紫
'#d946ef', // 洋红
],
// 动画配置
animation: true,
animationAppear: {
bar: {
duration: 600,
easing: 'cubicOut',
type: 'growWidthIn',
},
},
});
// ========== 数据处理函数 ==========
const generateModelColors = useCallback((uniqueModels, modelColors) => {
const newModelColors = {};
Array.from(uniqueModels).forEach((modelName) => {
if (!modelName) return; // 跳过 undefined/null
newModelColors[modelName] =
modelColorMap[modelName] ||
modelColors[modelName] ||
modelToColor(modelName);
});
return newModelColors;
}, []);
const updateChartData = useCallback(
(data) => {
const processedData = processRawData(
data,
dataExportDefaultTime,
initializeMaps,
updateMapValue,
);
const {
totalQuota,
totalTimes,
totalTokens,
uniqueModels,
timePoints,
timeQuotaMap,
timeTokensMap,
timeCountMap,
} = processedData;
const trendDataResult = calculateTrendData(
timePoints,
timeQuotaMap,
timeTokensMap,
timeCountMap,
dataExportDefaultTime,
);
setTrendData(trendDataResult);
const newModelColors = generateModelColors(uniqueModels, {});
setModelColors(newModelColors);
const aggregatedData = aggregateDataByTimeAndModel(
data,
dataExportDefaultTime,
);
const modelTotals = new Map();
for (let [_, value] of aggregatedData) {
updateMapValue(modelTotals, value.model, value.count);
}
const newPieData = Array.from(modelTotals)
.filter(([model]) => model) // 过滤掉 undefined/null
.map(([model, count]) => ({
type: String(model),
value: count,
}))
.sort((a, b) => b.value - a.value);
const chartTimePoints = generateChartTimePoints(
aggregatedData,
data,
dataExportDefaultTime,
);
let newLineData = [];
chartTimePoints.forEach((time) => {
let timeData = Array.from(uniqueModels)
.filter((model) => model) // 过滤掉 undefined/null
.map((model) => {
const key = `${time}-${model}`;
const aggregated = aggregatedData.get(key);
return {
Time: time,
Model: String(model),
rawQuota: aggregated?.quota || 0,
Usage: aggregated?.quota
? getQuotaWithUnit(aggregated.quota, 4)
: 0,
};
});
const timeSum = timeData.reduce((sum, item) => sum + item.rawQuota, 0);
timeData.sort((a, b) => b.rawQuota - a.rawQuota);
timeData = timeData.map((item) => ({ ...item, TimeSum: timeSum }));
newLineData.push(...timeData);
});
newLineData.sort((a, b) => a.Time.localeCompare(b.Time));
updateChartSpec(
setSpecPie,
newPieData,
`${t('总计')}:${renderNumber(totalTimes)}`,
newModelColors,
'id0',
);
updateChartSpec(
setSpecLine,
newLineData,
`${t('总计')}:${renderQuota(totalQuota, 2)}`,
newModelColors,
'barData',
);
// ===== 模型调用次数折线图 =====
let modelLineData = [];
chartTimePoints.forEach((time) => {
const timeData = Array.from(uniqueModels)
.filter((model) => model) // 过滤掉 undefined/null
.map((model) => {
const key = `${time}-${model}`;
const aggregated = aggregatedData.get(key);
return {
Time: time,
Model: String(model),
Count: aggregated?.count || 0,
};
});
modelLineData.push(...timeData);
});
modelLineData.sort((a, b) => a.Time.localeCompare(b.Time));
// ===== 模型调用次数排行柱状图 =====
const rankData = Array.from(modelTotals)
.filter(([model]) => model) // 过滤掉 undefined/null
.map(([model, count]) => ({
Model: String(model),
Count: count,
}))
.sort((a, b) => b.Count - a.Count);
updateChartSpec(
setSpecModelLine,
modelLineData,
`${t('总计')}:${renderNumber(totalTimes)}`,
newModelColors,
'lineData',
);
updateChartSpec(
setSpecRankBar,
rankData,
`${t('总计')}:${renderNumber(totalTimes)}`,
newModelColors,
'rankData',
);
setPieData(newPieData);
setLineData(newLineData);
setConsumeQuota(totalQuota);
setTimes(totalTimes);
setConsumeTokens(totalTokens);
},
[
dataExportDefaultTime,
setTrendData,
generateModelColors,
setModelColors,
setPieData,
setLineData,
setConsumeQuota,
setTimes,
setConsumeTokens,
t,
],
);
// ========== 初始化图表主题 ==========
useEffect(() => {
initVChartSemiTheme({
isWatchingThemeSwitch: true,
});
}, []);
return {
// 图表规格
spec_pie,
spec_line,
spec_model_line,
spec_rank_bar,
// 函数
updateChartData,
generateModelColors,
};
};
+362
View File
@@ -0,0 +1,362 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { API, isAdmin, showError, timestamp2string } from '../../helpers';
import { getDefaultTime, getInitialTimestamp } from '../../helpers/dashboard';
import { TIME_OPTIONS } from '../../constants/dashboard.constants';
import { useIsMobile } from '../common/useIsMobile';
import { useMinimumLoadingTime } from '../common/useMinimumLoadingTime';
const EMPTY_TOKEN_USAGE = {
input_tokens: 0,
output_tokens: 0,
cache_tokens: 0,
cache_creation_tokens: 0,
total_tokens: 0,
};
export const useDashboardData = (userState, userDispatch, statusState) => {
const { t } = useTranslation();
const navigate = useNavigate();
const isMobile = useIsMobile();
const initialized = useRef(false);
// ========== 基础状态 ==========
const [loading, setLoading] = useState(false);
const [tokenUsageLoading, setTokenUsageLoading] = useState(false);
const [greetingVisible, setGreetingVisible] = useState(false);
const [searchModalVisible, setSearchModalVisible] = useState(false);
const showLoading = useMinimumLoadingTime(loading);
// ========== 输入状态 ==========
const [inputs, setInputs] = useState({
username: '',
token_name: '',
model_name: '',
start_timestamp: getInitialTimestamp(),
end_timestamp: timestamp2string(new Date().getTime() / 1000 + 3600),
channel: '',
data_export_default_time: '',
});
const [dataExportDefaultTime, setDataExportDefaultTime] =
useState(getDefaultTime());
// ========== 数据状态 ==========
const [quotaData, setQuotaData] = useState([]);
const [consumeQuota, setConsumeQuota] = useState(0);
const [consumeTokens, setConsumeTokens] = useState(0);
const [times, setTimes] = useState(0);
const [pieData, setPieData] = useState([{ type: 'null', value: '0' }]);
const [lineData, setLineData] = useState([]);
const [modelColors, setModelColors] = useState({});
const [tokenUsage, setTokenUsage] = useState(EMPTY_TOKEN_USAGE);
// ========== 图表状态 ==========
const [activeChartTab, setActiveChartTab] = useState('1');
// ========== 趋势数据 ==========
const [trendData, setTrendData] = useState({
balance: [],
usedQuota: [],
requestCount: [],
times: [],
consumeQuota: [],
tokens: [],
rpm: [],
tpm: [],
});
// ========== Uptime 数据 ==========
const [uptimeData, setUptimeData] = useState([]);
const [uptimeLoading, setUptimeLoading] = useState(false);
const [activeUptimeTab, setActiveUptimeTab] = useState('');
// ========== 常量 ==========
const now = new Date();
const isAdminUser = isAdmin();
// ========== Panel enable flags ==========
const apiInfoEnabled = statusState?.status?.api_info_enabled ?? true;
const announcementsEnabled =
statusState?.status?.announcements_enabled ?? true;
const faqEnabled = statusState?.status?.faq_enabled ?? true;
const uptimeEnabled = statusState?.status?.uptime_kuma_enabled ?? true;
const hasApiInfoPanel = apiInfoEnabled;
const hasInfoPanels = announcementsEnabled || faqEnabled || uptimeEnabled;
// ========== Memoized Values ==========
const timeOptions = useMemo(
() =>
TIME_OPTIONS.map((option) => ({
...option,
label: t(option.label),
})),
[t],
);
const performanceMetrics = useMemo(() => {
const { start_timestamp, end_timestamp } = inputs;
const timeDiff =
(Date.parse(end_timestamp) - Date.parse(start_timestamp)) / 60000;
const avgRPM = isNaN(times / timeDiff)
? '0'
: (times / timeDiff).toFixed(3);
const avgTPM = isNaN(consumeTokens / timeDiff)
? '0'
: (consumeTokens / timeDiff).toFixed(3);
return { avgRPM, avgTPM, timeDiff };
}, [times, consumeTokens, inputs.start_timestamp, inputs.end_timestamp]);
const getGreeting = useMemo(() => {
const hours = new Date().getHours();
let greeting = '';
if (hours >= 5 && hours < 12) {
greeting = t('早上好');
} else if (hours >= 12 && hours < 14) {
greeting = t('中午好');
} else if (hours >= 14 && hours < 18) {
greeting = t('下午好');
} else {
greeting = t('晚上好');
}
const username = userState?.user?.username || '';
return `👋${greeting},${username}`;
}, [t, userState?.user?.username]);
// ========== 回调函数 ==========
const handleInputChange = useCallback((value, name) => {
if (name === 'data_export_default_time') {
setDataExportDefaultTime(value);
localStorage.setItem('data_export_default_time', value);
return;
}
setInputs((inputs) => ({ ...inputs, [name]: value }));
}, []);
const showSearchModal = useCallback(() => {
setSearchModalVisible(true);
}, []);
const handleCloseModal = useCallback(() => {
setSearchModalVisible(false);
}, []);
// ========== API 调用函数 ==========
const loadQuotaData = useCallback(async () => {
setLoading(true);
try {
let url = '';
const { start_timestamp, end_timestamp, username } = inputs;
let localStartTimestamp = Date.parse(start_timestamp) / 1000;
let localEndTimestamp = Date.parse(end_timestamp) / 1000;
if (isAdminUser) {
url = `/api/data/?username=${username}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}&default_time=${dataExportDefaultTime}`;
} else {
url = `/api/data/self/?start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}&default_time=${dataExportDefaultTime}`;
}
const res = await API.get(url);
const { success, message, data } = res.data;
if (success) {
setQuotaData(data);
if (data.length === 0) {
data.push({
count: 0,
model_name: '无数据',
quota: 0,
created_at: now.getTime() / 1000,
});
}
data.sort((a, b) => a.created_at - b.created_at);
return data;
} else {
showError(message);
return [];
}
} finally {
setLoading(false);
}
}, [inputs, dataExportDefaultTime, isAdminUser, now]);
const loadTokenUsageData = useCallback(async () => {
setTokenUsageLoading(true);
try {
const { start_timestamp, end_timestamp, username } = inputs;
const localStartTimestamp = Date.parse(start_timestamp) / 1000;
const localEndTimestamp = Date.parse(end_timestamp) / 1000;
const query = `start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}`;
const url = isAdminUser
? `/api/data/token_usage?username=${encodeURIComponent(username)}&${query}`
: `/api/data/token_usage/self?${query}`;
const res = await API.get(url);
const { success, message, data } = res.data;
if (success) {
const nextTokenUsage = data || EMPTY_TOKEN_USAGE;
setTokenUsage(nextTokenUsage);
return nextTokenUsage;
}
showError(message);
return null;
} finally {
setTokenUsageLoading(false);
}
}, [inputs, isAdminUser]);
const loadUptimeData = useCallback(async () => {
setUptimeLoading(true);
try {
const res = await API.get('/api/uptime/status');
const { success, message, data } = res.data;
if (success) {
setUptimeData(data || []);
if (data && data.length > 0 && !activeUptimeTab) {
setActiveUptimeTab(data[0].categoryName);
}
} else {
showError(message);
}
} catch (err) {
console.error(err);
} finally {
setUptimeLoading(false);
}
}, [activeUptimeTab]);
const getUserData = useCallback(async () => {
let res = await API.get(`/api/user/self`);
const { success, message, data } = res.data;
if (success) {
userDispatch({ type: 'login', payload: data });
} else {
showError(message);
}
}, [userDispatch]);
const refresh = useCallback(async () => {
const data = await loadQuotaData();
await loadUptimeData();
return data;
}, [loadQuotaData, loadUptimeData]);
const handleSearchConfirm = useCallback(
async (updateChartDataCallback) => {
const data = await refresh();
if (data && data.length > 0 && updateChartDataCallback) {
updateChartDataCallback(data);
}
setSearchModalVisible(false);
},
[refresh],
);
// ========== Effects ==========
useEffect(() => {
const timer = setTimeout(() => {
setGreetingVisible(true);
}, 100);
return () => clearTimeout(timer);
}, []);
useEffect(() => {
if (!initialized.current) {
getUserData();
initialized.current = true;
}
}, [getUserData]);
return {
// 基础状态
loading: showLoading,
tokenUsageLoading,
greetingVisible,
searchModalVisible,
// 输入状态
inputs,
dataExportDefaultTime,
// 数据状态
quotaData,
consumeQuota,
setConsumeQuota,
consumeTokens,
setConsumeTokens,
times,
setTimes,
pieData,
setPieData,
lineData,
setLineData,
modelColors,
setModelColors,
tokenUsage,
// 图表状态
activeChartTab,
setActiveChartTab,
// 趋势数据
trendData,
setTrendData,
// Uptime 数据
uptimeData,
uptimeLoading,
activeUptimeTab,
setActiveUptimeTab,
// 计算值
timeOptions,
performanceMetrics,
getGreeting,
isAdminUser,
hasApiInfoPanel,
hasInfoPanels,
apiInfoEnabled,
announcementsEnabled,
faqEnabled,
uptimeEnabled,
// 函数
handleInputChange,
showSearchModal,
handleCloseModal,
loadQuotaData,
loadTokenUsageData,
loadUptimeData,
getUserData,
refresh,
handleSearchConfirm,
// 导航和翻译
navigate,
t,
isMobile,
};
};
+151
View File
@@ -0,0 +1,151 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useMemo } from 'react';
import { Wallet, Activity, Gauge, Cpu } from 'lucide-react';
import {
IconMoneyExchangeStroked,
IconHistogram,
IconPulse,
IconStopwatchStroked,
IconTypograph,
IconSend,
} from '@douyinfe/semi-icons';
import { renderNumber, renderQuota } from '../../helpers';
import { createSectionTitle } from '../../helpers/dashboard';
export const useDashboardStats = (
userState,
consumeQuota,
consumeTokens,
times,
trendData,
performanceMetrics,
navigate,
t,
tokenUsage = null,
) => {
const groupedStatsData = useMemo(
() => [
{
title: createSectionTitle(Wallet, t('钱包概况')),
color: 'bg-blue-50',
items: [
{
title: t('可用余额'),
value: renderQuota(userState?.user?.quota),
icon: <IconMoneyExchangeStroked />,
avatarColor: 'blue',
},
{
title: t('累计支出'),
value: renderQuota(userState?.user?.used_quota),
icon: <IconHistogram />,
avatarColor: 'purple',
},
],
},
{
title: createSectionTitle(Activity, t('调用活跃度')),
color: 'bg-green-50',
items: [
{
title: t('总调用次数'),
value: userState.user?.request_count,
icon: <IconSend />,
avatarColor: 'green',
},
{
title: t('有效记录'),
value: times,
icon: <IconPulse />,
avatarColor: 'cyan',
},
],
},
...(tokenUsage
? [
{
title: createSectionTitle(Cpu, t('Token 流量')),
color: 'bg-amber-50',
layout: 'two-column',
items: [
{
title: t('输入 Token'),
value: renderNumber(tokenUsage.input_tokens || 0),
icon: <IconTypograph />,
avatarColor: 'blue',
},
{
title: t('输出 Token'),
value: renderNumber(tokenUsage.output_tokens || 0),
icon: <IconSend />,
avatarColor: 'green',
},
{
title: t('缓存命中'),
value: renderNumber(tokenUsage.cache_tokens || 0),
icon: <IconPulse />,
avatarColor: 'cyan',
},
{
title: t('缓存写入'),
value: renderNumber(tokenUsage.cache_creation_tokens || 0),
icon: <IconHistogram />,
avatarColor: 'orange',
},
],
},
]
: []),
{
title: createSectionTitle(Gauge, t('实时速率')),
color: 'bg-brand/5',
items: [
{
title: t('请求速率'),
value: performanceMetrics.avgRPM,
icon: <IconStopwatchStroked />,
avatarColor: 'indigo',
},
{
title: t('Token 速率'),
value: performanceMetrics.avgTPM,
icon: <IconTypograph />,
avatarColor: 'orange',
},
],
},
],
[
userState?.user?.quota,
userState?.user?.used_quota,
userState?.user?.request_count,
times,
trendData,
performanceMetrics,
tokenUsage,
t,
],
);
return {
groupedStatsData,
};
};
+334
View File
@@ -0,0 +1,334 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
/**
* 图像生成管理钩子
* @param {Function} onImageGenerated 图片生成成功后的回调函数
* @returns {Object} 图像生成相关状态和方法
*/
const useImageGeneration = (onImageGenerated) => {
const { t } = useTranslation();
// 状态管理
const [generatedImages, setGeneratedImages] = useState([]);
const [isGenerating, setIsGenerating] = useState(false);
const [error, setError] = useState('');
const [generationParams, setGenerationParams] = useState({});
// 加载状态管理
const [isLoading, setIsLoading] = useState(false);
const [loadingProgress, setLoadingProgress] = useState(0);
// 用于存储上一次成功生成的参数
const lastSuccessfulParamsRef = useRef({});
// 清除错误信息
const clearError = useCallback(() => {
setError('');
}, []);
// 清除生成的图片
const clearGeneratedImages = useCallback(() => {
setGeneratedImages([]);
clearError();
}, [clearError]);
/**
* 生成图片
* @param {Object} params 生成参数
* @param {string} params.prompt 提示词
* @param {string} params.model 模型名称
* @param {string} params.size 图片尺寸
* @param {string} params.quality 图片质量
* @param {string} params.negativePrompt 反向提示词
* @param {number} params.n 生成图片数量
*/
const generateImage = useCallback(
async (params) => {
const {
prompt,
model,
size,
quality,
negativePrompt = '',
n = 1,
} = params;
// 参数验证
if (!prompt || !prompt.trim()) {
setError(t('请输入提示词'));
return false;
}
if (!model) {
setError(t('请选择生成模型'));
return false;
}
if (!size) {
setError(t('请选择图片尺寸'));
return false;
}
// 重置状态
setIsGenerating(true);
setError('');
setIsLoading(true);
setLoadingProgress(0);
// 保存当前参数
setGenerationParams(params);
try {
// 模拟进度更新
const progressInterval = setInterval(() => {
setLoadingProgress((prev) => {
if (prev >= 90) {
clearInterval(progressInterval);
return prev;
}
return prev + Math.random() * 10;
});
}, 200);
// 这里是模拟API调用,实际实现需要替换为真实的API请求
// 模拟网络延迟
await new Promise((resolve) => setTimeout(resolve, 3000));
clearInterval(progressInterval);
// 模拟生成的图片数据
const mockImages = Array.from({ length: n }, (_, index) => ({
id: Date.now() + index,
url: `https://picsum.photos/seed/${Date.now() + index}/${size.split('x')[0]}/${size.split('x')[1]}`,
revised_prompt: prompt,
created_at: new Date().toISOString(),
metadata: {
model,
size,
quality,
negative_prompt: negativePrompt,
},
}));
setGeneratedImages(mockImages);
// 更新上一次成功生成的参数
lastSuccessfulParamsRef.current = params;
// 调用回调函数
if (onImageGenerated) {
onImageGenerated(mockImages, params);
}
return true;
} catch (err) {
console.error('Image generation failed:', err);
setError(t('图片生成失败,请重试') + ': ' + (err.message || ''));
return false;
} finally {
setIsGenerating(false);
setIsLoading(false);
setLoadingProgress(100);
}
},
[t, onImageGenerated],
);
/**
* 重新生成图片
* 使用上一次成功生成的参数或当前保存的参数
*/
const regenerateImage = useCallback(async () => {
// 获取有效的参数
const params =
Object.keys(lastSuccessfulParamsRef.current).length > 0
? lastSuccessfulParamsRef.current
: Object.keys(generationParams).length > 0
? generationParams
: null;
if (!params) {
setError(t('没有可用的生成参数'));
return false;
}
// 确保参数完整
if (!params.prompt || !params.model || !params.size) {
setError(t('参数不完整,无法重新生成'));
return false;
}
return generateImage(params);
}, [generateImage, generationParams, t]);
/**
* 下载单个图片
* @param {string} imageUrl 图片URL
* @param {number} index 图片索引
* @param {string} prompt 提示词(用于生成文件名)
*/
const downloadImage = useCallback((imageUrl, index = 0, prompt = '') => {
const link = document.createElement('a');
// 生成文件名
let filename = 'generated-image';
// 如果有提示词,使用前20个字符作为文件名的一部分
if (prompt && prompt.trim()) {
const safePrompt = prompt
.trim()
.replace(/[^a-z0-9]/gi, '_')
.substring(0, 20);
filename = `${filename}-${safePrompt}`;
}
// 添加索引和时间戳
filename = `${filename}-${index}-${Date.now()}.png`;
link.href = imageUrl;
link.download = filename;
// 模拟点击下载
document.body.appendChild(link);
link.click();
// 清理
setTimeout(() => {
document.body.removeChild(link);
}, 100);
}, []);
/**
* 批量下载所有生成的图片
* @param {string} prompt 提示词(用于生成文件名前缀)
*/
const downloadAllImages = useCallback(
(prompt = '') => {
if (generatedImages.length === 0) {
setError(t('没有可下载的图片'));
return;
}
// 为每个图片创建下载
generatedImages.forEach((image, index) => {
downloadImage(image.url, index, prompt);
});
},
[generatedImages, downloadImage, t],
);
/**
* 将图片转换为Blob对象
* @param {string} imageUrl 图片URL
* @returns {Promise<Blob>} Blob对象
*/
const imageUrlToBlob = useCallback(async (imageUrl) => {
try {
const response = await fetch(imageUrl);
const blob = await response.blob();
return blob;
} catch (error) {
console.error('Failed to convert image to blob:', error);
throw error;
}
}, []);
/**
* 将图片复制到剪贴板
* @param {string} imageUrl 图片URL
*/
const copyImageToClipboard = useCallback(
async (imageUrl) => {
try {
const blob = await imageUrlToBlob(imageUrl);
// 检查浏览器是否支持剪贴板API
if (navigator.clipboard && window.ClipboardItem) {
await navigator.clipboard.write([
new ClipboardItem({
'image/png': blob,
}),
]);
return true;
} else {
setError(t('您的浏览器不支持复制图片到剪贴板'));
return false;
}
} catch (error) {
console.error('Failed to copy image to clipboard:', error);
setError(t('复制图片失败: {{error}}', { error: error.message }));
return false;
}
},
[imageUrlToBlob, t],
);
/**
* 查看图片详情
* @param {Object} image 图片对象
*/
const viewImageDetails = useCallback((image) => {
// 可以在这里实现图片详情查看逻辑,比如打开模态框显示大图
console.log('Viewing image details:', image);
// 如果是浏览器环境,可以在新标签页打开图片
if (typeof window !== 'undefined' && window.open) {
window.open(image.url, '_blank');
}
}, []);
/**
* 获取图片信息
* @param {string} imageId 图片ID
* @returns {Object|null} 图片对象
*/
const getImageById = useCallback(
(imageId) => {
return generatedImages.find((image) => image.id === imageId) || null;
},
[generatedImages],
);
return {
// 状态
generatedImages,
isGenerating,
error,
loadingProgress,
isLoading,
generationParams,
// 操作方法
generateImage,
regenerateImage,
downloadImage,
downloadAllImages,
copyImageToClipboard,
viewImageDetails,
clearGeneratedImages,
clearError,
getImageById,
};
};
export default useImageGeneration;
+401
View File
@@ -0,0 +1,401 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
// 本地存储键名
const STORAGE_KEY = 'imageGenerationHistory';
// 最大历史记录条数
const MAX_HISTORY_ITEMS = 50;
/**
* 图像生成历史记录管理钩子
* @param {number} maxItems 最大历史记录条数
* @returns {Object} 历史记录相关状态和方法
*/
const useImageHistory = (maxItems = MAX_HISTORY_ITEMS) => {
const { t: _t } = useTranslation();
// 状态管理
const [history, setHistory] = useState([]);
const [isLoading, setIsLoading] = useState(true);
// 从本地存储加载历史记录
const loadHistory = useCallback(() => {
try {
setIsLoading(true);
const savedHistory = localStorage.getItem(STORAGE_KEY);
if (savedHistory) {
const parsedHistory = JSON.parse(savedHistory);
// 确保是数组格式
if (Array.isArray(parsedHistory)) {
setHistory(parsedHistory);
}
}
} catch (error) {
console.error('Failed to load history from localStorage:', error);
} finally {
setIsLoading(false);
}
}, []);
// 保存历史记录到本地存储
const saveHistory = useCallback((historyData) => {
try {
localStorage.setItem(STORAGE_KEY, JSON.stringify(historyData));
} catch (error) {
console.error('Failed to save history to localStorage:', error);
}
}, []);
// 初始化时加载历史记录
useEffect(() => {
loadHistory();
}, [loadHistory]);
/**
* 添加新的生成记录
* @param {Object} record 生成记录
* @param {string} record.model 使用的模型
* @param {string} record.prompt 使用的提示词
* @param {string} record.negativePrompt 使用的反向提示词
* @param {string} record.size 图片尺寸
* @param {string} record.quality 图片质量
* @param {Array} record.images 生成的图片数组
*/
const addHistoryRecord = useCallback(
(record) => {
if (
!record ||
!record.prompt ||
!record.images ||
!Array.isArray(record.images)
) {
console.error('Invalid history record:', record);
return;
}
// 创建完整的记录对象
const newRecord = {
id: Date.now().toString(), // 使用时间戳作为唯一ID
timestamp: new Date().toISOString(),
model: record.model || '',
prompt: record.prompt,
negativePrompt: record.negativePrompt || '',
size: record.size || '',
quality: record.quality || 'standard',
style: record.style || 'natural',
images: record.images,
};
setHistory((prev) => {
// 添加新记录到开头,并限制最大数量
const updatedHistory = [newRecord, ...prev].slice(0, maxItems);
// 保存到本地存储
saveHistory(updatedHistory);
return updatedHistory;
});
},
[maxItems, saveHistory],
);
/**
* 删除单条历史记录
* @param {string} recordId 记录ID
*/
const deleteHistoryRecord = useCallback(
(recordId) => {
setHistory((prev) => {
const updatedHistory = prev.filter((item) => item.id !== recordId);
// 保存到本地存储
saveHistory(updatedHistory);
return updatedHistory;
});
},
[saveHistory],
);
/**
* 清空所有历史记录
*/
const clearAllHistory = useCallback(() => {
setHistory([]);
// 从本地存储中删除
try {
localStorage.removeItem(STORAGE_KEY);
} catch (error) {
console.error('Failed to clear history from localStorage:', error);
}
}, []);
/**
* 根据ID获取历史记录
* @param {string} recordId 记录ID
* @returns {Object|null} 历史记录对象
*/
const getHistoryRecordById = useCallback(
(recordId) => {
return history.find((item) => item.id === recordId) || null;
},
[history],
);
/**
* 从历史记录中加载参数
* @param {string} recordId 记录ID
* @returns {Object|null} 生成参数对象
*/
const loadParamsFromHistory = useCallback(
(recordId) => {
const record = getHistoryRecordById(recordId);
if (!record) {
return null;
}
return {
model: record.model,
prompt: record.prompt,
negativePrompt: record.negativePrompt,
size: record.size,
quality: record.quality,
style: record.style,
images: record.images,
};
},
[getHistoryRecordById],
);
/**
* 搜索历史记录
* @param {string} keyword 搜索关键词
* @returns {Array} 符合条件的历史记录数组
*/
const searchHistory = useCallback(
(keyword) => {
if (!keyword || !keyword.trim()) {
return history;
}
const searchTerm = keyword.toLowerCase().trim();
return history.filter(
(item) =>
item.prompt.toLowerCase().includes(searchTerm) ||
(item.negativePrompt &&
item.negativePrompt.toLowerCase().includes(searchTerm)) ||
item.model.toLowerCase().includes(searchTerm),
);
},
[history],
);
/**
* 按时间范围过滤历史记录
* @param {Date} startDate 开始时间
* @param {Date} endDate 结束时间
* @returns {Array} 符合条件的历史记录数组
*/
const filterHistoryByDate = useCallback(
(startDate, endDate) => {
if (!startDate && !endDate) {
return history;
}
return history.filter((item) => {
const itemDate = new Date(item.timestamp);
if (startDate && itemDate < startDate) {
return false;
}
if (endDate && itemDate > endDate) {
return false;
}
return true;
});
},
[history],
);
/**
* 按模型过滤历史记录
* @param {string} modelName 模型名称
* @returns {Array} 符合条件的历史记录数组
*/
const filterHistoryByModel = useCallback(
(modelName) => {
if (!modelName || !modelName.trim()) {
return history;
}
return history.filter((item) => item.model === modelName);
},
[history],
);
/**
* 导出历史记录为JSON
* @returns {string} JSON格式的历史记录
*/
const exportHistory = useCallback(() => {
return JSON.stringify(history, null, 2);
}, [history]);
/**
* 导入历史记录
* @param {string} jsonData JSON格式的历史记录数据
* @returns {boolean} 是否导入成功
*/
const importHistory = useCallback(
(jsonData) => {
try {
const importedData = JSON.parse(jsonData);
// 验证导入的数据格式
if (!Array.isArray(importedData)) {
throw new Error('Invalid history data format');
}
// 验证每条记录的格式
const validRecords = importedData.filter(
(record) =>
record.id &&
record.timestamp &&
record.prompt &&
Array.isArray(record.images),
);
if (validRecords.length === 0) {
throw new Error('No valid history records found');
}
// 合并现有历史记录,避免重复,并限制最大数量
const combinedRecords = [...validRecords, ...history];
// 去重(基于ID)
const uniqueRecords = [];
const seenIds = new Set();
for (const record of combinedRecords) {
if (!seenIds.has(record.id)) {
seenIds.add(record.id);
uniqueRecords.push(record);
}
}
// 按时间戳排序(最新的在前)
uniqueRecords.sort(
(a, b) => new Date(b.timestamp) - new Date(a.timestamp),
);
// 限制最大数量
const finalRecords = uniqueRecords.slice(0, maxItems);
// 更新状态并保存
setHistory(finalRecords);
saveHistory(finalRecords);
return true;
} catch (error) {
console.error('Failed to import history:', error);
return false;
}
},
[history, maxItems, saveHistory],
);
/**
* 获取最近使用的提示词列表
* @param {number} limit 最大返回数量
* @returns {Array} 提示词数组
*/
const getRecentPrompts = useCallback(
(limit = 10) => {
const prompts = [];
const seenPrompts = new Set();
for (const item of history) {
if (item.prompt && !seenPrompts.has(item.prompt)) {
seenPrompts.add(item.prompt);
prompts.push(item.prompt);
if (prompts.length >= limit) {
break;
}
}
}
return prompts;
},
[history],
);
/**
* 获取历史记录统计信息
* @returns {Object} 统计信息
*/
const getHistoryStats = useCallback(() => {
const stats = {
totalRecords: history.length,
models: {},
sizes: {},
recentActivity:
history.length > 0 ? new Date(history[0].timestamp) : null,
};
// 统计各模型和尺寸的使用次数
history.forEach((item) => {
// 模型统计
if (item.model) {
stats.models[item.model] = (stats.models[item.model] || 0) + 1;
}
// 尺寸统计
if (item.size) {
stats.sizes[item.size] = (stats.sizes[item.size] || 0) + 1;
}
});
return stats;
}, [history]);
return {
// 状态
history,
isLoading,
// 操作方法
addHistoryRecord,
deleteHistoryRecord,
clearAllHistory,
getHistoryRecordById,
loadParamsFromHistory,
searchHistory,
filterHistoryByDate,
filterHistoryByModel,
exportHistory,
importHistory,
getRecentPrompts,
getHistoryStats,
loadHistory,
};
};
export default useImageHistory;
+276
View File
@@ -0,0 +1,276 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useCallback, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
// 导入模型判断函数
import { IsImageGenerationModel } from '../../../common/model';
// 定义支持的图片生成模型列表
const IMAGE_GENERATION_MODELS = [
{
value: 'dall-e-3',
label: 'DALL-E 3',
vendor: 'OpenAI',
description: '最新一代DALL-E模型,生成高质量、详细的图像',
recommended: true,
capabilities: {
sizes: ['1024x1024', '1024x1792', '1792x1024'],
supportsQuality: true,
maxImages: 1,
},
},
{
value: 'dall-e-2',
label: 'DALL-E 2',
vendor: 'OpenAI',
description: '较早的DALL-E模型,平衡效果和速度',
recommended: false,
capabilities: {
sizes: ['256x256', '512x512', '1024x1024'],
supportsQuality: false,
maxImages: 10,
},
},
{
value: 'gpt-image-1',
label: 'GPT-4V Image',
vendor: 'OpenAI',
description: '基于GPT-4V的图像生成能力',
recommended: false,
capabilities: {
sizes: ['1024x1024'],
supportsQuality: true,
maxImages: 1,
},
},
{
value: 'imagen-3',
label: 'Imagen 3',
vendor: 'Google',
description: 'Google最新的图像生成模型,擅长文本理解',
recommended: false,
capabilities: {
sizes: ['1024x1024', '1792x1024', '1024x1792'],
supportsQuality: true,
maxImages: 4,
},
},
{
value: 'flux.1-schnell',
label: 'FLUX.1 Schnell',
vendor: 'Black Forest Labs',
description: '快速版FLUX.1模型,生成速度快',
recommended: false,
capabilities: {
sizes: ['1024x1024', '1344x1024', '1024x1344'],
supportsQuality: true,
maxImages: 4,
},
},
{
value: 'flux.1-dev',
label: 'FLUX.1 Dev',
vendor: 'Black Forest Labs',
description: '开发版FLUX.1模型,质量更高',
recommended: false,
capabilities: {
sizes: ['1024x1024', '1344x1024', '1024x1344'],
supportsQuality: true,
maxImages: 4,
},
},
];
// 定义图片尺寸选项
const IMAGE_SIZES = [
{ value: '256x256', label: '256×256', description: '最小尺寸,生成速度最快' },
{
value: '512x512',
label: '512×512',
description: '中等尺寸,平衡质量和速度',
},
{ value: '1024x1024', label: '1024×1024', description: '标准高清尺寸' },
{
value: '1024x1792',
label: '1024×1792 (9:16)',
description: '纵向比例,适合手机壁纸',
},
{
value: '1792x1024',
label: '1792×1024 (16:9)',
description: '横向比例,适合桌面壁纸',
},
{ value: '1344x1024', label: '1344×1024', description: '宽屏比例' },
{ value: '1024x1344', label: '1024×1344', description: '竖屏比例' },
];
// 定义图片质量选项
const IMAGE_QUALITY = [
{ value: 'standard', label: '标准', description: '标准质量,速度较快' },
{ value: 'hd', label: '高清', description: '更高质量,细节更丰富' },
];
/**
* 图像生成模型管理钩子
* @returns {Object} 模型选择相关状态和方法
*/
const useImageModel = () => {
const { t: _t } = useTranslation();
// 获取推荐模型(默认选择第一个推荐的模型)
const getRecommendedModel = () => {
const recommended = IMAGE_GENERATION_MODELS.find(
(model) => model.recommended,
);
return recommended ? recommended.value : IMAGE_GENERATION_MODELS[0].value;
};
// 状态管理
const [selectedModel, setSelectedModel] = useState(() => {
// 尝试从localStorage获取上次选择的模型
const savedModel = localStorage.getItem('selectedImageModel');
return savedModel && IsImageGenerationModel(savedModel)
? savedModel
: getRecommendedModel();
});
const [selectedSize, setSelectedSize] = useState('1024x1024');
const [selectedQuality, setSelectedQuality] = useState('standard');
// 当模型改变时,更新可用的尺寸和质量设置
useEffect(() => {
// 保存选择的模型到localStorage
localStorage.setItem('selectedImageModel', selectedModel);
// 获取当前模型的能力
const currentModel = IMAGE_GENERATION_MODELS.find(
(m) => m.value === selectedModel,
);
if (currentModel) {
// 检查当前选择的尺寸是否可用,如果不可用则选择第一个可用尺寸
if (!currentModel.capabilities.sizes.includes(selectedSize)) {
setSelectedSize(currentModel.capabilities.sizes[0]);
}
// 如果模型不支持质量选择,确保质量设置为standard
if (
!currentModel.capabilities.supportsQuality &&
selectedQuality !== 'standard'
) {
setSelectedQuality('standard');
}
}
}, [selectedModel]);
// 获取当前选中模型的详细信息
const getCurrentModelInfo = useCallback(() => {
return (
IMAGE_GENERATION_MODELS.find((model) => model.value === selectedModel) ||
IMAGE_GENERATION_MODELS[0]
);
}, [selectedModel]);
// 获取当前模型可用的尺寸选项
const getAvailableSizes = useCallback(() => {
const modelInfo = getCurrentModelInfo();
return IMAGE_SIZES.filter((size) =>
modelInfo.capabilities.sizes.includes(size.value),
);
}, [getCurrentModelInfo]);
// 检查当前模型是否支持质量选择
const supportsQualityOption = useCallback(() => {
const modelInfo = getCurrentModelInfo();
return modelInfo.capabilities.supportsQuality;
}, [getCurrentModelInfo]);
// 获取当前模型支持的最大图片数量
const getMaxImages = useCallback(() => {
const modelInfo = getCurrentModelInfo();
return modelInfo.capabilities.maxImages;
}, [getCurrentModelInfo]);
// 按厂商分组模型
const getModelsByVendor = useCallback(() => {
const grouped = {};
IMAGE_GENERATION_MODELS.forEach((model) => {
if (!grouped[model.vendor]) {
grouped[model.vendor] = [];
}
grouped[model.vendor].push(model);
});
return grouped;
}, []);
// 获取模型描述信息
const getModelDescription = useCallback((modelValue) => {
const model = IMAGE_GENERATION_MODELS.find((m) => m.value === modelValue);
return model ? model.description : '';
}, []);
// 获取模型厂商信息
const getVendorInfo = useCallback((modelValue) => {
const model = IMAGE_GENERATION_MODELS.find((m) => m.value === modelValue);
return model ? model.vendor : '';
}, []);
// 检查模型是否为推荐模型
const isRecommendedModel = useCallback((modelValue) => {
const model = IMAGE_GENERATION_MODELS.find((m) => m.value === modelValue);
return model ? model.recommended : false;
}, []);
return {
// 模型列表和信息
models: IMAGE_GENERATION_MODELS,
modelOptions: IMAGE_GENERATION_MODELS.map((model) => ({
value: model.value,
label: model.label,
vendor: model.vendor,
recommended: model.recommended,
})),
// 状态和setter
selectedModel,
setSelectedModel,
selectedSize,
setSelectedSize,
selectedQuality,
setSelectedQuality,
// 尺寸和质量选项
sizeOptions: IMAGE_SIZES,
qualityOptions: IMAGE_QUALITY,
// 功能方法
getCurrentModelInfo,
getAvailableSizes,
supportsQualityOption,
getMaxImages,
getModelsByVendor,
getModelDescription,
getVendorInfo,
isRecommendedModel,
};
};
export default useImageModel;
+314
View File
@@ -0,0 +1,314 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useCallback, useMemo } from 'react';
/**
* 错误类型枚举
*/
export const ERROR_TYPES = {
NETWORK: 'network',
VALIDATION: 'validation',
API: 'api',
RATE_LIMIT: 'rate_limit',
CREDIT: 'credit',
UNKNOWN: 'unknown',
};
/**
* 加载阶段枚举
*/
export const LOADING_STAGES = {
IDLE: 'idle',
PROCESSING: 'processing',
GENERATING: 'generating',
COMPLETING: 'completing',
};
/**
* 图片状态管理钩子
* 用于管理图片生成过程中的加载状态、错误处理、进度显示等
*/
const useImageStatus = () => {
// 状态管理
const [isLoading, setIsLoading] = useState(false);
const [loadingStage, setLoadingStage] = useState(LOADING_STAGES.IDLE);
const [error, setError] = useState(null);
const [progress, setProgress] = useState(0);
const [successMessage, setSuccessMessage] = useState('');
const [notification, setNotification] = useState(null);
// 重置状态
const resetStatus = useCallback(() => {
setIsLoading(false);
setLoadingStage(LOADING_STAGES.IDLE);
setError(null);
setProgress(0);
setSuccessMessage('');
}, []);
// 设置加载状态
const setLoading = useCallback((stage, customProgress) => {
setIsLoading(true);
setLoadingStage(stage || LOADING_STAGES.PROCESSING);
setError(null);
setSuccessMessage('');
if (typeof customProgress !== 'undefined') {
setProgress(customProgress);
} else {
// 根据阶段设置默认进度
const stageProgress = {
[LOADING_STAGES.IDLE]: 0,
[LOADING_STAGES.PROCESSING]: 25,
[LOADING_STAGES.GENERATING]: 50,
[LOADING_STAGES.COMPLETING]: 75,
};
setProgress(stageProgress[stage] || 0);
}
}, []);
// 设置错误
const setErrorState = useCallback(
(message, type = ERROR_TYPES.UNKNOWN, details = {}) => {
setIsLoading(false);
setLoadingStage(LOADING_STAGES.IDLE);
setError({
message,
type,
details,
});
setProgress(0);
},
[],
);
// 设置成功
const setSuccess = useCallback((message = '') => {
setIsLoading(false);
setLoadingStage(LOADING_STAGES.IDLE);
setError(null);
setProgress(100);
setSuccessMessage(message);
// 如果有成功消息,短暂显示通知
if (message) {
showNotification(message, 'success');
}
}, []);
// 更新进度
const updateProgress = useCallback((newProgress) => {
setProgress(Math.min(Math.max(0, newProgress), 100));
}, []);
// 显示通知
const showNotification = useCallback(
(message, type = 'info', duration = 3000) => {
setNotification({
message,
type,
duration,
id: Date.now(),
});
// 自动清除通知
setTimeout(() => {
setNotification(null);
}, duration);
},
[],
);
// 清除通知
const clearNotification = useCallback(() => {
setNotification(null);
}, []);
// 根据错误类型获取建议操作
const getErrorAction = useCallback((errorType) => {
const actionMap = {
[ERROR_TYPES.NETWORK]: {
label: '重试连接',
type: 'retry',
},
[ERROR_TYPES.VALIDATION]: {
label: '修改参数',
type: 'edit',
},
[ERROR_TYPES.API]: {
label: '查看详情',
type: 'details',
},
[ERROR_TYPES.RATE_LIMIT]: {
label: '稍后重试',
type: 'wait',
},
[ERROR_TYPES.CREDIT]: {
label: '充值',
type: 'recharge',
},
[ERROR_TYPES.UNKNOWN]: {
label: '联系支持',
type: 'support',
},
};
return actionMap[errorType] || actionMap[ERROR_TYPES.UNKNOWN];
}, []);
// 根据加载阶段获取描述文本
const getStageText = useCallback((stage) => {
const stageTextMap = {
[LOADING_STAGES.IDLE]: '准备中...',
[LOADING_STAGES.PROCESSING]: '处理提示词...',
[LOADING_STAGES.GENERATING]: '正在生成图像...',
[LOADING_STAGES.COMPLETING]: '优化图片质量...',
};
return stageTextMap[stage] || stageTextMap[LOADING_STAGES.IDLE];
}, []);
// 格式化错误消息
const formatErrorMessage = useCallback((errorObj) => {
if (!errorObj) return '';
const { message, type, details } = errorObj;
// 特定错误类型的格式化
if (type === ERROR_TYPES.VALIDATION && details.field) {
return `${details.field}: ${message}`;
}
if (type === ERROR_TYPES.API && details.code) {
return `${message} (错误码: ${details.code})`;
}
return message;
}, []);
// 处理API错误响应
const handleApiError = useCallback(
(apiResponse) => {
if (!apiResponse) {
return setErrorState('未知错误,请重试', ERROR_TYPES.UNKNOWN);
}
const { error, status } = apiResponse;
if (!error) {
return setErrorState('API返回异常,请重试', ERROR_TYPES.API);
}
// 根据状态码和错误信息判断错误类型
if (status === 429) {
return setErrorState(
error.message || '请求过于频繁,请稍后重试',
ERROR_TYPES.RATE_LIMIT,
{ status },
);
}
if (status === 400 && error.validationErrors) {
return setErrorState(
error.message || '参数验证失败',
ERROR_TYPES.VALIDATION,
{ status, validationErrors: error.validationErrors },
);
}
if (status === 402) {
return setErrorState(
error.message || '余额不足,请充值',
ERROR_TYPES.CREDIT,
{ status },
);
}
// 网络相关错误
if (status >= 500 || status === 0) {
return setErrorState(
error.message || '网络错误,请检查连接后重试',
ERROR_TYPES.NETWORK,
{ status },
);
}
// 其他API错误
return setErrorState(error.message || 'API请求失败', ERROR_TYPES.API, {
status,
});
},
[setErrorState],
);
// 导出的状态和方法
const statusProps = useMemo(
() => ({
// 状态
isLoading,
loadingStage,
error,
progress,
successMessage,
notification,
// 操作方法
resetStatus,
setLoading,
setErrorState,
setSuccess,
updateProgress,
showNotification,
clearNotification,
// 辅助方法
getErrorAction,
getStageText,
formatErrorMessage,
handleApiError,
// 常量
ERROR_TYPES,
LOADING_STAGES,
}),
[
isLoading,
loadingStage,
error,
progress,
successMessage,
notification,
resetStatus,
setLoading,
setErrorState,
setSuccess,
updateProgress,
showNotification,
clearNotification,
getErrorAction,
getStageText,
formatErrorMessage,
handleApiError,
],
);
return statusProps;
};
export default useImageStatus;
+752
View File
@@ -0,0 +1,752 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useCallback, useEffect, useRef } from 'react';
import { API, showError, showSuccess } from '../../helpers';
import { buildImageRequestBody } from '../../constants/imageModelCapabilities';
/**
* 图片生成任务管理 Hook
*/
export const useImageTaskManagement = () => {
// 任务列表
const [tasks, setTasks] = useState([]);
// 加载状态
const [loading, setLoading] = useState(false);
// 轮询定时器
const pollingTimerRef = useRef(null);
// 正在轮询的任务ID集合
const pollingTasksRef = useRef(new Set());
// 轮询失败计数器
const pollingErrorCountRef = useRef(new Map());
/**
* 将后端任务数据转换为前端格式
*/
const convertBackendTask = useCallback((backendTask) => {
// 解析任务数据
let taskData = {};
let imageUrl = null;
let imageBase64 = null; // 标记是否有base64数据(用于刷新链接功能)
let sourceImageUrl = null; // 图生图的原图URL
let sourceImageBase64 = null; // 标记是否有原图base64数据
let prompt = '';
let width = 1024;
let height = 1024;
// 尝试解析 data 字段
if (backendTask.data) {
try {
if (typeof backendTask.data === 'string') {
taskData = JSON.parse(backendTask.data);
} else {
taskData = backendTask.data;
}
// 从 data 中提取图片URL和base64标记
if (
taskData.data &&
Array.isArray(taskData.data) &&
taskData.data.length > 0
) {
const firstImage = taskData.data[0];
// 优先使用 url
if (firstImage.url) {
imageUrl = firstImage.url;
}
// 记录是否有 b64_json(用于刷新链接功能,不保存完整数据避免内存问题)
if (firstImage.b64_json) {
imageBase64 = true; // 只保存标记,表示后端有base64数据可用
}
}
// 注意:任务处理中时data只包含请求参数,没有图片URL是正常的
// 从 properties 或 data 中提取提示词和尺寸
prompt = taskData.prompt || backendTask.properties?.input || '';
// 从 size 字段解析宽高
if (taskData.size) {
const [w, h] = taskData.size.split('x').map(Number);
width = w || 1024;
height = h || 1024;
}
// 提取图生图的原图URL和base64标记
if (taskData.source_image) {
sourceImageUrl = taskData.source_image;
}
if (taskData.source_image_base64) {
// 记录是否有原图base64数据
sourceImageBase64 = true;
// 如果没有source_image URL,使用base64作为显示(但这会影响性能)
// 为了兼容性,暂时保留这个逻辑
if (!sourceImageUrl) {
sourceImageUrl = taskData.source_image_base64;
}
}
} catch (e) {
console.error('Failed to parse task data:', e);
}
}
// 如果从 data 中没有提取到,尝试从 properties 中提取
if (!prompt && backendTask.properties?.input) {
prompt = backendTask.properties.input;
}
// 映射状态
let status = 'processing';
if (backendTask.status === 'SUCCESS') {
status = 'success';
} else if (backendTask.status === 'FAILURE') {
status = 'failed';
} else if (
backendTask.status === 'NOT_START' ||
backendTask.status === 'SUBMITTED' ||
backendTask.status === 'QUEUED' ||
backendTask.status === 'IN_PROGRESS'
) {
status = 'processing';
}
// 判断生成模式:优先从 taskData.mode 获取,其次从 properties.mode 获取,默认为文生图
const mode =
taskData.mode || backendTask.properties?.mode || 'text-to-image';
// 获取模型名称:优先从 taskData.model,其次从 properties.origin_model_name 或 upstream_model_name
const model =
taskData.model ||
backendTask.properties?.origin_model_name ||
backendTask.properties?.upstream_model_name ||
'unknown';
const convertedTask = {
id: backendTask.task_id || backendTask.id?.toString(),
backendId: backendTask.id,
prompt: prompt,
width: width,
height: height,
model: model,
mode: mode,
status: status,
createdAt: backendTask.created_at || new Date().toISOString(),
imageUrl: imageUrl,
imageBase64: imageBase64,
sourceImageUrl: sourceImageUrl,
sourceImageBase64: sourceImageBase64,
progress: parseInt(backendTask.progress) || 0,
errorMessage: backendTask.fail_reason || null,
quality: taskData.quality,
n: taskData.n,
negativePrompt: taskData.negative_prompt || taskData.negativePrompt,
taskData: taskData,
};
// 如果是成功状态但没有图片URL也没有base64,打印警告
if (status === 'success' && !imageUrl && !imageBase64) {
console.warn('警告:任务已成功但没有图片数据', {
taskId: convertedTask.id,
backendTask: backendTask,
taskData: taskData,
});
}
return convertedTask;
}, []);
// 添加新任务
const addTask = useCallback(
async (taskData) => {
setLoading(true);
try {
const modelName = taskData.model || 'sora_image';
let requestData = buildImageRequestBody(modelName, {
prompt: taskData.prompt,
width: taskData.width,
height: taskData.height,
quality: taskData.quality,
n: taskData.n,
negativePrompt: taskData.negativePrompt,
mode: taskData.mode || 'text-to-image',
});
// 图生图模式:将图片转换为 base64
if (taskData.mode === 'image-to-image' && taskData.referenceImage) {
// 获取原始文件对象
const file =
taskData.referenceImage.fileInstance || taskData.referenceImage;
// 将文件转换为 base64
const base64Image = await new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = (error) => reject(error);
reader.readAsDataURL(file);
});
requestData.image = base64Image;
}
const response = await API.post('/api/images/generations', requestData);
console.log('创建任务响应:', response.data);
// 后端返回任务信息,不是图片URL
if (response.data?.success && response.data?.data) {
const backendTask = response.data.data;
// 转换为前端格式并添加到任务列表
const newTask = convertBackendTask({
id: backendTask.id,
task_id: backendTask.task_id,
status: backendTask.status,
progress: backendTask.progress,
created_at: backendTask.created_at,
properties: {
input: taskData.prompt,
model: taskData.model,
mode: taskData.mode || 'text-to-image',
},
});
setTasks((prev) => [newTask, ...prev]);
// 将任务添加到轮询列表;终态以服务端为准,前端不再合成本地超时失败
pollingTasksRef.current.add(newTask.id);
showSuccess('图片生成任务已创建,正在生成中...');
return newTask.id;
} else {
throw new Error('Invalid response format');
}
} catch (error) {
console.error('创建图片生成任务失败:', error);
showError(
'图片生成失败:' +
(error.response?.data?.error?.message || error.message),
);
return null;
} finally {
setLoading(false);
}
},
[convertBackendTask],
);
// 更新任务状态
const updateTaskStatus = useCallback(
(taskId, status, additionalData = {}) => {
setTasks((prev) =>
prev.map((task) =>
task.id === taskId
? {
...task,
status,
...additionalData,
}
: task,
),
);
},
[],
);
// 更新单个任务数据
const updateTask = useCallback((taskId, updates) => {
setTasks((prev) =>
prev.map((task) =>
task.id === taskId
? {
...task,
...updates,
}
: task,
),
);
}, []);
// 刷新任务图片URL
// type: 'generated'(生成图,默认)或 'source'(原图,图生图模式)
// 支持两种场景:
// 1. 有URL时:刷新预签名URL
// 2. 无URL但有base64时:上传base64到COS,获取新URL
// 3. 无URL且前端无base64标记时:仍然发起请求,让后端从数据库获取base64
// silent: 是否静默模式(不显示提示信息)
const refreshTaskUrl = useCallback(
async (taskId, type = 'generated', silent = false) => {
const task = tasks.find((t) => t.id === taskId);
if (!task) {
if (!silent) showError('任务不存在');
return false;
}
// 根据类型确定要刷新的URL
const urlToRefresh =
type === 'source' ? task.sourceImageUrl : task.imageUrl;
// 如果URL是base64格式(data: 开头),说明前端保存了base64但还没上传到COS
// 这种情况需要上传到COS
const isBase64Url = urlToRefresh && urlToRefresh.startsWith('data:');
try {
// 构建请求参数
let apiUrl = `/api/images/refresh-url?task_id=${encodeURIComponent(taskId)}&type=${type}`;
// 如果有有效的COS URL(不是base64),传递给后端刷新
if (urlToRefresh && !isBase64Url) {
apiUrl += `&url=${encodeURIComponent(urlToRefresh)}`;
}
// 如果URL是空的或者是base64格式,不传url参数,后端会从数据库读取base64并上传
const response = await API.get(apiUrl);
if (response.data?.success && response.data?.data?.url) {
const newUrl = response.data.data.url;
console.log(
`${type === 'source' ? '原图' : '生成图'}URL刷新成功,新URL:`,
newUrl,
);
// 根据类型更新对应的URL,并清除base64数据(因为已上传到COS)
if (type === 'source') {
updateTask(taskId, {
sourceImageUrl: newUrl,
sourceImageBase64: null,
});
} else {
updateTask(taskId, { imageUrl: newUrl, imageBase64: null });
}
if (!silent) showSuccess('链接已刷新');
return true;
} else {
if (!silent) showError('刷新链接失败');
return false;
}
} catch (error) {
console.error('刷新URL失败:', error);
if (!silent)
showError(
'刷新链接失败:' +
(error.response?.data?.error?.message || error.message),
);
return false;
}
},
[tasks, updateTask],
);
// 批量刷新所有成功状态任务的图片链接(静默模式,用于页面加载时自动刷新)
const refreshAllSuccessUrls = useCallback(
async (taskList) => {
// 筛选出成功状态的任务
const successTasks = taskList.filter((task) => task.status === 'success');
if (successTasks.length === 0) {
return;
}
console.log(`开始批量刷新 ${successTasks.length} 个任务的图片链接...`);
// 并发刷新,但限制并发数避免请求过多
const BATCH_SIZE = 5;
let refreshedCount = 0;
for (let i = 0; i < successTasks.length; i += BATCH_SIZE) {
const batch = successTasks.slice(i, i + BATCH_SIZE);
await Promise.all(
batch.map(async (task) => {
try {
// 构建请求参数
let apiUrl = `/api/images/refresh-url?task_id=${encodeURIComponent(task.id)}&type=generated`;
const urlToRefresh = task.imageUrl;
const isBase64Url =
urlToRefresh && urlToRefresh.startsWith('data:');
if (urlToRefresh && !isBase64Url) {
apiUrl += `&url=${encodeURIComponent(urlToRefresh)}`;
}
const response = await API.get(apiUrl);
if (response.data?.success && response.data?.data?.url) {
const newUrl = response.data.data.url;
updateTask(task.id, { imageUrl: newUrl, imageBase64: null });
refreshedCount++;
}
} catch (error) {
// 静默失败,不影响其他任务
console.warn(`刷新任务 ${task.id} 链接失败:`, error.message);
}
}),
);
}
if (refreshedCount > 0) {
console.log(
`批量刷新完成,成功刷新 ${refreshedCount} 个任务的图片链接`,
);
}
},
[updateTask],
);
// 取消/删除任务
const deleteTask = useCallback(
async (taskId) => {
// 找到任务,判断是否需要调用取消API
const task = tasks.find((t) => t.id === taskId);
// 立即从轮询列表中移除,停止轮询
pollingTasksRef.current.delete(taskId);
pollingErrorCountRef.current.delete(taskId);
// 如果任务正在处理中,调用后端取消API
if (task && task.status === 'processing') {
try {
const response = await API.post(
`/api/images/generations/${taskId}/cancel`,
);
if (response.data?.success) {
showSuccess('任务已取消');
} else {
console.warn('后端取消任务失败:', response.data?.message);
showSuccess('任务已从列表中移除');
}
} catch (error) {
console.error('取消任务失败:', error);
showSuccess('任务已从列表中移除');
}
} else {
// 已完成的任务,调用删除API(软删除)
try {
const response = await API.delete(
`/api/images/generations/${taskId}`,
);
if (response.data?.success) {
showSuccess('任务已删除');
} else {
console.warn('后端删除任务失败:', response.data?.message);
showSuccess('任务已从列表中移除');
}
} catch (error) {
console.error('删除任务失败:', error);
showSuccess('任务已从列表中移除');
}
}
// 从前端列表中移除
setTasks((prev) => prev.filter((t) => t.id !== taskId));
},
[tasks],
);
// 重试任务 - 使用原任务的参数创建新任务
const retryTask = useCallback(
async (taskId) => {
const task = tasks.find((t) => t.id === taskId);
if (!task) {
showError('任务不存在');
return null;
}
// 检查是否是图生图模式
const isImageToImage = task.mode === 'image-to-image';
// 对于图生图任务,需要有原图数据
if (isImageToImage) {
// 检查是否有原图数据
if (!task.sourceImageUrl) {
showError('图生图任务缺少原图数据,无法重试。请重新上传图片');
return null;
}
// 如果原图是COS URL(不是base64),无法直接重试
if (!task.sourceImageUrl.startsWith('data:')) {
showError(
'图生图任务的原图已上传到云存储,无法直接重试。请重新上传图片',
);
return null;
}
}
try {
setLoading(true);
// 构建请求数据 — 复用 capability registry 清洗
const modelName = task.model || 'sora_image';
let requestData = buildImageRequestBody(modelName, {
prompt: task.prompt,
width: task.width,
height: task.height,
quality: task.quality,
n: task.n,
negativePrompt: task.negativePrompt,
mode: task.mode || 'text-to-image',
});
// 图生图模式:添加原图数据
if (isImageToImage && task.sourceImageUrl) {
requestData.image = task.sourceImageUrl;
}
const response = await API.post('/api/images/generations', requestData);
if (response.data?.success && response.data?.data) {
const backendTask = response.data.data;
// 转换为前端格式并添加到任务列表
const newTask = convertBackendTask({
id: backendTask.id,
task_id: backendTask.task_id,
status: backendTask.status,
progress: backendTask.progress,
created_at: backendTask.created_at,
properties: {
input: task.prompt,
model: task.model,
mode: task.mode || 'text-to-image',
},
});
setTasks((prev) => [newTask, ...prev]);
// 将任务添加到轮询列表,并记录开始时间
pollingTasksRef.current.add(newTask.id);
showSuccess('重试任务已创建,正在生成中...');
return newTask.id;
} else {
throw new Error('Invalid response format');
}
} catch (error) {
console.error('重试任务失败:', error);
showError(
'重试失败:' +
(error.response?.data?.error?.message || error.message),
);
return null;
} finally {
setLoading(false);
}
},
[tasks, convertBackendTask],
);
// 刷新任务列表
// autoRefreshUrls: 是否自动刷新成功任务的图片链接(默认 true,首次加载时使用)
const refreshTasks = useCallback(
async (showNotification = false, autoRefreshUrls = true) => {
setLoading(true);
try {
const response = await API.get('/api/images/tasks?page=1&page_size=50');
console.log('获取任务列表响应:', response.data);
if (response.data?.success && response.data?.data?.items) {
const backendTasks = response.data.data.items;
// 转换所有任务为前端格式
const convertedTasks = backendTasks.map((task) =>
convertBackendTask(task),
);
setTasks(convertedTasks);
// 找出所有正在进行中的任务,添加到轮询列表
convertedTasks.forEach((task) => {
if (task.status === 'processing') {
// 如果任务还没在轮询列表中,添加并记录开始时间
if (!pollingTasksRef.current.has(task.id)) {
pollingTasksRef.current.add(task.id);
}
}
});
// 自动刷新成功任务的图片链接(在后台静默执行,不阻塞页面)
if (autoRefreshUrls) {
// 使用 setTimeout 确保不阻塞 UI 渲染
setTimeout(() => {
refreshAllSuccessUrls(convertedTasks);
}, 500);
}
if (showNotification) {
showSuccess('刷新成功');
}
}
} catch (error) {
console.error('刷新任务列表失败:', error);
if (showNotification) {
showError(
'刷新失败:' +
(error.response?.data?.error?.message || error.message),
);
}
} finally {
setLoading(false);
}
},
[convertBackendTask, refreshAllSuccessUrls],
);
// 轮询单个任务状态
const pollTaskStatus = useCallback(
async (taskId) => {
try {
const response = await API.get(`/api/images/generations/${taskId}`);
if (response.data?.success && response.data?.data) {
const backendTask = response.data.data;
const updatedTask = convertBackendTask(backendTask);
// 轮询成功,清除错误计数
pollingErrorCountRef.current.delete(taskId);
// 更新任务状态
setTasks((prev) =>
prev.map((task) => (task.id === taskId ? updatedTask : task)),
);
// 如果任务已完成(成功或失败),从轮询列表中移除
if (
updatedTask.status === 'success' ||
updatedTask.status === 'failed'
) {
pollingTasksRef.current.delete(taskId);
}
return updatedTask;
} else {
// 非终态 API 错误只记录,不把本地状态伪造为失败;后端任务可能仍会成功并扣费。
const errorCount =
(pollingErrorCountRef.current.get(taskId) || 0) + 1;
const errorMessage =
response.data?.message || response.data?.error?.message || '';
if (errorMessage.toLowerCase().includes('task not found')) {
pollingTasksRef.current.delete(taskId);
pollingErrorCountRef.current.delete(taskId);
setTasks((prev) =>
prev.map((task) =>
task.id === taskId
? {
...task,
status: 'failed',
errorMessage: '任务不存在',
}
: task,
),
);
return;
}
pollingErrorCountRef.current.set(taskId, Math.min(errorCount, 3));
if (errorCount === 3) {
console.warn(`任务 ${taskId} 状态暂时无法获取,将继续轮询`);
}
}
} catch (error) {
console.error(`轮询任务 ${taskId} 状态失败:`, error);
// 增加错误计数
const errorCount = (pollingErrorCountRef.current.get(taskId) || 0) + 1;
pollingErrorCountRef.current.set(taskId, Math.min(errorCount, 3));
// 如果是404错误,直接停止轮询
if (error.response?.status === 404) {
console.warn(`任务 ${taskId} 不存在,停止轮询`);
pollingTasksRef.current.delete(taskId);
pollingErrorCountRef.current.delete(taskId);
// 更新任务状态为失败
setTasks((prev) =>
prev.map((task) =>
task.id === taskId
? { ...task, status: 'failed', errorMessage: '任务不存在' }
: task,
),
);
return;
}
if (errorCount === 3) {
console.warn(`任务 ${taskId} 状态暂时无法获取,将继续轮询`);
}
}
},
[convertBackendTask],
);
// 轮询所有进行中的任务
const pollAllTasks = useCallback(async () => {
const tasksToPool = Array.from(pollingTasksRef.current);
if (tasksToPool.length === 0) {
return;
}
console.log('轮询任务:', tasksToPool);
// 并发轮询所有任务
await Promise.all(tasksToPool.map((taskId) => pollTaskStatus(taskId)));
}, [pollTaskStatus]);
// 启动轮询定时器
useEffect(() => {
// 组件挂载时加载任务列表
refreshTasks();
// 设置定时器,每5秒轮询一次
pollingTimerRef.current = setInterval(() => {
pollAllTasks();
}, 5000);
// 清理函数
return () => {
if (pollingTimerRef.current) {
clearInterval(pollingTimerRef.current);
}
};
}, [refreshTasks, pollAllTasks]);
// 清空所有任务
const clearAllTasks = useCallback(() => {
setTasks([]);
showSuccess('已清空所有任务');
}, []);
return {
tasks,
loading,
addTask,
updateTaskStatus,
deleteTask,
retryTask,
refreshTasks,
refreshTaskUrl,
clearAllTasks,
};
};
+338
View File
@@ -0,0 +1,338 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Modal } from '@douyinfe/semi-ui';
import {
API,
copy,
isAdmin,
showError,
showSuccess,
timestamp2string,
} from '../../helpers';
import { ITEMS_PER_PAGE } from '../../constants';
import { useTableCompactMode } from '../common/useTableCompactMode';
export const useMjLogsData = () => {
const { t } = useTranslation();
// Define column keys for selection
const COLUMN_KEYS = {
SUBMIT_TIME: 'submit_time',
DURATION: 'duration',
CHANNEL: 'channel',
TYPE: 'type',
TASK_ID: 'task_id',
SUBMIT_RESULT: 'submit_result',
TASK_STATUS: 'task_status',
PROGRESS: 'progress',
IMAGE: 'image',
PROMPT: 'prompt',
PROMPT_EN: 'prompt_en',
FAIL_REASON: 'fail_reason',
};
// Basic state
const [logs, setLogs] = useState([]);
const [loading, setLoading] = useState(true);
const [activePage, setActivePage] = useState(1);
const [logCount, setLogCount] = useState(0);
const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
const [showBanner, setShowBanner] = useState(false);
// User and admin
const isAdminUser = isAdmin();
// Role-specific storage key to prevent different roles from overwriting each other
const STORAGE_KEY = isAdminUser
? 'mj-logs-table-columns-admin'
: 'mj-logs-table-columns-user';
// Modal states
const [isModalOpen, setIsModalOpen] = useState(false);
const [modalContent, setModalContent] = useState('');
const [isModalOpenurl, setIsModalOpenurl] = useState(false);
const [modalImageUrl, setModalImageUrl] = useState('');
// Form state
const [formApi, setFormApi] = useState(null);
let now = new Date();
const formInitValues = {
channel_id: '',
mj_id: '',
dateRange: [
timestamp2string(now.getTime() / 1000 - 2592000),
timestamp2string(now.getTime() / 1000 + 3600),
],
};
// Column visibility state
const [visibleColumns, setVisibleColumns] = useState({});
const [showColumnSelector, setShowColumnSelector] = useState(false);
// Compact mode
const [compactMode, setCompactMode] = useTableCompactMode('mjLogs');
// Load saved column preferences from localStorage
useEffect(() => {
const savedColumns = localStorage.getItem(STORAGE_KEY);
if (savedColumns) {
try {
const parsed = JSON.parse(savedColumns);
const defaults = getDefaultColumnVisibility();
const merged = { ...defaults, ...parsed };
// For non-admin users, force-hide admin-only columns (does not touch admin settings)
if (!isAdminUser) {
merged[COLUMN_KEYS.CHANNEL] = false;
merged[COLUMN_KEYS.SUBMIT_RESULT] = false;
}
setVisibleColumns(merged);
} catch (e) {
console.error('Failed to parse saved column preferences', e);
initDefaultColumns();
}
} else {
initDefaultColumns();
}
}, []);
// Check banner notification
useEffect(() => {
const mjNotifyEnabled = localStorage.getItem('mj_notify_enabled');
if (mjNotifyEnabled !== 'true') {
setShowBanner(true);
}
}, []);
// Get default column visibility based on user role
const getDefaultColumnVisibility = () => {
return {
[COLUMN_KEYS.SUBMIT_TIME]: true,
[COLUMN_KEYS.DURATION]: true,
[COLUMN_KEYS.CHANNEL]: isAdminUser,
[COLUMN_KEYS.TYPE]: true,
[COLUMN_KEYS.TASK_ID]: true,
[COLUMN_KEYS.SUBMIT_RESULT]: isAdminUser,
[COLUMN_KEYS.TASK_STATUS]: true,
[COLUMN_KEYS.PROGRESS]: true,
[COLUMN_KEYS.IMAGE]: true,
[COLUMN_KEYS.PROMPT]: true,
[COLUMN_KEYS.PROMPT_EN]: true,
[COLUMN_KEYS.FAIL_REASON]: true,
};
};
// Initialize default column visibility
const initDefaultColumns = () => {
const defaults = getDefaultColumnVisibility();
setVisibleColumns(defaults);
localStorage.setItem(STORAGE_KEY, JSON.stringify(defaults));
};
// Handle column visibility change
const handleColumnVisibilityChange = (columnKey, checked) => {
const updatedColumns = { ...visibleColumns, [columnKey]: checked };
setVisibleColumns(updatedColumns);
};
// Handle "Select All" checkbox
const handleSelectAll = (checked) => {
const allKeys = Object.keys(COLUMN_KEYS).map((key) => COLUMN_KEYS[key]);
const updatedColumns = {};
allKeys.forEach((key) => {
if (
(key === COLUMN_KEYS.CHANNEL || key === COLUMN_KEYS.SUBMIT_RESULT) &&
!isAdminUser
) {
updatedColumns[key] = false;
} else {
updatedColumns[key] = checked;
}
});
setVisibleColumns(updatedColumns);
};
// Persist column settings to the role-specific STORAGE_KEY
useEffect(() => {
if (Object.keys(visibleColumns).length > 0) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(visibleColumns));
}
}, [visibleColumns]);
// Get form values helper function
const getFormValues = () => {
const formValues = formApi ? formApi.getValues() : {};
let start_timestamp = timestamp2string(now.getTime() / 1000 - 2592000);
let end_timestamp = timestamp2string(now.getTime() / 1000 + 3600);
if (
formValues.dateRange &&
Array.isArray(formValues.dateRange) &&
formValues.dateRange.length === 2
) {
start_timestamp = formValues.dateRange[0];
end_timestamp = formValues.dateRange[1];
}
return {
channel_id: formValues.channel_id || '',
mj_id: formValues.mj_id || '',
start_timestamp,
end_timestamp,
};
};
// Enrich logs data
const enrichLogs = (items) => {
return items.map((log) => ({
...log,
timestamp2string: timestamp2string(log.created_at),
key: '' + log.id,
}));
};
// Sync page data
const syncPageData = (payload) => {
const items = enrichLogs(payload.items || []);
setLogs(items);
setLogCount(payload.total || 0);
setActivePage(payload.page || 1);
setPageSize(payload.page_size || pageSize);
};
// Load logs function
const loadLogs = async (page = 1, size = pageSize) => {
setLoading(true);
const { channel_id, mj_id, start_timestamp, end_timestamp } =
getFormValues();
let localStartTimestamp = Date.parse(start_timestamp);
let localEndTimestamp = Date.parse(end_timestamp);
const url = isAdminUser
? `/api/mj/?p=${page}&page_size=${size}&channel_id=${channel_id}&mj_id=${mj_id}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}`
: `/api/mj/self/?p=${page}&page_size=${size}&mj_id=${mj_id}&start_timestamp=${localStartTimestamp}&end_timestamp=${localEndTimestamp}`;
const res = await API.get(url);
const { success, message, data } = res.data;
if (success) {
syncPageData(data);
} else {
showError(message);
}
setLoading(false);
};
// Page handlers
const handlePageChange = (page) => {
loadLogs(page, pageSize).then();
};
const handlePageSizeChange = async (size) => {
localStorage.setItem('mj-page-size', size + '');
await loadLogs(1, size);
};
// Refresh function
const refresh = async () => {
await loadLogs(1, pageSize);
};
// Copy text function
const copyText = async (text) => {
if (await copy(text)) {
showSuccess(t('已复制:') + text);
} else {
Modal.error({ title: t('无法复制到剪贴板,请手动复制'), content: text });
}
};
// Modal handlers
const openContentModal = (content) => {
setModalContent(content);
setIsModalOpen(true);
};
const openImageModal = (imageUrl) => {
setModalImageUrl(imageUrl);
setIsModalOpenurl(true);
};
// Initialize data
useEffect(() => {
const localPageSize =
parseInt(localStorage.getItem('mj-page-size')) || ITEMS_PER_PAGE;
setPageSize(localPageSize);
loadLogs(1, localPageSize).then();
}, []);
return {
// Basic state
logs,
loading,
activePage,
logCount,
pageSize,
showBanner,
isAdminUser,
// Modal state
isModalOpen,
setIsModalOpen,
modalContent,
isModalOpenurl,
setIsModalOpenurl,
modalImageUrl,
// Form state
formApi,
setFormApi,
formInitValues,
getFormValues,
// Column visibility
visibleColumns,
showColumnSelector,
setShowColumnSelector,
handleColumnVisibilityChange,
handleSelectAll,
initDefaultColumns,
COLUMN_KEYS,
// Compact mode
compactMode,
setCompactMode,
// Functions
loadLogs,
handlePageChange,
handlePageSizeChange,
refresh,
copyText,
openContentModal,
openImageModal,
enrichLogs,
syncPageData,
// Translation
t,
};
};
@@ -0,0 +1,447 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect, useContext, useRef, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import {
API,
copy,
getCurrencySymbol,
showError,
showInfo,
showSuccess,
} from '../../helpers';
import { Modal } from '@douyinfe/semi-ui';
import { UserContext } from '../../context/User';
import { StatusContext } from '../../context/Status';
export const useModelPricingData = () => {
const { t } = useTranslation();
const [searchValue, setSearchValue] = useState('');
const compositionRef = useRef({ isComposition: false });
const [selectedRowKeys, setSelectedRowKeys] = useState([]);
const [modalImageUrl, setModalImageUrl] = useState('');
const [isModalOpenurl, setIsModalOpenurl] = useState(false);
const [selectedGroup, setSelectedGroup] = useState('all');
const [showModelDetail, setShowModelDetail] = useState(false);
const [selectedModel, setSelectedModel] = useState(null);
const [filterGroup, setFilterGroup] = useState('all'); // 用于 Table 的可用分组筛选,"all" 表示不过滤
const [filterQuotaType, setFilterQuotaType] = useState('all'); // 计费类型筛选: 'all' | 0 | 1
const [filterEndpointType, setFilterEndpointType] = useState('all'); // 端点类型筛选: 'all' | string
const [filterVendor, setFilterVendor] = useState('all'); // 供应商筛选: 'all' | 'unknown' | string
const [filterTag, setFilterTag] = useState('all'); // 模型标签筛选: 'all' | string
const [pageSize, setPageSize] = useState(20);
const [currentPage, setCurrentPage] = useState(1);
const [currency, setCurrency] = useState('USD');
const [showWithRecharge, setShowWithRecharge] = useState(false);
const [tokenUnit, setTokenUnit] = useState('M');
const [models, setModels] = useState([]);
const [vendorsMap, setVendorsMap] = useState({});
const [loading, setLoading] = useState(true);
const [groupRatio, setGroupRatio] = useState({});
// 模型级等级折扣修正系数(四期):{分组: {模型: 系数}},有效倍率 = groupRatio[g] × (系数 ?? 1)
const [groupModelDiscount, setGroupModelDiscount] = useState({});
// 折扣展示口径:enterprise=企业作用域按企业等级折扣展示(个人密钥调用仍按个人等级计费)
const [discountScope, setDiscountScope] = useState('personal');
const [usableGroup, setUsableGroup] = useState({});
const [endpointMap, setEndpointMap] = useState({});
const [autoGroups, setAutoGroups] = useState([]);
const [hidePrice, setHidePrice] = useState(false);
const [statusState] = useContext(StatusContext);
const [userState] = useContext(UserContext);
// 充值汇率(price)与美元兑人民币汇率(usd_exchange_rate)
const priceRate = useMemo(
() => statusState?.status?.price ?? 1,
[statusState],
);
const usdExchangeRate = useMemo(
() => statusState?.status?.usd_exchange_rate ?? priceRate,
[statusState, priceRate],
);
const customExchangeRate = useMemo(
() => statusState?.status?.custom_currency_exchange_rate ?? 1,
[statusState],
);
const customCurrencySymbol = useMemo(
() => statusState?.status?.custom_currency_symbol ?? '¤',
[statusState],
);
// 从系统配置中读取是否显示分组倍率(默认为 false)
const showRatio = useMemo(
() =>
statusState?.status?.show_group_ratio === 'true' ||
statusState?.status?.show_group_ratio === true,
[statusState],
);
// 默认货币与站点展示类型同步(USD/CNY),TOKENS 时仍允许切换视图内货币
const siteDisplayType = useMemo(
() => statusState?.status?.quota_display_type || 'USD',
[statusState],
);
useEffect(() => {
if (
siteDisplayType === 'USD' ||
siteDisplayType === 'CNY' ||
siteDisplayType === 'CUSTOM'
) {
setCurrency(siteDisplayType);
}
}, [siteDisplayType]);
const filteredModels = useMemo(() => {
let result = models;
// 分组筛选
if (filterGroup !== 'all') {
result = result.filter((model) =>
model.enable_groups.includes(filterGroup),
);
}
// 计费类型筛选
if (filterQuotaType !== 'all') {
result = result.filter((model) => model.quota_type === filterQuotaType);
}
// 端点类型筛选
if (filterEndpointType !== 'all') {
result = result.filter(
(model) =>
model.supported_endpoint_types &&
model.supported_endpoint_types.includes(filterEndpointType),
);
}
// 供应商筛选
if (filterVendor !== 'all') {
if (filterVendor === 'unknown') {
result = result.filter((model) => !model.vendor_name);
} else {
result = result.filter((model) => model.vendor_name === filterVendor);
}
}
// 标签筛选
if (filterTag !== 'all') {
const tagLower = filterTag.toLowerCase();
result = result.filter((model) => {
if (!model.tags) return false;
const tagsArr = model.tags
.toLowerCase()
.split(/[,;|]+/)
.map((tag) => tag.trim())
.filter(Boolean);
return tagsArr.includes(tagLower);
});
}
// 搜索筛选
if (searchValue.length > 0) {
const searchTerm = searchValue.toLowerCase();
result = result.filter(
(model) =>
(model.model_name &&
model.model_name.toLowerCase().includes(searchTerm)) ||
(model.description &&
model.description.toLowerCase().includes(searchTerm)) ||
(model.tags && model.tags.toLowerCase().includes(searchTerm)) ||
(model.vendor_name &&
model.vendor_name.toLowerCase().includes(searchTerm)),
);
}
return result;
}, [
models,
searchValue,
filterGroup,
filterQuotaType,
filterEndpointType,
filterVendor,
filterTag,
]);
const rowSelection = useMemo(
() => ({
selectedRowKeys,
onChange: (keys) => {
setSelectedRowKeys(keys);
},
}),
[selectedRowKeys],
);
const displayPrice = (usdPrice) => {
let priceInUSD = usdPrice;
if (showWithRecharge) {
priceInUSD = (usdPrice * priceRate) / usdExchangeRate;
}
if (currency === 'CNY') {
return `${getCurrencySymbol('CNY')}${(priceInUSD * usdExchangeRate).toFixed(3)}`;
} else if (currency === 'CUSTOM') {
return `${getCurrencySymbol('CUSTOM', customCurrencySymbol)}${(priceInUSD * customExchangeRate).toFixed(3)}`;
}
return `${getCurrencySymbol('USD')}${priceInUSD.toFixed(3)}`;
};
const setModelsFormat = (
models,
groupRatio,
vendorMap,
levelStates = {},
officialPrices = {},
) => {
for (let i = 0; i < models.length; i++) {
const m = models[i];
m.key = m.model_name;
// 官方(原厂)牌价:管理员维护,仅用于折扣展示(hide_price 时后端不下发)
m.official_price = officialPrices?.[m.model_name];
// 等级锁态(§6.2):后端已剔除 hidden,visible 标记为锁定,展示锁图标
m.level_locked = levelStates?.[m.model_name] === 'visible';
if (m.vendor_id && vendorMap[m.vendor_id]) {
const vendor = vendorMap[m.vendor_id];
m.vendor_name = vendor.name;
m.vendor_icon = vendor.icon;
m.vendor_description = vendor.description;
}
}
models.sort((a, b) => {
return a.quota_type - b.quota_type;
});
models.sort((a, b) => {
if (a.model_name.startsWith('gpt') && !b.model_name.startsWith('gpt')) {
return -1;
} else if (
!a.model_name.startsWith('gpt') &&
b.model_name.startsWith('gpt')
) {
return 1;
} else {
return a.model_name.localeCompare(b.model_name);
}
});
setModels(models);
};
const loadPricing = async () => {
setLoading(true);
let url = '/api/pricing';
const res = await API.get(url);
const {
success,
message,
data,
vendors,
group_ratio,
group_model_discount,
discount_scope,
usable_group,
supported_endpoint,
auto_groups,
hide_price,
level_states,
official_prices,
} = res.data;
if (success) {
setHidePrice(hide_price === true);
setGroupRatio(group_ratio);
setGroupModelDiscount(group_model_discount || {});
setDiscountScope(discount_scope || 'personal');
setUsableGroup(usable_group);
setSelectedGroup('all');
// 构建供应商 Map 方便查找
const vendorMap = {};
if (Array.isArray(vendors)) {
vendors.forEach((v) => {
vendorMap[v.id] = v;
});
}
setVendorsMap(vendorMap);
setEndpointMap(supported_endpoint || {});
setAutoGroups(auto_groups || []);
setModelsFormat(
data,
group_ratio,
vendorMap,
level_states || {},
official_prices || {},
);
} else {
showError(message);
}
setLoading(false);
};
const refresh = async () => {
await loadPricing();
};
const copyText = async (text) => {
if (await copy(text)) {
showSuccess(t('已复制:') + text);
} else {
Modal.error({ title: t('无法复制到剪贴板,请手动复制'), content: text });
}
};
const handleChange = (value) => {
const newSearchValue = value ? value : '';
setSearchValue(newSearchValue);
};
const handleCompositionStart = () => {
compositionRef.current.isComposition = true;
};
const handleCompositionEnd = (event) => {
compositionRef.current.isComposition = false;
const value = event.target.value;
const newSearchValue = value ? value : '';
setSearchValue(newSearchValue);
};
const handleGroupClick = (group) => {
setSelectedGroup(group);
setFilterGroup(group);
if (group === 'all') {
showInfo(t('已切换至最优倍率视图,每个模型使用其最低倍率分组'));
} else {
showInfo(
t('当前查看的分组为:{{group}},倍率为:{{ratio}}', {
group: group,
ratio: groupRatio[group] ?? 1,
}),
);
}
};
const openModelDetail = (model) => {
setSelectedModel(model);
setShowModelDetail(true);
};
const closeModelDetail = () => {
setShowModelDetail(false);
setTimeout(() => {
setSelectedModel(null);
}, 300);
};
useEffect(() => {
refresh().then();
}, []);
// 当筛选条件变化时重置到第一页
useEffect(() => {
setCurrentPage(1);
}, [
filterGroup,
filterQuotaType,
filterEndpointType,
filterVendor,
filterTag,
searchValue,
]);
return {
// 状态
searchValue,
setSearchValue,
selectedRowKeys,
setSelectedRowKeys,
modalImageUrl,
setModalImageUrl,
isModalOpenurl,
setIsModalOpenurl,
selectedGroup,
setSelectedGroup,
showModelDetail,
setShowModelDetail,
selectedModel,
setSelectedModel,
filterGroup,
setFilterGroup,
filterQuotaType,
setFilterQuotaType,
filterEndpointType,
setFilterEndpointType,
filterVendor,
setFilterVendor,
filterTag,
setFilterTag,
pageSize,
setPageSize,
currentPage,
setCurrentPage,
currency,
setCurrency,
showWithRecharge,
setShowWithRecharge,
tokenUnit,
setTokenUnit,
models,
loading,
groupRatio,
groupModelDiscount,
discountScope,
usableGroup,
endpointMap,
autoGroups,
showRatio,
hidePrice,
// 计算属性
priceRate,
usdExchangeRate,
filteredModels,
rowSelection,
// 供应商
vendorsMap,
// 用户和状态
userState,
statusState,
// 方法
displayPrice,
refresh,
copyText,
handleChange,
handleCompositionStart,
handleCompositionEnd,
handleGroupClick,
openModelDetail,
closeModelDetail,
// 引用
compositionRef,
// 国际化
t,
};
};
@@ -0,0 +1,174 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useMemo } from 'react';
// 工具函数:将 tags 字符串转为小写去重数组
const normalizeTags = (tags = '') =>
tags
.toLowerCase()
.split(/[,;|]+/)
.map((t) => t.trim())
.filter(Boolean);
/**
* 统一计算模型筛选后的各种集合与动态计数,供多个组件复用
*/
export const usePricingFilterCounts = ({
models = [],
filterGroup = 'all',
filterQuotaType = 'all',
filterEndpointType = 'all',
filterVendor = 'all',
filterTag = 'all',
searchValue = '',
}) => {
// 均使用同一份模型列表,避免创建新引用
const allModels = models;
/**
* 通用过滤函数
* @param {Object} model
* @param {Array<string>} ignore 需要忽略的过滤条件 key
* @returns {boolean}
*/
const matchesFilters = (model, ignore = []) => {
// 分组
if (!ignore.includes('group') && filterGroup !== 'all') {
if (!model.enable_groups || !model.enable_groups.includes(filterGroup))
return false;
}
// 计费类型
if (!ignore.includes('quota') && filterQuotaType !== 'all') {
if (model.quota_type !== filterQuotaType) return false;
}
// 端点类型
if (!ignore.includes('endpoint') && filterEndpointType !== 'all') {
if (
!model.supported_endpoint_types ||
!model.supported_endpoint_types.includes(filterEndpointType)
)
return false;
}
// 供应商
if (!ignore.includes('vendor') && filterVendor !== 'all') {
if (filterVendor === 'unknown') {
if (model.vendor_name) return false;
} else if (model.vendor_name !== filterVendor) {
return false;
}
}
// 标签
if (!ignore.includes('tag') && filterTag !== 'all') {
const tagsArr = normalizeTags(model.tags);
if (!tagsArr.includes(filterTag.toLowerCase())) return false;
}
// 搜索
if (!ignore.includes('search') && searchValue) {
const term = searchValue.toLowerCase();
const tags = model.tags ? model.tags.toLowerCase() : '';
if (
!(
model.model_name.toLowerCase().includes(term) ||
(model.description &&
model.description.toLowerCase().includes(term)) ||
tags.includes(term) ||
(model.vendor_name && model.vendor_name.toLowerCase().includes(term))
)
)
return false;
}
return true;
};
// 生成不同视图所需的模型集合
const quotaTypeModels = useMemo(
() => allModels.filter((m) => matchesFilters(m, ['quota'])),
[
allModels,
filterGroup,
filterEndpointType,
filterVendor,
filterTag,
searchValue,
],
);
const endpointTypeModels = useMemo(
() => allModels.filter((m) => matchesFilters(m, ['endpoint'])),
[
allModels,
filterGroup,
filterQuotaType,
filterVendor,
filterTag,
searchValue,
],
);
const vendorModels = useMemo(
() => allModels.filter((m) => matchesFilters(m, ['vendor'])),
[
allModels,
filterGroup,
filterQuotaType,
filterEndpointType,
filterTag,
searchValue,
],
);
const tagModels = useMemo(
() => allModels.filter((m) => matchesFilters(m, ['tag'])),
[
allModels,
filterGroup,
filterQuotaType,
filterEndpointType,
filterVendor,
searchValue,
],
);
const groupCountModels = useMemo(
() => allModels.filter((m) => matchesFilters(m, ['group'])),
[
allModels,
filterQuotaType,
filterEndpointType,
filterVendor,
filterTag,
searchValue,
],
);
return {
quotaTypeModels,
endpointTypeModels,
vendorModels,
groupCountModels,
tagModels,
};
};
+75
View File
@@ -0,0 +1,75 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect } from 'react';
import { API, showError } from '../../helpers';
import { MODEL_CATEGORY_NAMES } from '../../constants';
/**
* 加载模型分类数据的 Hook
* @returns {Object} 分类数据和映射
*/
export const useModelCategories = () => {
const [categories, setCategories] = useState([]);
const [categoryNames, setCategoryNames] = useState({
...MODEL_CATEGORY_NAMES,
});
const [loading, setLoading] = useState(false);
// 加载分类数据
const loadCategories = async () => {
setLoading(true);
try {
const res = await API.get('/api/model_categories/flat');
const { success, data, message } = res.data;
if (success) {
const categoriesData = data || [];
setCategories(categoriesData);
// 构建 category_key -> category_name 的映射
const nameMap = { ...MODEL_CATEGORY_NAMES };
categoriesData.forEach((cat) => {
if (cat.category_key && cat.category_name) {
nameMap[cat.category_key] = cat.category_name;
}
});
setCategoryNames(nameMap);
} else {
showError(message || '加载分类失败');
}
} catch (error) {
console.error('Failed to load categories:', error);
// 失败时使用默认映射
} finally {
setLoading(false);
}
};
useEffect(() => {
loadCategories();
}, []);
return {
categories,
categoryNames,
loading,
refresh: loadCategories,
};
};
+262
View File
@@ -0,0 +1,262 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect, useCallback } from 'react';
import { API, showError } from '../../helpers';
import {
MODEL_CATEGORY,
inferModelCategory,
getModelsByCategory,
} from '../../constants/model-category.constant';
/**
* 模型选择Hook
* @param {string} category - 模型分类(可选,如果指定则只获取该分类的模型)
*/
export const useModelSelector = (category = null) => {
const [models, setModels] = useState([]);
const [filteredModels, setFilteredModels] = useState([]);
const [loading, setLoading] = useState(false);
const [selectedModel, setSelectedModel] = useState(null);
// 根据前端分类映射到后端 category 参数
const getCategoryParam = useCallback((frontendCategory) => {
if (!frontendCategory) return '';
// 图片相关分类
if (
[
MODEL_CATEGORY.IMAGE_GENERATION,
MODEL_CATEGORY.TEXT_TO_IMAGE,
MODEL_CATEGORY.IMAGE_TO_IMAGE,
].includes(frontendCategory)
) {
return 'image';
}
// 视频相关分类
if (
[
MODEL_CATEGORY.VIDEO_GENERATION,
MODEL_CATEGORY.TEXT_TO_VIDEO,
MODEL_CATEGORY.IMAGE_TO_VIDEO,
].includes(frontendCategory)
) {
return 'video';
}
// 默认返回空(使用文本模型配置)
return '';
}, []);
// 加载模型列表
const loadModels = useCallback(async () => {
setLoading(true);
try {
// 根据分类确定 category 参数
const categoryParam = getCategoryParam(category);
const categoryQuery = categoryParam ? `&category=${categoryParam}` : '';
// 并行获取模型列表和价格信息
// 使用 /api/user/models 接口,普通用户可访问
const [modelsRes, pricingRes] = await Promise.all([
API.get(`/api/user/models/?page_size=1000${categoryQuery}`),
// discount_scope=personal:体验中心/模型选择器的调用恒按个人等级计费,
// 企业 web 会话下若跟随会话作用域会把企业折扣价标给个人计费的调用
API.get('/api/pricing?discount_scope=personal').catch(() => ({
data: { success: true, data: [] },
})), // 如果pricing接口失败,使用空数组
]);
const { success, message, data } = modelsRes.data;
if (success) {
const allModels = data?.items || data || [];
// 等级锁态元数据(§6.2):后端已剔除 hidden,剩余仅 callable/visible;
// visible 表示「仅可见、不可调用」,前端展示锁态并禁止选中提交(最终仍以调用闸门为准)。
const levelStates = data?.level_states || {};
const pricingData = pricingRes.data?.data || [];
const groupRatioMap = pricingRes.data?.group_ratio || {};
// 模型级等级折扣修正系数(四期):{分组: {模型: 系数}},乘在分组倍率之上
const groupModelDiscountMap =
pricingRes.data?.group_model_discount || {};
// 当前登录用户分组(用于计算实际价格 = model_price * 分组倍率)
let userGroup = '';
try {
userGroup =
JSON.parse(localStorage.getItem('user') || '{}')?.group || '';
} catch {
userGroup = '';
}
const userGroupRatio =
typeof groupRatioMap[userGroup] === 'number'
? groupRatioMap[userGroup]
: 1;
// 创建pricing映射表,以模型名称为key
const pricingMap = {};
pricingData.forEach((pricing) => {
pricingMap[pricing.model_name] = pricing;
});
// 为每个模型推断分类(如果没有 categories 字段)并添加价格信息
const modelsWithCategory = allModels.map((model) => {
// 添加价格信息
const pricing = pricingMap[model.model_name] || {};
let modelWithCategory = { ...model };
// 如果后端返回了 categories 数组,直接使用
if (Array.isArray(model.categories) && model.categories.length > 0) {
modelWithCategory = model;
}
// 如果有 category 单个字段,转换为 categories 数组
else if (model.category) {
modelWithCategory = {
...model,
categories: [model.category],
};
}
// 否则通过模型名称推断分类
else {
const inferredCategory = inferModelCategory(
model.model_name,
model.endpoint_type,
);
modelWithCategory = {
...model,
categories: [inferredCategory],
};
}
// 合并价格信息(group_ratio 为当前用户所在分组的有效倍率,已含该模型的等级折扣修正)
return {
...modelWithCategory,
model_ratio: pricing.model_ratio,
model_price: pricing.model_price,
quota_type: pricing.quota_type,
completion_ratio: pricing.completion_ratio,
// 浮点乘积收敛 4 位小数,避免展示 0.7200000000000001 类脏数字
group_ratio: parseFloat(
(
userGroupRatio *
(groupModelDiscountMap?.[userGroup]?.[model.model_name] ?? 1)
).toFixed(4),
),
// callable(默认)/ visible(锁定,不可调用)
level_state: levelStates[model.model_name] || 'callable',
level_locked: levelStates[model.model_name] === 'visible',
};
});
setModels(modelsWithCategory);
// 如果指定了分类,进行筛选
if (category) {
const filtered = getModelsByCategory(modelsWithCategory, category);
setFilteredModels(filtered);
// 自动选择第一个「可调用」模型(避免默认选中锁定模型导致提交即 403)
if (filtered.length > 0) {
const firstCallable = filtered.find((m) => !m.level_locked);
setSelectedModel((prev) =>
prev && filtered.some((m) => m.id === prev.id && !m.level_locked)
? prev
: firstCallable || null,
);
} else {
setSelectedModel(null);
}
} else {
setFilteredModels(modelsWithCategory);
}
} else {
showError(message || '获取模型列表失败');
}
} catch (error) {
console.error('加载模型失败:', error);
showError('加载模型失败: ' + error.message);
} finally {
setLoading(false);
}
}, [category, getCategoryParam]);
// 切换模型分类
const filterByCategory = useCallback(
(newCategory) => {
if (newCategory) {
const filtered = getModelsByCategory(models, newCategory);
setFilteredModels(filtered);
// 自动选择第一个「可调用」模型
if (filtered.length > 0) {
setSelectedModel(filtered.find((m) => !m.level_locked) || null);
} else {
setSelectedModel(null);
}
} else {
setFilteredModels(models);
}
},
[models],
);
// 根据ID选择模型
const selectModelById = useCallback(
(modelId) => {
const model = filteredModels.find((m) => m.id === modelId);
if (model && !model.level_locked) {
setSelectedModel(model);
}
},
[filteredModels],
);
// 根据模型名称选择模型
const selectModelByName = useCallback(
(modelName) => {
const model = filteredModels.find((m) => m.model_name === modelName);
if (model && !model.level_locked) {
setSelectedModel(model);
}
},
[filteredModels],
);
// 初始加载和category变化时重新加载
useEffect(() => {
loadModels();
}, [loadModels]);
return {
// 数据
allModels: models,
models: filteredModels,
selectedModel,
loading,
// 操作方法
loadModels,
filterByCategory,
selectModelById,
selectModelByName,
setSelectedModel,
};
};
+534
View File
@@ -0,0 +1,534 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { API, showError, showSuccess } from '../../helpers';
import { ITEMS_PER_PAGE } from '../../constants';
import { useTableCompactMode } from '../common/useTableCompactMode';
export const useModelsData = () => {
const { t } = useTranslation();
const [compactMode, setCompactMode] = useTableCompactMode('models');
// State management
const [models, setModels] = useState([]);
const [loading, setLoading] = useState(true);
const [activePage, setActivePage] = useState(1);
const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
const [searching, setSearching] = useState(false);
const [modelCount, setModelCount] = useState(0);
// Modal states
const [showEdit, setShowEdit] = useState(false);
const [editingModel, setEditingModel] = useState({
id: undefined,
});
// Row selection
const [selectedKeys, setSelectedKeys] = useState([]);
const rowSelection = {
getCheckboxProps: (record) => ({
name: record.model_name,
}),
selectedRowKeys: selectedKeys.map((model) => model.id),
onChange: (selectedRowKeys, selectedRows) => {
setSelectedKeys(selectedRows);
},
};
// Form initial values
const formInitValues = {
searchKeyword: '',
searchVendor: '',
searchCategory: '',
};
// ---------- helpers ----------
// Safely extract array items from API payload
const extractItems = (payload) => {
const items = payload?.items || payload || [];
return Array.isArray(items) ? items : [];
};
// Form API reference
const [formApi, setFormApi] = useState(null);
// Get form values helper function
const getFormValues = () => formApi?.getValues() || formInitValues;
// Close edit modal
const closeEdit = () => {
setShowEdit(false);
setTimeout(() => {
setEditingModel({ id: undefined });
}, 500);
};
// Set model format with key field
const setModelFormat = (models) => {
for (let i = 0; i < models.length; i++) {
models[i].key = models[i].id;
}
setModels(models);
};
// Vendor list
const [vendors, setVendors] = useState([]);
const [vendorCounts, setVendorCounts] = useState({});
const [activeVendorKey, setActiveVendorKey] = useState('all');
const [showAddVendor, setShowAddVendor] = useState(false);
const [showEditVendor, setShowEditVendor] = useState(false);
const [editingVendor, setEditingVendor] = useState({ id: undefined });
const [syncing, setSyncing] = useState(false);
const [previewing, setPreviewing] = useState(false);
const vendorMap = useMemo(() => {
const map = {};
vendors.forEach((v) => {
map[v.id] = v;
});
return map;
}, [vendors]);
// Load vendor list
const loadVendors = async () => {
try {
const res = await API.get('/api/vendors/?page_size=1000');
if (res.data.success) {
const items = res.data.data.items || res.data.data || [];
setVendors(Array.isArray(items) ? items : []);
}
} catch (_) {
// ignore
}
};
// Load models data
const loadModels = async (
page = 1,
size = pageSize,
vendorKey = activeVendorKey,
) => {
setLoading(true);
try {
let url = `/api/models/?p=${page}&page_size=${size}`;
if (vendorKey && vendorKey !== 'all') {
// Filter by vendor ID
url = `/api/models/search?vendor=${vendorKey}&p=${page}&page_size=${size}`;
}
const res = await API.get(url);
const { success, message, data } = res.data;
if (success) {
const newPageData = extractItems(data);
setActivePage(data.page || page);
setModelCount(data.total || newPageData.length);
setModelFormat(newPageData);
if (data.vendor_counts) {
const sumAll = Object.values(data.vendor_counts).reduce(
(acc, v) => acc + v,
0,
);
setVendorCounts({ ...data.vendor_counts, all: sumAll });
}
} else {
showError(message);
setModels([]);
}
} catch (error) {
console.error(error);
showError(t('获取模型列表失败'));
setModels([]);
}
setLoading(false);
};
// Refresh data
const refresh = async (page = activePage) => {
await loadModels(page, pageSize);
};
// Sync upstream models/vendors for missing models only
const syncUpstream = async (opts = {}) => {
const locale = opts?.locale;
setSyncing(true);
try {
const body = {};
if (locale) body.locale = locale;
const res = await API.post('/api/models/sync_upstream', body);
const { success, message, data } = res.data || {};
if (success) {
const createdModels = data?.created_models || 0;
const createdVendors = data?.created_vendors || 0;
const skipped = (data?.skipped_models || []).length || 0;
showSuccess(
t(
'已同步:新增 {{createdModels}} 模型,新增 {{createdVendors}} 供应商,跳过 {{skipped}} 项',
{ createdModels, createdVendors, skipped },
),
);
await loadVendors();
await refresh();
} else {
showError(message || t('同步失败'));
}
} catch (e) {
showError(t('同步失败'));
}
setSyncing(false);
};
// Preview upstream differences
const previewUpstreamDiff = async (opts = {}) => {
const locale = opts?.locale;
setPreviewing(true);
try {
const url = `/api/models/sync_upstream/preview${locale ? `?locale=${locale}` : ''}`;
const res = await API.get(url);
const { success, message, data } = res.data || {};
if (success) {
return data || { missing: [], conflicts: [] };
}
showError(message || t('预览失败'));
return { missing: [], conflicts: [] };
} catch (e) {
showError(t('预览失败'));
return { missing: [], conflicts: [] };
} finally {
setPreviewing(false);
}
};
// Apply selected overwrite
const applyUpstreamOverwrite = async (payloadOrArray = []) => {
const isArray = Array.isArray(payloadOrArray);
const overwrite = isArray ? payloadOrArray : payloadOrArray.overwrite || [];
const locale = isArray ? undefined : payloadOrArray.locale;
setSyncing(true);
try {
const body = { overwrite };
if (locale) body.locale = locale;
const res = await API.post('/api/models/sync_upstream', body);
const { success, message, data } = res.data || {};
if (success) {
const createdModels = data?.created_models || 0;
const updatedModels = data?.updated_models || 0;
const createdVendors = data?.created_vendors || 0;
const skipped = (data?.skipped_models || []).length || 0;
showSuccess(
t(
'完成:新增 {{createdModels}} 模型,更新 {{updatedModels}} 模型,新增 {{createdVendors}} 供应商,跳过 {{skipped}} 项',
{ createdModels, updatedModels, createdVendors, skipped },
),
);
await loadVendors();
await refresh();
return true;
}
showError(message || t('同步失败'));
return false;
} catch (e) {
showError(t('同步失败'));
return false;
} finally {
setSyncing(false);
}
};
// Search models with keyword and vendor
const searchModels = async () => {
const {
searchKeyword = '',
searchVendor = '',
searchCategory = '',
} = getFormValues();
if (searchKeyword === '' && searchVendor === '' && searchCategory === '') {
// If all filters are blank, load models instead
await loadModels(1, pageSize);
return;
}
setSearching(true);
try {
const res = await API.get(
`/api/models/search?keyword=${searchKeyword}&vendor=${searchVendor}&category=${searchCategory}&p=1&page_size=${pageSize}`,
);
const { success, message, data } = res.data;
if (success) {
const newPageData = extractItems(data);
setActivePage(data.page || 1);
setModelCount(data.total || newPageData.length);
setModelFormat(newPageData);
if (data.vendor_counts) {
const sumAll = Object.values(data.vendor_counts).reduce(
(acc, v) => acc + v,
0,
);
setVendorCounts({ ...data.vendor_counts, all: sumAll });
}
} else {
showError(message);
setModels([]);
}
} catch (error) {
console.error(error);
showError(t('搜索模型失败'));
setModels([]);
}
setSearching(false);
};
// Manage model (enable/disable/delete)
const manageModel = async (id, action, record) => {
let res;
switch (action) {
case 'delete':
res = await API.delete(`/api/models/${id}`);
break;
case 'enable':
res = await API.put('/api/models/?status_only=true', { id, status: 1 });
break;
case 'disable':
res = await API.put('/api/models/?status_only=true', { id, status: 0 });
break;
default:
return;
}
const { success, message } = res.data;
if (success) {
showSuccess(t('操作成功完成!'));
if (action === 'delete') {
await refresh();
} else {
// Update local state for enable/disable
setModels((prevModels) =>
prevModels.map((model) =>
model.id === id
? { ...model, status: action === 'enable' ? 1 : 0 }
: model,
),
);
}
} else {
showError(message);
}
};
// Handle page change
const handlePageChange = (page) => {
setActivePage(page);
loadModels(page, pageSize, activeVendorKey);
};
// Reload models when activeVendorKey changes
useEffect(() => {
loadModels(1, pageSize, activeVendorKey);
}, [activeVendorKey]);
// Handle page size change
const handlePageSizeChange = async (size) => {
setPageSize(size);
setActivePage(1);
await loadModels(1, size, activeVendorKey);
};
// Handle row click and styling
const handleRow = (record, index) => {
const rowStyle =
record.status !== 1
? {
style: {
background: 'var(--semi-color-disabled-border)',
},
}
: {};
return {
...rowStyle,
onClick: (event) => {
// Don't trigger row selection when clicking on buttons
if (event.target.closest('button, .semi-button')) {
return;
}
const newSelectedKeys = selectedKeys.some(
(item) => item.id === record.id,
)
? selectedKeys.filter((item) => item.id !== record.id)
: [...selectedKeys, record];
setSelectedKeys(newSelectedKeys);
},
};
};
// Batch delete models
const batchDeleteModels = async () => {
if (selectedKeys.length === 0) {
showError(t('请至少选择一个模型'));
return;
}
try {
const deletePromises = selectedKeys.map((model) =>
API.delete(`/api/models/${model.id}`),
);
const results = await Promise.all(deletePromises);
let successCount = 0;
results.forEach((res, index) => {
if (res.data.success) {
successCount++;
} else {
showError(`删除模型 ${selectedKeys[index].model_name} 失败: ${res.data.message}`,
);
}
});
if (successCount > 0) {
showSuccess(t('成功删除 {{successCount}} 个模型', { successCount }));
setSelectedKeys([]);
await refresh();
}
} catch (error) {
showError(t('批量删除失败'));
}
};
// Batch update model categories
const batchUpdateCategory = async (categories) => {
if (selectedKeys.length === 0) {
showError(t('请至少选择一个模型'));
return;
}
try {
const ids = selectedKeys.map((model) => model.id);
const res = await API.put('/api/models/batch-category', {
ids,
categories,
});
const { success, message, data } = res.data;
if (success) {
showSuccess(
t('成功更新 {{updated}} 个模型的分类', { updated: data.updated }),
);
setSelectedKeys([]);
await refresh();
} else {
showError(message || t('批量更新分类失败'));
}
} catch (error) {
console.error('Batch update category failed:', error);
showError(t('批量更新分类失败'));
}
};
// Copy text helper
const copyText = async (text) => {
try {
await navigator.clipboard.writeText(text);
showSuccess(t('复制成功'));
} catch (error) {
console.error('Copy failed:', error);
showError(t('复制失败'));
}
};
// Initial load
useEffect(() => {
(async () => {
await loadVendors();
})();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return {
// Data state
models,
loading,
searching,
activePage,
pageSize,
modelCount,
// Selection state
selectedKeys,
rowSelection,
handleRow,
setSelectedKeys,
// Modal state
showEdit,
editingModel,
setEditingModel,
setShowEdit,
closeEdit,
// Form state
formInitValues,
setFormApi,
// Actions
loadModels,
searchModels,
refresh,
manageModel,
batchDeleteModels,
batchUpdateCategory,
copyText,
// Pagination
setActivePage,
handlePageChange,
handlePageSizeChange,
// UI state
compactMode,
setCompactMode,
// Vendor data
vendors,
vendorMap,
vendorCounts,
activeVendorKey,
setActiveVendorKey,
showAddVendor,
setShowAddVendor,
showEditVendor,
setShowEditVendor,
editingVendor,
setEditingVendor,
loadVendors,
// Translation
t,
// Upstream sync
syncing,
previewing,
syncUpstream,
previewUpstreamDiff,
applyUpstreamOverwrite,
};
};
+483
View File
@@ -0,0 +1,483 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useCallback, useEffect, useRef } from 'react';
import { API } from '../../helpers/api';
import { showError } from '../../helpers';
// 获取企业X-Org-Id header
const getOrgHeaders = (orgId) => ({
'X-Org-Id': String(orgId),
});
// 获取企业仪表盘
export function useOrgDashboard(orgId) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const seqRef = useRef(0);
const orgRef = useRef(orgId);
orgRef.current = orgId;
useEffect(() => {
seqRef.current += 1;
setData(null);
setLoading(false);
}, [orgId]);
const fetch = useCallback(async () => {
if (!orgId) return;
const requestOrgId = orgId;
const seq = ++seqRef.current;
setLoading(true);
try {
const res = await API.get('/api/org/dashboard', {
headers: getOrgHeaders(requestOrgId),
});
if (
seq === seqRef.current &&
requestOrgId === orgRef.current &&
res.data.success
) {
setData(res.data.data);
}
} catch (err) {
if (seq === seqRef.current && requestOrgId === orgRef.current)
showError(err.message);
} finally {
if (seq === seqRef.current && requestOrgId === orgRef.current)
setLoading(false);
}
}, [orgId]);
return { data, loading, fetch };
}
// 获取企业额度
export function useOrgQuota(orgId) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const seqRef = useRef(0);
const orgRef = useRef(orgId);
orgRef.current = orgId;
useEffect(() => {
seqRef.current += 1;
setData(null);
setLoading(false);
}, [orgId]);
const fetch = useCallback(
async (memberPage = 1, memberPageSize = 10) => {
if (!orgId) return;
const seq = ++seqRef.current;
const requestOrgId = orgId;
setLoading(true);
try {
const res = await API.get('/api/org/quota', {
headers: getOrgHeaders(requestOrgId),
params: {
member_page: memberPage,
member_page_size: memberPageSize,
},
});
if (
seq === seqRef.current &&
requestOrgId === orgRef.current &&
res.data.success
) {
setData(res.data.data);
}
} catch (err) {
if (seq === seqRef.current && requestOrgId === orgRef.current)
showError(err.message);
} finally {
if (seq === seqRef.current && requestOrgId === orgRef.current)
setLoading(false);
}
},
[orgId],
);
return { data, loading, fetch };
}
// 获取企业审计日志
export function useOrgAuditLogs(orgId) {
const [logs, setLogs] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const seqRef = useRef(0);
const orgRef = useRef(orgId);
orgRef.current = orgId;
useEffect(() => {
seqRef.current += 1;
setLogs([]);
setTotal(0);
setLoading(false);
}, [orgId]);
const fetch = useCallback(
async (page = 1, pageSize = 20, action = '') => {
if (!orgId) return;
const requestOrgId = orgId;
const seq = ++seqRef.current;
setLoading(true);
try {
const res = await API.get('/api/org/audit', {
headers: getOrgHeaders(requestOrgId),
params: { p: page, page_size: pageSize, action },
});
if (
seq === seqRef.current &&
requestOrgId === orgRef.current &&
res.data.success
) {
setLogs(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
}
} catch (err) {
if (seq === seqRef.current && requestOrgId === orgRef.current)
showError(err.message);
} finally {
if (seq === seqRef.current && requestOrgId === orgRef.current)
setLoading(false);
}
},
[orgId],
);
return { logs, total, loading, fetch };
}
// 获取企业提示词记录(方案 §35 一期):数据来自企业自行配置的数据库。
// 连接失败时后端返回业务错误,error 状态供页面提示管理员去企业设置检查配置。
export function useOrgPromptRecords(orgId) {
const [records, setRecords] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
// 请求代次:切企业/翻页会触发并发请求,晚到的过期响应不得覆盖最新结果
const seqRef = useRef(0);
useEffect(() => {
// 企业切换时立即作废在途请求并清空旧租户数据,避免新请求返回前短暂展示旧记录。
seqRef.current += 1;
setRecords([]);
setTotal(0);
setError('');
setLoading(false);
}, [orgId]);
const fetch = useCallback(
async (
page = 1,
pageSize = 20,
{ memberId, modelName, keyword, startTimestamp, endTimestamp } = {},
) => {
if (!orgId) return;
const seq = ++seqRef.current;
setLoading(true);
setError('');
try {
const params = { p: page, page_size: pageSize };
if (memberId) params.member_id = memberId;
if (modelName) params.model_name = modelName;
if (keyword) params.keyword = keyword;
if (startTimestamp) params.start_timestamp = startTimestamp;
if (endTimestamp) params.end_timestamp = endTimestamp;
const res = await API.get('/api/org/prompt-archive/records', {
headers: getOrgHeaders(orgId),
params,
});
if (seq !== seqRef.current) return;
if (res.data.success) {
setRecords(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
} else {
setRecords([]);
setTotal(0);
setError(res.data.message || '查询失败');
}
} catch (err) {
if (seq !== seqRef.current) return;
setRecords([]);
setTotal(0);
setError(err.message);
} finally {
if (seq === seqRef.current) {
setLoading(false);
}
}
},
[orgId],
);
return { records, total, loading, error, fetch };
}
// 获取企业成员消耗日志
export function useOrgMemberLogs(orgId) {
const [logs, setLogs] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const fetch = useCallback(
async (
page = 1,
pageSize = 20,
{ userId, startTimestamp, endTimestamp, modelName } = {},
) => {
if (!orgId) return;
setLoading(true);
try {
const params = { p: page, page_size: pageSize };
if (userId) params.user_id = userId;
if (startTimestamp) params.start_timestamp = startTimestamp;
if (endTimestamp) params.end_timestamp = endTimestamp;
if (modelName) params.model_name = modelName;
const res = await API.get('/api/org/logs', {
headers: getOrgHeaders(orgId),
params,
});
if (res.data.success) {
setLogs(res.data.data?.items || []);
// 后端在翻页(page>1)时跳过 COUNT 并返回 total=-1,此处保留首页已知总数,避免分页器异常
const nextTotal = res.data.data?.total;
if (typeof nextTotal === 'number' && nextTotal >= 0) {
setTotal(nextTotal);
}
} else {
setLogs([]);
setTotal(0);
showError(res.data.message || '加载消耗明细失败');
}
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
},
[orgId],
);
return { logs, total, loading, fetch };
}
// 获取企业成员消耗汇总统计
export function useOrgLogsStat(orgId) {
const [stat, setStat] = useState({
quota: 0,
rpm: 0,
tpm: 0,
has_time_range: false,
});
const [loading, setLoading] = useState(false);
const fetch = useCallback(
async (
{ userId, startTimestamp, endTimestamp, modelName } = {},
noCache = false,
) => {
if (!orgId) return;
setLoading(true);
try {
const params = {};
if (userId) params.user_id = userId;
if (startTimestamp) params.start_timestamp = startTimestamp;
if (endTimestamp) params.end_timestamp = endTimestamp;
if (modelName) params.model_name = modelName;
if (noCache) params.nocache = 1;
const res = await API.get('/api/org/logs/stat', {
headers: getOrgHeaders(orgId),
params,
});
if (res.data.success) {
setStat(
res.data.data || {
quota: 0,
rpm: 0,
tpm: 0,
has_time_range: false,
},
);
} else {
setStat({
quota: 0,
rpm: 0,
tpm: 0,
has_time_range: false,
});
showError(res.data.message || '加载消耗统计失败');
}
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
},
[orgId],
);
return { stat, loading, fetch };
}
// 获取企业成员消耗排行榜
export function useOrgMemberRanking(orgId) {
const [ranking, setRanking] = useState([]);
const [loading, setLoading] = useState(false);
const fetch = useCallback(
async (
{ userId, startTimestamp, endTimestamp, modelName, limit } = {},
noCache = false,
) => {
if (!orgId) return;
setLoading(true);
try {
const params = {};
if (userId) params.user_id = userId;
if (startTimestamp) params.start_timestamp = startTimestamp;
if (endTimestamp) params.end_timestamp = endTimestamp;
if (modelName) params.model_name = modelName;
if (limit) params.limit = limit;
if (noCache) params.nocache = 1;
const res = await API.get('/api/org/logs/ranking', {
headers: getOrgHeaders(orgId),
params,
});
if (res.data.success) {
setRanking(res.data.data || []);
} else {
setRanking([]);
showError(res.data.message || '加载成员排行失败');
}
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
},
[orgId],
);
return { ranking, loading, fetch };
}
// 获取企业Token列表
export function useOrgTokens(orgId) {
const [tokens, setTokens] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const fetch = useCallback(
async (page = 1, pageSize = 20) => {
if (!orgId) return;
setLoading(true);
try {
const res = await API.get('/api/org/tokens', {
headers: getOrgHeaders(orgId),
params: { p: page, page_size: pageSize },
});
if (res.data.success) {
setTokens(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
}
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
},
[orgId],
);
const createToken = useCallback(
async (data) => {
if (!orgId) return null;
try {
const res = await API.post('/api/org/tokens', data, {
headers: getOrgHeaders(orgId),
});
if (res.data.success) {
return res.data.data;
}
showError(res.data.message);
return null;
} catch (err) {
showError(err.message);
return null;
}
},
[orgId],
);
const updateToken = useCallback(
async (tokenId, data) => {
if (!orgId) return false;
try {
const res = await API.put(`/api/org/tokens/${tokenId}`, data, {
headers: getOrgHeaders(orgId),
});
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[orgId],
);
const deleteToken = useCallback(
async (tokenId) => {
if (!orgId) return false;
try {
const res = await API.delete(`/api/org/tokens/${tokenId}`, {
headers: getOrgHeaders(orgId),
});
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[orgId],
);
return {
tokens,
total,
loading,
fetch,
createToken,
updateToken,
deleteToken,
};
}
+254
View File
@@ -0,0 +1,254 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useCallback } from 'react';
import { API } from '../../helpers/api';
import { showError } from '../../helpers';
const getOrgHeaders = (orgId) => ({
'X-Org-Id': String(orgId),
});
export function useOrgMembers(orgId) {
const [members, setMembers] = useState([]);
const [total, setTotal] = useState(0);
const [loading, setLoading] = useState(false);
const fetch = useCallback(
async (page = 1, pageSize = 20) => {
if (!orgId) return;
setLoading(true);
try {
const res = await API.get('/api/org/members', {
headers: getOrgHeaders(orgId),
params: { p: page, page_size: pageSize },
});
if (res.data.success) {
setMembers(res.data.data?.items || []);
setTotal(res.data.data?.total || 0);
}
} catch (err) {
showError(err.message);
} finally {
setLoading(false);
}
},
[orgId],
);
const removeMember = useCallback(
async (memberId) => {
if (!orgId) return false;
try {
const res = await API.delete(`/api/org/members/${memberId}`, {
headers: getOrgHeaders(orgId),
});
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[orgId],
);
const updateMemberRole = useCallback(
async (memberId, role) => {
if (!orgId) return false;
try {
const res = await API.put(
`/api/org/members/${memberId}/role`,
{ role },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[orgId],
);
const updateMemberQuota = useCallback(
async (memberId, quotaLimit, quotaPeriod = 'none') => {
if (!orgId) return false;
try {
const res = await API.put(
`/api/org/members/${memberId}/quota`,
{ quota_limit: quotaLimit, quota_period: quotaPeriod },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[orgId],
);
const updateMemberStatus = useCallback(
async (memberId, status) => {
if (!orgId) return false;
try {
const res = await API.put(
`/api/org/members/${memberId}/status`,
{ status },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[orgId],
);
const updateMemberModelLimits = useCallback(
async (memberId, modelLimitsEnabled, modelLimits) => {
if (!orgId) return false;
try {
const res = await API.put(
`/api/org/members/${memberId}/models`,
{
model_limits_enabled: modelLimitsEnabled,
model_limits: modelLimits,
},
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[orgId],
);
const updateMemberGroups = useCallback(
async (memberId, groups) => {
if (!orgId) return false;
try {
const res = await API.put(
`/api/org/members/${memberId}/groups`,
{ groups },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[orgId],
);
// 更新管理员细粒度权限(owner-only)。permissions 为 {key: bool} 对象。
const updateMemberAdminPermissions = useCallback(
async (memberId, permissions) => {
if (!orgId) return false;
try {
const res = await API.put(
`/api/org/members/${memberId}/admin-permissions`,
{ permissions },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[orgId],
);
const updateMemberRemark = useCallback(
async (memberId, remark) => {
if (!orgId) return false;
try {
const res = await API.put(
`/api/org/members/${memberId}/remark`,
{ remark },
{ headers: getOrgHeaders(orgId) },
);
if (res.data.success) {
return true;
}
showError(res.data.message);
return false;
} catch (err) {
showError(err.message);
return false;
}
},
[orgId],
);
// 乐观更新:直接修改本地列表中某成员的字段,无需重新请求
const updateMemberInList = useCallback((memberId, updates) => {
setMembers((prev) =>
prev.map((m) => (m.id === memberId ? { ...m, ...updates } : m)),
);
}, []);
return {
members,
total,
loading,
fetch,
removeMember,
updateMemberRole,
updateMemberQuota,
updateMemberModelLimits,
updateMemberGroups,
updateMemberStatus,
updateMemberRemark,
updateMemberAdminPermissions,
updateMemberInList,
};
}
+82
View File
@@ -0,0 +1,82 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
export const shouldRequireExplicitSession = ({
sessionEnabled = false,
activeSessionId = null,
} = {}) => Boolean(sessionEnabled && !activeSessionId);
export const shouldCreateDefaultSession = (sessions) =>
Array.isArray(sessions) && sessions.length === 0;
export const prependCreatedSession = (sessions = [], createdSession) => {
if (!createdSession?.id) {
return Array.isArray(sessions) ? [...sessions] : [];
}
const list = Array.isArray(sessions) ? sessions : [];
return [
createdSession,
...list.filter((session) => session.id !== createdSession.id),
];
};
export const removeSessionAndResolveNext = ({
sessions = [],
deletedSessionId = null,
activeSessionId = null,
} = {}) => {
const list = Array.isArray(sessions) ? sessions : [];
const remainingSessions = list.filter(
(session) => session.id !== deletedSessionId,
);
const deletedActiveSession = deletedSessionId === activeSessionId;
return {
remainingSessions,
deletedActiveSession,
nextActiveSessionId: deletedActiveSession
? (remainingSessions[0]?.id ?? null)
: activeSessionId,
};
};
export const bindConversationIdToPayload = (
payload,
{ sessionEnabled = false, activeSessionId = null, force = false } = {},
) => {
if (
!sessionEnabled ||
!activeSessionId ||
!payload ||
typeof payload !== 'object' ||
Array.isArray(payload)
) {
return payload;
}
if (!force && payload.conversation_id != null) {
return payload;
}
return {
...payload,
conversation_id: activeSessionId,
};
};
+126
View File
@@ -0,0 +1,126 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import test from 'node:test';
import assert from 'node:assert/strict';
import {
bindConversationIdToPayload,
prependCreatedSession,
removeSessionAndResolveNext,
shouldCreateDefaultSession,
shouldRequireExplicitSession,
} from './sessionFlow.js';
test('shouldRequireExplicitSession blocks sends only when session mode is enabled without a selection', () => {
assert.equal(
shouldRequireExplicitSession({
sessionEnabled: true,
activeSessionId: null,
}),
true,
);
assert.equal(
shouldRequireExplicitSession({ sessionEnabled: true, activeSessionId: 42 }),
false,
);
assert.equal(
shouldRequireExplicitSession({
sessionEnabled: false,
activeSessionId: null,
}),
false,
);
});
test('shouldCreateDefaultSession only creates after a successful empty list response', () => {
assert.equal(shouldCreateDefaultSession([]), true);
assert.equal(shouldCreateDefaultSession([{ id: 1 }]), false);
assert.equal(shouldCreateDefaultSession(null), false);
assert.equal(shouldCreateDefaultSession(undefined), false);
});
test('prependCreatedSession keeps the new session at the top without duplicates', () => {
const created = { id: 3, title: 'New' };
const sessions = [
{ id: 1, title: 'First' },
{ id: 3, title: 'Stale copy' },
{ id: 2, title: 'Second' },
];
assert.deepEqual(prependCreatedSession(sessions, created), [
{ id: 3, title: 'New' },
{ id: 1, title: 'First' },
{ id: 2, title: 'Second' },
]);
});
test('removeSessionAndResolveNext clears the active selection instead of creating a replacement session', () => {
const result = removeSessionAndResolveNext({
sessions: [{ id: 9, title: 'Only one' }],
deletedSessionId: 9,
activeSessionId: 9,
});
assert.deepEqual(result.remainingSessions, []);
assert.equal(result.deletedActiveSession, true);
assert.equal(result.nextActiveSessionId, null);
});
test('removeSessionAndResolveNext switches to the first remaining session after deleting the active one', () => {
const result = removeSessionAndResolveNext({
sessions: [
{ id: 4, title: 'Active' },
{ id: 5, title: 'Next' },
{ id: 6, title: 'Later' },
],
deletedSessionId: 4,
activeSessionId: 4,
});
assert.deepEqual(result.remainingSessions, [
{ id: 5, title: 'Next' },
{ id: 6, title: 'Later' },
]);
assert.equal(result.nextActiveSessionId, 5);
});
test('bindConversationIdToPayload always follows the active session in explicit-session mode when forced', () => {
const payload = bindConversationIdToPayload(
{ stream: true, conversation_id: 7 },
{ sessionEnabled: true, activeSessionId: 12, force: true },
);
assert.deepEqual(payload, {
stream: true,
conversation_id: 12,
});
});
test('bindConversationIdToPayload preserves an existing conversation_id when force is not requested', () => {
const payload = bindConversationIdToPayload(
{ stream: true, conversation_id: 7 },
{ sessionEnabled: true, activeSessionId: 12 },
);
assert.deepEqual(payload, {
stream: true,
conversation_id: 7,
});
});
File diff suppressed because it is too large Load Diff
+136
View File
@@ -0,0 +1,136 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback, useEffect, useRef, useState } from 'react';
/**
* useChatScroll —— 在 wrapper 内查找 Semi Chat 的滚动容器,跟踪是否在底部。
*
* 为什么不用 ScrollableContainer?
* Semi Chat 自带的滚动容器是组件内部 DOM,我们没法把它包到 ScrollableContainer 里。
* 只能拿外层 wrapperRef,向下 querySelector 找到那个 scrollable 的 inner 元素,再挂监听。
*
* 返回:
* isAtBottom (boolean) — 用户当前是否贴在底部(含 80px 容差,避免抖动)
* scrollToBottom() — 平滑滚到底部
*/
const NEAR_BOTTOM_PX = 80;
const findScrollable = (rootEl) => {
if (!rootEl) return null;
try {
const direct = rootEl.querySelector('[class*="semi-chat-container"]');
if (direct && direct.scrollHeight > direct.clientHeight) return direct;
if (direct) {
const inner = Array.from(direct.querySelectorAll('*')).find((el) => {
const cs = window.getComputedStyle(el);
return (
(cs.overflowY === 'auto' || cs.overflowY === 'scroll') &&
el.scrollHeight > el.clientHeight
);
});
if (inner) return inner;
}
} catch (_) {
// ignore
}
return null;
};
export const useChatScroll = (wrapperRef, deps = []) => {
const [isAtBottom, setIsAtBottom] = useState(true);
const containerRef = useRef(null);
const observerRef = useRef(null);
// 缓存当前的 deps 字符串,方便重定位 scroll 容器 / 重检 isAtBottom
const depsKey = deps
.map((d) => (typeof d === 'object' ? '' : String(d)))
.join('|');
const checkPosition = useCallback(() => {
const el = containerRef.current;
if (!el) return;
const fromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
setIsAtBottom(fromBottom <= NEAR_BOTTOM_PX);
}, []);
// 找滚动容器 + 装监听;容器可能在 mount 后才出现(Semi Chat 异步渲染),用 MutationObserver 兜底
useEffect(() => {
const root = wrapperRef.current;
if (!root) return undefined;
const attach = () => {
const el = findScrollable(root);
if (!el || el === containerRef.current) return;
// 旧的卸载
if (containerRef.current) {
containerRef.current.removeEventListener('scroll', checkPosition);
}
containerRef.current = el;
el.addEventListener('scroll', checkPosition, { passive: true });
checkPosition();
};
attach();
if (!observerRef.current) {
observerRef.current = new MutationObserver(() => {
// Chat 组件改 DOM 时只尝试重附加 listener;不在这里调 checkPosition ——
// 流式响应下子树每秒会有几十次 mutation,每次都读 scrollHeight/scrollTop
// 会触发 layout reflow,慢设备明显卡。scroll 事件 + deps 变化的 effect
// 已经足以维护 isAtBottom 的正确性。
attach();
});
observerRef.current.observe(root, { childList: true, subtree: true });
}
return () => {
if (containerRef.current) {
containerRef.current.removeEventListener('scroll', checkPosition);
}
if (observerRef.current) {
observerRef.current.disconnect();
observerRef.current = null;
}
containerRef.current = null;
};
// wrapperRef 是 ref,不放进 deps;其它依赖通过 depsKey 收敛
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [depsKey]);
// deps 改变时(消息列表变了/会话切了)也重测位置
useEffect(() => {
// 等下一帧,让 Chat 把新内容渲染完再判断
const id = requestAnimationFrame(checkPosition);
return () => cancelAnimationFrame(id);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [depsKey]);
const scrollToBottom = useCallback(
(opts = { behavior: 'smooth' }) => {
const el = containerRef.current || findScrollable(wrapperRef.current);
if (!el) return;
el.scrollTo({ top: el.scrollHeight, ...opts });
},
[wrapperRef],
);
return { isAtBottom, scrollToBottom };
};
export default useChatScroll;
@@ -0,0 +1,251 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// 体验中心长会话自动摘要:未摘要区间累积超过阈值时,把较早的对话压缩成一段摘要。
//
// 关键设计:
// - 【后台触发、不阻塞发送】:maybeSummarize 是 fire-and-forget,不增加用户发送消息的延迟。
// - 【锚点切片】:按 summarizedUpToMessageId 锚点之后的位置切片,assistant 消息没有
// backendId 也能随相邻 user 消息一起进入摘要范围(直播会话里 assistant 消息无 backendId)。
// - 摘要请求是普通 POST /pg/chat/completions,但【不带 source、不带 conversation_id】,
// 因此后端计费(用户为摘要付费,符合预期)但【不落库为对话轮次】。摘要复用当前对话模型。
// - 失败/超时一律不抛错、不打断用户;会话切换后只跳过内存 setState,PUT 仍写回原会话。
import { useCallback } from 'react';
import { Toast } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { API_ENDPOINTS } from '../../constants/playground.constants';
import {
getUserIdFromLocalStorage,
getExperienceCenterPositiveInt,
countRounds,
getMessagesAfterAnchor,
getMessagesBeforeWindow,
buildSummaryInstructionMessages,
} from '../../helpers';
import { getServerURL } from '../../helpers/config';
import { updateConversationSummary } from '../../services/playgroundConversation';
// 摘要请求超时,避免后台摘要请求长时间挂起
const SUMMARY_TIMEOUT_MS = 60 * 1000;
// 摘要输出的 max_tokens,摘要本身有界,显式带上让后端预扣费更准
const SUMMARY_MAX_TOKENS = 1024;
export const useConversationSummary = ({
appStatus,
apiInputs,
activeSessionId,
activeSessionIdRef,
sessionEnabled,
conversationSummary,
setConversationSummary,
summarizedUpToMessageId,
setSummarizedUpToMessageId,
summarizingRef,
summaryGenRef,
}) => {
const { t } = useTranslation();
/**
* 后台按需触发一次摘要(fire-and-forget,调用方不应 await)。
* @param {Array} currentMessages 当前完整消息数组(含刚加入、还没 backendId 的新 user 消息)
* @param {{force?: boolean}} options force=true 时绕过阈值/轮数检查,立刻对窗口外的全部历史做一次摘要;
* 用于用户在 UI 上点「重新生成摘要」时手动触发。
*/
const maybeSummarize = useCallback(
async (currentMessages, options = {}) => {
const { force = false } = options;
const threshold = getExperienceCenterPositiveInt(
appStatus,
'experience_center_summary_threshold',
'experience_center_summary_threshold',
0,
);
const maxRounds = getExperienceCenterPositiveInt(
appStatus,
'experience_center_max_history_rounds',
'experience_center_max_history_rounds',
0,
);
if (!force) {
// 摘要关闭,或阈值不大于保留轮数(误配,摘要会覆盖窗口内消息)→ 不触发
if (threshold <= 0 || threshold <= maxRounds) return;
}
// 非会话模式没有持久化载体,跳过
if (!sessionEnabled || !activeSessionId) return;
// 已有摘要任务在跑,避免并发重复摘要。
// force=true(用户手动点「重新生成」)时给一个 Toast 反馈,避免点了没反应。
if (summarizingRef.current) {
if (force) {
Toast.info({
content: t('上一次摘要任务还在进行中,请稍后再试'),
duration: 2,
});
}
return;
}
// 锚点之后的「未摘要区间」;累积轮数还没到阈值就不触发(批量摘要,不是每条都摘)。
// force=true 时锚点统一从 0 开始,覆盖完整历史,等价于「重新生成摘要」。
const anchor = force ? 0 : summarizedUpToMessageId;
const tail = getMessagesAfterAnchor(currentMessages, anchor);
if (!force && countRounds(tail) <= threshold) return;
if (force && countRounds(tail) === 0) return;
// 未摘要区间里、留出最近 maxRounds 轮之外的部分 = 本次要摘要的内容。
// 至少保留 1 轮不摘要(兜底 maxRounds=0 的退化配置,否则会把刚发的内容也摘掉)。
const toSummarize = getMessagesBeforeWindow(tail, Math.max(maxRounds, 1));
if (toSummarize.length === 0) return;
// newUpTo = toSummarize 里最后一条带 backendId 的 user 消息(user 消息一定有 backendId)。
// force=true 时基线取 0(重新生成 → 锚点应推进到 toSummarize 末尾,不和旧值比较)。
const baseline = force ? 0 : summarizedUpToMessageId || 0;
let newUpTo = baseline;
for (const m of toSummarize) {
if (m && m.role === 'user' && m.backendId && m.backendId > newUpTo) {
newUpTo = m.backendId;
}
}
if (newUpTo <= baseline) return;
summarizingRef.current = true;
const sessionIdAtStart = activeSessionId;
// 快照 generation:commit 前再次比对,若已变(清空 / 失效)则丢弃本次结果,
// 避免「用户清了摘要,几秒后旧 fetch 回来又把摘要写回」
const genAtStart = summaryGenRef?.current ?? 0;
const controller = new AbortController();
const timer = setTimeout(() => {
try {
controller.abort();
} catch (_) {
/* ignore */
}
}, SUMMARY_TIMEOUT_MS);
try {
// 透明计费提示:明确告知用户这是一次会计费的模型调用
Toast.info({
content: force
? t('正在重新生成对话摘要(一次模型调用,会产生计费)')
: t('正在后台压缩较早的对话以降低后续消耗(一次模型调用)'),
duration: 2,
});
const body = {
model: apiInputs?.model,
group: apiInputs?.group,
stream: false,
max_tokens: SUMMARY_MAX_TOKENS,
// 故意不带 source / conversation_id:计费但不落库为对话轮次。
// force=true 时不携带旧摘要,让模型基于全量历史生成全新摘要(用户重新生成的语义)。
messages: buildSummaryInstructionMessages(
toSummarize,
force ? '' : conversationSummary,
),
};
const response = await fetch(API_ENDPOINTS.CHAT_COMPLETIONS, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'New-Api-User': getUserIdFromLocalStorage(),
},
credentials: getServerURL() ? 'include' : 'same-origin',
body: JSON.stringify(body),
signal: controller.signal,
});
if (!response.ok) {
console.warn('Conversation summary request failed:', response.status);
// force 模式是用户主动触发,必须给可见反馈
if (force) {
Toast.error({
content: t('重新生成摘要失败:上游返回 {{status}}', {
status: response.status,
}),
duration: 3,
});
}
return;
}
const data = await response.json();
const newSummary = data?.choices?.[0]?.message?.content;
if (!newSummary || typeof newSummary !== 'string') {
console.warn('Conversation summary returned empty content');
if (force) {
Toast.error({
content: t('重新生成摘要失败:模型返回空内容'),
duration: 3,
});
}
return;
}
// 落库 / setState 前再次校对 generation;若期间有 clear / invalidate 操作发生,
// 丢弃本次结果,避免覆盖用户的「清空」动作。
if (summaryGenRef && (summaryGenRef.current ?? 0) !== genAtStart) {
return;
}
// 写回后端持久化:用启动时捕获的会话 ID,确保写到被摘要的那个会话
updateConversationSummary(sessionIdAtStart, newSummary, newUpTo).catch(
(e) => console.warn('Persist conversation summary failed:', e),
);
// 仅当用户仍停留在该会话时才更新内存状态,避免污染切换后的其它会话
if (activeSessionIdRef?.current === sessionIdAtStart) {
setConversationSummary(newSummary);
setSummarizedUpToMessageId(newUpTo);
}
} catch (e) {
if (e?.name !== 'AbortError') {
console.warn('Conversation summary error:', e);
if (force) {
Toast.error({
content: t('重新生成摘要失败:{{msg}}', {
msg: e?.message || String(e),
}),
duration: 3,
});
}
} else if (force) {
Toast.warning({
content: t('重新生成摘要超时,请稍后重试'),
duration: 3,
});
}
} finally {
clearTimeout(timer);
summarizingRef.current = false;
}
},
[
appStatus,
apiInputs,
activeSessionId,
activeSessionIdRef,
sessionEnabled,
conversationSummary,
setConversationSummary,
summarizedUpToMessageId,
setSummarizedUpToMessageId,
summarizingRef,
summaryGenRef,
t,
],
);
return { maybeSummarize };
};
+241
View File
@@ -0,0 +1,241 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback, useContext, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import {
API,
getExperienceCenterBool,
getExperienceCenterValue,
processModelsData,
processGroupsData,
showError,
} from '../../helpers';
import { API_ENDPOINTS } from '../../constants/playground.constants';
import { StatusContext } from '../../context/Status';
export const useDataLoader = (
userState,
inputs,
handleInputChange,
setModels,
setGroups,
isExperienceMode = false,
) => {
const { t } = useTranslation();
const [statusState] = useContext(StatusContext);
const status = statusState?.status;
const inputsGroupRef = useRef(inputs.group);
// model 也走 ref:loadModels 只在"读当前选中模型"时需要它,若直接依赖 inputs.model,
// 每次用户切换模型都会让 loadModels 换新引用 → 触发下面的 effect 重新拉一遍模型列表
//(纯浪费的网络请求,还可能在响应乱序时闪一下选中态)
const inputsModelRef = useRef(inputs.model);
// 防止 loadGroups 因 status 变化被反复触发时,"白名单无交集" Toast 也反复弹出
const emptyIntersectionToastShownRef = useRef(false);
useEffect(() => {
inputsGroupRef.current = inputs.group;
}, [inputs.group]);
useEffect(() => {
inputsModelRef.current = inputs.model;
}, [inputs.model]);
const getUserGroup = useCallback(() => {
if (userState?.user?.group) {
return userState.user.group;
}
try {
return JSON.parse(localStorage.getItem('user') || '{}')?.group || '';
} catch {
return '';
}
}, [userState]);
const resolveEffectiveGroup = useCallback(
(groupOptions = [], currentGroup = '') => {
const isGroupSelectEnabled =
!isExperienceMode ||
getExperienceCenterBool(
status,
'experience_center_enable_group_select',
'experience_center_enable_group_select',
true,
);
const hasGroup = (group) =>
!!group && groupOptions.some((option) => option.value === group);
if (groupOptions.length === 0) {
return currentGroup || '';
}
if (!isGroupSelectEnabled) {
if (hasGroup('default')) {
return 'default';
}
const userGroup = getUserGroup();
if (hasGroup(userGroup)) {
return userGroup;
}
if (hasGroup(currentGroup)) {
return currentGroup;
}
return groupOptions[0]?.value || '';
}
if (hasGroup(currentGroup)) {
return currentGroup;
}
const userGroup = getUserGroup();
if (hasGroup(userGroup)) {
return userGroup;
}
if (hasGroup('default')) {
return 'default';
}
return groupOptions[0]?.value || '';
},
[getUserGroup, isExperienceMode, status],
);
const loadModels = useCallback(
async (groupOverride) => {
try {
const group = groupOverride || inputsGroupRef.current;
const groupParam = group ? `?group=${encodeURIComponent(group)}` : '';
const modelEndpoint = isExperienceMode
? API_ENDPOINTS.EXPERIENCE_USER_MODELS
: API_ENDPOINTS.USER_MODELS;
const res = await API.get(`${modelEndpoint}${groupParam}`);
const { success, message, data, level_states } = res.data;
if (success) {
// 通过 ref 读当前选中模型(响应回来时可能已被用户切换,ref 保证读到最新值)
const currentModel = inputsModelRef.current;
const { modelOptions, selectedModel } = processModelsData(
data,
currentModel,
level_states,
);
setModels(modelOptions);
if (selectedModel !== currentModel) {
handleInputChange('model', selectedModel);
}
} else {
showError(t(message));
}
} catch (error) {
showError(t('加载模型失败'));
}
},
[handleInputChange, isExperienceMode, setModels, t],
);
const loadGroups = useCallback(async () => {
try {
const res = await API.get(API_ENDPOINTS.USER_GROUPS);
const { success, message, data } = res.data;
if (success) {
let groupOptions = processGroupsData(data, getUserGroup());
// 体验中心:根据管理员配置过滤可见分组(白名单)
// 仅当 isExperienceMode=true 且配置了非空白名单时才过滤
if (isExperienceMode) {
const allowedRaw = getExperienceCenterValue(
status,
'experience_center_allowed_groups',
'experience_center_allowed_groups',
'',
);
const allowedList = String(allowedRaw)
.split(',')
.map((g) => g.trim())
.filter((g) => g !== '');
if (allowedList.length > 0) {
const allowedSet = new Set(allowedList);
const filtered = groupOptions.filter((g) =>
allowedSet.has(g.value),
);
// 防御:如果过滤后为空(白名单与实际分组无交集),保留原列表避免页面不可用,
// 同时通过 Toast 让用户能感知到(管理员配错时也方便排查)。
// 用 ref 防止 status 频繁变化导致 loadGroups 重新触发时反复弹 Toast
if (filtered.length > 0) {
groupOptions = filtered;
emptyIntersectionToastShownRef.current = false;
} else if (!emptyIntersectionToastShownRef.current) {
showError(
t('体验中心分组白名单与当前账号可用分组无交集,已展示全部分组'),
);
emptyIntersectionToastShownRef.current = true;
}
}
}
setGroups(groupOptions);
const currentGroup = inputsGroupRef.current;
const effectiveGroup = resolveEffectiveGroup(
groupOptions,
currentGroup,
);
if (effectiveGroup && effectiveGroup !== currentGroup) {
handleInputChange('group', effectiveGroup);
}
} else {
showError(t(message));
}
} catch (error) {
showError(t('加载分组失败'));
}
}, [
getUserGroup,
handleInputChange,
resolveEffectiveGroup,
setGroups,
t,
isExperienceMode,
status,
]);
useEffect(() => {
if (userState?.user) {
loadGroups();
}
}, [userState?.user, loadGroups]);
useEffect(() => {
if (userState?.user && inputs.group) {
loadModels(inputs.group);
}
}, [userState?.user, inputs.group, loadModels]);
return {
loadModels,
loadGroups,
};
};
+464
View File
@@ -0,0 +1,464 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback, useRef, useState } from 'react';
import { Toast } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers';
// 唯一 ID 生成(不依赖 crypto.randomUUID 以兼容旧浏览器)
const genId = () =>
`f_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 8)}`;
// 仅当图片上传失败原因看起来是临时性的(网络中断、5xx)时才回退到 base64
// 业务错误(4xx,含 401/403/413/429)保留 failed 状态让用户重试或换文件
const isTransientError = (err) => {
const status = err?.response?.status;
return !status || status >= 500;
};
// 后端如果在错误里返回了真实的 max_size_mb,优先用它显示
const extractMaxSize = (err, fallback) => {
const raw = err?.response?.data?.data?.max_size_mb;
const n = parseInt(raw, 10);
return Number.isFinite(n) && n > 0 ? n : fallback;
};
// 给图片生成 96px 长边的缩略图,用于附件 chip 上的预览
const buildImageThumbnail = (file) =>
new Promise((resolve) => {
if (!file || !file.type?.startsWith('image/')) {
resolve(null);
return;
}
try {
const reader = new FileReader();
reader.onload = (event) => {
const img = new Image();
img.onload = () => {
const MAX = 96;
const scale = Math.min(MAX / img.width, MAX / img.height, 1);
const w = Math.max(1, Math.round(img.width * scale));
const h = Math.max(1, Math.round(img.height * scale));
try {
const canvas = document.createElement('canvas');
canvas.width = w;
canvas.height = h;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, w, h);
resolve(canvas.toDataURL('image/jpeg', 0.7));
} catch {
resolve(event.target.result);
}
};
img.onerror = () => resolve(null);
img.src = event.target.result;
};
reader.onerror = () => resolve(null);
reader.readAsDataURL(file);
} catch {
resolve(null);
}
});
const readAsDataURL = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = (e) => resolve(e.target.result);
reader.onerror = () => reject(reader.error);
reader.readAsDataURL(file);
});
/**
* useFileUpload — 体验中心文件上传统一 Hook
*
* 状态:files 数组,每项 { id, name, size, fileType, status, progress, url, thumbnail, error, _rawFile, _abort }
* - fileType: 'image' | 'file'
* - status: 'uploading' | 'success' | 'failed'
* - progress: 0..1(axios 真实上传进度)
*
* @param {object} opts
* @param {number} opts.maxSizeMB 单文件大小上限(MB)
* @param {number} opts.maxCount 队列最大容量(默认 10)
* @param {(file)=>void} opts.onSuccess 每个文件传完后回调(拿到 url/type 写入消息附件区)
*/
export const useFileUpload = ({ maxSizeMB, maxCount = 10, onSuccess } = {}) => {
const { t } = useTranslation();
const [files, setFiles] = useState([]);
// 用 ref 保证 retry/remove 在闭包里看到最新列表
const filesRef = useRef([]);
filesRef.current = files;
// 双击 retry 的硬隔离:React 的 setState 不是同步 commit 的,filesRef 在两次同步点击之间
// 可能还来不及刷成 'uploading',下面 retry 检查 entry.status 就会漏判。用同步 Set 兜底,
// 进入 runUpload 时立刻 add,结束时(成功/失败/取消)remove。
const inFlightIds = useRef(new Set());
const updateFile = useCallback((id, patch) => {
setFiles((prev) => {
const next = prev.map((f) => (f.id === id ? { ...f, ...patch } : f));
filesRef.current = next;
return next;
});
}, []);
const replaceFiles = useCallback((updater) => {
setFiles((prev) => {
const next = typeof updater === 'function' ? updater(prev) : updater;
filesRef.current = next;
return next;
});
}, []);
// 执行单个文件的真实上传(被 add 和 retry 共用)
const runUpload = useCallback(
async (entry) => {
if (!entry || !entry._rawFile) return;
// 同步占位 — 任何并发 retry 都会被 retry() 的 inFlight 检查挡住
inFlightIds.current.add(entry.id);
const rawFile = entry._rawFile;
const abortCtrl = new AbortController();
updateFile(entry.id, {
status: 'uploading',
progress: 0,
error: null,
_abort: abortCtrl,
});
try {
const formData = new FormData();
formData.append('file', rawFile);
const res = await API.post('/api/user/upload/file', formData, {
skipErrorHandler: true,
signal: abortCtrl.signal,
onUploadProgress: (e) => {
if (!e.total) return;
updateFile(entry.id, {
progress: Math.min(0.99, e.loaded / e.total),
});
},
});
if (res?.data?.success) {
const url = res.data.data.url;
updateFile(entry.id, {
status: 'success',
progress: 1,
url,
error: null,
_abort: null,
_rawFile: null, // 释放内存
});
onSuccess?.({
name: entry.name,
size: entry.size,
type: entry.fileType,
url,
thumbnail: entry.thumbnail,
});
// 老二进制 Office 格式(.doc/.ppt/.xls)OpenAI 解析率极低,
// 大概率"模型说看不到文件内容",给用户一次明确提示,引导改用新格式
const lowerName = (entry.name || '').toLowerCase();
if (/\.(doc|ppt|xls)$/.test(lowerName)) {
const newFormat = lowerName.endsWith('.doc')
? '.docx'
: lowerName.endsWith('.ppt')
? '.pptx'
: '.xlsx';
Toast.warning({
content: t(
'老格式 {{old}} 大模型解析效果不佳,建议另存为 {{new}} 后再上传',
{
old: lowerName.match(/\.(doc|ppt|xls)$/)[0],
new: newFormat,
},
),
// 6 秒:默认 3 秒会让用户在阅读完文件名前就消失。chip 上还有持久角标兜底,
// 但 Toast 是上传完瞬间的提醒,必须让用户来得及看完
duration: 6,
});
}
return;
}
// 后端返回 success=false(业务错)
const message = res?.data?.message || t('文件上传失败');
updateFile(entry.id, {
status: 'failed',
progress: 0,
error: message,
_abort: null,
});
Toast.error({ content: message, duration: 3 });
} catch (err) {
// 取消请求 → 直接移除条目(取消由 abort() 触发,无需 toast)
if (
err?.name === 'CanceledError' ||
err?.code === 'ERR_CANCELED' ||
abortCtrl.signal.aborted
) {
replaceFiles((prev) => prev.filter((f) => f.id !== entry.id));
return;
}
// 临时错误 + 是图片 → 自动回退 base64,仍可送入对话
if (entry.fileType === 'image' && isTransientError(err)) {
try {
const dataUrl = await readAsDataURL(rawFile);
updateFile(entry.id, {
status: 'success',
progress: 1,
url: dataUrl,
error: null,
_abort: null,
_rawFile: null,
});
onSuccess?.({
name: entry.name,
size: entry.size,
type: 'image',
url: dataUrl,
thumbnail: entry.thumbnail || dataUrl,
fromLocalFallback: true,
});
Toast.info({
content: t('网络异常,图片以本地数据上送'),
duration: 3,
});
return;
} catch {
// fall through to failed state
}
}
// 文件超大 → 显示后端返回的真实限制
if (
err?.response?.status === 400 &&
err?.response?.data?.data?.max_size_mb
) {
const limit = extractMaxSize(err, maxSizeMB);
const msg = t('文件大小不能超过 {{size}}MB', { size: limit });
updateFile(entry.id, {
status: 'failed',
progress: 0,
error: msg,
_abort: null,
});
Toast.error({ content: msg, duration: 3 });
return;
}
// 限流 / 鉴权 / 服务器错误
const status = err?.response?.status;
let message =
err?.response?.data?.message || t('文件上传失败,请稍后重试');
if (status === 429) message = t('上传太频繁,请稍后再试');
if (status === 401) message = t('登录已过期,请重新登录');
if (status === 403) message = t('没有上传权限');
updateFile(entry.id, {
status: 'failed',
progress: 0,
error: message,
_abort: null,
});
Toast.error({ content: message, duration: 3 });
} finally {
inFlightIds.current.delete(entry.id);
}
},
[updateFile, replaceFiles, onSuccess, maxSizeMB, t],
);
/**
* upload — 接收一个 FileList / File[] 并行上传
* 自动做:大小校验、数量校验、同名同大小去重、图片缩略图、并行 axios 上传
*/
const upload = useCallback(
async (rawFiles) => {
const arr = Array.from(rawFiles || []);
if (arr.length === 0) return;
const current = filesRef.current;
const slotsLeft = Math.max(0, maxCount - current.length);
if (slotsLeft === 0) {
Toast.warning({
content: t('附件数量已达上限({{max}} 个)', { max: maxCount }),
duration: 3,
});
return;
}
const accepted = [];
for (const file of arr) {
if (accepted.length >= slotsLeft) {
Toast.warning({
content: t('附件数量已达上限({{max}} 个)', { max: maxCount }),
duration: 3,
});
break;
}
// 大小校验:本地阈值,后端会再校验一次
const limitMB = maxSizeMB || 10;
if (file.size > limitMB * 1024 * 1024) {
Toast.error({
content: t('文件「{{name}}」超过 {{size}}MB 限制', {
name: file.name,
size: limitMB,
}),
duration: 3,
});
continue;
}
// 去重:同名 + 同大小视为重复
const dup = [...current, ...accepted].some(
(f) => f.name === file.name && f.size === file.size,
);
if (dup) {
Toast.info({
content: t('文件「{{name}}」已添加', { name: file.name }),
duration: 2,
});
continue;
}
accepted.push({
id: genId(),
name: file.name,
size: file.size,
// SVG 虽然 MIME 是 image/*,但本质是 XML 文本,多数大模型不接受 SVG 作为
// input_image(OpenAI vision 会返 "invalid image"),所以当 file 处理走文件分支。
fileType:
file.type?.startsWith('image/') &&
file.type !== 'image/svg+xml'
? 'image'
: 'file',
status: 'uploading',
progress: 0,
url: null,
thumbnail: null,
error: null,
_rawFile: file,
_abort: null,
});
}
if (accepted.length === 0) return;
// 先入队(UI 立即反馈),再异步起上传
replaceFiles((prev) => [...prev, ...accepted]);
// 并行起:缩略图 + 真实上传,每个文件独立
await Promise.all(
accepted.map(async (entry) => {
// 图片预生成缩略图(不阻塞上传)
if (entry.fileType === 'image') {
buildImageThumbnail(entry._rawFile).then((thumb) => {
if (thumb) updateFile(entry.id, { thumbnail: thumb });
});
}
await runUpload(entry);
}),
);
},
[maxCount, maxSizeMB, replaceFiles, runUpload, updateFile, t],
);
const retry = useCallback(
(id) => {
const entry = filesRef.current.find((f) => f.id === id);
if (!entry) return;
// 与 entry.status 双重保险:inFlightIds 是同步状态,能挡住 React 还没 flush 的并发点击
if (entry.status === 'uploading' || inFlightIds.current.has(id)) return;
if (!entry._rawFile) {
Toast.error({ content: t('原文件已释放,请重新选择'), duration: 3 });
return;
}
runUpload(entry);
},
[runUpload, t],
);
const remove = useCallback(
(id) => {
const entry = filesRef.current.find((f) => f.id === id);
if (!entry) return null;
const wasUploading = entry.status === 'uploading';
if (entry._abort) {
try {
entry._abort.abort();
} catch {
/* ignore */
}
}
replaceFiles((prev) => prev.filter((f) => f.id !== id));
// 返回被删条目供 UI 层做 undo —— uploading 状态的 abort 不可逆,返回 null 表示
// "无法撤销",调用方据此决定是否显示撤销按钮
return wasUploading ? null : entry;
},
[replaceFiles],
);
// 把被 remove 还回去的条目重新挂回列表末尾。简单实现:append 而不还原原 index,
// 避免在频繁删除时维护精确位置的复杂度;用户感受是"它回来了",足够好。
// 如果同 id 已经存在(罕见,比如用户飞快重传同名文件)就静默忽略不重复加。
const restore = useCallback(
(entry) => {
if (!entry || !entry.id) return;
replaceFiles((prev) => {
if (prev.some((f) => f.id === entry.id)) return prev;
return [...prev, entry];
});
},
[replaceFiles],
);
const clearAll = useCallback(() => {
filesRef.current.forEach((f) => {
if (f._abort) {
try {
f._abort.abort();
} catch {
/* ignore */
}
}
});
replaceFiles([]);
}, [replaceFiles]);
// clearSucceeded:仅清掉已成功发送的附件,保留失败状态的让用户继续重试 / 移除。
// 用在"发送完消息后"的场景 —— 用户明确感知到的成功附件已经走出去了,但失败的还没被处理,
// 一并清掉等于把用户的重试机会偷偷拿走。
const clearSucceeded = useCallback(() => {
replaceFiles((prev) => prev.filter((f) => f.status !== 'success'));
}, [replaceFiles]);
const isUploading = files.some((f) => f.status === 'uploading');
return {
files,
upload,
retry,
remove,
restore,
clearAll,
clearSucceeded,
isUploading,
};
};
export default useFileUpload;
+100
View File
@@ -0,0 +1,100 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers';
import { API_ENDPOINTS } from '../../constants/playground.constants';
import { buildImageRequestBody } from '../../constants/imageModelCapabilities';
export const useImageGen = () => {
const { t } = useTranslation();
const [isImageGenerating, setIsImageGenerating] = useState(false);
const pollForResult = useCallback(
async (taskId) => {
const maxAttempts = 60;
for (let i = 0; i < maxAttempts; i++) {
await new Promise((r) => setTimeout(r, 2000));
try {
const res = await API.get(
`${API_ENDPOINTS.IMAGE_GENERATIONS}/${taskId}`,
);
if (res.data?.success && res.data?.data) {
const task = res.data.data;
if (task.status === 'SUCCESS') {
let imageUrl = null;
let revisedPrompt = '';
if (
task.data?.data &&
Array.isArray(task.data.data) &&
task.data.data.length > 0
) {
imageUrl = task.data.data[0].url;
revisedPrompt = task.data.data[0].revised_prompt || '';
}
return imageUrl
? { url: imageUrl, revised_prompt: revisedPrompt }
: null;
}
if (task.status === 'FAILURE') {
return { error: task.fail_reason || t('图片生成失败') };
}
}
} catch {
// Ignore transient polling errors.
}
}
return { error: t('图片生成超时,请重试') };
},
[t],
);
const generateImage = useCallback(
async ({ prompt, model, size }) => {
setIsImageGenerating(true);
try {
const body = buildImageRequestBody(model, {
prompt,
size,
mode: 'text-to-image',
source: 'experience_center_text_model',
});
const res = await API.post(API_ENDPOINTS.IMAGE_GENERATIONS, body);
if (res.data?.success && res.data?.data?.task_id) {
return await pollForResult(res.data.data.task_id);
}
return { error: res.data?.message || t('图片生成失败') };
} catch (err) {
const backendMessage =
err?.response?.data?.message ||
err?.response?.data?.error?.message ||
err?.response?.data?.error;
return { error: backendMessage || t('图片生成失败,请检查网络连接') };
} finally {
setIsImageGenerating(false);
}
},
[t, pollForResult],
);
return { generateImage, isImageGenerating };
};
@@ -0,0 +1,91 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useEffect } from 'react';
// 是否处于"用户正在输入框里打字"的状态 —— 这种时候单字符快捷键(如 ?)不该触发,
// 否则用户按 ? 想打个问号,结果触发了帮助弹窗
const isTypingInField = (target) => {
if (!target) return false;
const tag = (target.tagName || '').toLowerCase();
if (tag === 'input' || tag === 'textarea') return true;
if (target.isContentEditable) return true;
return false;
};
/**
* useKeyboardShortcuts 注册全局键盘快捷键。
*
* 默认绑定:
* - Ctrl/Cmd + K → focusInput() 聚焦输入框
* - Ctrl/Cmd + E → exportSession() 导出当前会话
* - Ctrl/Cmd + / → toggleHelp() 打开/关闭快捷键面板
* - ? → toggleHelp() (仅在不在输入框打字时)
* - Esc → closeHelp() 关闭快捷键面板
*
* 所有 handler 都可选;只传你需要的。
*/
export const useKeyboardShortcuts = ({
enabled = true,
focusInput,
exportSession,
toggleHelp,
closeHelp,
}) => {
useEffect(() => {
if (!enabled) return undefined;
const onKeyDown = (e) => {
// mac vs windows 统一处理;用 metaKey || ctrlKey 兜底
const mod = e.metaKey || e.ctrlKey;
// Esc:关闭帮助;不阻断默认(其它 Modal 也想监听 Esc)
if (e.key === 'Escape') {
closeHelp?.();
return;
}
// ?:打开帮助,但要求用户不在输入框里(否则误触发)
if (e.key === '?' && !isTypingInField(e.target)) {
e.preventDefault();
toggleHelp?.();
return;
}
if (!mod) return;
const key = (e.key || '').toLowerCase();
if (key === 'k') {
e.preventDefault();
focusInput?.();
} else if (key === 'e') {
e.preventDefault();
exportSession?.();
} else if (key === '/') {
e.preventDefault();
toggleHelp?.();
}
};
window.addEventListener('keydown', onKeyDown);
return () => window.removeEventListener('keydown', onKeyDown);
}, [enabled, focusInput, exportSession, toggleHelp, closeHelp]);
};
export default useKeyboardShortcuts;
+435
View File
@@ -0,0 +1,435 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback } from 'react';
import { Toast, Modal } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { getTextContent } from '../../helpers';
import { ERROR_MESSAGES } from '../../constants/playground.constants';
import {
deleteMessage,
deleteMessagePair,
deleteMessagesFrom,
} from '../../services/playgroundConversation';
export const useMessageActions = (
message,
setMessage,
onMessageSend,
saveMessages,
options = {},
) => {
const { t } = useTranslation();
const {
activeSessionId,
sessionEnabled = false,
// 归档会话只读:handleMessageReset / handleMessageDelete 都涉及后端写
// (deleteMessagesFrom / deleteMessage),后端会拒绝但前端 setMessage 已经先动了,
// 必须在动手前拦截避免本地与服务端分叉
activeSessionArchived = false,
// 摘要锚点 + 失效回调(与 useMessageEdit 对齐):重新生成 / 删除若命中已被摘要
// 覆盖的消息(backendId ≤ 锚点),摘要里保留的是旧内容;更糟的是锚点消息本身
// 被删后 applySummaryAndWindow 找不到锚点会兜底发全量历史,变成
// 「陈旧摘要 + 全量历史」双份上下文。此时必须让摘要失效。
summarizedUpToMessageId = 0,
onSummaryInvalidate,
} = options;
// 命中摘要覆盖范围(消息有 backendId 且 ≤ 锚点)时使摘要失效
const invalidateSummaryIfCovered = useCallback(
(msgs) => {
if (!(summarizedUpToMessageId > 0)) return;
if (typeof onSummaryInvalidate !== 'function') return;
const covered = (Array.isArray(msgs) ? msgs : [msgs]).some(
(m) => m?.backendId && m.backendId <= summarizedUpToMessageId,
);
if (covered) onSummaryInvalidate();
},
[summarizedUpToMessageId, onSummaryInvalidate],
);
// 后端同步删除:仅当消息有 backendId(来自后端)时调用
const syncDeleteMessage = useCallback(
async (msg) => {
if (!sessionEnabled || !msg?.backendId) return;
try {
await deleteMessage(msg.backendId);
} catch (e) {
console.warn('后端删除消息失败:', e);
}
},
[sessionEnabled],
);
// 后端同步:删除 user 消息 + 紧随其后的 assistant 回复(问答对,assistant 无 backendId 时用)
const syncDeleteMessagePair = useCallback(
async (userMsg) => {
if (!sessionEnabled || !userMsg?.backendId) return;
try {
await deleteMessagePair(userMsg.backendId);
} catch (e) {
console.warn('后端删除问答对失败:', e);
}
},
[sessionEnabled],
);
// 后端同步:删除某条消息及之后所有(用于重新生成 / 编辑后重发)
const syncDeleteMessagesFrom = useCallback(
async (fromMsg) => {
if (!sessionEnabled || !activeSessionId || !fromMsg?.backendId) return;
try {
await deleteMessagesFrom(activeSessionId, fromMsg.backendId);
} catch (e) {
console.warn('后端删除消息序列失败:', e);
}
},
[sessionEnabled, activeSessionId],
);
// 复制消息
const handleMessageCopy = useCallback(
(targetMessage) => {
const textToCopy = getTextContent(targetMessage);
// 检测消息里有没有附件(图片 / 文件)— 因为剪贴板只能粘文本,附件会被静默丢掉,
// 必须明确告知用户,否则会出现"我刚复制的不是这个"的诡异体验
const hasAttachments =
Array.isArray(targetMessage?.content) &&
targetMessage.content.some(
(p) => p?.type === 'image_url' || p?.type === 'file',
);
if (!textToCopy) {
Toast.warning({
content: t(ERROR_MESSAGES.NO_TEXT_CONTENT),
duration: 2,
});
return;
}
const copyToClipboard = async (text) => {
if (navigator.clipboard?.writeText) {
try {
await navigator.clipboard.writeText(text);
Toast.success({
content: hasAttachments
? t('已复制文本(附件未包含)')
: t('消息已复制到剪贴板'),
duration: 2,
});
} catch (err) {
console.error('Clipboard API 复制失败:', err);
fallbackCopy(text);
}
} else {
fallbackCopy(text);
}
};
const fallbackCopy = (text) => {
try {
const textArea = document.createElement('textarea');
textArea.value = text;
textArea.style.cssText = `
position: fixed;
top: -9999px;
left: -9999px;
opacity: 0;
pointer-events: none;
z-index: -1;
`;
textArea.setAttribute('readonly', '');
document.body.appendChild(textArea);
textArea.select();
textArea.setSelectionRange(0, text.length);
const successful = document.execCommand('copy');
document.body.removeChild(textArea);
if (successful) {
Toast.success({
content: hasAttachments
? t('已复制文本(附件未包含)')
: t('消息已复制到剪贴板'),
duration: 2,
});
} else {
throw new Error('execCommand copy failed');
}
} catch (err) {
console.error('回退复制方案也失败:', err);
let errorMessage = t(ERROR_MESSAGES.COPY_FAILED);
if (
window.location.protocol === 'http:' &&
window.location.hostname !== 'localhost'
) {
errorMessage = t(ERROR_MESSAGES.COPY_HTTPS_REQUIRED);
} else if (!navigator.clipboard && !document.execCommand) {
errorMessage = t(ERROR_MESSAGES.BROWSER_NOT_SUPPORTED);
}
Toast.error({
content: errorMessage,
duration: 4,
});
}
};
copyToClipboard(textToCopy);
},
[t],
);
// 重新生成消息
// 注意:查找/切片/删除后端/重发等逻辑全部在 setMessage updater 外完成 ——
// StrictMode / 并发模式下 updater 可能执行两次,把 syncDeleteMessagesFrom 和
// setTimeout(onMessageSend) 放进 updater 会导致重复删除 + 重复发送(双请求双扣费)。
const handleMessageReset = useCallback(
(targetMessage) => {
// 归档会话拦截:handleMessageReset 会调用 onMessageSend(已拦截) + syncDeleteMessagesFrom(后端拒)
// 后者 catch 静默吞错,本地却已 slice 截断消息列表 → 刷新后老消息回来,体验诡异
if (activeSessionArchived) {
Toast.warning({
content: t('当前会话已归档,无法重新生成回复'),
duration: 2,
});
return;
}
// 使用引用查找索引,防止重复 id 造成误匹配;回退到 id 匹配兼容不同引用场景
let messageIndex = message.findIndex((msg) => msg === targetMessage);
if (messageIndex === -1) {
messageIndex = message.findIndex((msg) => msg.id === targetMessage.id);
}
if (messageIndex === -1) return;
// 从指定 user 消息处截断并重发。重发时若原消息带图片/文件附件,
// 把原 content 数组一并传给 onMessageSend(第三参数),保留附件 ——
// 只发纯文本会让附件在「后端已删、前端重发不带」的组合下彻底丢失。
const resendFromUser = (userMessage, sliceEnd) => {
const newMessages = message.slice(0, sliceEnd);
const contentToSend = getTextContent(userMessage);
const hasAttachmentParts =
Array.isArray(userMessage.content) &&
userMessage.content.some(
(p) => p && (p.type === 'image_url' || p.type === 'file'),
);
setMessage(newMessages);
// 重新生成命中摘要覆盖范围:锚点及旧回复即将被删,摘要必须失效
invalidateSummaryIfCovered(userMessage);
// 后端同步:删除该 user 消息及之后所有消息(重发会重新落库)。
// 必须等删除落地后再重发 —— 删除接口语义是「删 id ≥ fromId」,若重发的
// 新消息先落库、删除后执行,新消息(id 更大)会被一并删掉,DB 丢当前轮。
// syncDeleteMessagesFrom 内部吞错,不会 reject。100ms 延迟保留给 React
// 提交截断后的列表,让 onMessageSend 经 messageRef 读到新状态。
(async () => {
await syncDeleteMessagesFrom(userMessage);
setTimeout(() => {
onMessageSend(
contentToSend,
undefined,
hasAttachmentParts ? userMessage.content : undefined,
);
}, 100);
})();
};
if (targetMessage.role === 'user') {
resendFromUser(targetMessage, messageIndex);
return;
}
if (
targetMessage.role === 'assistant' ||
targetMessage.role === 'system'
) {
let userMessageIndex = messageIndex - 1;
while (
userMessageIndex >= 0 &&
message[userMessageIndex].role !== 'user'
) {
userMessageIndex--;
}
if (userMessageIndex >= 0) {
resendFromUser(message[userMessageIndex], userMessageIndex);
}
}
},
[
message,
setMessage,
onMessageSend,
syncDeleteMessagesFrom,
invalidateSummaryIfCovered,
activeSessionArchived,
t,
],
);
// 删除消息
const handleMessageDelete = useCallback(
(targetMessage) => {
// 归档会话拦截:后端 DeletePlaygroundMessageByUser 的子查询限定主表,
// 归档消息删不到,但前端 setMessage 会先把本地的删掉 → 刷新又回来,体验割裂
if (activeSessionArchived) {
Toast.warning({
content: t('当前会话已归档,无法删除消息'),
duration: 2,
});
return;
}
Modal.confirm({
title: t('确认删除'),
content: t('确定要删除这条消息吗?'),
okText: t('确定'),
cancelText: t('取消'),
okButtonProps: {
type: 'danger',
},
onOk: () => {
// Toast / 后端删除等副作用全部在 setMessage updater 外完成 ——
// StrictMode 下 updater 会执行两次,放里面会重复调删除接口、重复弹 Toast。
// 查找基于 Modal 弹出时捕获的 message 快照;本地过滤走函数式 updater
// (按 id 过滤,容忍弹窗期间列表发生的其它变化),结果用 let 捕获到外面做保存。
let messageIndex = message.findIndex((msg) => msg === targetMessage);
if (messageIndex === -1) {
messageIndex = message.findIndex(
(msg) => msg.id === targetMessage.id,
);
}
if (messageIndex === -1) return;
const nextMessage =
messageIndex < message.length - 1
? message[messageIndex + 1]
: null;
const deletePair =
targetMessage.role === 'user' &&
nextMessage &&
nextMessage.role === 'assistant';
const idsToRemove = new Set(
deletePair
? [targetMessage.id, nextMessage.id]
: [targetMessage.id],
);
// 删除命中摘要覆盖范围的消息:摘要里还留着它的内容(甚至它可能就是锚点,
// 锚点丢失会让下次发送退化为「摘要 + 全量历史」),一并失效
invalidateSummaryIfCovered(
deletePair ? [targetMessage, nextMessage] : targetMessage,
);
if (deletePair) {
Toast.success({ content: t('已删除消息及其回复'), duration: 2 });
// 后端同步。直播会话里 assistant 消息没有 backendId(响应头只回传 user 消息 ID),
// 逐条删会在 DB 留下孤儿 assistant 行,刷新后"复活"——此时改走 pair 接口,
// 由后端把「user 消息 + 紧随其后的 assistant 行」一并删掉(不限尾部)。
if (nextMessage.backendId) {
syncDeleteMessage(targetMessage);
syncDeleteMessage(nextMessage);
} else if (targetMessage.backendId) {
syncDeleteMessagePair(targetMessage);
}
// 两条都无 backendId:后端本就没有记录,仅前端移除即可
} else {
Toast.success({ content: t('消息已删除'), duration: 2 });
syncDeleteMessage(targetMessage);
}
let capturedUpdated = null;
setMessage((prevMessages) => {
const updated = prevMessages.filter(
(msg) => !idsToRemove.has(msg.id),
);
// 纯赋值捕获(幂等),StrictMode 双执行也只是重复赋同一个值
capturedUpdated = updated;
return updated;
});
// 删除消息后保存,传入更新后的消息列表
setTimeout(() => {
if (capturedUpdated) saveMessages(capturedUpdated);
}, 0);
},
});
},
[
message,
setMessage,
t,
saveMessages,
syncDeleteMessage,
syncDeleteMessagePair,
invalidateSummaryIfCovered,
activeSessionArchived,
],
);
// 切换角色
const handleRoleToggle = useCallback(
(targetMessage) => {
if (
!(targetMessage.role === 'assistant' || targetMessage.role === 'system')
) {
return;
}
const newRole =
targetMessage.role === 'assistant' ? 'system' : 'assistant';
// 保存副作用放 updater 外(StrictMode 下 updater 会执行两次),结果用 let 捕获
let capturedUpdated = null;
setMessage((prevMessages) => {
const updatedMessages = prevMessages.map((msg) => {
if (
msg.id === targetMessage.id &&
(msg.role === 'assistant' || msg.role === 'system')
) {
return { ...msg, role: newRole };
}
return msg;
});
capturedUpdated = updatedMessages;
return updatedMessages;
});
// 切换角色后保存,传入更新后的消息列表
setTimeout(() => {
if (capturedUpdated) saveMessages(capturedUpdated);
}, 0);
Toast.success({
content: t('已切换为{{role}}角色', {
role: newRole === 'system' ? 'System' : 'Assistant',
}),
duration: 2,
});
},
[setMessage, t, saveMessages],
);
return {
handleMessageCopy,
handleMessageReset,
handleMessageDelete,
handleRoleToggle,
};
};
+255
View File
@@ -0,0 +1,255 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback, useState, useRef } from 'react';
import { Toast, Modal } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import {
getTextContent,
buildApiPayload,
createLoadingAssistantMessage,
applySummaryAndWindow,
} from '../../helpers';
import { MESSAGE_ROLES } from '../../constants/playground.constants';
import { deleteMessagesFrom } from '../../services/playgroundConversation';
export const useMessageEdit = (
setMessage,
inputs,
parameterEnabled,
sendRequest,
saveMessages,
options = {},
) => {
const {
// 当前消息列表快照(由调用方每次渲染传入)。handleEditSave 的查找/确认弹窗/后端删除
// 必须在 setMessage updater 外完成 —— StrictMode 下 updater 会执行两次,
// 放里面会双弹 Modal、双发请求。
messages = [],
activeSessionId,
sessionEnabled = false,
maxHistoryRounds = 0,
conversationSummary = '',
summarizedUpToMessageId = 0,
summaryEnabled = false,
// 当编辑触发的消息在摘要覆盖范围内(其 backendId ≤ summarizedUpToMessageId)时调用,
// 用于使过时的摘要失效,避免模型同时看到「摘要里的旧版本」+「正文里的新版本」
onSummaryInvalidate,
// 归档会话只读:handleEditSave 进入即拦截,否则"重新生成"路径会发起
// deleteMessagesFrom + sendRequest 两个被后端拒的请求,本地状态与服务端永久分叉
activeSessionArchived = false,
} = options;
const { t } = useTranslation();
const [editingMessageId, setEditingMessageId] = useState(null);
const [editValue, setEditValue] = useState('');
const editingMessageRef = useRef(null);
const handleMessageEdit = useCallback((targetMessage) => {
const editableContent = getTextContent(targetMessage);
setEditingMessageId(targetMessage.id);
editingMessageRef.current = targetMessage;
setEditValue(editableContent);
}, []);
const handleEditSave = useCallback(() => {
if (!editingMessageId || !editValue.trim()) return;
// 归档会话只读拦截:任何路径(仅保存 / 重新生成)都会导致本地与服务端分叉,直接拒绝
if (activeSessionArchived) {
Toast.warning({
content: t('当前会话已归档,无法编辑消息'),
duration: 2,
});
setEditingMessageId(null);
editingMessageRef.current = null;
setEditValue('');
return;
}
// 查找目标消息:全部基于当前渲染传入的 messages 快照,在 updater 外完成。
let messageIndex = messages.findIndex(
(msg) => msg === editingMessageRef.current,
);
if (messageIndex === -1) {
messageIndex = messages.findIndex((msg) => msg.id === editingMessageId);
}
const targetMessage = messages[messageIndex];
// 目标消息已不存在(被删除 / 切换会话):静默退出编辑态,不能继续往下走
// (原实现会直接读 undefined.content 抛 TypeError)
if (!targetMessage) {
setEditingMessageId(null);
editingMessageRef.current = null;
setEditValue('');
return;
}
let newContent;
if (Array.isArray(targetMessage.content)) {
newContent = targetMessage.content.map((item) =>
item.type === 'text' ? { ...item, text: editValue.trim() } : item,
);
} else {
newContent = editValue.trim();
}
const updatedMessages = messages.map((msg) =>
msg.id === editingMessageId ? { ...msg, content: newContent } : msg,
);
// 编辑命中已被摘要覆盖的历史消息时,让摘要失效(next send 退化为不带摘要,再下一次到阈值时重摘)
const summaryInvalidated =
targetMessage.backendId &&
summarizedUpToMessageId > 0 &&
targetMessage.backendId <= summarizedUpToMessageId &&
typeof onSummaryInvalidate === 'function';
if (summaryInvalidated) {
onSummaryInvalidate();
}
const finishEditing = () => {
setEditingMessageId(null);
editingMessageRef.current = null;
setEditValue('');
};
// 处理用户消息编辑后的重新生成
const hasSubsequentAssistantReply =
targetMessage.role === MESSAGE_ROLES.USER &&
messageIndex < messages.length - 1 &&
messages[messageIndex + 1].role === MESSAGE_ROLES.ASSISTANT;
if (hasSubsequentAssistantReply) {
Modal.confirm({
title: t('消息已编辑'),
content: t('检测到该消息后有AI回复,是否删除后续回复并重新生成?'),
okText: t('重新生成'),
cancelText: t('仅保存'),
onOk: () => {
const messagesUntilUser = updatedMessages.slice(0, messageIndex + 1);
setMessage(messagesUntilUser);
// 编辑后保存(重新生成的情况),传入更新后的消息列表
setTimeout(() => saveMessages(messagesUntilUser), 0);
// 用 IIFE 而不是把 onOk 写成 async —— Semi Modal 会 await onOk 的返回值,
// 那样弹窗会挂着 loading 等删除接口返回,这里希望弹窗立即关闭
(async () => {
// 后端同步:删除被编辑的 user 消息及之后所有消息(重发时后端会基于
// 新内容重新落库)。必须等删除落地后再重发 —— 删除接口语义是
// 「删 id ≥ fromId」,若重发的新消息先落库、删除后执行,
// 新消息(id 更大)会被一并删掉,DB 丢当前轮。
if (sessionEnabled && activeSessionId && targetMessage.backendId) {
try {
await deleteMessagesFrom(
activeSessionId,
targetMessage.backendId,
);
} catch (e) {
console.warn('编辑后重发,后端删除消息序列失败:', e);
}
}
setTimeout(() => {
// 编辑后重发同样应用「摘要 + 窗口」处理(Feature A + B)。
// 不在编辑路径触发新摘要,沿用会话已有摘要(接受轻微陈旧)。
// 注意:本次编辑若已使摘要失效,这里必须用失效后的空值 ——
// 闭包里的 conversationSummary 是失效前的旧状态,直接用会把
// 「陈旧摘要 + 全量历史」双份上下文发给模型。
const payload = buildApiPayload(
applySummaryAndWindow(messagesUntilUser, {
maxRounds: maxHistoryRounds,
summary: summaryInvalidated ? '' : conversationSummary,
summarizedUpToMessageId: summaryInvalidated
? 0
: summarizedUpToMessageId,
summaryEnabled,
}),
null,
inputs,
parameterEnabled,
);
// 与 onMessageSend 对齐:若被编辑的 user 消息含 file 附件,
// loading 显示"正在处理 N 个附件…",避免重发时用户体感卡顿无反馈
const lastUserMsg =
messagesUntilUser[messagesUntilUser.length - 1];
const fileCount = Array.isArray(lastUserMsg?.content)
? lastUserMsg.content.filter((p) => p && p.type === 'file')
.length
: 0;
setMessage((prevMsg) => [
...prevMsg,
createLoadingAssistantMessage(
fileCount > 0 ? { processingAttachments: fileCount } : {},
),
]);
sendRequest(payload, inputs.stream);
}, 100);
})();
},
onCancel: () => {
setMessage(updatedMessages);
// 编辑后保存(仅保存的情况),传入更新后的消息列表
setTimeout(() => saveMessages(updatedMessages), 0);
Toast.success({ content: t('消息已更新'), duration: 2 });
},
});
finishEditing();
return;
}
// 编辑后保存(普通情况),传入更新后的消息列表
setMessage(updatedMessages);
setTimeout(() => saveMessages(updatedMessages), 0);
finishEditing();
Toast.success({ content: t('消息已更新'), duration: 2 });
}, [
editingMessageId,
editValue,
messages,
t,
inputs,
parameterEnabled,
sendRequest,
setMessage,
saveMessages,
sessionEnabled,
activeSessionId,
maxHistoryRounds,
conversationSummary,
summarizedUpToMessageId,
summaryEnabled,
onSummaryInvalidate,
activeSessionArchived,
]);
const handleEditCancel = useCallback(() => {
setEditingMessageId(null);
editingMessageRef.current = null;
setEditValue('');
}, []);
return {
editingMessageId,
editValue,
setEditValue,
handleMessageEdit,
handleEditSave,
handleEditCancel,
};
};
+96
View File
@@ -0,0 +1,96 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { API } from '../../helpers';
import { API_ENDPOINTS } from '../../constants/playground.constants';
const SYSTEM_PROMPT = `你是一个 AI 图像生成的提示词工程师。请把用户输入的提示词改写得更具体、更有画面感,让 AI 图像模型能产出更好的图。
要求:
1. 保留原意,但补充细节:构图、光线、风格、材质、镜头感、画质修饰词等
2. 用与输入相同的语言输出(中文输入 -> 中文输出,英文输入 -> 英文输出)
3. 控制在 100 字以内
4. 只输出优化后的提示词,不要解释、不要引号、不要标题`;
// 提取首尾包裹(引号 / 反引号 / 三连反引号代码块)
const stripWrappers = (s) => {
if (!s) return s;
let t = s.trim();
// ``` ... ```
const fence = t.match(/^```[a-zA-Z]*\s*\n([\s\S]*?)\n```$/);
if (fence) t = fence[1].trim();
// 引号
t = t.replace(/^["'`“”‘’]+|["'`“”‘’]+$/g, '');
return t.trim();
};
export const useOptimizePrompt = () => {
const { t } = useTranslation();
const [optimizing, setOptimizing] = useState(false);
const optimize = useCallback(
async (prompt, modelName) => {
if (!prompt || !prompt.trim()) return null;
if (!modelName) {
return { error: t('未配置文本模型,无法优化') };
}
setOptimizing(true);
try {
// 用项目统一的 API helper —— 自动带 cookies / New-API-User 头 / 错误拦截
const res = await API.post(
API_ENDPOINTS.CHAT_COMPLETIONS,
{
model: modelName,
source: 'experience_center_text_model',
stream: false,
messages: [
{ role: 'system', content: SYSTEM_PROMPT },
{ role: 'user', content: prompt },
],
max_tokens: 400,
temperature: 0.7,
},
{ skipErrorHandler: true },
);
const data = res?.data;
const content = data?.choices?.[0]?.message?.content;
if (!content || !content.trim()) {
return { error: t('模型未返回内容') };
}
return { content: stripWrappers(content) };
} catch (err) {
const msg =
err?.response?.data?.error?.message ||
err?.response?.data?.message ||
err?.message ||
t('优化失败');
return { error: msg };
} finally {
setOptimizing(false);
}
},
[t],
);
return { optimizing, optimize };
};
export default useOptimizePrompt;
+658
View File
@@ -0,0 +1,658 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useCallback, useRef, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Toast } from '@douyinfe/semi-ui';
import {
getDefaultMessages,
DEFAULT_CONFIG,
DEBUG_TABS,
MESSAGE_STATUS,
} from '../../constants/playground.constants';
import {
loadConfig,
saveConfig,
loadMessages,
saveMessages,
clearMessages,
migrateOldStorage,
loadActiveSessionId,
saveActiveSessionId,
} from '../../components/playground/configStorage';
import { processIncompleteThinkTags } from '../../helpers';
import {
listConversations,
createConversation,
getConversation,
deleteConversation,
updateConversationTitle,
} from '../../services/playgroundConversation';
import {
prependCreatedSession,
removeSessionAndResolveNext,
} from './sessionFlow';
const isMissingConversationMessage = (message = '') => {
const normalized = String(message).toLowerCase();
return (
normalized.includes('conversation_id is required') ||
(normalized.includes('conversation') && normalized.includes('not found')) ||
normalized.includes('not authorized') ||
normalized.includes('\u4f1a\u8bdd\u4e0d\u5b58\u5728') ||
normalized.includes('\u65e0\u6743') ||
normalized.includes('\u65e0\u6548\u4f1a\u8bdd')
);
};
export const usePlaygroundState = (options = {}) => {
const { t } = useTranslation();
const { experienceMode = false } = options;
const [savedConfig] = useState(() => {
migrateOldStorage();
return loadConfig();
});
const [initialMessages] = useState(() => {
if (experienceMode) {
return [];
}
const loaded = loadMessages();
if (
loaded &&
loaded.length === 2 &&
loaded[0].id === '2' &&
loaded[1].id === '3'
) {
const hasOldChinese = false;
if (hasOldChinese) {
clearMessages();
return null;
}
}
return loaded;
});
const [inputs, setInputs] = useState(
savedConfig.inputs || DEFAULT_CONFIG.inputs,
);
const [parameterEnabled, setParameterEnabled] = useState(
savedConfig.parameterEnabled || DEFAULT_CONFIG.parameterEnabled,
);
const [showDebugPanel, setShowDebugPanel] = useState(
savedConfig.showDebugPanel || DEFAULT_CONFIG.showDebugPanel,
);
const [customRequestMode, setCustomRequestMode] = useState(
savedConfig.customRequestMode || DEFAULT_CONFIG.customRequestMode,
);
const [customRequestBody, setCustomRequestBody] = useState(
savedConfig.customRequestBody || DEFAULT_CONFIG.customRequestBody,
);
const [showSettings, setShowSettings] = useState(false);
const [models, setModels] = useState([]);
const [groups, setGroups] = useState([]);
const [status, setStatus] = useState({});
const [message, setMessage] = useState(() => {
if (experienceMode) return [];
return initialMessages || getDefaultMessages(t);
});
useEffect(() => {
if (experienceMode) return;
if (!initialMessages) {
setMessage(getDefaultMessages(t));
}
}, [t, initialMessages, experienceMode]);
const [debugData, setDebugData] = useState({
request: null,
response: null,
timestamp: null,
previewRequest: null,
previewTimestamp: null,
});
const [activeDebugTab, setActiveDebugTab] = useState(DEBUG_TABS.PREVIEW);
const [previewPayload, setPreviewPayload] = useState(null);
const [editingMessageId, setEditingMessageId] = useState(null);
const [editValue, setEditValue] = useState('');
const [sessions, setSessions] = useState([]);
const [activeSessionId, setActiveSessionId] = useState(() =>
loadActiveSessionId(),
);
const [sessionsLoading, setSessionsLoading] = useState(false);
const [sessionPage, setSessionPage] = useState(1);
const [sessionHasMore, setSessionHasMore] = useState(false);
const [sessionSwitching, setSessionSwitching] = useState(false);
const [sessionCreating, setSessionCreating] = useState(false);
// 体验中心长会话自动摘要:当前会话的历史摘要 + 已被摘要覆盖到的最大消息 ID。
// 来自后端 conversation.summary / summarized_up_to_message_id,切换会话时载入、新建/清空时重置。
const [conversationSummary, setConversationSummary] = useState('');
const [summarizedUpToMessageId, setSummarizedUpToMessageId] = useState(0);
// 归档会话标记:后端 GetConversation 返回 is_archived=true 时为 true,
// 此时输入区禁用、发送按钮禁用、顶部展示"已归档(只读)"横幅。
// 强制只读是防止用户发消息触发后端 4xx 错误(playgroundPrepareSession 会拒绝)
const [activeSessionArchived, setActiveSessionArchived] = useState(false);
// Refs
const sseSourceRef = useRef(null);
const chatRef = useRef(null);
const saveConfigTimeoutRef = useRef(null);
const _saveMessagesTimeoutRef = useRef(null);
const sessionCreatePromiseRef = useRef(null);
const sessionLoadRequestRef = useRef(0);
// 摘要进行中标志,防止同一会话并发触发多次摘要请求
const summarizingRef = useRef(false);
// 摘要 generation:单调递增;任何使飞行中摘要的「结果」失效的动作(清空摘要 / 编辑命中摘要范围)
// 都把它 +1。maybeSummarize 在起跑前快照 gen,落库前对比 —— 不匹配则丢弃 setState + PUT,
// 避免「用户清了,几秒后旧的 fetch 回来把摘要又写回去」的竞态。
const summaryGenRef = useRef(0);
const handleInputChange = useCallback((name, value) => {
setInputs((prev) => ({ ...prev, [name]: value }));
}, []);
const handleParameterToggle = useCallback((paramName) => {
setParameterEnabled((prev) => ({
...prev,
[paramName]: !prev[paramName],
}));
}, []);
const saveMessagesImmediately = useCallback(
(messagesToSave) => {
// 体验模式:消息由后端会话逐条持久化,且本模式从不读 localStorage 的消息缓存。
// 若继续写共享的 playground_messages_user_* key,会把普通 Playground 页面
// 保存的本地对话悄悄覆盖掉(该 key 只有普通模式启动时会读)。
if (experienceMode) return;
saveMessages(messagesToSave || message);
},
[message, experienceMode],
);
const debouncedSaveConfig = useCallback(() => {
if (saveConfigTimeoutRef.current) {
clearTimeout(saveConfigTimeoutRef.current);
}
saveConfigTimeoutRef.current = setTimeout(() => {
const configToSave = {
inputs,
parameterEnabled,
showDebugPanel,
customRequestMode,
customRequestBody,
};
saveConfig(configToSave);
}, 1000);
}, [
inputs,
parameterEnabled,
showDebugPanel,
customRequestMode,
customRequestBody,
]);
const handleConfigImport = useCallback((importedConfig) => {
if (importedConfig.inputs) {
setInputs((prev) => ({ ...prev, ...importedConfig.inputs }));
}
if (importedConfig.parameterEnabled) {
setParameterEnabled((prev) => ({
...prev,
...importedConfig.parameterEnabled,
}));
}
if (typeof importedConfig.showDebugPanel === 'boolean') {
setShowDebugPanel(importedConfig.showDebugPanel);
}
if (importedConfig.customRequestMode) {
setCustomRequestMode(importedConfig.customRequestMode);
}
if (importedConfig.customRequestBody) {
setCustomRequestBody(importedConfig.customRequestBody);
}
if (importedConfig.messages && Array.isArray(importedConfig.messages)) {
setMessage(importedConfig.messages);
}
}, []);
const handleConfigReset = useCallback((options = {}) => {
const { resetMessages = false } = options;
setInputs(DEFAULT_CONFIG.inputs);
setParameterEnabled(DEFAULT_CONFIG.parameterEnabled);
setShowDebugPanel(DEFAULT_CONFIG.showDebugPanel);
setCustomRequestMode(DEFAULT_CONFIG.customRequestMode);
setCustomRequestBody(DEFAULT_CONFIG.customRequestBody);
if (resetMessages) {
setMessage([]);
setTimeout(() => {
setMessage(getDefaultMessages(t));
}, 0);
}
}, []);
const SESSIONS_PAGE_SIZE = 30;
const loadSessions = useCallback(async () => {
setSessionsLoading(true);
try {
const res = await listConversations(1, SESSIONS_PAGE_SIZE);
if (res?.data?.success) {
const list = res.data.data?.list || [];
const total = res.data.data?.total || 0;
setSessions(list);
setSessionPage(1);
setSessionHasMore(list.length < total);
return list;
}
} catch (e) {
console.error('Failed to load conversations', e);
} finally {
setSessionsLoading(false);
}
// null 表示加载失败;与“加载成功但列表为空”区分,避免误建重复会话。
return null;
}, []);
const loadMoreSessions = useCallback(async () => {
if (sessionsLoading || !sessionHasMore) return;
setSessionsLoading(true);
try {
const nextPage = sessionPage + 1;
const res = await listConversations(nextPage, SESSIONS_PAGE_SIZE);
if (res?.data?.success) {
const list = res.data.data?.list || [];
const total = res.data.data?.total || 0;
// setSessionHasMore 不能放进 setSessions updater(updater 必须纯函数,
// StrictMode 下会执行两次)。sessionsLoading 已挡住并发调用,直接基于
// 当前 sessions 状态合并即可。
const existing = new Set(sessions.map((s) => s.id));
const merged = [
...sessions,
...list.filter((s) => !existing.has(s.id)),
];
setSessions(merged);
setSessionHasMore(merged.length < total);
setSessionPage(nextPage);
}
} catch (e) {
console.error('Failed to load more conversations', e);
} finally {
setSessionsLoading(false);
}
}, [sessionsLoading, sessionHasMore, sessionPage, sessions]);
const abortInflightStream = useCallback(() => {
if (sseSourceRef.current) {
try {
sseSourceRef.current.close();
} catch (_) {
// ignore
}
sseSourceRef.current = null;
}
}, []);
const switchSession = useCallback(
async (id) => {
if (!id) {
return { success: false, missing: false };
}
abortInflightStream();
const requestId = sessionLoadRequestRef.current + 1;
sessionLoadRequestRef.current = requestId;
setSessionSwitching(true);
setActiveSessionId(id);
saveActiveSessionId(id);
setMessage([]);
try {
const res = await getConversation(id);
if (requestId !== sessionLoadRequestRef.current) {
return { success: false, missing: false };
}
if (!res?.data?.success) {
const errorMessage =
res?.data?.message || t('Failed to load conversation');
const missing = isMissingConversationMessage(errorMessage);
Toast.error(errorMessage);
if (missing) {
setSessions((prev) => prev.filter((session) => session.id !== id));
abortInflightStream();
sessionLoadRequestRef.current += 1;
setSessionSwitching(false);
setActiveSessionId(null);
saveActiveSessionId(null);
setMessage([]);
// 摘要/归档标记也要清:否则上一个会话的摘要 chip / 归档只读横幅会
// 残留在"无会话"状态上(与 clearActiveSessionSelection 保持一致)
setConversationSummary('');
setSummarizedUpToMessageId(0);
setActiveSessionArchived(false);
}
return { success: false, missing };
}
const data = res.data.data || {};
// 载入该会话已有的历史摘要(长会话上下文压缩)
setConversationSummary(data.conversation?.summary || '');
setSummarizedUpToMessageId(
data.conversation?.summarized_up_to_message_id || 0,
);
// 归档标记:来自后端 GetConversation 的 is_archived 字段(数据源是 *_archive 冷表)
setActiveSessionArchived(!!data.is_archived);
const msgs = (data.messages || []).map((m) => {
let parsedContent = m.content;
const trimmed = (m.content || '').trim();
if (trimmed.startsWith('[')) {
try {
parsedContent = JSON.parse(trimmed);
} catch {}
}
return {
id: `srv-${m.id}`,
backendId: m.id,
role: m.role,
content: parsedContent,
status:
m.status === 'error'
? MESSAGE_STATUS.ERROR
: m.status === 'interrupted'
? MESSAGE_STATUS.INCOMPLETE
: MESSAGE_STATUS.COMPLETE,
createAt: m.created_at,
promptTokens: m.prompt_tokens || 0,
completionTokens: m.completion_tokens || 0,
costQuota: m.cost_quota || 0,
};
});
if (requestId !== sessionLoadRequestRef.current) {
return { success: false, missing: false };
}
setMessage(msgs);
return { success: true, missing: false };
} catch (e) {
if (requestId !== sessionLoadRequestRef.current) {
return { success: false, missing: false };
}
console.error('Failed to switch conversation', e);
Toast.error(t('Failed to switch conversation'));
return { success: false, missing: false };
} finally {
if (requestId === sessionLoadRequestRef.current) {
setSessionSwitching(false);
}
}
},
[abortInflightStream, t],
);
const clearActiveSessionSelection = useCallback(() => {
abortInflightStream();
sessionLoadRequestRef.current += 1;
setSessionSwitching(false);
setActiveSessionId(null);
saveActiveSessionId(null);
setMessage([]);
setConversationSummary('');
setSummarizedUpToMessageId(0);
setActiveSessionArchived(false);
// 注意:不在此处重置 summarizingRef —— 若有摘要请求在飞行中,重置会让新会话能并发再起一次摘要。
// 飞行中的 maybeSummarize 自身的 finally 一定会把它复位,这里交给它处理。
}, [abortInflightStream]);
const createNewSession = useCallback(async () => {
if (sessionCreatePromiseRef.current) {
return sessionCreatePromiseRef.current;
}
const createPromise = (async () => {
setSessionCreating(true);
abortInflightStream();
sessionLoadRequestRef.current += 1;
setSessionSwitching(false);
try {
const res = await createConversation({
model: inputs.model,
group: inputs.group,
});
const createdConv = res?.data?.data;
const newId = createdConv?.id;
if (!res?.data?.success || !newId) {
Toast.error(res?.data?.message || t('Failed to create conversation'));
return null;
}
setSessions((prev) => prependCreatedSession(prev, createdConv));
setActiveSessionId(newId);
saveActiveSessionId(newId);
setMessage([]);
// 新会话没有历史摘要,重置(summarizingRef 交给飞行中的 maybeSummarize 自己复位)
setConversationSummary('');
setSummarizedUpToMessageId(0);
// 新会话不可能是归档
setActiveSessionArchived(false);
return createdConv;
} catch (e) {
console.error('Failed to create conversation', e);
Toast.error(t('Failed to create conversation'));
return null;
} finally {
setSessionCreating(false);
}
})();
sessionCreatePromiseRef.current = createPromise;
try {
return await createPromise;
} finally {
sessionCreatePromiseRef.current = null;
}
}, [abortInflightStream, inputs.group, inputs.model, t]);
const deleteSessionById = useCallback(
async (id) => {
if (!id) return;
const isDeletingActive = id === activeSessionId;
try {
const res = await deleteConversation(id);
if (!res?.data?.success) {
Toast.error(res?.data?.message || t('Failed to delete conversation'));
return;
}
Toast.success(t('Conversation deleted'));
if (isDeletingActive) {
abortInflightStream();
}
// 直接基于当前 sessions 状态计算"下一个会话",不能依赖 setSessions updater
// 的同步执行 —— React 只在特定条件下 eager 执行 updater,不保证在下一行代码
// 前跑完;靠 updater 里的赋值取 nextSessionId 会偶发拿到 null,
// 把"删除当前会话后自动切到下一个"退化成"清空选择"。
const resolved = removeSessionAndResolveNext({
sessions,
deletedSessionId: id,
activeSessionId,
});
const nextSessionId = resolved.nextActiveSessionId;
setSessions(resolved.remainingSessions);
if (isDeletingActive) {
if (nextSessionId) {
await switchSession(nextSessionId);
} else {
clearActiveSessionSelection();
}
}
} catch (e) {
console.error('Failed to delete conversation', e);
Toast.error(t('Failed to delete conversation'));
}
},
[
sessions,
activeSessionId,
switchSession,
clearActiveSessionSelection,
abortInflightStream,
t,
],
);
const renameSession = useCallback(
async (id, newTitle) => {
if (!id || !newTitle) return false;
try {
const res = await updateConversationTitle(id, newTitle);
if (!res?.data?.success) {
Toast.error(res?.data?.message || t('Failed to rename conversation'));
return false;
}
setSessions((prev) =>
prev.map((s) => (s.id === id ? { ...s, title: newTitle } : s)),
);
return true;
} catch (e) {
console.error('Failed to rename conversation', e);
Toast.error(t('Failed to rename conversation'));
return false;
}
},
[t],
);
useEffect(() => {
return () => {
if (saveConfigTimeoutRef.current) {
clearTimeout(saveConfigTimeoutRef.current);
}
};
}, []);
useEffect(() => {
if (!Array.isArray(message) || message.length === 0) return;
const lastMsg = message[message.length - 1];
if (
lastMsg.status === MESSAGE_STATUS.LOADING ||
lastMsg.status === MESSAGE_STATUS.INCOMPLETE
) {
const processed = processIncompleteThinkTags(
lastMsg.content || '',
lastMsg.reasoningContent || '',
);
const fixedLastMsg = {
...lastMsg,
status: MESSAGE_STATUS.COMPLETE,
content: processed.content,
reasoningContent: processed.reasoningContent || null,
isThinkingComplete: true,
};
const updatedMessages = [...message.slice(0, -1), fixedLastMsg];
setMessage(updatedMessages);
setTimeout(() => saveMessagesImmediately(updatedMessages), 0);
}
}, []);
return {
inputs,
parameterEnabled,
showDebugPanel,
customRequestMode,
customRequestBody,
showSettings,
models,
groups,
status,
message,
debugData,
activeDebugTab,
previewPayload,
editingMessageId,
editValue,
// Refs
sseSourceRef,
chatRef,
saveConfigTimeoutRef,
setInputs,
setParameterEnabled,
setShowDebugPanel,
setCustomRequestMode,
setCustomRequestBody,
setShowSettings,
setModels,
setGroups,
setStatus,
setMessage,
setDebugData,
setActiveDebugTab,
setPreviewPayload,
setEditingMessageId,
setEditValue,
handleInputChange,
handleParameterToggle,
debouncedSaveConfig,
saveMessagesImmediately,
handleConfigImport,
handleConfigReset,
sessions,
activeSessionId,
sessionsLoading,
sessionSwitching,
sessionCreating,
sessionHasMore,
setActiveSessionId,
setSessions,
loadSessions,
loadMoreSessions,
switchSession,
clearActiveSessionSelection,
createNewSession,
deleteSessionById,
renameSession,
// 长会话自动摘要
conversationSummary,
setConversationSummary,
summarizedUpToMessageId,
setSummarizedUpToMessageId,
summarizingRef,
summaryGenRef,
// 归档(只读)
activeSessionArchived,
};
};
@@ -0,0 +1,160 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback, useEffect, useRef, useState } from 'react';
/**
* useSpeechRecognition —— 浏览器原生 STT,目前依赖 webkit / 标准 SpeechRecognition。
*
* 兼容性:
* - Chrome / Edge / 大部分移动 Safari 支持
* - Firefox 不原生支持(API 不存在),isSupported 会返回 false
*
* 行为:
* - 默认 zh-CN,连续模式 (continuous=true),开 interim 结果实时反馈
* - onResult(text, isFinal) 把识别结果回传给调用方,由调用方决定怎么塞进输入框
* - 错误(permission denied / no-speech / aborted 等)转 onError 给上层
* - 自动处理 onend:如果用户没主动 stop,自动 restart 维持长录音(部分浏览器会自动 stop)
*/
const getRecognitionCtor = () => {
if (typeof window === 'undefined') return null;
return window.SpeechRecognition || window.webkitSpeechRecognition || null;
};
export const useSpeechRecognition = ({
onResult,
onError,
lang = 'zh-CN',
} = {}) => {
const RecognitionCtor = getRecognitionCtor();
const isSupported = !!RecognitionCtor;
const [isListening, setIsListening] = useState(false);
const recognitionRef = useRef(null);
const userStoppedRef = useRef(false); // 用户主动 stop vs 浏览器 auto end
const stop = useCallback(() => {
userStoppedRef.current = true;
const rec = recognitionRef.current;
if (rec) {
try {
rec.stop();
} catch (_) {
/* ignore */
}
}
setIsListening(false);
}, []);
const start = useCallback(() => {
if (!isSupported) return;
// 已经在录就不重复 start —— 浏览器会抛 InvalidStateError
if (recognitionRef.current && isListening) return;
let rec;
try {
rec = new RecognitionCtor();
} catch (e) {
onError?.(e);
return;
}
rec.lang = lang;
rec.continuous = true;
rec.interimResults = true;
rec.maxAlternatives = 1;
rec.onresult = (event) => {
// event.results 是累加的 SpeechRecognitionResultList;遍历从 resultIndex 开始的新分段
let finalText = '';
let interimText = '';
for (let i = event.resultIndex; i < event.results.length; i++) {
const res = event.results[i];
const transcript = res[0]?.transcript || '';
if (res.isFinal) finalText += transcript;
else interimText += transcript;
}
if (finalText) onResult?.(finalText, true);
else if (interimText) onResult?.(interimText, false);
};
rec.onerror = (event) => {
// no-speech / aborted 都是常见的非致命错误,不一定要广播;只对真出错时通知
if (
event?.error &&
event.error !== 'no-speech' &&
event.error !== 'aborted'
) {
onError?.(event);
}
};
rec.onend = () => {
// Chrome 长时间没说话会自动 onend,要么用户停了,要么浏览器停了
if (userStoppedRef.current) {
setIsListening(false);
recognitionRef.current = null;
return;
}
// 浏览器自停 → 尝试无缝续上
try {
rec.start();
} catch (_) {
// 续上失败,照常结束
setIsListening(false);
recognitionRef.current = null;
}
};
recognitionRef.current = rec;
userStoppedRef.current = false;
try {
rec.start();
setIsListening(true);
} catch (e) {
onError?.(e);
recognitionRef.current = null;
setIsListening(false);
}
}, [isSupported, RecognitionCtor, lang, isListening, onResult, onError]);
// 卸载时确保停掉,避免麦克风指示灯一直亮
useEffect(() => {
return () => {
const rec = recognitionRef.current;
if (rec) {
userStoppedRef.current = true;
try {
rec.stop();
} catch (_) {
/* ignore */
}
recognitionRef.current = null;
}
};
}, []);
const toggle = useCallback(() => {
if (isListening) stop();
else start();
}, [isListening, start, stop]);
return { isSupported, isListening, start, stop, toggle };
};
export default useSpeechRecognition;
+170
View File
@@ -0,0 +1,170 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback, useEffect, useRef, useState } from 'react';
/**
* useSpeechSynthesis —— 浏览器原生朗读 hook
*
* 设计要点:
* - speechSynthesis 是全局单例(同时只能播一个 utterance)。这里用一个全局 ref 跟踪"哪个消息在播",
* 避免多条助手消息的 TTS 按钮状态错位。
* - 中文响应默认挑 zh-* 的 voice;找不到就走系统默认。
* - 长文本会被部分浏览器(Chrome)在 ~15s 处自动断流,这里用 resume 心跳兜底;不完美但够用。
* - 卸载/路由切换时自动 cancel,避免后台还在念。
*/
// 模块级"当前正在播的 messageId",让所有调用 hook 的实例共享状态
let currentSpeakingId = null;
const listeners = new Set();
const notifyListeners = () => {
listeners.forEach((fn) => fn(currentSpeakingId));
};
export const useSpeechSynthesis = () => {
const isSupported =
typeof window !== 'undefined' && 'speechSynthesis' in window;
const [speakingId, setSpeakingId] = useState(currentSpeakingId);
const utteranceRef = useRef(null);
const heartbeatRef = useRef(null);
// 订阅模块级状态:任意 hook 实例改变了 currentSpeakingId,所有实例都收到
useEffect(() => {
const listener = (id) => setSpeakingId(id);
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}, []);
// 清掉 Chrome 长文本断流兜底
const clearHeartbeat = useCallback(() => {
if (heartbeatRef.current) {
clearInterval(heartbeatRef.current);
heartbeatRef.current = null;
}
}, []);
const stop = useCallback(() => {
if (!isSupported) return;
clearHeartbeat();
try {
window.speechSynthesis.cancel();
} catch (_) {
// ignore
}
utteranceRef.current = null;
currentSpeakingId = null;
notifyListeners();
}, [isSupported, clearHeartbeat]);
const speak = useCallback(
(id, text) => {
if (!isSupported || !text) return;
// 同一条消息再点 → 当作 stop 处理(按钮变 toggle)
if (currentSpeakingId === id) {
stop();
return;
}
// 抢占:之前在播别的就先停掉
try {
window.speechSynthesis.cancel();
} catch (_) {
/* ignore */
}
clearHeartbeat();
const utt = new SpeechSynthesisUtterance(text);
// 挑中文音色(如果是中文内容),否则用默认
try {
const voices = window.speechSynthesis.getVoices() || [];
const looksChinese = /[一-龥]/.test(text);
if (looksChinese) {
const zh = voices.find((v) => /zh|cmn|chinese/i.test(v.lang));
if (zh) utt.voice = zh;
utt.lang = 'zh-CN';
} else {
const en = voices.find((v) => /en[-_]US|english/i.test(v.lang));
if (en) utt.voice = en;
}
} catch (_) {
// 取 voices 失败也无所谓,用浏览器默认
}
utt.rate = 1;
utt.pitch = 1;
utt.onend = () => {
clearHeartbeat();
if (currentSpeakingId === id) {
currentSpeakingId = null;
notifyListeners();
}
};
utt.onerror = () => {
clearHeartbeat();
if (currentSpeakingId === id) {
currentSpeakingId = null;
notifyListeners();
}
};
utteranceRef.current = utt;
currentSpeakingId = id;
notifyListeners();
window.speechSynthesis.speak(utt);
// Chrome 长文本 bug 兜底:每 10s pause/resume 一次让它不要断
heartbeatRef.current = setInterval(() => {
try {
if (window.speechSynthesis.speaking) {
window.speechSynthesis.pause();
window.speechSynthesis.resume();
} else {
clearHeartbeat();
}
} catch (_) {
clearHeartbeat();
}
}, 10000);
},
[isSupported, stop, clearHeartbeat],
);
// 卸载时停止任何在播的 — 避免页面卸载后还在念
useEffect(() => {
return () => {
// 仅当当前 instance 正在播自己的 utterance 时才 cancel;其它实例还在使用就别打断
if (utteranceRef.current && window.speechSynthesis?.speaking) {
try {
window.speechSynthesis.cancel();
} catch (_) {
/* ignore */
}
clearHeartbeat();
}
};
}, [clearHeartbeat]);
return {
isSupported,
speakingId, // 当前模块内正在播放的消息 id,null 表示无
speak, // (id, text) => void;同 id 再次调用等同 stop
stop,
};
};
export default useSpeechSynthesis;
@@ -0,0 +1,149 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback, useRef } from 'react';
import { MESSAGE_ROLES } from '../../constants/playground.constants';
export const useSyncMessageAndCustomBody = (
customRequestMode,
customRequestBody,
message,
inputs,
setCustomRequestBody,
setMessage,
debouncedSaveConfig,
) => {
const isUpdatingFromMessage = useRef(false);
const isUpdatingFromCustomBody = useRef(false);
const lastMessageHash = useRef('');
const lastCustomBodyHash = useRef('');
const getMessageHash = useCallback((messages) => {
return JSON.stringify(
messages.map((msg) => ({
id: msg.id,
role: msg.role,
content: msg.content,
})),
);
}, []);
const getCustomBodyHash = useCallback((customBody) => {
try {
const parsed = JSON.parse(customBody);
return JSON.stringify(parsed.messages || []);
} catch {
return '';
}
}, []);
const syncMessageToCustomBody = useCallback(() => {
if (!customRequestMode || isUpdatingFromCustomBody.current) return;
const currentMessageHash = getMessageHash(message);
if (currentMessageHash === lastMessageHash.current) return;
try {
isUpdatingFromMessage.current = true;
let customPayload;
try {
customPayload = JSON.parse(customRequestBody || '{}');
} catch {
customPayload = {
model: inputs.model || 'gpt-4o',
messages: [],
temperature: inputs.temperature || 0.7,
stream: inputs.stream !== false,
};
}
customPayload.messages = message.map((msg) => ({
role: msg.role,
content: msg.content,
}));
const newCustomBody = JSON.stringify(customPayload, null, 2);
setCustomRequestBody(newCustomBody);
lastMessageHash.current = currentMessageHash;
lastCustomBodyHash.current = getCustomBodyHash(newCustomBody);
setTimeout(() => {
debouncedSaveConfig();
}, 0);
} finally {
isUpdatingFromMessage.current = false;
}
}, [
customRequestMode,
customRequestBody,
message,
inputs.model,
inputs.temperature,
inputs.stream,
getMessageHash,
getCustomBodyHash,
setCustomRequestBody,
debouncedSaveConfig,
]);
const syncCustomBodyToMessage = useCallback(() => {
if (!customRequestMode || isUpdatingFromMessage.current) return;
const currentCustomBodyHash = getCustomBodyHash(customRequestBody);
if (currentCustomBodyHash === lastCustomBodyHash.current) return;
try {
isUpdatingFromCustomBody.current = true;
const customPayload = JSON.parse(customRequestBody || '{}');
if (customPayload.messages && Array.isArray(customPayload.messages)) {
const newMessages = customPayload.messages.map((msg, index) => ({
id: msg.id || (index + 1).toString(),
role: msg.role || MESSAGE_ROLES.USER,
content: msg.content || '',
createAt: Date.now(),
...(msg.role === MESSAGE_ROLES.ASSISTANT && {
reasoningContent: msg.reasoningContent || '',
isReasoningExpanded: false,
}),
}));
setMessage(newMessages);
lastCustomBodyHash.current = currentCustomBodyHash;
lastMessageHash.current = getMessageHash(newMessages);
}
} catch (error) {
console.warn('同步自定义请求体到消息失败:', error);
} finally {
isUpdatingFromCustomBody.current = false;
}
}, [
customRequestMode,
customRequestBody,
getCustomBodyHash,
getMessageHash,
setMessage,
]);
return {
syncMessageToCustomBody,
syncCustomBodyToMessage,
};
};
+264
View File
@@ -0,0 +1,264 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { API } from '../../helpers';
import {
QUALITY_ERROR_TEXT,
TIME_RANGES,
} from '../../components/quality/qualityConstants';
// 筛选条件全部同步到 URL(q_ 前缀),刷新 / 分享链接可还原同一视图。
const FILTER_KEYS = [
'range',
'start',
'end',
'granularity',
'model',
'channel_id',
'group',
'org_id',
'user_id',
'token_id',
'dept_id',
'project_id',
'path',
'error_code',
'status_code',
'outcome',
'fault_side',
'source',
'include_abort',
'include_blocked',
];
export const DEFAULT_FILTERS = {
range: '24h',
start: '',
end: '',
granularity: 'auto',
model: '',
channel_id: '',
group: '',
org_id: '',
user_id: '',
token_id: '',
dept_id: '',
project_id: '',
path: '',
error_code: '',
status_code: '',
outcome: '',
fault_side: '',
source: '',
include_abort: '',
include_blocked: '',
};
const readFiltersFromURL = () => {
const next = { ...DEFAULT_FILTERS };
try {
const params = new URLSearchParams(window.location.search);
FILTER_KEYS.forEach((key) => {
const v = params.get(`q_${key}`);
if (v !== null) next[key] = v;
});
} catch (_e) {
// URL 不可解析时使用默认筛选
}
return next;
};
const writeFiltersToURL = (filters) => {
try {
const url = new URL(window.location.href);
FILTER_KEYS.forEach((key) => {
const v = filters[key];
if (v === '' || v === undefined || v === DEFAULT_FILTERS[key]) {
url.searchParams.delete(`q_${key}`);
} else {
url.searchParams.set(`q_${key}`, v);
}
});
window.history.replaceState(null, '', url.toString());
} catch (_e) {
// 忽略
}
};
export const resolveWindow = (filters) => {
if (filters.range === 'custom' && filters.start && filters.end) {
return { start: Number(filters.start), end: Number(filters.end) };
}
const now = Math.floor(Date.now() / 1000);
const preset =
TIME_RANGES.find((r) => r.value === filters.range) || TIME_RANGES[2];
return { start: now - preset.seconds, end: now };
};
export const buildQualityParams = (filters) => {
const { start, end } = resolveWindow(filters);
const params = { start, end };
FILTER_KEYS.forEach((key) => {
if (['range', 'start', 'end'].includes(key)) return;
const v = filters[key];
if (v !== '' && v !== undefined && v !== null) params[key] = v;
});
return params;
};
/**
* 调用质量看板数据 hook。
* @param {'platform'|'org'} scope
* @param {boolean} enabled 页签未激活时不发请求
* @param {number} [orgId] 企业侧显式注入 X-Org-Id
*/
const useQualityDashboard = (scope, enabled, orgId) => {
const base = scope === 'org' ? '/api/org/quality' : '/api/analytics/quality';
const headers = useMemo(
() => (scope === 'org' && orgId ? { 'X-Org-Id': String(orgId) } : {}),
[scope, orgId],
);
const [filters, setFiltersState] = useState(readFiltersFromURL);
const [options, setOptions] = useState({});
const [summary, setSummary] = useState(null);
const [trend, setTrend] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState('');
const [refreshKey, setRefreshKey] = useState(0);
const seq = useRef(0);
// 统一把 HTTP 错误与 success:false 归一成带 code 的 Error,由看板就地展示可读文案
// (skipErrorHandler:不走全局 toast,避免同一错误弹两次)
const unwrap = async (promise) => {
// 优先用后端错误码;中间件拒绝(企业冻结 / 权限不足等)只给了中文提示时改用提示文案
const toError = (body) => {
const code = body.code && QUALITY_ERROR_TEXT[body.code] ? body.code : '';
const err = new Error(body.message || 'query_failed');
err.code = code || body.message || body.code || 'query_failed';
return err;
};
let res;
try {
res = await promise;
} catch (e) {
throw toError(e?.response?.data || {});
}
const body = res?.data || {};
if (!body.success) {
throw toError(body);
}
return body.data;
};
const get = useCallback(
(path, params) =>
unwrap(
API.get(`${base}${path}`, { params, headers, skipErrorHandler: true }),
),
// eslint-disable-next-line react-hooks/exhaustive-deps
[base, headers],
);
const send = useCallback(
(method, path, data) =>
unwrap(
method === 'delete'
? API.delete(`${base}${path}`, { headers, skipErrorHandler: true })
: API[method](`${base}${path}`, data, {
headers,
skipErrorHandler: true,
}),
),
// eslint-disable-next-line react-hooks/exhaustive-deps
[base, headers],
);
const setFilters = useCallback((patch) => {
setFiltersState((prev) => {
const next = { ...prev, ...patch };
writeFiltersToURL(next);
return next;
});
}, []);
const resetFilters = useCallback(() => {
writeFiltersToURL(DEFAULT_FILTERS);
setFiltersState({ ...DEFAULT_FILTERS });
}, []);
const refresh = useCallback(() => setRefreshKey((k) => k + 1), []);
const params = useMemo(
() => buildQualityParams(filters),
// refreshKey 参与依赖:预设时间范围在刷新时重新以当前时刻为终点
// eslint-disable-next-line react-hooks/exhaustive-deps
[filters, refreshKey],
);
useEffect(() => {
if (!enabled) return;
get('/options', {})
.then((data) => setOptions(data || {}))
.catch(() => setOptions({}));
}, [enabled, get]);
useEffect(() => {
if (!enabled) return;
const current = ++seq.current;
setLoading(true);
setError('');
Promise.all([get('/summary', params), get('/trend', params)])
.then(([s, tr]) => {
if (current !== seq.current) return;
setSummary(s);
setTrend(tr);
})
.catch((err) => {
if (current !== seq.current) return;
setSummary(null);
setTrend(null);
setError(err.code || err.message || 'query_failed');
})
.finally(() => {
if (current === seq.current) setLoading(false);
});
}, [enabled, get, params]);
return {
scope,
base,
headers,
filters,
setFilters,
resetFilters,
params,
options,
summary,
trend,
loading,
error,
refresh,
refreshKey,
get,
send,
};
};
export default useQualityDashboard;
@@ -0,0 +1,360 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect } from 'react';
import { API, showError, showSuccess, copy } from '../../helpers';
import { ITEMS_PER_PAGE } from '../../constants';
import {
REDEMPTION_ACTIONS,
REDEMPTION_STATUS,
} from '../../constants/redemption.constants';
import { Modal } from '@douyinfe/semi-ui';
import { useTranslation } from 'react-i18next';
import { useTableCompactMode } from '../common/useTableCompactMode';
export const useRedemptionsData = () => {
const { t } = useTranslation();
// Basic state
const [redemptions, setRedemptions] = useState([]);
const [loading, setLoading] = useState(true);
const [searching, setSearching] = useState(false);
const [activePage, setActivePage] = useState(1);
const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
const [tokenCount, setTokenCount] = useState(0);
const [selectedKeys, setSelectedKeys] = useState([]);
// Edit state
const [editingRedemption, setEditingRedemption] = useState({
id: undefined,
});
const [showEdit, setShowEdit] = useState(false);
// Form API
const [formApi, setFormApi] = useState(null);
// UI state
const [compactMode, setCompactMode] = useTableCompactMode('redemptions');
// Form state
const formInitValues = {
searchKeyword: '',
};
// Get form values
const getFormValues = () => {
const formValues = formApi ? formApi.getValues() : {};
return {
searchKeyword: formValues.searchKeyword || '',
};
};
// Set redemption data format
const setRedemptionFormat = (redemptions) => {
setRedemptions(redemptions);
};
// Load redemption list
const loadRedemptions = async (page = 1, pageSize) => {
setLoading(true);
try {
const res = await API.get(
`/api/redemption/?p=${page}&page_size=${pageSize}`,
);
const { success, message, data } = res.data;
if (success) {
const newPageData = data.items;
setActivePage(data.page <= 0 ? 1 : data.page);
setTokenCount(data.total);
setRedemptionFormat(newPageData);
} else {
showError(message);
}
} catch (error) {
showError(error.message);
}
setLoading(false);
};
// Search redemption codes
const searchRedemptions = async () => {
const { searchKeyword } = getFormValues();
if (searchKeyword === '') {
await loadRedemptions(1, pageSize);
return;
}
setSearching(true);
try {
const res = await API.get(
`/api/redemption/search?keyword=${searchKeyword}&p=1&page_size=${pageSize}`,
);
const { success, message, data } = res.data;
if (success) {
const newPageData = data.items;
setActivePage(data.page || 1);
setTokenCount(data.total);
setRedemptionFormat(newPageData);
} else {
showError(message);
}
} catch (error) {
showError(error.message);
}
setSearching(false);
};
// Manage redemption codes (CRUD operations)
const manageRedemption = async (id, action, record) => {
setLoading(true);
let data = { id };
let res;
try {
switch (action) {
case REDEMPTION_ACTIONS.DELETE:
res = await API.delete(`/api/redemption/${id}/`);
break;
case REDEMPTION_ACTIONS.ENABLE:
data.status = REDEMPTION_STATUS.UNUSED;
res = await API.put('/api/redemption/?status_only=true', data);
break;
case REDEMPTION_ACTIONS.DISABLE:
data.status = REDEMPTION_STATUS.DISABLED;
res = await API.put('/api/redemption/?status_only=true', data);
break;
default:
throw new Error('Unknown operation type');
}
const { success, message } = res.data;
if (success) {
showSuccess(t('操作成功完成!'));
let redemption = res.data.data;
let newRedemptions = [...redemptions];
if (action !== REDEMPTION_ACTIONS.DELETE) {
record.status = redemption.status;
}
setRedemptions(newRedemptions);
} else {
showError(message);
}
} catch (error) {
showError(error.message);
}
setLoading(false);
};
// Refresh data
const refresh = async (page = activePage) => {
const { searchKeyword } = getFormValues();
if (searchKeyword === '') {
await loadRedemptions(page, pageSize);
} else {
await searchRedemptions();
}
};
// Handle page change
const handlePageChange = (page) => {
setActivePage(page);
const { searchKeyword } = getFormValues();
if (searchKeyword === '') {
loadRedemptions(page, pageSize);
} else {
searchRedemptions();
}
};
// Handle page size change
const handlePageSizeChange = (size) => {
setPageSize(size);
setActivePage(1);
const { searchKeyword } = getFormValues();
if (searchKeyword === '') {
loadRedemptions(1, size);
} else {
searchRedemptions();
}
};
// Row selection configuration
const rowSelection = {
onSelect: (record, selected) => {},
onSelectAll: (selected, selectedRows) => {},
onChange: (selectedRowKeys, selectedRows) => {
setSelectedKeys(selectedRows);
},
};
// Row style handling - using isExpired function
const handleRow = (record, index) => {
// Local isExpired function
const isExpired = (rec) => {
return (
rec.status === REDEMPTION_STATUS.UNUSED &&
rec.expired_time !== 0 &&
rec.expired_time < Math.floor(Date.now() / 1000)
);
};
if (record.status !== REDEMPTION_STATUS.UNUSED || isExpired(record)) {
return {
style: {
background: 'var(--semi-color-disabled-border)',
},
};
} else {
return {};
}
};
// Copy text
const copyText = async (text) => {
if (await copy(text)) {
showSuccess(t('已复制到剪贴板!'));
} else {
Modal.error({
title: '无法复制到剪贴板,请手动复制',
content: text,
size: 'large',
});
}
};
// Batch copy redemption codes
const batchCopyRedemptions = async () => {
if (selectedKeys.length === 0) {
showError(t('请至少选择一个兑换码!'));
return;
}
let keys = '';
for (let i = 0; i < selectedKeys.length; i++) {
keys += selectedKeys[i].name + ' ' + selectedKeys[i].key + '\n';
}
await copyText(keys);
};
// Batch delete redemption codes (clear invalid)
const batchDeleteRedemptions = async () => {
Modal.confirm({
title: t('确定清除所有失效兑换码?'),
content: t('将删除已使用、已禁用及过期的兑换码,此操作不可撤销。'),
onOk: async () => {
setLoading(true);
const res = await API.delete('/api/redemption/invalid');
const { success, message, data } = res.data;
if (success) {
showSuccess(t('已删除 {{count}} 条失效兑换码', { count: data }));
await refresh();
} else {
showError(message);
}
setLoading(false);
},
});
};
// Close edit modal
const closeEdit = () => {
setShowEdit(false);
setTimeout(() => {
setEditingRedemption({
id: undefined,
});
}, 500);
};
// Remove record (for UI update after deletion)
const removeRecord = (key) => {
let newDataSource = [...redemptions];
if (key != null) {
let idx = newDataSource.findIndex((data) => data.key === key);
if (idx > -1) {
newDataSource.splice(idx, 1);
setRedemptions(newDataSource);
}
}
};
// Initialize data loading
useEffect(() => {
loadRedemptions(1, pageSize)
.then()
.catch((reason) => {
showError(reason);
});
}, [pageSize]);
return {
// Data state
redemptions,
loading,
searching,
activePage,
pageSize,
tokenCount,
selectedKeys,
// Edit state
editingRedemption,
showEdit,
// Form state
formApi,
formInitValues,
// UI state
compactMode,
setCompactMode,
// Data operations
loadRedemptions,
searchRedemptions,
manageRedemption,
refresh,
copyText,
removeRecord,
// State updates
setActivePage,
setPageSize,
setSelectedKeys,
setEditingRedemption,
setShowEdit,
setFormApi,
setLoading,
// Event handlers
handlePageChange,
handlePageSizeChange,
rowSelection,
handleRow,
closeEdit,
getFormValues,
// Batch operations
batchCopyRedemptions,
batchDeleteRedemptions,
// Translation function
t,
};
};
+522
View File
@@ -0,0 +1,522 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect, useRef, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Modal } from '@douyinfe/semi-ui';
import {
API,
copy,
isAdmin,
showError,
showSuccess,
timestamp2string,
} from '../../helpers';
import { EVENTS, emit } from '../../helpers/eventBus';
import { ITEMS_PER_PAGE } from '../../constants';
import { useTableCompactMode } from '../common/useTableCompactMode';
export const useTaskLogsData = () => {
const { t } = useTranslation();
// Define column keys for selection
// 注意:这里列出的 key 必须与 TaskLogsColumnDefs.getTaskLogsColumns 返回的列 key 一一对应,
// 否则会在 localStorage 中留下无效状态并误导列选择器显示
const COLUMN_KEYS = {
SUBMIT_TIME: 'submit_time',
FINISH_TIME: 'finish_time',
DURATION: 'duration',
CHANNEL: 'channel',
PLATFORM: 'platform',
TYPE: 'type',
MODEL: 'model',
TASK_ID: 'task_id',
TASK_STATUS: 'task_status',
PROGRESS: 'progress',
QUOTA: 'quota',
FAIL_REASON: 'fail_reason',
};
// Basic state
const [logs, setLogs] = useState([]);
const [loading, setLoading] = useState(false);
const [activePage, setActivePage] = useState(1);
const [logCount, setLogCount] = useState(0);
const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
// User and admin
const isAdminUser = isAdmin();
// Role-specific storage key to prevent different roles from overwriting each other
const STORAGE_KEY = isAdminUser
? 'task-logs-table-columns-admin'
: 'task-logs-table-columns-user';
// Modal state
const [isModalOpen, setIsModalOpen] = useState(false);
const [modalContent, setModalContent] = useState('');
// 新增:视频预览弹窗状态
// videoUrl:用于 <video> 标签播放,走后端代理 /v1/videos/:id/content 避免跨域
// videoSourceUrl:上游原始可分享 URL,供"复制链接"使用,避免用户拿到无法外部访问的代理路径
const [isVideoModalOpen, setIsVideoModalOpen] = useState(false);
const [videoUrl, setVideoUrl] = useState('');
const [videoSourceUrl, setVideoSourceUrl] = useState('');
// Form state
const [formApi, setFormApi] = useState(null);
// 每次调用都返回"此刻"的默认时间范围,避免长时间驻留页面后
// 点击"重置"仍得到页面加载时的"今日"(跨日 bug)
const getFreshDateRange = () => {
const now = new Date();
const zeroNow = new Date(now.getFullYear(), now.getMonth(), now.getDate());
return [
timestamp2string(zeroNow.getTime() / 1000),
timestamp2string(now.getTime() / 1000 + 3600),
];
};
const getFreshInitValues = () => ({
channel_id: '',
task_id: '',
user_id: '',
status: '',
action: '',
dateRange: getFreshDateRange(),
});
// 统一的 URL 双向同步字段列表,读取和写入用同一份,避免两处维护漂移
const URL_SYNC_FIELDS = [
'channel_id',
'task_id',
'user_id',
'status',
'action',
];
// URL → 初始表单值:支持直接粘贴包含过滤条件的链接,典型场景是管理员分享"查某用户的任务"
// 用 useRef 锁定挂载那一刻的 URL 值,避免每次 render 都重读 window.location(浪费 + 若后续被别处改写会漂移)
const initialFormValuesRef = useRef(null);
if (initialFormValuesRef.current === null) {
const fresh = getFreshInitValues();
if (typeof window !== 'undefined') {
const sp = new URLSearchParams(window.location.search);
URL_SYNC_FIELDS.forEach((key) => {
const v = sp.get(key);
if (v != null && v !== '') fresh[key] = v;
});
}
initialFormValuesRef.current = fresh;
}
const formInitValues = initialFormValuesRef.current;
// Column visibility state
const [visibleColumns, setVisibleColumns] = useState({});
const [showColumnSelector, setShowColumnSelector] = useState(false);
// Compact mode
const [compactMode, setCompactMode] = useTableCompactMode('taskLogs');
// Load saved column preferences from localStorage
useEffect(() => {
const savedColumns = localStorage.getItem(STORAGE_KEY);
if (savedColumns) {
try {
const parsed = JSON.parse(savedColumns);
const defaults = getDefaultColumnVisibility();
const merged = { ...defaults, ...parsed };
// For non-admin users, force-hide admin-only columns (does not touch admin settings)
if (!isAdminUser) {
merged[COLUMN_KEYS.CHANNEL] = false;
}
setVisibleColumns(merged);
} catch (e) {
console.error('Failed to parse saved column preferences', e);
initDefaultColumns();
}
} else {
initDefaultColumns();
}
}, []);
// Get default column visibility based on user role
const getDefaultColumnVisibility = () => {
return {
[COLUMN_KEYS.SUBMIT_TIME]: true,
[COLUMN_KEYS.FINISH_TIME]: true,
[COLUMN_KEYS.DURATION]: true,
[COLUMN_KEYS.CHANNEL]: isAdminUser,
[COLUMN_KEYS.PLATFORM]: true,
[COLUMN_KEYS.TYPE]: true,
[COLUMN_KEYS.MODEL]: true,
[COLUMN_KEYS.TASK_ID]: true,
[COLUMN_KEYS.TASK_STATUS]: true,
[COLUMN_KEYS.PROGRESS]: true,
[COLUMN_KEYS.QUOTA]: true,
[COLUMN_KEYS.FAIL_REASON]: true,
};
};
// Initialize default column visibility
const initDefaultColumns = () => {
const defaults = getDefaultColumnVisibility();
setVisibleColumns(defaults);
localStorage.setItem(STORAGE_KEY, JSON.stringify(defaults));
};
// Handle column visibility change
const handleColumnVisibilityChange = (columnKey, checked) => {
const updatedColumns = { ...visibleColumns, [columnKey]: checked };
setVisibleColumns(updatedColumns);
};
// Handle "Select All" checkbox
const handleSelectAll = (checked) => {
const allKeys = Object.keys(COLUMN_KEYS).map((key) => COLUMN_KEYS[key]);
const updatedColumns = {};
allKeys.forEach((key) => {
if (key === COLUMN_KEYS.CHANNEL && !isAdminUser) {
updatedColumns[key] = false;
} else {
updatedColumns[key] = checked;
}
});
setVisibleColumns(updatedColumns);
};
// Persist column settings to the role-specific STORAGE_KEY
useEffect(() => {
if (Object.keys(visibleColumns).length > 0) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(visibleColumns));
}
}, [visibleColumns]);
// Get form values helper function
const getFormValues = () => {
// formApi 尚未注册时(首次挂载后、Form 回调前的短窗口),回落到初始 URL 派生值
// 否则 URL 带的 ?task_id=xxx 在第一次 loadLogs 时会被当成空字符串,导致初始列表不过滤
const formValues = formApi ? formApi.getValues() : formInitValues;
// 处理时间范围:每次调用时取"此刻"的默认值,避免闭包陈旧
const [freshStart, freshEnd] = getFreshDateRange();
let start_timestamp = freshStart;
let end_timestamp = freshEnd;
if (
formValues.dateRange &&
Array.isArray(formValues.dateRange) &&
formValues.dateRange.length === 2
) {
start_timestamp = formValues.dateRange[0];
end_timestamp = formValues.dateRange[1];
}
// 所有字符串字段做 trim,避免复制粘贴带上首尾空格导致精确匹配失败
return {
channel_id: (formValues.channel_id || '').trim(),
task_id: (formValues.task_id || '').trim(),
// user_id 仅管理员表单有,非管理员下默认 '' ;剥离非数字兼容 IME 粘贴
user_id: (formValues.user_id || '').toString().replace(/\D/g, ''),
status: (formValues.status || '').trim(),
action: (formValues.action || '').trim(),
start_timestamp,
end_timestamp,
};
};
// Enrich logs data
const enrichLogs = (items) => {
if (!Array.isArray(items)) return [];
return items.map((log) => ({
...log,
timestamp2string: timestamp2string(log.created_at),
key: '' + log.id,
}));
};
// 上一次数据中各任务的 status,用于检测"新完成"的任务
const prevStatusMapRef = useRef({});
// Sync page data
const syncPageData = (payload) => {
const items = enrichLogs(payload?.items || []);
// 检测终态转变(SUCCESS / FAILURE)——新完成的任务会触发后端生成使用日志,
// 发事件让 usage-logs 统计即时刷新,避免用户切到使用日志 tab 时看到陈旧数据
const prev = prevStatusMapRef.current;
const TERMINAL = new Set(['SUCCESS', 'FAILURE']);
const nextMap = {};
let anyJustCompleted = false;
items.forEach((it) => {
nextMap[it.id] = it.status;
if (
TERMINAL.has(it.status) &&
prev[it.id] !== undefined &&
!TERMINAL.has(prev[it.id])
) {
anyJustCompleted = true;
}
});
prevStatusMapRef.current = nextMap;
if (anyJustCompleted) {
emit(EVENTS.TASK_COMPLETED);
}
setLogs(items);
setLogCount(payload?.total || 0);
setActivePage(payload?.page || 1);
setPageSize(payload?.page_size || pageSize);
};
// 请求序列号:后发起的请求获得更大的 id,异步回来时丢弃已过期响应
// 避免快速翻页/切换过滤条件时,慢响应覆盖最新结果
const requestIdRef = useRef(0);
// Load logs function
// silent=true 时用于后台轮询,不触发 loading spinner,避免表格每 10s 闪烁
const loadLogs = async (page = 1, size = pageSize, silent = false) => {
const reqId = ++requestIdRef.current;
if (!silent) setLoading(true);
const {
channel_id,
task_id,
user_id,
status,
action,
start_timestamp,
end_timestamp,
} = getFormValues();
let localStartTimestamp = parseInt(Date.parse(start_timestamp) / 1000);
let localEndTimestamp = parseInt(Date.parse(end_timestamp) / 1000);
// 时间范围校验:起始晚于结束视为非法,避免白发一轮请求并给出提示
if (
Number.isFinite(localStartTimestamp) &&
Number.isFinite(localEndTimestamp) &&
localStartTimestamp > localEndTimestamp
) {
if (!silent) {
showError(t('开始时间不能晚于结束时间'));
if (reqId === requestIdRef.current) setLoading(false);
}
return;
}
const params = new URLSearchParams({
p: page,
page_size: size,
task_id,
start_timestamp: localStartTimestamp,
end_timestamp: localEndTimestamp,
});
// 空值不带到 URL,保持 query 简洁,也避免后端误把空串当作精确匹配
if (status) params.set('status', status);
if (action) params.set('action', action);
if (isAdminUser) {
params.set('channel_id', channel_id);
// 与使用日志对齐:管理员可按 user_id 过滤任务日志
if (user_id) params.set('user_id', user_id);
}
const url = isAdminUser
? `/api/task/?${params.toString()}`
: `/api/task/self?${params.toString()}`;
try {
const res = await API.get(url);
// 过时响应直接丢弃:reqId 小于最新值说明更新的请求已经发出
if (reqId !== requestIdRef.current) return;
const { success, message, data } = res.data;
if (success) {
syncPageData(data);
} else if (!silent) {
showError(message);
}
} catch (err) {
if (reqId !== requestIdRef.current) return;
if (!silent) showError(err);
} finally {
// 只有当自己仍是最新请求时才结束 loading,防止旧请求提前关闭 spinner
if (!silent && reqId === requestIdRef.current) setLoading(false);
}
};
// Page handlers
const handlePageChange = (page) => {
loadLogs(page, pageSize).then();
};
const handlePageSizeChange = async (size) => {
localStorage.setItem('task-page-size', size + '');
await loadLogs(1, size);
};
// 把当前表单过滤条件同步到浏览器 URL,便于用户分享链接
// 只写入非空值,保持 URL 简洁;tab 和 utm_* 等其他 query 参数原样保留
const syncFiltersToUrl = () => {
if (typeof window === 'undefined') return;
const formValues = formApi ? formApi.getValues() : {};
const sp = new URLSearchParams(window.location.search);
URL_SYNC_FIELDS.forEach((key) => {
const v = (formValues[key] || '').toString().trim();
if (v) sp.set(key, v);
else sp.delete(key);
});
const newQuery = sp.toString();
const newUrl =
window.location.pathname +
(newQuery ? '?' + newQuery : '') +
window.location.hash;
// replaceState:不新增历史记录项,避免每次查询都污染后退栈
window.history.replaceState({}, '', newUrl);
};
// Refresh function
const refresh = async () => {
syncFiltersToUrl();
await loadLogs(1, pageSize);
};
// Copy text function
const copyText = async (text) => {
if (await copy(text)) {
showSuccess(t('已复制:') + text);
} else {
Modal.error({ title: t('无法复制到剪贴板,请手动复制'), content: text });
}
};
// Modal handlers
const openContentModal = (content) => {
setModalContent(content);
setIsModalOpen(true);
};
// 新增:打开视频预览弹窗
// proxyUrl 是播放用的代理地址;sourceUrl 是上游可分享 URL(可选)
const openVideoModal = (proxyUrl, sourceUrl = '') => {
setVideoUrl(proxyUrl);
setVideoSourceUrl(sourceUrl || proxyUrl);
setIsVideoModalOpen(true);
};
// Initialize data
useEffect(() => {
const localPageSize =
parseInt(localStorage.getItem('task-page-size')) || ITEMS_PER_PAGE;
setPageSize(localPageSize);
loadLogs(1, localPageSize).then();
}, []);
// 存在进行中的任务时,自动轮询刷新(10s 间隔),无 pending 则停止,避免无谓请求
const loadLogsRef = useRef(loadLogs);
loadLogsRef.current = loadLogs;
// 派生稳定布尔值:只在"是否存在 pending 任务"真正翻转时才变
// 避免每次静默刷新 logs 引用变化都导致 interval 被清理 + 重建,使 10s 间隔不稳定
const hasPending = useMemo(
() =>
logs.some(
(log) =>
log.status === 'IN_PROGRESS' ||
log.status === 'SUBMITTED' ||
log.status === 'QUEUED' ||
!log.status,
),
[logs],
);
useEffect(() => {
if (!hasPending) return undefined;
const tick = () => {
// 浏览器标签不可见时跳过一轮,避免用户离开页面后继续白白打后端
// (用户切回来时 visibilitychange 会立即触发一次补刷新)
if (typeof document !== 'undefined' && document.hidden) return;
// silent=true:后台静默刷新,不弹 loading、不弹错误提示
loadLogsRef.current(activePage, pageSize, true);
};
const timer = setInterval(tick, 10000);
const onVis = () => {
if (typeof document !== 'undefined' && !document.hidden) tick();
};
if (typeof document !== 'undefined') {
document.addEventListener('visibilitychange', onVis);
}
return () => {
clearInterval(timer);
if (typeof document !== 'undefined') {
document.removeEventListener('visibilitychange', onVis);
}
};
}, [hasPending, activePage, pageSize]);
return {
// Basic state
logs,
loading,
activePage,
logCount,
pageSize,
isAdminUser,
// Modal state
isModalOpen,
setIsModalOpen,
modalContent,
// 新增:视频弹窗状态
isVideoModalOpen,
setIsVideoModalOpen,
videoUrl,
videoSourceUrl,
// Form state
formApi,
setFormApi,
formInitValues,
getFormValues,
getFreshInitValues,
// Column visibility
visibleColumns,
showColumnSelector,
setShowColumnSelector,
handleColumnVisibilityChange,
handleSelectAll,
initDefaultColumns,
COLUMN_KEYS,
// Compact mode
compactMode,
setCompactMode,
// Functions
loadLogs,
handlePageChange,
handlePageSizeChange,
refresh,
copyText,
openContentModal,
openVideoModal, // 新增
enrichLogs,
syncPageData,
// Translation
t,
};
};
+392
View File
@@ -0,0 +1,392 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { Modal } from '@douyinfe/semi-ui';
import {
API,
copy,
showError,
showSuccess,
encodeToBase64,
} from '../../helpers';
import { useTableCompactMode } from '../common/useTableCompactMode';
export const useTokensData = (openFluentNotification) => {
const { t } = useTranslation();
// Basic state
const [tokens, setTokens] = useState([]);
const [loading, setLoading] = useState(true);
const [activePage, setActivePage] = useState(1);
const [tokenCount, setTokenCount] = useState(0);
const [pageSize, setPageSize] = useState(5);
const [searching, setSearching] = useState(false);
// Selection state
const [selectedKeys, setSelectedKeys] = useState([]);
// Edit state
const [showEdit, setShowEdit] = useState(false);
const [editingToken, setEditingToken] = useState({
id: undefined,
});
// UI state
const [compactMode, setCompactMode] = useTableCompactMode('tokens');
const [showKeys, setShowKeys] = useState({});
// Form state
const [formApi, setFormApi] = useState(null);
const formInitValues = {
searchKeyword: '',
searchToken: '',
};
// Get form values helper function
const getFormValues = () => {
const formValues = formApi ? formApi.getValues() : {};
return {
searchKeyword: formValues.searchKeyword || '',
searchToken: formValues.searchToken || '',
};
};
// Close edit modal
const closeEdit = () => {
setShowEdit(false);
setTimeout(() => {
setEditingToken({
id: undefined,
});
}, 500);
};
// Sync page data from API response
const syncPageData = (payload) => {
setTokens(payload.items || []);
setTokenCount(payload.total || 0);
setActivePage(payload.page || 1);
setPageSize(payload.page_size || pageSize);
};
// Load tokens function
const loadTokens = async (page = 1, size = pageSize) => {
setLoading(true);
const res = await API.get(`/api/token/?p=${page}&size=${size}`);
const { success, message, data } = res.data;
if (success) {
syncPageData(data);
} else {
showError(message);
}
setLoading(false);
};
// Refresh function
const refresh = async (page = activePage) => {
await loadTokens(page);
setSelectedKeys([]);
};
// Copy text function
const copyText = async (text) => {
if (await copy(text)) {
showSuccess(t('已复制到剪贴板!'));
} else {
Modal.error({
title: t('无法复制到剪贴板,请手动复制'),
content: text,
size: 'large',
});
}
};
// Open link function for chat integrations
const onOpenLink = async (type, url, record) => {
if (url && url.startsWith('fluent')) {
openFluentNotification(record.key);
return;
}
let status = localStorage.getItem('status');
let serverAddress = '';
if (status) {
status = JSON.parse(status);
serverAddress = status.server_address;
}
if (serverAddress === '') {
serverAddress = window.location.origin;
}
if (url.includes('{cherryConfig}') === true) {
let cherryConfig = {
id: 'new-api',
baseUrl: serverAddress,
apiKey: 'sk-' + record.key,
};
let encodedConfig = encodeURIComponent(
encodeToBase64(JSON.stringify(cherryConfig)),
);
url = url.replaceAll('{cherryConfig}', encodedConfig);
} else {
let encodedServerAddress = encodeURIComponent(serverAddress);
url = url.replaceAll('{address}', encodedServerAddress);
url = url.replaceAll('{key}', 'sk-' + record.key);
}
window.open(url, '_blank');
};
// Manage token function (delete, enable, disable)
const manageToken = async (id, action, record) => {
setLoading(true);
let data = { id };
let res;
switch (action) {
case 'delete':
res = await API.delete(`/api/token/${id}/`);
break;
case 'enable':
data.status = 1;
res = await API.put('/api/token/?status_only=true', data);
break;
case 'disable':
data.status = 2;
res = await API.put('/api/token/?status_only=true', data);
break;
}
const { success, message } = res.data;
if (success) {
showSuccess(t('操作成功完成!'));
let token = res.data.data;
let newTokens = [...tokens];
if (action !== 'delete') {
record.status = token.status;
}
setTokens(newTokens);
} else {
showError(message);
}
setLoading(false);
};
// Search tokens function
const searchTokens = async () => {
const { searchKeyword, searchToken } = getFormValues();
if (searchKeyword === '' && searchToken === '') {
await loadTokens(1);
return;
}
setSearching(true);
const res = await API.get(
`/api/token/search?keyword=${searchKeyword}&token=${searchToken}`,
);
const { success, message, data } = res.data;
if (success) {
setTokens(data);
setTokenCount(data.length);
setActivePage(1);
} else {
showError(message);
}
setSearching(false);
};
// Sort tokens function
const sortToken = (key) => {
if (tokens.length === 0) return;
setLoading(true);
let sortedTokens = [...tokens];
sortedTokens.sort((a, b) => {
return ('' + a[key]).localeCompare(b[key]);
});
if (sortedTokens[0].id === tokens[0].id) {
sortedTokens.reverse();
}
setTokens(sortedTokens);
setLoading(false);
};
// Page handlers
const handlePageChange = (page) => {
loadTokens(page, pageSize).then();
};
const handlePageSizeChange = async (size) => {
setPageSize(size);
await loadTokens(1, size);
};
// Row selection handlers
const rowSelection = {
onSelect: (record, selected) => {},
onSelectAll: (selected, selectedRows) => {},
onChange: (selectedRowKeys, selectedRows) => {
setSelectedKeys(selectedRows);
},
};
// Handle row styling
const handleRow = (record, index) => {
if (record.status !== 1) {
return {
style: {
background: 'var(--semi-color-disabled-border)',
},
};
} else {
return {};
}
};
// Batch delete tokens
const batchDeleteTokens = async () => {
if (selectedKeys.length === 0) {
showError(t('请先选择要删除的令牌!'));
return;
}
setLoading(true);
try {
const ids = selectedKeys.map((token) => token.id);
const res = await API.post('/api/token/batch', { ids });
if (res?.data?.success) {
const count = res.data.data || 0;
showSuccess(t('已删除 {{count}} 个令牌!', { count }));
await refresh();
setTimeout(() => {
if (tokens.length === 0 && activePage > 1) {
refresh(activePage - 1);
}
}, 100);
} else {
showError(res?.data?.message || t('删除失败'));
}
} catch (error) {
showError(error.message);
} finally {
setLoading(false);
}
};
// Batch copy tokens
const batchCopyTokens = (copyType) => {
if (selectedKeys.length === 0) {
showError(t('请至少选择一个令牌!'));
return;
}
Modal.info({
title: t('复制令牌'),
icon: null,
content: t('请选择你的复制方式'),
footer: (
<div className='flex gap-2'>
<button
className='px-3 py-1 bg-gray-200 rounded'
onClick={async () => {
let content = '';
for (let i = 0; i < selectedKeys.length; i++) {
content +=
selectedKeys[i].name + ' sk-' + selectedKeys[i].key + '\n';
}
await copyText(content);
Modal.destroyAll();
}}
>
{t('名称+密钥')}
</button>
<button
className='px-3 py-1 bg-blue-500 text-white rounded'
onClick={async () => {
let content = '';
for (let i = 0; i < selectedKeys.length; i++) {
content += 'sk-' + selectedKeys[i].key + '\n';
}
await copyText(content);
Modal.destroyAll();
}}
>
{t('仅密钥')}
</button>
</div>
),
});
};
// Initialize data
useEffect(() => {
loadTokens(1)
.then()
.catch((reason) => {
showError(reason);
});
}, [pageSize]);
return {
// Basic state
tokens,
loading,
activePage,
tokenCount,
pageSize,
searching,
// Selection state
selectedKeys,
setSelectedKeys,
// Edit state
showEdit,
setShowEdit,
editingToken,
setEditingToken,
closeEdit,
// UI state
compactMode,
setCompactMode,
showKeys,
setShowKeys,
// Form state
formApi,
setFormApi,
formInitValues,
getFormValues,
// Functions
loadTokens,
refresh,
copyText,
onOpenLink,
manageToken,
searchTokens,
sortToken,
handlePageChange,
handlePageSizeChange,
rowSelection,
handleRow,
batchDeleteTokens,
batchCopyTokens,
syncPageData,
// Translation
t,
};
};
+766
View File
@@ -0,0 +1,766 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { Modal } from '@douyinfe/semi-ui';
import {
API,
getTodayStartTimestamp,
isAdmin,
isRoot,
showError,
showSuccess,
timestamp2string,
getLogOther,
copy,
} from '../../helpers';
import { ITEMS_PER_PAGE } from '../../constants';
import { useTableCompactMode } from '../common/useTableCompactMode';
import { EVENTS, subscribe } from '../../helpers/eventBus';
export const useLogsData = () => {
const { t } = useTranslation();
// Define column keys for selection
const COLUMN_KEYS = {
TIME: 'time',
CHANNEL: 'channel',
USERNAME: 'username',
TOKEN: 'token',
GROUP: 'group',
TYPE: 'type',
MODEL: 'model',
USE_TIME: 'use_time',
PROMPT: 'prompt',
COMPLETION: 'completion',
COST: 'cost',
RETRY: 'retry',
IP: 'ip',
DETAILS: 'details',
};
// Basic state
const [logs, setLogs] = useState([]);
const [expandData, setExpandData] = useState({});
const [showStat, setShowStat] = useState(false);
const [loading, setLoading] = useState(false);
const [loadingStat, setLoadingStat] = useState(false);
const [activePage, setActivePage] = useState(1);
const [logCount, setLogCount] = useState(0);
const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
// logType 由表单管理(field='logType'),不再维护独立的 React state —— 避免双真源导致的刷新时机错位
// User and admin
const isAdminUser = isAdmin();
const isRootUser = isRoot();
// Role-specific storage key to prevent different roles from overwriting each other
const STORAGE_KEY = isAdminUser
? 'logs-table-columns-admin'
: 'logs-table-columns-user';
// Statistics state
const [stat, setStat] = useState({
quota: 0,
rpm: 0,
tpm: 0,
});
// Form state
const [formApi, setFormApi] = useState(null);
// 每次调用都返回"此刻"的默认时间范围,避免长时间驻留页面后
// 点击"重置"仍得到页面加载时的"今日"(跨日 bug)
const getFreshDateRange = () => [
timestamp2string(getTodayStartTimestamp()),
timestamp2string(new Date().getTime() / 1000 + 3600),
];
const getFreshInitValues = () => ({
username: '',
token_name: '',
model_name: '',
channel: '',
group: '',
user_id: '',
dateRange: getFreshDateRange(),
logType: '0',
});
// URL → 初始表单值:支持分享携带过滤条件的链接
// 与 task-logs 的字段不同前缀/冲突:channel vs channel_id、user_id 两边都会读
const URL_SYNC_FIELDS = [
'username',
'token_name',
'model_name',
'channel',
'group',
'user_id',
'logType',
];
// 用 ref 锁定挂载时刻的 URL 值,后续 render 不再重读 window.location
const initialFormValuesRef = useRef(null);
if (initialFormValuesRef.current === null) {
const fresh = getFreshInitValues();
if (typeof window !== 'undefined') {
const sp = new URLSearchParams(window.location.search);
URL_SYNC_FIELDS.forEach((key) => {
const v = sp.get(key);
if (v != null && v !== '') fresh[key] = v;
});
// 错误日志仅管理员可见:非管理员经分享链接携带 logType=5 时归一化回"全部"
if (!isAdminUser && fresh.logType === '5') fresh.logType = '0';
}
initialFormValuesRef.current = fresh;
}
const formInitValues = initialFormValuesRef.current;
// Column visibility state
const [visibleColumns, setVisibleColumns] = useState({});
const [showColumnSelector, setShowColumnSelector] = useState(false);
// Compact mode
const [compactMode, setCompactMode] = useTableCompactMode('logs');
// User info modal state
const [showUserInfo, setShowUserInfoModal] = useState(false);
const [userInfoData, setUserInfoData] = useState(null);
// 导出弹窗状态
const [showExportModal, setShowExportModal] = useState(false);
// 记录「最近一次成功查询」所用的筛选条件,导出「全部筛选结果」时复用,
// 确保导出结果与当前表格展示(及统计总数 logCount)严格一致,
// 而非读取可能被编辑却未点「查询」的实时表单值
const appliedExportParamsRef = useRef(null);
// 按当前已应用筛选条件拉取用于导出的全部日志(不分页,后端最多返回 logExportLimit 条)
// 返回 { items, total, limit, truncated } 或 null(失败/尚未查询)
const fetchLogsForExport = async () => {
const applied = appliedExportParamsRef.current;
if (!applied) {
showError(t('请先查询后再导出'));
return null;
}
const params = new URLSearchParams({
type: applied.type || 0,
token_name: applied.token_name,
model_name: applied.model_name,
start_timestamp: applied.start_timestamp,
end_timestamp: applied.end_timestamp,
group: applied.group,
});
let url;
if (isAdminUser) {
params.set('username', applied.username);
params.set('channel', applied.channel);
params.set('user_id', applied.user_id);
url = `/api/log/export?${params.toString()}`;
} else {
url = `/api/log/self/export?${params.toString()}`;
}
try {
const res = await API.get(url);
const { success, message, data } = res.data;
if (!success) {
showError(message);
return null;
}
return data;
} catch (err) {
showError(err.message);
return null;
}
};
// Load saved column preferences from localStorage
useEffect(() => {
const savedColumns = localStorage.getItem(STORAGE_KEY);
if (savedColumns) {
try {
const parsed = JSON.parse(savedColumns);
const defaults = getDefaultColumnVisibility();
const merged = { ...defaults, ...parsed };
// For non-admin users, force-hide admin-only columns (does not touch admin settings)
if (!isAdminUser) {
merged[COLUMN_KEYS.CHANNEL] = false;
merged[COLUMN_KEYS.USERNAME] = false;
merged[COLUMN_KEYS.RETRY] = false;
}
setVisibleColumns(merged);
} catch (e) {
console.error('Failed to parse saved column preferences', e);
initDefaultColumns();
}
} else {
initDefaultColumns();
}
}, []);
// Get default column visibility based on user role
const getDefaultColumnVisibility = () => {
return {
[COLUMN_KEYS.TIME]: true,
[COLUMN_KEYS.CHANNEL]: isAdminUser,
[COLUMN_KEYS.USERNAME]: isAdminUser,
[COLUMN_KEYS.TOKEN]: true,
[COLUMN_KEYS.GROUP]: true,
[COLUMN_KEYS.TYPE]: true,
[COLUMN_KEYS.MODEL]: true,
[COLUMN_KEYS.USE_TIME]: true,
[COLUMN_KEYS.PROMPT]: true,
[COLUMN_KEYS.COMPLETION]: true,
[COLUMN_KEYS.COST]: true,
[COLUMN_KEYS.RETRY]: isAdminUser,
[COLUMN_KEYS.IP]: true,
[COLUMN_KEYS.DETAILS]: true,
};
};
// Initialize default column visibility
const initDefaultColumns = () => {
const defaults = getDefaultColumnVisibility();
setVisibleColumns(defaults);
localStorage.setItem(STORAGE_KEY, JSON.stringify(defaults));
};
// Handle column visibility change
const handleColumnVisibilityChange = (columnKey, checked) => {
const updatedColumns = { ...visibleColumns, [columnKey]: checked };
setVisibleColumns(updatedColumns);
};
// Handle "Select All" checkbox
const handleSelectAll = (checked) => {
const allKeys = Object.keys(COLUMN_KEYS).map((key) => COLUMN_KEYS[key]);
const updatedColumns = {};
allKeys.forEach((key) => {
if (
(key === COLUMN_KEYS.CHANNEL ||
key === COLUMN_KEYS.USERNAME ||
key === COLUMN_KEYS.RETRY) &&
!isAdminUser
) {
updatedColumns[key] = false;
} else {
updatedColumns[key] = checked;
}
});
setVisibleColumns(updatedColumns);
};
// Persist column settings to the role-specific STORAGE_KEY
useEffect(() => {
if (Object.keys(visibleColumns).length > 0) {
localStorage.setItem(STORAGE_KEY, JSON.stringify(visibleColumns));
}
}, [visibleColumns]);
// 获取表单值的辅助函数,确保所有值都是字符串
const getFormValues = () => {
// formApi 未就绪时回落到 URL 派生的初始值,避免首次 loadLogs 丢掉 ?username=xxx 等过滤条件
const formValues = formApi ? formApi.getValues() : formInitValues;
// 每次调用取"此刻"的默认值,避免闭包陈旧
const [freshStart, freshEnd] = getFreshDateRange();
let start_timestamp = freshStart;
let end_timestamp = freshEnd;
if (
formValues.dateRange &&
Array.isArray(formValues.dateRange) &&
formValues.dateRange.length === 2
) {
start_timestamp = formValues.dateRange[0];
end_timestamp = formValues.dateRange[1];
}
// 所有字符串字段做 trim,避免复制粘贴带上首尾空格导致精确匹配失败
return {
username: (formValues.username || '').trim(),
token_name: (formValues.token_name || '').trim(),
model_name: (formValues.model_name || '').trim(),
start_timestamp,
end_timestamp,
channel: (formValues.channel || '').trim(),
group: (formValues.group || '').trim(),
// user_id 额外剥离非数字(兼容 IME/中文输入法粘贴绕过 onKeyDown)
user_id: (formValues.user_id || '').toString().replace(/\D/g, ''),
logType: formValues.logType ? parseInt(formValues.logType) : 0,
};
};
// Statistics functions
const getLogSelfStat = async () => {
const {
token_name,
model_name,
start_timestamp,
end_timestamp,
group,
logType: formLogType,
} = getFormValues();
// 表单是唯一真源:getFormValues 已保证返回数字,未定义则为 0
const currentLogType = formLogType || 0;
let localStartTimestamp = Date.parse(start_timestamp) / 1000;
let localEndTimestamp = Date.parse(end_timestamp) / 1000;
const params = new URLSearchParams({
type: currentLogType,
token_name,
model_name,
start_timestamp: localStartTimestamp,
end_timestamp: localEndTimestamp,
group,
});
const url = `/api/log/self/stat?${params.toString()}`;
let res = await API.get(url);
const { success, message, data } = res.data;
if (success) {
setStat(data);
} else {
showError(message);
}
};
const getLogStat = async () => {
const {
username,
token_name,
model_name,
start_timestamp,
end_timestamp,
channel,
group,
user_id,
logType: formLogType,
} = getFormValues();
// 表单唯一真源
const currentLogType = formLogType || 0;
let localStartTimestamp = Date.parse(start_timestamp) / 1000;
let localEndTimestamp = Date.parse(end_timestamp) / 1000;
const params = new URLSearchParams({
type: currentLogType,
username,
token_name,
model_name,
start_timestamp: localStartTimestamp,
end_timestamp: localEndTimestamp,
channel,
group,
user_id,
});
const url = `/api/log/stat?${params.toString()}`;
let res = await API.get(url);
const { success, message, data } = res.data;
if (success) {
setStat(data);
} else {
showError(message);
}
};
const handleEyeClick = async () => {
if (loadingStat) {
return;
}
setLoadingStat(true);
if (isAdminUser) {
await getLogStat();
} else {
await getLogSelfStat();
}
setShowStat(true);
setLoadingStat(false);
};
// User info function
const showUserInfoFunc = async (userId) => {
if (!isAdminUser) {
return;
}
const res = await API.get(`/api/user/${userId}`);
const { success, message, data } = res.data;
if (success) {
setUserInfoData(data);
setShowUserInfoModal(true);
} else {
showError(message);
}
};
// Format logs data
const setLogsFormat = (logs) => {
let expandDatesLocal = {};
for (let i = 0; i < logs.length; i++) {
logs[i].timestamp2string = timestamp2string(logs[i].created_at);
logs[i].key = logs[i].id;
let other = getLogOther(logs[i].other);
let expandDataLocal = [];
if (isAdminUser && (logs[i].type === 0 || logs[i].type === 2)) {
expandDataLocal.push({
key: t('渠道信息'),
value: `${logs[i].channel} - ${logs[i].channel_name || '[未知]'}`,
});
}
if (other?.ws || other?.audio) {
expandDataLocal.push({
key: t('语音输入'),
value: other.audio_input,
});
expandDataLocal.push({
key: t('语音输出'),
value: other.audio_output,
});
expandDataLocal.push({
key: t('文字输入'),
value: other.text_input,
});
expandDataLocal.push({
key: t('文字输出'),
value: other.text_output,
});
}
if (other?.cache_tokens > 0) {
expandDataLocal.push({
key: t('缓存 Tokens'),
value: other.cache_tokens,
});
}
if (other?.cache_creation_tokens > 0) {
expandDataLocal.push({
key: t('缓存创建 Tokens'),
value: other.cache_creation_tokens,
});
}
if (logs[i].type === 2) {
expandDataLocal.push({
key: t('日志详情'),
value: t('查看简化计费摘要'),
});
if (logs[i]?.content) {
expandDataLocal.push({
key: t('其他详情'),
value: logs[i].content,
});
}
}
if (logs[i].type === 2) {
let modelMapped =
other?.is_model_mapped &&
other?.upstream_model_name &&
other?.upstream_model_name !== '';
if (isRootUser && modelMapped) {
expandDataLocal.push({
key: t('请求并计费模型'),
value: logs[i].model_name,
});
expandDataLocal.push({
key: t('实际模型'),
value: other.upstream_model_name,
});
}
expandDataLocal.push({
key: t('计费过程'),
value: t('已切换为摘要展示'),
});
if (other?.reasoning_effort) {
expandDataLocal.push({
key: t('Reasoning Effort'),
value: other.reasoning_effort,
});
}
}
if (other?.request_path) {
expandDataLocal.push({
key: t('请求路径'),
value: other.request_path,
});
}
if (isAdminUser) {
let localCountMode = '';
if (other?.admin_info?.local_count_tokens) {
localCountMode = t('本地计费');
} else {
localCountMode = t('上游返回');
}
expandDataLocal.push({
key: t('计费模式'),
value: localCountMode,
});
}
expandDatesLocal[logs[i].key] = expandDataLocal;
}
setExpandData(expandDatesLocal);
setLogs(logs);
};
// 请求序列号:丢弃乱序回来的过期响应,防止旧结果覆盖新结果
const logsRequestIdRef = useRef(0);
// Load logs function
const loadLogs = async (startIdx, pageSize, customLogType = null) => {
const reqId = ++logsRequestIdRef.current;
setLoading(true);
let url = '';
const {
username,
token_name,
model_name,
start_timestamp,
end_timestamp,
channel,
group,
user_id,
logType: formLogType,
} = getFormValues();
// 表单是 logType 的唯一真源;customLogType 仍保留用于显式覆盖(外部传参场景)
const currentLogType =
customLogType !== null ? customLogType : formLogType || 0;
let localStartTimestamp = Date.parse(start_timestamp) / 1000;
let localEndTimestamp = Date.parse(end_timestamp) / 1000;
// 时间范围校验:起始晚于结束直接提示并中止,避免无意义请求
if (
Number.isFinite(localStartTimestamp) &&
Number.isFinite(localEndTimestamp) &&
localStartTimestamp > localEndTimestamp
) {
showError(t('开始时间不能晚于结束时间'));
if (reqId === logsRequestIdRef.current) setLoading(false);
return;
}
if (isAdminUser) {
const params = new URLSearchParams({
p: startIdx,
page_size: pageSize,
type: currentLogType,
username,
token_name,
model_name,
start_timestamp: localStartTimestamp,
end_timestamp: localEndTimestamp,
channel,
group,
user_id,
});
url = `/api/log/?${params.toString()}`;
} else {
const params = new URLSearchParams({
p: startIdx,
page_size: pageSize,
type: currentLogType,
token_name,
model_name,
start_timestamp: localStartTimestamp,
end_timestamp: localEndTimestamp,
group,
});
url = `/api/log/self?${params.toString()}`;
}
const res = await API.get(url);
// 丢弃过期响应,只处理仍然是最新的请求
if (reqId !== logsRequestIdRef.current) return;
const { success, message, data } = res.data;
if (success) {
const newPageData = Array.isArray(data?.items) ? data.items : [];
setActivePage(data?.page || 1);
setPageSize(data?.page_size || pageSize);
setLogCount(data?.total || 0);
// 记录本次成功查询的筛选条件(与展示数据/总数一致),供「导出全部筛选结果」复用
appliedExportParamsRef.current = {
username,
token_name,
model_name,
start_timestamp: localStartTimestamp,
end_timestamp: localEndTimestamp,
channel,
group,
user_id,
type: currentLogType,
};
setLogsFormat(newPageData);
} else {
showError(message);
}
if (reqId === logsRequestIdRef.current) setLoading(false);
};
// Page handlers
const handlePageChange = (page) => {
setActivePage(page);
loadLogs(page, pageSize).then((r) => {});
};
const handlePageSizeChange = async (size) => {
localStorage.setItem('page-size', size + '');
setPageSize(size);
setActivePage(1);
loadLogs(1, size)
.then()
.catch((reason) => {
showError(reason);
});
};
// 同步表单筛选到 URL,支持分享;只覆盖 URL_SYNC_FIELDS,不触碰 tab/utm_*
const syncFiltersToUrl = () => {
if (typeof window === 'undefined') return;
const formValues = formApi ? formApi.getValues() : {};
const sp = new URLSearchParams(window.location.search);
URL_SYNC_FIELDS.forEach((key) => {
const v = (formValues[key] || '').toString().trim();
// logType 默认 '0',视为空不写入 URL
if (v && !(key === 'logType' && v === '0')) sp.set(key, v);
else sp.delete(key);
});
const newQuery = sp.toString();
const newUrl =
window.location.pathname +
(newQuery ? '?' + newQuery : '') +
window.location.hash;
window.history.replaceState({}, '', newUrl);
};
// Refresh function
const refresh = async () => {
syncFiltersToUrl();
setActivePage(1);
// 并行触发但等待两者完成,避免 stat 与 list 结果基于不同过滤条件导致错乱
await Promise.all([handleEyeClick(), loadLogs(1, pageSize)]);
};
// Copy text function
const copyText = async (e, text) => {
e.stopPropagation();
if (await copy(text)) {
showSuccess('已复制:' + text);
} else {
Modal.error({ title: t('无法复制到剪贴板,请手动复制'), content: text });
}
};
// Initialize data
useEffect(() => {
const localPageSize =
parseInt(localStorage.getItem('page-size')) || ITEMS_PER_PAGE;
setPageSize(localPageSize);
loadLogs(activePage, localPageSize)
.then()
.catch((reason) => {
showError(reason);
});
}, []);
// Initialize statistics when formApi is available
useEffect(() => {
if (formApi) {
handleEyeClick();
}
}, [formApi]);
// 订阅"任务完成"事件:任务转终态时后端会产生消费日志,这里跟随刷新
// 用 ref 保存最新的加载函数,避免依赖数组里塞太多 state 导致频繁重订阅
const refreshRef = useRef();
refreshRef.current = async () => {
// 只在 formApi 就绪时刷新,否则 loadLogs 拿不到过滤条件
if (!formApi) return;
await Promise.all([handleEyeClick(), loadLogs(activePage || 1, pageSize)]);
};
useEffect(() => {
const unsub = subscribe(EVENTS.TASK_COMPLETED, () => {
// 节流:任务完成事件可能在一轮轮询中批量出现
if (refreshRef.current) refreshRef.current();
});
return unsub;
}, []);
// Check if any record has expandable content
const hasExpandableRows = () => {
return logs.some(
(log) => expandData[log.key] && expandData[log.key].length > 0,
);
};
return {
// Basic state
logs,
expandData,
showStat,
loading,
loadingStat,
activePage,
logCount,
pageSize,
stat,
isAdminUser,
isRootUser,
// Form state
formApi,
setFormApi,
formInitValues,
getFormValues,
getFreshInitValues,
// Column visibility
visibleColumns,
showColumnSelector,
setShowColumnSelector,
handleColumnVisibilityChange,
handleSelectAll,
initDefaultColumns,
COLUMN_KEYS,
// Compact mode
compactMode,
setCompactMode,
// User info modal
showUserInfo,
setShowUserInfoModal,
userInfoData,
showUserInfoFunc,
// Export modal
showExportModal,
setShowExportModal,
fetchLogsForExport,
// Functions
loadLogs,
handlePageChange,
handlePageSizeChange,
refresh,
copyText,
handleEyeClick,
setLogsFormat,
hasExpandableRows,
// Translation
t,
};
};
+321
View File
@@ -0,0 +1,321 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect } from 'react';
import { useTranslation } from 'react-i18next';
import { API, showError, showSuccess } from '../../helpers';
import { ITEMS_PER_PAGE } from '../../constants';
import { useTableCompactMode } from '../common/useTableCompactMode';
export const useUsersData = () => {
const { t } = useTranslation();
const [compactMode, setCompactMode] = useTableCompactMode('users');
// State management
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
const [activePage, setActivePage] = useState(1);
const [pageSize, setPageSize] = useState(ITEMS_PER_PAGE);
const [searching, setSearching] = useState(false);
const [groupOptions, setGroupOptions] = useState([]);
const [userCount, setUserCount] = useState(0);
// Modal states
const [showAddUser, setShowAddUser] = useState(false);
const [showEditUser, setShowEditUser] = useState(false);
const [editingUser, setEditingUser] = useState({
id: undefined,
});
// Form initial values
const formInitValues = {
searchKeyword: '',
searchGroup: '',
};
// Form API reference
const [formApi, setFormApi] = useState(null);
// Get form values helper function
const getFormValues = () => {
const formValues = formApi ? formApi.getValues() : {};
return {
searchKeyword: formValues.searchKeyword || '',
searchGroup: formValues.searchGroup || '',
};
};
// Set user format with key field
const setUserFormat = (users) => {
for (let i = 0; i < users.length; i++) {
users[i].key = users[i].id;
}
setUsers(users);
};
// Load users data
const loadUsers = async (startIdx, pageSize) => {
setLoading(true);
const res = await API.get(`/api/user/?p=${startIdx}&page_size=${pageSize}`);
const { success, message, data } = res.data;
if (success) {
const newPageData = data.items;
setActivePage(data.page);
setUserCount(data.total);
setUserFormat(newPageData);
} else {
showError(message);
}
setLoading(false);
};
// Search users with keyword and group
const searchUsers = async (
startIdx,
pageSize,
searchKeyword = null,
searchGroup = null,
) => {
// If no parameters passed, get values from form
if (searchKeyword === null || searchGroup === null) {
const formValues = getFormValues();
searchKeyword = formValues.searchKeyword;
searchGroup = formValues.searchGroup;
}
if (searchKeyword === '' && searchGroup === '') {
// If keyword is blank, load files instead
await loadUsers(startIdx, pageSize);
return;
}
setSearching(true);
const res = await API.get(
`/api/user/search?keyword=${searchKeyword}&group=${searchGroup}&p=${startIdx}&page_size=${pageSize}`,
);
const { success, message, data } = res.data;
if (success) {
const newPageData = data.items;
setActivePage(data.page);
setUserCount(data.total);
setUserFormat(newPageData);
} else {
showError(message);
}
setSearching(false);
};
// Manage user operations (promote, demote, enable, disable, delete)
const manageUser = async (userId, action, record) => {
// Trigger loading state to force table re-render
setLoading(true);
const res = await API.post('/api/user/manage', {
id: userId,
action,
});
const { success, message } = res.data;
if (success) {
showSuccess(t('操作成功完成!'));
const user = res.data.data;
// Create a new array and new object to ensure React detects changes
const newUsers = users.map((u) => {
if (u.id === userId) {
if (action === 'delete') {
return { ...u, DeletedAt: new Date() };
}
return { ...u, status: user.status, role: user.role };
}
return u;
});
setUsers(newUsers);
} else {
showError(message);
}
setLoading(false);
};
const resetUserPasskey = async (user) => {
if (!user) {
return;
}
try {
const res = await API.delete(`/api/user/${user.id}/reset_passkey`);
const { success, message } = res.data;
if (success) {
showSuccess(t('Passkey 已重置'));
} else {
showError(message || t('操作失败,请重试'));
}
} catch (error) {
showError(t('操作失败,请重试'));
}
};
const resetUserTwoFA = async (user) => {
if (!user) {
return;
}
try {
const res = await API.delete(`/api/user/${user.id}/2fa`);
const { success, message } = res.data;
if (success) {
showSuccess(t('二步验证已重置'));
} else {
showError(message || t('操作失败,请重试'));
}
} catch (error) {
showError(t('操作失败,请重试'));
}
};
// Handle page change
const handlePageChange = (page) => {
setActivePage(page);
const { searchKeyword, searchGroup } = getFormValues();
if (searchKeyword === '' && searchGroup === '') {
loadUsers(page, pageSize).then();
} else {
searchUsers(page, pageSize, searchKeyword, searchGroup).then();
}
};
// Handle page size change
const handlePageSizeChange = async (size) => {
localStorage.setItem('page-size', size + '');
setPageSize(size);
setActivePage(1);
loadUsers(activePage, size)
.then()
.catch((reason) => {
showError(reason);
});
};
// Handle table row styling for disabled/deleted users
const handleRow = (record, index) => {
if (record.DeletedAt !== null || record.status !== 1) {
return {
style: {
background: 'var(--semi-color-disabled-border)',
},
};
} else {
return {};
}
};
// Refresh data
const refresh = async (page = activePage) => {
const { searchKeyword, searchGroup } = getFormValues();
if (searchKeyword === '' && searchGroup === '') {
await loadUsers(page, pageSize);
} else {
await searchUsers(page, pageSize, searchKeyword, searchGroup);
}
};
// Fetch groups data
const fetchGroups = async () => {
try {
let res = await API.get(`/api/group/`);
if (res === undefined) {
return;
}
setGroupOptions(
res.data.data.map((group) => ({
label: group,
value: group,
})),
);
} catch (error) {
showError(error.message);
}
};
// Modal control functions
const closeAddUser = () => {
setShowAddUser(false);
};
const closeEditUser = () => {
setShowEditUser(false);
setEditingUser({
id: undefined,
});
};
// Initialize data on component mount
useEffect(() => {
loadUsers(0, pageSize)
.then()
.catch((reason) => {
showError(reason);
});
fetchGroups().then();
}, []);
return {
// Data state
users,
loading,
activePage,
pageSize,
userCount,
searching,
groupOptions,
// Modal state
showAddUser,
showEditUser,
editingUser,
setShowAddUser,
setShowEditUser,
setEditingUser,
// Form state
formInitValues,
formApi,
setFormApi,
// UI state
compactMode,
setCompactMode,
// Actions
loadUsers,
searchUsers,
manageUser,
resetUserPasskey,
resetUserTwoFA,
handlePageChange,
handlePageSizeChange,
handleRow,
refresh,
closeAddUser,
closeEditUser,
getFormValues,
// Translation
t,
};
};
+213
View File
@@ -0,0 +1,213 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useCallback, useEffect, useRef, useState } from 'react';
import { API } from '../../helpers';
const errorCode = (error) => error?.response?.data?.error?.code || '';
const errorMessage = (error) =>
error?.response?.data?.error?.message || error?.message || '请求失败';
const readFileAsDataURL = (file) =>
new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(reader.result);
reader.onerror = reject;
reader.readAsDataURL(file);
});
export const usePortraitAssets = (open) => {
const [enabled, setEnabled] = useState(null);
const [loading, setLoading] = useState(false);
const [portraits, setPortraits] = useState([]);
const [assets, setAssets] = useState([]);
const [session, setSession] = useState(null);
const pollingRef = useRef(null);
const load = useCallback(async () => {
setLoading(true);
try {
const [portraitRes, assetRes] = await Promise.all([
API.get('/api/video/portraits', { skipErrorHandler: true }),
API.get('/api/video/assets?limit=100', { skipErrorHandler: true }),
]);
setEnabled(true);
setPortraits(portraitRes.data?.data || []);
setAssets(
(assetRes.data?.data || []).filter(
(asset) => asset.identity_type === 'real_person',
),
);
} catch (error) {
if (errorCode(error) === 'real_portrait_disabled') {
setEnabled(false);
} else {
throw error;
}
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
if (open) load().catch(() => {});
}, [open, load]);
const stopPolling = useCallback(() => {
if (pollingRef.current) {
clearInterval(pollingRef.current);
pollingRef.current = null;
}
}, []);
useEffect(() => stopPolling, [stopPolling]);
const createPortrait = useCallback(
async (name) => {
const response = await API.post(
'/api/video/portraits',
{
name,
consent_accepted: true,
consent_version: '2026-08-20',
},
{ skipErrorHandler: true },
);
await load();
return response.data;
},
[load],
);
const pollVerification = useCallback(
(sessionId) => {
stopPolling();
pollingRef.current = setInterval(async () => {
try {
const response = await API.get(
`/api/video/portrait-verifications/${sessionId}`,
{ skipErrorHandler: true, disableDuplicate: true },
);
const next = response.data;
setSession((current) => ({ ...current, ...next }));
if (
['succeeded', 'failed', 'expired', 'superseded'].includes(
next.status,
)
) {
stopPolling();
await load();
}
} catch {
// The next poll retries transient browser or gateway failures.
}
}, 2500);
},
[load, stopPolling],
);
const startVerification = useCallback(
async (portraitId) => {
const response = await API.post(
`/api/video/portraits/${portraitId}/verification-sessions`,
{},
{ skipErrorHandler: true },
);
setSession(response.data);
pollVerification(response.data.session_id);
return response.data;
},
[pollVerification],
);
const uploadPortraitAsset = useCallback(
async (portraitId, file) => {
const image = await readFileAsDataURL(file);
const response = await API.post(
'/api/video/assets',
{
portrait_id: portraitId,
image,
name: file.name,
asset_type: 'Image',
},
{ skipErrorHandler: true },
);
await load();
return response.data;
},
[load],
);
const refreshAssetUntilTerminal = useCallback(
async (assetId) => {
for (let attempt = 0; attempt < 90; attempt += 1) {
await new Promise((resolve) => setTimeout(resolve, 2000));
const response = await API.get(`/api/video/assets/${assetId}`, {
skipErrorHandler: true,
disableDuplicate: true,
});
if (response.data?.status !== 'processing') {
await load();
return response.data;
}
}
await load();
return null;
},
[load],
);
const deleteAsset = useCallback(
async (assetId) => {
await API.delete(`/api/video/assets/${assetId}`, {
skipErrorHandler: true,
});
await load();
},
[load],
);
const deletePortrait = useCallback(
async (portraitId) => {
await API.delete(`/api/video/portraits/${portraitId}`, {
skipErrorHandler: true,
});
setSession(null);
await load();
},
[load],
);
return {
enabled,
loading,
portraits,
assets,
session,
setSession,
createPortrait,
startVerification,
uploadPortraitAsset,
refreshAssetUntilTerminal,
deleteAsset,
deletePortrait,
errorMessage,
};
};
+369
View File
@@ -0,0 +1,369 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import { useState, useEffect, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { API, showError, showSuccess, showInfo } from '../../helpers';
import { DEFAULT_FORM_DATA } from '../../constants/video-generation.constant';
import {
canCancelVideoTask,
canRegenerateVideoTask,
getVideoURLFromDetail,
normalizeExperienceVideoError,
normalizeVideoTaskStatus,
} from '../../helpers/videoTask';
const DRAFT_STORAGE_KEY = 'video_generation_draft_v2';
const POLLING_INTERVAL = 3000; // 轮询间隔(毫秒)
export const useVideoGeneration = () => {
const { t } = useTranslation();
// 表单数据
const [formData, setFormData] = useState(() => {
// 从 localStorage 加载草稿
const draft = localStorage.getItem(DRAFT_STORAGE_KEY);
return draft ? JSON.parse(draft) : DEFAULT_FORM_DATA;
});
// 模型相关 - selectedModel 现在是完整的模型对象(也兼容字符串)
const [selectedModel, setSelectedModel] = useState(null);
// 从选中的模型对象生成 modelInfo
// 如果 selectedModel 是字符串(从 retryTask 来的),则 modelInfo 为 null
const modelInfo =
selectedModel && typeof selectedModel === 'object'
? {
provider: selectedModel.vendor || selectedModel.provider || '未知',
description: selectedModel.description || '',
features: selectedModel.features || [],
maxDuration: selectedModel.maxDuration || 10,
maxResolution: selectedModel.maxResolution || '1080P',
audioSupport: selectedModel.audioSupport || false,
price: selectedModel.model_price || selectedModel.price || '0.00',
}
: null;
// 生成相关
const [generating, setGenerating] = useState(false);
const [currentTask, setCurrentTask] = useState(null);
// 任务列表
const [tasks, setTasks] = useState([]);
// 轮询引用
const pollingTimerRef = useRef(null);
// 自动保存草稿
useEffect(() => {
const timer = setTimeout(() => {
localStorage.setItem(DRAFT_STORAGE_KEY, JSON.stringify(formData));
}, 1000);
return () => clearTimeout(timer);
}, [formData]);
// 加载任务列表
const loadTasks = useCallback(async () => {
try {
const res = await API.get('/api/video/tasks');
if (res?.data?.success) {
setTasks(res.data.data?.items || []);
}
} catch (error) {
console.error('Failed to load tasks:', error);
}
}, []);
// 初始加载
useEffect(() => {
loadTasks();
}, [loadTasks]);
// 轮询任务状态
const startPolling = useCallback(
(taskId) => {
if (pollingTimerRef.current) {
clearInterval(pollingTimerRef.current);
}
pollingTimerRef.current = setInterval(async () => {
try {
const res = await API.get(`/api/video/tasks/${taskId}`);
if (res?.data?.success) {
const task = res.data.data;
setCurrentTask(task);
const normalizedStatus = normalizeVideoTaskStatus(task.status);
// 如果任务完成或失败,停止轮询
// 支持 'completed'/'success' 和 'failed'/'failure' 两种格式
if (
normalizedStatus === 'success' ||
normalizedStatus === 'failure'
) {
setGenerating(false);
clearInterval(pollingTimerRef.current);
pollingTimerRef.current = null;
// 刷新任务列表
loadTasks();
// 显示通知
if (normalizedStatus === 'success') {
showSuccess(t('视频生成成功!'));
} else if (normalizedStatus === 'failure') {
showError(
t('视频生成失败: ') + (task.fail_reason || t('未知错误')),
);
}
}
}
} catch (error) {
console.error('Failed to poll task status:', error);
}
}, POLLING_INTERVAL);
},
[loadTasks, t],
);
// 停止轮询
const stopPolling = useCallback(() => {
if (pollingTimerRef.current) {
clearInterval(pollingTimerRef.current);
pollingTimerRef.current = null;
}
}, []);
// 清理定时器
useEffect(() => {
return () => {
stopPolling();
};
}, [stopPolling]);
const submitVideo = useCallback(
async (requestData, model = selectedModel) => {
if (!requestData.prompt) {
showError(t('请输入提示词或选择场景模板'));
return false;
}
if (!model) {
showError(t('请选择模型'));
return false;
}
if (typeof model === 'object' && model.level_locked) {
showError(t('当前等级无权调用此模型,请选择其他模型'));
return false;
}
if (requestData.mode === 'image2video' && !requestData.image) {
showError(t('请上传首帧图片'));
return false;
}
const modelName =
typeof model === 'object' ? model.model_name || model.id : model;
setGenerating(true);
try {
const res = await API.post('/api/video/generate', {
...requestData,
model: modelName,
});
if (!res?.data?.success) {
throw res?.data || new Error(t('提交失败'));
}
const task = res.data.data;
setCurrentTask(task);
showInfo(t('视频生成任务已提交,请稍候...'));
startPolling(task.task_id);
return true;
} catch (error) {
setGenerating(false);
const normalized = normalizeExperienceVideoError(error, t('提交失败'));
showError(`${t('提交失败')}: ${normalized.message}`);
return false;
}
},
[selectedModel, startPolling, t],
);
// 生成视频
const handleGenerate = useCallback(async () => {
if (!formData.prompt && !formData.selectedTemplate) {
showError(t('请输入提示词或选择场景模板'));
return;
}
let finalPrompt = formData.prompt;
if (formData.selectedTemplate) {
finalPrompt =
formData.selectedTemplate +
(formData.prompt ? '\n' + formData.prompt : '');
}
const requestData = {
mode: formData.mode,
prompt: finalPrompt,
negative_prompt: formData.negative_prompt,
resolution: formData.resolution,
duration: formData.duration,
fps: formData.fps,
ratio: formData.ratio,
audio: formData.audio,
seed: formData.seed === -1 ? null : formData.seed,
prompt_extend: formData.prompt_extend,
watermark: formData.watermark,
};
// 如果是图生视频,添加图片
if (formData.mode === 'image2video' && formData.image) {
requestData.image = formData.image;
}
await submitVideo(requestData, selectedModel);
}, [formData, selectedModel, submitVideo, t]);
// 取消生成
const handleCancel = useCallback(async () => {
if (!currentTask?.task_id || !canCancelVideoTask(currentTask)) return;
try {
const res = await API.post(
`/api/video/tasks/${currentTask.task_id}/cancel`,
);
if (res?.data?.success) {
showSuccess(t('已取消任务'));
setGenerating(false);
stopPolling();
setCurrentTask(null);
loadTasks();
} else {
throw new Error(res?.data?.message || t('取消失败'));
}
} catch (error) {
showError(t('取消失败: ') + (error.message || error));
}
}, [currentTask, t, stopPolling, loadTasks]);
// 刷新任务列表
const refreshTasks = useCallback(() => {
loadTasks();
}, [loadTasks]);
// 删除任务
const deleteTask = useCallback(
async (taskId) => {
try {
const res = await API.delete(`/api/video/tasks/${taskId}`);
if (res?.data?.success) {
showSuccess(t('任务已删除'));
loadTasks();
} else {
throw new Error(res?.data?.message || t('删除失败'));
}
} catch (error) {
showError(t('删除失败: ') + (error.message || error));
}
},
[t, loadTasks],
);
const getRegenerationTask = useCallback(
async (taskId) => {
try {
const res = await API.get(`/api/video/tasks/${taskId}`);
const task = res?.data?.data;
if (!res?.data?.success || !canRegenerateVideoTask(task)) {
showError(t('该任务不支持再生成'));
return null;
}
return task;
} catch (error) {
const normalized = normalizeExperienceVideoError(
error,
t('获取任务失败'),
);
showError(normalized.message);
return null;
}
},
[t],
);
// 获取任务的最新视频URL(用于播放/下载)
const getTaskVideoUrl = useCallback(async (taskId) => {
try {
const res = await API.get(`/api/video/tasks/${taskId}`);
if (res?.data?.success) {
const taskData = res.data.data;
const data = taskData?.data;
if (data && typeof data === 'object') {
return getVideoURLFromDetail(taskData);
}
}
} catch (error) {
console.error('Failed to get task video url:', error);
}
return null;
}, []);
// 下载任务
const downloadTask = useCallback(
async (task) => {
// 先获取最新的预签名URL
const videoUrl = await getTaskVideoUrl(task.task_id);
if (videoUrl) {
const link = document.createElement('a');
link.href = videoUrl;
link.download = `video_${task.task_id}.mp4`;
link.target = '_blank';
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
showSuccess(t('开始下载'));
} else {
showError(t('未找到视频URL'));
}
},
[t, getTaskVideoUrl],
);
return {
// 表单数据
formData,
setFormData,
// 模型相关
selectedModel,
setSelectedModel,
modelInfo,
// 生成相关
generating,
currentTask,
handleGenerate,
submitVideo,
handleCancel,
// 任务列表
tasks,
refreshTasks,
deleteTask,
getRegenerationTask,
downloadTask,
getTaskVideoUrl, // 获取最新的视频URL(用于播放)
};
};