fix(assets): scope the asset library by project
This commit is contained in:
parent
603a6a666d
commit
3f2cea8f5b
|
|
@ -63,6 +63,7 @@ type AssetListFilter struct {
|
|||
Status string
|
||||
Protocol string
|
||||
ProjectID string
|
||||
ProjectUnassigned bool
|
||||
Source string
|
||||
Tag string
|
||||
Host string
|
||||
|
|
@ -93,11 +94,12 @@ type AssetListFilter struct {
|
|||
}
|
||||
|
||||
type AssetImportResult struct {
|
||||
Created int `json:"created"`
|
||||
Updated int `json:"updated"`
|
||||
Skipped int `json:"skipped"`
|
||||
AppliedIDs []string `json:"-"`
|
||||
Collection *AssetCollection `json:"collection,omitempty"`
|
||||
Created int `json:"created"`
|
||||
Updated int `json:"updated"`
|
||||
Skipped int `json:"skipped"`
|
||||
ProjectConflicts int `json:"project_conflicts,omitempty"`
|
||||
AppliedIDs []string `json:"-"`
|
||||
Collection *AssetCollection `json:"collection,omitempty"`
|
||||
}
|
||||
|
||||
func normalizeAsset(a *Asset) {
|
||||
|
|
@ -374,12 +376,13 @@ func (db *DB) upsertAssets(assets []*Asset, ownerUserID string, global bool, pro
|
|||
return result, fmt.Errorf("检查资产去重键失败: %w", err)
|
||||
}
|
||||
asset.ID = existingID
|
||||
if projectBoundary != nil && existingProject.String != *projectBoundary {
|
||||
if !global && strings.TrimSpace(existingOwner.String) != strings.TrimSpace(ownerUserID) {
|
||||
result.Skipped++
|
||||
continue
|
||||
}
|
||||
if !global && strings.TrimSpace(existingOwner.String) != strings.TrimSpace(ownerUserID) {
|
||||
if existingProject.String != asset.ProjectID {
|
||||
result.Skipped++
|
||||
result.ProjectConflicts++
|
||||
continue
|
||||
}
|
||||
_, err = tx.Exec(`UPDATE assets SET
|
||||
|
|
@ -388,7 +391,7 @@ func (db *DB) upsertAssets(assets []*Asset, ownerUserID string, global bool, pro
|
|||
title=CASE WHEN ?<>'' THEN ? ELSE title END, server=CASE WHEN ?<>'' THEN ? ELSE server END,
|
||||
country=CASE WHEN ?<>'' THEN ? ELSE country END, province=CASE WHEN ?<>'' THEN ? ELSE province END,
|
||||
city=CASE WHEN ?<>'' THEN ? ELSE city END, source=CASE WHEN ?<>'' THEN ? ELSE source END,
|
||||
source_query=CASE WHEN ?<>'' THEN ? ELSE source_query END, project_id=CASE WHEN ?<>'' THEN ? ELSE project_id END,
|
||||
source_query=CASE WHEN ?<>'' THEN ? ELSE source_query END,
|
||||
responsible_person=CASE WHEN ?<>'' THEN ? ELSE responsible_person END,
|
||||
department=CASE WHEN ?<>'' THEN ? ELSE department END,
|
||||
business_system=CASE WHEN ?<>'' THEN ? ELSE business_system END,
|
||||
|
|
@ -398,7 +401,7 @@ func (db *DB) upsertAssets(assets []*Asset, ownerUserID string, global bool, pro
|
|||
last_seen_at=?, updated_at=? WHERE id=?`,
|
||||
asset.Host, asset.Host, asset.IP, asset.IP, asset.Domain, asset.Domain, asset.Protocol, asset.Protocol,
|
||||
asset.Title, asset.Title, asset.Server, asset.Server, asset.Country, asset.Country, asset.Province, asset.Province,
|
||||
asset.City, asset.City, asset.Source, asset.Source, asset.SourceQuery, asset.SourceQuery, asset.ProjectID, nullIfEmpty(asset.ProjectID),
|
||||
asset.City, asset.City, asset.Source, asset.Source, asset.SourceQuery, asset.SourceQuery,
|
||||
asset.ResponsiblePerson, asset.ResponsiblePerson, asset.Department, asset.Department, asset.BusinessSystem, asset.BusinessSystem,
|
||||
asset.Environment, asset.Environment, asset.Criticality, asset.Criticality, string(tagsJSON), string(tagsJSON),
|
||||
now, now, existingID)
|
||||
|
|
@ -447,6 +450,9 @@ func assetWhere(filter AssetListFilter, access RBACListAccess) (string, []interf
|
|||
query += " AND assets.project_id = ?"
|
||||
args = append(args, filter.ProjectID)
|
||||
}
|
||||
if filter.ProjectUnassigned {
|
||||
query += " AND (assets.project_id IS NULL OR assets.project_id = '')"
|
||||
}
|
||||
if filter.AssessmentID != "" {
|
||||
query += " AND EXISTS(SELECT 1 FROM deep_assessment_assets da WHERE da.asset_id=assets.id AND da.task_id=?)"
|
||||
args = append(args, filter.AssessmentID)
|
||||
|
|
@ -1236,21 +1242,27 @@ func (db *DB) MergeAssets(primary *Asset, duplicateIDs []string, writeAccess, de
|
|||
return 0, err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
primaryQuery, primaryArgs := appendAssetAccess("SELECT COUNT(*) FROM assets WHERE id=?", []interface{}{primary.ID}, writeAccess, "assets")
|
||||
var primaryCount int
|
||||
if err := tx.QueryRow(primaryQuery, primaryArgs...).Scan(&primaryCount); err != nil || primaryCount != 1 {
|
||||
primaryQuery, primaryArgs := appendAssetAccess("SELECT COALESCE(project_id,'') FROM assets WHERE id=?", []interface{}{primary.ID}, writeAccess, "assets")
|
||||
var projectID string
|
||||
if err := tx.QueryRow(primaryQuery, primaryArgs...).Scan(&projectID); err != nil {
|
||||
return 0, fmt.Errorf("主资产不存在或无权更新")
|
||||
}
|
||||
if projectID != primary.ProjectID {
|
||||
return 0, fmt.Errorf("主资产的项目归属已变更")
|
||||
}
|
||||
placeholders := strings.TrimSuffix(strings.Repeat("?,", len(duplicates)), ",")
|
||||
deleteArgs := make([]interface{}, len(duplicates))
|
||||
for i, id := range duplicates {
|
||||
deleteArgs[i] = id
|
||||
}
|
||||
countQuery, countArgs := appendAssetAccess("SELECT COUNT(*) FROM assets WHERE id IN ("+placeholders+")", deleteArgs, deleteAccess, "assets")
|
||||
var accessible int
|
||||
if err := tx.QueryRow(countQuery, countArgs...).Scan(&accessible); err != nil || accessible != len(duplicates) {
|
||||
countQuery, countArgs := appendAssetAccess("SELECT COUNT(*), COUNT(CASE WHEN COALESCE(project_id,'') = ? THEN 1 END) FROM assets WHERE id IN ("+placeholders+")", append([]interface{}{projectID}, deleteArgs...), deleteAccess, "assets")
|
||||
var accessible, sameProject int
|
||||
if err := tx.QueryRow(countQuery, countArgs...).Scan(&accessible, &sameProject); err != nil || accessible != len(duplicates) {
|
||||
return 0, fmt.Errorf("部分重复资产不存在或无权删除")
|
||||
}
|
||||
if sameProject != len(duplicates) {
|
||||
return 0, fmt.Errorf("只能合并同一项目或均未归属项目的资产")
|
||||
}
|
||||
deleteQuery, scopedDeleteArgs := appendAssetAccess("DELETE FROM assets WHERE id IN ("+placeholders+")", deleteArgs, deleteAccess, "assets")
|
||||
if result, err := tx.Exec(deleteQuery, scopedDeleteArgs...); err != nil {
|
||||
return 0, err
|
||||
|
|
|
|||
|
|
@ -621,8 +621,26 @@ func TestProjectBoundImportCannotReassignDeduplicatedAsset(t *testing.T) {
|
|||
if err != nil || result.Skipped != 1 {
|
||||
t.Fatal("project boundary bypass via dedup", result, err)
|
||||
}
|
||||
result, err = db.UpsertAssets([]*Asset{
|
||||
{Host: original.Host, ProjectID: currentProject.ID, Title: "Reassigned"},
|
||||
{Host: original.Host, Title: "Overwritten without project"},
|
||||
}, "admin", true)
|
||||
if err != nil || result.Skipped != 2 {
|
||||
t.Fatal("ordinary import ignored project boundary", result, err)
|
||||
}
|
||||
saved, err := db.GetAsset(original.ID, RBACListAccess{Scope: RBACScopeAll})
|
||||
if err != nil || saved.ProjectID != otherProject.ID || saved.Title != "Original" {
|
||||
t.Fatal("foreign project record changed", err)
|
||||
}
|
||||
other := &Asset{Host: "http://shared.example.test", ProjectID: currentProject.ID}
|
||||
if _, err := db.UpsertAssets([]*Asset{other}, "admin", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
access := RBACListAccess{Scope: RBACScopeAll}
|
||||
if _, err := db.MergeAssets(saved, []string{other.ID}, access, access); err == nil {
|
||||
t.Fatal("cross-project merge succeeded")
|
||||
}
|
||||
if _, err := db.GetAsset(other.ID, access); err != nil {
|
||||
t.Fatal("cross-project merge removed a record", err)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -263,6 +263,7 @@ func (h *AssetHandler) List(c *gin.Context) {
|
|||
|
||||
func assetListFilterFromQuery(c *gin.Context) (database.AssetListFilter, error) {
|
||||
filter := database.AssetListFilter{
|
||||
ID: strings.TrimSpace(c.Query("id")),
|
||||
Search: strings.TrimSpace(c.Query("q")), Status: strings.ToLower(strings.TrimSpace(c.Query("status"))),
|
||||
Protocol: strings.ToLower(strings.TrimSpace(c.Query("protocol"))), ProjectID: strings.TrimSpace(c.Query("project_id")),
|
||||
Source: strings.TrimSpace(c.Query("source")), Tag: strings.TrimSpace(c.Query("tag")), Host: strings.TrimSpace(c.Query("host")),
|
||||
|
|
@ -274,6 +275,13 @@ func assetListFilterFromQuery(c *gin.Context) (database.AssetListFilter, error)
|
|||
BusinessSystem: strings.TrimSpace(c.Query("business_system")), Environment: strings.ToLower(strings.TrimSpace(c.Query("environment"))),
|
||||
Criticality: strings.ToLower(strings.TrimSpace(c.Query("criticality"))),
|
||||
}
|
||||
if raw := strings.TrimSpace(c.Query("project_unassigned")); raw != "" {
|
||||
var err error
|
||||
filter.ProjectUnassigned, err = strconv.ParseBool(raw)
|
||||
if err != nil || (filter.ProjectUnassigned && filter.ProjectID != "") {
|
||||
return filter, &assetQueryError{field: "project_unassigned", value: raw}
|
||||
}
|
||||
}
|
||||
if raw := strings.TrimSpace(c.Query("port")); raw != "" {
|
||||
port, err := strconv.Atoi(raw)
|
||||
if err != nil || port < 0 || port > 65535 {
|
||||
|
|
@ -591,6 +599,10 @@ func (h *AssetHandler) Merge(c *gin.Context) {
|
|||
c.JSON(http.StatusBadRequest, gin.H{"error": "部分资产不存在或无权访问"})
|
||||
return
|
||||
}
|
||||
if item.ProjectID != primary.ProjectID {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "只能合并同一项目或均未归属项目的资产"})
|
||||
return
|
||||
}
|
||||
if !shareAssetIdentity(primary, item) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "所选资产没有共同域名、IP 或 Host,不能判定为重复资产"})
|
||||
return
|
||||
|
|
@ -611,7 +623,6 @@ func (h *AssetHandler) Merge(c *gin.Context) {
|
|||
tagSet[tag] = struct{}{}
|
||||
}
|
||||
for _, item := range others {
|
||||
mergeText(&primary.ProjectID, item.ProjectID)
|
||||
mergeText(&primary.Host, item.Host)
|
||||
mergeText(&primary.IP, item.IP)
|
||||
mergeText(&primary.Domain, item.Domain)
|
||||
|
|
|
|||
|
|
@ -45,12 +45,16 @@ func TestAssetListPaginatesWithinProject(t *testing.T) {
|
|||
Port: 443,
|
||||
Protocol: "https",
|
||||
})
|
||||
unassigned := &database.Asset{IP: "203.0.113.2", Protocol: "ip"}
|
||||
assets = append(assets, unassigned)
|
||||
if _, err := db.UpsertAssets(assets, "", true); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
router := gin.New()
|
||||
router.GET("/api/assets", NewAssetHandler(db, zap.NewNop()).List)
|
||||
handler := NewAssetHandler(db, zap.NewNop())
|
||||
router.GET("/api/assets", handler.List)
|
||||
router.GET("/api/assets/selection", handler.Selection)
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/assets?project_id="+project.ID+"&page=2&page_size=3", nil)
|
||||
response := httptest.NewRecorder()
|
||||
router.ServeHTTP(response, request)
|
||||
|
|
@ -80,4 +84,27 @@ func TestAssetListPaginatesWithinProject(t *testing.T) {
|
|||
t.Fatalf("asset from another project leaked into page: %#v", asset)
|
||||
}
|
||||
}
|
||||
|
||||
for _, path := range []string{"/api/assets", "/api/assets/selection"} {
|
||||
response = httptest.NewRecorder()
|
||||
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, path+"?project_unassigned=true", nil))
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("%s returned %d: %s", path, response.Code, response.Body.String())
|
||||
}
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if payload.Total != 1 || len(payload.Assets) != 1 || payload.Assets[0].ID != unassigned.ID {
|
||||
t.Fatalf("%s returned assets outside the unassigned scope: %s", path, response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
response = httptest.NewRecorder()
|
||||
router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, "/api/assets?project_id="+project.ID+"&id="+assets[6].ID, nil))
|
||||
if err := json.Unmarshal(response.Body.Bytes(), &payload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Code != http.StatusOK || payload.Total != 1 || len(payload.Assets) != 1 || payload.Assets[0].ID != assets[6].ID {
|
||||
t.Fatalf("exact asset lookup failed: %s", response.Body.String())
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ import { useEffect, useMemo, useRef, useState } from 'react';
|
|||
import { Banner, Button, Form, Space } from '@douyinfe/semi-ui';
|
||||
import { api, errorMessage } from '../../../lib/http';
|
||||
import { useT } from '../../../lib/i18n';
|
||||
import { Drawer, toastSuccess } from '../../../components/ui';
|
||||
import { Drawer, toastSuccess, toastWarning } from '../../../components/ui';
|
||||
import {
|
||||
CRITICALITY_OPTIONS, ENVIRONMENT_OPTIONS, STATUS_OPTIONS
|
||||
} from './assetConstants';
|
||||
|
|
@ -173,17 +173,17 @@ export default function AssetEditorModal({ visible, asset, defaultProjectId = ''
|
|||
const created = Number(result?.created || 0);
|
||||
const updated = Number(result?.updated || 0);
|
||||
const skipped = Number(result?.skipped || 0);
|
||||
if (result?.project_conflicts) {
|
||||
throw new Error(t('assets.importProjectConflicts', { count: 1 }, '已跳过 1 条归属不同的重复资产。'));
|
||||
}
|
||||
const conflicts = Number(result?.project_conflicts || 0);
|
||||
const conflictMessage = conflicts ? t('assets.importProjectConflicts', { count: conflicts }, `已跳过 ${conflicts} 条归属不同的重复资产。`) : '';
|
||||
if (!created && !updated && skipped) {
|
||||
throw new Error(t('assets.assetSkipped', null, '资产未保存,可能已存在且你没有更新权限'));
|
||||
throw new Error(conflictMessage || t('assets.assetSkipped', null, '资产未保存,可能已存在且你没有更新权限'));
|
||||
}
|
||||
const parts = [];
|
||||
if (created) parts.push(`新增 ${created}`);
|
||||
if (updated) parts.push(`合并 ${updated}`);
|
||||
if (skipped) parts.push(`跳过 ${skipped}`);
|
||||
toastSuccess(parts.length ? `已写入资产库:${parts.join(',')}` : t('assets.createdSuccessfully', null, '资产已添加'));
|
||||
if (conflictMessage) toastWarning(conflictMessage);
|
||||
}
|
||||
onSaved?.();
|
||||
onClose?.();
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
/** 资产库筛选栏:常用条件平铺,其余条件收进“高级筛选”。 */
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { Button, Collapse, Input, Select, Space } from '@douyinfe/semi-ui';
|
||||
import { IconSearch } from '@douyinfe/semi-icons';
|
||||
import { useT } from '../../../lib/i18n';
|
||||
|
|
@ -9,7 +9,7 @@ import {
|
|||
} from './assetConstants';
|
||||
|
||||
const EMPTY_FILTERS = {
|
||||
q: '', protocol: '', source: '', project_id: '', tag: '',
|
||||
q: '', protocol: '', source: '', tag: '',
|
||||
status: '', risk_level: '', environment: '', criticality: '',
|
||||
ip: '', domain: '', port: '', scan: '', sort: 'last_seen_at:desc'
|
||||
};
|
||||
|
|
@ -18,17 +18,12 @@ export function emptyAssetFilters() {
|
|||
return { ...EMPTY_FILTERS };
|
||||
}
|
||||
|
||||
export default function AssetFilterBar({ filters, projects, onChange, onReset, disabled }) {
|
||||
export default function AssetFilterBar({ filters, onChange, onReset, disabled }) {
|
||||
const t = useT();
|
||||
const [keyword, setKeyword] = useState(filters.q || '');
|
||||
|
||||
useEffect(() => { setKeyword(filters.q || ''); }, [filters.q]);
|
||||
|
||||
const projectOptions = useMemo(() => (projects || []).map(project => ({
|
||||
value: project.id,
|
||||
label: project.name || project.id
|
||||
})), [projects]);
|
||||
|
||||
const advancedCount = ['status', 'risk_level', 'environment', 'criticality', 'ip', 'domain', 'port', 'scan']
|
||||
.filter(key => filters[key]).length;
|
||||
|
||||
|
|
@ -60,15 +55,6 @@ export default function AssetFilterBar({ filters, projects, onChange, onReset, d
|
|||
onChange={value => onChange({ source: value })}
|
||||
showClear
|
||||
/>
|
||||
<Select
|
||||
value={filters.project_id || undefined}
|
||||
placeholder={t('assets.project', null, '所属项目')}
|
||||
optionList={projectOptions}
|
||||
filter
|
||||
showClear
|
||||
disabled={disabled}
|
||||
onChange={value => onChange({ project_id: value || '' })}
|
||||
/>
|
||||
<Input
|
||||
value={filters.tag}
|
||||
placeholder={t('assets.tagsLabel', null, '标签')}
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import {
|
|||
import { IconCloudUploadStroked } from '@douyinfe/semi-icons';
|
||||
import { api, errorMessage } from '../../../lib/http';
|
||||
import { useT } from '../../../lib/i18n';
|
||||
import { Drawer, toastSuccess } from '../../../components/ui';
|
||||
import { Drawer, toastSuccess, toastWarning } from '../../../components/ui';
|
||||
import { assetTargetLabel } from './assetTarget';
|
||||
import { csvTemplate, downloadTextFile, recordsFromCsv, recordsFromJson } from './assetCsv';
|
||||
|
||||
|
|
@ -38,7 +38,7 @@ const PREVIEW_COLUMNS = (t) => [
|
|||
}
|
||||
];
|
||||
|
||||
export default function AssetImportModal({ visible, projects, onClose, onDone }) {
|
||||
export default function AssetImportModal({ visible, projects, defaultProjectId, onClose, onDone }) {
|
||||
const t = useT();
|
||||
const [format, setFormat] = useState('csv');
|
||||
const [text, setText] = useState('');
|
||||
|
|
@ -50,14 +50,15 @@ export default function AssetImportModal({ visible, projects, onClose, onDone })
|
|||
const parsed = useMemo(() => {
|
||||
if (!String(text || '').trim()) return { records: [], error: '' };
|
||||
try {
|
||||
const options = { projects, projectId: defaultProjectId, source: 'manual-import' };
|
||||
const records = format === 'csv'
|
||||
? recordsFromCsv(text, { projects, source: 'manual-import' })
|
||||
: recordsFromJson(text, { projects, source: 'manual-import' });
|
||||
? recordsFromCsv(text, options)
|
||||
: recordsFromJson(text, options);
|
||||
return { records, error: '' };
|
||||
} catch (parseError) {
|
||||
return { records: [], error: parseError.message };
|
||||
}
|
||||
}, [text, format, projects]);
|
||||
}, [text, format, projects, defaultProjectId]);
|
||||
|
||||
const records = parsed.records;
|
||||
const valid = records.filter(record => !record.error);
|
||||
|
|
@ -112,11 +113,15 @@ export default function AssetImportModal({ visible, projects, onClose, onDone })
|
|||
source_query: fileName || 'paste'
|
||||
});
|
||||
const skipped = Number(result?.skipped || 0) + invalid;
|
||||
const conflicts = Number(result?.project_conflicts || 0);
|
||||
toastSuccess(t('assets.bulkImportDone', {
|
||||
created: Number(result?.created || 0),
|
||||
updated: Number(result?.updated || 0),
|
||||
skipped
|
||||
}, `导入完成:新增 ${Number(result?.created || 0)} 条,更新 ${Number(result?.updated || 0)} 条,跳过 ${skipped} 条`));
|
||||
if (conflicts) {
|
||||
toastWarning(t('assets.importProjectConflicts', { count: conflicts }, `已跳过 ${conflicts} 条归属不同的重复资产。`));
|
||||
}
|
||||
reset();
|
||||
onDone?.();
|
||||
onClose?.();
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@ export default function AssetTable({
|
|||
title: t('assets.project', null, '所属项目'),
|
||||
dataIndex: 'project_name',
|
||||
width: 160,
|
||||
render: value => <TooltipText text={value} max={18} />
|
||||
render: (value, record) => <TooltipText text={value || record.project_id || t('assets.scopeUnassigned', null, '未归属项目')} max={18} />
|
||||
},
|
||||
{
|
||||
title: t('assets.source', null, '来源'),
|
||||
|
|
|
|||
|
|
@ -94,7 +94,7 @@ function resolveProject(value, projects) {
|
|||
return { projectId: project.id, projectName: project.name, error: '' };
|
||||
}
|
||||
|
||||
function buildRecord(values, rowNumber, { projects, source }) {
|
||||
function buildRecord(values, rowNumber, { projects, projectId, source }) {
|
||||
const fail = message => ({ rowNumber, values, asset: null, error: message });
|
||||
const target = values.target || values.host || values.domain || values.ip || '';
|
||||
if (!target) return fail('缺少目标地址');
|
||||
|
|
@ -120,8 +120,9 @@ function buildRecord(values, rowNumber, { projects, source }) {
|
|||
if (environment === null) return fail('环境值无效');
|
||||
const criticality = localizedEnum(values.criticality, CRITICALITY_LABELS, '');
|
||||
if (criticality === null) return fail('重要性值无效');
|
||||
const project = resolveProject(values.project, projects);
|
||||
const project = resolveProject(values.project || projectId, projects);
|
||||
if (project.error) return fail(project.error);
|
||||
if (projectId !== undefined && project.projectId !== projectId) return fail('该行的项目与当前资产范围不一致');
|
||||
const tags = splitTags(values.tags);
|
||||
if (tags.length > 30) return fail('标签最多 30 个');
|
||||
if (tags.some(tag => Array.from(tag).length > 64)) return fail('单个标签最多 64 个字符');
|
||||
|
|
|
|||
|
|
@ -1,21 +1,30 @@
|
|||
/** 项目下拉数据:资产绑定/筛选共用,失败时降级为空列表。 */
|
||||
/** 项目下拉数据:资产范围与绑定共用。 */
|
||||
import { api } from '../../../lib/http';
|
||||
import { useResource } from '../../../components/hooks';
|
||||
|
||||
export function useAssetProjects() {
|
||||
const { data, loading, reload } = useResource(
|
||||
() => api.get('/projects', { limit: 200 }),
|
||||
[],
|
||||
{ initial: { projects: [] } }
|
||||
const { data, loading, error, reload } = useResource(
|
||||
fetchAssetProjects,
|
||||
[]
|
||||
);
|
||||
return {
|
||||
projects: Array.isArray(data?.projects) ? data.projects : [],
|
||||
projects: data || [],
|
||||
loading,
|
||||
error,
|
||||
reload
|
||||
};
|
||||
}
|
||||
|
||||
export async function fetchAssetProjects() {
|
||||
const payload = await api.get('/projects', { limit: 200 });
|
||||
return Array.isArray(payload?.projects) ? payload.projects : [];
|
||||
const projects = [];
|
||||
const limit = 500;
|
||||
let total;
|
||||
do {
|
||||
const payload = await api.get('/projects', { limit, offset: projects.length });
|
||||
const batch = payload?.projects || [];
|
||||
projects.push(...batch);
|
||||
if (batch.length < limit) break;
|
||||
total = Number(payload?.total || projects.length);
|
||||
} while (projects.length < total);
|
||||
return projects;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
/** 资产库:筛选、分页、行内操作、详情、新建/编辑、批量、导入、合并、绑定项目、导出。 */
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { useLocation, useSearchParams } from 'react-router-dom';
|
||||
import { Banner, Button, Space, Typography } from '@douyinfe/semi-ui';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { Banner, Button, Select, Space, Typography } from '@douyinfe/semi-ui';
|
||||
import { IconPlus, IconRefresh, IconCloudUploadStroked } from '@douyinfe/semi-icons';
|
||||
import { api } from '../../lib/http';
|
||||
import { useAuth } from '../../lib/auth';
|
||||
|
|
@ -32,7 +32,6 @@ export function buildAssetQuery(filters, page, pageSize) {
|
|||
q: filters.q,
|
||||
protocol: filters.protocol,
|
||||
source: filters.source,
|
||||
project_id: filters.project_id,
|
||||
tag: filters.tag,
|
||||
status: filters.status,
|
||||
risk_level: filters.risk_level,
|
||||
|
|
@ -50,16 +49,36 @@ export function buildAssetQuery(filters, page, pageSize) {
|
|||
}
|
||||
|
||||
export default function AssetLibraryPage() {
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const projectResource = useAssetProjects();
|
||||
const projectId = searchParams.get('project_id') || '';
|
||||
const scope = projectId ? 'project' : searchParams.get('scope');
|
||||
return (
|
||||
<AssetLibraryWorkspace
|
||||
key={projectId || scope || ''}
|
||||
projectId={projectId}
|
||||
scope={scope}
|
||||
projectResource={projectResource}
|
||||
searchParams={searchParams}
|
||||
setSearchParams={setSearchParams}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function AssetLibraryWorkspace({ projectId, scope, projectResource, searchParams, setSearchParams }) {
|
||||
const t = useT();
|
||||
const { hasPermission } = useAuth();
|
||||
const canRead = hasPermission('asset:read');
|
||||
const canWrite = hasPermission('asset:write');
|
||||
const canDelete = hasPermission('asset:delete');
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const location = useLocation();
|
||||
const deepId = searchParams.get('id') || '';
|
||||
const linkedAsset = location.state?.asset || null;
|
||||
const hasScope = Boolean(projectId) || scope === 'all' || scope === 'unassigned';
|
||||
const scopeValue = projectId ? `project:${projectId}` : (hasScope ? scope : undefined);
|
||||
const scopeQuery = useMemo(() => ({
|
||||
project_id: projectId,
|
||||
project_unassigned: scope === 'unassigned' ? true : undefined
|
||||
}), [projectId, scope]);
|
||||
|
||||
const [filters, setFilters] = useState(() => ({
|
||||
...emptyAssetFilters(),
|
||||
|
|
@ -67,8 +86,8 @@ export default function AssetLibraryPage() {
|
|||
}));
|
||||
const [page, setPage] = useState(1);
|
||||
const [pageSize, setPageSize] = useState(20);
|
||||
const [tick, setTick] = useState(0);
|
||||
const [selection, setSelection] = useState({ keys: [], rows: [] });
|
||||
const selectionRevision = useRef(0);
|
||||
const [detailAsset, setDetailAsset] = useState(null);
|
||||
const [editorOpen, setEditorOpen] = useState(false);
|
||||
const [editorAsset, setEditorAsset] = useState(null);
|
||||
|
|
@ -80,67 +99,81 @@ export default function AssetLibraryPage() {
|
|||
|
||||
const debouncedFilters = useDebounced(filters, 300);
|
||||
const query = useMemo(
|
||||
() => buildAssetQuery(debouncedFilters, page, pageSize),
|
||||
[debouncedFilters, page, pageSize]
|
||||
() => ({ ...buildAssetQuery(debouncedFilters, page, pageSize), ...scopeQuery }),
|
||||
[debouncedFilters, page, pageSize, scopeQuery]
|
||||
);
|
||||
const { data, loading, error, reload } = useResource(
|
||||
() => api.get('/assets', query),
|
||||
[query, tick],
|
||||
{ skip: !canRead }
|
||||
[query, canRead, hasScope],
|
||||
{ skip: !canRead || !hasScope }
|
||||
);
|
||||
const { projects, reload: reloadProjects } = useAssetProjects();
|
||||
const { projects, loading: projectsLoading, error: projectError, reload: reloadProjects } = projectResource;
|
||||
|
||||
const assets = useMemo(() => (Array.isArray(data?.assets) ? data.assets : []), [data]);
|
||||
const total = Number(data?.total || 0);
|
||||
const total = error ? 0 : Number(data?.total || 0);
|
||||
const queryPending = loading || debouncedFilters !== filters;
|
||||
const projectName = projects.find(project => project.id === projectId)?.name || projectId;
|
||||
const scopeOptions = [
|
||||
...projects.map(project => ({ value: `project:${project.id}`, label: project.name || project.id })),
|
||||
{ value: 'unassigned', label: t('assets.scopeUnassigned', null, '未归属项目') },
|
||||
{ value: 'all', label: t('assets.scopeAll', null, '全部资产') }
|
||||
];
|
||||
if (projectId && !scopeOptions.some(option => option.value === scopeValue)) {
|
||||
scopeOptions.unshift({ value: scopeValue, label: projectName });
|
||||
}
|
||||
const scopeName = scopeOptions.find(option => option.value === scopeValue)?.label;
|
||||
|
||||
const resolvedDeep = useRef('');
|
||||
|
||||
useEffect(() => {
|
||||
if (!deepId || !linkedAsset?.id || linkedAsset.id !== deepId || resolvedDeep.current === deepId) return;
|
||||
resolvedDeep.current = deepId;
|
||||
setDetailAsset(linkedAsset);
|
||||
}, [deepId, linkedAsset]);
|
||||
useEffect(() => () => { selectionRevision.current += 1; }, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!deepId || deepId === resolvedDeep.current) return undefined;
|
||||
const inPage = assets.find(item => item.id === deepId);
|
||||
if (inPage) {
|
||||
resolvedDeep.current = deepId;
|
||||
setDetailAsset(inPage);
|
||||
if (!deepId) {
|
||||
resolvedDeep.current = '';
|
||||
setDetailAsset(null);
|
||||
return undefined;
|
||||
}
|
||||
if (!canRead || deepId === resolvedDeep.current) return undefined;
|
||||
let cancelled = false;
|
||||
(async () => {
|
||||
for (let current = 1; current <= 5 && !cancelled; current += 1) {
|
||||
const payload = await api.get('/assets', { page_size: 100, page: current });
|
||||
const hit = (payload?.assets || []).find(item => item.id === deepId);
|
||||
if (hit) {
|
||||
if (!cancelled) {
|
||||
resolvedDeep.current = deepId;
|
||||
setDetailAsset(hit);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (current >= Number(payload?.total_pages || 1)) break;
|
||||
}
|
||||
if (!cancelled) resolvedDeep.current = deepId;
|
||||
})().catch(() => { resolvedDeep.current = deepId; });
|
||||
api.get('/assets', { ...scopeQuery, id: deepId, page_size: 1 }).then(payload => {
|
||||
if (cancelled) return;
|
||||
resolvedDeep.current = deepId;
|
||||
setDetailAsset(payload?.assets?.find(item => item.id === deepId) || null);
|
||||
}).catch(detailError => {
|
||||
if (!cancelled) toastError(detailError, t('assets.loadFailed', null, '加载资产失败'));
|
||||
});
|
||||
return () => { cancelled = true; };
|
||||
}, [deepId, assets]);
|
||||
}, [canRead, deepId, scopeQuery, t]);
|
||||
|
||||
const changeScope = value => {
|
||||
const next = new URLSearchParams();
|
||||
if (value?.startsWith('project:')) next.set('project_id', value.slice('project:'.length));
|
||||
else if (value) next.set('scope', value);
|
||||
setSearchParams(next);
|
||||
};
|
||||
|
||||
const clearSelection = () => {
|
||||
selectionRevision.current += 1;
|
||||
setSelection({ keys: [], rows: [] });
|
||||
};
|
||||
|
||||
const changeFilters = patch => {
|
||||
setFilters(prev => ({ ...prev, ...patch }));
|
||||
setPage(1);
|
||||
setSelection({ keys: [], rows: [] });
|
||||
clearSelection();
|
||||
};
|
||||
|
||||
const resetFilters = () => {
|
||||
setFilters(emptyAssetFilters());
|
||||
setPage(1);
|
||||
setSelection({ keys: [], rows: [] });
|
||||
clearSelection();
|
||||
};
|
||||
|
||||
const refresh = () => setTick(value => value + 1);
|
||||
const refresh = () => {
|
||||
clearSelection();
|
||||
if (hasScope) reload();
|
||||
reloadProjects();
|
||||
};
|
||||
|
||||
const writeDeepLink = assetId => {
|
||||
const next = new URLSearchParams(searchParams);
|
||||
|
|
@ -150,6 +183,7 @@ export default function AssetLibraryPage() {
|
|||
};
|
||||
|
||||
const openDetail = asset => {
|
||||
resolvedDeep.current = asset.id;
|
||||
setDetailAsset(asset);
|
||||
if (asset?.id) writeDeepLink(asset.id);
|
||||
};
|
||||
|
|
@ -169,7 +203,7 @@ export default function AssetLibraryPage() {
|
|||
};
|
||||
|
||||
const afterWrite = async () => {
|
||||
setSelection({ keys: [], rows: [] });
|
||||
clearSelection();
|
||||
await reload();
|
||||
};
|
||||
|
||||
|
|
@ -185,7 +219,10 @@ export default function AssetLibraryPage() {
|
|||
if (!ids.length) return;
|
||||
confirmAction({
|
||||
title: t('assets.deleteConfirm', null, '确定删除所选资产吗?'),
|
||||
content: `将永久删除 ${ids.length} 个资产。`,
|
||||
content: t('assets.scopedDeleteConfirm', {
|
||||
count: ids.length,
|
||||
project: selection.rows[0]?.project_name || selection.rows[0]?.project_id || t('assets.scopeUnassigned', null, '未归属项目')
|
||||
}, `将永久删除所选的 ${ids.length} 个资产。`),
|
||||
okText: t('common.delete', null, '删除'),
|
||||
onOk: async () => {
|
||||
try {
|
||||
|
|
@ -200,18 +237,20 @@ export default function AssetLibraryPage() {
|
|||
};
|
||||
|
||||
const selectionQuery = useMemo(() => {
|
||||
const { page: _page, page_size: _size, ...rest } = buildAssetQuery(debouncedFilters, 1, pageSize);
|
||||
const { page: _page, page_size: _size, ...rest } = query;
|
||||
return rest;
|
||||
}, [debouncedFilters, pageSize]);
|
||||
}, [query]);
|
||||
|
||||
const selectAllMatching = async () => {
|
||||
const revision = ++selectionRevision.current;
|
||||
try {
|
||||
const payload = await api.get('/assets/selection', selectionQuery);
|
||||
if (revision !== selectionRevision.current) return;
|
||||
const rows = Array.isArray(payload?.assets) ? payload.assets : [];
|
||||
setSelection({ keys: rows.map(item => item.id), rows });
|
||||
toastSuccess(t('assets.allResultsSelected', { count: rows.length }, `已选择 ${rows.length} 项`));
|
||||
} catch (selectionError) {
|
||||
toastError(selectionError, '选择全部结果失败');
|
||||
if (revision === selectionRevision.current) toastError(selectionError, '选择全部结果失败');
|
||||
}
|
||||
};
|
||||
|
||||
|
|
@ -241,10 +280,13 @@ export default function AssetLibraryPage() {
|
|||
};
|
||||
|
||||
const onSelectionChange = (keys, rows) => {
|
||||
selectionRevision.current += 1;
|
||||
setSelection({ keys: keys || [], rows: rows || [] });
|
||||
};
|
||||
|
||||
const selectedCount = selection.keys.length;
|
||||
const mixedProjects = new Set(selection.rows.map(asset => asset.project_id || '')).size > 1;
|
||||
const canChangeSelection = selectedCount > 0 && !queryPending && !mixedProjects;
|
||||
|
||||
if (!canRead) {
|
||||
return (
|
||||
|
|
@ -264,7 +306,6 @@ export default function AssetLibraryPage() {
|
|||
<div className="asset-library-page">
|
||||
<PageHeader
|
||||
title={t('assets.libraryTitle', null, '资产库')}
|
||||
description="统一维护域名、IP、端口与服务资产,支持批量入库、合并与项目绑定。"
|
||||
extra={(
|
||||
<Space>
|
||||
<Button icon={<IconRefresh />} onClick={refresh} loading={loading}>
|
||||
|
|
@ -283,90 +324,111 @@ export default function AssetLibraryPage() {
|
|||
</Space>
|
||||
)}
|
||||
/>
|
||||
<ErrorBanner error={error} onRetry={refresh} />
|
||||
|
||||
<SectionCard title={t('assets.filterTitle', null, '筛选条件')}>
|
||||
<AssetFilterBar
|
||||
filters={filters}
|
||||
projects={projects}
|
||||
onChange={changeFilters}
|
||||
onReset={resetFilters}
|
||||
<SectionCard title={<span id="asset-library-scope-label">{t('assets.scopeLabel', null, '资产范围')}</span>}>
|
||||
<Select
|
||||
aria-labelledby="asset-library-scope-label"
|
||||
className="asset-library-scope"
|
||||
value={scopeValue}
|
||||
placeholder={t('assets.scopePlaceholder', null, '选择项目或查看全部资产')}
|
||||
optionList={scopeOptions}
|
||||
loading={projectsLoading}
|
||||
onChange={changeScope}
|
||||
filter
|
||||
/>
|
||||
<ErrorBanner error={projectError} onRetry={reloadProjects} />
|
||||
</SectionCard>
|
||||
{hasScope && (
|
||||
<>
|
||||
<ErrorBanner error={error} onRetry={refresh} />
|
||||
|
||||
<SectionCard
|
||||
title={`${t('assets.libraryTitle', null, '资产库')}(${total})`}
|
||||
extra={(
|
||||
<Space>
|
||||
<Button
|
||||
theme="borderless"
|
||||
disabled={!selectedCount}
|
||||
onClick={() => setSelection({ keys: [], rows: [] })}
|
||||
>
|
||||
{t('assets.clearSelection', null, '清除选择')}
|
||||
</Button>
|
||||
<Button theme="borderless" onClick={() => exportCsv(false)} loading={exporting}>
|
||||
{t('assets.exportCsv', null, '导出 CSV')}
|
||||
</Button>
|
||||
<Button theme="borderless" onClick={() => exportCsv(true)} loading={exporting}>
|
||||
{t('assets.exportAll', null, '导出全部筛选结果')}
|
||||
</Button>
|
||||
</Space>
|
||||
)}
|
||||
>
|
||||
<div className="asset-library-toolbar">
|
||||
<Space>
|
||||
<Text type="tertiary">
|
||||
{selectedCount
|
||||
? t('assets.selectedCount', { count: selectedCount }, `已选择 ${selectedCount} 项`)
|
||||
: t('assets.selectedCount', { count: 0 }, '已选择 0 项')}
|
||||
</Text>
|
||||
<Button theme="borderless" size="small" onClick={selectAllMatching}>
|
||||
{t('assets.selectAllResults', { count: total }, `选择全部 ${total} 项`)}
|
||||
</Button>
|
||||
</Space>
|
||||
<Space>
|
||||
{canWrite && (
|
||||
<Button size="small" disabled={selectedCount < 2} onClick={() => setMergeOpen(true)}>
|
||||
{t('assets.mergeDuplicates', null, '合并重复资产')}
|
||||
</Button>
|
||||
)}
|
||||
{canWrite && (
|
||||
<Button size="small" disabled={!selectedCount} onClick={() => setProjectOpen(true)}>
|
||||
{t('assets.bindProject', null, '绑定项目')}
|
||||
</Button>
|
||||
)}
|
||||
{canWrite && (
|
||||
<Button size="small" disabled={!selectedCount} onClick={() => setBulkOpen(true)}>
|
||||
{t('assets.bulkEdit', null, '批量编辑')}
|
||||
</Button>
|
||||
)}
|
||||
{canDelete && (
|
||||
<Button size="small" type="danger" disabled={!selectedCount} onClick={batchDelete}>
|
||||
{t('assets.batchDelete', null, '批量删除…')}
|
||||
</Button>
|
||||
)}
|
||||
</Space>
|
||||
</div>
|
||||
<SectionCard title={t('assets.filterTitle', null, '筛选条件')}>
|
||||
<AssetFilterBar
|
||||
filters={filters}
|
||||
onChange={changeFilters}
|
||||
onReset={resetFilters}
|
||||
/>
|
||||
</SectionCard>
|
||||
|
||||
<AssetTable
|
||||
assets={assets}
|
||||
loading={loading}
|
||||
total={total}
|
||||
page={page}
|
||||
pageSize={pageSize}
|
||||
onPageChange={next => { setPage(next); setSelection({ keys: [], rows: [] }); }}
|
||||
onPageSizeChange={next => { setPageSize(next); setPage(1); setSelection({ keys: [], rows: [] }); }}
|
||||
selectedRowKeys={selection.keys}
|
||||
onSelectionChange={onSelectionChange}
|
||||
onView={openDetail}
|
||||
onEdit={openEditor}
|
||||
onDelete={deleteAsset}
|
||||
onRefresh={refresh}
|
||||
canWrite={canWrite}
|
||||
canDelete={canDelete}
|
||||
/>
|
||||
</SectionCard>
|
||||
<SectionCard
|
||||
title={`${scopeName}(${total})`}
|
||||
extra={(
|
||||
<Space>
|
||||
<Button
|
||||
theme="borderless"
|
||||
disabled={!selectedCount}
|
||||
onClick={clearSelection}
|
||||
>
|
||||
{t('assets.clearSelection', null, '清除选择')}
|
||||
</Button>
|
||||
<Button theme="borderless" disabled={queryPending || !total} onClick={() => exportCsv(false)} loading={exporting}>
|
||||
{t('assets.exportCsv', null, '导出 CSV')}
|
||||
</Button>
|
||||
<Button theme="borderless" disabled={queryPending || !total} onClick={() => exportCsv(true)} loading={exporting}>
|
||||
{t('assets.exportAll', null, '导出全部筛选结果')}
|
||||
</Button>
|
||||
</Space>
|
||||
)}
|
||||
>
|
||||
<div className="asset-library-toolbar">
|
||||
<Space>
|
||||
<Text type="tertiary">
|
||||
{selectedCount
|
||||
? t('assets.selectedCount', { count: selectedCount }, `已选择 ${selectedCount} 项`)
|
||||
: t('assets.selectedCount', { count: 0 }, '已选择 0 项')}
|
||||
</Text>
|
||||
<Button theme="borderless" size="small" disabled={queryPending || !total} onClick={selectAllMatching}>
|
||||
{t('assets.selectAllResults', { count: total }, `选择全部 ${total} 项`)}
|
||||
</Button>
|
||||
</Space>
|
||||
<Space>
|
||||
{canWrite && (
|
||||
<Button size="small" disabled={!canChangeSelection || selectedCount < 2 || !canDelete} onClick={() => setMergeOpen(true)}>
|
||||
{t('assets.mergeDuplicates', null, '合并重复资产')}
|
||||
</Button>
|
||||
)}
|
||||
{canWrite && (
|
||||
<Button size="small" disabled={!canChangeSelection} onClick={() => setProjectOpen(true)}>
|
||||
{t('assets.bindProject', null, '绑定项目')}
|
||||
</Button>
|
||||
)}
|
||||
{canWrite && (
|
||||
<Button size="small" disabled={!canChangeSelection} onClick={() => setBulkOpen(true)}>
|
||||
{t('assets.bulkEdit', null, '批量编辑')}
|
||||
</Button>
|
||||
)}
|
||||
{canDelete && (
|
||||
<Button size="small" type="danger" disabled={!canChangeSelection} onClick={batchDelete}>
|
||||
{t('assets.batchDelete', null, '批量删除…')}
|
||||
</Button>
|
||||
)}
|
||||
</Space>
|
||||
</div>
|
||||
{mixedProjects && (canWrite || canDelete) && (
|
||||
<Text type="tertiary" size="small">
|
||||
{t('assets.mixedProjectSelection', null, '批量修改前,请将选择缩小到同一项目或仅选择未归属资产。')}
|
||||
</Text>
|
||||
)}
|
||||
|
||||
<AssetTable
|
||||
assets={queryPending || error ? [] : assets}
|
||||
loading={queryPending}
|
||||
total={total}
|
||||
page={page}
|
||||
pageSize={pageSize}
|
||||
onPageChange={next => { setPage(next); clearSelection(); }}
|
||||
onPageSizeChange={next => { setPageSize(next); setPage(1); clearSelection(); }}
|
||||
selectedRowKeys={selection.keys}
|
||||
onSelectionChange={onSelectionChange}
|
||||
onView={openDetail}
|
||||
onEdit={openEditor}
|
||||
onDelete={deleteAsset}
|
||||
onRefresh={refresh}
|
||||
canWrite={canWrite}
|
||||
canDelete={canDelete}
|
||||
/>
|
||||
</SectionCard>
|
||||
</>
|
||||
)}
|
||||
|
||||
<AssetDetailDrawer
|
||||
asset={detailAsset}
|
||||
|
|
@ -388,12 +450,14 @@ export default function AssetLibraryPage() {
|
|||
<AssetEditorModal
|
||||
visible={editorOpen}
|
||||
asset={editorAsset}
|
||||
defaultProjectId={projectId}
|
||||
projects={projects}
|
||||
onClose={() => setEditorOpen(false)}
|
||||
onSaved={afterWrite}
|
||||
/>
|
||||
<AssetImportModal
|
||||
visible={importOpen}
|
||||
defaultProjectId={scope === 'all' || !hasScope ? undefined : projectId}
|
||||
projects={projects}
|
||||
onClose={() => setImportOpen(false)}
|
||||
onDone={afterWrite}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
/* 资产库页面私有布局样式(颜色一律使用 Semi 变量)。 */
|
||||
.asset-library-page { display: flex; flex-direction: column; gap: 0; }
|
||||
.asset-library-scope { width: min(100%, 360px); }
|
||||
|
||||
.asset-library-filters { display: flex; flex-direction: column; gap: 8px; }
|
||||
.asset-library-filter-grid {
|
||||
|
|
|
|||
|
|
@ -97,8 +97,10 @@ export default function AssetOverviewPage() {
|
|||
];
|
||||
|
||||
const goLibrary = asset => {
|
||||
const suffix = asset?.id ? `?id=${encodeURIComponent(asset.id)}` : '';
|
||||
navigate(`/asset-library${suffix}`, asset ? { state: { asset } } : undefined);
|
||||
const params = new URLSearchParams({ id: asset.id });
|
||||
if (asset.project_id) params.set('project_id', asset.project_id);
|
||||
else params.set('scope', 'unassigned');
|
||||
navigate(`/asset-library?${params}`);
|
||||
};
|
||||
|
||||
const columns = [
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
/** 项目详情:概览统计、标签页与事实弹窗/详情侧栏的统一入口。 */
|
||||
import { useCallback, useMemo, useState } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Button, Space, Tabs, Tag, Typography } from '@douyinfe/semi-ui';
|
||||
import { IconRefresh } from '@douyinfe/semi-icons';
|
||||
import { api } from '../../lib/http';
|
||||
|
|
@ -20,6 +21,7 @@ const { Title, Text, Paragraph } = Typography;
|
|||
|
||||
export default function ProjectDetail({ projectId, tab, refreshToken = 0, onTabChange, onChanged, onDeleted }) {
|
||||
const t = useT();
|
||||
const navigate = useNavigate();
|
||||
const { hasPermission } = useAuth();
|
||||
const canWrite = hasPermission('project:write');
|
||||
const canDelete = hasPermission('project:delete');
|
||||
|
|
@ -86,7 +88,12 @@ export default function ProjectDetail({ projectId, tab, refreshToken = 0, onTabC
|
|||
{' · '}ID: <code>{projectId}</code>
|
||||
</Text>
|
||||
</div>
|
||||
<Space>
|
||||
<Space wrap>
|
||||
{current && hasPermission('asset:read') && (
|
||||
<Button onClick={() => navigate(`/asset-library?project_id=${encodeURIComponent(projectId)}`)}>
|
||||
{t('assets.projectAssets', null, '项目资产')}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
icon={<IconRefresh />}
|
||||
theme="borderless"
|
||||
|
|
|
|||
|
|
@ -18,7 +18,7 @@ const PAGE_READS = {
|
|||
'tool-guard': ['/api/tool-guard'],
|
||||
projects: ['/api/projects', `/api/projects/${PROJECT.id}`, `/api/projects/${PROJECT.id}/facts`],
|
||||
'asset-overview': ['/api/assets/stats', '/api/assets'],
|
||||
'asset-library': ['/api/assets'],
|
||||
'asset-library': ['/api/projects'],
|
||||
'info-collect': [], // No search is triggered just by opening the page.
|
||||
vulnerabilities: ['/api/vulnerabilities', '/api/vulnerabilities/filter-options'],
|
||||
tasks: ['/api/batch-tasks'],
|
||||
|
|
@ -304,6 +304,96 @@ test('navigation: four Semi groups, parent expansion, child selection and collap
|
|||
await expect.poll(() => page.evaluate(() => localStorage.getItem('csai-nav-collapsed'))).toBe('0');
|
||||
});
|
||||
|
||||
test.describe('asset library project scope', () => {
|
||||
test.use({ appPermissions: [...UI_PERMISSIONS, 'asset:write', 'asset:delete'] });
|
||||
|
||||
test('requires an explicit scope and clears a pending selection on project switch', async ({ page, mockApi }) => {
|
||||
const other = { id: 'other-project', name: '另一个项目' };
|
||||
const rows = [
|
||||
{ id: 'asset-one', host: 'one.example.test', project_id: PROJECT.id, project_name: PROJECT.name },
|
||||
{ id: 'asset-two', host: 'two.example.test', project_id: other.id, project_name: other.name },
|
||||
{ id: 'asset-three', host: 'three.example.test' }
|
||||
];
|
||||
const respond = (_, url) => {
|
||||
const params = url.searchParams;
|
||||
const assets = rows.filter(asset => (
|
||||
(!params.has('id') || asset.id === params.get('id'))
|
||||
&& (!params.has('project_id') || asset.project_id === params.get('project_id'))
|
||||
&& (!params.has('project_unassigned') || !asset.project_id)
|
||||
));
|
||||
return { json: { assets, total: assets.length } };
|
||||
};
|
||||
mockApi.respond('GET', '/api/projects', { json: { projects: [PROJECT, other], total: 2 } });
|
||||
mockApi.respond('GET', '/api/assets', respond);
|
||||
const main = await visit(page, 'asset-library');
|
||||
await readsCompleted(mockApi, ['/api/projects']);
|
||||
await expect(main.getByText(label('assets.scopePlaceholder'), { exact: true })).toBeVisible();
|
||||
expect(mockApi.calls('GET', '/api/assets')).toEqual([]);
|
||||
|
||||
const chooseScope = async name => {
|
||||
await main.getByRole('combobox', { name: label('assets.scopeLabel') }).click();
|
||||
await page.getByRole('option').filter({ has: page.getByText(name, { exact: true }) }).click();
|
||||
};
|
||||
await chooseScope(PROJECT.name);
|
||||
await expect(page).toHaveURL(/project_id=fixture-project$/);
|
||||
await expect(main.getByText(rows[0].host, { exact: true })).toBeVisible();
|
||||
await expect(main.getByText(rows[1].host, { exact: true })).toHaveCount(0);
|
||||
|
||||
let finishSelection;
|
||||
const pending = new Promise(resolve => { finishSelection = resolve; });
|
||||
mockApi.respond('GET', '/api/assets/selection', async (request, url) => {
|
||||
await pending;
|
||||
return respond(request, url);
|
||||
});
|
||||
const selectAll = count => button(main, label('assets.selectAllResults').replace('{{count}}', String(count)));
|
||||
const bulkDelete = button(main, label('assets.batchDelete', '批量删除…'));
|
||||
await selectAll(1).click();
|
||||
try {
|
||||
await expect.poll(() => mockApi.calls('GET', '/api/assets/selection').length).toBe(1);
|
||||
expect(new URLSearchParams(mockApi.calls('GET', '/api/assets/selection')[0].query).get('project_id')).toBe(PROJECT.id);
|
||||
await chooseScope(other.name);
|
||||
await expect(main.getByText(rows[1].host, { exact: true })).toBeVisible();
|
||||
await expect(main.getByText(rows[0].host, { exact: true })).toHaveCount(0);
|
||||
} finally {
|
||||
finishSelection();
|
||||
}
|
||||
await readsCompleted(mockApi, ['/api/assets/selection']);
|
||||
await expect(bulkDelete).toBeDisabled();
|
||||
|
||||
await chooseScope(label('assets.scopeUnassigned'));
|
||||
await expect(main.getByText(rows[2].host, { exact: true })).toBeVisible();
|
||||
await expect(main.getByText(rows[1].host, { exact: true })).toHaveCount(0);
|
||||
await chooseScope(label('assets.scopeAll'));
|
||||
await selectAll(3).click();
|
||||
await expect(main.getByText(label('assets.mixedProjectSelection'), { exact: true })).toBeVisible();
|
||||
await expect(bulkDelete).toBeDisabled();
|
||||
expect(mockApi.writes()).toEqual([]);
|
||||
expect(mockApi.unexpected).toEqual([]);
|
||||
});
|
||||
|
||||
test('opens project assets and imports blank project fields into that scope', async ({ page, mockApi }) => {
|
||||
const other = { id: 'other-project', name: '另一个项目' };
|
||||
mockApi.respond('GET', '/api/projects', { json: { projects: [PROJECT, other], total: 2 } });
|
||||
const main = await visit(page, 'projects');
|
||||
await button(main, label('assets.projectAssets')).click();
|
||||
await expect(page).toHaveURL(/asset-library\?project_id=fixture-project$/);
|
||||
await readsCompleted(mockApi, ['/api/assets']);
|
||||
expect(mockApi.calls('GET', '/api/assets').every(call => new URLSearchParams(call.query).get('project_id') === PROJECT.id)).toBe(true);
|
||||
|
||||
await button(main, label('assets.bulkImport')).click();
|
||||
const drawer = page.getByRole('dialog', { name: label('assets.bulkImportTitle') });
|
||||
await drawer.locator('textarea').fill(`target,project\r\nhttps://one.example.test,\r\nhttps://two.example.test,${other.name}`);
|
||||
await expect(drawer.getByText('该行的项目与当前资产范围不一致', { exact: true })).toBeVisible();
|
||||
mockApi.respond('POST', '/api/assets/import', { json: { created: 1, updated: 0, skipped: 0 } });
|
||||
await drawer.getByRole('button', { name: /导入 1 条有效数据/ }).click();
|
||||
await expect(drawer).toHaveCount(0);
|
||||
const [request] = mockApi.writes();
|
||||
expect(request.path).toBe('/api/assets/import');
|
||||
expect(request.body.assets).toEqual([expect.objectContaining({ domain: 'one.example.test', project_id: PROJECT.id })]);
|
||||
expect(mockApi.unexpected).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
test('navigation: collapsed submenus fit their labels and center beside the parent', async ({ page }, testInfo) => {
|
||||
await visit(page, 'chat');
|
||||
const sidebar = page.locator('.cs-sider');
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{At as r,Dt as i,F as a,H as o,L as s,M as c,W as l,i as u,lt as d,ot as f,st as p}from"./semi-Dpcldp_F.js";import{F as m,I as h,P as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-C3OHVG4q.js";var k=e(t(),1),A=e(n(),1),{Text:j}=l;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),l=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>h.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await h.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await h.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await h.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(a,{children:[(0,A.jsx)(s,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(s,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(d,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(a,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(a,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(c,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(c,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(a,{children:[(0,A.jsx)(s,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(s,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(i,{}),onClick:()=>L({record:t,form:{}})}),l&&(0,A.jsx)(s,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(r,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(o,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(u,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(u.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(u.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(u.Input,{field:`description`,label:`描述`}),(0,A.jsx)(u.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(u.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(u.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{At as r,Dt as i,F as a,H as o,L as s,M as c,W as l,i as u,lt as d,ot as f,st as p}from"./semi-Dpcldp_F.js";import{F as m,I as h,P as g,a as _,b as v,c as y,d as b,f as x,l as S,m as C,p as w,s as T,u as E,x as D,y as O}from"./index-Bsu8fBML.js";var k=e(t(),1),A=e(n(),1),{Text:j}=l;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),l=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>h.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await h.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await h.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await h.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(a,{children:[(0,A.jsx)(s,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(s,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(d,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(a,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(a,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(c,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(c,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(a,{children:[(0,A.jsx)(s,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(s,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(i,{}),onClick:()=>L({record:t,form:{}})}),l&&(0,A.jsx)(s,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(r,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(o,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(u,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(u.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(u.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(u.Input,{field:`description`,label:`描述`}),(0,A.jsx)(u.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(u.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(u.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r}from"./semi-Dpcldp_F.js";import{E as i,P as a,k as o}from"./index-C3OHVG4q.js";import"./c2-shared-Cyoaidty.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=r,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:r,ns:i=`tasks`}){let o=a();return(0,c.jsxs)(t,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:o(`c2.tasks.timePresets`,null,`快捷`)}),v.map(t=>(0,c.jsx)(n,{size:`small`,theme:t.value===e?`solid`:`borderless`,type:t.value===e?`primary`:`tertiary`,onClick:()=>r(t.value),children:o(`c2.${i}.preset${t.value===`all`?`All`:t.value}`,null,t.label)},t.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=a();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:i(e),children:o(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r}from"./semi-Dpcldp_F.js";import{E as i,P as a,k as o}from"./index-Bsu8fBML.js";import"./c2-shared-suNnnhGd.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=r,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:r,ns:i=`tasks`}){let o=a();return(0,c.jsxs)(t,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:o(`c2.tasks.timePresets`,null,`快捷`)}),v.map(t=>(0,c.jsx)(n,{size:`small`,theme:t.value===e?`solid`:`borderless`,type:t.value===e?`primary`:`tertiary`,onClick:()=>r(t.value),children:o(`c2.${i}.preset${t.value===`all`?`All`:t.value}`,null,t.label)},t.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=a();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:i(e),children:o(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};
|
||||
|
|
@ -1 +1 @@
|
|||
import{I as e,L as t}from"./index-C3OHVG4q.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};
|
||||
import{I as e,L as t}from"./index-Bsu8fBML.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{At as r,F as i,H as a,L as o,M as s,W as c,ot as l,st as u}from"./semi-Dpcldp_F.js";import{E as d,F as f,I as p,P as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-C3OHVG4q.js";var T=e(t(),1),E=e(n(),1),{Text:D}=c;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[c,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:c||void 0,limit:k}),[c,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await p.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(o,{icon:(0,E.jsx)(u,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(s,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(i,{children:[(0,E.jsx)(o,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(o,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(r,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(i,{children:[(0,E.jsx)(a,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:c,onChange:O,style:{width:260}}),(0,E.jsx)(a,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{At as r,F as i,H as a,L as o,M as s,W as c,ot as l,st as u}from"./semi-Dpcldp_F.js";import{E as d,F as f,I as p,P as m,a as h,c as g,d as _,l as v,m as y,p as b,s as x,u as S,x as C,y as w}from"./index-Bsu8fBML.js";var T=e(t(),1),E=e(n(),1),{Text:D}=c;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[c,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:c||void 0,limit:k}),[c,k]),P=Array.isArray(N.data?.logs)?N.data.logs:[],F=e=>w({title:`删除该检索日志?`,content:e.query||e.id,onOk:async()=>{await p.del(`/knowledge/retrieval-logs/${encodeURIComponent(e.id)}`),C(`已删除`),N.reload()}});return(0,E.jsxs)(`div`,{children:[(0,E.jsx)(b,{title:e(`knowledge.retrievalLogsTitle`,null,`检索历史`),description:`记录智能体每次知识库检索的语句、命中项与会话,用于回溯回答依据。`,extra:(0,E.jsx)(o,{icon:(0,E.jsx)(u,{}),onClick:()=>N.reload(),loading:N.loading,children:`刷新`})}),(0,E.jsxs)(y,{title:`检索记录(${P.length})`,children:[(0,E.jsx)(v,{error:N.error,onRetry:()=>N.reload()}),(0,E.jsx)(x,{columns:[{title:`检索语句`,dataIndex:`query`,render:(e,t)=>(0,E.jsx)(`button`,{type:`button`,className:`link-button`,onClick:()=>M(t),style:{background:`none`,border:`none`,padding:0,cursor:`pointer`,textAlign:`left`,color:`var(--semi-color-primary)`},children:e||`—`})},{title:`风险类型`,dataIndex:`riskType`,width:140,render:e=>e?(0,E.jsx)(s,{size:`small`,children:e}):`—`},{title:`命中知识项`,dataIndex:`retrievedItems`,width:120,render:e=>(0,E.jsxs)(D,{type:`tertiary`,children:[Array.isArray(e)?e.length:0,` 条`]})},{title:`会话`,dataIndex:`conversationId`,width:200,render:e=>(0,E.jsx)(D,{type:`tertiary`,ellipsis:{showTooltip:!0},children:e||`—`})},{title:`时间`,dataIndex:`createdAt`,width:180,render:e=>d(e)},{title:`操作`,width:110,render:(e,t)=>(0,E.jsxs)(i,{children:[(0,E.jsx)(o,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(o,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(r,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(i,{children:[(0,E.jsx)(a,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:c,onChange:O,style:{width:260}}),(0,E.jsx)(a,{placeholder:`条数`,value:String(k),onChange:e=>A(Math.min(Math.max(Number(e)||50,1),500)),style:{width:100},suffix:(0,E.jsx)(D,{type:`tertiary`,children:`条`})})]})})]}),(0,E.jsx)(g,{title:`检索日志详情`,visible:!!j,onCancel:()=>M(null),width:560,children:j&&(0,E.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,E.jsx)(_,{items:[{label:`日志 ID`,value:j.id},{label:`检索语句`,value:j.query},{label:`风险类型`,value:j.riskType||`—`},{label:`会话 ID`,value:j.conversationId||`—`},{label:`消息 ID`,value:j.messageId||`—`},{label:`时间`,value:d(j.createdAt)}]}),(0,E.jsx)(S,{value:j.retrievedItems||[],title:`命中知识项`})]})})]})}export{O as default};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{W as r,i}from"./semi-Dpcldp_F.js";import{I as a,P as o,c as s,l as c,x as l}from"./index-C3OHVG4q.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=o(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await a.put(`/projects/${t.id}`,n):await a.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{W as r,i}from"./semi-Dpcldp_F.js";import{I as a,P as o,c as s,l as c,x as l}from"./index-Bsu8fBML.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=o(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await a.put(`/projects/${t.id}`,n):await a.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{At as r,Dt as i,F as a,H as o,L as s,M as c,W as l,i as u,lt as d,ot as f,st as p}from"./semi-Dpcldp_F.js";import{F as m,I as h,P as g,a as _,b as v,c as y,l as b,m as x,p as S,s as C,x as w,y as T}from"./index-C3OHVG4q.js";var E=e(t(),1),D=e(n(),1),{Text:O}=l;function k(){let e=g(),{hasPermission:t}=m(),n=t(`roles:write`),l=t(`roles:delete`),[k,A]=(0,E.useState)(``),[j,M]=(0,E.useState)(null),[N,P]=(0,E.useState)(!1),F=_(()=>h.get(`/roles`),[]),I=(Array.isArray(F.data?.roles)?F.data.roles:[]).filter(e=>{if(!k)return!0;let t=k.toLowerCase();return[e.name,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),L=async()=>{let e=await j.form.validate();P(!0);try{let t={name:e.name.trim(),description:e.description?.trim()||``,user_prompt:e.user_prompt||``,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean),enabled:e.enabled!==!1},n=j.role?.name;n&&n!==t.name?(await h.post(`/roles`,t),await h.del(`/roles/${encodeURIComponent(n)}`)):n?await h.put(`/roles/${encodeURIComponent(n)}`,t):await h.post(`/roles`,t),w(`角色已保存`),M(null),F.reload()}catch(e){v(e,`保存角色失败`)}finally{P(!1)}},R=e=>T({title:`删除角色「${e.name}」?`,content:`已绑定该角色的对话将失去对应提示词与工具配置。`,onOk:async()=>{await h.del(`/roles/${encodeURIComponent(e.name)}`),w(`已删除`),F.reload()}});return(0,D.jsxs)(`div`,{children:[(0,D.jsx)(S,{title:e(`roles.title`,null,`角色管理`),description:`角色定义对话的系统提示词、可用工具与绑定工作流。`,extra:(0,D.jsxs)(a,{children:[(0,D.jsx)(s,{icon:(0,D.jsx)(p,{}),onClick:()=>F.reload(),loading:F.loading,children:`刷新`}),n&&(0,D.jsx)(s,{theme:`solid`,type:`primary`,icon:(0,D.jsx)(d,{}),onClick:()=>M({role:null,form:{}}),children:`新建角色`})]})}),(0,D.jsxs)(x,{title:`角色(${I.length})`,children:[(0,D.jsx)(b,{error:F.error,onRetry:()=>F.reload()}),(0,D.jsx)(C,{columns:[{title:`角色`,dataIndex:`name`,render:(e,t)=>(0,D.jsxs)(a,{vertical:!0,spacing:0,align:`start`,children:[(0,D.jsxs)(a,{children:[(0,D.jsx)(O,{strong:!0,children:e}),t.enabled===!1&&(0,D.jsx)(c,{size:`small`,color:`grey`,children:`已停用`})]}),(0,D.jsx)(O,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:t.description||`—`})]})},{title:`工具`,dataIndex:`tools`,width:260,render:e=>Array.isArray(e)&&e.length?(0,D.jsxs)(a,{wrap:!0,spacing:4,children:[e.slice(0,4).map(e=>(0,D.jsx)(c,{size:`small`,children:e},e)),e.length>4&&(0,D.jsxs)(O,{type:`tertiary`,children:[`+`,e.length-4]})]}):(0,D.jsx)(O,{type:`tertiary`,children:`未绑定`})},{title:`工作流`,dataIndex:`workflow_id`,width:160,render:e=>e||`—`},{title:`操作`,width:150,render:(e,t)=>(0,D.jsxs)(a,{children:[n&&(0,D.jsx)(s,{size:`small`,theme:`borderless`,icon:(0,D.jsx)(i,{}),onClick:()=>M({role:t,form:{}}),children:`编辑`}),l&&(0,D.jsx)(s,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,D.jsx)(r,{}),onClick:()=>R(t)})]})}],dataSource:I,rowKey:`name`,loading:F.loading,pagination:{pageSize:20},toolbar:(0,D.jsx)(o,{prefix:(0,D.jsx)(f,{}),value:k,onChange:A,placeholder:`搜索角色名称`,style:{width:260}})})]}),(0,D.jsx)(y,{title:j?.role?`编辑角色`:`新建角色`,visible:!!j,onCancel:()=>M(null),onOk:L,confirmLoading:N,width:760,children:(0,D.jsxs)(u,{getFormApi:e=>M(t=>t&&{...t,form:e}),initValues:j?.role?{name:j.role.name,description:j.role.description,user_prompt:j.role.user_prompt,tools:Array.isArray(j.role.tools)?j.role.tools.join(`, `):``,enabled:j.role.enabled!==!1}:{enabled:!0},children:[(0,D.jsx)(u.Input,{field:`name`,label:`角色名称`,rules:[{required:!0,message:`请输入角色名称`}]}),(0,D.jsx)(u.Input,{field:`description`,label:`描述`}),(0,D.jsx)(u.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::toolName`}),(0,D.jsx)(u.TextArea,{field:`user_prompt`,label:`用户提示词(追加到用户消息前)`,autosize:{minRows:6,maxRows:18}}),(0,D.jsx)(u.Slot,{label:`启用`,children:(0,D.jsx)(u.Switch,{field:`enabled`})})]})},j?.role?.name||`new-role`)]})}export{k as default};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{At as r,Dt as i,F as a,H as o,L as s,M as c,W as l,i as u,lt as d,ot as f,st as p}from"./semi-Dpcldp_F.js";import{F as m,I as h,P as g,a as _,b as v,c as y,l as b,m as x,p as S,s as C,x as w,y as T}from"./index-Bsu8fBML.js";var E=e(t(),1),D=e(n(),1),{Text:O}=l;function k(){let e=g(),{hasPermission:t}=m(),n=t(`roles:write`),l=t(`roles:delete`),[k,A]=(0,E.useState)(``),[j,M]=(0,E.useState)(null),[N,P]=(0,E.useState)(!1),F=_(()=>h.get(`/roles`),[]),I=(Array.isArray(F.data?.roles)?F.data.roles:[]).filter(e=>{if(!k)return!0;let t=k.toLowerCase();return[e.name,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),L=async()=>{let e=await j.form.validate();P(!0);try{let t={name:e.name.trim(),description:e.description?.trim()||``,user_prompt:e.user_prompt||``,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean),enabled:e.enabled!==!1},n=j.role?.name;n&&n!==t.name?(await h.post(`/roles`,t),await h.del(`/roles/${encodeURIComponent(n)}`)):n?await h.put(`/roles/${encodeURIComponent(n)}`,t):await h.post(`/roles`,t),w(`角色已保存`),M(null),F.reload()}catch(e){v(e,`保存角色失败`)}finally{P(!1)}},R=e=>T({title:`删除角色「${e.name}」?`,content:`已绑定该角色的对话将失去对应提示词与工具配置。`,onOk:async()=>{await h.del(`/roles/${encodeURIComponent(e.name)}`),w(`已删除`),F.reload()}});return(0,D.jsxs)(`div`,{children:[(0,D.jsx)(S,{title:e(`roles.title`,null,`角色管理`),description:`角色定义对话的系统提示词、可用工具与绑定工作流。`,extra:(0,D.jsxs)(a,{children:[(0,D.jsx)(s,{icon:(0,D.jsx)(p,{}),onClick:()=>F.reload(),loading:F.loading,children:`刷新`}),n&&(0,D.jsx)(s,{theme:`solid`,type:`primary`,icon:(0,D.jsx)(d,{}),onClick:()=>M({role:null,form:{}}),children:`新建角色`})]})}),(0,D.jsxs)(x,{title:`角色(${I.length})`,children:[(0,D.jsx)(b,{error:F.error,onRetry:()=>F.reload()}),(0,D.jsx)(C,{columns:[{title:`角色`,dataIndex:`name`,render:(e,t)=>(0,D.jsxs)(a,{vertical:!0,spacing:0,align:`start`,children:[(0,D.jsxs)(a,{children:[(0,D.jsx)(O,{strong:!0,children:e}),t.enabled===!1&&(0,D.jsx)(c,{size:`small`,color:`grey`,children:`已停用`})]}),(0,D.jsx)(O,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:t.description||`—`})]})},{title:`工具`,dataIndex:`tools`,width:260,render:e=>Array.isArray(e)&&e.length?(0,D.jsxs)(a,{wrap:!0,spacing:4,children:[e.slice(0,4).map(e=>(0,D.jsx)(c,{size:`small`,children:e},e)),e.length>4&&(0,D.jsxs)(O,{type:`tertiary`,children:[`+`,e.length-4]})]}):(0,D.jsx)(O,{type:`tertiary`,children:`未绑定`})},{title:`工作流`,dataIndex:`workflow_id`,width:160,render:e=>e||`—`},{title:`操作`,width:150,render:(e,t)=>(0,D.jsxs)(a,{children:[n&&(0,D.jsx)(s,{size:`small`,theme:`borderless`,icon:(0,D.jsx)(i,{}),onClick:()=>M({role:t,form:{}}),children:`编辑`}),l&&(0,D.jsx)(s,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,D.jsx)(r,{}),onClick:()=>R(t)})]})}],dataSource:I,rowKey:`name`,loading:F.loading,pagination:{pageSize:20},toolbar:(0,D.jsx)(o,{prefix:(0,D.jsx)(f,{}),value:k,onChange:A,placeholder:`搜索角色名称`,style:{width:260}})})]}),(0,D.jsx)(y,{title:j?.role?`编辑角色`:`新建角色`,visible:!!j,onCancel:()=>M(null),onOk:L,confirmLoading:N,width:760,children:(0,D.jsxs)(u,{getFormApi:e=>M(t=>t&&{...t,form:e}),initValues:j?.role?{name:j.role.name,description:j.role.description,user_prompt:j.role.user_prompt,tools:Array.isArray(j.role.tools)?j.role.tools.join(`, `):``,enabled:j.role.enabled!==!1}:{enabled:!0},children:[(0,D.jsx)(u.Input,{field:`name`,label:`角色名称`,rules:[{required:!0,message:`请输入角色名称`}]}),(0,D.jsx)(u.Input,{field:`description`,label:`描述`}),(0,D.jsx)(u.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::toolName`}),(0,D.jsx)(u.TextArea,{field:`user_prompt`,label:`用户提示词(追加到用户消息前)`,autosize:{minRows:6,maxRows:18}}),(0,D.jsx)(u.Slot,{label:`启用`,children:(0,D.jsx)(u.Switch,{field:`enabled`})})]})},j?.role?.name||`new-role`)]})}export{k as default};
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,_ as n,t as r,y as i}from"./react-QV7DAAIx.js";import{A as a,F as o,H as s,I as c,L as l,M as u,O as d,Ot as f,Qt as p,W as m,Z as h,c as g,f as _,h as ee,m as v,ot as y,p as b,s as x,st as te,u as S,v as C,x as w,z as T}from"./semi-Dpcldp_F.js";import{A as E,D,E as O,F as k,I as A,L as j,M,N,P,R as F,S as I,T as L,_ as R,a as z,b as ne,d as B,j as re,l as V,m as H,n as ie,o as U,p as W,s as ae,u as G,x as oe,y as se}from"./index-C3OHVG4q.js";import{n as ce,r as le,t as K}from"./model-channel-mQ6lfvSO.js";var q=e(t(),1),J=class extends Error{constructor(e,t){super(t?`第 ${t} 行:${e}`:e),this.name=`YamlError`,this.line=t||0}},ue=/^(?:[-?:,\[\]{}#&*!|>'"%@`]|.*[:\s]$|.*\s#|.*[\n\r\t])/,de=/^(?:true|false|null|~|yes|no|on|off|[-+]?(?:\d+|\d*\.\d+)(?:[eE][-+]?\d+)?)$/i;function Y(e){let t=String(e);return!(t===``||de.test(t)||/^[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?$/.test(t)||ue.test(t)||/^(?:\s)|:(?:\s|$)|[\r\n\t]/.test(t)||/[,[\]{}]/.test(t)||/^[!&*|>@`]/.test(t))}function fe(e){return JSON.stringify(String(e))}function pe(e){let t=String(e);return Y(t)?t:fe(t)}function me(e){if(e==null)return`null`;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return Number.isFinite(e)?String(e):fe(String(e));let t=String(e);return Y(t)?t:fe(t)}function he(e){return e==null||[`string`,`number`,`boolean`].includes(typeof e)}function ge(e,t,n,r){let i=` `.repeat(n),a=pe(e);if(he(t))r.push(`${i}${a}: ${me(t)}`);else if(Array.isArray(t)){if(!t.length){r.push(`${i}${a}: []`);return}r.push(`${i}${a}:`),ye(t,n+2,r)}else Object.entries(t).length?(r.push(`${i}${a}:`),_e(t,n+2,r)):r.push(`${i}${a}: {}`)}function _e(e,t,n){for(let[r,i]of Object.entries(e))ge(r,i,t,n)}function ve(e,t,n){let r=` `.repeat(t);if(he(e)){n.push(`${r}- ${me(e)}`);return}if(Array.isArray(e)){if(!e.length){n.push(`${r}- []`);return}n.push(`${r}-`),ye(e,t+2,n);return}let i=Object.entries(e);if(!i.length){n.push(`${r}- {}`);return}let[a,o]=i[0],s=i.slice(1);he(o)?n.push(`${r}- ${pe(a)}: ${me(o)}`):(n.push(`${r}-`),ge(a,o,t+2,n));for(let[e,r]of s)ge(e,r,t+2,n)}function ye(e,t,n){for(let r of e)ve(r,t,n)}function be(e,{header:t}={}){let n=[];if(t){for(let e of String(t).replace(/\r\n?/g,`
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,_ as n,t as r,y as i}from"./react-QV7DAAIx.js";import{A as a,F as o,H as s,I as c,L as l,M as u,O as d,Ot as f,Qt as p,W as m,Z as h,c as g,f as _,h as ee,m as v,ot as y,p as b,s as x,st as te,u as S,v as C,x as w,z as T}from"./semi-Dpcldp_F.js";import{A as E,D,E as O,F as k,I as A,L as j,M,N,P,R as F,S as I,T as L,_ as R,a as z,b as ne,d as B,j as re,l as V,m as H,n as ie,o as U,p as W,s as ae,u as G,x as oe,y as se}from"./index-Bsu8fBML.js";import{n as ce,r as le,t as K}from"./model-channel-mQ6lfvSO.js";var q=e(t(),1),J=class extends Error{constructor(e,t){super(t?`第 ${t} 行:${e}`:e),this.name=`YamlError`,this.line=t||0}},ue=/^(?:[-?:,\[\]{}#&*!|>'"%@`]|.*[:\s]$|.*\s#|.*[\n\r\t])/,de=/^(?:true|false|null|~|yes|no|on|off|[-+]?(?:\d+|\d*\.\d+)(?:[eE][-+]?\d+)?)$/i;function Y(e){let t=String(e);return!(t===``||de.test(t)||/^[-+]?(?:\d+\.\d*|\.\d+|\d+)(?:[eE][-+]?\d+)?$/.test(t)||ue.test(t)||/^(?:\s)|:(?:\s|$)|[\r\n\t]/.test(t)||/[,[\]{}]/.test(t)||/^[!&*|>@`]/.test(t))}function fe(e){return JSON.stringify(String(e))}function pe(e){let t=String(e);return Y(t)?t:fe(t)}function me(e){if(e==null)return`null`;if(typeof e==`boolean`)return e?`true`:`false`;if(typeof e==`number`)return Number.isFinite(e)?String(e):fe(String(e));let t=String(e);return Y(t)?t:fe(t)}function he(e){return e==null||[`string`,`number`,`boolean`].includes(typeof e)}function ge(e,t,n,r){let i=` `.repeat(n),a=pe(e);if(he(t))r.push(`${i}${a}: ${me(t)}`);else if(Array.isArray(t)){if(!t.length){r.push(`${i}${a}: []`);return}r.push(`${i}${a}:`),ye(t,n+2,r)}else Object.entries(t).length?(r.push(`${i}${a}:`),_e(t,n+2,r)):r.push(`${i}${a}: {}`)}function _e(e,t,n){for(let[r,i]of Object.entries(e))ge(r,i,t,n)}function ve(e,t,n){let r=` `.repeat(t);if(he(e)){n.push(`${r}- ${me(e)}`);return}if(Array.isArray(e)){if(!e.length){n.push(`${r}- []`);return}n.push(`${r}-`),ye(e,t+2,n);return}let i=Object.entries(e);if(!i.length){n.push(`${r}- {}`);return}let[a,o]=i[0],s=i.slice(1);he(o)?n.push(`${r}- ${pe(a)}: ${me(o)}`):(n.push(`${r}-`),ge(a,o,t+2,n));for(let[e,r]of s)ge(e,r,t+2,n)}function ye(e,t,n){for(let r of e)ve(r,t,n)}function be(e,{header:t}={}){let n=[];if(t){for(let e of String(t).replace(/\r\n?/g,`
|
||||
`).split(`
|
||||
`))n.push(`# ${e}`.trimEnd());n.length&&n.push(``)}return he(e)?(n.push(me(e)),`${n.join(`
|
||||
`)}\n`):Array.isArray(e)?(e.length?ye(e,0,n):n.push(`[]`),`${n.join(`
|
||||
File diff suppressed because one or more lines are too long
|
|
@ -1 +1 @@
|
|||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{At as t,F as n,L as r,W as i,st as a}from"./semi-Dpcldp_F.js";import{D as o,F as s,I as c,O as l,P as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-C3OHVG4q.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=i;function S(){let e=u(),{hasPermission:i}=s(),y=i(`skills:delete`),S=f(()=>c.get(`/skills/stats`),[]),C=Array.isArray(S.data?.stats)?S.data.stats:[],w=Number(S.data?.total_calls||0),T=Number(S.data?.total_success||0),E=w>0?T/w:null,D=()=>v({title:`清空所有技能调用统计?`,content:`只影响统计计数,不删除技能文件。`,onOk:async()=>{await c.del(`/skills/stats`),_(`统计已清空`),S.reload()}}),O=e=>v({title:`清空「${e}」的统计?`,onOk:async()=>{await c.del(`/skills/${encodeURIComponent(e)}/stats`),_(`已清空`),S.reload()}});return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(h,{title:e(`skills.monitorTitle`,null,`技能状态`),description:S.data?.skills_dir?`技能目录:${S.data.skills_dir}`:`统计技能被调用的次数、成功率与最近使用时间。`,extra:(0,b.jsxs)(n,{children:[(0,b.jsx)(r,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(r,{type:`danger`,theme:`light`,onClick:D,children:`清空全部统计`})]})}),(0,b.jsx)(d,{columns:4,metrics:[{id:`skills`,label:`技能总数`,value:o(S.data?.total_skills||0),loading:S.loading},{id:`calls`,label:`调用总数`,value:o(w),loading:S.loading},{id:`success`,label:`成功次数`,value:o(T),loading:S.loading},{id:`rate`,label:`成功率`,value:E===null?`—`:l(E),tone:E!==null&&E<.8?`warning`:`success`,loading:S.loading}]}),(0,b.jsxs)(m,{title:`按技能统计`,children:[(0,b.jsx)(p,{error:S.error,onRetry:()=>S.reload()}),(0,b.jsx)(g,{columns:[{title:`技能`,dataIndex:`skill_name`,render:e=>(0,b.jsx)(x,{strong:!0,children:e})},{title:`调用次数`,dataIndex:`total_calls`,width:120,render:e=>o(e||0)},{title:`成功`,dataIndex:`success_calls`,width:100,render:e=>o(e||0)},{title:`失败`,dataIndex:`failed_calls`,width:100,render:e=>Number(e)>0?(0,b.jsx)(x,{type:`danger`,children:o(e)}):`0`},{title:`最后调用`,dataIndex:`last_call_time`,width:180,render:e=>e||`—`},{title:`操作`,width:110,render:(e,n)=>y&&Number(n.total_calls)>0?(0,b.jsx)(r,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(t,{}),onClick:()=>O(n.skill_name),children:`清空`}):null}],dataSource:C,rowKey:`skill_name`,loading:S.loading,pagination:{pageSize:20}})]})]})}export{S as default};
|
||||
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{At as t,F as n,L as r,W as i,st as a}from"./semi-Dpcldp_F.js";import{D as o,F as s,I as c,O as l,P as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-Bsu8fBML.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=i;function S(){let e=u(),{hasPermission:i}=s(),y=i(`skills:delete`),S=f(()=>c.get(`/skills/stats`),[]),C=Array.isArray(S.data?.stats)?S.data.stats:[],w=Number(S.data?.total_calls||0),T=Number(S.data?.total_success||0),E=w>0?T/w:null,D=()=>v({title:`清空所有技能调用统计?`,content:`只影响统计计数,不删除技能文件。`,onOk:async()=>{await c.del(`/skills/stats`),_(`统计已清空`),S.reload()}}),O=e=>v({title:`清空「${e}」的统计?`,onOk:async()=>{await c.del(`/skills/${encodeURIComponent(e)}/stats`),_(`已清空`),S.reload()}});return(0,b.jsxs)(`div`,{children:[(0,b.jsx)(h,{title:e(`skills.monitorTitle`,null,`技能状态`),description:S.data?.skills_dir?`技能目录:${S.data.skills_dir}`:`统计技能被调用的次数、成功率与最近使用时间。`,extra:(0,b.jsxs)(n,{children:[(0,b.jsx)(r,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(r,{type:`danger`,theme:`light`,onClick:D,children:`清空全部统计`})]})}),(0,b.jsx)(d,{columns:4,metrics:[{id:`skills`,label:`技能总数`,value:o(S.data?.total_skills||0),loading:S.loading},{id:`calls`,label:`调用总数`,value:o(w),loading:S.loading},{id:`success`,label:`成功次数`,value:o(T),loading:S.loading},{id:`rate`,label:`成功率`,value:E===null?`—`:l(E),tone:E!==null&&E<.8?`warning`:`success`,loading:S.loading}]}),(0,b.jsxs)(m,{title:`按技能统计`,children:[(0,b.jsx)(p,{error:S.error,onRetry:()=>S.reload()}),(0,b.jsx)(g,{columns:[{title:`技能`,dataIndex:`skill_name`,render:e=>(0,b.jsx)(x,{strong:!0,children:e})},{title:`调用次数`,dataIndex:`total_calls`,width:120,render:e=>o(e||0)},{title:`成功`,dataIndex:`success_calls`,width:100,render:e=>o(e||0)},{title:`失败`,dataIndex:`failed_calls`,width:100,render:e=>Number(e)>0?(0,b.jsx)(x,{type:`danger`,children:o(e)}):`0`},{title:`最后调用`,dataIndex:`last_call_time`,width:180,render:e=>e||`—`},{title:`操作`,width:110,render:(e,n)=>y&&Number(n.total_calls)>0?(0,b.jsx)(r,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(t,{}),onClick:()=>O(n.skill_name),children:`清空`}):null}],dataSource:C,rowKey:`skill_name`,loading:S.loading,pagination:{pageSize:20}})]})]})}export{S as default};
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -18,7 +18,7 @@
|
|||
} catch (error) { /* first paint fallback */ }
|
||||
})();
|
||||
</script>
|
||||
<script type="module" crossorigin src="/static/app/assets/index-C3OHVG4q.js"></script>
|
||||
<script type="module" crossorigin src="/static/app/assets/index-Bsu8fBML.js"></script>
|
||||
<link rel="modulepreload" crossorigin href="/static/app/assets/rolldown-runtime-WkwZ5CU-.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/app/assets/react-QV7DAAIx.js">
|
||||
<link rel="modulepreload" crossorigin href="/static/app/assets/semi-Dpcldp_F.js">
|
||||
|
|
|
|||
|
|
@ -1536,6 +1536,14 @@
|
|||
"overviewTitle": "نظرة عامة على الأصول",
|
||||
"libraryTitle": "مكتبة الأصول",
|
||||
"viewLibrary": "عرض مكتبة الأصول",
|
||||
"scopeLabel": "نطاق الأصول",
|
||||
"scopePlaceholder": "اختر مشروعًا أو اعرض جميع الأصول",
|
||||
"scopeAll": "جميع الأصول",
|
||||
"scopeUnassigned": "أصول غير مرتبطة بمشروع",
|
||||
"projectAssets": "أصول المشروع",
|
||||
"mixedProjectSelection": "لإجراء تعديلات جماعية، اختر أصول مشروع واحد أو الأصول غير المرتبطة بمشروع فقط.",
|
||||
"importProjectConflicts": "تم تخطي السجلات المكررة ذات الارتباط بمشروع مختلف ({{count}}).",
|
||||
"scopedDeleteConfirm": "هل تريد حذف الأصول المحددة ({{count}}) من «{{project}}» نهائيًا؟",
|
||||
"totalAssets": "إجمالي الأصول",
|
||||
"totalAssetsHint": "الأصول الخاضعة حاليًا للمراقبة المستمرة",
|
||||
"ipCount": "عناوين IP",
|
||||
|
|
|
|||
|
|
@ -1537,6 +1537,14 @@
|
|||
"overviewTitle": "Asset Overview",
|
||||
"libraryTitle": "Asset Library",
|
||||
"viewLibrary": "View asset library",
|
||||
"scopeLabel": "Asset scope",
|
||||
"scopePlaceholder": "Select a project or view all assets",
|
||||
"scopeAll": "All assets",
|
||||
"scopeUnassigned": "Unassigned assets",
|
||||
"projectAssets": "Project assets",
|
||||
"mixedProjectSelection": "Select assets from one project or only unassigned assets to make bulk changes.",
|
||||
"importProjectConflicts": "Skipped {{count}} duplicate records with a different project assignment.",
|
||||
"scopedDeleteConfirm": "Permanently delete {{count}} selected assets from “{{project}}”?",
|
||||
"totalAssets": "Total assets",
|
||||
"totalAssetsHint": "Assets currently under continuous monitoring",
|
||||
"ipCount": "IP addresses",
|
||||
|
|
|
|||
|
|
@ -1549,6 +1549,14 @@
|
|||
"overviewTitle": "Обзор активов",
|
||||
"libraryTitle": "Библиотека активов",
|
||||
"viewLibrary": "Открыть библиотеку активов",
|
||||
"scopeLabel": "Область просмотра",
|
||||
"scopePlaceholder": "Выберите проект или просмотрите все активы",
|
||||
"scopeAll": "Все активы",
|
||||
"scopeUnassigned": "Активы без проекта",
|
||||
"projectAssets": "Активы проекта",
|
||||
"mixedProjectSelection": "Для массового изменения выберите активы одного проекта или только активы без проекта.",
|
||||
"importProjectConflicts": "Пропущены дубликаты с другой привязкой к проекту ({{count}}).",
|
||||
"scopedDeleteConfirm": "Безвозвратно удалить выбранные активы ({{count}}) из «{{project}}»?",
|
||||
"totalAssets": "Всего активов",
|
||||
"totalAssetsHint": "Активы на постоянном мониторинге",
|
||||
"ipCount": "IP-адреса",
|
||||
|
|
|
|||
|
|
@ -1525,6 +1525,14 @@
|
|||
"overviewTitle": "资产概览",
|
||||
"libraryTitle": "资产库",
|
||||
"viewLibrary": "查看资产库",
|
||||
"scopeLabel": "资产范围",
|
||||
"scopePlaceholder": "选择项目或查看全部资产",
|
||||
"scopeAll": "全部资产",
|
||||
"scopeUnassigned": "未归属项目",
|
||||
"projectAssets": "项目资产",
|
||||
"mixedProjectSelection": "批量修改前,请将选择缩小到同一项目或仅选择未归属资产。",
|
||||
"importProjectConflicts": "已跳过 {{count}} 条归属不同的重复资产。",
|
||||
"scopedDeleteConfirm": "将永久删除「{{project}}」中的 {{count}} 个所选资产。",
|
||||
"totalAssets": "资产总数",
|
||||
"totalAssetsHint": "当前纳入持续监测的资产",
|
||||
"ipCount": "IP 数量",
|
||||
|
|
|
|||
Loading…
Reference in New Issue