Files
coder/coderd/x/chatd/chattool/stopworkspace.go
T
Ethan 2d725a1ced refactor(coderd): move the chat start decision into the start tool (#32433)
Closes CODAGT-292
Relates to CODAGT-1607

`coderd/export_test.go` re-exported `chatCreateWorkspace`,
`chatStartWorkspace`, `chatStopWorkspace` and
`chatRenderTemplateParameters`, just so four tests could call them
directly. This PR removes those tests and their aliases, and the last
alias in that file goes in the next PR in the stack.

The start and stop tests only checked which template version the build
ends up on. That decision lived in `coderd`, behind the function the
tool calls, so the only way to test it was to call that function
directly. Now `start_workspace` makes the decision itself, much like
`coder start` does: it checks whether the template requires its active
version, sends that version with the build request, and tells the model
how to retry when the update needs parameters. All of that is covered by
the tool's own tests. With the decision gone, the start and stop
functions were identical, so both tools now share `chatBuildWorkspace`,
which just creates a build as the workspace owner.

Two small behaviour changes. `start_workspace` now returns `template_id`
whenever it asks the model to retry with parameters. Previously it was
missing for templates on the classic parameter flow, even though the
message says to use it. The tool also reads the template's setting
directly, like `coder start`, so chat updates on start too when the
setting is still on after a licence lapses.

`TestStartWorkspaceTool_EndToEnd` now starts a workspace whose active
version needs a new parameter, so we still know the whole flow works
against a real `coderd`.

`chatRenderTemplateParameters` keeps a direct test, it's just an
internal one now, against a database instead of a whole `coderd`. It no
longer checks the owner default, as that's already tested in the
renderer and in the tool. The bind failure test needs a real
transaction, so it moves to `chatd` and runs through the
`create_workspace` tool.
2026-12-01 00:17:20 +11:00

182 lines
5.9 KiB
Go

package chattool
import (
"context"
"sync"
"charm.land/fantasy"
"github.com/google/uuid"
"golang.org/x/xerrors"
"cdr.dev/slog/v3"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/httpapi/httperror"
"github.com/coder/coder/v2/codersdk"
)
// StopWorkspaceOptions configures the stop_workspace tool.
type StopWorkspaceOptions struct {
OwnerID uuid.UUID
BuildFn BuildWorkspaceFn
WorkspaceMu *sync.Mutex
OnChatUpdated func(database.Chat)
Logger slog.Logger
}
type stopWorkspaceArgs struct{}
// StopWorkspace returns a tool that stops the workspace associated
// with the current chat. The tool is idempotent when the workspace is
// already stopped. db must not be nil and chatID must not be uuid.Nil.
func StopWorkspace(db database.Store, chatID uuid.UUID, options StopWorkspaceOptions) fantasy.AgentTool {
return fantasy.NewAgentTool(
"stop_workspace",
"Stop the chat's workspace and wait for the stop build to complete. "+
"If another workspace build is already in progress, this waits "+
"for that build first, then stops the workspace if needed. "+
"After waiting, this tool is idempotent if the workspace is "+
"already stopped or the in-progress build stopped it. Use "+
"this when the "+
"user explicitly asks to stop the workspace, or when a "+
"workspace-agent error tells you to stop and then start the "+
"workspace. Stopping a workspace terminates running processes "+
"and may discard unsaved in-memory state. This tool does not "+
"delete the workspace.",
func(ctx context.Context, _ stopWorkspaceArgs, _ fantasy.ToolCall) (fantasy.ToolResponse, error) {
if options.BuildFn == nil {
return fantasy.NewTextErrorResponse("workspace stopper is not configured"), nil
}
// Serialize with create_workspace and start_workspace to
// prevent lifecycle races.
if options.WorkspaceMu != nil {
options.WorkspaceMu.Lock()
defer options.WorkspaceMu.Unlock()
}
chat, err := db.GetChatByID(ctx, chatID)
if err != nil {
return fantasy.NewTextErrorResponse(
xerrors.Errorf("load chat: %w", err).Error(),
), nil
}
if !chat.WorkspaceID.Valid {
return fantasy.NewTextErrorResponse(
"chat has no workspace; use create_workspace first",
), nil
}
ws, err := db.GetWorkspaceByID(ctx, chat.WorkspaceID.UUID)
if err != nil {
return workspaceLoadErrorResponse(err), nil
}
if ws.Deleted {
return fantasy.NewTextErrorResponse(
"workspace was deleted; use create_workspace to make a new one",
), nil
}
build, job, err := latestWorkspaceBuildAndJob(ctx, db, ws.ID)
if err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
// If a build is already in progress, wait for it before
// deciding whether a stop build is still needed.
switch job.JobStatus {
case database.ProvisionerJobStatusPending,
database.ProvisionerJobStatusRunning,
database.ProvisionerJobStatusCanceling:
if err := publishBuildBinding(ctx, db, chatID, ws.ID, build.ID, options.OnChatUpdated); err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
waitErr := waitForBuild(ctx, db, build.ID)
// Re-read after waiting because another transition may
// have completed while this tool was blocked.
ws, err = db.GetWorkspaceByID(ctx, ws.ID)
if err != nil {
return workspaceLoadErrorResponse(err), nil
}
if ws.Deleted {
return fantasy.NewTextErrorResponse(
"workspace was deleted; use create_workspace to make a new one",
), nil
}
build, job, err = latestWorkspaceBuildAndJob(ctx, db, ws.ID)
if err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
// The fresh job row is authoritative. A wait error can
// be stale if the build reached a terminal state while the
// wait context was ending.
if waitErr != nil && !provisionerJobTerminal(job.JobStatus) {
return buildToolResponse(newBuildError(
xerrors.Errorf("waiting for in-progress build: %w", waitErr).Error(),
build.ID,
)), nil
}
}
if job.JobStatus == database.ProvisionerJobStatusSucceeded &&
build.Transition == database.WorkspaceTransitionStop {
if chat.BuildID.UUID != build.ID {
if err := publishBuildBinding(ctx, db, chatID, ws.ID, build.ID, options.OnChatUpdated); err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
}
result := map[string]any{
"stopped": true,
"workspace_name": ws.Name,
}
setNoBuild(result, uuid.Nil)
return toolResponse(result), nil
}
ownerCtx, ownerErr := asOwner(ctx, db, options.OwnerID)
if ownerErr != nil {
return fantasy.NewTextErrorResponse(ownerErr.Error()), nil
}
stopBuild, err := options.BuildFn(ownerCtx, options.OwnerID, ws.ID, codersdk.CreateWorkspaceBuildRequest{
Transition: codersdk.WorkspaceTransitionStop,
})
if err != nil {
if responseErr, ok := httperror.IsResponder(err); ok {
_, resp := responseErr.Response()
return toolResponse(responseErrorResult(resp)), nil
}
return fantasy.NewTextErrorResponse(
xerrors.Errorf("stop workspace: %w", err).Error(),
), nil
}
if err := publishBuildBinding(ctx, db, chatID, ws.ID, stopBuild.ID, options.OnChatUpdated); err != nil {
return fantasy.NewTextErrorResponse(err.Error()), nil
}
if err := waitForBuild(ctx, db, stopBuild.ID); err != nil {
return buildToolResponse(newBuildError(
xerrors.Errorf("workspace stop build failed: %w", err).Error(),
stopBuild.ID,
)), nil
}
if options.OnChatUpdated != nil {
latest, err := db.GetChatByID(ctx, chatID)
if err != nil {
return fantasy.NewTextErrorResponse(
xerrors.Errorf("load chat: %w", err).Error(),
), nil
}
options.OnChatUpdated(latest)
}
result := map[string]any{
"stopped": true,
"workspace_name": ws.Name,
}
setBuildID(result, stopBuild.ID)
return toolResponse(result), nil
})
}