From 367ceba38d4cc807f899cd47cf0d65cdc5b2c8c8 Mon Sep 17 00:00:00 2001 From: monster Date: Tue, 3 Nov 2026 21:44:59 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E5=96=84=E8=B5=84=E6=BA=90=E6=89=B9?= =?UTF-8?q?=E9=87=8F=E6=93=8D=E4=BD=9C=E5=B9=B6=E6=94=AF=E6=8C=81=E8=B5=84?= =?UTF-8?q?=E6=BA=90=E5=8C=85=E6=89=8B=E5=8A=A8=E5=90=AF=E5=81=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 统一技能、专家、连接器和规则的批量启停、标签、授权及删除流程,为模型增加批量删除,提供确认、进度反馈和失败重试。 统一卡片选中边框,补齐规则标签读写,并在资源包更新、退役和恢复时保留手动启停设置,补充前后端回归测试。 --- .../src/components/resource-batch-actions.tsx | 337 +++++++++ .../admin/src/components/resource-card.tsx | 13 +- .../src/components/skill-batch-actions.tsx | 10 + .../admin/src/hooks/use-resource-batch.ts | 177 +++++ monkeyai/admin/src/i18n/locales/en-US.ts | 79 ++ monkeyai/admin/src/i18n/locales/zh-CN.ts | 79 ++ monkeyai/admin/src/lib/model-batch-delete.ts | 37 + monkeyai/admin/src/lib/resource-batch.ts | 137 ++++ monkeyai/admin/src/lib/skill-batch.ts | 19 + monkeyai/admin/src/lib/utils.ts | 11 +- monkeyai/admin/src/pages/experts-page.tsx | 212 +++--- monkeyai/admin/src/pages/models-page.tsx | 109 ++- monkeyai/admin/src/pages/rules-page.tsx | 703 ++++++++---------- monkeyai/admin/src/pages/skills-page.tsx | 185 ++++- monkeyai/admin/src/pages/tools-page.tsx | 72 +- .../admin/test/model-batch-delete.test.mjs | 54 ++ monkeyai/admin/test/resource-batch.test.mjs | 48 ++ monkeyai/admin/test/skill-batch.test.mjs | 195 +++++ monkeyai/backend/api/admin.yaml | 52 +- monkeyai/backend/internal/expert/query.sql | 3 + monkeyai/backend/internal/expert/service.go | 2 +- .../backend/internal/expert/sqlc/query.sql.go | 3 + monkeyai/backend/internal/mcp/connector.sql | 3 + monkeyai/backend/internal/mcp/service.go | 15 +- .../mcp/sqlc/connector/connector.sql.go | 3 + monkeyai/backend/internal/resource/store.go | 48 +- .../internal/resourceimport/batch_test.go | 175 +++++ .../internal/resourceimport/enabled_test.go | 158 ++++ .../internal/resourceimport/preview.go | 9 +- .../backend/internal/resourceimport/query.sql | 8 +- .../internal/resourceimport/service.go | 4 + .../internal/resourceimport/sqlc/query.sql.go | 8 +- monkeyai/backend/internal/rule/query.sql | 3 + monkeyai/backend/internal/rule/service.go | 2 +- .../backend/internal/rule/sqlc/query.sql.go | 3 + monkeyai/backend/internal/skill/query.sql | 5 + monkeyai/backend/internal/skill/service.go | 2 +- .../backend/internal/skill/sqlc/query.sql.go | 5 + 38 files changed, 2406 insertions(+), 582 deletions(-) create mode 100644 monkeyai/admin/src/components/resource-batch-actions.tsx create mode 100644 monkeyai/admin/src/components/skill-batch-actions.tsx create mode 100644 monkeyai/admin/src/hooks/use-resource-batch.ts create mode 100644 monkeyai/admin/src/lib/model-batch-delete.ts create mode 100644 monkeyai/admin/src/lib/resource-batch.ts create mode 100644 monkeyai/admin/src/lib/skill-batch.ts create mode 100644 monkeyai/admin/test/model-batch-delete.test.mjs create mode 100644 monkeyai/admin/test/resource-batch.test.mjs create mode 100644 monkeyai/admin/test/skill-batch.test.mjs create mode 100644 monkeyai/backend/internal/resourceimport/batch_test.go create mode 100644 monkeyai/backend/internal/resourceimport/enabled_test.go diff --git a/monkeyai/admin/src/components/resource-batch-actions.tsx b/monkeyai/admin/src/components/resource-batch-actions.tsx new file mode 100644 index 00000000..3c1ae58d --- /dev/null +++ b/monkeyai/admin/src/components/resource-batch-actions.tsx @@ -0,0 +1,337 @@ +import { useState } from "react" +import { HugeiconsIcon } from "@hugeicons/react" +import { + ArrowRight01Icon, + CheckmarkSquare02Icon, + Delete02Icon, + Logout05Icon, + PauseIcon, + PlayIcon, + SquareIcon, + Tag01Icon, + UserGroupIcon, +} from "@hugeicons/core-free-icons" +import { useTranslation } from "react-i18next" + +import { GroupSelect, type GroupSelectOption } from "@/components/group-select" +import { SkillTagSelect } from "@/components/skill-tag-select" +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@/components/ui/alert-dialog" +import { Button } from "@/components/ui/button" +import { + Dialog, + DialogContent, + DialogFooter, + DialogHeader, + DialogTitle, +} from "@/components/ui/dialog" +import { + DropdownMenu, + DropdownMenuContent, + DropdownMenuGroup, + DropdownMenuItem, + DropdownMenuSeparator, + DropdownMenuTrigger, +} from "@/components/ui/dropdown-menu" +import { useSkillTags } from "@/hooks/use-skill-tags" +import type { + AuthorizationGroupNode, + AuthorizationMember, + AuthorizationSelection, +} from "@/lib/authorization-groups" + +import type { + ResourceBatchChange, + ResourceBatchProgress, + ResourceBatchKind, +} from "@/lib/resource-batch" + +type BatchAction = ResourceBatchChange["action"] + +export type ResourceBatchActionsProps = { + kind: ResourceBatchKind + selecting: boolean + selectedCount: number + disabled: boolean + pending: boolean + progress: ResourceBatchProgress + groups: AuthorizationGroupNode[] + members: AuthorizationMember[] + onEnter: () => void + onSelectAll: () => void + onClear: () => void + onExit: () => void + onApply: (change: ResourceBatchChange) => Promise +} + +function groupOptions( + groups: AuthorizationGroupNode[], + parentId: string | null = null +): GroupSelectOption[] { + return groups.flatMap((group) => [ + { id: group.value, name: group.labelKey, parentId }, + ...groupOptions(group.children ?? [], group.value), + ]) +} + +export function ResourceBatchActions({ + kind, + selecting, + selectedCount, + disabled, + pending, + progress, + groups, + members, + onEnter, + onSelectAll, + onClear, + onExit, + onApply, +}: ResourceBatchActionsProps) { + const { t, i18n } = useTranslation() + const text = (key: string, values: Record = {}) => + t(`resources.batch.${key}`, { + resource: t(`resources.batch.resourceNames.${kind}`), + ...values, + }) + const { tags } = useSkillTags() + const [menuOpen, setMenuOpen] = useState(false) + const [action, setAction] = useState(null) + const [confirmOpen, setConfirmOpen] = useState(false) + const [tagsOpen, setTagsOpen] = useState(false) + const [tagIds, setTagIds] = useState([]) + const [authorization, setAuthorization] = useState({ + groupIds: [], + memberIds: [], + }) + const editing = action === "tags" || action === "authorization" + const actions = [ + ["enable", PlayIcon], + ["disable", PauseIcon], + ["tags", Tag01Icon], + ["authorization", UserGroupIcon], + ["delete", Delete02Icon], + ] as const + + const openAction = (next: BatchAction) => { + if (!selectedCount || disabled) return + setMenuOpen(false) + setConfirmOpen(false) + setTagsOpen(false) + setTagIds([]) + setAuthorization({ groupIds: [], memberIds: [] }) + setAction(next) + } + + const apply = async () => { + if (!action || pending || !selectedCount) return + const change: ResourceBatchChange = + action === "tags" + ? { action, tagIds } + : action === "authorization" + ? { action, authorization } + : { action } + if (!(await onApply(change))) return + setAction(null) + setConfirmOpen(false) + setMenuOpen(false) + } + + return ( + <> + {selecting ? ( + + + {text("actions")} + + + } + /> + + + + + {text("selectAll")} + + + + {text("clear")} + + + + + {actions.map(([next, icon]) => ( + openAction(next)} + > + + {text(`${next}`)} + + ))} + + + + { + setMenuOpen(false) + onExit() + }} + > + + {text("exit")} + + + + + ) : ( + + )} + { + if (!open && !pending) setAction(null) + }} + > + + + {action && text(`${action}`)} + + {action === "tags" ? ( + + ) : ( + ({ + id: member.id, + name: member.name, + email: member.email ?? "", + groupIds: member.groupId ? [member.groupId] : [], + }))} + value={{ + groupIds: authorization.groupIds, + userIds: authorization.memberIds, + }} + onValueChange={(next) => + setAuthorization({ + groupIds: [...next.groupIds], + memberIds: [...next.userIds], + }) + } + label={text("authorizedUsers")} + placeholder={text("authorizationPlaceholder")} + emptyText={t("pages.models.noMatchingAuthorization")} + locale={i18n.resolvedLanguage ?? i18n.language} + multiple + selectionMode="both" + cascadeGroups + searchable + searchPlaceholder={t("pages.models.searchAuthorization")} + noResultsText={t("pages.models.noMatchingAuthorization")} + /> + )} + + + + + + + { + if (open || pending) return + if (editing) setConfirmOpen(false) + else setAction(null) + }} + > + + + + {action && text(`confirmTitles.${action}`)} + + + + {action && + text(`confirmDescriptions.${action}`, { + count: selectedCount, + })} + + {pending && ( +

