feat(update): support selecting and switching target branch in one-click update

This commit is contained in:
Sycun 2026-11-28 20:25:07 +08:00
parent 43aa4fe1eb
commit 4e12a49f09
51 changed files with 537 additions and 136 deletions

View File

@ -634,7 +634,8 @@ func New(cfg *config.Config, log *logger.Logger, configPath, updateActivation st
})
updateHandler := handler.NewUpdateHandler(configDir, log.Logger, auditSvc,
app.updateRestart(configDir), updateActivation, configHandler.UpdateSource, configHandler.SetUpdateSource)
app.updateRestart(configDir), updateActivation, configHandler.UpdateSource, configHandler.SetUpdateSource).
WithUpdateConfig(configHandler.GetUpdateConfig, configHandler.SetUpdateConfig)
// 设置路由(使用 App 实例以便动态获取 handler)
setupRoutes(
@ -1213,6 +1214,7 @@ func setupRoutes(
// 系统更新(保持本安装自身源码最新:查看、检查、应用、进度、回滚、接入、更新源)
protected.GET("/system/update", updateHandler.GetStatus)
protected.GET("/system/update/branches", updateHandler.Branches)
protected.GET("/system/update/job", updateHandler.Job)
protected.POST("/system/update/check", updateHandler.Check)
protected.POST("/system/update/apply", updateHandler.Apply)

View File

@ -56,11 +56,13 @@ type Config struct {
Update UpdateConfig `yaml:"update,omitempty" json:"update,omitempty"`
}
// UpdateConfig 一键更新的更新源(可选):一个仓库地址,更新跟随该仓库的默认分支。
// 留空即官方仓库(internal/update.DefaultRepoURL),跟随镜像或自己的二开只需改这一处。
// UpdateConfig 一键更新的更新源(可选):仓库地址与目标分支。
// 仓库留空即官方仓库(internal/update.DefaultRepoURL);分支留空即跟随该仓库的默认分支。
type UpdateConfig struct {
// Repo 更新源仓库地址(https/http/ssh/git/file:// 或本机绝对路径);留空 = 官方仓库。
Repo string `yaml:"repo,omitempty" json:"repo,omitempty"`
// Branch 目标分支名(如 main、feat/plugin-capability-platform);留空 = 跟随仓库默认分支。
Branch string `yaml:"branch,omitempty" json:"branch,omitempty"`
}
type EnsureLocalConfigResult struct {

View File

@ -2254,10 +2254,18 @@ func (h *ConfigHandler) ApplyConfig(c *gin.Context) {
// SetUpdateSource 记录一键更新的更新源(单个仓库地址;空 = 回到官方仓库)。
// 走与其他设置相同的写入路径:备份旧文件、按 YAML 文档只改 update 段、原子落盘。
func (h *ConfigHandler) SetUpdateSource(repo string) error {
return h.SetUpdateConfig(config.UpdateConfig{Repo: repo})
}
// SetUpdateConfig 记录一键更新的仓库地址和目标分支(留空分别回到官方仓库/默认分支)。
func (h *ConfigHandler) SetUpdateConfig(cfg config.UpdateConfig) error {
h.mu.Lock()
defer h.mu.Unlock()
previous := h.config.Update
h.config.Update = config.UpdateConfig{Repo: strings.TrimSpace(repo)}
h.config.Update = config.UpdateConfig{
Repo: strings.TrimSpace(cfg.Repo),
Branch: strings.TrimSpace(cfg.Branch),
}
if err := h.saveConfig(); err != nil {
h.config.Update = previous
return err
@ -2272,6 +2280,13 @@ func (h *ConfigHandler) UpdateSource() string {
return h.config.Update.Repo
}
// GetUpdateConfig 读当前配置的更新源仓库和目标分支。
func (h *ConfigHandler) GetUpdateConfig() config.UpdateConfig {
h.mu.RLock()
defer h.mu.RUnlock()
return h.config.Update
}
// saveConfig 保存配置到文件
func (h *ConfigHandler) saveConfig() error {
configFileMu.Lock()
@ -2430,18 +2445,27 @@ func updateMCPConfig(doc *yaml.Node, cfg config.MCPConfig) {
setIntInMap(mcpNode, "port", cfg.Port)
}
// updateUpdateSourceConfig 写入一键更新的更新源(update 段的单个 repo 字段)。
// 留空时把整段删掉,而不是留下一个空的 update: 块——"没有配置"应当就是文件里没有这一段,
// 运行时按官方仓库处理。
// updateUpdateSourceConfig 写入一键更新的更新源(update 段的 repo 与可选 branch 字段)。
// 两项均留空时把整段删掉,运行时按官方仓库默认分支处理。
func updateUpdateSourceConfig(doc *yaml.Node, cfg config.UpdateConfig) {
root := doc.Content[0]
repo := strings.TrimSpace(cfg.Repo)
if repo == "" {
branch := strings.TrimSpace(cfg.Branch)
if repo == "" && branch == "" {
removeKeyFromMap(root, "update")
return
}
node := ensureMap(root, "update")
setStringInMap(node, "repo", repo)
if repo != "" {
setStringInMap(node, "repo", repo)
} else {
removeKeyFromMap(node, "repo")
}
if branch != "" {
setStringInMap(node, "branch", branch)
} else {
removeKeyFromMap(node, "branch")
}
}
func updateVisionConfig(doc *yaml.Node, cfg config.VisionConfig) {

View File

@ -3,6 +3,7 @@ package handler
import (
"context"
"cyberstrike-ai/internal/audit"
"cyberstrike-ai/internal/config"
"cyberstrike-ai/internal/update"
"fmt"
"net/http"
@ -43,10 +44,11 @@ type UpdateHandler struct {
// operator last saved it; an empty string means "not configured" and the official
// repository is used. A function rather than a value because the config can change
// while the process runs.
source func() string
// saveSource persists a new source through the config layer; nil means this start
// has no config to write to.
source func() string
saveSource func(repo string) error
// Optional full update config hooks supporting repo + branch.
updateCfg func() config.UpdateConfig
saveUpdateCfg func(cfg config.UpdateConfig) error
// baseline is the binary this process is actually running: the file on disk at
// construction time. An update, a rollback or a CLI run that replaces it leaves a
// different file behind, and that difference is what "restart to activate" means.
@ -133,26 +135,44 @@ func restartSupervised() bool {
strings.TrimSpace(os.Getenv("JOURNAL_STREAM")) != ""
}
func (h *UpdateHandler) options() update.Options {
opts := update.Options{Root: h.root}
if h.source != nil {
opts.Repo = h.source()
// WithUpdateConfig attaches repo+branch persistence callbacks.
func (h *UpdateHandler) WithUpdateConfig(get func() config.UpdateConfig, save func(config.UpdateConfig) error) *UpdateHandler {
h.updateCfg = get
h.saveUpdateCfg = save
return h
}
func (h *UpdateHandler) currentConfig() config.UpdateConfig {
if h.updateCfg != nil {
return h.updateCfg()
}
if h.source != nil {
return config.UpdateConfig{Repo: h.source()}
}
return config.UpdateConfig{}
}
func (h *UpdateHandler) options() update.Options {
cfg := h.currentConfig()
return update.Options{
Root: h.root,
Repo: cfg.Repo,
Branch: cfg.Branch,
}
return opts
}
// sourceView is the configured source as the page edits it: the address (empty = the
// official repository) plus the default, so the page never hardcodes a URL the server
// would disagree with.
// official repository), optional branch (empty = repository default branch), plus the default.
func (h *UpdateHandler) sourceView() gin.H {
repo := ""
if h.source != nil {
repo = strings.TrimSpace(h.source())
}
cfg := h.currentConfig()
repo := strings.TrimSpace(cfg.Repo)
branch := strings.TrimSpace(cfg.Branch)
return gin.H{
"repo": repo,
"configured": repo != "",
"defaultRepo": update.DefaultRepoURL,
"repo": repo,
"branch": branch,
"configured": repo != "",
"branchConfigured": branch != "",
"defaultRepo": update.DefaultRepoURL,
}
}
@ -209,24 +229,54 @@ func (h *UpdateHandler) Check(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{"status": snap})
}
// Branches answers GET /api/system/update/branches: lists remote branches of the
// configured (or previewed via ?repo=...) update source repository via git ls-remote.
func (h *UpdateHandler) Branches(c *gin.Context) {
opts := h.options()
if repoParam := strings.TrimSpace(c.Query("repo")); repoParam != "" {
if !update.ValidRemoteURL(repoParam) {
c.JSON(http.StatusBadRequest, gin.H{"error": "仓库地址不合法(只允许 https/http/ssh/git/file:// 或本机绝对路径)"})
return
}
opts.Repo = repoParam
}
defaultBranch, branches, err := update.ListBranches(c.Request.Context(), opts)
if err != nil {
c.JSON(http.StatusBadGateway, gin.H{"error": err.Error()})
return
}
if branches == nil {
branches = []string{}
}
c.JSON(http.StatusOK, gin.H{
"repo": opts.Repo,
"defaultBranch": defaultBranch,
"branches": branches,
})
}
// SaveSource answers POST /api/system/update/source: the operator picks which repository
// this installation updates from - the official one, a mirror, or their own fork - and
// the choice lands in the update section of config.yaml. An empty address clears the
// setting, which means the official repository again.
// and optional target branch this installation updates from.
func (h *UpdateHandler) SaveSource(c *gin.Context) {
var body struct {
Repo string `json:"repo"`
Repo string `json:"repo"`
Branch string `json:"branch"`
}
if err := c.ShouldBindJSON(&body); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "请求体不是合法 JSON"})
return
}
body.Repo = strings.TrimSpace(body.Repo)
body.Branch = strings.TrimSpace(body.Branch)
if body.Repo != "" && !update.ValidRemoteURL(body.Repo) {
c.JSON(http.StatusBadRequest, gin.H{"error": "仓库地址不合法(只允许 https/http/ssh/git/file:// 或本机绝对路径)"})
return
}
if h.saveSource == nil {
if body.Branch != "" && !update.ValidName(body.Branch) {
c.JSON(http.StatusBadRequest, gin.H{"error": "目标分支名不合法"})
return
}
if h.saveUpdateCfg == nil && h.saveSource == nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": "本次启动没有接入配置保存,更新源改不了"})
return
}
@ -240,16 +290,28 @@ func (h *UpdateHandler) SaveSource(c *gin.Context) {
c.JSON(http.StatusConflict, gin.H{"error": "更新进行中,不能切换更新源", "job": busy})
return
}
if err := h.saveSource(body.Repo); err != nil {
if h.saveUpdateCfg != nil {
err = h.saveUpdateCfg(config.UpdateConfig{Repo: body.Repo, Branch: body.Branch})
} else {
err = h.saveSource(body.Repo)
}
if err != nil {
h.record(c, "update.source", "failure", "保存更新源失败: "+err.Error(), map[string]interface{}{"error": err.Error()})
c.JSON(http.StatusInternalServerError, gin.H{"error": "保存失败:" + err.Error()})
return
}
message := "更新源已保存:" + body.Repo
if body.Repo == "" {
message = "已恢复默认更新源(官方仓库)"
message := "更新源已保存"
if body.Repo != "" {
message += ":" + body.Repo
} else {
message += "(官方仓库)"
}
h.record(c, "update.source", "success", message, map[string]interface{}{"repo": body.Repo})
if body.Branch != "" {
message += " / 分支 " + body.Branch
} else {
message += " / 默认分支"
}
h.record(c, "update.source", "success", message, map[string]interface{}{"repo": body.Repo, "branch": body.Branch})
c.JSON(http.StatusOK, gin.H{"source": h.sourceView()})
}

View File

@ -120,7 +120,7 @@ func Preview(ctx context.Context, opts Options) (*AdoptPlan, error) {
if _, err := gitCmd(ctx, tmp, "init", "--quiet", "--bare"); err != nil {
return nil, err
}
branch, commit, subject, err := fetchSource(ctx, tmp, source)
branch, commit, subject, err := fetchSourceBranch(ctx, tmp, source, opts.Branch)
if err != nil {
return nil, err
}
@ -166,7 +166,7 @@ func Adopt(ctx context.Context, opts Options, onStep func(Step)) (*Result, error
return nil, &Error{Reason: "init_failed", Message: "添加远端失败:" + err.Error()}
}
branch, commit, subject, err := fetchSource(ctx, root, source)
branch, commit, subject, err := fetchSourceBranch(ctx, root, source, opts.Branch)
if err != nil {
return nil, err
}
@ -317,13 +317,22 @@ func adoptPreflight(ctx context.Context, opts Options) (root, source string, err
// that ended up being, its short commit and its subject. Both callers fetch into a
// repository of their own.
func fetchSource(ctx context.Context, repo, source string) (string, string, string, error) {
out, err := gitCmd(ctx, repo, "ls-remote", "--symref", source, "HEAD")
if err != nil {
return "", "", "", &Error{Reason: "fetch_failed", Message: "读取远端默认分支失败:" + err.Error()}
}
branch := parseDefaultBranch(out)
return fetchSourceBranch(ctx, repo, source, "")
}
func fetchSourceBranch(ctx context.Context, repo, source, configuredBranch string) (string, string, string, error) {
branch := strings.TrimSpace(configuredBranch)
if branch == "" {
return "", "", "", &Error{Reason: "no_branch", Message: "无法确定远端默认分支:" + source}
out, err := gitCmd(ctx, repo, "ls-remote", "--symref", source, "HEAD")
if err != nil {
return "", "", "", &Error{Reason: "fetch_failed", Message: "读取远端默认分支失败:" + err.Error()}
}
branch = parseDefaultBranch(out)
if branch == "" {
return "", "", "", &Error{Reason: "no_branch", Message: "无法确定远端默认分支:" + source}
}
} else if !ValidName(branch) {
return "", "", "", &Error{Reason: "bad_branch", Message: "配置的目标分支名不合法:" + branch}
}
if _, err := gitCmd(ctx, repo, "fetch", "--quiet", "--no-tags", "--recurse-submodules=no",
source, "+refs/heads/"+branch+":refs/remotes/origin/"+branch); err != nil {

View File

@ -261,7 +261,11 @@ func Apply(ctx context.Context, opts Options, onStep func(Step)) (*Result, error
return res, nil
}
step("fetch", fmt.Sprintf("%s(默认分支 %s)有 %d 个新提交:%s → %s", snap.sourceLabel(), snap.TargetBranch, snap.Behind, snap.Commit, snap.RemoteCommit))
if snap.BranchSwitch {
step("fetch", fmt.Sprintf("准备切换分支 %s → %s(%s → %s)", snap.Branch, snap.TargetBranch, snap.Commit, snap.RemoteCommit))
} else {
step("fetch", fmt.Sprintf("%s(分支 %s)有 %d 个新提交:%s → %s", snap.sourceLabel(), snap.TargetBranch, snap.Behind, snap.Commit, snap.RemoteCommit))
}
// Put operator-owned content aside, and clear the paths the incoming change would
// write to, so the fast-forward cannot be refused by "your local changes would be
@ -314,12 +318,19 @@ func Apply(ctx context.Context, opts Options, onStep func(Step)) (*Result, error
return nil, err
}
if out, err := gitCmd(ctx, root, "merge", "--ff-only", "--no-verify", ref); err != nil {
var moveOut string
var moveErr error
if snap.BranchSwitch {
moveOut, moveErr = gitCmd(ctx, root, "checkout", "-B", snap.TargetBranch, ref)
} else {
moveOut, moveErr = gitCmd(ctx, root, "merge", "--ff-only", "--no-verify", ref)
}
if moveErr != nil {
if restoreErr := restoreProtected(backupDir, kept); restoreErr != nil {
return nil, &Error{Reason: "backup_failed", Message: fmt.Sprintf("快进合并失败,恢复本地内容又失败:%v", restoreErr)}
return nil, &Error{Reason: "backup_failed", Message: fmt.Sprintf("更新工作树失败,恢复本地内容又失败:%v", restoreErr)}
}
_ = clearBuildPending(root)
return nil, &Error{Reason: "merge_failed", Message: fmt.Sprintf("快进合并失败:%v\n%s", err, strings.TrimSpace(out))}
return nil, &Error{Reason: "merge_failed", Message: fmt.Sprintf("更新工作树失败:%v\n%s", moveErr, strings.TrimSpace(moveOut))}
}
// The merge wrote upstream's version of the content paths; the operator's copies win
// them back, which is what "update the code, keep my work" means.

View File

@ -0,0 +1,94 @@
package update
import (
"context"
"os"
"path/filepath"
"slices"
"testing"
)
func TestBranchSwitchForwardAndBackPreservesProtectedFiles(t *testing.T) {
ctx := context.Background()
upstream := t.TempDir()
mustGit(t, upstream, "init", "--initial-branch=main")
mustGit(t, upstream, "config", "user.name", "Test")
mustGit(t, upstream, "config", "user.email", "test@example.com")
writeFile(t, filepath.Join(upstream, "app.txt"), "main-v1\n")
writeFile(t, filepath.Join(upstream, "roles", "default.yaml"), "upstream-v1\n")
mustGit(t, upstream, "add", ".")
mustGit(t, upstream, "commit", "-m", "main v1")
// Create feature branch with new commit.
mustGit(t, upstream, "checkout", "-b", "feat/plugin-capability-platform")
writeFile(t, filepath.Join(upstream, "app.txt"), "feat-v1\n")
writeFile(t, filepath.Join(upstream, "plugin.txt"), "plugin-ready\n")
mustGit(t, upstream, "add", ".")
mustGit(t, upstream, "commit", "-m", "feat plugin")
// Advance main independently so main and feat diverge!
mustGit(t, upstream, "checkout", "main")
writeFile(t, filepath.Join(upstream, "app.txt"), "main-v2\n")
mustGit(t, upstream, "add", ".")
mustGit(t, upstream, "commit", "-m", "main v2")
// Clone main at v1 as install tree.
install := t.TempDir()
mustGit(t, install, "clone", "--branch", "main", upstream, ".")
mustGit(t, install, "reset", "--hard", "HEAD~1")
writeFile(t, filepath.Join(install, "config.yaml"), "custom: true\n")
writeFile(t, filepath.Join(install, "roles", "default.yaml"), "operator-edited\n")
// 1. ListBranches lists default main first + feature branch.
def, branches, err := ListBranches(ctx, Options{Root: install, Repo: upstream})
if err != nil {
t.Fatalf("ListBranches failed: %v", err)
}
if def != "main" || len(branches) < 2 || branches[0] != "main" || !slices.Contains(branches, "feat/plugin-capability-platform") {
t.Fatalf("unexpected branches: default=%q list=%v", def, branches)
}
// 2. Switch main -> feat/plugin-capability-platform.
optsFeat := Options{Root: install, Repo: upstream, Branch: "feat/plugin-capability-platform", BinaryName: "none"}
snap, err := Check(ctx, optsFeat)
if err != nil {
t.Fatal(err)
}
if !snap.BranchSwitch || !snap.UpdateAvailable || snap.Diverged || snap.TargetBranch != "feat/plugin-capability-platform" {
t.Fatalf("unexpected check snapshot for branch switch: %+v", snap)
}
if _, err := Apply(ctx, optsFeat, nil); err != nil {
t.Fatalf("Apply branch switch failed: %v", err)
}
if got := mustGit(t, install, "rev-parse", "--abbrev-ref", "HEAD"); got != "feat/plugin-capability-platform" {
t.Fatalf("expected feat branch, got %q", got)
}
if data, err := os.ReadFile(filepath.Join(install, "plugin.txt")); err != nil || string(data) != "plugin-ready\n" {
t.Fatalf("expected plugin.txt on feat branch: %q %v", string(data), err)
}
if data, err := os.ReadFile(filepath.Join(install, "roles", "default.yaml")); err != nil || string(data) != "operator-edited\n" {
t.Fatalf("operator protected file was not preserved: %q %v", string(data), err)
}
// 3. Switch back feat/plugin-capability-platform -> main (diverged history!).
optsMain := Options{Root: install, Repo: upstream, Branch: "", BinaryName: "none"}
backSnap, err := Check(ctx, optsMain)
if err != nil {
t.Fatal(err)
}
if !backSnap.BranchSwitch || !backSnap.UpdateAvailable || backSnap.Diverged || backSnap.TargetBranch != "main" {
t.Fatalf("unexpected check snapshot switching back to main: %+v", backSnap)
}
if _, err := Apply(ctx, optsMain, nil); err != nil {
t.Fatalf("Apply switch back to main failed: %v", err)
}
if got := mustGit(t, install, "rev-parse", "--abbrev-ref", "HEAD"); got != "main" {
t.Fatalf("expected main branch, got %q", got)
}
if data, err := os.ReadFile(filepath.Join(install, "app.txt")); err != nil || string(data) != "main-v2\n" {
t.Fatalf("expected main-v2 after switching back: %q %v", string(data), err)
}
if _, err := os.Stat(filepath.Join(install, "plugin.txt")); !os.IsNotExist(err) {
t.Fatalf("plugin.txt should be removed after switching back to main")
}
}

View File

@ -119,8 +119,9 @@ func Protected(rel string) bool {
// Empty means the official repository, so an installation with no configuration at all
// still has exactly one answer to "where does an update come from".
type Options struct {
Root string
Repo string
Root string
Repo string
Branch string
// BinaryName overrides the executable swapped after a successful update. Empty
// means "cyberstrike-ai" in Root; "none" means leave the binary alone.
BinaryName string
@ -180,10 +181,11 @@ type Snapshot struct {
// came from config.yaml or is the built-in official repository.
Repo string `json:"repo"`
RepoConfigured bool `json:"repoConfigured"`
// TargetBranch is the update source's own default branch, learned from the source
// itself when the network answer arrives (empty until then).
TargetBranch string `json:"targetBranch,omitempty"`
Commit string `json:"commit"`
// TargetBranch is the configured target branch or the update source's default branch.
TargetBranch string `json:"targetBranch,omitempty"`
BranchConfigured bool `json:"branchConfigured,omitempty"`
BranchSwitch bool `json:"branchSwitch,omitempty"`
Commit string `json:"commit"`
Subject string `json:"subject"`
CommittedAt string `json:"committedAt"`
@ -260,7 +262,65 @@ func nulList(blob string) []string {
}
// ValidName reports whether s can safely reach git's argv as a branch name.
func ValidName(s string) bool { return namePattern.MatchString(s) }
func ValidName(s string) bool {
if !namePattern.MatchString(s) || len(s) > 180 {
return false
}
if strings.Contains(s, "..") || strings.Contains(s, "//") || strings.HasSuffix(s, "/") || strings.HasSuffix(s, ".") || strings.HasSuffix(s, ".lock") {
return false
}
for _, part := range strings.Split(s, "/") {
if part == "" || strings.HasPrefix(part, ".") || strings.HasSuffix(part, ".lock") {
return false
}
}
return true
}
// ListBranches queries the update source via git ls-remote without modifying the working tree.
func ListBranches(ctx context.Context, opts Options) (string, []string, error) {
root, err := opts.installRoot()
if err != nil {
return "", nil, err
}
repo := opts.repoURL()
if !ValidRemoteURL(repo) {
return "", nil, fmt.Errorf("配置的更新源仓库地址不合法")
}
out, err := gitCmd(ctx, root, "ls-remote", "--symref", repo, "HEAD", "refs/heads/*")
if err != nil {
return "", nil, fmt.Errorf("无法读取远端分支 %s:%s", repo, strings.TrimSpace(err.Error()))
}
defaultBranch := parseDefaultBranch(out)
seen := map[string]bool{}
var branches []string
for _, line := range strings.Split(out, "\n") {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "ref:") {
continue
}
fields := strings.Fields(line)
if len(fields) < 2 {
continue
}
name, ok := strings.CutPrefix(fields[1], "refs/heads/")
if !ok || !ValidName(name) || seen[name] {
continue
}
seen[name] = true
branches = append(branches, name)
}
sort.Slice(branches, func(i, j int) bool {
if branches[i] == defaultBranch {
return true
}
if branches[j] == defaultBranch {
return false
}
return branches[i] < branches[j]
})
return defaultBranch, branches, nil
}
// Status reads the install tree without touching the network.
func Status(ctx context.Context, opts Options) (*Snapshot, error) {
@ -268,18 +328,25 @@ func Status(ctx context.Context, opts Options) (*Snapshot, error) {
if err != nil {
return nil, err
}
configuredBranch := strings.TrimSpace(opts.Branch)
snap := &Snapshot{
Root: root,
Repo: opts.repoURL(),
RepoConfigured: strings.TrimSpace(opts.Repo) != "",
Incoming: []Commit{},
LocalChanges: []Change{},
BlockingChanges: []Change{},
Root: root,
Repo: opts.repoURL(),
RepoConfigured: strings.TrimSpace(opts.Repo) != "",
TargetBranch: configuredBranch,
BranchConfigured: configuredBranch != "",
Incoming: []Commit{},
LocalChanges: []Change{},
BlockingChanges: []Change{},
}
if !ValidRemoteURL(snap.Repo) {
snap.CheckError = "配置的更新源仓库地址不合法(只允许 https/http/ssh/git/file:// 或本机绝对路径)"
return snap, nil
}
if configuredBranch != "" && !ValidName(configuredBranch) {
snap.CheckError = "配置的目标分支名不合法"
return snap, nil
}
if _, err := gitCmd(ctx, root, "rev-parse", "--is-inside-work-tree"); err != nil {
// Not a git tree: the page still has to say something useful, so this is a
@ -400,14 +467,20 @@ func check(ctx context.Context, opts Options) (*Snapshot, error) {
}
root := snap.Root
// The branch to follow is the source repository's own default branch, so the
// operator never names one and a fork whose default differs from main still works.
target, err := resolveDefaultBranch(ctx, root, snap.Repo)
if err != nil {
snap.CheckError = err.Error()
target := strings.TrimSpace(opts.Branch)
if target == "" {
var resolveErr error
target, resolveErr = resolveDefaultBranch(ctx, root, snap.Repo)
if resolveErr != nil {
snap.CheckError = resolveErr.Error()
return snap, nil
}
} else if !ValidName(target) {
snap.CheckError = "配置的目标分支名不合法"
return snap, nil
}
snap.TargetBranch = target
snap.BranchConfigured = strings.TrimSpace(opts.Branch) != ""
// --recurse-submodules=no and --prune keep the fetch to this repository's own
// history. A branch-scoped fetch means a source with many refs cannot turn the
@ -438,8 +511,14 @@ func check(ctx context.Context, opts Options) (*Snapshot, error) {
return snap, nil
}
snap.Ahead, snap.Behind = ahead, behind
snap.Diverged = ahead > 0 && behind > 0
snap.UpdateAvailable = snap.Behind > 0
snap.BranchSwitch = snap.Branch != "" && snap.TargetBranch != "" && snap.Branch != snap.TargetBranch
if snap.BranchSwitch {
snap.Diverged = false
snap.UpdateAvailable = true
} else {
snap.Diverged = ahead > 0 && behind > 0
snap.UpdateAvailable = snap.Behind > 0
}
snap.IncomingTotal = snap.Behind
logs, err := gitCmd(ctx, root, "log", "--format=%h\x1f%s", "-n", fmt.Sprint(maxIncoming), "HEAD.."+ref)

View File

@ -2,7 +2,7 @@
* 更新源配置、远端版本检查和更新进度。
*/
import { useEffect, useState } from 'react';
import { Banner, Button, Input, Space, Tag, Timeline, Typography } from '@douyinfe/semi-ui';
import { Banner, Button, Input, Select, Space, Tag, Timeline, Typography } from '@douyinfe/semi-ui';
import { IconDownload, IconRefresh } from '@douyinfe/semi-icons';
import { api, errorMessage } from '../../../lib/http';
import { useAuth } from '../../../lib/auth';
@ -61,6 +61,10 @@ export default function UpdateSection() {
const [actionError, setActionError] = useState(null);
const [activationBootID, setActivationBootID] = useState(null);
const [sourceDraft, setSourceDraft] = useState(null);
const [branchDraft, setBranchDraft] = useState(null);
const [remoteBranches, setRemoteBranches] = useState([]);
const [remoteDefaultBranch, setRemoteDefaultBranch] = useState('');
const [loadingBranches, setLoadingBranches] = useState(false);
const [savingSource, setSavingSource] = useState(false);
const [sourceError, setSourceError] = useState(null);
@ -77,8 +81,10 @@ export default function UpdateSection() {
const needsRestart = consoleRes.data?.needsRestart;
const source = consoleRes.data?.source;
const sourceRepo = source?.repo || '';
const sourceBranch = source?.branch || '';
const sourceValue = sourceDraft ?? sourceRepo;
const sourceChanged = sourceValue.trim() !== sourceRepo;
const branchValue = branchDraft ?? sourceBranch;
const sourceChanged = sourceValue.trim() !== sourceRepo || branchValue.trim() !== sourceBranch;
const busy = Boolean(action || running || restarting);
const sourceBusy = savingSource || busy || consoleRes.loading;
@ -170,18 +176,39 @@ export default function UpdateSection() {
}
};
const fetchBranches = async () => {
setLoadingBranches(true);
setSourceError(null);
try {
const repoQuery = sourceValue.trim();
const payload = await api.get('/system/update/branches', repoQuery ? { repo: repoQuery } : undefined);
const list = Array.isArray(payload?.branches) ? payload.branches : [];
setRemoteBranches(list);
setRemoteDefaultBranch(payload?.defaultBranch || '');
toastSuccess(t('updateUi.branchesLoaded', { n: list.length }, `已获取 ${list.length} 个远端分支`));
} catch (error) {
setSourceError(error);
} finally {
setLoadingBranches(false);
}
};
const saveSource = async event => {
event.preventDefault();
if (!source || !canManage || !sourceChanged || sourceBusy) return;
setSavingSource(true);
setSourceError(null);
try {
const payload = await api.post('/system/update/source', { repo: sourceValue.trim() });
const payload = await api.post('/system/update/source', {
repo: sourceValue.trim(),
branch: branchValue.trim()
});
if (!payload?.source || typeof payload.source.repo !== 'string') {
throw new Error(t('updateUi.sourceResponseMissing', null, '服务端未返回更新源,刷新后可核对配置。'));
}
consoleRes.setData(previous => ({ ...previous, source: payload.source }));
setSourceDraft(null);
setBranchDraft(null);
setCheckResult(null);
setActionError(null);
toastSuccess(t('update.sourceSaveOk', null, '更新源已保存'));
@ -203,7 +230,13 @@ export default function UpdateSection() {
const facts = [
{ label: t('update.root', null, '安装目录'), value: <Mono>{snapshot.root || '—'}</Mono> },
{ label: t('update.gitTree', null, 'Git 安装树'), value: yesNo(t, snapshot.installed) },
{ label: t('update.branch', null, '分支'), value: snapshot.branch || '—' },
{ label: t('update.branch', null, '当前分支'), value: snapshot.branch || '—' },
{
label: t('updateUi.targetBranch', null, '目标分支'),
value: sourceBranch
? <Space spacing={4}><Mono>{sourceBranch}</Mono>{snapshot.branch && sourceBranch !== snapshot.branch && <Tag size="small" color="amber">{t('updateUi.branchSwitchPending', null, '待切换')}</Tag>}</Space>
: <Text type="tertiary">{t('updateUi.followDefaultBranch', null, '跟随仓库默认分支')}</Text>
},
{ label: t('updateUi.repo', null, '更新源仓库'), value: <Mono>{source?.repo || source?.defaultRepo || snapshot.repo || '—'}</Mono> },
{ label: t('update.commit', null, '当前提交'), value: <Mono>{shortCommit(snapshot.commit)}</Mono> },
{ label: t('update.subject', null, '提交说明'), value: truncate(snapshot.subject || '—', 80) },
@ -268,6 +301,7 @@ export default function UpdateSection() {
value={sourceValue}
onChange={value => {
setSourceDraft(value);
setRemoteBranches([]);
setSourceError(null);
}}
placeholder={source.defaultRepo}
@ -275,10 +309,48 @@ export default function UpdateSection() {
disabled={savingSource}
/>
</label>
<div className="settings-field" style={{ marginTop: 12 }}>
<Text size="small" type="tertiary">{t('updateUi.targetBranchLabel', null, '目标分支(留空 = 跟随仓库默认分支)')}</Text>
<Space style={{ width: '100%' }} wrap>
<Select
value={branchValue || undefined}
onChange={value => {
setBranchDraft(value || '');
setSourceError(null);
}}
placeholder={t('updateUi.targetBranchPlaceholder', null, '留空跟随默认分支,或选择/输入分支名')}
filter
allowCreate
showClear
disabled={!canManage || savingSource}
style={{ width: 340, maxWidth: '100%' }}
optionList={[
...new Set([
...(remoteBranches || []),
...(sourceBranch ? [sourceBranch] : []),
...(branchValue && branchValue.trim() ? [branchValue.trim()] : [])
])
].map(name => ({
value: name,
label: name === remoteDefaultBranch
? `${name} (${t('updateUi.defaultBranchTag', null, '默认')})`
: name
}))}
/>
<Button
icon={<IconRefresh />}
loading={loadingBranches}
disabled={savingSource}
onClick={fetchBranches}
>
{t('updateUi.fetchBranches', null, '获取远端分支')}
</Button>
</Space>
</div>
{canManage ? (
<>
<Hint>{t('update.sourceRepoHint', null, '留空即使用官方仓库。')}</Hint>
<Hint>{t('updateUi.sourceSaveOnly', null, '保存会修改配置文件中的 update.repo。')}</Hint>
<Hint>{t('update.sourceRepoHint', null, '留空即使用官方仓库;分支留空即跟随默认分支。')}</Hint>
<Hint>{t('updateUi.sourceSaveBranchHint', null, '保存会修改配置文件中的 update.repo 与 update.branch,下次点击「更新」时自动拉取并切换至该分支。')}</Hint>
<div>
<Button htmlType="submit" theme="solid" loading={savingSource}
disabled={!sourceChanged || sourceBusy}>
@ -313,7 +385,9 @@ export default function UpdateSection() {
<Space wrap spacing={8}>
{checkResult.installed && (
<Tag size="small" color={checkResult.updateAvailable || checkResult.buildPending || needsRestart ? 'amber' : 'green'}>
{checkResult.updateAvailable ? t('update.behindCount', { n: checkResult.behind })
{checkResult.branchSwitch
? t('updateUi.branchSwitchTag', { from: checkResult.branch, to: checkResult.targetBranch }, `切换分支:${checkResult.branch} → ${checkResult.targetBranch}`)
: checkResult.updateAvailable ? t('update.behindCount', { n: checkResult.behind })
: checkResult.buildPending ? t('updateUi.buildPending')
: needsRestart ? t('update.restartNeeded')
: t(checkResult.ahead > 0 ? 'updateUi.noNewerVersion' : 'updateUi.currentVersion')}

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-CFmEgVyi.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-GGN4sgsJ.js";var k=e(t(),1),A=e(n(),1),{Text:j}=c;function M(){let e=g(),{hasPermission:t}=m(),n=t(`agents:write`),c=t(`agents:delete`),[M,N]=(0,k.useState)(``),[P,F]=(0,k.useState)(null),[I,L]=(0,k.useState)(null),[R,z]=(0,k.useState)(!1),B=_(()=>h.get(`/multi-agent/markdown-agents`),[]),V=(Array.isArray(B.data?.agents)?B.data.agents:[]).filter(e=>{if(!M)return!0;let t=M.toLowerCase();return[e.name,e.id,e.filename,e.description].some(e=>String(e||``).toLowerCase().includes(t))}),H=async e=>{try{F(await h.get(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`))}catch(e){v(e,`读取智能体失败`)}},U=async()=>{let e=await I.form.validate();z(!0);try{await h.post(`/multi-agent/markdown-agents`,{filename:e.filename?.trim()||``,name:e.name.trim(),description:e.description?.trim()||``,instruction:e.instruction,kind:e.kind||`sub`,tools:String(e.tools||``).split(`,`).map(e=>e.trim()).filter(Boolean)}),D(`智能体已保存`),L(null),B.reload()}catch(e){v(e,`保存智能体失败`)}finally{z(!1)}},W=e=>O({title:`删除智能体「${e.name||e.filename}」?`,onOk:async()=>{await h.del(`/multi-agent/markdown-agents/${encodeURIComponent(e.filename)}`),D(`已删除`),B.reload()}});return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(w,{title:e(`agents.title`,null,`智能体管理`),description:B.data?.dir?`目录:${B.data.dir}`:`以 Markdown 文件定义的子智能体与编排器。`,extra:(0,A.jsxs)(r,{children:[(0,A.jsx)(a,{icon:(0,A.jsx)(p,{}),onClick:()=>B.reload(),loading:B.loading,children:`刷新`}),n&&(0,A.jsx)(a,{theme:`solid`,type:`primary`,icon:(0,A.jsx)(d,{}),onClick:()=>L({record:null,form:{}}),children:`新建智能体`})]})}),B.data?.error&&(0,A.jsx)(S,{error:B.data.error}),(0,A.jsxs)(C,{title:`智能体(${V.length})`,children:[(0,A.jsx)(S,{error:B.error,onRetry:()=>B.reload()}),(0,A.jsx)(T,{columns:[{title:`智能体`,dataIndex:`name`,render:(e,t)=>(0,A.jsxs)(r,{vertical:!0,spacing:0,align:`start`,children:[(0,A.jsxs)(r,{children:[(0,A.jsx)(j,{strong:!0,children:e||t.id}),t.is_orchestrator&&(0,A.jsx)(o,{size:`small`,color:`purple`,children:`编排器`})]}),(0,A.jsx)(j,{type:`tertiary`,children:t.filename})]})},{title:`类型`,dataIndex:`kind`,width:110,render:e=>(0,A.jsx)(o,{size:`small`,children:e||`sub`})},{title:`描述`,dataIndex:`description`,render:e=>(0,A.jsx)(j,{type:`tertiary`,ellipsis:{showTooltip:!0},style:{maxWidth:460},children:e||`—`})},{title:`操作`,width:180,render:(e,t)=>(0,A.jsxs)(r,{children:[(0,A.jsx)(a,{size:`small`,theme:`borderless`,onClick:()=>H(t),children:`详情`}),n&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,icon:(0,A.jsx)(s,{}),onClick:()=>L({record:t,form:{}})}),c&&(0,A.jsx)(a,{size:`small`,theme:`borderless`,type:`danger`,icon:(0,A.jsx)(u,{}),onClick:()=>W(t)})]})}],dataSource:V,rowKey:`filename`,loading:B.loading,pagination:{pageSize:20},toolbar:(0,A.jsx)(i,{prefix:(0,A.jsx)(f,{}),value:M,onChange:N,placeholder:`搜索名称或文件名`,style:{width:280}})})]}),(0,A.jsx)(y,{title:I?.record?`编辑智能体`:`新建智能体`,visible:!!I,onCancel:()=>L(null),onOk:U,confirmLoading:R,width:760,children:(0,A.jsxs)(l,{getFormApi:e=>L(t=>t&&{...t,form:e}),initValues:I?.record?{filename:I.record.filename,name:I.record.name,description:I.record.description,kind:I.record.kind||`sub`}:{kind:`sub`},children:[(0,A.jsx)(l.Input,{field:`filename`,label:`文件名(留空自动生成)`,placeholder:`例如 recon.md`}),(0,A.jsx)(l.Input,{field:`name`,label:`名称`,rules:[{required:!0,message:`请输入名称`}]}),(0,A.jsx)(l.Input,{field:`description`,label:`描述`}),(0,A.jsx)(l.Select,{field:`kind`,label:`类型`,optionList:[{value:`sub`,label:`子智能体`},{value:`orchestrator`,label:`编排器`},{value:`plan_execute`,label:`计划执行`}]}),(0,A.jsx)(l.Input,{field:`tools`,label:`工具(逗号分隔)`,placeholder:`toolName, mcp::tool`}),(0,A.jsx)(l.TextArea,{field:`instruction`,label:`指令(Markdown)`,autosize:{minRows:8,maxRows:20}})]})},I?.record?.filename||`new-agent`),(0,A.jsx)(y,{title:P?.name||`智能体详情`,visible:!!P,onCancel:()=>F(null),width:720,children:P&&(0,A.jsxs)(`div`,{style:{display:`flex`,flexDirection:`column`,gap:12},children:[(0,A.jsx)(b,{items:[{label:`文件名`,value:P.filename},{label:`ID`,value:P.id},{label:`类型`,value:P.kind},{label:`绑定角色`,value:P.bind_role||`—`},{label:`最大迭代`,value:P.max_iterations??`—`},{label:`工具`,value:Array.isArray(P.tools)&&P.tools.length?P.tools.join(`、`):`—`}]}),(0,A.jsx)(x,{content:P.instruction||P.raw||``}),(0,A.jsx)(E,{value:P.raw||P,title:`原始 Markdown`,collapsed:!0})]})})]})}export{M as default};

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r}from"./semi-CHxO7u8f.js";import{E as i,P as a,k as o}from"./index-CFmEgVyi.js";import"./c2-shared-Bp5-se02.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-GGN4sgsJ.js";import"./c2-shared-BfElLmLz.js";import{t as s}from"./react-QV7DAAIx.js";var c=e(s(),1),{Text:l}=r,u=[{value:`http_beacon`,label:`HTTP Beacon`},{value:`https_beacon`,label:`HTTPS Beacon`},{value:`tcp_reverse`,label:`TCP 反向`},{value:`websocket`,label:`WebSocket`}],d={running:`运行中`,stopped:`已停止`,error:`异常`},f={tcp_reverse:[{value:`bash`,label:`Bash (/dev/tcp)`},{value:`nc`,label:`Netcat (-e)`},{value:`nc_mkfifo`,label:`Netcat (mkfifo)`},{value:`python`,label:`Python`},{value:`perl`,label:`Perl`},{value:`powershell`,label:`PowerShell`}],http_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],https_beacon:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}],websocket:[{value:`curl_beacon`,label:`Curl Beacon (HTTP)`}]},p=[{value:`shell`,label:`shell`},{value:`exec`,label:`exec`},{value:`ls`,label:`ls`},{value:`pwd`,label:`pwd`},{value:`cd`,label:`cd`},{value:`ps`,label:`ps`},{value:`kill_proc`,label:`kill_proc`},{value:`download`,label:`download`},{value:`upload`,label:`upload`},{value:`screenshot`,label:`screenshot`},{value:`sleep`,label:`sleep`},{value:`exit`,label:`exit`},{value:`self_delete`,label:`self_delete`},{value:`port_fwd`,label:`port_fwd`},{value:`socks_start`,label:`socks_start`},{value:`socks_stop`,label:`socks_stop`},{value:`load_assembly`,label:`load_assembly`},{value:`persist`,label:`persist`}],m=[{value:`queued`,label:`队列中`},{value:`sent`,label:`已发送`},{value:`running`,label:`执行中`},{value:`success`,label:`成功`},{value:`failed`,label:`失败`},{value:`cancelled`,label:`已取消`}],h=[{value:`info`,label:`信息`},{value:`warn`,label:`警告`},{value:`critical`,label:`严重`}],g=[{value:`listener`,label:`监听器`},{value:`session`,label:`会话`},{value:`task`,label:`任务`},{value:`payload`,label:`Payload`},{value:`opsec`,label:`OPSEC`}],_=[{value:`active`,label:`活跃`},{value:`sleeping`,label:`休眠`},{value:`dead`,label:`离线`},{value:`killed`,label:`已终止`}],v=[{value:`15m`,label:`最近15分钟`,ms:9e5},{value:`1h`,label:`最近1小时`,ms:36e5},{value:`24h`,label:`最近24小时`,ms:864e5},{value:`7d`,label:`最近7天`,ms:6048e5},{value:`all`,label:`全部`,ms:0}];function y(e){let t=v.find(t=>t.value===e);return!t||!t.ms?``:new Date(Date.now()-t.ms).toISOString()}function b({value:e,onChange:r,ns:i=`tasks`}){let o=a();return(0,c.jsxs)(t,{spacing:6,wrap:!0,className:`c2-time-presets`,children:[(0,c.jsx)(l,{type:`tertiary`,size:`small`,children:o(`c2.tasks.timePresets`,null,`快捷`)}),v.map(t=>(0,c.jsx)(n,{size:`small`,theme:t.value===e?`solid`:`borderless`,type:t.value===e?`primary`:`tertiary`,onClick:()=>r(t.value),children:o(`c2.${i}.preset${t.value===`all`?`All`:t.value}`,null,t.label)},t.value))]})}function x(e){let t=Number(e);return!Number.isFinite(t)||t<=0?`—`:t<1e3?`${Math.round(t)}ms`:t<6e4?`${(t/1e3).toFixed(1)}秒`:`${Math.round(t/6e4)}分钟`}function S({value:e}){let t=a();return e?(0,c.jsx)(`span`,{className:`c2-time-text`,title:i(e),children:o(e,t)}):(0,c.jsx)(l,{type:`tertiary`,children:`—`})}var C={running:`green`,stopped:`grey`,error:`red`},w={queued:`amber`,sent:`blue`,running:`blue`,success:`green`,failed:`red`,cancelled:`grey`},T={active:`green`,sleeping:`amber`,dead:`grey`,killed:`red`},E={info:`blue`,warn:`amber`,critical:`red`};export{d as a,T as c,m as d,p as f,y as g,x as h,C as i,_ as l,S as m,E as n,u as o,b as p,h as r,f as s,g as t,w as u};

View File

@ -1 +1 @@
import{I as e,L as t}from"./index-CFmEgVyi.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-GGN4sgsJ.js";var n=encodeURIComponent,r=t=>e.get(`/c2/listeners`,t),i=t=>e.post(`/c2/listeners`,t),a=(t,r)=>e.put(`/c2/listeners/${n(t)}`,r),o=t=>e.del(`/c2/listeners/${n(t)}`),s=t=>e.post(`/c2/listeners/${n(t)}/start`,{}),c=t=>e.post(`/c2/listeners/${n(t)}/stop`,{}),l=t=>e.get(`/c2/sessions`,t),u=t=>e.get(`/c2/sessions/${n(t)}`),d=t=>e.del(`/c2/sessions/${n(t)}`),f=t=>e.del(`/c2/sessions`,{body:{ids:t}}),p=(t,{sleepSeconds:r,jitterPercent:i})=>e.put(`/c2/sessions/${n(t)}/sleep`,{sleep_seconds:r,jitter_percent:i}),m=(t,r)=>e.put(`/c2/sessions/${n(t)}/note`,{note:r}),h=t=>e.get(`/c2/tasks`,t),g=t=>e.get(`/c2/tasks/${n(t)}`),_=t=>e.post(`/c2/tasks`,t),v=(t,r)=>e.post(`/c2/sessions/${n(t)}/tasks`,r),y=t=>e.post(`/c2/tasks/${n(t)}/cancel`,{}),b=(t,r=30)=>e.get(`/c2/tasks/${n(t)}/wait`,{timeout:r},{timeout:(r+10)*1e3}),x=t=>e.del(`/c2/tasks`,{body:{ids:t}}),S=(e,r)=>t(`/c2/tasks/${n(e)}/result-file`,{filename:r}),C=t=>e.post(`/c2/payloads/oneliner`,t),w=t=>e.post(`/c2/payloads/build`,t),T=(e,r)=>t(`/c2/payloads/${n(e)}/download`,{filename:r}),E=t=>e.get(`/c2/events`,t),D=t=>e.del(`/c2/events`,{body:{ids:t}}),O=()=>e.get(`/c2/profiles`),k=t=>e.post(`/c2/profiles`,t),A=(t,r)=>e.put(`/c2/profiles/${n(t)}`,r),j=t=>e.del(`/c2/profiles/${n(t)}`);async function M(){try{let t=await e.get(`/projects`,{limit:200});return Array.isArray(t?.projects)?t.projects:[]}catch{return[]}}export{b as A,h as C,c as D,s as E,a as O,l as S,p as T,g as _,k as a,O as b,D as c,d,f,u as g,S as h,i,A as k,o as l,T as m,w as n,v as o,x as p,y as r,_ as s,C as t,j as u,E as v,m as w,M as x,r as y};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

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-CFmEgVyi.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-GGN4sgsJ.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-CFmEgVyi.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-GGN4sgsJ.js";var u=e(t(),1),d=e(n(),1),{Text:f}=r,p=120,m=4e3;function h({visible:e,project:t,onCancel:n,onSaved:r}){let h=o(),g=(0,u.useId)(),[_,v]=(0,u.useState)(!1),[y,b]=(0,u.useState)(null),x=!!t?.id;return(0,u.useEffect)(()=>{b(null)},[e,t?.id]),(0,d.jsxs)(s,{visible:e,width:560,closable:!_,closeOnEsc:!_,onCancel:n,cancelButtonProps:{disabled:_},title:x?h(`projects.modalEditTitle`,null,`编辑项目`):h(`projects.modalNewTitle`,null,`新建项目`),formId:g,okText:x?h(`projects.saveChanges`,null,`保存修改`):h(`projects.createProject`,null,`创建项目`),confirmLoading:_,children:[(0,d.jsx)(f,{type:`tertiary`,size:`small`,children:x?h(`projects.modalEditSubtitle`,null,`修改项目名称与描述`):h(`projects.modalNewSubtitle`,null,`创建后可绑定对话,跨会话共享事实黑板`)}),(0,d.jsxs)(i,{id:g,onSubmit:async e=>{if(!_){v(!0),b(null);try{let n={name:e.name.trim(),description:(e.description||``).slice(0,m)},i=x?await a.put(`/projects/${t.id}`,n):await a.post(`/projects`,n);l(x?h(`projects.saved`,null,`已保存`):h(`projects.createProject`,null,`创建项目`)),r?.(i)}catch(e){b(e)}finally{v(!1)}}},initValues:{name:t?.name||``,description:t?.description||``},children:[(0,d.jsx)(i.Input,{id:`${g}-name`,field:`name`,maxLength:p,label:h(`projects.projectName`,null,`项目名称`),placeholder:h(`projects.projectNamePlaceholder`,null,`例如:某客户 Web 渗透`),rules:[{required:!0,whitespace:!0,message:h(`projects.enterProjectName`,null,`请输入项目名称`)}]}),(0,d.jsx)(i.TextArea,{id:`${g}-description`,field:`description`,rows:4,maxCount:m,label:h(`projects.projectDescription`,null,`项目描述`),placeholder:h(`projects.projectDescriptionPlaceholder`,null,`客户/任务备注、协作说明…`),extraText:h(`projects.descriptionLengthHint`,null,`仅供团队成员查阅,Agent 不会读取;需让 Agent 知晓的内容请写入事实黑板`)}),(0,d.jsx)(c,{error:y})]},`${e}-${t?.id||`new`}`)]})}export{h as t};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -1 +1 @@
import{n as e}from"./rolldown-runtime-WkwZ5CU-.js";import{F as t,L as n,W as r,jt as i,st as a}from"./semi-CHxO7u8f.js";import{D as o,F as s,I as c,O as l,P as u,_ as d,a as f,l as p,m,p as h,s as g,x as _,y as v}from"./index-CFmEgVyi.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-GGN4sgsJ.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-CFmEgVyi.js"></script>
<script type="module" crossorigin src="/static/app/assets/index-GGN4sgsJ.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">

View File

@ -26,7 +26,7 @@
"chatModuleMissing": "لم يتمّ تحميل وحدة المحادثة بعد"
},
"common": {
"expandPanel": "توسيع اللوحة",
"expandPanel": "توسيع اللوحة",
"ok": "موافق",
"cancel": "إلغاء",
"refresh": "تحديث",
@ -4840,5 +4840,17 @@
"saveAuditModel": "حفظ نموذج التدقيق",
"auditModelSaved": "تم حفظ نموذج التدقيق",
"auditSavedApplyFailed": "تم حفظ نموذج التدقيق، لكن فشل تطبيق الإعدادات."
},
"updateUi": {
"targetBranch": "الفرع المستهدف",
"branchSwitchPending": "بانتظار التبديل",
"followDefaultBranch": "اتباع الفرع الافتراضي",
"targetBranchLabel": "الفرع المستهدف (فارغ = الفرع الافتراضي للمستودع)",
"targetBranchPlaceholder": "اتركه فارغاً أو اختر/أدخل اسم الفرع",
"defaultBranchTag": "افتراضي",
"fetchBranches": "جلب الفروع البعيدة",
"branchesLoaded": "تم جلب {{n}} فرعاً",
"sourceSaveBranchHint": "يحفظ update.repo و update.branch في ملف الإعدادات وسيتم التبديل عند التحديث القادم.",
"branchSwitchTag": "تبديل الفرع: {{from}} → {{to}}"
}
}

View File

@ -3313,7 +3313,17 @@
"build": "Build",
"done": "Complete",
"version": "Save version information"
}
},
"targetBranch": "Target Branch",
"branchSwitchPending": "Switch Pending",
"followDefaultBranch": "Follow default branch",
"targetBranchLabel": "Target Branch (empty = repository default branch)",
"targetBranchPlaceholder": "Leave empty for default branch, or select/type a branch",
"defaultBranchTag": "Default",
"fetchBranches": "Fetch Branches",
"branchesLoaded": "Loaded {{n}} remote branches",
"sourceSaveBranchHint": "Saving writes update.repo and update.branch to config.yaml; the next Update switches to that branch.",
"branchSwitchTag": "Switch branch: {{from}} → {{to}}"
},
"settingsBasic": {
"basicTitle": "Basic settings",

View File

@ -5875,5 +5875,17 @@
"saveAuditModel": "Сохранить модель аудита",
"auditModelSaved": "Модель аудита сохранена",
"auditSavedApplyFailed": "Модель аудита записана в конфигурацию, но применение не удалось."
},
"updateUi": {
"targetBranch": "Целевая ветка",
"branchSwitchPending": "Ожидает переключения",
"followDefaultBranch": "Ветка по умолчанию",
"targetBranchLabel": "Целевая ветка (пусто = ветка по умолчанию)",
"targetBranchPlaceholder": "Оставьте пустым или выберите/введите ветку",
"defaultBranchTag": "По умолчанию",
"fetchBranches": "Получить ветки",
"branchesLoaded": "Загружено веток: {{n}}",
"sourceSaveBranchHint": "Сохранение запишет update.repo и update.branch в config.yaml; следующее обновление переключит ветку.",
"branchSwitchTag": "Переключение ветки: {{from}} → {{to}}"
}
}

View File

@ -3301,7 +3301,17 @@
"build": "编译",
"done": "完成",
"version": "保存版本信息"
}
},
"targetBranch": "目标分支",
"branchSwitchPending": "待切换",
"followDefaultBranch": "跟随仓库默认分支",
"targetBranchLabel": "目标分支(留空 = 跟随仓库默认分支)",
"targetBranchPlaceholder": "留空跟随默认分支,或选择/输入分支名",
"defaultBranchTag": "默认",
"fetchBranches": "获取远端分支",
"branchesLoaded": "已获取 {{n}} 个远端分支",
"sourceSaveBranchHint": "保存会修改配置文件中的 update.repo 与 update.branch,下次点击「更新」时自动拉取并切换至该分支。",
"branchSwitchTag": "切换分支:{{from}} → {{to}}"
},
"settingsBasic": {
"basicTitle": "基本设置",