diff --git a/design-qa.md b/design-qa.md new file mode 100644 index 000000000..65a617d8b --- /dev/null +++ b/design-qa.md @@ -0,0 +1,35 @@ +# Suite 发布任务设计验收 + +## 验收范围 + +- 参考方案:方案 3 的任务列表分层、方案 2 的独立详情页。 +- 实现页面:`/dashboard/suites?tab=publishing`、`/dashboard/suites/publishing/:operationId`。 +- 视口:桌面端 1487 × 1058;移动端 390 × 844。 + +## 对照结论 + +| 检查项 | 结果 | 证据 | +|---|---|---| +| 控制台任务分层 | 通过 | 保留“需要处理 / 进行中 / 最近完成”,终态记录位于“最近完成” | +| 独立任务详情 | 通过 | 查看任务进入独立路由,不再回到创建 Suite 页面 | +| 取消后的可追溯性 | 通过 | 任务记录保留,并明确说明已有 SkillVersion 与审核任务不会撤回 | +| 成员审核入口 | 通过 | 取消后仍显示“查看技能版本与审核状态” | +| 状态表现 | 通过 | 任务使用静态状态图标,没有持续旋转图标 | +| 响应式 | 通过 | 390px 视口没有横向溢出,操作与成员信息仍可访问 | +| 现有设计系统 | 通过 | 复用 DashboardPageHeader、Card、Tabs、Button、Pagination 与 Lucide 图标 | + +参考图包含多条示例任务;真实预览库只有一条已停止记录,因此实际页面保留空分层并展示真实数据。参考详情图展示到“套件审核”,而当前 Bundle 工作流的职责止于“创建套件草稿”,实际实现按领域状态保留三阶段,避免暗示系统会自动提交 Suite 审核。 + +## 缺陷分级 + +- P0:无。 +- P1:无。 +- P2:无。 + +## 自动化结果 + +- 桌面端任务列表与详情页完成同视口截图对照。 +- 真实普通用户会话完成任务列表、详情、返回、成员审核入口和移动端检查。 +- 浏览器过程无 console error 或 pageerror。 + +final result: passed diff --git a/openspec/changes/add-suite-bundle-publishing/proposal.md b/openspec/changes/add-suite-bundle-publishing/proposal.md index a179192c3..26f5f8458 100644 --- a/openspec/changes/add-suite-bundle-publishing/proposal.md +++ b/openspec/changes/add-suite-bundle-publishing/proposal.md @@ -19,6 +19,9 @@ Suite 时,维护者仍需逐个创建或上传 Skill,再手工把 Suite 固 - 新增持久化 Bundle 发布操作。只有具备独立创建或发布权限且携带包的成员进入现有校验、扫描和 审核流程;所有包版本均为 PUBLISHED 且全部引用仍然有效后,才原子创建新 Suite 及首个草稿, 或为已有 Suite 创建 DRAFT SuiteVersion。 +- Bundle 确认后进入独立发布任务详情;“我的套件”以“技能套件/发布任务”页签分离结果和过程, + 发布任务按“需要处理/进行中/最近完成”分层。停止创建 Suite 后保留任务、已创建的 SkillVersion + 和审核任务,并继续提供成员版本与审核入口。 - 未变化成员继续使用原精确版本,不创建版本、扫描或审核;支持添加、移除、调整顺序和显式重新 固定引用成员版本。 - 任意成员 Skill 均可展示当前用户可见的所属 Suite,不再只支持 Entry Skill。 diff --git a/openspec/changes/add-suite-bundle-publishing/specs/suite-bundle-publishing/spec.md b/openspec/changes/add-suite-bundle-publishing/specs/suite-bundle-publishing/spec.md index 5f28a1595..f3bc66283 100644 --- a/openspec/changes/add-suite-bundle-publishing/specs/suite-bundle-publishing/spec.md +++ b/openspec/changes/add-suite-bundle-publishing/specs/suite-bundle-publishing/spec.md @@ -512,10 +512,12 @@ SHALL 支持上传一个 ZIP;浏览器支持安全目录选择时,也可以 确认页面 SHALL 展示将创建的 Skill、将创建的 SkillVersion、复用版本、纯引用和移除成员数量, 每个携带包成员的最终可见性、发布路径和 warning,并说明成员就绪后只生成 Suite 草稿。warning 必须逐成员明确确认。确认后,进度页 SHALL 展示每个成员的创建、扫描、审核、复用、引用、失败或 -阻塞状态,并能通过操作 ID 在刷新或重新登录后恢复。“我的套件” SHALL 展示当前用户发起的非终态 -Bundle 操作,使尚未生成 Suite 草稿的发布过程仍有稳定入口;公开套件专区 SHALL 继续只展示已发布 -Suite,不得把执行操作伪装成已经创建的 Suite。非终态操作列表 SHALL 分页,并在数据库中聚合成员 -进度;只有仍可能自动变化的运行或等待状态才进行短间隔轮询。 +阻塞状态,并能通过操作 ID 在刷新或重新登录后恢复。“我的套件” SHALL 将技能套件与发布任务分为 +两个页签,并在发布任务中按“需要处理”“进行中”“最近完成”分层展示当前用户发起的 Bundle 操作, +使尚未生成 Suite 草稿或已经取消的发布过程都有稳定入口。点击任务 SHALL 进入独立发布详情页,不得 +返回创建或新版本编辑页面。公开套件专区 SHALL 继续只展示已发布 Suite,不得把执行操作伪装成已经 +创建的 Suite。任务列表 SHALL 分页并在数据库中聚合成员进度;只有仍可能自动变化的运行或等待状态 +才进行短间隔轮询。 #### Scenario: 用户确认混合计划 - **WHEN** 预览同时包含创建 Skill、创建版本、复用、引用和移除 @@ -529,11 +531,17 @@ Suite,不得把执行操作伪装成已经创建的 Suite。非终态操作列 #### Scenario: 从我的套件继续查看发布 - **WHEN** 当前用户发起的 Bundle 操作仍为 `RUNNING`、`WAITING_FOR_MEMBERS` 或 `BLOCKED_RETRYABLE` -- **THEN** “我的套件”展示目标坐标、目标版本、整体状态和成员完成数量 -- **AND** 用户可以回到该操作的进度页继续查看或处理 +- **THEN** “我的套件”的“发布任务”页签按状态分层展示目标坐标、目标版本、整体状态和成员完成数量 +- **AND** 用户进入独立任务详情页继续查看或处理,不进入 Suite 创建或新版本编辑页 - **AND** 操作数量超过单页容量时仍可通过分页访问 - **AND** 公开套件专区不展示该未完成操作 +#### Scenario: 取消后保留发布记录和成员审核入口 +- **WHEN** 用户停止一个已经创建部分 SkillVersion 或审核任务的 Bundle 操作 +- **THEN** 操作以 `CANCELLED` 保留在“最近完成”分组,详情明确说明不会再创建 Suite 草稿 +- **AND** 已创建的 SkillVersion 和审核任务不撤回、不删除,仍可从成员行进入对应版本处理 +- **AND** 长时间等待状态使用静态状态图标而不是持续旋转的加载图标 + #### Scenario: 操作创建 Suite 草稿 - **WHEN** 操作达到 `SUITE_DRAFT_CREATED` - **THEN** 页面提供新 Suite 草稿入口及后续提交审核说明 diff --git a/openspec/changes/add-suite-bundle-publishing/tasks.md b/openspec/changes/add-suite-bundle-publishing/tasks.md index 17d546404..e992385e8 100644 --- a/openspec/changes/add-suite-bundle-publishing/tasks.md +++ b/openspec/changes/add-suite-bundle-publishing/tasks.md @@ -21,7 +21,7 @@ - [x] 3.3 `[REQ-SBP-12, REQ-SBP-13]` 记录包和引用结果,并按规范状态矩阵通过领域事件与有界恢复任务完成协调;覆盖 PRIVATE `UPLOADED`、`SCANNING`、`SCAN_FAILED`、`PENDING_REVIEW`、`REJECTED`、外部撤回/删除/下架、`BLOCKED_RETRYABLE` 与 `REPREVIEW_REQUIRED`,验证占用随终态原子释放,重复、延迟、丢失和乱序时按原 ID 收敛或明确要求重新预览。 - [x] 3.4 `[REQ-SBP-12]` 仅在包发布成功、引用最终有效且最终权限/状态检查通过时,原子创建新 Suite 及首个 DRAFT,或为已有 Suite 创建一个 SuiteVersion DRAFT;验证权限撤销、Namespace 冻结、待审核、被拒绝、失败包和失效引用不会产生空 Suite 或部分草稿。 - [x] 3.5 `[REQ-SBP-13, REQ-SBP-15]` 实现带当前授权和响应脱敏的状态读取、原 ID 重试、非破坏性取消、终态占用释放、PreviewSession/暂存对象过期和限定范围补偿清理;验证等待审核的 ExecutionOperation 不随预览过期,已有 SkillVersion 和引用保持不变,清理失败仍有可操作记录。 -- [x] 3.6 `[REQ-SBP-17, REQ-SBP-18]` 在“创建 Suite”和“创建新版本”入口提供手工组合/本地导入选择,并实现准确列出副作用、最终可见性、发布路径和逐成员 warning 确认的确认页及可恢复进度页;展示包/引用状态、Skill 审核链接、阻塞原因、重试/取消和生成的 Suite 草稿;“我的套件”通过分页和数据库聚合展示当前用户发起的非终态操作并提供继续查看入口,只对运行或等待状态短间隔轮询。通过正常、等待、可重试阻塞、必须重预览、取消、权限变化、刷新、重新登录、超过单页容量和离开导入页后恢复用例验证。 +- [x] 3.6 `[REQ-SBP-17, REQ-SBP-18]` 在“创建 Suite”和“创建新版本”入口提供手工组合/本地导入选择,并实现准确列出副作用、最终可见性、发布路径和逐成员 warning 确认的确认页;确认后统一进入独立发布任务详情页,展示包/引用状态、Skill 审核链接、阻塞原因、重试/停止和生成的 Suite 草稿。“我的套件”以“技能套件/发布任务”页签分离创作结果和过程记录,发布任务通过单次分页数据库聚合按“需要处理/进行中/最近完成”分层展示,保留取消记录,只对运行或等待状态短间隔轮询。通过正常、等待、可重试阻塞、必须重预览、取消后保留记录和成员审核、权限变化、刷新、重新登录、超过单页容量和离开导入页后恢复用例验证。 ## 4. 任意成员的所属 Suite diff --git a/server/skillhub-app/src/main/java/com/iflytek/skillhub/controller/portal/SkillSuiteBundleController.java b/server/skillhub-app/src/main/java/com/iflytek/skillhub/controller/portal/SkillSuiteBundleController.java index 87d2293fd..bfd3e8e89 100644 --- a/server/skillhub-app/src/main/java/com/iflytek/skillhub/controller/portal/SkillSuiteBundleController.java +++ b/server/skillhub-app/src/main/java/com/iflytek/skillhub/controller/portal/SkillSuiteBundleController.java @@ -7,15 +7,16 @@ import com.iflytek.skillhub.dto.ApiResponse; import com.iflytek.skillhub.dto.ApiResponseFactory; import com.iflytek.skillhub.dto.PageResponse; import com.iflytek.skillhub.dto.SkillSuiteBundleConfirmRequest; -import com.iflytek.skillhub.dto.SkillSuiteBundleOperationResponse; import com.iflytek.skillhub.dto.SkillSuiteBundleOperationDetailResponse; +import com.iflytek.skillhub.dto.SkillSuiteBundleOperationPageResponse; +import com.iflytek.skillhub.dto.SkillSuiteBundleOperationResponse; import com.iflytek.skillhub.dto.SkillSuiteBundleOperationSummaryResponse; import com.iflytek.skillhub.dto.SkillSuiteBundlePreviewResponse; import com.iflytek.skillhub.ratelimit.RateLimit; import com.iflytek.skillhub.service.bundle.SkillSuiteBundleConfirmationAppService; -import com.iflytek.skillhub.service.bundle.SkillSuiteBundlePreviewAppService; -import com.iflytek.skillhub.service.bundle.SkillSuiteBundleOperationQueryService; import com.iflytek.skillhub.service.bundle.SkillSuiteBundleOperationCommandService; +import com.iflytek.skillhub.service.bundle.SkillSuiteBundleOperationQueryService; +import com.iflytek.skillhub.service.bundle.SkillSuiteBundlePreviewAppService; import com.iflytek.skillhub.service.bundle.SkillSuiteBundleResponseMapper; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; @@ -121,6 +122,16 @@ public class SkillSuiteBundleController extends BaseApiController { return ok("response.success.read", operationQueryService.listActive(userId, page, size)); } + @GetMapping("/operations/mine") + @Operation(operationId = "listMySkillSuiteBundleOperations", summary = "List current and completed Bundle operations started by the current user") + public ApiResponse listMyOperations( + @RequestAttribute("userId") String userId, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "12") int size + ) { + return ok("response.success.read", operationQueryService.listMine(userId, page, size)); + } + @PostMapping("/operations/{operationId}/cancel") @Operation(operationId = "cancelSkillSuiteBundleOperation", summary = "Cancel one active Suite Bundle operation") public ApiResponse cancelOperation( diff --git a/server/skillhub-app/src/main/java/com/iflytek/skillhub/dto/SkillSuiteBundleOperationPageResponse.java b/server/skillhub-app/src/main/java/com/iflytek/skillhub/dto/SkillSuiteBundleOperationPageResponse.java new file mode 100644 index 000000000..98e2dfce2 --- /dev/null +++ b/server/skillhub-app/src/main/java/com/iflytek/skillhub/dto/SkillSuiteBundleOperationPageResponse.java @@ -0,0 +1,13 @@ +package com.iflytek.skillhub.dto; + +import java.util.List; + +/** One prioritized page of Bundle tasks plus collection-wide polling state. */ +public record SkillSuiteBundleOperationPageResponse( + List items, + long total, + int page, + int size, + boolean hasChangingOperations +) { +} diff --git a/server/skillhub-app/src/main/java/com/iflytek/skillhub/dto/SkillSuiteBundleOperationSummaryResponse.java b/server/skillhub-app/src/main/java/com/iflytek/skillhub/dto/SkillSuiteBundleOperationSummaryResponse.java index 0001f4be7..5d7d202ff 100644 --- a/server/skillhub-app/src/main/java/com/iflytek/skillhub/dto/SkillSuiteBundleOperationSummaryResponse.java +++ b/server/skillhub-app/src/main/java/com/iflytek/skillhub/dto/SkillSuiteBundleOperationSummaryResponse.java @@ -5,7 +5,7 @@ import com.iflytek.skillhub.domain.suite.bundle.SkillSuiteBundleOperationStatus; import java.time.Instant; -/** Active Bundle operation shown before its Suite draft exists. */ +/** Bundle operation summary shown in the current user's publishing task list. */ public record SkillSuiteBundleOperationSummaryResponse( String operationId, SkillSuiteBundleMode mode, diff --git a/server/skillhub-app/src/main/java/com/iflytek/skillhub/repository/SkillSuiteBundleOperationQueryRepository.java b/server/skillhub-app/src/main/java/com/iflytek/skillhub/repository/SkillSuiteBundleOperationQueryRepository.java index d5d59c6c2..ea1ad6f4f 100644 --- a/server/skillhub-app/src/main/java/com/iflytek/skillhub/repository/SkillSuiteBundleOperationQueryRepository.java +++ b/server/skillhub-app/src/main/java/com/iflytek/skillhub/repository/SkillSuiteBundleOperationQueryRepository.java @@ -3,6 +3,7 @@ package com.iflytek.skillhub.repository; import com.iflytek.skillhub.domain.suite.bundle.SkillSuiteBundleMode; import com.iflytek.skillhub.domain.suite.bundle.SkillSuiteBundleOperationStatus; import com.iflytek.skillhub.dto.PageResponse; +import com.iflytek.skillhub.dto.SkillSuiteBundleOperationPageResponse; import com.iflytek.skillhub.dto.SkillSuiteBundleOperationSummaryResponse; import jakarta.persistence.EntityManager; import jakarta.persistence.Query; @@ -15,7 +16,7 @@ import java.time.OffsetDateTime; import java.util.List; /** - * Dashboard read model for active Bundle operations owned by one actor. + * Dashboard read model for Bundle operations owned by one actor. * *

