6160a23117
同步基准:总仓库 a2ca13cb(= 本仓库初始导入 d8f3aee2) 范围:a2ca13cb..bfdfb339 中触及 web/ 的提交(不含 web/.claude/settings.local.json) - 8490ac02 feat(aliyun): integrate Wan 3 and Qwen Image models - 2aff08ec perf(analytics): 运营看板概览改读汇总表,首屏从 19s 降到 0.4s - dc69335e feat(experience): 体验中心图像/视频创作升级(能力 schema、估价、新创作台) - b059c657 fix(org): 下线 /org/create 自助加入企业页与 POST /api/org/join - 4fcf47e6 fix(i18n): 修复中/英/韩/繁体多语言错乱,补齐日/越/泰译文 - e4c301d5 fix: merge enterprise task record date filters - c9369b95 feat: expose enterprise image and video task records - a410fee5 feat(claude): 无断点请求自动注入 cache_control 断点(方案 2) - 521b3376 feat(claude): 缓存命中率优化——上游粘性路由 + 缓存时长强制改写 - 73b615dd feat(pricing): 企业成员不论登录身份均按所属企业等级计价与扣费 - f73f55c3 feat(client): 新增 WeyAi 版本说明管理与公开读取接口 - 8cdf1994 fix(topup): reset amount when switching from PayPal - 93a4ac34 feat(baidu): configure Seedance liveness header by channel - cb1818c5 fix(weyai): 按评审修正内容清理竞态、默认适用端与中文退回(M21) - 04214d83 feat(weyai): WeyAi 内容管理与客户端内容接口(M21 第二部分) - e3c4a57c feat(weyai): 设置页新增 WeyAi 页签与内容专用 COS 桶(M21 第一部分) - b5ee8e70 fix(auth): 会话角色/状态以 DB 为准,修复提升管理员后管理接口报权限不足 - e4618fc2 fix: 修复企业看板日志聚合死循环导致 CPU 打满,并降低看板查询开销 - 584aad52 style(web): 个人中心侧边栏按 prettier 换行 - b8d87064 fix: 小程序教程隐藏充值后保留原步骤编号,企业充值判断直接用 isMiniProgramWebView - eee7f5b2 fix: 小程序里企业首页不落到充值页,隐藏钱包入口与教程充值步骤 - 8b254d49 fix: 小程序里隐藏企业充值入口与页面 - a67661b4 fix(web): 小程序里个人中心默认页跳过充值和发票,避免来回跳转 - cff6c543 feat(web): WeyAi 小程序里打开个人中心时不出现充值和开票 - c6c99eb6 feat(billing): Claude 全部缓存写入统一按 1h 倍率计费 - 0699d1bf fix(web): 小程序 web-view 里注册页同样只显示站内方式 - 04853331 feat(web): WeyAi 小程序 web-view 里登录页只显示站内登录方式
427 lines
13 KiB
JavaScript
427 lines
13 KiB
JavaScript
/*
|
||
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 i18next from 'i18next';
|
||
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 || i18next.t('未知错误'),
|
||
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 = i18next.t('服务器返回了错误状态码');
|
||
} else if (error.message.includes('Failed to fetch')) {
|
||
errorInfo.details = i18next.t('网络连接失败或服务器无响应');
|
||
}
|
||
|
||
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: i18next.t('用户分组'),
|
||
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 [];
|
||
}
|