feat: local executor and worktree + new task dialog (#211)

This commit is contained in:
Carlos Florêncio
2026-02-08 11:56:23 +00:00
committed by GitHub
parent 3717d6982f
commit a70de7da11
40 changed files with 882 additions and 419 deletions
+5
View File
@@ -65,6 +65,11 @@ func provideLifecycleManager(
log.Warn("Docker runtime enabled but Docker client not available")
}
// Register Remote Docker runtime (always available, instances are created lazily per host)
remoteDockerRuntime := lifecycle.NewRemoteDockerRuntime(log)
runtimeRegistry.Register(remoteDockerRuntime)
log.Info("Remote Docker runtime registered")
agentRegistry, _, err := registry.Provide(log)
if err != nil {
return nil, nil, err
@@ -57,6 +57,9 @@ type AgentStreamEventData struct {
// comes from a subagent. Used for visual nesting in the UI.
ParentToolCallID string `json:"parent_tool_call_id,omitempty"`
// PendingID identifies a permission request (for "permission_cancelled" events).
PendingID string `json:"pending_id,omitempty"`
// Normalized contains the typed tool payload data.
// This is used to populate message metadata with structured tool information.
Normalized *streams.NormalizedPayload `json:"normalized,omitempty"`
@@ -135,6 +135,7 @@ func (p *EventPublisher) PublishAgentStreamEvent(execution *AgentExecution, even
Text: event.Text,
ToolCallID: event.ToolCallID,
ParentToolCallID: event.ParentToolCallID,
PendingID: event.PendingID,
ToolName: event.ToolName,
ToolTitle: event.ToolTitle,
ToolStatus: event.ToolStatus,
@@ -0,0 +1,69 @@
package lifecycle
import (
"context"
"fmt"
"go.uber.org/zap"
"github.com/kandev/kandev/internal/agent/runtime"
"github.com/kandev/kandev/internal/agentctl/server/process"
"github.com/kandev/kandev/internal/common/logger"
)
// RemoteDockerRuntime implements Runtime for remote Docker-based agent execution.
// Unlike the local Docker runtime which bind-mounts the host workspace, the remote
// Docker runtime clones the repository inside the container since the remote host
// does not have access to the local filesystem.
type RemoteDockerRuntime struct {
logger *logger.Logger
}
// NewRemoteDockerRuntime creates a new remote Docker runtime.
// Remote docker runtimes are created lazily per docker_host when executor configs are resolved.
func NewRemoteDockerRuntime(log *logger.Logger) *RemoteDockerRuntime {
return &RemoteDockerRuntime{
logger: log.WithFields(zap.String("runtime", "remote_docker")),
}
}
func (r *RemoteDockerRuntime) Name() runtime.Name {
return runtime.NameRemoteDocker
}
func (r *RemoteDockerRuntime) HealthCheck(ctx context.Context) error {
// Remote docker health is checked per-host when creating instances.
// The runtime itself is always "available" as a capability.
r.logger.Warn("remote_docker runtime is registered but not yet implemented; health check is a no-op")
return nil
}
func (r *RemoteDockerRuntime) CreateInstance(ctx context.Context, req *RuntimeCreateRequest) (*RuntimeInstance, error) {
// TODO: Implement remote docker instance creation.
// Flow:
// 1. Extract docker_host, git_token from req.Env or metadata
// 2. Create Docker client pointing to remote host
// 3. Create container with named volume for /workspace (no bind mount)
// 4. Start container, wait for agentctl health
// 5. Clone repo inside container via Docker exec API
// 6. Create agentctl instance pointing to /workspace
// 7. Return RuntimeInstance with container IP + agentctl client
return nil, fmt.Errorf("remote_docker runtime is not yet implemented")
}
func (r *RemoteDockerRuntime) StopInstance(ctx context.Context, instance *RuntimeInstance, force bool) error {
// TODO: Implement remote docker instance stopping.
// Connect to the remote docker host and stop/kill the container.
return fmt.Errorf("remote_docker runtime is not yet implemented")
}
func (r *RemoteDockerRuntime) RecoverInstances(ctx context.Context) ([]*RuntimeInstance, error) {
// Remote docker instances are not recovered on restart.
// The containers on remote hosts are ephemeral.
return nil, nil
}
func (r *RemoteDockerRuntime) GetInteractiveRunner() *process.InteractiveRunner {
// Remote docker does not support passthrough mode.
return nil
}
@@ -118,7 +118,8 @@ type LaunchRequest struct {
ModelOverride string // If set, use this model instead of the profile's model
// Executor configuration - determines which runtime to use
ExecutorType string // Executor type (e.g., "local_pc", "local_docker") - determines runtime
ExecutorType string // Executor type (e.g., "local", "worktree", "local_docker") - determines runtime
ExecutorConfig map[string]string // Executor config (docker_host, git_token, etc.)
// Worktree configuration
UseWorktree bool // Whether to use a Git worktree for isolation
@@ -9,23 +9,24 @@ import (
type Name string
const (
NameUnknown Name = ""
NameDocker Name = "docker"
NameStandalone Name = "standalone"
NameLocal Name = "local"
NameUnknown Name = ""
NameDocker Name = "docker"
NameStandalone Name = "standalone"
NameLocal Name = "local"
NameRemoteDocker Name = "remote_docker"
)
// ExecutorTypeToRuntime maps an ExecutorType to its corresponding runtime Name.
func ExecutorTypeToRuntime(execType models.ExecutorType) Name {
switch execType {
case models.ExecutorTypeLocalPC:
case models.ExecutorTypeLocal:
return NameStandalone
case models.ExecutorTypeWorktree:
return NameStandalone
case models.ExecutorTypeLocalDocker:
return NameDocker
case models.ExecutorTypeRemoteDocker:
// For now, remote docker uses the same runtime as local docker.
// Future: separate runtime for remote docker.
return NameDocker
return NameRemoteDocker
default:
return NameStandalone
}
@@ -186,7 +186,22 @@ Another example:
]
}`),
mcp.WithString("prompt", mcp.Required(), mcp.Description("The question to ask the user. Be specific and clear.")),
mcp.WithArray("options", mcp.Required(), mcp.Description(`Array of option objects. Each option must have: "label" (1-5 words, the clickable choice) and "description" (explanation of the option). Provide 2-4 concrete, actionable options.`)),
mcp.WithArray("options", mcp.Required(), mcp.Description(`Array of option objects. Each option must have: "label" (1-5 words, the clickable choice) and "description" (explanation of the option). Provide 2-4 concrete, actionable options.`),
mcp.Items(map[string]any{
"type": "object",
"properties": map[string]any{
"label": map[string]any{
"type": "string",
"description": "Short text (1-5 words) shown as the clickable option",
},
"description": map[string]any{
"type": "string",
"description": "Brief explanation of what this option means",
},
},
"required": []string{"label", "description"},
}),
),
mcp.WithString("context", mcp.Description("Optional background information to help the user understand why you're asking this question.")),
),
s.askUserQuestionHandler(),
@@ -46,7 +46,7 @@ type StartTaskRequest struct {
TaskID string `json:"task_id"`
SessionID string `json:"session_id,omitempty"` // If provided, resume this existing session instead of creating new
AgentProfileID string `json:"agent_profile_id,omitempty"` // Required when creating new session (SessionID not provided)
ExecutorID string `json:"executor_id,omitempty"` // Executor to use (determines runtime: local_pc, local_docker, etc.)
ExecutorID string `json:"executor_id,omitempty"` // Executor to use (determines runtime: local, worktree, local_docker, etc.)
Priority int `json:"priority,omitempty"`
Prompt string `json:"prompt,omitempty"` // Initial prompt to send to the agent
WorkflowStepID string `json:"workflow_step_id,omitempty"` // If provided, prompt prefix/suffix and plan mode are applied from the step
@@ -867,6 +867,17 @@ func (s *Service) handleAgentStreamEvent(ctx context.Context, payload *lifecycle
_ = s.eventBus.Publish(ctx, subject, bus.NewEvent(events.AvailableCommandsUpdated, "orchestrator", eventPayload))
}
case "permission_cancelled":
// Handle permission cancellation — mark the permission message as expired
if sessionID != "" && payload.Data.PendingID != "" && s.messageCreator != nil {
if err := s.messageCreator.UpdatePermissionMessage(ctx, sessionID, payload.Data.PendingID, "expired"); err != nil {
s.logger.Warn("failed to mark permission as expired",
zap.String("session_id", sessionID),
zap.String("pending_id", payload.Data.PendingID),
zap.Error(err))
}
}
case "log":
// Handle log events - store agent log messages to the database
if sessionID != "" && s.messageCreator != nil {
@@ -23,6 +23,7 @@ var (
ErrNoAgentProfileID = errors.New("task has no agent_profile_id configured")
ErrExecutionNotFound = errors.New("execution not found")
ErrExecutionAlreadyRunning = errors.New("execution already running")
ErrRemoteDockerNoRepoURL = errors.New("remote_docker executor requires a repository with provider owner and name set")
)
// PromptResult contains the result of a prompt operation
@@ -89,7 +90,8 @@ type LaunchAgentRequest struct {
Env map[string]string
ACPSessionID string // ACP session ID to resume, if available
ModelOverride string // If set, use this model instead of the profile's model
ExecutorType string // Executor type (e.g., "local_pc", "local_docker") - determines runtime
ExecutorType string // Executor type (e.g., "local", "worktree", "local_docker") - determines runtime
ExecutorConfig map[string]string // Executor config (docker_host, git_token, etc.)
// Worktree configuration for concurrent agent execution
UseWorktree bool // Whether to use a Git worktree for isolation
@@ -156,9 +158,8 @@ type Executor struct {
logger *logger.Logger
// Configuration
retryLimit int
retryDelay time.Duration
worktreeEnabled bool // Whether to use Git worktrees for agent isolation
retryLimit int
retryDelay time.Duration
// Per-session locks to prevent concurrent resume/launch operations on the same session.
// This prevents race conditions when the backend restarts and multiple resume requests
@@ -168,8 +169,7 @@ type Executor struct {
// ExecutorConfig holds configuration for the Executor
type ExecutorConfig struct {
WorktreeEnabled bool // Whether to use Git worktrees for agent isolation
ShellPrefs ShellPreferenceProvider
ShellPrefs ShellPreferenceProvider
}
type ShellPreferenceProvider interface {
@@ -179,16 +179,41 @@ type ShellPreferenceProvider interface {
// NewExecutor creates a new executor
func NewExecutor(agentManager AgentManagerClient, repo repository.Repository, log *logger.Logger, cfg ExecutorConfig) *Executor {
return &Executor{
agentManager: agentManager,
repo: repo,
shellPrefs: cfg.ShellPrefs,
logger: log.WithFields(zap.String("component", "executor")),
retryLimit: 3,
retryDelay: 5 * time.Second,
worktreeEnabled: cfg.WorktreeEnabled,
agentManager: agentManager,
repo: repo,
shellPrefs: cfg.ShellPrefs,
logger: log.WithFields(zap.String("component", "executor")),
retryLimit: 3,
retryDelay: 5 * time.Second,
}
}
// shouldUseWorktree returns true if the given executor type should use Git worktrees.
func shouldUseWorktree(executorType string) bool {
return models.ExecutorType(executorType) == models.ExecutorTypeWorktree
}
// repositoryCloneURL builds an HTTPS clone URL from the repository's provider info.
// Returns an empty string if the repository has no provider owner/name or if the
// provider is not recognized.
func repositoryCloneURL(repo *models.Repository) string {
if repo.ProviderOwner == "" || repo.ProviderName == "" {
return ""
}
var host string
switch strings.ToLower(repo.Provider) {
case "github", "":
host = "github.com"
case "gitlab":
host = "gitlab.com"
case "bitbucket":
host = "bitbucket.org"
default:
return ""
}
return fmt.Sprintf("https://%s/%s/%s.git", host, repo.ProviderOwner, repo.ProviderName)
}
// getSessionLock returns a per-session mutex, creating one if it doesn't exist.
// This serializes concurrent resume/launch operations on the same session to prevent
// duplicate agent processes after backend restart.
@@ -223,7 +248,7 @@ func (e *Executor) Execute(ctx context.Context, task *v1.Task) (*TaskExecution,
}
// ExecuteWithProfile starts agent execution for a task using an explicit agent profile.
// The executorID parameter specifies which executor to use (determines runtime: local_pc, local_docker, etc.).
// The executorID parameter specifies which executor to use (determines runtime: local, worktree, local_docker, etc.).
// If executorID is empty, falls back to workspace's default executor.
// The prompt parameter is the initial prompt to send to the agent.
// The workflowStepID parameter associates the session with a workflow step for transitions.
@@ -354,6 +379,7 @@ func (e *Executor) LaunchPreparedSession(ctx context.Context, task *v1.Task, ses
var baseBranch string
var worktreeBranchPrefix string
var pullBeforeWorktree bool
var repository *models.Repository
// Get the primary repository for this task
primaryTaskRepo, err := e.repo.GetPrimaryTaskRepository(ctx, task.ID)
@@ -369,7 +395,7 @@ func (e *Executor) LaunchPreparedSession(ctx context.Context, task *v1.Task, ses
baseBranch = primaryTaskRepo.BaseBranch
if repositoryID != "" {
repository, err := e.repo.GetRepository(ctx, repositoryID)
repository, err = e.repo.GetRepository(ctx, repositoryID)
if err != nil {
e.logger.Error("failed to get repository",
zap.String("repository_id", repositoryID),
@@ -394,19 +420,29 @@ func (e *Executor) LaunchPreparedSession(ctx context.Context, task *v1.Task, ses
SessionID: sessionID,
}
// Resolve executor configuration
execConfig := e.resolveExecutorConfig(ctx, executorID, task.WorkspaceID, metadata)
if execConfig.ExecutorID != "" {
metadata = execConfig.Metadata
req.ExecutorType = execConfig.ExecutorType
req.ExecutorConfig = execConfig.ExecutorCfg
}
if repositoryPath != "" {
req.UseWorktree = e.worktreeEnabled
req.UseWorktree = shouldUseWorktree(execConfig.ExecutorType)
req.RepositoryPath = repositoryPath
req.BaseBranch = baseBranch
req.WorktreeBranchPrefix = worktreeBranchPrefix
req.PullBeforeWorktree = pullBeforeWorktree
}
// Resolve executor configuration
execConfig := e.resolveExecutorConfig(ctx, executorID, task.WorkspaceID, metadata)
if execConfig.ExecutorID != "" {
metadata = execConfig.Metadata
req.ExecutorType = execConfig.ExecutorType
// Remote Docker needs a clone URL since the remote host has no access to the local filesystem.
if models.ExecutorType(execConfig.ExecutorType) == models.ExecutorTypeRemoteDocker && repository != nil {
cloneURL := repositoryCloneURL(repository)
if cloneURL == "" {
return nil, ErrRemoteDockerNoRepoURL
}
req.RepositoryURL = cloneURL
}
if len(metadata) > 0 {
@@ -622,11 +658,12 @@ func (e *Executor) ResumeSession(ctx context.Context, session *models.TaskSessio
var repositoryPath string
var worktreeBranchPrefix string
var pullBeforeWorktree bool
var repository *models.Repository
if repositoryID == "" && len(task.Repositories) > 0 {
repositoryID = task.Repositories[0].RepositoryID
}
if repositoryID != "" {
repository, err := e.repo.GetRepository(ctx, repositoryID)
repository, err = e.repo.GetRepository(ctx, repositoryID)
if err != nil {
e.logger.Error("failed to load repository for task session resume",
zap.String("task_id", task.ID),
@@ -650,7 +687,16 @@ func (e *Executor) ResumeSession(ctx context.Context, session *models.TaskSessio
req.Branch = baseBranch
}
if e.worktreeEnabled && repositoryPath != "" {
// Remote Docker needs a clone URL since the remote host has no access to the local filesystem.
if models.ExecutorType(req.ExecutorType) == models.ExecutorTypeRemoteDocker && repository != nil {
cloneURL := repositoryCloneURL(repository)
if cloneURL == "" {
return nil, ErrRemoteDockerNoRepoURL
}
req.RepositoryURL = cloneURL
}
if shouldUseWorktree(req.ExecutorType) && repositoryPath != "" {
req.UseWorktree = true
req.RepositoryPath = repositoryPath
req.RepositoryID = repositoryID
@@ -998,16 +1044,25 @@ func (e *Executor) SwitchModel(ctx context.Context, taskID, sessionID, newModel,
// Get repository info if available
var repositoryPath string
if session.RepositoryID != "" {
repository, err := e.repo.GetRepository(ctx, session.RepositoryID)
if err == nil && repository != nil {
repository, repoErr := e.repo.GetRepository(ctx, session.RepositoryID)
if repoErr == nil && repository != nil {
repositoryPath = repository.LocalPath
req.RepositoryURL = repository.LocalPath
req.Branch = session.BaseBranch
// Remote Docker needs a clone URL instead of a local path.
if models.ExecutorType(execConfig.ExecutorType) == models.ExecutorTypeRemoteDocker {
cloneURL := repositoryCloneURL(repository)
if cloneURL == "" {
return nil, ErrRemoteDockerNoRepoURL
}
req.RepositoryURL = cloneURL
}
}
}
// Configure worktree if enabled - reuse existing worktree from session
if e.worktreeEnabled && repositoryPath != "" {
// Configure worktree if executor type requires it - reuse existing worktree from session
if shouldUseWorktree(execConfig.ExecutorType) && repositoryPath != "" {
req.UseWorktree = true
req.RepositoryPath = repositoryPath
req.RepositoryID = session.RepositoryID
@@ -1202,41 +1257,11 @@ func (e *Executor) defaultExecutorID(ctx context.Context, workspaceID string) st
return strings.TrimSpace(*workspace.DefaultExecutorID)
}
func (e *Executor) applyExecutorMetadata(ctx context.Context, metadata map[string]interface{}, executorID string) map[string]interface{} {
if executorID == "" {
return metadata
}
if metadata == nil {
metadata = map[string]interface{}{}
}
metadata["executor_id"] = executorID
executor, err := e.repo.GetExecutor(ctx, executorID)
if err != nil || executor == nil {
return metadata
}
if policyJSON := strings.TrimSpace(executor.Config["mcp_policy"]); policyJSON != "" {
metadata["executor_mcp_policy"] = policyJSON
}
return metadata
}
// getExecutorType resolves an executor ID to its type string.
// Returns empty string if executor not found or on error.
func (e *Executor) getExecutorType(ctx context.Context, executorID string) string {
if executorID == "" {
return ""
}
executor, err := e.repo.GetExecutor(ctx, executorID)
if err != nil || executor == nil {
return ""
}
return string(executor.Type)
}
// executorConfig holds resolved executor configuration.
type executorConfig struct {
ExecutorID string
ExecutorType string
ExecutorCfg map[string]string // The executor record's Config map (docker_host, etc.)
Metadata map[string]interface{}
}
@@ -1254,13 +1279,28 @@ func (e *Executor) resolveExecutorConfig(ctx context.Context, executorID, worksp
metadata = make(map[string]interface{})
}
if resolved != "" {
metadata = e.applyExecutorMetadata(ctx, metadata, resolved)
if resolved == "" {
return executorConfig{Metadata: metadata}
}
metadata["executor_id"] = resolved
executor, err := e.repo.GetExecutor(ctx, resolved)
if err != nil || executor == nil {
return executorConfig{
ExecutorID: resolved,
Metadata: metadata,
}
}
if policyJSON := strings.TrimSpace(executor.Config["mcp_policy"]); policyJSON != "" {
metadata["executor_mcp_policy"] = policyJSON
}
return executorConfig{
ExecutorID: resolved,
ExecutorType: e.getExecutorType(ctx, resolved),
ExecutorType: string(executor.Type),
ExecutorCfg: executor.Config,
Metadata: metadata,
}
}
@@ -456,8 +456,7 @@ func newTestExecutor(t *testing.T, agentManager AgentManagerClient, repo *mockRe
t.Fatalf("failed to create logger: %v", err)
}
return NewExecutor(agentManager, repo, log, ExecutorConfig{
WorktreeEnabled: true,
ShellPrefs: &mockShellPrefs{},
ShellPrefs: &mockShellPrefs{},
})
}
@@ -695,3 +694,77 @@ func TestExecuteWithProfile_UsesPrepareThenLaunch(t *testing.T) {
t.Errorf("Expected task ID %s, got %s", task.ID, execution.TaskID)
}
}
func TestShouldUseWorktree(t *testing.T) {
tests := []struct {
executorType string
want bool
}{
{"worktree", true},
{"local", false},
{"local_docker", false},
{"remote_docker", false},
{"", false},
}
for _, tt := range tests {
if got := shouldUseWorktree(tt.executorType); got != tt.want {
t.Errorf("shouldUseWorktree(%q) = %v, want %v", tt.executorType, got, tt.want)
}
}
}
func TestRepositoryCloneURL(t *testing.T) {
tests := []struct {
name string
repo *models.Repository
want string
}{
{
name: "github repo",
repo: &models.Repository{Provider: "github", ProviderOwner: "acme", ProviderName: "app"},
want: "https://github.com/acme/app.git",
},
{
name: "gitlab repo",
repo: &models.Repository{Provider: "gitlab", ProviderOwner: "acme", ProviderName: "app"},
want: "https://gitlab.com/acme/app.git",
},
{
name: "bitbucket repo",
repo: &models.Repository{Provider: "bitbucket", ProviderOwner: "acme", ProviderName: "app"},
want: "https://bitbucket.org/acme/app.git",
},
{
name: "unknown provider returns empty",
repo: &models.Repository{Provider: "custom", ProviderOwner: "acme", ProviderName: "app"},
want: "",
},
{
name: "empty provider defaults to github",
repo: &models.Repository{ProviderOwner: "acme", ProviderName: "app"},
want: "https://github.com/acme/app.git",
},
{
name: "missing owner returns empty",
repo: &models.Repository{Provider: "github", ProviderName: "app"},
want: "",
},
{
name: "missing name returns empty",
repo: &models.Repository{Provider: "github", ProviderOwner: "acme"},
want: "",
},
{
name: "both missing returns empty",
repo: &models.Repository{},
want: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := repositoryCloneURL(tt.repo); got != tt.want {
t.Errorf("repositoryCloneURL() = %q, want %q", got, tt.want)
}
})
}
}
@@ -144,9 +144,7 @@ func createTestExecutor(t *testing.T, agentMgr *mockAgentManager, log *logger.Lo
t.Errorf("failed to close repo: %v", err)
}
})
cfg := executor.ExecutorConfig{
WorktreeEnabled: true,
}
cfg := executor.ExecutorConfig{}
return executor.NewExecutor(agentMgr, repo, log, cfg)
}
@@ -39,17 +39,15 @@ var (
// ServiceConfig holds orchestrator service configuration
type ServiceConfig struct {
Scheduler scheduler.SchedulerConfig
QueueSize int
WorktreeEnabled bool // Whether to use Git worktrees for agent isolation
Scheduler scheduler.SchedulerConfig
QueueSize int
}
// DefaultServiceConfig returns default configuration
func DefaultServiceConfig() ServiceConfig {
return ServiceConfig{
Scheduler: scheduler.DefaultSchedulerConfig(),
QueueSize: 1000,
WorktreeEnabled: true,
Scheduler: scheduler.DefaultSchedulerConfig(),
QueueSize: 1000,
}
}
@@ -197,8 +195,7 @@ func NewService(
// Create the executor with the agent manager client and repository for persistent sessions
execCfg := executor.ExecutorConfig{
WorktreeEnabled: cfg.WorktreeEnabled,
ShellPrefs: shellPrefs,
ShellPrefs: shellPrefs,
}
exec := executor.NewExecutor(agentManager, repo, log, execCfg)
@@ -644,6 +644,15 @@ func (s *Service) RespondToPermission(ctx context.Context, sessionID, pendingID,
// Respond to the permission via agentctl
if err := s.executor.RespondToPermission(ctx, sessionID, pendingID, optionID, cancelled); err != nil {
// Permission likely expired — update message so frontend reflects this
if s.messageCreator != nil {
if updateErr := s.messageCreator.UpdatePermissionMessage(ctx, sessionID, pendingID, "expired"); updateErr != nil {
s.logger.Warn("failed to mark expired permission message",
zap.String("session_id", sessionID),
zap.String("pending_id", pendingID),
zap.Error(updateErr))
}
}
return err
}
@@ -103,7 +103,7 @@ func (h *ProcessHandlers) httpStartProcess(c *gin.Context) {
}
}
if executorID == "" {
executorID = models.ExecutorIDLocalPC
executorID = models.ExecutorIDLocal
}
}
executor, err := h.service.GetExecutor(c.Request.Context(), executorID)
@@ -210,7 +210,7 @@ func (h *ProcessHandlers) httpStartProcess(c *gin.Context) {
}
switch executor.Type {
case models.ExecutorTypeLocalPC, models.ExecutorTypeLocalDocker:
case models.ExecutorTypeLocal, models.ExecutorTypeWorktree, models.ExecutorTypeLocalDocker:
if streams.ProcessKind(kind) == streams.ProcessKindDev {
if existing, err := h.lifecycleMgr.ListProcesses(c.Request.Context(), sessionID); err == nil {
for _, proc := range existing {
@@ -293,7 +293,7 @@ func (h *ProcessHandlers) httpStopProcessByID(c *gin.Context) {
}
}
if executorID == "" {
executorID = models.ExecutorIDLocalPC
executorID = models.ExecutorIDLocal
}
}
executor, err := h.service.GetExecutor(c.Request.Context(), executorID)
@@ -303,7 +303,7 @@ func (h *ProcessHandlers) httpStopProcessByID(c *gin.Context) {
}
switch executor.Type {
case models.ExecutorTypeLocalPC, models.ExecutorTypeLocalDocker:
case models.ExecutorTypeLocal, models.ExecutorTypeWorktree, models.ExecutorTypeLocalDocker:
proc, err := h.lifecycleMgr.GetProcess(c.Request.Context(), processID, false)
if err != nil {
handleNotFound(c, h.logger, err, "process not found")
@@ -349,7 +349,7 @@ func (h *ProcessHandlers) httpListProcesses(c *gin.Context) {
}
}
if executorID == "" {
executorID = models.ExecutorIDLocalPC
executorID = models.ExecutorIDLocal
}
}
executor, err := h.service.GetExecutor(c.Request.Context(), executorID)
@@ -358,7 +358,7 @@ func (h *ProcessHandlers) httpListProcesses(c *gin.Context) {
return
}
switch executor.Type {
case models.ExecutorTypeLocalPC, models.ExecutorTypeLocalDocker:
case models.ExecutorTypeLocal, models.ExecutorTypeWorktree, models.ExecutorTypeLocalDocker:
listCtx, cancel := context.WithTimeout(c.Request.Context(), 2*time.Second)
defer cancel()
procs, err := h.lifecycleMgr.ListProcesses(listCtx, sessionID)
@@ -410,7 +410,7 @@ func (h *ProcessHandlers) httpGetProcess(c *gin.Context) {
}
}
if executorID == "" {
executorID = models.ExecutorIDLocalPC
executorID = models.ExecutorIDLocal
}
}
executor, err := h.service.GetExecutor(c.Request.Context(), executorID)
@@ -420,7 +420,7 @@ func (h *ProcessHandlers) httpGetProcess(c *gin.Context) {
}
includeOutput := c.Query("include_output") == "true"
switch executor.Type {
case models.ExecutorTypeLocalPC, models.ExecutorTypeLocalDocker:
case models.ExecutorTypeLocal, models.ExecutorTypeWorktree, models.ExecutorTypeLocalDocker:
proc, err := h.lifecycleMgr.GetProcess(c.Request.Context(), processID, includeOutput)
if err != nil {
handleNotFound(c, h.logger, err, "process not found")
@@ -524,7 +524,7 @@ func TestStopProcessRejectsDifferentSession(t *testing.T) {
"session-a": {ID: "session-a", TaskID: "task-1", ExecutorID: "exec-1"},
},
executors: map[string]*models.Executor{
"exec-1": {ID: "exec-1", Type: models.ExecutorTypeLocalPC},
"exec-1": {ID: "exec-1", Type: models.ExecutorTypeLocal},
},
}
svc := service.NewService(repo, nil, log, service.RepositoryDiscoveryConfig{})
@@ -583,7 +583,7 @@ func TestStopProcessAgentctlUnavailable(t *testing.T) {
"session-a": {ID: "session-a", TaskID: "task-1", ExecutorID: "exec-1"},
},
executors: map[string]*models.Executor{
"exec-1": {ID: "exec-1", Type: models.ExecutorTypeLocalPC},
"exec-1": {ID: "exec-1", Type: models.ExecutorTypeLocal},
},
}
svc := service.NewService(repo, nil, log, service.RepositoryDiscoveryConfig{})
+6 -7
View File
@@ -316,17 +316,16 @@ type RepositoryScript struct {
type ExecutorType string
const (
ExecutorTypeLocalPC ExecutorType = "local_pc"
ExecutorTypeLocalDocker ExecutorType = "local_docker"
ExecutorTypeLocal ExecutorType = "local"
ExecutorTypeWorktree ExecutorType = "worktree"
ExecutorTypeLocalDocker ExecutorType = "local_docker"
ExecutorTypeRemoteDocker ExecutorType = "remote_docker"
ExecutorTypeRemoteVPS ExecutorType = "remote_vps"
ExecutorTypeK8s ExecutorType = "k8s"
)
const (
ExecutorIDLocalPC = "exec-local-pc"
ExecutorIDLocalDocker = "exec-local-docker"
ExecutorIDRemoteDocker = "exec-remote-docker"
ExecutorIDLocal = "exec-local"
ExecutorIDWorktree = "exec-worktree"
ExecutorIDLocalDocker = "exec-local-docker"
)
// ExecutorStatus represents executor availability.
@@ -112,9 +112,18 @@ func (r *Repository) ensureDefaultExecutorsAndEnvironments() error {
config map[string]string
}{
{
id: models.ExecutorIDLocalPC,
name: "Local PC",
execType: models.ExecutorTypeLocalPC,
id: models.ExecutorIDLocal,
name: "Local",
execType: models.ExecutorTypeLocal,
status: models.ExecutorStatusActive,
isSystem: true,
resumable: true,
config: map[string]string{},
},
{
id: models.ExecutorIDWorktree,
name: "Worktree",
execType: models.ExecutorTypeWorktree,
status: models.ExecutorStatusActive,
isSystem: true,
resumable: true,
@@ -146,10 +155,13 @@ func (r *Repository) ensureDefaultExecutorsAndEnvironments() error {
}
}
} else {
if _, err := r.db.ExecContext(ctx, `
UPDATE executors SET is_system = 1 WHERE id = ?
`, models.ExecutorIDLocalPC); err != nil {
return err
// Ensure system executors have is_system flag set
for _, systemID := range []string{models.ExecutorIDLocal, models.ExecutorIDWorktree} {
if _, err := r.db.ExecContext(ctx, `
UPDATE executors SET is_system = 1 WHERE id = ?
`, systemID); err != nil {
return err
}
}
}
@@ -2282,6 +2282,19 @@ func (s *Service) UpdatePermissionMessage(ctx context.Context, sessionID, pendin
// Publish message.updated event
s.publishMessageEvent(ctx, events.MessageUpdated, message)
// When a permission expires, also mark the related tool call as cancelled
// so the UI no longer shows a loading spinner on the tool call.
if status == "expired" {
if toolCallID, ok := message.Metadata["tool_call_id"].(string); ok && toolCallID != "" {
if err := s.UpdateToolCallMessage(ctx, sessionID, toolCallID, "error", "", "", nil); err != nil {
s.logger.Warn("failed to cancel related tool call message",
zap.String("tool_call_id", toolCallID),
zap.String("pending_id", pendingID),
zap.Error(err))
}
}
}
s.logger.Info("permission message updated",
zap.String("message_id", message.ID),
zap.String("pending_id", pendingID),
+1 -1
View File
@@ -68,7 +68,7 @@ function CommandInput({
}: React.ComponentProps<typeof CommandPrimitive.Input>) {
return (
<div data-slot="command-input-wrapper" className="p-1 pb-0">
<InputGroup className="bg-input/20 dark:bg-input/30 h-8!">
<InputGroup className="bg-input/20 dark:bg-input/30 h-8! border-0">
<CommandPrimitive.Input
data-slot="command-input"
className={cn(
+5 -1
View File
@@ -51,7 +51,7 @@ export default async function Page({ searchParams }: PageProps) {
activeId: activeWorkspaceId,
},
userSettings: {
workspaceId: settingsWorkspaceId,
workspaceId: activeWorkspaceId,
boardId: settingsBoardId,
repositoryIds: settingsRepositoryIds,
preferredShell: userSettings?.preferred_shell || null,
@@ -86,6 +86,10 @@ export default async function Page({ searchParams }: PageProps) {
boardList.boards[0]?.id;
initialState = {
...initialState,
userSettings: {
...(initialState.userSettings as AppState['userSettings']),
boardId: boardId ?? null,
},
boards: {
items: boardList.boards.map((board) => ({
id: board.id,
+13 -8
View File
@@ -2,7 +2,7 @@
import { use, useMemo, useState } from 'react';
import { useRouter } from 'next/navigation';
import { IconCpu, IconServer, IconTrash } from '@tabler/icons-react';
import { IconTrash } from '@tabler/icons-react';
import { Button } from '@kandev/ui/button';
import { Card, CardContent, CardHeader, CardTitle, CardDescription } from '@kandev/ui/card';
import { Input } from '@kandev/ui/input';
@@ -21,6 +21,7 @@ import { updateExecutorAction, deleteExecutorAction } from '@/app/actions/execut
import { getWebSocketClient } from '@/lib/ws/connection';
import { useAppStore } from '@/components/state-provider';
import type { Executor } from '@/lib/types/http';
import { getExecutorIcon } from '@/lib/executor-icons';
export default function ExecutorEditPage({ params }: { params: Promise<{ id: string }> }) {
const { id } = use(params);
@@ -61,7 +62,7 @@ function ExecutorEditForm({ executor }: ExecutorEditFormProps) {
const [isDeleting, setIsDeleting] = useState(false);
const isSystem = draft.is_system ?? false;
const isLocalDocker = draft.type === 'local_docker';
const isDockerType = draft.type === 'local_docker' || draft.type === 'remote_docker';
const mcpPolicyError = useMemo(() => {
const value = draft.config?.mcp_policy ?? '';
if (!value.trim()) return null;
@@ -77,7 +78,7 @@ function ExecutorEditForm({ executor }: ExecutorEditFormProps) {
}, [draft.config?.mcp_policy]);
const ExecutorIcon = useMemo(() => {
return draft.type === 'local_pc' ? IconCpu : IconServer;
return getExecutorIcon(draft.type);
}, [draft.type]);
const isDirty = useMemo(() => {
@@ -140,11 +141,15 @@ function ExecutorEditForm({ executor }: ExecutorEditFormProps) {
<div>
<h2 className="text-2xl font-bold">{draft.name}</h2>
<p className="text-sm text-muted-foreground mt-1">
{draft.type === 'local_pc'
? 'Uses locally installed agents on this machine.'
{draft.type === 'local'
? 'Runs agents directly in the repository folder.'
: draft.type === 'worktree'
? 'Creates git worktrees for isolated agent sessions.'
: draft.type === 'local_docker'
? 'Runs Docker containers on this machine.'
: 'Remote Docker support is coming soon.'}
: draft.type === 'remote_docker'
? 'Connects to a remote Docker host.'
: 'Custom executor.'}
</p>
</div>
<Button variant="outline" size="sm" onClick={() => router.push('/settings/executors')}>
@@ -178,11 +183,11 @@ function ExecutorEditForm({ executor }: ExecutorEditFormProps) {
</CardContent>
</Card>
{isLocalDocker && (
{isDockerType && (
<Card>
<CardHeader>
<CardTitle>Docker Configuration</CardTitle>
<CardDescription>Local Docker host settings.</CardDescription>
<CardDescription>{draft.type === 'remote_docker' ? 'Remote Docker host settings.' : 'Local Docker host settings.'}</CardDescription>
</CardHeader>
<CardContent className="space-y-2">
<Label htmlFor="docker-host">Docker host env value</Label>
+86 -18
View File
@@ -14,7 +14,7 @@ import { getWebSocketClient } from '@/lib/ws/connection';
import { useAppStore } from '@/components/state-provider';
import type { Executor } from '@/lib/types/http';
const EXECUTOR_TYPES = ['local_docker'] as const;
const EXECUTOR_TYPES = ['local_docker', 'remote_docker'] as const;
type ExecutorType = (typeof EXECUTOR_TYPES)[number];
export default function ExecutorCreatePage() {
@@ -35,23 +35,46 @@ function ExecutorCreatePageContent() {
}
return 'local_docker';
});
const [name, setName] = useState('Local Docker');
const [dockerHost, setDockerHost] = useState('unix:///var/run/docker.sock');
const [name, setName] = useState(() => {
if (initialType === 'remote_docker') return 'Remote Docker';
return 'Local Docker';
});
const [dockerHost, setDockerHost] = useState(() => {
if (initialType === 'remote_docker') return 'tcp://';
return 'unix:///var/run/docker.sock';
});
const [dockerTlsVerify, setDockerTlsVerify] = useState('');
const [dockerCertPath, setDockerCertPath] = useState('');
const [gitToken, setGitToken] = useState('');
const [isCreating, setIsCreating] = useState(false);
const executors = useAppStore((state) => state.executors.items);
const setExecutors = useAppStore((state) => state.setExecutors);
const handleCreate = async () => {
if (type !== 'local_docker') {
return;
const handleTypeChange = (value: ExecutorType) => {
setType(value);
if (value === 'local_docker') {
setName('Local Docker');
setDockerHost('unix:///var/run/docker.sock');
} else if (value === 'remote_docker') {
setName('Remote Docker');
setDockerHost('tcp://');
}
};
const handleCreate = async () => {
setIsCreating(true);
try {
const config: Record<string, string> = { docker_host: dockerHost };
if (type === 'remote_docker') {
if (dockerTlsVerify) config.docker_tls_verify = dockerTlsVerify;
if (dockerCertPath) config.docker_cert_path = dockerCertPath;
if (gitToken) config.git_token = gitToken;
}
const payload = {
name,
type,
status: 'active',
config: { docker_host: dockerHost },
config,
};
const client = getWebSocketClient();
const created = client
@@ -64,6 +87,8 @@ function ExecutorCreatePageContent() {
}
};
const isRemoteDocker = type === 'remote_docker';
return (
<div className="space-y-8">
<div>
@@ -78,24 +103,25 @@ function ExecutorCreatePageContent() {
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
{type === 'local_docker' ? <IconServer className="h-4 w-4" /> : <IconCloud className="h-4 w-4" />}
{type === 'local_docker' ? 'Local Docker Executor' : 'Remote Docker Executor'}
{isRemoteDocker ? <IconCloud className="h-4 w-4" /> : <IconServer className="h-4 w-4" />}
{isRemoteDocker ? 'Remote Docker Executor' : 'Local Docker Executor'}
</CardTitle>
<CardDescription>
{type === 'local_docker'
? 'Uses the local Docker daemon on this machine.'
: 'Connects to a remote Docker host (coming soon).'}
{isRemoteDocker
? 'Connects to a remote Docker host. The repository will be cloned inside the container.'
: 'Uses the local Docker daemon on this machine.'}
</CardDescription>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-2">
<Label htmlFor="executor-type">Executor type</Label>
<Select value={type} onValueChange={(value) => setType(value as ExecutorType)}>
<Select value={type} onValueChange={(value) => handleTypeChange(value as ExecutorType)}>
<SelectTrigger id="executor-type">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="local_docker">Local Docker</SelectItem>
<SelectItem value="remote_docker">Remote Docker</SelectItem>
</SelectContent>
</Select>
</div>
@@ -108,18 +134,60 @@ function ExecutorCreatePageContent() {
/>
</div>
<div className="space-y-2">
<Label htmlFor="docker-host">Docker host env value</Label>
<Label htmlFor="docker-host">Docker host</Label>
<Input
id="docker-host"
value={dockerHost}
onChange={(event) => setDockerHost(event.target.value)}
placeholder="unix:///var/run/docker.sock"
disabled={type !== 'local_docker'}
placeholder={isRemoteDocker ? 'tcp://remote:2376 or ssh://user@host' : 'unix:///var/run/docker.sock'}
/>
<p className="text-xs text-muted-foreground">
Repositories will be mounted as volumes at runtime.
{isRemoteDocker
? 'The remote Docker host URL (tcp://, ssh://).'
: 'Repositories will be mounted as volumes at runtime.'}
</p>
</div>
{isRemoteDocker && (
<>
<div className="space-y-2">
<Label htmlFor="docker-tls-verify">TLS verify</Label>
<Select value={dockerTlsVerify} onValueChange={setDockerTlsVerify}>
<SelectTrigger id="docker-tls-verify">
<SelectValue placeholder="Default (no TLS)" />
</SelectTrigger>
<SelectContent>
<SelectItem value="1">Enabled</SelectItem>
<SelectItem value="0">Disabled</SelectItem>
</SelectContent>
</Select>
</div>
<div className="space-y-2">
<Label htmlFor="docker-cert-path">TLS certificate path</Label>
<Input
id="docker-cert-path"
value={dockerCertPath}
onChange={(event) => setDockerCertPath(event.target.value)}
placeholder="/path/to/certs"
/>
<p className="text-xs text-muted-foreground">
Path to TLS certificates for the Docker host.
</p>
</div>
<div className="space-y-2">
<Label htmlFor="git-token">Git token (optional)</Label>
<Input
id="git-token"
type="password"
value={gitToken}
onChange={(event) => setGitToken(event.target.value)}
placeholder="ghp_..."
/>
<p className="text-xs text-muted-foreground">
Personal access token for cloning repositories inside the container. Auto-detected from host environment if not set.
</p>
</div>
</>
)}
</CardContent>
</Card>
@@ -127,7 +195,7 @@ function ExecutorCreatePageContent() {
<Button variant="outline" onClick={() => router.push('/settings/executors')}>
Cancel
</Button>
<Button onClick={handleCreate} disabled={isCreating || type !== 'local_docker'}>
<Button onClick={handleCreate} disabled={isCreating}>
{isCreating ? 'Creating...' : 'Create Executor'}
</Button>
</div>
+22 -21
View File
@@ -1,12 +1,13 @@
'use client';
import Link from 'next/link';
import { IconChevronRight, IconCpu, IconServer } from '@tabler/icons-react';
import { IconChevronRight, IconBrandDocker, IconCloud } from '@tabler/icons-react';
import { Badge } from '@kandev/ui/badge';
import { Card, CardContent } from '@kandev/ui/card';
import { Separator } from '@kandev/ui/separator';
import { useAppStore } from '@/components/state-provider';
import type { Executor } from '@/lib/types/http';
import { getExecutorIcon, getExecutorLabel } from '@/lib/executor-icons';
export default function ExecutorsSettingsPage() {
const executors = useAppStore((state) => state.executors.items);
@@ -16,7 +17,15 @@ export default function ExecutorsSettingsPage() {
label: 'Local Docker',
description: 'Run on the local Docker daemon.',
href: '/settings/executor/new?type=local_docker',
icon: IconServer,
icon: IconBrandDocker,
enabled: true,
},
{
id: 'remote_docker',
label: 'Remote Docker',
description: 'Connect to a remote Docker host.',
href: '/settings/executor/new?type=remote_docker',
icon: IconCloud,
enabled: true,
},
];
@@ -78,22 +87,9 @@ export default function ExecutorsSettingsPage() {
</div>
<div className="grid gap-3">
{executors
.filter((executor: Executor) => executor.type !== 'remote_docker')
.map((executor: Executor) => {
const Icon = executor.type === 'local_pc' ? IconCpu : IconServer;
const typeLabel =
executor.type === 'local_pc'
? 'Local PC'
: executor.type === 'local_docker'
? 'Local Docker'
: executor.type === 'remote_docker'
? 'Remote Docker'
: executor.type === 'remote_vps'
? 'Remote Server'
: executor.type === 'k8s'
? 'K8s'
: 'Remote';
{executors.map((executor: Executor) => {
const Icon = getExecutorIcon(executor.type);
const typeLabel = getExecutorLabel(executor.type);
return (
<Link key={executor.id} href={`/settings/executor/${executor.id}`}>
<Card className="hover:bg-accent transition-colors cursor-pointer">
@@ -115,14 +111,19 @@ export default function ExecutorsSettingsPage() {
</Badge>
)}
</div>
{executor.type === 'local_docker' && executor.config?.docker_host && (
{(executor.type === 'local_docker' || executor.type === 'remote_docker') && executor.config?.docker_host && (
<div className="text-xs text-muted-foreground mt-1">
{executor.config.docker_host}
</div>
)}
{executor.type === 'local_pc' && (
{executor.type === 'local' && (
<div className="text-xs text-muted-foreground mt-1">
Launches agents as local processes in the worktree folder set on the Local environment.
Runs agents directly in the repository folder. No worktree isolation.
</div>
)}
{executor.type === 'worktree' && (
<div className="text-xs text-muted-foreground mt-1">
Creates a git worktree for each session. Agents work in isolated branches.
</div>
)}
</div>
+2 -2
View File
@@ -484,7 +484,7 @@ type CompletionBucket = 'day' | 'week' | 'month';
function CompletedTasksChart({ completedActivity }: { completedActivity: CompletedTaskActivityDTO[] }) {
const [bucket, setBucket] = useState<CompletionBucket>('day');
const safeCompleted = completedActivity ?? [];
const safeCompleted = useMemo(() => completedActivity ?? [], [completedActivity]);
const series = useMemo(() => {
if (safeCompleted.length === 0) {
@@ -602,7 +602,7 @@ function CompletedTasksChart({ completedActivity }: { completedActivity: Complet
}
function MostProductiveSummary({ completedActivity }: { completedActivity: CompletedTaskActivityDTO[] }) {
const safeCompleted = completedActivity ?? [];
const safeCompleted = useMemo(() => completedActivity ?? [], [completedActivity]);
const stats = useMemo(() => {
if (safeCompleted.length === 0) {
+7 -5
View File
@@ -1,7 +1,7 @@
"use client"
import { memo, useState } from "react"
import { IconCheck, IconSelector } from "@tabler/icons-react"
import { IconCheck, IconChevronDown } from "@tabler/icons-react"
import { cn } from "@/lib/utils"
import { Button } from "@kandev/ui/button"
@@ -37,6 +37,7 @@ interface ComboboxProps {
disabled?: boolean
className?: string
triggerClassName?: string
showSearch?: boolean
}
export const Combobox = memo(function Combobox({
@@ -50,6 +51,7 @@ export const Combobox = memo(function Combobox({
disabled = false,
className,
triggerClassName,
showSearch = true,
}: ComboboxProps) {
const [open, setOpen] = useState(false)
@@ -59,7 +61,7 @@ export const Combobox = memo(function Combobox({
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="outline"
variant="ghost"
role="combobox"
aria-expanded={open}
className={cn("w-full justify-between", !disabled && "cursor-pointer", triggerClassName)}
@@ -72,17 +74,17 @@ export const Combobox = memo(function Combobox({
<span className="truncate">{selectedOption?.label || placeholder}</span>
)}
</div>
<IconSelector className="ml-2 h-4 w-4 shrink-0 opacity-50" />
<IconChevronDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className={cn("w-[var(--radix-popover-trigger-width)] max-w-none p-0", className)} align="start">
<PopoverContent className={cn("w-[var(--radix-popover-trigger-width)] min-w-[300px] max-w-none p-0", className)} align="start">
<Command>
{dropdownLabel ? (
<div className="text-muted-foreground px-2 py-1.5 text-xs border-b">
{dropdownLabel}
</div>
) : null}
<CommandInput placeholder={searchPlaceholder} className="h-9" />
{showSearch && <CommandInput placeholder={searchPlaceholder} className="h-9" />}
<CommandList>
<CommandEmpty>{emptyMessage}</CommandEmpty>
<CommandGroup>
@@ -1,11 +1,9 @@
'use client';
import { Badge } from '@kandev/ui/badge';
import { Button } from '@kandev/ui/button';
import { Input } from '@kandev/ui/input';
import { Label } from '@kandev/ui/label';
import { Switch } from '@kandev/ui/switch';
import { Tooltip, TooltipContent, TooltipTrigger } from '@kandev/ui/tooltip';
import { ModelCombobox } from '@/components/settings/model-combobox';
import type { ModelConfig, PermissionSetting, PassthroughConfig } from '@/lib/types/http';
@@ -218,6 +218,32 @@ export function SettingsAppSidebar() {
</SidebarMenuButton>
</SidebarMenuItem>
{/* Executors */}
<SidebarMenuItem>
<SidebarMenuButton asChild tooltip="Executors">
<Link href="/settings/executors">
<IconCpu className="h-4 w-4" />
<span>Executors</span>
</Link>
</SidebarMenuButton>
{executors.length > 0 && (
<SidebarMenuSub className="ml-3 mt-1">
{executors.map((executor: Executor) => (
<SidebarMenuSubItem key={executor.id}>
<SidebarMenuSubButton
asChild
isActive={pathname === `/settings/executor/${executor.id}`}
>
<Link href={`/settings/executor/${executor.id}`}>
<span>{executor.name}</span>
</Link>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
))}
</SidebarMenuSub>
)}
</SidebarMenuItem>
{/* Environments */}
<SidebarMenuItem>
<SidebarMenuButton asChild tooltip="Environments">
@@ -243,34 +269,6 @@ export function SettingsAppSidebar() {
</SidebarMenuSub>
)}
</SidebarMenuItem>
{/* Executors */}
<SidebarMenuItem>
<SidebarMenuButton asChild tooltip="Executors">
<Link href="/settings/executors">
<IconCpu className="h-4 w-4" />
<span>Executors</span>
</Link>
</SidebarMenuButton>
{executors.filter((executor: Executor) => executor.type !== 'remote_docker').length > 0 && (
<SidebarMenuSub className="ml-3 mt-1">
{executors
.filter((executor: Executor) => executor.type !== 'remote_docker')
.map((executor: Executor) => (
<SidebarMenuSubItem key={executor.id}>
<SidebarMenuSubButton
asChild
isActive={pathname === `/settings/executor/${executor.id}`}
>
<Link href={`/settings/executor/${executor.id}`}>
<span>{executor.name}</span>
</Link>
</SidebarMenuSubButton>
</SidebarMenuSubItem>
))}
</SidebarMenuSub>
)}
</SidebarMenuItem>
</SidebarMenu>
</SidebarGroupContent>
</SidebarGroup>
+252 -187
View File
@@ -3,7 +3,7 @@
import { useEffect, useRef, useState, FormEvent, memo, useMemo, useCallback } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { IconSettings, IconLoader2 } from '@tabler/icons-react';
import { IconLoader2, IconGitBranch } from '@tabler/icons-react';
import {
Dialog,
DialogContent,
@@ -16,13 +16,6 @@ import { Label } from '@kandev/ui/label';
import { Input } from '@kandev/ui/input';
import { Textarea } from '@kandev/ui/textarea';
import { Button } from '@kandev/ui/button';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@kandev/ui/select';
import { Combobox } from './combobox';
import { Badge } from '@kandev/ui/badge';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@kandev/ui/tooltip';
@@ -49,6 +42,7 @@ import { discoverRepositoriesAction, listLocalRepositoryBranchesAction } from '@
import { getLocalStorage, setLocalStorage } from '@/lib/local-storage';
import { STORAGE_KEYS } from '@/lib/settings/constants';
import { linkToSession } from '@/lib/links';
import { getExecutorIcon } from '@/lib/executor-icons';
interface TaskCreateDialogProps {
open: boolean;
@@ -93,6 +87,7 @@ type RepositorySelectorProps = {
placeholder: string;
searchPlaceholder: string;
emptyMessage: string;
triggerClassName?: string;
};
const RepositorySelector = memo(function RepositorySelector({
@@ -103,6 +98,7 @@ const RepositorySelector = memo(function RepositorySelector({
placeholder,
searchPlaceholder,
emptyMessage,
triggerClassName,
}: RepositorySelectorProps) {
return (
<Combobox
@@ -115,6 +111,7 @@ const RepositorySelector = memo(function RepositorySelector({
disabled={disabled}
dropdownLabel="Repository"
className={disabled ? undefined : 'cursor-pointer'}
triggerClassName={triggerClassName}
/>
);
});
@@ -192,9 +189,76 @@ const AgentSelector = memo(function AgentSelector({
);
});
type ExecutorSelectorProps = {
options: Array<{ value: string; label: string; renderLabel?: () => React.ReactNode }>;
value: string;
onValueChange: (value: string) => void;
disabled: boolean;
placeholder: string;
triggerClassName?: string;
};
const ExecutorSelector = memo(function ExecutorSelector({
options,
value,
onValueChange,
disabled,
placeholder,
triggerClassName,
}: ExecutorSelectorProps) {
return (
<Combobox
options={options}
value={value}
onValueChange={onValueChange}
placeholder={placeholder}
emptyMessage="No executor found."
disabled={disabled}
dropdownLabel="Executor"
className={disabled ? undefined : 'cursor-pointer'}
triggerClassName={triggerClassName}
showSearch={false}
/>
);
});
type InlineTaskNameProps = {
value: string;
onChange: (value: string) => void;
autoFocus?: boolean;
};
const InlineTaskName = memo(function InlineTaskName({
value,
onChange,
autoFocus,
}: InlineTaskNameProps) {
const inputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (autoFocus && inputRef.current) {
inputRef.current.focus();
inputRef.current.select();
}
}, [autoFocus]);
return (
<input
ref={inputRef}
type="text"
value={value}
onChange={(e) => onChange(e.target.value)}
placeholder="task-name"
size={Math.max(value.length, 9)}
className="bg-transparent border-none outline-none focus:ring-0 text-sm font-medium min-w-0 rounded-md px-1.5 py-0.5 -mx-1.5 hover:bg-muted focus:bg-muted transition-colors"
/>
);
});
// Memoized text inputs to prevent re-rendering the entire dialog on every keystroke
type TaskFormInputsProps = {
isSessionMode: boolean;
showTitleInput: boolean;
initialTitle: string;
initialDescription: string;
onTitleChange: (hasContent: boolean) => void;
@@ -206,6 +270,7 @@ type TaskFormInputsProps = {
const TaskFormInputs = memo(function TaskFormInputs({
isSessionMode,
showTitleInput,
initialTitle,
initialDescription,
onTitleChange,
@@ -265,10 +330,9 @@ const TaskFormInputs = memo(function TaskFormInputs({
return (
<>
{!isSessionMode && (
{showTitleInput && !isSessionMode && (
<div>
<Input
autoFocus
required
placeholder="Enter task title..."
value={title}
@@ -277,29 +341,15 @@ const TaskFormInputs = memo(function TaskFormInputs({
/>
</div>
)}
{isSessionMode && (
<div>
<Label htmlFor="task-title">Task</Label>
<Input
id="task-title"
value={title}
disabled
placeholder="Task"
className="bg-muted cursor-not-allowed mt-1.5"
/>
</div>
)}
<div>
{isSessionMode && <Label htmlFor="prompt">Prompt</Label>}
<Textarea
id={isSessionMode ? 'prompt' : undefined}
ref={textareaRef}
placeholder={isSessionMode ? 'Describe what you want the agent to do...' : 'Write a prompt for the agent...'}
value={description}
onChange={handleDescriptionChange}
onKeyDown={onKeyDown}
rows={2}
className={isSessionMode ? 'min-h-[120px] max-h-[240px] resize-none overflow-auto mt-1.5' : 'min-h-[96px] max-h-[240px] resize-y overflow-auto'}
className={isSessionMode ? 'min-h-[120px] max-h-[240px] resize-none overflow-auto' : 'min-h-[96px] max-h-[240px] resize-y overflow-auto'}
required={isSessionMode}
/>
</div>
@@ -326,8 +376,10 @@ export function TaskCreateDialog({
const router = useRouter();
const isSessionMode = mode === 'session';
const isEditMode = submitLabel !== 'Create';
const isCreateMode = !isEditMode && !isSessionMode;
const [isCreatingSession, setIsCreatingSession] = useState(false);
const [isCreatingTask, setIsCreatingTask] = useState(false);
const [taskName, setTaskName] = useState('');
// Track only whether inputs have content (not the actual values) to minimize re-renders
const [hasTitle, setHasTitle] = useState(Boolean(initialValues?.title?.trim()));
const [hasDescription, setHasDescription] = useState(Boolean(initialValues?.description?.trim()));
@@ -340,7 +392,6 @@ export function TaskCreateDialog({
const [agentProfileId, setAgentProfileId] = useState('');
const [environmentId, setEnvironmentId] = useState('');
const [executorId, setExecutorId] = useState('');
const [showAdvancedSettings, setShowAdvancedSettings] = useState(false);
const [discoveredRepositories, setDiscoveredRepositories] = useState<LocalRepository[]>([]);
const [discoveredRepoPath, setDiscoveredRepoPath] = useState('');
const [selectedLocalRepo, setSelectedLocalRepo] = useState<LocalRepository | null>(null);
@@ -353,6 +404,21 @@ export function TaskCreateDialog({
const executors = useAppStore((state) => state.executors.items);
const environments = useAppStore((state) => state.environments.items);
const settingsData = useAppStore((state) => state.settingsData);
// Derive repository name from store for session mode header
const activeTaskId = useAppStore((state) => state.tasks.activeTaskId);
const kanbanTasks = useAppStore((state) => state.kanban.tasks);
const reposByWorkspace = useAppStore((state) => state.repositories.itemsByWorkspaceId);
const sessionRepoName = useMemo(() => {
if (!isSessionMode) return undefined;
const activeTask = activeTaskId ? kanbanTasks.find((t) => t.id === activeTaskId) : null;
const repoId = activeTask?.repositoryId;
if (!repoId) return undefined;
for (const repos of Object.values(reposByWorkspace)) {
const repo = repos.find((r) => r.id === repoId);
if (repo) return repo.name;
}
return undefined;
}, [isSessionMode, activeTaskId, kanbanTasks, reposByWorkspace]);
const { toast } = useToast();
useSettingsData(open);
const { repositories, isLoading: repositoriesLoading } = useRepositories(workspaceId, open);
@@ -361,12 +427,17 @@ export function TaskCreateDialog({
Boolean(open && repositoryId)
);
const agentProfilesLoading = open && !settingsData.agentsLoaded;
const environmentsLoading = open && !settingsData.environmentsLoaded;
const executorsLoading = open && !settingsData.executorsLoaded;
useEffect(() => {
if (!open) return;
setHasTitle(Boolean(initialValues?.title?.trim()));
if (isCreateMode) {
const name = initialValues?.title || '';
setTaskName(name);
setHasTitle(name.trim().length > 0);
} else {
setHasTitle(Boolean(initialValues?.title?.trim()));
}
setHasDescription(Boolean(initialValues?.description?.trim()));
setRepositoryId(initialValues?.repositoryId ?? '');
setBranch(initialValues?.branch ?? '');
@@ -375,6 +446,7 @@ export function TaskCreateDialog({
setEnvironmentId('');
setExecutorId('');
}, [
isCreateMode,
isEditMode,
initialValues?.branch,
initialValues?.description,
@@ -495,6 +567,12 @@ export function TaskCreateDialog({
setLocalStorage(STORAGE_KEYS.LAST_AGENT_PROFILE_ID, value);
}, []);
// Memoized callback for InlineTaskName
const handleTaskNameChange = useCallback((value: string) => {
setTaskName(value);
setHasTitle(value.trim().length > 0);
}, []);
// Memoized callback for BranchSelector to save selection to localStorage
const handleBranchChange = useCallback((value: string) => {
setBranch(value);
@@ -550,6 +628,16 @@ export function TaskCreateDialog({
];
}, [repositories, discoveredRepositories]);
// Header-only repository options: name only, no path badge
const headerRepositoryOptions = useMemo(() => {
return repositoryOptions.map((opt) => ({
...opt,
renderLabel: () => (
<span className="truncate">{opt.label}</span>
),
}));
}, [repositoryOptions]);
// Memoize branch options to prevent re-renders when typing
const branchOptions = useMemo(() => {
return branchOptionsRaw.map((branchObj: Branch) => {
@@ -562,10 +650,13 @@ export function TaskCreateDialog({
label: displayName,
renderLabel: () => (
<span className="flex min-w-0 flex-1 items-center justify-between gap-2">
<span className="truncate" title={displayName}>
{displayName}
<span className="flex min-w-0 items-center gap-1.5">
<IconGitBranch className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span className="truncate" title={displayName}>
{displayName}
</span>
</span>
<Badge variant={branchObj.type === 'local' ? 'default' : 'secondary'} className="text-xs">
<Badge variant="outline" className="text-xs">
{branchObj.type === 'local' ? 'local' : branchObj.remote || 'remote'}
</Badge>
</span>
@@ -587,7 +678,7 @@ export function TaskCreateDialog({
<span className="flex min-w-0 flex-1 items-center justify-between gap-2">
<span className="truncate">{agentLabel}</span>
{profileLabel ? (
<Badge variant="secondary" className="text-xs">
<Badge variant="outline" className="text-xs">
{profileLabel}
</Badge>
) : null}
@@ -597,6 +688,29 @@ export function TaskCreateDialog({
});
}, [agentProfiles]);
const executorOptions = useMemo(() => {
return executors.map((executor: Executor) => {
const Icon = getExecutorIcon(executor.type);
return {
value: executor.id,
label: executor.name,
renderLabel: () => (
<span className="flex min-w-0 flex-1 items-center gap-2">
<Icon className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span className="truncate">{executor.name}</span>
</span>
),
};
});
}, [executors]);
const executorHint = useMemo(() => {
const selectedExecutor = executors.find((e: Executor) => e.id === executorId);
if (selectedExecutor?.type === 'worktree') return 'A git worktree will be created from the base branch.';
if (selectedExecutor?.type === 'local') return 'The agent will run directly on the repository.';
return null;
}, [executors, executorId]);
useEffect(() => {
if (!open || !workspaceId || !selectedLocalRepo) return;
setLocalBranchesLoading(true);
@@ -719,7 +833,6 @@ export function TaskCreateDialog({
setAgentProfileId('');
setExecutorId('');
setEnvironmentId('');
setShowAdvancedSettings(false);
onOpenChange(false);
return;
}
@@ -760,7 +873,6 @@ export function TaskCreateDialog({
setAgentProfileId('');
setExecutorId('');
setEnvironmentId('');
setShowAdvancedSettings(false);
// Navigate to the new session (this will unmount the dialog)
if (newSessionId) {
@@ -781,7 +893,9 @@ export function TaskCreateDialog({
}
// Task mode - create or edit task
const trimmedTitle = title.trim();
const trimmedTitle = isEditMode
? title.trim()
: taskName.trim();
if (!trimmedTitle) return;
if (isEditMode && editingTask) {
try {
@@ -891,6 +1005,7 @@ export function TaskCreateDialog({
// Reset form and close dialog
setHasTitle(false);
setHasDescription(false);
setTaskName('');
setRepositoryId('');
setBranch('');
setStartAgent(!isEditMode);
@@ -918,6 +1033,7 @@ export function TaskCreateDialog({
const handleCancel = () => {
setHasTitle(false);
setHasDescription(false);
setTaskName('');
setRepositoryId('');
setBranch('');
setStartAgent(!isEditMode);
@@ -931,15 +1047,57 @@ export function TaskCreateDialog({
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="w-full h-full max-w-full max-h-full rounded-none sm:w-[900px] sm:h-auto sm:max-w-none sm:max-h-[85vh] sm:rounded-lg flex flex-col bg-card">
<DialogHeader>
<DialogTitle>
{isSessionMode ? 'Create New Session' : submitLabel === 'Create' ? 'Create Task' : 'Edit Task'}
</DialogTitle>
{isCreateMode ? (
<DialogTitle asChild>
<div className="flex items-center gap-1 min-w-0 text-sm font-medium">
<RepositorySelector
options={headerRepositoryOptions}
value={repositoryId || discoveredRepoPath}
onValueChange={handleRepositoryChange}
placeholder={
!workspaceId
? 'Select workspace first'
: repositoriesLoading || discoverReposLoading
? 'Loading...'
: 'Select repository'
}
searchPlaceholder="Search repositories..."
emptyMessage={
repositoriesLoading || discoverReposLoading
? 'Loading repositories...'
: 'No repositories found.'
}
disabled={!workspaceId || repositoriesLoading || discoverReposLoading}
triggerClassName="w-auto text-sm"
/>
<span className="text-muted-foreground mr-2">/</span>
<InlineTaskName value={taskName} onChange={handleTaskNameChange} autoFocus />
</div>
</DialogTitle>
) : isSessionMode ? (
<DialogTitle asChild>
<div className="flex items-center gap-1 min-w-0 text-sm font-medium">
{sessionRepoName && (
<>
<span className="truncate text-muted-foreground">{sessionRepoName}</span>
<span className="text-muted-foreground mx-0.5">/</span>
</>
)}
<span className="truncate">{initialValues?.title || 'Task'}</span>
<span className="text-muted-foreground mx-0.5">/</span>
<span className="text-muted-foreground whitespace-nowrap">new session</span>
</div>
</DialogTitle>
) : (
<DialogTitle>Edit Task</DialogTitle>
)}
</DialogHeader>
<form onSubmit={handleSubmit} className="flex flex-col gap-4 overflow-hidden">
<div className="flex-1 space-y-4 overflow-y-auto pr-1">
<TaskFormInputs
key={`${open}-${initialValues?.title ?? ''}-${initialValues?.description ?? ''}`}
isSessionMode={isSessionMode}
showTitleInput={isEditMode}
initialTitle={initialValues?.title ?? ''}
initialDescription={initialValues?.description ?? ''}
onTitleChange={setHasTitle}
@@ -949,28 +1107,30 @@ export function TaskCreateDialog({
descriptionValueRef={descriptionInputRef}
/>
{!isSessionMode && (
<div className="grid gap-4 grid-cols-1 sm:grid-cols-3">
<div>
<RepositorySelector
options={repositoryOptions}
value={repositoryId || discoveredRepoPath}
onValueChange={handleRepositoryChange}
placeholder={
!workspaceId
? 'Select workspace first'
: repositoriesLoading || discoverReposLoading
<div className={`grid gap-4 grid-cols-1 ${isEditMode ? 'sm:grid-cols-4' : 'sm:grid-cols-3'}`}>
{isEditMode && (
<div>
<RepositorySelector
options={repositoryOptions}
value={repositoryId || discoveredRepoPath}
onValueChange={handleRepositoryChange}
placeholder={
!workspaceId
? 'Select workspace first'
: repositoriesLoading || discoverReposLoading
? 'Loading repositories...'
: 'Select repository'
}
searchPlaceholder="Search repositories..."
emptyMessage={
repositoriesLoading || discoverReposLoading
? 'Loading repositories...'
: 'Select repository'
}
searchPlaceholder="Search repositories..."
emptyMessage={
repositoriesLoading || discoverReposLoading
? 'Loading repositories...'
: 'No repositories found.'
}
disabled={!workspaceId || repositoriesLoading || discoverReposLoading || isEditMode}
/>
</div>
: 'No repositories found.'
}
disabled={!workspaceId || repositoriesLoading || discoverReposLoading || isEditMode}
/>
</div>
)}
<div>
<BranchSelector
options={branchOptions}
@@ -1025,139 +1185,44 @@ export function TaskCreateDialog({
)}
</div>
)}
{startAgent && (
<div>
<ExecutorSelector
options={executorOptions}
value={executorId}
onValueChange={setExecutorId}
placeholder={
executorsLoading
? 'Loading executors...'
: 'Select executor'
}
disabled={executorsLoading || isEditMode}
/>
</div>
)}
</div>
)}
{/* Agent Profile - shown in session mode */}
{/* Agent Profile + Executor - shown in session mode */}
{isSessionMode && (
<div className="flex items-center justify-between gap-3">
<div className="flex items-center gap-3">
<AgentSelector
options={agentProfileOptions}
value={agentProfileId}
onValueChange={handleAgentProfileChange}
placeholder={agentProfilesLoading ? 'Loading agent profiles...' : 'Select agent profile'}
disabled={agentProfilesLoading || isCreatingSession}
triggerClassName="w-[280px]"
/>
</div>
{/* More Options Toggle */}
<button
type="button"
onClick={() => setShowAdvancedSettings(!showAdvancedSettings)}
className="flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors cursor-pointer whitespace-nowrap"
>
<IconSettings className="h-4 w-4" />
More options
</button>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
<AgentSelector
options={agentProfileOptions}
value={agentProfileId}
onValueChange={handleAgentProfileChange}
placeholder={agentProfilesLoading ? 'Loading agent profiles...' : 'Select agent profile'}
disabled={agentProfilesLoading || isCreatingSession}
/>
<ExecutorSelector
options={executorOptions}
value={executorId}
onValueChange={setExecutorId}
placeholder={executorsLoading ? 'Loading executors...' : 'Select executor'}
disabled={executorsLoading || isCreatingSession}
/>
</div>
)}
{!isSessionMode && startAgent && (
<div className="flex items-center justify-end gap-2">
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => setShowAdvancedSettings(!showAdvancedSettings)}
className="text-muted-foreground cursor-pointer"
>
<IconSettings className="h-4 w-4 mr-1" />
{showAdvancedSettings ? 'Hide' : 'More Options'}
</Button>
</div>
)}
{showAdvancedSettings && isSessionMode && (
<div className="pt-2 border-t">
<div className="grid gap-4 md:grid-cols-2">
<div className="flex items-center gap-3">
<Label htmlFor="environment" className="text-sm whitespace-nowrap">
Environment
</Label>
<Select value={environmentId} onValueChange={setEnvironmentId}>
<SelectTrigger id="environment" className="w-full">
<SelectValue placeholder={environmentsLoading ? 'Loading environments...' : 'Select environment'} />
</SelectTrigger>
<SelectContent>
{environments.map((env: Environment) => (
<SelectItem key={env.id} value={env.id}>
{env.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex items-center gap-3">
<Label htmlFor="executor" className="text-sm whitespace-nowrap">
Executor
</Label>
<Select value={executorId} onValueChange={setExecutorId}>
<SelectTrigger id="executor" className="w-full">
<SelectValue placeholder={executorsLoading ? 'Loading executors...' : 'Select executor'} />
</SelectTrigger>
<SelectContent>
{executors.map((executor: Executor) => (
<SelectItem key={executor.id} value={executor.id}>
{executor.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
</div>
)}
{showAdvancedSettings && !isSessionMode && startAgent && (
<div className="grid gap-4 md:grid-cols-2">
<div className="flex items-center gap-3">
<Label className="text-sm whitespace-nowrap">Environment</Label>
<Select value={environmentId} onValueChange={setEnvironmentId} disabled={isEditMode}>
<SelectTrigger className="w-full">
<SelectValue
placeholder={
environmentsLoading
? 'Loading environments...'
: environments.length === 0
? 'No environments available'
: 'Select environment'
}
/>
</SelectTrigger>
<SelectContent>
{environments.map((environment: Environment) => (
<SelectItem key={environment.id} value={environment.id}>
{environment.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div className="flex items-center gap-3">
<Label className="text-sm whitespace-nowrap">Executor</Label>
<Select value={executorId} onValueChange={setExecutorId} disabled={isEditMode}>
<SelectTrigger className="w-full">
<SelectValue
placeholder={
executorsLoading
? 'Loading executors...'
: executors.length === 0
? 'No executors available'
: 'Select executor'
}
/>
</SelectTrigger>
<SelectContent>
{executors.map((executor: Executor) => (
<SelectItem key={executor.id} value={executor.id}>
{executor.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
</div>
)}
</div>
<DialogFooter className="border-t border-border pt-3 flex-col gap-3 sm:flex-row sm:gap-2">
{!isSessionMode && (
@@ -1185,9 +1250,9 @@ export function TaskCreateDialog({
</Tooltip>
</TooltipProvider>
</div>
{startAgent && (
{startAgent && executorHint && (
<span className="text-xs text-muted-foreground">
A git worktree will be created from the base branch.
{executorHint}
</span>
)}
</div>
@@ -51,7 +51,7 @@ export const ImageAttachmentPreview = memo(function ImageAttachmentPreview({
disabled && 'opacity-50'
)}
>
{/* Image thumbnail */}
{/* eslint-disable-next-line @next/next/no-img-element -- base64/blob preview URLs are not compatible with next/image */}
<img
src={attachment.preview}
alt="Attachment preview"
@@ -151,6 +151,7 @@ export const ChatMessage = memo(function ChatMessage({ comment, label, className
{hasAttachments && (
<div className={cn('flex flex-wrap gap-2', hasContent && 'mb-2')}>
{imageAttachments.map((att, index) => (
/* eslint-disable-next-line @next/next/no-img-element -- base64 data URLs are not compatible with next/image */
<img
key={index}
src={`data:${att.mime_type};base64,${att.data}`}
@@ -23,7 +23,7 @@ type PermissionRequestMetadata = {
path?: string;
cwd?: string;
};
status?: 'pending' | 'approved' | 'rejected';
status?: 'pending' | 'approved' | 'rejected' | 'expired';
};
type PermissionRequestMessageProps = {
@@ -34,7 +34,7 @@ export function PermissionRequestMessage({ comment }: PermissionRequestMessagePr
const [isResponding, setIsResponding] = useState(false);
const metadata = comment.metadata as PermissionRequestMetadata | undefined;
const isResolved = metadata?.status === 'approved' || metadata?.status === 'rejected';
const isResolved = metadata?.status === 'approved' || metadata?.status === 'rejected' || metadata?.status === 'expired';
const isPending = !isResolved;
const handleRespond = useCallback(
@@ -99,6 +99,13 @@ export function PermissionRequestMessage({ comment }: PermissionRequestMessagePr
</span>
);
}
if (metadata?.status === 'expired') {
return (
<span className="inline-flex items-center gap-1 text-xs text-muted-foreground">
Expired
</span>
);
}
return (
<span className="inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400">
Pending Approval
+3 -3
View File
@@ -48,6 +48,9 @@ function mergeTreeNodes(existing: FileTreeNode, incoming: FileTreeNode): FileTre
return { ...existing, ...incoming, children: mergedChildren };
}
const MAX_RETRY_ATTEMPTS = 4;
const RETRY_DELAYS_MS = [1000, 2000, 5000, 10000];
type FileBrowserProps = {
sessionId: string;
onOpenFile: (file: OpenFileTab) => void;
@@ -87,9 +90,6 @@ export function FileBrowser({ sessionId, onOpenFile, onDeleteFile, isSearchOpen
const retryTimerRef = useRef<NodeJS.Timeout | null>(null);
const loadInFlightRef = useRef(false);
const MAX_RETRY_ATTEMPTS = 4;
const RETRY_DELAYS_MS = [1000, 2000, 5000, 10000];
// Workspace path for header
const fullPath = session?.worktree_path ?? '';
const displayPath = fullPath.replace(/^\/(?:Users|home)\/[^/]+\//, '~/');
@@ -21,6 +21,7 @@ export function FileImageViewer({ path, content, worktreePath }: FileImageViewer
</div>
</div>
<div className="flex-1 flex items-center justify-center overflow-auto p-6">
{/* eslint-disable-next-line @next/next/no-img-element -- dynamic blob/data URLs from the agent workspace */}
<img
src={src}
alt={path}
+44 -13
View File
@@ -46,29 +46,42 @@ export function useUserDisplaySettings({
const lastAppliedWorkspaceIdRef = useRef<string | null>(null);
const lastAppliedBoardIdRef = useRef<string | null>(null);
// Use a ref for userSettings inside commitSettings to keep the callback stable.
// This prevents cascading effect re-runs when userSettings changes.
const userSettingsRef = useRef(userSettings);
useEffect(() => {
userSettingsRef.current = userSettings;
});
// Track whether redirect effects have initialized (skip first invocation
// after mount — SSR already resolved the correct workspace/board).
const wsInitializedRef = useRef(false);
const boardInitializedRef = useRef(false);
const commitSettings = useCallback(
(next: CommitPayload) => {
const current = userSettingsRef.current;
const repositoryIds = Array.from(new Set(next.repositoryIds)).sort();
const enablePreviewOnClick = next.enablePreviewOnClick ?? userSettings.enablePreviewOnClick;
const enablePreviewOnClick = next.enablePreviewOnClick ?? current.enablePreviewOnClick;
const normalized: DisplaySettings = {
workspaceId: next.workspaceId,
boardId: next.boardId,
repositoryIds,
preferredShell: next.preferredShell ?? userSettings.preferredShell ?? null,
shellOptions: userSettings.shellOptions ?? [],
defaultEditorId: userSettings.defaultEditorId ?? null,
preferredShell: next.preferredShell ?? current.preferredShell ?? null,
shellOptions: current.shellOptions ?? [],
defaultEditorId: current.defaultEditorId ?? null,
enablePreviewOnClick,
chatSubmitKey: userSettings.chatSubmitKey ?? 'cmd_enter',
reviewAutoMarkOnScroll: userSettings.reviewAutoMarkOnScroll ?? true,
chatSubmitKey: current.chatSubmitKey ?? 'cmd_enter',
reviewAutoMarkOnScroll: current.reviewAutoMarkOnScroll ?? true,
loaded: true,
};
const sameWorkspace = normalized.workspaceId === userSettings.workspaceId;
const sameBoard = normalized.boardId === userSettings.boardId;
const samePreview = normalized.enablePreviewOnClick === userSettings.enablePreviewOnClick;
const sameWorkspace = normalized.workspaceId === current.workspaceId;
const sameBoard = normalized.boardId === current.boardId;
const samePreview = normalized.enablePreviewOnClick === current.enablePreviewOnClick;
const sameRepos =
normalized.repositoryIds.length === userSettings.repositoryIds.length &&
normalized.repositoryIds.every((id, index) => id === userSettings.repositoryIds[index]);
if (sameWorkspace && sameBoard && sameRepos && samePreview && userSettings.loaded) {
normalized.repositoryIds.length === current.repositoryIds.length &&
normalized.repositoryIds.every((id, index) => id === current.repositoryIds[index]);
if (sameWorkspace && sameBoard && sameRepos && samePreview && current.loaded) {
return;
}
setUserSettings(normalized);
@@ -92,7 +105,7 @@ export function useUserDisplaySettings({
});
});
},
[setUserSettings, userSettings]
[setUserSettings]
);
useEffect(() => {
@@ -119,8 +132,18 @@ export function useUserDisplaySettings({
});
}, [setUserSettings, userSettings.loaded]);
// Workspace redirect effect — skip first invocation after mount.
// SSR already resolved the correct workspace; only redirect on
// subsequent settings changes (e.g. WebSocket push from another tab).
useEffect(() => {
if (!userSettings.loaded) return;
if (!wsInitializedRef.current) {
wsInitializedRef.current = true;
if (userSettings.workspaceId !== workspaceId) {
lastAppliedWorkspaceIdRef.current = null;
}
return;
}
if (userSettings.workspaceId && userSettings.workspaceId !== workspaceId) {
if (lastAppliedWorkspaceIdRef.current === userSettings.workspaceId) {
return;
@@ -147,8 +170,16 @@ export function useUserDisplaySettings({
}
}, [commitSettings, userSettings.boardId, userSettings.loaded, userSettings.repositoryIds, userSettings.workspaceId, workspaceId]);
// Board redirect effect — skip first invocation after mount.
useEffect(() => {
if (!userSettings.loaded) return;
if (!boardInitializedRef.current) {
boardInitializedRef.current = true;
if (userSettings.boardId !== boardId) {
lastAppliedBoardIdRef.current = null;
}
return;
}
if (userSettings.boardId && userSettings.boardId !== boardId) {
if (lastAppliedBoardIdRef.current === userSettings.boardId) {
return;
+23
View File
@@ -0,0 +1,23 @@
import { IconFolder, IconFolders, IconBrandDocker, IconCloud } from '@tabler/icons-react';
const EXECUTOR_ICON_MAP: Record<string, typeof IconFolder> = {
local: IconFolder,
worktree: IconFolders,
local_docker: IconBrandDocker,
remote_docker: IconCloud,
};
export function getExecutorIcon(type: string): typeof IconFolder {
return EXECUTOR_ICON_MAP[type] ?? IconFolder;
}
const EXECUTOR_LABEL_MAP: Record<string, string> = {
local: 'Local',
worktree: 'Worktree',
local_docker: 'Local Docker',
remote_docker: 'Remote Docker',
};
export function getExecutorLabel(type: string): string {
return EXECUTOR_LABEL_MAP[type] ?? type;
}
+1 -1
View File
@@ -55,7 +55,7 @@ export type KeyValue = {
value: string;
};
export type ExecutorType = 'local_pc' | 'local_docker' | 'remote_docker' | 'remote_vps' | 'k8s';
export type ExecutorType = 'local' | 'worktree' | 'local_docker' | 'remote_docker';
export type ExecutorStatus = 'active' | 'disabled';
export type Executor = {
+17 -7
View File
@@ -42,27 +42,37 @@ describe('truncateRepoPath', () => {
});
describe('selectPreferredBranch', () => {
it('selects origin/main first', () => {
it('selects local main first', () => {
const branches = [
{ name: 'main', type: 'local' },
{ name: 'main', type: 'remote', remote: 'origin' },
];
expect(selectPreferredBranch(branches)).toBe('main');
});
it('prefers local master over origin/main', () => {
const branches = [
{ name: 'master', type: 'local' },
{ name: 'main', type: 'remote', remote: 'origin' },
];
expect(selectPreferredBranch(branches)).toBe('master');
});
it('falls back to origin/main when no local main/master', () => {
const branches = [
{ name: 'main', type: 'remote', remote: 'origin' },
{ name: 'develop', type: 'local' },
];
expect(selectPreferredBranch(branches)).toBe('origin/main');
});
it('falls back to origin/master', () => {
const branches = [
{ name: 'master', type: 'remote', remote: 'origin' },
{ name: 'main', type: 'local' },
];
expect(selectPreferredBranch(branches)).toBe('origin/master');
});
it('falls back to local main', () => {
const branches = [{ name: 'main', type: 'local' }];
expect(selectPreferredBranch(branches)).toBe('main');
});
it('returns null when no preferred branches exist', () => {
const branches = [{ name: 'develop', type: 'local' }];
expect(selectPreferredBranch(branches)).toBeNull();
+7 -7
View File
@@ -121,6 +121,12 @@ type BranchSelectionCandidate = {
export function selectPreferredBranch(
branches: BranchSelectionCandidate[]
): string | null {
const localMain = branches.find((branch) => branch.type === 'local' && branch.name === 'main');
if (localMain) return 'main';
const localMaster = branches.find((branch) => branch.type === 'local' && branch.name === 'master');
if (localMaster) return 'master';
const originMain = branches.find(
(branch) => branch.type === 'remote' && branch.remote === 'origin' && branch.name === 'main'
);
@@ -131,17 +137,11 @@ export function selectPreferredBranch(
);
if (originMaster) return 'origin/master';
const localMain = branches.find((branch) => branch.type === 'local' && branch.name === 'main');
if (localMain) return 'main';
const localMaster = branches.find((branch) => branch.type === 'local' && branch.name === 'master');
if (localMaster) return 'master';
return null;
}
export const DEFAULT_LOCAL_ENVIRONMENT_KIND = 'local_pc';
export const DEFAULT_LOCAL_EXECUTOR_TYPE = 'local_pc';
export const DEFAULT_LOCAL_EXECUTOR_TYPE = 'worktree';
/**
* Format a date string as a human-readable relative time (e.g., "2m ago", "1h ago", "yesterday").
+5 -3
View File
@@ -9,11 +9,13 @@ export function registerUsersHandlers(store: StoreApi<AppState>): WsHandlers {
store.setState((state) => ({
...state,
userSettings: {
workspaceId: message.payload.workspace_id || null,
boardId: message.payload.board_id || null,
...state.userSettings,
// Preserve workspaceId and boardId — these are navigation state
// controlled by SSR and explicit user actions, not WebSocket broadcasts.
// Overwriting them here causes redirect loops when the broadcast
// arrives with a stale workspace/board from a previous commit.
repositoryIds,
preferredShell: message.payload.preferred_shell || null,
shellOptions: state.userSettings.shellOptions ?? [],
defaultEditorId: message.payload.default_editor_id || null,
enablePreviewOnClick: message.payload.enable_preview_on_click ?? false,
chatSubmitKey: (message.payload.chat_submit_key as 'enter' | 'cmd_enter') ?? 'cmd_enter',