Files

1871 lines
148 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { expect, test, type Page, type Route } from '@playwright/test';
import { readFileSync } from 'node:fs';
import { createHash } from 'node:crypto';
import { mkdir, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import { createServer } from 'node:http';
import type { ExperienceBuild, ExperienceDraftContent, ExperienceDraftView, ModelAsset } from '../src/api/experience-types';
const sha = 'a'.repeat(40);
const hash = 'b'.repeat(64);
const passed = { status: 'PASSED' as const, errors: [], warnings: [] };
const empty = (): ExperienceDraftContent => ({ wholeModel: null, assembly: null, walking: null });
const result = (overrides: object = {}) => ({ jobId: null, assets: [], draftCandidate: null, build: null, report: passed, ...overrides });
const asset = (overrides: Partial<ModelAsset> = {}): ModelAsset => ({
assetId: 'whole-1', type: 'whole-glb', relativePath: 'robot.glb', bytes: 24, sha256: hash, status: 'READY', downloadUrl: null, ...overrides,
});
const draftView = (overrides: Partial<ExperienceDraftView> = {}): ExperienceDraftView => ({
projectCode: 'project-a', revision: 7, ...empty(), report: null, latestBuild: null, published: null, ...overrides,
});
const buildView = (revision = 7): ExperienceBuild => ({
buildId: 'build-7', draftRevision: revision, status: 'READY', publishable: true, publicationMessage: null, report: passed,
outputs: { glbMainUrl: 'https://resources.example.com/robot.glb', glbConfig: { unit: 'meter', displayQuaternion: [0, 0, 0, 1] }, assemblyManifestUrl: null, walkingManifestUrl: null },
previewUrls: { wholeModel: 'https://community.example.com/preview/whole-1', assembly: null, walking: null },
});
const glb = () => {
const bytes = Buffer.alloc(24);
bytes.writeUInt32LE(0x46546c67, 0); bytes.writeUInt32LE(2, 4); bytes.writeUInt32LE(24, 8);
bytes.writeUInt32LE(4, 12); bytes.writeUInt32LE(0x4e4f534a, 16); bytes.write('{} ', 20);
return bytes;
};
const ok = (route: Route, data: unknown, status = 200) => route.fulfill({ status, json: { code: 'OK', message: '成功', data, requestId: null } });
async function workspace(page: Page, options: { assets?: ModelAsset[]; view?: ExperienceDraftView; missing?: boolean; repoStatus?: string; resourceApi?: boolean; project?: Record<string, unknown> } = {}) {
const state = {
assets: options.assets ?? [], view: options.view ?? draftView(),
calls: [] as { path: string; method: string; body: any }[],
signatureCount: 0, completed: [] as string[],
};
await page.addInitScript(() => localStorage.setItem('vibemake_admin_token', 'test-token'));
await page.route('**/admin-api/**', async (route) => {
const request = route.request();
const path = new URL(request.url()).pathname.replace('/admin-api', '');
const method = request.method();
const body = request.postData() ? request.postDataJSON() : null;
state.calls.push({ path, method, body });
if (path === '/auth/me') return ok(route, { userCode: 'admin', nickname: '管理员', email: 'admin@example.com', role: 'ADMIN' });
if (path === '/projects/types') return ok(route, [{ code: 'WHEELED', name: '轮式机器人' }]);
if (path === '/projects/project-a') return ok(route, {
project: {
...(options.resourceApi ? { modelGlbUrl: null, modelPartsBaseUrl: null, modelPartsFiles: [], assemblyJsonUrl: null, walkingResourcesBaseUrl: null, walkingResourcesFiles: [] } : {}),
projectCode: 'project-a', name: '测试项目', description: '', projectType: 'WHEELED', coverUrl: null,
owner: { userCode: null, nickname: '官方' }, repoStatus: options.repoStatus ?? 'READY', publishStatus: 'PUBLISHED',
publishedCommitSha: sha, publishedAt: null, urdfMainUrl: null, urdfBaseUrl: null,
sourceProjectCode: null, sourceRepositoryUrl: null, sourceLicense: null, likeCount: 0, commentCount: 0,
createdAt: '2026-10-28T00:00:00', updatedAt: '2026-10-28T00:00:00', ...options.project,
}, moderationStatus: 'NORMAL', moderationReason: null, deleted: false,
});
if (path.endsWith('/tree')) return ok(route, { commitSha: sha, path: '', entries: [] });
if (path.endsWith('/commits') || path === '/project-imports' || path === '/projects') return ok(route, { items: [], page: 1, size: 20, total: 0 });
if (path.endsWith('/experience-draft')) {
if (options.missing) return route.fulfill({ status: 404, json: { code: 'NOT_FOUND', message: '接口未实现', data: null } });
if (method === 'PUT') {
expect(body.expectedRevision).toBe(state.view.revision);
for (const field of ['wholeModel', 'assembly', 'walking']) expect(body).toHaveProperty(field);
state.view = { ...state.view, ...body, revision: state.view.revision + 1, latestBuild: null };
}
return ok(route, state.view);
}
if (path.endsWith('/model-assets')) return ok(route, { items: state.assets, nextCursor: null });
if (path.endsWith('/model-assets/signature')) {
state.signatureCount++;
return ok(route, {
batchCode: `batch-${state.signatureCount}`, uploadUrl: 'https://uploads.example.com', expiresAt: '2099-01-01T00:00:00',
files: body.files.map((file: { relativePath: string }) => ({ relativePath: file.relativePath, objectKey: file.relativePath, formFields: { key: `${state.signatureCount}/${file.relativePath}` } })),
});
}
if (path.endsWith('/model-assets/complete')) {
state.completed.push(body.batchCode);
expect(Object.keys(body)).toEqual(['batchCode']);
return ok(route, result({ assets: state.assets }));
}
if (path.endsWith('/publication')) return ok(route, { projectCode: 'project-a' });
return route.fulfill({ status: 404, json: { code: 'NOT_FOUND', message: `未模拟 ${path}`, data: null } });
});
await page.goto('/projects/project-a');
if (!options.repoStatus || options.repoStatus === 'READY') await page.getByRole('tab', { name: '装配与仿真' }).click();
await expect(page.getByRole('button', { name: options.resourceApi ? '刷新资源绑定' : '刷新状态' })).toBeVisible();
if (!options.missing && !options.resourceApi) await expect(page.getByRole('button', { name: '检查并预览', exact: true })).toBeEnabled();
return state;
}
async function chooseFiles(page: Page, files: { name: string; mimeType: string; buffer: Buffer }[], button = '选择整机 GLB') {
if (button === '选择行走资源 ZIP' && !await page.getByRole('button', { name: button, exact: true }).isVisible()) await page.getByText('旧版兼容资源与检查(不改变新表单)', { exact: true }).click();
const chooser = page.waitForEvent('filechooser');
await page.getByRole('button', { name: button, exact: true }).click();
const input = await chooser;
if (await input.element().getAttribute('webkitdirectory') !== null) {
const folder = test.info().outputPath(`selected-parts-${Date.now()}`);
await mkdir(folder, { recursive: true });
for (const file of files) {
const path = join(folder, file.name);
await mkdir(dirname(path), { recursive: true });
await writeFile(path, file.buffer);
}
await input.setFiles(folder);
} else await input.setFiles(files);
}
test('接口待接入时明确提示,可检查文件但不能伪上传或保存', async ({ page }) => {
const state = await workspace(page, { missing: true });
await expect(page.getByText(/模型上传服务尚未接入/)).toBeVisible();
await chooseFiles(page, [{ name: 'robot.glb', mimeType: 'model/gltf-binary', buffer: glb() }]);
await expect(page.getByRole('button', { name: '上传整机模型', exact: true })).toBeDisabled();
await expect(page.getByRole('button', { name: '保存设置', exact: true })).toBeDisabled();
expect(state.calls.filter((call) => call.method !== 'GET')).toHaveLength(0);
});
test('不内置 50 MiB 大小限制,只对 GLB 文件头进行格式检查', async ({ page }) => {
await workspace(page);
const inspected = await page.evaluate(async () => {
const moduleUrl = '/src/utils/modelAssets.ts';
const { inspectModelFiles } = await import(moduleUrl);
const bytes = new Uint8Array(60 * 1024 * 1024);
const header = new DataView(bytes.buffer);
header.setUint32(0, 0x46546c67, true); header.setUint32(4, 2, true); header.setUint32(8, bytes.length, true);
header.setUint32(12, 4, true); header.setUint32(16, 0x4e4f534a, true);
bytes.set(new TextEncoder().encode('{} '), 20);
const file = new File([bytes], 'large.glb');
return inspectModelFiles('whole-glb', [{ file, relativePath: file.name }]);
});
expect(inspected.problems).toEqual([]);
});
test('格式错误不申请签名,原字节上传后自动选用整机但不自动保存或发布', async ({ page }) => {
const state = await workspace(page);
await chooseFiles(page, [{ name: 'fake.glb', mimeType: 'model/gltf-binary', buffer: Buffer.from('not glb') }]);
await expect(page.getByText(/不是完整的 GLB 2.0 文件/)).toBeVisible();
expect(state.signatureCount).toBe(0);
await chooseFiles(page, [{ name: 'robot.glb', mimeType: 'model/gltf-binary', buffer: glb() }]);
await page.route('https://uploads.example.com/', async (route) => {
if (route.request().method() === 'OPTIONS') return route.fulfill({ status: 204 });
expect(route.request().headers().authorization).toBeUndefined();
expect(route.request().headers()['content-type']).toContain('multipart/form-data; boundary=');
expect(route.request().postDataBuffer()!.includes(glb())).toBe(true);
state.assets = [asset()];
return route.fulfill({ status: 204 });
});
await page.getByRole('button', { name: '上传整机模型', exact: true }).click();
await expect(page.getByRole('button', { name: '移除整机模型' })).toBeVisible();
expect(state.completed).toEqual(['batch-1']);
expect(state.calls.filter((call) => call.method === 'PUT')).toHaveLength(0);
expect(state.view.wholeModel).toBeNull();
});
test('批量零件最多四路上传,失败不 complete,手动重试只补传未成功文件', async ({ page }) => {
const state = await workspace(page);
const files = Array.from({ length: 6 }, (_, i) => ({ name: `part-${i}.glb`, mimeType: 'model/gltf-binary', buffer: glb() }));
await chooseFiles(page, files, '选择零件文件夹');
let active = 0, maximum = 0, failedOnce = false;
const attempts = new Map<string, number>();
await page.route('https://uploads.example.com/', async (route) => {
if (route.request().method() === 'OPTIONS') return route.fulfill({ status: 204 });
const key = /name="key"\r\n\r\n([^\r]+)/.exec(route.request().postDataBuffer()!.toString())![1];
attempts.set(key, (attempts.get(key) ?? 0) + 1);
maximum = Math.max(maximum, ++active);
await new Promise((resolve) => setTimeout(resolve, 100));
active--;
if (key.endsWith('part-1.glb') && !failedOnce) { failedOnce = true; return route.fulfill({ status: 503 }); }
state.assets = files.map((file, i) => asset({ assetId: `part-${i}`, type: 'part-glb', relativePath: file.name }));
return route.fulfill({ status: 204 });
});
await page.getByRole('button', { name: '上传零件文件夹', exact: true }).click();
await expect(page.getByText(/OSS 上传失败/)).toBeVisible();
expect(state.completed).toEqual([]);
const successful = [...attempts.keys()].filter((key) => !key.endsWith('part-1.glb'));
await page.getByRole('button', { name: '上传零件文件夹', exact: true }).click();
await expect.poll(() => state.completed.length).toBe(1);
expect(maximum).toBeLessThanOrEqual(4);
expect(state.signatureCount).toBe(1);
for (const key of successful) expect(attempts.get(key)).toBe(1);
expect(attempts.get('1/part-1.glb')).toBe(2);
});
test('上传断网后核对结果,新批次重传,不覆盖结果未知的旧对象', async ({ page }) => {
const state = await workspace(page);
await chooseFiles(page, [{ name: 'robot.glb', mimeType: 'model/gltf-binary', buffer: glb() }]);
let calls = 0;
await page.route('https://uploads.example.com/', async (route) => {
if (route.request().method() === 'OPTIONS') return route.fulfill({ status: 204 });
if (++calls === 1) return route.abort('failed');
state.assets = [asset()];
return route.fulfill({ status: 204 });
});
await page.getByRole('button', { name: '上传整机模型', exact: true }).click();
await expect(page.getByText(/操作结果待核对/)).toBeVisible();
await expect(page.getByRole('button', { name: '上传整机模型', exact: true })).toBeDisabled();
await page.getByRole('button', { name: '刷新状态' }).click();
await expect(page.getByRole('button', { name: '上传整机模型', exact: true })).toBeEnabled();
await page.getByRole('button', { name: '上传整机模型', exact: true }).click();
await expect.poll(() => state.completed.length).toBe(1);
expect(state.signatureCount).toBe(2);
expect(state.completed).toEqual(['batch-2']);
});
test('任意项目的机器人/运行器可导入,确认候选后才保存完整草稿', async ({ page }) => {
const walking = asset({ assetId: 'walking-custom', type: 'walking-zip', relativePath: 'custom-walking.zip' });
const state = await workspace(page, { assets: [walking] });
const candidate = { ...empty(), walking: { enabled: true, packageAssetId: walking.assetId, robotId: 'my-project-robot', runtimeProfile: 'custom-runner-v9' } };
await page.route('**/experience-imports', async (route) => {
expect(route.request().postDataJSON()).toEqual({ sourceAssetId: walking.assetId, kind: 'walking', expectedRevision: 7 });
return ok(route, result({ draftCandidate: candidate }));
});
await page.getByRole('button', { name: '读取已上传的行走包' }).click();
await expect(page.getByRole('dialog', { name: '确认使用行走演示' })).toBeVisible();
expect(state.view.walking).toBeNull();
await page.getByRole('dialog').getByRole('button', { name: '确认使用', exact: true }).click();
await page.getByText('查看行走包识别信息', { exact: true }).click();
await expect(page.locator('.experience-upload-walking').getByText('custom-runner-v9', { exact: true })).toBeVisible();
expect(state.calls.filter((call) => call.method === 'PUT')).toHaveLength(0);
await page.getByRole('button', { name: '保存设置', exact: true }).click();
await expect(page.getByText('展示设置已保存,发布后才会更新前台', { exact: true })).toBeVisible();
expect(state.view.walking).toEqual(candidate.walking);
expect(state.view.wholeModel).toBeNull();
expect(state.view.assembly).toBeNull();
expect(state.calls.filter((call) => call.path.endsWith('/publication'))).toHaveLength(0);
});
test('独立 JSON 用完整路径与哈希匹配,同名左右零件不误绑', async ({ page }) => {
const left = asset({ assetId: 'left', type: 'part-glb', relativePath: 'left/arm.glb' });
const right = asset({ assetId: 'right', type: 'part-glb', relativePath: 'right/arm.glb' });
const manifest = asset({ assetId: 'manifest', type: 'assembly-manifest', relativePath: 'manifest.json', metadata: {
manifestFiles: [left, right].map((item) => ({ path: item.relativePath, bytes: item.bytes, sha256: item.sha256 })),
} });
await workspace(page, { assets: [left, right, manifest] });
let bindings: unknown;
await page.route('**/experience-imports', async (route) => {
bindings = route.request().postDataJSON().assetBindings;
return ok(route, result());
});
await page.getByRole('button', { name: '读取已上传的拼装步骤' }).click();
await expect.poll(() => bindings).toEqual([{ path: 'left/arm.glb', assetId: 'left' }, { path: 'right/arm.glb', assetId: 'right' }]);
});
test('409 草稿冲突保留绑定和输入,不覆盖服务端', async ({ page }) => {
const state = await workspace(page, { assets: [asset()] });
await page.route('**/experience-draft', async (route) => {
if (route.request().method() === 'GET') return ok(route, state.view);
await route.fulfill({ status: 409, json: { code: 'REVISION_CONFLICT', message: '草稿版本已变化', data: null, requestId: 'conflict-7' } });
});
await page.getByRole('button', { name: '使用已上传的整机', exact: true }).click();
await page.getByRole('button', { name: '保存设置', exact: true }).click();
await expect(page.getByText(/本地修改已保留/)).toBeVisible();
await expect(page.getByText(/有尚未保存的展示设置/)).toBeVisible();
await expect(page.getByRole('button', { name: '移除整机模型' })).toBeVisible();
expect(state.view.wholeModel).toBeNull();
});
test('生成资源版本串行轮询,发布同时携带代码 SHA、buildId 和 revision', async ({ page }, testInfo) => {
const state = await workspace(page, { assets: [asset()] });
const built = buildView();
await page.route('**/experience-builds', (route) => {
expect(route.request().postDataJSON()).toEqual({ draftRevision: 7 });
return ok(route, result({ jobId: 'job-build' }), 202);
});
let queries = 0;
await page.route('**/experience-jobs/job-build', (route) => {
const complete = ++queries > 1;
return ok(route, { jobId: 'job-build', status: complete ? 'SUCCEEDED' : 'RUNNING', phase: 'VALIDATING', message: '正在校验引用', report: complete ? passed : null, result: complete ? result({ build: built }) : null });
});
await page.getByRole('button', { name: '检查并预览', exact: true }).click();
await expect(page.getByText('正在校验引用', { exact: true })).toBeVisible();
await expect(page.getByRole('button', { name: '发布到前台', exact: true })).toBeEnabled({ timeout: 8000 });
await page.screenshot({ path: testInfo.outputPath('models-and-demos.png'), fullPage: true });
await expect(page.getByRole('link', { name: '预览整机模型' })).toHaveAttribute('href', built.previewUrls.wholeModel!);
await page.getByRole('button', { name: '发布到前台', exact: true }).click();
await expect(page.getByRole('dialog').getByText('代码版本未变化,本次仍会发布新的装配与仿真快照')).toBeVisible();
await page.getByRole('dialog').getByRole('button', { name: '确认发布此版本' }).click();
await expect.poll(() => state.calls.filter((call) => call.path.endsWith('/publication')).length).toBe(1);
expect(state.calls.find((call) => call.path.endsWith('/publication'))!.body).toEqual({ commitSha: sha, experienceBuildId: 'build-7', expectedDraftRevision: 7 });
expect(queries).toBe(2);
});
test('普通代码发布不附带资源构建参数,保留旧发布绑定', async ({ page }) => {
const state = await workspace(page);
await page.getByRole('button', { name: '更新发布', exact: true }).click();
await expect(page.getByRole('dialog').getByText(/本次只更新代码,保留当前已发布的装配与仿真/)).toBeVisible();
await page.getByRole('dialog').getByRole('button', { name: '确认发布此版本' }).click();
await expect.poll(() => state.calls.filter((call) => call.path.endsWith('/publication')).length).toBe(1);
expect(state.calls.find((call) => call.path.endsWith('/publication'))!.body).toEqual({ commitSha: sha });
});
test('清空/禁用只改草稿,保存时显式传 null,已发布资源仍保留', async ({ page }) => {
const built = buildView();
const view = draftView({ wholeModel: { assetId: 'whole-1', displayQuaternion: [0, 0, 0, 1] },
published: { releaseId: 'release-old', commitSha: sha, draftRevision: 6, experienceBuildId: 'old', publishedAt: '2026-10-28T00:00:00', ...built.outputs } });
const state = await workspace(page, { view });
await page.getByRole('button', { name: '移除整机模型' }).click();
await page.getByRole('button', { name: /确\s*定/ }).click();
await page.getByRole('button', { name: '保存设置', exact: true }).click();
await expect(page.getByText('展示设置已保存,发布后才会更新前台', { exact: true })).toBeVisible();
expect(state.view.wholeModel).toBeNull();
expect(state.view.published!.glbMainUrl).toBe(built.outputs.glbMainUrl);
expect(state.calls.filter((call) => call.path.endsWith('/publication'))).toHaveLength(0);
});
test('仓库未就绪时仍可先管理模型资源,但不能发布', async ({ page }) => {
const state = await workspace(page, { repoStatus: 'CREATING' });
await expect(page.getByRole('button', { name: '检查并预览', exact: true })).toBeEnabled();
await expect(page.getByRole('button', { name: '选择整机 GLB', exact: true })).toBeEnabled();
expect(state.calls.some((call) => call.path.endsWith('/experience-draft'))).toBe(true);
});
test('任务查询断网后只恢复 GET,不重复构建,离开页面停止查询', async ({ page }) => {
await workspace(page);
let builds = 0, queries = 0;
await page.route('**/experience-builds', (route) => { builds++; return ok(route, result({ jobId: 'pending' }), 202); });
await page.route('**/experience-jobs/pending', (route) => {
if (++queries === 1) return route.abort('failed');
return ok(route, { jobId: 'pending', status: 'RUNNING', phase: 'VALIDATING', message: '正在校验模型文件', report: null, result: null });
});
await page.getByRole('button', { name: '检查并预览', exact: true }).click();
await expect(page.getByText(/获取处理状态失败/)).toBeVisible();
await page.getByRole('button', { name: '继续查看处理结果' }).click();
await expect(page.getByText('正在校验模型文件', { exact: true })).toBeVisible();
await page.getByRole('menuitem', { name: /项目管理/ }).click();
await expect(page).toHaveURL('/projects');
const afterLeave = queries;
await page.waitForTimeout(3300);
expect(queries).toBe(afterLeave);
expect(builds).toBe(1);
});
test('服务端校验失败展示文件定位,不绑定候选且不允许发布', async ({ page }) => {
await workspace(page);
const report = { status: 'FAILED', errors: [{ code: 'MISSING_ASSET', message: '左臂模型未上传', path: 'parts/arm.glb', partId: 'left-arm', stepId: 'step-2' }], warnings: [] };
await page.route('**/experience-builds', (route) => ok(route, result({ report })));
await page.getByRole('button', { name: '检查并预览', exact: true }).click();
await expect(page.getByText('左臂模型未上传', { exact: true })).toBeVisible();
await expect(page.getByText('文件:parts/arm.glb', { exact: true })).toBeVisible();
await expect(page.getByRole('button', { name: '发布到前台', exact: true })).toHaveCount(0);
});
test('新建项目可同时选择整机和零件,创建跳转后文件完整保留', async ({ page }, testInfo) => {
await workspace(page, { missing: true });
await page.goto('/projects/new');
for (const label of ['选择整机 GLB', '选择零件文件夹', '制作装配流程', '选择行走资源文件夹']) {
await expect(page.getByRole('button', { name: label, exact: true })).toBeVisible();
}
await expect(page.getByRole('combobox', { name: '上传资源类型' })).toHaveCount(0);
await page.getByRole('textbox', { name: '项目名称' }).fill('带模型的新项目');
await page.getByRole('combobox', { name: '项目类型' }).click();
await page.getByText('轮式机器人', { exact: true }).click();
await chooseFiles(page, [{ name: '完整机器人.glb', mimeType: 'model/gltf-binary', buffer: glb() }]);
await chooseFiles(page, [{ name: '左臂.glb', mimeType: 'model/gltf-binary', buffer: glb() }, { name: '右臂.glb', mimeType: 'model/gltf-binary', buffer: glb() }], '选择零件文件夹');
await expect(page.getByRole('cell', { name: '完整机器人.glb', exact: true })).toBeVisible();
await expect(page.getByRole('cell', { name: '左臂.glb', exact: true })).toBeVisible();
await page.screenshot({ path: testInfo.outputPath('create-project-models.png'), fullPage: true });
let creates = 0;
await page.route('**/admin-api/projects', async (route) => {
creates++;
expect(route.request().method()).toBe('POST');
expect(route.request().postDataJSON().project.name).toBe('带模型的新项目');
expect(route.request().postDataJSON()).not.toHaveProperty('files');
return ok(route, { projectCode: 'project-a' });
});
await page.getByRole('button', { name: '创建项目并继续上传' }).click();
await expect(page).toHaveURL('/projects/project-a?tab=experiences');
await expect(page.getByRole('tab', { name: '装配与仿真' })).toHaveAttribute('aria-selected', 'true');
for (const name of ['完整机器人.glb', '左臂.glb', '右臂.glb']) await expect(page.getByRole('cell', { name, exact: true })).toBeVisible();
await expect(page.getByText(/已保留新建项目时选好的文件/)).toBeVisible();
await expect(page.getByRole('button', { name: '上传全部已选文件' })).toBeDisabled();
expect(creates).toBe(1);
});
test('整机和零件独立选择,一次上传后整机自动选用且零件仍独立保存', async ({ page }, testInfo) => {
const state = await workspace(page);
await chooseFiles(page, [{ name: '整机.glb', mimeType: 'model/gltf-binary', buffer: glb() }]);
await chooseFiles(page, [{ name: '脚部.glb', mimeType: 'model/gltf-binary', buffer: glb() }], '选择零件文件夹');
await page.route('https://uploads.example.com/', async (route) => {
if (route.request().method() === 'OPTIONS') return route.fulfill({ status: 204 });
const input = state.calls.filter((call) => call.path.endsWith('/model-assets/signature')).at(-1)!.body;
const uploaded = asset({ assetId: input.type === 'whole-glb' ? 'new-whole' : 'new-part', type: input.type, relativePath: input.files[0].relativePath });
state.assets.push(uploaded);
return route.fulfill({ status: 204 });
});
await page.getByRole('button', { name: '上传全部已选文件' }).click();
await expect.poll(() => state.completed.length).toBe(2);
await expect(page.getByRole('button', { name: '移除整机模型' })).toBeVisible();
await expect(page.locator('.experience-upload-parts').getByRole('cell', { name: '脚部.glb', exact: true })).toBeVisible();
expect(state.calls.filter((call) => call.path.endsWith('/model-assets/signature')).map((call) => call.body.type)).toEqual(['whole-glb', 'part-glb']);
expect(state.calls.filter((call) => call.method === 'PUT')).toHaveLength(0);
await page.screenshot({ path: testInfo.outputPath('manage-models-separated.png'), fullPage: true });
await page.getByRole('button', { name: '保存设置', exact: true }).click();
await expect.poll(() => state.view.wholeModel?.assetId).toBe('new-whole');
expect(state.view.assembly).toBeNull();
});
test('导入拼装步骤只更新拼装区域,不覆盖已经选好的整机', async ({ page }) => {
const part = asset({ assetId: 'part-1', type: 'part-glb', relativePath: 'base.glb' });
const manifest = asset({ assetId: 'assembly-json', type: 'assembly-manifest', relativePath: 'assembly.json', metadata: { manifestFiles: [{ path: part.relativePath, bytes: part.bytes, sha256: part.sha256 }] } });
const state = await workspace(page, { assets: [asset(), part, manifest] });
await page.getByRole('button', { name: '使用已上传的整机', exact: true }).click();
const candidate = { ...empty(), assembly: {
enabled: true, title: '安装流程', unit: 'meter', referenceAssetId: null, displayQuaternion: [0, 0, 0, 1],
parts: [{ id: 'base', name: '底座', assetId: 'part-1', parentId: null, position: [0, 0, 0], quaternion: [0, 0, 0, 1], scale: [1, 1, 1], installOffset: [0, 0.08, 0] }],
steps: [{ id: 'step-1', label: '安装底座', parts: ['base'] }],
} };
await page.route('**/experience-imports', (route) => ok(route, result({ draftCandidate: candidate })));
await page.getByRole('button', { name: '读取已上传的拼装步骤' }).click();
await page.getByRole('dialog', { name: '确认使用拼装步骤' }).getByRole('button', { name: '确认使用', exact: true }).click();
await expect(page.getByRole('button', { name: '移除整机模型' })).toBeVisible();
await expect(page.getByRole('button', { name: '移除拼装步骤' })).toBeVisible();
await page.getByRole('button', { name: '保存设置', exact: true }).click();
await expect.poll(() => state.view.assembly?.title).toBe('安装流程');
expect(state.view.wholeModel?.assetId).toBe('whole-1');
});
test('检查并预览自动保存整机设置,再使用新的设置版本生成检查结果', async ({ page }) => {
const state = await workspace(page, { assets: [asset()] });
await page.getByRole('button', { name: '使用已上传的整机', exact: true }).click();
let revision = 0;
await page.route('**/experience-builds', async (route) => {
revision = route.request().postDataJSON().draftRevision;
expect(state.view.wholeModel?.assetId).toBe('whole-1');
return ok(route, result({ build: buildView(revision) }));
});
await page.getByRole('button', { name: '检查并预览', exact: true }).click();
await expect(page.getByRole('button', { name: '发布到前台', exact: true })).toBeEnabled();
expect(revision).toBe(8);
expect(state.calls.filter((call) => call.path.endsWith('/publication'))).toHaveLength(0);
});
test('新项目仓库由准备中变为可用,刷新后整机和零件选择不丢失', async ({ page }) => {
const options = { repoStatus: 'CREATING' };
await workspace(page, options);
await chooseFiles(page, [{ name: '待上传整机.glb', mimeType: 'model/gltf-binary', buffer: glb() }]);
await chooseFiles(page, [{ name: '待上传零件.glb', mimeType: 'model/gltf-binary', buffer: glb() }], '选择零件文件夹');
options.repoStatus = 'READY';
await page.getByRole('button', { name: '刷新状态' }).click();
await expect(page.getByRole('tab', { name: '文件', exact: true })).toBeVisible();
await expect(page.getByRole('tab', { name: '装配与仿真' })).toHaveAttribute('aria-selected', 'true');
await expect(page.getByRole('cell', { name: '待上传整机.glb', exact: true })).toBeVisible();
await expect(page.getByRole('cell', { name: '待上传零件.glb', exact: true })).toBeVisible();
});
// 真正可由 GLTFLoader 解析的彩色立方体,节点自带位姿;不依赖外部网络模型。
function editorGlb(x = 0, color = [0.18, 0.65, 0.45, 1]) {
const positions = new Float32Array([-.1,-.1,-.1, .1,-.1,-.1, .1,.1,-.1, -.1,.1,-.1, -.1,-.1,.1, .1,-.1,.1, .1,.1,.1, -.1,.1,.1]);
const indices = new Uint16Array([0,2,1,0,3,2,4,5,6,4,6,7,0,1,5,0,5,4,2,3,7,2,7,6,1,2,6,1,6,5,3,0,4,3,4,7]);
const bin = Buffer.concat([Buffer.from(positions.buffer), Buffer.from(indices.buffer)]);
const json = Buffer.from(JSON.stringify({ asset: { version: '2.0' }, scene: 0, scenes: [{ nodes: [0] }], nodes: [{ mesh: 0, translation: [x, 0, 0] }],
meshes: [{ primitives: [{ attributes: { POSITION: 0 }, indices: 1, material: 0 }] }], materials: [{ pbrMetallicRoughness: { baseColorFactor: color, metallicFactor: .1, roughnessFactor: .55 } }],
buffers: [{ byteLength: bin.length }], bufferViews: [{ buffer: 0, byteOffset: 0, byteLength: positions.byteLength }, { buffer: 0, byteOffset: positions.byteLength, byteLength: indices.byteLength }],
accessors: [{ bufferView: 0, componentType: 5126, count: 8, type: 'VEC3', min: [-.1,-.1,-.1], max: [.1,.1,.1] }, { bufferView: 1, componentType: 5123, count: 36, type: 'SCALAR' }],
}));
const padded = Buffer.concat([json, Buffer.alloc((4 - json.length % 4) % 4, 32)]), bytes = Buffer.alloc(12 + 8 + padded.length + 8 + bin.length);
bytes.writeUInt32LE(0x46546c67, 0); bytes.writeUInt32LE(2, 4); bytes.writeUInt32LE(bytes.length, 8);
bytes.writeUInt32LE(padded.length, 12); bytes.writeUInt32LE(0x4e4f534a, 16); padded.copy(bytes, 20);
bytes.writeUInt32LE(bin.length, 20 + padded.length); bytes.writeUInt32LE(0x004e4942, 24 + padded.length); bin.copy(bytes, 28 + padded.length);
return bytes;
}
async function editorDialog(page: Page) {
await page.getByRole('button', { name: '制作装配流程', exact: true }).click();
const dialog = page.getByRole('dialog', { name: '装配流程 可视化编排' });
await expect(dialog).toBeVisible();
await expect(dialog).toHaveCSS('animation-name', 'none');
await expect(dialog.locator('.assembly-loading')).toHaveCount(0, { timeout: 15000 });
await expect(dialog.locator('.assembly-preview-problem')).toHaveCount(0);
return dialog;
}
async function generatedManifest(page: Page) {
const dialog = page.getByRole('dialog', { name: '装配流程 可视化编排' });
if (!await dialog.getByRole('button', { name: '下载系统生成的 JSON' }).isVisible()) await dialog.getByText('更多操作', { exact: true }).click();
const download = page.waitForEvent('download');
await dialog.getByRole('button', { name: '下载系统生成的 JSON' }).click();
const stream = await (await download).createReadStream();
const chunks = []; for await (const chunk of stream!) chunks.push(chunk);
return JSON.parse(Buffer.concat(chunks).toString());
}
test('简化装配:默认空场景,右侧搜索点选即安装,顺序可调整撤销,原材质文件保留', async ({ page }, testInfo) => {
const state = await workspace(page, { missing: true });
const parts = ['左腿', '躯干', '右腿'].map((name, i) => ({ name: `${name}.glb`, mimeType: 'model/gltf-binary', buffer: editorGlb((i - 1) * .35) }));
await chooseFiles(page, parts, '选择零件文件夹');
const dialog = await editorDialog(page);
await expect(dialog.getByText('从第一个选择开始')).toBeVisible();
await expect(dialog.getByRole('button', { name: '保存装配流程' })).toBeDisabled();
await dialog.getByRole('textbox', { name: '搜索组件或零件' }).fill('躯干');
await expect(dialog.locator('.assembly-part-row')).toHaveCount(1);
await dialog.getByRole('button', { name: '安装零件 躯干', exact: true }).click();
await expect(dialog.getByText('1 / 1 · 安装 躯干')).toBeVisible();
await dialog.getByRole('textbox', { name: '搜索组件或零件' }).fill('');
await dialog.getByRole('button', { name: '安装零件 左腿', exact: true }).click();
await dialog.getByRole('button', { name: '查看零件 躯干', exact: true }).click();
await dialog.getByRole('tab', { name: '步骤 2', exact: true }).click();
await dialog.getByRole('button', { name: '上移第 2 步' }).click();
await expect(dialog.locator('.assembly-step-list > li').first()).toContainText('左腿');
await dialog.getByRole('button', { name: '撤销', exact: true }).click();
await expect(dialog.locator('.assembly-step-list > li').first()).toContainText('躯干');
await dialog.getByRole('button', { name: '重做', exact: true }).click();
const manifest = await generatedManifest(page);
expect(manifest.steps.map((s: any) => s.label)).toEqual(['安装 左腿', '安装 躯干']);
expect(manifest.parts).toHaveLength(2);
expect(manifest.componentPlan).toBeUndefined();
manifest.files.forEach((f: any) => { const input = parts.find(p => p.name === f.path)!; expect(f.bytes).toBe(input.buffer.length); expect(f.sha256).toBe(createHash('sha256').update(input.buffer).digest('hex')); });
await dialog.getByRole('button', { name: '播放全部步骤' }).click();
await expect(dialog.getByText('2 / 2 · 安装 躯干')).toBeVisible();
await page.screenshot({ path: testInfo.outputPath('assembly-editor-dark.png'), fullPage: true });
await dialog.getByRole('button', { name: '保存装配流程', exact: true }).click();
expect(state.calls.filter(c => c.method !== 'GET')).toHaveLength(0);
});
test('双视窗:左侧参考可点选隐藏、搜索恢复,显隐与右侧步骤、撤销和保存相互独立', async ({ page }, testInfo) => {
await workspace(page, { missing: true });
const files = ['左腿', '躯干', '右腿'].map((name, i) => ({ name: `${name}.glb`, mimeType: 'model/gltf-binary', buffer: editorGlb((i - 1) * .35) }));
await chooseFiles(page, files, '选择零件文件夹');
const dialog = await editorDialog(page), reference = dialog.locator('.assembly-reference-stage'), work = dialog.locator('.assembly-stage');
await expect(reference.locator('canvas[aria-label="整机参考三维预览"]')).toBeVisible();
await expect(work.locator('canvas[aria-label="装配模型三维预览"]')).toBeVisible();
await expect(reference.getByText('3 / 3 显示', { exact: true })).toBeVisible();
await expect(work.getByText('从第一个选择开始', { exact: true })).toBeVisible();
// Locator 点击会等待弹窗位置稳定,避免在展开动画中取到临时坐标。
await reference.locator('canvas').click();
await expect(reference.getByText('2 / 3 显示', { exact: true })).toBeVisible();
await reference.getByRole('button', { name: '参考零件显隐', exact: true }).click();
const visibility = page.getByRole('group', { name: '参考模型零件显隐' });
await visibility.getByRole('button', { name: '显示参考零件 躯干', exact: true }).click();
await visibility.getByRole('textbox', { name: '搜索参考零件', exact: true }).fill('左腿');
await visibility.getByRole('button', { name: '隐藏参考零件 左腿', exact: true }).click();
await visibility.locator('.ant-segmented').getByText('已隐藏', { exact: true }).click();
await expect(visibility.locator('.assembly-reference-visibility-list > button')).toHaveCount(1);
await reference.getByRole('button', { name: '参考零件显隐', exact: true }).click();
await dialog.getByRole('button', { name: '恢复整机参考', exact: true }).click();
await expect(reference.getByText('3 / 3 显示', { exact: true })).toBeVisible();
await reference.getByRole('button', { name: '参考零件显隐', exact: true }).click();
await visibility.locator('.ant-segmented').getByText('全部', { exact: true }).click();
await visibility.getByRole('textbox', { name: '搜索参考零件', exact: true }).fill('躯干');
await visibility.getByRole('button', { name: '隐藏参考零件 躯干', exact: true }).click();
await reference.getByRole('button', { name: '参考零件显隐', exact: true }).click();
await dialog.getByRole('button', { name: '安装零件 左腿', exact: true }).click();
await expect(reference.getByText('2 / 3 显示', { exact: true })).toBeVisible();
await expect(dialog.getByText('1 / 1 · 安装 左腿', { exact: true })).toBeVisible();
await dialog.getByRole('button', { name: '撤销', exact: true }).click();
await expect(reference.getByText('2 / 3 显示', { exact: true })).toBeVisible();
await dialog.getByRole('button', { name: '重做', exact: true }).click();
await dialog.getByRole('button', { name: '查看零件 左腿', exact: true }).click();
const json = await generatedManifest(page);
expect(json.parts.map((p: any) => p.name)).toEqual(['左腿']); expect(json.steps).toHaveLength(1);
expect(json.files[0].sha256).toBe(createHash('sha256').update(files[0].buffer).digest('hex'));
expect(Object.keys(json).some(key => /hidden|visibility/i.test(key))).toBe(false);
await reference.getByRole('button', { name: '全部显示', exact: true }).click();
await expect(dialog.getByText('1 / 1 · 安装 左腿', { exact: true })).toBeVisible();
await page.setViewportSize({ width: 1366, height: 768 });
await expect.poll(() => dialog.locator('.ant-modal-body').evaluate(el => el.scrollHeight <= el.clientHeight + 1)).toBe(true);
await page.screenshot({ path: testInfo.outputPath('assembly-dual-view.png'), fullPage: true });
});
test('可视化编辑保留导入位姿和父子关系,保存为真实草稿并校验父件顺序', async ({ page }) => {
const bytes = editorGlb();
const assets = ['base', 'leg'].map((id) => asset({ assetId: id, type: 'part-glb', relativePath: `${id}.glb`, bytes: bytes.length, downloadUrl: `https://models.example.com/${id}.glb` }));
await page.route('https://models.example.com/**', (route) => route.fulfill({ body: bytes, contentType: 'model/gltf-binary', headers: { 'Access-Control-Allow-Origin': '*' } }));
const assembly: NonNullable<ExperienceDraftContent['assembly']> = { enabled: true, title: '导入装配', unit: 'meter', referenceAssetId: null, displayQuaternion: [-Math.SQRT1_2,0,0,Math.SQRT1_2], parts: [
{ id: 'base', name: '底座', assetId: 'base', parentId: null, position: [1.1,2.2,3.3], quaternion: [0,Math.SQRT1_2,0,Math.SQRT1_2], scale: [1.5,2,3], installOffset: [0,.15,0] },
{ id: 'leg', name: '左腿', assetId: 'leg', parentId: 'base', position: [.1,.2,.3], quaternion: [0,0,0,1], scale: [1,1,1], installOffset: [.1,.2,.3] },
], steps: [{ id: 'step-base', label: '安装底座', parts: ['base'] }, { id: 'step-leg', label: '安装左腿', parts: ['leg'] }] };
const state = await workspace(page, { assets, view: draftView({ assembly }) });
const dialog = await editorDialog(page);
await dialog.getByRole('tab', { name: '步骤 2', exact: true }).click();
await dialog.getByRole('button', { name: '上移第 2 步', exact: true }).click();
await expect(dialog.getByText('请把 左腿 的父零件安排在同一步或更早安装。', { exact: true })).toBeVisible();
await expect(dialog.getByRole('button', { name: '保存装配流程', exact: true })).toBeDisabled();
await dialog.getByRole('button', { name: '撤销', exact: true }).click();
const generated = await generatedManifest(page);
expect(generated.displayQuaternion).toEqual(assembly.displayQuaternion);
generated.parts.forEach((part: any, i: number) => { const { assetId, ...original } = assembly.parts[i]; expect(part).toEqual({ ...original, file: `${assetId}.glb` }); });
await dialog.getByRole('button', { name: '保存装配流程', exact: true }).click();
await page.getByRole('button', { name: '保存设置', exact: true }).click();
await expect(page.getByText('展示设置已保存', { exact: true })).toBeVisible();
const put = state.calls.find((c) => c.method === 'PUT' && c.path.endsWith('/experience-draft'))!;
expect(put.body.assembly).toEqual(assembly);
});
test('本地制作流程在零件上传后自动关联服务器资源,构建前不提交临时编号', async ({ page }) => {
const bytes = editorGlb();
const { createHash } = await import('node:crypto');
const uploaded = asset({ assetId: 'uploaded-leg', type: 'part-glb', relativePath: 'leg.glb', bytes: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex') });
const state = await workspace(page);
await page.route('https://uploads.example.com/**', (route) => route.fulfill({ status: 204 }));
await chooseFiles(page, [{ name: 'leg.glb', mimeType: 'model/gltf-binary', buffer: bytes }], '选择零件文件夹');
const dialog = await editorDialog(page);
await dialog.getByRole('button', { name: '安装零件 leg', exact: true }).click();
await dialog.getByRole('button', { name: '保存装配流程', exact: true }).click();
await expect(page.getByRole('button', { name: '保存设置', exact: true })).toBeDisabled();
expect(state.calls.filter((c) => c.method === 'PUT')).toHaveLength(0);
state.assets = [uploaded];
await page.getByRole('button', { name: '上传零件文件夹', exact: true }).click();
await expect(page.getByRole('button', { name: '保存设置', exact: true })).toBeEnabled();
await page.getByRole('button', { name: '保存设置', exact: true }).click();
await expect(page.getByText('展示设置已保存', { exact: true })).toBeVisible();
expect(state.view.assembly?.parts[0].assetId).toBe('uploaded-leg');
expect(JSON.stringify(state.calls.filter((c) => c.method === 'PUT'))).not.toContain('local-part-glb');
});
test('新建项目中制作的装配流程与原文件一起带入项目管理', async ({ page }) => {
const state = await workspace(page, { missing: true });
await page.goto('/projects/new');
await page.getByRole('textbox', { name: '项目名称' }).fill('带可视化流程的项目');
await page.getByRole('combobox', { name: '项目类型' }).click();
await page.getByText('轮式机器人', { exact: true }).click();
const bytes = editorGlb();
await chooseFiles(page, [{ name: '零件.glb', mimeType: 'model/gltf-binary', buffer: bytes }], '选择零件文件夹');
const dialog = await editorDialog(page);
await dialog.getByRole('button', { name: '安装零件 零件', exact: true }).click();
await dialog.getByRole('button', { name: '保存装配流程', exact: true }).click();
await expect(page.getByText('已制作 1 个步骤,创建项目后会保留。', { exact: true })).toBeVisible();
await page.route('**/admin-api/projects', (route) => ok(route, { projectCode: 'project-a' }));
await page.getByRole('button', { name: '创建项目并继续上传' }).click();
await expect(page).toHaveURL('/projects/project-a?tab=experiences');
await expect(page.getByRole('cell', { name: '零件.glb', exact: true })).toBeVisible();
await expect(page.getByText('1 个零件实例 · 1 步', { exact: true })).toBeVisible();
const reopened = await editorDialog(page);
await reopened.getByRole('tab', { name: '步骤 1', exact: true }).click();
await expect(reopened.locator('.assembly-step-list')).toContainText('安装 零件');
expect(state.calls.filter((c) => c.method === 'PUT')).toHaveLength(0);
});
test('统一编排:组件和散件同屏选择,组件成员自动选中,重复成员不能再加入', async ({ page }, testInfo) => {
await workspace(page, { missing: true });
await chooseFiles(page, ['头壳', '头盖', '躯干', '手臂'].map((name, i) => ({ name: `${name}.glb`, mimeType: 'model/gltf-binary', buffer: editorGlb(i * .2) })), '选择零件文件夹');
const dialog = await editorDialog(page);
await dialog.getByRole('button', { name: '创建组件', exact: true }).first().click();
await page.getByRole('textbox', { name: '独立组件名称' }).fill('头部');
await page.getByRole('button', { name: '创建并制作' }).click();
for (const name of ['头壳', '头盖']) await dialog.getByRole('button', { name: `安装零件 ${name}`, exact: true }).click();
await dialog.getByText('步骤编排', { exact: true }).first().click();
await expect(dialog.getByText('直接装配', { exact: true })).toHaveCount(0);
await expect(dialog.getByText('组件装配', { exact: true })).toHaveCount(0);
const component = dialog.getByRole('checkbox', { name: '选择组件 头部', exact: true });
await component.check();
await expect(component).toBeChecked();
await expect(dialog.getByRole('button', { name: '查看零件 头壳', exact: true })).toHaveAttribute('aria-pressed', 'true');
await expect(dialog.getByRole('button', { name: '查看零件 头盖', exact: true })).toHaveAttribute('aria-pressed', 'true');
await dialog.getByRole('button', { name: '查看零件 头壳', exact: true }).click();
await expect(dialog.getByRole('tab', { name: '步骤 1', exact: true })).toBeVisible();
await dialog.getByRole('button', { name: '安装零件 躯干', exact: true }).click();
await dialog.getByRole('button', { name: '安装零件 手臂', exact: true }).click();
const json = await generatedManifest(page);
expect(json.steps.map((s: any) => s.label)).toEqual(['安装组件 头部', '安装 躯干', '安装 手臂']);
expect(json.steps.flatMap((s: any) => s.parts)).toHaveLength(4);
expect(new Set(json.steps.flatMap((s: any) => s.parts)).size).toBe(4);
expect(json.steps.every((s: any) => s.scene === undefined)).toBe(true);
await component.uncheck();
await expect(dialog.getByRole('button', { name: '安装零件 头壳', exact: true })).toHaveAttribute('aria-pressed', 'false');
await dialog.getByRole('button', { name: '安装零件 头壳', exact: true }).click();
await expect(component).toBeDisabled();
await dialog.getByRole('button', { name: '查看零件 头壳', exact: true }).click({ button: 'right' });
await expect(component).toBeEnabled();
await component.check();
const changed = await generatedManifest(page);
expect(changed.steps.map((s: any) => s.label)).toEqual(['安装 躯干', '安装 手臂', '安装组件 头部']);
await page.setViewportSize({ width: 1366, height: 768 });
await expect.poll(() => dialog.locator('.ant-modal-body').evaluate(el => el.scrollHeight <= el.clientHeight + 1)).toBe(true);
await page.screenshot({ path: testInfo.outputPath('unified-assembly-picker.png'), fullPage: true });
});
test('分段标记:新拼装只重置起点,后续自动累加;继续拼装可接回旧进度,保存回读不展开逐步标记', async ({ page }) => {
await workspace(page, { missing: true });
await chooseFiles(page, ['A', 'B', 'C', 'D', 'E', 'F'].map(name => ({ name: `${name}.glb`, mimeType: 'model/gltf-binary', buffer: editorGlb() })), '选择零件文件夹');
const dialog = await editorDialog(page);
for (const name of ['A', 'B', 'C', 'D', 'E', 'F']) await dialog.getByRole('button', { name: `安装零件 ${name}`, exact: true }).click();
await dialog.getByRole('tab', { name: '步骤 6', exact: true }).click();
await dialog.getByRole('button', { name: '查看第 3 步 安装 C', exact: true }).click();
await dialog.getByRole('button', { name: '标记新拼装', exact: true }).click();
await dialog.getByRole('button', { name: '查看第 5 步 安装 E', exact: true }).click();
await dialog.getByRole('button', { name: '标记继续拼装', exact: true }).click();
await dialog.getByRole('combobox', { name: '续装基准步骤' }).press('ArrowDown');
await page.getByRole('option', { name: '第 2 步 · 安装 B', exact: true }).click();
const json = await generatedManifest(page);
expect(json.steps.filter((s: any) => s.scene)).toHaveLength(2);
expect(json.steps[2].scene).toEqual({ mode: 'independent' });
expect(json.steps[4].scene).toEqual({ mode: 'continue', base: { kind: 'step', id: json.steps[1].id } });
expect(json.steps[5].scene).toBeUndefined();
const resolved = await page.evaluate(async document => {
const rp = '/src/utils/boundAssembly.ts', wp = '/src/utils/assemblyWorkflow.ts', ep = '/src/utils/assemblyEditor.ts';
const { restoreAssemblyDocument } = await import(rp), { assemblyStages, workflowForSave, removeWorkflowStep } = await import(wp), { assemblyManifest } = await import(ep);
const sources = document.files.map((f: any) => ({ asset: { assetId: f.path, type: 'part-glb', relativePath: f.path, bytes: f.bytes, sha256: f.sha256, status: 'READY' } }));
const session = restoreAssemblyDocument(document, { sources });
let protectedMessage = ''; try { removeWorkflowStep(session.assembly, session.assembly.steps[1].id); } catch (e) { protectedMessage = String(e); }
const removed = removeWorkflowStep(session.assembly, session.assembly.steps[3].id);
return { counts: assemblyStages(session.assembly).map((s: any) => s.parts.length), entering: assemblyStages(session.assembly).map((s: any) => s.entering.length), json: assemblyManifest(workflowForSave(session.assembly), sources, document), protectedMessage, afterRemove: assemblyStages(removed).map((s: any) => s.parts.length) };
}, json);
expect(resolved.counts).toEqual([1, 2, 1, 2, 3, 4]); expect(resolved.entering).toEqual([1,1,1,1,1,1]);
expect(resolved.json).toEqual(json); expect(resolved.protectedMessage).toContain('续装基准'); expect(resolved.afterRemove).toEqual([1,2,1,3,4]);
await dialog.getByRole('button', { name: '查看第 4 步 安装 D', exact: true }).click();
await dialog.getByRole('button', { name: '预览到此步', exact: true }).click();
await expect(dialog.getByText('1 / 6 · 安装 A', { exact: true })).toBeVisible();
await dialog.getByRole('button', { name: '暂停预览', exact: true }).click();
await expect(dialog.getByText('从第 1 步预览至第 4 步 · 已暂停', { exact: true })).toBeVisible();
await dialog.getByRole('button', { name: '继续预览', exact: true }).click();
await expect(dialog.getByText('4 / 6 · 安装 D', { exact: true })).toBeVisible();
await expect(dialog.getByRole('button', { name: '预览到此步', exact: true })).toBeVisible();
await dialog.getByRole('button', { name: '查看第 3 步 安装 C', exact: true }).click();
await dialog.getByRole('button', { name: '取消标记', exact: true }).click();
const inherited = await generatedManifest(page);
expect(inherited.steps.filter((s: any) => s.scene)).toHaveLength(1);
});
test('旧版组件整理:分组与嵌套连接变为组件层级,总装不重复安装成员,位姿和文件保持不变', async ({ page }) => {
await workspace(page, { resourceApi: true });
const checked = await page.evaluate(async () => {
const sp = '/src/utils/assemblySimplify.ts', wp = '/src/utils/assemblyWorkflow.ts';
const { simplifyAssembly } = await import(sp), { assemblyStages, workflowForSave } = await import(wp);
const part = (id: string) => ({ id, name: id, assetId: id, parentId: null, position: [1,2,3], quaternion: [0,0,0,1], scale: [1,1,1], installOffset: [0,.08,0] });
const old: any = { enabled: true, title: '旧版', unit: 'meter', referenceAssetId: null, displayQuaternion: [0,0,0,1], parts: ['head','body','leg'].map(part), steps: [{id:'h',label:'头',parts:['head']},{id:'b',label:'躯干',parts:['body']},{id:'l',label:'腿',parts:['leg'],scene:{mode:'continue',base:{kind:'connection',id:'joined'}}}], componentPlan:{version:1,components:[{id:'hc',name:'头',parts:['head']},{id:'bc',name:'躯干',parts:['body']}],connections:[{id:'joined',name:'头与躯干',members:['bc','hc'],installOffset:[0,.08,0]}]} };
const converted = workflowForSave(simplifyAssembly(old));
return { original: old, converted, counts: assemblyStages(converted).map((s: any) => s.parts.length) };
});
expect(checked.original.componentPlan.connections).toHaveLength(1);
expect(checked.converted.componentPlan).toBeUndefined(); expect(checked.converted.componentLibrary.components).toHaveLength(3);
expect(checked.converted.steps).toHaveLength(2); expect(checked.counts).toEqual([2,3]);
expect(checked.converted.parts).toEqual(checked.original.parts);
expect(new Set(checked.converted.steps.flatMap((s: any) => s.parts)).size).toBe(3);
});
test('资源自动关联拒绝版本歧义,上传成功后不再改绑已确定的资源', async ({ page }) => {
await workspace(page, { missing: true });
const ids = await page.evaluate(async () => {
const path = '/src/utils/assemblyEditor.ts';
const { bindAssemblySession, pendingAssemblyFiles } = await import(path);
const local = { assetId: 'local-part-glb-test', type: 'part-glb', relativePath: 'part.glb', bytes: 3, sha256: 'a'.repeat(64), status: 'READY', downloadUrl: null };
const remote1 = { ...local, assetId: 'remote-one' }, remote2 = { ...local, assetId: 'remote-two' };
const session = { assembly: { enabled: true, title: '装配', unit: 'meter', referenceAssetId: null, displayQuaternion: [0,0,0,1], parts: [{ id: 'part', name: '零件', assetId: local.assetId, parentId: null, position: [0,0,0], quaternion: [0,0,0,1], scale: [1,1,1], installOffset: [0,.08,0] }], steps: [{ id: 'step', label: '安装', parts: ['part'] }] }, sources: [{ asset: local, file: new File(['abc'], 'part.glb') }] };
const ambiguous = bindAssemblySession(session, [remote1, remote2]);
const confirmed = bindAssemblySession(ambiguous, [remote1]);
const later = bindAssemblySession(confirmed, [remote2]);
return { ambiguous: pendingAssemblyFiles(ambiguous), confirmed: pendingAssemblyFiles(confirmed), finalId: later.assembly.parts[0].assetId };
});
expect(ids).toEqual({ ambiguous: true, confirmed: false, finalId: 'remote-one' });
});
// 行走上传清单以随项目发布的配置为准,避免测试和界面各写一套策略名。
const walkingSpecPath = new URL('../src/config/walking-upload-requirements.json', import.meta.url);
const walkingTestSpec = JSON.parse(readFileSync(walkingSpecPath, 'utf8'));
const walkingAsset = () => asset({ assetId: 'walking-duck', type: 'walking-zip', relativePath: 'microduck-walking.zip', bytes: 12786579, metadata: { robotId: 'microduck-alpha', runtimeProfile: 'microduck-alpha-v1' } });
function walkingReport(overrides: any = {}) {
return { status: 'FAILED' as const, errors: [{ code: 'MISSING_POLICY', message: '缺少左脚踢球策略', path: 'policies/ball_kick_left.onnx' }], warnings: [], walking: {
sourceAssetId: 'walking-duck', robotId: 'microduck-alpha', runtimeProfile: 'microduck-alpha-v1',
items: walkingTestSpec.requiredFiles.map((file: any) => ({ key: file.path, path: file.path, state: file.id === 'kickL' ? 'missing' : 'found_pending_validation' })),
stages: [{ id: 'identify', state: 'passed' }, { id: 'integrity', state: 'mismatch', message: '资源包缺少必需文件' }, { id: 'compatibility', state: 'not_checked' }, { id: 'runtime', state: 'not_checked' }, { id: 'review', state: 'not_checked' }],
...overrides,
} };
}
test('默认运动上传说明是通用的,旧鸭子七策略只在主动选择专用示例后展示', async ({ page }, testInfo) => {
await workspace(page, { missing: true });
const card = page.locator('.experience-upload-walking');
await card.getByText('旧版兼容资源与检查(不改变新表单)', { exact: true }).click();
await expect(card.getByText('按当前资源包配置识别', { exact: true })).toBeVisible();
await expect(card.getByText('通常需要准备', { exact: true })).toBeVisible();
await expect(card.getByText('左脚踢球策略', { exact: true })).toHaveCount(0);
await expect(card.getByText('7 个全部必备', { exact: true })).toHaveCount(0);
await expect(card.getByText(/上传服务尚未接入,暂不能读取包配置/)).toBeVisible();
await card.screenshot({ path: testInfo.outputPath('walking-generic-desktop.png') });
await card.getByRole('button', { name: '查看准备说明', exact: true }).click();
const drawer = page.getByRole('dialog', { name: '机器人运动演示:准备说明与示例' });
await expect(drawer.getByText('左脚踢球策略', { exact: true })).toHaveCount(0);
await expect(drawer.getByText(/不是所有机器人都需要 GLB/)).toBeVisible();
await drawer.getByText('请选择参考示例', { exact: true }).click();
await page.getByText('旧版 Microduck v1:专用兼容示例', { exact: true }).click();
await expect(drawer.getByText('仅适用于旧版 Microduck v1,不能作为所有机器人的上传要求。', { exact: true })).toBeVisible();
await expect(drawer.getByText('左脚踢球策略', { exact: true })).toBeVisible();
const downloading = page.waitForEvent('download');
await drawer.getByRole('link', { name: '下载旧版 Microduck 示例 ZIP', exact: true }).click();
const download = await downloading;
expect(download.suggestedFilename()).toBe('microduck-walking.zip');
const stream = await download.createReadStream(), chunks = [];
for await (const chunk of stream!) chunks.push(chunk);
const zip = Buffer.concat(chunks), { createHash } = await import('node:crypto');
expect(zip.length).toBe(walkingTestSpec.example.zipBytes);
expect(createHash('sha256').update(zip).digest('hex')).toBe(walkingTestSpec.example.zipSha256);
const reqDownload = page.waitForEvent('download');
await drawer.getByRole('button', { name: '下载文件要求说明', exact: true }).click();
const requirements = await reqDownload;
expect(requirements.suggestedFilename()).toBe('机器人运动演示文件要求.txt');
});
test('ZIP 头检查不冒充包内容、兼容性或试运行通过', async ({ page }) => {
await workspace(page, { missing: true });
await chooseFiles(page, [{ name: 'test.zip', mimeType: 'application/zip', buffer: Buffer.from([0x50,0x4b,3,4,0,0,0,0]) }], '选择行走资源 ZIP');
const card = page.locator('.experience-upload-walking'), checks = card.getByRole('region', { name: '行走资源检查结果' });
await expect(checks.getByText('已选择文件,等待上传服务接入,尚未检查资源内容。', { exact: true })).toBeVisible();
await expect(checks.locator('.walking-check-row')).toHaveCount(0);
await expect(checks.locator('.walking-check-row .ant-tag').filter({ hasText: /^未检查$/ })).toHaveCount(0);
await expect(checks.locator('.walking-stage').filter({ hasText: '实际试运行' })).toContainText('未执行');
await expect(card.getByRole('button', { name: '上传并读取行走包', exact: true })).toBeDisabled();
await expect(checks.getByText('通过', { exact: true })).toHaveCount(0);
});
test('缺少第七个策略显示中文用途与修复提示,换包后清空旧检查状态', async ({ page }) => {
const report = walkingReport();
const view = draftView({ walking: { enabled: true, packageAssetId: 'walking-duck', robotId: 'microduck-alpha', runtimeProfile: 'microduck-alpha-v1' }, report,
published: { ...buildView().outputs, walkingManifestUrl: 'https://resources.example.com/old/manifest.json', releaseId: 'old-release', commitSha: sha, draftRevision: 5, experienceBuildId: 'old-build', publishedAt: '2026-10-28T00:00:00' } });
const state = await workspace(page, { assets: [walkingAsset()], view });
const checks = page.getByRole('region', { name: '行走资源检查结果' });
await expect(checks.locator('[data-check-key="kickL"]')).toContainText('左脚踢球策略');
await expect(checks.locator('[data-check-key="kickL"]')).toContainText('缺失');
await expect(checks.getByText(/7 个文件,6 个已确认找到/)).toBeVisible();
await expect(checks.getByText('缺少左脚踢球策略 policies/ball_kick_left.onnx。仅旧版 Microduck 播放器启动需要全部 7 个策略,请补齐后重新上传。', { exact: true })).toBeVisible();
await expect(checks.locator('.walking-stage').filter({ hasText: '实际试运行' })).toContainText('未执行');
expect(state.calls.filter((call) => call.method !== 'GET')).toHaveLength(0);
await checks.getByRole('button', { name: '查看完整检查报告', exact: true }).click();
await expect(page.getByRole('dialog', { name: '行走资源完整检查报告' }).getByText('缺少左脚踢球策略', { exact: true })).toBeVisible();
await page.getByRole('dialog', { name: '行走资源完整检查报告' }).getByRole('button', { name: '关闭报告', exact: true }).click();
await chooseFiles(page, [{ name: 'microduck-walking.zip', mimeType: 'application/zip', buffer: Buffer.from([0x50,0x4b,3,4,0,0,0,0]) }], '选择行走资源 ZIP');
await expect(checks.getByText('文件格式检查通过,尚未检查包内内容。', { exact: true })).toBeVisible();
await expect(checks.locator('.walking-check-row .ant-tag').filter({ hasText: /^未检查$/ })).toHaveCount(0);
await expect(checks.getByText('通过', { exact: true })).toHaveCount(0);
expect(state.view.published?.walkingManifestUrl).toBe('https://resources.example.com/old/manifest.json');
});
test('旧的总报告通过和其他包的逐项结果,不会推断当前行走包已运行', async ({ page }) => {
const view = draftView({ walking: { enabled: true, packageAssetId: 'walking-duck', robotId: 'microduck-alpha', runtimeProfile: 'microduck-alpha-v1' }, report: passed });
await workspace(page, { assets: [walkingAsset()], view });
const checks = page.getByRole('region', { name: '行走资源检查结果' });
await expect(checks.getByText(/尚未返回当前包的解析与逐项检查报告/)).toBeVisible();
await expect(checks.locator('.walking-check-row .ant-tag').filter({ hasText: /^未检查$/ })).toHaveCount(15);
const wrongReport = walkingReport({ sourceAssetId: 'other-package', items: walkingTestSpec.requiredFiles.map((f: any) => ({ key: f.path, state: 'passed' })), stages: [{ id: 'runtime', state: 'passed' }] });
await page.route('**/experience-draft', (route) => ok(route, { ...view, report: { ...wrongReport, status: 'PASSED', errors: [] } }));
await page.getByRole('button', { name: '刷新状态', exact: true }).click();
await expect(checks.locator('.walking-check-row .ant-tag').filter({ hasText: /^未检查$/ })).toHaveCount(15);
await expect(checks.locator('.walking-stage').filter({ hasText: '实际试运行' })).toContainText('未执行');
await expect(checks.getByText('通过', { exact: true })).toHaveCount(0);
});
test('行走导入校验失败保留原 ZIP 和逐项错误,不覆盖已发布资源', async ({ page }) => {
const state = await workspace(page, { assets: [walkingAsset()] });
await page.route('https://uploads.example.com/**', (route) => route.fulfill({ status: 204 }));
await page.route('**/experience-imports', (route) => ok(route, result({ report: walkingReport() })));
await chooseFiles(page, [{ name: 'bad-walking.zip', mimeType: 'application/zip', buffer: Buffer.from([0x50,0x4b,3,4,0,0,0,0]) }], '选择行走资源 ZIP');
await page.getByRole('button', { name: '上传并读取行走包', exact: true }).click();
const checks = page.getByRole('region', { name: '行走资源检查结果' });
await expect(checks.locator('[data-check-key="kickL"]')).toContainText('缺失');
await expect(page.getByRole('cell', { name: 'bad-walking.zip', exact: true })).toBeVisible();
await expect(checks.getByText(/仅旧版 Microduck 播放器启动需要全部 7 个策略,请补齐后重新上传/)).toBeVisible();
await expect(page.getByRole('dialog', { name: '确认使用行走演示' })).toHaveCount(0);
expect(state.calls.filter((call) => call.path.endsWith('/publication') || call.method === 'PUT')).toHaveLength(0);
expect(state.signatureCount).toBe(1);
});
test('手机新建页使用行走文件夹入口,不强制配置或固定动作且不横向溢出', async ({ page }, testInfo) => {
await page.setViewportSize({ width: 390, height: 844 });
await workspace(page, { missing: true });
await page.goto('/projects/new');
const card = page.locator('.experience-upload-walking');
await expect(card.getByRole('button', { name: '选择行走资源文件夹', exact: true })).toBeVisible();
await expect(card.getByText('左脚踢球策略', { exact: true })).toHaveCount(0);
await expect(card.getByRole('button', { name: /ZIP/ })).toHaveCount(0);
await card.scrollIntoViewIfNeeded();
await card.screenshot({ path: testInfo.outputPath('walking-folder-mobile.png') });
expect(await card.evaluate((element) => element.scrollWidth <= element.clientWidth + 1)).toBe(true);
});
test('旧报告只映射精确路径错误,缺清单有补齐建议,其他文件不自动通过', async ({ page }) => {
const legacy = { status: 'FAILED' as const, errors: [{ code: 'MANIFEST_NOT_FOUND', message: '未找到资源清单', path: 'manifest.json' }], warnings: [] };
await workspace(page, { assets: [walkingAsset()], view: draftView({ walking: { enabled: true, packageAssetId: 'walking-duck', robotId: 'microduck-alpha', runtimeProfile: 'microduck-alpha-v1' }, report: legacy }) });
const checks = page.getByRole('region', { name: '行走资源检查结果' });
await expect(checks.locator('[data-check-key="manifest"]')).toContainText('缺失');
await expect(checks.getByText('未找到 manifest.json。请选择配套工具生成的完整行走包,或下载旧版 Microduck 示例查看结构。', { exact: true }).last()).toBeVisible();
await expect(checks.locator('.walking-check-row .ant-tag').filter({ hasText: /^未检查$/ })).toHaveCount(14);
await expect(checks.getByText('通过', { exact: true })).toHaveCount(0);
});
const robotPackageReference = JSON.parse(readFileSync(new URL('../public/examples/robot-package/microban.robot.json', import.meta.url), 'utf8'));
function genericWalkingReport(options: { id?: string; policy?: string } = {}) {
const config = structuredClone(robotPackageReference);
config.id = options.id ?? config.id;
if (options.policy) config.skills.find((s: any) => s.controller.type === 'onnx').controller.policy = options.policy;
const requirements = [
{ key: 'entry', label: '机器人配置', path: 'robot.json', category: 'config', required: true },
{ key: 'model', label: '物理模型', path: config.model, category: 'model', required: true },
...config.assets.map((a: any) => ({ key: a.path, label: '模型依赖', path: a.path, category: 'dependency', required: true })),
...config.skills.filter((s: any) => s.controller.type === 'onnx').map((s: any) => ({ key: s.controller.policy, label: '动作策略', path: s.controller.policy, category: 'policy', required: true, skills: ['行走'] })),
];
return { status: 'PASSED' as const, errors: [] as { code: string; message: string; path: string }[], warnings: [], walking: {
sourceAssetId: 'generic-package', robotId: config.id, runtimeProfile: 'generic', format: 'robot-package' as const,
adapter: config.adapter, entry: 'robot.json', requirements, capabilities: config.skills.map((s: any) => ({ id: s.id, label: s.controller.type === 'oscillator' ? '转头' : '行走', controller: s.controller.type, policyPath: s.controller.policy, supported: true })),
items: requirements.map((r) => ({ key: r.key, path: r.path, state: 'found_pending_validation' as const })),
stages: [{ id: 'identify' as const, state: 'passed' as const }, { id: 'runtime' as const, state: 'not_checked' as const }],
communityRuntime: { status: 'pending' as const, message: '社区的通用包入口待部署' },
} };
}
function genericWalkingView(report = genericWalkingReport()) {
const build = { ...buildView(), report, previewUrls: { ...buildView().previewUrls, walking: 'https://community.example.com/preview/generic-package' } };
return draftView({ report, latestBuild: build, walking: { enabled: true, packageAssetId: report.walking.sourceAssetId, robotId: report.walking.robotId, runtimeProfile: 'generic' } });
}
test('通用包按报告显示一个行走策略和内置转头,不要求小鸭子其他动作或 GLB', async ({ page }, testInfo) => {
const report = genericWalkingReport();
const state = await workspace(page, { assets: [asset({ assetId: 'generic-package', type: 'walking-zip', relativePath: 'microban.zip' })], view: genericWalkingView(report) });
const card = page.locator('.experience-upload-walking'), checks = card.getByRole('region', { name: '行走资源检查结果' });
await expect(checks.getByRole('region', { name: '本包声明动作' })).toContainText('行走');
await expect(checks.getByRole('region', { name: '本包声明动作' })).toContainText('转头');
await expect(checks.getByText('内置控制器,无需策略文件', { exact: true })).toBeVisible();
await expect(checks.getByText(/本包声明的策略:1 个文件/)).toBeVisible();
await expect(checks.locator('.walking-check-row')).toHaveCount(robotPackageReference.assets.length + 3);
for (const forbidden of ['左脚踢球策略', '右脚踢球策略', '翻滚策略', '起身恢复策略', 'controller.json', 'robot/mjlab/microduck.glb', 'robot/mjlab/kinematics.json']) await expect(card.getByText(forbidden, { exact: true })).toHaveCount(0);
await expect(checks.getByText('社区播放器尚未接入此包格式,当前可作为待适配资源。', { exact: true })).toBeVisible();
await expect(page.getByRole('link', { name: '预览行走演示', exact: true })).toHaveCount(0);
await expect(page.getByRole('button', { name: '发布到前台', exact: true })).toBeDisabled();
expect(state.calls.filter((call) => call.method !== 'GET')).toHaveLength(0);
await card.screenshot({ path: testInfo.outputPath('walking-package-specific.png') });
});
test('同一 generic 适配器的新机器人和自定义策略路径不需要按名字改前端', async ({ page }) => {
const report = genericWalkingReport({ id: 'my-new-robot', policy: 'controllers/steady_stride.onnx' });
await workspace(page, { assets: [asset({ assetId: 'generic-package', type: 'walking-zip' })], view: genericWalkingView(report) });
const checks = page.getByRole('region', { name: '行走资源检查结果' });
await expect(checks.locator('.walking-robot')).toContainText('my-new-robot');
await expect(checks.locator('.walking-check-row').filter({ hasText: 'controllers/steady_stride.onnx' })).toHaveCount(1);
await expect(checks.getByText('policies/walk.onnx', { exact: true })).toHaveCount(0);
await expect(checks.getByText('左脚踢球策略', { exact: true })).toHaveCount(0);
await expect(checks.getByText(/1 个文件/)).toBeVisible();
});
test('通用包 LFS 指针错误不能因为文件存在而显示通过', async ({ page }) => {
const report = genericWalkingReport();
report.errors = [{ code: 'LFS_POINTER', message: '行走策略是 131 字节的 Git LFS 占位文件', path: 'policies/walk.onnx' }];
// 即使目录识别阶段找到了文件,明确的内容错误也应显示为不匹配。
const view = genericWalkingView(report);
view.report = { ...report, status: 'FAILED' };
await workspace(page, { assets: [asset({ assetId: 'generic-package', type: 'walking-zip' })], view });
const checks = page.getByRole('region', { name: '行走资源检查结果' });
await expect(checks.locator('[data-check-key="policies/walk.onnx"]')).toContainText('不匹配');
await expect(checks.getByText('发现 Git LFS 占位文件:policies/walk.onnx。这不是完整模型数据,请从原仓库取得实际大文件后重新上传。', { exact: true })).toBeVisible();
});
test('浏览旧鸭子模板不会把通用包的当前文件要求切换为七策略', async ({ page }) => {
await workspace(page, { assets: [asset({ assetId: 'generic-package', type: 'walking-zip' })], view: genericWalkingView() });
const card = page.locator('.experience-upload-walking');
await card.getByRole('button', { name: '查看示例模板', exact: true }).click();
const drawer = page.getByRole('dialog', { name: '机器人运动演示:准备说明与示例' });
await drawer.getByText('请选择参考示例', { exact: true }).click();
await page.getByText('旧版 Microduck v1:专用兼容示例', { exact: true }).click();
await expect(drawer.getByText('左脚踢球策略', { exact: true })).toBeVisible();
await drawer.getByRole('button', { name: 'Close', exact: true }).click();
const checks = card.getByRole('region', { name: '行走资源检查结果' });
await expect(checks.getByText(/本包声明的策略:1 个文件/)).toBeVisible();
await expect(card.getByText('左脚踢球策略', { exact: true })).toHaveCount(0);
});
test('多个动作引用同一策略只要求一份文件,保留动作关联', async ({ page }) => {
const report = genericWalkingReport();
const policy = report.walking.requirements.find((r) => r.category === 'policy')!;
report.walking.requirements.push({ ...policy, key: 'second-skill-policy', skills: ['另一行走模式'] });
await workspace(page, { assets: [asset({ assetId: 'generic-package', type: 'walking-zip' })], view: genericWalkingView(report) });
const checks = page.getByRole('region', { name: '行走资源检查结果' });
await expect(checks.locator('.walking-check-row').filter({ hasText: 'policies/walk.onnx' })).toHaveCount(1);
await expect(checks.locator('.walking-check-row').filter({ hasText: 'policies/walk.onnx' })).toContainText('行走、另一行走模式');
await expect(checks.getByText(/本包声明的策略:1 个文件/)).toBeVisible();
});
test('新版专用 Robot Package 显示声明的九策略,不能因旧 profile 回落到七策略', async ({ page }) => {
const report = genericWalkingReport({ id: 'microduck-legs' });
report.walking.adapter = 'microduck'; report.walking.runtimeProfile = 'microduck-alpha-v1';
const paths = [...walkingTestSpec.requiredFiles.filter((f: any) => f.path.endsWith('.onnx')).map((f: any) => f.path), ...walkingTestSpec.optionalExtension.paths.filter((p: string) => p.endsWith('.onnx'))];
report.walking.requirements = paths.map((path: string) => ({ key: path, label: '本包声明策略', path, category: 'policy', required: true }));
report.walking.items = paths.map((path: string) => ({ key: path, path, state: 'found_pending_validation' }));
await workspace(page, { assets: [asset({ assetId: 'generic-package', type: 'walking-zip' })], view: genericWalkingView(report) });
const card = page.locator('.experience-upload-walking'), checks = card.getByRole('region', { name: '行走资源检查结果' });
await expect(checks.getByText(/本包声明的策略:9 个文件/)).toBeVisible();
await expect(checks.locator('.walking-check-row')).toHaveCount(9);
await expect(card.getByText('旧版 Microduck 演示包专用清单', { exact: true })).toHaveCount(0);
await expect(checks.getByText('policies/BEST_roller.onnx', { exact: true })).toBeVisible();
});
test('新建和管理只保留零件文件夹入口,高级导入只有 JSON', async ({ page }) => {
await workspace(page);
for (const path of ['/projects/project-a?tab=experiences', '/projects/new']) {
await page.goto(path);
const parts = page.locator('.experience-upload-parts'), assembly = page.locator('.experience-upload-assembly');
await expect(parts.getByRole('button', { name: '选择零件文件夹', exact: true })).toBeVisible();
await expect(parts.getByRole('button')).toHaveCount(1);
await expect(page.getByRole('button', { name: '选择零件 ZIP', exact: true })).toHaveCount(0);
await expect(page.getByRole('button', { name: '选择零件 GLB(可多选)', exact: true })).toHaveCount(0);
await expect(assembly.getByRole('button', { name: '制作装配流程', exact: true })).toBeDisabled();
await assembly.getByText('高级导入(JSON)', { exact: true }).click();
await expect(assembly.getByRole('button', { name: '选择拼装步骤 JSON', exact: true })).toBeVisible();
await expect(page.getByRole('button', { name: '选择完整装配 ZIP', exact: true })).toHaveCount(0);
await expect(page.getByText(/引用的零件需先在上方“零件模型”通过文件夹上传/)).toBeVisible();
}
});
test('文件夹仅保留 GLB 和相对路径,装配直接使用同一批零件,不另选文件', async ({ page }, testInfo) => {
const state = await workspace(page, { missing: true, assets: [asset({ assetId: 'whole-only', relativePath: '整机.glb' })] });
await expect(page.getByRole('button', { name: '制作装配流程', exact: true })).toBeDisabled();
const files = [
{ name: 'left/leg.glb', mimeType: 'model/gltf-binary', buffer: editorGlb(-.3) },
{ name: 'right/leg.GLB', mimeType: 'model/gltf-binary', buffer: editorGlb(.3) },
{ name: 'README.md', mimeType: 'text/plain', buffer: Buffer.from('目录说明') },
{ name: '配置.json', mimeType: 'application/json', buffer: Buffer.from('{}') },
{ name: 'left/._leg.glb', mimeType: 'application/octet-stream', buffer: Buffer.from('macOS metadata') },
];
await chooseFiles(page, files, '选择零件文件夹');
const parts = page.locator('.experience-upload-parts');
await expect(parts.getByRole('cell', { name: 'left/leg.glb', exact: true })).toBeVisible();
await expect(parts.getByRole('cell', { name: 'right/leg.GLB', exact: true })).toBeVisible();
await expect(parts.getByRole('cell', { name: 'README.md', exact: true })).toHaveCount(0);
await expect(parts.getByText('已忽略 3 个非零件文件,仅使用文件夹中的 GLB。', { exact: true })).toBeVisible();
let extraChoosers = 0;
page.on('filechooser', () => extraChoosers++);
const dialog = await editorDialog(page);
await expect(dialog.locator('.assembly-part-row')).toHaveCount(2);
await expect(dialog.getByText('从第一个选择开始')).toBeVisible();
await dialog.locator('.assembly-part-row').nth(0).click();
await dialog.locator('.assembly-part-row').nth(1).click();
const manifest = await generatedManifest(page);
expect(manifest.files.map((f: any) => f.path).sort()).toEqual(['left/leg.glb', 'right/leg.GLB']);
expect(manifest.parts).toHaveLength(2);
expect(extraChoosers).toBe(0);
expect(state.signatureCount).toBe(0);
await page.screenshot({ path: testInfo.outputPath('folder-parts-assembly.png'), fullPage: true });
});
test('没有 GLB 的文件夹明确报错,清除后可重新选择有效零件文件夹', async ({ page }) => {
await workspace(page, { missing: true });
await chooseFiles(page, [{ name: 'README.md', mimeType: 'text/plain', buffer: Buffer.from('not a model') }], '选择零件文件夹');
await expect(page.getByText('该文件夹中没有可用的 GLB 零件文件,请重新选择零件文件夹。', { exact: true })).toBeVisible();
await expect(page.getByRole('button', { name: '制作装配流程', exact: true })).toBeDisabled();
await page.getByRole('button', { name: '清除已选零件模型文件', exact: true }).click();
await expect(page.getByText('该文件夹中没有可用的 GLB 零件文件,请重新选择零件文件夹。', { exact: true })).toHaveCount(0);
await chooseFiles(page, [{ name: 'base.glb', mimeType: 'model/gltf-binary', buffer: editorGlb() }], '选择零件文件夹');
await expect(page.getByRole('button', { name: '制作装配流程', exact: true })).toBeEnabled();
});
test('目录批量签名仅提交 GLB,并保留同名左右零件的子路径', async ({ page }) => {
const state = await workspace(page);
const bytes = editorGlb(), bodies: Buffer[] = [];
// 真实接收 multipart;CDP 的 postDataBuffer 会省略磁盘 File 的二进制内容。
const receiver = createServer(async (request, response) => {
response.setHeader('Access-Control-Allow-Origin', '*');
response.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
if (request.method === 'POST') {
const chunks = []; for await (const chunk of request) chunks.push(Buffer.from(chunk));
bodies.push(Buffer.concat(chunks));
}
response.writeHead(204); response.end();
});
await new Promise<void>((resolve) => receiver.listen(0, '127.0.0.1', resolve));
try {
const address = receiver.address() as { port: number };
await page.route('**/model-assets/signature', (route) => {
const body = route.request().postDataJSON();
state.signatureCount++;
state.calls.push({ path: '/projects/project-a/model-assets/signature', method: 'POST', body });
return ok(route, { batchCode: 'batch-1', uploadUrl: `http://127.0.0.1:${address.port}/upload`, expiresAt: '2099-01-01T00:00:00', files: body.files.map((f: any) => ({ relativePath: f.relativePath, objectKey: f.relativePath, formFields: { key: `1/${f.relativePath}` } })) });
});
await chooseFiles(page, [
{ name: 'left/leg.glb', mimeType: 'model/gltf-binary', buffer: bytes },
{ name: 'right/leg.glb', mimeType: 'model/gltf-binary', buffer: bytes },
{ name: 'notes.txt', mimeType: 'text/plain', buffer: Buffer.from('ignore this') },
], '选择零件文件夹');
await page.getByRole('button', { name: '上传零件文件夹', exact: true }).click();
await expect.poll(() => state.completed.length).toBe(1);
const signatures = state.calls.filter((c) => c.path.endsWith('/model-assets/signature'));
expect(signatures).toHaveLength(1);
expect(signatures[0].body.type).toBe('part-glb');
expect(signatures[0].body.files.map((f: any) => f.relativePath).sort()).toEqual(['left/leg.glb', 'right/leg.glb']);
expect(bodies).toHaveLength(2);
for (const body of bodies) { expect(body.includes(bytes)).toBe(true); expect(body.toString()).not.toContain('ignore this'); }
expect(bodies.map((body) => /name="key"\r\n\r\n([^\r]+)/.exec(body.toString())![1]).sort()).toEqual(['1/left/leg.glb', '1/right/leg.glb']);
} finally { receiver.closeAllConnections(); await new Promise<void>((resolve, reject) => receiver.close((error) => error ? reject(error) : resolve())); }
});
test('JSON 导入不能把整机模型自动关联为零件,也不提供整机候选', async ({ page }) => {
const whole = asset({ assetId: 'whole-only', relativePath: 'base.glb' });
const json = asset({ assetId: 'steps-json', type: 'assembly-manifest', relativePath: 'steps.json', metadata: { manifestFiles: [{ path: whole.relativePath, bytes: whole.bytes, sha256: whole.sha256 }] } });
const state = await workspace(page, { assets: [whole, json] });
await page.getByRole('button', { name: '读取已上传的拼装步骤', exact: true }).click();
const dialog = page.getByRole('dialog', { name: '核对步骤文件中的零件' });
await expect(dialog.getByText(/整机模型不会作为零件候选/)).toBeVisible();
await expect(dialog.getByRole('button', { name: '确认并读取', exact: true })).toBeDisabled();
expect(state.calls.filter((c) => c.path.endsWith('/experience-imports'))).toHaveLength(0);
});
test('步骤 JSON 上传读取已有零件,不上传装配 ZIP 或再次上传零件', async ({ page }) => {
const part = asset({ assetId: 'existing-part', type: 'part-glb', relativePath: 'left/leg.glb' });
const sourceJson = { schemaVersion: 1, kind: 'assembly', unit: 'meter', files: [{ path: part.relativePath, bytes: part.bytes, sha256: part.sha256 }], parts: [{ id: 'left-leg', file: part.relativePath }], steps: [{ id: 'step', label: '安装左腿', parts: ['left-leg'] }] };
const bytes = Buffer.from(JSON.stringify(sourceJson));
const jsonAsset = asset({ assetId: 'steps-json', type: 'assembly-manifest', relativePath: 'steps.json', bytes: bytes.length, metadata: { manifestFiles: sourceJson.files } });
const state = await workspace(page, { assets: [part, jsonAsset] });
await page.route('https://uploads.example.com/**', (route) => route.fulfill({ status: 204 }));
const imports: any[] = [];
await page.route('**/experience-imports', (route) => { imports.push(route.request().postDataJSON()); return ok(route, result()); });
await page.locator('.experience-upload-assembly').getByText('高级导入(JSON)', { exact: true }).click();
await chooseFiles(page, [{ name: 'steps.json', mimeType: 'application/json', buffer: bytes }], '选择拼装步骤 JSON');
await page.getByRole('button', { name: '上传并读取拼装步骤', exact: true }).click();
await expect.poll(() => imports.length).toBe(1);
expect(state.calls.filter((c) => c.path.endsWith('/model-assets/signature')).map((c) => c.body.type)).toEqual(['assembly-manifest']);
const imported = imports[0];
expect(imported).toEqual({ sourceAssetId: 'steps-json', kind: 'assembly', expectedRevision: 7, assetBindings: [{ path: 'left/leg.glb', assetId: 'existing-part' }] });
});
test('行走新表单:原文件上传、保存真实编号、分功能检查并确认发布子集', async ({ page }) => {
const state = await workspace(page);
const ids = ['head', 'sit_stand', 'roll', 'kick_left', 'kick_right', 'recovery', 'ground_pick', 'rollers', 'roller_crouch', 'visual_model'];
let view: any = { apiVersion: 1, revision: 0, experienceDraftRevision: 7, sourceVersion: 'source-0',
draft: { enabled: false, entryResource: null, modelResource: null, dependencyResources: [], walkPolicyResource: null, walkSkillId: null,
features: Object.fromEntries(ids.map(id => [id, { enabled: false, skillIds: [], configResource: null, policyResources: [], modelResource: null, dependencyResources: [], mappingResource: null, autoTrigger: false }])), football: null, pickupTarget: null, resourceIds: [] },
resources: [], skills: [], presets: [], featureSupport: [], check: null, latestBuild: null, experienceDraft: state.view };
let files: any[] = []; const mutations: any[] = [];
await page.route('**/walking-editor**', async route => {
const req = route.request(), path = new URL(req.url()).pathname, body = req.postDataJSON();
if (req.method() !== 'GET') mutations.push({ path, body });
if (path.endsWith('/resource-signatures')) {
files = body.files;
return ok(route, { batchCode: 'walking-batch', uploadUrl: 'https://walking-upload.example.com', expiresAt: '2099-01-01T00:00:00Z', files: files.map(f => ({ clientId: f.clientId, relativePath: f.relativePath, formFields: { key: f.relativePath } })) });
}
if (path.endsWith('/resource-completions')) {
expect(body).toEqual({ batchCode: 'walking-batch' });
view.resources = files.map((f, i) => ({ ...f, resourceId: `resource-${i}`, bytes: f.sizeBytes, sha256: hash, status: 'READY' }));
return ok(route, { resources: view.resources });
}
if (req.method() === 'PUT') {
expect(body.expectedRevision).toBe(0); expect(body.expectedExperienceDraftRevision).toBe(7);
expect(JSON.stringify(body.draft)).not.toContain('local-');
view = { ...view, revision: 1, sourceVersion: 'source-1', experienceDraftRevision: 8, draft: body.draft };
state.view = draftView({ revision: 8, walkingEditorRevision: 1 }); view.experienceDraft = state.view;
}
if (path.endsWith('/checks')) {
view.check = { checkId: 'check-1', draftRevision: 1, sourceVersion: 'source-1', communityRuntime: 'supported',
base: { capabilityId: 'walk', status: 'PASSED', message: '', issues: [] },
features: [{ capabilityId: 'head', status: 'FAILED', message: '头部控制契约不匹配', issues: [] }] };
return ok(route, { jobId: null, view });
}
if (path.endsWith('/builds')) {
expect(body.capabilityIds).toEqual(['walk']); expect(body.checkId).toBe('check-1');
expect(view.draft.features.head.enabled).toBe(true);
const build = buildView(8); build.previewUrls.walking = 'https://community.example.com/preview/walking';
view.latestBuild = { draftRevision: 1, sourceVersion: 'source-1', checkId: 'check-1', capabilityIds: ['walk'], experienceBuild: build };
return ok(route, { jobId: null, view });
}
return ok(route, view);
});
await page.route('https://walking-upload.example.com/**', route => route.fulfill({ status: 204 }));
await page.getByRole('button', { name: '刷新行走状态', exact: true }).click();
const form = page.getByLabel('行走演示配置表单', { exact: true });
await expect(form.getByRole('button', { name: '保存行走草稿' })).toBeDisabled();
for (const checkbox of await form.getByRole('checkbox').all()) await expect(checkbox).not.toBeChecked();
const config = { schema: 1, model: 'robot/model.xml', skills: [{ id: 'walk', kind: 'primary', controller: { type: 'onnx', policy: 'policies/walk.onnx' } }, { id: 'head', kind: 'overlay', controller: { type: 'oscillator' } }] };
await chooseFiles(page, [{ name: 'robot.json', mimeType: 'application/json', buffer: Buffer.from(JSON.stringify(config)) }], '选择机器人控制配置');
await chooseFiles(page, [{ name: 'model.xml', mimeType: 'text/xml', buffer: Buffer.from('<mujoco/>') }], '选择物理模型 XML');
await chooseFiles(page, [{ name: 'walk.onnx', mimeType: 'application/octet-stream', buffer: Buffer.from([8, 9, 10]) }], '选择基础行走策略 ONNX');
await form.getByRole('checkbox', { name: '启用头部摆动' }).check();
await form.getByRole('combobox', { name: '头部摆动技能绑定' }).fill('head');
await page.keyboard.press('Enter'); await page.keyboard.press('Escape');
await form.getByRole('button', { name: '上传已选行走资源', exact: true }).click();
await expect(form.getByText('资源已上传,尚未校验控制契约或运行效果。')).toBeVisible();
expect(files.map(f => f.relativePath)).toEqual(['robot.json', 'robot/model.xml', 'policies/walk.onnx']);
await form.getByRole('button', { name: '检查行走资源', exact: true }).click();
await expect(form.getByText('头部控制契约不匹配')).toBeVisible();
await form.getByRole('button', { name: '仅用已通过功能生成发布版本' }).click();
const dialog = page.getByRole('dialog', { name: '确认本次发布功能' });
await expect(dialog.getByText('无足球及额外道具')).toBeVisible();
expect(mutations.filter(m => m.path.endsWith('/builds'))).toHaveLength(0);
await dialog.getByRole('button', { name: '确认功能并生成发布版本' }).click();
await expect(form.getByRole('link', { name: '预览本版本行走演示' })).toBeVisible();
expect(mutations.filter(m => m.path.endsWith('/builds'))).toHaveLength(1);
await form.getByRole('checkbox', { name: '启用头部摆动' }).uncheck();
await expect(form.getByRole('link', { name: '预览本版本行走演示' })).toHaveCount(0);
});
test('行走功能约束:关闭功能不要求资源、共用足球、旧检查与缺依赖不能发布', async ({ page }) => {
await workspace(page);
const results = await page.evaluate(async () => {
// @ts-ignore Vite serves this source module in the test browser.
const m = await import('/src/utils/walkingForm.ts');
const s = m.emptyWalkingSession(); s.draft.enabled = true; s.draft.walkSkillId = 'walk';
for (const [field, path] of [['entryResource', 'robot.json'], ['modelResource', 'model.xml'], ['walkPolicyResource', 'walk.onnx']]) {
s.draft[field] = path; s.resources.push({ key: path, relativePath: path, originalPath: path, kind: 'extra', remote: { resourceId: `remote-${path}`, status: 'READY' } });
}
s.resources.push({ key: 'unused', relativePath: '../unused', originalPath: 'unused', kind: 'extra', problem: 'invalid' });
s.draft.football = { presetId: 'ball', version: '1', visualResource: 'unused' };
const problems = m.walkingFormProblems(s, true);
const saved = m.serializeWalkingDraft(s);
const noBall = m.publicationSummary(s.draft, ['walk']);
const leftBall = m.publicationSummary(s.draft, ['walk', 'kick_left']);
const bothBall = m.publicationSummary(s.draft, ['walk', 'kick_left', 'kick_right']);
s.draft.features.roller_crouch.enabled = true;
const view = { draft: s.draft, revision: 2, sourceVersion: 'new', check: { draftRevision: 1, sourceVersion: 'old', base: { status: 'PASSED' }, communityRuntime: 'supported', features: [{ capabilityId: 'roller_crouch', status: 'PASSED' }] } };
const stale = m.readyCapabilities(view);
view.check.draftRevision = 2; view.check.sourceVersion = 'new';
const dependency = m.readyCapabilities(view);
view.check.communityRuntime = 'pending';
return { problems, visual: saved.football.visualResource, noBall, leftBall, bothBall, stale, dependency, pending: m.readyCapabilities(view) };
});
expect(results.problems).toEqual([]); expect(results.visual).toBeNull();
expect(results.noBall.props).toEqual([]); expect(results.leftBall.props).toEqual(['football']); expect(results.bothBall.props).toEqual(['football']);
expect(results.stale).toEqual([]); expect(results.dependency).toEqual(['walk']); expect(results.pending).toEqual([]);
});
test('行走新表单移动端:缺接口保留选择,附加动作默认关闭且不承诺可运行', async ({ page }) => {
await page.setViewportSize({ width: 390, height: 844 });
const state = await workspace(page);
const form = page.getByLabel('行走演示配置表单', { exact: true });
await expect(form.getByText(/新版表单上传接口待接入/)).toBeVisible();
await chooseFiles(page, [{ name: 'walk.onnx', mimeType: 'application/octet-stream', buffer: Buffer.from('version https://git-lfs.github.com/spec/v1\noid sha256:abc') }], '选择基础行走策略 ONNX');
await expect(form.getByText(/这是 Git LFS 占位文件/).first()).toBeVisible();
await expect(form.getByRole('button', { name: '保存行走草稿' })).toBeDisabled();
await expect(form.getByRole('checkbox', { name: '启用左脚踢球' })).not.toBeChecked();
expect(state.calls.filter(c => c.method !== 'GET')).toHaveLength(0);
const dimensions = await form.evaluate(el => ({ width: el.getBoundingClientRect().width, scroll: el.scrollWidth }));
expect(dimensions.scroll).toBeLessThanOrEqual(Math.ceil(dimensions.width) + 1);
await form.scrollIntoViewIfNeeded();
await page.screenshot({ path: test.info().outputPath('walking-mobile.png'), fullPage: true });
});
test('行走工程直接选文件夹,自动识别基础三项并保留引用与额外素材,不启用附加动作', async ({ page }) => {
const state = await workspace(page);
const config = { schema: 1, model: 'robot/model.xml', skills: [{ id: 'walk', kind: 'primary', controller: { type: 'onnx', policy: 'policies/walk.onnx' } }, { id: 'kick', kind: 'primary', controller: { type: 'onnx', policy: 'policies/kick.onnx' } }] };
// 多 primary 不猜测哪个是行走;先验证需要用户明确选择。
await chooseFiles(page, [
{ name: 'robot.json', mimeType: 'application/json', buffer: Buffer.from(JSON.stringify(config)) },
{ name: 'robot/model.xml', mimeType: 'text/xml', buffer: Buffer.from('<mujoco/>') },
{ name: 'policies/walk.onnx', mimeType: 'application/octet-stream', buffer: Buffer.from([8, 9]) },
{ name: 'robot/meshes/leg.stl', mimeType: 'application/octet-stream', buffer: Buffer.from('solid leg') },
{ name: 'policies/kick.onnx', mimeType: 'application/octet-stream', buffer: Buffer.from([8, 10]) },
], '选择行走资源文件夹');
const form = page.getByLabel('行走演示配置表单', { exact: true });
await expect(form.locator('[data-walking-slot="机器人控制配置"] .walking-path')).toHaveText('robot.json');
await expect(form.locator('[data-walking-slot="物理模型 XML"] .walking-path')).toHaveText('robot/model.xml');
await expect(form.locator('[data-walking-slot="基础行走策略 ONNX"] .walking-path')).toHaveCount(0);
await expect(form.getByRole('checkbox', { name: '启用左脚踢球' })).not.toBeChecked();
await expect(form.getByRole('textbox', { name: /资源路径 .*robot\/meshes\/leg.stl/ })).toHaveValue('robot/meshes/leg.stl');
expect(state.calls.filter(c => c.method !== 'GET')).toHaveLength(0);
await expect(page.getByRole('tab', { name: '装配与仿真', exact: true })).toBeVisible();
await expect(page.getByText('模型与演示', { exact: true })).toHaveCount(0);
});
for (const item of [
{ type: 'model-glb', pick: '选择整机 GLB', upload: '上传整机模型', files: ['robot.GLB'], field: 'modelGlbUrl' },
{ type: 'model-parts', pick: '选择零件文件夹', upload: '上传零件文件夹', files: ['left/part.glb', 'right/part.GLB', 'ignore.txt'], field: 'modelPartsBaseUrl' },
{ type: 'assembly-json', pick: '选择拼装步骤 JSON', upload: '上传拼装步骤 JSON', files: ['steps.json'], field: 'assemblyJsonUrl' },
{ type: 'walking-resources', pick: '选择行走资源文件夹', upload: '上传行走资源文件夹', files: ['README.txt', 'nested/empty.bin', 'nested/示例 file.txt'], field: 'walkingResourcesBaseUrl' },
]) test(`实际资源接口 ${item.type}:签名直传确认,无草稿请求,允许零字节与原目录`, async ({ page }) => {
const state = await workspace(page, { resourceApi: true });
let signed: any[] = [], confirmed = false; const posts: string[] = [];
await page.route('**/resources/**', async route => {
const req = route.request(); const body = req.postDataJSON();
expect(req.url()).toContain(`/resources/${item.type}`);
if (req.url().endsWith('/signature')) {
signed = body.files;
return ok(route, { batchCode: 'actual-batch', uploadUrl: 'https://resources-upload.example.com', expiresAt: '2099-01-01T00:00:00Z', files: signed.map(f => ({ relativePath: f.relativePath, objectKey: f.relativePath, formFields: { key: f.relativePath } })) });
}
expect(req.method()).toBe('PUT'); expect(body).toEqual({ batchCode: 'actual-batch', files: signed });
expect(posts).toHaveLength(signed.length); confirmed = true;
return ok(route, { projectCode: 'project-a', name: '测试项目', owner: { nickname: '官方' }, repoStatus: 'READY', publishStatus: 'UNPUBLISHED', modelGlbUrl: null, modelPartsBaseUrl: null, assemblyJsonUrl: null, walkingResourcesBaseUrl: null, [item.field]: 'https://assets.example.com/bound' });
});
await page.route('https://resources-upload.example.com/**', async route => { expect(route.request().headers().authorization).toBeUndefined(); posts.push(route.request().url()); return route.fulfill({ status: 200, body: '' }); });
if (item.type === 'assembly-json') await page.getByText('高级导入(JSON)', { exact: true }).click();
await chooseFiles(page, item.files.map(name => ({ name, mimeType: 'application/octet-stream', buffer: Buffer.alloc(0) })), item.pick);
await expect(page.getByRole('button', { name: item.upload, exact: true })).toHaveCount(0);
await expect.poll(() => confirmed).toBe(true);
await expect(page.getByText('当前已绑定', { exact: true })).toBeVisible();
expect(signed.map(f => f.relativePath).sort()).toEqual(item.files.filter(f => item.type !== 'model-parts' || /\.glb$/i.test(f)).sort());
expect(signed.every(f => f.sizeBytes === 0)).toBe(true);
expect(state.calls.some(c => /experience-draft|walking-editor|model-assets/.test(c.path))).toBe(false);
});
test('实际资源上传部分失败不确认绑定,手动重试复用成功文件', async ({ page }) => {
await workspace(page, { resourceApi: true });
let signatures = 0, confirmations = 0, failedOnce = false; const uploads = new Map<string, number>(); let signed: any[] = [];
await page.route('**/resources/model-parts/**', route => {
signatures++; signed = route.request().postDataJSON().files;
return ok(route, { batchCode: 'retry-batch', uploadUrl: 'https://retry-upload.example.com', expiresAt: '2099-01-01T00:00:00Z', files: signed.map(f => ({ relativePath: f.relativePath, objectKey: f.relativePath, formFields: { key: f.relativePath } })) });
});
await page.route('**/resources/model-parts', route => { confirmations++; expect(route.request().postDataJSON()).toEqual({ batchCode: 'retry-batch', files: signed }); return ok(route, { projectCode: 'project-a', name: '测试', owner: { nickname: '官方' }, repoStatus: 'READY', modelGlbUrl: null, modelPartsBaseUrl: 'https://assets.example.com/parts/' }); });
await page.route('https://retry-upload.example.com/**', route => {
const path = /name="key"\r\n\r\n([^\r]+)/.exec(route.request().postDataBuffer()!.toString())![1];
uploads.set(path, (uploads.get(path) ?? 0) + 1);
if (path === 'b.glb' && !failedOnce) { failedOnce = true; return route.fulfill({ status: 500 }); }
return route.fulfill({ status: 200 });
});
await chooseFiles(page, ['a.glb','b.glb'].map(name => ({ name, mimeType: 'model/gltf-binary', buffer: glb() })), '选择零件文件夹');
await expect(page.getByText(/OSS 上传失败(b.glb/)).toBeVisible(); expect(confirmations).toBe(0);
await page.getByRole('button', { name: '重试上传零件文件夹', exact: true }).click();
await expect.poll(() => confirmations).toBe(1); expect(signatures).toBe(1); expect(uploads.get('a.glb')).toBe(1); expect(uploads.get('b.glb')).toBe(2);
});
test('实际资源:新建时选择的多类文件创建后自动串行上传,每类仅确认一次', async ({ page }) => {
await workspace(page, { resourceApi: true });
await page.goto('/projects/new');
await page.getByRole('textbox', { name: '项目名称' }).fill('自动上传测试');
await page.getByRole('combobox', { name: '项目类型' }).click();
await page.getByText('轮式机器人', { exact: true }).click();
await chooseFiles(page, [{ name: 'robot.glb', mimeType: 'model/gltf-binary', buffer: glb() }]);
await chooseFiles(page, [{ name: 'parts/leg.glb', mimeType: 'model/gltf-binary', buffer: glb() }], '选择零件文件夹');
const events: string[] = []; let current = '';
const updated = { projectCode: 'project-a', name: '自动上传测试', owner: { nickname: '官方' }, repoStatus: 'READY', modelGlbUrl: null as string | null, modelPartsBaseUrl: null as string | null };
await page.route('**/admin-api/projects', route => ok(route, { projectCode: 'project-a' }));
await page.route('**/resources/**', route => {
const req = route.request(), type = /resources\/([^/]+)/.exec(req.url())![1];
if (req.url().endsWith('/signature')) {
expect(current).toBe(''); current = type; events.push(`sign:${type}`);
return ok(route, { batchCode: type, uploadUrl: 'https://auto-upload.example.com', expiresAt: '2099-01-01T00:00:00Z', files: req.postDataJSON().files.map((f: any) => ({ relativePath: f.relativePath, objectKey: f.relativePath, formFields: { key: f.relativePath } })) });
}
expect(current).toBe(type); events.push(`bind:${type}`); current = '';
if (type === 'model-glb') updated.modelGlbUrl = 'https://assets.example.com/robot.glb';
else updated.modelPartsBaseUrl = 'https://assets.example.com/parts/';
return ok(route, updated);
});
await page.route('https://auto-upload.example.com/**', route => route.fulfill({ status: 200 }));
await page.getByRole('button', { name: '创建项目并继续上传' }).click();
await expect(page.getByText('当前已绑定', { exact: true })).toHaveCount(2);
expect(events).toEqual(['sign:model-glb','bind:model-glb','sign:model-parts','bind:model-parts']);
await expect(page.getByRole('button', { name: '上传整机模型', exact: true })).toHaveCount(0);
});
test('实际资源:仓库尚未就绪不上传,刷新 READY 后自动上传且不重复', async ({ page }) => {
const options = { resourceApi: true, repoStatus: 'CREATING' };
const state = await workspace(page, options); let signatures = 0, confirmations = 0;
await page.route('**/resources/**', route => {
const req = route.request();
if (req.url().endsWith('/signature')) {
signatures++;
return ok(route, { batchCode: 'ready-batch', uploadUrl: 'https://ready-upload.example.com', expiresAt: '2099-01-01T00:00:00Z', files: req.postDataJSON().files.map((f: any) => ({ relativePath: f.relativePath, objectKey: f.relativePath, formFields: { key: f.relativePath } })) });
}
confirmations++;
return ok(route, { projectCode: 'project-a', name: '测试', owner: { nickname: '官方' }, repoStatus: 'READY', modelGlbUrl: 'https://assets.example.com/robot.glb' });
});
await page.route('https://ready-upload.example.com/**', route => route.fulfill({ status: 200 }));
await chooseFiles(page, [{ name: 'robot.glb', mimeType: 'model/gltf-binary', buffer: glb() }]);
await expect(page.getByText(/仓库尚未 READY/)).toBeVisible();
expect(signatures).toBe(0); expect(state.calls.some(c => c.path.includes('/resources/'))).toBe(false);
options.repoStatus = 'READY';
await page.getByRole('button', { name: '刷新资源绑定' }).click();
await expect(page.getByText('当前已绑定', { exact: true })).toBeVisible();
expect(signatures).toBe(1); expect(confirmations).toBe(1);
await page.getByRole('button', { name: '刷新资源绑定' }).click();
await expect(page.getByRole('button', { name: '刷新资源绑定' })).toBeEnabled();
expect(signatures).toBe(1); expect(confirmations).toBe(1);
});
async function partsWorkspace(page: Page, paths = ['parts/left.glb', 'parts/right.glb']) {
const contents = new Map(paths.map((path, i) => [path, Buffer.from(`original-${i}`)]));
const resources = paths.map(relativePath => ({ relativePath, sizeBytes: contents.get(relativePath)!.length, url: `https://parts.example.com/${relativePath}` }));
const state = {
project: { projectCode: 'project-a', name: '零件管理测试', owner: { nickname: '官方' }, repoStatus: 'READY', modelGlbUrl: null, modelPartsBaseUrl: paths.length ? 'https://parts.example.com/' : null as string | null, modelPartsFiles: resources },
signatures: [] as any[][], confirmations: [] as any[], deletes: 0, downloads: [] as string[], uploads: [] as string[], failDownload: false, changeDuringUpload: false, contents,
};
await workspace(page, { resourceApi: true, project: state.project });
await page.route('**/admin-api/projects/project-a', route => ok(route, { project: state.project, deleted: false, moderationStatus: 'NORMAL' }));
await page.route('https://parts.example.com/**', route => {
expect(route.request().headers().authorization).toBeUndefined();
const path = decodeURIComponent(new URL(route.request().url()).pathname.slice(1)); state.downloads.push(path);
return route.fulfill({ status: state.failDownload ? 503 : 200, body: contents.get(path) ?? Buffer.alloc(0) });
});
await page.route('**/resources/model-parts/**', route => {
const files = route.request().postDataJSON().files; state.signatures.push(files);
return ok(route, { batchCode: 'parts-edit', uploadUrl: 'https://parts-upload.example.com', expiresAt: '2099-01-01T00:00:00Z', files: files.map((f: any) => ({ relativePath: f.relativePath, objectKey: f.relativePath, formFields: { key: f.relativePath } })) });
});
await page.route('https://parts-upload.example.com/**', route => {
expect(route.request().headers().authorization).toBeUndefined();
const body = route.request().postDataBuffer()!;
const path = /name="key"\r\n\r\n([^\r]+)/.exec(body.toString())![1]; state.uploads.push(path);
if (contents.has(path) && path !== 'parts/left.glb') expect(body.includes(contents.get(path)!)).toBe(true);
if (state.changeDuringUpload) state.project = { ...state.project, modelPartsBaseUrl: 'https://parts.example.com/changed/' };
return route.fulfill({ status: 200 });
});
await page.route('**/resources/model-parts', route => {
if (route.request().method() === 'DELETE') { state.deletes++; state.project = { ...state.project, modelPartsBaseUrl: null, modelPartsFiles: [] }; return ok(route, null); }
const body = route.request().postDataJSON(); state.confirmations.push(body);
expect(body).toEqual({ batchCode: 'parts-edit', files: state.signatures.at(-1) });
expect(state.uploads.length).toBe(body.files.length);
state.project = { ...state.project, modelPartsBaseUrl: 'https://parts.example.com/new/', modelPartsFiles: body.files.map((f: any) => ({ ...f, url: `https://parts.example.com/new/${f.relativePath}` })) };
return ok(route, state.project);
});
return state;
}
test('零件管理:跨页搜索名称与目录,不请求上传接口', async ({ page }) => {
const state = await partsWorkspace(page, [...Array.from({ length: 7 }, (_, i) => `零件${i}.glb`), 'Left/Hand.GLB']);
await page.getByRole('textbox', { name: '搜索零件', exact: true }).fill('left/hand');
await expect(page.getByRole('link', { name: 'Left/Hand.GLB', exact: true })).toBeVisible();
await expect(page.getByText('匹配 1 / 共 8 个零件')).toBeVisible();
await page.getByRole('textbox', { name: '搜索零件', exact: true }).fill('不存在');
await expect(page.getByText('没有匹配的零件')).toBeVisible();
await page.getByRole('textbox', { name: '搜索零件', exact: true }).fill('');
await expect(page.getByText('共 8 个零件')).toBeVisible();
expect(state.signatures).toHaveLength(0); expect(state.deletes).toBe(0);
});
test('零件管理:单文件选择后自动添加到指定子目录,其他零件字节和路径保留', async ({ page }) => {
const state = await partsWorkspace(page);
await page.getByRole('combobox', { name: '单个零件上传目录' }).fill('parts/head');
await chooseFiles(page, [{ name: 'sensor.GLB', mimeType: 'model/gltf-binary', buffer: glb() }], '上传单个零件');
await expect(page.getByText('共 3 个零件')).toBeVisible();
expect(state.confirmations).toHaveLength(1);
expect(state.signatures[0].map(f => f.relativePath)).toEqual(['parts/left.glb', 'parts/right.glb', 'parts/head/sensor.GLB']);
expect(state.downloads.sort()).toEqual(['parts/left.glb', 'parts/right.glb']);
await page.getByRole('button', { name: '刷新资源绑定' }).click();
await expect(page.getByText('共 3 个零件')).toBeVisible();
});
test('零件管理:同路径替换需要确认,取消不上传,确认后不重复路径', async ({ page }) => {
const state = await partsWorkspace(page);
await page.getByRole('combobox', { name: '单个零件上传目录' }).fill('parts');
const file = { name: 'left.glb', mimeType: 'model/gltf-binary', buffer: glb() };
await chooseFiles(page, [file], '上传单个零件');
await expect(page.getByText('替换同路径零件?')).toBeVisible();
await page.getByRole('button', { name: /^取\s*消$/ }).click();
expect(state.signatures).toHaveLength(0);
await chooseFiles(page, [file], '上传单个零件');
await page.getByRole('button', { name: '替换并上传' }).click();
await expect.poll(() => state.confirmations.length).toBe(1);
expect(state.signatures[0]).toEqual([{ relativePath: 'parts/right.glb', sizeBytes: state.contents.get('parts/right.glb')!.length }, { relativePath: 'parts/left.glb', sizeBytes: glb().length }]);
expect(state.downloads).toEqual(['parts/right.glb']);
});
test('零件管理:搜索后删除仅影响目标,最后一个零件用清除接口', async ({ page }) => {
const state = await partsWorkspace(page);
await page.getByRole('textbox', { name: '搜索零件', exact: true }).fill('left');
await page.getByRole('button', { name: '删除零件 parts/left.glb', exact: true }).click();
await page.getByRole('button', { name: '删除零件', exact: true }).click();
await expect(page.getByText('匹配 0 / 共 1 个零件')).toBeVisible();
expect(state.signatures[0].map(f => f.relativePath)).toEqual(['parts/right.glb']);
expect(state.downloads).toEqual(['parts/right.glb']);
expect(state.deletes).toBe(0);
await page.getByRole('textbox', { name: '搜索零件', exact: true }).fill('');
await page.getByRole('button', { name: '删除零件 parts/right.glb', exact: true }).click();
await page.getByRole('button', { name: '删除零件', exact: true }).click();
await expect(page.getByText('尚未上传零件')).toBeVisible();
expect(state.deletes).toBe(1); expect(state.confirmations).toHaveLength(1);
});
test('零件管理:保留旧零件失败时不更改绑定,显示重试并保留原选择', async ({ page }) => {
const state = await partsWorkspace(page); state.failDownload = true;
await chooseFiles(page, [{ name: 'new.glb', mimeType: 'model/gltf-binary', buffer: glb() }], '上传单个零件');
await expect(page.getByText(/无法保留零件/)).toBeVisible();
expect(state.confirmations).toHaveLength(0); expect(state.signatures).toHaveLength(0);
await expect(page.getByText('共 2 个零件')).toBeVisible();
state.failDownload = false;
await page.getByRole('button', { name: '重试本次零件操作' }).click();
await expect(page.getByText('共 3 个零件')).toBeVisible();
expect(state.confirmations).toHaveLength(1);
});
test('零件管理:上传期间资源被其他操作修改时,不覆盖最新绑定', async ({ page }) => {
const state = await partsWorkspace(page); state.changeDuringUpload = true;
await chooseFiles(page, [{ name: 'new.glb', mimeType: 'model/gltf-binary', buffer: glb() }], '上传单个零件');
await expect(page.getByText('零件列表已发生变化,请刷新资源绑定后重新操作。')).toBeVisible();
expect(state.confirmations).toHaveLength(0);
await expect(page.getByRole('button', { name: '上传单个零件', exact: true })).toBeDisabled();
await page.getByRole('button', { name: '刷新资源绑定' }).click();
await expect(page.getByRole('button', { name: '上传单个零件', exact: true })).toBeEnabled();
expect(state.confirmations).toHaveLength(0);
});
test('零件管理:无效上传目录在本地阻止,不触发原文件读取或绑定', async ({ page }) => {
const state = await partsWorkspace(page);
await page.getByRole('combobox', { name: '单个零件上传目录' }).fill('../other');
await chooseFiles(page, [{ name: 'new.glb', mimeType: 'model/gltf-binary', buffer: glb() }], '上传单个零件');
await expect(page.getByText(/路径不能包含/)).toBeVisible();
expect(state.downloads).toHaveLength(0); expect(state.signatures).toHaveLength(0); expect(state.confirmations).toHaveLength(0);
});
test('零件管理:绑定结果未知不自动重复提交,刷新核对后才能继续', async ({ page }) => {
const state = await partsWorkspace(page); let puts = 0;
await page.route('**/resources/model-parts', route => { puts++; return route.fulfill({ status: 500, json: { code: 'INTERNAL_ERROR', message: '暂时无法确认结果' } }); });
await chooseFiles(page, [{ name: 'new.glb', mimeType: 'model/gltf-binary', buffer: glb() }], '上传单个零件');
await expect(page.getByText(/确认或清除结果需核对/)).toBeVisible();
await expect(page.getByRole('button', { name: '上传单个零件', exact: true })).toBeDisabled();
await expect(page.getByRole('button', { name: '重试本次零件操作', exact: true })).toHaveCount(0);
expect(puts).toBe(1);
await page.getByRole('button', { name: '刷新资源绑定' }).click();
await expect(page.getByRole('button', { name: '上传单个零件', exact: true })).toBeEnabled();
expect(puts).toBe(1); expect(state.confirmations).toHaveLength(0);
});
async function boundAssemblyWorkspace(page: Page, issue?: 'missing' | 'mismatch' | 'json') {
const bytes = editorGlb();
const digest = createHash('sha256').update(bytes).digest('hex');
const manifest = {
schemaVersion: 1, kind: 'assembly', title: '已有装配流程', unit: 'meter', displayQuaternion: [0, 0, 0, 1],
files: ['leg.glb', '内六角扳手.glb'].map(path => ({ path, bytes: bytes.length, sha256: digest })),
parts: [{ id: 'leg', file: 'leg.glb', parentId: null, position: [.2, .1, 0], quaternion: [0, 0, 0, 1], scale: [1, 1, 1], installOffset: [.05, 0, 0], customPart: 'preserved' }],
steps: [{ id: 'step-1', label: '原安装步骤', parts: ['leg'], toolId: 'hex-key', duration: 1200 }],
tools: [{ id: 'hex-key', file: '内六角扳手.glb', tipPosition: [0, .01, 0], tipAxis: [0, 0, -1] }], custom: { preserve: true },
};
const files = (issue === 'missing' ? ['leg.glb'] : ['leg.glb', '内六角扳手.glb']).map(relativePath => ({ relativePath, sizeBytes: bytes.length, url: `https://bound.example.com/${relativePath}` }));
await page.route('https://bound.example.com/**', async route => {
expect(route.request().headers().authorization).toBeUndefined();
const path = decodeURIComponent(new URL(route.request().url()).pathname.slice(1));
return route.fulfill({ status: 200, body: path === 'assembly.json' ? issue === 'json' ? '{' : JSON.stringify(manifest) : issue === 'mismatch' ? editorGlb(1) : bytes });
});
const errors: string[] = [];
page.on('console', message => { if (message.type() === 'error' || message.text().includes('Future Flag Warning')) errors.push(message.text()); });
const state = await workspace(page, { resourceApi: true, project: { modelPartsBaseUrl: 'https://bound.example.com/', modelPartsFiles: files, assemblyJsonUrl: 'https://bound.example.com/assembly.json' } });
return { manifest, state, errors };
}
test('已有装配:打开后读取原步骤与位姿,保存保留工具文件和扩展字段,不重新上传零件', async ({ page }) => {
const { manifest, state, errors } = await boundAssemblyWorkspace(page);
await expect(page.getByText('编辑装配流程', { exact: true })).toBeVisible();
const dialog = await editorDialog(page);
await dialog.getByRole('tab', { name: '步骤 1', exact: true }).click();
await expect(dialog.locator('.assembly-step-list')).toContainText('原安装步骤');
const generated = await generatedManifest(page);
expect(generated.tools).toEqual(manifest.tools);
expect(generated.files).toEqual(manifest.files);
expect(generated.parts[0]).toMatchObject(manifest.parts[0]);
expect(generated.steps).toEqual(manifest.steps);
expect(generated.custom).toEqual(manifest.custom);
expect(state.calls.filter(c => c.method !== 'GET')).toHaveLength(0);
expect(errors).toEqual([]);
let signatures = 0, confirmations = 0, uploaded = '';
await page.route('**/resources/assembly-json/signature', route => {
signatures++;
return ok(route, { batchCode: 'assembly-edited', uploadUrl: 'https://assembly-upload.example.com', expiresAt: '2099-01-01T00:00:00Z', files: route.request().postDataJSON().files.map((f: any) => ({ relativePath: f.relativePath, formFields: { key: f.relativePath } })) });
});
await page.route('https://assembly-upload.example.com/**', route => { uploaded = route.request().postData()!; return route.fulfill({ status: 200 }); });
await page.route('**/resources/assembly-json', route => { confirmations++; return ok(route, { projectCode: 'project-a', repoStatus: 'READY', modelGlbUrl: null, assemblyJsonUrl: 'https://bound.example.com/new.json' }); });
await dialog.getByRole('button', { name: '保存装配流程', exact: true }).click();
await expect.poll(() => confirmations).toBe(1);
expect(signatures).toBe(1);
expect(uploaded).toContain('内六角扳手.glb');
expect(uploaded).toContain('customPart');
expect(state.calls.filter(c => c.method !== 'GET')).toHaveLength(0);
});
for (const issue of ['missing', 'mismatch', 'json'] as const) test(`已有装配:${issue} 时明确报错且保留绑定,不打开空流程或提交覆盖`, async ({ page }) => {
const { state } = await boundAssemblyWorkspace(page, issue);
await page.getByRole('button', { name: '制作装配流程', exact: true }).click();
await expect(page.getByText(/原流程已保留/)).toBeVisible();
await expect(page.getByRole('dialog')).toHaveCount(0);
await expect(page.getByRole('button', { name: '制作装配流程', exact: true })).toBeEnabled();
expect(state.calls.filter(c => c.method !== 'GET')).toHaveLength(0);
await expect(page.locator('.experience-upload-assembly').getByText('当前已绑定', { exact: true })).toBeVisible();
});
test('整机定位:新流程用唯一同名节点的世界变换,匹配失败不猜位置,原文件不变', async ({ page }) => {
await workspace(page, { resourceApi: true });
const result = await page.evaluate(async () => {
const path = '/src/utils/assemblyPlacement.ts', { placeFromWhole } = await import(path);
const makeGlb = (nodes: unknown[]) => {
const json = new TextEncoder().encode(JSON.stringify({ nodes, meshes: [{ primitives: [{ attributes: { POSITION: 0 } }] }], accessors: [{ count: 8, min: [-1, -1, -1], max: [1, 1, 1] }] }));
const size = Math.ceil(json.length / 4) * 4, bytes = new Uint8Array(20 + size), h = new DataView(bytes.buffer);
h.setUint32(0, 0x46546c67, true); h.setUint32(4, 2, true); h.setUint32(8, bytes.length, true); h.setUint32(12, size, true); h.setUint32(16, 0x4e4f534a, true); bytes.fill(32, 20); bytes.set(json, 20);
return new File([bytes], 'model.glb');
};
const source = (id: string, name: string) => ({ file: makeGlb([{ name, mesh: 0, translation: [.2, 0, 0] }]), asset: { assetId: id, type: 'part-glb', relativePath: `${id}.glb`, bytes: 1, sha256: 'a'.repeat(64), status: 'READY', downloadUrl: null } });
const sources = [source('left', 'left-mesh'), source('unknown', 'no-matching-node')];
const part = (id: string) => ({ id, name: id, assetId: id, parentId: null, position: [0, 0, 0], quaternion: [0, 0, 0, 1], scale: [1, 1, 1], installOffset: [0, .08, 0] });
const session = { sources, assembly: { title: '定位测试', enabled: true, unit: 'meter', displayQuaternion: [0, 0, 0, 1], referenceAssetId: null, parts: sources.map(s => part(s.asset.assetId)), steps: [] } };
const whole = makeGlb([{ translation: [1, 2, 3], children: [1] }, { name: 'left-mesh', mesh: 0, translation: [.6, 0, 0] }]);
const placed = await placeFromWhole(session, whole, new AbortController().signal);
return { position: placed.catalog[0].position, unplaced: placed.unplaced, sourcePosition: session.assembly.parts[0].position, filesUnchanged: placed.sources.every((s: any, i: number) => s.file === sources[i].file) };
});
expect(result.position[0]).toBeCloseTo(1.4); expect(result.position.slice(1)).toEqual([2, 3]);
expect(result.unplaced).toEqual(['unknown']); expect(result.sourcePosition).toEqual([0, 0, 0]); expect(result.filesUnchanged).toBe(true);
});
test('组件总装:支持嵌套连接,拒绝重复消费、未连接与循环,切换普通模式保留步骤', async ({ page }) => {
await workspace(page, { resourceApi: true });
const result = await page.evaluate(async () => {
const path = '/src/utils/assemblyWorkflow.ts', { assemblyStages, componentPlanProblems } = await import(path);
const a = { parts: ['h', 'b', 'a'].map(id => ({ id })), steps: ['h', 'b', 'a'].map(id => ({ id: `s-${id}`, parts: [id], label: id })), componentPlan: { version: 1, components: ['h', 'b', 'a'].map(id => ({ id: `c-${id}`, name: id, parts: [id] })), connections: [{ id: 'hb', name: '头部与身体', members: ['c-h', 'c-b'], installOffset: [0, .1, 0] }, { id: 'all', name: '加装手臂', members: ['hb', 'c-a'], installOffset: [0, .1, 0] }] } };
const valid = componentPlanProblems(a), stages = assemblyStages(a);
const duplicate = structuredClone(a); duplicate.componentPlan.connections[1].members = ['hb', 'c-b'];
const cycle = structuredClone(a); cycle.componentPlan.connections[0].members = ['all', 'c-h'];
const unfinished = structuredClone(a); unfinished.componentPlan.connections.pop();
const direct = structuredClone(a); delete (direct as any).componentPlan;
return { valid, visibility: stages.map((s: any) => s.parts), duplicate: componentPlanProblems(duplicate), cycle: componentPlanProblems(cycle), unfinished: componentPlanProblems(unfinished), direct: assemblyStages(direct).map((s: any) => s.parts) };
});
expect(result.valid).toEqual([]);
expect(result.visibility).toEqual([['h'], ['b'], ['h', 'b'], ['a'], ['h', 'b', 'a']]);
expect(result.direct).toEqual([['h'], ['h', 'b'], ['h', 'b', 'a']]);
expect(result.duplicate.length).toBeGreaterThan(0); expect(result.cycle.length).toBeGreaterThan(0); expect(result.unfinished.length).toBeGreaterThan(0);
});
test('部分编排保存后再次打开仍保留未用零件原文件,可以继续制作下一组件', async ({ page }) => {
await workspace(page, { resourceApi: true });
const counts = await page.evaluate(async () => {
const editorPath = '/src/utils/assemblyEditor.ts', filesPath = '/src/utils/experienceFiles.ts';
const { prepareAssemblySession } = await import(editorPath), { emptyExperienceFiles } = await import(filesPath);
const files = emptyExperienceFiles(); files.parts.selected = ['head', 'body'].map(name => ({ relativePath: `${name}.glb`, file: new File(['original'], `${name}.glb`) }));
const initial = await prepareAssemblySession(null, null, [], files);
const partial = { ...initial, catalog: initial.assembly.parts, assembly: { ...initial.assembly, parts: [initial.assembly.parts[0]], steps: [{ id: 's1', label: '头部', parts: [initial.assembly.parts[0].id] }] } };
const reopened = await prepareAssemblySession(partial, partial.assembly, [], emptyExperienceFiles());
return { sources: reopened.sources.length, catalog: reopened.catalog.length, steps: reopened.assembly.steps.length };
});
expect(counts).toEqual({ sources: 2, catalog: 2, steps: 1 });
});
test('零件选择:左键添加、右键仅移除目标,筛选可叠加搜索并随选择更新,撤销可恢复', async ({ page }) => {
const state = await workspace(page, { missing: true });
await chooseFiles(page, ['left', 'right', 'head'].map((name, i) => ({ name: `${name}.glb`, mimeType: 'model/gltf-binary', buffer: editorGlb(i * .2) })), '选择零件文件夹');
const dialog = await editorDialog(page);
await dialog.getByText('已选中', { exact: true }).click();
await expect(dialog.getByText('还没有选中零件', { exact: true })).toBeVisible();
await dialog.getByText('未选中', { exact: true }).click();
await expect(dialog.locator('.assembly-part-row')).toHaveCount(3);
await dialog.getByRole('button', { name: '安装零件 left', exact: true }).click({ button: 'right' });
await expect(dialog.locator('.assembly-part-row')).toHaveCount(3);
await dialog.getByRole('button', { name: '安装零件 left', exact: true }).click();
await expect(dialog.locator('.assembly-part-row')).toHaveCount(2);
await dialog.getByRole('button', { name: '安装零件 right', exact: true }).click();
await dialog.getByText('已选中', { exact: true }).click();
await expect(dialog.locator('.assembly-part-row')).toHaveCount(2);
await dialog.getByRole('textbox', { name: '搜索组件或零件' }).fill('LEFT');
await expect(dialog.locator('.assembly-part-row')).toHaveCount(1);
await dialog.getByRole('button', { name: '查看零件 left', exact: true }).click({ button: 'right' });
await expect(dialog.locator('.assembly-part-row')).toHaveCount(0);
await dialog.getByRole('textbox', { name: '搜索组件或零件' }).fill('');
await expect(dialog.getByRole('button', { name: '查看零件 right', exact: true })).toHaveAttribute('aria-pressed', 'true');
const json = await generatedManifest(page);
expect(json.parts).toHaveLength(1); expect(json.parts[0].file).toBe('right.glb');
await dialog.getByRole('button', { name: '撤销', exact: true }).click();
await expect(dialog.locator('.assembly-part-row')).toHaveCount(2);
await dialog.getByRole('button', { name: '重做', exact: true }).click();
await expect(dialog.locator('.assembly-part-row')).toHaveCount(1);
await dialog.getByText('未选中', { exact: true }).click();
await expect(dialog.getByRole('button', { name: '安装零件 left', exact: true })).toBeVisible();
await dialog.getByRole('button', { name: '安装零件 left', exact: true }).click();
const reselected = await generatedManifest(page);
expect(reselected.steps.map((s: any) => s.label)).toEqual(['安装 right', '安装 left']);
expect(state.calls.filter(c => c.method !== 'GET')).toHaveLength(0);
});
test('单零件移除:保留同一步其余零件,清理空组件和依赖连接,父件引用仍有保护', async ({ page }) => {
await workspace(page, { resourceApi: true });
const result = await page.evaluate(async () => {
const path = '/src/utils/assemblyWorkflow.ts', { removeWorkflowPart } = await import(path);
const original = { parts: ['left', 'right', 'body'].map(id => ({ id, name: id, parentId: null })), steps: [{ id: 's1', label: '双腿', parts: ['left', 'right'], duration: 1000 }, { id: 's2', label: '身体', parts: ['body'] }], componentPlan: { version: 1, components: [{ id: 'legs', name: '双腿', parts: ['left', 'right'] }, { id: 'body-c', name: '身体', parts: ['body'] }], connections: [{ id: 'joined', name: '总装', members: ['legs', 'body-c'], installOffset: [0, .1, 0] }] } };
const one = removeWorkflowPart(original, 'left'), two = removeWorkflowPart(one, 'right');
const child = structuredClone(original); child.parts[1].parentId = 'left';
let protectedMessage = ''; try { removeWorkflowPart(child, 'left'); } catch (e) { protectedMessage = (e as Error).message; }
return { one, two, original, protectedMessage, unchanged: removeWorkflowPart(original, 'not-selected') === original };
});
expect(result.one.steps[0]).toEqual({ id: 's1', label: '双腿', parts: ['right'], duration: 1000 });
expect(result.one.componentPlan.connections).toHaveLength(1);
expect(result.two.componentPlan.components.map((c: any) => c.id)).toEqual(['body-c']);
expect(result.two.componentPlan.connections).toEqual([]);
expect(result.original.steps[0].parts).toEqual(['left', 'right']);
expect(result.protectedMessage).toContain('先移除子零件'); expect(result.unchanged).toBe(true);
});
test('创建组件:内部步骤独立,选择后整体进入总装,撤销重做保留组件内容', async ({ page }) => {
await workspace(page, { missing: true });
await chooseFiles(page, ['头壳', '面罩', '支架'].map(name => ({ name: `${name}.glb`, mimeType: 'model/gltf-binary', buffer: editorGlb() })), '选择零件文件夹');
const dialog = await editorDialog(page);
await dialog.getByRole('button', { name: '创建组件', exact: true }).first().click();
await page.getByRole('textbox', { name: '独立组件名称' }).fill('头部');
await page.getByRole('button', { name: '创建并制作' }).click();
for (const name of ['面罩', '支架', '头壳']) await dialog.getByRole('button', { name: `安装零件 ${name}`, exact: true }).click();
const privateJson = await generatedManifest(page);
expect(privateJson.steps).toEqual([]);
expect(privateJson.componentLibrary.components[0].steps.map((s: any) => s.label)).toEqual(['安装 面罩', '安装 支架', '安装 头壳']);
await dialog.getByText('步骤编排', { exact: true }).first().click();
await dialog.getByRole('checkbox', { name: '选择组件 头部', exact: true }).check();
await expect(dialog.getByRole('tab', { name: '步骤 1', exact: true })).toBeVisible();
await dialog.getByRole('button', { name: '撤销', exact: true }).click();
await expect(dialog.getByRole('tab', { name: '步骤 0', exact: true })).toBeVisible();
await expect(dialog.getByRole('button', { name: '编辑库组件 头部', exact: true })).toBeVisible();
await dialog.getByRole('button', { name: '重做', exact: true }).click();
const total = await generatedManifest(page);
expect(total.steps).toHaveLength(1); expect(total.steps[0].parts).toHaveLength(3);
expect(total.componentLibrary.components).toEqual(privateJson.componentLibrary.components);
});
test('六向与工具:进入设置直接可见,GLB 工具校准后自动识别螺丝头并写入原有前台格式', async ({ page }, testInfo) => {
await workspace(page, { missing: true });
const fixture = await page.evaluate(async () => { const path = '/tests/assembly-fixtures.ts'; return (await import(path)).toolFixtures(); });
await chooseFiles(page, [{ name: '螺丝.glb', mimeType: 'model/gltf-binary', buffer: Buffer.from(fixture.screw) }, { name: '螺丝刀.glb', mimeType: 'model/gltf-binary', buffer: Buffer.from(fixture.driver) }], '选择零件文件夹');
const dialog = await editorDialog(page);
await dialog.getByRole('button', { name: '安装零件 螺丝', exact: true }).click();
for (const label of ['X', 'Y', 'Z', '−X', '−Y', '−Z']) await expect(dialog.getByRole('button', { name: `从 ${label} 进入`, exact: true })).toBeVisible();
await dialog.getByRole('button', { name: '从 −X 进入', exact: true }).click();
await dialog.getByRole('spinbutton', { name: '进入距离(毫米)' }).fill('25');
const ordinary = await generatedManifest(page); expect(ordinary.parts[0].installOffset).toEqual([-.025, 0, 0]);
await dialog.getByRole('switch', { name: '使用工具拧入' }).click();
await expect(dialog.getByRole('button', { name: '保存装配流程' })).toBeDisabled();
await dialog.getByRole('combobox', { name: '安装工具 GLB' }).click();
await page.getByRole('option', { name: '螺丝刀.glb', exact: true }).click();
const calibration = page.getByRole('dialog', { name: '校准工具工作端' });
await calibration.getByRole('spinbutton', { name: '校准点 X(毫米)' }).fill('0');
await calibration.getByRole('spinbutton', { name: '校准点 Y(毫米)' }).fill('0');
await calibration.getByRole('spinbutton', { name: '校准点 Z(毫米)' }).fill('10');
await calibration.getByRole('button', { name: '−Z', exact: true }).click();
await calibration.getByRole('button', { name: '使用此工作端' }).click();
await expect(dialog.getByRole('button', { name: '保存装配流程' })).toBeEnabled();
await expect(dialog.getByRole('button', { name: '安装零件 螺丝刀', exact: true })).toHaveCount(0);
const json = await generatedManifest(page);
expect(json.files.map((f: any) => f.path).sort()).toEqual(['螺丝.glb', '螺丝刀.glb']);
expect(json.parts).toHaveLength(1); expect(json.tools).toHaveLength(1);
expect(json.tools[0].tipPosition).toEqual([0, 0, .01]); expect(json.tools[0].tipAxis).toEqual([0, 0, -1]);
expect(json.parts[0].installation.axis[1]).toBeCloseTo(-1, 5);
expect(json.parts[0].installation.socketPosition[1]).toBeCloseTo(.00765, 5);
expect(json.parts[0].installation).toMatchObject({ type: 'screw', toolId: json.tools[0].id, turns: 3, direction: 'clockwise', travel: .0012 });
await dialog.getByRole('spinbutton', { name: '旋转圈数' }).fill('5');
await expect(dialog.getByRole('button', { name: '保存装配流程' })).toBeDisabled();
await dialog.getByRole('button', { name: '应用工具并预览' }).click();
await expect(dialog.getByRole('button', { name: '保存装配流程' })).toBeEnabled();
expect((await generatedManifest(page)).parts[0].installation.turns).toBe(5);
const configured = await generatedManifest(page);
const restored = await page.evaluate(async raw => {
const restorePath = '/src/utils/boundAssembly.ts', editorPath = '/src/utils/assemblyEditor.ts';
const sources = raw.files.map((f: any) => ({ asset: { assetId: f.path, type: 'part-glb', relativePath: f.path, bytes: f.bytes, sha256: f.sha256, status: 'READY' } }));
const session = (await import(restorePath)).restoreAssemblyDocument(raw, { sources });
return (await import(editorPath)).assemblyManifest(session.assembly, sources, session.manifest);
}, configured);
expect(restored.tools).toEqual(configured.tools); expect(restored.parts[0].installation).toEqual(configured.parts[0].installation);
await dialog.getByRole('switch', { name: '使用工具拧入' }).click();
const withoutTool = await generatedManifest(page); expect(withoutTool.parts[0].installation).toBeUndefined();
expect(withoutTool.tools).toHaveLength(1);
await page.screenshot({ path: testInfo.outputPath('tool-installation-editor.png'), fullPage: true });
});
test('工具坐标:六向螺丝在任意父级旋转下尖端始终贴合插入点,旋转后回到精确最终位姿', async ({ page }) => {
await workspace(page, { resourceApi: true });
const result = await page.evaluate(async () => {
const threePath = '/node_modules/three/build/three.module.js', motionPath = '/src/utils/assemblyMotion.ts', configPath = '/src/utils/assemblyToolConfig.ts';
const { Group, Vector3, Quaternion } = await import(threePath), { ScrewTransition } = await import(motionPath), { normalizedInstallation } = await import(configPath);
let maxError = 0, maxAxisError = 0, finals = true;
for (const axis of [[1, 0, 0], [-1, 0, 0], [0, 1, 0], [0, -1, 0], [0, 0, 1], [0, 0, -1]]) {
const toolConfig = { id: 'driver', assetId: 'tool', tipPosition: [.005, 0, .01], tipAxis: [0, 0, -1] };
const part = { id: 'screw', name: '螺丝', assetId: 'screw', parentId: null, position: [.2, .3, .1], quaternion: new Quaternion().setFromAxisAngle(new Vector3(1, 1, 0).normalize(), .7).toArray(), scale: [1, 1, 1], installOffset: [.02, .03, .01], installation: normalizedInstallation({ type: 'screw', toolId: 'driver', axis, socketPosition: [.003, .007, .001], toolQuaternion: new Quaternion().setFromUnitVectors(new Vector3(0, 0, 1), new Vector3(...axis)).toArray(), turns: 3, direction: 'clockwise', travel: .0012 }) };
const parent = new Group(), instance = new Group(), tool = new Group(); parent.add(instance); parent.scale.setScalar(2); parent.quaternion.setFromAxisAngle(new Vector3(0, 1, 0), 1.1);
instance.scale.fromArray(part.scale); const transition = new ScrewTransition(instance, part, tool, toolConfig), m = part.installation;
for (let i = 0; i <= 100; i++) {
transition.sample(m.approachDuration + m.engageDuration + m.tightenDuration * i / 100); parent.updateMatrixWorld(true);
maxError = Math.max(maxError, tool.localToWorld(new Vector3(...toolConfig.tipPosition)).distanceTo(instance.localToWorld(new Vector3(...m.socketPosition))));
const working = new Vector3(...toolConfig.tipAxis).applyQuaternion(tool.quaternion).normalize(); maxAxisError = Math.max(maxAxisError, working.distanceTo(new Vector3(...axis)));
}
transition.sample(100); finals &&= instance.position.toArray().every((v: number, i: number) => v === part.position[i]) && instance.quaternion.toArray().every((v: number, i: number) => v === part.quaternion[i]) && !tool.visible;
transition.dispose();
}
return { maxError, maxAxisError, finals };
});
expect(result.maxError).toBeLessThan(1e-10); expect(result.maxAxisError).toBeLessThan(1e-10); expect(result.finals).toBe(true);
});
test('独立组件库:空父组件与嵌套子组件单独制作,显式加入总装后才产生总装步骤,保存回读保留层级', async ({ page }, testInfo) => {
await workspace(page, { missing: true });
await chooseFiles(page, ['躯干1零件', '躯干2零件', '腿'].map((name, i) => ({ name: `${name}.glb`, mimeType: 'model/gltf-binary', buffer: editorGlb(i * .2) })), '选择零件文件夹');
const dialog = await editorDialog(page);
await dialog.getByText('组件制作', { exact: true }).first().click();
const create = async (name: string, child = false) => {
await dialog.getByRole('button', { name: child ? '创建子组件' : '创建组件', exact: true }).first().click();
const form = page.getByRole('dialog', { name: child ? '创建子组件' : '创建组件', exact: true });
await form.getByRole('textbox', { name: '独立组件名称' }).fill(name);
await form.getByRole('button', { name: '创建并制作' }).click();
};
await create('躯干');
await create('躯干1', true);
await dialog.getByRole('button', { name: '安装零件 躯干1零件', exact: true }).click();
await expect(dialog.getByRole('tab', { name: '内部步骤 1', exact: true })).toBeVisible();
await expect(dialog.locator('.assembly-operation-context')).toContainText('总装 0 步保持独立');
await dialog.getByRole('button', { name: '编辑库组件 躯干', exact: true }).click();
await create('躯干2', true);
await dialog.getByRole('button', { name: '安装零件 躯干2零件', exact: true }).click();
await dialog.getByRole('button', { name: '安装零件 躯干1零件', exact: true }).click();
await expect(page.getByText(/零件已属于“躯干 \/ 躯干1”/)).toBeVisible();
await expect(dialog.getByRole('tab', { name: '内部步骤 1', exact: true })).toBeVisible();
await dialog.getByRole('button', { name: '编辑库组件 躯干', exact: true }).click();
await dialog.getByRole('checkbox', { name: '选择组件 躯干2', exact: true }).check();
await dialog.getByRole('checkbox', { name: '选择组件 躯干1', exact: true }).check();
await expect(dialog.getByRole('tab', { name: '内部步骤 2', exact: true })).toBeVisible();
const privateOnly = await generatedManifest(page);
expect(privateOnly.steps).toEqual([]); expect(privateOnly.parts).toEqual([]);
expect(privateOnly.componentLibrary.components.map((c: any) => c.name)).toEqual(['躯干', '躯干1', '躯干2']);
expect(privateOnly.componentLibrary.parts).toHaveLength(2);
const torso = privateOnly.componentLibrary.components[0];
expect(torso.steps.map((s: any) => s.label)).toEqual(['安装组件 躯干2', '安装组件 躯干1']);
await dialog.getByText('步骤编排', { exact: true }).click();
await expect(dialog.getByRole('tab', { name: '步骤 0', exact: true })).toBeVisible();
await dialog.getByRole('checkbox', { name: '选择组件 躯干', exact: true }).check();
await expect(dialog.getByRole('tab', { name: '步骤 1', exact: true })).toBeVisible();
await dialog.getByRole('button', { name: '从 −X 进入', exact: true }).click();
const total = await generatedManifest(page);
expect(total.steps).toHaveLength(1); expect(total.steps[0].componentId).toBe(torso.id);
expect(total.steps[0].installOffset).toEqual([-.08, 0, 0]);
expect(total.parts).toHaveLength(2); expect(total.componentLibrary.parts).toEqual([]);
expect(total.componentLibrary.components[0].steps).toEqual(torso.steps);
const restored = await page.evaluate(async ({ privateOnly, total }) => {
const rp = '/src/utils/boundAssembly.ts', ep = '/src/utils/assemblyEditor.ts', wp = '/src/utils/assemblyWorkflow.ts';
const { restoreAssemblyDocument } = await import(rp), { assemblyManifest } = await import(ep), { workflowForSave, assemblyStages } = await import(wp);
const make = (json: any) => {
const sources = json.files.map((f: any) => ({ asset: { assetId: f.path, type: 'part-glb', relativePath: f.path, bytes: f.bytes, sha256: f.sha256, status: 'READY' } }));
const session = restoreAssemblyDocument(json, { sources });
return { json: assemblyManifest(workflowForSave(session.assembly), sources, json), stages: assemblyStages(session.assembly).map((s: any) => ({ parts: s.parts, offset: s.offset })) };
};
return { privateOnly: make(privateOnly), total: make(total) };
}, { privateOnly, total });
expect(restored.privateOnly.json).toEqual(privateOnly); expect(restored.privateOnly.stages).toEqual([]);
expect(restored.total.json).toEqual(total); expect(restored.total.stages).toHaveLength(1);
expect(restored.total.stages[0].offset).toEqual([-.08, 0, 0]);
await dialog.getByRole('button', { name: '撤销', exact: true }).click();
await dialog.getByRole('button', { name: '撤销', exact: true }).click();
await expect(dialog.getByRole('tab', { name: '步骤 0', exact: true })).toBeVisible();
await expect(dialog.getByRole('button', { name: '编辑库组件 躯干', exact: true })).toBeVisible();
await page.setViewportSize({ width: 1366, height: 768 });
await dialog.getByText('组件制作', { exact: true }).first().click();
await expect.poll(() => dialog.locator('.ant-modal-body').evaluate(el => el.scrollHeight <= el.clientHeight + 1)).toBe(true);
await page.screenshot({ path: testInfo.outputPath('independent-component-library.png'), fullPage: true });
});
test('独立组件库校验:重复零件、循环层级、非法子组件引用和删除引用目标均拒绝,保存组件不要求总装', async ({ page }) => {
await workspace(page, { resourceApi: true });
const checked = await page.evaluate(async () => {
const lp = '/src/utils/assemblyLibrary.ts', wp = '/src/utils/assemblyWorkflow.ts';
const { libraryProblems, deleteLibraryComponent, createLibraryComponent, editLibraryComponent, insertLibraryComponent, libraryComponentAssembly } = await import(lp), { workflowForSave } = await import(wp);
const part = (id: string) => ({ id, name: id, assetId: id, parentId: null, position: [0,0,0], quaternion: [0,0,0,1], scale: [1,1,1], installOffset: [0,.08,0] });
let a: any = { enabled: true, title: '独立组件', unit: 'meter', referenceAssetId: null, displayQuaternion: [0,0,0,1], parts: [part('p1'), part('p2')], steps: [] };
const parent = createLibraryComponent(a, '躯干', null); a = parent.assembly;
const child = createLibraryComponent(a, '躯干1', parent.componentId); a = child.assembly;
const local = libraryComponentAssembly(a, child.componentId); local.steps = [{ id: 'inside', label: '安装p1', parts: ['p1'] }];
a = editLibraryComponent(a, child.componentId, local);
const validPrivate = workflowForSave(a);
const parentLocal = insertLibraryComponent(libraryComponentAssembly(a, parent.componentId), a, child.componentId, parent.componentId);
a = editLibraryComponent(a, parent.componentId, parentLocal);
const total = insertLibraryComponent(a, a, parent.componentId, null);
const duplicate = structuredClone(a); duplicate.componentLibrary.components[0].steps.push({ id: 'duplicate', label: '重复', parts: ['p1'] }); duplicate.componentLibrary.components[0].parts.push('p1');
const cycle = structuredClone(a); cycle.componentLibrary.components[0].parentId = child.componentId;
const invalid = structuredClone(a); invalid.componentLibrary.components[0].steps[0].componentId = parent.componentId;
let deletion = ''; try { deleteLibraryComponent(total, child.componentId); } catch (e) { deletion = String(e); }
let repeated = ''; try { insertLibraryComponent(total, total, parent.componentId, null); } catch (e) { repeated = String(e); }
return { privateSteps: validPrivate.steps.length, privateParts: validPrivate.parts.map((p: any) => p.id), valid: libraryProblems(a), duplicate: libraryProblems(duplicate), cycle: libraryProblems(cycle), invalid: libraryProblems(invalid), deletion, repeated };
});
expect(checked.privateSteps).toBe(0); expect(checked.privateParts).toEqual(['p1']); expect(checked.valid).toEqual([]);
expect(checked.duplicate.join()).toContain('不能归属多个组件'); expect(checked.cycle.join()).toContain('循环');
expect(checked.invalid.length).toBeGreaterThan(0); expect(checked.deletion).toContain('已被步骤引用'); expect(checked.repeated).toContain('不能重复加入');
});
test('组件库上传协议:保存空父子组件仅上传一次JSON,原总装步骤不变,刷新后从资源接口恢复组件层级', async ({ page }) => {
const { manifest, state } = await boundAssemblyWorkspace(page);
const dialog = await editorDialog(page);
await dialog.getByText('组件制作', { exact: true }).first().click();
await dialog.getByRole('button', { name: '创建组件', exact: true }).first().click();
await page.getByRole('textbox', { name: '独立组件名称' }).fill('手臂');
await page.getByRole('button', { name: '创建并制作' }).click();
await dialog.getByRole('button', { name: '创建子组件', exact: true }).click();
await page.getByRole('textbox', { name: '独立组件名称' }).fill('前臂');
await page.getByRole('button', { name: '创建并制作' }).click();
let uploaded: any, signatures = 0, confirmations = 0;
await page.route('**/resources/assembly-json/signature', route => {
signatures++;
return ok(route, { batchCode: 'library-only', uploadUrl: 'https://library-upload.example.com', expiresAt: '2099-01-01T00:00:00Z', files: route.request().postDataJSON().files.map((f: any) => ({ relativePath: f.relativePath, formFields: { key: f.relativePath } })) });
});
await page.route('https://library-upload.example.com/**', route => {
const raw = route.request().postData()!;
uploaded = JSON.parse(raw.slice(raw.indexOf('{\n'), raw.lastIndexOf('\n}') + 2));
Object.assign(manifest, uploaded);
return route.fulfill({ status: 200 });
});
await page.route('**/resources/assembly-json', route => {
confirmations++;
return ok(route, { projectCode: 'project-a', repoStatus: 'READY', modelGlbUrl: null, modelPartsBaseUrl: 'https://bound.example.com/', modelPartsFiles: ['leg.glb', '内六角扳手.glb'].map(relativePath => ({ relativePath, sizeBytes: editorGlb().length, url: `https://bound.example.com/${relativePath}` })), assemblyJsonUrl: 'https://bound.example.com/assembly.json' });
});
await dialog.getByRole('button', { name: '保存组件库', exact: true }).click();
await expect.poll(() => confirmations).toBe(1);
expect(signatures).toBe(1); expect(uploaded.steps).toEqual([{ id: 'step-1', label: '原安装步骤', parts: ['leg'], toolId: 'hex-key', duration: 1200 }]);
expect(uploaded.componentLibrary.components.map((c: any) => c.name)).toEqual(['手臂', '前臂']);
await page.reload();
await page.getByRole('tab', { name: '装配与仿真' }).click();
const reopened = await editorDialog(page);
await expect(reopened.getByRole('button', { name: '编辑库组件 前臂', exact: true })).toBeVisible();
await expect(reopened.getByRole('tab', { name: '步骤 1', exact: true })).toBeVisible();
expect(state.calls.filter(c => c.method !== 'GET')).toHaveLength(0);
});