2026-02-27 11:50:56 -05:00
package chattool
import (
"context"
2026-05-08 13:51:13 +10:00
"database/sql"
2026-03-05 09:42:12 +00:00
"errors"
2026-02-27 11:50:56 -05:00
"fmt"
2026-06-01 23:31:25 +10:00
"net/http"
2026-02-27 11:50:56 -05:00
"strings"
"sync"
"time"
"charm.land/fantasy"
"github.com/google/uuid"
"golang.org/x/xerrors"
2026-03-13 19:53:20 +02:00
"cdr.dev/slog/v3"
2026-02-27 11:50:56 -05:00
"github.com/coder/coder/v2/coderd/database"
2026-04-14 22:23:06 -07:00
"github.com/coder/coder/v2/coderd/database/dbtime"
2026-04-21 11:36:20 +10:00
"github.com/coder/coder/v2/coderd/httpapi/httperror"
2026-02-27 11:50:56 -05:00
"github.com/coder/coder/v2/coderd/util/namesgenerator"
2026-07-14 13:50:25 +01:00
"github.com/coder/coder/v2/coderd/x/chatd/agentselect"
2026-02-27 11:50:56 -05:00
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/workspacesdk"
)
const (
// buildPollInterval is how often we check if the workspace
// build has completed.
buildPollInterval = 2 * time . Second
// buildTimeout is the maximum time to wait for a workspace
// build to complete before giving up.
buildTimeout = 10 * time . Minute
// agentConnectTimeout is the maximum time to wait for the
// workspace agent to become reachable after a successful build.
agentConnectTimeout = 2 * time . Minute
// agentRetryInterval is how often we retry connecting to the
// workspace agent.
agentRetryInterval = 2 * time . Second
// agentAttemptTimeout is the timeout for a single connection
// attempt to the workspace agent during the retry loop.
agentAttemptTimeout = 5 * time . Second
2026-03-05 09:42:12 +00:00
// startupScriptTimeout is the maximum time to wait for the
// workspace agent's startup scripts to finish after the agent
// is reachable.
startupScriptTimeout = 10 * time . Minute
// startupScriptPollInterval is how often we check the agent's
// lifecycle state while waiting for startup scripts.
startupScriptPollInterval = 2 * time . Second
2026-02-27 11:50:56 -05:00
)
// CreateWorkspaceFn creates a workspace for the given owner.
type CreateWorkspaceFn func (
ctx context . Context ,
ownerID uuid . UUID ,
req codersdk . CreateWorkspaceRequest ,
) ( codersdk . Workspace , error )
// AgentConnFunc provides access to workspace agent connections.
type AgentConnFunc func (
ctx context . Context ,
agentID uuid . UUID ,
) ( workspacesdk . AgentConn , func (), error )
// CreateWorkspaceOptions configures the create_workspace tool.
type CreateWorkspaceOptions struct {
2026-03-26 00:12:05 +11:00
OwnerID uuid . UUID
CreateFn CreateWorkspaceFn
AgentConnFn AgentConnFunc
AgentInactiveDisconnectTimeout time . Duration
WorkspaceMu * sync . Mutex
2026-03-26 17:22:38 +11:00
OnChatUpdated func ( database . Chat )
2026-03-26 00:12:05 +11:00
Logger slog . Logger
2026-02-27 11:50:56 -05:00
}
type createWorkspaceArgs struct {
2026-04-21 11:37:29 -07:00
TemplateID string `json:"template_id" description:"The UUIDv4 of the template to create the workspace from. Obtain this from list_templates."`
Name string `json:"name,omitempty" description:"The name of the workspace to create. If not provided, a random name will be generated."`
2026-06-18 13:41:47 +08:00
Parameters map [ string ] string `json:"parameters,omitempty" description:"Key-value pairs of template parameters to use when creating the workspace. Obtain available parameters from read_template when needed."`
PresetID string `json:"preset_id,omitempty" description:"The UUIDv4 of a template version preset to use. Obtain available presets from read_template when needed. When provided, the preset's parameters are applied automatically and the workspace may claim a prebuilt instance for faster startup."`
2026-02-27 11:50:56 -05:00
}
// CreateWorkspace returns a tool that creates a new workspace from a
// template. The tool is idempotent: if the chat already has a
// workspace that is building or running, it returns the existing
// workspace instead of creating a new one. A mutex prevents parallel
// calls from creating duplicate workspaces.
2026-05-06 11:05:16 +01:00
// db must not be nil and chatID must not be uuid.Nil.
func CreateWorkspace ( db database . Store , organizationID , chatID uuid . UUID , options CreateWorkspaceOptions ) fantasy . AgentTool {
2026-02-27 11:50:56 -05:00
return fantasy . NewAgentTool (
"create_workspace" ,
2026-05-22 16:08:07 +02:00
"Create a new workspace from a template only when workspace-backed " +
"file inspection, command execution, or file editing is required, " +
"or when the user explicitly asks for one. Do not use this as a " +
"default first step for requests answerable from conversation " +
"context, provider tools, or external MCP tools. Requires a " +
2026-06-18 13:41:47 +08:00
"template_id from list_templates; follow its " + NextStepField + " " +
"before calling. Optionally provide a name (one is generated if " +
"omitted), parameter values, and a preset_id from read_template " +
"to apply preset parameters and potentially claim a prebuilt " +
"workspace for faster startup. Idempotent: if the chat already " +
"has a workspace building or running, it is returned." ,
2026-02-27 11:50:56 -05:00
func ( ctx context . Context , args createWorkspaceArgs , _ fantasy . ToolCall ) ( fantasy . ToolResponse , error ) {
if options . CreateFn == nil {
return fantasy . NewTextErrorResponse ( "workspace creator is not configured" ), nil
}
templateIDStr := strings . TrimSpace ( args . TemplateID )
if templateIDStr == "" {
return fantasy . NewTextErrorResponse ( "template_id is required; use list_templates to find one" ), nil
}
templateID , err := uuid . Parse ( templateIDStr )
if err != nil {
return fantasy . NewTextErrorResponse (
xerrors . Errorf ( "invalid template_id: %w" , err ). Error (),
), nil
}
// Serialize workspace creation to prevent parallel
// tool calls from creating duplicate workspaces.
if options . WorkspaceMu != nil {
options . WorkspaceMu . Lock ()
defer options . WorkspaceMu . Unlock ()
}
2026-05-07 15:01:58 +10:00
ownerID := options . OwnerID
2026-02-27 11:50:56 -05:00
// Check for an existing workspace on the chat.
2026-05-06 11:05:16 +01:00
check := options . checkExistingWorkspace ( ctx , db , chatID )
2026-05-07 15:01:58 +10:00
if check . BuildErr != nil {
return buildFailureToolResponse (
ctx ,
options . Logger ,
db ,
ownerID ,
organizationID ,
check . BuildAction ,
check . BuildID ,
check . BuildErr ,
), nil
}
2026-04-12 15:04:10 +01:00
if check . Err != nil {
return fantasy . NewTextErrorResponse ( check . Err . Error ()), nil
2026-03-26 00:12:05 +11:00
}
2026-04-12 15:04:10 +01:00
if check . Done {
return toolResponse ( check . Result ), nil
2026-02-27 11:50:56 -05:00
}
// Set up dbauthz context for DB lookups.
2026-04-15 11:39:05 +01:00
ownerCtx , ownerErr := asOwner ( ctx , db , ownerID )
if ownerErr != nil {
return fantasy . NewTextErrorResponse ( ownerErr . Error ()), nil
2026-02-27 11:50:56 -05:00
}
2026-04-15 11:39:05 +01:00
ctx = ownerCtx
2026-02-27 11:50:56 -05:00
2026-04-13 12:31:25 +01:00
// Verify the template belongs to the same org as the
// chat. Without this check the tool could silently
// bind a cross-org workspace to the chat.
2026-04-15 11:39:05 +01:00
tmpl , tmplErr := db . GetTemplateByID ( ctx , templateID )
if tmplErr != nil {
return fantasy . NewTextErrorResponse (
xerrors . Errorf ( "look up template: %w" , tmplErr ). Error (),
), nil
}
if tmpl . OrganizationID != organizationID {
return fantasy . NewTextErrorResponse (
"template belongs to a different organization than this chat; " +
"use list_templates to find templates in the correct organization" ,
), nil
2026-04-13 12:31:25 +01:00
}
2026-08-06 14:14:37 +10:00
if ! tmpl . AgentsAllowed {
return fantasy . NewTextErrorResponse ( templateNotAvailableMessage ), nil
}
2026-04-13 12:31:25 +01:00
2026-05-08 13:51:13 +10:00
hasExternalAgent , externalAgentErr := templateHasExternalAgent ( ctx , db , tmpl )
if externalAgentErr != nil {
return fantasy . NewTextErrorResponse (
xerrors . Errorf ( "look up template version: %w" , externalAgentErr ). Error (),
), nil
}
if hasExternalAgent {
return fantasy . NewTextErrorResponse ( createWorkspaceExternalAgentMessage ), nil
}
2026-03-20 17:38:39 +00:00
var ttlMs * int64
2026-04-15 11:39:05 +01:00
raw , err := db . GetChatWorkspaceTTL ( ctx )
if err != nil {
options . Logger . Error ( ctx , "failed to read chat workspace TTL setting, using template default" ,
slog . Error ( err ),
)
} else {
d , parseErr := codersdk . ParseChatWorkspaceTTL ( raw )
if parseErr != nil {
options . Logger . Warn ( ctx , "invalid chat workspace TTL setting, using template default" ,
slog . F ( "raw" , raw ),
slog . Error ( parseErr ),
2026-03-20 17:38:39 +00:00
)
2026-04-15 11:39:05 +01:00
} else if d > 0 {
ms := d . Milliseconds ()
ttlMs = & ms
2026-03-20 17:38:39 +00:00
}
}
2026-02-27 11:50:56 -05:00
createReq := codersdk . CreateWorkspaceRequest {
TemplateID : templateID ,
2026-03-20 17:38:39 +00:00
TTLMillis : ttlMs ,
2026-02-27 11:50:56 -05:00
}
2026-05-01 10:57:52 +01:00
// Apply preset if provided.
presetIDStr := strings . TrimSpace ( args . PresetID )
if presetIDStr != "" {
presetID , err := uuid . Parse ( presetIDStr )
if err != nil {
return fantasy . NewTextErrorResponse (
xerrors . Errorf ( "invalid preset_id: %w" , err ). Error (),
), nil
}
createReq . TemplateVersionPresetID = presetID
}
2026-02-27 11:50:56 -05:00
name := strings . TrimSpace ( args . Name )
if name == "" {
2026-04-15 11:39:05 +01:00
name = generatedWorkspaceName ( tmpl . Name )
2026-02-27 11:50:56 -05:00
} else if err := codersdk . NameValid ( name ); err != nil {
name = generatedWorkspaceName ( name )
}
createReq . Name = name
// Map parameters.
for k , v := range args . Parameters {
createReq . RichParameterValues = append (
createReq . RichParameterValues ,
codersdk . WorkspaceBuildParameter { Name : k , Value : v },
)
}
2026-06-01 23:31:25 +10:00
workspace , err := createWorkspaceWithNameRetry ( ctx , ownerID , createReq , options . CreateFn )
2026-02-27 11:50:56 -05:00
if err != nil {
2026-04-21 11:36:20 +10:00
if responseErr , ok := httperror . IsResponder ( err ); ok {
_ , resp := responseErr . Response ()
return toolResponse ( responseErrorResult ( resp )), nil
}
2026-02-27 11:50:56 -05:00
return fantasy . NewTextErrorResponse ( err . Error ()), nil
}
2026-04-12 15:04:10 +01:00
// Persist the workspace binding on the chat
// immediately so the frontend can start streaming
// build logs while the build is still running.
// Note: this binding is intentional even if the build
// later fails. The checkExistingWorkspace recovery
// path handles failed workspaces by allowing
// re-creation.
2026-05-06 11:05:16 +01:00
updatedChat , err := db . UpdateChatWorkspaceBinding ( ctx , database . UpdateChatWorkspaceBindingParams {
ID : chatID ,
WorkspaceID : uuid . NullUUID {
UUID : workspace . ID ,
Valid : true ,
},
BuildID : uuid . NullUUID {
UUID : workspace . LatestBuild . ID ,
Valid : workspace . LatestBuild . ID != uuid . Nil ,
},
// AgentID is left null because the build hasn't
// completed yet. The chatd runtime binds it once
// the agent comes online.
AgentID : uuid . NullUUID {},
})
if err != nil {
options . Logger . Error ( ctx , "failed to persist chat workspace association" ,
slog . F ( "chat_id" , chatID ),
slog . F ( "workspace_id" , workspace . ID ),
slog . Error ( err ),
)
} else if options . OnChatUpdated != nil {
options . OnChatUpdated ( updatedChat )
2026-02-27 11:50:56 -05:00
}
2026-04-12 15:04:10 +01:00
// Wait for the build to complete and the agent to
// come online so subsequent tools can use the
// workspace immediately.
buildID := workspace . LatestBuild . ID
2026-04-15 11:39:05 +01:00
if buildID != uuid . Nil {
if err := waitForBuild ( ctx , db , buildID ); err != nil {
2026-05-07 15:01:58 +10:00
return buildFailureToolResponse (
ctx ,
options . Logger ,
db ,
ownerID ,
organizationID ,
buildFailureActionCreate ,
2026-04-12 15:04:10 +01:00
buildID ,
2026-05-07 15:01:58 +10:00
xerrors . Errorf ( "workspace build failed: %w" , err ),
), nil
2026-04-12 15:04:10 +01:00
}
}
2026-04-15 16:41:15 -04:00
2026-03-30 13:43:59 +02:00
result := map [ string ] any {
"created" : true ,
"workspace_name" : workspace . FullName (),
}
2026-04-12 15:04:10 +01:00
setBuildID ( result , buildID )
2026-03-30 13:43:59 +02:00
// Select the chat agent so follow-up tools wait on the
// intended workspace agent.
2026-05-08 13:51:13 +10:00
selectedAgent := database . WorkspaceAgent {}
2026-04-15 11:39:05 +01:00
agents , agentErr := db . GetWorkspaceAgentsInLatestBuildByWorkspaceID ( ctx , workspace . ID )
if agentErr == nil {
if len ( agents ) == 0 {
result [ "agent_status" ] = "no_agent"
} else {
selected , selectErr := agentselect . FindChatAgent ( agents )
if selectErr != nil {
result [ "agent_status" ] = "selection_error"
result [ "agent_error" ] = selectErr . Error ()
2026-03-30 13:43:59 +02:00
} else {
2026-05-08 13:51:13 +10:00
selectedAgent = selected
2026-03-30 13:43:59 +02:00
}
2026-02-27 11:50:56 -05:00
}
}
2026-03-05 09:42:12 +00:00
// Wait for the agent to come online and startup scripts to finish.
2026-05-08 13:51:13 +10:00
if selectedAgent . ID != uuid . Nil {
agentStatus := waitForAgentReady ( ctx , db , selectedAgent , options . AgentConnFn )
2026-03-05 09:42:12 +00:00
for k , v := range agentStatus {
result [ k ] = v
}
2026-02-27 11:50:56 -05:00
}
2026-04-15 19:18:54 -04:00
// Re-fire after the agent is fully ready so callers
// can load instruction files (AGENTS.md) from the
// running agent. This must happen after
// waitForAgentReady — firing earlier (e.g. right
// after waitForBuild) races with the agent startup
// and the connection usually times out before the
// agent is reachable.
if options . OnChatUpdated != nil {
2026-05-06 11:05:16 +01:00
if latest , err := db . GetChatByID ( ctx , chatID ); err == nil {
2026-04-15 19:18:54 -04:00
options . OnChatUpdated ( latest )
}
}
2026-03-30 13:43:59 +02:00
return toolResponse ( result ), nil
2026-03-05 09:42:12 +00:00
})
2026-02-27 11:50:56 -05:00
}
2026-04-12 15:04:10 +01:00
// existingWorkspaceResult holds the outcome of checking for an
// existing workspace on the chat.
type existingWorkspaceResult struct {
// Result is the tool response map when Done is true.
Result map [ string ] any
// Done indicates the caller should return early.
Done bool
2026-05-07 15:01:58 +10:00
// BuildAction, BuildID, and BuildErr are set together when
// waitForBuild failed, so the caller can render the build
// failure through the shared response path.
BuildAction buildFailureAction
BuildID uuid . UUID
BuildErr error
2026-04-12 15:04:10 +01:00
// Err is non-nil when the check itself failed.
Err error
}
2026-05-06 11:05:16 +01:00
// checkExistingWorkspace checks whether the given chat
2026-04-12 15:04:10 +01:00
// already has a usable workspace. Returns an
// existingWorkspaceResult with Done set when the caller should
// return early (workspace exists and is alive or building).
// Returns Done unset if the caller should proceed with creation
// (workspace is dead or missing).
2026-03-26 00:12:05 +11:00
func ( o CreateWorkspaceOptions ) checkExistingWorkspace (
2026-02-27 11:50:56 -05:00
ctx context . Context ,
2026-04-15 11:39:05 +01:00
db database . Store ,
2026-05-06 11:05:16 +01:00
chatID uuid . UUID ,
2026-04-12 15:04:10 +01:00
) existingWorkspaceResult {
2026-03-26 00:12:05 +11:00
agentConnFn := o . AgentConnFn
agentInactiveDisconnectTimeout := o . AgentInactiveDisconnectTimeout
2026-02-27 11:50:56 -05:00
chat , err := db . GetChatByID ( ctx , chatID )
if err != nil {
2026-04-12 15:04:10 +01:00
return existingWorkspaceResult { Err : xerrors . Errorf ( "load chat: %w" , err )}
2026-02-27 11:50:56 -05:00
}
if ! chat . WorkspaceID . Valid {
2026-04-12 15:04:10 +01:00
return existingWorkspaceResult {}
2026-02-27 11:50:56 -05:00
}
ws , err := db . GetWorkspaceByID ( ctx , chat . WorkspaceID . UUID )
if err != nil {
2026-04-12 15:04:10 +01:00
return existingWorkspaceResult { Err : xerrors . Errorf ( "load workspace: %w" , err )}
2026-02-27 11:50:56 -05:00
}
2026-03-12 09:09:17 -07:00
// Workspace was soft-deleted — allow creation.
if ws . Deleted {
2026-04-12 15:04:10 +01:00
return existingWorkspaceResult {}
2026-03-12 09:09:17 -07:00
}
2026-02-27 11:50:56 -05:00
// Check the latest build status.
build , err := db . GetLatestWorkspaceBuildByWorkspaceID ( ctx , ws . ID )
if err != nil {
// Can't determine status — allow creation.
2026-04-12 15:04:10 +01:00
return existingWorkspaceResult {}
2026-02-27 11:50:56 -05:00
}
job , err := db . GetProvisionerJobByID ( ctx , build . JobID )
if err != nil {
2026-04-12 15:04:10 +01:00
return existingWorkspaceResult {}
2026-02-27 11:50:56 -05:00
}
switch job . JobStatus {
case database . ProvisionerJobStatusPending ,
database . ProvisionerJobStatusRunning :
2026-04-12 15:04:10 +01:00
// Build is in progress. Publish the build ID so the
// frontend can start streaming logs, then wait.
updatedChat , bindErr := db . UpdateChatWorkspaceBinding ( ctx , database . UpdateChatWorkspaceBindingParams {
2026-05-06 11:05:16 +01:00
ID : chatID ,
2026-04-12 15:04:10 +01:00
WorkspaceID : uuid . NullUUID { UUID : ws . ID , Valid : true },
BuildID : uuid . NullUUID {
UUID : build . ID ,
Valid : build . ID != uuid . Nil ,
},
AgentID : uuid . NullUUID {},
})
if bindErr != nil {
o . Logger . Error ( ctx , "failed to persist build ID on chat binding" ,
2026-05-06 11:05:16 +01:00
slog . F ( "chat_id" , chatID ),
2026-04-12 15:04:10 +01:00
slog . F ( "build_id" , build . ID ),
slog . Error ( bindErr ),
2026-02-27 11:50:56 -05:00
)
2026-04-12 15:04:10 +01:00
} else if o . OnChatUpdated != nil {
o . OnChatUpdated ( updatedChat )
}
if err := waitForBuild ( ctx , db , build . ID ); err != nil {
2026-05-07 15:01:58 +10:00
action := buildFailureActionCreate
if build . Transition == database . WorkspaceTransitionStart {
action = buildFailureActionStart
}
2026-04-12 15:04:10 +01:00
return existingWorkspaceResult {
2026-05-07 15:01:58 +10:00
BuildAction : action ,
BuildID : build . ID ,
BuildErr : xerrors . Errorf ( "existing workspace build failed: %w" , err ),
2026-04-12 15:04:10 +01:00
}
2026-02-27 11:50:56 -05:00
}
2026-03-05 09:42:12 +00:00
result := map [ string ] any {
2026-02-27 11:50:56 -05:00
"created" : false ,
"workspace_name" : ws . Name ,
"status" : "already_exists" ,
2026-03-05 09:42:12 +00:00
"message" : "workspace build completed" ,
}
2026-04-12 15:04:10 +01:00
setBuildID ( result , build . ID )
2026-03-05 09:42:12 +00:00
agents , agentsErr := db . GetWorkspaceAgentsInLatestBuildByWorkspaceID ( ctx , ws . ID )
if agentsErr == nil && len ( agents ) > 0 {
2026-03-30 13:43:59 +02:00
selected , selectErr := agentselect . FindChatAgent ( agents )
if selectErr != nil {
o . Logger . Debug ( ctx , "agent selection failed, falling back to first agent for readiness check" ,
slog . F ( "workspace_id" , ws . ID ),
slog . Error ( selectErr ),
)
selected = agents [ 0 ]
}
2026-05-08 13:51:13 +10:00
for k , v := range waitForAgentReady ( ctx , db , selected , agentConnFn ) {
2026-03-05 09:42:12 +00:00
result [ k ] = v
}
}
2026-04-12 15:04:10 +01:00
return existingWorkspaceResult { Result : result , Done : true }
2026-02-27 11:50:56 -05:00
case database . ProvisionerJobStatusSucceeded :
2026-03-05 10:34:24 -05:00
// If the workspace was stopped, tell the model to use
// start_workspace instead of creating a new one.
if build . Transition == database . WorkspaceTransitionStop {
2026-04-12 15:04:10 +01:00
return existingWorkspaceResult { Result : map [ string ] any {
2026-03-05 10:34:24 -05:00
"created" : false ,
"workspace_name" : ws . Name ,
"status" : "stopped" ,
"message" : "workspace is stopped; use start_workspace to start it" ,
2026-04-12 15:04:10 +01:00
}, Done : true }
2026-03-05 10:34:24 -05:00
}
2026-03-26 00:12:05 +11:00
// Build succeeded — use the agent's recent DB-backed
// connection status to decide whether the workspace is
// still usable.
2026-02-28 16:46:51 -05:00
agents , agentsErr := db . GetWorkspaceAgentsInLatestBuildByWorkspaceID ( ctx , ws . ID )
2026-03-26 00:12:05 +11:00
if agentsErr == nil && len ( agents ) > 0 {
2026-03-30 13:43:59 +02:00
selected , selectErr := agentselect . FindChatAgent ( agents )
if selectErr != nil {
o . Logger . Debug ( ctx , "agent selection failed, falling back to first agent for status check" ,
slog . F ( "workspace_id" , ws . ID ),
slog . Error ( selectErr ),
)
selected = agents [ 0 ]
}
2026-04-14 22:23:06 -07:00
status := selected . Status ( dbtime . Now (), agentInactiveDisconnectTimeout )
2026-03-26 00:12:05 +11:00
result := map [ string ] any {
"created" : false ,
"workspace_name" : ws . Name ,
"status" : "already_exists" ,
}
switch status . Status {
case database . WorkspaceAgentStatusConnected :
result [ "message" ] = "workspace is already running and recently connected"
2026-05-08 13:51:13 +10:00
for k , v := range waitForAgentReady ( ctx , db , selected , nil ) {
2026-03-05 09:42:12 +00:00
result [ k ] = v
}
2026-04-12 15:04:10 +01:00
return existingWorkspaceResult { Result : result , Done : true }
2026-03-26 00:12:05 +11:00
case database . WorkspaceAgentStatusConnecting :
result [ "message" ] = "workspace exists and the agent is still connecting"
2026-05-08 13:51:13 +10:00
for k , v := range waitForAgentReady ( ctx , db , selected , agentConnFn ) {
2026-03-26 00:12:05 +11:00
result [ k ] = v
}
2026-04-12 15:04:10 +01:00
return existingWorkspaceResult { Result : result , Done : true }
2026-03-26 00:12:05 +11:00
case database . WorkspaceAgentStatusDisconnected ,
database . WorkspaceAgentStatusTimeout :
2026-03-30 13:43:59 +02:00
// Agent is offline or never became ready - allow
2026-03-26 00:12:05 +11:00
// creation.
2026-02-27 11:50:56 -05:00
}
}
2026-03-26 00:12:05 +11:00
// No agent ID or no agent status — allow creation.
2026-04-12 15:04:10 +01:00
return existingWorkspaceResult {}
2026-02-27 11:50:56 -05:00
default :
// Failed, canceled, etc — allow creation.
2026-04-12 15:04:10 +01:00
return existingWorkspaceResult {}
2026-02-27 11:50:56 -05:00
}
}
2026-04-12 15:04:10 +01:00
// waitForBuild polls the specified build until its provisioner job
2026-02-27 11:50:56 -05:00
// completes or the context expires.
func waitForBuild (
ctx context . Context ,
db database . Store ,
2026-04-12 15:04:10 +01:00
buildID uuid . UUID ,
2026-02-27 11:50:56 -05:00
) error {
buildCtx , cancel := context . WithTimeout ( ctx , buildTimeout )
defer cancel ()
ticker := time . NewTicker ( buildPollInterval )
defer ticker . Stop ()
for {
2026-04-12 15:04:10 +01:00
build , err := db . GetWorkspaceBuildByID ( buildCtx , buildID )
2026-02-27 11:50:56 -05:00
if err != nil {
2026-04-12 15:04:10 +01:00
return xerrors . Errorf ( "get build: %w" , err )
2026-02-27 11:50:56 -05:00
}
job , err := db . GetProvisionerJobByID ( buildCtx , build . JobID )
if err != nil {
return xerrors . Errorf ( "get provisioner job: %w" , err )
}
switch job . JobStatus {
case database . ProvisionerJobStatusSucceeded :
return nil
case database . ProvisionerJobStatusFailed :
errMsg := "build failed"
if job . Error . Valid {
errMsg = job . Error . String
}
2026-05-07 15:01:58 +10:00
var code codersdk . JobErrorCode
if job . ErrorCode . Valid {
code = codersdk . JobErrorCode ( job . ErrorCode . String )
}
return & workspaceBuildError { message : errMsg , code : code }
2026-02-27 11:50:56 -05:00
case database . ProvisionerJobStatusCanceled :
return xerrors . New ( "build was canceled" )
case database . ProvisionerJobStatusPending ,
database . ProvisionerJobStatusRunning ,
database . ProvisionerJobStatusCanceling :
// Still in progress — keep waiting.
default :
return xerrors . Errorf ( "unexpected job status: %s" , job . JobStatus )
}
select {
case <- buildCtx . Done ():
return xerrors . Errorf (
"timed out waiting for workspace build: %w" ,
buildCtx . Err (),
)
case <- ticker . C :
}
}
}
2026-05-08 13:51:13 +10:00
func templateHasExternalAgent (
ctx context . Context ,
db database . Store ,
tmpl database . Template ,
) ( bool , error ) {
version , err := db . GetTemplateVersionByID ( ctx , tmpl . ActiveVersionID )
if err != nil {
if errors . Is ( err , sql . ErrNoRows ) {
return false , nil
}
return false , err
}
return version . HasExternalAgent . Valid && version . HasExternalAgent . Bool , nil
}
// externalAgentReadyError returns the external-agent-specific error
// message when agent belongs to an external resource, or the empty
// string otherwise. Errors looking up the resource are treated as
// non-external so the caller falls back to the dial error.
func externalAgentReadyError (
ctx context . Context ,
db database . Store ,
agent database . WorkspaceAgent ,
) string {
isExternal , err := IsExternalWorkspaceAgent ( ctx , db , agent )
if err != nil || ! isExternal {
return ""
}
return ExternalAgentUnavailableMessage ( agent )
}
2026-03-05 09:42:12 +00:00
// waitForAgentReady waits for the workspace agent to become
// reachable and for its startup scripts to finish. It returns
// status fields suitable for merging into a tool response.
func waitForAgentReady (
2026-02-27 11:50:56 -05:00
ctx context . Context ,
2026-03-05 09:42:12 +00:00
db database . Store ,
2026-05-08 13:51:13 +10:00
agent database . WorkspaceAgent ,
2026-03-05 09:42:12 +00:00
agentConnFn AgentConnFunc ,
) map [ string ] any {
result := map [ string ] any {}
2026-05-08 13:51:13 +10:00
agentID := agent . ID
2026-02-27 11:50:56 -05:00
2026-03-05 09:42:12 +00:00
// Phase 1: retry connecting to the agent.
if agentConnFn != nil {
agentCtx , agentCancel := context . WithTimeout ( ctx , agentConnectTimeout )
defer agentCancel ()
2026-02-27 11:50:56 -05:00
2026-03-05 09:42:12 +00:00
ticker := time . NewTicker ( agentRetryInterval )
defer ticker . Stop ()
2026-02-27 11:50:56 -05:00
2026-03-05 09:42:12 +00:00
var lastErr error
for {
attemptCtx , attemptCancel := context . WithTimeout ( agentCtx , agentAttemptTimeout )
2026-06-12 13:33:12 +02:00
_ , release , err := agentConnFn ( attemptCtx , agentID )
2026-03-05 09:42:12 +00:00
attemptCancel ()
if err == nil {
release ()
break
}
lastErr = err
select {
case <- agentCtx . Done ():
result [ "agent_status" ] = "not_ready"
2026-05-08 13:51:13 +10:00
// External agents may need user action on a different
// host. Surface that guidance instead of the raw dial
// error after the retry window has elapsed. The retry
// loop itself is unchanged, so a Connecting external
// agent still gets the full window to come online.
if msg := externalAgentReadyError ( ctx , db , agent ); msg != "" {
result [ "agent_error" ] = msg
} else {
result [ "agent_error" ] = lastErr . Error ()
}
2026-03-05 09:42:12 +00:00
return result
case <- ticker . C :
}
2026-02-27 11:50:56 -05:00
}
}
2026-03-05 09:42:12 +00:00
// Phase 2: poll lifecycle until startup scripts finish.
2026-05-06 11:05:16 +01:00
scriptCtx , scriptCancel := context . WithTimeout ( ctx , startupScriptTimeout )
defer scriptCancel ()
2026-03-05 09:42:12 +00:00
2026-05-06 11:05:16 +01:00
ticker := time . NewTicker ( startupScriptPollInterval )
defer ticker . Stop ()
2026-03-05 09:42:12 +00:00
2026-05-06 11:05:16 +01:00
var lastState database . WorkspaceAgentLifecycleState
for {
row , err := db . GetWorkspaceAgentLifecycleStateByID ( scriptCtx , agentID )
if err == nil {
lastState = row . LifecycleState
switch lastState {
case database . WorkspaceAgentLifecycleStateCreated ,
database . WorkspaceAgentLifecycleStateStarting :
// Still in progress, keep polling.
case database . WorkspaceAgentLifecycleStateReady :
return result
default :
// Terminal non-ready state.
result [ "startup_scripts" ] = "startup_scripts_failed"
result [ "lifecycle_state" ] = string ( lastState )
2026-03-05 09:42:12 +00:00
return result
}
}
2026-05-06 11:05:16 +01:00
select {
case <- scriptCtx . Done ():
if errors . Is ( scriptCtx . Err (), context . DeadlineExceeded ) {
result [ "startup_scripts" ] = "startup_scripts_timeout"
} else {
result [ "startup_scripts" ] = "startup_scripts_unknown"
}
return result
case <- ticker . C :
}
}
2026-02-27 11:50:56 -05:00
}
2026-06-01 23:31:25 +10:00
func createWorkspaceWithNameRetry (
ctx context . Context ,
ownerID uuid . UUID ,
req codersdk . CreateWorkspaceRequest ,
createFn CreateWorkspaceFn ,
) ( codersdk . Workspace , error ) {
workspace , err := createFn ( ctx , ownerID , req )
if err == nil {
return workspace , nil
}
if ! isWorkspaceNameConflict ( err ) {
return codersdk . Workspace {}, err
}
req . Name = generatedWorkspaceName ( req . Name )
return createFn ( ctx , ownerID , req )
}
func isWorkspaceNameConflict ( err error ) bool {
responseErr , ok := httperror . IsResponder ( err )
if ! ok {
return false
}
status , resp := responseErr . Response ()
if status != http . StatusConflict {
return false
}
for _ , validation := range resp . Validations {
if validation . Field == "name" {
return true
}
}
return false
}
2026-02-27 11:50:56 -05:00
func generatedWorkspaceName ( seed string ) string {
base := codersdk . UsernameFrom ( strings . TrimSpace ( strings . ToLower ( seed )))
if strings . TrimSpace ( base ) == "" {
base = "workspace"
}
suffix := strings . ReplaceAll ( uuid . NewString (), "-" , "" )[: 4 ]
if len ( base ) > 27 {
base = strings . Trim ( base [: 27 ], "-" )
}
if base == "" {
base = "workspace"
}
name := fmt . Sprintf ( "%s-%s" , base , suffix )
if err := codersdk . NameValid ( name ); err == nil {
return name
}
return namesgenerator . NameDigitWith ( "-" )
}