d83c1dd982
* feat(diff): use stored base_branch for diff stats + per-task compare picker
Task-card additions/deletions and the Changes panel were computed against a
hardcoded origin/main → master priority list inside agentctl. For tasks
branched off a release/staging branch this inflated the counts by every
commit since the actual fork point, and the Changes panel grouped unrelated
files alongside the task's real work.
This wires the per-repo task_repositories.base_branch end-to-end into the
agentctl WorkspaceTracker so each repo's diff stats resolve against the
recorded base instead of the integration-branch fallback. A picker on the
Changes panel branch hover card lets the user change the base mid-task; the
new value is persisted via PATCH /tasks/:id/repositories/:repo_id, pushed
live to the running agentctl instance, and the session's cached
base_commit_sha is cleared so the commits panel + cumulative diff refetch
against the new base without a session restart.
Falls back to the existing origin/main → master list for legacy tasks
(empty base_branch) and to the branch tip when no merge-base exists with
HEAD (unrelated histories — local rebase backups, etc.) so the stats and
commits panels stay anchored on the same SHA in every failure mode.
* fix(agentctl): sanitize user-controlled base_branch refs before git exec
CodeQL flagged the picker's user-controlled base_branch payload reaching
exec.Command("git", ..., baseBranch) inside workspace_git_cmd.go as a
command-built-from-user-controlled-source vulnerability. A malicious caller
could smuggle a leading-"-" argument like "-upload-pack=..." that git
itself reinterprets as a flag, even though exec.Command keeps args
separate from the shell.
Adds an IsSafeGitRef sanitizer at every boundary the value crosses on its
way to git: the service write path, the agentctl HTTP handlers
(/workspace/base-branches, /git/log, /git/cumulative-diff), and
WorkspaceTracker.SetBaseBranch itself. Unsafe values are rejected at the
service tier and silently downgraded to the no-override fallback inside
agentctl so a misbehaving caller can't half-break the tracker.
* fix(diff): address PR review blockers and CI lint
- Split UpdateRepositoryBaseBranch into validate/load/apply helpers to drop
cyclomatic complexity below the cyclop limit that gated Run Backend Tests.
- Replace direct m.cfg.BaseBranches reads/writes with getBaseBranches /
setBaseBranches under a dedicated RWMutex. UpdateBaseBranches used to
write under repoTrackersMu while rescan + lazy-subpath callers read under
workspaceTrackersMu, leaving an unsynchronized data race on the map.
- Drop the false 'PR target is auto-wired' claim from the MCP tool
description — GitOperator.CreatePR takes baseBranch as an explicit arg
and never reads the tracker's value.
- Picker no-op guard now compares against currentBase instead of storedBase
so selecting the displayed fallback (legacy task before any picker
change) is treated as no-op instead of triggering a spurious save.
- HTTP handler now maps non-validation service errors to 500 instead of
400, classifying via the existing isValidationError helper plus the new
unsafe-git-ref message.
* fix(diff): regex-based ref sanitiser at every git subprocess sink
CodeQL kept flagging workspace_git_cmd.go:43 even after SetBaseBranch
rejected unsafe values — the taint tracker doesn't follow sanitised stores
through struct fields, so it still saw user input flowing into
exec.Command("git", ..., baseBranch).
Switches IsSafeGitRef to a single regex check (a pattern CodeQL recognises
as a sanitiser barrier) and adds SanitizeGitRef calls inline at every
agentctl call site that splices a user-controlled ref into a git arg:
- workspace_git_status.resolveStoredRef (before the rev-parse probes)
- workspace_git_status.computeBaseCommit (before merge-base/rev-parse)
- workspace_git_status.getAheadBehindCounts (before rev-list)
- agentctl/server/api/git.go runGitLogForRepo + handleGitCumulativeDiff
(before computeMergeBase/GetRevParse on the HTTP TargetBranch)
Behaviour is unchanged for valid refs — only narrows the allowlist (now
[A-Za-z0-9_./-]) so the sanitiser barrier is recognisable to static
analysis. SetBaseBranch's field-store sanitiser stays as defence in depth.
* fix(diff): transform sanitiser at every map read for CodeQL taint flow
CodeQL still flagged workspace_git_cmd.go:43 because:
- handleSetBaseBranches used an IsSafeGitRef bool guard before a verbatim
map[k] = v copy. CodeQL recognises regex-transforming sanitisers but not
bool-guarded passthroughs.
- lookupBaseBranch returned m.cfg.BaseBranches[k] verbatim. Even though
the map was sanitised on write, taint flow across map stores + field
stores loses the sanitised state in the analyser.
Switches both sites to the transforming SanitizeGitRef helper so every
read produces a freshly-sanitised value before it flows to a downstream
git argument. Behaviour is unchanged for valid refs.
* fix(diff): regex transformer sanitiser + guard live push from empty map
CodeQL still flagged the previous SanitizeGitRef because it returned the
input string unchanged on success — an identity passthrough that the taint
tracker doesn't recognise as a sanitiser barrier.
Switches to safeGitRefPattern.FindString so the output comes from the
regex match (not the parameter). IsSafeGitRef now wraps SanitizeGitRef so
the predicate and the transformer share one allowlist.
Also addresses two Claude review blockers:
- collectTaskBaseBranches returns a nil/empty map when the task has no
recorded base_branches; pushing that to agentctl wipes every tracker's
override. Now skipped — the DB row is the source of truth for the next
session launch.
- applyBaseBranchSideEffects now runs on context.WithoutCancel so an HTTP
/ WS request cancel after the task_repositories UPDATE commits can't
leave session.base_commit_sha stale + the live agentctl tracker map
un-pushed, drifting from the persisted row.
* fix(diff): share securityutil.IsValidBranchName + harden error classification
CodeQL still flagged the picker's regex sanitiser as taint passthrough.
Refactors SanitizeGitRef / isSafeBaseBranchRef to delegate to the existing
securityutil.IsValidBranchName helper that agentctl's Rebase / Merge /
RenameBranch already use without being flagged. The shared allowlist also
fixes a Claude review blocker: 'feature/@2024' used to pass the service
validator but get dropped by the agentctl-side check at push time,
silently wiping every tracker's override.
Plus the two error-classification blockers Claude raised on the previous
HEAD:
- WS handler (task_ws_handlers.go wsUpdateTaskRepository) now distinguishes
validation errors (surfaced verbatim) from internal faults (opaque
500-style message). HTTP path already did this via the existing
isValidationError helper.
- MCP handler (handlers.handleUpdateRepositoryBaseBranch) gets the same
treatment via a new isValidationError local to the mcp/handlers
package so raw service error strings stop leaking across the MCP
boundary.
* fix(diff): inline securityutil.IsValidBranchName at every git subprocess sink
CodeQL's interprocedural taint tracking wasn't recognising SanitizeGitRef
as a sanitiser even after it delegated to securityutil.IsValidBranchName
— the wrapper helper + map/field hops between source and sink kept the
flow tainted in the analyser.
Inlines the IsValidBranchName allowlist check (already used inline by
Rebase/Merge in git.go without being flagged) at every call site that
splices a user-controlled ref into a git subprocess argument:
- workspace_git_status.resolveStoredRef (before rev-parse --verify)
- workspace_git_status.computeBaseCommit (before merge-base / rev-parse)
- workspace_git_status.getAheadBehindCounts (before rev-list)
- agentctl/server/api/git.go runGitLogForRepo + handleGitCumulativeDiff
- agentctl/server/api/workspace_base_branches.go handleSetBaseBranches
Behaviour unchanged: same allowlist as Rebase / Merge / RenameBranch
already use. SanitizeGitRef / IsSafeGitRef survive as defence-in-depth
helpers for callers that want a one-line check; they delegate to the same
securityutil helper so the rules stay aligned.
* fix(diff): inline regexp.MatchString at every git subprocess sink
CodeQL still flagged workspace_git_cmd.go:43 even with the inline
securityutil.IsValidBranchName helper — the taint tracker apparently does
not follow into helper functions for the go/command-injection rule on
this path.
Hoists the regex to package-scope vars (safeBranchRefPattern in both
process and api packages) and calls regexp.MatchString directly at each
sink site. Behaviour is identical to securityutil.IsValidBranchName; only
the call form changes.
* fix(diff): SHA-shape allowlist on BaseCommit before downstream git diff
CodeQL still flagged workspace_git_cmd.go:43 because update.BaseCommit
is the OUTPUT of an earlier merge-base / rev-parse call whose argument
list contained a user-controlled branch ref — the analyser treats that
command's output as still tainted even when the input ref was sanitised.
Adds an inline 40-hex SHA-shape allowlist check in enrichWithBranchDiff
right before `git diff --numstat <update.BaseCommit>` so the sanitiser
barrier sits in the same function as the next subprocess call. Behaviour
is unchanged: merge-base / rev-parse already produce SHA-shaped output.
* fix(diff): async tracker refresh + tighten init spread order
Two CodeRabbit/Claude review fixes:
- UpdateBaseBranches stamps each tracker's new baseBranch synchronously
then runs RefreshGitStatus on a background goroutine instead of inside
the picker-save HTTP handler. Per-tracker git subprocesses can each
take ~3-5 calls; serialising them on the request goroutine made the
PATCH response wait for every refresh to finish. The picker UI re-fetches
via the existing WS stream once Refresh emits, so the handler doesn't
need to block.
- updateTaskRepositoryBaseBranch now spreads options.init BEFORE the
required method/body fields so an upstream caller's init overrides
can't replace the PATCH method or the base_branch payload. Matches
the convention deleteTask / moveTask already follow.
* fix(diff): narrow mcp isValidationError + opaque 500 + post-sanitize log count
Three final Claude review threads on the latest commit:
- mcp/handlers isValidationError drops the broad 'invalid' substring so
DB / IO errors whose messages happen to contain 'invalid' don't
misclassify as ErrorCodeValidation.
- task_http_handlers httpUpdateTaskRepository now logs the raw service
error server-side and returns an opaque 'failed to update task
repository' on the 500 path. Stops potential DB / IO detail leakage
through the HTTP boundary.
- workspace_base_branches debug log reports accepted + rejected counts
(post-sanitisation) instead of the pre-filter total so the metric
actually reflects what hit UpdateBaseBranches.
---------
Co-authored-by: Kandev Agent <agent@kandev.dev>
1377 lines
49 KiB
Go
1377 lines
49 KiB
Go
package handlers
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"strconv"
|
|
"strings"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"github.com/kandev/kandev/internal/common/constants"
|
|
"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"
|
|
"github.com/kandev/kandev/internal/worktree"
|
|
v1 "github.com/kandev/kandev/pkg/api/v1"
|
|
"go.uber.org/zap"
|
|
)
|
|
|
|
func (h *TaskHandlers) httpListTasks(c *gin.Context) {
|
|
tasks, err := h.service.ListTasks(c.Request.Context(), c.Param("id"))
|
|
if err != nil {
|
|
handleNotFound(c, h.logger, err, "tasks not found")
|
|
return
|
|
}
|
|
taskDTOs := make([]dto.TaskDTO, 0, len(tasks))
|
|
for _, task := range tasks {
|
|
taskDTOs = append(taskDTOs, dto.FromTask(task))
|
|
}
|
|
c.JSON(http.StatusOK, dto.ListTasksResponse{
|
|
Tasks: taskDTOs,
|
|
Total: len(tasks),
|
|
})
|
|
}
|
|
|
|
func (h *TaskHandlers) httpListTasksByWorkspace(c *gin.Context) {
|
|
page := 1
|
|
pageSize := 50
|
|
|
|
if p := c.Query("page"); p != "" {
|
|
if parsed, err := strconv.Atoi(p); err == nil && parsed > 0 {
|
|
page = parsed
|
|
}
|
|
}
|
|
if ps := c.Query("page_size"); ps != "" {
|
|
if parsed, err := strconv.Atoi(ps); err == nil && parsed > 0 && parsed <= 100 {
|
|
pageSize = parsed
|
|
}
|
|
}
|
|
|
|
query := c.Query("query")
|
|
workflowID := c.Query("workflow_id")
|
|
repositoryID := c.Query("repository_id")
|
|
includeArchived := c.Query("include_archived") == queryValueTrue
|
|
includeEphemeral := c.Query("include_ephemeral") == queryValueTrue
|
|
onlyEphemeral := c.Query("only_ephemeral") == queryValueTrue
|
|
excludeConfig := c.Query("exclude_config") == queryValueTrue
|
|
|
|
tasks, total, err := h.service.ListTasksByWorkspace(
|
|
c.Request.Context(), c.Param("id"), workflowID, repositoryID, query, page, pageSize, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig,
|
|
)
|
|
if err != nil {
|
|
handleNotFound(c, h.logger, err, "tasks not found")
|
|
return
|
|
}
|
|
|
|
taskDTOs, err := h.toTaskDTOsWithSessionInfo(c.Request.Context(), tasks)
|
|
if err != nil {
|
|
h.logger.Error("failed to enrich tasks with session info", zap.Error(err))
|
|
handleNotFound(c, h.logger, err, "tasks not found")
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, dto.ListTasksResponse{
|
|
Tasks: taskDTOs,
|
|
Total: total,
|
|
})
|
|
}
|
|
|
|
// buildTaskDTOsWithSessionInfo converts tasks to DTOs enriched with primary
|
|
// session IDs, session counts, and review status. Uses BatchGetSessionsForTasks
|
|
// to derive the primary session ID and session count in a single round trip,
|
|
// then calls GetPrimarySessionInfoForTasks for the executor type/name fields
|
|
// — those are populated by a LEFT JOIN to the executors table inside that
|
|
// method (the persisted ExecutorSnapshot JSON uses different keys), so the
|
|
// batch loader alone can't supply them without a regression. Two queries
|
|
// total, down from three pre-batch.
|
|
func buildTaskDTOsWithSessionInfo(ctx context.Context, svc *service.Service, tasks []*models.Task) ([]dto.TaskDTO, error) {
|
|
if len(tasks) == 0 {
|
|
return []dto.TaskDTO{}, nil
|
|
}
|
|
taskIDs := make([]string, len(tasks))
|
|
for i, t := range tasks {
|
|
taskIDs[i] = t.ID
|
|
}
|
|
sessionsByTask, err := svc.BatchGetSessionsForTasks(ctx, taskIDs)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
primarySessionInfoMap, err := svc.GetPrimarySessionInfoForTasks(ctx, taskIDs)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
result := make([]dto.TaskDTO, 0, len(tasks))
|
|
for _, task := range tasks {
|
|
sessions := sessionsByTask[task.ID]
|
|
var primarySessionID *string
|
|
for _, s := range sessions {
|
|
if s.IsPrimary {
|
|
id := s.ID
|
|
primarySessionID = &id
|
|
break
|
|
}
|
|
}
|
|
var sessionCount *int
|
|
if n := len(sessions); n > 0 {
|
|
sessionCount = &n
|
|
}
|
|
si := extractSessionInfo(primarySessionInfoMap[task.ID])
|
|
result = append(result, dto.FromTaskWithSessionInfo(
|
|
task,
|
|
primarySessionID,
|
|
sessionCount,
|
|
si.reviewStatus,
|
|
si.executorID,
|
|
si.executorType,
|
|
si.executorName,
|
|
si.agentName,
|
|
si.workingDirectory,
|
|
si.sessionState,
|
|
))
|
|
}
|
|
return result, nil
|
|
}
|
|
|
|
type sessionInfoFields struct {
|
|
reviewStatus models.ReviewStatus
|
|
sessionState *string
|
|
executorID *string
|
|
executorType *string
|
|
executorName *string
|
|
agentName *string
|
|
workingDirectory *string
|
|
}
|
|
|
|
func extractSessionInfo(info *models.TaskSession) sessionInfoFields {
|
|
var si sessionInfoFields
|
|
if info == nil {
|
|
return si
|
|
}
|
|
si.reviewStatus = info.ReviewStatus
|
|
if info.State != "" {
|
|
val := string(info.State)
|
|
si.sessionState = &val
|
|
}
|
|
if info.ExecutorID != "" {
|
|
val := info.ExecutorID
|
|
si.executorID = &val
|
|
}
|
|
if info.ExecutorSnapshot != nil {
|
|
if t, ok := info.ExecutorSnapshot["executor_type"].(string); ok && t != "" {
|
|
si.executorType = &t
|
|
}
|
|
if n, ok := info.ExecutorSnapshot["executor_name"].(string); ok && n != "" {
|
|
si.executorName = &n
|
|
}
|
|
}
|
|
if info.AgentProfileSnapshot != nil {
|
|
if name, ok := info.AgentProfileSnapshot["name"].(string); ok && name != "" {
|
|
si.agentName = &name
|
|
}
|
|
}
|
|
if info.RepositorySnapshot != nil {
|
|
if path, ok := info.RepositorySnapshot["path"].(string); ok && path != "" {
|
|
si.workingDirectory = &path
|
|
}
|
|
}
|
|
return si
|
|
}
|
|
|
|
func (h *TaskHandlers) toTaskDTOsWithSessionInfo(ctx context.Context, tasks []*models.Task) ([]dto.TaskDTO, error) {
|
|
return buildTaskDTOsWithSessionInfo(ctx, h.service, tasks)
|
|
}
|
|
|
|
func (h *TaskHandlers) httpGetTask(c *gin.Context) {
|
|
task, err := h.service.GetTask(c.Request.Context(), c.Param("id"))
|
|
if err != nil {
|
|
handleNotFound(c, h.logger, err, "task not found")
|
|
return
|
|
}
|
|
dtos, err := buildTaskDTOsWithSessionInfo(c.Request.Context(), h.service, []*models.Task{task})
|
|
if err != nil {
|
|
h.logger.Error("failed to build task DTO with session info", zap.Error(err))
|
|
c.JSON(http.StatusOK, dto.FromTask(task))
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, dtos[0])
|
|
}
|
|
|
|
func (h *TaskHandlers) httpListTaskSessions(c *gin.Context) {
|
|
ctx := c.Request.Context()
|
|
sessions, err := h.service.ListTaskSessions(ctx, c.Param("id"))
|
|
if err != nil {
|
|
handleNotFound(c, h.logger, err, "task sessions not found")
|
|
return
|
|
}
|
|
sessionDTOs := make([]dto.TaskSessionSummaryDTO, 0, len(sessions))
|
|
ids := make([]string, 0, len(sessions))
|
|
for _, session := range sessions {
|
|
sessionDTOs = append(sessionDTOs, dto.FromTaskSessionSummary(session))
|
|
ids = append(ids, session.ID)
|
|
}
|
|
// Resolve the per-session tool_call counts so the frontend can render
|
|
// the "ran N commands" segment without fetching every session's full
|
|
// message list. Best-effort: a count failure leaves CommandCount at 0.
|
|
if counts, cErr := h.repo.CountToolCallMessagesBySession(ctx, ids); cErr == nil {
|
|
for i := range sessionDTOs {
|
|
sessionDTOs[i].CommandCount = counts[sessionDTOs[i].ID]
|
|
}
|
|
} else {
|
|
h.logger.Warn("count tool calls failed", zap.Error(cErr))
|
|
}
|
|
c.JSON(http.StatusOK, dto.ListTaskSessionSummariesResponse{
|
|
Sessions: sessionDTOs,
|
|
Total: len(sessionDTOs),
|
|
})
|
|
}
|
|
|
|
// httpEnsureTaskSession returns the task's existing primary/newest session if any,
|
|
// otherwise resolves the agent profile server-side and creates one (prepare or
|
|
// start, depending on the workflow step). Idempotent under concurrent calls.
|
|
func (h *TaskHandlers) httpEnsureTaskSession(c *gin.Context) {
|
|
taskID := c.Param("id")
|
|
if taskID == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "task id is required"})
|
|
return
|
|
}
|
|
resp, err := h.orchestrator.EnsureSession(c.Request.Context(), taskID)
|
|
if err != nil {
|
|
handleNotFound(c, h.logger, err, "task not found")
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, resp)
|
|
}
|
|
|
|
func (h *TaskHandlers) httpGetTaskSession(c *gin.Context) {
|
|
session, err := h.service.GetTaskSession(c.Request.Context(), c.Param("id"))
|
|
if err != nil {
|
|
handleNotFound(c, h.logger, err, "task session not found")
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, dto.GetTaskSessionResponse{
|
|
Session: dto.FromTaskSession(session),
|
|
})
|
|
}
|
|
|
|
func (h *TaskHandlers) httpListSessionTurns(c *gin.Context) {
|
|
sessionID := c.Param("id")
|
|
if sessionID == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "session id is required"})
|
|
return
|
|
}
|
|
|
|
turns, err := h.repo.ListTurnsBySession(c.Request.Context(), sessionID)
|
|
if err != nil {
|
|
h.logger.Error("failed to list turns", zap.String("session_id", sessionID), zap.Error(err))
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list turns"})
|
|
return
|
|
}
|
|
|
|
// Convert to DTO
|
|
turnDTOs := make([]dto.TurnDTO, 0, len(turns))
|
|
for _, turn := range turns {
|
|
turnDTOs = append(turnDTOs, dto.FromTurn(turn))
|
|
}
|
|
|
|
c.JSON(http.StatusOK, dto.ListTurnsResponse{Turns: turnDTOs, Total: len(turnDTOs)})
|
|
}
|
|
|
|
func (h *TaskHandlers) httpApproveSession(c *gin.Context) {
|
|
result, err := h.service.ApproveSession(c.Request.Context(), c.Param("id"))
|
|
if err != nil {
|
|
h.logger.Error("failed to approve session", zap.String("session_id", c.Param("id")), zap.Error(err))
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
resp := dto.ApproveSessionResponse{
|
|
Success: true,
|
|
Session: dto.FromTaskSession(result.Session),
|
|
}
|
|
if result.WorkflowStep != nil {
|
|
resp.WorkflowStep = dto.FromWorkflowStep(result.WorkflowStep)
|
|
}
|
|
c.JSON(http.StatusOK, resp)
|
|
}
|
|
|
|
func (h *TaskHandlers) httpGetWorkflowTaskCount(c *gin.Context) {
|
|
count, err := h.service.CountTasksByWorkflow(c.Request.Context(), c.Param("id"))
|
|
if err != nil {
|
|
h.logger.Error("failed to count tasks by workflow", zap.Error(err))
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to count tasks"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, dto.TaskCountResponse{TaskCount: count})
|
|
}
|
|
|
|
func (h *TaskHandlers) httpGetStepTaskCount(c *gin.Context) {
|
|
count, err := h.service.CountTasksByWorkflowStep(c.Request.Context(), c.Param("id"))
|
|
if err != nil {
|
|
h.logger.Error("failed to count tasks by step", zap.Error(err))
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to count tasks"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, dto.TaskCountResponse{TaskCount: count})
|
|
}
|
|
|
|
type httpBulkMoveTasksRequest struct {
|
|
SourceWorkflowID string `json:"source_workflow_id"`
|
|
SourceStepID string `json:"source_step_id,omitempty"`
|
|
TargetWorkflowID string `json:"target_workflow_id"`
|
|
TargetStepID string `json:"target_step_id"`
|
|
TaskIDs []string `json:"task_ids,omitempty"`
|
|
}
|
|
|
|
func (h *TaskHandlers) httpBulkMoveTasks(c *gin.Context) {
|
|
var body httpBulkMoveTasksRequest
|
|
if err := c.ShouldBindJSON(&body); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
|
|
return
|
|
}
|
|
if body.TargetWorkflowID == "" || body.TargetStepID == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "target_workflow_id and target_step_id are required"})
|
|
return
|
|
}
|
|
if len(body.TaskIDs) > 0 {
|
|
h.httpBulkMoveSelectedTasks(c, body)
|
|
return
|
|
}
|
|
if body.SourceWorkflowID == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "source_workflow_id, target_workflow_id, and target_step_id are required"})
|
|
return
|
|
}
|
|
result, err := h.service.BulkMoveTasks(
|
|
c.Request.Context(),
|
|
body.SourceWorkflowID, body.SourceStepID,
|
|
body.TargetWorkflowID, body.TargetStepID,
|
|
)
|
|
if err != nil {
|
|
h.logger.Error("failed to bulk move tasks", zap.Error(err))
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to bulk move tasks"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, dto.BulkMoveTasksResponse{MovedCount: result.MovedCount})
|
|
}
|
|
|
|
func (h *TaskHandlers) httpBulkMoveSelectedTasks(c *gin.Context, body httpBulkMoveTasksRequest) {
|
|
result, err := h.service.BulkMoveSelectedTasks(
|
|
c.Request.Context(),
|
|
body.TaskIDs,
|
|
body.TargetWorkflowID,
|
|
body.TargetStepID,
|
|
)
|
|
if err != nil {
|
|
handleSelectedMoveError(c, h.logger, err)
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, dto.BulkMoveTasksResponse{MovedCount: result.MovedCount})
|
|
}
|
|
|
|
type httpTaskRepositoryInput struct {
|
|
RepositoryID string `json:"repository_id"`
|
|
BaseBranch string `json:"base_branch"`
|
|
CheckoutBranch string `json:"checkout_branch"`
|
|
LocalPath string `json:"local_path"`
|
|
Name string `json:"name"`
|
|
DefaultBranch string `json:"default_branch"`
|
|
GitHubURL string `json:"github_url"`
|
|
|
|
// Fresh-branch flow (local executor only): when FreshBranch is true the
|
|
// handler discards uncommitted changes in the local clone and creates
|
|
// NewBranchName from BaseBranch before the task is persisted.
|
|
// ConfirmDiscard must be true if the working tree is dirty; otherwise
|
|
// the request is rejected with 409 + the dirty file list.
|
|
// ConsentedDirtyFiles is the dirty-file list the UI showed the user;
|
|
// the backend rejects with 409 if the live dirty set has any path
|
|
// that wasn't on this list, protecting against silent loss of files
|
|
// that became dirty between preflight and execution.
|
|
FreshBranch bool `json:"fresh_branch,omitempty"`
|
|
NewBranchName string `json:"new_branch_name,omitempty"`
|
|
ConfirmDiscard bool `json:"confirm_discard,omitempty"`
|
|
ConsentedDirtyFiles []string `json:"consented_dirty_files,omitempty"`
|
|
}
|
|
|
|
type httpCreateTaskRequest struct {
|
|
WorkspaceID string `json:"workspace_id"`
|
|
WorkflowID string `json:"workflow_id"`
|
|
WorkflowStepID string `json:"workflow_step_id"`
|
|
Title string `json:"title"`
|
|
Description string `json:"description,omitempty"`
|
|
Priority string `json:"priority,omitempty"`
|
|
State *v1.TaskState `json:"state,omitempty"`
|
|
Repositories []httpTaskRepositoryInput `json:"repositories,omitempty"`
|
|
Position int `json:"position,omitempty"`
|
|
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
|
StartAgent bool `json:"start_agent,omitempty"`
|
|
PrepareSession bool `json:"prepare_session,omitempty"`
|
|
AgentProfileID string `json:"agent_profile_id,omitempty"`
|
|
ExecutorID string `json:"executor_id,omitempty"`
|
|
ExecutorProfileID string `json:"executor_profile_id,omitempty"`
|
|
PlanMode bool `json:"plan_mode,omitempty"`
|
|
Attachments []v1.MessageAttachment `json:"attachments,omitempty"`
|
|
ParentID string `json:"parent_id,omitempty"`
|
|
WorkspacePath string `json:"workspace_path,omitempty"`
|
|
BlockedBy []string `json:"blocked_by,omitempty"`
|
|
ProjectID string `json:"project_id,omitempty"`
|
|
// Office task-handoffs phase 5 — workspace policy. Optional; same
|
|
// shape as the MCP create_task_kandev fields.
|
|
WorkspaceMode string `json:"workspace_mode,omitempty"`
|
|
WorkspaceGroupID string `json:"workspace_group_id,omitempty"`
|
|
DefaultChildWorkspace string `json:"default_child_workspace,omitempty"`
|
|
DefaultChildOrdering string `json:"default_child_ordering,omitempty"`
|
|
}
|
|
|
|
type createTaskResponse struct {
|
|
dto.TaskDTO
|
|
TaskSessionID string `json:"session_id,omitempty"`
|
|
AgentExecutionID string `json:"agent_execution_id,omitempty"`
|
|
}
|
|
|
|
const (
|
|
maxCreateTaskAttachments = 10
|
|
maxAttachmentDataBytes = 10 * 1024 * 1024 // 10 MB base64 string length cap
|
|
)
|
|
|
|
var allowedAttachmentTypes = map[string]struct{}{
|
|
"image": {},
|
|
"audio": {},
|
|
"resource": {},
|
|
}
|
|
|
|
func validateAttachments(items []v1.MessageAttachment) error {
|
|
if len(items) > maxCreateTaskAttachments {
|
|
return fmt.Errorf("too many attachments (max %d)", maxCreateTaskAttachments)
|
|
}
|
|
var totalSize int
|
|
for i, a := range items {
|
|
typ := strings.TrimSpace(a.Type)
|
|
if _, ok := allowedAttachmentTypes[typ]; !ok {
|
|
return fmt.Errorf("attachment[%d] has unsupported type %q", i, typ)
|
|
}
|
|
if strings.TrimSpace(a.MimeType) == "" {
|
|
return fmt.Errorf("attachment[%d] mime_type is required", i)
|
|
}
|
|
if len(a.Data) == 0 {
|
|
return fmt.Errorf("attachment[%d] data is required", i)
|
|
}
|
|
if len(a.Data) > maxAttachmentDataBytes {
|
|
return fmt.Errorf("attachment[%d] data exceeds size limit", i)
|
|
}
|
|
totalSize += len(a.Data)
|
|
}
|
|
if totalSize > maxAttachmentDataBytes {
|
|
return fmt.Errorf("total attachment size exceeds limit")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (h *TaskHandlers) httpCreateTask(c *gin.Context) {
|
|
var body httpCreateTaskRequest
|
|
if err := c.ShouldBindJSON(&body); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
|
|
return
|
|
}
|
|
if err := validateAttachments(body.Attachments); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
if body.WorkspaceID == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "workspace_id is required"})
|
|
return
|
|
}
|
|
if (body.StartAgent || body.PrepareSession) && body.AgentProfileID == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "agent_profile_id is required to start agent"})
|
|
return
|
|
}
|
|
|
|
repos, ok := convertCreateTaskRepositories(c, body.Repositories)
|
|
if !ok {
|
|
return
|
|
}
|
|
|
|
// Always persist profile IDs in task metadata so they can be used as the
|
|
// task's "default" agent profile. This is needed both for deferred agent start
|
|
// (handleTaskMovedNoSession) and for reverting to the default agent when a
|
|
// workflow step has no agent_profile override.
|
|
if body.AgentProfileID != "" {
|
|
if body.Metadata == nil {
|
|
body.Metadata = make(map[string]interface{})
|
|
}
|
|
body.Metadata[models.MetaKeyAgentProfileID] = body.AgentProfileID
|
|
if body.ExecutorProfileID != "" {
|
|
body.Metadata[models.MetaKeyExecutorProfileID] = body.ExecutorProfileID
|
|
}
|
|
}
|
|
|
|
title := strings.TrimSpace(body.Title)
|
|
description := strings.TrimSpace(body.Description)
|
|
|
|
// Office task-handoffs phase 5: resolve workspace policy from the
|
|
// request + parent task, merge into Metadata, and remember it so the
|
|
// post-create attach can record group membership / blocker chain.
|
|
wsPolicy, policyErr := h.resolveWorkspacePolicy(c.Request.Context(), body)
|
|
if policyErr != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": policyErr.Error()})
|
|
return
|
|
}
|
|
metadata := mergeWorkspaceMetadata(body.Metadata, wsPolicy.MetadataBlock())
|
|
|
|
task, err := h.service.CreateTask(c.Request.Context(), &service.CreateTaskRequest{
|
|
WorkspaceID: body.WorkspaceID,
|
|
WorkflowID: body.WorkflowID,
|
|
WorkflowStepID: body.WorkflowStepID,
|
|
Title: title,
|
|
Description: description,
|
|
Priority: body.Priority,
|
|
State: body.State,
|
|
Repositories: convertToServiceRepos(repos),
|
|
Position: body.Position,
|
|
Metadata: metadata,
|
|
PlanMode: body.PlanMode && !body.StartAgent,
|
|
ParentID: body.ParentID,
|
|
WorkspacePath: body.WorkspacePath,
|
|
BlockedBy: body.BlockedBy,
|
|
ProjectID: body.ProjectID,
|
|
})
|
|
if err != nil {
|
|
handleNotFound(c, h.logger, err, "task not created")
|
|
return
|
|
}
|
|
|
|
if h.handoffSvc != nil && wsPolicy.NeedsAttachment() {
|
|
if attachErr := h.handoffSvc.AttachWorkspacePolicy(c.Request.Context(), task.ID, body.ParentID, wsPolicy); attachErr != nil {
|
|
h.logger.Error("attach workspace policy; rolling back task creation",
|
|
zap.String("task_id", task.ID), zap.Error(attachErr))
|
|
if delErr := h.service.DeleteTask(c.Request.Context(), task.ID); delErr != nil {
|
|
h.logger.Error("rollback delete failed; task left in inconsistent state",
|
|
zap.String("task_id", task.ID), zap.Error(delErr))
|
|
}
|
|
c.JSON(http.StatusInternalServerError, gin.H{
|
|
"error": "failed to attach workspace policy: " + attachErr.Error(),
|
|
})
|
|
return
|
|
}
|
|
}
|
|
|
|
if !h.commitFreshBranch(c, task.ID, title, body.WorkspaceID, body.Repositories, repos) {
|
|
return
|
|
}
|
|
|
|
taskDTO := dto.FromTask(task)
|
|
response := createTaskResponse{TaskDTO: taskDTO}
|
|
// Use the backend-resolved workflow step ID (from the created task) instead of the request's
|
|
resolvedStepID := taskDTO.WorkflowStepID
|
|
h.handlePostCreateTaskSession(c, &response, taskDTO.ID, taskDTO.Description, body, resolvedStepID)
|
|
|
|
// Associate PR with task if any repository input contains a PR URL
|
|
h.associatePRFromRepoInputs(taskDTO.ID, response.TaskSessionID, body.Repositories)
|
|
|
|
c.JSON(http.StatusOK, response)
|
|
}
|
|
|
|
// commitFreshBranch wraps the post-CreateTask fresh-branch sequence: run the
|
|
// destructive checkout, compensate by deleting the task if it fails, then
|
|
// persist the rewritten BaseBranch onto the now-existing task. Returns false
|
|
// when an HTTP error response was already written.
|
|
func (h *TaskHandlers) commitFreshBranch(
|
|
c *gin.Context,
|
|
taskID, title, workspaceID string,
|
|
inputs []httpTaskRepositoryInput,
|
|
repos []dto.TaskRepositoryInput,
|
|
) bool {
|
|
hasFresh := false
|
|
for _, raw := range inputs {
|
|
if raw.FreshBranch {
|
|
hasFresh = true
|
|
break
|
|
}
|
|
}
|
|
if !hasFresh {
|
|
// No fresh-branch opt-in — repos were already persisted by CreateTask,
|
|
// so skip the destructive checkout and the DELETE+INSERT rewrite.
|
|
return true
|
|
}
|
|
if !h.applyFreshBranch(c, title, inputs, repos) {
|
|
if delErr := h.service.DeleteTask(c.Request.Context(), taskID); delErr != nil {
|
|
h.logger.Warn("failed to compensate by deleting task after fresh-branch failure",
|
|
zap.String("task_id", taskID), zap.Error(delErr))
|
|
}
|
|
return false
|
|
}
|
|
// Persist the rewritten BaseBranch (set by applyFreshBranch) onto the task.
|
|
// applyFreshBranch already mutated the git repo, so we can't roll back —
|
|
// but we must surface a 5xx so the caller knows the DB still references
|
|
// the user's original fork point. Otherwise every subsequent session
|
|
// resume would silently check out the old branch and abandon the new one.
|
|
if err := h.service.ReplaceTaskRepositories(c.Request.Context(), taskID, workspaceID, convertToServiceRepos(repos)); err != nil {
|
|
h.logger.Error("failed to persist fresh-branch base branch onto task",
|
|
zap.String("task_id", taskID), zap.Error(err))
|
|
c.JSON(http.StatusInternalServerError, gin.H{
|
|
"error": "fresh branch was created but the task record could not be updated; please check the repository",
|
|
})
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
// applyFreshBranch executes the fresh-branch flow for any local-executor
|
|
// repository inputs that opted in. Mutates `repos[i].BaseBranch` to the
|
|
// newly-created branch on success so the persisted task uses it as the
|
|
// effective base branch on every session resume. Writes the appropriate
|
|
// HTTP error response and returns false on failure.
|
|
//
|
|
// When the caller doesn't supply NewBranchName, the backend generates a
|
|
// semantic name from the task title (matching the worktree executor's
|
|
// branch-naming) so the user only has to flip a switch.
|
|
func (h *TaskHandlers) applyFreshBranch(c *gin.Context, taskTitle string, inputs []httpTaskRepositoryInput, repos []dto.TaskRepositoryInput) bool {
|
|
ctx := c.Request.Context()
|
|
for i, raw := range inputs {
|
|
if !raw.FreshBranch {
|
|
continue
|
|
}
|
|
repoPath, ok := h.resolveLocalRepoPath(c, raw)
|
|
if !ok {
|
|
return false
|
|
}
|
|
baseBranch := raw.BaseBranch
|
|
if baseBranch == "" {
|
|
// User didn't pick one — fall back to the repo's checked-out branch.
|
|
baseBranch, _ = h.service.LocalRepositoryCurrentBranch(ctx, repoPath)
|
|
}
|
|
newBranch := resolveFreshBranchName(raw.NewBranchName, taskTitle)
|
|
err := h.service.PerformFreshBranch(ctx, service.FreshBranchRequest{
|
|
RepoPath: repoPath,
|
|
BaseBranch: baseBranch,
|
|
NewBranch: newBranch,
|
|
ConfirmDiscard: raw.ConfirmDiscard,
|
|
ConsentedDirtyFiles: raw.ConsentedDirtyFiles,
|
|
})
|
|
if err != nil {
|
|
h.respondFreshBranchError(c, err)
|
|
return false
|
|
}
|
|
repos[i].BaseBranch = newBranch
|
|
repos[i].CheckoutBranch = ""
|
|
}
|
|
return true
|
|
}
|
|
|
|
// resolveFreshBranchName returns the user-supplied branch name when present,
|
|
// otherwise generates one from the task title using the same semantic name +
|
|
// random-suffix scheme as the worktree executor. Returns an empty string only
|
|
// when both the raw name and the task title would produce nothing useful;
|
|
// PerformFreshBranch's sanitizeGitRef rejects that downstream.
|
|
func resolveFreshBranchName(rawNewBranch, taskTitle string) string {
|
|
if name := strings.TrimSpace(rawNewBranch); name != "" {
|
|
return name
|
|
}
|
|
return worktree.SemanticWorktreeName(taskTitle, worktree.SmallSuffix(3))
|
|
}
|
|
|
|
func (h *TaskHandlers) resolveLocalRepoPath(c *gin.Context, raw httpTaskRepositoryInput) (string, bool) {
|
|
if raw.LocalPath != "" {
|
|
return raw.LocalPath, true
|
|
}
|
|
if raw.RepositoryID == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "fresh_branch requires repository_id or local_path"})
|
|
return "", false
|
|
}
|
|
repo, err := h.service.GetRepository(c.Request.Context(), raw.RepositoryID)
|
|
if err != nil || repo == nil || repo.LocalPath == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "repository has no local path"})
|
|
return "", false
|
|
}
|
|
return repo.LocalPath, true
|
|
}
|
|
|
|
func (h *TaskHandlers) respondFreshBranchError(c *gin.Context, err error) {
|
|
var dirty *service.ErrDirtyWorkingTree
|
|
if errors.As(err, &dirty) {
|
|
c.JSON(http.StatusConflict, gin.H{
|
|
"error": "working tree has uncommitted changes",
|
|
"dirty_files": dirty.DirtyFiles,
|
|
})
|
|
return
|
|
}
|
|
if errors.Is(err, service.ErrPathNotAllowed) {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "repository path is not within an allowed root"})
|
|
return
|
|
}
|
|
if errors.Is(err, service.ErrInvalidGitRef) {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
if errors.Is(err, service.ErrFreshBranchCheckout) {
|
|
// git checkout failure (e.g. branch already exists, base branch unknown).
|
|
// Surface the underlying message — it tells the user what to fix.
|
|
c.JSON(http.StatusUnprocessableEntity, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
if errors.Is(err, service.ErrPartialDiscard) {
|
|
// Tracked files already gone, untracked survived. The user needs to
|
|
// know they have lost work before retrying — never a generic 500.
|
|
h.logger.Error("partial discard during fresh-branch", zap.Error(err))
|
|
c.JSON(http.StatusInternalServerError, gin.H{
|
|
"error": "tracked changes were discarded but git clean failed; untracked files remain — inspect the repo before retrying",
|
|
"partial": true,
|
|
})
|
|
return
|
|
}
|
|
h.logger.Error("fresh branch checkout failed", zap.Error(err))
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to prepare fresh branch"})
|
|
}
|
|
|
|
// convertCreateTaskRepositories converts httpTaskRepositoryInput slice to dto.TaskRepositoryInput slice.
|
|
// Returns (nil, false) and writes a 400 response if any entry is missing both repository_id and local_path.
|
|
func convertCreateTaskRepositories(c *gin.Context, inputs []httpTaskRepositoryInput) ([]dto.TaskRepositoryInput, bool) {
|
|
var repos []dto.TaskRepositoryInput
|
|
for _, r := range inputs {
|
|
if r.RepositoryID == "" && r.LocalPath == "" && r.GitHubURL == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "repository_id, local_path, or github_url is required"})
|
|
return nil, false
|
|
}
|
|
repos = append(repos, dto.TaskRepositoryInput{
|
|
RepositoryID: r.RepositoryID,
|
|
BaseBranch: r.BaseBranch,
|
|
CheckoutBranch: r.CheckoutBranch,
|
|
LocalPath: r.LocalPath,
|
|
Name: r.Name,
|
|
DefaultBranch: r.DefaultBranch,
|
|
GitHubURL: r.GitHubURL,
|
|
})
|
|
}
|
|
return repos, true
|
|
}
|
|
|
|
// associatePRFromRepoInputs checks if any repository input contains a GitHub PR URL
|
|
// (e.g., github.com/owner/repo/pull/123) and fires the onTaskCreatedWithPR callback
|
|
// in a background goroutine to associate the PR with the newly created task.
|
|
func (h *TaskHandlers) associatePRFromRepoInputs(taskID, sessionID string, repos []httpTaskRepositoryInput) {
|
|
if h.onTaskCreatedWithPR == nil {
|
|
return
|
|
}
|
|
for _, r := range repos {
|
|
if r.GitHubURL != "" && strings.Contains(r.GitHubURL, "/pull/") {
|
|
prURL := r.GitHubURL
|
|
branch := r.CheckoutBranch
|
|
go h.onTaskCreatedWithPR(context.Background(), taskID, sessionID, prURL, branch)
|
|
return // only one PR per task
|
|
}
|
|
}
|
|
}
|
|
|
|
// handlePostCreateTaskSession prepares or starts an agent session after a task is created,
|
|
// depending on the PrepareSession and StartAgent flags in the request body.
|
|
func (h *TaskHandlers) handlePostCreateTaskSession(
|
|
c *gin.Context,
|
|
response *createTaskResponse,
|
|
taskID, description string,
|
|
body httpCreateTaskRequest,
|
|
resolvedStepID string,
|
|
) {
|
|
if h.orchestrator == nil || body.AgentProfileID == "" {
|
|
return
|
|
}
|
|
if body.PrepareSession && !body.StartAgent {
|
|
resp, err := h.orchestrator.LaunchSession(c.Request.Context(), &orchestrator.LaunchSessionRequest{
|
|
TaskID: taskID,
|
|
Intent: orchestrator.IntentPrepare,
|
|
AgentProfileID: body.AgentProfileID,
|
|
ExecutorID: body.ExecutorID,
|
|
ExecutorProfileID: body.ExecutorProfileID,
|
|
WorkflowStepID: resolvedStepID,
|
|
LaunchWorkspace: true,
|
|
})
|
|
if err != nil {
|
|
h.logger.Error("failed to prepare session for task", zap.Error(err), zap.String("task_id", taskID))
|
|
} else {
|
|
response.TaskSessionID = resp.SessionID
|
|
}
|
|
} else if body.StartAgent {
|
|
h.startAgentForNewTask(c.Request.Context(), response, taskID, description, body, resolvedStepID)
|
|
}
|
|
}
|
|
|
|
// startAgentForNewTask prepares a session and launches the agent asynchronously for a
|
|
// newly created task when start_agent is requested. It populates response.TaskSessionID
|
|
// on success.
|
|
func (h *TaskHandlers) startAgentForNewTask(
|
|
ctx context.Context,
|
|
response *createTaskResponse,
|
|
taskID, description string,
|
|
body httpCreateTaskRequest,
|
|
resolvedStepID string,
|
|
) {
|
|
// Create session entry synchronously so we can return the session ID immediately.
|
|
// Skip workspace launch — the start intent will handle it in the background goroutine.
|
|
// This prevents blocking for 30-60s on remote executors (sprites, remote_docker).
|
|
prepResp, err := h.orchestrator.LaunchSession(ctx, &orchestrator.LaunchSessionRequest{
|
|
TaskID: taskID,
|
|
Intent: orchestrator.IntentPrepare,
|
|
AgentProfileID: body.AgentProfileID,
|
|
ExecutorID: body.ExecutorID,
|
|
ExecutorProfileID: body.ExecutorProfileID,
|
|
WorkflowStepID: resolvedStepID,
|
|
})
|
|
if err != nil {
|
|
h.logger.Error("failed to prepare session for task", zap.Error(err), zap.String("task_id", taskID))
|
|
return
|
|
}
|
|
sessionID := prepResp.SessionID
|
|
response.TaskSessionID = sessionID
|
|
|
|
// Launch agent asynchronously so the HTTP request can return immediately.
|
|
// The frontend will receive WebSocket updates when the agent actually starts.
|
|
go func() {
|
|
startCtx, cancel := context.WithTimeout(context.Background(), constants.AgentLaunchTimeout)
|
|
defer cancel()
|
|
launchResp, err := h.orchestrator.LaunchSession(startCtx, &orchestrator.LaunchSessionRequest{
|
|
TaskID: taskID,
|
|
Intent: orchestrator.IntentStartCreated,
|
|
SessionID: sessionID,
|
|
AgentProfileID: body.AgentProfileID,
|
|
Prompt: description,
|
|
SkipMessageRecord: false,
|
|
PlanMode: body.PlanMode,
|
|
Attachments: body.Attachments,
|
|
})
|
|
if err != nil {
|
|
h.logger.Error("failed to start agent for task (async)", zap.Error(err), zap.String("task_id", taskID), zap.String("session_id", sessionID))
|
|
return
|
|
}
|
|
h.logger.Info("agent started for task (async)",
|
|
zap.String("task_id", taskID),
|
|
zap.String("session_id", launchResp.SessionID),
|
|
zap.String("execution_id", launchResp.AgentExecutionID))
|
|
}()
|
|
}
|
|
|
|
type httpUpdateTaskRequest struct {
|
|
Title *string `json:"title,omitempty"`
|
|
Description *string `json:"description,omitempty"`
|
|
Priority *string `json:"priority,omitempty"`
|
|
State *v1.TaskState `json:"state,omitempty"`
|
|
Repositories []httpTaskRepositoryInput `json:"repositories,omitempty"`
|
|
Position *int `json:"position,omitempty"`
|
|
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
|
}
|
|
|
|
func (h *TaskHandlers) httpUpdateTask(c *gin.Context) {
|
|
var body httpUpdateTaskRequest
|
|
if err := c.ShouldBindJSON(&body); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
|
|
return
|
|
}
|
|
|
|
// Convert repositories if provided
|
|
var repos []dto.TaskRepositoryInput
|
|
if body.Repositories != nil {
|
|
for _, r := range body.Repositories {
|
|
repos = append(repos, dto.TaskRepositoryInput{
|
|
RepositoryID: r.RepositoryID,
|
|
BaseBranch: r.BaseBranch,
|
|
LocalPath: r.LocalPath,
|
|
Name: r.Name,
|
|
DefaultBranch: r.DefaultBranch,
|
|
})
|
|
}
|
|
}
|
|
|
|
// Trim strings like the controller did
|
|
var title *string
|
|
if body.Title != nil {
|
|
trimmed := strings.TrimSpace(*body.Title)
|
|
title = &trimmed
|
|
}
|
|
var description *string
|
|
if body.Description != nil {
|
|
trimmed := strings.TrimSpace(*body.Description)
|
|
description = &trimmed
|
|
}
|
|
|
|
task, err := h.service.UpdateTask(c.Request.Context(), c.Param("id"), &service.UpdateTaskRequest{
|
|
Title: title,
|
|
Description: description,
|
|
Priority: body.Priority,
|
|
State: body.State,
|
|
Repositories: convertToServiceRepos(repos),
|
|
Position: body.Position,
|
|
Metadata: body.Metadata,
|
|
})
|
|
if err != nil {
|
|
handleNotFound(c, h.logger, err, "task not updated")
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, dto.FromTask(task))
|
|
}
|
|
|
|
type httpUpdateTaskRepositoryRequest struct {
|
|
BaseBranch string `json:"base_branch"`
|
|
}
|
|
|
|
// httpUpdateTaskRepository handles PATCH /tasks/:id/repositories/:repo_id.
|
|
// Today it only mutates base_branch; future per-row fields can be added on
|
|
// httpUpdateTaskRepositoryRequest. Mirrors the WS / MCP paths through the
|
|
// same service method so all three surfaces stay in sync.
|
|
func (h *TaskHandlers) httpUpdateTaskRepository(c *gin.Context) {
|
|
var body httpUpdateTaskRepositoryRequest
|
|
if err := c.ShouldBindJSON(&body); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
|
|
return
|
|
}
|
|
taskRepo, err := h.service.UpdateRepositoryBaseBranch(c.Request.Context(), service.UpdateRepositoryBaseBranchRequest{
|
|
TaskID: c.Param("id"),
|
|
TaskRepositoryID: c.Param("repo_id"),
|
|
BaseBranch: body.BaseBranch,
|
|
})
|
|
if err != nil {
|
|
if errors.Is(err, service.ErrTaskRepositoryNotFound) {
|
|
c.JSON(http.StatusNotFound, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
// Distinguish caller-fixable validation failures (required field
|
|
// missing, unsafe ref name, …) from server-side faults (DB write
|
|
// errors propagated up from the service). Anything that matches a
|
|
// known validation message stays at 400; everything else escalates
|
|
// to 500 so client retries don't mask backend regressions.
|
|
if isValidationError(err) {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
// Avoid echoing raw service errors on the 500 path — DB / IO
|
|
// failures can carry connection strings, table names, or stack
|
|
// traces. Log the detail server-side; return an opaque message.
|
|
h.logger.Error("update task repository failed",
|
|
zap.String("task_id", c.Param("id")),
|
|
zap.String("repo_id", c.Param("repo_id")),
|
|
zap.Error(err))
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to update task repository"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, taskRepo)
|
|
}
|
|
|
|
type httpMoveTaskRequest struct {
|
|
WorkflowID string `json:"workflow_id"`
|
|
WorkflowStepID string `json:"workflow_step_id"`
|
|
Position int `json:"position"`
|
|
}
|
|
|
|
func (h *TaskHandlers) httpMoveTask(c *gin.Context) {
|
|
var body httpMoveTaskRequest
|
|
if err := c.ShouldBindJSON(&body); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
|
|
return
|
|
}
|
|
if body.WorkflowID == "" || body.WorkflowStepID == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "workflow_id and workflow_step_id are required"})
|
|
return
|
|
}
|
|
result, err := h.service.MoveTaskWithOptions(
|
|
c.Request.Context(), c.Param("id"),
|
|
body.WorkflowID, body.WorkflowStepID, body.Position,
|
|
service.MoveTaskOptions{AllowActivePrimarySession: true},
|
|
)
|
|
if err != nil {
|
|
handleSelectedMoveError(c, h.logger, err)
|
|
return
|
|
}
|
|
|
|
response := dto.MoveTaskResponse{
|
|
Task: dto.FromTask(result.Task),
|
|
}
|
|
if result.WorkflowStep != nil {
|
|
response.WorkflowStep = dto.FromWorkflowStep(result.WorkflowStep)
|
|
}
|
|
c.JSON(http.StatusOK, response)
|
|
}
|
|
|
|
func (h *TaskHandlers) httpDeleteTask(c *gin.Context) {
|
|
deleteCtx, cancel := context.WithTimeout(context.Background(), constants.TaskDeleteTimeout)
|
|
defer cancel()
|
|
taskID := c.Param("id")
|
|
cascade := cascadeQueryParam(c)
|
|
// Office task-handoffs phase 6: route through HandoffService.DeleteTaskTree
|
|
// when wired so descendant runs are cancelled, group memberships are
|
|
// released with reason=deleted, and the cleanup state machine fires.
|
|
if h.handoffSvc != nil {
|
|
if _, err := h.handoffSvc.DeleteTaskTree(deleteCtx, taskID, cascade); err != nil {
|
|
handleNotFound(c, h.logger, err, "task not deleted")
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, dto.SuccessResponse{Success: true})
|
|
return
|
|
}
|
|
if err := h.service.DeleteTask(deleteCtx, taskID); err != nil {
|
|
handleNotFound(c, h.logger, err, "task not deleted")
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, dto.SuccessResponse{Success: true})
|
|
}
|
|
|
|
func (h *TaskHandlers) httpArchiveTask(c *gin.Context) {
|
|
taskID := c.Param("id")
|
|
cascade := cascadeQueryParam(c)
|
|
// Office task-handoffs phase 6: when a HandoffService is wired,
|
|
// archive the whole subtree under a single cascade ID so
|
|
// descendants get tagged for scoped unarchive AND workspace-group
|
|
// memberships are released. When HandoffService is unconfigured
|
|
// (legacy / tests) fall back to the single-task path.
|
|
if h.handoffSvc != nil {
|
|
if _, err := h.handoffSvc.ArchiveTaskTree(c.Request.Context(), taskID, cascade); err != nil {
|
|
handleNotFound(c, h.logger, err, "task not archived")
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, dto.SuccessResponse{Success: true})
|
|
return
|
|
}
|
|
if err := h.service.ArchiveTask(c.Request.Context(), taskID); err != nil {
|
|
handleNotFound(c, h.logger, err, "task not archived")
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, dto.SuccessResponse{Success: true})
|
|
}
|
|
|
|
// cascadeQueryParam returns whether the archive/delete request asked to
|
|
// cascade into subtasks. Default is false — subtasks are preserved
|
|
// unless the client explicitly opts in via ?cascade=true.
|
|
func cascadeQueryParam(c *gin.Context) bool {
|
|
return strings.EqualFold(c.Query("cascade"), "true")
|
|
}
|
|
|
|
// httpTaskSubtaskCount returns the count of direct, non-archived,
|
|
// non-ephemeral subtasks for a task. Used by the frontend's archive /
|
|
// delete confirmation dialogs to decide whether to render the
|
|
// "Also archive/delete subtasks" checkbox.
|
|
func (h *TaskHandlers) httpTaskSubtaskCount(c *gin.Context) {
|
|
taskID := c.Param("id")
|
|
children, err := h.repo.ListChildren(c.Request.Context(), taskID)
|
|
if err != nil {
|
|
// Don't surface the raw repo error to the client — it can leak
|
|
// driver / SQL details. Log the full reason server-side, return
|
|
// a generic 500 to the caller.
|
|
h.logger.Error("failed to list direct subtasks",
|
|
zap.String("task_id", taskID), zap.Error(err))
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to count subtasks"})
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{"count": len(children)})
|
|
}
|
|
|
|
// httpUnarchiveTask routes through HandoffService.UnarchiveTaskTree so
|
|
// every task this cascade archived (and only those) is restored. The
|
|
// handler returns 503 when no HandoffService is wired since unarchive
|
|
// is meaningless without the cascade infrastructure.
|
|
func (h *TaskHandlers) httpUnarchiveTask(c *gin.Context) {
|
|
if h.handoffSvc == nil {
|
|
c.JSON(http.StatusServiceUnavailable, gin.H{
|
|
"error": "unarchive requires office task-handoffs to be configured",
|
|
})
|
|
return
|
|
}
|
|
taskID := c.Param("id")
|
|
outcome, err := h.handoffSvc.UnarchiveTaskTree(c.Request.Context(), taskID)
|
|
if err != nil {
|
|
handleNotFound(c, h.logger, err, "task not unarchived")
|
|
return
|
|
}
|
|
c.JSON(http.StatusOK, gin.H{
|
|
"success": true,
|
|
"cascade_id": outcome.CascadeID,
|
|
"unarchived_ids": outcome.ArchivedTaskIDs,
|
|
"skipped_ids": outcome.SkippedTaskIDs,
|
|
"affected_group_ids": outcome.ReleasedGroupIDs,
|
|
})
|
|
}
|
|
|
|
// httpStartQuickChatRequest is the request body for starting a quick chat session.
|
|
type httpStartQuickChatRequest struct {
|
|
Title string `json:"title,omitempty"`
|
|
RepositoryID string `json:"repository_id,omitempty"`
|
|
AgentProfileID string `json:"agent_profile_id,omitempty"`
|
|
ExecutorID string `json:"executor_id,omitempty"`
|
|
Prompt string `json:"prompt,omitempty"`
|
|
LocalPath string `json:"local_path,omitempty"`
|
|
RepositoryName string `json:"repository_name,omitempty"`
|
|
DefaultBranch string `json:"default_branch,omitempty"`
|
|
BaseBranch string `json:"base_branch,omitempty"`
|
|
LaunchImmediately bool `json:"launch_immediately,omitempty"`
|
|
}
|
|
|
|
// httpStartQuickChatResponse is returned when a quick chat session is created.
|
|
type httpStartQuickChatResponse struct {
|
|
TaskID string `json:"task_id"`
|
|
SessionID string `json:"session_id"`
|
|
}
|
|
|
|
// quickChatParams holds resolved parameters for creating a quick chat session.
|
|
type quickChatParams struct {
|
|
agentProfileID string
|
|
executorID string
|
|
title string
|
|
repos []service.TaskRepositoryInput
|
|
metadata map[string]interface{}
|
|
}
|
|
|
|
// buildQuickChatRepositories builds the repository input list from the request.
|
|
func (body *httpStartQuickChatRequest) buildRepositories() []service.TaskRepositoryInput {
|
|
if body.RepositoryID == "" && body.LocalPath == "" {
|
|
return nil
|
|
}
|
|
return []service.TaskRepositoryInput{{
|
|
RepositoryID: body.RepositoryID,
|
|
LocalPath: body.LocalPath,
|
|
Name: body.RepositoryName,
|
|
DefaultBranch: body.DefaultBranch,
|
|
BaseBranch: body.BaseBranch,
|
|
}}
|
|
}
|
|
|
|
// resolveParams resolves agent/executor IDs and builds metadata for quick chat.
|
|
func (body *httpStartQuickChatRequest) resolveParams(workspace *models.Workspace) quickChatParams {
|
|
agentProfileID := body.AgentProfileID
|
|
if agentProfileID == "" && workspace.DefaultAgentProfileID != nil {
|
|
agentProfileID = *workspace.DefaultAgentProfileID
|
|
}
|
|
executorID := body.ExecutorID
|
|
if executorID == "" && workspace.DefaultExecutorID != nil {
|
|
executorID = *workspace.DefaultExecutorID
|
|
}
|
|
|
|
metadata := make(map[string]interface{})
|
|
if agentProfileID != "" {
|
|
metadata["agent_profile_id"] = agentProfileID
|
|
}
|
|
if executorID != "" {
|
|
metadata["executor_id"] = executorID
|
|
}
|
|
|
|
title := body.Title
|
|
if title == "" {
|
|
title = "Quick Chat"
|
|
}
|
|
|
|
return quickChatParams{
|
|
agentProfileID: agentProfileID,
|
|
executorID: executorID,
|
|
title: title,
|
|
repos: body.buildRepositories(),
|
|
metadata: metadata,
|
|
}
|
|
}
|
|
|
|
// httpStartQuickChat creates an ephemeral task and prepares a session for quick chat.
|
|
func (h *TaskHandlers) httpStartQuickChat(c *gin.Context) {
|
|
workspaceID := c.Param("id")
|
|
var body httpStartQuickChatRequest
|
|
if err := c.ShouldBindJSON(&body); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
|
|
return
|
|
}
|
|
|
|
ctx := c.Request.Context()
|
|
|
|
workspace, err := h.service.GetWorkspace(ctx, workspaceID)
|
|
if err != nil {
|
|
handleNotFound(c, h.logger, err, "workspace not found")
|
|
return
|
|
}
|
|
|
|
params := body.resolveParams(workspace)
|
|
if params.agentProfileID == "" {
|
|
h.logger.Error("no agent profile configured for quick chat", zap.String("workspace_id", workspaceID))
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "workspace has no default agent profile configured"})
|
|
return
|
|
}
|
|
|
|
task, err := h.service.CreateTask(ctx, &service.CreateTaskRequest{
|
|
WorkspaceID: workspaceID,
|
|
Title: params.title,
|
|
Description: body.Prompt,
|
|
Repositories: params.repos,
|
|
IsEphemeral: true,
|
|
Metadata: params.metadata,
|
|
})
|
|
if err != nil {
|
|
h.logger.Error("failed to create ephemeral task", zap.Error(err))
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create quick chat"})
|
|
return
|
|
}
|
|
|
|
// Eager-init: launch the agent process up-front so ACP `initialize` + `session/new`
|
|
// fire and the agent emits available_commands/modes/models. This populates the
|
|
// slash menu, mode dropdown, and model selector before the user sends any prompt.
|
|
resp, err := h.orchestrator.LaunchSession(ctx, &orchestrator.LaunchSessionRequest{
|
|
TaskID: task.ID,
|
|
Intent: orchestrator.IntentStart,
|
|
AgentProfileID: params.agentProfileID,
|
|
ExecutorID: params.executorID,
|
|
})
|
|
if err != nil {
|
|
// Rollback: delete the ephemeral task to prevent orphans. Use a fresh
|
|
// background context — the request context may already be cancelled
|
|
// (e.g. client aborted, deadline exceeded), and we still want cleanup
|
|
// to run. TaskDeleteTimeout matches the other DeleteTask call sites
|
|
// in this file so a future change to the constant covers this path too.
|
|
rollbackCtx, cancel := context.WithTimeout(context.Background(), constants.TaskDeleteTimeout)
|
|
defer cancel()
|
|
if deleteErr := h.service.DeleteTask(rollbackCtx, task.ID); deleteErr != nil {
|
|
h.logger.Error("failed to rollback quick chat task",
|
|
zap.String("task_id", task.ID),
|
|
zap.Error(deleteErr))
|
|
}
|
|
h.logger.Error("failed to start quick chat session", zap.Error(err), zap.String("task_id", task.ID))
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to start session"})
|
|
return
|
|
}
|
|
|
|
h.logger.Info("quick chat session created",
|
|
zap.String("task_id", task.ID),
|
|
zap.String("session_id", resp.SessionID),
|
|
zap.String("workspace_id", workspaceID))
|
|
|
|
c.JSON(http.StatusOK, httpStartQuickChatResponse{
|
|
TaskID: task.ID,
|
|
SessionID: resp.SessionID,
|
|
})
|
|
}
|
|
|
|
// httpStartConfigChatRequest is the request body for starting a config chat session.
|
|
type httpStartConfigChatRequest struct {
|
|
AgentProfileID string `json:"agent_profile_id,omitempty"`
|
|
ExecutorID string `json:"executor_id,omitempty"`
|
|
Prompt string `json:"prompt,omitempty"`
|
|
}
|
|
|
|
// httpStartConfigChat creates an ephemeral task with config_mode and prepares a session.
|
|
// The session will have config MCP tools (workflow, agent, MCP management) instead of
|
|
// the normal kanban/plan tools used for task-solving agents.
|
|
// resolveConfigChatDefaults resolves the agent profile ID, executor ID, and task
|
|
// metadata for a config chat session. Profile priority: request → workspace config → workspace default.
|
|
func resolveConfigChatDefaults(body httpStartConfigChatRequest, ws *models.Workspace) (agentProfileID, executorID string, metadata map[string]interface{}) {
|
|
agentProfileID = body.AgentProfileID
|
|
if agentProfileID == "" && ws.DefaultConfigAgentProfileID != nil {
|
|
agentProfileID = *ws.DefaultConfigAgentProfileID
|
|
}
|
|
if agentProfileID == "" && ws.DefaultAgentProfileID != nil {
|
|
agentProfileID = *ws.DefaultAgentProfileID
|
|
}
|
|
executorID = body.ExecutorID
|
|
if executorID == "" && ws.DefaultExecutorID != nil {
|
|
executorID = *ws.DefaultExecutorID
|
|
}
|
|
metadata = map[string]interface{}{
|
|
"config_mode": true,
|
|
"agent_profile_id": agentProfileID,
|
|
}
|
|
if executorID != "" {
|
|
metadata["executor_id"] = executorID
|
|
}
|
|
return agentProfileID, executorID, metadata
|
|
}
|
|
|
|
func (h *TaskHandlers) httpStartConfigChat(c *gin.Context) {
|
|
workspaceID := c.Param("id")
|
|
var body httpStartConfigChatRequest
|
|
if err := c.ShouldBindJSON(&body); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"})
|
|
return
|
|
}
|
|
|
|
ctx := c.Request.Context()
|
|
|
|
workspace, err := h.service.GetWorkspace(ctx, workspaceID)
|
|
if err != nil {
|
|
handleNotFound(c, h.logger, err, "workspace not found")
|
|
return
|
|
}
|
|
|
|
agentProfileID, executorID, metadata := resolveConfigChatDefaults(body, workspace)
|
|
if agentProfileID == "" {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": "no agent profile configured — set a default agent profile in workspace settings"})
|
|
return
|
|
}
|
|
|
|
task, err := h.service.CreateTask(ctx, &service.CreateTaskRequest{
|
|
WorkspaceID: workspaceID,
|
|
Title: "Config Chat",
|
|
Description: body.Prompt,
|
|
IsEphemeral: true,
|
|
Metadata: metadata,
|
|
})
|
|
if err != nil {
|
|
h.logger.Error("failed to create config chat task", zap.Error(err))
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create config chat"})
|
|
return
|
|
}
|
|
|
|
resp, err := h.orchestrator.LaunchSession(ctx, &orchestrator.LaunchSessionRequest{
|
|
TaskID: task.ID,
|
|
Intent: orchestrator.IntentPrepare,
|
|
AgentProfileID: agentProfileID,
|
|
ExecutorID: executorID,
|
|
})
|
|
if err != nil {
|
|
h.deleteTaskOnError(task.ID, "config chat", err)
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to prepare session"})
|
|
return
|
|
}
|
|
|
|
sessionID := resp.SessionID
|
|
|
|
// If a prompt was provided, launch the agent asynchronously so it starts
|
|
// processing immediately. The frontend receives WS updates when it starts.
|
|
if body.Prompt != "" {
|
|
go h.launchConfigChatAgent(task.ID, sessionID, agentProfileID, body.Prompt)
|
|
}
|
|
|
|
h.logger.Info("config chat session created",
|
|
zap.String("task_id", task.ID),
|
|
zap.String("session_id", sessionID),
|
|
zap.String("workspace_id", workspaceID))
|
|
|
|
c.JSON(http.StatusOK, httpStartQuickChatResponse{
|
|
TaskID: task.ID,
|
|
SessionID: sessionID,
|
|
})
|
|
}
|
|
|
|
func (h *TaskHandlers) deleteTaskOnError(taskID, label string, err error) {
|
|
if deleteErr := h.service.DeleteTask(context.Background(), taskID); deleteErr != nil {
|
|
h.logger.Error("failed to rollback "+label+" task",
|
|
zap.String("task_id", taskID), zap.Error(deleteErr))
|
|
}
|
|
h.logger.Error("failed to prepare "+label+" session",
|
|
zap.Error(err), zap.String("task_id", taskID))
|
|
}
|
|
|
|
func (h *TaskHandlers) launchConfigChatAgent(
|
|
taskID, sessionID, agentProfileID, prompt string,
|
|
) {
|
|
startCtx, cancel := context.WithTimeout(
|
|
context.Background(), constants.AgentLaunchTimeout,
|
|
)
|
|
defer cancel()
|
|
launchResp, err := h.orchestrator.LaunchSession(startCtx, &orchestrator.LaunchSessionRequest{
|
|
TaskID: taskID,
|
|
Intent: orchestrator.IntentStartCreated,
|
|
SessionID: sessionID,
|
|
AgentProfileID: agentProfileID,
|
|
Prompt: prompt,
|
|
})
|
|
if err != nil {
|
|
h.logger.Error("failed to start config chat agent",
|
|
zap.Error(err), zap.String("task_id", taskID),
|
|
zap.String("session_id", sessionID))
|
|
return
|
|
}
|
|
h.logger.Info("config chat agent started",
|
|
zap.String("task_id", taskID),
|
|
zap.String("session_id", launchResp.SessionID),
|
|
zap.String("execution_id", launchResp.AgentExecutionID))
|
|
}
|