feat: agent-native config mode (#396)
* feat: add MCP mode pipeline for config vs task tool registration
Thread McpMode field through the entire instance creation chain:
CreateInstanceRequest → InstanceOverrides → InstanceConfig → MCP Server.
This allows config-mode MCP sessions to register a different set of
tools than the default task-mode sessions.
* feat: add config-mode MCP tools and agentctl handlers
Register config-mode tools (workflow steps, agents, MCP config, tasks)
when MCP server mode is "config". Add 16 new WS action constants and
agentctl-side handlers that forward tool calls to the backend via the
existing BackendClient channel.
* feat: add backend MCP handlers for config-mode operations
Add backend WebSocket handlers for workflow step CRUD, agent CRUD,
MCP config get/update, and task move/delete/archive/state operations.
Wire config dependencies via SetConfigDeps pattern to avoid breaking
the existing NewHandlers constructor.
* feat: add config-mode system prompt and unit tests
Add ConfigContext system prompt listing all config-mode MCP tools.
Add unit tests for mode-based tool registration, agentctl config
handler forwarding, backend handler validation, and system prompt
content.
* test: add exhaustive E2E tests for config-mode MCP handlers
38 end-to-end tests covering the full handler → service → DB pipeline
for all 16 config-mode operations: workflow step CRUD, agent CRUD,
agent profiles, MCP config, and task management (move, delete, archive,
update state). Includes handler registration verification and two
full pipeline integration tests.
* fix: remove E2E test that depends on agent CLIs installed in CI
TestE2E_Agent_CreateMultipleAndList tried to create claude-code and
codex agents, which aren't available in CI. Agents are unique by type
ID so creating duplicates also fails. Removed the test since
CreateAndList already validates the create+list flow.
* test: remove Go E2E tests for config-mode handlers
Replacing with Playwright E2E tests.
* test: add Playwright E2E tests for config-mode features
13 tests covering workflow steps, task operations, agent/profile
settings pages, MCP config, and workflow settings round-trips.
* feat: add dynamic MCP mode reconfiguration for agentctl instances
Add SetMode() to the MCP server that clears and re-registers tools for
the new mode. Expose it via PUT /api/v1/mcp/mode on per-instance servers,
a SetMcpMode client method, and a lifecycle Manager.SetMcpMode wrapper.
This enables switching from task to config MCP tools on workspaces that
were prepared before plan_mode was set on the session.
* feat: wire McpMode through executor launch and resume pipelines
Add McpMode to LaunchOptions so callers can set it at launch time.
StartTask and StartTaskWithSession now pass McpMode="config" when
plan mode is active. startAgentOnExistingWorkspace reconfigures the
MCP server via SetMcpMode before starting the agent subprocess.
The AgentManagerClient interface gains SetMcpMode; the lifecycle
adapter, executor, and all mock implementations are updated.
* fix: pass plan_mode from workflow step when auto-starting moved tasks
handleTaskMovedNoSession was hardcoding planMode=false when calling
StartTask. Now it loads the target step and checks for enable_plan_mode
in on_enter actions, passing the correct value so config-mode MCP tools
are registered for the agent.
* test: fix config-mode E2E tests and add SetMcpMode mock stubs
- Add SetMcpMode stubs to all AgentManager mock implementations
- Fix strict mode violations with { exact: true } on tool name assertions
- Expand collapsed tool call groups before asserting individual names
- Remove temporary diagnostic code
* fix: address CodeRabbit review comments
- Add servers parameter to update_mcp_config tool schema
- Add mutex protection to SetMode for thread safety
- Create session before building prompt so config context has session ID
- Fix inconsistent ask_user_question tool name reference (use _kandev suffix)
* refactor: use canonical ws.ActionMCP constants and handle marshal errors
- Import ActionMCP* constants from pkg/websocket instead of duplicating
them locally in config_handlers.go and handlers.go
- Handle json.MarshalIndent error in forwardToBackend instead of ignoring it
* fix: extract McpModeConfig constant and fix Prettier formatting
- Add McpModeConfig constant to avoid repeated "config" string (goconst)
- Fix Prettier formatting in config-management E2E spec
* fix: validate task state before update and strengthen sysprompt tests
- Add TaskState validation in handleUpdateTaskState to return proper
validation error instead of internal error for invalid states
- Strengthen format-contract assertions (exact %s counts, no %! markers)
- Extract repeated test data into constants per project guidelines
* refactor: decouple config MCP mode from plan_mode, use session metadata
Replace plan_mode-based config MCP activation with config_mode in
session metadata. Add isConfigModeSession() helper used across
executor_execute, executor_interaction, and executor_resume.
Propagate task.Metadata to session.Metadata in PrepareSession so
config_mode flows from task creation through to the agent launch.
* refactor: remove task tools from config MCP mode and update sysprompt
Remove task management tools (list_tasks, move_task, delete_task,
archive_task) from ModeConfig registration — they remain available in
ModeTask. Update ConfigContext system prompt to remove task tool docs
and add example requests section. Update MCP server tests for new tool
count (18→14) and remove deleted task handler tests.
* feat: add config-chat endpoint and workspace config agent profile
Add default_config_agent_profile_id column to workspaces with SQLite
migration. Add POST /workspaces/:id/config-chat endpoint that creates
an ephemeral task with config_mode metadata and starts a session with
config MCP tools. Extract resolveConfigChatDefaults helper to stay
within lint complexity limits.
* feat: add config chat UI with workspace settings integration
Add config chat modal component and hook for starting config sessions.
Add configChat state slice with open/close actions. Add workspace API
client for config-chat endpoint. Add configuration agent profile
selector to workspace settings form. Add config chat button to
settings layout sidebar.
* test: rewrite config-mode E2E tests to use metadata and session_id
Rewrite config-management E2E tests to use createTaskWithAgent with
config_mode metadata instead of a custom fetch helper. Fix navigation
to use task.session_id instead of task.id. Add metadata parameter
support to ApiClient.createTaskWithAgent.
* fix: use floating FAB for config chat and pass default agent profile
Move config chat button from header to a floating action button in the
bottom-right corner with a sparkles icon. Pass the workspace's default
agent profile ID when opening the config chat to avoid "no agent
profile configured" error. Add default_config_agent_profile_id to
workspace slice type.
* feat: async agent launch for config-chat and extract helpers
The config-chat endpoint now launches the agent asynchronously when a
prompt is provided, matching the start_agent flow used by task creation.
Extract deleteTaskOnError and launchConfigChatAgent helpers. Remove
LaunchWorkspace from prepare step to avoid blocking.
* feat: first-interaction agent profile selection for config chat
Open the config chat modal immediately on FAB click. If no default
config agent profile is set, the empty state now shows a profile
selector before starting. The selected profile is saved as the
workspace default_config_agent_profile_id for future sessions.
* test: fix config E2E tests — remove duplicate method, use real tools
Remove duplicate startConfigChat method in ApiClient that overrode the
correct 3-param signature. Replace invalid create_agent test (requires
registered agent type) with update_agent test. Remove fragile tool calls
group UI assertion from multi-tool test.
* fix: resolve 'no active session' error in config chat
Add openConfigChatModal action that only sets isOpen and workspaceId
without touching sessionId. Previously, open() called openConfigChat
with empty sessionId which was truthy, causing QuickChatContent to
render with an invalid session.
* feat: add minimal toolbar mode for config chat input
Thread minimalToolbar prop through ChatInputArea → ChatInputContainer →
ChatInputBody → ChatInputToolbar → QuickChatContent. When enabled,
renders only the submit/cancel button, hiding plan toggle, MCP
indicator, context popover, model selector, and other controls.
* feat: replace config chat dialog with floating popover panel
Replace Dialog with Popover from @kandev/ui so the config chat floats
up from the FAB button. Reduce FAB size to h-12/w-12 with larger h-7/w-7
icon. Rename tooltip to "Configuration Chat". Remove standalone
ConfigChatFAB component from settings layout.
* feat: filter config chat tasks from quick chat listing
Add exclude_config query parameter to ListTasksByWorkspace that filters
out tasks with metadata.config_mode=true. Apply it in the quick chat
sessions API call to prevent config chat tasks from appearing as tabs.
* refactor: move config agent profile setting to agents page
Remove the Configuration Agent Profile selector from workspace settings
and add a dedicated ConfigChatAgentSection to the agents settings page
with auto-save on change.
* feat: redesign config chat empty state with inline text input
Replace clickable template buttons with subtle suggestion hints that
fill the textarea on click and disappear once the user starts typing.
Add a persistent Textarea + send button at the bottom so users can
type directly without clicking templates. This prevents the "no active
session" error since QuickChatContent only renders after startSession
succeeds.
* fix: config chat UX polish — non-clickable suggestions, profile persistence
- Make suggestion prompts purely visual (non-interactive text hints)
- Update workspace store after saving config agent profile so the
profile selector doesn't reappear on subsequent opens
- Use useAppStoreApi for store access in callbacks
* fix: add inline error display and prevent accidental popover dismiss
- Show API errors inline below the input instead of via toast (which
can be hidden behind the popover)
- Prevent popover from closing on outside click via onInteractOutside,
so the user doesn't lose their typed input or active session
- Surface error state from useConfigChat hook to the empty state UI
* fix: use config-specific placeholder in config chat input
Add placeholderOverride prop through ChatInputArea and QuickChatContent
so the config chat shows "Ask anything about your configuration..."
instead of the default "Continue working on the task..." placeholder.
* feat: add default_config_agent_profile_id to workspace DTO and API
Wire the field through WorkspaceDTO, FromWorkspace(), HTTP/WS request
structs, service layer, and public API types so the config chat default
profile persists across page reloads and SSR hydration.
* feat: add config chat store actions and prompt delivery via WS
Add configChat slice actions (open, close, rename, tab management),
pendingPrompt state in useConfigChat hook, and initialPrompt support
in QuickChatContent so prompts are delivered via WS after subscription
is established rather than via HTTP (avoiding race condition).
* fix: resolve dual store issue and message fetch race condition
Replace StateProvider with StateHydrator in settings layout to prevent
a shadow Zustand store that intercepted WS events. Fix message fetch
race condition by merging WS-delivered messages with fetch results
instead of replacing them.
* feat: make config chat global with command panel integration
Add ConfigChatProvider at root layout so the popover is available on all
pages. FAB button only visible on settings pages; hidden anchor on other
pages for popover positioning. Add "Configuration Chat" command to the
command panel (Cmd+K). Add close button and header bar to the popover.
* test: add E2E tests for config chat popover and command panel
Add tests for opening config chat via FAB on settings page (with full
agent response flow) and opening via command panel on kanban page.
Fix api-client endpoint and add workspace update fields for E2E setup.
* fix: compress props destructuring to satisfy max-lines-per-function lint
Rebase merged both sides' additions into ChatInputEditorArea and
ChatInputToolbar, pushing them over the 100-line function limit.
Use object parameter with compact destructuring to reduce line count.
* fix: register config task tools and add exhaustive E2E coverage
Config-mode MCP task tools (list_tasks, move_task, delete_task,
archive_task) were defined but never registered — registerConfigTaskTools()
was never called in registerTools(). Fixed the registration and expanded
E2E tests from 5 to 15, covering all testable config-mode MCP tools
(workflow, agent, MCP config, and task management) with API-side
verification of side effects.
* feat: replace create/delete agent with create/delete agent profile in config mode
Agent creation/deletion via MCP isn't practical since agents map to
registered types. Replace with create_agent_profile and
delete_agent_profile tools that manage the per-agent configuration
presets users actually need to work with. Wires full chain: agentctl
MCP tools → WS actions → backend handlers → controller layer.
* chore: fix Prettier formatting
* fix: compress props destructuring to satisfy max-lines-per-function lint
* test: update MCP tests for agent profile tools and correct config tool count
* fix: address CodeRabbit review — normalize MCP mode, set default, consolidate tests
* fix: address CodeRabbit review — error leaks, search filter bug, stale prompt, sysprompt tools
* feat: expose all workflow step fields in config-mode MCP tools
* feat: add workflow CRUD to config-mode MCP tools
* fix: split workflow CRUD E2E test into separate tests
* fix: prevent cascade deletion of config session in delete workflow E2E test
The config-chat endpoint picks the newest workflow (ORDER BY created_at
DESC) for the ephemeral task. When the test created a deletable workflow
right before starting the config session, the session's own task landed
under that workflow. Deleting the workflow then cascaded and wiped the
running session's task, causing the MCP tool call to hang.
Add a "Config Anchor" bumper workflow so the config session uses it
instead of the deletable one.
* feat: add executor management to config-mode MCP tools
Add 8 new MCP tools for executor and executor profile CRUD in config
mode: list/create/update/delete for both executors and profiles.
Wired through the full stack (WS actions, backend handlers, agentctl
tools, sysprompt) with unit tests and E2E coverage.
* fix: auto-focus config chat input and rename popover title
* fix: remove executor CRUD MCP tools, keep executor profile management
Executors are pre-defined system entities (local, worktree, docker,
sprites). Only executor profiles should be managed via config chat.
Removes create_executor, update_executor, delete_executor MCP tools
while keeping list_executors and all executor profile tools.
* fix: add realtime UI sync for workflow steps and agent profiles via MCP
Workflow step and agent profile changes made through the config chat
MCP tools were not broadcasting events to the frontend. Executor
profile events worked because they went through the task service which
has event bus integration.
- Add WorkflowStep and AgentProfile event types to the event bus
- Add WS notification action constants for workflow step events
- Publish events from MCP handlers after step/profile CRUD operations
- Register gateway subscriptions for the new event types
- Add frontend WS handlers for workflow.step.created/updated/deleted
* fix: reuse existing config chat session when opened from command panel
The command panel always called openConfigChatModal() which reset the
session state, causing the profile picker to show again. Now it checks
for an existing active session first, matching the FAB behavior.
* fix: suppress FAB tooltip while config chat popover is open
When closing the popover via the X button, the mouse ends up over the
FAB area and the tooltip re-appears. Force the tooltip closed while
the popover is open so it cannot re-trigger on close.
* fix: thread default_config_agent_profile_id through all workspace data paths
The field was defined on the workspace type but never populated in:
- SSR mapper (page.tsx) — missing from initial hydration
- WS workspace handlers — wiped on workspace.created/updated events
- Backend publishWorkspaceEvent — not included in event data
This caused the config chat to always show the profile picker when
opened from the command panel, since the saved default was lost.
* fix: address PR review comments — workspace sync, type fixes, missing tool doc
- Sync configChat.workspaceId when promoting next tab in closeConfigChatSession
- Add update_task_state_kandev to ConfigContext system prompt
- Fix workflow step WS event types (workflow.step.* instead of step.*)
- Fix const reassignment in E2E tests (const → let)
* refactor: clean up dead code and register missing MCP tools
- Register update_task_state, delete_workflow_step, and
reorder_workflow_steps as MCP tools in agentctl config mode
- Remove dead handleCreateAgent/handleDeleteAgent WS handlers
and their ActionMCP constants (only profiles are managed)
- Rename openConfigChatModal to startNewConfigChat across frontend
- Update sysprompt, tests, and tool counts
* fix: remove extra next.config.ts machine
* fix: address CI failures — prettier formatting and funlen split
* fix: address coderabbit review comments across config-mode stack
- Include prompt field in workflow step broadcast payloads
- Align sysprompt task-state values with actual backend enum
- Return error instead of continuing when MCP mode switch fails
- Validate mode values in agentctl set-mcp-mode endpoint
- Use errors.Is() for sentinel error comparison
- Fix nullish coalescing to allow clearing config agent profile
- Expand StepPayload type with missing config-step fields
- Derive config agent Select value from store instead of local state
* fix: reuse persisted config chat session and reduce toolbar complexity
- Look up configChat.sessions for workspace before creating new session
- Extract MinimalToolbar and move defaults to module-level object to
reduce ChatInputToolbar cyclomatic complexity from 16 to 7
* fix: E2E executor test strict mode violation and invalid cleanup
- Use exact match for list_executors text to avoid matching 2 elements
- Remove cleanup that tried to delete pre-existing system executor
- Reuse persisted config chat session for workspace in global commands
- Reduce ChatInputToolbar cyclomatic complexity with module-level defaults
This commit is contained in:
@@ -92,7 +92,7 @@ func run(cfg *config.Config, log *logger.Logger) {
|
||||
mcpBackendClient := mcpserver.NewChannelBackendClient(instLog)
|
||||
|
||||
// Create MCP server using the channel-based backend client
|
||||
mcpSrv := mcpserver.New(mcpBackendClient, instCfg.SessionID, instCfg.Port, instLog, cfg.McpLogFile, instCfg.DisableAskQuestion)
|
||||
mcpSrv := mcpserver.New(mcpBackendClient, instCfg.SessionID, instCfg.Port, instLog, cfg.McpLogFile, instCfg.DisableAskQuestion, instCfg.McpMode)
|
||||
instLog.Info("MCP server enabled (channel-based)",
|
||||
zap.String("session_id", instCfg.SessionID))
|
||||
|
||||
|
||||
@@ -82,6 +82,7 @@ func (a *lifecycleAdapter) LaunchAgent(ctx context.Context, req *executor.Launch
|
||||
ExecutorType: req.ExecutorType,
|
||||
ExecutorConfig: req.ExecutorConfig,
|
||||
PreviousExecutionID: req.PreviousExecutionID,
|
||||
McpMode: req.McpMode,
|
||||
SetupScript: req.SetupScript,
|
||||
// Worktree configuration for concurrent agent execution
|
||||
UseWorktree: req.UseWorktree,
|
||||
@@ -129,6 +130,11 @@ func (a *lifecycleAdapter) SetExecutionDescription(ctx context.Context, agentExe
|
||||
return a.mgr.SetExecutionDescription(ctx, agentExecutionID, description)
|
||||
}
|
||||
|
||||
// SetMcpMode changes the MCP tool mode on an existing execution's agentctl instance.
|
||||
func (a *lifecycleAdapter) SetMcpMode(ctx context.Context, executionID string, mode string) error {
|
||||
return a.mgr.SetMcpMode(ctx, executionID, mode)
|
||||
}
|
||||
|
||||
// StartAgentProcess starts the agent subprocess for an instance.
|
||||
// The command is built internally based on the instance's agent profile.
|
||||
func (a *lifecycleAdapter) StartAgentProcess(ctx context.Context, agentInstanceID string) error {
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/kandev/kandev/internal/agent/docker"
|
||||
agenthandlers "github.com/kandev/kandev/internal/agent/handlers"
|
||||
"github.com/kandev/kandev/internal/agent/lifecycle"
|
||||
"github.com/kandev/kandev/internal/agent/mcpconfig"
|
||||
agentsettingscontroller "github.com/kandev/kandev/internal/agent/settings/controller"
|
||||
agentsettingshandlers "github.com/kandev/kandev/internal/agent/settings/handlers"
|
||||
"github.com/kandev/kandev/internal/agentctl/tracing"
|
||||
@@ -431,6 +432,7 @@ type routeParams struct {
|
||||
msgCreator *messageCreatorAdapter
|
||||
secretsSvc *secrets.Service
|
||||
secretStore secrets.SecretStore
|
||||
mcpConfigSvc *mcpconfig.Service
|
||||
webInternalURL string
|
||||
log *logger.Logger
|
||||
}
|
||||
@@ -580,6 +582,9 @@ func registerMCPAndDebugRoutes(
|
||||
p.taskSvc, wfCtrl,
|
||||
clarificationStore, p.msgCreator, p.taskRepo, p.taskRepo, p.eventBus, planService, p.log,
|
||||
)
|
||||
// Wire config-mode dependencies for agent-native configuration
|
||||
mcpHandlers.SetConfigDeps(p.services.Workflow, p.agentSettingsController, p.mcpConfigSvc)
|
||||
|
||||
mcpHandlers.RegisterHandlers(p.gateway.Dispatcher)
|
||||
p.log.Debug("Registered MCP handlers (WebSocket)")
|
||||
|
||||
|
||||
@@ -30,6 +30,7 @@ import (
|
||||
|
||||
// Agent infrastructure
|
||||
"github.com/kandev/kandev/internal/agent/lifecycle"
|
||||
"github.com/kandev/kandev/internal/agent/mcpconfig"
|
||||
"github.com/kandev/kandev/internal/agent/registry"
|
||||
agentsettingscontroller "github.com/kandev/kandev/internal/agent/settings/controller"
|
||||
|
||||
@@ -440,6 +441,7 @@ func buildHTTPServer(
|
||||
msgCreator: msgCreator,
|
||||
secretsSvc: secrets.NewService(repos.Secrets, log),
|
||||
secretStore: repos.Secrets,
|
||||
mcpConfigSvc: mcpconfig.NewService(repos.AgentSettings),
|
||||
webInternalURL: cfg.Server.WebInternalURL,
|
||||
log: log,
|
||||
})
|
||||
|
||||
@@ -30,6 +30,7 @@ type ContainerConfig struct {
|
||||
InstanceID string
|
||||
MainRepoGitDir string // Path to main repo's .git directory (for worktrees)
|
||||
McpServers []McpServerConfig
|
||||
McpMode string
|
||||
}
|
||||
|
||||
// ContainerManager handles Docker container lifecycle operations
|
||||
@@ -113,6 +114,7 @@ func (cm *ContainerManager) LaunchContainer(ctx context.Context, config Containe
|
||||
SessionID: config.SessionID,
|
||||
DisableAskQuestion: disableAskQuestion,
|
||||
AssumeMcpSse: assumeMcpSse,
|
||||
McpMode: config.McpMode,
|
||||
}
|
||||
|
||||
resp, err := ctl.CreateInstance(ctx, createReq)
|
||||
|
||||
@@ -177,6 +177,7 @@ type ExecutorCreateRequest struct {
|
||||
McpServers []McpServerConfig
|
||||
AgentConfig agents.Agent // Agent type info needed by runtimes
|
||||
PreviousExecutionID string // Non-empty when reconnecting to a previous execution
|
||||
McpMode string // MCP tool mode: "task" (default) or "config"
|
||||
|
||||
// OnProgress is an optional callback for streaming preparation progress.
|
||||
// Executors that perform multi-step setup (e.g. Sprites, remote Docker) can
|
||||
|
||||
@@ -229,6 +229,7 @@ func (r *SpritesExecutor) createAgentInstance(
|
||||
Protocol: req.Protocol,
|
||||
AgentType: agentTypeFromReq(req),
|
||||
McpServers: req.McpServers,
|
||||
McpMode: req.McpMode,
|
||||
}
|
||||
reqJSON, err := json.Marshal(instanceReq)
|
||||
if err != nil {
|
||||
|
||||
@@ -108,6 +108,7 @@ func (r *StandaloneExecutor) CreateInstance(ctx context.Context, req *ExecutorCr
|
||||
SessionID: req.SessionID,
|
||||
DisableAskQuestion: disableAskQuestion,
|
||||
AssumeMcpSse: assumeMcpSse,
|
||||
McpMode: req.McpMode,
|
||||
}
|
||||
|
||||
r.logger.Info("CreateInstance: sending request to agentctl",
|
||||
|
||||
@@ -252,6 +252,7 @@ func (m *Manager) launchBuildExecutorRequest(ctx context.Context, executionID st
|
||||
AgentConfig: agentConfig,
|
||||
McpServers: mcpServers,
|
||||
PreviousExecutionID: reqWithWorktree.PreviousExecutionID,
|
||||
McpMode: reqWithWorktree.McpMode,
|
||||
OnProgress: m.newProgressCallback(reqWithWorktree.TaskID, reqWithWorktree.SessionID),
|
||||
}
|
||||
|
||||
@@ -479,6 +480,20 @@ func (m *Manager) SetExecutionDescription(_ context.Context, executionID string,
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetMcpMode changes the MCP tool mode on an existing execution's agentctl instance.
|
||||
// This is used when a session transitions to plan/config mode after the workspace was
|
||||
// already prepared with the default (task) mode.
|
||||
func (m *Manager) SetMcpMode(ctx context.Context, executionID string, mode string) error {
|
||||
execution, exists := m.executionStore.Get(executionID)
|
||||
if !exists {
|
||||
return fmt.Errorf("execution %q not found", executionID)
|
||||
}
|
||||
if execution.agentctl == nil {
|
||||
return fmt.Errorf("execution %q has no agentctl client", executionID)
|
||||
}
|
||||
return execution.agentctl.SetMcpMode(ctx, mode)
|
||||
}
|
||||
|
||||
// resolveApprovalPolicyAndDisplayName resolves the approval policy and agent display name
|
||||
// from the execution's agent profile and registry.
|
||||
func (m *Manager) resolveApprovalPolicyAndDisplayName(ctx context.Context, execution *AgentExecution) (string, string) {
|
||||
|
||||
@@ -259,6 +259,7 @@ type LaunchRequest struct {
|
||||
ExecutorType string // Executor type (e.g., "local", "worktree", "local_docker") - determines runtime
|
||||
ExecutorConfig map[string]string // Executor config (docker_host, git_token, etc.)
|
||||
PreviousExecutionID string // Previous execution ID for runtime reconnect
|
||||
McpMode string // MCP tool mode: "config" activates config-mode tools
|
||||
|
||||
// Environment preparation
|
||||
SetupScript string // Setup script to run before agent starts
|
||||
|
||||
@@ -243,6 +243,45 @@ func (c *Client) ConfigureAgent(ctx context.Context, command string, env map[str
|
||||
return nil
|
||||
}
|
||||
|
||||
// SetMcpMode changes the MCP tool mode on the agentctl instance.
|
||||
// This reconfigures which MCP tools are available to the agent.
|
||||
func (c *Client) SetMcpMode(ctx context.Context, mode string) error {
|
||||
ctx, span := tracing.TraceHTTPRequest(ctx, "PUT", "/api/v1/mcp/mode", c.executionID)
|
||||
defer span.End()
|
||||
|
||||
body, err := json.Marshal(struct {
|
||||
Mode string `json:"mode"`
|
||||
}{Mode: mode})
|
||||
if err != nil {
|
||||
tracing.TraceHTTPResponse(span, 0, err)
|
||||
return err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "PUT", c.baseURL+"/api/v1/mcp/mode", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
tracing.TraceHTTPResponse(span, 0, err)
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
tracing.TraceHTTPResponse(span, 0, err)
|
||||
return err
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
respBody, _ := readResponseBody(resp)
|
||||
httpErr := fmt.Errorf("set MCP mode failed with status %d: %s", resp.StatusCode, string(respBody))
|
||||
tracing.TraceHTTPResponse(span, resp.StatusCode, httpErr)
|
||||
return httpErr
|
||||
}
|
||||
|
||||
tracing.TraceHTTPResponse(span, resp.StatusCode, nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
// Start starts the agent process and returns the full command that was executed.
|
||||
func (c *Client) Start(ctx context.Context) (string, error) {
|
||||
ctx, span := tracing.TraceHTTPRequest(ctx, "POST", "/api/v1/start", c.executionID)
|
||||
|
||||
@@ -46,6 +46,7 @@ type CreateInstanceRequest struct {
|
||||
SessionID string `json:"session_id,omitempty"` // Task session ID for MCP tool calls
|
||||
DisableAskQuestion bool `json:"disable_ask_question,omitempty"` // Disable ask_user_question MCP tool (TUI agents)
|
||||
AssumeMcpSse bool `json:"assume_mcp_sse,omitempty"` // Assume agent supports SSE MCP servers
|
||||
McpMode string `json:"mcp_mode,omitempty"` // MCP tool mode: "task" (default) or "config"
|
||||
}
|
||||
|
||||
// CreateInstanceResponse contains the result of creating a new agent instance.
|
||||
|
||||
@@ -153,6 +153,7 @@ func (s *Server) setupRoutes() {
|
||||
// MCP routes (if MCP server is configured)
|
||||
if s.mcpServer != nil {
|
||||
s.mcpServer.RegisterRoutes(s.router)
|
||||
api.PUT("/mcp/mode", s.handleSetMcpMode)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -169,6 +170,23 @@ func (s *Server) handleHealth(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// handleSetMcpMode changes the MCP tool mode for this instance.
|
||||
func (s *Server) handleSetMcpMode(c *gin.Context) {
|
||||
var req struct {
|
||||
Mode string `json:"mode"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
if req.Mode != "task" && req.Mode != "config" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid mode: must be 'task' or 'config'"})
|
||||
return
|
||||
}
|
||||
s.mcpServer.SetMode(req.Mode)
|
||||
c.JSON(http.StatusOK, gin.H{"mode": req.Mode})
|
||||
}
|
||||
|
||||
// Status response
|
||||
type StatusResponse struct {
|
||||
AgentStatus string `json:"agent_status"`
|
||||
|
||||
@@ -158,6 +158,10 @@ type InstanceConfig struct {
|
||||
|
||||
// AssumeMcpSse overrides MCP capability filtering to assume the agent supports SSE.
|
||||
AssumeMcpSse bool
|
||||
|
||||
// McpMode controls which MCP tools are registered for this instance.
|
||||
// "task" (default) registers kanban/plan tools; "config" registers config tools.
|
||||
McpMode string
|
||||
}
|
||||
|
||||
// Load loads the configuration from environment variables.
|
||||
@@ -200,6 +204,7 @@ func (c *Config) NewInstanceConfig(port int, overrides *InstanceOverrides) *Inst
|
||||
LogFormat: c.LogFormat,
|
||||
ProcessBufferMaxBytes: c.Defaults.ProcessBufferMaxBytes,
|
||||
VscodeCommand: c.VscodeCommand,
|
||||
McpMode: "task",
|
||||
}
|
||||
|
||||
applyOverrides(cfg, overrides)
|
||||
@@ -261,6 +266,9 @@ func applyOverrides(cfg *InstanceConfig, overrides *InstanceOverrides) {
|
||||
if overrides.AssumeMcpSse {
|
||||
cfg.AssumeMcpSse = true
|
||||
}
|
||||
if overrides.McpMode != "" {
|
||||
cfg.McpMode = overrides.McpMode
|
||||
}
|
||||
}
|
||||
|
||||
// InstanceOverrides allows overriding default values when creating an instance
|
||||
@@ -276,6 +284,7 @@ type InstanceOverrides struct {
|
||||
SessionID string
|
||||
DisableAskQuestion bool
|
||||
AssumeMcpSse bool
|
||||
McpMode string
|
||||
}
|
||||
|
||||
// ParseCommand splits a command string into arguments
|
||||
|
||||
@@ -89,6 +89,9 @@ type CreateRequest struct {
|
||||
|
||||
// AssumeMcpSse overrides MCP capability filtering to assume SSE support.
|
||||
AssumeMcpSse bool `json:"assume_mcp_sse,omitempty"`
|
||||
|
||||
// McpMode controls which MCP tools are registered: "task" (default) or "config".
|
||||
McpMode string `json:"mcp_mode,omitempty"`
|
||||
}
|
||||
|
||||
// CreateResponse contains the result of creating a new agent instance.
|
||||
|
||||
@@ -91,6 +91,7 @@ func (m *Manager) CreateInstance(ctx context.Context, req *CreateRequest) (*Crea
|
||||
SessionID: req.SessionID,
|
||||
DisableAskQuestion: req.DisableAskQuestion,
|
||||
AssumeMcpSse: req.AssumeMcpSse,
|
||||
McpMode: req.McpMode,
|
||||
}
|
||||
|
||||
m.logger.Info("CreateInstance: applying overrides",
|
||||
|
||||
@@ -0,0 +1,697 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
ws "github.com/kandev/kandev/pkg/websocket"
|
||||
"github.com/mark3labs/mcp-go/mcp"
|
||||
"github.com/mark3labs/mcp-go/server"
|
||||
)
|
||||
|
||||
// --- Workflow config tools ---
|
||||
|
||||
func (s *Server) registerConfigWorkflowTools() {
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewToolWithRawSchema("list_workspaces",
|
||||
"List all workspaces. Use this first to get workspace IDs.",
|
||||
json.RawMessage(`{"type":"object","properties":{}}`),
|
||||
),
|
||||
s.wrapHandler("list_workspaces", s.listWorkspacesHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("list_workflows",
|
||||
mcp.WithDescription("List all workflows in a workspace."),
|
||||
mcp.WithString("workspace_id", mcp.Required(), mcp.Description("The workspace ID")),
|
||||
),
|
||||
s.wrapHandler("list_workflows", s.listWorkflowsHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("create_workflow",
|
||||
mcp.WithDescription("Create a new workflow in a workspace."),
|
||||
mcp.WithString("workspace_id", mcp.Required(), mcp.Description("The workspace ID")),
|
||||
mcp.WithString("name", mcp.Required(), mcp.Description("Workflow name")),
|
||||
mcp.WithString("description", mcp.Description("Workflow description")),
|
||||
),
|
||||
s.wrapHandler("create_workflow", s.createWorkflowHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("update_workflow",
|
||||
mcp.WithDescription("Update an existing workflow."),
|
||||
mcp.WithString("workflow_id", mcp.Required(), mcp.Description("The workflow ID")),
|
||||
mcp.WithString("name", mcp.Description("New workflow name")),
|
||||
mcp.WithString("description", mcp.Description("New workflow description")),
|
||||
),
|
||||
s.wrapHandler("update_workflow", s.updateWorkflowHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("delete_workflow",
|
||||
mcp.WithDescription("Delete a workflow and all its steps. This is destructive and cannot be undone."),
|
||||
mcp.WithString("workflow_id", mcp.Required(), mcp.Description("The workflow ID to delete")),
|
||||
),
|
||||
s.wrapHandler("delete_workflow", s.deleteWorkflowHandler()),
|
||||
)
|
||||
s.registerConfigWorkflowStepTools()
|
||||
}
|
||||
|
||||
func (s *Server) registerConfigWorkflowStepTools() {
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("list_workflow_steps",
|
||||
mcp.WithDescription("List all workflow steps (columns) in a workflow."),
|
||||
mcp.WithString("workflow_id", mcp.Required(), mcp.Description("The workflow ID")),
|
||||
),
|
||||
s.wrapHandler("list_workflow_steps", s.listWorkflowStepsHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("create_workflow_step",
|
||||
mcp.WithDescription("Create a new workflow step (column) in a workflow."),
|
||||
mcp.WithString("workflow_id", mcp.Required(), mcp.Description("The workflow ID")),
|
||||
mcp.WithString("name", mcp.Required(), mcp.Description("Step name")),
|
||||
mcp.WithNumber("position", mcp.Description("Step position (0-based). Defaults to end.")),
|
||||
mcp.WithString("color", mcp.Description("Step color hex code (e.g. '#3b82f6')")),
|
||||
mcp.WithString("prompt", mcp.Description("System prompt for agents in this step")),
|
||||
mcp.WithBoolean("is_start_step", mcp.Description("Whether this is the start step")),
|
||||
mcp.WithBoolean("allow_manual_move", mcp.Description("Allow manual task moves into this step (default: false)")),
|
||||
mcp.WithBoolean("show_in_command_panel", mcp.Description("Show this step in the command panel")),
|
||||
mcp.WithObject("events", mcp.Description("Event-driven actions. Keys: on_enter, on_exit, on_turn_start, on_turn_complete. Each is an array of {type, config} objects.")),
|
||||
),
|
||||
s.wrapHandler("create_workflow_step", s.createWorkflowStepHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("update_workflow_step",
|
||||
mcp.WithDescription("Update an existing workflow step."),
|
||||
mcp.WithString("step_id", mcp.Required(), mcp.Description("The workflow step ID")),
|
||||
mcp.WithString("name", mcp.Description("New step name")),
|
||||
mcp.WithString("color", mcp.Description("New color hex code")),
|
||||
mcp.WithString("prompt", mcp.Description("New system prompt")),
|
||||
mcp.WithBoolean("is_start_step", mcp.Description("Whether this is the start step")),
|
||||
mcp.WithBoolean("allow_manual_move", mcp.Description("Allow manual task moves into this step")),
|
||||
mcp.WithBoolean("show_in_command_panel", mcp.Description("Show this step in the command panel")),
|
||||
mcp.WithNumber("auto_archive_after_hours", mcp.Description("Auto-archive tasks after N hours in this step (0 to disable)")),
|
||||
mcp.WithObject("events", mcp.Description("Event-driven actions. Keys: on_enter, on_exit, on_turn_start, on_turn_complete.")),
|
||||
),
|
||||
s.wrapHandler("update_workflow_step", s.updateWorkflowStepHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("delete_workflow_step",
|
||||
mcp.WithDescription("Delete a workflow step. This is destructive and cannot be undone."),
|
||||
mcp.WithString("step_id", mcp.Required(), mcp.Description("The workflow step ID to delete")),
|
||||
),
|
||||
s.wrapHandler("delete_workflow_step", s.deleteWorkflowStepHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("reorder_workflow_steps",
|
||||
mcp.WithDescription("Reorder workflow steps by providing the full ordered list of step IDs."),
|
||||
mcp.WithString("workflow_id", mcp.Required(), mcp.Description("The workflow ID")),
|
||||
mcp.WithArray("step_ids", mcp.Required(), mcp.Description("Ordered list of step IDs defining the new order")),
|
||||
),
|
||||
s.wrapHandler("reorder_workflow_steps", s.reorderWorkflowStepsHandler()),
|
||||
)
|
||||
}
|
||||
|
||||
// --- Agent config tools ---
|
||||
|
||||
func (s *Server) registerConfigAgentTools() {
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewToolWithRawSchema("list_agents",
|
||||
"List all configured agents with their profiles.",
|
||||
json.RawMessage(`{"type":"object","properties":{}}`),
|
||||
),
|
||||
s.wrapHandler("list_agents", s.listAgentsHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("update_agent",
|
||||
mcp.WithDescription("Update an existing agent."),
|
||||
mcp.WithString("agent_id", mcp.Required(), mcp.Description("The agent ID")),
|
||||
mcp.WithBoolean("supports_mcp", mcp.Description("Whether the agent supports MCP")),
|
||||
mcp.WithString("mcp_config_path", mcp.Description("Path to MCP config file")),
|
||||
),
|
||||
s.wrapHandler("update_agent", s.updateAgentHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("create_agent_profile",
|
||||
mcp.WithDescription("Create a new agent profile for an agent."),
|
||||
mcp.WithString("agent_id", mcp.Required(), mcp.Description("The agent ID to create a profile for")),
|
||||
mcp.WithString("name", mcp.Required(), mcp.Description("Profile name")),
|
||||
mcp.WithString("model", mcp.Required(), mcp.Description("Model name (e.g. 'claude-sonnet-4-5-20250514')")),
|
||||
mcp.WithBoolean("auto_approve", mcp.Description("Auto-approve permissions (default: false)")),
|
||||
),
|
||||
s.wrapHandler("create_agent_profile", s.createAgentProfileHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("delete_agent_profile",
|
||||
mcp.WithDescription("Delete an agent profile. Fails if the profile is used by an active session."),
|
||||
mcp.WithString("profile_id", mcp.Required(), mcp.Description("The profile ID to delete")),
|
||||
),
|
||||
s.wrapHandler("delete_agent_profile", s.deleteAgentProfileHandler()),
|
||||
)
|
||||
}
|
||||
|
||||
// --- MCP config tools ---
|
||||
|
||||
func (s *Server) registerConfigMcpTools() {
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("list_agent_profiles",
|
||||
mcp.WithDescription("List all profiles for an agent."),
|
||||
mcp.WithString("agent_id", mcp.Required(), mcp.Description("The agent ID")),
|
||||
),
|
||||
s.wrapHandler("list_agent_profiles", s.listAgentProfilesHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("update_agent_profile",
|
||||
mcp.WithDescription("Update an agent profile's settings."),
|
||||
mcp.WithString("profile_id", mcp.Required(), mcp.Description("The profile ID")),
|
||||
mcp.WithString("name", mcp.Description("New profile name")),
|
||||
mcp.WithString("model", mcp.Description("New model name")),
|
||||
mcp.WithBoolean("auto_approve", mcp.Description("Auto-approve permissions")),
|
||||
),
|
||||
s.wrapHandler("update_agent_profile", s.updateAgentProfileHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("get_mcp_config",
|
||||
mcp.WithDescription("Get MCP server configuration for an agent profile."),
|
||||
mcp.WithString("profile_id", mcp.Required(), mcp.Description("The agent profile ID")),
|
||||
),
|
||||
s.wrapHandler("get_mcp_config", s.getMcpConfigHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("update_mcp_config",
|
||||
mcp.WithDescription("Update MCP server configuration for an agent profile. Pass the full servers map."),
|
||||
mcp.WithString("profile_id", mcp.Required(), mcp.Description("The agent profile ID")),
|
||||
mcp.WithBoolean("enabled", mcp.Description("Whether MCP is enabled for this profile")),
|
||||
mcp.WithObject("servers", mcp.Description("Full MCP servers map to set. Each key is a server name, value is the server configuration object.")),
|
||||
),
|
||||
s.wrapHandler("update_mcp_config", s.updateMcpConfigHandler()),
|
||||
)
|
||||
}
|
||||
|
||||
// --- Executor config tools ---
|
||||
|
||||
func (s *Server) registerConfigExecutorTools() {
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewToolWithRawSchema("list_executors",
|
||||
"List all executors.",
|
||||
json.RawMessage(`{"type":"object","properties":{}}`),
|
||||
),
|
||||
s.wrapHandler("list_executors", s.listExecutorsHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("list_executor_profiles",
|
||||
mcp.WithDescription("List all profiles for an executor."),
|
||||
mcp.WithString("executor_id", mcp.Required(), mcp.Description("The executor ID")),
|
||||
),
|
||||
s.wrapHandler("list_executor_profiles", s.listExecutorProfilesHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("create_executor_profile",
|
||||
mcp.WithDescription("Create a new executor profile."),
|
||||
mcp.WithString("executor_id", mcp.Required(), mcp.Description("The executor ID")),
|
||||
mcp.WithString("name", mcp.Required(), mcp.Description("Profile name")),
|
||||
mcp.WithString("mcp_policy", mcp.Description("MCP policy for this profile")),
|
||||
mcp.WithObject("config", mcp.Description("Key-value configuration map")),
|
||||
mcp.WithString("prepare_script", mcp.Description("Script to run before agent starts")),
|
||||
mcp.WithString("cleanup_script", mcp.Description("Script to run after agent stops")),
|
||||
),
|
||||
s.wrapHandler("create_executor_profile", s.createExecutorProfileHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("update_executor_profile",
|
||||
mcp.WithDescription("Update an existing executor profile."),
|
||||
mcp.WithString("profile_id", mcp.Required(), mcp.Description("The executor profile ID")),
|
||||
mcp.WithString("name", mcp.Description("New profile name")),
|
||||
mcp.WithString("mcp_policy", mcp.Description("New MCP policy")),
|
||||
mcp.WithObject("config", mcp.Description("New configuration map")),
|
||||
mcp.WithString("prepare_script", mcp.Description("New prepare script")),
|
||||
mcp.WithString("cleanup_script", mcp.Description("New cleanup script")),
|
||||
),
|
||||
s.wrapHandler("update_executor_profile", s.updateExecutorProfileHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("delete_executor_profile",
|
||||
mcp.WithDescription("Delete an executor profile."),
|
||||
mcp.WithString("profile_id", mcp.Required(), mcp.Description("The executor profile ID to delete")),
|
||||
),
|
||||
s.wrapHandler("delete_executor_profile", s.deleteExecutorProfileHandler()),
|
||||
)
|
||||
}
|
||||
|
||||
// --- Task config tools ---
|
||||
|
||||
func (s *Server) registerConfigTaskTools() {
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("list_tasks",
|
||||
mcp.WithDescription("List all tasks in a workflow."),
|
||||
mcp.WithString("workflow_id", mcp.Required(), mcp.Description("The workflow ID")),
|
||||
),
|
||||
s.wrapHandler("list_tasks", s.listTasksHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("move_task",
|
||||
mcp.WithDescription("Move a task to a different workflow step."),
|
||||
mcp.WithString("task_id", mcp.Required(), mcp.Description("The task ID")),
|
||||
mcp.WithString("workflow_id", mcp.Required(), mcp.Description("Target workflow ID")),
|
||||
mcp.WithString("workflow_step_id", mcp.Required(), mcp.Description("Target workflow step ID")),
|
||||
mcp.WithNumber("position", mcp.Description("Position within the step (0-based)")),
|
||||
),
|
||||
s.wrapHandler("move_task", s.moveTaskHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("delete_task",
|
||||
mcp.WithDescription("Delete a task permanently."),
|
||||
mcp.WithString("task_id", mcp.Required(), mcp.Description("The task ID to delete")),
|
||||
),
|
||||
s.wrapHandler("delete_task", s.deleteTaskHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("archive_task",
|
||||
mcp.WithDescription("Archive a task."),
|
||||
mcp.WithString("task_id", mcp.Required(), mcp.Description("The task ID to archive")),
|
||||
),
|
||||
s.wrapHandler("archive_task", s.archiveTaskHandler()),
|
||||
)
|
||||
s.mcpServer.AddTool(
|
||||
mcp.NewTool("update_task_state",
|
||||
mcp.WithDescription("Update the state of a task."),
|
||||
mcp.WithString("task_id", mcp.Required(), mcp.Description("The task ID")),
|
||||
mcp.WithString("state", mcp.Required(), mcp.Description("New state: open, in_progress, complete, blocked, cancelled")),
|
||||
),
|
||||
s.wrapHandler("update_task_state", s.updateTaskStateHandler()),
|
||||
)
|
||||
}
|
||||
|
||||
// --- Handler implementations ---
|
||||
|
||||
func (s *Server) createWorkflowHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
workspaceID, err := req.RequireString("workspace_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("workspace_id is required"), nil
|
||||
}
|
||||
name, err := req.RequireString("name")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("name is required"), nil
|
||||
}
|
||||
payload := map[string]interface{}{
|
||||
"workspace_id": workspaceID,
|
||||
"name": name,
|
||||
}
|
||||
if desc := req.GetString("description", ""); desc != "" {
|
||||
payload["description"] = desc
|
||||
}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPCreateWorkflow, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) updateWorkflowHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
workflowID, err := req.RequireString("workflow_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("workflow_id is required"), nil
|
||||
}
|
||||
payload := map[string]interface{}{"workflow_id": workflowID}
|
||||
if name := req.GetString("name", ""); name != "" {
|
||||
payload["name"] = name
|
||||
}
|
||||
if desc := req.GetString("description", ""); desc != "" {
|
||||
payload["description"] = desc
|
||||
}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPUpdateWorkflow, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) deleteWorkflowHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
workflowID, err := req.RequireString("workflow_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("workflow_id is required"), nil
|
||||
}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPDeleteWorkflow, map[string]string{"workflow_id": workflowID})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) createWorkflowStepHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
workflowID, err := req.RequireString("workflow_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("workflow_id is required"), nil
|
||||
}
|
||||
name, err := req.RequireString("name")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("name is required"), nil
|
||||
}
|
||||
payload := map[string]interface{}{
|
||||
"workflow_id": workflowID,
|
||||
"name": name,
|
||||
}
|
||||
if color := req.GetString("color", ""); color != "" {
|
||||
payload["color"] = color
|
||||
}
|
||||
if prompt := req.GetString("prompt", ""); prompt != "" {
|
||||
payload["prompt"] = prompt
|
||||
}
|
||||
args := req.GetArguments()
|
||||
for _, key := range []string{"position", "is_start_step", "allow_manual_move", "show_in_command_panel", "events"} {
|
||||
if args[key] != nil {
|
||||
payload[key] = args[key]
|
||||
}
|
||||
}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPCreateWorkflowStep, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) updateWorkflowStepHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
stepID, err := req.RequireString("step_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("step_id is required"), nil
|
||||
}
|
||||
payload := map[string]interface{}{"step_id": stepID}
|
||||
if name := req.GetString("name", ""); name != "" {
|
||||
payload["name"] = name
|
||||
}
|
||||
if color := req.GetString("color", ""); color != "" {
|
||||
payload["color"] = color
|
||||
}
|
||||
if prompt := req.GetString("prompt", ""); prompt != "" {
|
||||
payload["prompt"] = prompt
|
||||
}
|
||||
args := req.GetArguments()
|
||||
for _, key := range []string{"is_start_step", "allow_manual_move", "show_in_command_panel", "auto_archive_after_hours", "events"} {
|
||||
if args[key] != nil {
|
||||
payload[key] = args[key]
|
||||
}
|
||||
}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPUpdateWorkflowStep, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) listAgentsHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPListAgents, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) createAgentProfileHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
agentID, err := req.RequireString("agent_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("agent_id is required"), nil
|
||||
}
|
||||
name, err := req.RequireString("name")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("name is required"), nil
|
||||
}
|
||||
model, err := req.RequireString("model")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("model is required"), nil
|
||||
}
|
||||
payload := map[string]interface{}{
|
||||
"agent_id": agentID,
|
||||
"name": name,
|
||||
"model": model,
|
||||
}
|
||||
if args := req.GetArguments(); args["auto_approve"] != nil {
|
||||
payload["auto_approve"] = args["auto_approve"]
|
||||
}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPCreateAgentProfile, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) updateAgentHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
agentID, err := req.RequireString("agent_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("agent_id is required"), nil
|
||||
}
|
||||
payload := map[string]interface{}{"agent_id": agentID}
|
||||
if args := req.GetArguments(); args["supports_mcp"] != nil {
|
||||
payload["supports_mcp"] = args["supports_mcp"]
|
||||
}
|
||||
if path := req.GetString("mcp_config_path", ""); path != "" {
|
||||
payload["mcp_config_path"] = path
|
||||
}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPUpdateAgent, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) deleteAgentProfileHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
profileID, err := req.RequireString("profile_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("profile_id is required"), nil
|
||||
}
|
||||
payload := map[string]string{"profile_id": profileID}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPDeleteAgentProfile, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) listAgentProfilesHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
agentID, err := req.RequireString("agent_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("agent_id is required"), nil
|
||||
}
|
||||
payload := map[string]string{"agent_id": agentID}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPListAgentProfiles, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) updateAgentProfileHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
profileID, err := req.RequireString("profile_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("profile_id is required"), nil
|
||||
}
|
||||
payload := map[string]interface{}{"profile_id": profileID}
|
||||
if name := req.GetString("name", ""); name != "" {
|
||||
payload["name"] = name
|
||||
}
|
||||
if model := req.GetString("model", ""); model != "" {
|
||||
payload["model"] = model
|
||||
}
|
||||
if args := req.GetArguments(); args["auto_approve"] != nil {
|
||||
payload["auto_approve"] = args["auto_approve"]
|
||||
}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPUpdateAgentProfile, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) getMcpConfigHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
profileID, err := req.RequireString("profile_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("profile_id is required"), nil
|
||||
}
|
||||
payload := map[string]string{"profile_id": profileID}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPGetMcpConfig, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) updateMcpConfigHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
profileID, err := req.RequireString("profile_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("profile_id is required"), nil
|
||||
}
|
||||
payload := map[string]interface{}{"profile_id": profileID}
|
||||
args := req.GetArguments()
|
||||
if args["enabled"] != nil {
|
||||
payload["enabled"] = args["enabled"]
|
||||
}
|
||||
if args["servers"] != nil {
|
||||
payload["servers"] = args["servers"]
|
||||
}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPUpdateMcpConfig, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) moveTaskHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
taskID, err := req.RequireString("task_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("task_id is required"), nil
|
||||
}
|
||||
workflowID, err := req.RequireString("workflow_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("workflow_id is required"), nil
|
||||
}
|
||||
stepID, err := req.RequireString("workflow_step_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("workflow_step_id is required"), nil
|
||||
}
|
||||
payload := map[string]interface{}{
|
||||
"task_id": taskID,
|
||||
"workflow_id": workflowID,
|
||||
"workflow_step_id": stepID,
|
||||
}
|
||||
if args := req.GetArguments(); args["position"] != nil {
|
||||
payload["position"] = args["position"]
|
||||
}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPMoveTask, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) deleteTaskHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
taskID, err := req.RequireString("task_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("task_id is required"), nil
|
||||
}
|
||||
payload := map[string]string{"task_id": taskID}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPDeleteTask, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) updateTaskStateHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
taskID, err := req.RequireString("task_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("task_id is required"), nil
|
||||
}
|
||||
state, err := req.RequireString("state")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("state is required"), nil
|
||||
}
|
||||
payload := map[string]string{"task_id": taskID, "state": state}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPUpdateTaskState, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) deleteWorkflowStepHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
stepID, err := req.RequireString("step_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("step_id is required"), nil
|
||||
}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPDeleteWorkflowStep, map[string]string{"step_id": stepID})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) reorderWorkflowStepsHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
workflowID, err := req.RequireString("workflow_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("workflow_id is required"), nil
|
||||
}
|
||||
args := req.GetArguments()
|
||||
stepIDs := args["step_ids"]
|
||||
if stepIDs == nil {
|
||||
return mcp.NewToolResultError("step_ids is required"), nil
|
||||
}
|
||||
payload := map[string]interface{}{
|
||||
"workflow_id": workflowID,
|
||||
"step_ids": stepIDs,
|
||||
}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPReorderWorkflowStep, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) archiveTaskHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
taskID, err := req.RequireString("task_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("task_id is required"), nil
|
||||
}
|
||||
payload := map[string]string{"task_id": taskID}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPArchiveTask, payload)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Executor handler implementations ---
|
||||
|
||||
func (s *Server) listExecutorsHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPListExecutors, nil)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) listExecutorProfilesHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
executorID, err := req.RequireString("executor_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("executor_id is required"), nil
|
||||
}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPListExecutorProfiles, map[string]string{"executor_id": executorID})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) createExecutorProfileHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
executorID, err := req.RequireString("executor_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("executor_id is required"), nil
|
||||
}
|
||||
name, err := req.RequireString("name")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("name is required"), nil
|
||||
}
|
||||
payload := map[string]interface{}{
|
||||
"executor_id": executorID,
|
||||
"name": name,
|
||||
}
|
||||
if mcpPolicy := req.GetString("mcp_policy", ""); mcpPolicy != "" {
|
||||
payload["mcp_policy"] = mcpPolicy
|
||||
}
|
||||
if prepareScript := req.GetString("prepare_script", ""); prepareScript != "" {
|
||||
payload["prepare_script"] = prepareScript
|
||||
}
|
||||
if cleanupScript := req.GetString("cleanup_script", ""); cleanupScript != "" {
|
||||
payload["cleanup_script"] = cleanupScript
|
||||
}
|
||||
args := req.GetArguments()
|
||||
if args["config"] != nil {
|
||||
payload["config"] = args["config"]
|
||||
}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPCreateExecutorProfile, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) updateExecutorProfileHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
profileID, err := req.RequireString("profile_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("profile_id is required"), nil
|
||||
}
|
||||
payload := map[string]interface{}{"profile_id": profileID}
|
||||
if name := req.GetString("name", ""); name != "" {
|
||||
payload["name"] = name
|
||||
}
|
||||
if mcpPolicy := req.GetString("mcp_policy", ""); mcpPolicy != "" {
|
||||
payload["mcp_policy"] = mcpPolicy
|
||||
}
|
||||
if prepareScript := req.GetString("prepare_script", ""); prepareScript != "" {
|
||||
payload["prepare_script"] = prepareScript
|
||||
}
|
||||
if cleanupScript := req.GetString("cleanup_script", ""); cleanupScript != "" {
|
||||
payload["cleanup_script"] = cleanupScript
|
||||
}
|
||||
args := req.GetArguments()
|
||||
if args["config"] != nil {
|
||||
payload["config"] = args["config"]
|
||||
}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPUpdateExecutorProfile, payload)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) deleteExecutorProfileHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
profileID, err := req.RequireString("profile_id")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("profile_id is required"), nil
|
||||
}
|
||||
return s.forwardToBackend(ctx, ws.ActionMCPDeleteExecutorProfile, map[string]string{"profile_id": profileID})
|
||||
}
|
||||
}
|
||||
|
||||
// forwardToBackend sends a request to the backend and returns the result as JSON text.
|
||||
func (s *Server) forwardToBackend(ctx context.Context, action string, payload interface{}) (*mcp.CallToolResult, error) {
|
||||
var result map[string]interface{}
|
||||
if err := s.backend.RequestPayload(ctx, action, payload, &result); err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
data, err := json.MarshalIndent(result, "", " ")
|
||||
if err != nil {
|
||||
return mcp.NewToolResultError("failed to marshal response: " + err.Error()), nil
|
||||
}
|
||||
return mcp.NewToolResultText(string(data)), nil
|
||||
}
|
||||
@@ -0,0 +1,674 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
ws "github.com/kandev/kandev/pkg/websocket"
|
||||
mcplib "github.com/mark3labs/mcp-go/mcp"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// testBackend implements BackendClient for testing handlers.
|
||||
type testBackend struct {
|
||||
lastAction string
|
||||
lastPayload interface{}
|
||||
response map[string]interface{}
|
||||
err error
|
||||
}
|
||||
|
||||
func (tb *testBackend) RequestPayload(_ context.Context, action string, payload, result interface{}) error {
|
||||
tb.lastAction = action
|
||||
tb.lastPayload = payload
|
||||
if tb.err != nil {
|
||||
return tb.err
|
||||
}
|
||||
if tb.response != nil && result != nil {
|
||||
data, _ := json.Marshal(tb.response)
|
||||
return json.Unmarshal(data, result)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func newTestServer(t *testing.T, backend BackendClient) *Server {
|
||||
t.Helper()
|
||||
log := newTestLogger(t)
|
||||
return New(backend, "test-session", 10005, log, "", false, ModeConfig)
|
||||
}
|
||||
|
||||
func callTool(t *testing.T, s *Server, toolName string, args map[string]interface{}) *mcplib.CallToolResult {
|
||||
t.Helper()
|
||||
toolsMap := s.mcpServer.ListTools()
|
||||
st, ok := toolsMap[toolName]
|
||||
require.True(t, ok, "tool %q not registered", toolName)
|
||||
|
||||
reqArgs, err := json.Marshal(args)
|
||||
require.NoError(t, err)
|
||||
|
||||
req := mcplib.CallToolRequest{}
|
||||
req.Method = "tools/call"
|
||||
req.Params.Name = toolName
|
||||
req.Params.Arguments = make(map[string]interface{})
|
||||
if err := json.Unmarshal(reqArgs, &req.Params.Arguments); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
result, err := st.Handler(context.Background(), req)
|
||||
require.NoError(t, err)
|
||||
return result
|
||||
}
|
||||
|
||||
// --- Action constant tests ---
|
||||
|
||||
func TestActionConstants_MatchWebSocketActions(t *testing.T) {
|
||||
// Verify canonical constants in pkg/websocket match the expected WS action strings.
|
||||
assert.Equal(t, "mcp.create_workflow", ws.ActionMCPCreateWorkflow)
|
||||
assert.Equal(t, "mcp.update_workflow", ws.ActionMCPUpdateWorkflow)
|
||||
assert.Equal(t, "mcp.delete_workflow", ws.ActionMCPDeleteWorkflow)
|
||||
assert.Equal(t, "mcp.create_workflow_step", ws.ActionMCPCreateWorkflowStep)
|
||||
assert.Equal(t, "mcp.update_workflow_step", ws.ActionMCPUpdateWorkflowStep)
|
||||
assert.Equal(t, "mcp.delete_workflow_step", ws.ActionMCPDeleteWorkflowStep)
|
||||
assert.Equal(t, "mcp.reorder_workflow_steps", ws.ActionMCPReorderWorkflowStep)
|
||||
assert.Equal(t, "mcp.list_agents", ws.ActionMCPListAgents)
|
||||
assert.Equal(t, "mcp.update_agent", ws.ActionMCPUpdateAgent)
|
||||
assert.Equal(t, "mcp.list_agent_profiles", ws.ActionMCPListAgentProfiles)
|
||||
assert.Equal(t, "mcp.create_agent_profile", ws.ActionMCPCreateAgentProfile)
|
||||
assert.Equal(t, "mcp.update_agent_profile", ws.ActionMCPUpdateAgentProfile)
|
||||
assert.Equal(t, "mcp.delete_agent_profile", ws.ActionMCPDeleteAgentProfile)
|
||||
assert.Equal(t, "mcp.get_mcp_config", ws.ActionMCPGetMcpConfig)
|
||||
assert.Equal(t, "mcp.update_mcp_config", ws.ActionMCPUpdateMcpConfig)
|
||||
assert.Equal(t, "mcp.list_executors", ws.ActionMCPListExecutors)
|
||||
assert.Equal(t, "mcp.list_executor_profiles", ws.ActionMCPListExecutorProfiles)
|
||||
assert.Equal(t, "mcp.create_executor_profile", ws.ActionMCPCreateExecutorProfile)
|
||||
assert.Equal(t, "mcp.update_executor_profile", ws.ActionMCPUpdateExecutorProfile)
|
||||
assert.Equal(t, "mcp.delete_executor_profile", ws.ActionMCPDeleteExecutorProfile)
|
||||
assert.Equal(t, "mcp.move_task", ws.ActionMCPMoveTask)
|
||||
assert.Equal(t, "mcp.delete_task", ws.ActionMCPDeleteTask)
|
||||
assert.Equal(t, "mcp.archive_task", ws.ActionMCPArchiveTask)
|
||||
assert.Equal(t, "mcp.update_task_state", ws.ActionMCPUpdateTaskState)
|
||||
}
|
||||
|
||||
// --- Workflow handler tests ---
|
||||
|
||||
func TestCreateWorkflowHandler_Success(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"id": "wf-1", "name": "Sprint Board"},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "create_workflow", map[string]interface{}{
|
||||
"workspace_id": "ws-123",
|
||||
"name": "Sprint Board",
|
||||
"description": "A sprint workflow",
|
||||
})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPCreateWorkflow, backend.lastAction)
|
||||
payload, ok := backend.lastPayload.(map[string]interface{})
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "ws-123", payload["workspace_id"])
|
||||
assert.Equal(t, "Sprint Board", payload["name"])
|
||||
assert.Equal(t, "A sprint workflow", payload["description"])
|
||||
}
|
||||
|
||||
func TestCreateWorkflowHandler_MissingWorkspaceID(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "create_workflow", map[string]interface{}{
|
||||
"name": "Sprint Board",
|
||||
})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
func TestCreateWorkflowHandler_MissingName(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "create_workflow", map[string]interface{}{
|
||||
"workspace_id": "ws-123",
|
||||
})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
func TestUpdateWorkflowHandler_Success(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"id": "wf-1", "name": "Updated"},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "update_workflow", map[string]interface{}{
|
||||
"workflow_id": "wf-1",
|
||||
"name": "Updated",
|
||||
"description": "New description",
|
||||
})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPUpdateWorkflow, backend.lastAction)
|
||||
}
|
||||
|
||||
func TestUpdateWorkflowHandler_MissingWorkflowID(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "update_workflow", map[string]interface{}{
|
||||
"name": "Updated",
|
||||
})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
func TestDeleteWorkflowHandler_Success(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"success": true},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "delete_workflow", map[string]interface{}{
|
||||
"workflow_id": "wf-1",
|
||||
})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPDeleteWorkflow, backend.lastAction)
|
||||
}
|
||||
|
||||
func TestDeleteWorkflowHandler_MissingWorkflowID(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "delete_workflow", map[string]interface{}{})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
func TestCreateWorkflowStepHandler_Success(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"step": map[string]interface{}{"id": "step-1", "name": "Review"}},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "create_workflow_step", map[string]interface{}{
|
||||
"workflow_id": "wf-123",
|
||||
"name": "Review",
|
||||
"color": "#3b82f6",
|
||||
"position": float64(2),
|
||||
})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPCreateWorkflowStep, backend.lastAction)
|
||||
}
|
||||
|
||||
func TestCreateWorkflowStepHandler_AllFields(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"step": map[string]interface{}{"id": "step-1"}},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "create_workflow_step", map[string]interface{}{
|
||||
"workflow_id": "wf-123",
|
||||
"name": "Deploy",
|
||||
"position": float64(0),
|
||||
"color": "#22c55e",
|
||||
"prompt": "Deploy prompt",
|
||||
"is_start_step": true,
|
||||
"allow_manual_move": true,
|
||||
"show_in_command_panel": true,
|
||||
"events": map[string]interface{}{
|
||||
"on_enter": []interface{}{map[string]interface{}{"type": "auto_start_agent"}},
|
||||
},
|
||||
})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPCreateWorkflowStep, backend.lastAction)
|
||||
// Verify optional fields are forwarded in the payload
|
||||
payload, ok := backend.lastPayload.(map[string]interface{})
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, true, payload["allow_manual_move"])
|
||||
assert.Equal(t, true, payload["show_in_command_panel"])
|
||||
assert.NotNil(t, payload["events"])
|
||||
}
|
||||
|
||||
func TestCreateWorkflowStepHandler_MissingWorkflowID(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "create_workflow_step", map[string]interface{}{
|
||||
"name": "Review",
|
||||
})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
func TestCreateWorkflowStepHandler_MissingName(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "create_workflow_step", map[string]interface{}{
|
||||
"workflow_id": "wf-123",
|
||||
})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
func TestUpdateWorkflowStepHandler_Success(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"step": map[string]interface{}{"id": "step-1"}},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "update_workflow_step", map[string]interface{}{
|
||||
"step_id": "step-1",
|
||||
"name": "Updated Name",
|
||||
})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPUpdateWorkflowStep, backend.lastAction)
|
||||
}
|
||||
|
||||
func TestUpdateWorkflowStepHandler_AllFields(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"step": map[string]interface{}{"id": "step-1"}},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "update_workflow_step", map[string]interface{}{
|
||||
"step_id": "step-1",
|
||||
"name": "In Review",
|
||||
"color": "#3b82f6",
|
||||
"allow_manual_move": true,
|
||||
"show_in_command_panel": true,
|
||||
"auto_archive_after_hours": float64(48),
|
||||
"events": map[string]interface{}{
|
||||
"on_enter": []interface{}{map[string]interface{}{"type": "enable_plan_mode"}},
|
||||
},
|
||||
})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPUpdateWorkflowStep, backend.lastAction)
|
||||
payload, ok := backend.lastPayload.(map[string]interface{})
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, true, payload["allow_manual_move"])
|
||||
assert.Equal(t, true, payload["show_in_command_panel"])
|
||||
assert.Equal(t, float64(48), payload["auto_archive_after_hours"])
|
||||
assert.NotNil(t, payload["events"])
|
||||
}
|
||||
|
||||
func TestUpdateWorkflowStepHandler_MissingStepID(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "update_workflow_step", map[string]interface{}{
|
||||
"name": "Updated",
|
||||
})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
// --- Agent handler tests ---
|
||||
|
||||
func TestListAgentsHandler_Success(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"agents": []interface{}{}, "total": float64(0)},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "list_agents", map[string]interface{}{})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPListAgents, backend.lastAction)
|
||||
}
|
||||
|
||||
func TestCreateAgentProfileHandler_Success(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"id": "profile-1", "name": "My Profile"},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "create_agent_profile", map[string]interface{}{
|
||||
"agent_id": "agent-1",
|
||||
"name": "My Profile",
|
||||
"model": "claude-sonnet-4-5-20250514",
|
||||
})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPCreateAgentProfile, backend.lastAction)
|
||||
}
|
||||
|
||||
func TestCreateAgentProfileHandler_MissingAgentID(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "create_agent_profile", map[string]interface{}{
|
||||
"name": "My Profile",
|
||||
"model": "claude-sonnet-4-5-20250514",
|
||||
})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
func TestCreateAgentProfileHandler_MissingModel(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "create_agent_profile", map[string]interface{}{
|
||||
"agent_id": "agent-1",
|
||||
"name": "My Profile",
|
||||
})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
func TestUpdateAgentHandler_Success(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"id": "agent-1"},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "update_agent", map[string]interface{}{
|
||||
"agent_id": "agent-1",
|
||||
"supports_mcp": true,
|
||||
})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPUpdateAgent, backend.lastAction)
|
||||
}
|
||||
|
||||
func TestUpdateAgentHandler_MissingAgentID(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "update_agent", map[string]interface{}{
|
||||
"supports_mcp": true,
|
||||
})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
func TestDeleteAgentProfileHandler_Success(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"id": "profile-1"},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "delete_agent_profile", map[string]interface{}{
|
||||
"profile_id": "profile-1",
|
||||
})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPDeleteAgentProfile, backend.lastAction)
|
||||
}
|
||||
|
||||
func TestDeleteAgentProfileHandler_MissingProfileID(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "delete_agent_profile", map[string]interface{}{})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
// --- MCP config handler tests ---
|
||||
|
||||
func TestListAgentProfilesHandler_Success(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"profiles": []interface{}{}, "total": float64(0)},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "list_agent_profiles", map[string]interface{}{
|
||||
"agent_id": "agent-1",
|
||||
})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPListAgentProfiles, backend.lastAction)
|
||||
}
|
||||
|
||||
func TestListAgentProfilesHandler_MissingAgentID(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "list_agent_profiles", map[string]interface{}{})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
func TestUpdateAgentProfileHandler_Success(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"id": "profile-1"},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "update_agent_profile", map[string]interface{}{
|
||||
"profile_id": "profile-1",
|
||||
"name": "Updated Profile",
|
||||
"model": "claude-3.5-sonnet",
|
||||
})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPUpdateAgentProfile, backend.lastAction)
|
||||
}
|
||||
|
||||
func TestUpdateAgentProfileHandler_MissingProfileID(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "update_agent_profile", map[string]interface{}{
|
||||
"name": "Updated",
|
||||
})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
func TestGetMcpConfigHandler_Success(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"profile_id": "p-1", "enabled": true},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "get_mcp_config", map[string]interface{}{
|
||||
"profile_id": "p-1",
|
||||
})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPGetMcpConfig, backend.lastAction)
|
||||
}
|
||||
|
||||
func TestGetMcpConfigHandler_MissingProfileID(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "get_mcp_config", map[string]interface{}{})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
func TestUpdateMcpConfigHandler_Success(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"profile_id": "p-1"},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "update_mcp_config", map[string]interface{}{
|
||||
"profile_id": "p-1",
|
||||
"enabled": true,
|
||||
})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPUpdateMcpConfig, backend.lastAction)
|
||||
}
|
||||
|
||||
func TestUpdateMcpConfigHandler_MissingProfileID(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "update_mcp_config", map[string]interface{}{})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
// --- Executor handler tests ---
|
||||
|
||||
func TestListExecutorsHandler_Success(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"executors": []interface{}{}, "total": float64(0)},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "list_executors", map[string]interface{}{})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPListExecutors, backend.lastAction)
|
||||
}
|
||||
|
||||
func TestListExecutorProfilesHandler_Success(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"profiles": []interface{}{}, "total": float64(0)},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "list_executor_profiles", map[string]interface{}{
|
||||
"executor_id": "exec-1",
|
||||
})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPListExecutorProfiles, backend.lastAction)
|
||||
}
|
||||
|
||||
func TestListExecutorProfilesHandler_MissingExecutorID(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "list_executor_profiles", map[string]interface{}{})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
func TestCreateExecutorProfileHandler_Success(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"id": "prof-1", "name": "Default"},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "create_executor_profile", map[string]interface{}{
|
||||
"executor_id": "exec-1",
|
||||
"name": "Default",
|
||||
})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPCreateExecutorProfile, backend.lastAction)
|
||||
payload, ok := backend.lastPayload.(map[string]interface{})
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, "exec-1", payload["executor_id"])
|
||||
assert.Equal(t, "Default", payload["name"])
|
||||
}
|
||||
|
||||
func TestCreateExecutorProfileHandler_MissingExecutorID(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "create_executor_profile", map[string]interface{}{
|
||||
"name": "Default",
|
||||
})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
func TestCreateExecutorProfileHandler_MissingName(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "create_executor_profile", map[string]interface{}{
|
||||
"executor_id": "exec-1",
|
||||
})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
func TestUpdateExecutorProfileHandler_Success(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"id": "prof-1"},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "update_executor_profile", map[string]interface{}{
|
||||
"profile_id": "prof-1",
|
||||
"name": "Updated Profile",
|
||||
})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPUpdateExecutorProfile, backend.lastAction)
|
||||
}
|
||||
|
||||
func TestUpdateExecutorProfileHandler_MissingProfileID(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "update_executor_profile", map[string]interface{}{
|
||||
"name": "Updated",
|
||||
})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
func TestDeleteExecutorProfileHandler_Success(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{"success": true},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "delete_executor_profile", map[string]interface{}{
|
||||
"profile_id": "prof-1",
|
||||
})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
assert.Equal(t, ws.ActionMCPDeleteExecutorProfile, backend.lastAction)
|
||||
}
|
||||
|
||||
func TestDeleteExecutorProfileHandler_MissingProfileID(t *testing.T) {
|
||||
backend := &testBackend{}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "delete_executor_profile", map[string]interface{}{})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
// --- ForwardToBackend tests ---
|
||||
|
||||
func TestForwardToBackend_BackendError(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
err: fmt.Errorf("connection refused"),
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "list_agents", map[string]interface{}{})
|
||||
|
||||
assert.True(t, result.IsError)
|
||||
}
|
||||
|
||||
func TestForwardToBackend_ResultContainsJSON(t *testing.T) {
|
||||
backend := &testBackend{
|
||||
response: map[string]interface{}{
|
||||
"agents": []interface{}{
|
||||
map[string]interface{}{"id": "a1", "name": "claude-code"},
|
||||
},
|
||||
"total": float64(1),
|
||||
},
|
||||
}
|
||||
s := newTestServer(t, backend)
|
||||
|
||||
result := callTool(t, s, "list_agents", map[string]interface{}{})
|
||||
|
||||
assert.False(t, result.IsError)
|
||||
require.NotEmpty(t, result.Content)
|
||||
|
||||
// The result should be JSON text content
|
||||
tc, ok := result.Content[0].(mcplib.TextContent)
|
||||
assert.True(t, ok, "expected TextContent")
|
||||
assert.NotEmpty(t, tc.Text)
|
||||
}
|
||||
@@ -5,33 +5,17 @@ import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
ws "github.com/kandev/kandev/pkg/websocket"
|
||||
"github.com/mark3labs/mcp-go/mcp"
|
||||
"github.com/mark3labs/mcp-go/server"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// MCP action constants for backend WS requests
|
||||
// These must match the actions registered in pkg/websocket/actions.go
|
||||
const (
|
||||
ActionMCPListWorkspaces = "mcp.list_workspaces"
|
||||
ActionMCPListWorkflows = "mcp.list_workflows"
|
||||
ActionMCPListWorkflowSteps = "mcp.list_workflow_steps"
|
||||
ActionMCPListTasks = "mcp.list_tasks"
|
||||
ActionMCPCreateTask = "mcp.create_task"
|
||||
ActionMCPUpdateTask = "mcp.update_task"
|
||||
ActionMCPAskUserQuestion = "mcp.ask_user_question"
|
||||
ActionMCPClarificationTimeout = "mcp.clarification_timeout"
|
||||
ActionMCPCreateTaskPlan = "mcp.create_task_plan"
|
||||
ActionMCPGetTaskPlan = "mcp.get_task_plan"
|
||||
ActionMCPUpdateTaskPlan = "mcp.update_task_plan"
|
||||
ActionMCPDeleteTaskPlan = "mcp.delete_task_plan"
|
||||
)
|
||||
|
||||
func (s *Server) listWorkspacesHandler() server.ToolHandlerFunc {
|
||||
return func(ctx context.Context, req mcp.CallToolRequest) (*mcp.CallToolResult, error) {
|
||||
// Backend returns {workspaces: [...], total: N}
|
||||
var result map[string]interface{}
|
||||
if err := s.backend.RequestPayload(ctx, ActionMCPListWorkspaces, nil, &result); err != nil {
|
||||
if err := s.backend.RequestPayload(ctx, ws.ActionMCPListWorkspaces, nil, &result); err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
data, _ := json.MarshalIndent(result, "", " ")
|
||||
@@ -48,7 +32,7 @@ func (s *Server) listWorkflowsHandler() server.ToolHandlerFunc {
|
||||
payload := map[string]string{"workspace_id": workspaceID}
|
||||
// Backend returns {workflows: [...], total: N}
|
||||
var result map[string]interface{}
|
||||
if err := s.backend.RequestPayload(ctx, ActionMCPListWorkflows, payload, &result); err != nil {
|
||||
if err := s.backend.RequestPayload(ctx, ws.ActionMCPListWorkflows, payload, &result); err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
data, _ := json.MarshalIndent(result, "", " ")
|
||||
@@ -65,7 +49,7 @@ func (s *Server) listWorkflowStepsHandler() server.ToolHandlerFunc {
|
||||
payload := map[string]string{"workflow_id": workflowID}
|
||||
// Backend returns {workflow_steps: [...], total: N}
|
||||
var result map[string]interface{}
|
||||
if err := s.backend.RequestPayload(ctx, ActionMCPListWorkflowSteps, payload, &result); err != nil {
|
||||
if err := s.backend.RequestPayload(ctx, ws.ActionMCPListWorkflowSteps, payload, &result); err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
data, _ := json.MarshalIndent(result, "", " ")
|
||||
@@ -82,7 +66,7 @@ func (s *Server) listTasksHandler() server.ToolHandlerFunc {
|
||||
payload := map[string]string{"workflow_id": workflowID}
|
||||
// Backend returns {tasks: [...], total: N}
|
||||
var result map[string]interface{}
|
||||
if err := s.backend.RequestPayload(ctx, ActionMCPListTasks, payload, &result); err != nil {
|
||||
if err := s.backend.RequestPayload(ctx, ws.ActionMCPListTasks, payload, &result); err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
data, _ := json.MarshalIndent(result, "", " ")
|
||||
@@ -118,7 +102,7 @@ func (s *Server) createTaskHandler() server.ToolHandlerFunc {
|
||||
"description": description,
|
||||
}
|
||||
var result map[string]interface{}
|
||||
if err := s.backend.RequestPayload(ctx, ActionMCPCreateTask, payload, &result); err != nil {
|
||||
if err := s.backend.RequestPayload(ctx, ws.ActionMCPCreateTask, payload, &result); err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
data, _ := json.MarshalIndent(result, "", " ")
|
||||
@@ -143,7 +127,7 @@ func (s *Server) updateTaskHandler() server.ToolHandlerFunc {
|
||||
payload["state"] = state
|
||||
}
|
||||
var result map[string]interface{}
|
||||
if err := s.backend.RequestPayload(ctx, ActionMCPUpdateTask, payload, &result); err != nil {
|
||||
if err := s.backend.RequestPayload(ctx, ws.ActionMCPUpdateTask, payload, &result); err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
data, _ := json.MarshalIndent(result, "", " ")
|
||||
@@ -179,7 +163,7 @@ func (s *Server) askUserQuestionHandler() server.ToolHandlerFunc {
|
||||
// Use the MCP request context from the agent. This ensures that if the agent's
|
||||
// MCP client times out, we'll detect it and not update the session state.
|
||||
var result map[string]interface{}
|
||||
if err := s.backend.RequestPayload(ctx, ActionMCPAskUserQuestion, payload, &result); err != nil {
|
||||
if err := s.backend.RequestPayload(ctx, ws.ActionMCPAskUserQuestion, payload, &result); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
// Agent's MCP client disconnected/timed out. Notify backend to cancel
|
||||
// pending clarifications so the user's answer goes through the event
|
||||
@@ -281,7 +265,7 @@ func extractAnswerMap(answer interface{}) *mcp.CallToolResult {
|
||||
// the event fallback path (new turn) instead of the primary path (same turn).
|
||||
func (s *Server) notifyClarificationTimeout() {
|
||||
payload := map[string]string{"session_id": s.sessionID}
|
||||
if err := s.backend.RequestPayload(context.Background(), ActionMCPClarificationTimeout, payload, nil); err != nil {
|
||||
if err := s.backend.RequestPayload(context.Background(), ws.ActionMCPClarificationTimeout, payload, nil); err != nil {
|
||||
s.logger.Warn("failed to notify backend of clarification timeout",
|
||||
zap.String("session_id", s.sessionID),
|
||||
zap.Error(err))
|
||||
@@ -307,7 +291,7 @@ func (s *Server) createTaskPlanHandler() server.ToolHandlerFunc {
|
||||
"created_by": "agent",
|
||||
}
|
||||
var result map[string]interface{}
|
||||
if err := s.backend.RequestPayload(ctx, ActionMCPCreateTaskPlan, payload, &result); err != nil {
|
||||
if err := s.backend.RequestPayload(ctx, ws.ActionMCPCreateTaskPlan, payload, &result); err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
data, _ := json.MarshalIndent(result, "", " ")
|
||||
@@ -324,7 +308,7 @@ func (s *Server) getTaskPlanHandler() server.ToolHandlerFunc {
|
||||
|
||||
payload := map[string]string{"task_id": taskID}
|
||||
var result map[string]interface{}
|
||||
if err := s.backend.RequestPayload(ctx, ActionMCPGetTaskPlan, payload, &result); err != nil {
|
||||
if err := s.backend.RequestPayload(ctx, ws.ActionMCPGetTaskPlan, payload, &result); err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
|
||||
@@ -365,7 +349,7 @@ func (s *Server) updateTaskPlanHandler() server.ToolHandlerFunc {
|
||||
}
|
||||
|
||||
var result map[string]interface{}
|
||||
if err := s.backend.RequestPayload(ctx, ActionMCPUpdateTaskPlan, payload, &result); err != nil {
|
||||
if err := s.backend.RequestPayload(ctx, ws.ActionMCPUpdateTaskPlan, payload, &result); err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
data, _ := json.MarshalIndent(result, "", " ")
|
||||
@@ -382,7 +366,7 @@ func (s *Server) deleteTaskPlanHandler() server.ToolHandlerFunc {
|
||||
|
||||
payload := map[string]string{"task_id": taskID}
|
||||
var result map[string]interface{}
|
||||
if err := s.backend.RequestPayload(ctx, ActionMCPDeleteTaskPlan, payload, &result); err != nil {
|
||||
if err := s.backend.RequestPayload(ctx, ws.ActionMCPDeleteTaskPlan, payload, &result); err != nil {
|
||||
return mcp.NewToolResultError(err.Error()), nil
|
||||
}
|
||||
return mcp.NewToolResultText("Plan deleted successfully."), nil
|
||||
|
||||
@@ -24,11 +24,28 @@ type BackendClient interface {
|
||||
RequestPayload(ctx context.Context, action string, payload, result interface{}) error
|
||||
}
|
||||
|
||||
// MCP mode constants control which tools are registered.
|
||||
const (
|
||||
// ModeTask registers kanban, plan, and interaction tools (default for task-solving agents).
|
||||
ModeTask = "task"
|
||||
// ModeConfig registers configuration tools for workflows, agents, and MCP servers.
|
||||
ModeConfig = "config"
|
||||
)
|
||||
|
||||
// normalizeMode returns a valid MCP mode, defaulting unknown values to ModeTask.
|
||||
func normalizeMode(mode string) string {
|
||||
if mode == ModeConfig {
|
||||
return ModeConfig
|
||||
}
|
||||
return ModeTask
|
||||
}
|
||||
|
||||
// Server wraps the MCP server with backend client for communication.
|
||||
type Server struct {
|
||||
backend BackendClient
|
||||
sessionID string
|
||||
disableAskQuestion bool
|
||||
mode string // "task" (default) or "config"
|
||||
mcpServer *server.MCPServer
|
||||
sseServer *server.SSEServer
|
||||
httpServer *server.StreamableHTTPServer
|
||||
@@ -41,11 +58,13 @@ type Server struct {
|
||||
// New creates a new MCP server for agentctl.
|
||||
// port is the HTTP server port used to build the SSE base URL (http://localhost:<port>).
|
||||
// mcpLogFile is an optional file path for MCP debug logging; pass "" to disable.
|
||||
func New(backend BackendClient, sessionID string, port int, log *logger.Logger, mcpLogFile string, disableAskQuestion bool) *Server {
|
||||
func New(backend BackendClient, sessionID string, port int, log *logger.Logger, mcpLogFile string, disableAskQuestion bool, mcpMode string) *Server {
|
||||
mcpMode = normalizeMode(mcpMode)
|
||||
s := &Server{
|
||||
backend: backend,
|
||||
sessionID: sessionID,
|
||||
disableAskQuestion: disableAskQuestion,
|
||||
mode: mcpMode,
|
||||
logger: log.WithFields(zap.String("component", "mcp-server")),
|
||||
}
|
||||
|
||||
@@ -187,18 +206,50 @@ func (s *Server) wrapHandler(toolName string, handler server.ToolHandlerFunc) se
|
||||
}
|
||||
}
|
||||
|
||||
// registerTools registers all MCP tools.
|
||||
// SetMode changes the MCP server mode and re-registers tools accordingly.
|
||||
// This allows reconfiguring the tool set after initial creation (e.g., when
|
||||
// a session transitions to plan/config mode on a pre-existing workspace).
|
||||
func (s *Server) SetMode(mode string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.mode = normalizeMode(mode)
|
||||
// Clear all existing tools and re-register for the new mode.
|
||||
s.mcpServer.SetTools() // empty call clears all tools
|
||||
s.registerTools()
|
||||
}
|
||||
|
||||
// registerTools registers MCP tools based on the server mode.
|
||||
func (s *Server) registerTools() {
|
||||
count := 0
|
||||
s.registerKanbanTools()
|
||||
count += 6
|
||||
if !s.disableAskQuestion {
|
||||
s.registerInteractionTools()
|
||||
count++
|
||||
switch s.mode {
|
||||
case ModeConfig:
|
||||
s.registerConfigWorkflowTools()
|
||||
count += 10
|
||||
s.registerConfigAgentTools()
|
||||
count += 4
|
||||
s.registerConfigMcpTools()
|
||||
count += 4
|
||||
s.registerConfigExecutorTools()
|
||||
count += 5
|
||||
s.registerConfigTaskTools()
|
||||
count += 5
|
||||
if !s.disableAskQuestion {
|
||||
s.registerInteractionTools()
|
||||
count++
|
||||
}
|
||||
default: // ModeTask
|
||||
s.registerKanbanTools()
|
||||
count += 6
|
||||
if !s.disableAskQuestion {
|
||||
s.registerInteractionTools()
|
||||
count++
|
||||
}
|
||||
s.registerPlanTools()
|
||||
count += 4
|
||||
}
|
||||
s.registerPlanTools()
|
||||
count += 4
|
||||
s.logger.Info("registered MCP tools",
|
||||
zap.String("mode", s.mode),
|
||||
zap.Int("count", count),
|
||||
zap.Bool("disable_ask_question", s.disableAskQuestion))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func newTestLogger(t *testing.T) *logger.Logger {
|
||||
t.Helper()
|
||||
log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console"})
|
||||
require.NoError(t, err)
|
||||
return log
|
||||
}
|
||||
|
||||
// getRegisteredToolNames returns the names of all tools registered on the MCP server.
|
||||
func getRegisteredToolNames(s *Server) []string {
|
||||
toolsMap := s.mcpServer.ListTools()
|
||||
names := make([]string, 0, len(toolsMap))
|
||||
for name := range toolsMap {
|
||||
names = append(names, name)
|
||||
}
|
||||
return names
|
||||
}
|
||||
|
||||
func TestServerModeTask_RegistersCorrectTools(t *testing.T) {
|
||||
log := newTestLogger(t)
|
||||
backend := NewChannelBackendClient(log)
|
||||
defer backend.Close()
|
||||
|
||||
s := New(backend, "test-session", 10005, log, "", false, ModeTask)
|
||||
require.NotNil(t, s)
|
||||
|
||||
tools := getRegisteredToolNames(s)
|
||||
|
||||
// Task mode should have kanban tools
|
||||
assert.Contains(t, tools, "list_workspaces")
|
||||
assert.Contains(t, tools, "list_workflows")
|
||||
assert.Contains(t, tools, "list_workflow_steps")
|
||||
assert.Contains(t, tools, "list_tasks")
|
||||
assert.Contains(t, tools, "create_task")
|
||||
assert.Contains(t, tools, "update_task")
|
||||
|
||||
// Task mode should have plan tools
|
||||
assert.Contains(t, tools, "create_task_plan")
|
||||
assert.Contains(t, tools, "get_task_plan")
|
||||
assert.Contains(t, tools, "update_task_plan")
|
||||
assert.Contains(t, tools, "delete_task_plan")
|
||||
|
||||
// Task mode should have interaction tools
|
||||
assert.Contains(t, tools, "ask_user_question")
|
||||
|
||||
// Task mode should NOT have config tools
|
||||
assert.NotContains(t, tools, "create_workflow")
|
||||
assert.NotContains(t, tools, "update_workflow")
|
||||
assert.NotContains(t, tools, "delete_workflow")
|
||||
assert.NotContains(t, tools, "create_workflow_step")
|
||||
assert.NotContains(t, tools, "update_workflow_step")
|
||||
assert.NotContains(t, tools, "list_agents")
|
||||
assert.NotContains(t, tools, "update_agent")
|
||||
assert.NotContains(t, tools, "create_agent_profile")
|
||||
assert.NotContains(t, tools, "delete_agent_profile")
|
||||
assert.NotContains(t, tools, "list_agent_profiles")
|
||||
assert.NotContains(t, tools, "update_agent_profile")
|
||||
assert.NotContains(t, tools, "get_mcp_config")
|
||||
assert.NotContains(t, tools, "update_mcp_config")
|
||||
assert.NotContains(t, tools, "move_task")
|
||||
assert.NotContains(t, tools, "delete_task")
|
||||
assert.NotContains(t, tools, "archive_task")
|
||||
assert.NotContains(t, tools, "list_executors")
|
||||
assert.NotContains(t, tools, "list_executor_profiles")
|
||||
assert.NotContains(t, tools, "create_executor_profile")
|
||||
assert.NotContains(t, tools, "update_executor_profile")
|
||||
assert.NotContains(t, tools, "delete_executor_profile")
|
||||
assert.NotContains(t, tools, "update_task_state")
|
||||
assert.NotContains(t, tools, "delete_workflow_step")
|
||||
assert.NotContains(t, tools, "reorder_workflow_steps")
|
||||
}
|
||||
|
||||
func TestServerModeConfig_RegistersCorrectTools(t *testing.T) {
|
||||
log := newTestLogger(t)
|
||||
backend := NewChannelBackendClient(log)
|
||||
defer backend.Close()
|
||||
|
||||
s := New(backend, "test-session", 10005, log, "", false, ModeConfig)
|
||||
require.NotNil(t, s)
|
||||
|
||||
tools := getRegisteredToolNames(s)
|
||||
|
||||
// Config mode should have workflow config tools
|
||||
assert.Contains(t, tools, "list_workspaces")
|
||||
assert.Contains(t, tools, "list_workflows")
|
||||
assert.Contains(t, tools, "create_workflow")
|
||||
assert.Contains(t, tools, "update_workflow")
|
||||
assert.Contains(t, tools, "delete_workflow")
|
||||
assert.Contains(t, tools, "list_workflow_steps")
|
||||
assert.Contains(t, tools, "create_workflow_step")
|
||||
assert.Contains(t, tools, "update_workflow_step")
|
||||
assert.Contains(t, tools, "delete_workflow_step")
|
||||
assert.Contains(t, tools, "reorder_workflow_steps")
|
||||
|
||||
// Config mode should have agent tools
|
||||
assert.Contains(t, tools, "list_agents")
|
||||
assert.Contains(t, tools, "update_agent")
|
||||
assert.Contains(t, tools, "create_agent_profile")
|
||||
assert.Contains(t, tools, "delete_agent_profile")
|
||||
|
||||
// Config mode should have MCP config tools
|
||||
assert.Contains(t, tools, "list_agent_profiles")
|
||||
assert.Contains(t, tools, "update_agent_profile")
|
||||
assert.Contains(t, tools, "get_mcp_config")
|
||||
assert.Contains(t, tools, "update_mcp_config")
|
||||
|
||||
// Config mode should have executor profile tools
|
||||
assert.Contains(t, tools, "list_executors")
|
||||
assert.Contains(t, tools, "list_executor_profiles")
|
||||
assert.Contains(t, tools, "create_executor_profile")
|
||||
assert.Contains(t, tools, "update_executor_profile")
|
||||
assert.Contains(t, tools, "delete_executor_profile")
|
||||
|
||||
// Config mode should have task tools
|
||||
assert.Contains(t, tools, "list_tasks")
|
||||
assert.Contains(t, tools, "move_task")
|
||||
assert.Contains(t, tools, "delete_task")
|
||||
assert.Contains(t, tools, "archive_task")
|
||||
assert.Contains(t, tools, "update_task_state")
|
||||
|
||||
// Config mode should have interaction tools
|
||||
assert.Contains(t, tools, "ask_user_question")
|
||||
|
||||
// Config mode should NOT have plan tools
|
||||
assert.NotContains(t, tools, "create_task_plan")
|
||||
assert.NotContains(t, tools, "get_task_plan")
|
||||
assert.NotContains(t, tools, "update_task_plan")
|
||||
assert.NotContains(t, tools, "delete_task_plan")
|
||||
|
||||
// Config mode should NOT have task-mode kanban create/update tools
|
||||
assert.NotContains(t, tools, "create_task")
|
||||
assert.NotContains(t, tools, "update_task")
|
||||
}
|
||||
|
||||
func TestServerModeDefault_DefaultsToTask(t *testing.T) {
|
||||
log := newTestLogger(t)
|
||||
backend := NewChannelBackendClient(log)
|
||||
defer backend.Close()
|
||||
|
||||
s := New(backend, "test-session", 10005, log, "", false, "")
|
||||
require.NotNil(t, s)
|
||||
assert.Equal(t, ModeTask, s.mode)
|
||||
|
||||
tools := getRegisteredToolNames(s)
|
||||
assert.Contains(t, tools, "create_task")
|
||||
assert.Contains(t, tools, "create_task_plan")
|
||||
assert.NotContains(t, tools, "create_workflow_step")
|
||||
}
|
||||
|
||||
func TestServerModeConfig_DisableAskQuestion(t *testing.T) {
|
||||
log := newTestLogger(t)
|
||||
backend := NewChannelBackendClient(log)
|
||||
defer backend.Close()
|
||||
|
||||
s := New(backend, "test-session", 10005, log, "", true, ModeConfig)
|
||||
require.NotNil(t, s)
|
||||
|
||||
tools := getRegisteredToolNames(s)
|
||||
assert.NotContains(t, tools, "ask_user_question")
|
||||
assert.Contains(t, tools, "list_agents")
|
||||
assert.Contains(t, tools, "create_workflow_step")
|
||||
}
|
||||
|
||||
func TestServerModeTask_DisableAskQuestion(t *testing.T) {
|
||||
log := newTestLogger(t)
|
||||
backend := NewChannelBackendClient(log)
|
||||
defer backend.Close()
|
||||
|
||||
s := New(backend, "test-session", 10005, log, "", true, ModeTask)
|
||||
require.NotNil(t, s)
|
||||
|
||||
tools := getRegisteredToolNames(s)
|
||||
assert.NotContains(t, tools, "ask_user_question")
|
||||
assert.Contains(t, tools, "create_task")
|
||||
assert.Contains(t, tools, "create_task_plan")
|
||||
}
|
||||
|
||||
func TestServerModeTask_ToolCount(t *testing.T) {
|
||||
log := newTestLogger(t)
|
||||
backend := NewChannelBackendClient(log)
|
||||
defer backend.Close()
|
||||
|
||||
s := New(backend, "test-session", 10005, log, "", false, ModeTask)
|
||||
tools := getRegisteredToolNames(s)
|
||||
// 6 kanban + 1 interaction + 4 plan = 11
|
||||
assert.Equal(t, 11, len(tools))
|
||||
}
|
||||
|
||||
func TestServerModeConfig_ToolCount(t *testing.T) {
|
||||
log := newTestLogger(t)
|
||||
backend := NewChannelBackendClient(log)
|
||||
defer backend.Close()
|
||||
|
||||
s := New(backend, "test-session", 10005, log, "", false, ModeConfig)
|
||||
tools := getRegisteredToolNames(s)
|
||||
// 10 workflow + 4 agent + 4 mcp + 5 executor + 5 task + 1 interaction = 29
|
||||
assert.Equal(t, 29, len(tools))
|
||||
}
|
||||
|
||||
func TestServerModeConfig_ToolDescriptions(t *testing.T) {
|
||||
log := newTestLogger(t)
|
||||
backend := NewChannelBackendClient(log)
|
||||
defer backend.Close()
|
||||
|
||||
s := New(backend, "test-session", 10005, log, "", false, ModeConfig)
|
||||
|
||||
toolsMap := s.mcpServer.ListTools()
|
||||
|
||||
assert.Contains(t, toolsMap["create_workflow_step"].Tool.Description, "Create a new workflow step")
|
||||
assert.Contains(t, toolsMap["list_agents"].Tool.Description, "List all configured agents")
|
||||
assert.Contains(t, toolsMap["get_mcp_config"].Tool.Description, "Get MCP server configuration")
|
||||
}
|
||||
|
||||
func TestServerModeConstants(t *testing.T) {
|
||||
assert.Equal(t, "task", ModeTask)
|
||||
assert.Equal(t, "config", ModeConfig)
|
||||
}
|
||||
@@ -24,6 +24,13 @@ const (
|
||||
WorkflowDeleted = "workflow.deleted"
|
||||
)
|
||||
|
||||
// Event types for workflow steps
|
||||
const (
|
||||
WorkflowStepCreated = "workflow_step.created"
|
||||
WorkflowStepUpdated = "workflow_step.updated"
|
||||
WorkflowStepDeleted = "workflow_step.deleted"
|
||||
)
|
||||
|
||||
// Event types for comments
|
||||
const (
|
||||
MessageAdded = "message.added"
|
||||
@@ -99,6 +106,13 @@ const (
|
||||
EnvironmentDeleted = "environment.deleted"
|
||||
)
|
||||
|
||||
// Event types for agent profiles (settings)
|
||||
const (
|
||||
AgentProfileCreated = "agent_profile.created"
|
||||
AgentProfileUpdated = "agent_profile.updated"
|
||||
AgentProfileDeleted = "agent_profile.deleted"
|
||||
)
|
||||
|
||||
// Event types for agents
|
||||
const (
|
||||
AgentStarted = "agent.started"
|
||||
|
||||
@@ -31,6 +31,12 @@ func RegisterTaskNotifications(ctx context.Context, eventBus bus.EventBus, hub *
|
||||
b.subscribe(eventBus, events.WorkflowCreated, ws.ActionWorkflowCreated)
|
||||
b.subscribe(eventBus, events.WorkflowUpdated, ws.ActionWorkflowUpdated)
|
||||
b.subscribe(eventBus, events.WorkflowDeleted, ws.ActionWorkflowDeleted)
|
||||
b.subscribe(eventBus, events.WorkflowStepCreated, ws.ActionWorkflowStepCreated)
|
||||
b.subscribe(eventBus, events.WorkflowStepUpdated, ws.ActionWorkflowStepUpdated)
|
||||
b.subscribe(eventBus, events.WorkflowStepDeleted, ws.ActionWorkflowStepDeleted)
|
||||
b.subscribe(eventBus, events.AgentProfileCreated, ws.ActionAgentProfileCreated)
|
||||
b.subscribe(eventBus, events.AgentProfileUpdated, ws.ActionAgentProfileUpdated)
|
||||
b.subscribe(eventBus, events.AgentProfileDeleted, ws.ActionAgentProfileDeleted)
|
||||
b.subscribe(eventBus, events.TaskCreated, ws.ActionTaskCreated)
|
||||
b.subscribe(eventBus, events.TaskUpdated, ws.ActionTaskUpdated)
|
||||
b.subscribe(eventBus, events.TaskDeleted, ws.ActionTaskDeleted)
|
||||
|
||||
@@ -127,6 +127,10 @@ func (s *SimulatedAgentManagerClient) SetExecutionDescription(ctx context.Contex
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *SimulatedAgentManagerClient) SetMcpMode(_ context.Context, _ string, _ string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// StartAgentProcess simulates starting the agent subprocess
|
||||
func (s *SimulatedAgentManagerClient) StartAgentProcess(ctx context.Context, agentExecutionID string) error {
|
||||
s.logger.Info("simulated: starting agent process",
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
agentsettingscontroller "github.com/kandev/kandev/internal/agent/settings/controller"
|
||||
"github.com/kandev/kandev/internal/events"
|
||||
"github.com/kandev/kandev/internal/events/bus"
|
||||
ws "github.com/kandev/kandev/pkg/websocket"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func (h *Handlers) handleListAgents(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
resp, err := h.agentSettingsCtrl.ListAgents(ctx)
|
||||
if err != nil {
|
||||
h.logger.Error("failed to list agents", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to list agents", nil)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, resp)
|
||||
}
|
||||
|
||||
func (h *Handlers) handleUpdateAgent(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
AgentID string `json:"agent_id"`
|
||||
SupportsMCP *bool `json:"supports_mcp"`
|
||||
MCPConfigPath *string `json:"mcp_config_path"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if req.AgentID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "agent_id is required", nil)
|
||||
}
|
||||
|
||||
agent, err := h.agentSettingsCtrl.UpdateAgent(ctx, agentsettingscontroller.UpdateAgentRequest{
|
||||
ID: req.AgentID,
|
||||
SupportsMCP: req.SupportsMCP,
|
||||
MCPConfigPath: req.MCPConfigPath,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("failed to update agent", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to update agent", nil)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, agent)
|
||||
}
|
||||
|
||||
func (h *Handlers) handleListAgentProfiles(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
agentID, err := unmarshalStringField(msg.Payload, "agent_id")
|
||||
if err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if agentID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "agent_id is required", nil)
|
||||
}
|
||||
|
||||
agent, err := h.agentSettingsCtrl.GetAgent(ctx, agentID)
|
||||
if err != nil {
|
||||
h.logger.Error("failed to get agent profiles", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to get agent profiles", nil)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{
|
||||
"profiles": agent.Profiles,
|
||||
"total": len(agent.Profiles),
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handlers) handleCreateAgentProfile(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
AgentID string `json:"agent_id"`
|
||||
Name string `json:"name"`
|
||||
Model string `json:"model"`
|
||||
AutoApprove bool `json:"auto_approve"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if req.AgentID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "agent_id is required", nil)
|
||||
}
|
||||
if req.Name == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "name is required", nil)
|
||||
}
|
||||
if req.Model == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "model is required", nil)
|
||||
}
|
||||
|
||||
profile, err := h.agentSettingsCtrl.CreateProfile(ctx, agentsettingscontroller.CreateProfileRequest{
|
||||
AgentID: req.AgentID,
|
||||
Name: req.Name,
|
||||
Model: req.Model,
|
||||
AutoApprove: req.AutoApprove,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("failed to create agent profile", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to create agent profile: "+err.Error(), nil)
|
||||
}
|
||||
h.publishAgentProfileEvent(ctx, events.AgentProfileCreated, profile)
|
||||
return ws.NewResponse(msg.ID, msg.Action, profile)
|
||||
}
|
||||
|
||||
func (h *Handlers) handleDeleteAgentProfile(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
profileID, err := unmarshalStringField(msg.Payload, "profile_id")
|
||||
if err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if profileID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "profile_id is required", nil)
|
||||
}
|
||||
|
||||
profile, err := h.agentSettingsCtrl.DeleteProfile(ctx, profileID)
|
||||
if err != nil {
|
||||
h.logger.Error("failed to delete agent profile", zap.Error(err))
|
||||
if errors.Is(err, agentsettingscontroller.ErrAgentProfileInUse) {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "Cannot delete: profile is used by an active agent session", nil)
|
||||
}
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to delete agent profile: "+err.Error(), nil)
|
||||
}
|
||||
h.publishAgentProfileEvent(ctx, events.AgentProfileDeleted, profile)
|
||||
return ws.NewResponse(msg.ID, msg.Action, profile)
|
||||
}
|
||||
|
||||
func (h *Handlers) handleUpdateAgentProfile(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
ProfileID string `json:"profile_id"`
|
||||
Name *string `json:"name"`
|
||||
Model *string `json:"model"`
|
||||
AutoApprove *bool `json:"auto_approve"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if req.ProfileID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "profile_id is required", nil)
|
||||
}
|
||||
|
||||
profile, err := h.agentSettingsCtrl.UpdateProfile(ctx, agentsettingscontroller.UpdateProfileRequest{
|
||||
ID: req.ProfileID,
|
||||
Name: req.Name,
|
||||
Model: req.Model,
|
||||
AutoApprove: req.AutoApprove,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("failed to update agent profile", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to update agent profile", nil)
|
||||
}
|
||||
h.publishAgentProfileEvent(ctx, events.AgentProfileUpdated, profile)
|
||||
return ws.NewResponse(msg.ID, msg.Action, profile)
|
||||
}
|
||||
|
||||
// publishAgentProfileEvent publishes an agent profile event to the event bus.
|
||||
// The payload wraps the profile in a "profile" key to match the format expected
|
||||
// by existing frontend WS handlers (same format as HTTP agent settings handlers).
|
||||
func (h *Handlers) publishAgentProfileEvent(ctx context.Context, eventType string, profile interface{}) {
|
||||
if h.eventBus == nil || profile == nil {
|
||||
return
|
||||
}
|
||||
data := map[string]interface{}{
|
||||
"profile": profile,
|
||||
}
|
||||
if err := h.eventBus.Publish(ctx, eventType, bus.NewEvent(eventType, "mcp-handlers", data)); err != nil {
|
||||
h.logger.Error("failed to publish agent profile event",
|
||||
zap.String("event_type", eventType),
|
||||
zap.Error(err))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/kandev/kandev/internal/task/dto"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/service"
|
||||
ws "github.com/kandev/kandev/pkg/websocket"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func (h *Handlers) handleListExecutors(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
executors, err := h.taskSvc.ListExecutors(ctx)
|
||||
if err != nil {
|
||||
h.logger.Error("failed to list executors", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to list executors", nil)
|
||||
}
|
||||
dtos := make([]dto.ExecutorDTO, 0, len(executors))
|
||||
for _, e := range executors {
|
||||
dtos = append(dtos, dto.FromExecutor(e))
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, dto.ListExecutorsResponse{Executors: dtos, Total: len(dtos)})
|
||||
}
|
||||
|
||||
func (h *Handlers) handleListExecutorProfiles(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
return h.handleListByField(ctx, msg, "executor_id", "failed to list executor profiles", "Failed to list executor profiles",
|
||||
func(ctx context.Context, executorID string) (any, error) {
|
||||
profiles, err := h.taskSvc.ListExecutorProfiles(ctx, executorID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
dtos := make([]dto.ExecutorProfileDTO, 0, len(profiles))
|
||||
for _, p := range profiles {
|
||||
dtos = append(dtos, dto.FromExecutorProfile(p))
|
||||
}
|
||||
return dto.ListExecutorProfilesResponse{Profiles: dtos, Total: len(dtos)}, nil
|
||||
})
|
||||
}
|
||||
|
||||
func (h *Handlers) handleCreateExecutorProfile(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
ExecutorID string `json:"executor_id"`
|
||||
Name string `json:"name"`
|
||||
McpPolicy string `json:"mcp_policy"`
|
||||
Config map[string]string `json:"config"`
|
||||
PrepareScript string `json:"prepare_script"`
|
||||
CleanupScript string `json:"cleanup_script"`
|
||||
EnvVars []models.ProfileEnvVar `json:"env_vars"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if req.ExecutorID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "executor_id is required", nil)
|
||||
}
|
||||
if req.Name == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "name is required", nil)
|
||||
}
|
||||
|
||||
profile, err := h.taskSvc.CreateExecutorProfile(ctx, &service.CreateExecutorProfileRequest{
|
||||
ExecutorID: req.ExecutorID,
|
||||
Name: req.Name,
|
||||
McpPolicy: req.McpPolicy,
|
||||
Config: req.Config,
|
||||
PrepareScript: req.PrepareScript,
|
||||
CleanupScript: req.CleanupScript,
|
||||
EnvVars: req.EnvVars,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("failed to create executor profile", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to create executor profile: "+err.Error(), nil)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, dto.FromExecutorProfile(profile))
|
||||
}
|
||||
|
||||
func (h *Handlers) handleUpdateExecutorProfile(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
ProfileID string `json:"profile_id"`
|
||||
Name *string `json:"name"`
|
||||
McpPolicy *string `json:"mcp_policy"`
|
||||
Config map[string]string `json:"config"`
|
||||
PrepareScript *string `json:"prepare_script"`
|
||||
CleanupScript *string `json:"cleanup_script"`
|
||||
EnvVars []models.ProfileEnvVar `json:"env_vars"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if req.ProfileID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "profile_id is required", nil)
|
||||
}
|
||||
|
||||
profile, err := h.taskSvc.UpdateExecutorProfile(ctx, req.ProfileID, &service.UpdateExecutorProfileRequest{
|
||||
Name: req.Name,
|
||||
McpPolicy: req.McpPolicy,
|
||||
Config: req.Config,
|
||||
PrepareScript: req.PrepareScript,
|
||||
CleanupScript: req.CleanupScript,
|
||||
EnvVars: req.EnvVars,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("failed to update executor profile", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to update executor profile: "+err.Error(), nil)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, dto.FromExecutorProfile(profile))
|
||||
}
|
||||
|
||||
func (h *Handlers) handleDeleteExecutorProfile(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
return h.handleDeleteByField(ctx, msg, "profile_id", "failed to delete executor profile", "Failed to delete executor profile",
|
||||
func(ctx context.Context, id string) error { return h.taskSvc.DeleteExecutorProfile(ctx, id) })
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
ws "github.com/kandev/kandev/pkg/websocket"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// --- Test helpers ---
|
||||
|
||||
func testLogger(t *testing.T) *logger.Logger {
|
||||
t.Helper()
|
||||
log, err := logger.NewLogger(logger.LoggingConfig{Level: "error", Format: "console"})
|
||||
require.NoError(t, err)
|
||||
return log
|
||||
}
|
||||
|
||||
func makeWSMessage(t *testing.T, action string, payload interface{}) *ws.Message {
|
||||
t.Helper()
|
||||
data, err := json.Marshal(payload)
|
||||
require.NoError(t, err)
|
||||
return &ws.Message{
|
||||
ID: "test-id",
|
||||
Type: ws.MessageTypeRequest,
|
||||
Action: action,
|
||||
Payload: data,
|
||||
}
|
||||
}
|
||||
|
||||
func assertWSError(t *testing.T, resp *ws.Message, expectedCode string) {
|
||||
t.Helper()
|
||||
require.NotNil(t, resp)
|
||||
assert.Equal(t, ws.MessageTypeError, resp.Type)
|
||||
var ep ws.ErrorPayload
|
||||
require.NoError(t, json.Unmarshal(resp.Payload, &ep))
|
||||
assert.Equal(t, expectedCode, ep.Code)
|
||||
}
|
||||
|
||||
// --- Workflow handler tests ---
|
||||
|
||||
func TestHandleCreateWorkflowStep_MissingWorkflowID(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := makeWSMessage(t, ws.ActionMCPCreateWorkflowStep, map[string]interface{}{
|
||||
"name": "Test Step",
|
||||
})
|
||||
|
||||
resp, err := h.handleCreateWorkflowStep(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
}
|
||||
|
||||
func TestHandleCreateWorkflowStep_MissingName(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := makeWSMessage(t, ws.ActionMCPCreateWorkflowStep, map[string]interface{}{
|
||||
"workflow_id": "wf-123",
|
||||
})
|
||||
|
||||
resp, err := h.handleCreateWorkflowStep(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
}
|
||||
|
||||
func TestHandleCreateWorkflowStep_InvalidPayload(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := &ws.Message{
|
||||
ID: "test-id",
|
||||
Type: ws.MessageTypeRequest,
|
||||
Action: ws.ActionMCPCreateWorkflowStep,
|
||||
Payload: json.RawMessage(`{invalid`),
|
||||
}
|
||||
|
||||
resp, err := h.handleCreateWorkflowStep(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeBadRequest)
|
||||
}
|
||||
|
||||
func TestHandleUpdateWorkflowStep_MissingStepID(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := makeWSMessage(t, ws.ActionMCPUpdateWorkflowStep, map[string]interface{}{
|
||||
"name": "New Name",
|
||||
})
|
||||
|
||||
resp, err := h.handleUpdateWorkflowStep(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
}
|
||||
|
||||
func TestHandleUpdateWorkflowStep_InvalidPayload(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := &ws.Message{
|
||||
ID: "test-id",
|
||||
Type: ws.MessageTypeRequest,
|
||||
Action: ws.ActionMCPUpdateWorkflowStep,
|
||||
Payload: json.RawMessage(`not json`),
|
||||
}
|
||||
|
||||
resp, err := h.handleUpdateWorkflowStep(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeBadRequest)
|
||||
}
|
||||
|
||||
func TestHandleDeleteWorkflowStep_MissingStepID(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := makeWSMessage(t, ws.ActionMCPDeleteWorkflowStep, map[string]string{})
|
||||
|
||||
resp, err := h.handleDeleteWorkflowStep(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
}
|
||||
|
||||
func TestHandleDeleteWorkflowStep_InvalidPayload(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := &ws.Message{
|
||||
ID: "test-id",
|
||||
Type: ws.MessageTypeRequest,
|
||||
Action: ws.ActionMCPDeleteWorkflowStep,
|
||||
Payload: json.RawMessage(`badjson`),
|
||||
}
|
||||
|
||||
resp, err := h.handleDeleteWorkflowStep(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeBadRequest)
|
||||
}
|
||||
|
||||
func TestHandleReorderWorkflowSteps_MissingWorkflowID(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := makeWSMessage(t, ws.ActionMCPReorderWorkflowStep, map[string]interface{}{
|
||||
"step_ids": []string{"s1", "s2"},
|
||||
})
|
||||
|
||||
resp, err := h.handleReorderWorkflowSteps(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
}
|
||||
|
||||
func TestHandleReorderWorkflowSteps_MissingStepIDs(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := makeWSMessage(t, ws.ActionMCPReorderWorkflowStep, map[string]interface{}{
|
||||
"workflow_id": "wf-123",
|
||||
"step_ids": []string{},
|
||||
})
|
||||
|
||||
resp, err := h.handleReorderWorkflowSteps(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
}
|
||||
|
||||
func TestHandleReorderWorkflowSteps_InvalidPayload(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := &ws.Message{
|
||||
ID: "test-id",
|
||||
Type: ws.MessageTypeRequest,
|
||||
Action: ws.ActionMCPReorderWorkflowStep,
|
||||
Payload: json.RawMessage(`{bad}`),
|
||||
}
|
||||
|
||||
resp, err := h.handleReorderWorkflowSteps(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeBadRequest)
|
||||
}
|
||||
|
||||
// --- Agent handler tests ---
|
||||
|
||||
func TestHandleUpdateAgent_MissingAgentID(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := makeWSMessage(t, ws.ActionMCPUpdateAgent, map[string]interface{}{
|
||||
"supports_mcp": true,
|
||||
})
|
||||
|
||||
resp, err := h.handleUpdateAgent(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
}
|
||||
|
||||
func TestHandleUpdateAgent_InvalidPayload(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := &ws.Message{
|
||||
ID: "test-id",
|
||||
Type: ws.MessageTypeRequest,
|
||||
Action: ws.ActionMCPUpdateAgent,
|
||||
Payload: json.RawMessage(`not json`),
|
||||
}
|
||||
|
||||
resp, err := h.handleUpdateAgent(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeBadRequest)
|
||||
}
|
||||
|
||||
func TestHandleListAgentProfiles_MissingAgentID(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := makeWSMessage(t, ws.ActionMCPListAgentProfiles, map[string]string{})
|
||||
|
||||
resp, err := h.handleListAgentProfiles(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
}
|
||||
|
||||
func TestHandleListAgentProfiles_InvalidPayload(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := &ws.Message{
|
||||
ID: "test-id",
|
||||
Type: ws.MessageTypeRequest,
|
||||
Action: ws.ActionMCPListAgentProfiles,
|
||||
Payload: json.RawMessage(`badpayload`),
|
||||
}
|
||||
|
||||
resp, err := h.handleListAgentProfiles(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeBadRequest)
|
||||
}
|
||||
|
||||
func TestHandleUpdateAgentProfile_MissingProfileID(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := makeWSMessage(t, ws.ActionMCPUpdateAgentProfile, map[string]interface{}{
|
||||
"name": "New Name",
|
||||
})
|
||||
|
||||
resp, err := h.handleUpdateAgentProfile(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
}
|
||||
|
||||
func TestHandleUpdateAgentProfile_InvalidPayload(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := &ws.Message{
|
||||
ID: "test-id",
|
||||
Type: ws.MessageTypeRequest,
|
||||
Action: ws.ActionMCPUpdateAgentProfile,
|
||||
Payload: json.RawMessage(`not json`),
|
||||
}
|
||||
|
||||
resp, err := h.handleUpdateAgentProfile(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeBadRequest)
|
||||
}
|
||||
|
||||
// --- MCP Config handler tests ---
|
||||
|
||||
func TestHandleGetMcpConfig_MissingProfileID(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := makeWSMessage(t, ws.ActionMCPGetMcpConfig, map[string]string{})
|
||||
|
||||
resp, err := h.handleGetMcpConfig(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
}
|
||||
|
||||
func TestHandleGetMcpConfig_InvalidPayload(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := &ws.Message{
|
||||
ID: "test-id",
|
||||
Type: ws.MessageTypeRequest,
|
||||
Action: ws.ActionMCPGetMcpConfig,
|
||||
Payload: json.RawMessage(`not json`),
|
||||
}
|
||||
|
||||
resp, err := h.handleGetMcpConfig(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeBadRequest)
|
||||
}
|
||||
|
||||
func TestHandleUpdateMcpConfig_MissingProfileID(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := makeWSMessage(t, ws.ActionMCPUpdateMcpConfig, map[string]interface{}{
|
||||
"enabled": true,
|
||||
})
|
||||
|
||||
resp, err := h.handleUpdateMcpConfig(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
}
|
||||
|
||||
func TestHandleUpdateMcpConfig_InvalidPayload(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := &ws.Message{
|
||||
ID: "test-id",
|
||||
Type: ws.MessageTypeRequest,
|
||||
Action: ws.ActionMCPUpdateMcpConfig,
|
||||
Payload: json.RawMessage(`invalid`),
|
||||
}
|
||||
|
||||
resp, err := h.handleUpdateMcpConfig(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeBadRequest)
|
||||
}
|
||||
|
||||
// --- Task handler tests ---
|
||||
|
||||
func TestHandleMoveTask_MissingTaskID(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := makeWSMessage(t, ws.ActionMCPMoveTask, map[string]interface{}{
|
||||
"workflow_id": "wf-123",
|
||||
"workflow_step_id": "step-1",
|
||||
})
|
||||
|
||||
resp, err := h.handleMoveTask(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
}
|
||||
|
||||
func TestHandleMoveTask_MissingWorkflowID(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := makeWSMessage(t, ws.ActionMCPMoveTask, map[string]interface{}{
|
||||
"task_id": "task-1",
|
||||
"workflow_step_id": "step-1",
|
||||
})
|
||||
|
||||
resp, err := h.handleMoveTask(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
}
|
||||
|
||||
func TestHandleMoveTask_MissingStepID(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := makeWSMessage(t, ws.ActionMCPMoveTask, map[string]interface{}{
|
||||
"task_id": "task-1",
|
||||
"workflow_id": "wf-123",
|
||||
})
|
||||
|
||||
resp, err := h.handleMoveTask(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
}
|
||||
|
||||
func TestHandleMoveTask_InvalidPayload(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := &ws.Message{
|
||||
ID: "test-id",
|
||||
Type: ws.MessageTypeRequest,
|
||||
Action: ws.ActionMCPMoveTask,
|
||||
Payload: json.RawMessage(`invalid`),
|
||||
}
|
||||
|
||||
resp, err := h.handleMoveTask(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeBadRequest)
|
||||
}
|
||||
|
||||
func TestHandleDeleteTask_MissingTaskID(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := makeWSMessage(t, ws.ActionMCPDeleteTask, map[string]string{})
|
||||
|
||||
resp, err := h.handleDeleteTask(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
}
|
||||
|
||||
func TestHandleDeleteTask_InvalidPayload(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := &ws.Message{
|
||||
ID: "test-id",
|
||||
Type: ws.MessageTypeRequest,
|
||||
Action: ws.ActionMCPDeleteTask,
|
||||
Payload: json.RawMessage(`not json`),
|
||||
}
|
||||
|
||||
resp, err := h.handleDeleteTask(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeBadRequest)
|
||||
}
|
||||
|
||||
func TestHandleArchiveTask_MissingTaskID(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := makeWSMessage(t, ws.ActionMCPArchiveTask, map[string]string{})
|
||||
|
||||
resp, err := h.handleArchiveTask(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
}
|
||||
|
||||
func TestHandleArchiveTask_InvalidPayload(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := &ws.Message{
|
||||
ID: "test-id",
|
||||
Type: ws.MessageTypeRequest,
|
||||
Action: ws.ActionMCPArchiveTask,
|
||||
Payload: json.RawMessage(`bad`),
|
||||
}
|
||||
|
||||
resp, err := h.handleArchiveTask(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeBadRequest)
|
||||
}
|
||||
|
||||
func TestHandleUpdateTaskState_MissingTaskID(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := makeWSMessage(t, ws.ActionMCPUpdateTaskState, map[string]interface{}{
|
||||
"state": "in_progress",
|
||||
})
|
||||
|
||||
resp, err := h.handleUpdateTaskState(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
}
|
||||
|
||||
func TestHandleUpdateTaskState_MissingState(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := makeWSMessage(t, ws.ActionMCPUpdateTaskState, map[string]interface{}{
|
||||
"task_id": "task-1",
|
||||
})
|
||||
|
||||
resp, err := h.handleUpdateTaskState(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeValidation)
|
||||
}
|
||||
|
||||
func TestHandleUpdateTaskState_InvalidPayload(t *testing.T) {
|
||||
h := &Handlers{}
|
||||
msg := &ws.Message{
|
||||
ID: "test-id",
|
||||
Type: ws.MessageTypeRequest,
|
||||
Action: ws.ActionMCPUpdateTaskState,
|
||||
Payload: json.RawMessage(`not json`),
|
||||
}
|
||||
|
||||
resp, err := h.handleUpdateTaskState(context.Background(), msg)
|
||||
require.NoError(t, err)
|
||||
assertWSError(t, resp, ws.ErrorCodeBadRequest)
|
||||
}
|
||||
|
||||
// --- Registration tests ---
|
||||
|
||||
func TestRegisterHandlers_NilDeps_DoesNotPanic(t *testing.T) {
|
||||
log := testLogger(t)
|
||||
h := &Handlers{logger: log}
|
||||
d := ws.NewDispatcher()
|
||||
|
||||
// Should not panic with nil config/task deps — handlers simply not registered.
|
||||
assert.NotPanics(t, func() { h.RegisterHandlers(d) })
|
||||
}
|
||||
|
||||
// --- Helper function tests ---
|
||||
|
||||
func TestUnmarshalStringField(t *testing.T) {
|
||||
t.Run("valid field", func(t *testing.T) {
|
||||
payload := json.RawMessage(`{"task_id":"abc-123"}`)
|
||||
val, err := unmarshalStringField(payload, "task_id")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "abc-123", val)
|
||||
})
|
||||
|
||||
t.Run("missing field returns empty", func(t *testing.T) {
|
||||
payload := json.RawMessage(`{"other":"value"}`)
|
||||
val, err := unmarshalStringField(payload, "task_id")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "", val)
|
||||
})
|
||||
|
||||
t.Run("invalid json", func(t *testing.T) {
|
||||
payload := json.RawMessage(`not json`)
|
||||
_, err := unmarshalStringField(payload, "task_id")
|
||||
assert.Error(t, err)
|
||||
})
|
||||
|
||||
t.Run("empty payload", func(t *testing.T) {
|
||||
payload := json.RawMessage(`{}`)
|
||||
val, err := unmarshalStringField(payload, "task_id")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, "", val)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/mcpconfig"
|
||||
ws "github.com/kandev/kandev/pkg/websocket"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func (h *Handlers) handleGetMcpConfig(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
profileID, err := unmarshalStringField(msg.Payload, "profile_id")
|
||||
if err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if profileID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "profile_id is required", nil)
|
||||
}
|
||||
|
||||
config, err := h.mcpConfigSvc.GetConfigByProfileID(ctx, profileID)
|
||||
if err != nil {
|
||||
h.logger.Error("failed to get MCP config", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to get MCP config", nil)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, config)
|
||||
}
|
||||
|
||||
func (h *Handlers) handleUpdateMcpConfig(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
ProfileID string `json:"profile_id"`
|
||||
Enabled *bool `json:"enabled"`
|
||||
Servers map[string]mcpconfig.ServerDef `json:"servers"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if req.ProfileID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "profile_id is required", nil)
|
||||
}
|
||||
|
||||
// Get existing config to merge with
|
||||
existing, err := h.mcpConfigSvc.GetConfigByProfileID(ctx, req.ProfileID)
|
||||
if err != nil {
|
||||
h.logger.Error("failed to get existing MCP config", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to get existing MCP config", nil)
|
||||
}
|
||||
|
||||
if req.Enabled != nil {
|
||||
existing.Enabled = *req.Enabled
|
||||
}
|
||||
if req.Servers != nil {
|
||||
existing.Servers = req.Servers
|
||||
}
|
||||
|
||||
updated, err := h.mcpConfigSvc.UpsertConfigByProfileID(ctx, req.ProfileID, existing)
|
||||
if err != nil {
|
||||
h.logger.Error("failed to update MCP config", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to update MCP config", nil)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, updated)
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/kandev/kandev/internal/task/dto"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
ws "github.com/kandev/kandev/pkg/websocket"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func (h *Handlers) handleMoveTask(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
TaskID string `json:"task_id"`
|
||||
WorkflowID string `json:"workflow_id"`
|
||||
WorkflowStepID string `json:"workflow_step_id"`
|
||||
Position int `json:"position"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if req.TaskID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "task_id is required", nil)
|
||||
}
|
||||
if req.WorkflowID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "workflow_id is required", nil)
|
||||
}
|
||||
if req.WorkflowStepID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "workflow_step_id is required", nil)
|
||||
}
|
||||
|
||||
result, err := h.taskSvc.MoveTask(ctx, req.TaskID, req.WorkflowID, req.WorkflowStepID, req.Position)
|
||||
if err != nil {
|
||||
h.logger.Error("failed to move task", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to move task", nil)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, dto.FromTask(result.Task))
|
||||
}
|
||||
|
||||
func (h *Handlers) handleDeleteTask(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
taskID, err := unmarshalStringField(msg.Payload, "task_id")
|
||||
if err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if taskID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "task_id is required", nil)
|
||||
}
|
||||
|
||||
if err := h.taskSvc.DeleteTask(ctx, taskID); err != nil {
|
||||
h.logger.Error("failed to delete task", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to delete task", nil)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{"success": true})
|
||||
}
|
||||
|
||||
func (h *Handlers) handleArchiveTask(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
taskID, err := unmarshalStringField(msg.Payload, "task_id")
|
||||
if err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if taskID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "task_id is required", nil)
|
||||
}
|
||||
|
||||
if err := h.taskSvc.ArchiveTask(ctx, taskID); err != nil {
|
||||
h.logger.Error("failed to archive task", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to archive task", nil)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{"success": true})
|
||||
}
|
||||
|
||||
func (h *Handlers) handleUpdateTaskState(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
TaskID string `json:"task_id"`
|
||||
State string `json:"state"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if req.TaskID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "task_id is required", nil)
|
||||
}
|
||||
if req.State == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "state is required", nil)
|
||||
}
|
||||
state := v1.TaskState(req.State)
|
||||
switch state {
|
||||
case v1.TaskStateTODO, v1.TaskStateCreated, v1.TaskStateScheduling,
|
||||
v1.TaskStateInProgress, v1.TaskStateReview, v1.TaskStateBlocked,
|
||||
v1.TaskStateWaitingForInput, v1.TaskStateCompleted,
|
||||
v1.TaskStateFailed, v1.TaskStateCancelled:
|
||||
// valid
|
||||
default:
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "invalid task state: "+req.State, nil)
|
||||
}
|
||||
|
||||
task, err := h.taskSvc.UpdateTaskState(ctx, req.TaskID, state)
|
||||
if err != nil {
|
||||
h.logger.Error("failed to update task state", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to update task state", nil)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, dto.FromTask(task))
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/kandev/kandev/internal/events"
|
||||
"github.com/kandev/kandev/internal/events/bus"
|
||||
"github.com/kandev/kandev/internal/task/service"
|
||||
workflowctrl "github.com/kandev/kandev/internal/workflow/controller"
|
||||
wfmodels "github.com/kandev/kandev/internal/workflow/models"
|
||||
ws "github.com/kandev/kandev/pkg/websocket"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func (h *Handlers) handleCreateWorkflow(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
WorkspaceID string `json:"workspace_id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if req.WorkspaceID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "workspace_id is required", nil)
|
||||
}
|
||||
if req.Name == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "name is required", nil)
|
||||
}
|
||||
|
||||
workflow, err := h.taskSvc.CreateWorkflow(ctx, &service.CreateWorkflowRequest{
|
||||
WorkspaceID: req.WorkspaceID,
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("failed to create workflow", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to create workflow", nil)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, workflow)
|
||||
}
|
||||
|
||||
func (h *Handlers) handleUpdateWorkflow(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
WorkflowID string `json:"workflow_id"`
|
||||
Name *string `json:"name"`
|
||||
Description *string `json:"description"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if req.WorkflowID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "workflow_id is required", nil)
|
||||
}
|
||||
|
||||
workflow, err := h.taskSvc.UpdateWorkflow(ctx, req.WorkflowID, &service.UpdateWorkflowRequest{
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("failed to update workflow", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to update workflow", nil)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, workflow)
|
||||
}
|
||||
|
||||
func (h *Handlers) handleDeleteWorkflow(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
workflowID, err := unmarshalStringField(msg.Payload, "workflow_id")
|
||||
if err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if workflowID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "workflow_id is required", nil)
|
||||
}
|
||||
|
||||
if err := h.taskSvc.DeleteWorkflow(ctx, workflowID); err != nil {
|
||||
h.logger.Error("failed to delete workflow", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to delete workflow", nil)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{"success": true})
|
||||
}
|
||||
|
||||
func (h *Handlers) handleCreateWorkflowStep(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
WorkflowID string `json:"workflow_id"`
|
||||
Name string `json:"name"`
|
||||
Position int `json:"position"`
|
||||
Color string `json:"color"`
|
||||
Prompt string `json:"prompt"`
|
||||
IsStartStep *bool `json:"is_start_step"`
|
||||
AllowManualMove *bool `json:"allow_manual_move"`
|
||||
ShowInCommandPanel *bool `json:"show_in_command_panel"`
|
||||
Events *wfmodels.StepEvents `json:"events"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if req.WorkflowID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "workflow_id is required", nil)
|
||||
}
|
||||
if req.Name == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "name is required", nil)
|
||||
}
|
||||
|
||||
createReq := workflowctrl.CreateStepRequest{
|
||||
WorkflowID: req.WorkflowID,
|
||||
Name: req.Name,
|
||||
Position: req.Position,
|
||||
Color: req.Color,
|
||||
Prompt: req.Prompt,
|
||||
IsStartStep: req.IsStartStep,
|
||||
ShowInCommandPanel: req.ShowInCommandPanel,
|
||||
Events: req.Events,
|
||||
}
|
||||
if req.AllowManualMove != nil {
|
||||
createReq.AllowManualMove = *req.AllowManualMove
|
||||
}
|
||||
|
||||
resp, err := h.workflowCtrl.CreateStep(ctx, createReq)
|
||||
if err != nil {
|
||||
h.logger.Error("failed to create workflow step", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to create workflow step", nil)
|
||||
}
|
||||
h.publishWorkflowStepEvent(ctx, events.WorkflowStepCreated, resp.Step)
|
||||
return ws.NewResponse(msg.ID, msg.Action, resp)
|
||||
}
|
||||
|
||||
func (h *Handlers) handleUpdateWorkflowStep(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
StepID string `json:"step_id"`
|
||||
Name *string `json:"name"`
|
||||
Color *string `json:"color"`
|
||||
Prompt *string `json:"prompt"`
|
||||
IsStartStep *bool `json:"is_start_step"`
|
||||
AllowManualMove *bool `json:"allow_manual_move"`
|
||||
ShowInCommandPanel *bool `json:"show_in_command_panel"`
|
||||
AutoArchiveAfterHours *int `json:"auto_archive_after_hours"`
|
||||
Events *wfmodels.StepEvents `json:"events"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if req.StepID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "step_id is required", nil)
|
||||
}
|
||||
|
||||
updateReq := workflowctrl.UpdateStepRequest{
|
||||
ID: req.StepID,
|
||||
Name: req.Name,
|
||||
Color: req.Color,
|
||||
Prompt: req.Prompt,
|
||||
IsStartStep: req.IsStartStep,
|
||||
AllowManualMove: req.AllowManualMove,
|
||||
ShowInCommandPanel: req.ShowInCommandPanel,
|
||||
AutoArchiveAfterHours: req.AutoArchiveAfterHours,
|
||||
Events: req.Events,
|
||||
}
|
||||
|
||||
resp, err := h.workflowCtrl.UpdateStep(ctx, updateReq)
|
||||
if err != nil {
|
||||
h.logger.Error("failed to update workflow step", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to update workflow step", nil)
|
||||
}
|
||||
h.publishWorkflowStepEvent(ctx, events.WorkflowStepUpdated, resp.Step)
|
||||
return ws.NewResponse(msg.ID, msg.Action, resp)
|
||||
}
|
||||
|
||||
func (h *Handlers) handleDeleteWorkflowStep(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
stepID, err := unmarshalStringField(msg.Payload, "step_id")
|
||||
if err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if stepID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "step_id is required", nil)
|
||||
}
|
||||
|
||||
// Fetch step before deleting to get workflow_id for the event
|
||||
stepResp, _ := h.workflowCtrl.GetStep(ctx, stepID)
|
||||
|
||||
if err := h.workflowCtrl.DeleteStep(ctx, stepID); err != nil {
|
||||
h.logger.Error("failed to delete workflow step", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to delete workflow step", nil)
|
||||
}
|
||||
if stepResp != nil {
|
||||
h.publishWorkflowStepEvent(ctx, events.WorkflowStepDeleted, stepResp.Step)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{"success": true})
|
||||
}
|
||||
|
||||
func (h *Handlers) handleReorderWorkflowSteps(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req struct {
|
||||
WorkflowID string `json:"workflow_id"`
|
||||
StepIDs []string `json:"step_ids"`
|
||||
}
|
||||
if err := json.Unmarshal(msg.Payload, &req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if req.WorkflowID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "workflow_id is required", nil)
|
||||
}
|
||||
if len(req.StepIDs) == 0 {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "step_ids is required", nil)
|
||||
}
|
||||
|
||||
if err := h.workflowCtrl.ReorderSteps(ctx, workflowctrl.ReorderStepsRequest{
|
||||
WorkflowID: req.WorkflowID,
|
||||
StepIDs: req.StepIDs,
|
||||
}); err != nil {
|
||||
h.logger.Error("failed to reorder workflow steps", zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to reorder workflow steps", nil)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{"success": true})
|
||||
}
|
||||
|
||||
// publishWorkflowStepEvent publishes a workflow step event to the event bus.
|
||||
func (h *Handlers) publishWorkflowStepEvent(ctx context.Context, eventType string, step *wfmodels.WorkflowStep) {
|
||||
if h.eventBus == nil || step == nil {
|
||||
return
|
||||
}
|
||||
data := map[string]interface{}{
|
||||
"step": map[string]interface{}{
|
||||
"id": step.ID,
|
||||
"workflow_id": step.WorkflowID,
|
||||
"name": step.Name,
|
||||
"position": step.Position,
|
||||
"color": step.Color,
|
||||
"prompt": step.Prompt,
|
||||
"events": step.Events,
|
||||
"show_in_command_panel": step.ShowInCommandPanel,
|
||||
"allow_manual_move": step.AllowManualMove,
|
||||
"is_start_step": step.IsStartStep,
|
||||
"auto_archive_after_hours": step.AutoArchiveAfterHours,
|
||||
},
|
||||
}
|
||||
if err := h.eventBus.Publish(ctx, eventType, bus.NewEvent(eventType, "mcp-handlers", data)); err != nil {
|
||||
h.logger.Error("failed to publish workflow step event",
|
||||
zap.String("event_type", eventType),
|
||||
zap.String("step_id", step.ID),
|
||||
zap.Error(err))
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,8 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/mcpconfig"
|
||||
agentsettingscontroller "github.com/kandev/kandev/internal/agent/settings/controller"
|
||||
"github.com/kandev/kandev/internal/clarification"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/internal/events"
|
||||
@@ -17,6 +19,7 @@ import (
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
"github.com/kandev/kandev/internal/task/service"
|
||||
workflowctrl "github.com/kandev/kandev/internal/workflow/controller"
|
||||
workflowsvc "github.com/kandev/kandev/internal/workflow/service"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
ws "github.com/kandev/kandev/pkg/websocket"
|
||||
"go.uber.org/zap"
|
||||
@@ -61,6 +64,11 @@ type Handlers struct {
|
||||
eventBus EventBus
|
||||
planService *service.PlanService
|
||||
logger *logger.Logger
|
||||
|
||||
// Config-mode dependencies (optional, set via SetConfigDeps)
|
||||
workflowSvc *workflowsvc.Service
|
||||
agentSettingsCtrl *agentsettingscontroller.Controller
|
||||
mcpConfigSvc *mcpconfig.Service
|
||||
}
|
||||
|
||||
// NewHandlers creates new MCP handlers.
|
||||
@@ -88,8 +96,21 @@ func NewHandlers(
|
||||
}
|
||||
}
|
||||
|
||||
// SetConfigDeps sets the config-mode dependencies for agent-native configuration handlers.
|
||||
// These are optional and only needed when config-mode MCP sessions are used.
|
||||
func (h *Handlers) SetConfigDeps(
|
||||
workflowSvc *workflowsvc.Service,
|
||||
agentSettingsCtrl *agentsettingscontroller.Controller,
|
||||
mcpConfigSvc *mcpconfig.Service,
|
||||
) {
|
||||
h.workflowSvc = workflowSvc
|
||||
h.agentSettingsCtrl = agentSettingsCtrl
|
||||
h.mcpConfigSvc = mcpConfigSvc
|
||||
}
|
||||
|
||||
// RegisterHandlers registers all MCP handlers with the dispatcher.
|
||||
func (h *Handlers) RegisterHandlers(d *ws.Dispatcher) {
|
||||
// Task-mode handlers (always registered)
|
||||
d.RegisterFunc(ws.ActionMCPListWorkspaces, h.handleListWorkspaces)
|
||||
d.RegisterFunc(ws.ActionMCPListWorkflows, h.handleListWorkflows)
|
||||
d.RegisterFunc(ws.ActionMCPListWorkflowSteps, h.handleListWorkflowSteps)
|
||||
@@ -102,8 +123,52 @@ func (h *Handlers) RegisterHandlers(d *ws.Dispatcher) {
|
||||
d.RegisterFunc(ws.ActionMCPUpdateTaskPlan, h.handleUpdateTaskPlan)
|
||||
d.RegisterFunc(ws.ActionMCPDeleteTaskPlan, h.handleDeleteTaskPlan)
|
||||
d.RegisterFunc(ws.ActionMCPClarificationTimeout, h.handleClarificationTimeout)
|
||||
count := 12
|
||||
|
||||
h.logger.Info("registered MCP handlers", zap.Int("count", 12))
|
||||
// Config-mode handlers (registered when config deps are set)
|
||||
if h.workflowSvc != nil {
|
||||
d.RegisterFunc(ws.ActionMCPCreateWorkflow, h.handleCreateWorkflow)
|
||||
d.RegisterFunc(ws.ActionMCPUpdateWorkflow, h.handleUpdateWorkflow)
|
||||
d.RegisterFunc(ws.ActionMCPDeleteWorkflow, h.handleDeleteWorkflow)
|
||||
d.RegisterFunc(ws.ActionMCPCreateWorkflowStep, h.handleCreateWorkflowStep)
|
||||
d.RegisterFunc(ws.ActionMCPUpdateWorkflowStep, h.handleUpdateWorkflowStep)
|
||||
d.RegisterFunc(ws.ActionMCPDeleteWorkflowStep, h.handleDeleteWorkflowStep)
|
||||
d.RegisterFunc(ws.ActionMCPReorderWorkflowStep, h.handleReorderWorkflowSteps)
|
||||
count += 7
|
||||
}
|
||||
if h.agentSettingsCtrl != nil {
|
||||
d.RegisterFunc(ws.ActionMCPListAgents, h.handleListAgents)
|
||||
d.RegisterFunc(ws.ActionMCPUpdateAgent, h.handleUpdateAgent)
|
||||
d.RegisterFunc(ws.ActionMCPListAgentProfiles, h.handleListAgentProfiles)
|
||||
d.RegisterFunc(ws.ActionMCPCreateAgentProfile, h.handleCreateAgentProfile)
|
||||
d.RegisterFunc(ws.ActionMCPUpdateAgentProfile, h.handleUpdateAgentProfile)
|
||||
d.RegisterFunc(ws.ActionMCPDeleteAgentProfile, h.handleDeleteAgentProfile)
|
||||
count += 6
|
||||
}
|
||||
if h.mcpConfigSvc != nil {
|
||||
d.RegisterFunc(ws.ActionMCPGetMcpConfig, h.handleGetMcpConfig)
|
||||
d.RegisterFunc(ws.ActionMCPUpdateMcpConfig, h.handleUpdateMcpConfig)
|
||||
count += 2
|
||||
}
|
||||
if h.taskSvc != nil {
|
||||
d.RegisterFunc(ws.ActionMCPMoveTask, h.handleMoveTask)
|
||||
d.RegisterFunc(ws.ActionMCPDeleteTask, h.handleDeleteTask)
|
||||
d.RegisterFunc(ws.ActionMCPArchiveTask, h.handleArchiveTask)
|
||||
d.RegisterFunc(ws.ActionMCPUpdateTaskState, h.handleUpdateTaskState)
|
||||
count += 4
|
||||
|
||||
// Executor config handlers (gated on config-mode via workflowSvc)
|
||||
if h.workflowSvc != nil {
|
||||
d.RegisterFunc(ws.ActionMCPListExecutors, h.handleListExecutors)
|
||||
d.RegisterFunc(ws.ActionMCPListExecutorProfiles, h.handleListExecutorProfiles)
|
||||
d.RegisterFunc(ws.ActionMCPCreateExecutorProfile, h.handleCreateExecutorProfile)
|
||||
d.RegisterFunc(ws.ActionMCPUpdateExecutorProfile, h.handleUpdateExecutorProfile)
|
||||
d.RegisterFunc(ws.ActionMCPDeleteExecutorProfile, h.handleDeleteExecutorProfile)
|
||||
count += 5
|
||||
}
|
||||
}
|
||||
|
||||
h.logger.Info("registered MCP handlers", zap.Int("count", count))
|
||||
}
|
||||
|
||||
// handleListWorkspaces lists all workspaces.
|
||||
@@ -150,6 +215,26 @@ func (h *Handlers) handleListByField(
|
||||
return ws.NewResponse(msg.ID, msg.Action, resp)
|
||||
}
|
||||
|
||||
// handleDeleteByField is a generic handler for deleting a resource identified by a single string field.
|
||||
func (h *Handlers) handleDeleteByField(
|
||||
ctx context.Context, msg *ws.Message,
|
||||
fieldName, logErrMsg, clientErrMsg string,
|
||||
fn func(context.Context, string) error,
|
||||
) (*ws.Message, error) {
|
||||
value, err := unmarshalStringField(msg.Payload, fieldName)
|
||||
if err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid payload: "+err.Error(), nil)
|
||||
}
|
||||
if value == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, fieldName+" is required", nil)
|
||||
}
|
||||
if err := fn(ctx, value); err != nil {
|
||||
h.logger.Error(logErrMsg, zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, clientErrMsg+": "+err.Error(), nil)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{"success": true})
|
||||
}
|
||||
|
||||
// handleListWorkflows lists workflows for a workspace.
|
||||
func (h *Handlers) handleListWorkflows(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
return h.handleListByField(ctx, msg, "workspace_id", "failed to list workflows", "Failed to list workflows",
|
||||
|
||||
@@ -175,6 +175,9 @@ func (m *mockAgentManager) SetExecutionDescription(_ context.Context, _, _ strin
|
||||
func (m *mockAgentManager) SetSessionModelBySessionID(_ context.Context, _, _ string) error {
|
||||
return fmt.Errorf("not supported")
|
||||
}
|
||||
func (m *mockAgentManager) SetMcpMode(_ context.Context, _ string, _ string) error {
|
||||
return nil
|
||||
}
|
||||
func (m *mockAgentManager) WasSessionInitialized(_ string) bool { return false }
|
||||
func (m *mockAgentManager) GetSessionAuthMethods(_ string) []streams.AuthMethodInfo {
|
||||
return nil
|
||||
|
||||
@@ -299,7 +299,16 @@ func (s *Service) handleTaskMoved(ctx context.Context, data watcher.TaskMovedEve
|
||||
// If the target step has auto_start_agent, it creates a session and starts the agent
|
||||
// using agent/executor profile IDs from the task's metadata.
|
||||
func (s *Service) handleTaskMovedNoSession(ctx context.Context, data watcher.TaskMovedEventData) {
|
||||
if !s.shouldAutoStartStep(ctx, data.ToStepID) {
|
||||
// Load the target step to check auto-start and plan mode flags
|
||||
step, err := s.workflowStepGetter.GetStep(ctx, data.ToStepID)
|
||||
if err != nil {
|
||||
s.logger.Warn("task.moved: failed to load target step",
|
||||
zap.String("task_id", data.TaskID),
|
||||
zap.String("to_step_id", data.ToStepID),
|
||||
zap.Error(err))
|
||||
return
|
||||
}
|
||||
if step == nil || !step.HasOnEnterAction(wfmodels.OnEnterAutoStartAgent) {
|
||||
s.logger.Debug("task.moved: no session and target step has no auto-start",
|
||||
zap.String("task_id", data.TaskID),
|
||||
zap.String("to_step_id", data.ToStepID))
|
||||
@@ -316,14 +325,16 @@ func (s *Service) handleTaskMovedNoSession(ctx context.Context, data watcher.Tas
|
||||
|
||||
agentProfileID, _ := task.Metadata["agent_profile_id"].(string)
|
||||
executorProfileID, _ := task.Metadata["executor_profile_id"].(string)
|
||||
planMode := step.HasOnEnterAction(wfmodels.OnEnterEnablePlanMode)
|
||||
|
||||
s.logger.Info("task.moved: starting task (no session, auto-start step)",
|
||||
zap.String("task_id", data.TaskID),
|
||||
zap.String("to_step_id", data.ToStepID),
|
||||
zap.String("agent_profile_id", agentProfileID),
|
||||
zap.String("executor_profile_id", executorProfileID))
|
||||
zap.String("executor_profile_id", executorProfileID),
|
||||
zap.Bool("plan_mode", planMode))
|
||||
|
||||
_, err = s.StartTask(ctx, task.ID, agentProfileID, "", executorProfileID, 0, task.Description, data.ToStepID, false)
|
||||
_, err = s.StartTask(ctx, task.ID, agentProfileID, "", executorProfileID, 0, task.Description, data.ToStepID, planMode)
|
||||
if err != nil {
|
||||
s.logger.Error("task.moved: failed to auto-start task",
|
||||
zap.String("task_id", data.TaskID),
|
||||
@@ -455,7 +466,7 @@ func (s *Service) processOnEnter(ctx context.Context, taskID string, session *mo
|
||||
// Passthrough path: write prompt directly to PTY stdin.
|
||||
// By the time processOnEnter runs (from an on_turn_complete transition),
|
||||
// the agent has finished its previous turn and the PTY is waiting for input.
|
||||
effectivePrompt := s.buildWorkflowPrompt(taskDescription, step, taskID)
|
||||
effectivePrompt := s.buildWorkflowPrompt(taskDescription, step, taskID, sessionID)
|
||||
if err := s.autoStartPassthroughPrompt(ctx, taskID, session, step.Name, effectivePrompt); err != nil {
|
||||
s.logger.Error("failed to auto-start passthrough agent for step",
|
||||
zap.String("task_id", taskID),
|
||||
@@ -470,7 +481,7 @@ func (s *Service) processOnEnter(ctx context.Context, taskID string, session *mo
|
||||
// ACP path: build prompt from step configuration.
|
||||
// Run auto-start inline so queue state is visible before handleAgentReady
|
||||
// checks for queued messages.
|
||||
effectivePrompt := s.buildWorkflowPrompt(taskDescription, step, taskID)
|
||||
effectivePrompt := s.buildWorkflowPrompt(taskDescription, step, taskID, sessionID)
|
||||
planMode := hasPlanMode
|
||||
err := s.autoStartStepPrompt(ctx, taskID, session, step.Name, effectivePrompt, planMode, true)
|
||||
if err != nil {
|
||||
|
||||
@@ -97,6 +97,10 @@ type AgentManagerClient interface {
|
||||
// Used when starting an agent on a session whose workspace was already launched.
|
||||
SetExecutionDescription(ctx context.Context, agentExecutionID string, description string) error
|
||||
|
||||
// SetMcpMode changes the MCP tool mode on an existing execution's agentctl instance.
|
||||
// Used when a session transitions to config mode after the workspace was prepared with default mode.
|
||||
SetMcpMode(ctx context.Context, executionID string, mode string) error
|
||||
|
||||
// RestartAgentProcess stops the agent subprocess and starts a fresh one with a new ACP session,
|
||||
// clearing the agent's conversation context. The execution environment (container/agentctl) is preserved.
|
||||
RestartAgentProcess(ctx context.Context, agentExecutionID string) error
|
||||
@@ -213,6 +217,7 @@ type LaunchAgentRequest struct {
|
||||
ExecutorType string // Executor type (e.g., "local", "worktree", "local_docker") - determines runtime
|
||||
ExecutorConfig map[string]string // Executor config (docker_host, git_token, etc.)
|
||||
PreviousExecutionID string // Previous execution ID for runtime reconnect
|
||||
McpMode string // MCP tool mode: "config" activates config-mode tools
|
||||
|
||||
// Setup script from executor profile (runs in execution environment before agent starts)
|
||||
SetupScript string
|
||||
@@ -227,6 +232,10 @@ type LaunchAgentRequest struct {
|
||||
PullBeforeWorktree bool // Whether to pull from remote before creating the worktree
|
||||
}
|
||||
|
||||
// McpModeConfig activates config-mode MCP tools (workflow steps, agents, MCP
|
||||
// config, tasks). Used when plan_mode is enabled on a session.
|
||||
const McpModeConfig = "config"
|
||||
|
||||
// LaunchOptions contains optional parameters for LaunchPreparedSession.
|
||||
type LaunchOptions struct {
|
||||
AgentProfileID string
|
||||
@@ -234,6 +243,7 @@ type LaunchOptions struct {
|
||||
Prompt string
|
||||
WorkflowStepID string
|
||||
StartAgent bool
|
||||
McpMode string // MCP tool mode: McpModeConfig activates config-mode tools
|
||||
}
|
||||
|
||||
// LaunchAgentResponse contains the result of launching an agent
|
||||
|
||||
@@ -14,6 +14,16 @@ import (
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// isConfigModeSession returns true if the session has config_mode: true in its metadata.
|
||||
// Config-mode sessions are dedicated settings-chat sessions that get config MCP tools.
|
||||
func isConfigModeSession(session *models.TaskSession) bool {
|
||||
if session == nil || session.Metadata == nil {
|
||||
return false
|
||||
}
|
||||
cm, ok := session.Metadata["config_mode"].(bool)
|
||||
return ok && cm
|
||||
}
|
||||
|
||||
// runAgentProcessAsync starts the agent subprocess in a background goroutine.
|
||||
// On error it marks both the session and task as FAILED.
|
||||
// On success it calls onSuccess with a non-cancellable context derived from ctx.
|
||||
@@ -221,6 +231,7 @@ func (e *Executor) PrepareSession(ctx context.Context, task *v1.Task, agentProfi
|
||||
AgentProfileSnapshot: agentProfileSnapshot,
|
||||
IsPrimary: true,
|
||||
IsPassthrough: isPassthrough,
|
||||
Metadata: metadata,
|
||||
}
|
||||
if workflowStepID != "" {
|
||||
session.WorkflowStepID = &workflowStepID
|
||||
@@ -311,7 +322,7 @@ func (e *Executor) LaunchPreparedSession(ctx context.Context, task *v1.Task, ses
|
||||
// Fast path: workspace already launched (e.g., from PrepareSession with workspace).
|
||||
// Only start the agent subprocess if requested; otherwise return early.
|
||||
if session.AgentExecutionID != "" {
|
||||
return e.startAgentOnExistingWorkspace(ctx, task, session, prompt, startAgent)
|
||||
return e.startAgentOnExistingWorkspace(ctx, task, session, prompt, startAgent, opts.McpMode)
|
||||
}
|
||||
|
||||
repoInfo, err := e.resolvePrimaryRepoInfo(ctx, task.ID)
|
||||
@@ -324,6 +335,11 @@ func (e *Executor) LaunchPreparedSession(ctx context.Context, task *v1.Task, ses
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Apply McpMode from options (takes precedence over session metadata check in buildLaunchAgentRequest)
|
||||
if opts.McpMode != "" {
|
||||
req.McpMode = opts.McpMode
|
||||
}
|
||||
|
||||
e.logger.Info("launching agent for prepared session",
|
||||
zap.String("task_id", task.ID),
|
||||
zap.String("session_id", sessionID),
|
||||
@@ -466,6 +482,11 @@ func (e *Executor) buildLaunchAgentRequest(ctx context.Context, task *v1.Task, s
|
||||
req.RepositoryURL = cloneURL
|
||||
}
|
||||
|
||||
// Activate config-mode MCP tools when config_mode is set in session metadata.
|
||||
if isConfigModeSession(session) {
|
||||
req.McpMode = McpModeConfig
|
||||
}
|
||||
|
||||
if len(metadata) > 0 {
|
||||
req.Metadata = metadata
|
||||
}
|
||||
@@ -475,7 +496,7 @@ func (e *Executor) buildLaunchAgentRequest(ctx context.Context, task *v1.Task, s
|
||||
|
||||
// startAgentOnExistingWorkspace handles the case where LaunchPreparedSession is called on a session
|
||||
// whose workspace (agentctl) was already launched. It optionally starts just the agent subprocess.
|
||||
func (e *Executor) startAgentOnExistingWorkspace(ctx context.Context, task *v1.Task, session *models.TaskSession, prompt string, startAgent bool) (*TaskExecution, error) {
|
||||
func (e *Executor) startAgentOnExistingWorkspace(ctx context.Context, task *v1.Task, session *models.TaskSession, prompt string, startAgent bool, mcpMode string) (*TaskExecution, error) {
|
||||
if !startAgent {
|
||||
// Workspace already launched, nothing else to do
|
||||
now := time.Now().UTC()
|
||||
@@ -501,6 +522,23 @@ func (e *Executor) startAgentOnExistingWorkspace(ctx context.Context, task *v1.T
|
||||
}
|
||||
}
|
||||
|
||||
// If config MCP mode is needed, reconfigure the MCP server before starting the agent.
|
||||
// The workspace may have been prepared before config_mode was set on the session.
|
||||
effectiveMcpMode := mcpMode
|
||||
if effectiveMcpMode == "" && isConfigModeSession(session) {
|
||||
effectiveMcpMode = McpModeConfig
|
||||
}
|
||||
if effectiveMcpMode != "" {
|
||||
if err := e.agentManager.SetMcpMode(ctx, session.AgentExecutionID, effectiveMcpMode); err != nil {
|
||||
e.logger.Error("failed to set MCP mode for existing workspace",
|
||||
zap.String("session_id", session.ID),
|
||||
zap.String("agent_execution_id", session.AgentExecutionID),
|
||||
zap.String("mcp_mode", effectiveMcpMode),
|
||||
zap.Error(err))
|
||||
return nil, fmt.Errorf("set MCP mode %q: %w", effectiveMcpMode, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Transition session to STARTING
|
||||
now := time.Now().UTC()
|
||||
session.State = models.TaskSessionStateStarting
|
||||
|
||||
@@ -283,6 +283,11 @@ func (e *Executor) buildSwitchModelRequest(ctx context.Context, task *models.Tas
|
||||
Metadata: execConfig.Metadata,
|
||||
}
|
||||
|
||||
// Activate config-mode MCP tools when config_mode is set in session metadata.
|
||||
if isConfigModeSession(session) {
|
||||
req.McpMode = McpModeConfig
|
||||
}
|
||||
|
||||
repositoryPath, err := e.applyRepositoryToSwitchRequest(ctx, req, session, execConfig)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
|
||||
@@ -364,6 +364,11 @@ func (e *Executor) buildResumeRequest(ctx context.Context, task *v1.Task, sessio
|
||||
return nil, "", execConfig, nil, err
|
||||
}
|
||||
|
||||
// Activate config-mode MCP tools when config_mode is set in session metadata.
|
||||
if isConfigModeSession(session) {
|
||||
req.McpMode = McpModeConfig
|
||||
}
|
||||
|
||||
existingRunning := e.applyRunningRecordToResumeRequest(ctx, req, task, session, startAgent)
|
||||
|
||||
return req, repositoryID, execConfig, existingRunning, nil
|
||||
|
||||
@@ -42,6 +42,10 @@ func (m *mockAgentManager) SetExecutionDescription(ctx context.Context, agentExe
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockAgentManager) SetMcpMode(_ context.Context, _ string, _ string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockAgentManager) StartAgentProcess(ctx context.Context, agentExecutionID string) error {
|
||||
if m.startAgentProcessFunc != nil {
|
||||
return m.startAgentProcessFunc(ctx, agentExecutionID)
|
||||
@@ -292,7 +296,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, includeEphemeral, onlyEphemeral bool) ([]*models.Task, int, error) {
|
||||
func (m *mockRepository) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig bool) ([]*models.Task, int, error) {
|
||||
return nil, 0, nil
|
||||
}
|
||||
func (m *mockRepository) ListTasksByWorkflowStep(ctx context.Context, workflowStepID string) ([]*models.Task, error) {
|
||||
|
||||
@@ -51,6 +51,10 @@ func (m *mockAgentManager) SetExecutionDescription(ctx context.Context, agentExe
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockAgentManager) SetMcpMode(_ context.Context, _ string, _ string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockAgentManager) StartAgentProcess(ctx context.Context, agentExecutionID string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -189,7 +189,7 @@ func (s *Service) StartTaskWithSession(ctx context.Context, taskID string, sessi
|
||||
effectivePrompt = task.Description
|
||||
}
|
||||
|
||||
effectivePrompt, planModeActive := s.applyWorkflowAndPlanMode(ctx, effectivePrompt, task.ID, workflowStepID, planMode)
|
||||
effectivePrompt, planModeActive := s.applyWorkflowAndPlanMode(ctx, effectivePrompt, task.ID, sessionID, workflowStepID, planMode)
|
||||
|
||||
execution, err := s.executor.LaunchPreparedSession(ctx, task, sessionID, executor.LaunchOptions{AgentProfileID: agentProfileID, ExecutorID: executorID, Prompt: effectivePrompt, WorkflowStepID: workflowStepID, StartAgent: true})
|
||||
if err != nil {
|
||||
@@ -282,7 +282,12 @@ func (s *Service) StartCreatedSession(ctx context.Context, taskID, sessionID, ag
|
||||
if session.WorkflowStepID != nil {
|
||||
stepID = *session.WorkflowStepID
|
||||
}
|
||||
effectivePrompt, planModeActive := s.applyWorkflowAndPlanMode(ctx, effectivePrompt, taskID, stepID, planMode)
|
||||
effectivePrompt, planModeActive := s.applyWorkflowAndPlanMode(ctx, effectivePrompt, taskID, sessionID, stepID, planMode)
|
||||
|
||||
// Inject config context for config-mode sessions (dedicated settings chat)
|
||||
if cm, ok := session.Metadata["config_mode"].(bool); ok && cm {
|
||||
effectivePrompt = sysprompt.InjectConfigContext(sessionID, effectivePrompt)
|
||||
}
|
||||
|
||||
executorID := session.ExecutorID
|
||||
|
||||
@@ -379,15 +384,34 @@ func (s *Service) StartTask(ctx context.Context, taskID string, agentProfileID s
|
||||
effectivePrompt = task.Description
|
||||
}
|
||||
|
||||
effectivePrompt, planModeActive := s.applyWorkflowAndPlanMode(ctx, effectivePrompt, task.ID, workflowStepID, planMode)
|
||||
// Prepare session first so we have the sessionID for config context injection
|
||||
sessionID, err := s.executor.PrepareSession(ctx, task, agentProfileID, executorID, executorProfileID, workflowStepID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
execution, err := s.executor.ExecuteWithFullProfile(ctx, task, agentProfileID, executorID, executorProfileID, effectivePrompt, workflowStepID)
|
||||
effectivePrompt, planModeActive := s.applyWorkflowAndPlanMode(ctx, effectivePrompt, task.ID, sessionID, workflowStepID, planMode)
|
||||
|
||||
// Inject config context for config-mode sessions (dedicated settings chat)
|
||||
configMode := false
|
||||
if cm, ok := task.Metadata["config_mode"].(bool); ok && cm {
|
||||
configMode = true
|
||||
effectivePrompt = sysprompt.InjectConfigContext(sessionID, effectivePrompt)
|
||||
}
|
||||
|
||||
execution, err := s.executor.LaunchPreparedSession(ctx, task, sessionID, executor.LaunchOptions{
|
||||
AgentProfileID: agentProfileID,
|
||||
ExecutorID: executorID,
|
||||
Prompt: effectivePrompt,
|
||||
WorkflowStepID: workflowStepID,
|
||||
StartAgent: true,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if execution.SessionID != "" {
|
||||
s.recordInitialMessage(ctx, taskID, execution.SessionID, effectivePrompt, planModeActive)
|
||||
s.recordInitialMessage(ctx, taskID, execution.SessionID, effectivePrompt, planModeActive || configMode)
|
||||
|
||||
// Set plan mode in session metadata so the frontend can detect it.
|
||||
// applyWorkflowAndPlanMode only injects plan mode into the prompt text;
|
||||
@@ -411,7 +435,7 @@ func (s *Service) StartTask(ctx context.Context, taskID string, agentProfileID s
|
||||
|
||||
// applyWorkflowAndPlanMode applies workflow step configuration and plan mode injection to a prompt.
|
||||
// Returns the effective prompt and whether plan mode is active (from either the step or the caller).
|
||||
func (s *Service) applyWorkflowAndPlanMode(ctx context.Context, prompt string, taskID string, workflowStepID string, planMode bool) (string, bool) {
|
||||
func (s *Service) applyWorkflowAndPlanMode(ctx context.Context, prompt string, taskID string, sessionID string, workflowStepID string, planMode bool) (string, bool) {
|
||||
effectivePrompt := prompt
|
||||
|
||||
stepHasPlanMode := false
|
||||
@@ -423,13 +447,12 @@ func (s *Service) applyWorkflowAndPlanMode(ctx context.Context, prompt string, t
|
||||
zap.Error(err))
|
||||
} else {
|
||||
stepHasPlanMode = step.HasOnEnterAction(wfmodels.OnEnterEnablePlanMode)
|
||||
effectivePrompt = s.buildWorkflowPrompt(effectivePrompt, step, taskID)
|
||||
effectivePrompt = s.buildWorkflowPrompt(effectivePrompt, step, taskID, sessionID)
|
||||
}
|
||||
}
|
||||
|
||||
if planMode && !stepHasPlanMode {
|
||||
var parts []string
|
||||
parts = append(parts, sysprompt.Wrap(sysprompt.PlanMode))
|
||||
parts = append(parts, sysprompt.Wrap(sysprompt.InterpolatePlaceholders(sysprompt.DefaultPlanPrefix, taskID)))
|
||||
parts = append(parts, effectivePrompt)
|
||||
effectivePrompt = strings.Join(parts, "\n\n")
|
||||
@@ -453,16 +476,10 @@ func (s *Service) recordInitialMessage(ctx context.Context, taskID, sessionID, p
|
||||
// buildWorkflowPrompt constructs the effective prompt using workflow step configuration.
|
||||
// If step.Prompt contains {{task_prompt}}, it is replaced with the base prompt.
|
||||
// Otherwise, step.Prompt is prepended to the base prompt.
|
||||
// If the step has enable_plan_mode in on_enter events, plan mode prefix is also prepended.
|
||||
// System-injected content is wrapped in <kandev-system> tags so it can be stripped when displaying to users.
|
||||
func (s *Service) buildWorkflowPrompt(basePrompt string, step *wfmodels.WorkflowStep, taskID string) string {
|
||||
func (s *Service) buildWorkflowPrompt(basePrompt string, step *wfmodels.WorkflowStep, taskID string, sessionID string) string {
|
||||
var parts []string
|
||||
|
||||
// Apply plan mode prefix if enabled (wrapped in system tags)
|
||||
if step.HasOnEnterAction(wfmodels.OnEnterEnablePlanMode) {
|
||||
parts = append(parts, sysprompt.Wrap(sysprompt.PlanMode))
|
||||
}
|
||||
|
||||
// Build the prompt from step.Prompt template and base prompt
|
||||
if step.Prompt != "" {
|
||||
interpolatedPrompt := sysprompt.InterpolatePlaceholders(step.Prompt, taskID)
|
||||
@@ -585,7 +602,7 @@ func (s *Service) StartSessionForWorkflowStep(ctx context.Context, taskID, sessi
|
||||
|
||||
s.advanceSessionWorkflowStep(ctx, sessionID, workflowStepID, session)
|
||||
|
||||
effectivePrompt := s.buildWorkflowPrompt(task.Description, step, taskID)
|
||||
effectivePrompt := s.buildWorkflowPrompt(task.Description, step, taskID, sessionID)
|
||||
|
||||
if err := s.ensureSessionRunning(ctx, sessionID, session); err != nil {
|
||||
return err
|
||||
@@ -1184,10 +1201,10 @@ func (s *Service) PromptTask(ctx context.Context, taskID, sessionID string, prom
|
||||
return nil, fmt.Errorf("failed to ensure session is running: %w", err)
|
||||
}
|
||||
|
||||
// Apply plan mode prefix if enabled
|
||||
// Inject config context for config-mode sessions (dedicated settings chat, not plan mode)
|
||||
effectivePrompt := prompt
|
||||
if planMode {
|
||||
effectivePrompt = sysprompt.InjectPlanMode(prompt)
|
||||
if cm, ok := session.Metadata["config_mode"].(bool); ok && cm {
|
||||
effectivePrompt = sysprompt.InjectConfigContext(sessionID, prompt)
|
||||
}
|
||||
|
||||
// Check if model switching is requested
|
||||
|
||||
@@ -85,6 +85,80 @@ func FormatKandevContext(taskID, sessionID string) string {
|
||||
return fmt.Sprintf(KandevContext, taskID, sessionID)
|
||||
}
|
||||
|
||||
// ConfigContext is the system prompt for config-mode MCP sessions.
|
||||
// It provides instructions for agents performing configuration operations
|
||||
// via the dedicated config chat on the settings page.
|
||||
const ConfigContext = `KANDEV CONFIG MCP TOOLS — You are a configuration assistant for the Kandev platform.
|
||||
You have access to the following MCP tools from the "kandev" server.
|
||||
Always use the exact tool names shown below (they include the _kandev suffix).
|
||||
|
||||
Session ID: %s
|
||||
|
||||
WORKFLOW TOOLS:
|
||||
- list_workspaces_kandev: List all workspaces to get workspace IDs.
|
||||
- list_workflows_kandev: List workflows in a workspace. Required: workspace_id.
|
||||
- create_workflow_kandev: Create a new workflow. Required: workspace_id, name. Optional: description.
|
||||
- update_workflow_kandev: Update a workflow. Required: workflow_id. Optional: name, description.
|
||||
- delete_workflow_kandev: Delete a workflow and all its steps (destructive). Required: workflow_id.
|
||||
- list_workflow_steps_kandev: List workflow steps (columns) in a workflow. Required: workflow_id.
|
||||
- create_workflow_step_kandev: Create a new workflow step. Required: workflow_id, name. Optional: position, color, prompt, is_start_step, allow_manual_move, show_in_command_panel, events.
|
||||
- update_workflow_step_kandev: Update a workflow step. Required: step_id. Optional: name, color, prompt, is_start_step, allow_manual_move, show_in_command_panel, auto_archive_after_hours, events.
|
||||
- delete_workflow_step_kandev: Delete a workflow step (destructive). Required: step_id.
|
||||
- reorder_workflow_steps_kandev: Reorder workflow steps. Required: workflow_id, step_ids (ordered array of step IDs).
|
||||
|
||||
AGENT TOOLS:
|
||||
- list_agents_kandev: List all configured agents and their profiles.
|
||||
- update_agent_kandev: Update agent settings. Required: agent_id. Optional: supports_mcp, mcp_config_path.
|
||||
- create_agent_profile_kandev: Create a new agent profile. Required: agent_id, name, model. Optional: auto_approve.
|
||||
- delete_agent_profile_kandev: Delete an agent profile. Required: profile_id.
|
||||
|
||||
EXECUTOR PROFILE TOOLS:
|
||||
Executors (local, worktree, local_docker, sprites) are pre-defined. Use list_executors to find executor IDs, then manage profiles.
|
||||
- list_executors_kandev: List all executors with their IDs and types.
|
||||
- list_executor_profiles_kandev: List profiles for an executor. Required: executor_id.
|
||||
- create_executor_profile_kandev: Create an executor profile. Required: executor_id, name. Optional: mcp_policy, config, prepare_script, cleanup_script.
|
||||
- update_executor_profile_kandev: Update an executor profile. Required: profile_id. Optional: name, mcp_policy, config, prepare_script, cleanup_script.
|
||||
- delete_executor_profile_kandev: Delete an executor profile. Required: profile_id.
|
||||
|
||||
MCP CONFIG TOOLS:
|
||||
- list_agent_profiles_kandev: List profiles for an agent. Required: agent_id.
|
||||
- update_agent_profile_kandev: Update a profile. Required: profile_id. Optional: name, model, auto_approve.
|
||||
- get_mcp_config_kandev: Get MCP server config for a profile. Required: profile_id.
|
||||
- update_mcp_config_kandev: Update MCP config for a profile. Required: profile_id. Optional: enabled, servers.
|
||||
|
||||
TASK TOOLS:
|
||||
- list_tasks_kandev: List all tasks in a workflow. Required: workflow_id.
|
||||
- move_task_kandev: Move a task to a different workflow step. Required: task_id, workflow_step_id.
|
||||
- delete_task_kandev: Delete a task. Required: task_id.
|
||||
- archive_task_kandev: Archive a task. Required: task_id.
|
||||
- update_task_state_kandev: Update task state. Required: task_id, state (TODO, CREATED, SCHEDULING, IN_PROGRESS, REVIEW, BLOCKED, WAITING_FOR_INPUT, COMPLETED, FAILED, CANCELLED).
|
||||
|
||||
INTERACTION:
|
||||
- ask_user_question_kandev: Ask the user a clarifying question with multiple-choice options. Required: prompt, options.
|
||||
|
||||
EXAMPLE REQUESTS the user might ask:
|
||||
- "Create a new workflow called 'Feature Development'"
|
||||
- "Add a 'Code Review' step to my workflow"
|
||||
- "Create a new agent profile for Claude with auto-approve enabled"
|
||||
- "Show me the current workflow steps"
|
||||
- "Update the MCP servers for the default agent profile"
|
||||
- "Create a new executor profile for Docker with a prepare script"
|
||||
- "Move all completed tasks to the 'Done' column"
|
||||
- "Archive old tasks from last month"
|
||||
|
||||
IMPORTANT: Always list existing resources before creating or modifying. Confirm destructive operations (delete, archive) with the user first using ask_user_question_kandev.`
|
||||
|
||||
// FormatConfigContext returns the config context prompt with the session ID injected.
|
||||
func FormatConfigContext(sessionID string) string {
|
||||
return fmt.Sprintf(ConfigContext, sessionID)
|
||||
}
|
||||
|
||||
// InjectConfigContext prepends the config system prompt to a user's prompt.
|
||||
// The system content is wrapped in <kandev-system> tags.
|
||||
func InjectConfigContext(sessionID, prompt string) string {
|
||||
return Wrap(FormatConfigContext(sessionID)) + "\n\n" + prompt
|
||||
}
|
||||
|
||||
// InjectKandevContext prepends the Kandev system prompt and session context to a user's prompt.
|
||||
// The system content is wrapped in <kandev-system> tags.
|
||||
func InjectKandevContext(taskID, sessionID, prompt string) string {
|
||||
|
||||
@@ -0,0 +1,206 @@
|
||||
package sysprompt
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
// Test constants to avoid repeated string literals.
|
||||
const (
|
||||
testConfigPrompt = "Configure my workflow"
|
||||
testPlanPrompt = "Plan this task"
|
||||
testTaskID = "task-123"
|
||||
testSessionID = "session-123"
|
||||
)
|
||||
|
||||
// --- ConfigContext tests ---
|
||||
|
||||
func TestConfigContext_ContainsAllTools(t *testing.T) {
|
||||
expectedTools := []string{
|
||||
"list_workspaces_kandev",
|
||||
"list_workflows_kandev",
|
||||
"create_workflow_kandev",
|
||||
"update_workflow_kandev",
|
||||
"delete_workflow_kandev",
|
||||
"list_workflow_steps_kandev",
|
||||
"create_workflow_step_kandev",
|
||||
"update_workflow_step_kandev",
|
||||
"delete_workflow_step_kandev",
|
||||
"reorder_workflow_steps_kandev",
|
||||
"list_agents_kandev",
|
||||
"update_agent_kandev",
|
||||
"create_agent_profile_kandev",
|
||||
"delete_agent_profile_kandev",
|
||||
"list_executors_kandev",
|
||||
"list_executor_profiles_kandev",
|
||||
"create_executor_profile_kandev",
|
||||
"update_executor_profile_kandev",
|
||||
"delete_executor_profile_kandev",
|
||||
"list_agent_profiles_kandev",
|
||||
"update_agent_profile_kandev",
|
||||
"get_mcp_config_kandev",
|
||||
"update_mcp_config_kandev",
|
||||
"list_tasks_kandev",
|
||||
"move_task_kandev",
|
||||
"delete_task_kandev",
|
||||
"archive_task_kandev",
|
||||
"update_task_state_kandev",
|
||||
"ask_user_question_kandev",
|
||||
}
|
||||
|
||||
for _, tool := range expectedTools {
|
||||
assert.Contains(t, ConfigContext, tool, "ConfigContext should contain tool: %s", tool)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigContext_ContainsSections(t *testing.T) {
|
||||
assert.Contains(t, ConfigContext, "WORKFLOW TOOLS:")
|
||||
assert.Contains(t, ConfigContext, "AGENT TOOLS:")
|
||||
assert.Contains(t, ConfigContext, "EXECUTOR PROFILE TOOLS:")
|
||||
assert.Contains(t, ConfigContext, "MCP CONFIG TOOLS:")
|
||||
assert.Contains(t, ConfigContext, "TASK TOOLS:")
|
||||
assert.Contains(t, ConfigContext, "INTERACTION:")
|
||||
assert.Contains(t, ConfigContext, "EXAMPLE REQUESTS")
|
||||
}
|
||||
|
||||
func TestConfigContext_HasExactlyOneSessionIDPlaceholder(t *testing.T) {
|
||||
count := strings.Count(ConfigContext, "%s")
|
||||
assert.Equal(t, 1, count, "ConfigContext should have exactly 1 %%s placeholder")
|
||||
}
|
||||
|
||||
func TestFormatConfigContext_InjectsSessionID(t *testing.T) {
|
||||
result := FormatConfigContext("session-abc-123")
|
||||
assert.Contains(t, result, "Session ID: session-abc-123")
|
||||
assert.NotContains(t, result, "%s")
|
||||
assert.NotContains(t, result, "%!")
|
||||
}
|
||||
|
||||
func TestInjectConfigContext_WrapsInSystemTags(t *testing.T) {
|
||||
result := InjectConfigContext(testSessionID, testConfigPrompt)
|
||||
assert.True(t, strings.HasPrefix(result, TagStart))
|
||||
assert.Contains(t, result, TagEnd)
|
||||
assert.Contains(t, result, testConfigPrompt)
|
||||
assert.Contains(t, result, testSessionID)
|
||||
}
|
||||
|
||||
func TestInjectConfigContext_SystemContentStrippable(t *testing.T) {
|
||||
result := InjectConfigContext(testSessionID, testConfigPrompt)
|
||||
stripped := StripSystemContent(result)
|
||||
assert.Equal(t, testConfigPrompt, stripped)
|
||||
assert.NotContains(t, stripped, "KANDEV CONFIG MCP TOOLS")
|
||||
}
|
||||
|
||||
// --- KandevContext tests (existing, verify not broken) ---
|
||||
|
||||
func TestKandevContext_HasExactlyTwoPlaceholders(t *testing.T) {
|
||||
count := strings.Count(KandevContext, "%s")
|
||||
assert.Equal(t, 2, count, "KandevContext should have exactly 2 %%s placeholders")
|
||||
}
|
||||
|
||||
func TestFormatKandevContext_InjectsIDs(t *testing.T) {
|
||||
result := FormatKandevContext("task-abc", "session-xyz")
|
||||
assert.Contains(t, result, "Kandev Task ID: task-abc")
|
||||
assert.Contains(t, result, "Session ID: session-xyz")
|
||||
assert.NotContains(t, result, "%!")
|
||||
}
|
||||
|
||||
func TestInjectKandevContext_WrapsInSystemTags(t *testing.T) {
|
||||
result := InjectKandevContext("task-abc", "session-xyz", "Do something")
|
||||
assert.True(t, strings.HasPrefix(result, TagStart))
|
||||
assert.Contains(t, result, "Do something")
|
||||
}
|
||||
|
||||
func TestInjectKandevContext_SystemContentStrippable(t *testing.T) {
|
||||
result := InjectKandevContext("task-abc", "session-xyz", "Do something")
|
||||
stripped := StripSystemContent(result)
|
||||
assert.Equal(t, "Do something", stripped)
|
||||
}
|
||||
|
||||
// --- StripSystemContent tests ---
|
||||
|
||||
func TestStripSystemContent_NoTags(t *testing.T) {
|
||||
assert.Equal(t, "Hello world", StripSystemContent("Hello world"))
|
||||
}
|
||||
|
||||
func TestStripSystemContent_OnlyTags(t *testing.T) {
|
||||
input := Wrap("system content only")
|
||||
assert.Equal(t, "", StripSystemContent(input))
|
||||
}
|
||||
|
||||
func TestStripSystemContent_MixedContent(t *testing.T) {
|
||||
input := Wrap("hidden") + "\n\nvisible text"
|
||||
result := StripSystemContent(input)
|
||||
assert.Equal(t, "visible text", result)
|
||||
}
|
||||
|
||||
func TestStripSystemContent_MultipleTags(t *testing.T) {
|
||||
input := Wrap("first") + " middle " + Wrap("second") + " end"
|
||||
result := StripSystemContent(input)
|
||||
// The regex replaces tags + trailing whitespace, so check both parts are present
|
||||
assert.Contains(t, result, "middle")
|
||||
assert.Contains(t, result, "end")
|
||||
assert.NotContains(t, result, "first")
|
||||
assert.NotContains(t, result, "second")
|
||||
}
|
||||
|
||||
// --- Wrap and HasSystemContent tests ---
|
||||
|
||||
func TestWrap(t *testing.T) {
|
||||
result := Wrap("test content")
|
||||
assert.Equal(t, TagStart+"test content"+TagEnd, result)
|
||||
}
|
||||
|
||||
func TestHasSystemContent(t *testing.T) {
|
||||
assert.True(t, HasSystemContent(Wrap("content")))
|
||||
assert.False(t, HasSystemContent("no tags"))
|
||||
}
|
||||
|
||||
// --- PlanMode tests ---
|
||||
|
||||
func TestInjectPlanMode_WrapsInTags(t *testing.T) {
|
||||
result := InjectPlanMode(testPlanPrompt)
|
||||
assert.True(t, strings.HasPrefix(result, TagStart))
|
||||
assert.Contains(t, result, "PLAN MODE ACTIVE")
|
||||
assert.Contains(t, result, testPlanPrompt)
|
||||
}
|
||||
|
||||
func TestInjectPlanMode_SystemContentStrippable(t *testing.T) {
|
||||
result := InjectPlanMode(testPlanPrompt)
|
||||
stripped := StripSystemContent(result)
|
||||
assert.Equal(t, testPlanPrompt, stripped)
|
||||
}
|
||||
|
||||
// --- InterpolatePlaceholders tests ---
|
||||
|
||||
func TestInterpolatePlaceholders_TaskID(t *testing.T) {
|
||||
result := InterpolatePlaceholders("Check {task_id} status", testTaskID)
|
||||
assert.Equal(t, "Check task-123 status", result)
|
||||
}
|
||||
|
||||
func TestInterpolatePlaceholders_NoPlaceholders(t *testing.T) {
|
||||
result := InterpolatePlaceholders("No placeholders here", testTaskID)
|
||||
assert.Equal(t, "No placeholders here", result)
|
||||
}
|
||||
|
||||
func TestInterpolatePlaceholders_MultiplePlaceholders(t *testing.T) {
|
||||
result := InterpolatePlaceholders("{task_id} and {task_id}", testTaskID)
|
||||
assert.Equal(t, "task-123 and task-123", result)
|
||||
}
|
||||
|
||||
// --- ConfigContext vs KandevContext distinction ---
|
||||
|
||||
func TestConfigContext_DoesNotContainPlanTools(t *testing.T) {
|
||||
assert.NotContains(t, ConfigContext, "create_task_plan_kandev")
|
||||
assert.NotContains(t, ConfigContext, "get_task_plan_kandev")
|
||||
assert.NotContains(t, ConfigContext, "update_task_plan_kandev")
|
||||
assert.NotContains(t, ConfigContext, "delete_task_plan_kandev")
|
||||
}
|
||||
|
||||
func TestKandevContext_DoesNotContainConfigTools(t *testing.T) {
|
||||
assert.NotContains(t, KandevContext, "create_workflow_step_kandev")
|
||||
assert.NotContains(t, KandevContext, "update_workflow_step_kandev")
|
||||
assert.NotContains(t, KandevContext, "list_agents_kandev")
|
||||
assert.NotContains(t, KandevContext, "create_agent_kandev")
|
||||
}
|
||||
@@ -18,15 +18,16 @@ type WorkflowDTO struct {
|
||||
}
|
||||
|
||||
type WorkspaceDTO struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
type RepositoryDTO struct {
|
||||
@@ -341,15 +342,16 @@ func FromWorkspace(workspace *models.Workspace) WorkspaceDTO {
|
||||
}
|
||||
|
||||
return WorkspaceDTO{
|
||||
ID: workspace.ID,
|
||||
Name: workspace.Name,
|
||||
Description: description,
|
||||
OwnerID: workspace.OwnerID,
|
||||
DefaultExecutorID: workspace.DefaultExecutorID,
|
||||
DefaultEnvironmentID: workspace.DefaultEnvironmentID,
|
||||
DefaultAgentProfileID: workspace.DefaultAgentProfileID,
|
||||
CreatedAt: workspace.CreatedAt,
|
||||
UpdatedAt: workspace.UpdatedAt,
|
||||
ID: workspace.ID,
|
||||
Name: workspace.Name,
|
||||
Description: description,
|
||||
OwnerID: workspace.OwnerID,
|
||||
DefaultExecutorID: workspace.DefaultExecutorID,
|
||||
DefaultEnvironmentID: workspace.DefaultEnvironmentID,
|
||||
DefaultAgentProfileID: workspace.DefaultAgentProfileID,
|
||||
DefaultConfigAgentProfileID: workspace.DefaultConfigAgentProfileID,
|
||||
CreatedAt: workspace.CreatedAt,
|
||||
UpdatedAt: workspace.UpdatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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, includeEphemeral, onlyEphemeral bool) ([]*models.Task, int, error) {
|
||||
func (m *mockRepository) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig bool) ([]*models.Task, int, error) {
|
||||
return nil, 0, nil
|
||||
}
|
||||
func (m *mockRepository) ListTasksByWorkflowStep(ctx context.Context, workflowStepID string) ([]*models.Task, error) {
|
||||
|
||||
@@ -74,6 +74,9 @@ func (h *TaskHandlers) registerHTTP(router *gin.Engine) {
|
||||
|
||||
// Quick chat endpoint - creates ephemeral task with prepared session
|
||||
api.POST("/workspaces/:id/quick-chat", h.httpStartQuickChat)
|
||||
|
||||
// Config chat endpoint - creates ephemeral task with config-mode MCP tools
|
||||
api.POST("/workspaces/:id/config-chat", h.httpStartConfigChat)
|
||||
}
|
||||
|
||||
func (h *TaskHandlers) registerWS(dispatcher *ws.Dispatcher) {
|
||||
|
||||
@@ -52,9 +52,10 @@ func (h *TaskHandlers) httpListTasksByWorkspace(c *gin.Context) {
|
||||
includeArchived := c.Query("include_archived") == queryValueTrue
|
||||
includeEphemeral := c.Query("include_ephemeral") == queryValueTrue
|
||||
onlyEphemeral := c.Query("only_ephemeral") == queryValueTrue
|
||||
excludeConfig := c.Query("exclude_config") == queryValueTrue
|
||||
|
||||
tasks, total, err := h.service.ListTasksByWorkspace(
|
||||
c.Request.Context(), c.Param("id"), query, page, pageSize, includeArchived, includeEphemeral, onlyEphemeral,
|
||||
c.Request.Context(), c.Param("id"), query, page, pageSize, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig,
|
||||
)
|
||||
if err != nil {
|
||||
handleNotFound(c, h.logger, err, "tasks not found")
|
||||
@@ -761,3 +762,150 @@ func (h *TaskHandlers) httpStartQuickChat(c *gin.Context) {
|
||||
SessionID: resp.SessionID,
|
||||
})
|
||||
}
|
||||
|
||||
// httpStartConfigChatRequest is the request body for starting a config chat session.
|
||||
type httpStartConfigChatRequest struct {
|
||||
AgentProfileID string `json:"agent_profile_id,omitempty"`
|
||||
ExecutorID string `json:"executor_id,omitempty"`
|
||||
Prompt string `json:"prompt,omitempty"`
|
||||
}
|
||||
|
||||
// httpStartConfigChat creates an ephemeral task with config_mode and prepares a session.
|
||||
// The session will have config MCP tools (workflow, agent, MCP management) instead of
|
||||
// the normal kanban/plan tools used for task-solving agents.
|
||||
// resolveConfigChatDefaults resolves the agent profile ID, executor ID, and task
|
||||
// metadata for a config chat session. Profile priority: request → workspace config → workspace default.
|
||||
func resolveConfigChatDefaults(body httpStartConfigChatRequest, ws *models.Workspace) (agentProfileID, executorID string, metadata map[string]interface{}) {
|
||||
agentProfileID = body.AgentProfileID
|
||||
if agentProfileID == "" && ws.DefaultConfigAgentProfileID != nil {
|
||||
agentProfileID = *ws.DefaultConfigAgentProfileID
|
||||
}
|
||||
if agentProfileID == "" && ws.DefaultAgentProfileID != nil {
|
||||
agentProfileID = *ws.DefaultAgentProfileID
|
||||
}
|
||||
executorID = body.ExecutorID
|
||||
if executorID == "" && ws.DefaultExecutorID != nil {
|
||||
executorID = *ws.DefaultExecutorID
|
||||
}
|
||||
metadata = map[string]interface{}{
|
||||
"config_mode": true,
|
||||
"agent_profile_id": agentProfileID,
|
||||
}
|
||||
if executorID != "" {
|
||||
metadata["executor_id"] = executorID
|
||||
}
|
||||
return agentProfileID, executorID, metadata
|
||||
}
|
||||
|
||||
func (h *TaskHandlers) httpStartConfigChat(c *gin.Context) {
|
||||
workspaceID := c.Param("id")
|
||||
var body httpStartConfigChatRequest
|
||||
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
|
||||
}
|
||||
|
||||
agentProfileID, executorID, metadata := resolveConfigChatDefaults(body, workspace)
|
||||
if agentProfileID == "" {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "no agent profile configured — set a default agent profile in workspace settings"})
|
||||
return
|
||||
}
|
||||
|
||||
task, err := h.service.CreateTask(ctx, &service.CreateTaskRequest{
|
||||
WorkspaceID: workspaceID,
|
||||
WorkflowID: workflows[0].ID,
|
||||
Title: "Config Chat",
|
||||
Description: body.Prompt,
|
||||
IsEphemeral: true,
|
||||
Metadata: metadata,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("failed to create config chat task", zap.Error(err))
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to create config chat"})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.orchestrator.LaunchSession(ctx, &orchestrator.LaunchSessionRequest{
|
||||
TaskID: task.ID,
|
||||
Intent: orchestrator.IntentPrepare,
|
||||
AgentProfileID: agentProfileID,
|
||||
ExecutorID: executorID,
|
||||
})
|
||||
if err != nil {
|
||||
h.deleteTaskOnError(task.ID, "config chat", err)
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to prepare session"})
|
||||
return
|
||||
}
|
||||
|
||||
sessionID := resp.SessionID
|
||||
|
||||
// If a prompt was provided, launch the agent asynchronously so it starts
|
||||
// processing immediately. The frontend receives WS updates when it starts.
|
||||
if body.Prompt != "" {
|
||||
go h.launchConfigChatAgent(task.ID, sessionID, agentProfileID, body.Prompt)
|
||||
}
|
||||
|
||||
h.logger.Info("config chat session created",
|
||||
zap.String("task_id", task.ID),
|
||||
zap.String("session_id", sessionID),
|
||||
zap.String("workspace_id", workspaceID))
|
||||
|
||||
c.JSON(http.StatusOK, httpStartQuickChatResponse{
|
||||
TaskID: task.ID,
|
||||
SessionID: sessionID,
|
||||
})
|
||||
}
|
||||
|
||||
func (h *TaskHandlers) deleteTaskOnError(taskID, label string, err error) {
|
||||
if deleteErr := h.service.DeleteTask(context.Background(), taskID); deleteErr != nil {
|
||||
h.logger.Error("failed to rollback "+label+" task",
|
||||
zap.String("task_id", taskID), zap.Error(deleteErr))
|
||||
}
|
||||
h.logger.Error("failed to prepare "+label+" session",
|
||||
zap.Error(err), zap.String("task_id", taskID))
|
||||
}
|
||||
|
||||
func (h *TaskHandlers) launchConfigChatAgent(
|
||||
taskID, sessionID, agentProfileID, prompt string,
|
||||
) {
|
||||
startCtx, cancel := context.WithTimeout(
|
||||
context.Background(), constants.AgentLaunchTimeout,
|
||||
)
|
||||
defer cancel()
|
||||
launchResp, err := h.orchestrator.LaunchSession(startCtx, &orchestrator.LaunchSessionRequest{
|
||||
TaskID: taskID,
|
||||
Intent: orchestrator.IntentStartCreated,
|
||||
SessionID: sessionID,
|
||||
AgentProfileID: agentProfileID,
|
||||
Prompt: prompt,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("failed to start config chat agent",
|
||||
zap.Error(err), zap.String("task_id", taskID),
|
||||
zap.String("session_id", sessionID))
|
||||
return
|
||||
}
|
||||
h.logger.Info("config chat agent started",
|
||||
zap.String("task_id", taskID),
|
||||
zap.String("session_id", launchResp.SessionID),
|
||||
zap.String("execution_id", launchResp.AgentExecutionID))
|
||||
}
|
||||
|
||||
@@ -73,12 +73,13 @@ func (h *WorkspaceHandlers) httpListWorkspaces(c *gin.Context) {
|
||||
}
|
||||
|
||||
type httpCreateWorkspaceRequest struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
OwnerID string `json:"owner_id,omitempty"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
OwnerID string `json:"owner_id,omitempty"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"`
|
||||
}
|
||||
|
||||
func (h *WorkspaceHandlers) httpCreateWorkspace(c *gin.Context) {
|
||||
@@ -92,12 +93,13 @@ func (h *WorkspaceHandlers) httpCreateWorkspace(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
workspace, err := h.service.CreateWorkspace(c.Request.Context(), &service.CreateWorkspaceRequest{
|
||||
Name: body.Name,
|
||||
Description: body.Description,
|
||||
OwnerID: body.OwnerID,
|
||||
DefaultExecutorID: body.DefaultExecutorID,
|
||||
DefaultEnvironmentID: body.DefaultEnvironmentID,
|
||||
DefaultAgentProfileID: body.DefaultAgentProfileID,
|
||||
Name: body.Name,
|
||||
Description: body.Description,
|
||||
OwnerID: body.OwnerID,
|
||||
DefaultExecutorID: body.DefaultExecutorID,
|
||||
DefaultEnvironmentID: body.DefaultEnvironmentID,
|
||||
DefaultAgentProfileID: body.DefaultAgentProfileID,
|
||||
DefaultConfigAgentProfileID: body.DefaultConfigAgentProfileID,
|
||||
})
|
||||
if err != nil {
|
||||
handleNotFound(c, h.logger, err, "workspace not created")
|
||||
@@ -116,11 +118,12 @@ func (h *WorkspaceHandlers) httpGetWorkspace(c *gin.Context) {
|
||||
}
|
||||
|
||||
type httpUpdateWorkspaceRequest struct {
|
||||
Name *string `json:"name,omitempty"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"`
|
||||
}
|
||||
|
||||
func (h *WorkspaceHandlers) httpUpdateWorkspace(c *gin.Context) {
|
||||
@@ -130,11 +133,12 @@ func (h *WorkspaceHandlers) httpUpdateWorkspace(c *gin.Context) {
|
||||
return
|
||||
}
|
||||
workspace, err := h.service.UpdateWorkspace(c.Request.Context(), c.Param("id"), &service.UpdateWorkspaceRequest{
|
||||
Name: body.Name,
|
||||
Description: body.Description,
|
||||
DefaultExecutorID: body.DefaultExecutorID,
|
||||
DefaultEnvironmentID: body.DefaultEnvironmentID,
|
||||
DefaultAgentProfileID: body.DefaultAgentProfileID,
|
||||
Name: body.Name,
|
||||
Description: body.Description,
|
||||
DefaultExecutorID: body.DefaultExecutorID,
|
||||
DefaultEnvironmentID: body.DefaultEnvironmentID,
|
||||
DefaultAgentProfileID: body.DefaultAgentProfileID,
|
||||
DefaultConfigAgentProfileID: body.DefaultConfigAgentProfileID,
|
||||
})
|
||||
if err != nil {
|
||||
handleNotFound(c, h.logger, err, "workspace not updated")
|
||||
@@ -163,12 +167,13 @@ func (h *WorkspaceHandlers) wsListWorkspaces(ctx context.Context, msg *ws.Messag
|
||||
}
|
||||
|
||||
type wsCreateWorkspaceRequest struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
OwnerID string `json:"owner_id,omitempty"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description,omitempty"`
|
||||
OwnerID string `json:"owner_id,omitempty"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"`
|
||||
}
|
||||
|
||||
func (h *WorkspaceHandlers) wsCreateWorkspace(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
@@ -180,12 +185,13 @@ func (h *WorkspaceHandlers) wsCreateWorkspace(ctx context.Context, msg *ws.Messa
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "name is required", nil)
|
||||
}
|
||||
workspace, err := h.service.CreateWorkspace(ctx, &service.CreateWorkspaceRequest{
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
OwnerID: req.OwnerID,
|
||||
DefaultExecutorID: req.DefaultExecutorID,
|
||||
DefaultEnvironmentID: req.DefaultEnvironmentID,
|
||||
DefaultAgentProfileID: req.DefaultAgentProfileID,
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
OwnerID: req.OwnerID,
|
||||
DefaultExecutorID: req.DefaultExecutorID,
|
||||
DefaultEnvironmentID: req.DefaultEnvironmentID,
|
||||
DefaultAgentProfileID: req.DefaultAgentProfileID,
|
||||
DefaultConfigAgentProfileID: req.DefaultConfigAgentProfileID,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("failed to create workspace", zap.Error(err))
|
||||
@@ -215,12 +221,13 @@ func (h *WorkspaceHandlers) wsGetWorkspace(ctx context.Context, msg *ws.Message)
|
||||
}
|
||||
|
||||
type wsUpdateWorkspaceRequest struct {
|
||||
ID string `json:"id"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
ID string `json:"id"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"`
|
||||
}
|
||||
|
||||
func (h *WorkspaceHandlers) wsUpdateWorkspace(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
@@ -233,11 +240,12 @@ func (h *WorkspaceHandlers) wsUpdateWorkspace(ctx context.Context, msg *ws.Messa
|
||||
}
|
||||
|
||||
workspace, err := h.service.UpdateWorkspace(ctx, req.ID, &service.UpdateWorkspaceRequest{
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
DefaultExecutorID: req.DefaultExecutorID,
|
||||
DefaultEnvironmentID: req.DefaultEnvironmentID,
|
||||
DefaultAgentProfileID: req.DefaultAgentProfileID,
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
DefaultExecutorID: req.DefaultExecutorID,
|
||||
DefaultEnvironmentID: req.DefaultEnvironmentID,
|
||||
DefaultAgentProfileID: req.DefaultAgentProfileID,
|
||||
DefaultConfigAgentProfileID: req.DefaultConfigAgentProfileID,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("failed to update workspace", zap.Error(err))
|
||||
|
||||
@@ -52,15 +52,16 @@ type Workflow struct {
|
||||
|
||||
// Workspace represents a workspace
|
||||
type Workspace struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// TaskRepository represents a repository associated with a task
|
||||
|
||||
@@ -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, false, false)
|
||||
tasks, total, err := repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 10, false, 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, false, false)
|
||||
tasks, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 10, true, false, 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, false, false)
|
||||
_, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "Task", 1, 10, false, 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, false, false)
|
||||
_, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "Task", 1, 10, true, false, 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, includeEphemeral, onlyEphemeral bool) ([]*models.Task, int, error)
|
||||
ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig 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)
|
||||
|
||||
@@ -136,6 +136,8 @@ func (r *Repository) runMigrations() error {
|
||||
_, _ = 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)
|
||||
_, _ = r.db.Exec(`ALTER TABLE task_sessions ADD COLUMN base_commit_sha TEXT DEFAULT ''`)
|
||||
// Add default_config_agent_profile_id column to workspaces (ignore error if already exists)
|
||||
_, _ = r.db.Exec(`ALTER TABLE workspaces ADD COLUMN default_config_agent_profile_id TEXT DEFAULT ''`)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -159,6 +161,7 @@ func (r *Repository) initInfraSchema() error {
|
||||
default_executor_id TEXT DEFAULT '',
|
||||
default_environment_id TEXT DEFAULT '',
|
||||
default_agent_profile_id TEXT DEFAULT '',
|
||||
default_config_agent_profile_id TEXT DEFAULT '',
|
||||
created_at TIMESTAMP NOT NULL,
|
||||
updated_at TIMESTAMP NOT NULL
|
||||
);
|
||||
|
||||
@@ -179,7 +179,7 @@ func (r *Repository) ListTasksByWorkflowStep(ctx context.Context, workflowStepID
|
||||
// If includeArchived is false, archived tasks are excluded
|
||||
// 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) {
|
||||
func (r *Repository) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig bool) ([]*models.Task, int, error) {
|
||||
ctx, span := tracing.Tracer("kandev-db").Start(ctx, "db.ListTasksByWorkspace")
|
||||
defer span.End()
|
||||
// Calculate offset
|
||||
@@ -203,6 +203,10 @@ func (r *Repository) ListTasksByWorkspace(ctx context.Context, workspaceID strin
|
||||
filter += " AND archived_at IS NULL"
|
||||
}
|
||||
|
||||
if excludeConfig {
|
||||
filter += " AND (metadata IS NULL OR json_extract(metadata, '$.config_mode') IS NOT 1)"
|
||||
}
|
||||
|
||||
var rows *sql.Rows
|
||||
var total int
|
||||
var err error
|
||||
@@ -210,7 +214,7 @@ func (r *Repository) ListTasksByWorkspace(ctx context.Context, workspaceID strin
|
||||
if query == "" {
|
||||
rows, total, err = r.queryAllTasks(ctx, workspaceID, filter, pageSize, offset)
|
||||
} else {
|
||||
rows, total, err = r.searchTasks(ctx, workspaceID, query, filter, pageSize, offset, includeArchived, includeEphemeral, onlyEphemeral)
|
||||
rows, total, err = r.searchTasks(ctx, workspaceID, query, filter, pageSize, offset, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
@@ -244,7 +248,7 @@ 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, filter string, pageSize, offset int, includeArchived, includeEphemeral, onlyEphemeral bool) (*sql.Rows, int, error) {
|
||||
func (r *Repository) searchTasks(ctx context.Context, workspaceID, query, filter string, pageSize, offset int, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig bool) (*sql.Rows, int, error) {
|
||||
searchPattern := "%" + query + "%"
|
||||
like := dialect.Like(r.ro.DriverName())
|
||||
|
||||
@@ -258,6 +262,9 @@ func (r *Repository) searchTasks(ctx context.Context, workspaceID, query, filter
|
||||
if !includeArchived {
|
||||
tFilter += " AND t.archived_at IS NULL"
|
||||
}
|
||||
if excludeConfig {
|
||||
tFilter += " AND (t.metadata IS NULL OR json_extract(t.metadata, '$.config_mode') IS NOT 1)"
|
||||
}
|
||||
|
||||
countQuery := fmt.Sprintf(`
|
||||
SELECT COUNT(DISTINCT t.id) FROM tasks t
|
||||
|
||||
@@ -29,11 +29,12 @@ func (r *Repository) CreateWorkspace(ctx context.Context, workspace *models.Work
|
||||
default_executor_id,
|
||||
default_environment_id,
|
||||
default_agent_profile_id,
|
||||
default_config_agent_profile_id,
|
||||
created_at,
|
||||
updated_at
|
||||
)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`), workspace.ID, workspace.Name, workspace.Description, workspace.OwnerID, workspace.DefaultExecutorID, workspace.DefaultEnvironmentID, workspace.DefaultAgentProfileID, workspace.CreatedAt, workspace.UpdatedAt)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`), workspace.ID, workspace.Name, workspace.Description, workspace.OwnerID, workspace.DefaultExecutorID, workspace.DefaultEnvironmentID, workspace.DefaultAgentProfileID, workspace.DefaultConfigAgentProfileID, workspace.CreatedAt, workspace.UpdatedAt)
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -44,9 +45,10 @@ func (r *Repository) GetWorkspace(ctx context.Context, id string) (*models.Works
|
||||
var defaultExecutorID sql.NullString
|
||||
var defaultEnvironmentID sql.NullString
|
||||
var defaultAgentProfileID sql.NullString
|
||||
var defaultConfigAgentProfileID sql.NullString
|
||||
|
||||
err := r.ro.QueryRowContext(ctx, r.ro.Rebind(`
|
||||
SELECT id, name, description, owner_id, default_executor_id, default_environment_id, default_agent_profile_id, created_at, updated_at
|
||||
SELECT id, name, description, owner_id, default_executor_id, default_environment_id, default_agent_profile_id, default_config_agent_profile_id, created_at, updated_at
|
||||
FROM workspaces WHERE id = ?
|
||||
`), id).Scan(
|
||||
&workspace.ID,
|
||||
@@ -56,6 +58,7 @@ func (r *Repository) GetWorkspace(ctx context.Context, id string) (*models.Works
|
||||
&defaultExecutorID,
|
||||
&defaultEnvironmentID,
|
||||
&defaultAgentProfileID,
|
||||
&defaultConfigAgentProfileID,
|
||||
&workspace.CreatedAt,
|
||||
&workspace.UpdatedAt,
|
||||
)
|
||||
@@ -68,6 +71,9 @@ func (r *Repository) GetWorkspace(ctx context.Context, id string) (*models.Works
|
||||
if defaultAgentProfileID.Valid && defaultAgentProfileID.String != "" {
|
||||
workspace.DefaultAgentProfileID = &defaultAgentProfileID.String
|
||||
}
|
||||
if defaultConfigAgentProfileID.Valid && defaultConfigAgentProfileID.String != "" {
|
||||
workspace.DefaultConfigAgentProfileID = &defaultConfigAgentProfileID.String
|
||||
}
|
||||
|
||||
if err == sql.ErrNoRows {
|
||||
return nil, fmt.Errorf("workspace not found: %s", id)
|
||||
@@ -86,9 +92,10 @@ func (r *Repository) UpdateWorkspace(ctx context.Context, workspace *models.Work
|
||||
default_executor_id = ?,
|
||||
default_environment_id = ?,
|
||||
default_agent_profile_id = ?,
|
||||
default_config_agent_profile_id = ?,
|
||||
updated_at = ?
|
||||
WHERE id = ?
|
||||
`), workspace.Name, workspace.Description, workspace.DefaultExecutorID, workspace.DefaultEnvironmentID, workspace.DefaultAgentProfileID, workspace.UpdatedAt, workspace.ID)
|
||||
`), workspace.Name, workspace.Description, workspace.DefaultExecutorID, workspace.DefaultEnvironmentID, workspace.DefaultAgentProfileID, workspace.DefaultConfigAgentProfileID, workspace.UpdatedAt, workspace.ID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -117,7 +124,7 @@ func (r *Repository) DeleteWorkspace(ctx context.Context, id string) error {
|
||||
// ListWorkspaces returns all workspaces
|
||||
func (r *Repository) ListWorkspaces(ctx context.Context) ([]*models.Workspace, error) {
|
||||
rows, err := r.ro.QueryContext(ctx, `
|
||||
SELECT id, name, description, owner_id, default_executor_id, default_environment_id, default_agent_profile_id, created_at, updated_at
|
||||
SELECT id, name, description, owner_id, default_executor_id, default_environment_id, default_agent_profile_id, default_config_agent_profile_id, created_at, updated_at
|
||||
FROM workspaces ORDER BY created_at DESC
|
||||
`)
|
||||
if err != nil {
|
||||
@@ -131,6 +138,7 @@ func (r *Repository) ListWorkspaces(ctx context.Context) ([]*models.Workspace, e
|
||||
var defaultExecutorID sql.NullString
|
||||
var defaultEnvironmentID sql.NullString
|
||||
var defaultAgentProfileID sql.NullString
|
||||
var defaultConfigAgentProfileID sql.NullString
|
||||
if err := rows.Scan(
|
||||
&workspace.ID,
|
||||
&workspace.Name,
|
||||
@@ -139,6 +147,7 @@ func (r *Repository) ListWorkspaces(ctx context.Context) ([]*models.Workspace, e
|
||||
&defaultExecutorID,
|
||||
&defaultEnvironmentID,
|
||||
&defaultAgentProfileID,
|
||||
&defaultConfigAgentProfileID,
|
||||
&workspace.CreatedAt,
|
||||
&workspace.UpdatedAt,
|
||||
); err != nil {
|
||||
@@ -153,6 +162,9 @@ func (r *Repository) ListWorkspaces(ctx context.Context) ([]*models.Workspace, e
|
||||
if defaultAgentProfileID.Valid && defaultAgentProfileID.String != "" {
|
||||
workspace.DefaultAgentProfileID = &defaultAgentProfileID.String
|
||||
}
|
||||
if defaultConfigAgentProfileID.Valid && defaultConfigAgentProfileID.String != "" {
|
||||
workspace.DefaultConfigAgentProfileID = &defaultConfigAgentProfileID.String
|
||||
}
|
||||
result = append(result, workspace)
|
||||
}
|
||||
return result, rows.Err()
|
||||
|
||||
@@ -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, false, false)
|
||||
tasks, total, err := repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 10, false, 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, false, false)
|
||||
tasks, total, err = repo.ListTasksByWorkspace(ctx, "ws-1", "", 1, 2, false, 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, false, false)
|
||||
tasksPage2, _, err := repo.ListTasksByWorkspace(ctx, "ws-1", "", 2, 2, false, 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, false, false)
|
||||
_, totalAuth, err := repo.ListTasksByWorkspace(ctx, "ws-1", "authentication", 1, 10, false, 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, false, false)
|
||||
tasksDarkMode, totalDarkMode, err := repo.ListTasksByWorkspace(ctx, "ws-1", "dark mode", 1, 10, false, 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, false, false)
|
||||
tasksRepo, totalRepo, err := repo.ListTasksByWorkspace(ctx, "ws-1", "MyProject", 1, 10, false, 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, false, false)
|
||||
_, totalPath, err := repo.ListTasksByWorkspace(ctx, "ws-1", "myproject", 1, 10, false, 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, false, false)
|
||||
tasksNone, totalNone, err := repo.ListTasksByWorkspace(ctx, "ws-1", "nonexistent", 1, 10, false, false, false, false)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to search tasks with no results: %v", err)
|
||||
}
|
||||
|
||||
@@ -122,15 +122,16 @@ func (s *Service) publishWorkspaceEvent(ctx context.Context, eventType string, w
|
||||
}
|
||||
|
||||
data := map[string]interface{}{
|
||||
"id": workspace.ID,
|
||||
"name": workspace.Name,
|
||||
"description": workspace.Description,
|
||||
"owner_id": workspace.OwnerID,
|
||||
"default_executor_id": workspace.DefaultExecutorID,
|
||||
"default_environment_id": workspace.DefaultEnvironmentID,
|
||||
"default_agent_profile_id": workspace.DefaultAgentProfileID,
|
||||
"created_at": workspace.CreatedAt.Format(time.RFC3339),
|
||||
"updated_at": workspace.UpdatedAt.Format(time.RFC3339),
|
||||
"id": workspace.ID,
|
||||
"name": workspace.Name,
|
||||
"description": workspace.Description,
|
||||
"owner_id": workspace.OwnerID,
|
||||
"default_executor_id": workspace.DefaultExecutorID,
|
||||
"default_environment_id": workspace.DefaultEnvironmentID,
|
||||
"default_agent_profile_id": workspace.DefaultAgentProfileID,
|
||||
"default_config_agent_profile_id": workspace.DefaultConfigAgentProfileID,
|
||||
"created_at": workspace.CreatedAt.Format(time.RFC3339),
|
||||
"updated_at": workspace.UpdatedAt.Format(time.RFC3339),
|
||||
}
|
||||
|
||||
s.publishEventToBus(ctx, eventType, "workspace", workspace.ID, data)
|
||||
|
||||
@@ -62,21 +62,23 @@ type UpdateWorkflowRequest struct {
|
||||
|
||||
// CreateWorkspaceRequest contains the data for creating a new workspace
|
||||
type CreateWorkspaceRequest struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateWorkspaceRequest contains the data for updating a workspace
|
||||
type UpdateWorkspaceRequest struct {
|
||||
Name *string `json:"name,omitempty"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
Name *string `json:"name,omitempty"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"`
|
||||
}
|
||||
|
||||
// FindOrCreateRepositoryRequest contains the data for finding or creating a repository by provider info.
|
||||
|
||||
@@ -21,13 +21,14 @@ const spritesTokenEnvKey = "SPRITES_API_TOKEN"
|
||||
// CreateWorkspace creates a new workspace
|
||||
func (s *Service) CreateWorkspace(ctx context.Context, req *CreateWorkspaceRequest) (*models.Workspace, error) {
|
||||
workspace := &models.Workspace{
|
||||
ID: uuid.New().String(),
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
OwnerID: req.OwnerID,
|
||||
DefaultExecutorID: normalizeOptionalID(req.DefaultExecutorID),
|
||||
DefaultEnvironmentID: normalizeOptionalID(req.DefaultEnvironmentID),
|
||||
DefaultAgentProfileID: normalizeOptionalID(req.DefaultAgentProfileID),
|
||||
ID: uuid.New().String(),
|
||||
Name: req.Name,
|
||||
Description: req.Description,
|
||||
OwnerID: req.OwnerID,
|
||||
DefaultExecutorID: normalizeOptionalID(req.DefaultExecutorID),
|
||||
DefaultEnvironmentID: normalizeOptionalID(req.DefaultEnvironmentID),
|
||||
DefaultAgentProfileID: normalizeOptionalID(req.DefaultAgentProfileID),
|
||||
DefaultConfigAgentProfileID: normalizeOptionalID(req.DefaultConfigAgentProfileID),
|
||||
}
|
||||
|
||||
if err := s.workspaces.CreateWorkspace(ctx, workspace); err != nil {
|
||||
@@ -67,6 +68,9 @@ func (s *Service) UpdateWorkspace(ctx context.Context, id string, req *UpdateWor
|
||||
if req.DefaultAgentProfileID != nil {
|
||||
workspace.DefaultAgentProfileID = normalizeOptionalID(req.DefaultAgentProfileID)
|
||||
}
|
||||
if req.DefaultConfigAgentProfileID != nil {
|
||||
workspace.DefaultConfigAgentProfileID = normalizeOptionalID(req.DefaultConfigAgentProfileID)
|
||||
}
|
||||
workspace.UpdatedAt = time.Now().UTC()
|
||||
|
||||
if err := s.workspaces.UpdateWorkspace(ctx, workspace); err != nil {
|
||||
|
||||
@@ -656,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, includeEphemeral, onlyEphemeral bool) ([]*models.Task, int, error) {
|
||||
tasks, total, err := s.tasks.ListTasksByWorkspace(ctx, workspaceID, query, page, pageSize, includeArchived, includeEphemeral, onlyEphemeral)
|
||||
func (s *Service) ListTasksByWorkspace(ctx context.Context, workspaceID string, query string, page, pageSize int, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig bool) ([]*models.Task, int, error) {
|
||||
tasks, total, err := s.tasks.ListTasksByWorkspace(ctx, workspaceID, query, page, pageSize, includeArchived, includeEphemeral, onlyEphemeral, excludeConfig)
|
||||
if err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
|
||||
@@ -4,31 +4,34 @@ import "time"
|
||||
|
||||
// Workspace represents a workspace
|
||||
type Workspace struct {
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
ID string `json:"id"`
|
||||
Name string `json:"name"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// CreateWorkspaceRequest for creating a new workspace
|
||||
type CreateWorkspaceRequest struct {
|
||||
Name string `json:"name" binding:"required,max=255"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
Name string `json:"name" binding:"required,max=255"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"`
|
||||
}
|
||||
|
||||
// UpdateWorkspaceRequest for updating an existing workspace
|
||||
type UpdateWorkspaceRequest struct {
|
||||
Name *string `json:"name,omitempty" binding:"omitempty,max=255"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
Name *string `json:"name,omitempty" binding:"omitempty,max=255"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
DefaultExecutorID *string `json:"default_executor_id,omitempty"`
|
||||
DefaultEnvironmentID *string `json:"default_environment_id,omitempty"`
|
||||
DefaultAgentProfileID *string `json:"default_agent_profile_id,omitempty"`
|
||||
DefaultConfigAgentProfileID *string `json:"default_config_agent_profile_id,omitempty"`
|
||||
}
|
||||
|
||||
@@ -156,6 +156,9 @@ const (
|
||||
ActionWorkflowCreated = "workflow.created"
|
||||
ActionWorkflowUpdated = "workflow.updated"
|
||||
ActionWorkflowDeleted = "workflow.deleted"
|
||||
ActionWorkflowStepCreated = "workflow.step.created"
|
||||
ActionWorkflowStepUpdated = "workflow.step.updated"
|
||||
ActionWorkflowStepDeleted = "workflow.step.deleted"
|
||||
ActionSessionMessageAdded = "session.message.added"
|
||||
ActionSessionMessageUpdated = "session.message.updated"
|
||||
ActionSessionStateChanged = "session.state_changed"
|
||||
@@ -299,6 +302,37 @@ const (
|
||||
ActionMCPUpdateTaskPlan = "mcp.update_task_plan"
|
||||
ActionMCPDeleteTaskPlan = "mcp.delete_task_plan"
|
||||
ActionMCPClarificationTimeout = "mcp.clarification_timeout"
|
||||
|
||||
// Config-mode MCP actions (agent-native configuration)
|
||||
ActionMCPCreateWorkflow = "mcp.create_workflow"
|
||||
ActionMCPUpdateWorkflow = "mcp.update_workflow"
|
||||
ActionMCPDeleteWorkflow = "mcp.delete_workflow"
|
||||
|
||||
ActionMCPCreateWorkflowStep = "mcp.create_workflow_step"
|
||||
ActionMCPUpdateWorkflowStep = "mcp.update_workflow_step"
|
||||
ActionMCPDeleteWorkflowStep = "mcp.delete_workflow_step"
|
||||
ActionMCPReorderWorkflowStep = "mcp.reorder_workflow_steps"
|
||||
|
||||
ActionMCPListAgents = "mcp.list_agents"
|
||||
ActionMCPUpdateAgent = "mcp.update_agent"
|
||||
|
||||
ActionMCPListAgentProfiles = "mcp.list_agent_profiles"
|
||||
ActionMCPCreateAgentProfile = "mcp.create_agent_profile"
|
||||
ActionMCPUpdateAgentProfile = "mcp.update_agent_profile"
|
||||
ActionMCPDeleteAgentProfile = "mcp.delete_agent_profile"
|
||||
ActionMCPGetMcpConfig = "mcp.get_mcp_config"
|
||||
ActionMCPUpdateMcpConfig = "mcp.update_mcp_config"
|
||||
|
||||
ActionMCPListExecutors = "mcp.list_executors"
|
||||
ActionMCPListExecutorProfiles = "mcp.list_executor_profiles"
|
||||
ActionMCPCreateExecutorProfile = "mcp.create_executor_profile"
|
||||
ActionMCPUpdateExecutorProfile = "mcp.update_executor_profile"
|
||||
ActionMCPDeleteExecutorProfile = "mcp.delete_executor_profile"
|
||||
|
||||
ActionMCPMoveTask = "mcp.move_task"
|
||||
ActionMCPDeleteTask = "mcp.delete_task"
|
||||
ActionMCPArchiveTask = "mcp.archive_task"
|
||||
ActionMCPUpdateTaskState = "mcp.update_task_state"
|
||||
)
|
||||
|
||||
// GitHub integration actions
|
||||
|
||||
@@ -78,6 +78,7 @@ export async function updateWorkspaceAction(
|
||||
default_executor_id?: string;
|
||||
default_environment_id?: string;
|
||||
default_agent_profile_id?: string;
|
||||
default_config_agent_profile_id?: string;
|
||||
},
|
||||
) {
|
||||
return fetchJson<Workspace>(`${apiBaseUrl}/api/v1/workspaces/${id}`, {
|
||||
|
||||
@@ -10,6 +10,7 @@ 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 { ConfigChatProvider } from "@/components/config-chat/config-chat-provider";
|
||||
import { SessionFailureToastBridge } from "@/components/session-failure-toast-bridge";
|
||||
|
||||
export const metadata: Metadata = {
|
||||
@@ -64,7 +65,9 @@ export default function RootLayout({
|
||||
<WebSocketConnector />
|
||||
<GlobalCommands />
|
||||
<CommandPanel />
|
||||
<QuickChatProvider>{children}</QuickChatProvider>
|
||||
<ConfigChatProvider>
|
||||
<QuickChatProvider>{children}</QuickChatProvider>
|
||||
</ConfigChatProvider>
|
||||
</CommandRegistryProvider>
|
||||
</ToastProvider>
|
||||
</TooltipProvider>
|
||||
|
||||
@@ -33,6 +33,7 @@ function mapWorkspaceItem(ws: WorkspaceItem) {
|
||||
default_executor_id: ws.default_executor_id ?? null,
|
||||
default_environment_id: ws.default_environment_id ?? null,
|
||||
default_agent_profile_id: ws.default_agent_profile_id ?? null,
|
||||
default_config_agent_profile_id: ws.default_config_agent_profile_id ?? null,
|
||||
created_at: ws.created_at,
|
||||
updated_at: ws.updated_at,
|
||||
};
|
||||
|
||||
@@ -14,8 +14,11 @@ import {
|
||||
import { Badge } from "@kandev/ui/badge";
|
||||
import { Button } from "@kandev/ui/button";
|
||||
import { Card, CardContent } from "@kandev/ui/card";
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@kandev/ui/select";
|
||||
import { Separator } from "@kandev/ui/separator";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
|
||||
import { useToast } from "@/components/toast-provider";
|
||||
import { updateWorkspaceAction } from "@/app/actions/workspaces";
|
||||
import {
|
||||
createCustomTUIAgent,
|
||||
listAgentDiscovery,
|
||||
@@ -369,6 +372,72 @@ function AgentProfilesSection({ savedAgents }: AgentProfilesSectionProps) {
|
||||
);
|
||||
}
|
||||
|
||||
function ConfigChatAgentSection() {
|
||||
const workspace = useAppStore(
|
||||
(s) => s.workspaces.items.find((w) => w.id === s.workspaces.activeId) ?? null,
|
||||
);
|
||||
const profiles = useAppStore((s) => s.agentProfiles.items ?? []);
|
||||
const currentProfileId = workspace?.default_config_agent_profile_id ?? "";
|
||||
const [saving, setSaving] = useState(false);
|
||||
const { toast } = useToast();
|
||||
|
||||
const storeApi = useAppStoreApi();
|
||||
|
||||
const handleChange = async (value: string) => {
|
||||
const effectiveValue = value === "none" ? "" : value;
|
||||
if (!workspace) return;
|
||||
setSaving(true);
|
||||
try {
|
||||
await updateWorkspaceAction(workspace.id, {
|
||||
default_config_agent_profile_id: effectiveValue,
|
||||
});
|
||||
const { workspaces, setWorkspaces } = storeApi.getState();
|
||||
setWorkspaces(
|
||||
workspaces.items.map((w) =>
|
||||
w.id === workspace.id ? { ...w, default_config_agent_profile_id: effectiveValue } : w,
|
||||
),
|
||||
);
|
||||
toast({ title: "Configuration agent updated", variant: "success" });
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Failed to update",
|
||||
description: error instanceof Error ? error.message : "Unknown error",
|
||||
variant: "error",
|
||||
});
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (!workspace) return null;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Separator />
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold">Configuration Chat Agent</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Choose which agent profile to use for the Configuration Chat. This agent can manage your
|
||||
workflows, agent profiles, and MCP configuration.
|
||||
</p>
|
||||
</div>
|
||||
<Select value={currentProfileId || "none"} onValueChange={handleChange} disabled={saving}>
|
||||
<SelectTrigger className="w-full max-w-sm cursor-pointer">
|
||||
<SelectValue placeholder="Choose an agent profile..." />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="none">No default</SelectItem>
|
||||
{profiles.map((p) => (
|
||||
<SelectItem key={p.id} value={p.id} className="cursor-pointer">
|
||||
{p.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function useAgentPageState() {
|
||||
const { items: discoveryAgents, loading: discoveryLoading } = useAgentDiscovery();
|
||||
const savedAgents = useAppStore((state) => state.settingsAgents.items);
|
||||
@@ -494,6 +563,8 @@ export default function AgentsSettingsPage() {
|
||||
|
||||
<AgentProfilesSection savedAgents={savedAgents} />
|
||||
|
||||
<ConfigChatAgentSection />
|
||||
|
||||
<AddTUIAgentDialog
|
||||
open={tuiDialogOpen}
|
||||
onOpenChange={setTuiDialogOpen}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { SettingsLayoutClient } from "@/components/settings/settings-layout-client";
|
||||
import { StateProvider } from "@/components/state-provider";
|
||||
import { StateHydrator } from "@/components/state-hydrator";
|
||||
import { listAgents, listExecutors, listWorkspaces } from "@/lib/api";
|
||||
import { toAgentProfileOption } from "@/lib/state/slices/settings/types";
|
||||
|
||||
@@ -23,6 +23,7 @@ async function SettingsLayoutServer({ children }: { children: React.ReactNode })
|
||||
default_executor_id: workspace.default_executor_id ?? null,
|
||||
default_environment_id: workspace.default_environment_id ?? null,
|
||||
default_agent_profile_id: workspace.default_agent_profile_id ?? null,
|
||||
default_config_agent_profile_id: workspace.default_config_agent_profile_id ?? null,
|
||||
})),
|
||||
activeId: workspaces.workspaces[0]?.id ?? null,
|
||||
},
|
||||
@@ -47,8 +48,9 @@ async function SettingsLayoutServer({ children }: { children: React.ReactNode })
|
||||
}
|
||||
|
||||
return (
|
||||
<StateProvider initialState={initialState}>
|
||||
<>
|
||||
<StateHydrator initialState={initialState} />
|
||||
<SettingsLayoutClient>{children}</SettingsLayoutClient>
|
||||
</StateProvider>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
"use client";
|
||||
|
||||
import { memo, useEffect, useRef, useState } from "react";
|
||||
import {
|
||||
IconLoader2,
|
||||
IconMessageCircle,
|
||||
IconPlus,
|
||||
IconSend2,
|
||||
IconSparkles,
|
||||
IconX,
|
||||
} from "@tabler/icons-react";
|
||||
import { Popover, PopoverContent, PopoverTrigger } from "@kandev/ui/popover";
|
||||
import { Button } from "@kandev/ui/button";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
|
||||
import { Textarea } from "@kandev/ui/textarea";
|
||||
import { QuickChatContent } from "@/components/quick-chat/quick-chat-content";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { useConfigChat } from "./use-config-chat";
|
||||
import type { ConfigChatSession } from "@/lib/state/slices/ui/types";
|
||||
|
||||
const SUGGESTION_PROMPTS = [
|
||||
"Add a 'Code Review' step to my workflow",
|
||||
"Create a new agent profile with auto-approve enabled",
|
||||
"Show me the current workflow configuration",
|
||||
"Update the MCP servers for the default agent profile",
|
||||
];
|
||||
|
||||
function SuggestionList() {
|
||||
return (
|
||||
<div className="flex-1 flex flex-col justify-end space-y-1.5 mb-3">
|
||||
<p className="text-xs text-muted-foreground font-medium">Try asking</p>
|
||||
{SUGGESTION_PROMPTS.map((prompt) => (
|
||||
<p key={prompt} className="text-xs text-muted-foreground/70 py-0.5">
|
||||
{prompt}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ProfileSelector({ onSelect }: { onSelect: (id: string) => void }) {
|
||||
const profiles = useAppStore((s) => s.agentProfiles.items ?? []);
|
||||
return (
|
||||
<div className="flex-1 flex flex-col">
|
||||
<p className="text-xs font-medium mb-3">Select an agent profile</p>
|
||||
<div className="space-y-1.5 max-h-[320px] overflow-y-auto">
|
||||
{profiles.map((profile) => (
|
||||
<button
|
||||
key={profile.id}
|
||||
type="button"
|
||||
onClick={() => onSelect(profile.id)}
|
||||
className="w-full flex items-center gap-2.5 rounded-md border p-2.5 text-left transition-colors cursor-pointer hover:border-primary/50 hover:bg-accent/50"
|
||||
>
|
||||
<div className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md border bg-background">
|
||||
<IconMessageCircle className="h-3.5 w-3.5" />
|
||||
</div>
|
||||
<div className="min-w-0">
|
||||
<p className="text-xs font-medium truncate">{profile.label}</p>
|
||||
<p className="text-[11px] text-muted-foreground truncate">{profile.agent_name}</p>
|
||||
</div>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="text-[11px] text-muted-foreground mt-3">
|
||||
This will be saved as your default. Change it in Agent settings.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ConfigChatTabs({
|
||||
sessions,
|
||||
activeSessionId,
|
||||
onTabChange,
|
||||
onTabClose,
|
||||
onNewChat,
|
||||
}: {
|
||||
sessions: ConfigChatSession[];
|
||||
activeSessionId: string | null;
|
||||
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;
|
||||
const tabName = s.name || `Chat ${index + 1}`;
|
||||
return (
|
||||
<div
|
||||
key={s.sessionId}
|
||||
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 config chat"
|
||||
>
|
||||
<IconPlus className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function LoadingState() {
|
||||
return (
|
||||
<div className="flex-1 flex flex-col items-center justify-center gap-3">
|
||||
<IconLoader2 className="h-6 w-6 animate-spin text-muted-foreground" />
|
||||
<p className="text-xs text-muted-foreground">Starting config chat...</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function ConfigChatEmptyState({
|
||||
defaultProfileId,
|
||||
onSelectPrompt,
|
||||
isStarting,
|
||||
error,
|
||||
}: {
|
||||
defaultProfileId: string | undefined;
|
||||
onSelectPrompt: (prompt: string, profileId: string) => void;
|
||||
isStarting: boolean;
|
||||
error: string | null;
|
||||
}) {
|
||||
const profileCount = useAppStore((s) => s.agentProfiles.items?.length ?? 0);
|
||||
const [selectedProfileId, setSelectedProfileId] = useState(defaultProfileId ?? "");
|
||||
const [inputValue, setInputValue] = useState("");
|
||||
|
||||
const textareaRef = useRef<HTMLTextAreaElement>(null);
|
||||
const needsProfileSelection = !selectedProfileId && !defaultProfileId && profileCount > 0;
|
||||
const effectiveProfileId = selectedProfileId || defaultProfileId || "";
|
||||
const canSubmit = inputValue.trim().length > 0 && !!effectiveProfileId && !isStarting;
|
||||
|
||||
useEffect(() => {
|
||||
if (!needsProfileSelection && !isStarting && textareaRef.current) {
|
||||
textareaRef.current.focus();
|
||||
}
|
||||
}, [needsProfileSelection, isStarting]);
|
||||
|
||||
const handleSubmit = () => {
|
||||
const trimmed = inputValue.trim();
|
||||
if (!trimmed || !effectiveProfileId) return;
|
||||
onSelectPrompt(trimmed, effectiveProfileId);
|
||||
};
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
handleSubmit();
|
||||
}
|
||||
};
|
||||
|
||||
if (isStarting) return <LoadingState />;
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col p-3">
|
||||
<div className="text-center space-y-1 mb-3">
|
||||
<div className="flex justify-center">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-full border bg-muted">
|
||||
<IconSparkles className="h-4 w-4 text-muted-foreground" />
|
||||
</div>
|
||||
</div>
|
||||
<h3 className="text-sm font-medium">Configure Kandev with AI</h3>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Manage workflows, agent profiles, and MCP configuration.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{needsProfileSelection ? (
|
||||
<ProfileSelector onSelect={setSelectedProfileId} />
|
||||
) : (
|
||||
<>
|
||||
{inputValue.length === 0 ? <SuggestionList /> : <div className="flex-1" />}
|
||||
|
||||
<div className="flex items-end gap-2">
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={inputValue}
|
||||
onChange={(e) => setInputValue(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Ask anything about your configuration..."
|
||||
disabled={!effectiveProfileId || isStarting}
|
||||
className="min-h-[40px] max-h-[120px] flex-1 resize-none text-xs"
|
||||
/>
|
||||
<Button
|
||||
size="icon"
|
||||
onClick={handleSubmit}
|
||||
disabled={!canSubmit}
|
||||
className="h-[40px] w-[40px] shrink-0 cursor-pointer"
|
||||
>
|
||||
<IconSend2 className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{error && <p className="text-xs text-destructive mt-2">{error}</p>}
|
||||
</>
|
||||
)}
|
||||
|
||||
{profileCount === 0 && (
|
||||
<p className="text-xs text-center text-muted-foreground mt-2">
|
||||
No agent profiles found. Create one in the Agents settings first.
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type ConfigChatPanelProps = {
|
||||
workspaceId: string;
|
||||
showFab?: boolean;
|
||||
};
|
||||
|
||||
export const ConfigChatPanel = memo(function ConfigChatPanel({
|
||||
workspaceId,
|
||||
showFab = true,
|
||||
}: ConfigChatPanelProps) {
|
||||
const chat = useConfigChat(workspaceId);
|
||||
const showEmptyState = !chat.activeSessionId;
|
||||
|
||||
return (
|
||||
<Popover
|
||||
open={chat.isOpen}
|
||||
onOpenChange={(nextOpen) => {
|
||||
if (nextOpen) {
|
||||
chat.open();
|
||||
} else {
|
||||
chat.close();
|
||||
}
|
||||
}}
|
||||
>
|
||||
{showFab ? (
|
||||
<Tooltip open={chat.isOpen ? false : undefined}>
|
||||
<TooltipTrigger asChild>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
size="icon"
|
||||
className="fixed bottom-6 right-6 z-50 h-12 w-12 rounded-full shadow-lg cursor-pointer"
|
||||
>
|
||||
<IconSparkles className="h-8 w-8" />
|
||||
<span className="sr-only">Configuration Chat</span>
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent side="left">
|
||||
<p className="font-medium">Configuration Chat</p>
|
||||
<p className="text-xs text-muted-foreground">Configure Kandev with natural language</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
) : (
|
||||
<PopoverTrigger asChild>
|
||||
<span className="fixed bottom-6 right-6 h-0 w-0" aria-hidden />
|
||||
</PopoverTrigger>
|
||||
)}
|
||||
<PopoverContent
|
||||
side="top"
|
||||
align="end"
|
||||
sideOffset={8}
|
||||
onInteractOutside={(e) => e.preventDefault()}
|
||||
className="w-[420px] max-h-[550px] h-[550px] p-0 gap-0 flex flex-col shadow-2xl"
|
||||
>
|
||||
<div className="flex items-center justify-between px-3 py-1.5 border-b bg-muted/30">
|
||||
<div className="flex items-center gap-1.5">
|
||||
<IconSparkles className="h-3.5 w-3.5 text-muted-foreground" />
|
||||
<span className="text-xs font-medium">Configuration Chat</span>
|
||||
</div>
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-6 w-6 p-0 cursor-pointer"
|
||||
onClick={chat.close}
|
||||
aria-label="Close config chat"
|
||||
>
|
||||
<IconX className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</div>
|
||||
<ConfigChatTabs
|
||||
sessions={chat.sessions}
|
||||
activeSessionId={chat.activeSessionId}
|
||||
onTabChange={chat.setActiveSession}
|
||||
onTabClose={chat.closeSession}
|
||||
onNewChat={chat.newChat}
|
||||
/>
|
||||
{showEmptyState ? (
|
||||
<ConfigChatEmptyState
|
||||
defaultProfileId={chat.defaultProfileId}
|
||||
onSelectPrompt={(prompt, profileId) => chat.startSession(profileId, prompt)}
|
||||
isStarting={chat.isStarting}
|
||||
error={chat.error}
|
||||
/>
|
||||
) : (
|
||||
<QuickChatContent
|
||||
sessionId={chat.activeSessionId!}
|
||||
minimalToolbar
|
||||
placeholderOverride="Ask anything about your configuration..."
|
||||
initialPrompt={chat.pendingPrompt ?? undefined}
|
||||
onInitialPromptSent={chat.clearPendingPrompt}
|
||||
/>
|
||||
)}
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,41 @@
|
||||
"use client";
|
||||
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { useSettingsData } from "@/hooks/domains/settings/use-settings-data";
|
||||
import { ConfigChatPanel } from "./config-chat-panel";
|
||||
|
||||
// SSR-safe client mount detection without useEffect setState
|
||||
const emptySubscribe = () => () => {};
|
||||
const getClientSnapshot = () => true;
|
||||
const getServerSnapshot = () => false;
|
||||
|
||||
function useIsMounted() {
|
||||
return useSyncExternalStore(emptySubscribe, getClientSnapshot, getServerSnapshot);
|
||||
}
|
||||
|
||||
/**
|
||||
* Global provider for Config Chat functionality.
|
||||
* Renders the floating popover that can be opened from anywhere in the app.
|
||||
* The FAB trigger is only visible on settings pages; on other pages the popover
|
||||
* can be opened via the command panel (Cmd+K → "Configuration Chat").
|
||||
*/
|
||||
export function ConfigChatProvider({ children }: { children: React.ReactNode }) {
|
||||
const activeWorkspace = useAppStore((s) => s.workspaces.activeId);
|
||||
const mounted = useIsMounted();
|
||||
const pathname = usePathname();
|
||||
const isSettingsPage = pathname.startsWith("/settings");
|
||||
|
||||
// Preload agent profiles so they're available when config chat is opened
|
||||
useSettingsData(true);
|
||||
|
||||
return (
|
||||
<>
|
||||
{children}
|
||||
{mounted && activeWorkspace && (
|
||||
<ConfigChatPanel workspaceId={activeWorkspace} showFab={isSettingsPage} />
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useState } from "react";
|
||||
import { useShallow } from "zustand/react/shallow";
|
||||
import { useAppStore, useAppStoreApi } from "@/components/state-provider";
|
||||
import { startConfigChat } from "@/lib/api/domains/workspace-api";
|
||||
import { updateWorkspaceAction } from "@/app/actions/workspaces";
|
||||
|
||||
function useConfigChatStore() {
|
||||
return useAppStore(
|
||||
useShallow((s) => ({
|
||||
isOpen: s.configChat.isOpen,
|
||||
sessions: s.configChat.sessions,
|
||||
activeSessionId: s.configChat.activeSessionId,
|
||||
workspaceId: s.configChat.workspaceId,
|
||||
openConfigChat: s.openConfigChat,
|
||||
startNewConfigChat: s.startNewConfigChat,
|
||||
closeConfigChat: s.closeConfigChat,
|
||||
closeConfigChatSession: s.closeConfigChatSession,
|
||||
setActiveConfigChatSession: s.setActiveConfigChatSession,
|
||||
renameConfigChatSession: s.renameConfigChatSession,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
function useUpdateWorkspaceInStore() {
|
||||
const storeApi = useAppStoreApi();
|
||||
return (workspaceId: string, updates: Record<string, unknown>) => {
|
||||
const { workspaces, setWorkspaces } = storeApi.getState();
|
||||
setWorkspaces(workspaces.items.map((w) => (w.id === workspaceId ? { ...w, ...updates } : w)));
|
||||
};
|
||||
}
|
||||
|
||||
export function useConfigChat(workspaceId: string) {
|
||||
const store = useConfigChatStore();
|
||||
const storeApi = useAppStoreApi();
|
||||
const [isStarting, setIsStarting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [pendingPrompt, setPendingPrompt] = useState<string | null>(null);
|
||||
const updateWorkspaceInStore = useUpdateWorkspaceInStore();
|
||||
|
||||
const workspace = useAppStore(
|
||||
(s) => s.workspaces.items.find((w) => w.id === workspaceId) ?? null,
|
||||
);
|
||||
|
||||
const defaultProfileId =
|
||||
workspace?.default_config_agent_profile_id ?? workspace?.default_agent_profile_id ?? undefined;
|
||||
|
||||
const open = useCallback(() => {
|
||||
if (store.activeSessionId && store.workspaceId === workspaceId) {
|
||||
store.openConfigChat(store.activeSessionId, workspaceId);
|
||||
return;
|
||||
}
|
||||
store.startNewConfigChat(workspaceId);
|
||||
}, [workspaceId, store]);
|
||||
|
||||
const startSession = useCallback(
|
||||
async (agentProfileId: string, prompt?: string) => {
|
||||
if (isStarting) return;
|
||||
setIsStarting(true);
|
||||
setError(null);
|
||||
try {
|
||||
// Don't send the prompt to the backend — it will be sent via WS
|
||||
// message.add by QuickChatContent after the WS subscription is
|
||||
// established. This avoids a race condition where the agent completes
|
||||
// before the frontend subscribes and events are lost.
|
||||
const response = await startConfigChat(workspaceId, {
|
||||
agent_profile_id: agentProfileId,
|
||||
});
|
||||
|
||||
// Seed the task session in the main store so QuickChatContent can find it
|
||||
// immediately. The WS event will merge on top when it arrives.
|
||||
storeApi.getState().setTaskSession({
|
||||
id: response.session_id,
|
||||
task_id: response.task_id,
|
||||
state: "CREATED",
|
||||
started_at: new Date().toISOString(),
|
||||
updated_at: new Date().toISOString(),
|
||||
agent_profile_id: agentProfileId,
|
||||
});
|
||||
|
||||
// Store the prompt so QuickChatContent can send it via WS.
|
||||
setPendingPrompt(prompt ?? null);
|
||||
|
||||
store.openConfigChat(response.session_id, workspaceId);
|
||||
store.renameConfigChatSession(response.session_id, prompt?.slice(0, 40) || "Config Chat");
|
||||
|
||||
// Save the selected profile as the workspace default for future sessions
|
||||
if (!workspace?.default_config_agent_profile_id) {
|
||||
try {
|
||||
await updateWorkspaceAction(workspaceId, {
|
||||
default_config_agent_profile_id: agentProfileId,
|
||||
});
|
||||
updateWorkspaceInStore(workspaceId, {
|
||||
default_config_agent_profile_id: agentProfileId,
|
||||
});
|
||||
} catch {
|
||||
// Non-critical — don't fail the chat start for this
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : "Unknown error";
|
||||
setError(message);
|
||||
} finally {
|
||||
setIsStarting(false);
|
||||
}
|
||||
},
|
||||
[
|
||||
workspaceId,
|
||||
isStarting,
|
||||
store,
|
||||
storeApi,
|
||||
workspace?.default_config_agent_profile_id,
|
||||
updateWorkspaceInStore,
|
||||
],
|
||||
);
|
||||
|
||||
const close = useCallback(() => {
|
||||
store.closeConfigChat();
|
||||
}, [store]);
|
||||
|
||||
const newChat = useCallback(() => {
|
||||
store.startNewConfigChat(workspaceId);
|
||||
}, [store, workspaceId]);
|
||||
|
||||
const clearPendingPrompt = useCallback(() => setPendingPrompt(null), []);
|
||||
|
||||
return {
|
||||
isOpen: store.isOpen,
|
||||
sessions: store.sessions,
|
||||
activeSessionId: store.activeSessionId,
|
||||
isStarting,
|
||||
error,
|
||||
workspace,
|
||||
defaultProfileId,
|
||||
pendingPrompt,
|
||||
clearPendingPrompt,
|
||||
open,
|
||||
startSession,
|
||||
close,
|
||||
closeSession: store.closeConfigChatSession,
|
||||
setActiveSession: store.setActiveConfigChatSession,
|
||||
newChat,
|
||||
};
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
IconServer,
|
||||
IconFolder,
|
||||
IconMessageCircle,
|
||||
IconSparkles,
|
||||
} from "@tabler/icons-react";
|
||||
import { useRegisterCommands } from "@/hooks/use-register-commands";
|
||||
import { useKeyboardShortcut } from "@/hooks/use-keyboard-shortcut";
|
||||
@@ -122,6 +123,11 @@ export function GlobalCommands() {
|
||||
const activeWorkspaceId = useAppStore((s) => s.workspaces.activeId);
|
||||
const quickChatSessions = useAppStore((s) => s.quickChat.sessions);
|
||||
const openQuickChat = useAppStore((s) => s.openQuickChat);
|
||||
const startNewConfigChat = useAppStore((s) => s.startNewConfigChat);
|
||||
const openConfigChat = useAppStore((s) => s.openConfigChat);
|
||||
const configChatSessions = useAppStore((s) => s.configChat.sessions);
|
||||
const configChatActiveSessionId = useAppStore((s) => s.configChat.activeSessionId);
|
||||
const configChatWorkspaceId = useAppStore((s) => s.configChat.workspaceId);
|
||||
|
||||
const handleOpenQuickChat = useCallback(() => {
|
||||
if (!activeWorkspaceId) {
|
||||
@@ -138,6 +144,29 @@ export function GlobalCommands() {
|
||||
}
|
||||
}, [activeWorkspaceId, quickChatSessions, openQuickChat]);
|
||||
|
||||
const handleOpenConfigChat = useCallback(() => {
|
||||
if (!activeWorkspaceId) return;
|
||||
// Reuse existing session if one is active for this workspace
|
||||
if (configChatActiveSessionId && configChatWorkspaceId === activeWorkspaceId) {
|
||||
openConfigChat(configChatActiveSessionId, activeWorkspaceId);
|
||||
return;
|
||||
}
|
||||
// Check for a persisted session for this workspace
|
||||
const existingSession = configChatSessions.find((s) => s.workspaceId === activeWorkspaceId);
|
||||
if (existingSession) {
|
||||
openConfigChat(existingSession.sessionId, activeWorkspaceId);
|
||||
return;
|
||||
}
|
||||
startNewConfigChat(activeWorkspaceId);
|
||||
}, [
|
||||
activeWorkspaceId,
|
||||
configChatSessions,
|
||||
configChatActiveSessionId,
|
||||
configChatWorkspaceId,
|
||||
openConfigChat,
|
||||
startNewConfigChat,
|
||||
]);
|
||||
|
||||
const quickChatCommand: CommandItem = useMemo(
|
||||
() => ({
|
||||
id: "quick-chat",
|
||||
@@ -151,13 +180,26 @@ export function GlobalCommands() {
|
||||
[handleOpenQuickChat],
|
||||
);
|
||||
|
||||
const configChatCommand: CommandItem = useMemo(
|
||||
() => ({
|
||||
id: "config-chat",
|
||||
label: "Configuration Chat",
|
||||
group: "Actions",
|
||||
icon: <IconSparkles className="size-3.5" />,
|
||||
keywords: ["config", "configure", "settings", "chat", "ai"],
|
||||
action: handleOpenConfigChat,
|
||||
}),
|
||||
[handleOpenConfigChat],
|
||||
);
|
||||
|
||||
const commands = useMemo<CommandItem[]>(
|
||||
() => [
|
||||
...buildNavigationCommands(router.push),
|
||||
buildThemeCommand(resolvedTheme, setTheme),
|
||||
quickChatCommand,
|
||||
configChatCommand,
|
||||
],
|
||||
[router.push, resolvedTheme, setTheme, quickChatCommand],
|
||||
[router.push, resolvedTheme, setTheme, quickChatCommand, configChatCommand],
|
||||
);
|
||||
|
||||
useRegisterCommands(commands);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"use client";
|
||||
|
||||
import { memo, useCallback, useRef, useState } from "react";
|
||||
import { memo, useCallback, useEffect, 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";
|
||||
@@ -14,13 +14,22 @@ import { ClarificationInputOverlay } from "@/components/task/chat/clarification-
|
||||
|
||||
type QuickChatContentProps = {
|
||||
sessionId: string;
|
||||
minimalToolbar?: boolean;
|
||||
placeholderOverride?: string;
|
||||
initialPrompt?: string;
|
||||
onInitialPromptSent?: () => void;
|
||||
};
|
||||
|
||||
export const QuickChatContent = memo(function QuickChatContent({
|
||||
sessionId,
|
||||
minimalToolbar,
|
||||
placeholderOverride,
|
||||
initialPrompt,
|
||||
onInitialPromptSent,
|
||||
}: QuickChatContentProps) {
|
||||
const chatInputRef = useRef<ChatInputContainerHandle>(null);
|
||||
const [clarificationKey, setClarificationKey] = useState(0);
|
||||
const initialPromptSent = useRef(false);
|
||||
|
||||
useSettingsData(true);
|
||||
const panelState = useChatPanelState({
|
||||
@@ -45,6 +54,16 @@ export const QuickChatContent = memo(function QuickChatContent({
|
||||
} = panelState;
|
||||
const { handleCancelTurn } = useChatPanelHandlers(resolvedSessionId, cancelQueue, chatInputRef);
|
||||
|
||||
// Auto-send the initial prompt once the session is ready (has taskId).
|
||||
// This is used by config chat which creates the session first, then sends
|
||||
// the user's prompt through normal WS message flow.
|
||||
useEffect(() => {
|
||||
if (!initialPrompt || !taskId || initialPromptSent.current) return;
|
||||
initialPromptSent.current = true;
|
||||
handleSubmit(initialPrompt);
|
||||
onInitialPromptSent?.();
|
||||
}, [initialPrompt, taskId, handleSubmit, onInitialPromptSent]);
|
||||
|
||||
const handleClarificationResolved = useCallback(() => setClarificationKey((k) => k + 1), []);
|
||||
|
||||
return (
|
||||
@@ -84,6 +103,8 @@ export const QuickChatContent = memo(function QuickChatContent({
|
||||
panelState={panelState}
|
||||
isSending={isSending}
|
||||
hideSessionsDropdown={true}
|
||||
minimalToolbar={minimalToolbar}
|
||||
placeholderOverride={placeholderOverride}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -4,8 +4,8 @@ import { IconArrowLeft } from "@tabler/icons-react";
|
||||
import { usePathname } from "next/navigation";
|
||||
import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList } from "@kandev/ui/breadcrumb";
|
||||
import { SidebarInset, SidebarProvider, SidebarTrigger } from "@kandev/ui/sidebar";
|
||||
import { SettingsAppSidebar } from "@/components/settings/settings-app-sidebar";
|
||||
import { TooltipProvider } from "@kandev/ui/tooltip";
|
||||
import { SettingsAppSidebar } from "@/components/settings/settings-app-sidebar";
|
||||
|
||||
export function SettingsLayoutClient({ children }: { children: React.ReactNode }) {
|
||||
const pathname = usePathname();
|
||||
|
||||
@@ -325,6 +325,8 @@ type ChatInputAreaProps = {
|
||||
panelState: ReturnType<typeof useChatPanelState>;
|
||||
isSending: boolean;
|
||||
hideSessionsDropdown?: boolean;
|
||||
minimalToolbar?: boolean;
|
||||
placeholderOverride?: string;
|
||||
};
|
||||
|
||||
export function ChatInputArea({
|
||||
@@ -338,6 +340,8 @@ export function ChatInputArea({
|
||||
panelState,
|
||||
isSending,
|
||||
hideSessionsDropdown,
|
||||
minimalToolbar,
|
||||
placeholderOverride,
|
||||
}: ChatInputAreaProps) {
|
||||
const {
|
||||
resolvedSessionId,
|
||||
@@ -369,13 +373,15 @@ export function ChatInputArea({
|
||||
);
|
||||
|
||||
const hasClarification = !!panelState.pendingClarification;
|
||||
const placeholder = resolveInputPlaceholder(
|
||||
isAgentBusy,
|
||||
activeDocument?.type,
|
||||
planModeEnabled,
|
||||
hasClarification,
|
||||
needsRecovery,
|
||||
);
|
||||
const placeholder =
|
||||
placeholderOverride ??
|
||||
resolveInputPlaceholder(
|
||||
isAgentBusy,
|
||||
activeDocument?.type,
|
||||
planModeEnabled,
|
||||
hasClarification,
|
||||
needsRecovery,
|
||||
);
|
||||
return (
|
||||
<div className="bg-card flex-shrink-0 px-2 pb-2 pt-1">
|
||||
<SessionStatusBar todoItems={todoItems} />
|
||||
@@ -416,6 +422,7 @@ export function ChatInputArea({
|
||||
onAddContextFile={handleAddContextFile}
|
||||
onImplementPlan={handleImplementPlan}
|
||||
hideSessionsDropdown={hideSessionsDropdown}
|
||||
minimalToolbar={minimalToolbar}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -34,6 +34,7 @@ export type ChatInputEditorAreaProps = {
|
||||
fileInputRef: React.RefObject<HTMLInputElement | null>;
|
||||
showRequestChangesTooltip: boolean;
|
||||
hideSessionsDropdown?: boolean;
|
||||
minimalToolbar?: boolean;
|
||||
isAgentBusy: boolean;
|
||||
onPlanModeChange: (enabled: boolean) => void;
|
||||
taskTitle?: string;
|
||||
@@ -109,44 +110,16 @@ function FileInput({
|
||||
);
|
||||
}
|
||||
|
||||
export function ChatInputEditorArea({
|
||||
inputRef,
|
||||
value,
|
||||
handleChange,
|
||||
handleSubmitWithReset,
|
||||
inputPlaceholder,
|
||||
isDisabled,
|
||||
hasClarification,
|
||||
planModeEnabled,
|
||||
planModeAvailable,
|
||||
mcpServers,
|
||||
submitKey,
|
||||
setIsInputFocused,
|
||||
sessionId,
|
||||
taskId,
|
||||
onAddContextFile,
|
||||
onToggleContextFile,
|
||||
planContextEnabled,
|
||||
handleAgentCommand,
|
||||
addFiles,
|
||||
fileInputRef,
|
||||
showRequestChangesTooltip,
|
||||
isAgentBusy,
|
||||
onPlanModeChange,
|
||||
taskTitle,
|
||||
taskDescription,
|
||||
isSending,
|
||||
onCancel,
|
||||
contextCount,
|
||||
contextPopoverOpen,
|
||||
setContextPopoverOpen,
|
||||
contextFiles,
|
||||
onImplementPlan,
|
||||
onEnhancePrompt,
|
||||
isEnhancingPrompt,
|
||||
isUtilityConfigured,
|
||||
hideSessionsDropdown,
|
||||
}: ChatInputEditorAreaProps) {
|
||||
export function ChatInputEditorArea(p: ChatInputEditorAreaProps) {
|
||||
const { inputRef, value, handleChange, handleSubmitWithReset, inputPlaceholder } = p;
|
||||
const { isDisabled, hasClarification, planModeEnabled, planModeAvailable, mcpServers } = p;
|
||||
const { submitKey, setIsInputFocused, sessionId, taskId, planContextEnabled } = p;
|
||||
const { onAddContextFile, onToggleContextFile, handleAgentCommand, addFiles, fileInputRef } = p;
|
||||
const { showRequestChangesTooltip, isAgentBusy, onPlanModeChange, taskTitle, taskDescription } =
|
||||
p;
|
||||
const { isSending, onCancel, contextCount, contextPopoverOpen, setContextPopoverOpen } = p;
|
||||
const { contextFiles, onImplementPlan, onEnhancePrompt, isEnhancingPrompt } = p;
|
||||
const { isUtilityConfigured, hideSessionsDropdown, minimalToolbar } = p;
|
||||
// Block submit while enhancing prompt, but keep editor editable for programmatic updates
|
||||
const wrappedSubmit = isEnhancingPrompt ? () => {} : handleSubmitWithReset;
|
||||
const handleAttachFiles = useCallback(() => fileInputRef.current?.click(), [fileInputRef]);
|
||||
@@ -205,6 +178,7 @@ export function ChatInputEditorArea({
|
||||
isUtilityConfigured={isUtilityConfigured}
|
||||
onAttachFiles={handleAttachFiles}
|
||||
hideSessionsDropdown={hideSessionsDropdown}
|
||||
minimalToolbar={minimalToolbar}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -74,6 +74,7 @@ type ChatInputContainerProps = {
|
||||
onAddContextFile?: (file: ContextFile) => void;
|
||||
onImplementPlan?: () => void;
|
||||
hideSessionsDropdown?: boolean;
|
||||
minimalToolbar?: boolean;
|
||||
};
|
||||
|
||||
function FailedSessionBanner({
|
||||
@@ -184,6 +185,7 @@ function buildEditorAreaProps(
|
||||
isEnhancingPrompt: extras.isEnhancingPrompt,
|
||||
isUtilityConfigured: extras.isUtilityConfigured,
|
||||
hideSessionsDropdown: p.hideSessionsDropdown,
|
||||
minimalToolbar: p.minimalToolbar,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -70,6 +70,8 @@ export type ChatInputToolbarProps = {
|
||||
onAttachFiles?: () => void;
|
||||
/** Hide the sessions dropdown (for quick chat) */
|
||||
hideSessionsDropdown?: boolean;
|
||||
/** When true, only render the submit/cancel button — no other controls */
|
||||
minimalToolbar?: boolean;
|
||||
};
|
||||
|
||||
type SubmitButtonProps = {
|
||||
@@ -407,52 +409,78 @@ function AttachFilesButton({ onClick }: { onClick: () => void }) {
|
||||
);
|
||||
}
|
||||
|
||||
export const ChatInputToolbar = memo(function ChatInputToolbar({
|
||||
planModeEnabled,
|
||||
planModeAvailable = true,
|
||||
mcpServers = [],
|
||||
onPlanModeChange,
|
||||
sessionId,
|
||||
taskId,
|
||||
taskTitle,
|
||||
taskDescription,
|
||||
function MinimalToolbar({
|
||||
isAgentBusy,
|
||||
isDisabled,
|
||||
isSending,
|
||||
onCancel,
|
||||
onSubmit,
|
||||
submitKey = "cmd_enter",
|
||||
contextCount = 0,
|
||||
contextPopoverOpen = false,
|
||||
onContextPopoverOpenChange,
|
||||
planContextEnabled = false,
|
||||
contextFiles = [],
|
||||
onToggleFile,
|
||||
onImplementPlan,
|
||||
onEnhancePrompt,
|
||||
isEnhancingPrompt = false,
|
||||
isUtilityConfigured = false,
|
||||
onAttachFiles,
|
||||
hideSessionsDropdown,
|
||||
}: ChatInputToolbarProps) {
|
||||
}: Pick<
|
||||
ChatInputToolbarProps,
|
||||
"isAgentBusy" | "isDisabled" | "isSending" | "onCancel" | "onSubmit" | "submitKey"
|
||||
>) {
|
||||
const submitShortcut = submitKey === "enter" ? SHORTCUTS.SUBMIT_ENTER : SHORTCUTS.SUBMIT;
|
||||
return (
|
||||
<div className="flex items-center justify-end gap-1 px-1 pt-0 pb-0.5 border-t border-border">
|
||||
<SubmitButton
|
||||
isAgentBusy={isAgentBusy}
|
||||
isDisabled={isDisabled}
|
||||
isSending={isSending}
|
||||
planModeEnabled={false}
|
||||
onCancel={onCancel}
|
||||
onSubmit={onSubmit}
|
||||
submitShortcut={submitShortcut}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const toolbarDefaults = {
|
||||
planModeAvailable: true,
|
||||
mcpServers: [] as string[],
|
||||
submitKey: "cmd_enter" as const,
|
||||
contextCount: 0,
|
||||
contextPopoverOpen: false,
|
||||
planContextEnabled: false,
|
||||
contextFiles: [] as ContextFile[],
|
||||
isEnhancingPrompt: false,
|
||||
isUtilityConfigured: false,
|
||||
};
|
||||
|
||||
export const ChatInputToolbar = memo(function ChatInputToolbar(rawProps: ChatInputToolbarProps) {
|
||||
const props = { ...toolbarDefaults, ...rawProps };
|
||||
const submitShortcut = props.submitKey === "enter" ? SHORTCUTS.SUBMIT_ENTER : SHORTCUTS.SUBMIT;
|
||||
|
||||
if (props.minimalToolbar) {
|
||||
return (
|
||||
<MinimalToolbar
|
||||
isAgentBusy={props.isAgentBusy}
|
||||
isDisabled={props.isDisabled}
|
||||
isSending={props.isSending}
|
||||
onCancel={props.onCancel}
|
||||
onSubmit={props.onSubmit}
|
||||
submitKey={props.submitKey}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1 px-1 pt-0 pb-0.5 border-t border-border">
|
||||
<div className="flex items-center gap-0.5">
|
||||
<PlanToggleButton
|
||||
planModeEnabled={planModeEnabled}
|
||||
planModeAvailable={planModeAvailable}
|
||||
onPlanModeChange={onPlanModeChange}
|
||||
planModeEnabled={props.planModeEnabled}
|
||||
planModeAvailable={props.planModeAvailable}
|
||||
onPlanModeChange={props.onPlanModeChange}
|
||||
/>
|
||||
|
||||
<McpIndicator mcpServers={mcpServers} />
|
||||
<McpIndicator mcpServers={props.mcpServers} />
|
||||
|
||||
{onAttachFiles && <AttachFilesButton onClick={onAttachFiles} />}
|
||||
{props.onAttachFiles && <AttachFilesButton onClick={props.onAttachFiles} />}
|
||||
|
||||
<ContextPopover
|
||||
open={contextPopoverOpen}
|
||||
onOpenChange={onContextPopoverOpenChange ?? (() => {})}
|
||||
open={props.contextPopoverOpen}
|
||||
onOpenChange={props.onContextPopoverOpenChange ?? (() => {})}
|
||||
trigger={
|
||||
<Button
|
||||
type="button"
|
||||
@@ -461,40 +489,39 @@ export const ChatInputToolbar = memo(function ChatInputToolbar({
|
||||
className="h-7 gap-1.5 px-2 cursor-pointer hover:bg-muted/40 relative"
|
||||
>
|
||||
<IconAt className="h-4 w-4" />
|
||||
{contextCount > 0 && (
|
||||
{props.contextCount > 0 && (
|
||||
<span className="absolute -top-1 -right-1 h-4 min-w-4 rounded-full bg-muted-foreground/80 text-[10px] text-background flex items-center justify-center px-0.5">
|
||||
{contextCount}
|
||||
{props.contextCount}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
}
|
||||
sessionId={sessionId}
|
||||
planContextEnabled={planContextEnabled}
|
||||
contextFiles={contextFiles}
|
||||
onToggleFile={onToggleFile ?? (() => {})}
|
||||
sessionId={props.sessionId}
|
||||
planContextEnabled={props.planContextEnabled}
|
||||
contextFiles={props.contextFiles}
|
||||
onToggleFile={props.onToggleFile ?? (() => {})}
|
||||
/>
|
||||
<ModeSelector sessionId={sessionId} />
|
||||
<ModeSelector sessionId={props.sessionId} />
|
||||
</div>
|
||||
|
||||
<div className="flex-1" />
|
||||
|
||||
<ToolbarRightSection
|
||||
taskId={taskId}
|
||||
sessionId={sessionId}
|
||||
taskTitle={taskTitle}
|
||||
taskDescription={taskDescription}
|
||||
planModeEnabled={planModeEnabled}
|
||||
isAgentBusy={isAgentBusy}
|
||||
isDisabled={isDisabled}
|
||||
isSending={isSending}
|
||||
onCancel={onCancel}
|
||||
onSubmit={onSubmit}
|
||||
taskId={props.taskId}
|
||||
sessionId={props.sessionId}
|
||||
taskTitle={props.taskTitle}
|
||||
taskDescription={props.taskDescription}
|
||||
planModeEnabled={props.planModeEnabled}
|
||||
isAgentBusy={props.isAgentBusy}
|
||||
isDisabled={props.isDisabled}
|
||||
isSending={props.isSending}
|
||||
onCancel={props.onCancel}
|
||||
onSubmit={props.onSubmit}
|
||||
submitShortcut={submitShortcut}
|
||||
onEnhancePrompt={onEnhancePrompt}
|
||||
isEnhancingPrompt={isEnhancingPrompt}
|
||||
isUtilityConfigured={isUtilityConfigured}
|
||||
onImplementPlan={onImplementPlan}
|
||||
hideSessionsDropdown={hideSessionsDropdown}
|
||||
onEnhancePrompt={props.onEnhancePrompt}
|
||||
isEnhancingPrompt={props.isEnhancingPrompt}
|
||||
isUtilityConfigured={props.isUtilityConfigured}
|
||||
onImplementPlan={props.onImplementPlan}
|
||||
hideSessionsDropdown={props.hideSessionsDropdown}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -193,7 +193,7 @@ export const backendFixture = base.extend<object, { backend: BackendContext }>({
|
||||
KANDEV_WORKTREE_ENABLED: "false",
|
||||
KANDEV_WORKTREE_BASEPATH: worktreeBase,
|
||||
KANDEV_REPOCLONE_BASEPATH: repoCloneBase,
|
||||
KANDEV_LOG_LEVEL: "warn",
|
||||
KANDEV_LOG_LEVEL: process.env.KANDEV_LOG_LEVEL ?? "warn",
|
||||
AGENTCTL_INSTANCE_PORT_BASE: String(agentctlPortBase),
|
||||
AGENTCTL_INSTANCE_PORT_MAX: String(agentctlPortMax),
|
||||
GIT_AUTHOR_NAME: "E2E Test",
|
||||
|
||||
@@ -177,6 +177,7 @@ export class ApiClient {
|
||||
workflow_step_id?: string;
|
||||
repository_ids?: string[];
|
||||
executor_id?: string;
|
||||
metadata?: Record<string, unknown>;
|
||||
},
|
||||
): Promise<CreateTaskResponse> {
|
||||
return this.request("POST", "/api/v1/tasks", {
|
||||
@@ -191,6 +192,19 @@ export class ApiClient {
|
||||
? { repositories: opts.repository_ids.map((id) => ({ repository_id: id })) }
|
||||
: {}),
|
||||
...(opts?.executor_id ? { executor_id: opts.executor_id } : {}),
|
||||
...(opts?.metadata ? { metadata: opts.metadata } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
/** Start a config chat session via the dedicated config-chat endpoint. */
|
||||
async startConfigChat(
|
||||
workspaceId: string,
|
||||
agentProfileId: string,
|
||||
prompt: string,
|
||||
): Promise<{ task_id: string; session_id: string }> {
|
||||
return this.request("POST", `/api/v1/workspaces/${workspaceId}/config-chat`, {
|
||||
agent_profile_id: agentProfileId,
|
||||
prompt,
|
||||
});
|
||||
}
|
||||
|
||||
@@ -247,11 +261,36 @@ export class ApiClient {
|
||||
|
||||
async updateWorkspace(
|
||||
workspaceId: string,
|
||||
updates: { default_executor_id?: string },
|
||||
updates: {
|
||||
default_executor_id?: string;
|
||||
default_agent_profile_id?: string;
|
||||
default_config_agent_profile_id?: string;
|
||||
},
|
||||
): Promise<void> {
|
||||
await this.request("PATCH", `/api/v1/workspaces/${workspaceId}`, updates);
|
||||
}
|
||||
|
||||
async deleteExecutor(executorId: string): Promise<void> {
|
||||
await this.request("DELETE", `/api/v1/executors/${executorId}`);
|
||||
}
|
||||
|
||||
async createExecutorProfile(
|
||||
executorId: string,
|
||||
name: string,
|
||||
opts?: { mcp_policy?: string; prepare_script?: string; cleanup_script?: string },
|
||||
): Promise<{ id: string; name: string }> {
|
||||
return this.request("POST", `/api/v1/executors/${executorId}/profiles`, {
|
||||
name,
|
||||
...(opts?.mcp_policy ? { mcp_policy: opts.mcp_policy } : {}),
|
||||
...(opts?.prepare_script ? { prepare_script: opts.prepare_script } : {}),
|
||||
...(opts?.cleanup_script ? { cleanup_script: opts.cleanup_script } : {}),
|
||||
});
|
||||
}
|
||||
|
||||
async deleteExecutorProfile(profileId: string): Promise<void> {
|
||||
await this.request("DELETE", `/api/v1/executor-profiles/${profileId}`);
|
||||
}
|
||||
|
||||
async listExecutors(): Promise<{
|
||||
executors: Array<{
|
||||
id: string;
|
||||
@@ -314,6 +353,20 @@ export class ApiClient {
|
||||
return this.request("GET", "/api/v1/workflow/templates");
|
||||
}
|
||||
|
||||
async deleteTask(taskId: string): Promise<void> {
|
||||
await this.request("DELETE", `/api/v1/tasks/${taskId}`);
|
||||
}
|
||||
|
||||
async archiveTask(taskId: string): Promise<void> {
|
||||
await this.request("POST", `/api/v1/tasks/${taskId}/archive`);
|
||||
}
|
||||
|
||||
async getAgentProfileMcpConfig(
|
||||
profileId: string,
|
||||
): Promise<{ profile_id: string; enabled: boolean; servers: Record<string, unknown> }> {
|
||||
return this.request("GET", `/api/v1/agent-profiles/${profileId}/mcp-config`);
|
||||
}
|
||||
|
||||
// --- E2E Test Reset ---
|
||||
|
||||
async e2eReset(workspaceId: string, keepWorkflowIds?: string[]): Promise<void> {
|
||||
@@ -452,6 +505,12 @@ export class ApiClient {
|
||||
async listSessionMessages(
|
||||
sessionId: string,
|
||||
): Promise<{ messages: Array<{ id: string; content: string; author_type: string }> }> {
|
||||
return this.request("GET", `/api/v1/sessions/${sessionId}/messages`);
|
||||
return this.request("GET", `/api/v1/task-sessions/${sessionId}/messages`);
|
||||
}
|
||||
|
||||
async listTasks(
|
||||
workspaceId: string,
|
||||
): Promise<{ tasks: Array<{ id: string; title: string; workflow_step_id?: string }> }> {
|
||||
return this.request("GET", `/api/v1/workspaces/${workspaceId}/tasks`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { test, expect } from "../fixtures/test-base";
|
||||
|
||||
/**
|
||||
* Config chat popover UI tests.
|
||||
*/
|
||||
|
||||
test.describe("Config chat popover", () => {
|
||||
test("opens popover, sends prompt, and shows agent response", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
// Set the mock agent profile as the default config chat profile.
|
||||
await apiClient.updateWorkspace(seedData.workspaceId, {
|
||||
default_config_agent_profile_id: seedData.agentProfileId,
|
||||
});
|
||||
|
||||
// Navigate to settings page.
|
||||
await testPage.goto("/settings/agents");
|
||||
await testPage.waitForLoadState("networkidle");
|
||||
|
||||
// Open the config chat popover.
|
||||
const fab = testPage.getByRole("button", { name: "Configuration Chat" });
|
||||
await expect(fab).toBeVisible({ timeout: 10_000 });
|
||||
await fab.click();
|
||||
|
||||
const popover = testPage.locator("[data-radix-popper-content-wrapper]");
|
||||
await expect(popover).toBeVisible({ timeout: 5_000 });
|
||||
|
||||
// Select profile if needed (appears when no default is set).
|
||||
const profileCard = popover.getByText("Mock Default", { exact: false });
|
||||
const textarea = popover.locator("textarea");
|
||||
if (await profileCard.isVisible()) {
|
||||
await profileCard.click();
|
||||
await expect(textarea).toBeVisible({ timeout: 5_000 });
|
||||
}
|
||||
|
||||
// Submit prompt.
|
||||
await textarea.fill("Show me the current configuration");
|
||||
await textarea.press("Enter");
|
||||
|
||||
// Wait for the tab to appear (means session was created).
|
||||
// Use the tab bar specifically to avoid matching message text.
|
||||
const tabBar = popover.locator(".scrollbar-hide");
|
||||
await expect(tabBar.getByText("Show me the cu", { exact: false })).toBeVisible({
|
||||
timeout: 15_000,
|
||||
});
|
||||
|
||||
// Wait for the agent response to appear in the chat area.
|
||||
const chatArea = popover.locator(".chat-message-list");
|
||||
await expect(chatArea.getByText("completed the analysis", { exact: false })).toBeVisible({
|
||||
timeout: 30_000,
|
||||
});
|
||||
});
|
||||
|
||||
test("opens config chat via command panel (Cmd+K)", async ({ testPage, apiClient, seedData }) => {
|
||||
// Set the mock agent profile as the default config chat profile.
|
||||
await apiClient.updateWorkspace(seedData.workspaceId, {
|
||||
default_config_agent_profile_id: seedData.agentProfileId,
|
||||
});
|
||||
|
||||
// Navigate to the kanban page (not settings) — FAB is hidden here,
|
||||
// but the command panel should still open config chat globally.
|
||||
await testPage.goto("/");
|
||||
await testPage.waitForLoadState("networkidle");
|
||||
|
||||
// Open the command panel via Cmd+K.
|
||||
const modifier = process.platform === "darwin" ? "Meta" : "Control";
|
||||
await testPage.keyboard.press(`${modifier}+k`);
|
||||
|
||||
const cmdPanel = testPage.getByRole("dialog", { name: "Command Palette" });
|
||||
await expect(cmdPanel).toBeVisible({ timeout: 5_000 });
|
||||
|
||||
// Type to find the config chat command.
|
||||
await cmdPanel.locator("input").fill("Configuration Chat");
|
||||
await expect(cmdPanel.getByText("Configuration Chat")).toBeVisible({ timeout: 5_000 });
|
||||
|
||||
// Select the command.
|
||||
await testPage.keyboard.press("Enter");
|
||||
|
||||
// Command panel should close and config chat popover should open.
|
||||
await expect(cmdPanel).not.toBeVisible({ timeout: 3_000 });
|
||||
const popover = testPage.locator("[data-radix-popper-content-wrapper]");
|
||||
await expect(popover).toBeVisible({ timeout: 5_000 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,657 @@
|
||||
import { test, expect } from "../fixtures/test-base";
|
||||
import { SessionPage } from "../pages/session-page";
|
||||
import type { ApiClient } from "../helpers/api-client";
|
||||
import type { SeedData } from "../fixtures/test-base";
|
||||
|
||||
/**
|
||||
* Config management via the dedicated config-chat endpoint.
|
||||
*
|
||||
* These tests verify the config-mode MCP flow: config chat sessions are
|
||||
* created via POST /workspaces/:id/config-chat, which sets config_mode: true
|
||||
* in session metadata. The agent then receives config-mode MCP tools
|
||||
* (workflow, agent, and MCP management) that are NOT available in regular
|
||||
* task sessions.
|
||||
*
|
||||
* The mock agent uses `e2e:mcp:kandev:<tool>(<json_args>)` script commands
|
||||
* to call real MCP tools through the agentctl MCP server.
|
||||
*/
|
||||
|
||||
/** Creates a config chat session via the dedicated config-chat endpoint. */
|
||||
function startConfigSession(apiClient: ApiClient, seedData: SeedData, prompt: string) {
|
||||
return apiClient.startConfigChat(seedData.workspaceId, seedData.agentProfileId, prompt);
|
||||
}
|
||||
|
||||
/** Navigate to session page and wait for the final marker message. */
|
||||
async function runAndWait(
|
||||
testPage: import("@playwright/test").Page,
|
||||
sessionId: string,
|
||||
marker: string,
|
||||
) {
|
||||
await testPage.goto(`/s/${sessionId}`);
|
||||
const page = new SessionPage(testPage);
|
||||
await page.waitForLoad();
|
||||
await expect(page.chat.getByText(marker, { exact: true })).toBeVisible({ timeout: 30_000 });
|
||||
return page;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Workflow management
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test.describe("Config-mode MCP — workflow management", () => {
|
||||
test("agent can list workspaces and workflows", async ({ testPage, apiClient, seedData }) => {
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Listing workspaces...")',
|
||||
"e2e:mcp:kandev:list_workspaces({})",
|
||||
`e2e:mcp:kandev:list_workflows({"workspace_id":"${seedData.workspaceId}"})`,
|
||||
'e2e:message("Done listing")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
const page = await runAndWait(testPage, session.session_id, "Done listing");
|
||||
await expect(page.chat.getByText("list_workspaces")).toBeVisible({ timeout: 10_000 });
|
||||
await expect(page.chat.getByText("list_workflows")).toBeVisible({ timeout: 10_000 });
|
||||
});
|
||||
|
||||
test("agent can create and list workflow steps", async ({ testPage, apiClient, seedData }) => {
|
||||
const workflow = await apiClient.createWorkflow(seedData.workspaceId, "Step CRUD Workflow");
|
||||
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Creating step...")',
|
||||
`e2e:mcp:kandev:create_workflow_step({"workflow_id":"${workflow.id}","name":"QA Review","position":0})`,
|
||||
`e2e:mcp:kandev:list_workflow_steps({"workflow_id":"${workflow.id}"})`,
|
||||
'e2e:message("Steps listed")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await runAndWait(testPage, session.session_id, "Steps listed");
|
||||
|
||||
// Verify via API
|
||||
const { steps } = await apiClient.listWorkflowSteps(workflow.id);
|
||||
const qaStep = steps.find((s) => s.name === "QA Review");
|
||||
expect(qaStep).toBeTruthy();
|
||||
});
|
||||
|
||||
test("agent can create a step with all optional fields", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
const workflow = await apiClient.createWorkflow(seedData.workspaceId, "Full Fields Workflow");
|
||||
|
||||
const createArgs = JSON.stringify({
|
||||
workflow_id: workflow.id,
|
||||
name: "Deploy",
|
||||
position: 0,
|
||||
color: "#22c55e",
|
||||
prompt: "Deploy to production",
|
||||
is_start_step: true,
|
||||
allow_manual_move: true,
|
||||
show_in_command_panel: true,
|
||||
events: {
|
||||
on_enter: [{ type: "auto_start_agent" }],
|
||||
},
|
||||
});
|
||||
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Creating step with all fields...")',
|
||||
`e2e:mcp:kandev:create_workflow_step(${createArgs})`,
|
||||
'e2e:message("Step created")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await runAndWait(testPage, session.session_id, "Step created");
|
||||
|
||||
// Verify all fields via API
|
||||
const { steps } = await apiClient.listWorkflowSteps(workflow.id);
|
||||
const deploy = steps.find((s) => s.name === "Deploy");
|
||||
expect(deploy).toBeTruthy();
|
||||
expect(deploy!.color).toBe("#22c55e");
|
||||
expect(deploy!.prompt).toBe("Deploy to production");
|
||||
expect(deploy!.is_start_step).toBe(true);
|
||||
expect(deploy!.allow_manual_move).toBe(true);
|
||||
expect(deploy!.show_in_command_panel).toBe(true);
|
||||
expect(deploy!.events?.on_enter).toEqual([{ type: "auto_start_agent" }]);
|
||||
});
|
||||
|
||||
test("agent can create a workflow", async ({ testPage, apiClient, seedData }) => {
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Creating workflow...")',
|
||||
`e2e:mcp:kandev:create_workflow({"workspace_id":"${seedData.workspaceId}","name":"E2E Workflow","description":"Created by E2E test"})`,
|
||||
'e2e:message("Workflow created")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await runAndWait(testPage, session.session_id, "Workflow created");
|
||||
|
||||
// Verify workflow was created via API
|
||||
const { workflows } = await apiClient.listWorkflows(seedData.workspaceId);
|
||||
const created = workflows.find((w) => w.name === "E2E Workflow");
|
||||
expect(created).toBeTruthy();
|
||||
expect(created!.description).toBe("Created by E2E test");
|
||||
});
|
||||
|
||||
test("agent can update a workflow", async ({ testPage, apiClient, seedData }) => {
|
||||
const workflow = await apiClient.createWorkflow(seedData.workspaceId, "Before Update");
|
||||
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Updating workflow...")',
|
||||
`e2e:mcp:kandev:update_workflow({"workflow_id":"${workflow.id}","name":"After Update","description":"Updated description"})`,
|
||||
'e2e:message("Workflow updated")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await runAndWait(testPage, session.session_id, "Workflow updated");
|
||||
|
||||
// Verify via API
|
||||
const { workflows } = await apiClient.listWorkflows(seedData.workspaceId);
|
||||
const updated = workflows.find((w) => w.id === workflow.id);
|
||||
expect(updated?.name).toBe("After Update");
|
||||
expect(updated?.description).toBe("Updated description");
|
||||
});
|
||||
|
||||
test("agent can delete a workflow", async ({ testPage, apiClient, seedData }) => {
|
||||
const workflow = await apiClient.createWorkflow(seedData.workspaceId, "Deletable Workflow");
|
||||
// Create a bumper workflow so the config-chat session (which picks the newest
|
||||
// workflow via ORDER BY created_at DESC) doesn't land on the deletable one.
|
||||
// Otherwise ON DELETE CASCADE would wipe the config task/session mid-run.
|
||||
await apiClient.createWorkflow(seedData.workspaceId, "Config Anchor");
|
||||
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Deleting workflow...")',
|
||||
`e2e:mcp:kandev:delete_workflow({"workflow_id":"${workflow.id}"})`,
|
||||
'e2e:message("Workflow deleted")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await runAndWait(testPage, session.session_id, "Workflow deleted");
|
||||
|
||||
// Verify workflow was deleted via API
|
||||
const { workflows } = await apiClient.listWorkflows(seedData.workspaceId);
|
||||
expect(workflows.find((w) => w.id === workflow.id)).toBeUndefined();
|
||||
});
|
||||
|
||||
test("agent can update a workflow step", async ({ testPage, apiClient, seedData }) => {
|
||||
const workflow = await apiClient.createWorkflow(seedData.workspaceId, "Update Step Workflow");
|
||||
const step = await apiClient.createWorkflowStep(workflow.id, "Draft", 0);
|
||||
|
||||
const updateArgs = JSON.stringify({
|
||||
step_id: step.id,
|
||||
name: "In Review",
|
||||
color: "#3b82f6",
|
||||
allow_manual_move: true,
|
||||
show_in_command_panel: true,
|
||||
auto_archive_after_hours: 48,
|
||||
events: {
|
||||
on_enter: [{ type: "enable_plan_mode" }],
|
||||
on_turn_complete: [{ type: "move_to_next" }],
|
||||
},
|
||||
});
|
||||
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Updating step...")',
|
||||
`e2e:mcp:kandev:update_workflow_step(${updateArgs})`,
|
||||
'e2e:message("Step updated")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await runAndWait(testPage, session.session_id, "Step updated");
|
||||
|
||||
// Verify via API
|
||||
const { steps } = await apiClient.listWorkflowSteps(workflow.id);
|
||||
const updated = steps.find((s) => s.id === step.id);
|
||||
expect(updated?.name).toBe("In Review");
|
||||
expect(updated?.color).toBe("#3b82f6");
|
||||
expect(updated?.allow_manual_move).toBe(true);
|
||||
expect(updated?.show_in_command_panel).toBe(true);
|
||||
expect(updated?.auto_archive_after_hours).toBe(48);
|
||||
expect(updated?.events?.on_enter).toEqual([{ type: "enable_plan_mode" }]);
|
||||
expect(updated?.events?.on_turn_complete).toEqual([{ type: "move_to_next" }]);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Agent management
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test.describe("Config-mode MCP — agent management", () => {
|
||||
test("agent can list agents and profiles", async ({ testPage, apiClient, seedData }) => {
|
||||
const { agents } = await apiClient.listAgents();
|
||||
const agent = agents[0];
|
||||
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Listing agents...")',
|
||||
"e2e:mcp:kandev:list_agents({})",
|
||||
`e2e:mcp:kandev:list_agent_profiles({"agent_id":"${agent.id}"})`,
|
||||
'e2e:message("Agents listed")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
const page = await runAndWait(testPage, session.session_id, "Agents listed");
|
||||
await expect(page.chat.getByText("list_agents")).toBeVisible({ timeout: 10_000 });
|
||||
await expect(page.chat.getByText("list_agent_profiles")).toBeVisible({ timeout: 10_000 });
|
||||
});
|
||||
|
||||
test("agent can create and delete an agent profile", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
const { agents } = await apiClient.listAgents();
|
||||
const agent = agents[0];
|
||||
const initialProfileCount = (agent.profiles ?? []).length;
|
||||
|
||||
// Create a new profile via MCP tool
|
||||
const createSession = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Creating profile...")',
|
||||
`e2e:mcp:kandev:create_agent_profile({"agent_id":"${agent.id}","name":"E2E Created Profile","model":"claude-sonnet-4-5-20250514"})`,
|
||||
'e2e:message("Profile created")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await runAndWait(testPage, createSession.session_id, "Profile created");
|
||||
|
||||
// Verify profile was created via API
|
||||
const { agents: afterCreate } = await apiClient.listAgents();
|
||||
const agentAfterCreate = afterCreate.find((a) => a.id === agent.id);
|
||||
const newProfiles = (agentAfterCreate?.profiles ?? []).filter(
|
||||
(p) => p.name === "E2E Created Profile",
|
||||
);
|
||||
expect(newProfiles.length).toBe(1);
|
||||
expect(newProfiles[0].model).toBe("claude-sonnet-4-5-20250514");
|
||||
|
||||
// Delete the profile via MCP tool
|
||||
const newProfileId = newProfiles[0].id;
|
||||
const deleteSession = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Deleting profile...")',
|
||||
`e2e:mcp:kandev:delete_agent_profile({"profile_id":"${newProfileId}"})`,
|
||||
'e2e:message("Profile deleted")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await runAndWait(testPage, deleteSession.session_id, "Profile deleted");
|
||||
|
||||
// Verify profile was deleted via API
|
||||
const { agents: afterDelete } = await apiClient.listAgents();
|
||||
const agentAfterDelete = afterDelete.find((a) => a.id === agent.id);
|
||||
expect((agentAfterDelete?.profiles ?? []).length).toBe(initialProfileCount);
|
||||
expect((agentAfterDelete?.profiles ?? []).find((p) => p.id === newProfileId)).toBeUndefined();
|
||||
});
|
||||
|
||||
test("agent can update an agent", async ({ testPage, apiClient, seedData }) => {
|
||||
const { agents } = await apiClient.listAgents();
|
||||
const agent = agents[0];
|
||||
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Updating agent...")',
|
||||
`e2e:mcp:kandev:update_agent({"agent_id":"${agent.id}","supports_mcp":true})`,
|
||||
'e2e:message("Agent updated")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await runAndWait(testPage, session.session_id, "Agent updated");
|
||||
|
||||
// Verify via API
|
||||
const { agents: updated } = await apiClient.listAgents();
|
||||
const updatedAgent = updated.find((a) => a.id === agent.id);
|
||||
expect(updatedAgent?.supports_mcp).toBe(true);
|
||||
});
|
||||
|
||||
test("agent can update an agent profile name", async ({ testPage, apiClient, seedData }) => {
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Updating profile...")',
|
||||
`e2e:mcp:kandev:update_agent_profile({"profile_id":"${seedData.agentProfileId}","name":"Renamed Profile"})`,
|
||||
'e2e:message("Profile updated")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await runAndWait(testPage, session.session_id, "Profile updated");
|
||||
|
||||
// Verify via API
|
||||
const { agents } = await apiClient.listAgents();
|
||||
const profile = agents
|
||||
.flatMap((a) => a.profiles ?? [])
|
||||
.find((p) => p.id === seedData.agentProfileId);
|
||||
expect(profile?.name).toBe("Renamed Profile");
|
||||
});
|
||||
|
||||
test("agent can update agent profile model and auto_approve", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Updating profile settings...")',
|
||||
`e2e:mcp:kandev:update_agent_profile({"profile_id":"${seedData.agentProfileId}","model":"claude-sonnet-4-5-20250514","auto_approve":false})`,
|
||||
'e2e:message("Profile settings updated")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await runAndWait(testPage, session.session_id, "Profile settings updated");
|
||||
|
||||
// Verify via API
|
||||
const { agents } = await apiClient.listAgents();
|
||||
const profile = agents
|
||||
.flatMap((a) => a.profiles ?? [])
|
||||
.find((p) => p.id === seedData.agentProfileId);
|
||||
expect(profile?.model).toBe("claude-sonnet-4-5-20250514");
|
||||
expect(profile?.auto_approve).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// MCP server configuration
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test.describe("Config-mode MCP — MCP server configuration", () => {
|
||||
test("agent can get and update MCP config", async ({ testPage, apiClient, seedData }) => {
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Reading MCP config...")',
|
||||
`e2e:mcp:kandev:get_mcp_config({"profile_id":"${seedData.agentProfileId}"})`,
|
||||
`e2e:mcp:kandev:update_mcp_config({"profile_id":"${seedData.agentProfileId}","enabled":true,"servers":{"test-server":{"command":"node","args":["server.js"]}}})`,
|
||||
'e2e:message("MCP config updated")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
const page = await runAndWait(testPage, session.session_id, "MCP config updated");
|
||||
await expect(page.chat.getByText("get_mcp_config")).toBeVisible({ timeout: 10_000 });
|
||||
await expect(page.chat.getByText("update_mcp_config")).toBeVisible({ timeout: 10_000 });
|
||||
|
||||
// Verify via API
|
||||
const config = await apiClient.getAgentProfileMcpConfig(seedData.agentProfileId);
|
||||
expect(config.enabled).toBe(true);
|
||||
expect(config.servers).toHaveProperty("test-server");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Task management
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test.describe("Config-mode MCP — task management", () => {
|
||||
test("agent can list tasks in a workflow", async ({ testPage, apiClient, seedData }) => {
|
||||
// Create a task so there's something to list
|
||||
await apiClient.createTask(seedData.workspaceId, "Listable Task", {
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
});
|
||||
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Listing tasks...")',
|
||||
`e2e:mcp:kandev:list_tasks({"workflow_id":"${seedData.workflowId}"})`,
|
||||
'e2e:message("Tasks listed")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
const page = await runAndWait(testPage, session.session_id, "Tasks listed");
|
||||
await expect(page.chat.getByText("list_tasks").first()).toBeVisible({ timeout: 10_000 });
|
||||
});
|
||||
|
||||
test("agent can move a task to a different step", async ({ testPage, apiClient, seedData }) => {
|
||||
// Find a target step that is NOT the start step
|
||||
const targetStep = seedData.steps.find((s) => s.id !== seedData.startStepId);
|
||||
expect(targetStep).toBeTruthy();
|
||||
|
||||
// Create a task in the start step
|
||||
const task = await apiClient.createTask(seedData.workspaceId, "Movable Task", {
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
});
|
||||
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Moving task...")',
|
||||
`e2e:mcp:kandev:move_task({"task_id":"${task.id}","workflow_id":"${seedData.workflowId}","workflow_step_id":"${targetStep!.id}"})`,
|
||||
'e2e:message("Task moved")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await runAndWait(testPage, session.session_id, "Task moved");
|
||||
|
||||
// Verify the task is now in the target step
|
||||
const { tasks } = await apiClient.listTasks(seedData.workspaceId);
|
||||
const moved = tasks.find((t) => t.id === task.id);
|
||||
expect(moved?.workflow_step_id).toBe(targetStep!.id);
|
||||
});
|
||||
|
||||
test("agent can archive a task", async ({ testPage, apiClient, seedData }) => {
|
||||
const task = await apiClient.createTask(seedData.workspaceId, "Archivable Task", {
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
});
|
||||
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Archiving task...")',
|
||||
`e2e:mcp:kandev:archive_task({"task_id":"${task.id}"})`,
|
||||
'e2e:message("Task archived")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await runAndWait(testPage, session.session_id, "Task archived");
|
||||
|
||||
// Verify the task no longer appears in active task list
|
||||
const { tasks } = await apiClient.listTasks(seedData.workspaceId);
|
||||
expect(tasks.find((t) => t.id === task.id)).toBeUndefined();
|
||||
});
|
||||
|
||||
test("agent can delete a task", async ({ testPage, apiClient, seedData }) => {
|
||||
const task = await apiClient.createTask(seedData.workspaceId, "Deletable Task", {
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
});
|
||||
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Deleting task...")',
|
||||
`e2e:mcp:kandev:delete_task({"task_id":"${task.id}"})`,
|
||||
'e2e:message("Task deleted")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await runAndWait(testPage, session.session_id, "Task deleted");
|
||||
|
||||
// Verify the task is gone
|
||||
const { tasks } = await apiClient.listTasks(seedData.workspaceId);
|
||||
expect(tasks.find((t) => t.id === task.id)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Executor management
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test.describe("Config-mode MCP — executor management", () => {
|
||||
test("agent can list executors", async ({ testPage, apiClient, seedData }) => {
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Listing executors...")',
|
||||
"e2e:mcp:kandev:list_executors({})",
|
||||
'e2e:message("Executors listed")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
const page = await runAndWait(testPage, session.session_id, "Executors listed");
|
||||
await expect(page.chat.getByText("list_executors", { exact: true })).toBeVisible({
|
||||
timeout: 10_000,
|
||||
});
|
||||
});
|
||||
|
||||
test("agent can create and delete an executor profile", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
// Use the system "Local" executor for the profile
|
||||
let { executors } = await apiClient.listExecutors();
|
||||
const executor = executors.find((e) => e.type === "local")!;
|
||||
|
||||
// Create profile via MCP
|
||||
const createSession = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Creating executor profile...")',
|
||||
`e2e:mcp:kandev:create_executor_profile({"executor_id":"${executor.id}","name":"E2E Profile"})`,
|
||||
'e2e:message("Executor profile created")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await runAndWait(testPage, createSession.session_id, "Executor profile created");
|
||||
|
||||
// Verify via API
|
||||
({ executors } = await apiClient.listExecutors());
|
||||
const exec = executors.find((e) => e.id === executor.id);
|
||||
const profile = exec?.profiles?.find((p) => p.name === "E2E Profile");
|
||||
expect(profile).toBeTruthy();
|
||||
|
||||
// Delete profile via MCP
|
||||
const deleteSession = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Deleting executor profile...")',
|
||||
`e2e:mcp:kandev:delete_executor_profile({"profile_id":"${profile!.id}"})`,
|
||||
'e2e:message("Executor profile deleted")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await runAndWait(testPage, deleteSession.session_id, "Executor profile deleted");
|
||||
|
||||
// Verify deleted
|
||||
const { executors: afterDelete } = await apiClient.listExecutors();
|
||||
const execAfter = afterDelete.find((e) => e.id === executor.id);
|
||||
expect(execAfter?.profiles?.find((p) => p.id === profile!.id)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Multi-tool workflows
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test.describe("Config-mode MCP — multi-tool workflow", () => {
|
||||
test("agent executes multiple config tools in sequence", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
const workflow = await apiClient.createWorkflow(seedData.workspaceId, "Multi-Tool Workflow");
|
||||
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Starting multi-tool config...")',
|
||||
"e2e:mcp:kandev:list_workspaces({})",
|
||||
`e2e:mcp:kandev:list_workflows({"workspace_id":"${seedData.workspaceId}"})`,
|
||||
`e2e:mcp:kandev:create_workflow_step({"workflow_id":"${workflow.id}","name":"Agent Created Step","position":0})`,
|
||||
"e2e:mcp:kandev:list_agents({})",
|
||||
'e2e:message("Multi-tool config complete")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await runAndWait(testPage, session.session_id, "Multi-tool config complete");
|
||||
|
||||
// Verify the step was actually created
|
||||
const { steps } = await apiClient.listWorkflowSteps(workflow.id);
|
||||
const createdStep = steps.find((s) => s.name === "Agent Created Step");
|
||||
expect(createdStep).toBeTruthy();
|
||||
});
|
||||
|
||||
test("agent performs full workflow setup with steps, profile, and MCP config", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
const workflow = await apiClient.createWorkflow(seedData.workspaceId, "Full Setup Workflow");
|
||||
const { agents } = await apiClient.listAgents();
|
||||
const agent = agents[0];
|
||||
|
||||
const session = await startConfigSession(
|
||||
apiClient,
|
||||
seedData,
|
||||
[
|
||||
'e2e:message("Setting up full workflow...")',
|
||||
// Create 3 steps
|
||||
`e2e:mcp:kandev:create_workflow_step({"workflow_id":"${workflow.id}","name":"Build","position":0,"color":"#3b82f6"})`,
|
||||
`e2e:mcp:kandev:create_workflow_step({"workflow_id":"${workflow.id}","name":"Test","position":1,"color":"#eab308"})`,
|
||||
`e2e:mcp:kandev:create_workflow_step({"workflow_id":"${workflow.id}","name":"Deploy","position":2,"color":"#22c55e"})`,
|
||||
// Create a new agent profile
|
||||
`e2e:mcp:kandev:create_agent_profile({"agent_id":"${agent.id}","name":"CI Profile","model":"claude-sonnet-4-5-20250514"})`,
|
||||
// Update MCP config on the test profile
|
||||
`e2e:mcp:kandev:update_mcp_config({"profile_id":"${seedData.agentProfileId}","enabled":true,"servers":{"ci-tools":{"command":"npx","args":["-y","@ci/tools"]}}})`,
|
||||
'e2e:message("Full setup complete")',
|
||||
].join("\n"),
|
||||
);
|
||||
|
||||
await runAndWait(testPage, session.session_id, "Full setup complete");
|
||||
|
||||
// Verify steps
|
||||
const { steps } = await apiClient.listWorkflowSteps(workflow.id);
|
||||
expect(steps.length).toBe(3);
|
||||
expect(steps.map((s) => s.name).sort()).toEqual(["Build", "Deploy", "Test"]);
|
||||
|
||||
// Verify new profile was created
|
||||
const { agents: updatedAgents } = await apiClient.listAgents();
|
||||
const updatedAgent = updatedAgents.find((a) => a.id === agent.id);
|
||||
expect((updatedAgent?.profiles ?? []).find((p) => p.name === "CI Profile")).toBeTruthy();
|
||||
|
||||
// Verify MCP config
|
||||
const config = await apiClient.getAgentProfileMcpConfig(seedData.agentProfileId);
|
||||
expect(config.enabled).toBe(true);
|
||||
expect(config.servers).toHaveProperty("ci-tools");
|
||||
});
|
||||
});
|
||||
@@ -15,7 +15,7 @@ type MessageListResponse = { messages: Message[]; has_more?: boolean; cursor?: s
|
||||
const EMPTY_MESSAGES: Message[] = [];
|
||||
const EMPTY_META = { isLoading: false, hasMore: false, oldestCursor: null };
|
||||
|
||||
/** Fetch latest messages via WS and store them. Returns the fetched messages. */
|
||||
/** Fetch latest messages via WS and merge with any that arrived via live notifications. */
|
||||
async function fetchAndStoreMessages(
|
||||
sessionId: string,
|
||||
store: ReturnType<typeof useAppStoreApi>,
|
||||
@@ -29,11 +29,26 @@ async function fetchAndStoreMessages(
|
||||
10000,
|
||||
);
|
||||
const fetched = [...(response.messages ?? [])].reverse();
|
||||
store.getState().setMessages(sessionId, fetched, {
|
||||
|
||||
// Merge: keep WS-delivered messages that aren't in the fetch response.
|
||||
// This prevents a slow fetch (sent before messages existed) from wiping
|
||||
// messages that arrived via real-time notifications while the fetch was
|
||||
// in flight.
|
||||
const existing = store.getState().messages.bySession[sessionId] ?? [];
|
||||
const fetchedIds = new Set(fetched.map((m) => m.id));
|
||||
const extras = existing.filter((m) => !fetchedIds.has(m.id));
|
||||
const merged =
|
||||
extras.length > 0
|
||||
? [...fetched, ...extras].sort(
|
||||
(a, b) => new Date(a.created_at).getTime() - new Date(b.created_at).getTime(),
|
||||
)
|
||||
: fetched;
|
||||
|
||||
store.getState().setMessages(sessionId, merged, {
|
||||
hasMore: response.has_more ?? false,
|
||||
oldestCursor: fetched[0]?.id ?? null,
|
||||
oldestCursor: merged[0]?.id ?? null,
|
||||
});
|
||||
return fetched;
|
||||
return merged;
|
||||
}
|
||||
|
||||
type FetchMessagesParams = {
|
||||
|
||||
@@ -88,5 +88,28 @@ export async function listQuickChatSessions(workspaceId: string, options?: ApiRe
|
||||
workspace_id: string;
|
||||
primary_session_id?: string | null;
|
||||
}>;
|
||||
}>(`/api/v1/workspaces/${workspaceId}/tasks?only_ephemeral=true`, options);
|
||||
}>(`/api/v1/workspaces/${workspaceId}/tasks?only_ephemeral=true&exclude_config=true`, options);
|
||||
}
|
||||
|
||||
// Config Chat operations
|
||||
export type StartConfigChatRequest = {
|
||||
agent_profile_id?: string;
|
||||
executor_id?: string;
|
||||
prompt?: string;
|
||||
};
|
||||
|
||||
export type StartConfigChatResponse = {
|
||||
task_id: string;
|
||||
session_id: string;
|
||||
};
|
||||
|
||||
export async function startConfigChat(
|
||||
workspaceId: string,
|
||||
payload: StartConfigChatRequest,
|
||||
options?: ApiRequestOptions,
|
||||
) {
|
||||
return fetchJson<StartConfigChatResponse>(`/api/v1/workspaces/${workspaceId}/config-chat`, {
|
||||
...options,
|
||||
init: { method: "POST", body: JSON.stringify(payload), ...(options?.init ?? {}) },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -63,6 +63,19 @@ export type QuickChatState = {
|
||||
activeSessionId: string | null;
|
||||
};
|
||||
|
||||
export type ConfigChatSession = {
|
||||
sessionId: string;
|
||||
workspaceId: string;
|
||||
name?: string;
|
||||
};
|
||||
|
||||
export type ConfigChatState = {
|
||||
isOpen: boolean;
|
||||
sessions: ConfigChatSession[];
|
||||
activeSessionId: string | null;
|
||||
workspaceId: string | null;
|
||||
};
|
||||
|
||||
export type SessionFailureNotification = {
|
||||
sessionId: string;
|
||||
taskId: string;
|
||||
@@ -85,6 +98,7 @@ export type UISliceState = {
|
||||
documentPanel: DocumentPanelState;
|
||||
systemHealth: SystemHealthState;
|
||||
quickChat: QuickChatState;
|
||||
configChat: ConfigChatState;
|
||||
sessionFailureNotification: SessionFailureNotification | null;
|
||||
bottomTerminal: BottomTerminalState;
|
||||
};
|
||||
@@ -113,6 +127,12 @@ export type UISliceActions = {
|
||||
closeQuickChatSession: (sessionId: string) => void;
|
||||
setActiveQuickChatSession: (sessionId: string) => void;
|
||||
renameQuickChatSession: (sessionId: string, name: string) => void;
|
||||
openConfigChat: (sessionId: string, workspaceId: string) => void;
|
||||
startNewConfigChat: (workspaceId: string) => void;
|
||||
closeConfigChat: () => void;
|
||||
closeConfigChatSession: (sessionId: string) => void;
|
||||
setActiveConfigChatSession: (sessionId: string) => void;
|
||||
renameConfigChatSession: (sessionId: string, name: string) => void;
|
||||
setSessionFailureNotification: (n: SessionFailureNotification | null) => void;
|
||||
toggleBottomTerminal: () => void;
|
||||
openBottomTerminalWithCommand: (command: string) => void;
|
||||
|
||||
@@ -20,6 +20,7 @@ export const defaultUIState: UISliceState = {
|
||||
documentPanel: { activeDocumentBySessionId: {} },
|
||||
systemHealth: { issues: [], healthy: true, loaded: false, loading: false },
|
||||
quickChat: { isOpen: false, sessions: [], activeSessionId: null },
|
||||
configChat: { isOpen: false, sessions: [], activeSessionId: null, workspaceId: null },
|
||||
sessionFailureNotification: null,
|
||||
bottomTerminal: { isOpen: false, pendingCommand: null },
|
||||
};
|
||||
@@ -118,6 +119,58 @@ function buildBottomTerminalActions(set: ImmerSet) {
|
||||
};
|
||||
}
|
||||
|
||||
function buildConfigChatActions(set: ImmerSet) {
|
||||
return {
|
||||
openConfigChat: (sessionId: string, workspaceId: string) =>
|
||||
set((draft) => {
|
||||
draft.configChat.isOpen = true;
|
||||
draft.configChat.workspaceId = workspaceId;
|
||||
const exists = draft.configChat.sessions.some((s) => s.sessionId === sessionId);
|
||||
if (!exists) {
|
||||
draft.configChat.sessions.push({ sessionId, workspaceId });
|
||||
}
|
||||
draft.configChat.activeSessionId = sessionId;
|
||||
}),
|
||||
startNewConfigChat: (workspaceId: string) =>
|
||||
set((draft) => {
|
||||
draft.configChat.isOpen = true;
|
||||
draft.configChat.activeSessionId = null;
|
||||
draft.configChat.workspaceId = workspaceId;
|
||||
}),
|
||||
closeConfigChat: () =>
|
||||
set((draft) => {
|
||||
draft.configChat.isOpen = false;
|
||||
}),
|
||||
closeConfigChatSession: (sessionId: string) =>
|
||||
set((draft) => {
|
||||
draft.configChat.sessions = draft.configChat.sessions.filter(
|
||||
(s) => s.sessionId !== sessionId,
|
||||
);
|
||||
if (draft.configChat.activeSessionId === sessionId) {
|
||||
if (draft.configChat.sessions.length > 0) {
|
||||
const next = draft.configChat.sessions[0];
|
||||
draft.configChat.activeSessionId = next.sessionId;
|
||||
draft.configChat.workspaceId = next.workspaceId;
|
||||
} else {
|
||||
draft.configChat.activeSessionId = null;
|
||||
draft.configChat.workspaceId = null;
|
||||
}
|
||||
}
|
||||
}),
|
||||
setActiveConfigChatSession: (sessionId: string) =>
|
||||
set((draft) => {
|
||||
draft.configChat.activeSessionId = sessionId;
|
||||
}),
|
||||
renameConfigChatSession: (sessionId: string, name: string) =>
|
||||
set((draft) => {
|
||||
const session = draft.configChat.sessions.find((s) => s.sessionId === sessionId);
|
||||
if (session) {
|
||||
session.name = name;
|
||||
}
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
export const createUISlice: StateCreator<UISlice, [["zustand/immer", never]], [], UISlice> = (
|
||||
set,
|
||||
) => ({
|
||||
@@ -125,6 +178,7 @@ export const createUISlice: StateCreator<UISlice, [["zustand/immer", never]], []
|
||||
...buildPreviewActions(set),
|
||||
...buildMobileActions(set),
|
||||
...buildBottomTerminalActions(set),
|
||||
...buildConfigChatActions(set),
|
||||
setRightPanelActiveTab: (sessionId, tab) =>
|
||||
set((draft) => {
|
||||
draft.rightPanel.activeTabBySessionId[sessionId] = tab;
|
||||
|
||||
@@ -9,6 +9,7 @@ export type WorkspaceState = {
|
||||
default_executor_id?: string | null;
|
||||
default_environment_id?: string | null;
|
||||
default_agent_profile_id?: string | null;
|
||||
default_config_agent_profile_id?: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
}>;
|
||||
|
||||
@@ -204,6 +204,7 @@ export type AppState = {
|
||||
documentPanel: (typeof defaultUIState)["documentPanel"];
|
||||
systemHealth: (typeof defaultUIState)["systemHealth"];
|
||||
quickChat: (typeof defaultUIState)["quickChat"];
|
||||
configChat: (typeof defaultUIState)["configChat"];
|
||||
sessionFailureNotification: (typeof defaultUIState)["sessionFailureNotification"];
|
||||
bottomTerminal: (typeof defaultUIState)["bottomTerminal"];
|
||||
|
||||
@@ -315,6 +316,12 @@ export type AppState = {
|
||||
closeQuickChatSession: (sessionId: string) => void;
|
||||
setActiveQuickChatSession: (sessionId: string) => void;
|
||||
renameQuickChatSession: (sessionId: string, name: string) => void;
|
||||
openConfigChat: (sessionId: string, workspaceId: string) => void;
|
||||
startNewConfigChat: (workspaceId: string) => void;
|
||||
closeConfigChat: () => void;
|
||||
closeConfigChatSession: (sessionId: string) => void;
|
||||
setActiveConfigChatSession: (sessionId: string) => void;
|
||||
renameConfigChatSession: (sessionId: string, name: string) => void;
|
||||
setSessionFailureNotification: (
|
||||
n: import("./slices/ui/types").SessionFailureNotification | null,
|
||||
) => void;
|
||||
|
||||
@@ -19,9 +19,9 @@ export type BackendMessageType =
|
||||
| "workflow.created"
|
||||
| "workflow.updated"
|
||||
| "workflow.deleted"
|
||||
| "step.created"
|
||||
| "step.updated"
|
||||
| "step.deleted"
|
||||
| "workflow.step.created"
|
||||
| "workflow.step.updated"
|
||||
| "workflow.step.deleted"
|
||||
| "session.message.added"
|
||||
| "session.message.updated"
|
||||
| "session.state_changed"
|
||||
@@ -169,6 +169,7 @@ export type WorkspacePayload = {
|
||||
default_executor_id?: string | null;
|
||||
default_environment_id?: string | null;
|
||||
default_agent_profile_id?: string | null;
|
||||
default_config_agent_profile_id?: string | null;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
};
|
||||
@@ -189,12 +190,20 @@ export type StepPayload = {
|
||||
position: number;
|
||||
state: string;
|
||||
color: string;
|
||||
prompt?: string;
|
||||
events?: StepEvents;
|
||||
is_start_step?: boolean;
|
||||
allow_manual_move?: boolean;
|
||||
show_in_command_panel?: boolean;
|
||||
auto_archive_after_hours?: number;
|
||||
created_at?: string;
|
||||
updated_at?: string;
|
||||
};
|
||||
|
||||
export type WorkflowStepEventPayload = {
|
||||
step: StepPayload;
|
||||
};
|
||||
|
||||
export type MessageAddedPayload = {
|
||||
task_id: string;
|
||||
message_id: string;
|
||||
@@ -494,9 +503,9 @@ export type BackendMessageMap = {
|
||||
"workflow.created": BackendMessage<"workflow.created", WorkflowPayload>;
|
||||
"workflow.updated": BackendMessage<"workflow.updated", WorkflowPayload>;
|
||||
"workflow.deleted": BackendMessage<"workflow.deleted", WorkflowPayload>;
|
||||
"step.created": BackendMessage<"step.created", StepPayload>;
|
||||
"step.updated": BackendMessage<"step.updated", StepPayload>;
|
||||
"step.deleted": BackendMessage<"step.deleted", StepPayload>;
|
||||
"workflow.step.created": BackendMessage<"workflow.step.created", WorkflowStepEventPayload>;
|
||||
"workflow.step.updated": BackendMessage<"workflow.step.updated", WorkflowStepEventPayload>;
|
||||
"workflow.step.deleted": BackendMessage<"workflow.step.deleted", WorkflowStepEventPayload>;
|
||||
"session.message.added": BackendMessage<"session.message.added", MessageAddedPayload>;
|
||||
"session.message.updated": BackendMessage<"session.message.updated", MessageAddedPayload>;
|
||||
"session.state_changed": BackendMessage<"session.state_changed", TaskSessionStateChangedPayload>;
|
||||
|
||||
@@ -151,6 +151,7 @@ export type Workspace = {
|
||||
default_executor_id?: string | null;
|
||||
default_environment_id?: string | null;
|
||||
default_agent_profile_id?: string | null;
|
||||
default_config_agent_profile_id?: string | null;
|
||||
created_at: string;
|
||||
updated_at: string;
|
||||
};
|
||||
|
||||
@@ -2,6 +2,21 @@ import type { StoreApi } from "zustand";
|
||||
import type { AppState } from "@/lib/state/store";
|
||||
import type { WsHandlers } from "@/lib/ws/handlers/types";
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
function stepFromPayload(step: any) {
|
||||
return {
|
||||
id: step.id as string,
|
||||
title: (step.name ?? step.title) as string,
|
||||
color: (step.color ?? "bg-neutral-400") as string,
|
||||
position: (step.position ?? 0) as number,
|
||||
events: step.events,
|
||||
show_in_command_panel: step.show_in_command_panel,
|
||||
allow_manual_move: step.allow_manual_move,
|
||||
prompt: step.prompt,
|
||||
is_start_step: step.is_start_step,
|
||||
};
|
||||
}
|
||||
|
||||
export function registerWorkflowsHandlers(store: StoreApi<AppState>): WsHandlers {
|
||||
return {
|
||||
"workflow.created": (message) => {
|
||||
@@ -60,5 +75,34 @@ export function registerWorkflowsHandlers(store: StoreApi<AppState>): WsHandlers
|
||||
};
|
||||
});
|
||||
},
|
||||
"workflow.step.created": (message) => {
|
||||
const step = message.payload.step;
|
||||
store.setState((state) => {
|
||||
if (state.kanban.workflowId !== step.workflow_id) return state;
|
||||
if (state.kanban.steps.some((s) => s.id === step.id)) return state;
|
||||
const steps = [...state.kanban.steps, stepFromPayload(step)].sort(
|
||||
(a, b) => a.position - b.position,
|
||||
);
|
||||
return { ...state, kanban: { ...state.kanban, steps } };
|
||||
});
|
||||
},
|
||||
"workflow.step.updated": (message) => {
|
||||
const step = message.payload.step;
|
||||
store.setState((state) => {
|
||||
if (state.kanban.workflowId !== step.workflow_id) return state;
|
||||
const steps = state.kanban.steps
|
||||
.map((s) => (s.id === step.id ? stepFromPayload(step) : s))
|
||||
.sort((a, b) => a.position - b.position);
|
||||
return { ...state, kanban: { ...state.kanban, steps } };
|
||||
});
|
||||
},
|
||||
"workflow.step.deleted": (message) => {
|
||||
const step = message.payload.step;
|
||||
store.setState((state) => {
|
||||
if (state.kanban.workflowId !== step.workflow_id) return state;
|
||||
const steps = state.kanban.steps.filter((s) => s.id !== step.id);
|
||||
return { ...state, kanban: { ...state.kanban, steps } };
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -17,6 +17,7 @@ export function registerWorkspacesHandlers(store: StoreApi<AppState>): WsHandler
|
||||
default_executor_id: payload.default_executor_id ?? null,
|
||||
default_environment_id: payload.default_environment_id ?? null,
|
||||
default_agent_profile_id: payload.default_agent_profile_id ?? null,
|
||||
default_config_agent_profile_id: payload.default_config_agent_profile_id ?? null,
|
||||
created_at: payload.created_at ?? new Date().toISOString(),
|
||||
updated_at: payload.updated_at ?? new Date().toISOString(),
|
||||
};
|
||||
@@ -50,6 +51,10 @@ export function registerWorkspacesHandlers(store: StoreApi<AppState>): WsHandler
|
||||
default_executor_id: message.payload.default_executor_id ?? null,
|
||||
default_environment_id: message.payload.default_environment_id ?? null,
|
||||
default_agent_profile_id: message.payload.default_agent_profile_id ?? null,
|
||||
default_config_agent_profile_id:
|
||||
"default_config_agent_profile_id" in message.payload
|
||||
? (message.payload.default_config_agent_profile_id ?? null)
|
||||
: (item.default_config_agent_profile_id ?? null),
|
||||
updated_at: message.payload.updated_at ?? item.updated_at,
|
||||
}
|
||||
: item,
|
||||
|
||||
Reference in New Issue
Block a user