Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 7c65540366 | |||
| 5db7478c98 | |||
| d523b9595d | |||
| 49ff7c9bad | |||
| 7c18c998bd | |||
| 07a88eb194 | |||
| 8e4fc09cb5 | |||
| 391ba0b705 | |||
| c44017eccd |
@@ -280,6 +280,9 @@ H5_ACCESS_PASSWORD=change-me
|
||||
# H5_COST_ESTIMATE_FROM_TOKENS=1
|
||||
# H5_COST_ESTIMATE_INPUT_USD_PER_1M=0.27
|
||||
# H5_COST_ESTIMATE_OUTPUT_USD_PER_1M=1.1
|
||||
# 上述计费公式也可在 memind_adm「计费中心 → 计量公式」后台覆盖(写入 h5_billing_admin_config)。
|
||||
# 设为 env 时强制只读环境变量,禁止后台改写:
|
||||
# H5_BILLING_CONFIG_SOURCE=env
|
||||
|
||||
# 用户自助充值(微信支付)
|
||||
# H5_RECHARGE_TIERS_CENTS=500,1000,3000,5000,10000,20000
|
||||
|
||||
@@ -0,0 +1,310 @@
|
||||
import { loadBillingConfig } from './billing.mjs';
|
||||
|
||||
const CONFIG_TABLE = 'h5_billing_admin_config';
|
||||
const CONFIG_SCOPE = 'global';
|
||||
const SOURCE_ADMIN_DB = 'admin-db';
|
||||
const SOURCE_ENV = 'env';
|
||||
const SOURCE_ENV_OVERRIDE = 'env-override';
|
||||
const SOURCE_DEFAULT = 'default';
|
||||
const CACHE_TTL_MS = 5_000;
|
||||
const DEFAULT_ESTIMATE_INPUT_USD_PER_1M = 0.27;
|
||||
const DEFAULT_ESTIMATE_OUTPUT_USD_PER_1M = 1.1;
|
||||
|
||||
function normalizeBoolean(value, fallback = false) {
|
||||
if (value == null || value === '') return fallback;
|
||||
if (typeof value === 'boolean') return value;
|
||||
const normalized = String(value).trim().toLowerCase();
|
||||
if (['1', 'true', 'yes', 'on'].includes(normalized)) return true;
|
||||
if (['0', 'false', 'no', 'off'].includes(normalized)) return false;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function normalizePositiveNumber(value, fallback) {
|
||||
const num = Number(value);
|
||||
if (!Number.isFinite(num) || num <= 0) return fallback;
|
||||
return num;
|
||||
}
|
||||
|
||||
function normalizeNonNegativeNumber(value, fallback) {
|
||||
const num = Number(value);
|
||||
if (!Number.isFinite(num) || num < 0) return fallback;
|
||||
return num;
|
||||
}
|
||||
|
||||
function defaultConfigShape(env = process.env) {
|
||||
const billing = loadBillingConfig(env);
|
||||
const costEstimateFromTokens = env.H5_COST_ESTIMATE_FROM_TOKENS !== '0';
|
||||
const inputUsdPer1M = Number(env.H5_COST_ESTIMATE_INPUT_USD_PER_1M ?? DEFAULT_ESTIMATE_INPUT_USD_PER_1M);
|
||||
const outputUsdPer1M = Number(env.H5_COST_ESTIMATE_OUTPUT_USD_PER_1M ?? DEFAULT_ESTIMATE_OUTPUT_USD_PER_1M);
|
||||
return {
|
||||
useBackendCost: billing.useBackendCost,
|
||||
usdCnyRate: billing.usdCnyRate,
|
||||
marginMultiplier: billing.marginMultiplier,
|
||||
inputCentsPer1k: billing.inputCentsPer1k,
|
||||
outputCentsPer1k: billing.outputCentsPer1k,
|
||||
minBillCents: billing.minBillCents,
|
||||
costEstimateFromTokens,
|
||||
costEstimateInputUsdPer1M:
|
||||
Number.isFinite(inputUsdPer1M) && inputUsdPer1M >= 0
|
||||
? inputUsdPer1M
|
||||
: DEFAULT_ESTIMATE_INPUT_USD_PER_1M,
|
||||
costEstimateOutputUsdPer1M:
|
||||
Number.isFinite(outputUsdPer1M) && outputUsdPer1M >= 0
|
||||
? outputUsdPer1M
|
||||
: DEFAULT_ESTIMATE_OUTPUT_USD_PER_1M,
|
||||
};
|
||||
}
|
||||
|
||||
function cloneConfig(config = null, env = process.env) {
|
||||
return structuredClone?.(config ?? defaultConfigShape(env))
|
||||
?? JSON.parse(JSON.stringify(config ?? defaultConfigShape(env)));
|
||||
}
|
||||
|
||||
function parseJsonLike(value, fallback) {
|
||||
if (value == null || value === '') return fallback;
|
||||
if (typeof value === 'string') {
|
||||
try {
|
||||
return JSON.parse(value);
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
if (typeof value === 'object') return value;
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function envLocked(env = process.env) {
|
||||
return String(env.H5_BILLING_CONFIG_SOURCE ?? '').trim().toLowerCase() === 'env';
|
||||
}
|
||||
|
||||
function mergePatch(currentConfig, patch = {}, env = process.env) {
|
||||
const base = defaultConfigShape(env);
|
||||
const next = cloneConfig({ ...base, ...currentConfig }, env);
|
||||
const raw = patch?.config && typeof patch.config === 'object' ? patch.config : patch;
|
||||
|
||||
if ('useBackendCost' in raw) next.useBackendCost = normalizeBoolean(raw.useBackendCost, next.useBackendCost);
|
||||
if ('usdCnyRate' in raw) next.usdCnyRate = normalizePositiveNumber(raw.usdCnyRate, next.usdCnyRate);
|
||||
if ('marginMultiplier' in raw) {
|
||||
next.marginMultiplier = normalizePositiveNumber(raw.marginMultiplier, next.marginMultiplier);
|
||||
}
|
||||
if ('inputCentsPer1k' in raw) {
|
||||
next.inputCentsPer1k = normalizeNonNegativeNumber(raw.inputCentsPer1k, next.inputCentsPer1k);
|
||||
}
|
||||
if ('outputCentsPer1k' in raw) {
|
||||
next.outputCentsPer1k = normalizeNonNegativeNumber(raw.outputCentsPer1k, next.outputCentsPer1k);
|
||||
}
|
||||
if ('minBillCents' in raw) {
|
||||
next.minBillCents = normalizePositiveNumber(raw.minBillCents, next.minBillCents);
|
||||
}
|
||||
if ('costEstimateFromTokens' in raw) {
|
||||
next.costEstimateFromTokens = normalizeBoolean(raw.costEstimateFromTokens, next.costEstimateFromTokens);
|
||||
}
|
||||
if ('costEstimateInputUsdPer1M' in raw) {
|
||||
next.costEstimateInputUsdPer1M = normalizeNonNegativeNumber(
|
||||
raw.costEstimateInputUsdPer1M,
|
||||
next.costEstimateInputUsdPer1M,
|
||||
);
|
||||
}
|
||||
if ('costEstimateOutputUsdPer1M' in raw) {
|
||||
next.costEstimateOutputUsdPer1M = normalizeNonNegativeNumber(
|
||||
raw.costEstimateOutputUsdPer1M,
|
||||
next.costEstimateOutputUsdPer1M,
|
||||
);
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export function toComputeBillingConfig(config) {
|
||||
return {
|
||||
useBackendCost: Boolean(config?.useBackendCost),
|
||||
usdCnyRate: Number(config?.usdCnyRate ?? 7.2),
|
||||
marginMultiplier: Number(config?.marginMultiplier ?? 1),
|
||||
inputCentsPer1k: Number(config?.inputCentsPer1k ?? 2),
|
||||
outputCentsPer1k: Number(config?.outputCentsPer1k ?? 6),
|
||||
minBillCents: Number(config?.minBillCents ?? 1),
|
||||
};
|
||||
}
|
||||
|
||||
export function toCostEstimateConfig(config) {
|
||||
const useBackendCost = Boolean(config?.useBackendCost);
|
||||
const enabled = useBackendCost && config?.costEstimateFromTokens !== false;
|
||||
return {
|
||||
enabled,
|
||||
inputUsdPer1M: Number(config?.costEstimateInputUsdPer1M ?? 0.27),
|
||||
outputUsdPer1M: Number(config?.costEstimateOutputUsdPer1M ?? 1.1),
|
||||
};
|
||||
}
|
||||
|
||||
function envLooksCustomized(env = process.env) {
|
||||
return [
|
||||
'H5_USE_BACKEND_COST',
|
||||
'H5_USD_CNY_RATE',
|
||||
'H5_MARGIN_MULTIPLIER',
|
||||
'H5_BILL_INPUT_CENTS_PER_1K',
|
||||
'H5_BILL_OUTPUT_CENTS_PER_1K',
|
||||
'H5_MIN_BILL_CENTS',
|
||||
'H5_COST_ESTIMATE_FROM_TOKENS',
|
||||
'H5_COST_ESTIMATE_INPUT_USD_PER_1M',
|
||||
'H5_COST_ESTIMATE_OUTPUT_USD_PER_1M',
|
||||
].some((key) => String(env[key] ?? '').trim() !== '');
|
||||
}
|
||||
|
||||
async function ensureConfigTable(pool) {
|
||||
await pool.query(`
|
||||
CREATE TABLE IF NOT EXISTS ${CONFIG_TABLE} (
|
||||
config_scope VARCHAR(32) PRIMARY KEY,
|
||||
config_json JSON NOT NULL,
|
||||
updated_by CHAR(36) NULL,
|
||||
updated_at BIGINT NOT NULL
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||
`);
|
||||
}
|
||||
|
||||
async function loadStoredState(pool) {
|
||||
await ensureConfigTable(pool);
|
||||
const [rows] = await pool.query(
|
||||
`SELECT config_json, updated_by, updated_at
|
||||
FROM ${CONFIG_TABLE}
|
||||
WHERE config_scope = ?
|
||||
LIMIT 1`,
|
||||
[CONFIG_SCOPE],
|
||||
);
|
||||
const row = rows[0];
|
||||
if (!row) return null;
|
||||
return {
|
||||
config: mergePatch(defaultConfigShape(), parseJsonLike(row.config_json, {})),
|
||||
updatedAt: Number(row.updated_at ?? 0) || null,
|
||||
updatedBy: row.updated_by ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export function createBillingAdminConfigService(pool, { env = process.env, cacheTtlMs = CACHE_TTL_MS } = {}) {
|
||||
let cache = null;
|
||||
|
||||
function clearCache() {
|
||||
cache = null;
|
||||
}
|
||||
|
||||
async function loadEffectiveConfig({ bypassCache = false } = {}) {
|
||||
const now = Date.now();
|
||||
if (!bypassCache && cache && now - cache.loadedAt < cacheTtlMs) {
|
||||
return cache.state;
|
||||
}
|
||||
|
||||
if (envLocked(env)) {
|
||||
const state = {
|
||||
config: defaultConfigShape(env),
|
||||
updatedAt: null,
|
||||
updatedBy: null,
|
||||
source: SOURCE_ENV_OVERRIDE,
|
||||
};
|
||||
cache = { loadedAt: now, state };
|
||||
return state;
|
||||
}
|
||||
|
||||
const stored = await loadStoredState(pool);
|
||||
let state;
|
||||
if (stored) {
|
||||
state = {
|
||||
config: cloneConfig(stored.config, env),
|
||||
updatedAt: stored.updatedAt,
|
||||
updatedBy: stored.updatedBy,
|
||||
source: SOURCE_ADMIN_DB,
|
||||
};
|
||||
} else if (envLooksCustomized(env)) {
|
||||
state = {
|
||||
config: defaultConfigShape(env),
|
||||
updatedAt: null,
|
||||
updatedBy: null,
|
||||
source: SOURCE_ENV,
|
||||
};
|
||||
} else {
|
||||
state = {
|
||||
config: defaultConfigShape(env),
|
||||
updatedAt: null,
|
||||
updatedBy: null,
|
||||
source: SOURCE_DEFAULT,
|
||||
};
|
||||
}
|
||||
cache = { loadedAt: now, state };
|
||||
return state;
|
||||
}
|
||||
|
||||
return {
|
||||
async ensureSchema() {
|
||||
await ensureConfigTable(pool);
|
||||
},
|
||||
|
||||
clearCache,
|
||||
|
||||
async getAdminConfig() {
|
||||
const state = await loadEffectiveConfig({ bypassCache: true });
|
||||
return {
|
||||
config: state.config,
|
||||
updatedAt: state.updatedAt,
|
||||
updatedBy: state.updatedBy,
|
||||
source: state.source,
|
||||
envOverrideActive: state.source === SOURCE_ENV_OVERRIDE,
|
||||
formula: '最终扣费 = 上游成本(USD) × 汇率 × 毛利倍数(成本模式);无上游成本时回退 Token 单价',
|
||||
};
|
||||
},
|
||||
|
||||
async updateAdminConfig(patch = {}, { updatedBy = null } = {}) {
|
||||
if (envLocked(env)) {
|
||||
throw Object.assign(new Error('H5_BILLING_CONFIG_SOURCE=env 时不允许通过后台修改'), {
|
||||
code: 'BILLING_CONFIG_ENV_LOCKED',
|
||||
});
|
||||
}
|
||||
const stored = await loadStoredState(pool);
|
||||
const base = stored?.config ?? defaultConfigShape(env);
|
||||
const nextConfig = mergePatch(base, patch, env);
|
||||
await ensureConfigTable(pool);
|
||||
const now = Date.now();
|
||||
await pool.query(
|
||||
`INSERT INTO ${CONFIG_TABLE}
|
||||
(config_scope, config_json, updated_by, updated_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
ON DUPLICATE KEY UPDATE
|
||||
config_json = VALUES(config_json),
|
||||
updated_by = VALUES(updated_by),
|
||||
updated_at = VALUES(updated_at)`,
|
||||
[CONFIG_SCOPE, JSON.stringify(nextConfig), updatedBy, now],
|
||||
);
|
||||
clearCache();
|
||||
return this.getAdminConfig();
|
||||
},
|
||||
|
||||
async getRuntimeState() {
|
||||
const state = await loadEffectiveConfig();
|
||||
return {
|
||||
source: state.source,
|
||||
updatedAt: state.updatedAt,
|
||||
updatedBy: state.updatedBy,
|
||||
config: state.config,
|
||||
compute: toComputeBillingConfig(state.config),
|
||||
estimate: toCostEstimateConfig(state.config),
|
||||
envOverrideActive: state.source === SOURCE_ENV_OVERRIDE,
|
||||
};
|
||||
},
|
||||
|
||||
async getEffectiveBillingConfig() {
|
||||
const state = await loadEffectiveConfig();
|
||||
return toComputeBillingConfig(state.config);
|
||||
},
|
||||
|
||||
async getEffectiveCostEstimateConfig() {
|
||||
const state = await loadEffectiveConfig();
|
||||
return toCostEstimateConfig(state.config);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export const billingAdminConfigInternals = {
|
||||
CONFIG_SCOPE,
|
||||
CONFIG_TABLE,
|
||||
defaultConfigShape,
|
||||
mergePatch,
|
||||
toComputeBillingConfig,
|
||||
toCostEstimateConfig,
|
||||
envLocked,
|
||||
};
|
||||
@@ -0,0 +1,131 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
billingAdminConfigInternals,
|
||||
createBillingAdminConfigService,
|
||||
toComputeBillingConfig,
|
||||
toCostEstimateConfig,
|
||||
} from './billing-admin-config.mjs';
|
||||
|
||||
function createMemoryPool(initialRows = []) {
|
||||
const rows = new Map(
|
||||
initialRows.map((row) => [row.config_scope, { ...row }]),
|
||||
);
|
||||
return {
|
||||
async query(sql, params = []) {
|
||||
if (/CREATE TABLE/i.test(sql)) return [{}, undefined];
|
||||
if (/SELECT/i.test(sql)) {
|
||||
const scope = params[0];
|
||||
const row = rows.get(scope);
|
||||
return [row ? [row] : [], undefined];
|
||||
}
|
||||
if (/INSERT INTO/i.test(sql)) {
|
||||
const [scope, configJson, updatedBy, updatedAt] = params;
|
||||
rows.set(scope, {
|
||||
config_scope: scope,
|
||||
config_json: configJson,
|
||||
updated_by: updatedBy,
|
||||
updated_at: updatedAt,
|
||||
});
|
||||
return [{ affectedRows: 1 }, undefined];
|
||||
}
|
||||
return [{}, undefined];
|
||||
},
|
||||
_rows: rows,
|
||||
};
|
||||
}
|
||||
|
||||
test('mergePatch validates margin and FX', () => {
|
||||
const next = billingAdminConfigInternals.mergePatch(
|
||||
billingAdminConfigInternals.defaultConfigShape({}),
|
||||
{
|
||||
marginMultiplier: 1.5,
|
||||
usdCnyRate: 7.1,
|
||||
useBackendCost: true,
|
||||
},
|
||||
{},
|
||||
);
|
||||
assert.equal(next.marginMultiplier, 1.5);
|
||||
assert.equal(next.usdCnyRate, 7.1);
|
||||
assert.equal(next.useBackendCost, true);
|
||||
});
|
||||
|
||||
test('toComputeBillingConfig maps admin shape', () => {
|
||||
const compute = toComputeBillingConfig({
|
||||
useBackendCost: true,
|
||||
usdCnyRate: 7.2,
|
||||
marginMultiplier: 1.2,
|
||||
inputCentsPer1k: 2,
|
||||
outputCentsPer1k: 6,
|
||||
minBillCents: 1,
|
||||
});
|
||||
assert.deepEqual(compute, {
|
||||
useBackendCost: true,
|
||||
usdCnyRate: 7.2,
|
||||
marginMultiplier: 1.2,
|
||||
inputCentsPer1k: 2,
|
||||
outputCentsPer1k: 6,
|
||||
minBillCents: 1,
|
||||
});
|
||||
});
|
||||
|
||||
test('toCostEstimateConfig disables when cost mode off', () => {
|
||||
const estimate = toCostEstimateConfig({
|
||||
useBackendCost: false,
|
||||
costEstimateFromTokens: true,
|
||||
costEstimateInputUsdPer1M: 0.27,
|
||||
costEstimateOutputUsdPer1M: 1.1,
|
||||
});
|
||||
assert.equal(estimate.enabled, false);
|
||||
});
|
||||
|
||||
test('admin-db config wins over env for effective billing', async () => {
|
||||
const pool = createMemoryPool();
|
||||
const env = {
|
||||
H5_USE_BACKEND_COST: '1',
|
||||
H5_USD_CNY_RATE: '7.2',
|
||||
H5_MARGIN_MULTIPLIER: '1.2',
|
||||
};
|
||||
const service = createBillingAdminConfigService(pool, { env, cacheTtlMs: 0 });
|
||||
await service.updateAdminConfig(
|
||||
{ marginMultiplier: 2, usdCnyRate: 7.5, useBackendCost: true },
|
||||
{ updatedBy: 'admin-1' },
|
||||
);
|
||||
const effective = await service.getEffectiveBillingConfig();
|
||||
assert.equal(effective.marginMultiplier, 2);
|
||||
assert.equal(effective.usdCnyRate, 7.5);
|
||||
const admin = await service.getAdminConfig();
|
||||
assert.equal(admin.source, 'admin-db');
|
||||
assert.equal(admin.updatedBy, 'admin-1');
|
||||
});
|
||||
|
||||
test('H5_BILLING_CONFIG_SOURCE=env locks admin writes', async () => {
|
||||
const pool = createMemoryPool();
|
||||
const service = createBillingAdminConfigService(pool, {
|
||||
env: { H5_BILLING_CONFIG_SOURCE: 'env', H5_MARGIN_MULTIPLIER: '1.2' },
|
||||
cacheTtlMs: 0,
|
||||
});
|
||||
await assert.rejects(
|
||||
() => service.updateAdminConfig({ marginMultiplier: 9 }),
|
||||
/H5_BILLING_CONFIG_SOURCE=env/,
|
||||
);
|
||||
const admin = await service.getAdminConfig();
|
||||
assert.equal(admin.source, 'env-override');
|
||||
assert.equal(admin.config.marginMultiplier, 1.2);
|
||||
});
|
||||
|
||||
test('env fallback used when no admin row', async () => {
|
||||
const pool = createMemoryPool();
|
||||
const service = createBillingAdminConfigService(pool, {
|
||||
env: {
|
||||
H5_USE_BACKEND_COST: '1',
|
||||
H5_MARGIN_MULTIPLIER: '1.2',
|
||||
H5_USD_CNY_RATE: '7.2',
|
||||
},
|
||||
cacheTtlMs: 0,
|
||||
});
|
||||
const admin = await service.getAdminConfig();
|
||||
assert.equal(admin.source, 'env');
|
||||
assert.equal(admin.config.marginMultiplier, 1.2);
|
||||
assert.equal(admin.config.useBackendCost, true);
|
||||
});
|
||||
+17
-4
@@ -35,7 +35,7 @@ export function estimateAccumulatedCostUsd(tokenStateRaw, estimateConfig = loadC
|
||||
|
||||
export function enrichTokenStateForBilling(
|
||||
tokenStateRaw,
|
||||
{ sessionCost = null } = {},
|
||||
{ sessionCost = null, estimateConfig = null } = {},
|
||||
env = process.env,
|
||||
) {
|
||||
const state = normalizeTokenState(tokenStateRaw);
|
||||
@@ -49,7 +49,10 @@ export function enrichTokenStateForBilling(
|
||||
return state;
|
||||
}
|
||||
|
||||
const estimatedUsd = estimateAccumulatedCostUsd(state, loadCostEstimateConfig(env));
|
||||
const estimatedUsd = estimateAccumulatedCostUsd(
|
||||
state,
|
||||
estimateConfig ?? loadCostEstimateConfig(env),
|
||||
);
|
||||
if (estimatedUsd != null) {
|
||||
return { ...state, accumulatedCost: estimatedUsd };
|
||||
}
|
||||
@@ -86,7 +89,13 @@ async function resolveSessionCostPayload(sessionId, fetchSession, fetchSessionCo
|
||||
|
||||
export async function resolveBillingTokenState(
|
||||
tokenStateRaw,
|
||||
{ sessionId = null, fetchSession = null, fetchSessionCostFromPg = null } = {},
|
||||
{
|
||||
sessionId = null,
|
||||
fetchSession = null,
|
||||
fetchSessionCostFromPg = null,
|
||||
estimateConfig = null,
|
||||
loadEstimateConfig = null,
|
||||
} = {},
|
||||
env = process.env,
|
||||
) {
|
||||
const state = normalizeTokenState(tokenStateRaw);
|
||||
@@ -96,5 +105,9 @@ export async function resolveBillingTokenState(
|
||||
fetchSessionCostFromPg,
|
||||
env,
|
||||
);
|
||||
return enrichTokenStateForBilling(state, { sessionCost }, env);
|
||||
const resolvedEstimateConfig =
|
||||
estimateConfig
|
||||
?? (typeof loadEstimateConfig === 'function' ? await loadEstimateConfig() : null)
|
||||
?? loadCostEstimateConfig(env);
|
||||
return enrichTokenStateForBilling(state, { sessionCost, estimateConfig: resolvedEstimateConfig }, env);
|
||||
}
|
||||
|
||||
+8
-7
@@ -1,16 +1,17 @@
|
||||
export function loadBillingConfig() {
|
||||
export function loadBillingConfig(env = process.env) {
|
||||
// 默认按人民币分(CNY cents)计费;仅当 H5_USE_BACKEND_COST=1 时才用上游 USD 成本换算。
|
||||
const useBackendCost = process.env.H5_USE_BACKEND_COST === '1';
|
||||
const useBackendCost = env.H5_USE_BACKEND_COST === '1';
|
||||
// 成本模式下的毛利倍数:最终扣费 = 上游真实成本(USD) × 汇率 × marginMultiplier。
|
||||
// 默认 1(按成本价卖,零毛利)——启用 useBackendCost 时务必显式设置目标倍数。
|
||||
const marginMultiplier = Number(process.env.H5_MARGIN_MULTIPLIER ?? 1);
|
||||
// 生产可通过 memind_adm「计费中心 → 计量公式」覆盖(见 billing-admin-config.mjs)。
|
||||
const marginMultiplier = Number(env.H5_MARGIN_MULTIPLIER ?? 1);
|
||||
return {
|
||||
useBackendCost,
|
||||
usdCnyRate: Number(process.env.H5_USD_CNY_RATE ?? 7.2),
|
||||
usdCnyRate: Number(env.H5_USD_CNY_RATE ?? 7.2),
|
||||
marginMultiplier: Number.isFinite(marginMultiplier) && marginMultiplier > 0 ? marginMultiplier : 1,
|
||||
inputCentsPer1k: Number(process.env.H5_BILL_INPUT_CENTS_PER_1K ?? 2),
|
||||
outputCentsPer1k: Number(process.env.H5_BILL_OUTPUT_CENTS_PER_1K ?? 6),
|
||||
minBillCents: Number(process.env.H5_MIN_BILL_CENTS ?? 1),
|
||||
inputCentsPer1k: Number(env.H5_BILL_INPUT_CENTS_PER_1K ?? 2),
|
||||
outputCentsPer1k: Number(env.H5_BILL_OUTPUT_CENTS_PER_1K ?? 6),
|
||||
minBillCents: Number(env.H5_MIN_BILL_CENTS ?? 1),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -194,6 +194,12 @@ export async function migrateSchema(pool) {
|
||||
`ALTER TABLE h5_usage_records ADD UNIQUE KEY uniq_h5_usage_request_id (request_id)`,
|
||||
);
|
||||
}
|
||||
if (!(await columnExists(pool, 'h5_usage_records', 'billing_source'))) {
|
||||
await pool.query(
|
||||
`ALTER TABLE h5_usage_records
|
||||
ADD COLUMN billing_source VARCHAR(16) NOT NULL DEFAULT 'wallet' AFTER balance_after_cents`,
|
||||
);
|
||||
}
|
||||
|
||||
const assetForeignKeys = [
|
||||
{
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
- 仅当上游回传 `accumulatedCost` 时生效;缺失则**回退**原 flat token 路径,不破坏现有计费。
|
||||
- 若 goose Finish / session 均未带 cost,且 `H5_COST_ESTIMATE_FROM_TOKENS=1`(成本模式默认开启),Portal 会按 DeepSeek 中继粗估价(`billing-token-state.mjs`)补齐 `accumulatedCost`,再走 `× margin`。
|
||||
- 生产启用:`.env` 设 `H5_USE_BACKEND_COST=1` + `H5_MARGIN_MULTIPLIER=<目标毛利>`。
|
||||
- 也可在 memind_adm「计费中心 → 计量公式」修改同一套参数(`h5_billing_admin_config`,优先级高于 env;`H5_BILLING_CONFIG_SOURCE=env` 可锁定)。
|
||||
|
||||
> ⚠️ 上线前需确认:一帧真实 SSE 的 `token_state` 是否带 `accumulated_cost`(goose `sessions.db` 有该列,但要确认 SSE Finish 事件也序列化了它)。确认前 multiplier 改动是安全的(无 cost 即回退)。
|
||||
|
||||
|
||||
+1
-1
@@ -9,7 +9,7 @@
|
||||
<meta name="mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="theme-color" content="#0f1419" />
|
||||
<title>TKMind</title>
|
||||
<title>Memind</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
@@ -511,6 +511,7 @@ CREATE TABLE IF NOT EXISTS h5_usage_records (
|
||||
output_tokens INT NOT NULL DEFAULT 0,
|
||||
cost_cents BIGINT NOT NULL,
|
||||
balance_after_cents BIGINT NOT NULL,
|
||||
billing_source VARCHAR(16) NOT NULL DEFAULT 'wallet',
|
||||
created_at BIGINT NOT NULL,
|
||||
UNIQUE KEY uniq_h5_usage_request_id (request_id),
|
||||
KEY idx_h5_usage_user_time (user_id, created_at),
|
||||
|
||||
@@ -412,6 +412,8 @@ async function bootstrapUserAuth() {
|
||||
});
|
||||
subscriptionService =
|
||||
authServices.subscriptionService;
|
||||
const billingConfigService =
|
||||
authServices.billingConfigService;
|
||||
userAuth = authServices.userAuth;
|
||||
sessionAccess = authServices.sessionAccess;
|
||||
wechatPayClient = authServices.wechatPayClient;
|
||||
@@ -501,6 +503,7 @@ async function bootstrapUserAuth() {
|
||||
sessionStreamStore,
|
||||
llmProviderService,
|
||||
subscriptionService,
|
||||
billingConfigService,
|
||||
sessionSnapshotService,
|
||||
conversationMemoryService,
|
||||
memoryV2,
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { createBillingAdminConfigService } from '../billing-admin-config.mjs';
|
||||
import { createRechargeService } from '../billing-recharge.mjs';
|
||||
import {
|
||||
createPlanCatalogService,
|
||||
@@ -53,6 +54,7 @@ export async function bootstrapPortalAuthServices({
|
||||
loadWechatOAuthConfigFn = loadWechatOAuthConfig,
|
||||
createWechatOAuthServiceFn = createWechatOAuthService,
|
||||
createRechargeServiceFn = createRechargeService,
|
||||
createBillingAdminConfigServiceFn = createBillingAdminConfigService,
|
||||
} = {}) {
|
||||
if (
|
||||
!pool ||
|
||||
@@ -77,6 +79,10 @@ export async function bootstrapPortalAuthServices({
|
||||
subscriptionService._planCatalogService =
|
||||
planCatalogService;
|
||||
|
||||
const billingConfigService =
|
||||
createBillingAdminConfigServiceFn(pool, { env });
|
||||
await billingConfigService.ensureSchema();
|
||||
|
||||
const userAuth = createUserAuthFn(pool, {
|
||||
usersRoot,
|
||||
h5Root,
|
||||
@@ -84,6 +90,7 @@ export async function bootstrapPortalAuthServices({
|
||||
env.H5_SIGNUP_BALANCE_CENTS ?? 500,
|
||||
),
|
||||
subscriptionService,
|
||||
billingConfigService,
|
||||
getMindSearchConfig: () =>
|
||||
mindSearchConfigService.getEffectiveConfig(),
|
||||
provisionUserDataSpace: async ({
|
||||
@@ -158,6 +165,7 @@ export async function bootstrapPortalAuthServices({
|
||||
return {
|
||||
planCatalogService,
|
||||
subscriptionService,
|
||||
billingConfigService,
|
||||
userAuth,
|
||||
sessionAccess,
|
||||
routerDecisionMode,
|
||||
|
||||
@@ -65,6 +65,20 @@ function createSetup(overrides = {}) {
|
||||
subscriptionOptions = receivedOptions;
|
||||
return { id: 'subscription' };
|
||||
},
|
||||
createBillingAdminConfigServiceFn(receivedPool, receivedOptions) {
|
||||
assert.equal(receivedPool, pool);
|
||||
assert.equal(receivedOptions?.env, options.env);
|
||||
calls.push(['billing-config']);
|
||||
return {
|
||||
id: 'billing-config',
|
||||
async ensureSchema() {
|
||||
calls.push(['billing-config-schema']);
|
||||
},
|
||||
async getEffectiveBillingConfig() {
|
||||
return { marginMultiplier: 1.2 };
|
||||
},
|
||||
};
|
||||
},
|
||||
createUserAuthFn(receivedPool, receivedOptions) {
|
||||
assert.equal(receivedPool, pool);
|
||||
calls.push(['user-auth']);
|
||||
@@ -161,11 +175,13 @@ test('preserves subscription, auth, and user-space wiring', async () => {
|
||||
let captured = setup.getCaptured();
|
||||
|
||||
assert.deepEqual(
|
||||
setup.calls.slice(0, 4).map(([name]) => name),
|
||||
setup.calls.slice(0, 6).map(([name]) => name),
|
||||
[
|
||||
'plan-schema',
|
||||
'plan-service',
|
||||
'subscription-service',
|
||||
'billing-config',
|
||||
'billing-config-schema',
|
||||
'user-auth',
|
||||
],
|
||||
);
|
||||
@@ -173,6 +189,11 @@ test('preserves subscription, auth, and user-space wiring', async () => {
|
||||
result.subscriptionService._planCatalogService,
|
||||
setup.planCatalogService,
|
||||
);
|
||||
assert.equal(result.billingConfigService?.id, 'billing-config');
|
||||
assert.equal(
|
||||
captured.userAuthOptions.billingConfigService?.id,
|
||||
'billing-config',
|
||||
);
|
||||
assert.deepEqual(
|
||||
await captured.subscriptionOptions.getPlanAsync(
|
||||
'pro',
|
||||
|
||||
@@ -129,6 +129,7 @@ export function bootstrapPortalGatewayServices({
|
||||
sessionStreamStore,
|
||||
llmProviderService,
|
||||
subscriptionService,
|
||||
billingConfigService = null,
|
||||
sessionSnapshotService,
|
||||
conversationMemoryService,
|
||||
memoryV2,
|
||||
@@ -176,6 +177,7 @@ export function bootstrapPortalGatewayServices({
|
||||
sessionStreamStore,
|
||||
llmProviderService,
|
||||
subscriptionService,
|
||||
billingConfigService,
|
||||
sessionSnapshotService,
|
||||
conversationMemoryService,
|
||||
memoryV2,
|
||||
|
||||
@@ -86,9 +86,6 @@ export function extensionsNeedingRefresh(currentExtensions, desiredExtensions) {
|
||||
if (!name) continue;
|
||||
const exists = current.some((ext) => extensionName(ext) === name);
|
||||
if (!exists) {
|
||||
// goosed may omit active stdio MCP extensions from the session listing
|
||||
// even though /agent/start already loaded them; do not hot-add stdio.
|
||||
if (String(config?.type ?? '') === 'stdio') continue;
|
||||
toAdd.push(config);
|
||||
}
|
||||
}
|
||||
@@ -98,7 +95,7 @@ export function extensionsNeedingRefresh(currentExtensions, desiredExtensions) {
|
||||
|
||||
function stdioListingOmissionAllowed(currentExt, desiredConfig) {
|
||||
if (String(desiredConfig?.type ?? '') !== 'stdio') return false;
|
||||
if (!currentExt) return true;
|
||||
if (!currentExt) return false;
|
||||
const currentExec = extensionExecutionConfig(currentExt);
|
||||
const desiredExec = extensionExecutionConfig(desiredConfig);
|
||||
return currentExec.type === 'stdio'
|
||||
|
||||
+79
-11
@@ -122,22 +122,24 @@ test('extensionsNeedingRefresh adds missing extensions', () => {
|
||||
assert.equal(toAdd[0].name, 'summon');
|
||||
});
|
||||
|
||||
test('extensionsNeedingRefresh does not hot-add missing stdio extensions', () => {
|
||||
test('extensionsNeedingRefresh re-adds missing stdio extensions after quiesce', () => {
|
||||
const desiredSandbox = {
|
||||
type: 'stdio',
|
||||
name: 'sandbox-fs',
|
||||
cmd: '/usr/local/bin/node',
|
||||
args: ['/opt/portal/mindspace-sandbox-mcp.mjs', '/tmp/user-1'],
|
||||
available_tools: ['read_file', 'generate_image'],
|
||||
};
|
||||
const { toRemove, toAdd } = extensionsNeedingRefresh(
|
||||
[{ name: 'developer', available_tools: ['read_image'] }],
|
||||
[
|
||||
{ name: 'developer', available_tools: ['read_image'] },
|
||||
{
|
||||
type: 'stdio',
|
||||
name: 'sandbox-fs',
|
||||
cmd: '/usr/local/bin/node',
|
||||
args: ['/opt/portal/mindspace-sandbox-mcp.mjs', '/tmp/user-1'],
|
||||
available_tools: ['read_file'],
|
||||
},
|
||||
desiredSandbox,
|
||||
],
|
||||
);
|
||||
assert.deepEqual(toRemove, []);
|
||||
assert.deepEqual(toAdd, []);
|
||||
assert.equal(toAdd.length, 1);
|
||||
assert.equal(toAdd[0].name, 'sandbox-fs');
|
||||
});
|
||||
|
||||
test('extensionPolicyViolations reports unexpected, duplicate, and mismatched extensions', () => {
|
||||
@@ -161,7 +163,7 @@ test('extensionPolicyViolations reports unexpected, duplicate, and mismatched ex
|
||||
);
|
||||
});
|
||||
|
||||
test('extensionPolicyViolations ignores stdio extensions omitted from goosed listing', () => {
|
||||
test('extensionPolicyViolations flags stdio extensions missing from goosed listing', () => {
|
||||
assert.deepEqual(
|
||||
extensionPolicyViolations(
|
||||
[{ name: 'developer', available_tools: ['read_image'] }],
|
||||
@@ -186,7 +188,7 @@ test('extensionPolicyViolations ignores stdio extensions omitted from goosed lis
|
||||
{
|
||||
unexpected: [],
|
||||
duplicate: [],
|
||||
missingOrMismatched: [],
|
||||
missingOrMismatched: ['sandbox-fs', 'tkmind-search'],
|
||||
},
|
||||
);
|
||||
});
|
||||
@@ -334,6 +336,72 @@ test('reconcileAgentSession restarts after adding missing extensions', async ()
|
||||
]);
|
||||
});
|
||||
|
||||
test('reconcileAgentSession restarts after re-adding quiesced stdio extensions', async () => {
|
||||
const calls = [];
|
||||
let extensionReads = 0;
|
||||
const desiredSandbox = {
|
||||
type: 'stdio',
|
||||
name: 'sandbox-fs',
|
||||
cmd: '/usr/local/bin/node',
|
||||
args: ['/opt/portal/mindspace-sandbox-mcp.mjs', '/tmp/user-1'],
|
||||
available_tools: ['write_file', 'generate_image'],
|
||||
};
|
||||
const apiFetch = async (pathname) => {
|
||||
calls.push(pathname);
|
||||
if (pathname === '/sessions/session-1') {
|
||||
return {
|
||||
ok: true,
|
||||
text: async () => JSON.stringify({ working_dir: '/valid/workspace' }),
|
||||
};
|
||||
}
|
||||
if (pathname === '/sessions/session-1/extensions') {
|
||||
extensionReads += 1;
|
||||
return {
|
||||
ok: true,
|
||||
text: async () =>
|
||||
JSON.stringify({
|
||||
extensions:
|
||||
extensionReads === 1
|
||||
? [{ name: 'developer', available_tools: ['read_image'] }]
|
||||
: [desiredSandbox, { name: 'developer', available_tools: ['read_image'] }],
|
||||
}),
|
||||
};
|
||||
}
|
||||
if (
|
||||
pathname === '/agent/add_extension'
|
||||
|| pathname === '/agent/restart'
|
||||
) {
|
||||
return {
|
||||
ok: true,
|
||||
text: async () => JSON.stringify({ ok: true }),
|
||||
};
|
||||
}
|
||||
const harness = harnessMemoryResponse(pathname);
|
||||
if (harness) return harness;
|
||||
throw new Error(`unexpected path: ${pathname}`);
|
||||
};
|
||||
|
||||
await reconcileAgentSession(apiFetch, 'session-1', {
|
||||
workingDir: '/valid/workspace',
|
||||
sessionPolicy: {
|
||||
extensionOverrides: [
|
||||
{ name: 'developer', available_tools: ['read_image'] },
|
||||
desiredSandbox,
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
'/sessions/session-1',
|
||||
'/sessions/session-1/extensions',
|
||||
'/agent/add_extension',
|
||||
'/agent/restart',
|
||||
'/sessions/session-1/extensions',
|
||||
'/agent/harness_remember',
|
||||
'/agent/harness_bootstrap',
|
||||
]);
|
||||
});
|
||||
|
||||
test('reconcileAgentSession fails closed when restart does not apply the requested policy', async () => {
|
||||
const apiFetch = async (pathname) => {
|
||||
if (pathname === '/sessions/session-1') {
|
||||
|
||||
@@ -2,6 +2,9 @@ function extensionName(config) {
|
||||
return String(config?.name ?? '').trim();
|
||||
}
|
||||
|
||||
/** Stdio MCP extensions that must survive agent-run quiesce (page write + image gen). */
|
||||
export const PRESERVED_STDIO_EXTENSIONS = new Set(['sandbox-fs']);
|
||||
|
||||
async function readJson(response) {
|
||||
const text = await response.text();
|
||||
if (!response.ok) {
|
||||
@@ -52,6 +55,7 @@ export async function cancelSessionActiveRequest(apiFetch, sessionId, requestId)
|
||||
/**
|
||||
* Stop per-session stdio MCP children while preserving the Goose conversation.
|
||||
* Session reconciliation restores the required extensions before the next turn.
|
||||
* Critical page tools (sandbox-fs) stay attached so the next turn is not tool-less.
|
||||
*/
|
||||
export async function quiesceSessionStdioExtensions(apiFetch, sessionId) {
|
||||
const normalizedSessionId = String(sessionId ?? '').trim();
|
||||
@@ -60,7 +64,9 @@ export async function quiesceSessionStdioExtensions(apiFetch, sessionId) {
|
||||
const payload = await readJson(
|
||||
await apiFetch(`/sessions/${encodeURIComponent(normalizedSessionId)}/extensions`),
|
||||
);
|
||||
const names = sessionStdioExtensionNames(payload?.extensions);
|
||||
const names = sessionStdioExtensionNames(payload?.extensions).filter(
|
||||
(name) => !PRESERVED_STDIO_EXTENSIONS.has(name),
|
||||
);
|
||||
const removed = [];
|
||||
for (const name of names) {
|
||||
await readJson(
|
||||
|
||||
@@ -2,6 +2,7 @@ import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
cancelSessionActiveRequest,
|
||||
PRESERVED_STDIO_EXTENSIONS,
|
||||
quiesceSessionStdioExtensions,
|
||||
sessionStdioExtensionNames,
|
||||
} from './session-runtime-lifecycle.mjs';
|
||||
@@ -82,7 +83,7 @@ test('quiesceSessionStdioExtensions removes stdio children without deleting sess
|
||||
const result = await quiesceSessionStdioExtensions(apiFetch, 'session-1');
|
||||
|
||||
assert.deepEqual(result, {
|
||||
removed: ['sandbox-fs', 'tkmind-search'],
|
||||
removed: ['tkmind-search'],
|
||||
skipped: false,
|
||||
});
|
||||
assert.deepEqual(
|
||||
@@ -90,23 +91,27 @@ test('quiesceSessionStdioExtensions removes stdio children without deleting sess
|
||||
[
|
||||
'/sessions/session-1/extensions',
|
||||
'/agent/remove_extension',
|
||||
'/agent/remove_extension',
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
calls.slice(1).map(({ init }) => JSON.parse(init.body)),
|
||||
[
|
||||
{ session_id: 'session-1', name: 'sandbox-fs' },
|
||||
{ session_id: 'session-1', name: 'tkmind-search' },
|
||||
],
|
||||
);
|
||||
assert.equal(PRESERVED_STDIO_EXTENSIONS.has('sandbox-fs'), true);
|
||||
assert.equal(calls.some(({ pathname }) => pathname.includes('delete')), false);
|
||||
});
|
||||
|
||||
test('quiesceSessionStdioExtensions fails when upstream removal is not acknowledged', async () => {
|
||||
const apiFetch = async (pathname) => {
|
||||
if (pathname.endsWith('/extensions')) {
|
||||
return jsonResponse({ extensions: [{ name: 'sandbox-fs', type: 'stdio' }] });
|
||||
return jsonResponse({
|
||||
extensions: [
|
||||
{ name: 'sandbox-fs', type: 'stdio' },
|
||||
{ name: 'tkmind-search', type: 'stdio' },
|
||||
],
|
||||
});
|
||||
}
|
||||
return jsonResponse({ message: 'remove failed' }, { ok: false, status: 500 });
|
||||
};
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
readWechatAuthError,
|
||||
readWechatPendingToken,
|
||||
} from '../utils/wechat';
|
||||
import { APP_DISPLAY_NAME } from '../utils/appBrand';
|
||||
import { TKMindAvatar } from './TKMindAvatar';
|
||||
import { resolvePlazaHomeUrl } from '../utils/publicUrl';
|
||||
import { WechatBindGate } from './WechatBindGate';
|
||||
@@ -26,7 +27,7 @@ import { WechatOpenGuide } from './WechatOpenGuide';
|
||||
type Mode = 'login' | 'register' | 'reset';
|
||||
|
||||
const MODE_META: Record<Mode, { title: string; desc: string }> = {
|
||||
login: { title: 'TKMind', desc: '登录你的账号' },
|
||||
login: { title: APP_DISPLAY_NAME, desc: '登录你的账号' },
|
||||
register: { title: '创建账号', desc: '填写信息完成注册' },
|
||||
reset: { title: '重置密码', desc: '验证注册邮箱后设置新密码' },
|
||||
};
|
||||
@@ -239,7 +240,7 @@ export function AuthView({
|
||||
}
|
||||
|
||||
const meta = legacyMode
|
||||
? { title: 'TKMind', desc: '内部访问入口' }
|
||||
? { title: APP_DISPLAY_NAME, desc: '内部访问入口' }
|
||||
: fromPlaza
|
||||
? {
|
||||
...MODE_META[mode],
|
||||
|
||||
@@ -8,6 +8,7 @@ import { getSessionDisplayName } from '../utils/sessions';
|
||||
import { isH5OrWechatClient } from '../utils/wechat';
|
||||
import { BalanceRing } from './BalanceRing';
|
||||
import { HistorySidebar } from './HistorySidebar';
|
||||
import { APP_DISPLAY_NAME } from '../utils/appBrand';
|
||||
import { TKMindAvatar } from './TKMindAvatar';
|
||||
import { ChatPanel } from './ChatPanel';
|
||||
import { ChatLoadingSpinner } from './ChatLoadingSpinner';
|
||||
@@ -163,6 +164,7 @@ export function ChatView({
|
||||
user,
|
||||
capabilities,
|
||||
grantedSkills,
|
||||
onGrantedSkillsUpdate,
|
||||
onLogout,
|
||||
onOpenSpace,
|
||||
onOpenPage,
|
||||
@@ -173,6 +175,7 @@ export function ChatView({
|
||||
capabilities?: CapabilityMap;
|
||||
grantedSkills?: string[];
|
||||
onUserUpdate?: (user: PortalUser) => void;
|
||||
onGrantedSkillsUpdate?: (skills: string[]) => void;
|
||||
onLogout?: () => void;
|
||||
onOpenSpace?: (target?: { categoryCode?: MindSpaceSaveCategory; pageId?: string }) => void;
|
||||
onOpenPage?: (pageId: string) => void;
|
||||
@@ -213,6 +216,7 @@ export function ChatView({
|
||||
subscription,
|
||||
openRecharge,
|
||||
openSubscribe,
|
||||
completeRecharge,
|
||||
uploadChatImage,
|
||||
uploadChatAttachment,
|
||||
followAgentRun,
|
||||
@@ -357,7 +361,7 @@ export function ChatView({
|
||||
</button>
|
||||
<TKMindAvatar size="sm" className="header-brand-avatar" />
|
||||
<div>
|
||||
<div className="header-title">{user?.displayName ?? 'TKMind'}</div>
|
||||
<div className="header-title">{user?.displayName ?? APP_DISPLAY_NAME}</div>
|
||||
<div className="header-sub">
|
||||
{isConnectingTitle ? <ChatLoadingSpinner /> : null}
|
||||
<span>{sessionTitle}</span>
|
||||
@@ -569,6 +573,10 @@ export function ChatView({
|
||||
session={session}
|
||||
capabilities={capabilities}
|
||||
grantedSkills={grantedSkills}
|
||||
balanceCents={balanceCents ?? 0}
|
||||
onBalanceUpdate={(nextBalance) => completeRecharge(nextBalance)}
|
||||
onGrantedSkillsUpdate={onGrantedSkillsUpdate}
|
||||
onOpenRecharge={() => openRecharge(false)}
|
||||
onSubmit={(text, imageUrls, previewImageUrls, options) =>
|
||||
void submit(
|
||||
text,
|
||||
|
||||
@@ -6,6 +6,7 @@ import {
|
||||
FileText,
|
||||
Bot,
|
||||
} from 'lucide-react';
|
||||
import { APP_DISPLAY_NAME, APP_DISPLAY_TAGLINE } from '../utils/appBrand';
|
||||
import { TKMindAvatar } from './TKMindAvatar';
|
||||
|
||||
const features = [
|
||||
@@ -21,7 +22,7 @@ export function ChatWelcomePanel({ compact }: { compact?: boolean }) {
|
||||
return (
|
||||
<div className="empty-state empty-state-compact">
|
||||
<TKMindAvatar />
|
||||
<h2>TKMind</h2>
|
||||
<h2>{APP_DISPLAY_NAME}</h2>
|
||||
<p>继续和空间里的 Agent 对话</p>
|
||||
</div>
|
||||
);
|
||||
@@ -45,7 +46,7 @@ export function ChatWelcomePanel({ compact }: { compact?: boolean }) {
|
||||
transition={{ delay: 0.15 }}
|
||||
className="welcome-panel-brand"
|
||||
>
|
||||
MeMind 智趣
|
||||
{APP_DISPLAY_TAGLINE}
|
||||
</motion.h2>
|
||||
|
||||
<motion.h1
|
||||
@@ -73,7 +74,7 @@ export function ChatWelcomePanel({ compact }: { compact?: boolean }) {
|
||||
transition={{ delay: 0.55 }}
|
||||
className="welcome-panel-description"
|
||||
>
|
||||
旅行攻略、行业分析、活动页面、心情记录……从一个念头开始,MeMind 帮你把想法变成可用的成果。
|
||||
旅行攻略、行业分析、活动页面、心情记录……从一个念头开始,{APP_DISPLAY_NAME} 帮你把想法变成可用的成果。
|
||||
</motion.p>
|
||||
|
||||
<motion.div
|
||||
|
||||
@@ -277,7 +277,7 @@ export function FeedbackSubmitView({
|
||||
>
|
||||
<div className="feedback-board-toolbar">
|
||||
<div className="feedback-board-toolbar-copy">
|
||||
<p className="feedback-submit-eyebrow">帮助我们改进 TKMind</p>
|
||||
<p className="feedback-submit-eyebrow">帮助我们改进 Memind</p>
|
||||
<h1>提交 Bug 或需求</h1>
|
||||
<p className="feedback-submit-desc feedback-board-desc">
|
||||
你可以用文字描述、上传截图,或点击麦克风口述问题。我们会自动附带当前页面与设备信息,便于定位问题。
|
||||
|
||||
@@ -7,6 +7,7 @@ import type { MindSpaceChatContext, MindSpaceSaveCategory, PortalUser, Message }
|
||||
import { formatContextChip } from '../utils/mindspaceChatContext';
|
||||
import { shouldShowChatMessage } from '../utils/message';
|
||||
import { ChatPanel } from './ChatPanel';
|
||||
import { APP_DISPLAY_NAME } from '../utils/appBrand';
|
||||
import { TKMindAvatar } from './TKMindAvatar';
|
||||
import { GoalRunAwaitingBanner } from './GoalRunAwaitingBanner';
|
||||
|
||||
@@ -19,7 +20,7 @@ export function SpaceChatPanel({
|
||||
onPageSaved,
|
||||
chatBridge,
|
||||
hideOpenFullChat = false,
|
||||
title = 'TKMind',
|
||||
title = APP_DISPLAY_NAME,
|
||||
prefillMessages = [],
|
||||
}: {
|
||||
open: boolean;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { APP_DISPLAY_NAME } from '../utils/appBrand';
|
||||
import tkmindAvatar from '../assets/tkmind-avatar.png';
|
||||
|
||||
type TKMindAvatarProps = {
|
||||
@@ -13,7 +14,7 @@ export function TKMindAvatar({ className = '', size = 'sm' }: TKMindAvatarProps)
|
||||
className={`tkmind-avatar ${sizeClass} msg-avatar msg-avatar-assistant ${className}`.trim()}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<img src={tkmindAvatar} alt="TKMind" className="tkmind-avatar-img" />
|
||||
<img src={tkmindAvatar} alt={APP_DISPLAY_NAME} className="tkmind-avatar-img" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
/** User-facing product name shown in nav, login, and page chrome. */
|
||||
export const APP_DISPLAY_NAME = 'Memind';
|
||||
|
||||
/** Branded tagline suffix used on welcome and marketing surfaces. */
|
||||
export const APP_DISPLAY_TAGLINE = `${APP_DISPLAY_NAME} 智趣`;
|
||||
@@ -1138,6 +1138,7 @@ export function createTkmindProxy({
|
||||
llmProviderService,
|
||||
localFetchAsset,
|
||||
subscriptionService,
|
||||
billingConfigService = null,
|
||||
sessionSnapshotService,
|
||||
conversationMemoryService,
|
||||
memoryV2,
|
||||
@@ -2097,6 +2098,9 @@ export function createTkmindProxy({
|
||||
return resolveBillingTokenState(tokenStateRaw, {
|
||||
sessionId,
|
||||
fetchSession: fetchSessionBillingCost,
|
||||
loadEstimateConfig: billingConfigService?.getEffectiveCostEstimateConfig
|
||||
? () => billingConfigService.getEffectiveCostEstimateConfig()
|
||||
: null,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+34
-7
@@ -142,6 +142,7 @@ export function createUserAuth(pool, options = {}) {
|
||||
? options.provisionUserDataSpace
|
||||
: null;
|
||||
const getMindSearchConfig = typeof options.getMindSearchConfig === 'function' ? options.getMindSearchConfig : null;
|
||||
const billingConfigService = options.billingConfigService ?? null;
|
||||
const sessions = new Map();
|
||||
const loginFailures = new Map();
|
||||
|
||||
@@ -1334,7 +1335,9 @@ export function createUserAuth(pool, options = {}) {
|
||||
};
|
||||
}
|
||||
const tokenState = normalizeTokenState(tokenStateRaw);
|
||||
const config = loadBillingConfig();
|
||||
const config = billingConfigService?.getEffectiveBillingConfig
|
||||
? await billingConfigService.getEffectiveBillingConfig()
|
||||
: loadBillingConfig(env);
|
||||
const normalizedRequestId = requestId ? String(requestId).trim() || null : null;
|
||||
const now = Date.now();
|
||||
const conn = await pool.getConnection();
|
||||
@@ -1439,10 +1442,12 @@ export function createUserAuth(pool, options = {}) {
|
||||
);
|
||||
|
||||
// Subscription quota check: consume tokens from active plan before touching balance.
|
||||
let subscriptionCovered = false;
|
||||
if (costCents > 0 && subscriptionService) {
|
||||
const coverage = await subscriptionService.consumeQuota(userId, deltaTokens, conn);
|
||||
if (coverage.fullyCovers) {
|
||||
costCents = 0;
|
||||
subscriptionCovered = true;
|
||||
} else if (coverage.overageRate < 1.0) {
|
||||
costCents = Math.max(1, Math.ceil(costCents * coverage.overageRate));
|
||||
}
|
||||
@@ -1479,8 +1484,8 @@ export function createUserAuth(pool, options = {}) {
|
||||
|
||||
await conn.query(
|
||||
`INSERT INTO h5_usage_records
|
||||
(user_id, agent_session_id, request_id, input_tokens, output_tokens, cost_cents, balance_after_cents, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
(user_id, agent_session_id, request_id, input_tokens, output_tokens, cost_cents, balance_after_cents, billing_source, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, 'wallet', ?)`,
|
||||
[
|
||||
userId,
|
||||
agentSessionId,
|
||||
@@ -1521,6 +1526,28 @@ export function createUserAuth(pool, options = {}) {
|
||||
userId,
|
||||
]);
|
||||
}
|
||||
} else if (subscriptionCovered && deltaTokens > 0) {
|
||||
const [walletRows] = await conn.query(
|
||||
`SELECT balance_cents, tokens_used FROM h5_user_wallets WHERE user_id = ?`,
|
||||
[userId],
|
||||
);
|
||||
balanceAfter = walletRows[0] ? Number(walletRows[0].balance_cents) : 0;
|
||||
tokensUsedAfter = walletRows[0] ? Number(walletRows[0].tokens_used ?? 0) : null;
|
||||
|
||||
await conn.query(
|
||||
`INSERT INTO h5_usage_records
|
||||
(user_id, agent_session_id, request_id, input_tokens, output_tokens, cost_cents, balance_after_cents, billing_source, created_at)
|
||||
VALUES (?, ?, ?, ?, ?, 0, ?, 'subscription', ?)`,
|
||||
[
|
||||
userId,
|
||||
agentSessionId,
|
||||
normalizedRequestId,
|
||||
deltaIn,
|
||||
deltaOut,
|
||||
balanceAfter,
|
||||
now,
|
||||
],
|
||||
);
|
||||
} else {
|
||||
const user = await getUserById(userId);
|
||||
balanceAfter = user ? Number(user.balance_cents) : null;
|
||||
@@ -1553,12 +1580,12 @@ export function createUserAuth(pool, options = {}) {
|
||||
if (userId) params.push(userId);
|
||||
const [rows] = await pool.query(
|
||||
`SELECT r.id, r.user_id, u.username, r.agent_session_id, r.request_id,
|
||||
r.input_tokens, r.output_tokens, r.cost_cents, r.balance_after_cents, r.created_at
|
||||
r.input_tokens, r.output_tokens, r.cost_cents, r.balance_after_cents, r.billing_source, r.created_at
|
||||
FROM h5_usage_records r JOIN h5_users u ON u.id = r.user_id
|
||||
${where} ORDER BY r.created_at DESC LIMIT ${safeLimit}`,
|
||||
params,
|
||||
);
|
||||
return rows.map((row) => ({ id: Number(row.id), userId: row.user_id, username: row.username, agentSessionId: row.agent_session_id, requestId: row.request_id, inputTokens: Number(row.input_tokens), outputTokens: Number(row.output_tokens), costCents: Number(row.cost_cents), balanceAfterCents: Number(row.balance_after_cents), createdAt: Number(row.created_at) }));
|
||||
return rows.map((row) => ({ id: Number(row.id), userId: row.user_id, username: row.username, agentSessionId: row.agent_session_id, requestId: row.request_id, inputTokens: Number(row.input_tokens), outputTokens: Number(row.output_tokens), costCents: Number(row.cost_cents), balanceAfterCents: Number(row.balance_after_cents), billingSource: row.billing_source ?? 'wallet', createdAt: Number(row.created_at) }));
|
||||
}
|
||||
const safePageSize = Math.min(Math.max(Number(pageSize) || 50, 1), 200);
|
||||
const safePage = Math.max(Number(page) || 1, 1);
|
||||
@@ -1572,7 +1599,7 @@ export function createUserAuth(pool, options = {}) {
|
||||
);
|
||||
const [rows] = await pool.query(
|
||||
`SELECT r.id, r.user_id, u.username, r.agent_session_id, r.request_id,
|
||||
r.input_tokens, r.output_tokens, r.cost_cents, r.balance_after_cents, r.created_at
|
||||
r.input_tokens, r.output_tokens, r.cost_cents, r.balance_after_cents, r.billing_source, r.created_at
|
||||
FROM h5_usage_records r JOIN h5_users u ON u.id = r.user_id
|
||||
${where}
|
||||
ORDER BY r.created_at DESC
|
||||
@@ -1580,7 +1607,7 @@ export function createUserAuth(pool, options = {}) {
|
||||
params,
|
||||
);
|
||||
return {
|
||||
records: rows.map((row) => ({ id: Number(row.id), userId: row.user_id, username: row.username, agentSessionId: row.agent_session_id, requestId: row.request_id, inputTokens: Number(row.input_tokens), outputTokens: Number(row.output_tokens), costCents: Number(row.cost_cents), balanceAfterCents: Number(row.balance_after_cents), createdAt: Number(row.created_at) })),
|
||||
records: rows.map((row) => ({ id: Number(row.id), userId: row.user_id, username: row.username, agentSessionId: row.agent_session_id, requestId: row.request_id, inputTokens: Number(row.input_tokens), outputTokens: Number(row.output_tokens), costCents: Number(row.cost_cents), balanceAfterCents: Number(row.balance_after_cents), billingSource: row.billing_source ?? 'wallet', createdAt: Number(row.created_at) })),
|
||||
total: Number(total),
|
||||
page: safePage,
|
||||
pageSize: safePageSize,
|
||||
|
||||
@@ -770,6 +770,114 @@ test('billSessionUsage auto gifts low-balance bonus once for eligible new users'
|
||||
assert.deepEqual(notificationTypes, ['low_balance_gift']);
|
||||
});
|
||||
|
||||
test('billSessionUsage writes usage record when subscription fully covers tokens', async () => {
|
||||
const userRow = {
|
||||
id: 'user-sub-1',
|
||||
username: 'pro_user',
|
||||
slug: 'pro_user',
|
||||
email: 'pro@example.com',
|
||||
display_name: 'Pro User',
|
||||
role: 'user',
|
||||
status: 'active',
|
||||
plan_type: 'pro',
|
||||
workspace_root: '/tmp/pro-user',
|
||||
balance_cents: 200,
|
||||
tokens_used: 0,
|
||||
spent_cents: 0,
|
||||
};
|
||||
const stateBySession = new Map();
|
||||
let walletBalance = 200;
|
||||
let tokensUsed = 0;
|
||||
const usageRecords = [];
|
||||
let ledgerCount = 0;
|
||||
let consumeQuotaCalls = 0;
|
||||
|
||||
const subscriptionService = {
|
||||
async consumeQuota(userId, deltaTokens) {
|
||||
consumeQuotaCalls += 1;
|
||||
assert.equal(userId, userRow.id);
|
||||
assert.equal(deltaTokens, 15_000);
|
||||
return { fullyCovers: true, overageRate: 0.5 };
|
||||
},
|
||||
};
|
||||
|
||||
const pool = {
|
||||
async query(sql) {
|
||||
if (sql.includes('FROM h5_users u') && sql.includes('WHERE u.id = ?')) {
|
||||
return [[{ ...userRow, balance_cents: walletBalance, tokens_used: tokensUsed }]];
|
||||
}
|
||||
throw new Error(`unexpected pool query: ${sql}`);
|
||||
},
|
||||
async getConnection() {
|
||||
return {
|
||||
async beginTransaction() {},
|
||||
async commit() {},
|
||||
async rollback() {},
|
||||
release() {},
|
||||
async query(sql, params = []) {
|
||||
if (sql.includes('SELECT cost_cents FROM h5_usage_records WHERE request_id = ? LIMIT 1')) return [[]];
|
||||
if (sql.includes('INSERT INTO h5_session_billing_state') && sql.includes('agent_session_id = agent_session_id')) {
|
||||
return [{ affectedRows: 1 }, []];
|
||||
}
|
||||
if (sql.includes('FROM h5_session_billing_state') && sql.includes('FOR UPDATE')) {
|
||||
const row = stateBySession.get(params[0]);
|
||||
return [row ? [row] : []];
|
||||
}
|
||||
if (sql.includes('INSERT INTO h5_session_billing_state') && sql.includes('ON DUPLICATE KEY UPDATE')) {
|
||||
stateBySession.set(params[0], {
|
||||
last_accumulated_cost: params[2],
|
||||
last_input_tokens: params[3],
|
||||
last_output_tokens: params[4],
|
||||
});
|
||||
return [{ affectedRows: 1 }, []];
|
||||
}
|
||||
if (sql.includes('SELECT balance_cents, tokens_used FROM h5_user_wallets WHERE user_id = ?')) {
|
||||
return [[{ balance_cents: walletBalance, tokens_used: tokensUsed }]];
|
||||
}
|
||||
if (sql.includes('INSERT INTO h5_usage_records')) {
|
||||
const subscription = sql.includes("'subscription'");
|
||||
usageRecords.push({
|
||||
user_id: params[0],
|
||||
agent_session_id: params[1],
|
||||
request_id: params[2],
|
||||
input_tokens: params[3],
|
||||
output_tokens: params[4],
|
||||
cost_cents: subscription ? 0 : params[5],
|
||||
balance_after_cents: subscription ? params[5] : params[6],
|
||||
billing_source: subscription ? 'subscription' : 'wallet',
|
||||
});
|
||||
return [{ affectedRows: 1 }, []];
|
||||
}
|
||||
if (sql.includes("INSERT INTO h5_billing_ledger") && sql.includes("'deduct'")) {
|
||||
ledgerCount += 1;
|
||||
return [{ affectedRows: 1 }, []];
|
||||
}
|
||||
throw new Error(`unexpected connection query: ${sql}`);
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const auth = createUserAuth(pool, { persistSessions: false, subscriptionService });
|
||||
const result = await auth.billSessionUsage(
|
||||
userRow.id,
|
||||
'session-sub-1',
|
||||
{ accumulatedOutputTokens: 15_000 },
|
||||
'req-sub-1',
|
||||
);
|
||||
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.costCents, 0);
|
||||
assert.equal(result.balanceCents, 200);
|
||||
assert.equal(consumeQuotaCalls, 1);
|
||||
assert.equal(ledgerCount, 0);
|
||||
assert.equal(usageRecords.length, 1);
|
||||
assert.equal(usageRecords[0].cost_cents, 0);
|
||||
assert.equal(usageRecords[0].billing_source, 'subscription');
|
||||
assert.equal(usageRecords[0].output_tokens, 15_000);
|
||||
assert.equal(walletBalance, 200);
|
||||
});
|
||||
|
||||
test('updateUser rejects quota smaller than occupied bytes', async () => {
|
||||
const userRow = {
|
||||
id: 'user-3',
|
||||
|
||||
+2
-1
@@ -2658,7 +2658,8 @@ test('wechat mp service reconciles existing dedicated session before reply', asy
|
||||
assert.equal(result.status, 200);
|
||||
await result.task;
|
||||
assert.equal(calls.some(([pathname]) => pathname === '/agent/update_working_dir'), true);
|
||||
assert.equal(calls.some(([pathname]) => pathname === '/agent/add_extension'), false);
|
||||
assert.equal(calls.some(([pathname]) => pathname === '/agent/add_extension'), true);
|
||||
assert.equal(calls.some(([pathname]) => pathname === '/agent/restart'), true);
|
||||
assert.equal(calls.some(([pathname]) => pathname === '/sessions/session-1/reply'), true);
|
||||
} finally {
|
||||
crypto.randomUUID = originalRandomUuid;
|
||||
|
||||
Reference in New Issue
Block a user