Files
monkey-ai-web/src/helpers/api.js
T
qiubaishen 870b51d054 feat: 同步权限管理、企业成员排行与消费计费明细
- 接入平台与企业角色权限,按权限展示菜单、页面及操作。
- 企业成员排行按需加载,翻页沿用同一榜单快照,保留连续名次与前三名样式。
- 更新消费日志的费用明细、超管指标和官方价格汇率设置,补齐翻译与回归测试。
2026-11-25 21:08:24 +08:00

459 lines
14 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {
getUserIdFromLocalStorage,
redirectToExpiredLogin,
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';
import {
DEFAULT_READ_TIMEOUT_MS,
installRequestLifecycle,
} from './requestLifecycle';
import {
getCurrentOrgId,
getProxySession,
clearProxySession,
isProxyMode,
markProxyExpired,
} from './orgContext';
function createAPIInstance() {
const serverURL = getServerURL();
return axios.create({
baseURL: serverURL,
withCredentials: serverURL !== '',
// Let the lifecycle apply a read default while preserving explicit timeouts.
timeout: null,
headers: {
'Cache-Control': 'no-store',
},
});
}
export let API;
let retireAPI;
function patchAPIInstance(instance) {
const originalGet = instance.get.bind(instance);
const inFlightGetRequests = new Map();
instance.get = (url, config = {}) => {
if (
config?.disableDuplicate ||
config?.signal ||
config?.cancelToken ||
config?.requestGroup
) {
return originalGet(url, config);
}
const fallbackOrgId = url.startsWith('/api/org/')
? String(getCurrentOrgId() || '')
: '';
const requestKey = buildGetRequestKey(
url,
config,
fallbackOrgId,
getUserIdFromLocalStorage(),
);
const timeout =
config?.timeout ?? instance.defaults.timeout ?? DEFAULT_READ_TIMEOUT_MS;
const key = `${requestKey}#error=${!config?.skipErrorHandler}#session=${config?.sessionBound !== false}#timeout=${timeout}`;
if (inFlightGetRequests.has(key)) {
return inFlightGetRequests.get(key);
}
const reqPromise = originalGet(url, config).finally(() => {
inFlightGetRequests.delete(key);
});
inFlightGetRequests.set(key, reqPromise);
return reqPromise;
};
}
// 表示代理会话已失效、需清掉本标签页代理上下文的返回码
const PROXY_INVALID_CODES = new Set([
'proxy_invalid',
'proxy_timeout',
'proxy_org_mismatch',
]);
// 企业会话须先修改初始密码(服务端在改密前拒绝企业业务接口):回到企业登录页的改密步骤。
// 已在企业登录页时不再跳转(登录页自己处理),同一页面只跳一次。
let redirectingToChangePassword = false;
function redirectToChangeInitialPassword() {
if (redirectingToChangePassword || typeof window === 'undefined') return;
const { pathname, search, hash } = window.location;
if (/^\/org(?:\/[^/]+)?\/login\/?$/.test(pathname)) return;
redirectingToChangePassword = true;
const params = new URLSearchParams({ must_change: '1' });
if (pathname.startsWith('/org')) {
params.set('redirect', `${pathname}${search}${hash}`);
}
window.location.replace(`/org/login?${params.toString()}`);
}
// 添加 response interceptor:按业务返回码维护企业上下文(HTTP 200 + success:false)
function addOrgResponseInterceptor(instance) {
instance.interceptors.response.use((response) => {
const code = response?.data?.code;
// 代理会话失效(超时、重新登录、被结束、企业不一致):清掉本标签页的代理上下文,提示从企业管理重新进入。
// proxy_error 是服务端校验出错("稍后重试"),代理会话本身仍有效,不清理
if (PROXY_INVALID_CODES.has(code) && isProxyMode()) {
clearProxySession();
// 记下"本标签页代理已失效":企业中心据此固定显示失效提示,不回落到 localStorage 里的企业
markProxyExpired();
}
if (code === 'must_change_password' && response?.data?.success === false) {
redirectToChangeInitialPassword();
}
return response;
});
}
// 添加 request interceptor:自动为 /api/org/ 请求注入 X-Org-Id 头;超管代理标签页同时带上
// X-Proxy-Session(企业以代理会话为准,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 || getCurrentOrgId();
if (orgId && !explicitOrgId) {
config.headers['X-Org-Id'] = String(orgId);
}
const proxy = getProxySession();
if (proxy) {
config.headers['X-Proxy-Session'] = proxy.id;
}
}
return config;
});
}
export function updateAPI() {
const instance = createAPIInstance();
patchAPIInstance(instance);
addOrgHeaderInterceptor(instance);
addOrgResponseInterceptor(instance);
const previous = retireAPI;
retireAPI = installRequestLifecycle(instance, {
onError: (error) => showError(error, { redirectOnUnauthorized: false }),
onSessionExpired: redirectToExpiredLogin,
});
API = instance;
previous?.();
}
updateAPI();
// 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;
};
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 [];
}