Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5396: validate agent concurrency limits (#6034)
Multica Evecf4114cd5d4c
diff --git a/packages/core/agents/constants.ts b/packages/core/agents/constants.tsindex 6749aea7ff..815fa613cf 100644--- a/packages/core/agents/constants.ts+++ b/packages/core/agents/constants.ts@@ -2,3 +2,8 @@// disabled save) and the back-end (handler validation + DB CHECK constraint).// Kept in core so both apps and the test suite read from one source.export const AGENT_DESCRIPTION_MAX_LENGTH = 255;++// Valid range for the per-agent scheduler cap. Kept here so creation,+// duplication, and settings editing cannot silently drift.+export const AGENT_MAX_CONCURRENT_TASKS_MIN = 1;+export const AGENT_MAX_CONCURRENT_TASKS_MAX = 50;diff --git a/packages/views/agents/components/agent-creation-studio.test.ts b/packages/views/agents/components/agent-creation-studio.test.tsindex 013fcea1e2..f30566b78d 100644--- a/packages/views/agents/components/agent-creation-studio.test.ts+++ b/packages/views/agents/components/agent-creation-studio.test.ts@@ -527,6 +527,22 @@ describe("Agent creation studio execution overrides", () => {expect(request.thinking_level).toBe("high");});+ it.each([0, -1, 51])(+ "omits an invalid historical duplicate concurrency of %i",+ (maxConcurrentTasks) => {+ const request = buildCreateAgentRequest({+ draft: draft(),+ runtimeId: "runtime-1",+ duplicateSource: sourceAgent({+ max_concurrent_tasks: maxConcurrentTasks,+ }),+ });++ expect(request.max_concurrent_tasks).toBeUndefined();+ expect(request).not.toHaveProperty("max_concurrent_tasks");+ },+ );+it("clears model, thinking level and service tier on a runtime change", () => {const current = {...draft(),diff --git a/packages/views/agents/components/agent-creation-studio.tsx b/packages/views/agents/components/agent-creation-studio.tsxindex 83a072c236..abeb9c819e 100644--- a/packages/views/agents/components/agent-creation-studio.tsx+++ b/packages/views/agents/components/agent-creation-studio.tsx@@ -18,6 +18,8 @@ import { api, ApiError } from "@multica/core/api";import { useAuthStore } from "@multica/core/auth";import {AGENT_DESCRIPTION_MAX_LENGTH,+ AGENT_MAX_CONCURRENT_TASKS_MAX,+ AGENT_MAX_CONCURRENT_TASKS_MIN,agentTemplateDetailOptions,agentTemplateListOptions,} from "@multica/core/agents";@@ -1943,7 +1945,14 @@ export function buildCreateAgentRequest(options: {if (duplicateSource.custom_args.length > 0) {request.custom_args = duplicateSource.custom_args;}- request.max_concurrent_tasks = duplicateSource.max_concurrent_tasks;+ const sourceConcurrency = duplicateSource.max_concurrent_tasks;+ if (+ Number.isInteger(sourceConcurrency) &&+ sourceConcurrency >= AGENT_MAX_CONCURRENT_TASKS_MIN &&+ sourceConcurrency <= AGENT_MAX_CONCURRENT_TASKS_MAX+ ) {+ request.max_concurrent_tasks = sourceConcurrency;+ }}return request;}diff --git a/packages/views/agents/components/agent-detail-inspector.tsx b/packages/views/agents/components/agent-detail-inspector.tsxindex 1b8891ff09..fc74e78b44 100644--- a/packages/views/agents/components/agent-detail-inspector.tsx+++ b/packages/views/agents/components/agent-detail-inspector.tsx@@ -7,7 +7,11 @@ import type {AgentRuntime,MemberWithUser,} from "@multica/core/types";-import { AGENT_DESCRIPTION_MAX_LENGTH } from "@multica/core/agents";+import {+ AGENT_DESCRIPTION_MAX_LENGTH,+ AGENT_MAX_CONCURRENT_TASKS_MAX,+ AGENT_MAX_CONCURRENT_TASKS_MIN,+} from "@multica/core/agents";import { runtimeModelsOptions } from "@multica/core/runtimes";import { isImeComposing } from "@multica/core/utils";import { Input } from "@multica/ui/components/ui/input";@@ -330,14 +334,16 @@ function ConcurrencyField({}) {const { t } = useT("agents");const [draft, setDraft] = useState(String(value));- const min = 1;- const max = 50;useEffect(() => setDraft(String(value)), [value]);const commit = () => {const next = Number(draft);- if (!Number.isInteger(next) || next < min || next > max) {+ if (+ !Number.isInteger(next) ||+ next < AGENT_MAX_CONCURRENT_TASKS_MIN ||+ next > AGENT_MAX_CONCURRENT_TASKS_MAX+ ) {setDraft(String(value));return;}@@ -352,8 +358,8 @@ function ConcurrencyField({name="agent-concurrency"autoComplete="off"inputMode="numeric"- min={min}- max={max}+ min={AGENT_MAX_CONCURRENT_TASKS_MIN}+ max={AGENT_MAX_CONCURRENT_TASKS_MAX}value={draft}onChange={(event) => setDraft(event.target.value)}onBlur={commit}@@ -369,7 +375,10 @@ function ConcurrencyField({className="font-mono tabular-nums"/><p className="mt-1 text-xs text-muted-foreground">- {t(($) => $.pickers.concurrency_range, { min, max })}+ {t(($) => $.pickers.concurrency_range, {+ min: AGENT_MAX_CONCURRENT_TASKS_MIN,+ max: AGENT_MAX_CONCURRENT_TASKS_MAX,+ })}</p></div>);diff --git a/server/cmd/multica/cmd_agent.go b/server/cmd/multica/cmd_agent.goindex 011c7738f4..802585b558 100644--- a/server/cmd/multica/cmd_agent.go+++ b/server/cmd/multica/cmd_agent.go@@ -176,7 +176,7 @@ func init() {agentCreateCmd.Flags().String("permission-mode", "", "Invocation permission mode: private (owner only) or public_to (allow-list via --public-to-*). Authoritative over --visibility when set.")agentCreateCmd.Flags().Bool("public-to-workspace", false, "public_to: allow every workspace member to invoke this agent.")agentCreateCmd.Flags().StringSlice("public-to-member", nil, "public_to: allow the given member user id(s) to invoke this agent. Repeatable.")- agentCreateCmd.Flags().Int32("max-concurrent-tasks", 6, "Maximum concurrent tasks")+ agentCreateCmd.Flags().Int32("max-concurrent-tasks", 6, "Maximum concurrent tasks (1-50)")agentCreateCmd.Flags().String("output", "json", "Output format: table or json")// agent update@@ -205,7 +205,7 @@ func init() {agentUpdateCmd.Flags().Bool("public-to-workspace", false, "public_to: allow every workspace member to invoke this agent.")agentUpdateCmd.Flags().StringSlice("public-to-member", nil, "public_to: allow the given member user id(s) to invoke this agent. Repeatable.")agentUpdateCmd.Flags().String("status", "", "New status")- agentUpdateCmd.Flags().Int32("max-concurrent-tasks", 0, "New max concurrent tasks")+ agentUpdateCmd.Flags().Int32("max-concurrent-tasks", 0, "New max concurrent tasks (1-50)")agentUpdateCmd.Flags().String("output", "json", "Output format: table or json")// agent archive@@ -604,6 +604,9 @@ func runAgentCreate(cmd *cobra.Command, _ []string) error {applyAgentPermissionFlags(cmd, body)if cmd.Flags().Changed("max-concurrent-tasks") {v, _ := cmd.Flags().GetInt32("max-concurrent-tasks")+ if err := validateAgentMaxConcurrentTasksFlag(v); err != nil {+ return err+ }body["max_concurrent_tasks"] = v}@@ -689,6 +692,9 @@ func runAgentUpdate(cmd *cobra.Command, args []string) error {}if cmd.Flags().Changed("max-concurrent-tasks") {v, _ := cmd.Flags().GetInt32("max-concurrent-tasks")+ if err := validateAgentMaxConcurrentTasksFlag(v); err != nil {+ return err+ }body["max_concurrent_tasks"] = v}if mc, ok, err := resolveMcpConfig(cmd); err != nil {diff --git a/server/cmd/multica/cmd_agent_copy.go b/server/cmd/multica/cmd_agent_copy.goindex 289d00cf74..d84fe2ad1d 100644--- a/server/cmd/multica/cmd_agent_copy.go+++ b/server/cmd/multica/cmd_agent_copy.go@@ -4,10 +4,12 @@ import ("context""encoding/json""fmt"+ "math""os""github.com/spf13/cobra"+ "github.com/multica-ai/multica/server/internal/agentconfig""github.com/multica-ai/multica/server/internal/cli")@@ -83,6 +85,15 @@ func registerAgentCopyFlags(cmd *cobra.Command) {// never read back from the source — GET redacts / masks them anyway — and are// set only when supplied explicitly on the command line.func runAgentCopy(cmd *cobra.Command, args []string) error {+ var maxConcurrentTasksOverride *int32+ if cmd.Flags().Changed("max-concurrent-tasks") {+ v, _ := cmd.Flags().GetInt32("max-concurrent-tasks")+ if err := validateAgentMaxConcurrentTasksFlag(v); err != nil {+ return err+ }+ maxConcurrentTasksOverride = &v+ }+client, err := newAPIClient(cmd)if err != nil {return err@@ -159,12 +170,13 @@ func runAgentCopy(cmd *cobra.Command, args []string) error {body["custom_args"] = ca}- // max_concurrent_tasks: copy the source's value, override with the flag.- if v, ok := src["max_concurrent_tasks"]; ok && v != nil {- body["max_concurrent_tasks"] = v- }- if cmd.Flags().Changed("max-concurrent-tasks") {- v, _ := cmd.Flags().GetInt32("max-concurrent-tasks")+ // max_concurrent_tasks: a valid source value is portable. Historical rows+ // may predate the 1-50 invariant; omit those values so create applies its+ // default instead of turning Duplicate into a 400. An explicit flag is+ // validated before any API request and remains authoritative.+ if maxConcurrentTasksOverride != nil {+ body["max_concurrent_tasks"] = *maxConcurrentTasksOverride+ } else if v, ok := copiedAgentMaxConcurrentTasks(src["max_concurrent_tasks"]); ok {body["max_concurrent_tasks"] = v}@@ -276,3 +288,14 @@ func runAgentCopy(cmd *cobra.Command, args []string) error {fmt.Printf("Agent copied: %s (%s)\n", strVal(result, "name"), strVal(result, "id"))return nil}++func copiedAgentMaxConcurrentTasks(value any) (int32, bool) {+ number, ok := value.(float64)+ if !ok || number != math.Trunc(number) ||+ number < float64(agentconfig.MinMaxConcurrentTasks) ||+ number > float64(agentconfig.MaxMaxConcurrentTasks) {+ return 0, false+ }+ value32 := int32(number)+ return value32, agentconfig.IsValidMaxConcurrentTasks(value32)+}diff --git a/server/cmd/multica/cmd_agent_copy_test.go b/server/cmd/multica/cmd_agent_copy_test.goindex e406a28735..727fa042b1 100644--- a/server/cmd/multica/cmd_agent_copy_test.go+++ b/server/cmd/multica/cmd_agent_copy_test.go@@ -2,6 +2,7 @@ package mainimport ("encoding/json"+ "fmt""net/http""net/http/httptest""reflect"@@ -147,6 +148,61 @@ func TestAgentCopySameRuntimeCopiesPortableFields(t *testing.T) {}}+func TestAgentCopyOmitsInvalidHistoricalConcurrency(t *testing.T) {+ for _, value := range []any{0, -1, 51} {+ t.Run(fmt.Sprint(value), func(t *testing.T) {+ source := fullSourceAgent()+ source["max_concurrent_tasks"] = value++ var gotBody map[string]any+ srv := copyMockServer(t, source, &gotBody)+ defer srv.Close()+ setCopyTestEnv(t, srv.URL)++ cmd := newAgentCopyTestCmd()+ if err := runAgentCopy(cmd, []string{"agent-src"}); err != nil {+ t.Fatalf("runAgentCopy: %v", err)+ }+ if _, ok := gotBody["max_concurrent_tasks"]; ok {+ t.Errorf("invalid historical max_concurrent_tasks must be omitted, got %v", gotBody["max_concurrent_tasks"])+ }+ })+ }+}++func TestAgentCopyValidConcurrencyOverrideRepairsInvalidSource(t *testing.T) {+ source := fullSourceAgent()+ source["max_concurrent_tasks"] = 0++ var gotBody map[string]any+ srv := copyMockServer(t, source, &gotBody)+ defer srv.Close()+ setCopyTestEnv(t, srv.URL)++ cmd := newAgentCopyTestCmd()+ _ = cmd.Flags().Set("max-concurrent-tasks", "12")++ if err := runAgentCopy(cmd, []string{"agent-src"}); err != nil {+ t.Fatalf("runAgentCopy: %v", err)+ }+ if gotBody["max_concurrent_tasks"] != float64(12) {+ t.Errorf("max_concurrent_tasks = %v, want 12", gotBody["max_concurrent_tasks"])+ }+}++func TestAgentCopyRejectsInvalidConcurrencyOverrideBeforeRequest(t *testing.T) {+ cmd := newAgentCopyTestCmd()+ _ = cmd.Flags().Set("max-concurrent-tasks", "51")++ err := runAgentCopy(cmd, []string{"agent-src"})+ if err == nil {+ t.Fatal("expected invalid --max-concurrent-tasks error")+ }+ if !strings.Contains(err.Error(), "between 1 and 50") {+ t.Fatalf("error = %q, want 1-50 range", err.Error())+ }+}+func TestAgentCopyCrossRuntimeRequiresModel(t *testing.T) {postCalled := falsesrv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {diff --git a/server/cmd/multica/cmd_agent_test.go b/server/cmd/multica/cmd_agent_test.goindex 1fa2376eb0..836eaaecac 100644--- a/server/cmd/multica/cmd_agent_test.go+++ b/server/cmd/multica/cmd_agent_test.go@@ -652,6 +652,136 @@ func TestAgentCreateDoesNotExposeFromTemplate(t *testing.T) {}}+func TestAgentMaxConcurrentTasksFlagValidation(t *testing.T) {+ previousDir, err := os.Getwd()+ if err != nil {+ t.Fatal(err)+ }+ if err := os.Chdir(t.TempDir()); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ if err := os.Chdir(previousDir); err != nil {+ t.Errorf("restore working directory: %v", err)+ }+ })++ var requestCount int+ var gotBody map[string]any+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ requestCount+++ if err := json.NewDecoder(r.Body).Decode(&gotBody); err != nil {+ t.Errorf("decode request body: %v", err)+ }+ json.NewEncoder(w).Encode(map[string]any{"id": "agent-123", "name": "TestAgent"})+ }))+ defer srv.Close()++ t.Setenv("HOME", t.TempDir())+ t.Setenv("MULTICA_SERVER_URL", srv.URL)+ t.Setenv("MULTICA_WORKSPACE_ID", "ws-1")+ t.Setenv("MULTICA_TOKEN", "test-token")+ t.Setenv("MULTICA_AGENT_ID", "")+ t.Setenv("MULTICA_TASK_ID", "")++ newCreateCmd := func(t *testing.T, value string) *cobra.Command {+ t.Helper()+ cmd := &cobra.Command{Use: "create"}+ cmd.Flags().String("name", "", "")+ cmd.Flags().String("runtime-id", "", "")+ cmd.Flags().Int32("max-concurrent-tasks", 6, "")+ cmd.Flags().String("output", "json", "")+ cmd.Flags().String("profile", "", "")+ if err := cmd.Flags().Set("name", "TestAgent"); err != nil {+ t.Fatal(err)+ }+ if err := cmd.Flags().Set("runtime-id", "runtime-1"); err != nil {+ t.Fatal(err)+ }+ if value != "" {+ if err := cmd.Flags().Set("max-concurrent-tasks", value); err != nil {+ t.Fatal(err)+ }+ }+ return cmd+ }+ newUpdateCmd := func(t *testing.T, value string) *cobra.Command {+ t.Helper()+ cmd := &cobra.Command{Use: "update"}+ cmd.Flags().Int32("max-concurrent-tasks", 0, "")+ cmd.Flags().String("output", "json", "")+ cmd.Flags().String("profile", "", "")+ if err := cmd.Flags().Set("max-concurrent-tasks", value); err != nil {+ t.Fatal(err)+ }+ return cmd+ }++ for _, value := range []string{"0", "-1", "51"} {+ t.Run("create rejects "+value, func(t *testing.T) {+ before := requestCount+ err := runAgentCreate(newCreateCmd(t, value), nil)+ if err == nil || !strings.Contains(err.Error(), "between 1 and 50") {+ t.Fatalf("error = %v, want readable 1-50 validation error", err)+ }+ if requestCount != before {+ t.Fatalf("invalid create sent %d HTTP request(s), want 0", requestCount-before)+ }+ })++ t.Run("update rejects "+value, func(t *testing.T) {+ before := requestCount+ err := runAgentUpdate(newUpdateCmd(t, value), []string{"agent-123"})+ if err == nil || !strings.Contains(err.Error(), "between 1 and 50") {+ t.Fatalf("error = %v, want readable 1-50 validation error", err)+ }+ if requestCount != before {+ t.Fatalf("invalid update sent %d HTTP request(s), want 0", requestCount-before)+ }+ })+ }++ for _, value := range []string{"1", "50"} {+ t.Run("create accepts "+value, func(t *testing.T) {+ gotBody = nil+ if err := runAgentCreate(newCreateCmd(t, value), nil); err != nil {+ t.Fatalf("runAgentCreate: %v", err)+ }+ want := float64(1)+ if value == "50" {+ want = 50+ }+ if gotBody["max_concurrent_tasks"] != want {+ t.Fatalf("body max_concurrent_tasks = %v, want %v", gotBody["max_concurrent_tasks"], want)+ }+ })++ t.Run("update accepts "+value, func(t *testing.T) {+ gotBody = nil+ if err := runAgentUpdate(newUpdateCmd(t, value), []string{"agent-123"}); err != nil {+ t.Fatalf("runAgentUpdate: %v", err)+ }+ want := float64(1)+ if value == "50" {+ want = 50+ }+ if gotBody["max_concurrent_tasks"] != want {+ t.Fatalf("body max_concurrent_tasks = %v, want %v", gotBody["max_concurrent_tasks"], want)+ }+ })+ }++ t.Run("create omission stays omitted", func(t *testing.T) {+ gotBody = nil+ if err := runAgentCreate(newCreateCmd(t, ""), nil); err != nil {+ t.Fatalf("runAgentCreate: %v", err)+ }+ if _, ok := gotBody["max_concurrent_tasks"]; ok {+ t.Fatalf("omitted flag should not be sent: %v", gotBody)+ }+ })+}+// TestParseCustomEnvErrorSanitization guards against future changes// re-introducing %w wrapping of json.Unmarshal errors. Those errors// can surface short fragments of the input, which — for a flag thatdiff --git a/server/cmd/multica/cmd_agent_validation.go b/server/cmd/multica/cmd_agent_validation.gonew file mode 100644index 0000000000..2a4ee39b65--- /dev/null+++ b/server/cmd/multica/cmd_agent_validation.go@@ -0,0 +1,18 @@+package main++import (+ "fmt"++ "github.com/multica-ai/multica/server/internal/agentconfig"+)++func validateAgentMaxConcurrentTasksFlag(value int32) error {+ if err := agentconfig.ValidateMaxConcurrentTasks(value); err != nil {+ return fmt.Errorf(+ "--max-concurrent-tasks %w (got %d)",+ err,+ value,+ )+ }+ return nil+}diff --git a/server/internal/agentconfig/concurrency.go b/server/internal/agentconfig/concurrency.gonew file mode 100644index 0000000000..a362fa708e--- /dev/null+++ b/server/internal/agentconfig/concurrency.go@@ -0,0 +1,24 @@+package agentconfig++import "fmt"++const (+ DefaultMaxConcurrentTasks int32 = 6+ MinMaxConcurrentTasks int32 = 1+ MaxMaxConcurrentTasks int32 = 50+)++func IsValidMaxConcurrentTasks(value int32) bool {+ return value >= MinMaxConcurrentTasks && value <= MaxMaxConcurrentTasks+}++func ValidateMaxConcurrentTasks(value int32) error {+ if !IsValidMaxConcurrentTasks(value) {+ return fmt.Errorf(+ "must be between %d and %d",+ MinMaxConcurrentTasks,+ MaxMaxConcurrentTasks,+ )+ }+ return nil+}diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 47feadb8df..366d2e2f83 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -1021,8 +1021,9 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {if req.Visibility == "" {req.Visibility = "private"}- if req.MaxConcurrentTasks == 0 {- req.MaxConcurrentTasks = 6+ if err := defaultAndValidateAgentMaxConcurrentTasks(rawFields, &req.MaxConcurrentTasks); err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return}runtimeUUID, ok := parseUUIDOrBadRequest(w, req.RuntimeID, "runtime_id")@@ -1655,6 +1656,10 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {params.Status = pgtype.Text{String: *req.Status, Valid: true}}if req.MaxConcurrentTasks != nil {+ if err := validateAgentMaxConcurrentTasks(*req.MaxConcurrentTasks); err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return+ }params.MaxConcurrentTasks = pgtype.Int4{Int32: *req.MaxConcurrentTasks, Valid: true}}if req.Model != nil {diff --git a/server/internal/handler/agent_concurrency_test.go b/server/internal/handler/agent_concurrency_test.gonew file mode 100644index 0000000000..7534fd154c--- /dev/null+++ b/server/internal/handler/agent_concurrency_test.go@@ -0,0 +1,225 @@+package handler++import (+ "context"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+)++func TestCreateAgent_MaxConcurrentTasksBoundsAndDefault(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ tests := []struct {+ name string+ value any+ provided bool+ wantCode int+ want int32+ }{+ {name: "omitted defaults to six", provided: false, wantCode: http.StatusCreated, want: 6},+ {name: "null defaults to six", value: nil, provided: true, wantCode: http.StatusCreated, want: 6},+ {name: "minimum accepted", value: 1, provided: true, wantCode: http.StatusCreated, want: 1},+ {name: "maximum accepted", value: 50, provided: true, wantCode: http.StatusCreated, want: 50},+ {name: "zero rejected", value: 0, provided: true, wantCode: http.StatusBadRequest},+ {name: "negative rejected", value: -1, provided: true, wantCode: http.StatusBadRequest},+ {name: "above maximum rejected", value: 51, provided: true, wantCode: http.StatusBadRequest},+ }++ for i, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ agentName := fmt.Sprintf("concurrency-create-%d", i)+ body := map[string]any{+ "name": agentName,+ "runtime_id": handlerTestRuntimeID(t),+ }+ if tt.provided {+ body["max_concurrent_tasks"] = tt.value+ }++ w := httptest.NewRecorder()+ testHandler.CreateAgent(w, newRequest(http.MethodPost, "/api/agents", body))+ if w.Code != tt.wantCode {+ t.Fatalf("status = %d, want %d: %s", w.Code, tt.wantCode, w.Body.String())+ }++ if tt.wantCode == http.StatusBadRequest {+ if !strings.Contains(w.Body.String(), "between 1 and 50") {+ t.Fatalf("error should explain the 1-50 range: %s", w.Body.String())+ }+ return+ }++ var response AgentResponse+ if err := json.NewDecoder(w.Body).Decode(&response); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, response.ID)+ })+ if response.MaxConcurrentTasks != tt.want {+ t.Fatalf("max_concurrent_tasks = %d, want %d", response.MaxConcurrentTasks, tt.want)+ }+ })+ }+}++func TestUpdateAgent_MaxConcurrentTasksBoundsAndOmission(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ agentID := createHandlerTestAgent(t, "concurrency-update", nil)+ if _, err := testPool.Exec(context.Background(),+ `UPDATE agent SET max_concurrent_tasks = 17 WHERE id = $1`, agentID,+ ); err != nil {+ t.Fatalf("seed max_concurrent_tasks: %v", err)+ }++ readPersisted := func() int32 {+ t.Helper()+ var got int32+ if err := testPool.QueryRow(context.Background(),+ `SELECT max_concurrent_tasks FROM agent WHERE id = $1`, agentID,+ ).Scan(&got); err != nil {+ t.Fatalf("read max_concurrent_tasks: %v", err)+ }+ return got+ }++ for _, value := range []int32{0, -1, 51} {+ t.Run(fmt.Sprintf("rejects_%d", value), func(t *testing.T) {+ w := httptest.NewRecorder()+ req := withURLParam(newRequest(http.MethodPut, "/api/agents/"+agentID, map[string]any{+ "max_concurrent_tasks": value,+ }), "id", agentID)+ testHandler.UpdateAgent(w, req)++ if w.Code != http.StatusBadRequest {+ t.Fatalf("status = %d, want 400: %s", w.Code, w.Body.String())+ }+ if !strings.Contains(w.Body.String(), "between 1 and 50") {+ t.Fatalf("error should explain the 1-50 range: %s", w.Body.String())+ }+ if got := readPersisted(); got != 17 {+ t.Fatalf("rejected update persisted %d, want existing value 17", got)+ }+ })+ }++ for _, value := range []int32{1, 50} {+ t.Run(fmt.Sprintf("accepts_%d", value), func(t *testing.T) {+ w := httptest.NewRecorder()+ req := withURLParam(newRequest(http.MethodPut, "/api/agents/"+agentID, map[string]any{+ "max_concurrent_tasks": value,+ }), "id", agentID)+ testHandler.UpdateAgent(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())+ }+ if got := readPersisted(); got != value {+ t.Fatalf("persisted max_concurrent_tasks = %d, want %d", got, value)+ }+ })+ }++ t.Run("omitted preserves existing value", func(t *testing.T) {+ w := httptest.NewRecorder()+ req := withURLParam(newRequest(http.MethodPut, "/api/agents/"+agentID, map[string]any{+ "description": "concurrency unchanged",+ }), "id", agentID)+ testHandler.UpdateAgent(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())+ }+ if got := readPersisted(); got != 50 {+ t.Fatalf("omitted max_concurrent_tasks changed value to %d, want 50", got)+ }+ })++ t.Run("null preserves existing value", func(t *testing.T) {+ w := httptest.NewRecorder()+ req := withURLParam(newRequest(http.MethodPut, "/api/agents/"+agentID, map[string]any{+ "max_concurrent_tasks": nil,+ }), "id", agentID)+ testHandler.UpdateAgent(w, req)++ if w.Code != http.StatusOK {+ t.Fatalf("status = %d, want 200: %s", w.Code, w.Body.String())+ }+ if got := readPersisted(); got != 50 {+ t.Fatalf("null max_concurrent_tasks changed value to %d, want 50", got)+ }+ })+}++func TestCreateAgentFromTemplate_MaxConcurrentTasksBoundsAndDefault(t *testing.T) {+ if testHandler == nil || testPool == nil {+ t.Skip("database not available")+ }++ const templateSlug = "commit-message"+ if _, ok := agentTemplates.Get(templateSlug); !ok {+ t.Fatalf("expected template %q to be loaded", templateSlug)+ }++ tests := []struct {+ name string+ value any+ provided bool+ wantCode int+ want int32+ }{+ {name: "omitted defaults to six", provided: false, wantCode: http.StatusCreated, want: 6},+ {name: "null defaults to six", value: nil, provided: true, wantCode: http.StatusCreated, want: 6},+ {name: "minimum accepted", value: 1, provided: true, wantCode: http.StatusCreated, want: 1},+ {name: "maximum accepted", value: 50, provided: true, wantCode: http.StatusCreated, want: 50},+ {name: "zero rejected", value: 0, provided: true, wantCode: http.StatusBadRequest},+ {name: "negative rejected", value: -1, provided: true, wantCode: http.StatusBadRequest},+ {name: "above maximum rejected", value: 51, provided: true, wantCode: http.StatusBadRequest},+ }++ for i, tt := range tests {+ t.Run(tt.name, func(t *testing.T) {+ body := map[string]any{+ "template_slug": templateSlug,+ "name": fmt.Sprintf("concurrency-template-%d", i),+ "runtime_id": handlerTestRuntimeID(t),+ }+ if tt.provided {+ body["max_concurrent_tasks"] = tt.value+ }++ w := httptest.NewRecorder()+ testHandler.CreateAgentFromTemplate(w, newRequest(http.MethodPost, "/api/agents/from-template", body))+ if w.Code != tt.wantCode {+ t.Fatalf("status = %d, want %d: %s", w.Code, tt.wantCode, w.Body.String())+ }++ if tt.wantCode == http.StatusBadRequest {+ if !strings.Contains(w.Body.String(), "between 1 and 50") {+ t.Fatalf("error should explain the 1-50 range: %s", w.Body.String())+ }+ return+ }++ var response CreateAgentFromTemplateResponse+ if err := json.NewDecoder(w.Body).Decode(&response); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, response.Agent.ID)+ })+ if response.Agent.MaxConcurrentTasks != tt.want {+ t.Fatalf("max_concurrent_tasks = %d, want %d", response.Agent.MaxConcurrentTasks, tt.want)+ }+ })+ }+}diff --git a/server/internal/handler/agent_template.go b/server/internal/handler/agent_template.goindex 4572b8833d..9c5e49bd3d 100644--- a/server/internal/handler/agent_template.go+++ b/server/internal/handler/agent_template.go@@ -185,8 +185,9 @@ func (h *Handler) CreateAgentFromTemplate(w http.ResponseWriter, r *http.Requestif req.Visibility == "" {req.Visibility = "private"}- if req.MaxConcurrentTasks == 0 {- req.MaxConcurrentTasks = 6+ if err := defaultAndValidateAgentMaxConcurrentTasks(rawFields, &req.MaxConcurrentTasks); err != nil {+ writeError(w, http.StatusBadRequest, err.Error())+ return}tmpl, found := agentTemplates.Get(req.TemplateSlug)diff --git a/server/internal/handler/agent_validation.go b/server/internal/handler/agent_validation.gonew file mode 100644index 0000000000..03b6688416--- /dev/null+++ b/server/internal/handler/agent_validation.go@@ -0,0 +1,25 @@+package handler++import (+ "bytes"+ "encoding/json"+ "fmt"++ "github.com/multica-ai/multica/server/internal/agentconfig"+)++func validateAgentMaxConcurrentTasks(value int32) error {+ if err := agentconfig.ValidateMaxConcurrentTasks(value); err != nil {+ return fmt.Errorf("max_concurrent_tasks %w", err)+ }+ return nil+}++func defaultAndValidateAgentMaxConcurrentTasks(rawFields map[string]json.RawMessage, value *int32) error {+ raw, provided := rawFields["max_concurrent_tasks"]+ if !provided || bytes.Equal(bytes.TrimSpace(raw), []byte("null")) {+ *value = agentconfig.DefaultMaxConcurrentTasks+ return nil+ }+ return validateAgentMaxConcurrentTasks(*value)+}diff --git a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md b/server/internal/service/builtin_skills/multica-creating-agents/SKILL.mdindex ca8d9a8e33..beb3a936de 100644--- a/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md+++ b/server/internal/service/builtin_skills/multica-creating-agents/SKILL.md@@ -58,8 +58,10 @@ multica agent create --name <name> --runtime-id <runtime-id> \`runAgentCreate` builds a JSON body and posts it to `/api/agents`. It onlyadds a key when its flag was provided — `description`/`instructions` on anon-empty value, the rest (`runtime-config`, `custom-args`, `model`,-`thinking-level`, `service-tier`, `visibility`, …) on the flag being `Changed` — so omitted-flags fall through to server defaults rather than sending empty strings.+`thinking-level`, `service-tier`, `visibility`, …) on the flag being `Changed`+— so omitted flags fall through to server defaults rather than sending empty+strings. `--max-concurrent-tasks` is validated as 1–50 before the request is+sent.The HTTP body (`CreateAgentRequest`) accepts: `name`, `description`,`instructions`, `avatar_url`, `runtime_id`, `runtime_config`, `custom_env`,@@ -85,6 +87,10 @@ multica agent copy <source-agent-id> --runtime-id <target> --model <model> # cr`" (copy)"`), `description`, `instructions`, avatar, `custom_args`,`max_concurrent_tasks`, invocation permission (`permission_mode` +allow-list), and assigned workspace skills.+- A copied `max_concurrent_tasks` is included only when the source value is+ within 1–50. Historical out-of-range values are omitted so the new agent+ receives the server default (`6`); an explicit out-of-range+ `--max-concurrent-tasks` override is rejected before any API request.- Runtime-specific fields (`model`, `thinking_level`, `service_tier`) are copiedONLY when the target runtime is unchanged. `--runtime-id` selecting adifferent runtime drops them and REQUIRES `--model` (pass `--model ""` to@@ -113,15 +119,22 @@ multica agent copy <source-agent-id> --runtime-id <target> --model <model> # cr| `custom_env` | `agent.custom_env` (JSON object) | — | daemon (process env); see Env & secrets || `mcp_config` | `agent.mcp_config` (raw JSON) | CLI checks it is a JSON object or `null`; server stores as-is. At create, literal `null` is dropped (no-op); at update, `null` clears the column | daemon → provider (provider-specific MCP handling); redacted on read || `visibility` | `agent.visibility` | — | access control; defaults to `private`; gates who can read/route a private agent (e.g. a private squad leader) — NOT the runtime prompt |-| `max_concurrent_tasks` | `agent.max_concurrent_tasks` | — | scheduler task cap; defaults to `6` |+| `max_concurrent_tasks` | `agent.max_concurrent_tasks` | integer from 1 through 50; out-of-range values return 400 | scheduler task cap; defaults to `6` |-Defaults when omitted: `runtime_config` → `{}`, `custom_env` → `{}`,+Defaults when omitted or explicitly `null`: `max_concurrent_tasks` → `6`.+Other defaults when omitted: `runtime_config` → `{}`, `custom_env` → `{}`,`custom_args` → `[]`, `avatar_url` → a random `emoji:<glyph>`, `visibility` →-`private`, `max_concurrent_tasks` → `6`+`private`(all materialized server-side before the insert). `custom_args`/`runtime_config`are typed `[]string`/`any` and marshaled as-is — the JSON-shape rejectionhappens in the CLI, not the create handler.+The 1–50 concurrency range applies consistently to manual create, update, and+the create-from-template HTTP path. On create paths, an omitted field defaults+to 6 while an explicitly supplied 0 is rejected; on update, omission preserves+the current value. The CLI performs the same range check before sending create+or update requests.+`thinking_level` is validated only at the provider level: fixed-catalogproviders reject an unrecognized literal, while dynamic-catalog providers suchas Codex/OpenCode accept a syntactically safe token. A value unsupported fordiff --git a/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md b/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.mdindex 1e61b45a6e..db810a954b 100644--- a/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md+++ b/server/internal/service/builtin_skills/multica-creating-agents/references/creating-agents-source-map.md@@ -23,15 +23,16 @@ go test ./internal/service -run TestBuiltinSkillsConformToTemplate| Secret-safe MCP input: `mcp-config`, `mcp-config-stdin`, `mcp-config-file` (create) | 172–174 | Same three-channel pattern as `custom-env`; `--mcp-config` warns about shell history / `ps`; value must be a JSON object or `null` | `multica agent create --help` || MCP flags on `agent update` | 200–202 | Same three channels on update; `--mcp-config null` clears. Unlike `custom_env`, `mcp_config` IS settable via update | `multica agent update --help` || `thinking-level` / `service-tier` flags on `agent update` | 189–190 | Thin pass-throughs; an explicit empty string clears the saved override and restores the runtime/local Codex default | `multica agent update --help` |-| `runAgentCreate` builds body + `POST /api/agents` | 533–624 | Only sets a body key when the flag `Changed`; posts to `/api/agents` (line 614) | read 533–624 |-| Body assembly: description/instructions/runtime-config/custom-args/custom-env/mcp-config/model/thinking-level/service-tier | 548–608 | `model`, `thinking_level`, and `service_tier` are `Changed`-gated pass-throughs; omitted flags are not sent | read the `runAgentCreate` body assembly |-| `runAgentUpdate` sends `thinking_level` / `service_tier` / `mcp_config` | 627–718 | Each override key is added only when its flag is `Changed`; `custom_env` is intentionally not a flag here | read the `runAgentUpdate` body assembly |-| `parseMcpConfig` / `resolveMcpConfig` helpers | 1210, 1238 | Validator (object-or-`null`, content-free errors) + three-channel resolver, mirroring `parseCustomEnv`/`resolveCustomEnv` | read 1210–1294 |-| `agent skills set` = replace-all | 916 | `PUT /api/agents/{id}/skills` (934); `--skill-ids ''` clears all (922–925) | `multica agent skills set --help` |-| `agent skills add` = additive | 941 | `POST /api/agents/{id}/skills/add` (962); requires ≥1 id (947–952) | `multica agent skills add --help` |-| `agent skills list` | 884 | reads bindings, no side effect | `multica agent skills list --help` |-| `agent env get` | 1018 | `GET /api/agents/{id}/env` (1028) | `multica agent env get --help` |-| `agent env set` | 1053 | `PUT /api/agents/{id}/env` with full `custom_env` map (1073) | `multica agent env set --help` |+| `max-concurrent-tasks` flags + validation | `cmd_agent.go` 179, 208; `cmd_agent_validation.go` 5–20 | Shared CLI helper enforces 1–50; create/update call it before their HTTP mutation and omitted create flags stay absent | `multica agent create --help`; `multica agent update --help` |+| `runAgentCreate` builds body + `POST /api/agents` | 533–628 | Only sets a body key when the flag `Changed`; validates `max_concurrent_tasks` at 605–611, then posts to `/api/agents` (617) | read 533–628 |+| Body assembly: description/instructions/runtime-config/custom-args/custom-env/mcp-config/model/thinking-level/service-tier | 548–611 | `model`, `thinking_level`, and `service_tier` are `Changed`-gated pass-throughs; omitted flags are not sent | read the `runAgentCreate` body assembly |+| `runAgentUpdate` sends `thinking_level` / `service_tier` / `mcp_config` | 630–725 | Each override key is added only when its flag is `Changed`; `max_concurrent_tasks` is range-checked at 693–699; `custom_env` is intentionally not a flag here | read the `runAgentUpdate` body assembly |+| `parseMcpConfig` / `resolveMcpConfig` helpers | 1216, 1244 | Validator (object-or-`null`, content-free errors) + three-channel resolver, mirroring `parseCustomEnv`/`resolveCustomEnv` | read 1216–1301 |+| `agent skills set` = replace-all | 922 | `PUT /api/agents/{id}/skills` (940); `--skill-ids ''` clears all (928–931) | `multica agent skills set --help` |+| `agent skills add` = additive | 947 | `POST /api/agents/{id}/skills/add` (968); requires ≥1 id (953–958) | `multica agent skills add --help` |+| `agent skills list` | 890 | reads bindings, no side effect | `multica agent skills list --help` |+| `agent env get` | 1024 | `GET /api/agents/{id}/env` (1034) | `multica agent env get --help` |+| `agent env set` | 1059 | `PUT /api/agents/{id}/env` with full `custom_env` map (1079) | `multica agent env set --help` |## Copy command — `server/cmd/multica/cmd_agent_copy.go`@@ -40,6 +41,7 @@ go test ./internal/service -run TestBuiltinSkillsConformToTemplate| `agentCopyCmd` (`copy <source-agent-id>`) + flag registrar | 21, 47, 54 | Own file with its own `init()` so `cmd_agent.go` line refs stay stable; `registerAgentCopyFlags` is shared with the tests | `multica agent copy --help` || Reads source via `GET /api/agents/<id>` | 95 | Composes over existing endpoints — no dedicated copy API | read `runAgentCopy` || Same-runtime vs cross-runtime rule | 114, 187 | `sameRuntime` copies `model`/`thinking_level`/`service_tier`; a different `--runtime-id` drops them and requires `--model` (empty allowed) | `multica agent copy --help` |+| Concurrency copy compatibility | `runAgentCopy`, `copiedAgentMaxConcurrentTasks` | Explicit `--max-concurrent-tasks` is validated before any request; valid source values are copied, while historical values outside 1–50 are omitted so create defaults to 6 | read the concurrency body assembly || Skills copied in the create transaction | 239 | Source skill ids sent as `skill_ids`, bound in the same `POST /api/agents` tx (267); `--no-skills` opts out | read `runAgentCopy` || Secrets never copied | 240–266 | `custom_env`/`mcp_config`/`runtime_config` set only from explicit secret-safe flags, never read from the source | `multica agent copy --help` |@@ -69,7 +71,8 @@ only.| `service_tier` provider-level validation | `agent.go` create/update paths | Non-empty values are Codex-only safe tokens; exact per-model support is daemon-owned || Defaults: `{}` config/env, `[]` args | 688–701 | `RuntimeConfig`→`{}`, `CustomEnv`→`{}`, `CustomArgs`→`[]` when nil, before insert || `visibility` default | 635–636 | `if req.Visibility == "" { req.Visibility = "private" }` — access-control field, not the runtime prompt |-| `max_concurrent_tasks` default | 638–639 | `if req.MaxConcurrentTasks == 0 { req.MaxConcurrentTasks = 6 }` — scheduler cap |+| `max_concurrent_tasks` create/default validation | `agent.go`; `agent_validation.go`; `internal/agentconfig/concurrency.go` | Shared 1–50 validator; a missing or explicit `null` field defaults to 6, while an explicitly supplied numeric 0/out-of-range value returns 400 |+| `max_concurrent_tasks` update validation | 1660–1666 | Omission preserves the existing value; a supplied value outside 1–50 returns 400 before persistence || `mcp_config` null-skip on create | 704–705 | raw JSON copied through unless the body value is the literal `null` || `mcp_config` redacted on read | 54, 848–851 | `redactMcpConfig` sets `McpConfigRedacted=true`; a private agent read by a member also redacts (494, 509) || Qwen Code managed-MCP injection | `pkg/agent/qwen.go` | Non-null `mcp_config` is written to a daemon-owned 0600 temporary JSON file and passed with `--mcp-config`; the file is removed after the process exits, while `null` preserves native inheritance. |@@ -79,6 +82,12 @@ only.| `UpdateAgent` persists / clears `mcp_config` | 944–948, 1060–1061 | Tri-state from the raw body: key omitted → no change; literal `null` → `ClearAgentMcpConfig`; object → replace. No 400 like `custom_env` — `mcp_config` IS updatable here || `description` ≤ 255 on update too | 921–924 | same cap re-checked on update |+## Create-from-template handler — `server/internal/handler/agent_template.go`++| Contract | Line | Behavior |+|---|---|---|+| `max_concurrent_tasks` default + validation | `CreateAgentFromTemplate`; `defaultAndValidateAgentMaxConcurrentTasks` | Uses the same helper as manual create: omission or `null` defaults to 6; explicit numeric values outside 1–50 return 400 |+## Runtime model/thinking discovery — `server/pkg/agent/{models,thinking}.go`| Contract | Line | Behavior |