feat: quick chat implementation (#393)
This commit is contained in:
@@ -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
|
||||
// ============================================
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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({
|
||||
<WebSocketConnector />
|
||||
<GlobalCommands />
|
||||
<CommandPanel />
|
||||
{children}
|
||||
<QuickChatProvider>{children}</QuickChatProvider>
|
||||
</CommandRegistryProvider>
|
||||
</ToastProvider>
|
||||
</TooltipProvider>
|
||||
|
||||
+17
-1
@@ -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) {
|
||||
|
||||
@@ -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<typeof useRouter>["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: <IconMessageCircle className="size-3.5" />,
|
||||
keywords: ["quick", "chat", "ai", "agent"],
|
||||
shortcut: SHORTCUTS.QUICK_CHAT,
|
||||
action: handleOpenQuickChat,
|
||||
}),
|
||||
[handleOpenQuickChat],
|
||||
);
|
||||
|
||||
const commands = useMemo<CommandItem[]>(
|
||||
() => [...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;
|
||||
}
|
||||
|
||||
@@ -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({
|
||||
<span className="hidden sm:inline ml-1">Add task</span>
|
||||
</Button>
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon-lg"
|
||||
onClick={onOpenQuickChat}
|
||||
className="cursor-pointer h-8 w-8"
|
||||
>
|
||||
<IconMessageCircle className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Quick Chat</TooltipContent>
|
||||
</Tooltip>
|
||||
<ViewToggleGroup
|
||||
toggleValue={toggleValue}
|
||||
onValueChange={handleViewChange}
|
||||
@@ -170,6 +187,7 @@ function TabletHeader({
|
||||
|
||||
function DesktopHeader({
|
||||
onCreateTask,
|
||||
onOpenQuickChat,
|
||||
searchQuery,
|
||||
onSearchChange,
|
||||
isSearchLoading,
|
||||
@@ -181,6 +199,7 @@ function DesktopHeader({
|
||||
onOpenHealthDialog,
|
||||
}: {
|
||||
onCreateTask: () => void;
|
||||
onOpenQuickChat: () => void;
|
||||
searchQuery: string;
|
||||
onSearchChange?: (query: string) => void;
|
||||
isSearchLoading: boolean;
|
||||
@@ -214,6 +233,19 @@ function DesktopHeader({
|
||||
Add task
|
||||
</Button>
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={onOpenQuickChat}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<IconMessageCircle className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Quick Chat</TooltipContent>
|
||||
</Tooltip>
|
||||
<ViewToggleGroup toggleValue={toggleValue} onValueChange={handleViewChange} />
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
@@ -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 = (
|
||||
<KanbanHeaderMobile
|
||||
workspaceId={workspaceId}
|
||||
currentPage={currentPage}
|
||||
{...sharedSearch}
|
||||
{...indicatorProps}
|
||||
/>
|
||||
);
|
||||
} else if (isTablet) {
|
||||
header = (
|
||||
<>
|
||||
<TabletHeader
|
||||
onCreateTask={onCreateTask}
|
||||
{...sharedSearch}
|
||||
toggleValue={toggleValue}
|
||||
handleViewChange={handleViewChange}
|
||||
setMenuOpen={setMenuOpen}
|
||||
{...indicatorProps}
|
||||
/>
|
||||
<MobileMenuSheet
|
||||
open={isMenuOpen}
|
||||
onOpenChange={setMenuOpen}
|
||||
const sharedActions = { onCreateTask, onOpenQuickChat: handleOpenQuickChat };
|
||||
|
||||
const renderHeader = () => {
|
||||
if (isMobile) {
|
||||
return (
|
||||
<KanbanHeaderMobile
|
||||
workspaceId={workspaceId}
|
||||
currentPage={currentPage}
|
||||
{...sharedSearch}
|
||||
{...indicatorProps}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
} else {
|
||||
header = (
|
||||
);
|
||||
}
|
||||
if (isTablet) {
|
||||
return (
|
||||
<>
|
||||
<TabletHeader
|
||||
{...sharedActions}
|
||||
{...sharedSearch}
|
||||
toggleValue={toggleValue}
|
||||
handleViewChange={handleViewChange}
|
||||
setMenuOpen={setMenuOpen}
|
||||
{...indicatorProps}
|
||||
/>
|
||||
<MobileMenuSheet
|
||||
open={isMenuOpen}
|
||||
onOpenChange={setMenuOpen}
|
||||
workspaceId={workspaceId}
|
||||
currentPage={currentPage}
|
||||
{...sharedSearch}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<DesktopHeader
|
||||
onCreateTask={onCreateTask}
|
||||
{...sharedActions}
|
||||
{...sharedSearch}
|
||||
toggleValue={toggleValue}
|
||||
handleViewChange={handleViewChange}
|
||||
{...indicatorProps}
|
||||
/>
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{header}
|
||||
{renderHeader()}
|
||||
{releaseNotes.hasNotes && (
|
||||
<ReleaseNotesDialog
|
||||
open={releaseNotes.dialogOpen}
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
"use client";
|
||||
|
||||
import { memo, useCallback, useRef, useState } from "react";
|
||||
import { useSettingsData } from "@/hooks/domains/settings/use-settings-data";
|
||||
import { type ChatInputContainerHandle } from "@/components/task/chat/chat-input-container";
|
||||
import { MessageList } from "@/components/task/chat/message-list";
|
||||
import { useChatPanelState } from "@/components/task/chat/use-chat-panel-state";
|
||||
import {
|
||||
ChatInputArea,
|
||||
useSubmitHandler,
|
||||
useChatPanelHandlers,
|
||||
} from "@/components/task/chat/chat-input-area";
|
||||
import { ClarificationInputOverlay } from "@/components/task/chat/clarification-input-overlay";
|
||||
|
||||
type QuickChatContentProps = {
|
||||
sessionId: string;
|
||||
};
|
||||
|
||||
export const QuickChatContent = memo(function QuickChatContent({
|
||||
sessionId,
|
||||
}: QuickChatContentProps) {
|
||||
const chatInputRef = useRef<ChatInputContainerHandle>(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 (
|
||||
<div className="flex flex-col flex-1 min-h-0">
|
||||
<div className="flex-1 min-h-0 overflow-hidden">
|
||||
<MessageList
|
||||
items={groupedItems}
|
||||
messages={allMessages}
|
||||
permissionsByToolCallId={permissionsByToolCallId}
|
||||
childrenByParentToolCallId={childrenByParentToolCallId}
|
||||
taskId={taskId ?? undefined}
|
||||
sessionId={resolvedSessionId}
|
||||
messagesLoading={messagesLoading}
|
||||
isWorking={isWorking}
|
||||
sessionState={session?.state}
|
||||
taskState={task?.state}
|
||||
worktreePath={session?.worktree_path}
|
||||
onOpenFile={undefined}
|
||||
/>
|
||||
</div>
|
||||
{pendingClarification && (
|
||||
<div className="flex-shrink-0 border-t border-sky-400/30 bg-card px-1">
|
||||
<ClarificationInputOverlay
|
||||
message={pendingClarification}
|
||||
onResolved={handleClarificationResolved}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
<ChatInputArea
|
||||
chatInputRef={chatInputRef}
|
||||
clarificationKey={clarificationKey}
|
||||
onClarificationResolved={handleClarificationResolved}
|
||||
handleSubmit={handleSubmit}
|
||||
handleCancelTurn={handleCancelTurn}
|
||||
showRequestChangesTooltip={false}
|
||||
onRequestChangesTooltipDismiss={undefined}
|
||||
panelState={panelState}
|
||||
isSending={isSending}
|
||||
hideSessionsDropdown={true}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -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 (
|
||||
<AlertDialog open={!!sessionToDelete} onOpenChange={onOpenChange}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete Quick Chat?</AlertDialogTitle>
|
||||
<AlertDialogDescription asChild>
|
||||
<div>
|
||||
<p>This will permanently delete this quick chat session, including:</p>
|
||||
<ul className="list-disc list-inside mt-2 space-y-1">
|
||||
<li>All conversation history</li>
|
||||
<li>The task and its data</li>
|
||||
<li>The associated worktree</li>
|
||||
</ul>
|
||||
<p className="mt-2">This action cannot be undone.</p>
|
||||
</div>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel className="cursor-pointer">Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={onConfirm}
|
||||
className="cursor-pointer bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
);
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="p-4 space-y-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Start a quick conversation with an agent without creating a formal task.
|
||||
</p>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="repository">Repository (optional)</Label>
|
||||
<Select
|
||||
value={selectedRepoId || NONE_VALUE}
|
||||
onValueChange={(v) => setSelectedRepoId(v === NONE_VALUE ? "" : v)}
|
||||
>
|
||||
<SelectTrigger id="repository" className="w-full">
|
||||
<SelectValue placeholder="Select a repository..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={NONE_VALUE}>No repository</SelectItem>
|
||||
{state.repositories.map((repo) => (
|
||||
<SelectItem key={repo.id} value={repo.id}>
|
||||
{repo.name}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="agent">Agent (optional)</Label>
|
||||
<Select
|
||||
value={selectedAgentId || NONE_VALUE}
|
||||
onValueChange={(v) => setSelectedAgentId(v === NONE_VALUE ? "" : v)}
|
||||
>
|
||||
<SelectTrigger id="agent" className="w-full">
|
||||
<SelectValue placeholder="Use workspace default..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value={NONE_VALUE}>Use workspace default</SelectItem>
|
||||
{state.agentProfiles.map((profile) => (
|
||||
<SelectItem key={profile.id} value={profile.id}>
|
||||
{profile.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** 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<string>("");
|
||||
const [selectedAgentId, setSelectedAgentId] = useState<string>("");
|
||||
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 (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent
|
||||
className="!max-w-md p-0 gap-0 flex flex-col shadow-2xl"
|
||||
showCloseButton={false}
|
||||
overlayClassName="bg-black/20"
|
||||
>
|
||||
<DialogTitle className="sr-only">New Quick Chat</DialogTitle>
|
||||
<div className="flex items-center justify-between px-4 py-3 border-b">
|
||||
<h2 className="text-lg font-semibold">New Quick Chat</h2>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => onOpenChange(false)}
|
||||
className="cursor-pointer h-8 w-8"
|
||||
>
|
||||
<IconX className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<QuickChatFormBody state={formState} />
|
||||
<div className="flex justify-end gap-2 px-4 py-3 border-t bg-muted/30">
|
||||
<Button variant="outline" onClick={() => onOpenChange(false)} className="cursor-pointer">
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleStart} disabled={isStarting} className="cursor-pointer">
|
||||
<IconRocket className="h-4 w-4 mr-2" />
|
||||
{isStarting ? "Starting..." : "Start Chat"}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
});
|
||||
|
||||
/** Alias for backwards compatibility */
|
||||
export const QuickChatDialog = QuickChatPickerDialog;
|
||||
@@ -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 (
|
||||
<div className="flex items-center gap-1 px-2 py-1 border-b bg-muted/20">
|
||||
<div className="flex items-center gap-1 overflow-x-auto flex-1 scrollbar-hide">
|
||||
{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 (
|
||||
<div
|
||||
key={s.sessionId || `new-${index}`}
|
||||
className={`flex items-center gap-1 rounded transition-colors whitespace-nowrap ${
|
||||
isActive
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:bg-muted"
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onTabChange(s.sessionId)}
|
||||
className="flex items-center px-2.5 py-1 text-xs cursor-pointer"
|
||||
>
|
||||
<span className="truncate max-w-[100px]">{tabName}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
aria-label={`Close ${tabName}`}
|
||||
className="p-1 cursor-pointer opacity-60 hover:opacity-100"
|
||||
onClick={() => onTabClose(s.sessionId)}
|
||||
>
|
||||
<IconX className="h-3 w-3" />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-6 w-6 p-0 cursor-pointer shrink-0"
|
||||
onClick={onNewChat}
|
||||
aria-label="Start new chat"
|
||||
>
|
||||
<IconPlus className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentPickerView({ onSelectAgent }: { onSelectAgent: (agentId: string) => void }) {
|
||||
const agentProfiles = useAppStore((s) => s.agentProfiles.items) ?? [];
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col items-center justify-center p-8">
|
||||
<div className="max-w-2xl w-full space-y-6">
|
||||
<div className="text-center space-y-2">
|
||||
<h3 className="text-lg font-medium">Choose an agent to start chatting</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Select an AI agent to begin your conversation
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
|
||||
{agentProfiles.map((profile) => (
|
||||
<button
|
||||
key={profile.id}
|
||||
onClick={() => onSelectAgent(profile.id)}
|
||||
className="group relative flex flex-col items-start gap-2 rounded-lg border p-4 text-left transition-all hover:border-primary hover:bg-accent cursor-pointer"
|
||||
>
|
||||
<div className="flex items-center gap-2 w-full">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-md border bg-background">
|
||||
<IconMessageCircle className="h-4 w-4" />
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<p className="font-medium text-sm truncate">{profile.label}</p>
|
||||
<p className="text-xs text-muted-foreground truncate">{profile.agent_name}</p>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const QuickChatModal = memo(function QuickChatModal({ workspaceId }: QuickChatModalProps) {
|
||||
const {
|
||||
isOpen,
|
||||
sessions,
|
||||
activeSessionId,
|
||||
sessionToClose,
|
||||
activeSessionNeedsAgent,
|
||||
setActiveQuickChatSession,
|
||||
setSessionToClose,
|
||||
handleOpenChange,
|
||||
handleNewChat,
|
||||
handleSelectAgent,
|
||||
handleCloseTab,
|
||||
handleConfirmClose,
|
||||
} = useQuickChatModal(workspaceId);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={isOpen} onOpenChange={handleOpenChange}>
|
||||
<DialogContent
|
||||
className="!max-w-[80vw] !w-[80vw] max-h-[85vh] h-[85vh] p-0 gap-0 flex flex-col shadow-2xl"
|
||||
showCloseButton={false}
|
||||
overlayClassName="bg-transparent"
|
||||
>
|
||||
<DialogTitle className="sr-only">Quick Chat</DialogTitle>
|
||||
<QuickChatTabs
|
||||
sessions={sessions}
|
||||
activeSessionId={activeSessionId || ""}
|
||||
onTabChange={setActiveQuickChatSession}
|
||||
onTabClose={handleCloseTab}
|
||||
onNewChat={handleNewChat}
|
||||
/>
|
||||
{activeSessionId && !activeSessionNeedsAgent && (
|
||||
<QuickChatContent sessionId={activeSessionId} />
|
||||
)}
|
||||
{activeSessionNeedsAgent && <AgentPickerView onSelectAgent={handleSelectAgent} />}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<QuickChatDeleteDialog
|
||||
sessionToDelete={sessionToClose}
|
||||
onOpenChange={(open) => !open && setSessionToClose(null)}
|
||||
onConfirm={handleConfirmClose}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
});
|
||||
@@ -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 && <QuickChatModal workspaceId={workspaceId} />}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -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<string | null>(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,
|
||||
};
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="flex items-center gap-1.5 px-3 py-1 text-xs text-muted-foreground">
|
||||
<IconBrain className="h-3 w-3" />
|
||||
<span className="capitalize">{agentMode} mode</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type ChatInputAreaProps = {
|
||||
chatInputRef: React.RefObject<ChatInputContainerHandle | null>;
|
||||
clarificationKey: number;
|
||||
@@ -307,6 +320,7 @@ type ChatInputAreaProps = {
|
||||
onRequestChangesTooltipDismiss?: () => void;
|
||||
panelState: ReturnType<typeof useChatPanelState>;
|
||||
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 (
|
||||
<div className="bg-card flex-shrink-0 px-2 pb-2 pt-1">
|
||||
{agentMode && agentMode !== "default" && (
|
||||
<div className="flex items-center gap-1.5 px-3 py-1 text-xs text-muted-foreground">
|
||||
<IconBrain className="h-3 w-3" />
|
||||
<span className="capitalize">{agentMode} mode</span>
|
||||
</div>
|
||||
)}
|
||||
<AgentModeIndicator sessionId={resolvedSessionId} />
|
||||
{taskId && <PRMergedBanner key={taskId} taskId={taskId} />}
|
||||
<ChatInputContainer
|
||||
ref={chatInputRef}
|
||||
@@ -406,6 +412,7 @@ export function ChatInputArea({
|
||||
onAddContextFile={handleAddContextFile}
|
||||
todoItems={todoItems}
|
||||
onImplementPlan={handleImplementPlan}
|
||||
hideSessionsDropdown={hideSessionsDropdown}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -34,6 +34,7 @@ export type ChatInputEditorAreaProps = {
|
||||
handleAgentCommand: (command: string) => void;
|
||||
handleImagePaste: (files: File[]) => Promise<void>;
|
||||
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 (
|
||||
<div className="flex flex-col flex-1 min-h-0 overflow-hidden">
|
||||
<Tooltip open={showRequestChangesTooltip}>
|
||||
<Tooltip open={p.showRequestChangesTooltip}>
|
||||
<TooltipTrigger asChild>
|
||||
<div
|
||||
className={cn(
|
||||
"flex-1 min-h-0 transition-opacity",
|
||||
isEnhancingPrompt && "opacity-50 pointer-events-none",
|
||||
p.isEnhancingPrompt && "opacity-50 pointer-events-none",
|
||||
)}
|
||||
>
|
||||
<TipTapInput
|
||||
ref={inputRef}
|
||||
value={value}
|
||||
onChange={handleChange}
|
||||
value={p.value}
|
||||
onChange={p.handleChange}
|
||||
onSubmit={wrappedSubmit}
|
||||
placeholder={inputPlaceholder}
|
||||
disabled={isDisabled || hasClarification}
|
||||
planModeEnabled={planModeEnabled}
|
||||
submitKey={submitKey}
|
||||
onFocus={() => 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}
|
||||
/>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
@@ -124,29 +91,30 @@ export function ChatInputEditorArea({
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
<ChatInputToolbar
|
||||
planModeEnabled={planModeEnabled}
|
||||
planModeAvailable={planModeAvailable}
|
||||
mcpServers={mcpServers}
|
||||
onPlanModeChange={onPlanModeChange}
|
||||
sessionId={sessionId}
|
||||
taskId={taskId}
|
||||
taskTitle={taskTitle}
|
||||
taskDescription={taskDescription}
|
||||
isAgentBusy={isAgentBusy}
|
||||
isDisabled={isDisabled}
|
||||
isSending={isSending}
|
||||
onCancel={onCancel}
|
||||
planModeEnabled={p.planModeEnabled}
|
||||
planModeAvailable={p.planModeAvailable}
|
||||
mcpServers={p.mcpServers}
|
||||
onPlanModeChange={p.onPlanModeChange}
|
||||
sessionId={p.sessionId}
|
||||
taskId={p.taskId}
|
||||
taskTitle={p.taskTitle}
|
||||
taskDescription={p.taskDescription}
|
||||
isAgentBusy={p.isAgentBusy}
|
||||
isDisabled={p.isDisabled}
|
||||
isSending={p.isSending}
|
||||
onCancel={p.onCancel}
|
||||
onSubmit={wrappedSubmit}
|
||||
submitKey={submitKey}
|
||||
contextCount={contextCount}
|
||||
contextPopoverOpen={contextPopoverOpen}
|
||||
onContextPopoverOpenChange={setContextPopoverOpen}
|
||||
planContextEnabled={planContextEnabled}
|
||||
contextFiles={contextFiles}
|
||||
onToggleFile={onToggleContextFile}
|
||||
onImplementPlan={onImplementPlan}
|
||||
onEnhancePrompt={onEnhancePrompt}
|
||||
isEnhancingPrompt={isEnhancingPrompt}
|
||||
submitKey={p.submitKey}
|
||||
contextCount={p.contextCount}
|
||||
contextPopoverOpen={p.contextPopoverOpen}
|
||||
onContextPopoverOpenChange={p.setContextPopoverOpen}
|
||||
planContextEnabled={p.planContextEnabled}
|
||||
contextFiles={p.contextFiles}
|
||||
onToggleFile={p.onToggleContextFile}
|
||||
onImplementPlan={p.onImplementPlan}
|
||||
onEnhancePrompt={p.onEnhancePrompt}
|
||||
isEnhancingPrompt={p.isEnhancingPrompt}
|
||||
hideSessionsDropdown={p.hideSessionsDropdown}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -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 (
|
||||
<div className="flex items-center gap-0.5 shrink-0">
|
||||
{showResetContext && <ResetContextButton sessionId={sessionId} />}
|
||||
<SessionsDropdown
|
||||
taskId={taskId}
|
||||
activeSessionId={sessionId}
|
||||
taskTitle={taskTitle}
|
||||
taskDescription={taskDescription}
|
||||
/>
|
||||
{!hideSessionsDropdown && (
|
||||
<SessionsDropdown
|
||||
taskId={taskId}
|
||||
activeSessionId={sessionId}
|
||||
taskTitle={taskTitle}
|
||||
taskDescription={taskDescription}
|
||||
/>
|
||||
)}
|
||||
<TokenUsageDisplay sessionId={sessionId} />
|
||||
<ModelSelector sessionId={sessionId} />
|
||||
{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}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -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 (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="cursor-pointer px-2"
|
||||
onClick={handleOpenQuickChat}
|
||||
>
|
||||
<IconMessageCircle className="h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Quick Chat</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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({
|
||||
<EditorsMenu activeSessionId={activeSessionId ?? null} />
|
||||
</>
|
||||
)}
|
||||
<QuickChatButton workspaceId={workspaceId} />
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button size="sm" variant="outline" className="cursor-pointer px-2" asChild>
|
||||
|
||||
@@ -81,6 +81,7 @@ export function useAllWorkflowSnapshots(workspaceId: string | null) {
|
||||
const stepIds = new Set(steps.map((s) => s.id));
|
||||
|
||||
const tasks: KanbanTask[] = snapshot.tasks
|
||||
.filter((task) => !task.is_ephemeral) // Filter out ephemeral tasks (e.g., quick chat)
|
||||
.map((task) => mapSnapshotTask(task, stepIds))
|
||||
.filter((t): t is KanbanTask => t !== null);
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useCallback } from "react";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
|
||||
/**
|
||||
* Hook to handle opening quick chat.
|
||||
* Just opens the modal - the user will select an agent from the picker.
|
||||
*/
|
||||
export function useQuickChatLauncher(workspaceId?: string | null) {
|
||||
const openQuickChat = useAppStore((state) => state.openQuickChat);
|
||||
const quickChatSessions = useAppStore((state) => state.quickChat.sessions);
|
||||
|
||||
const handleOpenQuickChat = useCallback(() => {
|
||||
if (!workspaceId) return;
|
||||
|
||||
// If there's an existing session, open it. Otherwise just open the modal with agent picker
|
||||
const existingSession = quickChatSessions.find((s) => s.workspaceId === workspaceId);
|
||||
if (existingSession) {
|
||||
openQuickChat(existingSession.sessionId, workspaceId);
|
||||
} else {
|
||||
// Open modal without a session - will show agent picker
|
||||
openQuickChat("", workspaceId);
|
||||
}
|
||||
}, [workspaceId, quickChatSessions, openQuickChat]);
|
||||
|
||||
return handleOpenQuickChat;
|
||||
}
|
||||
@@ -50,3 +50,43 @@ export async function listRepositoryScripts(repositoryId: string, options?: ApiR
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
// Quick Chat operations
|
||||
export type StartQuickChatRequest = {
|
||||
title?: string;
|
||||
repository_id?: string;
|
||||
agent_profile_id?: string;
|
||||
executor_id?: string;
|
||||
prompt?: string;
|
||||
local_path?: string;
|
||||
repository_name?: string;
|
||||
default_branch?: string;
|
||||
base_branch?: string;
|
||||
};
|
||||
|
||||
export type StartQuickChatResponse = {
|
||||
task_id: string;
|
||||
session_id: string;
|
||||
};
|
||||
|
||||
export async function startQuickChat(
|
||||
workspaceId: string,
|
||||
payload: StartQuickChatRequest,
|
||||
options?: ApiRequestOptions,
|
||||
) {
|
||||
return fetchJson<StartQuickChatResponse>(`/api/v1/workspaces/${workspaceId}/quick-chat`, {
|
||||
...options,
|
||||
init: { method: "POST", body: JSON.stringify(payload), ...(options?.init ?? {}) },
|
||||
});
|
||||
}
|
||||
|
||||
export async function listQuickChatSessions(workspaceId: string, options?: ApiRequestOptions) {
|
||||
return fetchJson<{
|
||||
tasks: Array<{
|
||||
id: string;
|
||||
title: string;
|
||||
workspace_id: string;
|
||||
primary_session_id?: string | null;
|
||||
}>;
|
||||
}>(`/api/v1/workspaces/${workspaceId}/tasks?only_ephemeral=true`, options);
|
||||
}
|
||||
|
||||
@@ -137,4 +137,8 @@ export const SHORTCUTS = {
|
||||
key: KEYS.TAB,
|
||||
modifiers: { shift: true },
|
||||
},
|
||||
QUICK_CHAT: {
|
||||
key: KEYS.Q,
|
||||
modifiers: { ctrlOrCmd: true, shift: true },
|
||||
},
|
||||
} as const;
|
||||
|
||||
@@ -114,7 +114,10 @@ export function matchesShortcut(
|
||||
event: KeyboardEvent | React.KeyboardEvent,
|
||||
shortcut: KeyboardShortcut,
|
||||
): boolean {
|
||||
if (event.key !== shortcut.key) return false;
|
||||
// Case-insensitive comparison for letter keys
|
||||
const eventKey = event.key.toLowerCase();
|
||||
const shortcutKey = shortcut.key.toLowerCase();
|
||||
if (eventKey !== shortcutKey) return false;
|
||||
|
||||
if (!shortcut.modifiers) {
|
||||
return !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey;
|
||||
|
||||
@@ -5,6 +5,7 @@ type KanbanTask = KanbanState["tasks"][number];
|
||||
|
||||
export function snapshotToState(snapshot: WorkflowSnapshot): Partial<AppState> {
|
||||
const tasks = snapshot.tasks
|
||||
.filter((task) => !task.is_ephemeral) // Filter out ephemeral tasks (e.g., quick chat)
|
||||
.map((task) => {
|
||||
const workflowStepId = task.workflow_step_id;
|
||||
if (!workflowStepId) return null;
|
||||
|
||||
@@ -183,6 +183,23 @@ function hydrateUI(draft: Draft<AppState>, state: Partial<AppState>): void {
|
||||
if (state.previewPanel) deepMerge(draft.previewPanel, state.previewPanel);
|
||||
if (state.rightPanel) deepMerge(draft.rightPanel, state.rightPanel);
|
||||
if (state.diffs) deepMerge(draft.diffs, state.diffs);
|
||||
if (state.quickChat) {
|
||||
// Merge quick chat sessions, preserving isOpen from client
|
||||
if (state.quickChat.sessions) {
|
||||
draft.quickChat.sessions = state.quickChat.sessions;
|
||||
// Validate activeSessionId exists in sessions after merge
|
||||
if (
|
||||
draft.quickChat.activeSessionId &&
|
||||
!draft.quickChat.sessions.some((s) => s.sessionId === draft.quickChat.activeSessionId)
|
||||
) {
|
||||
draft.quickChat.activeSessionId = draft.quickChat.sessions[0]?.sessionId ?? null;
|
||||
}
|
||||
// Close quick chat if no sessions remain
|
||||
if (draft.quickChat.sessions.length === 0) {
|
||||
draft.quickChat.isOpen = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (state.connection) {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
const { status: _status, ...rest } = state.connection || {};
|
||||
|
||||
@@ -57,6 +57,12 @@ export type SystemHealthState = {
|
||||
loading: boolean;
|
||||
};
|
||||
|
||||
export type QuickChatState = {
|
||||
isOpen: boolean;
|
||||
sessions: Array<{ sessionId: string; workspaceId: string; name?: string }>;
|
||||
activeSessionId: string | null;
|
||||
};
|
||||
|
||||
export type SessionFailureNotification = {
|
||||
sessionId: string;
|
||||
taskId: string;
|
||||
@@ -73,6 +79,7 @@ export type UISliceState = {
|
||||
chatInput: ChatInputState;
|
||||
documentPanel: DocumentPanelState;
|
||||
systemHealth: SystemHealthState;
|
||||
quickChat: QuickChatState;
|
||||
sessionFailureNotification: SessionFailureNotification | null;
|
||||
};
|
||||
|
||||
@@ -95,6 +102,11 @@ export type UISliceActions = {
|
||||
setSystemHealth: (response: SystemHealthResponse) => void;
|
||||
setSystemHealthLoading: (loading: boolean) => void;
|
||||
invalidateSystemHealth: () => void;
|
||||
openQuickChat: (sessionId: string, workspaceId: string) => void;
|
||||
closeQuickChat: () => void;
|
||||
closeQuickChatSession: (sessionId: string) => void;
|
||||
setActiveQuickChatSession: (sessionId: string) => void;
|
||||
renameQuickChatSession: (sessionId: string, name: string) => void;
|
||||
setSessionFailureNotification: (n: SessionFailureNotification | null) => void;
|
||||
};
|
||||
|
||||
|
||||
@@ -19,48 +19,89 @@ export const defaultUIState: UISliceState = {
|
||||
chatInput: { planModeBySessionId: {} },
|
||||
documentPanel: { activeDocumentBySessionId: {} },
|
||||
systemHealth: { issues: [], healthy: true, loaded: false, loading: false },
|
||||
quickChat: { isOpen: false, sessions: [], activeSessionId: null },
|
||||
sessionFailureNotification: null,
|
||||
};
|
||||
|
||||
type ImmerSet = Parameters<typeof createUISlice>[0];
|
||||
|
||||
function buildPreviewActions(set: ImmerSet) {
|
||||
return {
|
||||
setPreviewOpen: (sessionId: string, open: boolean) =>
|
||||
set((draft) => {
|
||||
draft.previewPanel.openBySessionId[sessionId] = open;
|
||||
setLocalStorage(`preview-open-${sessionId}`, open);
|
||||
}),
|
||||
togglePreviewOpen: (sessionId: string) =>
|
||||
set((draft) => {
|
||||
const current = draft.previewPanel.openBySessionId[sessionId] ?? false;
|
||||
draft.previewPanel.openBySessionId[sessionId] = !current;
|
||||
setLocalStorage(`preview-open-${sessionId}`, !current);
|
||||
}),
|
||||
setPreviewView: (
|
||||
sessionId: string,
|
||||
view: UISliceState["previewPanel"]["viewBySessionId"][string],
|
||||
) =>
|
||||
set((draft) => {
|
||||
draft.previewPanel.viewBySessionId[sessionId] = view;
|
||||
setLocalStorage(`preview-view-${sessionId}`, view);
|
||||
}),
|
||||
setPreviewDevice: (
|
||||
sessionId: string,
|
||||
device: UISliceState["previewPanel"]["deviceBySessionId"][string],
|
||||
) =>
|
||||
set((draft) => {
|
||||
draft.previewPanel.deviceBySessionId[sessionId] = device;
|
||||
setLocalStorage(`preview-device-${sessionId}`, device);
|
||||
}),
|
||||
setPreviewStage: (
|
||||
sessionId: string,
|
||||
stage: UISliceState["previewPanel"]["stageBySessionId"][string],
|
||||
) =>
|
||||
set((draft) => {
|
||||
draft.previewPanel.stageBySessionId[sessionId] = stage;
|
||||
}),
|
||||
setPreviewUrl: (sessionId: string, url: string) =>
|
||||
set((draft) => {
|
||||
draft.previewPanel.urlBySessionId[sessionId] = url;
|
||||
}),
|
||||
setPreviewUrlDraft: (sessionId: string, url: string) =>
|
||||
set((draft) => {
|
||||
draft.previewPanel.urlDraftBySessionId[sessionId] = url;
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
function buildMobileActions(set: ImmerSet) {
|
||||
return {
|
||||
setMobileKanbanColumnIndex: (index: number) =>
|
||||
set((draft) => {
|
||||
draft.mobileKanban.activeColumnIndex = index;
|
||||
}),
|
||||
setMobileKanbanMenuOpen: (open: boolean) =>
|
||||
set((draft) => {
|
||||
draft.mobileKanban.isMenuOpen = open;
|
||||
}),
|
||||
setMobileSessionPanel: (
|
||||
sessionId: string,
|
||||
panel: UISliceState["mobileSession"]["activePanelBySessionId"][string],
|
||||
) =>
|
||||
set((draft) => {
|
||||
draft.mobileSession.activePanelBySessionId[sessionId] = panel;
|
||||
}),
|
||||
setMobileSessionTaskSwitcherOpen: (open: boolean) =>
|
||||
set((draft) => {
|
||||
draft.mobileSession.isTaskSwitcherOpen = open;
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export const createUISlice: StateCreator<UISlice, [["zustand/immer", never]], [], UISlice> = (
|
||||
set,
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
_get,
|
||||
) => ({
|
||||
...defaultUIState,
|
||||
setPreviewOpen: (sessionId, open) =>
|
||||
set((draft) => {
|
||||
draft.previewPanel.openBySessionId[sessionId] = open;
|
||||
setLocalStorage(`preview-open-${sessionId}`, open);
|
||||
}),
|
||||
togglePreviewOpen: (sessionId) =>
|
||||
set((draft) => {
|
||||
const current = draft.previewPanel.openBySessionId[sessionId] ?? false;
|
||||
draft.previewPanel.openBySessionId[sessionId] = !current;
|
||||
setLocalStorage(`preview-open-${sessionId}`, !current);
|
||||
}),
|
||||
setPreviewView: (sessionId, view) =>
|
||||
set((draft) => {
|
||||
draft.previewPanel.viewBySessionId[sessionId] = view;
|
||||
setLocalStorage(`preview-view-${sessionId}`, view);
|
||||
}),
|
||||
setPreviewDevice: (sessionId, device) =>
|
||||
set((draft) => {
|
||||
draft.previewPanel.deviceBySessionId[sessionId] = device;
|
||||
setLocalStorage(`preview-device-${sessionId}`, device);
|
||||
}),
|
||||
setPreviewStage: (sessionId, stage) =>
|
||||
set((draft) => {
|
||||
draft.previewPanel.stageBySessionId[sessionId] = stage;
|
||||
}),
|
||||
setPreviewUrl: (sessionId, url) =>
|
||||
set((draft) => {
|
||||
draft.previewPanel.urlBySessionId[sessionId] = url;
|
||||
}),
|
||||
setPreviewUrlDraft: (sessionId, url) =>
|
||||
set((draft) => {
|
||||
draft.previewPanel.urlDraftBySessionId[sessionId] = url;
|
||||
}),
|
||||
...buildPreviewActions(set),
|
||||
...buildMobileActions(set),
|
||||
setRightPanelActiveTab: (sessionId, tab) =>
|
||||
set((draft) => {
|
||||
draft.rightPanel.activeTabBySessionId[sessionId] = tab;
|
||||
@@ -70,22 +111,6 @@ export const createUISlice: StateCreator<UISlice, [["zustand/immer", never]], []
|
||||
draft.connection.status = status;
|
||||
draft.connection.error = error ?? null;
|
||||
}),
|
||||
setMobileKanbanColumnIndex: (index) =>
|
||||
set((draft) => {
|
||||
draft.mobileKanban.activeColumnIndex = index;
|
||||
}),
|
||||
setMobileKanbanMenuOpen: (open) =>
|
||||
set((draft) => {
|
||||
draft.mobileKanban.isMenuOpen = open;
|
||||
}),
|
||||
setMobileSessionPanel: (sessionId, panel) =>
|
||||
set((draft) => {
|
||||
draft.mobileSession.activePanelBySessionId[sessionId] = panel;
|
||||
}),
|
||||
setMobileSessionTaskSwitcherOpen: (open) =>
|
||||
set((draft) => {
|
||||
draft.mobileSession.isTaskSwitcherOpen = open;
|
||||
}),
|
||||
setPlanMode: (sessionId, enabled) =>
|
||||
set((draft) => {
|
||||
draft.chatInput.planModeBySessionId[sessionId] = enabled;
|
||||
@@ -110,6 +135,55 @@ export const createUISlice: StateCreator<UISlice, [["zustand/immer", never]], []
|
||||
set((draft) => {
|
||||
draft.systemHealth.loaded = false;
|
||||
}),
|
||||
openQuickChat: (sessionId, workspaceId) =>
|
||||
set((draft) => {
|
||||
draft.quickChat.isOpen = true;
|
||||
// If sessionId is empty, create a placeholder tab for agent selection
|
||||
if (!sessionId) {
|
||||
// Check if there's already an empty tab
|
||||
const emptyTabExists = draft.quickChat.sessions.some((s) => s.sessionId === "");
|
||||
if (!emptyTabExists) {
|
||||
draft.quickChat.sessions.push({ sessionId: "", workspaceId });
|
||||
}
|
||||
draft.quickChat.activeSessionId = "";
|
||||
return;
|
||||
}
|
||||
// Add session if not already in list
|
||||
const exists = draft.quickChat.sessions.some((s) => s.sessionId === sessionId);
|
||||
if (!exists) {
|
||||
draft.quickChat.sessions.push({ sessionId, workspaceId });
|
||||
}
|
||||
draft.quickChat.activeSessionId = sessionId;
|
||||
}),
|
||||
closeQuickChat: () =>
|
||||
set((draft) => {
|
||||
draft.quickChat.isOpen = false;
|
||||
}),
|
||||
closeQuickChatSession: (sessionId) =>
|
||||
set((draft) => {
|
||||
// Remove session from list
|
||||
draft.quickChat.sessions = draft.quickChat.sessions.filter((s) => s.sessionId !== sessionId);
|
||||
// If closing active session, switch to another or close modal
|
||||
if (draft.quickChat.activeSessionId === sessionId) {
|
||||
if (draft.quickChat.sessions.length > 0) {
|
||||
draft.quickChat.activeSessionId = draft.quickChat.sessions[0].sessionId;
|
||||
} else {
|
||||
draft.quickChat.activeSessionId = null;
|
||||
draft.quickChat.isOpen = false;
|
||||
}
|
||||
}
|
||||
}),
|
||||
setActiveQuickChatSession: (sessionId) =>
|
||||
set((draft) => {
|
||||
draft.quickChat.activeSessionId = sessionId;
|
||||
}),
|
||||
renameQuickChatSession: (sessionId, name) =>
|
||||
set((draft) => {
|
||||
const session = draft.quickChat.sessions.find((s) => s.sessionId === sessionId);
|
||||
if (session) {
|
||||
session.name = name;
|
||||
}
|
||||
}),
|
||||
setSessionFailureNotification: (n) =>
|
||||
set((draft) => {
|
||||
draft.sessionFailureNotification = n;
|
||||
|
||||
@@ -189,6 +189,7 @@ export type AppState = {
|
||||
chatInput: (typeof defaultUIState)["chatInput"];
|
||||
documentPanel: (typeof defaultUIState)["documentPanel"];
|
||||
systemHealth: (typeof defaultUIState)["systemHealth"];
|
||||
quickChat: (typeof defaultUIState)["quickChat"];
|
||||
sessionFailureNotification: (typeof defaultUIState)["sessionFailureNotification"];
|
||||
|
||||
// GitHub actions
|
||||
@@ -291,6 +292,11 @@ export type AppState = {
|
||||
setSystemHealth: (response: SystemHealthResponse) => void;
|
||||
setSystemHealthLoading: (loading: boolean) => void;
|
||||
invalidateSystemHealth: () => void;
|
||||
openQuickChat: (sessionId: string, workspaceId: string) => void;
|
||||
closeQuickChat: () => void;
|
||||
closeQuickChatSession: (sessionId: string) => void;
|
||||
setActiveQuickChatSession: (sessionId: string) => void;
|
||||
renameQuickChatSession: (sessionId: string, name: string) => void;
|
||||
setSessionFailureNotification: (
|
||||
n: import("./slices/ui/types").SessionFailureNotification | null,
|
||||
) => void;
|
||||
@@ -420,7 +426,10 @@ const defaultState = {
|
||||
mobileKanban: defaultUIState.mobileKanban,
|
||||
mobileSession: defaultUIState.mobileSession,
|
||||
chatInput: defaultUIState.chatInput,
|
||||
documentPanel: defaultUIState.documentPanel,
|
||||
systemHealth: defaultUIState.systemHealth,
|
||||
quickChat: defaultUIState.quickChat,
|
||||
sessionFailureNotification: defaultUIState.sessionFailureNotification,
|
||||
};
|
||||
|
||||
function mergeInitialState(initialState?: Partial<AppState>): typeof defaultState {
|
||||
@@ -487,7 +496,11 @@ function mergeInitialState(initialState?: Partial<AppState>): typeof defaultStat
|
||||
mobileKanban: { ...defaultState.mobileKanban, ...initialState.mobileKanban },
|
||||
mobileSession: { ...defaultState.mobileSession, ...initialState.mobileSession },
|
||||
chatInput: { ...defaultState.chatInput, ...initialState.chatInput },
|
||||
documentPanel: { ...defaultState.documentPanel, ...initialState.documentPanel },
|
||||
systemHealth: { ...defaultState.systemHealth, ...initialState.systemHealth },
|
||||
quickChat: { ...defaultState.quickChat, ...initialState.quickChat },
|
||||
sessionFailureNotification:
|
||||
initialState.sessionFailureNotification ?? defaultState.sessionFailureNotification,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -562,7 +575,10 @@ export function createAppStore(initialState?: Partial<AppState>) {
|
||||
mobileKanban: merged.mobileKanban,
|
||||
mobileSession: merged.mobileSession,
|
||||
chatInput: merged.chatInput,
|
||||
documentPanel: merged.documentPanel,
|
||||
systemHealth: merged.systemHealth,
|
||||
quickChat: merged.quickChat,
|
||||
sessionFailureNotification: merged.sessionFailureNotification,
|
||||
// Add hydrate method
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
hydrate: (state, options) => set((draft) => hydrateState(draft as any, state, options)),
|
||||
|
||||
@@ -109,6 +109,7 @@ export type TaskEventPayload = {
|
||||
review_status?: "pending" | "approved" | "changes_requested" | "rejected" | null;
|
||||
archived_at?: string | null;
|
||||
updated_at?: string;
|
||||
is_ephemeral: boolean;
|
||||
};
|
||||
|
||||
export type AgentUpdatePayload = {
|
||||
|
||||
@@ -238,6 +238,7 @@ export type Task = {
|
||||
primary_agent_name?: string | null;
|
||||
primary_working_directory?: string | null;
|
||||
is_remote_executor?: boolean;
|
||||
is_ephemeral?: boolean;
|
||||
archived_at?: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
|
||||
@@ -19,15 +19,19 @@ export function registerKanbanHandlers(store: StoreApi<AppState>): WsHandlers {
|
||||
events: step.events,
|
||||
show_in_command_panel: step.show_in_command_panel,
|
||||
}));
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
const tasks: KanbanTask[] = message.payload.tasks.map((task: any) => ({
|
||||
id: task.id,
|
||||
workflowStepId: task.workflowStepId,
|
||||
title: task.title,
|
||||
description: task.description,
|
||||
position: task.position ?? 0,
|
||||
state: task.state,
|
||||
}));
|
||||
const tasks: KanbanTask[] = message.payload.tasks
|
||||
// Filter out ephemeral tasks (e.g., quick chat)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
.filter((task: any) => !task.is_ephemeral)
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
.map((task: any) => ({
|
||||
id: task.id,
|
||||
workflowStepId: task.workflowStepId,
|
||||
title: task.title,
|
||||
description: task.description,
|
||||
position: task.position ?? 0,
|
||||
state: task.state,
|
||||
}));
|
||||
|
||||
store.setState((state) => {
|
||||
const next = {
|
||||
|
||||
@@ -61,6 +61,11 @@ function upsertMultiTask(state: AppState, workflowId: string, task: KanbanTask):
|
||||
/** Upsert a task in both single-kanban and multi-kanban snapshots. */
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function upsertTaskInBothKanbans(state: AppState, wfId: string, payload: any): AppState {
|
||||
// Skip ephemeral tasks - they should never be added to kanban
|
||||
if (payload.is_ephemeral) {
|
||||
return state;
|
||||
}
|
||||
|
||||
let next = state;
|
||||
|
||||
if (state.kanban.workflowId === wfId) {
|
||||
@@ -107,11 +112,16 @@ function removeTaskFromBothKanbans(state: AppState, wfId: string, taskId: string
|
||||
export function registerTasksHandlers(store: StoreApi<AppState>): WsHandlers {
|
||||
return {
|
||||
"task.created": (message) => {
|
||||
// Skip ephemeral tasks (e.g., quick chat) - they shouldn't appear on the Kanban board
|
||||
if (message.payload.is_ephemeral) return;
|
||||
store.setState((state) =>
|
||||
upsertTaskInBothKanbans(state, message.payload.workflow_id, message.payload),
|
||||
);
|
||||
},
|
||||
"task.updated": (message) => {
|
||||
// Skip ephemeral tasks (e.g., quick chat) - they shouldn't appear on the Kanban board
|
||||
if (message.payload.is_ephemeral) return;
|
||||
|
||||
store.setState((state) => {
|
||||
const wfId = message.payload.workflow_id;
|
||||
const taskId = message.payload.task_id;
|
||||
@@ -150,6 +160,9 @@ export function registerTasksHandlers(store: StoreApi<AppState>): WsHandlers {
|
||||
});
|
||||
},
|
||||
"task.state_changed": (message) => {
|
||||
// Skip ephemeral tasks (e.g., quick chat) - they shouldn't appear on the Kanban board
|
||||
if (message.payload.is_ephemeral) return;
|
||||
|
||||
store.setState((state) =>
|
||||
upsertTaskInBothKanbans(state, message.payload.workflow_id, message.payload),
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user