Files
kandev/apps/backend/cmd/kandev/worktree.go
T
José Almeida 6cd50ab841 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.
2026-05-04 21:09:39 +01:00

183 lines
6.4 KiB
Go

package main
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"strings"
"time"
"github.com/kandev/kandev/internal/agent/lifecycle"
"github.com/kandev/kandev/internal/common/config"
"github.com/kandev/kandev/internal/common/constants"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/internal/db"
"github.com/kandev/kandev/internal/task/models"
taskservice "github.com/kandev/kandev/internal/task/service"
"github.com/kandev/kandev/internal/worktree"
)
// taskServiceAdapter adapts the task service to the worktree.TaskService interface.
type taskServiceAdapter struct {
svc *taskservice.Service
}
func (a *taskServiceAdapter) CreateMessage(ctx context.Context, req *worktree.CreateMessageRequest) (*models.Message, error) {
// Convert worktree.CreateMessageRequest to taskservice.CreateMessageRequest
return a.svc.CreateMessage(ctx, &taskservice.CreateMessageRequest{
TaskSessionID: req.TaskSessionID,
TaskID: req.TaskID,
TurnID: req.TurnID,
Content: req.Content,
AuthorType: req.AuthorType,
AuthorID: req.AuthorID,
RequestsInput: req.RequestsInput,
Type: req.Type,
Metadata: req.Metadata,
})
}
func (a *taskServiceAdapter) UpdateMessage(ctx context.Context, message *models.Message) error {
return a.svc.UpdateMessage(ctx, message)
}
// bootMsgAdapter adapts the task service to the lifecycle.BootMessageService interface.
type bootMsgAdapter struct {
svc *taskservice.Service
}
func (a *bootMsgAdapter) CreateMessage(ctx context.Context, req *lifecycle.BootMessageRequest) (*models.Message, error) {
return a.svc.CreateMessage(ctx, &taskservice.CreateMessageRequest{
TaskSessionID: req.TaskSessionID,
TaskID: req.TaskID,
Content: req.Content,
AuthorType: req.AuthorType,
Type: req.Type,
Metadata: req.Metadata,
})
}
func (a *bootMsgAdapter) UpdateMessage(ctx context.Context, message *models.Message) error {
return a.svc.UpdateMessage(ctx, message)
}
func provideWorktreeManager(dbPool *db.Pool, cfg *config.Config, log *logger.Logger, lifecycleMgr *lifecycle.Manager, taskSvc *taskservice.Service) (*worktree.Manager, *worktree.Recreator, func() error, error) {
manager, cleanup, err := worktree.Provide(dbPool.Writer(), dbPool.Reader(), cfg, log)
if err != nil {
return nil, nil, nil, err
}
if lifecycleMgr != nil {
lifecycleMgr.SetWorktreeManager(manager)
lifecycleMgr.SetBootMessageService(&bootMsgAdapter{svc: taskSvc})
}
taskSvc.SetWorktreeCleanup(manager)
if lifecycleMgr != nil {
taskSvc.SetEnvironmentDestroyer(&environmentDestroyerAdapter{
lifecycle: lifecycleMgr,
worktrees: manager,
})
}
// Wire script message handler with adapters
taskSvcAdapter := &taskServiceAdapter{svc: taskSvc}
scriptHandler := worktree.NewDefaultScriptMessageHandler(
log,
taskSvcAdapter,
constants.SetupScriptTimeout,
)
repoAdapter := worktree.NewRepositoryAdapter(taskSvc)
manager.SetScriptMessageHandler(scriptHandler)
manager.SetRepositoryProvider(repoAdapter)
// Create recreator for orchestrator to use during session resume
recreator := worktree.NewRecreator(manager)
return manager, recreator, cleanup, nil
}
// environmentDestroyerAdapter implements taskservice.EnvironmentDestroyer by
// delegating to the lifecycle Manager (for containers/sandboxes) and the worktree
// Manager (for worktrees). Branch is preserved on worktree removal so unpushed
// work is never silently dropped.
type environmentDestroyerAdapter struct {
lifecycle *lifecycle.Manager
worktrees *worktree.Manager
}
func (a *environmentDestroyerAdapter) DestroyContainer(ctx context.Context, containerID string) error {
return a.lifecycle.DestroyContainer(ctx, containerID)
}
func (a *environmentDestroyerAdapter) DestroySandbox(ctx context.Context, sandboxID, executionID string) error {
return a.lifecycle.DestroySandbox(ctx, sandboxID, executionID)
}
func (a *environmentDestroyerAdapter) DestroyWorktree(ctx context.Context, worktreeID string) error {
// removeBranch=false: preserve the branch so unpushed work isn't lost.
return a.worktrees.RemoveByID(ctx, worktreeID, false)
}
func (a *environmentDestroyerAdapter) GetContainerLiveStatus(ctx context.Context, containerID string) (*taskservice.ContainerLiveStatus, error) {
live, err := a.lifecycle.GetContainerLiveStatus(ctx, containerID)
if err != nil || live == nil {
return nil, err
}
out := &taskservice.ContainerLiveStatus{
ContainerID: live.ContainerID,
State: live.State,
Status: live.Status,
ExitCode: live.ExitCode,
Health: live.Health,
Missing: live.Missing,
}
if live.StartedAt != nil {
out.StartedAt = live.StartedAt.Format(time.RFC3339)
}
if live.FinishedAt != nil {
out.FinishedAt = live.FinishedAt.Format(time.RFC3339)
}
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
// error so the user knows to push manually.
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(pushCtx, "git", "push")
} else {
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
}