feat: discover ACP harnesses configured in the workspace (#30557)
Discovers ACP harnesses configured in `~/.coder/acp/*.json`, validates their configuration, and refreshes the cached catalog every 30 seconds. Exposes harness names and configuration errors through the agent API and workspace SDK. Generated with Codex. Carefully reviewed by Hugo.
This commit is contained in:
1 parent
bd1b10673f
commit
bf5dda330c
12 files changed
+626
No files matched your search
@@ -54,6 +54,7 @@ import (
|
||||
"github.com/coder/coder/v2/agent/proto/resourcesmonitor"
|
||||
"github.com/coder/coder/v2/agent/reconnectingpty"
|
||||
"github.com/coder/coder/v2/agent/usershell"
|
||||
"github.com/coder/coder/v2/agent/x/agentacp"
|
||||
"github.com/coder/coder/v2/agent/x/agentdesktop"
|
||||
"github.com/coder/coder/v2/agent/x/agentmcp"
|
||||
"github.com/coder/coder/v2/buildinfo"
|
||||
@@ -346,6 +347,8 @@ type agent struct {
|
||||
toolCalls *agenttoolcall.Table
|
||||
desktopAPI *agentdesktop.API
|
||||
mcpManager *agentmcp.Manager
|
||||
acpManager *agentacp.Manager
|
||||
acpAPI *agentacp.API
|
||||
mcpAPI *agentmcp.API
|
||||
contextConfigAPI *agentcontextconfig.API
|
||||
contextManager *agentcontext.Manager
|
||||
@@ -462,6 +465,8 @@ func (a *agent) init() {
|
||||
)
|
||||
a.desktopAPI = agentdesktop.NewAPI(a.logger.Named("desktop"), desktop, a.clock)
|
||||
a.mcpManager = agentmcp.NewManager(a.gracefulCtx, a.logger.Named("mcp"), a.execer, a.filesystem, a.envInfo, a.updateCommandEnv, workingDirFn)
|
||||
a.acpManager = agentacp.NewManager(a.gracefulCtx, agentacp.Options{Logger: a.logger.Named("acp"), Clock: a.clock, Filesystem: a.filesystem, EnvInfo: a.envInfo})
|
||||
a.acpAPI = agentacp.NewAPI(a.acpManager)
|
||||
a.contextConfigAPI = agentcontextconfig.NewAPI(workingDirFn, a.contextConfig)
|
||||
a.mcpAPI = agentmcp.NewAPI(a.mcpManager)
|
||||
|
||||
@@ -1392,6 +1397,7 @@ func (a *agent) handleManifest(manifestOK *checkpoint) func(ctx context.Context,
|
||||
// re-trigger a push once up, so we don't block readiness
|
||||
// on them.
|
||||
a.contextManager.SetReady()
|
||||
a.acpManager.RunDiscovery()
|
||||
|
||||
// Connect to workspace MCP servers after the
|
||||
// lifecycle transition to avoid delaying Ready.
|
||||
@@ -2298,6 +2304,9 @@ func (a *agent) Close() error {
|
||||
a.logger.Error(a.hardCtx, "desktop API close", slog.Error(err))
|
||||
}
|
||||
|
||||
if err := a.acpManager.Close(); err != nil {
|
||||
a.logger.Error(a.hardCtx, "close ACP manager", slog.Error(err))
|
||||
}
|
||||
if err := a.mcpManager.Close(); err != nil {
|
||||
a.logger.Error(a.hardCtx, "mcp manager close", slog.Error(err))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
package agent_test
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/coder/coder/v2/agent"
|
||||
"github.com/coder/coder/v2/agent/agenttest"
|
||||
"github.com/coder/coder/v2/agent/usershell"
|
||||
"github.com/coder/coder/v2/codersdk/agentsdk"
|
||||
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
)
|
||||
|
||||
type acpEnvInfo struct {
|
||||
usershell.SystemEnvInfo
|
||||
home string
|
||||
}
|
||||
|
||||
func (e acpEnvInfo) HomeDir() (string, error) { return e.home, nil }
|
||||
|
||||
func TestAgent_ACPInterface(t *testing.T) {
|
||||
t.Parallel()
|
||||
home, dir := t.TempDir(), t.TempDir()
|
||||
configDir := filepath.Join(home, ".coder", "acp")
|
||||
require.NoError(t, os.MkdirAll(configDir, 0o700))
|
||||
require.NoError(t, os.WriteFile(filepath.Join(configDir, "broken.json"), []byte(`{"command":"false"}`), 0o600))
|
||||
//nolint:dogsled // The integration fixture also returns unrelated transports.
|
||||
conn, _, _, _, _ := setupAgent(t, agentsdk.Manifest{Directory: dir}, 0, func(_ *agenttest.Client, opts *agent.Options) {
|
||||
opts.EnvInfo = acpEnvInfo{home: home}
|
||||
opts.Filesystem = afero.NewOsFs()
|
||||
})
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
_, err := conn.ListACPHarnesses(ctx)
|
||||
require.NoError(t, err)
|
||||
var catalog []workspacesdk.ACPHarness
|
||||
require.Eventually(t, func() bool { catalog, err = conn.ListACPHarnesses(ctx); return err == nil && len(catalog) == 1 }, testutil.WaitLong, testutil.IntervalFast)
|
||||
require.Equal(t, "broken", catalog[0].Slug)
|
||||
}
|
||||
@@ -41,6 +41,7 @@ func (a *agent) apiHandler(upgradeListener *httpUpgrader) http.Handler {
|
||||
r.Mount("/api/v0/tool-calls", a.toolCalls.Routes())
|
||||
r.Mount("/api/v0/desktop", a.desktopAPI.Routes())
|
||||
r.Mount("/api/v0/mcp", a.mcpAPI.Routes())
|
||||
r.Mount("/api/v0/acp", a.acpAPI.Routes())
|
||||
r.Mount("/api/v0/context-config", a.contextConfigAPI.Routes())
|
||||
if a.contextAPI != nil {
|
||||
r.Mount("/api/v0/context", a.contextAPI.Routes())
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package agentacp
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"github.com/coder/coder/v2/coderd/httpapi"
|
||||
)
|
||||
|
||||
// API serves the agent-local ACP harness catalog.
|
||||
type API struct{ manager *Manager }
|
||||
|
||||
// NewAPI constructs the agent-local HTTP API.
|
||||
func NewAPI(m *Manager) *API { return &API{manager: m} }
|
||||
|
||||
// Routes returns handlers mounted under /api/v0/acp.
|
||||
func (api *API) Routes() http.Handler {
|
||||
r := chi.NewRouter()
|
||||
r.Get("/harnesses", func(w http.ResponseWriter, r *http.Request) {
|
||||
httpapi.Write(r.Context(), w, http.StatusOK, api.manager.Catalog())
|
||||
})
|
||||
return r
|
||||
}
|
||||
@@ -0,0 +1,165 @@
|
||||
package agentacp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"maps"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"cdr.dev/slog/v3"
|
||||
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
||||
)
|
||||
|
||||
const (
|
||||
discoveryInterval = 30 * time.Second
|
||||
reloadTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
type harnessConfig struct {
|
||||
slug, displayName, command string
|
||||
hash [32]byte
|
||||
}
|
||||
|
||||
type configFile struct {
|
||||
DisplayName string `json:"display_name"`
|
||||
Command string `json:"command"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
}
|
||||
|
||||
// Catalog returns an immutable copy of the cached discovery results.
|
||||
func (m *Manager) Catalog() []workspacesdk.ACPHarness {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
return m.catalogLocked()
|
||||
}
|
||||
|
||||
func (m *Manager) catalogLocked() []workspacesdk.ACPHarness {
|
||||
out := slices.Clone(m.catalog)
|
||||
if out == nil {
|
||||
out = []workspacesdk.ACPHarness{}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// Reload discovers and validates immediate harness configuration files.
|
||||
func (m *Manager) Reload(ctx context.Context) error {
|
||||
m.mu.Lock()
|
||||
if m.closed {
|
||||
m.mu.Unlock()
|
||||
return ErrManagerClosed
|
||||
}
|
||||
m.wg.Add(1)
|
||||
m.mu.Unlock()
|
||||
defer m.wg.Done()
|
||||
return m.discover(ctx)
|
||||
}
|
||||
|
||||
func (m *Manager) discover(ctx context.Context) error {
|
||||
m.reloadMu.Lock()
|
||||
defer m.reloadMu.Unlock()
|
||||
home, err := m.envInfo.HomeDir()
|
||||
if err != nil {
|
||||
return xerrors.Errorf("resolve ACP configuration directory: %w", err)
|
||||
}
|
||||
configDir := filepath.Join(home, ".coder", "acp")
|
||||
entries, err := afero.ReadDir(m.fs, configDir)
|
||||
if err != nil && !errors.Is(err, os.ErrNotExist) {
|
||||
return err
|
||||
}
|
||||
configs := make(map[string]harnessConfig)
|
||||
hashes := make(map[string][32]byte)
|
||||
catalog := []workspacesdk.ACPHarness{}
|
||||
for _, entry := range entries {
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
if !entry.Mode().IsRegular() || !strings.HasSuffix(entry.Name(), ".json") {
|
||||
continue
|
||||
}
|
||||
slug := strings.TrimSuffix(entry.Name(), ".json")
|
||||
if slug == "" {
|
||||
continue
|
||||
}
|
||||
h := workspacesdk.ACPHarness{Slug: slug, DisplayName: slug}
|
||||
{
|
||||
raw, err := afero.ReadFile(m.fs, filepath.Join(configDir, entry.Name()))
|
||||
hashes[slug] = sha256.Sum256(raw)
|
||||
if err != nil {
|
||||
h.Error = "cannot read harness configuration"
|
||||
goto appendHarness
|
||||
}
|
||||
var file configFile
|
||||
if err := json.Unmarshal(raw, &file); err != nil {
|
||||
h.Error = "invalid harness configuration JSON"
|
||||
goto appendHarness
|
||||
}
|
||||
if file.Enabled != nil && !*file.Enabled {
|
||||
continue
|
||||
}
|
||||
if strings.TrimSpace(file.Command) == "" {
|
||||
h.Error = "harness command is required"
|
||||
goto appendHarness
|
||||
}
|
||||
if file.DisplayName != "" {
|
||||
h.DisplayName = file.DisplayName
|
||||
}
|
||||
canonical, err := json.Marshal(file)
|
||||
if err != nil {
|
||||
return xerrors.Errorf("marshal ACP harness configuration %q: %w", slug, err)
|
||||
}
|
||||
cfg := harnessConfig{slug: slug, displayName: h.DisplayName, command: file.Command, hash: sha256.Sum256(canonical)}
|
||||
configs[slug] = cfg
|
||||
hashes[slug] = cfg.hash
|
||||
}
|
||||
appendHarness:
|
||||
catalog = append(catalog, h)
|
||||
}
|
||||
slices.SortFunc(catalog, func(a, b workspacesdk.ACPHarness) int { return strings.Compare(a.Slug, b.Slug) })
|
||||
m.mu.Lock()
|
||||
changed := !slices.Equal(m.catalog, catalog) || !maps.Equal(m.configs, configs) || !maps.Equal(m.configHashes, hashes) || m.configDir != configDir
|
||||
m.configs, m.catalog, m.configHashes = configs, catalog, hashes
|
||||
m.configDir = configDir
|
||||
callback := m.onChange
|
||||
m.mu.Unlock()
|
||||
if changed && callback != nil {
|
||||
callback()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RunDiscovery starts filesystem discovery once and returns immediately.
|
||||
// It scans immediately and polls for configuration changes every 30 seconds.
|
||||
func (m *Manager) RunDiscovery() {
|
||||
m.runOnce.Do(func() { m.run(m.pollDiscovery) })
|
||||
}
|
||||
|
||||
func (m *Manager) pollDiscovery() {
|
||||
reload := func() {
|
||||
ctx, cancel := context.WithTimeout(m.ctx, reloadTimeout)
|
||||
defer cancel()
|
||||
if err := m.Reload(ctx); err != nil {
|
||||
m.logger.Warn(m.ctx, "acp discovery failed", slog.Error(err))
|
||||
}
|
||||
}
|
||||
reload()
|
||||
timer := m.clock.NewTimer(discoveryInterval, "acp-discovery")
|
||||
defer timer.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-m.ctx.Done():
|
||||
return
|
||||
case <-timer.C:
|
||||
reload()
|
||||
timer.Reset(discoveryInterval, "acp-discovery")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
package agentacp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
"github.com/coder/quartz"
|
||||
)
|
||||
|
||||
func TestDiscoveryCatalog(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
m, configDir := newTestManager(t)
|
||||
catalog := m.Catalog()
|
||||
require.Equal(t, "fake", catalog[0].DisplayName)
|
||||
require.NoError(t, m.Reload(ctx))
|
||||
require.Equal(t, catalog, m.Catalog())
|
||||
// Returned snapshots must not let callers mutate discovery state.
|
||||
catalog[0].DisplayName = "mutated"
|
||||
require.Equal(t, "fake", m.Catalog()[0].DisplayName)
|
||||
writeConfig(t, filepath.Join(configDir, "disabled.json"), map[string]any{"command": "false", "enabled": false})
|
||||
require.NoError(t, os.WriteFile(filepath.Join(configDir, "broken.json"), []byte(`{`), 0o600))
|
||||
writeConfig(t, filepath.Join(configDir, "missing.json"), map[string]any{})
|
||||
require.NoError(t, os.Mkdir(filepath.Join(configDir, "nested"), 0o700))
|
||||
writeConfig(t, filepath.Join(configDir, "nested", "ignored.json"), map[string]any{"command": "false"})
|
||||
require.NoError(t, m.Reload(ctx))
|
||||
catalog = m.Catalog()
|
||||
require.Len(t, catalog, 3)
|
||||
for _, h := range catalog {
|
||||
if h.Slug != "fake" {
|
||||
require.NotEmpty(t, h.Error)
|
||||
}
|
||||
}
|
||||
writeConfig(t, filepath.Join(configDir, "fake.json"), map[string]any{"command": "false", "display_name": "Changed"})
|
||||
require.NoError(t, m.Reload(ctx))
|
||||
var found bool
|
||||
for _, harness := range m.Catalog() {
|
||||
if harness.Slug == "fake" {
|
||||
found = true
|
||||
require.Equal(t, "Changed", harness.DisplayName)
|
||||
require.Empty(t, harness.Error)
|
||||
}
|
||||
}
|
||||
require.True(t, found, "the edited harness must remain in the catalog")
|
||||
require.NoError(t, os.Remove(filepath.Join(configDir, "fake.json")))
|
||||
require.NoError(t, m.Reload(ctx))
|
||||
require.Len(t, m.Catalog(), 2)
|
||||
}
|
||||
|
||||
func TestDiscoveryDirectoryCreation(t *testing.T) {
|
||||
t.Parallel()
|
||||
home := t.TempDir()
|
||||
clock := quartz.NewMock(t)
|
||||
m := NewManager(context.Background(), Options{
|
||||
Logger: testutil.Logger(t),
|
||||
Clock: clock,
|
||||
Filesystem: afero.NewOsFs(),
|
||||
EnvInfo: testEnv{home: home},
|
||||
})
|
||||
t.Cleanup(func() { require.NoError(t, m.Close()) })
|
||||
changed := make(chan struct{}, 8)
|
||||
m.SetOnChange(func() { changed <- struct{}{} })
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
startTestDiscovery(ctx, t, m)
|
||||
testutil.RequireReceive(ctx, t, changed)
|
||||
require.Empty(t, m.Catalog())
|
||||
configDir := filepath.Join(home, ".coder", "acp")
|
||||
require.NoError(t, os.MkdirAll(configDir, 0o700))
|
||||
writeConfig(t, filepath.Join(configDir, "fake.json"), map[string]any{"command": "false"})
|
||||
require.Empty(t, m.Catalog())
|
||||
advanceTestDiscovery(ctx, t, clock)
|
||||
testutil.RequireReceive(ctx, t, changed)
|
||||
require.Len(t, m.Catalog(), 1)
|
||||
require.Empty(t, m.Catalog()[0].Error)
|
||||
}
|
||||
|
||||
func TestDiscoveryEditsAndDirectoryRecreation(t *testing.T) {
|
||||
t.Parallel()
|
||||
m, configDir := newTestManager(t)
|
||||
changed := make(chan struct{}, 16)
|
||||
m.SetOnChange(func() { changed <- struct{}{} })
|
||||
clock := m.clock.(*quartz.Mock)
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
startTestDiscovery(ctx, t, m)
|
||||
writeConfig(t, filepath.Join(configDir, "fake.json"), map[string]any{"command": "false", "display_name": "Edited"})
|
||||
require.Equal(t, "fake", m.Catalog()[0].DisplayName)
|
||||
advanceTestDiscovery(ctx, t, clock)
|
||||
testutil.RequireReceive(ctx, t, changed)
|
||||
require.Equal(t, "Edited", m.Catalog()[0].DisplayName)
|
||||
backup := configDir + "-backup"
|
||||
require.NoError(t, os.Rename(configDir, backup))
|
||||
advanceTestDiscovery(ctx, t, clock)
|
||||
testutil.RequireReceive(ctx, t, changed)
|
||||
require.Empty(t, m.Catalog())
|
||||
require.NoError(t, os.Mkdir(configDir, 0o700))
|
||||
writeConfig(t, filepath.Join(configDir, "fake.json"), map[string]any{"command": "false"})
|
||||
advanceTestDiscovery(ctx, t, clock)
|
||||
testutil.RequireReceive(ctx, t, changed)
|
||||
require.Len(t, m.Catalog(), 1)
|
||||
require.NoError(t, os.Remove(filepath.Join(configDir, "fake.json")))
|
||||
advanceTestDiscovery(ctx, t, clock)
|
||||
testutil.RequireReceive(ctx, t, changed)
|
||||
require.Empty(t, m.Catalog())
|
||||
}
|
||||
|
||||
func TestDiscoveryUnchangedCatalog(t *testing.T) {
|
||||
t.Parallel()
|
||||
m, _ := newTestManager(t)
|
||||
changed := make(chan struct{}, 8)
|
||||
m.SetOnChange(func() { changed <- struct{}{} })
|
||||
clock := m.clock.(*quartz.Mock)
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
catalog := m.Catalog()
|
||||
startTestDiscovery(ctx, t, m)
|
||||
m.RunDiscovery()
|
||||
for range 2 {
|
||||
advanceTestDiscovery(ctx, t, clock)
|
||||
require.Equal(t, catalog, m.Catalog())
|
||||
require.Empty(t, changed)
|
||||
}
|
||||
require.NoError(t, m.Close())
|
||||
_, pending := clock.Peek()
|
||||
require.False(t, pending, "shutdown must stop the discovery timer")
|
||||
}
|
||||
|
||||
func startTestDiscovery(ctx context.Context, t *testing.T, m *Manager) {
|
||||
t.Helper()
|
||||
trap := m.clock.(*quartz.Mock).Trap().NewTimer("acp-discovery")
|
||||
defer trap.Close()
|
||||
m.RunDiscovery()
|
||||
call := trap.MustWait(ctx)
|
||||
require.Equal(t, discoveryInterval, call.Duration)
|
||||
call.MustRelease(ctx)
|
||||
}
|
||||
|
||||
func advanceTestDiscovery(ctx context.Context, t *testing.T, clock *quartz.Mock) {
|
||||
t.Helper()
|
||||
trap := clock.Trap().TimerReset("acp-discovery")
|
||||
defer trap.Close()
|
||||
clock.Advance(discoveryInterval).MustWait(ctx)
|
||||
call := trap.MustWait(ctx)
|
||||
require.Equal(t, discoveryInterval, call.Duration)
|
||||
call.MustRelease(ctx)
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// Package agentacp manages workspace-local ACP harnesses.
|
||||
package agentacp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"cdr.dev/slog/v3"
|
||||
"github.com/coder/coder/v2/agent/usershell"
|
||||
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
||||
"github.com/coder/quartz"
|
||||
)
|
||||
|
||||
// ErrManagerClosed is returned when the manager has been closed.
|
||||
var ErrManagerClosed = xerrors.New("ACP manager closed")
|
||||
|
||||
// Options supplies the workspace execution environment and lifecycle.
|
||||
type Options struct {
|
||||
Logger slog.Logger
|
||||
Clock quartz.Clock
|
||||
Filesystem afero.Fs
|
||||
EnvInfo usershell.EnvInfoer
|
||||
}
|
||||
|
||||
// Manager owns filesystem discovery and catalog snapshots.
|
||||
type Manager struct {
|
||||
configHashes map[string][32]byte
|
||||
closedDone chan struct{}
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
logger slog.Logger
|
||||
clock quartz.Clock
|
||||
fs afero.Fs
|
||||
envInfo usershell.EnvInfoer
|
||||
mu sync.Mutex
|
||||
closed bool
|
||||
configs map[string]harnessConfig
|
||||
configDir string
|
||||
catalog []workspacesdk.ACPHarness
|
||||
onChange func()
|
||||
wg sync.WaitGroup
|
||||
reloadMu sync.Mutex
|
||||
runOnce sync.Once
|
||||
}
|
||||
|
||||
// NewManager creates a manager; RunDiscovery starts filesystem discovery.
|
||||
// Clock, Filesystem, and EnvInfo must be supplied.
|
||||
func NewManager(ctx context.Context, opts Options) *Manager {
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
return &Manager{
|
||||
ctx: ctx,
|
||||
cancel: cancel,
|
||||
logger: opts.Logger,
|
||||
clock: opts.Clock,
|
||||
fs: opts.Filesystem,
|
||||
envInfo: opts.EnvInfo,
|
||||
closedDone: make(chan struct{}),
|
||||
configs: make(map[string]harnessConfig),
|
||||
configHashes: make(map[string][32]byte),
|
||||
}
|
||||
}
|
||||
|
||||
// SetOnChange installs the callback invoked after discovery changes.
|
||||
func (m *Manager) SetOnChange(fn func()) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
m.onChange = fn
|
||||
}
|
||||
|
||||
// run starts fn in a goroutine tracked by Close. It returns false if shutdown
|
||||
// has begun. The manager lock makes starting work atomic with shutdown.
|
||||
func (m *Manager) run(fn func()) bool {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.closed {
|
||||
return false
|
||||
}
|
||||
m.wg.Go(fn)
|
||||
return true
|
||||
}
|
||||
|
||||
// Close stops discovery and all manager-owned goroutines.
|
||||
func (m *Manager) Close() error {
|
||||
m.mu.Lock()
|
||||
if m.closed {
|
||||
m.mu.Unlock()
|
||||
<-m.closedDone
|
||||
return nil
|
||||
}
|
||||
m.closed = true
|
||||
m.cancel()
|
||||
m.mu.Unlock()
|
||||
m.wg.Wait()
|
||||
close(m.closedDone)
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package agentacp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/afero"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"cdr.dev/slog/v3/sloggers/slogtest"
|
||||
"github.com/coder/coder/v2/agent/usershell"
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
"github.com/coder/quartz"
|
||||
)
|
||||
|
||||
type testEnv struct {
|
||||
usershell.SystemEnvInfo
|
||||
home string
|
||||
}
|
||||
|
||||
func (e testEnv) HomeDir() (string, error) { return e.home, nil }
|
||||
|
||||
func newTestManager(t *testing.T) (manager *Manager, configsDirectory string) {
|
||||
t.Helper()
|
||||
home := t.TempDir()
|
||||
m := NewManager(context.Background(), Options{
|
||||
Logger: slogtest.Make(t, nil),
|
||||
Clock: quartz.NewMock(t),
|
||||
Filesystem: afero.NewOsFs(),
|
||||
EnvInfo: testEnv{home: home},
|
||||
})
|
||||
t.Cleanup(func() { require.NoError(t, m.Close()) })
|
||||
configDir := filepath.Join(home, ".coder", "acp")
|
||||
require.NoError(t, os.MkdirAll(configDir, 0o700))
|
||||
writeConfig(t, filepath.Join(configDir, "fake.json"), map[string]any{"command": "false"})
|
||||
require.NoError(t, m.Reload(testutil.Context(t, testutil.WaitLong)))
|
||||
require.Len(t, m.Catalog(), 1)
|
||||
require.Empty(t, m.Catalog()[0].Error)
|
||||
return m, configDir
|
||||
}
|
||||
|
||||
func writeConfig(t *testing.T, path string, value any) {
|
||||
t.Helper()
|
||||
raw, err := json.Marshal(value)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, os.WriteFile(path, raw, 0o600))
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package workspacesdk
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"golang.org/x/xerrors"
|
||||
|
||||
"github.com/coder/coder/v2/codersdk"
|
||||
)
|
||||
|
||||
// ACPHarness is the public discovery result. Commands stay on the agent.
|
||||
type ACPHarness struct {
|
||||
Slug string `json:"slug"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// ListACPHarnesses returns the cached agent-local harness catalog.
|
||||
func (c *agentConn) ListACPHarnesses(ctx context.Context) ([]ACPHarness, error) {
|
||||
var result []ACPHarness
|
||||
res, err := c.apiRequest(ctx, http.MethodGet, "/api/v0/acp/harnesses", nil)
|
||||
if err != nil {
|
||||
return nil, xerrors.Errorf("list ACP harnesses: %w", err)
|
||||
}
|
||||
defer res.Body.Close()
|
||||
if res.StatusCode != http.StatusOK {
|
||||
return nil, codersdk.ReadBodyAsError(res)
|
||||
}
|
||||
return result, decodeAgentJSON(res, &result)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package workspacesdk_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/coder/coder/v2/codersdk/workspacesdk"
|
||||
"github.com/coder/coder/v2/tailnet"
|
||||
"github.com/coder/coder/v2/tailnet/tailnettest"
|
||||
"github.com/coder/coder/v2/testutil"
|
||||
)
|
||||
|
||||
func TestACPTransport(t *testing.T) {
|
||||
t.Parallel()
|
||||
derpMap, _ := tailnettest.RunDERPAndSTUN(t)
|
||||
clientID, agentID := uuid.New(), uuid.New()
|
||||
client, _ := newTailnetConn(t, derpMap, clientID, "client")
|
||||
agent, agentIP := newTailnetConn(t, derpMap, agentID, "agent")
|
||||
stitchTailnet(t, map[uuid.UUID]*tailnet.Conn{clientID: client, agentID: agent})
|
||||
router := http.NewServeMux()
|
||||
router.HandleFunc("/api/v0/acp/harnesses", func(w http.ResponseWriter, r *http.Request) {
|
||||
require.Equal(t, http.MethodGet, r.Method)
|
||||
require.Empty(t, r.Header.Get(workspacesdk.CoderChatIDHeader))
|
||||
require.Empty(t, r.Header.Get(workspacesdk.CoderToolCallIDHeader))
|
||||
require.NoError(t, json.NewEncoder(w).Encode([]workspacesdk.ACPHarness{{Slug: "fake"}}))
|
||||
})
|
||||
serveTailnetHTTP(t, agent, router)
|
||||
ctx := testutil.Context(t, testutil.WaitLong)
|
||||
require.True(t, client.AwaitReachable(ctx, agentIP))
|
||||
conn := workspacesdk.NewAgentConn(client, workspacesdk.AgentConnOptions{AgentID: agentID, Logger: testutil.Logger(t)})
|
||||
catalog, err := conn.ListACPHarnesses(ctx)
|
||||
require.NoError(t, err)
|
||||
require.Len(t, catalog, 1)
|
||||
}
|
||||
@@ -91,6 +91,7 @@ const (
|
||||
// AgentConn represents a connection to a workspace agent.
|
||||
// @typescript-ignore AgentConn
|
||||
type AgentConn interface {
|
||||
ListACPHarnesses(ctx context.Context) ([]ACPHarness, error)
|
||||
TailnetConn() *tailnet.Conn
|
||||
SetExtraHeaders(h http.Header)
|
||||
|
||||
|
||||
@@ -311,6 +311,21 @@ func (mr *MockAgentConnMockRecorder) LS(ctx, path, req any) *gomock.Call {
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "LS", reflect.TypeOf((*MockAgentConn)(nil).LS), ctx, path, req)
|
||||
}
|
||||
|
||||
// ListACPHarnesses mocks base method.
|
||||
func (m *MockAgentConn) ListACPHarnesses(ctx context.Context) ([]workspacesdk.ACPHarness, error) {
|
||||
m.ctrl.T.Helper()
|
||||
ret := m.ctrl.Call(m, "ListACPHarnesses", ctx)
|
||||
ret0, _ := ret[0].([]workspacesdk.ACPHarness)
|
||||
ret1, _ := ret[1].(error)
|
||||
return ret0, ret1
|
||||
}
|
||||
|
||||
// ListACPHarnesses indicates an expected call of ListACPHarnesses.
|
||||
func (mr *MockAgentConnMockRecorder) ListACPHarnesses(ctx any) *gomock.Call {
|
||||
mr.mock.ctrl.T.Helper()
|
||||
return mr.mock.ctrl.RecordCallWithMethodType(mr.mock, "ListACPHarnesses", reflect.TypeOf((*MockAgentConn)(nil).ListACPHarnesses), ctx)
|
||||
}
|
||||
|
||||
// ListContainers mocks base method.
|
||||
func (m *MockAgentConn) ListContainers(ctx context.Context) (codersdk.WorkspaceAgentListContainersResponse, error) {
|
||||
m.ctrl.T.Helper()
|
||||
|
||||
Reference in new issue
Block a user