Skip to content

Commit 0a47fd1

Browse files
committed
fix(cli)!: select sub agent if available and error on multiple agents
In the past we randomly selected workspace agent if there were multiple. Unless both are running on the same machine with the same configuration, this would be very confusing behavior for a user. With the introduction of sub agents (devcontainer agents), it was decided prioritize them if present. Similarly as before, selecting a devcontainer randomly would be confusing. We now error out if the agent name is not specified and there are multiple agents. Fixes coder/internal#696
1 parent 5e3a225 commit 0a47fd1

File tree

1 file changed

+19
-16
lines changed

1 file changed

+19
-16
lines changed

cli/ssh.go

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -926,35 +926,38 @@ func getWorkspaceAgent(workspace codersdk.Workspace, agentName string) (workspac
926926
resources := workspace.LatestBuild.Resources
927927

928928
agents := make([]codersdk.WorkspaceAgent, 0)
929+
subAgents := make([]codersdk.WorkspaceAgent, 0)
929930
for _, resource := range resources {
930-
agents = append(agents, resource.Agents...)
931+
for _, agent := range resource.Agents {
932+
if agent.ParentID.UUID == uuid.Nil {
933+
agents = append(agents, agent)
934+
} else {
935+
subAgents = append(subAgents, agent)
936+
}
937+
}
931938
}
932939
if len(agents) == 0 {
933940
return codersdk.WorkspaceAgent{}, xerrors.Errorf("workspace %q has no agents", workspace.Name)
934941
}
935942
if agentName != "" {
943+
agents = append(agents, subAgents...)
936944
for _, otherAgent := range agents {
937945
if otherAgent.Name != agentName {
938946
continue
939947
}
940-
workspaceAgent = otherAgent
941-
break
942-
}
943-
if workspaceAgent.ID == uuid.Nil {
944-
return codersdk.WorkspaceAgent{}, xerrors.Errorf("agent not found by name %q", agentName)
948+
return otherAgent, nil
945949
}
950+
return codersdk.WorkspaceAgent{}, xerrors.Errorf("agent not found by name %q", agentName)
946951
}
947-
if workspaceAgent.ID == uuid.Nil {
948-
if len(agents) > 1 {
949-
workspaceAgent, err = cryptorand.Element(agents)
950-
if err != nil {
951-
return codersdk.WorkspaceAgent{}, err
952-
}
953-
} else {
954-
workspaceAgent = agents[0]
955-
}
952+
if len(subAgents) == 1 {
953+
return subAgents[0], nil
954+
} else if len(subAgents) > 1 {
955+
return codersdk.WorkspaceAgent{}, xerrors.New("multiple sub-agents found, please specify the agent name")
956+
}
957+
if len(agents) == 1 {
958+
return agents[0], nil
956959
}
957-
return workspaceAgent, nil
960+
return codersdk.WorkspaceAgent{}, xerrors.New("multiple agents found, please specify the agent name")
958961
}
959962

960963
// Attempt to poll workspace autostop. We write a per-workspace lockfile to

0 commit comments

Comments
 (0)