From 678385838334c9bbdc8b877da42bcc8811549488 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E6=9D=8E=E5=BA=B7?= Date: Wed, 28 Oct 2026 16:31:42 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E4=B8=8A=E4=BC=A0=E6=96=87?= =?UTF-8?q?=E4=BB=B6=EF=BC=8C=E4=B8=8A=E4=BC=A0=E5=B0=81=E9=9D=A2=E5=9B=BE?= =?UTF-8?q?=EF=BC=8C=E4=B8=8A=E4=BC=A0urdf=E8=BF=87=E6=BB=A4=E6=96=87?= =?UTF-8?q?=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 4 +- deploy/nginx.dev-api-location.conf | 3 +- deploy/nginx.prod-api-location.conf | 3 +- deploy/nginx.prod.conf | 3 +- deploy/nginx.test.conf | 3 +- src/api/index.ts | 27 +++- src/api/request.ts | 55 +++++++ src/components/ProjectFields.tsx | 2 +- src/components/project/FileBrowser.tsx | 133 ++++++++++++++--- src/components/project/UrdfDirPicker.tsx | 26 +++- src/components/project/projectUpload.ts | 28 ++++ src/components/project/urdfFiles.ts | 23 +++ src/utils/compressImage.ts | 89 ++++++++++++ tests/cover-compression.spec.ts | 44 ++++++ tests/project-upload.spec.ts | 137 ++++++++++++++++++ tests/urdf.spec.ts | 174 +++++++++++++++++++++++ vite.config.ts | 2 +- 17 files changed, 713 insertions(+), 43 deletions(-) create mode 100644 src/components/project/projectUpload.ts create mode 100644 src/components/project/urdfFiles.ts create mode 100644 src/utils/compressImage.ts create mode 100644 tests/cover-compression.spec.ts create mode 100644 tests/project-upload.spec.ts create mode 100644 tests/urdf.spec.ts diff --git a/README.md b/README.md index 63a068b..2414e2e 100644 --- a/README.md +++ b/README.md @@ -49,9 +49,9 @@ DevTools 中 `preflight` 是浏览器发送的 OPTIONS 跨域预检,`fetch` - 用户管理:列表筛选、详情、名下项目、编辑昵称、启用/禁用(不可禁用自己与官方账号) - 项目管理:列表筛选、新建(封面 OSS 直传、归属官方或普通用户)、编辑、删除 - 发布 / 更新发布 / 撤回 / 下架 / 解除下架(发布前确认当前 main SHA,409 冲突需刷新重新确认) -- 文件:目录浏览、预览(文本/图片)、在线编辑提交、新建文件/目录、删除文件、多文件/文件夹上传(含限额与路径预检)、鉴权下载 +- 文件:目录浏览、预览(文本/图片)、在线编辑提交、新建文件/目录、删除文件、多文件/文件夹上传(单次合计 ≤ 1 GiB,含选择、限额与路径预检、进度反馈)、鉴权下载 - 提交历史,并可只读浏览任一历史版本 -- URDF 目录上传绑定(签名 → 并发 OSS 直传 → 确认)与移除 +- URDF 目录上传绑定(签名 → 并发 OSS 直传 → 确认)与移除;项目详情和迁移页均按扩展名保留 URDF、模型、材质、贴图及模型数据,过滤代码、文档、配置、隐藏文件和依赖目录,数量/大小限制仅计算待上传资源 - GitHub 迁移:预检 → 补充信息(可选上传封面、URDF)→ 创建任务并绑定资源 → 3 秒串行轮询阶段 → 检查后手动发布;重复来源跳转已有项目 - 迁移重试:`FAILED`、`REVIEW` 始终提供手动重试入口,不按 `canRetry` 隐藏;列表点击重试即进入任务确认框,展示 `retryMessage`,由重试接口判断是否受理;支持 `CLEANING` 清理阶段,409 后刷新状态,网络异常时先查询确认结果 diff --git a/deploy/nginx.dev-api-location.conf b/deploy/nginx.dev-api-location.conf index 4e56100..0474ecc 100644 --- a/deploy/nginx.dev-api-location.conf +++ b/deploy/nginx.dev-api-location.conf @@ -8,7 +8,8 @@ location ^~ /admin-api/ { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; - client_max_body_size 60m; + # 前端单次文件合计上限为 1 GiB;预留 multipart 请求体开销。 + client_max_body_size 1100m; proxy_read_timeout 300s; proxy_send_timeout 300s; } diff --git a/deploy/nginx.prod-api-location.conf b/deploy/nginx.prod-api-location.conf index d538024..f87f2b9 100644 --- a/deploy/nginx.prod-api-location.conf +++ b/deploy/nginx.prod-api-location.conf @@ -8,7 +8,8 @@ location ^~ /admin-api/ { proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; - client_max_body_size 60m; + # 前端单次文件合计上限为 1 GiB;预留 multipart 请求体开销。 + client_max_body_size 1100m; proxy_read_timeout 300s; proxy_send_timeout 300s; } diff --git a/deploy/nginx.prod.conf b/deploy/nginx.prod.conf index a054bca..0ffbcf3 100644 --- a/deploy/nginx.prod.conf +++ b/deploy/nginx.prod.conf @@ -13,7 +13,8 @@ server { root /usr/share/nginx/vibemake-admin; index index.html; - client_max_body_size 60m; + # 前端单次文件合计上限为 1 GiB;预留 multipart 请求体开销。 + client_max_body_size 1100m; # 后台接口反向代理 location ^~ /admin-api/ { diff --git a/deploy/nginx.test.conf b/deploy/nginx.test.conf index 9763926..135f370 100644 --- a/deploy/nginx.test.conf +++ b/deploy/nginx.test.conf @@ -13,7 +13,8 @@ server { root /usr/share/nginx/vibemake-admin; index index.html; - client_max_body_size 60m; + # 前端单次文件合计上限为 1 GiB;预留 multipart 请求体开销。 + client_max_body_size 1100m; # 后台接口反向代理 location ^~ /admin-api/ { diff --git a/src/api/index.ts b/src/api/index.ts index 5755bfc..6f7492c 100644 --- a/src/api/index.ts +++ b/src/api/index.ts @@ -1,4 +1,5 @@ -import { downloadAdmin, queryString, requestAdmin, setToken, uploadOssFile } from './request'; +import { downloadAdmin, queryString, requestAdmin, requestAdminUpload, setToken, uploadOssFile } from './request'; +import { compressCoverImage } from '@/utils/compressImage'; import type { AdminView, CommitInput, @@ -139,6 +140,7 @@ export function uploadProjectFiles( message: string, selected: SelectedFile[], directory = '', + onProgress?: (loaded: number, total: number) => void, ): Promise { const form = new FormData(); form.append('expectedCommitSha', expectedCommitSha); @@ -148,19 +150,30 @@ export function uploadProjectFiles( form.append('files', item.file, item.file.name); form.append('paths', item.relativePath); } - return requestAdmin(`/projects/${enc(code)}/uploads/commit`, { - method: 'POST', - body: form, - }); + const totalBytes = selected.reduce((sum, item) => sum + item.file.size, 0); + return requestAdminUpload( + `/projects/${enc(code)}/uploads/commit`, + form, + (loaded, requestTotal) => { + if (!onProgress) return; + if (!requestTotal) { + onProgress(0, totalBytes); + return; + } + onProgress(Math.min(totalBytes, Math.round((loaded / requestTotal) * totalBytes)), totalBytes); + }, + () => onProgress?.(totalBytes, totalBytes), + ); } // ---------- 封面 ---------- export async function uploadCover(file: File): Promise { + const uploadFile = await compressCoverImage(file); const signature = await requestAdmin('/uploads/project-covers/signature', { method: 'POST', - body: { contentType: file.type, fileSize: file.size }, + body: { contentType: uploadFile.type, fileSize: uploadFile.size }, }); - await uploadOssFile(signature.uploadUrl, signature.formFields, file); + await uploadOssFile(signature.uploadUrl, signature.formFields, uploadFile); return signature.coverUrl; } diff --git a/src/api/request.ts b/src/api/request.ts index e8fde64..a8d88a8 100644 --- a/src/api/request.ts +++ b/src/api/request.ts @@ -80,6 +80,61 @@ export async function requestAdmin(path: string, options: AdminRequestOptions return result.data; } +/** 带上传进度的管理端 multipart 请求。XHR 才能监听请求体上传进度。 */ +export function requestAdminUpload( + path: string, + body: FormData, + onProgress?: (loaded: number, total: number) => void, + onUploadComplete?: () => void, +): Promise { + return new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + let lastTotal = 0; + let uploadComplete = false; + const signalUploadComplete = () => { + if (uploadComplete) return; + uploadComplete = true; + if (lastTotal > 0) onProgress?.(lastTotal, lastTotal); + onUploadComplete?.(); + }; + xhr.open('POST', `${ADMIN_API_BASE}${path}`); + buildHeaders().forEach((value, key) => xhr.setRequestHeader(key, value)); + xhr.upload.onprogress = (event) => { + if (event.lengthComputable) lastTotal = event.total; + onProgress?.(event.loaded, event.lengthComputable ? event.total : 0); + }; + xhr.upload.onload = signalUploadComplete; + xhr.upload.onloadend = signalUploadComplete; + xhr.onerror = () => reject(new TypeError('网络异常,请检查网络后刷新确认结果')); + xhr.onabort = () => reject(new DOMException('请求已取消', 'AbortError')); + xhr.onload = () => { + let result: ApiResponse | null = null; + try { + result = JSON.parse(xhr.responseText || 'null') as ApiResponse | null; + } catch { + // Keep response parsing failures on the normal API error path. + } + if (xhr.status < 200 || xhr.status >= 300 || result?.code !== 'OK') { + handle401(path, xhr.status); + reject(new AdminApiError( + xhr.status, + result?.code ?? 'INVALID_RESPONSE', + result?.message ?? `服务响应异常(HTTP ${xhr.status}),请稍后查看状态`, + result?.requestId ?? xhr.getResponseHeader('X-Request-Id'), + result?.data, + )); + return; + } + resolve(result.data); + }; + try { + xhr.send(body); + } catch (error) { + reject(error); + } + }); +} + /** 带鉴权的二进制下载,不经过 JSON 解包 */ export async function downloadAdmin(path: string, fallbackName: string): Promise { const response = await fetch(`${ADMIN_API_BASE}${path}`, { headers: buildHeaders() }); diff --git a/src/components/ProjectFields.tsx b/src/components/ProjectFields.tsx index 22269e4..b484986 100644 --- a/src/components/ProjectFields.tsx +++ b/src/components/ProjectFields.tsx @@ -15,7 +15,7 @@ export default function ProjectFields({ types }: { types: TypeView[] }) { setCommitMsg(e.target.value)} /> + {progress && ( +
+ + {progress.status === 'error' + ? '上传失败,可修改选择后重试' + : progress.status === 'processing' + ? '正在处理并提交版本' + : '正在上传文件'} + + 0 ? Math.min(100, Math.round((progress.loaded / progress.total) * 100)) : 0} + format={() => progress.status === 'processing' + ? '正在处理' + : `${formatSize(progress.loaded)} / ${formatSize(progress.total)}`} + /> +
+ )} + setCommitMsg(e.target.value)} + /> ); diff --git a/src/components/project/UrdfDirPicker.tsx b/src/components/project/UrdfDirPicker.tsx index 8376722..c5f05ba 100644 --- a/src/components/project/UrdfDirPicker.tsx +++ b/src/components/project/UrdfDirPicker.tsx @@ -4,6 +4,7 @@ import { CloseOutlined, FolderOpenOutlined } from '@ant-design/icons'; import type { SelectedFile } from '@/api/types'; import { formatSize, MiB } from '@/utils/format'; import { pickFiles, toSelected, validatePath } from './pickFiles'; +import { filterUrdfFiles } from './urdfFiles'; export interface UrdfSelection { selected: SelectedFile[]; @@ -26,7 +27,15 @@ export function checkUrdf(selected: SelectedFile[]): string[] { ].filter(Boolean) as string[]; } -/** URDF 目录选择:生成相对路径清单并展示校验结果 */ +function getUrdfSelection(files: File[], keepRoot: boolean): UrdfSelection { + const selected = toSelected(filterUrdfFiles(files), keepRoot); + const problems = files.length > 0 && selected.length === 0 + ? ['所选目录中没有可上传的 URDF 渲染资源,请重新选择目录或清除选择'] + : checkUrdf(selected); + return { selected, problems }; +} + +/** URDF 目录选择:过滤非渲染资源,生成相对路径清单并展示校验结果 */ export default function UrdfDirPicker({ onChange, disabled, @@ -37,13 +46,12 @@ export default function UrdfDirPicker({ const [raw, setRaw] = useState([]); const [keepRoot, setKeepRoot] = useState(false); - const selected = useMemo(() => toSelected(raw, keepRoot), [raw, keepRoot]); - const problems = useMemo(() => checkUrdf(selected), [selected]); + const { selected, problems } = useMemo(() => getUrdfSelection(raw, keepRoot), [raw, keepRoot]); + const filteredCount = raw.length - selected.length; const total = selected.reduce((s, f) => s + f.file.size, 0); const emit = (files: File[], keep: boolean) => { - const sel = toSelected(files, keep); - onChange({ selected: sel, problems: checkUrdf(sel) }); + onChange(getUrdfSelection(files, keep)); }; const choose = async () => { @@ -69,6 +77,9 @@ export default function UrdfDirPicker({ )} + + 支持 URDF、STL/DAE/OBJ、GLTF/GLB/FBX/PLY、MTL、BIN 及常见贴图;自动过滤代码、文档、配置和隐藏文件。 + {raw.length > 0 && ( <> @@ -82,7 +93,10 @@ export default function UrdfDirPicker({ > 保留所选文件夹名称 - {selected.length} 个文件 · {formatSize(total)} + + 待上传 {selected.length} 个文件 · {formatSize(total)} + {filteredCount > 0 && ` · 已过滤 ${filteredCount} 个无关文件`} +
{selected.map((f) => ( diff --git a/src/components/project/projectUpload.ts b/src/components/project/projectUpload.ts new file mode 100644 index 0000000..fc5a7bf --- /dev/null +++ b/src/components/project/projectUpload.ts @@ -0,0 +1,28 @@ +import type { SelectedFile } from '@/api/types'; +import { joinPath, validatePath } from './pickFiles'; + +const MiB = 1024 * 1024; +export const MAX_PROJECT_UPLOAD_TOTAL = 1024 * MiB; +export const MAX_PROJECT_UPLOAD_FILE = 50 * MiB; +export const MAX_PROJECT_UPLOAD_COUNT = 500; + +function formatProjectSize(bytes: number): string { + if (bytes < 1024) return `${bytes} B`; + if (bytes < MiB) return `${(bytes / 1024).toFixed(1)} KB`; + return `${(bytes / MiB).toFixed(2)} MB`; +} + +export function validateProjectUpload(selected: SelectedFile[], directory: string): string[] { + const total = selected.reduce((sum, item) => sum + item.file.size, 0); + const tooBig = selected.filter((item) => item.file.size > MAX_PROJECT_UPLOAD_FILE); + const pathError = selected + .map((item) => validatePath(joinPath(directory, item.relativePath))) + .find(Boolean); + return [ + selected.length === 0 && '至少选择一个文件', + selected.length > MAX_PROJECT_UPLOAD_COUNT && `单次最多 ${MAX_PROJECT_UPLOAD_COUNT} 个文件,请分批上传`, + total > MAX_PROJECT_UPLOAD_TOTAL && `合计 ${formatProjectSize(total)},超过 1 GiB,请分批上传`, + tooBig.length > 0 && `${tooBig.length} 个文件超过单文件 50 MiB 限制:${tooBig.slice(0, 3).map((item) => item.relativePath).join('、')}`, + pathError && `存在非法路径:${pathError}`, + ].filter(Boolean) as string[]; +} diff --git a/src/components/project/urdfFiles.ts b/src/components/project/urdfFiles.ts new file mode 100644 index 0000000..be6cdab --- /dev/null +++ b/src/components/project/urdfFiles.ts @@ -0,0 +1,23 @@ +// URDF 预览可能依赖模型、材质、外部二进制数据和贴图;按扩展名保留资源, +// 不改写相对路径,避免破坏 URDF → mesh → 材质/贴图之间的引用。 +const RENDER_EXTENSIONS = new Set([ + 'urdf', + 'stl', 'dae', 'obj', 'gltf', 'glb', 'fbx', 'ply', '3ds', '3mf', + 'mtl', 'bin', 'drc', + 'png', 'jpg', 'jpeg', 'jpe', 'jfif', 'webp', 'avif', 'bmp', 'gif', + 'tga', 'tif', 'tiff', 'dds', 'ktx', 'ktx2', 'basis', 'hdr', 'exr', 'svg', +]); + +/** 过滤 URDF 目录中的非渲染资源,以及隐藏文件、依赖目录和系统元数据。 */ +export function filterUrdfFiles(files: File[]): File[] { + return files.filter((file) => { + const path = file.webkitRelativePath || file.name; + const parts = path.split('/'); + if (parts.some((part) => part.startsWith('.') || part === '__MACOSX' || part === 'node_modules')) { + return false; + } + const name = parts[parts.length - 1]; + const dot = name.lastIndexOf('.'); + return dot > 0 && RENDER_EXTENSIONS.has(name.slice(dot + 1).toLowerCase()); + }); +} diff --git a/src/utils/compressImage.ts b/src/utils/compressImage.ts new file mode 100644 index 0000000..88efb50 --- /dev/null +++ b/src/utils/compressImage.ts @@ -0,0 +1,89 @@ +export const COVER_MAX_BYTES = 5 * 1024 * 1024; + +const MAX_WIDTH = 768; +const MAX_HEIGHT = 480; +const TARGET_BYTES = 500 * 1024; +const DEFAULT_QUALITY = 0.72; +const FALLBACK_QUALITY = 0.62; + +type DecodedImage = { + source: CanvasImageSource; + width: number; + height: number; + dispose: () => void; +}; + +async function decodeImage(file: File): Promise { + if (typeof createImageBitmap === 'function') { + try { + const bitmap = await createImageBitmap(file, { imageOrientation: 'from-image' }); + return { source: bitmap, width: bitmap.width, height: bitmap.height, dispose: () => bitmap.close() }; + } catch { + // Fall back to an HTMLImageElement for browsers without ImageBitmap support. + } + } + + const objectUrl = URL.createObjectURL(file); + try { + const image = await new Promise((resolve, reject) => { + const element = new Image(); + element.onload = () => resolve(element); + element.onerror = () => reject(new Error('无法读取封面图片')); + element.src = objectUrl; + }); + return { + source: image, + width: image.naturalWidth, + height: image.naturalHeight, + dispose: () => URL.revokeObjectURL(objectUrl), + }; + } catch (error) { + URL.revokeObjectURL(objectUrl); + throw error; + } +} + +function canvasBlob(canvas: HTMLCanvasElement, quality: number): Promise { + return new Promise((resolve) => canvas.toBlob(resolve, 'image/webp', quality)); +} + +/** Resize covers for the largest current display and encode them as a compact WebP. */ +export async function compressCoverImage(file: File): Promise { + if (file.size <= 0 || file.size > COVER_MAX_BYTES) return file; + + let decoded: DecodedImage; + try { + decoded = await decodeImage(file); + } catch { + return file; + } + + try { + if (decoded.width <= 0 || decoded.height <= 0) return file; + const scale = Math.min(1, MAX_WIDTH / decoded.width, MAX_HEIGHT / decoded.height); + const width = Math.max(1, Math.round(decoded.width * scale)); + const height = Math.max(1, Math.round(decoded.height * scale)); + const canvas = document.createElement('canvas'); + canvas.width = width; + canvas.height = height; + const context = canvas.getContext('2d'); + if (!context) return file; + context.drawImage(decoded.source, 0, 0, width, height); + + const candidates: Blob[] = []; + const normal = await canvasBlob(canvas, DEFAULT_QUALITY); + if (normal) candidates.push(normal); + if (normal && normal.size > TARGET_BYTES) { + const smaller = await canvasBlob(canvas, FALLBACK_QUALITY); + if (smaller) candidates.push(smaller); + } + const smallest = candidates.sort((a, b) => a.size - b.size)[0]; + if (!smallest || smallest.type !== 'image/webp' || smallest.size >= file.size) return file; + const name = file.name.replace(/\.[^.]+$/, '') || 'cover'; + return new File([smallest], `${name}.webp`, { type: 'image/webp', lastModified: file.lastModified }); + } catch { + return file; + } finally { + decoded.dispose(); + } +} diff --git a/tests/cover-compression.spec.ts b/tests/cover-compression.spec.ts new file mode 100644 index 0000000..bc9fe55 --- /dev/null +++ b/tests/cover-compression.spec.ts @@ -0,0 +1,44 @@ +import { expect, test } from '@playwright/test'; + +test('封面上传前按比例缩放并压缩为更小的 WebP', async ({ page }) => { + await page.goto('/login'); + const result = await page.evaluate(async () => { + const canvas = document.createElement('canvas'); + canvas.width = 1600; + canvas.height = 1000; + const context = canvas.getContext('2d'); + if (!context) throw new Error('Canvas 不可用'); + const gradient = context.createLinearGradient(0, 0, canvas.width, canvas.height); + gradient.addColorStop(0, '#e53935'); + gradient.addColorStop(0.5, '#43a047'); + gradient.addColorStop(1, '#1e88e5'); + context.fillStyle = gradient; + context.fillRect(0, 0, canvas.width, canvas.height); + for (let i = 0; i < 120; i++) { + context.fillStyle = `rgba(${i * 2}, ${255 - i}, ${i}, 0.7)`; + context.fillRect((i * 137) % canvas.width, (i * 83) % canvas.height, 180, 96); + } + const sourceBlob = await new Promise((resolve, reject) => { + canvas.toBlob((blob) => blob ? resolve(blob) : reject(new Error('JPEG 编码失败')), 'image/jpeg', 0.94); + }); + const source = new File([sourceBlob], 'robot-cover.jpg', { type: 'image/jpeg' }); + const { compressCoverImage } = await import('/src/utils/compressImage.ts'); + const compressed = await compressCoverImage(source); + const decoded = await createImageBitmap(compressed); + const result = { + sourceSize: source.size, + outputSize: compressed.size, + type: compressed.type, + width: decoded.width, + height: decoded.height, + }; + decoded.close(); + return result; + }); + + expect(result.type).toBe('image/webp'); + expect(result.outputSize).toBeLessThan(result.sourceSize); + expect(result.width).toBeLessThanOrEqual(768); + expect(result.height).toBeLessThanOrEqual(480); + expect(result.width / result.height).toBeCloseTo(1.6, 1); +}); diff --git a/tests/project-upload.spec.ts b/tests/project-upload.spec.ts new file mode 100644 index 0000000..fe25e45 --- /dev/null +++ b/tests/project-upload.spec.ts @@ -0,0 +1,137 @@ +import { expect, test, type Page, type Route } from '@playwright/test'; +import { MAX_PROJECT_UPLOAD_FILE, MAX_PROJECT_UPLOAD_TOTAL, validateProjectUpload } from '../src/components/project/projectUpload'; +import type { ManagedProjectView, SelectedFile } from '../src/api/types'; + +const project: ManagedProjectView = { + project: { + projectCode: 'upload-test', name: '上传测试项目', description: '', coverUrl: null, + urdfMainUrl: null, urdfBaseUrl: null, projectType: 'WHEELED', + owner: { userCode: null, nickname: '社区官方' }, repoStatus: 'READY', publishStatus: 'UNPUBLISHED', + publishedCommitSha: null, publishedAt: null, sourceProjectCode: null, sourceCommitSha: null, + likeCount: 0, commentCount: 0, liked: false, sourceRepositoryUrl: null, sourceLicense: null, + createdAt: '2026-10-27T00:00:00', updatedAt: '2026-10-27T00:00:00', + }, + moderationStatus: 'NORMAL', moderationReason: null, deleted: false, +}; + +async function ok(route: Route, data: unknown) { + await route.fulfill({ json: { code: 'OK', message: '成功', data, requestId: null } }); +} + +async function prepare(page: Page, onCommit: (route: Route) => Promise) { + await page.addInitScript(() => localStorage.setItem('vibemake_admin_token', 'test-token')); + await page.route('https://fonts.googleapis.com/**', (route) => route.abort()); + await page.route('**/admin-api/**', async (route) => { + const path = new URL(route.request().url()).pathname.replace('/admin-api', ''); + if (path === '/auth/me') return ok(route, { userCode: 'admin', nickname: '测试管理员', role: 'ADMIN' }); + if (path === '/projects/types') return ok(route, [{ code: 'WHEELED', name: '轮式机器人' }]); + if (path === '/projects/upload-test') return ok(route, project); + if (path.endsWith('/tree')) return ok(route, { commitSha: 'main-sha', path: '', entries: [] }); + if (path.endsWith('/commits')) return ok(route, { items: [], page: 1, size: 20, total: 0 }); + if (path.endsWith('/uploads/commit')) return onCommit(route); + return ok(route, { items: [], page: 1, size: 20, total: 0 }); + }); + await page.goto('/projects/upload-test'); + await page.getByRole('button', { name: '上传' }).click(); +} + +async function chooseDirectory(page: Page) { + const parent = await import('node:fs/promises').then(({ mkdtemp }) => mkdtemp('/tmp/project-upload-')); + const fs = await import('node:fs/promises'); + const path = await import('node:path'); + const directory = path.join(parent, 'robot'); + try { + await fs.mkdir(path.join(directory, 'left'), { recursive: true }); + await fs.mkdir(path.join(directory, 'right'), { recursive: true }); + await fs.writeFile(path.join(directory, 'left', 'model.stl'), '1234'); + await fs.writeFile(path.join(directory, 'right', 'notes.txt'), 'abcd'); + const chooser = page.waitForEvent('filechooser'); + await page.getByRole('menuitem', { name: '上传文件夹' }).click(); + await (await chooser).setFiles(directory); + } finally { + await fs.rm(parent, { recursive: true, force: true }); + } +} + +test('项目文件夹上传可勾选路径并展示实际上传进度', async ({ page }) => { + let requestBody = ''; + let finishCommit!: () => void; + const commitGate = new Promise((resolve) => { finishCommit = resolve; }); + await prepare(page, async (route) => { + requestBody = route.request().postDataBuffer()?.toString('utf8') ?? ''; + await commitGate; + await ok(route, { commitSha: 'new-sha', message: '上传文件' }); + }); + await chooseDirectory(page); + + const keepRoot = page.getByRole('checkbox', { name: '保留所选文件夹名称' }); + await expect(keepRoot).not.toBeChecked(); + await expect(page.getByText('left/model.stl', { exact: true })).toBeVisible(); + await expect(page.getByText('right/notes.txt', { exact: true })).toBeVisible(); + + const notes = page.getByRole('checkbox', { name: '选择 right/notes.txt' }); + await notes.uncheck(); + await expect(page.getByText(/目标目录:.*1 个文件 · 4 B/)).toBeVisible(); + + await keepRoot.check(); + await expect(page.getByRole('checkbox', { name: '选择 robot/left/model.stl' })).toBeChecked(); + await expect(page.getByRole('checkbox', { name: '选择 robot/right/notes.txt' })).not.toBeChecked(); + await page.getByRole('checkbox', { name: '选择 robot/left/model.stl' }).uncheck(); + await expect(page.getByText('至少选择一个文件', { exact: true })).toBeVisible(); + await expect(page.getByRole('button', { name: '提交上传' })).toBeDisabled(); + await page.getByRole('checkbox', { name: '选择 robot/left/model.stl' }).check(); + + await page.getByPlaceholder('提交说明(必填)').fill('只上传模型'); + await page.getByRole('button', { name: '提交上传' }).click(); + const failsafe = setTimeout(finishCommit, 8000); + await expect(page.getByText('正在上传文件')).toBeVisible(); + await expect(page.getByRole('progressbar')).toBeVisible(); + await expect(page.getByPlaceholder('提交说明(必填)')).toBeDisabled(); + finishCommit(); + await expect(page.getByText('上传成功,新版本 new-sha')).toBeVisible(); + expect(requestBody).toContain('robot/left/model.stl'); + expect(requestBody).not.toContain('robot/right/notes.txt'); + expect(requestBody).toContain('只上传模型'); + clearTimeout(failsafe); +}); + +test('上传失败保留弹窗和选择状态,可重试', async ({ page }) => { + let attempts = 0; + await prepare(page, async (route) => { + attempts += 1; + if (attempts === 1) { + await route.fulfill({ status: 500, json: { code: 'UPLOAD_FAILED', message: '模拟上传失败', data: null } }); + } else { + await ok(route, { commitSha: 'retry-sha', message: '重试上传' }); + } + }); + await chooseDirectory(page); + const first = page.getByRole('checkbox', { name: '选择 left/model.stl' }); + await first.uncheck(); + await page.getByRole('button', { name: '提交上传' }).click(); + await expect(page.getByText('上传失败,可修改选择后重试')).toBeVisible(); + await expect(first).not.toBeChecked(); + await expect(page.getByRole('button', { name: '提交上传' })).toBeEnabled(); + await first.check(); + await page.getByRole('button', { name: '提交上传' }).click(); + await expect(page.getByText('上传成功,新版本 retry-sha')).toBeVisible(); + expect(attempts).toBe(2); +}); + +test('项目文件上传限制只校验已选文件并允许总计正好 1 GiB', () => { + const file = (size: number, relativePath: string): SelectedFile => ({ + file: { size } as File, + relativePath, + }); + const exactTotal = [ + ...Array.from({ length: 20 }, (_, index) => file(MAX_PROJECT_UPLOAD_FILE, `${index}.bin`)), + file(24 * 1024 * 1024, 'last.bin'), + ]; + expect(validateProjectUpload(exactTotal, '')).toEqual([]); + expect(validateProjectUpload([...exactTotal, file(1, 'overflow.bin')], '').find((problem) => problem.includes('超过 1 GiB'))).toBeTruthy(); + expect(validateProjectUpload([file(MAX_PROJECT_UPLOAD_FILE + 1, 'large.bin')], '')[0]).toContain('50 MiB'); + expect(validateProjectUpload(Array.from({ length: 501 }, (_, index) => file(1, `${index}.txt`)), '')[0]).toContain('最多 500 个'); + expect(validateProjectUpload([], '')[0]).toBe('至少选择一个文件'); + expect(validateProjectUpload([file(MAX_PROJECT_UPLOAD_FILE + 1, 'ignored.bin')], '').length).toBeGreaterThan(0); + expect(validateProjectUpload([file(1, 'kept.txt')], '')).toEqual([]); +}); diff --git a/tests/urdf.spec.ts b/tests/urdf.spec.ts new file mode 100644 index 0000000..983f422 --- /dev/null +++ b/tests/urdf.spec.ts @@ -0,0 +1,174 @@ +import { expect, test, type Page, type Route } from '@playwright/test'; +import { mkdtemp, mkdir, rm, writeFile } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import type { ManagedProjectView, UrdfFile } from '../src/api/types'; +import { filterUrdfFiles } from '../src/components/project/urdfFiles'; + +const resources = [ + 'robot.URDF', 'meshes/base.STL', 'meshes/body.dae', 'meshes/arm.obj', + 'materials/arm.mtl', 'meshes/sensor.gltf', 'meshes/sensor.bin', + 'textures/base.PNG', 'textures/arm.ktx2', +]; +const unrelated = [ + 'README.md', 'src/main.py', 'package.xml', 'config/settings.yaml', 'archive.zip', + '.git/backup.urdf', '.DS_Store', '__MACOSX/._base.stl', 'node_modules/example/mesh.obj', +]; + +const project: ManagedProjectView = { + project: { + projectCode: 'test-robot', name: '测试机器人', description: '', coverUrl: null, + urdfMainUrl: null, urdfBaseUrl: null, projectType: 'WHEELED', + owner: { userCode: null, nickname: '社区官方' }, repoStatus: 'READY', publishStatus: 'UNPUBLISHED', + publishedCommitSha: null, publishedAt: null, sourceProjectCode: null, sourceCommitSha: null, + likeCount: 0, commentCount: 0, liked: false, sourceRepositoryUrl: null, sourceLicense: null, + createdAt: '2026-10-27T00:00:00', updatedAt: '2026-10-27T00:00:00', + }, + moderationStatus: 'NORMAL', moderationReason: null, deleted: false, +}; + +async function ok(route: Route, data: unknown) { + await route.fulfill({ json: { code: 'OK', message: '成功', data, requestId: null } }); +} + +async function prepare(page: Page, entry: 'project' | 'import') { + const signed: UrdfFile[][] = []; + const confirmed: UrdfFile[][] = []; + await page.addInitScript(() => localStorage.setItem('vibemake_admin_token', 'test-token')); + await page.addInitScript(() => { + const originalFetch = window.fetch.bind(window); + window.fetch = (input, init) => { + const url = typeof input === 'string' ? input : input instanceof Request ? input.url : input.href; + if (new URL(url, window.location.href).pathname === '/mock-oss' && init?.body instanceof FormData) { + const uploads = JSON.parse(localStorage.getItem('urdf_test_uploads') ?? '[]'); + uploads.push(Object.fromEntries([...init.body.entries()].map(([key, value]) => [key, value instanceof File ? value.name : value]))); + localStorage.setItem('urdf_test_uploads', JSON.stringify(uploads)); + } + return originalFetch(input, init); + }; + }); + await page.route('https://fonts.googleapis.com/**', (route) => route.abort()); + await page.route('**/mock-oss', async (route) => { + await route.fulfill({ status: 204 }); + }); + // 拦截全部管理 API 和 OSS,测试不会向真实后端上传或创建项目。 + await page.route('**/admin-api/**', async (route) => { + const path = new URL(route.request().url()).pathname.replace('/admin-api', ''); + if (path === '/auth/me') return ok(route, { userCode: 'admin', nickname: '测试管理员', role: 'ADMIN' }); + if (path === '/projects/types') return ok(route, [{ code: 'WHEELED', name: '轮式机器人' }]); + if (path === '/projects/test-robot') return ok(route, project); + if (path.endsWith('/tree')) return ok(route, { commitSha: 'main-sha', path: '', entries: [] }); + if (path === '/project-imports/preview') return ok(route, { + repositoryUrl: 'https://github.com/example/robot', defaultBranch: 'main', name: '测试机器人', + description: '', license: null, existingProjectCode: null, + }); + if (path.endsWith('/urdf/signature')) { + const files = route.request().postDataJSON().files as UrdfFile[]; + signed.push(files); + return ok(route, { + batchCode: 'test-batch', mainRelativePath: files[0].relativePath, + uploadUrl: 'http://127.0.0.1:5190/mock-oss', + files: files.map(({ relativePath }) => ({ relativePath, formFields: { key: relativePath } })), + }); + } + if (path.endsWith('/urdf') && route.request().method() === 'PUT') { + confirmed.push(route.request().postDataJSON().files); + return ok(route, project.project); + } + if (path === '/project-imports' && route.request().method() === 'POST') { + confirmed.push(route.request().postDataJSON().urdf.files); + // 留在创建页,便于断言本次提交,避免进入任务轮询。 + return route.fulfill({ status: 409, json: { code: 'DUPLICATE_SOURCE', message: '模拟重复来源', data: null } }); + } + return ok(route, { items: [], page: 1, size: 20, total: 0 }); + }); + if (entry === 'project') { + await page.goto('/projects/test-robot'); + await page.getByRole('tab', { name: 'URDF', exact: true }).click(); + } else { + await page.goto('/imports/new'); + await page.getByRole('textbox', { name: 'GitHub 仓库地址' }).fill('https://github.com/example/robot'); + await page.getByRole('button', { name: /预\s*检/, exact: true }).click(); + await page.getByRole('combobox', { name: '项目类型' }).click(); + await page.getByText('轮式机器人', { exact: true }).click(); + } + return { signed, confirmed }; +} + +async function chooseDirectory(page: Page, paths: string[], label = '选择 URDF 目录') { + const parent = await mkdtemp(join(tmpdir(), 'urdf-filter-')); + const directory = join(parent, 'robot'); + try { + await Promise.all(paths.map(async (path) => { + const fullPath = join(directory, path); + await mkdir(dirname(fullPath), { recursive: true }); + await writeFile(fullPath, 'test'); + })); + const chooser = page.waitForEvent('filechooser'); + await page.getByRole('button', { name: new RegExp(label) }).click(); + await (await chooser).setFiles(directory); + await expect(page.getByRole('button', { name: '重新选择目录' })).toBeVisible(); + } finally { + await rm(parent, { recursive: true, force: true }); + } +} + +for (const entry of ['project', 'import'] as const) { + test(`${entry} URDF 目录仅签名、上传和绑定渲染资源,保留嵌套引用路径`, async ({ page }) => { + const requests = await prepare(page, entry); + await chooseDirectory(page, [...resources, ...unrelated]); + await expect(page.getByText(`已过滤 ${unrelated.length} 个无关文件`, { exact: false })).toBeVisible(); + await expect(page.locator('.file-list-row')).toHaveCount(resources.length); + await expect(page.locator('.file-list-main')).toHaveText('robot.URDF'); + + const keepRoot = page.getByRole('checkbox', { name: '保留所选文件夹名称' }); + await keepRoot.check(); + await expect(page.locator('.file-list-main')).toHaveText('robot/robot.URDF'); + if (entry === 'project') await keepRoot.uncheck(); + const expected = resources.map((relativePath) => ({ + relativePath: entry === 'import' ? `robot/${relativePath}` : relativePath, sizeBytes: 4, + })).sort((a, b) => a.relativePath.localeCompare(b.relativePath)); + await page.getByRole('button', { name: entry === 'project' ? '上传并绑定' : '创建迁移任务', exact: true }).click(); + await expect.poll(() => requests.confirmed.length).toBe(1); + expect(requests.signed).toHaveLength(1); + expect([...requests.signed[0]].sort((a, b) => a.relativePath.localeCompare(b.relativePath))).toEqual(expected); + expect(requests.confirmed[0]).toEqual(requests.signed[0]); + await expect.poll(() => page.evaluate(() => JSON.parse(localStorage.getItem('urdf_test_uploads') ?? '[]').length)).toBe(expected.length); + const uploads = await page.evaluate(() => JSON.parse(localStorage.getItem('urdf_test_uploads') ?? '[]')) as Record[]; + expect(uploads.map(({ key }) => key).sort()).toEqual(expected.map((file) => file.relativePath).sort()); + expect(uploads.map(({ file }) => file).sort()).toEqual(expected.map((file) => file.relativePath.split('/').at(-1)!).sort()); + }); +} + +test('过滤后仍校验多个或缺失的 URDF,全部过滤时阻止创建,清除后可继续', async ({ page }) => { + const requests = await prepare(page, 'import'); + await chooseDirectory(page, ['first.urdf', 'second.URDF', 'README.md']); + await expect(page.getByText('目录中必须有且仅有一个 .urdf 文件(当前 2 个)', { exact: true })).toBeVisible(); + await chooseDirectory(page, ['meshes/base.stl'], '重新选择目录'); + await expect(page.getByText('目录中必须有且仅有一个 .urdf 文件(当前 0 个)', { exact: true })).toBeVisible(); + await chooseDirectory(page, ['README.md', 'src/main.py'], '重新选择目录'); + await expect(page.getByText('所选目录中没有可上传的 URDF 渲染资源,请重新选择目录或清除选择')).toBeVisible(); + await expect(page.locator('.file-list-row')).toHaveCount(0); + await page.getByRole('button', { name: '创建迁移任务', exact: true }).click(); + await expect(page.getByText('URDF 目录不符合要求,请重新选择或清除后再创建')).toBeVisible(); + expect(requests.signed).toHaveLength(0); + expect(requests.confirmed).toHaveLength(0); + await page.getByRole('button', { name: /清\s*除/, exact: true }).click(); + await expect(page.getByText('所选目录中没有可上传的 URDF 渲染资源,请重新选择目录或清除选择')).toHaveCount(0); + await expect(page.getByRole('button', { name: '选择 URDF 目录' })).toBeVisible(); +}); + +test('扩展名大小写不敏感,保留材质和贴图数据,排除伪装扩展名和隐藏路径', () => { + const paths = [ + 'robot.URDF', 'meshes/arm.OBJ', 'materials/arm.MTL', 'textures/base.KTX2', 'mesh.bin', + 'robot.urdf.bak', 'mesh.stl.zip', '.hidden.urdf', '.cache/mesh.stl', + 'assets/.git/mesh.stl', '__MACOSX/mesh.stl', 'node_modules/pkg/model.glb', + ]; + const files = paths.map((path) => { + const file = new File(['test'], path.split('/').at(-1)!); + Object.defineProperty(file, 'webkitRelativePath', { value: `robot/${path}` }); + return file; + }); + expect(filterUrdfFiles(files)).toEqual(files.slice(0, 5)); + expect(filterUrdfFiles([new File(['test'], 'standalone.STL')])).toHaveLength(1); +}); diff --git a/vite.config.ts b/vite.config.ts index 5ef3313..67ff92b 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -25,7 +25,7 @@ export default defineConfig(({ mode }) => { resolve: { alias: { '@': path.resolve(__dirname, 'src') } }, server: { host: '0.0.0.0', - port: 5188, + port: 8091, strictPort: true, // 开发环境统一代理 /admin-api 到后端,避免跨域 proxy,