Files
kandev/apps/backend/internal/orchestrator/task_operations.go
T
José Almeida f1da9644f4 feat: agent-native config mode (#396)
* feat: add MCP mode pipeline for config vs task tool registration

Thread McpMode field through the entire instance creation chain:
CreateInstanceRequest → InstanceOverrides → InstanceConfig → MCP Server.
This allows config-mode MCP sessions to register a different set of
tools than the default task-mode sessions.

* feat: add config-mode MCP tools and agentctl handlers

Register config-mode tools (workflow steps, agents, MCP config, tasks)
when MCP server mode is "config". Add 16 new WS action constants and
agentctl-side handlers that forward tool calls to the backend via the
existing BackendClient channel.

* feat: add backend MCP handlers for config-mode operations

Add backend WebSocket handlers for workflow step CRUD, agent CRUD,
MCP config get/update, and task move/delete/archive/state operations.
Wire config dependencies via SetConfigDeps pattern to avoid breaking
the existing NewHandlers constructor.

* feat: add config-mode system prompt and unit tests

Add ConfigContext system prompt listing all config-mode MCP tools.
Add unit tests for mode-based tool registration, agentctl config
handler forwarding, backend handler validation, and system prompt
content.

* test: add exhaustive E2E tests for config-mode MCP handlers

38 end-to-end tests covering the full handler → service → DB pipeline
for all 16 config-mode operations: workflow step CRUD, agent CRUD,
agent profiles, MCP config, and task management (move, delete, archive,
update state). Includes handler registration verification and two
full pipeline integration tests.

* fix: remove E2E test that depends on agent CLIs installed in CI

TestE2E_Agent_CreateMultipleAndList tried to create claude-code and
codex agents, which aren't available in CI. Agents are unique by type
ID so creating duplicates also fails. Removed the test since
CreateAndList already validates the create+list flow.

* test: remove Go E2E tests for config-mode handlers

Replacing with Playwright E2E tests.

* test: add Playwright E2E tests for config-mode features

13 tests covering workflow steps, task operations, agent/profile
settings pages, MCP config, and workflow settings round-trips.

* feat: add dynamic MCP mode reconfiguration for agentctl instances

Add SetMode() to the MCP server that clears and re-registers tools for
the new mode. Expose it via PUT /api/v1/mcp/mode on per-instance servers,
a SetMcpMode client method, and a lifecycle Manager.SetMcpMode wrapper.

This enables switching from task to config MCP tools on workspaces that
were prepared before plan_mode was set on the session.

* feat: wire McpMode through executor launch and resume pipelines

Add McpMode to LaunchOptions so callers can set it at launch time.
StartTask and StartTaskWithSession now pass McpMode="config" when
plan mode is active. startAgentOnExistingWorkspace reconfigures the
MCP server via SetMcpMode before starting the agent subprocess.

The AgentManagerClient interface gains SetMcpMode; the lifecycle
adapter, executor, and all mock implementations are updated.

* fix: pass plan_mode from workflow step when auto-starting moved tasks

handleTaskMovedNoSession was hardcoding planMode=false when calling
StartTask. Now it loads the target step and checks for enable_plan_mode
in on_enter actions, passing the correct value so config-mode MCP tools
are registered for the agent.

* test: fix config-mode E2E tests and add SetMcpMode mock stubs

- Add SetMcpMode stubs to all AgentManager mock implementations
- Fix strict mode violations with { exact: true } on tool name assertions
- Expand collapsed tool call groups before asserting individual names
- Remove temporary diagnostic code

* fix: address CodeRabbit review comments

- Add servers parameter to update_mcp_config tool schema
- Add mutex protection to SetMode for thread safety
- Create session before building prompt so config context has session ID
- Fix inconsistent ask_user_question tool name reference (use _kandev suffix)

* refactor: use canonical ws.ActionMCP constants and handle marshal errors

- Import ActionMCP* constants from pkg/websocket instead of duplicating
  them locally in config_handlers.go and handlers.go
- Handle json.MarshalIndent error in forwardToBackend instead of ignoring it

* fix: extract McpModeConfig constant and fix Prettier formatting

- Add McpModeConfig constant to avoid repeated "config" string (goconst)
- Fix Prettier formatting in config-management E2E spec

* fix: validate task state before update and strengthen sysprompt tests

- Add TaskState validation in handleUpdateTaskState to return proper
  validation error instead of internal error for invalid states
- Strengthen format-contract assertions (exact %s counts, no %! markers)
- Extract repeated test data into constants per project guidelines

* refactor: decouple config MCP mode from plan_mode, use session metadata

Replace plan_mode-based config MCP activation with config_mode in
session metadata. Add isConfigModeSession() helper used across
executor_execute, executor_interaction, and executor_resume.
Propagate task.Metadata to session.Metadata in PrepareSession so
config_mode flows from task creation through to the agent launch.

* refactor: remove task tools from config MCP mode and update sysprompt

Remove task management tools (list_tasks, move_task, delete_task,
archive_task) from ModeConfig registration — they remain available in
ModeTask. Update ConfigContext system prompt to remove task tool docs
and add example requests section. Update MCP server tests for new tool
count (18→14) and remove deleted task handler tests.

* feat: add config-chat endpoint and workspace config agent profile

Add default_config_agent_profile_id column to workspaces with SQLite
migration. Add POST /workspaces/:id/config-chat endpoint that creates
an ephemeral task with config_mode metadata and starts a session with
config MCP tools. Extract resolveConfigChatDefaults helper to stay
within lint complexity limits.

* feat: add config chat UI with workspace settings integration

Add config chat modal component and hook for starting config sessions.
Add configChat state slice with open/close actions. Add workspace API
client for config-chat endpoint. Add configuration agent profile
selector to workspace settings form. Add config chat button to
settings layout sidebar.

* test: rewrite config-mode E2E tests to use metadata and session_id

Rewrite config-management E2E tests to use createTaskWithAgent with
config_mode metadata instead of a custom fetch helper. Fix navigation
to use task.session_id instead of task.id. Add metadata parameter
support to ApiClient.createTaskWithAgent.

* fix: use floating FAB for config chat and pass default agent profile

Move config chat button from header to a floating action button in the
bottom-right corner with a sparkles icon. Pass the workspace's default
agent profile ID when opening the config chat to avoid "no agent
profile configured" error. Add default_config_agent_profile_id to
workspace slice type.

* feat: async agent launch for config-chat and extract helpers

The config-chat endpoint now launches the agent asynchronously when a
prompt is provided, matching the start_agent flow used by task creation.
Extract deleteTaskOnError and launchConfigChatAgent helpers. Remove
LaunchWorkspace from prepare step to avoid blocking.

* feat: first-interaction agent profile selection for config chat

Open the config chat modal immediately on FAB click. If no default
config agent profile is set, the empty state now shows a profile
selector before starting. The selected profile is saved as the
workspace default_config_agent_profile_id for future sessions.

* test: fix config E2E tests — remove duplicate method, use real tools

Remove duplicate startConfigChat method in ApiClient that overrode the
correct 3-param signature. Replace invalid create_agent test (requires
registered agent type) with update_agent test. Remove fragile tool calls
group UI assertion from multi-tool test.

* fix: resolve 'no active session' error in config chat

Add openConfigChatModal action that only sets isOpen and workspaceId
without touching sessionId. Previously, open() called openConfigChat
with empty sessionId which was truthy, causing QuickChatContent to
render with an invalid session.

* feat: add minimal toolbar mode for config chat input

Thread minimalToolbar prop through ChatInputArea → ChatInputContainer →
ChatInputBody → ChatInputToolbar → QuickChatContent. When enabled,
renders only the submit/cancel button, hiding plan toggle, MCP
indicator, context popover, model selector, and other controls.

* feat: replace config chat dialog with floating popover panel

Replace Dialog with Popover from @kandev/ui so the config chat floats
up from the FAB button. Reduce FAB size to h-12/w-12 with larger h-7/w-7
icon. Rename tooltip to "Configuration Chat". Remove standalone
ConfigChatFAB component from settings layout.

* feat: filter config chat tasks from quick chat listing

Add exclude_config query parameter to ListTasksByWorkspace that filters
out tasks with metadata.config_mode=true. Apply it in the quick chat
sessions API call to prevent config chat tasks from appearing as tabs.

* refactor: move config agent profile setting to agents page

Remove the Configuration Agent Profile selector from workspace settings
and add a dedicated ConfigChatAgentSection to the agents settings page
with auto-save on change.

* feat: redesign config chat empty state with inline text input

Replace clickable template buttons with subtle suggestion hints that
fill the textarea on click and disappear once the user starts typing.
Add a persistent Textarea + send button at the bottom so users can
type directly without clicking templates. This prevents the "no active
session" error since QuickChatContent only renders after startSession
succeeds.

* fix: config chat UX polish — non-clickable suggestions, profile persistence

- Make suggestion prompts purely visual (non-interactive text hints)
- Update workspace store after saving config agent profile so the
  profile selector doesn't reappear on subsequent opens
- Use useAppStoreApi for store access in callbacks

* fix: add inline error display and prevent accidental popover dismiss

- Show API errors inline below the input instead of via toast (which
  can be hidden behind the popover)
- Prevent popover from closing on outside click via onInteractOutside,
  so the user doesn't lose their typed input or active session
- Surface error state from useConfigChat hook to the empty state UI

* fix: use config-specific placeholder in config chat input

Add placeholderOverride prop through ChatInputArea and QuickChatContent
so the config chat shows "Ask anything about your configuration..."
instead of the default "Continue working on the task..." placeholder.

* feat: add default_config_agent_profile_id to workspace DTO and API

Wire the field through WorkspaceDTO, FromWorkspace(), HTTP/WS request
structs, service layer, and public API types so the config chat default
profile persists across page reloads and SSR hydration.

* feat: add config chat store actions and prompt delivery via WS

Add configChat slice actions (open, close, rename, tab management),
pendingPrompt state in useConfigChat hook, and initialPrompt support
in QuickChatContent so prompts are delivered via WS after subscription
is established rather than via HTTP (avoiding race condition).

* fix: resolve dual store issue and message fetch race condition

Replace StateProvider with StateHydrator in settings layout to prevent
a shadow Zustand store that intercepted WS events. Fix message fetch
race condition by merging WS-delivered messages with fetch results
instead of replacing them.

* feat: make config chat global with command panel integration

Add ConfigChatProvider at root layout so the popover is available on all
pages. FAB button only visible on settings pages; hidden anchor on other
pages for popover positioning. Add "Configuration Chat" command to the
command panel (Cmd+K). Add close button and header bar to the popover.

* test: add E2E tests for config chat popover and command panel

Add tests for opening config chat via FAB on settings page (with full
agent response flow) and opening via command panel on kanban page.
Fix api-client endpoint and add workspace update fields for E2E setup.

* fix: compress props destructuring to satisfy max-lines-per-function lint

Rebase merged both sides' additions into ChatInputEditorArea and
ChatInputToolbar, pushing them over the 100-line function limit.
Use object parameter with compact destructuring to reduce line count.

* fix: register config task tools and add exhaustive E2E coverage

Config-mode MCP task tools (list_tasks, move_task, delete_task,
archive_task) were defined but never registered — registerConfigTaskTools()
was never called in registerTools(). Fixed the registration and expanded
E2E tests from 5 to 15, covering all testable config-mode MCP tools
(workflow, agent, MCP config, and task management) with API-side
verification of side effects.

* feat: replace create/delete agent with create/delete agent profile in config mode

Agent creation/deletion via MCP isn't practical since agents map to
registered types. Replace with create_agent_profile and
delete_agent_profile tools that manage the per-agent configuration
presets users actually need to work with. Wires full chain: agentctl
MCP tools → WS actions → backend handlers → controller layer.

* chore: fix Prettier formatting

* fix: compress props destructuring to satisfy max-lines-per-function lint

* test: update MCP tests for agent profile tools and correct config tool count

* fix: address CodeRabbit review — normalize MCP mode, set default, consolidate tests

* fix: address CodeRabbit review — error leaks, search filter bug, stale prompt, sysprompt tools

* feat: expose all workflow step fields in config-mode MCP tools

* feat: add workflow CRUD to config-mode MCP tools

* fix: split workflow CRUD E2E test into separate tests

* fix: prevent cascade deletion of config session in delete workflow E2E test

The config-chat endpoint picks the newest workflow (ORDER BY created_at
DESC) for the ephemeral task. When the test created a deletable workflow
right before starting the config session, the session's own task landed
under that workflow. Deleting the workflow then cascaded and wiped the
running session's task, causing the MCP tool call to hang.

Add a "Config Anchor" bumper workflow so the config session uses it
instead of the deletable one.

* feat: add executor management to config-mode MCP tools

Add 8 new MCP tools for executor and executor profile CRUD in config
mode: list/create/update/delete for both executors and profiles.
Wired through the full stack (WS actions, backend handlers, agentctl
tools, sysprompt) with unit tests and E2E coverage.

* fix: auto-focus config chat input and rename popover title

* fix: remove executor CRUD MCP tools, keep executor profile management

Executors are pre-defined system entities (local, worktree, docker,
sprites). Only executor profiles should be managed via config chat.
Removes create_executor, update_executor, delete_executor MCP tools
while keeping list_executors and all executor profile tools.

* fix: add realtime UI sync for workflow steps and agent profiles via MCP

Workflow step and agent profile changes made through the config chat
MCP tools were not broadcasting events to the frontend. Executor
profile events worked because they went through the task service which
has event bus integration.

- Add WorkflowStep and AgentProfile event types to the event bus
- Add WS notification action constants for workflow step events
- Publish events from MCP handlers after step/profile CRUD operations
- Register gateway subscriptions for the new event types
- Add frontend WS handlers for workflow.step.created/updated/deleted

* fix: reuse existing config chat session when opened from command panel

The command panel always called openConfigChatModal() which reset the
session state, causing the profile picker to show again. Now it checks
for an existing active session first, matching the FAB behavior.

* fix: suppress FAB tooltip while config chat popover is open

When closing the popover via the X button, the mouse ends up over the
FAB area and the tooltip re-appears. Force the tooltip closed while
the popover is open so it cannot re-trigger on close.

* fix: thread default_config_agent_profile_id through all workspace data paths

The field was defined on the workspace type but never populated in:
- SSR mapper (page.tsx) — missing from initial hydration
- WS workspace handlers — wiped on workspace.created/updated events
- Backend publishWorkspaceEvent — not included in event data

This caused the config chat to always show the profile picker when
opened from the command panel, since the saved default was lost.

* fix: address PR review comments — workspace sync, type fixes, missing tool doc

- Sync configChat.workspaceId when promoting next tab in closeConfigChatSession
- Add update_task_state_kandev to ConfigContext system prompt
- Fix workflow step WS event types (workflow.step.* instead of step.*)
- Fix const reassignment in E2E tests (const → let)

* refactor: clean up dead code and register missing MCP tools

- Register update_task_state, delete_workflow_step, and
  reorder_workflow_steps as MCP tools in agentctl config mode
- Remove dead handleCreateAgent/handleDeleteAgent WS handlers
  and their ActionMCP constants (only profiles are managed)
- Rename openConfigChatModal to startNewConfigChat across frontend
- Update sysprompt, tests, and tool counts

* fix: remove extra next.config.ts machine

* fix: address CI failures — prettier formatting and funlen split

* fix: address coderabbit review comments across config-mode stack

- Include prompt field in workflow step broadcast payloads
- Align sysprompt task-state values with actual backend enum
- Return error instead of continuing when MCP mode switch fails
- Validate mode values in agentctl set-mcp-mode endpoint
- Use errors.Is() for sentinel error comparison
- Fix nullish coalescing to allow clearing config agent profile
- Expand StepPayload type with missing config-step fields
- Derive config agent Select value from store instead of local state

* fix: reuse persisted config chat session and reduce toolbar complexity

- Look up configChat.sessions for workspace before creating new session
- Extract MinimalToolbar and move defaults to module-level object to
  reduce ChatInputToolbar cyclomatic complexity from 16 to 7

* fix: E2E executor test strict mode violation and invalid cleanup

- Use exact match for list_executors text to avoid matching 2 elements
- Remove cleanup that tried to delete pre-existing system executor
- Reuse persisted config chat session for workspace in global commands
- Reduce ChatInputToolbar cyclomatic complexity with module-level defaults
2026-03-13 00:44:06 +00:00

1481 lines
55 KiB
Go

// Package orchestrator provides the main orchestrator service that ties all components together.
package orchestrator
import (
"context"
"errors"
"fmt"
"os"
"strings"
"time"
"go.uber.org/zap"
"github.com/kandev/kandev/internal/agentctl/client"
"github.com/kandev/kandev/internal/events"
"github.com/kandev/kandev/internal/events/bus"
"github.com/kandev/kandev/internal/orchestrator/dto"
"github.com/kandev/kandev/internal/orchestrator/executor"
"github.com/kandev/kandev/internal/orchestrator/queue"
"github.com/kandev/kandev/internal/sysprompt"
"github.com/kandev/kandev/internal/task/models"
wfmodels "github.com/kandev/kandev/internal/workflow/models"
v1 "github.com/kandev/kandev/pkg/api/v1"
)
// PromptResult contains the result of a prompt operation
type PromptResult struct {
StopReason string // The reason the agent stopped (e.g., "end_turn")
AgentMessage string // The agent's accumulated response message
}
var ErrAgentPromptInProgress = errors.New("agent is currently processing a prompt")
var ErrSessionResetInProgress = errors.New("session reset in progress")
func isAgentPromptInProgressError(err error) bool {
return err != nil && (errors.Is(err, ErrAgentPromptInProgress) || strings.Contains(err.Error(), ErrAgentPromptInProgress.Error()))
}
func isSessionResetInProgressError(err error) bool {
return err != nil && (errors.Is(err, ErrSessionResetInProgress) || strings.Contains(err.Error(), ErrSessionResetInProgress.Error()))
}
func isTransientPromptError(err error) bool {
if err == nil {
return false
}
msg := strings.ToLower(err.Error())
return strings.Contains(msg, "agent stream disconnected") ||
strings.Contains(msg, "use of closed network connection")
}
func isAgentAlreadyRunningError(err error) bool {
return err != nil && strings.Contains(err.Error(), "already has an agent running")
}
func validateSessionWorktrees(session *models.TaskSession) error {
for _, wt := range session.Worktrees {
if wt.WorktreePath == "" {
continue
}
if _, err := os.Stat(wt.WorktreePath); err != nil {
return fmt.Errorf("worktree path not found: %w", err)
}
}
return nil
}
// EnqueueTask manually adds a task to the queue
func (s *Service) EnqueueTask(ctx context.Context, task *v1.Task) error {
s.logger.Debug("manually enqueueing task",
zap.String("task_id", task.ID),
zap.String("title", task.Title))
return s.scheduler.EnqueueTask(task)
}
// PrepareTaskSession creates a session entry without launching the agent.
// This allows the HTTP handler to return the session ID immediately while the agent setup
// continues in the background. Use StartTaskWithSession to continue with agent launch.
// When launchWorkspace is true, workspace infrastructure (agentctl) is launched synchronously
// so file browsing works immediately. When false, the workspace launch is deferred to
// StartTaskWithSession (useful for remote executors where provisioning takes 30-60s).
func (s *Service) PrepareTaskSession(ctx context.Context, taskID string, agentProfileID string, executorID string, executorProfileID string, workflowStepID string, launchWorkspace bool) (string, error) {
s.logger.Debug("preparing task session",
zap.String("task_id", taskID),
zap.String("agent_profile_id", agentProfileID),
zap.String("executor_id", executorID),
zap.String("executor_profile_id", executorProfileID),
zap.String("workflow_step_id", workflowStepID),
zap.Bool("launch_workspace", launchWorkspace))
// Fetch the task to get workspace info
task, err := s.scheduler.GetTask(ctx, taskID)
if err != nil {
s.logger.Error("failed to fetch task for session preparation",
zap.String("task_id", taskID),
zap.Error(err))
return "", err
}
// Resolve agent/executor profile from task metadata if not explicitly provided
if agentProfileID == "" {
if v, ok := task.Metadata["agent_profile_id"].(string); ok && v != "" {
agentProfileID = v
}
}
if executorProfileID == "" {
if v, ok := task.Metadata["executor_profile_id"].(string); ok && v != "" {
executorProfileID = v
}
}
// Fall back to the task's current workflow step when the caller didn't provide one.
// This ensures sessions created via the kanban card (which doesn't send workflow_step_id)
// inherit the task's step and participate in workflow events.
if workflowStepID == "" {
dbTask, err := s.repo.GetTask(ctx, taskID)
if err != nil {
s.logger.Warn("failed to fetch task for workflow step fallback",
zap.String("task_id", taskID),
zap.Error(err))
} else if dbTask.WorkflowStepID != "" {
workflowStepID = dbTask.WorkflowStepID
}
}
// Create session entry in database
sessionID, err := s.executor.PrepareSession(ctx, task, agentProfileID, executorID, executorProfileID, workflowStepID)
if err != nil {
s.logger.Error("failed to prepare session",
zap.String("task_id", taskID),
zap.Error(err))
return "", err
}
if launchWorkspace {
// Launch workspace infrastructure (agentctl) without starting the agent subprocess.
// This enables file browsing, editing, etc. while the session is in CREATED state.
if prepExec, launchErr := s.executor.LaunchPreparedSession(ctx, task, sessionID, executor.LaunchOptions{AgentProfileID: agentProfileID, ExecutorID: executorID, WorkflowStepID: workflowStepID}); launchErr != nil {
s.logger.Warn("failed to launch workspace for prepared session (file browsing may be unavailable)",
zap.String("task_id", taskID),
zap.String("session_id", sessionID),
zap.Error(launchErr))
// Non-fatal: session is still usable, workspace will be launched when agent starts
} else if prepExec != nil && prepExec.WorktreeBranch != "" {
go s.ensureSessionPRWatch(context.Background(), taskID, prepExec.SessionID, prepExec.WorktreeBranch)
}
}
s.logger.Info("task session prepared",
zap.String("task_id", taskID),
zap.String("session_id", sessionID))
return sessionID, nil
}
// StartTaskWithSession starts agent execution for a task using a pre-created session.
// This is used after PrepareTaskSession to continue with the agent launch.
// If planMode is true and the workflow step doesn't already apply plan mode,
// default plan mode instructions are injected into the prompt.
func (s *Service) StartTaskWithSession(ctx context.Context, taskID string, sessionID string, agentProfileID string, executorID string, executorProfileID string, priority int, prompt string, workflowStepID string, planMode bool) (*executor.TaskExecution, error) {
s.logger.Debug("starting task with existing session",
zap.String("task_id", taskID),
zap.String("session_id", sessionID),
zap.String("agent_profile_id", agentProfileID),
zap.Bool("plan_mode", planMode))
// Process on_turn_start before launching the agent.
if session, err := s.repo.GetTaskSession(ctx, sessionID); err == nil {
s.processOnTurnStartViaEngine(ctx, taskID, session)
}
if err := s.taskRepo.UpdateTaskState(ctx, taskID, v1.TaskStateScheduling); err != nil {
s.logger.Warn("failed to update task state to SCHEDULING",
zap.String("task_id", taskID),
zap.Error(err))
}
task, err := s.scheduler.GetTask(ctx, taskID)
if err != nil {
return nil, err
}
if priority > 0 {
task.Priority = priority
}
effectivePrompt := prompt
if effectivePrompt == "" {
effectivePrompt = task.Description
}
effectivePrompt, planModeActive := s.applyWorkflowAndPlanMode(ctx, effectivePrompt, task.ID, sessionID, workflowStepID, planMode)
execution, err := s.executor.LaunchPreparedSession(ctx, task, sessionID, executor.LaunchOptions{AgentProfileID: agentProfileID, ExecutorID: executorID, Prompt: effectivePrompt, WorkflowStepID: workflowStepID, StartAgent: true})
if err != nil {
return nil, err
}
if execution.SessionID != "" {
s.recordInitialMessage(ctx, taskID, execution.SessionID, effectivePrompt, planModeActive)
if planModeActive {
sess, sessErr := s.repo.GetTaskSession(ctx, execution.SessionID)
if sessErr == nil {
s.setSessionPlanMode(ctx, sess, true)
}
}
}
if execution.WorktreeBranch != "" {
go s.ensureSessionPRWatch(context.Background(), taskID, execution.SessionID, execution.WorktreeBranch)
}
return execution, nil
}
// StartCreatedSession starts agent execution for a task using a session that is in CREATED state.
// This is used when a session was prepared (via PrepareSession) but the agent was not launched,
// and the user now wants to start the agent with a prompt (e.g., from the plan panel or chat).
// When skipMessageRecord is true, only the session state is updated (the caller already stored the user message).
// When planMode is true, plan mode instructions are injected into the prompt and session metadata is set.
func (s *Service) StartCreatedSession(ctx context.Context, taskID, sessionID, agentProfileID, prompt string, skipMessageRecord, planMode bool) (*executor.TaskExecution, error) {
s.logger.Debug("starting created session",
zap.String("task_id", taskID),
zap.String("session_id", sessionID),
zap.String("agent_profile_id", agentProfileID))
// Load and verify session
session, err := s.repo.GetTaskSession(ctx, sessionID)
if err != nil {
return nil, fmt.Errorf("failed to get session: %w", err)
}
if session.TaskID != taskID {
return nil, fmt.Errorf("session does not belong to task")
}
// Accept CREATED (normal) or WAITING_FOR_INPUT (after on_turn_start step transition).
// When the user sends the first message to a prepared session, on_turn_start may fire
// and move the step, which sets the session to WAITING_FOR_INPUT before we get here.
if session.State != models.TaskSessionStateCreated && session.State != models.TaskSessionStateWaitingForInput {
return nil, fmt.Errorf("session is not in CREATED or WAITING_FOR_INPUT state (current: %s)", session.State)
}
// Use agent profile from request, fall back to session's stored value
effectiveProfileID := agentProfileID
if effectiveProfileID == "" {
effectiveProfileID = session.AgentProfileID
}
if effectiveProfileID == "" {
return nil, fmt.Errorf("agent_profile_id is required")
}
// Transition task state: CREATED → SCHEDULING → (IN_PROGRESS via executor)
if err := s.taskRepo.UpdateTaskState(ctx, taskID, v1.TaskStateScheduling); err != nil {
s.logger.Warn("failed to update task state to SCHEDULING",
zap.String("task_id", taskID),
zap.Error(err))
}
task, err := s.scheduler.GetTask(ctx, taskID)
if err != nil {
return nil, err
}
effectivePrompt := prompt
if effectivePrompt == "" {
effectivePrompt = task.Description
}
// Process on_turn_start before launching the agent, just like user-initiated messages.
// This allows workflow transitions (e.g. move_to_next) to fire on the initial prompt.
s.processOnTurnStartViaEngine(ctx, taskID, session)
// Re-read the session after on_turn_start may have changed the workflow step.
session, err = s.repo.GetTaskSession(ctx, sessionID)
if err != nil {
return nil, fmt.Errorf("failed to reload session after on_turn_start: %w", err)
}
// Apply workflow step prompt wrapping and plan mode injection.
// Called unconditionally so workflow-step prompt composition (prefix/suffix)
// applies even when plan mode is not requested.
stepID := ""
if session.WorkflowStepID != nil {
stepID = *session.WorkflowStepID
}
effectivePrompt, planModeActive := s.applyWorkflowAndPlanMode(ctx, effectivePrompt, taskID, sessionID, stepID, planMode)
// Inject config context for config-mode sessions (dedicated settings chat)
if cm, ok := session.Metadata["config_mode"].(bool); ok && cm {
effectivePrompt = sysprompt.InjectConfigContext(sessionID, effectivePrompt)
}
executorID := session.ExecutorID
execution, err := s.executor.LaunchPreparedSession(ctx, task, sessionID, executor.LaunchOptions{AgentProfileID: effectiveProfileID, ExecutorID: executorID, Prompt: effectivePrompt, StartAgent: true})
if err != nil {
return nil, err
}
// Record the initial user message and set plan mode metadata after launch.
// Note: we do NOT set session state here — the executor sets it to STARTING,
// and event handlers (handleAgentReady) transition it to WAITING_FOR_INPUT.
s.postLaunchCreated(ctx, taskID, sessionID, effectivePrompt, skipMessageRecord, planModeActive)
return execution, nil
}
// postLaunchCreated handles post-launch bookkeeping for a created session:
// records the initial user message (unless skipped) and sets plan mode metadata.
// It does NOT modify session state — the executor sets STARTING, and event handlers
// (handleAgentReady) handle the transition to WAITING_FOR_INPUT.
func (s *Service) postLaunchCreated(ctx context.Context, taskID, sessionID, prompt string, skipMessage, planModeActive bool) {
if !skipMessage {
s.recordInitialMessage(ctx, taskID, sessionID, prompt, planModeActive)
}
if planModeActive {
sess, err := s.repo.GetTaskSession(ctx, sessionID)
if err == nil {
s.setSessionPlanMode(ctx, sess, true)
}
}
}
// StartTask manually starts agent execution for a task.
// If workflowStepID is provided and workflowStepGetter is set, the prompt will be built
// using the step's prompt_prefix + base prompt + prompt_suffix, and plan mode will be
// applied if the step has plan_mode enabled.
// If planMode is true and the workflow step doesn't already apply plan mode,
// default plan mode instructions are injected into the prompt.
func (s *Service) StartTask(ctx context.Context, taskID string, agentProfileID string, executorID string, executorProfileID string, priority int, prompt string, workflowStepID string, planMode bool) (*executor.TaskExecution, error) {
s.logger.Debug("manually starting task",
zap.String("task_id", taskID),
zap.String("agent_profile_id", agentProfileID),
zap.String("executor_id", executorID),
zap.Int("priority", priority),
zap.Int("prompt_length", len(prompt)),
zap.String("workflow_step_id", workflowStepID),
zap.Bool("plan_mode", planMode))
if err := s.taskRepo.UpdateTaskState(ctx, taskID, v1.TaskStateScheduling); err != nil {
s.logger.Warn("failed to update task state to SCHEDULING",
zap.String("task_id", taskID),
zap.Error(err))
}
// Move task to the target workflow step if provided and different from current
if workflowStepID != "" {
dbTask, err := s.repo.GetTask(ctx, taskID)
if err == nil && dbTask.WorkflowStepID != workflowStepID {
dbTask.WorkflowStepID = workflowStepID
dbTask.UpdatedAt = time.Now().UTC()
if err := s.repo.UpdateTask(ctx, dbTask); err != nil {
s.logger.Warn("failed to move task to workflow step",
zap.String("task_id", taskID),
zap.String("workflow_step_id", workflowStepID),
zap.Error(err))
} else if s.eventBus != nil {
_ = s.eventBus.Publish(ctx, events.TaskUpdated, bus.NewEvent(
events.TaskUpdated,
"orchestrator",
buildTaskEventPayload(dbTask),
))
}
}
}
// Fetch the task from the repository to get complete task info
task, err := s.scheduler.GetTask(ctx, taskID)
if err != nil {
s.logger.Error("failed to fetch task for manual start",
zap.String("task_id", taskID),
zap.Error(err))
return nil, err
}
// Override priority if provided in the request
if priority > 0 {
task.Priority = priority
}
// Use provided prompt, fall back to task description
effectivePrompt := prompt
if effectivePrompt == "" {
effectivePrompt = task.Description
}
// Prepare session first so we have the sessionID for config context injection
sessionID, err := s.executor.PrepareSession(ctx, task, agentProfileID, executorID, executorProfileID, workflowStepID)
if err != nil {
return nil, err
}
effectivePrompt, planModeActive := s.applyWorkflowAndPlanMode(ctx, effectivePrompt, task.ID, sessionID, workflowStepID, planMode)
// Inject config context for config-mode sessions (dedicated settings chat)
configMode := false
if cm, ok := task.Metadata["config_mode"].(bool); ok && cm {
configMode = true
effectivePrompt = sysprompt.InjectConfigContext(sessionID, effectivePrompt)
}
execution, err := s.executor.LaunchPreparedSession(ctx, task, sessionID, executor.LaunchOptions{
AgentProfileID: agentProfileID,
ExecutorID: executorID,
Prompt: effectivePrompt,
WorkflowStepID: workflowStepID,
StartAgent: true,
})
if err != nil {
return nil, err
}
if execution.SessionID != "" {
s.recordInitialMessage(ctx, taskID, execution.SessionID, effectivePrompt, planModeActive || configMode)
// Set plan mode in session metadata so the frontend can detect it.
// applyWorkflowAndPlanMode only injects plan mode into the prompt text;
// the session metadata is needed for the frontend to switch the layout.
if planModeActive {
session, err := s.repo.GetTaskSession(ctx, execution.SessionID)
if err == nil {
s.setSessionPlanMode(ctx, session, true)
}
}
}
if execution.WorktreeBranch != "" {
go s.ensureSessionPRWatch(context.Background(), taskID, execution.SessionID, execution.WorktreeBranch)
}
// Note: Task stays in SCHEDULING state until the agent is fully initialized.
// The executor will transition to IN_PROGRESS after StartAgentProcess() succeeds.
return execution, nil
}
// applyWorkflowAndPlanMode applies workflow step configuration and plan mode injection to a prompt.
// Returns the effective prompt and whether plan mode is active (from either the step or the caller).
func (s *Service) applyWorkflowAndPlanMode(ctx context.Context, prompt string, taskID string, sessionID string, workflowStepID string, planMode bool) (string, bool) {
effectivePrompt := prompt
stepHasPlanMode := false
if workflowStepID != "" && s.workflowStepGetter != nil {
step, err := s.workflowStepGetter.GetStep(ctx, workflowStepID)
if err != nil {
s.logger.Warn("failed to get workflow step for prompt building",
zap.String("workflow_step_id", workflowStepID),
zap.Error(err))
} else {
stepHasPlanMode = step.HasOnEnterAction(wfmodels.OnEnterEnablePlanMode)
effectivePrompt = s.buildWorkflowPrompt(effectivePrompt, step, taskID, sessionID)
}
}
if planMode && !stepHasPlanMode {
var parts []string
parts = append(parts, sysprompt.Wrap(sysprompt.InterpolatePlaceholders(sysprompt.DefaultPlanPrefix, taskID)))
parts = append(parts, effectivePrompt)
effectivePrompt = strings.Join(parts, "\n\n")
}
return effectivePrompt, planMode || stepHasPlanMode
}
// recordInitialMessage creates the initial user message and updates session state after launch.
func (s *Service) recordInitialMessage(ctx context.Context, taskID, sessionID, prompt string, planModeActive bool) {
if s.messageCreator != nil && prompt != "" {
meta := NewUserMessageMeta().WithPlanMode(planModeActive)
if err := s.messageCreator.CreateUserMessage(ctx, taskID, prompt, sessionID, s.getActiveTurnID(sessionID), meta.ToMap()); err != nil {
s.logger.Error("failed to create initial user message",
zap.String("task_id", taskID),
zap.Error(err))
}
}
}
// buildWorkflowPrompt constructs the effective prompt using workflow step configuration.
// If step.Prompt contains {{task_prompt}}, it is replaced with the base prompt.
// Otherwise, step.Prompt is prepended to the base prompt.
// System-injected content is wrapped in <kandev-system> tags so it can be stripped when displaying to users.
func (s *Service) buildWorkflowPrompt(basePrompt string, step *wfmodels.WorkflowStep, taskID string, sessionID string) string {
var parts []string
// Build the prompt from step.Prompt template and base prompt
if step.Prompt != "" {
interpolatedPrompt := sysprompt.InterpolatePlaceholders(step.Prompt, taskID)
if strings.Contains(interpolatedPrompt, "{{task_prompt}}") {
// Replace placeholder with base prompt
combined := strings.Replace(interpolatedPrompt, "{{task_prompt}}", basePrompt, 1)
parts = append(parts, combined)
} else {
// Prepend step prompt, then base prompt
parts = append(parts, sysprompt.Wrap(interpolatedPrompt))
parts = append(parts, basePrompt)
}
} else {
// No step prompt, just use base prompt
parts = append(parts, basePrompt)
}
return strings.Join(parts, "\n\n")
}
// ResumeTaskSession restarts a specific task session using its stored worktree.
func (s *Service) ResumeTaskSession(ctx context.Context, taskID, sessionID string) (*executor.TaskExecution, error) {
s.logger.Debug("resuming task session",
zap.String("task_id", taskID),
zap.String("session_id", sessionID))
session, err := s.repo.GetTaskSession(ctx, sessionID)
if err != nil {
return nil, err
}
if session.TaskID != taskID {
return nil, fmt.Errorf("task session does not belong to task")
}
running, err := s.repo.GetExecutorRunningBySessionID(ctx, sessionID)
if err != nil || running == nil {
return nil, fmt.Errorf("session is not resumable: no executor record")
}
if err := validateSessionWorktrees(session); err != nil {
return nil, err
}
// Don't resume sessions that are in a terminal state.
switch session.State {
case models.TaskSessionStateFailed, models.TaskSessionStateCompleted, models.TaskSessionStateCancelled:
return nil, fmt.Errorf("session is in terminal state %s and cannot be resumed", session.State)
}
// Use context.WithoutCancel to prevent WebSocket request timeout from canceling the resume.
// Session resume can take time and shouldn't be tied to the WS request lifecycle.
resumeCtx := context.WithoutCancel(ctx)
execution, err := s.executor.ResumeSession(resumeCtx, session, true)
if err != nil {
// If the execution is already running (duplicate resume request), return it as success.
if errors.Is(err, executor.ErrExecutionAlreadyRunning) {
if existing, ok := s.executor.GetExecutionBySession(sessionID); ok && existing != nil {
existing.SessionState = v1.TaskSessionState(session.State)
return existing, nil
}
}
s.updateTaskSessionState(ctx, taskID, sessionID, models.TaskSessionStateFailed, err.Error(), false, session)
if stateErr := s.taskRepo.UpdateTaskState(ctx, taskID, v1.TaskStateFailed); stateErr != nil {
s.logger.Warn("failed to update task state to FAILED after resume error",
zap.String("task_id", taskID),
zap.String("session_id", sessionID),
zap.Error(stateErr))
}
return nil, err
}
// Preserve persisted task/session state; resume should not mutate state/columns.
execution.SessionState = v1.TaskSessionState(session.State)
s.logger.Debug("task session resumed and ready for input",
zap.String("task_id", taskID),
zap.String("session_id", sessionID))
if execution.WorktreeBranch != "" {
go s.ensureSessionPRWatch(context.Background(), taskID, execution.SessionID, execution.WorktreeBranch)
}
return execution, nil
}
// StartSessionForWorkflowStep starts an existing session with a workflow step's prompt configuration.
// If the session is not running, it will be resumed first. Then a prompt is sent using the
// step's prompt_prefix, prompt_suffix, and plan_mode settings combined with the task description.
func (s *Service) StartSessionForWorkflowStep(ctx context.Context, taskID, sessionID, workflowStepID string) error {
s.logger.Debug("starting session for workflow step",
zap.String("task_id", taskID),
zap.String("session_id", sessionID),
zap.String("workflow_step_id", workflowStepID))
if workflowStepID == "" {
return fmt.Errorf("workflow_step_id is required")
}
if s.workflowStepGetter == nil {
return fmt.Errorf("workflow step getter not configured")
}
step, err := s.workflowStepGetter.GetStep(ctx, workflowStepID)
if err != nil {
return fmt.Errorf("failed to get workflow step: %w", err)
}
session, err := s.repo.GetTaskSession(ctx, sessionID)
if err != nil {
return fmt.Errorf("failed to get session: %w", err)
}
if session.TaskID != taskID {
return fmt.Errorf("session does not belong to task")
}
task, err := s.scheduler.GetTask(ctx, taskID)
if err != nil {
return fmt.Errorf("failed to get task: %w", err)
}
if session.ReviewStatus != nil && *session.ReviewStatus == "pending" {
return fmt.Errorf("session is pending approval - use Approve button to proceed or send a message to request changes")
}
s.advanceSessionWorkflowStep(ctx, sessionID, workflowStepID, session)
effectivePrompt := s.buildWorkflowPrompt(task.Description, step, taskID, sessionID)
if err := s.ensureSessionRunning(ctx, sessionID, session); err != nil {
return err
}
stepPlanMode := step.HasOnEnterAction(wfmodels.OnEnterEnablePlanMode)
_, err = s.PromptTask(ctx, taskID, sessionID, effectivePrompt, "", stepPlanMode, nil)
if err != nil {
return fmt.Errorf("failed to prompt session: %w", err)
}
s.logger.Info("session started for workflow step",
zap.String("task_id", taskID),
zap.String("session_id", sessionID),
zap.String("workflow_step_id", workflowStepID),
zap.String("step_name", step.Name),
zap.Bool("plan_mode", stepPlanMode))
return nil
}
// advanceSessionWorkflowStep updates the session's workflow step and clears review status if the step changed.
func (s *Service) advanceSessionWorkflowStep(ctx context.Context, sessionID, workflowStepID string, session *models.TaskSession) {
if session.WorkflowStepID != nil && *session.WorkflowStepID == workflowStepID {
return
}
if err := s.repo.UpdateSessionWorkflowStep(ctx, sessionID, workflowStepID); err != nil {
s.logger.Warn("failed to update session workflow step",
zap.String("session_id", sessionID),
zap.String("workflow_step_id", workflowStepID),
zap.Error(err))
}
if session.ReviewStatus != nil && *session.ReviewStatus != "" {
if err := s.repo.UpdateSessionReviewStatus(ctx, sessionID, ""); err != nil {
s.logger.Warn("failed to clear session review status",
zap.String("session_id", sessionID),
zap.Error(err))
}
}
}
// ensureSessionRunning resumes the session if the agent is not actually running.
// After lazy recovery, a session may be in WAITING_FOR_INPUT with no agent process;
// this function detects that case and triggers a resume.
func (s *Service) ensureSessionRunning(ctx context.Context, sessionID string, session *models.TaskSession) error {
// Check if agent is genuinely running (in-memory execution store, not just DB state)
if exec, ok := s.executor.GetExecutionBySession(sessionID); ok && exec != nil {
return nil
}
s.logger.Debug("agent not running for session, attempting resume",
zap.String("session_id", sessionID),
zap.String("session_state", string(session.State)))
// If the session is in CREATED state with an existing workspace (AgentExecutionID set),
// the workspace was prepared but the agent was never started. Use LaunchPreparedSession
// which routes to startAgentOnExistingWorkspace to reuse the workspace rather than
// ResumeSession which tries a full LaunchAgent and conflicts with the existing execution.
if session.State == models.TaskSessionStateCreated && session.AgentExecutionID != "" {
return s.startAgentOnPreparedWorkspace(ctx, sessionID, session)
}
running, err := s.repo.GetExecutorRunningBySessionID(ctx, sessionID)
if err != nil || running == nil {
return fmt.Errorf("session is not resumable: no executor record (state: %s)", session.State)
}
if err := validateSessionWorktrees(session); err != nil {
return err
}
// Use context.WithoutCancel to prevent WebSocket request timeout from canceling the resume.
resumeCtx := context.WithoutCancel(ctx)
if _, err = s.executor.ResumeSession(resumeCtx, session, true); err != nil {
if errors.Is(err, executor.ErrExecutionAlreadyRunning) {
return nil // Agent is already running, nothing to do
}
s.updateTaskSessionState(ctx, session.TaskID, sessionID, models.TaskSessionStateFailed, err.Error(), false, session)
if stateErr := s.taskRepo.UpdateTaskState(ctx, session.TaskID, v1.TaskStateFailed); stateErr != nil {
s.logger.Warn("failed to update task state to FAILED after session ensure resume error",
zap.String("task_id", session.TaskID),
zap.String("session_id", sessionID),
zap.Error(stateErr))
}
return fmt.Errorf("failed to resume session: %w", err)
}
// ResumeSession launches the agent asynchronously. Wait for it to finish
// initializing before returning, so the caller can send a prompt immediately.
if err := s.waitForSessionReady(ctx, sessionID); err != nil {
return fmt.Errorf("session not ready after resume: %w", err)
}
s.logger.Debug("session resumed and ready for prompt")
return nil
}
// startAgentOnPreparedWorkspace starts the agent subprocess on a session whose workspace
// was prepared (agentctl running) but whose agent process was never started. This avoids
// the "session already has an agent running" error from ResumeSession which tries a full
// LaunchAgent and conflicts with the existing execution in the lifecycle manager's store.
func (s *Service) startAgentOnPreparedWorkspace(ctx context.Context, sessionID string, session *models.TaskSession) error {
s.logger.Debug("session has prepared workspace but no agent, starting agent on existing workspace",
zap.String("session_id", sessionID),
zap.String("agent_execution_id", session.AgentExecutionID))
launchCtx := context.WithoutCancel(ctx)
task, err := s.scheduler.GetTask(launchCtx, session.TaskID)
if err != nil {
return fmt.Errorf("failed to get task for prepared session: %w", err)
}
if _, err = s.executor.LaunchPreparedSession(launchCtx, task, sessionID, executor.LaunchOptions{
AgentProfileID: session.AgentProfileID,
ExecutorID: session.ExecutorID,
StartAgent: true,
}); err != nil {
return fmt.Errorf("failed to start agent on prepared workspace: %w", err)
}
if err := s.waitForSessionReady(ctx, sessionID); err != nil {
return fmt.Errorf("session not ready after starting agent: %w", err)
}
s.logger.Debug("agent started on prepared workspace and ready for prompt")
return nil
}
// waitForSessionReady polls the session state until the agent is ready for prompts.
func (s *Service) waitForSessionReady(ctx context.Context, sessionID string) error {
const (
pollInterval = 500 * time.Millisecond
maxWait = 90 * time.Second
)
deadline := time.Now().Add(maxWait)
for {
if time.Now().After(deadline) {
return fmt.Errorf("timeout waiting for agent to become ready")
}
select {
case <-ctx.Done():
return ctx.Err()
case <-time.After(pollInterval):
}
sess, err := s.repo.GetTaskSession(ctx, sessionID)
if err != nil {
return fmt.Errorf("failed to check session state: %w", err)
}
switch sess.State {
case models.TaskSessionStateWaitingForInput:
return nil
case models.TaskSessionStateFailed:
errMsg := sess.ErrorMessage
if errMsg == "" {
errMsg = "session failed during startup"
}
return fmt.Errorf("session failed: %s", errMsg)
case models.TaskSessionStateCancelled, models.TaskSessionStateCompleted:
return fmt.Errorf("session in unexpected state: %s", sess.State)
}
}
}
// GetTaskSessionStatus returns the status of a task session including whether it's resumable
func (s *Service) GetTaskSessionStatus(ctx context.Context, taskID, sessionID string) (dto.TaskSessionStatusResponse, error) {
s.logger.Debug("checking task session status",
zap.String("task_id", taskID),
zap.String("session_id", sessionID))
resp := dto.TaskSessionStatusResponse{
SessionID: sessionID,
TaskID: taskID,
}
// 1. Load session from database
session, err := s.repo.GetTaskSession(ctx, sessionID)
if err != nil {
resp.Error = "session not found"
return resp, nil
}
if session.TaskID != taskID {
resp.Error = "session does not belong to task"
return resp, nil
}
resp.State = string(session.State)
resp.AgentProfileID = session.AgentProfileID
s.populateExecutorStatusInfo(ctx, session, &resp)
running, runErr := s.repo.GetExecutorRunningBySessionID(ctx, sessionID)
resumeToken := ""
if runErr == nil && running != nil {
resumeToken = running.ResumeToken
resp.ACPSessionID = running.ResumeToken
resp.Runtime = running.Runtime
if running.Resumable {
resp.IsResumable = true
}
s.applyRemoteRuntimeStatus(ctx, sessionID, &resp)
}
if shouldHealStuckStartingSession(session, running) {
s.logger.Info("healing stale STARTING session state from ready runtime status",
zap.String("task_id", taskID),
zap.String("session_id", sessionID),
zap.String("agent_execution_id", session.AgentExecutionID))
s.setSessionWaitingForInput(ctx, taskID, sessionID)
refreshedSession, refreshErr := s.repo.GetTaskSession(ctx, sessionID)
if refreshErr == nil && refreshedSession != nil {
session = refreshedSession
resp.State = string(session.State)
}
}
// Extract worktree info
populateWorktreeInfo(session, &resp)
// 2. Check if this session's agent is running
if exec, ok := s.executor.GetExecutionBySession(sessionID); ok && exec != nil {
resp.IsAgentRunning = true
resp.NeedsResume = false
return resp, nil
}
// 3. Session can be resumed if it has a resume token
if resumeToken != "" {
// Don't auto-resume terminal sessions — they failed/completed for a reason.
if !isActiveSessionState(session.State) {
resp.IsAgentRunning = false
resp.IsResumable = false
resp.NeedsResume = false
resp.NeedsWorkspaceRestore = canRestoreWorkspace(&resp)
return resp, nil
}
return s.validateResumeEligibility(session, resp), nil
}
// 4. No resume token, but session may still be startable as a fresh session
// if there's an ExecutorRunning record (worktree info) and session is in an active state.
// NeedsResume triggers the frontend to auto-resume, which launches agentctl and the agent
// process (idle, no prompt). For agents with HistoryContextInjection, conversation history
// is injected into the user's first message.
if runErr == nil && running != nil && isActiveSessionState(session.State) {
resp.IsAgentRunning = false
resp.IsResumable = true
resp.NeedsResume = true
resp.ResumeReason = "agent_not_running_fresh_start"
return resp, nil
}
resp.IsAgentRunning = false
resp.IsResumable = false
resp.NeedsResume = false
resp.NeedsWorkspaceRestore = canRestoreWorkspace(&resp)
return resp, nil
}
func (s *Service) populateExecutorStatusInfo(ctx context.Context, session *models.TaskSession, resp *dto.TaskSessionStatusResponse) {
if session == nil || resp == nil {
return
}
resp.ExecutorID = session.ExecutorID
if session.ExecutorID == "" {
return
}
execModel, err := s.repo.GetExecutor(ctx, session.ExecutorID)
if err != nil || execModel == nil {
return
}
resp.ExecutorType = string(execModel.Type)
resp.ExecutorName = execModel.Name
resp.IsRemoteExecutor = models.IsRemoteExecutorType(execModel.Type)
}
func (s *Service) applyRemoteRuntimeStatus(ctx context.Context, sessionID string, resp *dto.TaskSessionStatusResponse) {
if s.agentManager == nil || resp == nil || !resp.IsRemoteExecutor {
return
}
status, err := s.agentManager.GetRemoteRuntimeStatusBySession(ctx, sessionID)
if err != nil || status == nil {
return
}
if status.RuntimeName != "" {
resp.Runtime = status.RuntimeName
}
resp.RemoteState = status.State
resp.RemoteName = status.RemoteName
if status.ErrorMessage != "" {
resp.RemoteStatusErr = status.ErrorMessage
}
if status.CreatedAt != nil && !status.CreatedAt.IsZero() {
resp.RemoteCreatedAt = status.CreatedAt.UTC().Format(time.RFC3339)
}
if !status.LastCheckedAt.IsZero() {
resp.RemoteCheckedAt = status.LastCheckedAt.UTC().Format(time.RFC3339)
}
}
// populateWorktreeInfo copies worktree path and branch into the response if present.
func canRestoreWorkspace(resp *dto.TaskSessionStatusResponse) bool {
return resp != nil && resp.WorktreePath != nil && *resp.WorktreePath != ""
}
func populateWorktreeInfo(session *models.TaskSession, resp *dto.TaskSessionStatusResponse) {
if len(session.Worktrees) == 0 {
return
}
wt := session.Worktrees[0]
if wt.WorktreePath != "" {
resp.WorktreePath = &wt.WorktreePath
}
if wt.WorktreeBranch != "" {
resp.WorktreeBranch = &wt.WorktreeBranch
}
}
// isActiveSessionState returns true for session states where lazy resume makes sense.
func isActiveSessionState(state models.TaskSessionState) bool {
switch state {
case models.TaskSessionStateWaitingForInput,
models.TaskSessionStateStarting,
models.TaskSessionStateRunning:
return true
}
return false
}
func shouldHealStuckStartingSession(session *models.TaskSession, running *models.ExecutorRunning) bool {
if session == nil || running == nil {
return false
}
if session.State != models.TaskSessionStateStarting {
return false
}
if running.Status != "ready" {
return false
}
if session.AgentExecutionID != "" && running.AgentExecutionID != "" && session.AgentExecutionID != running.AgentExecutionID {
return false
}
return true
}
// validateResumeEligibility performs final checks before marking a session as resumable.
func (s *Service) validateResumeEligibility(session *models.TaskSession, resp dto.TaskSessionStatusResponse) dto.TaskSessionStatusResponse {
if session.AgentProfileID == "" {
resp.Error = "session missing agent profile"
resp.IsResumable = false
return resp
}
// Check if worktree exists (if one was used)
if len(session.Worktrees) > 0 && session.Worktrees[0].WorktreePath != "" {
if _, err := os.Stat(session.Worktrees[0].WorktreePath); err != nil {
resp.Error = "worktree not found"
resp.IsResumable = false
return resp
}
}
resp.IsAgentRunning = false
resp.NeedsResume = true
resp.ResumeReason = "agent_not_running"
return resp
}
// StopTask stops agent execution for a task (stops all active sessions for the task)
func (s *Service) StopTask(ctx context.Context, taskID string, reason string, force bool) error {
s.logger.Info("stopping task execution",
zap.String("task_id", taskID),
zap.String("reason", reason),
zap.Bool("force", force))
// Stop all agents for this task
if err := s.executor.StopByTaskID(ctx, taskID, reason, force); err != nil {
return err
}
// Move task to REVIEW state for user review
if err := s.taskRepo.UpdateTaskState(ctx, taskID, v1.TaskStateReview); err != nil {
s.logger.Error("failed to update task state to REVIEW after stop",
zap.String("task_id", taskID),
zap.Error(err))
// Don't return error - the stop was successful
} else {
s.logger.Info("task moved to REVIEW state after stop",
zap.String("task_id", taskID))
}
return nil
}
// StopSession stops agent execution for a specific session
func (s *Service) StopSession(ctx context.Context, sessionID string, reason string, force bool) error {
s.logger.Info("stopping session execution",
zap.String("session_id", sessionID),
zap.String("reason", reason),
zap.Bool("force", force))
return s.executor.Stop(ctx, sessionID, reason, force)
}
// StopExecution stops agent execution for a specific execution ID.
func (s *Service) StopExecution(ctx context.Context, executionID string, reason string, force bool) error {
s.logger.Info("stopping execution",
zap.String("execution_id", executionID),
zap.String("reason", reason),
zap.Bool("force", force))
return s.executor.StopExecution(ctx, executionID, reason, force)
}
// CaptureArchiveSnapshot captures git state (commits, cumulative diff) for a session before archiving.
// This preserves the final git state for historical purposes.
func (s *Service) CaptureArchiveSnapshot(ctx context.Context, sessionID string) error {
s.logger.Info("capturing archive snapshot", zap.String("session_id", sessionID))
baseCommit, err := s.resolveArchiveBaseCommit(ctx, sessionID)
if err != nil {
return err
}
if baseCommit == "" {
s.logger.Debug("no base_commit available, skipping archive snapshot capture",
zap.String("session_id", sessionID))
return nil
}
if !s.captureArchiveCommits(ctx, sessionID, baseCommit) {
// Agent not running, skip diff capture as well
return nil
}
s.captureArchiveDiff(ctx, sessionID, baseCommit)
return nil
}
// resolveArchiveBaseCommit retrieves the base commit for archive snapshot capture.
// It first checks the session's stored base_commit_sha, falling back to git status if empty.
func (s *Service) resolveArchiveBaseCommit(ctx context.Context, sessionID string) (string, error) {
session, err := s.repo.GetTaskSession(ctx, sessionID)
if err != nil {
return "", fmt.Errorf("failed to get session: %w", err)
}
if session.BaseCommitSHA != "" {
return session.BaseCommitSHA, nil
}
// Fallback: try to get base commit from git status for legacy sessions
status, err := s.agentManager.GetGitStatus(ctx, sessionID)
if err != nil {
s.logger.Debug("failed to get git status for base commit fallback",
zap.String("session_id", sessionID),
zap.Error(err))
return "", nil
}
if status != nil && status.BaseCommit != "" {
s.logger.Debug("using git status base commit as fallback for archive",
zap.String("session_id", sessionID),
zap.String("base_commit", status.BaseCommit))
return status.BaseCommit, nil
}
return "", nil
}
// captureArchiveCommits fetches and saves commits from baseCommit to HEAD.
// Returns false if the agent is not running (caller should skip remaining capture).
func (s *Service) captureArchiveCommits(ctx context.Context, sessionID, baseCommit string) bool {
logResult, err := s.agentManager.GetGitLog(ctx, sessionID, baseCommit, 0) // 0 = no limit
if err != nil {
s.logger.Warn("failed to capture git log for archive",
zap.String("session_id", sessionID),
zap.Error(err))
return true // Continue with diff capture even if log fails
}
if logResult == nil {
s.logger.Debug("agent not running, skipping archive snapshot capture",
zap.String("session_id", sessionID))
return false
}
if logResult.Success && len(logResult.Commits) > 0 {
s.saveArchiveCommits(ctx, sessionID, logResult.Commits)
}
return true
}
// captureArchiveDiff fetches and saves the cumulative diff from baseCommit to HEAD.
func (s *Service) captureArchiveDiff(ctx context.Context, sessionID, baseCommit string) {
diffResult, err := s.agentManager.GetCumulativeDiff(ctx, sessionID, baseCommit)
if err != nil {
s.logger.Warn("failed to capture cumulative diff for archive",
zap.String("session_id", sessionID),
zap.Error(err))
return
}
if diffResult == nil || !diffResult.Success {
return
}
if err := s.repo.CreateGitSnapshot(ctx, &models.GitSnapshot{
SessionID: sessionID,
SnapshotType: models.SnapshotTypeArchive,
HeadCommit: diffResult.HeadCommit,
BaseCommit: diffResult.BaseCommit,
Files: diffResult.Files,
}); err != nil {
s.logger.Warn("failed to save archive snapshot",
zap.String("session_id", sessionID),
zap.Error(err))
return
}
s.logger.Debug("saved archive snapshot",
zap.String("session_id", sessionID),
zap.String("head_commit", diffResult.HeadCommit),
zap.Int("total_commits", diffResult.TotalCommits))
}
// parseCommitTime parses a commit timestamp from git log output.
// Returns UTC time to ensure consistent timestamps across environments.
func parseCommitTime(s string) time.Time {
t, err := time.Parse(time.RFC3339, s)
if err != nil {
return time.Now().UTC()
}
return t.UTC()
}
// saveArchiveCommits persists commits to the database for archive purposes.
func (s *Service) saveArchiveCommits(ctx context.Context, sessionID string, commits []*client.GitCommitInfo) {
for _, commit := range commits {
if err := s.repo.CreateSessionCommit(ctx, &models.SessionCommit{
SessionID: sessionID,
CommitSHA: commit.CommitSHA,
ParentSHA: commit.ParentSHA,
AuthorName: commit.AuthorName,
AuthorEmail: commit.AuthorEmail,
CommitMessage: commit.CommitMessage,
CommittedAt: parseCommitTime(commit.CommittedAt),
FilesChanged: commit.FilesChanged,
Insertions: commit.Insertions,
Deletions: commit.Deletions,
}); err != nil {
s.logger.Warn("failed to save commit for archive",
zap.String("session_id", sessionID),
zap.String("commit_sha", commit.CommitSHA),
zap.Error(err))
}
}
s.logger.Debug("saved archive commits",
zap.String("session_id", sessionID),
zap.Int("count", len(commits)))
}
// PromptTask sends a follow-up prompt to a running agent for a task session.
// If planMode is true, a plan mode prefix is prepended to the prompt.
// Attachments (images) are passed through to the agent if provided.
func (s *Service) PromptTask(ctx context.Context, taskID, sessionID string, prompt string, model string, planMode bool, attachments []v1.MessageAttachment) (*PromptResult, error) {
s.logger.Debug("PromptTask called",
zap.String("task_id", taskID),
zap.String("session_id", sessionID),
zap.Int("prompt_length", len(prompt)),
zap.String("requested_model", model),
zap.Bool("plan_mode", planMode),
zap.Int("attachments_count", len(attachments)))
if sessionID == "" {
return nil, fmt.Errorf("session_id is required")
}
if s.isSessionResetInProgress(sessionID) {
return nil, ErrSessionResetInProgress
}
// Only allow prompts when the session is ready for input.
// Reject when the agent is still starting, already processing, or in a terminal state.
session, err := s.repo.GetTaskSession(ctx, sessionID)
if err != nil {
return nil, fmt.Errorf("failed to get session: %w", err)
}
switch session.State {
case models.TaskSessionStateWaitingForInput, models.TaskSessionStateCompleted:
// OK — session is ready for a new prompt
case models.TaskSessionStateRunning:
s.logger.Warn("rejected prompt while agent is already running",
zap.String("task_id", taskID),
zap.String("session_id", sessionID),
zap.String("session_state", string(session.State)))
return nil, fmt.Errorf("%w, please wait for completion", ErrAgentPromptInProgress)
default:
s.logger.Warn("rejected prompt: session not ready for input",
zap.String("task_id", taskID),
zap.String("session_id", sessionID),
zap.String("session_state", string(session.State)))
return nil, fmt.Errorf("%w, session is in %s state", ErrAgentPromptInProgress, session.State)
}
// Ensure the agent process is actually running. After a lazy backend restart,
// the session may be in WAITING_FOR_INPUT but no agent process exists yet.
if err := s.ensureSessionRunning(ctx, sessionID, session); err != nil {
return nil, fmt.Errorf("failed to ensure session is running: %w", err)
}
// Inject config context for config-mode sessions (dedicated settings chat, not plan mode)
effectivePrompt := prompt
if cm, ok := session.Metadata["config_mode"].(bool); ok && cm {
effectivePrompt = sysprompt.InjectConfigContext(sessionID, prompt)
}
// Check if model switching is requested
if result, switched, err := s.trySwitchModel(ctx, taskID, sessionID, model, effectivePrompt, session); switched || err != nil {
return result, err
}
previousSessionState := session.State
s.setSessionRunning(ctx, taskID, sessionID, session)
s.startTurnForSession(ctx, sessionID)
// Use context.WithoutCancel to prevent WebSocket request timeout from canceling the prompt.
// Prompts can take a long time (minutes) while the WS request may timeout in 15 seconds.
// We still want to log and respond, but the prompt should continue regardless.
promptCtx := context.WithoutCancel(ctx)
result, err := s.executor.Prompt(promptCtx, taskID, sessionID, effectivePrompt, attachments, session)
if err != nil {
expectedResetInterrupt := false
if isTransientPromptError(err) && s.isSessionResetInProgress(sessionID) {
s.logger.Warn("prompt interrupted by in-progress session reset; retry expected",
zap.String("task_id", taskID),
zap.String("session_id", sessionID),
zap.Error(err))
err = ErrSessionResetInProgress
expectedResetInterrupt = true
}
if expectedResetInterrupt {
s.logger.Warn("prompt deferred while session reset is in progress",
zap.String("task_id", taskID),
zap.String("session_id", sessionID),
zap.Error(err))
} else {
s.logger.Error("prompt failed",
zap.String("task_id", taskID),
zap.String("session_id", sessionID),
zap.Error(err))
}
// Revert session state so it doesn't stay stuck in RUNNING.
// Use repo directly to bypass state machine guards that block transitions from terminal states.
if revertErr := s.repo.UpdateTaskSessionState(ctx, sessionID, previousSessionState, ""); revertErr != nil {
s.logger.Error("failed to revert session state after prompt error",
zap.String("session_id", sessionID),
zap.String("target_state", string(previousSessionState)),
zap.Error(revertErr))
}
if !isTransientPromptError(err) {
_ = s.taskRepo.UpdateTaskState(ctx, taskID, v1.TaskStateReview)
}
s.completeTurnForSession(ctx, sessionID)
return nil, err
}
return &PromptResult{
StopReason: result.StopReason,
AgentMessage: result.AgentMessage,
}, nil
}
// trySwitchModel handles model switching for a prompt. Returns (result, true, nil) if a switch was
// performed, (nil, false, err) on error, or (nil, false, nil) if no switch was needed.
func (s *Service) trySwitchModel(ctx context.Context, taskID, sessionID, model, effectivePrompt string, session *models.TaskSession) (*PromptResult, bool, error) {
if model == "" {
return nil, false, nil
}
var currentModel string
if session.AgentProfileSnapshot != nil {
if m, ok := session.AgentProfileSnapshot["model"].(string); ok {
currentModel = m
}
}
if currentModel == model {
return nil, false, nil
}
s.logger.Info("switching model",
zap.String("task_id", taskID),
zap.String("session_id", sessionID),
zap.String("from", currentModel),
zap.String("to", model))
switchCtx := context.WithoutCancel(ctx)
switchResult, err := s.executor.SwitchModel(switchCtx, taskID, sessionID, model, effectivePrompt)
if err != nil {
return nil, true, fmt.Errorf("model switch failed: %w", err)
}
if switchResult.StopReason == "model_switched_in_place" {
// Agent is still running with the new model — let PromptTask send the prompt normally.
// Invalidate the message creator's model cache so the next message picks up the new model.
if s.messageCreator != nil {
s.messageCreator.InvalidateModelCache(sessionID)
}
return nil, false, nil
}
s.startTurnForSession(ctx, sessionID)
s.setSessionRunning(ctx, taskID, sessionID, session)
return &PromptResult{
StopReason: switchResult.StopReason,
AgentMessage: switchResult.AgentMessage,
}, true, nil
}
// RespondToPermission sends a response to a permission request for a session
func (s *Service) RespondToPermission(ctx context.Context, sessionID, pendingID, optionID string, cancelled bool) error {
s.logger.Debug("responding to permission request",
zap.String("session_id", sessionID),
zap.String("pending_id", pendingID),
zap.String("option_id", optionID),
zap.Bool("cancelled", cancelled))
// Respond to the permission via agentctl
if err := s.executor.RespondToPermission(ctx, sessionID, pendingID, optionID, cancelled); err != nil {
// Permission likely expired — update message so frontend reflects this
if s.messageCreator != nil {
if updateErr := s.messageCreator.UpdatePermissionMessage(ctx, sessionID, pendingID, "expired"); updateErr != nil {
s.logger.Warn("failed to mark expired permission message",
zap.String("session_id", sessionID),
zap.String("pending_id", pendingID),
zap.Error(updateErr))
}
}
return err
}
// Determine status based on response
status := "approved"
if cancelled {
status = "rejected"
}
// Update the permission message with the new status
if s.messageCreator != nil {
if err := s.messageCreator.UpdatePermissionMessage(ctx, sessionID, pendingID, status); err != nil {
s.logger.Warn("failed to update permission message status",
zap.String("session_id", sessionID),
zap.String("pending_id", pendingID),
zap.String("status", status),
zap.Error(err))
// Don't fail the whole operation if message update fails
}
}
if !cancelled {
session, err := s.repo.GetTaskSession(ctx, sessionID)
if err != nil {
s.logger.Warn("failed to load task session after permission response",
zap.String("session_id", sessionID),
zap.Error(err))
return nil
}
s.setSessionRunning(ctx, session.TaskID, sessionID, session)
}
return nil
}
// CancelAgent interrupts the current agent turn without terminating the process,
// allowing the user to send a new prompt.
func (s *Service) CancelAgent(ctx context.Context, sessionID string) error {
s.logger.Debug("cancelling agent turn", zap.String("session_id", sessionID))
// Fetch session for state updates and message creation
session, err := s.repo.GetTaskSession(ctx, sessionID)
if err != nil {
s.logger.Warn("failed to get session for cancel",
zap.String("session_id", sessionID),
zap.Error(err))
}
if err := s.agentManager.CancelAgent(ctx, sessionID); err != nil {
return fmt.Errorf("cancel agent: %w", err)
}
// Transition to WAITING_FOR_INPUT so the user can send a new prompt
if session != nil {
s.updateTaskSessionState(ctx, session.TaskID, sessionID, models.TaskSessionStateWaitingForInput, "", true, session)
}
// Record cancellation in the message history
if s.messageCreator != nil && session != nil {
metadata := map[string]interface{}{
"cancelled": true,
"variant": "warning",
}
if err := s.messageCreator.CreateSessionMessage(
ctx,
session.TaskID,
"Turn cancelled by user",
sessionID,
string(v1.MessageTypeStatus),
s.getActiveTurnID(sessionID),
metadata,
false,
); err != nil {
s.logger.Warn("failed to create cancel message",
zap.String("session_id", sessionID),
zap.Error(err))
}
}
// Complete the turn since the agent was cancelled
s.completeTurnForSession(ctx, sessionID)
s.logger.Debug("agent turn cancelled", zap.String("session_id", sessionID))
return nil
}
// CompleteTask explicitly completes a task and stops all its agents
func (s *Service) CompleteTask(ctx context.Context, taskID string) error {
s.logger.Info("completing task",
zap.String("task_id", taskID))
// Stop all agents for this task (which will trigger AgentCompleted events and update session states)
if err := s.executor.StopByTaskID(ctx, taskID, "task completed by user", false); err != nil {
// If agents are already stopped, just update the task state directly
s.logger.Warn("failed to stop agents, updating task state directly",
zap.String("task_id", taskID),
zap.Error(err))
}
// Update task state to COMPLETED
if err := s.taskRepo.UpdateTaskState(ctx, taskID, v1.TaskStateCompleted); err != nil {
return fmt.Errorf("failed to update task state: %w", err)
}
s.logger.Info("task marked as COMPLETED",
zap.String("task_id", taskID))
return nil
}
// ResetAgentContext resets the agent's conversation context for a session,
// clearing conversation history while preserving the workspace environment.
func (s *Service) ResetAgentContext(ctx context.Context, sessionID string) error {
session, err := s.repo.GetTaskSession(ctx, sessionID)
if err != nil {
return fmt.Errorf("session not found: %w", err)
}
if session.State != models.TaskSessionStateWaitingForInput {
return fmt.Errorf("agent must be idle to reset context, current state: %s", session.State)
}
if session.AgentExecutionID == "" {
return fmt.Errorf("no active agent execution for session %s", sessionID)
}
// Set STARTING so frontend disables input and shows restarting state
s.updateTaskSessionState(ctx, session.TaskID, sessionID, models.TaskSessionStateStarting, "", false, session)
if ok := s.resetAgentContext(ctx, session.TaskID, session, "user_request"); !ok {
// Restore WAITING_FOR_INPUT on failure
s.setSessionWaitingForInput(ctx, session.TaskID, sessionID)
return fmt.Errorf("failed to reset agent context for session %s", sessionID)
}
// Restore WAITING_FOR_INPUT — handleAgentReady ignores events during reset
s.setSessionWaitingForInput(ctx, session.TaskID, sessionID)
if s.messageCreator != nil {
if err := s.messageCreator.CreateSessionMessage(
ctx, session.TaskID,
"Context reset — new conversation started",
sessionID, string(v1.MessageTypeStatus),
s.getActiveTurnID(sessionID),
nil, false,
); err != nil {
s.logger.Warn("failed to create context reset message",
zap.String("session_id", sessionID), zap.Error(err))
}
}
return nil
}
// GetQueuedTasks returns tasks in the queue
func (s *Service) GetQueuedTasks() []*queue.QueuedTask {
return s.queue.List()
}