package api import ( "bytes" "encoding/json" "fmt" "log/slog" "net/http" "net/http/httptest" "os" "path/filepath" "strings" "testing" "time" "context" "github.com/thepeterstone/claudomator/internal/executor" "github.com/thepeterstone/claudomator/internal/notify" "github.com/thepeterstone/claudomator/internal/storage" "github.com/thepeterstone/claudomator/internal/task" ) // mockNotifier records calls to Notify. type mockNotifier struct { events []notify.Event } func (m *mockNotifier) Notify(e notify.Event) error { m.events = append(m.events, e) return nil } func TestServer_ProcessResult_CallsNotifier(t *testing.T) { srv, store := testServer(t) mn := &mockNotifier{} srv.SetNotifier(mn) tk := &task.Task{ ID: "task-notifier-test", Name: "Notifier Task", State: task.StatePending, } if err := store.CreateTask(tk); err != nil { t.Fatal(err) } result := &executor.Result{ TaskID: tk.ID, Execution: &storage.Execution{ ID: "exec-1", TaskID: tk.ID, Status: "COMPLETED", CostUSD: 0.42, ErrorMsg: "", }, } srv.processResult(result) if len(mn.events) != 1 { t.Fatalf("expected 1 notify event, got %d", len(mn.events)) } ev := mn.events[0] if ev.TaskID != tk.ID { t.Errorf("event.TaskID = %q, want %q", ev.TaskID, tk.ID) } if ev.Status != "COMPLETED" { t.Errorf("event.Status = %q, want COMPLETED", ev.Status) } if ev.CostUSD != 0.42 { t.Errorf("event.CostUSD = %v, want 0.42", ev.CostUSD) } } func testServer(t *testing.T) (*Server, *storage.DB) { t.Helper() dbPath := filepath.Join(t.TempDir(), "test.db") store, err := storage.Open(dbPath) if err != nil { t.Fatal(err) } t.Cleanup(func() { store.Close() }) logger := slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError})) runner := &mockRunner{} runners := map[string]executor.Runner{ "claude": runner, "gemini": runner, } pool := executor.NewPool(2, runners, store, logger) srv := NewServer(store, pool, logger, "claude", "gemini") return srv, store } type mockRunner struct{} func (m *mockRunner) Run(_ context.Context, _ *task.Task, _ *storage.Execution) error { return nil } func TestHealthEndpoint(t *testing.T) { srv, _ := testServer(t) req := httptest.NewRequest("GET", "/api/health", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("status: want 200, got %d", w.Code) } var body map[string]string json.NewDecoder(w.Body).Decode(&body) if body["status"] != "ok" { t.Errorf("want status=ok, got %v", body) } } func TestCreateTask_Success(t *testing.T) { srv, _ := testServer(t) payload := `{ "name": "API Task", "description": "Created via API", "agent": { "type": "claude", "instructions": "do the thing", "model": "sonnet" }, "timeout": "5m", "tags": ["api"] }` req := httptest.NewRequest("POST", "/api/tasks", bytes.NewBufferString(payload)) req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusCreated { t.Fatalf("status: want 201, got %d; body: %s", w.Code, w.Body.String()) } var created task.Task json.NewDecoder(w.Body).Decode(&created) if created.Name != "API Task" { t.Errorf("name: want 'API Task', got %q", created.Name) } if created.ID == "" { t.Error("expected auto-generated ID") } } func TestCreateTask_InvalidJSON(t *testing.T) { srv, _ := testServer(t) req := httptest.NewRequest("POST", "/api/tasks", bytes.NewBufferString("{bad json")) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusBadRequest { t.Errorf("status: want 400, got %d", w.Code) } } func TestCreateTask_ValidationFailure(t *testing.T) { srv, _ := testServer(t) payload := `{"name": "", "agent": {"type": "claude", "instructions": ""}}` req := httptest.NewRequest("POST", "/api/tasks", bytes.NewBufferString(payload)) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusBadRequest { t.Errorf("status: want 400, got %d", w.Code) } } func TestListTasks_Empty(t *testing.T) { srv, _ := testServer(t) req := httptest.NewRequest("GET", "/api/tasks", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("status: want 200, got %d", w.Code) } var tasks []task.Task json.NewDecoder(w.Body).Decode(&tasks) if len(tasks) != 0 { t.Errorf("want 0 tasks, got %d", len(tasks)) } } func TestGetTask_NotFound(t *testing.T) { srv, _ := testServer(t) req := httptest.NewRequest("GET", "/api/tasks/nonexistent", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusNotFound { t.Errorf("status: want 404, got %d", w.Code) } } func TestListTasks_WithTasks(t *testing.T) { srv, store := testServer(t) // Create tasks directly in store. for i := 0; i < 3; i++ { tk := &task.Task{ ID: fmt.Sprintf("lt-%d", i), Name: fmt.Sprintf("T%d", i), Agent: task.AgentConfig{Type: "claude", Instructions: "x"}, Priority: task.PriorityNormal, Retry: task.RetryConfig{MaxAttempts: 1, Backoff: "linear"}, Tags: []string{}, DependsOn: []string{}, State: task.StatePending, } store.CreateTask(tk) } req := httptest.NewRequest("GET", "/api/tasks", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) var tasks []task.Task json.NewDecoder(w.Body).Decode(&tasks) if len(tasks) != 3 { t.Errorf("want 3 tasks, got %d", len(tasks)) } } // stateWalkPaths defines the sequence of intermediate states needed to reach each target state. var stateWalkPaths = map[task.State][]task.State{ task.StatePending: {}, task.StateQueued: {task.StateQueued}, task.StateRunning: {task.StateQueued, task.StateRunning}, task.StateCompleted: {task.StateQueued, task.StateRunning, task.StateCompleted}, task.StateFailed: {task.StateQueued, task.StateRunning, task.StateFailed}, task.StateTimedOut: {task.StateQueued, task.StateRunning, task.StateTimedOut}, task.StateCancelled: {task.StateCancelled}, task.StateBudgetExceeded: {task.StateQueued, task.StateRunning, task.StateBudgetExceeded}, task.StateReady: {task.StateQueued, task.StateRunning, task.StateReady}, task.StateBlocked: {task.StateQueued, task.StateRunning, task.StateBlocked}, } func createTaskWithState(t *testing.T, store *storage.DB, id string, state task.State) *task.Task { t.Helper() tk := &task.Task{ ID: id, Name: "test-task-" + id, Agent: task.AgentConfig{Type: "claude", Instructions: "do something"}, Priority: task.PriorityNormal, Retry: task.RetryConfig{MaxAttempts: 1, Backoff: "linear"}, Tags: []string{}, DependsOn: []string{}, State: task.StatePending, } if err := store.CreateTask(tk); err != nil { t.Fatalf("createTaskWithState: CreateTask: %v", err) } for _, s := range stateWalkPaths[state] { if err := store.UpdateTaskState(id, s); err != nil { t.Fatalf("createTaskWithState: UpdateTaskState(%s): %v", s, err) } } tk.State = state return tk } func TestRunTask_PendingTask_Returns202(t *testing.T) { srv, store := testServer(t) createTaskWithState(t, store, "run-pending", task.StatePending) req := httptest.NewRequest("POST", "/api/tasks/run-pending/run", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusAccepted { t.Errorf("status: want 202, got %d; body: %s", w.Code, w.Body.String()) } } func TestRunTask_FailedTask_Returns202(t *testing.T) { srv, store := testServer(t) createTaskWithState(t, store, "run-failed", task.StateFailed) req := httptest.NewRequest("POST", "/api/tasks/run-failed/run", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusAccepted { t.Errorf("status: want 202, got %d; body: %s", w.Code, w.Body.String()) } } func TestRunTask_TimedOutTask_Returns202(t *testing.T) { srv, store := testServer(t) // TIMED_OUT → QUEUED is a valid transition (retry path). // We need to get the task into TIMED_OUT state; storage allows direct state writes. createTaskWithState(t, store, "run-timedout", task.StateTimedOut) req := httptest.NewRequest("POST", "/api/tasks/run-timedout/run", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusAccepted { t.Errorf("status: want 202, got %d; body: %s", w.Code, w.Body.String()) } } func TestRunTask_CompletedTask_Returns409(t *testing.T) { srv, store := testServer(t) createTaskWithState(t, store, "run-completed", task.StateCompleted) req := httptest.NewRequest("POST", "/api/tasks/run-completed/run", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusConflict { t.Errorf("status: want 409, got %d; body: %s", w.Code, w.Body.String()) } var body map[string]string json.NewDecoder(w.Body).Decode(&body) wantMsg := "task cannot be queued from state COMPLETED" if body["error"] != wantMsg { t.Errorf("error body: want %q, got %q", wantMsg, body["error"]) } } func TestAcceptTask_ReadyTask_Returns200(t *testing.T) { srv, store := testServer(t) createTaskWithState(t, store, "accept-ready", task.StateReady) req := httptest.NewRequest("POST", "/api/tasks/accept-ready/accept", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("status: want 200, got %d; body: %s", w.Code, w.Body.String()) } got, _ := store.GetTask("accept-ready") if got.State != task.StateCompleted { t.Errorf("task state: want COMPLETED, got %v", got.State) } } func TestAcceptTask_NonReadyTask_Returns409(t *testing.T) { srv, store := testServer(t) createTaskWithState(t, store, "accept-pending", task.StatePending) req := httptest.NewRequest("POST", "/api/tasks/accept-pending/accept", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusConflict { t.Errorf("status: want 409, got %d; body: %s", w.Code, w.Body.String()) } } func TestRejectTask_ReadyTask_Returns200(t *testing.T) { srv, store := testServer(t) createTaskWithState(t, store, "reject-ready", task.StateReady) body := bytes.NewBufferString(`{"comment": "needs more detail"}`) req := httptest.NewRequest("POST", "/api/tasks/reject-ready/reject", body) req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("status: want 200, got %d; body: %s", w.Code, w.Body.String()) } got, _ := store.GetTask("reject-ready") if got.State != task.StatePending { t.Errorf("task state: want PENDING, got %v", got.State) } if got.RejectionComment != "needs more detail" { t.Errorf("rejection_comment: want 'needs more detail', got %q", got.RejectionComment) } } func TestRejectTask_NonReadyTask_Returns409(t *testing.T) { srv, store := testServer(t) createTaskWithState(t, store, "reject-pending", task.StatePending) body := bytes.NewBufferString(`{"comment": "comment"}`) req := httptest.NewRequest("POST", "/api/tasks/reject-pending/reject", body) req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusConflict { t.Errorf("status: want 409, got %d; body: %s", w.Code, w.Body.String()) } } func TestCORS_Headers(t *testing.T) { srv, _ := testServer(t) req := httptest.NewRequest("OPTIONS", "/api/tasks", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Header().Get("Access-Control-Allow-Origin") != "*" { t.Error("missing CORS origin header") } if w.Code != http.StatusOK { t.Errorf("OPTIONS status: want 200, got %d", w.Code) } } func TestAnswerQuestion_NoTask_Returns404(t *testing.T) { srv, _ := testServer(t) req := httptest.NewRequest("POST", "/api/tasks/nonexistent/answer", bytes.NewBufferString(`{"answer":"blue"}`)) req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusNotFound { t.Errorf("status: want 404, got %d; body: %s", w.Code, w.Body.String()) } } func TestAnswerQuestion_TaskNotBlocked_Returns409(t *testing.T) { srv, store := testServer(t) createTaskWithState(t, store, "answer-task-1", task.StatePending) req := httptest.NewRequest("POST", "/api/tasks/answer-task-1/answer", bytes.NewBufferString(`{"answer":"blue"}`)) req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusConflict { t.Errorf("status: want 409, got %d; body: %s", w.Code, w.Body.String()) } } func TestAnswerQuestion_MissingAnswer_Returns400(t *testing.T) { srv, store := testServer(t) createTaskWithState(t, store, "answer-task-2", task.StateBlocked) req := httptest.NewRequest("POST", "/api/tasks/answer-task-2/answer", bytes.NewBufferString(`{}`)) req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusBadRequest { t.Errorf("status: want 400, got %d; body: %s", w.Code, w.Body.String()) } } func TestAnswerQuestion_BlockedTask_QueuesResume(t *testing.T) { srv, store := testServer(t) createTaskWithState(t, store, "answer-task-3", task.StateBlocked) // Create an execution with a session ID, as the runner would have. exec := &storage.Execution{ ID: "exec-blocked-1", TaskID: "answer-task-3", SessionID: "550e8400-e29b-41d4-a716-446655440001", Status: "BLOCKED", } if err := store.CreateExecution(exec); err != nil { t.Fatalf("create execution: %v", err) } req := httptest.NewRequest("POST", "/api/tasks/answer-task-3/answer", bytes.NewBufferString(`{"answer":"main"}`)) req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusOK { t.Errorf("status: want 200, got %d; body: %s", w.Code, w.Body.String()) } // Task should now be QUEUED (or RUNNING since the mock runner is instant). got, _ := store.GetTask("answer-task-3") if got.State != task.StateQueued && got.State != task.StateRunning && got.State != task.StateReady { t.Errorf("task state: want QUEUED/RUNNING/READY after answer, got %v", got.State) } } func TestHandleStartNextTask_Success(t *testing.T) { dir := t.TempDir() script := filepath.Join(dir, "start-next-task") if err := os.WriteFile(script, []byte("#!/bin/sh\necho 'claudomator start abc-123'\n"), 0755); err != nil { t.Fatal(err) } srv, _ := testServer(t) srv.SetScripts(ScriptRegistry{"start-next-task": script}) req := httptest.NewRequest("POST", "/api/scripts/start-next-task", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusOK { t.Fatalf("want 200, got %d; body: %s", w.Code, w.Body.String()) } var body map[string]interface{} json.NewDecoder(w.Body).Decode(&body) if body["output"] != "claudomator start abc-123\n" { t.Errorf("unexpected output: %v", body["output"]) } if body["exit_code"] != float64(0) { t.Errorf("unexpected exit_code: %v", body["exit_code"]) } } func TestHandleStartNextTask_NoTask(t *testing.T) { dir := t.TempDir() script := filepath.Join(dir, "start-next-task") if err := os.WriteFile(script, []byte("#!/bin/sh\necho 'No task to start.'\n"), 0755); err != nil { t.Fatal(err) } srv, _ := testServer(t) srv.SetScripts(ScriptRegistry{"start-next-task": script}) req := httptest.NewRequest("POST", "/api/scripts/start-next-task", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusOK { t.Fatalf("want 200, got %d; body: %s", w.Code, w.Body.String()) } var body map[string]interface{} json.NewDecoder(w.Body).Decode(&body) if body["output"] != "No task to start.\n" { t.Errorf("unexpected output: %v", body["output"]) } } func TestResumeTimedOut_NoTask_Returns404(t *testing.T) { srv, _ := testServer(t) req := httptest.NewRequest("POST", "/api/tasks/nonexistent/resume", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusNotFound { t.Errorf("status: want 404, got %d; body: %s", w.Code, w.Body.String()) } } func TestResumeTimedOut_TaskNotTimedOut_Returns409(t *testing.T) { srv, store := testServer(t) createTaskWithState(t, store, "resume-task-1", task.StatePending) req := httptest.NewRequest("POST", "/api/tasks/resume-task-1/resume", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusConflict { t.Errorf("status: want 409, got %d; body: %s", w.Code, w.Body.String()) } } func TestResumeTimedOut_NoSession_Returns500(t *testing.T) { srv, store := testServer(t) createTaskWithState(t, store, "resume-task-2", task.StateTimedOut) // No execution created — so no session ID. req := httptest.NewRequest("POST", "/api/tasks/resume-task-2/resume", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusInternalServerError { t.Errorf("status: want 500, got %d; body: %s", w.Code, w.Body.String()) } } func TestResumeTimedOut_Success_Returns202(t *testing.T) { srv, store := testServer(t) createTaskWithState(t, store, "resume-task-3", task.StateTimedOut) exec := &storage.Execution{ ID: "exec-timedout-1", TaskID: "resume-task-3", SessionID: "550e8400-e29b-41d4-a716-446655440002", Status: "TIMED_OUT", } if err := store.CreateExecution(exec); err != nil { t.Fatalf("create execution: %v", err) } req := httptest.NewRequest("POST", "/api/tasks/resume-task-3/resume", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusAccepted { t.Errorf("status: want 202, got %d; body: %s", w.Code, w.Body.String()) } got, _ := store.GetTask("resume-task-3") if got.State != task.StateQueued && got.State != task.StateRunning && got.State != task.StateReady { t.Errorf("task state: want QUEUED/RUNNING/READY after resume, got %v", got.State) } } // TestRunTask_ManualRunIgnoresRetryLimit verifies that a manual POST /run always // succeeds regardless of MaxAttempts — retry limits only gate automatic retries. func TestRunTask_ManualRunIgnoresRetryLimit(t *testing.T) { srv, store := testServer(t) tk := &task.Task{ ID: "retry-limit-manual", Name: "Retry Limit Task", Agent: task.AgentConfig{Instructions: "do something"}, Priority: task.PriorityNormal, Retry: task.RetryConfig{MaxAttempts: 1, Backoff: "linear"}, Tags: []string{}, DependsOn: []string{}, State: task.StateFailed, } if err := store.CreateTask(tk); err != nil { t.Fatal(err) } // Record one execution — MaxAttempts already exhausted. exec := &storage.Execution{ ID: "exec-retry-manual", TaskID: "retry-limit-manual", StartTime: time.Now(), Status: "FAILED", } if err := store.CreateExecution(exec); err != nil { t.Fatal(err) } req := httptest.NewRequest("POST", "/api/tasks/retry-limit-manual/run", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) // Manual run must succeed (202) even though MaxAttempts is exhausted. if w.Code != http.StatusAccepted { t.Errorf("status: want 202, got %d; body: %s", w.Code, w.Body.String()) } } func TestRunTask_WithinRetryLimit_Returns202(t *testing.T) { srv, store := testServer(t) // Task with MaxAttempts: 3 — 1 execution used, 2 remaining. tk := &task.Task{ ID: "retry-within-1", Name: "Retry Within Task", Agent: task.AgentConfig{Instructions: "do something"}, Priority: task.PriorityNormal, Retry: task.RetryConfig{MaxAttempts: 3, Backoff: "linear"}, Tags: []string{}, DependsOn: []string{}, State: task.StatePending, } if err := store.CreateTask(tk); err != nil { t.Fatal(err) } exec := &storage.Execution{ ID: "exec-within-1", TaskID: "retry-within-1", StartTime: time.Now(), Status: "FAILED", } if err := store.CreateExecution(exec); err != nil { t.Fatal(err) } store.UpdateTaskState("retry-within-1", task.StateFailed) req := httptest.NewRequest("POST", "/api/tasks/retry-within-1/run", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusAccepted { t.Errorf("status: want 202, got %d; body: %s", w.Code, w.Body.String()) } } func TestHandleStartNextTask_ScriptNotFound(t *testing.T) { srv, _ := testServer(t) srv.SetScripts(ScriptRegistry{"start-next-task": "/nonexistent/start-next-task"}) req := httptest.NewRequest("POST", "/api/scripts/start-next-task", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusInternalServerError { t.Errorf("want 500, got %d; body: %s", w.Code, w.Body.String()) } } func TestDeleteTask_Success(t *testing.T) { srv, store := testServer(t) // Create a task to delete. created := createTestTask(t, srv, `{"name":"Delete Me","agent":{"type":"claude","instructions":"x","model":"sonnet"}}`) req := httptest.NewRequest("DELETE", "/api/tasks/"+created.ID, nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusNoContent { t.Fatalf("want 204, got %d; body: %s", w.Code, w.Body.String()) } _, err := store.GetTask(created.ID) if err == nil { t.Error("task should be deleted from store") } } func TestDeleteTask_NotFound(t *testing.T) { srv, _ := testServer(t) req := httptest.NewRequest("DELETE", "/api/tasks/does-not-exist", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusNotFound { t.Errorf("want 404, got %d", w.Code) } } func TestDeleteTask_RunningTaskRejected(t *testing.T) { srv, store := testServer(t) // Create the task directly in RUNNING state to avoid going through state transitions. tk := &task.Task{ ID: "running-task-del", Name: "Running Task", Agent: task.AgentConfig{Instructions: "x", Model: "sonnet"}, Priority: task.PriorityNormal, Tags: []string{}, DependsOn: []string{}, State: task.StateRunning, } if err := store.CreateTask(tk); err != nil { t.Fatal(err) } req := httptest.NewRequest("DELETE", "/api/tasks/running-task-del", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusConflict { t.Errorf("want 409 for running task, got %d", w.Code) } } // createTestTask is a helper that POSTs a task and returns the parsed Task. func createTestTask(t *testing.T, srv *Server, payload string) task.Task { t.Helper() req := httptest.NewRequest("POST", "/api/tasks", bytes.NewBufferString(payload)) req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusCreated { t.Fatalf("createTestTask: want 201, got %d; body: %s", w.Code, w.Body.String()) } var tk task.Task json.NewDecoder(w.Body).Decode(&tk) return tk } func TestServer_CancelTask_Pending_TransitionsToCancelled(t *testing.T) { srv, store := testServer(t) createTaskWithState(t, store, "cancel-pending-1", task.StatePending) req := httptest.NewRequest("POST", "/api/tasks/cancel-pending-1/cancel", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusOK { t.Fatalf("status: want 200, got %d; body: %s", w.Code, w.Body.String()) } updated, err := store.GetTask("cancel-pending-1") if err != nil { t.Fatal(err) } if updated.State != task.StateCancelled { t.Errorf("state: want CANCELLED, got %s", updated.State) } } func TestServer_CancelTask_Queued_TransitionsToCancelled(t *testing.T) { srv, store := testServer(t) createTaskWithState(t, store, "cancel-queued-1", task.StateQueued) req := httptest.NewRequest("POST", "/api/tasks/cancel-queued-1/cancel", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusOK { t.Fatalf("status: want 200, got %d; body: %s", w.Code, w.Body.String()) } updated, err := store.GetTask("cancel-queued-1") if err != nil { t.Fatal(err) } if updated.State != task.StateCancelled { t.Errorf("state: want CANCELLED, got %s", updated.State) } } func TestServer_CancelTask_Completed_Returns409(t *testing.T) { srv, store := testServer(t) createTaskWithState(t, store, "cancel-completed-1", task.StateCompleted) req := httptest.NewRequest("POST", "/api/tasks/cancel-completed-1/cancel", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusConflict { t.Errorf("status: want 409, got %d; body: %s", w.Code, w.Body.String()) } } // mockQuestionStore implements questionStore for testing handleAnswerQuestion. type mockQuestionStore struct { getTaskFn func(id string) (*task.Task, error) getLatestExecutionFn func(taskID string) (*storage.Execution, error) updateTaskQuestionFn func(taskID, questionJSON string) error updateTaskStateFn func(id string, newState task.State) error } func (m *mockQuestionStore) GetTask(id string) (*task.Task, error) { return m.getTaskFn(id) } func (m *mockQuestionStore) GetLatestExecution(taskID string) (*storage.Execution, error) { return m.getLatestExecutionFn(taskID) } func (m *mockQuestionStore) UpdateTaskQuestion(taskID, questionJSON string) error { return m.updateTaskQuestionFn(taskID, questionJSON) } func (m *mockQuestionStore) UpdateTaskState(id string, newState task.State) error { return m.updateTaskStateFn(id, newState) } func TestServer_AnswerQuestion_UpdateQuestionFails_Returns500(t *testing.T) { srv, _ := testServer(t) srv.questionStore = &mockQuestionStore{ getTaskFn: func(id string) (*task.Task, error) { return &task.Task{ID: id, State: task.StateBlocked}, nil }, getLatestExecutionFn: func(taskID string) (*storage.Execution, error) { return &storage.Execution{SessionID: "sess-1"}, nil }, updateTaskQuestionFn: func(taskID, questionJSON string) error { return fmt.Errorf("db error") }, updateTaskStateFn: func(id string, newState task.State) error { return nil }, } body := bytes.NewBufferString(`{"answer":"yes"}`) req := httptest.NewRequest("POST", "/api/tasks/task-1/answer", body) req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusInternalServerError { t.Errorf("status: want 500, got %d; body: %s", w.Code, w.Body.String()) } } func TestServer_AnswerQuestion_UpdateStateFails_Returns500(t *testing.T) { srv, _ := testServer(t) srv.questionStore = &mockQuestionStore{ getTaskFn: func(id string) (*task.Task, error) { return &task.Task{ID: id, State: task.StateBlocked}, nil }, getLatestExecutionFn: func(taskID string) (*storage.Execution, error) { return &storage.Execution{SessionID: "sess-1"}, nil }, updateTaskQuestionFn: func(taskID, questionJSON string) error { return nil }, updateTaskStateFn: func(id string, newState task.State) error { return fmt.Errorf("db error") }, } body := bytes.NewBufferString(`{"answer":"yes"}`) req := httptest.NewRequest("POST", "/api/tasks/task-1/answer", body) req.Header.Set("Content-Type", "application/json") w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusInternalServerError { t.Errorf("status: want 500, got %d; body: %s", w.Code, w.Body.String()) } } func TestRateLimit_ElaborateRejectsExcess(t *testing.T) { srv, _ := testServer(t) // Use burst-1 and rate-0 so the second request from the same IP is rejected. srv.elaborateLimiter = newIPRateLimiter(0, 1) makeReq := func(remoteAddr string) int { req := httptest.NewRequest("POST", "/api/tasks/elaborate", bytes.NewBufferString(`{"description":"x"}`)) req.Header.Set("Content-Type", "application/json") req.RemoteAddr = remoteAddr w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) return w.Code } // First request from IP A: limiter allows it (non-429). if code := makeReq("192.0.2.1:1234"); code == http.StatusTooManyRequests { t.Errorf("first request should not be rate limited, got 429") } // Second request from IP A: bucket exhausted, must be 429. if code := makeReq("192.0.2.1:1234"); code != http.StatusTooManyRequests { t.Errorf("second request from same IP should be 429, got %d", code) } // First request from IP B: separate bucket, not limited. if code := makeReq("192.0.2.2:1234"); code == http.StatusTooManyRequests { t.Errorf("first request from different IP should not be rate limited, got 429") } } func TestListWorkspaces_RequiresAuth(t *testing.T) { srv, _ := testServer(t) srv.SetAPIToken("secret-token") // No token: expect 401. req := httptest.NewRequest("GET", "/api/workspaces", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusUnauthorized { t.Errorf("expected 401 without token, got %d", w.Code) } } func TestListWorkspaces_RejectsWrongToken(t *testing.T) { srv, _ := testServer(t) srv.SetAPIToken("secret-token") req := httptest.NewRequest("GET", "/api/workspaces", nil) req.Header.Set("Authorization", "Bearer wrong-token") w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code != http.StatusUnauthorized { t.Errorf("expected 401 with wrong token, got %d", w.Code) } } func TestListWorkspaces_SuppressesRawError(t *testing.T) { srv, _ := testServer(t) // No token configured so auth is bypassed; /workspace likely doesn't exist in test env. req := httptest.NewRequest("GET", "/api/workspaces", nil) w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) if w.Code == http.StatusInternalServerError { body := w.Body.String() if strings.Contains(body, "/workspace") || strings.Contains(body, "no such file") { t.Errorf("response leaks filesystem details: %s", body) } } } func TestRateLimit_ValidateRejectsExcess(t *testing.T) { srv, _ := testServer(t) srv.elaborateLimiter = newIPRateLimiter(0, 1) makeReq := func(remoteAddr string) int { req := httptest.NewRequest("POST", "/api/tasks/validate", bytes.NewBufferString(`{"description":"x"}`)) req.Header.Set("Content-Type", "application/json") req.RemoteAddr = remoteAddr w := httptest.NewRecorder() srv.Handler().ServeHTTP(w, req) return w.Code } if code := makeReq("192.0.2.1:1234"); code == http.StatusTooManyRequests { t.Errorf("first validate request should not be rate limited, got 429") } if code := makeReq("192.0.2.1:1234"); code != http.StatusTooManyRequests { t.Errorf("second validate request from same IP should be 429, got %d", code) } }