merge: 合入总仓库 weiyuan(bfdfb339) web/ 新功能,保留 ui-optimization 的 UI 重构

来源:luoguang/monkey-ai weiyuan@bfdfb339 的 web/(经 sync/main-weiyuan-web-bfdfb339 同步)
同步基准:总仓库 a2ca13cb = 本仓库初始导入 d8f3aee2

冲突处理原则:保留 ui-optimization 的 UI(样式/结构/组件),嫁接 weiyuan 的功能逻辑。
- i18n:按键三方合并;ours 的「令牌→密钥」改名键上移植 theirs 的术语修订
- task-logs / OrgLogs:ours 已手工移植同一功能(6ad95e2),保留 ours
- 删除:OrgCreate(theirs 下线 /org/create)、旧 image 组件与 VideoRegenerateModal(theirs 体验中心重写)、
  OrgAvatarSection / PricingBentoPage / CommissionConsole(ours 重构中已移除)
- 测试:users-pagination 的 i18next mock 补 t();theirs 新增文件补 license header
This commit is contained in:
qiubaishen
2026-11-10 12:01:21 +08:00
266 changed files with 38432 additions and 7570 deletions
+5 -4
View File
@@ -25,6 +25,7 @@ import {
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';
@@ -232,7 +233,7 @@ export const extractErrorMessage = (body) => {
// 处理API错误响应
export const handleApiError = (error, response = null) => {
const errorInfo = {
error: error.message || '未知错误',
error: error.message || i18next.t('未知错误'),
timestamp: new Date().toISOString(),
stack: error.stack,
};
@@ -243,9 +244,9 @@ export const handleApiError = (error, response = null) => {
}
if (error.message.includes('HTTP error')) {
errorInfo.details = '服务器返回了错误状态码';
errorInfo.details = i18next.t('服务器返回了错误状态码');
} else if (error.message.includes('Failed to fetch')) {
errorInfo.details = '网络连接失败或服务器无响应';
errorInfo.details = i18next.t('网络连接失败或服务器无响应');
}
return errorInfo;
@@ -293,7 +294,7 @@ export const processGroupsData = (data, userGroup) => {
if (groupOptions.length === 0) {
groupOptions = [
{
label: '用户分组',
label: i18next.t('用户分组'),
value: '',
ratio: 1,
},
+36
View File
@@ -0,0 +1,36 @@
/*
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 i18next from 'i18next';
// Preserve settings unknown to this version of the channel form.
export function mergeChannelSettings(raw, edits, channelType, mode) {
const saved = raw ? JSON.parse(raw) : {};
if (!saved || Array.isArray(saved) || typeof saved !== 'object') {
throw new Error(i18next.t('渠道 setting 必须是 JSON 对象'));
}
const next = { ...saved, ...edits };
if (channelType === 62) {
const normalized = mode === undefined || mode === '' ? 'legacy' : mode;
if (!['legacy', 'omit'].includes(normalized)) {
throw new Error(i18next.t('百度真人 Header 模式必须是 legacy 或 omit'));
}
next.baidu_liveness_header_mode = normalized;
}
return JSON.stringify(next);
}
+53
View File
@@ -0,0 +1,53 @@
/*
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 { mergeChannelSettings } from './baiduChannelSettings.js';
test('channel form preserves unknown and existing settings while changing mode', () => {
const saved = JSON.stringify({
proxy: 'http://proxy',
future_field: { value: 7 },
baidu_liveness_header_mode: 'legacy',
});
const updated = JSON.parse(
mergeChannelSettings(saved, { proxy: 'http://new-proxy' }, 62, 'omit'),
);
assert.deepEqual(updated, {
proxy: 'http://new-proxy',
future_field: { value: 7 },
baidu_liveness_header_mode: 'omit',
});
assert.equal(
JSON.parse(mergeChannelSettings('', {}, 62, undefined))
.baidu_liveness_header_mode,
'legacy',
);
assert.deepEqual(
JSON.parse(mergeChannelSettings(saved, {}, 61, 'omit')),
JSON.parse(saved),
);
});
test('invalid saved settings and mode fail without silent replacement', () => {
for (const raw of ['null', '[]', '{bad'])
assert.throws(() => mergeChannelSettings(raw, {}, 62, 'omit'));
for (const mode of ['other', false, null])
assert.throws(() => mergeChannelSettings('{}', {}, 62, mode));
});
+372
View File
@@ -0,0 +1,372 @@
/*
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
*/
// 创作台统一错误映射(WP B-7,方案 §4.4「失败可理解」):图像 / 视频的提交错误与任务失败原因
// → 中文文案(i18n key)+ 下一步动作。纯函数、无 React / i18n 依赖,可直接 node --test。
// 旧视频页仍使用 helpers/videoTask.normalizeExperienceVideoError(只取 code / message),两者互不影响。
/** 下一步动作:界面据此渲染按钮(去充值 / 重试 / 修改提示词 / 重新上传)。 */
export const ERROR_ACTIONS = Object.freeze({
TOPUP: 'topup',
RETRY: 'retry',
EDIT_PROMPT: 'edit_prompt',
REPLACE_IMAGE: 'replace_image',
WAIT: 'wait',
CONTACT_ADMIN: 'contact_admin',
NONE: '',
});
/** 动作按钮文案(i18n key);无按钮的动作为 ''。 */
export const ERROR_ACTION_LABELS = Object.freeze({
topup: '去充值',
retry: '重试',
edit_prompt: '修改提示词',
replace_image: '重新上传',
});
const MODERATION_CODES = new Set([
'sensitive_words_detected',
'prompt_blocked',
'content_guard_error',
'content_policy_violation',
'content_moderation',
'moderation_blocked',
'data_inspection_failed',
]);
const BALANCE_CODES = new Set([
'insufficient_user_quota',
'insufficient_quota',
'quota_not_enough',
'pre_consume_token_quota_failed',
]);
const TIMEOUT_CODES = new Set([
'fallback_total_timeout',
'channel:response_time_exceeded',
'upstream_timeout',
]);
const BUSY_CODES = new Set([
'channel_not_enabled',
'get_channel_failed',
'channel:no_available_key',
'video_task_poller_unavailable',
'fallback_exhausted',
'task_busy',
]);
const VALIDATION_CODES = new Set([
'invalid_request',
'invalid_size',
'invalid_image',
'invalid_parameter',
'unsupported_parameter',
'unsupported_model',
'bad_request_body',
'too_many_ids',
]);
const RE_EXPIRED =
/原图已失效|image_result_expired|reference (image )?expired/i;
const RE_BUDGET = /预算(已达上限|已停用|不足)|企业额度不足/;
const RE_BALANCE =
/余额不足|额度不足|insufficient[_ ](user[_ ])?(quota|balance)|quota (is )?not enough|quota exceeded/i;
const RE_MODERATION =
/审核|敏感|违规|不合规|安全策略|内容安全|content[ _-]?(policy|filter|moderation|safety)|moderation|sensitive|safety (system|check|filter)|nsfw|inappropriate|data[_ ]inspection/i;
const RE_TIMEOUT =
/timed? ?out|timeout|超时|deadline exceeded|context deadline/i;
const RE_BUSY =
/no available (channel|key)|无可用渠道|渠道.{0,6}不可用|service unavailable|overloaded|繁忙|rate limit|too many requests/i;
const str = (v) => (typeof v === 'string' ? v : v == null ? '' : String(v));
/**
* 从 axios 错误 / 接口响应体 / { code, message } / 失败原因字符串中取出 code、message、status、type。
*/
export const extractCreationError = (input) => {
if (typeof input === 'string') {
return { code: '', message: input, status: 0, type: '' };
}
const err = input || {};
const body = err.response?.data || err.data || err;
const nested = body && typeof body.error === 'object' ? body.error : null;
return {
code: str(body?.code || nested?.code || err.code).trim(),
message: str(
body?.message ||
nested?.message ||
body?.description ||
err.failReason ||
err.message,
).trim(),
status: Number(err.response?.status || err.status) || 0,
type: str(body?.type || nested?.type).trim(),
};
};
/**
* 内容审核由哪个输入触发(后端在 message 中写明时):
* { key: 'prompt' } | { key: 'first_frame' } | { key: 'last_frame' }
* | { key: 'reference_images', index?: number(从 0 开始) } | { key: 'image' } | null
*/
export const moderationInputOf = (message) => {
const m = str(message);
if (!m) return null;
const bracket = m.match(/reference[_ ]?images?\s*\[\s*(\d+)\s*\]/i);
if (bracket) return { key: 'reference_images', index: Number(bracket[1]) };
const numbered = m.match(
/(?:参考图|图|reference[_ ]?image|image)\s*#?\s*(\d{1,2})(?![\dx×])/i,
);
if (numbered && Number(numbered[1]) > 0) {
return { key: 'reference_images', index: Number(numbered[1]) - 1 };
}
if (/首帧|first[_ ]?(frame|image)/i.test(m)) return { key: 'first_frame' };
if (/尾帧|last[_ ]?(frame|image)/i.test(m)) return { key: 'last_frame' };
if (/参考图|reference[_ ]?image/i.test(m)) {
return { key: 'reference_images' };
}
if (/提示词|prompt|text input|input text/i.test(m)) return { key: 'prompt' };
if (/图片|图像|image|photo|picture/i.test(m)) return { key: 'image' };
return null;
};
const INPUT_LABELS = {
first_frame: '首帧',
last_frame: '尾帧',
reference_images: '参考图',
};
const moderationResult = (base, message) => {
const input = moderationInputOf(message);
const out = {
...base,
category: 'moderation',
titleKey: '内容审核未通过',
input,
};
if (!input) {
return {
...out,
detailKey: '提示词或图片触发了内容安全策略,请修改后重试',
action: ERROR_ACTIONS.EDIT_PROMPT,
};
}
if (input.key === 'prompt') {
return {
...out,
detailKey: '提示词触发了内容安全策略,请修改后重试',
action: ERROR_ACTIONS.EDIT_PROMPT,
};
}
if (input.key === 'image') {
return {
...out,
detailKey: '上传的图片触发了内容安全策略,请更换图片',
action: ERROR_ACTIONS.REPLACE_IMAGE,
};
}
return {
...out,
detailKey: '{{input}}触发了内容安全策略,请更换图片',
detailParams: {
inputKey: INPUT_LABELS[input.key],
inputIndex:
input.key === 'reference_images' && Number.isInteger(input.index)
? input.index + 1
: 0,
},
action: ERROR_ACTIONS.REPLACE_IMAGE,
};
};
/**
* 统一错误分类。
* @param {any} input axios 错误、接口响应体、{ code, message, status } 或失败原因字符串
* @param {{ running?: number }} [extra] too_many_running_tasks 时进行中的任务数
* @returns {{
* category: 'concurrency'|'image_expired'|'budget'|'balance'|'moderation'|'timeout'
* |'busy'|'model_unavailable'|'validation'|'unknown',
* code: string, raw: string, action: string,
* titleKey: string, titleParams?: object, passthrough?: boolean,
* detailKey?: string, detailParams?: object, input?: object|null,
* }}
* passthrough=true 时标题直接使用 raw(后端校验文案,已是中文)。
*/
export const classifyCreationError = (input, extra = {}) => {
const { code, message, status, type } = extractCreationError(input);
const raw = message;
const lower = code.toLowerCase();
const base = { code, raw, action: ERROR_ACTIONS.NONE };
if (lower === 'too_many_running_tasks' || (!code && status === 429)) {
const running = Number(extra.running) || 0;
return running > 0
? {
...base,
category: 'concurrency',
titleKey: '已有 {{n}} 个任务进行中,完成后可继续',
titleParams: { n: running },
action: ERROR_ACTIONS.WAIT,
}
: {
...base,
category: 'concurrency',
titleKey: '进行中的任务过多,请稍后再试',
action: ERROR_ACTIONS.WAIT,
};
}
if (RE_EXPIRED.test(raw) || lower === 'image_result_expired') {
return {
...base,
category: 'image_expired',
titleKey: '引用的图片已失效,请重新上传',
action: ERROR_ACTIONS.REPLACE_IMAGE,
};
}
if (RE_BUDGET.test(raw)) {
return {
...base,
category: 'budget',
titleKey: raw,
passthrough: true,
detailKey: '请联系企业管理员调整预算',
action: ERROR_ACTIONS.CONTACT_ADMIN,
};
}
if (BALANCE_CODES.has(lower) || RE_BALANCE.test(raw)) {
return {
...base,
category: 'balance',
titleKey: '余额不足,请充值后再试',
action: ERROR_ACTIONS.TOPUP,
};
}
if (
MODERATION_CODES.has(lower) ||
type === 'content_guard_error' ||
RE_MODERATION.test(raw)
) {
return moderationResult(base, raw);
}
if (TIMEOUT_CODES.has(lower) || status === 504 || RE_TIMEOUT.test(raw)) {
return {
...base,
category: 'timeout',
titleKey: '上游响应超时,请稍后重试',
action: ERROR_ACTIONS.RETRY,
};
}
if (lower === 'model_not_found') {
return {
...base,
category: 'model_unavailable',
titleKey: '模型暂不可用,请切换其他模型',
};
}
if (
BUSY_CODES.has(lower) ||
status === 502 ||
status === 503 ||
RE_BUSY.test(raw)
) {
return {
...base,
category: 'busy',
titleKey: '服务繁忙,请稍后重试',
action: ERROR_ACTIONS.RETRY,
};
}
if ((VALIDATION_CODES.has(lower) || status === 400) && raw) {
return {
...base,
category: 'validation',
titleKey: raw,
passthrough: true,
};
}
return {
...base,
category: 'unknown',
titleKey: '生成失败',
action: ERROR_ACTIONS.RETRY,
};
};
/**
* 翻译分类结果:{ title, detail, actionLabel }。
* detail 在没有映射说明时回退为原始信息(与标题相同时省略)。
*/
export const describeCreationError = (t, info) => {
const tr = typeof t === 'function' ? t : (k) => k;
if (!info) return { title: '', detail: '', actionLabel: '' };
const title = info.passthrough
? info.raw
: tr(info.titleKey, info.titleParams);
let detail = '';
if (info.detailKey) {
const p = info.detailParams;
if (p && p.inputKey) {
const label = tr(p.inputKey);
detail = tr(info.detailKey, {
input: p.inputIndex ? `${label} ${p.inputIndex}` : label,
});
} else {
detail = tr(info.detailKey, p);
}
} else if (info.category === 'unknown' && info.raw && info.raw !== title) {
detail = info.raw;
}
const labelKey = ERROR_ACTION_LABELS[info.action] || '';
return { title, detail, actionLabel: labelKey ? tr(labelKey) : '' };
};
// ---------------------------------------------------------------------------
// 估价 dry-run 的预算不足(quote.balance_enough=false 时的 budget_source,见
// service/org_quota_dryrun.go):个人钱包 → 去充值;企业 / 令牌 → 说明是哪一级预算不足。
// ---------------------------------------------------------------------------
const PERSONAL_SOURCES = new Set(['user', 'membership', 'gift', 'unknown', '']);
const ORG_BUDGET_LABELS = {
department: '部门预算不足',
project: '项目预算不足',
member: '成员预算不足',
token: '令牌预算不足',
org: '企业预算不足',
};
/**
* @returns {null | { personal: boolean, source: string, labelKey: string }}
*/
export const budgetShortfallOf = (quote) => {
if (!quote || quote.balance_enough !== false) return null;
const source = str(quote.budget_source).trim();
if (PERSONAL_SOURCES.has(source)) {
return { personal: true, source, labelKey: '余额不足' };
}
if (source.startsWith('org_budget:')) {
const subject = source.slice('org_budget:'.length);
return {
personal: false,
source,
labelKey: ORG_BUDGET_LABELS[subject] || '企业预算不足',
};
}
if (source === 'token') {
return { personal: false, source, labelKey: '令牌额度不足' };
}
// org / org_member / org_gift:企业额度
return { personal: false, source, labelKey: '企业额度不足' };
};
+172
View File
@@ -0,0 +1,172 @@
/*
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 assert from 'node:assert/strict';
import test from 'node:test';
import {
ERROR_ACTIONS,
budgetShortfallOf,
classifyCreationError,
describeCreationError,
extractCreationError,
moderationInputOf,
} from './creationError.js';
const axiosError = (status, data) => ({ response: { status, data } });
const fmt = (k, p) =>
p ? k.replace(/\{\{(\w+)\}\}/g, (_, name) => String(p[name])) : k;
test('extract from axios error, body, nested error and string', () => {
assert.deepEqual(
extractCreationError(axiosError(400, { code: 'x', message: 'm' })),
{ code: 'x', message: 'm', status: 400, type: '' },
);
assert.deepEqual(
extractCreationError({
data: { error: { message: 'blocked', type: 'content_guard_error' } },
}),
{ code: '', message: 'blocked', status: 0, type: 'content_guard_error' },
);
assert.equal(extractCreationError('timeout').message, 'timeout');
});
test('concurrency limit', () => {
const a = classifyCreationError(
axiosError(429, { code: 'too_many_running_tasks' }),
{ running: 3 },
);
assert.equal(a.category, 'concurrency');
assert.equal(a.action, ERROR_ACTIONS.WAIT);
assert.deepEqual(a.titleParams, { n: 3 });
assert.equal(
classifyCreationError(axiosError(429, {})).category,
'concurrency',
);
});
test('balance → topup, org budget → contact admin', () => {
const b = classifyCreationError({ code: 'insufficient_user_quota' });
assert.equal(b.category, 'balance');
assert.equal(b.action, ERROR_ACTIONS.TOPUP);
assert.equal(classifyCreationError('用户余额不足').action, 'topup');
const o = classifyCreationError('部门预算已达上限');
assert.equal(o.category, 'budget');
assert.equal(o.passthrough, true);
assert.equal(o.action, ERROR_ACTIONS.CONTACT_ADMIN);
assert.equal(describeCreationError(fmt, o).title, '部门预算已达上限');
});
test('moderation names the triggering input when the backend says so', () => {
const p = classifyCreationError({
code: 'sensitive_words_detected',
message: 'prompt contains sensitive words',
});
assert.equal(p.category, 'moderation');
assert.deepEqual(p.input, { key: 'prompt' });
assert.equal(p.action, ERROR_ACTIONS.EDIT_PROMPT);
const ref = classifyCreationError(
'reference_images[1] rejected by moderation',
);
assert.deepEqual(ref.input, { key: 'reference_images', index: 1 });
assert.equal(ref.action, ERROR_ACTIONS.REPLACE_IMAGE);
assert.equal(
describeCreationError(fmt, ref).detail,
'参考图 2触发了内容安全策略,请更换图片',
);
const first = classifyCreationError('首帧图片审核未通过');
assert.deepEqual(first.input, { key: 'first_frame' });
const unknown = classifyCreationError({
data: { error: { message: 'blocked', type: 'content_guard_error' } },
});
assert.equal(unknown.category, 'moderation');
assert.equal(unknown.input, null);
assert.equal(moderationInputOf('image 1024x1024 nsfw')?.key, 'image');
});
test('timeout / busy → retry', () => {
assert.equal(
classifyCreationError('context deadline exceeded').category,
'timeout',
);
assert.equal(
classifyCreationError({ code: 'fallback_total_timeout' }).action,
ERROR_ACTIONS.RETRY,
);
assert.equal(
classifyCreationError(axiosError(503, { code: 'channel_not_enabled' }))
.category,
'busy',
);
});
test('expired reference image', () => {
const e = classifyCreationError(
axiosError(400, {
code: 'invalid_image',
message: '原图已失效,请重新上传',
}),
);
assert.equal(e.category, 'image_expired');
assert.equal(e.action, ERROR_ACTIONS.REPLACE_IMAGE);
});
test('validation passes through, unknown falls back to generic + raw detail', () => {
const v = classifyCreationError(
axiosError(400, {
code: 'unsupported_parameter',
message: '时长不支持 8 秒',
}),
);
assert.equal(v.category, 'validation');
assert.equal(describeCreationError(fmt, v).title, '时长不支持 8 秒');
const u = classifyCreationError('upstream said: weird');
assert.equal(u.category, 'unknown');
const d = describeCreationError(fmt, u);
assert.equal(d.title, '生成失败');
assert.equal(d.detail, 'upstream said: weird');
assert.equal(d.actionLabel, '重试');
});
test('budgetShortfallOf maps budget_source', () => {
assert.equal(budgetShortfallOf({ balance_enough: true }), null);
assert.equal(budgetShortfallOf(null), null);
assert.deepEqual(
budgetShortfallOf({ balance_enough: false, budget_source: 'user' }),
{ personal: true, source: 'user', labelKey: '余额不足' },
);
assert.equal(
budgetShortfallOf({
balance_enough: false,
budget_source: 'org_budget:department',
}).labelKey,
'部门预算不足',
);
assert.equal(
budgetShortfallOf({ balance_enough: false, budget_source: 'org' }).personal,
false,
);
assert.equal(
budgetShortfallOf({ balance_enough: false, budget_source: 'token' })
.labelKey,
'令牌额度不足',
);
});
+199
View File
@@ -0,0 +1,199 @@
/*
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
*/
// 创作页前端埋点(WP B-7,方案 §7.1),批量发往 POST /api/creation/events(WP A1-11)。
// - 每 10 秒 / 攒满 50 条 / 页面隐藏或 pagehide 时发送;每批 ≤ 50 条(后端上限);
// - fire-and-forget:发送失败直接丢弃、不重试;任何情况下都不抛异常、不打断页面。
// - 卸载时优先 fetch keepalive(UserAuth 需要 New-Api-User 头,sendBeacon 不能带头),
// fetch 不可用时回退 sendBeacon(尽力而为)。
export const EVENTS_ENDPOINT = '/api/creation/events';
export const EVENTS_MAX_BATCH = 50;
export const EVENTS_FLUSH_MS = 10 * 1000;
// 发送持续失败时队列的上限(超出丢弃最旧的)
export const EVENTS_MAX_QUEUE = 200;
const safe = (fn) => {
try {
const r = fn();
if (r && typeof r.catch === 'function') r.catch(() => {});
return r;
} catch (e) {
return undefined;
}
};
/**
* 可注入传输层的事件队列(单测直接用;页面使用下方默认单例)。
* @param {{
* send: (events: object[]) => Promise<any>|any, 常规发送
* sendOnUnload?: (events: object[]) => any, 页面卸载时发送(同步发起)
* now?: () => number,
* setTimer?: (fn, ms) => any, clearTimer?: (id) => void,
* flushMs?: number, maxBatch?: number, maxQueue?: number,
* }} options
*/
export const createCreationEventQueue = ({
send,
sendOnUnload,
now = () => Date.now(),
setTimer = (fn, ms) => setTimeout(fn, ms),
clearTimer = (id) => clearTimeout(id),
flushMs = EVENTS_FLUSH_MS,
maxBatch = EVENTS_MAX_BATCH,
maxQueue = EVENTS_MAX_QUEUE,
} = {}) => {
let queue = [];
let timer = null;
const takeBatches = () => {
const batches = [];
while (queue.length) batches.push(queue.splice(0, maxBatch));
return batches;
};
const stopTimer = () => {
if (timer !== null) safe(() => clearTimer(timer));
timer = null;
};
const flush = () => {
stopTimer();
takeBatches().forEach((batch) => safe(() => send && send(batch)));
};
const flushOnUnload = () => {
stopTimer();
const fn = sendOnUnload || send;
takeBatches().forEach((batch) => safe(() => fn && fn(batch)));
};
const track = (event, props) => {
safe(() => {
if (!event || typeof event !== 'string') return;
const item = { event, ts: Math.floor(now() / 1000) };
if (props && typeof props === 'object' && !Array.isArray(props)) {
item.props = props;
}
queue.push(item);
if (queue.length > maxQueue) queue = queue.slice(-maxQueue);
if (queue.length >= maxBatch) {
flush();
} else if (timer === null) {
timer = setTimer(() => {
timer = null;
flush();
}, flushMs);
}
});
};
return {
track,
flush,
flushOnUnload,
size: () => queue.length,
};
};
// ---------------------------------------------------------------------------
// 默认单例:常规发送走 API(axios 拦截器带 New-Api-User),卸载时 fetch keepalive
// ---------------------------------------------------------------------------
const readUserId = () => {
try {
const raw = window.localStorage.getItem('user');
const id = raw ? JSON.parse(raw)?.id : null;
return id === undefined || id === null ? '' : String(id);
} catch (e) {
return '';
}
};
const defaultSend = async (events) => {
const { API } = await import('./api');
await API.post(
EVENTS_ENDPOINT,
{ events },
{ skipErrorHandler: true, timeout: 10000 },
);
};
const defaultSendOnUnload = (events) => {
const body = JSON.stringify({ events });
const base =
(typeof window !== 'undefined' && window.__APP_CONFIG__?.SERVER_URL) || '';
const url = `${base}${EVENTS_ENDPOINT}`;
try {
if (typeof fetch === 'function') {
fetch(url, {
method: 'POST',
keepalive: true,
credentials: base ? 'include' : 'same-origin',
headers: {
'Content-Type': 'application/json',
'New-API-User': readUserId(),
},
body,
}).catch(() => {});
return;
}
} catch (e) {
// 落到 sendBeacon
}
try {
if (navigator?.sendBeacon) {
navigator.sendBeacon(url, new Blob([body], { type: 'application/json' }));
}
} catch (e) {
// 忽略
}
};
let defaultQueue = null;
const getDefaultQueue = () => {
if (defaultQueue) return defaultQueue;
defaultQueue = createCreationEventQueue({
send: defaultSend,
sendOnUnload: defaultSendOnUnload,
});
if (typeof window !== 'undefined') {
safe(() => {
window.addEventListener('pagehide', () => defaultQueue.flushOnUnload());
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') defaultQueue.flushOnUnload();
});
});
}
return defaultQueue;
};
/**
* 记录一个创作页事件(事件名需在后端白名单内:studio_view / prompt_focus / model_switch /
* quote_shown / submit / reuse_params / api_code_open / key_created_from_studio)。永不抛异常。
*/
export const trackCreationEvent = (event, props) => {
safe(() => getDefaultQueue().track(event, props));
};
/** 立即发送队列中的事件(如离开创作页时)。 */
export const flushCreationEvents = () => {
safe(() => defaultQueue && defaultQueue.flush());
};
+125
View File
@@ -0,0 +1,125 @@
/*
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 assert from 'node:assert/strict';
import test from 'node:test';
import {
EVENTS_MAX_BATCH,
createCreationEventQueue,
} from './creationEvents.js';
const fakeTimers = () => {
const timers = new Map();
let seq = 0;
return {
setTimer: (fn, ms) => {
seq += 1;
timers.set(seq, { fn, ms });
return seq;
},
clearTimer: (id) => timers.delete(id),
fire: () => {
const list = [...timers.values()];
timers.clear();
list.forEach((t) => t.fn());
},
count: () => timers.size,
};
};
test('batches events and flushes on the timer', () => {
const sent = [];
const timers = fakeTimers();
const q = createCreationEventQueue({
send: (batch) => sent.push(batch),
now: () => 5000,
...timers,
});
q.track('studio_view', { kind: 'image' });
q.track('prompt_focus');
assert.equal(sent.length, 0);
assert.equal(timers.count(), 1);
timers.fire();
assert.deepEqual(sent, [
[
{ event: 'studio_view', ts: 5, props: { kind: 'image' } },
{ event: 'prompt_focus', ts: 5 },
],
]);
assert.equal(q.size(), 0);
});
test('flushes immediately at 50 and never sends more than 50 per batch', () => {
const sent = [];
const timers = fakeTimers();
const q = createCreationEventQueue({
send: (batch) => sent.push(batch),
...timers,
});
for (let i = 0; i < EVENTS_MAX_BATCH; i += 1) q.track('submit', { i });
assert.equal(sent.length, 1);
assert.equal(sent[0].length, EVENTS_MAX_BATCH);
assert.equal(timers.count(), 0);
const unload = [];
const q2 = createCreationEventQueue({
send: () => {},
sendOnUnload: (batch) => unload.push(batch.length),
maxBatch: 50,
maxQueue: 500,
...fakeTimers(),
});
// 未达阈值的 49 条在卸载时一次发出
for (let i = 0; i < 49; i += 1) q2.track('a');
q2.flushOnUnload();
assert.deepEqual(unload, [49]);
});
test('never throws: send errors, rejected promises, bad input', async () => {
const q = createCreationEventQueue({
send: () => {
throw new Error('boom');
},
...fakeTimers(),
});
q.track('studio_view');
q.track('');
q.track(null);
q.track('x', ['not', 'object']);
assert.doesNotThrow(() => q.flush());
const q2 = createCreationEventQueue({
send: () => Promise.reject(new Error('net')),
...fakeTimers(),
});
q2.track('studio_view');
assert.doesNotThrow(() => q2.flush());
await new Promise((r) => setTimeout(r, 0));
});
test('queue is bounded when nothing is flushed', () => {
const q = createCreationEventQueue({
send: () => {},
maxBatch: 1000,
maxQueue: 10,
...fakeTimers(),
});
for (let i = 0; i < 25; i += 1) q.track('submit');
assert.equal(q.size(), 10);
});
+29
View File
@@ -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
*/
/**
* 新创作台灰度开关(/api/status 的 experience_creation_v2_enabled,对应系统选项
* ExperienceCreationV2Enabled,默认 "false")。只读服务端状态,不读 localStorage,
* 避免用户自行打开未上线的界面。
*/
export const isCreationStudioEnabled = (status) => {
const v = status?.experience_creation_v2_enabled;
if (typeof v === 'boolean') return v;
return String(v || '').toLowerCase() === 'true';
};
+16 -5
View File
@@ -26,6 +26,8 @@ For commercial licensing, please contact support@quantumnous.com
// - 时间戳标在每条消息标题旁,方便回溯;
// - 没有 HTML、没有样式,导出后可直接贴到 Obsidian / Notion / GitHub。
import i18next from 'i18next';
const formatTs = (ms) => {
if (!ms) return '';
const d = new Date(ms);
@@ -73,13 +75,20 @@ const renderSources = (message) => {
const title = s.title || s.url || '';
return `${idx}. [${title}](${s.url})`;
});
return `\n\n**参考来源**\n\n${lines.join('\n')}\n`;
return `\n\n**${i18next.t('参考来源')}**\n\n${lines.join('\n')}\n`;
};
const ROLE_ICON = {
user: '👤',
assistant: '🤖',
system: '⚙️',
};
// 保留中文作为 i18n key,导出时再翻译
const ROLE_LABEL = {
user: '👤 用户',
assistant: '🤖 助手',
system: '⚙️ 系统',
user: '用户',
assistant: '助手',
system: '系统',
};
/**
@@ -100,7 +109,9 @@ export const conversationToMarkdown = ({ title, 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 label = ROLE_LABEL[m.role]
? `${ROLE_ICON[m.role]} ${i18next.t(ROLE_LABEL[m.role])}`
: m.role;
const tsStr = m.createAt ? ` · ${formatTs(m.createAt)}` : '';
lines.push(`## ${label}${tsStr}`, '');
const body = renderMessageBody(m).trim();
+24 -8
View File
@@ -25,12 +25,20 @@ For commercial licensing, please contact support@quantumnous.com
// - filter 天然保序,导出顺序 == 会话顺序;
// - Word 走 docx 库,动态 import 懒加载,首次导出 Word 才拉这个 chunk。
import i18next from 'i18next';
// 保留中文作为 i18n key,导出时再翻译
const ROLE_LABEL = {
user: '用户',
assistant: '助手',
system: '系统',
};
const roleLabel = (m) =>
ROLE_LABEL[m.role]
? i18next.t(ROLE_LABEL[m.role])
: m.role || i18next.t('消息');
// formatTs 把毫秒时间戳格式化为 YYYY-MM-DD HH:mm
const formatTs = (ms) => {
if (!ms) return '';
@@ -53,11 +61,13 @@ const messageToText = (m) => {
if (part.type === 'text') {
return typeof part.text === 'string' ? part.text : '';
}
if (part.type === 'image_url') return '[图片]';
if (part.type === 'image_url') return `[${i18next.t('图片')}]`;
if (part.type === 'file') {
const f = part.file || {};
const name = f.filename || f.file_name || '';
return name ? `[文件: ${name}]` : '[文件]';
return name
? i18next.t('[文件: {{name}}]', { name })
: `[${i18next.t('文件')}]`;
}
return '';
})
@@ -111,10 +121,16 @@ 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())})`, ''];
const safeTitle = (title && title.trim()) || i18next.t('导出消息');
const lines = [
i18next.t('{{title}}(导出于 {{time}})', {
title: safeTitle,
time: formatTs(Date.now()),
}),
'',
];
for (const m of selected) {
const label = ROLE_LABEL[m.role] || m.role || '消息';
const label = roleLabel(m);
const tsStr = m.createAt ? ` (${formatTs(m.createAt)})` : '';
lines.push(`【${label}】${tsStr}`);
const body = messageToText(m).trim();
@@ -140,7 +156,7 @@ export const exportSelectedAsWord = async (messages, selectedIds, title) => {
const { Document, Paragraph, TextRun, Packer } = await import('docx');
const safeTitle = (title && title.trim()) || '导出消息';
const safeTitle = (title && title.trim()) || i18next.t('导出消息');
const children = [
new Paragraph({
children: [new TextRun({ text: safeTitle, bold: true, size: 32 })],
@@ -148,7 +164,7 @@ export const exportSelectedAsWord = async (messages, selectedIds, title) => {
new Paragraph({
children: [
new TextRun({
text: `导出于 ${formatTs(Date.now())}`,
text: i18next.t('导出于 {{time}}', { time: formatTs(Date.now()) }),
italics: true,
size: 18,
color: '888888',
@@ -159,7 +175,7 @@ export const exportSelectedAsWord = async (messages, selectedIds, title) => {
];
for (const m of selected) {
const label = ROLE_LABEL[m.role] || m.role || '消息';
const label = roleLabel(m);
const tsStr = m.createAt ? `(${formatTs(m.createAt)})` : '';
children.push(
new Paragraph({
+75
View File
@@ -0,0 +1,75 @@
/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
// WeyAi 微信小程序的 web-view 里打开登录页时(WeyAi 仓库 docs/fork/16 第 5.2 节 MP-M1):
// web-view 只能打开登记过的业务域名,第三方登录要跳到 GitHub、OIDC 等外部域名,会被拦下;
// passkey 依赖的 WebAuthn 在 web-view 里也用不了。所以只留站内能完成的方式:
// 账号密码、公众号验证码、2FA、首次改密码。
/**
* 是否在小程序 web-view 里。JSSDK 注入的 `__wxjs_environment` 最准,但要等 WeixinJSBridgeReady;
* 页面刚加载时它可能还没有,所以再用 UA 里的 `miniProgram` 兜底(安卓和 iOS 的 web-view 都带)。
*/
export function isMiniProgramWebView(
win = typeof window === 'undefined' ? undefined : window,
) {
if (!win) return false;
if (win.__wxjs_environment === 'miniprogram') return true;
const ua = (win.navigator?.userAgent || '').toLowerCase();
return ua.includes('miniprogram');
}
/** 要跳到外部域名、或依赖 WebAuthn 的登录方式开关。 */
const EXTERNAL_LOGIN_FLAGS = [
'github_oauth',
'discord_oauth',
'oidc_enabled',
'linuxdo_oauth',
'telegram_oauth',
'wechat_open_oauth',
'passkey_login',
];
/**
* 小程序里不出现的付费页面。iOS 小程序按微信规则不能售卖虚拟商品,充值和开票都回到网页完成
* (WeyAi 仓库 docs/fork/16)。
*/
const MINI_PROGRAM_PAYMENT_PATHS = [
'/recharge',
'/topup',
'/user-center/topup',
'/user-center/invoice',
'/console/topup',
'/org/recharge',
];
/** 这个地址是不是小程序里不出现的付费页面(含其下的子路径)。 */
export function isMiniProgramPaymentPath(pathname) {
const path = (pathname || '').replace(/\/+$/, '');
return MINI_PROGRAM_PAYMENT_PATHS.some(
(prefix) => path === prefix || path.startsWith(`${prefix}/`),
);
}
/** 小程序里用的站点状态:关掉上面这些开关,其他原样保留(包括 Turnstile)。 */
export function withMiniProgramLogins(status) {
const next = { ...status };
for (const flag of EXTERNAL_LOGIN_FLAGS) next[flag] = false;
return next;
}
+104
View File
@@ -0,0 +1,104 @@
/*
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 {
isMiniProgramPaymentPath,
isMiniProgramWebView,
withMiniProgramLogins,
} from './miniProgram.js';
const ua = (userAgent) => ({ navigator: { userAgent } });
test('识别小程序 web-view:JSSDK 标记或 UA', () => {
assert.equal(
isMiniProgramWebView({ __wxjs_environment: 'miniprogram', navigator: {} }),
true,
);
assert.equal(
isMiniProgramWebView(
ua(
'Mozilla/5.0 (Linux; Android 13) MicroMessenger/8.0.47 miniProgram/wx123',
),
),
true,
);
// 微信内置浏览器(公众号网页)不是小程序,照旧走公众号授权。
assert.equal(
isMiniProgramWebView(ua('Mozilla/5.0 (iPhone) MicroMessenger/8.0.47')),
false,
);
assert.equal(isMiniProgramWebView(ua('Mozilla/5.0 Chrome/120')), false);
assert.equal(isMiniProgramWebView(undefined), false);
});
test('小程序里只关掉外部登录和 passkey,其他开关不动', () => {
const status = {
github_oauth: true,
discord_oauth: true,
oidc_enabled: true,
linuxdo_oauth: true,
telegram_oauth: true,
wechat_open_oauth: true,
passkey_login: true,
wechat_login: true,
turnstile_check: true,
system_name: 'x',
};
const next = withMiniProgramLogins(status);
assert.deepEqual(next, {
github_oauth: false,
discord_oauth: false,
oidc_enabled: false,
linuxdo_oauth: false,
telegram_oauth: false,
wechat_open_oauth: false,
passkey_login: false,
wechat_login: true,
turnstile_check: true,
system_name: 'x',
});
// 不改原对象(它是全站共享的状态)。
assert.equal(status.github_oauth, true);
});
test('小程序里的付费页面:充值、开票及其子路径', () => {
for (const path of [
'/recharge',
'/recharge/',
'/user-center/topup',
'/user-center/invoice/detail',
'/topup',
'/console/topup',
'/org/recharge',
]) {
assert.equal(isMiniProgramPaymentPath(path), true, path);
}
for (const path of [
'/user-center/dashboard',
'/rechargeable',
'/',
'',
undefined,
]) {
assert.equal(isMiniProgramPaymentPath(path), false, String(path));
}
});
+38 -10
View File
@@ -17,6 +17,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import i18next from 'i18next';
// ============================================================================
// 模型原厂(官方)价格 · 折扣计算纯函数
// ----------------------------------------------------------------------------
@@ -391,26 +393,33 @@ export const sanitizeOfficialPriceMap = (raw) => {
return {
value,
errors: [
'顶层必须是 { 模型名: { input, output, per_call, cache_read, cache_creation, per_second: {档位: 价}, per_image: {档位: 价} } } 结构',
i18next.t(
'顶层必须是 { 模型名: { 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('存在空模型名');
errors.push(i18next.t('存在空模型名'));
return;
}
const entry = raw[model];
if (!entry || typeof entry !== 'object' || Array.isArray(entry)) {
errors.push(`${name}: 价格必须是对象`);
errors.push(i18next.t('{{name}}: 价格必须是对象', { name }));
return;
}
const unknown = Object.keys(entry).filter(
(k) => !OFFICIAL_FIELDS.includes(k),
);
if (unknown.length > 0) {
errors.push(`${name}: 不认识的字段 ${unknown.join('、')}`);
errors.push(
i18next.t('{{name}}: 不认识的字段 {{fields}}', {
name,
fields: unknown.join(', '),
}),
);
return;
}
const kept = {};
@@ -421,7 +430,11 @@ export const sanitizeOfficialPriceMap = (raw) => {
if (isTierField(field)) {
// 分档字段是 { 档位键: 价格 } 映射;写成标量说明量纲搞错了,必须报错
if (typeof v !== 'object' || Array.isArray(v)) {
errors.push(`${name}.${field}: 必须是 { 档位键: 价格 } 结构`);
errors.push(
i18next.t('{{name}}: 必须是 { 档位键: 价格 } 结构', {
name: `${name}.${field}`,
}),
);
fieldFailed = true;
return;
}
@@ -429,21 +442,30 @@ export const sanitizeOfficialPriceMap = (raw) => {
Object.keys(v).forEach((rawKey) => {
const key = normalizeTierKey(rawKey);
if (!key) {
errors.push(`${name}.${field}: 存在空档位键`);
errors.push(
i18next.t('{{name}}: 存在空档位键', { name: `${name}.${field}` }),
);
fieldFailed = true;
return;
}
// 归一后重键:只差大小写的两档会互相覆盖,静默丢掉一档的牌价
if (tiers[key] !== undefined) {
errors.push(
`${name}.${field}: 档位键 ${key} 重复(档位键大小写不敏感)`,
i18next.t('{{name}}: 档位键 {{key}} 重复(档位键大小写不敏感)', {
name: `${name}.${field}`,
key,
}),
);
fieldFailed = true;
return;
}
const tv = Number(v[rawKey]);
if (!isPositiveFinite(tv)) {
errors.push(`${name}.${field}.${rawKey}: 必须是大于 0 的数值`);
errors.push(
i18next.t('{{name}}: 必须是大于 0 的数值', {
name: `${name}.${field}.${rawKey}`,
}),
);
fieldFailed = true;
return;
}
@@ -454,7 +476,11 @@ export const sanitizeOfficialPriceMap = (raw) => {
}
const n = Number(v);
if (!isPositiveFinite(n)) {
errors.push(`${name}.${field}: 必须是大于 0 的数值`);
errors.push(
i18next.t('{{name}}: 必须是大于 0 的数值', {
name: `${name}.${field}`,
}),
);
fieldFailed = true;
return;
}
@@ -462,7 +488,9 @@ export const sanitizeOfficialPriceMap = (raw) => {
});
if (Object.keys(kept).length === 0) {
// 已按字段报过错就不再叠一条「未填写任何字段」,否则同一处问题报两遍
if (!fieldFailed) errors.push(`${name}: 未填写任何官方价字段`);
if (!fieldFailed) {
errors.push(i18next.t('{{name}}: 未填写任何官方价字段', { name }));
}
return;
}
value[name] = kept;
+4 -2
View File
@@ -16,6 +16,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import i18next from 'i18next';
export function base64UrlToBuffer(base64url) {
if (!base64url) return new ArrayBuffer(0);
let padding = '='.repeat((4 - (base64url.length % 4)) % 4);
@@ -50,7 +52,7 @@ export function prepareCredentialCreationOptions(payload) {
payload?.response ||
payload?.Response;
if (!options) {
throw new Error('无法从服务端响应中解析 Passkey 注册参数');
throw new Error(i18next.t('无法从服务端响应中解析 Passkey 注册参数'));
}
const publicKey = {
...options,
@@ -85,7 +87,7 @@ export function prepareCredentialRequestOptions(payload) {
payload?.response ||
payload?.Response;
if (!options) {
throw new Error('无法从服务端响应中解析 Passkey 登录参数');
throw new Error(i18next.t('无法从服务端响应中解析 Passkey 登录参数'));
}
const publicKey = {
...options,
+41
View File
@@ -0,0 +1,41 @@
/*
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 calculatePresetPayableAmount(
preset,
priceRatio = 1,
topupInfo = {},
) {
const value = Number(preset?.value);
if (!Number.isFinite(value)) return 0;
const configuredDiscount =
preset?.discount ?? topupInfo?.discount?.[preset.value];
const discount = Number(configuredDiscount ?? 1);
const safeDiscount = Number.isFinite(discount) ? discount : 1;
// New recharge tiers are already denominated in CNY. Legacy tiers use the
// historical USD-to-display-currency ratio before applying their discount.
if (preset?.id !== undefined) {
return value * safeDiscount;
}
const ratio = Number(priceRatio);
return value * (Number.isFinite(ratio) ? ratio : 1) * safeDiscount;
}
+36
View File
@@ -0,0 +1,36 @@
/*
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 { calculatePresetPayableAmount } from './rechargeAmount.js';
test('calculates a new recharge tier in CNY without applying the legacy exchange rate', () => {
assert.equal(
calculatePresetPayableAmount({ id: 1, value: 10, discount: 1 }, 7.3),
10,
);
});
test('calculates a legacy recharge amount with the configured exchange rate', () => {
assert.equal(
calculatePresetPayableAmount({ value: 10, discount: 1 }, 7.3),
73,
);
});
+8 -3
View File
@@ -624,7 +624,7 @@ export function renderGroup(group) {
onClick={async (event) => {
event.stopPropagation();
if (await copy(group)) {
showSuccess(i18next.t('已复制:') + group);
showSuccess(i18next.t('已复制:{{name}}', { name: group }));
} else {
Modal.error({
title: i18next.t('无法复制到剪贴板,请手动复制'),
@@ -1161,7 +1161,10 @@ export function renderModelPrice(
symbol: symbol,
price: (inputRatioPrice * rate).toFixed(6),
audioPrice: audioInputSeperatePrice
? `,音频 ${symbol}${(audioInputPrice * rate).toFixed(6)} / 1M tokens`
? i18next.t(',音频 {{symbol}}{{price}} / 1M tokens', {
symbol,
price: (audioInputPrice * rate).toFixed(6),
})
: '',
},
)}
@@ -1665,7 +1668,9 @@ export function renderAudioModelPrice(
export function renderQuotaWithPrompt(quota, digits) {
const quotaDisplayType = localStorage.getItem('quota_display_type') || 'USD';
if (quotaDisplayType !== 'TOKENS') {
return i18next.t('等价金额:') + renderQuota(quota, digits);
return i18next.t('等价金额:{{amount}}', {
amount: renderQuota(quota, digits),
});
}
return '';
}
+35 -21
View File
@@ -134,7 +134,7 @@ export function showError(error) {
if (error.name === 'AxiosError') {
// 检查 response 是否存在(网络错误时 response 为 undefined)
if (!error.response) {
Toast.error('错误:网络请求失败,请检查网络连接');
Toast.error(i18next.t('错误:网络请求失败,请检查网络连接'));
return;
}
switch (error.response.status) {
@@ -153,26 +153,30 @@ export function showError(error) {
window.location.href = `/org/login?expired=true${redirect}`;
break;
case 429:
Toast.error('错误:请求次数过多,请稍后再试!');
Toast.error(i18next.t('错误:请求次数过多,请稍后再试!'));
break;
case 500:
Toast.error('错误:服务器内部错误,请联系管理员!');
Toast.error(i18next.t('错误:服务器内部错误,请联系管理员!'));
break;
case 405:
Toast.info('本站仅作演示之用,无服务端!');
Toast.info(i18next.t('本站仅作演示之用,无服务端!'));
break;
default: {
// 后端业务错误(4xx/5xx)带有面向用户的 message 字段;
// 优先展示它,而不是 axios 的 "Request failed with status code XXX"。
const backendMessage = error.response?.data?.message;
Toast.error('错误:' + (backendMessage || error.message));
Toast.error(
i18next.t('错误:{{message}}', {
message: backendMessage || error.message,
}),
);
}
}
return;
}
Toast.error('错误:' + error.message);
Toast.error(i18next.t('错误:{{message}}', { message: error.message }));
} else {
Toast.error('错误:' + error);
Toast.error(i18next.t('错误:{{message}}', { message: error }));
}
}
@@ -676,19 +680,19 @@ export const getRelativeTime = (publishDate) => {
// 根据时间差返回相应的描述
if (diffSeconds < 60) {
return '刚刚';
return i18next.t('刚刚');
} else if (diffMinutes < 60) {
return `${diffMinutes} 分钟前`;
return i18next.t('{{n}} 分钟前', { n: diffMinutes });
} else if (diffHours < 24) {
return `${diffHours} 小时前`;
return i18next.t('{{n}} 小时前', { n: diffHours });
} else if (diffDays < 7) {
return `${diffDays} 天前`;
return i18next.t('{{n}} 天前', { n: diffDays });
} else if (diffWeeks < 4) {
return `${diffWeeks} 周前`;
return i18next.t('{{n}} 周前', { n: diffWeeks });
} else if (diffMonths < 12) {
return `${diffMonths} 个月前`;
return i18next.t('{{n}} 个月前', { n: diffMonths });
} else if (diffYears < 2) {
return '1 年前';
return i18next.t('{{n}} 年前', { n: 1 });
} else {
// 超过2年显示具体日期
return formatDateString(pubDate);
@@ -835,14 +839,20 @@ export const calculateModelPrice = ({
const hasCacheCreation5m = hasNumericPriceValue(
record.cache_creation_5m_ratio,
);
// 只有 1h 档(Claude:全部写入按 1h 计费)时不再重复展示通用缓存创建价
const onlyCacheCreation1h =
!hasCacheCreation5m &&
hasNumericPriceValue(record.cache_creation_1h_ratio);
const cacheCreationRatio = hasCacheCreation5m
? record.cache_creation_5m_ratio
: record.cache_creation_ratio;
addExtraPrice(
hasCacheCreation5m ? 'cache_creation_5m' : 'cache_creation',
hasCacheCreation5m ? '缓存创建(5m)' : '缓存创建',
cacheCreationRatio,
);
if (!onlyCacheCreation1h) {
addExtraPrice(
hasCacheCreation5m ? 'cache_creation_5m' : 'cache_creation',
hasCacheCreation5m ? '缓存创建(5m)' : '缓存创建',
cacheCreationRatio,
);
}
addExtraPrice(
'cache_creation_1h',
'缓存创建(1h)',
@@ -1068,7 +1078,7 @@ export const createCardProPagination = ({
showSizeChanger = true,
showRange = true,
preventPageChangeOnPageSizeChange = false,
t = (key) => key,
t = i18next.t.bind(i18next),
}) => {
if (!total || total <= 0) return null;
@@ -1078,7 +1088,11 @@ export const createCardProPagination = ({
const start = (currentPage - 1) * pageSize + 1;
const end = Math.min(currentPage * pageSize, total);
const totalText = `${t('显示第')} ${start} ${t('条 - 第')} ${end} ${t('条,共')} ${total} ${t('条')}`;
const totalText = t('显示第 {{start}} 条 - 第 {{end}} 条,共 {{total}} 条', {
start,
end,
total,
});
return (
<>
+6 -14
View File
@@ -17,6 +17,8 @@ along with this program. If not, see <https://www.gnu.org/licenses/>.
For commercial licensing, please contact support@quantumnous.com
*/
import i18next from 'i18next';
const SUCCESS_STATUSES = new Set(['success', 'completed', 'succeeded']);
const FAILURE_STATUSES = new Set([
'failure',
@@ -61,20 +63,10 @@ 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 = '请求失败') {
export function normalizeExperienceVideoError(
error,
fallback = i18next.t('请求失败'),
) {
const payload = error?.response?.data || error?.data || error;
return {
code: payload?.code || 'video_generation_failed',
-11
View File
@@ -21,7 +21,6 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import {
buildVideoRegenerateRequest,
canCancelVideoTask,
canRegenerateVideoTask,
getVideoURLFromDetail,
@@ -68,16 +67,6 @@ test('honors task capabilities', () => {
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({