添加上传step

This commit is contained in:
2026-11-03 15:50:13 +08:00
parent 6783858383
commit 4bd2e7c16b
16 changed files with 1408 additions and 28 deletions
+2
View File
@@ -48,10 +48,12 @@ DevTools 中 `preflight` 是浏览器发送的 OPTIONS 跨域预检,`fetch`
- 登录 / 退出 / 修改密码(401 自动回登录页并保留返回路径)
- 用户管理:列表筛选、详情、名下项目、编辑昵称、启用/禁用(不可禁用自己与官方账号)
- 项目管理:列表筛选、新建(封面 OSS 直传、归属官方或普通用户)、编辑、删除
- 项目日期:编辑信息支持设置/清空发布时间 `publishedAt`;项目管理仅按发布时间倒序,创建时间只展示,查询、重置和分页均保留发布时间排序。按上海时间解析与提交,系统 `updatedAt` 由后端维护。对接既有接口,见 [项目日期对接说明](docs/project-dates-backend-requirements.md)。
- 发布 / 更新发布 / 撤回 / 下架 / 解除下架(发布前确认当前 main SHA,409 冲突需刷新重新确认)
- 文件:目录浏览、预览(文本/图片)、在线编辑提交、新建文件/目录、删除文件、多文件/文件夹上传(单次合计 ≤ 1 GiB,含选择、限额与路径预检、进度反馈)、鉴权下载
- 提交历史,并可只读浏览任一历史版本
- URDF 目录上传绑定(签名 → 并发 OSS 直传 → 确认)与移除;项目详情和迁移页均按扩展名保留 URDF、模型、材质、贴图及模型数据,过滤代码、文档、配置、隐藏文件和依赖目录,数量/大小限制仅计算待上传资源
- STEP 文件管理:URDF 右侧 STEP tab,支持 .step/.stp 单文件上传(≤ 500 MiB)、替换、移除绑定和直接下载。已按后端文档 §8.4 对接签名、OSS 直传和确认;确认异常保留原请求,手动重试前提示重新写入绑定。下载直接使用 `stepMainUrl`,不新增接口、不携带管理 Token。详见 [STEP 接口对接说明](docs/step-backend-requirements.md)。
- GitHub 迁移:预检 → 补充信息(可选上传封面、URDF)→ 创建任务并绑定资源 → 3 秒串行轮询阶段 → 检查后手动发布;重复来源跳转已有项目
- 迁移重试:`FAILED`、`REVIEW` 始终提供手动重试入口,不按 `canRetry` 隐藏;列表点击重试即进入任务确认框,展示 `retryMessage`,由重试接口判断是否受理;支持 `CLEANING` 清理阶段,409 后刷新状态,网络异常时先查询确认结果
BIN
View File
Binary file not shown.
@@ -0,0 +1,54 @@
# 项目发布时间编辑与排序对接说明
依据:用户提供的 `admin-api(8).md` 第 2.2、5.3、5.4、5.5 节。更新日期:2026-11-02。
本说明替代此前关于手动修改 `updatedAt` 及 `sortBy` / `sortDirection` 的拟定需求。按当前接口文档,后端已提供发布时间编辑和排序能力,本功能无需再新增接口或字段;真实部署环境仍需联调确认。
## 编辑字段:publishedAt
使用既有 `PATCH /admin-api/projects/{projectCode}`,平铺提交当前完整基础信息及可选 `publishedAt`:
```json
{
"name": "microduck",
"description": "A Tiny biped duck robot",
"projectType": "GENERAL",
"coverUrl": "",
"publishedAt": "2026-11-02T10:30:00.000"
}
```
- `publishedAt` 是现有发布时间字段新增了后台编辑能力,并非新的 `updatedAt` 替代字段。
- 不修改日期时省略该字段,由后端保留原值;修改时传上海时间字符串;清空时显式提交 `"publishedAt": null`。未设置时间的项目可以留空。
- 仅指定发布时间,不提交 `updatedAt`,系统更新时间仍由后端维护;不改变发布状态或已发布 Commit。
- 发布时只有 `publishedAt` 为空才自动填入当前上海时间;已有的手工时间会保留。清空后下次发布会重新填充。
- 响应仍为 `ProjectView`。前端核对返回的 `publishedAt` 是否与修改/清空一致,异常时保留表单并提示确认结果。
## 时间约定
- `createdAt`、`updatedAt`、`publishedAt` 等无时区后缀的服务端日期按 `Asia/Shanghai`(UTC+8)解析,不能补 `Z`。
- 带 `Z` 或明确偏移的时间直接解析,以兼容 STEP 签名等接口。
- 界面转换到浏览器本地时区显示;编辑提交则转换为上海时间、保留毫秒且不带时区后缀,不依赖浏览器默认时区。
- 例如上海本地 `2026-10-28 12:34:56` 提交为 `2026-10-28T12:34:56.000`;纽约冬季本地 `2026-01-01 23:45:00` 提交为 `2026-01-02T12:45:00.000`。
## 列表排序:sort
项目管理列表仅按发布时间倒序,始终向 `GET /admin-api/projects` 显式发送 `sort=PUBLISHED_AT_DESC`。空值排最后,同值时的固定顺序由服务端负责,并在分页之前完成。前端直接展示响应,不额外对当前页排序。
接口文档仍列出 `CREATED_AT_DESC`(服务端默认)和 `RESOURCES_FIRST`,但管理页面不再提供这两种排序。首次加载、查询、重置和翻页都显式指定发布时间排序,避免省略参数后回退到创建时间排序。现有后端已支持所需枚举,无需修改接口。
```text
GET /admin-api/projects?page=1&size=20&sort=PUBLISHED_AT_DESC
GET /admin-api/projects?page=2&size=20&ownerUserCode=owner-1&keyword=robot&sort=PUBLISHED_AT_DESC
```
- 只发送 `PUBLISHED_AT_DESC`,不发送 `sortBy`、`sortDirection`,不提供升序。
- 项目表格显示「创建时间」「发布时间」;创建时间仅展示,发布时间表头标记倒序,移除多模式「排序方式」选择器。
- 点击发布时间表头回第一页并保留已提交筛选;查询、翻页和页大小切换保留发布时间倒序;重置清空筛选并回到第一页,仍按发布时间倒序。
- 用户详情「名下项目」复用表格展示发布时间,但原有用户项目接口本次不增加排序参数或入口。
## 验证与联调
前端回归:`npx playwright test tests/project-dates.spec.ts`。覆盖上海时间、带时区值、毫秒原值保留、其他浏览器时区跨日转换、空值/清空、保存失败、取消编辑、响应核对、排序枚举及筛选分页联动。
这些测试拦截全部管理 API,不代表已验证真实后端。联调时应确认:修改时间在刷新后持久保留;清空后返回 null;排序与空值规则在多页数据上成立;再次发布保留已有手工时间。
+185
View File
@@ -0,0 +1,185 @@
# STEP 文件管理:接口对接说明
更新日期:2026-11-02。对应前端 `vibemake-admin`、后端 `community-adminapi`。
本文依据后端交付的 `admin-api(8).md` 第 8.4 节整理,替代本文件之前的待实现需求。批次持久化、严格幂等、过期拒绝和绑定冲突检测不属于本期后端能力,前端不再依赖这些假设。接口以交付的后端文档为准。
## 1. 功能范围
- 项目详情中,在 URDF 右侧提供 STEP tab,沿用现有后台组件和布局。
- 一个项目绑定一个 `.step` / `.stp` 文件,支持上传、替换、移除绑定和直接下载。
- 单文件范围为 **1–524288000 字节,包含两端(500 MiB)**;文件本体直传 OSS。
- STEP 与 URDF、Git 独立,不创建 Git 提交、不改变发布状态;Git 历史浏览不切换 STEP。
- 管理操作仅面向已 READY 且未删除的项目,沿用既有管理员鉴权。
- 替换、移除绑定、删除项目均不物理删除 OSS 对象,旧链接仍然可访问。Fork 继承资源引用,之后可分别修改。
不新增 STEP 列表、下载或预览接口。
## 2. 项目字段和响应层级
```ts
interface StepProjectFields {
stepMainUrl: string | null; // 当前公开资源地址,也用于直接下载
stepFileName: string | null; // 原始文件名,保留中文、空格及大小写
stepSizeBytes: number | null;
}
```
未绑定时三个字段为 `null`。前端也兼容旧项目响应暂未包含这些字段的情况。
所有管理 API 使用既有响应包装:
```json
{
"code": "OK",
"message": "成功",
"data": {},
"requestId": null
}
```
- 项目详情 `GET /admin-api/projects/{projectCode}`:项目对象仍在 `data.project`。
- STEP 确认成功:`data` **直接为完整 `ProjectView`**,不包裹 `project`。
- STEP 移除成功:`data` 为 `null`。
签名、确认、移除请求使用现有管理端 Bearer Token;OSS 上传和公开资源下载均不携带管理端 Token。
## 3. 上传签名
```http
POST /admin-api/projects/{projectCode}/step/signature
Content-Type: application/json
Authorization: Bearer <admin-token>
```
请求:
```json
{
"files": [
{ "relativePath": "机械臂 装配.STEP", "sizeBytes": 10485760 }
]
}
```
文件规则:
- `files` 只允许一个元素;扩展名大小写不敏感。
- `relativePath` 是单个原始文件名,最多 1024 字符,不接受目录、反斜杠、冒号和控制字符。
- `sizeBytes` 为正整数字节数,最大 524288000。
- 不根据浏览器 MIME 推断或拒绝 STEP 文件。
返回 `data`:
```ts
interface StepUploadSignature {
batchCode: string;
mainRelativePath: string;
uploadUrl: string;
expiresAt: string; // 带时区的 ISO 时间,例如 2026-11-02T08:15:00Z
files: [{
relativePath: string;
objectKey: string;
formFields: Record<string, string>;
}];
}
```
签名有效期为 15 分钟,签名响应禁止缓存。`relativePath`、`mainRelativePath` 保留原始名称;实际 OSS 对象名称是 `model{原始后缀}`,例如 `model.STEP`。对象路径和表单字段由服务端生成,前端不自行拼接或改写。
## 4. OSS 直传
1. 前端核验签名中的文件数量和原始名称与当前选择一致。
2. 将 `formFields` **全部按原值**追加到 `FormData`,包含 Content-Disposition 等字段。
3. 最后追加 `file` 字段,内容为所选原文件。
4. 向 `uploadUrl` 发起 multipart POST,不添加管理端 Authorization,也不手写 Content-Type / boundary。
5. OSS 成功后进入确认阶段;签名或上传本身不会修改当前绑定。
原始文件名通过 `stepFileName` 和签名中的 Content-Disposition 保留,不从资源 URL 末尾的 `model.step` 猜测原名。OSS Policy 精确限制对象和大小,并禁止覆盖对象。
## 5. 确认绑定与失败重试
```http
PUT /admin-api/projects/{projectCode}/step
Content-Type: application/json
Authorization: Bearer <admin-token>
```
请求使用签名返回的 `batchCode` 和原始文件清单:
```json
{
"batchCode": "<signature.batchCode>",
"files": [
{ "relativePath": "机械臂 装配.STEP", "sizeBytes": 10485760 }
]
}
```
返回 `data` 为完整 `ProjectView`。前端核验项目编号和 STEP 三个字段后展示成功,并刷新项目详情。
本期后端语义:
- 不保存上传批次,不比较历史签名清单;仅核验该项目 STEP 目录下对象存在及大小。
- 每次 PUT 都重新核验并写入,**没有严格幂等或绑定冲突检测**。
- 上传签名过期后,已经上传的对象仍可确认。
- 并发以最后一次成功写入为准;旧请求可在替换或移除后重新绑定旧对象。
前端处理:
- 签名/上传失败时保留所选文件,允许重新签名上传,不提前修改当前绑定。
- OSS 成功后,若确认遭遇网络异常、OSS 故障或无效响应,保留原请求,仅手动重试 PUT,不重复上传。
- 异常后刷新项目状态,不把失败响应视为服务端一定未写入,也不自动重试。
- 点击“重试绑定”先提示重新写入可能覆盖其他操作;确认后才发送请求,取消不发送。
- 对象缺失或大小不匹配时丢弃待确认请求,要求重新上传。
- 重新选文件、清除选择、离开项目后不继续重试旧请求;移除操作也会放弃本地待确认请求。
## 6. 移除绑定
```http
DELETE /admin-api/projects/{projectCode}/step
Authorization: Bearer <admin-token>
```
无请求体,成功返回 `data: null`。界面二次确认后调用,仅清空 STEP 绑定,不删除已上传对象,不修改 URDF。成功后更新展示并刷新项目;失败提示刷新核对当前状态。
## 7. 直接下载 STEP
当前项目存在 `stepMainUrl` 时,显示“下载 STEP”,与“移除绑定”并排。
- 直接通过浏览器原生链接访问 `stepMainUrl`,**不调用管理端下载接口**。
- 使用 `stepFileName` 设置 `download` 属性;跨域下载的附件行为及原始文件名以 OSS 返回的 Content-Disposition 为准。
- 保留新窗口打开方式,避免遗留对象缺少附件响应头时离开管理页面。
- 不携带管理端 Authorization,不先 fetch / Blob,不将最高 500 MiB 的文件整体读入前端内存。
- 下载不需要资源服务器允许 JavaScript 跨域读取;上传仍需 OSS 正确配置跨域上传。
- 替换成功后按钮使用新的资源地址;移除绑定后隐藏下载按钮。历史链接仍可访问是后端既定语义。
## 8. 实际错误码
| HTTP | code | 前端处理 |
| --- | --- | --- |
| 400 | `STEP_INVALID_FILE` | 展示后端错误及 requestId |
| 413 | `STEP_FILE_TOO_LARGE` | 展示限额错误,前端选择时也校验 500 MiB |
| 409 | `STEP_FILE_MISSING` | 已上传对象不可用,重新签名上传 |
| 409 | `STEP_FILE_SIZE_MISMATCH` | 已上传对象不可用,重新签名上传 |
| 5xx | `OSS_ERROR` / `OSS_UNAVAILABLE` | 若已上传则保留请求,允许手动重试确认 |
| 401 | 既有鉴权错误 | 沿用管理端登出及登录跳转 |
其余权限、项目状态、存储和网络异常沿用现有请求层。前端不依赖 `STEP_BATCH_EXPIRED`、`STEP_BATCH_MISMATCH`、`STEP_BINDING_CHANGED` 等旧需求中的批次状态错误。
## 9. 对应代码与验证
- `src/api/index.ts`:`uploadStep`、`confirmStep`、`removeStep`。
- `src/api/request.ts`:复用既有 `requestAdmin` 和 `uploadOssFile`。
- `src/api/types.ts`:STEP 签名、确认请求、项目资源字段类型。
- `src/components/project/StepPanel.tsx`:阶段反馈、重试确认、移除和直接下载。
- `src/components/project/StepFilePicker.tsx`、`stepFiles.ts`:单文件选择与限制。
- `tests/step.spec.ts`:接口包装/方法/鉴权、multipart 字段顺序、OSS 对象名与原始名、失败重试、签名过期后确认、移除、跨域原生下载及中文文件名。
```bash
npx playwright test tests/step.spec.ts
npm run build
npx playwright test
```
自动化测试拦截管理 API 和 OSS,不对真实环境执行上传、绑定或删除;它验证前端行为与文档契约,不能代替真实环境的接口/OSS 联调。
+50 -2
View File
@@ -15,10 +15,13 @@ import type {
ManagedProjectView,
PageResponse,
ProjectInput,
ProjectUpdateInput,
ProjectView,
PublishStatus,
RepoStatus,
SelectedFile,
StepUploadBatch,
StepUploadSignature,
TaskView,
TreeView,
TypeView,
@@ -71,6 +74,8 @@ export const listUserProjects = (userCode: string, page = 1, size = 20) =>
);
// ---------- 项目 ----------
export type ProjectSort = 'PUBLISHED_AT_DESC';
export interface ProjectQuery {
page?: number;
size?: number;
@@ -80,6 +85,7 @@ export interface ProjectQuery {
publishStatus?: PublishStatus;
repoStatus?: RepoStatus;
moderationStatus?: 'NORMAL' | 'BLOCKED';
sort?: ProjectSort;
}
// 项目类型基本不变,整个会话只请求一次;失败时清掉缓存以便下次重试
@@ -92,7 +98,8 @@ export const listProjectTypes = () => {
return typesCache;
};
export const listProjects = (q: ProjectQuery = {}) =>
requestAdmin<PageResponse<ManagedProjectView>>(`/projects${queryString({ ...q })}`);
// 显式传排序,避免省略时回退到服务端默认的创建时间倒序。
requestAdmin<PageResponse<ManagedProjectView>>(`/projects${queryString({ ...q, sort: q.sort ?? 'PUBLISHED_AT_DESC' })}`);
export const getProject = (code: string) =>
requestAdmin<ManagedProjectView>(`/projects/${enc(code)}`);
export const createProject = (project: ProjectInput, ownerUserCode?: string) =>
@@ -100,7 +107,7 @@ export const createProject = (project: ProjectInput, ownerUserCode?: string) =>
method: 'POST',
body: ownerUserCode ? { project, ownerUserCode } : { project },
});
export const updateProject = (code: string, project: ProjectInput) =>
export const updateProject = (code: string, project: ProjectUpdateInput) =>
requestAdmin<ProjectView>(`/projects/${enc(code)}`, { method: 'PATCH', body: project });
export const deleteProject = (code: string) =>
requestAdmin<null>(`/projects/${enc(code)}`, { method: 'DELETE' });
@@ -232,6 +239,47 @@ export async function uploadImportUrdf(
export const removeUrdf = (code: string) =>
requestAdmin<null>(`/projects/${enc(code)}/urdf`, { method: 'DELETE' });
// ---------- STEP ----------
/** 签名 → OSS 直传;返回待确认批次,此时尚未修改项目绑定。 */
export async function uploadStep(
code: string,
file: File,
onStage?: (stage: 'signing' | 'uploading') => void,
): Promise<StepUploadBatch> {
const files: StepUploadBatch['files'] = [{ relativePath: file.name, sizeBytes: file.size }];
onStage?.('signing');
const signature = await requestAdmin<StepUploadSignature>(`/projects/${enc(code)}/step/signature`, {
method: 'POST',
body: { files },
});
const signedFile = signature.files?.[0];
if (!signature.batchCode || !signature.uploadUrl || signature.files?.length !== 1
|| signature.mainRelativePath !== file.name || signedFile?.relativePath !== file.name
|| !signedFile.formFields) {
throw new Error('STEP 上传签名与所选文件不匹配,请重新上传');
}
onStage?.('uploading');
await uploadOssFile(signature.uploadUrl, signedFile.formFields, file);
return { batchCode: signature.batchCode, files };
}
/** 确认已上传对象;手动重试复用原请求,每次都会重新核验并写入绑定。 */
export async function confirmStep(code: string, batch: StepUploadBatch): Promise<ProjectView> {
const project = await requestAdmin<ProjectView>(`/projects/${enc(code)}/step`, {
method: 'PUT',
body: batch,
});
const file = batch.files[0];
if (project?.projectCode !== code || !project.stepMainUrl
|| project.stepFileName !== file.relativePath || project.stepSizeBytes !== file.sizeBytes) {
throw new Error('服务端未返回有效的 STEP 绑定信息,请重试绑定或刷新确认结果');
}
return project;
}
export const removeStep = (code: string) =>
requestAdmin<null>(`/projects/${enc(code)}/step`, { method: 'DELETE' });
// ---------- GitHub 迁移 ----------
export const previewImport = (repositoryUrl: string) =>
requestAdmin<ImportPreview>('/project-imports/preview', {
+39 -10
View File
@@ -1,4 +1,5 @@
export type UtcDateTime = string;
/** 无时区后缀时为 Asia/Shanghai;兼容部分接口返回带 Z/偏移的 ISO 时间。 */
export type ShanghaiDateTime = string;
export interface ApiResponse<T> {
code: string;
@@ -38,7 +39,7 @@ export interface UserView {
status: UserStatus;
role: UserRole;
projectCount: number;
createdAt: UtcDateTime;
createdAt: ShanghaiDateTime;
}
export type RepoStatus = 'CREATING' | 'READY' | 'FAILED';
@@ -51,6 +52,11 @@ export interface ProjectInput {
coverUrl?: string | null;
}
/** 仅管理端可编辑发布时间:省略保留,null 清空,字符串按上海时间保存。 */
export interface ProjectUpdateInput extends ProjectInput {
publishedAt?: ShanghaiDateTime | null;
}
export interface ProjectView {
projectCode: string;
name: string;
@@ -58,12 +64,16 @@ export interface ProjectView {
coverUrl: string | null;
urdfMainUrl: string | null;
urdfBaseUrl: string | null;
/** 可选以兼容后端分批上线;新接口应显式返回值或 null。 */
stepMainUrl?: string | null;
stepFileName?: string | null;
stepSizeBytes?: number | null;
projectType: string;
owner: { userCode: string | null; nickname: string };
repoStatus: RepoStatus;
publishStatus: PublishStatus;
publishedCommitSha: string | null;
publishedAt: UtcDateTime | null;
publishedAt: ShanghaiDateTime | null;
sourceProjectCode: string | null;
sourceCommitSha: string | null;
likeCount: number;
@@ -71,8 +81,8 @@ export interface ProjectView {
liked: boolean;
sourceRepositoryUrl: string | null;
sourceLicense: string | null;
createdAt: UtcDateTime;
updatedAt: UtcDateTime;
createdAt: ShanghaiDateTime;
updatedAt: ShanghaiDateTime;
}
export interface ManagedProjectView {
@@ -146,7 +156,7 @@ export interface CoverUploadSignature {
uploadUrl: string;
objectKey: string;
coverUrl: string;
expiresAt: UtcDateTime;
expiresAt: ShanghaiDateTime;
formFields: Record<string, string>;
}
@@ -165,10 +175,29 @@ export interface UrdfUploadSignature {
batchCode: string;
mainRelativePath: string;
uploadUrl: string;
expiresAt: UtcDateTime;
expiresAt: ShanghaiDateTime;
files: UrdfFileSignature[];
}
export interface StepFile {
relativePath: string;
sizeBytes: number;
}
export interface StepUploadSignature {
batchCode: string;
mainRelativePath: string;
uploadUrl: string;
expiresAt: ShanghaiDateTime;
files: [{ relativePath: string; objectKey: string; formFields: Record<string, string> }];
}
/** 前端内存中保留的已上传请求;确认异常时手动重试 PUT,后端不保存批次状态。 */
export interface StepUploadBatch {
batchCode: string;
files: [StepFile];
}
export interface ImportPreview {
repositoryUrl: string;
defaultBranch: string;
@@ -210,7 +239,7 @@ export interface TaskView {
canRetry: boolean;
retryMessage: string | null;
warnings: string[];
createdAt: UtcDateTime;
startedAt: UtcDateTime | null;
finishedAt: UtcDateTime | null;
createdAt: ShanghaiDateTime;
startedAt: ShanghaiDateTime | null;
finishedAt: ShanghaiDateTime | null;
}
+30 -5
View File
@@ -1,7 +1,8 @@
import { Image, Table, Tooltip, Typography } from 'antd';
import type { TablePaginationConfig } from 'antd';
import { Image, Table, Tag, Tooltip, Typography } from 'antd';
import type { TablePaginationConfig, TableProps } from 'antd';
import { Link } from 'react-router-dom';
import type { ManagedProjectView, TypeView } from '@/api/types';
import type { ProjectSort } from '@/api';
import StatusTag from './StatusTag';
import { formatTime, shortSha } from '@/utils/format';
import { publishStatusLabel, repoStatusLabel } from '@/utils/labels';
@@ -27,21 +28,31 @@ export default function ProjectTable({
pagination,
types = [],
hideOwner,
sort,
onSortChange,
}: {
items: ManagedProjectView[];
loading?: boolean;
pagination: TablePaginationConfig;
types?: TypeView[];
hideOwner?: boolean;
sort?: ProjectSort;
onSortChange?: (sort: ProjectSort) => void;
}) {
const typeName = (code: string) => types.find((t) => t.code === code)?.name ?? code;
const onChange: TableProps<ManagedProjectView>['onChange'] = (_, __, sorter, extra) => {
if (extra.action !== 'sort' || !onSortChange) return;
const current = Array.isArray(sorter) ? sorter[0] : sorter;
if (current?.columnKey === 'publishedAt') onSortChange('PUBLISHED_AT_DESC');
};
return (
<Table<ManagedProjectView>
rowKey={(r) => r.project.projectCode}
loading={loading}
dataSource={items}
pagination={pagination}
scroll={{ x: 1250 }}
scroll={{ x: 1420 }}
onChange={onChange}
columns={[
{
title: '项目',
@@ -82,8 +93,22 @@ export default function ProjectTable({
),
},
{ title: '发布版本', width: 120, render: (_, r) => <span className="mono">{shortSha(r.project.publishedCommitSha)}</span> },
{ title: '点赞 / 评论', width: 110, render: (_, r) => `${r.project.likeCount} / ${r.project.commentCount}` },
{ title: '创建时间', width: 170, render: (_, r) => <span className="nowrap">{formatTime(r.project.createdAt)}</span> },
{
title: '是否有 STEP',
width: 110,
render: (_, r) => <Tag color={r.project.stepMainUrl ? 'green' : 'default'}>{r.project.stepMainUrl ? '有' : '无'}</Tag>,
},
{ title: '创建时间', key: 'createdAt', width: 180, render: (_, r) => <span className="nowrap">{formatTime(r.project.createdAt)}</span> },
{
title: '发布时间',
key: 'publishedAt',
sorter: !!onSortChange,
sortOrder: onSortChange && sort === 'PUBLISHED_AT_DESC' ? 'descend' : null,
// 仅支持发布时间倒序;不切换到升序或无序状态。
sortDirections: ['descend', 'descend'],
width: 180,
render: (_, r) => <span className="nowrap">{formatTime(r.project.publishedAt)}</span>,
},
{ title: '操作', fixed: 'right', width: 80, render: (_, r) => <Link to={`/projects/${r.project.projectCode}`}>管理</Link> },
]}
/>
+34 -6
View File
@@ -1,9 +1,12 @@
import { useEffect, useState } from 'react';
import { App, Form, Modal } from 'antd';
import { App, DatePicker, Form, Modal } from 'antd';
import dayjs, { type Dayjs } from 'dayjs';
import * as api from '@/api';
import type { ProjectView, TypeView } from '@/api/types';
import type { ProjectInput, ProjectView, TypeView } from '@/api/types';
import ProjectFields from '@/components/ProjectFields';
import { errorText } from '@/utils/format';
import { errorText, parseServerTime, toShanghaiDateTime } from '@/utils/format';
type EditProjectValues = ProjectInput & { publishedAt: Dayjs | null };
export default function EditProjectModal({
project,
@@ -18,7 +21,7 @@ export default function EditProjectModal({
onClose: () => void;
onSaved: () => void;
}) {
const [form] = Form.useForm();
const [form] = Form.useForm<EditProjectValues>();
const { message } = App.useApp();
const [loading, setLoading] = useState(false);
@@ -29,21 +32,32 @@ export default function EditProjectModal({
description: project.description,
projectType: project.projectType,
coverUrl: project.coverUrl ?? '',
publishedAt: project.publishedAt ? dayjs(parseServerTime(project.publishedAt)) : null,
});
}
}, [open, project, form]);
const onOk = async () => {
const v = await form.validateFields();
const v = await form.validateFields().catch(() => null);
if (!v) return;
const dateChanged = (v.publishedAt?.valueOf() ?? null)
!== (project.publishedAt ? parseServerTime(project.publishedAt).getTime() : null);
const publishedAt = v.publishedAt ? toShanghaiDateTime(v.publishedAt.toDate()) : null;
setLoading(true);
try {
// PATCH 仍需提交完整基础信息;coverUrl 传 "" 表示清空
await api.updateProject(project.projectCode, {
const saved = await api.updateProject(project.projectCode, {
name: v.name.trim(),
description: v.description ?? '',
projectType: v.projectType,
coverUrl: v.coverUrl ?? '',
...(dateChanged ? { publishedAt } : {}),
});
if (dateChanged && !(publishedAt === null
? saved?.publishedAt === null
: saved?.publishedAt && parseServerTime(saved.publishedAt).getTime() === parseServerTime(publishedAt).getTime())) {
throw new Error('服务端未保存所选发布时间,请刷新确认结果后重试');
}
message.success('已保存');
onSaved();
} catch (e) {
@@ -57,6 +71,20 @@ export default function EditProjectModal({
<Modal title="编辑项目信息" open={open} onCancel={onClose} onOk={onOk} confirmLoading={loading} width={720} destroyOnClose>
<Form form={form} layout="vertical">
<ProjectFields types={types} />
<Form.Item
name="publishedAt"
label="发布时间"
extra={<>
<div>用于列表排序,不影响发布状态或版本;清空后下次发布自动填写。</div>
<div>按本地时区显示,按上海时间保存。</div>
</>}
rules={[
{ validator: (_, value: Dayjs | null) => !value || value.isValid()
? Promise.resolve() : Promise.reject(new Error('请输入有效的发布时间')) },
]}
>
<DatePicker showTime format="YYYY-MM-DD HH:mm:ss" placeholder="请选择发布时间(可留空)" style={{ width: '100%', maxWidth: 320 }} />
</Form.Item>
</Form>
</Modal>
);
+47
View File
@@ -0,0 +1,47 @@
import { Alert, Button, Space, Typography } from 'antd';
import { CloseOutlined, FileOutlined } from '@ant-design/icons';
import { formatSize } from '@/utils/format';
import { pickFiles } from './pickFiles';
import { checkStepFile } from './stepFiles';
export default function StepFilePicker({
value,
onChange,
disabled,
}: {
value: File | null;
onChange: (file: File | null) => void;
disabled?: boolean;
}) {
const choose = async () => {
const files = await pickFiles({ multiple: false, accept: '.step,.stp' });
if (files.length) onChange(files[0]);
};
return (
<Space direction="vertical" style={{ width: '100%' }}>
<Space wrap>
<Button icon={<FileOutlined aria-hidden="true" />} onClick={choose} disabled={disabled}>
{value ? '重新选择文件' : '选择 STEP 文件'}
</Button>
{value && (
<Button type="text" icon={<CloseOutlined aria-hidden="true" />} onClick={() => onChange(null)} disabled={disabled}>清除</Button>
)}
</Space>
<Typography.Text type="secondary">
支持 .step、.stp,扩展名大小写不敏感;每次选择一个文件,文件大小不超过 500 MiB。
</Typography.Text>
{value && (
<>
<div className="file-list">
<div className="file-list-row">
<span className="file-list-main" style={{ minWidth: 0, overflowWrap: 'anywhere' }}>{value.name}</span>
<span className="file-list-size">{formatSize(value.size)}</span>
</div>
</div>
{checkStepFile(value).map((problem) => <Alert key={problem} type="error" showIcon message={problem} />)}
</>
)}
</Space>
);
}
+176
View File
@@ -0,0 +1,176 @@
import { useEffect, useRef, useState } from 'react';
import { Alert, App, Button, Descriptions, Popconfirm, Space, Spin, Typography } from 'antd';
import { DeleteOutlined, DownloadOutlined } from '@ant-design/icons';
import * as api from '@/api';
import { AdminApiError } from '@/api/request';
import type { ProjectView, StepUploadBatch } from '@/api/types';
import { errorText, formatSize } from '@/utils/format';
import StepFilePicker from './StepFilePicker';
import { checkStepFile } from './stepFiles';
type Stage = 'idle' | 'signing' | 'uploading' | 'binding' | 'removing';
// 后端只核验对象存在及大小;这两种错误需要重新上传文件。
const RESET_BATCH_CODES = new Set([
'STEP_FILE_MISSING', 'STEP_FILE_SIZE_MISMATCH',
]);
export default function StepPanel({ project, onChanged }: {
project: ProjectView;
onChanged: (project?: ProjectView) => void;
}) {
const { message } = App.useApp();
const [file, setFile] = useState<File | null>(null);
const [batch, setBatch] = useState<StepUploadBatch | null>(null);
const [stage, setStage] = useState<Stage>('idle');
const [error, setError] = useState('');
const locked = useRef(false);
const mounted = useRef(true);
const busy = stage !== 'idle';
useEffect(() => {
mounted.current = true;
return () => { mounted.current = false; };
}, []);
const selectFile = (next: File | null) => {
if (locked.current || !mounted.current) return;
setFile(next);
setBatch(null);
setError('');
};
const upload = async () => {
if (locked.current || !file || checkStepFile(file).length) return;
locked.current = true;
setError('');
let pending = batch;
try {
if (!pending) {
pending = await api.uploadStep(project.projectCode, file, (next) => {
if (mounted.current) setStage(next);
});
if (!mounted.current) return;
setBatch(pending);
}
setStage('binding');
const updated = await api.confirmStep(project.projectCode, pending);
if (!mounted.current) return;
setFile(null);
setBatch(null);
message.success('STEP 已绑定');
onChanged(updated);
} catch (e) {
if (!mounted.current) return;
if (e instanceof AdminApiError && RESET_BATCH_CODES.has(e.code)) {
setBatch(null);
setError(`${errorText(e)}。已上传文件不可用,请重新上传。`);
} else if (pending) {
setError(`${errorText(e)}。绑定结果尚未确认,请先刷新查看当前状态;重试绑定会重新写入本次上传的文件。`);
} else {
setError(`${errorText(e)}。可保留所选文件重新上传。`);
}
if (pending) onChanged();
} finally {
locked.current = false;
if (mounted.current) setStage('idle');
}
};
const remove = async () => {
if (locked.current) return;
locked.current = true;
setStage('removing');
setError('');
// 放弃待确认的旧批次,移除后不能再从界面重试它。
setBatch(null);
try {
await api.removeStep(project.projectCode);
if (!mounted.current) return;
message.success('已移除 STEP 绑定');
onChanged({ ...project, stepMainUrl: null, stepFileName: null, stepSizeBytes: null });
} catch (e) {
if (!mounted.current) return;
setError(`${errorText(e)}。请刷新确认当前绑定状态后再操作。`);
onChanged();
} finally {
locked.current = false;
if (mounted.current) setStage('idle');
}
};
const stageText = stage === 'signing' ? '正在获取 STEP 上传签名'
: stage === 'uploading' ? '正在上传 STEP 文件'
: stage === 'binding' ? '文件已上传,正在确认 STEP 绑定'
: '正在移除 STEP 绑定';
return (
<Space direction="vertical" style={{ width: '100%' }} size="large">
<Descriptions column={1} bordered size="small">
<Descriptions.Item label="STEP 主文件">
{project.stepMainUrl ? (
<a href={project.stepMainUrl} target="_blank" rel="noreferrer" style={{ overflowWrap: 'anywhere' }}>
{project.stepFileName || project.stepMainUrl}
</a>
) : '未绑定'}
</Descriptions.Item>
<Descriptions.Item label="文件大小">
{project.stepMainUrl ? formatSize(project.stepSizeBytes) : '—'}
</Descriptions.Item>
</Descriptions>
<Alert
type="info"
showIcon
message="STEP 为独立文件上传,不产生 Git 提交;绑定或清除后直接更新项目展示资源。重新上传会替换当前绑定。"
/>
{project.stepMainUrl && (
<Space wrap>
{/* 直接交给浏览器下载,避免将 500 MiB 文件读入内存;跨域文件名由 OSS Content-Disposition 提供。 */}
<Button
icon={<DownloadOutlined aria-hidden="true" />}
href={project.stepMainUrl}
download={project.stepFileName || undefined}
target="_blank"
rel="noopener noreferrer"
>下载 STEP</Button>
<Popconfirm
title="确定移除 STEP 绑定?(不会删除已上传对象)"
disabled={busy}
onConfirm={remove}
>
<Button danger icon={<DeleteOutlined aria-hidden="true" />} loading={stage === 'removing'} disabled={busy}>移除绑定</Button>
</Popconfirm>
</Space>
)}
<StepFilePicker value={file} onChange={selectFile} disabled={busy} />
{busy && (
<Space role="status" aria-live="polite">
<Spin size="small" />
<Typography.Text>{stageText}</Typography.Text>
</Space>
)}
{error && (
<Alert
type="error"
showIcon
message={error}
action={<Button size="small" onClick={() => onChanged()} disabled={busy}>刷新状态</Button>}
/>
)}
{file && (
<Popconfirm
title="确定重试 STEP 绑定?"
description="重试将使用本次上传文件重新设置 STEP 绑定,可能覆盖其他操作的结果。"
disabled={!batch || busy}
onConfirm={upload}
okText="确认重试"
cancelText="取消"
>
<Button type="primary" loading={busy} disabled={busy || checkStepFile(file).length > 0} onClick={batch ? undefined : upload}>
{batch ? '重试绑定' : '上传并绑定'}
</Button>
</Popconfirm>
)}
</Space>
);
}
+15
View File
@@ -0,0 +1,15 @@
import { validatePath } from './pickFiles';
export const MAX_STEP_FILE_SIZE = 500 * 1024 * 1024;
/** STEP 单文件校验;空选择不报错,由面板隐藏提交按钮。 */
export function checkStepFile(file: File | null): string[] {
if (!file) return [];
const pathError = validatePath(file.name);
return [
!/^.+\.(step|stp)$/i.test(file.name) && '仅支持 .step、.stp 文件(扩展名大小写不敏感)',
file.size <= 0 && '不能上传空文件',
file.size > MAX_STEP_FILE_SIZE && '文件大小不能超过 500 MiB',
(file.name.includes('/') || pathError) && `文件名不合法:${pathError || '不支持目录路径'}`,
].filter(Boolean) as string[];
}
+24
View File
@@ -25,6 +25,7 @@ import ImportTaskActions from '@/components/ImportTaskActions';
import FileBrowser from '@/components/project/FileBrowser';
import CommitHistory from '@/components/project/CommitHistory';
import UrdfPanel from '@/components/project/UrdfPanel';
import StepPanel from '@/components/project/StepPanel';
import EditProjectModal from '@/components/project/EditProjectModal';
import { coverGradient } from '@/components/ProjectTable';
import { errorText, formatTime, shortSha } from '@/utils/format';
@@ -186,6 +187,7 @@ export default function ProjectDetailPage() {
</Descriptions.Item>
)}
<Descriptions.Item label="URDF">{p.urdfMainUrl ? '已绑定' : '未绑定'}</Descriptions.Item>
<Descriptions.Item label="STEP">{p.stepMainUrl ? '已绑定' : '未绑定'}</Descriptions.Item>
</Descriptions>
{data.moderationReason && (
<Alert style={{ marginTop: 16 }} type="error" showIcon message={`下架原因:${data.moderationReason}`} />
@@ -235,6 +237,28 @@ export default function ProjectDetailPage() {
),
},
{ key: 'urdf', label: 'URDF', children: <UrdfPanel project={p} onChanged={load} /> },
{
key: 'step',
label: 'STEP',
children: (
<StepPanel
key={p.projectCode}
project={p}
onChanged={(updated) => {
if (updated) setData((current) => current?.project.projectCode === updated.projectCode ? {
...current,
project: {
...current.project,
stepMainUrl: updated.stepMainUrl ?? null,
stepFileName: updated.stepFileName ?? null,
stepSizeBytes: updated.stepSizeBytes ?? null,
},
} : current);
load();
}}
/>
),
},
...(tasks.length ? [{ key: 'imports', label: '迁移任务', children: <ImportTaskTable tasks={tasks} /> }] : []),
]}
/>
+16 -4
View File
@@ -16,7 +16,7 @@ export default function ProjectListPage() {
const [params] = useSearchParams();
const [form] = Form.useForm<Q>();
const [types, setTypes] = useState<TypeView[]>([]);
const initial = clean({ ownerUserCode: params.get('ownerUserCode') ?? undefined });
const initial: Q = clean({ ownerUserCode: params.get('ownerUserCode') ?? undefined, sort: 'PUBLISHED_AT_DESC' });
const list = usePaged<ManagedProjectView, Q>((q) => api.listProjects(q), initial);
useEffect(() => {
@@ -35,7 +35,12 @@ export default function ProjectListPage() {
</Space>
}
>
<Form form={form} layout="inline" onFinish={(v) => list.search(clean(v))} style={{ marginBottom: 16, rowGap: 8 }}>
<Form
form={form}
layout="inline"
onFinish={(v) => list.search(clean({ ...v, sort: list.query.sort }))}
style={{ marginBottom: 16, rowGap: 8 }}
>
<Form.Item name="keyword"><Input placeholder="名称 / 描述" allowClear maxLength={254} /></Form.Item>
<Form.Item name="ownerUserCode"><Input placeholder="所有者编码" allowClear /></Form.Item>
<Form.Item name="type">
@@ -46,10 +51,17 @@ export default function ProjectListPage() {
<Form.Item name="moderationStatus"><Select placeholder="治理状态" allowClear style={{ width: 120 }} options={toOptions(moderationLabel)} /></Form.Item>
<Space>
<Button type="primary" htmlType="submit">查询</Button>
<Button onClick={() => { form.resetFields(); list.search({}); }}>重置</Button>
<Button onClick={() => { form.resetFields(); list.search({ sort: 'PUBLISHED_AT_DESC' }); }}>重置</Button>
</Space>
</Form>
<ProjectTable items={list.data.items} loading={list.loading} pagination={list.pagination} types={types} />
<ProjectTable
items={list.data.items}
loading={list.loading}
pagination={list.pagination}
types={types}
sort={list.query.sort}
onSortChange={(sort) => list.search({ ...list.query, sort })}
/>
</Card>
);
}
+6 -1
View File
@@ -2,7 +2,12 @@ import dayjs from 'dayjs';
import { AdminApiError } from '@/api/request';
export function parseServerTime(value: string): Date {
return new Date(/(?:Z|[+-]\d{2}:?\d{2})$/i.test(value) ? value : `${value}Z`);
return new Date(/(?:Z|[+-]\d{2}:?\d{2})$/i.test(value) ? value : `${value}+08:00`);
}
/** 编辑接口要求无时区后缀的上海时间,转换不依赖浏览器或运行环境时区。 */
export function toShanghaiDateTime(value: Date): string {
return new Date(value.getTime() + 8 * 60 * 60 * 1000).toISOString().slice(0, -1);
}
export function formatTime(value?: string | null): string {
+247
View File
@@ -0,0 +1,247 @@
import { expect, test, type Page, type Route } from '@playwright/test';
import type { ManagedProjectView, ProjectUpdateInput } from '../src/api/types';
test.use({ timezoneId: 'Asia/Shanghai' });
async function ok(route: Route, data: unknown) {
await route.fulfill({ json: { code: 'OK', message: '成功', data, requestId: null } });
}
async function prepare(page: Page, options: { publishedAt?: string | null; ignoreDate?: boolean; failSave?: boolean } = {}) {
const project: ManagedProjectView = {
project: {
projectCode: 'date-test', name: '日期测试项目', description: '项目描述', coverUrl: null,
urdfMainUrl: null, urdfBaseUrl: null, projectType: 'GENERAL',
owner: { userCode: null, nickname: '社区官方' }, repoStatus: 'READY', publishStatus: 'UNPUBLISHED',
publishedCommitSha: null, publishedAt: options.publishedAt === undefined ? '2026-11-01T10:03:04.000' : options.publishedAt,
sourceProjectCode: null, sourceCommitSha: null,
likeCount: 0, commentCount: 0, liked: false, sourceRepositoryUrl: null, sourceLicense: null,
createdAt: '2026-10-27T08:00:00', updatedAt: '2026-11-02T09:00:00',
},
moderationStatus: 'NORMAL', moderationReason: null, deleted: false,
};
const other: ManagedProjectView = {
...project,
project: { ...project.project, projectCode: 'other-date', name: '另一日期项目', publishedAt: '2026-10-30T10:03:04' },
};
const state = { project, updates: [] as ProjectUpdateInput[], lists: [] as Record<string, string>[] };
await page.addInitScript(() => localStorage.setItem('vibemake_admin_token', 'test-token'));
await page.route('https://fonts.googleapis.com/**', (route) => route.abort());
// 所有管理 API 都拦截,不读写真实项目。
await page.route('**/admin-api/**', async (route) => {
const url = new URL(route.request().url());
const path = 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: 'GENERAL', name: '通用' }]);
if (path === '/projects/date-test') {
if (route.request().method() === 'PATCH') {
const input = route.request().postDataJSON() as ProjectUpdateInput;
state.updates.push(input);
expect(input).not.toHaveProperty('updatedAt');
if (options.failSave && state.updates.length === 1) {
return route.fulfill({ status: 400, json: { code: 'INVALID_DATE', message: '发布时间校验失败', data: null } });
}
const { publishedAt, ...base } = input;
Object.assign(project.project, base);
if (publishedAt !== undefined && !options.ignoreDate) project.project.publishedAt = publishedAt;
return ok(route, project.project);
}
return ok(route, project);
}
if (path === '/projects') {
const query = Object.fromEntries(url.searchParams);
expect(query).not.toHaveProperty('sortBy');
expect(query).not.toHaveProperty('sortDirection');
expect(query.sort).toBe('PUBLISHED_AT_DESC');
state.lists.push(query);
// 故意给出不同于客户端时间排序的顺序,验证表格原样展示服务端分页结果。
const items = query.sort === 'PUBLISHED_AT_DESC' ? [other, project] : [project, other];
return ok(route, { items, page: Number(query.page ?? 1), size: Number(query.size ?? 20), total: 42 });
}
if (path.endsWith('/tree')) return ok(route, { commitSha: 'main-sha', path: '', entries: [] });
if (path.endsWith('/commits') || path === '/project-imports') return ok(route, { items: [], page: 1, size: 20, total: 0 });
throw new Error(`未预期的管理请求:${route.request().method()} ${path}`);
});
return state;
}
async function openEditor(page: Page) {
await page.goto('/projects/date-test');
await page.getByRole('button', { name: '编辑信息', exact: true }).click();
const dialog = page.getByRole('dialog', { name: '编辑项目信息' });
await expect(dialog.getByLabel('发布时间', { exact: true })).toBeVisible();
await expect(dialog.getByLabel('更新时间', { exact: true })).toHaveCount(0);
return dialog;
}
async function setDate(page: Page, value: string | null) {
const dialog = page.getByRole('dialog', { name: '编辑项目信息' });
const input = dialog.getByLabel('发布时间', { exact: true });
if (value === null) {
await input.hover();
await dialog.locator('.ant-picker-clear').click();
} else {
await input.fill(value);
await input.press('Enter');
}
}
for (const publishedAt of ['2026-11-01T10:03:04', '2026-11-01T10:03:04.123', '2026-11-01T02:03:04Z', '2026-11-01T10:03:04+08:00']) {
test(`回填发布时间 ${publishedAt},未修改日期时省略字段`, async ({ page }) => {
const state = await prepare(page, { publishedAt });
const dialog = await openEditor(page);
await expect(dialog.getByLabel('发布时间', { exact: true })).toHaveValue('2026-11-01 10:03:04');
await dialog.getByLabel('项目名称', { exact: true }).fill('修改后的项目');
await dialog.getByRole('button', { name: /确\s*定/ }).click();
await expect(dialog).toBeHidden();
expect(state.updates).toEqual([{ name: '修改后的项目', description: '项目描述', projectType: 'GENERAL', coverUrl: '' }]);
});
}
test('修改发布时间提交上海时间,刷新回显,保留发布状态且不提交系统更新时间', async ({ page }, testInfo) => {
const state = await prepare(page);
const dialog = await openEditor(page);
await setDate(page, '2026-10-28 12:34:56');
await dialog.getByText('编辑项目信息', { exact: true }).click();
await dialog.screenshot({ path: testInfo.outputPath('project-edit-published-date.png') });
await dialog.getByRole('button', { name: /确\s*定/ }).click();
await expect(dialog).toBeHidden();
expect(state.updates[0].publishedAt).toBe('2026-10-28T12:34:56.000');
expect(state.project.project.updatedAt).toBe('2026-11-02T09:00:00');
expect(state.project.project.publishStatus).toBe('UNPUBLISHED');
expect(state.project.project.publishedCommitSha).toBeNull();
await expect(page.getByText('2026-10-28 12:34:56', { exact: true })).toBeVisible();
await expect(page.getByText('2026-11-02 09:00:00', { exact: true })).toBeVisible();
await page.getByRole('button', { name: '编辑信息', exact: true }).click();
await expect(dialog.getByLabel('发布时间', { exact: true })).toHaveValue('2026-10-28 12:34:56');
await setDate(page, '2026-10-29 12:34:56');
await dialog.getByRole('button', { name: /取\s*消/ }).click();
expect(state.updates).toHaveLength(1);
await page.getByRole('button', { name: '编辑信息', exact: true }).click();
await expect(dialog.getByLabel('发布时间', { exact: true })).toHaveValue('2026-10-28 12:34:56');
});
test('未设置发布时间可留空保存,不自动填入更新时间或当前时间', async ({ page }) => {
const state = await prepare(page, { publishedAt: null });
const dialog = await openEditor(page);
await expect(dialog.getByLabel('发布时间', { exact: true })).toHaveValue('');
await dialog.getByRole('button', { name: /确\s*定/ }).click();
await expect(dialog).toBeHidden();
expect(state.updates[0]).not.toHaveProperty('publishedAt');
expect(state.project.project.publishedAt).toBeNull();
});
test('首次设置发布时间与清空均支持,清空必须显式提交 null', async ({ page }) => {
const state = await prepare(page, { publishedAt: null });
const dialog = await openEditor(page);
await setDate(page, '2026-10-28 12:34:56');
await dialog.getByRole('button', { name: /确\s*定/ }).click();
await expect(dialog).toBeHidden();
expect(state.updates[0].publishedAt).toBe('2026-10-28T12:34:56.000');
await page.getByRole('button', { name: '编辑信息', exact: true }).click();
await expect(dialog.getByLabel('发布时间', { exact: true })).toHaveValue('2026-10-28 12:34:56');
await setDate(page, null);
await expect(dialog.getByLabel('发布时间', { exact: true })).toHaveValue('');
await dialog.getByRole('button', { name: /确\s*定/ }).click();
await expect(dialog).toBeHidden();
expect(state.updates[1].publishedAt).toBeNull();
expect(state.project.project.publishedAt).toBeNull();
});
for (const value of ['2026-10-28 12:34:56', null]) {
test(`后端忽略发布时间${value === null ? '清空' : '修改'}时保留表单,不误报成功`, async ({ page }) => {
const state = await prepare(page, { ignoreDate: true });
const dialog = await openEditor(page);
await setDate(page, value);
await dialog.getByRole('button', { name: /确\s*定/ }).click();
await expect(page.getByText('服务端未保存所选发布时间,请刷新确认结果后重试')).toBeVisible();
await expect(dialog).toBeVisible();
await expect(page.getByText('已保存', { exact: true })).toHaveCount(0);
expect(state.updates).toHaveLength(1);
});
}
test('保存失败保留发布时间与基础信息,允许重试', async ({ page }) => {
const state = await prepare(page, { failSave: true });
const dialog = await openEditor(page);
await setDate(page, '2026-10-28 12:34:56');
await dialog.getByRole('button', { name: /确\s*定/ }).click();
await expect(page.getByText('发布时间校验失败', { exact: true })).toBeVisible();
await expect(dialog.getByLabel('发布时间', { exact: true })).toHaveValue('2026-10-28 12:34:56');
await dialog.getByRole('button', { name: /确\s*定/ }).click();
await expect(dialog).toBeHidden();
expect(state.updates).toHaveLength(2);
expect(state.updates[1]).toEqual(state.updates[0]);
});
test('发布时间倒序使用 sort 枚举,保留筛选分页,不发送未支持的升序参数', async ({ page }, testInfo) => {
const state = await prepare(page);
await page.goto('/projects');
const header = page.getByRole('columnheader', { name: '发布时间' });
await expect(header).toBeVisible();
await expect(header).toHaveAttribute('aria-sort', 'descending');
await expect.poll(() => state.lists.at(-1)).toEqual({ sort: 'PUBLISHED_AT_DESC', page: '1', size: '20' });
await expect(page.getByRole('columnheader', { name: '更新时间' })).toHaveCount(0);
await page.getByPlaceholder('名称 / 描述').fill('日期');
await page.getByRole('button', { name: /查\s*询/, exact: true }).click();
await expect.poll(() => state.lists.at(-1)?.keyword).toBe('日期');
await page.getByTitle('2', { exact: true }).click();
await expect.poll(() => state.lists.at(-1)?.page).toBe('2');
await header.click();
await expect(header).toHaveAttribute('aria-sort', 'descending');
await expect.poll(() => state.lists.at(-1)).toEqual({ keyword: '日期', sort: 'PUBLISHED_AT_DESC', page: '1', size: '20' });
await expect(page.locator('.ant-table-tbody .pt-name')).toHaveText(['另一日期项目', '日期测试项目']);
await page.screenshot({ path: testInfo.outputPath('project-published-sort.png'), fullPage: true });
await page.getByTitle('2', { exact: true }).click();
await expect.poll(() => state.lists.at(-1)).toMatchObject({ sort: 'PUBLISHED_AT_DESC', page: '2', keyword: '日期' });
await page.getByRole('button', { name: /查\s*询/, exact: true }).click();
await expect.poll(() => state.lists.at(-1)).toMatchObject({ sort: 'PUBLISHED_AT_DESC', page: '1', keyword: '日期' });
await page.getByTitle('20 条/页', { exact: true }).click();
await page.getByRole('option', { name: '50 条/页', exact: true }).click();
await expect.poll(() => state.lists.at(-1)).toMatchObject({ sort: 'PUBLISHED_AT_DESC', page: '1', size: '50', keyword: '日期' });
await header.click();
await expect(header).toHaveAttribute('aria-sort', 'descending');
await expect.poll(() => state.lists.at(-1)).toEqual({ keyword: '日期', sort: 'PUBLISHED_AT_DESC', page: '1', size: '50' });
});
test('仅提供发布时间倒序,创建时间只展示,重置后仍显式请求发布时间排序', async ({ page }) => {
const state = await prepare(page);
await page.goto('/projects?ownerUserCode=owner-1');
const published = page.getByRole('columnheader', { name: '发布时间' });
const created = page.getByRole('columnheader', { name: '创建时间' });
await expect.poll(() => state.lists.at(-1)).toEqual({ ownerUserCode: 'owner-1', sort: 'PUBLISHED_AT_DESC', page: '1', size: '20' });
await expect(published).toHaveAttribute('aria-sort', 'descending');
await expect(created).not.toHaveAttribute('aria-sort');
await expect(created.locator('.ant-table-column-sorters')).toHaveCount(0);
await expect(page.getByRole('combobox', { name: '排序方式' })).toHaveCount(0);
await expect(page.getByText('创建时间倒序', { exact: true })).toHaveCount(0);
await expect(page.getByText('资源齐全优先', { exact: true })).toHaveCount(0);
await expect(page.locator('.ant-table-tbody .nowrap').filter({ hasText: '2026-10-27 08:00:00' })).toHaveCount(2);
const requests = state.lists.length;
await created.click();
expect(state.lists).toHaveLength(requests);
await expect(published).toHaveAttribute('aria-sort', 'descending');
await page.getByTitle('2', { exact: true }).click();
await expect.poll(() => state.lists.at(-1)?.page).toBe('2');
await page.getByRole('button', { name: /重\s*置/, exact: true }).click();
await expect.poll(() => state.lists.at(-1)).toEqual({ sort: 'PUBLISHED_AT_DESC', page: '1', size: '20' });
await expect(page.getByPlaceholder('所有者编码')).toHaveValue('');
await expect(published).toHaveAttribute('aria-sort', 'descending');
await expect(created).not.toHaveAttribute('aria-sort');
await page.getByTitle('2', { exact: true }).click();
await expect.poll(() => state.lists.at(-1)).toEqual({ sort: 'PUBLISHED_AT_DESC', page: '2', size: '20' });
});
test.describe('其他浏览器时区', () => {
test.use({ timezoneId: 'America/New_York' });
test('发布时间按用户本地时间回填,跨日转换后仍提交上海时间且无时区后缀', async ({ page }) => {
const state = await prepare(page, { publishedAt: '2026-01-02T02:30:00.000' });
const dialog = await openEditor(page);
await expect(dialog.getByLabel('发布时间', { exact: true })).toHaveValue('2026-01-01 13:30:00');
await setDate(page, '2026-01-01 23:45:00');
await dialog.getByRole('button', { name: /确\s*定/ }).click();
await expect(dialog).toBeHidden();
expect(state.updates[0].publishedAt).toBe('2026-01-02T12:45:00.000');
await expect(page.getByText('2026-01-01 23:45:00', { exact: true })).toBeVisible();
});
});
+483
View File
@@ -0,0 +1,483 @@
import { expect, test, type Page, type Route } from '@playwright/test';
import { readFile } from 'node:fs/promises';
import type { ManagedProjectView, StepUploadBatch } from '../src/api/types';
import { checkStepFile, MAX_STEP_FILE_SIZE } from '../src/components/project/stepFiles';
const content = Buffer.from('step-test-content');
const oldUrl = 'https://assets.example.com/projects/step-test/step/old/model.step';
function objectKey(batchCode: string, name: string) {
return `projects/step-test/step/${batchCode}/model${name.slice(name.lastIndexOf('.'))}`;
}
function disposition(name: string) {
return `attachment; filename*=UTF-8''${encodeURIComponent(name)}`;
}
interface Options {
bound?: boolean;
legacy?: boolean;
notReady?: boolean;
signatureFailure?: boolean;
invalidSignature?: boolean;
uploadFailure?: boolean;
confirmFailure?: 'server' | 'network' | 'missing' | 'size-mismatch' | 'invalid-response';
signatureExpiresAt?: string;
deleteFailure?: boolean;
signatureGate?: Promise<void>;
uploadGate?: Promise<void>;
confirmGate?: Promise<void>;
}
async function ok(route: Route, data: unknown) {
await route.fulfill({ json: { code: 'OK', message: '成功', data, requestId: null } });
}
async function failure(route: Route, code: string, message: string, status = 409) {
await route.fulfill({ status, json: { code, message, data: null, requestId: 'step-request-id' } });
}
async function prepare(page: Page, options: Options = {}) {
const project: ManagedProjectView = {
project: {
projectCode: 'step-test', name: 'STEP 测试机器人', description: '项目独立模型资源管理', coverUrl: null,
urdfMainUrl: 'https://assets.example.com/robot.urdf', urdfBaseUrl: 'https://assets.example.com/',
stepMainUrl: options.bound ? oldUrl : null,
stepFileName: options.bound ? 'old.step' : null,
stepSizeBytes: options.bound ? 1024 : null,
projectType: 'WHEELED', owner: { userCode: null, nickname: '社区官方' },
repoStatus: options.notReady ? 'CREATING' : 'READY', publishStatus: 'UNPUBLISHED',
publishedCommitSha: null, publishedAt: null, sourceProjectCode: null, sourceCommitSha: null,
likeCount: 0, commentCount: 0, liked: false, sourceRepositoryUrl: null, sourceLicense: null,
createdAt: '2026-11-02T00:00:00Z', updatedAt: '2026-11-02T00:00:00Z',
},
moderationStatus: 'NORMAL', moderationReason: null, deleted: false,
};
if (options.legacy) {
delete project.project.stepMainUrl;
delete project.project.stepFileName;
delete project.project.stepSizeBytes;
}
const state = {
project,
signatures: [] as { files: StepUploadBatch['files'] }[],
uploads: [] as { body: string; headers: Record<string, string> }[],
confirmations: [] as StepUploadBatch[],
deletes: 0,
gets: 0,
requests: [] as { path: string; method: string; headers: Record<string, string>; body: string | null }[],
};
const bind = (body: StepUploadBatch) => {
project.project.stepMainUrl = `https://assets.example.com/${objectKey(body.batchCode, body.files[0].relativePath)}`;
project.project.stepFileName = body.files[0].relativePath;
project.project.stepSizeBytes = body.files[0].sizeBytes;
};
await page.addInitScript(() => localStorage.setItem('vibemake_admin_token', 'test-token'));
await page.route('https://fonts.googleapis.com/**', (route) => route.abort());
await page.route('**/mock-step-oss', async (route) => {
state.uploads.push({ body: route.request().postDataBuffer()?.toString('utf8') ?? '', headers: route.request().headers() });
await options.uploadGate;
if (options.uploadFailure && state.uploads.length === 1) return route.fulfill({ status: 503 });
return route.fulfill({ status: 204 });
});
// 全部管理请求均被拦截;测试不访问真实后端或 OSS。
await page.route('**/admin-api/**', async (route) => {
const path = new URL(route.request().url()).pathname.replace('/admin-api', '');
const method = route.request().method();
state.requests.push({ path, method, headers: route.request().headers(), body: route.request().postData() });
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/step-test' && method === 'GET') {
state.gets++;
return ok(route, project);
}
if (path.endsWith('/tree')) return ok(route, { commitSha: 'main-sha', path: '', entries: [] });
if (path === '/projects' || path === '/project-imports' || path.endsWith('/commits')) {
return ok(route, { items: [], page: 1, size: 20, total: 0 });
}
if (path.endsWith('/step/signature') && method === 'POST') {
const body = route.request().postDataJSON() as { files: StepUploadBatch['files'] };
state.signatures.push(body);
await options.signatureGate;
if (options.signatureFailure && state.signatures.length === 1) {
return failure(route, 'OSS_UNAVAILABLE', '签名服务暂不可用', 503);
}
const name = options.invalidSignature ? 'different.step' : body.files[0].relativePath;
const batchCode = `step-batch-${state.signatures.length}`;
const key = objectKey(batchCode, name);
return ok(route, {
batchCode, mainRelativePath: name,
expiresAt: options.signatureExpiresAt ?? '2099-01-01T00:00:00Z', uploadUrl: 'http://127.0.0.1:5190/mock-step-oss',
files: [{ relativePath: name, objectKey: key, formFields: {
key, policy: 'step-policy', OSSAccessKeyId: 'step-access-key', signature: 'step-signature',
success_action_status: '204', 'Content-Disposition': disposition(name), 'x-oss-forbid-overwrite': 'true',
} }],
});
}
if (path.endsWith('/step') && method === 'PUT') {
const body = route.request().postDataJSON() as StepUploadBatch;
state.confirmations.push(body);
await options.confirmGate;
if (state.confirmations.length === 1 && options.confirmFailure) {
if (options.confirmFailure === 'server') return failure(route, 'OSS_ERROR', '绑定服务暂不可用', 503);
if (options.confirmFailure === 'missing') return failure(route, 'STEP_FILE_MISSING', 'STEP 对象不存在');
if (options.confirmFailure === 'size-mismatch') return failure(route, 'STEP_FILE_SIZE_MISMATCH', 'STEP 对象大小不匹配');
if (options.confirmFailure === 'invalid-response') return ok(route, { projectCode: 'step-test' });
// 模拟服务端已经提交,但成功响应丢失。
bind(body);
return route.abort('failed');
}
bind(body);
return ok(route, project.project);
}
if (path.endsWith('/step') && method === 'DELETE') {
state.deletes++;
if (options.deleteFailure && state.deletes === 1) {
return failure(route, 'OSS_UNAVAILABLE', '移除服务暂不可用', 503);
}
project.project.stepMainUrl = null;
project.project.stepFileName = null;
project.project.stepSizeBytes = null;
return ok(route, null);
}
return failure(route, 'UNEXPECTED_REQUEST', `${method} ${path}`, 404);
});
await page.goto('/projects/step-test');
if (!options.notReady) await page.getByRole('tab', { name: 'STEP', exact: true }).click();
return state;
}
function panel(page: Page) {
return page.getByRole('tabpanel', { name: 'STEP', exact: true });
}
async function chooseFile(page: Page, name = 'robot.step', buffer = content) {
const chooserPromise = page.waitForEvent('filechooser');
await panel(page).getByRole('button', { name: /^(选择 STEP 文件|重新选择文件)$/ }).click();
const chooser = await chooserPromise;
expect(chooser.isMultiple()).toBe(false);
await chooser.setFiles({ name, mimeType: '', buffer });
await expect(panel(page).locator('.file-list-main')).toHaveText(name);
}
function gate() {
let release!: () => void;
const promise = new Promise<void>((resolve) => { release = resolve; });
return { promise, release };
}
test('STEP 紧邻 URDF,兼容尚未返回 STEP 字段的后端', async ({ page }, testInfo) => {
const state = await prepare(page, { legacy: true });
const tabs = await page.getByRole('tab').allTextContents();
expect(tabs.indexOf('STEP')).toBe(tabs.indexOf('URDF') + 1);
await expect(panel(page).getByText('未绑定', { exact: true })).toBeVisible();
await expect(panel(page).getByText(/文件大小不超过 500 MiB/)).toBeVisible();
await expect(panel(page).getByRole('button', { name: '上传并绑定' })).toHaveCount(0);
await expect(panel(page).getByRole('button', { name: '移除绑定' })).toHaveCount(0);
await expect(panel(page).getByRole('link', { name: '下载 STEP' })).toHaveCount(0);
expect(state.signatures).toHaveLength(0);
await page.screenshot({ path: testInfo.outputPath('step-empty.png'), fullPage: true, animations: 'disabled' });
});
test('仓库未就绪时不开放 STEP 入口', async ({ page }) => {
await prepare(page, { notReady: true });
await expect(page.getByText('仓库准备中,暂不开放文件与发布操作')).toBeVisible();
await expect(page.getByRole('tab', { name: 'STEP', exact: true })).toHaveCount(0);
});
test('文件选择可清除,保留已有绑定并沿用当前面板样式', async ({ page }, testInfo) => {
await prepare(page, { bound: true });
await chooseFile(page, '机械臂 装配.STP');
await expect(panel(page).getByRole('link', { name: 'old.step' })).toHaveAttribute('href', oldUrl);
await page.screenshot({ path: testInfo.outputPath('step-selected.png'), fullPage: true, animations: 'disabled' });
await panel(page).getByRole('button', { name: /清\s*除/, exact: true }).click();
await expect(panel(page).locator('.file-list-row')).toHaveCount(0);
await expect(panel(page).getByRole('button', { name: '上传并绑定' })).toHaveCount(0);
await expect(panel(page).getByRole('link', { name: 'old.step' })).toBeVisible();
});
for (const name of ['robot.step', 'robot.stp', '机械臂 装配.STEP', 'Robot.STP']) {
test(`上传 ${name} 使用正确签名和确认契约,不写入 Git`, async ({ page }) => {
const state = await prepare(page, { bound: true });
await chooseFile(page, name);
await panel(page).getByRole('button', { name: '上传并绑定' }).click();
await expect(page.getByText('STEP 已绑定', { exact: true })).toBeVisible();
await expect(panel(page).getByRole('link', { name, exact: true })).toBeVisible();
expect(state.signatures).toEqual([{ files: [{ relativePath: name, sizeBytes: content.length }] }]);
expect(state.confirmations).toEqual([{ batchCode: 'step-batch-1', files: state.signatures[0].files }]);
expect(state.uploads).toHaveLength(1);
for (const value of [objectKey('step-batch-1', name), 'step-policy', 'step-access-key', 'step-signature', '204', disposition(name), 'true']) {
expect(state.uploads[0].body).toContain(value);
}
expect(state.uploads[0].body).toContain(`filename="${name}"`);
expect(state.uploads[0].body.indexOf('name="file"')).toBeGreaterThan(state.uploads[0].body.indexOf('name="x-oss-forbid-overwrite"'));
expect(state.uploads[0].headers.authorization).toBeUndefined();
expect(state.uploads[0].headers['content-type']).toContain('multipart/form-data; boundary=');
const adminWrites = state.requests.filter(({ method }) => method !== 'GET');
expect(adminWrites.every(({ headers }) => headers.authorization === 'Bearer test-token')).toBe(true);
expect(adminWrites.every(({ headers }) => headers['content-type'] === 'application/json')).toBe(true);
expect(state.requests.filter(({ method }) => method !== 'GET').map(({ path }) => path)).toEqual([
'/projects/step-test/step/signature', '/projects/step-test/step',
]);
expect(state.project.project.urdfMainUrl).toBe('https://assets.example.com/robot.urdf');
expect(state.project.project.publishStatus).toBe('UNPUBLISHED');
await expect(panel(page).getByRole('link', { name: '下载 STEP' })).toHaveAttribute('href', state.project.project.stepMainUrl!);
await expect(panel(page).getByRole('link', { name: '下载 STEP' })).toHaveAttribute('download', name);
await expect(panel(page).locator('.file-list-row')).toHaveCount(0);
});
}
test('格式与空文件校验在请求前生效,重新选择后恢复', async ({ page }) => {
const state = await prepare(page);
await chooseFile(page, 'robot.step.exe');
await expect(panel(page).getByText('仅支持 .step、.stp 文件(扩展名大小写不敏感)')).toBeVisible();
await expect(panel(page).getByRole('button', { name: '上传并绑定' })).toBeDisabled();
await chooseFile(page, 'empty.step', Buffer.alloc(0));
await expect(panel(page).getByText('不能上传空文件')).toBeVisible();
await expect(panel(page).getByRole('button', { name: '上传并绑定' })).toBeDisabled();
await chooseFile(page);
await expect(panel(page).getByRole('button', { name: '上传并绑定' })).toBeEnabled();
expect(state.signatures).toHaveLength(0);
});
test('签名、上传与确认分阶段反馈,确认前保留旧绑定并阻止重复操作', async ({ page }) => {
const signing = gate();
const uploading = gate();
const confirming = gate();
try {
const state = await prepare(page, {
bound: true, signatureGate: signing.promise, uploadGate: uploading.promise, confirmGate: confirming.promise,
});
await chooseFile(page);
await panel(page).getByRole('button', { name: '上传并绑定' }).click();
await expect(panel(page).getByRole('status')).toHaveText('正在获取 STEP 上传签名');
await expect(panel(page).getByRole('button', { name: '重新选择文件' })).toBeDisabled();
await expect(panel(page).getByRole('button', { name: '移除绑定' })).toBeDisabled();
signing.release();
await expect(panel(page).getByRole('status')).toHaveText('正在上传 STEP 文件');
expect(state.confirmations).toHaveLength(0);
uploading.release();
await expect(panel(page).getByRole('status')).toHaveText('文件已上传,正在确认 STEP 绑定');
await expect(panel(page).getByRole('link', { name: 'old.step' })).toBeVisible();
await expect(page.getByText('STEP 已绑定', { exact: true })).toHaveCount(0);
await expect(panel(page).getByRole('button', { name: '重试绑定' })).toBeDisabled();
confirming.release();
await expect(page.getByText('STEP 已绑定', { exact: true })).toBeVisible();
expect(state.signatures).toHaveLength(1);
expect(state.confirmations).toHaveLength(1);
} finally {
signing.release(); uploading.release(); confirming.release();
}
});
for (const stage of ['signature', 'upload'] as const) {
test(`${stage} 失败保留文件和旧绑定,重试可成功`, async ({ page }) => {
const state = await prepare(page, { bound: true, signatureFailure: stage === 'signature', uploadFailure: stage === 'upload' });
await chooseFile(page);
await panel(page).getByRole('button', { name: '上传并绑定' }).click();
await expect(panel(page).getByText(/可保留所选文件重新上传/)).toBeVisible();
await expect(panel(page).getByRole('link', { name: 'old.step' })).toBeVisible();
expect(state.confirmations).toHaveLength(0);
await panel(page).getByRole('button', { name: '上传并绑定' }).click();
await expect(page.getByText('STEP 已绑定', { exact: true })).toBeVisible();
expect(state.signatures).toHaveLength(2);
});
}
for (const reason of ['server', 'network', 'invalid-response'] as const) {
test(`确认 ${reason} 异常保留批次,重试不重复上传`, async ({ page }) => {
const state = await prepare(page, { bound: true, confirmFailure: reason });
await chooseFile(page);
await panel(page).getByRole('button', { name: '上传并绑定' }).click();
await expect(panel(page).getByText(/绑定结果尚未确认/)).toBeVisible();
await expect(page.getByText('STEP 已绑定', { exact: true })).toHaveCount(0);
if (reason === 'network') {
await expect(panel(page).getByRole('link', { name: 'robot.step' })).toBeVisible();
} else {
await expect(panel(page).getByRole('link', { name: 'old.step' })).toBeVisible();
}
await panel(page).getByRole('button', { name: '重试绑定' }).click();
await expect(page.getByText('重试将使用本次上传文件重新设置 STEP 绑定,可能覆盖其他操作的结果。')).toBeVisible();
expect(state.confirmations).toHaveLength(1);
await page.getByRole('button', { name: '确认重试', exact: true }).click();
await expect(page.getByText('STEP 已绑定', { exact: true })).toBeVisible();
expect(state.signatures).toHaveLength(1);
expect(state.uploads).toHaveLength(1);
expect(state.confirmations).toHaveLength(2);
expect(state.confirmations[1]).toEqual(state.confirmations[0]);
});
}
for (const reason of ['missing', 'size-mismatch'] as const) {
test(`对象 ${reason} 时展示请求编号,重新签名上传`, async ({ page }) => {
const state = await prepare(page, { confirmFailure: reason });
await chooseFile(page);
await panel(page).getByRole('button', { name: '上传并绑定' }).click();
await expect(panel(page).getByText(/已上传文件不可用,请重新上传/)).toContainText('step-request-id');
await expect(panel(page).getByRole('button', { name: '重试绑定' })).toHaveCount(0);
await panel(page).getByRole('button', { name: '上传并绑定' }).click();
await expect(page.getByText('STEP 已绑定', { exact: true })).toBeVisible();
expect(state.signatures).toHaveLength(2);
expect(state.uploads).toHaveLength(2);
expect(state.confirmations[1].batchCode).toBe('step-batch-2');
});
}
test('已上传对象在签名过期后仍可手动重试确认,取消不发请求', async ({ page }) => {
await page.clock.install({ time: new Date('2026-11-02T08:00:00Z') });
const state = await prepare(page, { confirmFailure: 'server', signatureExpiresAt: '2026-11-02T08:15:00Z' });
await chooseFile(page);
await panel(page).getByRole('button', { name: '上传并绑定' }).click();
await expect(panel(page).getByText(/绑定结果尚未确认/)).toBeVisible();
await page.clock.setFixedTime(new Date('2026-11-02T08:16:00Z'));
await panel(page).getByRole('button', { name: '重试绑定' }).click();
await expect(page.getByText('确定重试 STEP 绑定?')).toBeVisible();
await page.getByRole('button', { name: /取\s*消/, exact: true }).click();
await expect(page.getByText('确定重试 STEP 绑定?')).not.toBeVisible();
expect(state.confirmations).toHaveLength(1);
await panel(page).getByRole('button', { name: '重试绑定' }).click();
await page.getByRole('button', { name: '确认重试', exact: true }).click();
await expect(page.getByText('STEP 已绑定', { exact: true })).toBeVisible();
expect(state.signatures).toHaveLength(1);
expect(state.uploads).toHaveLength(1);
expect(state.confirmations).toEqual([state.confirmations[0], state.confirmations[0]]);
});
test('重新选择文件会放弃待确认批次', async ({ page }) => {
const state = await prepare(page, { confirmFailure: 'server' });
await chooseFile(page);
await panel(page).getByRole('button', { name: '上传并绑定' }).click();
await expect(panel(page).getByRole('button', { name: '重试绑定' })).toBeEnabled();
await chooseFile(page, 'replacement.stp');
await panel(page).getByRole('button', { name: '上传并绑定' }).click();
await expect(panel(page).getByRole('link', { name: 'replacement.stp' })).toBeVisible();
expect(state.signatures).toHaveLength(2);
expect(state.confirmations[1].files[0].relativePath).toBe('replacement.stp');
});
test('签名与文件不匹配时不上传或确认', async ({ page }) => {
const state = await prepare(page, { invalidSignature: true });
await chooseFile(page);
await panel(page).getByRole('button', { name: '上传并绑定' }).click();
await expect(panel(page).getByText(/STEP 上传签名与所选文件不匹配/)).toBeVisible();
expect(state.uploads).toHaveLength(0);
expect(state.confirmations).toHaveLength(0);
});
test('移除绑定二次确认,仅调用 DELETE 并保留 URDF', async ({ page }) => {
const state = await prepare(page, { bound: true });
await panel(page).getByRole('button', { name: '移除绑定' }).click();
await expect(page.getByText('确定移除 STEP 绑定?(不会删除已上传对象)')).toBeVisible();
expect(state.deletes).toBe(0);
await page.getByRole('button', { name: /确\s*定/, exact: true }).click();
await expect(page.getByText('已移除 STEP 绑定', { exact: true })).toBeVisible();
await expect(panel(page).getByText('未绑定', { exact: true })).toBeVisible();
await expect(panel(page).getByRole('link', { name: '下载 STEP' })).toHaveCount(0);
expect(state.deletes).toBe(1);
expect(state.requests.find(({ method }) => method === 'DELETE')?.body).toBeNull();
expect(state.uploads).toHaveLength(0);
expect(state.project.project.urdfMainUrl).toBe('https://assets.example.com/robot.urdf');
});
test('STEP 通过跨域资源地址直接下载,原始文件名由 OSS 响应保留,不请求管理下载接口', async ({ page, context }) => {
const downloads: { url: string; headers: Record<string, string>; method: string }[] = [];
await context.route('https://assets.example.com/**', async (route) => {
downloads.push({ url: route.request().url(), headers: route.request().headers(), method: route.request().method() });
// 不返回 CORS 头,验证原生下载不依赖 fetch/Blob 或管理端鉴权。
return route.fulfill({
body: content,
headers: { 'Content-Type': 'application/octet-stream', 'Content-Disposition': disposition('机械臂 装配.STEP') },
});
});
const state = await prepare(page, { bound: true });
await chooseFile(page, '机械臂 装配.STEP');
await panel(page).getByRole('button', { name: '上传并绑定' }).click();
await expect(panel(page).getByRole('link', { name: '机械臂 装配.STEP', exact: true })).toBeVisible();
const expectedUrl = `https://assets.example.com/${objectKey('step-batch-1', '机械臂 装配.STEP')}`;
const button = panel(page).getByRole('link', { name: '下载 STEP' });
await expect(button).toHaveAttribute('href', expectedUrl);
await expect(button).toHaveAttribute('download', '机械臂 装配.STEP');
const downloadPromise = page.waitForEvent('download');
await button.click();
const downloaded = await downloadPromise;
expect(downloaded.suggestedFilename()).toBe('机械臂 装配.STEP');
const downloadedPath = await downloaded.path();
expect(downloadedPath).not.toBeNull();
expect(await readFile(downloadedPath!)).toEqual(content);
expect(downloads).toHaveLength(1);
expect(downloads[0].url).toBe(expectedUrl);
expect(downloads[0].method).toBe('GET');
expect(downloads[0].headers.authorization).toBeUndefined();
expect(state.requests.some(({ path }) => path.includes('/download'))).toBe(false);
await expect(page).toHaveURL('/projects/step-test');
});
test('移除失败刷新当前状态后允许重试', async ({ page }) => {
const state = await prepare(page, { bound: true, deleteFailure: true });
await panel(page).getByRole('button', { name: '移除绑定' }).click();
await page.getByRole('button', { name: /确\s*定/, exact: true }).click();
await expect(panel(page).getByText(/请刷新确认当前绑定状态后再操作/)).toBeVisible();
await expect(panel(page).getByRole('link', { name: 'old.step' })).toBeVisible();
await expect.poll(() => state.gets).toBeGreaterThan(1);
await panel(page).getByRole('button', { name: '移除绑定' }).click();
await page.getByRole('button', { name: /确\s*定/, exact: true }).click();
await expect(panel(page).getByText('未绑定', { exact: true })).toBeVisible();
expect(state.deletes).toBe(2);
});
test('移除绑定会放弃待确认的旧请求,再上传使用新签名', async ({ page }) => {
const state = await prepare(page, { bound: true, confirmFailure: 'server' });
await chooseFile(page);
await panel(page).getByRole('button', { name: '上传并绑定' }).click();
await expect(panel(page).getByRole('button', { name: '重试绑定' })).toBeEnabled();
await panel(page).getByRole('button', { name: '移除绑定' }).click();
await page.getByRole('button', { name: /确\s*定/, exact: true }).click();
await expect(panel(page).getByText('未绑定', { exact: true })).toBeVisible();
await expect(panel(page).getByRole('button', { name: '重试绑定' })).toHaveCount(0);
await panel(page).getByRole('button', { name: '上传并绑定' }).click();
await expect(page.getByText('STEP 已绑定', { exact: true })).toBeVisible();
expect(state.deletes).toBe(1);
expect(state.signatures).toHaveLength(2);
expect(state.uploads).toHaveLength(2);
expect(state.confirmations[1].batchCode).toBe('step-batch-2');
});
test('登录失效沿用现有 401 跳转', async ({ page }) => {
await prepare(page);
await page.route('**/step/signature', (route) => failure(route, 'UNAUTHORIZED', '登录已过期', 401));
await chooseFile(page);
await panel(page).getByRole('button', { name: '上传并绑定' }).click();
await expect(page).toHaveURL(/\/login\?redirect=/);
expect(await page.evaluate(() => localStorage.getItem('vibemake_admin_token'))).toBeNull();
});
test('离开项目后,未完成的 OSS 上传不会继续触发绑定', async ({ page }) => {
const uploading = gate();
try {
const state = await prepare(page, { uploadGate: uploading.promise });
await chooseFile(page);
await panel(page).getByRole('button', { name: '上传并绑定' }).click();
await expect(panel(page).getByRole('status')).toHaveText('正在上传 STEP 文件');
await page.getByRole('link', { name: '项目管理', exact: true }).first().click();
await expect(page).toHaveURL('/projects');
uploading.release();
await expect(page.getByRole('heading', { name: 'STEP 测试机器人' })).toHaveCount(0);
expect(state.confirmations).toHaveLength(0);
} finally {
uploading.release();
}
});
test('STEP 校验接受大小边界与合法文件名,拒绝空文件、目录和非法路径', () => {
const file = (name: string, size = 1) => ({ name, size } as File);
expect(MAX_STEP_FILE_SIZE).toBe(524288000);
expect(checkStepFile(null)).toEqual([]);
expect(checkStepFile(file('large.step', 51 * 1024 * 1024))).toEqual([]);
expect(checkStepFile(file('机械臂 装配.STEP', MAX_STEP_FILE_SIZE))).toEqual([]);
expect(checkStepFile(file('robot.StP'))).toEqual([]);
expect(checkStepFile(file('robot.step', MAX_STEP_FILE_SIZE + 1))).toContain('文件大小不能超过 500 MiB');
expect(checkStepFile(file('robot.step', 0))).toContain('不能上传空文件');
for (const name of ['robot.step.exe', '.step', 'robot', 'dir/robot.step', '..\\robot.stp', 'a:robot.step', 'a\u0000.step', `${'a'.repeat(1024)}.step`]) {
expect(checkStepFile(file(name)).length, name).toBeGreaterThan(0);
}
});