Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 53 additions & 0 deletions cmd/hlctl/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
type Client interface {
CreateTask(req *CreateTaskRequest) (*CreateTaskResponse, error)
ListAgents(tags []string) ([]Agent, error)
ListTasks(filters *ListTasksRequest) ([]Task, error)
}

// HTTPClient implements the Client interface
Expand Down Expand Up @@ -49,6 +50,21 @@ type Agent struct {
ID string `json:"id"`
}

// ListTasksRequest represents filters for listing tasks
type ListTasksRequest struct {
Status string
AgentID string
}

// Task represents a task from the API
type Task struct {
ID string `json:"id"`
Command string `json:"command"`
Status string `json:"status"`
Priority int `json:"priority"`
CreatedAt time.Time `json:"created_at"`
}

// CreateTask creates a new task via the API
func (c *HTTPClient) CreateTask(req *CreateTaskRequest) (*CreateTaskResponse, error) {
jsonData, err := json.Marshal(req)
Expand Down Expand Up @@ -113,3 +129,40 @@ func (c *HTTPClient) ListAgents(tags []string) ([]Agent, error) {

return agents, nil
}

// ListTasks lists tasks with optional filters
func (c *HTTPClient) ListTasks(filters *ListTasksRequest) ([]Task, error) {
u, err := url.Parse(c.baseURL + "/api/v2/tasks")
if err != nil {
return nil, fmt.Errorf("failed to parse URL: %w", err)
}

if filters != nil {
q := u.Query()
if filters.Status != "" {
q.Add("status", filters.Status)
}
if filters.AgentID != "" {
q.Add("agent", filters.AgentID)
}
u.RawQuery = q.Encode()
}

resp, err := c.client.Get(u.String())
if err != nil {
return nil, fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
return nil, fmt.Errorf("API error: status %d, body: %s", resp.StatusCode, string(body))
}

var tasks []Task
if err := json.NewDecoder(resp.Body).Decode(&tasks); err != nil {
return nil, fmt.Errorf("failed to decode response: %w", err)
}

return tasks, nil
}
148 changes: 148 additions & 0 deletions cmd/hlctl/client/client_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -222,3 +222,151 @@ func TestListAgents_ParsesResponse(t *testing.T) {
assert.Equal(t, "agt_200", agents[1].ID)
assert.Equal(t, "agt_300", agents[2].ID)
}

func TestListTasks_WithoutFilters(t *testing.T) {
// Verifies that GET /api/v2/tasks is called with no query params when filters are nil
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/api/v2/tasks", r.URL.Path)
assert.Equal(t, "GET", r.Method)
assert.Empty(t, r.URL.Query().Get("status"))
assert.Empty(t, r.URL.Query().Get("agent"))

w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode([]Task{
{ID: "task-1", Command: "ls", Status: "pending", Priority: 1},
})
}))
defer server.Close()

client := NewHTTPClient(server.URL)

tasks, err := client.ListTasks(nil)

require.NoError(t, err)
assert.Len(t, tasks, 1)
assert.Equal(t, "task-1", tasks[0].ID)
}

func TestListTasks_WithStatusFilter(t *testing.T) {
// Verifies that GET /api/v2/tasks?status=pending is called when Status filter is provided
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/api/v2/tasks", r.URL.Path)
assert.Equal(t, "pending", r.URL.Query().Get("status"))

w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode([]Task{
{ID: "task-1", Command: "ls", Status: "pending", Priority: 1},
})
}))
defer server.Close()

client := NewHTTPClient(server.URL)
filters := &ListTasksRequest{Status: "pending"}

tasks, err := client.ListTasks(filters)

require.NoError(t, err)
assert.Len(t, tasks, 1)
assert.Equal(t, "pending", tasks[0].Status)
}

func TestListTasks_WithAgentFilter(t *testing.T) {
// Verifies that GET /api/v2/tasks?agent=agt_123 is called when AgentID filter is provided
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/api/v2/tasks", r.URL.Path)
assert.Equal(t, "agt_123", r.URL.Query().Get("agent"))

w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode([]Task{
{ID: "task-1", Command: "ls", Status: "pending", Priority: 1},
})
}))
defer server.Close()

client := NewHTTPClient(server.URL)
filters := &ListTasksRequest{AgentID: "agt_123"}

tasks, err := client.ListTasks(filters)

require.NoError(t, err)
assert.Len(t, tasks, 1)
}

