sync: 同步 monkey-ai@weiyuan(ddc5b9443) 的 web/ 到 ui-optimization

- 合入 weiyuan 新功能前端:分佣 V2 / 伙伴工作台、智能路由、企业资金与分析、官网设置与预约演示等,
  semi-ui 已全部迁移到 antd 6 / @/components/ui,不重新引入 Semi
- 分佣二级菜单与页头去重、伙伴入口探测(企业伙伴走企业中心「企业分佣」)、超管侧栏入口恢复
- 适配层 DatePicker / TimePicker 统一 onChange(Date|Date[]|null, 文本) 契约;生产构建剔除调试日志
- 图片链接刷新:同任务请求复用、后台刷新不弹全局错误、离页停止批量请求
- 恢复 bun.lock(与 package-lock.json 共存);docs 规范与 CHANGELOG 更新
- 停止跟踪 .env.playwright.local(本地登录凭据,已加入 .gitignore)
This commit is contained in:
qiubaishen
2026-11-18 10:22:02 +08:00
parent dfa5c1edd6
commit a57aae3043
157 changed files with 29960 additions and 1197 deletions
+724
View File
@@ -0,0 +1,724 @@
/**
* Isolated browser regression for the real model-cost settings components.
* No backend is started: every /api/ request is mocked; off-origin traffic is blocked.
* Requires existing web/node_modules and an externally available Playwright + Chromium.
* PowerShell example:
* $env:PLAYWRIGHT_MODULE='C:/path/to/node_modules/playwright/index.mjs'
* node web/scripts/model-cost-qa.mjs
* Optional: COST_QA_OUTPUT (artifact directory), QA_FILTER (case-name substring).
* Browser plugin not available in the authoring environment; regular Playwright used.
*/
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { fileURLToPath, pathToFileURL } from 'node:url';
const webRoot = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'..',
);
const out =
process.env.COST_QA_OUTPUT ||
fs.mkdtempSync(path.join(os.tmpdir(), 'model-cost-qa-'));
fs.mkdirSync(out, { recursive: true });
const playwrightModule = process.env.PLAYWRIGHT_MODULE;
const { chromium } = await import(
playwrightModule
? pathToFileURL(path.resolve(playwrightModule)).href
: 'playwright'
);
const { createServer, loadConfigFromFile } = await import(
pathToFileURL(path.join(webRoot, 'node_modules/vite/dist/node/index.js')).href
);
const loadedConfig = await loadConfigFromFile(
{ command: 'serve', mode: 'development' },
path.join(webRoot, 'vite.config.js'),
);
const base = loadedConfig.config;
const entry = path.join(webRoot, 'src/__cost-test.jsx').replaceAll('\\', '/');
const server = await createServer({
...base,
configFile: false,
root: webRoot,
cacheDir: path.join(out, 'vite-cache'),
optimizeDeps: { ...base.optimizeDeps, force: false },
server: { host: '127.0.0.1', port: 0, strictPort: false, proxy: {} },
plugins: [
...base.plugins,
{
name: 'isolated-model-cost-qa',
configureServer(vite) {
vite.middlewares.use('/api/', (_req, res) => {
res.statusCode = 503;
res.end('QA requires browser request interception');
});
vite.middlewares.use('/__cost-test.html', async (_req, res) => {
res.setHeader('Content-Type', 'text/html');
res.end(
await vite.transformIndexHtml(
'/__cost-test.html',
'<html><head><title>Cost settings QA</title></head><body><div id="root"></div><script type="module" src="/__cost-test.jsx"></script></body></html>',
),
);
});
},
resolveId(id) {
if (id === '/__cost-test.jsx') return entry;
},
load(id) {
if (id === entry)
return `
import '/src/styles/tokens.css';import '/src/index.css';import '/src/styles/org.css';
import React from 'react';import {createRoot} from 'react-dom/client';
import i18n from 'i18next';import {initReactI18next} from 'react-i18next';
import {MemoryRouter} from 'react-router-dom';
import {StatusProvider} from '/src/context/Status/index.jsx';import {UserProvider} from '/src/context/User/index.jsx';
import RatioSetting from '/src/components/settings/RatioSetting.jsx';
import ModelCostSettings from '/src/pages/Setting/Ratio/ModelCostSettings.jsx';
i18n.use(initReactI18next).init({lng:'zh',fallbackLng:'zh',resources:{zh:{translation:{}}},interpolation:{escapeValue:false}});
createRoot(document.getElementById('root')).render(<MemoryRouter><StatusProvider><UserProvider><div style={{padding:20}}>{location.search.includes('direct')?<ModelCostSettings/>:<RatioSetting/>}</div></UserProvider></StatusProvider></MemoryRouter>);
`;
},
},
],
});
await server.listen();
const origin = 'http://127.0.0.1:' + server.httpServer.address().port;
console.log('QA origin:', origin, 'Artifacts:', out);
let browser;
try {
browser = await chromium.launch({ headless: true });
} catch (error) {
await server.close();
throw error;
}
const results = [];
const allRequests = [];
const allErrors = [];
let active;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
async function until(predicate) {
const deadline = Date.now() + 12000;
while (!predicate()) {
if (Date.now() > deadline)
throw new Error('Timed out waiting for intercepted request');
await sleep(20);
}
}
function deferred() {
let resolve;
const promise = new Promise((r) => (resolve = r));
return { promise, resolve };
}
async function setup({
direct = true,
role = 100,
channels = true,
viewport = { width: 1500, height: 1000 },
} = {}) {
const ctx = await browser.newContext({ viewport });
await ctx.addInitScript(
(role) =>
localStorage.setItem(
'user',
JSON.stringify({ id: 1, role, username: 'qa' }),
),
role,
);
const p = await ctx.newPage();
p.setDefaultTimeout(12000);
p.setDefaultNavigationTimeout(120000);
p.on('dialog', (d) => d.accept());
const s = {
p,
ctx,
requests: [],
writes: [],
errors: [],
readMode: 'normal',
writeMode: 'normal',
readGates: {},
writeGate: null,
channels,
};
active = s;
p.on('pageerror', (e) => s.errors.push(e.message));
p.on('console', (m) => {
if (m.type() === 'error' && !m.text().startsWith('Warning:'))
allErrors.push(m.text());
});
await p.route('**/*', async (route) => {
const r = route.request(),
u = new URL(r.url());
if (u.origin !== origin) {
await route.abort();
return;
}
if (!u.pathname.startsWith('/api/')) return route.continue();
const event = {
method: r.method(),
path: u.pathname,
key: u.searchParams.get('scope_key'),
body: r.postDataJSON(),
};
s.requests.push(event);
allRequests.push(event);
const ok = (data) => route.fulfill({ json: { success: true, data } });
const path = u.pathname,
k = event.key || '1';
if (r.method() !== 'GET') {
s.writes.push(event);
if (s.writeGate) await s.writeGate.promise;
if (s.writeMode === 'network') return route.abort('failed');
if (s.writeMode === 'business-reject')
return route.fulfill({
json: { success: false, message: 'mock rejected write' },
});
if (s.writeMode === 'reject')
return route.fulfill({
status: 500,
json: { success: false, message: 'mock write failure' },
});
return ok({ created: 1, updated: 1, closed: 1, deleted: 1 });
}
if (path === '/api/channel/')
return ok({
items: channels
? [
{ id: 1, name: 'Channel A', status: 1 },
{ id: 2, name: 'Channel B', status: 1 },
]
: [],
total: channels ? 2 : 0,
});
if (path === '/api/option/') return ok([]);
if (path.endsWith('/uncovered')) return ok({ total: 0, items: [] });
if (path.includes('/commission/costs/')) {
const capturedMode = s.readMode;
const gate = s.readGates[k];
if (gate) await gate.promise;
if (capturedMode === 'network') return route.abort('failed');
if (capturedMode === '500' || (capturedMode === 'failB' && k === '2'))
return route.fulfill({
status: 500,
json: { message: 'internal stack not for display' },
});
if (capturedMode.startsWith('410'))
return route.fulfill({
status: 410,
json: {
success: false,
message:
capturedMode === '410-valid'
? '旧版分佣已停用:测试说明'
: capturedMode === '410-object'
? { bad: true }
: '',
},
});
if (path.endsWith('scope_models'))
return ok({
models: [
{
model_name: `model-${k === '1' ? 'A' : 'B'}`,
units: [{ unit: 'input_1m', tier_key: '' }],
enabled_channels: 1,
},
],
official: { [`model-${k === '1' ? 'A' : 'B'}`]: { input: 10 } },
});
return ok([
{
id: Number(k) * 100 + 1,
scope: 'channel',
scope_key: k,
model_name: `model-${k === '1' ? 'A' : 'B'}`,
unit: 'input_1m',
tier_key: '',
cost_uyuan_per_unit: Number(k) * 1000000,
effective_from: 1,
effective_to: 0,
note: 'original',
},
]);
}
return ok([]);
});
s.goto = async () => {
await p.goto(origin + '/__cost-test.html' + (direct ? '?direct' : ''), {
waitUntil: 'domcontentloaded',
});
await p
.getByText(direct ? '渠道' : '模型倍率设置', { exact: true })
.first()
.waitFor();
};
s.close = async () => {
assert.deepEqual(s.errors, [], 'no page runtime errors');
await ctx.close();
};
return s;
}
async function loaded(s, model = 'A') {
await s.p.getByPlaceholder('成本单价').first().waitFor();
await s.p
.getByText('model-' + model, { exact: true })
.first()
.waitFor();
}
const button = (p, name) =>
p
.locator('button')
.filter({ hasText: new RegExp('^' + name + '$') })
.first();
const modal = (p) =>
p.locator('.semi-modal-content').filter({ visible: true }).last();
async function confirm(p, label) {
await p.getByText(label, { exact: true }).last().click();
}
async function choose(s, id) {
await s.p.locator('.semi-select').first().click();
await s.p
.getByText(`#${id} Channel ${id === 1 ? 'A' : 'B'}`, { exact: true })
.click();
}
async function refresh(s) {
await button(s.p, '刷新').click();
}
async function noWrites(s) {
await sleep(100);
assert.equal(s.writes.length, 0);
}
async function history(s) {
await button(s.p, '版本(1)').click();
}
async function advanced(s) {
await history(s);
await button(s.p, '编辑').click();
await s.p.getByText('编辑价格版本', { exact: true }).waitFor();
}
async function modalOk(s) {
await modal(s.p).locator('.semi-modal-footer button').last().click();
}
async function test(name, fn) {
if (process.env.QA_FILTER && !name.includes(process.env.QA_FILTER)) return;
let s;
try {
s = await fn();
if (s) await s.close();
results.push({ name, pass: true });
console.log('PASS', name);
} catch (e) {
results.push({ name, pass: false, error: e.stack });
console.error('FAIL', name, e.message);
console.error('BODY', await active.p.locator('body').innerText());
await active.p.screenshot({
path: out + '/failure-' + results.length + '.png',
});
await active.ctx.close();
}
fs.writeFileSync(
out + '/fixed-results.json',
JSON.stringify(results, null, 2),
);
}
try {
await test('lazy mounting, first cost load, tab draft persistence', async () => {
const s = await setup({ direct: false });
await s.goto();
await sleep(300);
assert.equal(
s.requests.filter((r) => r.path.includes('/commission/costs')).length,
0,
);
await s.p.getByText('模型成本价格', { exact: true }).click();
await loaded(s);
await s.p.getByPlaceholder('成本单价').fill('7');
await s.p.getByText('模型倍率设置', { exact: true }).first().click();
await s.p.getByText('模型成本价格', { exact: true }).click();
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '7');
await sleep(350);
await s.p.screenshot({ path: out + '/fixed-tabs.png' });
return s;
});
await test('non Root has no cost tab', async () => {
const s = await setup({ direct: false, role: 10 });
await s.goto();
assert.equal(
await s.p.getByText('模型成本价格', { exact: true }).count(),
0,
);
return s;
});
await test('A dirty -> B 500 clears A and prevents all writes', async () => {
const s = await setup();
await s.goto();
await loaded(s);
await s.p.getByPlaceholder('成本单价').fill('7');
s.readMode = 'failB';
await choose(s, 2);
await confirm(s.p, '放弃修改并切换');
await s.p
.getByText('错误:加载成本配置失败,请重试', { exact: true })
.waitFor();
assert.equal(await s.p.getByPlaceholder('成本单价').count(), 0);
assert(await button(s.p, '保存成本价').isDisabled());
assert(await button(s.p, '按官方价折扣批量定价').isDisabled());
await sleep(350);
await s.p.screenshot({ path: out + '/fixed-cross-channel.png' });
await noWrites(s);
return s;
});
await test('A slow B fast keeps B snapshot after A completes', async () => {
const s = await setup();
const gate = deferred();
s.readGates['1'] = gate;
await s.goto();
await choose(s, 2);
await loaded(s, 'B');
gate.resolve();
await sleep(200);
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '2');
assert.equal(await s.p.getByText('model-A', { exact: true }).count(), 0);
await s.p.getByPlaceholder('成本单价').fill('8');
await button(s.p, '保存成本价').click();
await sleep(200);
assert.equal(s.writes[0].body.scope_key, '2');
assert.equal(s.writes[0].body.items[0].model_name, 'model-B');
return s;
});
await test('old failed request cannot toast or unlock newer B pending read', async () => {
const s = await setup();
const a = deferred(),
b = deferred();
s.readMode = '500';
s.readGates['1'] = a;
await s.goto();
await sleep(100);
s.readMode = 'normal';
s.readGates['2'] = b;
await choose(s, 2);
await until(() => s.requests.filter((r) => r.key === '2').length === 2);
a.resolve();
await sleep(100);
assert.equal(await s.p.locator('.semi-toast-content').count(), 0);
assert(await button(s.p, '按官方价折扣批量定价').isDisabled());
b.resolve();
await loaded(s, 'B');
return s;
});
await test('invalid draft switch cancel preserves; confirm discards', async () => {
const s = await setup();
await s.goto();
await loaded(s);
await s.p.getByPlaceholder('成本单价').fill('-2');
await choose(s, 2);
await confirm(s.p, '留在当前渠道');
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '-2');
await choose(s, 2);
await confirm(s.p, '放弃修改并切换');
await loaded(s, 'B');
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '2');
return s;
});
await test('same-channel failed refresh retains readonly draft then confirms recovery', async () => {
const s = await setup();
await s.goto();
await loaded(s);
await s.p.getByPlaceholder('成本单价').fill('7');
s.readMode = '500';
await refresh(s);
await confirm(s.p, '放弃修改并刷新');
await s.p
.getByText('错误:加载成本配置失败,请重试', { exact: true })
.waitFor();
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '7');
assert(await s.p.getByPlaceholder('成本单价').isDisabled());
assert(await button(s.p, '保存成本价').isDisabled());
assert(await button(s.p, '按官方价折扣批量定价').isDisabled());
s.readMode = 'normal';
await refresh(s);
await confirm(s.p, '放弃修改并刷新');
await sleep(200);
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '1');
return s;
});
await test('clear selection confirms dirty draft, disables writes, no empty scope GET', async () => {
const s = await setup();
await s.goto();
await loaded(s);
await s.p.getByPlaceholder('成本单价').fill('7');
await s.p.locator('.semi-select').first().hover();
await s.p.locator('.semi-select-clear').first().click();
await confirm(s.p, '放弃修改并切换');
await sleep(100);
assert.equal(await s.p.getByPlaceholder('成本单价').count(), 0);
assert(await button(s.p, '保存成本价').isDisabled());
assert(await button(s.p, '按官方价折扣批量定价').isDisabled());
assert(
!s.requests.some(
(r) =>
r.path.includes('/commission/costs/') &&
!r.path.endsWith('uncovered') &&
r.key === '',
),
);
return s;
});
await test('no channel defaults has no scoped requests or writes', async () => {
const s = await setup({ channels: false });
await s.goto();
await sleep(100);
assert(!s.requests.some((r) => r.path.endsWith('scope_models')));
assert(await button(s.p, '保存成本价').isDisabled());
return s;
});
for (const mode of ['410-valid', '410-empty', '410-object', '500', 'network'])
await test('error presentation ' + mode, async () => {
const s = await setup();
s.readMode = mode;
await s.goto();
const expected =
mode === '410-valid'
? '错误:旧版分佣已停用:测试说明'
: '错误:加载成本配置失败,请重试';
await s.p.getByText(expected, { exact: true }).waitFor();
assert.equal(await s.p.locator('.semi-toast-content').count(), 1);
assert(await button(s.p, '保存成本价').isDisabled());
await noWrites(s);
if (mode === '410-valid') await sleep(350);
await s.p.screenshot({ path: out + '/fixed-410.png' });
return s;
});
for (const kind of ['save', 'save-delete', 'discount', 'advanced', 'delete'])
await test('write lock and payload ' + kind, async () => {
const s = await setup();
await s.goto();
await loaded(s);
s.writeGate = deferred();
let submit;
if (kind === 'save') {
await s.p.getByPlaceholder('成本单价').fill('7');
submit = button(s.p, '保存成本价');
}
if (kind === 'save-delete') {
await s.p.getByPlaceholder('成本单价').fill('');
await button(s.p, '保存成本价').click();
submit = s.p.getByText('确认保存', { exact: true });
}
if (kind === 'discount') {
await button(s.p, '按官方价折扣批量定价').click();
await s.p.getByText('覆盖(新开一版价格)', { exact: true }).click();
submit = modal(s.p).locator('.semi-modal-footer button').last();
}
if (kind === 'advanced') {
await advanced(s);
await modal(s.p).locator('input').first().fill('9');
submit = modal(s.p).locator('.semi-modal-footer button').last();
}
if (kind === 'delete') {
await history(s);
await button(s.p, '删除').click();
submit = modal(s.p).locator('.semi-modal-footer button').last();
}
await submit.evaluate((el) => {
el.click();
el.click();
});
await sleep(100);
assert.equal(s.writes.length, 1);
assert(await button(s.p, '刷新').isDisabled());
assert(await button(s.p, '按官方价折扣批量定价').isDisabled());
assert(
await s.p
.locator('.semi-select')
.first()
.getAttribute('class')
.then((v) => v.includes('disabled')),
);
const w = s.writes[0];
if (['save', 'discount'].includes(kind)) {
assert.equal(w.body.scope, 'channel');
assert.equal(w.body.scope_key, '1');
if (kind === 'save') {
assert.equal(w.body.items[0].model_name, 'model-A');
assert.equal(w.body.items[0].cost_uyuan_per_unit, 7000000);
} else {
assert.deepEqual(w.body.model_names, ['model-A']);
assert.equal(w.body.discount, 0.2);
}
}
if (kind === 'advanced') {
assert.equal(w.body[0].scope_key, '1');
assert.equal(w.body[0].model_name, 'model-A');
assert.equal(w.body[0].id, 101);
assert.equal(w.body[0].cost_uyuan_per_unit, 9000000);
}
if (kind === 'save-delete') assert.deepEqual(w.body.ids, [101]);
if (kind === 'delete') assert(w.path.endsWith('/101'));
s.writeGate.resolve();
await sleep(250);
assert.equal(s.writes.length, 1);
return s;
});
for (const mode of ['reject', 'business-reject', 'network'])
await test('failed delete retains inline draft ' + mode, async () => {
const s = await setup();
await s.goto();
await loaded(s);
await s.p.getByPlaceholder('成本单价').fill('7');
await history(s);
await button(s.p, '删除').click();
s.writeMode = mode;
await modalOk(s);
await until(
() =>
s.requests.filter(
(r) => r.method === 'GET' && r.path.endsWith('scope_models'),
).length === 2,
);
await s.p.waitForFunction(() => {
const input = document.querySelector('input[placeholder="成本单价"]');
return input && !input.disabled;
});
assert.equal(await s.p.getByPlaceholder('成本单价').inputValue(), '7');
assert.equal(await button(s.p, '保存成本价').isEnabled(), true);
assert.equal(s.writes.length, 1, 'failed deletion must not auto-retry');
assert.equal(s.writes[0].method, 'DELETE');
assert.equal(s.writes[0].path, '/api/commission/costs/101');
return s;
});
for (const failRead of [false, true])
await test(
'failed advanced write retains draft, read ' +
(failRead ? 'fails' : 'succeeds'),
async () => {
const s = await setup();
await s.goto();
await loaded(s);
await advanced(s);
await modal(s.p).locator('input').first().fill('9');
await modal(s.p).locator('input').last().fill('keep draft');
s.writeMode = 'reject';
if (failRead) s.readMode = '500';
await modalOk(s);
await sleep(350);
assert.equal(
await modal(s.p).locator('input').first().inputValue(),
'9',
);
assert.equal(
await modal(s.p).locator('input').last().inputValue(),
'keep draft',
);
assert.equal(
await modal(s.p)
.locator('.semi-modal-footer button')
.last()
.isDisabled(),
failRead,
);
assert.equal(s.writes.length, 1);
if (!failRead) {
s.writeMode = 'normal';
await modalOk(s);
await sleep(200);
assert.equal(s.writes.length, 2);
assert.equal(s.writes[1].body[0].cost_uyuan_per_unit, 9000000);
}
return s;
},
);
for (const kind of ['save-delete', 'discount', 'advanced', 'delete'])
await test('stale confirmation after reload rejects ' + kind, async () => {
const s = await setup();
await s.goto();
await loaded(s);
if (kind === 'save-delete') {
await s.p.getByPlaceholder('成本单价').fill('');
await button(s.p, '保存成本价').click();
}
if (kind === 'discount')
await button(s.p, '按官方价折扣批量定价').click();
if (kind === 'advanced') await advanced(s);
if (kind === 'delete') {
await history(s);
await button(s.p, '删除').click();
}
// Native DOM click exercises the underlying refresh handler while an old modal remains mounted.
await button(s.p, '刷新').evaluate((el) => el.click());
if (kind === 'save-delete') {
await confirm(s.p, '放弃修改并刷新');
}
await sleep(150);
const old =
kind === 'save-delete'
? s.p.getByText('确认保存', { exact: true })
: kind === 'delete'
? modal(s.p).locator('.semi-modal-footer button').last()
: modal(s.p).locator('.semi-modal-footer button').last();
// The refresh may unmount the dialog between count and click; inspect
// and click any surviving controls atomically without locator retries.
await old.evaluateAll((elements) => elements.forEach((el) => el.click()));
await noWrites(s);
return s;
});
for (const action of ['edit', 'cancel'])
await test('pending failed advanced PUT ' + action, async () => {
const s = await setup();
await s.goto();
await loaded(s);
await advanced(s);
await modal(s.p).locator('input').first().fill('9');
s.writeMode = 'reject';
s.writeGate = deferred();
await modalOk(s);
await sleep(100);
if (action === 'edit')
await modal(s.p).locator('input').last().fill('typed while pending');
else
await modal(s.p).locator('.semi-modal-footer button').first().click();
s.writeGate.resolve();
await sleep(300);
assert.equal(s.writes.length, 1);
if (action === 'edit')
assert.equal(
await modal(s.p).locator('input').last().inputValue(),
'typed while pending',
);
else
await s.p
.getByText('编辑价格版本', { exact: true })
.waitFor({ state: 'detached' });
return s;
});
await test('mobile meaningful cost view', async () => {
const s = await setup({ viewport: { width: 390, height: 844 } });
await s.goto();
await loaded(s);
await sleep(350);
await s.p.screenshot({ path: out + '/fixed-mobile.png' });
assert.equal(await s.p.locator('vite-error-overlay').count(), 0);
assert.equal(await s.p.title(), 'Cost settings QA');
return s;
});
} finally {
fs.writeFileSync(
out + '/fixed-requests.json',
JSON.stringify(allRequests, null, 2),
);
fs.writeFileSync(
out + '/fixed-console.json',
JSON.stringify(allErrors, null, 2),
);
await browser.close();
await server.close();
console.log(
JSON.stringify({
passed: results.filter((r) => r.pass).length,
total: results.length,
}),
);
if (results.some((r) => !r.pass)) process.exitCode = 1;
}