From 3d2a04e77669237f4d0e4fca3051f1b9e48718ba Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Salavisa?= Date: Thu, 30 Apr 2026 18:17:36 +0100 Subject: [PATCH] feat(orchestrator): deferred task move with hand-off prompt + boot/turn-end event split (#743) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(orchestrator): reuse existing same-profile session on workflow step switch When a workflow step transition needs a different agent profile, look up an existing session on the same task that already uses the target profile and promote it back to primary instead of creating a fresh one. Reuses COMPLETED and FAILED sessions (CANCELLED stays excluded — explicit user stops shouldn't be auto-revived). Backend (event_handlers_workflow.go): - findReusableSessionForProfile: most recently updated session matching the target profile, skipping CANCELLED. - reuseSessionForStep: promotes the session to primary; if terminal, revives via reviveReusedSession. - reviveReusedSession: distinguishes "previously launched" (has executors_running record -> flip to WAITING_FOR_INPUT, lazy-resume via ResumeSession with stored token) from "never launched" (no record -> flip to CREATED so autoStartStepPrompt routes through StartCreatedSession for a full fresh launch). Clears stale ErrorMessage/CompletedAt so the UI stops surfacing prior failures. - createNewSessionForStep + completeAndStopSession: shared helpers. Backend (task_operations.go): - StartCreatedSession no longer calls processOnTurnStartViaEngine. User-initiated messages already fire on_turn_start in dispatchPromptAsync. Workflow-driven auto-start prompts arrived because the workflow just transitioned us into this step via on_turn_complete; firing on_turn_start again cascades the workflow back out and the redirect-to-active-session logic delivers the prompt to the wrong session's agent. Frontend (web): - task.updated handler follows focus to the new primary when the user is viewing the task and was sitting on the previous primary. - pinnedSessionId tracks user-initiated session selection (setActiveSession sets it; setActiveSessionAuto leaves it alone). The terminal-handoff branch in maybeAdoptSessionOnTransition skips replacement when the terminating session matches the pin, so manually clicking a session no longer yanks focus back to the workflow primary each time the pinned session terminates. Tests: - TestSwitchSessionForStep_ReusesExistingProfileSession (never-launched). - TestSwitchSessionForStep_ReusesPreviouslyLaunchedSession (launched). - TestSwitchSessionForStep_ReusesFailedSession (FAILED reuse + cleanup). - tasks.test.ts: focus-follow behavior across 4 scenarios. - agent-session.test.ts: pinnedSessionId guard plus migration to setActiveSessionAuto for WS-driven adoption. Co-Authored-By: Claude Opus 4.7 * feat(orchestrator): deferred task move with hand-off prompt + boot/turn-end event split Adds move_task_kandev MCP tool that lets a workflow agent (e.g. QA at "Review") move a task to another step with a prompt for the receiving agent. The move is queued as a PendingMove and applied on the calling agent's turn-end so on_enter processing doesn't race the still-running turn. Also splits agent.ready into agent.boot_ready + agent.ready at the lifecycle layer. Previously both signals shared one event and the orchestrator disambiguated them via a resumeInProgressSessions flag — which had a race when the boot signal arrived before persistResumeState wrote state=STARTING, causing the boot to fire on_turn_complete against the just-revived step and ping-pong the task forward through the workflow. Co-Authored-By: Claude Opus 4.7 * fix: address PR #743 review feedback (Greptile + CodeRabbit) Backend: - isTransientPromptError no longer treats ErrExecutionNotFound as transient, preventing executeQueuedMessage from infinite-requeueing on permanent missing-execution errors. autoStartStepPrompt's explicit errors.Is check before the transient branch keeps the recovery path working (Greptile P2 #1) - applyPendingMove drains the orphaned hand-off prompt on ApplyTransition failure so it can't be misdelivered to the source step on a future turn (Greptile P2 #2) - handleMoveTask returns errors instead of panicking when messageQueue is nil; queueMoveTaskPrompt returns an error so the deferred path fails fast if the queue can't accept the prompt (CodeRabbit CR-2) - handleMoveTask rejects when no primary session exists and a hand-off prompt is required, instead of silently dropping it (CodeRabbit CR-3) - autoStartStepPrompt preserves attachments from queued messages (was: silently dropped); attachment-only messages are no longer skipped; the fallback path also forwards attachments (CodeRabbit CR-5) - applyPendingMove reinserts the pending move on early failure paths (config missing, task/step load errors) so a future turn-end retries naturally (CodeRabbit CR-6) - registerKanbanTools split into 3 helpers (list/profile/task) to satisfy backend function-size lint limits (CodeRabbit CR-1) Web: - maybeAdoptSessionOnTransition's auto-adopt path also checks pinnedSessionId to handle the reverse-event-ordering race (old COMPLETED arrives before new STARTING) — pinned sessions are no longer yanked off the user. Regression test added (CodeRabbit CR-7) Tests: - mockAgentManager records (executionID, prompt) pairs; new helper capturedPromptsForExecution actually filters by exec ID instead of returning all captured prompts (CodeRabbit CR-4) Co-Authored-By: Claude Opus 4.7 * fix(web): respect pinned session in primary-follow-focus path When the user clicks a session, setActiveSession sets pinnedSessionId. If a workflow profile switch then updates the task's primarySessionId while the user happens to still be on the previous primary, the focus-follow block in tasks.ts was calling setActiveSessionAuto(taskId, newPrimary) and silently overriding the explicit pin. Add pinnedSessionId !== previousPrimary as a fifth condition. Regression test in tasks.test.ts covers exactly this sequence. Addresses Greptile P1 on PR #743. Co-Authored-By: Claude Opus 4.7 * fix: address CodeRabbit review on PR #743 (3 new comments) - handleMoveTask idle path now rolls back the queued hand-off prompt when taskSvc.MoveTask fails, so a "you were moved..." message can't be delivered on a future turn for a transition that didn't actually happen. Added TakeQueued to the MessageQueuer interface to support this. - lookupSession now returns (*models.TaskSession, error) so callers can distinguish a backend lookup failure from a legitimate "no primary session" state. handleMoveTask maps the error case to ErrorCodeInternalError instead of collapsing it into ErrorCodeValidation. - queueMoveTaskPrompt returns errors instead of log-and-continue (signature change already shipped); existing tests updated to reflect the new contract. - Refactored TestPendingMove_ReviewToInProgress_OneTransitionOnly: the ~280-line monolithic test is now split into a pendingMoveScenario builder + assertion helpers, each well under the 80-line / 50-statement lint limit. All 14 review threads resolved. Co-Authored-By: Claude Opus 4.7 * fix: relax move_task_kandev prompt requirement; fix CI lint CI surfaced two issues after rebasing onto main: - nestif lint warning on autoStartStepPrompt's queued-message merge block. Extracted the take-and-merge logic into takeAndMergeHandoffMessage helper, flattening the nested conditionals. - E2E test settings/config-management 'agent can move a task to a different step' failed because my CR-3 fix made the move_task_kandev prompt parameter required. That broke admin/config-mode moves where there's no agent to hand off to. Made prompt optional: when supplied AND the source session is mid-turn, the deferred-move flow runs (queue prompt + record PendingMove); otherwise just move the task. Refactored handleMoveTask into deferMoveTaskWithPrompt and applyMoveTaskImmediate to keep each function under the 80-line lint limit. Tool descriptions in mcp/server/server.go and mcp/server/config_handlers.go updated to reflect prompt's now-optional status. moveTaskHandler in config_handlers.go forwards prompt only when set. Co-Authored-By: Claude Opus 4.7 * fix(mcp): treat 'no primary session' as a not-found, not an internal error GetPrimarySessionByTaskID returns a plain error string ("no primary session found for task: ") when the repo has no rows. My CR-B refactor was treating ALL lookup errors as ErrorCodeInternalError, which broke the E2E test 'agent can move a task to a different step' (config-mode move on a freshly-created task that has no agent yet). Match the not-found message and return (nil, nil); only real backend failures bubble up as InternalError. Distinguishing properly with errors.Is would require an exported sentinel that doesn't exist; matching the noRowsErr substring is the pragmatic fix. Co-Authored-By: Claude Opus 4.7 --------- Co-authored-by: Kandev Agent Co-authored-by: Claude Opus 4.7 --- apps/backend/cmd/kandev/helpers.go | 2 +- .../agent/lifecycle/manager_interaction.go | 67 +- .../lifecycle/manager_interaction_test.go | 7 +- .../agent/lifecycle/manager_profile.go | 8 +- apps/backend/internal/events/types.go | 3 +- .../integration/mcp_integration_test.go | 2 +- .../mcp/handlers/config_handlers_test.go | 79 +++ .../mcp/handlers/config_task_handlers.go | 177 ++++++ .../backend/internal/mcp/handlers/handlers.go | 14 + .../internal/mcp/server/config_handlers.go | 8 +- apps/backend/internal/mcp/server/server.go | 13 +- .../internal/mcp/server/server_test.go | 6 +- .../orchestrator/event_handlers_agent.go | 114 +++- .../event_handlers_pending_move_test.go | 588 ++++++++++++++++++ .../orchestrator/event_handlers_test.go | 16 +- .../orchestrator/event_handlers_workflow.go | 429 ++++++++++++- .../event_handlers_workflow_profile_test.go | 320 ++++++++++ .../orchestrator/messagequeue/service.go | 65 +- .../orchestrator/messagequeue/service_test.go | 79 +++ .../orchestrator/messagequeue/types.go | 12 + apps/backend/internal/orchestrator/service.go | 1 + .../internal/orchestrator/task_operations.go | 50 +- .../internal/orchestrator/watcher/watcher.go | 4 +- apps/web/lib/ssr/mapper.ts | 1 + .../lib/state/slices/kanban/kanban-slice.ts | 14 +- apps/web/lib/state/slices/kanban/types.ts | 10 + apps/web/lib/state/store.ts | 1 + .../web/lib/ws/handlers/agent-session.test.ts | 103 ++- apps/web/lib/ws/handlers/agent-session.ts | 15 +- apps/web/lib/ws/handlers/tasks.test.ts | 179 ++++++ apps/web/lib/ws/handlers/tasks.ts | 39 +- 31 files changed, 2325 insertions(+), 101 deletions(-) create mode 100644 apps/backend/internal/orchestrator/event_handlers_pending_move_test.go create mode 100644 apps/web/lib/ws/handlers/tasks.test.ts diff --git a/apps/backend/cmd/kandev/helpers.go b/apps/backend/cmd/kandev/helpers.go index 9078cba963..ab43d72037 100644 --- a/apps/backend/cmd/kandev/helpers.go +++ b/apps/backend/cmd/kandev/helpers.go @@ -513,7 +513,7 @@ func registerMCPAndDebugRoutes( ) { mcpHandlers := mcphandlers.NewHandlers( p.taskSvc, wfCtrl, - clarificationStore, p.msgCreator, p.taskRepo, p.taskRepo, p.eventBus, planService, p.orchestratorSvc, p.log, + clarificationStore, p.msgCreator, p.taskRepo, p.taskRepo, p.eventBus, planService, p.orchestratorSvc, p.orchestratorSvc.GetMessageQueue(), p.log, ) // Wire config-mode dependencies for agent-native configuration mcpHandlers.SetConfigDeps(p.services.Workflow, p.agentSettingsController, p.mcpConfigSvc) diff --git a/apps/backend/internal/agent/lifecycle/manager_interaction.go b/apps/backend/internal/agent/lifecycle/manager_interaction.go index e8ca27209e..5a4180e3f8 100644 --- a/apps/backend/internal/agent/lifecycle/manager_interaction.go +++ b/apps/backend/internal/agent/lifecycle/manager_interaction.go @@ -341,7 +341,12 @@ func (m *Manager) ResetAgentContext(ctx context.Context, executionID string) err zap.String("new_acp_session_id", newSessionID)) m.eventPublisher.PublishAgentEvent(ctx, events.AgentContextReset, execution) - m.eventPublisher.PublishAgentEvent(ctx, events.AgentReady, execution) + // Boot-equivalent signal: a fresh ACP session is alive but no turn has run yet. + // Use AgentBootReady so the orchestrator routes this to handleAgentBootReady + // (idle/WAITING transition) rather than handleAgentReady (turn-end transition, + // which would fire on_turn_complete against the current step — the original + // boot-vs-turn ambiguity bug). + m.eventPublisher.PublishAgentEvent(ctx, events.AgentBootReady, execution) return nil } @@ -595,9 +600,11 @@ func (m *Manager) initializeACPSessionForRestart( m.sessionManager.eventPublisher.PublishACPSessionCreated(execution, result.SessionID) } - // Mark execution as ready + // Mark execution as ready. This is a *boot* signal — initializeACPSessionForRestart + // is the post-restart init path and no turn has run yet, so AgentBootReady (not + // AgentReady) is what subscribers want to route on. m.executionStore.UpdateStatus(execution.ID, v1.AgentStatusReady) - m.eventPublisher.PublishAgentEvent(ctx, events.AgentReady, execution) + m.eventPublisher.PublishAgentEvent(ctx, events.AgentBootReady, execution) return nil } @@ -813,42 +820,62 @@ func (m *Manager) UpdateStatus(executionID string, status v1.AgentStatus) error return nil } -// MarkReady marks an execution as ready for follow-up prompts. +// MarkReady marks an execution as ready for follow-up prompts AFTER A TURN. +// Use MarkBootReady instead when the agent has just initialized and hasn't yet +// processed a turn — orchestrator subscribers rely on the distinction. // // This transitions the execution to the "ready" state, indicating the agent has finished -// processing the current prompt and is waiting for user input. This is called: -// - After agent initialization completes (session loaded, workspace ready) -// - After agent finishes processing a prompt (via stream completion event) -// - After cancelling an agent turn (to allow new prompts) +// processing the current prompt and is waiting for user input. Called when: +// - Agent finishes processing a prompt (via stream completion event) +// - User cancels an agent turn (to allow new prompts) +// +// State Machine Transitions: +// +// Running -> Ready (after prompt completion) +// Any -> Ready (after cancel) +// +// Publishes events.AgentReady. Returns error if execution not found. +func (m *Manager) MarkReady(executionID string) error { + return m.markReadyEvent(executionID, events.AgentReady) +} + +// MarkBootReady marks a freshly-initialized execution as ready for its first +// prompt. Distinct from MarkReady so the orchestrator can disambiguate boot +// signals from turn-end signals without race-prone flag tracking. Use this +// from session/init paths and post-context-reset; use MarkReady from the +// turn-completion path. // // State Machine Transitions: // // Starting -> Ready (after initialization) -// Running -> Ready (after prompt completion) -// Any -> Ready (after cancel) // -// Publishes an AgentReady event to notify subscribers (frontend, orchestrator). -// -// Returns error if execution not found. -func (m *Manager) MarkReady(executionID string) error { +// Publishes events.AgentBootReady. Returns error if execution not found. +func (m *Manager) MarkBootReady(executionID string) error { + return m.markReadyEvent(executionID, events.AgentBootReady) +} + +// markReadyEvent is the shared body of MarkReady / MarkBootReady — both flip +// the execution to the Ready status and publish their respective event type. +func (m *Manager) markReadyEvent(executionID, eventType string) error { execution, exists := m.executionStore.Get(executionID) if !exists { return fmt.Errorf("execution %q not found", executionID) } - // Skip if already ready (prevents duplicate events) + // Skip if already ready (prevents duplicate events). This guard is shared + // across MarkReady and MarkBootReady — once Ready is set, neither type fires + // again until the next status transition (Running on prompt, Stopped on stop). if execution.Status == v1.AgentStatusReady { return nil } m.executionStore.UpdateStatus(executionID, v1.AgentStatusReady) - m.logger.Info("execution ready for follow-up prompts", - zap.String("execution_id", executionID)) - - // Publish ready event - m.eventPublisher.PublishAgentEvent(context.Background(), events.AgentReady, execution) + m.logger.Info("execution ready", + zap.String("execution_id", executionID), + zap.String("event_type", eventType)) + m.eventPublisher.PublishAgentEvent(context.Background(), eventType, execution) return nil } diff --git a/apps/backend/internal/agent/lifecycle/manager_interaction_test.go b/apps/backend/internal/agent/lifecycle/manager_interaction_test.go index 664f5ceb26..3d995f7c9b 100644 --- a/apps/backend/internal/agent/lifecycle/manager_interaction_test.go +++ b/apps/backend/internal/agent/lifecycle/manager_interaction_test.go @@ -251,8 +251,11 @@ func TestManager_RestartAgentProcess_Success(t *testing.T) { for _, ev := range mockBus.PublishedEvents { eventTypes = append(eventTypes, ev.Type) } - if !slices.Contains(eventTypes, events.AgentReady) { - t.Fatalf("expected %q event, got %v", events.AgentReady, eventTypes) + // Restart is a boot scenario — initializeACPSessionForRestart publishes + // AgentBootReady (not AgentReady) so the orchestrator routes it to + // handleAgentBootReady rather than evaluating on_turn_complete. + if !slices.Contains(eventTypes, events.AgentBootReady) { + t.Fatalf("expected %q event, got %v", events.AgentBootReady, eventTypes) } if !slices.Contains(eventTypes, events.AgentACPSessionCreated) { t.Fatalf("expected %q event, got %v", events.AgentACPSessionCreated, eventTypes) diff --git a/apps/backend/internal/agent/lifecycle/manager_profile.go b/apps/backend/internal/agent/lifecycle/manager_profile.go index 8891ed4586..715eb81ce4 100644 --- a/apps/backend/internal/agent/lifecycle/manager_profile.go +++ b/apps/backend/internal/agent/lifecycle/manager_profile.go @@ -157,8 +157,12 @@ func (m *Manager) resolveProfileModelAndMode(ctx context.Context, profileID stri return info.Model, info.Mode } -// initializeACPSession delegates to SessionManager for full ACP session initialization and prompting +// initializeACPSession delegates to SessionManager for full ACP session initialization and prompting. +// We pass MarkBootReady (not MarkReady) for the no-prompt branches: dispatchInitialPrompt only +// invokes the callback when there's no taskDescription/attachments to send, which is a *boot* +// signal (the agent has never run a turn). When there IS a prompt, the callback is unused and +// MarkReady fires later from handleCompleteEvent — that path is the true turn-end. func (m *Manager) initializeACPSession(ctx context.Context, execution *AgentExecution, agentConfig agents.Agent, taskDescription string, attachments []MessageAttachment, mcpServers []agentctltypes.McpServer) error { profileModel, profileMode := m.resolveProfileModelAndMode(ctx, execution.AgentProfileID) - return m.sessionManager.InitializeAndPrompt(ctx, execution, agentConfig, taskDescription, attachments, mcpServers, m.MarkReady, profileModel, profileMode) + return m.sessionManager.InitializeAndPrompt(ctx, execution, agentConfig, taskDescription, attachments, mcpServers, m.MarkBootReady, profileModel, profileMode) } diff --git a/apps/backend/internal/events/types.go b/apps/backend/internal/events/types.go index 80f5e54fd3..0b4813ca5d 100644 --- a/apps/backend/internal/events/types.go +++ b/apps/backend/internal/events/types.go @@ -119,7 +119,8 @@ const ( const ( AgentStarted = "agent.started" AgentRunning = "agent.running" - AgentReady = "agent.ready" // Agent finished prompt, ready for follow-up + AgentBootReady = "agent.boot_ready" // Agent's ACP session initialized, ready to receive its first prompt. Distinct from AgentReady so the orchestrator can tell a boot signal apart from a turn-end without flag-based disambiguation. + AgentReady = "agent.ready" // Agent finished a prompt turn, ready for follow-up AgentCompleted = "agent.completed" AgentFailed = "agent.failed" AgentStopped = "agent.stopped" diff --git a/apps/backend/internal/integration/mcp_integration_test.go b/apps/backend/internal/integration/mcp_integration_test.go index a9195e6268..fa5578e257 100644 --- a/apps/backend/internal/integration/mcp_integration_test.go +++ b/apps/backend/internal/integration/mcp_integration_test.go @@ -18,7 +18,7 @@ func setupMCPTestServer(t *testing.T) (*TestServer, string, string, string, stri ts := NewTestServer(t) // Register MCP handlers on the gateway dispatcher - mcpH := mcphandlers.NewHandlers(ts.TaskSvc, nil, nil, nil, nil, nil, nil, nil, nil, ts.Logger) + mcpH := mcphandlers.NewHandlers(ts.TaskSvc, nil, nil, nil, nil, nil, nil, nil, nil, nil, ts.Logger) mcpH.RegisterHandlers(ts.Gateway.Dispatcher) client := NewWSClient(t, ts.Server.URL) diff --git a/apps/backend/internal/mcp/handlers/config_handlers_test.go b/apps/backend/internal/mcp/handlers/config_handlers_test.go index 5e8f126a08..377da09c63 100644 --- a/apps/backend/internal/mcp/handlers/config_handlers_test.go +++ b/apps/backend/internal/mcp/handlers/config_handlers_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/orchestrator/messagequeue" ws "github.com/kandev/kandev/pkg/websocket" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" @@ -341,6 +342,84 @@ func TestHandleMoveTask_InvalidPayload(t *testing.T) { assertWSError(t, resp, ws.ErrorCodeBadRequest) } +// recordingMessageQueuer captures QueueMessage calls for assertion. +type recordingMessageQueuer struct { + calls []messagequeue.QueuedMessage +} + +func (r *recordingMessageQueuer) QueueMessage(_ context.Context, sessionID, taskID, content, model, userID string, planMode bool, _ []messagequeue.MessageAttachment) (*messagequeue.QueuedMessage, error) { + msg := messagequeue.QueuedMessage{ + SessionID: sessionID, + TaskID: taskID, + Content: content, + Model: model, + PlanMode: planMode, + QueuedBy: userID, + } + r.calls = append(r.calls, msg) + return &msg, nil +} + +func (r *recordingMessageQueuer) SetPendingMove(_ context.Context, _ string, _ *messagequeue.PendingMove) { +} + +// TakeQueued is a no-op stub — the unit tests below don't exercise rollback, +// they just exercise QueueMessage. Returning (nil, false) is consistent with +// "nothing to take", which is what the rollback path checks before logging. +func (r *recordingMessageQueuer) TakeQueued(_ context.Context, _ string) (*messagequeue.QueuedMessage, bool) { + return nil, false +} + +// TestQueueMoveTaskPrompt_NilQueueReturnsError ensures the call is safe (no panic) +// and surfaces a descriptive error so callers can fail fast instead of silently +// dropping the user-supplied prompt. +func TestQueueMoveTaskPrompt_NilQueueReturnsError(t *testing.T) { + h := &Handlers{logger: testLogger(t).WithFields()} + + err := h.queueMoveTaskPrompt(context.Background(), "task-1", "session-1", "fix issues") + require.Error(t, err) + assert.Contains(t, err.Error(), "message queue") +} + +// TestQueueMoveTaskPrompt_EmptySessionIDReturnsError ensures a missing session ID +// surfaces an error rather than silently no-op'ing — without a session there's +// nowhere to deliver the prompt. +func TestQueueMoveTaskPrompt_EmptySessionIDReturnsError(t *testing.T) { + queue := &recordingMessageQueuer{} + h := &Handlers{ + messageQueue: queue, + logger: testLogger(t).WithFields(), + } + + err := h.queueMoveTaskPrompt(context.Background(), "task-1", "", "fix issues") + require.Error(t, err) + assert.Contains(t, err.Error(), "primary session") + assert.Empty(t, queue.calls, "queue must not be invoked without a session ID") +} + +// TestQueueMoveTaskPrompt_QueuesWithExpectedFields verifies the happy-path +// invocation: the prompt is queued on the resolved session with the expected +// metadata (sender = "mcp-move-task", plan mode disabled, no model override). +func TestQueueMoveTaskPrompt_QueuesWithExpectedFields(t *testing.T) { + queue := &recordingMessageQueuer{} + h := &Handlers{ + messageQueue: queue, + logger: testLogger(t).WithFields(), + } + + err := h.queueMoveTaskPrompt(context.Background(), "task-1", "session-99", "Please fix the failing test in foo_test.go") + require.NoError(t, err) + + require.Len(t, queue.calls, 1) + got := queue.calls[0] + assert.Equal(t, "session-99", got.SessionID) + assert.Equal(t, "task-1", got.TaskID) + assert.Equal(t, "Please fix the failing test in foo_test.go", got.Content) + assert.Equal(t, "mcp-move-task", got.QueuedBy) + assert.False(t, got.PlanMode) + assert.Equal(t, "", got.Model) +} + func TestHandleDeleteTask_MissingTaskID(t *testing.T) { h := &Handlers{} msg := makeWSMessage(t, ws.ActionMCPDeleteTask, map[string]string{}) diff --git a/apps/backend/internal/mcp/handlers/config_task_handlers.go b/apps/backend/internal/mcp/handlers/config_task_handlers.go index 4589e589fc..f9021aac77 100644 --- a/apps/backend/internal/mcp/handlers/config_task_handlers.go +++ b/apps/backend/internal/mcp/handlers/config_task_handlers.go @@ -3,8 +3,12 @@ package handlers import ( "context" "encoding/json" + "fmt" + "strings" + "github.com/kandev/kandev/internal/orchestrator/messagequeue" "github.com/kandev/kandev/internal/task/dto" + "github.com/kandev/kandev/internal/task/models" v1 "github.com/kandev/kandev/pkg/api/v1" ws "github.com/kandev/kandev/pkg/websocket" "go.uber.org/zap" @@ -16,6 +20,7 @@ func (h *Handlers) handleMoveTask(ctx context.Context, msg *ws.Message) (*ws.Mes WorkflowID string `json:"workflow_id"` WorkflowStepID string `json:"workflow_step_id"` Position int `json:"position"` + Prompt string `json:"prompt"` } if err := json.Unmarshal(msg.Payload, &req); err != nil { return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil) @@ -30,14 +35,186 @@ func (h *Handlers) handleMoveTask(ctx context.Context, msg *ws.Message) (*ws.Mes return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "workflow_step_id is required", nil) } + // Prompt is OPTIONAL — config-mode/admin moves don't always have an agent + // to hand off to. When supplied, it activates the deferred-move path that + // hands the receiving agent a directive on its first turn at the new step. + // When omitted, we just move the task and return. + session, lookupErr := h.lookupSession(ctx, req.TaskID) + if lookupErr != nil { + // Backend lookup failure is an internal error, not validation — don't + // collapse it into "you have no session" downstream. + h.logger.Error("move_task: failed to look up primary session", + zap.String("task_id", req.TaskID), zap.Error(lookupErr)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, + "failed to look up task's primary session", nil) + } + + // Active source session + prompt → deferred path. Running MoveTask now + // would race on_enter processing against the agent's still-active turn — + // corrupting session state and orphaning the queued prompt. Defer until + // handleAgentReady fires applyPendingMove on turn-end. + if req.Prompt != "" && session != nil && + (session.State == models.TaskSessionStateRunning || session.State == models.TaskSessionStateStarting) { + return h.deferMoveTaskWithPrompt(ctx, msg, req, session) + } + + // Idle path — apply immediately. If a prompt was supplied, queue it on the + // session so the receiving agent's next turn picks it up; if not, just move. + return h.applyMoveTaskImmediate(ctx, msg, req, session) +} + +// deferMoveTaskWithPrompt queues the hand-off prompt + records a PendingMove +// for the agent's turn-end handler to apply. Used when the source session is +// active and the caller supplied a prompt. Returns a synthetic moved-task DTO +// so the agent's tool call resolves successfully and ends the turn cleanly. +func (h *Handlers) deferMoveTaskWithPrompt( + ctx context.Context, + msg *ws.Message, + req struct { + TaskID string `json:"task_id"` + WorkflowID string `json:"workflow_id"` + WorkflowStepID string `json:"workflow_step_id"` + Position int `json:"position"` + Prompt string `json:"prompt"` + }, + session *models.TaskSession, +) (*ws.Message, error) { + if h.messageQueue == nil { + h.logger.Error("move_task: message queue not configured; cannot defer move from active session", + zap.String("task_id", req.TaskID), zap.String("session_id", session.ID)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, + "move_task requires message queue support while the source session is active", nil) + } + wrapped := "You were moved to this step with the following message: " + req.Prompt + if err := h.queueMoveTaskPrompt(ctx, req.TaskID, session.ID, wrapped); err != nil { + h.logger.Error("move_task: failed to queue hand-off prompt", + zap.String("task_id", req.TaskID), zap.String("session_id", session.ID), zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, + "failed to queue move_task hand-off prompt", nil) + } + h.messageQueue.SetPendingMove(ctx, session.ID, &messagequeue.PendingMove{ + TaskID: req.TaskID, + WorkflowID: req.WorkflowID, + WorkflowStepID: req.WorkflowStepID, + Position: req.Position, + }) + return ws.NewResponse(msg.ID, msg.Action, + h.synthesizeMovedTaskDTO(ctx, req.TaskID, req.WorkflowID, req.WorkflowStepID, req.Position)) +} + +// applyMoveTaskImmediate runs the move now, optionally queueing a hand-off +// prompt on the (idle) primary session beforehand. Used when the source +// session is idle, when there's no source session at all, or when no prompt +// was supplied (config-mode/admin moves). +func (h *Handlers) applyMoveTaskImmediate( + ctx context.Context, + msg *ws.Message, + req struct { + TaskID string `json:"task_id"` + WorkflowID string `json:"workflow_id"` + WorkflowStepID string `json:"workflow_step_id"` + Position int `json:"position"` + Prompt string `json:"prompt"` + }, + session *models.TaskSession, +) (*ws.Message, error) { + queuedSessionID := "" + if req.Prompt != "" && session != nil { + wrapped := "You were moved to this step with the following message: " + req.Prompt + if err := h.queueMoveTaskPrompt(ctx, req.TaskID, session.ID, wrapped); err != nil { + h.logger.Error("move_task: failed to queue hand-off prompt for idle session", + zap.String("task_id", req.TaskID), zap.String("session_id", session.ID), zap.Error(err)) + return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, + "failed to queue move_task hand-off prompt", nil) + } + queuedSessionID = session.ID + } + result, err := h.taskSvc.MoveTask(ctx, req.TaskID, req.WorkflowID, req.WorkflowStepID, req.Position) if err != nil { + // Roll back the queued prompt — without this, the next turn would + // deliver a "You were moved to this step…" message for a transition + // that didn't actually happen. + if queuedSessionID != "" && h.messageQueue != nil { + if _, ok := h.messageQueue.TakeQueued(ctx, queuedSessionID); ok { + h.logger.Warn("move_task: dropped queued hand-off prompt after MoveTask failure", + zap.String("task_id", req.TaskID), zap.String("session_id", queuedSessionID)) + } + } h.logger.Error("failed to move task", zap.Error(err)) return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to move task", nil) } return ws.NewResponse(msg.ID, msg.Action, dto.FromTask(result.Task)) } +// synthesizeMovedTaskDTO returns a task DTO with the post-move step/workflow +// values filled in. Used by the deferred-move path so the agent's tool call +// sees a "successful move" response shape, freeing it to end the turn (which +// is what triggers applyPendingMove). If we can't load the task, fall back to +// a minimal map so the call still resolves. +func (h *Handlers) synthesizeMovedTaskDTO(ctx context.Context, taskID, workflowID, workflowStepID string, position int) any { + task, err := h.taskSvc.GetTask(ctx, taskID) + if err != nil || task == nil { + h.logger.Warn("failed to load task for synthetic move response", + zap.String("task_id", taskID), + zap.Error(err)) + return map[string]any{ + "id": taskID, + "workflow_id": workflowID, + "workflow_step_id": workflowStepID, + "position": position, + } + } + clone := *task + clone.WorkflowID = workflowID + clone.WorkflowStepID = workflowStepID + clone.Position = position + return dto.FromTask(&clone) +} + +// lookupSession returns the task's primary session. +// - (session, nil) — task has a primary session. +// - (nil, nil) — task has no primary session yet (legitimate "empty" +// state — task was created but no agent has been launched). The +// repository signals this with a "no primary session found for task:" +// error string; we treat it as a not-found rather than a failure so the +// caller can fall through to the idle-move path instead of rejecting the +// request. +// - (nil, err) — real backend lookup failure (DB error, etc.). The +// caller should map this to an internal error rather than collapsing it +// into "no session" downstream. +func (h *Handlers) lookupSession(ctx context.Context, taskID string) (*models.TaskSession, error) { + session, err := h.taskSvc.GetPrimarySession(ctx, taskID) + if err != nil { + // "no primary session found for task: " is the repo's not-found + // signal — see scanTaskSession's noRowsErr formatting. Match by + // substring; there's no exported sentinel to errors.Is against. + if strings.Contains(err.Error(), "no primary session found for task") { + return nil, nil + } + return nil, err + } + return session, nil +} + +// queueMoveTaskPrompt enqueues a user-supplied prompt on the task's primary session. +// Returns an error when the queue itself is missing or QueueMessage fails — the +// caller decides whether to fail the whole move (running-session deferred path) +// or proceed (idle path), since a queue failure makes the deferred contract +// impossible to honor. +func (h *Handlers) queueMoveTaskPrompt(ctx context.Context, taskID, sessionID, prompt string) error { + if h.messageQueue == nil { + return fmt.Errorf("message queue is unavailable") + } + if sessionID == "" { + return fmt.Errorf("task has no primary session") + } + if _, err := h.messageQueue.QueueMessage(ctx, sessionID, taskID, prompt, "", "mcp-move-task", false, nil); err != nil { + return fmt.Errorf("queue message: %w", err) + } + return nil +} + func (h *Handlers) handleDeleteTask(ctx context.Context, msg *ws.Message) (*ws.Message, error) { taskID, err := unmarshalStringField(msg.Payload, "task_id") if err != nil { diff --git a/apps/backend/internal/mcp/handlers/handlers.go b/apps/backend/internal/mcp/handlers/handlers.go index 2567f97cf7..41b04b8a6f 100644 --- a/apps/backend/internal/mcp/handlers/handlers.go +++ b/apps/backend/internal/mcp/handlers/handlers.go @@ -17,6 +17,7 @@ import ( "github.com/kandev/kandev/internal/events" "github.com/kandev/kandev/internal/events/bus" "github.com/kandev/kandev/internal/orchestrator" + "github.com/kandev/kandev/internal/orchestrator/messagequeue" "github.com/kandev/kandev/internal/task/dto" "github.com/kandev/kandev/internal/task/models" "github.com/kandev/kandev/internal/task/service" @@ -60,6 +61,16 @@ type SessionLauncher interface { LaunchSession(ctx context.Context, req *orchestrator.LaunchSessionRequest) (*orchestrator.LaunchSessionResponse, error) } +// MessageQueuer queues a prompt message for delivery to a session on its next turn. +// TakeQueued is exposed so move_task can roll back the hand-off prompt when the +// underlying MoveTask call fails — without it, a queued "you were moved..." +// message would survive a failed move and be delivered on the next agent turn. +type MessageQueuer interface { + QueueMessage(ctx context.Context, sessionID, taskID, content, model, userID string, planMode bool, attachments []messagequeue.MessageAttachment) (*messagequeue.QueuedMessage, error) + SetPendingMove(ctx context.Context, sessionID string, move *messagequeue.PendingMove) + TakeQueued(ctx context.Context, sessionID string) (*messagequeue.QueuedMessage, bool) +} + // Handlers provides MCP WebSocket handlers. type Handlers struct { taskSvc *service.Service @@ -71,6 +82,7 @@ type Handlers struct { eventBus EventBus planService *service.PlanService sessionLauncher SessionLauncher + messageQueue MessageQueuer logger *logger.Logger // Config-mode dependencies (optional, set via SetConfigDeps) @@ -90,6 +102,7 @@ func NewHandlers( eventBus EventBus, planService *service.PlanService, sessionLauncher SessionLauncher, + messageQueue MessageQueuer, log *logger.Logger, ) *Handlers { return &Handlers{ @@ -102,6 +115,7 @@ func NewHandlers( eventBus: eventBus, planService: planService, sessionLauncher: sessionLauncher, + messageQueue: messageQueue, logger: log.WithFields(zap.String("component", "mcp-handlers")), } } diff --git a/apps/backend/internal/mcp/server/config_handlers.go b/apps/backend/internal/mcp/server/config_handlers.go index 6b7781e8e6..e6bc4a26c7 100644 --- a/apps/backend/internal/mcp/server/config_handlers.go +++ b/apps/backend/internal/mcp/server/config_handlers.go @@ -247,11 +247,12 @@ func (s *Server) registerConfigTaskTools() { ) s.mcpServer.AddTool( mcp.NewTool("move_task_kandev", - mcp.WithDescription("Move a task to a different workflow step."), + mcp.WithDescription("Move a task to a different workflow step. Optionally send a hand-off prompt to the receiving agent — required only when handing the task off mid-turn (e.g. QA → review) with specific instructions. Plain admin/config moves can omit prompt."), mcp.WithString("task_id", mcp.Required(), mcp.Description("The task ID")), mcp.WithString("workflow_id", mcp.Required(), mcp.Description("Target workflow ID")), mcp.WithString("workflow_step_id", mcp.Required(), mcp.Description("Target workflow step ID")), mcp.WithNumber("position", mcp.Description("Position within the step (0-based)")), + mcp.WithString("prompt", mcp.Description("Optional hand-off message for the receiving agent. When supplied AND the source session is mid-turn, the move is deferred to the agent's turn-end and the prompt is delivered at the new step (concatenated after the step's own auto_start prompt, if any). Omit for plain admin/config moves where there's no agent to address.")), ), s.wrapHandler("move_task_kandev", s.moveTaskHandler()), ) @@ -519,11 +520,16 @@ func (s *Server) moveTaskHandler() server.ToolHandlerFunc { if err != nil { return mcp.NewToolResultError("workflow_step_id is required"), nil } + // prompt is optional — only relevant when handing off mid-turn from one + // agent to another. Admin/config moves of idle tasks omit it. payload := map[string]interface{}{ "task_id": taskID, "workflow_id": workflowID, "workflow_step_id": stepID, } + if prompt := req.GetString("prompt", ""); prompt != "" { + payload["prompt"] = prompt + } if args := req.GetArguments(); args["position"] != nil { payload["position"] = args["position"] } diff --git a/apps/backend/internal/mcp/server/server.go b/apps/backend/internal/mcp/server/server.go index fe259c551a..f30b3bb29c 100644 --- a/apps/backend/internal/mcp/server/server.go +++ b/apps/backend/internal/mcp/server/server.go @@ -307,7 +307,7 @@ func (s *Server) registerTools() { count++ default: // ModeTask s.registerKanbanTools() - count += 8 + count += 9 if !s.disableAskQuestion { s.registerInteractionTools() count++ @@ -379,6 +379,17 @@ func (s *Server) registerKanbanTools() { ), s.wrapHandler("update_task_kandev", s.updateTaskHandler()), ) + s.mcpServer.AddTool( + mcp.NewTool("move_task_kandev", + mcp.WithDescription("Move a task to a different workflow step. Optionally send a hand-off prompt to the receiving agent — required only when handing the task off mid-turn (e.g. QA → review) with specific instructions. Plain admin/config moves can omit prompt."), + mcp.WithString("task_id", mcp.Required(), mcp.Description("The task ID")), + mcp.WithString("workflow_id", mcp.Required(), mcp.Description("Target workflow ID")), + mcp.WithString("workflow_step_id", mcp.Required(), mcp.Description("Target workflow step ID")), + mcp.WithNumber("position", mcp.Description("Position within the step (0-based)")), + mcp.WithString("prompt", mcp.Description("Optional hand-off message for the receiving agent. When supplied AND the source session is mid-turn, the move is deferred to the agent's turn-end and the prompt is delivered at the new step (concatenated after the step's own auto_start prompt, if any). Omit for plain admin/config moves where there's no agent to address.")), + ), + s.wrapHandler("move_task_kandev", s.moveTaskHandler()), + ) } // registerCreateTaskTool registers the create_task_kandev tool. Shared between diff --git a/apps/backend/internal/mcp/server/server_test.go b/apps/backend/internal/mcp/server/server_test.go index f041b013c3..65c5984d73 100644 --- a/apps/backend/internal/mcp/server/server_test.go +++ b/apps/backend/internal/mcp/server/server_test.go @@ -42,6 +42,7 @@ func TestServerModeTask_RegistersCorrectTools(t *testing.T) { assert.Contains(t, tools, "list_tasks_kandev") assert.Contains(t, tools, "create_task_kandev") assert.Contains(t, tools, "update_task_kandev") + assert.Contains(t, tools, "move_task_kandev") // Task mode should have plan tools assert.Contains(t, tools, "create_task_plan_kandev") @@ -69,7 +70,6 @@ func TestServerModeTask_RegistersCorrectTools(t *testing.T) { assert.NotContains(t, tools, "update_agent_profile_kandev") assert.NotContains(t, tools, "get_mcp_config_kandev") assert.NotContains(t, tools, "update_mcp_config_kandev") - assert.NotContains(t, tools, "move_task_kandev") assert.NotContains(t, tools, "delete_task_kandev") assert.NotContains(t, tools, "archive_task_kandev") assert.NotContains(t, tools, "list_executors_kandev") @@ -193,8 +193,8 @@ func TestServerModeTask_ToolCount(t *testing.T) { s := New(backend, "test-session", "test-task", 10005, log, "", false, ModeTask) tools := getRegisteredToolNames(s) - // 8 kanban + 1 interaction + 4 plan = 13 - assert.Equal(t, 13, len(tools)) + // 9 kanban + 1 interaction + 4 plan = 14 + assert.Equal(t, 14, len(tools)) } func TestServerModeConfig_ToolCount(t *testing.T) { diff --git a/apps/backend/internal/orchestrator/event_handlers_agent.go b/apps/backend/internal/orchestrator/event_handlers_agent.go index c025410555..be88b9afdb 100644 --- a/apps/backend/internal/orchestrator/event_handlers_agent.go +++ b/apps/backend/internal/orchestrator/event_handlers_agent.go @@ -99,8 +99,79 @@ func (s *Service) requeueMessage(ctx context.Context, queuedMsg *messagequeue.Qu s.publishQueueStatusEvent(ctx, queuedMsg.SessionID) } -// handleAgentReady handles agent ready events (turn complete in passthrough mode) -// This is called when the agent finishes processing and is waiting for input. +// handleAgentBootReady handles the boot signal: an agent's ACP session has +// finished initializing but no turn has run yet. This event is distinct from +// agent.ready (turn-end) so the orchestrator never has to disambiguate the +// two with race-prone flags. +// +// The only job here is to flip the session to WAITING_FOR_INPUT so callers +// that are gating on that state (e.g. PromptTask's waitForSessionReady after +// ensureSessionRunning kicked off ResumeSession) can proceed. Crucially we do +// NOT call processOnTurnCompleteViaEngine — there's no turn to complete, and +// stepping the workflow off a boot signal is what caused the production +// ping-pong bug. +func (s *Service) handleAgentBootReady(ctx context.Context, data watcher.AgentEventData) { + if data.SessionID == "" { + s.logger.Warn("missing session_id for agent boot ready event", + zap.String("task_id", data.TaskID)) + return + } + + if s.isSessionResetInProgress(data.SessionID) { + s.logger.Debug("ignoring agent.boot_ready while session reset is in progress", + zap.String("task_id", data.TaskID), + zap.String("session_id", data.SessionID)) + return + } + + session, err := s.repo.GetTaskSession(ctx, data.SessionID) + if err != nil { + s.logger.Warn("failed to load session for agent.boot_ready", + zap.String("task_id", data.TaskID), + zap.String("session_id", data.SessionID), + zap.Error(err)) + return + } + + // Stale event: the session has rotated to a different execution. The agent + // process tied to data.AgentExecutionID is no longer the active one for this + // session, so its boot signal is irrelevant. + if data.AgentExecutionID != "" && session.AgentExecutionID != "" && session.AgentExecutionID != data.AgentExecutionID { + s.logger.Debug("ignoring stale agent.boot_ready for non-active execution", + zap.String("task_id", data.TaskID), + zap.String("session_id", data.SessionID), + zap.String("event_execution_id", data.AgentExecutionID), + zap.String("active_execution_id", session.AgentExecutionID)) + return + } + + // Terminal sessions never need a boot signal — if a stale init event + // arrives after the session was completed/cancelled, just drop it. + if isTerminalSessionState(session.State) { + s.logger.Debug("ignoring agent.boot_ready for terminal session", + zap.String("task_id", data.TaskID), + zap.String("session_id", data.SessionID), + zap.String("session_state", string(session.State))) + return + } + + // Idempotent: if the session is already WAITING_FOR_INPUT (e.g. revived + // from a previously launched session and the boot signal arrived faster + // than persistResumeState wrote STARTING), skip — there's nothing to flip + // and waitForSessionReady's poll will pick it up. + if session.State == models.TaskSessionStateWaitingForInput { + s.logger.Debug("agent.boot_ready: session already WAITING_FOR_INPUT, no-op", + zap.String("session_id", data.SessionID)) + return + } + + s.setSessionWaitingForInput(ctx, data.TaskID, data.SessionID, session) +} + +// handleAgentReady handles turn-end ready events: the agent finished processing +// a prompt and is waiting for the next input. This is the *only* event that +// should evaluate workflow on_turn_complete actions — boot signals route +// through handleAgentBootReady instead. func (s *Service) handleAgentReady(ctx context.Context, data watcher.AgentEventData) { if data.SessionID == "" { @@ -146,6 +217,15 @@ func (s *Service) handleAgentReady(ctx context.Context, data watcher.AgentEventD // Complete the current turn s.completeTurnForSession(ctx, data.SessionID) + // A move_task_kandev call during this turn deferred the actual move to + // avoid racing on_enter against the running turn. Apply it now: the move + // is the explicit transition the agent requested, so skip the regular + // on_turn_complete evaluation against the (still old) step. + if pendingMove, exists := s.messageQueue.TakePendingMove(ctx, data.SessionID); exists { + s.applyPendingMove(ctx, data.TaskID, data.SessionID, session, pendingMove) + return + } + // Check for workflow transition based on session's current step. // Uses the engine when available; falls back to legacy evaluation. // The ViaEngine method handles setSessionWaitingForInput internally when no transition occurs. @@ -318,6 +398,36 @@ func (s *Service) handleAgentCompleted(ctx context.Context, data watcher.AgentEv zap.Error(err)) return } + + // Skip transition logic when this event is the side-effect of a deliberate + // stop (e.g. a workflow profile-switch calling completeAndStopSession). Two + // signals identify that case: + // - Stale execution ID: the session has already adopted a new agent + // execution (or cleared the old one), so this event refers to a stopped + // run, not the current one. + // - Terminal session state: completeAndStopSession set state to COMPLETED + // before StopAgent fired this event. + // Without this guard, processOnTurnCompleteViaEngine evaluates the *current* + // task step (which has already moved past where this agent ran) and triggers + // spurious transitions — manifesting as task-step ping-pong on profile switches. + if data.AgentExecutionID != "" && session.AgentExecutionID != "" && session.AgentExecutionID != data.AgentExecutionID { + s.logger.Debug("ignoring stale agent.completed for non-active execution", + zap.String("task_id", data.TaskID), + zap.String("session_id", data.SessionID), + zap.String("event_execution_id", data.AgentExecutionID), + zap.String("active_execution_id", session.AgentExecutionID)) + go s.cleanupAgentExecution(data.AgentExecutionID, data.TaskID, data.SessionID) + return + } + if isTerminalSessionState(session.State) { + s.logger.Debug("ignoring agent.completed; session already in terminal state (deliberate stop)", + zap.String("task_id", data.TaskID), + zap.String("session_id", data.SessionID), + zap.String("session_state", string(session.State))) + go s.cleanupAgentExecution(data.AgentExecutionID, data.TaskID, data.SessionID) + return + } + transitioned := s.processOnTurnCompleteViaEngine(ctx, data.TaskID, session) // If no workflow transition occurred, move task to REVIEW state for user review diff --git a/apps/backend/internal/orchestrator/event_handlers_pending_move_test.go b/apps/backend/internal/orchestrator/event_handlers_pending_move_test.go new file mode 100644 index 0000000000..afb9bdbd65 --- /dev/null +++ b/apps/backend/internal/orchestrator/event_handlers_pending_move_test.go @@ -0,0 +1,588 @@ +package orchestrator + +import ( + "context" + "strings" + "testing" + "time" + + "github.com/kandev/kandev/internal/orchestrator/executor" + "github.com/kandev/kandev/internal/orchestrator/messagequeue" + "github.com/kandev/kandev/internal/orchestrator/queue" + "github.com/kandev/kandev/internal/orchestrator/scheduler" + "github.com/kandev/kandev/internal/orchestrator/watcher" + "github.com/kandev/kandev/internal/task/models" + sqliterepo "github.com/kandev/kandev/internal/task/repository/sqlite" + wfmodels "github.com/kandev/kandev/internal/workflow/models" + v1 "github.com/kandev/kandev/pkg/api/v1" +) + +// TestPendingMove_ReviewToInProgress_OneTransitionOnly reproduces the production bug +// observed at task a99d863e ("buggy fibo"): a QA agent calls move_task_kandev to send +// the task back to "In Progress" with a hand-off prompt, but the deferred-move flow +// triggers spurious additional transitions and the task ends up at "Reviewed" instead. +// +// Workflow (simplified, matches the user's actual setup): +// +// [In Progress] --on_turn_complete--> [In Review] --on_turn_complete--> [Reviewed] +// on_enter: auto_start_agent on_enter: auto_start_agent +// profile-impl profile-review +// +// Both on_turn_complete rules are unconditional — any agent.ready event triggers +// a transition. That's the workflow author's choice, but the orchestrator must +// not feed it spurious ready events. The deferred-move feature must produce +// exactly one transition: "In Review" → "In Progress". Anything else (e.g. +// "In Progress" → "In Review", or worse, "In Review" → "Reviewed" via a stale +// ready) is the bug. +// +// Scenario the test sets up: +// - Task is currently at "In Review" (the QA step). +// - Two sessions exist: an "In Progress" session (profile-impl, completed earlier +// when the workflow first transitioned to Review) and an "In Review" session +// (profile-review, currently RUNNING, primary). +// - QA called move_task_kandev mid-turn → handleMoveTask set a PendingMove +// pointing at "In Progress" and queued the hand-off prompt. +// - QA's turn ends → agent.ready fires → handleAgentReady is invoked. +// +// Expected outcome: +// - Task workflow_step_id == "In Progress" step ID. +// - The "In Progress" session is the primary (revived from COMPLETED). +// - The "In Review" session is COMPLETED. +// - No subsequent transition fires. +// +// The test deliberately stubs PromptAgent / LaunchAgent so we don't need a real +// agent process. The bug we're chasing is in the orchestrator's transition +// logic, not in the executor — so an executor that returns success deterministically +// is sufficient to expose multiple transitions if they occur. +func TestPendingMove_ReviewToInProgress_OneTransitionOnly(t *testing.T) { + sc := buildPendingMoveScenario(t) + + // Snapshot the workflow_step_id history by sampling at intervals. We expect + // exactly one change: stepInReviewID → stepInProgressID. Anything else + // (e.g. stepInProgressID → stepInReviewID right after, or skipping ahead + // to stepReviewedID) means the bug has fired. + historyDone, stepHistory := sc.startStepHistorySampler(t, 2*time.Second) + + // Fire the QA session's agent.ready — this is what handleAgentReady receives + // when MarkReady is called from handleCompleteEventMarkState after the QA + // agent's turn ends. + sc.svc.handleAgentReady(sc.ctx, watcher.AgentEventData{ + TaskID: "task-1", + SessionID: sc.reviewSessionID, + AgentExecutionID: "ae-review", + AgentProfileID: profileReview, + }) + + // Give the async processStepExitAndEnter goroutine time to complete. + // Then drain the history collector. + time.Sleep(1 * time.Second) + <-historyDone + + sc.assertOneTransitionToInProgress(t, *stepHistory) +} + +// --- Pending-move scenario builder & assertions --- + +const ( + stepInProgressID = "step-in-progress" + stepInReviewID = "step-in-review" + stepReviewedID = "step-reviewed" + + profileImpl = "profile-impl" + profileReview = "profile-review" +) + +// pendingMoveScenario is the seeded fixture used by deferred-move tests. +// It owns the repo + service + mock agent manager so a single value carries +// every reference an assertion needs without long parameter lists. +type pendingMoveScenario struct { + ctx context.Context + svc *Service + repo *sqliterepo.Repository + agentMgr *mockAgentManager + stepGetter *mockStepGetter + implSessionID string + reviewSessionID string + implRelaunchExec string +} + +// buildPendingMoveScenario sets up the full repro scenario: +// - 3 workflow steps: In Progress (auto_start, on_turn_complete → Review), +// In Review (auto_start, on_turn_complete → Reviewed), Reviewed (terminal). +// - Task currently at "In Review", with two sessions: an Impl session that +// was completed earlier (revivable — has executors_running), and a Review +// session that's currently RUNNING and primary. +// - PendingMove + hand-off prompt seeded as if the QA agent just called +// move_task_kandev mid-turn. +// - Mock LaunchAgent that fires the boot signal asynchronously so the +// resume path can complete in tests without a real agent process. +func buildPendingMoveScenario(t *testing.T) *pendingMoveScenario { + t.Helper() + ctx := context.Background() + now := time.Now().UTC() + + repo := setupTestRepo(t) + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws1", Name: "Test", CreatedAt: now, UpdatedAt: now}); err != nil { + t.Fatalf("create workspace: %v", err) + } + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf1", WorkspaceID: "ws1", Name: "Test WF", CreatedAt: now, UpdatedAt: now}); err != nil { + t.Fatalf("create workflow: %v", err) + } + + stepGetter := newPendingMoveStepGetter() + + if err := repo.CreateTask(ctx, &models.Task{ + ID: "task-1", WorkflowID: "wf1", WorkflowStepID: stepInReviewID, + Title: "Test", Description: "Implement a python buggy fibonnacci", + State: v1.TaskStateInProgress, CreatedAt: now, UpdatedAt: now, + }); err != nil { + t.Fatalf("create task: %v", err) + } + + implSessionID := seedImplSession(t, repo, now) + reviewSessionID := seedReviewSession(t, repo, now) + + taskRepo := newMockTaskRepo() + taskRepo.tasks["task-1"] = &v1.Task{ + ID: "task-1", WorkspaceID: "ws1", WorkflowID: "wf1", + Title: "Test", Description: "Implement a python buggy fibonnacci", + State: v1.TaskStateInProgress, + } + + agentMgr := &mockAgentManager{} + log := testLogger() + exec := executor.NewExecutor(agentMgr, repo, log, executor.ExecutorConfig{}) + sched := scheduler.NewScheduler(queue.NewTaskQueue(100), exec, taskRepo, log, scheduler.SchedulerConfig{}) + + svc := &Service{ + logger: log, + repo: repo, + workflowStepGetter: stepGetter, + taskRepo: taskRepo, + agentManager: agentMgr, + messageQueue: messagequeue.NewService(log), + executor: exec, + scheduler: sched, + } + svc.SetWorkflowStepGetter(stepGetter) + + const implRelaunchExec = "ae-impl-relaunch" + wireBootReadySimulator(svc, agentMgr, implRelaunchExec) + + const handoffPrompt = "You were moved to this step with the following message: " + + "The file fibonacci.py has two bugs — fix them." + if _, err := svc.messageQueue.QueueMessage( + ctx, reviewSessionID, "task-1", handoffPrompt, "", "mcp-move-task", false, nil, + ); err != nil { + t.Fatalf("queue hand-off prompt: %v", err) + } + svc.messageQueue.SetPendingMove(ctx, reviewSessionID, &messagequeue.PendingMove{ + TaskID: "task-1", + WorkflowID: "wf1", + WorkflowStepID: stepInProgressID, + }) + + return &pendingMoveScenario{ + ctx: ctx, + svc: svc, + repo: repo, + agentMgr: agentMgr, + stepGetter: stepGetter, + implSessionID: implSessionID, + reviewSessionID: reviewSessionID, + implRelaunchExec: implRelaunchExec, + } +} + +// newPendingMoveStepGetter builds the 3-step workflow used by the scenario. +// Both auto_start steps have UNCONDITIONAL on_turn_complete rules — that's +// the workflow shape that exposed the original ping-pong bug, so we keep it. +func newPendingMoveStepGetter() *mockStepGetter { + sg := newMockStepGetter() + sg.steps[stepInProgressID] = &wfmodels.WorkflowStep{ + ID: stepInProgressID, WorkflowID: "wf1", Name: "In Progress", Position: 1, + AgentProfileID: profileImpl, + Events: wfmodels.StepEvents{ + OnEnter: []wfmodels.OnEnterAction{{Type: wfmodels.OnEnterAutoStartAgent}}, + OnTurnComplete: []wfmodels.OnTurnCompleteAction{ + {Type: wfmodels.OnTurnCompleteMoveToStep, Config: map[string]interface{}{"step_id": stepInReviewID}}, + }, + }, + } + sg.steps[stepInReviewID] = &wfmodels.WorkflowStep{ + ID: stepInReviewID, WorkflowID: "wf1", Name: "In Review", Position: 2, + AgentProfileID: profileReview, + Events: wfmodels.StepEvents{ + OnEnter: []wfmodels.OnEnterAction{{Type: wfmodels.OnEnterAutoStartAgent}}, + OnTurnComplete: []wfmodels.OnTurnCompleteAction{ + {Type: wfmodels.OnTurnCompleteMoveToStep, Config: map[string]interface{}{"step_id": stepReviewedID}}, + }, + }, + } + sg.steps[stepReviewedID] = &wfmodels.WorkflowStep{ + ID: stepReviewedID, WorkflowID: "wf1", Name: "Reviewed", Position: 3, + } + return sg +} + +// seedImplSession seeds the previously-completed Impl session with an +// executors_running record so reuseSessionForStep revives it as +// WAITING_FOR_INPUT (matching the real-world "previously launched" path). +func seedImplSession(t *testing.T, repo *sqliterepo.Repository, now time.Time) string { + t.Helper() + const id = "session-impl" + completedAt := now.Add(-1 * time.Minute) + sess := &models.TaskSession{ + ID: id, + TaskID: "task-1", + AgentProfileID: profileImpl, + ExecutorID: "exec-local", + ExecutorProfileID: "ep1", + AgentExecutionID: "ae-impl-original", + State: models.TaskSessionStateCompleted, + CompletedAt: &completedAt, + StartedAt: now.Add(-2 * time.Minute), + UpdatedAt: completedAt, + } + if err := repo.CreateTaskSession(context.Background(), sess); err != nil { + t.Fatalf("create impl session: %v", err) + } + if err := repo.UpsertExecutorRunning(context.Background(), &models.ExecutorRunning{ + ID: id, SessionID: id, TaskID: "task-1", + ResumeToken: "resume-token-impl", AgentExecutionID: "ae-impl-original", + CreatedAt: now.Add(-2 * time.Minute), UpdatedAt: completedAt, + }); err != nil { + t.Fatalf("upsert executors_running for impl: %v", err) + } + return id +} + +// seedReviewSession seeds the currently-active Review session as primary, +// RUNNING — the QA agent that's about to fire its move_task_kandev call. +func seedReviewSession(t *testing.T, repo *sqliterepo.Repository, now time.Time) string { + t.Helper() + const id = "session-review" + sess := &models.TaskSession{ + ID: id, + TaskID: "task-1", + AgentProfileID: profileReview, + ExecutorID: "exec-local", + ExecutorProfileID: "ep1", + AgentExecutionID: "ae-review", + State: models.TaskSessionStateRunning, + IsPrimary: true, + StartedAt: now, + UpdatedAt: now, + } + if err := repo.CreateTaskSession(context.Background(), sess); err != nil { + t.Fatalf("create review session: %v", err) + } + return id +} + +// wireBootReadySimulator stubs LaunchAgent to fire handleAgentBootReady ~50ms +// after returning. Real agentctl bootstrap publishes events.AgentBootReady from +// outside the LaunchAgent call; mirroring that timing here lets the resume +// path complete in unit tests without spawning a real subprocess. +func wireBootReadySimulator(svc *Service, agentMgr *mockAgentManager, newExecID string) { + agentMgr.launchAgentFunc = func(_ context.Context, req *executor.LaunchAgentRequest) (*executor.LaunchAgentResponse, error) { + go func() { + time.Sleep(50 * time.Millisecond) + svc.handleAgentBootReady(context.Background(), watcher.AgentEventData{ + TaskID: req.TaskID, + SessionID: req.SessionID, + AgentExecutionID: newExecID, + AgentProfileID: req.AgentProfileID, + }) + }() + return &executor.LaunchAgentResponse{ + AgentExecutionID: newExecID, + ContainerID: "container-relaunch", + Status: v1.AgentStatusReady, + }, nil + } +} + +// startStepHistorySampler polls task.WorkflowStepID and appends every change +// to a slice. Returned channel closes when sampling ends; the *[]string is +// safe to read from the caller after that. +func (sc *pendingMoveScenario) startStepHistorySampler(t *testing.T, duration time.Duration) (<-chan struct{}, *[]string) { + t.Helper() + done := make(chan struct{}) + history := []string{stepInReviewID} + go func() { + defer close(done) + seen := stepInReviewID + deadline := time.Now().Add(duration) + for time.Now().Before(deadline) { + task, err := sc.repo.GetTask(sc.ctx, "task-1") + if err == nil && task.WorkflowStepID != seen { + seen = task.WorkflowStepID + history = append(history, seen) + } + time.Sleep(10 * time.Millisecond) + } + }() + return done, &history +} + +// assertOneTransitionToInProgress checks every postcondition of the scenario: +// task moved to In Progress, exactly one transition, sessions in the right +// state, and the hand-off prompt landed on the impl session (delivered or +// queued — either is acceptable for this regression). +func (sc *pendingMoveScenario) assertOneTransitionToInProgress(t *testing.T, stepHistory []string) { + t.Helper() + + finalTask, err := sc.repo.GetTask(sc.ctx, "task-1") + if err != nil { + t.Fatalf("load final task: %v", err) + } + + dedup := dedupConsecutive(stepHistory) + t.Logf("workflow_step_id transition history: %v", stepNamesFromIDs(dedup, sc.stepGetter)) + + if finalTask.WorkflowStepID != stepInProgressID { + t.Errorf("final workflow_step_id = %q, want %q (In Progress)", finalTask.WorkflowStepID, stepInProgressID) + } + + expected := []string{stepInReviewID, stepInProgressID} + if !sliceEqual(dedup, expected) { + t.Errorf("transition history = %v, want %v\n (this means the deferred-move triggered spurious additional transitions — the bug)", + stepNamesFromIDs(dedup, sc.stepGetter), stepNamesFromIDs(expected, sc.stepGetter)) + } + + rev, err := sc.repo.GetTaskSession(sc.ctx, sc.reviewSessionID) + if err != nil { + t.Fatalf("load review session: %v", err) + } + if rev.State != models.TaskSessionStateCompleted { + t.Errorf("review session state = %q, want COMPLETED (parked by the profile switch)", rev.State) + } + if rev.IsPrimary { + t.Error("review session must no longer be primary (the impl session takes over)") + } + + impl, err := sc.repo.GetTaskSession(sc.ctx, sc.implSessionID) + if err != nil { + t.Fatalf("load impl session: %v", err) + } + if !impl.IsPrimary { + t.Error("impl session must be primary after the deferred move applies") + } + if impl.State == models.TaskSessionStateCompleted { + t.Errorf("impl session state = %q, expected non-terminal (revived for a new turn)", impl.State) + } + + sc.assertHandoffDeliveredOrQueued(t) +} + +// assertHandoffDeliveredOrQueued checks the hand-off prompt landed on the impl +// session — either delivered to its agent (PromptAgent capture) or sitting in +// the queue waiting for delivery. Both are acceptable; the failure mode the +// regression catches is "lost" (neither delivered nor queued) or "delivered +// to the wrong session". +func (sc *pendingMoveScenario) assertHandoffDeliveredOrQueued(t *testing.T) { + t.Helper() + implPrompts := capturedPromptsForExecution(sc.agentMgr, sc.implRelaunchExec) + implQueued := sc.svc.messageQueue.GetStatus(sc.ctx, sc.implSessionID) + + if len(implPrompts) == 0 && !implQueued.IsQueued { + t.Error("hand-off prompt was neither delivered to the impl session nor queued for it") + return + } + for _, p := range implPrompts { + if strings.Contains(p, "fibonacci.py has two bugs") { + return + } + } + if implQueued.IsQueued && implQueued.Message != nil && + strings.Contains(implQueued.Message.Content, "fibonacci.py has two bugs") { + return + } + t.Errorf("hand-off prompt was neither delivered nor queued with the expected content") +} + +// --- Helpers --- + +// capturedPromptsForExecution returns only the prompts that were sent to the +// given agent execution ID. The earlier version ignored its selector and +// returned every recorded prompt — which would let the test pass even if the +// hand-off had been delivered to the wrong session. +func capturedPromptsForExecution(agentMgr *mockAgentManager, executionID string) []string { + agentMgr.mu.Lock() + defer agentMgr.mu.Unlock() + out := make([]string, 0, len(agentMgr.capturedPromptCalls)) + for _, c := range agentMgr.capturedPromptCalls { + if c.ExecutionID == executionID { + out = append(out, c.Prompt) + } + } + return out +} + +func dedupConsecutive(in []string) []string { + if len(in) == 0 { + return in + } + out := []string{in[0]} + for i := 1; i < len(in); i++ { + if in[i] != in[i-1] { + out = append(out, in[i]) + } + } + return out +} + +func sliceEqual(a, b []string) bool { + if len(a) != len(b) { + return false + } + for i := range a { + if a[i] != b[i] { + return false + } + } + return true +} + +func stepNamesFromIDs(ids []string, sg *mockStepGetter) []string { + out := make([]string, 0, len(ids)) + for _, id := range ids { + if step, ok := sg.steps[id]; ok { + out = append(out, step.Name) + } else { + out = append(out, id) + } + } + return out +} + +// TestHandleAgentBootReady_DoesNotTriggerOnTurnComplete locks in the post-fix +// invariant: a boot-ready signal (agent's ACP session has just initialized, +// no turn has run yet) must NEVER step the workflow. The lifecycle layer now +// publishes events.AgentBootReady — distinct from events.AgentReady — and the +// orchestrator routes it to handleAgentBootReady which only flips the session +// to WAITING_FOR_INPUT. +// +// Before this split, both signals shared events.AgentReady and the +// orchestrator tried to disambiguate them with the resumeInProgressSessions +// flag. That flag had a race: when the boot ready arrived BEFORE +// persistResumeState wrote state=STARTING, handleAgentReady's state guard +// returned without consuming the flag, leaking it to the next event and +// firing on_turn_complete against the wrong session. +// +// This test fires the boot signal directly into handleAgentBootReady to +// confirm: (a) no on_turn_complete evaluation runs, (b) the session ends up +// WAITING_FOR_INPUT regardless of what state it was in. +func TestHandleAgentBootReady_DoesNotTriggerOnTurnComplete(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC() + + repo := setupTestRepo(t) + if err := repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws1", Name: "Test", CreatedAt: now, UpdatedAt: now}); err != nil { + t.Fatalf("create workspace: %v", err) + } + if err := repo.CreateWorkflow(ctx, &models.Workflow{ID: "wf1", WorkspaceID: "ws1", Name: "WF", CreatedAt: now, UpdatedAt: now}); err != nil { + t.Fatalf("create workflow: %v", err) + } + + // One step with an unconditional on_turn_complete. If a boot-ready + // somehow reaches the turn-end path, this rule fires and the task moves — + // the user-visible symptom of the original bug. + stepGetter := newMockStepGetter() + stepGetter.steps["step-current"] = &wfmodels.WorkflowStep{ + ID: "step-current", WorkflowID: "wf1", Name: "Current", Position: 1, + Events: wfmodels.StepEvents{ + OnTurnComplete: []wfmodels.OnTurnCompleteAction{ + {Type: wfmodels.OnTurnCompleteMoveToStep, Config: map[string]interface{}{"step_id": "step-next"}}, + }, + }, + } + stepGetter.steps["step-next"] = &wfmodels.WorkflowStep{ + ID: "step-next", WorkflowID: "wf1", Name: "Next", Position: 2, + } + + if err := repo.CreateTask(ctx, &models.Task{ + ID: "task-1", WorkflowID: "wf1", WorkflowStepID: "step-current", + Title: "T", Description: "D", State: v1.TaskStateInProgress, + CreatedAt: now, UpdatedAt: now, + }); err != nil { + t.Fatalf("create task: %v", err) + } + + // Two scenarios the boot signal must handle correctly: + // - state=STARTING (the textbook case: persistResumeState wrote it) + // - state=WAITING_FOR_INPUT (the racy case: boot signal beat + // persistResumeState, or reviveReusedSession left it WAITING) + cases := []struct { + name string + startSt models.TaskSessionState + expectSt models.TaskSessionState + }{ + {"STARTING", models.TaskSessionStateStarting, models.TaskSessionStateWaitingForInput}, + {"WAITING_FOR_INPUT (race-with-persistResumeState)", models.TaskSessionStateWaitingForInput, models.TaskSessionStateWaitingForInput}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + sessionID := "s1-" + tc.name + if err := repo.CreateTaskSession(ctx, &models.TaskSession{ + ID: sessionID, TaskID: "task-1", AgentProfileID: "profile-impl", + AgentExecutionID: "ae-current", + State: tc.startSt, + IsPrimary: true, + StartedAt: now, UpdatedAt: now, + }); err != nil { + t.Fatalf("create session: %v", err) + } + + taskRepo := newMockTaskRepo() + taskRepo.tasks["task-1"] = &v1.Task{ + ID: "task-1", WorkflowID: "wf1", State: v1.TaskStateInProgress, + } + + agentMgr := &mockAgentManager{} + log := testLogger() + exec := executor.NewExecutor(agentMgr, repo, log, executor.ExecutorConfig{}) + svc := &Service{ + logger: log, + repo: repo, + workflowStepGetter: stepGetter, + taskRepo: taskRepo, + agentManager: agentMgr, + messageQueue: messagequeue.NewService(log), + executor: exec, + } + svc.SetWorkflowStepGetter(stepGetter) + + // Reset task to step-current in case a prior subtest moved it. + tk, _ := repo.GetTask(ctx, "task-1") + tk.WorkflowStepID = "step-current" + _ = repo.UpdateTask(ctx, tk) + + // Fire the new boot-only event. The handler must NOT run on_turn_complete. + svc.handleAgentBootReady(ctx, watcher.AgentEventData{ + TaskID: "task-1", SessionID: sessionID, + AgentExecutionID: "ae-current", + AgentProfileID: "profile-impl", + }) + + finalTask, err := repo.GetTask(ctx, "task-1") + if err != nil { + t.Fatalf("load task: %v", err) + } + if finalTask.WorkflowStepID != "step-current" { + t.Errorf("workflow_step_id = %q, want %q (boot signal must not move the workflow)", + finalTask.WorkflowStepID, "step-current") + } + + finalSess, err := repo.GetTaskSession(ctx, sessionID) + if err != nil { + t.Fatalf("load session: %v", err) + } + if finalSess.State != tc.expectSt { + t.Errorf("session.State = %q, want %q", finalSess.State, tc.expectSt) + } + }) + } +} diff --git a/apps/backend/internal/orchestrator/event_handlers_test.go b/apps/backend/internal/orchestrator/event_handlers_test.go index 77c8a5c37a..62c2c5c39d 100644 --- a/apps/backend/internal/orchestrator/event_handlers_test.go +++ b/apps/backend/internal/orchestrator/event_handlers_test.go @@ -126,8 +126,11 @@ type mockAgentManager struct { mu sync.Mutex stopAgentWithReasonArgs []stopAgentCall // tracks StopAgentWithReason calls - // Prompt tracking - capturedPrompts []string // tracks prompts passed to PromptAgent + // Prompt tracking — capturedPrompts records prompts only (legacy, several + // tests assert on it directly). capturedPromptCalls records the same with + // the execution ID so callers can filter by the agent that received it. + capturedPrompts []string + capturedPromptCalls []promptCall // Optional: closed once on the first PromptAgent call so tests can wait // deterministically without polling. Tests opt in by initializing the channel. promptDone chan struct{} @@ -148,6 +151,12 @@ type stopAgentCall struct { Force bool } +// promptCall records one PromptAgent invocation with its target execution ID. +type promptCall struct { + ExecutionID string + Prompt string +} + type passthroughStdinCall struct { SessionID string Data string @@ -171,10 +180,11 @@ func (m *mockAgentManager) StopAgentWithReason(_ context.Context, agentExecution }) return nil } -func (m *mockAgentManager) PromptAgent(_ context.Context, _ string, prompt string, _ []v1.MessageAttachment) (*executor.PromptResult, error) { +func (m *mockAgentManager) PromptAgent(_ context.Context, executionID string, prompt string, _ []v1.MessageAttachment) (*executor.PromptResult, error) { m.mu.Lock() first := len(m.capturedPrompts) == 0 m.capturedPrompts = append(m.capturedPrompts, prompt) + m.capturedPromptCalls = append(m.capturedPromptCalls, promptCall{ExecutionID: executionID, Prompt: prompt}) promptErr := m.promptErr promptResult := m.promptResult doneCh := m.promptDone diff --git a/apps/backend/internal/orchestrator/event_handlers_workflow.go b/apps/backend/internal/orchestrator/event_handlers_workflow.go index 9057554da6..9c74743694 100644 --- a/apps/backend/internal/orchestrator/event_handlers_workflow.go +++ b/apps/backend/internal/orchestrator/event_handlers_workflow.go @@ -2,6 +2,7 @@ package orchestrator import ( "context" + "errors" "fmt" "time" @@ -9,6 +10,7 @@ import ( "github.com/kandev/kandev/internal/events" "github.com/kandev/kandev/internal/events/bus" + "github.com/kandev/kandev/internal/orchestrator/executor" "github.com/kandev/kandev/internal/orchestrator/messagequeue" "github.com/kandev/kandev/internal/orchestrator/watcher" "github.com/kandev/kandev/internal/task/models" @@ -458,10 +460,11 @@ func (s *Service) resolveStepAgentProfile(ctx context.Context, step *wfmodels.Wo return "" } -// switchSessionForStep stops the current session and creates a new one with a different agent profile. -// Returns the new session, or nil + error if the switch fails. -// The new session is prepared BEFORE completing the old one: if PrepareSession fails, the old -// session remains active and the task stays recoverable. +// switchSessionForStep activates a session for the new agent profile. +// If an existing session on this task already uses the target profile it is +// reused (re-promoted to primary, brought out of COMPLETED if it had been +// switched away from previously). Otherwise a new session is prepared. +// In both cases the previous session is stopped and marked COMPLETED. func (s *Service) switchSessionForStep(ctx context.Context, taskID string, currentSession *models.TaskSession, newAgentProfileID string) (*models.TaskSession, error) { s.logger.Info("switching session for workflow step agent profile change", zap.String("task_id", taskID), @@ -475,6 +478,129 @@ func (s *Service) switchSessionForStep(ctx context.Context, taskID string, curre zap.String("task_id", taskID), zap.Error(err)) } + existing, lookupErr := s.findReusableSessionForProfile(ctx, taskID, newAgentProfileID, currentSession.ID) + if lookupErr != nil { + s.logger.Warn("failed to look up reusable session, falling through to create new", + zap.String("task_id", taskID), + zap.String("agent_profile_id", newAgentProfileID), + zap.Error(lookupErr)) + } + if existing != nil { + return s.reuseSessionForStep(ctx, taskID, currentSession, existing) + } + + return s.createNewSessionForStep(ctx, taskID, currentSession, newAgentProfileID) +} + +// findReusableSessionForProfile returns the most-recently-updated session on +// this task that uses the target profile (and is not the session being +// switched away from), or nil if none exists. Failed/cancelled sessions are +// excluded — those are dead and shouldn't be revived implicitly. +func (s *Service) findReusableSessionForProfile(ctx context.Context, taskID, profileID, excludeSessionID string) (*models.TaskSession, error) { + if profileID == "" { + return nil, nil + } + sessions, err := s.repo.ListTaskSessions(ctx, taskID) + if err != nil { + return nil, err + } + var best *models.TaskSession + for _, sess := range sessions { + if sess.ID == excludeSessionID { + continue + } + if sess.AgentProfileID != profileID { + continue + } + // Skip user-cancelled sessions — those are explicit stops and + // shouldn't be auto-revived. FAILED sessions are reused (the failure + // may have been transient; either way the user expects "one session + // per profile per task" so we revive rather than orphan a duplicate). + if sess.State == models.TaskSessionStateCancelled { + continue + } + if best == nil || sess.UpdatedAt.After(best.UpdatedAt) { + best = sess + } + } + return best, nil +} + +// reuseSessionForStep promotes an existing session to primary, brings it out +// of COMPLETED/FAILED if needed, and stops + completes the previous session. +// The agent for the reused session is not relaunched here — when a prompt +// arrives, the autoStart/PromptTask paths handle the launch. +// +// Previously-launched sessions (executors_running record exists, has resume +// token) are flipped to WAITING_FOR_INPUT so PromptTask's ensureSessionRunning +// lazy-resumes them via ResumeSession. +// +// Never-launched sessions (e.g. PrepareSession created the row but the +// workflow switched away before the agent started) have no executors_running +// record. They go to CREATED so autoStartStepPrompt routes through +// StartCreatedSession → LaunchPreparedSession (a full fresh launch). +func (s *Service) reuseSessionForStep(ctx context.Context, taskID string, currentSession, existing *models.TaskSession) (*models.TaskSession, error) { + s.logger.Info("reusing existing session for profile", + zap.String("task_id", taskID), + zap.String("current_session", currentSession.ID), + zap.String("reused_session", existing.ID), + zap.String("reused_profile", existing.AgentProfileID), + zap.String("reused_state", string(existing.State))) + + if existing.State == models.TaskSessionStateCompleted || existing.State == models.TaskSessionStateFailed { + s.reviveReusedSession(ctx, existing) + } + + if err := s.SetPrimarySession(ctx, existing.ID); err != nil { + s.logger.Warn("failed to set reused session as primary", + zap.String("session_id", existing.ID), zap.Error(err)) + } + + // Transfer any queued message and pending move from the session being + // switched away from to the reused session — without this, a hand-off + // prompt queued via move_task_kandev on the previous session is orphaned + // and gets delivered to the wrong agent the next time that previous + // session is reused (e.g. on the on_turn_complete bounce back). + if s.messageQueue != nil { + s.messageQueue.TransferSession(ctx, currentSession.ID, existing.ID) + } + + s.completeAndStopSession(ctx, taskID, currentSession) + return existing, nil +} + +// reviveReusedSession flips a terminal (COMPLETED/FAILED) session back to a +// state where the downstream autoStart/PromptTask paths can launch its agent. +// The target state depends on whether the session was ever launched: +// - Has executors_running record → WAITING_FOR_INPUT, lazy-resume from token +// - No record → CREATED, fresh launch via StartCreatedSession +// +// The previous error message (from a prior FAILED state) is cleared so the +// frontend stops surfacing stale red banners on a now-active session. +func (s *Service) reviveReusedSession(ctx context.Context, session *models.TaskSession) { + wasLaunched := false + if running, err := s.repo.GetExecutorRunningBySessionID(ctx, session.ID); err == nil && running != nil { + wasLaunched = true + } + if wasLaunched { + session.State = models.TaskSessionStateWaitingForInput + } else { + session.State = models.TaskSessionStateCreated + } + session.CompletedAt = nil + session.ErrorMessage = "" + session.UpdatedAt = time.Now().UTC() + if err := s.repo.UpdateTaskSession(ctx, session); err != nil { + s.logger.Warn("failed to revive reused session out of COMPLETED", + zap.String("session_id", session.ID), + zap.String("target_state", string(session.State)), + zap.Error(err)) + } +} + +// createNewSessionForStep is the original switch-and-create-fresh-session path, +// used when there is no existing session for the target profile. +func (s *Service) createNewSessionForStep(ctx context.Context, taskID string, currentSession *models.TaskSession, newAgentProfileID string) (*models.TaskSession, error) { // Prepare the new session BEFORE touching the old one. // If any step below fails, the old session remains active and the task stays recoverable. task, err := s.scheduler.GetTask(ctx, taskID) @@ -514,6 +640,13 @@ func (s *Service) switchSessionForStep(ctx context.Context, taskID string, curre } } + // Transfer any queued message (e.g. a move_task_kandev hand-off prompt) and + // pending move from the old session to the new one — the queue is keyed by + // session ID, and without this the prompt would never reach the new agent. + if s.messageQueue != nil { + s.messageQueue.TransferSession(ctx, currentSession.ID, newSession.ID) + } + // Promote the new session to primary so it's loaded when navigating back to this task. // Use SetPrimarySession (not repo.SetSessionPrimary) to broadcast a task.updated WS // event — the frontend reads primarySessionId from the task to render the star icon. @@ -522,34 +655,44 @@ func (s *Service) switchSessionForStep(ctx context.Context, taskID string, curre zap.String("session_id", newSession.ID), zap.Error(err)) } - // New session is ready — now safe to stop the old agent and complete the old session. - if currentSession.AgentExecutionID != "" { - if err := s.agentManager.StopAgent(ctx, currentSession.AgentExecutionID, false); err != nil { + s.completeAndStopSession(ctx, taskID, currentSession) + return newSession, nil +} + +// completeAndStopSession stops the agent for a session and marks it COMPLETED. +// Used by both the reuse path and the create-new path to terminate the +// previous session in a uniform way. IsPrimary is cleared explicitly so the +// full-row UpdateTaskSession write doesn't overwrite the SetPrimarySession +// call the caller just made on the replacement session. +func (s *Service) completeAndStopSession(ctx context.Context, taskID string, session *models.TaskSession) { + // Flip state to COMPLETED *before* stopping the agent. StopAgent fires an + // agent.completed event, and handleAgentCompleted's terminal-state guard + // only short-circuits when the session is already in a terminal state. If + // we stopped first, the event would fire while state is still RUNNING (or + // WAITING_FOR_INPUT for the deferred-move flow), the guard would miss it, + // and processOnTurnCompleteViaEngine would evaluate the *new* (already + // transitioned) step's on_turn_complete — re-firing the very transition we + // just performed and ping-ponging the task between steps. + s.updateTaskSessionState(ctx, taskID, session.ID, models.TaskSessionStateCompleted, "", false) + + if session.AgentExecutionID != "" { + if err := s.agentManager.StopAgent(ctx, session.AgentExecutionID, false); err != nil { s.logger.Warn("failed to stop agent for session switch", - zap.String("session_id", currentSession.ID), + zap.String("session_id", session.ID), zap.Error(err)) } } - // Mark the current session as completed. - // Use updateTaskSessionState to publish a session.state_changed WS event so the - // frontend learns the old session is terminal and can adopt the new one. - s.updateTaskSessionState(ctx, taskID, currentSession.ID, models.TaskSessionStateCompleted, "", false) - // Also set CompletedAt timestamp for bookkeeping (updateTaskSessionState only sets state). - // Clear IsPrimary to avoid overwriting the SetPrimarySession call above when writing back. now := time.Now().UTC() - currentSession.State = models.TaskSessionStateCompleted - currentSession.IsPrimary = false - currentSession.CompletedAt = &now - currentSession.UpdatedAt = now - if err := s.repo.UpdateTaskSession(ctx, currentSession); err != nil { - // New session is already created; log but don't abort. + session.State = models.TaskSessionStateCompleted + session.IsPrimary = false + session.CompletedAt = &now + session.UpdatedAt = now + if err := s.repo.UpdateTaskSession(ctx, session); err != nil { s.logger.Warn("failed to complete old session after switch", - zap.String("session_id", currentSession.ID), + zap.String("session_id", session.ID), zap.Error(err)) } - - return newSession, nil } // maybySwitchSessionForProfile checks whether the step requires a different agent profile @@ -608,6 +751,14 @@ func (s *Service) processOnEnter(ctx context.Context, taskID string, session *mo hasPlanMode := s.resolveStepPlanMode(ctx, session, step, isPassthrough) if len(step.Events.OnEnter) == 0 && !sessionSwitched { + // Active-turn case (e.g. move_task_kandev mid-turn): the agent is still + // running and will fire agent.ready when the turn ends. Don't flip state + // to WAITING here — handleAgentReady's RUNNING/STARTING guard would then + // silence the event and orphan the queue. handleAgentReady runs + // on_turn_complete against the new step and drains the queue itself. + if session.State == models.TaskSessionStateRunning || session.State == models.TaskSessionStateStarting { + return + } s.setSessionWaitingForInput(ctx, taskID, sessionID, session) s.publishSessionWaitingEvent(ctx, taskID, sessionID, step.ID, session) s.drainQueuedMessageAfterTransition(ctx, sessionID) @@ -702,6 +853,12 @@ func (s *Service) processOnEnter(ctx context.Context, taskID string, session *mo }() return } + // Same active-turn guard as the no-on_enter branch above: if the agent + // is still mid-turn, leave state alone so handleAgentReady can run on + // turn end. See that branch for the full rationale. + if session.State == models.TaskSessionStateRunning || session.State == models.TaskSessionStateStarting { + return + } s.setSessionWaitingForInput(ctx, taskID, sessionID, session) s.publishSessionWaitingEvent(ctx, taskID, sessionID, step.ID, session) // handleAgentReady early-returns when a workflow transition occurs (#677), @@ -713,6 +870,108 @@ func (s *Service) processOnEnter(ctx context.Context, taskID string, session *mo } } +// applyPendingMove applies a deferred move_task_kandev call now that the agent's +// turn has ended. Synchronous: updates the task's step in the DB, runs on_exit +// for the source step and on_enter for the target step. Bypasses +// task.Service.MoveTask (and the task.moved event) so the orchestrator's async +// task.moved handler doesn't run a second processStepExitAndEnter for the same +// transition. The message queue is left intact — any user-supplied prompt +// already queued by handleMoveTask is delivered by the on_enter path or by +// drainQueuedMessageAfterTransition. +func (s *Service) applyPendingMove(ctx context.Context, taskID, sessionID string, session *models.TaskSession, move *messagequeue.PendingMove) { + // reinsertPendingMove restores the move so a future agent.ready can retry. + // Used on early failure paths (load errors, config issues) where the state + // hasn't been touched yet. NOT used after ApplyTransition has executed — + // at that point the workflow has either advanced or is in a corrupted state + // and re-attempting the move on the next turn would just re-trip the same + // failure (or worse, double-apply on a now-half-transitioned task). + reinsertPendingMove := func() { + if s.messageQueue == nil { + return + } + s.messageQueue.SetPendingMove(ctx, sessionID, move) + } + + if s.workflowStepGetter == nil || s.workflowStore == nil { + s.logger.Warn("cannot apply pending move: workflow components missing", + zap.String("task_id", taskID), + zap.String("session_id", sessionID)) + reinsertPendingMove() + return + } + + task, err := s.repo.GetTask(ctx, taskID) + if err != nil { + s.logger.Error("failed to load task for pending move", + zap.String("task_id", taskID), + zap.Error(err)) + reinsertPendingMove() + return + } + fromStepID := task.WorkflowStepID + if fromStepID == move.WorkflowStepID { + // Step already matches — nothing to transition. Just leave the queued + // prompt for the natural drain path. Don't reinsert: the move is + // effectively complete since the task is already at the target step. + s.logger.Info("pending move target equals current step; skipping transition", + zap.String("task_id", taskID), + zap.String("step_id", fromStepID)) + s.drainQueuedMessageAfterTransition(ctx, sessionID) + return + } + + targetStep, err := s.workflowStepGetter.GetStep(ctx, move.WorkflowStepID) + if err != nil || targetStep == nil { + s.logger.Error("failed to load target step for pending move", + zap.String("task_id", taskID), + zap.String("target_step_id", move.WorkflowStepID), + zap.Error(err)) + reinsertPendingMove() + return + } + + // Mark the session WAITING_FOR_INPUT before processOnEnter runs. The agent + // just finished its turn; the active-turn guard in processOnEnter would + // otherwise see RUNNING and skip the on_enter processing. + s.setSessionWaitingForInput(ctx, taskID, sessionID, session) + + if err := s.workflowStore.ApplyTransition(ctx, taskID, sessionID, fromStepID, move.WorkflowStepID, engine.TriggerOnEnter); err != nil { + s.logger.Error("failed to apply pending move transition", + zap.String("task_id", taskID), + zap.Error(err)) + // The hand-off prompt was queued by handleMoveTask before the move was + // applied. Now that the move failed, the on_enter path that would have + // drained the queue won't run, and handleAgentReady has already returned. + // Drop the orphan so it can't be misdelivered to the source step's agent + // on a future turn (it was authored for the move's *target* step). + if s.messageQueue != nil { + if _, ok := s.messageQueue.TakeQueued(ctx, sessionID); ok { + s.publishQueueStatusEvent(ctx, sessionID) + s.logger.Warn("dropped hand-off prompt after pending-move transition failure", + zap.String("task_id", taskID), + zap.String("session_id", sessionID)) + } + } + return + } + + s.logger.Info("applying pending move", + zap.String("task_id", taskID), + zap.String("session_id", sessionID), + zap.String("from_step_id", fromStepID), + zap.String("to_step_id", move.WorkflowStepID)) + + // Run on_exit + on_enter asynchronously. This call originated from + // handleAgentReady on the WS event reader goroutine; processStepExitAndEnter + // can take many seconds (resume + agentctl bootstrap) and would otherwise + // block that reader, queueing other agent events behind it and creating + // race conditions with concurrent on_turn_complete / agent.completed events + // for the same session. The DB transition is already persisted above, so + // it's safe to defer the rest. + taskDescription := task.Description + go s.processStepExitAndEnter(context.WithoutCancel(ctx), taskID, session, fromStepID, move.WorkflowStepID, taskDescription) +} + // drainQueuedMessageAfterTransition takes any user-queued message and dispatches // it for execution. Used by processOnEnter branches that don't auto-start the // agent — without this, the message is orphaned because handleAgentReady skips @@ -777,9 +1036,28 @@ func (s *Service) autoStartStepPrompt( ) error { sessionID := session.ID + // Take any queued message (e.g. from move_task_kandev with a hand-off + // prompt) and merge it with the step's auto-start prompt — auto-start + // content first, hand-off after — and forward attachments verbatim. + // Track the original message so terminal failure paths can restore it + // instead of dropping the user's prompt or attachments on the floor. + takenMsg, mergedPrompt, attachments := s.takeAndMergeHandoffMessage(ctx, sessionID, prompt) + prompt = mergedPrompt + + // requeueTaken puts the original queued message back so a manual retry can + // pick it up. Skip when shouldQueueIfBusy successfully re-queued the + // concatenated prompt (the content is already preserved there). + requeueTaken := func() { + if takenMsg == nil { + return + } + s.requeueMessage(ctx, takenMsg, takenMsg.QueuedBy) + } + if shouldQueueIfBusy { queued, err := s.queueAutoStartPromptIfRunning(ctx, taskID, session, prompt, planMode) if err != nil { + requeueTaken() return err } if queued { @@ -799,45 +1077,67 @@ func (s *Service) autoStartStepPrompt( zap.String("task_id", taskID), zap.String("session_id", sessionID), zap.String("step_name", stepName)) - _, err := s.StartCreatedSession(ctx, taskID, sessionID, session.AgentProfileID, prompt, true, planMode, nil) + _, err := s.StartCreatedSession(ctx, taskID, sessionID, session.AgentProfileID, prompt, true, planMode, attachments) + if err != nil { + requeueTaken() + } return err } const maxRetryAttempts = 5 for attempt := 1; attempt <= maxRetryAttempts; attempt++ { - _, err := s.PromptTask(ctx, taskID, sessionID, prompt, "", planMode, nil) + _, err := s.PromptTask(ctx, taskID, sessionID, prompt, "", planMode, attachments) if err == nil { return nil } + // ErrExecutionNotFound means ResumeSession landed on an execution that + // the lifecycle manager no longer has (e.g. the post-resume agent + // process failed to start and runAgentProcessAsync removed it). The + // session's stored AgentExecutionID is now stale. Recover by clearing + // it and routing through StartCreatedSession for a fresh launch — the + // prompt is baked into LaunchPreparedSession so we don't lose it. + if errors.Is(err, executor.ErrExecutionNotFound) { + s.logger.Warn("auto-start: PromptTask hit missing execution; falling back to fresh launch", + zap.String("task_id", taskID), + zap.String("session_id", sessionID), + zap.String("step_name", stepName)) + return s.fallbackFreshLaunchOnMissingExecution(ctx, taskID, sessionID, prompt, planMode, takenMsg, attachments) + } + // "already has an agent running" means the execution store still tracks // an active agent for this session (e.g. session state is CREATED but // the agent was launched by a concurrent path). Queue instead of retrying. if isAgentAlreadyRunningError(err) && shouldQueueIfBusy { if queueErr := s.queueAutoStartPrompt(ctx, taskID, sessionID, prompt, planMode); queueErr != nil { + requeueTaken() return queueErr } return nil } if !isAgentPromptInProgressError(err) && !isTransientPromptError(err) && !isSessionResetInProgressError(err) { + requeueTaken() return err } if shouldQueueIfBusy { if queueErr := s.queueAutoStartPrompt(ctx, taskID, sessionID, prompt, planMode); queueErr != nil { + requeueTaken() return queueErr } return nil } if attempt == maxRetryAttempts { + requeueTaken() return err } delay := time.Duration(50*(1<<(attempt-1))) * time.Millisecond select { case <-ctx.Done(): + requeueTaken() return fmt.Errorf("auto-start context canceled: %w", ctx.Err()) case <-time.After(delay): } @@ -846,6 +1146,85 @@ func (s *Service) autoStartStepPrompt( return nil } +// fallbackFreshLaunchOnMissingExecution recovers from a PromptTask that returned +// ErrExecutionNotFound — the session's stored AgentExecutionID points at an +// execution the lifecycle manager doesn't have, so the resume path is dead. +// Clear the stale ID, flip state to CREATED, and route through StartCreatedSession +// (which uses LaunchPreparedSession with the prompt baked in — bypassing resume). +// On further failure, the queued message is restored so a manual retry recovers it. +func (s *Service) fallbackFreshLaunchOnMissingExecution( + ctx context.Context, + taskID, sessionID, prompt string, + planMode bool, + takenMsg *messagequeue.QueuedMessage, + attachments []v1.MessageAttachment, +) error { + requeue := func() { + if takenMsg != nil { + s.requeueMessage(ctx, takenMsg, takenMsg.QueuedBy) + } + } + + fresh, err := s.repo.GetTaskSession(ctx, sessionID) + if err != nil { + s.logger.Error("auto-start fallback: failed to load session", + zap.String("session_id", sessionID), zap.Error(err)) + requeue() + return err + } + + fresh.AgentExecutionID = "" + fresh.State = models.TaskSessionStateCreated + fresh.UpdatedAt = time.Now().UTC() + if err := s.repo.UpdateTaskSession(ctx, fresh); err != nil { + s.logger.Error("auto-start fallback: failed to reset session for fresh launch", + zap.String("session_id", sessionID), zap.Error(err)) + requeue() + return err + } + + if _, err := s.StartCreatedSession(ctx, taskID, sessionID, fresh.AgentProfileID, prompt, true, planMode, attachments); err != nil { + s.logger.Error("auto-start fallback: fresh launch failed", + zap.String("session_id", sessionID), zap.Error(err)) + requeue() + return err + } + return nil +} + +// takeAndMergeHandoffMessage drains any queued hand-off message for the session +// (set by handleMoveTask via move_task_kandev or by drainQueuedMessageAfterTransition) +// and merges its content + attachments into the auto-start prompt. Returns the +// original queued message (so terminal failure paths can re-queue it via +// requeueMessage), the merged prompt, and the converted attachments. Empty +// messages with neither content nor attachments are left in the queue. +func (s *Service) takeAndMergeHandoffMessage(ctx context.Context, sessionID, basePrompt string) (*messagequeue.QueuedMessage, string, []v1.MessageAttachment) { + if s.messageQueue == nil { + return nil, basePrompt, nil + } + msg, ok := s.messageQueue.TakeQueued(ctx, sessionID) + if !ok || msg == nil || (msg.Content == "" && len(msg.Attachments) == 0) { + return nil, basePrompt, nil + } + prompt := basePrompt + if msg.Content != "" { + prompt = basePrompt + "\n\n" + msg.Content + } + var attachments []v1.MessageAttachment + if len(msg.Attachments) > 0 { + attachments = make([]v1.MessageAttachment, 0, len(msg.Attachments)) + for _, a := range msg.Attachments { + attachments = append(attachments, v1.MessageAttachment{ + Type: a.Type, + Data: a.Data, + MimeType: a.MimeType, + }) + } + } + s.publishQueueStatusEvent(ctx, sessionID) + return msg, prompt, attachments +} + // recordAutoStartMessage creates a user message for a workflow auto-start prompt // so it appears in the chat history. The prompt content includes system-injected // tags which are stripped when displayed to users via ToAPI(). diff --git a/apps/backend/internal/orchestrator/event_handlers_workflow_profile_test.go b/apps/backend/internal/orchestrator/event_handlers_workflow_profile_test.go index 74832551ca..3f23b1d739 100644 --- a/apps/backend/internal/orchestrator/event_handlers_workflow_profile_test.go +++ b/apps/backend/internal/orchestrator/event_handlers_workflow_profile_test.go @@ -162,6 +162,326 @@ func TestSwitchSessionForStep(t *testing.T) { }) } +// TestSwitchSessionForStep_ReusesExistingProfileSession verifies the core +// requirement: when switching to a profile that already has a session on this +// task, switchSessionForStep reuses it instead of creating a third session. +// Covers the A→B→A round trip (and beyond) at the unit-test level. +func TestSwitchSessionForStep_ReusesExistingProfileSession(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC() + + repo := setupTestRepo(t) + + ws := &models.Workspace{ID: "ws1", Name: "Test", CreatedAt: now, UpdatedAt: now} + _ = repo.CreateWorkspace(ctx, ws) + wf := &models.Workflow{ID: "wf1", WorkspaceID: "ws1", Name: "WF", CreatedAt: now, UpdatedAt: now} + _ = repo.CreateWorkflow(ctx, wf) + task := &models.Task{ + ID: "t1", WorkflowID: "wf1", WorkflowStepID: "step1", + Title: "Test", Description: "Test", State: v1.TaskStateInProgress, + CreatedAt: now, UpdatedAt: now, + } + _ = repo.CreateTask(ctx, task) + + // Prior session for profile-A — was active before, then completed when + // the workflow switched away from this profile last time. + completedAt := now.Add(-2 * time.Minute) + prior := &models.TaskSession{ + ID: "session-a", + TaskID: "t1", + AgentProfileID: "profile-a", + ExecutorID: "exec-local", + ExecutorProfileID: "ep1", + State: models.TaskSessionStateCompleted, + IsPrimary: false, + CompletedAt: &completedAt, + StartedAt: now.Add(-3 * time.Minute), + UpdatedAt: completedAt, + } + _ = repo.CreateTaskSession(ctx, prior) + + // Currently-active session for profile-B — about to be switched away from. + current := &models.TaskSession{ + ID: "session-b", + TaskID: "t1", + AgentProfileID: "profile-b", + ExecutorID: "exec-local", + ExecutorProfileID: "ep1", + AgentExecutionID: "ae-b", + State: models.TaskSessionStateRunning, + IsPrimary: true, + StartedAt: now, + UpdatedAt: now, + } + _ = repo.CreateTaskSession(ctx, current) + + taskRepo := newMockTaskRepo() + taskRepo.tasks["t1"] = &v1.Task{ + ID: "t1", WorkspaceID: "ws1", WorkflowID: "wf1", + Title: "Test", Description: "Test", State: v1.TaskStateInProgress, + } + + agentMgr := &mockAgentManager{} + log := testLogger() + exec := executor.NewExecutor(agentMgr, repo, log, executor.ExecutorConfig{}) + sched := scheduler.NewScheduler(queue.NewTaskQueue(100), exec, taskRepo, log, scheduler.SchedulerConfig{}) + svc := &Service{ + logger: log, + repo: repo, + workflowStepGetter: newMockStepGetter(), + taskRepo: taskRepo, + agentManager: agentMgr, + messageQueue: messagequeue.NewService(log), + executor: exec, + scheduler: sched, + } + + revived, err := svc.switchSessionForStep(ctx, "t1", current, "profile-a") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + + // Critical: reuse must return the existing session — NOT a brand-new id. + if revived == nil || revived.ID != "session-a" { + t.Fatalf("expected reused session-a, got %+v", revived) + } + + // Total session count must remain 2 — no third session created. + sessions, err := repo.ListTaskSessions(ctx, "t1") + if err != nil { + t.Fatalf("failed to list sessions: %v", err) + } + if len(sessions) != 2 { + t.Errorf("expected 2 sessions after reuse, got %d", len(sessions)) + } + + // The reused session must be back to a non-terminal state (so it can + // receive the next prompt) and be primary. Specifically, since the prior + // session has no executors_running record (never launched), it should + // flip to CREATED so autoStartStepPrompt routes through StartCreatedSession + // for a fresh launch (instead of hitting "no executor record" in + // ensureSessionRunning). + reused, _ := repo.GetTaskSession(ctx, "session-a") + if reused.State != models.TaskSessionStateCreated { + t.Errorf("never-launched reused session must be CREATED (so StartCreatedSession launches it fresh), got %s", reused.State) + } + if reused.CompletedAt != nil { + t.Error("reused session must have CompletedAt cleared") + } + if !reused.IsPrimary { + t.Error("reused session must be primary") + } + + // The previous current session-b must now be COMPLETED, not primary. + parked, _ := repo.GetTaskSession(ctx, "session-b") + if parked.State != models.TaskSessionStateCompleted { + t.Errorf("previous current session must be COMPLETED, got %s", parked.State) + } + if parked.IsPrimary { + t.Error("previous current session must no longer be primary") + } +} + +// TestSwitchSessionForStep_ReusesPreviouslyLaunchedSession covers the other +// branch of the revive: when the reused session has an executors_running +// record (it was previously launched and has a resume token), it flips to +// WAITING_FOR_INPUT so PromptTask's ensureSessionRunning lazy-resumes the +// agent via ResumeSession (preserving its prior conversation context). +func TestSwitchSessionForStep_ReusesPreviouslyLaunchedSession(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC() + + repo := setupTestRepo(t) + + ws := &models.Workspace{ID: "ws1", Name: "Test", CreatedAt: now, UpdatedAt: now} + _ = repo.CreateWorkspace(ctx, ws) + wf := &models.Workflow{ID: "wf1", WorkspaceID: "ws1", Name: "WF", CreatedAt: now, UpdatedAt: now} + _ = repo.CreateWorkflow(ctx, wf) + task := &models.Task{ + ID: "t1", WorkflowID: "wf1", WorkflowStepID: "step1", + Title: "Test", Description: "Test", State: v1.TaskStateInProgress, + CreatedAt: now, UpdatedAt: now, + } + _ = repo.CreateTask(ctx, task) + + // Prior session for profile-A — was previously active and has the + // signals of a real launch: an executors_running record with a resume + // token. This should route through the WAITING_FOR_INPUT branch of + // reviveReusedSession. + completedAt := now.Add(-2 * time.Minute) + prior := &models.TaskSession{ + ID: "session-a", + TaskID: "t1", + AgentProfileID: "profile-a", + ExecutorID: "exec-local", + ExecutorProfileID: "ep1", + AgentExecutionID: "ae-a-1", + State: models.TaskSessionStateCompleted, + CompletedAt: &completedAt, + StartedAt: now.Add(-3 * time.Minute), + UpdatedAt: completedAt, + } + _ = repo.CreateTaskSession(ctx, prior) + _ = repo.UpsertExecutorRunning(ctx, &models.ExecutorRunning{ + ID: "er-a", SessionID: "session-a", TaskID: "t1", + ResumeToken: "acp-session-a", + Resumable: true, + CreatedAt: completedAt, UpdatedAt: completedAt, + }) + + current := &models.TaskSession{ + ID: "session-b", + TaskID: "t1", + AgentProfileID: "profile-b", + ExecutorID: "exec-local", + ExecutorProfileID: "ep1", + AgentExecutionID: "ae-b", + State: models.TaskSessionStateRunning, + IsPrimary: true, + StartedAt: now, + UpdatedAt: now, + } + _ = repo.CreateTaskSession(ctx, current) + + taskRepo := newMockTaskRepo() + taskRepo.tasks["t1"] = &v1.Task{ + ID: "t1", WorkspaceID: "ws1", WorkflowID: "wf1", + Title: "Test", Description: "Test", State: v1.TaskStateInProgress, + } + + agentMgr := &mockAgentManager{} + log := testLogger() + exec := executor.NewExecutor(agentMgr, repo, log, executor.ExecutorConfig{}) + sched := scheduler.NewScheduler(queue.NewTaskQueue(100), exec, taskRepo, log, scheduler.SchedulerConfig{}) + svc := &Service{ + logger: log, + repo: repo, + workflowStepGetter: newMockStepGetter(), + taskRepo: taskRepo, + agentManager: agentMgr, + messageQueue: messagequeue.NewService(log), + executor: exec, + scheduler: sched, + } + + revived, err := svc.switchSessionForStep(ctx, "t1", current, "profile-a") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if revived == nil || revived.ID != "session-a" { + t.Fatalf("expected reused session-a, got %+v", revived) + } + + reused, _ := repo.GetTaskSession(ctx, "session-a") + if reused.State != models.TaskSessionStateWaitingForInput { + t.Errorf("previously-launched reused session must be WAITING_FOR_INPUT (so PromptTask lazy-resumes via ResumeSession), got %s", reused.State) + } +} + +// TestSwitchSessionForStep_ReusesFailedSession exercises the requirement that +// FAILED sessions are reused too. Without this, a previously-failed session +// would be skipped and a fresh one created, leaving the FAILED one as a +// duplicate tab in the UI showing its stale error banner. +func TestSwitchSessionForStep_ReusesFailedSession(t *testing.T) { + ctx := context.Background() + now := time.Now().UTC() + + repo := setupTestRepo(t) + + ws := &models.Workspace{ID: "ws1", Name: "Test", CreatedAt: now, UpdatedAt: now} + _ = repo.CreateWorkspace(ctx, ws) + wf := &models.Workflow{ID: "wf1", WorkspaceID: "ws1", Name: "WF", CreatedAt: now, UpdatedAt: now} + _ = repo.CreateWorkflow(ctx, wf) + task := &models.Task{ + ID: "t1", WorkflowID: "wf1", WorkflowStepID: "step1", + Title: "Test", Description: "Test", State: v1.TaskStateInProgress, + CreatedAt: now, UpdatedAt: now, + } + _ = repo.CreateTask(ctx, task) + + failedAt := now.Add(-2 * time.Minute) + prior := &models.TaskSession{ + ID: "session-a", + TaskID: "t1", + AgentProfileID: "profile-a", + ExecutorID: "exec-local", + ExecutorProfileID: "ep1", + AgentExecutionID: "ae-a", + State: models.TaskSessionStateFailed, + ErrorMessage: "execution already running", + CompletedAt: &failedAt, + StartedAt: now.Add(-3 * time.Minute), + UpdatedAt: failedAt, + } + _ = repo.CreateTaskSession(ctx, prior) + _ = repo.UpsertExecutorRunning(ctx, &models.ExecutorRunning{ + ID: "er-a", SessionID: "session-a", TaskID: "t1", + ResumeToken: "acp-session-a", + Resumable: true, + CreatedAt: failedAt, UpdatedAt: failedAt, + }) + + current := &models.TaskSession{ + ID: "session-b", + TaskID: "t1", + AgentProfileID: "profile-b", + ExecutorID: "exec-local", + ExecutorProfileID: "ep1", + AgentExecutionID: "ae-b", + State: models.TaskSessionStateRunning, + IsPrimary: true, + StartedAt: now, + UpdatedAt: now, + } + _ = repo.CreateTaskSession(ctx, current) + + taskRepo := newMockTaskRepo() + taskRepo.tasks["t1"] = &v1.Task{ + ID: "t1", WorkspaceID: "ws1", WorkflowID: "wf1", + Title: "Test", Description: "Test", State: v1.TaskStateInProgress, + } + + agentMgr := &mockAgentManager{} + log := testLogger() + exec := executor.NewExecutor(agentMgr, repo, log, executor.ExecutorConfig{}) + sched := scheduler.NewScheduler(queue.NewTaskQueue(100), exec, taskRepo, log, scheduler.SchedulerConfig{}) + svc := &Service{ + logger: log, + repo: repo, + workflowStepGetter: newMockStepGetter(), + taskRepo: taskRepo, + agentManager: agentMgr, + messageQueue: messagequeue.NewService(log), + executor: exec, + scheduler: sched, + } + + revived, err := svc.switchSessionForStep(ctx, "t1", current, "profile-a") + if err != nil { + t.Fatalf("unexpected error: %v", err) + } + if revived == nil || revived.ID != "session-a" { + t.Fatalf("expected reused FAILED session-a, got %+v", revived) + } + + // No duplicate session must be created. + sessions, _ := repo.ListTaskSessions(ctx, "t1") + if len(sessions) != 2 { + t.Errorf("expected 2 sessions, got %d (FAILED session was not reused)", len(sessions)) + } + + reused, _ := repo.GetTaskSession(ctx, "session-a") + if reused.State != models.TaskSessionStateWaitingForInput { + t.Errorf("FAILED reused session must flip to WAITING_FOR_INPUT (lazy-resume via token), got %s", reused.State) + } + if reused.ErrorMessage != "" { + t.Errorf("FAILED reused session must have ErrorMessage cleared, got %q", reused.ErrorMessage) + } + if reused.CompletedAt != nil { + t.Error("FAILED reused session must have CompletedAt cleared") + } +} + func TestProcessOnEnter_ProfileSwitch(t *testing.T) { ctx := context.Background() diff --git a/apps/backend/internal/orchestrator/messagequeue/service.go b/apps/backend/internal/orchestrator/messagequeue/service.go index 7c41e9f0c9..19a6dbfa6f 100644 --- a/apps/backend/internal/orchestrator/messagequeue/service.go +++ b/apps/backend/internal/orchestrator/messagequeue/service.go @@ -16,18 +16,75 @@ import ( type Service struct { // In-memory storage: sessionID -> QueuedMessage queued map[string]*QueuedMessage - mu sync.RWMutex - logger *logger.Logger + // In-memory storage: sessionID -> PendingMove (deferred move_task_kandev moves) + pendingMoves map[string]*PendingMove + mu sync.RWMutex + logger *logger.Logger } // NewService creates a new message queue service func NewService(log *logger.Logger) *Service { return &Service{ - queued: make(map[string]*QueuedMessage), - logger: log.WithFields(zap.String("component", "message-queue")), + queued: make(map[string]*QueuedMessage), + pendingMoves: make(map[string]*PendingMove), + logger: log.WithFields(zap.String("component", "message-queue")), } } +// TransferSession moves any queued message and pending move from one session +// to another. Used by workflow session switches (when a target step has a +// different agent profile and switchSessionForStep creates a new session) so +// a prompt queued by move_task_kandev on the old session reaches the new one. +// Existing entries on the destination session are preserved if no source entry +// is present; otherwise the source entry replaces the destination entry. +func (s *Service) TransferSession(ctx context.Context, oldSessionID, newSessionID string) { + s.mu.Lock() + defer s.mu.Unlock() + + if msg, ok := s.queued[oldSessionID]; ok { + msg.SessionID = newSessionID + s.queued[newSessionID] = msg + delete(s.queued, oldSessionID) + s.logger.Info("transferred queued message between sessions", + zap.String("from_session_id", oldSessionID), + zap.String("to_session_id", newSessionID), + zap.String("queue_id", msg.ID)) + } + + if move, ok := s.pendingMoves[oldSessionID]; ok { + s.pendingMoves[newSessionID] = move + delete(s.pendingMoves, oldSessionID) + s.logger.Info("transferred pending move between sessions", + zap.String("from_session_id", oldSessionID), + zap.String("to_session_id", newSessionID)) + } +} + +// SetPendingMove records a pending move for a session (replaces any existing one). +// The move is applied by handleAgentReady when the agent's current turn completes. +func (s *Service) SetPendingMove(ctx context.Context, sessionID string, move *PendingMove) { + s.mu.Lock() + defer s.mu.Unlock() + move.QueuedAt = time.Now() + s.pendingMoves[sessionID] = move + s.logger.Info("pending move recorded", + zap.String("session_id", sessionID), + zap.String("task_id", move.TaskID), + zap.String("workflow_step_id", move.WorkflowStepID)) +} + +// TakePendingMove retrieves and removes the pending move for a session. +func (s *Service) TakePendingMove(ctx context.Context, sessionID string) (*PendingMove, bool) { + s.mu.Lock() + defer s.mu.Unlock() + move, exists := s.pendingMoves[sessionID] + if !exists { + return nil, false + } + delete(s.pendingMoves, sessionID) + return move, true +} + // QueueMessage queues a message for a session (replaces existing queued message) func (s *Service) QueueMessage(ctx context.Context, sessionID, taskID, content, model, userID string, planMode bool, attachments []MessageAttachment) (*QueuedMessage, error) { s.mu.Lock() diff --git a/apps/backend/internal/orchestrator/messagequeue/service_test.go b/apps/backend/internal/orchestrator/messagequeue/service_test.go index e72131304f..b0a8a0606b 100644 --- a/apps/backend/internal/orchestrator/messagequeue/service_test.go +++ b/apps/backend/internal/orchestrator/messagequeue/service_test.go @@ -87,6 +87,85 @@ func TestQueueMessage(t *testing.T) { }) } +func TestTransferSession(t *testing.T) { + t.Run("moves queued message and pending move from old to new session", func(t *testing.T) { + svc := setupService(t) + ctx := context.Background() + + _, err := svc.QueueMessage(ctx, "old-sess", "task-1", "hand-off prompt", "", "mcp-move-task", false, nil) + require.NoError(t, err) + svc.SetPendingMove(ctx, "old-sess", &PendingMove{ + TaskID: "task-1", + WorkflowStepID: "step-b", + }) + + svc.TransferSession(ctx, "old-sess", "new-sess") + + // Old session is empty. + _, exists := svc.TakeQueued(ctx, "old-sess") + assert.False(t, exists) + _, exists = svc.TakePendingMove(ctx, "old-sess") + assert.False(t, exists) + + // New session has both. + msg, exists := svc.TakeQueued(ctx, "new-sess") + require.True(t, exists) + assert.Equal(t, "hand-off prompt", msg.Content) + assert.Equal(t, "new-sess", msg.SessionID) + + move, exists := svc.TakePendingMove(ctx, "new-sess") + require.True(t, exists) + assert.Equal(t, "step-b", move.WorkflowStepID) + }) + + t.Run("no-op when source session is empty", func(t *testing.T) { + svc := setupService(t) + ctx := context.Background() + + svc.TransferSession(ctx, "empty-sess", "new-sess") + + _, exists := svc.TakeQueued(ctx, "new-sess") + assert.False(t, exists) + }) +} + +func TestPendingMove(t *testing.T) { + t.Run("set then take returns the move and clears it", func(t *testing.T) { + svc := setupService(t) + ctx := context.Background() + + svc.SetPendingMove(ctx, "session-1", &PendingMove{ + TaskID: "task-1", + WorkflowID: "wf-1", + WorkflowStepID: "step-2", + Position: 3, + }) + + got, exists := svc.TakePendingMove(ctx, "session-1") + require.True(t, exists) + assert.Equal(t, "task-1", got.TaskID) + assert.Equal(t, "step-2", got.WorkflowStepID) + assert.Equal(t, 3, got.Position) + assert.NotZero(t, got.QueuedAt) + + // Idempotent — second take returns nothing. + _, exists = svc.TakePendingMove(ctx, "session-1") + assert.False(t, exists) + }) + + t.Run("setting twice replaces the previous move", func(t *testing.T) { + svc := setupService(t) + ctx := context.Background() + + svc.SetPendingMove(ctx, "session-1", &PendingMove{TaskID: "task-1", WorkflowStepID: "step-a"}) + svc.SetPendingMove(ctx, "session-1", &PendingMove{TaskID: "task-1", WorkflowStepID: "step-b"}) + + got, exists := svc.TakePendingMove(ctx, "session-1") + require.True(t, exists) + assert.Equal(t, "step-b", got.WorkflowStepID) + }) +} + func TestTakeQueued(t *testing.T) { t.Run("retrieves and removes queued message", func(t *testing.T) { svc := setupService(t) diff --git a/apps/backend/internal/orchestrator/messagequeue/types.go b/apps/backend/internal/orchestrator/messagequeue/types.go index b5437d9031..8f2cdcdf5a 100644 --- a/apps/backend/internal/orchestrator/messagequeue/types.go +++ b/apps/backend/internal/orchestrator/messagequeue/types.go @@ -27,3 +27,15 @@ type QueueStatus struct { IsQueued bool `json:"is_queued"` // Whether a message is queued Message *QueuedMessage `json:"message"` // The queued message (nil if not queued) } + +// PendingMove represents a workflow step move requested by an agent (via +// move_task_kandev) while its turn is still active. Applied by handleAgentReady +// once the turn ends, to avoid racing the on_enter processing against the +// agent's running turn. +type PendingMove struct { + TaskID string `json:"task_id"` + WorkflowID string `json:"workflow_id"` + WorkflowStepID string `json:"workflow_step_id"` + Position int `json:"position"` + QueuedAt time.Time `json:"queued_at"` +} diff --git a/apps/backend/internal/orchestrator/service.go b/apps/backend/internal/orchestrator/service.go index 112d94c717..67fa51338d 100644 --- a/apps/backend/internal/orchestrator/service.go +++ b/apps/backend/internal/orchestrator/service.go @@ -332,6 +332,7 @@ func NewService( handlers := watcher.EventHandlers{ OnTaskDeleted: s.handleTaskDeleted, OnAgentRunning: s.handleAgentRunning, + OnAgentBootReady: s.handleAgentBootReady, OnAgentReady: s.handleAgentReady, OnAgentCompleted: s.handleAgentCompleted, OnAgentFailed: s.handleAgentFailed, diff --git a/apps/backend/internal/orchestrator/task_operations.go b/apps/backend/internal/orchestrator/task_operations.go index e2487cfe49..0ffed110b6 100644 --- a/apps/backend/internal/orchestrator/task_operations.go +++ b/apps/backend/internal/orchestrator/task_operations.go @@ -48,6 +48,13 @@ func isSessionResetInProgressError(err error) bool { return err != nil && (errors.Is(err, ErrSessionResetInProgress) || strings.Contains(err.Error(), ErrSessionResetInProgress.Error())) } +// isTransientPromptError reports whether a prompt error is worth retrying via +// the queue. ErrExecutionNotFound is intentionally NOT included here: +// callers that can recover (autoStartStepPrompt → fallbackFreshLaunchOnMissingExecution) +// detect it explicitly via errors.Is and route differently; callers that +// can't (executeQueuedMessage) should not infinite-requeue on it. Treating +// "execution not found" as transient blanket-applies a retry that loops +// forever when the execution is genuinely gone. func isTransientPromptError(err error) bool { if err == nil { return false @@ -350,23 +357,26 @@ func (s *Service) StartCreatedSession(ctx context.Context, taskID, sessionID, ag 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. - // If the target step has a different agent profile, executeStepTransition switches - // the session — so we need to pick up the new session afterwards. - s.processOnTurnStartViaEngine(ctx, taskID, session) - - // Re-read the session after on_turn_start may have switched it (agent profile change). - // The original session may have been completed; use the active session for this task. + // NOTE: on_turn_start is intentionally NOT processed here. + // - User-initiated path: dispatchPromptAsync (message_handlers.go) already + // calls ProcessOnTurnStart before invoking StartCreatedSession via + // forwardMessageAsPrompt, so on_turn_start has already fired. + // - Workflow auto-start path: autoStartStepPrompt calls us because the + // workflow just transitioned us into this step (via on_turn_complete or + // on_enter). Firing on_turn_start again here cascades the workflow back + // out before the step's auto-start prompt can be delivered to its agent. + // + // However, for the user-initiated path, on_turn_start may have switched the + // session profile already, in which case the session ID we were called with + // is now COMPLETED and we need to redirect to the new active session. session, err = s.repo.GetTaskSession(ctx, sessionID) if err != nil { - return nil, fmt.Errorf("failed to reload session after on_turn_start: %w", err) + return nil, fmt.Errorf("failed to reload session: %w", err) } if session.State == models.TaskSessionStateCompleted { - // on_turn_start switched the agent profile — find the new active session. activeSession, activeErr := s.repo.GetActiveTaskSessionByTaskID(ctx, taskID) if activeErr != nil || activeSession == nil { - return nil, fmt.Errorf("session was switched during on_turn_start but no active session found: %w", activeErr) + return nil, fmt.Errorf("session was switched but no active session found: %w", activeErr) } session = activeSession sessionID = activeSession.ID @@ -889,6 +899,9 @@ func (s *Service) ensureSessionRunning(ctx context.Context, sessionID string, se } // Use context.WithoutCancel to prevent WebSocket request timeout from canceling the resume. + // The lifecycle layer publishes events.AgentBootReady (handled by handleAgentBootReady) + // when the agent's ACP session initializes — that's what unblocks waitForSessionReady, + // no flag-tracking needed. resumeCtx := context.WithoutCancel(ctx) if _, err = s.executor.ResumeSession(resumeCtx, session, true); err != nil { if errors.Is(err, executor.ErrExecutionAlreadyRunning) { @@ -923,6 +936,10 @@ func (s *Service) startAgentOnPreparedWorkspace(ctx context.Context, sessionID s zap.String("session_id", sessionID), zap.String("agent_execution_id", session.AgentExecutionID)) + // Boot ready is published as events.AgentBootReady by the lifecycle layer + // and routed to handleAgentBootReady, which flips the session to + // WAITING_FOR_INPUT — that's what waitForSessionReady polls for. No flag + // tracking required here. launchCtx := context.WithoutCancel(ctx) task, err := s.scheduler.GetTask(launchCtx, session.TaskID) if err != nil { @@ -1614,6 +1631,17 @@ func (s *Service) PromptTask(ctx context.Context, taskID, sessionID string, prom return nil, fmt.Errorf("failed to ensure session is running: %w", err) } + // Reload session after ensureSessionRunning. If a resume happened, ResumeSession + // updated the session's AgentExecutionID via persistResumeState — but only on the + // pointer it received. If anything along the way swapped the pointer or the + // caller's struct is otherwise stale (e.g. a concurrent write), executor.Prompt + // would call PromptAgent with the OLD execution ID and get ErrExecutionNotFound. + // Re-reading from the DB after ensureSessionRunning guarantees we use the + // freshly-persisted AgentExecutionID. + if reloaded, err := s.repo.GetTaskSession(ctx, sessionID); err == nil && reloaded != nil { + session = reloaded + } + // 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 { diff --git a/apps/backend/internal/orchestrator/watcher/watcher.go b/apps/backend/internal/orchestrator/watcher/watcher.go index 2faa55afe3..60fec1543d 100644 --- a/apps/backend/internal/orchestrator/watcher/watcher.go +++ b/apps/backend/internal/orchestrator/watcher/watcher.go @@ -92,7 +92,8 @@ type EventHandlers struct { // Agent events OnAgentStarted func(ctx context.Context, data AgentEventData) OnAgentRunning func(ctx context.Context, data AgentEventData) - OnAgentReady func(ctx context.Context, data AgentEventData) + OnAgentBootReady func(ctx context.Context, data AgentEventData) // ACP session initialized; idle, no turn yet + OnAgentReady func(ctx context.Context, data AgentEventData) // Turn ended; agent idle waiting for follow-up OnAgentCompleted func(ctx context.Context, data AgentEventData) OnAgentFailed func(ctx context.Context, data AgentEventData) OnAgentStopped func(ctx context.Context, data AgentEventData) @@ -280,6 +281,7 @@ func (w *Watcher) subscribeToAgentEvents() error { }{ {events.AgentStarted, w.handlers.OnAgentStarted}, {events.AgentRunning, w.handlers.OnAgentRunning}, + {events.AgentBootReady, w.handlers.OnAgentBootReady}, {events.AgentReady, w.handlers.OnAgentReady}, {events.AgentCompleted, w.handlers.OnAgentCompleted}, {events.AgentFailed, w.handlers.OnAgentFailed}, diff --git a/apps/web/lib/ssr/mapper.ts b/apps/web/lib/ssr/mapper.ts index f7efcae211..ccff7b2229 100644 --- a/apps/web/lib/ssr/mapper.ts +++ b/apps/web/lib/ssr/mapper.ts @@ -78,6 +78,7 @@ export function taskToState( tasks: { activeTaskId: task.id, activeSessionId: resolvedSessionId, + pinnedSessionId: null, }, messages: resolvedSessionId && messages diff --git a/apps/web/lib/state/slices/kanban/kanban-slice.ts b/apps/web/lib/state/slices/kanban/kanban-slice.ts index 3a5ea1529c..152515ee01 100644 --- a/apps/web/lib/state/slices/kanban/kanban-slice.ts +++ b/apps/web/lib/state/slices/kanban/kanban-slice.ts @@ -5,7 +5,7 @@ export const defaultKanbanState: KanbanSliceState = { kanban: { workflowId: null, steps: [], tasks: [] }, kanbanMulti: { snapshots: {}, isLoading: false }, workflows: { items: [], activeId: null }, - tasks: { activeTaskId: null, activeSessionId: null }, + tasks: { activeTaskId: null, activeSessionId: null, pinnedSessionId: null }, }; export const createKanbanSlice: StateCreator< @@ -46,17 +46,29 @@ export const createKanbanSlice: StateCreator< set((draft) => { draft.tasks.activeTaskId = taskId; draft.tasks.activeSessionId = null; + // New task → drop any pin; the pin only applies within a single task. + draft.tasks.pinnedSessionId = null; }); }, setActiveSession: (taskId, sessionId) => { set((draft) => { draft.tasks.activeTaskId = taskId; draft.tasks.activeSessionId = sessionId; + // User-initiated selection: pin so WS auto-replace handoff respects it. + draft.tasks.pinnedSessionId = sessionId; + }); + }, + setActiveSessionAuto: (taskId, sessionId) => { + set((draft) => { + draft.tasks.activeTaskId = taskId; + draft.tasks.activeSessionId = sessionId; + // Auto-driven (WS) selection: don't touch pinnedSessionId. }); }, clearActiveSession: () => set((draft) => { draft.tasks.activeSessionId = null; + draft.tasks.pinnedSessionId = null; }), setWorkflowSnapshot: (workflowId, data) => set((draft) => { diff --git a/apps/web/lib/state/slices/kanban/types.ts b/apps/web/lib/state/slices/kanban/types.ts index 25838bfc61..3f356705e2 100644 --- a/apps/web/lib/state/slices/kanban/types.ts +++ b/apps/web/lib/state/slices/kanban/types.ts @@ -75,6 +75,12 @@ export type WorkflowsState = { export type TaskState = { activeTaskId: string | null; activeSessionId: string | null; + // pinnedSessionId tracks the session the USER explicitly selected. + // Set by setActiveSession (user-initiated). Cleared when navigating to a + // different task. WS auto-adopt paths use setActiveSessionAuto which leaves + // pinnedSessionId alone — and skip auto-replace when the terminating session + // matches the pin (the user wants to stay even though the workflow moved on). + pinnedSessionId: string | null; }; export type KanbanSliceState = { @@ -90,6 +96,10 @@ export type KanbanSliceActions = { reorderWorkflowItems: (workflowIds: string[]) => void; setActiveTask: (taskId: string) => void; setActiveSession: (taskId: string, sessionId: string) => void; + // setActiveSessionAuto is the same as setActiveSession but doesn't update + // pinnedSessionId. Used by WS handlers to follow workflow-driven session + // switches without overriding a user's manual selection. + setActiveSessionAuto: (taskId: string, sessionId: string) => void; clearActiveSession: () => void; setWorkflowSnapshot: (workflowId: string, data: WorkflowSnapshotData) => void; setKanbanMultiLoading: (loading: boolean) => void; diff --git a/apps/web/lib/state/store.ts b/apps/web/lib/state/store.ts index 4347aae3ff..52c229ec06 100644 --- a/apps/web/lib/state/store.ts +++ b/apps/web/lib/state/store.ts @@ -369,6 +369,7 @@ export type AppState = { ) => void; setMessagesLoading: (sessionId: string, loading: boolean) => void; setActiveSession: (taskId: string, sessionId: string) => void; + setActiveSessionAuto: (taskId: string, sessionId: string) => void; setActiveTask: (taskId: string) => void; clearActiveSession: () => void; setTaskSession: (session: TaskSession) => void; diff --git a/apps/web/lib/ws/handlers/agent-session.test.ts b/apps/web/lib/ws/handlers/agent-session.test.ts index ec689b9e51..db98ed0bcd 100644 --- a/apps/web/lib/ws/handlers/agent-session.test.ts +++ b/apps/web/lib/ws/handlers/agent-session.test.ts @@ -11,12 +11,13 @@ import type { TaskSessionState } from "@/lib/types/http"; function makeStore(overrides: Record = {}) { const state: Record = { - tasks: { activeTaskId: null, activeSessionId: null }, + tasks: { activeTaskId: null, activeSessionId: null, pinnedSessionId: null }, taskSessions: { items: {} }, taskSessionsByTask: { itemsByTaskId: {} }, setTaskSession: vi.fn(), setTaskSessionsForTask: vi.fn(), setActiveSession: vi.fn(), + setActiveSessionAuto: vi.fn(), setSessionFailureNotification: vi.fn(), setContextWindow: vi.fn(), ...overrides, @@ -133,7 +134,7 @@ describe("session.state_changed handler", () => { function makeAppState(partial: Partial): AppState { return { - tasks: { activeTaskId: null, activeSessionId: null }, + tasks: { activeTaskId: null, activeSessionId: null, pinnedSessionId: null }, taskSessions: { items: {} }, taskSessionsByTask: { itemsByTaskId: {} }, ...partial, @@ -158,14 +159,14 @@ describe("isTerminalSessionState", () => { describe("shouldAdoptNewSession", () => { it("adopts when there is no active session for the task", () => { const state = makeAppState({ - tasks: { activeTaskId: "t-1", activeSessionId: null }, + tasks: { activeTaskId: "t-1", activeSessionId: null, pinnedSessionId: null }, }); expect(shouldAdoptNewSession(state, "t-1", "STARTING")).toBe(true); }); it("adopts when active session belongs to a different task", () => { const state = makeAppState({ - tasks: { activeTaskId: "t-1", activeSessionId: "s-other" }, + tasks: { activeTaskId: "t-1", activeSessionId: "s-other", pinnedSessionId: null }, taskSessions: { items: { "s-other": { id: "s-other", task_id: "t-2", state: "RUNNING" } }, } as unknown as AppState["taskSessions"], @@ -175,7 +176,7 @@ describe("shouldAdoptNewSession", () => { it("adopts when active session is already terminal", () => { const state = makeAppState({ - tasks: { activeTaskId: "t-1", activeSessionId: "s-old" }, + tasks: { activeTaskId: "t-1", activeSessionId: "s-old", pinnedSessionId: null }, taskSessions: { items: { "s-old": { id: "s-old", task_id: "t-1", state: "COMPLETED" } }, } as unknown as AppState["taskSessions"], @@ -185,7 +186,7 @@ describe("shouldAdoptNewSession", () => { it("does NOT adopt while the current active session is still running", () => { const state = makeAppState({ - tasks: { activeTaskId: "t-1", activeSessionId: "s-old" }, + tasks: { activeTaskId: "t-1", activeSessionId: "s-old", pinnedSessionId: null }, taskSessions: { items: { "s-old": { id: "s-old", task_id: "t-1", state: "RUNNING" } }, } as unknown as AppState["taskSessions"], @@ -195,14 +196,14 @@ describe("shouldAdoptNewSession", () => { it("does NOT adopt when the event is for a non-active task", () => { const state = makeAppState({ - tasks: { activeTaskId: "t-1", activeSessionId: null }, + tasks: { activeTaskId: "t-1", activeSessionId: null, pinnedSessionId: null }, }); expect(shouldAdoptNewSession(state, "t-2", "STARTING")).toBe(false); }); it("does NOT adopt terminal state events", () => { const state = makeAppState({ - tasks: { activeTaskId: "t-1", activeSessionId: null }, + tasks: { activeTaskId: "t-1", activeSessionId: null, pinnedSessionId: null }, }); expect(shouldAdoptNewSession(state, "t-1", "COMPLETED")).toBe(false); }); @@ -250,7 +251,7 @@ describe("session.state_changed → active session switching", () => { it("adopts a newly-created session for the active task", () => { const store = makeStore({ - tasks: { activeTaskId: "t-1", activeSessionId: null }, + tasks: { activeTaskId: "t-1", activeSessionId: null, pinnedSessionId: null }, }); const handler = registerTaskSessionHandlers(store)[STATE_CHANGED_EVENT]!; @@ -261,12 +262,13 @@ describe("session.state_changed → active session switching", () => { payload: { task_id: "t-1", session_id: "s-new", new_state: "STARTING" }, }); - expect(store.getState().setActiveSession).toHaveBeenCalledWith("t-1", "s-new"); + expect(store.getState().setActiveSessionAuto).toHaveBeenCalledWith("t-1", "s-new"); + expect(store.getState().setActiveSession).not.toHaveBeenCalled(); }); it("does not adopt a new session for a task that is not active", () => { const store = makeStore({ - tasks: { activeTaskId: "other-task", activeSessionId: null }, + tasks: { activeTaskId: "other-task", activeSessionId: null, pinnedSessionId: null }, }); const handler = registerTaskSessionHandlers(store)[STATE_CHANGED_EVENT]!; @@ -277,12 +279,12 @@ describe("session.state_changed → active session switching", () => { payload: { task_id: "t-1", session_id: "s-new", new_state: "STARTING" }, }); - expect(store.getState().setActiveSession).not.toHaveBeenCalled(); + expect(store.getState().setActiveSessionAuto).not.toHaveBeenCalled(); }); it("does not adopt while the current active session is still running", () => { const store = makeStore({ - tasks: { activeTaskId: "t-1", activeSessionId: "s-old" }, + tasks: { activeTaskId: "t-1", activeSessionId: "s-old", pinnedSessionId: null }, taskSessions: { items: { "s-old": { id: "s-old", task_id: "t-1", state: "RUNNING" } }, }, @@ -296,7 +298,33 @@ describe("session.state_changed → active session switching", () => { payload: { task_id: "t-1", session_id: "s-new", new_state: "STARTING" }, }); - expect(store.getState().setActiveSession).not.toHaveBeenCalled(); + expect(store.getState().setActiveSessionAuto).not.toHaveBeenCalled(); + }); + + // Regression for the reverse-event-ordering race: if the OLD pinned session's + // COMPLETED event arrives before the NEW session's STARTING event, the + // terminal-handoff guard (which protects pinning) doesn't run on the COMPLETED + // event because s-new isn't yet in the store. When the STARTING event + // arrives, shouldAdoptNewSession returns true (old is now terminal) and would + // auto-yank the user off their pinned session — unless we re-check pinning on + // this path too. + it("does not yank a pinned session on reverse event ordering (old COMPLETED, then new STARTING)", () => { + const store = makeStore({ + tasks: { activeTaskId: "t-1", activeSessionId: "s-old", pinnedSessionId: "s-old" }, + taskSessions: { + items: { "s-old": { id: "s-old", task_id: "t-1", state: "COMPLETED" } }, + }, + }); + const handler = registerTaskSessionHandlers(store)[STATE_CHANGED_EVENT]!; + + handler({ + id: "m", + type: "notification", + action: STATE_CHANGED_EVENT, + payload: { task_id: "t-1", session_id: "s-new", new_state: "STARTING" }, + }); + + expect(store.getState().setActiveSessionAuto).not.toHaveBeenCalled(); }); }); @@ -307,7 +335,7 @@ describe("session.state_changed → active session handoff on terminal", () => { it("hands off when the current active session transitions to terminal", () => { const store = makeStore({ - tasks: { activeTaskId: "t-1", activeSessionId: "s-old" }, + tasks: { activeTaskId: "t-1", activeSessionId: "s-old", pinnedSessionId: null }, taskSessions: { items: { "s-old": { id: "s-old", task_id: "t-1", state: "RUNNING" } }, }, @@ -329,7 +357,8 @@ describe("session.state_changed → active session handoff on terminal", () => { payload: { task_id: "t-1", session_id: "s-old", new_state: "COMPLETED" }, }); - expect(store.getState().setActiveSession).toHaveBeenCalledWith("t-1", "s-new"); + expect(store.getState().setActiveSessionAuto).toHaveBeenCalledWith("t-1", "s-new"); + expect(store.getState().setActiveSession).not.toHaveBeenCalled(); }); // The per-task list here still shows s-old as RUNNING (pre-event state), so @@ -338,7 +367,7 @@ describe("session.state_changed → active session handoff on terminal", () => { // to the same session that just became terminal. it("does not hand off when the only candidate is the terminating session itself", () => { const store = makeStore({ - tasks: { activeTaskId: "t-1", activeSessionId: "s-old" }, + tasks: { activeTaskId: "t-1", activeSessionId: "s-old", pinnedSessionId: null }, taskSessions: { items: { "s-old": { id: "s-old", task_id: "t-1", state: "RUNNING" } }, }, @@ -359,12 +388,12 @@ describe("session.state_changed → active session handoff on terminal", () => { payload: { task_id: "t-1", session_id: "s-old", new_state: "COMPLETED" }, }); - expect(store.getState().setActiveSession).not.toHaveBeenCalled(); + expect(store.getState().setActiveSessionAuto).not.toHaveBeenCalled(); }); it("does not hand off when all other sessions for the task are terminal", () => { const store = makeStore({ - tasks: { activeTaskId: "t-1", activeSessionId: "s-old" }, + tasks: { activeTaskId: "t-1", activeSessionId: "s-old", pinnedSessionId: null }, taskSessions: { items: { "s-old": { id: "s-old", task_id: "t-1", state: "RUNNING" } }, }, @@ -386,6 +415,42 @@ describe("session.state_changed → active session handoff on terminal", () => { payload: { task_id: "t-1", session_id: "s-old", new_state: "COMPLETED" }, }); + expect(store.getState().setActiveSessionAuto).not.toHaveBeenCalled(); + }); +}); + +describe("session.state_changed → respects user-pinned session", () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it("does NOT hand off when the user pinned the session that just terminated", () => { + // User manually clicked s-old, so pinnedSessionId === "s-old". + // When s-old terminates we should respect the pin and stay on it. + const store = makeStore({ + tasks: { activeTaskId: "t-1", activeSessionId: "s-old", pinnedSessionId: "s-old" }, + taskSessions: { + items: { "s-old": { id: "s-old", task_id: "t-1", state: "RUNNING" } }, + }, + taskSessionsByTask: { + itemsByTaskId: { + "t-1": [ + { id: "s-old", task_id: "t-1", state: "RUNNING", started_at: "", updated_at: "" }, + { id: "s-new", task_id: "t-1", state: "STARTING", started_at: "", updated_at: "" }, + ], + }, + }, + }); + const handler = registerTaskSessionHandlers(store)[STATE_CHANGED_EVENT]!; + + handler({ + id: "m", + type: "notification", + action: STATE_CHANGED_EVENT, + payload: { task_id: "t-1", session_id: "s-old", new_state: "COMPLETED" }, + }); + + expect(store.getState().setActiveSessionAuto).not.toHaveBeenCalled(); expect(store.getState().setActiveSession).not.toHaveBeenCalled(); }); }); diff --git a/apps/web/lib/ws/handlers/agent-session.ts b/apps/web/lib/ws/handlers/agent-session.ts index 5b40b56524..6ccd6fae37 100644 --- a/apps/web/lib/ws/handlers/agent-session.ts +++ b/apps/web/lib/ws/handlers/agent-session.ts @@ -171,17 +171,28 @@ function maybeAdoptSessionOnTransition( if (!wasKnownToStore && shouldAdoptNewSession(state, taskId, newState)) { const oldSessionId = state.tasks.activeSessionId; + // Reverse-ordering guard: if the events arrive as old=COMPLETED then + // new=STARTING (instead of the typical new=STARTING then old=COMPLETED), + // shouldAdoptNewSession returns true on the second event because the old + // session is now terminal. But the user may have pinned the old session — + // in that case the symmetric guard below was skipped (no terminal event + // for the new session), and we'd auto-yank them off their pinned session + // here. Match the terminal-handoff path's pinning check. + if (oldSessionId && state.tasks.pinnedSessionId === oldSessionId) return; if (oldSessionId) inheritAgentctlStatus(state, oldSessionId, sessionId); - state.setActiveSession(taskId, sessionId); + state.setActiveSessionAuto(taskId, sessionId); return; } const isActive = state.tasks.activeSessionId === sessionId; if (isActive && newState && isTerminalSessionState(newState)) { + // If the user explicitly pinned this session (manual click), don't yank + // them away just because the workflow moved it to a terminal state. + if (state.tasks.pinnedSessionId === sessionId) return; const replacement = pickReplacementSessionId(state, taskId); if (replacement && replacement !== sessionId) { inheritAgentctlStatus(state, sessionId, replacement); - state.setActiveSession(taskId, replacement); + state.setActiveSessionAuto(taskId, replacement); } } } diff --git a/apps/web/lib/ws/handlers/tasks.test.ts b/apps/web/lib/ws/handlers/tasks.test.ts new file mode 100644 index 0000000000..a263d40469 --- /dev/null +++ b/apps/web/lib/ws/handlers/tasks.test.ts @@ -0,0 +1,179 @@ +import { beforeEach, describe, expect, it, vi } from "vitest"; +import type { StoreApi } from "zustand"; +import type { AppState } from "@/lib/state/store"; +import { registerTasksHandlers } from "./tasks"; + +type Listener = (state: AppState) => void; + +/** + * Minimal in-memory store for the tasks WS handler tests. + * The handler reads kanban tasks, kanbanMulti snapshots, and tasks.activeTaskId/activeSessionId, + * and calls setActiveSession; everything else can stay default. + */ +function makeStore(initial: Partial = {}) { + let state = { + kanban: { workflowId: "wf1", steps: [], tasks: [] }, + kanbanMulti: { snapshots: {}, isLoading: false }, + tasks: { activeTaskId: null, activeSessionId: null, pinnedSessionId: null }, + setActiveSession: vi.fn((taskId: string, sessionId: string | null) => { + state = { + ...state, + tasks: { + activeTaskId: taskId, + activeSessionId: sessionId, + pinnedSessionId: sessionId, + }, + }; + }), + setActiveSessionAuto: vi.fn((taskId: string, sessionId: string | null) => { + state = { + ...state, + tasks: { + ...state.tasks, + activeTaskId: taskId, + activeSessionId: sessionId, + }, + }; + }), + ...initial, + } as unknown as AppState; + + const listeners = new Set(); + return { + getState: () => state, + setState: (updater: AppState | ((s: AppState) => AppState)) => { + const next = + typeof updater === "function" ? (updater as (s: AppState) => AppState)(state) : updater; + state = { ...state, ...next }; + for (const l of listeners) l(state); + }, + subscribe: (l: Listener) => { + listeners.add(l); + return () => listeners.delete(l); + }, + destroy: vi.fn(), + getInitialState: vi.fn(), + } as unknown as StoreApi & { getState: () => AppState }; +} + +function makeTask(id: string, primarySessionId: string | null, workflowId = "wf1") { + return { + task_id: id, + workflow_id: workflowId, + workflow_step_id: "step1", + title: "Test", + description: "", + state: "IN_PROGRESS", + primary_session_id: primarySessionId, + is_ephemeral: false, + } as Record; +} + +function makeMessage(payload: Record) { + return { + id: "msg-1", + type: "notification" as const, + action: "task.updated" as const, + payload, + } as Parameters["task.updated"]>>[0]; +} + +describe("task.updated primary-session focus follow", () => { + let store: ReturnType; + let setActiveSessionAuto: ReturnType; + + beforeEach(() => { + setActiveSessionAuto = vi.fn(); + }); + + it("follows focus to the new primary when the user is on the previous primary", () => { + store = makeStore({ + kanban: { + workflowId: "wf1", + steps: [], + tasks: [{ id: "t1", primarySessionId: "sess-old", workflowId: "wf1" }], + } as unknown as AppState["kanban"], + tasks: { activeTaskId: "t1", activeSessionId: "sess-old", pinnedSessionId: null }, + setActiveSessionAuto, + }); + + const handlers = registerTasksHandlers(store); + handlers["task.updated"]!(makeMessage(makeTask("t1", "sess-new"))); + + expect(setActiveSessionAuto).toHaveBeenCalledTimes(1); + expect(setActiveSessionAuto).toHaveBeenCalledWith("t1", "sess-new"); + }); + + it("does NOT follow focus when the user is on a different session than the previous primary", () => { + // User manually selected sess-other; primary swapping shouldn't yank them away. + store = makeStore({ + kanban: { + workflowId: "wf1", + steps: [], + tasks: [{ id: "t1", primarySessionId: "sess-old", workflowId: "wf1" }], + } as unknown as AppState["kanban"], + tasks: { activeTaskId: "t1", activeSessionId: "sess-other", pinnedSessionId: "sess-other" }, + setActiveSessionAuto, + }); + + const handlers = registerTasksHandlers(store); + handlers["task.updated"]!(makeMessage(makeTask("t1", "sess-new"))); + + expect(setActiveSessionAuto).not.toHaveBeenCalled(); + }); + + it("does NOT follow focus when the user is viewing a different task", () => { + store = makeStore({ + kanban: { + workflowId: "wf1", + steps: [], + tasks: [{ id: "t1", primarySessionId: "sess-old", workflowId: "wf1" }], + } as unknown as AppState["kanban"], + tasks: { activeTaskId: "t2", activeSessionId: "sess-old", pinnedSessionId: null }, + setActiveSessionAuto, + }); + + const handlers = registerTasksHandlers(store); + handlers["task.updated"]!(makeMessage(makeTask("t1", "sess-new"))); + + expect(setActiveSessionAuto).not.toHaveBeenCalled(); + }); + + it("does NOT call setActiveSessionAuto when the primary did not change", () => { + store = makeStore({ + kanban: { + workflowId: "wf1", + steps: [], + tasks: [{ id: "t1", primarySessionId: "sess-old", workflowId: "wf1" }], + } as unknown as AppState["kanban"], + tasks: { activeTaskId: "t1", activeSessionId: "sess-old", pinnedSessionId: null }, + setActiveSessionAuto, + }); + + const handlers = registerTasksHandlers(store); + handlers["task.updated"]!(makeMessage(makeTask("t1", "sess-old"))); + + expect(setActiveSessionAuto).not.toHaveBeenCalled(); + }); + + // Regression: even when the user happens to be sitting on the previous + // primary, an explicit pin on it must override primary-follow-focus — + // otherwise a workflow profile switch silently yanks them off the session + // they deliberately clicked into. + it("does NOT follow focus when the user has pinned the previous primary", () => { + store = makeStore({ + kanban: { + workflowId: "wf1", + steps: [], + tasks: [{ id: "t1", primarySessionId: "sess-old", workflowId: "wf1" }], + } as unknown as AppState["kanban"], + tasks: { activeTaskId: "t1", activeSessionId: "sess-old", pinnedSessionId: "sess-old" }, + setActiveSessionAuto, + }); + + const handlers = registerTasksHandlers(store); + handlers["task.updated"]!(makeMessage(makeTask("t1", "sess-new"))); + + expect(setActiveSessionAuto).not.toHaveBeenCalled(); + }); +}); diff --git a/apps/web/lib/ws/handlers/tasks.ts b/apps/web/lib/ws/handlers/tasks.ts index 3a7cdbb197..63ed3b5a37 100644 --- a/apps/web/lib/ws/handlers/tasks.ts +++ b/apps/web/lib/ws/handlers/tasks.ts @@ -64,6 +64,17 @@ function upsertTaskInBothKanbans( return next; } +/** Look up a task across both single-kanban and multi-kanban snapshots. */ +function findTaskInState(state: AppState, taskId: string): KanbanTask | undefined { + const fromKanban = state.kanban.tasks.find((t) => t.id === taskId); + if (fromKanban) return fromKanban; + for (const snapshot of Object.values(state.kanbanMulti.snapshots)) { + const found = snapshot.tasks.find((t) => t.id === taskId); + if (found) return found; + } + return undefined; +} + /** Remove a task from both single-kanban and multi-kanban snapshots. */ function removeTaskFromBothKanbans(state: AppState, wfId: string, taskId: string): AppState { let next = state; @@ -102,9 +113,15 @@ export function registerTasksHandlers(store: StoreApi): WsHandlers { // Skip ephemeral tasks (e.g., quick chat) - they shouldn't appear on the Kanban board if (message.payload.is_ephemeral) return; + // Capture the previous primary session id BEFORE the upsert so we can + // detect a primary-session swap (e.g. workflow profile switch reusing a + // different session) and follow focus to the new primary. + const beforeState = store.getState(); + const taskId = message.payload.task_id; + const previousPrimary = findTaskInState(beforeState, taskId)?.primarySessionId ?? null; + store.setState((state) => { const wfId = message.payload.workflow_id; - const taskId = message.payload.task_id; if (message.payload.archived_at) { return removeTaskFromBothKanbans(state, wfId, taskId); @@ -112,6 +129,26 @@ export function registerTasksHandlers(store: StoreApi): WsHandlers { return upsertTaskInBothKanbans(state, wfId, message.payload); }); + + // Follow focus to the new primary when: + // - the user is currently viewing this task, + // - the user was sitting on the previous primary, + // - they did NOT explicitly pin that previous primary (a manual click + // sets pinnedSessionId; pinned sessions must be left alone), and + // - the primary actually changed. + // This makes workflow profile switches transparent for unpinned users + // without yanking pinned ones off their deliberate selection. + const afterState = store.getState(); + const newPrimary = findTaskInState(afterState, taskId)?.primarySessionId ?? null; + if ( + newPrimary && + newPrimary !== previousPrimary && + afterState.tasks.activeTaskId === taskId && + afterState.tasks.activeSessionId === previousPrimary && + afterState.tasks.pinnedSessionId !== previousPrimary + ) { + afterState.setActiveSessionAuto(taskId, newPrimary); + } }, "task.deleted": (message) => { const deletedId = message.payload.task_id;