func TestListTasks_WithMultipleFilters(t *testing.T) {
// Verifies that GET /api/v2/tasks?status=completed&agent=agt_123 is called with both filters
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
assert.Equal(t, "/api/v2/tasks", r.URL.Path)
assert.Equal(t, "completed", r.URL.Query().Get("status"))
assert.Equal(t, "agt_123", r.URL.Query().Get("agent"))

w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode([]Task{
{ID: "task-1", Command: "ls", Status: "completed", Priority: 1},
})
}))
defer server.Close()

client := NewHTTPClient(server.URL)
filters := &ListTasksRequest{Status: "completed", AgentID: "agt_123"}

tasks, err := client.ListTasks(filters)

require.NoError(t, err)
assert.Len(t, tasks, 1)
assert.Equal(t, "completed", tasks[0].Status)
}

func TestListTasks_ParsesResponse(t *testing.T) {
// Verifies that JSON array response is correctly parsed into []Task struct with all fields
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode([]map[string]any{
{
"id": "task-100",
"command": "ls -la",
"status": "pending",
"priority": 5,
"created_at": "2025-10-03T10:00:00Z",
},
{
"id": "task-200",
"command": "echo test",
"status": "completed",
"priority": 1,
"created_at": "2025-10-03T11:00:00Z",
},
})
}))
defer server.Close()

client := NewHTTPClient(server.URL)

tasks, err := client.ListTasks(nil)

require.NoError(t, err)
require.Len(t, tasks, 2)
assert.Equal(t, "task-100", tasks[0].ID)
assert.Equal(t, "ls -la", tasks[0].Command)
assert.Equal(t, "pending", tasks[0].Status)
assert.Equal(t, 5, tasks[0].Priority)
assert.False(t, tasks[0].CreatedAt.IsZero())
assert.Equal(t, "task-200", tasks[1].ID)
}

func TestListTasks_HandlesAPIError(t *testing.T) {
// Verifies that non-200 status code returns an error with status code and body in error message
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{
"error": "database connection failed",
})
}))
defer server.Close()

client := NewHTTPClient(server.URL)

_, err := client.ListTasks(nil)

require.Error(t, err)
assert.Contains(t, err.Error(), "500")
}
57 changes: 57 additions & 0 deletions cmd/hlctl/commands/task.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ func TaskCommand() *cli.Command {
Usage: "Manage tasks",
Commands: []*cli.Command{
createTaskCommand(),
listTaskCommand(),
},
}
}
Expand Down Expand Up @@ -138,3 +139,59 @@ func readScriptFile(filePath string) (string, error) {
}
return string(content), nil
}

// listTaskCommand returns the list subcommand
func listTaskCommand() *cli.Command {
return &cli.Command{
Name: "list",
Usage: "List tasks",
Flags: []cli.Flag{
&cli.StringFlag{
Name: "status",
Usage: "Filter by status",
},
&cli.StringFlag{
Name: "agent",
Usage: "Filter by agent ID",
},
},
Action: listTaskAction,
}
}

// listTaskAction handles the list task command
func listTaskAction(ctx context.Context, c *cli.Command) error {
cfg, err := config.Load()
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
}

serverURL := cfg.GetServerURL()
if c.IsSet("server") {
serverURL = c.String("server")
}

httpClient := client.NewHTTPClient(serverURL)

filters := &client.ListTasksRequest{}
if c.IsSet("status") {
filters.Status = c.String("status")
}
if c.IsSet("agent") {
filters.AgentID = c.String("agent")
}

tasks, err := httpClient.ListTasks(filters)
if err != nil {
return fmt.Errorf("failed to list tasks: %w", err)
}

formatter := output.NewJSONFormatter()
jsonOutput, err := formatter.Format(tasks)
if err != nil {
return fmt.Errorf("failed to format output: %w", err)
}

fmt.Println(jsonOutput)
return nil
}
20 changes: 10 additions & 10 deletions domain/task/task.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,16 @@ import (
)

type Task struct {
ID string
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time
Command string
Status string
Priority int
Output string
Error string
ExitCode int
ID string `json:"id"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
DeletedAt *time.Time `json:"deleted_at,omitempty"`
Command string `json:"command"`
Status string `json:"status"`
Priority int `json:"priority"`
Output string `json:"output"`
Error string `json:"error"`
ExitCode int `json:"exit_code"`
}

type TaskFilters struct {
Expand Down
Loading