Skip to content

refactor: create tasks in coderd instead of frontend #19280

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 15 commits into from
Aug 12, 2025
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
Prev Previous commit
Next Next commit
chore: finish making that change
  • Loading branch information
DanielleMaywood committed Aug 12, 2025
commit 9b5a99ce2979c44d6857f6a6a5216d2ddb62a00c
52 changes: 46 additions & 6 deletions coderd/aitasks.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"net/http"
"slices"
"strings"

"github.com/google/uuid"
Expand Down Expand Up @@ -75,10 +76,10 @@ func (api *API) tasksCreate(rw http.ResponseWriter, r *http.Request) {
ctx = r.Context()
apiKey = httpmw.APIKey(r)
auditor = api.Auditor.Load()
member = httpmw.OrganizationMemberParam(r)
mems = httpmw.OrganizationMembersParam(r)
)

var req codersdk.CreateAITasksRequest
var req codersdk.CreateTaskRequest
if !httpapi.Read(ctx, rw, r, &req) {
return
}
Expand Down Expand Up @@ -112,10 +113,49 @@ func (api *API) tasksCreate(rw http.ResponseWriter, r *http.Request) {
},
}

owner := workspaceOwner{
ID: member.UserID,
Username: member.Username,
AvatarURL: member.AvatarURL,
var owner workspaceOwner
if mems.User != nil {
// This user fetch is an optimization path for the most common case of creating a
// task for 'Me'.
//
// This is also required to allow `owners` to create workspaces for users
// that are not in an organization.
owner = workspaceOwner{
ID: mems.User.ID,
Username: mems.User.Username,
AvatarURL: mems.User.AvatarURL,
}
} else {
// A task can still be created if the caller can read the organization
// member. The organization is required, which can be sourced from the
// template.
//
// TODO: This code gets called twice for each workspace build request.
// This is inefficient and costs at most 2 extra RTTs to the DB.
// This can be optimized. It exists as it is now for code simplicity.
// The most common case is to create a workspace for 'Me'. Which does
// not enter this code branch.
template, ok := requestTemplate(ctx, rw, createReq, api.Database)
if !ok {
return
}

// If the caller can find the organization membership in the same org
// as the template, then they can continue.
orgIndex := slices.IndexFunc(mems.Memberships, func(mem httpmw.OrganizationMember) bool {
return mem.OrganizationID == template.OrganizationID
})
if orgIndex == -1 {
httpapi.ResourceNotFound(rw)
return
}

member := mems.Memberships[orgIndex]
owner = workspaceOwner{
ID: member.UserID,
Username: member.Username,
AvatarURL: member.AvatarURL,
}
}

aReq, commitAudit := audit.InitRequest[database.WorkspaceTable](rw, &audit.RequestParams{
Expand Down
8 changes: 4 additions & 4 deletions coderd/aitasks_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ func TestAITasksPrompts(t *testing.T) {
})
}

func TestAITasksCreate(t *testing.T) {
func TestTaskCreate(t *testing.T) {
t.Parallel()

t.Run("OK", func(t *testing.T) {
Expand Down Expand Up @@ -175,7 +175,7 @@ func TestAITasksCreate(t *testing.T) {
expClient := codersdk.NewExperimentalClient(client)

// When: We attempt to create a Task.
workspace, err := expClient.AITasksCreate(ctx, codersdk.CreateAITasksRequest{
workspace, err := expClient.CreateTask(ctx, "me", codersdk.CreateTaskRequest{
Name: taskName,
TemplateVersionID: template.ActiveVersionID,
Prompt: taskPrompt,
Expand Down Expand Up @@ -216,7 +216,7 @@ func TestAITasksCreate(t *testing.T) {
expClient := codersdk.NewExperimentalClient(client)

// When: We attempt to create a Task.
_, err := expClient.AITasksCreate(ctx, codersdk.CreateAITasksRequest{
_, err := expClient.CreateTask(ctx, "me", codersdk.CreateTaskRequest{
Name: taskName,
TemplateVersionID: template.ActiveVersionID,
Prompt: taskPrompt,
Expand Down Expand Up @@ -250,7 +250,7 @@ func TestAITasksCreate(t *testing.T) {
expClient := codersdk.NewExperimentalClient(client)

// When: We attempt to create a Task with an invalid template version ID.
_, err := expClient.AITasksCreate(ctx, codersdk.CreateAITasksRequest{
_, err := expClient.CreateTask(ctx, "me", codersdk.CreateTaskRequest{
Name: taskName,
TemplateVersionID: uuid.New(),
Prompt: taskPrompt,
Expand Down
6 changes: 5 additions & 1 deletion coderd/coderd.go
Original file line number Diff line number Diff line change
Expand Up @@ -998,7 +998,11 @@ func New(options *Options) *API {
r.Route("/tasks", func(r chi.Router) {
r.Use(apiRateLimiter)

r.Post("/{user}", api.tasksCreate)
r.Route("/{user}", func(r chi.Router) {
r.Use(httpmw.ExtractOrganizationMembersParam(options.Database, api.HTTPAuth.Authorize))

r.Post("/", api.tasksCreate)
})
})
r.Route("/mcp", func(r chi.Router) {
r.Use(
Expand Down
7 changes: 4 additions & 3 deletions codersdk/aitasks.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package codersdk
import (
"context"
"encoding/json"
"fmt"
"net/http"
"strings"

Expand Down Expand Up @@ -45,15 +46,15 @@ func (c *ExperimentalClient) AITaskPrompts(ctx context.Context, buildIDs []uuid.
return prompts, json.NewDecoder(res.Body).Decode(&prompts)
}

type CreateAITasksRequest struct {
type CreateTaskRequest struct {
Name string `json:"name"`
TemplateVersionID uuid.UUID `json:"template_version_id" format:"uuid"`
TemplateVersionPresetID uuid.UUID `json:"template_version_preset_id,omitempty" format:"uuid"`
Prompt string `json:"prompt"`
}

func (c *ExperimentalClient) AITasksCreate(ctx context.Context, request CreateAITasksRequest) (Workspace, error) {
res, err := c.Request(ctx, http.MethodPost, "/api/experimental/aitasks", request)
func (c *ExperimentalClient) CreateTask(ctx context.Context, user string, request CreateTaskRequest) (Workspace, error) {
res, err := c.Request(ctx, http.MethodPost, fmt.Sprintf("/api/experimental/tasks/%s", user), request)
if err != nil {
return Workspace{}, err
}
Expand Down
7 changes: 4 additions & 3 deletions site/src/api/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2666,11 +2666,12 @@ class ExperimentalApiMethods {
return response.data;
};

createAITask = async (
req: TypesGen.CreateAITasksRequest,
createTask = async (
user: string,
req: TypesGen.CreateTaskRequest,
): Promise<TypesGen.Workspace> => {
const response = await this.axios.post<TypesGen.Workspace>(
"/api/experimental/aitasks",
`/api/experimental/tasks/${user}`,
req,
);

Expand Down
16 changes: 8 additions & 8 deletions site/src/api/typesGenerated.ts

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 4 additions & 2 deletions site/src/pages/TasksPage/TasksPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,7 @@ type TaskFormProps = {
};

const TaskForm: FC<TaskFormProps> = ({ templates, onSuccess }) => {
const { user } = useAuthenticated();
const queryClient = useQueryClient();
const [selectedTemplateId, setSelectedTemplateId] = useState<string>(
templates[0].id,
Expand Down Expand Up @@ -292,7 +293,7 @@ const TaskForm: FC<TaskFormProps> = ({ templates, onSuccess }) => {
templateVersionId,
presetId,
}: CreateTaskMutationFnProps) =>
data.createTask(prompt, templateVersionId, presetId),
data.createTask(prompt, user.id, templateVersionId, presetId),
onSuccess: async (task) => {
await queryClient.invalidateQueries({
queryKey: ["tasks"],
Expand Down Expand Up @@ -726,6 +727,7 @@ export const data = {

async createTask(
prompt: string,
userId: string,
templateVersionId: string,
presetId: string | null = null,
): Promise<Task> {
Expand All @@ -739,7 +741,7 @@ export const data = {
}
}

const workspace = await API.experimental.createAITask({
const workspace = await API.experimental.createTask(userId, {
name: `task-${generateWorkspaceName()}`,
template_version_id: templateVersionId,
template_version_preset_id: preset_id || undefined,
Expand Down
Loading