diff --git a/apps/backend/cmd/kandev/main.go b/apps/backend/cmd/kandev/main.go index f7bf9c5764..7d441236a4 100644 --- a/apps/backend/cmd/kandev/main.go +++ b/apps/backend/cmd/kandev/main.go @@ -10,6 +10,7 @@ import ( "net/http" "os" "os/signal" + "path/filepath" "syscall" "github.com/gin-gonic/gin" @@ -280,6 +281,13 @@ func startAgentInfrastructure( lifecycleMgr.SetWorkspaceInfoProvider(services.Task) log.Info("Workspace info provider configured for session recovery") + // Configure quick-chat workspace cleanup + if dataDir := cfg.ResolvedDataDir(); dataDir != "" { + quickChatDir := filepath.Join(dataDir, "quick-chat") + services.Task.SetQuickChatDir(quickChatDir) + log.Info("Quick-chat workspace cleanup configured", zap.String("quick_chat_dir", quickChatDir)) + } + // ============================================ // REPO CLONER // ============================================ diff --git a/apps/backend/internal/agent/lifecycle/manager.go b/apps/backend/internal/agent/lifecycle/manager.go index 9b9237af5c..ba4af5dbeb 100644 --- a/apps/backend/internal/agent/lifecycle/manager.go +++ b/apps/backend/internal/agent/lifecycle/manager.go @@ -38,6 +38,11 @@ type Manager struct { worktreeMgr *worktree.Manager mcpProvider McpConfigProvider logger *logger.Logger + // dataDir is the base data directory for Kandev (from config.ResolvedDataDir()). + // Used for: + // - Session history storage (SessionHistoryManager) + // - Ephemeral workspace creation (quick chat, tasks without repositories) + dataDir string // ExecutorRegistry manages multiple runtimes (Docker, Standalone, etc.) // Each task can select its runtime based on executor type. @@ -121,6 +126,7 @@ func NewManager( profileResolver: profileResolver, mcpProvider: mcpProvider, logger: componentLogger, + dataDir: dataDir, executionStore: executionStore, commandBuilder: commandBuilder, sessionManager: sessionManager, diff --git a/apps/backend/internal/agent/lifecycle/manager_launch.go b/apps/backend/internal/agent/lifecycle/manager_launch.go index 8d8977e9fb..268891e4f5 100644 --- a/apps/backend/internal/agent/lifecycle/manager_launch.go +++ b/apps/backend/internal/agent/lifecycle/manager_launch.go @@ -3,6 +3,10 @@ package lifecycle import ( "context" "fmt" + "os" + "os/exec" + "path/filepath" + "strings" "time" "github.com/google/uuid" @@ -104,8 +108,9 @@ func (m *Manager) buildAgentCommand(req *LaunchRequest, profileInfo *AgentProfil // launchResolveWorkspacePath resolves the effective workspace path for non-worktree executors. // For worktree executors, workspace resolution is handled by the WorktreePreparer. +// For tasks without repositories, creates a workspace directory in ~/.kandev/quick-chat/. // Returns workspacePath, mainRepoGitDir, worktreeID, worktreeBranch. -func (m *Manager) launchResolveWorkspacePath(_ context.Context, req *LaunchRequest) (workspacePath, mainRepoGitDir, worktreeID, worktreeBranch string) { +func (m *Manager) launchResolveWorkspacePath(ctx context.Context, req *LaunchRequest) (workspacePath, mainRepoGitDir, worktreeID, worktreeBranch string) { if req.UseWorktree { // Worktree executors: preparer handles worktree creation. // Return empty path; it will be populated from preparer results. @@ -115,6 +120,46 @@ func (m *Manager) launchResolveWorkspacePath(_ context.Context, req *LaunchReque if req.RepositoryPath != "" && workspacePath == "" { workspacePath = req.RepositoryPath } + // For tasks without repositories (e.g., quick chat), create a workspace in ~/.kandev/quick-chat/ + // These directories are cleaned up when the ephemeral task is deleted (see task service performTaskCleanup). + if workspacePath == "" && req.SessionID != "" && m.dataDir != "" { + quickChatDir := filepath.Join(m.dataDir, "quick-chat") + if err := os.MkdirAll(quickChatDir, 0755); err != nil { + m.logger.Warn("failed to create quick-chat directory, continuing without workspace", + zap.String("session_id", req.SessionID), + zap.String("quick_chat_dir", quickChatDir), + zap.Error(err)) + return "", "", "", "" + } + // Validate SessionID doesn't contain path separators (security: prevent path traversal) + if strings.ContainsAny(req.SessionID, `/\`) { + m.logger.Warn("session ID contains path separator, rejecting", + zap.String("session_id", req.SessionID)) + return "", "", "", "" + } + // Use session ID as directory name for easy cleanup + workspacePath = filepath.Join(quickChatDir, req.SessionID) + if err := os.MkdirAll(workspacePath, 0755); err != nil { + m.logger.Warn("failed to create session workspace, continuing without workspace", + zap.String("session_id", req.SessionID), + zap.String("workspace_path", workspacePath), + zap.Error(err)) + return "", "", "", "" + } + + // Initialize git repository in the workspace (if not already initialized) + if err := m.initGitRepo(ctx, workspacePath); err != nil { + m.logger.Warn("failed to initialize git repository in quick chat workspace", + zap.String("session_id", req.SessionID), + zap.String("workspace_path", workspacePath), + zap.Error(err)) + // Continue anyway - git is optional for quick chat + } + + m.logger.Info("created quick chat workspace", + zap.String("session_id", req.SessionID), + zap.String("workspace_path", workspacePath)) + } return } @@ -558,3 +603,55 @@ func (m *Manager) initializeAgentSession(ctx context.Context, execution *AgentEx m.finalizeBootMessage(execution, bootMsg, bootStopCh, execution.agentctl, containerStateExited) return nil } + +// initGitRepo initializes a git repository in the given directory. +// Creates an initial commit so the workspace has a clean git state. +// This function is idempotent - it skips initialization if .git already exists. +func (m *Manager) initGitRepo(ctx context.Context, workspacePath string) error { + // Check if git repository already exists (idempotent) + gitDir := filepath.Join(workspacePath, ".git") + if info, err := os.Stat(gitDir); err == nil { + if info.IsDir() { + return nil // Already initialized + } + } else if !os.IsNotExist(err) { + // Non-ENOENT error (permissions, I/O, etc.) - fail explicitly + return fmt.Errorf("failed to check for .git directory: %w", err) + } + + // Initialize git repository + cmd := exec.CommandContext(ctx, "git", "init") + cmd.Dir = workspacePath + if output, err := cmd.CombinedOutput(); err != nil { + return fmt.Errorf("git init failed: %w (output: %s)", err, string(output)) + } + + // Configure git user (required for initial commit) + configName := exec.CommandContext(ctx, "git", "config", "user.name", "Kandev Quick Chat") + configName.Dir = workspacePath + _ = configName.Run() // Ignore error - might already be configured globally + + configEmail := exec.CommandContext(ctx, "git", "config", "user.email", "quickchat@kandev.local") + configEmail.Dir = workspacePath + _ = configEmail.Run() // Ignore error - might already be configured globally + + // Create initial commit with empty .gitkeep file + gitkeepPath := filepath.Join(workspacePath, ".gitkeep") + if err := os.WriteFile(gitkeepPath, []byte(""), 0644); err != nil { + return fmt.Errorf("failed to create .gitkeep: %w", err) + } + + addCmd := exec.CommandContext(ctx, "git", "add", ".gitkeep") + addCmd.Dir = workspacePath + if output, err := addCmd.CombinedOutput(); err != nil { + return fmt.Errorf("git add failed: %w (output: %s)", err, string(output)) + } + + commitCmd := exec.CommandContext(ctx, "git", "commit", "-m", "Initial commit") + commitCmd.Dir = workspacePath + if output, err := commitCmd.CombinedOutput(); err != nil { + return fmt.Errorf("git commit failed: %w (output: %s)", err, string(output)) + } + + return nil +} diff --git a/apps/backend/internal/orchestrator/event_handlers.go b/apps/backend/internal/orchestrator/event_handlers.go index b9bca362b5..3d4ddc6934 100644 --- a/apps/backend/internal/orchestrator/event_handlers.go +++ b/apps/backend/internal/orchestrator/event_handlers.go @@ -32,6 +32,7 @@ func buildTaskEventPayload(task *models.Task) map[string]interface{} { "priority": task.Priority, "position": task.Position, "updated_at": task.UpdatedAt.Format(time.RFC3339Nano), + "is_ephemeral": task.IsEphemeral, } } diff --git a/apps/backend/internal/orchestrator/executor/executor_test.go b/apps/backend/internal/orchestrator/executor/executor_test.go index be02073574..e776ca9703 100644 --- a/apps/backend/internal/orchestrator/executor/executor_test.go +++ b/apps/backend/internal/orchestrator/executor/executor_test.go @@ -281,7 +281,7 @@ func (m *mockRepository) DeleteTask(ctx context.Context, id string) error 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 bool) ([]*models.Task, int, error) { +func (m *mockRepository) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral bool) ([]*models.Task, int, error) { return nil, 0, nil } func (m *mockRepository) ListTasksByWorkflowStep(ctx context.Context, workflowStepID string) ([]*models.Task, error) { diff --git a/apps/backend/internal/task/handlers/process_handlers_test.go b/apps/backend/internal/task/handlers/process_handlers_test.go index 86539ee028..b29380f935 100644 --- a/apps/backend/internal/task/handlers/process_handlers_test.go +++ b/apps/backend/internal/task/handlers/process_handlers_test.go @@ -60,7 +60,7 @@ func (m *mockRepository) DeleteTask(ctx context.Context, id string) error { 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 bool) ([]*models.Task, int, error) { +func (m *mockRepository) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral bool) ([]*models.Task, int, error) { return nil, 0, nil } func (m *mockRepository) ListTasksByWorkflowStep(ctx context.Context, workflowStepID string) ([]*models.Task, error) { diff --git a/apps/backend/internal/task/handlers/task_handlers.go b/apps/backend/internal/task/handlers/task_handlers.go index 1cb03fe97c..8781b49480 100644 --- a/apps/backend/internal/task/handlers/task_handlers.go +++ b/apps/backend/internal/task/handlers/task_handlers.go @@ -71,6 +71,9 @@ func (h *TaskHandlers) registerHTTP(router *gin.Engine) { // Session workflow review endpoints api.POST("/sessions/:id/approve", h.httpApproveSession) + + // Quick chat endpoint - creates ephemeral task with prepared session + api.POST("/workspaces/:id/quick-chat", h.httpStartQuickChat) } func (h *TaskHandlers) registerWS(dispatcher *ws.Dispatcher) { diff --git a/apps/backend/internal/task/handlers/task_http_handlers.go b/apps/backend/internal/task/handlers/task_http_handlers.go index 89fbd9c90e..f2732249b6 100644 --- a/apps/backend/internal/task/handlers/task_http_handlers.go +++ b/apps/backend/internal/task/handlers/task_http_handlers.go @@ -50,9 +50,11 @@ func (h *TaskHandlers) httpListTasksByWorkspace(c *gin.Context) { query := c.Query("query") includeArchived := c.Query("include_archived") == queryValueTrue + includeEphemeral := c.Query("include_ephemeral") == queryValueTrue + onlyEphemeral := c.Query("only_ephemeral") == queryValueTrue tasks, total, err := h.service.ListTasksByWorkspace( - c.Request.Context(), c.Param("id"), query, page, pageSize, includeArchived, + c.Request.Context(), c.Param("id"), query, page, pageSize, includeArchived, includeEphemeral, onlyEphemeral, ) if err != nil { handleNotFound(c, h.logger, err, "tasks not found") @@ -599,3 +601,163 @@ func (h *TaskHandlers) httpArchiveTask(c *gin.Context) { } c.JSON(http.StatusOK, dto.SuccessResponse{Success: true}) } + +// httpStartQuickChatRequest is the request body for starting a quick chat session. +type httpStartQuickChatRequest struct { + Title string `json:"title,omitempty"` + RepositoryID string `json:"repository_id,omitempty"` + AgentProfileID string `json:"agent_profile_id,omitempty"` + ExecutorID string `json:"executor_id,omitempty"` + Prompt string `json:"prompt,omitempty"` + LocalPath string `json:"local_path,omitempty"` + RepositoryName string `json:"repository_name,omitempty"` + DefaultBranch string `json:"default_branch,omitempty"` + BaseBranch string `json:"base_branch,omitempty"` + LaunchImmediately bool `json:"launch_immediately,omitempty"` +} + +// httpStartQuickChatResponse is returned when a quick chat session is created. +type httpStartQuickChatResponse struct { + TaskID string `json:"task_id"` + SessionID string `json:"session_id"` +} + +// quickChatParams holds resolved parameters for creating a quick chat session. +type quickChatParams struct { + workflowID string + agentProfileID string + executorID string + title string + repos []service.TaskRepositoryInput + metadata map[string]interface{} +} + +// buildQuickChatRepositories builds the repository input list from the request. +func (body *httpStartQuickChatRequest) buildRepositories() []service.TaskRepositoryInput { + if body.RepositoryID == "" && body.LocalPath == "" { + return nil + } + return []service.TaskRepositoryInput{{ + RepositoryID: body.RepositoryID, + LocalPath: body.LocalPath, + Name: body.RepositoryName, + DefaultBranch: body.DefaultBranch, + BaseBranch: body.BaseBranch, + }} +} + +// resolveQuickChatParams resolves agent/executor IDs and builds metadata. +func (body *httpStartQuickChatRequest) resolveParams( + workspace *models.Workspace, workflowID string, +) quickChatParams { + agentProfileID := body.AgentProfileID + if agentProfileID == "" && workspace.DefaultAgentProfileID != nil { + agentProfileID = *workspace.DefaultAgentProfileID + } + executorID := body.ExecutorID + if executorID == "" && workspace.DefaultExecutorID != nil { + executorID = *workspace.DefaultExecutorID + } + + metadata := make(map[string]interface{}) + if agentProfileID != "" { + metadata["agent_profile_id"] = agentProfileID + } + if executorID != "" { + metadata["executor_id"] = executorID + } + + title := body.Title + if title == "" { + title = "Quick Chat" + } + + return quickChatParams{ + workflowID: workflowID, + agentProfileID: agentProfileID, + executorID: executorID, + title: title, + repos: body.buildRepositories(), + metadata: metadata, + } +} + +// httpStartQuickChat creates an ephemeral task and prepares a session for quick chat. +func (h *TaskHandlers) httpStartQuickChat(c *gin.Context) { + workspaceID := c.Param("id") + var body httpStartQuickChatRequest + if err := c.ShouldBindJSON(&body); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "invalid payload"}) + return + } + + ctx := c.Request.Context() + + workspace, err := h.service.GetWorkspace(ctx, workspaceID) + if err != nil { + handleNotFound(c, h.logger, err, "workspace not found") + return + } + + workflows, err := h.service.ListWorkflows(ctx, workspaceID) + if err != nil { + h.logger.Error("failed to list workflows", zap.Error(err), zap.String("workspace_id", workspaceID)) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to list workflows"}) + return + } + if len(workflows) == 0 { + c.JSON(http.StatusBadRequest, gin.H{"error": "workspace has no workflows"}) + return + } + + params := body.resolveParams(workspace, workflows[0].ID) + if params.agentProfileID == "" { + h.logger.Error("no agent profile configured for quick chat", zap.String("workspace_id", workspaceID)) + c.JSON(http.StatusBadRequest, gin.H{"error": "workspace has no default agent profile configured"}) + return + } + + task, err := h.service.CreateTask(ctx, &service.CreateTaskRequest{ + WorkspaceID: workspaceID, + WorkflowID: params.workflowID, + Title: params.title, + Description: body.Prompt, + Repositories: params.repos, + IsEphemeral: true, + Metadata: params.metadata, + }) + if err != nil { + h.logger.Error("failed to create ephemeral task", zap.Error(err)) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create quick chat"}) + return + } + + resp, err := h.orchestrator.LaunchSession(ctx, &orchestrator.LaunchSessionRequest{ + TaskID: task.ID, + Intent: orchestrator.IntentPrepare, + AgentProfileID: params.agentProfileID, + ExecutorID: params.executorID, + LaunchWorkspace: true, + }) + if err != nil { + // Rollback: delete the ephemeral task to prevent orphans + if deleteErr := h.service.DeleteTask(ctx, task.ID); deleteErr != nil { + h.logger.Error("failed to rollback quick chat task", + zap.String("task_id", task.ID), + zap.Error(deleteErr)) + } + h.logger.Error("failed to prepare quick chat session", zap.Error(err), zap.String("task_id", task.ID)) + c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to prepare session"}) + return + } + + h.logger.Info("quick chat session created", + zap.String("task_id", task.ID), + zap.String("session_id", resp.SessionID), + zap.String("workspace_id", workspaceID)) + + c.JSON(http.StatusOK, httpStartQuickChatResponse{ + TaskID: task.ID, + SessionID: resp.SessionID, + }) +} diff --git a/apps/backend/internal/task/models/models.go b/apps/backend/internal/task/models/models.go index 66286dfc8f..cf04ef3719 100644 --- a/apps/backend/internal/task/models/models.go +++ b/apps/backend/internal/task/models/models.go @@ -29,6 +29,7 @@ type Task struct { Position int `json:"position"` // Order within workflow step Metadata map[string]interface{} `json:"metadata,omitempty"` Repositories []*TaskRepository `json:"repositories,omitempty"` + IsEphemeral bool `json:"is_ephemeral"` // Ephemeral tasks are not shown in kanban, used for quick chat ArchivedAt *time.Time `json:"archived_at,omitempty"` CreatedAt time.Time `json:"created_at"` UpdatedAt time.Time `json:"updated_at"` @@ -529,5 +530,6 @@ func (t *Task) ToAPI() *v1.Task { CreatedAt: t.CreatedAt, UpdatedAt: t.UpdatedAt, Metadata: t.Metadata, + IsEphemeral: t.IsEphemeral, } } diff --git a/apps/backend/internal/task/repository/archive_repository_test.go b/apps/backend/internal/task/repository/archive_repository_test.go index 28c069e04f..34b70d3004 100644 --- a/apps/backend/internal/task/repository/archive_repository_test.go +++ b/apps/backend/internal/task/repository/archive_repository_test.go @@ -114,7 +114,7 @@ func TestSQLiteRepository_ListTasksByWorkspace_IncludeArchived(t *testing.T) { _ = repo.ArchiveTask(ctx, "task-2") // Without includeArchived: should return only active task - tasks, total, err := repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 10, false) + tasks, total, err := repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 10, false, false, false) if err != nil { t.Fatalf("failed to list tasks: %v", err) } @@ -126,7 +126,7 @@ func TestSQLiteRepository_ListTasksByWorkspace_IncludeArchived(t *testing.T) { } // With includeArchived: should return both tasks - tasks, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 10, true) + tasks, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 10, true, false, false) if err != nil { t.Fatalf("failed to list tasks with archived: %v", err) } @@ -138,7 +138,7 @@ func TestSQLiteRepository_ListTasksByWorkspace_IncludeArchived(t *testing.T) { } // Search with includeArchived=false should filter archived - _, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "Task", 1, 10, false) + _, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "Task", 1, 10, false, false, false) if err != nil { t.Fatalf("failed to search tasks: %v", err) } @@ -147,7 +147,7 @@ func TestSQLiteRepository_ListTasksByWorkspace_IncludeArchived(t *testing.T) { } // Search with includeArchived=true should include archived - _, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "Task", 1, 10, true) + _, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "Task", 1, 10, true, false, false) if err != nil { t.Fatalf("failed to search tasks with archived: %v", err) } diff --git a/apps/backend/internal/task/repository/interface.go b/apps/backend/internal/task/repository/interface.go index 9c2f78b279..5a12617e24 100644 --- a/apps/backend/internal/task/repository/interface.go +++ b/apps/backend/internal/task/repository/interface.go @@ -24,7 +24,7 @@ type TaskRepository interface { UpdateTask(ctx context.Context, task *models.Task) error DeleteTask(ctx context.Context, id string) error ListTasks(ctx context.Context, workflowID string) ([]*models.Task, error) - ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived bool) ([]*models.Task, int, error) + ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral bool) ([]*models.Task, int, error) ListTasksByWorkflowStep(ctx context.Context, workflowStepID string) ([]*models.Task, error) ArchiveTask(ctx context.Context, id string) error ListTasksForAutoArchive(ctx context.Context) ([]*models.Task, error) diff --git a/apps/backend/internal/task/repository/sqlite/base.go b/apps/backend/internal/task/repository/sqlite/base.go index 528d039c39..7bcf8a8680 100644 --- a/apps/backend/internal/task/repository/sqlite/base.go +++ b/apps/backend/internal/task/repository/sqlite/base.go @@ -130,6 +130,8 @@ func (r *Repository) runMigrations() error { _, _ = r.db.Exec(`ALTER TABLE executors_running ADD COLUMN last_message_uuid TEXT DEFAULT ''`) // Add metadata column to executors_running (ignore error if already exists) _, _ = r.db.Exec(`ALTER TABLE executors_running ADD COLUMN metadata TEXT DEFAULT '{}'`) + // Add is_ephemeral column to tasks for quick chat (ignore error if already exists) + _, _ = r.db.Exec(`ALTER TABLE tasks ADD COLUMN is_ephemeral INTEGER NOT NULL DEFAULT 0`) // Add checkout_branch column to task_repositories (ignore error if already exists) _, _ = r.db.Exec(`ALTER TABLE task_repositories ADD COLUMN checkout_branch TEXT DEFAULT ''`) // Add base_commit_sha column to task_sessions for tracking session start commit (ignore error if already exists) diff --git a/apps/backend/internal/task/repository/sqlite/task.go b/apps/backend/internal/task/repository/sqlite/task.go index a6810cbd4f..609b0a9deb 100644 --- a/apps/backend/internal/task/repository/sqlite/task.go +++ b/apps/backend/internal/task/repository/sqlite/task.go @@ -35,9 +35,9 @@ func (r *Repository) CreateTask(ctx context.Context, task *models.Task) error { } _, err = tx.ExecContext(ctx, r.db.Rebind(` - INSERT INTO tasks (id, workspace_id, workflow_id, workflow_step_id, title, description, state, priority, position, metadata, created_at, updated_at) - VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) - `), task.ID, task.WorkspaceID, task.WorkflowID, task.WorkflowStepID, task.Title, task.Description, task.State, task.Priority, task.Position, string(metadata), task.CreatedAt, task.UpdatedAt) + INSERT INTO tasks (id, workspace_id, workflow_id, workflow_step_id, title, description, state, priority, position, metadata, is_ephemeral, created_at, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + `), task.ID, task.WorkspaceID, task.WorkflowID, task.WorkflowStepID, task.Title, task.Description, task.State, task.Priority, task.Position, string(metadata), task.IsEphemeral, task.CreatedAt, task.UpdatedAt) if err != nil { if rollbackErr := tx.Rollback(); rollbackErr != nil { return fmt.Errorf("failed to rollback task insert: %w", rollbackErr) @@ -54,9 +54,9 @@ func (r *Repository) GetTask(ctx context.Context, id string) (*models.Task, erro var metadata string var archivedAt sql.NullTime err := r.ro.QueryRowContext(ctx, r.ro.Rebind(` - SELECT id, workspace_id, workflow_id, workflow_step_id, title, description, state, priority, position, metadata, archived_at, created_at, updated_at + SELECT id, workspace_id, workflow_id, workflow_step_id, title, description, state, priority, position, metadata, is_ephemeral, archived_at, created_at, updated_at FROM tasks WHERE id = ? - `), id).Scan(&task.ID, &task.WorkspaceID, &task.WorkflowID, &task.WorkflowStepID, &task.Title, &task.Description, &task.State, &task.Priority, &task.Position, &metadata, &archivedAt, &task.CreatedAt, &task.UpdatedAt) + `), id).Scan(&task.ID, &task.WorkspaceID, &task.WorkflowID, &task.WorkflowStepID, &task.Title, &task.Description, &task.State, &task.Priority, &task.Position, &metadata, &task.IsEphemeral, &archivedAt, &task.CreatedAt, &task.UpdatedAt) if err == sql.ErrNoRows { return nil, fmt.Errorf("task not found: %s", id) @@ -121,14 +121,14 @@ func (r *Repository) DeleteTask(ctx context.Context, id string) error { return nil } -// ListTasks returns all non-archived tasks for a workflow +// ListTasks returns all non-archived, non-ephemeral tasks for a workflow func (r *Repository) ListTasks(ctx context.Context, workflowID string) ([]*models.Task, error) { ctx, span := tracing.Tracer("kandev-db").Start(ctx, "db.ListTasks") defer span.End() rows, err := r.ro.QueryContext(ctx, r.ro.Rebind(` - SELECT id, workspace_id, workflow_id, workflow_step_id, title, description, state, priority, position, metadata, archived_at, created_at, updated_at + SELECT id, workspace_id, workflow_id, workflow_step_id, title, description, state, priority, position, metadata, is_ephemeral, archived_at, created_at, updated_at FROM tasks - WHERE workflow_id = ? AND archived_at IS NULL + WHERE workflow_id = ? AND archived_at IS NULL AND is_ephemeral = 0 ORDER BY position `), workflowID) if err != nil { @@ -139,32 +139,32 @@ func (r *Repository) ListTasks(ctx context.Context, workflowID string) ([]*model return r.scanTasks(rows) } -// CountTasksByWorkflow returns the number of non-archived tasks in a workflow +// CountTasksByWorkflow returns the number of non-archived, non-ephemeral tasks in a workflow func (r *Repository) CountTasksByWorkflow(ctx context.Context, workflowID string) (int, error) { var count int - err := r.ro.QueryRowContext(ctx, r.ro.Rebind(`SELECT COUNT(*) FROM tasks WHERE workflow_id = ? AND archived_at IS NULL`), workflowID).Scan(&count) + err := r.ro.QueryRowContext(ctx, r.ro.Rebind(`SELECT COUNT(*) FROM tasks WHERE workflow_id = ? AND archived_at IS NULL AND is_ephemeral = 0`), workflowID).Scan(&count) if err != nil { return 0, err } return count, nil } -// CountTasksByWorkflowStep returns the number of non-archived tasks in a workflow step +// CountTasksByWorkflowStep returns the number of non-archived, non-ephemeral tasks in a workflow step func (r *Repository) CountTasksByWorkflowStep(ctx context.Context, stepID string) (int, error) { var count int - err := r.ro.QueryRowContext(ctx, r.ro.Rebind(`SELECT COUNT(*) FROM tasks WHERE workflow_step_id = ? AND archived_at IS NULL`), stepID).Scan(&count) + err := r.ro.QueryRowContext(ctx, r.ro.Rebind(`SELECT COUNT(*) FROM tasks WHERE workflow_step_id = ? AND archived_at IS NULL AND is_ephemeral = 0`), stepID).Scan(&count) if err != nil { return 0, err } return count, nil } -// ListTasksByWorkflowStep returns all non-archived tasks in a workflow step +// ListTasksByWorkflowStep returns all non-archived, non-ephemeral tasks in a workflow step func (r *Repository) ListTasksByWorkflowStep(ctx context.Context, workflowStepID string) ([]*models.Task, error) { rows, err := r.ro.QueryContext(ctx, r.ro.Rebind(` - SELECT id, workspace_id, workflow_id, workflow_step_id, title, description, state, priority, position, metadata, archived_at, created_at, updated_at + SELECT id, workspace_id, workflow_id, workflow_step_id, title, description, state, priority, position, metadata, is_ephemeral, archived_at, created_at, updated_at FROM tasks - WHERE workflow_step_id = ? AND archived_at IS NULL ORDER BY position + WHERE workflow_step_id = ? AND archived_at IS NULL AND is_ephemeral = 0 ORDER BY position `), workflowStepID) if err != nil { return nil, err @@ -177,7 +177,9 @@ func (r *Repository) ListTasksByWorkflowStep(ctx context.Context, workflowStepID // ListTasksByWorkspace returns paginated tasks for a workspace with total count // If query is non-empty, filters by task title, description, repository name, or repository path // If includeArchived is false, archived tasks are excluded -func (r *Repository) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived bool) ([]*models.Task, int, error) { +// If includeEphemeral is false, ephemeral tasks are excluded +// If onlyEphemeral is true, only ephemeral tasks are returned +func (r *Repository) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral bool) ([]*models.Task, int, error) { ctx, span := tracing.Tracer("kandev-db").Start(ctx, "db.ListTasksByWorkspace") defer span.End() // Calculate offset @@ -186,9 +188,19 @@ func (r *Repository) ListTasksByWorkspace(ctx context.Context, workspaceID strin offset = 0 } - archiveFilter := "" + // Build filter conditions + filter := "" + if onlyEphemeral { + // Only ephemeral tasks + filter += " AND is_ephemeral = 1" + } else if !includeEphemeral { + // Exclude ephemeral tasks + filter += " AND is_ephemeral = 0" + } + // If includeEphemeral is true and onlyEphemeral is false, include both + if !includeArchived { - archiveFilter = " AND archived_at IS NULL" + filter += " AND archived_at IS NULL" } var rows *sql.Rows @@ -196,9 +208,9 @@ func (r *Repository) ListTasksByWorkspace(ctx context.Context, workspaceID strin var err error if query == "" { - rows, total, err = r.queryAllTasks(ctx, workspaceID, archiveFilter, pageSize, offset) + rows, total, err = r.queryAllTasks(ctx, workspaceID, filter, pageSize, offset) } else { - rows, total, err = r.searchTasks(ctx, workspaceID, query, archiveFilter, pageSize, offset, includeArchived) + rows, total, err = r.searchTasks(ctx, workspaceID, query, filter, pageSize, offset, includeArchived, includeEphemeral, onlyEphemeral) } if err != nil { @@ -222,7 +234,7 @@ func (r *Repository) queryAllTasks(ctx context.Context, workspaceID, archiveFilt return nil, 0, err } rows, err := r.ro.QueryContext(ctx, r.ro.Rebind(` - SELECT id, workspace_id, workflow_id, workflow_step_id, title, description, state, priority, position, metadata, archived_at, created_at, updated_at + SELECT id, workspace_id, workflow_id, workflow_step_id, title, description, state, priority, position, metadata, is_ephemeral, archived_at, created_at, updated_at FROM tasks WHERE workspace_id = ?`+archiveFilter+` ORDER BY updated_at DESC @@ -232,13 +244,19 @@ func (r *Repository) queryAllTasks(ctx context.Context, workspaceID, archiveFilt } // searchTasks fetches tasks matching a search query for a workspace with pagination. -func (r *Repository) searchTasks(ctx context.Context, workspaceID, query, archiveFilter string, pageSize, offset int, includeArchived bool) (*sql.Rows, int, error) { +func (r *Repository) searchTasks(ctx context.Context, workspaceID, query, filter string, pageSize, offset int, includeArchived, includeEphemeral, onlyEphemeral bool) (*sql.Rows, int, error) { searchPattern := "%" + query + "%" like := dialect.Like(r.ro.DriverName()) + // Build task filter tFilter := "" + if onlyEphemeral { + tFilter += " AND t.is_ephemeral = 1" + } else if !includeEphemeral { + tFilter += " AND t.is_ephemeral = 0" + } if !includeArchived { - tFilter = " AND t.archived_at IS NULL" + tFilter += " AND t.archived_at IS NULL" } countQuery := fmt.Sprintf(` @@ -259,7 +277,7 @@ func (r *Repository) searchTasks(ctx context.Context, workspaceID, query, archiv } selectQuery := fmt.Sprintf(` - SELECT DISTINCT t.id, t.workspace_id, t.workflow_id, t.workflow_step_id, t.title, t.description, t.state, t.priority, t.position, t.metadata, t.archived_at, t.created_at, t.updated_at + SELECT DISTINCT t.id, t.workspace_id, t.workflow_id, t.workflow_step_id, t.title, t.description, t.state, t.priority, t.position, t.metadata, t.is_ephemeral, t.archived_at, t.created_at, t.updated_at FROM tasks t LEFT JOIN task_repositories tr ON t.id = tr.task_id LEFT JOIN repositories r ON tr.repository_id = r.id @@ -295,6 +313,7 @@ func (r *Repository) scanTasks(rows *sql.Rows) ([]*models.Task, error) { &task.Priority, &task.Position, &metadata, + &task.IsEphemeral, &archivedAt, &task.CreatedAt, &task.UpdatedAt, @@ -329,7 +348,7 @@ func (r *Repository) ArchiveTask(ctx context.Context, id string) error { func (r *Repository) ListTasksForAutoArchive(ctx context.Context) ([]*models.Task, error) { drv := r.ro.DriverName() query := fmt.Sprintf(` - SELECT t.id, t.workspace_id, t.workflow_id, t.workflow_step_id, t.title, t.description, t.state, t.priority, t.position, t.metadata, t.archived_at, t.created_at, t.updated_at + SELECT t.id, t.workspace_id, t.workflow_id, t.workflow_step_id, t.title, t.description, t.state, t.priority, t.position, t.metadata, t.is_ephemeral, t.archived_at, t.created_at, t.updated_at FROM tasks t JOIN workflow_steps ws ON ws.id = t.workflow_step_id WHERE ws.auto_archive_after_hours > 0 diff --git a/apps/backend/internal/task/repository/task_repository_test.go b/apps/backend/internal/task/repository/task_repository_test.go index eef00fe305..a218d28060 100644 --- a/apps/backend/internal/task/repository/task_repository_test.go +++ b/apps/backend/internal/task/repository/task_repository_test.go @@ -196,7 +196,7 @@ func TestSQLiteRepository_ListTasksByWorkspace(t *testing.T) { _ = repo.CreateTask(ctx, &models.Task{ID: "task-4", WorkspaceID: "ws-2", WorkflowID: "wf-456", WorkflowStepID: "step-2", Title: "Task Four"}) // Test basic listing without search - tasks, total, err := repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 10, false) + tasks, total, err := repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 10, false, false, false) if err != nil { t.Fatalf("failed to list tasks by workspace: %v", err) } @@ -208,7 +208,7 @@ func TestSQLiteRepository_ListTasksByWorkspace(t *testing.T) { } // Test pagination - tasks, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 2, false) + tasks, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 2, false, false, false) if err != nil { t.Fatalf("failed to list tasks with pagination: %v", err) } @@ -220,7 +220,7 @@ func TestSQLiteRepository_ListTasksByWorkspace(t *testing.T) { } // Test page 2 - tasksPage2, _, err := repo.ListTasksByWorkspace(ctx, "ws-1", "", 2, 2, false) + tasksPage2, _, err := repo.ListTasksByWorkspace(ctx, "ws-1", "", 2, 2, false, false, false) if err != nil { t.Fatalf("failed to list tasks page 2: %v", err) } @@ -250,7 +250,7 @@ func TestSQLiteRepository_ListTasksByWorkspaceWithSearch(t *testing.T) { _ = repo.CreateTaskRepository(ctx, &models.TaskRepository{ID: "tr-1", TaskID: "task-1", RepositoryID: "repo-1", BaseBranch: "main"}) // Test search by title - _, totalAuth, err := repo.ListTasksByWorkspace(ctx, "ws-1", "authentication", 1, 10, false) + _, totalAuth, err := repo.ListTasksByWorkspace(ctx, "ws-1", "authentication", 1, 10, false, false, false) if err != nil { t.Fatalf("failed to search tasks by title: %v", err) } @@ -259,7 +259,7 @@ func TestSQLiteRepository_ListTasksByWorkspaceWithSearch(t *testing.T) { } // Test search by description - tasksDarkMode, totalDarkMode, err := repo.ListTasksByWorkspace(ctx, "ws-1", "dark mode", 1, 10, false) + tasksDarkMode, totalDarkMode, err := repo.ListTasksByWorkspace(ctx, "ws-1", "dark mode", 1, 10, false, false, false) if err != nil { t.Fatalf("failed to search tasks by description: %v", err) } @@ -271,7 +271,7 @@ func TestSQLiteRepository_ListTasksByWorkspaceWithSearch(t *testing.T) { } // Test search by repository name - tasksRepo, totalRepo, err := repo.ListTasksByWorkspace(ctx, "ws-1", "MyProject", 1, 10, false) + tasksRepo, totalRepo, err := repo.ListTasksByWorkspace(ctx, "ws-1", "MyProject", 1, 10, false, false, false) if err != nil { t.Fatalf("failed to search tasks by repository name: %v", err) } @@ -283,7 +283,7 @@ func TestSQLiteRepository_ListTasksByWorkspaceWithSearch(t *testing.T) { } // Test search by repository local_path - _, totalPath, err := repo.ListTasksByWorkspace(ctx, "ws-1", "myproject", 1, 10, false) + _, totalPath, err := repo.ListTasksByWorkspace(ctx, "ws-1", "myproject", 1, 10, false, false, false) if err != nil { t.Fatalf("failed to search tasks by repository path: %v", err) } @@ -292,7 +292,7 @@ func TestSQLiteRepository_ListTasksByWorkspaceWithSearch(t *testing.T) { } // Test search with no results - tasksNone, totalNone, err := repo.ListTasksByWorkspace(ctx, "ws-1", "nonexistent", 1, 10, false) + tasksNone, totalNone, err := repo.ListTasksByWorkspace(ctx, "ws-1", "nonexistent", 1, 10, false, false, false) if err != nil { t.Fatalf("failed to search tasks with no results: %v", err) } diff --git a/apps/backend/internal/task/service/service.go b/apps/backend/internal/task/service/service.go index f065af6bd1..a17bb14437 100644 --- a/apps/backend/internal/task/service/service.go +++ b/apps/backend/internal/task/service/service.go @@ -132,6 +132,7 @@ type Service struct { workflowStepCreator WorkflowStepCreator workflowStepGetter WorkflowStepGetter startStepResolver StartStepResolver + quickChatDir string // Directory for quick-chat workspaces (e.g., ~/.kandev/quick-chat) } // NewService creates a new task service @@ -184,3 +185,9 @@ func (s *Service) SetWorkflowStepGetter(getter WorkflowStepGetter) { func (s *Service) SetStartStepResolver(resolver StartStepResolver) { s.startStepResolver = resolver } + +// SetQuickChatDir sets the directory for quick-chat workspaces. +// When set, ephemeral task cleanup will delete the session directory under this path. +func (s *Service) SetQuickChatDir(dir string) { + s.quickChatDir = dir +} diff --git a/apps/backend/internal/task/service/service_events.go b/apps/backend/internal/task/service/service_events.go index 1ae18e1cdb..abdbfeab6c 100644 --- a/apps/backend/internal/task/service/service_events.go +++ b/apps/backend/internal/task/service/service_events.go @@ -58,6 +58,9 @@ func (s *Service) publishTaskEvent(ctx context.Context, eventType string, task * data["archived_at"] = task.ArchivedAt.Format(time.RFC3339) } + // Always include is_ephemeral field so frontend filters work correctly + data["is_ephemeral"] = task.IsEphemeral + if len(task.Repositories) > 0 { data["repository_id"] = task.Repositories[0].RepositoryID } diff --git a/apps/backend/internal/task/service/service_requests.go b/apps/backend/internal/task/service/service_requests.go index 132daa9ec4..df0585cbdf 100644 --- a/apps/backend/internal/task/service/service_requests.go +++ b/apps/backend/internal/task/service/service_requests.go @@ -32,6 +32,7 @@ type CreateTaskRequest struct { Position int `json:"position"` Metadata map[string]interface{} `json:"metadata,omitempty"` PlanMode bool `json:"plan_mode,omitempty"` + IsEphemeral bool `json:"is_ephemeral,omitempty"` // Ephemeral tasks are hidden from kanban, used for quick chat } // UpdateTaskRequest contains the data for updating a task diff --git a/apps/backend/internal/task/service/service_tasks.go b/apps/backend/internal/task/service/service_tasks.go index 3a779bc709..7a6e16b552 100644 --- a/apps/backend/internal/task/service/service_tasks.go +++ b/apps/backend/internal/task/service/service_tasks.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "net/url" + "os" "path/filepath" "strings" "time" @@ -60,6 +61,7 @@ func (s *Service) CreateTask(ctx context.Context, req *CreateTaskRequest) (*mode Priority: req.Priority, Position: req.Position, Metadata: req.Metadata, + IsEphemeral: req.IsEphemeral, } if err := s.tasks.CreateTask(ctx, task); err != nil { @@ -407,8 +409,9 @@ func (s *Service) ArchiveTask(ctx context.Context, id string) error { zap.Duration("duration", time.Since(start))) // 6. Background: Stop agents and cleanup worktrees + // Note: isEphemeral=false for archive to preserve quick-chat directories if len(stopTargets) > 0 || s.worktreeCleanup != nil || len(sessions) > 0 { - s.runAsyncTaskCleanup(id, sessions, worktrees, stopTargets, + s.runAsyncTaskCleanup(id, sessions, worktrees, stopTargets, false, "task archived", "failed to stop session on task archive", "task archive cleanup completed") } @@ -465,8 +468,8 @@ func (s *Service) DeleteTask(ctx context.Context, id string) error { // 6. Return immediately - all remaining cleanup is async // 7. Background: Stop agents and cleanup worktrees - if len(stopTargets) > 0 || s.worktreeCleanup != nil || len(sessions) > 0 { - s.runAsyncTaskCleanup(id, sessions, worktrees, stopTargets, + if len(stopTargets) > 0 || s.worktreeCleanup != nil || len(sessions) > 0 || task.IsEphemeral { + s.runAsyncTaskCleanup(id, sessions, worktrees, stopTargets, task.IsEphemeral, "task deleted", "failed to stop session on task delete", "task cleanup completed") } @@ -504,6 +507,7 @@ func (s *Service) runAsyncTaskCleanup( sessions []*models.TaskSession, worktrees []*worktree.Worktree, stopTargets []taskStopTarget, + isEphemeral bool, stopReason, stopFailMsg, cleanupMsg string, ) { go func() { @@ -532,7 +536,7 @@ func (s *Service) runAsyncTaskCleanup( } } - cleanupErrors := s.performTaskCleanup(cleanupCtx, id, sessions, worktrees) + cleanupErrors := s.performTaskCleanup(cleanupCtx, id, sessions, worktrees, isEphemeral) if len(cleanupErrors) > 0 { s.logger.Warn(cleanupMsg+" with errors", @@ -572,7 +576,7 @@ func (s *Service) buildStopTargets(ctx context.Context, taskID string, activeSes } // performTaskCleanup handles post-deletion cleanup operations. -// Handles worktree cleanup and executor_running records. +// Handles worktree cleanup, executor_running records, and quick-chat workspace directories. // Agent stopping is handled separately in the DeleteTask background goroutine. // Returns a slice of errors encountered (empty if all succeeded). func (s *Service) performTaskCleanup( @@ -580,6 +584,7 @@ func (s *Service) performTaskCleanup( taskID string, sessions []*models.TaskSession, worktrees []*worktree.Worktree, + isEphemeral bool, ) []error { var errs []error @@ -609,6 +614,29 @@ func (s *Service) performTaskCleanup( } } + // Cleanup quick-chat workspace directories for ephemeral tasks + if isEphemeral && s.quickChatDir != "" { + for _, session := range sessions { + if session == nil || session.ID == "" { + continue + } + sessionDir := filepath.Join(s.quickChatDir, session.ID) + if err := os.RemoveAll(sessionDir); err != nil { + s.logger.Warn("failed to cleanup quick-chat workspace directory", + zap.String("task_id", taskID), + zap.String("session_id", session.ID), + zap.String("path", sessionDir), + zap.Error(err)) + errs = append(errs, fmt.Errorf("cleanup quick-chat dir %s: %w", session.ID, err)) + } else { + s.logger.Debug("cleaned up quick-chat workspace directory", + zap.String("task_id", taskID), + zap.String("session_id", session.ID), + zap.String("path", sessionDir)) + } + } + } + return errs } @@ -628,8 +656,8 @@ func (s *Service) ListTasks(ctx context.Context, workflowID string) ([]*models.T // ListTasksByWorkspace returns paginated tasks for a workspace with task repositories loaded. // If query is non-empty, filters by task title, description, repository name, or repository path. -func (s *Service) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived bool) ([]*models.Task, int, error) { - tasks, total, err := s.tasks.ListTasksByWorkspace(ctx, workspaceID, query, page, pageSize, includeArchived) +func (s *Service) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral bool) ([]*models.Task, int, error) { + tasks, total, err := s.tasks.ListTasksByWorkspace(ctx, workspaceID, query, page, pageSize, includeArchived, includeEphemeral, onlyEphemeral) if err != nil { return nil, 0, err } diff --git a/apps/backend/pkg/api/v1/task.go b/apps/backend/pkg/api/v1/task.go index fd9f9de101..663610f382 100644 --- a/apps/backend/pkg/api/v1/task.go +++ b/apps/backend/pkg/api/v1/task.go @@ -74,6 +74,7 @@ type Task struct { StartedAt *time.Time `json:"started_at,omitempty"` CompletedAt *time.Time `json:"completed_at,omitempty"` Metadata map[string]interface{} `json:"metadata,omitempty"` + IsEphemeral bool `json:"is_ephemeral"` // Ephemeral tasks are not shown in kanban, used for quick chat } // TaskRepositoryInput for creating/updating task repositories diff --git a/apps/web/app/layout.tsx b/apps/web/app/layout.tsx index 1b335e41da..b505b4e498 100644 --- a/apps/web/app/layout.tsx +++ b/apps/web/app/layout.tsx @@ -9,6 +9,7 @@ import { CommandRegistryProvider } from "@/lib/commands/command-registry"; import { CommandPanel } from "@/components/command-panel"; import { GlobalCommands } from "@/components/global-commands"; import { DiffWorkerPoolProvider } from "@/components/diff-worker-pool-provider"; +import { QuickChatProvider } from "@/components/quick-chat/quick-chat-provider"; import { SessionFailureToastBridge } from "@/components/session-failure-toast-bridge"; export const metadata: Metadata = { @@ -63,7 +64,7 @@ export default function RootLayout({ - {children} + {children} diff --git a/apps/web/app/page.tsx b/apps/web/app/page.tsx index f272854ba8..c9d307645d 100644 --- a/apps/web/app/page.tsx +++ b/apps/web/app/page.tsx @@ -7,6 +7,7 @@ import { listRepositories, listWorkspaces, listTaskSessionMessages, + listQuickChatSessions, } from "@/lib/api"; import { snapshotToState } from "@/lib/ssr/mapper"; import { mapUserSettingsResponse } from "@/lib/ssr/user-settings"; @@ -135,15 +136,25 @@ export default async function Page({ searchParams }: PageProps) { ); } - const [workflowList, repositoriesResponse] = await Promise.all([ + const [workflowList, repositoriesResponse, quickChatResponse] = await Promise.all([ listWorkflows(activeWorkspaceId, { cache: "no-store" }), listRepositories(activeWorkspaceId, undefined, { cache: "no-store" }).catch(() => ({ repositories: [], })), + listQuickChatSessions(activeWorkspaceId, { cache: "no-store" }).catch(() => ({ tasks: [] })), ]); const workflowId = resolveActiveId(workflowList.workflows, workflowIdParam, settingsWorkflowId); + // Map quick chat tasks to sessions + const quickChatSessions = quickChatResponse.tasks + .filter((t) => t.primary_session_id) // Only include tasks with active sessions + .map((t) => ({ + sessionId: t.primary_session_id!, + workspaceId: t.workspace_id, + name: t.title !== "Quick Chat" ? t.title : undefined, + })); + initialState = { ...initialState, userSettings: { @@ -163,6 +174,11 @@ export default async function Page({ searchParams }: PageProps) { loadingByWorkspaceId: { [activeWorkspaceId]: false }, loadedByWorkspaceId: { [activeWorkspaceId]: true }, }, + quickChat: { + isOpen: false, + sessions: quickChatSessions, + activeSessionId: null, + }, }; if (!workflowId) { diff --git a/apps/web/components/global-commands.tsx b/apps/web/components/global-commands.tsx index 4ec5bb7b01..31ff34230b 100644 --- a/apps/web/components/global-commands.tsx +++ b/apps/web/components/global-commands.tsx @@ -1,6 +1,6 @@ "use client"; -import { useMemo } from "react"; +import { useMemo, useCallback } from "react"; import { useRouter } from "next/navigation"; import { useTheme } from "next-themes"; import { @@ -17,6 +17,9 @@ import { IconMessageCircle, } from "@tabler/icons-react"; import { useRegisterCommands } from "@/hooks/use-register-commands"; +import { useKeyboardShortcut } from "@/hooks/use-keyboard-shortcut"; +import { useAppStore } from "@/components/state-provider"; +import { SHORTCUTS } from "@/lib/keyboard/constants"; import type { CommandItem } from "@/lib/commands/types"; type PushFn = ReturnType["push"]; @@ -116,13 +119,49 @@ function buildThemeCommand( export function GlobalCommands() { const router = useRouter(); const { resolvedTheme, setTheme } = useTheme(); + const activeWorkspaceId = useAppStore((s) => s.workspaces.activeId); + const quickChatSessions = useAppStore((s) => s.quickChat.sessions); + const openQuickChat = useAppStore((s) => s.openQuickChat); + + const handleOpenQuickChat = useCallback(() => { + if (!activeWorkspaceId) { + return; + } + + // If there's an existing session for this workspace, open it + const existingSession = quickChatSessions.find((s) => s.workspaceId === activeWorkspaceId); + if (existingSession) { + openQuickChat(existingSession.sessionId, activeWorkspaceId); + } else { + // Open modal without a session - will show agent picker + openQuickChat("", activeWorkspaceId); + } + }, [activeWorkspaceId, quickChatSessions, openQuickChat]); + + const quickChatCommand: CommandItem = useMemo( + () => ({ + id: "quick-chat", + label: "Quick Chat", + group: "Actions", + icon: , + keywords: ["quick", "chat", "ai", "agent"], + shortcut: SHORTCUTS.QUICK_CHAT, + action: handleOpenQuickChat, + }), + [handleOpenQuickChat], + ); const commands = useMemo( - () => [...buildNavigationCommands(router.push), buildThemeCommand(resolvedTheme, setTheme)], - [router.push, resolvedTheme, setTheme], + () => [ + ...buildNavigationCommands(router.push), + buildThemeCommand(resolvedTheme, setTheme), + quickChatCommand, + ], + [router.push, resolvedTheme, setTheme, quickChatCommand], ); useRegisterCommands(commands); + useKeyboardShortcut(SHORTCUTS.QUICK_CHAT, handleOpenQuickChat); return null; } diff --git a/apps/web/components/kanban/kanban-header.tsx b/apps/web/components/kanban/kanban-header.tsx index 654d9f589d..0dddc9e61a 100644 --- a/apps/web/components/kanban/kanban-header.tsx +++ b/apps/web/components/kanban/kanban-header.tsx @@ -13,6 +13,7 @@ import { IconMenu2, IconChartBar, IconTimeline, + IconMessageCircle, } from "@tabler/icons-react"; import { KanbanDisplayDropdown } from "../kanban-display-dropdown"; import { RefreshReviewsButton } from "../github/refresh-reviews-button"; @@ -20,6 +21,7 @@ import { ReleaseNotesButton } from "../release-notes/release-notes-button"; import { ReleaseNotesDialog } from "../release-notes/release-notes-dialog"; import { HealthIndicatorButton, HealthIssuesDialog } from "../system-health/health-indicator"; import { TaskSearchInput } from "./task-search-input"; +import { useQuickChatLauncher } from "@/hooks/use-quick-chat-launcher"; import { KanbanHeaderMobile } from "./kanban-header-mobile"; import { MobileMenuSheet } from "./mobile-menu-sheet"; import { linkToTasks } from "@/lib/links"; @@ -97,6 +99,7 @@ function getToggleValue(currentPage: string, kanbanViewMode: string | null): str function TabletHeader({ onCreateTask, + onOpenQuickChat, searchQuery, onSearchChange, isSearchLoading, @@ -109,6 +112,7 @@ function TabletHeader({ onOpenHealthDialog, }: { onCreateTask: () => void; + onOpenQuickChat: () => void; searchQuery: string; onSearchChange?: (query: string) => void; isSearchLoading: boolean; @@ -145,6 +149,19 @@ function TabletHeader({ Add task + + + + + Quick Chat + void; + onOpenQuickChat: () => void; searchQuery: string; onSearchChange?: (query: string) => void; isSearchLoading: boolean; @@ -214,6 +233,19 @@ function DesktopHeader({ Add task + + + + + Quick Chat + @@ -241,23 +273,13 @@ function DesktopHeader({ ); } -export function KanbanHeader({ - onCreateTask, - workspaceId, - currentPage = "kanban", - searchQuery = "", - onSearchChange, - isSearchLoading = false, -}: KanbanHeaderProps) { +function useHeaderViewChange( + currentPage: string, + workspaceId: string | undefined, + onViewModeChange: (mode: string) => void, +) { const router = useRouter(); - const { isMobile, isTablet } = useResponsiveBreakpoint(); - const isMenuOpen = useAppStore((state) => state.mobileKanban.isMenuOpen); - const setMenuOpen = useAppStore((state) => state.setMobileKanbanMenuOpen); - const { kanbanViewMode, onViewModeChange } = useKanbanDisplaySettings(); - const releaseNotes = useReleaseNotes(); - const healthIndicator = useSystemHealthIndicator(); - const toggleValue = getToggleValue(currentPage, kanbanViewMode); - const handleViewChange = (value: string) => { + return (value: string) => { if (value === "list") { if (currentPage !== "tasks") router.push(linkToTasks(workspaceId)); } else if (value === "kanban") { @@ -268,6 +290,26 @@ export function KanbanHeader({ onViewModeChange("graph2"); } }; +} + +export function KanbanHeader({ + onCreateTask, + workspaceId, + currentPage = "kanban", + searchQuery = "", + onSearchChange, + isSearchLoading = false, +}: KanbanHeaderProps) { + const { isMobile, isTablet } = useResponsiveBreakpoint(); + const isMenuOpen = useAppStore((state) => state.mobileKanban.isMenuOpen); + const setMenuOpen = useAppStore((state) => state.setMobileKanbanMenuOpen); + const { kanbanViewMode, onViewModeChange } = useKanbanDisplaySettings(); + const releaseNotes = useReleaseNotes(); + const healthIndicator = useSystemHealthIndicator(); + const toggleValue = getToggleValue(currentPage, kanbanViewMode); + const handleViewChange = useHeaderViewChange(currentPage, workspaceId, onViewModeChange); + const handleOpenQuickChat = useQuickChatLauncher(workspaceId); + const indicatorProps = { showReleaseNotesButton: releaseNotes.showTopbarButton, onOpenReleaseNotes: releaseNotes.openDialog, @@ -275,50 +317,54 @@ export function KanbanHeader({ onOpenHealthDialog: healthIndicator.openDialog, }; const sharedSearch = { searchQuery, onSearchChange, isSearchLoading }; - let header: React.ReactNode; - if (isMobile) { - header = ( - - ); - } else if (isTablet) { - header = ( - <> - - { + if (isMobile) { + return ( + - - ); - } else { - header = ( + ); + } + if (isTablet) { + return ( + <> + + + + ); + } + return ( ); - } + }; + return ( <> - {header} + {renderHeader()} {releaseNotes.hasNotes && ( (null); + const [clarificationKey, setClarificationKey] = useState(0); + + useSettingsData(true); + const panelState = useChatPanelState({ + sessionId, + onOpenFile: undefined, + onOpenFileAtLine: undefined, + }); + const { isSending, handleSubmit } = useSubmitHandler(panelState, undefined); + const { + resolvedSessionId, + session, + task, + taskId, + isWorking, + messagesLoading, + groupedItems, + allMessages, + permissionsByToolCallId, + childrenByParentToolCallId, + cancelQueue, + pendingClarification, + } = panelState; + const { handleCancelTurn } = useChatPanelHandlers(resolvedSessionId, cancelQueue, chatInputRef); + + const handleClarificationResolved = useCallback(() => setClarificationKey((k) => k + 1), []); + + return ( +
+
+ +
+ {pendingClarification && ( +
+ +
+ )} + +
+ ); +}); diff --git a/apps/web/components/quick-chat/quick-chat-delete-dialog.tsx b/apps/web/components/quick-chat/quick-chat-delete-dialog.tsx new file mode 100644 index 0000000000..a4f7ca6414 --- /dev/null +++ b/apps/web/components/quick-chat/quick-chat-delete-dialog.tsx @@ -0,0 +1,54 @@ +"use client"; + +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, +} from "@kandev/ui/alert-dialog"; + +type QuickChatDeleteDialogProps = { + sessionToDelete: string | null; + onOpenChange: (open: boolean) => void; + onConfirm: () => void; +}; + +export function QuickChatDeleteDialog({ + sessionToDelete, + onOpenChange, + onConfirm, +}: QuickChatDeleteDialogProps) { + return ( + + + + Delete Quick Chat? + +
+

This will permanently delete this quick chat session, including:

+
    +
  • All conversation history
  • +
  • The task and its data
  • +
  • The associated worktree
  • +
+

This action cannot be undone.

+
+
+
+ + Cancel + + Delete + + +
+
+ ); +} diff --git a/apps/web/components/quick-chat/quick-chat-dialog.tsx b/apps/web/components/quick-chat/quick-chat-dialog.tsx new file mode 100644 index 0000000000..d7cd1b0071 --- /dev/null +++ b/apps/web/components/quick-chat/quick-chat-dialog.tsx @@ -0,0 +1,169 @@ +"use client"; + +import { memo, useCallback, useState } from "react"; +import { Dialog, DialogContent, DialogTitle } from "@kandev/ui/dialog"; +import { Button } from "@kandev/ui/button"; +import { Label } from "@kandev/ui/label"; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select"; +import { IconX, IconRocket } from "@tabler/icons-react"; +import { useAppStore } from "@/components/state-provider"; +import { useToast } from "@/components/toast-provider"; +import { startQuickChat } from "@/lib/api/domains/workspace-api"; +import type { Repository } from "@/lib/types/http"; +import type { AgentProfileOption } from "@/lib/state/slices/settings/types"; + +type QuickChatPickerDialogProps = { + open: boolean; + onOpenChange: (open: boolean) => void; + workspaceId: string; +}; + +type FormState = { + selectedRepoId: string; + setSelectedRepoId: (id: string) => void; + selectedAgentId: string; + setSelectedAgentId: (id: string) => void; + repositories: Repository[]; + agentProfiles: AgentProfileOption[]; +}; + +const NONE_VALUE = "__none__"; + +function QuickChatFormBody({ state }: { state: FormState }) { + const { selectedRepoId, setSelectedRepoId, selectedAgentId, setSelectedAgentId } = state; + return ( +
+

