feat(settings,chat): add GUI controls and entry points for vision model and knowledge base

This commit is contained in:
Sycun 2026-11-28 19:52:38 +08:00
parent 524ee29a84
commit 1c5c04362b
62 changed files with 2132 additions and 118 deletions

View File

@ -1208,6 +1208,7 @@ func setupRoutes(
protected.POST("/config/test-typesafe", configHandler.TestTypeSafe)
protected.POST("/config/test-audit-model", configHandler.TestAuditModel)
protected.POST("/config/test-vision", configHandler.TestVision)
protected.POST("/config/test-embedding", configHandler.TestEmbedding)
protected.POST("/config/list-models", configHandler.ListModels)
// 系统更新(保持本安装自身源码最新:查看、检查、应用、进度、回滚、接入、更新源)

View File

@ -963,6 +963,10 @@ func (h *ConfigHandler) UpdateConfig(c *gin.Context) {
}
if req.Vision != nil {
if req.Vision.Enabled && strings.TrimSpace(req.Vision.Model) == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "启用视觉分析时请填写视觉模型名称"})
return
}
h.config.Vision = *req.Vision
h.logger.Info("更新 Vision 配置",
zap.Bool("enabled", h.config.Vision.Enabled),
@ -1919,6 +1923,71 @@ func (h *ConfigHandler) TestVision(c *gin.Context) {
})
}
// TestEmbeddingRequest 测试知识库嵌入模型连接;embedding.api_key/base_url 留空时可传 openai 段作回退。
type TestEmbeddingRequest struct {
ChannelID string `json:"channel_id,omitempty"`
Embedding config.EmbeddingConfig `json:"embedding"`
OpenAI config.OpenAIConfig `json:"openai,omitempty"`
}
// TestEmbedding 测试知识库 Embedding 模型 API 连接。
func (h *ConfigHandler) TestEmbedding(c *gin.Context) {
var req TestEmbeddingRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "无效的请求参数: " + err.Error()})
return
}
mainKey, mainErr := h.resolveProbeSecret(req.OpenAI.APIKey, req.ChannelID, req.OpenAI.BaseURL, "openai")
if mainErr != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": mainErr.Error()})
return
}
req.OpenAI.APIKey = mainKey
embedKey, embedErr := h.resolveProbeSecret(req.Embedding.APIKey, "", req.Embedding.BaseURL, "knowledgeEmbedding")
if embedErr != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": embedErr.Error()})
return
}
req.Embedding.APIKey = embedKey
effectiveKey := strings.TrimSpace(req.Embedding.APIKey)
if effectiveKey == "" {
effectiveKey = strings.TrimSpace(req.OpenAI.APIKey)
}
if effectiveKey == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "API Key 不能为空(可填写嵌入模型 API Key 或复用默认通道)"})
return
}
if strings.TrimSpace(req.Embedding.Model) == "" {
c.JSON(http.StatusBadRequest, gin.H{"error": "嵌入模型名称不能为空"})
return
}
ctx, cancel := context.WithTimeout(c.Request.Context(), 30*time.Second)
defer cancel()
start := time.Now()
modelName, dims, err := knowledge.ProbeEmbedding(ctx, &config.KnowledgeConfig{
Embedding: req.Embedding,
}, &req.OpenAI, h.logger)
latency := time.Since(start)
if err != nil {
c.JSON(http.StatusOK, gin.H{
"success": false,
"error": "连接失败: " + err.Error(),
})
return
}
c.JSON(http.StatusOK, gin.H{
"success": true,
"model": modelName,
"dimensions": dims,
"latency_ms": latency.Milliseconds(),
})
}
// ApplyConfig 应用配置(重新加载并重启相关服务)
func (h *ConfigHandler) ApplyConfig(c *gin.Context) {
// 先检查是否需要动态初始化知识库(在锁外执行,避免阻塞其他请求)
@ -2379,38 +2448,40 @@ func updateVisionConfig(doc *yaml.Node, cfg config.VisionConfig) {
root := doc.Content[0]
visionNode := ensureMap(root, "vision")
setBoolInMap(visionNode, "enabled", cfg.Enabled)
if strings.TrimSpace(cfg.APIKey) != "" {
setStringInMap(visionNode, "api_key", cfg.APIKey)
} else {
setStringInMap(visionNode, "api_key", "")
}
if strings.TrimSpace(cfg.BaseURL) != "" {
setStringInMap(visionNode, "base_url", cfg.BaseURL)
} else {
setStringInMap(visionNode, "base_url", "")
}
setStringInMap(visionNode, "model", cfg.Model)
if strings.TrimSpace(cfg.Provider) != "" {
setStringInMap(visionNode, "provider", cfg.Provider)
}
setStringInMap(visionNode, "api_key", strings.TrimSpace(cfg.APIKey))
setStringInMap(visionNode, "base_url", strings.TrimSpace(cfg.BaseURL))
setStringInMap(visionNode, "model", strings.TrimSpace(cfg.Model))
setStringInMap(visionNode, "provider", strings.TrimSpace(cfg.Provider))
if cfg.TimeoutSeconds > 0 {
setIntInMap(visionNode, "timeout_seconds", cfg.TimeoutSeconds)
} else {
removeKeyFromMap(visionNode, "timeout_seconds")
}
if cfg.MaxImageBytes > 0 {
setIntInMap(visionNode, "max_image_bytes", int(cfg.MaxImageBytes))
} else {
removeKeyFromMap(visionNode, "max_image_bytes")
}
if cfg.MaxDimension > 0 {
setIntInMap(visionNode, "max_dimension", cfg.MaxDimension)
} else {
removeKeyFromMap(visionNode, "max_dimension")
}
if cfg.JPEGQuality > 0 {
setIntInMap(visionNode, "jpeg_quality", cfg.JPEGQuality)
} else {
removeKeyFromMap(visionNode, "jpeg_quality")
}
if cfg.MaxPayloadBytes > 0 {
setIntInMap(visionNode, "max_payload_bytes", int(cfg.MaxPayloadBytes))
} else {
removeKeyFromMap(visionNode, "max_payload_bytes")
}
setIntInMap(visionNode, "skip_preprocess_below_bytes", int(cfg.SkipPreprocessBelowBytes))
if strings.TrimSpace(cfg.Detail) != "" {
setStringInMap(visionNode, "detail", cfg.Detail)
setStringInMap(visionNode, "detail", strings.TrimSpace(cfg.Detail))
} else {
removeKeyFromMap(visionNode, "detail")
}
}
@ -2564,14 +2635,10 @@ func updateKnowledgeConfig(doc *yaml.Node, cfg config.KnowledgeConfig) {
// 更新嵌入配置
embeddingNode := ensureMap(knowledgeNode, "embedding")
setStringInMap(embeddingNode, "provider", cfg.Embedding.Provider)
setStringInMap(embeddingNode, "model", cfg.Embedding.Model)
if cfg.Embedding.BaseURL != "" {
setStringInMap(embeddingNode, "base_url", cfg.Embedding.BaseURL)
}
if cfg.Embedding.APIKey != "" {
setStringInMap(embeddingNode, "api_key", cfg.Embedding.APIKey)
}
setStringInMap(embeddingNode, "provider", strings.TrimSpace(cfg.Embedding.Provider))
setStringInMap(embeddingNode, "model", strings.TrimSpace(cfg.Embedding.Model))
setStringInMap(embeddingNode, "base_url", strings.TrimSpace(cfg.Embedding.BaseURL))
setStringInMap(embeddingNode, "api_key", strings.TrimSpace(cfg.Embedding.APIKey))
// 更新检索配置
retrievalNode := ensureMap(knowledgeNode, "retrieval")

View File

@ -0,0 +1,142 @@
package handler
import (
"encoding/json"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"cyberstrike-ai/internal/config"
"github.com/gin-gonic/gin"
"go.uber.org/zap"
)
func TestTestEmbeddingAndClearingSavedKnowledgeOverrides(t *testing.T) {
gin.SetMode(gin.TestMode)
var seenAuth string
embedServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/v1/embeddings" {
http.NotFound(w, r)
return
}
seenAuth = r.Header.Get("Authorization")
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[{"index":0,"embedding":[0.1,0.2,0.3,0.4]}]}`))
}))
defer embedServer.Close()
dir := t.TempDir()
cfgPath := filepath.Join(dir, "config.yaml")
initialYAML := strings.Join([]string{
"openai:",
" provider: openai_compatible",
" base_url: " + embedServer.URL + "/v1",
" api_key: sk-main-channel",
" model: demo-chat",
"vision:",
" enabled: true",
" provider: claude",
" model: qwen-vl-max",
" timeout_seconds: 90",
"knowledge:",
" enabled: false",
" base_path: knowledge_base",
" embedding:",
" provider: openai",
" model: text-embedding-v4",
" base_url: https://stale.example.test/v1",
" api_key: sk-stale",
"",
}, "\n")
if err := os.WriteFile(cfgPath, []byte(initialYAML), 0o600); err != nil {
t.Fatalf("write config.yaml: %v", err)
}
cfg := &config.Config{
OpenAI: config.OpenAIConfig{
Provider: "openai_compatible",
BaseURL: embedServer.URL + "/v1",
APIKey: "sk-main-channel",
Model: "demo-chat",
},
Vision: config.VisionConfig{
Enabled: true,
Provider: "claude",
Model: "qwen-vl-max",
TimeoutSeconds: 90,
},
Knowledge: config.KnowledgeConfig{
Enabled: false,
BasePath: "knowledge_base",
Embedding: config.EmbeddingConfig{
Provider: "openai",
Model: "text-embedding-v4",
BaseURL: "https://stale.example.test/v1",
APIKey: "sk-stale",
},
},
}
h := &ConfigHandler{
config: cfg,
configPath: cfgPath,
logger: zap.NewNop(),
}
// 1. TestEmbedding falls back to OpenAI base_url + masked OpenAI api_key when embedding fields are blank.
rec := httptest.NewRecorder()
ctx, _ := gin.CreateTestContext(rec)
probeBody := `{"embedding":{"provider":"openai","model":"text-embedding-v4","base_url":"","api_key":""},"openai":{"provider":"openai_compatible","base_url":"` + embedServer.URL + `/v1","api_key":"********","model":"demo-chat"}}`
ctx.Request = httptest.NewRequest(http.MethodPost, "/api/config/test-embedding", strings.NewReader(probeBody))
ctx.Request.Header.Set("Content-Type", "application/json")
h.TestEmbedding(ctx)
if rec.Code != http.StatusOK {
t.Fatalf("TestEmbedding HTTP %d: %s", rec.Code, rec.Body.String())
}
var probeResp struct {
Success bool `json:"success"`
Dimensions int `json:"dimensions"`
Error string `json:"error"`
}
if err := json.Unmarshal(rec.Body.Bytes(), &probeResp); err != nil {
t.Fatalf("decode probe response: %v", err)
}
if !probeResp.Success || probeResp.Dimensions != 4 {
t.Fatalf("unexpected probe response: %+v", probeResp)
}
if seenAuth != "Bearer sk-main-channel" {
t.Fatalf("expected fallback Bearer sk-main-channel, got %q", seenAuth)
}
// 2. Clearing knowledge.embedding.base_url / api_key and vision.provider / timeout_seconds persists empty values to disk.
rec = httptest.NewRecorder()
ctx, _ = gin.CreateTestContext(rec)
updateBody := `{
"vision":{"enabled":true,"provider":"","base_url":"","api_key":"","model":"qwen-vl-max","timeout_seconds":0},
"knowledge":{"enabled":true,"base_path":"knowledge_base","embedding":{"provider":"openai","model":"text-embedding-v4","base_url":"","api_key":""}}
}`
ctx.Request = httptest.NewRequest(http.MethodPut, "/api/config", strings.NewReader(updateBody))
ctx.Request.Header.Set("Content-Type", "application/json")
h.UpdateConfig(ctx)
if rec.Code != http.StatusOK {
t.Fatalf("UpdateConfig HTTP %d: %s", rec.Code, rec.Body.String())
}
savedYAML, err := os.ReadFile(cfgPath)
if err != nil {
t.Fatalf("read saved config.yaml: %v", err)
}
text := string(savedYAML)
if strings.Contains(text, "stale.example.test") || strings.Contains(text, "sk-stale") {
t.Fatalf("stale embedding fields were not cleared in config.yaml:\n%s", text)
}
if strings.Contains(text, "provider: claude") || strings.Contains(text, "timeout_seconds: 90") {
t.Fatalf("stale vision fields were not cleared in config.yaml:\n%s", text)
}
}

View File

@ -5086,6 +5086,51 @@ func (h *OpenAPIHandler) GetOpenAPISpec(c *gin.Context) {
},
},
},
"/api/config/test-embedding": map[string]interface{}{
"post": map[string]interface{}{
"tags": []string{"配置管理"},
"summary": "测试知识库嵌入模型连接",
"description": "测试知识库 Embedding 模型 API 是否可用,返回向量维度与延迟。",
"operationId": "testEmbedding",
"requestBody": map[string]interface{}{
"required": true,
"content": map[string]interface{}{
"application/json": map[string]interface{}{
"schema": map[string]interface{}{
"type": "object",
"required": []string{"embedding"},
"properties": map[string]interface{}{
"channel_id": map[string]interface{}{"type": "string"},
"embedding": map[string]interface{}{"type": "object"},
"openai": map[string]interface{}{"type": "object"},
},
},
},
},
},
"responses": map[string]interface{}{
"200": map[string]interface{}{
"description": "测试结果",
"content": map[string]interface{}{
"application/json": map[string]interface{}{
"schema": map[string]interface{}{
"type": "object",
"properties": map[string]interface{}{
"success": map[string]interface{}{"type": "boolean"},
"error": map[string]interface{}{"type": "string"},
"model": map[string]interface{}{"type": "string"},
"dimensions": map[string]interface{}{"type": "integer"},
"latency_ms": map[string]interface{}{"type": "number"},
},
},
},
},
},
"400": map[string]interface{}{"description": "参数错误"},
"401": map[string]interface{}{"description": "未授权"},
},
},
},
"/api/config/test-openai": map[string]interface{}{
"post": map[string]interface{}{
"tags": []string{"配置管理"},

View File

@ -63,6 +63,12 @@ func NewEmbedder(ctx context.Context, cfg *config.KnowledgeConfig, openAIConfig
}
baseURL := strings.TrimSpace(cfg.Embedding.BaseURL)
if baseURL == "" && openAIConfig != nil {
provider := strings.ToLower(strings.TrimSpace(openAIConfig.Provider))
if provider != "claude" && provider != "anthropic" {
baseURL = strings.TrimSpace(openAIConfig.BaseURL)
}
}
baseURL = strings.TrimSuffix(baseURL, "/")
if baseURL == "" {
baseURL = "https://api.openai.com/v1"
@ -95,6 +101,32 @@ func NewEmbedder(ctx context.Context, cfg *config.KnowledgeConfig, openAIConfig
}, nil
}
// ProbeEmbedding 发送一条最小文本向量化请求以验证 Embedding 接口连通性与返回维度。
func ProbeEmbedding(ctx context.Context, cfg *config.KnowledgeConfig, openAIConfig *config.OpenAIConfig, logger *zap.Logger) (string, int, error) {
probeCfg := config.KnowledgeConfig{}
if cfg != nil {
probeCfg = *cfg
}
probeCfg.Indexing.MaxRetries = 1
probeCfg.Indexing.RateLimitDelayMs = 0
probeCfg.Indexing.MaxRPM = 0
if probeCfg.Indexing.RequestTimeoutSeconds <= 0 || probeCfg.Indexing.RequestTimeoutSeconds > 30 {
probeCfg.Indexing.RequestTimeoutSeconds = 30
}
embedder, err := NewEmbedder(ctx, &probeCfg, openAIConfig, logger)
if err != nil {
return "", 0, err
}
vecs, err := embedder.provider.EmbedStrings(ctx, []string{"CyberStrikeAI knowledge connectivity check"})
if err != nil {
return embedder.EmbeddingModelName(), 0, err
}
if len(vecs) == 0 || len(vecs[0]) == 0 {
return embedder.EmbeddingModelName(), 0, fmt.Errorf("API 返回了空向量")
}
return embedder.EmbeddingModelName(), len(vecs[0]), nil
}
// EmbeddingModelName 返回配置的嵌入模型名(用于 tiktoken 分块与向量行元数据)。
func (e *Embedder) EmbeddingModelName() string {
if e == nil || e.config == nil {

View File

@ -1,4 +1,5 @@
import { useEffect, useId, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Dropdown, RadioGroup, Select, SideSheet, Slider, Spin, TextArea, Typography } from '@douyinfe/semi-ui';
import { IconBolt, IconChevronRight, IconUndo } from '@douyinfe/semi-icons';
import { useResource } from '../../components/hooks';
@ -85,6 +86,7 @@ function SettingSelect({ label, ...props }) {
export function ModelSettings({ model, busy, canReadConfig }) {
const t = useT();
const navigate = useNavigate();
const channelLabelId = useId();
const pickerRef = useRef(null);
const defaultId = model.config.data?.default_channel;
@ -188,6 +190,24 @@ export function ModelSettings({ model, busy, canReadConfig }) {
{t('chat.reasoningOverrideBlocked', null, '此通道使用系统设置中的推理强度。')}
</Text>
)}
{canReadConfig && !model.config.loading && !model.config.error && (
<div className="chat-vision-entry">
<Text type="tertiary" size="small" className="chat-vision-entry-status">
{model.vision?.ready
? `辅助识图:${model.vision.model}`
: model.vision?.nativeMode === 'enabled'
? '图片识别:通道原生支持'
: '当前模型不支持识图?'}
</Text>
<button
type="button"
className="chat-vision-entry-link"
onClick={() => navigate('/settings?section=models&focus=vision')}
>
{model.vision?.ready ? '配置' : '配置视觉模型'}
</button>
</div>
)}
</div>
);
}

View File

@ -1,4 +1,5 @@
import { useId, useMemo, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { Banner, Button, Popover, Select, Tag, TextArea, Tooltip, Typography } from '@douyinfe/semi-ui';
import { IconArrowUp, IconChevronDown, IconDesktop, IconFolder, IconPaperclip, IconPlus, IconShield, IconStop, IconUser } from '@douyinfe/semi-icons';
import { useT } from '../../lib/i18n';
@ -42,11 +43,16 @@ export default function Composer({
uploading
}) {
const t = useT();
const navigate = useNavigate();
const fileRef = useRef(null);
const modeLabelId = useId();
const projectLabelId = useId();
const roleLabelId = useId();
const list = Array.isArray(attachments) ? attachments : [];
const hasImageAttachment = list.some(item => (
String(item?.mimeType || '').startsWith('image/')
|| /\.(?:png|jpe?g|gif|webp|bmp)$/i.test(String(item?.fileName || ''))
));
const modeOptions = useMemo(() => [
{
value: 'single',
@ -252,6 +258,22 @@ export default function Composer({
))}
</div>
)}
{hasImageAttachment && canReadConfig && !model.config.loading && model.vision?.nativeMode !== 'enabled' && (
<div className={`chat-image-vision-tip${model.vision?.ready ? ' is-ready' : ''}`}>
<span>
{model.vision?.ready
? `已启用独立视觉模型(${model.vision.model}),若当前模型不支持图片输入将自动通过 analyze_image 识图。`
: '若当前对话模型不支持识别图片,可开启独立「视觉分析模型」代为识图(或为支持识图的通道启用原生图片输入)。'}
</span>
<button
type="button"
className="chat-vision-entry-link"
onClick={() => navigate('/settings?section=models&focus=vision')}
>
{model.vision?.ready ? '切换视觉模型' : '去开启视觉模型'}
</button>
</div>
)}
<TextArea
className="chat-textarea"
borderless

View File

@ -393,6 +393,53 @@
.chat-file-chip .semi-tag-content { display: flex; align-items: center; gap: 6px; min-width: 0; }
.chat-file-name { min-width: 0; max-width: 220px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.chat-file-state { flex: 0 0 auto; font-size: 11px; }
.chat-image-vision-tip {
display: flex;
align-items: center;
justify-content: space-between;
flex-wrap: wrap;
gap: 6px 12px;
margin-bottom: 10px;
padding: 8px 12px;
border-radius: 10px;
border: 1px solid var(--semi-color-warning-light-active);
background: var(--semi-color-warning-light-default);
color: var(--semi-color-text-1);
font-size: 12px;
line-height: 1.5;
}
.chat-image-vision-tip.is-ready {
border-color: var(--semi-color-border);
background: var(--semi-color-fill-0);
color: var(--semi-color-text-2);
}
.chat-vision-entry {
display: flex;
align-items: center;
justify-content: space-between;
gap: 6px;
margin-top: 8px;
padding-top: 8px;
border-top: 1px solid var(--semi-color-border);
}
.chat-vision-entry-status.semi-typography {
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.chat-vision-entry-link {
flex: 0 0 auto;
background: none;
border: none;
padding: 0;
color: var(--semi-color-primary);
font-size: 12px;
font-weight: 500;
cursor: pointer;
}
.chat-vision-entry-link:hover { text-decoration: underline; }
.chat-vision-entry-link:focus-visible { outline: 2px solid var(--semi-color-primary); outline-offset: 2px; border-radius: 4px; }
.chat-composer-box .semi-input-textarea-wrapper,
.chat-composer-box .semi-input-textarea { border: none; box-shadow: none; background: none; padding: 0; font-size: 15px; line-height: 1.75; }

View File

@ -26,17 +26,34 @@ function useChatPreference(key, fallback) {
}];
}
function resolveNativeImageMode(channelConfig, imageDefault) {
if (channelConfig?.image_input === 'enabled') return 'enabled';
if (channelConfig?.image_input === 'disabled') return 'disabled';
if (imageDefault === true) return 'enabled';
if (imageDefault === false) return 'disabled';
return 'auto';
}
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 ({ 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 fullConfig = useResource(({ signal } = {}) => api.get('/config', { include_tools: 0 }, { signal }), [canReadConfig], { skip: !canReadConfig });
const aiData = fullConfig.data?.ai;
const config = { ...fullConfig, data: aiData };
const channels = Object.entries(aiData?.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]
|| channels.find(([id]) => id === normalizedChannel)?.[0] || '';
const channelConfig = config.data?.channels?.[channel || config.data?.default_channel];
const activeId = channel || aiData?.default_channel || '';
const channelConfig = activeId ? aiData?.channels?.[activeId] : fullConfig.data?.openai;
const overrideBlocked = channelConfig?.reasoning?.allow_client_reasoning === false;
const visionModel = String(fullConfig.data?.vision?.model || '').trim();
const visionReady = Boolean(fullConfig.data?.vision?.enabled && visionModel);
const nativeImageMode = resolveNativeImageMode(
channelConfig,
fullConfig.data?.image_input_defaults?.[activeId]
);
const mode = REASONING_MODES.includes(storedMode) ? storedMode : 'default';
const effort = REASONING_EFFORTS.includes(storedEffort) ? storedEffort : '';
const reasoning = {
@ -46,6 +63,11 @@ export function useModelPreferences(canReadConfig) {
return {
channel, channels, setChannel, config, mode, setMode, effort, setEffort, overrideBlocked,
vision: {
ready: visionReady,
model: visionModel,
nativeMode: nativeImageMode
},
waitingForChannel: Boolean(canReadConfig && storedChannel && config.loading),
request: {
aiChannelId: canReadConfig ? channel || undefined : undefined,

View File

@ -1,6 +1,7 @@
import { useCallback, useEffect, useState } from 'react';
import { Button, Form, Input, Select, Space, Tag, TextArea, Typography } from '@douyinfe/semi-ui';
import { IconDelete, IconEdit, IconPlus, IconRefresh, IconSearch } from '@douyinfe/semi-icons';
import { useCallback, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Banner, Button, Form, Input, Select, Space, Tag, Typography } from '@douyinfe/semi-ui';
import { IconDelete, IconEdit, IconPlus, IconRefresh, IconSearch, IconSetting } from '@douyinfe/semi-icons';
import { api } from '../../lib/http';
import { useAuth } from '../../lib/auth';
import { useT } from '../../lib/i18n';
@ -12,8 +13,10 @@ const { Text } = Typography;
export default function KnowledgeManagementPage() {
const t = useT();
const navigate = useNavigate();
const { hasPermission } = useAuth();
const canWrite = hasPermission('knowledge:write');
const canReadConfig = hasPermission('config:read');
const [category, setCategory] = useState('');
const [keyword, setKeyword] = useState('');
const [page, setPage] = useState(1);
@ -34,6 +37,7 @@ export default function KnowledgeManagementPage() {
const items = Array.isArray(list.data?.items) ? list.data.items : [];
const total = Number(list.data?.total || 0);
const knowledgeDisabled = list.data?.enabled === false || indexStatus.data?.enabled === false;
const categoryOptions = (Array.isArray(categories.data?.categories) ? categories.data.categories : [])
.map(item => (typeof item === 'string' ? { value: item, label: item } : { value: item.name || item.category, label: item.name || item.category }));
@ -109,14 +113,37 @@ export default function KnowledgeManagementPage() {
title={t('knowledge.title', null, '知识管理')}
description="知识条目会参与智能体检索;修改后需要重建索引才能生效。"
extra={(
<Space>
<Space wrap>
{canReadConfig && (
<Button icon={<IconSetting />} onClick={() => navigate('/settings?section=knowledge')}>
知识库设置
</Button>
)}
<Button icon={<IconRefresh />} onClick={refreshAll}>刷新</Button>
{canWrite && <Button onClick={() => buildIndex(false)}>构建索引</Button>}
{canWrite && <Button onClick={() => buildIndex(true)}>全量重建</Button>}
{canWrite && <Button theme="solid" type="primary" icon={<IconPlus />} onClick={() => setEditor({ item: null, form: {} })}>新增知识</Button>}
{canWrite && <Button disabled={knowledgeDisabled} onClick={() => buildIndex(false)}>构建索引</Button>}
{canWrite && <Button disabled={knowledgeDisabled} onClick={() => buildIndex(true)}>全量重建</Button>}
{canWrite && <Button theme="solid" type="primary" icon={<IconPlus />} disabled={knowledgeDisabled} onClick={() => setEditor({ item: null, form: {} })}>新增知识</Button>}
</Space>
)}
/>
{knowledgeDisabled && (
<Banner
type="warning"
bordered
closeIcon={null}
style={{ marginBottom: 16 }}
description={(
<Space wrap>
<span>{list.data?.message || indexStatus.data?.message || '知识库功能未启用,请先在系统设置中开启知识检索并配置嵌入模型。'}</span>
{canReadConfig && (
<Button size="small" theme="solid" type="primary" onClick={() => navigate('/settings?section=knowledge')}>
前往启用知识库
</Button>
)}
</Space>
)}
/>
)}
<StatGrid
columns={4}
metrics={[

View File

@ -9,6 +9,7 @@ import { PageHeader } from '../../components/ui';
import { useT } from '../../lib/i18n';
import BasicSection from './sections/BasicSection';
import ModelsSection from './sections/ModelsSection';
import KnowledgeSection from './sections/KnowledgeSection';
import TokenUsageSection from './sections/TokenUsageSection';
import StorageSection from './sections/StorageSection';
import UpdateSection from './sections/UpdateSection';
@ -16,7 +17,7 @@ import AuditSection from './sections/AuditSection';
import AppearanceSection from './sections/AppearanceSection';
import './page.css';
const SECTION_KEYS = ['basic', 'models', 'token-usage', 'storage', 'update', 'audit', 'appearance'];
const SECTION_KEYS = ['basic', 'models', 'knowledge', 'token-usage', 'storage', 'update', 'audit', 'appearance'];
export default function SettingsPage() {
const t = useT();
@ -32,6 +33,7 @@ export default function SettingsPage() {
const change = key => {
const next = new URLSearchParams(params);
next.set('section', key);
next.delete('focus');
setParams(next, { replace: true });
};
@ -51,11 +53,14 @@ export default function SettingsPage() {
className="settings-tabs"
>
<Tabs.TabPane itemKey="basic" tab={t('settings.nav.basic', null, '基础配置')}>
<BasicSection />
<BasicSection active={activeKey === 'basic'} />
</Tabs.TabPane>
<Tabs.TabPane itemKey="models" tab={t('settings.nav.models', null, '模型与工具')}>
<ModelsSection />
</Tabs.TabPane>
<Tabs.TabPane itemKey="knowledge" tab={t('settings.nav.knowledge', null, '知识库')}>
<KnowledgeSection />
</Tabs.TabPane>
<Tabs.TabPane itemKey="token-usage" tab={t('settings.nav.tokenUsage', null, 'Token 用量')}>
<TokenUsageSection />
</Tabs.TabPane>

View File

@ -57,7 +57,8 @@
}
.settings-schema-table th { color: var(--semi-color-text-2); font-weight: 600; }
.settings-probe-form {
.settings-probe-form,
.settings-vision-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 12px 16px;
@ -65,7 +66,9 @@
.settings-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
.settings-field-wide { grid-column: span 2; }
.settings-probe-actions { margin-top: 14px; }
.settings-channel-panel .semi-card-header-wrapper { align-items: center; gap: 8px; }
.settings-channel-panel .semi-card-header-wrapper,
.settings-vision-panel .semi-card-header-wrapper,
.settings-knowledge-panel .semi-card-header-wrapper { align-items: center; gap: 8px; }
.settings-channel-notices { display: grid; gap: 8px; margin-top: 14px; }
.settings-probe-result { margin-top: 12px; display: flex; flex-direction: column; gap: 10px; }
.settings-model-picker { width: min(280px, 60vw); }
@ -76,6 +79,42 @@
.settings-probe-card { display: flex; flex-direction: column; gap: 8px; min-width: 0; }
.settings-probe-inline { display: grid; grid-template-columns: repeat(auto-fit, minmax(140px, 1fr)); gap: 8px; }
.settings-switch-row {
display: flex;
align-items: flex-start;
gap: 12px;
padding: 12px 14px;
margin-bottom: 14px;
border: 1px solid var(--semi-color-border);
border-radius: 8px;
background: var(--semi-color-fill-0);
}
.settings-switch-copy { display: flex; flex-direction: column; gap: 2px; min-width: 0; }
.settings-subsection {
display: flex;
flex-direction: column;
gap: 10px;
margin-top: 18px;
padding-top: 16px;
border-top: 1px solid var(--semi-color-border);
}
.settings-subsection-title { font-size: 14px; }
.settings-image-fallback-tip { margin-top: 10px; }
.settings-focus-ring .cs-section-card {
box-shadow: 0 0 0 2px var(--semi-color-primary);
}
.settings-overview-inline {
display: inline-flex;
align-items: center;
flex-wrap: wrap;
gap: 6px;
}
.settings-overview-link.semi-button {
height: 22px;
padding: 0 6px;
font-size: 12px;
}
.settings-disk { display: flex; flex-direction: column; gap: 6px; margin-bottom: 16px; max-width: 720px; }
.settings-policy-grid {
display: grid;
@ -116,8 +155,12 @@
}
@media (max-width: 480px) {
.settings-channel-panel .semi-card-header-wrapper { flex-direction: column-reverse; align-items: stretch; }
.settings-channel-panel .semi-card-header-wrapper-title { margin-inline: 0; }
.settings-channel-panel .semi-card-header-wrapper,
.settings-vision-panel .semi-card-header-wrapper,
.settings-knowledge-panel .semi-card-header-wrapper { flex-direction: column-reverse; align-items: stretch; }
.settings-channel-panel .semi-card-header-wrapper-title,
.settings-vision-panel .semi-card-header-wrapper-title,
.settings-knowledge-panel .semi-card-header-wrapper-title { margin-inline: 0; }
}
.settings-update-source-form {

View File

@ -6,7 +6,8 @@
* POST /config/apply 重新加载并重启相关服务
* 选择 YAML 而不是逐项表单:GET /config 暴露 18 个段落,逐项表单必然漏字段。
*/
import { useCallback, useEffect, useMemo, useState } from 'react';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Banner, Button, Collapse, Space, Tag, TextArea, Typography } from '@douyinfe/semi-ui';
import { IconRefresh, IconTick } from '@douyinfe/semi-icons';
import { api, errorMessage } from '../../../lib/http';
@ -32,10 +33,11 @@ const WRITABLE_SECTIONS = [
const EDITOR_HEADER = [
'系统设置 · 原始配置(由 GET /config 生成)',
'',
'· 视觉模型与知识库设置现可直接在左侧「模型与工具」与「知识库」页签可视化启用。',
'· 密钥字段显示为 ********:原样保存会沿用已保存的凭据,填写新值即替换。',
'· 保存 = PUT /config(写入 config.yaml)+ POST /config/apply(重新加载)。',
'· 只提交文本里有修改的段落,省略的段落沿用服务端配置。',
'· storage(清理策略)不在 GET /config 里,请到「存储与更新」分区编辑。',
'· storage(清理策略)不在 GET /config 里,请到「存储清理」分区编辑。',
'· server / auth / log / audit / monitor / database / security / external_mcp / update',
' 不在本接口的写入范围,保存时会被忽略(这些段落请改 config.yaml 或其他页面)。'
].join('\n');
@ -50,13 +52,15 @@ function normalizeTools(tools) {
}));
}
export default function BasicSection() {
export default function BasicSection({ active = true }) {
const t = useT();
const navigate = useNavigate();
const { hasPermission } = useAuth();
const canRead = hasPermission('config:read');
const canWrite = hasPermission('config:write');
const loader = useCallback(({ signal } = {}) => api.get('/config', null, { signal }), []);
const config = useResource(loader, [canRead], { skip: !canRead });
const prevActive = useRef(active);
const [text, setText] = useState('');
const [baseline, setBaseline] = useState('');
@ -67,7 +71,11 @@ export default function BasicSection() {
useEffect(() => {
if (!config.data) return;
const { context_window_defaults: _defaults, ...configuration } = config.data;
const {
context_window_defaults: _defaults,
image_input_defaults: _imageDefaults,
...configuration
} = config.data;
const next = dumpYaml(configuration, { header: EDITOR_HEADER });
setText(next);
setBaseline(next);
@ -77,6 +85,13 @@ export default function BasicSection() {
const dirty = baseline !== '' && text !== baseline;
const busy = phase !== 'idle';
useEffect(() => {
if (active && !prevActive.current && canRead && !dirty && !busy) {
config.reload({ silent: true });
}
prevActive.current = active;
}, [active, busy, canRead, config.reload, dirty]);
const summary = useMemo(() => {
const data = config.data;
if (!data) return [];
@ -85,6 +100,8 @@ export default function BasicSection() {
const defaultId = data.ai?.default_channel;
const tools = Array.isArray(data.tools) ? data.tools : [];
const enabledTools = tools.filter(tool => tool.enabled).length;
const visionOn = Boolean(data.vision?.enabled && String(data.vision?.model || '').trim());
const knowledgeOn = Boolean(data.knowledge?.enabled);
return [
{ label: t('settings.defaultChannel', null, '默认 AI 通道'), value: defaultId ? modelChannelName(defaultId, channels[defaultId]) : '—' },
{
@ -97,12 +114,41 @@ export default function BasicSection() {
},
{
label: t('settings.visionLabel', null, '视觉模型'),
value: data.vision?.enabled ? (data.vision.model || '已启用') : '未启用'
value: (
<span className="settings-overview-inline">
<span>{data.vision?.enabled ? (data.vision.model || '已启用') : '未启用'}</span>
<Button
size="small"
theme="borderless"
type="primary"
className="settings-overview-link"
onClick={() => navigate('/settings?section=models&focus=vision')}
>
{visionOn ? '配置' : '去启用'}
</Button>
</span>
)
},
{
label: t('settings.knowledge.title', null, '知识库设置'),
value: (
<span className="settings-overview-inline">
<span>{knowledgeOn ? '已启用' : '未启用'}</span>
<Button
size="small"
theme="borderless"
type="primary"
className="settings-overview-link"
onClick={() => navigate('/settings?section=knowledge')}
>
{knowledgeOn ? '配置' : '去启用'}
</Button>
</span>
)
},
{ label: t('settings.knowledge.title', null, '知识库'), value: data.knowledge?.enabled ? '已启用' : '未启用' },
{ label: 'C2', value: data.c2?.enabled ? '已启用' : '未启用' }
];
}, [config.data, t]);
}, [config.data, navigate, t]);
const doReload = useCallback(async () => {
setSaveError(null);

View File

@ -0,0 +1,740 @@
/**
* 知识库设置(knowledge 段):启用开关、嵌入模型(Embedding)配置与连通性测试、
* 检索参数(Top-K / 阈值 / MultiQuery / Rerank)以及索引构建分块限流配置。
*/
import { useCallback, useEffect, useId, useMemo, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Banner, Button, Collapse, Input, Select, Space, Switch, Tag, Typography } from '@douyinfe/semi-ui';
import { api } from '../../../lib/http';
import { useAuth } from '../../../lib/auth';
import { useT } from '../../../lib/i18n';
import { modelChannelName } from '../../../lib/model-channel';
import { useResource } from '../../../components/hooks';
import { ErrorBanner, KeyValueList, SectionCard, toastSuccess } from '../../../components/ui';
import { Hint, LoadingBlock, PermissionBanner } from './common';
const { Text } = Typography;
const EMPTY_PROBE = { key: '', payload: null, error: null };
function strNum(val) {
return val != null && val !== '' && Number(val) !== 0 ? String(val) : (val === 0 ? '0' : '');
}
function knowledgeValues(knowledge = {}) {
const emb = knowledge.embedding || {};
const ret = knowledge.retrieval || {};
const mq = ret.multi_query || {};
const rerank = ret.rerank || {};
const post = ret.post_retrieve || {};
const idx = knowledge.indexing || {};
return {
enabled: Boolean(knowledge.enabled),
base_path: knowledge.base_path || 'knowledge_base',
embedding_provider: emb.provider || 'openai',
embedding_model: emb.model || '',
embedding_base_url: emb.base_url || '',
embedding_api_key: emb.api_key || '',
top_k: ret.top_k > 0 ? String(ret.top_k) : '5',
similarity_threshold: ret.similarity_threshold > 0 ? String(ret.similarity_threshold) : '0.4',
sub_index_filter: ret.sub_index_filter || '',
multi_query_max_queries: mq.max_queries > 0 ? String(mq.max_queries) : '',
rerank_provider: rerank.provider || '',
rerank_model: rerank.model || '',
rerank_base_url: rerank.base_url || '',
rerank_api_key: rerank.api_key || '',
prefetch_top_k: strNum(post.prefetch_top_k),
max_context_chars: strNum(post.max_context_chars),
max_context_tokens: strNum(post.max_context_tokens),
chunk_strategy: idx.chunk_strategy || '',
chunk_size: idx.chunk_size > 0 ? String(idx.chunk_size) : '',
chunk_overlap: idx.chunk_overlap > 0 ? String(idx.chunk_overlap) : '',
max_chunks_per_item: strNum(idx.max_chunks_per_item),
batch_size: idx.batch_size > 0 ? String(idx.batch_size) : '',
request_timeout_seconds: idx.request_timeout_seconds > 0 ? String(idx.request_timeout_seconds) : '',
max_rpm: strNum(idx.max_rpm),
rate_limit_delay_ms: strNum(idx.rate_limit_delay_ms),
max_retries: idx.max_retries > 0 ? String(idx.max_retries) : '',
retry_delay_ms: idx.retry_delay_ms > 0 ? String(idx.retry_delay_ms) : '',
prefer_source_file: Boolean(idx.prefer_source_file),
sub_indexes: Array.isArray(idx.sub_indexes) ? idx.sub_indexes.join(', ') : ''
};
}
function parseNonNegInt(raw, labelText) {
const trimmed = String(raw ?? '').trim();
if (!trimmed) return 0;
if (!/^\d+$/.test(trimmed)) {
throw new Error(`${labelText}请输入非负整数`);
}
const num = Number(trimmed);
if (!Number.isSafeInteger(num) || num < 0) {
throw new Error(`${labelText}请输入有效的非负整数`);
}
return num;
}
function resolveDefaultChannel(config) {
const channels = config?.ai?.channels || {};
const defaultId = config?.ai?.default_channel || '';
if (defaultId && channels[defaultId]) {
const ch = channels[defaultId];
return {
channelId: defaultId,
displayName: modelChannelName(defaultId, ch),
openai: {
provider: ch.provider || 'openai_compatible',
base_url: ch.base_url || '',
api_key: ch.api_key || '',
model: ch.model || ''
}
};
}
const oa = config?.openai || {};
return {
channelId: '',
displayName: oa.model || '',
openai: {
provider: oa.provider || 'openai_compatible',
base_url: oa.base_url || '',
api_key: oa.api_key || '',
model: oa.model || ''
}
};
}
export default function KnowledgeSection() {
const t = useT();
const navigate = useNavigate();
const { hasPermission } = useAuth();
const canRead = hasPermission('config:read');
const canWrite = hasPermission('config:write');
const loader = useCallback(({ signal } = {}) => api.get('/config', { include_tools: 0 }, { signal }), []);
const configRes = useResource(loader, [canRead], { skip: !canRead });
const providerLabelId = useId();
const rerankProviderId = useId();
const strategyLabelId = useId();
const pickerLabelId = useId();
const baseline = useMemo(() => knowledgeValues(configRes.data?.knowledge), [configRes.data?.knowledge]);
const baselineSig = JSON.stringify(baseline);
const [draft, setDraft] = useState({});
const form = { ...baseline, ...draft };
const dirty = Object.keys(draft).length > 0;
const [busy, setBusy] = useState('');
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState(null);
const [applyPending, setApplyPending] = useState(false);
const [probe, setProbe] = useState(EMPTY_PROBE);
useEffect(() => {
setDraft({});
setProbe(EMPTY_PROBE);
}, [baselineSig]);
if (!canRead) {
return <PermissionBanner permission="config:read" label={t('settings.nav.knowledge', null, '读取知识库配置')} />;
}
if (configRes.loading && !configRes.data) return <LoadingBlock rows={6} />;
const locked = !canWrite || saving || Boolean(busy);
const fallbackChannel = resolveDefaultChannel(configRes.data);
const mainIsDeepSeekOfficial = /api\.deepseek\.com/i.test(fallbackChannel.openai.base_url || '');
const mainIsClaude = ['claude', 'anthropic'].includes(String(fallbackChannel.openai.provider || '').toLowerCase());
const needsSeparateEmbeddingNotice = !form.embedding_base_url.trim() && (mainIsDeepSeekOfficial || mainIsClaude);
const update = (field, value) => {
if (probe.key !== 'list' || ['embedding_provider', 'embedding_base_url', 'embedding_api_key'].includes(field)) {
setProbe(EMPTY_PROBE);
}
if (!applyPending) setSaveError(null);
setDraft(current => {
const next = { ...current };
if (value === baseline[field]) delete next[field];
else next[field] = value;
return next;
});
};
const discard = () => {
setDraft({});
setProbe(EMPTY_PROBE);
if (!applyPending) setSaveError(null);
};
const buildKnowledgePayload = () => {
const topK = parseNonNegInt(form.top_k, t('settingsBasic.topK', null, 'Top-K 结果数量')) || 5;
const rawThreshold = String(form.similarity_threshold ?? '').trim();
const threshold = rawThreshold === '' ? 0.4 : Number(rawThreshold);
if (!Number.isFinite(threshold) || threshold < 0 || threshold > 1) {
throw new Error('相似度阈值请输入 0 到 1 之间的数值(例如 0.4)');
}
const maxQueries = parseNonNegInt(form.multi_query_max_queries, t('settingsBasic.multiQueryMaxQueries', null, 'MultiQuery 改写变体上限'));
if (maxQueries > 8) {
throw new Error('MultiQuery 改写变体上限最大为 8(留空使用默认 4,填 1 跳过改写)');
}
const subIndexes = String(form.sub_indexes || '')
.split(/[,\n\r]+/)
.map(item => item.trim())
.filter(Boolean);
return {
enabled: Boolean(form.enabled),
base_path: form.base_path.trim() || 'knowledge_base',
embedding: {
provider: form.embedding_provider.trim() || 'openai',
model: form.embedding_model.trim() || 'text-embedding-3-small',
base_url: form.embedding_base_url.trim(),
api_key: form.embedding_api_key
},
retrieval: {
top_k: topK,
similarity_threshold: threshold,
sub_index_filter: form.sub_index_filter.trim(),
multi_query: {
max_queries: maxQueries
},
rerank: {
provider: form.rerank_provider.trim(),
model: form.rerank_model.trim(),
base_url: form.rerank_base_url.trim(),
api_key: form.rerank_api_key
},
post_retrieve: {
prefetch_top_k: parseNonNegInt(form.prefetch_top_k, t('settingsBasic.prefetchTopK', null, '预取候选数')),
max_context_chars: parseNonNegInt(form.max_context_chars, t('settingsBasic.maxContextChars', null, '返回内容最大字符数')),
max_context_tokens: parseNonNegInt(form.max_context_tokens, t('settingsBasic.maxContextTokens', null, '返回内容最大 Token 数'))
}
},
indexing: {
chunk_strategy: form.chunk_strategy.trim(),
chunk_size: parseNonNegInt(form.chunk_size, t('settingsBasic.chunkSize', null, '分块大小')),
chunk_overlap: parseNonNegInt(form.chunk_overlap, t('settingsBasic.chunkOverlap', null, '分块重叠')),
max_chunks_per_item: parseNonNegInt(form.max_chunks_per_item, t('settingsBasic.maxChunksPerItem', null, '单个知识项最大块数')),
batch_size: parseNonNegInt(form.batch_size, t('settingsBasic.batchSize', null, '嵌入批大小')),
request_timeout_seconds: parseNonNegInt(form.request_timeout_seconds, t('settingsBasic.requestTimeoutSeconds', null, '嵌入 HTTP 超时')),
max_rpm: parseNonNegInt(form.max_rpm, t('settingsBasic.maxRpm', null, '每分钟最大请求数')),
rate_limit_delay_ms: parseNonNegInt(form.rate_limit_delay_ms, t('settingsBasic.rateLimitDelay', null, '请求间隔延迟')),
max_retries: parseNonNegInt(form.max_retries, t('settingsBasic.maxRetries', null, '最大重试次数')),
retry_delay_ms: parseNonNegInt(form.retry_delay_ms, t('settingsBasic.retryDelay', null, '重试间隔')),
prefer_source_file: Boolean(form.prefer_source_file),
sub_indexes: subIndexes
}
};
};
const applyConfig = async message => {
try {
await api.post('/config/apply');
setApplyPending(false);
toastSuccess(message);
} catch (error) {
setApplyPending(true);
setSaveError(error);
}
};
const save = async () => {
if (locked || !dirty) return;
setSaveError(null);
if (form.enabled && !form.embedding_model.trim()) {
setSaveError(new Error('启用知识库时请填写嵌入模型名称(例如 text-embedding-v4 或 text-embedding-3-small)'));
return;
}
let payload;
try {
payload = buildKnowledgePayload();
} catch (error) {
setSaveError(error);
return;
}
setSaving(true);
try {
await api.put('/config', { knowledge: payload });
setDraft({});
await applyConfig('知识库配置已保存并应用');
await configRes.reload({ silent: true });
} catch (error) {
setSaveError(error);
} finally {
setSaving(false);
}
};
const retryApply = async () => {
if (locked || !applyPending) return;
setSaving(true);
setSaveError(null);
try {
await applyConfig(t('settings.apply.applySuccess', null, '配置已成功应用'));
} finally {
setSaving(false);
}
};
const testEmbedding = async () => {
if (locked) return;
if (!form.embedding_model.trim()) {
setProbe({ key: 'embedding', payload: null, error: new Error('请先填写嵌入模型名称') });
return;
}
setBusy('embedding');
setProbe(EMPTY_PROBE);
try {
const payload = await api.post('/config/test-embedding', {
channel_id: fallbackChannel.channelId || undefined,
embedding: {
provider: form.embedding_provider.trim() || 'openai',
model: form.embedding_model.trim(),
base_url: form.embedding_base_url.trim(),
api_key: form.embedding_api_key
},
openai: fallbackChannel.openai
});
setProbe({ key: 'embedding', payload, error: null });
} catch (error) {
setProbe({ key: 'embedding', payload: null, error });
} finally {
setBusy('');
}
};
const fetchModels = async () => {
if (locked) return;
setBusy('list');
setProbe(EMPTY_PROBE);
const usingOwnKey = Boolean(form.embedding_api_key);
const effectiveBaseUrl = form.embedding_base_url.trim()
|| (!mainIsClaude ? fallbackChannel.openai.base_url : '')
|| 'https://api.openai.com/v1';
try {
const payload = await api.post('/config/list-models', {
provider: 'openai_compatible',
credential_scope: usingOwnKey ? 'knowledgeEmbedding' : (fallbackChannel.channelId ? undefined : 'openai'),
channel_id: !usingOwnKey && fallbackChannel.channelId ? fallbackChannel.channelId : undefined,
base_url: effectiveBaseUrl,
api_key: usingOwnKey ? form.embedding_api_key : fallbackChannel.openai.api_key
});
setProbe({ key: 'list', payload, error: null });
} catch (error) {
setProbe({ key: 'list', payload: null, error });
} finally {
setBusy('');
}
};
const listedModels = probe.key === 'list' && Array.isArray(probe.payload?.models) ? probe.payload.models : [];
return (
<>
<ErrorBanner error={configRes.error} onRetry={configRes.reload} />
{configRes.data && (
<SectionCard
title={(
<Space wrap spacing={8}>
<span>{t('settings.knowledge.title', null, '知识库设置')}</span>
<Tag color={form.enabled ? 'green' : 'grey'} size="small">
{form.enabled ? t('common.enabled', null, '已启用') : t('common.disabled', null, '未启用')}
</Tag>
{dirty && <Tag color="amber" size="small">{t('settings.unsaved', null, '有未保存修改')}</Tag>}
</Space>
)}
description="开启后将自动初始化向量知识库并向智能体挂载 search_knowledge_base 检索工具。启用保存后,可前往「知识管理」新增知识条目并构建索引。"
className="settings-knowledge-panel"
extra={(
<Space wrap>
<Button onClick={() => navigate('/knowledge-management')}>
前往知识管理
</Button>
{canWrite ? (
<>
{dirty && (
<Button disabled={saving || Boolean(busy)} onClick={discard}>
{t('toolGuard.reset', null, '撤销修改')}
</Button>
)}
<Button
theme="solid"
type="primary"
loading={saving}
disabled={!dirty || Boolean(busy)}
onClick={save}
>
{t('settings.saveAndApply', null, '保存并应用')}
</Button>
</>
) : (
<Tag color="grey" size="small">{t('settingsProbe.channelReadOnly', null, '只读')}</Tag>
)}
</Space>
)}
>
<div className="settings-switch-row">
<Switch
checked={form.enabled}
disabled={locked}
onChange={next => update('enabled', next)}
aria-label={t('settingsBasic.enableKnowledge', null, '启用知识检索功能')}
/>
<div className="settings-switch-copy">
<Text strong>{t('settingsBasic.enableKnowledge', null, '启用知识检索功能')}</Text>
<Hint>保存并应用后立即在线生效,无需重启服务。</Hint>
</div>
</div>
<div className="settings-vision-grid">
<label className="settings-field settings-field-wide">
<Text type="tertiary" size="small">{t('settingsBasic.knowledgeBasePath', null, '知识库路径')}</Text>
<Input
value={form.base_path}
onChange={value => update('base_path', value)}
readOnly={locked}
placeholder={t('settingsBasic.knowledgeBasePathPlaceholder', null, 'knowledge_base')}
/>
<Hint>{t('settingsBasic.knowledgeBasePathHint', null, '相对于配置文件所在目录的路径')}</Hint>
</label>
</div>
<div className="settings-subsection">
<Text strong className="settings-subsection-title">{t('settingsBasic.embeddingConfig', null, '嵌入模型配置')}</Text>
{needsSeparateEmbeddingNotice && (
<Banner
type="info"
bordered
closeIcon={null}
description="提示:当前默认 AI 通道(如 DeepSeek 官方或 Claude 接口)通常不提供 OpenAI 兼容的 /embeddings 向量接口。启用知识库时,请在此处填写独立的向量服务地址与密钥(如阿里云百炼 DashScope、OpenAI、SiliconFlow 或本地 Ollama / vLLM)。"
/>
)}
<div className="settings-vision-grid">
<div className="settings-field">
<Text id={providerLabelId} type="tertiary" size="small">{t('settingsBasic.provider', null, '提供商')}</Text>
<Select
value={form.embedding_provider || 'openai'}
onChange={value => update('embedding_provider', value)}
optionList={[{ value: 'openai', label: t('settingsProbe.compatible', null, '兼容 OpenAI 的接口') }]}
aria-labelledby={providerLabelId}
disabled={locked}
style={{ width: '100%' }}
/>
</div>
<label className="settings-field">
<Text type="tertiary" size="small">{t('settingsBasic.modelName', null, '模型名称')}</Text>
<Input
value={form.embedding_model}
onChange={value => update('embedding_model', value)}
readOnly={locked}
placeholder={t('settingsBasic.embeddingModelPlaceholder', null, 'text-embedding-v4')}
/>
</label>
<label className="settings-field settings-field-wide">
<Text type="tertiary" size="small">{t('settingsBasic.baseUrl', null, 'API 地址')}</Text>
<Input
value={form.embedding_base_url}
onChange={value => update('embedding_base_url', value)}
readOnly={locked}
placeholder={!mainIsClaude && fallbackChannel.openai.base_url
? `留空复用默认通道(${fallbackChannel.openai.base_url})`
: '例如 https://dashscope.aliyuncs.com/compatible-mode/v1'}
/>
</label>
<label className="settings-field">
<Text type="tertiary" size="small">{t('settingsBasic.apiKey', null, 'API 密钥')}</Text>
<Input
mode="password"
autoComplete="new-password"
value={form.embedding_api_key}
onChange={value => update('embedding_api_key', value)}
readOnly={locked}
placeholder={t('settingsBasic.embeddingApiKeyPlaceholder', null, '留空则使用默认通道 API Key')}
/>
</label>
</div>
<Space wrap className="settings-probe-actions">
<Button
loading={busy === 'embedding'}
disabled={!canWrite || saving || (Boolean(busy) && busy !== 'embedding')}
onClick={testEmbedding}
>
测试嵌入模型
</Button>
<Button
loading={busy === 'list'}
disabled={!canWrite || saving || (Boolean(busy) && busy !== 'list')}
onClick={fetchModels}
>
{t('settingsBasic.modelsList', null, '获取模型列表')}
</Button>
</Space>
{probe.error && <div className="settings-probe-result"><ErrorBanner error={probe.error} /></div>}
{probe.key === 'embedding' && probe.payload && (
<div className="settings-probe-result">
{probe.payload.success ? (
<KeyValueList
columns={4}
items={[
{ label: t('settingsProbe.result', null, '测试结果'), value: <Tag color="green">{t('settingsBasic.testSuccess', null, '连接成功')}</Tag> },
{ label: t('settingsBasic.modelName', null, '模型名称'), value: probe.payload.model || form.embedding_model || '—' },
{ label: '向量维度', value: probe.payload.dimensions ? `${probe.payload.dimensions} 维` : '—' },
{
label: t('settingsProbe.latency', null, '响应耗时'),
value: probe.payload.latency_ms != null
? t('settingsProbe.milliseconds', { value: probe.payload.latency_ms }, `${probe.payload.latency_ms} 毫秒`)
: '—'
}
]}
/>
) : (
<Banner type="danger" bordered closeIcon={null} description={probe.payload.error || t('settingsBasic.testFailed', null, '连接失败')} />
)}
</div>
)}
{probe.key === 'list' && probe.payload && (
<div className="settings-probe-result">
{probe.payload.success ? (
<Space wrap spacing={8}>
<Text>
{t('settingsBasic.modelsListSuccess', { count: probe.payload.count ?? listedModels.length }, `已获取 ${probe.payload.count ?? listedModels.length} 个模型`)}
</Text>
<span id={pickerLabelId} hidden>{t('settingsBasic.modelsListSelectPlaceholder', null, '请选择嵌入模型')}</span>
{listedModels.length > 0 && (
<Select
filter
aria-labelledby={pickerLabelId}
placeholder={t('settingsBasic.modelsListSelectPlaceholder', null, '请选择模型')}
value={listedModels.includes(form.embedding_model) ? form.embedding_model : undefined}
optionList={listedModels.map(id => ({ value: id, label: id }))}
onChange={value => update('embedding_model', value)}
disabled={locked}
className="settings-model-picker"
/>
)}
</Space>
) : (
<Banner
type={probe.payload.supported === false ? 'info' : 'danger'}
bordered
closeIcon={null}
description={probe.payload.error || t('settingsBasic.modelsListFailed', null, '获取模型列表失败')}
/>
)}
</div>
)}
</div>
<div className="settings-subsection">
<Text strong className="settings-subsection-title">{t('settingsBasic.retrievalConfig', null, '检索配置')}</Text>
<div className="settings-vision-grid">
<label className="settings-field">
<Text type="tertiary" size="small">{t('settingsBasic.topK', null, 'Top-K 结果数量')}</Text>
<Input
value={form.top_k}
onChange={value => update('top_k', value)}
inputMode="numeric"
readOnly={locked}
placeholder={t('settingsBasic.topKPlaceholder', null, '5')}
/>
</label>
<label className="settings-field">
<Text type="tertiary" size="small">{t('settingsBasic.similarityThreshold', null, '相似度阈值(0 ~ 1)')}</Text>
<Input
value={form.similarity_threshold}
onChange={value => update('similarity_threshold', value)}
readOnly={locked}
placeholder="0.4"
/>
</label>
<label className="settings-field">
<Text type="tertiary" size="small">{t('settingsBasic.multiQueryMaxQueries', null, 'MultiQuery 改写变体上限')}</Text>
<Input
value={form.multi_query_max_queries}
onChange={value => update('multi_query_max_queries', value)}
inputMode="numeric"
readOnly={locked}
placeholder={t('settingsBasic.multiQueryMaxQueriesPlaceholder', null, '4')}
/>
</label>
<label className="settings-field">
<Text type="tertiary" size="small">{t('settingsBasic.subIndexFilter', null, '子索引过滤(可选)')}</Text>
<Input
value={form.sub_index_filter}
onChange={value => update('sub_index_filter', value)}
readOnly={locked}
placeholder={t('settingsBasic.subIndexFilterPlaceholder', null, '如 prod,与索引 sub_indexes 一致')}
/>
</label>
</div>
<Hint>{t('settingsBasic.similarityHint', null, '低于相似度阈值的结果将被过滤;MultiQuery 设为 1 时跳过 LLM 改写直接做向量检索。')}</Hint>
</div>
{(applyPending || saveError) && (
<div className="settings-channel-notices">
{applyPending && (
<Banner type="warning" bordered closeIcon={null} description={(
<Space wrap>
<span>知识库配置已写入 config.yaml,但动态应用失败(请检查嵌入模型配置或密钥)。</span>
<Button size="small" disabled={locked} onClick={retryApply}>
{t('settingsProbe.retryApply', null, '重试应用')}
</Button>
</Space>
)} />
)}
<ErrorBanner error={saveError} />
</div>
)}
<Collapse className="settings-audit-model">
<Collapse.Panel
itemKey="knowledge-rerank"
header={<Text strong>{t('settingsBasic.ragPipelineHeader', null, '高级:精排(Rerank)与检索后处理')}</Text>}
>
<Hint>{t('settingsBasic.ragPipelineHint', null, '精排失败时会自动降级为融合排序,不影响基础检索可用性。')}</Hint>
<div className="settings-vision-grid" style={{ marginTop: 8 }}>
<div className="settings-field">
<Text id={rerankProviderId} type="tertiary" size="small">{t('settingsBasic.rerankProvider', null, '精排提供商')}</Text>
<Select
value={form.rerank_provider}
onChange={value => update('rerank_provider', value)}
optionList={[
{ value: '', label: t('settingsBasic.rerankProviderAuto', null, '自动(按 Base URL 推断)') },
{ value: 'dashscope', label: 'DashScope(gte-rerank)' },
{ value: 'cohere', label: t('settingsBasic.rerankProviderCohere', null, 'Cohere / /v1/rerank 兼容接口') }
]}
aria-labelledby={rerankProviderId}
disabled={locked}
style={{ width: '100%' }}
/>
</div>
<label className="settings-field">
<Text type="tertiary" size="small">{t('settingsBasic.rerankModel', null, '精排模型(可选)')}</Text>
<Input
value={form.rerank_model}
onChange={value => update('rerank_model', value)}
readOnly={locked}
placeholder={t('settingsBasic.rerankModelPlaceholder', null, '留空按提供商自动选择')}
/>
</label>
<label className="settings-field settings-field-wide">
<Text type="tertiary" size="small">{t('settingsBasic.rerankBaseUrl', null, '精排 Base URL(可选)')}</Text>
<Input
value={form.rerank_base_url}
onChange={value => update('rerank_base_url', value)}
readOnly={locked}
placeholder={t('settingsBasic.rerankBaseUrlPlaceholder', null, '留空则复用嵌入 / OpenAI 的 base_url')}
/>
</label>
<label className="settings-field">
<Text type="tertiary" size="small">{t('settingsBasic.rerankApiKey', null, '精排 API Key(可选)')}</Text>
<Input
mode="password"
autoComplete="new-password"
value={form.rerank_api_key}
onChange={value => update('rerank_api_key', value)}
readOnly={locked}
placeholder={t('settingsBasic.rerankApiKeyPlaceholder', null, '留空则复用嵌入 / OpenAI 的 api_key')}
/>
</label>
<label className="settings-field">
<Text type="tertiary" size="small">{t('settingsBasic.prefetchTopK', null, '预取候选数')}</Text>
<Input
value={form.prefetch_top_k}
onChange={value => update('prefetch_top_k', value)}
inputMode="numeric"
readOnly={locked}
placeholder={t('settingsBasic.prefetchTopKPlaceholder', null, '20')}
/>
</label>
<label className="settings-field">
<Text type="tertiary" size="small">{t('settingsBasic.maxContextChars', null, '返回内容最大字符数')}</Text>
<Input
value={form.max_context_chars}
onChange={value => update('max_context_chars', value)}
inputMode="numeric"
readOnly={locked}
placeholder="0"
/>
</label>
<label className="settings-field">
<Text type="tertiary" size="small">{t('settingsBasic.maxContextTokens', null, '返回内容最大 Token 数')}</Text>
<Input
value={form.max_context_tokens}
onChange={value => update('max_context_tokens', value)}
inputMode="numeric"
readOnly={locked}
placeholder="0"
/>
</label>
</div>
</Collapse.Panel>
<Collapse.Panel
itemKey="knowledge-indexing"
header={<Text strong>{t('settingsBasic.indexConfig', null, '高级:索引分块与限流配置')}</Text>}
>
<div className="settings-vision-grid">
<div className="settings-field">
<Text id={strategyLabelId} type="tertiary" size="small">{t('settingsBasic.chunkStrategy', null, '分块策略')}</Text>
<Select
value={form.chunk_strategy}
onChange={value => update('chunk_strategy', value)}
optionList={[
{ value: '', label: t('settingsBasic.chunkStrategyMarkdownRecursive', null, 'Markdown 标题切分后递归(默认推荐)') },
{ value: 'markdown_then_recursive', label: t('settingsBasic.chunkStrategyMarkdownRecursive', null, 'Markdown 标题切分后递归') },
{ value: 'recursive', label: t('settingsBasic.chunkStrategyRecursive', null, '仅递归切分') }
]}
aria-labelledby={strategyLabelId}
disabled={locked}
style={{ width: '100%' }}
/>
</div>
{[
['chunk_size', 'chunkSize', '分块大小(Chunk Size)', '512'],
['chunk_overlap', 'chunkOverlap', '分块重叠(Chunk Overlap)', '50'],
['max_chunks_per_item', 'maxChunksPerItem', '单个知识项最大块数', '0'],
['batch_size', 'batchSize', '嵌入批大小', '64'],
['request_timeout_seconds', 'requestTimeoutSeconds', '嵌入 HTTP 超时(秒)', '120'],
['max_rpm', 'maxRpm', '每分钟最大请求数(Max RPM)', '0'],
['rate_limit_delay_ms', 'rateLimitDelay', '请求间隔延迟(毫秒)', '0'],
['max_retries', 'maxRetries', '最大重试次数', '3'],
['retry_delay_ms', 'retryDelay', '重试间隔(毫秒)', '1000']
].map(([field, key, fallback, placeholder]) => (
<label key={field} className="settings-field">
<Text type="tertiary" size="small">{t('settingsBasic.' + key, null, fallback)}</Text>
<Input
value={form[field]}
onChange={value => update(field, value)}
inputMode="numeric"
readOnly={locked}
placeholder={placeholder}
/>
</label>
))}
<label className="settings-field settings-field-wide">
<Text type="tertiary" size="small">{t('settingsBasic.subIndexes', null, '子索引标签(逗号分隔)')}</Text>
<Input
value={form.sub_indexes}
onChange={value => update('sub_indexes', value)}
readOnly={locked}
placeholder={t('settingsBasic.subIndexesPlaceholder', null, '例如: prod, knowledge')}
/>
</label>
<div className="settings-field">
<Text type="tertiary" size="small">{t('settingsBasic.preferSourceFile', null, '优先从磁盘源文件读取')}</Text>
<Switch
checked={form.prefer_source_file}
disabled={locked}
onChange={next => update('prefer_source_file', next)}
aria-label={t('settingsBasic.preferSourceFile', null, '优先从磁盘源文件读取')}
/>
</div>
</div>
</Collapse.Panel>
</Collapse>
</SectionCard>
)}
</>
);
}

View File

@ -1,5 +1,6 @@
/** 模型与工具:通道配置、模型连接探测和工具开关。 */
/** 模型与工具:通道配置、模型连接探测、独立视觉分析模型和工具开关。 */
import { useCallback } from 'react';
import { useSearchParams } from 'react-router-dom';
import { api } from '../../../lib/http';
import { useAuth } from '../../../lib/auth';
import { useT } from '../../../lib/i18n';
@ -7,12 +8,15 @@ import { useResource } from '../../../components/hooks';
import { ErrorBanner } from '../../../components/ui';
import { LoadingBlock, PermissionBanner } from './common';
import ProbePanel from './ProbePanel';
import VisionPanel from './VisionPanel';
import ToolsPanel from './ToolsPanel';
export default function ModelsSection() {
const t = useT();
const [params] = useSearchParams();
const { hasPermission } = useAuth();
const canRead = hasPermission('config:read');
const canWrite = hasPermission('config:write');
const loader = useCallback(({ signal } = {}) => api.get('/config', { include_tools: 0 }, { signal }), []);
const config = useResource(loader, [canRead], { skip: !canRead });
@ -26,11 +30,19 @@ export default function ModelsSection() {
<>
<ErrorBanner error={config.error} onRetry={config.reload} />
{config.data && (
<ProbePanel
config={config.data}
canWrite={hasPermission('config:write')}
reloadConfig={config.reload}
/>
<>
<ProbePanel
config={config.data}
canWrite={canWrite}
reloadConfig={config.reload}
/>
<VisionPanel
config={config.data}
canWrite={canWrite}
reloadConfig={config.reload}
focused={params.get('focus') === 'vision'}
/>
</>
)}
</>
)}

View File

@ -214,6 +214,7 @@ function ProbeOutput({ state, defaultWindow, defaultWindowSource, model, onModel
export default function ProbePanel({ config, canWrite, reloadConfig }) {
const t = useT();
const channelLabelId = useId();
const imageModeLabelId = useId();
const channels = config.ai?.channels || NO_CHANNELS;
const channelIds = Object.keys(channels);
const defaultId = config.ai?.default_channel;
@ -604,6 +605,28 @@ export default function ProbePanel({ config, canWrite, reloadConfig }) {
style={{ width: '100%' }}
/>
</label>
<div className="settings-field">
<Text id={imageModeLabelId} type="tertiary" size="small">图片输入能力</Text>
<Select
value={imageMode || ''}
onChange={value => update('image_input', value)}
disabled={locked}
aria-labelledby={imageModeLabelId}
optionList={[
{
value: '',
label: imageDefault === true
? '自动识别(支持图片)'
: imageDefault === false
? '自动识别(仅文本)'
: '自动识别'
},
{ value: 'enabled', label: '启用(该模型原生支持识图)' },
{ value: 'disabled', label: '禁用(仅文本 / 走下方独立视觉模型)' }
]}
style={{ width: '100%' }}
/>
</div>
{TOKEN_LIMITS.map(([field, key, fallback]) => {
const isWindow = field === 'context_window';
const showDefault = isWindow && useDefaultWindow;
@ -692,6 +715,13 @@ export default function ProbePanel({ config, canWrite, reloadConfig }) {
onModelChange={value => update('model', value)}
disabled={locked}
/>
{!imageEnabled && (
<div className="settings-image-fallback-tip">
<Hint>
当前通道未启用原生图片输入。若所选模型本身不支持识图,可开启下方「视觉分析(analyze_image)」由独立视觉模型代为识别截图与验证码;若模型通过中转接口实际支持识图,可将「图片输入能力」切换为「启用」或点击「测试图片」验证。
</Hint>
</div>
)}
<Collapse className="settings-audit-model">
<Collapse.Panel itemKey="audit-model" header={(

View File

@ -0,0 +1,517 @@
/**
* 独立视觉分析模型配置(vision 段 / analyze_image 工具):
* 当主对话模型不支持图片输入,或安全测试中需要识别本地截图、验证码文件时,
* 由独立 VL 模型识图并将文字结果返回给主模型。
*/
import { useEffect, useId, useRef, useState } from 'react';
import { Banner, Button, Collapse, Input, Select, Space, Switch, Tag, Typography } from '@douyinfe/semi-ui';
import { api } from '../../../lib/http';
import { useT } from '../../../lib/i18n';
import { modelChannelName } from '../../../lib/model-channel';
import { ErrorBanner, KeyValueList, SectionCard, toastSuccess } from '../../../components/ui';
import { Hint } from './common';
const { Text } = Typography;
const EMPTY_PROBE = { key: '', payload: null, error: null };
function normalizeProvider(raw) {
const value = String(raw || '').trim();
const lower = value.toLowerCase();
if (!lower) return '';
if (lower === 'openai' || lower === 'openai_compatible') return 'openai_compatible';
if (lower === 'claude' || lower === 'anthropic') return 'claude';
return value;
}
function visionValues(vision = {}) {
return {
enabled: Boolean(vision.enabled),
provider: normalizeProvider(vision.provider),
base_url: vision.base_url || '',
api_key: vision.api_key || '',
model: vision.model || '',
detail: vision.detail || '',
timeout_seconds: vision.timeout_seconds > 0 ? String(vision.timeout_seconds) : '',
max_image_bytes: vision.max_image_bytes > 0 ? String(vision.max_image_bytes) : '',
max_dimension: vision.max_dimension > 0 ? String(vision.max_dimension) : '',
jpeg_quality: vision.jpeg_quality > 0 ? String(vision.jpeg_quality) : '',
max_payload_bytes: vision.max_payload_bytes > 0 ? String(vision.max_payload_bytes) : '',
skip_preprocess_below_bytes: vision.skip_preprocess_below_bytes != null && vision.skip_preprocess_below_bytes !== 0
? String(vision.skip_preprocess_below_bytes)
: (vision.skip_preprocess_below_bytes === 0 && Object.hasOwn(vision, 'skip_preprocess_below_bytes') ? '0' : '')
};
}
function parseNonNegInt(raw) {
const trimmed = String(raw ?? '').trim();
if (!trimmed) return 0;
if (!/^\d+$/.test(trimmed)) return null;
const num = Number(trimmed);
return Number.isSafeInteger(num) && num >= 0 ? num : null;
}
function resolveDefaultChannel(config) {
const channels = config?.ai?.channels || {};
const defaultId = config?.ai?.default_channel || '';
if (defaultId && channels[defaultId]) {
const ch = channels[defaultId];
return {
channelId: defaultId,
displayName: modelChannelName(defaultId, ch),
openai: {
provider: ch.provider || 'openai_compatible',
base_url: ch.base_url || '',
api_key: ch.api_key || '',
model: ch.model || ''
}
};
}
const oa = config?.openai || {};
return {
channelId: '',
displayName: oa.model || '',
openai: {
provider: oa.provider || 'openai_compatible',
base_url: oa.base_url || '',
api_key: oa.api_key || '',
model: oa.model || ''
}
};
}
export default function VisionPanel({ config, canWrite, reloadConfig, focused }) {
const t = useT();
const cardRef = useRef(null);
const providerLabelId = useId();
const detailLabelId = useId();
const pickerLabelId = useId();
const baseline = visionValues(config.vision);
const baselineSig = JSON.stringify(baseline);
const [draft, setDraft] = useState({});
const form = { ...baseline, ...draft };
const dirty = Object.keys(draft).length > 0;
const [busy, setBusy] = useState('');
const [saving, setSaving] = useState(false);
const [saveError, setSaveError] = useState(null);
const [applyPending, setApplyPending] = useState(false);
const [probe, setProbe] = useState(EMPTY_PROBE);
useEffect(() => {
setDraft({});
setProbe(EMPTY_PROBE);
}, [baselineSig]);
useEffect(() => {
if (focused && cardRef.current) {
cardRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
}, [focused]);
const locked = !canWrite || saving || Boolean(busy);
const fallbackChannel = resolveDefaultChannel(config);
const effectiveProvider = form.provider || normalizeProvider(fallbackChannel.openai.provider) || 'openai_compatible';
const effectiveBaseUrl = form.base_url.trim() || fallbackChannel.openai.base_url || (
effectiveProvider === 'claude' ? 'https://api.anthropic.com' : 'https://api.openai.com/v1'
);
const providerOptions = [
{
value: '',
label: fallbackChannel.displayName
? `${t('settingsBasic.visionProviderReuseOpenAI', null, '默认 AI 通道(留空复用)')} · ${fallbackChannel.displayName}`
: t('settingsBasic.visionProviderReuseOpenAI', null, '默认 AI 通道(留空复用)')
},
{ value: 'openai_compatible', label: t('settingsProbe.compatible', null, '兼容 OpenAI 的接口') },
{ value: 'claude', label: t('settingsBasic.providerClaude', null, 'Claude(Anthropic Messages)') }
];
if (form.provider && !providerOptions.some(opt => opt.value === form.provider)) {
providerOptions.push({ value: form.provider, label: form.provider });
}
const detailOptions = [
{ value: '', label: '默认(low)' },
{ value: 'auto', label: 'auto(自动)' },
{ value: 'low', label: 'low(省流快速)' },
{ value: 'high', label: 'high(高清细节)' }
];
const update = (field, value) => {
if (probe.key !== 'list' || ['provider', 'base_url', 'api_key'].includes(field)) {
setProbe(EMPTY_PROBE);
}
if (!applyPending) setSaveError(null);
setDraft(current => {
const next = { ...current };
if (value === baseline[field]) delete next[field];
else next[field] = value;
return next;
});
};
const discard = () => {
setDraft({});
setProbe(EMPTY_PROBE);
if (!applyPending) setSaveError(null);
};
const buildVisionPayload = () => {
const numericFields = [
['timeout_seconds', t('settingsBasic.visionTimeout', null, '超时(秒)')],
['max_image_bytes', t('settingsBasic.visionMaxImageBytes', null, '原始文件上限(字节)')],
['max_dimension', t('settingsBasic.visionMaxDimension', null, '长边缩放像素')],
['jpeg_quality', t('settingsBasic.visionJpegQuality', null, 'JPEG 质量')],
['max_payload_bytes', t('settingsBasic.visionMaxPayloadBytes', null, '送 API 体积上限(字节)')],
['skip_preprocess_below_bytes', t('settingsBasic.visionSkipPreprocessBytes', null, '低于该字节可原图直传')]
];
const parsedNums = {};
for (const [key, labelText] of numericFields) {
const num = parseNonNegInt(form[key]);
if (num === null) {
throw new Error(t('settingsProbe.invalidLimit', { field: labelText }, `${labelText}请输入非负整数`));
}
parsedNums[key] = num;
}
if (parsedNums.jpeg_quality > 100) {
throw new Error('JPEG 质量需在 1 ~ 100 之间(留空或 0 使用默认 82)');
}
return {
enabled: Boolean(form.enabled),
provider: form.provider.trim(),
base_url: form.base_url.trim(),
api_key: form.api_key,
model: form.model.trim(),
detail: form.detail.trim(),
...parsedNums
};
};
const applyConfig = async message => {
try {
await api.post('/config/apply');
setApplyPending(false);
toastSuccess(message);
} catch (error) {
setApplyPending(true);
setSaveError(error);
}
};
const save = async () => {
if (locked || !dirty) return;
setSaveError(null);
if (form.enabled && !form.model.trim()) {
setSaveError(new Error(t('settingsBasic.visionModelRequired', null, '启用视觉分析时请填写视觉模型名称')));
return;
}
let visionPayload;
try {
visionPayload = buildVisionPayload();
} catch (error) {
setSaveError(error);
return;
}
setSaving(true);
try {
await api.put('/config', { vision: visionPayload });
setDraft({});
await applyConfig(t('settingsProbe.visionSaved', null, '视觉模型配置已保存并应用'));
await reloadConfig({ silent: true });
} catch (error) {
setSaveError(error);
} finally {
setSaving(false);
}
};
const retryApply = async () => {
if (locked || !applyPending) return;
setSaving(true);
setSaveError(null);
try {
await applyConfig(t('settings.apply.applySuccess', null, '配置已成功应用'));
} finally {
setSaving(false);
}
};
const testVision = async () => {
if (locked) return;
if (!form.model.trim()) {
setProbe({
key: 'vision',
payload: null,
error: new Error(t('settingsBasic.visionTestFillRequired', null, '请填写视觉模型,并确保 API Key 可用(可复用 OpenAI)'))
});
return;
}
setBusy('vision');
setProbe(EMPTY_PROBE);
try {
const visionPayload = buildVisionPayload();
const payload = await api.post('/config/test-vision', {
channel_id: fallbackChannel.channelId || undefined,
vision: visionPayload,
openai: fallbackChannel.openai
});
setProbe({ key: 'vision', payload, error: null });
} catch (error) {
setProbe({ key: 'vision', payload: null, error });
} finally {
setBusy('');
}
};
const fetchModels = async () => {
if (locked) return;
setBusy('list');
setProbe(EMPTY_PROBE);
const usingOwnKey = Boolean(form.api_key);
try {
const payload = await api.post('/config/list-models', {
provider: effectiveProvider,
credential_scope: usingOwnKey ? 'vision' : (fallbackChannel.channelId ? undefined : 'openai'),
channel_id: !usingOwnKey && fallbackChannel.channelId ? fallbackChannel.channelId : undefined,
base_url: effectiveBaseUrl,
api_key: usingOwnKey ? form.api_key : fallbackChannel.openai.api_key
});
setProbe({ key: 'list', payload, error: null });
} catch (error) {
setProbe({ key: 'list', payload: null, error });
} finally {
setBusy('');
}
};
const statusTag = form.enabled
? (form.model.trim()
? <Tag color="green" size="small">{`${t('common.enabled', null, '已启用')} · ${form.model.trim()}`}</Tag>
: <Tag color="amber" size="small">待填写模型</Tag>)
: <Tag color="grey" size="small">{t('common.disabled', null, '未启用')}</Tag>;
const listedModels = probe.key === 'list' && Array.isArray(probe.payload?.models) ? probe.payload.models : [];
return (
<div id="settings-vision-panel" ref={cardRef} className={focused ? 'settings-focus-ring' : undefined}>
<SectionCard
title={(
<Space wrap spacing={8}>
<span>{t('settingsBasic.visionConfig', null, '视觉分析(analyze_image)')}</span>
{statusTag}
{dirty && <Tag color="amber" size="small">{t('settings.unsaved', null, '有未保存修改')}</Tag>}
</Space>
)}
description="当主对话模型不支持图片识别(如纯文本推理模型),或安全测试中需要识别本地截图、验证码图片时,开启后将挂载 analyze_image 工具,由独立视觉模型代为识图并仅向主模型返回文字摘要。"
className="settings-vision-panel"
extra={canWrite ? (
<Space wrap>
{dirty && (
<Button disabled={saving || Boolean(busy)} onClick={discard}>
{t('toolGuard.reset', null, '撤销修改')}
</Button>
)}
<Button
theme="solid"
type="primary"
loading={saving}
disabled={!dirty || Boolean(busy)}
onClick={save}
>
保存视觉模型
</Button>
</Space>
) : (
<Tag color="grey" size="small">{t('settingsProbe.channelReadOnly', null, '只读')}</Tag>
)}
>
<div className="settings-switch-row">
<Switch
checked={form.enabled}
disabled={locked}
onChange={next => update('enabled', next)}
aria-label={t('settingsBasic.visionEnabled', null, '启用视觉分析工具 analyze_image')}
/>
<div className="settings-switch-copy">
<Text strong>{t('settingsBasic.visionEnabled', null, '启用视觉分析工具 analyze_image')}</Text>
<Hint>{t('settingsBasic.visionEnabledHint', null, '启用后注册 MCP 工具;图片仅在单次 VL 调用中出现,Agent 上下文只保留文字摘要。保存并应用后生效。')}</Hint>
</div>
</div>
<div className="settings-vision-grid">
<label className="settings-field">
<Text type="tertiary" size="small">{t('settingsBasic.visionModel', null, '视觉模型')}</Text>
<Input
value={form.model}
onChange={value => update('model', value)}
readOnly={locked}
placeholder={t('settingsBasic.visionModelPlaceholder', null, 'qwen-vl-max')}
/>
</label>
<div className="settings-field">
<Text id={providerLabelId} type="tertiary" size="small">{t('settingsBasic.apiProvider', null, 'API 提供商')}</Text>
<Select
value={form.provider}
onChange={value => update('provider', value)}
optionList={providerOptions}
aria-labelledby={providerLabelId}
disabled={locked}
style={{ width: '100%' }}
/>
</div>
<label className="settings-field settings-field-wide">
<Text type="tertiary" size="small">{t('settingsBasic.baseUrl', null, 'API 地址')}</Text>
<Input
value={form.base_url}
onChange={value => update('base_url', value)}
readOnly={locked}
placeholder={fallbackChannel.openai.base_url
? `留空复用默认通道(${fallbackChannel.openai.base_url})`
: t('settingsBasic.visionBaseUrlPlaceholder', null, '留空则复用 OpenAI Base URL')}
/>
</label>
<label className="settings-field">
<Text type="tertiary" size="small">{t('settingsBasic.apiKey', null, 'API 密钥')}</Text>
<Input
mode="password"
autoComplete="new-password"
value={form.api_key}
onChange={value => update('api_key', value)}
readOnly={locked}
placeholder={t('settingsBasic.visionApiKeyPlaceholder', null, '留空则复用 OpenAI API Key')}
/>
</label>
</div>
{(applyPending || saveError) && (
<div className="settings-channel-notices">
{applyPending && (
<Banner type="warning" bordered closeIcon={null} description={(
<Space wrap>
<span>视觉模型配置已写入,但应用失败。</span>
<Button size="small" disabled={locked} onClick={retryApply}>
{t('settingsProbe.retryApply', null, '重试应用')}
</Button>
</Space>
)} />
)}
<ErrorBanner error={saveError} />
</div>
)}
<Space wrap className="settings-probe-actions">
<Button
loading={busy === 'vision'}
disabled={!canWrite || saving || (Boolean(busy) && busy !== 'vision')}
onClick={testVision}
>
{t('settingsProbe.testVision', null, '测试视觉模型')}
</Button>
<Button
loading={busy === 'list'}
disabled={!canWrite || saving || (Boolean(busy) && busy !== 'list')}
onClick={fetchModels}
>
{t('settingsBasic.modelsList', null, '获取模型列表')}
</Button>
</Space>
{probe.error && <div className="settings-probe-result"><ErrorBanner error={probe.error} /></div>}
{probe.key === 'vision' && probe.payload && (
<div className="settings-probe-result">
{probe.payload.success ? (
<KeyValueList
columns={3}
items={[
{ label: t('settingsProbe.result', null, '测试结果'), value: <Tag color="green">{t('settingsBasic.testSuccess', null, '连接成功')}</Tag> },
{ label: t('settingsBasic.visionModel', null, '视觉模型'), value: probe.payload.model || form.model || '—' },
{
label: t('settingsProbe.latency', null, '响应耗时'),
value: probe.payload.latency_ms != null
? t('settingsProbe.milliseconds', { value: probe.payload.latency_ms }, `${probe.payload.latency_ms} 毫秒`)
: '—'
}
]}
/>
) : (
<Banner type="danger" bordered closeIcon={null} description={probe.payload.error || t('settingsBasic.testFailed', null, '连接失败')} />
)}
</div>
)}
{probe.key === 'list' && probe.payload && (
<div className="settings-probe-result">
{probe.payload.success ? (
<Space wrap spacing={8}>
<Text>
{t('settingsBasic.modelsListSuccess', { count: probe.payload.count ?? listedModels.length }, `已获取 ${probe.payload.count ?? listedModels.length} 个模型`)}
</Text>
<span id={pickerLabelId} hidden>{t('settingsBasic.modelsListSelectPlaceholder', null, '请选择视觉模型')}</span>
{listedModels.length > 0 && (
<Select
filter
aria-labelledby={pickerLabelId}
placeholder={t('settingsBasic.modelsListSelectPlaceholder', null, '请选择模型')}
value={listedModels.includes(form.model) ? form.model : undefined}
optionList={listedModels.map(id => ({ value: id, label: id }))}
onChange={value => update('model', value)}
disabled={locked}
className="settings-model-picker"
/>
)}
</Space>
) : (
<Banner
type={probe.payload.supported === false ? 'info' : 'danger'}
bordered
closeIcon={null}
description={probe.payload.error || t('settingsBasic.modelsListFailed', null, '获取模型列表失败')}
/>
)}
</div>
)}
<Collapse className="settings-audit-model">
<Collapse.Panel
itemKey="vision-advanced"
header={<Text strong>{t('settingsBasic.visionAdvanced', null, '高级:预处理与限制')}</Text>}
>
<div className="settings-vision-grid">
<div className="settings-field">
<Text id={detailLabelId} type="tertiary" size="small">{t('settingsBasic.visionDetail', null, '图片精度(Detail)')}</Text>
<Select
value={form.detail}
onChange={value => update('detail', value)}
optionList={detailOptions}
aria-labelledby={detailLabelId}
disabled={locked}
style={{ width: '100%' }}
/>
</div>
{[
['timeout_seconds', 'visionTimeout', '超时(秒)', '60'],
['max_image_bytes', 'visionMaxImageBytes', '原始文件上限(字节)', '5242880'],
['max_dimension', 'visionMaxDimension', '长边缩放像素', '2048'],
['jpeg_quality', 'visionJpegQuality', 'JPEG 质量', '82'],
['max_payload_bytes', 'visionMaxPayloadBytes', '送 API 体积上限(字节)', '524288'],
['skip_preprocess_below_bytes', 'visionSkipPreprocessBytes', '低于该字节可原图直传', '2097152']
].map(([field, key, fallback, placeholder]) => (
<label key={field} className="settings-field">
<Text type="tertiary" size="small">{t('settingsBasic.' + key, null, fallback)}</Text>
<Input
value={form[field]}
onChange={value => update(field, value)}
inputMode="numeric"
readOnly={locked}
placeholder={placeholder}
/>
</label>
))}
</div>
<Hint>{t('settingsBasic.visionSkipPreprocessHint', null, '0 表示始终 JPEG 压缩;需同时满足长边与 payload 限制。留空使用系统默认值。')}</Hint>
</Collapse.Panel>
</Collapse>
</SectionCard>
</div>
);
}

View File

@ -34,14 +34,16 @@ test.describe('model probe localization', () => {
await page.goto('/static/app/#/settings?section=models');
const main = await ready(page);
const probe = main.locator('.cs-section-card').filter({ has: page.locator('.settings-probe-form') });
const vision = main.locator('.settings-vision-panel');
await expect(probe.getByLabel('API 地址', { exact: true }).first()).toHaveValue('https://example.test/models');
await expect(probe.getByText('最大输出令牌数', { exact: true })).toBeVisible();
await probe.getByRole('button', { name: '测试连接', exact: true }).click();
await probe.getByRole('button', { name: '测试视觉模型', exact: true }).click();
await vision.getByRole('button', { name: '测试视觉模型', exact: true }).click();
await expect(probe.getByRole('cell', { name: /响应耗时.*961 毫秒/ })).toBeVisible();
await expect(probe.getByText('连接成功', { exact: true })).toHaveCount(2);
await expect(probe.getByText('连接成功', { exact: true })).toHaveCount(1);
await expect(vision.getByText('连接成功', { exact: true })).toHaveCount(1);
await expect(probe.getByText('961 毫秒', { exact: true })).toBeVisible();
await expect(probe.getByText('994 毫秒', { exact: true })).toBeVisible();
await expect(vision.getByText('994 毫秒', { exact: true })).toBeVisible();
await expect(probe.getByText('未检测到上下文窗口,请手动填写', { exact: true })).toBeVisible();
await expect(probe.getByText(/context_warnings|context_window_unknown|latency_ms/)).toHaveCount(0);
expect(mockApi.calls('POST', '/api/config/test-openai')[0].body).toMatchObject({

View File

@ -0,0 +1,193 @@
import { test, expect, ready, visit, UI_PERMISSIONS } from './fixtures.mjs';
test.describe('vision and knowledge frontend configuration', () => {
test.use({ appPermissions: [...UI_PERMISSIONS, 'config:write', 'knowledge:write'] });
test('enables vision and knowledge from GUI without editing YAML and updates overview', async ({ page, mockApi }) => {
const state = {
ai: {
default_channel: 'ds',
channels: {
ds: {
name: 'ds',
provider: 'openai_compatible',
base_url: 'https://api.deepseek.com/v1',
model: 'deepseek-chat',
api_key: '********'
}
}
},
vision: { enabled: false, model: '', base_url: '', api_key: '' },
knowledge: {
enabled: false,
base_path: 'knowledge_base',
embedding: { provider: 'openai', model: 'text-embedding-v4', base_url: '', api_key: '' },
retrieval: { top_k: 5, similarity_threshold: 0.4, multi_query: { max_queries: 4 }, rerank: {}, post_retrieve: {} },
indexing: { chunk_size: 512, chunk_overlap: 50 }
},
tools: []
};
mockApi.respond('GET', '/api/config', () => ({ json: state }));
mockApi.respond('PUT', '/api/config', ({ body }) => {
if (body.vision) {
state.vision = {
...state.vision,
...body.vision,
api_key: body.vision.api_key ? '********' : ''
};
}
if (body.knowledge) {
state.knowledge = {
...state.knowledge,
...body.knowledge,
embedding: {
...state.knowledge.embedding,
...body.knowledge.embedding,
api_key: body.knowledge.embedding?.api_key ? '********' : ''
}
};
}
return { json: {} };
});
mockApi.respond('POST', '/api/config/apply', { json: {} });
mockApi.respond('POST', '/api/config/test-vision', { json: {
success: true,
model: 'qwen-vl-max',
latency_ms: 185
} });
mockApi.respond('POST', '/api/config/test-embedding', { json: {
success: true,
model: 'text-embedding-v4',
dimensions: 1024,
latency_ms: 92
} });
// 1. Start on Basic Settings overview and jump to Vision config
const main = await visit(page, 'settings?section=basic');
const overview = main.locator('.cs-section-card').first();
await expect(overview.getByRole('cell', { name: /视觉模型.*未启用/ })).toBeVisible();
await expect(overview.getByRole('cell', { name: /知识库设置.*未启用/ })).toBeVisible();
await overview.getByRole('cell', { name: /视觉模型/ }).getByRole('button', { name: '去启用' }).click();
await expect(page).toHaveURL(/#\/settings\?section=models&focus=vision$/);
const vision = main.locator('.settings-vision-panel');
await vision.getByRole('switch', { name: '启用视觉分析工具 analyze_image' }).click();
await vision.getByLabel('视觉模型', { exact: true }).fill('qwen-vl-max');
await vision.getByLabel('API 地址', { exact: true }).fill('https://dashscope.aliyuncs.com/compatible-mode/v1');
await vision.getByLabel('API 密钥', { exact: true }).fill('sk-vision-demo');
await vision.getByRole('button', { name: '测试视觉模型', exact: true }).click();
await expect(vision.getByText('185 毫秒', { exact: true })).toBeVisible();
await vision.getByRole('button', { name: '保存视觉模型', exact: true }).click();
await expect(vision.getByRole('button', { name: '保存视觉模型', exact: true })).toBeDisabled();
expect(mockApi.calls('PUT', '/api/config').at(-1).body.vision).toMatchObject({
enabled: true,
model: 'qwen-vl-max',
base_url: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
api_key: 'sk-vision-demo'
});
// 2. Switch to Knowledge tab, verify DeepSeek notice, probe embedding, and save
await page.getByRole('tab', { name: '知识库' }).click();
await expect(page).toHaveURL(/#\/settings\?section=knowledge$/);
const knowledge = main.locator('.settings-knowledge-panel');
await expect(knowledge.getByText(/DeepSeek 官方或 Claude 接口/)).toBeVisible();
await knowledge.getByRole('switch', { name: '启用知识检索功能' }).click();
await knowledge.getByLabel('API 地址', { exact: true }).fill('https://dashscope.aliyuncs.com/compatible-mode/v1');
await knowledge.getByLabel('API 密钥', { exact: true }).fill('sk-embed-demo');
await knowledge.getByRole('button', { name: '测试嵌入模型', exact: true }).click();
await expect(knowledge.getByText('1024 维', { exact: true })).toBeVisible();
await expect(knowledge.getByText('92 毫秒', { exact: true })).toBeVisible();
await knowledge.getByRole('button', { name: '保存并应用', exact: true }).click();
await expect(knowledge.getByRole('button', { name: '保存并应用', exact: true })).toBeDisabled();
expect(mockApi.calls('PUT', '/api/config').at(-1).body.knowledge).toMatchObject({
enabled: true,
base_path: 'knowledge_base',
embedding: {
provider: 'openai',
model: 'text-embedding-v4',
base_url: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
api_key: 'sk-embed-demo'
}
});
// 3. Return to Basic Settings and verify overview reflects both enabled states
await page.getByRole('tab', { name: '基本设置' }).click();
await expect(overview.getByRole('cell', { name: /视觉模型.*qwen-vl-max/ })).toBeVisible();
await expect(overview.getByRole('cell', { name: /知识库设置.*已启用/ })).toBeVisible();
// 4. Verify mobile layout has no horizontal overflow
await page.setViewportSize({ width: 390, height: 844 });
await page.goto('/static/app/#/settings?section=knowledge');
await ready(page);
expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(391);
});
test('knowledge management banner guides users to settings when knowledge is disabled', async ({ page, mockApi }) => {
mockApi.respond('GET', '/api/knowledge/items', { json: {
items: [],
enabled: false,
message: '知识库功能未启用,请前往系统设置启用知识检索功能'
} });
mockApi.respond('GET', '/api/knowledge/index-status', { json: {
enabled: false,
total_items: 0,
indexed_items: 0
} });
const main = await visit(page, 'knowledge-management');
await expect(main.getByText('知识库功能未启用,请前往系统设置启用知识检索功能')).toBeVisible();
await expect(main.getByRole('button', { name: '构建索引', exact: true })).toBeDisabled();
await main.getByRole('button', { name: '前往启用知识库', exact: true }).click();
await expect(page).toHaveURL(/#\/settings\?section=knowledge$/);
});
test('chat composer offers vision model entry when current channel lacks native image support', async ({ page, mockApi }) => {
mockApi.respond('GET', '/api/config', { json: {
ai: {
default_channel: 'opus-relay',
channels: {
'opus-relay': {
name: 'opus4.6',
provider: 'claude',
base_url: 'https://relay.example.test',
model: 'claude-opus-4-6',
api_key: '********'
}
}
},
vision: { enabled: false, model: '' },
tools: []
} });
mockApi.respond('POST', '/api/chat-uploads', { json: { absolutePath: '/tmp/captcha.png' } });
const main = await visit(page, 'chat');
const composer = main.locator('.chat-composer');
// Open model popover and check vision shortcut
await composer.locator('.chat-composer-model').click();
const popover = page.locator('.chat-reasoning-picker');
await expect(popover.getByText('当前模型不支持识图?', { exact: true })).toBeVisible();
await expect(popover.getByRole('button', { name: '配置视觉模型', exact: true })).toBeVisible();
// Upload an image attachment and verify inline vision guidance appears
const chooserPending = page.waitForEvent('filechooser');
await composer.getByRole('button', { name: '附件', exact: true }).click();
const chooser = await chooserPending;
await chooser.setFiles({
name: 'captcha.png',
mimeType: 'image/png',
buffer: Buffer.from('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=', 'base64')
});
const tip = composer.locator('.chat-image-vision-tip');
await expect(tip).toBeVisible();
await tip.getByRole('button', { name: '去开启视觉模型', exact: true }).click();
await expect(page).toHaveURL(/#\/settings\?section=models&focus=vision$/);
});
});

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-3n4RPEnj.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-CVkIID9D.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{I as e,L as t}from"./index-3n4RPEnj.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-CVkIID9D.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};

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-3n4RPEnj.js";import"./c2-shared-BYx1I4ct.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-CVkIID9D.js";import"./c2-shared-CliHH6g8.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};

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

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-3n4RPEnj.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-CVkIID9D.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-3n4RPEnj.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-CVkIID9D.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};

View File

@ -0,0 +1 @@
.settings-page{flex-direction:column;min-width:0;display:flex}.settings-tabs .semi-tabs-content{min-width:0;padding-top:0}.settings-tabs .semi-tabs-pane{min-width:0}.settings-tabs .semi-tabs-bar-left{flex:0 0 156px;margin-inline-end:24px}.settings-tabs .semi-tabs-bar-left .semi-tabs-tab{text-align:start;border-radius:8px;margin-bottom:4px;padding:12px 16px;font-size:13px}.settings-tabs .semi-tabs-bar-left .semi-tabs-tab-active{background:var(--semi-color-primary-light-default)}.settings-tabs .semi-tabs-bar-top{margin-bottom:16px}.settings-tabs .semi-tabs-bar-top .semi-tabs-tab{font-size:13px}.settings-loading-block{padding:18px 4px}.settings-token-filters{flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:14px;display:flex}.settings-token-conversation{width:280px;max-width:100%}.settings-hint{color:var(--semi-color-text-2);font-size:12px;line-height:1.6;display:inline-block}.settings-mono{word-break:break-all;font-family:SFMono-Regular,Consolas,Liberation Mono,monospace;font-size:12px}.settings-yaml-toolbar{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:8px;margin-bottom:10px;display:flex}.settings-yaml-input .semi-input-textarea{-moz-tab-size:2;tab-size:2;min-height:420px;font-family:SFMono-Regular,Consolas,Liberation Mono,monospace;font-size:12.5px;line-height:1.6}.settings-yaml-notice{margin-bottom:12px}.settings-schema{flex-direction:column;gap:14px;display:flex}.settings-schema-table{border-collapse:collapse;width:100%;font-size:12.5px}.settings-schema-table th,.settings-schema-table td{border-bottom:1px solid var(--semi-color-border);text-align:left;vertical-align:top;padding:8px 10px}.settings-schema-table th{color:var(--semi-color-text-2);font-weight:600}.settings-probe-form,.settings-vision-grid{grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px 16px;display:grid}.settings-field{flex-direction:column;gap:6px;min-width:0;display:flex}.settings-field-wide{grid-column:span 2}.settings-probe-actions{margin-top:14px}.settings-channel-panel .semi-card-header-wrapper,.settings-vision-panel .semi-card-header-wrapper,.settings-knowledge-panel .semi-card-header-wrapper{align-items:center;gap:8px}.settings-channel-notices{gap:8px;margin-top:14px;display:grid}.settings-probe-result{flex-direction:column;gap:10px;margin-top:12px;display:flex}.settings-model-picker{width:min(280px,60vw)}.settings-audit-model{border-top:1px solid var(--semi-color-border);margin-top:18px}.settings-probe-card{flex-direction:column;gap:8px;min-width:0;display:flex}.settings-probe-inline{grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;display:grid}.settings-switch-row{border:1px solid var(--semi-color-border);background:var(--semi-color-fill-0);border-radius:8px;align-items:flex-start;gap:12px;margin-bottom:14px;padding:12px 14px;display:flex}.settings-switch-copy{flex-direction:column;gap:2px;min-width:0;display:flex}.settings-subsection{border-top:1px solid var(--semi-color-border);flex-direction:column;gap:10px;margin-top:18px;padding-top:16px;display:flex}.settings-subsection-title{font-size:14px}.settings-image-fallback-tip{margin-top:10px}.settings-focus-ring .cs-section-card{box-shadow:0 0 0 2px var(--semi-color-primary)}.settings-overview-inline{flex-wrap:wrap;align-items:center;gap:6px;display:inline-flex}.settings-overview-link.semi-button{height:22px;padding:0 6px;font-size:12px}.settings-disk{flex-direction:column;gap:6px;max-width:720px;margin-bottom:16px;display:flex}.settings-policy-grid{grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:12px 16px;margin-bottom:10px;display:grid}.settings-incoming{margin-top:12px}.settings-incoming ul{margin:6px 0 0;padding-left:18px;font-size:12.5px;line-height:1.8}.settings-update-steps{max-height:360px;margin-top:16px;padding-right:4px;overflow:auto}.settings-audit-filters{flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:12px;display:flex}.settings-audit-banner{margin-bottom:12px}.settings-audit-detail{flex-direction:column;gap:16px;display:flex}.settings-audit-message-block{border:1px solid var(--semi-color-border);background:var(--semi-color-fill-0);word-break:break-word;border-radius:8px;flex-direction:column;gap:4px;padding:10px 12px;display:flex}.settings-appearance-status{margin-top:12px}@media (max-width:900px){.settings-field-wide{grid-column:span 1}.settings-yaml-input .semi-input-textarea{min-height:300px}}@media (max-width:480px){.settings-channel-panel .semi-card-header-wrapper,.settings-vision-panel .semi-card-header-wrapper,.settings-knowledge-panel .semi-card-header-wrapper{flex-direction:column-reverse;align-items:stretch}.settings-channel-panel .semi-card-header-wrapper-title,.settings-vision-panel .semi-card-header-wrapper-title,.settings-knowledge-panel .semi-card-header-wrapper-title{margin-inline-start:0;margin-inline-end:0}}.settings-update-source-form{flex-direction:column;gap:8px;max-width:760px;display:flex}

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 +0,0 @@
.settings-page{flex-direction:column;min-width:0;display:flex}.settings-tabs .semi-tabs-content{min-width:0;padding-top:0}.settings-tabs .semi-tabs-pane{min-width:0}.settings-tabs .semi-tabs-bar-left{flex:0 0 156px;margin-inline-end:24px}.settings-tabs .semi-tabs-bar-left .semi-tabs-tab{text-align:start;border-radius:8px;margin-bottom:4px;padding:12px 16px;font-size:13px}.settings-tabs .semi-tabs-bar-left .semi-tabs-tab-active{background:var(--semi-color-primary-light-default)}.settings-tabs .semi-tabs-bar-top{margin-bottom:16px}.settings-tabs .semi-tabs-bar-top .semi-tabs-tab{font-size:13px}.settings-loading-block{padding:18px 4px}.settings-token-filters{flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:14px;display:flex}.settings-token-conversation{width:280px;max-width:100%}.settings-hint{color:var(--semi-color-text-2);font-size:12px;line-height:1.6;display:inline-block}.settings-mono{word-break:break-all;font-family:SFMono-Regular,Consolas,Liberation Mono,monospace;font-size:12px}.settings-yaml-toolbar{flex-wrap:wrap;justify-content:space-between;align-items:center;gap:8px;margin-bottom:10px;display:flex}.settings-yaml-input .semi-input-textarea{-moz-tab-size:2;tab-size:2;min-height:420px;font-family:SFMono-Regular,Consolas,Liberation Mono,monospace;font-size:12.5px;line-height:1.6}.settings-yaml-notice{margin-bottom:12px}.settings-schema{flex-direction:column;gap:14px;display:flex}.settings-schema-table{border-collapse:collapse;width:100%;font-size:12.5px}.settings-schema-table th,.settings-schema-table td{border-bottom:1px solid var(--semi-color-border);text-align:left;vertical-align:top;padding:8px 10px}.settings-schema-table th{color:var(--semi-color-text-2);font-weight:600}.settings-probe-form{grid-template-columns:repeat(auto-fit,minmax(200px,1fr));gap:12px 16px;display:grid}.settings-field{flex-direction:column;gap:6px;min-width:0;display:flex}.settings-field-wide{grid-column:span 2}.settings-probe-actions{margin-top:14px}.settings-channel-panel .semi-card-header-wrapper{align-items:center;gap:8px}.settings-channel-notices{gap:8px;margin-top:14px;display:grid}.settings-probe-result{flex-direction:column;gap:10px;margin-top:12px;display:flex}.settings-model-picker{width:min(280px,60vw)}.settings-audit-model{border-top:1px solid var(--semi-color-border);margin-top:18px}.settings-probe-card{flex-direction:column;gap:8px;min-width:0;display:flex}.settings-probe-inline{grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:8px;display:grid}.settings-disk{flex-direction:column;gap:6px;max-width:720px;margin-bottom:16px;display:flex}.settings-policy-grid{grid-template-columns:repeat(auto-fit,minmax(190px,1fr));gap:12px 16px;margin-bottom:10px;display:grid}.settings-incoming{margin-top:12px}.settings-incoming ul{margin:6px 0 0;padding-left:18px;font-size:12.5px;line-height:1.8}.settings-update-steps{max-height:360px;margin-top:16px;padding-right:4px;overflow:auto}.settings-audit-filters{flex-wrap:wrap;align-items:center;gap:8px;margin-bottom:12px;display:flex}.settings-audit-banner{margin-bottom:12px}.settings-audit-detail{flex-direction:column;gap:16px;display:flex}.settings-audit-message-block{border:1px solid var(--semi-color-border);background:var(--semi-color-fill-0);word-break:break-word;border-radius:8px;flex-direction:column;gap:4px;padding:10px 12px;display:flex}.settings-appearance-status{margin-top:12px}@media (max-width:900px){.settings-field-wide{grid-column:span 1}.settings-yaml-input .semi-input-textarea{min-height:300px}}@media (max-width:480px){.settings-channel-panel .semi-card-header-wrapper{flex-direction:column-reverse;align-items:stretch}.settings-channel-panel .semi-card-header-wrapper-title{margin-inline-start:0;margin-inline-end:0}}.settings-update-source-form{flex-direction:column;gap:8px;max-width:760px;display:flex}

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-3n4RPEnj.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-CVkIID9D.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-3n4RPEnj.js"></script>
<script type="module" crossorigin src="/static/app/assets/index-CVkIID9D.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">