diff --git a/db/chat_mentions.go b/db/chat_mentions.go index e201038..a0ceedd 100644 --- a/db/chat_mentions.go +++ b/db/chat_mentions.go @@ -34,7 +34,7 @@ type chatMentionCursor struct { func ValidChatMentionKind(kind string) bool { switch kind { - case "task", "finding", "company", "asset", "endpoint", "ip", "app", "root_domain", "subdomain", "service": + case "task", "schedule", "finding", "company", "asset", "endpoint", "ip", "app", "root_domain", "subdomain", "service": return true } return false @@ -76,6 +76,21 @@ SELECT kind, id, left(label, 160), left(description, 240) FROM ( AND ($4::bigint=0 OR (id::text=$2)<$6 OR ((id::text=$2)=$6 AND (id<$4 OR (id=$4 AND 'task'>$5)))) ORDER BY (id::text=$2) DESC, id DESC LIMIT 21) UNION ALL + (SELECT 'schedule' AS kind, id, + COALESCE(NULLIF(name,''), '计划任务 #'||id::text) AS label, + concat_ws(' · ', + status, + CASE WHEN schedule_type='once' + THEN concat_ws(' ~ ', to_char(run_date,'YYYY-MM-DD'), to_char(end_date,'YYYY-MM-DD')) + ELSE 'weekly:'||weekdays END, + to_char(start_time,'HH24:MI') || CASE WHEN end_time IS NOT NULL THEN '-'||to_char(end_time,'HH24:MI') ELSE '+' END, + NULLIF(left(remark, 120), '') + ) AS description + FROM task_schedules WHERE ($1='' OR $1='schedule') AND + ($2='' OR id::text=$2 OR concat_ws(' ', name, remark, schedule_type, status) ILIKE $3) + AND ($4::bigint=0 OR (id::text=$2)<$6 OR ((id::text=$2)=$6 AND (id<$4 OR (id=$4 AND 'schedule'>$5)))) + ORDER BY (id::text=$2) DESC, id DESC LIMIT 21) + UNION ALL (SELECT 'finding' AS kind, id, COALESCE(NULLIF(name,''), vulnclass) AS label, concat_ws(' · ', severity, status, left(summary, 160)) AS description FROM findings WHERE ($1='' OR $1='finding') AND diff --git a/server/chat_mentions.go b/server/chat_mentions.go index 70a7000..24cecb2 100644 --- a/server/chat_mentions.go +++ b/server/chat_mentions.go @@ -1,6 +1,7 @@ package server import ( + "database/sql" "encoding/json" "errors" "fmt" @@ -8,6 +9,7 @@ import ( "regexp" "strconv" "strings" + "time" "unicode/utf8" "github.com/Autumn-27/artex/db" @@ -17,11 +19,11 @@ const maxChatMentions = 10 // The visible token survives drafts, uploads, retries and conversation history. // Labels are only for display: the server trusts only the type and numeric ID. -var chatMentionPattern = regexp.MustCompile(`@\[(task|finding|asset|company|endpoint|ip|app|root_domain|subdomain|service|任务|漏洞|资产|企业|接口|IP|应用|域名|子域名|服务)#([0-9]+)(?: [^\]\r\n]*)?\]`) +var chatMentionPattern = regexp.MustCompile(`@\[(schedule|task|finding|asset|company|endpoint|ip|app|root_domain|subdomain|service|计划任务|计划|任务|漏洞|资产|企业|接口|IP|应用|域名|子域名|服务)#([0-9]+)(?: [^\]\r\n]*)?\]`) var chatMentionKinds = map[string]string{ - "任务": "task", "漏洞": "finding", "资产": "asset", "企业": "company", "接口": "endpoint", + "任务": "task", "计划任务": "schedule", "计划": "schedule", "漏洞": "finding", "资产": "asset", "企业": "company", "接口": "endpoint", "IP": "ip", "应用": "app", "域名": "root_domain", "子域名": "subdomain", "服务": "service", - "task": "task", "finding": "finding", "asset": "asset", "company": "company", "endpoint": "endpoint", + "task": "task", "schedule": "schedule", "finding": "finding", "asset": "asset", "company": "company", "endpoint": "endpoint", "ip": "ip", "app": "app", "root_domain": "root_domain", "subdomain": "subdomain", "service": "service", } @@ -164,6 +166,31 @@ func loadChatMention(pg *db.DB, ref chatMentionRef) (any, error) { } } return map[string]any{"task": t, "proxy_route": route}, nil + case "schedule": + item, err := pg.GetTaskSchedule(ref.ID) + if err != nil { + if errors.Is(err, sql.ErrNoRows) { + return nil, nil + } + return nil, err + } + if item == nil { + return nil, nil + } + safe := *item + safe.ProxyURL = maskSecrets(safe.ProxyURL) + out := map[string]any{ + "schedule": safe, + "timezone": scheduleLocation(item.TimezoneMode).String(), + "server_time": time.Now().Format(time.RFC3339), + } + if stats, err := pg.ScheduleRunStats(item.ID); err == nil { + out["run_count"] = stats.RunCount + if stats.LastRunAt != nil { + out["last_run_at"] = stats.LastRunAt + } + } + return out, nil case "finding": f, err := pg.GetFinding(ref.ID) if err != nil || f == nil { diff --git a/server/proxy_routes.go b/server/proxy_routes.go index 08bd24a..be6445b 100644 --- a/server/proxy_routes.go +++ b/server/proxy_routes.go @@ -184,17 +184,31 @@ func (s *Server) resolveContainerUpstream(src traffic.SourceIdentity) (*url.URL, } } -type proxyRouteValidationError struct{ msg string } +type proxyRouteValidationError struct { + code string + msg string + params map[string]any +} func (e *proxyRouteValidationError) Error() string { return e.msg } +func writeProxyRouteErr(w http.ResponseWriter, status int, err error) { + if verr, ok := err.(*proxyRouteValidationError); ok && verr.code != "" { + writeProductError(w, status, verr.code, verr.msg, verr.params) + return + } + writeErr(w, status, err.Error()) +} func (s *Server) validateAndNormalizeProxyRoute(req ProxyRouteInput, prev *ContainerProxyRoute) (ContainerProxyRoute, error) { mode := strings.ToLower(strings.TrimSpace(req.Mode)) if mode == "" { mode = "inherit" } if mode != "inherit" && mode != "direct" && mode != "pool" && mode != "proxy" { - return ContainerProxyRoute{}, &proxyRouteValidationError{"mode must be inherit, direct, pool, or proxy"} + return ContainerProxyRoute{}, &proxyRouteValidationError{ + code: "proxy_route_invalid_mode", + msg: "mode must be inherit, direct, pool, or proxy", + } } route := ContainerProxyRoute{ Mode: mode, @@ -209,7 +223,10 @@ func (s *Server) validateAndNormalizeProxyRoute(req ProxyRouteInput, prev *Conta route.ProxyURL = "" case "pool": if _, raw := s.m.ActivePoolRawURL(); raw == "" { - return ContainerProxyRoute{}, &proxyRouteValidationError{"代理池暂无可用节点,请先在代理设置中添加并启用节点"} + return ContainerProxyRoute{}, &proxyRouteValidationError{ + code: "proxy_pool_no_available_nodes", + msg: "代理池暂无可用节点,请先在代理设置中添加并启用节点", + } } route.ProxyPoolID = "" route.ProxyURL = "" @@ -217,7 +234,11 @@ func (s *Server) validateAndNormalizeProxyRoute(req ProxyRouteInput, prev *Conta if route.ProxyPoolID != "" { id, raw := s.resolvePoolEntryByIDOrName(route.ProxyPoolID) if raw == "" { - return ContainerProxyRoute{}, &proxyRouteValidationError{fmt.Sprintf("proxy_pool_id %q not found", route.ProxyPoolID)} + return ContainerProxyRoute{}, &proxyRouteValidationError{ + code: "proxy_pool_node_not_found", + msg: fmt.Sprintf("proxy_pool_id %q not found", route.ProxyPoolID), + params: map[string]any{"id": route.ProxyPoolID}, + } } route.ProxyPoolID = id route.ProxyURL = "" @@ -227,7 +248,11 @@ func (s *Server) validateAndNormalizeProxyRoute(req ProxyRouteInput, prev *Conta route.ProxyURL = prev.ProxyURL } if _, err := traffic.ValidateProxyURL(route.ProxyURL); err != nil { - return ContainerProxyRoute{}, &proxyRouteValidationError{err.Error()} + return ContainerProxyRoute{}, &proxyRouteValidationError{ + code: "proxy_route_invalid_url", + msg: err.Error(), + params: map[string]any{"detail": err.Error()}, + } } } } @@ -238,7 +263,10 @@ func (s *Server) setContainerProxyRoute(scope, ownerID string, req ProxyRouteInp scope = strings.ToLower(strings.TrimSpace(scope)) ownerID = strings.TrimSpace(ownerID) if (scope != "task" && scope != "session") || ownerID == "" { - return ContainerProxyRoute{}, &proxyRouteValidationError{"invalid scope or owner_id (scope must be task or session)"} + return ContainerProxyRoute{}, &proxyRouteValidationError{ + code: "proxy_route_invalid_target", + msg: "invalid scope or owner_id (scope must be task or session)", + } } rt := s.ensureRouteRuntime() key := scope + ":" + ownerID @@ -510,7 +538,7 @@ func (s *Server) getProxyRoute(w http.ResponseWriter, r *http.Request) { scope := strings.ToLower(strings.TrimSpace(r.PathValue("scope"))) ownerID := strings.TrimSpace(r.PathValue("owner_id")) if (scope != "task" && scope != "session") || ownerID == "" { - writeErr(w, http.StatusBadRequest, "invalid scope or owner_id (scope must be task or session)") + writeProductError(w, http.StatusBadRequest, "proxy_route_invalid_target", "invalid scope or owner_id (scope must be task or session)", nil) return } item, globalDisplay := s.containerProxyRouteView(scope, ownerID) @@ -539,7 +567,7 @@ func (s *Server) putProxyRoute(w http.ResponseWriter, r *http.Request) { route, err := s.setContainerProxyRoute(scope, ownerID, req) if err != nil { if _, ok := err.(*proxyRouteValidationError); ok { - writeErr(w, http.StatusBadRequest, err.Error()) + writeProxyRouteErr(w, http.StatusBadRequest, err) return } writeErr(w, http.StatusInternalServerError, err.Error()) diff --git a/server/proxy_routes_feature_test.go b/server/proxy_routes_feature_test.go index 31b95db..7d65c05 100644 --- a/server/proxy_routes_feature_test.go +++ b/server/proxy_routes_feature_test.go @@ -436,3 +436,61 @@ func TestProxyScheduleAndTaskMentionWithPostgres(t *testing.T) { t.Fatalf("expected task snapshot with proxy_route in mention message, got: %s", injected) } } + +func TestValidateScheduleProxyUnchangedAndErrorCodes(t *testing.T) { + m := &Manager{ + tasks: map[string]*Task{}, + proxyPool: &proxyPoolState{entries: nil}, + } + s := &Server{m: m} + s.initProxyRoutesAndGateway() + + // 1. Existing schedule with proxy_mode=pool can still be rescheduled/updated when pool has no active nodes. + existingPool := &db.TaskSchedule{ID: 9, Name: "nightly", ProxyMode: "pool"} + inUnchanged := db.TaskScheduleInput{Name: "nightly", ProxyMode: "pool"} + if err := s.validateScheduleProxy(&inUnchanged, existingPool); err != nil { + t.Fatalf("expected unchanged pool schedule update to succeed with empty pool, got: %v", err) + } + if inUnchanged.ProxyMode != "pool" || inUnchanged.ProxyPoolID != "" || inUnchanged.ProxyURL != "" { + t.Fatalf("unexpected normalized unchanged pool input: %+v", inUnchanged) + } + + // 2. Existing schedule with masked custom proxy URL keeps raw secret when unchanged. + existingURL := &db.TaskSchedule{ID: 10, Name: "custom", ProxyMode: "proxy", ProxyURL: "http://alice:secret@127.0.0.1:8080"} + inMasked := db.TaskScheduleInput{Name: "custom", ProxyMode: "proxy", ProxyURL: "http://alice:***@127.0.0.1:8080"} + if err := s.validateScheduleProxy(&inMasked, existingURL); err != nil { + t.Fatalf("expected unchanged masked proxy URL update to succeed, got: %v", err) + } + if inMasked.ProxyURL != existingURL.ProxyURL { + t.Fatalf("expected raw proxy URL preserved, got %q", inMasked.ProxyURL) + } + + // 3. Newly selecting mode=pool with empty pool fails with structured error code. + existingInherit := &db.TaskSchedule{ID: 11, Name: "inherit", ProxyMode: "inherit"} + inSwitchToPool := db.TaskScheduleInput{Name: "inherit", ProxyMode: "pool"} + err := s.validateScheduleProxy(&inSwitchToPool, existingInherit) + verr, ok := err.(*proxyRouteValidationError) + if !ok || verr.code != "proxy_pool_no_available_nodes" { + t.Fatalf("expected proxy_pool_no_available_nodes error, got %T %v", err, err) + } + + // 4. HTTP PUT /api/proxy/routes/task/5 returns structured code for i18n clients. + req := httptest.NewRequest(http.MethodPut, "/api/proxy/routes/task/5", bytes.NewBufferString(`{"mode":"pool"}`)) + req.SetPathValue("scope", "task") + req.SetPathValue("owner_id", "5") + rec := httptest.NewRecorder() + s.putProxyRoute(rec, req) + if rec.Code != http.StatusBadRequest { + t.Fatalf("expected 400, got %d %s", rec.Code, rec.Body.String()) + } + var payload struct { + Error string `json:"error"` + Code string `json:"code"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &payload); err != nil { + t.Fatalf("decode error payload: %v", err) + } + if payload.Code != "proxy_pool_no_available_nodes" || payload.Error == "" { + t.Fatalf("unexpected error payload: %+v", payload) + } +} diff --git a/server/schedule_tools_test.go b/server/schedule_tools_test.go index 641c41e..9dc2a70 100644 --- a/server/schedule_tools_test.go +++ b/server/schedule_tools_test.go @@ -12,6 +12,21 @@ import ( "github.com/Autumn-27/artex/db" ) +func TestChatMentionScheduleParsing(t *testing.T) { + refs, err := parseChatMentions("请修改 @[计划任务#3 夜间扫描] 和 @[schedule#3 重复] 以及 @[schedule#9 应急复测] 和 @[计划#12 周末巡检]") + if err != nil { + t.Fatalf("parseChatMentions error: %v", err) + } + if len(refs) != 3 { + t.Fatalf("expected 3 deduplicated schedule refs, got %+v", refs) + } + for i, wantID := range []int64{3, 9, 12} { + if refs[i].Kind != "schedule" || refs[i].ID != wantID { + t.Fatalf("ref[%d] = %+v, want schedule #%d", i, refs[i], wantID) + } + } +} + func TestChatScheduleToolsAndServerClock(t *testing.T) { dsn := strings.TrimSpace(os.Getenv("ARTEX_PG_DSN")) @@ -95,6 +110,31 @@ func TestChatScheduleToolsAndServerClock(t *testing.T) { t.Fatalf("update_task_schedule failed: err=%v res=%+v", err, updRes) } updText := "" + // 2b. Search schedule mentions via DB and compose @[schedule#ID] snapshot. + page, err := pg.SearchChatMentionsPage(context.Background(), "schedule", "工作日", "") + if err != nil { + t.Fatalf("SearchChatMentionsPage(schedule): %v", err) + } + foundMention := false + for _, item := range page.Items { + if item.Kind == "schedule" && item.ID == schedID { + foundMention = true + if !strings.Contains(item.Description, "18:00-23:45") { + t.Fatalf("expected schedule time window in mention description, got %+v", item) + } + } + } + if !foundMention { + t.Fatalf("expected schedule #%d in SearchChatMentionsPage results, got %+v", schedID, page.Items) + } + injected, err := composeChatMentionMessage(pg, fmt.Sprintf("把 @[schedule#%d 工作日夜间扫描] 改成 23:45 结束", schedID)) + if err != nil { + t.Fatalf("composeChatMentionMessage(schedule): %v", err) + } + if !strings.Contains(injected, "工作日夜间扫描") || !strings.Contains(injected, `"proxy_mode":"pool"`) || !strings.Contains(injected, `"server_time"`) { + t.Fatalf("unexpected injected schedule snapshot: %s", injected) + } + for _, b := range updRes.Content { updText += b.Text } @@ -122,4 +162,8 @@ func TestChatScheduleToolsAndServerClock(t *testing.T) { if err != nil || delRes.IsError { t.Fatalf("delete_task_schedule failed: err=%v res=%+v", err, delRes) } + // Verify deleted schedule mention returns a clean input error. + if _, err := composeChatMentionMessage(pg, fmt.Sprintf("查看 @[schedule#%d 已删]", schedID)); err == nil { + t.Fatalf("expected error for deleted schedule mention") + } } diff --git a/server/schedules.go b/server/schedules.go index 0cee5ea..af93552 100644 --- a/server/schedules.go +++ b/server/schedules.go @@ -56,18 +56,55 @@ func (s *Server) scheduleInput(req scheduleRequest, existing *db.TaskSchedule) d } func (s *Server) validateScheduleProxy(in *db.TaskScheduleInput, existing *db.TaskSchedule) error { + inMode := strings.ToLower(strings.TrimSpace(in.ProxyMode)) + if inMode == "" { + inMode = "inherit" + } + inPoolID := strings.TrimSpace(in.ProxyPoolID) + inURL := strings.TrimSpace(in.ProxyURL) + var prev *ContainerProxyRoute - if existing != nil && existing.ProxyURL != "" { + if existing != nil { + oldMode := strings.ToLower(strings.TrimSpace(existing.ProxyMode)) + if oldMode == "" { + oldMode = "inherit" + } + oldPoolID := strings.TrimSpace(existing.ProxyPoolID) + oldURL := strings.TrimSpace(existing.ProxyURL) prev = &ContainerProxyRoute{ - Mode: existing.ProxyMode, - ProxyPoolID: existing.ProxyPoolID, - ProxyURL: existing.ProxyURL, + Mode: oldMode, + ProxyPoolID: oldPoolID, + ProxyURL: oldURL, + } + // Allow editing/rescheduling an existing plan without re-validating unchanged proxy routes + // (e.g. dragging a schedule whose proxy_mode is already "pool" when the live pool is temporarily empty). + if inMode == oldMode { + switch oldMode { + case "inherit", "direct", "pool": + in.ProxyMode = oldMode + in.ProxyPoolID = "" + in.ProxyURL = "" + return nil + case "proxy": + if oldPoolID != "" && inPoolID == oldPoolID && inURL == "" { + in.ProxyMode = "proxy" + in.ProxyPoolID = oldPoolID + in.ProxyURL = "" + return nil + } + if oldPoolID == "" && inPoolID == "" && oldURL != "" && (inURL == oldURL || strings.Contains(inURL, "***")) { + in.ProxyMode = "proxy" + in.ProxyPoolID = "" + in.ProxyURL = oldURL + return nil + } + } } } norm, err := s.validateAndNormalizeProxyRoute(ProxyRouteInput{ - Mode: in.ProxyMode, - ProxyPoolID: in.ProxyPoolID, - ProxyURL: in.ProxyURL, + Mode: inMode, + ProxyPoolID: inPoolID, + ProxyURL: inURL, }, prev) if err != nil { return err @@ -197,7 +234,7 @@ func (s *Server) createSchedule(w http.ResponseWriter, r *http.Request) { } input := s.scheduleInput(req, nil) if err := s.validateScheduleProxy(&input, nil); err != nil { - writeErr(w, 400, err.Error()) + writeProxyRouteErr(w, 400, err) return } item, err := s.m.pg.CreateTaskSchedule(input) @@ -230,7 +267,7 @@ func (s *Server) updateSchedule(w http.ResponseWriter, r *http.Request) { } input := s.scheduleInput(req, old) if err := s.validateScheduleProxy(&input, old); err != nil { - writeErr(w, 400, err.Error()) + writeProxyRouteErr(w, 400, err) return } item, err := s.m.pg.UpdateTaskSchedule(id, input) diff --git a/server/server.go b/server/server.go index 9935550..f37817a 100644 --- a/server/server.go +++ b/server/server.go @@ -1833,6 +1833,8 @@ type createTaskReq struct { type taskCreateError struct { Status int Msg string + Code string + Params map[string]any } func (s *Server) createTask(w http.ResponseWriter, r *http.Request) { @@ -1843,7 +1845,11 @@ func (s *Server) createTask(w http.ResponseWriter, r *http.Request) { } t, cerr := s.createTaskFromRequest(req) if cerr != nil { - writeErr(w, cerr.Status, cerr.Msg) + if cerr.Code != "" { + writeProductError(w, cerr.Status, cerr.Code, cerr.Msg, cerr.Params) + } else { + writeErr(w, cerr.Status, cerr.Msg) + } return } dto := taskDTO(t, s.resolvedTaskStatus(t)) @@ -1862,48 +1868,51 @@ func (s *Server) createTaskFromRequest(req createTaskReq) (*Task, *taskCreateErr req.LLMProfileIDs = []int64{*req.LLMProfileID} } if err := s.validateTaskProfileIDs(req.LLMProfileIDs); err != nil { - return nil, &taskCreateError{400, err.Error()} + return nil, &taskCreateError{Status: 400, Msg: err.Error()} } if err := db.NormalizeNoResultOptions(&db.TaskCreateOptions{NoResultSeconds: req.NoResultSeconds, NoResultMinFindings: req.NoResultMinFindings, NoResultMinSeverity: req.NoResultMinSeverity}); err != nil { - return nil, &taskCreateError{400, err.Error()} + return nil, &taskCreateError{Status: 400, Msg: err.Error()} } if req.TimeoutSeconds < 0 { req.TimeoutSeconds = 0 } if len(req.SourceTaskIDs) > db.MaxTaskSourceCount { - return nil, &taskCreateError{400, fmt.Sprintf("关联任务最多选择 %d 个", db.MaxTaskSourceCount)} + return nil, &taskCreateError{Status: 400, Msg: fmt.Sprintf("关联任务最多选择 %d 个", db.MaxTaskSourceCount)} } sourceIDs := make([]int64, 0, len(req.SourceTaskIDs)) seenSources := map[int64]bool{} for _, raw := range req.SourceTaskIDs { id, err := strconv.ParseInt(strings.TrimSpace(raw), 10, 64) if err != nil || id <= 0 || seenSources[id] { - return nil, &taskCreateError{400, "关联任务 id 无效或重复"} + return nil, &taskCreateError{Status: 400, Msg: "关联任务 id 无效或重复"} } if _, ok := s.m.Task(strconv.FormatInt(id, 10)); !ok { - return nil, &taskCreateError{400, fmt.Sprintf("关联任务 #%d 不存在", id)} + return nil, &taskCreateError{Status: 400, Msg: fmt.Sprintf("关联任务 #%d 不存在", id)} } seenSources[id] = true sourceIDs = append(sourceIDs, id) } companyIDs, err := db.NormalizeTaskCompanyIDs(req.CompanyIDs) if err != nil { - return nil, &taskCreateError{400, fmt.Sprintf("关联企业无效:最多选择 %d 个有效企业", db.MaxTaskCompanyCount)} + return nil, &taskCreateError{Status: 400, Msg: fmt.Sprintf("关联企业无效:最多选择 %d 个有效企业", db.MaxTaskCompanyCount)} } req.CompanyIDs = companyIDs interceptRules, err := buildTaskInterceptRules(req.InterceptRules) if err != nil { - return nil, &taskCreateError{400, "任务级拦截规则无效:" + err.Error()} + return nil, &taskCreateError{Status: 400, Msg: "任务级拦截规则无效:" + err.Error()} } var schedule *db.TaskScheduleInput if req.Schedule != nil { input := s.scheduleInput(*req.Schedule, nil) input.TaskIDs = nil if err := db.ValidateTaskScheduleInput(input); err != nil { - return nil, &taskCreateError{400, err.Error()} + return nil, &taskCreateError{Status: 400, Msg: err.Error()} } if err := s.validateScheduleProxy(&input, nil); err != nil { - return nil, &taskCreateError{400, err.Error()} + if verr, ok := err.(*proxyRouteValidationError); ok { + return nil, &taskCreateError{Status: 400, Msg: verr.msg, Code: verr.code, Params: verr.params} + } + return nil, &taskCreateError{Status: 400, Msg: err.Error()} } schedule = &input } @@ -1911,7 +1920,10 @@ func (s *Server) createTaskFromRequest(req createTaskReq) (*Task, *taskCreateErr if req.ProxyRoute != nil { norm, err := s.validateAndNormalizeProxyRoute(*req.ProxyRoute, nil) if err != nil { - return nil, &taskCreateError{400, "任务代理配置无效:" + err.Error()} + if verr, ok := err.(*proxyRouteValidationError); ok { + return nil, &taskCreateError{Status: 400, Msg: verr.msg, Code: verr.code, Params: verr.params} + } + return nil, &taskCreateError{Status: 400, Msg: "任务代理配置无效:" + err.Error()} } if norm.Mode != "inherit" { validatedProxy = &ProxyRouteInput{ @@ -1935,13 +1947,13 @@ func (s *Server) createTaskFromRequest(req createTaskReq) (*Task, *taskCreateErr } remark, err := normalizeRemark(req.Remark) if err != nil { - return nil, &taskCreateError{400, err.Error()} + return nil, &taskCreateError{Status: 400, Msg: err.Error()} } if req.WorkerCount < 0 { - return nil, &taskCreateError{400, "Worker 运行数量不能为负数"} + return nil, &taskCreateError{Status: 400, Msg: "Worker 运行数量不能为负数"} } if req.WorkerCount > db.MaxTaskWorkerCount { - return nil, &taskCreateError{400, fmt.Sprintf("Worker 运行数量最多 %d", db.MaxTaskWorkerCount)} + return nil, &taskCreateError{Status: 400, Msg: fmt.Sprintf("Worker 运行数量最多 %d", db.MaxTaskWorkerCount)} } t, err := s.m.CreateTaskWithOptions(req.Description, req.Goal, db.TaskCreateOptions{ Schedule: schedule, @@ -1957,12 +1969,12 @@ func (s *Server) createTaskFromRequest(req createTaskReq) (*Task, *taskCreateErr }) if err != nil { if errors.Is(err, db.ErrTaskCategoryInvalid) || errors.Is(err, db.ErrTaskCategoryNotFound) { - return nil, &taskCreateError{400, "任务分类不存在或无效"} + return nil, &taskCreateError{Status: 400, Msg: "任务分类不存在或无效"} } if errors.Is(err, db.ErrTaskCompanyIDsInvalid) || errors.Is(err, db.ErrTaskCompanyNotFound) { - return nil, &taskCreateError{400, "关联企业不存在或无效"} + return nil, &taskCreateError{Status: 400, Msg: "关联企业不存在或无效"} } - return nil, &taskCreateError{500, err.Error()} + return nil, &taskCreateError{Status: 500, Msg: err.Error()} } if newDesc, newGoal, copied := transferDraftUploadsToTask(s.m.dir, t.ID, req.Description, req.Goal); copied > 0 { req.Description, req.Goal = newDesc, newGoal diff --git a/web/src/app/(main)/system/proxy/_components/container-routes-tab.tsx b/web/src/app/(main)/system/proxy/_components/container-routes-tab.tsx index 342758e..e99bc20 100644 --- a/web/src/app/(main)/system/proxy/_components/container-routes-tab.tsx +++ b/web/src/app/(main)/system/proxy/_components/container-routes-tab.tsx @@ -13,6 +13,7 @@ import { Label } from "@/components/ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; import { Switch } from "@/components/ui/switch"; import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table"; +import { localizedError } from "@/i18n/errors"; import { useLiveTranslation } from "@/i18n/use-live-translation"; import { api } from "@/lib/api"; import type { ContainerRouteStatusItem, ProxyPoolEntry, ProxyRoutesState } from "@/lib/types"; @@ -26,7 +27,7 @@ export function ContainerRoutesTab({ routesState: ProxyRoutesState | null; onRefresh: () => Promise; }) { - const { isEn, locale } = useLiveTranslation(); + const { isEn, locale, liveT } = useLiveTranslation(); const L = (zh: string, en: string) => (isEn ? en : zh); const formatProxyValue = (raw?: string) => { const clean = (raw ?? "").replace(/\s*\((全局|Global)\)\s*$/i, "").trim(); @@ -139,7 +140,7 @@ export function ContainerRoutesTab({ await onRefresh(); toast.success(L("容器出口路由已生效", "Container egress route saved")); } catch (err) { - toast.error(err instanceof Error ? err.message : String(err)); + toast.error(localizedError(err, liveT)); } finally { setSavingRoute(false); } @@ -165,7 +166,7 @@ export function ContainerRoutesTab({ await onRefresh(); toast.success(L("已更新容器出口路由", "Container egress route updated")); } catch (e) { - toast.error(e instanceof Error ? e.message : String(e)); + toast.error(localizedError(e, liveT)); } finally { setBusyKey(null); } @@ -179,7 +180,7 @@ export function ContainerRoutesTab({ await onRefresh(); toast.success(L("已恢复继承全局代理", "Reverted to global proxy")); } catch (e) { - toast.error(e instanceof Error ? e.message : String(e)); + toast.error(localizedError(e, liveT)); } finally { setBusyKey(null); } diff --git a/web/src/components/proxy-route-selector.tsx b/web/src/components/proxy-route-selector.tsx index d7bba3d..4bec279 100644 --- a/web/src/components/proxy-route-selector.tsx +++ b/web/src/components/proxy-route-selector.tsx @@ -13,6 +13,7 @@ import { Input } from "@/components/ui/input"; import { Label } from "@/components/ui/label"; import { Popover, PopoverContent, PopoverDescription, PopoverHeader, PopoverTitle, PopoverTrigger } from "@/components/ui/popover"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"; +import { localizedError } from "@/i18n/errors"; import { useLiveTranslation } from "@/i18n/use-live-translation"; import { api } from "@/lib/api"; import type { ProxyPoolEntry, TaskProxyRoute } from "@/lib/types"; @@ -198,7 +199,7 @@ export function ContainerProxyControlSection({ open: boolean; onSaved?: () => void; }) { - const { isEn } = useLiveTranslation(); + const { isEn, liveT } = useLiveTranslation(); const L = (zh: string, en: string) => (isEn ? en : zh); const [loading, setLoading] = React.useState(false); @@ -263,7 +264,7 @@ export function ContainerProxyControlSection({ toast.success(L("容器代理路由已更新并实时生效", "Container proxy route updated")); onSaved?.(); } catch (e) { - toast.error(e instanceof Error ? e.message : String(e)); + toast.error(localizedError(e, liveT)); } finally { setSaving(false); } diff --git a/web/src/i18n/error-messages.ts b/web/src/i18n/error-messages.ts index b68d2e5..fc44715 100644 --- a/web/src/i18n/error-messages.ts +++ b/web/src/i18n/error-messages.ts @@ -43,6 +43,26 @@ export const errorMessages = { "error.password_not_initialized": ["密码未初始化,请先设置密码", "Set up a password first"], "error.current_password_incorrect": ["当前密码错误", "The current password is incorrect"], "error.invalid_credentials": ["用户名或密码错误", "Incorrect username or password"], + "error.proxy_pool_no_available_nodes": [ + "代理池暂无可用节点,请先在代理设置中添加并启用节点", + "No available nodes in the proxy pool. Add and enable a node in Proxy Settings first.", + ], + "error.proxy_route_invalid_mode": [ + "代理模式无效,必须是 inherit、direct、pool 或 proxy", + "Invalid proxy mode. Must be inherit, direct, pool, or proxy.", + ], + "error.proxy_pool_node_not_found": [ + "未找到代理池节点:{{id}}", + "Proxy pool node not found: {{id}}", + ], + "error.proxy_route_invalid_target": [ + "无效的容器路由目标(scope 必须为 task 或 session)", + "Invalid container route target (scope must be task or session).", + ], + "error.proxy_route_invalid_url": [ + "代理地址无效:{{detail}}", + "Invalid proxy URL: {{detail}}", + ], "update.available": ["新版本", "Update available"], "update.hint": ["发现新版本 {{version}},点击前往更新", "Version {{version}} is available. Click to update."], } satisfies Record; diff --git a/web/src/i18n/i18n.test.cjs b/web/src/i18n/i18n.test.cjs index f707bed..bcef873 100644 --- a/web/src/i18n/i18n.test.cjs +++ b/web/src/i18n/i18n.test.cjs @@ -297,6 +297,17 @@ test("schedule windows, counts and stored system messages follow the selected la const original = "用户的计划与备注,包含 start_time"; assert.equal(en.scheduleErrorText(original), original); assert.equal(en.scheduleErrorText("任务 #42:unknown original detail"), "Task #42: unknown original detail"); + assert.equal( + en.scheduleErrorText("代理池暂无可用节点,请先在代理设置中添加并启用节点"), + "No available nodes in the proxy pool. Add and enable a node in Proxy Settings first.", + ); + const proxyErr = Object.assign(new Error("代理池暂无可用节点,请先在代理设置中添加并启用节点"), { + code: "proxy_pool_no_available_nodes", + }); + assert.equal( + localizedError(proxyErr, i18n.t.bind(i18n)), + "No available nodes in the proxy pool. Add and enable a node in Proxy Settings first.", + ); for (const [key, singular, plural] of [ ["schedule.started", "Started 1 task immediately", "Started 2 tasks immediately"], ["schedule.deleted", "Deleted 1 schedule", "Deleted 2 schedules"], diff --git a/web/src/i18n/messages.ts b/web/src/i18n/messages.ts index 1319e72..3f5349e 100644 --- a/web/src/i18n/messages.ts +++ b/web/src/i18n/messages.ts @@ -118,6 +118,7 @@ export const messages = { "auth.saving": ["保存中...", "Saving…"], "auth.setupAndLogin": ["设置密码并登录", "Set password and sign in"], "mention.task": ["任务", "Task"], + "mention.schedule": ["计划任务", "Schedule"], "mention.finding": ["漏洞", "Finding"], "mention.asset": ["资产", "Asset"], "mention.company": ["企业", "Company"], diff --git a/web/src/i18n/schedule-runtime.ts b/web/src/i18n/schedule-runtime.ts index 762bb97..0b8ec78 100644 --- a/web/src/i18n/schedule-runtime.ts +++ b/web/src/i18n/schedule-runtime.ts @@ -27,6 +27,7 @@ const messages: Record = { 立即运行: "schedule.runtime.runNow", "立即运行(显式恢复人工暂停)": "schedule.runtime.forceResume", 计划窗口: "schedule.runtime.window", + "代理池暂无可用节点,请先在代理设置中添加并启用节点": "error.proxy_pool_no_available_nodes", }; const taskMessages: [RegExp, string][] = [ [/^任务 #(\d+) 未找到$/, "schedule.runtime.taskNotFound"], diff --git a/web/src/lib/chat-mentions.test.mjs b/web/src/lib/chat-mentions.test.mjs index 577e664..c36829f 100644 --- a/web/src/lib/chat-mentions.test.mjs +++ b/web/src/lib/chat-mentions.test.mjs @@ -10,11 +10,16 @@ test("mention trigger supports Chinese and cursor placement without hijacking em }); test("categories, Chinese aliases, IP and keyword search", () => { - assert.equal(mentionSearch("").categories.length, 10); + assert.equal(mentionSearch("").categories.length, 11); assert.equal(mentionSearch("任").categories[0].kind, "task"); assert.equal(mentionSearch("任务").kind, "task"); assert.equal(mentionSearch("任务 5").query, "5"); assert.equal(mentionSearch("task 5").kind, "task"); + assert.equal(mentionSearch("计划").categories[0].kind, "schedule"); + assert.equal(mentionSearch("计划任务").kind, "schedule"); + assert.equal(mentionSearch("计划任务 夜间").query, "夜间"); + assert.equal(mentionSearch("schedule 2").kind, "schedule"); + assert.equal(mentionSearch("schedule 2").query, "2"); assert.equal(mentionSearch("漏").categories[0].kind, "finding"); assert.equal(mentionSearch("漏洞").kind, "finding"); assert.equal(mentionSearch("漏洞SQL注入").query, "SQL注入"); @@ -35,8 +40,8 @@ test("tokens roundtrip labels and removing one reference preserves its neighbors }); test("all mention kinds use stable tokens and recognize their legacy Chinese form", () => { - const kinds = ["task", "finding", "asset", "company", "endpoint", "ip", "app", "root_domain", "subdomain", "service"]; - const legacy = ["任务", "漏洞", "资产", "企业", "接口", "IP", "应用", "域名", "子域名", "服务"]; + const kinds = ["task", "schedule", "finding", "asset", "company", "endpoint", "ip", "app", "root_domain", "subdomain", "service"]; + const legacy = ["任务", "计划任务", "漏洞", "资产", "企业", "接口", "IP", "应用", "域名", "子域名", "服务"]; for (const [i, kind] of kinds.entries()) { const token = mentionToken({kind, id:i + 1, label:"Keep 用户名称"}); assert.ok(token.startsWith("@[" + kind + "#")); diff --git a/web/src/lib/chat-mentions.ts b/web/src/lib/chat-mentions.ts index 15bee99..ded9c20 100644 --- a/web/src/lib/chat-mentions.ts +++ b/web/src/lib/chat-mentions.ts @@ -1,5 +1,6 @@ export const mentionKinds = [ { kind: "task", label: "任务", alias: "task", english: "Task" }, + { kind: "schedule", label: "计划任务", alias: "schedule", english: "Schedule" }, { kind: "finding", label: "漏洞", alias: "finding", english: "Finding" }, { kind: "asset", label: "资产", alias: "asset", english: "Asset" }, { kind: "company", label: "企业", alias: "company", english: "Company" }, @@ -64,10 +65,11 @@ export function selectedMentions(value: string, translate?: (key: string) => str // Keep recognizing Chinese tokens in saved drafts and conversation history. return [ ...value.matchAll( - /@\[(task|finding|asset|company|endpoint|ip|app|root_domain|subdomain|service|任务|漏洞|资产|企业|接口|IP|应用|域名|子域名|服务)#([0-9]+)(?: ([^\]\r\n]*))?\]/g, + /@\[(schedule|task|finding|asset|company|endpoint|ip|app|root_domain|subdomain|service|计划任务|计划|任务|漏洞|资产|企业|接口|IP|应用|域名|子域名|服务)#([0-9]+)(?: ([^\]\r\n]*))?\]/g, ), ].map((match) => { - const entry = mentionKinds.find((item) => item.kind === match[1] || item.label === match[1]); + const rawKind = match[1] === "计划" ? "schedule" : match[1]; + const entry = mentionKinds.find((item) => item.kind === rawKind || item.label === rawKind); const label = translate ? translate(`mention.${entry?.kind ?? "asset"}`) : (entry?.label ?? match[1]); return { token: match[0],