perf(web,config): prevent cross-page HTTP stalls and honor 1M context default in probes

- Upgrade useResource and NotificationsBell with AbortController cancellation on unmount/reload and in-flight deduplication for silent polling, preventing abandoned requests from exhausting browser HTTP/1.1 connection slots
- Move external MCP tool lookups and markdown agent directory scans outside ConfigHandler.mu.RLock, bind request context, and support GET /api/config?include_tools=0 for chat model preferences and model settings
- Add immutable Cache-Control headers for content-hashed /static/app/assets/* and 1h caching for /static/i18n/*
- Add indexed created_at lower bound to NotificationHandler vulnerability summary query
- Pass effective configured/default 1M context_window in model probe requests, compute effective_max_total_tokens on fallback, display fallback window/source in ProbePanel, and suppress false context_window_unknown warnings when 1M default or manual window is active
- Rebuild web/static/app bundle and add Go + Playwright regression tests
This commit is contained in:
Sycun 2026-11-28 18:52:08 +08:00
parent 966836ef19
commit f4257cea3a
54 changed files with 423 additions and 200 deletions

View File

@ -1562,7 +1562,9 @@ func setupRoutes(
protected.GET("/openapi/spec", openAPIHandler.GetOpenAPISpec)
// 静态文件(前端为 React + Semi Design 单页应用,构建产物在 web/static/app)
router.Static("/static", "./web/static")
// 带内容哈希的 Vite 产物使用长期不可变缓存,减少跨境与高延迟链路重复下载。
staticGroup := router.Group("/static", staticCacheControlMiddleware())
staticGroup.Static("/", "./web/static")
// API 文档已并入单页应用路由(#/api-docs),保留旧地址跳转
router.GET("/api-docs", func(c *gin.Context) {

View File

@ -185,3 +185,20 @@ func (w *gzipResponseWriter) close() {
w.gz = nil
}
}
// staticCacheControlMiddleware 为带内容哈希的 Vite 前端构建产物设置长期不可变缓存,
// 对语言包设置适度缓存,对 index.html 等入口文件保持 no-cache。
func staticCacheControlMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
path := c.Request.URL.Path
switch {
case strings.HasPrefix(path, "/static/app/assets/"):
c.Header("Cache-Control", "public, max-age=31536000, immutable")
case strings.HasPrefix(path, "/static/i18n/"):
c.Header("Cache-Control", "public, max-age=3600")
case path == "/static/app/" || path == "/static/app/index.html":
c.Header("Cache-Control", "no-cache")
}
c.Next()
}
}

View File

@ -85,3 +85,29 @@ func TestGzipMiddlewareCompressesJSONAndSkipsSSE(t *testing.T) {
t.Fatalf("204 Content-Encoding = %q, want empty", got)
}
}
func TestStaticCacheControlMiddleware(t *testing.T) {
gin.SetMode(gin.TestMode)
r := gin.New()
g := r.Group("/static", staticCacheControlMiddleware())
g.GET("/*filepath", func(c *gin.Context) {
c.String(http.StatusOK, "ok")
})
cases := []struct {
path string
want string
}{
{"/static/app/assets/chat-abc123.js", "public, max-age=31536000, immutable"},
{"/static/i18n/zh-CN.json", "public, max-age=3600"},
{"/static/app/index.html", "no-cache"},
{"/static/logo.png", ""},
}
for _, tc := range cases {
w := httptest.NewRecorder()
r.ServeHTTP(w, httptest.NewRequest(http.MethodGet, tc.path, nil))
if got := w.Header().Get("Cache-Control"); got != tc.want {
t.Fatalf("%s Cache-Control = %q, want %q", tc.path, got, tc.want)
}
}
}

View File

@ -299,52 +299,45 @@ type ToolConfigInfo struct {
// GetConfig 获取当前配置
func (h *ConfigHandler) GetConfig(c *gin.Context) {
includeToolsStr := strings.ToLower(strings.TrimSpace(c.DefaultQuery("include_tools", "1")))
includeTools := includeToolsStr != "0" && includeToolsStr != "false" && includeToolsStr != "no"
h.mu.RLock()
defer h.mu.RUnlock()
// 获取工具列表(包含内部和外部工具)
// 首先从配置文件获取工具
configToolMap := make(map[string]bool)
tools := make([]ToolConfigInfo, 0, len(h.config.Security.Tools))
for _, tool := range h.config.Security.Tools {
configToolMap[tool.Name] = true
info := ToolConfigInfo{
Name: tool.Name,
Description: h.pickToolDescription(tool.ShortDescription, tool.Description),
Enabled: tool.Enabled,
IsExternal: false,
}
tools = append(tools, info)
}
// 从MCP服务器获取所有已注册的工具(包括直接注册的工具,如知识检索工具)
if h.mcpServer != nil {
mcpTools := h.mcpServer.GetAllTools()
for _, mcpTool := range mcpTools {
if configToolMap[mcpTool.Name] {
continue
}
description := h.pickToolDescription(mcpTool.ShortDescription, mcpTool.Description)
// 仅在读锁内快速拷贝内存配置快照,避免在持有锁期间执行外部 MCP 网络探测或扫盘。
var tools []ToolConfigInfo
var mcpServer *mcp.Server
var externalMCPMgr *mcp.ExternalMCPManager
pickDesc := h.pickToolDescription
if includeTools {
configToolMap := make(map[string]bool, len(h.config.Security.Tools))
tools = make([]ToolConfigInfo, 0, len(h.config.Security.Tools))
for _, tool := range h.config.Security.Tools {
configToolMap[tool.Name] = true
tools = append(tools, ToolConfigInfo{
Name: mcpTool.Name,
Description: description,
Enabled: true,
Name: tool.Name,
Description: pickDesc(tool.ShortDescription, tool.Description),
Enabled: tool.Enabled,
IsExternal: false,
})
}
}
// 获取外部MCP工具(走缓存,持锁期间通常不阻塞)
if h.externalMCPMgr != nil {
ctx := context.Background()
externalTools := h.getExternalMCPTools(ctx)
for _, toolInfo := range externalTools {
tools = append(tools, toolInfo)
mcpServer = h.mcpServer
externalMCPMgr = h.externalMCPMgr
if mcpServer != nil {
for _, mcpTool := range mcpServer.GetAllTools() {
if configToolMap[mcpTool.Name] {
continue
}
tools = append(tools, ToolConfigInfo{
Name: mcpTool.Name,
Description: pickDesc(mcpTool.ShortDescription, mcpTool.Description),
Enabled: true,
IsExternal: false,
})
}
}
}
subAgentCount := len(h.config.MultiAgent.SubAgents)
yamlSubAgents := append(h.config.MultiAgent.SubAgents[:0:0], h.config.MultiAgent.SubAgents...)
agentsDir := strings.TrimSpace(h.config.AgentsDir)
if agentsDir == "" {
agentsDir = "agents"
@ -352,9 +345,6 @@ func (h *ConfigHandler) GetConfig(c *gin.Context) {
if !filepath.IsAbs(agentsDir) {
agentsDir = filepath.Join(filepath.Dir(h.configPath), agentsDir)
}
if load, err := agents.LoadMarkdownAgentsDir(agentsDir); err == nil {
subAgentCount = len(agents.MergeYAMLAndMarkdown(h.config.MultiAgent.SubAgents, load.SubAgents))
}
effectiveRuntime := config.EffectiveRuntimeForChannel(h.config.MultiAgent.Runtime, h.config.OpenAI)
builtinAlwaysVisible := builtin.GetAllBuiltinTools()
if !effectiveRuntime.ToolSearchIncludeBuiltinsEffective() {
@ -364,7 +354,7 @@ func (h *ConfigHandler) GetConfig(c *gin.Context) {
Enabled: h.config.MultiAgent.Enabled,
RobotDefaultAgentMode: config.NormalizeRobotAgentMode(h.config.MultiAgent),
BatchUseMultiAgent: h.config.MultiAgent.BatchUseMultiAgent,
SubAgentCount: subAgentCount,
SubAgentCount: len(yamlSubAgents),
Orchestration: config.NormalizeMultiAgentOrchestration(h.config.MultiAgent.Orchestration),
PlanExecuteLoopMaxIterations: h.config.MultiAgent.PlanExecuteLoopMaxIterations,
ModelRetryMaxRetries: h.config.MultiAgent.Runtime.ModelRetryMaxRetries,
@ -401,7 +391,7 @@ func (h *ConfigHandler) GetConfig(c *gin.Context) {
}
}
response, err := maskedConfigResponse(GetConfigResponse{
respModel := GetConfigResponse{
Proxy: h.config.Proxy,
AgentRuntime: h.config.AgentRuntime,
AI: h.config.AI,
@ -422,7 +412,21 @@ func (h *ConfigHandler) GetConfig(c *gin.Context) {
ContextWindowDefaults: windowDefaults,
ImageInputDefaults: imageDefaults,
})
}
h.mu.RUnlock()
// 锁外执行外部 MCP 工具读取(绑定请求 Context,客户端切页断开立即中止)与子代理目录扫描。
if includeTools && externalMCPMgr != nil {
externalTools := h.getExternalMCPToolsWithManager(c.Request.Context(), externalMCPMgr, pickDesc)
if len(externalTools) > 0 {
respModel.Tools = append(respModel.Tools, externalTools...)
}
}
if load, err := agents.LoadMarkdownAgentsDir(agentsDir); err == nil {
respModel.MultiAgent.SubAgentCount = len(agents.MergeYAMLAndMarkdown(yamlSubAgents, load.SubAgents))
}
response, err := maskedConfigResponse(respModel)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "配置序列化失败"})
return
@ -1369,6 +1373,7 @@ type TestOpenAIRequest struct {
APIKey string `json:"api_key"`
Model string `json:"model"`
Headers map[string]string `json:"headers,omitempty"`
ContextWindow int `json:"context_window,omitempty"`
MaxTotalTokens int `json:"max_total_tokens,omitempty"`
MaxCompletionTokens int `json:"max_completion_tokens,omitempty"`
ContextProfile string `json:"context_profile,omitempty"`
@ -1392,6 +1397,10 @@ func probeModelContext(ctx context.Context, provider, baseURL, apiKey, model str
}
func addModelContextToResponse(resp gin.H, info modelmeta.ContextInfo, maxTotalTokens, maxCompletionTokens int, contextProfile string) {
addModelContextToResponseWithConfigured(resp, info, 0, maxTotalTokens, maxCompletionTokens, contextProfile)
}
func addModelContextToResponseWithConfigured(resp gin.H, info modelmeta.ContextInfo, configuredWindow, maxTotalTokens, maxCompletionTokens int, contextProfile string) {
if info.Backend != "" {
resp["context_backend"] = info.Backend
}
@ -1419,8 +1428,15 @@ func addModelContextToResponse(resp gin.H, info modelmeta.ContextInfo, maxTotalT
}
}
resp["context_profile"] = profile
isLocal := profile == "local" || profile == "local_auto"
effectiveWindow := info.ContextWindow
usedFallbackWindow := false
if effectiveWindow <= 0 && !info.RuntimeUnknown && !isLocal && configuredWindow > 0 {
effectiveWindow = configuredWindow
usedFallbackWindow = true
}
oa := config.OpenAIConfig{
ContextWindow: info.ContextWindow,
ContextWindow: effectiveWindow,
ContextProfile: profile,
MaxTotalTokens: maxTotalTokens,
MaxCompletionTokens: maxCompletionTokens,
@ -1428,11 +1444,17 @@ func addModelContextToResponse(resp gin.H, info modelmeta.ContextInfo, maxTotalT
if profile == "local_auto" && info.RuntimeUnknown {
oa.ContextWindow = 0
}
if info.ContextWindow > 0 || profile != "" {
if effectiveWindow > 0 || profile != "" {
resp["effective_max_total_tokens"] = oa.EffectiveMaxTotalTokens()
}
warnings := append([]string(nil), info.Warnings...)
if info.ContextWindow > 0 && maxTotalTokens > info.ContextWindow {
warnings := make([]string, 0, len(info.Warnings)+2)
for _, w := range info.Warnings {
if usedFallbackWindow && w == modelmeta.WarningContextUnknown {
continue
}
warnings = append(warnings, w)
}
if effectiveWindow > 0 && maxTotalTokens > effectiveWindow {
warnings = append(warnings, modelmeta.WarningBudgetExceedsWindow)
}
warnings = append(warnings, oa.ContextBudgetWarnings()...)
@ -1494,7 +1516,7 @@ func (h *ConfigHandler) DetectContext(c *gin.Context) {
}
info := probeModelContext(c.Request.Context(), req.Provider, baseURL, req.APIKey, req.Model, resolvedHeaders)
resp := gin.H{"success": true, "model": req.Model}
addModelContextToResponse(resp, info, req.MaxTotalTokens, req.MaxCompletionTokens, req.ContextProfile)
addModelContextToResponseWithConfigured(resp, info, req.ContextWindow, req.MaxTotalTokens, req.MaxCompletionTokens, req.ContextProfile)
c.JSON(http.StatusOK, resp)
}
@ -1545,7 +1567,7 @@ func (h *ConfigHandler) testOpenAI(c *gin.Context, req TestOpenAIRequest) {
// Identify local servers before the completion so the first connection
// test already uses the output-limit field supported by that backend.
metadata := gin.H{}
addModelContextToResponse(metadata, probeModelContext(c.Request.Context(), req.Provider, baseURL, req.APIKey, req.Model, resolvedHeaders), req.MaxTotalTokens, req.MaxCompletionTokens, req.ContextProfile)
addModelContextToResponseWithConfigured(metadata, probeModelContext(c.Request.Context(), req.Provider, baseURL, req.APIKey, req.Model, resolvedHeaders), req.ContextWindow, req.MaxTotalTokens, req.MaxCompletionTokens, req.ContextProfile)
detectedProfile, _ := metadata["context_profile"].(string)
maxTokensField := (config.OpenAIConfig{ContextProfile: detectedProfile}).OutputLimitField()
payload := map[string]interface{}{

View File

@ -222,3 +222,64 @@ func TestContextProbeDoesNotRedirectCredentials(t *testing.T) {
defer source.Close()
probeModelContext(context.Background(), "openai", source.URL+"/v1", "test-key", "test-model", map[string]string{"X-Gateway-Key": "test-gateway"})
}
func TestGetConfigIncludeToolsZeroSkipsToolAssembly(t *testing.T) {
cfg := &config.Config{
Security: config.SecurityConfig{
Tools: []config.ToolConfig{
{Name: "nmap", Description: "port scanner", Enabled: true},
{Name: "sqlmap", Description: "sqli scanner", Enabled: true},
},
},
AI: config.AIConfig{
DefaultChannel: "primary",
Channels: map[string]config.AIChannelConfig{
"primary": {BaseURL: "https://example.test/v1", Model: "gpt-test"},
},
},
}
h := &ConfigHandler{config: cfg, logger: zap.NewNop()}
router := gin.New()
router.GET("/config", h.GetConfig)
res := httptest.NewRecorder()
router.ServeHTTP(res, httptest.NewRequest(http.MethodGet, "/config?include_tools=0", nil))
if res.Code != http.StatusOK {
t.Fatalf("GET /config?include_tools=0: %d %s", res.Code, res.Body.String())
}
var result GetConfigResponse
if err := json.Unmarshal(res.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
if len(result.Tools) != 0 {
t.Fatalf("expected 0 tools when include_tools=0, got %d", len(result.Tools))
}
if result.AI.DefaultChannel != "primary" {
t.Fatalf("default channel = %q, want primary", result.AI.DefaultChannel)
}
}
func TestAddModelContextToResponseWithConfiguredWindowSuppressesUnknownWarning(t *testing.T) {
t.Parallel()
resp := gin.H{}
addModelContextToResponseWithConfigured(
resp,
modelmeta.ContextInfo{
Backend: modelmeta.BackendOpenAICompatible,
Warnings: []string{modelmeta.WarningContextUnknown},
},
1048576,
0,
0,
"",
)
if _, hasWindow := resp["context_window"]; hasWindow {
t.Fatalf("fallback configured window should not masquerade as upstream detected context_window: %#v", resp)
}
if got := resp["effective_max_total_tokens"]; got != config.DefaultMaxTotalTokens {
t.Fatalf("effective_max_total_tokens = %#v, want %d", got, config.DefaultMaxTotalTokens)
}
if warnings, ok := resp["context_warnings"].([]string); ok && containsWarning(warnings, modelmeta.WarningContextUnknown) {
t.Fatalf("context_window_unknown should be suppressed when configured/default 1M window is active: %#v", warnings)
}
}

View File

@ -257,6 +257,11 @@ func (h *NotificationHandler) loadPendingHITLItems(limit int, english bool, acce
func (h *NotificationHandler) loadVulnerabilityItems(sinceMs int64, limit int, english bool, access database.RBACListAccess) ([]NotificationSummaryItem, map[string]int, error) {
sinceSec := normalizedSinceSec(sinceMs)
// 先用保守的 48h 字典序下界命中 idx_vulnerabilities_created_at 索引,再由 strftime 做跨时区精确过滤。
createdAtLowerBound := ""
if sinceSec > 48*3600 {
createdAtLowerBound = time.Unix(sinceSec-48*3600, 0).UTC().Format("2006-01-02")
}
query := `
SELECT
id,
@ -268,6 +273,10 @@ func (h *NotificationHandler) loadVulnerabilityItems(sinceMs int64, limit int, e
WHERE CAST(strftime('%s', created_at) AS INTEGER) > ?
`
args := []interface{}{sinceSec}
if createdAtLowerBound != "" {
query += ` AND created_at >= ?`
args = append(args, createdAtLowerBound)
}
query, args = appendVulnerabilityNotificationAccessSQL(query, args, access)
query += `
ORDER BY created_at DESC

View File

@ -1,4 +1,4 @@
/** 通用异步数据装载:统一 loading / error / reload 语义。 */
/** 通用异步数据装载:统一 loading / error / reload 语义,支持卸载自动取消与静默轮询防重入。 */
import { useCallback, useEffect, useRef, useState } from 'react';
export function useResource(loader, deps = [], { initial = null, skip = false } = {}) {
@ -6,28 +6,54 @@ export function useResource(loader, deps = [], { initial = null, skip = false }
const [loading, setLoading] = useState(!skip);
const [error, setError] = useState(null);
const seq = useRef(0);
const abortRef = useRef(null);
const inFlightRef = useRef(false);
const reload = useCallback(async (options = {}) => {
if (skip) return null;
// 静默轮询若上一次请求仍在途中则跳过,避免高延迟链路下堆叠请求占满 HTTP/1.1 连接槽。
if (options.silent && !options.force && inFlightRef.current) return null;
abortRef.current?.abort();
const controller = new AbortController();
abortRef.current = controller;
inFlightRef.current = true;
const current = ++seq.current;
if (!options.silent) setLoading(true);
setError(null);
try {
const result = await loader();
if (current === seq.current) setData(result);
const result = await loader({ signal: controller.signal });
if (!controller.signal.aborted && current === seq.current) setData(result);
return result;
} catch (err) {
if (controller.signal.aborted) return null;
if (current === seq.current) setError(err);
return null;
} finally {
if (current === seq.current) setLoading(false);
if (abortRef.current === controller) {
abortRef.current = null;
inFlightRef.current = false;
}
if (!controller.signal.aborted && current === seq.current) setLoading(false);
}
}, deps); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (skip) { setLoading(false); return; }
if (skip) {
abortRef.current?.abort();
abortRef.current = null;
inFlightRef.current = false;
setLoading(false);
return undefined;
}
reload();
return () => { seq.current += 1; };
return () => {
seq.current += 1;
abortRef.current?.abort();
abortRef.current = null;
inFlightRef.current = false;
};
}, [reload, skip]);
return { data, setData, loading, error, reload };

