From b832390914a4eb8218d558388bd92ac658aed9d7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Carlos=20Flor=C3=AAncio?= Date: Tue, 31 Mar 2026 22:37:31 +0100 Subject: [PATCH] fix: preserve task status when resuming agent after backend restart (#508) --- .../executor/executor_mocks_test.go | 674 +++++++++++++++++ .../orchestrator/executor/executor_test.go | 700 ++---------------- apps/web/components/task/task-switcher.tsx | 13 +- .../e2e/tests/session/session-resume.spec.ts | 70 ++ 4 files changed, 802 insertions(+), 655 deletions(-) create mode 100644 apps/backend/internal/orchestrator/executor/executor_mocks_test.go diff --git a/apps/backend/internal/orchestrator/executor/executor_mocks_test.go b/apps/backend/internal/orchestrator/executor/executor_mocks_test.go new file mode 100644 index 0000000000..b1b58cd386 --- /dev/null +++ b/apps/backend/internal/orchestrator/executor/executor_mocks_test.go @@ -0,0 +1,674 @@ +package executor + +import ( + "context" + "fmt" + "sync" + "testing" + + agentdto "github.com/kandev/kandev/internal/agent/dto" + "github.com/kandev/kandev/internal/agentctl/client" + "github.com/kandev/kandev/internal/agentctl/types/streams" + "github.com/kandev/kandev/internal/common/logger" + "github.com/kandev/kandev/internal/task/models" + v1 "github.com/kandev/kandev/pkg/api/v1" +) + +// mockAgentManager implements AgentManagerClient for testing +type mockAgentManager struct { + launchAgentFunc func(ctx context.Context, req *LaunchAgentRequest) (*LaunchAgentResponse, error) + startAgentProcessFunc func(ctx context.Context, agentExecutionID string) error + stopAgentFunc func(ctx context.Context, agentExecutionID string, force bool) error + resolveAgentProfileFunc func(ctx context.Context, profileID string) (*AgentProfileInfo, error) + setExecutionDescriptionFunc func(ctx context.Context, agentExecutionID string, description string) error + getExecutionIDForSessionFunc func(ctx context.Context, sessionID string) (string, error) +} + +func (m *mockAgentManager) LaunchAgent(ctx context.Context, req *LaunchAgentRequest) (*LaunchAgentResponse, error) { + if m.launchAgentFunc != nil { + return m.launchAgentFunc(ctx, req) + } + return &LaunchAgentResponse{ + AgentExecutionID: "exec-123", + ContainerID: "container-123", + Status: v1.AgentStatusStarting, + }, nil +} + +func (m *mockAgentManager) SetExecutionDescription(ctx context.Context, agentExecutionID string, description string) error { + if m.setExecutionDescriptionFunc != nil { + return m.setExecutionDescriptionFunc(ctx, agentExecutionID, description) + } + return nil +} + +func (m *mockAgentManager) SetMcpMode(_ context.Context, _ string, _ string) error { + return nil +} + +func (m *mockAgentManager) StartAgentProcess(ctx context.Context, agentExecutionID string) error { + if m.startAgentProcessFunc != nil { + return m.startAgentProcessFunc(ctx, agentExecutionID) + } + return nil +} + +func (m *mockAgentManager) StopAgent(ctx context.Context, agentExecutionID string, force bool) error { + if m.stopAgentFunc != nil { + return m.stopAgentFunc(ctx, agentExecutionID, force) + } + return nil +} + +func (m *mockAgentManager) StopAgentWithReason(ctx context.Context, agentExecutionID string, reason string, force bool) error { + return m.StopAgent(ctx, agentExecutionID, force) +} + +func (m *mockAgentManager) PromptAgent(ctx context.Context, agentExecutionID string, prompt string, _ []v1.MessageAttachment) (*PromptResult, error) { + return nil, nil +} + +func (m *mockAgentManager) CancelAgent(ctx context.Context, sessionID string) error { + return nil +} + +func (m *mockAgentManager) RespondToPermissionBySessionID(ctx context.Context, sessionID, pendingID, optionID string, cancelled bool) error { + return nil +} + +func (m *mockAgentManager) RestartAgentProcess(ctx context.Context, agentExecutionID string) error { + return nil +} +func (m *mockAgentManager) ResetAgentContext(ctx context.Context, agentExecutionID string) error { + return nil +} + +func (m *mockAgentManager) SetSessionModelBySessionID(ctx context.Context, sessionID, modelID string) error { + return fmt.Errorf("not supported") +} + +func (m *mockAgentManager) IsAgentRunningForSession(ctx context.Context, sessionID string) bool { + return false +} + +func (m *mockAgentManager) WasSessionInitialized(_ string) bool { return false } +func (m *mockAgentManager) GetSessionAuthMethods(_ string) []streams.AuthMethodInfo { + return nil +} +func (m *mockAgentManager) IsPassthroughSession(ctx context.Context, sessionID string) bool { + return false +} +func (m *mockAgentManager) WritePassthroughStdin(_ context.Context, _ string, _ string) error { + return nil +} +func (m *mockAgentManager) MarkPassthroughRunning(_ string) error { + return nil +} + +func (m *mockAgentManager) GetRemoteRuntimeStatusBySession(ctx context.Context, sessionID string) (*RemoteRuntimeStatus, error) { + return nil, nil +} +func (m *mockAgentManager) PollRemoteStatusForRecords(ctx context.Context, records []RemoteStatusPollRequest) { +} +func (m *mockAgentManager) CleanupStaleExecutionBySessionID(ctx context.Context, sessionID string) error { + return nil +} +func (m *mockAgentManager) EnsureWorkspaceExecutionForSession(ctx context.Context, taskID, sessionID string) error { + return nil +} +func (m *mockAgentManager) GetExecutionIDForSession(ctx context.Context, sessionID string) (string, error) { + if m.getExecutionIDForSessionFunc != nil { + return m.getExecutionIDForSessionFunc(ctx, sessionID) + } + return "", fmt.Errorf("no execution found for session %s", sessionID) +} + +func (m *mockAgentManager) ResolveAgentProfile(ctx context.Context, profileID string) (*AgentProfileInfo, error) { + if m.resolveAgentProfileFunc != nil { + return m.resolveAgentProfileFunc(ctx, profileID) + } + return &AgentProfileInfo{ + ProfileID: profileID, + ProfileName: "Test Profile", + AgentID: "agent-123", + AgentName: "Test Agent", + Model: "claude-3-opus", + }, nil +} + +func (m *mockAgentManager) GetGitLog(ctx context.Context, sessionID, baseCommit string, limit int) (*client.GitLogResult, error) { + return nil, nil +} + +func (m *mockAgentManager) GetCumulativeDiff(ctx context.Context, sessionID, baseCommit string) (*client.CumulativeDiffResult, error) { + return nil, nil +} + +func (m *mockAgentManager) GetGitStatus(ctx context.Context, sessionID string) (*client.GitStatusResult, error) { + // Return a mock git status with a head commit for base commit capture + return &client.GitStatusResult{ + Success: true, + Branch: "main", + HeadCommit: "abc123def456", + }, nil +} + +func (m *mockAgentManager) WaitForAgentctlReady(ctx context.Context, sessionID string) error { + // Mock returns immediately + return nil +} + +// mockRepository implements executorStore for testing +type mockRepository struct { + mu sync.Mutex + sessions map[string]*models.TaskSession + tasks map[string]*models.Task + taskRepositories map[string]*models.TaskRepository + repositories map[string]*models.Repository + executors map[string]*models.Executor + executorsRunning map[string]*models.ExecutorRunning + + // Track calls for verification + createTaskSessionCalls []*models.TaskSession + updateTaskSessionCalls []*models.TaskSession + setSessionPrimaryCalls []string +} + +func newMockRepository() *mockRepository { + return &mockRepository{ + sessions: make(map[string]*models.TaskSession), + tasks: make(map[string]*models.Task), + taskRepositories: make(map[string]*models.TaskRepository), + repositories: make(map[string]*models.Repository), + executors: make(map[string]*models.Executor), + executorsRunning: make(map[string]*models.ExecutorRunning), + } +} + +// Implement required repository methods + +func (m *mockRepository) GetPrimaryTaskRepository(ctx context.Context, taskID string) (*models.TaskRepository, error) { + // Return first matching repository for the task (matches sqlite implementation) + for _, tr := range m.taskRepositories { + if tr.TaskID == taskID { + return tr, nil + } + } + return nil, nil +} + +func (m *mockRepository) GetRepository(ctx context.Context, id string) (*models.Repository, error) { + if repo, ok := m.repositories[id]; ok { + return repo, nil + } + return nil, nil +} + +func (m *mockRepository) CreateTaskSession(ctx context.Context, session *models.TaskSession) error { + m.mu.Lock() + defer m.mu.Unlock() + m.createTaskSessionCalls = append(m.createTaskSessionCalls, session) + m.sessions[session.ID] = session + return nil +} + +func (m *mockRepository) GetTaskSession(ctx context.Context, id string) (*models.TaskSession, error) { + m.mu.Lock() + defer m.mu.Unlock() + if session, ok := m.sessions[id]; ok { + return session, nil + } + return nil, nil +} + +func (m *mockRepository) UpdateTaskSession(ctx context.Context, session *models.TaskSession) error { + m.mu.Lock() + defer m.mu.Unlock() + m.updateTaskSessionCalls = append(m.updateTaskSessionCalls, session) + m.sessions[session.ID] = session + return nil +} + +func (m *mockRepository) SetSessionPrimary(ctx context.Context, sessionID string) error { + m.mu.Lock() + defer m.mu.Unlock() + m.setSessionPrimaryCalls = append(m.setSessionPrimaryCalls, sessionID) + return nil +} + +func (m *mockRepository) UpdateTaskSessionState(ctx context.Context, sessionID string, state models.TaskSessionState, errorMessage string) error { + m.mu.Lock() + defer m.mu.Unlock() + if session, ok := m.sessions[sessionID]; ok { + session.State = state + session.ErrorMessage = errorMessage + } + return nil +} + +func (m *mockRepository) UpdateTaskSessionBaseCommit(ctx context.Context, sessionID string, baseCommitSHA string) error { + m.mu.Lock() + defer m.mu.Unlock() + if session, ok := m.sessions[sessionID]; ok { + session.BaseCommitSHA = baseCommitSHA + } + return nil +} + +func (m *mockRepository) GetExecutor(ctx context.Context, id string) (*models.Executor, error) { + if exec, ok := m.executors[id]; ok { + return exec, nil + } + return nil, nil +} + +func (m *mockRepository) UpsertExecutorRunning(ctx context.Context, running *models.ExecutorRunning) error { + return nil +} + +func (m *mockRepository) CreateTaskSessionWorktree(ctx context.Context, worktree *models.TaskSessionWorktree) error { + return nil +} + +func (m *mockRepository) UpdateTaskState(ctx context.Context, taskID string, state v1.TaskState) error { + return nil +} +func (m *mockRepository) ArchiveTask(ctx context.Context, id string) error { return nil } +func (m *mockRepository) ListTasksForAutoArchive(ctx context.Context) ([]*models.Task, error) { + return nil, nil +} + +func (m *mockRepository) GetWorkspace(ctx context.Context, id string) (*models.Workspace, error) { + return nil, nil +} + +// Stub implementations for additional repository methods + +// Workspace operations +func (m *mockRepository) CreateWorkspace(ctx context.Context, workspace *models.Workspace) error { + return nil +} +func (m *mockRepository) UpdateWorkspace(ctx context.Context, workspace *models.Workspace) error { + return nil +} +func (m *mockRepository) DeleteWorkspace(ctx context.Context, id string) error { return nil } +func (m *mockRepository) ListWorkspaces(ctx context.Context) ([]*models.Workspace, error) { + return nil, nil +} + +// Task operations +func (m *mockRepository) CreateTask(ctx context.Context, task *models.Task) error { return nil } +func (m *mockRepository) GetTask(ctx context.Context, id string) (*models.Task, error) { + if task, ok := m.tasks[id]; ok { + return task, nil + } + return nil, nil +} +func (m *mockRepository) UpdateTask(ctx context.Context, task *models.Task) error { return nil } +func (m *mockRepository) DeleteTask(ctx context.Context, id string) error { return nil } +func (m *mockRepository) ListTasks(ctx context.Context, workflowID string) ([]*models.Task, error) { + return nil, nil +} +func (m *mockRepository) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig bool) ([]*models.Task, int, error) { + return nil, 0, nil +} +func (m *mockRepository) ListTasksByWorkflowStep(ctx context.Context, workflowStepID string) ([]*models.Task, error) { + return nil, nil +} +func (m *mockRepository) AddTaskToWorkflow(ctx context.Context, taskID, workflowID, workflowStepID string, position int) error { + return nil +} +func (m *mockRepository) RemoveTaskFromWorkflow(ctx context.Context, taskID, workflowID string) error { + return nil +} + +// TaskRepository operations +func (m *mockRepository) CreateTaskRepository(ctx context.Context, taskRepo *models.TaskRepository) error { + return nil +} +func (m *mockRepository) GetTaskRepository(ctx context.Context, id string) (*models.TaskRepository, error) { + return nil, nil +} +func (m *mockRepository) ListTaskRepositories(ctx context.Context, taskID string) ([]*models.TaskRepository, error) { + return nil, nil +} +func (m *mockRepository) ListTaskRepositoriesByTaskIDs(_ context.Context, _ []string) (map[string][]*models.TaskRepository, error) { + return make(map[string][]*models.TaskRepository), nil +} +func (m *mockRepository) UpdateTaskRepository(ctx context.Context, taskRepo *models.TaskRepository) error { + return nil +} +func (m *mockRepository) DeleteTaskRepository(ctx context.Context, id string) error { return nil } +func (m *mockRepository) DeleteTaskRepositoriesByTask(ctx context.Context, taskID string) error { + return nil +} + +// Workflow operations +func (m *mockRepository) CreateWorkflow(ctx context.Context, workflow *models.Workflow) error { + return nil +} +func (m *mockRepository) GetWorkflow(ctx context.Context, id string) (*models.Workflow, error) { + return nil, nil +} +func (m *mockRepository) UpdateWorkflow(ctx context.Context, workflow *models.Workflow) error { + return nil +} +func (m *mockRepository) DeleteWorkflow(ctx context.Context, id string) error { return nil } +func (m *mockRepository) ListWorkflows(ctx context.Context, workspaceID string) ([]*models.Workflow, error) { + return nil, nil +} + +// Message operations +func (m *mockRepository) CreateMessage(ctx context.Context, message *models.Message) error { + return nil +} +func (m *mockRepository) GetMessage(ctx context.Context, id string) (*models.Message, error) { + return nil, nil +} +func (m *mockRepository) GetMessageByToolCallID(ctx context.Context, sessionID, toolCallID string) (*models.Message, error) { + return nil, nil +} +func (m *mockRepository) GetMessageByPendingID(ctx context.Context, sessionID, pendingID string) (*models.Message, error) { + return nil, nil +} +func (m *mockRepository) FindMessageByPendingID(ctx context.Context, pendingID string) (*models.Message, error) { + return nil, nil +} +func (m *mockRepository) UpdateMessage(ctx context.Context, message *models.Message) error { + return nil +} +func (m *mockRepository) ListMessages(ctx context.Context, sessionID string) ([]*models.Message, error) { + return nil, nil +} +func (m *mockRepository) ListMessagesPaginated(ctx context.Context, sessionID string, opts models.ListMessagesOptions) ([]*models.Message, bool, error) { + return nil, false, nil +} +func (m *mockRepository) DeleteMessage(ctx context.Context, id string) error { return nil } + +// Turn operations +func (m *mockRepository) CreateTurn(ctx context.Context, turn *models.Turn) error { return nil } +func (m *mockRepository) GetTurn(ctx context.Context, id string) (*models.Turn, error) { + return nil, nil +} +func (m *mockRepository) GetActiveTurnBySessionID(ctx context.Context, sessionID string) (*models.Turn, error) { + return nil, nil +} +func (m *mockRepository) UpdateTurn(ctx context.Context, turn *models.Turn) error { return nil } +func (m *mockRepository) CompleteTurn(ctx context.Context, id string) error { return nil } +func (m *mockRepository) CompletePendingToolCallsForTurn(ctx context.Context, turnID string) (int64, error) { + return 0, nil +} +func (m *mockRepository) ListTurnsBySession(ctx context.Context, sessionID string) ([]*models.Turn, error) { + return nil, nil +} + +// Task Session operations +func (m *mockRepository) GetTaskSessionByTaskID(ctx context.Context, taskID string) (*models.TaskSession, error) { + return nil, nil +} +func (m *mockRepository) GetActiveTaskSessionByTaskID(ctx context.Context, taskID string) (*models.TaskSession, error) { + return nil, nil +} +func (m *mockRepository) ClearSessionExecutionID(ctx context.Context, id string) error { return nil } +func (m *mockRepository) ListTaskSessions(ctx context.Context, taskID string) ([]*models.TaskSession, error) { + return nil, nil +} +func (m *mockRepository) ListActiveTaskSessions(ctx context.Context) ([]*models.TaskSession, error) { + return nil, nil +} +func (m *mockRepository) ListActiveTaskSessionsByTaskID(ctx context.Context, taskID string) ([]*models.TaskSession, error) { + return nil, nil +} +func (m *mockRepository) HasActiveTaskSessionsByAgentProfile(ctx context.Context, agentProfileID string) (bool, error) { + return false, nil +} +func (m *mockRepository) GetActiveTaskInfoByAgentProfile(ctx context.Context, agentProfileID string) ([]agentdto.ActiveTaskInfo, error) { + return nil, nil +} +func (m *mockRepository) HasActiveTaskSessionsByExecutor(ctx context.Context, executorID string) (bool, error) { + return false, nil +} +func (m *mockRepository) HasActiveTaskSessionsByEnvironment(ctx context.Context, environmentID string) (bool, error) { + return false, nil +} +func (m *mockRepository) HasActiveTaskSessionsByRepository(ctx context.Context, repositoryID string) (bool, error) { + return false, nil +} +func (m *mockRepository) DeleteEphemeralTasksByAgentProfile(ctx context.Context, agentProfileID string) (int64, error) { + return 0, nil +} +func (m *mockRepository) DeleteTaskSession(ctx context.Context, id string) error { return nil } + +// Workflow-related session operations +func (m *mockRepository) GetPrimarySessionByTaskID(ctx context.Context, taskID string) (*models.TaskSession, error) { + return nil, nil +} +func (m *mockRepository) GetPrimarySessionIDsByTaskIDs(ctx context.Context, taskIDs []string) (map[string]string, error) { + return nil, nil +} +func (m *mockRepository) GetSessionCountsByTaskIDs(ctx context.Context, taskIDs []string) (map[string]int, error) { + return nil, nil +} +func (m *mockRepository) GetPrimarySessionInfoByTaskIDs(ctx context.Context, taskIDs []string) (map[string]*models.TaskSession, error) { + return nil, nil +} +func (m *mockRepository) UpdateSessionWorkflowStep(ctx context.Context, sessionID string, stepID string) error { + return nil +} +func (m *mockRepository) UpdateSessionReviewStatus(ctx context.Context, sessionID string, status string) error { + return nil +} +func (m *mockRepository) UpdateSessionMetadata(ctx context.Context, sessionID string, metadata map[string]interface{}) error { + return nil +} + +// Task Session Worktree operations +func (m *mockRepository) ListTaskSessionWorktrees(ctx context.Context, sessionID string) ([]*models.TaskSessionWorktree, error) { + return nil, nil +} +func (m *mockRepository) ListWorktreesBySessionIDs(_ context.Context, _ []string) (map[string][]*models.TaskSessionWorktree, error) { + return make(map[string][]*models.TaskSessionWorktree), nil +} +func (m *mockRepository) DeleteTaskSessionWorktree(ctx context.Context, id string) error { return nil } +func (m *mockRepository) DeleteTaskSessionWorktreesBySession(ctx context.Context, sessionID string) error { + return nil +} + +// Git Snapshot operations +func (m *mockRepository) CreateGitSnapshot(ctx context.Context, snapshot *models.GitSnapshot) error { + return nil +} +func (m *mockRepository) GetLatestGitSnapshot(ctx context.Context, sessionID string) (*models.GitSnapshot, error) { + return nil, nil +} +func (m *mockRepository) GetFirstGitSnapshot(ctx context.Context, sessionID string) (*models.GitSnapshot, error) { + return nil, nil +} +func (m *mockRepository) GetGitSnapshotsBySession(ctx context.Context, sessionID string, limit int) ([]*models.GitSnapshot, error) { + return nil, nil +} + +// Session Commit operations +func (m *mockRepository) CreateSessionCommit(ctx context.Context, commit *models.SessionCommit) error { + return nil +} +func (m *mockRepository) GetSessionCommits(ctx context.Context, sessionID string) ([]*models.SessionCommit, error) { + return nil, nil +} +func (m *mockRepository) GetLatestSessionCommit(ctx context.Context, sessionID string) (*models.SessionCommit, error) { + return nil, nil +} +func (m *mockRepository) DeleteSessionCommit(ctx context.Context, id string) error { return nil } + +// Repository operations +func (m *mockRepository) CreateRepository(ctx context.Context, repository *models.Repository) error { + return nil +} +func (m *mockRepository) UpdateRepository(ctx context.Context, repository *models.Repository) error { + return nil +} +func (m *mockRepository) DeleteRepository(ctx context.Context, id string) error { return nil } +func (m *mockRepository) ListRepositories(ctx context.Context, workspaceID string) ([]*models.Repository, error) { + return nil, nil +} + +// Repository script operations +func (m *mockRepository) CreateRepositoryScript(ctx context.Context, script *models.RepositoryScript) error { + return nil +} +func (m *mockRepository) GetRepositoryScript(ctx context.Context, id string) (*models.RepositoryScript, error) { + return nil, nil +} +func (m *mockRepository) UpdateRepositoryScript(ctx context.Context, script *models.RepositoryScript) error { + return nil +} +func (m *mockRepository) DeleteRepositoryScript(ctx context.Context, id string) error { return nil } +func (m *mockRepository) ListRepositoryScripts(ctx context.Context, repositoryID string) ([]*models.RepositoryScript, error) { + return nil, nil +} +func (m *mockRepository) ListScriptsByRepositoryIDs(_ context.Context, _ []string) (map[string][]*models.RepositoryScript, error) { + return make(map[string][]*models.RepositoryScript), nil +} +func (m *mockRepository) GetRepositoryByProviderInfo(_ context.Context, _, _, _, _ string) (*models.Repository, error) { + return nil, nil +} + +// Executor operations +func (m *mockRepository) CreateExecutor(ctx context.Context, executor *models.Executor) error { + return nil +} +func (m *mockRepository) UpdateExecutor(ctx context.Context, executor *models.Executor) error { + return nil +} +func (m *mockRepository) DeleteExecutor(ctx context.Context, id string) error { return nil } +func (m *mockRepository) ListExecutors(ctx context.Context) ([]*models.Executor, error) { + return nil, nil +} + +// Executor running operations +func (m *mockRepository) ListExecutorsRunning(ctx context.Context) ([]*models.ExecutorRunning, error) { + return nil, nil +} +func (m *mockRepository) GetExecutorRunningBySessionID(ctx context.Context, sessionID string) (*models.ExecutorRunning, error) { + if running, ok := m.executorsRunning[sessionID]; ok { + return running, nil + } + return nil, nil +} +func (m *mockRepository) DeleteExecutorRunningBySessionID(ctx context.Context, sessionID string) error { + return nil +} + +// Environment operations +func (m *mockRepository) CreateEnvironment(ctx context.Context, environment *models.Environment) error { + return nil +} +func (m *mockRepository) GetEnvironment(ctx context.Context, id string) (*models.Environment, error) { + return nil, nil +} +func (m *mockRepository) UpdateEnvironment(ctx context.Context, environment *models.Environment) error { + return nil +} +func (m *mockRepository) DeleteEnvironment(ctx context.Context, id string) error { return nil } +func (m *mockRepository) ListEnvironments(ctx context.Context) ([]*models.Environment, error) { + return nil, nil +} + +// Task environment operations +func (m *mockRepository) GetTaskEnvironmentByTaskID(ctx context.Context, taskID string) (*models.TaskEnvironment, error) { + return nil, nil +} +func (m *mockRepository) CreateTaskEnvironment(ctx context.Context, env *models.TaskEnvironment) error { + return nil +} +func (m *mockRepository) UpdateTaskEnvironment(ctx context.Context, env *models.TaskEnvironment) error { + return nil +} + +// Task Plan operations +func (m *mockRepository) CreateTaskPlan(ctx context.Context, plan *models.TaskPlan) error { return nil } +func (m *mockRepository) GetTaskPlan(ctx context.Context, taskID string) (*models.TaskPlan, error) { + return nil, nil +} +func (m *mockRepository) UpdateTaskPlan(ctx context.Context, plan *models.TaskPlan) error { return nil } +func (m *mockRepository) DeleteTaskPlan(ctx context.Context, taskID string) error { return nil } + +// Session File Review operations +func (m *mockRepository) UpsertSessionFileReview(ctx context.Context, review *models.SessionFileReview) error { + return nil +} +func (m *mockRepository) GetSessionFileReviews(ctx context.Context, sessionID string) ([]*models.SessionFileReview, error) { + return nil, nil +} +func (m *mockRepository) DeleteSessionFileReviews(ctx context.Context, sessionID string) error { + return nil +} +func (m *mockRepository) CountTasksByWorkflow(ctx context.Context, workflowID string) (int, error) { + return 0, nil +} +func (m *mockRepository) CountTasksByWorkflowStep(ctx context.Context, stepID string) (int, error) { + return 0, nil +} + +// Executor profile operations +func (m *mockRepository) CreateExecutorProfile(ctx context.Context, profile *models.ExecutorProfile) error { + return nil +} +func (m *mockRepository) GetExecutorProfile(ctx context.Context, id string) (*models.ExecutorProfile, error) { + return nil, nil +} +func (m *mockRepository) UpdateExecutorProfile(ctx context.Context, profile *models.ExecutorProfile) error { + return nil +} +func (m *mockRepository) DeleteExecutorProfile(ctx context.Context, id string) error { return nil } +func (m *mockRepository) ListExecutorProfiles(ctx context.Context, executorID string) ([]*models.ExecutorProfile, error) { + return nil, nil +} +func (m *mockRepository) ListAllExecutorProfiles(ctx context.Context) ([]*models.ExecutorProfile, error) { + return nil, nil +} + +// Close operation +func (m *mockRepository) Close() error { return nil } + +// mockShellPrefs implements ShellPreferenceProvider +type mockShellPrefs struct{} + +func (m *mockShellPrefs) PreferredShell(ctx context.Context) (string, error) { + return "/bin/bash", nil +} + +// mockCapabilities implements ExecutorTypeCapabilities for testing. +type mockCapabilities struct{} + +func (m *mockCapabilities) RequiresCloneURL(executorType string) bool { + switch models.ExecutorType(executorType) { + case models.ExecutorTypeRemoteDocker, models.ExecutorTypeSprites: + return true + default: + return false + } +} + +func (m *mockCapabilities) ShouldApplyPreferredShell(executorType string) bool { + switch models.ExecutorType(executorType) { + case models.ExecutorTypeLocal, models.ExecutorTypeWorktree, models.ExecutorTypeMockRemote: + return true + default: + return false + } +} + +// Helper to create a test executor +func newTestExecutor(t *testing.T, agentManager AgentManagerClient, repo *mockRepository) *Executor { + t.Helper() + log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"}) + if err != nil { + t.Fatalf("failed to create logger: %v", err) + } + exec := NewExecutor(agentManager, repo, log, ExecutorConfig{ + ShellPrefs: &mockShellPrefs{}, + }) + exec.SetCapabilities(&mockCapabilities{}) + return exec +} diff --git a/apps/backend/internal/orchestrator/executor/executor_test.go b/apps/backend/internal/orchestrator/executor/executor_test.go index 34e33681c7..14082e9f18 100644 --- a/apps/backend/internal/orchestrator/executor/executor_test.go +++ b/apps/backend/internal/orchestrator/executor/executor_test.go @@ -3,647 +3,14 @@ package executor import ( "context" "fmt" - "sync" "sync/atomic" "testing" "time" - agentdto "github.com/kandev/kandev/internal/agent/dto" - "github.com/kandev/kandev/internal/agentctl/client" - "github.com/kandev/kandev/internal/agentctl/types/streams" - "github.com/kandev/kandev/internal/common/logger" "github.com/kandev/kandev/internal/task/models" v1 "github.com/kandev/kandev/pkg/api/v1" ) -// mockAgentManager implements AgentManagerClient for testing -type mockAgentManager struct { - launchAgentFunc func(ctx context.Context, req *LaunchAgentRequest) (*LaunchAgentResponse, error) - startAgentProcessFunc func(ctx context.Context, agentExecutionID string) error - stopAgentFunc func(ctx context.Context, agentExecutionID string, force bool) error - resolveAgentProfileFunc func(ctx context.Context, profileID string) (*AgentProfileInfo, error) - setExecutionDescriptionFunc func(ctx context.Context, agentExecutionID string, description string) error - getExecutionIDForSessionFunc func(ctx context.Context, sessionID string) (string, error) -} - -func (m *mockAgentManager) LaunchAgent(ctx context.Context, req *LaunchAgentRequest) (*LaunchAgentResponse, error) { - if m.launchAgentFunc != nil { - return m.launchAgentFunc(ctx, req) - } - return &LaunchAgentResponse{ - AgentExecutionID: "exec-123", - ContainerID: "container-123", - Status: v1.AgentStatusStarting, - }, nil -} - -func (m *mockAgentManager) SetExecutionDescription(ctx context.Context, agentExecutionID string, description string) error { - if m.setExecutionDescriptionFunc != nil { - return m.setExecutionDescriptionFunc(ctx, agentExecutionID, description) - } - return nil -} - -func (m *mockAgentManager) SetMcpMode(_ context.Context, _ string, _ string) error { - return nil -} - -func (m *mockAgentManager) StartAgentProcess(ctx context.Context, agentExecutionID string) error { - if m.startAgentProcessFunc != nil { - return m.startAgentProcessFunc(ctx, agentExecutionID) - } - return nil -} - -func (m *mockAgentManager) StopAgent(ctx context.Context, agentExecutionID string, force bool) error { - if m.stopAgentFunc != nil { - return m.stopAgentFunc(ctx, agentExecutionID, force) - } - return nil -} - -func (m *mockAgentManager) StopAgentWithReason(ctx context.Context, agentExecutionID string, reason string, force bool) error { - return m.StopAgent(ctx, agentExecutionID, force) -} - -func (m *mockAgentManager) PromptAgent(ctx context.Context, agentExecutionID string, prompt string, _ []v1.MessageAttachment) (*PromptResult, error) { - return nil, nil -} - -func (m *mockAgentManager) CancelAgent(ctx context.Context, sessionID string) error { - return nil -} - -func (m *mockAgentManager) RespondToPermissionBySessionID(ctx context.Context, sessionID, pendingID, optionID string, cancelled bool) error { - return nil -} - -func (m *mockAgentManager) RestartAgentProcess(ctx context.Context, agentExecutionID string) error { - return nil -} -func (m *mockAgentManager) ResetAgentContext(ctx context.Context, agentExecutionID string) error { - return nil -} - -func (m *mockAgentManager) SetSessionModelBySessionID(ctx context.Context, sessionID, modelID string) error { - return fmt.Errorf("not supported") -} - -func (m *mockAgentManager) IsAgentRunningForSession(ctx context.Context, sessionID string) bool { - return false -} - -func (m *mockAgentManager) WasSessionInitialized(_ string) bool { return false } -func (m *mockAgentManager) GetSessionAuthMethods(_ string) []streams.AuthMethodInfo { - return nil -} -func (m *mockAgentManager) IsPassthroughSession(ctx context.Context, sessionID string) bool { - return false -} -func (m *mockAgentManager) WritePassthroughStdin(_ context.Context, _ string, _ string) error { - return nil -} -func (m *mockAgentManager) MarkPassthroughRunning(_ string) error { - return nil -} - -func (m *mockAgentManager) GetRemoteRuntimeStatusBySession(ctx context.Context, sessionID string) (*RemoteRuntimeStatus, error) { - return nil, nil -} -func (m *mockAgentManager) PollRemoteStatusForRecords(ctx context.Context, records []RemoteStatusPollRequest) { -} -func (m *mockAgentManager) CleanupStaleExecutionBySessionID(ctx context.Context, sessionID string) error { - return nil -} -func (m *mockAgentManager) EnsureWorkspaceExecutionForSession(ctx context.Context, taskID, sessionID string) error { - return nil -} -func (m *mockAgentManager) GetExecutionIDForSession(ctx context.Context, sessionID string) (string, error) { - if m.getExecutionIDForSessionFunc != nil { - return m.getExecutionIDForSessionFunc(ctx, sessionID) - } - return "", fmt.Errorf("no execution found for session %s", sessionID) -} - -func (m *mockAgentManager) ResolveAgentProfile(ctx context.Context, profileID string) (*AgentProfileInfo, error) { - if m.resolveAgentProfileFunc != nil { - return m.resolveAgentProfileFunc(ctx, profileID) - } - return &AgentProfileInfo{ - ProfileID: profileID, - ProfileName: "Test Profile", - AgentID: "agent-123", - AgentName: "Test Agent", - Model: "claude-3-opus", - }, nil -} - -func (m *mockAgentManager) GetGitLog(ctx context.Context, sessionID, baseCommit string, limit int) (*client.GitLogResult, error) { - return nil, nil -} - -func (m *mockAgentManager) GetCumulativeDiff(ctx context.Context, sessionID, baseCommit string) (*client.CumulativeDiffResult, error) { - return nil, nil -} - -func (m *mockAgentManager) GetGitStatus(ctx context.Context, sessionID string) (*client.GitStatusResult, error) { - // Return a mock git status with a head commit for base commit capture - return &client.GitStatusResult{ - Success: true, - Branch: "main", - HeadCommit: "abc123def456", - }, nil -} - -func (m *mockAgentManager) WaitForAgentctlReady(ctx context.Context, sessionID string) error { - // Mock returns immediately - return nil -} - -// mockRepository implements executorStore for testing -type mockRepository struct { - mu sync.Mutex - sessions map[string]*models.TaskSession - taskRepositories map[string]*models.TaskRepository - repositories map[string]*models.Repository - executors map[string]*models.Executor - - // Track calls for verification - createTaskSessionCalls []*models.TaskSession - updateTaskSessionCalls []*models.TaskSession - setSessionPrimaryCalls []string -} - -func newMockRepository() *mockRepository { - return &mockRepository{ - sessions: make(map[string]*models.TaskSession), - taskRepositories: make(map[string]*models.TaskRepository), - repositories: make(map[string]*models.Repository), - executors: make(map[string]*models.Executor), - } -} - -// Implement required repository methods - -func (m *mockRepository) GetPrimaryTaskRepository(ctx context.Context, taskID string) (*models.TaskRepository, error) { - // Return first matching repository for the task (matches sqlite implementation) - for _, tr := range m.taskRepositories { - if tr.TaskID == taskID { - return tr, nil - } - } - return nil, nil -} - -func (m *mockRepository) GetRepository(ctx context.Context, id string) (*models.Repository, error) { - if repo, ok := m.repositories[id]; ok { - return repo, nil - } - return nil, nil -} - -func (m *mockRepository) CreateTaskSession(ctx context.Context, session *models.TaskSession) error { - m.mu.Lock() - defer m.mu.Unlock() - m.createTaskSessionCalls = append(m.createTaskSessionCalls, session) - m.sessions[session.ID] = session - return nil -} - -func (m *mockRepository) GetTaskSession(ctx context.Context, id string) (*models.TaskSession, error) { - m.mu.Lock() - defer m.mu.Unlock() - if session, ok := m.sessions[id]; ok { - return session, nil - } - return nil, nil -} - -func (m *mockRepository) UpdateTaskSession(ctx context.Context, session *models.TaskSession) error { - m.mu.Lock() - defer m.mu.Unlock() - m.updateTaskSessionCalls = append(m.updateTaskSessionCalls, session) - m.sessions[session.ID] = session - return nil -} - -func (m *mockRepository) SetSessionPrimary(ctx context.Context, sessionID string) error { - m.mu.Lock() - defer m.mu.Unlock() - m.setSessionPrimaryCalls = append(m.setSessionPrimaryCalls, sessionID) - return nil -} - -func (m *mockRepository) UpdateTaskSessionState(ctx context.Context, sessionID string, state models.TaskSessionState, errorMessage string) error { - m.mu.Lock() - defer m.mu.Unlock() - if session, ok := m.sessions[sessionID]; ok { - session.State = state - session.ErrorMessage = errorMessage - } - return nil -} - -func (m *mockRepository) UpdateTaskSessionBaseCommit(ctx context.Context, sessionID string, baseCommitSHA string) error { - m.mu.Lock() - defer m.mu.Unlock() - if session, ok := m.sessions[sessionID]; ok { - session.BaseCommitSHA = baseCommitSHA - } - return nil -} - -func (m *mockRepository) GetExecutor(ctx context.Context, id string) (*models.Executor, error) { - if exec, ok := m.executors[id]; ok { - return exec, nil - } - return nil, nil -} - -func (m *mockRepository) UpsertExecutorRunning(ctx context.Context, running *models.ExecutorRunning) error { - return nil -} - -func (m *mockRepository) CreateTaskSessionWorktree(ctx context.Context, worktree *models.TaskSessionWorktree) error { - return nil -} - -func (m *mockRepository) UpdateTaskState(ctx context.Context, taskID string, state v1.TaskState) error { - return nil -} -func (m *mockRepository) ArchiveTask(ctx context.Context, id string) error { return nil } -func (m *mockRepository) ListTasksForAutoArchive(ctx context.Context) ([]*models.Task, error) { - return nil, nil -} - -func (m *mockRepository) GetWorkspace(ctx context.Context, id string) (*models.Workspace, error) { - return nil, nil -} - -// Stub implementations for additional repository methods - -// Workspace operations -func (m *mockRepository) CreateWorkspace(ctx context.Context, workspace *models.Workspace) error { - return nil -} -func (m *mockRepository) UpdateWorkspace(ctx context.Context, workspace *models.Workspace) error { - return nil -} -func (m *mockRepository) DeleteWorkspace(ctx context.Context, id string) error { return nil } -func (m *mockRepository) ListWorkspaces(ctx context.Context) ([]*models.Workspace, error) { - return nil, nil -} - -// Task operations -func (m *mockRepository) CreateTask(ctx context.Context, task *models.Task) error { return nil } -func (m *mockRepository) GetTask(ctx context.Context, id string) (*models.Task, error) { - return nil, nil -} -func (m *mockRepository) UpdateTask(ctx context.Context, task *models.Task) error { return nil } -func (m *mockRepository) DeleteTask(ctx context.Context, id string) error { return nil } -func (m *mockRepository) ListTasks(ctx context.Context, workflowID string) ([]*models.Task, error) { - return nil, nil -} -func (m *mockRepository) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig bool) ([]*models.Task, int, error) { - return nil, 0, nil -} -func (m *mockRepository) ListTasksByWorkflowStep(ctx context.Context, workflowStepID string) ([]*models.Task, error) { - return nil, nil -} -func (m *mockRepository) AddTaskToWorkflow(ctx context.Context, taskID, workflowID, workflowStepID string, position int) error { - return nil -} -func (m *mockRepository) RemoveTaskFromWorkflow(ctx context.Context, taskID, workflowID string) error { - return nil -} - -// TaskRepository operations -func (m *mockRepository) CreateTaskRepository(ctx context.Context, taskRepo *models.TaskRepository) error { - return nil -} -func (m *mockRepository) GetTaskRepository(ctx context.Context, id string) (*models.TaskRepository, error) { - return nil, nil -} -func (m *mockRepository) ListTaskRepositories(ctx context.Context, taskID string) ([]*models.TaskRepository, error) { - return nil, nil -} -func (m *mockRepository) ListTaskRepositoriesByTaskIDs(_ context.Context, _ []string) (map[string][]*models.TaskRepository, error) { - return make(map[string][]*models.TaskRepository), nil -} -func (m *mockRepository) UpdateTaskRepository(ctx context.Context, taskRepo *models.TaskRepository) error { - return nil -} -func (m *mockRepository) DeleteTaskRepository(ctx context.Context, id string) error { return nil } -func (m *mockRepository) DeleteTaskRepositoriesByTask(ctx context.Context, taskID string) error { - return nil -} - -// Workflow operations -func (m *mockRepository) CreateWorkflow(ctx context.Context, workflow *models.Workflow) error { - return nil -} -func (m *mockRepository) GetWorkflow(ctx context.Context, id string) (*models.Workflow, error) { - return nil, nil -} -func (m *mockRepository) UpdateWorkflow(ctx context.Context, workflow *models.Workflow) error { - return nil -} -func (m *mockRepository) DeleteWorkflow(ctx context.Context, id string) error { return nil } -func (m *mockRepository) ListWorkflows(ctx context.Context, workspaceID string) ([]*models.Workflow, error) { - return nil, nil -} - -// Message operations -func (m *mockRepository) CreateMessage(ctx context.Context, message *models.Message) error { - return nil -} -func (m *mockRepository) GetMessage(ctx context.Context, id string) (*models.Message, error) { - return nil, nil -} -func (m *mockRepository) GetMessageByToolCallID(ctx context.Context, sessionID, toolCallID string) (*models.Message, error) { - return nil, nil -} -func (m *mockRepository) GetMessageByPendingID(ctx context.Context, sessionID, pendingID string) (*models.Message, error) { - return nil, nil -} -func (m *mockRepository) FindMessageByPendingID(ctx context.Context, pendingID string) (*models.Message, error) { - return nil, nil -} -func (m *mockRepository) UpdateMessage(ctx context.Context, message *models.Message) error { - return nil -} -func (m *mockRepository) ListMessages(ctx context.Context, sessionID string) ([]*models.Message, error) { - return nil, nil -} -func (m *mockRepository) ListMessagesPaginated(ctx context.Context, sessionID string, opts models.ListMessagesOptions) ([]*models.Message, bool, error) { - return nil, false, nil -} -func (m *mockRepository) DeleteMessage(ctx context.Context, id string) error { return nil } - -// Turn operations -func (m *mockRepository) CreateTurn(ctx context.Context, turn *models.Turn) error { return nil } -func (m *mockRepository) GetTurn(ctx context.Context, id string) (*models.Turn, error) { - return nil, nil -} -func (m *mockRepository) GetActiveTurnBySessionID(ctx context.Context, sessionID string) (*models.Turn, error) { - return nil, nil -} -func (m *mockRepository) UpdateTurn(ctx context.Context, turn *models.Turn) error { return nil } -func (m *mockRepository) CompleteTurn(ctx context.Context, id string) error { return nil } -func (m *mockRepository) CompletePendingToolCallsForTurn(ctx context.Context, turnID string) (int64, error) { - return 0, nil -} -func (m *mockRepository) ListTurnsBySession(ctx context.Context, sessionID string) ([]*models.Turn, error) { - return nil, nil -} - -// Task Session operations -func (m *mockRepository) GetTaskSessionByTaskID(ctx context.Context, taskID string) (*models.TaskSession, error) { - return nil, nil -} -func (m *mockRepository) GetActiveTaskSessionByTaskID(ctx context.Context, taskID string) (*models.TaskSession, error) { - return nil, nil -} -func (m *mockRepository) ClearSessionExecutionID(ctx context.Context, id string) error { return nil } -func (m *mockRepository) ListTaskSessions(ctx context.Context, taskID string) ([]*models.TaskSession, error) { - return nil, nil -} -func (m *mockRepository) ListActiveTaskSessions(ctx context.Context) ([]*models.TaskSession, error) { - return nil, nil -} -func (m *mockRepository) ListActiveTaskSessionsByTaskID(ctx context.Context, taskID string) ([]*models.TaskSession, error) { - return nil, nil -} -func (m *mockRepository) HasActiveTaskSessionsByAgentProfile(ctx context.Context, agentProfileID string) (bool, error) { - return false, nil -} -func (m *mockRepository) GetActiveTaskInfoByAgentProfile(ctx context.Context, agentProfileID string) ([]agentdto.ActiveTaskInfo, error) { - return nil, nil -} -func (m *mockRepository) HasActiveTaskSessionsByExecutor(ctx context.Context, executorID string) (bool, error) { - return false, nil -} -func (m *mockRepository) HasActiveTaskSessionsByEnvironment(ctx context.Context, environmentID string) (bool, error) { - return false, nil -} -func (m *mockRepository) HasActiveTaskSessionsByRepository(ctx context.Context, repositoryID string) (bool, error) { - return false, nil -} -func (m *mockRepository) DeleteEphemeralTasksByAgentProfile(ctx context.Context, agentProfileID string) (int64, error) { - return 0, nil -} -func (m *mockRepository) DeleteTaskSession(ctx context.Context, id string) error { return nil } - -// Workflow-related session operations -func (m *mockRepository) GetPrimarySessionByTaskID(ctx context.Context, taskID string) (*models.TaskSession, error) { - return nil, nil -} -func (m *mockRepository) GetPrimarySessionIDsByTaskIDs(ctx context.Context, taskIDs []string) (map[string]string, error) { - return nil, nil -} -func (m *mockRepository) GetSessionCountsByTaskIDs(ctx context.Context, taskIDs []string) (map[string]int, error) { - return nil, nil -} -func (m *mockRepository) GetPrimarySessionInfoByTaskIDs(ctx context.Context, taskIDs []string) (map[string]*models.TaskSession, error) { - return nil, nil -} -func (m *mockRepository) UpdateSessionWorkflowStep(ctx context.Context, sessionID string, stepID string) error { - return nil -} -func (m *mockRepository) UpdateSessionReviewStatus(ctx context.Context, sessionID string, status string) error { - return nil -} -func (m *mockRepository) UpdateSessionMetadata(ctx context.Context, sessionID string, metadata map[string]interface{}) error { - return nil -} - -// Task Session Worktree operations -func (m *mockRepository) ListTaskSessionWorktrees(ctx context.Context, sessionID string) ([]*models.TaskSessionWorktree, error) { - return nil, nil -} -func (m *mockRepository) ListWorktreesBySessionIDs(_ context.Context, _ []string) (map[string][]*models.TaskSessionWorktree, error) { - return make(map[string][]*models.TaskSessionWorktree), nil -} -func (m *mockRepository) DeleteTaskSessionWorktree(ctx context.Context, id string) error { return nil } -func (m *mockRepository) DeleteTaskSessionWorktreesBySession(ctx context.Context, sessionID string) error { - return nil -} - -// Git Snapshot operations -func (m *mockRepository) CreateGitSnapshot(ctx context.Context, snapshot *models.GitSnapshot) error { - return nil -} -func (m *mockRepository) GetLatestGitSnapshot(ctx context.Context, sessionID string) (*models.GitSnapshot, error) { - return nil, nil -} -func (m *mockRepository) GetFirstGitSnapshot(ctx context.Context, sessionID string) (*models.GitSnapshot, error) { - return nil, nil -} -func (m *mockRepository) GetGitSnapshotsBySession(ctx context.Context, sessionID string, limit int) ([]*models.GitSnapshot, error) { - return nil, nil -} - -// Session Commit operations -func (m *mockRepository) CreateSessionCommit(ctx context.Context, commit *models.SessionCommit) error { - return nil -} -func (m *mockRepository) GetSessionCommits(ctx context.Context, sessionID string) ([]*models.SessionCommit, error) { - return nil, nil -} -func (m *mockRepository) GetLatestSessionCommit(ctx context.Context, sessionID string) (*models.SessionCommit, error) { - return nil, nil -} -func (m *mockRepository) DeleteSessionCommit(ctx context.Context, id string) error { return nil } - -// Repository operations -func (m *mockRepository) CreateRepository(ctx context.Context, repository *models.Repository) error { - return nil -} -func (m *mockRepository) UpdateRepository(ctx context.Context, repository *models.Repository) error { - return nil -} -func (m *mockRepository) DeleteRepository(ctx context.Context, id string) error { return nil } -func (m *mockRepository) ListRepositories(ctx context.Context, workspaceID string) ([]*models.Repository, error) { - return nil, nil -} - -// Repository script operations -func (m *mockRepository) CreateRepositoryScript(ctx context.Context, script *models.RepositoryScript) error { - return nil -} -func (m *mockRepository) GetRepositoryScript(ctx context.Context, id string) (*models.RepositoryScript, error) { - return nil, nil -} -func (m *mockRepository) UpdateRepositoryScript(ctx context.Context, script *models.RepositoryScript) error { - return nil -} -func (m *mockRepository) DeleteRepositoryScript(ctx context.Context, id string) error { return nil } -func (m *mockRepository) ListRepositoryScripts(ctx context.Context, repositoryID string) ([]*models.RepositoryScript, error) { - return nil, nil -} -func (m *mockRepository) ListScriptsByRepositoryIDs(_ context.Context, _ []string) (map[string][]*models.RepositoryScript, error) { - return make(map[string][]*models.RepositoryScript), nil -} -func (m *mockRepository) GetRepositoryByProviderInfo(_ context.Context, _, _, _, _ string) (*models.Repository, error) { - return nil, nil -} - -// Executor operations -func (m *mockRepository) CreateExecutor(ctx context.Context, executor *models.Executor) error { - return nil -} -func (m *mockRepository) UpdateExecutor(ctx context.Context, executor *models.Executor) error { - return nil -} -func (m *mockRepository) DeleteExecutor(ctx context.Context, id string) error { return nil } -func (m *mockRepository) ListExecutors(ctx context.Context) ([]*models.Executor, error) { - return nil, nil -} - -// Executor running operations -func (m *mockRepository) ListExecutorsRunning(ctx context.Context) ([]*models.ExecutorRunning, error) { - return nil, nil -} -func (m *mockRepository) GetExecutorRunningBySessionID(ctx context.Context, sessionID string) (*models.ExecutorRunning, error) { - return nil, nil -} -func (m *mockRepository) DeleteExecutorRunningBySessionID(ctx context.Context, sessionID string) error { - return nil -} - -// Environment operations -func (m *mockRepository) CreateEnvironment(ctx context.Context, environment *models.Environment) error { - return nil -} -func (m *mockRepository) GetEnvironment(ctx context.Context, id string) (*models.Environment, error) { - return nil, nil -} -func (m *mockRepository) UpdateEnvironment(ctx context.Context, environment *models.Environment) error { - return nil -} -func (m *mockRepository) DeleteEnvironment(ctx context.Context, id string) error { return nil } -func (m *mockRepository) ListEnvironments(ctx context.Context) ([]*models.Environment, error) { - return nil, nil -} - -// Task environment operations -func (m *mockRepository) GetTaskEnvironmentByTaskID(ctx context.Context, taskID string) (*models.TaskEnvironment, error) { - return nil, nil -} -func (m *mockRepository) CreateTaskEnvironment(ctx context.Context, env *models.TaskEnvironment) error { - return nil -} -func (m *mockRepository) UpdateTaskEnvironment(ctx context.Context, env *models.TaskEnvironment) error { - return nil -} - -// Task Plan operations -func (m *mockRepository) CreateTaskPlan(ctx context.Context, plan *models.TaskPlan) error { return nil } -func (m *mockRepository) GetTaskPlan(ctx context.Context, taskID string) (*models.TaskPlan, error) { - return nil, nil -} -func (m *mockRepository) UpdateTaskPlan(ctx context.Context, plan *models.TaskPlan) error { return nil } -func (m *mockRepository) DeleteTaskPlan(ctx context.Context, taskID string) error { return nil } - -// Session File Review operations -func (m *mockRepository) UpsertSessionFileReview(ctx context.Context, review *models.SessionFileReview) error { - return nil -} -func (m *mockRepository) GetSessionFileReviews(ctx context.Context, sessionID string) ([]*models.SessionFileReview, error) { - return nil, nil -} -func (m *mockRepository) DeleteSessionFileReviews(ctx context.Context, sessionID string) error { - return nil -} -func (m *mockRepository) CountTasksByWorkflow(ctx context.Context, workflowID string) (int, error) { - return 0, nil -} -func (m *mockRepository) CountTasksByWorkflowStep(ctx context.Context, stepID string) (int, error) { - return 0, nil -} - -// Executor profile operations -func (m *mockRepository) CreateExecutorProfile(ctx context.Context, profile *models.ExecutorProfile) error { - return nil -} -func (m *mockRepository) GetExecutorProfile(ctx context.Context, id string) (*models.ExecutorProfile, error) { - return nil, nil -} -func (m *mockRepository) UpdateExecutorProfile(ctx context.Context, profile *models.ExecutorProfile) error { - return nil -} -func (m *mockRepository) DeleteExecutorProfile(ctx context.Context, id string) error { return nil } -func (m *mockRepository) ListExecutorProfiles(ctx context.Context, executorID string) ([]*models.ExecutorProfile, error) { - return nil, nil -} -func (m *mockRepository) ListAllExecutorProfiles(ctx context.Context) ([]*models.ExecutorProfile, error) { - return nil, nil -} - -// Close operation -func (m *mockRepository) Close() error { return nil } - -// mockShellPrefs implements ShellPreferenceProvider -type mockShellPrefs struct{} - -func (m *mockShellPrefs) PreferredShell(ctx context.Context) (string, error) { - return "/bin/bash", nil -} - -// Helper to create a test executor -func newTestExecutor(t *testing.T, agentManager AgentManagerClient, repo *mockRepository) *Executor { - t.Helper() - log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "json"}) - if err != nil { - t.Fatalf("failed to create logger: %v", err) - } - exec := NewExecutor(agentManager, repo, log, ExecutorConfig{ - ShellPrefs: &mockShellPrefs{}, - }) - exec.SetCapabilities(&mockCapabilities{}) - return exec -} - // Tests func TestPrepareSession_Success(t *testing.T) { @@ -1097,27 +464,6 @@ func TestShouldUseWorktree(t *testing.T) { } } -// mockCapabilities implements ExecutorTypeCapabilities for testing. -type mockCapabilities struct{} - -func (m *mockCapabilities) RequiresCloneURL(executorType string) bool { - switch models.ExecutorType(executorType) { - case models.ExecutorTypeRemoteDocker, models.ExecutorTypeSprites: - return true - default: - return false - } -} - -func (m *mockCapabilities) ShouldApplyPreferredShell(executorType string) bool { - switch models.ExecutorType(executorType) { - case models.ExecutorTypeLocal, models.ExecutorTypeWorktree, models.ExecutorTypeMockRemote: - return true - default: - return false - } -} - func TestApplyPreferredShellEnv(t *testing.T) { repo := newMockRepository() agentManager := &mockAgentManager{} @@ -1271,3 +617,49 @@ func TestRepositoryCloneURL(t *testing.T) { }) } } + +func TestPersistResumeState_SetsStartingState(t *testing.T) { + repo := newMockRepository() + agentManager := &mockAgentManager{} + executor := newTestExecutor(t, agentManager, repo) + now := time.Now().UTC() + completedAt := now.Add(-time.Hour) + + t.Run("sets STARTING when startAgent is true", func(t *testing.T) { + session := &models.TaskSession{ + ID: "session-1", + TaskID: "task-1", + State: models.TaskSessionStateWaitingForInput, + CompletedAt: &completedAt, + UpdatedAt: now, + } + repo.sessions[session.ID] = session + + resp := &LaunchAgentResponse{AgentExecutionID: "exec-1"} + executor.persistResumeState(context.Background(), "task-1", session, resp, true, executorConfig{}, nil) + + if session.State != models.TaskSessionStateStarting { + t.Errorf("expected state STARTING, got %s", session.State) + } + if session.CompletedAt != nil { + t.Error("expected CompletedAt to be nil") + } + }) + + t.Run("does not change state when startAgent is false", func(t *testing.T) { + session := &models.TaskSession{ + ID: "session-2", + TaskID: "task-1", + State: models.TaskSessionStateWaitingForInput, + UpdatedAt: now, + } + repo.sessions[session.ID] = session + + resp := &LaunchAgentResponse{AgentExecutionID: "exec-2"} + executor.persistResumeState(context.Background(), "task-1", session, resp, false, executorConfig{}, nil) + + if session.State != models.TaskSessionStateWaitingForInput { + t.Errorf("expected state WAITING_FOR_INPUT, got %s", session.State) + } + }) +} diff --git a/apps/web/components/task/task-switcher.tsx b/apps/web/components/task/task-switcher.tsx index d5cc754891..ac32246b8c 100644 --- a/apps/web/components/task/task-switcher.tsx +++ b/apps/web/components/task/task-switcher.tsx @@ -66,10 +66,21 @@ const REVIEW_STATES = new Set([ const IN_PROGRESS_STATES = new Set(["RUNNING"]); const BACKLOG_STATES = new Set(["CREATED", "STARTING"]); +const TASK_STATE_REVIEW = new Set(["REVIEW", "COMPLETED"]); +const TASK_STATE_IN_PROGRESS = new Set(["IN_PROGRESS"]); + function classifyTask( sessionState: TaskSessionState | undefined, + taskState?: TaskState, ): "review" | "in_progress" | "backlog" { if (!sessionState) return "backlog"; + // STARTING is transient (e.g., resume after backend restart). Use the + // task-level state so the sidebar position stays stable. + if (sessionState === "STARTING" && taskState) { + if (TASK_STATE_REVIEW.has(taskState)) return "review"; + if (TASK_STATE_IN_PROGRESS.has(taskState)) return "in_progress"; + return "backlog"; + } if (REVIEW_STATES.has(sessionState)) return "review"; if (IN_PROGRESS_STATES.has(sessionState)) return "in_progress"; if (BACKLOG_STATES.has(sessionState)) return "backlog"; @@ -189,7 +200,7 @@ export const TaskSwitcher = memo(function TaskSwitcher({ const backlog: TaskSwitcherItem[] = []; for (const task of tasks) { - const bucket = classifyTask(task.sessionState); + const bucket = classifyTask(task.sessionState, task.state); if (bucket === "review") review.push(task); else if (bucket === "in_progress") inProgress.push(task); else backlog.push(task); diff --git a/apps/web/e2e/tests/session/session-resume.spec.ts b/apps/web/e2e/tests/session/session-resume.spec.ts index 2ac0f2a6f6..2912e580b5 100644 --- a/apps/web/e2e/tests/session/session-resume.spec.ts +++ b/apps/web/e2e/tests/session/session-resume.spec.ts @@ -108,6 +108,76 @@ test.describe("Session resume (ACP mode)", () => { }); }); +// --------------------------------------------------------------------------- +// Tests — task status preservation during resume +// --------------------------------------------------------------------------- + +test.describe("Task status during resume", () => { + test.describe.configure({ retries: 1 }); + + test("task stays in Turn Finished section after backend restart and agent resume", async ({ + testPage, + apiClient, + seedData, + backend, + }) => { + test.setTimeout(120_000); + + // 1. Create task and start agent — after the turn completes the workflow + // advances it from "Running" to "Turn Finished". + await apiClient.createTaskWithAgent( + seedData.workspaceId, + "Status Stable Task", + seedData.agentProfileId, + { + description: "/e2e:simple-message", + workflow_id: seedData.workflowId, + workflow_step_id: seedData.startStepId, + repository_ids: [seedData.repositoryId], + }, + ); + + // 2. Navigate to the session and wait for the agent to finish its first turn + const session = await openTaskSession(testPage, "Status Stable Task"); + await expect(session.chat.getByText("simple mock response", { exact: false })).toBeVisible({ + timeout: 30_000, + }); + await expect(session.idleInput()).toBeVisible({ timeout: 15_000 }); + + // 3. Confirm the task moved to the "Turn Finished" section after the turn completed + await expect(session.taskInSection("Status Stable Task", "Turn Finished")).toBeVisible({ + timeout: 15_000, + }); + + // 4. Restart the backend + await backend.restart(); + + // 5. Reload the page so SSR fetches from the new backend instance + await testPage.reload(); + await session.waitForLoad(); + + // 6. Immediately after reload, the task must still be in "Turn Finished" — not + // regressed to "Backlog" or "Running" due to resume lifecycle. + await expect(session.taskInSection("Status Stable Task", "Turn Finished")).toBeVisible({ + timeout: 30_000, + }); + await expect(session.taskInSection("Status Stable Task", "Running")).not.toBeVisible({ + timeout: 5_000, + }); + await expect(session.taskInSection("Status Stable Task", "Backlog")).not.toBeVisible({ + timeout: 5_000, + }); + + // 7. Wait for auto-resume to complete (agent relaunches and becomes idle) + await expect(session.idleInput()).toBeVisible({ timeout: 60_000 }); + + // 8. After resume completes, the task must still be in "Turn Finished" + await expect(session.taskInSection("Status Stable Task", "Turn Finished")).toBeVisible({ + timeout: 15_000, + }); + }); +}); + // --------------------------------------------------------------------------- // Tests — TUI (passthrough) mode // ---------------------------------------------------------------------------