Skip to content

feat(agent/agentcontainers): auto detect dev containers #18950

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 13 commits into from
Jul 22, 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
Next Next commit
feat(agent/agentcontainers): auto detect dev containers
  • Loading branch information
DanielleMaywood committed Jul 16, 2025
commit f528eb33526bef34ca0a469a5ecfc6fe48dd0dfa
2 changes: 1 addition & 1 deletion agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -1168,7 +1168,7 @@ func (a *agent) handleManifest(manifestOK *checkpoint) func(ctx context.Context,
// return existing devcontainers but actual container detection
// and creation will be deferred.
a.containerAPI.Init(
agentcontainers.WithManifestInfo(manifest.OwnerName, manifest.WorkspaceName, manifest.AgentName),
agentcontainers.WithManifestInfo(manifest.OwnerName, manifest.WorkspaceName, manifest.AgentName, manifest.Directory),
agentcontainers.WithDevcontainers(manifest.Devcontainers, manifest.Scripts),
agentcontainers.WithSubAgentClient(agentcontainers.NewSubAgentClientFromAPI(a.logger, aAPI)),
)
Expand Down
98 changes: 94 additions & 4 deletions agent/agentcontainers/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"encoding/json"
"errors"
"fmt"
"io/fs"
"maps"
"net/http"
"os"
Expand All @@ -21,6 +22,7 @@ import (
"github.com/fsnotify/fsnotify"
"github.com/go-chi/chi/v5"
"github.com/google/uuid"
"github.com/spf13/afero"
"golang.org/x/xerrors"

"cdr.dev/slog"
Expand Down Expand Up @@ -60,6 +62,7 @@ type API struct {
updateInterval time.Duration // Interval for periodic container updates.
logger slog.Logger
watcher watcher.Watcher
fs afero.Fs
execer agentexec.Execer
commandEnv CommandEnv
ccli ContainerCLI
Expand All @@ -71,9 +74,10 @@ type API struct {
subAgentURL string
subAgentEnv []string

ownerName string
workspaceName string
parentAgent string
ownerName string
workspaceName string
parentAgent string
agentDirectory string

mu sync.RWMutex // Protects the following fields.
initDone chan struct{} // Closed by Init.
Expand Down Expand Up @@ -192,11 +196,12 @@ func WithSubAgentEnv(env ...string) Option {

// WithManifestInfo sets the owner name, and workspace name
// for the sub-agent.
func WithManifestInfo(owner, workspace, parentAgent string) Option {
func WithManifestInfo(owner, workspace, parentAgent, agentDirectory string) Option {
return func(api *API) {
api.ownerName = owner
api.workspaceName = workspace
api.parentAgent = parentAgent
api.agentDirectory = agentDirectory
}
}

Expand Down Expand Up @@ -261,6 +266,13 @@ func WithWatcher(w watcher.Watcher) Option {
}
}

// WithFileSystem sets the file system used for discovering projects.
func WithFileSystem(fs afero.Fs) Option {
return func(api *API) {
api.fs = fs
}
}

// ScriptLogger is an interface for sending devcontainer logs to the
// controlplane.
type ScriptLogger interface {
Expand Down Expand Up @@ -331,6 +343,9 @@ func NewAPI(logger slog.Logger, options ...Option) *API {
api.watcher = watcher.NewNoop()
}
}
if api.fs == nil {
api.fs = afero.NewOsFs()
}
if api.subAgentClient.Load() == nil {
var c SubAgentClient = noopSubAgentClient{}
api.subAgentClient.Store(&c)
Expand Down Expand Up @@ -375,10 +390,85 @@ func (api *API) Start() {
api.watcherDone = make(chan struct{})
api.updaterDone = make(chan struct{})

go func() {
if err := api.discoverDevcontainerProjects(); err != nil {
api.logger.Error(api.ctx, "discovering dev container projects", slog.Error(err))
}
}()

go api.watcherLoop()
go api.updaterLoop()
}

func (api *API) discoverDevcontainerProjects() error {
isGitProject, err := afero.DirExists(api.fs, filepath.Join(api.agentDirectory, "/.git"))
if err != nil {
return xerrors.Errorf(".git dir exists: %w", err)
}

// If the agent directory is a git project, we'll search
// the project for any `.devcontainer/devcontainer.json`
// files.
if isGitProject {
return api.discoverDevcontainersInProject(api.agentDirectory)
}

// The agent directory is _not_ a git project, so we'll
// search the top level of the agent directory for any
// git projects, and search those.
entries, err := afero.ReadDir(api.fs, api.agentDirectory)
if err != nil {
return xerrors.Errorf("read agent directory: %w", err)
}

for _, entry := range entries {
if !entry.IsDir() {
continue
}

isGitProject, err = afero.DirExists(api.fs, filepath.Join(api.agentDirectory, entry.Name(), ".git"))
if err != nil {
return xerrors.Errorf(".git dir exists: %w", err)
}

// If this directory is a git project, we'll search
// it for any `.devcontainer/devcontainer.json` files.
if isGitProject {
if err := api.discoverDevcontainersInProject(filepath.Join(api.agentDirectory, entry.Name())); err != nil {
return err
}
}
}

return nil
}

func (api *API) discoverDevcontainersInProject(projectPath string) error {
return afero.Walk(api.fs, projectPath, func(path string, info fs.FileInfo, err error) error {
if strings.HasSuffix(path, ".devcontainer/devcontainer.json") {
workspaceFolder := strings.TrimSuffix(path, ".devcontainer/devcontainer.json")

api.mu.Lock()
if _, found := api.knownDevcontainers[workspaceFolder]; !found {
dc := codersdk.WorkspaceAgentDevcontainer{
ID: uuid.New(),
Name: "", // Updated later based on container state.
WorkspaceFolder: workspaceFolder,
ConfigPath: path,
Status: "", // Updated later based on container state.
Dirty: false, // Updated later based on config file changes.
Container: nil,
}

api.knownDevcontainers[workspaceFolder] = dc
}
api.mu.Unlock()
}

return nil
})
}

func (api *API) watcherLoop() {
defer close(api.watcherDone)
defer api.logger.Debug(api.ctx, "watcher loop stopped")
Expand Down
4 changes: 2 additions & 2 deletions agent/agentcontainers/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1678,7 +1678,7 @@ func TestAPI(t *testing.T) {
agentcontainers.WithSubAgentClient(fakeSAC),
agentcontainers.WithSubAgentURL("test-subagent-url"),
agentcontainers.WithDevcontainerCLI(fakeDCCLI),
agentcontainers.WithManifestInfo("test-user", "test-workspace", "test-parent-agent"),
agentcontainers.WithManifestInfo("test-user", "test-workspace", "test-parent-agent", "/parent-agent"),
)
api.Start()
apiClose := func() {
Expand Down Expand Up @@ -2662,7 +2662,7 @@ func TestAPI(t *testing.T) {
agentcontainers.WithSubAgentClient(fSAC),
agentcontainers.WithSubAgentURL("test-subagent-url"),
agentcontainers.WithWatcher(watcher.NewNoop()),
agentcontainers.WithManifestInfo("test-user", "test-workspace", "test-parent-agent"),
agentcontainers.WithManifestInfo("test-user", "test-workspace", "test-parent-agent", "/parent-agent"),
)
api.Start()
defer api.Close()
Expand Down
7 changes: 5 additions & 2 deletions site/src/modules/resources/AgentDevcontainerCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,8 @@ export const AgentDevcontainerCard: FC<AgentDevcontainerCardProps> = ({

const appsClasses = "flex flex-wrap gap-4 empty:hidden md:justify-start";

console.log(devcontainer);

return (
<Stack
key={devcontainer.id}
Expand Down Expand Up @@ -218,7 +220,8 @@ export const AgentDevcontainerCard: FC<AgentDevcontainerCardProps> = ({
text-sm font-semibold text-content-primary
md:overflow-visible"
>
{subAgent?.name ?? devcontainer.name}
{subAgent?.name ??
(devcontainer.name || devcontainer.config_path)}
{devcontainer.container && (
<span className="text-content-tertiary">
{" "}
Expand Down Expand Up @@ -253,7 +256,7 @@ export const AgentDevcontainerCard: FC<AgentDevcontainerCardProps> = ({
disabled={devcontainer.status === "starting"}
>
<Spinner loading={devcontainer.status === "starting"} />
Rebuild
{devcontainer.container === undefined ? <>Start</> : <>Rebuild</>}
</Button>

{showDevcontainerControls && displayApps.includes("ssh_helper") && (
Expand Down