View File

@ -1,4 +1,4 @@
import { useEffect, useId, useMemo, useState } from 'react';
import { useEffect, useId, useMemo, useRef, useState } from 'react';
import { Outlet, useLocation, useNavigate } from 'react-router-dom';
import {
Avatar, Badge, Breadcrumb, Button, Dropdown, Form, Nav, Popover, SideSheet, Space, Typography
@ -101,20 +101,44 @@ function NotificationsBell({ navigate }) {
const [pending, setPending] = useState(0);
const [visible, setVisible] = useState(false);
const [marking, setMarking] = useState(false);
const loadAbortRef = useRef(null);
const loadInFlightRef = useRef(false);
const load = async () => {
const load = async ({ force = false } = {}) => {
if (!force && loadInFlightRef.current) return;
loadAbortRef.current?.abort();
const controller = new AbortController();
loadAbortRef.current = controller;
loadInFlightRef.current = true;
try {
const summary = await api.get('/notifications/summary', { limit: 80, lang: document.documentElement.lang || 'zh-CN' });
const summary = await api.get(
'/notifications/summary',
{ limit: 80, lang: document.documentElement.lang || 'zh-CN' },
{ signal: controller.signal }
);
if (controller.signal.aborted) return;
const list = Array.isArray(summary?.items) ? summary.items : [];
setItems(list);
setPending(summary?.unreadCount ?? list.filter(item => !item.read).length);
} catch (error) {
/* 通知属于辅助信息,失败不打扰 */
} finally {
if (loadAbortRef.current === controller) {
loadAbortRef.current = null;
loadInFlightRef.current = false;
}
}
};
useEffect(() => { load(); }, []);
useInterval(load, 60000);
useEffect(() => {
load({ force: true });
return () => {
loadAbortRef.current?.abort();
loadAbortRef.current = null;
loadInFlightRef.current = false;
};
}, []);
useInterval(() => load(), 60000);
const markSeen = async () => {
const ids = items.filter(item => !item.read).map(item => item.id).filter(Boolean);
@ -122,7 +146,7 @@ function NotificationsBell({ navigate }) {
setMarking(true);
try {
await api.post('/notifications/read', { eventIds: ids });
await load();
await load({ force: true });
} catch (error) {
toastError(error);
} finally {

View File

@ -116,8 +116,8 @@ export default function Page() {
const detailInFlightRef = useRef({ id: '', active: false });
const hitlSeq = useRef(0);
const planSeq = useRef(0);
const activeTask = useResource(async () => {
const payload = await api.get('/agent-loop/tasks');
const activeTask = useResource(async ({ signal } = {}) => {
const payload = await api.get('/agent-loop/tasks', null, { signal });
return { id: conversationId, running: Array.isArray(payload?.tasks) && payload.tasks.some(task => task.conversationId === conversationId) };
}, [conversationId, canReadTasks], { skip: !conversationId || !canReadTasks });
const backgroundRunning = canReadTasks && activeTask.data?.id === conversationId && activeTask.data.running;
@ -125,14 +125,14 @@ export default function Page() {
const lastActive = useRef(null);
const conversations = useResource(
async () => ({
async ({ signal } = {}) => ({
...(await api.get('/conversations', {
limit: PAGE_SIZE,
offset: (page - 1) * PAGE_SIZE,
search: debouncedSearch || undefined,
project_id: projectGroup,
group_by_project: 1
})),
}, { signal })),
projectGroup, page, search: debouncedSearch
}),
[page, debouncedSearch, projectGroup]
@ -141,8 +141,8 @@ export default function Page() {
const reloadConversations = useRef(conversations.reload);
useEffect(() => { reloadConversations.current = conversations.reload; }, [conversations.reload]);
const projectsResource = useResource(() => api.get('/projects', { limit: 200 }), []);
const rolesResource = useResource(() => api.get('/roles'), [canReadRoles], { skip: !canReadRoles });
const projectsResource = useResource(({ signal } = {}) => api.get('/projects', { limit: 200 }, { signal }), []);
const rolesResource = useResource(({ signal } = {}) => api.get('/roles', null, { signal }), [canReadRoles], { skip: !canReadRoles });
const projects = useMemo(() => (
Array.isArray(projectsResource.data?.projects) ? projectsResource.data.projects : []
), [projectsResource.data]);

View File

@ -30,7 +30,7 @@ export function useModelPreferences(canReadConfig) {
const [storedChannel, setChannel] = useChatPreference('cyberstrike-chat-ai-channel', '');
const [storedMode, setMode] = useChatPreference('cyberstrike-chat-reasoning-mode', 'default');
const [storedEffort, setEffort] = useChatPreference('cyberstrike-chat-reasoning-effort', '');
const config = useResource(async () => (await api.get('/config'))?.ai, [canReadConfig], { skip: !canReadConfig });
const config = useResource(async ({ signal } = {}) => (await api.get('/config', { include_tools: 0 }, { signal }))?.ai, [canReadConfig], { skip: !canReadConfig });
const channels = Object.entries(config.data?.channels || {}).sort(([a], [b]) => a.localeCompare(b));
const normalizedChannel = storedChannel.trim().toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
const channel = channels.find(([id]) => id === storedChannel)?.[0]

View File

@ -55,7 +55,7 @@ export default function BasicSection() {
const { hasPermission } = useAuth();
const canRead = hasPermission('config:read');
const canWrite = hasPermission('config:write');
const loader = useCallback(() => api.get('/config'), []);
const loader = useCallback(({ signal } = {}) => api.get('/config', null, { signal }), []);
const config = useResource(loader, [canRead], { skip: !canRead });
const [text, setText] = useState('');

View File

@ -13,7 +13,7 @@ export default function ModelsSection() {
const t = useT();
const { hasPermission } = useAuth();
const canRead = hasPermission('config:read');
const loader = useCallback(() => api.get('/config'), []);
const loader = useCallback(({ signal } = {}) => api.get('/config', { include_tools: 0 }, { signal }), []);
const config = useResource(loader, [canRead], { skip: !canRead });
if (!canRead) {

View File

@ -93,10 +93,13 @@ function summarizeTest(t, payload) {
];
}
function summarizeContext(t, payload, fallbackWindow) {
function summarizeContext(t, payload, fallbackWindow, fallbackSource) {
const source = payload.context_source;
const sourceKey = source?.replace(/^omlx_models_(?=max_model_len|context_length|max_context_length|context_window)/, 'openai_models_');
const backend = payload.context_backend;
const fallbackLabel = fallbackSource === 'configured'
? t('settingsProbe.windowConfigured', null, '手动配置')
: t('settingsProbe.windowDefault', null, '默认值');
return [
...summarizeTest(t, payload),
{ label: t('settingsProbe.window', null, '上下文窗口'), value: payload.context_window || fallbackWindow || '—' },
@ -108,14 +111,14 @@ function summarizeContext(t, payload, fallbackWindow) {
},
{
label: t('settingsProbe.source', null, '窗口信息来源'),
value: fallbackWindow ? t('settingsProbe.windowDefault', null, '默认值') : (source ? t('settingsProbe.sources.' + sourceKey, null, source) : '—')
value: fallbackWindow ? fallbackLabel : (source ? t('settingsProbe.sources.' + sourceKey, null, source) : '—')
},
{ label: t('settingsProbe.profile', null, '上下文配置'), value: profileLabel(t, payload.context_profile) },
{ label: t('settingsProbe.effectiveBudget', null, '实际可用上下文令牌数'), value: payload.effective_max_total_tokens ?? '—' }
];
}
function ProbeOutput({ state, defaultWindow, model, onModelChange, disabled }) {
function ProbeOutput({ state, defaultWindow, defaultWindowSource, model, onModelChange, disabled }) {
const t = useT();
const pickerLabelId = useId();
const { key, payload, error } = state;
@ -182,7 +185,7 @@ function ProbeOutput({ state, defaultWindow, model, onModelChange, disabled }) {
.filter(code => !fallbackWindow || code !== 'context_window_unknown');
return (
<div className="settings-probe-result">
<KeyValueList columns={3} items={summarizeContext(t, payload, fallbackWindow)} />
<KeyValueList columns={3} items={summarizeContext(t, payload, fallbackWindow, defaultWindowSource)} />
{warnings.length > 0 && (
<Banner
type="warning"
@ -230,8 +233,14 @@ export default function ProbePanel({ config, canWrite, reloadConfig }) {
const defaultWindow = sameModelEndpoint && form.context_profile === baseline.context_profile
? config.context_window_defaults?.[legacy ? '' : channelId]
: listedModel?.context_window;
const isLocalProfile = ['local', 'local_auto'].includes(String(form.context_profile || '').trim().toLowerCase());
const needsDefaultWindow = Boolean(form.model.trim()) && !form.context_window;
const useDefaultWindow = needsDefaultWindow && !Object.hasOwn(draft, 'context_window');
const explicitWindow = numberValue(form.context_window);
const probeFallbackWindow = explicitWindow > 0
? explicitWindow
: (useDefaultWindow ? (isLocalProfile ? (defaultWindow || 0) : (defaultWindow || DEFAULT_FORM_CONTEXT_WINDOW)) : 0);
const probeFallbackSource = explicitWindow > 0 ? 'configured' : (probeFallbackWindow > 0 ? 'default' : '');
const matchesServerDefault = defaultWindow === DEFAULT_FORM_CONTEXT_WINDOW;
const dirty = Object.keys(draft).length > 0;
const [busy, setBusy] = useState('');
@ -381,6 +390,7 @@ export default function ProbePanel({ config, canWrite, reloadConfig }) {
api_key: form.api_key,
model: form.model,
headers: form.headers,
context_window: probeFallbackWindow || undefined,
max_total_tokens: numberValue(form.max_total_tokens),
max_completion_tokens: numberValue(form.max_completion_tokens),
context_profile: form.context_profile
@ -676,7 +686,8 @@ export default function ProbePanel({ config, canWrite, reloadConfig }) {
</Space>
<ProbeOutput
state={state}
defaultWindow={useDefaultWindow ? defaultWindow : 0}
defaultWindow={probeFallbackWindow}
defaultWindowSource={probeFallbackSource}
model={form.model}
onModelChange={value => update('model', value)}
disabled={locked}

View File

@ -252,6 +252,31 @@ test.describe('model channel editing', () => {
expect(mockApi.calls('PUT', '/api/config')).toHaveLength(2);
expect(mockApi.calls('POST', '/api/config/apply')).toHaveLength(2);
});
test('generic OpenAI-compatible channel uses 1M default context window during probe without false unknown warning', async ({ page, mockApi }) => {
const config = modelConfig();
mockApi.respond('GET', '/api/config', () => ({ json: config }));
mockApi.respond('POST', '/api/config/test-openai', ({ body }) => ({
json: {
success: true,
model: body.model,
context_backend: 'openai_compatible',
effective_max_total_tokens: body.context_window ? 120000 : undefined,
context_warnings: ['context_window_unknown']
}
}));
await page.goto('/static/app/#/settings?section=models');
const panel = (await ready(page)).locator('.settings-channel-panel');
await expect(panel.getByLabel('模型上下文窗口(Token)', { exact: true })).toHaveValue('1048576');
await panel.getByRole('button', { name: '测试连接', exact: true }).click();
expect(mockApi.calls('POST', '/api/config/test-openai')[0].body.context_window).toBe(1048576);
await expect(panel.getByRole('cell', { name: /上下文窗口.*1048576/ })).toBeVisible();
await expect(panel.getByRole('cell', { name: /窗口信息来源.*默认值/ })).toBeVisible();
await expect(panel.getByRole('cell', { name: /实际可用上下文令牌数.*120000/ })).toBeVisible();
await expect(panel.getByText('未检测到上下文窗口,请手动填写', { exact: true })).toHaveCount(0);
});
});
test('model configuration remains readable with view permission', async ({ page, mockApi }) => {

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{F as r,H as i,L as a,M as o,Ot as s,W as c,i as l,jt as u,lt as d,ot as f,st as p}from"./semi-CHxO7u8f.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-L6htuljo.js";var k=e(t(),1),A=e(n(),1),{Text:j}=c;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),c=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)(r,{children:[(0,A.jsx)(a,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(a,{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)(r,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(r,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(o,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(o,{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)(r,{children:[(0,A.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(s,{}),onClick:()=>L({record:t,form:{}})}),c&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(u,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(i,{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)(l,{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)(l.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(l.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(l.Input,{field:`description`,label:`描述`}),(0,A.jsx)(l.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(l.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(l.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{F as r,H as i,L as a,M as o,Ot as s,W as c,i as l,jt as u,lt as d,ot as f,st as p}from"./semi-CHxO7u8f.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-CdhqZYMl.js";var k=e(t(),1),A=e(n(),1),{Text:j}=c;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),c=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)(r,{children:[(0,A.jsx)(a,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(a,{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)(r,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(r,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(o,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(o,{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)(r,{children:[(0,A.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(s,{}),onClick:()=>L({record:t,form:{}})}),c&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(u,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(i,{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)(l,{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)(l.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(l.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(l.Input,{field:`description`,label:`描述`}),(0,A.jsx)(l.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(l.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(l.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};

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r}from"./semi-CHxO7u8f.js";import{E as i,P as a,k as o}from"./index-L6htuljo.js";import"./c2-shared-sB4ii0L_.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-CHxO7u8f.js";import{E as i,P as a,k as o}from"./index-CdhqZYMl.js";import"./c2-shared-q-J1Hn-o.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};

View File

@ -1 +1 @@
import{I as e,L as t}from"./index-L6htuljo.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-CdhqZYMl.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

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{S as t,t as n}from"./react-QV7DAAIx.js";import{F as r,H as i,L as a,M as o,W as s,jt as c,ot as l,st as u}from"./semi-CHxO7u8f.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-L6htuljo.js";var T=e(t(),1),E=e(n(),1),{Text:D}=s;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[s,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:s||void 0,limit:k}),[s,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)(a,{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)(o,{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)(r,{children:[(0,E.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(c,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(r,{children:[(0,E.jsx)(i,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:s,onChange:O,style:{width:260}}),(0,E.jsx)(i,{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{F as r,H as i,L as a,M as o,W as s,jt as c,ot as l,st as u}from"./semi-CHxO7u8f.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-CdhqZYMl.js";var T=e(t(),1),E=e(n(),1),{Text:D}=s;function O(){let e=m(),{hasPermission:t}=f(),n=t(`knowledge:delete`),[s,O]=(0,T.useState)(``),[k,A]=(0,T.useState)(50),[j,M]=(0,T.useState)(null),N=h(()=>p.get(`/knowledge/retrieval-logs`,{conversationId:s||void 0,limit:k}),[s,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)(a,{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)(o,{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)(r,{children:[(0,E.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>M(t),children:`详情`}),n&&(0,E.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,E.jsx)(c,{}),onClick:()=>F(t)})]})}],dataSource:P,rowKey:`id`,loading:N.loading,pagination:!1,toolbar:(0,E.jsxs)(r,{children:[(0,E.jsx)(i,{prefix:(0,E.jsx)(l,{}),placeholder:`按会话 ID 过滤`,value:s,onChange:O,style:{width:260}}),(0,E.jsx)(i,{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};

View File

@ -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-CHxO7u8f.js";import{I as a,P as o,c as s,l as c,x as l}from"./index-L6htuljo.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-CHxO7u8f.js";import{I as a,P as o,c as s,l as c,x as l}from"./index-CdhqZYMl.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

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r,jt as i,st as a}from"./semi-CHxO7u8f.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-L6htuljo.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=r;function S(){let e=u(),{hasPermission:r}=s(),y=r(`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)(t,{children:[(0,b.jsx)(n,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(n,{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,t)=>y&&Number(t.total_calls)>0?(0,b.jsx)(n,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(i,{}),onClick:()=>O(t.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{F as t,L as n,W as r,jt as i,st as a}from"./semi-CHxO7u8f.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-CdhqZYMl.js";import{t as y}from"./react-QV7DAAIx.js";var b=e(y(),1),{Text:x}=r;function S(){let e=u(),{hasPermission:r}=s(),y=r(`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)(t,{children:[(0,b.jsx)(n,{icon:(0,b.jsx)(a,{}),onClick:()=>S.reload(),loading:S.loading,children:`刷新`}),y&&(0,b.jsx)(n,{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,t)=>y&&Number(t.total_calls)>0?(0,b.jsx)(n,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,b.jsx)(i,{}),onClick:()=>O(t.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

View File

@ -18,7 +18,7 @@
} catch (error) { /* first paint fallback */ }
})();
</script>
<script type="module" crossorigin src="/static/app/assets/index-L6htuljo.js"></script>
<script type="module" crossorigin src="/static/app/assets/index-CdhqZYMl.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-CHxO7u8f.js">