Files
kandev/apps/backend/internal/task/handlers/task_handlers.go
T
José Almeida f169d25b72 fix(executor-profile): live Configured badge + session/load resilience + live container status
Three independent fixes that all surface together while iterating on the
Docker executor flow:

- Remote Credentials card: the per-agent "Configured" / "Not Configured"
  badge was driven by useState that only seeded once on mount. Picking a
  secret in the dropdown updated the parent's `agentEnvVars` map but the
  local `choice` never moved to `"env"`, so the badge stayed grey until
  the page was reloaded. Derive `choice` straight from props every render
  so the badge tracks live state.

- ACP session/load: when the agent process restarted between turns
  (common with claude-agent-acp because its session map is in-memory),
  the host's session/load call failed with JSON-RPC -32002 "Resource not
  found" and the entire launch errored out. Treat that as the same kind
  of "session is gone" signal as -32601 / capability=false and fall back
  to session/new. Worst case the agent loses prior context; best case
  the user just keeps typing.

- Executor Settings popover: dropped Execution ID and Environment ID
  rows (debug-only noise users don't need), kept Container ID + the
  copyable `docker exec -it … bash` line, added a live status badge
  with tones for running / exited / paused / dead / error / missing,
  and a 3-second polling interval so the badge follows the real
  container state. New `GET /api/v1/tasks/:id/environment/live`
  endpoint plumbs Docker `inspect` data through the lifecycle manager
  → task service → handler. ContainerLiveStatus mirror type at the
  service layer keeps lifecycle types out of the public surface.
2026-05-04 21:08:51 +01:00

139 lines
6.2 KiB
Go

package handlers
import (
"context"
"github.com/gin-gonic/gin"
"github.com/kandev/kandev/internal/common/logger"
"github.com/kandev/kandev/internal/orchestrator"
"github.com/kandev/kandev/internal/task/dto"
"github.com/kandev/kandev/internal/task/models"
"github.com/kandev/kandev/internal/task/service"
ws "github.com/kandev/kandev/pkg/websocket"
"go.uber.org/zap"
)
// handlerRepo is the minimal repository interface needed by task handlers.
type handlerRepo interface {
UpsertSessionFileReview(ctx context.Context, review *models.SessionFileReview) error
GetSessionFileReviews(ctx context.Context, sessionID string) ([]*models.SessionFileReview, error)
DeleteSessionFileReviews(ctx context.Context, sessionID string) error
ListTurnsBySession(ctx context.Context, sessionID string) ([]*models.Turn, error)
}
type TaskHandlers struct {
service *service.Service
orchestrator OrchestratorStarter
repo handlerRepo
planService *service.PlanService
onTaskCreatedWithPR func(ctx context.Context, taskID, sessionID, prURL, branch string)
logger *logger.Logger
}
// SetOnTaskCreatedWithPR sets a callback invoked when a task is created with a PR URL
// in one of its repository inputs. The callback runs in a background goroutine.
func (h *TaskHandlers) SetOnTaskCreatedWithPR(fn func(ctx context.Context, taskID, sessionID, prURL, branch string)) {
h.onTaskCreatedWithPR = fn
}
type OrchestratorStarter interface {
// LaunchSession is the unified entry point for all session operations.
LaunchSession(ctx context.Context, req *orchestrator.LaunchSessionRequest) (*orchestrator.LaunchSessionResponse, error)
// EnsureSession returns the task's existing primary/newest session if any,
// otherwise resolves the agent profile server-side and creates one.
EnsureSession(ctx context.Context, taskID string) (*orchestrator.EnsureSessionResponse, error)
}
func NewTaskHandlers(svc *service.Service, orchestrator OrchestratorStarter, repo handlerRepo, planService *service.PlanService, log *logger.Logger) *TaskHandlers {
return &TaskHandlers{
service: svc,
orchestrator: orchestrator,
repo: repo,
planService: planService,
logger: log.WithFields(zap.String("component", "task-task-handlers")),
}
}
func RegisterTaskRoutes(router *gin.Engine, dispatcher *ws.Dispatcher, svc *service.Service, orchestrator OrchestratorStarter, repo handlerRepo, planService *service.PlanService, log *logger.Logger) *TaskHandlers {
handlers := NewTaskHandlers(svc, orchestrator, repo, planService, log)
handlers.registerHTTP(router)
handlers.registerWS(dispatcher)
return handlers
}
func (h *TaskHandlers) registerHTTP(router *gin.Engine) {
api := router.Group("/api/v1")
api.GET("/workflows/:id/tasks", h.httpListTasks)
api.GET("/workspaces/:id/tasks", h.httpListTasksByWorkspace)
api.GET("/tasks/:id", h.httpGetTask)
api.GET("/task-sessions/:id", h.httpGetTaskSession)
api.GET("/tasks/:id/sessions", h.httpListTaskSessions)
api.POST("/tasks/:id/sessions/ensure", h.httpEnsureTaskSession)
api.GET("/tasks/:id/environment", h.httpGetTaskEnvironment)
api.GET("/tasks/:id/environment/live", h.httpGetTaskEnvironmentLive)
api.POST("/tasks/:id/environment/reset", h.httpResetTaskEnvironment)
api.GET("/task-sessions/:id/turns", h.httpListSessionTurns)
api.POST("/tasks", h.httpCreateTask)
api.PATCH("/tasks/:id", h.httpUpdateTask)
api.POST("/tasks/:id/move", h.httpMoveTask)
api.DELETE("/tasks/:id", h.httpDeleteTask)
api.POST("/tasks/:id/archive", h.httpArchiveTask)
api.POST("/tasks/bulk-move", h.httpBulkMoveTasks)
api.GET("/workflows/:id/task-count", h.httpGetWorkflowTaskCount)
api.GET("/workflow/steps/:id/task-count", h.httpGetStepTaskCount)
// Session workflow review endpoints
api.POST("/sessions/:id/approve", h.httpApproveSession)
// Quick chat endpoint - creates ephemeral task with prepared session
api.POST("/workspaces/:id/quick-chat", h.httpStartQuickChat)
// Config chat endpoint - creates ephemeral task with config-mode MCP tools
api.POST("/workspaces/:id/config-chat", h.httpStartConfigChat)
}
func (h *TaskHandlers) registerWS(dispatcher *ws.Dispatcher) {
dispatcher.RegisterFunc(ws.ActionTaskList, h.wsListTasks)
dispatcher.RegisterFunc(ws.ActionTaskCreate, h.wsCreateTask)
dispatcher.RegisterFunc(ws.ActionTaskGet, h.wsGetTask)
dispatcher.RegisterFunc(ws.ActionTaskUpdate, h.wsUpdateTask)
dispatcher.RegisterFunc(ws.ActionTaskDelete, h.wsDeleteTask)
dispatcher.RegisterFunc(ws.ActionTaskMove, h.wsMoveTask)
dispatcher.RegisterFunc(ws.ActionTaskState, h.wsUpdateTaskState)
dispatcher.RegisterFunc(ws.ActionTaskArchive, h.wsArchiveTask)
dispatcher.RegisterFunc(ws.ActionTaskSessionList, h.wsListTaskSessions)
// Git snapshot handler (commits and cumulative diff are handled by agent/handlers/git_handlers.go)
dispatcher.RegisterFunc(ws.ActionSessionGitSnapshots, h.wsGetGitSnapshots)
// Session file review handlers
dispatcher.RegisterFunc(ws.ActionSessionFileReviewGet, h.wsGetSessionFileReviews)
dispatcher.RegisterFunc(ws.ActionSessionFileReviewUpdate, h.wsUpdateSessionFileReview)
dispatcher.RegisterFunc(ws.ActionSessionFileReviewReset, h.wsResetSessionFileReviews)
// Task plan handlers
dispatcher.RegisterFunc(ws.ActionTaskPlanCreate, h.wsCreateTaskPlan)
dispatcher.RegisterFunc(ws.ActionTaskPlanGet, h.wsGetTaskPlan)
dispatcher.RegisterFunc(ws.ActionTaskPlanUpdate, h.wsUpdateTaskPlan)
dispatcher.RegisterFunc(ws.ActionTaskPlanDelete, h.wsDeleteTaskPlan)
dispatcher.RegisterFunc(ws.ActionTaskPlanRevisionsList, h.wsListTaskPlanRevisions)
dispatcher.RegisterFunc(ws.ActionTaskPlanRevisionGet, h.wsGetTaskPlanRevision)
dispatcher.RegisterFunc(ws.ActionTaskPlanRevert, h.wsRevertTaskPlan)
}
// convertToServiceRepos converts dto.TaskRepositoryInput slice to service.TaskRepositoryInput slice.
func convertToServiceRepos(repos []dto.TaskRepositoryInput) []service.TaskRepositoryInput {
result := make([]service.TaskRepositoryInput, len(repos))
for i, r := range repos {
result[i] = service.TaskRepositoryInput{
RepositoryID: r.RepositoryID,
BaseBranch: r.BaseBranch,
CheckoutBranch: r.CheckoutBranch,
LocalPath: r.LocalPath,
Name: r.Name,
DefaultBranch: r.DefaultBranch,
GitHubURL: r.GitHubURL,
}
}
return result
}