Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Next Next commit
feat(coderd): add tasks delete endpoint
  • Loading branch information
mafredri committed Aug 27, 2025
commit aa46321dea9477ddbdbf098fdfc202083e2c9efa
121 changes: 121 additions & 0 deletions coderd/aitasks.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package coderd

import (
"bytes"
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"net/http"
Expand Down Expand Up @@ -440,3 +442,122 @@ func (api *API) taskGet(rw http.ResponseWriter, r *http.Request) {

httpapi.Write(ctx, rw, http.StatusOK, tasks[0])
}

// taskDelete is an experimental endpoint to delete a task by ID (workspace ID).
// It creates a delete workspace build and returns 202 Accepted if the build was created.
func (api *API) taskDelete(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()

idStr := chi.URLParam(r, "id")
taskID, err := uuid.Parse(idStr)
if err != nil {
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: fmt.Sprintf("Invalid UUID %q for task ID.", idStr),
})
return
}

// For now, taskID = workspaceID, once we have a task data model in
// the DB, we can change this lookup.
workspaceID := taskID
workspace, err := api.Database.GetWorkspaceByID(ctx, workspaceID)
if httpapi.Is404Error(err) {
httpapi.ResourceNotFound(rw)
return
}
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error fetching workspace.",
Detail: err.Error(),
})
return
}

data, err := api.workspaceData(ctx, []database.Workspace{workspace})
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error fetching workspace resources.",
Detail: err.Error(),
})
return
}
if len(data.builds) == 0 || len(data.templates) == 0 {
httpapi.ResourceNotFound(rw)
return
}
if data.builds[0].HasAITask == nil || !*data.builds[0].HasAITask {
httpapi.ResourceNotFound(rw)
return
}

// Construct a request to the workspace build creation handler to initiate deletion.
buildReq := codersdk.CreateWorkspaceBuildRequest{
Transition: codersdk.WorkspaceTransitionDelete,
}
body, err := json.Marshal(buildReq)
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error marshaling delete request.",
Detail: err.Error(),
})
return
}

req, err := http.NewRequestWithContext(ctx, http.MethodPost, fmt.Sprintf("/api/v2/workspaces/%s/builds", workspace.ID.String()), bytes.NewReader(body))
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Internal error creating request.",
Detail: err.Error(),
})
return
}
req.Header.Set("Content-Type", "application/json")

// Inject the "workspace" URL param so ExtractWorkspaceParam can
// resolve the workspace.
rctx := chi.NewRouteContext()
rctx.URLParams.Add("workspace", workspace.ID.String())
req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))

// Call the existing workspace build handler via middleware.
rc := &responseWriterCapture{}
handler := httpmw.ExtractWorkspaceParam(api.Database)(http.HandlerFunc(api.postWorkspaceBuilds))
handler.ServeHTTP(rc, req)

status := rc.status
if status == 0 {
status = http.StatusOK
}

if status != http.StatusCreated {
// Propagate the error response from the workspace build handler.
for k, vs := range rc.Header() {
for _, v := range vs {
rw.Header().Add(k, v)
}
}
rw.WriteHeader(status)
_, _ = rw.Write(rc.body.Bytes())
return
}

// Delete build created successfully.
rw.WriteHeader(http.StatusAccepted)
}

type responseWriterCapture struct {
header http.Header
status int
body bytes.Buffer
}

func (w *responseWriterCapture) Header() http.Header {
if w.header == nil {
w.header = make(http.Header)
}
return w.header
}

func (w *responseWriterCapture) Write(b []byte) (int, error) { return w.body.Write(b) }

func (w *responseWriterCapture) WriteHeader(statusCode int) { w.status = statusCode }
114 changes: 114 additions & 0 deletions coderd/aitasks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package coderd_test
import (
"net/http"
"testing"
"time"

"github.com/google/uuid"
"github.com/stretchr/testify/assert"
Expand Down Expand Up @@ -265,6 +266,119 @@ func TestTasks(t *testing.T) {
assert.Equal(t, workspace.ID, task.WorkspaceID.UUID, "workspace id should match")
assert.NotEmpty(t, task.Status, "task status should not be empty")
})

t.Run("Delete", func(t *testing.T) {
t.Parallel()

t.Run("OK", func(t *testing.T) {
t.Parallel()

client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true})
user := coderdtest.CreateFirstUser(t, client)
template := createAITemplate(t, client, user)

ws := coderdtest.CreateWorkspace(t, client, template.ID, func(req *codersdk.CreateWorkspaceRequest) {
req.RichParameterValues = []codersdk.WorkspaceBuildParameter{
{Name: codersdk.AITaskPromptParameterName, Value: "delete-me"},
}
})
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, ws.LatestBuild.ID)

ctx := testutil.Context(t, testutil.WaitLong)

exp := codersdk.NewExperimentalClient(client)
err := exp.DeleteTask(ctx, "me", ws.ID)
require.NoError(t, err, "delete task request should be accepted")

// Poll until the workspace is deleted.
for {
dws, derr := client.DeletedWorkspace(ctx, ws.ID)
if derr == nil && dws.LatestBuild.Status == codersdk.WorkspaceStatusDeleted {
break
}
if ctx.Err() != nil {
require.NoError(t, derr, "expected to fetch deleted workspace before deadline")
require.Equal(t, codersdk.WorkspaceStatusDeleted, dws.LatestBuild.Status, "workspace should be deleted before deadline")
break
}
time.Sleep(testutil.IntervalMedium)
}
})

