fix: address PR review feedback (CI, CodeRabbit, Greptile, Claude)
Backend: - service_task_environments: fail closed when checkAnySessionRunning errors so a transient DB hiccup can't bypass the running-session guard and tear down a live container/sandbox; teardown is now truly best-effort with errors.Join across container/sandbox/worktree, so a failed Docker call doesn't permanently orphan the worktree on retry. Adds tests for the running-check error path and the multi-resource best-effort path. - executor_execute: propagate GetTaskEnvironmentByTaskID errors instead of silently launching a fresh environment that orphans existing containers/worktrees; gate environment reuse on matching ExecutorType so a profile switch doesn't pass stale PreviousExecutionID/container IDs to the wrong backend. - task_environment_handlers: reject malformed JSON on POST /tasks/:id/environment/reset (still allow empty body) so a destructive endpoint doesn't silently proceed with a bad payload. - worktree (PushEnvironmentBranch): bound git push with a 30s context timeout and disable interactive prompts via GIT_TERMINAL_PROMPT=0 so a stalled remote can't hang the request thread. - manager_environment: explicitly call ensureClient() before ContainerMgr() in DestroyContainer/GetContainerLiveStatus so a missing Docker daemon surfaces as "docker unavailable" rather than the generic "container manager not initialized". - container: WorkingDir always uses the in-container /workspace path rather than the host workspace path (Docker would happily start in an unrelated directory in host bind-mount mode); bootstrap now logs the prepare-script exit code so failures show up in container logs. - docker/client: CreateContainerInteractive honors ContainerConfig.Entrypoint so the same config struct produces consistent behavior on both creation paths. Frontend: - executor-settings-button: extract useTaskEnvironment hook (component shrinks below the 100-line limit); only treat 404 as empty env (other errors no longer wipe a valid environment); track "loaded once" via a ref so loadEnv doesn't depend on env state — that dep was creating a new function identity on every successful poll, cancelling the 3-second interval and turning the popover into a tight loop hammering /environment/live; copy-shell command uses sh instead of bash so it works on user-built minimal images. - task-reset-env-confirm-dialog: AlertDialogAction onClick calls e.preventDefault() so Radix's auto-close doesn't dismiss the dialog before the async reset completes (loading spinner now visible; close is parent-controlled via onOpenChange). - remote-credentials-card: track env method in selectedIds the same way files/gh_cli_token are tracked, and let initialChoice match either selectedIds OR envSecretId. First-time env-credential setup for an agent that exposes both files+env was broken: clicking the env radio never updated state, choice re-derived to "none", and the secret picker disappeared before the user could pick anything. - e2e/executor-reuse: select the acknowledge checkbox by label, not by positional last(), so adding another checkbox to the dialog can't silently target the wrong control. Format pass on prettier-flagged files; gofmt fixed two whitespace nits in lifecycle files.
This commit is contained in:
@@ -2,7 +2,9 @@ package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
@@ -141,6 +143,12 @@ func (a *environmentDestroyerAdapter) GetContainerLiveStatus(ctx context.Context
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// pushBranchTimeout caps how long we'll wait for `git push` before treating
|
||||
// the call as hung. Reset is invoked from the request thread; without a bound
|
||||
// a stalled remote (auth prompt, packet loss, slow proxy) would block the
|
||||
// entire HTTP handler indefinitely.
|
||||
const pushBranchTimeout = 30 * time.Second
|
||||
|
||||
func (a *environmentDestroyerAdapter) PushEnvironmentBranch(ctx context.Context, env *models.TaskEnvironment) error {
|
||||
// For host-side worktrees we can push directly. Container/sandbox workspaces
|
||||
// would require an active agentctl client — not wired yet, surface a clear
|
||||
@@ -148,16 +156,26 @@ func (a *environmentDestroyerAdapter) PushEnvironmentBranch(ctx context.Context,
|
||||
if env.WorktreePath == "" {
|
||||
return fmt.Errorf("push-before-reset is not supported for this environment type; please push manually first")
|
||||
}
|
||||
pushCtx, cancel := context.WithTimeout(ctx, pushBranchTimeout)
|
||||
defer cancel()
|
||||
|
||||
branch := strings.TrimSpace(env.WorktreeBranch)
|
||||
var cmd *exec.Cmd
|
||||
if branch == "" {
|
||||
cmd = exec.CommandContext(ctx, "git", "push")
|
||||
cmd = exec.CommandContext(pushCtx, "git", "push")
|
||||
} else {
|
||||
cmd = exec.CommandContext(ctx, "git", "push", "origin", branch)
|
||||
cmd = exec.CommandContext(pushCtx, "git", "push", "origin", branch)
|
||||
}
|
||||
cmd.Dir = env.WorktreePath
|
||||
// Disable interactive credential prompts — without this, a missing
|
||||
// credential helper can hang waiting on stdin even with the timeout above
|
||||
// (signal delivery is gated behind the prompt read).
|
||||
cmd.Env = append(os.Environ(), "GIT_TERMINAL_PROMPT=0")
|
||||
out, err := cmd.CombinedOutput()
|
||||
if err != nil {
|
||||
if errors.Is(pushCtx.Err(), context.DeadlineExceeded) {
|
||||
return fmt.Errorf("git push timed out after %s in %s (branch %q); push manually and retry", pushBranchTimeout, env.WorktreePath, branch)
|
||||
}
|
||||
return fmt.Errorf("git push failed: %s: %w", strings.TrimSpace(string(out)), err)
|
||||
}
|
||||
return nil
|
||||
|
||||
@@ -528,9 +528,12 @@ func (c *Client) CreateContainerInteractive(ctx context.Context, cfg ContainerCo
|
||||
})
|
||||
}
|
||||
|
||||
// Container configuration with stdin attached
|
||||
// Container configuration with stdin attached. Mirror CreateContainer's
|
||||
// handling of ContainerConfig fields — including Entrypoint — so the same
|
||||
// config struct produces consistent container behavior on both paths.
|
||||
containerCfg := &container.Config{
|
||||
Image: cfg.Image,
|
||||
Entrypoint: cfg.Entrypoint,
|
||||
Cmd: cfg.Cmd,
|
||||
Env: cfg.Env,
|
||||
WorkingDir: cfg.WorkingDir,
|
||||
|
||||
@@ -274,15 +274,19 @@ func (cm *ContainerManager) buildContainerConfig(config ContainerConfig) (docker
|
||||
// via its HTTP API (CreateInstance). The container only needs to launch
|
||||
// agentctl as its main process — see the Entrypoint setup below.
|
||||
|
||||
// Resolve the in-container workspace path. Clone-inside-container mode leaves
|
||||
// config.WorkspacePath empty (no host bind mount); the entrypoint clones into
|
||||
// /workspace, so use that for both mount expansion and the container WorkingDir.
|
||||
workspacePath := config.WorkspacePath
|
||||
if workspacePath == "" {
|
||||
workspacePath = "/workspace"
|
||||
}
|
||||
// Two paths through here use different "workspace" strings:
|
||||
// - Mount sources expand against the HOST workspace path (config.WorkspacePath
|
||||
// when set, otherwise no host mount in clone-inside-container mode).
|
||||
// - WorkingDir is an in-container path; it must always be the container-side
|
||||
// mount target. Both modes converge on /workspace (the bind-mount target
|
||||
// in host mode, the clone destination in clone-inside mode), so we hard-
|
||||
// code it here. Without this distinction, host-bind setups would set
|
||||
// WorkingDir to the host path, and Docker would happily start the
|
||||
// container in an unrelated directory.
|
||||
const containerWorkspacePath = "/workspace"
|
||||
|
||||
// Expand mounts
|
||||
// Expand mounts using the host path so {workspace} substitutions in mount
|
||||
// sources resolve to a real on-disk location.
|
||||
mounts := cm.expandMounts(rt.Mounts, config.WorkspacePath, ag)
|
||||
|
||||
// Add main repo .git directory mount for worktrees
|
||||
@@ -357,7 +361,11 @@ func (cm *ContainerManager) buildContainerConfig(config ContainerConfig) (docker
|
||||
bootstrap := []string{
|
||||
"sh", "-c",
|
||||
`if [ -n "$KANDEV_PREPARE_SCRIPT" ]; then
|
||||
(eval "$KANDEV_PREPARE_SCRIPT") || echo "[kandev-bootstrap] prepare script failed; starting agentctl anyway" >&2
|
||||
(eval "$KANDEV_PREPARE_SCRIPT")
|
||||
prep_rc=$?
|
||||
if [ "$prep_rc" -ne 0 ]; then
|
||||
echo "[kandev-bootstrap] prepare script failed (exit $prep_rc); starting agentctl anyway so the host can connect and the user can debug via Executor Settings" >&2
|
||||
fi
|
||||
fi
|
||||
exec /usr/local/bin/agentctl`,
|
||||
}
|
||||
@@ -368,7 +376,7 @@ exec /usr/local/bin/agentctl`,
|
||||
Entrypoint: bootstrap,
|
||||
Cmd: nil,
|
||||
Env: env,
|
||||
WorkingDir: cm.expandMountSource(rt.WorkingDir, workspacePath),
|
||||
WorkingDir: cm.expandMountSource(rt.WorkingDir, containerWorkspacePath),
|
||||
Mounts: mounts,
|
||||
NetworkMode: cm.networkName,
|
||||
Memory: memoryBytes,
|
||||
|
||||
@@ -68,11 +68,17 @@ func TestBuildContainerConfig_ExpandsWorkingDirPlaceholder(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildContainerConfig_ExpandsWorkingDirWithProvidedWorkspace(t *testing.T) {
|
||||
func TestBuildContainerConfig_WorkingDirIsAlwaysContainerPath(t *testing.T) {
|
||||
// Regression: WorkingDir is the container-side path, not the host path.
|
||||
// In host bind-mount mode, WorkspacePath holds the host path; the bind
|
||||
// mount target is the in-container /workspace, so WorkingDir must point
|
||||
// at the container target — otherwise Docker happily starts the
|
||||
// container in /host/path/to/repo (which doesn't exist inside) and the
|
||||
// agent runs in an unrelated directory.
|
||||
cm := newCMTest(t)
|
||||
cfg := ContainerConfig{
|
||||
AgentConfig: newConfigStubAgent(),
|
||||
WorkspacePath: "/host/path/to/repo", // pre-clone-inside-container mount mode
|
||||
WorkspacePath: "/host/path/to/repo",
|
||||
InstanceID: "0123456789abcdef",
|
||||
TaskID: "task-1",
|
||||
}
|
||||
@@ -81,8 +87,8 @@ func TestBuildContainerConfig_ExpandsWorkingDirWithProvidedWorkspace(t *testing.
|
||||
if err != nil {
|
||||
t.Fatalf("buildContainerConfig: %v", err)
|
||||
}
|
||||
if got.WorkingDir != "/host/path/to/repo" {
|
||||
t.Errorf("WorkingDir = %q, want /host/path/to/repo", got.WorkingDir)
|
||||
if got.WorkingDir != "/workspace" {
|
||||
t.Errorf("WorkingDir = %q, want /workspace (container-side path)", got.WorkingDir)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -63,15 +63,15 @@ const (
|
||||
MetadataKeyWorktreeBranch = "worktree_branch"
|
||||
|
||||
// Remote executor metadata keys
|
||||
MetadataKeyRepositoryPath = "repository_path"
|
||||
MetadataKeySetupScript = "setup_script"
|
||||
MetadataKeyCleanupScript = "cleanup_script"
|
||||
MetadataKeyRepoSetupScript = "repository_setup_script"
|
||||
MetadataKeyBaseBranch = "base_branch"
|
||||
MetadataKeyIsRemote = "is_remote"
|
||||
MetadataKeyRemoteAuthHome = "remote_auth_target_home"
|
||||
MetadataKeyGitUserName = "git_user_name"
|
||||
MetadataKeyGitUserEmail = "git_user_email"
|
||||
MetadataKeyRepositoryPath = "repository_path"
|
||||
MetadataKeySetupScript = "setup_script"
|
||||
MetadataKeyCleanupScript = "cleanup_script"
|
||||
MetadataKeyRepoSetupScript = "repository_setup_script"
|
||||
MetadataKeyBaseBranch = "base_branch"
|
||||
MetadataKeyIsRemote = "is_remote"
|
||||
MetadataKeyRemoteAuthHome = "remote_auth_target_home"
|
||||
MetadataKeyGitUserName = "git_user_name"
|
||||
MetadataKeyGitUserEmail = "git_user_email"
|
||||
MetadataKeyImageTagOverride = "image_tag_override"
|
||||
)
|
||||
|
||||
|
||||
@@ -12,8 +12,8 @@ import (
|
||||
// suitable for surfacing in the Executor Settings popover.
|
||||
type ContainerLiveStatus struct {
|
||||
ContainerID string `json:"container_id"`
|
||||
State string `json:"state"` // running, exited, paused, restarting, removing, dead, created
|
||||
Status string `json:"status"` // human-readable, e.g. "Up 5 minutes"
|
||||
State string `json:"state"` // running, exited, paused, restarting, removing, dead, created
|
||||
Status string `json:"status"` // human-readable, e.g. "Up 5 minutes"
|
||||
StartedAt *time.Time `json:"started_at,omitempty"`
|
||||
FinishedAt *time.Time `json:"finished_at,omitempty"`
|
||||
ExitCode int `json:"exit_code,omitempty"`
|
||||
@@ -36,6 +36,13 @@ func (m *Manager) DestroyContainer(ctx context.Context, containerID string) erro
|
||||
if !ok {
|
||||
return fmt.Errorf("docker backend has unexpected type %T", backend)
|
||||
}
|
||||
// Force lazy initialization here. After a backend restart this method
|
||||
// can be the first caller to touch Docker, and a missing daemon should
|
||||
// surface as a clear "docker unavailable" error rather than a generic
|
||||
// "container manager not initialized".
|
||||
if _, _, err := dockerExec.ensureClient(); err != nil {
|
||||
return fmt.Errorf("initialize docker backend: %w", err)
|
||||
}
|
||||
cm := dockerExec.ContainerMgr()
|
||||
if cm == nil {
|
||||
return fmt.Errorf("docker container manager not initialized")
|
||||
@@ -57,6 +64,9 @@ func (m *Manager) GetContainerLiveStatus(ctx context.Context, containerID string
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("docker backend has unexpected type %T", backend)
|
||||
}
|
||||
if _, _, err := dockerExec.ensureClient(); err != nil {
|
||||
return nil, fmt.Errorf("initialize docker backend: %w", err)
|
||||
}
|
||||
cm := dockerExec.ContainerMgr()
|
||||
if cm == nil {
|
||||
return nil, fmt.Errorf("docker container manager not initialized")
|
||||
|
||||
@@ -423,8 +423,14 @@ func (e *Executor) LaunchPreparedSession(ctx context.Context, task *v1.Task, ses
|
||||
|
||||
// Resolve the env ID before LaunchAgent so the in-memory AgentExecution
|
||||
// is env-scoped from the first shell/layout request, not only after DB
|
||||
// persistence succeeds.
|
||||
existingEnv, _ := e.repo.GetTaskEnvironmentByTaskID(ctx, task.ID)
|
||||
// persistence succeeds. GetTaskEnvironmentByTaskID returns (nil, nil)
|
||||
// when no row exists; a real DB error must propagate so the launch
|
||||
// fails closed instead of silently launching a fresh environment that
|
||||
// orphans the existing container/sandbox/worktree.
|
||||
existingEnv, err := e.repo.GetTaskEnvironmentByTaskID(ctx, task.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("lookup existing task environment: %w", err)
|
||||
}
|
||||
assignLaunchTaskEnvironmentID(session, existingEnv)
|
||||
|
||||
req, execCfg, err := e.buildLaunchAgentRequest(ctx, task, session, agentProfileID, executorID, prompt, primaryRepo, allRepos)
|
||||
@@ -1078,10 +1084,23 @@ func (e *Executor) persistTaskEnvironmentRepos(ctx context.Context, envID string
|
||||
// applyExistingEnvironment propagates worktree, container, and sandbox IDs from
|
||||
// an existing TaskEnvironment into the launch request so that executor backends
|
||||
// can reuse the existing execution environment.
|
||||
//
|
||||
// Reuse is gated on the env's executor_type matching the launch request: if
|
||||
// the user switched the task's executor profile to a different type, we must
|
||||
// NOT pass stale `PreviousExecutionID`/container_id/sprite_name to the wrong
|
||||
// backend (it would either fail loudly or, worse, overwrite the persisted env
|
||||
// with mixed resource IDs on the next save).
|
||||
func (e *Executor) applyExistingEnvironment(req *LaunchAgentRequest, env *models.TaskEnvironment) {
|
||||
if env == nil {
|
||||
return
|
||||
}
|
||||
if env.ExecutorType != "" && env.ExecutorType != req.ExecutorType {
|
||||
e.logger.Info("skipping task environment reuse: executor type changed",
|
||||
zap.String("task_id", req.TaskID),
|
||||
zap.String("env_executor_type", env.ExecutorType),
|
||||
zap.String("req_executor_type", req.ExecutorType))
|
||||
return
|
||||
}
|
||||
|
||||
// Worktree reuse
|
||||
if env.WorktreeID != "" && req.UseWorktree {
|
||||
|
||||
@@ -2,6 +2,7 @@ package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
@@ -59,8 +60,13 @@ type resetEnvironmentRequest struct {
|
||||
func (h *TaskHandlers) httpResetTaskEnvironment(c *gin.Context) {
|
||||
taskID := c.Param("id")
|
||||
var body resetEnvironmentRequest
|
||||
// Body is optional; ignore bind errors so an empty POST works.
|
||||
_ = c.ShouldBindJSON(&body)
|
||||
// The body is optional (an empty POST is valid: defaults to push_branch=false),
|
||||
// but a malformed JSON payload should be rejected loudly rather than silently
|
||||
// proceeding with a destructive reset.
|
||||
if err := c.ShouldBindJSON(&body); err != nil && !errors.Is(err, io.EOF) {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid JSON body: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
err := h.service.ResetTaskEnvironment(c.Request.Context(), taskID, service.ResetOptions{
|
||||
PushBranch: body.PushBranch,
|
||||
|
||||
@@ -148,12 +148,15 @@ func (s *Service) ResetTaskEnvironment(ctx context.Context, taskID string, opts
|
||||
return ErrNoEnvironment
|
||||
}
|
||||
|
||||
// Fail closed: if the running-session check itself errors (DB hiccup,
|
||||
// locked table) we cannot prove the task is idle and must abort rather
|
||||
// than risk destroying a container or sandbox while an agent is still
|
||||
// writing to it.
|
||||
running, err := s.checkAnySessionRunning(ctx, taskID)
|
||||
if err != nil {
|
||||
s.logger.Warn("failed to check running sessions before reset, continuing",
|
||||
zap.String("task_id", taskID),
|
||||
zap.Error(err))
|
||||
} else if running {
|
||||
return fmt.Errorf("check running sessions before reset: %w", err)
|
||||
}
|
||||
if running {
|
||||
return ErrSessionRunning
|
||||
}
|
||||
|
||||
@@ -189,31 +192,33 @@ func (s *Service) ResetTaskEnvironment(ctx context.Context, taskID string, opts
|
||||
}
|
||||
|
||||
// teardownEnvironmentResources destroys runtime resources (container/sandbox/worktree)
|
||||
// recorded on a TaskEnvironment. On any failure, the caller should preserve the row.
|
||||
// recorded on a TaskEnvironment. Best-effort per resource: every resource is
|
||||
// attempted even when an earlier one fails, and all failures are joined into a
|
||||
// single error so a stuck container can't permanently orphan the worktree.
|
||||
// On any error, the caller should preserve the row so the user can retry.
|
||||
func (s *Service) teardownEnvironmentResources(ctx context.Context, env *models.TaskEnvironment) error {
|
||||
if env.ContainerID == "" && env.SandboxID == "" && env.WorktreeID == "" {
|
||||
return nil
|
||||
}
|
||||
if s.envDestroyer == nil {
|
||||
return fmt.Errorf("environment destroyer not configured; cannot tear down resources")
|
||||
}
|
||||
|
||||
var errs []error
|
||||
if env.ContainerID != "" {
|
||||
if s.envDestroyer == nil {
|
||||
return fmt.Errorf("environment destroyer not configured; cannot remove container")
|
||||
}
|
||||
if err := s.envDestroyer.DestroyContainer(ctx, env.ContainerID); err != nil {
|
||||
return fmt.Errorf("destroy container %s: %w", env.ContainerID, err)
|
||||
errs = append(errs, fmt.Errorf("destroy container %s: %w", env.ContainerID, err))
|
||||
}
|
||||
}
|
||||
if env.SandboxID != "" {
|
||||
if s.envDestroyer == nil {
|
||||
return fmt.Errorf("environment destroyer not configured; cannot destroy sandbox")
|
||||
}
|
||||
if err := s.envDestroyer.DestroySandbox(ctx, env.SandboxID, env.AgentExecutionID); err != nil {
|
||||
return fmt.Errorf("destroy sandbox %s: %w", env.SandboxID, err)
|
||||
errs = append(errs, fmt.Errorf("destroy sandbox %s: %w", env.SandboxID, err))
|
||||
}
|
||||
}
|
||||
if env.WorktreeID != "" {
|
||||
if s.envDestroyer == nil {
|
||||
return fmt.Errorf("environment destroyer not configured; cannot remove worktree")
|
||||
}
|
||||
if err := s.envDestroyer.DestroyWorktree(ctx, env.WorktreeID); err != nil {
|
||||
return fmt.Errorf("destroy worktree %s: %w", env.WorktreeID, err)
|
||||
errs = append(errs, fmt.Errorf("destroy worktree %s: %w", env.WorktreeID, err))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
return errors.Join(errs...)
|
||||
}
|
||||
|
||||
@@ -163,6 +163,56 @@ func TestResetTaskEnvironment_ContainerDestroyFailurePreservesRow(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetTaskEnvironment_RunningCheckErrorFailsClosed(t *testing.T) {
|
||||
repo := &stubEnvRepo{env: &models.TaskEnvironment{
|
||||
ID: "env-1",
|
||||
TaskID: "task-1",
|
||||
ContainerID: "container-abc",
|
||||
}}
|
||||
destroyer := &stubDestroyer{}
|
||||
svc := newResetTestService(t, repo)
|
||||
svc.SetSessionRunningChecker(&stubRunningChecker{err: errors.New("db locked")})
|
||||
svc.SetEnvironmentDestroyer(destroyer)
|
||||
|
||||
err := svc.ResetTaskEnvironment(context.Background(), "task-1", ResetOptions{})
|
||||
if err == nil {
|
||||
t.Fatal("expected error when running-session check fails")
|
||||
}
|
||||
if len(destroyer.containerCalls) != 0 {
|
||||
t.Errorf("expected teardown to be skipped when guard errors, got %v", destroyer.containerCalls)
|
||||
}
|
||||
if repo.deleted {
|
||||
t.Error("expected environment row to be preserved when guard errors")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetTaskEnvironment_TeardownIsBestEffortAcrossResources(t *testing.T) {
|
||||
repo := &stubEnvRepo{env: &models.TaskEnvironment{
|
||||
ID: "env-1",
|
||||
TaskID: "task-1",
|
||||
ContainerID: "container-abc",
|
||||
WorktreeID: "wt-1",
|
||||
}}
|
||||
destroyer := &stubDestroyer{containerErr: errors.New("docker unreachable")}
|
||||
svc := newResetTestService(t, repo)
|
||||
svc.SetSessionRunningChecker(&stubRunningChecker{running: false})
|
||||
svc.SetEnvironmentDestroyer(destroyer)
|
||||
|
||||
err := svc.ResetTaskEnvironment(context.Background(), "task-1", ResetOptions{})
|
||||
if err == nil {
|
||||
t.Fatal("expected joined error when container destroy fails")
|
||||
}
|
||||
if len(destroyer.containerCalls) != 1 {
|
||||
t.Errorf("expected container destroy attempted, got %v", destroyer.containerCalls)
|
||||
}
|
||||
if len(destroyer.worktreeCalls) != 1 {
|
||||
t.Errorf("expected worktree destroy attempted even when container failed, got %v", destroyer.worktreeCalls)
|
||||
}
|
||||
if repo.deleted {
|
||||
t.Error("expected environment row to be preserved when any destroy fails")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResetTaskEnvironment_PushBranchFailureAbortsResetBeforeTeardown(t *testing.T) {
|
||||
repo := &stubEnvRepo{env: &models.TaskEnvironment{
|
||||
ID: "env-1",
|
||||
|
||||
@@ -278,7 +278,15 @@ function initialChoice(opts: InitialChoiceOpts): AuthChoice {
|
||||
if (opts.ghTokenMethod && opts.selectedIds.has(opts.ghTokenMethod.method_id))
|
||||
return "gh_cli_token";
|
||||
if (opts.fileMethod && opts.selectedIds.has(opts.fileMethod.method_id)) return "files";
|
||||
if (opts.envSecretId && opts.envMethod) return "env";
|
||||
// Treat env as selected either when the user just clicked the radio (its
|
||||
// method id is in selectedIds, no secret picked yet) or when a secret is
|
||||
// already persisted. Without the selectedIds branch, first-time env setup
|
||||
// for an agent that exposes both `files` and `env` methods is broken: the
|
||||
// radio click never updates state, `choice` re-derives to "none", the env
|
||||
// option deselects, and the secret dropdown disappears before the user can
|
||||
// pick anything.
|
||||
if (opts.envMethod && (opts.selectedIds.has(opts.envMethod.method_id) || opts.envSecretId))
|
||||
return "env";
|
||||
return "none";
|
||||
}
|
||||
|
||||
@@ -323,8 +331,14 @@ function AuthSection({
|
||||
if (ghTokenMethod) {
|
||||
onCredentialToggle(ghTokenMethod.method_id, value === "gh_cli_token");
|
||||
}
|
||||
if (value !== "env" && envMethod) {
|
||||
onMethodSecretChange(envMethod.method_id, null);
|
||||
if (envMethod) {
|
||||
// Track env in selectedIds the same way `files`/`gh_cli_token` are
|
||||
// tracked, so `initialChoice` stays "env" while the user is still
|
||||
// picking a secret. Switching away clears the secret too.
|
||||
onCredentialToggle(envMethod.method_id, value === "env");
|
||||
if (value !== "env") {
|
||||
onMethodSecretChange(envMethod.method_id, null);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
type ContainerLiveStatus,
|
||||
type TaskEnvironment,
|
||||
} from "@/lib/api/domains/task-environment-api";
|
||||
import { ApiError } from "@/lib/api/client";
|
||||
import { TaskResetEnvConfirmDialog } from "./task-reset-env-confirm-dialog";
|
||||
|
||||
type ExecutorSettingsButtonProps = {
|
||||
@@ -22,55 +23,71 @@ type ExecutorSettingsButtonProps = {
|
||||
|
||||
const POLL_INTERVAL_MS = 3000;
|
||||
|
||||
export function ExecutorSettingsButton({ taskId, disabled }: ExecutorSettingsButtonProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
/**
|
||||
* Owns the env+container fetch/poll lifecycle and the reset action so the
|
||||
* popover component stays small. Polls only while `active` is true (the
|
||||
* popover is open) to avoid hammering /environment/live when nobody is
|
||||
* watching.
|
||||
*/
|
||||
function useTaskEnvironment(taskId: string | null | undefined, active: boolean) {
|
||||
const [env, setEnv] = useState<TaskEnvironment | null>(null);
|
||||
const [container, setContainer] = useState<ContainerLiveStatus | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [resetDialogOpen, setResetDialogOpen] = useState(false);
|
||||
const [isResetting, setIsResetting] = useState(false);
|
||||
const inFlight = useRef(false);
|
||||
// hasLoadedRef tracks "have we ever fetched successfully" so the spinner
|
||||
// only shows on the first open. Keeping it in a ref instead of state means
|
||||
// `loadEnv` doesn't depend on `env` — without that, every successful fetch
|
||||
// creates a new `env` reference, forces a new `loadEnv` identity, and the
|
||||
// polling effect's cleanup+rerun fires immediately, turning the 3-second
|
||||
// poll into a tight loop.
|
||||
const hasLoadedRef = useRef(false);
|
||||
|
||||
const loadEnv = useCallback(async () => {
|
||||
if (!taskId || inFlight.current) return;
|
||||
inFlight.current = true;
|
||||
setLoading((prev) => prev || env == null);
|
||||
setLoading((prev) => prev || !hasLoadedRef.current);
|
||||
try {
|
||||
const data = await fetchTaskEnvironmentLive(taskId);
|
||||
hasLoadedRef.current = true;
|
||||
setEnv(data.environment);
|
||||
setContainer(data.container ?? null);
|
||||
} catch {
|
||||
setEnv(null);
|
||||
setContainer(null);
|
||||
} catch (err) {
|
||||
// Only treat 404 as "no environment yet" — a transient 500 / auth /
|
||||
// network error should leave the last-known view in place rather than
|
||||
// erase a valid environment and disable the Reset action.
|
||||
if (err instanceof ApiError && err.status === 404) {
|
||||
hasLoadedRef.current = true;
|
||||
setEnv(null);
|
||||
setContainer(null);
|
||||
}
|
||||
} finally {
|
||||
inFlight.current = false;
|
||||
setLoading(false);
|
||||
}
|
||||
}, [taskId, env]);
|
||||
}, [taskId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open || !taskId) return;
|
||||
if (!active || !taskId) return;
|
||||
void loadEnv();
|
||||
const interval = window.setInterval(() => {
|
||||
void loadEnv();
|
||||
}, POLL_INTERVAL_MS);
|
||||
const interval = window.setInterval(() => void loadEnv(), POLL_INTERVAL_MS);
|
||||
return () => window.clearInterval(interval);
|
||||
}, [open, taskId, loadEnv]);
|
||||
}, [active, taskId, loadEnv]);
|
||||
|
||||
const handleReset = useCallback(
|
||||
const reset = useCallback(
|
||||
async ({ pushBranch }: { pushBranch: boolean }) => {
|
||||
if (!taskId) return;
|
||||
if (!taskId) return false;
|
||||
setIsResetting(true);
|
||||
try {
|
||||
await resetTaskEnvironment(taskId, { push_branch: pushBranch });
|
||||
toast.success("Environment reset");
|
||||
setEnv(null);
|
||||
setContainer(null);
|
||||
setResetDialogOpen(false);
|
||||
setOpen(false);
|
||||
return true;
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : "Unknown error";
|
||||
toast.error(`Reset failed: ${msg}`);
|
||||
return false;
|
||||
} finally {
|
||||
setIsResetting(false);
|
||||
}
|
||||
@@ -78,6 +95,25 @@ export function ExecutorSettingsButton({ taskId, disabled }: ExecutorSettingsBut
|
||||
[taskId],
|
||||
);
|
||||
|
||||
return { env, container, loading, isResetting, reset };
|
||||
}
|
||||
|
||||
export function ExecutorSettingsButton({ taskId, disabled }: ExecutorSettingsButtonProps) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [resetDialogOpen, setResetDialogOpen] = useState(false);
|
||||
const { env, container, loading, isResetting, reset } = useTaskEnvironment(taskId, open);
|
||||
|
||||
const handleReset = useCallback(
|
||||
async (opts: { pushBranch: boolean }) => {
|
||||
const ok = await reset(opts);
|
||||
if (ok) {
|
||||
setResetDialogOpen(false);
|
||||
setOpen(false);
|
||||
}
|
||||
},
|
||||
[reset],
|
||||
);
|
||||
|
||||
if (!taskId) return null;
|
||||
|
||||
return (
|
||||
@@ -271,7 +307,9 @@ function Field({ label, value, copy }: { label: string; value: string; copy?: bo
|
||||
className="cursor-pointer text-muted-foreground hover:text-foreground"
|
||||
aria-label={`Copy ${label}`}
|
||||
onClick={() => {
|
||||
void navigator.clipboard.writeText(value).then(() => toast.success(`${label} copied`));
|
||||
void navigator.clipboard
|
||||
.writeText(value)
|
||||
.then(() => toast.success(`${label} copied`));
|
||||
}}
|
||||
>
|
||||
<IconCopy className="h-3 w-3" />
|
||||
@@ -297,9 +335,12 @@ function buildFields(env: TaskEnvironment, container: ContainerLiveStatus | null
|
||||
if (env.container_id) {
|
||||
const short = env.container_id.slice(0, 12);
|
||||
rows.push({ label: "Container", value: short, copy: true });
|
||||
// Use `sh` rather than `bash` — user-built images may only ship
|
||||
// /bin/sh (busybox/alpine/etc.), and the bootstrap entrypoint already
|
||||
// assumes sh-only.
|
||||
rows.push({
|
||||
label: "Shell",
|
||||
value: `docker exec -it ${short} bash`,
|
||||
value: `docker exec -it ${short} sh`,
|
||||
copy: true,
|
||||
});
|
||||
if (container?.started_at && container.state === "running") {
|
||||
|
||||
@@ -49,8 +49,8 @@ export function TaskResetEnvConfirmDialog({
|
||||
<AlertDialogDescription asChild>
|
||||
<div className="space-y-2">
|
||||
<p>
|
||||
This tears down the current container, sandbox, and/or worktree for this task so
|
||||
the next session starts with a fresh environment.
|
||||
This tears down the current container, sandbox, and/or worktree for this task so the
|
||||
next session starts with a fresh environment.
|
||||
</p>
|
||||
<p className="text-destructive">
|
||||
Any uncommitted or unpushed changes in the workspace will be lost.
|
||||
@@ -92,7 +92,13 @@ export function TaskResetEnvConfirmDialog({
|
||||
disabled={isResetting || !acknowledged}
|
||||
className="cursor-pointer bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
data-testid="reset-env-confirm"
|
||||
onClick={() => {
|
||||
onClick={(e) => {
|
||||
// Radix's AlertDialogAction auto-closes the dialog on click,
|
||||
// which would dismiss it before the async reset completes — the
|
||||
// user never sees the loading spinner, and the dialog closes
|
||||
// even on failure. Block the auto-close so the parent owns the
|
||||
// close decision via `onOpenChange` after the promise settles.
|
||||
e.preventDefault();
|
||||
if (isResetting || !acknowledged) return;
|
||||
onConfirm({ pushBranch });
|
||||
}}
|
||||
|
||||
@@ -181,8 +181,10 @@ test.describe("Executor reuse", () => {
|
||||
|
||||
// Click Reset → confirmation dialog
|
||||
await testPage.getByTestId("executor-settings-reset").click();
|
||||
const ackCheckbox = testPage.getByRole("checkbox").last();
|
||||
await ackCheckbox.click();
|
||||
// Pick the acknowledgement checkbox by its label rather than position so
|
||||
// adding another checkbox to the dialog (e.g. push-before-reset) doesn't
|
||||
// silently make this test click the wrong control.
|
||||
await testPage.getByLabel("I understand any uncommitted changes will be lost.").click();
|
||||
await testPage.getByTestId("reset-env-confirm").click();
|
||||
|
||||
// Poll environment until gone
|
||||
|
||||
Reference in New Issue
Block a user