Initial import of weiyuan frontend
This commit is contained in:
@@ -0,0 +1,425 @@
|
||||
/*
|
||||
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 {
|
||||
getUserIdFromLocalStorage,
|
||||
showError,
|
||||
formatMessageForAPI,
|
||||
isValidMessage,
|
||||
stripHistoryAttachments,
|
||||
} from './utils';
|
||||
import axios from 'axios';
|
||||
import { MESSAGE_ROLES } from '../constants/playground.constants';
|
||||
import { getServerURL } from './config';
|
||||
import { buildGetRequestKey, getHeaderValue } from './requestDedupe';
|
||||
|
||||
function createAPIInstance() {
|
||||
const serverURL = getServerURL();
|
||||
return axios.create({
|
||||
baseURL: serverURL,
|
||||
withCredentials: serverURL !== '',
|
||||
headers: {
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
export let API = createAPIInstance();
|
||||
|
||||
function patchAPIInstance(instance) {
|
||||
const originalGet = instance.get.bind(instance);
|
||||
const inFlightGetRequests = new Map();
|
||||
|
||||
instance.get = (url, config = {}) => {
|
||||
if (config?.disableDuplicate) {
|
||||
return originalGet(url, config);
|
||||
}
|
||||
|
||||
const fallbackOrgId =
|
||||
url.startsWith('/api/org/') && typeof localStorage !== 'undefined'
|
||||
? localStorage.getItem('current_org_id') || ''
|
||||
: '';
|
||||
const key = buildGetRequestKey(
|
||||
url,
|
||||
config,
|
||||
fallbackOrgId,
|
||||
getUserIdFromLocalStorage(),
|
||||
);
|
||||
if (inFlightGetRequests.has(key)) {
|
||||
return inFlightGetRequests.get(key);
|
||||
}
|
||||
|
||||
const reqPromise = originalGet(url, config).finally(() => {
|
||||
inFlightGetRequests.delete(key);
|
||||
});
|
||||
|
||||
inFlightGetRequests.set(key, reqPromise);
|
||||
return reqPromise;
|
||||
};
|
||||
}
|
||||
|
||||
patchAPIInstance(API);
|
||||
|
||||
// 添加 response interceptor 的函数
|
||||
function addResponseInterceptor(instance) {
|
||||
instance.interceptors.response.use(
|
||||
(response) => response,
|
||||
(error) => {
|
||||
// 如果请求配置中显式要求跳过全局错误处理,则不弹出默认错误提示
|
||||
if (error.config && error.config.skipErrorHandler) {
|
||||
return Promise.reject(error);
|
||||
}
|
||||
showError(error);
|
||||
return Promise.reject(error);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// 添加 request interceptor:自动为 /api/org/ 请求注入 X-Org-Id 头
|
||||
function addOrgHeaderInterceptor(instance) {
|
||||
instance.interceptors.request.use((config) => {
|
||||
config.headers['New-API-User'] = getUserIdFromLocalStorage();
|
||||
if (config.url && config.url.startsWith('/api/org/')) {
|
||||
const explicitOrgId = getHeaderValue(config.headers, 'X-Org-Id');
|
||||
const orgId = explicitOrgId || localStorage.getItem('current_org_id');
|
||||
if (orgId && !explicitOrgId) {
|
||||
config.headers['X-Org-Id'] = orgId;
|
||||
}
|
||||
}
|
||||
return config;
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化时添加 interceptor
|
||||
addResponseInterceptor(API);
|
||||
addOrgHeaderInterceptor(API);
|
||||
|
||||
export function updateAPI() {
|
||||
API = createAPIInstance();
|
||||
|
||||
patchAPIInstance(API);
|
||||
// 重新添加 interceptors
|
||||
addResponseInterceptor(API);
|
||||
addOrgHeaderInterceptor(API);
|
||||
}
|
||||
|
||||
// playground
|
||||
|
||||
// 构建API请求负载
|
||||
export const buildApiPayload = (
|
||||
messages,
|
||||
systemPrompt,
|
||||
inputs,
|
||||
parameterEnabled,
|
||||
) => {
|
||||
// 剥离历史轮的文件/图片附件:只把最后一条 user 消息的附件发给上游,
|
||||
// 之前轮的文件已经在历史 assistant 回复里被"消化"过,再重发只是浪费 token,
|
||||
// 还会因 COS 私有桶预签名 URL 过期导致上游报"failed to fetch file"。
|
||||
const processedMessages = stripHistoryAttachments(
|
||||
messages.filter(isValidMessage).map(formatMessageForAPI).filter(Boolean),
|
||||
);
|
||||
|
||||
// 如果有系统提示,插入到消息开头
|
||||
if (systemPrompt && systemPrompt.trim()) {
|
||||
processedMessages.unshift({
|
||||
role: MESSAGE_ROLES.SYSTEM,
|
||||
content: systemPrompt.trim(),
|
||||
});
|
||||
}
|
||||
|
||||
const payload = {
|
||||
model: inputs.model,
|
||||
group: inputs.group,
|
||||
messages: processedMessages,
|
||||
stream: inputs.stream,
|
||||
};
|
||||
|
||||
if (inputs.source) {
|
||||
payload.source = inputs.source;
|
||||
}
|
||||
|
||||
if (inputs.conversation_id) {
|
||||
payload.conversation_id = inputs.conversation_id;
|
||||
}
|
||||
|
||||
// 联网搜索
|
||||
if (inputs.enableWebSearch) {
|
||||
payload.enable_web_search = true;
|
||||
}
|
||||
|
||||
// 添加启用的参数
|
||||
const parameterMappings = {
|
||||
temperature: 'temperature',
|
||||
top_p: 'top_p',
|
||||
max_tokens: 'max_tokens',
|
||||
frequency_penalty: 'frequency_penalty',
|
||||
presence_penalty: 'presence_penalty',
|
||||
seed: 'seed',
|
||||
};
|
||||
|
||||
Object.entries(parameterMappings).forEach(([key, param]) => {
|
||||
const enabled = parameterEnabled[key];
|
||||
const value = inputs[param];
|
||||
const hasValue = value !== undefined && value !== null;
|
||||
|
||||
if (enabled && hasValue) {
|
||||
payload[param] = value;
|
||||
}
|
||||
});
|
||||
|
||||
return payload;
|
||||
};
|
||||
|
||||
// 从上游响应体里提取用户可读的错误文案。
|
||||
// 后端 / 上游模型常以 OpenAI 兼容格式返回 `{"error":{"message":"..."}}`,
|
||||
// 也可能是纯字符串、HTML、空。我们尽量把"模型 / 适配器写的人类可读 message"挖出来。
|
||||
//
|
||||
// 返回值约定:
|
||||
// - 成功提取到 message 或拿到纯文本 → 返回该字符串
|
||||
// - body 为空 / JSON 合法但找不到任何已知 message 字段 → 返回 ''
|
||||
// 调用方应据此回退到 "HTTP {status} 请求失败" 之类的通用文案,
|
||||
// 而不是把原 JSON 字符串展示给用户
|
||||
export const extractErrorMessage = (body) => {
|
||||
if (body == null) return '';
|
||||
const str = typeof body === 'string' ? body : String(body);
|
||||
const trimmed = str.trim();
|
||||
if (trimmed === '') return '';
|
||||
|
||||
// 优先尝试 JSON:OpenAI 兼容格式 `{"error":{"message":"...","code":"..."}}`
|
||||
const looksLikeJson = trimmed.startsWith('{') || trimmed.startsWith('[');
|
||||
if (looksLikeJson) {
|
||||
try {
|
||||
const parsed = JSON.parse(trimmed);
|
||||
// 各种常见嵌套位置
|
||||
const candidates = [
|
||||
parsed?.error?.message,
|
||||
parsed?.error?.error?.message,
|
||||
parsed?.message,
|
||||
typeof parsed?.error === 'string' ? parsed.error : null,
|
||||
parsed?.error_msg,
|
||||
];
|
||||
for (const c of candidates) {
|
||||
if (typeof c === 'string' && c.trim() !== '') return c.trim();
|
||||
}
|
||||
// JSON 合法但没有任何已知 message 字段 → 不向用户展示原 JSON
|
||||
// (用户看不懂 `{"data":[]}` 这种东西,让调用方退回通用文案)
|
||||
return '';
|
||||
} catch {
|
||||
// JSON 解析失败 — 不是合法 JSON 就当文本
|
||||
}
|
||||
}
|
||||
|
||||
// 纯文本(HTML / plain message):截断 500 字符直接返回
|
||||
return trimmed.length > 500 ? trimmed.slice(0, 500) + '…' : trimmed;
|
||||
};
|
||||
|
||||
// 处理API错误响应
|
||||
export const handleApiError = (error, response = null) => {
|
||||
const errorInfo = {
|
||||
error: error.message || '未知错误',
|
||||
timestamp: new Date().toISOString(),
|
||||
stack: error.stack,
|
||||
};
|
||||
|
||||
if (response) {
|
||||
errorInfo.status = response.status;
|
||||
errorInfo.statusText = response.statusText;
|
||||
}
|
||||
|
||||
if (error.message.includes('HTTP error')) {
|
||||
errorInfo.details = '服务器返回了错误状态码';
|
||||
} else if (error.message.includes('Failed to fetch')) {
|
||||
errorInfo.details = '网络连接失败或服务器无响应';
|
||||
}
|
||||
|
||||
return errorInfo;
|
||||
};
|
||||
|
||||
// 处理模型数据
|
||||
export const processModelsData = (data, currentModel, levelStates = {}) => {
|
||||
// levelStates(§6.2):后端已剔除 hidden,仅 visible 需锁定(不可选中提交)。
|
||||
const modelOptions = data.map((model) => {
|
||||
const locked = levelStates?.[model] === 'visible';
|
||||
return {
|
||||
label: model,
|
||||
value: model,
|
||||
disabled: locked,
|
||||
level_locked: locked,
|
||||
};
|
||||
});
|
||||
|
||||
const hasCurrentModel = modelOptions.some(
|
||||
(option) => option.value === currentModel && !option.level_locked,
|
||||
);
|
||||
// 自动选中首个「可调用」模型,避免默认落在锁定模型上
|
||||
const firstCallable = modelOptions.find((o) => !o.level_locked);
|
||||
const selectedModel = hasCurrentModel
|
||||
? currentModel
|
||||
: firstCallable?.value || '';
|
||||
|
||||
return { modelOptions, selectedModel };
|
||||
};
|
||||
|
||||
// 处理分组数据
|
||||
export const processGroupsData = (data, userGroup) => {
|
||||
let groupOptions = Object.entries(data).map(([group, info]) => {
|
||||
const desc = info?.desc || '';
|
||||
|
||||
return {
|
||||
label: group,
|
||||
value: group,
|
||||
ratio: info?.ratio,
|
||||
description: desc.length > 20 ? desc.substring(0, 20) + '...' : desc,
|
||||
fullLabel: desc,
|
||||
};
|
||||
});
|
||||
|
||||
if (groupOptions.length === 0) {
|
||||
groupOptions = [
|
||||
{
|
||||
label: '用户分组',
|
||||
value: '',
|
||||
ratio: 1,
|
||||
},
|
||||
];
|
||||
} else if (userGroup) {
|
||||
const userGroupIndex = groupOptions.findIndex((g) => g.value === userGroup);
|
||||
if (userGroupIndex > -1) {
|
||||
const userGroupOption = groupOptions.splice(userGroupIndex, 1)[0];
|
||||
groupOptions.unshift(userGroupOption);
|
||||
}
|
||||
}
|
||||
|
||||
return groupOptions;
|
||||
};
|
||||
|
||||
// 原来components中的utils.js
|
||||
|
||||
export async function getOAuthState() {
|
||||
let path = '/api/oauth/state';
|
||||
let affCode = localStorage.getItem('aff');
|
||||
if (affCode && affCode.length > 0) {
|
||||
path += `?aff=${affCode}`;
|
||||
}
|
||||
const res = await API.get(path);
|
||||
const { success, message, data } = res.data;
|
||||
if (success) {
|
||||
return data;
|
||||
} else {
|
||||
showError(message);
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
export async function onDiscordOAuthClicked(client_id) {
|
||||
const state = await getOAuthState();
|
||||
if (!state) return false;
|
||||
const redirect_uri = `${window.location.origin}/oauth/discord`;
|
||||
const response_type = 'code';
|
||||
const scope = 'identify+openid';
|
||||
window.open(
|
||||
`https://discord.com/oauth2/authorize?client_id=${client_id}&redirect_uri=${redirect_uri}&response_type=${response_type}&scope=${scope}&state=${state}`,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function onOIDCClicked(auth_url, client_id, openInNewTab = false) {
|
||||
const state = await getOAuthState();
|
||||
if (!state) return false;
|
||||
const url = new URL(auth_url);
|
||||
url.searchParams.set('client_id', client_id);
|
||||
url.searchParams.set('redirect_uri', `${window.location.origin}/oauth/oidc`);
|
||||
url.searchParams.set('response_type', 'code');
|
||||
url.searchParams.set('scope', 'openid profile email');
|
||||
url.searchParams.set('state', state);
|
||||
if (openInNewTab) {
|
||||
window.open(url.toString(), '_blank');
|
||||
} else {
|
||||
window.location.href = url.toString();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function onGitHubOAuthClicked(github_client_id) {
|
||||
const state = await getOAuthState();
|
||||
if (!state) return false;
|
||||
window.open(
|
||||
`https://github.com/login/oauth/authorize?client_id=${github_client_id}&state=${state}&scope=user:email`,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function onLinuxDOOAuthClicked(linuxdo_client_id) {
|
||||
const state = await getOAuthState();
|
||||
if (!state) return false;
|
||||
window.open(
|
||||
`https://connect.linux.do/oauth2/authorize?response_type=code&client_id=${linuxdo_client_id}&state=${state}`,
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function onWeChatOpenOAuthClicked(wechat_open_app_id) {
|
||||
const state = await getOAuthState();
|
||||
if (!state) return false;
|
||||
const redirect_uri = encodeURIComponent(
|
||||
`${window.location.origin}/oauth/wechat-open`,
|
||||
);
|
||||
window.location.href = `https://open.weixin.qq.com/connect/qrconnect?appid=${wechat_open_app_id}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_login&state=${state}#wechat_redirect`;
|
||||
return true;
|
||||
}
|
||||
|
||||
// 微信公众号网页授权(移动端微信浏览器内直接授权登录,无需扫码)
|
||||
export async function onWeChatMPOAuthClicked(wechat_mp_app_id) {
|
||||
const state = await getOAuthState();
|
||||
if (!state) return false;
|
||||
const redirect_uri = encodeURIComponent(
|
||||
`${window.location.origin}/oauth/wechat-mp`,
|
||||
);
|
||||
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${wechat_mp_app_id}&redirect_uri=${redirect_uri}&response_type=code&scope=snsapi_userinfo&state=${state}#wechat_redirect`;
|
||||
return true;
|
||||
}
|
||||
|
||||
let channelModels = undefined;
|
||||
export async function loadChannelModels() {
|
||||
const res = await API.get('/api/models');
|
||||
const { success, data } = res.data;
|
||||
if (!success) {
|
||||
return;
|
||||
}
|
||||
channelModels = data;
|
||||
localStorage.setItem('channel_models', JSON.stringify(data));
|
||||
}
|
||||
|
||||
export function getChannelModels(type) {
|
||||
if (channelModels !== undefined && type in channelModels) {
|
||||
if (!channelModels[type]) {
|
||||
return [];
|
||||
}
|
||||
return channelModels[type];
|
||||
}
|
||||
let models = localStorage.getItem('channel_models');
|
||||
if (!models) {
|
||||
return [];
|
||||
}
|
||||
channelModels = JSON.parse(models);
|
||||
if (type in channelModels) {
|
||||
return channelModels[type];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
/*
|
||||
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, { useContext } from 'react';
|
||||
import { Navigate, useLocation } from 'react-router-dom';
|
||||
import { history } from './history';
|
||||
import { UserContext } from '../context/User';
|
||||
import Loading from '../components/common/ui/Loading';
|
||||
import {
|
||||
DEFAULT_LOGIN_REDIRECT,
|
||||
getUserData,
|
||||
isSafePostLoginRedirect,
|
||||
savePostLoginRedirect,
|
||||
} from './data';
|
||||
|
||||
/**
|
||||
* 判断是否处于认证类页面(登录/注册/重置密码/企业登录/企业注册)。
|
||||
* 认证页顶栏遵循行业惯例只保留最小化工具(logo + 主题切换),
|
||||
* HeaderBar / ActionButtons / UserArea 共用本判断,避免各处正则漂移。
|
||||
*/
|
||||
export const isAuthPagePath = (pathname) =>
|
||||
['/login', '/register', '/reset', '/user/reset'].includes(pathname) ||
|
||||
pathname === '/org/login' ||
|
||||
pathname === '/org/register' ||
|
||||
// WeyAi 客户端授权页:与登录页同属认证流程,使用最小化顶栏。
|
||||
// 大小写不敏感——React Router 默认如此,/Client/Authorize 渲染的是同一个
|
||||
// 页面,后端 ClientFrameGuard 也按 EqualFold 判定,这里必须跟上,否则该
|
||||
// 写法会带出完整顶栏与跑马灯
|
||||
pathname.toLowerCase() === '/client/authorize' ||
|
||||
/^\/org\/[^/]+\/login$/.test(pathname);
|
||||
|
||||
// 未登录统一引导到企业登录(本产品主推企业用户;个人用户可经页内切换回 /login)。
|
||||
// 回跳地址已存本地(savePostLoginRedirect),切换到个人登录后仍可正常回跳。
|
||||
const getLoginTarget = (location) => {
|
||||
const target = `${location.pathname}${location.search}${location.hash}`;
|
||||
if (isSafePostLoginRedirect(target)) {
|
||||
savePostLoginRedirect(target);
|
||||
return `/org/login?redirect=${encodeURIComponent(target)}`;
|
||||
}
|
||||
return '/org/login';
|
||||
};
|
||||
|
||||
export const AuthRedirect = ({ children }) => {
|
||||
const [userState] = useContext(UserContext);
|
||||
const cachedUser = getUserData();
|
||||
|
||||
if (userState?.user) {
|
||||
// org_only(仅企业资源)员工登录后直接进入企业空间
|
||||
if (userState.user.org_only_mode === true) {
|
||||
return <Navigate to='/org' replace />;
|
||||
}
|
||||
// 已登录用户统一跳转到默认登录落地页,而不是控制台(控制台需要管理员权限)
|
||||
return <Navigate to={DEFAULT_LOGIN_REDIRECT} replace />;
|
||||
}
|
||||
if (!userState?.authChecked && cachedUser) {
|
||||
return <Loading />;
|
||||
}
|
||||
|
||||
return children;
|
||||
};
|
||||
|
||||
function PrivateRoute({ children }) {
|
||||
const [userState] = useContext(UserContext);
|
||||
const location = useLocation();
|
||||
const cachedUser = getUserData();
|
||||
|
||||
if (userState?.user) {
|
||||
return children;
|
||||
}
|
||||
if (!userState?.authChecked && cachedUser) {
|
||||
return <Loading />;
|
||||
}
|
||||
return (
|
||||
<Navigate
|
||||
to={getLoginTarget(location)}
|
||||
replace
|
||||
state={{ from: history.location }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export function AdminRoute({ children }) {
|
||||
const [userState] = useContext(UserContext);
|
||||
const location = useLocation();
|
||||
const cachedUser = getUserData();
|
||||
|
||||
if (!userState?.authChecked && cachedUser) {
|
||||
return <Loading />;
|
||||
}
|
||||
if (!userState?.user) {
|
||||
return (
|
||||
<Navigate
|
||||
to={getLoginTarget(location)}
|
||||
replace
|
||||
state={{ from: history.location }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (typeof userState.user.role === 'number' && userState.user.role >= 10) {
|
||||
return children;
|
||||
}
|
||||
return <Navigate to='/forbidden' replace />;
|
||||
}
|
||||
|
||||
export function RootRoute({ children }) {
|
||||
const [userState] = useContext(UserContext);
|
||||
const location = useLocation();
|
||||
const cachedUser = getUserData();
|
||||
|
||||
if (!userState?.authChecked && cachedUser) {
|
||||
return <Loading />;
|
||||
}
|
||||
if (!userState?.user) {
|
||||
return (
|
||||
<Navigate
|
||||
to={getLoginTarget(location)}
|
||||
replace
|
||||
state={{ from: history.location }}
|
||||
/>
|
||||
);
|
||||
}
|
||||
if (typeof userState.user.role === 'number' && userState.user.role >= 100) {
|
||||
return children;
|
||||
}
|
||||
return <Navigate to='/forbidden' replace />;
|
||||
}
|
||||
|
||||
export { PrivateRoute };
|
||||
@@ -0,0 +1,312 @@
|
||||
/*
|
||||
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 { encodeToBase64 } from './base64';
|
||||
import { stringToColor } from './render';
|
||||
|
||||
export const USER_AVATAR_TYPES = {
|
||||
PRESET: 'preset',
|
||||
INITIAL: 'initial',
|
||||
CUSTOM: 'custom',
|
||||
};
|
||||
|
||||
export const CARTOON_AVATAR_PRESETS = [
|
||||
{
|
||||
id: 'fox',
|
||||
label: '灵感小狐',
|
||||
bg: ['#ffedd5', '#fed7aa'],
|
||||
face: '#fb923c',
|
||||
faceAlt: '#fff7ed',
|
||||
accent: '#ea580c',
|
||||
},
|
||||
{
|
||||
id: 'cat',
|
||||
label: '蓝莓小猫',
|
||||
bg: ['#dbeafe', '#bfdbfe'],
|
||||
face: '#60a5fa',
|
||||
faceAlt: '#eff6ff',
|
||||
accent: '#2563eb',
|
||||
},
|
||||
{
|
||||
id: 'panda',
|
||||
label: '云朵熊猫',
|
||||
bg: ['#f8fafc', '#cbd5e1'],
|
||||
face: '#ffffff',
|
||||
faceAlt: '#111827',
|
||||
accent: '#475569',
|
||||
},
|
||||
{
|
||||
id: 'bunny',
|
||||
label: '樱桃小兔',
|
||||
bg: ['#fce7f3', '#fbcfe8'],
|
||||
face: '#ffffff',
|
||||
faceAlt: '#f9a8d4',
|
||||
accent: '#db2777',
|
||||
},
|
||||
{
|
||||
id: 'robot',
|
||||
label: '像素机器人',
|
||||
bg: ['#ccfbf1', '#99f6e4'],
|
||||
face: '#2dd4bf',
|
||||
faceAlt: '#0f766e',
|
||||
accent: '#14b8a6',
|
||||
},
|
||||
{
|
||||
id: 'koala',
|
||||
label: '雾灰考拉',
|
||||
bg: ['#e5e7eb', '#d1d5db'],
|
||||
face: '#9ca3af',
|
||||
faceAlt: '#f3f4f6',
|
||||
accent: '#4b5563',
|
||||
},
|
||||
{
|
||||
id: 'tiger',
|
||||
label: '蜜糖小虎',
|
||||
bg: ['#fef3c7', '#fde68a'],
|
||||
face: '#f59e0b',
|
||||
faceAlt: '#fff7ed',
|
||||
accent: '#b45309',
|
||||
},
|
||||
{
|
||||
id: 'owl',
|
||||
label: '夜航猫头鹰',
|
||||
bg: ['#ede9fe', '#ddd6fe'],
|
||||
face: '#8b5cf6',
|
||||
faceAlt: '#f5f3ff',
|
||||
accent: '#6d28d9',
|
||||
},
|
||||
];
|
||||
|
||||
const DEFAULT_AVATAR_FALLBACK =
|
||||
'https://lf3-static.bytednsdoc.com/obj/eden-cn/ptlz_zlp/ljhwZthlaukjlkulzlp/docs-icon.png';
|
||||
|
||||
const escapeSvgText = (value) =>
|
||||
String(value ?? '')
|
||||
.replace(/&/g, '&')
|
||||
.replace(/</g, '<')
|
||||
.replace(/>/g, '>')
|
||||
.replace(/"/g, '"');
|
||||
|
||||
const svgToDataUrl = (svg) =>
|
||||
`data:image/svg+xml;base64,${encodeToBase64(svg)}`;
|
||||
|
||||
const hashString = (value) => {
|
||||
const text = String(value || '');
|
||||
let hash = 0;
|
||||
for (let i = 0; i < text.length; i += 1) {
|
||||
hash = (hash * 31 + text.charCodeAt(i)) >>> 0;
|
||||
}
|
||||
return hash;
|
||||
};
|
||||
|
||||
export const getAvatarPresetById = (id) =>
|
||||
CARTOON_AVATAR_PRESETS.find((item) => item.id === id) ||
|
||||
CARTOON_AVATAR_PRESETS[0];
|
||||
|
||||
export const getDefaultAvatarPresetId = (user) => {
|
||||
if (!user) return CARTOON_AVATAR_PRESETS[0].id;
|
||||
const seed = user.id || user.username || user.display_name || 'user';
|
||||
return CARTOON_AVATAR_PRESETS[
|
||||
hashString(seed) % CARTOON_AVATAR_PRESETS.length
|
||||
].id;
|
||||
};
|
||||
|
||||
export const parseUserSetting = (setting) => {
|
||||
if (!setting) return {};
|
||||
if (typeof setting === 'object') return setting;
|
||||
try {
|
||||
const parsed = JSON.parse(setting);
|
||||
return parsed && typeof parsed === 'object' ? parsed : {};
|
||||
} catch (_) {
|
||||
return {};
|
||||
}
|
||||
};
|
||||
|
||||
export const getInitialAvatarDataUrl = (username, size = 96) => {
|
||||
if (!username) return DEFAULT_AVATAR_FALLBACK;
|
||||
const firstLetter = escapeSvgText(username[0].toUpperCase());
|
||||
const bgColor = stringToColor(username);
|
||||
const svg = `
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 96 96">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="${bgColor}" stop-opacity="0.92"/>
|
||||
<stop offset="1" stop-color="#111827" stop-opacity="0.88"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="96" height="96" rx="28" fill="url(#bg)" />
|
||||
<circle cx="72" cy="22" r="18" fill="#ffffff" opacity="0.16" />
|
||||
<text x="50%" y="52%" dominant-baseline="central" text-anchor="middle" font-size="42" font-weight="700" fill="#ffffff" font-family="Lato, Arial, sans-serif">${firstLetter}</text>
|
||||
</svg>
|
||||
`;
|
||||
return svgToDataUrl(svg);
|
||||
};
|
||||
|
||||
export const getCartoonAvatarDataUrl = (presetId, size = 96) => {
|
||||
const preset = getAvatarPresetById(presetId);
|
||||
const { id, bg, face, faceAlt, accent } = preset;
|
||||
|
||||
const details = {
|
||||
fox: `
|
||||
<path d="M19 33 L31 14 L41 34 Z" fill="${face}" />
|
||||
<path d="M77 33 L65 14 L55 34 Z" fill="${face}" />
|
||||
<path d="M27 29 L31 22 L35 31 Z" fill="${faceAlt}" opacity="0.9" />
|
||||
<path d="M69 29 L65 22 L61 31 Z" fill="${faceAlt}" opacity="0.9" />
|
||||
<circle cx="48" cy="52" r="30" fill="${face}" />
|
||||
<path d="M26 52 C34 44 39 42 48 42 C57 42 62 44 70 52 C66 68 58 78 48 80 C38 78 30 68 26 52Z" fill="${faceAlt}" />
|
||||
<circle cx="38" cy="50" r="3.5" fill="#111827" />
|
||||
<circle cx="58" cy="50" r="3.5" fill="#111827" />
|
||||
<path d="M43 61 Q48 65 53 61" stroke="#7c2d12" stroke-width="3" stroke-linecap="round" fill="none" />
|
||||
<path d="M45 56 Q48 58 51 56 Q48 62 45 56Z" fill="#111827" />
|
||||
`,
|
||||
cat: `
|
||||
<path d="M20 35 L31 18 L40 38 Z" fill="${face}" />
|
||||
<path d="M76 35 L65 18 L56 38 Z" fill="${face}" />
|
||||
<path d="M28 33 L32 26 L36 36 Z" fill="${faceAlt}" />
|
||||
<path d="M68 33 L64 26 L60 36 Z" fill="${faceAlt}" />
|
||||
<circle cx="48" cy="54" r="30" fill="${face}" />
|
||||
<circle cx="37" cy="51" r="4" fill="#0f172a" />
|
||||
<circle cx="59" cy="51" r="4" fill="#0f172a" />
|
||||
<path d="M45 61 Q48 64 51 61" stroke="#0f172a" stroke-width="2.8" stroke-linecap="round" fill="none" />
|
||||
<path d="M30 60 L18 56 M30 65 L18 66 M66 60 L78 56 M66 65 L78 66" stroke="${accent}" stroke-width="2.5" stroke-linecap="round" opacity="0.75" />
|
||||
`,
|
||||
panda: `
|
||||
<circle cx="26" cy="34" r="13" fill="${faceAlt}" />
|
||||
<circle cx="70" cy="34" r="13" fill="${faceAlt}" />
|
||||
<circle cx="48" cy="54" r="31" fill="${face}" />
|
||||
<ellipse cx="36" cy="51" rx="10" ry="12" fill="${faceAlt}" />
|
||||
<ellipse cx="60" cy="51" rx="10" ry="12" fill="${faceAlt}" />
|
||||
<circle cx="38" cy="50" r="3" fill="#ffffff" />
|
||||
<circle cx="58" cy="50" r="3" fill="#ffffff" />
|
||||
<ellipse cx="48" cy="62" rx="6" ry="4" fill="${faceAlt}" />
|
||||
<path d="M42 69 Q48 73 54 69" stroke="${faceAlt}" stroke-width="3" stroke-linecap="round" fill="none" />
|
||||
`,
|
||||
bunny: `
|
||||
<rect x="29" y="9" width="13" height="38" rx="7" fill="${face}" transform="rotate(-10 35.5 28)" />
|
||||
<rect x="54" y="9" width="13" height="38" rx="7" fill="${face}" transform="rotate(10 60.5 28)" />
|
||||
<rect x="33" y="16" width="6" height="25" rx="3" fill="${faceAlt}" transform="rotate(-10 36 28)" />
|
||||
<rect x="57" y="16" width="6" height="25" rx="3" fill="${faceAlt}" transform="rotate(10 60 28)" />
|
||||
<circle cx="48" cy="57" r="29" fill="${face}" />
|
||||
<circle cx="38" cy="55" r="3.4" fill="#1f2937" />
|
||||
<circle cx="58" cy="55" r="3.4" fill="#1f2937" />
|
||||
<circle cx="32" cy="63" r="5" fill="${faceAlt}" opacity="0.75" />
|
||||
<circle cx="64" cy="63" r="5" fill="${faceAlt}" opacity="0.75" />
|
||||
<path d="M45 62 Q48 66 51 62" stroke="#1f2937" stroke-width="2.6" stroke-linecap="round" fill="none" />
|
||||
`,
|
||||
robot: `
|
||||
<rect x="27" y="29" width="42" height="42" rx="12" fill="${face}" />
|
||||
<rect x="35" y="38" width="26" height="20" rx="6" fill="#ecfeff" />
|
||||
<circle cx="41" cy="48" r="4" fill="${faceAlt}" />
|
||||
<circle cx="55" cy="48" r="4" fill="${faceAlt}" />
|
||||
<path d="M42 62 H54" stroke="${faceAlt}" stroke-width="3" stroke-linecap="round" />
|
||||
<path d="M48 21 V29" stroke="${accent}" stroke-width="4" stroke-linecap="round" />
|
||||
<circle cx="48" cy="18" r="5" fill="${accent}" />
|
||||
<rect x="20" y="43" width="7" height="16" rx="3.5" fill="${accent}" />
|
||||
<rect x="69" y="43" width="7" height="16" rx="3.5" fill="${accent}" />
|
||||
`,
|
||||
koala: `
|
||||
<circle cx="25" cy="44" r="16" fill="${accent}" />
|
||||
<circle cx="71" cy="44" r="16" fill="${accent}" />
|
||||
<circle cx="48" cy="55" r="30" fill="${face}" />
|
||||
<circle cx="36" cy="51" r="4" fill="#111827" />
|
||||
<circle cx="60" cy="51" r="4" fill="#111827" />
|
||||
<ellipse cx="48" cy="60" rx="7" ry="9" fill="#111827" />
|
||||
<path d="M41 72 Q48 76 55 72" stroke="#111827" stroke-width="3" stroke-linecap="round" fill="none" />
|
||||
<circle cx="30" cy="45" r="8" fill="${faceAlt}" opacity="0.7" />
|
||||
<circle cx="66" cy="45" r="8" fill="${faceAlt}" opacity="0.7" />
|
||||
`,
|
||||
tiger: `
|
||||
<circle cx="26" cy="34" r="12" fill="${face}" />
|
||||
<circle cx="70" cy="34" r="12" fill="${face}" />
|
||||
<circle cx="48" cy="54" r="30" fill="${face}" />
|
||||
<path d="M35 30 L40 42 M48 25 V39 M61 30 L56 42" stroke="${accent}" stroke-width="4" stroke-linecap="round" />
|
||||
<circle cx="38" cy="52" r="3.5" fill="#111827" />
|
||||
<circle cx="58" cy="52" r="3.5" fill="#111827" />
|
||||
<ellipse cx="48" cy="63" rx="12" ry="10" fill="${faceAlt}" />
|
||||
<path d="M45 60 Q48 63 51 60" fill="#111827" />
|
||||
<path d="M43 68 Q48 72 53 68" stroke="#111827" stroke-width="2.5" stroke-linecap="round" fill="none" />
|
||||
`,
|
||||
owl: `
|
||||
<path d="M23 39 C24 22 36 17 48 28 C60 17 72 22 73 39 C77 62 65 80 48 80 C31 80 19 62 23 39Z" fill="${face}" />
|
||||
<circle cx="38" cy="49" r="12" fill="${faceAlt}" />
|
||||
<circle cx="58" cy="49" r="12" fill="${faceAlt}" />
|
||||
<circle cx="38" cy="49" r="4" fill="#111827" />
|
||||
<circle cx="58" cy="49" r="4" fill="#111827" />
|
||||
<path d="M45 58 L51 58 L48 65Z" fill="#f59e0b" />
|
||||
<path d="M31 34 Q38 28 45 34 M51 34 Q58 28 65 34" stroke="${accent}" stroke-width="3" stroke-linecap="round" fill="none" />
|
||||
`,
|
||||
};
|
||||
|
||||
const svg = `
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 96 96">
|
||||
<defs>
|
||||
<linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0" stop-color="${bg[0]}"/>
|
||||
<stop offset="1" stop-color="${bg[1]}"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<rect width="96" height="96" rx="28" fill="url(#bg)" />
|
||||
<circle cx="72" cy="23" r="19" fill="#ffffff" opacity="0.24" />
|
||||
<circle cx="18" cy="79" r="20" fill="${accent}" opacity="0.12" />
|
||||
${details[id] || details.fox}
|
||||
</svg>
|
||||
`;
|
||||
|
||||
return svgToDataUrl(svg);
|
||||
};
|
||||
|
||||
export const getUserAvatarSetting = (user) => {
|
||||
const settings = parseUserSetting(user?.setting);
|
||||
const avatarType = Object.values(USER_AVATAR_TYPES).includes(
|
||||
settings.avatar_type,
|
||||
)
|
||||
? settings.avatar_type
|
||||
: USER_AVATAR_TYPES.PRESET;
|
||||
const preset = getAvatarPresetById(
|
||||
settings.avatar_preset || getDefaultAvatarPresetId(user),
|
||||
);
|
||||
|
||||
return {
|
||||
avatarType,
|
||||
avatarPreset: preset.id,
|
||||
customAvatarUrl:
|
||||
typeof settings.custom_avatar_url === 'string'
|
||||
? settings.custom_avatar_url
|
||||
: '',
|
||||
};
|
||||
};
|
||||
|
||||
export const getUserAvatarUrl = (user, options = {}) => {
|
||||
const { size = 96 } = options;
|
||||
const username = user?.display_name || user?.username || 'User';
|
||||
const setting = getUserAvatarSetting(user);
|
||||
|
||||
if (
|
||||
setting.avatarType === USER_AVATAR_TYPES.CUSTOM &&
|
||||
setting.customAvatarUrl
|
||||
) {
|
||||
return setting.customAvatarUrl;
|
||||
}
|
||||
|
||||
if (setting.avatarType === USER_AVATAR_TYPES.INITIAL) {
|
||||
return getInitialAvatarDataUrl(username, size);
|
||||
}
|
||||
|
||||
return getCartoonAvatarDataUrl(setting.avatarPreset, size);
|
||||
};
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
const toBinaryString = (text) => {
|
||||
if (typeof TextEncoder !== 'undefined') {
|
||||
const bytes = new TextEncoder().encode(text);
|
||||
let binary = '';
|
||||
|
||||
bytes.forEach((byte) => {
|
||||
binary += String.fromCharCode(byte);
|
||||
});
|
||||
|
||||
return binary;
|
||||
}
|
||||
|
||||
return encodeURIComponent(text).replace(/%([0-9A-F]{2})/g, (_, hex) =>
|
||||
String.fromCharCode(parseInt(hex, 16)),
|
||||
);
|
||||
};
|
||||
|
||||
export const encodeToBase64 = (value) => {
|
||||
const input = value == null ? '' : String(value);
|
||||
|
||||
if (typeof window === 'undefined') {
|
||||
if (typeof Buffer !== 'undefined') {
|
||||
return Buffer.from(input, 'utf-8').toString('base64');
|
||||
}
|
||||
if (
|
||||
typeof globalThis !== 'undefined' &&
|
||||
typeof globalThis.btoa === 'function'
|
||||
) {
|
||||
return globalThis.btoa(toBinaryString(input));
|
||||
}
|
||||
throw new Error(
|
||||
'Base64 encoding is unavailable in the current environment',
|
||||
);
|
||||
}
|
||||
|
||||
return window.btoa(toBinaryString(input));
|
||||
};
|
||||
@@ -0,0 +1,29 @@
|
||||
/*
|
||||
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 toBoolean = (value) => {
|
||||
// 兼容字符串、数字以及布尔原生类型
|
||||
if (typeof value === 'boolean') return value;
|
||||
if (typeof value === 'number') return value === 1;
|
||||
if (typeof value === 'string') {
|
||||
const v = value.toLowerCase();
|
||||
return v === 'true' || v === '1';
|
||||
}
|
||||
return false;
|
||||
};
|
||||
@@ -0,0 +1,154 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
const CHUNK_RELOAD_KEY = 'weelinking:chunk-reload';
|
||||
const CHUNK_RELOAD_PARAM = '__wl_reload';
|
||||
const RELOAD_COOLDOWN_MS = 60 * 1000;
|
||||
|
||||
const CHUNK_ERROR_PATTERNS = [
|
||||
/Failed to fetch dynamically imported module/i,
|
||||
/error loading dynamically imported module/i,
|
||||
/Importing a module script failed/i,
|
||||
/Failed to load module script/i,
|
||||
/Expected a JavaScript module script/i,
|
||||
/module script.*MIME type/i,
|
||||
/disallowed MIME type/i,
|
||||
/Loading chunk [\w-]+ failed/i,
|
||||
/ChunkLoadError/i,
|
||||
/Unable to preload CSS/i,
|
||||
];
|
||||
|
||||
function getErrorMessage(error) {
|
||||
if (!error) return '';
|
||||
if (typeof error === 'string') return error;
|
||||
if (typeof error.message === 'string') return error.message;
|
||||
if (typeof error.reason === 'string') return error.reason;
|
||||
if (error.reason) return getErrorMessage(error.reason);
|
||||
|
||||
try {
|
||||
return String(error);
|
||||
} catch {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
function getStoredReload() {
|
||||
try {
|
||||
return JSON.parse(sessionStorage.getItem(CHUNK_RELOAD_KEY) || 'null');
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function getReloadFingerprint() {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.delete(CHUNK_RELOAD_PARAM);
|
||||
return `${url.origin}${url.pathname}${url.search}`;
|
||||
}
|
||||
|
||||
function getReloadUrl() {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set(CHUNK_RELOAD_PARAM, String(Date.now()));
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
function rememberReload(message) {
|
||||
try {
|
||||
sessionStorage.setItem(
|
||||
CHUNK_RELOAD_KEY,
|
||||
JSON.stringify({
|
||||
fingerprint: getReloadFingerprint(),
|
||||
href: window.location.href,
|
||||
time: Date.now(),
|
||||
message: message.slice(0, 200),
|
||||
}),
|
||||
);
|
||||
} catch {
|
||||
// Ignore storage failures; reloading is still safe.
|
||||
}
|
||||
}
|
||||
|
||||
export function isChunkLoadError(error) {
|
||||
const message = getErrorMessage(error);
|
||||
return CHUNK_ERROR_PATTERNS.some((pattern) => pattern.test(message));
|
||||
}
|
||||
|
||||
export function reloadForChunkError(error, { force = false } = {}) {
|
||||
if (typeof window === 'undefined') return false;
|
||||
if (!force && !isChunkLoadError(error)) return false;
|
||||
|
||||
const message = getErrorMessage(error);
|
||||
const previousReload = getStoredReload();
|
||||
const fingerprint = getReloadFingerprint();
|
||||
const now = Date.now();
|
||||
|
||||
if (
|
||||
(previousReload?.fingerprint || previousReload?.href) === fingerprint &&
|
||||
now - previousReload.time < RELOAD_COOLDOWN_MS
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
rememberReload(message || 'chunk load failed');
|
||||
window.location.replace(getReloadUrl());
|
||||
return true;
|
||||
}
|
||||
|
||||
export function installChunkReloadHandlers() {
|
||||
if (typeof window === 'undefined') return;
|
||||
if (window.__weelinkingChunkReloadHandlersInstalled) return;
|
||||
|
||||
window.__weelinkingChunkReloadHandlersInstalled = true;
|
||||
|
||||
window.addEventListener('vite:preloadError', (event) => {
|
||||
if (reloadForChunkError(event.payload, { force: true })) {
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener('unhandledrejection', (event) => {
|
||||
if (reloadForChunkError(event.reason)) {
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
window.addEventListener(
|
||||
'error',
|
||||
(event) => {
|
||||
const target = event.target;
|
||||
const url = target?.src || target?.href || '';
|
||||
const isStaticModule =
|
||||
url.includes('/assets/') && /\.(js|css)(\?|$)/i.test(url);
|
||||
|
||||
if (isStaticModule) {
|
||||
const error = new Error(
|
||||
`Failed to fetch dynamically imported module: ${url}`,
|
||||
);
|
||||
if (reloadForChunkError(error, { force: true })) {
|
||||
event.preventDefault();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (reloadForChunkError(event.error || event.message)) {
|
||||
event.preventDefault();
|
||||
}
|
||||
},
|
||||
true,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
/*
|
||||
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 function getServerURL() {
|
||||
return (
|
||||
window.__APP_CONFIG__?.SERVER_URL ||
|
||||
import.meta.env.VITE_REACT_APP_SERVER_URL ||
|
||||
''
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
/*
|
||||
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 from 'react';
|
||||
import { Progress, Divider, Empty } from '@douyinfe/semi-ui';
|
||||
import {
|
||||
IllustrationConstruction,
|
||||
IllustrationConstructionDark,
|
||||
} from '../components/common/illustrations';
|
||||
import {
|
||||
timestamp2string,
|
||||
timestamp2string1,
|
||||
copy,
|
||||
showSuccess,
|
||||
} from './utils';
|
||||
import {
|
||||
STORAGE_KEYS,
|
||||
DEFAULT_TIME_INTERVALS,
|
||||
DEFAULTS,
|
||||
ILLUSTRATION_SIZE,
|
||||
} from '../constants/dashboard.constants';
|
||||
|
||||
// ========== 时间相关工具函数 ==========
|
||||
export const getDefaultTime = () => {
|
||||
return localStorage.getItem(STORAGE_KEYS.DATA_EXPORT_DEFAULT_TIME) || 'hour';
|
||||
};
|
||||
|
||||
export const getTimeInterval = (timeType, isSeconds = false) => {
|
||||
const intervals =
|
||||
DEFAULT_TIME_INTERVALS[timeType] || DEFAULT_TIME_INTERVALS.hour;
|
||||
return isSeconds ? intervals.seconds : intervals.minutes;
|
||||
};
|
||||
|
||||
export const getInitialTimestamp = () => {
|
||||
const defaultTime = getDefaultTime();
|
||||
const now = new Date().getTime() / 1000;
|
||||
|
||||
switch (defaultTime) {
|
||||
case 'hour':
|
||||
return timestamp2string(now - 86400);
|
||||
case 'week':
|
||||
return timestamp2string(now - 86400 * 30);
|
||||
default:
|
||||
return timestamp2string(now - 86400 * 7);
|
||||
}
|
||||
};
|
||||
|
||||
// ========== 数据处理工具函数 ==========
|
||||
export const updateMapValue = (map, key, value) => {
|
||||
if (!map.has(key)) {
|
||||
map.set(key, 0);
|
||||
}
|
||||
map.set(key, map.get(key) + value);
|
||||
};
|
||||
|
||||
export const initializeMaps = (key, ...maps) => {
|
||||
maps.forEach((map) => {
|
||||
if (!map.has(key)) {
|
||||
map.set(key, 0);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
// ========== 图表相关工具函数 ==========
|
||||
export const updateChartSpec = (
|
||||
setterFunc,
|
||||
newData,
|
||||
subtitle,
|
||||
newColors,
|
||||
dataId,
|
||||
) => {
|
||||
setterFunc((prev) => ({
|
||||
...prev,
|
||||
data: [{ id: dataId, values: newData }],
|
||||
title: {
|
||||
...prev.title,
|
||||
subtext: subtitle,
|
||||
},
|
||||
color: {
|
||||
specified: newColors,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
export const getTrendSpec = (data, color) => ({
|
||||
type: 'area',
|
||||
data: [{ id: 'trend', values: data.map((val, idx) => ({ x: idx, y: val })) }],
|
||||
xField: 'x',
|
||||
yField: 'y',
|
||||
height: 40,
|
||||
width: 100,
|
||||
axes: [
|
||||
{
|
||||
orient: 'bottom',
|
||||
visible: false,
|
||||
},
|
||||
{
|
||||
orient: 'left',
|
||||
visible: false,
|
||||
},
|
||||
],
|
||||
padding: 0,
|
||||
autoFit: false,
|
||||
legends: { visible: false },
|
||||
tooltip: { visible: false },
|
||||
crosshair: { visible: false },
|
||||
line: {
|
||||
style: {
|
||||
stroke: color,
|
||||
lineWidth: 2.5,
|
||||
lineCap: 'round',
|
||||
lineJoin: 'round',
|
||||
curveType: 'monotone',
|
||||
},
|
||||
},
|
||||
area: {
|
||||
style: {
|
||||
fill: {
|
||||
gradient: 'linear',
|
||||
x0: 0.5,
|
||||
y0: 0,
|
||||
x1: 0.5,
|
||||
y1: 1,
|
||||
stops: [
|
||||
{ offset: 0, color: color, opacity: 0.4 },
|
||||
{ offset: 1, color: color, opacity: 0.05 },
|
||||
],
|
||||
},
|
||||
curveType: 'monotone',
|
||||
},
|
||||
},
|
||||
point: {
|
||||
visible: false,
|
||||
},
|
||||
background: {
|
||||
fill: 'transparent',
|
||||
},
|
||||
animation: true,
|
||||
animationAppear: {
|
||||
duration: 600,
|
||||
easing: 'cubicOut',
|
||||
},
|
||||
});
|
||||
|
||||
// ========== UI 工具函数 ==========
|
||||
export const createSectionTitle = (Icon, text) => (
|
||||
<div className='flex items-center gap-2'>
|
||||
<Icon size={16} />
|
||||
{text}
|
||||
</div>
|
||||
);
|
||||
|
||||
// ========== 操作处理函数 ==========
|
||||
export const handleCopyUrl = async (url, t) => {
|
||||
if (await copy(url)) {
|
||||
showSuccess(t('复制成功'));
|
||||
}
|
||||
};
|
||||
|
||||
export const handleSpeedTest = (apiUrl) => {
|
||||
const encodedUrl = encodeURIComponent(apiUrl);
|
||||
const speedTestUrl = `https://www.tcptest.cn/http/${encodedUrl}`;
|
||||
window.open(speedTestUrl, '_blank', 'noopener,noreferrer');
|
||||
};
|
||||
|
||||
// ========== 状态映射函数 ==========
|
||||
export const getUptimeStatusColor = (status, uptimeStatusMap) =>
|
||||
uptimeStatusMap[status]?.color || '#8b9aa7';
|
||||
|
||||
export const getUptimeStatusText = (status, uptimeStatusMap, t) =>
|
||||
uptimeStatusMap[status]?.text || t('未知');
|
||||
|
||||
// ========== 监控列表渲染函数 ==========
|
||||
export const renderMonitorList = (
|
||||
monitors,
|
||||
getUptimeStatusColor,
|
||||
getUptimeStatusText,
|
||||
t,
|
||||
) => {
|
||||
if (!monitors || monitors.length === 0) {
|
||||
return (
|
||||
<div className='flex justify-center items-center py-4'>
|
||||
<Empty
|
||||
image={<IllustrationConstruction style={ILLUSTRATION_SIZE} />}
|
||||
darkModeImage={
|
||||
<IllustrationConstructionDark style={ILLUSTRATION_SIZE} />
|
||||
}
|
||||
title={t('暂无监控数据')}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const grouped = {};
|
||||
monitors.forEach((m) => {
|
||||
const g = m.group || '';
|
||||
if (!grouped[g]) grouped[g] = [];
|
||||
grouped[g].push(m);
|
||||
});
|
||||
|
||||
const renderItem = (monitor, idx) => (
|
||||
<div key={idx} className='p-2 hover:bg-white rounded-lg transition-colors'>
|
||||
<div className='flex items-center justify-between mb-1'>
|
||||
<div className='flex items-center gap-2'>
|
||||
<div
|
||||
className='w-2 h-2 rounded-full flex-shrink-0'
|
||||
style={{ backgroundColor: getUptimeStatusColor(monitor.status) }}
|
||||
/>
|
||||
<span className='text-sm font-medium text-gray-900'>
|
||||
{monitor.name}
|
||||
</span>
|
||||
</div>
|
||||
<span className='text-xs text-gray-500'>
|
||||
{((monitor.uptime || 0) * 100).toFixed(2)}%
|
||||
</span>
|
||||
</div>
|
||||
<div className='flex items-center gap-2'>
|
||||
<span className='text-xs text-gray-500'>
|
||||
{getUptimeStatusText(monitor.status)}
|
||||
</span>
|
||||
<div className='flex-1'>
|
||||
<Progress
|
||||
percent={(monitor.uptime || 0) * 100}
|
||||
showInfo={false}
|
||||
aria-label={`${monitor.name} uptime`}
|
||||
stroke={getUptimeStatusColor(monitor.status)}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
return Object.entries(grouped).map(([gname, list]) => (
|
||||
<div key={gname || 'default'} className='mb-2'>
|
||||
{gname && (
|
||||
<>
|
||||
<div className='text-md font-semibold text-gray-500 px-2 py-1'>
|
||||
{gname}
|
||||
</div>
|
||||
<Divider />
|
||||
</>
|
||||
)}
|
||||
{list.map(renderItem)}
|
||||
</div>
|
||||
));
|
||||
};
|
||||
|
||||
// ========== 数据处理函数 ==========
|
||||
export const processRawData = (
|
||||
data,
|
||||
dataExportDefaultTime,
|
||||
initializeMaps,
|
||||
updateMapValue,
|
||||
) => {
|
||||
const result = {
|
||||
totalQuota: 0,
|
||||
totalTimes: 0,
|
||||
totalTokens: 0,
|
||||
uniqueModels: new Set(),
|
||||
timePoints: [],
|
||||
timeQuotaMap: new Map(),
|
||||
timeTokensMap: new Map(),
|
||||
timeCountMap: new Map(),
|
||||
};
|
||||
|
||||
data.forEach((item) => {
|
||||
if (item.model_name) {
|
||||
result.uniqueModels.add(item.model_name);
|
||||
}
|
||||
result.totalTokens += item.token_used;
|
||||
result.totalQuota += item.quota;
|
||||
result.totalTimes += item.count;
|
||||
|
||||
const timeKey = timestamp2string1(item.created_at, dataExportDefaultTime);
|
||||
if (!result.timePoints.includes(timeKey)) {
|
||||
result.timePoints.push(timeKey);
|
||||
}
|
||||
|
||||
initializeMaps(
|
||||
timeKey,
|
||||
result.timeQuotaMap,
|
||||
result.timeTokensMap,
|
||||
result.timeCountMap,
|
||||
);
|
||||
updateMapValue(result.timeQuotaMap, timeKey, item.quota);
|
||||
updateMapValue(result.timeTokensMap, timeKey, item.token_used);
|
||||
updateMapValue(result.timeCountMap, timeKey, item.count);
|
||||
});
|
||||
|
||||
result.timePoints.sort();
|
||||
return result;
|
||||
};
|
||||
|
||||
export const calculateTrendData = (
|
||||
timePoints,
|
||||
timeQuotaMap,
|
||||
timeTokensMap,
|
||||
timeCountMap,
|
||||
dataExportDefaultTime,
|
||||
) => {
|
||||
const quotaTrend = timePoints.map((time) => timeQuotaMap.get(time) || 0);
|
||||
const tokensTrend = timePoints.map((time) => timeTokensMap.get(time) || 0);
|
||||
const countTrend = timePoints.map((time) => timeCountMap.get(time) || 0);
|
||||
|
||||
const rpmTrend = [];
|
||||
const tpmTrend = [];
|
||||
|
||||
if (timePoints.length >= 2) {
|
||||
const interval = getTimeInterval(dataExportDefaultTime);
|
||||
|
||||
for (let i = 0; i < timePoints.length; i++) {
|
||||
rpmTrend.push(timeCountMap.get(timePoints[i]) / interval);
|
||||
tpmTrend.push(timeTokensMap.get(timePoints[i]) / interval);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
balance: [],
|
||||
usedQuota: [],
|
||||
requestCount: [],
|
||||
times: countTrend,
|
||||
consumeQuota: quotaTrend,
|
||||
tokens: tokensTrend,
|
||||
rpm: rpmTrend,
|
||||
tpm: tpmTrend,
|
||||
};
|
||||
};
|
||||
|
||||
export const aggregateDataByTimeAndModel = (data, dataExportDefaultTime) => {
|
||||
const aggregatedData = new Map();
|
||||
|
||||
data.forEach((item) => {
|
||||
const timeKey = timestamp2string1(item.created_at, dataExportDefaultTime);
|
||||
const modelKey = item.model_name;
|
||||
const key = `${timeKey}-${modelKey}`;
|
||||
|
||||
if (!aggregatedData.has(key)) {
|
||||
aggregatedData.set(key, {
|
||||
time: timeKey,
|
||||
model: modelKey,
|
||||
quota: 0,
|
||||
count: 0,
|
||||
});
|
||||
}
|
||||
|
||||
const existing = aggregatedData.get(key);
|
||||
existing.quota += item.quota;
|
||||
existing.count += item.count;
|
||||
});
|
||||
|
||||
return aggregatedData;
|
||||
};
|
||||
|
||||
export const generateChartTimePoints = (
|
||||
aggregatedData,
|
||||
data,
|
||||
dataExportDefaultTime,
|
||||
) => {
|
||||
let chartTimePoints = Array.from(
|
||||
new Set([...aggregatedData.values()].map((d) => d.time)),
|
||||
);
|
||||
|
||||
if (chartTimePoints.length < DEFAULTS.MAX_TREND_POINTS) {
|
||||
const lastTime = Math.max(...data.map((item) => item.created_at));
|
||||
const interval = getTimeInterval(dataExportDefaultTime, true);
|
||||
|
||||
chartTimePoints = Array.from(
|
||||
{ length: DEFAULTS.MAX_TREND_POINTS },
|
||||
(_, i) =>
|
||||
timestamp2string1(lastTime - (6 - i) * interval, dataExportDefaultTime),
|
||||
);
|
||||
}
|
||||
|
||||
return chartTimePoints;
|
||||
};
|
||||
@@ -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
|
||||
*/
|
||||
|
||||
export function setStatusData(data) {
|
||||
localStorage.setItem('status', JSON.stringify(data));
|
||||
localStorage.setItem('system_name', data.system_name);
|
||||
localStorage.setItem('logo', data.logo);
|
||||
localStorage.setItem('footer_html', data.footer_html);
|
||||
localStorage.setItem('quota_per_unit', data.quota_per_unit);
|
||||
// 兼容:保留旧字段,同时写入新的额度展示类型
|
||||
localStorage.setItem('display_in_currency', data.display_in_currency);
|
||||
localStorage.setItem('quota_display_type', data.quota_display_type || 'USD');
|
||||
localStorage.setItem('enable_drawing', data.enable_drawing);
|
||||
localStorage.setItem('enable_task', data.enable_task);
|
||||
localStorage.setItem('enable_data_export', data.enable_data_export);
|
||||
localStorage.setItem('chats', JSON.stringify(data.chats));
|
||||
localStorage.setItem(
|
||||
'data_export_default_time',
|
||||
data.data_export_default_time,
|
||||
);
|
||||
localStorage.setItem(
|
||||
'default_collapse_sidebar',
|
||||
data.default_collapse_sidebar,
|
||||
);
|
||||
localStorage.setItem('mj_notify_enabled', data.mj_notify_enabled);
|
||||
|
||||
// 体验中心配置
|
||||
localStorage.setItem(
|
||||
'experience_center_enable_group_select',
|
||||
data.experience_center_enable_group_select ?? 'true',
|
||||
);
|
||||
localStorage.setItem(
|
||||
'experience_center_enable_web_search',
|
||||
data.experience_center_enable_web_search ?? 'false',
|
||||
);
|
||||
localStorage.setItem(
|
||||
'experience_center_enable_file_upload',
|
||||
data.experience_center_enable_file_upload ?? 'false',
|
||||
);
|
||||
localStorage.setItem(
|
||||
'experience_center_upload_max_size',
|
||||
data.experience_center_upload_max_size ?? '10',
|
||||
);
|
||||
localStorage.setItem(
|
||||
'experience_center_allowed_file_types',
|
||||
data.experience_center_allowed_file_types ??
|
||||
'image/*,.pdf,.doc,.docx,.ppt,.pptx,.xls,.xlsx,.txt,.csv,.json,.xml',
|
||||
);
|
||||
localStorage.setItem(
|
||||
'experience_center_enable_image_gen',
|
||||
data.experience_center_enable_image_gen ?? 'false',
|
||||
);
|
||||
localStorage.setItem(
|
||||
'experience_center_image_gen_models',
|
||||
data.experience_center_image_gen_models ?? 'dall-e-3,gpt-image-1',
|
||||
);
|
||||
localStorage.setItem(
|
||||
'experience_center_default_image_size',
|
||||
data.experience_center_default_image_size ?? '1024x1024',
|
||||
);
|
||||
localStorage.setItem(
|
||||
'experience_center_enable_drag_upload',
|
||||
data.experience_center_enable_drag_upload ?? 'true',
|
||||
);
|
||||
|
||||
if (data.chat_link) {
|
||||
// localStorage.setItem('chat_link', data.chat_link);
|
||||
} else {
|
||||
localStorage.removeItem('chat_link');
|
||||
}
|
||||
if (data.chat_link2) {
|
||||
// localStorage.setItem('chat_link2', data.chat_link2);
|
||||
} else {
|
||||
localStorage.removeItem('chat_link2');
|
||||
}
|
||||
if (data.docs_link) {
|
||||
localStorage.setItem('docs_link', data.docs_link);
|
||||
} else {
|
||||
localStorage.removeItem('docs_link');
|
||||
}
|
||||
}
|
||||
|
||||
export const DEFAULT_LOGIN_REDIRECT = '/key-management';
|
||||
const USER_STORAGE_KEY = 'user';
|
||||
const POST_LOGIN_REDIRECT_KEY = 'post_login_redirect';
|
||||
|
||||
export function getUserData() {
|
||||
const raw = localStorage.getItem(USER_STORAGE_KEY);
|
||||
if (!raw) return null;
|
||||
try {
|
||||
const data = JSON.parse(raw);
|
||||
return data && typeof data === 'object' ? data : null;
|
||||
} catch {
|
||||
localStorage.removeItem(USER_STORAGE_KEY);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function setUserData(data) {
|
||||
if (!data) {
|
||||
clearUserData();
|
||||
return;
|
||||
}
|
||||
localStorage.setItem(USER_STORAGE_KEY, JSON.stringify(data));
|
||||
}
|
||||
|
||||
export function clearUserData() {
|
||||
localStorage.removeItem(USER_STORAGE_KEY);
|
||||
localStorage.removeItem('current_org_id');
|
||||
}
|
||||
|
||||
export function isSafePostLoginRedirect(path) {
|
||||
if (!path || typeof path !== 'string') return false;
|
||||
if (!path.startsWith('/') || path.startsWith('//')) return false;
|
||||
// 浏览器把 \ 当作 /,「/\evil.com」会被解析成协议相对地址跳到站外
|
||||
if (path.includes('\\')) return false;
|
||||
if (/^\/(?:login|register|reset)(?:$|[/?#])/.test(path)) return false;
|
||||
// 企业认证页(/org/login、/org/register、/org/:slug/login)同样不可作为
|
||||
// 登录后回跳目标,否则登录成功会被带回登录页
|
||||
return !/^\/org(?:\/[^/?#]+)?\/(?:login|register)(?:$|[/?#])/.test(path);
|
||||
}
|
||||
|
||||
export function savePostLoginRedirect(path) {
|
||||
if (isSafePostLoginRedirect(path)) {
|
||||
sessionStorage.setItem(POST_LOGIN_REDIRECT_KEY, path);
|
||||
}
|
||||
}
|
||||
|
||||
export function consumePostLoginRedirect(defaultPath = DEFAULT_LOGIN_REDIRECT) {
|
||||
const path = sessionStorage.getItem(POST_LOGIN_REDIRECT_KEY);
|
||||
sessionStorage.removeItem(POST_LOGIN_REDIRECT_KEY);
|
||||
return isSafePostLoginRedirect(path) ? path : defaultPath;
|
||||
}
|
||||
@@ -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
|
||||
*/
|
||||
|
||||
// 极简事件总线,用于在不建立父子 props 链的前提下让页面间互相通知
|
||||
// 典型场景:任务日志轮询到某任务完成后,通知使用日志刷新,使额度/费用统计即时更新
|
||||
const listeners = new Map();
|
||||
|
||||
export const EVENTS = {
|
||||
TASK_COMPLETED: 'task_completed',
|
||||
};
|
||||
|
||||
export const subscribe = (event, handler) => {
|
||||
if (!listeners.has(event)) listeners.set(event, new Set());
|
||||
listeners.get(event).add(handler);
|
||||
return () => {
|
||||
const set = listeners.get(event);
|
||||
if (set) set.delete(handler);
|
||||
};
|
||||
};
|
||||
|
||||
export const emit = (event, payload) => {
|
||||
const set = listeners.get(event);
|
||||
if (!set) return;
|
||||
set.forEach((fn) => {
|
||||
try {
|
||||
fn(payload);
|
||||
} catch (e) {
|
||||
// 单个订阅者异常不应阻断其他订阅者
|
||||
// eslint-disable-next-line no-console
|
||||
console.error('eventBus listener error:', e);
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,77 @@
|
||||
/*
|
||||
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 getExperienceCenterValue = (
|
||||
status,
|
||||
statusKey,
|
||||
storageKey,
|
||||
defaultValue = '',
|
||||
) => {
|
||||
const statusValue = status?.[statusKey];
|
||||
if (statusValue !== undefined && statusValue !== null && statusValue !== '') {
|
||||
return statusValue;
|
||||
}
|
||||
|
||||
const storageValue = localStorage.getItem(storageKey);
|
||||
if (
|
||||
storageValue !== null &&
|
||||
storageValue !== undefined &&
|
||||
storageValue !== ''
|
||||
) {
|
||||
return storageValue;
|
||||
}
|
||||
|
||||
return defaultValue;
|
||||
};
|
||||
|
||||
export const getExperienceCenterBool = (
|
||||
status,
|
||||
statusKey,
|
||||
storageKey,
|
||||
defaultValue = false,
|
||||
) => {
|
||||
const value = getExperienceCenterValue(
|
||||
status,
|
||||
statusKey,
|
||||
storageKey,
|
||||
defaultValue,
|
||||
);
|
||||
if (typeof value === 'boolean') {
|
||||
return value;
|
||||
}
|
||||
return String(value).toLowerCase() === 'true';
|
||||
};
|
||||
|
||||
export const getExperienceCenterPositiveInt = (
|
||||
status,
|
||||
statusKey,
|
||||
storageKey,
|
||||
defaultValue,
|
||||
) => {
|
||||
const value = parseInt(
|
||||
getExperienceCenterValue(
|
||||
status,
|
||||
statusKey,
|
||||
storageKey,
|
||||
String(defaultValue),
|
||||
),
|
||||
10,
|
||||
);
|
||||
return Number.isFinite(value) && value > 0 ? value : defaultValue;
|
||||
};
|
||||
@@ -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
|
||||
*/
|
||||
|
||||
// 把当前会话的 messages 数组转成可分享的 Markdown 文档。
|
||||
//
|
||||
// 设计要点:
|
||||
// - 用户消息 / 助手消息分别用 ## 二级标题,沿用 Claude / ChatGPT 导出风格;
|
||||
// - 多模态消息的图片渲染为 ;文件渲染为 [文件名](url);
|
||||
// - 助手消息附带的"参考来源"卡片转写为脚注式链接列表;
|
||||
// - 时间戳标在每条消息标题旁,方便回溯;
|
||||
// - 没有 HTML、没有样式,导出后可直接贴到 Obsidian / Notion / GitHub。
|
||||
|
||||
const formatTs = (ms) => {
|
||||
if (!ms) return '';
|
||||
const d = new Date(ms);
|
||||
const pad = (n) => ('0' + n).slice(-2);
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
};
|
||||
|
||||
const partToMarkdown = (part) => {
|
||||
if (!part || typeof part !== 'object') return '';
|
||||
if (part.type === 'text') {
|
||||
return typeof part.text === 'string' ? part.text : '';
|
||||
}
|
||||
if (part.type === 'image_url') {
|
||||
const url = part.image_url?.url || '';
|
||||
return url ? `\n\n\n` : '';
|
||||
}
|
||||
if (part.type === 'file') {
|
||||
const f = part.file || {};
|
||||
const name = f.filename || f.file_name || 'file';
|
||||
const url = f.file_data || '';
|
||||
return url ? `\n\n📎 [${name}](${url})\n` : `\n\n📎 ${name}\n`;
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
const renderMessageBody = (message) => {
|
||||
if (typeof message.content === 'string') {
|
||||
return message.content;
|
||||
}
|
||||
if (Array.isArray(message.content)) {
|
||||
return message.content.map(partToMarkdown).filter(Boolean).join('\n');
|
||||
}
|
||||
return '';
|
||||
};
|
||||
|
||||
const renderSources = (message) => {
|
||||
if (
|
||||
!Array.isArray(message.webSearchSources) ||
|
||||
message.webSearchSources.length === 0
|
||||
) {
|
||||
return '';
|
||||
}
|
||||
const lines = message.webSearchSources.map((s, i) => {
|
||||
const idx = s.index || i + 1;
|
||||
const title = s.title || s.url || '';
|
||||
return `${idx}. [${title}](${s.url})`;
|
||||
});
|
||||
return `\n\n**参考来源**\n\n${lines.join('\n')}\n`;
|
||||
};
|
||||
|
||||
const ROLE_LABEL = {
|
||||
user: '👤 用户',
|
||||
assistant: '🤖 助手',
|
||||
system: '⚙️ 系统',
|
||||
};
|
||||
|
||||
/**
|
||||
* 把会话转换为 Markdown 字符串。
|
||||
* @param {object} opts
|
||||
* @param {string} opts.title 会话标题(如无则用日期)
|
||||
* @param {Array} opts.messages 当前 message 数组
|
||||
* @returns {string} markdown
|
||||
*/
|
||||
export const conversationToMarkdown = ({ title, messages }) => {
|
||||
const safeTitle =
|
||||
(title && title.trim()) || `Conversation ${formatTs(Date.now())}`;
|
||||
const lines = [`# ${safeTitle}`, ''];
|
||||
lines.push(`*Exported at ${formatTs(Date.now())}*`, '');
|
||||
lines.push('---', '');
|
||||
|
||||
for (const m of messages || []) {
|
||||
if (!m || !m.role) continue;
|
||||
// loading / error 的中间态不导出,保持文档干净
|
||||
if (m.status === 'loading' || m.status === 'incomplete') continue;
|
||||
const label = ROLE_LABEL[m.role] || m.role;
|
||||
const tsStr = m.createAt ? ` · ${formatTs(m.createAt)}` : '';
|
||||
lines.push(`## ${label}${tsStr}`, '');
|
||||
const body = renderMessageBody(m).trim();
|
||||
if (body) lines.push(body, '');
|
||||
const srcs = renderSources(m);
|
||||
if (srcs) lines.push(srcs.trim(), '');
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
};
|
||||
|
||||
/**
|
||||
* 把会话内容下载为 .md 文件。
|
||||
* @param {object} opts 同 conversationToMarkdown
|
||||
* @returns {boolean} 是否成功触发下载
|
||||
*/
|
||||
export const downloadConversationAsMarkdown = ({ title, messages }) => {
|
||||
if (!Array.isArray(messages) || messages.length === 0) return false;
|
||||
const md = conversationToMarkdown({ title, messages });
|
||||
const safeFilename = ((title && title.trim()) || 'conversation')
|
||||
.replace(/[<>:"/\\|?*\x00-\x1F]/g, '_')
|
||||
.slice(0, 80);
|
||||
const blob = new Blob([md], { type: 'text/markdown;charset=utf-8;' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `${safeFilename}.md`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
return true;
|
||||
};
|
||||
@@ -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
|
||||
*/
|
||||
|
||||
// 导出当前页日志为 CSV,只在前端处理,不新增后端接口
|
||||
// 作用域:仅当前页(rows 是已加载到内存的列表)。如需全量导出,后续可接后端 stream 接口
|
||||
// 用 \uFEFF BOM 让 Excel 自动识别 UTF-8;字段值里遇到 "、,、换行 的用双引号包裹并转义
|
||||
|
||||
const escapeCsvCell = (value) => {
|
||||
if (value === null || value === undefined) return '';
|
||||
const s = String(value);
|
||||
if (
|
||||
s.includes('"') ||
|
||||
s.includes(',') ||
|
||||
s.includes('\n') ||
|
||||
s.includes('\r')
|
||||
) {
|
||||
return '"' + s.replace(/"/g, '""') + '"';
|
||||
}
|
||||
return s;
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {Array<{key: string, title: string, format?: (row:any)=>string}>} columns
|
||||
* @param {Array<Object>} rows
|
||||
* @param {string} filename
|
||||
*/
|
||||
export const exportToCsv = (columns, rows, filename) => {
|
||||
const header = columns.map((c) => escapeCsvCell(c.title)).join(',');
|
||||
const body = rows
|
||||
.map((row) =>
|
||||
columns
|
||||
.map((c) => {
|
||||
const raw =
|
||||
typeof c.format === 'function' ? c.format(row) : row[c.key];
|
||||
return escapeCsvCell(raw);
|
||||
})
|
||||
.join(','),
|
||||
)
|
||||
.join('\n');
|
||||
|
||||
const csv = '\uFEFF' + header + '\n' + body;
|
||||
const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
// 把秒级时间戳格式化为 CSV 友好的 YYYY-MM-DD HH:mm:ss,空值回落为空串
|
||||
export const formatTimestampForCsv = (sec) => {
|
||||
if (!sec) return '';
|
||||
const d = new Date(sec * 1000);
|
||||
const pad = (n) => ('0' + n).slice(-2);
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`;
|
||||
};
|
||||
@@ -0,0 +1,185 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
// 体验中心:把用户多选的若干条消息导出为 TXT / Word 文件。
|
||||
//
|
||||
// 设计要点:
|
||||
// - 纯文本导出,多模态 part(图片/文件)渲染为 [图片] / [文件: name] 占位;
|
||||
// - 跳过 loading / incomplete 中间态消息;
|
||||
// - filter 天然保序,导出顺序 == 会话顺序;
|
||||
// - Word 走 docx 库,动态 import 懒加载,首次导出 Word 才拉这个 chunk。
|
||||
|
||||
const ROLE_LABEL = {
|
||||
user: '用户',
|
||||
assistant: '助手',
|
||||
system: '系统',
|
||||
};
|
||||
|
||||
// formatTs 把毫秒时间戳格式化为 YYYY-MM-DD HH:mm
|
||||
const formatTs = (ms) => {
|
||||
if (!ms) return '';
|
||||
const d = new Date(ms);
|
||||
const pad = (n) => ('0' + n).slice(-2);
|
||||
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`;
|
||||
};
|
||||
|
||||
// messageToText 把单条消息的 content 规整为纯文本:
|
||||
// - string content 原样返回;
|
||||
// - 多模态数组:text part 取文本,image_url → [图片],file → [文件: name],换行连接。
|
||||
const messageToText = (m) => {
|
||||
if (!m) return '';
|
||||
const content = m.content;
|
||||
if (typeof content === 'string') return content;
|
||||
if (!Array.isArray(content)) return '';
|
||||
return content
|
||||
.map((part) => {
|
||||
if (!part || typeof part !== 'object') return '';
|
||||
if (part.type === 'text') {
|
||||
return typeof part.text === 'string' ? part.text : '';
|
||||
}
|
||||
if (part.type === 'image_url') return '[图片]';
|
||||
if (part.type === 'file') {
|
||||
const f = part.file || {};
|
||||
const name = f.filename || f.file_name || '';
|
||||
return name ? `[文件: ${name}]` : '[文件]';
|
||||
}
|
||||
return '';
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
};
|
||||
|
||||
/**
|
||||
* 按会话原始顺序取出被选中、且可导出的消息。
|
||||
* @param {Array} messages 完整消息数组
|
||||
* @param {Set} selectedIds 被选中的 message.id 集合
|
||||
* @returns {Array}
|
||||
*/
|
||||
export const getSelectedMessagesInOrder = (messages, selectedIds) => {
|
||||
if (!Array.isArray(messages) || !selectedIds || selectedIds.size === 0) {
|
||||
return [];
|
||||
}
|
||||
return messages.filter(
|
||||
(m) =>
|
||||
m &&
|
||||
selectedIds.has(m.id) &&
|
||||
m.status !== 'loading' &&
|
||||
m.status !== 'incomplete',
|
||||
);
|
||||
};
|
||||
|
||||
// safeFilename 清理非法字符 + 限长,复用 exportConversation.js 的规则
|
||||
const safeFilename = (title) =>
|
||||
((title && title.trim()) || 'messages')
|
||||
// eslint-disable-next-line no-control-regex
|
||||
.replace(/[<>:"/\\|?*\x00-\x1F]/g, '_')
|
||||
.slice(0, 80);
|
||||
|
||||
// triggerDownload 走项目通用的 Blob + anchor 下载模式
|
||||
const triggerDownload = (blob, filename) => {
|
||||
const url = URL.createObjectURL(blob);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = filename;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
};
|
||||
|
||||
/**
|
||||
* 把选中的消息导出为 .txt 文件。
|
||||
* @returns {boolean} 是否成功触发下载(无可导出消息时返回 false)
|
||||
*/
|
||||
export const exportSelectedAsTxt = (messages, selectedIds, title) => {
|
||||
const selected = getSelectedMessagesInOrder(messages, selectedIds);
|
||||
if (selected.length === 0) return false;
|
||||
|
||||
const safeTitle = (title && title.trim()) || '导出消息';
|
||||
const lines = [`${safeTitle}(导出于 ${formatTs(Date.now())})`, ''];
|
||||
for (const m of selected) {
|
||||
const label = ROLE_LABEL[m.role] || m.role || '消息';
|
||||
const tsStr = m.createAt ? ` (${formatTs(m.createAt)})` : '';
|
||||
lines.push(`【${label}】${tsStr}`);
|
||||
const body = messageToText(m).trim();
|
||||
if (body) lines.push(body);
|
||||
lines.push('');
|
||||
}
|
||||
|
||||
const blob = new Blob([lines.join('\n')], {
|
||||
type: 'text/plain;charset=utf-8;',
|
||||
});
|
||||
triggerDownload(blob, `${safeFilename(title)}.txt`);
|
||||
return true;
|
||||
};
|
||||
|
||||
/**
|
||||
* 把选中的消息导出为 .docx(Word)文件。docx 库动态 import 懒加载。
|
||||
* 纯文本段落:加粗角色标题 + 正文段落;Markdown 标记原样保留为文本。
|
||||
* @returns {Promise<boolean>} 是否成功触发下载(无可导出消息时返回 false)
|
||||
*/
|
||||
export const exportSelectedAsWord = async (messages, selectedIds, title) => {
|
||||
const selected = getSelectedMessagesInOrder(messages, selectedIds);
|
||||
if (selected.length === 0) return false;
|
||||
|
||||
const { Document, Paragraph, TextRun, Packer } = await import('docx');
|
||||
|
||||
const safeTitle = (title && title.trim()) || '导出消息';
|
||||
const children = [
|
||||
new Paragraph({
|
||||
children: [new TextRun({ text: safeTitle, bold: true, size: 32 })],
|
||||
}),
|
||||
new Paragraph({
|
||||
children: [
|
||||
new TextRun({
|
||||
text: `导出于 ${formatTs(Date.now())}`,
|
||||
italics: true,
|
||||
size: 18,
|
||||
color: '888888',
|
||||
}),
|
||||
],
|
||||
}),
|
||||
new Paragraph({ text: '' }),
|
||||
];
|
||||
|
||||
for (const m of selected) {
|
||||
const label = ROLE_LABEL[m.role] || m.role || '消息';
|
||||
const tsStr = m.createAt ? `(${formatTs(m.createAt)})` : '';
|
||||
children.push(
|
||||
new Paragraph({
|
||||
children: [new TextRun({ text: `【${label}】${tsStr}`, bold: true })],
|
||||
}),
|
||||
);
|
||||
const body = messageToText(m).trim();
|
||||
if (body) {
|
||||
// docx 不会对 \n 自动换行,逐行拆成独立段落。
|
||||
// 用 /\r\n|\r|\n/ 兼容三种行尾,避免模型输出含 \r\n 时段尾留下不可见的 \r
|
||||
// (Word 会把它渲染成方框等乱码字符)。
|
||||
for (const line of body.split(/\r\n|\r|\n/)) {
|
||||
children.push(new Paragraph({ text: line }));
|
||||
}
|
||||
}
|
||||
children.push(new Paragraph({ text: '' }));
|
||||
}
|
||||
|
||||
const doc = new Document({ sections: [{ children }] });
|
||||
const blob = await Packer.toBlob(doc);
|
||||
triggerDownload(blob, `${safeFilename(title)}.docx`);
|
||||
return true;
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
/*
|
||||
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 { createBrowserHistory } from 'history';
|
||||
|
||||
export const history = createBrowserHistory();
|
||||
@@ -0,0 +1,38 @@
|
||||
/*
|
||||
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 * from './history';
|
||||
export * from './auth';
|
||||
export * from './utils';
|
||||
export * from './base64';
|
||||
export * from './api';
|
||||
export * from './render';
|
||||
export * from './log';
|
||||
export * from './data';
|
||||
export * from './token';
|
||||
export * from './boolean';
|
||||
export * from './dashboard';
|
||||
export * from './experienceCenter';
|
||||
export * from './playgroundCapability';
|
||||
export * from './playgroundHistory';
|
||||
export * from './passkey';
|
||||
export * from './loginFlow';
|
||||
export * from './avatar';
|
||||
export * from './paging';
|
||||
export * from './officialPrice';
|
||||
@@ -0,0 +1,30 @@
|
||||
/*
|
||||
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 function getLogOther(otherStr) {
|
||||
if (otherStr === undefined || otherStr === null || otherStr === '') {
|
||||
otherStr = '{}';
|
||||
}
|
||||
let other = JSON.parse(otherStr);
|
||||
// 确保返回对象而不是 null(处理 JSON.parse("null") 的情况)
|
||||
if (other === null || typeof other !== 'object') {
|
||||
return {};
|
||||
}
|
||||
return other;
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
/*
|
||||
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 { API, updateAPI } from './api';
|
||||
import { clearUserData, consumePostLoginRedirect, setUserData } from './data';
|
||||
import { showError, showSuccess } from './utils';
|
||||
|
||||
const SESSION_NOT_PERSISTED_MESSAGE =
|
||||
'登录成功但浏览器未能保存登录会话,请确认 Cookie 未被拦截后重试';
|
||||
|
||||
// Verifies that the session cookie issued by the login endpoint was actually
|
||||
// persisted by the browser before treating the user as logged in. Some
|
||||
// environments (third-party-cookie blocking, privacy extensions, mismatched
|
||||
// SameSite/Secure attrs behind a proxy) silently drop the Set-Cookie, which
|
||||
// previously left users stuck on a half-logged-in state that only a manual
|
||||
// cache wipe could recover from. Returns true on success, false on failure.
|
||||
export async function finishLogin({
|
||||
data,
|
||||
userDispatch,
|
||||
navigate,
|
||||
t = (s) => s,
|
||||
successMessage,
|
||||
redirectOverride,
|
||||
}) {
|
||||
setUserData(data);
|
||||
// Recreate the axios instance so any in-flight request map from a prior
|
||||
// session is dropped before we issue the verification GET.
|
||||
updateAPI();
|
||||
|
||||
let verifiedUser;
|
||||
try {
|
||||
const res = await API.get('/api/user/self', {
|
||||
skipErrorHandler: true,
|
||||
disableDuplicate: true,
|
||||
});
|
||||
if (!res.data?.success || !res.data?.data) {
|
||||
throw new Error(res.data?.message || 'session verify failed');
|
||||
}
|
||||
verifiedUser = res.data.data;
|
||||
} catch {
|
||||
clearUserData();
|
||||
updateAPI();
|
||||
userDispatch({ type: 'logout' });
|
||||
showError(t(SESSION_NOT_PERSISTED_MESSAGE));
|
||||
return false;
|
||||
}
|
||||
|
||||
setUserData(verifiedUser);
|
||||
userDispatch({ type: 'login', payload: verifiedUser });
|
||||
|
||||
const message =
|
||||
successMessage === undefined ? t('登录成功!') : successMessage;
|
||||
if (message) {
|
||||
showSuccess(message);
|
||||
}
|
||||
// org_only(仅企业资源)用户默认落企业空间,与 AuthRedirect 一致:默认落地页
|
||||
// (秘钥管理)挂载即调用被 BlockOrgOnlyMode 拦截的 /api/token,会先弹报错再被
|
||||
// orgConfined 踢回 /org;企业中心整体关闭时 orgConfined 不生效,会一直停在报错页
|
||||
const defaultRedirect =
|
||||
verifiedUser.org_only_mode === true ? '/org' : undefined;
|
||||
navigate(redirectOverride ?? consumePostLoginRedirect(defaultRedirect), {
|
||||
replace: true,
|
||||
});
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
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 normalizeGroups = (groups) => {
|
||||
if (!Array.isArray(groups)) return [];
|
||||
return groups.map((group) => String(group).trim()).filter(Boolean);
|
||||
};
|
||||
|
||||
export const getEffectiveUserGroup = (userGroup) => userGroup || 'default';
|
||||
|
||||
export const isGroupAllowed = (groups, userGroup) => {
|
||||
const allowedGroups = normalizeGroups(groups);
|
||||
if (allowedGroups.length === 0) return true;
|
||||
return allowedGroups.includes(getEffectiveUserGroup(userGroup));
|
||||
};
|
||||
|
||||
export const isHeaderActionButtonVisible = (config, key, userGroup) => {
|
||||
let buttons = config;
|
||||
|
||||
if (typeof buttons === 'string') {
|
||||
try {
|
||||
buttons = JSON.parse(buttons);
|
||||
} catch (_error) {
|
||||
buttons = null;
|
||||
}
|
||||
}
|
||||
|
||||
if (!Array.isArray(buttons)) return true;
|
||||
|
||||
const button = buttons.find((item) => item?.key === key);
|
||||
if (!button) return true;
|
||||
|
||||
return button.enabled !== false && isGroupAllowed(button.groups, userGroup);
|
||||
};
|
||||
|
||||
export const isConfigEnabled = (config) => {
|
||||
if (typeof config === 'boolean') return config;
|
||||
if (!config || typeof config !== 'object') return false;
|
||||
return config.enabled !== false;
|
||||
};
|
||||
|
||||
export const getConfigGroups = (config) => {
|
||||
if (!config || typeof config !== 'object') return [];
|
||||
return normalizeGroups(config.groups);
|
||||
};
|
||||
|
||||
export const getVisibleGroupOptions = (groupOptions, selectedGroups) => {
|
||||
const normalizedSelected = normalizeGroups(selectedGroups);
|
||||
const known = new Set((groupOptions || []).map((group) => group.value));
|
||||
const extras = normalizedSelected
|
||||
.filter((group) => !known.has(group))
|
||||
.map((group) => ({ value: group, label: group }));
|
||||
return [...(groupOptions || []), ...extras];
|
||||
};
|
||||
@@ -0,0 +1,85 @@
|
||||
/*
|
||||
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 * as navigationVisibility from './navigationVisibility.js';
|
||||
|
||||
test('header tutorial action follows the saved enabled switch', () => {
|
||||
assert.equal(
|
||||
typeof navigationVisibility.isHeaderActionButtonVisible,
|
||||
'function',
|
||||
);
|
||||
|
||||
const disabledConfig = [
|
||||
{ key: 'tutorial', enabled: false, groups: [] },
|
||||
];
|
||||
|
||||
assert.equal(
|
||||
navigationVisibility.isHeaderActionButtonVisible?.(
|
||||
disabledConfig,
|
||||
'tutorial',
|
||||
'default',
|
||||
),
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test('header tutorial action follows its visible user groups', () => {
|
||||
const groupedConfig = JSON.stringify([
|
||||
{ key: 'tutorial', enabled: true, groups: ['vip'] },
|
||||
]);
|
||||
|
||||
assert.equal(
|
||||
navigationVisibility.isHeaderActionButtonVisible?.(
|
||||
groupedConfig,
|
||||
'tutorial',
|
||||
'default',
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
navigationVisibility.isHeaderActionButtonVisible?.(
|
||||
groupedConfig,
|
||||
'tutorial',
|
||||
'vip',
|
||||
),
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test('header actions stay visible when their saved config is unavailable', () => {
|
||||
assert.equal(
|
||||
navigationVisibility.isHeaderActionButtonVisible?.(
|
||||
'not-json',
|
||||
'tutorial',
|
||||
'default',
|
||||
),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
navigationVisibility.isHeaderActionButtonVisible?.(
|
||||
JSON.stringify([{ key: 'pricing', enabled: false }]),
|
||||
'tutorial',
|
||||
'default',
|
||||
),
|
||||
true,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,471 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
// ============================================================================
|
||||
// 模型原厂(官方)价格 · 折扣计算纯函数
|
||||
// ----------------------------------------------------------------------------
|
||||
// 官方价由管理员在 系统设置-倍率设置-模型原厂价格 维护,单位 ¥(平台按人民币兑
|
||||
// 美元 1:1 口径,与站内计价基准 model_ratio×2 同量纲)。折扣只做前端展示,
|
||||
// 不参与任何计费。折扣率一律用「实付/官方」的数值比计算,绝不从格式化字符串反推。
|
||||
// 保持纯 JS(无 JSX/无副作用)以便 node --test 直测。
|
||||
// ============================================================================
|
||||
|
||||
const DISCOUNT_EPSILON = 0.995; // 比值 ≥ 该阈值视为无折扣(避免 9.9 折之类的噪声标签)
|
||||
|
||||
const isPositiveFinite = (v) =>
|
||||
typeof v === 'number' && Number.isFinite(v) && v > 0;
|
||||
|
||||
/**
|
||||
* 单价折扣比:实付 / 官方。任一值非法或实付不低于官方(含加价)→ null(不展示)。
|
||||
*/
|
||||
export const computeDiscountRatio = (actualPrice, officialPrice) => {
|
||||
if (!isPositiveFinite(actualPrice) || !isPositiveFinite(officialPrice)) {
|
||||
return null;
|
||||
}
|
||||
const ratio = actualPrice / officialPrice;
|
||||
if (ratio >= DISCOUNT_EPSILON) return null;
|
||||
return ratio;
|
||||
};
|
||||
|
||||
/**
|
||||
* 从多个方向的折扣比中挑选卡片徽标使用的「代表折扣」。
|
||||
* 取有效值中的最大比值(= 折扣最保守的方向),避免「输入 2.5 折、输出 5 折」
|
||||
* 时徽标夸大宣传;任一方向为 null(无折扣/加价)→ 整体不出徽标,防止误导。
|
||||
*/
|
||||
export const pickBadgeDiscount = (ratios) => {
|
||||
const list = Array.isArray(ratios) ? ratios : [ratios];
|
||||
const valid = list.filter((r) => r !== null && r !== undefined);
|
||||
if (valid.length === 0 || valid.length !== list.length) return null;
|
||||
return Math.max(...valid);
|
||||
};
|
||||
|
||||
/**
|
||||
* 折扣文案:中文用「X 折」(如 0.25 → "2.5折"),其他语言用 "-75%"。
|
||||
* @param {number} ratio 实付/官方 比值 (0,1)
|
||||
* @param {string} language i18next 当前语言
|
||||
*/
|
||||
export const formatDiscountLabel = (ratio, language = 'zh') => {
|
||||
if (!isPositiveFinite(ratio) || ratio >= 1) return '';
|
||||
if (String(language).toLowerCase().startsWith('zh')) {
|
||||
// 保留 1 位小数并去掉尾零:0.25→2.5折,0.5→5折,0.08→0.8折
|
||||
const zhe = Math.round(ratio * 100) / 10;
|
||||
return `${zhe}折`;
|
||||
}
|
||||
return `-${Math.round((1 - ratio) * 100)}%`;
|
||||
};
|
||||
|
||||
/**
|
||||
* 组装某模型在指定分组倍率下的官方价对比信息(数值层,不做货币格式化)。
|
||||
* @param {object} record 模型定价记录(/api/pricing data 条目)
|
||||
* @param {object|undefined} official { input, output, per_call },单位 ¥(1:1 兑美元口径),/1M tokens 或 /次
|
||||
* @param {number} usedGroupRatio 实际使用的分组倍率(已含等级折扣)
|
||||
* @returns {null | {
|
||||
* officialInput?: number, officialOutput?: number, officialPerCall?: number,
|
||||
* discountInput?: number|null, discountOutput?: number|null, discountPerCall?: number|null,
|
||||
* badgeDiscount: number|null,
|
||||
* }}
|
||||
*/
|
||||
export const buildOfficialComparison = (record, official, usedGroupRatio) => {
|
||||
if (!record || !official) return null;
|
||||
if (!isPositiveFinite(usedGroupRatio)) return null;
|
||||
|
||||
if (record.quota_type === 0) {
|
||||
const hasInput = isPositiveFinite(official.input);
|
||||
const hasOutput = isPositiveFinite(official.output);
|
||||
if (!hasInput && !hasOutput) return null;
|
||||
const actualInput = record.model_ratio * 2 * usedGroupRatio;
|
||||
const actualOutput =
|
||||
record.model_ratio * (record.completion_ratio ?? 1) * 2 * usedGroupRatio;
|
||||
const discountInput = hasInput
|
||||
? computeDiscountRatio(actualInput, official.input)
|
||||
: undefined;
|
||||
const discountOutput = hasOutput
|
||||
? computeDiscountRatio(actualOutput, official.output)
|
||||
: undefined;
|
||||
return {
|
||||
officialInput: hasInput ? official.input : undefined,
|
||||
officialOutput: hasOutput ? official.output : undefined,
|
||||
discountInput,
|
||||
discountOutput,
|
||||
badgeDiscount: pickBadgeDiscount(
|
||||
[discountInput, discountOutput].filter((d) => d !== undefined),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
if (record.quota_type === 1) {
|
||||
if (!isPositiveFinite(official.per_call)) return null;
|
||||
const actual = parseFloat(record.model_price) * usedGroupRatio;
|
||||
const discountPerCall = computeDiscountRatio(actual, official.per_call);
|
||||
return {
|
||||
officialPerCall: official.per_call,
|
||||
discountPerCall,
|
||||
badgeDiscount: discountPerCall,
|
||||
};
|
||||
}
|
||||
|
||||
// quota_type 2/3(按秒、按分辨率分档):官方价按档位登记(见 tierPricingOf),
|
||||
// 只服务成本核算与毛利,不上市场页——市场页的分组价表按档位横排,再叠一行
|
||||
// 逐档原价会把表挤爆,且分档模型的折扣本就要逐档看,一个整体徽标只会误导。
|
||||
return null;
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// 分档计费(视频按秒 / 图片按分辨率)
|
||||
// ----------------------------------------------------------------------------
|
||||
// 分档模型的每个档位单价互不相干(720p 与 1080p 可差数倍),官方价必须逐档登记:
|
||||
// 一个"整模型均价"在高档位必然算亏、低档位虚高,毛利与分佣都会失真。
|
||||
// 档位键与收入侧规范键同源(大小写不敏感,比较前一律归一)。
|
||||
// ============================================================================
|
||||
|
||||
export const normalizeTierKey = (key) =>
|
||||
String(key ?? '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
|
||||
/**
|
||||
* 该记录的分档计价元信息;非分档计费返回 null。
|
||||
* @returns {null | { field: 'per_second'|'per_image', unit: string,
|
||||
* tiers: Array<{key: string, label: string, basePrice: number}> }}
|
||||
*/
|
||||
export const tierPricingOf = (record) => {
|
||||
if (!record) return null;
|
||||
// 档位键为空的条目一律剔除:牌价按档位键存,空键在后端 normalizeTierMap 被拒、
|
||||
// 在前端 canonical 里被丢弃——若照样渲染输入框,用户填的值会静默消失且提示
|
||||
// 「你似乎并没有修改什么」。收入侧本身允许空 key(parseVideoPricing 无校验)。
|
||||
const mapTiers = (tiers, priceField) =>
|
||||
(tiers || [])
|
||||
.filter((t) => normalizeTierKey(t?.key) !== '')
|
||||
.map((t) => ({
|
||||
key: t.key,
|
||||
label: t.label || t.key,
|
||||
basePrice: Number(t[priceField]),
|
||||
}));
|
||||
if (record.quota_type === 2) {
|
||||
return {
|
||||
field: 'per_second',
|
||||
unit: '秒',
|
||||
tiers: mapTiers(record.video_second_pricing?.tiers, 'price_per_second'),
|
||||
};
|
||||
}
|
||||
if (record.quota_type === 3) {
|
||||
return {
|
||||
field: 'per_image',
|
||||
unit: '张',
|
||||
tiers: mapTiers(
|
||||
record.image_resolution_pricing?.tiers,
|
||||
'price_per_image',
|
||||
),
|
||||
};
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
/** 归一化取档位官方价;未填/非法 → undefined */
|
||||
export const tierPriceOf = (entry, field, tierKey) => {
|
||||
const map = entry?.[field];
|
||||
if (!map || typeof map !== 'object') return undefined;
|
||||
const want = normalizeTierKey(tierKey);
|
||||
const found = Object.keys(map).find((k) => normalizeTierKey(k) === want);
|
||||
if (found === undefined) return undefined;
|
||||
const v = map[found];
|
||||
return isPositiveFinite(v) ? v : undefined;
|
||||
};
|
||||
|
||||
/**
|
||||
* 分档模型的逐档折扣对照(管理端预览用;市场页不展示,理由见 buildOfficialComparison)。
|
||||
* @returns {null | Array<{key,label,basePrice,official?:number,discount?:number|null}>}
|
||||
*/
|
||||
export const buildTierComparison = (record, official) => {
|
||||
const pricing = tierPricingOf(record);
|
||||
if (!pricing) return null;
|
||||
return pricing.tiers.map((tier) => {
|
||||
const officialPrice = tierPriceOf(official, pricing.field, tier.key);
|
||||
return {
|
||||
...tier,
|
||||
official: officialPrice,
|
||||
discount:
|
||||
officialPrice === undefined
|
||||
? undefined
|
||||
: computeDiscountRatio(tier.basePrice, officialPrice),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
// ============================================================================
|
||||
// 管理端维护辅助(系统设置-倍率设置-模型原厂价格)
|
||||
// ----------------------------------------------------------------------------
|
||||
// 填写完整度判定 / 稳定序列化 / 导入校验。保持纯函数以便 node --test 直测。
|
||||
// ============================================================================
|
||||
|
||||
export const OFFICIAL_FILL_NA = 'na'; // 无可填字段的计费类型(未知形态 / 分档模型没有任何档位)
|
||||
export const OFFICIAL_FILL_EMPTY = 'empty';
|
||||
export const OFFICIAL_FILL_PARTIAL = 'partial';
|
||||
export const OFFICIAL_FILL_FILLED = 'filled';
|
||||
|
||||
/**
|
||||
* 官方价字段的固定顺序(序列化与遍历口径统一,避免键序影响比较)。
|
||||
* cache_read / cache_creation 不参与市场页折扣展示,只服务成本核算:
|
||||
* 收入侧对缓存读取与缓存创建单独计价,成本侧要「扣费的每一项都有成本价」,
|
||||
* 就必须有对应的原厂参照价。
|
||||
*/
|
||||
const OFFICIAL_SCALAR_FIELDS = [
|
||||
'input',
|
||||
'output',
|
||||
'per_call',
|
||||
'cache_read',
|
||||
'cache_creation',
|
||||
];
|
||||
|
||||
/** 分档字段:值是 { 档位键: ¥单价 } 映射,不是标量(校验/序列化都要区别对待) */
|
||||
export const OFFICIAL_TIER_FIELDS = ['per_second', 'per_image'];
|
||||
|
||||
const OFFICIAL_FIELDS = [...OFFICIAL_SCALAR_FIELDS, ...OFFICIAL_TIER_FIELDS];
|
||||
|
||||
export const isOfficialTierField = (field) =>
|
||||
OFFICIAL_TIER_FIELDS.includes(field);
|
||||
|
||||
const isTierField = isOfficialTierField;
|
||||
|
||||
/** 该字段是否填了有效值(标量 = 正数;分档 = 至少一个档位是正数) */
|
||||
const hasFieldValue = (entry, field) => {
|
||||
const v = entry?.[field];
|
||||
if (!isTierField(field)) return isPositiveFinite(v);
|
||||
if (!v || typeof v !== 'object') return false;
|
||||
return Object.values(v).some((p) => isPositiveFinite(p));
|
||||
};
|
||||
|
||||
/** 各计费类型下真正用得上的字段(其余字段填了也不生效) */
|
||||
const applicableFields = (quotaType) => {
|
||||
// per_image 对按量计费模型同样生效:Responses 内嵌出图是「token 费 + 出图调用费」
|
||||
// 相加,成本侧 CalcDirectCost 也是把 imageCost 加到 token 段上(不是二选一)。
|
||||
// 漏了它会把一条正在记账的基准标成「配置不生效」,诱导管理员删掉。
|
||||
if (quotaType === 0)
|
||||
return ['input', 'output', 'cache_read', 'cache_creation', 'per_image'];
|
||||
if (quotaType === 1) return ['per_call'];
|
||||
if (quotaType === 2) return ['per_second'];
|
||||
if (quotaType === 3) return ['per_image'];
|
||||
return [];
|
||||
};
|
||||
|
||||
/**
|
||||
* 某模型官方价的填写完整度。
|
||||
* 按量计费(quota_type=0)必须输入价 + 输出价都填才算「已填写」:市场页的折扣
|
||||
* 徽标走 pickBadgeDiscount(任一方向缺失即不出徽标),只填一侧其实不生效——
|
||||
* 若把它计入已填写,管理员会误以为该模型已经配好。
|
||||
*
|
||||
* 缓存两项按 need 传入时才纳入判定:只有收入侧确实按缓存计费的模型才需要它们,
|
||||
* 给所有模型都要求会让绝大多数模型永远停在「部分填写」,状态也就失去指示意义。
|
||||
*
|
||||
* 分档计费(按秒 / 按分辨率)以 need.tierKeys 为必填集:收入侧逐档定价,成本侧
|
||||
* 也逐档记账,缺一档就是那一档的毛利算不出来,必须显示「部分填写」点名。
|
||||
* 该模型没有任何档位(分档配置被清空)时无字段可填,返回 NA。
|
||||
* @param {{needCacheRead?: boolean, needCacheCreation?: boolean, tierKeys?: string[]}} [need]
|
||||
*/
|
||||
export const officialFillState = (quotaType, entry, need) => {
|
||||
const e = entry || {};
|
||||
if (quotaType === 0) {
|
||||
const required = ['input', 'output'];
|
||||
if (need?.needCacheRead) required.push('cache_read');
|
||||
if (need?.needCacheCreation) required.push('cache_creation');
|
||||
const filled = required.filter((f) => isPositiveFinite(e[f])).length;
|
||||
if (filled === required.length) return OFFICIAL_FILL_FILLED;
|
||||
if (filled > 0) return OFFICIAL_FILL_PARTIAL;
|
||||
return OFFICIAL_FILL_EMPTY;
|
||||
}
|
||||
if (quotaType === 1) {
|
||||
return isPositiveFinite(e.per_call)
|
||||
? OFFICIAL_FILL_FILLED
|
||||
: OFFICIAL_FILL_EMPTY;
|
||||
}
|
||||
if (quotaType === 2 || quotaType === 3) {
|
||||
const field = quotaType === 2 ? 'per_second' : 'per_image';
|
||||
const tiers = need?.tierKeys || [];
|
||||
if (tiers.length === 0) return OFFICIAL_FILL_NA;
|
||||
const filled = tiers.filter(
|
||||
(k) => tierPriceOf(e, field, k) !== undefined,
|
||||
).length;
|
||||
if (filled === tiers.length) return OFFICIAL_FILL_FILLED;
|
||||
if (filled > 0) return OFFICIAL_FILL_PARTIAL;
|
||||
return OFFICIAL_FILL_EMPTY;
|
||||
}
|
||||
return OFFICIAL_FILL_NA;
|
||||
};
|
||||
|
||||
/**
|
||||
* 该条目在当前计费类型下是否**完全不生效**(填了值,但没有一个字段用得上)。
|
||||
* 典型成因:模型事后改了计费方式(按量↔按次)、改成按秒分档、导入时字段填错。
|
||||
* 这类条目在页面上「看起来没填」,却会被原样保存、永远不产生折扣——必须显式标出,
|
||||
* 否则管理员会以为配好了。
|
||||
*
|
||||
* 判定看的是「有没有任何一个**适用**字段有值」,不能拿 officialFillState 的
|
||||
* EMPTY 来代替:按量计费模型只填了缓存价时 fillState 仍是 EMPTY(缓存不算必填),
|
||||
* 但那个值成本侧照用不误,标成「配置不生效」是误报。
|
||||
*/
|
||||
export const isOfficialEntryInert = (quotaType, entry) => {
|
||||
const e = entry || {};
|
||||
if (!OFFICIAL_FIELDS.some((f) => hasFieldValue(e, f))) return false;
|
||||
return !applicableFields(quotaType).some((f) => hasFieldValue(e, f));
|
||||
};
|
||||
|
||||
/**
|
||||
* 稳定序列化:模型名按字典序、字段按固定序、丢弃非正数与空条目。
|
||||
* 「是否有未保存修改」必须用它比较——直接 JSON.stringify 对键序敏感,
|
||||
* 「清空某字段后又填回同一个值」会让条目被删除再追加到末尾,键序变化,
|
||||
* 于是页面永远挂着「有未保存的修改」。
|
||||
*/
|
||||
export const canonicalOfficialPriceJSON = (map) => {
|
||||
const src = map && typeof map === 'object' ? map : {};
|
||||
const out = {};
|
||||
Object.keys(src)
|
||||
.sort()
|
||||
.forEach((model) => {
|
||||
const entry = src[model];
|
||||
if (!entry || typeof entry !== 'object') return;
|
||||
const kept = {};
|
||||
OFFICIAL_FIELDS.forEach((field) => {
|
||||
if (!isTierField(field)) {
|
||||
if (isPositiveFinite(entry[field])) kept[field] = entry[field];
|
||||
return;
|
||||
}
|
||||
// 分档字段:档位键归一 + 按字典序落盘,序列化结果才与键序无关;
|
||||
// 归一后同键取字典序靠前的原键,避免「1080p / 1080P」两写法互相覆盖出抖动
|
||||
const rawTiers = entry[field];
|
||||
if (
|
||||
!rawTiers ||
|
||||
typeof rawTiers !== 'object' ||
|
||||
Array.isArray(rawTiers)
|
||||
)
|
||||
return;
|
||||
const normalized = {};
|
||||
Object.keys(rawTiers)
|
||||
.sort() // 同一归一键有多种写法时取字典序靠前的那个,结果才确定
|
||||
.forEach((rawKey) => {
|
||||
const key = normalizeTierKey(rawKey);
|
||||
if (!key || normalized[key] !== undefined) return;
|
||||
if (isPositiveFinite(rawTiers[rawKey]))
|
||||
normalized[key] = rawTiers[rawKey];
|
||||
});
|
||||
const keys = Object.keys(normalized).sort();
|
||||
if (keys.length === 0) return;
|
||||
// 按归一键字典序重建:JSON.stringify 依插入序输出,归一前排序不足以定序
|
||||
kept[field] = keys.reduce((acc, k) => {
|
||||
acc[k] = normalized[k];
|
||||
return acc;
|
||||
}, {});
|
||||
});
|
||||
if (Object.keys(kept).length > 0) out[model] = kept;
|
||||
});
|
||||
return JSON.stringify(out);
|
||||
};
|
||||
|
||||
/**
|
||||
* 导入校验:把任意 JSON 收敛成合法的
|
||||
* model -> {input?,output?,per_call?,cache_read?,cache_creation?,per_second?,per_image?} 映射
|
||||
*(per_second / per_image 的值是 { 档位键: ¥单价 })。
|
||||
* 校验口径与后端 ValidateOfficialPriceJSONString 一致(必须是 > 0 的有限数、
|
||||
* 不允许空条目),未知字段视为错误而非静默丢弃——拼错 per_call 会导致整条配置
|
||||
* 看似导入成功却完全不生效。
|
||||
* @returns {{ value: object, errors: string[] }}
|
||||
*/
|
||||
export const sanitizeOfficialPriceMap = (raw) => {
|
||||
const errors = [];
|
||||
const value = {};
|
||||
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
||||
return {
|
||||
value,
|
||||
errors: [
|
||||
'顶层必须是 { 模型名: { input, output, per_call, cache_read, cache_creation, per_second: {档位: 价}, per_image: {档位: 价} } } 结构',
|
||||
],
|
||||
};
|
||||
}
|
||||
Object.keys(raw).forEach((model) => {
|
||||
const name = String(model).trim();
|
||||
if (!name) {
|
||||
errors.push('存在空模型名');
|
||||
return;
|
||||
}
|
||||
const entry = raw[model];
|
||||
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
|
||||
errors.push(`${name}: 价格必须是对象`);
|
||||
return;
|
||||
}
|
||||
const unknown = Object.keys(entry).filter(
|
||||
(k) => !OFFICIAL_FIELDS.includes(k),
|
||||
);
|
||||
if (unknown.length > 0) {
|
||||
errors.push(`${name}: 不认识的字段 ${unknown.join('、')}`);
|
||||
return;
|
||||
}
|
||||
const kept = {};
|
||||
let fieldFailed = false;
|
||||
OFFICIAL_FIELDS.forEach((field) => {
|
||||
const v = entry[field];
|
||||
if (v === undefined || v === null || v === '') return;
|
||||
if (isTierField(field)) {
|
||||
// 分档字段是 { 档位键: 价格 } 映射;写成标量说明量纲搞错了,必须报错
|
||||
if (typeof v !== 'object' || Array.isArray(v)) {
|
||||
errors.push(`${name}.${field}: 必须是 { 档位键: 价格 } 结构`);
|
||||
fieldFailed = true;
|
||||
return;
|
||||
}
|
||||
const tiers = {};
|
||||
Object.keys(v).forEach((rawKey) => {
|
||||
const key = normalizeTierKey(rawKey);
|
||||
if (!key) {
|
||||
errors.push(`${name}.${field}: 存在空档位键`);
|
||||
fieldFailed = true;
|
||||
return;
|
||||
}
|
||||
// 归一后重键:只差大小写的两档会互相覆盖,静默丢掉一档的牌价
|
||||
if (tiers[key] !== undefined) {
|
||||
errors.push(
|
||||
`${name}.${field}: 档位键 ${key} 重复(档位键大小写不敏感)`,
|
||||
);
|
||||
fieldFailed = true;
|
||||
return;
|
||||
}
|
||||
const tv = Number(v[rawKey]);
|
||||
if (!isPositiveFinite(tv)) {
|
||||
errors.push(`${name}.${field}.${rawKey}: 必须是大于 0 的数值`);
|
||||
fieldFailed = true;
|
||||
return;
|
||||
}
|
||||
tiers[key] = tv;
|
||||
});
|
||||
if (Object.keys(tiers).length > 0) kept[field] = tiers;
|
||||
return;
|
||||
}
|
||||
const n = Number(v);
|
||||
if (!isPositiveFinite(n)) {
|
||||
errors.push(`${name}.${field}: 必须是大于 0 的数值`);
|
||||
fieldFailed = true;
|
||||
return;
|
||||
}
|
||||
kept[field] = n;
|
||||
});
|
||||
if (Object.keys(kept).length === 0) {
|
||||
// 已按字段报过错就不再叠一条「未填写任何字段」,否则同一处问题报两遍
|
||||
if (!fieldFailed) errors.push(`${name}: 未填写任何官方价字段`);
|
||||
return;
|
||||
}
|
||||
value[name] = kept;
|
||||
});
|
||||
return { value, errors };
|
||||
};
|
||||
@@ -0,0 +1,424 @@
|
||||
/*
|
||||
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 {
|
||||
computeDiscountRatio,
|
||||
pickBadgeDiscount,
|
||||
formatDiscountLabel,
|
||||
buildOfficialComparison,
|
||||
officialFillState,
|
||||
isOfficialEntryInert,
|
||||
canonicalOfficialPriceJSON,
|
||||
sanitizeOfficialPriceMap,
|
||||
tierPricingOf,
|
||||
tierPriceOf,
|
||||
buildTierComparison,
|
||||
isOfficialTierField,
|
||||
} from './officialPrice.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 折扣比:实付/官方,数值层计算,加价与噪声折扣一律 null(不展示)
|
||||
// ---------------------------------------------------------------------------
|
||||
test('computeDiscountRatio basic and guard cases', () => {
|
||||
assert.equal(computeDiscountRatio(0.5, 2), 0.25);
|
||||
// 实付 ≥ 官方(含加价)→ 不展示
|
||||
assert.equal(computeDiscountRatio(2, 2), null);
|
||||
assert.equal(computeDiscountRatio(3, 2), null);
|
||||
// 9.96 折之类的噪声 → 不展示
|
||||
assert.equal(computeDiscountRatio(1.995, 2), null);
|
||||
// 非法输入
|
||||
assert.equal(computeDiscountRatio(0, 2), null);
|
||||
assert.equal(computeDiscountRatio(1, 0), null);
|
||||
assert.equal(computeDiscountRatio(NaN, 2), null);
|
||||
assert.equal(computeDiscountRatio(1, undefined), null);
|
||||
});
|
||||
|
||||
test('pickBadgeDiscount is conservative and all-or-nothing', () => {
|
||||
// 取比值最大(折扣最保守)的方向,避免夸大宣传
|
||||
assert.equal(pickBadgeDiscount([0.25, 0.5]), 0.5);
|
||||
assert.equal(pickBadgeDiscount([0.3]), 0.3);
|
||||
// 任一方向无折扣(null)→ 整体不出徽标
|
||||
assert.equal(pickBadgeDiscount([0.25, null]), null);
|
||||
assert.equal(pickBadgeDiscount([]), null);
|
||||
});
|
||||
|
||||
test('formatDiscountLabel per language', () => {
|
||||
assert.equal(formatDiscountLabel(0.25, 'zh'), '2.5折');
|
||||
assert.equal(formatDiscountLabel(0.25, 'zh-CN'), '2.5折');
|
||||
assert.equal(formatDiscountLabel(0.5, 'zh'), '5折');
|
||||
assert.equal(formatDiscountLabel(0.08, 'zh'), '0.8折');
|
||||
assert.equal(formatDiscountLabel(0.25, 'en'), '-75%');
|
||||
assert.equal(formatDiscountLabel(0.25, 'ja'), '-75%');
|
||||
// 无效比值不产生文案
|
||||
assert.equal(formatDiscountLabel(1.2, 'zh'), '');
|
||||
assert.equal(formatDiscountLabel(null, 'en'), '');
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 组装:按量 / 按次 / 按秒 × 折扣 / 加价 / 未配置
|
||||
// ---------------------------------------------------------------------------
|
||||
const perTokenRecord = {
|
||||
quota_type: 0,
|
||||
model_ratio: 1, // 实付输入 = 1×2×ratio = 2×ratio (¥/1M)
|
||||
completion_ratio: 4, // 实付输出 = 8×ratio
|
||||
};
|
||||
|
||||
test('buildOfficialComparison per-token with discount', () => {
|
||||
const c = buildOfficialComparison(
|
||||
perTokenRecord,
|
||||
{ input: 8, output: 32 },
|
||||
1, // usedGroupRatio
|
||||
);
|
||||
// 实付 2/8 = 0.25;输出 8/32 = 0.25
|
||||
assert.equal(c.discountInput, 0.25);
|
||||
assert.equal(c.discountOutput, 0.25);
|
||||
assert.equal(c.badgeDiscount, 0.25);
|
||||
assert.equal(c.officialInput, 8);
|
||||
assert.equal(c.officialOutput, 32);
|
||||
});
|
||||
|
||||
test('buildOfficialComparison respects group ratio (incl. level discount)', () => {
|
||||
const c = buildOfficialComparison(
|
||||
perTokenRecord,
|
||||
{ input: 8, output: 32 },
|
||||
0.5,
|
||||
);
|
||||
assert.equal(c.discountInput, 0.125);
|
||||
assert.equal(c.badgeDiscount, 0.125);
|
||||
});
|
||||
|
||||
test('buildOfficialComparison badge is conservative across directions', () => {
|
||||
// 输入 2.5 折、输出 5 折 → 徽标 5 折
|
||||
const c = buildOfficialComparison(
|
||||
perTokenRecord,
|
||||
{ input: 8, output: 16 },
|
||||
1,
|
||||
);
|
||||
assert.equal(c.discountInput, 0.25);
|
||||
assert.equal(c.discountOutput, 0.5);
|
||||
assert.equal(c.badgeDiscount, 0.5);
|
||||
});
|
||||
|
||||
test('buildOfficialComparison markup direction suppresses badge entirely', () => {
|
||||
// 输入打折但输出高于官方 → 整体不出徽标(防误导)
|
||||
const c = buildOfficialComparison(perTokenRecord, { input: 8, output: 4 }, 1);
|
||||
assert.equal(c.discountInput, 0.25);
|
||||
assert.equal(c.discountOutput, null);
|
||||
assert.equal(c.badgeDiscount, null);
|
||||
});
|
||||
|
||||
test('buildOfficialComparison per-call', () => {
|
||||
const record = { quota_type: 1, model_price: '0.1' };
|
||||
const c = buildOfficialComparison(record, { per_call: 0.4 }, 1);
|
||||
assert.equal(c.discountPerCall, 0.25);
|
||||
assert.equal(c.badgeDiscount, 0.25);
|
||||
assert.equal(c.officialPerCall, 0.4);
|
||||
// 加价 → null 徽标
|
||||
const up = buildOfficialComparison(record, { per_call: 0.05 }, 1);
|
||||
assert.equal(up.badgeDiscount, null);
|
||||
});
|
||||
|
||||
test('buildOfficialComparison unsupported / missing cases', () => {
|
||||
// 官方价未配置
|
||||
assert.equal(buildOfficialComparison(perTokenRecord, undefined, 1), null);
|
||||
// 按秒分档暂不支持
|
||||
assert.equal(
|
||||
buildOfficialComparison({ quota_type: 2 }, { input: 1 }, 1),
|
||||
null,
|
||||
);
|
||||
// 官方价对象存在但与计费类型不匹配(按量模型只配了 per_call)
|
||||
assert.equal(
|
||||
buildOfficialComparison(perTokenRecord, { per_call: 1 }, 1),
|
||||
null,
|
||||
);
|
||||
// 分组倍率非法
|
||||
assert.equal(buildOfficialComparison(perTokenRecord, { input: 8 }, 0), null);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 管理端维护辅助:填写完整度 / 稳定序列化 / 导入校验
|
||||
// ---------------------------------------------------------------------------
|
||||
test('officialFillState treats half-filled per-token models as partial', () => {
|
||||
assert.equal(officialFillState(0, undefined), 'empty');
|
||||
assert.equal(officialFillState(0, {}), 'empty');
|
||||
assert.equal(officialFillState(0, { input: 8 }), 'partial');
|
||||
assert.equal(officialFillState(0, { output: 8 }), 'partial');
|
||||
assert.equal(officialFillState(0, { input: 8, output: 16 }), 'filled');
|
||||
// 非正数不算填写(与后端校验同口径)
|
||||
assert.equal(officialFillState(0, { input: 0, output: 16 }), 'partial');
|
||||
// 按次计费
|
||||
assert.equal(officialFillState(1, {}), 'empty');
|
||||
assert.equal(officialFillState(1, { per_call: 0.4 }), 'filled');
|
||||
// 按次模型误配了 token 价 → 仍算未填(市场页不会用)
|
||||
assert.equal(officialFillState(1, { input: 1 }), 'empty');
|
||||
// 按秒分档不支持
|
||||
assert.equal(officialFillState(2, { input: 1 }), 'na');
|
||||
});
|
||||
|
||||
test('canonicalOfficialPriceJSON is key-order and noise insensitive', () => {
|
||||
const a = { 'b-model': { output: 2, input: 1 }, 'a-model': { per_call: 3 } };
|
||||
const b = { 'a-model': { per_call: 3 }, 'b-model': { input: 1, output: 2 } };
|
||||
assert.equal(canonicalOfficialPriceJSON(a), canonicalOfficialPriceJSON(b));
|
||||
// 空条目 / 非正数字段被丢弃,等价于「未填」
|
||||
assert.equal(canonicalOfficialPriceJSON({ m: {} }), '{}');
|
||||
assert.equal(canonicalOfficialPriceJSON({ m: { input: 0 } }), '{}');
|
||||
assert.equal(
|
||||
canonicalOfficialPriceJSON({ m: { input: 1, output: 0 } }),
|
||||
'{"m":{"input":1}}',
|
||||
);
|
||||
assert.equal(canonicalOfficialPriceJSON(undefined), '{}');
|
||||
});
|
||||
|
||||
test('sanitizeOfficialPriceMap mirrors backend validation', () => {
|
||||
const ok = sanitizeOfficialPriceMap({
|
||||
'gpt-4o': { input: '2.5', output: 10 },
|
||||
'sd-3': { per_call: 0.4 },
|
||||
});
|
||||
assert.deepEqual(ok.errors, []);
|
||||
assert.deepEqual(ok.value, {
|
||||
'gpt-4o': { input: 2.5, output: 10 },
|
||||
'sd-3': { per_call: 0.4 },
|
||||
});
|
||||
// 非法值 / 空条目 / 未知字段一律报错,不静默丢弃
|
||||
const bad = sanitizeOfficialPriceMap({
|
||||
a: { input: 0 },
|
||||
b: {},
|
||||
c: { percall: 1 },
|
||||
d: 'x',
|
||||
});
|
||||
assert.equal(bad.errors.length, 4);
|
||||
assert.deepEqual(bad.value, {});
|
||||
// 顶层结构错误
|
||||
assert.equal(sanitizeOfficialPriceMap([]).errors.length, 1);
|
||||
assert.equal(sanitizeOfficialPriceMap(null).errors.length, 1);
|
||||
});
|
||||
|
||||
test('isOfficialEntryInert flags silently dead entries', () => {
|
||||
// 模型改成按次计费后,旧的 token 价整条不生效
|
||||
assert.equal(isOfficialEntryInert(1, { input: 8, output: 24 }), true);
|
||||
// 模型改成按量计费后,旧的按次价整条不生效
|
||||
assert.equal(isOfficialEntryInert(0, { per_call: 0.4 }), true);
|
||||
// 按秒分档:填什么都不生效
|
||||
assert.equal(isOfficialEntryInert(2, { input: 8, output: 24 }), true);
|
||||
// 正常配置 / 只填一侧 / 没填 → 不是 inert
|
||||
assert.equal(isOfficialEntryInert(0, { input: 8, output: 24 }), false);
|
||||
assert.equal(isOfficialEntryInert(0, { input: 8 }), false);
|
||||
assert.equal(isOfficialEntryInert(1, { per_call: 0.4 }), false);
|
||||
assert.equal(isOfficialEntryInert(0, undefined), false);
|
||||
assert.equal(isOfficialEntryInert(2, undefined), false);
|
||||
// 非正数不算「填了值」
|
||||
assert.equal(isOfficialEntryInert(1, { input: 0 }), false);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 分档计费(按秒 / 按分辨率):逐档官方价
|
||||
// ---------------------------------------------------------------------------
|
||||
const videoRecord = {
|
||||
quota_type: 2,
|
||||
video_second_pricing: {
|
||||
tier_param: 'resolution',
|
||||
tiers: [
|
||||
{ key: '720p', label: '720P', price_per_second: 0.1 },
|
||||
{ key: '1080p', label: '1080P', price_per_second: 0.2 },
|
||||
],
|
||||
},
|
||||
};
|
||||
const imageRecord = {
|
||||
quota_type: 3,
|
||||
image_resolution_pricing: {
|
||||
tiers: [{ key: 'hd', label: 'HD', price_per_image: 0.05 }],
|
||||
},
|
||||
};
|
||||
|
||||
test('tierPricingOf maps both tiered billing types', () => {
|
||||
assert.equal(tierPricingOf(videoRecord).field, 'per_second');
|
||||
assert.deepEqual(tierPricingOf(videoRecord).tiers[1], {
|
||||
key: '1080p',
|
||||
label: '1080P',
|
||||
basePrice: 0.2,
|
||||
});
|
||||
assert.equal(tierPricingOf(imageRecord).field, 'per_image');
|
||||
assert.equal(tierPricingOf({ quota_type: 0 }), null);
|
||||
// 分档配置被清空的模型:不是 null,而是空档位列表(页面据此提示"无档位可填")
|
||||
assert.deepEqual(tierPricingOf({ quota_type: 2 }).tiers, []);
|
||||
});
|
||||
|
||||
test('tierPriceOf is case/whitespace insensitive', () => {
|
||||
const entry = { per_second: { '1080p': 0.5 } };
|
||||
assert.equal(tierPriceOf(entry, 'per_second', '1080P'), 0.5);
|
||||
assert.equal(tierPriceOf(entry, 'per_second', ' 1080p '), 0.5);
|
||||
assert.equal(tierPriceOf(entry, 'per_second', '720p'), undefined);
|
||||
// 非正数不算填写(与后端校验同口径)
|
||||
assert.equal(
|
||||
tierPriceOf({ per_second: { a: 0 } }, 'per_second', 'a'),
|
||||
undefined,
|
||||
);
|
||||
assert.equal(tierPriceOf(undefined, 'per_second', 'a'), undefined);
|
||||
});
|
||||
|
||||
test('buildTierComparison computes per-tier discount', () => {
|
||||
const c = buildTierComparison(videoRecord, {
|
||||
per_second: { '720P': 0.4, '1080p': 0.2 },
|
||||
});
|
||||
assert.equal(c[0].discount, 0.25); // 0.1 / 0.4
|
||||
// 站内价 = 官方价 → 无折扣(null),不是"未填"(undefined)
|
||||
assert.equal(c[1].discount, null);
|
||||
// 某档未填官方价 → undefined,逐档独立,不影响其他档
|
||||
const partial = buildTierComparison(videoRecord, {
|
||||
per_second: { '720p': 0.4 },
|
||||
});
|
||||
assert.equal(partial[1].official, undefined);
|
||||
assert.equal(partial[1].discount, undefined);
|
||||
assert.equal(buildTierComparison({ quota_type: 1 }, {}), null);
|
||||
});
|
||||
|
||||
test('officialFillState requires every tier of a tiered model', () => {
|
||||
const tierKeys = ['720p', '1080p'];
|
||||
assert.equal(officialFillState(2, undefined, { tierKeys }), 'empty');
|
||||
assert.equal(
|
||||
officialFillState(2, { per_second: { '720p': 1 } }, { tierKeys }),
|
||||
'partial',
|
||||
);
|
||||
assert.equal(
|
||||
officialFillState(
|
||||
2,
|
||||
{ per_second: { '720P': 1, '1080p': 2 } },
|
||||
{ tierKeys },
|
||||
),
|
||||
'filled',
|
||||
);
|
||||
// 按张分档同理,且不吃 per_second 的值
|
||||
assert.equal(
|
||||
officialFillState(3, { per_second: { hd: 1 } }, { tierKeys: ['hd'] }),
|
||||
'empty',
|
||||
);
|
||||
assert.equal(
|
||||
officialFillState(3, { per_image: { HD: 1 } }, { tierKeys: ['hd'] }),
|
||||
'filled',
|
||||
);
|
||||
// 没有任何档位可填 → NA(不能报"未填写",管理员无从下手)
|
||||
assert.equal(officialFillState(2, {}, { tierKeys: [] }), 'na');
|
||||
assert.equal(officialFillState(2, {}), 'na');
|
||||
});
|
||||
|
||||
test('tier entries participate in inert / canonical / sanitize', () => {
|
||||
// 按秒模型配了 token 价 → 整条不生效
|
||||
assert.equal(isOfficialEntryInert(2, { input: 8 }), true);
|
||||
assert.equal(isOfficialEntryInert(2, { per_second: { '1080p': 1 } }), false);
|
||||
// 按量模型配了分档价 → 同样不生效
|
||||
assert.equal(isOfficialEntryInert(0, { per_second: { '1080p': 1 } }), true);
|
||||
// 空档位映射不算"填了值"
|
||||
assert.equal(isOfficialEntryInert(0, { per_second: {} }), false);
|
||||
|
||||
// 序列化:档位键归一 + 定序,键序与大小写差异不产生"未保存修改"
|
||||
assert.equal(
|
||||
canonicalOfficialPriceJSON({
|
||||
m: { per_second: { '1080P': 2, '720p': 1 } },
|
||||
}),
|
||||
canonicalOfficialPriceJSON({
|
||||
m: { per_second: { '720P': 1, '1080p': 2 } },
|
||||
}),
|
||||
);
|
||||
assert.equal(
|
||||
canonicalOfficialPriceJSON({ m: { per_second: { '1080P': 2 } } }),
|
||||
'{"m":{"per_second":{"1080p":2}}}',
|
||||
);
|
||||
// 非正数档位被丢弃;丢空后整条不落盘
|
||||
assert.equal(
|
||||
canonicalOfficialPriceJSON({ m: { per_image: { hd: 0 } } }),
|
||||
'{}',
|
||||
);
|
||||
|
||||
// 导入:结构/数值/重键校验
|
||||
const ok = sanitizeOfficialPriceMap({
|
||||
v: { per_second: { '1080P': '0.5' } },
|
||||
});
|
||||
assert.deepEqual(ok.errors, []);
|
||||
assert.deepEqual(ok.value, { v: { per_second: { '1080p': 0.5 } } });
|
||||
assert.equal(
|
||||
sanitizeOfficialPriceMap({ v: { per_second: 0.5 } }).errors.length,
|
||||
1,
|
||||
);
|
||||
assert.equal(
|
||||
sanitizeOfficialPriceMap({ v: { per_second: { a: 0 } } }).errors.length,
|
||||
1,
|
||||
);
|
||||
assert.equal(
|
||||
sanitizeOfficialPriceMap({ v: { per_second: { hd: 1, HD: 2 } } }).errors
|
||||
.length,
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
test('tierPricingOf drops tiers with an unusable (empty) key', () => {
|
||||
// 收入侧允许空 key(parseVideoPricing 无校验),但空键的牌价存不下来
|
||||
//(后端拒收 / canonical 丢弃)。若照样渲染输入框,用户填的值会静默消失。
|
||||
const rec = {
|
||||
quota_type: 2,
|
||||
video_second_pricing: {
|
||||
tiers: [
|
||||
{ key: '', price_per_second: 3 },
|
||||
{ key: ' ', price_per_second: 4 },
|
||||
{ key: '1080p', price_per_second: 0.2 },
|
||||
],
|
||||
},
|
||||
};
|
||||
assert.deepEqual(
|
||||
tierPricingOf(rec).tiers.map((t) => t.key),
|
||||
['1080p'],
|
||||
);
|
||||
});
|
||||
|
||||
test('isOfficialTierField distinguishes map-valued fields', () => {
|
||||
assert.equal(isOfficialTierField('per_second'), true);
|
||||
assert.equal(isOfficialTierField('per_image'), true);
|
||||
assert.equal(isOfficialTierField('per_call'), false);
|
||||
assert.equal(isOfficialTierField('input'), false);
|
||||
});
|
||||
|
||||
test('per_image stays applicable to per-token models', () => {
|
||||
// Responses 内嵌出图 = token 费 + 出图调用费相加,成本侧同口径按 per_image 记账。
|
||||
// 把它标成「配置不生效」会诱导管理员删掉一条正在记账的基准。
|
||||
assert.equal(
|
||||
isOfficialEntryInert(0, { input: 8, per_image: { hd: 1 } }),
|
||||
false,
|
||||
);
|
||||
assert.equal(isOfficialEntryInert(0, { per_image: { hd: 1 } }), false);
|
||||
// 按秒价对按量模型确实不生效,仍要点名
|
||||
assert.equal(isOfficialEntryInert(0, { per_second: { '1080p': 1 } }), true);
|
||||
});
|
||||
|
||||
test('canonicalOfficialPriceJSON orders tier keys after normalization', () => {
|
||||
// 原始键序('Z' < 'a')与归一后键序('a' < 'z')相反:不按归一键重排的话,
|
||||
// 同一份配置会序列化出两种字节串,页面永远挂着「有未保存的修改」
|
||||
assert.equal(
|
||||
canonicalOfficialPriceJSON({ m: { per_second: { Z: 1, a: 2 } } }),
|
||||
'{"m":{"per_second":{"a":2,"z":1}}}',
|
||||
);
|
||||
});
|
||||
|
||||
test('sanitizeOfficialPriceMap rejects array-shaped tier maps', () => {
|
||||
// 数组不拦的话会被当对象处理,静默产出档位键 "0"/"1"
|
||||
const res = sanitizeOfficialPriceMap({ v: { per_second: [1, 2] } });
|
||||
assert.equal(res.errors.length, 1);
|
||||
assert.deepEqual(res.value, {});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
// 企业管理员(Owner)登录名的前置校验,与后端 controller.normalizeOrgOwnerLoginName /
|
||||
// common.OrgDirectLoginNameDenylist 保持一致。管理员登录名不再默认 admin——默认名让所有企业的
|
||||
// 管理员账号高度可预测(扩大撞库面),且 admin 命中直登黑名单,管理员反而用不了「账号直登」。
|
||||
// 前端只做同款前置提示,后端仍是唯一裁决方。
|
||||
|
||||
/** 3-32 位,字母开头,仅字母/数字/下划线/点/短横线。 */
|
||||
export const LOGIN_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_.-]{2,31}$/;
|
||||
|
||||
/** 保留登录名黑名单(与后端 common.OrgDirectLoginNameDenylist 逐项对齐)。 */
|
||||
export const RESERVED_LOGIN_NAMES = [
|
||||
'admin',
|
||||
'administrator',
|
||||
'root',
|
||||
'test',
|
||||
'user',
|
||||
'guest',
|
||||
'system',
|
||||
'manager',
|
||||
'owner',
|
||||
'operator',
|
||||
'sa',
|
||||
'superadmin',
|
||||
];
|
||||
|
||||
/** 是否命中保留名(大小写不敏感、去空格,与后端同口径)。 */
|
||||
export function isReservedLoginName(name) {
|
||||
return RESERVED_LOGIN_NAMES.includes(String(name || '').trim().toLowerCase());
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验企业管理员登录名,返回 null 表示通过,否则返回未翻译的错误文案 key。
|
||||
* 调用方自行 t() —— 文案与 OrgRegister 表单规则、后端错误文案三处一致。
|
||||
*/
|
||||
export function validateOrgOwnerLoginName(name) {
|
||||
const value = String(name || '').trim();
|
||||
if (!value) return '请设置管理员登录名';
|
||||
if (!LOGIN_NAME_PATTERN.test(value))
|
||||
return '登录名需为 3-32 位,以字母开头,仅可包含字母、数字、下划线、点或短横线';
|
||||
if (isReservedLoginName(value))
|
||||
return '该登录名为系统保留名称,请换一个登录名';
|
||||
return null;
|
||||
}
|
||||
@@ -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 test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import {
|
||||
LOGIN_NAME_PATTERN,
|
||||
RESERVED_LOGIN_NAMES,
|
||||
isReservedLoginName,
|
||||
validateOrgOwnerLoginName,
|
||||
} from './orgLoginName.js';
|
||||
|
||||
// 本文件的作用是把「前端前置校验」与后端 controller.normalizeOrgOwnerLoginName /
|
||||
// common.OrgDirectLoginNameDenylist 的口径钉住:两侧任一方改规则而另一方没跟,
|
||||
// 用户就会遇到「前端放行、提交才报错」或「前端拦住了后端其实允许的名字」。
|
||||
|
||||
test('保留名黑名单与后端 OrgDirectLoginNameDenylist 逐项一致', () => {
|
||||
assert.deepEqual(RESERVED_LOGIN_NAMES, [
|
||||
'admin',
|
||||
'administrator',
|
||||
'root',
|
||||
'test',
|
||||
'user',
|
||||
'guest',
|
||||
'system',
|
||||
'manager',
|
||||
'owner',
|
||||
'operator',
|
||||
'sa',
|
||||
'superadmin',
|
||||
]);
|
||||
});
|
||||
|
||||
test('保留名判定大小写不敏感且忽略首尾空格(同后端 IsDirectLoginNameDenied)', () => {
|
||||
for (const name of ['admin', 'ADMIN', ' Admin ', 'Root', 'SuperAdmin']) {
|
||||
assert.equal(isReservedLoginName(name), true, name);
|
||||
}
|
||||
for (const name of ['admin2', 'root_user', 'zhang.san', '', null, undefined]) {
|
||||
assert.equal(isReservedLoginName(name), false, String(name));
|
||||
}
|
||||
});
|
||||
|
||||
test('格式规则:3-32 位、字母开头、仅 字母/数字/_ . -', () => {
|
||||
for (const ok of ['abc', 'Lee_Wei', 'zhang.san', 'acme-ops', 'a'.repeat(32)]) {
|
||||
assert.equal(LOGIN_NAME_PATTERN.test(ok), true, ok);
|
||||
}
|
||||
for (const bad of [
|
||||
'ab', // 太短
|
||||
'a'.repeat(33), // 超长
|
||||
'1abc', // 数字开头
|
||||
'_abc', // 符号开头
|
||||
'管理员登录', // 非 ASCII
|
||||
'zhang san', // 含空格
|
||||
'a@bc', // 非法符号
|
||||
]) {
|
||||
assert.equal(LOGIN_NAME_PATTERN.test(bad), false, bad);
|
||||
}
|
||||
});
|
||||
|
||||
test('全局正则不带 g 标志:连续调用不会因 lastIndex 漂移而误判', () => {
|
||||
assert.equal(LOGIN_NAME_PATTERN.global, false);
|
||||
assert.equal(LOGIN_NAME_PATTERN.test('zhang.san'), true);
|
||||
assert.equal(LOGIN_NAME_PATTERN.test('zhang.san'), true);
|
||||
});
|
||||
|
||||
test('validateOrgOwnerLoginName 返回未翻译文案 key,通过时为 null', () => {
|
||||
assert.equal(validateOrgOwnerLoginName('zhang.san'), null);
|
||||
assert.equal(validateOrgOwnerLoginName(' Lee_Wei '), null); // 先 trim 再判
|
||||
assert.equal(validateOrgOwnerLoginName(''), '请设置管理员登录名');
|
||||
assert.equal(validateOrgOwnerLoginName(' '), '请设置管理员登录名');
|
||||
assert.equal(
|
||||
validateOrgOwnerLoginName('ab'),
|
||||
'登录名需为 3-32 位,以字母开头,仅可包含字母、数字、下划线、点或短横线',
|
||||
);
|
||||
assert.equal(
|
||||
validateOrgOwnerLoginName('Admin'),
|
||||
'该登录名为系统保留名称,请换一个登录名',
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
// 后端 common/page_info.go 的 GetPageQuery 对 page_size > 100 是**静默钳到
|
||||
// 100**——不报错、不提示。因此前端"传个大 page_size 一次取全"的写法拿到的
|
||||
// 永远只有前 100 条,且无从察觉。这类页面往往还带前端分页控件(Table 的
|
||||
// pagination),管理员翻到最后一页会以为已经看完全部数据。
|
||||
//
|
||||
// collectPagedItems 按后端返回的 total 逐页取全,是这类"取全部"场景的统一写法。
|
||||
export const ORG_PAGE_SIZE = 100;
|
||||
const DEFAULT_MAX_PAGES = 20;
|
||||
|
||||
/**
|
||||
* 逐页取全一个分页列表接口。
|
||||
*
|
||||
* @param {(page: number, pageSize: number) => Promise<any>} fetchPage
|
||||
* 取单页的函数,返回 axios 响应;页码从 1 开始。
|
||||
* @param {{pageSize?: number, maxPages?: number, shouldAbort?: () => boolean}} [options]
|
||||
* shouldAbort 每页请求前调用;返回 true 立即停止翻页并返回已取到的数据。
|
||||
* 调用方用它接入自己的竞态围栏(切企业/切实体时不再继续发请求)。
|
||||
* @returns {Promise<{items: any[], total: number, message: string, truncated: boolean}>}
|
||||
* items 已取到的全部条目(失败时保留已成功的页,不连带丢弃)
|
||||
* total 后端报告的总条数;后端未返回时回落为已取到的条数
|
||||
* message 首页即失败时的后端错误文案,否则为空
|
||||
* truncated 是否因触达 maxPages 上限而未取完
|
||||
*/
|
||||
export async function collectPagedItems(fetchPage, options = {}) {
|
||||
const pageSize = options.pageSize || ORG_PAGE_SIZE;
|
||||
const maxPages = options.maxPages || DEFAULT_MAX_PAGES;
|
||||
const items = [];
|
||||
let message = '';
|
||||
let truncated = false;
|
||||
let total = 0;
|
||||
|
||||
for (let page = 1; page <= maxPages; page += 1) {
|
||||
if (options.shouldAbort && options.shouldAbort()) {
|
||||
return { items, total: total || items.length, message, truncated };
|
||||
}
|
||||
let response;
|
||||
try {
|
||||
response = await fetchPage(page, pageSize);
|
||||
} catch (error) {
|
||||
// 网络错误 / HTTP 错误会让 axios reject。首页失败继续抛给调用方,
|
||||
// 保持它原有的 catch + showError 行为不变;**后续页失败必须吞掉**,
|
||||
// 否则异常冒泡会让调用方跳过 setState,把已经取到的前几页一起丢掉
|
||||
// ——那正是云脑任务时间线补页(R10)踩过并修掉的坑。
|
||||
if (page === 1) throw error;
|
||||
return { items, total: total || items.length, message, truncated };
|
||||
}
|
||||
if (!response?.data?.success) {
|
||||
// 同上:首页业务失败才算整体失败,后续页保留已到手的数据。
|
||||
if (page === 1) message = response?.data?.message || '';
|
||||
return { items, total: total || items.length, message, truncated };
|
||||
}
|
||||
const pageItems = response.data.data?.items || [];
|
||||
items.push(...pageItems);
|
||||
total = Number(response.data.data?.total || 0);
|
||||
if (pageItems.length < pageSize) break;
|
||||
if (total > 0 && items.length >= total) break;
|
||||
if (page === maxPages) truncated = true;
|
||||
}
|
||||
return { items, total: total || items.length, message, truncated };
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
/*
|
||||
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 function base64UrlToBuffer(base64url) {
|
||||
if (!base64url) return new ArrayBuffer(0);
|
||||
let padding = '='.repeat((4 - (base64url.length % 4)) % 4);
|
||||
const base64 = (base64url + padding).replace(/-/g, '+').replace(/_/g, '/');
|
||||
const rawData = window.atob(base64);
|
||||
const buffer = new ArrayBuffer(rawData.length);
|
||||
const uintArray = new Uint8Array(buffer);
|
||||
for (let i = 0; i < rawData.length; i += 1) {
|
||||
uintArray[i] = rawData.charCodeAt(i);
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
export function bufferToBase64Url(buffer) {
|
||||
if (!buffer) return '';
|
||||
const uintArray = new Uint8Array(buffer);
|
||||
let binary = '';
|
||||
for (let i = 0; i < uintArray.byteLength; i += 1) {
|
||||
binary += String.fromCharCode(uintArray[i]);
|
||||
}
|
||||
return window
|
||||
.btoa(binary)
|
||||
.replace(/\+/g, '-')
|
||||
.replace(/\//g, '_')
|
||||
.replace(/=+$/g, '');
|
||||
}
|
||||
|
||||
export function prepareCredentialCreationOptions(payload) {
|
||||
const options =
|
||||
payload?.publicKey ||
|
||||
payload?.PublicKey ||
|
||||
payload?.response ||
|
||||
payload?.Response;
|
||||
if (!options) {
|
||||
throw new Error('无法从服务端响应中解析 Passkey 注册参数');
|
||||
}
|
||||
const publicKey = {
|
||||
...options,
|
||||
challenge: base64UrlToBuffer(options.challenge),
|
||||
user: {
|
||||
...options.user,
|
||||
id: base64UrlToBuffer(options.user?.id),
|
||||
},
|
||||
};
|
||||
|
||||
if (Array.isArray(options.excludeCredentials)) {
|
||||
publicKey.excludeCredentials = options.excludeCredentials.map((item) => ({
|
||||
...item,
|
||||
id: base64UrlToBuffer(item.id),
|
||||
}));
|
||||
}
|
||||
|
||||
if (
|
||||
Array.isArray(options.attestationFormats) &&
|
||||
options.attestationFormats.length === 0
|
||||
) {
|
||||
delete publicKey.attestationFormats;
|
||||
}
|
||||
|
||||
return publicKey;
|
||||
}
|
||||
|
||||
export function prepareCredentialRequestOptions(payload) {
|
||||
const options =
|
||||
payload?.publicKey ||
|
||||
payload?.PublicKey ||
|
||||
payload?.response ||
|
||||
payload?.Response;
|
||||
if (!options) {
|
||||
throw new Error('无法从服务端响应中解析 Passkey 登录参数');
|
||||
}
|
||||
const publicKey = {
|
||||
...options,
|
||||
challenge: base64UrlToBuffer(options.challenge),
|
||||
};
|
||||
|
||||
if (Array.isArray(options.allowCredentials)) {
|
||||
publicKey.allowCredentials = options.allowCredentials.map((item) => ({
|
||||
...item,
|
||||
id: base64UrlToBuffer(item.id),
|
||||
}));
|
||||
}
|
||||
|
||||
return publicKey;
|
||||
}
|
||||
|
||||
export function buildRegistrationResult(credential) {
|
||||
if (!credential) return null;
|
||||
|
||||
const { response } = credential;
|
||||
const transports =
|
||||
typeof response.getTransports === 'function'
|
||||
? response.getTransports()
|
||||
: undefined;
|
||||
|
||||
return {
|
||||
id: credential.id,
|
||||
rawId: bufferToBase64Url(credential.rawId),
|
||||
type: credential.type,
|
||||
authenticatorAttachment: credential.authenticatorAttachment,
|
||||
response: {
|
||||
attestationObject: bufferToBase64Url(response.attestationObject),
|
||||
clientDataJSON: bufferToBase64Url(response.clientDataJSON),
|
||||
transports,
|
||||
},
|
||||
clientExtensionResults: credential.getClientExtensionResults?.() ?? {},
|
||||
};
|
||||
}
|
||||
|
||||
export function buildAssertionResult(assertion) {
|
||||
if (!assertion) return null;
|
||||
|
||||
const { response } = assertion;
|
||||
|
||||
return {
|
||||
id: assertion.id,
|
||||
rawId: bufferToBase64Url(assertion.rawId),
|
||||
type: assertion.type,
|
||||
authenticatorAttachment: assertion.authenticatorAttachment,
|
||||
response: {
|
||||
authenticatorData: bufferToBase64Url(response.authenticatorData),
|
||||
clientDataJSON: bufferToBase64Url(response.clientDataJSON),
|
||||
signature: bufferToBase64Url(response.signature),
|
||||
userHandle: response.userHandle
|
||||
? bufferToBase64Url(response.userHandle)
|
||||
: null,
|
||||
},
|
||||
clientExtensionResults: assertion.getClientExtensionResults?.() ?? {},
|
||||
};
|
||||
}
|
||||
|
||||
export async function isPasskeySupported() {
|
||||
if (typeof window === 'undefined' || !window.PublicKeyCredential) {
|
||||
return false;
|
||||
}
|
||||
if (
|
||||
typeof window.PublicKeyCredential.isConditionalMediationAvailable ===
|
||||
'function'
|
||||
) {
|
||||
try {
|
||||
const available =
|
||||
await window.PublicKeyCredential.isConditionalMediationAvailable();
|
||||
if (available) return true;
|
||||
} catch (error) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
if (
|
||||
typeof window.PublicKeyCredential
|
||||
.isUserVerifyingPlatformAuthenticatorAvailable === 'function'
|
||||
) {
|
||||
try {
|
||||
return await window.PublicKeyCredential.isUserVerifyingPlatformAuthenticatorAvailable();
|
||||
} catch (error) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
@@ -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
|
||||
*/
|
||||
|
||||
export const PAYPAL_RETURN_STATES = {
|
||||
success: { type: 'success', message: 'PayPal 充值成功' },
|
||||
pending: { type: 'info', message: 'PayPal 支付处理中,请稍后查看充值记录' },
|
||||
error: { type: 'error', message: 'PayPal 支付确认失败,请稍后重试' },
|
||||
cancelled: { type: 'info', message: '已取消 PayPal 支付' },
|
||||
};
|
||||
|
||||
export function parsePayPalQuote(payload) {
|
||||
const data = payload?.data?.data ?? payload?.data ?? payload;
|
||||
if (!data || data.currency !== 'USD') {
|
||||
throw new Error('Invalid PayPal quote currency');
|
||||
}
|
||||
const payAmount = Number(data.pay_amount);
|
||||
const basePayAmount = Number(data.base_pay_amount);
|
||||
const serviceFee = Number(data.service_fee);
|
||||
const cnyPayAmount = Number(data.cny_pay_amount);
|
||||
const exchangeRate = Number(data.exchange_rate);
|
||||
const quoteExpiresAt = Number(data.quote_expires_at);
|
||||
if (
|
||||
!Number.isFinite(payAmount) ||
|
||||
payAmount < 0.01 ||
|
||||
!Number.isFinite(basePayAmount) ||
|
||||
basePayAmount < 0.01 ||
|
||||
!Number.isFinite(serviceFee) ||
|
||||
serviceFee < 0 ||
|
||||
Math.abs(basePayAmount + serviceFee - payAmount) > 0.001 ||
|
||||
!Number.isFinite(cnyPayAmount) ||
|
||||
!Number.isFinite(exchangeRate) ||
|
||||
exchangeRate <= 0 ||
|
||||
typeof data.quote_token !== 'string' ||
|
||||
data.quote_token.length === 0 ||
|
||||
!Number.isFinite(quoteExpiresAt)
|
||||
) {
|
||||
throw new Error('Invalid PayPal quote amount');
|
||||
}
|
||||
return {
|
||||
currency: 'USD',
|
||||
basePayAmount,
|
||||
serviceFee,
|
||||
payAmount,
|
||||
feePayer: data.fee_payer === 'user' ? 'user' : 'platform',
|
||||
feeRateBps: Number(data.fee_rate_bps) || 0,
|
||||
feePolicyVersion: Number(data.fee_policy_version) || 0,
|
||||
cnyPayAmount,
|
||||
exchangeRate,
|
||||
quota: Number(data.quota) || 0,
|
||||
marketExchangeRate: Number(data.market_exchange_rate) || exchangeRate,
|
||||
exchangeRateSource: data.exchange_rate_source || 'manual',
|
||||
exchangeRateQuotedAt: Number(data.exchange_rate_quoted_at) || 0,
|
||||
quoteExpiresAt,
|
||||
quoteToken: data.quote_token,
|
||||
};
|
||||
}
|
||||
|
||||
export function isPayPalQuoteExpired(quote, now = Date.now()) {
|
||||
return !quote?.quoteExpiresAt || quote.quoteExpiresAt * 1000 <= now;
|
||||
}
|
||||
|
||||
export function getPayPalQuoteRemainingSeconds(quote, now = Date.now()) {
|
||||
if (!quote?.quoteExpiresAt) return 0;
|
||||
return Math.max(0, Math.ceil(quote.quoteExpiresAt - now / 1000));
|
||||
}
|
||||
|
||||
export function formatPayPalUSD(amount) {
|
||||
const value = Number(amount);
|
||||
return `$${Number.isFinite(value) ? value.toFixed(2) : '0.00'} USD`;
|
||||
}
|
||||
|
||||
export function getPayPalReturnState(search) {
|
||||
const status = new URLSearchParams(search).get('paypal');
|
||||
return status && PAYPAL_RETURN_STATES[status]
|
||||
? { status, ...PAYPAL_RETURN_STATES[status] }
|
||||
: null;
|
||||
}
|
||||
|
||||
export function removePayPalReturnState(url) {
|
||||
const next = new URL(url, 'https://local.invalid');
|
||||
next.searchParams.delete('paypal');
|
||||
return `${next.pathname}${next.search}${next.hash}`;
|
||||
}
|
||||
|
||||
export function isPayPalAvailable(enabled, methods) {
|
||||
return Boolean(
|
||||
enabled && methods?.some((method) => method.type === 'paypal'),
|
||||
);
|
||||
}
|
||||
|
||||
export function mergePayPalFeePolicyFormValues(currentValues, policy) {
|
||||
return {
|
||||
...(currentValues || {}),
|
||||
PayPalUserPaysFee: Boolean(policy?.user_pays_fee),
|
||||
PayPalFeeRatePercent: Number(policy?.rate_bps || 0) / 100,
|
||||
};
|
||||
}
|
||||
|
||||
export async function requestPayPalOrder(
|
||||
api,
|
||||
endpoint,
|
||||
body,
|
||||
config,
|
||||
maxAttempts = 3,
|
||||
) {
|
||||
let response;
|
||||
for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
|
||||
response = await api.post(endpoint, body, config);
|
||||
if (
|
||||
response.status !== 202 ||
|
||||
response.data?.message !== 'PAYPAL_ORDER_CREATING'
|
||||
) {
|
||||
return response;
|
||||
}
|
||||
if (attempt + 1 < maxAttempts) {
|
||||
await new Promise((resolve) => setTimeout(resolve, 800));
|
||||
}
|
||||
}
|
||||
return response;
|
||||
}
|
||||
@@ -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 test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
formatPayPalUSD,
|
||||
getPayPalReturnState,
|
||||
getPayPalQuoteRemainingSeconds,
|
||||
isPayPalQuoteExpired,
|
||||
isPayPalAvailable,
|
||||
mergePayPalFeePolicyFormValues,
|
||||
parsePayPalQuote,
|
||||
removePayPalReturnState,
|
||||
requestPayPalOrder,
|
||||
} from './paypalPayment.js';
|
||||
|
||||
test('merges fee policy without clearing saved PayPal settings', () => {
|
||||
assert.deepEqual(
|
||||
mergePayPalFeePolicyFormValues(
|
||||
{
|
||||
PayPalClientID: 'client-id',
|
||||
PayPalWebhookID: 'webhook-id',
|
||||
PayPalSandbox: true,
|
||||
PayPalFXMode: 'realtime',
|
||||
},
|
||||
{ user_pays_fee: true, rate_bps: 440 },
|
||||
),
|
||||
{
|
||||
PayPalClientID: 'client-id',
|
||||
PayPalWebhookID: 'webhook-id',
|
||||
PayPalSandbox: true,
|
||||
PayPalFXMode: 'realtime',
|
||||
PayPalUserPaysFee: true,
|
||||
PayPalFeeRatePercent: 4.4,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('parses a PayPal USD quote', () => {
|
||||
assert.deepEqual(
|
||||
parsePayPalQuote({
|
||||
data: {
|
||||
data: {
|
||||
currency: 'USD',
|
||||
base_pay_amount: '95.60',
|
||||
service_fee: '4.40',
|
||||
pay_amount: '100.00',
|
||||
fee_payer: 'user',
|
||||
fee_rate_bps: 440,
|
||||
fee_policy_version: 3,
|
||||
cny_pay_amount: '730.00',
|
||||
exchange_rate: '7.3',
|
||||
quota: 50000000,
|
||||
market_exchange_rate: '7.28',
|
||||
exchange_rate_source: 'open_exchange_rates',
|
||||
exchange_rate_quoted_at: 1790236800,
|
||||
quote_expires_at: 1790237400,
|
||||
quote_token: 'v2.payload.signature',
|
||||
},
|
||||
},
|
||||
}),
|
||||
{
|
||||
currency: 'USD',
|
||||
basePayAmount: 95.6,
|
||||
serviceFee: 4.4,
|
||||
payAmount: 100,
|
||||
feePayer: 'user',
|
||||
feeRateBps: 440,
|
||||
feePolicyVersion: 3,
|
||||
cnyPayAmount: 730,
|
||||
exchangeRate: 7.3,
|
||||
quota: 50000000,
|
||||
marketExchangeRate: 7.28,
|
||||
exchangeRateSource: 'open_exchange_rates',
|
||||
exchangeRateQuotedAt: 1790236800,
|
||||
quoteExpiresAt: 1790237400,
|
||||
quoteToken: 'v2.payload.signature',
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('rejects malformed or non-USD quotes', () => {
|
||||
assert.throws(() => parsePayPalQuote({ currency: 'CNY' }));
|
||||
assert.throws(() =>
|
||||
parsePayPalQuote({
|
||||
currency: 'USD',
|
||||
pay_amount: 'NaN',
|
||||
cny_pay_amount: '10',
|
||||
exchange_rate: '7.3',
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
test('formats USD and handles return state once', () => {
|
||||
assert.equal(formatPayPalUSD('12.3'), '$12.30 USD');
|
||||
assert.deepEqual(getPayPalReturnState('?foo=1&paypal=cancelled'), {
|
||||
status: 'cancelled',
|
||||
type: 'info',
|
||||
message: '已取消 PayPal 支付',
|
||||
});
|
||||
assert.equal(
|
||||
removePayPalReturnState('/recharge?foo=1&paypal=success#top'),
|
||||
'/recharge?foo=1#top',
|
||||
);
|
||||
});
|
||||
|
||||
test('PayPal is selectable only when enabled and present', () => {
|
||||
assert.equal(isPayPalAvailable(true, [{ type: 'paypal' }]), true);
|
||||
assert.equal(isPayPalAvailable(false, [{ type: 'paypal' }]), false);
|
||||
assert.equal(isPayPalAvailable(true, [{ type: 'stripe' }]), false);
|
||||
});
|
||||
|
||||
test('calculates quote expiry without going negative', () => {
|
||||
const quote = { quoteExpiresAt: 1010 };
|
||||
assert.equal(getPayPalQuoteRemainingSeconds(quote, 1000_000), 10);
|
||||
assert.equal(isPayPalQuoteExpired(quote, 1009_000), false);
|
||||
assert.equal(isPayPalQuoteExpired(quote, 1010_000), true);
|
||||
assert.equal(getPayPalQuoteRemainingSeconds(quote, 1020_000), 0);
|
||||
});
|
||||
|
||||
test('retries an in-progress PayPal create with the same quote token', async () => {
|
||||
const bodies = [];
|
||||
const api = {
|
||||
post: async (_endpoint, body) => {
|
||||
bodies.push(body);
|
||||
if (bodies.length < 3) {
|
||||
return {
|
||||
status: 202,
|
||||
data: { success: true, message: 'PAYPAL_ORDER_CREATING' },
|
||||
};
|
||||
}
|
||||
return { status: 200, data: { success: true, data: {} } };
|
||||
},
|
||||
};
|
||||
const body = { amount_option_id: 1, quote_token: 'signed-token' };
|
||||
const response = await requestPayPalOrder(api, '/paypal', body, undefined, 3);
|
||||
assert.equal(response.status, 200);
|
||||
assert.equal(bodies.length, 3);
|
||||
assert.equal(
|
||||
bodies.every((item) => item.quote_token === 'signed-token'),
|
||||
true,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,76 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
// 体验中心:判断当前模型是否具备分析上传文件的能力。
|
||||
//
|
||||
// 采用"反向黑名单"策略而不是正向白名单:
|
||||
// - 主流多模态模型(gpt-4o / claude-3 / gemini-* / qwen-vl / o1 / o3 等)数量大且持续增长,
|
||||
// 维护正向列表必然漏判 → 默认放行;
|
||||
// - 只把已知**文本-only**的传统模型列入黑名单,避免它们被选中时用户却看到上传按钮,
|
||||
// 传上去再被上游 400 退回的尴尬体验。
|
||||
//
|
||||
// 黑名单基于模型名前缀匹配,admin 后端可以通过自定义模型映射绕过;这里只是 UI 的预判,
|
||||
// 真要发请求时后端的 inlining / 上游错误仍是最终防线。
|
||||
const LEGACY_TEXT_ONLY_PATTERNS = [
|
||||
/^gpt-3\.5/i, // GPT-3.5 系列:纯文本
|
||||
/^text-(davinci|curie|babbage|ada)/i, // OpenAI legacy completion 模型
|
||||
/^(davinci|curie|babbage|ada)(-|$)/i, // 同上的简称
|
||||
/^o1-mini/i, // OpenAI o1-mini:纯文本(无视觉/文件)
|
||||
/^o3-mini/i, // OpenAI o3-mini:纯文本
|
||||
/^deepseek-(chat|coder)(-|$)/i, // DeepSeek 非视觉系列(V2.5 起部分支持,但 chat/coder 不支持)
|
||||
/^qwen(-?max|-?plus|-?turbo)(?!-vl)/i, // 通义千问非视觉系列(qwen-vl-* 才有视觉)
|
||||
/^moonshot-v1-(?!.*vision)/i, // Moonshot 非视觉系列
|
||||
/embed/i, // embedding 模型不应出现在聊天里,但兜底
|
||||
];
|
||||
|
||||
/**
|
||||
* 当前模型是否支持文件/图片输入。
|
||||
* @param {string} modelName 模型 ID(如 'gpt-4o-mini')
|
||||
* @returns {boolean} true = 支持(默认),false = 已知不支持
|
||||
*/
|
||||
export const isModelFilesCapable = (modelName) => {
|
||||
if (!modelName || typeof modelName !== 'string') return true;
|
||||
const trimmed = modelName.trim();
|
||||
if (trimmed === '') return true;
|
||||
return !LEGACY_TEXT_ONLY_PATTERNS.some((p) => p.test(trimmed));
|
||||
};
|
||||
|
||||
/**
|
||||
* 当前模型是否被管理员允许图片输入。
|
||||
*
|
||||
* 与后端 controller/playground.go 的视觉模型白名单逻辑保持一致:
|
||||
* - visionModelsConfig 为空(管理员未配置)→ 放行所有模型;
|
||||
* - 非空 → 仅白名单内模型放行。
|
||||
* 配置来源:status.experience_center_vision_models(逗号分隔)。
|
||||
*
|
||||
* @param {string} modelName 模型 ID
|
||||
* @param {string} visionModelsConfig 逗号分隔的白名单字符串
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export const isModelVisionAllowed = (modelName, visionModelsConfig) => {
|
||||
const config =
|
||||
typeof visionModelsConfig === 'string' ? visionModelsConfig.trim() : '';
|
||||
if (config === '') return true;
|
||||
if (!modelName || typeof modelName !== 'string') return true;
|
||||
const allowed = config
|
||||
.split(',')
|
||||
.map((m) => m.trim())
|
||||
.filter((m) => m !== '');
|
||||
return allowed.includes(modelName.trim());
|
||||
};
|
||||
@@ -0,0 +1,206 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
// 体验中心长会话上下文管理:历史窗口裁剪 + 摘要拼接。
|
||||
// 纯函数,不依赖 React,供 Playground 各发送入口与摘要 hook 复用。
|
||||
|
||||
import { MESSAGE_ROLES } from '../constants/playground.constants';
|
||||
import { getTextContent } from './utils';
|
||||
|
||||
// 摘要指令:要求模型输出简洁中文摘要,保留关键信息
|
||||
export const SUMMARIZE_INSTRUCTION =
|
||||
'请把以上对话压缩成一段简洁的中文摘要,保留关键事实、用户意图、已确定的结论与尚未解决的问题,' +
|
||||
'不要遗漏代码片段、数字、专有名词等关键信息。直接输出摘要正文,不要任何额外说明。';
|
||||
|
||||
// splitSystemPrefix 拆出开头连续的 system 消息(系统提示),其余为对话主体
|
||||
const splitSystemPrefix = (messages) => {
|
||||
let i = 0;
|
||||
while (i < messages.length && messages[i]?.role === MESSAGE_ROLES.SYSTEM) {
|
||||
i += 1;
|
||||
}
|
||||
return { systemPrefix: messages.slice(0, i), body: messages.slice(i) };
|
||||
};
|
||||
|
||||
/**
|
||||
* 把消息裁剪到「最近 maxRounds 轮」窗口。
|
||||
* 一轮 = 一条 user 消息 + 其后的 assistant 回复。开头连续的 system 提示永远保留。
|
||||
* maxRounds <= 0 时原样返回(不限制)。
|
||||
*
|
||||
* 局限:纯按消息序号裁剪,不做跨消息的图片依赖分析——可能裁掉后文「这张图...」
|
||||
* 引用的历史图片。这是刻意的成本控制取舍,由管理员配置轮数时自行权衡。
|
||||
*
|
||||
* @param {Array} messages 完整消息数组
|
||||
* @param {number} maxRounds 保留的最近轮数,<=0 表示不限制
|
||||
* @returns {Array} 裁剪后的消息数组(maxRounds<=0 或无需裁剪时返回原数组引用)
|
||||
*/
|
||||
export const trimMessagesToWindow = (messages, maxRounds) => {
|
||||
if (!Array.isArray(messages) || !maxRounds || maxRounds <= 0) {
|
||||
return messages;
|
||||
}
|
||||
const { systemPrefix, body } = splitSystemPrefix(messages);
|
||||
// 收集 body 里所有 user 消息的下标
|
||||
const userIdx = [];
|
||||
for (let i = 0; i < body.length; i += 1) {
|
||||
if (body[i]?.role === MESSAGE_ROLES.USER) userIdx.push(i);
|
||||
}
|
||||
// 保留最近 maxRounds 轮 + 当前新 user 消息 = 最多 maxRounds+1 条 user 消息
|
||||
if (userIdx.length <= maxRounds + 1) {
|
||||
return messages;
|
||||
}
|
||||
const cutFrom = userIdx[userIdx.length - (maxRounds + 1)];
|
||||
return [...systemPrefix, ...body.slice(cutFrom)];
|
||||
};
|
||||
|
||||
/**
|
||||
* 取出落在「最近 maxRounds 轮窗口」之前的消息(即会被裁掉、需要被摘要覆盖的那部分)。
|
||||
* 与 trimMessagesToWindow 互补:trim 返回保留的,本函数返回被裁掉的。
|
||||
* 不含开头的 system 前缀(system 提示永远保留,不进摘要)。
|
||||
*
|
||||
* @param {Array} messages
|
||||
* @param {number} maxRounds
|
||||
* @returns {Array} 窗口之前的消息(maxRounds<=0 或无需裁剪时返回空数组)
|
||||
*/
|
||||
export const getMessagesBeforeWindow = (messages, maxRounds) => {
|
||||
if (!Array.isArray(messages) || !maxRounds || maxRounds <= 0) {
|
||||
return [];
|
||||
}
|
||||
const { body } = splitSystemPrefix(messages);
|
||||
const userIdx = [];
|
||||
for (let i = 0; i < body.length; i += 1) {
|
||||
if (body[i]?.role === MESSAGE_ROLES.USER) userIdx.push(i);
|
||||
}
|
||||
if (userIdx.length <= maxRounds + 1) {
|
||||
return [];
|
||||
}
|
||||
const cutFrom = userIdx[userIdx.length - (maxRounds + 1)];
|
||||
return body.slice(0, cutFrom);
|
||||
};
|
||||
|
||||
/**
|
||||
* 取出「锚点消息之后」的全部对话主体消息(不含 system 前缀)。
|
||||
* 锚点 = backendId 等于 anchorBackendId 的消息(通常是已被摘要覆盖到的最后一条 user 消息)。
|
||||
*
|
||||
* 设计要点:按位置切片而非按 backendId 过滤——直播会话里 assistant 消息没有 backendId,
|
||||
* 但它们必须随相邻 user 消息一起被带上,否则模型只看到提问看不到回答。
|
||||
*
|
||||
* @param {Array} messages
|
||||
* @param {number} anchorBackendId 锚点消息的 backendId(<=0 视为无锚点)
|
||||
* @returns {Array} 锚点之后的消息;锚点不存在(如被删除)时兜底返回全部主体,避免丢上下文
|
||||
*/
|
||||
export const getMessagesAfterAnchor = (messages, anchorBackendId) => {
|
||||
if (!Array.isArray(messages)) return [];
|
||||
const { body } = splitSystemPrefix(messages);
|
||||
if (!anchorBackendId || anchorBackendId <= 0) return body;
|
||||
const idx = body.findIndex((m) => m && m.backendId === anchorBackendId);
|
||||
if (idx < 0) return body;
|
||||
return body.slice(idx + 1);
|
||||
};
|
||||
|
||||
/**
|
||||
* 统计对话主体里的「轮数」(body 内 user 消息数量)。
|
||||
* @param {Array} messages
|
||||
* @returns {number}
|
||||
*/
|
||||
export const countRounds = (messages) => {
|
||||
if (!Array.isArray(messages)) return 0;
|
||||
const { body } = splitSystemPrefix(messages);
|
||||
return body.filter((m) => m?.role === MESSAGE_ROLES.USER).length;
|
||||
};
|
||||
|
||||
/**
|
||||
* 发送前对消息做「摘要 + 窗口」处理:
|
||||
* - 启用摘要(summaryEnabled) 且摘要已就绪 → [system 前缀] + [摘要 system 消息] + [锚点之后的全部历史]
|
||||
* (锚点之后全发,不再二次截断,避免「摘要边界」与「窗口边界」之间出现上下文空洞)
|
||||
* - 启用摘要 但摘要还没生成 → 原样返回完整历史(首次摘要前不截断,避免丢上下文)
|
||||
* - 未启用摘要 → 纯 Feature A:trimMessagesToWindow 截断到最近 maxRounds 轮
|
||||
*
|
||||
* @param {Array} messages
|
||||
* @param {{maxRounds?: number, summary?: string, summarizedUpToMessageId?: number, summaryEnabled?: boolean}} opts
|
||||
* @returns {Array}
|
||||
*/
|
||||
export const applySummaryAndWindow = (messages, opts = {}) => {
|
||||
if (!Array.isArray(messages)) return messages;
|
||||
const { maxRounds, summary, summarizedUpToMessageId, summaryEnabled } = opts;
|
||||
|
||||
if (summaryEnabled) {
|
||||
if (summary && summarizedUpToMessageId > 0) {
|
||||
const { systemPrefix } = splitSystemPrefix(messages);
|
||||
let tail = getMessagesAfterAnchor(messages, summarizedUpToMessageId);
|
||||
// tail 以「锚点(user 消息)的 assistant 回复」开头;去掉开头的非 user 消息,
|
||||
// 保证发给上游的对话体首条(非 system)为 user —— Claude 等上游要求严格 user 起始,
|
||||
// 否则会报错。被去掉的 assistant 回复属于已被摘要覆盖的那一轮,不会丢上下文。
|
||||
let cut = 0;
|
||||
while (cut < tail.length && tail[cut]?.role !== MESSAGE_ROLES.USER) {
|
||||
cut += 1;
|
||||
}
|
||||
if (cut > 0) tail = tail.slice(cut);
|
||||
return [
|
||||
...systemPrefix,
|
||||
{ role: MESSAGE_ROLES.SYSTEM, content: '对话历史摘要:' + summary },
|
||||
...tail,
|
||||
];
|
||||
}
|
||||
// 摘要还没生成 → 发送完整历史
|
||||
return messages;
|
||||
}
|
||||
|
||||
return trimMessagesToWindow(messages, maxRounds);
|
||||
};
|
||||
|
||||
/**
|
||||
* 构造摘要请求的 messages:把「已有摘要 + 待摘要对话 + 摘要指令」整段塞进【一条 user 消息】。
|
||||
*
|
||||
* 为什么塞成单条 user 消息:摘要请求会经普通 /pg/chat/completions 转发到用户当前模型,
|
||||
* 而待摘要片段往往以 assistant 消息开头、且未必严格 user/assistant 交替;Claude 等上游
|
||||
* 对「首条非 system 必须是 user」「角色必须交替」有硬性要求,多条消息形态会被直接打回,
|
||||
* 导致摘要在这些模型上永远静默失败。单条 user 消息彻底规避所有角色约束。
|
||||
*
|
||||
* 待摘要消息只取纯文本(getTextContent):摘要不需要图片,且能避开历史多模态消息里
|
||||
* COS 预签名 URL 过期、当前模型不支持视觉等问题。空文本消息直接跳过。
|
||||
*
|
||||
* @param {Array} messagesToSummarize 需要被压缩的历史消息
|
||||
* @param {string} existingSummary 已有摘要(增量摘要时把旧摘要也带上)
|
||||
* @returns {Array} 仅含一条 user 消息的数组
|
||||
*/
|
||||
export const buildSummaryInstructionMessages = (
|
||||
messagesToSummarize,
|
||||
existingSummary,
|
||||
) => {
|
||||
const parts = [];
|
||||
if (existingSummary && existingSummary.trim()) {
|
||||
parts.push('【已有摘要】\n' + existingSummary.trim());
|
||||
}
|
||||
const transcript = [];
|
||||
for (const m of messagesToSummarize || []) {
|
||||
const text = getTextContent(m);
|
||||
if (!text || !text.trim()) continue;
|
||||
const label =
|
||||
m?.role === MESSAGE_ROLES.USER
|
||||
? '用户'
|
||||
: m?.role === MESSAGE_ROLES.ASSISTANT
|
||||
? '助手'
|
||||
: m?.role === MESSAGE_ROLES.SYSTEM
|
||||
? '系统'
|
||||
: m?.role || '消息';
|
||||
transcript.push(`${label}:${text.trim()}`);
|
||||
}
|
||||
parts.push('【待总结的对话】\n' + transcript.join('\n'));
|
||||
parts.push(SUMMARIZE_INSTRUCTION);
|
||||
return [{ role: MESSAGE_ROLES.USER, content: parts.join('\n\n') }];
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
/*
|
||||
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 { isSafePostLoginRedirect } from './data.js';
|
||||
|
||||
test('isSafePostLoginRedirect only allows same-origin relative paths', () => {
|
||||
for (const ok of [
|
||||
'/console',
|
||||
'/client/authorize?client_id=weyai-desktop&state=a%5Cb',
|
||||
]) {
|
||||
assert.equal(isSafePostLoginRedirect(ok), true, ok);
|
||||
}
|
||||
for (const bad of [
|
||||
'',
|
||||
'https://evil.example.com',
|
||||
'//evil.example.com',
|
||||
'/\\evil.example.com',
|
||||
'/\\/evil.example.com',
|
||||
'/console\\..\\x',
|
||||
'/login',
|
||||
'/org/login',
|
||||
]) {
|
||||
assert.equal(isSafePostLoginRedirect(bad), false, bad);
|
||||
}
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
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 function getHeaderValue(headers, name) {
|
||||
if (!headers) return '';
|
||||
if (typeof headers.get === 'function') {
|
||||
const value = headers.get(name);
|
||||
if (value !== undefined && value !== null) return String(value);
|
||||
}
|
||||
const normalizedName = name.toLowerCase();
|
||||
const key = Object.keys(headers).find(
|
||||
(headerName) => headerName.toLowerCase() === normalizedName,
|
||||
);
|
||||
return key && headers[key] !== undefined && headers[key] !== null
|
||||
? String(headers[key])
|
||||
: '';
|
||||
}
|
||||
|
||||
export function buildGetRequestKey(
|
||||
url,
|
||||
config = {},
|
||||
fallbackOrgId = '',
|
||||
fallbackUserId = '',
|
||||
) {
|
||||
const params = config.params ? JSON.stringify(config.params) : '{}';
|
||||
const orgId = getHeaderValue(config.headers, 'X-Org-Id') || fallbackOrgId;
|
||||
const userId =
|
||||
getHeaderValue(config.headers, 'New-API-User') || fallbackUserId;
|
||||
const authorization = getHeaderValue(config.headers, 'Authorization');
|
||||
return `${url}?${params}#org=${encodeURIComponent(orgId)}#user=${encodeURIComponent(userId)}#auth=${encodeURIComponent(authorization)}`;
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
/*
|
||||
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 { buildGetRequestKey, getHeaderValue } from './requestDedupe.js';
|
||||
|
||||
test('GET dedupe key isolates requests by enterprise header', () => {
|
||||
const orgA = buildGetRequestKey('/api/org/data-security/config', {
|
||||
headers: { 'X-Org-Id': '101' },
|
||||
});
|
||||
const orgB = buildGetRequestKey('/api/org/data-security/config', {
|
||||
headers: { 'x-org-id': '202' },
|
||||
});
|
||||
|
||||
assert.notEqual(orgA, orgB);
|
||||
assert.match(orgA, /org=101/);
|
||||
assert.match(orgB, /org=202/);
|
||||
});
|
||||
|
||||
test('GET dedupe key uses the current enterprise when the header is injected later', () => {
|
||||
const orgA = buildGetRequestKey('/api/org/info', {}, '101');
|
||||
const orgB = buildGetRequestKey('/api/org/info', {}, '202');
|
||||
|
||||
assert.notEqual(orgA, orgB);
|
||||
});
|
||||
|
||||
test('header lookup supports AxiosHeaders-style accessors', () => {
|
||||
const headers = { get: (name) => (name === 'X-Org-Id' ? 303 : undefined) };
|
||||
assert.equal(getHeaderValue(headers, 'X-Org-Id'), '303');
|
||||
});
|
||||
|
||||
test('GET dedupe key isolates users and explicit authorization', () => {
|
||||
const userA = buildGetRequestKey('/api/org/info', {}, '101', '7');
|
||||
const userB = buildGetRequestKey('/api/org/info', {}, '101', '8');
|
||||
const bearerA = buildGetRequestKey('/api/data', {
|
||||
headers: { Authorization: 'Bearer token-a' },
|
||||
});
|
||||
const bearerB = buildGetRequestKey('/api/data', {
|
||||
headers: { Authorization: 'Bearer token-b' },
|
||||
});
|
||||
|
||||
assert.notEqual(userA, userB);
|
||||
assert.notEqual(bearerA, bearerB);
|
||||
});
|
||||
@@ -0,0 +1,37 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
/**
|
||||
* 只放行 http(s) 绝对地址:来自后台配置或接口的地址在做成链接、发请求前先过滤,
|
||||
* 挡住 javascript:、data:、file: 之类的伪协议和协议相对地址。
|
||||
* 合法时返回去掉首尾空白的地址,否则返回空串。
|
||||
*/
|
||||
export function toSafeHttpUrl(value) {
|
||||
if (!value || typeof value !== 'string') return '';
|
||||
const trimmed = value.trim();
|
||||
if (!/^https?:\/\//i.test(trimmed)) return '';
|
||||
try {
|
||||
const url = new URL(trimmed);
|
||||
if (!['http:', 'https:'].includes(url.protocol) || !url.host) return '';
|
||||
if (url.username || url.password) return '';
|
||||
} catch (_e) {
|
||||
return '';
|
||||
}
|
||||
return trimmed;
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
/*
|
||||
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 { toSafeHttpUrl } from './safeUrl.js';
|
||||
|
||||
test('toSafeHttpUrl keeps absolute http(s) urls only', () => {
|
||||
assert.equal(
|
||||
toSafeHttpUrl(' https://ai.example.com/ '),
|
||||
'https://ai.example.com/',
|
||||
);
|
||||
assert.equal(toSafeHttpUrl('http://10.0.0.5:8080'), 'http://10.0.0.5:8080');
|
||||
for (const bad of [
|
||||
'',
|
||||
null,
|
||||
undefined,
|
||||
42,
|
||||
'javascript:alert(1)',
|
||||
'JAVASCRIPT:alert(1)',
|
||||
'data:text/html,x',
|
||||
'file:///etc/passwd',
|
||||
'//evil.example.com',
|
||||
'/relative/path',
|
||||
'ai.example.com',
|
||||
'https://',
|
||||
'https://user:pw@ai.example.com',
|
||||
]) {
|
||||
assert.equal(toSafeHttpUrl(bad), '', `${bad} must be rejected`);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,47 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
/**
|
||||
* 安全 API 调用包装器
|
||||
* 自动处理需要验证的 403 错误,透明地触发验证流程
|
||||
*/
|
||||
|
||||
/**
|
||||
* 检查错误是否是需要安全验证的错误
|
||||
* @param {Error} error - 错误对象
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isVerificationRequiredError(error) {
|
||||
if (!error.response) return false;
|
||||
|
||||
const { status, data } = error.response;
|
||||
|
||||
// 检查是否是 403 错误且包含验证相关的错误码
|
||||
if (status === 403 && data) {
|
||||
const verificationCodes = [
|
||||
'VERIFICATION_REQUIRED',
|
||||
'VERIFICATION_EXPIRED',
|
||||
'VERIFICATION_INVALID',
|
||||
];
|
||||
|
||||
return verificationCodes.includes(data.code);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
@@ -0,0 +1,437 @@
|
||||
/*
|
||||
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 { colord, extend } from 'colord';
|
||||
import mixPlugin from 'colord/plugins/mix';
|
||||
import { getPreset, DEFAULT_PRESET_KEY } from '../styles/presets';
|
||||
|
||||
extend([mixPlugin]);
|
||||
|
||||
const CACHE_KEY = 'theme-config';
|
||||
const PRESETS_CACHE_KEY = 'theme-presets';
|
||||
const STYLE_ID_LIGHT = 'theme-tokens-light';
|
||||
const STYLE_ID_DARK = 'theme-tokens-dark';
|
||||
const STYLE_ID_SEMI_LIGHT = 'theme-semi-light';
|
||||
const STYLE_ID_SEMI_DARK = 'theme-semi-dark';
|
||||
// 下次启动时供 index.html 头部内联脚本同步注入,避免首屏 splash 用兜底色刷一遍再跳到品牌色。
|
||||
const CSS_CACHE_KEY = 'theme-css-cache';
|
||||
const STYLE_ID_PRESPLASH = 'theme-presplash';
|
||||
|
||||
// 管理员对内置预设的覆盖(仅浅色 token,目前 8 个可编辑:brand-primary,
|
||||
// brand-gradient-from/via/to, bg-glow-from/to, accent-blue, accent-emerald)。
|
||||
// 模块级单例,供 getEffectivePreset 读取。
|
||||
// 形如 { ocean: { light: { 'brand-primary': '#xxx', ... } }, ... }
|
||||
let presetOverrides = {};
|
||||
|
||||
/** 安全解析 ThemeConfig JSON。任意失败都回落到默认预设。 */
|
||||
function parseConfig(jsonString) {
|
||||
if (!jsonString) return { preset: DEFAULT_PRESET_KEY };
|
||||
try {
|
||||
const parsed = JSON.parse(jsonString);
|
||||
if (parsed && typeof parsed === 'object') return parsed;
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
return { preset: DEFAULT_PRESET_KEY };
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置预设覆盖(管理员编辑过的预设模板)。在 applyTheme 之前调用才生效。
|
||||
* @param jsonString 后端 theme_presets 字段
|
||||
* @param persist 是否写 localStorage(默认 true,供下次 FOUC 同步注入)
|
||||
*/
|
||||
export function setPresetOverrides(jsonString, { persist = true } = {}) {
|
||||
try {
|
||||
presetOverrides =
|
||||
jsonString && typeof jsonString === 'string' ? JSON.parse(jsonString) : {};
|
||||
if (!presetOverrides || typeof presetOverrides !== 'object') {
|
||||
presetOverrides = {};
|
||||
}
|
||||
} catch {
|
||||
presetOverrides = {};
|
||||
}
|
||||
if (!persist) return;
|
||||
try {
|
||||
window.localStorage.setItem(
|
||||
PRESETS_CACHE_KEY,
|
||||
jsonString || '{}',
|
||||
);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 由浅色 token 自动派生暗色 token(管理员只编辑浅色,暗色由此生成)。
|
||||
* 规则:在暗背景上需要更亮的主色,故整体提亮;soft 用半透明叠加。
|
||||
*
|
||||
* Exported so SettingsTheme.jsx 的"派生到深色"按钮可复用同一套规则,
|
||||
* 保持自定义模式与编辑预设模板的光暗联动逻辑一致。
|
||||
*/
|
||||
export function deriveDarkTokens(light) {
|
||||
const lift = (hex, amt) => {
|
||||
try {
|
||||
return colord(hex).lighten(amt).toHex();
|
||||
} catch {
|
||||
return hex;
|
||||
}
|
||||
};
|
||||
const softOf = (hex) => {
|
||||
try {
|
||||
return colord(hex).lighten(0.12).alpha(0.18).toRgbString();
|
||||
} catch {
|
||||
return 'rgba(129, 140, 248, 0.18)';
|
||||
}
|
||||
};
|
||||
return {
|
||||
// primary 只轻抬一档 —— 暗色实色按钮用白字需足够对比度;
|
||||
// 抬太多(旧 0.12/0.22)会让按钮底太浅、白字看不清。装饰类(gradient/glow/accent)仍可多抬。
|
||||
'brand-primary': lift(light['brand-primary'], 0.04),
|
||||
'brand-primary-hover': lift(light['brand-primary'], 0.14),
|
||||
'brand-primary-soft': softOf(light['brand-primary']),
|
||||
'brand-gradient-from': lift(light['brand-gradient-from'], 0.08),
|
||||
'brand-gradient-via': lift(light['brand-gradient-via'], 0.1),
|
||||
'brand-gradient-to': lift(light['brand-gradient-to'], 0.1),
|
||||
// 页面背景晕染 —— 管理员只编辑浅色,暗色统一上抬一档
|
||||
'bg-glow-from': lift(light['bg-glow-from'], 0.08),
|
||||
'bg-glow-to': lift(light['bg-glow-to'], 0.1),
|
||||
'accent-blue': lift(light['accent-blue'], 0.12),
|
||||
'accent-teal': lift(light['accent-teal'], 0.12),
|
||||
'accent-emerald': lift(light['accent-emerald'], 0.12),
|
||||
};
|
||||
}
|
||||
|
||||
// 派生 token 的"反向依赖" —— 描述某个浅色 token 改变后会牵动哪些暗色 token。
|
||||
// 大多数 token 是一对一映射;brand-primary 因为衍生 hover/soft,多带 2 个。
|
||||
// getEffectivePreset 和 SettingsTheme 的"派生到深色"按钮都用这张表精确派生
|
||||
// "实际被覆盖的项",避免覆盖管理员在 presets.js 中手调的、未触动的 dark token。
|
||||
export const DARK_DERIVE_DEPS = {
|
||||
'brand-primary': [
|
||||
'brand-primary',
|
||||
'brand-primary-hover',
|
||||
'brand-primary-soft',
|
||||
],
|
||||
'brand-gradient-from': ['brand-gradient-from'],
|
||||
'brand-gradient-via': ['brand-gradient-via'],
|
||||
'brand-gradient-to': ['brand-gradient-to'],
|
||||
'bg-glow-from': ['bg-glow-from'],
|
||||
'bg-glow-to': ['bg-glow-to'],
|
||||
'accent-blue': ['accent-blue'],
|
||||
'accent-teal': ['accent-teal'],
|
||||
'accent-emerald': ['accent-emerald'],
|
||||
};
|
||||
|
||||
/**
|
||||
* 取生效后的预设:内置默认 ∪ 管理员覆盖(浅色),暗色随覆盖**精准派生**。
|
||||
* 未被编辑的预设原样返回内置定义。
|
||||
*
|
||||
* 精准派生(vs 旧版全量覆盖):
|
||||
* 只对 ov.light 中**实际被覆盖**的 token 派生对应的 dark token,
|
||||
* 保留预设手调的、未被触动的 dark 值(例如 mono 预设手调的 slate-300)。
|
||||
* brand-primary 一次性带 hover/soft 三件套,靠 DARK_DERIVE_DEPS 映射。
|
||||
*/
|
||||
export function getEffectivePreset(key) {
|
||||
const base = getPreset(key);
|
||||
const ov = presetOverrides[key];
|
||||
if (!ov || !ov.light || Object.keys(ov.light).length === 0) return base;
|
||||
const light = { ...base.light, ...ov.light };
|
||||
const derived = deriveDarkTokens(light);
|
||||
const dark = { ...base.dark };
|
||||
for (const changedKey of Object.keys(ov.light)) {
|
||||
const deps = DARK_DERIVE_DEPS[changedKey];
|
||||
if (!deps) continue;
|
||||
for (const dep of deps) {
|
||||
if (dep in derived) dark[dep] = derived[dep];
|
||||
}
|
||||
}
|
||||
return { ...base, light, dark };
|
||||
}
|
||||
|
||||
/**
|
||||
* 在 React 渲染前同步执行 —— 从 localStorage 命中上次的主题立即注入,
|
||||
* 避免"默认色 → 服务器色"的首屏闪烁。
|
||||
*
|
||||
* 首次访问(cache 空)时 tokens.css 的默认值作为兜底,仍只在首次有闪烁。
|
||||
*/
|
||||
export function applyThemeFromCache() {
|
||||
if (typeof window === 'undefined') return;
|
||||
try {
|
||||
// 先恢复预设覆盖,再应用主题,确保 getEffectivePreset 拿到编辑后的预设
|
||||
const cachedPresets = window.localStorage.getItem(PRESETS_CACHE_KEY);
|
||||
if (cachedPresets) setPresetOverrides(cachedPresets, { persist: false });
|
||||
const cached = window.localStorage.getItem(CACHE_KEY);
|
||||
if (cached) {
|
||||
doApply(parseConfig(cached));
|
||||
// 本路径来源就是已持久化的 theme-config,对 presplash CSS 缓存做一次刷新即可,
|
||||
// 同时自愈 theme-css-cache 被清掉的情况(下次刷新就不再有兜底色跳变)
|
||||
cachePresplashCSS();
|
||||
}
|
||||
} catch {
|
||||
/* localStorage 不可用时静默 */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 完整应用主题:注入 CSS + 写回 cache。
|
||||
*
|
||||
* 调用时机:
|
||||
* - PageLayout loadStatus 拿到 theme_config 后(默认 persist=true,刷新后保留)
|
||||
* - SettingsTheme.jsx 保存成功后(默认 persist=true)
|
||||
*
|
||||
* options.persist:是否写入 localStorage(默认 true)。
|
||||
* 预览场景(管理员点选预设但未保存)应传 false,
|
||||
* 避免未保存的预览值污染 cache,导致刷新后看到预览色再闪回 server 真实色。
|
||||
*/
|
||||
export function applyTheme(jsonString, { persist = true } = {}) {
|
||||
const config = parseConfig(jsonString);
|
||||
doApply(config);
|
||||
if (!persist) return;
|
||||
try {
|
||||
window.localStorage.setItem(CACHE_KEY, jsonString || JSON.stringify(config));
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
// 关键:cachePresplashCSS 必须挂在 persist 的同一道闸门后,
|
||||
// 否则预览模式(persist=false)会把预览的 CSS 写进 presplash 缓存,
|
||||
// 下次刷新时 splash 闪一下"未保存的预览色"再回弹到真实色。
|
||||
cachePresplashCSS();
|
||||
}
|
||||
|
||||
/** 清缓存,下次启动回落到默认预设。仅供调试用。 */
|
||||
export function resetTheme() {
|
||||
try {
|
||||
window.localStorage.removeItem(CACHE_KEY);
|
||||
// 同步清掉 presplash CSS 缓存,否则下次刷新 splash 还是用旧色(即便 theme-config 已清)
|
||||
window.localStorage.removeItem(CSS_CACHE_KEY);
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
/* ============= 内部实现 ============= */
|
||||
|
||||
function doApply(config) {
|
||||
disableTransitionsBriefly();
|
||||
|
||||
// 用生效后的预设(含管理员对预设模板的编辑),再叠加 ThemeConfig 的自定义覆盖
|
||||
const preset = getEffectivePreset(config.preset);
|
||||
const lightTokens = { ...preset.light, ...(config.lightTokens || {}) };
|
||||
const darkTokens = { ...preset.dark, ...(config.darkTokens || {}) };
|
||||
|
||||
// 1. 自定义品牌 token(hex + RGB 三元组)
|
||||
injectTokens(STYLE_ID_LIGHT, ':root', withRgbTriplets(lightTokens));
|
||||
injectTokens(
|
||||
STYLE_ID_DARK,
|
||||
'html.dark, body[theme-mode="dark"]',
|
||||
withRgbTriplets(darkTokens),
|
||||
);
|
||||
|
||||
// 2. Semi 派生色(19 个变量 × 浅/暗 = 38 个)。
|
||||
// info 单独传 accent-blue,保留"信息=蓝"语义;primary/link/focus 跟随 brand-primary。
|
||||
// 浅色选择器必须包含 body:Semi 把浅色主题变量声明在 body 上,CSS 变量继承取最近祖先,
|
||||
// 只注入 :root 会被 Semi 的 body 级默认值(蓝色)覆盖,表现为浅色模式下
|
||||
// Checkbox/Link 等原生 Semi 组件不跟随主题色(暗色注入 body[theme-mode=dark] 无此问题)。
|
||||
injectSemiVars(
|
||||
STYLE_ID_SEMI_LIGHT,
|
||||
':root, body',
|
||||
lightTokens['brand-primary'],
|
||||
false,
|
||||
lightTokens['accent-blue'],
|
||||
);
|
||||
injectSemiVars(
|
||||
STYLE_ID_SEMI_DARK,
|
||||
'html.dark, body[theme-mode="dark"]',
|
||||
darkTokens['brand-primary'],
|
||||
true,
|
||||
darkTokens['accent-blue'],
|
||||
);
|
||||
|
||||
// 3. 一次性清理掉本次启动时 index.html 注入的 presplash style——它的内容已经被
|
||||
// 上面 4 个 style tag 覆盖,多留着只是占 DOM,无功能影响。
|
||||
// 注意:presplash CSS 缓存(theme-css-cache)不在 doApply 写,而是在 applyTheme(persist=true)
|
||||
// 与 applyThemeFromCache 两条"承诺持久化"的入口里写。否则预览(persist=false)会污染缓存。
|
||||
const pre = document.getElementById(STYLE_ID_PRESPLASH);
|
||||
if (pre && pre.parentNode) pre.parentNode.removeChild(pre);
|
||||
|
||||
// 通知运行时读取 CSS 变量的消费方(如 vchart 图表的系列色)预设已切换。
|
||||
// Semi 明暗切换有 initVChartSemiTheme 的 watcher,但预设注入只改 CSS 变量,
|
||||
// 不改 theme-mode,watcher 感知不到,必须靠这个事件补。
|
||||
try {
|
||||
window.dispatchEvent(new CustomEvent('theme-tokens-applied'));
|
||||
} catch {
|
||||
/* CustomEvent 不可用时静默 */
|
||||
}
|
||||
}
|
||||
|
||||
function cachePresplashCSS() {
|
||||
try {
|
||||
const ids = [STYLE_ID_LIGHT, STYLE_ID_DARK, STYLE_ID_SEMI_LIGHT, STYLE_ID_SEMI_DARK];
|
||||
const css = ids
|
||||
.map((id) => {
|
||||
const el = document.getElementById(id);
|
||||
return el ? el.textContent : '';
|
||||
})
|
||||
.filter(Boolean)
|
||||
.join('\n');
|
||||
if (css) window.localStorage.setItem(CSS_CACHE_KEY, css);
|
||||
} catch {
|
||||
/* localStorage 写失败(隐私模式/超配额)静默:splash 仍能用 CSS var 兜底色 */
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 派生 Semi primary 系列 + info + link + focus-border (D1=B 路线)。
|
||||
*
|
||||
* primary / link / focus-border 跟随 brand-primary;
|
||||
* info 单独跟随 infoHex(accent-blue)—— 保留"信息=蓝"的语义惯例,
|
||||
* 避免森林/日落等非蓝主题下出现绿色/橙色的 info 提示。infoHex 缺省回落到 primary。
|
||||
*
|
||||
* isDark 决定 hover/active 是 darken 还是 lighten。
|
||||
*/
|
||||
function buildSemiRules(baseHex, isDark, infoHex) {
|
||||
const base = colord(baseHex);
|
||||
const info = colord(infoHex || baseHex);
|
||||
const step = (c, n) =>
|
||||
isDark ? c.lighten(n).toHex() : c.darken(n).toHex();
|
||||
const alphaSoft = (c, a) => c.alpha(a).toRgbString();
|
||||
|
||||
// 浅暗模式 light 系列透明度策略略不同(参考 Semi 默认)
|
||||
const softDefault = isDark ? 0.2 : 0.12;
|
||||
const softHover = isDark ? 0.3 : 0.16;
|
||||
const softActive = isDark ? 0.4 : 0.2;
|
||||
const infoHexNorm = (infoHex || baseHex);
|
||||
|
||||
return {
|
||||
/* primary(7 个)—— 跟随 brand-primary */
|
||||
'semi-color-primary': baseHex,
|
||||
'semi-color-primary-hover': step(base, 0.05),
|
||||
'semi-color-primary-active': step(base, 0.1),
|
||||
'semi-color-primary-disabled': alphaSoft(base, 0.4),
|
||||
'semi-color-primary-light-default': alphaSoft(base, softDefault),
|
||||
'semi-color-primary-light-hover': alphaSoft(base, softHover),
|
||||
'semi-color-primary-light-active': alphaSoft(base, softActive),
|
||||
/* info(7 个)—— 跟随 accent-blue,保留"信息=蓝"语义 */
|
||||
'semi-color-info': infoHexNorm,
|
||||
'semi-color-info-hover': step(info, 0.05),
|
||||
'semi-color-info-active': step(info, 0.1),
|
||||
'semi-color-info-disabled': alphaSoft(info, 0.4),
|
||||
'semi-color-info-light-default': alphaSoft(info, softDefault),
|
||||
'semi-color-info-light-hover': alphaSoft(info, softHover),
|
||||
'semi-color-info-light-active': alphaSoft(info, softActive),
|
||||
/* link(4 个)—— 跟随 brand-primary */
|
||||
'semi-color-link': baseHex,
|
||||
'semi-color-link-hover': step(base, 0.05),
|
||||
'semi-color-link-active': step(base, 0.1),
|
||||
'semi-color-link-visited': baseHex,
|
||||
/* focus-border(1 个) */
|
||||
'semi-color-focus-border': baseHex,
|
||||
};
|
||||
}
|
||||
|
||||
function injectSemiVars(styleId, selector, baseHex, isDark, infoHex) {
|
||||
if (!baseHex) return;
|
||||
const rules = buildSemiRules(baseHex, isDark, infoHex);
|
||||
injectTokens(styleId, selector, rules);
|
||||
}
|
||||
|
||||
/**
|
||||
* 给一组 hex token 追加 -rgb 三元组版本("R G B" 空格分隔)。
|
||||
*
|
||||
* 用途:Tailwind 配置用 `rgb(var(--brand-primary-rgb) / <alpha-value>)` 模式
|
||||
* 才能让 `bg-brand-primary/20` 等带透明度的类正常工作。
|
||||
*
|
||||
* 兼容 6 位(#RRGGBB)与 8 位(#RRGGBBAA)hex —— 三元组只取 RGB,
|
||||
* 不含 alpha(Tailwind 的透明度由工具类 /N 控制;token 自身的 alpha
|
||||
* 通过 var(--brand-*) 直接使用时生效)。非 hex 值(rgba 等)跳过。
|
||||
*/
|
||||
const HEX_RE = /^#([0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/;
|
||||
function withRgbTriplets(tokens) {
|
||||
const out = { ...tokens };
|
||||
for (const [k, v] of Object.entries(tokens)) {
|
||||
const s = String(v || '').trim();
|
||||
if (!HEX_RE.test(s)) continue;
|
||||
const c = colord(s);
|
||||
if (!c.isValid()) continue;
|
||||
const { r, g, b } = c.toRgb();
|
||||
out[`${k}-rgb`] = `${r} ${g} ${b}`;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Token key/value 注入校验 —— 防 CSS 注入。
|
||||
*
|
||||
* value 中若含 `;{}` 等 CSS 规则终止符,攻击者可以"逃出"当前 :root 规则
|
||||
* 注入任意 body { display:none } 之类,导致 defacement。
|
||||
* 这是最后一道防御,即使前端 UI 校验被绕过(手改 state、导入恶意 JSON)
|
||||
* 也会在注入点拒绝。
|
||||
*
|
||||
* key 仅允许 ASCII 字母数字与连字符;长度 ≤ 60。
|
||||
* value 长度 ≤ 200;禁止字符 `;{}`(CSS 规则边界符)。
|
||||
* 拒绝的条目被静默丢弃,回退到 tokens.css 静态默认。
|
||||
*/
|
||||
const SAFE_KEY_RE = /^[a-zA-Z][a-zA-Z0-9-]*$/;
|
||||
function isSafeCssKey(k) {
|
||||
if (typeof k !== 'string') return false;
|
||||
if (k.length === 0 || k.length > 60) return false;
|
||||
return SAFE_KEY_RE.test(k);
|
||||
}
|
||||
function isSafeCssValue(v) {
|
||||
if (typeof v !== 'string') return false;
|
||||
if (v.length === 0 || v.length > 200) return false;
|
||||
// CSS 规则终止符:禁止以防止逃出当前 :root 规则
|
||||
if (/[;{}]/.test(v)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 用动态 <style> 标签注入一组 CSS 变量。
|
||||
* 每次替换同一个 styleId 的内容,避免重复堆积。
|
||||
*/
|
||||
function injectTokens(styleId, selector, tokens) {
|
||||
if (typeof document === 'undefined') return;
|
||||
let style = document.getElementById(styleId);
|
||||
if (!style) {
|
||||
style = document.createElement('style');
|
||||
style.id = styleId;
|
||||
document.head.appendChild(style);
|
||||
}
|
||||
const body = Object.entries(tokens)
|
||||
.filter(([k, v]) => isSafeCssKey(k) && isSafeCssValue(v))
|
||||
.map(([k, v]) => ` --${k}: ${v};`)
|
||||
.join('\n');
|
||||
style.textContent = `${selector} {\n${body}\n}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* 切换瞬间临时禁用所有 transition / animation,
|
||||
* 避免大量带 transition 的组件同时渐变产生"卡 200ms"的观感。
|
||||
*
|
||||
* 用 requestAnimationFrame 两次确保新样式已应用后再恢复。
|
||||
*/
|
||||
function disableTransitionsBriefly() {
|
||||
if (typeof document === 'undefined') return;
|
||||
const html = document.documentElement;
|
||||
html.classList.add('theme-switching');
|
||||
requestAnimationFrame(() => {
|
||||
requestAnimationFrame(() => {
|
||||
html.classList.remove('theme-switching');
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
/*
|
||||
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 { API } from './api';
|
||||
|
||||
/**
|
||||
* 获取可用的token keys
|
||||
* @returns {Promise<string[]>} 返回active状态的token key数组
|
||||
*/
|
||||
export async function fetchTokenKeys() {
|
||||
try {
|
||||
const response = await API.get('/api/token/?p=1&size=10');
|
||||
const { success, data } = response.data;
|
||||
if (!success) throw new Error('Failed to fetch token keys');
|
||||
|
||||
const tokenItems = Array.isArray(data) ? data : data.items || [];
|
||||
const activeTokens = tokenItems.filter((token) => token.status === 1);
|
||||
return activeTokens.map((token) => token.key);
|
||||
} catch (error) {
|
||||
console.error('Error fetching token keys:', error);
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取服务器地址
|
||||
* @returns {string} 服务器地址
|
||||
*/
|
||||
export function getServerAddress() {
|
||||
let status = localStorage.getItem('status');
|
||||
let serverAddress = '';
|
||||
|
||||
if (status) {
|
||||
try {
|
||||
status = JSON.parse(status);
|
||||
serverAddress = status.server_address || '';
|
||||
} catch (error) {
|
||||
console.error('Failed to parse status from localStorage:', error);
|
||||
}
|
||||
}
|
||||
|
||||
if (!serverAddress) {
|
||||
serverAddress = window.location.origin;
|
||||
}
|
||||
|
||||
return serverAddress;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,83 @@
|
||||
/*
|
||||
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
|
||||
*/
|
||||
|
||||
const SUCCESS_STATUSES = new Set(['success', 'completed', 'succeeded']);
|
||||
const FAILURE_STATUSES = new Set([
|
||||
'failure',
|
||||
'failed',
|
||||
'canceled',
|
||||
'cancelled',
|
||||
]);
|
||||
|
||||
export function normalizeVideoTaskStatus(status) {
|
||||
const normalized = String(status || '')
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
if (SUCCESS_STATUSES.has(normalized)) return 'success';
|
||||
if (FAILURE_STATUSES.has(normalized)) return 'failure';
|
||||
if (normalized === 'in_progress' || normalized === 'processing') {
|
||||
return 'in_progress';
|
||||
}
|
||||
if (
|
||||
normalized === 'queued' ||
|
||||
normalized === 'submitted' ||
|
||||
normalized === 'not_start'
|
||||
) {
|
||||
return 'queued';
|
||||
}
|
||||
return normalized || 'unknown';
|
||||
}
|
||||
|
||||
export function getVideoURLFromDetail(detail) {
|
||||
const value = detail?.data?.video_url;
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : null;
|
||||
}
|
||||
|
||||
export function canCancelVideoTask(task) {
|
||||
const status = normalizeVideoTaskStatus(task?.status);
|
||||
return (
|
||||
task?.cancel_supported === true &&
|
||||
(status === 'queued' || status === 'in_progress')
|
||||
);
|
||||
}
|
||||
|
||||
export function canRegenerateVideoTask(task) {
|
||||
return task?.regenerate_supported === true;
|
||||
}
|
||||
|
||||
export function buildVideoRegenerateRequest(snapshot, selectedModel) {
|
||||
const model =
|
||||
typeof selectedModel === 'object'
|
||||
? selectedModel?.model_name || selectedModel?.id
|
||||
: selectedModel;
|
||||
return {
|
||||
...snapshot,
|
||||
model: model || snapshot?.model || '',
|
||||
image: snapshot?.image || '',
|
||||
seed: snapshot?.seed ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function normalizeExperienceVideoError(error, fallback = '请求失败') {
|
||||
const payload = error?.response?.data || error?.data || error;
|
||||
return {
|
||||
code: payload?.code || 'video_generation_failed',
|
||||
message: payload?.message || error?.message || fallback,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
/*
|
||||
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 {
|
||||
buildVideoRegenerateRequest,
|
||||
canCancelVideoTask,
|
||||
canRegenerateVideoTask,
|
||||
getVideoURLFromDetail,
|
||||
normalizeExperienceVideoError,
|
||||
normalizeVideoTaskStatus,
|
||||
} from './videoTask.js';
|
||||
|
||||
test('normalizes provider task statuses', () => {
|
||||
for (const status of ['SUCCESS', 'completed', 'SUCCEEDED']) {
|
||||
assert.equal(normalizeVideoTaskStatus(status), 'success');
|
||||
}
|
||||
for (const status of ['FAILURE', 'failed', 'CANCELED']) {
|
||||
assert.equal(normalizeVideoTaskStatus(status), 'failure');
|
||||
}
|
||||
assert.equal(normalizeVideoTaskStatus('SUBMITTED'), 'queued');
|
||||
assert.equal(normalizeVideoTaskStatus('processing'), 'in_progress');
|
||||
});
|
||||
|
||||
test('reads only the unified detail video URL', () => {
|
||||
assert.equal(
|
||||
getVideoURLFromDetail({ data: { video_url: ' https://cdn/video.mp4 ' } }),
|
||||
'https://cdn/video.mp4',
|
||||
);
|
||||
assert.equal(
|
||||
getVideoURLFromDetail({ data: { url: 'https://legacy/video.mp4' } }),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('honors task capabilities', () => {
|
||||
assert.equal(
|
||||
canCancelVideoTask({ status: 'IN_PROGRESS', cancel_supported: true }),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
canCancelVideoTask({ status: 'SUCCESS', cancel_supported: true }),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
canCancelVideoTask({ status: 'IN_PROGRESS', cancel_supported: false }),
|
||||
false,
|
||||
);
|
||||
assert.equal(canRegenerateVideoTask({ regenerate_supported: true }), true);
|
||||
assert.equal(canRegenerateVideoTask({ regenerate_supported: false }), false);
|
||||
});
|
||||
|
||||
test('builds regeneration request with the final selected model', () => {
|
||||
const request = buildVideoRegenerateRequest(
|
||||
{ model: 'old-model', prompt: 'hello', seed: 0 },
|
||||
{ id: 9, model_name: 'new-model' },
|
||||
);
|
||||
assert.equal(request.model, 'new-model');
|
||||
assert.equal(request.prompt, 'hello');
|
||||
assert.equal(request.seed, 0);
|
||||
});
|
||||
|
||||
test('normalizes API errors with stable code', () => {
|
||||
assert.deepEqual(
|
||||
normalizeExperienceVideoError({
|
||||
response: { data: { message: 'disabled', code: 'channel_not_enabled' } },
|
||||
}),
|
||||
{ message: 'disabled', code: 'channel_not_enabled' },
|
||||
);
|
||||
});
|
||||
Reference in New Issue
Block a user