diff --git a/apps/backend/internal/agent/settings/handlers/agent_crud_handlers_test.go b/apps/backend/internal/agent/settings/handlers/agent_crud_handlers_test.go new file mode 100644 index 0000000000..3dbe547a66 --- /dev/null +++ b/apps/backend/internal/agent/settings/handlers/agent_crud_handlers_test.go @@ -0,0 +1,451 @@ +package handlers + +import ( + "encoding/json" + "errors" + "net/http" + "net/http/httptest" + "reflect" + "strings" + "testing" + "time" + + "github.com/gin-gonic/gin" + + "github.com/kandev/kandev/internal/agent/agents" + "github.com/kandev/kandev/internal/agent/registry" + "github.com/kandev/kandev/internal/agent/settings/dto" + "github.com/kandev/kandev/internal/agent/settings/models" + "github.com/kandev/kandev/internal/common/httpmw" + ws "github.com/kandev/kandev/pkg/websocket" +) + +// fixedSettingsTime pins every seeded row's timestamps so a response body can +// be compared whole rather than field by field. +var fixedSettingsTime = time.Date(2026, 3, 4, 5, 6, 7, 0, time.UTC) + +// registerTestTUIAgent registers a deterministic agent implementation under the +// given ID. A TUI agent is the only built-in whose logo, billing type, display +// order and command are all fixed by its config, so assertions on them do not +// depend on what is installed on the machine running the test. +func registerTestTUIAgent(t *testing.T, reg *registry.Registry, id string, order int) { + t.Helper() + if err := reg.Register(agents.NewTUIAgent(agents.TUIAgentConfig{ + AgentID: id, + AgentName: id + "-name", + Display: id + " Display", + Command: id + "-binary", + Order: &order, + LogoLight: []byte(""), + LogoDark: []byte(""), + })); err != nil { + t.Fatalf("register %s: %v", id, err) + } +} + +// seedAgent adds an agent row with pinned timestamps. +func seedAgent(repo *fakeSettingsRepo, id, name string, supportsMCP bool) *models.Agent { + return repo.putAgent(&models.Agent{ + ID: id, + Name: name, + SupportsMCP: supportsMCP, + CreatedAt: fixedSettingsTime, + UpdatedAt: fixedSettingsTime, + }) +} + +// seedProfile adds a profile row with pinned timestamps. +func seedProfile(repo *fakeSettingsRepo, id, agentID, name, workspaceID string) *models.AgentProfile { + return repo.putProfile(&models.AgentProfile{ + ID: id, + AgentID: agentID, + Name: name, + AgentDisplayName: "Display", + Model: "model-a", + WorkspaceID: workspaceID, + Enabled: true, + CreatedAt: fixedSettingsTime, + UpdatedAt: fixedSettingsTime, + }) +} + +// wantProfileDTO is the DTO the seeded profile is expected to serialize to. +func wantProfileDTO(id, agentID, name, billingType string) dto.AgentProfileDTO { + return dto.AgentProfileDTO{ + ID: id, + AgentID: agentID, + Name: name, + AgentDisplayName: "Display", + Model: "model-a", + CLIFlags: []dto.CLIFlagDTO{}, + Enabled: true, + BillingType: billingType, + CreatedAt: fixedSettingsTime, + UpdatedAt: fixedSettingsTime, + } +} + +func doSettingsRequest(router *gin.Engine, method, path, body string) *httptest.ResponseRecorder { + var request *http.Request + if body == "" { + request = httptest.NewRequest(method, path, nil) + } else { + request = httptest.NewRequest(method, path, strings.NewReader(body)) + request.Header.Set("Content-Type", "application/json") + } + request.Header.Set(httpmw.InterimSettingsInterlockHeader, "test-interlock") + response := httptest.NewRecorder() + router.ServeHTTP(response, request) + return response +} + +// decodeSettingsJSON decodes a response body, failing the test on bad JSON. +func decodeSettingsJSON(t *testing.T, response *httptest.ResponseRecorder, into any) { + t.Helper() + if err := json.Unmarshal(response.Body.Bytes(), into); err != nil { + t.Fatalf("decode body %s: %v", response.Body.String(), err) + } +} + +// requireErrorBody asserts the response is exactly {"error": }. +func requireErrorBody(t *testing.T, response *httptest.ResponseRecorder, wantStatus int, wantError string) { + t.Helper() + if response.Code != wantStatus { + t.Fatalf("status = %d, want %d; body = %s", response.Code, wantStatus, response.Body.String()) + } + var body map[string]string + decodeSettingsJSON(t, response, &body) + if body["error"] != wantError { + t.Fatalf("error = %q, want %q", body["error"], wantError) + } +} + +// TestListAgentsEndpointReturnsRegistryOrderAndHidesOfficeProfiles asserts the +// whole GET /agents body: agents are ranked by the registry's DisplayOrder +// rather than store order, workspace-scoped (office) profiles are withheld, +// and billing type is filled in from the registered agent implementation. +func TestListAgentsEndpointReturnsRegistryOrderAndHidesOfficeProfiles(t *testing.T) { + repo := newFakeSettingsRepo() + seedAgent(repo, "agent-late", "late-agent", false) + seedAgent(repo, "agent-early", "early-agent", true) + seedProfile(repo, "profile-1", "agent-early", "Kanban", "") + seedProfile(repo, "profile-2", "agent-early", "Office", "ws-1") + + router, _, reg := newSettingsHarness(t, repo, nil) + registerTestTUIAgent(t, reg, "early-agent", 1) + registerTestTUIAgent(t, reg, "late-agent", 2) + + response := doSettingsRequest(router, http.MethodGet, "/api/v1/agents", "") + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + var got dto.ListAgentsResponse + decodeSettingsJSON(t, response, &got) + + want := dto.ListAgentsResponse{ + Total: 2, + Agents: []dto.AgentDTO{ + { + ID: "agent-early", Name: "early-agent", SupportsMCP: true, + Profiles: []dto.AgentProfileDTO{wantProfileDTO("profile-1", "agent-early", "Kanban", "api_key")}, + CreatedAt: fixedSettingsTime, UpdatedAt: fixedSettingsTime, + }, + { + ID: "agent-late", Name: "late-agent", + Profiles: []dto.AgentProfileDTO{}, + CreatedAt: fixedSettingsTime, UpdatedAt: fixedSettingsTime, + }, + }, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("response =\n%#v\nwant\n%#v", got, want) + } +} + +func TestListAgentsEndpointReportsStoreFailure(t *testing.T) { + repo := newFakeSettingsRepo().failWith("ListAgents", errors.New("database is locked")) + router := newSettingsRouter(t, repo, nil) + + response := doSettingsRequest(router, http.MethodGet, "/api/v1/agents", "") + requireErrorBody(t, response, http.StatusInternalServerError, "failed to list agents") +} + +// TestGetAgentEndpoint distinguishes the missing-row 404 from a store failure, +// and pins the success body including the withheld office profile. +func TestGetAgentEndpoint(t *testing.T) { + t.Run("returns the agent with only its kanban profiles", func(t *testing.T) { + repo := newFakeSettingsRepo() + seedAgent(repo, "agent-1", "test-agent", true) + seedProfile(repo, "profile-1", "agent-1", "Kanban", "") + seedProfile(repo, "profile-2", "agent-1", "Office", "ws-1") + router, _, reg := newSettingsHarness(t, repo, nil) + registerTestTUIAgent(t, reg, "test-agent", 1) + + response := doSettingsRequest(router, http.MethodGet, "/api/v1/agents/agent-1", "") + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + var got dto.AgentDTO + decodeSettingsJSON(t, response, &got) + want := dto.AgentDTO{ + ID: "agent-1", Name: "test-agent", SupportsMCP: true, + Profiles: []dto.AgentProfileDTO{wantProfileDTO("profile-1", "agent-1", "Kanban", "api_key")}, + CreatedAt: fixedSettingsTime, UpdatedAt: fixedSettingsTime, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("response =\n%#v\nwant\n%#v", got, want) + } + }) + + t.Run("unknown id is 404", func(t *testing.T) { + router := newSettingsRouter(t, newFakeSettingsRepo(), nil) + response := doSettingsRequest(router, http.MethodGet, "/api/v1/agents/missing", "") + requireErrorBody(t, response, http.StatusNotFound, "agent not found") + }) + + t.Run("store failure is 500, not 404", func(t *testing.T) { + repo := newFakeSettingsRepo().failWith("GetAgent", errors.New("database is locked")) + router := newSettingsRouter(t, repo, nil) + response := doSettingsRequest(router, http.MethodGet, "/api/v1/agents/agent-1", "") + requireErrorBody(t, response, http.StatusInternalServerError, "failed to get agent") + }) +} + +// TestCreateAgentEndpointRejectsInvalidRequests covers every 400 branch of +// httpCreateAgent, each with the specific message the handler emits. +func TestCreateAgentEndpointRejectsInvalidRequests(t *testing.T) { + cases := []struct { + name string + body string + wantError string + }{ + {name: "malformed json", body: "{", wantError: "invalid payload"}, + {name: "missing name", body: `{"profiles":[]}`, wantError: "name is required"}, + { + name: "blank nested profile name", + body: `{"name":"test-agent","profiles":[{"name":" ","model":"m"}]}`, + wantError: "profile name is required", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + repo := newFakeSettingsRepo() + router := newSettingsRouter(t, repo, nil) + response := doSettingsRequest(router, http.MethodPost, "/api/v1/agents", tc.body) + requireErrorBody(t, response, http.StatusBadRequest, tc.wantError) + if len(repo.agents) != 0 { + t.Fatalf("rejected create still wrote %d agent rows", len(repo.agents)) + } + }) + } +} + +// TestUpdateAgentEndpoint asserts the persisted mutation as well as the body: +// a handler that returned the right JSON without writing the row would pass a +// body-only assertion. +func TestUpdateAgentEndpoint(t *testing.T) { + t.Run("applies every optional field and persists it", func(t *testing.T) { + repo := newFakeSettingsRepo() + seedAgent(repo, "agent-1", "test-agent", false) + router := newSettingsRouter(t, repo, nil) + + response := doSettingsRequest(router, http.MethodPatch, "/api/v1/agents/agent-1", + `{"workspace_id":"ws-9","supports_mcp":true,"mcp_config_path":"/tmp/mcp.json"}`) + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + var got dto.AgentDTO + decodeSettingsJSON(t, response, &got) + if got.WorkspaceID == nil || *got.WorkspaceID != "ws-9" { + t.Errorf("workspace_id = %v, want ws-9", got.WorkspaceID) + } + if !got.SupportsMCP || got.MCPConfigPath != "/tmp/mcp.json" { + t.Errorf("supports_mcp/mcp_config_path = %v/%q", got.SupportsMCP, got.MCPConfigPath) + } + if len(repo.updatedAgents) != 1 { + t.Fatalf("UpdateAgent called %d times, want 1", len(repo.updatedAgents)) + } + stored := repo.updatedAgents[0] + if stored.ID != "agent-1" || !stored.SupportsMCP || stored.MCPConfigPath != "/tmp/mcp.json" { + t.Fatalf("persisted agent = %#v", stored) + } + }) + + t.Run("unknown id is 404", func(t *testing.T) { + repo := newFakeSettingsRepo() + router := newSettingsRouter(t, repo, nil) + response := doSettingsRequest(router, http.MethodPatch, "/api/v1/agents/missing", `{"supports_mcp":true}`) + requireErrorBody(t, response, http.StatusNotFound, "agent not found") + if len(repo.updatedAgents) != 0 { + t.Fatalf("404 path still wrote %d agent rows", len(repo.updatedAgents)) + } + }) + + t.Run("malformed json is 400", func(t *testing.T) { + repo := newFakeSettingsRepo() + seedAgent(repo, "agent-1", "test-agent", false) + router := newSettingsRouter(t, repo, nil) + response := doSettingsRequest(router, http.MethodPatch, "/api/v1/agents/agent-1", "{") + requireErrorBody(t, response, http.StatusBadRequest, "invalid payload") + }) +} + +// TestDeleteAgentEndpoint covers the success body, the deletion actually +// reaching the store, the async available-agents broadcast, and the 404. +func TestDeleteAgentEndpoint(t *testing.T) { + t.Run("deletes the row and broadcasts the refreshed agent list", func(t *testing.T) { + repo := newFakeSettingsRepo() + seedAgent(repo, "agent-1", "test-agent", false) + hub := newSignallingHub() + router := newSettingsRouter(t, repo, hub) + + response := doSettingsRequest(router, http.MethodDelete, "/api/v1/agents/agent-1", "") + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + var body map[string]bool + decodeSettingsJSON(t, response, &body) + if !body["success"] { + t.Fatalf("body = %s, want success true", response.Body.String()) + } + if !reflect.DeepEqual(repo.deletedAgents, []string{"agent-1"}) { + t.Fatalf("deleted agents = %v, want [agent-1]", repo.deletedAgents) + } + hub.awaitAction(t, ws.ActionAgentAvailableUpdated) + }) + + t.Run("unknown id is 404 and broadcasts nothing", func(t *testing.T) { + repo := newFakeSettingsRepo() + hub := &duplicateHub{} + router := newSettingsRouter(t, repo, hub) + + response := doSettingsRequest(router, http.MethodDelete, "/api/v1/agents/missing", "") + requireErrorBody(t, response, http.StatusNotFound, "agent not found") + if len(hub.actions()) != 0 { + t.Fatalf("404 delete broadcast %v", hub.actions()) + } + }) + + t.Run("store failure is 500", func(t *testing.T) { + repo := newFakeSettingsRepo() + seedAgent(repo, "agent-1", "test-agent", false) + repo.failWith("DeleteAgent", errors.New("database is locked")) + router := newSettingsRouter(t, repo, nil) + + response := doSettingsRequest(router, http.MethodDelete, "/api/v1/agents/agent-1", "") + requireErrorBody(t, response, http.StatusInternalServerError, "failed to delete agent") + }) +} + +// TestGetAgentLogoEndpoint pins the SVG bytes, the variant switch and the +// caching header, and separates "no such agent" from "agent has no logo" — +// both 404s, but only one of them means the agent is unknown. +func TestGetAgentLogoEndpoint(t *testing.T) { + t.Run("serves the light logo by default and the dark variant on request", func(t *testing.T) { + router, _, reg := newSettingsHarness(t, newFakeSettingsRepo(), nil) + registerTestTUIAgent(t, reg, "logo-agent", 1) + + light := doSettingsRequest(router, http.MethodGet, "/api/v1/agents/logo-agent/logo", "") + if light.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", light.Code, light.Body.String()) + } + if got := light.Body.String(); got != `` { + t.Errorf("light body = %q", got) + } + if got := light.Header().Get("Content-Type"); got != "image/svg+xml" { + t.Errorf("Content-Type = %q, want image/svg+xml", got) + } + if got := light.Header().Get("Cache-Control"); got != "public, max-age=86400" { + t.Errorf("Cache-Control = %q", got) + } + + dark := doSettingsRequest(router, http.MethodGet, "/api/v1/agents/logo-agent/logo?variant=dark", "") + if got := dark.Body.String(); got != `` { + t.Errorf("dark body = %q", got) + } + }) + + t.Run("unknown agent reports agent not found", func(t *testing.T) { + router := newSettingsRouter(t, newFakeSettingsRepo(), nil) + response := doSettingsRequest(router, http.MethodGet, "/api/v1/agents/nope/logo", "") + requireErrorBody(t, response, http.StatusNotFound, "agent not found") + }) + + t.Run("registered agent without a logo reports logo not available", func(t *testing.T) { + router, _, reg := newSettingsHarness(t, newFakeSettingsRepo(), nil) + order := 1 + if err := reg.Register(agents.NewTUIAgent(agents.TUIAgentConfig{ + AgentID: "bare-agent", AgentName: "bare", Command: "bare", Order: &order, + })); err != nil { + t.Fatalf("register bare agent: %v", err) + } + response := doSettingsRequest(router, http.MethodGet, "/api/v1/agents/bare-agent/logo", "") + requireErrorBody(t, response, http.StatusNotFound, "logo not available for agent") + }) +} + +// TestPreviewAgentCommandEndpoint asserts the rendered argv, the launcher +// prefix and the CLI-flag tokens, plus both failure branches. +func TestPreviewAgentCommandEndpoint(t *testing.T) { + t.Run("renders the argv including prefix and enabled cli flags", func(t *testing.T) { + router, _, reg := newSettingsHarness(t, newFakeSettingsRepo(), nil) + registerTestTUIAgent(t, reg, "preview-agent", 1) + + response := doSettingsRequest(router, http.MethodPost, "/api/v1/agent-command-preview/preview-agent", + `{"model":"m","command_prefix":"greywall --","cli_flags":[{"flag":"--verbose","enabled":true}]}`) + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + var got dto.CommandPreviewResponse + decodeSettingsJSON(t, response, &got) + want := dto.CommandPreviewResponse{ + Supported: true, + Command: []string{"greywall", "--", "preview-agent-binary", "--verbose"}, + CommandString: "greywall -- preview-agent-binary --verbose", + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("preview = %#v, want %#v", got, want) + } + }) + + t.Run("malformed json is 400", func(t *testing.T) { + router, _, reg := newSettingsHarness(t, newFakeSettingsRepo(), nil) + registerTestTUIAgent(t, reg, "preview-agent", 1) + response := doSettingsRequest(router, http.MethodPost, "/api/v1/agent-command-preview/preview-agent", "{") + requireErrorBody(t, response, http.StatusBadRequest, "invalid payload") + }) + + t.Run("unregistered agent is 500", func(t *testing.T) { + router := newSettingsRouter(t, newFakeSettingsRepo(), nil) + response := doSettingsRequest(router, http.MethodPost, "/api/v1/agent-command-preview/nope", `{"model":"m"}`) + requireErrorBody(t, response, http.StatusInternalServerError, `agent type "nope" not found in registry`) + }) +} + +// TestInstallJobEndpoints covers the job list/lookup pair and each distinct +// enqueue rejection: an unknown agent is 404, a known agent with no install +// script is 400, and a backend without a WS hub reports the job store as +// unavailable rather than pretending the agent is missing. +func TestInstallJobEndpoints(t *testing.T) { + router, _, reg := newSettingsHarness(t, newFakeSettingsRepo(), newSignallingHub()) + registerTestTUIAgent(t, reg, "scriptless-agent", 1) + + list := doSettingsRequest(router, http.MethodGet, "/api/v1/agent-install/jobs", "") + if list.Code != http.StatusOK || list.Body.String() != `{"jobs":[]}` { + t.Fatalf("list = %d %s", list.Code, list.Body.String()) + } + + missing := doSettingsRequest(router, http.MethodGet, "/api/v1/agent-install/jobs/nope", "") + requireErrorBody(t, missing, http.StatusNotFound, "job not found") + + unknownAgent := doSettingsRequest(router, http.MethodPost, "/api/v1/agent-install/ghost", "") + requireErrorBody(t, unknownAgent, http.StatusNotFound, "agent not found") + + scriptless := doSettingsRequest(router, http.MethodPost, "/api/v1/agent-install/scriptless-agent", "") + requireErrorBody(t, scriptless, http.StatusBadRequest, "agent has no install script") + + hubless, _, hublessReg := newSettingsHarness(t, newFakeSettingsRepo(), nil) + registerTestTUIAgent(t, hublessReg, "scriptless-agent", 1) + unavailable := doSettingsRequest(hubless, http.MethodPost, "/api/v1/agent-install/scriptless-agent", "") + requireErrorBody(t, unavailable, http.StatusServiceUnavailable, "install service not ready") +} diff --git a/apps/backend/internal/agent/settings/handlers/discovery_handlers_test.go b/apps/backend/internal/agent/settings/handlers/discovery_handlers_test.go new file mode 100644 index 0000000000..940591beda --- /dev/null +++ b/apps/backend/internal/agent/settings/handlers/discovery_handlers_test.go @@ -0,0 +1,257 @@ +package handlers + +import ( + "errors" + "net/http" + "testing" + + "github.com/kandev/kandev/internal/agent/settings/controller" + "github.com/kandev/kandev/internal/agent/settings/dto" + ws "github.com/kandev/kandev/pkg/websocket" +) + +// TestDiscoverAgentsEndpointInvalidatesCacheAndBroadcasts asserts the scan +// endpoint returns the discovery snapshot and then pushes the refreshed +// available-agents list, which is what flips the settings page out of its +// pre-scan state without a reload. +func TestDiscoverAgentsEndpointInvalidatesCacheAndBroadcasts(t *testing.T) { + hub := newSignallingHub() + router := newSettingsRouter(t, newFakeSettingsRepo(), hub) + + response := doSettingsRequest(router, http.MethodGet, "/api/v1/agents/discovery", "") + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + var got dto.ListDiscoveryResponse + decodeSettingsJSON(t, response, &got) + if got.Total != 0 || len(got.Agents) != 0 { + t.Fatalf("discovery = %#v, want an empty snapshot for an empty registry", got) + } + hub.awaitAction(t, ws.ActionAgentAvailableUpdated) +} + +// TestListAvailableAgentsEndpointIncludesUninstalledAgents pins that a +// registered agent the host does not have installed is still listed (with +// available=false) rather than dropped, and that the endpoint broadcasts +// nothing of its own. +func TestListAvailableAgentsEndpointIncludesUninstalledAgents(t *testing.T) { + hub := &duplicateHub{} + router, _, reg := newSettingsHarness(t, newFakeSettingsRepo(), hub) + registerTestTUIAgent(t, reg, "absent-agent", 1) + + response := doSettingsRequest(router, http.MethodGet, "/api/v1/agents/available", "") + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + var got dto.ListAvailableAgentsResponse + decodeSettingsJSON(t, response, &got) + if got.Total != 1 || len(got.Agents) != 1 { + t.Fatalf("available = %#v, want exactly the registered agent", got.Agents) + } + agent := got.Agents[0] + if agent.Name != "absent-agent" || agent.DisplayName != "absent-agent Display" { + t.Errorf("agent identity = %q / %q", agent.Name, agent.DisplayName) + } + if agent.Available { + t.Errorf("agent %q reported available although discovery never found it", agent.Name) + } + if len(hub.actions()) != 0 { + t.Fatalf("read-only list broadcast %v", hub.actions()) + } +} + +// TestGetAgentModelsEndpoint covers the two reachable outcomes of +// /agent-models/:agentName. +// +// KNOWN DEFECT, asserted as-is rather than fixed here (test-only work): the +// handler's controller.ErrAgentNotFound -> 404 branch is unreachable, because +// FetchDynamicModels reports an unknown agent with a fresh fmt.Errorf rather +// than the sentinel. An unknown agent therefore surfaces as a 500 carrying the +// raw message. When FetchDynamicModels is switched to the sentinel, the second +// expectation below becomes 404 / "agent not found". +func TestGetAgentModelsEndpoint(t *testing.T) { + t.Run("registered agent without a probe reports not_configured", func(t *testing.T) { + router, _, reg := newSettingsHarness(t, newFakeSettingsRepo(), nil) + registerTestTUIAgent(t, reg, "model-agent", 1) + + response := doSettingsRequest(router, http.MethodGet, "/api/v1/agent-models/model-agent", "") + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + var got dto.DynamicModelsResponse + decodeSettingsJSON(t, response, &got) + if got.AgentName != "model-agent" || got.Status != "not_configured" || got.Error != nil { + t.Fatalf("models response = %#v", got) + } + }) + + t.Run("unknown agent currently reports 500 instead of 404", func(t *testing.T) { + router := newSettingsRouter(t, newFakeSettingsRepo(), nil) + response := doSettingsRequest(router, http.MethodGet, "/api/v1/agent-models/ghost", "") + requireErrorBody(t, response, http.StatusInternalServerError, `agent "ghost" not found`) + }) +} + +// TestCreateCustomTUIAgentEndpoint covers the full create: the persisted agent +// and its seeded passthrough profile, both broadcasts, the two field +// validations, and the duplicate-slug conflict. +func TestCreateCustomTUIAgentEndpoint(t *testing.T) { + t.Run("registers the agent, seeds a passthrough profile, and broadcasts twice", func(t *testing.T) { + repo := newFakeSettingsRepo() + hub := &duplicateHub{} + router, _, reg := newSettingsHarness(t, repo, hub) + + response := doSettingsRequest(router, http.MethodPost, "/api/v1/agents/tui", + `{"display_name":"My CLI","command":"my-cli","command_args":["--flag","with space"],"model":"fast"}`) + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + var got dto.AgentDTO + decodeSettingsJSON(t, response, &got) + if got.Name != "my-cli" { + t.Errorf("agent name = %q, want the slugified display name", got.Name) + } + if got.TUIConfig == nil || got.TUIConfig.Command != "my-cli" || !got.TUIConfig.WaitForTerminal { + t.Fatalf("tui config = %#v", got.TUIConfig) + } + if len(got.TUIConfig.CommandArgs) != 2 || got.TUIConfig.CommandArgs[1] != "with space" { + t.Errorf("command args = %#v, want the spaced element preserved", got.TUIConfig.CommandArgs) + } + if len(got.Profiles) != 1 || got.Profiles[0].Name != "fast" || !got.Profiles[0].CLIPassthrough { + t.Fatalf("seeded profiles = %#v", got.Profiles) + } + if _, registered := reg.Get("my-cli"); !registered { + t.Error("agent was not registered in the in-memory registry") + } + if len(repo.created) != 1 { + t.Fatalf("stored profiles = %#v", repo.created) + } + actions := hub.actions() + if len(actions) != 2 || + actions[0] != ws.ActionAgentAvailableUpdated || + actions[1] != ws.ActionAgentProfileCreated { + t.Fatalf("broadcasts = %v, want the available list then the new profile", actions) + } + }) + + t.Run("rejections", func(t *testing.T) { + cases := []struct { + name string + body string + wantStatus int + wantError string + }{ + {name: "malformed json", body: "{", wantStatus: http.StatusBadRequest, wantError: "invalid payload"}, + { + name: "missing display name", body: `{"command":"my-cli"}`, + wantStatus: http.StatusBadRequest, wantError: "display_name is required", + }, + { + name: "missing command", body: `{"display_name":"My CLI"}`, + wantStatus: http.StatusBadRequest, wantError: "command is required", + }, + { + // Punctuation-only names slugify to the empty string, which + // would otherwise register an agent with no ID. + name: "display name with no slug characters", body: `{"display_name":"!!!","command":"my-cli"}`, + wantStatus: http.StatusBadRequest, wantError: "display name must produce a valid slug", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + repo := newFakeSettingsRepo() + hub := &duplicateHub{} + router := newSettingsRouter(t, repo, hub) + response := doSettingsRequest(router, http.MethodPost, "/api/v1/agents/tui", tc.body) + requireErrorBody(t, response, tc.wantStatus, tc.wantError) + if len(repo.agents) != 0 || len(hub.actions()) != 0 { + t.Fatalf("rejected create wrote %d agents and broadcast %v", len(repo.agents), hub.actions()) + } + }) + } + }) + + t.Run("a second agent with the same slug is 409", func(t *testing.T) { + repo := newFakeSettingsRepo() + router := newSettingsRouter(t, repo, &duplicateHub{}) + body := `{"display_name":"My CLI","command":"my-cli"}` + + if first := doSettingsRequest(router, http.MethodPost, "/api/v1/agents/tui", body); first.Code != http.StatusOK { + t.Fatalf("first create status = %d, body = %s", first.Code, first.Body.String()) + } + second := doSettingsRequest(router, http.MethodPost, "/api/v1/agents/tui", body) + requireErrorBody(t, second, http.StatusConflict, "agent already exists") + if len(repo.agents) != 1 { + t.Fatalf("conflicting create left %d agent rows, want 1", len(repo.agents)) + } + }) +} + +// TestMaintenanceErrorClassifiers pins the status/message each controller +// sentinel maps to. These feed both the install and the update endpoints, so a +// mis-mapped sentinel shows up as the wrong HTTP status on either route. +func TestMaintenanceErrorClassifiers(t *testing.T) { + t.Run("install", func(t *testing.T) { + cases := []struct { + err error + wantStatus int + wantMessage string + wantMatched bool + }{ + {controller.ErrAgentNotFound, http.StatusNotFound, "agent not found", true}, + {controller.ErrInstallScriptEmpty, http.StatusBadRequest, "agent has no install script", true}, + {controller.ErrJobStoreUnavailable, http.StatusServiceUnavailable, "install service not ready", true}, + {errors.New("disk on fire"), 0, "", false}, + } + for _, tc := range cases { + status, message, matched := classifyInstallError(tc.err) + if status != tc.wantStatus || message != tc.wantMessage || matched != tc.wantMatched { + t.Errorf("classifyInstallError(%v) = (%d, %q, %v), want (%d, %q, %v)", + tc.err, status, message, matched, tc.wantStatus, tc.wantMessage, tc.wantMatched) + } + } + }) + + t.Run("update", func(t *testing.T) { + cases := []struct { + err error + wantStatus int + wantMessage string + wantMatched bool + }{ + {controller.ErrAgentNotFound, http.StatusNotFound, "agent not found", true}, + {controller.ErrRuntimeUpdateUnsupported, http.StatusBadRequest, "agent runtime update unsupported", true}, + {controller.ErrRuntimeUpdaterUnavailable, http.StatusServiceUnavailable, "agent update service not ready", true}, + {controller.ErrRuntimeUpdateTargetRequired, http.StatusBadRequest, "target version is required", true}, + {controller.ErrRuntimeUpdateTargetInvalid, http.StatusBadRequest, "target version is invalid", true}, + {controller.ErrRuntimeUpdateTargetMissing, http.StatusBadRequest, "target version is not published", true}, + // Preview-only: the plain update classifier must not claim it, or + // the enqueue path would answer 502 for an error it cannot get. + {controller.ErrRuntimeUpdatePreviewFailed, 0, "", false}, + {errors.New("disk on fire"), 0, "", false}, + } + for _, tc := range cases { + status, message, matched := classifyUpdateError(tc.err) + if status != tc.wantStatus || message != tc.wantMessage || matched != tc.wantMatched { + t.Errorf("classifyUpdateError(%v) = (%d, %q, %v), want (%d, %q, %v)", + tc.err, status, message, matched, tc.wantStatus, tc.wantMessage, tc.wantMatched) + } + } + }) + + t.Run("update preview adds the upstream-resolution failure", func(t *testing.T) { + status, message, matched := classifyUpdatePreviewError(controller.ErrRuntimeUpdatePreviewFailed) + if status != http.StatusBadGateway || message != "unable to resolve runtime versions" || !matched { + t.Errorf("preview classifier = (%d, %q, %v), want (502, %q, true)", + status, message, matched, "unable to resolve runtime versions") + } + // Everything the update classifier already handles is delegated. + if status, message, matched := classifyUpdatePreviewError(controller.ErrAgentNotFound); //nolint:govet // shadow is intentional + status != http.StatusNotFound || message != "agent not found" || !matched { + t.Errorf("delegated classification = (%d, %q, %v)", status, message, matched) + } + if _, _, matched := classifyUpdatePreviewError(errors.New("disk on fire")); matched { + t.Error("unrelated error must not be classified") + } + }) +} diff --git a/apps/backend/internal/agent/settings/handlers/mcp_config_handlers_test.go b/apps/backend/internal/agent/settings/handlers/mcp_config_handlers_test.go new file mode 100644 index 0000000000..a6d0c0fc45 --- /dev/null +++ b/apps/backend/internal/agent/settings/handlers/mcp_config_handlers_test.go @@ -0,0 +1,224 @@ +package handlers + +import ( + "errors" + "net/http" + "reflect" + "testing" + + "github.com/gin-gonic/gin" + + "github.com/kandev/kandev/internal/agent/mcpconfig" + "github.com/kandev/kandev/internal/agent/settings/dto" + "github.com/kandev/kandev/internal/agent/settings/models" +) + +// newMcpFixture seeds one agent with one profile and returns the repo plus a +// router; supportsMCP toggles the agent's MCP capability. +func newMcpFixture(t *testing.T, supportsMCP bool) (*fakeSettingsRepo, *gin.Engine) { + t.Helper() + repo := newFakeSettingsRepo() + seedAgent(repo, "agent-1", "mcp-agent", supportsMCP) + seedProfile(repo, "profile-1", "agent-1", "Default", "") + return repo, newSettingsRouter(t, repo, nil) +} + +// TestGetProfileMcpConfigEndpoint pins the default-config body for a profile +// with no stored row, the stored body, and each distinct rejection: an unknown +// profile is 404 while an agent that does not support MCP is 400 — two +// different causes the UI renders differently. +func TestGetProfileMcpConfigEndpoint(t *testing.T) { + t.Run("profile without a stored row gets the empty default config", func(t *testing.T) { + _, router := newMcpFixture(t, true) + + response := doSettingsRequest(router, http.MethodGet, "/api/v1/agent-profiles/profile-1/mcp-config", "") + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + // `servers` must serialize as an object even when empty (the settings + // page indexes into it); `meta` is omitempty, so an empty map is + // absent from the body entirely. + if body := response.Body.String(); body != `{"profile_id":"profile-1","enabled":false,"servers":{}}` { + t.Fatalf("body = %s", body) + } + var got dto.AgentProfileMcpConfigDTO + decodeSettingsJSON(t, response, &got) + want := dto.AgentProfileMcpConfigDTO{ + ProfileID: "profile-1", + Enabled: false, + Servers: map[string]mcpconfig.ServerDef{}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("config = %#v, want %#v", got, want) + } + }) + + t.Run("stored row is returned verbatim", func(t *testing.T) { + repo, router := newMcpFixture(t, true) + repo.mcpConfigs["profile-1"] = &models.AgentProfileMcpConfig{ + ProfileID: "profile-1", + Enabled: true, + Servers: map[string]interface{}{ + "linear": map[string]interface{}{"type": "http", "url": "https://mcp.linear.app"}, + }, + Meta: map[string]interface{}{"source": "user"}, + } + + response := doSettingsRequest(router, http.MethodGet, "/api/v1/agent-profiles/profile-1/mcp-config", "") + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + var got dto.AgentProfileMcpConfigDTO + decodeSettingsJSON(t, response, &got) + want := dto.AgentProfileMcpConfigDTO{ + ProfileID: "profile-1", + Enabled: true, + Servers: map[string]mcpconfig.ServerDef{ + "linear": {Type: "http", URL: "https://mcp.linear.app"}, + }, + Meta: map[string]any{"source": "user"}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("config = %#v, want %#v", got, want) + } + }) + + t.Run("unknown profile is 404", func(t *testing.T) { + _, router := newMcpFixture(t, true) + response := doSettingsRequest(router, http.MethodGet, "/api/v1/agent-profiles/missing/mcp-config", "") + requireErrorBody(t, response, http.StatusNotFound, "agent profile not found") + }) + + t.Run("agent without MCP support is 400, not 404", func(t *testing.T) { + _, router := newMcpFixture(t, false) + response := doSettingsRequest(router, http.MethodGet, "/api/v1/agent-profiles/profile-1/mcp-config", "") + requireErrorBody(t, response, http.StatusBadRequest, "mcp not supported by agent") + }) + + t.Run("store failure is 500", func(t *testing.T) { + repo, router := newMcpFixture(t, true) + repo.failWith("GetAgentProfileMcpConfig", errors.New("database is locked")) + response := doSettingsRequest(router, http.MethodGet, "/api/v1/agent-profiles/profile-1/mcp-config", "") + requireErrorBody(t, response, http.StatusInternalServerError, "failed to get mcp config") + }) +} + +// TestUpdateProfileMcpConfigEndpoint covers the persisted write, the +// `mcpServers` compatibility alias, the never-nil servers map, and each +// rejection. +func TestUpdateProfileMcpConfigEndpoint(t *testing.T) { + t.Run("persists the servers map and echoes it back", func(t *testing.T) { + repo, router := newMcpFixture(t, true) + + response := doSettingsRequest(router, http.MethodPost, "/api/v1/agent-profiles/profile-1/mcp-config", + `{"enabled":true,"servers":{"linear":{"type":"http","url":"https://mcp.linear.app"}},"meta":{"source":"user"}}`) + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + var got dto.AgentProfileMcpConfigDTO + decodeSettingsJSON(t, response, &got) + want := dto.AgentProfileMcpConfigDTO{ + ProfileID: "profile-1", + Enabled: true, + Servers: map[string]mcpconfig.ServerDef{"linear": {Type: "http", URL: "https://mcp.linear.app"}}, + Meta: map[string]any{"source": "user"}, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("config = %#v, want %#v", got, want) + } + if len(repo.upsertedMcp) != 1 { + t.Fatalf("upserted %d rows, want 1", len(repo.upsertedMcp)) + } + stored := repo.upsertedMcp[0] + if stored.ProfileID != "profile-1" || !stored.Enabled { + t.Fatalf("stored row = %#v", stored) + } + if _, ok := stored.Servers["linear"]; !ok { + t.Fatalf("stored servers = %#v, want a linear entry", stored.Servers) + } + }) + + t.Run("mcpServers is accepted as an alias when servers is absent", func(t *testing.T) { + repo, router := newMcpFixture(t, true) + + response := doSettingsRequest(router, http.MethodPost, "/api/v1/agent-profiles/profile-1/mcp-config", + `{"enabled":true,"mcpServers":{"aliased":{"type":"stdio","command":"run-me"}}}`) + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + var got dto.AgentProfileMcpConfigDTO + decodeSettingsJSON(t, response, &got) + want := map[string]mcpconfig.ServerDef{"aliased": {Type: "stdio", Command: "run-me"}} + if !reflect.DeepEqual(got.Servers, want) { + t.Fatalf("servers = %#v, want %#v", got.Servers, want) + } + if len(repo.upsertedMcp) != 1 || len(repo.upsertedMcp[0].Servers) != 1 { + t.Fatalf("stored rows = %#v", repo.upsertedMcp) + } + }) + + t.Run("omitted servers persists an empty map, never nil", func(t *testing.T) { + repo, router := newMcpFixture(t, true) + + response := doSettingsRequest(router, http.MethodPost, + "/api/v1/agent-profiles/profile-1/mcp-config", `{"enabled":false}`) + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + var got dto.AgentProfileMcpConfigDTO + decodeSettingsJSON(t, response, &got) + if got.Servers == nil || len(got.Servers) != 0 { + t.Fatalf("servers = %#v, want an empty non-nil map", got.Servers) + } + if repo.upsertedMcp[0].Servers == nil { + t.Fatal("stored servers map is nil") + } + }) + + t.Run("rejections", func(t *testing.T) { + cases := []struct { + name string + profileID string + supportMCP bool + body string + wantStatus int + wantError string + }{ + { + name: "malformed json", profileID: "profile-1", supportMCP: true, body: "{", + wantStatus: http.StatusBadRequest, wantError: "invalid payload", + }, + { + name: "enabled omitted", profileID: "profile-1", supportMCP: true, body: `{"servers":{}}`, + wantStatus: http.StatusBadRequest, wantError: "enabled is required", + }, + { + name: "unknown profile", profileID: "missing", supportMCP: true, body: `{"enabled":true}`, + wantStatus: http.StatusNotFound, wantError: "agent profile not found", + }, + { + name: "agent without mcp support", profileID: "profile-1", supportMCP: false, body: `{"enabled":true}`, + wantStatus: http.StatusBadRequest, wantError: "mcp not supported by agent", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + repo, router := newMcpFixture(t, tc.supportMCP) + response := doSettingsRequest(router, http.MethodPost, + "/api/v1/agent-profiles/"+tc.profileID+"/mcp-config", tc.body) + requireErrorBody(t, response, tc.wantStatus, tc.wantError) + if len(repo.upsertedMcp) != 0 { + t.Fatalf("rejected update wrote %d rows", len(repo.upsertedMcp)) + } + }) + } + }) + + t.Run("store failure is 500", func(t *testing.T) { + repo, router := newMcpFixture(t, true) + repo.failWith("UpsertAgentProfileMcpConfig", errors.New("database is locked")) + response := doSettingsRequest(router, http.MethodPost, + "/api/v1/agent-profiles/profile-1/mcp-config", `{"enabled":true}`) + requireErrorBody(t, response, http.StatusInternalServerError, "failed to update mcp config") + }) +} diff --git a/apps/backend/internal/agent/settings/handlers/profile_crud_handlers_test.go b/apps/backend/internal/agent/settings/handlers/profile_crud_handlers_test.go new file mode 100644 index 0000000000..6903e3cbe4 --- /dev/null +++ b/apps/backend/internal/agent/settings/handlers/profile_crud_handlers_test.go @@ -0,0 +1,427 @@ +package handlers + +import ( + "context" + "encoding/json" + "errors" + "net/http" + "reflect" + "testing" + + "github.com/kandev/kandev/internal/agent/settings/controller" + "github.com/kandev/kandev/internal/agent/settings/dto" + ws "github.com/kandev/kandev/pkg/websocket" +) + +// fakeUtilityDeps reports the utility agents bound to a profile so the +// disable/delete confirmation branches are reachable. +type fakeUtilityDeps struct { + refs []controller.UtilityAgentReference + listErr error + cleared []string +} + +func (f *fakeUtilityDeps) ListUtilityAgentsByAgentProfile( + context.Context, string, +) ([]controller.UtilityAgentReference, error) { + return f.refs, f.listErr +} + +func (f *fakeUtilityDeps) ClearUtilityAgentProfileBindings(_ context.Context, profileID string) error { + f.cleared = append(f.cleared, profileID) + return nil +} + +// fakeRoutingTierDeps reports workspace routing tiers seeded from a profile. +// Routing tiers are a hard blocker: force=true must not bypass them. +type fakeRoutingTierDeps struct { + refs []controller.RoutingTierReference +} + +func (f *fakeRoutingTierDeps) ListRoutingTierReferencesByAgentProfile( + context.Context, string, +) ([]controller.RoutingTierReference, error) { + return f.refs, nil +} + +// decodeProfileBroadcast returns the profile carried by the single recorded +// broadcast of the given action. +func decodeProfileBroadcast(t *testing.T, hub *duplicateHub, action string) dto.AgentProfileDTO { + t.Helper() + payloads := hub.payloads(action) + if len(payloads) != 1 { + t.Fatalf("recorded %d %s broadcasts (all: %v), want 1", len(payloads), action, hub.actions()) + } + var envelope struct { + Profile dto.AgentProfileDTO `json:"profile"` + } + if err := json.Unmarshal(payloads[0], &envelope); err != nil { + t.Fatalf("decode %s payload: %v", action, err) + } + return envelope.Profile +} + +// TestCreateProfileEndpoint pins the created row, the broadcast that lets open +// settings surfaces pick it up, and each validation rejection with its own +// error message. +func TestCreateProfileEndpoint(t *testing.T) { + t.Run("creates the profile and broadcasts agent.profile.created", func(t *testing.T) { + repo := newFakeSettingsRepo() + seedAgent(repo, "agent-1", "profile-agent", false) + hub := &duplicateHub{} + router, _, reg := newSettingsHarness(t, repo, hub) + registerTestTUIAgent(t, reg, "profile-agent", 1) + + response := doSettingsRequest(router, http.MethodPost, "/api/v1/agents/agent-1/profiles", + `{"name":"Fast","model":"model-x","cli_flags":[{"flag":"--verbose","enabled":true}]}`) + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + var got dto.AgentProfileDTO + decodeSettingsJSON(t, response, &got) + if got.ID == "" || got.AgentID != "agent-1" || got.Name != "Fast" || got.Model != "model-x" { + t.Fatalf("created profile = %#v", got) + } + if !got.Enabled || !got.UserModified { + t.Errorf("created profile should be enabled and user-modified: %#v", got) + } + wantFlags := []dto.CLIFlagDTO{{Flag: "--verbose", Enabled: true}} + if !reflect.DeepEqual(got.CLIFlags, wantFlags) { + t.Errorf("cli_flags = %#v, want %#v", got.CLIFlags, wantFlags) + } + if len(repo.created) != 1 || repo.created[0].ID != got.ID { + t.Fatalf("stored profiles = %#v", repo.created) + } + if broadcast := decodeProfileBroadcast(t, hub, ws.ActionAgentProfileCreated); broadcast.ID != got.ID { + t.Errorf("broadcast profile id = %q, want %q", broadcast.ID, got.ID) + } + }) + + t.Run("rejections keep their specific message and write nothing", func(t *testing.T) { + cases := []struct { + name string + body string + wantError string + }{ + {name: "malformed json", body: "{", wantError: "invalid payload"}, + {name: "blank name", body: `{"name":" ","model":"m"}`, wantError: "profile name is required"}, + { + name: "unterminated command prefix", + body: `{"name":"Fast","command_prefix":"greywall \""}`, + wantError: `invalid command prefix: unterminated " quote`, + }, + { + name: "env var without a name", + body: `{"name":"Fast","env_vars":[{"key":"","value":"v"}]}`, + wantError: "invalid profile env vars: env_vars[0].key is required", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + repo := newFakeSettingsRepo() + seedAgent(repo, "agent-1", "profile-agent", false) + hub := &duplicateHub{} + router, _, reg := newSettingsHarness(t, repo, hub) + registerTestTUIAgent(t, reg, "profile-agent", 1) + + response := doSettingsRequest(router, http.MethodPost, "/api/v1/agents/agent-1/profiles", tc.body) + requireErrorBody(t, response, http.StatusBadRequest, tc.wantError) + if len(repo.created) != 0 { + t.Fatalf("rejected create wrote %d profiles", len(repo.created)) + } + if len(hub.actions()) != 0 { + t.Fatalf("rejected create broadcast %v", hub.actions()) + } + }) + } + }) +} + +// TestUpdateProfileEndpoint covers the success body plus broadcast, the +// missing-profile 404, and the 409 raised when disabling a profile a utility +// agent still points at. +func TestUpdateProfileEndpoint(t *testing.T) { + t.Run("applies the update and broadcasts agent.profile.updated", func(t *testing.T) { + repo := newFakeSettingsRepo() + seedAgent(repo, "agent-1", "profile-agent", false) + seedProfile(repo, "profile-1", "agent-1", "Original", "") + hub := &duplicateHub{} + router := newSettingsRouter(t, repo, hub) + + response := doSettingsRequest(router, http.MethodPatch, "/api/v1/agent-profiles/profile-1", + `{"name":"Renamed","auto_approve":true,"command_prefix":" greywall -- "}`) + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + var got dto.AgentProfileDTO + decodeSettingsJSON(t, response, &got) + if got.Name != "Renamed" || !got.AutoApprove || got.CommandPrefix != "greywall --" { + t.Fatalf("updated profile = %#v", got) + } + if len(repo.updatedProfiles) != 1 || repo.updatedProfiles[0].Name != "Renamed" { + t.Fatalf("persisted updates = %#v", repo.updatedProfiles) + } + if broadcast := decodeProfileBroadcast(t, hub, ws.ActionAgentProfileUpdated); broadcast.Name != "Renamed" { + t.Errorf("broadcast profile name = %q, want Renamed", broadcast.Name) + } + }) + + t.Run("unknown profile is 404 and broadcasts nothing", func(t *testing.T) { + repo := newFakeSettingsRepo() + hub := &duplicateHub{} + router := newSettingsRouter(t, repo, hub) + + response := doSettingsRequest(router, http.MethodPatch, "/api/v1/agent-profiles/missing", `{"name":"X"}`) + requireErrorBody(t, response, http.StatusNotFound, "agent profile not found") + if len(hub.actions()) != 0 { + t.Fatalf("404 update broadcast %v", hub.actions()) + } + }) + + t.Run("blank name is 400", func(t *testing.T) { + repo := newFakeSettingsRepo() + seedProfile(repo, "profile-1", "agent-1", "Original", "") + router := newSettingsRouter(t, repo, nil) + response := doSettingsRequest(router, http.MethodPatch, "/api/v1/agent-profiles/profile-1", `{"name":" "}`) + requireErrorBody(t, response, http.StatusBadRequest, "profile name is required") + }) + + t.Run("disabling a profile a utility agent uses is 409 unless forced", func(t *testing.T) { + repo := newFakeSettingsRepo() + seedProfile(repo, "profile-1", "agent-1", "Original", "") + hub := &duplicateHub{} + router, ctrl, _ := newSettingsHarness(t, repo, hub) + ctrl.SetUtilityDependencyChecker(&fakeUtilityDeps{ + refs: []controller.UtilityAgentReference{{ID: "utility-1", Name: "Commit message"}}, + }) + + blocked := doSettingsRequest(router, http.MethodPatch, "/api/v1/agent-profiles/profile-1", `{"enabled":false}`) + if blocked.Code != http.StatusConflict { + t.Fatalf("status = %d, want 409; body = %s", blocked.Code, blocked.Body.String()) + } + var conflict struct { + Error string `json:"error"` + UtilityAgents []controller.UtilityAgentReference `json:"utility_agents"` + } + decodeSettingsJSON(t, blocked, &conflict) + if conflict.Error != "agent profile is in use" { + t.Errorf("error = %q", conflict.Error) + } + want := []controller.UtilityAgentReference{{ID: "utility-1", Name: "Commit message"}} + if !reflect.DeepEqual(conflict.UtilityAgents, want) { + t.Errorf("utility_agents = %#v, want %#v", conflict.UtilityAgents, want) + } + if repo.profiles["profile-1"].Enabled != true { + t.Error("blocked disable still flipped the stored enabled flag") + } + if len(hub.actions()) != 0 { + t.Fatalf("blocked update broadcast %v", hub.actions()) + } + + forced := doSettingsRequest(router, http.MethodPatch, + "/api/v1/agent-profiles/profile-1?force=true", `{"enabled":false}`) + if forced.Code != http.StatusOK { + t.Fatalf("forced status = %d, body = %s", forced.Code, forced.Body.String()) + } + if repo.profiles["profile-1"].Enabled { + t.Error("forced disable did not flip the stored enabled flag") + } + }) +} + +// TestDeleteProfileEndpoint separates the success path, the 404, and the two +// distinct 409 shapes (soft blocker vs. routing tier, which force cannot skip). +func TestDeleteProfileEndpoint(t *testing.T) { + t.Run("deletes the row and broadcasts agent.profile.deleted", func(t *testing.T) { + repo := newFakeSettingsRepo() + seedProfile(repo, "profile-1", "agent-1", "Doomed", "") + hub := &duplicateHub{} + router := newSettingsRouter(t, repo, hub) + + response := doSettingsRequest(router, http.MethodDelete, "/api/v1/agent-profiles/profile-1", "") + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + var body map[string]bool + decodeSettingsJSON(t, response, &body) + if !body["success"] { + t.Fatalf("body = %s, want success true", response.Body.String()) + } + if !reflect.DeepEqual(repo.deletedProfiles, []string{"profile-1"}) { + t.Fatalf("deleted profiles = %v", repo.deletedProfiles) + } + if broadcast := decodeProfileBroadcast(t, hub, ws.ActionAgentProfileDeleted); broadcast.ID != "profile-1" { + t.Errorf("broadcast profile id = %q, want profile-1", broadcast.ID) + } + }) + + // KNOWN DEFECT, asserted as-is rather than fixed here: this test is + // test-only work. controller.DeleteProfile classifies the missing-source + // lookup with a `strings.Contains(err.Error(), "agent profile not found")` + // check, but the sqlite store returns sql.ErrNoRows from GetAgentProfile + // (its soft-delete tests pin that), so the message never matches and the + // error falls through as a 500. The sibling helper isProfileNotFoundErr in + // the same file already handles both shapes and is what DuplicateProfile + // uses. When DeleteProfile is switched to it, this expectation becomes 404 + // with an "agent profile not found" body. + t.Run("unknown profile currently reports 500 instead of 404", func(t *testing.T) { + repo := newFakeSettingsRepo() + hub := &duplicateHub{} + router := newSettingsRouter(t, repo, hub) + response := doSettingsRequest(router, http.MethodDelete, "/api/v1/agent-profiles/missing", "") + requireErrorBody(t, response, http.StatusInternalServerError, "failed to delete profile") + if len(hub.actions()) != 0 { + t.Fatalf("failed delete broadcast %v", hub.actions()) + } + if len(repo.deletedProfiles) != 0 { + t.Fatalf("failed delete removed %v", repo.deletedProfiles) + } + }) + + t.Run("routing tier references block the delete even with force", func(t *testing.T) { + repo := newFakeSettingsRepo() + seedProfile(repo, "profile-1", "agent-1", "Tiered", "") + router, ctrl, _ := newSettingsHarness(t, repo, &duplicateHub{}) + ctrl.SetRoutingTierDependencyChecker(&fakeRoutingTierDeps{ + refs: []controller.RoutingTierReference{{WorkspaceID: "ws-1", ProviderID: "anthropic", Tier: "primary"}}, + }) + + response := doSettingsRequest(router, http.MethodDelete, "/api/v1/agent-profiles/profile-1?force=true", "") + if response.Code != http.StatusConflict { + t.Fatalf("status = %d, want 409; body = %s", response.Code, response.Body.String()) + } + var conflict struct { + Error string `json:"error"` + RoutingTiers []controller.RoutingTierReference `json:"routing_tiers"` + Watchers []controller.WatcherReference `json:"watchers"` + } + decodeSettingsJSON(t, response, &conflict) + if conflict.Error != "agent profile is in use" { + t.Errorf("error = %q", conflict.Error) + } + want := []controller.RoutingTierReference{{WorkspaceID: "ws-1", ProviderID: "anthropic", Tier: "primary"}} + if !reflect.DeepEqual(conflict.RoutingTiers, want) { + t.Errorf("routing_tiers = %#v, want %#v", conflict.RoutingTiers, want) + } + if len(repo.deletedProfiles) != 0 { + t.Fatalf("blocked delete removed %v", repo.deletedProfiles) + } + }) + + t.Run("force clears utility bindings that block an unforced delete", func(t *testing.T) { + repo := newFakeSettingsRepo() + seedProfile(repo, "profile-1", "agent-1", "Bound", "") + router, ctrl, _ := newSettingsHarness(t, repo, &duplicateHub{}) + deps := &fakeUtilityDeps{refs: []controller.UtilityAgentReference{{ID: "utility-1", Name: "Title"}}} + ctrl.SetUtilityDependencyChecker(deps) + + blocked := doSettingsRequest(router, http.MethodDelete, "/api/v1/agent-profiles/profile-1", "") + if blocked.Code != http.StatusConflict { + t.Fatalf("unforced status = %d, want 409; body = %s", blocked.Code, blocked.Body.String()) + } + if len(repo.deletedProfiles) != 0 { + t.Fatalf("unforced delete removed %v", repo.deletedProfiles) + } + + forced := doSettingsRequest(router, http.MethodDelete, "/api/v1/agent-profiles/profile-1?force=true", "") + if forced.Code != http.StatusOK { + t.Fatalf("forced status = %d, body = %s", forced.Code, forced.Body.String()) + } + if !reflect.DeepEqual(deps.cleared, []string{"profile-1"}) { + t.Fatalf("cleared utility bindings = %v, want [profile-1]", deps.cleared) + } + }) + + t.Run("store failure is 500", func(t *testing.T) { + repo := newFakeSettingsRepo() + seedProfile(repo, "profile-1", "agent-1", "Doomed", "") + repo.failWith("DeleteAgentProfile", errors.New("database is locked")) + router := newSettingsRouter(t, repo, nil) + response := doSettingsRequest(router, http.MethodDelete, "/api/v1/agent-profiles/profile-1", "") + requireErrorBody(t, response, http.StatusInternalServerError, "failed to delete profile") + }) +} + +// TestProfileWriteStoreFailuresAre500 keeps a store failure distinguishable +// from a validation rejection on every profile write: each of these inputs is +// valid, so a 400 or 404 here would be the handler mis-classifying an outage. +func TestProfileWriteStoreFailuresAre500(t *testing.T) { + cases := []struct { + name string + method string + path string + body string + failMethod string + wantError string + }{ + { + name: "create profile", method: http.MethodPost, path: "/api/v1/agents/agent-1/profiles", + body: `{"name":"Fast"}`, failMethod: "CreateAgentProfile", wantError: "failed to create profile", + }, + { + name: "update profile", method: http.MethodPatch, path: "/api/v1/agent-profiles/profile-1", + body: `{"name":"Renamed"}`, failMethod: "UpdateAgentProfile", wantError: "failed to update profile", + }, + { + name: "duplicate profile", method: http.MethodPost, path: "/api/v1/agent-profiles/profile-1/duplicate", + failMethod: "GetAgentProfile", wantError: "failed to duplicate profile", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + repo := newFakeSettingsRepo() + seedAgent(repo, "agent-1", "profile-agent", false) + seedProfile(repo, "profile-1", "agent-1", "Original", "") + repo.failWith(tc.failMethod, errors.New("database is locked")) + hub := &duplicateHub{} + router, _, reg := newSettingsHarness(t, repo, hub) + registerTestTUIAgent(t, reg, "profile-agent", 1) + + response := doSettingsRequest(router, tc.method, tc.path, tc.body) + requireErrorBody(t, response, http.StatusInternalServerError, tc.wantError) + if len(hub.actions()) != 0 { + t.Fatalf("failed write broadcast %v", hub.actions()) + } + }) + } +} + +// TestProfileBroadcastIsWorkspaceScoped guards the boundary in +// broadcastProfileEvent: an office-scoped profile must never reach the global +// settings channel, and must be dropped entirely when the hub cannot route by +// workspace. +func TestProfileBroadcastIsWorkspaceScoped(t *testing.T) { + t.Run("workspace-aware hub receives it on the workspace channel only", func(t *testing.T) { + repo := newFakeSettingsRepo() + seedProfile(repo, "profile-1", "agent-1", "Office", "ws-7") + hub := newWorkspaceDuplicateHub() + router := newSettingsRouter(t, repo, hub) + + response := doSettingsRequest(router, http.MethodPatch, "/api/v1/agent-profiles/profile-1", `{"name":"Renamed"}`) + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + if len(hub.global) != 0 { + t.Fatalf("office profile leaked to the global channel: %d messages", len(hub.global)) + } + msgs := hub.workspaceMsgs["ws-7"] + if len(msgs) != 1 || msgs[0].Action != ws.ActionAgentProfileUpdated { + t.Fatalf("workspace messages = %#v", msgs) + } + }) + + t.Run("hub without workspace routing drops the event fail-closed", func(t *testing.T) { + repo := newFakeSettingsRepo() + seedProfile(repo, "profile-1", "agent-1", "Office", "ws-7") + hub := &duplicateHub{} + router := newSettingsRouter(t, repo, hub) + + response := doSettingsRequest(router, http.MethodPatch, "/api/v1/agent-profiles/profile-1", `{"name":"Renamed"}`) + if response.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", response.Code, response.Body.String()) + } + if len(hub.actions()) != 0 { + t.Fatalf("office profile reached the global channel: %v", hub.actions()) + } + }) +} diff --git a/apps/backend/internal/agent/settings/handlers/profile_duplicate_handlers_test.go b/apps/backend/internal/agent/settings/handlers/profile_duplicate_handlers_test.go index cd92831724..d88449bee4 100644 --- a/apps/backend/internal/agent/settings/handlers/profile_duplicate_handlers_test.go +++ b/apps/backend/internal/agent/settings/handlers/profile_duplicate_handlers_test.go @@ -2,16 +2,20 @@ package handlers import ( "context" + "database/sql" "encoding/json" "fmt" "net/http" "net/http/httptest" + "sort" "strings" "sync" "testing" "time" "github.com/gin-gonic/gin" + "github.com/kandev/kandev/internal/agent/discovery" + "github.com/kandev/kandev/internal/agent/registry" "github.com/kandev/kandev/internal/agent/settings/controller" "github.com/kandev/kandev/internal/agent/settings/dto" "github.com/kandev/kandev/internal/agent/settings/models" @@ -21,44 +25,106 @@ import ( ws "github.com/kandev/kandev/pkg/websocket" ) -// duplicateRepo is a minimal store.Repository stub: the duplicate path only -// reads one profile, inserts the copy, flips enabled, and reads/writes the -// MCP config row. Everything else is a no-op. -type duplicateRepo struct { - profiles map[string]*models.AgentProfile - created []*models.AgentProfile +// fakeSettingsRepo is the in-memory store.Repository shared by every handler +// test in this package. Agents, profiles and MCP config rows live in maps; +// every mutation the controller performs is recorded so a test can assert the +// downstream call, and `errs` injects a failure per repository method so the +// handlers' 500 branches are reachable. +// +// Missing rows are reported the way the sqlite store reports them, because the +// controller branches on both shapes: sql.ErrNoRows for agents, and an +// "agent profile not found" message for profiles. +type fakeSettingsRepo struct { + agents map[string]*models.Agent + agentOrder []string + profiles map[string]*models.AgentProfile + mcpConfigs map[string]*models.AgentProfileMcpConfig + + created []*models.AgentProfile + updatedProfiles []*models.AgentProfile + deletedProfiles []string + updatedAgents []*models.Agent + deletedAgents []string + upsertedMcp []*models.AgentProfileMcpConfig + + // errs maps a repository method name to the error it should return. + errs map[string]error + seq int } -// newDuplicateRepo returns a fake repository preloaded with one kanban profile (p-1) under agent-1. -func newDuplicateRepo() *duplicateRepo { - return &duplicateRepo{profiles: map[string]*models.AgentProfile{}} +// newFakeSettingsRepo returns an empty in-memory settings repository. +func newFakeSettingsRepo() *fakeSettingsRepo { + return &fakeSettingsRepo{ + agents: map[string]*models.Agent{}, + profiles: map[string]*models.AgentProfile{}, + mcpConfigs: map[string]*models.AgentProfileMcpConfig{}, + errs: map[string]error{}, + } } -// GetAgentProfile implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) GetAgentProfile(_ context.Context, id string) (*models.AgentProfile, error) { +// failWith makes the named repository method return err. +func (r *fakeSettingsRepo) failWith(method string, err error) *fakeSettingsRepo { + r.errs[method] = err + return r +} + +// putAgent seeds an agent row, preserving insertion order for ListAgents. +func (r *fakeSettingsRepo) putAgent(agent *models.Agent) *models.Agent { + if _, exists := r.agents[agent.ID]; !exists { + r.agentOrder = append(r.agentOrder, agent.ID) + } + r.agents[agent.ID] = agent + return agent +} + +// putProfile seeds a profile row. +func (r *fakeSettingsRepo) putProfile(profile *models.AgentProfile) *models.AgentProfile { + r.profiles[profile.ID] = profile + return profile +} + +func (r *fakeSettingsRepo) nextID(prefix string) string { + r.seq++ + return fmt.Sprintf("%s-%d", prefix, r.seq) +} + +// GetAgentProfile implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) GetAgentProfile(_ context.Context, id string) (*models.AgentProfile, error) { + if err := r.errs["GetAgentProfile"]; err != nil { + return nil, err + } if p, ok := r.profiles[id]; ok { return p, nil } - return nil, fmt.Errorf("agent profile not found: %s", id) + // The sqlite store returns sql.ErrNoRows here (see its soft-delete tests); + // only the update/delete paths report the "agent profile not found" + // message. The controller branches on both shapes, so the fake has to + // reproduce the split rather than pick one. + return nil, sql.ErrNoRows } -// GetAgentProfileIncludingDeleted implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) GetAgentProfileIncludingDeleted(ctx context.Context, id string) (*models.AgentProfile, error) { +// GetAgentProfileIncludingDeleted implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) GetAgentProfileIncludingDeleted(ctx context.Context, id string) (*models.AgentProfile, error) { return r.GetAgentProfile(ctx, id) } -// CreateAgentProfile implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) CreateAgentProfile(_ context.Context, p *models.AgentProfile) error { - if p.ID == "" { - p.ID = "duplicate-" + p.Name +// CreateAgentProfile implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) CreateAgentProfile(_ context.Context, p *models.AgentProfile) error { + if err := r.errs["CreateAgentProfile"]; err != nil { + return err } + if p.ID == "" { + p.ID = r.nextID("profile") + } + now := time.Now().UTC() + p.CreatedAt, p.UpdatedAt = now, now r.profiles[p.ID] = p r.created = append(r.created, p) return nil } -// DuplicateAgentProfile implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) DuplicateAgentProfile(_ context.Context, input store.DuplicateAgentProfileInput) error { +// DuplicateAgentProfile implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) DuplicateAgentProfile(_ context.Context, input store.DuplicateAgentProfileInput) error { // Version check: the stored source must match the caller's snapshot. if src, ok := r.profiles[input.Source.ID]; ok && !src.UpdatedAt.Equal(input.Source.UpdatedAt) { return store.ErrProfileChanged @@ -78,8 +144,11 @@ func (r *duplicateRepo) DuplicateAgentProfile(_ context.Context, input store.Dup return nil } -// UpdateAgentProfileEnabled implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) UpdateAgentProfileEnabled(_ context.Context, id string, enabled bool) (time.Time, error) { +// UpdateAgentProfileEnabled implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) UpdateAgentProfileEnabled(_ context.Context, id string, enabled bool) (time.Time, error) { + if err := r.errs["UpdateAgentProfileEnabled"]; err != nil { + return time.Time{}, err + } p, ok := r.profiles[id] if !ok { return time.Time{}, fmt.Errorf("agent profile not found: %s", id) @@ -89,79 +158,207 @@ func (r *duplicateRepo) UpdateAgentProfileEnabled(_ context.Context, id string, return p.UpdatedAt, nil } -// GetAgentProfileMcpConfig implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) GetAgentProfileMcpConfig(context.Context, string) (*models.AgentProfileMcpConfig, error) { - return nil, nil +// GetAgentProfileMcpConfig implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) GetAgentProfileMcpConfig(_ context.Context, profileID string) (*models.AgentProfileMcpConfig, error) { + if err := r.errs["GetAgentProfileMcpConfig"]; err != nil { + return nil, err + } + if cfg, ok := r.mcpConfigs[profileID]; ok { + return cfg, nil + } + return nil, sql.ErrNoRows } -// UpsertAgentProfileMcpConfig implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) UpsertAgentProfileMcpConfig(context.Context, *models.AgentProfileMcpConfig) error { +// UpsertAgentProfileMcpConfig implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) UpsertAgentProfileMcpConfig(_ context.Context, config *models.AgentProfileMcpConfig) error { + if err := r.errs["UpsertAgentProfileMcpConfig"]; err != nil { + return err + } + r.mcpConfigs[config.ProfileID] = config + r.upsertedMcp = append(r.upsertedMcp, config) return nil } -// CreateAgent implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) CreateAgent(context.Context, *models.Agent) error { return nil } - -// GetAgent implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) GetAgent(context.Context, string) (*models.Agent, error) { - return nil, nil -} - -// GetAgentByName implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) GetAgentByName(context.Context, string) (*models.Agent, error) { - return nil, nil -} - -// UpdateAgent implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) UpdateAgent(context.Context, *models.Agent) error { return nil } - -// DeleteAgent implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) DeleteAgent(context.Context, string) error { return nil } - -// ListAgents implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) ListAgents(context.Context) ([]*models.Agent, error) { - return nil, nil -} - -// ListTUIAgents implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) ListTUIAgents(context.Context) ([]*models.Agent, error) { - return nil, nil -} - -// UpdateAgentProfile implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) UpdateAgentProfile(context.Context, *models.AgentProfile) error { +// CreateAgent implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) CreateAgent(_ context.Context, agent *models.Agent) error { + if err := r.errs["CreateAgent"]; err != nil { + return err + } + if agent.ID == "" { + agent.ID = r.nextID("agent") + } + r.putAgent(agent) return nil } -// DeleteAgentProfile implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) DeleteAgentProfile(context.Context, string) error { return nil } - -// ListAgentProfiles implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) ListAgentProfiles(context.Context, string) ([]*models.AgentProfile, error) { - return nil, nil +// GetAgent implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) GetAgent(_ context.Context, id string) (*models.Agent, error) { + if err := r.errs["GetAgent"]; err != nil { + return nil, err + } + if agent, ok := r.agents[id]; ok { + return agent, nil + } + return nil, sql.ErrNoRows } -// HasDeletedAgentProfiles implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) HasDeletedAgentProfiles(context.Context, string) (bool, error) { +// GetAgentByName implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) GetAgentByName(_ context.Context, name string) (*models.Agent, error) { + if err := r.errs["GetAgentByName"]; err != nil { + return nil, err + } + for _, agent := range r.agents { + if agent.Name == name { + return agent, nil + } + } + return nil, sql.ErrNoRows +} + +// UpdateAgent implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) UpdateAgent(_ context.Context, agent *models.Agent) error { + if err := r.errs["UpdateAgent"]; err != nil { + return err + } + r.putAgent(agent) + r.updatedAgents = append(r.updatedAgents, agent) + return nil +} + +// DeleteAgent implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) DeleteAgent(_ context.Context, id string) error { + if err := r.errs["DeleteAgent"]; err != nil { + return err + } + if _, ok := r.agents[id]; !ok { + return fmt.Errorf("agent not found: %s", id) + } + delete(r.agents, id) + r.deletedAgents = append(r.deletedAgents, id) + return nil +} + +// ListAgents implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) ListAgents(context.Context) ([]*models.Agent, error) { + if err := r.errs["ListAgents"]; err != nil { + return nil, err + } + out := make([]*models.Agent, 0, len(r.agentOrder)) + for _, id := range r.agentOrder { + if agent, ok := r.agents[id]; ok { + out = append(out, agent) + } + } + return out, nil +} + +// ListTUIAgents implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) ListTUIAgents(ctx context.Context) ([]*models.Agent, error) { + agents, err := r.ListAgents(ctx) + if err != nil { + return nil, err + } + out := make([]*models.Agent, 0, len(agents)) + for _, agent := range agents { + if agent.TUIConfig != nil { + out = append(out, agent) + } + } + return out, nil +} + +// UpdateAgentProfile implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) UpdateAgentProfile(_ context.Context, profile *models.AgentProfile) error { + if err := r.errs["UpdateAgentProfile"]; err != nil { + return err + } + profile.UpdatedAt = time.Now().UTC() + r.profiles[profile.ID] = profile + r.updatedProfiles = append(r.updatedProfiles, profile) + return nil +} + +// DeleteAgentProfile implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) DeleteAgentProfile(_ context.Context, id string) error { + if err := r.errs["DeleteAgentProfile"]; err != nil { + return err + } + if _, ok := r.profiles[id]; !ok { + return fmt.Errorf("agent profile not found: %s", id) + } + delete(r.profiles, id) + r.deletedProfiles = append(r.deletedProfiles, id) + return nil +} + +// ListAgentProfiles implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) ListAgentProfiles(_ context.Context, agentID string) ([]*models.AgentProfile, error) { + if err := r.errs["ListAgentProfiles"]; err != nil { + return nil, err + } + out := make([]*models.AgentProfile, 0, len(r.profiles)) + for _, p := range r.profiles { + if p.AgentID == agentID && p.DeletedAt == nil { + out = append(out, p) + } + } + sort.Slice(out, func(i, j int) bool { return out[i].ID < out[j].ID }) + return out, nil +} + +// HasDeletedAgentProfiles implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) HasDeletedAgentProfiles(context.Context, string) (bool, error) { return false, nil } -// Close implements the settings store interface for the duplicate handler tests. -func (r *duplicateRepo) Close() error { return nil } +// Close implements the settings store interface for the handler tests. +func (r *fakeSettingsRepo) Close() error { return nil } -var _ store.Repository = (*duplicateRepo)(nil) +var _ store.Repository = (*fakeSettingsRepo)(nil) // duplicateHub captures every WS message so tests can assert the broadcast. +// It deliberately does NOT implement BroadcastToWorkspaceOrDrop, which is what +// makes it the fixture for broadcastProfileEvent's fail-closed drop branch. type duplicateHub struct { mu sync.Mutex msgs []*ws.Message + // signal receives every broadcast action, so a test can join an + // asynchronous broadcast goroutine instead of sleeping. Nil by default: + // the non-blocking send then falls straight through to the default case. + signal chan string +} + +// newSignallingHub returns a hub that also publishes each broadcast action on +// a buffered channel, for tests that must wait on an async broadcast. +func newSignallingHub() *duplicateHub { + return &duplicateHub{signal: make(chan string, 8)} } // Broadcast records a global notification so tests can assert (non-)delivery. func (h *duplicateHub) Broadcast(msg *ws.Message) { h.mu.Lock() - defer h.mu.Unlock() h.msgs = append(h.msgs, msg) + h.mu.Unlock() + select { + case h.signal <- msg.Action: + default: + } +} + +// awaitAction blocks until the hub broadcasts the given action. +func (h *duplicateHub) awaitAction(t *testing.T, action string) { + t.Helper() + deadline := time.After(2 * time.Second) + for { + select { + case got := <-h.signal: + if got == action { + return + } + case <-deadline: + t.Fatalf("no %q broadcast within 2s; recorded %v", action, h.actions()) + } + } } // actions returns the global notifications recorded by Broadcast. @@ -175,6 +372,19 @@ func (h *duplicateHub) actions() []string { return out } +// payloads returns the recorded notifications for one action. +func (h *duplicateHub) payloads(action string) []json.RawMessage { + h.mu.Lock() + defer h.mu.Unlock() + out := make([]json.RawMessage, 0, len(h.msgs)) + for _, m := range h.msgs { + if m.Action == action { + out = append(out, m.Payload) + } + } + return out +} + // workspaceDuplicateHub models the gateway hub: global Broadcast plus the // workspace-scoped, fail-closed BroadcastToWorkspaceOrDrop. type workspaceDuplicateHub struct { @@ -183,6 +393,11 @@ type workspaceDuplicateHub struct { workspaceMsgs map[string][]*ws.Message } +// newWorkspaceDuplicateHub returns a workspace-routing-aware hub fake. +func newWorkspaceDuplicateHub() *workspaceDuplicateHub { + return &workspaceDuplicateHub{workspaceMsgs: map[string][]*ws.Message{}} +} + // Broadcast records a global notification so tests can assert (non-)delivery. func (h *workspaceDuplicateHub) Broadcast(msg *ws.Message) { h.mu.Lock() @@ -197,23 +412,47 @@ func (h *workspaceDuplicateHub) BroadcastToWorkspaceOrDrop(workspaceID string, m h.workspaceMsgs[workspaceID] = append(h.workspaceMsgs[workspaceID], msg) } -// newDuplicateRouter builds a gin router with the settings handlers wired to the given repo and hub. -func newDuplicateRouter(t *testing.T, repo store.Repository, hub Broadcaster) *gin.Engine { +// newSettingsHarness wires the settings handlers to the given repo and hub and +// returns the router plus the controller and agent registry, so a test can +// register a deterministic agent implementation or attach a dependency checker. +func newSettingsHarness( + t *testing.T, + repo store.Repository, + hub Broadcaster, +) (*gin.Engine, *controller.Controller, *registry.Registry) { t.Helper() gin.SetMode(gin.TestMode) log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"}) if err != nil { t.Fatalf("NewLogger: %v", err) } - ctrl := controller.NewController(repo, nil, nil, nil, log) + reg := registry.NewRegistry(log) + // The async available-agents broadcast dereferences the discovery registry, + // and it runs in a goroutine where a nil panic would take the test binary + // down rather than failing one test. Load an (empty) real one instead. + discoveryRegistry, err := discovery.LoadRegistry(context.Background(), reg, log) + if err != nil { + t.Fatalf("LoadRegistry: %v", err) + } + ctrl := controller.NewController(repo, discoveryRegistry, reg, nil, log) router := gin.New() - NewHandlers(ctrl, hub, log, "test-interlock").registerHTTP(router) + // Register through the production entry point so the install/update job + // stores are wired from the hub exactly as they are at startup — with a nil + // hub they stay unavailable, which is itself a behaviour under test. + RegisterRoutes(router, ctrl, hub, log, "test-interlock") + return router, ctrl, reg +} + +// newSettingsRouter builds a gin router with the settings handlers wired to the given repo and hub. +func newSettingsRouter(t *testing.T, repo store.Repository, hub Broadcaster) *gin.Engine { + t.Helper() + router, _, _ := newSettingsHarness(t, repo, hub) return router } // TestDuplicateProfileEndpoint_CopiesAndBroadcasts verifies the HTTP endpoint copies a kanban profile and broadcasts agent.profile.created. func TestDuplicateProfileEndpoint_CopiesAndBroadcasts(t *testing.T) { - repo := newDuplicateRepo() + repo := newFakeSettingsRepo() repo.profiles["source-1"] = &models.AgentProfile{ ID: "source-1", AgentID: "agent-1", @@ -224,7 +463,7 @@ func TestDuplicateProfileEndpoint_CopiesAndBroadcasts(t *testing.T) { Enabled: true, } hub := &duplicateHub{} - router := newDuplicateRouter(t, repo, hub) + router := newSettingsRouter(t, repo, hub) req := httptest.NewRequest(http.MethodPost, "/api/v1/agent-profiles/source-1/duplicate", nil) req.Header.Set(httpmw.InterimSettingsInterlockHeader, "test-interlock") @@ -267,7 +506,7 @@ func TestDuplicateProfileEndpoint_CopiesAndBroadcasts(t *testing.T) { // TestDuplicateProfileEndpoint_NotFound verifies an unknown source ID surfaces as HTTP 404. func TestDuplicateProfileEndpoint_NotFound(t *testing.T) { - router := newDuplicateRouter(t, newDuplicateRepo(), nil) + router := newSettingsRouter(t, newFakeSettingsRepo(), nil) req := httptest.NewRequest(http.MethodPost, "/api/v1/agent-profiles/missing/duplicate", nil) req.Header.Set(httpmw.InterimSettingsInterlockHeader, "test-interlock") @@ -288,7 +527,7 @@ func TestDuplicateProfileEndpoint_NotFound(t *testing.T) { // surfaces as 404 (existence hidden) and no event is broadcast on any channel // (workspace-aware or global). func TestDuplicateProfileEndpoint_RejectsOfficeScopedSource(t *testing.T) { - repo := newDuplicateRepo() + repo := newFakeSettingsRepo() repo.profiles["source-office"] = &models.AgentProfile{ ID: "source-office", AgentID: "agent-1", @@ -296,8 +535,8 @@ func TestDuplicateProfileEndpoint_RejectsOfficeScopedSource(t *testing.T) { WorkspaceID: "ws-1", Enabled: true, } - hub := &workspaceDuplicateHub{workspaceMsgs: map[string][]*ws.Message{}} - router := newDuplicateRouter(t, repo, hub) + hub := newWorkspaceDuplicateHub() + router := newSettingsRouter(t, repo, hub) req := httptest.NewRequest(http.MethodPost, "/api/v1/agent-profiles/source-office/duplicate", nil) req.Header.Set(httpmw.InterimSettingsInterlockHeader, "test-interlock") @@ -317,7 +556,7 @@ func TestDuplicateProfileEndpoint_RejectsOfficeScopedSource(t *testing.T) { // TestDuplicateProfileEndpoint_RequiresInterlock verifies the duplicate route is rejected without the interlock token. func TestDuplicateProfileEndpoint_RequiresInterlock(t *testing.T) { - router := newDuplicateRouter(t, newDuplicateRepo(), nil) + router := newSettingsRouter(t, newFakeSettingsRepo(), nil) req := httptest.NewRequest(http.MethodPost, "/api/v1/agent-profiles/source-1/duplicate", nil) rec := httptest.NewRecorder() diff --git a/apps/backend/internal/utility/handlers/crud_handlers_test.go b/apps/backend/internal/utility/handlers/crud_handlers_test.go new file mode 100644 index 0000000000..f8dfa084cf --- /dev/null +++ b/apps/backend/internal/utility/handlers/crud_handlers_test.go @@ -0,0 +1,483 @@ +package handlers + +import ( + "bytes" + "encoding/json" + "errors" + "io" + "net/http" + "reflect" + "testing" + "time" + + "github.com/kandev/kandev/internal/utility/dto" + "github.com/kandev/kandev/internal/utility/models" +) + +// fixedUtilityTime pins seeded timestamps so a response body can be compared +// whole rather than field by field. +var fixedUtilityTime = time.Date(2026, 3, 4, 5, 6, 7, 0, time.UTC) + +// seedUtilityAgent adds an agent row with pinned timestamps. +func seedUtilityAgent(f *utilityFixture, agent *models.UtilityAgent) *models.UtilityAgent { + agent.CreatedAt = fixedUtilityTime + agent.UpdatedAt = fixedUtilityTime + return f.repo.putAgent(agent) +} + +// do issues a request against the fixture's live server and returns the status +// plus the raw body. +func do(t *testing.T, f *utilityFixture, method, path, body string) (int, []byte) { + t.Helper() + var reader io.Reader + if body != "" { + reader = bytes.NewReader([]byte(body)) + } + req, err := http.NewRequest(method, f.server.URL+path, reader) //nolint:noctx // httptest server + if err != nil { + t.Fatalf("new request: %v", err) + } + if body != "" { + req.Header.Set("Content-Type", "application/json") + } + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatalf("%s %s: %v", method, path, err) + } + defer func() { _ = resp.Body.Close() }() + raw, err := io.ReadAll(resp.Body) + if err != nil { + t.Fatalf("read body: %v", err) + } + return resp.StatusCode, raw +} + +// decodeInto decodes a response body, failing the test on bad JSON. +func decodeInto(t *testing.T, raw []byte, into any) { + t.Helper() + if err := json.Unmarshal(raw, into); err != nil { + t.Fatalf("decode body %s: %v", raw, err) + } +} + +// requireUtilityError asserts the response is exactly {"error": }. +func requireUtilityError(t *testing.T, status int, raw []byte, wantStatus int, wantError string) { + t.Helper() + if status != wantStatus { + t.Fatalf("status = %d, want %d; body = %s", status, wantStatus, raw) + } + var body map[string]string + decodeInto(t, raw, &body) + if body["error"] != wantError { + t.Fatalf("error = %q, want %q", body["error"], wantError) + } +} + +// TestListUtilityAgentsEndpoint pins the whole list body in store order and the +// store-failure 500. +func TestListUtilityAgentsEndpoint(t *testing.T) { + t.Run("returns every agent in store order", func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{}) + seedUtilityAgent(f, &models.UtilityAgent{ + ID: "builtin-1", Name: "Commit message", Prompt: "Summarize {{GitDiff}}", + AgentID: "claude-acp", Model: "sonnet", Builtin: true, Enabled: true, + ProfileBindingState: models.ProfileBindingInherit, + }) + seedUtilityAgent(f, &models.UtilityAgent{ + ID: "custom-1", Name: "Reviewer", Description: "Reviews diffs", Prompt: "Review", + AgentID: "codex-acp", Model: "gpt-5", Enabled: true, + }) + + status, raw := do(t, f, http.MethodGet, "/api/v1/utility/agents", "") + if status != http.StatusOK { + t.Fatalf("status = %d, body = %s", status, raw) + } + var got dto.UtilityAgentsResponse + decodeInto(t, raw, &got) + want := dto.UtilityAgentsResponse{Agents: []dto.UtilityAgentDTO{ + { + ID: "builtin-1", Name: "Commit message", Prompt: "Summarize {{GitDiff}}", + AgentID: "claude-acp", Model: "sonnet", Builtin: true, Enabled: true, + ProfileBindingState: models.ProfileBindingInherit, + CreatedAt: "2026-03-04T05:06:07Z", UpdatedAt: "2026-03-04T05:06:07Z", + }, + { + ID: "custom-1", Name: "Reviewer", Description: "Reviews diffs", Prompt: "Review", + AgentID: "codex-acp", Model: "gpt-5", Enabled: true, + CreatedAt: "2026-03-04T05:06:07Z", UpdatedAt: "2026-03-04T05:06:07Z", + }, + }} + if !reflect.DeepEqual(got, want) { + t.Fatalf("response =\n%#v\nwant\n%#v", got, want) + } + }) + + t.Run("store failure is 500", func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{}) + f.repo.failWith("ListAgents", errors.New("database is locked")) + status, raw := do(t, f, http.MethodGet, "/api/v1/utility/agents", "") + requireUtilityError(t, status, raw, http.StatusInternalServerError, "failed to list utility agents") + }) +} + +// TestGetUtilityAgentEndpoint separates the missing-row 404 from a store +// failure; both used to be reported as 500 by an earlier revision. +func TestGetUtilityAgentEndpoint(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{}) + seedUtilityAgent(f, &models.UtilityAgent{ + ID: "custom-1", Name: "Reviewer", Prompt: "Review", AgentID: "codex-acp", Model: "gpt-5", Enabled: true, + }) + + status, raw := do(t, f, http.MethodGet, "/api/v1/utility/agents/custom-1", "") + if status != http.StatusOK { + t.Fatalf("status = %d, body = %s", status, raw) + } + var got dto.UtilityAgentDTO + decodeInto(t, raw, &got) + if got.ID != "custom-1" || got.Name != "Reviewer" || got.Model != "gpt-5" { + t.Fatalf("agent = %#v", got) + } + + missingStatus, missingRaw := do(t, f, http.MethodGet, "/api/v1/utility/agents/nope", "") + requireUtilityError(t, missingStatus, missingRaw, http.StatusNotFound, "failed to get utility agent") + + f.repo.failWith("GetAgentByID", errors.New("database is locked")) + brokenStatus, brokenRaw := do(t, f, http.MethodGet, "/api/v1/utility/agents/custom-1", "") + requireUtilityError(t, brokenStatus, brokenRaw, http.StatusInternalServerError, "failed to get utility agent") +} + +// TestCreateUtilityAgentEndpoint pins the created row (including the enabled +// default that a bad revision once left false) and each rejection. +func TestCreateUtilityAgentEndpoint(t *testing.T) { + t.Run("creates an enabled custom agent", func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{}) + status, raw := do(t, f, http.MethodPost, "/api/v1/utility/agents", + `{"name":"Reviewer","description":"Reviews diffs","prompt":"Review {{GitDiff}}",`+ + `"agent_id":"codex-acp","model":"gpt-5"}`) + if status != http.StatusCreated { + t.Fatalf("status = %d, body = %s", status, raw) + } + var got dto.UtilityAgentDTO + decodeInto(t, raw, &got) + if got.ID == "" || got.Name != "Reviewer" || got.Prompt != "Review {{GitDiff}}" { + t.Fatalf("created agent = %#v", got) + } + if got.Builtin || !got.Enabled { + t.Errorf("created agent should be custom and enabled: %#v", got) + } + stored, err := f.repo.GetAgentByID(t.Context(), got.ID) + if err != nil { + t.Fatalf("stored agent lookup: %v", err) + } + if stored.AgentID != "codex-acp" || stored.Model != "gpt-5" || !stored.Enabled { + t.Fatalf("stored agent = %#v", stored) + } + }) + + t.Run("rejections", func(t *testing.T) { + cases := []struct { + name string + body string + wantStatus int + wantError string + }{ + { + name: "malformed json", body: "{", + wantStatus: http.StatusBadRequest, wantError: "invalid payload", + }, + { + // name and prompt are `binding:"required"`, so this is rejected + // by the binder before the service sees it. + name: "missing prompt", body: `{"name":"Reviewer"}`, + wantStatus: http.StatusBadRequest, wantError: "invalid payload", + }, + { + // Past the binder: the service rejects a custom agent with no + // inference target, which is a 400 rather than a 500. + name: "no agent_id or model", body: `{"name":"Reviewer","prompt":"Review"}`, + wantStatus: http.StatusBadRequest, wantError: "failed to create utility agent", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{}) + status, raw := do(t, f, http.MethodPost, "/api/v1/utility/agents", tc.body) + requireUtilityError(t, status, raw, tc.wantStatus, tc.wantError) + agents, err := f.repo.ListAgents(t.Context()) + if err != nil { + t.Fatalf("list agents: %v", err) + } + if len(agents) != 0 { + t.Fatalf("rejected create wrote %d rows", len(agents)) + } + }) + } + }) + + t.Run("store failure is 500", func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{}) + f.repo.failWith("CreateAgent", errors.New("database is locked")) + status, raw := do(t, f, http.MethodPost, "/api/v1/utility/agents", + `{"name":"Reviewer","prompt":"Review","agent_id":"codex-acp","model":"gpt-5"}`) + requireUtilityError(t, status, raw, http.StatusInternalServerError, "failed to create utility agent") + }) +} + +// TestUpdateUtilityAgentEndpoint covers each of the four statuses the handler +// can return, which is the point: not-found, invalid and built-in are three +// different causes that a "not 200" assertion would conflate. +func TestUpdateUtilityAgentEndpoint(t *testing.T) { + t.Run("applies the patch and persists it", func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{}) + seedUtilityAgent(f, &models.UtilityAgent{ + ID: "custom-1", Name: "Reviewer", Prompt: "Review", AgentID: "codex-acp", Model: "gpt-5", Enabled: true, + }) + + status, raw := do(t, f, http.MethodPatch, "/api/v1/utility/agents/custom-1", + `{"name":" Renamed ","description":"New","enabled":false}`) + if status != http.StatusOK { + t.Fatalf("status = %d, body = %s", status, raw) + } + var got dto.UtilityAgentDTO + decodeInto(t, raw, &got) + if got.Name != "Renamed" || got.Description != "New" || got.Enabled { + t.Fatalf("updated agent = %#v", got) + } + stored, err := f.repo.GetAgentByID(t.Context(), "custom-1") + if err != nil { + t.Fatalf("stored agent lookup: %v", err) + } + if stored.Name != "Renamed" || stored.Enabled { + t.Fatalf("stored agent = %#v", stored) + } + }) + + t.Run("rejections", func(t *testing.T) { + cases := []struct { + name string + id string + body string + wantStatus int + wantError string + }{ + { + // Rejected by the binder, before the service is reached, so it + // carries the binder's own message rather than the service's. + name: "malformed json", id: "custom-1", body: "{", + wantStatus: http.StatusBadRequest, wantError: "invalid payload", + }, + { + name: "unknown id", id: "nope", body: `{"name":"X"}`, + wantStatus: http.StatusNotFound, wantError: "failed to update utility agent", + }, + { + name: "blank name", id: "custom-1", body: `{"name":" "}`, + wantStatus: http.StatusBadRequest, wantError: "failed to update utility agent", + }, + { + name: "blank prompt", id: "custom-1", body: `{"prompt":" "}`, + wantStatus: http.StatusBadRequest, wantError: "failed to update utility agent", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{}) + seedUtilityAgent(f, &models.UtilityAgent{ + ID: "custom-1", Name: "Reviewer", Prompt: "Review", + AgentID: "codex-acp", Model: "gpt-5", Enabled: true, + }) + status, raw := do(t, f, http.MethodPatch, "/api/v1/utility/agents/"+tc.id, tc.body) + requireUtilityError(t, status, raw, tc.wantStatus, tc.wantError) + stored, err := f.repo.GetAgentByID(t.Context(), "custom-1") + if err != nil { + t.Fatalf("stored agent lookup: %v", err) + } + if stored.Name != "Reviewer" || stored.Prompt != "Review" { + t.Fatalf("rejected update mutated the row: %#v", stored) + } + }) + } + }) + + t.Run("a built-in with no inference target may still be enabled", func(t *testing.T) { + // Built-ins fall back to the user's default agent/model at execution + // time, so the "custom agent needs a target" rule must not apply. + f := newUtilityFixture(t, utilityFixtureOptions{}) + seedUtilityAgent(f, &models.UtilityAgent{ + ID: "builtin-1", Name: "Commit", Prompt: "Sum", Builtin: true, + ProfileBindingState: models.ProfileBindingInherit, + }) + status, raw := do(t, f, http.MethodPatch, "/api/v1/utility/agents/builtin-1", `{"enabled":true}`) + if status != http.StatusOK { + t.Fatalf("status = %d, body = %s", status, raw) + } + stored, err := f.repo.GetAgentByID(t.Context(), "builtin-1") + if err != nil { + t.Fatalf("stored agent lookup: %v", err) + } + if !stored.Enabled { + t.Fatal("built-in was not enabled") + } + }) + + t.Run("enabling a custom agent with no inference target is 400", func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{}) + seedUtilityAgent(f, &models.UtilityAgent{ID: "custom-1", Name: "Reviewer", Prompt: "Review"}) + status, raw := do(t, f, http.MethodPatch, "/api/v1/utility/agents/custom-1", `{"enabled":true}`) + requireUtilityError(t, status, raw, http.StatusBadRequest, "failed to update utility agent") + stored, err := f.repo.GetAgentByID(t.Context(), "custom-1") + if err != nil { + t.Fatalf("stored agent lookup: %v", err) + } + if stored.Enabled { + t.Fatal("rejected update still enabled the row") + } + }) +} + +// TestDeleteUtilityAgentEndpoint keeps forbidden (built-in) distinct from +// not-found: the UI hides the delete affordance on the former, so collapsing +// them would hide a real regression. +func TestDeleteUtilityAgentEndpoint(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{}) + seedUtilityAgent(f, &models.UtilityAgent{ID: "custom-1", Name: "Reviewer", Prompt: "Review"}) + seedUtilityAgent(f, &models.UtilityAgent{ID: "builtin-1", Name: "Commit", Prompt: "Sum", Builtin: true}) + + status, raw := do(t, f, http.MethodDelete, "/api/v1/utility/agents/custom-1", "") + if status != http.StatusOK || string(raw) != `{"success":true}` { + t.Fatalf("delete = %d %s", status, raw) + } + if _, err := f.repo.GetAgentByID(t.Context(), "custom-1"); err == nil { + t.Fatal("row survived the delete") + } + + builtinStatus, builtinRaw := do(t, f, http.MethodDelete, "/api/v1/utility/agents/builtin-1", "") + requireUtilityError(t, builtinStatus, builtinRaw, http.StatusForbidden, "failed to delete utility agent") + if _, err := f.repo.GetAgentByID(t.Context(), "builtin-1"); err != nil { + t.Fatal("forbidden delete removed the built-in row") + } + + missingStatus, missingRaw := do(t, f, http.MethodDelete, "/api/v1/utility/agents/nope", "") + requireUtilityError(t, missingStatus, missingRaw, http.StatusNotFound, "failed to delete utility agent") + + f.repo.failWith("DeleteAgent", errors.New("database is locked")) + seedUtilityAgent(f, &models.UtilityAgent{ID: "custom-2", Name: "Other", Prompt: "P"}) + brokenStatus, brokenRaw := do(t, f, http.MethodDelete, "/api/v1/utility/agents/custom-2", "") + requireUtilityError(t, brokenStatus, brokenRaw, http.StatusInternalServerError, "failed to delete utility agent") +} + +// TestTemplateVariablesEndpoint pins that the documented variables reach the +// wire: the settings editor renders this list as the insertable placeholders, +// so an empty or renamed entry breaks prompt authoring silently. +func TestTemplateVariablesEndpoint(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{}) + status, raw := do(t, f, http.MethodGet, "/api/v1/utility/template-variables", "") + if status != http.StatusOK { + t.Fatalf("status = %d, body = %s", status, raw) + } + var got dto.TemplateVariablesResponse + decodeInto(t, raw, &got) + if len(got.Variables) == 0 { + t.Fatal("no template variables returned") + } + names := make(map[string]bool, len(got.Variables)) + for _, v := range got.Variables { + names[v.Name] = true + } + for _, want := range []string{"GitDiff", "TaskTitle", "UserPrompt"} { + if !names[want] { + t.Errorf("variable %q missing from %v", want, names) + } + } +} + +// TestListCallsEndpointClampsLimit pins the limit rules the handler applies +// before touching the store: only 1..100 is honoured, everything else falls +// back to 50. The store records what it was asked for, so a dropped clamp is +// visible rather than merely "still 200". +func TestListCallsEndpointClampsLimit(t *testing.T) { + cases := []struct { + query string + wantLimit int + }{ + {query: "", wantLimit: 50}, + {query: "?limit=10", wantLimit: 10}, + {query: "?limit=100", wantLimit: 100}, + {query: "?limit=101", wantLimit: 50}, + {query: "?limit=0", wantLimit: 50}, + {query: "?limit=-5", wantLimit: 50}, + {query: "?limit=abc", wantLimit: 50}, + } + for _, tc := range cases { + t.Run("limit"+tc.query, func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{}) + status, raw := do(t, f, http.MethodGet, "/api/v1/utility/agents/custom-1/calls"+tc.query, "") + if status != http.StatusOK { + t.Fatalf("status = %d, body = %s", status, raw) + } + if got := f.repo.listCallsLimit(); got != tc.wantLimit { + t.Fatalf("store limit = %d, want %d", got, tc.wantLimit) + } + }) + } + + t.Run("returns the stored calls and 500s on a store failure", func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{}) + completed := fixedUtilityTime.Add(time.Minute) + if err := f.repo.CreateCall(t.Context(), &models.UtilityAgentCall{ + ID: "call-a", UtilityID: "custom-1", Status: "completed", Response: "done", + CreatedAt: fixedUtilityTime, CompletedAt: &completed, + }); err != nil { + t.Fatalf("seed call: %v", err) + } + status, raw := do(t, f, http.MethodGet, "/api/v1/utility/agents/custom-1/calls", "") + if status != http.StatusOK { + t.Fatalf("status = %d, body = %s", status, raw) + } + var got dto.UtilityAgentCallsResponse + decodeInto(t, raw, &got) + if len(got.Calls) != 1 || got.Calls[0].ID != "call-a" || got.Calls[0].Response != "done" { + t.Fatalf("calls = %#v", got.Calls) + } + if got.Calls[0].CompletedAt == nil || *got.Calls[0].CompletedAt != "2026-03-04T05:07:07Z" { + t.Fatalf("completed_at = %v", got.Calls[0].CompletedAt) + } + + f.repo.failWith("ListCalls", errors.New("database is locked")) + brokenStatus, brokenRaw := do(t, f, http.MethodGet, "/api/v1/utility/agents/custom-1/calls", "") + requireUtilityError(t, brokenStatus, brokenRaw, http.StatusInternalServerError, "failed to list calls") + }) +} + +// TestListUtilityAgentsAfterDeleteAndReseed guards the fixture itself: the +// in-memory store keeps a separate slice for list ordering, and a delete that +// forgot to drop the ordering entry would make a re-created agent with the same +// ID appear twice. Every list assertion in this file is written against that +// ordering, so the bug would surface as a confusing failure somewhere unrelated +// rather than here. +func TestListUtilityAgentsAfterDeleteAndReseed(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{}) + seedUtilityAgent(f, &models.UtilityAgent{ID: "custom-1", Name: "First", Prompt: "P"}) + seedUtilityAgent(f, &models.UtilityAgent{ID: "custom-2", Name: "Second", Prompt: "P"}) + + if status, raw := do(t, f, http.MethodDelete, "/api/v1/utility/agents/custom-1", ""); status != http.StatusOK { + t.Fatalf("delete = %d %s", status, raw) + } + seedUtilityAgent(f, &models.UtilityAgent{ID: "custom-1", Name: "Recreated", Prompt: "P"}) + + status, raw := do(t, f, http.MethodGet, "/api/v1/utility/agents", "") + if status != http.StatusOK { + t.Fatalf("status = %d, body = %s", status, raw) + } + var got dto.UtilityAgentsResponse + decodeInto(t, raw, &got) + + names := make([]string, 0, len(got.Agents)) + for _, a := range got.Agents { + names = append(names, a.Name) + } + // custom-1 was deleted, so it re-enters at the end of the ordering. + if !reflect.DeepEqual(names, []string{"Second", "Recreated"}) { + t.Fatalf("agents = %v, want [Second Recreated]", names) + } +} diff --git a/apps/backend/internal/utility/handlers/execute_handlers_test.go b/apps/backend/internal/utility/handlers/execute_handlers_test.go new file mode 100644 index 0000000000..eff0effa4b --- /dev/null +++ b/apps/backend/internal/utility/handlers/execute_handlers_test.go @@ -0,0 +1,376 @@ +package handlers + +import ( + "errors" + "net/http" + "reflect" + "testing" + + "github.com/kandev/kandev/internal/agent/hostutility" + "github.com/kandev/kandev/internal/agent/runtime/lifecycle" + agentsettingsmodels "github.com/kandev/kandev/internal/agent/settings/models" + agentctlutil "github.com/kandev/kandev/internal/agentctl/server/utility" + "github.com/kandev/kandev/internal/utility/dto" + "github.com/kandev/kandev/internal/utility/models" +) + +// executePrompt POSTs to /utility/execute and decodes the response. +func executePrompt(t *testing.T, f *utilityFixture, body string) (int, dto.ExecutePromptResponse) { + t.Helper() + status, raw := do(t, f, http.MethodPost, "/api/v1/utility/execute", body) + var got dto.ExecutePromptResponse + decodeInto(t, raw, &got) + return status, got +} + +// seedExecutableAgent adds a runnable custom utility agent whose prompt +// interpolates one template variable. +func seedExecutableAgent(f *utilityFixture) *models.UtilityAgent { + return seedUtilityAgent(f, &models.UtilityAgent{ + ID: "custom-1", Name: "Reviewer", Prompt: "Review this: {{GitDiff}}", + AgentID: "codex-acp", Model: "gpt-5", Enabled: true, + }) +} + +// TestExecutePromptSessionSuccess pins the full success contract of the +// session-bound path: the resolved prompt that reached the executor, the +// response body, and the completed call record. A test that only checked the +// 200 would pass with the response fields dropped. +func TestExecutePromptSessionSuccess(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{ + executor: &stubInferenceExecutor{resp: &agentctlutil.PromptResponse{ + Success: true, Response: "looks good", Model: "gpt-5", + PromptTokens: 12, ResponseTokens: 34, DurationMs: 56, + }}, + }) + seedExecutableAgent(f) + + status, got := executePrompt(t, f, + `{"utility_agent_id":"custom-1","session_id":"session-1","git_diff":"+one line"}`) + if status != http.StatusOK { + t.Fatalf("status = %d, body = %#v", status, got) + } + if got.CallID == "" { + t.Fatal("response carries no call id") + } + want := dto.ExecutePromptResponse{ + Success: true, CallID: got.CallID, Response: "looks good", Model: "gpt-5", + PromptTokens: 12, ResponseTokens: 34, DurationMs: 56, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("response = %#v, want %#v", got, want) + } + + if len(f.executor.calls) != 1 { + t.Fatalf("executor invocations = %#v, want 1", f.executor.calls) + } + call := f.executor.calls[0] + wantCall := inferenceCall{ + sessionID: "session-1", agentID: "codex-acp", model: "gpt-5", + prompt: "Review this: +one line", + } + if call != wantCall { + t.Fatalf("executor received %#v, want %#v", call, wantCall) + } + + record := f.repo.call(got.CallID) + if record == nil { + t.Fatal("no call record stored") + } + if record.Status != "completed" || record.Response != "looks good" || + record.PromptTokens != 12 || record.ResponseTokens != 34 || record.DurationMs != 56 { + t.Fatalf("call record = %#v", record) + } + if record.CompletedAt == nil { + t.Fatal("completed call record has no completion timestamp") + } +} + +// TestExecutePromptSessionFailures covers the two ways a session-bound run can +// fail. They are deliberately different statuses: a transport error is a 500, +// while an agent that ran and reported failure is a 200 carrying the reason — +// and both must leave the call record marked failed rather than pending. +func TestExecutePromptSessionFailures(t *testing.T) { + t.Run("executor error is 500 and fails the call", func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{ + executor: &stubInferenceExecutor{err: errors.New("agentctl unreachable")}, + }) + seedExecutableAgent(f) + + status, got := executePrompt(t, f, `{"utility_agent_id":"custom-1","session_id":"session-1"}`) + if status != http.StatusInternalServerError { + t.Fatalf("status = %d, body = %#v", status, got) + } + if got.Success || got.Error != "failed to execute prompt: agentctl unreachable" { + t.Fatalf("response = %#v", got) + } + record := f.repo.call(got.CallID) + if record == nil || record.Status != "failed" || record.ErrorMessage != "agentctl unreachable" { + t.Fatalf("call record = %#v", record) + } + }) + + t.Run("agent-reported failure is 200 carrying the reason", func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{ + executor: &stubInferenceExecutor{resp: &agentctlutil.PromptResponse{ + Success: false, Error: "model refused", DurationMs: 7, + }}, + }) + seedExecutableAgent(f) + + status, got := executePrompt(t, f, `{"utility_agent_id":"custom-1","session_id":"session-1"}`) + if status != http.StatusOK { + t.Fatalf("status = %d, body = %#v", status, got) + } + want := dto.ExecutePromptResponse{CallID: got.CallID, Error: "model refused", DurationMs: 7} + if !reflect.DeepEqual(got, want) { + t.Fatalf("response = %#v, want %#v", got, want) + } + record := f.repo.call(got.CallID) + if record == nil || record.Status != "failed" || record.DurationMs != 7 { + t.Fatalf("call record = %#v", record) + } + }) +} + +// TestExecutePromptRejections covers the rejections that happen before any +// execution, and asserts no call record is written for them — a pending row +// with no run behind it shows up in the call history as a stuck invocation. +func TestExecutePromptRejections(t *testing.T) { + t.Run("malformed payload", func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{}) + status, got := executePrompt(t, f, "{") + if status != http.StatusBadRequest || got.Error != "invalid payload" { + t.Fatalf("status = %d, body = %#v", status, got) + } + if f.repo.callCount() != 0 { + t.Fatalf("rejected request wrote %d call records", f.repo.callCount()) + } + }) + + t.Run("missing utility_agent_id", func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{}) + status, got := executePrompt(t, f, `{"session_id":"session-1"}`) + if status != http.StatusBadRequest || got.Error != "invalid payload" { + t.Fatalf("status = %d, body = %#v", status, got) + } + }) + + t.Run("unknown utility agent is 404", func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{}) + status, got := executePrompt(t, f, `{"utility_agent_id":"nope","session_id":"session-1"}`) + if status != http.StatusNotFound || got.Error != "failed to prepare prompt" { + t.Fatalf("status = %d, body = %#v", status, got) + } + if f.repo.callCount() != 0 { + t.Fatalf("404 request wrote %d call records", f.repo.callCount()) + } + }) + + t.Run("unresolvable inference agent is 400 before any call record", func(t *testing.T) { + // No agent_id on the row and no user default to fall back on, so the + // request cannot name an agent to run. + f := newUtilityFixture(t, utilityFixtureOptions{noSettings: true}) + seedUtilityAgent(f, &models.UtilityAgent{ID: "custom-1", Name: "Reviewer", Prompt: "Review"}) + + status, got := executePrompt(t, f, `{"utility_agent_id":"custom-1","session_id":"session-1"}`) + if status != http.StatusBadRequest { + t.Fatalf("status = %d, body = %#v", status, got) + } + if got.Error != lifecycle.ErrInferenceAgentIDRequired.Error() { + t.Fatalf("error = %q, want %q", got.Error, lifecycle.ErrInferenceAgentIDRequired.Error()) + } + if got.CallID != "" || f.repo.callCount() != 0 { + t.Fatalf("missing-agent rejection wrote call %q (%d records)", got.CallID, f.repo.callCount()) + } + if len(f.executor.calls) != 0 { + t.Fatalf("missing-agent rejection still executed %#v", f.executor.calls) + } + }) + + t.Run("call-record write failure is 500 and never executes", func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{}) + seedExecutableAgent(f) + f.repo.failWith("CreateCall", errors.New("database is locked")) + + status, got := executePrompt(t, f, `{"utility_agent_id":"custom-1","session_id":"session-1"}`) + if status != http.StatusInternalServerError || got.Error != "failed to create call record" { + t.Fatalf("status = %d, body = %#v", status, got) + } + if len(f.executor.calls) != 0 { + t.Fatalf("execution ran despite the failed call record: %#v", f.executor.calls) + } + }) +} + +// TestExecutePromptUsesUserDefaults pins that the user's default agent/model +// pair is applied as a unit when the utility agent names neither: sending a +// default model from one provider to another provider's CLI is exactly the +// mix-up the pairing rule exists to prevent. +func TestExecutePromptUsesUserDefaults(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{ + settings: &stubUserSettings{agentID: "claude-acp", model: "sonnet"}, + }) + seedUtilityAgent(f, &models.UtilityAgent{ + ID: "builtin-1", Name: "Commit", Prompt: "Summarize", Builtin: true, Enabled: true, + ProfileBindingState: models.ProfileBindingInherit, + }) + + status, got := executePrompt(t, f, `{"utility_agent_id":"builtin-1","session_id":"session-1"}`) + if status != http.StatusOK { + t.Fatalf("status = %d, body = %#v", status, got) + } + if len(f.executor.calls) != 1 { + t.Fatalf("executor invocations = %#v", f.executor.calls) + } + if f.executor.calls[0].agentID != "claude-acp" || f.executor.calls[0].model != "sonnet" { + t.Fatalf("executor received %#v, want the default agent/model pair", f.executor.calls[0]) + } + if record := f.repo.call(got.CallID); record == nil || record.Model != "sonnet" { + t.Fatalf("call record = %#v, want the default model persisted", record) + } +} + +// TestExecutePromptSessionless covers the no-session path used by flows like +// "enhance prompt" in the new-task modal: it runs through the host utility, and +// an unconfigured host is a 503 rather than a generic failure. +func TestExecutePromptSessionless(t *testing.T) { + t.Run("runs through the host utility and completes the call", func(t *testing.T) { + host := newStatefulHostStub() + host.promptResult = &hostutility.PromptResult{ + Response: "enhanced", Model: "gpt-5", PromptTokens: 3, ResponseTokens: 4, DurationMs: 5, + } + f := newUtilityFixture(t, utilityFixtureOptions{host: host}) + seedExecutableAgent(f) + + status, got := executePrompt(t, f, `{"utility_agent_id":"custom-1","git_diff":"+one line"}`) + if status != http.StatusOK { + t.Fatalf("status = %d, body = %#v", status, got) + } + want := dto.ExecutePromptResponse{ + Success: true, CallID: got.CallID, Response: "enhanced", Model: "gpt-5", + PromptTokens: 3, ResponseTokens: 4, DurationMs: 5, + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("response = %#v, want %#v", got, want) + } + if len(host.prompts) != 1 { + t.Fatalf("host invocations = %#v, want 1", host.prompts) + } + wantPrompt := hostPrompt{agentType: "codex-acp", model: "gpt-5", prompt: "Review this: +one line"} + if host.prompts[0] != wantPrompt { + t.Fatalf("host received %#v, want %#v", host.prompts[0], wantPrompt) + } + if len(f.executor.calls) != 0 { + t.Fatalf("sessionless run also hit the session executor: %#v", f.executor.calls) + } + if record := f.repo.call(got.CallID); record == nil || record.Status != "completed" { + t.Fatalf("call record = %#v", record) + } + }) + + t.Run("host failure is 500 and fails the call", func(t *testing.T) { + host := newStatefulHostStub() + host.promptErr = errors.New("host agent not installed") + f := newUtilityFixture(t, utilityFixtureOptions{host: host}) + seedExecutableAgent(f) + + status, got := executePrompt(t, f, `{"utility_agent_id":"custom-1"}`) + if status != http.StatusInternalServerError { + t.Fatalf("status = %d, body = %#v", status, got) + } + if got.Error != "failed to execute prompt: host agent not installed" { + t.Fatalf("error = %q", got.Error) + } + if record := f.repo.call(got.CallID); record == nil || record.Status != "failed" { + t.Fatalf("call record = %#v", record) + } + }) + + t.Run("no host utility is 503 telling the client to supply a session", func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{nilHost: true}) + seedExecutableAgent(f) + + status, got := executePrompt(t, f, `{"utility_agent_id":"custom-1"}`) + if status != http.StatusServiceUnavailable { + t.Fatalf("status = %d, body = %#v", status, got) + } + if got.Error != "host utility not configured; session_id is required" { + t.Fatalf("error = %q", got.Error) + } + record := f.repo.call(got.CallID) + if record == nil || record.Status != "failed" || record.ErrorMessage != "host utility not configured" { + t.Fatalf("call record = %#v", record) + } + }) +} + +// TestExecutePromptProfileBound covers the profile-resolution path. Neither +// stub executor implements the profile-aware interface, so both transports +// must report the capability as unavailable (503) instead of silently +// executing with the legacy agent/model pair — which would run the prompt +// against a provider the profile did not select. +func TestExecutePromptProfileBound(t *testing.T) { + resolver := stubProfileResolver{profile: &agentsettingsmodels.AgentProfile{ + ID: "profile-1", AgentID: "claude-acp", Model: "sonnet", + }} + + t.Run("session path without a profile-aware executor is 503", func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{resolver: resolver}) + seedUtilityAgent(f, &models.UtilityAgent{ + ID: "custom-1", Name: "Reviewer", Prompt: "Review", Enabled: true, + AgentProfileID: "profile-1", ProfileBindingState: models.ProfileBindingExplicit, + }) + + status, got := executePrompt(t, f, `{"utility_agent_id":"custom-1","session_id":"session-1"}`) + if status != http.StatusServiceUnavailable { + t.Fatalf("status = %d, body = %#v", status, got) + } + if got.Error != "profile-aware inference executor is unavailable" { + t.Fatalf("error = %q", got.Error) + } + if len(f.executor.calls) != 0 { + t.Fatalf("fell back to the legacy executor: %#v", f.executor.calls) + } + if record := f.repo.call(got.CallID); record == nil || record.Status != "failed" { + t.Fatalf("call record = %#v", record) + } + }) + + t.Run("sessionless path without a profile-aware host is 503", func(t *testing.T) { + host := newStatefulHostStub() + f := newUtilityFixture(t, utilityFixtureOptions{resolver: resolver, host: host}) + seedUtilityAgent(f, &models.UtilityAgent{ + ID: "custom-1", Name: "Reviewer", Prompt: "Review", Enabled: true, + AgentProfileID: "profile-1", ProfileBindingState: models.ProfileBindingExplicit, + }) + + status, got := executePrompt(t, f, `{"utility_agent_id":"custom-1"}`) + if status != http.StatusServiceUnavailable { + t.Fatalf("status = %d, body = %#v", status, got) + } + if got.Error != "profile-aware host utility executor is unavailable" { + t.Fatalf("error = %q", got.Error) + } + if len(host.prompts) != 0 { + t.Fatalf("fell back to the legacy host prompt: %#v", host.prompts) + } + }) + + t.Run("an unconfigured binding never reaches an executor", func(t *testing.T) { + f := newUtilityFixture(t, utilityFixtureOptions{resolver: resolver}) + seedUtilityAgent(f, &models.UtilityAgent{ + ID: "custom-1", Name: "Reviewer", Prompt: "Review", Enabled: true, + ProfileBindingState: models.ProfileBindingUnconfigured, + }) + + status, got := executePrompt(t, f, `{"utility_agent_id":"custom-1","session_id":"session-1"}`) + if status != http.StatusInternalServerError || got.Error != "failed to prepare prompt" { + t.Fatalf("status = %d, body = %#v", status, got) + } + if f.repo.callCount() != 0 || len(f.executor.calls) != 0 { + t.Fatalf("unconfigured binding wrote %d calls and executed %#v", + f.repo.callCount(), f.executor.calls) + } + }) +} diff --git a/apps/backend/internal/utility/handlers/fixture_test.go b/apps/backend/internal/utility/handlers/fixture_test.go new file mode 100644 index 0000000000..02872256b6 --- /dev/null +++ b/apps/backend/internal/utility/handlers/fixture_test.go @@ -0,0 +1,346 @@ +package handlers + +import ( + "context" + "database/sql" + "fmt" + "net/http/httptest" + "sort" + "sync" + "testing" + "time" + + "github.com/gin-gonic/gin" + + "github.com/kandev/kandev/internal/agent/runtime/lifecycle" + agentsettingsmodels "github.com/kandev/kandev/internal/agent/settings/models" + "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/utility/controller" + "github.com/kandev/kandev/internal/utility/models" + "github.com/kandev/kandev/internal/utility/service" +) + +// fakeUtilityRepo is an in-memory store.Repository. Missing rows are reported +// as sql.ErrNoRows because that is the shape the service maps to +// ErrAgentNotFound; anything else falls through as a 500. +type fakeUtilityRepo struct { + mu sync.Mutex + agents map[string]*models.UtilityAgent + agentOrder []string + calls map[string]*models.UtilityAgentCall + callOrder []string + + // lastListCallsLimit records the limit the handler resolved, so the + // clamping rules are observable from a test. + lastListCallsLimit int + errs map[string]error + seq int +} + +func newFakeUtilityRepo() *fakeUtilityRepo { + return &fakeUtilityRepo{ + agents: map[string]*models.UtilityAgent{}, + calls: map[string]*models.UtilityAgentCall{}, + errs: map[string]error{}, + } +} + +// failWith makes the named repository method return err. Guarded by the same +// mutex as every other field: the concurrent-refresh test drives 50 requests at +// once, so a future test that injects a failure mid-flight must not race. +func (r *fakeUtilityRepo) failWith(method string, err error) *fakeUtilityRepo { + r.mu.Lock() + defer r.mu.Unlock() + r.errs[method] = err + return r +} + +// fail returns the injected error for a method, if any. Callers must not hold +// r.mu. +func (r *fakeUtilityRepo) fail(method string) error { + r.mu.Lock() + defer r.mu.Unlock() + return r.errs[method] +} + +// putAgent seeds an agent row, preserving insertion order for ListAgents. +func (r *fakeUtilityRepo) putAgent(agent *models.UtilityAgent) *models.UtilityAgent { + r.mu.Lock() + defer r.mu.Unlock() + if _, exists := r.agents[agent.ID]; !exists { + r.agentOrder = append(r.agentOrder, agent.ID) + } + r.agents[agent.ID] = agent + return agent +} + +// call returns a stored call record. +func (r *fakeUtilityRepo) call(id string) *models.UtilityAgentCall { + r.mu.Lock() + defer r.mu.Unlock() + return r.calls[id] +} + +// listCallsLimit returns the limit the handler last resolved. +func (r *fakeUtilityRepo) listCallsLimit() int { + r.mu.Lock() + defer r.mu.Unlock() + return r.lastListCallsLimit +} + +// callCount returns how many call records were created. +func (r *fakeUtilityRepo) callCount() int { + r.mu.Lock() + defer r.mu.Unlock() + return len(r.calls) +} + +func (r *fakeUtilityRepo) ListAgents(context.Context) ([]*models.UtilityAgent, error) { + if err := r.fail("ListAgents"); err != nil { + return nil, err + } + r.mu.Lock() + defer r.mu.Unlock() + out := make([]*models.UtilityAgent, 0, len(r.agentOrder)) + for _, id := range r.agentOrder { + if agent, ok := r.agents[id]; ok { + out = append(out, agent) + } + } + return out, nil +} + +func (r *fakeUtilityRepo) GetAgentByID(_ context.Context, id string) (*models.UtilityAgent, error) { + if err := r.fail("GetAgentByID"); err != nil { + return nil, err + } + r.mu.Lock() + defer r.mu.Unlock() + if agent, ok := r.agents[id]; ok { + return agent, nil + } + return nil, sql.ErrNoRows +} + +func (r *fakeUtilityRepo) GetAgentByName(_ context.Context, name string) (*models.UtilityAgent, error) { + r.mu.Lock() + defer r.mu.Unlock() + for _, agent := range r.agents { + if agent.Name == name { + return agent, nil + } + } + return nil, sql.ErrNoRows +} + +func (r *fakeUtilityRepo) CreateAgent(_ context.Context, agent *models.UtilityAgent) error { + if err := r.fail("CreateAgent"); err != nil { + return err + } + r.mu.Lock() + r.seq++ + if agent.ID == "" { + agent.ID = fmt.Sprintf("utility-%d", r.seq) + } + now := time.Now().UTC() + agent.CreatedAt, agent.UpdatedAt = now, now + r.mu.Unlock() + r.putAgent(agent) + return nil +} + +func (r *fakeUtilityRepo) UpdateAgent(_ context.Context, agent *models.UtilityAgent) error { + if err := r.fail("UpdateAgent"); err != nil { + return err + } + agent.UpdatedAt = time.Now().UTC() + r.putAgent(agent) + return nil +} + +func (r *fakeUtilityRepo) NormalizeEmptyBuiltinBinding(context.Context, string) (bool, error) { + return false, nil +} + +func (r *fakeUtilityRepo) DeleteAgent(_ context.Context, id string) error { + if err := r.fail("DeleteAgent"); err != nil { + return err + } + r.mu.Lock() + defer r.mu.Unlock() + if _, ok := r.agents[id]; !ok { + return sql.ErrNoRows + } + delete(r.agents, id) + // Drop the ordering entry too. putAgent only appends when the ID is absent + // from `agents`, so leaving a stale entry here would make a re-seeded ID + // appear twice in ListAgents. + for i, existing := range r.agentOrder { + if existing == id { + r.agentOrder = append(r.agentOrder[:i], r.agentOrder[i+1:]...) + break + } + } + return nil +} + +func (r *fakeUtilityRepo) ListCalls(_ context.Context, utilityID string, limit int) ([]*models.UtilityAgentCall, error) { + r.mu.Lock() + defer r.mu.Unlock() + r.lastListCallsLimit = limit + if err := r.errs["ListCalls"]; err != nil { + return nil, err + } + out := make([]*models.UtilityAgentCall, 0, len(r.callOrder)) + for _, id := range r.callOrder { + if c, ok := r.calls[id]; ok && c.UtilityID == utilityID { + out = append(out, c) + } + } + sort.SliceStable(out, func(i, j int) bool { return out[i].ID < out[j].ID }) + if limit > 0 && len(out) > limit { + out = out[:limit] + } + return out, nil +} + +func (r *fakeUtilityRepo) GetCallByID(_ context.Context, id string) (*models.UtilityAgentCall, error) { + r.mu.Lock() + defer r.mu.Unlock() + if c, ok := r.calls[id]; ok { + return c, nil + } + return nil, sql.ErrNoRows +} + +func (r *fakeUtilityRepo) CreateCall(_ context.Context, call *models.UtilityAgentCall) error { + if err := r.fail("CreateCall"); err != nil { + return err + } + r.mu.Lock() + defer r.mu.Unlock() + r.seq++ + if call.ID == "" { + call.ID = fmt.Sprintf("call-%d", r.seq) + } + r.calls[call.ID] = call + r.callOrder = append(r.callOrder, call.ID) + return nil +} + +func (r *fakeUtilityRepo) UpdateCall(_ context.Context, call *models.UtilityAgentCall) error { + r.mu.Lock() + defer r.mu.Unlock() + r.calls[call.ID] = call + return nil +} + +// stubUserSettings supplies the user's default utility agent/model pair. +type stubUserSettings struct { + agentID string + model string + err error +} + +func (s *stubUserSettings) GetDefaultUtilitySettings(context.Context) (string, string, error) { + return s.agentID, s.model, s.err +} + +// stubProfileResolver resolves an agent profile for the profile-bound +// execution path. +type stubProfileResolver struct { + profile *agentsettingsmodels.AgentProfile + err error +} + +func (r stubProfileResolver) Resolve(context.Context, string) (*agentsettingsmodels.AgentProfile, error) { + return r.profile, r.err +} + +func (r stubProfileResolver) MatchLegacy( + context.Context, string, string, +) (*agentsettingsmodels.AgentProfile, error) { + return r.profile, r.err +} + +// utilityFixture is the full utility stack behind a live HTTP server: a fake +// store under the real service and controller, with every route from +// RegisterRoutes wired to stub executors. +type utilityFixture struct { + server *httptest.Server + repo *fakeUtilityRepo + service *service.Service + host *statefulHostStub + executor *stubInferenceExecutor + settings *stubUserSettings +} + +// utilityFixtureOptions tunes the pieces individual tests care about. The zero +// value gives a working stack with no agents registered and no host utility +// failures. +type utilityFixtureOptions struct { + agents []lifecycle.InferenceAgentInfo + host *statefulHostStub + // nilHost drops the host utility entirely, which is the "sessionless + // execution unavailable" configuration. + nilHost bool + settings *stubUserSettings + // noSettings drops the user-settings provider so defaults never apply. + noSettings bool + executor *stubInferenceExecutor + resolver service.ProfileResolver +} + +func newUtilityFixture(t *testing.T, opts utilityFixtureOptions) *utilityFixture { + t.Helper() + gin.SetMode(gin.TestMode) + log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"}) + if err != nil { + t.Fatalf("NewLogger: %v", err) + } + + repo := newFakeUtilityRepo() + svc := service.NewService(repo) + if opts.resolver != nil { + svc.SetProfileResolver(opts.resolver) + } + + host := opts.host + if host == nil && !opts.nilHost { + host = newStatefulHostStub() + } + executor := opts.executor + if executor == nil { + executor = &stubInferenceExecutor{} + } + executor.agents = opts.agents + settings := opts.settings + if settings == nil && !opts.noSettings { + settings = &stubUserSettings{} + } + + router := gin.New() + // Register through the production entry point so the route table under + // test is the one the app serves. + var hostExecutor HostUtilityExecutor + if host != nil { + hostExecutor = host + } + var userSettings UserSettingsProvider + if settings != nil { + userSettings = settings + } + RegisterRoutes(router, controller.NewController(svc), executor, hostExecutor, userSettings, log) + + server := httptest.NewServer(router) + t.Cleanup(server.Close) + + return &utilityFixture{ + server: server, + repo: repo, + service: svc, + host: host, + executor: executor, + settings: settings, + } +} diff --git a/apps/backend/internal/utility/handlers/handlers_integration_test.go b/apps/backend/internal/utility/handlers/handlers_integration_test.go index 26432a2aa7..e742d3104f 100644 --- a/apps/backend/internal/utility/handlers/handlers_integration_test.go +++ b/apps/backend/internal/utility/handlers/handlers_integration_test.go @@ -11,11 +11,8 @@ import ( "sync" "testing" - "github.com/gin-gonic/gin" - "github.com/kandev/kandev/internal/agent/hostutility" "github.com/kandev/kandev/internal/agent/runtime/lifecycle" - "github.com/kandev/kandev/internal/common/logger" ) // statefulHostStub is a goroutine-safe stub that models the real probe @@ -28,6 +25,22 @@ type statefulHostStub struct { caps map[string]hostutility.AgentCapabilities nextRefresh map[string]hostutility.AgentCapabilities refreshCalls int + + // promptResult/promptErr drive the sessionless execution path; when both + // are unset the stub reports a trivially successful run. + promptResult *hostutility.PromptResult + promptErr error + // prompts records every (agentType, model, mode, prompt) tuple forwarded + // to the host utility, so a test can assert what was actually executed. + prompts []hostPrompt +} + +// hostPrompt is one recorded ExecutePrompt invocation. +type hostPrompt struct { + agentType string + model string + mode string + prompt string } func newStatefulHostStub() *statefulHostStub { @@ -37,8 +50,20 @@ func newStatefulHostStub() *statefulHostStub { } } -func (h *statefulHostStub) ExecutePrompt(_ context.Context, _, _, _, _ string) (*hostutility.PromptResult, error) { - return nil, nil +func (h *statefulHostStub) ExecutePrompt( + _ context.Context, agentType, model, mode, prompt string, +) (*hostutility.PromptResult, error) { + h.mu.Lock() + h.prompts = append(h.prompts, hostPrompt{agentType: agentType, model: model, mode: mode, prompt: prompt}) + result, err := h.promptResult, h.promptErr + h.mu.Unlock() + if err != nil { + return nil, err + } + if result != nil { + return result, nil + } + return &hostutility.PromptResult{}, nil } func (h *statefulHostStub) Get(agentType string) (hostutility.AgentCapabilities, bool) { @@ -60,24 +85,12 @@ func (h *statefulHostStub) Refresh(_ context.Context, agentType string) (hostuti return next, nil } +// newIntegrationServer returns a live server with every utility route wired to +// a real controller over the in-memory fake store (see newUtilityFixture), so +// the inference-agents tests below and the CRUD/execute tests share one stack. func newIntegrationServer(t *testing.T, agents []lifecycle.InferenceAgentInfo, host *statefulHostStub) *httptest.Server { t.Helper() - gin.SetMode(gin.TestMode) - r := gin.New() - log, _ := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"}) - - // Register only the two routes under test directly. RegisterRoutes - // requires a real Controller (full service stack); for integration - // against the inference-agents surface we only need these two. - h := &Handlers{ - executor: &stubInferenceExecutor{agents: agents}, - hostExecutor: host, - logger: log, - } - r.GET("/api/v1/utility/inference-agents", h.httpListInferenceAgents) - r.POST("/api/v1/utility/inference-agents/:id/refresh", h.httpRefreshInferenceAgent) - - return httptest.NewServer(r) + return newUtilityFixture(t, utilityFixtureOptions{agents: agents, host: host}).server } func getJSON(t *testing.T, url string) (int, http.Header, map[string]any) { diff --git a/apps/backend/internal/utility/handlers/handlers_test.go b/apps/backend/internal/utility/handlers/handlers_test.go index 28cb6e8d24..5fc9ee10cd 100644 --- a/apps/backend/internal/utility/handlers/handlers_test.go +++ b/apps/backend/internal/utility/handlers/handlers_test.go @@ -20,10 +20,35 @@ import ( type stubInferenceExecutor struct { agents []lifecycle.InferenceAgentInfo + // resp/err drive the session-bound execution path; when both are unset the + // stub reports a trivially successful run so a caller that only cares + // about routing does not have to configure one. + resp *agentctlutil.PromptResponse + err error + // calls records every (sessionID, agentID, model, prompt) tuple the + // handler forwarded, so a test can assert what was actually executed. + calls []inferenceCall } -func (s *stubInferenceExecutor) ExecuteInferencePrompt(_ context.Context, _, _, _, _ string) (*agentctlutil.PromptResponse, error) { - return nil, nil +// inferenceCall is one recorded ExecuteInferencePrompt invocation. +type inferenceCall struct { + sessionID string + agentID string + model string + prompt string +} + +func (s *stubInferenceExecutor) ExecuteInferencePrompt( + _ context.Context, sessionID, agentID, model, prompt string, +) (*agentctlutil.PromptResponse, error) { + s.calls = append(s.calls, inferenceCall{sessionID: sessionID, agentID: agentID, model: model, prompt: prompt}) + if s.err != nil { + return nil, s.err + } + if s.resp != nil { + return s.resp, nil + } + return &agentctlutil.PromptResponse{Success: true}, nil } func (s *stubInferenceExecutor) ListInferenceAgentsWithContext(_ context.Context) []lifecycle.InferenceAgentInfo { diff --git a/apps/backend/internal/workflow/handlers/http_handlers_test.go b/apps/backend/internal/workflow/handlers/http_handlers_test.go new file mode 100644 index 0000000000..ba3331ff56 --- /dev/null +++ b/apps/backend/internal/workflow/handlers/http_handlers_test.go @@ -0,0 +1,615 @@ +package handlers + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "gopkg.in/yaml.v3" + + taskmodels "github.com/kandev/kandev/internal/task/models" + "github.com/kandev/kandev/internal/task/repository/repoerrors" + "github.com/kandev/kandev/internal/workflow/controller" + "github.com/kandev/kandev/internal/workflow/models" +) + +// fakeWorkflowProvider is the task-domain seam the workflow service reads +// workflows through. It is an ordered in-memory map so export ordering and +// import dedup-by-name are both observable. +type fakeWorkflowProvider struct { + workflows []*taskmodels.Workflow + listErr error + created []string + updated []string +} + +func (p *fakeWorkflowProvider) ListWorkflows( + _ context.Context, workspaceID string, includeHidden bool, +) ([]*taskmodels.Workflow, error) { + if p.listErr != nil { + return nil, p.listErr + } + out := make([]*taskmodels.Workflow, 0, len(p.workflows)) + for _, wf := range p.workflows { + if wf.WorkspaceID != workspaceID { + continue + } + if wf.Hidden && !includeHidden { + continue + } + out = append(out, wf) + } + return out, nil +} + +// GetWorkflow mirrors the production provider's error shape deliberately: the +// task repository reports a missing workflow as a formatted +// `workflow not found: ` error, not a sentinel (see +// internal/task/repository/sqlite/workflow.go). Nothing between there and the +// handler classifies it — the workflow service wraps it as +// `failed to get workflow: %w` and httpExportWorkflow answers 500 for any +// error — so returning a sentinel here would make the fake diverge from the +// only behaviour production can produce. +func (p *fakeWorkflowProvider) GetWorkflow(_ context.Context, id string) (*taskmodels.Workflow, error) { + for _, wf := range p.workflows { + if wf.ID == id { + return wf, nil + } + } + return nil, fmt.Errorf("workflow not found: %s", id) +} + +func (p *fakeWorkflowProvider) CreateWorkflow( + _ context.Context, workspaceID, name, description string, +) (*taskmodels.Workflow, error) { + wf := &taskmodels.Workflow{ + ID: "created-" + name, + WorkspaceID: workspaceID, + Name: name, + Description: description, + } + p.workflows = append(p.workflows, wf) + p.created = append(p.created, name) + return wf, nil +} + +func (p *fakeWorkflowProvider) UpdateWorkflow(_ context.Context, workflow *taskmodels.Workflow) error { + p.updated = append(p.updated, workflow.ID) + return nil +} + +// fakeWorkspaceProvider resolves workspaces for the read-only guard. +type fakeWorkspaceProvider struct { + workspaces map[string]*taskmodels.Workspace +} + +func (p *fakeWorkspaceProvider) GetWorkspace(_ context.Context, id string) (*taskmodels.Workspace, error) { + if ws, ok := p.workspaces[id]; ok { + return ws, nil + } + return nil, errors.New("workspace not found") +} + +// doRaw issues a request with a raw (possibly non-JSON) body. +func doRaw(t *testing.T, h *workflowHarness, method, path, body string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(method, path, strings.NewReader(body)) + rec := httptest.NewRecorder() + h.router.ServeHTTP(rec, req) + return rec +} + +// requireJSONError asserts the response is exactly {"error": }. +func requireJSONError(t *testing.T, rec *httptest.ResponseRecorder, wantStatus int, wantError string) { + t.Helper() + if rec.Code != wantStatus { + t.Fatalf("status = %d, want %d; body = %s", rec.Code, wantStatus, rec.Body.String()) + } + var body map[string]string + if err := json.Unmarshal(rec.Body.Bytes(), &body); err != nil { + t.Fatalf("decode body %s: %v", rec.Body.String(), err) + } + if body["error"] != wantError { + t.Fatalf("error = %q, want %q", body["error"], wantError) + } +} + +// TestListStepsEndpoints pins the two list surfaces. The workspace variant +// resolves through a join, so a step created under a workflow in another +// workspace must not leak into it. +func TestListStepsEndpoints(t *testing.T) { + h := setupStepRouter(t) + if _, err := h.db.Exec( + `INSERT INTO workflows (id, workspace_id, name, created_at, updated_at) + VALUES ('workflow-1','ws-1','Main',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP), + ('workflow-2','ws-2','Other',CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)`); err != nil { + t.Fatalf("seed workflows: %v", err) + } + mine := createStepViaHTTP(t, h.router, map[string]interface{}{ + "workflow_id": "workflow-1", "name": "Backlog", "position": 0, + }) + createStepViaHTTP(t, h.router, map[string]interface{}{ + "workflow_id": "workflow-2", "name": "Elsewhere", "position": 0, + }) + + t.Run("by workflow", func(t *testing.T) { + rec := doJSON(t, h.router, http.MethodGet, "/api/v1/workflows/workflow-1/workflow/steps", nil) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String()) + } + var got controller.ListStepsResponse + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v", err) + } + if len(got.Steps) != 1 || got.Steps[0].ID != mine.ID || got.Steps[0].Name != "Backlog" { + t.Fatalf("steps = %#v, want only the workflow-1 step", got.Steps) + } + }) + + t.Run("by workspace", func(t *testing.T) { + rec := doJSON(t, h.router, http.MethodGet, "/api/v1/workspaces/ws-1/workflow-steps", nil) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String()) + } + var got controller.ListStepsResponse + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v", err) + } + if len(got.Steps) != 1 || got.Steps[0].ID != mine.ID { + t.Fatalf("steps = %#v, want only the ws-1 step", got.Steps) + } + }) + + t.Run("empty workspace returns an empty list, not an error", func(t *testing.T) { + rec := doJSON(t, h.router, http.MethodGet, "/api/v1/workspaces/ws-none/workflow-steps", nil) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String()) + } + }) +} + +// TestGetStepEndpoint pins the single-step body and the not-found mapping. +func TestGetStepEndpoint(t *testing.T) { + h := setupStepRouter(t) + step := createStepViaHTTP(t, h.router, map[string]interface{}{ + "workflow_id": "workflow-1", "name": "Backlog", "position": 0, "color": "#123456", + }) + + rec := doJSON(t, h.router, http.MethodGet, "/api/v1/workflow/steps/"+step.ID, nil) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String()) + } + var got controller.GetStepResponse + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v", err) + } + if got.Step == nil || got.Step.ID != step.ID || got.Step.Name != "Backlog" || got.Step.Color != "#123456" { + t.Fatalf("step = %#v", got.Step) + } + + missing := doJSON(t, h.router, http.MethodGet, "/api/v1/workflow/steps/nope", nil) + requireJSONError(t, missing, http.StatusNotFound, "Step not found") +} + +// TestStepMutationValidationRejections pins each rejection code, because the +// handler collapses several service errors into three distinct statuses and +// the kanban UI branches on them. +func TestStepMutationValidationRejections(t *testing.T) { + t.Run("create with malformed json", func(t *testing.T) { + h := setupStepRouter(t) + rec := recordStepEvents(t, h.eventBus) + resp := doRaw(t, h, http.MethodPost, "/api/v1/workflow/steps", "{") + if resp.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400; body = %s", resp.Code, resp.Body.String()) + } + if len(rec.events) != 0 { + t.Fatalf("rejected create published %v", rec.subjects()) + } + }) + + t.Run("create without workflow_id or name", func(t *testing.T) { + h := setupStepRouter(t) + rec := recordStepEvents(t, h.eventBus) + for _, body := range []map[string]interface{}{ + {"name": "Backlog"}, + {"workflow_id": "workflow-1"}, + } { + resp := doJSON(t, h.router, http.MethodPost, "/api/v1/workflow/steps", body) + requireJSONError(t, resp, http.StatusBadRequest, "workflow_id and name are required") + } + if len(rec.events) != 0 { + t.Fatalf("rejected create published %v", rec.subjects()) + } + }) + + t.Run("update with a self-referential pull source", func(t *testing.T) { + h := setupStepRouter(t) + step := createStepViaHTTP(t, h.router, map[string]interface{}{ + "workflow_id": "workflow-1", "name": "Backlog", "position": 0, + }) + rec := recordStepEvents(t, h.eventBus) + + resp := doJSON(t, h.router, http.MethodPut, "/api/v1/workflow/steps/"+step.ID, map[string]interface{}{ + "pull_from_step_id": step.ID, + }) + if resp.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400; body = %s", resp.Code, resp.Body.String()) + } + if len(rec.events) != 0 { + t.Fatalf("rejected update published %v", rec.subjects()) + } + }) + + t.Run("update of a missing step is 404", func(t *testing.T) { + h := setupStepRouter(t) + rec := recordStepEvents(t, h.eventBus) + resp := doJSON(t, h.router, http.MethodPut, "/api/v1/workflow/steps/nope", map[string]interface{}{ + "name": "Ghost", + }) + requireJSONError(t, resp, http.StatusNotFound, "Step not found") + if len(rec.events) != 0 { + t.Fatalf("404 update published %v", rec.subjects()) + } + }) + + t.Run("delete of a missing step is 404 and publishes nothing", func(t *testing.T) { + h := setupStepRouter(t) + rec := recordStepEvents(t, h.eventBus) + resp := doJSON(t, h.router, http.MethodDelete, "/api/v1/workflow/steps/nope", nil) + requireJSONError(t, resp, http.StatusNotFound, "Step not found") + if len(rec.events) != 0 { + t.Fatalf("404 delete published %v", rec.subjects()) + } + }) +} + +// TestStepMutationsBlockedOnReadOnlyWorkflows covers the two read-only causes +// with their own message: a GitHub-synced workflow and a workflow in the +// Improve Kandev workspace. Both are 409 and neither may publish an event or +// touch the database. +func TestStepMutationsBlockedOnReadOnlyWorkflows(t *testing.T) { + cases := []struct { + name string + workflow *taskmodels.Workflow + workspace *taskmodels.Workspace + wantError string + }{ + { + name: "github-synced workflow", + workflow: &taskmodels.Workflow{ID: "workflow-1", WorkspaceID: "ws-1", Source: taskmodels.WorkflowSourceGitHub}, + workspace: &taskmodels.Workspace{ID: "ws-1", Name: "Normal"}, + wantError: "workflow is managed by GitHub sync and is read-only; " + + "edit its definition in the synced repository", + }, + { + name: "improve kandev workspace", + workflow: &taskmodels.Workflow{ID: "workflow-1", WorkspaceID: "ws-1"}, + workspace: &taskmodels.Workspace{ID: "ws-1", Name: taskmodels.WorkspaceNameImproveKandev}, + wantError: "this workspace is managed by Improve Kandev and is read-only", + }, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + h := setupStepRouter(t) + // Create the step before the guard is wired, so the delete/update + // cases exercise a real row rather than a missing one. + step := createStepViaHTTP(t, h.router, map[string]interface{}{ + "workflow_id": "workflow-1", "name": "Backlog", "position": 0, + }) + h.service.SetWorkflowProvider(&fakeWorkflowProvider{workflows: []*taskmodels.Workflow{tc.workflow}}) + h.service.SetWorkspaceProvider(&fakeWorkspaceProvider{ + workspaces: map[string]*taskmodels.Workspace{tc.workspace.ID: tc.workspace}, + }) + rec := recordStepEvents(t, h.eventBus) + + create := doJSON(t, h.router, http.MethodPost, "/api/v1/workflow/steps", map[string]interface{}{ + "workflow_id": "workflow-1", "name": "Nope", "position": 1, + }) + requireJSONError(t, create, http.StatusConflict, tc.wantError) + + update := doJSON(t, h.router, http.MethodPut, "/api/v1/workflow/steps/"+step.ID, + map[string]interface{}{"name": "Nope"}) + requireJSONError(t, update, http.StatusConflict, tc.wantError) + + del := doJSON(t, h.router, http.MethodDelete, "/api/v1/workflow/steps/"+step.ID, nil) + requireJSONError(t, del, http.StatusConflict, tc.wantError) + + reorder := doJSON(t, h.router, http.MethodPut, + "/api/v1/workflows/workflow-1/workflow/steps/reorder", + map[string]interface{}{"step_ids": []string{step.ID}}) + requireJSONError(t, reorder, http.StatusConflict, tc.wantError) + + template := doJSON(t, h.router, http.MethodPost, "/api/v1/workflows/workflow-1/workflow/steps", + map[string]interface{}{"template_id": "whatever"}) + requireJSONError(t, template, http.StatusConflict, tc.wantError) + + if len(rec.events) != 0 { + t.Fatalf("read-only rejections published %v", rec.subjects()) + } + steps, err := h.repo.ListStepsByWorkflow(context.Background(), "workflow-1") + if err != nil { + t.Fatalf("list steps: %v", err) + } + if len(steps) != 1 || steps[0].Name != "Backlog" { + t.Fatalf("read-only rejections mutated the database: %#v", steps) + } + }) + } +} + +// TestReorderStepsEndpoint pins the persisted positions, not just the 200: +// the handler's own body is a bare success flag, so only the stored order can +// tell a working reorder from a no-op. +func TestReorderStepsEndpoint(t *testing.T) { + h := setupStepRouter(t) + first := createStepViaHTTP(t, h.router, map[string]interface{}{ + "workflow_id": "workflow-1", "name": "First", "position": 0, + }) + second := createStepViaHTTP(t, h.router, map[string]interface{}{ + "workflow_id": "workflow-1", "name": "Second", "position": 1, + }) + + rec := doJSON(t, h.router, http.MethodPut, "/api/v1/workflows/workflow-1/workflow/steps/reorder", + map[string]interface{}{"step_ids": []string{second.ID, first.ID}}) + if rec.Code != http.StatusOK || rec.Body.String() != `{"success":true}` { + t.Fatalf("reorder = %d %s", rec.Code, rec.Body.String()) + } + + steps, err := h.repo.ListStepsByWorkflow(context.Background(), "workflow-1") + if err != nil { + t.Fatalf("list steps: %v", err) + } + if len(steps) != 2 || steps[0].ID != second.ID || steps[1].ID != first.ID { + t.Fatalf("stored order = %#v, want the reversed order", steps) + } + + t.Run("malformed json is 400", func(t *testing.T) { + resp := doRaw(t, h, http.MethodPut, "/api/v1/workflows/workflow-1/workflow/steps/reorder", "{") + if resp.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400; body = %s", resp.Code, resp.Body.String()) + } + }) + + t.Run("an unknown step id in the list is 404 and leaves the order alone", func(t *testing.T) { + resp := doJSON(t, h.router, http.MethodPut, "/api/v1/workflows/workflow-1/workflow/steps/reorder", + map[string]interface{}{"step_ids": []string{"nope"}}) + requireJSONError(t, resp, http.StatusNotFound, "Step not found") + steps, err := h.repo.ListStepsByWorkflow(context.Background(), "workflow-1") + if err != nil { + t.Fatalf("list steps: %v", err) + } + if len(steps) != 2 || steps[0].ID != second.ID || steps[1].ID != first.ID { + t.Fatalf("failed reorder changed the order: %#v", steps) + } + }) +} + +// TestListHistoryEndpointSeparatesDeniedFromBroken guards the comment on +// httpListHistoryBySession: an unauthorized/missing session must read as 404 +// so session existence is not leaked, while a genuine read failure must stay a +// 500 rather than being masked as not-found. +func TestListHistoryEndpointSeparatesDeniedFromBroken(t *testing.T) { + t.Run("empty history for an unknown session", func(t *testing.T) { + h := setupStepRouter(t) + rec := doJSON(t, h.router, http.MethodGet, "/api/v1/sessions/session-1/workflow/history", nil) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String()) + } + var got controller.ListHistoryResponse + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v", err) + } + if len(got.History) != 0 { + t.Fatalf("history = %#v, want empty", got.History) + } + }) + + t.Run("denied session is 404", func(t *testing.T) { + for _, denial := range []error{taskmodels.ErrTaskSessionNotFound, repoerrors.ErrTaskNotFound} { + h := setupStepRouter(t) + h.service.SetSessionAccessChecker(func(context.Context, string) error { return denial }) + rec := doJSON(t, h.router, http.MethodGet, "/api/v1/sessions/session-1/workflow/history", nil) + requireJSONError(t, rec, http.StatusNotFound, "session not found") + } + }) + + t.Run("read failure stays a 500", func(t *testing.T) { + h := setupStepRouter(t) + h.service.SetSessionAccessChecker(func(context.Context, string) error { + return errors.New("database is locked") + }) + rec := doJSON(t, h.router, http.MethodGet, "/api/v1/sessions/session-1/workflow/history", nil) + requireJSONError(t, rec, http.StatusInternalServerError, "failed to list history") + }) +} + +// TestExportWorkflowEndpoints pins the YAML content type and the exported +// document, plus the `ids` filter semantics: absent means "everything +// non-hidden", present restricts to that set and may name a hidden workflow. +func TestExportWorkflowEndpoints(t *testing.T) { + newExportHarness := func(t *testing.T) *workflowHarness { + t.Helper() + h := setupStepRouter(t) + h.service.SetWorkflowProvider(&fakeWorkflowProvider{workflows: []*taskmodels.Workflow{ + {ID: "workflow-1", WorkspaceID: "ws-1", Name: "Main", Description: "Primary"}, + {ID: "workflow-2", WorkspaceID: "ws-1", Name: "Hidden", Hidden: true}, + }}) + createStepViaHTTP(t, h.router, map[string]interface{}{ + "workflow_id": "workflow-1", "name": "Backlog", "position": 0, "color": "#123456", + }) + return h + } + + decodeExport := func(t *testing.T, rec *httptest.ResponseRecorder) models.WorkflowExport { + t.Helper() + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String()) + } + if ct := rec.Header().Get("Content-Type"); ct != "application/x-yaml" { + t.Fatalf("Content-Type = %q, want application/x-yaml", ct) + } + var export models.WorkflowExport + if err := yaml.Unmarshal(rec.Body.Bytes(), &export); err != nil { + t.Fatalf("decode yaml %s: %v", rec.Body.String(), err) + } + return export + } + + t.Run("single workflow export carries its steps", func(t *testing.T) { + h := newExportHarness(t) + export := decodeExport(t, doJSON(t, h.router, http.MethodGet, "/api/v1/workflows/workflow-1/export", nil)) + if export.Version != models.ExportVersion || export.Type != models.ExportType { + t.Fatalf("export envelope = %d/%q", export.Version, export.Type) + } + if len(export.Workflows) != 1 || export.Workflows[0].Name != "Main" { + t.Fatalf("workflows = %#v", export.Workflows) + } + steps := export.Workflows[0].Steps + if len(steps) != 1 || steps[0].Name != "Backlog" || steps[0].Color != "#123456" { + t.Fatalf("steps = %#v", steps) + } + }) + + t.Run("workspace export without ids omits hidden workflows", func(t *testing.T) { + h := newExportHarness(t) + export := decodeExport(t, doJSON(t, h.router, http.MethodGet, "/api/v1/workspaces/ws-1/workflows/export", nil)) + if len(export.Workflows) != 1 || export.Workflows[0].Name != "Main" { + t.Fatalf("workflows = %#v, want only the visible one", export.Workflows) + } + }) + + t.Run("explicit ids restrict the export and may include a hidden workflow", func(t *testing.T) { + h := newExportHarness(t) + export := decodeExport(t, doJSON(t, h.router, + http.MethodGet, "/api/v1/workspaces/ws-1/workflows/export?ids=workflow-2", nil)) + if len(export.Workflows) != 1 || export.Workflows[0].Name != "Hidden" { + t.Fatalf("workflows = %#v, want only the named hidden one", export.Workflows) + } + }) + + t.Run("an ids list that matches nothing exports nothing", func(t *testing.T) { + h := newExportHarness(t) + export := decodeExport(t, doJSON(t, h.router, + http.MethodGet, "/api/v1/workspaces/ws-1/workflows/export?ids=%20,%20", nil)) + if len(export.Workflows) != 0 { + t.Fatalf("workflows = %#v, want none", export.Workflows) + } + }) + + t.Run("provider failure is 500", func(t *testing.T) { + h := setupStepRouter(t) + h.service.SetWorkflowProvider(&fakeWorkflowProvider{listErr: errors.New("database is locked")}) + rec := doJSON(t, h.router, http.MethodGet, "/api/v1/workspaces/ws-1/workflows/export", nil) + requireJSONError(t, rec, http.StatusInternalServerError, "Failed to export workflows") + }) +} + +// TestImportWorkflowsEndpoint covers a successful import (created workflow and +// its persisted steps), dedup-by-name, and the two rejection shapes: unparsable +// YAML and a structurally invalid document. +func TestImportWorkflowsEndpoint(t *testing.T) { + const validYAML = `version: 1 +type: kandev_workflow +workflows: + - name: Imported + description: From YAML + steps: + - name: Backlog + position: 0 + color: "#111111" + - name: Doing + position: 1 + color: "#222222" +` + + t.Run("creates the workflow and persists its steps", func(t *testing.T) { + h := setupStepRouter(t) + provider := &fakeWorkflowProvider{} + h.service.SetWorkflowProvider(provider) + + rec := doRaw(t, h, http.MethodPost, "/api/v1/workspaces/ws-1/workflows/import", validYAML) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String()) + } + var got struct { + Created []string `json:"created"` + Skipped []string `json:"skipped"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v", err) + } + if len(got.Created) != 1 || got.Created[0] != "Imported" || len(got.Skipped) != 0 { + t.Fatalf("result = %#v", got) + } + if len(provider.created) != 1 || provider.created[0] != "Imported" { + t.Fatalf("provider created = %v", provider.created) + } + steps, err := h.repo.ListStepsByWorkflow(context.Background(), "created-Imported") + if err != nil { + t.Fatalf("list steps: %v", err) + } + if len(steps) != 2 || steps[0].Name != "Backlog" || steps[1].Name != "Doing" { + t.Fatalf("persisted steps = %#v", steps) + } + }) + + t.Run("a workflow whose name already exists is skipped, not duplicated", func(t *testing.T) { + h := setupStepRouter(t) + provider := &fakeWorkflowProvider{workflows: []*taskmodels.Workflow{ + {ID: "existing", WorkspaceID: "ws-1", Name: "Imported"}, + }} + h.service.SetWorkflowProvider(provider) + + rec := doRaw(t, h, http.MethodPost, "/api/v1/workspaces/ws-1/workflows/import", validYAML) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, body = %s", rec.Code, rec.Body.String()) + } + var got struct { + Created []string `json:"created"` + Skipped []string `json:"skipped"` + } + if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil { + t.Fatalf("decode: %v", err) + } + if len(got.Created) != 0 || len(got.Skipped) != 1 || got.Skipped[0] != "Imported" { + t.Fatalf("result = %#v, want the name skipped", got) + } + if len(provider.created) != 0 { + t.Fatalf("skipped import still created %v", provider.created) + } + }) + + t.Run("unparsable yaml is 400", func(t *testing.T) { + h := setupStepRouter(t) + h.service.SetWorkflowProvider(&fakeWorkflowProvider{}) + rec := doRaw(t, h, http.MethodPost, "/api/v1/workspaces/ws-1/workflows/import", "version: [1") + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400; body = %s", rec.Code, rec.Body.String()) + } + if !strings.Contains(rec.Body.String(), "Invalid YAML") { + t.Fatalf("body = %s, want an Invalid YAML message", rec.Body.String()) + } + }) + + t.Run("structurally invalid export is 400 with the validation reason", func(t *testing.T) { + h := setupStepRouter(t) + provider := &fakeWorkflowProvider{} + h.service.SetWorkflowProvider(provider) + rec := doRaw(t, h, http.MethodPost, "/api/v1/workspaces/ws-1/workflows/import", + "version: 99\ntype: kandev_workflow\nworkflows: []\n") + if rec.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400; body = %s", rec.Code, rec.Body.String()) + } + if !strings.Contains(rec.Body.String(), "unsupported export version") { + t.Fatalf("body = %s, want the version reason", rec.Body.String()) + } + if len(provider.created) != 0 { + t.Fatalf("invalid import created %v", provider.created) + } + }) +} diff --git a/apps/backend/internal/workflow/handlers/step_events_test.go b/apps/backend/internal/workflow/handlers/step_events_test.go index 54d87852c7..13445e78e7 100644 --- a/apps/backend/internal/workflow/handlers/step_events_test.go +++ b/apps/backend/internal/workflow/handlers/step_events_test.go @@ -20,6 +20,7 @@ import ( "github.com/kandev/kandev/internal/workflow/models" "github.com/kandev/kandev/internal/workflow/repository" "github.com/kandev/kandev/internal/workflow/service" + ws "github.com/kandev/kandev/pkg/websocket" ) type stepEvent struct { @@ -81,7 +82,39 @@ func (r *stepEventRecorder) only(t *testing.T, subject string) stepEvent { return r.events[0] } -func setupStepRouter(t *testing.T) (*gin.Engine, *bus.MemoryEventBus, *repository.Repository) { +// workflowHarness is the shared fixture for this package's handler tests: a +// real repository/service/controller stack over an in-memory SQLite database, +// with both the HTTP routes and the WS actions registered against it. +type workflowHarness struct { + router *gin.Engine + dispatcher *ws.Dispatcher + eventBus *bus.MemoryEventBus + repo *repository.Repository + service *service.Service + // db is the same handle the repository writes through, so a test can seed + // the task-owned `workflows` table the workspace step join reads. + db *sqlx.DB +} + +// dispatch routes one WS message through the registered handlers. +func (h *workflowHarness) dispatch(t *testing.T, action string, payload any) *ws.Message { + t.Helper() + raw, err := json.Marshal(payload) + if err != nil { + t.Fatalf("marshal payload: %v", err) + } + msg := &ws.Message{ID: "req-1", Type: ws.MessageTypeRequest, Action: action, Payload: raw} + resp, err := h.dispatcher.Dispatch(context.Background(), msg) + if err != nil { + t.Fatalf("dispatch %s: %v", action, err) + } + if resp == nil { + t.Fatalf("dispatch %s returned no message", action) + } + return resp +} + +func setupStepRouter(t *testing.T) *workflowHarness { t.Helper() rawDB, err := sql.Open("sqlite3", ":memory:") if err != nil { @@ -111,12 +144,21 @@ func setupStepRouter(t *testing.T) (*gin.Engine, *bus.MemoryEventBus, *repositor eventBus := bus.NewMemoryEventBus(log) workflowSvc := service.NewService(repo, log) t.Cleanup(func() { _ = workflowSvc.Close() }) - h := NewHandlers(controller.NewController(workflowSvc), eventBus, log) gin.SetMode(gin.TestMode) router := gin.New() - h.registerHTTP(router) - return router, eventBus, repo + dispatcher := ws.NewDispatcher() + // Register through the production entry point so HTTP routes and WS + // actions are wired exactly as they are at startup. + RegisterRoutes(router, dispatcher, controller.NewController(workflowSvc), eventBus, log) + return &workflowHarness{ + router: router, + dispatcher: dispatcher, + eventBus: eventBus, + repo: repo, + service: workflowSvc, + db: db, + } } func doJSON(t *testing.T, router *gin.Engine, method, path string, body interface{}) *httptest.ResponseRecorder { @@ -150,10 +192,10 @@ func createStepViaHTTP(t *testing.T, router *gin.Engine, body map[string]interfa } func TestHTTPCreateStepPublishesCreatedEvent(t *testing.T) { - router, eventBus, _ := setupStepRouter(t) - rec := recordStepEvents(t, eventBus) + h := setupStepRouter(t) + rec := recordStepEvents(t, h.eventBus) - step := createStepViaHTTP(t, router, map[string]interface{}{ + step := createStepViaHTTP(t, h.router, map[string]interface{}{ "workflow_id": "workflow-1", "name": "Backlog", "position": 0, @@ -170,15 +212,15 @@ func TestHTTPCreateStepPublishesCreatedEvent(t *testing.T) { } func TestHTTPUpdateStepPublishesUpdatedEvent(t *testing.T) { - router, eventBus, _ := setupStepRouter(t) - step := createStepViaHTTP(t, router, map[string]interface{}{ + h := setupStepRouter(t) + step := createStepViaHTTP(t, h.router, map[string]interface{}{ "workflow_id": "workflow-1", "name": "Backlog", "position": 0, }) - rec := recordStepEvents(t, eventBus) + rec := recordStepEvents(t, h.eventBus) - resp := doJSON(t, router, http.MethodPut, "/api/v1/workflow/steps/"+step.ID, map[string]interface{}{ + resp := doJSON(t, h.router, http.MethodPut, "/api/v1/workflow/steps/"+step.ID, map[string]interface{}{ "name": "Triage", "stage_type": "review", "wip_limit": 3, @@ -200,15 +242,15 @@ func TestHTTPUpdateStepPublishesUpdatedEvent(t *testing.T) { } func TestHTTPDeleteStepPublishesDeletedEvent(t *testing.T) { - router, eventBus, _ := setupStepRouter(t) - step := createStepViaHTTP(t, router, map[string]interface{}{ + h := setupStepRouter(t) + step := createStepViaHTTP(t, h.router, map[string]interface{}{ "workflow_id": "workflow-1", "name": "Backlog", "position": 0, }) - rec := recordStepEvents(t, eventBus) + rec := recordStepEvents(t, h.eventBus) - resp := doJSON(t, router, http.MethodDelete, "/api/v1/workflow/steps/"+step.ID, nil) + resp := doJSON(t, h.router, http.MethodDelete, "/api/v1/workflow/steps/"+step.ID, nil) if resp.Code != http.StatusOK { t.Fatalf("delete status = %d, body = %s", resp.Code, resp.Body.String()) } @@ -220,16 +262,16 @@ func TestHTTPDeleteStepPublishesDeletedEvent(t *testing.T) { } func TestHTTPCreateStepPublishesDemotedStartSteps(t *testing.T) { - router, eventBus, _ := setupStepRouter(t) - oldStart := createStepViaHTTP(t, router, map[string]interface{}{ + h := setupStepRouter(t) + oldStart := createStepViaHTTP(t, h.router, map[string]interface{}{ "workflow_id": "workflow-1", "name": "Old Start", "position": 0, "is_start_step": true, }) - rec := recordStepEvents(t, eventBus) + rec := recordStepEvents(t, h.eventBus) - newStart := createStepViaHTTP(t, router, map[string]interface{}{ + newStart := createStepViaHTTP(t, h.router, map[string]interface{}{ "workflow_id": "workflow-1", "name": "New Start", "position": 1, @@ -254,21 +296,21 @@ func TestHTTPCreateStepPublishesDemotedStartSteps(t *testing.T) { } func TestHTTPUpdateStepPublishesDemotedStartSteps(t *testing.T) { - router, eventBus, _ := setupStepRouter(t) - oldStart := createStepViaHTTP(t, router, map[string]interface{}{ + h := setupStepRouter(t) + oldStart := createStepViaHTTP(t, h.router, map[string]interface{}{ "workflow_id": "workflow-1", "name": "Old Start", "position": 0, "is_start_step": true, }) - promoted := createStepViaHTTP(t, router, map[string]interface{}{ + promoted := createStepViaHTTP(t, h.router, map[string]interface{}{ "workflow_id": "workflow-1", "name": "Doing", "position": 1, }) - rec := recordStepEvents(t, eventBus) + rec := recordStepEvents(t, h.eventBus) - resp := doJSON(t, router, http.MethodPut, "/api/v1/workflow/steps/"+promoted.ID, map[string]interface{}{ + resp := doJSON(t, h.router, http.MethodPut, "/api/v1/workflow/steps/"+promoted.ID, map[string]interface{}{ "is_start_step": true, }) if resp.Code != http.StatusOK { @@ -290,15 +332,15 @@ func TestHTTPUpdateStepPublishesDemotedStartSteps(t *testing.T) { } func TestHTTPStepMutationFailurePublishesNothing(t *testing.T) { - router, eventBus, _ := setupStepRouter(t) - step := createStepViaHTTP(t, router, map[string]interface{}{ + h := setupStepRouter(t) + step := createStepViaHTTP(t, h.router, map[string]interface{}{ "workflow_id": "workflow-1", "name": "Backlog", "position": 0, }) - rec := recordStepEvents(t, eventBus) + rec := recordStepEvents(t, h.eventBus) - resp := doJSON(t, router, http.MethodPut, "/api/v1/workflow/steps/"+step.ID, map[string]interface{}{ + resp := doJSON(t, h.router, http.MethodPut, "/api/v1/workflow/steps/"+step.ID, map[string]interface{}{ "wip_limit": -1, }) if resp.Code != http.StatusBadRequest { diff --git a/apps/backend/internal/workflow/handlers/ws_handlers_test.go b/apps/backend/internal/workflow/handlers/ws_handlers_test.go new file mode 100644 index 0000000000..a159089f4f --- /dev/null +++ b/apps/backend/internal/workflow/handlers/ws_handlers_test.go @@ -0,0 +1,353 @@ +package handlers + +import ( + "encoding/json" + "net/http" + "strings" + "testing" + + "github.com/kandev/kandev/internal/events" + "github.com/kandev/kandev/internal/workflow/controller" + "github.com/kandev/kandev/internal/workflow/models" + ws "github.com/kandev/kandev/pkg/websocket" +) + +// requireWSError asserts the dispatched message came back as an error frame +// with the given code. The code is what the frontend branches on, so a +// validation failure reported as INTERNAL_ERROR is a real regression even +// though both are "not a response". +func requireWSError(t *testing.T, msg *ws.Message, wantCode string) ws.ErrorPayload { + t.Helper() + if msg.Type != ws.MessageTypeError { + t.Fatalf("message type = %q, want error; payload = %s", msg.Type, msg.Payload) + } + var payload ws.ErrorPayload + if err := json.Unmarshal(msg.Payload, &payload); err != nil { + t.Fatalf("decode error payload: %v", err) + } + if payload.Code != wantCode { + t.Fatalf("error code = %q, want %q (message %q)", payload.Code, wantCode, payload.Message) + } + return payload +} + +// requireWSResponse asserts a success frame and decodes its payload. +func requireWSResponse(t *testing.T, msg *ws.Message, into any) { + t.Helper() + if msg.Type != ws.MessageTypeResponse { + t.Fatalf("message type = %q, want response; payload = %s", msg.Type, msg.Payload) + } + if msg.ID != "req-1" { + t.Fatalf("correlation id = %q, want req-1", msg.ID) + } + if err := json.Unmarshal(msg.Payload, into); err != nil { + t.Fatalf("decode response payload: %v", err) + } +} + +// seedTemplate inserts a workflow template directly so the template routes have +// a known row to read, independent of whatever the repo seeds at boot. +func seedTemplate(t *testing.T, h *workflowHarness, id, name string) { + t.Helper() + // Distinct template step IDs matter: the apply path builds its + // template-ID -> new-UUID map keyed by them, so two steps sharing an ID + // would collapse into one row. + steps := `[{"id":"tpl-backlog","name":"Backlog","position":0,"color":"#111111"},` + + `{"id":"tpl-doing","name":"Doing","position":1,"color":"#222222"}]` + if _, err := h.db.Exec( + `INSERT INTO workflow_templates (id, name, description, is_system, steps, created_at, updated_at) + VALUES (?, ?, 'seeded', 0, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)`, id, name, steps); err != nil { + t.Fatalf("seed template: %v", err) + } +} + +// TestTemplateEndpoints covers both transports for the template pair: the +// listed template must include the seeded row, and an unknown ID is a 404 over +// HTTP and a NOT_FOUND frame over WS. +func TestTemplateEndpoints(t *testing.T) { + t.Run("http", func(t *testing.T) { + h := setupStepRouter(t) + seedTemplate(t, h, "template-1", "Seeded Flow") + + list := doJSON(t, h.router, http.MethodGet, "/api/v1/workflow/templates", nil) + if list.Code != http.StatusOK { + t.Fatalf("list status = %d, body = %s", list.Code, list.Body.String()) + } + var listed controller.ListTemplatesResponse + if err := json.Unmarshal(list.Body.Bytes(), &listed); err != nil { + t.Fatalf("decode list: %v", err) + } + if !containsTemplate(listed.Templates, "template-1") { + t.Fatalf("templates = %#v, want the seeded row", listed.Templates) + } + + get := doJSON(t, h.router, http.MethodGet, "/api/v1/workflow/templates/template-1", nil) + if get.Code != http.StatusOK { + t.Fatalf("get status = %d, body = %s", get.Code, get.Body.String()) + } + var single controller.GetTemplateResponse + if err := json.Unmarshal(get.Body.Bytes(), &single); err != nil { + t.Fatalf("decode get: %v", err) + } + if single.Template == nil || single.Template.Name != "Seeded Flow" || len(single.Template.Steps) != 2 { + t.Fatalf("template = %#v", single.Template) + } + + missing := doJSON(t, h.router, http.MethodGet, "/api/v1/workflow/templates/nope", nil) + requireJSONError(t, missing, http.StatusNotFound, "Template not found") + }) + + t.Run("ws", func(t *testing.T) { + h := setupStepRouter(t) + seedTemplate(t, h, "template-1", "Seeded Flow") + + var listed controller.ListTemplatesResponse + requireWSResponse(t, h.dispatch(t, ws.ActionWorkflowTemplateList, map[string]any{}), &listed) + if !containsTemplate(listed.Templates, "template-1") { + t.Fatalf("templates = %#v, want the seeded row", listed.Templates) + } + + var single controller.GetTemplateResponse + requireWSResponse(t, h.dispatch(t, ws.ActionWorkflowTemplateGet, map[string]any{"id": "template-1"}), &single) + if single.Template == nil || single.Template.Name != "Seeded Flow" { + t.Fatalf("template = %#v", single.Template) + } + + requireWSError(t, h.dispatch(t, ws.ActionWorkflowTemplateGet, map[string]any{"id": ""}), ws.ErrorCodeValidation) + requireWSError(t, h.dispatch(t, ws.ActionWorkflowTemplateGet, map[string]any{"id": "nope"}), ws.ErrorCodeNotFound) + requireWSError(t, h.dispatch(t, ws.ActionWorkflowTemplateGet, map[string]any{"id": 7}), ws.ErrorCodeBadRequest) + }) +} + +func containsTemplate(templates []*models.WorkflowTemplate, id string) bool { + for _, tpl := range templates { + if tpl != nil && tpl.ID == id { + return true + } + } + return false +} + +// TestWSStepReadActions covers the two step read actions on the WS transport, +// including the three-way split between a malformed payload (BAD_REQUEST), a +// missing required field (VALIDATION_ERROR) and a failed lookup. +func TestWSStepReadActions(t *testing.T) { + h := setupStepRouter(t) + step := createStepViaHTTP(t, h.router, map[string]interface{}{ + "workflow_id": "workflow-1", "name": "Backlog", "position": 0, + }) + + t.Run("list", func(t *testing.T) { + var listed controller.ListStepsResponse + requireWSResponse(t, + h.dispatch(t, ws.ActionWorkflowStepList, map[string]any{"workflow_id": "workflow-1"}), &listed) + if len(listed.Steps) != 1 || listed.Steps[0].ID != step.ID { + t.Fatalf("steps = %#v", listed.Steps) + } + + payload := requireWSError(t, + h.dispatch(t, ws.ActionWorkflowStepList, map[string]any{}), ws.ErrorCodeValidation) + if payload.Message != "workflow_id is required" { + t.Errorf("message = %q", payload.Message) + } + requireWSError(t, + h.dispatch(t, ws.ActionWorkflowStepList, map[string]any{"workflow_id": 7}), ws.ErrorCodeBadRequest) + }) + + t.Run("get", func(t *testing.T) { + var got controller.GetStepResponse + requireWSResponse(t, h.dispatch(t, ws.ActionWorkflowStepGet, map[string]any{"id": step.ID}), &got) + if got.Step == nil || got.Step.Name != "Backlog" { + t.Fatalf("step = %#v", got.Step) + } + requireWSError(t, h.dispatch(t, ws.ActionWorkflowStepGet, map[string]any{"id": ""}), ws.ErrorCodeValidation) + requireWSError(t, h.dispatch(t, ws.ActionWorkflowStepGet, map[string]any{"id": "nope"}), ws.ErrorCodeNotFound) + }) +} + +// TestWSListHistoryAction covers the history action's required-field guard and +// its success shape. +func TestWSListHistoryAction(t *testing.T) { + h := setupStepRouter(t) + + var got controller.ListHistoryResponse + requireWSResponse(t, + h.dispatch(t, ws.ActionWorkflowHistoryList, map[string]any{"session_id": "session-1"}), &got) + if len(got.History) != 0 { + t.Fatalf("history = %#v, want empty", got.History) + } + + payload := requireWSError(t, + h.dispatch(t, ws.ActionWorkflowHistoryList, map[string]any{}), ws.ErrorCodeValidation) + if payload.Message != "session_id is required" { + t.Errorf("message = %q", payload.Message) + } + requireWSError(t, + h.dispatch(t, ws.ActionWorkflowHistoryList, map[string]any{"session_id": 7}), ws.ErrorCodeBadRequest) +} + +// TestCreateStepsFromTemplate covers both transports of the template-apply +// mutation: the steps it writes, and each rejection. +// +// The apply path deliberately does NOT publish workflow_step.created for the +// steps it writes — the kanban board reloads its columns off the template +// response instead. Asserting the absence here means a later publish added to +// this path has to be a deliberate change rather than a silent one. +func TestCreateStepsFromTemplate(t *testing.T) { + t.Run("http applies the template steps", func(t *testing.T) { + h := setupStepRouter(t) + seedTemplate(t, h, "template-1", "Seeded Flow") + rec := recordStepEvents(t, h.eventBus) + + resp := doJSON(t, h.router, http.MethodPost, "/api/v1/workflows/workflow-1/workflow/steps", + map[string]interface{}{"template_id": "template-1"}) + if resp.Code != http.StatusCreated || resp.Body.String() != `{"success":true}` { + t.Fatalf("apply = %d %s", resp.Code, resp.Body.String()) + } + steps := listStepNames(t, h, "workflow-1") + if len(steps) != 2 || steps[0] != "Backlog" || steps[1] != "Doing" { + t.Fatalf("persisted steps = %v, want the template's two steps", steps) + } + if len(rec.events) != 0 { + t.Fatalf("template apply published %v; the board reloads instead", rec.subjects()) + } + }) + + t.Run("http rejections", func(t *testing.T) { + h := setupStepRouter(t) + malformed := doRaw(t, h, http.MethodPost, "/api/v1/workflows/workflow-1/workflow/steps", "{") + requireJSONError(t, malformed, http.StatusBadRequest, "Invalid request") + + unknown := doJSON(t, h.router, http.MethodPost, "/api/v1/workflows/workflow-1/workflow/steps", + map[string]interface{}{"template_id": "nope"}) + requireJSONError(t, unknown, http.StatusNotFound, "Step not found") + if names := listStepNames(t, h, "workflow-1"); len(names) != 0 { + t.Fatalf("rejected apply wrote %v", names) + } + }) + + t.Run("ws applies the template steps", func(t *testing.T) { + h := setupStepRouter(t) + seedTemplate(t, h, "template-1", "Seeded Flow") + + var got map[string]bool + requireWSResponse(t, h.dispatch(t, ws.ActionWorkflowStepCreate, map[string]any{ + "workflow_id": "workflow-1", "template_id": "template-1", + }), &got) + if !got["success"] { + t.Fatalf("response = %#v", got) + } + if names := listStepNames(t, h, "workflow-1"); len(names) != 2 { + t.Fatalf("persisted steps = %v", names) + } + }) + + t.Run("ws rejections", func(t *testing.T) { + h := setupStepRouter(t) + for _, payload := range []map[string]any{ + {"template_id": "template-1"}, + {"workflow_id": "workflow-1"}, + } { + frame := requireWSError(t, + h.dispatch(t, ws.ActionWorkflowStepCreate, payload), ws.ErrorCodeValidation) + if frame.Message != "workflow_id and template_id are required" { + t.Errorf("message = %q", frame.Message) + } + } + requireWSError(t, h.dispatch(t, ws.ActionWorkflowStepCreate, map[string]any{ + "workflow_id": 7, + }), ws.ErrorCodeBadRequest) + requireWSError(t, h.dispatch(t, ws.ActionWorkflowStepCreate, map[string]any{ + "workflow_id": "workflow-1", "template_id": "nope", + }), ws.ErrorCodeInternalError) + if names := listStepNames(t, h, "workflow-1"); len(names) != 0 { + t.Fatalf("rejected apply wrote %v", names) + } + }) +} + +// TestStepMutationStoreFailureIsNotMisreported guards the default branch of +// writeStepMutationError: a write that fails for a reason which is neither a +// known validation message nor a not-found must stay a 500. Misreporting it as +// 400 or 404 would tell the board the input was bad and stop it retrying. +// +// The trigger is a template whose two steps share a template-level ID: they +// collapse onto one generated UUID and the second insert violates the primary +// key, which no validation rule catches. +func TestStepMutationStoreFailureIsNotMisreported(t *testing.T) { + h := setupStepRouter(t) + if _, err := h.db.Exec( + `INSERT INTO workflow_templates (id, name, description, is_system, steps, created_at, updated_at) + VALUES ('collide','Colliding','',0,?,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP)`, + `[{"id":"same","name":"One","position":0},{"id":"same","name":"Two","position":1}]`); err != nil { + t.Fatalf("seed template: %v", err) + } + rec := recordStepEvents(t, h.eventBus) + + resp := doJSON(t, h.router, http.MethodPost, "/api/v1/workflows/workflow-1/workflow/steps", + map[string]interface{}{"template_id": "collide"}) + requireJSONError(t, resp, http.StatusInternalServerError, "Failed to save step") + if len(rec.events) != 0 { + t.Fatalf("failed apply published %v", rec.subjects()) + } +} + +// TestUpdateStepMalformedJSON pins the 400 for an unparsable update body, with +// the parse reason preserved so the client can tell it apart from a rejected +// but well-formed request. +func TestUpdateStepMalformedJSON(t *testing.T) { + h := setupStepRouter(t) + step := createStepViaHTTP(t, h.router, map[string]interface{}{ + "workflow_id": "workflow-1", "name": "Backlog", "position": 0, + }) + rec := recordStepEvents(t, h.eventBus) + + resp := doRaw(t, h, http.MethodPut, "/api/v1/workflow/steps/"+step.ID, "{") + if resp.Code != http.StatusBadRequest { + t.Fatalf("status = %d, want 400; body = %s", resp.Code, resp.Body.String()) + } + if !strings.Contains(resp.Body.String(), "Invalid request: ") { + t.Fatalf("body = %s, want the parse reason", resp.Body.String()) + } + if len(rec.events) != 0 { + t.Fatalf("rejected update published %v", rec.subjects()) + } +} + +// TestExportSingleWorkflowFailureIs500 covers the remaining export branch: an +// unresolvable workflow is a server error, not an empty document, so the UI +// does not offer the user a download of nothing. +func TestExportSingleWorkflowFailureIs500(t *testing.T) { + h := setupStepRouter(t) + h.service.SetWorkflowProvider(&fakeWorkflowProvider{}) + rec := doJSON(t, h.router, http.MethodGet, "/api/v1/workflows/nope/export", nil) + requireJSONError(t, rec, http.StatusInternalServerError, "Failed to export workflow") +} + +// listStepNames returns the persisted step names for a workflow, in order. +func listStepNames(t *testing.T, h *workflowHarness, workflowID string) []string { + t.Helper() + rec := doJSON(t, h.router, http.MethodGet, "/api/v1/workflows/"+workflowID+"/workflow/steps", nil) + if rec.Code != http.StatusOK { + t.Fatalf("list steps status = %d, body = %s", rec.Code, rec.Body.String()) + } + var listed controller.ListStepsResponse + if err := json.Unmarshal(rec.Body.Bytes(), &listed); err != nil { + t.Fatalf("decode steps: %v", err) + } + names := make([]string, 0, len(listed.Steps)) + for _, step := range listed.Steps { + names = append(names, step.Name) + } + return names +} + +// TestUnknownWorkflowActionIsRejected pins the dispatcher contract the handlers +// rely on: an action this package never registered is answered, not dropped. +func TestUnknownWorkflowActionIsRejected(t *testing.T) { + h := setupStepRouter(t) + requireWSError(t, h.dispatch(t, "workflow.step.delete", map[string]any{"id": "x"}), ws.ErrorCodeUnknownAction) + if h.dispatcher.HasHandler(events.WorkflowStepDeleted) { + t.Fatal("the event subject must not be registered as a dispatchable action") + } +}