t.Run("NotFound", func(t *testing.T) {
t.Parallel()

client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true})
_ = coderdtest.CreateFirstUser(t, client)

ctx := testutil.Context(t, testutil.WaitShort)

exp := codersdk.NewExperimentalClient(client)
err := exp.DeleteTask(ctx, "me", uuid.New())

var sdkErr *codersdk.Error
require.Error(t, err, "expected an error for non-existent task")
require.ErrorAs(t, err, &sdkErr)
require.Equal(t, 404, sdkErr.StatusCode())
})

t.Run("NotTaskWorkspace", func(t *testing.T) {
t.Parallel()

client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true})
user := coderdtest.CreateFirstUser(t, client)

ctx := testutil.Context(t, testutil.WaitShort)

// Create a template without AI tasks support and a workspace from it.
version := coderdtest.CreateTemplateVersion(t, client, user.OrganizationID, nil)
coderdtest.AwaitTemplateVersionJobCompleted(t, client, version.ID)
template := coderdtest.CreateTemplate(t, client, user.OrganizationID, version.ID)
ws := coderdtest.CreateWorkspace(t, client, template.ID)
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, ws.LatestBuild.ID)

exp := codersdk.NewExperimentalClient(client)
err := exp.DeleteTask(ctx, "me", ws.ID)

var sdkErr *codersdk.Error
require.Error(t, err, "expected an error for non-task workspace delete via tasks endpoint")
require.ErrorAs(t, err, &sdkErr)
require.Equal(t, 404, sdkErr.StatusCode())
})

t.Run("UnauthorizedUserCannotDeleteOthersTask", func(t *testing.T) {
t.Parallel()

client := coderdtest.New(t, &coderdtest.Options{IncludeProvisionerDaemon: true})
owner := coderdtest.CreateFirstUser(t, client)

// Owner's AI-capable template and workspace (task).
template := createAITemplate(t, client, owner)
ws := coderdtest.CreateWorkspace(t, client, template.ID, func(req *codersdk.CreateWorkspaceRequest) {
req.RichParameterValues = []codersdk.WorkspaceBuildParameter{
{Name: codersdk.AITaskPromptParameterName, Value: "secure"},
}
})
coderdtest.AwaitWorkspaceBuildJobCompleted(t, client, ws.LatestBuild.ID)

ctx := testutil.Context(t, testutil.WaitShort)

// Another regular org member without elevated permissions.
otherClient, _ := coderdtest.CreateAnotherUser(t, client, owner.OrganizationID)
expOther := codersdk.NewExperimentalClient(otherClient)

// Attempt to delete the owner's task as a non-owner without permissions.
err := expOther.DeleteTask(ctx, "me", ws.ID)

var authErr *codersdk.Error
require.Error(t, err, "expected an authorization error when deleting another user's task")
require.ErrorAs(t, err, &authErr)
// Accept either 403 or 404 depending on authz behavior.
if authErr.StatusCode() != 403 && authErr.StatusCode() != 404 {
t.Fatalf("unexpected status code: %d (expected 403 or 404)", authErr.StatusCode())
}
})
})
}

func TestTasksCreate(t *testing.T) {
Expand Down
1 change: 1 addition & 0 deletions coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -1013,6 +1013,7 @@ func New(options *Options) *API {
r.Route("/{user}", func(r chi.Router) {
r.Use(httpmw.ExtractOrganizationMembersParam(options.Database, api.HTTPAuth.Authorize))
r.Get("/{id}", api.taskGet)
r.Delete("/{id}", api.taskDelete)
r.Post("/", api.tasksCreate)
})
})
Expand Down
15 changes: 15 additions & 0 deletions codersdk/aitasks.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,3 +183,18 @@ func (c *ExperimentalClient) TaskByID(ctx context.Context, id uuid.UUID) (Task,

return task, nil
}

// DeleteTask deletes a task by its ID.
//
// Experimental: This method is experimental and may change in the future.
func (c *ExperimentalClient) DeleteTask(ctx context.Context, user string, id uuid.UUID) error {
res, err := c.Request(ctx, http.MethodDelete, fmt.Sprintf("/api/experimental/tasks/%s/%s", user, id.String()), nil)
if err != nil {
return err
}
defer res.Body.Close()
if res.StatusCode != http.StatusAccepted {
return ReadBodyAsError(res)
}
return nil
}
Loading