+ Start a quick conversation with an agent without creating a formal task. +

+
+ + +
+
+ + +
+
+ ); +} + +/** Dialog to pick repository and agent for a new quick chat session */ +export const QuickChatPickerDialog = memo(function QuickChatPickerDialog({ + open, + onOpenChange, + workspaceId, +}: QuickChatPickerDialogProps) { + const { toast } = useToast(); + const openQuickChat = useAppStore((s) => s.openQuickChat); + const [isStarting, setIsStarting] = useState(false); + const [selectedRepoId, setSelectedRepoId] = useState(""); + const [selectedAgentId, setSelectedAgentId] = useState(""); + const repositories = useAppStore((s) => s.repositories.itemsByWorkspaceId?.[workspaceId] ?? []); + const agentProfiles = useAppStore((s) => s.agentProfiles.items ?? []); + + const handleStart = useCallback(async () => { + if (isStarting) return; + setIsStarting(true); + try { + const response = await startQuickChat(workspaceId, { + repository_id: selectedRepoId || undefined, + agent_profile_id: selectedAgentId || undefined, + }); + onOpenChange(false); + // Open the quick chat modal with the new session + openQuickChat(response.session_id, workspaceId); + } catch (error) { + toast({ + title: "Failed to start quick chat", + description: error instanceof Error ? error.message : "Unknown error", + variant: "error", + }); + } finally { + setIsStarting(false); + } + }, [ + workspaceId, + selectedRepoId, + selectedAgentId, + isStarting, + onOpenChange, + openQuickChat, + toast, + ]); + + const formState: FormState = { + selectedRepoId, + setSelectedRepoId, + selectedAgentId, + setSelectedAgentId, + repositories, + agentProfiles, + }; + + return ( + + + New Quick Chat +
+

New Quick Chat

+ +
+ +
+ + +
+
+
+ ); +}); + +/** Alias for backwards compatibility */ +export const QuickChatDialog = QuickChatPickerDialog; diff --git a/apps/web/components/quick-chat/quick-chat-modal.tsx b/apps/web/components/quick-chat/quick-chat-modal.tsx new file mode 100644 index 0000000000..f0073a1b4d --- /dev/null +++ b/apps/web/components/quick-chat/quick-chat-modal.tsx @@ -0,0 +1,161 @@ +"use client"; + +import { memo } from "react"; +import { Dialog, DialogContent, DialogTitle } from "@kandev/ui/dialog"; +import { Button } from "@kandev/ui/button"; +import { IconMessageCircle, IconPlus, IconX } from "@tabler/icons-react"; +import { useAppStore } from "@/components/state-provider"; +import { QuickChatContent } from "./quick-chat-content"; +import { QuickChatDeleteDialog } from "./quick-chat-delete-dialog"; +import { useQuickChatModal } from "./use-quick-chat-modal"; + +type QuickChatModalProps = { + workspaceId: string; +}; + +function QuickChatTabs({ + sessions, + activeSessionId, + onTabChange, + onTabClose, + onNewChat, +}: { + sessions: Array<{ sessionId: string; workspaceId: string; name?: string }>; + activeSessionId: string; + onTabChange: (sessionId: string) => void; + onTabClose: (sessionId: string) => void; + onNewChat: () => void; +}) { + if (sessions.length === 0) return null; + + return ( +
+
+ {sessions.map((s, index) => { + const isActive = s.sessionId === activeSessionId; + // Show "New Chat" for empty session IDs (agent picker tabs) + const tabName = s.sessionId === "" ? "New Chat" : s.name || `Chat ${index + 1}`; + return ( +
+ + +
+ ); + })} +
+ +
+ ); +} + +function AgentPickerView({ onSelectAgent }: { onSelectAgent: (agentId: string) => void }) { + const agentProfiles = useAppStore((s) => s.agentProfiles.items) ?? []; + + return ( +
+
+
+

Choose an agent to start chatting

+

+ Select an AI agent to begin your conversation +

+
+
+ {agentProfiles.map((profile) => ( + + ))} +
+
+
+ ); +} + +export const QuickChatModal = memo(function QuickChatModal({ workspaceId }: QuickChatModalProps) { + const { + isOpen, + sessions, + activeSessionId, + sessionToClose, + activeSessionNeedsAgent, + setActiveQuickChatSession, + setSessionToClose, + handleOpenChange, + handleNewChat, + handleSelectAgent, + handleCloseTab, + handleConfirmClose, + } = useQuickChatModal(workspaceId); + + return ( + <> + + + Quick Chat + + {activeSessionId && !activeSessionNeedsAgent && ( + + )} + {activeSessionNeedsAgent && } + + + + !open && setSessionToClose(null)} + onConfirm={handleConfirmClose} + /> + + ); +}); diff --git a/apps/web/components/quick-chat/quick-chat-provider.tsx b/apps/web/components/quick-chat/quick-chat-provider.tsx new file mode 100644 index 0000000000..643cae4355 --- /dev/null +++ b/apps/web/components/quick-chat/quick-chat-provider.tsx @@ -0,0 +1,55 @@ +"use client"; + +import { useSyncExternalStore } from "react"; +import { useAppStore } from "@/components/state-provider"; +import { useSettingsData } from "@/hooks/domains/settings/use-settings-data"; +import { QuickChatModal } from "./quick-chat-modal"; + +// SSR-safe client mount detection without useEffect setState +const emptySubscribe = () => () => {}; +const getClientSnapshot = () => true; +const getServerSnapshot = () => false; + +function useIsMounted() { + return useSyncExternalStore(emptySubscribe, getClientSnapshot, getServerSnapshot); +} + +function getWorkspaceId( + sessions: { workspaceId: string }[], + isOpen: boolean, + activeWorkspace: string | null, +): string | null { + if (sessions.length > 0) { + return sessions[0].workspaceId; + } + if (isOpen) { + return activeWorkspace; + } + return null; +} + +/** + * Global provider for Quick Chat functionality. + * Renders the modal that can be opened from anywhere in the app. + * Preloads agent profiles so they're available when quick chat is opened. + */ +export function QuickChatProvider({ children }: { children: React.ReactNode }) { + const quickChatSessions = useAppStore((s) => s.quickChat.sessions); + const isOpen = useAppStore((s) => s.quickChat.isOpen); + const activeWorkspace = useAppStore((s) => s.workspaces.activeId); + const mounted = useIsMounted(); + + // Preload agent profiles so they're available when quick chat is opened + useSettingsData(true); + + // Get workspace ID from first session, or use active workspace if modal is open + const workspaceId = getWorkspaceId(quickChatSessions, isOpen, activeWorkspace); + + return ( + <> + {children} + {/* Only render modal on client side and if we have a workspace */} + {mounted && workspaceId && } + + ); +} diff --git a/apps/web/components/quick-chat/use-quick-chat-modal.ts b/apps/web/components/quick-chat/use-quick-chat-modal.ts new file mode 100644 index 0000000000..a2088a4ddd --- /dev/null +++ b/apps/web/components/quick-chat/use-quick-chat-modal.ts @@ -0,0 +1,126 @@ +"use client"; + +import { useCallback, useState } from "react"; +import { useShallow } from "zustand/react/shallow"; +import { useAppStore } from "@/components/state-provider"; +import { useToast } from "@/components/toast-provider"; +import { startQuickChat } from "@/lib/api/domains/workspace-api"; + +async function deleteQuickChatTask(taskId: string) { + const { deleteTask } = await import("@/lib/api/domains/kanban-api"); + await deleteTask(taskId); +} + +function useQuickChatStore() { + return useAppStore( + useShallow((s) => ({ + isOpen: s.quickChat.isOpen, + sessions: s.quickChat.sessions, + activeSessionId: s.quickChat.activeSessionId, + closeQuickChat: s.closeQuickChat, + closeQuickChatSession: s.closeQuickChatSession, + setActiveQuickChatSession: s.setActiveQuickChatSession, + renameQuickChatSession: s.renameQuickChatSession, + openQuickChat: s.openQuickChat, + agentProfiles: s.agentProfiles.items ?? [], + taskSessions: s.taskSessions.items || {}, + })), + ); +} + +export function useQuickChatModal(workspaceId: string) { + const { toast } = useToast(); + const store = useQuickChatStore(); + const [isCreating, setIsCreating] = useState(false); + const [showAgentPicker, setShowAgentPicker] = useState(false); + const [sessionToClose, setSessionToClose] = useState(null); + + const handleOpenChange = useCallback( + (open: boolean) => { + if (!open) { + store.closeQuickChat(); + setShowAgentPicker(false); + } + }, + [store], + ); + + const handleNewChat = useCallback(() => { + store.openQuickChat("", workspaceId); + }, [store, workspaceId]); + + const handleSelectAgent = useCallback( + async (agentId: string) => { + if (isCreating) return; + setIsCreating(true); + try { + const agent = store.agentProfiles.find((p) => p.id === agentId); + const sessionCount = store.sessions.filter((s) => s.sessionId !== "").length + 1; + const initialName = `${agent?.label || "Agent"} - Chat ${sessionCount}`; + const response = await startQuickChat(workspaceId, { + agent_profile_id: agentId, + title: initialName, + }); + if (store.activeSessionId === "") store.closeQuickChatSession(""); + store.openQuickChat(response.session_id, workspaceId); + store.renameQuickChatSession(response.session_id, initialName); + setShowAgentPicker(false); + } catch (error) { + toast({ + title: "Failed to start quick chat", + description: error instanceof Error ? error.message : "Unknown error", + variant: "error", + }); + } finally { + setIsCreating(false); + } + }, + [workspaceId, isCreating, store, toast], + ); + + const handleCloseTab = useCallback( + (sessionId: string) => { + if (sessionId === "") { + store.closeQuickChatSession(sessionId); + return; + } + setSessionToClose(sessionId); + }, + [store], + ); + + const handleConfirmClose = useCallback(async () => { + if (!sessionToClose) return; + const sessionId = sessionToClose; + setSessionToClose(null); + const taskId = store.taskSessions[sessionId]?.task_id; + store.closeQuickChatSession(sessionId); + if (taskId) { + try { + await deleteQuickChatTask(taskId); + } catch (error) { + console.error("Failed to delete quick chat task:", error); + toast({ + title: "Failed to delete quick chat", + description: error instanceof Error ? error.message : "Unknown error", + variant: "error", + }); + } + } + }, [sessionToClose, store, toast]); + + return { + isOpen: store.isOpen, + sessions: store.sessions, + activeSessionId: store.activeSessionId, + sessionToClose, + activeSessionNeedsAgent: store.activeSessionId === "" || showAgentPicker, + setActiveQuickChatSession: store.setActiveQuickChatSession, + setSessionToClose, + handleOpenChange, + handleNewChat, + handleSelectAgent, + handleCloseTab, + handleConfirmClose, + }; +} diff --git a/apps/web/components/task/chat/chat-input-area.tsx b/apps/web/components/task/chat/chat-input-area.tsx index f3b3213617..89ef7eeed5 100644 --- a/apps/web/components/task/chat/chat-input-area.tsx +++ b/apps/web/components/task/chat/chat-input-area.tsx @@ -292,6 +292,19 @@ function PRMergedBanner({ taskId }: { taskId: string }) { ); } +function AgentModeIndicator({ sessionId }: { sessionId: string | null }) { + const agentMode = useAppStore((state) => + sessionId ? state.sessionMode.bySessionId[sessionId] : undefined, + ); + if (!agentMode || agentMode === "default") return null; + return ( +
+ + {agentMode} mode +
+ ); +} + type ChatInputAreaProps = { chatInputRef: React.RefObject; clarificationKey: number; @@ -307,6 +320,7 @@ type ChatInputAreaProps = { onRequestChangesTooltipDismiss?: () => void; panelState: ReturnType; isSending: boolean; + hideSessionsDropdown?: boolean; }; export function ChatInputArea({ @@ -319,6 +333,7 @@ export function ChatInputArea({ onRequestChangesTooltipDismiss, panelState, isSending, + hideSessionsDropdown, }: ChatInputAreaProps) { const { resolvedSessionId, @@ -349,10 +364,6 @@ export function ChatInputArea({ chatInputRef, ); - const agentMode = useAppStore((state) => - resolvedSessionId ? state.sessionMode.bySessionId[resolvedSessionId] : undefined, - ); - const hasClarification = !!panelState.pendingClarification; const placeholder = resolveInputPlaceholder( isAgentBusy, @@ -363,12 +374,7 @@ export function ChatInputArea({ ); return (
- {agentMode && agentMode !== "default" && ( -
- - {agentMode} mode -
- )} + {taskId && }
); diff --git a/apps/web/components/task/chat/chat-input-body.tsx b/apps/web/components/task/chat/chat-input-body.tsx index 2373df808a..12641ca95f 100644 --- a/apps/web/components/task/chat/chat-input-body.tsx +++ b/apps/web/components/task/chat/chat-input-body.tsx @@ -34,6 +34,7 @@ export type ChatInputEditorAreaProps = { handleAgentCommand: (command: string) => void; handleImagePaste: (files: File[]) => Promise; showRequestChangesTooltip: boolean; + hideSessionsDropdown?: boolean; isAgentBusy: boolean; onPlanModeChange: (enabled: boolean) => void; taskTitle?: string; @@ -49,73 +50,39 @@ export type ChatInputEditorAreaProps = { isEnhancingPrompt?: boolean; }; -export function ChatInputEditorArea({ - inputRef, - value, - handleChange, - handleSubmitWithReset, - inputPlaceholder, - isDisabled, - hasClarification, - planModeEnabled, - planModeAvailable, - mcpServers, - submitKey, - setIsInputFocused, - sessionId, - taskId, - onAddContextFile, - onToggleContextFile, - planContextEnabled, - handleAgentCommand, - handleImagePaste, - showRequestChangesTooltip, - isAgentBusy, - onPlanModeChange, - taskTitle, - taskDescription, - isSending, - onCancel, - contextCount, - contextPopoverOpen, - setContextPopoverOpen, - contextFiles, - onImplementPlan, - onEnhancePrompt, - isEnhancingPrompt, -}: ChatInputEditorAreaProps) { - // Block submit while enhancing prompt, but keep editor editable for programmatic updates - const wrappedSubmit = isEnhancingPrompt ? () => {} : handleSubmitWithReset; +export function ChatInputEditorArea({ inputRef, ...p }: ChatInputEditorAreaProps) { + const wrappedSubmit = p.isEnhancingPrompt ? () => {} : p.handleSubmitWithReset; + const inputDisabled = p.isDisabled || p.hasClarification; return (
- +
setIsInputFocused(true)} - onBlur={() => setIsInputFocused(false)} - sessionId={sessionId} - taskId={taskId} - onAddContextFile={onAddContextFile} - onToggleContextFile={onToggleContextFile} - planContextEnabled={planContextEnabled} - onAgentCommand={handleAgentCommand} - onImagePaste={handleImagePaste} - onPlanModeChange={onPlanModeChange} + placeholder={p.inputPlaceholder} + disabled={inputDisabled} + planModeEnabled={p.planModeEnabled} + submitKey={p.submitKey} + onFocus={() => p.setIsInputFocused(true)} + onBlur={() => p.setIsInputFocused(false)} + sessionId={p.sessionId} + taskId={p.taskId} + onAddContextFile={p.onAddContextFile} + onToggleContextFile={p.onToggleContextFile} + planContextEnabled={p.planContextEnabled} + onAgentCommand={p.handleAgentCommand} + onImagePaste={p.handleImagePaste} + onPlanModeChange={p.onPlanModeChange} />
@@ -124,29 +91,30 @@ export function ChatInputEditorArea({
); diff --git a/apps/web/components/task/chat/chat-input-container.tsx b/apps/web/components/task/chat/chat-input-container.tsx index 7270b22ed0..e318eebb0a 100644 --- a/apps/web/components/task/chat/chat-input-container.tsx +++ b/apps/web/components/task/chat/chat-input-container.tsx @@ -75,6 +75,7 @@ type ChatInputContainerProps = { onAddContextFile?: (file: ContextFile) => void; todoItems?: TodoItem[]; onImplementPlan?: () => void; + hideSessionsDropdown?: boolean; }; function FailedSessionBanner({ @@ -183,6 +184,7 @@ function buildEditorAreaProps( onImplementPlan: p.onImplementPlan, onEnhancePrompt: extras.onEnhancePrompt, isEnhancingPrompt: extras.isEnhancingPrompt, + hideSessionsDropdown: p.hideSessionsDropdown, }; } diff --git a/apps/web/components/task/chat/chat-input-toolbar.tsx b/apps/web/components/task/chat/chat-input-toolbar.tsx index b2791560c6..a9473366a7 100644 --- a/apps/web/components/task/chat/chat-input-toolbar.tsx +++ b/apps/web/components/task/chat/chat-input-toolbar.tsx @@ -62,6 +62,8 @@ export type ChatInputToolbarProps = { onEnhancePrompt?: () => void; /** Whether prompt enhancement is in progress */ isEnhancingPrompt?: boolean; + /** Hide the sessions dropdown (for quick chat) */ + hideSessionsDropdown?: boolean; }; type SubmitButtonProps = { @@ -302,6 +304,7 @@ type ToolbarRightSectionProps = { onEnhancePrompt?: () => void; isEnhancingPrompt?: boolean; onImplementPlan?: () => void; + hideSessionsDropdown?: boolean; }; function ToolbarRightSection({ @@ -319,6 +322,7 @@ function ToolbarRightSection({ onEnhancePrompt, isEnhancingPrompt, onImplementPlan, + hideSessionsDropdown, }: ToolbarRightSectionProps) { const showEnhance = onEnhancePrompt && !isAgentBusy; const showImplement = planModeEnabled && !isAgentBusy && onImplementPlan; @@ -326,12 +330,14 @@ function ToolbarRightSection({ return (
{showResetContext && } - + {!hideSessionsDropdown && ( + + )} {showEnhance && ( @@ -377,6 +383,7 @@ export const ChatInputToolbar = memo(function ChatInputToolbar({ onImplementPlan, onEnhancePrompt, isEnhancingPrompt = false, + hideSessionsDropdown, }: ChatInputToolbarProps) { const submitShortcut = submitKey === "enter" ? SHORTCUTS.SUBMIT_ENTER : SHORTCUTS.SUBMIT; @@ -433,6 +440,7 @@ export const ChatInputToolbar = memo(function ChatInputToolbar({ onEnhancePrompt={onEnhancePrompt} isEnhancingPrompt={isEnhancingPrompt} onImplementPlan={onImplementPlan} + hideSessionsDropdown={hideSessionsDropdown} />
); diff --git a/apps/web/components/task/quick-chat-button.tsx b/apps/web/components/task/quick-chat-button.tsx new file mode 100644 index 0000000000..e9c2eb07c0 --- /dev/null +++ b/apps/web/components/task/quick-chat-button.tsx @@ -0,0 +1,27 @@ +import { IconMessageCircle } from "@tabler/icons-react"; +import { Button } from "@kandev/ui/button"; +import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip"; +import { useQuickChatLauncher } from "@/hooks/use-quick-chat-launcher"; + +/** Quick Chat button that opens the quick chat modal */ +export function QuickChatButton({ workspaceId }: { workspaceId?: string | null }) { + const handleOpenQuickChat = useQuickChatLauncher(workspaceId); + + if (!workspaceId) return null; + + return ( + + + + + Quick Chat + + ); +} diff --git a/apps/web/components/task/task-page-content.tsx b/apps/web/components/task/task-page-content.tsx index 98aa3214e1..09f9580388 100644 --- a/apps/web/components/task/task-page-content.tsx +++ b/apps/web/components/task/task-page-content.tsx @@ -273,6 +273,7 @@ function buildTaskTopBarProps(params: { workflowSteps, currentStepId: resolveCurrentStepId(params.sessionWorkflowStepId, taskProps.workflowStepId), workflowId: taskProps.workflowId, + workspaceId: taskProps.workspaceId, isArchived: taskProps.isArchived, isRemoteExecutor: params.remote.isRemoteExecutor, isAgentctlReady: params.agentctlReady, diff --git a/apps/web/components/task/task-session-sidebar.tsx b/apps/web/components/task/task-session-sidebar.tsx index 66c4e5b670..58d5b76421 100644 --- a/apps/web/components/task/task-session-sidebar.tsx +++ b/apps/web/components/task/task-session-sidebar.tsx @@ -119,6 +119,7 @@ function useSidebarData(workspaceId: string | null) { for (const step of snapshot.steps) { if (!stepMap.has(step.id)) stepMap.set(step.id, step); } + // Ephemeral tasks are already filtered out by useAllWorkflowSnapshots tasks.push(...snapshot.tasks); } const sortedSteps = [...stepMap.values()].sort((a, b) => a.position - b.position); diff --git a/apps/web/components/task/task-top-bar.tsx b/apps/web/components/task/task-top-bar.tsx index 64cc59d513..1c275c0525 100644 --- a/apps/web/components/task/task-top-bar.tsx +++ b/apps/web/components/task/task-top-bar.tsx @@ -34,6 +34,7 @@ import { PRTopbarButton } from "@/components/github/pr-topbar-button"; import { PortForwardButton } from "@/components/task/port-forward-dialog"; import { WorkflowStepper, type WorkflowStepperStep } from "@/components/task/workflow-stepper"; import { RemoteCloudTooltip } from "@/components/task/remote-cloud-tooltip"; +import { QuickChatButton } from "@/components/task/quick-chat-button"; import { DEBUG_UI } from "@/lib/config"; import { toast } from "sonner"; @@ -55,6 +56,7 @@ type TaskTopBarProps = { workflowSteps?: WorkflowStepperStep[]; currentStepId?: string | null; workflowId?: string | null; + workspaceId?: string | null; isArchived?: boolean; isRemoteExecutor?: boolean; isAgentctlReady?: boolean; @@ -80,6 +82,7 @@ const TaskTopBar = memo(function TaskTopBar({ workflowSteps, currentStepId, workflowId, + workspaceId, isArchived, isRemoteExecutor, isAgentctlReady, @@ -144,6 +147,7 @@ const TaskTopBar = memo(function TaskTopBar({ showDebugOverlay={showDebugOverlay} onToggleDebugOverlay={onToggleDebugOverlay} isArchived={isArchived} + workspaceId={workspaceId} isRemoteExecutor={isRemoteExecutor} isAgentctlReady={isAgentctlReady} /> @@ -546,6 +550,7 @@ function TopBarRight({ showDebugOverlay, onToggleDebugOverlay, isArchived, + workspaceId, isRemoteExecutor, isAgentctlReady, }: { @@ -555,6 +560,7 @@ function TopBarRight({ showDebugOverlay?: boolean; onToggleDebugOverlay?: () => void; isArchived?: boolean; + workspaceId?: string | null; isRemoteExecutor?: boolean; isAgentctlReady?: boolean; }) { @@ -592,6 +598,7 @@ function TopBarRight({ )} +