Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
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
10 changes: 9 additions & 1 deletion agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ import (
"github.com/coder/coder/v2/agent/agentscripts"
"github.com/coder/coder/v2/agent/agentsocket"
"github.com/coder/coder/v2/agent/agentssh"
"github.com/coder/coder/v2/agent/agenttoolcall"
"github.com/coder/coder/v2/agent/boundarylogproxy"
"github.com/coder/coder/v2/agent/proto"
"github.com/coder/coder/v2/agent/proto/resourcesmonitor"
Expand Down Expand Up @@ -344,6 +345,7 @@ type agent struct {
filesAPI *agentfiles.API
gitAPI *agentgit.API
processAPI *agentproc.API
toolCallStore *agenttoolcall.Store
desktopAPI *agentdesktop.API
mcpManager *agentmcp.Manager
mcpAPI *agentmcp.API
Expand Down Expand Up @@ -473,7 +475,8 @@ func (a *agent) init() {
}
return ""
}
a.processAPI = agentproc.NewAPI(a.logger.Named("processes"), a.execer, a.filesystem, pathStore, a.envInfo, a.updateCommandEnv, workingDirFn)
a.toolCallStore = agenttoolcall.NewStore(a.clock)
a.processAPI = agentproc.NewAPI(a.logger.Named("processes"), a.execer, a.filesystem, pathStore, a.envInfo, a.updateCommandEnv, workingDirFn, agentproc.WithClock(a.clock), agentproc.WithToolCallStore(a.toolCallStore))
gitOpts := append([]agentgit.Option{agentgit.WithClock(a.clock)}, a.gitAPIOptions...)
a.gitAPI = agentgit.NewAPI(a.logger.Named("git"), pathStore, gitOpts...)
desktop := agentdesktop.NewPortableDesktop(
Expand Down Expand Up @@ -1384,6 +1387,11 @@ func (a *agent) handleManifest(manifestOK *checkpoint) func(ctx context.Context,
if manifest.AgentID == uuid.Nil {
return xerrors.New("nil agentID returned by manifest")
}
// Every reconnect fetches a manifest; the store keeps the
// value from the first one.
if manifest.LastChatMessageID != nil {
a.toolCallStore.SetLastChatMessageID(*manifest.LastChatMessageID)
}
if manifest.ParentID != uuid.Nil {
// This is a sub agent, disable all the features that should not
// be used by sub agents.
Expand Down
35 changes: 35 additions & 0 deletions agent/agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3639,6 +3639,41 @@ func TestAgent_WriteVSCodeConfigs(t *testing.T) {
}, testutil.WaitShort, testutil.IntervalFast)
}

// TestAgent_ProcessToolCall checks the tool call wiring: the cutoff
// from the first manifest, the start route through the tool call store,
// and the cancel route.
func TestAgent_ProcessToolCall(t *testing.T) {
t.Parallel()

ctx := testutil.Context(t, testutil.WaitLong)
lastChatMessageID := int64(10)
//nolint:dogsled
conn, _, _, _, _ := setupAgent(t, agentsdk.Manifest{LastChatMessageID: &lastChatMessageID}, 0)
chatID := uuid.New()
conn.SetExtraHeaders(http.Header{workspacesdk.CoderChatIDHeader: {chatID.String()}})

// An earlier agent instance may have received a tool call at or
// below the cutoff.
old := workspacesdk.ToolCall{MessageID: lastChatMessageID, ID: "old", Name: "execute"}
_, err := conn.StartProcess(workspacesdk.WithToolCall(ctx, old), workspacesdk.StartProcessRequest{Command: "true"})
var toolCallErr *workspacesdk.ToolCallError
require.ErrorAs(t, err, &toolCallErr)
require.Equal(t, workspacesdk.ToolCallErrorUnknown, toolCallErr.Code)

toolCall := workspacesdk.ToolCall{MessageID: lastChatMessageID + 1, ID: "new", Name: "execute"}
toolCallCtx := workspacesdk.WithToolCall(ctx, toolCall)
resp, err := conn.StartProcess(toolCallCtx, workspacesdk.StartProcessRequest{Command: "sleep 300"})
require.NoError(t, err)
id := workspacesdk.ToolCallUUID(chatID, toolCall.MessageID, toolCall.Name, toolCall.ID).String()
require.Equal(t, id, resp.ID)

require.NoError(t, conn.CancelToolCall(toolCallCtx, id))
out, err := conn.ProcessOutput(ctx, id, nil)
require.NoError(t, err)
require.False(t, out.Running)
require.True(t, out.Canceled)
}

func TestAgent_DebugServer(t *testing.T) {
t.Parallel()

Expand Down
86 changes: 69 additions & 17 deletions agent/agentproc/api.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package agentproc

import (
"context"
"encoding/json"
"errors"
"fmt"
Expand All @@ -17,10 +16,12 @@ import (
"github.com/coder/coder/v2/agent/agentchat"
"github.com/coder/coder/v2/agent/agentexec"
"github.com/coder/coder/v2/agent/agentgit"
"github.com/coder/coder/v2/agent/agenttoolcall"
"github.com/coder/coder/v2/agent/usershell"
"github.com/coder/coder/v2/coderd/httpapi"
"github.com/coder/coder/v2/codersdk"
"github.com/coder/coder/v2/codersdk/workspacesdk"
"github.com/coder/quartz"
)

const (
Expand All @@ -35,14 +36,48 @@ type API struct {
logger slog.Logger
manager *manager
pathStore *agentgit.PathStore
// toolCallStore runs the start route once per tool call. Nil
// leaves tool call headers unhandled.
toolCallStore *agenttoolcall.Store
}

// Option configures an API.
type Option func(*apiOptions)

type apiOptions struct {
clock quartz.Clock
toolCallStore *agenttoolcall.Store
}

// WithClock sets the clock for process times, execute deadlines,
// output waits, and the periodic sweep.
func WithClock(clock quartz.Clock) Option {
return func(o *apiOptions) {
o.clock = clock
}
}

// WithToolCallStore runs the start route through store.Middleware, so
// a start with tool call headers runs once and its process ID is the
// tool call UUID. An exited tool call process is kept while the store
// retains its record.
func WithToolCallStore(store *agenttoolcall.Store) Option {
return func(o *apiOptions) {
o.toolCallStore = store
}
}

// NewAPI creates a new process API handler.
func NewAPI(logger slog.Logger, execer agentexec.Execer, fs afero.Fs, pathStore *agentgit.PathStore, envInfo usershell.EnvInfoer, updateEnv func(current []string) (updated []string, err error), workingDir func() string) *API {
func NewAPI(logger slog.Logger, execer agentexec.Execer, fs afero.Fs, pathStore *agentgit.PathStore, envInfo usershell.EnvInfoer, updateEnv func(current []string) (updated []string, err error), workingDir func() string, opts ...Option) *API {
options := apiOptions{clock: quartz.NewReal()}
for _, opt := range opts {
opt(&options)
}
return &API{
logger: logger,
manager: newManager(logger, execer, fs, envInfo, updateEnv, workingDir),
pathStore: pathStore,
logger: logger,
manager: newManager(logger, execer, fs, envInfo, updateEnv, workingDir, options.clock, options.toolCallStore),
pathStore: pathStore,
toolCallStore: options.toolCallStore,
}
}

Expand All @@ -55,7 +90,11 @@ func (api *API) Close() error {
// Routes returns the HTTP handler for process-related routes.
func (api *API) Routes() http.Handler {
r := chi.NewRouter()
r.Post("/start", api.handleStartProcess)
if api.toolCallStore != nil {
r.With(api.toolCallStore.Middleware).Post("/start", api.handleStartProcess)
} else {
r.Post("/start", api.handleStartProcess)
}
r.Get("/list", api.handleListProcesses)
r.Get("/{id}/output", api.handleProcessOutput)
r.Post("/{id}/signal", api.handleSignalProcess)
Expand All @@ -65,9 +104,14 @@ func (api *API) Routes() http.Handler {
// handleStartProcess starts a new process.
func (api *API) handleStartProcess(rw http.ResponseWriter, r *http.Request) {
ctx := r.Context()
toolCall, isToolCall := agenttoolcall.FromContext(ctx)

var req workspacesdk.StartProcessRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
// Nothing ran, so a repeated request may run the tool call.
if isToolCall {
toolCall.Abandon()
}
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: "Request body must be valid JSON.",
Detail: err.Error(),
Expand All @@ -81,13 +125,19 @@ func (api *API) handleStartProcess(rw http.ResponseWriter, r *http.Request) {
})
return
}
if req.TimeoutMs < 0 {
httpapi.Write(ctx, rw, http.StatusBadRequest, codersdk.Response{
Message: "Timeout must not be negative.",
})
return
}

var chatID string
if chatContext, ok := agentchat.FromContext(ctx); ok {
chatID = chatContext.ID.String()
}

proc, err := api.manager.start(req, chatID)
proc, err := api.manager.start(req, chatID, toolCall)
if err != nil {
httpapi.Write(ctx, rw, http.StatusInternalServerError, codersdk.Response{
Message: "Failed to start process.",
Expand Down Expand Up @@ -194,11 +244,9 @@ func (api *API) handleProcessOutput(rw http.ResponseWriter, r *http.Request) {
}

// Cap the wait at maxWaitDuration regardless of
// client-supplied timeout.
waitCtx, waitCancel := context.WithTimeout(ctx, maxWaitDuration)
defer waitCancel()

_ = proc.waitForOutput(waitCtx)
// client-supplied timeout, and end it at the execute
// deadline.
api.manager.waitForExit(ctx, proc, maxWaitDuration)
// Fall through to read snapshot below.
}

Expand All @@ -209,13 +257,17 @@ func (api *API) handleProcessOutput(rw http.ResponseWriter, r *http.Request) {
// the final buffer state.
info := proc.info()
output, truncated := proc.output()
timedOut, canceled, duration := proc.runState(info, api.manager.clock.Now())

httpapi.Write(ctx, rw, http.StatusOK, workspacesdk.ProcessOutputResponse{
Output: output,
Truncated: truncated,
Running: info.Running,
ExitCode: info.ExitCode,
Command: info.Command,
Output: output,
Truncated: truncated,
Running: info.Running,
ExitCode: info.ExitCode,
Command: info.Command,
TimedOut: timedOut,
Canceled: canceled,
DurationMs: duration.Milliseconds(),
})
}

Expand Down
Loading
Loading