+ {text("progress", progress)} +

+ )} + + + {text("cancel")} + + + {text("confirm")} + + +
+
+ + ) +} diff --git a/monkeyai/admin/src/components/resource-card.tsx b/monkeyai/admin/src/components/resource-card.tsx index 4a269e07..f99905ac 100644 --- a/monkeyai/admin/src/components/resource-card.tsx +++ b/monkeyai/admin/src/components/resource-card.tsx @@ -6,11 +6,15 @@ import { cn } from "@/lib/utils" type Props = ComponentProps & { origin?: ResourceRow["origin"] disabled?: boolean + selectable?: boolean + selected?: boolean } export function ResourceCard({ origin, disabled = false, + selectable = false, + selected = false, className, ...props }: Props) { @@ -18,7 +22,7 @@ export function ResourceCard({ [data-slot=card-footer]]:border-blue-200 dark:[&>[data-slot=card-footer]]:border-blue-800", @@ -31,6 +35,13 @@ export function ResourceCard({ "[&_[data-slot=avatar]]:bg-gray-200 [&_[data-slot=avatar]]:text-gray-600 dark:[&_[data-slot=avatar]]:bg-gray-700 dark:[&_[data-slot=avatar]]:text-gray-300", "[&_[data-slot=avatar]]:after:border-gray-300 dark:[&_[data-slot=avatar]]:after:border-gray-700", ], + selectable && "cursor-pointer", + selected && + "relative ring-0 after:pointer-events-none after:absolute after:inset-0 after:rounded-[inherit] after:border-2", + selected && + (origin !== "package" && !disabled + ? "after:border-blue-500 dark:after:border-blue-400" + : "after:border-gray-500 dark:after:border-gray-400"), className )} /> diff --git a/monkeyai/admin/src/components/skill-batch-actions.tsx b/monkeyai/admin/src/components/skill-batch-actions.tsx new file mode 100644 index 00000000..7c718566 --- /dev/null +++ b/monkeyai/admin/src/components/skill-batch-actions.tsx @@ -0,0 +1,10 @@ +import { + ResourceBatchActions, + type ResourceBatchActionsProps, +} from "@/components/resource-batch-actions" + +export function SkillBatchActions( + props: Omit +) { + return +} diff --git a/monkeyai/admin/src/hooks/use-resource-batch.ts b/monkeyai/admin/src/hooks/use-resource-batch.ts new file mode 100644 index 00000000..4829d689 --- /dev/null +++ b/monkeyai/admin/src/hooks/use-resource-batch.ts @@ -0,0 +1,177 @@ +import { useState, type KeyboardEvent } from "react" +import { useTranslation } from "react-i18next" +import { useAppToast } from "@/components/animated-toast-provider" +import type { useResourceList } from "@/hooks/use-resource-list" +import type { ResourceRow } from "@/lib/resources" +import { + applyResourceBatch, + type ResourceBatchChange, + type ResourceBatchKind, + type ResourceBatchProgress, +} from "@/lib/resource-batch" + +export function useResourceBatch( + kind: ResourceBatchKind, + remote: ReturnType> +) { + const { t } = useTranslation() + const { showToast } = useAppToast() + const [selecting, setSelecting] = useState(false) + const [selectedIds, setSelectedIds] = useState([]) + const [progress, setProgress] = useState({ + completed: 0, + total: 0, + }) + const selectedRows = remote.items.filter( + (row) => row.ownership_type === "system" && selectedIds.includes(row.id) + ) + const resource = t(`resources.batch.resourceNames.${kind}`) + const exit = () => { + setSelecting(false) + setSelectedIds([]) + } + const toggle = (id: string) => { + if (remote.pending) return + setSelectedIds((current) => + current.includes(id) + ? current.filter((selectedId) => selectedId !== id) + : [...current, id] + ) + } + const apply = async (change: ResourceBatchChange) => { + if (remote.loading || selectedRows.length === 0) return false + return remote.run(async () => { + setProgress({ completed: 0, total: selectedRows.length }) + const result = await applyResourceBatch( + kind, + selectedRows, + change, + undefined, + setProgress + ) + if ( + change.action === "delete" && + result.succeeded.length === remote.items.length && + remote.page > 1 + ) { + remote.previousPage(remote.type) + } + setSelectedIds(result.failed.map((failure) => failure.id)) + setSelecting(result.failed.length > 0) + showToast({ + status: result.failed.length + ? "error" + : result.skipped.length + ? "info" + : "success", + title: t("resources.batch.result", { + succeeded: result.succeeded.length, + failed: result.failed.length, + skipped: result.skipped.length, + }), + description: result.failed.length + ? `${t("resources.batch.retryFailed")} ${result.failed + .slice(0, 3) + .map((failure) => `${failure.name}: ${failure.message}`) + .join(";")}` + : result.skipped.length + ? t("resources.batch.packageSkipped", { + resource, + count: result.skipped.length, + }) + : undefined, + }) + }) + } + + return { + key: `${remote.type}:${remote.search}:${remote.page}:${remote.pageSize}`, + exit, + toggle, + isSelected: (id: string) => selecting && selectedIds.includes(id), + actions: { + kind, + selecting, + selectedCount: selectedRows.length, + disabled: + remote.loading || + remote.pending || + (!selecting && remote.items.length === 0), + pending: remote.pending, + progress, + onApply: apply, + onEnter: () => { + setSelectedIds([]) + setSelecting(true) + }, + onSelectAll: () => + setSelectedIds( + remote.items + .filter((row) => row.ownership_type === "system") + .map((row) => row.id) + ), + onClear: () => setSelectedIds([]), + onExit: exit, + }, + page: { + ...remote, + setType: (...args: Parameters) => { + if (!remote.pending) { + exit() + remote.setType(...args) + } + }, + handleSearch: (...args: Parameters) => { + args[0].preventDefault() + if (!remote.pending) { + exit() + remote.handleSearch(...args) + } + }, + setPageSize: (...args: Parameters) => { + if (!remote.pending) { + exit() + remote.setPageSize(...args) + } + }, + nextPage: () => { + if (!remote.pending) { + exit() + remote.nextPage() + } + }, + previousPage: (type = remote.type) => { + if (!remote.pending) { + exit() + remote.previousPage(type) + } + }, + }, + cardProps: (id: string, name: string, ownership: "system" | "user") => { + const selectable = selecting && ownership === "system" + return { + selectable, + selected: selectable && selectedIds.includes(id), + role: selectable ? "checkbox" : undefined, + "aria-checked": selectable ? selectedIds.includes(id) : undefined, + "aria-disabled": selectable && remote.pending ? true : undefined, + "aria-label": selectable + ? t("resources.batch.selectResource", { name }) + : undefined, + tabIndex: selectable ? 0 : undefined, + onClick: selectable ? () => toggle(id) : undefined, + onKeyDown: selectable + ? (event: KeyboardEvent) => { + if ( + event.target !== event.currentTarget || + (event.key !== "Enter" && event.key !== " ") + ) + return + event.preventDefault() + toggle(id) + } + : undefined, + } + }, + } +} diff --git a/monkeyai/admin/src/i18n/locales/en-US.ts b/monkeyai/admin/src/i18n/locales/en-US.ts index 70f164dd..2730afb0 100644 --- a/monkeyai/admin/src/i18n/locales/en-US.ts +++ b/monkeyai/admin/src/i18n/locales/en-US.ts @@ -144,6 +144,85 @@ export const enUS = { operationCompleted: "Operation completed.", availableScope: "Available to", noDescription: "No description", + modelBatchDelete: { + action: "Delete models", + title: "Delete selected models?", + description: "Delete the {{count}} selected models? This cannot be undone.", + progress: "Processed {{completed}} / {{total}} models", + result: "Succeeded: {{succeeded}}, failed: {{failed}}", + retryFailed: "Failed models remain selected for retry.", + }, + batch: { + resourceNames: { skill: "skills", expert: "experts", connector: "connectors", rule: "rules" }, + actions: "Batch actions", + selectAll: "Select all", + clear: "Clear selection", + exit: "Exit batch actions", + enable: "Enable {{resource}}", + disable: "Disable {{resource}}", + delete: "Delete {{resource}}", + tags: "Set tags", + authorization: "Set authorization", + selectResource: "Select {{name}}", + cancel: "Cancel", + save: "Save", + confirm: "Confirm", + disabled: "Disabled", + tagsPlaceholder: "Select tags", + authorizedUsers: "Authorized users", + authorizationPlaceholder: "Select users or groups", + confirmTitles: { + enable: "Enable selected {{resource}}?", + disable: "Disable selected {{resource}}?", + delete: "Delete selected {{resource}}?", + tags: "Set tags for selected {{resource}}?", + authorization: "Set authorization for selected {{resource}}?", + }, + confirmDescriptions: { + enable: "Enable the {{count}} selected {{resource}}?", + disable: "Disable the {{count}} selected {{resource}}?", + delete: "Delete the {{count}} selected {{resource}}? This cannot be undone.", + tags: "Replace tags on the {{count}} selected {{resource}}?", + authorization: "Replace authorization on the {{count}} selected {{resource}}?", + }, + packageSkipped: "Skipped {{count}} {{resource}} managed by resource packages.", + progress: "Processed {{completed}} / {{total}} {{resource}}", + result: "Succeeded: {{succeeded}}, failed: {{failed}}, skipped: {{skipped}}", + retryFailed: "Failed items remain selected for retry.", + }, + skillBatch: { + actions: "Bulk actions", + selectAll: "Select all", + clear: "Clear selection", + exit: "Exit bulk actions", + enable: "Enable skills", + disable: "Disable skills", + delete: "Delete skills", + tags: "Set tags", + authorization: "Set access scope", + selectSkill: "Select {{skill}}", + cancel: "Cancel", + save: "Save", + confirm: "Confirm", + confirmTitles: { + enable: "Enable selected skills?", + disable: "Disable selected skills?", + delete: "Delete selected skills?", + tags: "Set tags for selected skills?", + authorization: "Set access scope for selected skills?", + }, + confirmDescriptions: { + enable: "Enable the {{count}} selected skills?", + disable: "Disable the {{count}} selected skills?", + delete: "Delete the {{count}} selected skills? This cannot be undone.", + tags: "Replace the tags of the {{count}} selected skills with the selected tags?", + authorization: "Replace the access scope of the {{count}} selected skills with the selected scope?", + }, + packageSkipped: "Skipped {{count}} package-managed skills.", + progress: "Processed {{completed}} / {{total}} skills", + result: "Succeeded: {{succeeded}}, failed: {{failed}}, skipped: {{skipped}}", + retryFailed: "Failed skills remain selected for retry.", + }, searchPlaceholder: "Search {{resource}}", ruleSearchPlaceholder: "Search name or description", modelSearchPlaceholder: "Search name, model ID or URL", diff --git a/monkeyai/admin/src/i18n/locales/zh-CN.ts b/monkeyai/admin/src/i18n/locales/zh-CN.ts index 4d52769d..2a2a3d44 100644 --- a/monkeyai/admin/src/i18n/locales/zh-CN.ts +++ b/monkeyai/admin/src/i18n/locales/zh-CN.ts @@ -139,6 +139,85 @@ export const zhCN = { operationCompleted: "操作已完成。", availableScope: "可用范围", noDescription: "暂无说明", + modelBatchDelete: { + action: "删除模型", + title: "删除所选模型?", + description: "确定删除已选择的 {{count}} 个模型吗?此操作无法撤销。", + progress: "已处理 {{completed}} / {{total}} 个模型", + result: "成功 {{succeeded}} 个,失败 {{failed}} 个", + retryFailed: "失败项已保留勾选,可重试。", + }, + batch: { + resourceNames: { skill: "技能", expert: "专家", connector: "连接器", rule: "规则" }, + actions: "批量操作", + selectAll: "选择全部", + clear: "取消选择", + exit: "退出批量操作", + enable: "启用{{resource}}", + disable: "禁用{{resource}}", + delete: "删除{{resource}}", + tags: "设置标签", + authorization: "设置授权范围", + selectResource: "选择{{name}}", + cancel: "取消", + save: "保存", + confirm: "确定", + disabled: "禁用", + tagsPlaceholder: "选择标签", + authorizedUsers: "授权用户", + authorizationPlaceholder: "选择用户或分组", + confirmTitles: { + enable: "启用所选{{resource}}?", + disable: "禁用所选{{resource}}?", + delete: "删除所选{{resource}}?", + tags: "设置所选{{resource}}的标签?", + authorization: "设置所选{{resource}}的授权范围?", + }, + confirmDescriptions: { + enable: "确定启用已选择的 {{count}} 个{{resource}}吗?", + disable: "确定禁用已选择的 {{count}} 个{{resource}}吗?", + delete: "确定删除已选择的 {{count}} 个{{resource}}吗?此操作无法撤销。", + tags: "确定将已选择的 {{count}} 个{{resource}}设置为所选标签吗?", + authorization: "确定将已选择的 {{count}} 个{{resource}}设置为所选授权范围吗?", + }, + packageSkipped: "已跳过 {{count}} 个由资源包管理的{{resource}}。", + progress: "已处理 {{completed}} / {{total}} 个{{resource}}", + result: "成功 {{succeeded}} 个,失败 {{failed}} 个,跳过 {{skipped}} 个", + retryFailed: "失败项已保留勾选,可重试。", + }, + skillBatch: { + actions: "批量操作", + selectAll: "选择全部", + clear: "取消选择", + exit: "退出批量操作", + enable: "启用技能", + disable: "禁用技能", + delete: "删除技能", + tags: "设置标签", + authorization: "设置授权范围", + selectSkill: "选择{{skill}}", + cancel: "取消", + save: "保存", + confirm: "确定", + confirmTitles: { + enable: "启用所选技能?", + disable: "禁用所选技能?", + delete: "删除所选技能?", + tags: "设置所选技能的标签?", + authorization: "设置所选技能的授权范围?", + }, + confirmDescriptions: { + enable: "确定启用已选择的 {{count}} 个技能吗?", + disable: "确定禁用已选择的 {{count}} 个技能吗?", + delete: "确定删除已选择的 {{count}} 个技能吗?此操作无法撤销。", + tags: "确定将已选择的 {{count}} 个技能设置为所选标签吗?", + authorization: "确定将已选择的 {{count}} 个技能设置为所选授权范围吗?", + }, + packageSkipped: "已跳过 {{count}} 个由资源包管理的技能。", + progress: "已处理 {{completed}} / {{total}} 个技能", + result: "成功 {{succeeded}} 个,失败 {{failed}} 个,跳过 {{skipped}} 个", + retryFailed: "失败项已保留勾选,可重试。", + }, searchPlaceholder: "搜索{{resource}}", ruleSearchPlaceholder: "搜索名称或描述", modelSearchPlaceholder: "搜索名称、模型 ID 或地址", diff --git a/monkeyai/admin/src/lib/model-batch-delete.ts b/monkeyai/admin/src/lib/model-batch-delete.ts new file mode 100644 index 00000000..18c1e51d --- /dev/null +++ b/monkeyai/admin/src/lib/model-batch-delete.ts @@ -0,0 +1,37 @@ +import { api } from "./api.ts" + +type ModelTarget = { + id: string + displayName: string + type: "system" | "user" +} + +type Request = (path: string, init: RequestInit) => Promise + +export async function deleteModelBatch( + models: readonly ModelTarget[], + request: Request = api, + onProgress?: (progress: { completed: number; total: number }) => void +) { + const selected = [ + ...new Map( + models.filter((model) => model.type === "system").map((model) => [model.id, model]) + ).values(), + ] + const succeeded: string[] = [] + const failed: { id: string; name: string; message: string }[] = [] + for (const [index, model] of selected.entries()) { + try { + await request(`/api/admin/v1/models/${model.id}`, { method: "DELETE" }) + succeeded.push(model.id) + } catch (reason) { + failed.push({ + id: model.id, + name: model.displayName, + message: reason instanceof Error ? reason.message : String(reason), + }) + } + onProgress?.({ completed: index + 1, total: selected.length }) + } + return { succeeded, failed } +} diff --git a/monkeyai/admin/src/lib/resource-batch.ts b/monkeyai/admin/src/lib/resource-batch.ts new file mode 100644 index 00000000..b63769cb --- /dev/null +++ b/monkeyai/admin/src/lib/resource-batch.ts @@ -0,0 +1,137 @@ +import { api } from "./api.ts" +import type { AuthorizationSelection } from "./authorization-groups" +import type { ResourceRow } from "./resources" + +export type ResourceBatchKind = "skill" | "expert" | "connector" | "rule" +export type ResourceBatchChange = + | { action: "enable" } + | { action: "disable" } + | { action: "delete" } + | { action: "tags"; tagIds: string[] } + | { action: "authorization"; authorization: AuthorizationSelection } +export type ResourceBatchResource = Pick< + ResourceRow, + | "id" + | "name" + | "description" + | "ownership_type" + | "origin" + | "revision" + | "grants" +> & + Partial> +export type ResourceBatchProgress = { completed: number; total: number } +export type ResourceBatchResult = { + succeeded: string[] + skipped: string[] + failed: { id: string; name: string; message: string }[] +} + +type Request = (path: string, init: RequestInit) => Promise +const endpoints: Record = { + skill: "skills", + expert: "experts", + connector: "connectors", + rule: "rules", +} + +export async function applyResourceBatch( + kind: ResourceBatchKind, + resources: readonly ResourceBatchResource[], + change: ResourceBatchChange, + request: Request = api, + onProgress?: (progress: ResourceBatchProgress) => void +): Promise { + const selected = [ + ...new Map(resources.map((item) => [item.id, item])).values(), + ] + const result: ResourceBatchResult = { succeeded: [], skipped: [], failed: [] } + const update: ResourceBatchChange = + change.action === "tags" + ? { action: "tags", tagIds: [...change.tagIds] } + : change.action === "authorization" + ? { + action: "authorization", + authorization: { + groupIds: [...change.authorization.groupIds], + memberIds: [...change.authorization.memberIds], + }, + } + : { ...change } + + for (const [index, item] of selected.entries()) { + try { + if ( + item.ownership_type !== "system" || + (item.origin === "package" && + (update.action === "tags" || update.action === "delete")) + ) { + result.skipped.push(item.id) + continue + } + const path = `/api/admin/v1/${endpoints[kind]}/${item.id}` + const headers = { "If-Match": `"${item.revision}"` } + if (update.action === "enable" || update.action === "disable") { + await request(`${path}/enabled`, { + method: "PATCH", + headers, + body: JSON.stringify({ enabled: update.action === "enable" }), + }) + } else if (update.action === "delete") { + await request(path, { method: "DELETE", headers }) + } else if (update.action === "tags") { + // Save validators require the canonical prompt/content for these kinds. + // Omitted associations, credentials, grants and enabled remain untouched. + await request(path, { + method: "PUT", + headers, + body: JSON.stringify({ + name: item.name, + description: item.description, + ...(kind === "expert" ? { prompt: item.prompt } : {}), + ...(kind === "rule" ? { content: item.content } : {}), + tag_ids: [...new Set(update.tagIds)], + }), + }) + } else { + const requirements = new Map( + item.grants.map((grant) => [ + grant.group_id + ? `group:${grant.group_id}` + : `user:${grant.user_id}`, + grant.usage_requirement, + ]) + ) + const groupGrants = [...new Set(update.authorization.groupIds)].map( + (group_id) => ({ + group_id, + usage_requirement: + requirements.get(`group:${group_id}`) ?? "optional", + }) + ) + const userGrants = [...new Set(update.authorization.memberIds)].map( + (user_id) => ({ + user_id, + usage_requirement: + requirements.get(`user:${user_id}`) ?? "optional", + }) + ) + await request(`/api/admin/v1/resources/${kind}/${item.id}/grants`, { + method: "PUT", + headers, + body: JSON.stringify({ grants: [...groupGrants, ...userGrants] }), + }) + } + result.succeeded.push(item.id) + } catch (reason) { + result.failed.push({ + id: item.id, + name: item.name, + message: reason instanceof Error ? reason.message : String(reason), + }) + } finally { + onProgress?.({ completed: index + 1, total: selected.length }) + } + } + return result +} diff --git a/monkeyai/admin/src/lib/skill-batch.ts b/monkeyai/admin/src/lib/skill-batch.ts new file mode 100644 index 00000000..278e34ab --- /dev/null +++ b/monkeyai/admin/src/lib/skill-batch.ts @@ -0,0 +1,19 @@ +import { applyResourceBatch } from "./resource-batch.ts" + +export type { + ResourceBatchChange as SkillBatchChange, + ResourceBatchResource as SkillBatchResource, + ResourceBatchProgress as SkillBatchProgress, + ResourceBatchResult as SkillBatchResult, +} from "./resource-batch.ts" + +export function applySkillBatch( + ...args: Parameters extends [ + unknown, + ...infer Rest, + ] + ? Rest + : never +) { + return applyResourceBatch("skill", ...args) +} diff --git a/monkeyai/admin/src/lib/utils.ts b/monkeyai/admin/src/lib/utils.ts index 4527db00..096d58a1 100644 --- a/monkeyai/admin/src/lib/utils.ts +++ b/monkeyai/admin/src/lib/utils.ts @@ -5,11 +5,14 @@ export function cn(...inputs: ClassValue[]) { return twMerge(clsx(inputs)) } -const creatorNameSegmenter = new Intl.Segmenter(undefined, { - granularity: "grapheme", -}) +const creatorNameSegmenter = + typeof Intl.Segmenter === "function" + ? new Intl.Segmenter(undefined, { granularity: "grapheme" }) + : null export function getCreatorInitial(creator: string) { - const segments = creatorNameSegmenter.segment(creator.trim().toUpperCase()) + const name = creator.trim().toUpperCase() + if (!creatorNameSegmenter) return Array.from(name)[0] ?? "" + const segments = creatorNameSegmenter.segment(name) return segments[Symbol.iterator]().next().value?.segment ?? "" } diff --git a/monkeyai/admin/src/pages/experts-page.tsx b/monkeyai/admin/src/pages/experts-page.tsx index 1a181d81..1392268c 100644 --- a/monkeyai/admin/src/pages/experts-page.tsx +++ b/monkeyai/admin/src/pages/experts-page.tsx @@ -18,6 +18,8 @@ import { ResourceCardMenuButton } from "@/components/resource-card-menu-button" import { useEffect, useState, type FormEvent } from "react" import { ResourceList } from "@/components/resource-list" import { useResourceList } from "@/hooks/use-resource-list" +import { useResourceBatch } from "@/hooks/use-resource-batch" +import { ResourceBatchActions } from "@/components/resource-batch-actions" import { AiBrain01Icon, Copy02Icon, @@ -233,7 +235,10 @@ function ExpertAssociationSelect({ - + {label} @@ -299,6 +304,7 @@ export function ExpertsPage() { const { tags: availableTags } = useSkillTags() const { showToast } = useAppToast() const remote = useResourceList("/experts") + const batch = useResourceBatch("expert", remote) const experts = remote.items.map((row) => toExpert(row, i18n.language)) const subjects = useSubjects() const [options, setOptions] = useState< @@ -360,6 +366,7 @@ export function ExpertsPage() { }, [editorOpen, optionRevision, showToast, t, i18n.language]) const openCreateDialog = () => { + batch.exit() setEditingExpert(null) setForm(EMPTY_FORM) setAuthorizationOpen(false) @@ -458,7 +465,7 @@ export function ExpertsPage() { } const setExpertEnabled = async (id: string, enabled: boolean) => { const item = experts.find((e) => e.id === id) - if (!item || item.origin === "package") return + if (!item) return await remote.run(async () => { await api(base + `/experts/${id}/enabled`, { method: "PATCH", @@ -493,7 +500,7 @@ export function ExpertsPage() { return (
- - {t("pages.experts.createExpert")} - +
+ + +
} >
@@ -519,6 +535,7 @@ export function ExpertsPage() { key={expert.id} origin={expert.origin} disabled={!expert.enabled} + {...batch.cardProps(expert.id, expert.name, expert.ownership)} >
@@ -558,87 +575,106 @@ export function ExpertsPage() { )} - + {expert.owner}
- - - } - > - - - - {expert.ownership === "system" && ( - <> - - - - openEditDialog(expert)} - > - - {t("pages.experts.edit")} - - - - - + } + > + + + + {expert.ownership === "system" && ( + <> + + + setExpertEnabled(expert.id, true) + } + > + + {t("pages.experts.enable")} + + + setExpertEnabled(expert.id, false) + } + > + + {t("pages.experts.disable")} + + openEditDialog(expert)} + > + + {t("pages.experts.edit")} + + + + + + )} + + setPendingDeletion(expert)} + > + + {t("pages.experts.delete")} + + + + + )}
diff --git a/monkeyai/admin/src/pages/models-page.tsx b/monkeyai/admin/src/pages/models-page.tsx index e234c236..7855e09b 100644 --- a/monkeyai/admin/src/pages/models-page.tsx +++ b/monkeyai/admin/src/pages/models-page.tsx @@ -93,6 +93,7 @@ import { useResourceList } from "@/hooks/use-resource-list" import { Iconfont } from "@/components/iconfont" import type { AuthorizationSelection } from "@/lib/authorization-groups" import { api } from "@/lib/api" +import { deleteModelBatch } from "@/lib/model-batch-delete" import { SystemProxySelect } from "@/components/proxy-settings" import { loadProxies, type SystemProxy } from "@/lib/proxy-settings" import { useSkillTags } from "@/hooks/use-skill-tags" @@ -358,6 +359,11 @@ export function ModelsPage() { const [selecting, setSelecting] = useState(false) const [selectionMenuOpen, setSelectionMenuOpen] = useState(false) const [selectedIds, setSelectedIds] = useState([]) + const selectedModels = models.filter( + (model) => model.type === "system" && selectedIds.includes(model.id) + ) + const [batchDeleteOpen, setBatchDeleteOpen] = useState(false) + const [batchDeleteProgress, setBatchDeleteProgress] = useState({ completed: 0, total: 0 }) const [batchEnabled, setBatchEnabled] = useState(null) const [batchTagsOpen, setBatchTagsOpen] = useState(false) const [batchTagsConfirm, setBatchTagsConfirm] = useState(false) @@ -586,6 +592,7 @@ export function ModelsPage() { setSelecting(false) setSelectionMenuOpen(false) setSelectedIds([]) + setBatchDeleteOpen(false) setBatchEnabled(null) setBatchTagsOpen(false) setBatchTagsConfirm(false) @@ -604,6 +611,48 @@ export function ModelsPage() { setBatchEnabled(enabled) } + const openBatchDelete = () => { + if (selectedModels.length === 0) return + setSelectionMenuOpen(false) + setBatchDeleteOpen(true) + } + + const applyBatchDelete = async () => { + if (batchPending || remote.loading || selectedModels.length === 0) return + await remote.run(async () => { + setBatchPending(true) + setBatchDeleteProgress({ completed: 0, total: selectedModels.length }) + try { + const result = await deleteModelBatch(selectedModels, api, setBatchDeleteProgress) + if (result.succeeded.length === models.length && remote.page > 1) { + remote.previousPage(activeModelType) + } + setBatchDeleteOpen(false) + if (result.failed.length) { + setSelectedIds(result.failed.map((failure) => failure.id)) + setSelecting(true) + } else { + exitSelection() + } + showToast({ + status: result.failed.length ? "error" : "success", + title: t("resources.modelBatchDelete.result", { + succeeded: result.succeeded.length, + failed: result.failed.length, + }), + description: result.failed.length + ? `${t("resources.modelBatchDelete.retryFailed")} ${result.failed + .slice(0, 3) + .map((failure) => `${failure.name}: ${failure.message}`) + .join(";")}` + : undefined, + }) + } finally { + setBatchPending(false) + } + }) + } + const applyBatchEnabled = async () => { if (batchEnabled === null || batchPending) return const ids = [...selectedIds] @@ -750,6 +799,7 @@ export function ModelsPage() { } const toggleSelected = (id: string) => { + if (batchPending || remote.pending) return setSelectedIds((current) => current.includes(id) ? current.filter((item) => item !== id) @@ -1062,7 +1112,7 @@ export function ModelsPage() {
+