Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

fix(agent): return 409 on duplicate agent name (#1182)

joyanup3ea6b5c7b8d5
diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.go
index d32fb74f88..80be91906b 100644
--- a/server/internal/handler/agent.go
+++ b/server/internal/handler/agent.go
@@ -2,10 +2,13 @@ package handler
import (
"encoding/json"
+ "errors"
+ "fmt"
"log/slog"
"net/http"
"github.com/go-chi/chi/v5"
+ "github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/logger"
"github.com/multica-ai/multica/server/internal/service"
@@ -319,6 +322,13 @@ func (h *Handler) CreateAgent(w http.ResponseWriter, r *http.Request) {
CustomArgs: ca,
})
if err != nil {
+ // Unique constraint on (workspace_id, name) — return a clear conflict error
+ // so the UI can show the right message instead of a generic 500.
+ var pgErr *pgconn.PgError
+ if errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "agent_workspace_name_unique" {
+ writeError(w, http.StatusConflict, fmt.Sprintf("an agent named %q already exists in this workspace", req.Name))
+ return
+ }
slog.Warn("create agent failed", append(logger.RequestAttrs(r), "error", err, "workspace_id", workspaceID)...)
writeError(w, http.StatusInternalServerError, "failed to create agent: "+err.Error())
return
diff --git a/server/internal/handler/agent_test.go b/server/internal/handler/agent_test.go
new file mode 100644
index 0000000000..d777067027
--- /dev/null
+++ b/server/internal/handler/agent_test.go
@@ -0,0 +1,55 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestCreateAgent_RejectsDuplicateName(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+
+ // Clean up any agents created by this test.
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(),
+ `DELETE FROM agent WHERE workspace_id = $1 AND name = $2`,
+ testWorkspaceID, "duplicate-name-test-agent",
+ )
+ })
+
+ body := map[string]any{
+ "name": "duplicate-name-test-agent",
+ "description": "first description",
+ "runtime_id": testRuntimeID,
+ "visibility": "private",
+ "max_concurrent_tasks": 1,
+ }
+
+ // First call — creates the agent.
+ w1 := httptest.NewRecorder()
+ testHandler.CreateAgent(w1, newRequest(http.MethodPost, "/api/agents", body))
+ if w1.Code != http.StatusCreated {
+ t.Fatalf("first CreateAgent: expected 201, got %d: %s", w1.Code, w1.Body.String())
+ }
+ var resp1 map[string]any
+ if err := json.NewDecoder(w1.Body).Decode(&resp1); err != nil {
+ t.Fatalf("decode first response: %v", err)
+ }
+ agentID1, _ := resp1["id"].(string)
+ if agentID1 == "" {
+ t.Fatalf("first CreateAgent: no id in response: %v", resp1)
+ }
+
+ // Second call — same name must be rejected with 409 Conflict.
+ // The unique constraint prevents silent duplicates; the UI shows a clear error.
+ body["description"] = "updated description"
+ w2 := httptest.NewRecorder()
+ testHandler.CreateAgent(w2, newRequest(http.MethodPost, "/api/agents", body))
+ if w2.Code != http.StatusConflict {
+ t.Fatalf("second CreateAgent with duplicate name: expected 409, got %d: %s", w2.Code, w2.Body.String())
+ }
+}
diff --git a/server/internal/handler/handler_test.go b/server/internal/handler/handler_test.go
index 79614baec1..0b3ea69da2 100644
--- a/server/internal/handler/handler_test.go
+++ b/server/internal/handler/handler_test.go
@@ -23,6 +23,7 @@ var testHandler *Handler
var testPool *pgxpool.Pool
var testUserID string
var testWorkspaceID string
+var testRuntimeID string
const (
handlerTestEmail = "[email protected]"
@@ -114,6 +115,7 @@ func setupHandlerTestFixture(ctx context.Context, pool *pgxpool.Pool) (string, s
`, workspaceID, "Handler Test Runtime", "handler_test_runtime", "Handler test runtime").Scan(&runtimeID); err != nil {
return "", "", err
}
+ testRuntimeID = runtimeID
if _, err := pool.Exec(ctx, `
INSERT INTO agent (
diff --git a/server/migrations/046_agent_unique_name.down.sql b/server/migrations/046_agent_unique_name.down.sql
new file mode 100644
index 0000000000..97d086996d
--- /dev/null
+++ b/server/migrations/046_agent_unique_name.down.sql
@@ -0,0 +1 @@
+ALTER TABLE agent DROP CONSTRAINT IF EXISTS agent_workspace_name_unique;
diff --git a/server/migrations/046_agent_unique_name.up.sql b/server/migrations/046_agent_unique_name.up.sql
new file mode 100644
index 0000000000..98318d7d1a
--- /dev/null
+++ b/server/migrations/046_agent_unique_name.up.sql
@@ -0,0 +1,22 @@
+-- Migration: 046_agent_unique_name
+-- Enforces uniqueness of agent names within a workspace so that the API can
+-- return a clear 409 Conflict instead of a silent duplicate or a 500 error.
+--
+-- Step 1 deduplicates any existing rows that would violate the constraint,
+-- keeping the most recently updated agent when names collide.
+-- Step 2 adds the constraint so future inserts are rejected at the DB level.
+--
+-- See: docs/improvements.md PR-3, docs/pr-strategy.md Milestone 1
+
+-- Step 1: delete duplicates, keep the most recently updated one
+DELETE FROM agent a
+USING (
+ SELECT id,
+ ROW_NUMBER() OVER (PARTITION BY workspace_id, name ORDER BY updated_at DESC) AS rn
+ FROM agent
+) ranked
+WHERE a.id = ranked.id AND ranked.rn > 1;
+
+-- Step 2: add the constraint
+ALTER TABLE agent
+ ADD CONSTRAINT agent_workspace_name_unique UNIQUE (workspace_id, name);