The native query pages operations before joining member rows, then computes status counts in * PostgreSQL. This keeps each poll bounded and avoids loading member errors and warnings.

@@ -86,6 +87,71 @@ public class SkillSuiteBundleOperationQueryRepository { ((Number) count.getSingleResult()).longValue(), page, size); } + @Transactional(readOnly = true) + public SkillSuiteBundleOperationPageResponse findMine( + String actorId, + int page, + int size + ) { + Query select = entityManager.createNativeQuery(""" + WITH selected_operation AS ( + SELECT operation.operation_id, operation.mode, + '@' || namespace.slug || '/' || operation.target_suite_slug AS target_coordinate, + operation.target_version, operation.status, operation.failure_code, + base_version.version AS base_version, operation.updated_at + FROM skill_suite_bundle_operation operation + JOIN namespace ON namespace.id = operation.namespace_id + LEFT JOIN skill_suite_version base_version + ON base_version.id = operation.base_suite_version_id + WHERE operation.actor_id = :actorId + ORDER BY CASE + WHEN operation.status IN ('BLOCKED_RETRYABLE', 'REPREVIEW_REQUIRED') THEN 0 + WHEN operation.status IN ('RUNNING', 'WAITING_FOR_MEMBERS') THEN 1 + ELSE 2 + END, + operation.updated_at DESC, operation.operation_id DESC + OFFSET :offset ROWS FETCH NEXT :size ROWS ONLY + ) + SELECT operation.operation_id, operation.mode, operation.target_coordinate, + operation.target_version, operation.status, operation.failure_code, + operation.base_version, operation.updated_at, + COUNT(member.id) AS total_members, + COUNT(member.id) FILTER (WHERE member.status = 'COMPLETED') AS completed_members, + COUNT(member.id) FILTER (WHERE member.status = 'WAITING_FOR_MEMBER') AS waiting_members + FROM selected_operation operation + LEFT JOIN skill_suite_bundle_member_result member + ON member.operation_id = operation.operation_id + GROUP BY operation.operation_id, operation.mode, operation.target_coordinate, + operation.target_version, operation.status, operation.failure_code, + operation.base_version, operation.updated_at + ORDER BY CASE + WHEN operation.status IN ('BLOCKED_RETRYABLE', 'REPREVIEW_REQUIRED') THEN 0 + WHEN operation.status IN ('RUNNING', 'WAITING_FOR_MEMBERS') THEN 1 + ELSE 2 + END, + operation.updated_at DESC, operation.operation_id DESC + """); + select.setParameter("actorId", actorId) + .setParameter("offset", (long) page * size) + .setParameter("size", size); + Query count = entityManager.createNativeQuery(""" + SELECT (SELECT COUNT(*) + FROM skill_suite_bundle_operation operation + WHERE operation.actor_id = :actorId), + EXISTS(SELECT 1 + FROM skill_suite_bundle_operation changing + WHERE changing.actor_id = :actorId + AND changing.status IN ('RUNNING', 'WAITING_FOR_MEMBERS')) + """).setParameter("actorId", actorId); + + @SuppressWarnings("unchecked") + List rows = select.getResultList(); + Object[] metrics = (Object[]) count.getSingleResult(); + return new SkillSuiteBundleOperationPageResponse( + rows.stream().map(this::map).toList(), + ((Number) metrics[0]).longValue(), page, size, (Boolean) metrics[1]); + } + private Query bind(Query query, String actorId) { return query.setParameter("actorId", actorId).setParameter("statuses", ACTIVE_STATUSES); } diff --git a/server/skillhub-app/src/main/java/com/iflytek/skillhub/service/bundle/SkillSuiteBundleOperationQueryService.java b/server/skillhub-app/src/main/java/com/iflytek/skillhub/service/bundle/SkillSuiteBundleOperationQueryService.java index fb3a0b57c..7d8b62018 100644 --- a/server/skillhub-app/src/main/java/com/iflytek/skillhub/service/bundle/SkillSuiteBundleOperationQueryService.java +++ b/server/skillhub-app/src/main/java/com/iflytek/skillhub/service/bundle/SkillSuiteBundleOperationQueryService.java @@ -14,6 +14,7 @@ import com.iflytek.skillhub.domain.suite.bundle.SkillSuiteBundleMemberResultRepo import com.iflytek.skillhub.domain.suite.bundle.SkillSuiteBundleOperationAuthorizationPolicy; import com.iflytek.skillhub.dto.PageResponse; import com.iflytek.skillhub.dto.SkillSuiteBundleOperationDetailResponse; +import com.iflytek.skillhub.dto.SkillSuiteBundleOperationPageResponse; import com.iflytek.skillhub.dto.SkillSuiteBundleOperationSummaryResponse; import com.iflytek.skillhub.repository.SkillSuiteBundleOperationQueryRepository; import org.springframework.stereotype.Service; @@ -114,6 +115,17 @@ public class SkillSuiteBundleOperationQueryService { actorId, Math.max(0, page), Math.min(Math.max(1, size), 50)); } + /** Returns one bounded page of the caller's operations, including terminal history. */ + @Transactional(readOnly = true) + public SkillSuiteBundleOperationPageResponse listMine( + String actorId, + int page, + int size + ) { + return operationQueryRepository.findMine( + actorId, Math.max(0, page), Math.min(Math.max(1, size), 50)); + } + private boolean canReadMember( Skill skill, Long namespaceId, diff --git a/server/skillhub-app/src/main/resources/db/migration/V59__index_bundle_operation_history_by_actor.sql b/server/skillhub-app/src/main/resources/db/migration/V59__index_bundle_operation_history_by_actor.sql new file mode 100644 index 000000000..c9096e12d --- /dev/null +++ b/server/skillhub-app/src/main/resources/db/migration/V59__index_bundle_operation_history_by_actor.sql @@ -0,0 +1,11 @@ +CREATE INDEX idx_suite_bundle_operation_actor_priority_updated + ON skill_suite_bundle_operation( + actor_id, + (CASE + WHEN status IN ('BLOCKED_RETRYABLE', 'REPREVIEW_REQUIRED') THEN 0 + WHEN status IN ('RUNNING', 'WAITING_FOR_MEMBERS') THEN 1 + ELSE 2 + END), + updated_at DESC, + operation_id DESC + ); diff --git a/server/skillhub-app/src/test/java/com/iflytek/skillhub/controller/portal/SkillSuiteBundleControllerTest.java b/server/skillhub-app/src/test/java/com/iflytek/skillhub/controller/portal/SkillSuiteBundleControllerTest.java index c21d04476..4a2950c48 100644 --- a/server/skillhub-app/src/test/java/com/iflytek/skillhub/controller/portal/SkillSuiteBundleControllerTest.java +++ b/server/skillhub-app/src/test/java/com/iflytek/skillhub/controller/portal/SkillSuiteBundleControllerTest.java @@ -6,6 +6,7 @@ import com.iflytek.skillhub.auth.rbac.PlatformPrincipal; import com.iflytek.skillhub.domain.namespace.NamespaceMemberRepository; import com.iflytek.skillhub.dto.SkillSuiteBundleOperationResponse; import com.iflytek.skillhub.dto.SkillSuiteBundleOperationDetailResponse; +import com.iflytek.skillhub.dto.SkillSuiteBundleOperationPageResponse; import com.iflytek.skillhub.dto.SkillSuiteBundleOperationSummaryResponse; import com.iflytek.skillhub.dto.PageResponse; import com.iflytek.skillhub.domain.suite.bundle.SkillSuiteBundleMode; @@ -181,6 +182,23 @@ class SkillSuiteBundleControllerTest { .andExpect(jsonPath("$.data.total").value(1)); } + @Test + void authenticatedCallerCanListTheirOperationHistory() throws Exception { + when(operationQueryService.listMine("actor", 0, 12)).thenReturn(new SkillSuiteBundleOperationPageResponse(List.of( + new SkillSuiteBundleOperationSummaryResponse( + "operation-cancelled", SkillSuiteBundleMode.CREATE, "@global/suite", "1.0.0", + SkillSuiteBundleOperationStatus.CANCELLED, null, + null, 2, 1, 0, Instant.parse("2026-09-11T08:00:00Z"))), 1, 0, 12, true)); + + mockMvc.perform(get("/api/v1/suite-bundles/operations/mine") + .with(authentication(authToken("actor")))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.data.total").value(1)) + .andExpect(jsonPath("$.data.hasChangingOperations").value(true)) + .andExpect(jsonPath("$.data.items[0].operationId").value("operation-cancelled")) + .andExpect(jsonPath("$.data.items[0].status").value("CANCELLED")); + } + @Test void authenticatedCallerCanCancelAndRetryAnOperation() throws Exception { when(operationCommandService.cancel("operation-1", "actor", Map.of(), Set.of())) diff --git a/server/skillhub-app/src/test/java/com/iflytek/skillhub/integration/SkillSuiteBundleOperationQueryRepositoryTest.java b/server/skillhub-app/src/test/java/com/iflytek/skillhub/integration/SkillSuiteBundleOperationQueryRepositoryTest.java index 0d5635b1b..9f3d21c10 100644 --- a/server/skillhub-app/src/test/java/com/iflytek/skillhub/integration/SkillSuiteBundleOperationQueryRepositoryTest.java +++ b/server/skillhub-app/src/test/java/com/iflytek/skillhub/integration/SkillSuiteBundleOperationQueryRepositoryTest.java @@ -9,6 +9,7 @@ import com.iflytek.skillhub.domain.suite.bundle.SkillSuiteBundleExecutionOperati import com.iflytek.skillhub.domain.suite.bundle.SkillSuiteBundleMemberResult; import com.iflytek.skillhub.domain.suite.bundle.SkillSuiteBundleMemberSourceType; import com.iflytek.skillhub.domain.suite.bundle.SkillSuiteBundleMode; +import com.iflytek.skillhub.domain.suite.bundle.SkillSuiteBundleOperationStatus; import com.iflytek.skillhub.domain.suite.bundle.SkillSuiteBundlePreviewSession; import com.iflytek.skillhub.domain.suite.bundle.SkillSuiteBundlePublishAction; import com.iflytek.skillhub.domain.suite.bundle.SkillSuiteBundleRelationshipChange; @@ -123,11 +124,58 @@ class SkillSuiteBundleOperationQueryRepositoryTest { assertThat(repository.findActive("another-actor", 0, 1).items()).singleElement() .extracting(summary -> summary.operationId()) .isEqualTo("operation-4"); + var history = repository.findMine("actor", 0, 10); + assertThat(history.total()).isEqualTo(3); + assertThat(history.hasChangingOperations()).isTrue(); + assertThat(history.items()).extracting(summary -> summary.operationId()) + .containsExactly("operation-2", "operation-1", "operation-3"); + assertThat(repository.findMine("another-actor", 0, 10).items()).singleElement() + .extracting(summary -> summary.operationId()) + .isEqualTo("operation-4"); assertThat(entityManager.getEntityManager().createNativeQuery(""" SELECT indexdef FROM pg_indexes WHERE indexname = 'idx_suite_bundle_operation_actor_status_updated' """).getSingleResult().toString()) .contains("(actor_id, status, updated_at DESC, operation_id DESC)"); + assertThat(entityManager.getEntityManager().createNativeQuery(""" + SELECT indexdef FROM pg_indexes + WHERE indexname = 'idx_suite_bundle_operation_actor_priority_updated' + """).getSingleResult().toString()) + .contains("actor_id", "CASE", "updated_at DESC", "operation_id DESC"); + } + + @Test + void prioritizesActionableAndChangingTasksAheadOfNewerTerminalHistory() { + entityManager.persist(new UserAccount("actor", "Actor", null, null)); + Namespace namespace = entityManager.persistFlushFind( + new Namespace("team-ai", "AI Team", "actor")); + List terminalTokens = List.of("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b"); + for (int index = 0; index < terminalTokens.size(); index++) { + String token = terminalTokens.get(index); + SkillSuiteBundleExecutionOperation terminal = createOperation( + "operation-" + token, "actor", namespace, "terminal-" + token); + terminal.cancel(NOW.plusSeconds(100L + index)); + entityManager.persist(terminal); + } + SkillSuiteBundleExecutionOperation running = createOperation( + "operation-c", "actor", namespace, "running-suite"); + entityManager.persist(running); + SkillSuiteBundleExecutionOperation blocked = createOperation( + "operation-d", "actor", namespace, "blocked-suite"); + blocked.markBlockedRetryable("MEMBER_FAILED", "retry", NOW.plusSeconds(1)); + entityManager.persist(blocked); + entityManager.flush(); + + var page = repository.findMine("actor", 0, 12); + + assertThat(page.total()).isEqualTo(14); + assertThat(page.hasChangingOperations()).isTrue(); + assertThat(page.items()).hasSize(12); + assertThat(page.items()).extracting(summary -> summary.operationId()) + .startsWith("operation-d", "operation-c"); + assertThat(page.items()).extracting(summary -> summary.status()) + .startsWith(SkillSuiteBundleOperationStatus.BLOCKED_RETRYABLE, + SkillSuiteBundleOperationStatus.RUNNING); } private SkillSuiteBundleMemberResult member(int position, String slug, boolean waiting) { diff --git a/server/skillhub-app/src/test/java/com/iflytek/skillhub/service/bundle/SkillSuiteBundleOperationQueryServiceTest.java b/server/skillhub-app/src/test/java/com/iflytek/skillhub/service/bundle/SkillSuiteBundleOperationQueryServiceTest.java index 510b4eae8..7b97f4b7e 100644 --- a/server/skillhub-app/src/test/java/com/iflytek/skillhub/service/bundle/SkillSuiteBundleOperationQueryServiceTest.java +++ b/server/skillhub-app/src/test/java/com/iflytek/skillhub/service/bundle/SkillSuiteBundleOperationQueryServiceTest.java @@ -18,6 +18,7 @@ import com.iflytek.skillhub.domain.suite.bundle.SkillSuiteBundleMode; import com.iflytek.skillhub.domain.suite.bundle.SkillSuiteBundlePublishAction; import com.iflytek.skillhub.domain.suite.bundle.SkillSuiteBundleRelationshipChange; import com.iflytek.skillhub.dto.PageResponse; +import com.iflytek.skillhub.dto.SkillSuiteBundleOperationPageResponse; import com.iflytek.skillhub.dto.SkillSuiteBundleOperationSummaryResponse; import com.iflytek.skillhub.repository.SkillSuiteBundleOperationQueryRepository; import org.junit.jupiter.api.BeforeEach; @@ -148,6 +149,16 @@ class SkillSuiteBundleOperationQueryServiceTest { verify(operationQueryRepository).findActive("actor", 2, 50); } + @Test + void delegatesOperationHistoryPagingToTheReadModel() { + SkillSuiteBundleOperationPageResponse expected = + new SkillSuiteBundleOperationPageResponse(List.of(), 0, 2, 50, true); + when(operationQueryRepository.findMine("actor", 2, 50)).thenReturn(expected); + + assertThat(service.listMine("actor", 2, 100)).isSameAs(expected); + verify(operationQueryRepository).findMine("actor", 2, 50); + } + private SkillSuiteBundleExecutionOperation operation() { return new SkillSuiteBundleExecutionOperation( "operation-1", "preview-1", "request-1", "actor", SkillSuiteBundleMode.CREATE, diff --git a/web/src/api/generated/schema.d.ts b/web/src/api/generated/schema.d.ts index 5649c6d1d..5d42eb883 100644 --- a/web/src/api/generated/schema.d.ts +++ b/web/src/api/generated/schema.d.ts @@ -2742,6 +2742,40 @@ export interface paths { patch?: never; trace?: never; }; + "/api/v1/suite-bundles/operations/mine": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** List current and completed Bundle operations started by the current user */ + get: operations["listMySkillSuiteBundleOperations"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; + "/api/web/suite-bundles/operations/mine": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** List current and completed Bundle operations started by the current user */ + get: operations["listMySkillSuiteBundleOperations_1"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/web/suite-bundles/operations/active": { parameters: { query?: never; @@ -5860,16 +5894,16 @@ export interface components { completedAt?: string; members?: components["schemas"]["OperationMember"][]; }; - ApiResponsePageResponseSkillSuiteBundleOperationSummaryResponse: { + ApiResponseSkillSuiteBundleOperationPageResponse: { /** Format: int32 */ code?: number; msg?: string; - data?: components["schemas"]["PageResponseSkillSuiteBundleOperationSummaryResponse"]; + data?: components["schemas"]["SkillSuiteBundleOperationPageResponse"]; /** Format: date-time */ timestamp?: string; requestId?: string; }; - PageResponseSkillSuiteBundleOperationSummaryResponse: { + SkillSuiteBundleOperationPageResponse: { items?: components["schemas"]["SkillSuiteBundleOperationSummaryResponse"][]; /** Format: int64 */ total?: number; @@ -5877,6 +5911,7 @@ export interface components { page?: number; /** Format: int32 */ size?: number; + hasChangingOperations?: boolean; }; SkillSuiteBundleOperationSummaryResponse: { operationId?: string; @@ -5897,6 +5932,24 @@ export interface components { /** Format: date-time */ updatedAt?: string; }; + ApiResponsePageResponseSkillSuiteBundleOperationSummaryResponse: { + /** Format: int32 */ + code?: number; + msg?: string; + data?: components["schemas"]["PageResponseSkillSuiteBundleOperationSummaryResponse"]; + /** Format: date-time */ + timestamp?: string; + requestId?: string; + }; + PageResponseSkillSuiteBundleOperationSummaryResponse: { + items?: components["schemas"]["SkillSuiteBundleOperationSummaryResponse"][]; + /** Format: int64 */ + total?: number; + /** Format: int32 */ + page?: number; + /** Format: int32 */ + size?: number; + }; ApiResponseSearchResponse: { /** Format: int32 */ code?: number; @@ -12297,6 +12350,52 @@ export interface operations { }; }; }; + listMySkillSuiteBundleOperations: { + parameters: { + query?: { + page?: number; + size?: number; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "*/*": components["schemas"]["ApiResponseSkillSuiteBundleOperationPageResponse"]; + }; + }; + }; + }; + listMySkillSuiteBundleOperations_1: { + parameters: { + query?: { + page?: number; + size?: number; + }; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description OK */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "*/*": components["schemas"]["ApiResponseSkillSuiteBundleOperationPageResponse"]; + }; + }; + }; + }; listActiveSkillSuiteBundleOperations: { parameters: { query?: { diff --git a/web/src/api/types.ts b/web/src/api/types.ts index 860535f9e..d1bbdb444 100644 --- a/web/src/api/types.ts +++ b/web/src/api/types.ts @@ -477,6 +477,11 @@ export type SkillSuiteBundleOperationSummary = RequiredGenerated< components['schemas']['SkillSuiteBundleOperationSummaryResponse'], 'failureCode' | 'baseVersion' > +type GeneratedSkillSuiteBundleOperationPage = components['schemas']['SkillSuiteBundleOperationPageResponse'] +export type SkillSuiteBundleOperationPage = Omit< + RequiredGenerated, + 'items' +> & { items: SkillSuiteBundleOperationSummary[] } // Publish export interface PublishResult { diff --git a/web/src/app/router.tsx b/web/src/app/router.tsx index 5e01de1bf..5ac6995b4 100644 --- a/web/src/app/router.tsx +++ b/web/src/app/router.tsx @@ -121,6 +121,11 @@ const MySuitesPage = createLazyRouteComponent( 'MySuitesPage', dashboardRouteOptions, ) +const SuitePublishingTaskPage = createLazyRouteComponent( + () => import('@/pages/dashboard/suite-publishing-task'), + 'SuitePublishingTaskPage', + dashboardRouteOptions, +) const MyNamespacesPage = createLazyRouteComponent( () => import('@/pages/dashboard/my-namespaces'), 'MyNamespacesPage', @@ -377,9 +382,19 @@ const dashboardSuitesRoute = createRoute({ getParentRoute: () => rootRoute, path: 'dashboard/suites', beforeLoad: requireAuth, + validateSearch: (search: Record): { tab?: 'suites' | 'publishing' } => ({ + tab: search.tab === 'publishing' ? 'publishing' : undefined, + }), component: MySuitesPage, }) +const dashboardSuitePublishingTaskRoute = createRoute({ + getParentRoute: () => rootRoute, + path: 'dashboard/suites/publishing/$operationId', + beforeLoad: requireAuth, + component: SuitePublishingTaskPage, +}) + const dashboardSuiteEditRoute = createRoute({ getParentRoute: () => rootRoute, path: 'dashboard/suites/$namespace/$slug/edit', @@ -611,6 +626,7 @@ const routeTree = rootRoute.addChildren([ dashboardSkillsRoute, dashboardPublishRoute, dashboardSuitesRoute, + dashboardSuitePublishingTaskRoute, dashboardSuiteCreateRoute, dashboardSuiteEditRoute, dashboardSuiteVersionCreateRoute, diff --git a/web/src/features/suite/suite-bundle-import.test.tsx b/web/src/features/suite/suite-bundle-import.test.tsx index 41bdafc3e..aa068d115 100644 --- a/web/src/features/suite/suite-bundle-import.test.tsx +++ b/web/src/features/suite/suite-bundle-import.test.tsx @@ -277,15 +277,9 @@ describe('SuiteBundleImport', () => { expect(firstSignal?.aborted).toBe(true) }) - it('shows redacted progress and exposes retry and non-destructive cancel actions', async () => { + it('opens the dedicated publishing task after confirmation', async () => { mocks.preview.mutateAsync.mockResolvedValue(preview({ members: [] })) mocks.confirm.mutateAsync.mockResolvedValue({ operationId: 'operation-1', status: 'RUNNING' }) - mocks.operation.data = { - operationId: 'operation-1', - status: 'BLOCKED_RETRYABLE', - mode: 'CREATE', - members: [{ position: 0, status: 'FAILED_RETRYABLE', redacted: true }], - } render() fireEvent.click(screen.getByRole('button', { name: 'pick-zip' })) await waitFor(() => expect( @@ -293,93 +287,47 @@ describe('SuiteBundleImport', () => { ).toBe(false)) fireEvent.click(screen.getByRole('button', { name: 'suite.bundle.confirm' })) - await waitFor(() => expect(screen.getByText('suite.bundle.redactedMember')).not.toBeNull()) - fireEvent.click(screen.getByRole('button', { name: /suite.bundle.retry/ })) - fireEvent.click(screen.getByRole('button', { name: 'suite.bundle.cancelOperation' })) - - expect(mocks.retry.mutate).toHaveBeenCalledWith('operation-1', expect.objectContaining({ onError: expect.any(Function) })) - expect(mocks.cancel.mutate).toHaveBeenCalledWith('operation-1', expect.objectContaining({ onError: expect.any(Function) })) - }) - - it('lets the user reload an operation after a status request fails', async () => { - mocks.preview.mutateAsync.mockResolvedValue(preview({ members: [] })) - mocks.confirm.mutateAsync.mockResolvedValue({ operationId: 'operation-1', status: 'RUNNING' }) - mocks.operation.error = new Error('offline') - render() - fireEvent.click(screen.getByRole('button', { name: 'pick-zip' })) - await waitFor(() => expect( - screen.getByRole('button', { name: 'suite.bundle.confirm' }).hasAttribute('disabled') - ).toBe(false)) - fireEvent.click(screen.getByRole('button', { name: 'suite.bundle.confirm' })) - - await waitFor(() => expect(screen.getByRole('button', { name: /suite.bundle.reloadOperation/ })).not.toBeNull()) - fireEvent.click(screen.getByRole('button', { name: /suite.bundle.reloadOperation/ })) - expect(mocks.operation.refetch).toHaveBeenCalledTimes(1) - }) - - it('restores an operation after refresh and can discard a stale recovery entry', async () => { - window.sessionStorage.setItem('skillhub:suite-bundle-operation:CREATE:new', 'operation-restored') - mocks.operation.error = new Error('not found') - - render() - - expect(screen.getByText('operation-restored')).not.toBeNull() - fireEvent.click(screen.getByRole('button', { name: 'suite.bundle.forgetOperation' })) - await waitFor(() => expect(window.sessionStorage.getItem( + await waitFor(() => expect(mocks.navigate).toHaveBeenCalledWith({ + to: '/dashboard/suites/publishing/operation-1', + replace: true, + })) + expect(window.sessionStorage.getItem( 'skillhub:suite-bundle-operation:CREATE:new' - )).toBeNull()) + )).toBeNull() }) - it('links a waiting member to its exact Skill version and shows its package path', () => { - window.sessionStorage.setItem('skillhub:suite-bundle-operation:CREATE:new', 'operation-waiting') + it('opens the dedicated publishing task when a stored operation is restored', async () => { + const key = 'skillhub:suite-bundle-operation:CREATE:new' + window.sessionStorage.setItem(key, 'operation-restored') mocks.operation.data = { - operationId: 'operation-waiting', - status: 'WAITING_FOR_MEMBERS', + operationId: 'operation-restored', + status: 'RUNNING', mode: 'CREATE', - members: [{ - position: 0, - status: 'WAITING_FOR_MEMBER', - redacted: false, - coordinate: '@global/member-under-review', - version: '1.4.0', - visibility: 'PUBLIC', - sourceType: 'PACKAGE', - relationship: 'UPDATED', - publishAction: 'CREATE_VERSION', - packagePath: 'skills/member-under-review', - errors: [], - warnings: [], - }], - } - - render() - expect(screen.getByText('suite.bundle.memberDirectory')).not.toBeNull() - fireEvent.click(screen.getByRole('button', { name: 'suite.bundle.viewMemberReview' })) - - expect(mocks.navigate).toHaveBeenCalledWith({ - to: '/space/global/member-under-review', - search: { version: '1.4.0' }, - }) - }) - - it('opens the exact generated Suite draft from a recovered terminal operation', () => { - window.sessionStorage.setItem('skillhub:suite-bundle-operation:CREATE:new', 'operation-complete') - mocks.operation.data = { - operationId: 'operation-complete', - status: 'SUITE_DRAFT_CREATED', - mode: 'CREATE', - targetCoordinate: '@global/generated-suite', - targetVersion: '1.2.0', + targetCoordinate: '@global/suite', members: [], } render() - fireEvent.click(screen.getByRole('button', { name: 'suite.bundle.openDraft' })) - expect(mocks.navigate).toHaveBeenCalledWith({ - to: '/suite/global/generated-suite', - search: { version: '1.2.0' }, - }) + await waitFor(() => expect(mocks.navigate).toHaveBeenCalledWith({ + to: '/dashboard/suites/publishing/operation-restored', + replace: true, + })) + expect(window.sessionStorage.getItem(key)).toBeNull() + }) + + it('opens the dedicated task when restoring its status fails instead of staying stuck', async () => { + const key = 'skillhub:suite-bundle-operation:CREATE:new' + window.sessionStorage.setItem(key, 'operation-offline') + mocks.operation.error = new Error('offline') + + render() + + await waitFor(() => expect(mocks.navigate).toHaveBeenCalledWith({ + to: '/dashboard/suites/publishing/operation-offline', + replace: true, + })) + expect(window.sessionStorage.getItem(key)).toBeNull() }) it('reads the new Suite recovery key when an UPDATE route changes without a full page reload', async () => { diff --git a/web/src/features/suite/suite-bundle-import.tsx b/web/src/features/suite/suite-bundle-import.tsx index d06011bc7..85214a0e8 100644 --- a/web/src/features/suite/suite-bundle-import.tsx +++ b/web/src/features/suite/suite-bundle-import.tsx @@ -1,15 +1,13 @@ import { useEffect, useRef, useState } from 'react' -import { AlertTriangle, CheckCircle2, FileArchive, RefreshCw, ShieldAlert, XCircle } from 'lucide-react' +import { AlertTriangle, CheckCircle2, FileArchive, ShieldAlert, XCircle } from 'lucide-react' import { useTranslation } from 'react-i18next' import { useNavigate } from '@tanstack/react-router' import type { SkillSuiteBundlePreview } from '@/api/types' import { packageFolderAsZip } from '@/features/publish/folder-zip' import { UploadZone } from '@/features/publish/upload-zone' import { - useCancelSuiteBundleOperation, useConfirmSuiteBundle, usePreviewSuiteBundle, - useRetrySuiteBundleOperation, useSuiteBundleOperation, } from '@/shared/hooks/use-suite-queries' import { Button } from '@/shared/ui/button' @@ -52,11 +50,6 @@ export function rememberSuiteBundleOperation( writeStoredOperation(operationStorageKey(mode, mode === 'UPDATE' ? coordinate : undefined), operationId) } -function splitCoordinate(coordinate?: string): { namespace: string; slug: string } | null { - const match = coordinate?.match(/^@([^/]+)\/(.+)$/) - return match ? { namespace: match[1], slug: match[2] } : null -} - export function SuiteBundleImport({ expectedMode, expectedCoordinate }: { expectedMode: BundleMode expectedCoordinate?: string @@ -66,13 +59,12 @@ export function SuiteBundleImport({ expectedMode, expectedCoordinate }: { const storageKey = operationStorageKey(expectedMode, expectedCoordinate) const previewMutation = usePreviewSuiteBundle() const confirmMutation = useConfirmSuiteBundle() - const cancelMutation = useCancelSuiteBundleOperation() - const retryMutation = useRetrySuiteBundleOperation() const [preview, setPreview] = useState(null) const [fileName, setFileName] = useState('') const [acceptedWarningMembers, setAcceptedWarningMembers] = useState>(() => new Set()) const [removalsAccepted, setRemovalsAccepted] = useState(false) const [operationId, setOperationId] = useState(() => readStoredOperation(storageKey)) + const restoredOperationIdRef = useRef(operationId) const [packaging, setPackaging] = useState(false) const [now, setNow] = useState(() => Date.now()) const requestRef = useRef(null) @@ -95,6 +87,13 @@ export function SuiteBundleImport({ expectedMode, expectedCoordinate }: { setOperationId(undefined) toast.error(t('suite.bundle.operationTargetMismatch')) }, [operation, operationId, operationMatchesTarget, storageKey, t]) + useEffect(() => { + if (!operationId || !operationMatchesTarget) return + if (restoredOperationIdRef.current === operationId && !operation && !operationQuery.error) return + writeStoredOperation(storageKey) + restoredOperationIdRef.current = undefined + void navigate({ to: `/dashboard/suites/publishing/${operationId}`, replace: true }) + }, [navigate, operation, operationId, operationMatchesTarget, operationQuery.error, storageKey]) useEffect(() => { if (!preview) return undefined const timer = window.setInterval(() => setNow(Date.now()), 1_000) @@ -206,133 +205,9 @@ export function SuiteBundleImport({ expectedMode, expectedCoordinate }: { if (!operationMatchesTarget) { return {t('suite.bundle.operationTargetMismatch')} } - const status = operation?.status - const draftCoordinate = splitCoordinate(operation?.targetCoordinate) - const resetOperation = () => { - setOperationId(undefined) - setPreview(null) - setFileName('') - } return ( - -
-
-

{t('suite.bundle.progressTitle')}

-

- {operationQuery.isLoading - ? t('suite.bundle.loadingOperation') - : status - ? t(`suite.bundle.status.${status}`) - : t('suite.bundle.operationLoadFailed')} -

-
- {status ?? 'RUNNING'} -
-

{operationId}

- {operationQuery.error ? ( -
- {t('suite.bundle.operationLoadFailed')} - -
- ) : null} - {operation?.failureCode ? ( -
- {operation.failureCode} -
- ) : null} -
- {(operation?.members ?? []).map((member) => ( -
-
- - {member.redacted ? t('suite.bundle.redactedMember') : member.coordinate} - - {member.status} -
- {!member.redacted ? ( - <> -

- {member.sourceType ? t(`suite.bundle.source.${member.sourceType}`) : null} - {member.relationship ? ` · ${t(`suite.bundle.relationship.${member.relationship}`)}` : null} - {member.publishAction ? ` · ${t(`suite.bundle.action.${member.publishAction}`)}` : null} -

- {member.packagePath ? ( -

- {t('suite.bundle.memberDirectory', { path: member.packagePath })} -

- ) : null} -

- {member.visibility ?? '—'} · v{member.version ?? '—'} -

- {(member.errors ?? []).map((error) =>

{error}

)} - {(member.warnings ?? []).map((warning) =>

{warning}

)} - {member.coordinate && member.version && member.status === 'WAITING_FOR_MEMBER' ? ( - - ) : null} - - ) : null} -
- ))} -
-
- {status === 'BLOCKED_RETRYABLE' ? ( - - ) : null} - {status !== 'CANCELLED' && status !== 'REPREVIEW_REQUIRED' && status !== 'SUITE_DRAFT_CREATED' ? ( - - ) : null} - {status === 'REPREVIEW_REQUIRED' || status === 'CANCELLED' ? ( - - ) : null} - {operationQuery.error ? ( - - ) : null} - {status === 'SUITE_DRAFT_CREATED' && draftCoordinate && operation?.targetVersion ? ( - <> - - - - ) : null} -
+ + {t('suite.bundle.openingTask')} ) } diff --git a/web/src/features/suite/suite-bundle-operation-detail.test.tsx b/web/src/features/suite/suite-bundle-operation-detail.test.tsx new file mode 100644 index 000000000..1a74ff604 --- /dev/null +++ b/web/src/features/suite/suite-bundle-operation-detail.test.tsx @@ -0,0 +1,111 @@ +/** @vitest-environment jsdom */ + +import { cleanup, fireEvent, render, screen } from '@testing-library/react' +import { afterEach, describe, expect, it, vi } from 'vitest' +import { SuiteBundleOperationDetail } from './suite-bundle-operation-detail' + +const mocks = vi.hoisted(() => ({ + navigate: vi.fn(), + cancel: { mutate: vi.fn(), isPending: false }, + retry: { mutate: vi.fn(), isPending: false }, + operation: { + data: undefined as Record | undefined, + isLoading: false, + error: null as Error | null, + refetch: vi.fn(), + }, +})) + +vi.mock('@tanstack/react-router', () => ({ useNavigate: () => mocks.navigate })) +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'zh-CN' } }), +})) +vi.mock('@/shared/hooks/use-suite-queries', () => ({ + useSuiteBundleOperation: () => mocks.operation, + useCancelSuiteBundleOperation: () => mocks.cancel, + useRetrySuiteBundleOperation: () => mocks.retry, +})) + +describe('SuiteBundleOperationDetail', () => { + afterEach(() => { + cleanup() + vi.clearAllMocks() + mocks.operation.data = undefined + mocks.operation.error = null + }) + + it('explains cancellation before stopping Suite creation', () => { + mocks.operation.data = { + operationId: 'operation-1', + status: 'WAITING_FOR_MEMBERS', + mode: 'CREATE', + targetCoordinate: '@global/care-suite', + targetVersion: '1.0.0', + updatedAt: '2026-09-14T04:00:00Z', + members: [], + } + + render() + fireEvent.click(screen.getByRole('button', { name: 'suite.bundle.cancelOperation' })) + + expect(screen.getByText('suite.bundle.cancelConfirmDescription')).not.toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'suite.bundle.cancelConfirmAction' })) + expect(mocks.cancel.mutate).toHaveBeenCalledWith( + 'operation-1', + expect.objectContaining({ onSuccess: expect.any(Function), onError: expect.any(Function) }), + ) + }) + + it('keeps the review link available for a created member version after cancellation', () => { + mocks.operation.data = { + operationId: 'operation-1', + status: 'CANCELLED', + mode: 'CREATE', + targetCoordinate: '@global/care-suite', + targetVersion: '1.0.0', + updatedAt: '2026-09-14T04:00:00Z', + members: [{ + position: 0, + redacted: false, + coordinate: '@global/member-under-review', + status: 'CANCELLED', + version: '1.4.0', + skillVersionId: 42, + sourceType: 'PACKAGE', + relationship: 'ADDED', + publishAction: 'CREATE_VERSION', + visibility: 'PUBLIC', + errors: [], + warnings: [], + }], + } + + render() + + expect(screen.getByText('suite.bundle.cancelledDescription')).not.toBeNull() + fireEvent.click(screen.getByRole('button', { name: 'suite.bundle.viewMemberReview' })) + expect(mocks.navigate).toHaveBeenCalledWith({ + to: '/space/global/member-under-review', + search: { version: '1.4.0' }, + }) + }) + + it('opens the generated Suite draft when publishing completes', () => { + mocks.operation.data = { + operationId: 'operation-2', + status: 'SUITE_DRAFT_CREATED', + mode: 'CREATE', + targetCoordinate: '@global/generated-suite', + targetVersion: '1.2.0', + updatedAt: '2026-09-14T04:00:00Z', + members: [], + } + + render() + fireEvent.click(screen.getByRole('button', { name: 'suite.bundle.openDraft' })) + expect(mocks.navigate).toHaveBeenCalledWith({ + to: '/suite/global/generated-suite', + search: { version: '1.2.0' }, + }) + }) +}) diff --git a/web/src/features/suite/suite-bundle-operation-detail.tsx b/web/src/features/suite/suite-bundle-operation-detail.tsx new file mode 100644 index 000000000..5aeeff454 --- /dev/null +++ b/web/src/features/suite/suite-bundle-operation-detail.tsx @@ -0,0 +1,266 @@ +import { useState } from 'react' +import { useNavigate } from '@tanstack/react-router' +import { AlertTriangle, Check, Circle, Clock3, RefreshCw, Square } from 'lucide-react' +import { useTranslation } from 'react-i18next' +import { ConfirmDialog } from '@/shared/components/confirm-dialog' +import { formatLocalDateTime } from '@/shared/lib/date-time' +import { toast } from '@/shared/lib/toast' +import { cn } from '@/shared/lib/utils' +import { + useCancelSuiteBundleOperation, + useRetrySuiteBundleOperation, + useSuiteBundleOperation, +} from '@/shared/hooks/use-suite-queries' +import { Button } from '@/shared/ui/button' +import { Card } from '@/shared/ui/card' + +const TERMINAL_STATUSES = new Set(['CANCELLED', 'REPREVIEW_REQUIRED', 'SUITE_DRAFT_CREATED']) + +function splitCoordinate(coordinate?: string): { namespace: string; slug: string } | null { + const match = coordinate?.match(/^@([^/]+)\/(.+)$/) + return match ? { namespace: match[1], slug: match[2] } : null +} + +export function SuiteBundleOperationDetail({ operationId }: { operationId: string }) { + const { t, i18n } = useTranslation() + const navigate = useNavigate() + const operationQuery = useSuiteBundleOperation(operationId) + const cancelMutation = useCancelSuiteBundleOperation() + const retryMutation = useRetrySuiteBundleOperation() + const [cancelOpen, setCancelOpen] = useState(false) + const operation = operationQuery.data + const status = operation?.status + const draftCoordinate = splitCoordinate(operation?.targetCoordinate) + const canCancel = Boolean(status && !TERMINAL_STATUSES.has(status)) + const memberStageComplete = status === 'SUITE_DRAFT_CREATED' + const memberStageActive = status === 'RUNNING' || status === 'WAITING_FOR_MEMBERS' + || status === 'BLOCKED_RETRYABLE' + + return ( +
+ +
+
+

+ {operation?.targetCoordinate ?? t('suite.bundle.loadingOperation')} + {operation?.targetVersion ? `@${operation.targetVersion}` : ''} +

+

+ {status ? t(`suite.bundle.status.${status}`) : t('suite.bundle.loadingOperation')} +

+
+ {status ? ( + + {t(`suite.bundle.statusLabel.${status}`)} + + ) : null} +
+ +
    + } + title={t('suite.bundle.lifecycle.preview')} + description={t('suite.bundle.lifecycle.previewDescription')} + state="complete" + /> + : } + title={t('suite.bundle.lifecycle.members')} + description={t('suite.bundle.lifecycle.membersDescription')} + state={memberStageComplete ? 'complete' : memberStageActive ? 'active' : 'inactive'} + /> + : } + title={t('suite.bundle.lifecycle.draft')} + description={t('suite.bundle.lifecycle.draftDescription')} + state={memberStageComplete ? 'complete' : 'inactive'} + /> +
+ +
+
+

{t('suite.bundle.operationId')}

+

{operationId}

+
+
+

{t('suite.bundle.lastUpdated')}

+

+ {operation?.updatedAt ? formatLocalDateTime(operation.updatedAt, i18n.language) : '—'} +

+
+
+
+ + {operationQuery.error ? ( + + {t('suite.bundle.operationLoadFailed')} + + + ) : null} + + {status === 'CANCELLED' ? ( +
+
+ ) : null} + + {operation?.failureCode ? ( +
+ + {operation.failureCode} +
+ ) : null} + + +
+

{t('suite.bundle.memberTitle')}

+

{t('suite.bundle.memberDescription')}

+
+
+ {(operation?.members ?? []).map((member) => { + const memberCoordinate = splitCoordinate(member.coordinate) + const canViewVersion = !member.redacted && memberCoordinate && member.version && member.skillVersionId + return ( +
+
+
+

+ {member.redacted ? t('suite.bundle.redactedMember') : member.coordinate} +

+ {!member.redacted ? ( +

+ {member.sourceType ? t(`suite.bundle.source.${member.sourceType}`) : null} + {member.relationship ? ` · ${t(`suite.bundle.relationship.${member.relationship}`)}` : null} + {member.publishAction ? ` · ${t(`suite.bundle.action.${member.publishAction}`)}` : null} +

+ ) : null} +
+ + {t(`suite.bundle.memberStatus.${member.status}`)} + +
+ {!member.redacted ? ( + <> + {member.packagePath ? ( +

+ {t('suite.bundle.memberDirectory', { path: member.packagePath })} +

+ ) : null} +

+ {member.visibility ?? '—'} · v{member.version ?? '—'} +

+ {(member.errors ?? []).map((error) =>

{error}

)} + {(member.warnings ?? []).map((warning) =>

{warning}

)} + {canViewVersion ? ( + + ) : null} + + ) : null} +
+ ) + })} + {!operationQuery.isLoading && (operation?.members?.length ?? 0) === 0 ? ( +

{t('suite.bundle.noMembers')}

+ ) : null} +
+
+ +
+ {status === 'BLOCKED_RETRYABLE' ? ( + + ) : null} + {canCancel ? ( + + ) : null} + {status === 'REPREVIEW_REQUIRED' || status === 'CANCELLED' ? ( + + ) : null} + {status === 'SUITE_DRAFT_CREATED' && draftCoordinate && operation?.targetVersion ? ( + + ) : null} +
+ + cancelMutation.mutate(operationId, { + onSuccess: () => setCancelOpen(false), + onError: (error) => toast.error(t('suite.bundle.cancelFailed'), error.message), + })} + /> +
+ ) +} + +function LifecycleStep({ icon, title, description, state }: { + icon: React.ReactNode + title: string + description: string + state: 'complete' | 'active' | 'inactive' +}) { + return ( +
  • + + {icon} + +
    +

    {title}

    +

    {description}

    +
    +
  • + ) +} diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 31a5bcff5..764ffaf73 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -1998,6 +1998,10 @@ "authoringMode": "Suite authoring method", "manualAuthoring": "Compose manually", "localImport": "Import locally", + "tabs": { + "suites": "Skill Suites", + "publishing": "Publishing tasks" + }, "bundle": { "uploadTitle": "Upload a Suite Bundle", "uploadDescription": "Choose one ZIP or a root folder containing SUITE.yaml and multiple Skill folders. The browser creates and uploads one ZIP only.", @@ -2034,15 +2038,71 @@ "openDraft": "Open Suite draft", "retry": "Retry unfinished work", "retryFailed": "Failed to retry the Bundle operation", - "cancelOperation": "Cancel remaining work", + "cancelOperation": "Stop creating Suite", "cancelFailed": "Failed to cancel the Bundle operation", + "openingTask": "Opening the publishing task…", + "taskListTitle": "Suite publishing tasks", + "taskListDescription": "Review tasks that need attention, are in progress, or recently finished.", + "taskDetailTitle": "Suite publishing task", + "taskDetailDescription": "Track member publishing and Suite draft creation outside the authoring page.", + "backToTasks": "Back to publishing tasks", + "taskEmpty": "No publishing tasks", + "taskEmptyDescription": "Publishing progress appears here after you import and confirm a Suite Bundle.", + "groups": { + "attention": "Needs attention", + "attentionDescription": "Blocked or requires a new preview", + "attentionEmpty": "No tasks currently need attention.", + "progress": "In progress", + "progressDescription": "Processing member Skills or waiting for review", + "progressEmpty": "No tasks are currently in progress.", + "recent": "Recently finished", + "recentDescription": "Drafts created or tasks stopped", + "recentEmpty": "No recently finished tasks." + }, + "statusLabel": { + "RUNNING": "Processing", + "WAITING_FOR_MEMBERS": "Waiting for members", + "BLOCKED_RETRYABLE": "Needs attention", + "REPREVIEW_REQUIRED": "New preview required", + "SUITE_DRAFT_CREATED": "Draft created", + "CANCELLED": "Stopped" + }, + "lifecycleTitle": "Suite publishing stages", + "lifecycle": { + "preview": "Confirm changes", + "previewDescription": "The upload and member changes are locked", + "members": "Publish members", + "membersDescription": "Create or reuse Skill versions and wait for review", + "draft": "Create Suite draft", + "draftDescription": "Runs only after every member is ready" + }, + "operationId": "Task ID", + "lastUpdated": "Last updated", + "memberTitle": "Member Skills", + "memberDescription": "Each member follows the existing scan and review workflow.", + "memberStatus": { + "PLANNED": "Planned", + "RUNNING": "Processing", + "WAITING_FOR_MEMBER": "Waiting for scan or review", + "COMPLETED": "Ready", + "BLOCKED_RETRYABLE": "Retryable block", + "REPREVIEW_REQUIRED": "New preview required", + "CANCELLED": "Further work stopped" + }, + "noMembers": "No member progress yet.", + "cancelConfirmTitle": "Stop creating this Suite?", + "cancelConfirmDescription": "SkillHub will stop waiting for members and will not create the Suite draft. Skill versions and review tasks already created remain available and are not withdrawn.", + "cancelConfirmAction": "Stop creating Suite", + "cancelledTitle": "Suite creation stopped", + "cancelledDescription": "This task remains in history. Existing Skill versions and review tasks are not withdrawn or deleted.", + "startAgain": "Import Bundle again", "status": { "RUNNING": "Member skills are being processed.", "WAITING_FOR_MEMBERS": "Waiting for member scans or reviews.", "BLOCKED_RETRYABLE": "A recoverable condition blocked progress. Retry after it is resolved.", "REPREVIEW_REQUIRED": "The plan or permissions changed. Upload and preview the Bundle again.", "SUITE_DRAFT_CREATED": "Members are ready and the Suite draft was created.", - "CANCELLED": "The operation was cancelled. Existing Skill versions were not deleted." + "CANCELLED": "Suite creation was stopped. Existing Skill versions were not deleted." }, "relationship": { "ADDED": "Add member", diff --git a/web/src/i18n/locales/ru.json b/web/src/i18n/locales/ru.json index 143e736d9..7cffae9b3 100644 --- a/web/src/i18n/locales/ru.json +++ b/web/src/i18n/locales/ru.json @@ -1995,6 +1995,10 @@ "authoringMode": "Способ создания набора", "manualAuthoring": "Собрать вручную", "localImport": "Импортировать локально", + "tabs": { + "suites": "Наборы навыков", + "publishing": "Задачи публикации" + }, "bundle": { "uploadTitle": "Загрузить Suite Bundle", "uploadDescription": "Выберите ZIP или корневую папку с SUITE.yaml и папками Skill. Браузер создаст и загрузит только один ZIP.", @@ -2031,15 +2035,71 @@ "openDraft": "Открыть черновик набора", "retry": "Повторить незавершённую работу", "retryFailed": "Не удалось повторить операцию Bundle", - "cancelOperation": "Отменить оставшуюся работу", + "cancelOperation": "Остановить создание набора", "cancelFailed": "Не удалось отменить операцию Bundle", + "openingTask": "Открывается задача публикации…", + "taskListTitle": "Задачи публикации наборов", + "taskListDescription": "Задачи, требующие внимания, выполняемые и недавно завершённые.", + "taskDetailTitle": "Задача публикации набора", + "taskDetailDescription": "Отслеживайте публикацию участников и создание черновика отдельно от страницы создания.", + "backToTasks": "К задачам публикации", + "taskEmpty": "Нет задач публикации", + "taskEmptyDescription": "Прогресс появится здесь после импорта и подтверждения Suite Bundle.", + "groups": { + "attention": "Требуют внимания", + "attentionDescription": "Заблокированы или требуют нового предпросмотра", + "attentionEmpty": "Нет задач, требующих внимания.", + "progress": "Выполняются", + "progressDescription": "Обработка навыков или ожидание проверки", + "progressEmpty": "Нет выполняемых задач.", + "recent": "Недавно завершены", + "recentDescription": "Черновик создан или задача остановлена", + "recentEmpty": "Нет недавно завершённых задач." + }, + "statusLabel": { + "RUNNING": "Обработка", + "WAITING_FOR_MEMBERS": "Ожидание участников", + "BLOCKED_RETRYABLE": "Требует внимания", + "REPREVIEW_REQUIRED": "Нужен новый предпросмотр", + "SUITE_DRAFT_CREATED": "Черновик создан", + "CANCELLED": "Остановлено" + }, + "lifecycleTitle": "Этапы публикации набора", + "lifecycle": { + "preview": "Подтвердить изменения", + "previewDescription": "Загрузка и изменения участников зафиксированы", + "members": "Опубликовать участников", + "membersDescription": "Создать или использовать версии навыков и дождаться проверки", + "draft": "Создать черновик набора", + "draftDescription": "Выполняется после готовности всех участников" + }, + "operationId": "ID задачи", + "lastUpdated": "Последнее обновление", + "memberTitle": "Навыки-участники", + "memberDescription": "Каждый участник проходит существующий процесс сканирования и проверки.", + "memberStatus": { + "PLANNED": "Запланировано", + "RUNNING": "Обработка", + "WAITING_FOR_MEMBER": "Ожидание сканирования или проверки", + "COMPLETED": "Готово", + "BLOCKED_RETRYABLE": "Можно повторить", + "REPREVIEW_REQUIRED": "Нужен новый предпросмотр", + "CANCELLED": "Дальнейшая работа остановлена" + }, + "noMembers": "Нет прогресса участников.", + "cancelConfirmTitle": "Остановить создание набора?", + "cancelConfirmDescription": "SkillHub перестанет ждать участников и не создаст черновик набора. Уже созданные версии навыков и задачи проверки останутся и не будут отозваны.", + "cancelConfirmAction": "Остановить создание набора", + "cancelledTitle": "Создание набора остановлено", + "cancelledDescription": "Задача сохранена в истории. Созданные версии навыков и проверки не отзываются и не удаляются.", + "startAgain": "Импортировать Bundle снова", "status": { "RUNNING": "Навыки обрабатываются.", "WAITING_FOR_MEMBERS": "Ожидание проверки участников.", "BLOCKED_RETRYABLE": "Работа остановлена восстановимой причиной. После устранения можно повторить.", "REPREVIEW_REQUIRED": "План или права изменились. Загрузите Bundle и выполните предпросмотр снова.", "SUITE_DRAFT_CREATED": "Участники готовы, черновик набора создан.", - "CANCELLED": "Операция отменена. Созданные версии Skill не удалены." + "CANCELLED": "Создание Suite остановлено. Созданные версии Skill не удалены." }, "relationship": { "ADDED": "Добавить участника", diff --git a/web/src/i18n/locales/zh.json b/web/src/i18n/locales/zh.json index e1df0cad9..a8c2bda53 100644 --- a/web/src/i18n/locales/zh.json +++ b/web/src/i18n/locales/zh.json @@ -1997,6 +1997,10 @@ "authoringMode": "套件创建方式", "manualAuthoring": "手工组合", "localImport": "本地导入", + "tabs": { + "suites": "技能套件", + "publishing": "发布任务" + }, "bundle": { "uploadTitle": "上传 Suite Bundle", "uploadDescription": "选择一个 ZIP,或选择包含 SUITE.yaml 和多个 Skill 文件夹的根目录。浏览器只会生成并上传一个 ZIP。", @@ -2033,15 +2037,71 @@ "openDraft": "打开套件草稿", "retry": "重试未完成工作", "retryFailed": "重试 Bundle 操作失败", - "cancelOperation": "取消后续处理", + "cancelOperation": "停止创建套件", "cancelFailed": "取消 Bundle 操作失败", + "openingTask": "正在打开独立发布任务页面…", + "taskListTitle": "套件发布任务", + "taskListDescription": "集中查看需要处理、正在推进和最近完成的 Bundle 发布记录。", + "taskDetailTitle": "套件发布任务", + "taskDetailDescription": "跟踪成员技能发布与套件草稿创建,不会跳回创建页面。", + "backToTasks": "返回发布任务", + "taskEmpty": "暂无发布任务", + "taskEmptyDescription": "从本地导入 Suite Bundle 并确认后,发布进度会显示在这里。", + "groups": { + "attention": "需要处理", + "attentionDescription": "存在阻塞或需要重新预览", + "attentionEmpty": "当前没有需要处理的任务。", + "progress": "进行中", + "progressDescription": "正在处理成员技能或等待审核", + "progressEmpty": "当前没有进行中的任务。", + "recent": "最近完成", + "recentDescription": "已创建草稿或已停止的记录", + "recentEmpty": "暂无最近完成的任务。" + }, + "statusLabel": { + "RUNNING": "处理中", + "WAITING_FOR_MEMBERS": "等待成员", + "BLOCKED_RETRYABLE": "需要处理", + "REPREVIEW_REQUIRED": "需要重新预览", + "SUITE_DRAFT_CREATED": "草稿已创建", + "CANCELLED": "已停止" + }, + "lifecycleTitle": "套件发布阶段", + "lifecycle": { + "preview": "确认差异", + "previewDescription": "已锁定本次上传与成员变更", + "members": "推进成员发布", + "membersDescription": "创建或复用技能版本并等待审核", + "draft": "创建套件草稿", + "draftDescription": "仅在所有成员就绪后执行" + }, + "operationId": "任务 ID", + "lastUpdated": "最近更新", + "memberTitle": "成员技能", + "memberDescription": "每个成员独立走现有扫描与审核流程。", + "memberStatus": { + "PLANNED": "待处理", + "RUNNING": "处理中", + "WAITING_FOR_MEMBER": "等待扫描或审核", + "COMPLETED": "已就绪", + "BLOCKED_RETRYABLE": "可重试阻塞", + "REPREVIEW_REQUIRED": "需要重新预览", + "CANCELLED": "已停止后续处理" + }, + "noMembers": "暂无成员进度。", + "cancelConfirmTitle": "停止创建这个套件?", + "cancelConfirmDescription": "停止后,SkillHub 不再等待成员或创建套件草稿。已经创建的技能版本和已经提交的审核任务不会撤回,仍可在技能审核中继续处理。", + "cancelConfirmAction": "停止创建套件", + "cancelledTitle": "套件创建已停止", + "cancelledDescription": "任务记录会保留。已创建的技能版本和审核任务仍然存在,不会自动撤回或删除。", + "startAgain": "重新导入 Bundle", "status": { "RUNNING": "正在处理成员技能。", "WAITING_FOR_MEMBERS": "正在等待成员扫描或审核。", "BLOCKED_RETRYABLE": "遇到可恢复阻塞,可以在条件恢复后重试。", "REPREVIEW_REQUIRED": "计划或权限已经变化,必须重新上传并预览。", "SUITE_DRAFT_CREATED": "成员已就绪,套件草稿已创建。", - "CANCELLED": "操作已取消;已创建的技能版本不会被删除。" + "CANCELLED": "套件创建已停止;已创建的技能版本不会被删除。" }, "relationship": { "ADDED": "新增成员", diff --git a/web/src/pages/dashboard/my-suites.test.tsx b/web/src/pages/dashboard/my-suites.test.tsx index 42d721805..5774c28f2 100644 --- a/web/src/pages/dashboard/my-suites.test.tsx +++ b/web/src/pages/dashboard/my-suites.test.tsx @@ -2,122 +2,131 @@ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react' import { afterEach, describe, expect, it, vi } from 'vitest' -import type { PagedResponse, SkillSuiteBundleOperationSummary } from '@/api/types' +import type { SkillSuiteBundleOperationPage, SkillSuiteBundleOperationSummary } from '@/api/types' import { MySuitesPage } from './my-suites' const mocks = vi.hoisted(() => ({ navigate: vi.fn(), - remember: vi.fn(), - activeHook: vi.fn(), - active: { items: [], total: 0, page: 0, size: 12 } as PagedResponse, + search: { tab: 'publishing' as 'publishing' | undefined }, + suiteHook: vi.fn(), + operationHook: vi.fn(), + operations: { + items: [], total: 0, page: 0, size: 12, hasChangingOperations: false, + } as SkillSuiteBundleOperationPage, })) -vi.mock('@tanstack/react-router', () => ({ useNavigate: () => mocks.navigate })) -vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) })) -vi.mock('@/features/suite/suite-bundle-import', () => ({ - rememberSuiteBundleOperation: mocks.remember, +vi.mock('@tanstack/react-router', () => ({ + useNavigate: () => mocks.navigate, + useSearch: () => mocks.search, +})) +vi.mock('react-i18next', () => ({ + useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'zh-CN' } }), })) vi.mock('@/shared/hooks/use-suite-queries', () => ({ - useMySuites: () => ({ data: { items: [], total: 0, page: 0, size: 12 }, isLoading: false }), - useActiveSuiteBundleOperations: (page: number) => { - mocks.activeHook(page) - return { data: mocks.active, isLoading: false } + useMySuites: (...args: unknown[]) => { + mocks.suiteHook(...args) + return { data: { items: [], total: 0, page: 0, size: 12 }, isLoading: false } + }, + useMySuiteBundleOperations: (page: number, size: number, enabled: boolean) => { + mocks.operationHook(page, size, enabled) + return { data: mocks.operations, isLoading: false } }, })) -describe('MySuitesPage', () => { +function operation( + operationId: string, + status: SkillSuiteBundleOperationSummary['status'], +): SkillSuiteBundleOperationSummary { + return { + operationId, + mode: 'CREATE', + targetCoordinate: `@global/${operationId}`, + targetVersion: '1.0.0', + status, + failureCode: undefined, + baseVersion: undefined, + totalMembers: 2, + completedMembers: status === 'SUITE_DRAFT_CREATED' ? 2 : 1, + waitingMembers: status === 'WAITING_FOR_MEMBERS' ? 1 : 0, + updatedAt: '2026-09-14T04:00:00Z', + } +} + +describe('MySuitesPage publishing tasks', () => { afterEach(() => { cleanup() vi.clearAllMocks() - mocks.active = { items: [], total: 0, page: 0, size: 12 } + mocks.search = { tab: 'publishing' } + mocks.operations = { + items: [], total: 0, page: 0, size: 12, hasChangingOperations: false, + } }) - it('shows an active Bundle before its Suite draft exists and restores its progress', () => { - mocks.active = { - items: [{ - operationId: 'operation-1', - mode: 'CREATE', - targetCoordinate: '@global/waiting-suite', - targetVersion: '1.0.0', - status: 'WAITING_FOR_MEMBERS', - failureCode: undefined, - baseVersion: undefined, - totalMembers: 2, - completedMembers: 1, - waitingMembers: 1, - updatedAt: '2026-09-14T04:00:00Z', - }], + it('groups attention, in-progress, completed and cancelled tasks without a spinner', () => { + mocks.operations = { + items: [ + operation('blocked', 'BLOCKED_RETRYABLE'), + operation('waiting', 'WAITING_FOR_MEMBERS'), + operation('draft', 'SUITE_DRAFT_CREATED'), + operation('cancelled', 'CANCELLED'), + ], + total: 4, + page: 0, + size: 12, + hasChangingOperations: true, + } + + const { container } = render() + + expect(screen.getByText('suite.bundle.groups.attention')).not.toBeNull() + expect(screen.getByText('suite.bundle.groups.progress')).not.toBeNull() + expect(screen.getByText('suite.bundle.groups.recent')).not.toBeNull() + expect(screen.getByText('@global/cancelled@1.0.0')).not.toBeNull() + expect(container.querySelector('.animate-spin')).toBeNull() + expect(mocks.suiteHook).toHaveBeenCalledWith('', 0, 12, false) + expect(mocks.operationHook).toHaveBeenCalledWith(0, 12, true) + }) + + it('opens a dedicated task detail instead of a Suite creation page', () => { + mocks.operations = { + items: [operation('waiting', 'WAITING_FOR_MEMBERS')], total: 1, page: 0, size: 12, + hasChangingOperations: true, } render() + fireEvent.click(screen.getByRole('button', { name: /@global\/waiting@1.0.0/ })) - expect(screen.getByText('@global/waiting-suite@1.0.0')).not.toBeNull() - expect(screen.getByText('suite.bundle.status.WAITING_FOR_MEMBERS')).not.toBeNull() - fireEvent.click(screen.getByRole('button', { name: 'suite.bundle.continueOperation' })) - expect(mocks.remember).toHaveBeenCalledWith('CREATE', '@global/waiting-suite', 'operation-1') - expect(mocks.navigate).toHaveBeenCalledWith({ to: '/dashboard/suites/new' }) - }) - - it('restores an UPDATE operation against its frozen base version', () => { - mocks.active = { - items: [{ - operationId: 'operation-2', - mode: 'UPDATE', - targetCoordinate: '@team-ai/care-suite', - targetVersion: '1.1.0', - status: 'BLOCKED_RETRYABLE', - failureCode: 'TEMPORARY_STORAGE_FAILURE', - baseVersion: '1.0.0', - totalMembers: 3, - completedMembers: 2, - waitingMembers: 0, - updatedAt: '2026-09-14T05:00:00Z', - }], - total: 1, - page: 0, - size: 12, - } - - render() - fireEvent.click(screen.getByRole('button', { name: 'suite.bundle.continueOperation' })) - - expect(mocks.remember).toHaveBeenCalledWith('UPDATE', '@team-ai/care-suite', 'operation-2') expect(mocks.navigate).toHaveBeenCalledWith({ - to: '/dashboard/suites/team-ai/care-suite/new-version', - search: { sourceVersion: '1.0.0' }, + to: '/dashboard/suites/publishing/waiting', }) }) - it('returns to the previous active page when the last page becomes empty', async () => { - mocks.active = { - items: [{ - operationId: 'operation-13', - mode: 'CREATE', - targetCoordinate: '@global/suite-13', - targetVersion: '1.0.0', - status: 'WAITING_FOR_MEMBERS', - failureCode: undefined, - baseVersion: undefined, - totalMembers: 1, - completedMembers: 0, - waitingMembers: 1, - updatedAt: '2026-09-14T06:00:00Z', - }], + it('keeps the publishing tab in the URL and returns to a valid task page', async () => { + mocks.operations = { + items: [operation('task-13', 'WAITING_FOR_MEMBERS')], total: 13, page: 0, size: 12, + hasChangingOperations: true, } const view = render() fireEvent.click(screen.getByRole('button', { name: 'pagination.next' })) - expect(mocks.activeHook).toHaveBeenCalledWith(1) + expect(mocks.operationHook).toHaveBeenCalledWith(1, 12, true) - mocks.active = { items: [], total: 12, page: 1, size: 12 } + mocks.operations = { + items: [], total: 12, page: 1, size: 12, hasChangingOperations: false, + } view.rerender() + await waitFor(() => expect(mocks.operationHook).toHaveBeenLastCalledWith(0, 12, true)) - await waitFor(() => expect(mocks.activeHook).toHaveBeenLastCalledWith(0)) - expect(screen.getByRole('button', { name: 'pagination.next' })).not.toBeNull() + fireEvent.click(screen.getByRole('tab', { name: 'suite.tabs.suites' })) + expect(mocks.navigate).toHaveBeenCalledWith({ + to: '/dashboard/suites', + search: { tab: undefined }, + replace: true, + }) }) }) diff --git a/web/src/pages/dashboard/my-suites.tsx b/web/src/pages/dashboard/my-suites.tsx index 777a8c043..a2172be0c 100644 --- a/web/src/pages/dashboard/my-suites.tsx +++ b/web/src/pages/dashboard/my-suites.tsx @@ -1,45 +1,48 @@ -import { useEffect, useState } from 'react' -import { useNavigate } from '@tanstack/react-router' +import { useEffect, useState, type ReactNode } from 'react' +import { useNavigate, useSearch } from '@tanstack/react-router' import { useTranslation } from 'react-i18next' -import { AlertTriangle, Boxes, Loader2 } from 'lucide-react' -import { useActiveSuiteBundleOperations, useMySuites } from '@/shared/hooks/use-suite-queries' +import { AlertTriangle, Boxes, CheckCircle2, ChevronRight, CircleDot, Clock3, Square } from 'lucide-react' +import type { SkillSuiteBundleOperationSummary } from '@/api/types' +import { useMySuiteBundleOperations, useMySuites } from '@/shared/hooks/use-suite-queries' import { DashboardPageHeader } from '@/shared/components/dashboard-page-header' import { EmptyState } from '@/shared/components/empty-state' import { Pagination } from '@/shared/components/pagination' +import { formatLocalDateTime } from '@/shared/lib/date-time' import { Button } from '@/shared/ui/button' import { Card } from '@/shared/ui/card' import { Input } from '@/shared/ui/input' +import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/shared/ui/tabs' import { suiteStatusLabel } from '@/features/suite/suite-labels' -import { rememberSuiteBundleOperation } from '@/features/suite/suite-bundle-import' const PAGE_SIZE = 12 +const NEEDS_ATTENTION = new Set(['BLOCKED_RETRYABLE', 'REPREVIEW_REQUIRED']) +const IN_PROGRESS = new Set(['RUNNING', 'WAITING_FOR_MEMBERS']) export function MySuitesPage() { - const { t } = useTranslation() + const { t, i18n } = useTranslation() const navigate = useNavigate() + const search = useSearch({ from: '/dashboard/suites' }) + const activeTab = search.tab ?? 'suites' const [query, setQuery] = useState('') const [page, setPage] = useState(0) - const [activePage, setActivePage] = useState(0) - const { data, isLoading } = useMySuites(query.trim(), page, PAGE_SIZE) - const { data: activeOperations, isLoading: isLoadingOperations } = - useActiveSuiteBundleOperations(activePage, PAGE_SIZE) - const activeTotalPages = Math.max(1, Math.ceil((activeOperations?.total ?? 0) / PAGE_SIZE)) + const [taskPage, setTaskPage] = useState(0) + const { data, isLoading } = useMySuites(query.trim(), page, PAGE_SIZE, activeTab === 'suites') + const { data: operations, isLoading: isLoadingOperations } = useMySuiteBundleOperations( + taskPage, + PAGE_SIZE, + activeTab === 'publishing', + ) + const taskTotalPages = Math.max(1, Math.ceil((operations?.total ?? 0) / PAGE_SIZE)) useEffect(() => { - if (activePage >= activeTotalPages) setActivePage(activeTotalPages - 1) - }, [activePage, activeTotalPages]) + if (taskPage >= taskTotalPages) setTaskPage(taskTotalPages - 1) + }, [taskPage, taskTotalPages]) - const continueOperation = (operation: NonNullable['items'][number]) => { - rememberSuiteBundleOperation(operation.mode, operation.targetCoordinate, operation.operationId) - const coordinate = operation.targetCoordinate.match(/^@([^/]+)\/(.+)$/) - if (operation.mode === 'UPDATE' && coordinate) { - navigate({ - to: `/dashboard/suites/${coordinate[1]}/${encodeURIComponent(coordinate[2])}/new-version`, - search: { sourceVersion: operation.baseVersion }, - }) - return - } - navigate({ to: '/dashboard/suites/new' }) + const groups = { + attention: operations?.items.filter(operation => NEEDS_ATTENTION.has(operation.status)) ?? [], + progress: operations?.items.filter(operation => IN_PROGRESS.has(operation.status)) ?? [], + recent: operations?.items.filter(operation => + !NEEDS_ATTENTION.has(operation.status) && !IN_PROGRESS.has(operation.status)) ?? [], } return ( @@ -49,98 +52,173 @@ export function MySuitesPage() { subtitle={t('suite.myDescription')} actions={} /> - { - setQuery(event.target.value) - setPage(0) - }} - /> - {isLoadingOperations ? ( -
    - ) : activeOperations?.total ? ( -
    + navigate({ + to: '/dashboard/suites', + search: { tab: tab === 'publishing' ? 'publishing' : undefined }, + replace: true, + })} + className="space-y-6" + > + + {t('suite.tabs.suites')} + {t('suite.tabs.publishing')} + + + + { + setQuery(event.target.value) + setPage(0) + }} + /> + {isLoading ? ( +
    + ) : data?.items.length ? ( + <> +
    + {data.items.map((suite) => ( + +
    +
    +

    {suite.displayName}

    +

    @{suite.namespace}/{suite.slug}@{suite.version}

    +
    + {suiteStatusLabel(t, suite.versionStatus)} +
    +

    {suite.summary || t('suite.noSummary')}

    +
    + +
    +
    + ))} +
    + + + ) : ( + + )} + + +
    -

    - {t('suite.bundle.activeTitle')} -

    -

    {t('suite.bundle.activeDescription')}

    +

    {t('suite.bundle.taskListTitle')}

    +

    {t('suite.bundle.taskListDescription')}

    -
    - {activeOperations.items.map(operation => ( - -
    -
    -

    - {operation.targetCoordinate}@{operation.targetVersion} -

    -

    - {t(`suite.bundle.status.${operation.status}`)} -

    -
    - {operation.status === 'BLOCKED_RETRYABLE' ? ( -
    -

    - {t('suite.bundle.memberProgress', { - completed: operation.completedMembers, - total: operation.totalMembers, - waiting: operation.waitingMembers, - })} -

    -
    - -
    -
    - ))} -
    - -
    - ) : null} - {isLoading ? ( -
    - ) : data?.items.length ? ( - <> -
    - {data.items.map((suite) => ( - -
    -
    -

    {suite.displayName}

    -

    @{suite.namespace}/{suite.slug}@{suite.version}

    -
    - {suiteStatusLabel(t, suite.versionStatus)} -
    -

    {suite.summary || t('suite.noSummary')}

    -
    - -
    -
    - ))} -
    - - - ) : ( - - )} + {isLoadingOperations ? ( +
    + ) : operations?.total ? ( + <> + } + locale={i18n.language} + onOpen={(operationId) => navigate({ to: `/dashboard/suites/publishing/${operationId}` })} + /> + } + locale={i18n.language} + onOpen={(operationId) => navigate({ to: `/dashboard/suites/publishing/${operationId}` })} + /> + } + locale={i18n.language} + onOpen={(operationId) => navigate({ to: `/dashboard/suites/publishing/${operationId}` })} + /> + + + ) : ( + + )} + +
    ) } + +function TaskSection({ title, description, operations, emptyLabel, icon, locale, onOpen }: { + title: string + description: string + operations: SkillSuiteBundleOperationSummary[] + emptyLabel: string + icon: ReactNode + locale: string + onOpen: (operationId: string) => void +}) { + const { t } = useTranslation() + return ( +
    +
    + {icon} +
    +

    {title}

    +

    {description}

    +
    +
    + {operations.length ? ( + + {operations.map((operation) => ( + + ))} + + ) : ( +

    {emptyLabel}

    + )} +
    + ) +} + +function OperationStatusIcon({ status }: { status: SkillSuiteBundleOperationSummary['status'] }) { + if (status === 'BLOCKED_RETRYABLE' || status === 'REPREVIEW_REQUIRED') { + return