mirror of
https://github.com/chaitin/MonkeyCode.git
synced 2026-11-24 21:29:00 +08:00
完善资源批量操作并支持资源包手动启停
统一技能、专家、连接器和规则的批量启停、标签、授权及删除流程,为模型增加批量删除,提供确认、进度反馈和失败重试。 统一卡片选中边框,补齐规则标签读写,并在资源包更新、退役和恢复时保留手动启停设置,补充前后端回归测试。
This commit is contained in:
1 parent
9de4e0357a
commit
367ceba38d
38 files changed
+2406
-582
No files matched your search
@@ -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<boolean>
|
||||
}
|
||||
|
||||
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<string, unknown> = {}) =>
|
||||
t(`resources.batch.${key}`, {
|
||||
resource: t(`resources.batch.resourceNames.${kind}`),
|
||||
...values,
|
||||
})
|
||||
const { tags } = useSkillTags()
|
||||
const [menuOpen, setMenuOpen] = useState(false)
|
||||
const [action, setAction] = useState<BatchAction | null>(null)
|
||||
const [confirmOpen, setConfirmOpen] = useState(false)
|
||||
const [tagsOpen, setTagsOpen] = useState(false)
|
||||
const [tagIds, setTagIds] = useState<string[]>([])
|
||||
const [authorization, setAuthorization] = useState<AuthorizationSelection>({
|
||||
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 ? (
|
||||
<DropdownMenu open={menuOpen} onOpenChange={setMenuOpen}>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<Button type="button" variant="outline" disabled={disabled}>
|
||||
{text("actions")}
|
||||
<HugeiconsIcon
|
||||
icon={ArrowRight01Icon}
|
||||
data-icon="inline-end"
|
||||
className="rotate-90"
|
||||
/>
|
||||
</Button>
|
||||
}
|
||||
/>
|
||||
<DropdownMenuContent align="end" className="w-40 whitespace-nowrap">
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem onClick={onSelectAll}>
|
||||
<HugeiconsIcon icon={CheckmarkSquare02Icon} strokeWidth={2} />
|
||||
{text("selectAll")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem onClick={onClear}>
|
||||
<HugeiconsIcon icon={SquareIcon} strokeWidth={2} />
|
||||
{text("clear")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
{actions.map(([next, icon]) => (
|
||||
<DropdownMenuItem
|
||||
key={next}
|
||||
variant={next === "delete" ? "destructive" : undefined}
|
||||
disabled={selectedCount === 0}
|
||||
onClick={() => openAction(next)}
|
||||
>
|
||||
<HugeiconsIcon icon={icon} strokeWidth={2} />
|
||||
{text(`${next}`)}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
setMenuOpen(false)
|
||||
onExit()
|
||||
}}
|
||||
>
|
||||
<HugeiconsIcon icon={Logout05Icon} strokeWidth={2} />
|
||||
{text("exit")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
) : (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
onClick={() => {
|
||||
onEnter()
|
||||
setMenuOpen(true)
|
||||
}}
|
||||
>
|
||||
{text("actions")}
|
||||
</Button>
|
||||
)}
|
||||
<Dialog
|
||||
open={editing}
|
||||
onOpenChange={(open) => {
|
||||
if (!open && !pending) setAction(null)
|
||||
}}
|
||||
>
|
||||
<DialogContent className="sm:max-w-sm" showCloseButton={!pending}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>{action && text(`${action}`)}</DialogTitle>
|
||||
</DialogHeader>
|
||||
{action === "tags" ? (
|
||||
<SkillTagSelect
|
||||
id={`batch-${kind}-tags`}
|
||||
open={tagsOpen}
|
||||
options={tags}
|
||||
placeholder={text("tagsPlaceholder")}
|
||||
value={tagIds}
|
||||
onOpenChange={setTagsOpen}
|
||||
onValueChange={setTagIds}
|
||||
/>
|
||||
) : (
|
||||
<GroupSelect
|
||||
id={`batch-${kind}-authorization`}
|
||||
disabled={pending}
|
||||
options={groupOptions(groups)}
|
||||
users={members.map((member) => ({
|
||||
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")}
|
||||
/>
|
||||
)}
|
||||
<DialogFooter>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={pending}
|
||||
onClick={() => setAction(null)}
|
||||
>
|
||||
{text("cancel")}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
disabled={
|
||||
pending ||
|
||||
(action === "authorization" &&
|
||||
authorization.groupIds.length +
|
||||
authorization.memberIds.length ===
|
||||
0)
|
||||
}
|
||||
onClick={() => setConfirmOpen(true)}
|
||||
>
|
||||
{text("save")}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
<AlertDialog
|
||||
open={action !== null && (!editing || confirmOpen)}
|
||||
onOpenChange={(open) => {
|
||||
if (open || pending) return
|
||||
if (editing) setConfirmOpen(false)
|
||||
else setAction(null)
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent size="sm">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>
|
||||
{action && text(`confirmTitles.${action}`)}
|
||||
</AlertDialogTitle>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogDescription>
|
||||
{action &&
|
||||
text(`confirmDescriptions.${action}`, {
|
||||
count: selectedCount,
|
||||
})}
|
||||
</AlertDialogDescription>
|
||||
{pending && (
|
||||
<p role="status" className="text-sm text-muted-foreground">
|
||||
{text("progress", progress)}
|
||||
</p>
|
||||
)}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={pending}>
|
||||
{text("cancel")}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
variant={action === "delete" ? "destructive" : undefined}
|
||||
loading={pending}
|
||||
disabled={selectedCount === 0}
|
||||
onClick={apply}
|
||||
>
|
||||
{text("confirm")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -6,11 +6,15 @@ import { cn } from "@/lib/utils"
|
||||
type Props = ComponentProps<typeof Card> & {
|
||||
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({
|
||||
<Card
|
||||
{...props}
|
||||
className={cn(
|
||||
"[&_[data-slot=avatar]]:bg-gray-100 [&_[data-slot=avatar]]:text-gray-700 dark:[&_[data-slot=avatar]]:bg-gray-800 dark:[&_[data-slot=avatar]]:text-gray-200 [&_[data-slot=avatar-fallback]]:bg-inherit [&_[data-slot=avatar-fallback]]:text-inherit",
|
||||
"[&_[data-slot=avatar-fallback]]:bg-inherit [&_[data-slot=avatar-fallback]]:text-inherit [&_[data-slot=avatar]]:bg-gray-100 [&_[data-slot=avatar]]:text-gray-700 dark:[&_[data-slot=avatar]]:bg-gray-800 dark:[&_[data-slot=avatar]]:text-gray-200",
|
||||
origin !== "package" && [
|
||||
"bg-blue-50 ring-blue-200 dark:bg-blue-950 dark:ring-blue-800",
|
||||
"[&>[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
|
||||
)}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
import {
|
||||
ResourceBatchActions,
|
||||
type ResourceBatchActionsProps,
|
||||
} from "@/components/resource-batch-actions"
|
||||
|
||||
export function SkillBatchActions(
|
||||
props: Omit<ResourceBatchActionsProps, "kind">
|
||||
) {
|
||||
return <ResourceBatchActions {...props} kind="skill" />
|
||||
}
|
||||
@@ -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<typeof useResourceList<ResourceRow>>
|
||||
) {
|
||||
const { t } = useTranslation()
|
||||
const { showToast } = useAppToast()
|
||||
const [selecting, setSelecting] = useState(false)
|
||||
const [selectedIds, setSelectedIds] = useState<string[]>([])
|
||||
const [progress, setProgress] = useState<ResourceBatchProgress>({
|
||||
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<typeof remote.setType>) => {
|
||||
if (!remote.pending) {
|
||||
exit()
|
||||
remote.setType(...args)
|
||||
}
|
||||
},
|
||||
handleSearch: (...args: Parameters<typeof remote.handleSearch>) => {
|
||||
args[0].preventDefault()
|
||||
if (!remote.pending) {
|
||||
exit()
|
||||
remote.handleSearch(...args)
|
||||
}
|
||||
},
|
||||
setPageSize: (...args: Parameters<typeof remote.setPageSize>) => {
|
||||
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<HTMLDivElement>) => {
|
||||
if (
|
||||
event.target !== event.currentTarget ||
|
||||
(event.key !== "Enter" && event.key !== " ")
|
||||
)
|
||||
return
|
||||
event.preventDefault()
|
||||
toggle(id)
|
||||
}
|
||||
: undefined,
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -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",
|
||||
|
||||
@@ -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 或地址",
|
||||
|
||||
@@ -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<unknown>
|
||||
|
||||
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 }
|
||||
}
|
||||
@@ -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<Pick<ResourceRow, "prompt" | "content">>
|
||||
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<unknown>
|
||||
const endpoints: Record<ResourceBatchKind, string> = {
|
||||
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<ResourceBatchResult> {
|
||||
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
|
||||
}
|
||||
@@ -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<typeof applyResourceBatch> extends [
|
||||
unknown,
|
||||
...infer Rest,
|
||||
]
|
||||
? Rest
|
||||
: never
|
||||
) {
|
||||
return applyResourceBatch("skill", ...args)
|
||||
}
|
||||
@@ -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 ?? ""
|
||||
}
|
||||
@@ -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({
|
||||
</span>
|
||||
<HugeiconsIcon icon={UnfoldMoreIcon} data-icon="inline-end" />
|
||||
</PopoverTrigger>
|
||||
<PopoverContent align="start" className="w-[var(--anchor-width)] gap-1 p-1">
|
||||
<PopoverContent
|
||||
align="start"
|
||||
className="w-[var(--anchor-width)] gap-1 p-1"
|
||||
>
|
||||
<PopoverHeader className="sr-only">
|
||||
<PopoverTitle>{label}</PopoverTitle>
|
||||
</PopoverHeader>
|
||||
@@ -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 (
|
||||
<section className="flex h-[calc(100vh-4rem)] min-h-0 flex-none flex-col gap-4 p-4 pt-0 md:h-[calc(100vh-5rem)]">
|
||||
<ResourceList
|
||||
page={remote}
|
||||
page={batch.page}
|
||||
error={subjects.error}
|
||||
typeLabel={t("pages.models.type")}
|
||||
systemLabel={t("resources.systemExpert")}
|
||||
@@ -503,14 +510,23 @@ export function ExpertsPage() {
|
||||
})}
|
||||
searchClassName="sm:max-w-44 sm:flex-none"
|
||||
actions={
|
||||
<Button
|
||||
className="ms-auto shrink-0"
|
||||
type="button"
|
||||
onClick={openCreateDialog}
|
||||
>
|
||||
<HugeiconsIcon icon={PlusSignIcon} data-icon="inline-start" />
|
||||
{t("pages.experts.createExpert")}
|
||||
</Button>
|
||||
<div className="ms-auto flex shrink-0 items-center gap-2">
|
||||
<ResourceBatchActions
|
||||
key={batch.key}
|
||||
{...batch.actions}
|
||||
groups={subjects.groups}
|
||||
members={subjects.members}
|
||||
/>
|
||||
<Button
|
||||
className="shrink-0"
|
||||
type="button"
|
||||
disabled={remote.pending}
|
||||
onClick={openCreateDialog}
|
||||
>
|
||||
<HugeiconsIcon icon={PlusSignIcon} data-icon="inline-start" />
|
||||
{t("pages.experts.createExpert")}
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
|
||||
@@ -519,6 +535,7 @@ export function ExpertsPage() {
|
||||
key={expert.id}
|
||||
origin={expert.origin}
|
||||
disabled={!expert.enabled}
|
||||
{...batch.cardProps(expert.id, expert.name, expert.ownership)}
|
||||
>
|
||||
<CardHeader>
|
||||
<div className="flex min-w-0 items-start gap-3">
|
||||
@@ -558,87 +575,106 @@ export function ExpertsPage() {
|
||||
</Badge>
|
||||
)}
|
||||
</CardTitle>
|
||||
<CardDescription
|
||||
className="truncate"
|
||||
title={expert.owner}
|
||||
>
|
||||
<CardDescription className="truncate" title={expert.owner}>
|
||||
{expert.owner}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<ResourceCardMenuButton
|
||||
aria-label={t("common.more")}
|
||||
tone={
|
||||
expert.origin !== "package" && expert.enabled
|
||||
? "blue"
|
||||
: "neutral"
|
||||
}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
icon={MoreHorizontalIcon}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{expert.ownership === "system" && (
|
||||
<>
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem
|
||||
hidden={expert.origin === "package"}
|
||||
disabled={expert.enabled}
|
||||
onClick={() => setExpertEnabled(expert.id, true)}
|
||||
>
|
||||
<HugeiconsIcon icon={PlayIcon} strokeWidth={2} />
|
||||
{t("pages.experts.enable")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
hidden={expert.origin === "package"}
|
||||
disabled={!expert.enabled}
|
||||
onClick={() => setExpertEnabled(expert.id, false)}
|
||||
>
|
||||
<HugeiconsIcon icon={PauseIcon} strokeWidth={2} />
|
||||
{t("pages.experts.disable")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => openEditDialog(expert)}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
icon={Edit02Icon}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
{t("pages.experts.edit")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
hidden={expert.origin === "package"}
|
||||
onClick={() => duplicateExpert(expert)}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
icon={Copy02Icon}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
{t("pages.experts.duplicate")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator
|
||||
hidden={expert.origin === "package"}
|
||||
{batch.actions.selecting && expert.ownership === "system" ? (
|
||||
<Checkbox
|
||||
checked={batch.isSelected(expert.id)}
|
||||
disabled={remote.pending}
|
||||
aria-label={t("resources.batch.selectResource", {
|
||||
name: expert.name,
|
||||
})}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onCheckedChange={() => batch.toggle(expert.id)}
|
||||
/>
|
||||
) : (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<ResourceCardMenuButton
|
||||
aria-label={t("common.more")}
|
||||
tone={
|
||||
expert.origin !== "package" && expert.enabled
|
||||
? "blue"
|
||||
: "neutral"
|
||||
}
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
<DropdownMenuGroup hidden={expert.origin === "package"}>
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
onClick={() => setPendingDeletion(expert)}
|
||||
>
|
||||
<HugeiconsIcon icon={Delete02Icon} strokeWidth={2} />
|
||||
{t("pages.experts.delete")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
icon={MoreHorizontalIcon}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
{expert.ownership === "system" && (
|
||||
<>
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem
|
||||
disabled={expert.enabled}
|
||||
onClick={() =>
|
||||
setExpertEnabled(expert.id, true)
|
||||
}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
icon={PlayIcon}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
{t("pages.experts.enable")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
disabled={!expert.enabled}
|
||||
onClick={() =>
|
||||
setExpertEnabled(expert.id, false)
|
||||
}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
icon={PauseIcon}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
{t("pages.experts.disable")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => openEditDialog(expert)}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
icon={Edit02Icon}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
{t("pages.experts.edit")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
hidden={expert.origin === "package"}
|
||||
onClick={() => duplicateExpert(expert)}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
icon={Copy02Icon}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
{t("pages.experts.duplicate")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
</>
|
||||
)}
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
disabled={expert.origin === "package"}
|
||||
onClick={() => setPendingDeletion(expert)}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
icon={Delete02Icon}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
{t("pages.experts.delete")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
|
||||
@@ -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<string[]>([])
|
||||
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<boolean | null>(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() {
|
||||
<section className="flex h-[calc(100vh-4rem)] min-h-0 flex-none flex-col gap-4 p-4 pt-0 md:h-[calc(100vh-5rem)]">
|
||||
<ResourceList
|
||||
page={remote}
|
||||
pending={saving}
|
||||
pending={saving || batchPending}
|
||||
typeLabel={t("pages.models.type")}
|
||||
systemLabel={t("pages.models.systemModel")}
|
||||
userLabel={t("pages.models.userModel")}
|
||||
@@ -1079,7 +1129,11 @@ export function ModelsPage() {
|
||||
>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<Button type="button" variant="outline">
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={batchPending || remote.pending}
|
||||
>
|
||||
批量操作
|
||||
<HugeiconsIcon
|
||||
icon={ArrowRight01Icon}
|
||||
@@ -1145,6 +1199,14 @@ export function ModelsPage() {
|
||||
{label}
|
||||
</DropdownMenuItem>
|
||||
))}
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
disabled={selectedModels.length === 0 || remote.loading}
|
||||
onClick={openBatchDelete}
|
||||
>
|
||||
<HugeiconsIcon icon={Delete02Icon} strokeWidth={2} />
|
||||
{t("resources.modelBatchDelete.action")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
@@ -1160,6 +1222,7 @@ export function ModelsPage() {
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
disabled={batchPending || remote.pending}
|
||||
onClick={() => {
|
||||
setSelecting(true)
|
||||
setSelectionMenuOpen(true)
|
||||
@@ -1173,6 +1236,7 @@ export function ModelsPage() {
|
||||
render={
|
||||
<Button
|
||||
className="shrink-0"
|
||||
disabled={batchPending || remote.pending}
|
||||
onClick={() => openModelForm(null, false)}
|
||||
/>
|
||||
}
|
||||
@@ -1851,13 +1915,15 @@ export function ModelsPage() {
|
||||
!model.enabled &&
|
||||
"bg-muted ring-gray-300 dark:bg-muted dark:ring-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 &&
|
||||
(model.kind === "text"
|
||||
? "ring-2 ring-blue-500 dark:ring-blue-400"
|
||||
: "ring-2 ring-purple-500 dark:ring-purple-400"),
|
||||
? "after:border-blue-500 dark:after:border-blue-400"
|
||||
: "after:border-purple-500 dark:after:border-purple-400"),
|
||||
selected &&
|
||||
!model.enabled &&
|
||||
"ring-2 ring-gray-500 dark:ring-gray-400"
|
||||
"after:border-gray-500 dark:after:border-gray-400"
|
||||
)}
|
||||
key={model.id}
|
||||
onClick={
|
||||
@@ -2214,6 +2280,39 @@ export function ModelsPage() {
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
<AlertDialog
|
||||
open={batchDeleteOpen}
|
||||
onOpenChange={(open) => {
|
||||
if (!batchPending && !remote.pending) setBatchDeleteOpen(open)
|
||||
}}
|
||||
>
|
||||
<AlertDialogContent size="sm">
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>{t("resources.modelBatchDelete.title")}</AlertDialogTitle>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogDescription>
|
||||
{t("resources.modelBatchDelete.description", { count: selectedModels.length })}
|
||||
</AlertDialogDescription>
|
||||
{batchPending && (
|
||||
<p role="status" className="text-sm text-muted-foreground">
|
||||
{t("resources.modelBatchDelete.progress", batchDeleteProgress)}
|
||||
</p>
|
||||
)}
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel disabled={batchPending}>
|
||||
{t("resources.skillBatch.cancel")}
|
||||
</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
variant="destructive"
|
||||
loading={batchPending}
|
||||
disabled={selectedModels.length === 0}
|
||||
onClick={applyBatchDelete}
|
||||
>
|
||||
{t("resources.skillBatch.confirm")}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
<AlertDialog
|
||||
open={batchEnabled !== null}
|
||||
onOpenChange={(open) => {
|
||||
|
||||
@@ -11,20 +11,18 @@ import {
|
||||
type ResourceRow,
|
||||
} from "@/lib/resources"
|
||||
import { getCreatorInitial } from "@/lib/utils"
|
||||
import { ResourceList } from "@/components/resource-list"
|
||||
import { ResourceNotice } from "@/components/resource-notice"
|
||||
import { ResourceBatchActions } from "@/components/resource-batch-actions"
|
||||
import { useResourceList } from "@/hooks/use-resource-list"
|
||||
import { useResourceBatch } from "@/hooks/use-resource-batch"
|
||||
import { ResourceTagSummary } from "@/components/resource-tag-summary"
|
||||
import { ResourceCard } from "@/components/resource-card"
|
||||
import { ResourceCardMenuButton } from "@/components/resource-card-menu-button"
|
||||
import { ResourceEditorFooter } from "@/components/resource-editor-footer"
|
||||
import {
|
||||
RULE_PAGE_SIZE,
|
||||
useRulePage,
|
||||
type RuleType,
|
||||
} from "@/hooks/use-rule-page"
|
||||
import type { RuleType } from "@/hooks/use-rule-page"
|
||||
import { useState, type FormEvent } from "react"
|
||||
import {
|
||||
ArrowLeft01Icon,
|
||||
ArrowRight01Icon,
|
||||
Delete02Icon,
|
||||
DocumentValidationIcon,
|
||||
Edit02Icon,
|
||||
@@ -79,9 +77,6 @@ import {
|
||||
FieldLabel,
|
||||
} from "@/components/ui/field"
|
||||
import { Input } from "@/components/ui/input"
|
||||
import { ScrollArea } from "@/components/ui/scroll-area"
|
||||
import { PageSizeSelect } from "@/components/page-size-select"
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import type { AuthorizationSelection } from "@/lib/authorization-groups"
|
||||
|
||||
@@ -90,6 +85,7 @@ type AgentRule = {
|
||||
publisher?: string
|
||||
retired?: boolean
|
||||
revision: number
|
||||
enabled: boolean
|
||||
id: string
|
||||
name: string
|
||||
description: string
|
||||
@@ -110,6 +106,7 @@ function toRule(row: ResourceRow, language: string): AgentRule {
|
||||
publisher: row.publisher,
|
||||
retired: row.retired,
|
||||
revision: row.revision,
|
||||
enabled: row.enabled,
|
||||
name: text.name,
|
||||
description: text.description,
|
||||
tagIds: (row.tags ?? []).map((tag) => tag.id),
|
||||
@@ -124,21 +121,9 @@ function toRule(row: ResourceRow, language: string): AgentRule {
|
||||
|
||||
export function RulesPage() {
|
||||
const { t, i18n } = useTranslation()
|
||||
const [activeRuleType, setActiveRuleType] = useState<RuleType>("system")
|
||||
const [searchDraft, setSearchDraft] = useState("")
|
||||
const [search, setSearch] = useState("")
|
||||
const [cursors, setCursors] = useState<Record<RuleType, string[]>>({
|
||||
system: [""],
|
||||
user: [""],
|
||||
})
|
||||
const [pageSize, setPageSize] = useState(RULE_PAGE_SIZE)
|
||||
const pageCursors = cursors[activeRuleType]
|
||||
const remote = useRulePage(
|
||||
activeRuleType,
|
||||
pageCursors.at(-1) ?? "",
|
||||
search,
|
||||
pageSize
|
||||
)
|
||||
const remote = useResourceList("/rules")
|
||||
const batch = useResourceBatch("rule", remote)
|
||||
const activeRuleType = remote.type
|
||||
const rules = remote.items.map((row) => toRule(row, i18n.language))
|
||||
const subjects = useSubjects()
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
@@ -153,22 +138,6 @@ export function RulesPage() {
|
||||
const [forced, setForced] = useState(false)
|
||||
const importedRule = editingRule?.origin === "package"
|
||||
|
||||
const handleSearch = (event: FormEvent<HTMLFormElement>) => {
|
||||
event.preventDefault()
|
||||
if (remote.pending) return
|
||||
setSearch(searchDraft.trim())
|
||||
setCursors({ system: [""], user: [""] })
|
||||
remote.reload()
|
||||
}
|
||||
|
||||
const previousPage = (type: RuleType = activeRuleType) => {
|
||||
setCursors((current) => ({
|
||||
...current,
|
||||
[type]:
|
||||
current[type].length > 1 ? current[type].slice(0, -1) : current[type],
|
||||
}))
|
||||
}
|
||||
|
||||
const resetRuleOptions = () => {
|
||||
setAuthorization({ groupIds: [], memberIds: [] })
|
||||
setForced(false)
|
||||
@@ -240,388 +209,310 @@ export function RulesPage() {
|
||||
method: "DELETE",
|
||||
headers: match(rulePendingDeletion.revision),
|
||||
})
|
||||
if (rules.length === 1) previousPage(rulePendingDeletion.type)
|
||||
if (rules.length === 1) remote.previousPage(rulePendingDeletion.type)
|
||||
setRulePendingDeletion(null)
|
||||
}, t("resources.operationCompleted"))
|
||||
}
|
||||
|
||||
return (
|
||||
<section className="flex h-[calc(100vh-4rem)] min-h-0 flex-none flex-col gap-4 p-4 pt-0 md:h-[calc(100vh-5rem)]">
|
||||
<Tabs
|
||||
className="-m-1 min-h-0 flex-1 gap-4 overflow-hidden p-1"
|
||||
value={activeRuleType}
|
||||
onValueChange={(value) => {
|
||||
setActiveRuleType(value as RuleType)
|
||||
}}
|
||||
>
|
||||
<div className="flex shrink-0 flex-wrap items-center gap-3">
|
||||
<TabsList className="shrink-0" aria-label={t("pages.rules.type")}>
|
||||
<TabsTrigger value="system" disabled={remote.pending}>
|
||||
{t("pages.rules.systemRule")}
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="user" disabled={remote.pending}>
|
||||
{t("pages.rules.userRule")}
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<form
|
||||
className="order-2 flex basis-full items-center gap-2 sm:order-none sm:min-w-40 sm:max-w-44 sm:flex-none"
|
||||
onSubmit={handleSearch}
|
||||
>
|
||||
<Input
|
||||
type="search"
|
||||
value={searchDraft}
|
||||
onChange={(event) => setSearchDraft(event.target.value)}
|
||||
placeholder={t("resources.searchPlaceholder", {
|
||||
resource: t("pages.rules.title"),
|
||||
})}
|
||||
aria-label={t("resources.searchPlaceholder", {
|
||||
resource: t("pages.rules.title"),
|
||||
})}
|
||||
<ResourceList
|
||||
page={batch.page}
|
||||
error={subjects.error}
|
||||
typeLabel={t("pages.rules.type")}
|
||||
systemLabel={t("pages.rules.systemRule")}
|
||||
userLabel={t("pages.rules.userRule")}
|
||||
searchPlaceholder={t("resources.searchPlaceholder", {
|
||||
resource: t("pages.rules.title"),
|
||||
})}
|
||||
searchClassName="sm:max-w-44 sm:flex-none"
|
||||
actions={
|
||||
<div className="ms-auto flex shrink-0 items-center gap-2">
|
||||
<ResourceBatchActions
|
||||
key={batch.key}
|
||||
{...batch.actions}
|
||||
groups={subjects.groups}
|
||||
members={subjects.members}
|
||||
/>
|
||||
</form>
|
||||
{activeRuleType === "system" && (
|
||||
<Dialog open={dialogOpen} onOpenChange={handleDialogOpenChange}>
|
||||
<DialogTrigger
|
||||
render={
|
||||
<Button
|
||||
className="ms-auto shrink-0"
|
||||
onClick={() => {
|
||||
setEditingRule(null)
|
||||
resetRuleOptions()
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<HugeiconsIcon icon={PlusSignIcon} data-icon="inline-start" />
|
||||
{t("pages.rules.add")}
|
||||
</DialogTrigger>
|
||||
<DialogContent
|
||||
className="max-h-[calc(100vh-2rem)] overflow-y-auto sm:max-w-2xl"
|
||||
closeLabel={t("common.close")}
|
||||
aria-describedby={
|
||||
importedRule ? "imported-rule-readonly" : undefined
|
||||
}
|
||||
>
|
||||
<form
|
||||
key={editingRule?.id ?? "new-rule"}
|
||||
className="flex flex-col gap-6"
|
||||
onSubmit={handleSubmitRule}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{editingRule
|
||||
? t("pages.rules.editDialogTitle")
|
||||
: t("pages.rules.dialogTitle")}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<FieldGroup className="gap-4">
|
||||
<Field>
|
||||
<FieldLabel>{t("resources.availableScope")}</FieldLabel>
|
||||
<AuthorizationSelect
|
||||
groups={subjects.groups}
|
||||
members={subjects.members}
|
||||
id="rule-available"
|
||||
open={authorizationOpen}
|
||||
onOpenChange={setAuthorizationOpen}
|
||||
value={authorization}
|
||||
onValueChange={setAuthorization}
|
||||
title={t("resources.availableScope")}
|
||||
placeholder={t("resources.selectScope")}
|
||||
/>
|
||||
{importedRule && editingRule?.retired && (
|
||||
<p className="text-sm text-amber-700">
|
||||
{t("resources.retiredGrantsOnly")}
|
||||
</p>
|
||||
)}
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="rule-name">
|
||||
{t("pages.rules.name")}
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id="rule-name"
|
||||
name="name"
|
||||
defaultValue={editingRule?.name}
|
||||
placeholder={t("pages.rules.namePlaceholder")}
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="rule-description">
|
||||
{t("pages.rules.ruleDescription")}
|
||||
</FieldLabel>
|
||||
<Textarea
|
||||
className="max-h-32 min-h-20 resize-none overflow-y-auto"
|
||||
id="rule-description"
|
||||
name="description"
|
||||
defaultValue={editingRule?.description}
|
||||
placeholder={t(
|
||||
"pages.rules.ruleDescriptionPlaceholder"
|
||||
)}
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="rule-content">
|
||||
{t("pages.rules.content")}
|
||||
</FieldLabel>
|
||||
<Textarea
|
||||
className="max-h-64 min-h-40 resize-y overflow-y-auto"
|
||||
id="rule-content"
|
||||
name="content"
|
||||
defaultValue={editingRule?.content}
|
||||
disabled={importedRule}
|
||||
placeholder={t("pages.rules.contentPlaceholder")}
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field orientation="horizontal">
|
||||
<Checkbox
|
||||
id="rule-forced"
|
||||
checked={forced}
|
||||
disabled={importedRule}
|
||||
onCheckedChange={setForced}
|
||||
/>
|
||||
<div className="flex flex-col gap-1">
|
||||
<FieldLabel htmlFor="rule-forced">
|
||||
{t("pages.rules.forcedScope")}
|
||||
</FieldLabel>
|
||||
<FieldDescription>
|
||||
{t("pages.rules.forcedScopeDescription")}
|
||||
</FieldDescription>
|
||||
</div>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
<ResourceNotice
|
||||
error={remote.error || subjects.error}
|
||||
loading={false}
|
||||
pending={remote.pending}
|
||||
/>
|
||||
<ResourceEditorFooter
|
||||
id="imported-rule-readonly"
|
||||
reason={
|
||||
importedRule
|
||||
? t("resources.importedRuleReadOnly")
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<DialogClose
|
||||
render={<Button type="button" variant="outline" />}
|
||||
>
|
||||
{t("pages.rules.cancel")}
|
||||
</DialogClose>
|
||||
{activeRuleType === "system" && (
|
||||
<Dialog open={dialogOpen} onOpenChange={handleDialogOpenChange}>
|
||||
<DialogTrigger
|
||||
render={
|
||||
<Button
|
||||
type="submit"
|
||||
loading={remote.pending}
|
||||
className="shrink-0"
|
||||
disabled={remote.pending}
|
||||
>
|
||||
{editingRule
|
||||
? t("pages.rules.save")
|
||||
: t("pages.rules.create")}
|
||||
</Button>
|
||||
</ResourceEditorFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<TabsContent
|
||||
key={activeRuleType}
|
||||
value={activeRuleType}
|
||||
className="min-h-0 overflow-hidden"
|
||||
>
|
||||
<ScrollArea
|
||||
key={`${search}:${pageCursors.length}:${pageSize}`}
|
||||
className="h-full"
|
||||
>
|
||||
<div className="flex flex-col gap-4 p-px">
|
||||
<ResourceNotice
|
||||
error={remote.error || subjects.error}
|
||||
loading={remote.loading}
|
||||
pending={remote.pending}
|
||||
/>
|
||||
{remote.error && (
|
||||
<Button
|
||||
className="self-start"
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={remote.reload}
|
||||
onClick={() => {
|
||||
batch.exit()
|
||||
setEditingRule(null)
|
||||
resetRuleOptions()
|
||||
}}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{t("statistics.retry")}
|
||||
</Button>
|
||||
)}
|
||||
{!remote.loading && !remote.error && rules.length === 0 && (
|
||||
<p className="py-12 text-center text-sm text-muted-foreground">
|
||||
{t("statistics.empty")}
|
||||
</p>
|
||||
)}
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
|
||||
{rules.map((rule) => {
|
||||
return (
|
||||
<ResourceCard key={rule.id} origin={rule.origin}>
|
||||
<CardHeader>
|
||||
<div className="flex min-w-0 items-start gap-3">
|
||||
<Avatar size="lg">
|
||||
<AvatarFallback
|
||||
className={
|
||||
rule.type === "user"
|
||||
? "text-lg font-normal"
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{rule.type === "system" ? (
|
||||
<HugeiconsIcon
|
||||
icon={DocumentValidationIcon}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
) : (
|
||||
getCreatorInitial(rule.creator)
|
||||
)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="min-w-0 flex-1">
|
||||
<CardTitle className="flex min-w-0 items-center gap-2">
|
||||
<span className="truncate" title={rule.name}>
|
||||
{rule.name}
|
||||
</span>
|
||||
{rule.origin === "package" && (
|
||||
<Badge variant="amber" title={rule.publisher}>
|
||||
资源包导入
|
||||
</Badge>
|
||||
)}
|
||||
</CardTitle>
|
||||
<CardDescription
|
||||
className="truncate"
|
||||
title={rule.creator}
|
||||
>
|
||||
{rule.creator}
|
||||
</CardDescription>
|
||||
</div>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<ResourceCardMenuButton
|
||||
aria-label={t("common.more")}
|
||||
tone={
|
||||
rule.origin !== "package"
|
||||
? "blue"
|
||||
: "neutral"
|
||||
}
|
||||
/>
|
||||
<HugeiconsIcon icon={PlusSignIcon} data-icon="inline-start" />
|
||||
{t("pages.rules.add")}
|
||||
</DialogTrigger>
|
||||
<DialogContent
|
||||
className="max-h-[calc(100vh-2rem)] overflow-y-auto sm:max-w-2xl"
|
||||
closeLabel={t("common.close")}
|
||||
aria-describedby={
|
||||
importedRule ? "imported-rule-readonly" : undefined
|
||||
}
|
||||
>
|
||||
<form
|
||||
key={editingRule?.id ?? "new-rule"}
|
||||
className="flex flex-col gap-6"
|
||||
onSubmit={handleSubmitRule}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle>
|
||||
{editingRule
|
||||
? t("pages.rules.editDialogTitle")
|
||||
: t("pages.rules.dialogTitle")}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
<FieldGroup className="gap-4">
|
||||
<Field>
|
||||
<FieldLabel>{t("resources.availableScope")}</FieldLabel>
|
||||
<AuthorizationSelect
|
||||
groups={subjects.groups}
|
||||
members={subjects.members}
|
||||
id="rule-available"
|
||||
open={authorizationOpen}
|
||||
onOpenChange={setAuthorizationOpen}
|
||||
value={authorization}
|
||||
onValueChange={setAuthorization}
|
||||
title={t("resources.availableScope")}
|
||||
placeholder={t("resources.selectScope")}
|
||||
/>
|
||||
{importedRule && editingRule?.retired && (
|
||||
<p className="text-sm text-amber-700">
|
||||
{t("resources.retiredGrantsOnly")}
|
||||
</p>
|
||||
)}
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="rule-name">
|
||||
{t("pages.rules.name")}
|
||||
</FieldLabel>
|
||||
<Input
|
||||
id="rule-name"
|
||||
name="name"
|
||||
defaultValue={editingRule?.name}
|
||||
placeholder={t("pages.rules.namePlaceholder")}
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="rule-description">
|
||||
{t("pages.rules.ruleDescription")}
|
||||
</FieldLabel>
|
||||
<Textarea
|
||||
className="max-h-32 min-h-20 resize-none overflow-y-auto"
|
||||
id="rule-description"
|
||||
name="description"
|
||||
defaultValue={editingRule?.description}
|
||||
placeholder={t(
|
||||
"pages.rules.ruleDescriptionPlaceholder"
|
||||
)}
|
||||
/>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel htmlFor="rule-content">
|
||||
{t("pages.rules.content")}
|
||||
</FieldLabel>
|
||||
<Textarea
|
||||
className="max-h-64 min-h-40 resize-y overflow-y-auto"
|
||||
id="rule-content"
|
||||
name="content"
|
||||
defaultValue={editingRule?.content}
|
||||
disabled={importedRule}
|
||||
placeholder={t("pages.rules.contentPlaceholder")}
|
||||
required
|
||||
/>
|
||||
</Field>
|
||||
<Field orientation="horizontal">
|
||||
<Checkbox
|
||||
id="rule-forced"
|
||||
checked={forced}
|
||||
disabled={importedRule}
|
||||
onCheckedChange={setForced}
|
||||
/>
|
||||
<div className="flex flex-col gap-1">
|
||||
<FieldLabel htmlFor="rule-forced">
|
||||
{t("pages.rules.forcedScope")}
|
||||
</FieldLabel>
|
||||
<FieldDescription>
|
||||
{t("pages.rules.forcedScopeDescription")}
|
||||
</FieldDescription>
|
||||
</div>
|
||||
</Field>
|
||||
</FieldGroup>
|
||||
<ResourceNotice
|
||||
error={remote.error || subjects.error}
|
||||
loading={false}
|
||||
pending={remote.pending}
|
||||
/>
|
||||
<ResourceEditorFooter
|
||||
id="imported-rule-readonly"
|
||||
reason={
|
||||
importedRule
|
||||
? t("resources.importedRuleReadOnly")
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
<DialogClose
|
||||
render={<Button type="button" variant="outline" />}
|
||||
>
|
||||
{t("pages.rules.cancel")}
|
||||
</DialogClose>
|
||||
<Button
|
||||
type="submit"
|
||||
loading={remote.pending}
|
||||
disabled={remote.pending}
|
||||
>
|
||||
{editingRule
|
||||
? t("pages.rules.save")
|
||||
: t("pages.rules.create")}
|
||||
</Button>
|
||||
</ResourceEditorFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
|
||||
{rules.map((rule) => {
|
||||
return (
|
||||
<ResourceCard
|
||||
key={rule.id}
|
||||
origin={rule.origin}
|
||||
disabled={!rule.enabled}
|
||||
{...batch.cardProps(rule.id, rule.name, rule.type)}
|
||||
>
|
||||
<CardHeader>
|
||||
<div className="flex min-w-0 items-start gap-3">
|
||||
<Avatar size="lg">
|
||||
<AvatarFallback
|
||||
className={
|
||||
rule.type === "user"
|
||||
? "text-lg font-normal"
|
||||
: undefined
|
||||
}
|
||||
>
|
||||
{rule.type === "system" ? (
|
||||
<HugeiconsIcon
|
||||
icon={DocumentValidationIcon}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
) : (
|
||||
getCreatorInitial(rule.creator)
|
||||
)}
|
||||
</AvatarFallback>
|
||||
</Avatar>
|
||||
<div className="min-w-0 flex-1">
|
||||
<CardTitle className="flex min-w-0 items-center gap-2">
|
||||
<span className="truncate" title={rule.name}>
|
||||
{rule.name}
|
||||
</span>
|
||||
{rule.origin === "package" && (
|
||||
<Badge variant="amber" title={rule.publisher}>
|
||||
资源包导入
|
||||
</Badge>
|
||||
)}
|
||||
{!rule.enabled && (
|
||||
<Badge variant="outline">
|
||||
{t("resources.batch.disabled")}
|
||||
</Badge>
|
||||
)}
|
||||
</CardTitle>
|
||||
<CardDescription
|
||||
className="truncate"
|
||||
title={rule.creator}
|
||||
>
|
||||
{rule.creator}
|
||||
</CardDescription>
|
||||
</div>
|
||||
{batch.actions.selecting && rule.type === "system" ? (
|
||||
<Checkbox
|
||||
checked={batch.isSelected(rule.id)}
|
||||
disabled={remote.pending}
|
||||
aria-label={t("resources.batch.selectResource", {
|
||||
name: rule.name,
|
||||
})}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onCheckedChange={() => batch.toggle(rule.id)}
|
||||
/>
|
||||
) : (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<ResourceCardMenuButton
|
||||
aria-label={t("common.more")}
|
||||
tone={
|
||||
rule.origin !== "package" && rule.enabled
|
||||
? "blue"
|
||||
: "neutral"
|
||||
}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
icon={MoreHorizontalIcon}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuGroup hidden={rule.type !== "system"}>
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleEditRule(rule)}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
icon={MoreHorizontalIcon}
|
||||
icon={Edit02Icon}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuGroup
|
||||
hidden={rule.type !== "system"}
|
||||
>
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleEditRule(rule)}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
icon={Edit02Icon}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
{t("pages.rules.edit")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator
|
||||
hidden={
|
||||
rule.type !== "system" ||
|
||||
rule.origin === "package"
|
||||
}
|
||||
{t("pages.rules.edit")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator
|
||||
hidden={rule.type !== "system"}
|
||||
/>
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
disabled={rule.origin === "package"}
|
||||
onClick={() => setRulePendingDeletion(rule)}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
icon={Delete02Icon}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
<DropdownMenuGroup
|
||||
hidden={rule.origin === "package"}
|
||||
>
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
onClick={() => setRulePendingDeletion(rule)}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
icon={Delete02Icon}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
{t("pages.rules.delete")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p
|
||||
className="truncate text-muted-foreground"
|
||||
title={rule.description}
|
||||
>
|
||||
{rule.description?.trim() ||
|
||||
t("resources.noDescription")}
|
||||
</p>
|
||||
</CardContent>
|
||||
<CardFooter className="min-w-0 border-t">
|
||||
<ResourceTagSummary tagIds={rule.tagIds} />
|
||||
</CardFooter>
|
||||
</ResourceCard>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
<div className="flex shrink-0 flex-wrap items-center justify-between gap-3">
|
||||
<PageSizeSelect
|
||||
value={pageSize}
|
||||
onValueChange={(size) => {
|
||||
setPageSize(size)
|
||||
setCursors({ system: [""], user: [""] })
|
||||
}}
|
||||
disabled={remote.pending}
|
||||
/>
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm text-muted-foreground" aria-live="polite">
|
||||
{t("pages.sessionReporting.clients.cursorPage", {
|
||||
page: pageCursors.length,
|
||||
})}
|
||||
</span>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon-sm"
|
||||
disabled={
|
||||
remote.loading || remote.pending || pageCursors.length === 1
|
||||
}
|
||||
onClick={() => previousPage()}
|
||||
aria-label={t("pages.operationLogs.pagination.previous")}
|
||||
>
|
||||
<HugeiconsIcon icon={ArrowLeft01Icon} className="[[dir=rtl]_&]:rotate-180" />
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon-sm"
|
||||
disabled={remote.loading || remote.pending || !remote.nextCursor}
|
||||
onClick={() => {
|
||||
if (!remote.nextCursor) return
|
||||
setCursors((current) => ({
|
||||
...current,
|
||||
[activeRuleType]: [
|
||||
...current[activeRuleType],
|
||||
remote.nextCursor,
|
||||
],
|
||||
}))
|
||||
}}
|
||||
aria-label={t("pages.operationLogs.pagination.next")}
|
||||
>
|
||||
<HugeiconsIcon icon={ArrowRight01Icon} className="[[dir=rtl]_&]:rotate-180" />
|
||||
</Button>
|
||||
{t("pages.rules.delete")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p
|
||||
className="truncate text-muted-foreground"
|
||||
title={rule.description}
|
||||
>
|
||||
{rule.description?.trim() || t("resources.noDescription")}
|
||||
</p>
|
||||
</CardContent>
|
||||
<CardFooter className="min-w-0 border-t">
|
||||
<ResourceTagSummary tagIds={rule.tagIds} />
|
||||
</CardFooter>
|
||||
</ResourceCard>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</ResourceList>
|
||||
|
||||
<AlertDialog
|
||||
open={rulePendingDeletion !== null}
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
import { api } from "@/lib/api"
|
||||
import { useAppToast } from "@/components/animated-toast-provider"
|
||||
import {
|
||||
applySkillBatch,
|
||||
type SkillBatchChange,
|
||||
type SkillBatchProgress,
|
||||
} from "@/lib/skill-batch"
|
||||
import {
|
||||
base,
|
||||
grants,
|
||||
@@ -29,6 +35,7 @@ import { useTranslation } from "react-i18next"
|
||||
|
||||
import { AuthorizationSelect } from "@/components/authorization-select"
|
||||
import { SkillImportWizard } from "@/components/skill-import-wizard"
|
||||
import { SkillBatchActions } from "@/components/skill-batch-actions"
|
||||
import { ResourceEditorFooter } from "@/components/resource-editor-footer"
|
||||
import { SkillTagSelect } from "@/components/skill-tag-select"
|
||||
import {
|
||||
@@ -44,6 +51,7 @@ import {
|
||||
import { Avatar, AvatarFallback } from "@/components/ui/avatar"
|
||||
import { Badge } from "@/components/ui/badge"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Checkbox } from "@/components/ui/checkbox"
|
||||
import {
|
||||
CardContent,
|
||||
CardDescription,
|
||||
@@ -163,11 +171,22 @@ function formatBytes(bytes: number) {
|
||||
|
||||
export function SkillsPage() {
|
||||
const { t, i18n } = useTranslation()
|
||||
const { showToast } = useAppToast()
|
||||
const { tags: availableTags } = useSkillTags()
|
||||
const remote = useResourceList("/skills")
|
||||
const skills = remote.items.map((row) => toSkill(row, i18n.language))
|
||||
const subjects = useSubjects()
|
||||
const activeSkillType = remote.type
|
||||
const [selecting, setSelecting] = useState(false)
|
||||
const [selectedIds, setSelectedIds] = useState<string[]>([])
|
||||
const selectedRows = remote.items.filter(
|
||||
(skill) => skill.ownership_type === "system" && selectedIds.includes(skill.id)
|
||||
)
|
||||
const [batchProgress, setBatchProgress] = useState<SkillBatchProgress>({
|
||||
completed: 0,
|
||||
total: 0,
|
||||
})
|
||||
const selectionKey = `${remote.type}:${remote.search}:${remote.page}:${remote.pageSize}`
|
||||
const [dialogOpen, setDialogOpen] = useState(false)
|
||||
const [editingSkill, setEditingSkill] = useState<AgentSkill | null>(null)
|
||||
const [skillPendingDeletion, setSkillPendingDeletion] =
|
||||
@@ -188,6 +207,64 @@ export function SkillsPage() {
|
||||
const packageRequestId = useRef(0)
|
||||
const importedSkill = editingSkill?.origin === "package"
|
||||
|
||||
const exitSelection = () => {
|
||||
setSelecting(false)
|
||||
setSelectedIds([])
|
||||
}
|
||||
|
||||
const handleBatchApply = async (change: SkillBatchChange) => {
|
||||
if (remote.loading || selectedRows.length === 0) return false
|
||||
return remote.run(async () => {
|
||||
setBatchProgress({ completed: 0, total: selectedRows.length })
|
||||
const result = await applySkillBatch(
|
||||
selectedRows,
|
||||
change,
|
||||
api,
|
||||
setBatchProgress
|
||||
)
|
||||
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.skillBatch.result", {
|
||||
succeeded: result.succeeded.length,
|
||||
failed: result.failed.length,
|
||||
skipped: result.skipped.length,
|
||||
}),
|
||||
description: result.failed.length
|
||||
? `${t("resources.skillBatch.retryFailed")} ${result.failed
|
||||
.slice(0, 3)
|
||||
.map((failure) => `${failure.name}: ${failure.message}`)
|
||||
.join(";")}`
|
||||
: result.skipped.length
|
||||
? t("resources.skillBatch.packageSkipped", {
|
||||
count: result.skipped.length,
|
||||
})
|
||||
: undefined,
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
const toggleSelected = (id: string) => {
|
||||
if (remote.pending) return
|
||||
setSelectedIds((current) =>
|
||||
current.includes(id)
|
||||
? current.filter((selectedId) => selectedId !== id)
|
||||
: [...current, id]
|
||||
)
|
||||
}
|
||||
|
||||
const resetSkillOptions = () => {
|
||||
packageRequestId.current += 1
|
||||
setAuthorizationOpen(false)
|
||||
@@ -298,7 +375,7 @@ export function SkillsPage() {
|
||||
|
||||
const setSkillEnabled = async (id: string, enabled: boolean) => {
|
||||
const item = skills.find((s) => s.id === id)
|
||||
if (!item || item.origin === "package") return
|
||||
if (!item) return
|
||||
await remote.run(async () => {
|
||||
await api(base + `/skills/${id}/enabled`, {
|
||||
method: "PATCH",
|
||||
@@ -362,7 +439,29 @@ export function SkillsPage() {
|
||||
return (
|
||||
<section className="flex h-[calc(100vh-4rem)] min-h-0 flex-none flex-col gap-4 p-4 pt-0 md:h-[calc(100vh-5rem)]">
|
||||
<ResourceList
|
||||
page={remote}
|
||||
page={{
|
||||
...remote,
|
||||
setType: (type) => {
|
||||
exitSelection()
|
||||
remote.setType(type)
|
||||
},
|
||||
handleSearch: (event) => {
|
||||
exitSelection()
|
||||
remote.handleSearch(event)
|
||||
},
|
||||
setPageSize: (size) => {
|
||||
exitSelection()
|
||||
remote.setPageSize(size)
|
||||
},
|
||||
nextPage: () => {
|
||||
exitSelection()
|
||||
remote.nextPage()
|
||||
},
|
||||
previousPage: (type = remote.type) => {
|
||||
exitSelection()
|
||||
remote.previousPage(type)
|
||||
},
|
||||
}}
|
||||
error={subjects.error}
|
||||
typeLabel={t("pages.skills.type")}
|
||||
systemLabel={t("pages.skills.systemSkill")}
|
||||
@@ -372,14 +471,44 @@ export function SkillsPage() {
|
||||
})}
|
||||
searchClassName="sm:max-w-44 sm:flex-none"
|
||||
actions={
|
||||
<>
|
||||
<div className="ms-auto flex shrink-0 items-center gap-2">
|
||||
<SkillBatchActions
|
||||
key={selectionKey}
|
||||
selecting={selecting}
|
||||
selectedCount={selectedRows.length}
|
||||
pending={remote.pending}
|
||||
progress={batchProgress}
|
||||
onApply={handleBatchApply}
|
||||
disabled={
|
||||
remote.loading ||
|
||||
remote.pending ||
|
||||
(!selecting && skills.length === 0)
|
||||
}
|
||||
groups={subjects.groups}
|
||||
members={subjects.members}
|
||||
onEnter={() => {
|
||||
setSelectedIds([])
|
||||
setSelecting(true)
|
||||
}}
|
||||
onSelectAll={() =>
|
||||
setSelectedIds(
|
||||
skills
|
||||
.filter((skill) => skill.type === "system")
|
||||
.map((skill) => skill.id)
|
||||
)
|
||||
}
|
||||
onClear={() => setSelectedIds([])}
|
||||
onExit={exitSelection}
|
||||
/>
|
||||
{activeSkillType === "system" && (
|
||||
<Dialog open={dialogOpen} onOpenChange={handleDialogOpenChange}>
|
||||
<DialogTrigger
|
||||
render={
|
||||
<Button
|
||||
className="ms-auto shrink-0"
|
||||
className="shrink-0"
|
||||
disabled={remote.pending}
|
||||
onClick={() => {
|
||||
exitSelection()
|
||||
setEditingSkill(null)
|
||||
resetSkillOptions()
|
||||
}}
|
||||
@@ -631,7 +760,7 @@ export function SkillsPage() {
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
|
||||
@@ -639,12 +768,36 @@ export function SkillsPage() {
|
||||
const selectedTags = availableTags.filter((tag) =>
|
||||
skill.tagIds.includes(tag.id)
|
||||
)
|
||||
const selectable = selecting && skill.type === "system"
|
||||
const selected = selectable && selectedIds.includes(skill.id)
|
||||
|
||||
return (
|
||||
<ResourceCard
|
||||
key={skill.id}
|
||||
origin={skill.origin}
|
||||
disabled={!skill.enabled}
|
||||
selectable={selectable}
|
||||
selected={selected}
|
||||
onClick={selectable ? () => toggleSelected(skill.id) : undefined}
|
||||
onKeyDown={
|
||||
selectable
|
||||
? (event) => {
|
||||
if (event.target !== event.currentTarget) return
|
||||
if (event.key !== "Enter" && event.key !== " ") return
|
||||
event.preventDefault()
|
||||
toggleSelected(skill.id)
|
||||
}
|
||||
: undefined
|
||||
}
|
||||
role={selectable ? "checkbox" : undefined}
|
||||
aria-checked={selectable ? selected : undefined}
|
||||
aria-disabled={selectable && remote.pending ? true : undefined}
|
||||
aria-label={
|
||||
selectable
|
||||
? t("resources.skillBatch.selectSkill", { skill: skill.name })
|
||||
: undefined
|
||||
}
|
||||
tabIndex={selectable ? 0 : undefined}
|
||||
>
|
||||
<CardHeader>
|
||||
<div className="flex min-w-0 items-start gap-3">
|
||||
@@ -689,7 +842,14 @@ export function SkillsPage() {
|
||||
{skill.creator}
|
||||
</CardDescription>
|
||||
</div>
|
||||
{skill.type === "system" && (
|
||||
{selectable ? (
|
||||
<Checkbox
|
||||
checked={selected}
|
||||
aria-hidden="true"
|
||||
className="pointer-events-none mt-1 bg-background"
|
||||
tabIndex={-1}
|
||||
/>
|
||||
) : skill.type === "system" ? (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
@@ -711,7 +871,6 @@ export function SkillsPage() {
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem
|
||||
hidden={skill.origin === "package"}
|
||||
disabled={skill.enabled}
|
||||
onClick={() => setSkillEnabled(skill.id, true)}
|
||||
>
|
||||
@@ -719,7 +878,6 @@ export function SkillsPage() {
|
||||
{t("pages.skills.enable")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
hidden={skill.origin === "package"}
|
||||
disabled={!skill.enabled}
|
||||
onClick={() => setSkillEnabled(skill.id, false)}
|
||||
>
|
||||
@@ -736,14 +894,11 @@ export function SkillsPage() {
|
||||
{t("pages.skills.edit")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator
|
||||
hidden={skill.origin === "package"}
|
||||
/>
|
||||
<DropdownMenuGroup
|
||||
hidden={skill.origin === "package"}
|
||||
>
|
||||
<DropdownMenuSeparator />
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
disabled={skill.origin === "package"}
|
||||
onClick={() => setSkillPendingDeletion(skill)}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
@@ -755,7 +910,7 @@ export function SkillsPage() {
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
)}
|
||||
) : null}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
|
||||
@@ -101,6 +101,9 @@ import {
|
||||
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs"
|
||||
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 { Checkbox } from "@/components/ui/checkbox"
|
||||
import { Textarea } from "@/components/ui/textarea"
|
||||
import type { AuthorizationSelection } from "@/lib/authorization-groups"
|
||||
|
||||
@@ -240,6 +243,7 @@ export function ToolsPage() {
|
||||
const { t, i18n } = useTranslation()
|
||||
const { tags: availableTags } = useSkillTags()
|
||||
const remote = useResourceList("/connectors")
|
||||
const batch = useResourceBatch("connector", remote)
|
||||
const servers = remote.items.map((row) => toServer(row, i18n.language))
|
||||
const reload = remote.reload
|
||||
const subjects = useSubjects()
|
||||
@@ -313,7 +317,6 @@ export function ToolsPage() {
|
||||
]
|
||||
|
||||
const setConnectionEnabled = async (server: McpServer) => {
|
||||
if (server.origin === "package") return
|
||||
await remote.run(async () => {
|
||||
await api(base + `/connectors/${server.id}/enabled`, {
|
||||
method: "PATCH",
|
||||
@@ -574,7 +577,7 @@ export function ToolsPage() {
|
||||
return (
|
||||
<section className="flex h-[calc(100vh-4rem)] min-h-0 flex-none flex-col gap-4 p-4 pt-0 md:h-[calc(100vh-5rem)]">
|
||||
<ResourceList
|
||||
page={remote}
|
||||
page={batch.page}
|
||||
error={subjects.error}
|
||||
typeLabel={t("pages.tools.type")}
|
||||
systemLabel={t("pages.tools.systemTool")}
|
||||
@@ -584,14 +587,22 @@ export function ToolsPage() {
|
||||
})}
|
||||
searchClassName="sm:max-w-44 sm:flex-none"
|
||||
actions={
|
||||
<>
|
||||
<div className="ms-auto flex shrink-0 items-center gap-2">
|
||||
<ResourceBatchActions
|
||||
key={batch.key}
|
||||
{...batch.actions}
|
||||
groups={subjects.groups}
|
||||
members={subjects.members}
|
||||
/>
|
||||
{activeType === "system" && (
|
||||
<Dialog open={dialogOpen} onOpenChange={handleDialogOpenChange}>
|
||||
<DialogTrigger
|
||||
render={
|
||||
<Button
|
||||
className="ms-auto shrink-0"
|
||||
className="shrink-0"
|
||||
disabled={remote.pending}
|
||||
onClick={() => {
|
||||
batch.exit()
|
||||
resetDraft()
|
||||
}}
|
||||
/>
|
||||
@@ -1010,7 +1021,7 @@ export function ToolsPage() {
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<div className="grid gap-4 sm:grid-cols-2 xl:grid-cols-3">
|
||||
@@ -1020,6 +1031,7 @@ export function ToolsPage() {
|
||||
key={server.id}
|
||||
origin={server.origin}
|
||||
disabled={!server.enabled}
|
||||
{...batch.cardProps(server.id, server.name, server.type)}
|
||||
>
|
||||
<CardHeader>
|
||||
<div className="flex min-w-0 items-start gap-3">
|
||||
@@ -1059,7 +1071,17 @@ export function ToolsPage() {
|
||||
{server.creator}
|
||||
</CardDescription>
|
||||
</div>
|
||||
{
|
||||
{batch.actions.selecting && server.type === "system" ? (
|
||||
<Checkbox
|
||||
checked={batch.isSelected(server.id)}
|
||||
disabled={remote.pending}
|
||||
aria-label={t("resources.batch.selectResource", {
|
||||
name: server.name,
|
||||
})}
|
||||
onClick={(event) => event.stopPropagation()}
|
||||
onCheckedChange={() => batch.toggle(server.id)}
|
||||
/>
|
||||
) : (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
@@ -1080,17 +1102,15 @@ export function ToolsPage() {
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
<DropdownMenuGroup hidden={server.type !== "system"}>
|
||||
{server.origin !== "package" && (
|
||||
<DropdownMenuItem
|
||||
onClick={() => setConnectionEnabled(server)}
|
||||
>
|
||||
{t(
|
||||
server.enabled
|
||||
? "resources.disable"
|
||||
: "resources.enable"
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
)}
|
||||
<DropdownMenuItem
|
||||
onClick={() => setConnectionEnabled(server)}
|
||||
>
|
||||
{t(
|
||||
server.enabled
|
||||
? "resources.disable"
|
||||
: "resources.enable"
|
||||
)}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => handleViewTools(server)}
|
||||
>
|
||||
@@ -1136,16 +1156,12 @@ export function ToolsPage() {
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuGroup>
|
||||
<DropdownMenuSeparator
|
||||
hidden={
|
||||
server.type !== "system" ||
|
||||
server.origin === "package"
|
||||
}
|
||||
hidden={server.type !== "system"}
|
||||
/>
|
||||
<DropdownMenuGroup
|
||||
hidden={server.origin === "package"}
|
||||
>
|
||||
<DropdownMenuGroup>
|
||||
<DropdownMenuItem
|
||||
variant="destructive"
|
||||
disabled={server.origin === "package"}
|
||||
onClick={() => setServerPendingDeletion(server)}
|
||||
>
|
||||
<HugeiconsIcon
|
||||
@@ -1157,7 +1173,7 @@ export function ToolsPage() {
|
||||
</DropdownMenuGroup>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
}
|
||||
)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
@@ -1263,7 +1279,11 @@ export function ToolsPage() {
|
||||
{remote.pending && !toolDrafts.length && (
|
||||
<TableRow>
|
||||
<TableCell
|
||||
colSpan={viewingServer?.authorizationMode === "centralized" ? 3 : 2}
|
||||
colSpan={
|
||||
viewingServer?.authorizationMode === "centralized"
|
||||
? 3
|
||||
: 2
|
||||
}
|
||||
className="h-28 text-center"
|
||||
>
|
||||
<TableLoading />
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
|
||||
import { deleteModelBatch } from "../src/lib/model-batch-delete.ts"
|
||||
|
||||
const model = (id, type = "system") => ({ id, displayName: `模型 ${id}`, type })
|
||||
|
||||
test("model batch deletion deletes each selected system model once", async () => {
|
||||
const calls = []
|
||||
const progress = []
|
||||
const result = await deleteModelBatch(
|
||||
[model("text"), model("image"), model("video"), model("text"), model("personal", "user")],
|
||||
async (path, init) => calls.push([path, init]),
|
||||
(value) => progress.push(value)
|
||||
)
|
||||
assert.deepEqual(calls, ["text", "image", "video"].map((id) => [`/api/admin/v1/models/${id}`, { method: "DELETE" }]))
|
||||
assert.deepEqual(result, { succeeded: ["text", "image", "video"], failed: [] })
|
||||
assert.deepEqual(progress, [1, 2, 3].map((completed) => ({ completed, total: 3 })))
|
||||
})
|
||||
|
||||
test("model batch deletion collects per-model errors and continues without automatic retries", async () => {
|
||||
const calls = []
|
||||
const result = await deleteModelBatch([model("a"), model("b"), model("c")], async (path) => {
|
||||
calls.push(path)
|
||||
if (path.endsWith("/b")) throw new Error("删除失败")
|
||||
})
|
||||
assert.equal(calls.length, 3)
|
||||
assert.deepEqual(result, {
|
||||
succeeded: ["a", "c"],
|
||||
failed: [{ id: "b", name: "模型 b", message: "删除失败" }],
|
||||
})
|
||||
const retried = []
|
||||
await deleteModelBatch([model("a"), model("b"), model("c")].filter((item) => result.failed.some(({ id }) => id === item.id)), async (path) => retried.push(path))
|
||||
assert.deepEqual(retried, ["/api/admin/v1/models/b"])
|
||||
})
|
||||
|
||||
test("empty and user-only model batches perform no requests", async () => {
|
||||
for (const rows of [[], [model("personal", "user")]]) {
|
||||
assert.deepEqual(await deleteModelBatch(rows, async () => assert.fail("Unexpected deletion")), { succeeded: [], failed: [] })
|
||||
}
|
||||
})
|
||||
|
||||
test("model delete accepts a 204 response through the real HTTP client", async (t) => {
|
||||
const calls = []
|
||||
t.mock.method(globalThis, "fetch", async (path, init) => {
|
||||
calls.push({ path, ...init })
|
||||
return new Response(null, { status: 204 })
|
||||
})
|
||||
assert.deepEqual(await deleteModelBatch([model("a")]), { succeeded: ["a"], failed: [] })
|
||||
assert.equal(calls[0].path, "/api/admin/v1/models/a")
|
||||
assert.equal(calls[0].method, "DELETE")
|
||||
assert.equal(calls[0].credentials, "include")
|
||||
assert.equal(calls[0].body, undefined)
|
||||
})
|
||||
@@ -0,0 +1,48 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
import { applyResourceBatch } from "../src/lib/resource-batch.ts"
|
||||
|
||||
const paths = { skill: "skills", expert: "experts", connector: "connectors", rule: "rules" }
|
||||
const row = (id, extra = {}) => ({
|
||||
id, name: `Canonical ${id}`, description: `Description ${id}`, revision: 7,
|
||||
ownership_type: "system", origin: "admin", content: "Original rule content", prompt: "Original expert prompt",
|
||||
grants: [{ group_id: "required", usage_requirement: "required" }], ...extra,
|
||||
})
|
||||
|
||||
for (const [kind, endpoint] of Object.entries(paths)) {
|
||||
test(`${kind}: toggles include package resources and version every request`, async () => {
|
||||
for (const action of ["enable", "disable"]) {
|
||||
const calls = []
|
||||
const result = await applyResourceBatch(kind, [row("local"), row("package", { origin: "package" }), row("personal", { ownership_type: "user" })], { action }, async (path, init) => calls.push({ path, ...init }))
|
||||
assert.deepEqual(result, { succeeded: ["local", "package"], skipped: ["personal"], failed: [] })
|
||||
assert.deepEqual(calls.map(({ path, method, headers, body }) => [path, method, headers, JSON.parse(body)]), ["local", "package"].map((id) => [`/api/admin/v1/${endpoint}/${id}/enabled`, "PATCH", { "If-Match": '"7"' }, { enabled: action === "enable" }]))
|
||||
}
|
||||
})
|
||||
test(`${kind}: tags preserve canonical required content and omit unrelated configuration`, async () => {
|
||||
const calls = []
|
||||
const result = await applyResourceBatch(kind, [row("local"), row("package", { origin: "package" })], { action: "tags", tagIds: ["a", "a", "b"] }, async (path, init) => calls.push({ path, ...init }))
|
||||
assert.deepEqual(result, { succeeded: ["local"], skipped: ["package"], failed: [] })
|
||||
assert.equal(calls[0].path, `/api/admin/v1/${endpoint}/local`)
|
||||
assert.deepEqual(JSON.parse(calls[0].body), { name: "Canonical local", description: "Description local", ...(kind === "expert" ? { prompt: "Original expert prompt" } : {}), ...(kind === "rule" ? { content: "Original rule content" } : {}), tag_ids: ["a", "b"] })
|
||||
await applyResourceBatch(kind, [row("local")], { action: "tags", tagIds: [] }, async (_, init) => assert.deepEqual(JSON.parse(init.body).tag_ids, []))
|
||||
})
|
||||
test(`${kind}: authorization replaces scope using the grants API and preserves required rules`, async () => {
|
||||
const calls = []
|
||||
await applyResourceBatch(kind, [row("package", { origin: "package" })], { action: "authorization", authorization: { groupIds: ["required", "new"], memberIds: ["member"] } }, async (path, init) => calls.push({ path, ...init }))
|
||||
assert.equal(calls[0].path, `/api/admin/v1/resources/${kind}/package/grants`)
|
||||
assert.deepEqual(JSON.parse(calls[0].body), { grants: [{ group_id: "required", usage_requirement: "required" }, { group_id: "new", usage_requirement: "optional" }, { user_id: "member", usage_requirement: "optional" }] })
|
||||
assert.deepEqual(calls[0].headers, { "If-Match": '"7"' })
|
||||
})
|
||||
test(`${kind}: delete skips package/personal resources, continues after conflict, and reports progress`, async () => {
|
||||
const calls = [], progress = []
|
||||
const result = await applyResourceBatch(kind, [row("a"), row("a"), row("stale"), row("package", { origin: "package" }), row("personal", { ownership_type: "user" }), row("last")], { action: "delete" }, async (path, init) => {
|
||||
calls.push({ path, ...init })
|
||||
if (path.endsWith("/stale")) throw new Error("资源已更新,请刷新后重试")
|
||||
}, (value) => progress.push(value))
|
||||
assert.deepEqual(result.succeeded, ["a", "last"])
|
||||
assert.deepEqual(result.skipped, ["package", "personal"])
|
||||
assert.deepEqual(result.failed, [{ id: "stale", name: "Canonical stale", message: "资源已更新,请刷新后重试" }])
|
||||
assert.deepEqual(calls, ["a", "stale", "last"].map((id) => ({ path: `/api/admin/v1/${endpoint}/${id}`, method: "DELETE", headers: { "If-Match": '"7"' } })))
|
||||
assert.deepEqual(progress, [1, 2, 3, 4, 5].map((completed) => ({ completed, total: 5 })))
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
import assert from "node:assert/strict"
|
||||
import test from "node:test"
|
||||
|
||||
import { applySkillBatch } from "../src/lib/skill-batch.ts"
|
||||
|
||||
function skill(id, overrides = {}) {
|
||||
return {
|
||||
id,
|
||||
name: `Canonical ${id}`,
|
||||
description: `Canonical description ${id}`,
|
||||
ownership_type: "system",
|
||||
origin: "admin",
|
||||
revision: 7,
|
||||
grants: [],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
for (const action of ["enable", "disable"]) {
|
||||
test(`${action} uses versioned requests for local/package skills and skips personal skills`, async () => {
|
||||
const requests = []
|
||||
const progress = []
|
||||
const result = await applySkillBatch(
|
||||
[skill("a"), skill("b", { revision: 12 }), skill("package", { origin: "package" }), skill("personal", { ownership_type: "user" })],
|
||||
{ action },
|
||||
async (path, init) => requests.push({ path, ...init }),
|
||||
(value) => progress.push(value)
|
||||
)
|
||||
assert.deepEqual(requests.map(({ path, method, headers, body }) => [path, method, headers["If-Match"], JSON.parse(body)]), [
|
||||
["/api/admin/v1/skills/a/enabled", "PATCH", '"7"', { enabled: action === "enable" }],
|
||||
["/api/admin/v1/skills/b/enabled", "PATCH", '"12"', { enabled: action === "enable" }],
|
||||
["/api/admin/v1/skills/package/enabled", "PATCH", '"7"', { enabled: action === "enable" }],
|
||||
])
|
||||
assert.deepEqual(result, { succeeded: ["a", "b", "package"], skipped: ["personal"], failed: [] })
|
||||
assert.deepEqual(progress, [1, 2, 3, 4].map((completed) => ({ completed, total: 4 })))
|
||||
})
|
||||
}
|
||||
|
||||
test("delete sends If-Match and skips package and personal skills", async () => {
|
||||
const calls = []
|
||||
const result = await applySkillBatch(
|
||||
[skill("a"), skill("b", { revision: 8 }), skill("package", { origin: "package" }), skill("personal", { ownership_type: "user" })],
|
||||
{ action: "delete" },
|
||||
async (path, init) => calls.push({ path, ...init })
|
||||
)
|
||||
assert.deepEqual(calls, [
|
||||
{ path: "/api/admin/v1/skills/a", method: "DELETE", headers: { "If-Match": '"7"' } },
|
||||
{ path: "/api/admin/v1/skills/b", method: "DELETE", headers: { "If-Match": '"8"' } },
|
||||
])
|
||||
assert.deepEqual(result, { succeeded: ["a", "b"], skipped: ["package", "personal"], failed: [] })
|
||||
})
|
||||
|
||||
test("delete reports reference/version conflicts and continues with remaining skills", async () => {
|
||||
const calls = []
|
||||
const result = await applySkillBatch([skill("referenced"), skill("stale"), skill("ok")], { action: "delete" }, async (path) => {
|
||||
calls.push(path)
|
||||
if (path.endsWith("/referenced")) throw new Error("资源仍被引用")
|
||||
if (path.endsWith("/stale")) throw new Error("资源已更新,请刷新后重试")
|
||||
})
|
||||
assert.equal(calls.length, 3)
|
||||
assert.deepEqual(result.succeeded, ["ok"])
|
||||
assert.deepEqual(result.failed.map(({ id, message }) => [id, message]), [
|
||||
["referenced", "资源仍被引用"], ["stale", "资源已更新,请刷新后重试"],
|
||||
])
|
||||
})
|
||||
|
||||
test("package-only delete completes without sending requests", async () => {
|
||||
const result = await applySkillBatch([skill("package", { origin: "package" })], { action: "delete" }, async () => assert.fail("Package skill cannot be deleted"))
|
||||
assert.deepEqual(result, { succeeded: [], skipped: ["package"], failed: [] })
|
||||
})
|
||||
|
||||
test("tag replacement preserves canonical metadata and omits content, grants and enabled", async () => {
|
||||
const requests = []
|
||||
const resource = skill("a", {
|
||||
name_i18n: { "zh-CN": "显示名称" },
|
||||
description_i18n: { "zh-CN": "显示说明" },
|
||||
})
|
||||
await applySkillBatch([resource, skill("package", { origin: "package" })], { action: "tags", tagIds: ["review", "security", "review"] }, async (path, init) => requests.push({ path, ...init }))
|
||||
assert.equal(requests.length, 1)
|
||||
assert.equal(requests[0].path, "/api/admin/v1/skills/a")
|
||||
assert.equal(requests[0].method, "PUT")
|
||||
assert.equal(requests[0].headers["If-Match"], '"7"')
|
||||
assert.deepEqual(JSON.parse(requests[0].body), {
|
||||
name: resource.name,
|
||||
description: resource.description,
|
||||
tag_ids: ["review", "security"],
|
||||
})
|
||||
await applySkillBatch([resource], { action: "tags", tagIds: [] }, async (_, init) => {
|
||||
assert.deepEqual(JSON.parse(init.body).tag_ids, [])
|
||||
})
|
||||
})
|
||||
|
||||
test("package-only tag batches complete by skipping every resource without requests", async () => {
|
||||
const progress = []
|
||||
const result = await applySkillBatch(
|
||||
[skill("package-a", { origin: "package" }), skill("package-b", { origin: "package" })],
|
||||
{ action: "tags", tagIds: ["review"] },
|
||||
async () => assert.fail("Package tags must not be written"),
|
||||
(value) => progress.push(value)
|
||||
)
|
||||
assert.deepEqual(result, { succeeded: [], failed: [], skipped: ["package-a", "package-b"] })
|
||||
assert.deepEqual(progress, [{ completed: 1, total: 2 }, { completed: 2, total: 2 }])
|
||||
})
|
||||
|
||||
test("authorization uses the grants endpoint for local/package skills and preserves required flags", async () => {
|
||||
const resources = [skill("local"), skill("package", { origin: "package" })].map((row) => ({
|
||||
...row,
|
||||
grants: [
|
||||
{ group_id: "existing", usage_requirement: "required" },
|
||||
{ user_id: "member", usage_requirement: "required" },
|
||||
{ user_id: "removed", usage_requirement: "optional" },
|
||||
],
|
||||
}))
|
||||
const calls = []
|
||||
const result = await applySkillBatch(resources, { action: "authorization", authorization: { groupIds: ["existing", "new", "existing"], memberIds: ["member", "new-user"] } }, async (path, init) => calls.push({ path, ...init }))
|
||||
assert.deepEqual(result.succeeded, ["local", "package"])
|
||||
assert.deepEqual(result.skipped, [])
|
||||
assert.deepEqual(calls.map((call) => call.path), ["/api/admin/v1/resources/skill/local/grants", "/api/admin/v1/resources/skill/package/grants"])
|
||||
for (const call of calls) {
|
||||
assert.equal(call.method, "PUT")
|
||||
assert.equal(call.headers["If-Match"], '"7"')
|
||||
assert.deepEqual(JSON.parse(call.body), { grants: [
|
||||
{ group_id: "existing", usage_requirement: "required" },
|
||||
{ group_id: "new", usage_requirement: "optional" },
|
||||
{ user_id: "member", usage_requirement: "required" },
|
||||
{ user_id: "new-user", usage_requirement: "optional" },
|
||||
] })
|
||||
}
|
||||
})
|
||||
|
||||
test("failures do not abort the batch or retry stale revisions automatically", async () => {
|
||||
const calls = []
|
||||
const progress = []
|
||||
const result = await applySkillBatch([skill("conflict"), skill("ok"), skill("retired", { origin: "package" })], { action: "authorization", authorization: { groupIds: ["group"], memberIds: [] } }, async (path) => {
|
||||
calls.push(path)
|
||||
if (path.includes("/conflict/")) throw new Error("资源版本冲突")
|
||||
if (path.includes("/retired/")) throw new Error("退役资源只能撤销现有授权")
|
||||
}, (value) => progress.push(value.completed))
|
||||
assert.equal(calls.length, 3)
|
||||
assert.deepEqual(result.succeeded, ["ok"])
|
||||
assert.deepEqual(result.failed, [
|
||||
{ id: "conflict", name: "Canonical conflict", message: "资源版本冲突" },
|
||||
{ id: "retired", name: "Canonical retired", message: "退役资源只能撤销现有授权" },
|
||||
])
|
||||
assert.deepEqual(progress, [1, 2, 3])
|
||||
})
|
||||
|
||||
test("a running batch captures the tag draft and deduplicates resources", async () => {
|
||||
let release
|
||||
const first = new Promise((resolve) => { release = resolve })
|
||||
const change = { action: "tags", tagIds: ["original"] }
|
||||
const bodies = []
|
||||
const execution = applySkillBatch([skill("a"), skill("a"), skill("b")], change, async (_, init) => {
|
||||
bodies.push(JSON.parse(init.body))
|
||||
if (bodies.length === 1) await first
|
||||
})
|
||||
change.tagIds.push("changed-during-submit")
|
||||
release()
|
||||
const result = await execution
|
||||
assert.deepEqual(result.succeeded, ["a", "b"])
|
||||
assert.deepEqual(bodies.map((body) => body.tag_ids), [["original"], ["original"]])
|
||||
})
|
||||
|
||||
test("authorization captures both recipient lists before submission", async () => {
|
||||
let release
|
||||
const first = new Promise((resolve) => { release = resolve })
|
||||
const change = { action: "authorization", authorization: { groupIds: ["group"], memberIds: ["member"] } }
|
||||
const bodies = []
|
||||
const execution = applySkillBatch([skill("a"), skill("b")], change, async (_, init) => {
|
||||
bodies.push(JSON.parse(init.body))
|
||||
if (bodies.length === 1) await first
|
||||
})
|
||||
change.authorization.groupIds.push("other")
|
||||
change.authorization.memberIds.length = 0
|
||||
release()
|
||||
await execution
|
||||
assert.deepEqual(bodies[0], bodies[1])
|
||||
assert.deepEqual(bodies[1].grants, [
|
||||
{ group_id: "group", usage_requirement: "optional" },
|
||||
{ user_id: "member", usage_requirement: "optional" },
|
||||
])
|
||||
})
|
||||
|
||||
test("the real HTTP client sends credentials, JSON and If-Match and exposes API errors", async (t) => {
|
||||
const calls = []
|
||||
t.mock.method(globalThis, "fetch", async (path, init) => {
|
||||
calls.push({ path, ...init })
|
||||
return new Response(JSON.stringify({ error: { message: "版本不匹配" } }), { status: 409, headers: { "Content-Type": "application/json" } })
|
||||
})
|
||||
const result = await applySkillBatch([skill("a")], { action: "enable" })
|
||||
assert.equal(calls[0].credentials, "include")
|
||||
assert.equal(calls[0].headers["Content-Type"], "application/json")
|
||||
assert.equal(calls[0].headers["If-Match"], '"7"')
|
||||
assert.equal(result.failed[0].message, "版本不匹配")
|
||||
})
|
||||
@@ -3141,6 +3141,42 @@ paths:
|
||||
schema:
|
||||
type: string
|
||||
format: uuid
|
||||
/api/admin/v1/rules/{id}/enabled:
|
||||
patch:
|
||||
summary: 启停规则
|
||||
description: 支持管理员创建和资源包导入的规则。手动启停设置会保留到后续资源包更新。
|
||||
parameters:
|
||||
- name: id
|
||||
in: path
|
||||
required: true
|
||||
schema: {type: string, format: uuid}
|
||||
- name: If-Match
|
||||
in: header
|
||||
required: true
|
||||
description: 上次读取返回的 ETag,例如 "1"。
|
||||
schema: {type: string}
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
required: [enabled]
|
||||
properties:
|
||||
enabled: {type: boolean}
|
||||
responses:
|
||||
'200':
|
||||
description: 更新后的规则
|
||||
content:
|
||||
application/json:
|
||||
schema: {$ref: '#/components/schemas/RuleResource'}
|
||||
'400': {$ref: '#/components/responses/ResourceError400'}
|
||||
'401': {$ref: '#/components/responses/ResourceError401'}
|
||||
'403': {$ref: '#/components/responses/ResourceError403'}
|
||||
'404': {$ref: '#/components/responses/ResourceError404'}
|
||||
'409': {$ref: '#/components/responses/ResourceError409'}
|
||||
'412': {$ref: '#/components/responses/ResourceError412'}
|
||||
'500': {$ref: '#/components/responses/ResourceError500'}
|
||||
/api/admin/v1/skills:
|
||||
get:
|
||||
summary: 查询Skill
|
||||
@@ -3367,7 +3403,8 @@ paths:
|
||||
format: uuid
|
||||
/api/admin/v1/skills/{id}/enabled:
|
||||
patch:
|
||||
summary: 启停Skill
|
||||
summary: 启停技能
|
||||
description: 支持管理员创建和资源包导入的技能。手动启停设置会保留到后续资源包更新。
|
||||
responses:
|
||||
'200':
|
||||
description: 启停Skill
|
||||
@@ -3634,6 +3671,7 @@ paths:
|
||||
/api/admin/v1/experts/{id}/enabled:
|
||||
patch:
|
||||
summary: 启停Expert
|
||||
description: 支持管理员创建和资源包导入的专家。手动启停设置会保留到后续资源包更新。
|
||||
responses:
|
||||
'200':
|
||||
description: 启停Expert
|
||||
@@ -3907,6 +3945,7 @@ paths:
|
||||
/api/admin/v1/connectors/{id}/enabled:
|
||||
patch:
|
||||
summary: 启停Connector
|
||||
description: 支持管理员创建和资源包导入的连接器。手动启停设置会保留到后续资源包更新。
|
||||
responses:
|
||||
'200':
|
||||
description: 启停Connector
|
||||
@@ -7699,6 +7738,11 @@ components:
|
||||
RuleResource:
|
||||
type: object
|
||||
properties:
|
||||
description:
|
||||
type: string
|
||||
tags:
|
||||
type: array
|
||||
items: {$ref: '#/components/schemas/ResourceTag'}
|
||||
shared_users:
|
||||
type: array
|
||||
readOnly: true
|
||||
@@ -7747,6 +7791,12 @@ components:
|
||||
RuleInput:
|
||||
type: object
|
||||
properties:
|
||||
description:
|
||||
type: string
|
||||
tag_ids:
|
||||
type: array
|
||||
items: {type: string, format: uuid}
|
||||
description: 替换系统规则的标签;省略时保留已有标签,空数组清空标签。
|
||||
content:
|
||||
type: string
|
||||
name:
|
||||
|
||||
@@ -167,6 +167,9 @@ UPDATE
|
||||
experts
|
||||
SET
|
||||
enabled = (sqlc.arg(DATA)::jsonb ->> 'enabled')::boolean,
|
||||
admin_overrides = CASE WHEN sqlc.arg(DATA)::jsonb ? 'admin_overrides' THEN
|
||||
sqlc.arg(DATA)::jsonb -> 'admin_overrides'
|
||||
ELSE admin_overrides END,
|
||||
updated_at = now(),
|
||||
revision = revision + 1
|
||||
WHERE
|
||||
|
||||
@@ -31,7 +31,7 @@ func (s *Service) WithStorage(storage resource.Storage) *Service {
|
||||
|
||||
func NewService(store *resource.Store) *Service {
|
||||
s := &Service{Store: store}
|
||||
s.CRUD = resource.NewCRUD(store, resource.Definition{Kind: "expert", Repository: func(q resource.Queryer) resource.Repository { return sqlc.New(q) }, Path: "/experts", Fields: []string{"name", "description", "prompt", "enabled"}, UserFields: []string{"name", "description", "prompt", "rule_ids", "skill_ids", "connectors", "tag_ids"}, OverrideFields: []string{"name", "description"}, Hidden: []string{"avatar_s3_key"}, Validate: s.validate, Persist: s.links, Decorate: s.decorate})
|
||||
s.CRUD = resource.NewCRUD(store, resource.Definition{Kind: "expert", Repository: func(q resource.Queryer) resource.Repository { return sqlc.New(q) }, Path: "/experts", Fields: []string{"name", "description", "prompt", "enabled"}, UserFields: []string{"name", "description", "prompt", "rule_ids", "skill_ids", "connectors", "tag_ids"}, OverrideFields: []string{"name", "description"}, AllowImportedEnabled: true, Hidden: []string{"avatar_s3_key"}, Validate: s.validate, Persist: s.links, Decorate: s.decorate})
|
||||
return s
|
||||
}
|
||||
func (s *Service) validate(ctx context.Context, tx pgx.Tx, in, old resource.Object) error {
|
||||
|
||||
@@ -396,6 +396,9 @@ UPDATE
|
||||
experts
|
||||
SET
|
||||
enabled = ($1::jsonb ->> 'enabled')::boolean,
|
||||
admin_overrides = CASE WHEN $1::jsonb ? 'admin_overrides' THEN
|
||||
$1::jsonb -> 'admin_overrides'
|
||||
ELSE admin_overrides END,
|
||||
updated_at = now(),
|
||||
revision = revision + 1
|
||||
WHERE
|
||||
|
||||
@@ -187,6 +187,9 @@ UPDATE
|
||||
connectors
|
||||
SET
|
||||
enabled = (sqlc.arg(DATA)::jsonb ->> 'enabled')::boolean,
|
||||
admin_overrides = CASE WHEN sqlc.arg(DATA)::jsonb ? 'admin_overrides' THEN
|
||||
sqlc.arg(DATA)::jsonb -> 'admin_overrides'
|
||||
ELSE admin_overrides END,
|
||||
updated_at = now(),
|
||||
revision = revision + 1
|
||||
WHERE
|
||||
|
||||
@@ -45,13 +45,14 @@ func NewService(store *resource.Store, publicURL string) *Service {
|
||||
s := &Service{Store: store, PublicURL: strings.TrimRight(publicURL, "/")}
|
||||
s.Connectors = resource.NewCRUD(store, resource.Definition{
|
||||
Kind: "connector", Path: "/connectors",
|
||||
Repository: func(q resource.Queryer) resource.Repository { return connector.New(q) },
|
||||
Fields: []string{"name", "description", "url", "authorization_mode", "authorization_method", "oauth_config", "oauth_client_secret", "auth_header_name", "proxy_id", "enabled", "config_revision", "connection_status"},
|
||||
UserFields: []string{"name", "description", "url", "authorization_mode", "authorization_method", "oauth_config", "oauth_client_secret", "tag_ids"},
|
||||
OverrideFields: []string{"name", "description", "url", "proxy_id", "authorization_mode", "authorization_method", "oauth_config", "oauth_client_secret", "auth_header_name", "tag_ids"},
|
||||
Hidden: []string{"oauth_client_secret", "icon_s3_key"},
|
||||
PrepareOverride: s.validateConnector,
|
||||
Validate: s.validateConnector, Decorate: s.decorateConnector, UserDecorate: userIcon,
|
||||
Repository: func(q resource.Queryer) resource.Repository { return connector.New(q) },
|
||||
Fields: []string{"name", "description", "url", "authorization_mode", "authorization_method", "oauth_config", "oauth_client_secret", "auth_header_name", "proxy_id", "enabled", "config_revision", "connection_status"},
|
||||
UserFields: []string{"name", "description", "url", "authorization_mode", "authorization_method", "oauth_config", "oauth_client_secret", "tag_ids"},
|
||||
OverrideFields: []string{"name", "description", "url", "proxy_id", "authorization_mode", "authorization_method", "oauth_config", "oauth_client_secret", "auth_header_name", "tag_ids"},
|
||||
Hidden: []string{"oauth_client_secret", "icon_s3_key"},
|
||||
AllowImportedEnabled: true,
|
||||
PrepareOverride: s.validateConnector,
|
||||
Validate: s.validateConnector, Decorate: s.decorateConnector, UserDecorate: userIcon,
|
||||
References: func(ctx context.Context, tx pgx.Tx, id string) ([]resource.Object, error) {
|
||||
return resource.DecodeObjects(sqlc.New(tx).ListConnectorReferences(ctx, id))
|
||||
},
|
||||
|
||||
@@ -179,6 +179,9 @@ UPDATE
|
||||
connectors
|
||||
SET
|
||||
enabled = ($1::jsonb ->> 'enabled')::boolean,
|
||||
admin_overrides = CASE WHEN $1::jsonb ? 'admin_overrides' THEN
|
||||
$1::jsonb -> 'admin_overrides'
|
||||
ELSE admin_overrides END,
|
||||
updated_at = now(),
|
||||
revision = revision + 1
|
||||
WHERE
|
||||
|
||||
@@ -239,18 +239,19 @@ func Audit(ctx context.Context, tx pgx.Tx, actor, kind, id, action string) error
|
||||
}
|
||||
|
||||
type Definition struct {
|
||||
Kind, Path string
|
||||
Repository func(Queryer) Repository
|
||||
Fields []string
|
||||
UserFields []string
|
||||
Hidden []string
|
||||
OverrideFields []string
|
||||
Validate func(context.Context, pgx.Tx, Object, Object) error
|
||||
PrepareOverride func(context.Context, pgx.Tx, Object, Object) error
|
||||
Persist func(context.Context, pgx.Tx, Object) error
|
||||
Decorate func(context.Context, Queryer, Object) error
|
||||
UserDecorate func(Object)
|
||||
References func(context.Context, pgx.Tx, string) ([]Object, error)
|
||||
Kind, Path string
|
||||
Repository func(Queryer) Repository
|
||||
Fields []string
|
||||
UserFields []string
|
||||
Hidden []string
|
||||
OverrideFields []string
|
||||
AllowImportedEnabled bool
|
||||
Validate func(context.Context, pgx.Tx, Object, Object) error
|
||||
PrepareOverride func(context.Context, pgx.Tx, Object, Object) error
|
||||
Persist func(context.Context, pgx.Tx, Object) error
|
||||
Decorate func(context.Context, Queryer, Object) error
|
||||
UserDecorate func(Object)
|
||||
References func(context.Context, pgx.Tx, string) ([]Object, error)
|
||||
}
|
||||
type CRUD struct {
|
||||
Store *Store
|
||||
@@ -304,7 +305,7 @@ func (c *CRUD) decorate(ctx context.Context, q Queryer, o Object) (Object, error
|
||||
|
||||
o["user"] = users[owner]
|
||||
}
|
||||
if c.Def.Kind == "expert" || c.Def.Kind == "connector" {
|
||||
if c.Def.Kind == "expert" || c.Def.Kind == "connector" || c.Def.Kind == "rule" {
|
||||
o["tags"], err = Tags(ctx, q, c.Def.Kind, o.String("id"))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -446,7 +447,7 @@ func (c *CRUD) save(ctx context.Context, actor, id, match string, in Object, per
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if raw, ok := in["tag_ids"]; ok && (c.Def.Kind == "expert" || c.Def.Kind == "connector") {
|
||||
if raw, ok := in["tag_ids"]; ok && (c.Def.Kind == "expert" || c.Def.Kind == "connector" || c.Def.Kind == "rule") {
|
||||
if err = SaveTags(ctx, tx, c.Def.Kind, id, actor, raw); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -767,13 +768,28 @@ func (c *CRUD) SetEnabled(ctx context.Context, actor, id, match string, enabled
|
||||
if o.String("ownership_type") == "user" {
|
||||
return nil, Invalid("个人资源仅允许治理删除")
|
||||
}
|
||||
imported := false
|
||||
if err = RequireEditable(ctx, tx, c.Def.Kind, id); err != nil {
|
||||
return nil, err
|
||||
if !c.Def.AllowImportedEnabled || !errors.Is(err, ImportedReadOnly) {
|
||||
return nil, err
|
||||
}
|
||||
imported = true
|
||||
}
|
||||
if match != fmt.Sprintf(`"%v"`, o["revision"]) {
|
||||
return nil, Conflict
|
||||
}
|
||||
data, err := json.Marshal(Object{"id": id, "enabled": enabled})
|
||||
update := Object{"id": id, "enabled": enabled}
|
||||
if imported {
|
||||
overrides := Object{}
|
||||
if current, ok := o["admin_overrides"].(map[string]any); ok {
|
||||
for key, value := range current {
|
||||
overrides[key] = value
|
||||
}
|
||||
}
|
||||
overrides["enabled"] = true
|
||||
update["admin_overrides"] = overrides
|
||||
}
|
||||
data, err := json.Marshal(update)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
package resourceimport
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/expert"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/identity"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/mcp"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/rule"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func TestImportedResourcesEnabled(t *testing.T) {
|
||||
f := newImportTest(t)
|
||||
apply := func(data []byte) {
|
||||
t.Helper()
|
||||
preview := f.post(data, nil, http.StatusOK)
|
||||
f.post(data, &preview, http.StatusOK)
|
||||
}
|
||||
apply(taggedFixture(t, 30, []string{"初始标签"}))
|
||||
current, err := bindings(t.Context(), f.pool, "monkeyai-respub")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
store := resource.NewStore(f.pool)
|
||||
router := chi.NewRouter()
|
||||
router.Use(identity.NewService(f.pool, nil, "").RequireAdmin)
|
||||
expert.NewService(store).RegisterAdmin(router)
|
||||
mcp.NewService(store, "").RegisterAdmin(router)
|
||||
rule.NewService(store).Register(router)
|
||||
store.RegisterAdmin(router)
|
||||
call := func(method, target, etag string, input any, want int) resource.Object {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := httptest.NewRequest(method, target, bytes.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
request.Header.Set("If-Match", etag)
|
||||
request.AddCookie(f.cookie)
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
if response.Code != want {
|
||||
t.Fatalf("%s %s: %d %s, want %d", method, target, response.Code, response.Body.String(), want)
|
||||
}
|
||||
var out resource.Object
|
||||
if want == http.StatusOK {
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
etag := func(o resource.Object) string { return fmt.Sprintf(`"%d"`, o.Int("revision")) }
|
||||
type target struct{ kind, table, path, id string }
|
||||
var targets []target
|
||||
for _, item := range []struct{ kind, table string }{{"expert", "experts"}, {"connector", "connectors"}, {"rule", "rules"}} {
|
||||
id := current["demo-"+item.kind].ID
|
||||
if id == "" {
|
||||
t.Fatalf("missing imported %s", item.kind)
|
||||
}
|
||||
targets = append(targets, target{item.kind, item.table, "/" + item.table + "/" + id, id})
|
||||
f.exec(fmt.Sprintf(`UPDATE %s SET admin_overrides='{"name":true}'::jsonb WHERE id=$1`, item.table), id)
|
||||
}
|
||||
read := func(item target) resource.Object { return call(http.MethodGet, item.path, "", nil, http.StatusOK) }
|
||||
snapshot := func(item target) string {
|
||||
t.Helper()
|
||||
var result string
|
||||
err := f.pool.QueryRow(t.Context(), fmt.Sprintf(`SELECT jsonb_build_array(
|
||||
to_jsonb(r)-'enabled'-'revision'-'updated_at'-'admin_overrides',
|
||||
(SELECT jsonb_agg(to_jsonb(g) ORDER BY id) FROM resource_access_grants g WHERE resource_type=$1 AND resource_id=r.id),
|
||||
(SELECT jsonb_agg(to_jsonb(g) ORDER BY tag_id) FROM resource_tags g WHERE resource_type=$1 AND resource_id=r.id),
|
||||
(SELECT to_jsonb(b) FROM resource_import_bindings b WHERE resource_type=$1 AND resource_id=r.id))::text FROM %s r WHERE id=$2`, item.table), item.kind, item.id).Scan(&result)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return result
|
||||
}
|
||||
for _, item := range targets {
|
||||
before, original := read(item), snapshot(item)
|
||||
disabled := call(http.MethodPatch, item.path+"/enabled", etag(before), resource.Object{"enabled": false}, http.StatusOK)
|
||||
if disabled.Bool("enabled") || disabled.Int("revision") != before.Int("revision")+1 || snapshot(item) != original {
|
||||
t.Fatalf("%s toggle changed content, configuration, tags, grants or binding: %+v", item.kind, disabled)
|
||||
}
|
||||
var overrides map[string]bool
|
||||
if err := f.pool.QueryRow(t.Context(), fmt.Sprintf("SELECT admin_overrides FROM %s WHERE id=$1", item.table), item.id).Scan(&overrides); err != nil || !overrides["name"] || !overrides["enabled"] {
|
||||
t.Fatalf("%s lost manual overrides: %+v %v", item.kind, overrides, err)
|
||||
}
|
||||
call(http.MethodPatch, item.path+"/enabled", etag(before), resource.Object{"enabled": true}, http.StatusPreconditionFailed)
|
||||
call(http.MethodPatch, item.path+"/enabled", "", resource.Object{"enabled": true}, http.StatusPreconditionFailed)
|
||||
call(http.MethodPatch, item.path+"/enabled", etag(disabled), resource.Object{"enabled": "true"}, http.StatusBadRequest)
|
||||
call(http.MethodDelete, item.path, etag(disabled), nil, http.StatusConflict)
|
||||
if after := read(item); after.Bool("enabled") || after.Int("revision") != disabled.Int("revision") || snapshot(item) != original {
|
||||
t.Fatalf("invalid %s mutation changed resource", item.kind)
|
||||
}
|
||||
}
|
||||
assertState := func(enabled, retired bool) {
|
||||
t.Helper()
|
||||
for _, item := range targets {
|
||||
if after := read(item); after.Bool("enabled") != enabled || after.Bool("retired") != retired {
|
||||
t.Fatalf("%s state: %+v, want enabled=%t retired=%t", item.kind, after, enabled, retired)
|
||||
}
|
||||
}
|
||||
}
|
||||
toggleAll := func(enabled bool) {
|
||||
for _, item := range targets {
|
||||
call(http.MethodPatch, item.path+"/enabled", etag(read(item)), resource.Object{"enabled": enabled}, http.StatusOK)
|
||||
}
|
||||
}
|
||||
retire := func(version int64) []byte {
|
||||
return packageFixture(t, func(m *Manifest, _ map[string][]byte) {
|
||||
m.Version = version
|
||||
m.ReleaseID = fmt.Sprintf("7321da1e-bf59-41a1-9ae9-%012d", version)
|
||||
m.AgentResources = AgentResources{}
|
||||
})
|
||||
}
|
||||
apply(taggedFixture(t, 31, []string{"更新标签"}))
|
||||
assertState(false, false)
|
||||
toggleAll(true)
|
||||
apply(taggedFixture(t, 32, []string{"再次更新标签"}))
|
||||
assertState(true, false)
|
||||
apply(retire(33))
|
||||
assertState(false, true)
|
||||
toggleAll(true)
|
||||
apply(taggedFixture(t, 34, []string{"恢复标签"}))
|
||||
assertState(true, false)
|
||||
toggleAll(false)
|
||||
apply(retire(35))
|
||||
apply(taggedFixture(t, 36, []string{"再次恢复标签"}))
|
||||
assertState(false, false)
|
||||
|
||||
t.Run("local rule tags preserve content and required grants", func(t *testing.T) {
|
||||
created := call(http.MethodPost, "/rules", "", resource.Object{
|
||||
"name": "local rule", "description": "canonical description", "content": "original content",
|
||||
"grants": []resource.Object{{"user_id": f.actor, "usage_requirement": "required"}},
|
||||
}, http.StatusOK)
|
||||
path := "/rules/" + created.String("id")
|
||||
tag := resource.ID()
|
||||
f.exec("INSERT INTO tags(id,name,created_by_user_id) VALUES($1,'batch tag',$2)", tag, f.actor)
|
||||
update := func(o resource.Object, tags []string, want int) resource.Object {
|
||||
return call(http.MethodPut, path, etag(o), resource.Object{"name": o.String("name"), "description": o.String("description"), "content": o.String("content"), "tag_ids": tags}, want)
|
||||
}
|
||||
updated := update(created, []string{tag, tag}, http.StatusOK)
|
||||
var links int
|
||||
if err := f.pool.QueryRow(t.Context(), "SELECT count(*) FROM resource_tags WHERE resource_type='rule' AND resource_id=$1", created.String("id")).Scan(&links); err != nil || links != 1 {
|
||||
t.Fatalf("rule tags not saved once: %d %v", links, err)
|
||||
}
|
||||
if updated.String("content") != "original content" || updated.String("description") != "canonical description" || !updated.Bool("enabled") {
|
||||
t.Fatalf("tag update changed rule settings: %+v", updated)
|
||||
}
|
||||
if tags, ok := updated["tags"].([]any); !ok || len(tags) != 1 {
|
||||
t.Fatalf("rule tags missing in response: %+v", updated)
|
||||
}
|
||||
var required bool
|
||||
if err := f.pool.QueryRow(t.Context(), "SELECT usage_requirement='required' FROM resource_access_grants WHERE resource_type='rule' AND resource_id=$1 AND user_id=$2", created.String("id"), f.actor).Scan(&required); err != nil || !required {
|
||||
t.Fatalf("tag update lost required authorization: %t %v", required, err)
|
||||
}
|
||||
update(updated, []string{resource.ID()}, http.StatusBadRequest)
|
||||
after := call(http.MethodGet, path, "", nil, http.StatusOK)
|
||||
if after.Int("revision") != updated.Int("revision") || len(after["tags"].([]any)) != 1 {
|
||||
t.Fatalf("invalid tag update did not roll back: %+v", after)
|
||||
}
|
||||
cleared := update(after, []string{}, http.StatusOK)
|
||||
if len(cleared["tags"].([]any)) != 0 {
|
||||
t.Fatalf("empty tag update did not clear tags: %+v", cleared)
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
package resourceimport
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/identity"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/resource"
|
||||
"github.com/chaitin/MonkeyCode/monkeyai/backend/internal/skill"
|
||||
"github.com/go-chi/chi/v5"
|
||||
)
|
||||
|
||||
func TestImportedSkillEnabled(t *testing.T) {
|
||||
f := newImportTest(t)
|
||||
apply := func(data []byte) {
|
||||
t.Helper()
|
||||
preview := f.post(data, nil, http.StatusOK)
|
||||
f.post(data, &preview, http.StatusOK)
|
||||
}
|
||||
apply(taggedFixture(t, 16, []string{"初始标签"}))
|
||||
current, err := bindings(t.Context(), f.pool, "monkeyai-respub")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
id := current["demo-skill"].ID
|
||||
if id == "" {
|
||||
t.Fatalf("缺少导入技能: %+v", current)
|
||||
}
|
||||
f.exec(`UPDATE skills SET admin_overrides='{"name":true}'::jsonb WHERE id=$1`, id)
|
||||
store := resource.NewStore(f.pool)
|
||||
router := chi.NewRouter()
|
||||
router.Use(identity.NewService(f.pool, nil, "").RequireAdmin)
|
||||
skill.NewService(store, nil).RegisterAdmin(router)
|
||||
call := func(method, target, match string, input any, want int) resource.Object {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(input)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
request := httptest.NewRequest(method, target, bytes.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
if match != "" {
|
||||
request.Header.Set("If-Match", match)
|
||||
}
|
||||
request.AddCookie(f.cookie)
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
if response.Code != want {
|
||||
t.Fatalf("%s %s: %d %s,预期 %d", method, target, response.Code, response.Body.String(), want)
|
||||
}
|
||||
var out resource.Object
|
||||
if want == http.StatusOK {
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if etag := response.Header().Get("ETag"); etag != fmt.Sprintf(`"%d"`, out.Int("revision")) {
|
||||
t.Fatalf("ETag 与版本不一致: %s %+v", etag, out)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
path := "/skills/" + id
|
||||
read := func() resource.Object { return call(http.MethodGet, path, "", nil, http.StatusOK) }
|
||||
etag := func(object resource.Object) string { return fmt.Sprintf(`"%d"`, object.Int("revision")) }
|
||||
snapshot := func() string {
|
||||
t.Helper()
|
||||
var data string
|
||||
if err := f.pool.QueryRow(t.Context(), `SELECT jsonb_build_array(
|
||||
to_jsonb(s)-'enabled'-'revision'-'updated_at'-'admin_overrides',
|
||||
(SELECT jsonb_agg(to_jsonb(g) ORDER BY id) FROM resource_access_grants g WHERE resource_type='skill' AND resource_id=s.id),
|
||||
(SELECT jsonb_agg(to_jsonb(g) ORDER BY tag_id) FROM resource_tags g WHERE resource_type='skill' AND resource_id=s.id),
|
||||
(SELECT to_jsonb(b) FROM resource_import_bindings b WHERE resource_type='skill' AND resource_id=s.id))::text FROM skills s WHERE id=$1`, id).Scan(&data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return data
|
||||
}
|
||||
before := read()
|
||||
original := snapshot()
|
||||
disabled := call(http.MethodPatch, path+"/enabled", etag(before), resource.Object{"enabled": false}, http.StatusOK)
|
||||
if disabled.Bool("enabled") || disabled.Int("revision") != before.Int("revision")+1 || snapshot() != original {
|
||||
t.Fatalf("停用改变了内容、标签、授权或绑定: %+v", disabled)
|
||||
}
|
||||
var overrides map[string]bool
|
||||
if err := f.pool.QueryRow(t.Context(), "SELECT admin_overrides FROM skills WHERE id=$1", id).Scan(&overrides); err != nil || !overrides["enabled"] || !overrides["name"] {
|
||||
t.Fatalf("未保留已有覆盖或记录手动启停: %+v %v", overrides, err)
|
||||
}
|
||||
call(http.MethodPatch, path+"/enabled", etag(before), resource.Object{"enabled": true}, http.StatusPreconditionFailed)
|
||||
call(http.MethodPatch, path+"/enabled", "", resource.Object{"enabled": true}, http.StatusPreconditionFailed)
|
||||
call(http.MethodPatch, path+"/enabled", etag(disabled), resource.Object{"enabled": "true"}, http.StatusBadRequest)
|
||||
if after := read(); after.Bool("enabled") || after.Int("revision") != disabled.Int("revision") || snapshot() != original {
|
||||
t.Fatalf("无效请求改变了技能: %+v", after)
|
||||
}
|
||||
for _, field := range []string{"content", "tag_ids"} {
|
||||
call(http.MethodPut, path, etag(disabled), resource.Object{field: []string{}}, http.StatusBadRequest)
|
||||
}
|
||||
call(http.MethodDelete, path, etag(disabled), nil, http.StatusConflict)
|
||||
if after := read(); after.Int("revision") != disabled.Int("revision") || snapshot() != original {
|
||||
t.Fatalf("启停放开了其他受限修改: %+v", after)
|
||||
}
|
||||
apply(taggedFixture(t, 17, []string{"更新标签"}))
|
||||
if read().Bool("enabled") {
|
||||
t.Fatal("资源包更新覆盖了手动停用状态")
|
||||
}
|
||||
before = read()
|
||||
enabled := call(http.MethodPatch, path+"/enabled", etag(before), resource.Object{"enabled": true}, http.StatusOK)
|
||||
if !enabled.Bool("enabled") || enabled.Int("revision") != before.Int("revision")+1 {
|
||||
t.Fatalf("资源包技能无法重新启用: %+v", enabled)
|
||||
}
|
||||
apply(taggedFixture(t, 18, []string{"再次更新标签"}))
|
||||
if !read().Bool("enabled") {
|
||||
t.Fatal("资源包更新未保留手动启用状态")
|
||||
}
|
||||
retire := func(version int64) []byte {
|
||||
return packageFixture(t, func(m *Manifest, _ map[string][]byte) {
|
||||
m.Version = version
|
||||
m.ReleaseID = fmt.Sprintf("6321da1e-bf59-41a1-9ae9-%012d", version)
|
||||
m.AgentResources = AgentResources{}
|
||||
})
|
||||
}
|
||||
apply(retire(19))
|
||||
before = read()
|
||||
if before.Bool("enabled") || !before.Bool("retired") {
|
||||
t.Fatalf("退役未停用技能: %+v", before)
|
||||
}
|
||||
call(http.MethodPatch, path+"/enabled", etag(before), resource.Object{"enabled": true}, http.StatusOK)
|
||||
apply(taggedFixture(t, 20, []string{"恢复标签"}))
|
||||
if after := read(); !after.Bool("enabled") || after.Bool("retired") {
|
||||
t.Fatalf("手动启用的技能无法正常恢复导入: %+v", after)
|
||||
}
|
||||
before = read()
|
||||
call(http.MethodPatch, path+"/enabled", etag(before), resource.Object{"enabled": false}, http.StatusOK)
|
||||
apply(retire(21))
|
||||
apply(taggedFixture(t, 22, []string{"再次恢复标签"}))
|
||||
if after := read(); after.Bool("enabled") || after.Bool("retired") {
|
||||
t.Fatalf("手动停用的技能在恢复导入后被自动启用: %+v", after)
|
||||
}
|
||||
|
||||
for _, ownership := range []string{"system", "user"} {
|
||||
localID := resource.ID()
|
||||
f.exec(`INSERT INTO skills(id,owner_user_id,ownership_type,name,description,package_file_name,package_s3_key,package_size_bytes,package_sha256)
|
||||
VALUES($1,$2,$3,'local','description','local.zip','local.zip',0,'hash')`, localID, f.actor, ownership)
|
||||
localPath := "/skills/" + localID
|
||||
old := call(http.MethodGet, localPath, "", nil, http.StatusOK)
|
||||
want := http.StatusOK
|
||||
if ownership == "user" {
|
||||
want = http.StatusBadRequest
|
||||
}
|
||||
call(http.MethodPatch, localPath+"/enabled", etag(old), resource.Object{"enabled": false}, want)
|
||||
var changed bool
|
||||
if err := f.pool.QueryRow(t.Context(), "SELECT admin_overrides ? 'enabled' FROM skills WHERE id=$1", localID).Scan(&changed); err != nil || changed {
|
||||
t.Fatalf("本地或个人技能不应记录导入覆盖: %v %v", changed, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -102,6 +102,11 @@ func target(ctx context.Context, q resource.Queryer, b binding) (resource.Object
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func hasEnabledOverride(kind string, object resource.Object) bool {
|
||||
overrides, _ := object["admin_overrides"].(map[string]any)
|
||||
return slices.Contains([]string{"skill", "expert", "connector", "rule"}, kind) && overrides["enabled"] == true
|
||||
}
|
||||
|
||||
type desired struct {
|
||||
Kind, Slug, Name, Source, StoredSHA string
|
||||
Fields resource.Object
|
||||
@@ -270,7 +275,7 @@ func (s *Service) Evaluate(ctx context.Context, q resource.Queryer, p Package, r
|
||||
change.ResourceID, change.Revision = b.ID, obj.Int("revision")
|
||||
switch {
|
||||
case b.Retired:
|
||||
if obj.Bool("enabled") {
|
||||
if obj.Bool("enabled") && !hasEnabledOverride(b.Type, obj) {
|
||||
return result, fmt.Errorf("退役资源 %s 状态异常", item.Slug)
|
||||
}
|
||||
change.Action = "restore"
|
||||
@@ -296,7 +301,7 @@ func (s *Service) Evaluate(ctx context.Context, q resource.Queryer, p Package, r
|
||||
if err != nil {
|
||||
return result, fmt.Errorf("将退役资源 %s 目标异常: %w", slug, err)
|
||||
}
|
||||
if v, ok := obj["enabled"].(bool); !ok || !v {
|
||||
if v, ok := obj["enabled"].(bool); !ok || (!v && !hasEnabledOverride(b.Type, obj)) {
|
||||
return result, fmt.Errorf("将退役资源 %s 启停状态异常", slug)
|
||||
}
|
||||
warnings, err := checkReferences(ctx, q, b, present, r, current)
|
||||
|
||||
@@ -82,7 +82,7 @@ FROM (SELECT sqlc.arg(data)::jsonb AS d) input;
|
||||
UPDATE skills SET origin='package',name=d->>'name',description=d->>'description',name_i18n=d->'name_i18n',description_i18n=d->'description_i18n',
|
||||
package_file_name=d->>'package_file_name',package_s3_key=CASE WHEN d->>'package_s3_key'='' THEN package_s3_key ELSE d->>'package_s3_key' END,
|
||||
package_size_bytes=(d->>'package_size_bytes')::bigint,package_sha256=d->>'package_sha256',file_count=(d->>'file_count')::int,
|
||||
enabled=true,revision=revision+1,updated_at=now()
|
||||
enabled=COALESCE((d->>'enabled')::boolean,true),revision=revision+1,updated_at=now()
|
||||
FROM (SELECT sqlc.arg(data)::jsonb AS d) input WHERE id=(d->>'id')::uuid;
|
||||
|
||||
-- name: CreateImportRule :exec
|
||||
@@ -92,7 +92,7 @@ FROM (SELECT sqlc.arg(data)::jsonb AS d) input;
|
||||
|
||||
-- name: UpdateImportRule :exec
|
||||
UPDATE rules SET origin='package',name=d->>'name',description=d->>'description',content=d->>'content',name_i18n=d->'name_i18n',description_i18n=d->'description_i18n',
|
||||
enabled=true,revision=revision+1,updated_at=now()
|
||||
enabled=COALESCE((d->>'enabled')::boolean,true),revision=revision+1,updated_at=now()
|
||||
FROM (SELECT sqlc.arg(data)::jsonb AS d) input WHERE id=(d->>'id')::uuid;
|
||||
|
||||
-- name: CreateImportConnector :exec
|
||||
@@ -109,7 +109,7 @@ UPDATE connectors SET origin='package',name=d->>'name',description=d->>'descript
|
||||
config_revision=(d->>'config_revision')::bigint,connection_status=d->>'connection_status',
|
||||
last_checked_at=CASE WHEN (d->>'config_changed')::boolean THEN NULL ELSE last_checked_at END,
|
||||
last_error=CASE WHEN (d->>'config_changed')::boolean THEN NULL ELSE last_error END,
|
||||
enabled=true,revision=revision+1,updated_at=now()
|
||||
enabled=COALESCE((d->>'enabled')::boolean,true),revision=revision+1,updated_at=now()
|
||||
FROM (SELECT sqlc.arg(data)::jsonb AS d) input WHERE id=(d->>'id')::uuid;
|
||||
|
||||
-- name: InvalidateImportTools :exec
|
||||
@@ -128,7 +128,7 @@ FROM (SELECT sqlc.arg(data)::jsonb AS d) input;
|
||||
|
||||
-- name: UpdateImportExpert :exec
|
||||
UPDATE experts SET origin='package',name=d->>'name',description=d->>'description',prompt=d->>'prompt',avatar_s3_key=d->>'avatar_s3_key',
|
||||
name_i18n=d->'name_i18n',description_i18n=d->'description_i18n',enabled=true,revision=revision+1,updated_at=now()
|
||||
name_i18n=d->'name_i18n',description_i18n=d->'description_i18n',enabled=COALESCE((d->>'enabled')::boolean,true),revision=revision+1,updated_at=now()
|
||||
FROM (SELECT sqlc.arg(data)::jsonb AS d) input WHERE id=(d->>'id')::uuid;
|
||||
|
||||
-- name: ClearImportExpertSkills :exec
|
||||
|
||||
@@ -588,6 +588,7 @@ func writeResource(ctx context.Context, tx pgx.Tx, r Resources, change Change, i
|
||||
}
|
||||
preserveOverride(old, payloadObject, overrides, "name")
|
||||
preserveOverride(old, payloadObject, overrides, "description")
|
||||
preserveOverride(old, payloadObject, overrides, "enabled")
|
||||
return sqlc.New(tx).UpdateImportSkill(ctx, payload(payloadObject))
|
||||
case "rule":
|
||||
item := r.Rules[change.Slug]
|
||||
@@ -610,6 +611,7 @@ func writeResource(ctx context.Context, tx pgx.Tx, r Resources, change Change, i
|
||||
}
|
||||
preserveOverride(old, payloadObject, overrides, "name")
|
||||
preserveOverride(old, payloadObject, overrides, "description")
|
||||
preserveOverride(old, payloadObject, overrides, "enabled")
|
||||
return sqlc.New(tx).UpdateImportRule(ctx, payload(payloadObject))
|
||||
case "connector":
|
||||
return writeConnector(ctx, tx, r.Connectors[change.Slug], change, id, actor, objects, opts)
|
||||
@@ -635,6 +637,7 @@ func writeResource(ctx context.Context, tx pgx.Tx, r Resources, change Change, i
|
||||
}
|
||||
preserveOverride(old, payloadObject, overrides, "name")
|
||||
preserveOverride(old, payloadObject, overrides, "description")
|
||||
preserveOverride(old, payloadObject, overrides, "enabled")
|
||||
if err := queries.UpdateImportExpert(ctx, payload(payloadObject)); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -800,6 +803,7 @@ func writeConnector(ctx context.Context, tx pgx.Tx, item Connector, change Chang
|
||||
}
|
||||
}
|
||||
data["config_revision"], data["connection_status"], data["config_changed"] = revision, connectionStatus, changed
|
||||
preserveOverride(old, data, overrides, "enabled")
|
||||
return sqlc.New(tx).UpdateImportConnector(ctx, payload(data))
|
||||
}
|
||||
|
||||
|
||||
@@ -726,7 +726,7 @@ UPDATE connectors SET origin='package',name=d->>'name',description=d->>'descript
|
||||
config_revision=(d->>'config_revision')::bigint,connection_status=d->>'connection_status',
|
||||
last_checked_at=CASE WHEN (d->>'config_changed')::boolean THEN NULL ELSE last_checked_at END,
|
||||
last_error=CASE WHEN (d->>'config_changed')::boolean THEN NULL ELSE last_error END,
|
||||
enabled=true,revision=revision+1,updated_at=now()
|
||||
enabled=COALESCE((d->>'enabled')::boolean,true),revision=revision+1,updated_at=now()
|
||||
FROM (SELECT $1::jsonb AS d) input WHERE id=(d->>'id')::uuid
|
||||
`
|
||||
|
||||
@@ -737,7 +737,7 @@ func (q *Queries) UpdateImportConnector(ctx context.Context, data []byte) error
|
||||
|
||||
const updateImportExpert = `-- name: UpdateImportExpert :exec
|
||||
UPDATE experts SET origin='package',name=d->>'name',description=d->>'description',prompt=d->>'prompt',avatar_s3_key=d->>'avatar_s3_key',
|
||||
name_i18n=d->'name_i18n',description_i18n=d->'description_i18n',enabled=true,revision=revision+1,updated_at=now()
|
||||
name_i18n=d->'name_i18n',description_i18n=d->'description_i18n',enabled=COALESCE((d->>'enabled')::boolean,true),revision=revision+1,updated_at=now()
|
||||
FROM (SELECT $1::jsonb AS d) input WHERE id=(d->>'id')::uuid
|
||||
`
|
||||
|
||||
@@ -748,7 +748,7 @@ func (q *Queries) UpdateImportExpert(ctx context.Context, data []byte) error {
|
||||
|
||||
const updateImportRule = `-- name: UpdateImportRule :exec
|
||||
UPDATE rules SET origin='package',name=d->>'name',description=d->>'description',content=d->>'content',name_i18n=d->'name_i18n',description_i18n=d->'description_i18n',
|
||||
enabled=true,revision=revision+1,updated_at=now()
|
||||
enabled=COALESCE((d->>'enabled')::boolean,true),revision=revision+1,updated_at=now()
|
||||
FROM (SELECT $1::jsonb AS d) input WHERE id=(d->>'id')::uuid
|
||||
`
|
||||
|
||||
@@ -761,7 +761,7 @@ const updateImportSkill = `-- name: UpdateImportSkill :exec
|
||||
UPDATE skills SET origin='package',name=d->>'name',description=d->>'description',name_i18n=d->'name_i18n',description_i18n=d->'description_i18n',
|
||||
package_file_name=d->>'package_file_name',package_s3_key=CASE WHEN d->>'package_s3_key'='' THEN package_s3_key ELSE d->>'package_s3_key' END,
|
||||
package_size_bytes=(d->>'package_size_bytes')::bigint,package_sha256=d->>'package_sha256',file_count=(d->>'file_count')::int,
|
||||
enabled=true,revision=revision+1,updated_at=now()
|
||||
enabled=COALESCE((d->>'enabled')::boolean,true),revision=revision+1,updated_at=now()
|
||||
FROM (SELECT $1::jsonb AS d) input WHERE id=(d->>'id')::uuid
|
||||
`
|
||||
|
||||
|
||||
@@ -138,6 +138,9 @@ WHERE
|
||||
-- name: SetResourceEnabled :exec
|
||||
UPDATE rules
|
||||
SET enabled = (sqlc.arg(DATA)::jsonb ->> 'enabled')::boolean,
|
||||
admin_overrides = CASE WHEN sqlc.arg(DATA)::jsonb ? 'admin_overrides' THEN
|
||||
sqlc.arg(DATA)::jsonb -> 'admin_overrides'
|
||||
ELSE admin_overrides END,
|
||||
revision = revision + 1,
|
||||
updated_at = now()
|
||||
WHERE id = (sqlc.arg(DATA)::jsonb ->> 'id')::uuid;
|
||||
@@ -11,7 +11,7 @@ import (
|
||||
)
|
||||
|
||||
func NewService(s *resource.Store) *resource.CRUD {
|
||||
return resource.NewCRUD(s, resource.Definition{Kind: "rule", Repository: func(q resource.Queryer) resource.Repository { return sqlc.New(q) }, Path: "/rules", Fields: []string{"name", "description", "content", "enabled"}, UserFields: []string{"name", "description", "content"}, OverrideFields: []string{"name", "description"}, Validate: func(ctx context.Context, tx pgx.Tx, in, old resource.Object) error {
|
||||
return resource.NewCRUD(s, resource.Definition{Kind: "rule", Repository: func(q resource.Queryer) resource.Repository { return sqlc.New(q) }, Path: "/rules", Fields: []string{"name", "description", "content", "enabled"}, UserFields: []string{"name", "description", "content"}, OverrideFields: []string{"name", "description"}, AllowImportedEnabled: true, Validate: func(ctx context.Context, tx pgx.Tx, in, old resource.Object) error {
|
||||
if strings.TrimSpace(in.String("content")) == "" {
|
||||
return resource.Invalid("规则正文不能为空")
|
||||
}
|
||||
|
||||
@@ -192,6 +192,9 @@ func (q *Queries) PageResources(ctx context.Context, filter []byte) ([][]byte, e
|
||||
const setResourceEnabled = `-- name: SetResourceEnabled :exec
|
||||
UPDATE rules
|
||||
SET enabled = ($1::jsonb ->> 'enabled')::boolean,
|
||||
admin_overrides = CASE WHEN $1::jsonb ? 'admin_overrides' THEN
|
||||
$1::jsonb -> 'admin_overrides'
|
||||
ELSE admin_overrides END,
|
||||
revision = revision + 1,
|
||||
updated_at = now()
|
||||
WHERE id = ($1::jsonb ->> 'id')::uuid
|
||||
|
||||
@@ -228,6 +228,11 @@ UPDATE
|
||||
skills
|
||||
SET
|
||||
enabled = (sqlc.arg(DATA)::jsonb ->> 'enabled')::boolean,
|
||||
admin_overrides = CASE WHEN sqlc.arg(DATA)::jsonb ? 'admin_overrides' THEN
|
||||
sqlc.arg(DATA)::jsonb -> 'admin_overrides'
|
||||
ELSE
|
||||
admin_overrides
|
||||
END,
|
||||
updated_at = now(),
|
||||
revision = revision + 1
|
||||
WHERE
|
||||
|
||||
@@ -27,7 +27,7 @@ type Service struct {
|
||||
|
||||
func NewService(store *resource.Store, storage resource.Storage) *Service {
|
||||
s := &Service{store: store, storage: storage}
|
||||
s.CRUD = resource.NewCRUD(store, resource.Definition{Kind: "skill", Repository: func(q resource.Queryer) resource.Repository { return sqlc.New(q) }, Path: "/skills", Fields: []string{"name", "description", "package_file_name", "package_s3_key", "package_size_bytes", "package_sha256", "file_count", "enabled"}, UserFields: []string{"name", "description", "content", "tag_ids", "package_bytes"}, OverrideFields: []string{"name", "description"}, Hidden: []string{"package_s3_key"}, Validate: s.validate, Decorate: s.decorate, Persist: s.tags, References: func(ctx context.Context, tx pgx.Tx, id string) ([]resource.Object, error) {
|
||||
s.CRUD = resource.NewCRUD(store, resource.Definition{Kind: "skill", Repository: func(q resource.Queryer) resource.Repository { return sqlc.New(q) }, Path: "/skills", Fields: []string{"name", "description", "package_file_name", "package_s3_key", "package_size_bytes", "package_sha256", "file_count", "enabled"}, UserFields: []string{"name", "description", "content", "tag_ids", "package_bytes"}, OverrideFields: []string{"name", "description"}, AllowImportedEnabled: true, Hidden: []string{"package_s3_key"}, Validate: s.validate, Decorate: s.decorate, Persist: s.tags, References: func(ctx context.Context, tx pgx.Tx, id string) ([]resource.Object, error) {
|
||||
return resource.DecodeObjects(sqlc.New(tx).ListReferences(ctx, id))
|
||||
}})
|
||||
return s
|
||||
|
||||
@@ -293,6 +293,11 @@ UPDATE
|
||||
skills
|
||||
SET
|
||||
enabled = ($1::jsonb ->> 'enabled')::boolean,
|
||||
admin_overrides = CASE WHEN $1::jsonb ? 'admin_overrides' THEN
|
||||
$1::jsonb -> 'admin_overrides'
|
||||
ELSE
|
||||
admin_overrides
|
||||
END,
|
||||
updated_at = now(),
|
||||
revision = revision + 1
|
||||
WHERE
|
||||
|
||||
Reference in new issue
Block a user