refactor: session resumption cleanup and AgentInstance → AgentExecution rename (#23)
* feat: session resumption with ACP session ID support - Add useSessionResumption hook for automatic session recovery on page reload - Fix ACPSessionID not being set on AgentInstance in Launch() and createInstance() - Add task.session.status and task.session.resume WebSocket actions - Fix shell terminal retry logic for resumed sessions - Fix taskSessionState reading from Zustand store instead of local state - Remove dead code: unused stream handling functions in lifecycle/manager.go - Fix test mock interfaces (CleanupStaleInstanceByTaskID, NewManager signature) - Add enhanced logging for session resumption debugging - Simplify page-client.tsx state merging logic * refactor: remove unused AgentController (dead code) - Delete agent_controller.go - entirely unused duplicate of Manager methods - Remove agentController field from Manager struct - Remove AgentController initialization in NewManager The AgentController duplicated StartAgentProcess, initializeACPSession, and PromptAgent from Manager but was never called. All agent control operations go through Manager's own methods. * refactor: remove unused MemoryRepository (dead code) - Delete memory.go - entire MemoryRepository implementation unused (replaced by SQLite repository) - Delete memory_test.go - tests for removed MemoryRepository Found via 'deadcode' tool analysis. * refactor: consolidate agentctl packages into server/client structure Reorganize the confusing dual agentctl packages: - internal/agentctl/* → internal/agentctl/server/ - internal/agent/agentctl/* → internal/agentctl/client/ Structure is now: internal/agentctl/ ├── client/ - HTTP client for talking to agentctl servers │ ├── client.go │ ├── standalone.go │ ├── acp.go │ └── launcher/ ├── server/ - agentctl server implementation (runs in containers) │ ├── api/ │ ├── adapter/ │ ├── acp/ │ ├── config/ │ ├── instance/ │ ├── process/ │ └── shell/ └── types/ - Shared types used by both client and server Also consolidated shared types (GitStatusUpdate, FileInfo, etc.) from process/types.go into the shared types/ package. * refactor: rename AgentInstance to AgentExecution for clarity Rename AgentInstance -> AgentExecution across the entire codebase to better reflect what it represents: an agent actively working on a task, not just a generic 'instance'. Changes: - AgentInstance struct -> AgentExecution - InstanceStore -> ExecutionStore (new file: execution_store.go) - RecoveredInstance -> RecoveredExecution - All method names: GetInstance* -> GetExecution*, ListInstances -> ListExecutions, etc. - All parameters: instanceID -> executionID - All local variables: instance -> execution - DTOs and JSON tags: agent_instance_id -> agent_execution_id - Database columns: agent_instance_id -> agent_execution_id Also consolidates duplicate prompt logic: - Merge sendInitialPrompt and SendPrompt into single SendPrompt method - Add validateStatus parameter to differentiate initial vs follow-up prompts Also extracts ACP session management to session.go: - Move initializeACPSession logic to SessionManager.InitializeAndPrompt - Move PromptAgent logic to SessionManager.SendPrompt - Manager now delegates to SessionManager for all prompt operations Also removes duplicate event publishing: - Remove 9 duplicate m.publish*() methods from manager.go - Use existing EventPublisher methods via m.eventPublisher.Publish*() Also extracts types to dedicated file: - Move AgentExecution, LaunchRequest, PromptResult, etc. to types.go Net reduction: ~600 lines removed from manager.go through deduplication and better separation of concerns. * fix(backend): Docker runtime now creates instance via ControlServer The Docker runtime was incorrectly creating an agentctl.Client pointing directly to port 9999 (the ControlServer port), then trying to call instance-specific APIs like /api/v1/agent/configure which only exist on per-instance servers. Fixed by making Docker runtime follow the same flow as standalone mode: - LaunchContainer now uses StandaloneCtl to create an instance via the control API, then creates Client pointing to the instance port - RecoverInstances queries the ControlServer to get the instance port - Added waitForHealth helper to wait for agentctl to be ready Also improved HTTP error handling in agentctl client: - All client methods now check HTTP status codes before JSON decoding - Better error messages include status code and response body * fix: restore session resumption imports and variables * fix: add sessionId prop back to TaskLayout
This commit is contained in:
@@ -17,10 +17,10 @@ import (
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/agentctl/api"
|
||||
"github.com/kandev/kandev/internal/agentctl/config"
|
||||
"github.com/kandev/kandev/internal/agentctl/instance"
|
||||
"github.com/kandev/kandev/internal/agentctl/process"
|
||||
"github.com/kandev/kandev/internal/agentctl/server/api"
|
||||
"github.com/kandev/kandev/internal/agentctl/server/config"
|
||||
"github.com/kandev/kandev/internal/agentctl/server/instance"
|
||||
"github.com/kandev/kandev/internal/agentctl/server/process"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/pkg/agent"
|
||||
"go.uber.org/zap"
|
||||
|
||||
@@ -28,7 +28,8 @@ import (
|
||||
gateways "github.com/kandev/kandev/internal/gateway/websocket"
|
||||
|
||||
// Agent Manager packages
|
||||
"github.com/kandev/kandev/internal/agent/agentctl/launcher"
|
||||
agentctl "github.com/kandev/kandev/internal/agentctl/client"
|
||||
"github.com/kandev/kandev/internal/agentctl/client/launcher"
|
||||
agentcontroller "github.com/kandev/kandev/internal/agent/controller"
|
||||
"github.com/kandev/kandev/internal/agent/credentials"
|
||||
"github.com/kandev/kandev/internal/agent/discovery"
|
||||
@@ -300,10 +301,39 @@ func main() {
|
||||
credsMgr.AddProvider(credentials.NewFileProvider(credsFile))
|
||||
}
|
||||
|
||||
// Profile Resolver
|
||||
profileResolver := lifecycle.NewStoreProfileResolver(agentSettingsRepo)
|
||||
|
||||
// Create the appropriate runtime based on configuration
|
||||
var agentRuntime lifecycle.Runtime
|
||||
var containerMgr *lifecycle.ContainerManager
|
||||
switch cfg.Agent.Runtime {
|
||||
case "standalone":
|
||||
standaloneCtl := agentctl.NewStandaloneCtl(
|
||||
cfg.Agent.StandaloneHost,
|
||||
cfg.Agent.StandalonePort,
|
||||
log,
|
||||
)
|
||||
agentRuntime = lifecycle.NewStandaloneRuntime(
|
||||
standaloneCtl,
|
||||
cfg.Agent.StandaloneHost,
|
||||
cfg.Agent.StandalonePort,
|
||||
log,
|
||||
)
|
||||
log.Info("Using standalone runtime",
|
||||
zap.String("host", cfg.Agent.StandaloneHost),
|
||||
zap.Int("port", cfg.Agent.StandalonePort))
|
||||
default:
|
||||
// Docker mode (default)
|
||||
if dockerClient != nil {
|
||||
containerMgr = lifecycle.NewContainerManager(dockerClient, "", log)
|
||||
agentRuntime = lifecycle.NewDockerRuntime(dockerClient, log)
|
||||
log.Info("Using Docker runtime")
|
||||
}
|
||||
}
|
||||
|
||||
// Lifecycle Manager (uses agentctl for agent communication)
|
||||
lifecycleMgr = lifecycle.NewManager(dockerClient, agentRegistry, eventBus, cfg.Agent, log)
|
||||
lifecycleMgr.SetCredentialsManager(credsMgr)
|
||||
lifecycleMgr.SetProfileResolver(lifecycle.NewStoreProfileResolver(agentSettingsRepo))
|
||||
lifecycleMgr = lifecycle.NewManager(agentRegistry, eventBus, agentRuntime, containerMgr, credsMgr, profileResolver, log)
|
||||
|
||||
if err := lifecycleMgr.Start(ctx); err != nil {
|
||||
log.Fatal("Failed to start lifecycle manager", zap.Error(err))
|
||||
@@ -421,6 +451,7 @@ func main() {
|
||||
// Register shell handlers
|
||||
shellHandlers := agenthandlers.NewShellHandlers(lifecycleMgr, log)
|
||||
shellHandlers.SetHub(gateway.Hub)
|
||||
shellHandlers.SetSessionResumer(&shellSessionResumerAdapter{svc: orchestratorSvc})
|
||||
shellHandlers.RegisterHandlers(gateway.Dispatcher)
|
||||
lifecycleMgr.SetShellStreamStarter(shellHandlers)
|
||||
log.Info("Registered Shell WebSocket handlers")
|
||||
@@ -896,7 +927,8 @@ func newLifecycleAdapter(mgr *lifecycle.Manager, reg *registry.Registry, log *lo
|
||||
}
|
||||
}
|
||||
|
||||
// LaunchAgent starts a new agent container for a task
|
||||
// LaunchAgent creates a new agentctl instance for a task.
|
||||
// Agent subprocess is NOT started - call StartAgentProcess() explicitly.
|
||||
func (a *lifecycleAdapter) LaunchAgent(ctx context.Context, req *executor.LaunchAgentRequest) (*executor.LaunchAgentResponse, error) {
|
||||
// The RepositoryURL field contains a local filesystem path for the workspace
|
||||
// If empty, the agent will run without a mounted workspace
|
||||
@@ -917,68 +949,73 @@ func (a *lifecycleAdapter) LaunchAgent(ctx context.Context, req *executor.Launch
|
||||
BaseBranch: req.BaseBranch,
|
||||
}
|
||||
|
||||
instance, err := a.mgr.Launch(ctx, launchReq)
|
||||
// Create the agentctl execution (does NOT start agent process)
|
||||
execution, err := a.mgr.Launch(ctx, launchReq)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Streaming is now handled by the lifecycle manager
|
||||
|
||||
// Extract worktree info from metadata if available
|
||||
var worktreeID, worktreePath, worktreeBranch string
|
||||
if instance.Metadata != nil {
|
||||
if id, ok := instance.Metadata["worktree_id"].(string); ok {
|
||||
if execution.Metadata != nil {
|
||||
if id, ok := execution.Metadata["worktree_id"].(string); ok {
|
||||
worktreeID = id
|
||||
}
|
||||
if path, ok := instance.Metadata["worktree_path"].(string); ok {
|
||||
if path, ok := execution.Metadata["worktree_path"].(string); ok {
|
||||
worktreePath = path
|
||||
}
|
||||
if branch, ok := instance.Metadata["worktree_branch"].(string); ok {
|
||||
if branch, ok := execution.Metadata["worktree_branch"].(string); ok {
|
||||
worktreeBranch = branch
|
||||
}
|
||||
}
|
||||
|
||||
return &executor.LaunchAgentResponse{
|
||||
AgentInstanceID: instance.ID,
|
||||
ContainerID: instance.ContainerID,
|
||||
Status: instance.Status,
|
||||
AgentExecutionID: execution.ID,
|
||||
ContainerID: execution.ContainerID,
|
||||
Status: execution.Status,
|
||||
WorktreeID: worktreeID,
|
||||
WorktreePath: worktreePath,
|
||||
WorktreeBranch: worktreeBranch,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// 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 {
|
||||
return a.mgr.StartAgentProcess(ctx, agentInstanceID)
|
||||
}
|
||||
|
||||
// StopAgent stops a running agent
|
||||
func (a *lifecycleAdapter) StopAgent(ctx context.Context, agentInstanceID string, force bool) error {
|
||||
return a.mgr.StopAgent(ctx, agentInstanceID, force)
|
||||
}
|
||||
|
||||
// GetAgentStatus returns the status of an agent instance
|
||||
func (a *lifecycleAdapter) GetAgentStatus(ctx context.Context, agentInstanceID string) (*v1.AgentInstance, error) {
|
||||
instance, found := a.mgr.GetInstance(agentInstanceID)
|
||||
// GetAgentStatus returns the status of an agent execution
|
||||
func (a *lifecycleAdapter) GetAgentStatus(ctx context.Context, agentInstanceID string) (*v1.AgentExecution, error) {
|
||||
execution, found := a.mgr.GetExecution(agentInstanceID)
|
||||
if !found {
|
||||
return nil, fmt.Errorf("agent instance %q not found", agentInstanceID)
|
||||
return nil, fmt.Errorf("agent execution %q not found", agentInstanceID)
|
||||
}
|
||||
|
||||
containerID := instance.ContainerID
|
||||
containerID := execution.ContainerID
|
||||
now := time.Now()
|
||||
result := &v1.AgentInstance{
|
||||
ID: instance.ID,
|
||||
TaskID: instance.TaskID,
|
||||
AgentProfileID: instance.AgentProfileID,
|
||||
result := &v1.AgentExecution{
|
||||
ID: execution.ID,
|
||||
TaskID: execution.TaskID,
|
||||
AgentProfileID: execution.AgentProfileID,
|
||||
ContainerID: &containerID,
|
||||
Status: instance.Status,
|
||||
StartedAt: &instance.StartedAt,
|
||||
StoppedAt: instance.FinishedAt,
|
||||
CreatedAt: instance.StartedAt,
|
||||
Status: execution.Status,
|
||||
StartedAt: &execution.StartedAt,
|
||||
StoppedAt: execution.FinishedAt,
|
||||
CreatedAt: execution.StartedAt,
|
||||
UpdatedAt: now,
|
||||
}
|
||||
|
||||
if instance.ExitCode != nil {
|
||||
result.ExitCode = instance.ExitCode
|
||||
if execution.ExitCode != nil {
|
||||
result.ExitCode = execution.ExitCode
|
||||
}
|
||||
if instance.ErrorMessage != "" {
|
||||
result.ErrorMessage = &instance.ErrorMessage
|
||||
if execution.ErrorMessage != "" {
|
||||
result.ErrorMessage = &execution.ErrorMessage
|
||||
}
|
||||
|
||||
return result, nil
|
||||
@@ -1011,13 +1048,13 @@ func (a *lifecycleAdapter) RespondToPermissionByTaskID(ctx context.Context, task
|
||||
return a.mgr.RespondToPermissionByTaskID(taskID, pendingID, optionID, cancelled)
|
||||
}
|
||||
|
||||
// GetRecoveredInstances returns instances recovered from Docker during startup
|
||||
func (a *lifecycleAdapter) GetRecoveredInstances() []executor.RecoveredInstanceInfo {
|
||||
recovered := a.mgr.GetRecoveredInstances()
|
||||
result := make([]executor.RecoveredInstanceInfo, len(recovered))
|
||||
// GetRecoveredExecutions returns executions recovered from Docker during startup
|
||||
func (a *lifecycleAdapter) GetRecoveredExecutions() []executor.RecoveredExecutionInfo {
|
||||
recovered := a.mgr.GetRecoveredExecutions()
|
||||
result := make([]executor.RecoveredExecutionInfo, len(recovered))
|
||||
for i, r := range recovered {
|
||||
result[i] = executor.RecoveredInstanceInfo{
|
||||
InstanceID: r.InstanceID,
|
||||
result[i] = executor.RecoveredExecutionInfo{
|
||||
ExecutionID: r.ExecutionID,
|
||||
TaskID: r.TaskID,
|
||||
ContainerID: r.ContainerID,
|
||||
AgentProfileID: r.AgentProfileID,
|
||||
@@ -1032,6 +1069,11 @@ func (a *lifecycleAdapter) IsAgentRunningForTask(ctx context.Context, taskID str
|
||||
return a.mgr.IsAgentRunningForTask(ctx, taskID)
|
||||
}
|
||||
|
||||
// CleanupStaleExecutionByTaskID removes a stale agent execution from tracking without trying to stop it.
|
||||
func (a *lifecycleAdapter) CleanupStaleExecutionByTaskID(ctx context.Context, taskID string) error {
|
||||
return a.mgr.CleanupStaleExecutionByTaskID(ctx, taskID)
|
||||
}
|
||||
|
||||
// corsMiddleware returns a CORS middleware for HTTP and WebSocket connections
|
||||
func corsMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
@@ -1071,6 +1113,16 @@ func (a *orchestratorAdapter) ResumeTaskSession(ctx context.Context, taskID, tas
|
||||
return err
|
||||
}
|
||||
|
||||
// shellSessionResumerAdapter adapts the orchestrator service to the shell handlers' SessionResumer interface
|
||||
type shellSessionResumerAdapter struct {
|
||||
svc *orchestrator.Service
|
||||
}
|
||||
|
||||
func (a *shellSessionResumerAdapter) ResumeTaskSession(ctx context.Context, taskID, taskSessionID string) error {
|
||||
_, err := a.svc.ResumeTaskSession(ctx, taskID, taskSessionID)
|
||||
return err
|
||||
}
|
||||
|
||||
// messageCreatorAdapter adapts the task service to the orchestrator.MessageCreator interface
|
||||
type messageCreatorAdapter struct {
|
||||
svc *taskservice.Service
|
||||
|
||||
@@ -29,14 +29,14 @@ func (c *Controller) ListAgents(ctx context.Context, req dto.ListAgentsRequest)
|
||||
return dto.ListAgentsResponse{}, ErrLifecycleManagerNotAvailable
|
||||
}
|
||||
|
||||
agents := c.lifecycle.ListInstances()
|
||||
agents := c.lifecycle.ListExecutions()
|
||||
resp := dto.ListAgentsResponse{
|
||||
Agents: make([]dto.AgentDTO, 0, len(agents)),
|
||||
Total: len(agents),
|
||||
}
|
||||
|
||||
for _, a := range agents {
|
||||
agent := dto.FromAgentInstance(&dto.AgentInstanceData{
|
||||
agent := dto.FromAgentExecution(&dto.AgentExecutionData{
|
||||
ID: a.ID,
|
||||
TaskID: a.TaskID,
|
||||
AgentProfileID: a.AgentProfileID,
|
||||
@@ -67,14 +67,14 @@ func (c *Controller) LaunchAgent(ctx context.Context, req dto.LaunchAgentRequest
|
||||
Env: req.Env,
|
||||
}
|
||||
|
||||
instance, err := c.lifecycle.Launch(ctx, launchReq)
|
||||
execution, err := c.lifecycle.Launch(ctx, launchReq)
|
||||
if err != nil {
|
||||
return dto.LaunchAgentResponse{}, err
|
||||
}
|
||||
|
||||
return dto.LaunchAgentResponse{
|
||||
Success: true,
|
||||
AgentID: instance.ID,
|
||||
AgentID: execution.ID,
|
||||
TaskID: req.TaskID,
|
||||
}, nil
|
||||
}
|
||||
@@ -85,12 +85,12 @@ func (c *Controller) GetAgentStatus(ctx context.Context, req dto.GetAgentStatusR
|
||||
return dto.AgentDTO{}, ErrLifecycleManagerNotAvailable
|
||||
}
|
||||
|
||||
agent, found := c.lifecycle.GetInstance(req.AgentID)
|
||||
agent, found := c.lifecycle.GetExecution(req.AgentID)
|
||||
if !found {
|
||||
return dto.AgentDTO{}, ErrAgentNotFound
|
||||
}
|
||||
|
||||
return dto.FromAgentInstance(&dto.AgentInstanceData{
|
||||
return dto.FromAgentExecution(&dto.AgentExecutionData{
|
||||
ID: agent.ID,
|
||||
TaskID: agent.TaskID,
|
||||
AgentProfileID: agent.AgentProfileID,
|
||||
@@ -110,7 +110,7 @@ func (c *Controller) GetAgentLogs(ctx context.Context, req dto.GetAgentLogsReque
|
||||
return dto.GetAgentLogsResponse{}, ErrLifecycleManagerNotAvailable
|
||||
}
|
||||
|
||||
_, found := c.lifecycle.GetInstance(req.AgentID)
|
||||
_, found := c.lifecycle.GetExecution(req.AgentID)
|
||||
if !found {
|
||||
return dto.GetAgentLogsResponse{}, ErrAgentNotFound
|
||||
}
|
||||
|
||||
@@ -88,31 +88,31 @@ type ListAgentTypesResponse struct {
|
||||
Total int `json:"total"`
|
||||
}
|
||||
|
||||
// FromAgentInstance converts a lifecycle.AgentInstance to AgentDTO
|
||||
func FromAgentInstance(a *AgentInstanceData) AgentDTO {
|
||||
// FromAgentExecution converts a lifecycle.AgentExecution to AgentDTO
|
||||
func FromAgentExecution(execution *AgentExecutionData) AgentDTO {
|
||||
agent := AgentDTO{
|
||||
ID: a.ID,
|
||||
TaskID: a.TaskID,
|
||||
AgentProfileID: a.AgentProfileID,
|
||||
ContainerID: a.ContainerID,
|
||||
Status: a.Status,
|
||||
Progress: a.Progress,
|
||||
StartedAt: a.StartedAt.Format("2006-01-02T15:04:05Z"),
|
||||
ID: execution.ID,
|
||||
TaskID: execution.TaskID,
|
||||
AgentProfileID: execution.AgentProfileID,
|
||||
ContainerID: execution.ContainerID,
|
||||
Status: execution.Status,
|
||||
Progress: execution.Progress,
|
||||
StartedAt: execution.StartedAt.Format("2006-01-02T15:04:05Z"),
|
||||
}
|
||||
if a.FinishedAt != nil && !a.FinishedAt.IsZero() {
|
||||
agent.FinishedAt = a.FinishedAt.Format("2006-01-02T15:04:05Z")
|
||||
if execution.FinishedAt != nil && !execution.FinishedAt.IsZero() {
|
||||
agent.FinishedAt = execution.FinishedAt.Format("2006-01-02T15:04:05Z")
|
||||
}
|
||||
if a.ExitCode != nil {
|
||||
agent.ExitCode = a.ExitCode
|
||||
if execution.ExitCode != nil {
|
||||
agent.ExitCode = execution.ExitCode
|
||||
}
|
||||
if a.ErrorMessage != "" {
|
||||
agent.Error = a.ErrorMessage
|
||||
if execution.ErrorMessage != "" {
|
||||
agent.Error = execution.ErrorMessage
|
||||
}
|
||||
return agent
|
||||
}
|
||||
|
||||
// AgentInstanceData is the input data for FromAgentInstance (avoids circular import)
|
||||
type AgentInstanceData struct {
|
||||
// AgentExecutionData is the input data for FromAgentExecution (avoids circular import)
|
||||
type AgentExecutionData struct {
|
||||
ID string
|
||||
TaskID string
|
||||
AgentProfileID string
|
||||
|
||||
@@ -6,18 +6,24 @@ import (
|
||||
"fmt"
|
||||
"sync"
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/agentctl"
|
||||
agentctl "github.com/kandev/kandev/internal/agentctl/client"
|
||||
"github.com/kandev/kandev/internal/agent/lifecycle"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
ws "github.com/kandev/kandev/pkg/websocket"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// SessionResumer is an interface for resuming task sessions
|
||||
type SessionResumer interface {
|
||||
ResumeTaskSession(ctx context.Context, taskID, taskSessionID string) error
|
||||
}
|
||||
|
||||
// ShellHandlers provides WebSocket handlers for shell terminal operations
|
||||
type ShellHandlers struct {
|
||||
lifecycleMgr *lifecycle.Manager
|
||||
logger *logger.Logger
|
||||
hub ShellOutputBroadcaster
|
||||
lifecycleMgr *lifecycle.Manager
|
||||
logger *logger.Logger
|
||||
hub ShellOutputBroadcaster
|
||||
sessionResumer SessionResumer
|
||||
|
||||
// Track active shell streams per task
|
||||
activeStreams map[string]context.CancelFunc
|
||||
@@ -43,6 +49,11 @@ func (h *ShellHandlers) SetHub(hub ShellOutputBroadcaster) {
|
||||
h.hub = hub
|
||||
}
|
||||
|
||||
// SetSessionResumer sets the session resumer for auto-resuming sessions on shell subscribe
|
||||
func (h *ShellHandlers) SetSessionResumer(resumer SessionResumer) {
|
||||
h.sessionResumer = resumer
|
||||
}
|
||||
|
||||
// RegisterHandlers registers shell handlers with the WebSocket dispatcher
|
||||
func (h *ShellHandlers) RegisterHandlers(d *ws.Dispatcher) {
|
||||
d.RegisterFunc(ws.ActionShellStatus, h.wsShellStatus)
|
||||
@@ -72,8 +83,8 @@ func (h *ShellHandlers) wsShellStatus(ctx context.Context, msg *ws.Message) (*ws
|
||||
return nil, fmt.Errorf("task_id is required")
|
||||
}
|
||||
|
||||
// Get the agent instance for this task
|
||||
instance, ok := h.lifecycleMgr.GetInstanceByTaskID(req.TaskID)
|
||||
// Get the agent execution for this task
|
||||
execution, ok := h.lifecycleMgr.GetExecutionByTaskID(req.TaskID)
|
||||
if !ok {
|
||||
return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{
|
||||
"available": false,
|
||||
@@ -82,7 +93,7 @@ func (h *ShellHandlers) wsShellStatus(ctx context.Context, msg *ws.Message) (*ws
|
||||
}
|
||||
|
||||
// Get shell status from agentctl
|
||||
client := instance.GetAgentCtlClient()
|
||||
client := execution.GetAgentCtlClient()
|
||||
if client == nil {
|
||||
return ws.NewResponse(msg.ID, msg.Action, map[string]interface{}{
|
||||
"available": false,
|
||||
@@ -124,8 +135,8 @@ func (h *ShellHandlers) wsShellSubscribe(ctx context.Context, msg *ws.Message) (
|
||||
return nil, fmt.Errorf("task_id is required")
|
||||
}
|
||||
|
||||
// Verify the agent instance exists for this task
|
||||
instance, ok := h.lifecycleMgr.GetInstanceByTaskID(req.TaskID)
|
||||
// Verify the agent execution exists for this task
|
||||
execution, ok := h.lifecycleMgr.GetExecutionByTaskID(req.TaskID)
|
||||
if !ok {
|
||||
return nil, fmt.Errorf("no agent running for task %s", req.TaskID)
|
||||
}
|
||||
@@ -138,7 +149,7 @@ func (h *ShellHandlers) wsShellSubscribe(ctx context.Context, msg *ws.Message) (
|
||||
// Get buffered output to include in response
|
||||
// This ensures client gets current shell state without duplicate broadcasts
|
||||
buffer := ""
|
||||
if client := instance.GetAgentCtlClient(); client != nil {
|
||||
if client := execution.GetAgentCtlClient(); client != nil {
|
||||
if b, err := client.ShellBuffer(ctx); err == nil {
|
||||
buffer = b
|
||||
}
|
||||
@@ -162,8 +173,8 @@ func (h *ShellHandlers) wsShellInput(ctx context.Context, msg *ws.Message) (*ws.
|
||||
return nil, fmt.Errorf("task_id is required")
|
||||
}
|
||||
|
||||
// Verify the agent instance exists for this task
|
||||
if _, ok := h.lifecycleMgr.GetInstanceByTaskID(req.TaskID); !ok {
|
||||
// Verify the agent execution exists for this task
|
||||
if _, ok := h.lifecycleMgr.GetExecutionByTaskID(req.TaskID); !ok {
|
||||
return nil, fmt.Errorf("no agent running for task %s", req.TaskID)
|
||||
}
|
||||
|
||||
@@ -194,12 +205,22 @@ func (h *ShellHandlers) StartShellStreamWithHub(ctx context.Context, taskID stri
|
||||
return nil // Already streaming
|
||||
}
|
||||
|
||||
streamCtx, cancel := context.WithCancel(ctx)
|
||||
streamCtx, cancel := context.WithCancel(context.Background()) // Use background context so stream survives request
|
||||
h.activeStreams[taskID] = cancel
|
||||
h.mu.Unlock()
|
||||
|
||||
go h.runShellStream(streamCtx, taskID, hub)
|
||||
return nil
|
||||
// Use a channel to wait for stream setup to complete
|
||||
readyCh := make(chan error, 1)
|
||||
go h.runShellStreamWithReady(streamCtx, taskID, hub, readyCh)
|
||||
|
||||
// Wait for stream to be ready (or fail)
|
||||
select {
|
||||
case err := <-readyCh:
|
||||
return err
|
||||
case <-ctx.Done():
|
||||
cancel()
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
// StopShellStream stops the shell stream for a task
|
||||
@@ -217,29 +238,32 @@ type ShellOutputBroadcaster interface {
|
||||
BroadcastToTask(taskID string, msg *ws.Message)
|
||||
}
|
||||
|
||||
// runShellStream runs the shell output stream for a task
|
||||
func (h *ShellHandlers) runShellStream(ctx context.Context, taskID string, hub ShellOutputBroadcaster) {
|
||||
// runShellStreamWithReady runs the shell output stream for a task and signals when ready
|
||||
func (h *ShellHandlers) runShellStreamWithReady(ctx context.Context, taskID string, hub ShellOutputBroadcaster, readyCh chan<- error) {
|
||||
defer func() {
|
||||
h.mu.Lock()
|
||||
delete(h.activeStreams, taskID)
|
||||
h.mu.Unlock()
|
||||
}()
|
||||
|
||||
instance, ok := h.lifecycleMgr.GetInstanceByTaskID(taskID)
|
||||
execution, ok := h.lifecycleMgr.GetExecutionByTaskID(taskID)
|
||||
if !ok {
|
||||
h.logger.Debug("no agent instance for shell stream", zap.String("task_id", taskID))
|
||||
h.logger.Debug("no agent execution for shell stream", zap.String("task_id", taskID))
|
||||
readyCh <- fmt.Errorf("no agent execution for task %s", taskID)
|
||||
return
|
||||
}
|
||||
|
||||
client := instance.GetAgentCtlClient()
|
||||
client := execution.GetAgentCtlClient()
|
||||
if client == nil {
|
||||
h.logger.Debug("no client for shell stream", zap.String("task_id", taskID))
|
||||
readyCh <- fmt.Errorf("no agent client for task %s", taskID)
|
||||
return
|
||||
}
|
||||
|
||||
outputCh, inputCh, err := client.StreamShell(ctx)
|
||||
if err != nil {
|
||||
h.logger.Error("failed to start shell stream", zap.String("task_id", taskID), zap.Error(err))
|
||||
readyCh <- fmt.Errorf("failed to start shell stream: %w", err)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -249,6 +273,9 @@ func (h *ShellHandlers) runShellStream(ctx context.Context, taskID string, hub S
|
||||
|
||||
h.logger.Info("shell stream started", zap.String("task_id", taskID))
|
||||
|
||||
// Signal that we're ready - input channel is now stored
|
||||
readyCh <- nil
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
|
||||
@@ -8,7 +8,6 @@ import (
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/lifecycle"
|
||||
"github.com/kandev/kandev/internal/agent/registry"
|
||||
"github.com/kandev/kandev/internal/common/config"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/internal/events/bus"
|
||||
ws "github.com/kandev/kandev/pkg/websocket"
|
||||
@@ -42,13 +41,24 @@ func (m *MockEventBus) IsConnected() bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// testAgentConfig returns a default AgentConfig for testing
|
||||
func testAgentConfig() config.AgentConfig {
|
||||
return config.AgentConfig{
|
||||
Runtime: "docker",
|
||||
StandaloneHost: "localhost",
|
||||
StandalonePort: 9999,
|
||||
}
|
||||
// MockCredentialsManager implements lifecycle.CredentialsManager for testing
|
||||
type MockCredentialsManager struct{}
|
||||
|
||||
func (m *MockCredentialsManager) GetCredentialValue(ctx context.Context, key string) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// MockProfileResolver implements lifecycle.ProfileResolver for testing
|
||||
type MockProfileResolver struct{}
|
||||
|
||||
func (m *MockProfileResolver) ResolveProfile(ctx context.Context, profileID string) (*lifecycle.AgentProfileInfo, error) {
|
||||
return &lifecycle.AgentProfileInfo{
|
||||
ProfileID: profileID,
|
||||
ProfileName: "Test Profile",
|
||||
AgentID: "augment-agent",
|
||||
AgentName: "auggie",
|
||||
Model: "claude-sonnet-4-20250514",
|
||||
}, nil
|
||||
}
|
||||
|
||||
func newTestRegistry() *registry.Registry {
|
||||
@@ -176,7 +186,10 @@ func newTestManager() *lifecycle.Manager {
|
||||
log := newTestLogger()
|
||||
reg := newTestRegistry()
|
||||
eventBus := &MockEventBus{}
|
||||
return lifecycle.NewManager(nil, reg, eventBus, testAgentConfig(), log)
|
||||
credsMgr := &MockCredentialsManager{}
|
||||
profileResolver := &MockProfileResolver{}
|
||||
// Pass nil for runtime and containerManager - tests don't need them
|
||||
return lifecycle.NewManager(reg, eventBus, nil, nil, credsMgr, profileResolver, log)
|
||||
}
|
||||
|
||||
func TestWsShellStatus_NoInstanceFound(t *testing.T) {
|
||||
|
||||
@@ -46,14 +46,14 @@ func (h *WorkspaceFileHandlers) wsGetFileTree(ctx context.Context, msg *ws.Messa
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "task_id is required", nil)
|
||||
}
|
||||
|
||||
// Get agent instance for this task
|
||||
instance, found := h.lifecycle.GetInstanceByTaskID(req.TaskID)
|
||||
// Get agent execution for this task
|
||||
execution, found := h.lifecycle.GetExecutionByTaskID(req.TaskID)
|
||||
if !found {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeNotFound, "No agent found for task", nil)
|
||||
}
|
||||
|
||||
// Get agentctl client
|
||||
client := instance.GetAgentCtlClient()
|
||||
client := execution.GetAgentCtlClient()
|
||||
if client == nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Agent client not available", nil)
|
||||
}
|
||||
@@ -87,14 +87,14 @@ func (h *WorkspaceFileHandlers) wsGetFileContent(ctx context.Context, msg *ws.Me
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeValidation, "path is required", nil)
|
||||
}
|
||||
|
||||
// Get agent instance for this task
|
||||
instance, found := h.lifecycle.GetInstanceByTaskID(req.TaskID)
|
||||
// Get agent execution for this task
|
||||
execution, found := h.lifecycle.GetExecutionByTaskID(req.TaskID)
|
||||
if !found {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeNotFound, "No agent found for task", nil)
|
||||
}
|
||||
|
||||
// Get agentctl client
|
||||
client := instance.GetAgentCtlClient()
|
||||
client := execution.GetAgentCtlClient()
|
||||
if client == nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Agent client not available", nil)
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/agentctl"
|
||||
agentctl "github.com/kandev/kandev/internal/agentctl/client"
|
||||
"github.com/kandev/kandev/internal/agent/docker"
|
||||
"github.com/kandev/kandev/internal/agent/registry"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
@@ -48,8 +48,8 @@ func NewContainerManager(dockerClient *docker.Client, networkName string, log *l
|
||||
}
|
||||
}
|
||||
|
||||
// LaunchContainer creates and starts a Docker container for an agent
|
||||
// Returns the container ID and agentctl client
|
||||
// LaunchContainer creates and starts a Docker container for an agent.
|
||||
// Returns the container ID and agentctl client pointing to the instance.
|
||||
func (cm *ContainerManager) LaunchContainer(ctx context.Context, config ContainerConfig) (string, *agentctl.Client, error) {
|
||||
// Build container config
|
||||
containerCfg, err := cm.buildContainerConfig(config)
|
||||
@@ -78,17 +78,60 @@ func (cm *ContainerManager) LaunchContainer(ctx context.Context, config Containe
|
||||
containerIP = "127.0.0.1"
|
||||
}
|
||||
|
||||
// Create agentctl client pointing to the container
|
||||
agentctlClient := agentctl.NewClient(containerIP, AgentCtlPort, cm.logger)
|
||||
// Create StandaloneCtl to communicate with the container's ControlServer
|
||||
ctl := agentctl.NewStandaloneCtl(containerIP, AgentCtlPort, cm.logger)
|
||||
|
||||
// Wait for agentctl to be healthy
|
||||
if err := cm.waitForHealth(ctx, ctl); err != nil {
|
||||
_ = cm.dockerClient.RemoveContainer(ctx, containerID, true)
|
||||
return "", nil, fmt.Errorf("agentctl health check failed: %w", err)
|
||||
}
|
||||
|
||||
// Create an instance via the control API (same flow as standalone mode)
|
||||
createReq := &agentctl.CreateInstanceRequest{
|
||||
ID: config.InstanceID,
|
||||
WorkspacePath: "/workspace",
|
||||
AgentCommand: "", // Agent command set via Configure endpoint later
|
||||
Env: config.Credentials,
|
||||
AutoStart: false,
|
||||
}
|
||||
|
||||
resp, err := ctl.CreateInstance(ctx, createReq)
|
||||
if err != nil {
|
||||
_ = cm.dockerClient.RemoveContainer(ctx, containerID, true)
|
||||
return "", nil, fmt.Errorf("failed to create instance in container: %w", err)
|
||||
}
|
||||
|
||||
// Create agentctl client pointing to the instance port
|
||||
agentctlClient := agentctl.NewClient(containerIP, resp.Port, cm.logger)
|
||||
|
||||
cm.logger.Info("docker container launched",
|
||||
zap.String("container_id", containerID),
|
||||
zap.String("container_ip", containerIP),
|
||||
zap.String("instance_id", config.InstanceID))
|
||||
zap.String("instance_id", config.InstanceID),
|
||||
zap.Int("instance_port", resp.Port))
|
||||
|
||||
return containerID, agentctlClient, nil
|
||||
}
|
||||
|
||||
// waitForHealth waits for agentctl to be healthy with retries
|
||||
func (cm *ContainerManager) waitForHealth(ctx context.Context, ctl *agentctl.StandaloneCtl) error {
|
||||
const maxRetries = 30
|
||||
const retryDelay = 500 * time.Millisecond
|
||||
|
||||
for i := 0; i < maxRetries; i++ {
|
||||
if err := ctl.Health(ctx); err == nil {
|
||||
return nil
|
||||
}
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
time.Sleep(retryDelay)
|
||||
}
|
||||
|
||||
return fmt.Errorf("agentctl not healthy after %d retries", maxRetries)
|
||||
}
|
||||
|
||||
// StopContainer stops and removes a Docker container
|
||||
func (cm *ContainerManager) StopContainer(ctx context.Context, containerID string, timeout time.Duration) error {
|
||||
if containerID == "" {
|
||||
@@ -256,3 +299,20 @@ func (cm *ContainerManager) buildEnvVars(config ContainerConfig) []string {
|
||||
|
||||
return env
|
||||
}
|
||||
|
||||
// ListManagedContainers returns all containers managed by kandev
|
||||
func (cm *ContainerManager) ListManagedContainers(ctx context.Context) ([]docker.ContainerInfo, error) {
|
||||
return cm.dockerClient.ListContainers(ctx, map[string]string{
|
||||
"kandev.managed": "true",
|
||||
})
|
||||
}
|
||||
|
||||
// GetContainerInfo returns information about a specific container
|
||||
func (cm *ContainerManager) GetContainerInfo(ctx context.Context, containerID string) (*docker.ContainerInfo, error) {
|
||||
return cm.dockerClient.GetContainerInfo(ctx, containerID)
|
||||
}
|
||||
|
||||
// RemoveContainer removes a container
|
||||
func (cm *ContainerManager) RemoveContainer(ctx context.Context, containerID string, force bool) error {
|
||||
return cm.dockerClient.RemoveContainer(ctx, containerID, force)
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import (
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/agentctl"
|
||||
agentctl "github.com/kandev/kandev/internal/agentctl/client"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/internal/events"
|
||||
"github.com/kandev/kandev/internal/events/bus"
|
||||
@@ -29,27 +29,27 @@ func NewEventPublisher(eventBus bus.EventBus, log *logger.Logger) *EventPublishe
|
||||
}
|
||||
|
||||
// PublishAgentEvent publishes an agent lifecycle event (started, stopped, ready, completed, failed).
|
||||
func (p *EventPublisher) PublishAgentEvent(ctx context.Context, eventType string, instance *AgentInstance) {
|
||||
func (p *EventPublisher) PublishAgentEvent(ctx context.Context, eventType string, execution *AgentExecution) {
|
||||
if p.eventBus == nil {
|
||||
return
|
||||
}
|
||||
|
||||
data := map[string]interface{}{
|
||||
"instance_id": instance.ID,
|
||||
"task_id": instance.TaskID,
|
||||
"agent_profile_id": instance.AgentProfileID,
|
||||
"container_id": instance.ContainerID,
|
||||
"status": string(instance.Status),
|
||||
"started_at": instance.StartedAt,
|
||||
"progress": instance.Progress,
|
||||
"error_message": instance.ErrorMessage,
|
||||
"instance_id": execution.ID,
|
||||
"task_id": execution.TaskID,
|
||||
"agent_profile_id": execution.AgentProfileID,
|
||||
"container_id": execution.ContainerID,
|
||||
"status": string(execution.Status),
|
||||
"started_at": execution.StartedAt,
|
||||
"progress": execution.Progress,
|
||||
"error_message": execution.ErrorMessage,
|
||||
}
|
||||
|
||||
if instance.FinishedAt != nil {
|
||||
data["finished_at"] = *instance.FinishedAt
|
||||
if execution.FinishedAt != nil {
|
||||
data["finished_at"] = *execution.FinishedAt
|
||||
}
|
||||
if instance.ExitCode != nil {
|
||||
data["exit_code"] = *instance.ExitCode
|
||||
if execution.ExitCode != nil {
|
||||
data["exit_code"] = *execution.ExitCode
|
||||
}
|
||||
|
||||
event := bus.NewEvent(eventType, "agent-manager", data)
|
||||
@@ -57,24 +57,24 @@ func (p *EventPublisher) PublishAgentEvent(ctx context.Context, eventType string
|
||||
if err := p.eventBus.Publish(ctx, eventType, event); err != nil {
|
||||
p.logger.Error("failed to publish event",
|
||||
zap.String("event_type", eventType),
|
||||
zap.String("instance_id", instance.ID),
|
||||
zap.String("instance_id", execution.ID),
|
||||
zap.Error(err))
|
||||
} else {
|
||||
p.logger.Debug("published agent event",
|
||||
zap.String("event_type", eventType),
|
||||
zap.String("instance_id", instance.ID))
|
||||
zap.String("instance_id", execution.ID))
|
||||
}
|
||||
}
|
||||
|
||||
// PublishACPSessionCreated publishes an event when an ACP session is created.
|
||||
func (p *EventPublisher) PublishACPSessionCreated(instance *AgentInstance, sessionID string) {
|
||||
func (p *EventPublisher) PublishACPSessionCreated(execution *AgentExecution, sessionID string) {
|
||||
if p.eventBus == nil || sessionID == "" {
|
||||
return
|
||||
}
|
||||
|
||||
data := map[string]interface{}{
|
||||
"task_id": instance.TaskID,
|
||||
"agent_instance_id": instance.ID,
|
||||
"task_id": execution.TaskID,
|
||||
"agent_instance_id": execution.ID,
|
||||
"acp_session_id": sessionID,
|
||||
}
|
||||
|
||||
@@ -82,13 +82,13 @@ func (p *EventPublisher) PublishACPSessionCreated(instance *AgentInstance, sessi
|
||||
if err := p.eventBus.Publish(context.Background(), events.AgentACPSessionCreated, event); err != nil {
|
||||
p.logger.Error("failed to publish ACP session event",
|
||||
zap.String("event_type", events.AgentACPSessionCreated),
|
||||
zap.String("instance_id", instance.ID),
|
||||
zap.String("instance_id", execution.ID),
|
||||
zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// PublishSessionUpdate publishes a session update to the event bus for WebSocket streaming.
|
||||
func (p *EventPublisher) PublishSessionUpdate(instance *AgentInstance, update agentctl.SessionUpdate) {
|
||||
func (p *EventPublisher) PublishSessionUpdate(execution *AgentExecution, update agentctl.SessionUpdate) {
|
||||
if p.eventBus == nil {
|
||||
return
|
||||
}
|
||||
@@ -133,32 +133,32 @@ func (p *EventPublisher) PublishSessionUpdate(instance *AgentInstance, update ag
|
||||
data := map[string]interface{}{
|
||||
"type": "session/update",
|
||||
"timestamp": time.Now().UTC().Format(time.RFC3339Nano),
|
||||
"agent_id": instance.ID,
|
||||
"task_id": instance.TaskID,
|
||||
"agent_id": execution.ID,
|
||||
"task_id": execution.TaskID,
|
||||
"session_id": update.SessionID,
|
||||
"data": updateData,
|
||||
}
|
||||
|
||||
event := bus.NewEvent(events.ACPMessage, "agent-manager", data)
|
||||
subject := events.BuildACPSubject(instance.TaskID)
|
||||
subject := events.BuildACPSubject(execution.TaskID)
|
||||
|
||||
if err := p.eventBus.Publish(context.Background(), subject, event); err != nil {
|
||||
p.logger.Error("failed to publish session update",
|
||||
zap.String("instance_id", instance.ID),
|
||||
zap.String("task_id", instance.TaskID),
|
||||
zap.String("instance_id", execution.ID),
|
||||
zap.String("task_id", execution.TaskID),
|
||||
zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// PublishGitStatus publishes a git status update to the event bus.
|
||||
func (p *EventPublisher) PublishGitStatus(instance *AgentInstance, update *agentctl.GitStatusUpdate) {
|
||||
func (p *EventPublisher) PublishGitStatus(execution *AgentExecution, update *agentctl.GitStatusUpdate) {
|
||||
if p.eventBus == nil {
|
||||
return
|
||||
}
|
||||
|
||||
data := map[string]interface{}{
|
||||
"task_id": instance.TaskID,
|
||||
"agent_id": instance.ID,
|
||||
"task_id": execution.TaskID,
|
||||
"agent_id": execution.ID,
|
||||
"branch": update.Branch,
|
||||
"remote_branch": update.RemoteBranch,
|
||||
"modified": update.Modified,
|
||||
@@ -173,44 +173,44 @@ func (p *EventPublisher) PublishGitStatus(instance *AgentInstance, update *agent
|
||||
}
|
||||
|
||||
event := bus.NewEvent(events.GitStatusUpdated, "agent-manager", data)
|
||||
subject := events.BuildGitStatusSubject(instance.TaskID)
|
||||
subject := events.BuildGitStatusSubject(execution.TaskID)
|
||||
|
||||
if err := p.eventBus.Publish(context.Background(), subject, event); err != nil {
|
||||
p.logger.Error("failed to publish git status event",
|
||||
zap.String("instance_id", instance.ID),
|
||||
zap.String("task_id", instance.TaskID),
|
||||
zap.String("instance_id", execution.ID),
|
||||
zap.String("task_id", execution.TaskID),
|
||||
zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// PublishFileChange publishes a file change notification to the event bus.
|
||||
func (p *EventPublisher) PublishFileChange(instance *AgentInstance, notification *agentctl.FileChangeNotification) {
|
||||
func (p *EventPublisher) PublishFileChange(execution *AgentExecution, notification *agentctl.FileChangeNotification) {
|
||||
if p.eventBus == nil {
|
||||
return
|
||||
}
|
||||
|
||||
data := map[string]interface{}{
|
||||
"task_id": instance.TaskID,
|
||||
"agent_id": instance.ID,
|
||||
"task_id": execution.TaskID,
|
||||
"agent_id": execution.ID,
|
||||
"path": notification.Path,
|
||||
"operation": notification.Operation,
|
||||
"timestamp": notification.Timestamp.Format(time.RFC3339Nano),
|
||||
}
|
||||
|
||||
event := bus.NewEvent(events.FileChangeNotified, "agent-manager", data)
|
||||
subject := events.BuildFileChangeSubject(instance.TaskID)
|
||||
subject := events.BuildFileChangeSubject(execution.TaskID)
|
||||
|
||||
if err := p.eventBus.Publish(context.Background(), subject, event); err != nil {
|
||||
p.logger.Error("failed to publish file change event",
|
||||
zap.String("instance_id", instance.ID),
|
||||
zap.String("task_id", instance.TaskID),
|
||||
zap.String("instance_id", execution.ID),
|
||||
zap.String("task_id", execution.TaskID),
|
||||
zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// PublishPromptComplete publishes a prompt_complete event when an agent finishes responding.
|
||||
// This is used to save the agent's response as a comment on the task.
|
||||
func (p *EventPublisher) PublishPromptComplete(instance *AgentInstance, agentMessage, reasoning, summary string) {
|
||||
func (p *EventPublisher) PublishPromptComplete(execution *AgentExecution, agentMessage, reasoning, summary string) {
|
||||
if p.eventBus == nil {
|
||||
return
|
||||
}
|
||||
@@ -223,8 +223,8 @@ func (p *EventPublisher) PublishPromptComplete(instance *AgentInstance, agentMes
|
||||
data := map[string]interface{}{
|
||||
"type": "prompt_complete",
|
||||
"timestamp": time.Now().UTC().Format(time.RFC3339Nano),
|
||||
"agent_id": instance.ID,
|
||||
"task_id": instance.TaskID,
|
||||
"agent_id": execution.ID,
|
||||
"task_id": execution.TaskID,
|
||||
"agent_message": agentMessage,
|
||||
}
|
||||
if reasoning != "" {
|
||||
@@ -236,18 +236,18 @@ func (p *EventPublisher) PublishPromptComplete(instance *AgentInstance, agentMes
|
||||
|
||||
event := bus.NewEvent(events.PromptComplete, "agent-manager", data)
|
||||
// Publish on task-specific subject so orchestrator can subscribe
|
||||
subject := events.PromptComplete + "." + instance.TaskID
|
||||
subject := events.PromptComplete + "." + execution.TaskID
|
||||
|
||||
if err := p.eventBus.Publish(context.Background(), subject, event); err != nil {
|
||||
p.logger.Error("failed to publish prompt_complete event",
|
||||
zap.String("instance_id", instance.ID),
|
||||
zap.String("task_id", instance.TaskID),
|
||||
zap.String("instance_id", execution.ID),
|
||||
zap.String("task_id", execution.TaskID),
|
||||
zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// PublishToolCall publishes a tool call start event (to be saved as a comment).
|
||||
func (p *EventPublisher) PublishToolCall(instance *AgentInstance, toolCallID, title, status string, args map[string]interface{}) {
|
||||
func (p *EventPublisher) PublishToolCall(execution *AgentExecution, toolCallID, title, status string, args map[string]interface{}) {
|
||||
if p.eventBus == nil {
|
||||
return
|
||||
}
|
||||
@@ -255,8 +255,8 @@ func (p *EventPublisher) PublishToolCall(instance *AgentInstance, toolCallID, ti
|
||||
data := map[string]interface{}{
|
||||
"type": "tool_call",
|
||||
"timestamp": time.Now().UTC().Format(time.RFC3339Nano),
|
||||
"agent_id": instance.ID,
|
||||
"task_id": instance.TaskID,
|
||||
"agent_id": execution.ID,
|
||||
"task_id": execution.TaskID,
|
||||
"tool_call_id": toolCallID,
|
||||
"title": title,
|
||||
"status": status,
|
||||
@@ -266,23 +266,23 @@ func (p *EventPublisher) PublishToolCall(instance *AgentInstance, toolCallID, ti
|
||||
}
|
||||
|
||||
event := bus.NewEvent(events.ToolCallStarted, "agent-manager", data)
|
||||
subject := events.ToolCallStarted + "." + instance.TaskID
|
||||
subject := events.ToolCallStarted + "." + execution.TaskID
|
||||
|
||||
if err := p.eventBus.Publish(context.Background(), subject, event); err != nil {
|
||||
p.logger.Error("failed to publish tool_call event",
|
||||
zap.String("instance_id", instance.ID),
|
||||
zap.String("task_id", instance.TaskID),
|
||||
zap.String("instance_id", execution.ID),
|
||||
zap.String("task_id", execution.TaskID),
|
||||
zap.Error(err))
|
||||
} else {
|
||||
p.logger.Debug("published tool_call event",
|
||||
zap.String("task_id", instance.TaskID),
|
||||
zap.String("task_id", execution.TaskID),
|
||||
zap.String("tool_call_id", toolCallID),
|
||||
zap.String("title", title))
|
||||
}
|
||||
}
|
||||
|
||||
// PublishToolCallComplete publishes a tool call completion event from a SessionUpdate.
|
||||
func (p *EventPublisher) PublishToolCallComplete(instance *AgentInstance, update agentctl.SessionUpdate) {
|
||||
func (p *EventPublisher) PublishToolCallComplete(execution *AgentExecution, update agentctl.SessionUpdate) {
|
||||
if p.eventBus == nil {
|
||||
return
|
||||
}
|
||||
@@ -290,25 +290,25 @@ func (p *EventPublisher) PublishToolCallComplete(instance *AgentInstance, update
|
||||
data := map[string]interface{}{
|
||||
"type": "tool_call_complete",
|
||||
"timestamp": time.Now().UTC().Format(time.RFC3339Nano),
|
||||
"agent_id": instance.ID,
|
||||
"task_id": instance.TaskID,
|
||||
"agent_id": execution.ID,
|
||||
"task_id": execution.TaskID,
|
||||
"tool_call_id": update.ToolCallID,
|
||||
"status": update.ToolStatus,
|
||||
}
|
||||
|
||||
event := bus.NewEvent(events.ToolCallComplete, "agent-manager", data)
|
||||
subject := events.ToolCallComplete + "." + instance.TaskID
|
||||
subject := events.ToolCallComplete + "." + execution.TaskID
|
||||
|
||||
if err := p.eventBus.Publish(context.Background(), subject, event); err != nil {
|
||||
p.logger.Error("failed to publish tool_call_complete event",
|
||||
zap.String("instance_id", instance.ID),
|
||||
zap.String("task_id", instance.TaskID),
|
||||
zap.String("instance_id", execution.ID),
|
||||
zap.String("task_id", execution.TaskID),
|
||||
zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// PublishPermissionRequest publishes a permission request event.
|
||||
func (p *EventPublisher) PublishPermissionRequest(instance *AgentInstance, notification *agentctl.PermissionNotification) {
|
||||
func (p *EventPublisher) PublishPermissionRequest(execution *AgentExecution, notification *agentctl.PermissionNotification) {
|
||||
if p.eventBus == nil {
|
||||
return
|
||||
}
|
||||
@@ -325,8 +325,8 @@ func (p *EventPublisher) PublishPermissionRequest(instance *AgentInstance, notif
|
||||
|
||||
data := map[string]interface{}{
|
||||
"type": "permission_request",
|
||||
"task_id": instance.TaskID,
|
||||
"agent_instance_id": instance.ID,
|
||||
"task_id": execution.TaskID,
|
||||
"agent_instance_id": execution.ID,
|
||||
"pending_id": notification.PendingID,
|
||||
"session_id": notification.SessionID,
|
||||
"tool_call_id": notification.ToolCallID,
|
||||
@@ -337,16 +337,16 @@ func (p *EventPublisher) PublishPermissionRequest(instance *AgentInstance, notif
|
||||
}
|
||||
|
||||
event := bus.NewEvent(events.ACPMessage, "agent-manager", data)
|
||||
subject := events.BuildACPSubject(instance.TaskID)
|
||||
subject := events.BuildACPSubject(execution.TaskID)
|
||||
|
||||
if err := p.eventBus.Publish(context.Background(), subject, event); err != nil {
|
||||
p.logger.Error("failed to publish permission_request event",
|
||||
zap.String("instance_id", instance.ID),
|
||||
zap.String("task_id", instance.TaskID),
|
||||
zap.String("instance_id", execution.ID),
|
||||
zap.String("task_id", execution.TaskID),
|
||||
zap.Error(err))
|
||||
} else {
|
||||
p.logger.Info("published permission_request event",
|
||||
zap.String("task_id", instance.TaskID),
|
||||
zap.String("task_id", execution.TaskID),
|
||||
zap.String("pending_id", notification.PendingID),
|
||||
zap.String("title", notification.Title))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,193 @@
|
||||
// Package lifecycle manages agent execution lifecycles including tracking,
|
||||
// state transitions, and cleanup.
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"sync"
|
||||
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
)
|
||||
|
||||
// ExecutionStore provides thread-safe storage and retrieval of agent executions.
|
||||
// It maintains three indexes for efficient lookup by execution ID, task ID, and container ID.
|
||||
type ExecutionStore struct {
|
||||
executions map[string]*AgentExecution
|
||||
byTask map[string]string // taskID -> executionID
|
||||
byContainer map[string]string // containerID -> executionID
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
// NewExecutionStore creates a new ExecutionStore with initialized maps.
|
||||
func NewExecutionStore() *ExecutionStore {
|
||||
return &ExecutionStore{
|
||||
executions: make(map[string]*AgentExecution),
|
||||
byTask: make(map[string]string),
|
||||
byContainer: make(map[string]string),
|
||||
}
|
||||
}
|
||||
|
||||
// Add adds an agent execution to all tracking maps.
|
||||
// The execution must have a valid ID. TaskID and ContainerID are optional
|
||||
// but will be indexed if present.
|
||||
func (s *ExecutionStore) Add(execution *AgentExecution) {
|
||||
if execution == nil || execution.ID == "" {
|
||||
return
|
||||
}
|
||||
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
s.executions[execution.ID] = execution
|
||||
|
||||
if execution.TaskID != "" {
|
||||
s.byTask[execution.TaskID] = execution.ID
|
||||
}
|
||||
|
||||
if execution.ContainerID != "" {
|
||||
s.byContainer[execution.ContainerID] = execution.ID
|
||||
}
|
||||
}
|
||||
|
||||
// Remove removes an agent execution from all tracking maps.
|
||||
func (s *ExecutionStore) Remove(executionID string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
execution, exists := s.executions[executionID]
|
||||
if !exists {
|
||||
return
|
||||
}
|
||||
|
||||
// Remove from secondary indexes
|
||||
if execution.TaskID != "" {
|
||||
delete(s.byTask, execution.TaskID)
|
||||
}
|
||||
if execution.ContainerID != "" {
|
||||
delete(s.byContainer, execution.ContainerID)
|
||||
}
|
||||
|
||||
// Remove from primary map
|
||||
delete(s.executions, executionID)
|
||||
}
|
||||
|
||||
// Get returns an agent execution by its ID.
|
||||
func (s *ExecutionStore) Get(executionID string) (*AgentExecution, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
execution, exists := s.executions[executionID]
|
||||
return execution, exists
|
||||
}
|
||||
|
||||
// GetByTaskID returns the agent execution associated with a task ID.
|
||||
func (s *ExecutionStore) GetByTaskID(taskID string) (*AgentExecution, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
executionID, exists := s.byTask[taskID]
|
||||
if !exists {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
execution, exists := s.executions[executionID]
|
||||
return execution, exists
|
||||
}
|
||||
|
||||
// GetByContainerID returns the agent execution associated with a container ID.
|
||||
func (s *ExecutionStore) GetByContainerID(containerID string) (*AgentExecution, bool) {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
executionID, exists := s.byContainer[containerID]
|
||||
if !exists {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
execution, exists := s.executions[executionID]
|
||||
return execution, exists
|
||||
}
|
||||
|
||||
// List returns all tracked agent executions.
|
||||
func (s *ExecutionStore) List() []*AgentExecution {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
result := make([]*AgentExecution, 0, len(s.executions))
|
||||
for _, execution := range s.executions {
|
||||
result = append(result, execution)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
// UpdateStatus updates the status of an agent execution.
|
||||
func (s *ExecutionStore) UpdateStatus(executionID string, status v1.AgentStatus) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if execution, exists := s.executions[executionID]; exists {
|
||||
execution.Status = status
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateProgress updates the progress of an agent execution.
|
||||
func (s *ExecutionStore) UpdateProgress(executionID string, progress int) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if execution, exists := s.executions[executionID]; exists {
|
||||
execution.Progress = progress
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateError updates the error message of an agent execution and sets its status to failed.
|
||||
func (s *ExecutionStore) UpdateError(executionID string, errorMsg string) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if execution, exists := s.executions[executionID]; exists {
|
||||
execution.ErrorMessage = errorMsg
|
||||
execution.Status = v1.AgentStatusFailed
|
||||
}
|
||||
}
|
||||
|
||||
// UpdateMetadata updates the metadata of an agent execution using the provided function.
|
||||
func (s *ExecutionStore) UpdateMetadata(executionID string, updateFn func(metadata map[string]interface{}) map[string]interface{}) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if execution, exists := s.executions[executionID]; exists {
|
||||
if execution.Metadata == nil {
|
||||
execution.Metadata = make(map[string]interface{})
|
||||
}
|
||||
execution.Metadata = updateFn(execution.Metadata)
|
||||
}
|
||||
}
|
||||
|
||||
// WithLock executes a function with the store lock held, providing access to the execution.
|
||||
// Returns false if the execution doesn't exist.
|
||||
func (s *ExecutionStore) WithLock(executionID string, fn func(execution *AgentExecution)) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
execution, exists := s.executions[executionID]
|
||||
if !exists {
|
||||
return false
|
||||
}
|
||||
fn(execution)
|
||||
return true
|
||||
}
|
||||
|
||||
// WithRLock executes a function with the store read lock held, providing access to the execution.
|
||||
// Returns false if the execution doesn't exist.
|
||||
func (s *ExecutionStore) WithRLock(executionID string, fn func(execution *AgentExecution)) bool {
|
||||
s.mu.RLock()
|
||||
defer s.mu.RUnlock()
|
||||
|
||||
execution, exists := s.executions[executionID]
|
||||
if !exists {
|
||||
return false
|
||||
}
|
||||
fn(execution)
|
||||
return true
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -9,21 +9,11 @@ import (
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/docker"
|
||||
"github.com/kandev/kandev/internal/agent/registry"
|
||||
"github.com/kandev/kandev/internal/common/config"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/internal/events/bus"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
)
|
||||
|
||||
// testAgentConfig returns a default AgentConfig for testing (docker mode)
|
||||
func testAgentConfig() config.AgentConfig {
|
||||
return config.AgentConfig{
|
||||
Runtime: "docker",
|
||||
StandaloneHost: "localhost",
|
||||
StandalonePort: 9999,
|
||||
}
|
||||
}
|
||||
|
||||
// MockDockerClient implements a mock for the docker.Client for testing
|
||||
type MockDockerClient struct {
|
||||
CreateContainerFn func(ctx context.Context, cfg docker.ContainerConfig) (string, error)
|
||||
@@ -135,30 +125,54 @@ func newTestRegistry() *registry.Registry {
|
||||
return reg
|
||||
}
|
||||
|
||||
func TestNewManager(t *testing.T) {
|
||||
// MockCredentialsManager implements CredentialsManager for testing
|
||||
type MockCredentialsManager struct{}
|
||||
|
||||
func (m *MockCredentialsManager) GetCredentialValue(ctx context.Context, key string) (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// MockProfileResolver implements ProfileResolver for testing
|
||||
type MockProfileResolver struct{}
|
||||
|
||||
func (m *MockProfileResolver) ResolveProfile(ctx context.Context, profileID string) (*AgentProfileInfo, error) {
|
||||
return &AgentProfileInfo{
|
||||
ProfileID: profileID,
|
||||
ProfileName: "Test Profile",
|
||||
AgentID: "augment-agent",
|
||||
AgentName: "auggie",
|
||||
Model: "claude-sonnet-4-20250514",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// newTestManager creates a Manager for testing with mock dependencies
|
||||
func newTestManager() *Manager {
|
||||
log := newTestLogger()
|
||||
reg := newTestRegistry()
|
||||
eventBus := &MockEventBus{}
|
||||
credsMgr := &MockCredentialsManager{}
|
||||
profileResolver := &MockProfileResolver{}
|
||||
// Pass nil for runtime and containerManager - tests don't need them
|
||||
return NewManager(reg, eventBus, nil, nil, credsMgr, profileResolver, log)
|
||||
}
|
||||
|
||||
mgr := NewManager(nil, reg, eventBus, testAgentConfig(), log)
|
||||
func TestNewManager(t *testing.T) {
|
||||
mgr := newTestManager()
|
||||
|
||||
if mgr == nil {
|
||||
t.Fatal("expected non-nil manager")
|
||||
}
|
||||
if len(mgr.instances) != 0 {
|
||||
t.Errorf("expected empty instances, got %d", len(mgr.instances))
|
||||
if len(mgr.ListExecutions()) != 0 {
|
||||
t.Errorf("expected empty executions, got %d", len(mgr.ListExecutions()))
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_GetInstance(t *testing.T) {
|
||||
log := newTestLogger()
|
||||
reg := newTestRegistry()
|
||||
eventBus := &MockEventBus{}
|
||||
mgr := NewManager(nil, reg, eventBus, testAgentConfig(), log)
|
||||
func TestManager_GetExecution(t *testing.T) {
|
||||
mgr := newTestManager()
|
||||
|
||||
// Manually add an instance for testing
|
||||
instance := &AgentInstance{
|
||||
ID: "test-instance-id",
|
||||
// Manually add an execution for testing
|
||||
execution := &AgentExecution{
|
||||
ID: "test-execution-id",
|
||||
TaskID: "test-task-id",
|
||||
AgentProfileID: "test-agent",
|
||||
ContainerID: "container-123",
|
||||
@@ -166,36 +180,29 @@ func TestManager_GetInstance(t *testing.T) {
|
||||
StartedAt: time.Now(),
|
||||
}
|
||||
|
||||
mgr.mu.Lock()
|
||||
mgr.instances[instance.ID] = instance
|
||||
mgr.byTask[instance.TaskID] = instance.ID
|
||||
mgr.byContainer[instance.ContainerID] = instance.ID
|
||||
mgr.mu.Unlock()
|
||||
mgr.executionStore.Add(execution)
|
||||
|
||||
// Test GetInstance
|
||||
got, found := mgr.GetInstance("test-instance-id")
|
||||
// Test GetExecution
|
||||
got, found := mgr.GetExecution("test-execution-id")
|
||||
if !found {
|
||||
t.Fatal("expected to find instance")
|
||||
t.Fatal("expected to find execution")
|
||||
}
|
||||
if got.ID != instance.ID {
|
||||
t.Errorf("expected ID %q, got %q", instance.ID, got.ID)
|
||||
if got.ID != execution.ID {
|
||||
t.Errorf("expected ID %q, got %q", execution.ID, got.ID)
|
||||
}
|
||||
|
||||
// Test not found
|
||||
_, found = mgr.GetInstance("non-existent")
|
||||
_, found = mgr.GetExecution("non-existent")
|
||||
if found {
|
||||
t.Error("expected not to find instance")
|
||||
t.Error("expected not to find execution")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_GetInstanceByTaskID(t *testing.T) {
|
||||
log := newTestLogger()
|
||||
reg := newTestRegistry()
|
||||
eventBus := &MockEventBus{}
|
||||
mgr := NewManager(nil, reg, eventBus, testAgentConfig(), log)
|
||||
func TestManager_GetExecutionByTaskID(t *testing.T) {
|
||||
mgr := newTestManager()
|
||||
|
||||
instance := &AgentInstance{
|
||||
ID: "test-instance-id",
|
||||
execution := &AgentExecution{
|
||||
ID: "test-execution-id",
|
||||
TaskID: "test-task-id",
|
||||
AgentProfileID: "test-agent",
|
||||
ContainerID: "container-123",
|
||||
@@ -203,35 +210,29 @@ func TestManager_GetInstanceByTaskID(t *testing.T) {
|
||||
StartedAt: time.Now(),
|
||||
}
|
||||
|
||||
mgr.mu.Lock()
|
||||
mgr.instances[instance.ID] = instance
|
||||
mgr.byTask[instance.TaskID] = instance.ID
|
||||
mgr.mu.Unlock()
|
||||
mgr.executionStore.Add(execution)
|
||||
|
||||
// Test GetInstanceByTaskID
|
||||
got, found := mgr.GetInstanceByTaskID("test-task-id")
|
||||
// Test GetExecutionByTaskID
|
||||
got, found := mgr.GetExecutionByTaskID("test-task-id")
|
||||
if !found {
|
||||
t.Fatal("expected to find instance")
|
||||
t.Fatal("expected to find execution")
|
||||
}
|
||||
if got.TaskID != instance.TaskID {
|
||||
t.Errorf("expected TaskID %q, got %q", instance.TaskID, got.TaskID)
|
||||
if got.TaskID != execution.TaskID {
|
||||
t.Errorf("expected TaskID %q, got %q", execution.TaskID, got.TaskID)
|
||||
}
|
||||
|
||||
// Test not found
|
||||
_, found = mgr.GetInstanceByTaskID("non-existent")
|
||||
_, found = mgr.GetExecutionByTaskID("non-existent")
|
||||
if found {
|
||||
t.Error("expected not to find instance")
|
||||
t.Error("expected not to find execution")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_GetInstanceByContainerID(t *testing.T) {
|
||||
log := newTestLogger()
|
||||
reg := newTestRegistry()
|
||||
eventBus := &MockEventBus{}
|
||||
mgr := NewManager(nil, reg, eventBus, testAgentConfig(), log)
|
||||
func TestManager_GetExecutionByContainerID(t *testing.T) {
|
||||
mgr := newTestManager()
|
||||
|
||||
instance := &AgentInstance{
|
||||
ID: "test-instance-id",
|
||||
execution := &AgentExecution{
|
||||
ID: "test-execution-id",
|
||||
TaskID: "test-task-id",
|
||||
AgentProfileID: "test-agent",
|
||||
ContainerID: "container-123",
|
||||
@@ -239,74 +240,61 @@ func TestManager_GetInstanceByContainerID(t *testing.T) {
|
||||
StartedAt: time.Now(),
|
||||
}
|
||||
|
||||
mgr.mu.Lock()
|
||||
mgr.instances[instance.ID] = instance
|
||||
mgr.byContainer[instance.ContainerID] = instance.ID
|
||||
mgr.mu.Unlock()
|
||||
mgr.executionStore.Add(execution)
|
||||
|
||||
// Test GetInstanceByContainerID
|
||||
got, found := mgr.GetInstanceByContainerID("container-123")
|
||||
// Test GetExecutionByContainerID
|
||||
got, found := mgr.GetExecutionByContainerID("container-123")
|
||||
if !found {
|
||||
t.Fatal("expected to find instance")
|
||||
t.Fatal("expected to find execution")
|
||||
}
|
||||
if got.ContainerID != instance.ContainerID {
|
||||
t.Errorf("expected ContainerID %q, got %q", instance.ContainerID, got.ContainerID)
|
||||
if got.ContainerID != execution.ContainerID {
|
||||
t.Errorf("expected ContainerID %q, got %q", execution.ContainerID, got.ContainerID)
|
||||
}
|
||||
|
||||
// Test not found
|
||||
_, found = mgr.GetInstanceByContainerID("non-existent")
|
||||
_, found = mgr.GetExecutionByContainerID("non-existent")
|
||||
if found {
|
||||
t.Error("expected not to find instance")
|
||||
t.Error("expected not to find execution")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_ListInstances(t *testing.T) {
|
||||
log := newTestLogger()
|
||||
reg := newTestRegistry()
|
||||
eventBus := &MockEventBus{}
|
||||
mgr := NewManager(nil, reg, eventBus, testAgentConfig(), log)
|
||||
func TestManager_ListExecutions(t *testing.T) {
|
||||
mgr := newTestManager()
|
||||
|
||||
// Empty list
|
||||
list := mgr.ListInstances()
|
||||
list := mgr.ListExecutions()
|
||||
if len(list) != 0 {
|
||||
t.Errorf("expected empty list, got %d", len(list))
|
||||
}
|
||||
|
||||
// Add instances
|
||||
mgr.mu.Lock()
|
||||
mgr.instances["instance-1"] = &AgentInstance{ID: "instance-1", TaskID: "task-1", Status: v1.AgentStatusRunning}
|
||||
mgr.instances["instance-2"] = &AgentInstance{ID: "instance-2", TaskID: "task-2", Status: v1.AgentStatusCompleted}
|
||||
mgr.mu.Unlock()
|
||||
// Add executions
|
||||
mgr.executionStore.Add(&AgentExecution{ID: "execution-1", TaskID: "task-1", Status: v1.AgentStatusRunning})
|
||||
mgr.executionStore.Add(&AgentExecution{ID: "execution-2", TaskID: "task-2", Status: v1.AgentStatusCompleted})
|
||||
|
||||
list = mgr.ListInstances()
|
||||
list = mgr.ListExecutions()
|
||||
if len(list) != 2 {
|
||||
t.Errorf("expected 2 instances, got %d", len(list))
|
||||
t.Errorf("expected 2 executions, got %d", len(list))
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_UpdateStatus(t *testing.T) {
|
||||
log := newTestLogger()
|
||||
reg := newTestRegistry()
|
||||
eventBus := &MockEventBus{}
|
||||
mgr := NewManager(nil, reg, eventBus, testAgentConfig(), log)
|
||||
mgr := newTestManager()
|
||||
|
||||
instance := &AgentInstance{
|
||||
ID: "test-instance-id",
|
||||
execution := &AgentExecution{
|
||||
ID: "test-execution-id",
|
||||
TaskID: "test-task-id",
|
||||
Status: v1.AgentStatusRunning,
|
||||
}
|
||||
|
||||
mgr.mu.Lock()
|
||||
mgr.instances[instance.ID] = instance
|
||||
mgr.mu.Unlock()
|
||||
mgr.executionStore.Add(execution)
|
||||
|
||||
// Test UpdateStatus
|
||||
err := mgr.UpdateStatus("test-instance-id", v1.AgentStatusCompleted)
|
||||
err := mgr.UpdateStatus("test-execution-id", v1.AgentStatusCompleted)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
got, _ := mgr.GetInstance("test-instance-id")
|
||||
got, _ := mgr.GetExecution("test-execution-id")
|
||||
if got.Status != v1.AgentStatusCompleted {
|
||||
t.Errorf("expected status %v, got %v", v1.AgentStatusCompleted, got.Status)
|
||||
}
|
||||
@@ -314,34 +302,29 @@ func TestManager_UpdateStatus(t *testing.T) {
|
||||
// Test not found
|
||||
err = mgr.UpdateStatus("non-existent", v1.AgentStatusCompleted)
|
||||
if err == nil {
|
||||
t.Error("expected error for non-existent instance")
|
||||
t.Error("expected error for non-existent execution")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_UpdateProgress(t *testing.T) {
|
||||
log := newTestLogger()
|
||||
reg := newTestRegistry()
|
||||
eventBus := &MockEventBus{}
|
||||
mgr := NewManager(nil, reg, eventBus, testAgentConfig(), log)
|
||||
mgr := newTestManager()
|
||||
|
||||
instance := &AgentInstance{
|
||||
ID: "test-instance-id",
|
||||
execution := &AgentExecution{
|
||||
ID: "test-execution-id",
|
||||
TaskID: "test-task-id",
|
||||
Status: v1.AgentStatusRunning,
|
||||
Progress: 0,
|
||||
}
|
||||
|
||||
mgr.mu.Lock()
|
||||
mgr.instances[instance.ID] = instance
|
||||
mgr.mu.Unlock()
|
||||
mgr.executionStore.Add(execution)
|
||||
|
||||
// Test UpdateProgress
|
||||
err := mgr.UpdateProgress("test-instance-id", 50)
|
||||
err := mgr.UpdateProgress("test-execution-id", 50)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
got, _ := mgr.GetInstance("test-instance-id")
|
||||
got, _ := mgr.GetExecution("test-execution-id")
|
||||
if got.Progress != 50 {
|
||||
t.Errorf("expected progress 50, got %d", got.Progress)
|
||||
}
|
||||
@@ -349,18 +332,15 @@ func TestManager_UpdateProgress(t *testing.T) {
|
||||
// Test not found
|
||||
err = mgr.UpdateProgress("non-existent", 50)
|
||||
if err == nil {
|
||||
t.Error("expected error for non-existent instance")
|
||||
t.Error("expected error for non-existent execution")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_MarkCompleted_Success(t *testing.T) {
|
||||
log := newTestLogger()
|
||||
reg := newTestRegistry()
|
||||
eventBus := &MockEventBus{}
|
||||
mgr := NewManager(nil, reg, eventBus, testAgentConfig(), log)
|
||||
mgr := newTestManager()
|
||||
|
||||
instance := &AgentInstance{
|
||||
ID: "test-instance-id",
|
||||
execution := &AgentExecution{
|
||||
ID: "test-execution-id",
|
||||
TaskID: "test-task-id",
|
||||
AgentProfileID: "test-agent",
|
||||
ContainerID: "container-123",
|
||||
@@ -369,17 +349,15 @@ func TestManager_MarkCompleted_Success(t *testing.T) {
|
||||
Progress: 50,
|
||||
}
|
||||
|
||||
mgr.mu.Lock()
|
||||
mgr.instances[instance.ID] = instance
|
||||
mgr.mu.Unlock()
|
||||
mgr.executionStore.Add(execution)
|
||||
|
||||
// Mark as completed successfully (exit code 0)
|
||||
err := mgr.MarkCompleted("test-instance-id", 0, "")
|
||||
err := mgr.MarkCompleted("test-execution-id", 0, "")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
got, _ := mgr.GetInstance("test-instance-id")
|
||||
got, _ := mgr.GetExecution("test-execution-id")
|
||||
if got.Status != v1.AgentStatusCompleted {
|
||||
t.Errorf("expected status %v, got %v", v1.AgentStatusCompleted, got.Status)
|
||||
}
|
||||
@@ -395,13 +373,10 @@ func TestManager_MarkCompleted_Success(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestManager_MarkCompleted_Failure(t *testing.T) {
|
||||
log := newTestLogger()
|
||||
reg := newTestRegistry()
|
||||
eventBus := &MockEventBus{}
|
||||
mgr := NewManager(nil, reg, eventBus, testAgentConfig(), log)
|
||||
mgr := newTestManager()
|
||||
|
||||
instance := &AgentInstance{
|
||||
ID: "test-instance-id",
|
||||
execution := &AgentExecution{
|
||||
ID: "test-execution-id",
|
||||
TaskID: "test-task-id",
|
||||
AgentProfileID: "test-agent",
|
||||
ContainerID: "container-123",
|
||||
@@ -409,17 +384,15 @@ func TestManager_MarkCompleted_Failure(t *testing.T) {
|
||||
StartedAt: time.Now(),
|
||||
}
|
||||
|
||||
mgr.mu.Lock()
|
||||
mgr.instances[instance.ID] = instance
|
||||
mgr.mu.Unlock()
|
||||
mgr.executionStore.Add(execution)
|
||||
|
||||
// Mark as failed
|
||||
err := mgr.MarkCompleted("test-instance-id", 1, "process failed")
|
||||
err := mgr.MarkCompleted("test-execution-id", 1, "process failed")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
got, _ := mgr.GetInstance("test-instance-id")
|
||||
got, _ := mgr.GetExecution("test-execution-id")
|
||||
if got.Status != v1.AgentStatusFailed {
|
||||
t.Errorf("expected status %v, got %v", v1.AgentStatusFailed, got.Status)
|
||||
}
|
||||
@@ -432,58 +405,45 @@ func TestManager_MarkCompleted_Failure(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestManager_MarkCompleted_NotFound(t *testing.T) {
|
||||
log := newTestLogger()
|
||||
reg := newTestRegistry()
|
||||
eventBus := &MockEventBus{}
|
||||
mgr := NewManager(nil, reg, eventBus, testAgentConfig(), log)
|
||||
mgr := newTestManager()
|
||||
|
||||
err := mgr.MarkCompleted("non-existent", 0, "")
|
||||
if err == nil {
|
||||
t.Error("expected error for non-existent instance")
|
||||
t.Error("expected error for non-existent execution")
|
||||
}
|
||||
}
|
||||
|
||||
func TestManager_RemoveInstance(t *testing.T) {
|
||||
log := newTestLogger()
|
||||
reg := newTestRegistry()
|
||||
eventBus := &MockEventBus{}
|
||||
mgr := NewManager(nil, reg, eventBus, testAgentConfig(), log)
|
||||
func TestManager_RemoveExecution(t *testing.T) {
|
||||
mgr := newTestManager()
|
||||
|
||||
instance := &AgentInstance{
|
||||
ID: "test-instance-id",
|
||||
execution := &AgentExecution{
|
||||
ID: "test-execution-id",
|
||||
TaskID: "test-task-id",
|
||||
ContainerID: "container-123",
|
||||
}
|
||||
|
||||
mgr.mu.Lock()
|
||||
mgr.instances[instance.ID] = instance
|
||||
mgr.byTask[instance.TaskID] = instance.ID
|
||||
mgr.byContainer[instance.ContainerID] = instance.ID
|
||||
mgr.mu.Unlock()
|
||||
mgr.executionStore.Add(execution)
|
||||
|
||||
// Remove instance
|
||||
mgr.RemoveInstance("test-instance-id")
|
||||
// Remove execution
|
||||
mgr.RemoveExecution("test-execution-id")
|
||||
|
||||
// Verify it's gone from all maps
|
||||
if _, found := mgr.GetInstance("test-instance-id"); found {
|
||||
t.Error("instance should be removed from instances map")
|
||||
if _, found := mgr.GetExecution("test-execution-id"); found {
|
||||
t.Error("execution should be removed from executions map")
|
||||
}
|
||||
if _, found := mgr.GetInstanceByTaskID("test-task-id"); found {
|
||||
t.Error("instance should be removed from byTask map")
|
||||
if _, found := mgr.GetExecutionByTaskID("test-task-id"); found {
|
||||
t.Error("execution should be removed from byTask map")
|
||||
}
|
||||
if _, found := mgr.GetInstanceByContainerID("container-123"); found {
|
||||
t.Error("instance should be removed from byContainer map")
|
||||
if _, found := mgr.GetExecutionByContainerID("container-123"); found {
|
||||
t.Error("execution should be removed from byContainer map")
|
||||
}
|
||||
|
||||
// Remove non-existent should not panic
|
||||
mgr.RemoveInstance("non-existent")
|
||||
mgr.RemoveExecution("non-existent")
|
||||
}
|
||||
|
||||
func TestManager_StartStop(t *testing.T) {
|
||||
log := newTestLogger()
|
||||
reg := newTestRegistry()
|
||||
eventBus := &MockEventBus{}
|
||||
mgr := NewManager(nil, reg, eventBus, testAgentConfig(), log)
|
||||
mgr := newTestManager()
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
// Package lifecycle provides agent runtime abstractions.
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
agentctl "github.com/kandev/kandev/internal/agentctl/client"
|
||||
"github.com/kandev/kandev/internal/agent/registry"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
)
|
||||
|
||||
// Runtime abstracts the agent execution environment (Docker, Standalone, K8s, SSH, etc.)
|
||||
// Each runtime is responsible for creating and managing agentctl instances.
|
||||
// Agent subprocess launching is handled separately via agentctl client methods.
|
||||
type Runtime interface {
|
||||
// Name returns the runtime identifier (e.g., "docker", "standalone", "k8s")
|
||||
Name() string
|
||||
|
||||
// HealthCheck verifies the runtime is available and operational
|
||||
HealthCheck(ctx context.Context) error
|
||||
|
||||
// CreateInstance creates a new agentctl instance for a task.
|
||||
// This starts the agentctl process/container with workspace access (shell, git, files).
|
||||
// Agent subprocess is NOT started - use agentctl.Client.ConfigureAgent() + Start().
|
||||
CreateInstance(ctx context.Context, req *RuntimeCreateRequest) (*RuntimeInstance, error)
|
||||
|
||||
// StopInstance stops an agentctl instance.
|
||||
StopInstance(ctx context.Context, instance *RuntimeInstance, force bool) error
|
||||
|
||||
// RecoverInstances discovers and recovers instances that were running before a restart.
|
||||
// Returns recovered instances that can be re-tracked by the manager.
|
||||
RecoverInstances(ctx context.Context) ([]*RuntimeInstance, error)
|
||||
}
|
||||
|
||||
// RuntimeCreateRequest contains parameters for creating an agentctl instance.
|
||||
type RuntimeCreateRequest struct {
|
||||
InstanceID string
|
||||
TaskID string
|
||||
AgentProfileID string
|
||||
WorkspacePath string
|
||||
Protocol string
|
||||
Env map[string]string
|
||||
Metadata map[string]interface{}
|
||||
// Docker-specific
|
||||
AgentConfig *registry.AgentTypeConfig
|
||||
MainRepoGitDir string
|
||||
WorktreeID string
|
||||
WorktreeBranch string
|
||||
}
|
||||
|
||||
// RuntimeInstance represents an agentctl instance created by a runtime.
|
||||
// This is returned by the runtime and contains enough info to build an AgentExecution.
|
||||
type RuntimeInstance struct {
|
||||
// Core identifiers
|
||||
InstanceID string
|
||||
TaskID string
|
||||
|
||||
// Agentctl client for communicating with this instance
|
||||
Client *agentctl.Client
|
||||
|
||||
// Runtime-specific identifiers (only one set is populated)
|
||||
ContainerID string // Docker
|
||||
ContainerIP string // Docker
|
||||
StandaloneInstanceID string // Standalone
|
||||
StandalonePort int // Standalone
|
||||
|
||||
// Common fields
|
||||
WorkspacePath string
|
||||
Metadata map[string]interface{}
|
||||
}
|
||||
|
||||
// ToAgentExecution converts a RuntimeInstance to an AgentExecution.
|
||||
func (ri *RuntimeInstance) ToAgentExecution(req *RuntimeCreateRequest) *AgentExecution {
|
||||
metadata := req.Metadata
|
||||
if metadata == nil {
|
||||
metadata = make(map[string]interface{})
|
||||
}
|
||||
// Merge runtime metadata
|
||||
for k, v := range ri.Metadata {
|
||||
metadata[k] = v
|
||||
}
|
||||
|
||||
workspacePath := ri.WorkspacePath
|
||||
if workspacePath == "" {
|
||||
workspacePath = req.WorkspacePath
|
||||
}
|
||||
|
||||
return &AgentExecution{
|
||||
ID: ri.InstanceID,
|
||||
TaskID: req.TaskID,
|
||||
AgentProfileID: req.AgentProfileID,
|
||||
ContainerID: ri.ContainerID,
|
||||
ContainerIP: ri.ContainerIP,
|
||||
WorkspacePath: workspacePath,
|
||||
Status: v1.AgentStatusRunning,
|
||||
StartedAt: time.Now(),
|
||||
Progress: 0,
|
||||
Metadata: metadata,
|
||||
agentctl: ri.Client,
|
||||
standaloneInstanceID: ri.StandaloneInstanceID,
|
||||
standalonePort: ri.StandalonePort,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
agentctl "github.com/kandev/kandev/internal/agentctl/client"
|
||||
"github.com/kandev/kandev/internal/agent/docker"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
)
|
||||
|
||||
// DockerRuntime implements Runtime for Docker-based agent execution.
|
||||
type DockerRuntime struct {
|
||||
containerMgr *ContainerManager
|
||||
docker *docker.Client
|
||||
logger *logger.Logger
|
||||
}
|
||||
|
||||
// NewDockerRuntime creates a new Docker runtime.
|
||||
func NewDockerRuntime(dockerClient *docker.Client, log *logger.Logger) *DockerRuntime {
|
||||
return &DockerRuntime{
|
||||
containerMgr: NewContainerManager(dockerClient, "", log),
|
||||
docker: dockerClient,
|
||||
logger: log.WithFields(zap.String("runtime", "docker")),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *DockerRuntime) Name() string {
|
||||
return "docker"
|
||||
}
|
||||
|
||||
func (r *DockerRuntime) HealthCheck(ctx context.Context) error {
|
||||
// Check Docker is reachable by listing containers
|
||||
_, err := r.docker.ListContainers(ctx, map[string]string{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("docker not reachable: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *DockerRuntime) CreateInstance(ctx context.Context, req *RuntimeCreateRequest) (*RuntimeInstance, error) {
|
||||
// Convert RuntimeCreateRequest to ContainerConfig
|
||||
containerCfg := ContainerConfig{
|
||||
AgentConfig: req.AgentConfig,
|
||||
WorkspacePath: req.WorkspacePath,
|
||||
TaskID: req.TaskID,
|
||||
InstanceID: req.InstanceID,
|
||||
MainRepoGitDir: req.MainRepoGitDir,
|
||||
Credentials: req.Env, // Env contains credentials from the caller
|
||||
}
|
||||
|
||||
// Use ContainerManager to launch container
|
||||
containerID, client, err := r.containerMgr.LaunchContainer(ctx, containerCfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to launch container: %w", err)
|
||||
}
|
||||
|
||||
// Get container IP for logging
|
||||
containerIP, _ := r.docker.GetContainerIP(ctx, containerID)
|
||||
|
||||
// Build metadata
|
||||
metadata := make(map[string]interface{})
|
||||
if req.WorktreeID != "" {
|
||||
metadata["worktree_id"] = req.WorktreeID
|
||||
metadata["worktree_path"] = req.WorkspacePath
|
||||
metadata["worktree_branch"] = req.WorktreeBranch
|
||||
}
|
||||
|
||||
r.logger.Info("docker instance created",
|
||||
zap.String("instance_id", req.InstanceID),
|
||||
zap.String("container_id", containerID),
|
||||
zap.String("container_ip", containerIP))
|
||||
|
||||
return &RuntimeInstance{
|
||||
InstanceID: req.InstanceID,
|
||||
TaskID: req.TaskID,
|
||||
Client: client,
|
||||
ContainerID: containerID,
|
||||
ContainerIP: containerIP,
|
||||
WorkspacePath: "/workspace", // Docker mounts workspace to /workspace
|
||||
Metadata: metadata,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *DockerRuntime) StopInstance(ctx context.Context, instance *RuntimeInstance, force bool) error {
|
||||
if instance.ContainerID == "" {
|
||||
return nil // No container to stop
|
||||
}
|
||||
|
||||
var err error
|
||||
if force {
|
||||
err = r.docker.KillContainer(ctx, instance.ContainerID, "SIGKILL")
|
||||
} else {
|
||||
err = r.docker.StopContainer(ctx, instance.ContainerID, 30*time.Second)
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to stop container: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *DockerRuntime) RecoverInstances(ctx context.Context) ([]*RuntimeInstance, error) {
|
||||
// Find containers with kandev.managed label
|
||||
containers, err := r.docker.ListContainers(ctx, map[string]string{
|
||||
"kandev.managed": "true",
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to list containers: %w", err)
|
||||
}
|
||||
|
||||
var recovered []*RuntimeInstance
|
||||
for _, ctr := range containers {
|
||||
// Only recover running containers
|
||||
if ctr.State != "running" {
|
||||
r.logger.Debug("skipping non-running container",
|
||||
zap.String("container_id", ctr.ID),
|
||||
zap.String("state", ctr.State))
|
||||
continue
|
||||
}
|
||||
|
||||
// Get container labels to extract instance info
|
||||
labels, err := r.docker.GetContainerLabels(ctx, ctr.ID)
|
||||
if err != nil {
|
||||
r.logger.Warn("failed to get container labels",
|
||||
zap.String("container_id", ctr.ID),
|
||||
zap.Error(err))
|
||||
continue
|
||||
}
|
||||
|
||||
instanceID := labels["kandev.instance_id"]
|
||||
taskID := labels["kandev.task_id"]
|
||||
agentProfileID := labels["kandev.agent_profile_id"]
|
||||
|
||||
if instanceID == "" || taskID == "" {
|
||||
r.logger.Warn("container missing required labels",
|
||||
zap.String("container_id", ctr.ID))
|
||||
continue
|
||||
}
|
||||
|
||||
// Get container IP
|
||||
containerIP, err := r.docker.GetContainerIP(ctx, ctr.ID)
|
||||
if err != nil {
|
||||
r.logger.Warn("failed to get container IP",
|
||||
zap.String("container_id", ctr.ID),
|
||||
zap.Error(err))
|
||||
containerIP = "127.0.0.1"
|
||||
}
|
||||
|
||||
// Query the ControlServer to get the instance port
|
||||
ctl := agentctl.NewStandaloneCtl(containerIP, AgentCtlPort, r.logger)
|
||||
instanceInfo, err := ctl.GetInstance(ctx, instanceID)
|
||||
if err != nil {
|
||||
r.logger.Warn("failed to get instance info from container",
|
||||
zap.String("container_id", ctr.ID),
|
||||
zap.String("instance_id", instanceID),
|
||||
zap.Error(err))
|
||||
continue
|
||||
}
|
||||
|
||||
client := agentctl.NewClient(containerIP, instanceInfo.Port, r.logger)
|
||||
|
||||
recovered = append(recovered, &RuntimeInstance{
|
||||
InstanceID: instanceID,
|
||||
TaskID: taskID,
|
||||
Client: client,
|
||||
ContainerID: ctr.ID,
|
||||
ContainerIP: containerIP,
|
||||
WorkspacePath: "/workspace",
|
||||
Metadata: map[string]interface{}{"agent_profile_id": agentProfileID},
|
||||
})
|
||||
|
||||
r.logger.Info("recovered docker instance",
|
||||
zap.String("instance_id", instanceID),
|
||||
zap.String("task_id", taskID),
|
||||
zap.String("container_id", ctr.ID),
|
||||
zap.Int("instance_port", instanceInfo.Port))
|
||||
}
|
||||
|
||||
return recovered, nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
agentctl "github.com/kandev/kandev/internal/agentctl/client"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
)
|
||||
|
||||
// StandaloneRuntime implements Runtime for standalone agentctl execution.
|
||||
// In this mode, a single agentctl control server manages multiple agent instances.
|
||||
type StandaloneRuntime struct {
|
||||
ctl *agentctl.StandaloneCtl
|
||||
host string
|
||||
port int
|
||||
logger *logger.Logger
|
||||
}
|
||||
|
||||
// NewStandaloneRuntime creates a new standalone runtime.
|
||||
func NewStandaloneRuntime(ctl *agentctl.StandaloneCtl, host string, port int, log *logger.Logger) *StandaloneRuntime {
|
||||
return &StandaloneRuntime{
|
||||
ctl: ctl,
|
||||
host: host,
|
||||
port: port,
|
||||
logger: log.WithFields(zap.String("runtime", "standalone")),
|
||||
}
|
||||
}
|
||||
|
||||
func (r *StandaloneRuntime) Name() string {
|
||||
return "standalone"
|
||||
}
|
||||
|
||||
func (r *StandaloneRuntime) HealthCheck(ctx context.Context) error {
|
||||
return r.ctl.Health(ctx)
|
||||
}
|
||||
|
||||
func (r *StandaloneRuntime) CreateInstance(ctx context.Context, req *RuntimeCreateRequest) (*RuntimeInstance, error) {
|
||||
// Build environment variables
|
||||
env := req.Env
|
||||
if env == nil {
|
||||
env = make(map[string]string)
|
||||
}
|
||||
env["KANDEV_TASK_ID"] = req.TaskID
|
||||
|
||||
// Create instance via control API
|
||||
// Agent command is NOT set - workspace access only. Agent is started explicitly via agentctl client.
|
||||
createReq := &agentctl.CreateInstanceRequest{
|
||||
ID: req.InstanceID,
|
||||
WorkspacePath: req.WorkspacePath,
|
||||
AgentCommand: "", // Agent command set via Configure endpoint
|
||||
Protocol: req.Protocol,
|
||||
Env: env,
|
||||
AutoStart: false,
|
||||
}
|
||||
|
||||
resp, err := r.ctl.CreateInstance(ctx, createReq)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to create standalone instance: %w", err)
|
||||
}
|
||||
|
||||
// Create agentctl client pointing to the instance port
|
||||
client := agentctl.NewClient(r.host, resp.Port, r.logger)
|
||||
|
||||
// Build metadata
|
||||
metadata := make(map[string]interface{})
|
||||
metadata["standalone_port"] = resp.Port
|
||||
if req.WorktreeID != "" {
|
||||
metadata["worktree_id"] = req.WorktreeID
|
||||
metadata["worktree_path"] = req.WorkspacePath
|
||||
metadata["worktree_branch"] = req.WorktreeBranch
|
||||
}
|
||||
|
||||
r.logger.Info("standalone instance created",
|
||||
zap.String("instance_id", req.InstanceID),
|
||||
zap.Int("port", resp.Port),
|
||||
zap.String("workspace", req.WorkspacePath))
|
||||
|
||||
return &RuntimeInstance{
|
||||
InstanceID: req.InstanceID,
|
||||
TaskID: req.TaskID,
|
||||
Client: client,
|
||||
StandaloneInstanceID: resp.ID,
|
||||
StandalonePort: resp.Port,
|
||||
WorkspacePath: req.WorkspacePath,
|
||||
Metadata: metadata,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (r *StandaloneRuntime) StopInstance(ctx context.Context, instance *RuntimeInstance, force bool) error {
|
||||
if instance.StandaloneInstanceID == "" {
|
||||
return nil // No standalone instance to stop
|
||||
}
|
||||
|
||||
if err := r.ctl.DeleteInstance(ctx, instance.StandaloneInstanceID); err != nil {
|
||||
return fmt.Errorf("failed to stop standalone instance: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *StandaloneRuntime) RecoverInstances(ctx context.Context) ([]*RuntimeInstance, error) {
|
||||
// Standalone instances are not persisted - they are transient processes
|
||||
// managed by agentctl. Session resume will restart them as needed.
|
||||
return nil, nil
|
||||
}
|
||||
@@ -3,17 +3,22 @@ package lifecycle
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/agentctl"
|
||||
agentctl "github.com/kandev/kandev/internal/agentctl/client"
|
||||
"github.com/kandev/kandev/internal/agent/registry"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
)
|
||||
|
||||
// SessionManager handles ACP session initialization and management
|
||||
type SessionManager struct {
|
||||
logger *logger.Logger
|
||||
logger *logger.Logger
|
||||
eventPublisher *EventPublisher
|
||||
streamManager *StreamManager
|
||||
executionStore *ExecutionStore
|
||||
}
|
||||
|
||||
// NewSessionManager creates a new SessionManager
|
||||
@@ -23,6 +28,14 @@ func NewSessionManager(log *logger.Logger) *SessionManager {
|
||||
}
|
||||
}
|
||||
|
||||
// SetDependencies sets the optional dependencies for full session orchestration.
|
||||
// These are set after construction to avoid circular dependencies.
|
||||
func (sm *SessionManager) SetDependencies(ep *EventPublisher, strm *StreamManager, store *ExecutionStore) {
|
||||
sm.eventPublisher = ep
|
||||
sm.streamManager = strm
|
||||
sm.executionStore = store
|
||||
}
|
||||
|
||||
// InitializeResult contains the result of session initialization
|
||||
type InitializeResult struct {
|
||||
AgentName string
|
||||
@@ -167,3 +180,170 @@ func (sm *SessionManager) createNewSession(
|
||||
|
||||
return sessionID, nil
|
||||
}
|
||||
|
||||
// InitializeAndPrompt performs full ACP session initialization and sends the initial prompt.
|
||||
// This orchestrates:
|
||||
// 1. Session initialization (initialize + session/new or session/load)
|
||||
// 2. Publishing ACP session created event
|
||||
// 3. Connecting WebSocket streams
|
||||
// 4. Sending the initial task prompt (if provided)
|
||||
// 5. Marking the execution as ready
|
||||
//
|
||||
// Returns the session ID on success.
|
||||
func (sm *SessionManager) InitializeAndPrompt(
|
||||
ctx context.Context,
|
||||
execution *AgentExecution,
|
||||
agentConfig *registry.AgentTypeConfig,
|
||||
taskDescription string,
|
||||
markReady func(executionID string) error,
|
||||
) error {
|
||||
sm.logger.Info("initializing ACP session",
|
||||
zap.String("execution_id", execution.ID),
|
||||
zap.String("agentctl_url", execution.agentctl.BaseURL()),
|
||||
zap.String("agent_type", agentConfig.ID),
|
||||
zap.String("existing_acp_session_id", execution.ACPSessionID),
|
||||
zap.Bool("resume_via_acp", agentConfig.SessionConfig.ResumeViaACP))
|
||||
|
||||
// Use InitializeSession for configuration-driven session initialization
|
||||
result, err := sm.InitializeSession(
|
||||
ctx,
|
||||
execution.agentctl,
|
||||
agentConfig,
|
||||
execution.ACPSessionID,
|
||||
execution.WorkspacePath,
|
||||
)
|
||||
if err != nil {
|
||||
sm.logger.Error("session initialization failed",
|
||||
zap.String("execution_id", execution.ID),
|
||||
zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
sm.logger.Info("ACP session initialized",
|
||||
zap.String("execution_id", execution.ID),
|
||||
zap.String("agent_name", result.AgentName),
|
||||
zap.String("agent_version", result.AgentVersion),
|
||||
zap.String("session_id", result.SessionID))
|
||||
|
||||
execution.ACPSessionID = result.SessionID
|
||||
|
||||
// Publish session created event
|
||||
if sm.eventPublisher != nil {
|
||||
sm.eventPublisher.PublishACPSessionCreated(execution, result.SessionID)
|
||||
}
|
||||
|
||||
// Set up WebSocket streams
|
||||
if sm.streamManager != nil {
|
||||
updatesReady := make(chan struct{})
|
||||
sm.streamManager.ConnectAll(execution, updatesReady)
|
||||
|
||||
// Wait for the updates stream to connect before sending prompt
|
||||
select {
|
||||
case <-updatesReady:
|
||||
sm.logger.Debug("updates stream ready")
|
||||
case <-time.After(5 * time.Second):
|
||||
sm.logger.Warn("timeout waiting for updates stream to connect, proceeding anyway")
|
||||
}
|
||||
}
|
||||
|
||||
// Send the task prompt if provided
|
||||
if taskDescription != "" {
|
||||
// Use a long timeout for initial prompts
|
||||
promptCtx, cancel := context.WithTimeout(context.Background(), 10*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
_, err := sm.SendPrompt(promptCtx, execution, taskDescription, false, markReady)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
sm.logger.Warn("no task description provided, marking as ready",
|
||||
zap.String("execution_id", execution.ID))
|
||||
if err := markReady(execution.ID); err != nil {
|
||||
sm.logger.Error("failed to mark execution as ready",
|
||||
zap.String("execution_id", execution.ID),
|
||||
zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// SendPrompt sends a prompt to an agent execution and waits for completion.
|
||||
// For initial prompts, pass validateStatus=false. For follow-up prompts, pass validateStatus=true.
|
||||
// Returns the prompt result containing the stop reason and agent message.
|
||||
func (sm *SessionManager) SendPrompt(
|
||||
ctx context.Context,
|
||||
execution *AgentExecution,
|
||||
prompt string,
|
||||
validateStatus bool,
|
||||
markReady func(executionID string) error,
|
||||
) (*PromptResult, error) {
|
||||
if execution.agentctl == nil {
|
||||
return nil, fmt.Errorf("execution %q has no agentctl client", execution.ID)
|
||||
}
|
||||
|
||||
// For follow-up prompts, validate status and update to RUNNING
|
||||
if validateStatus {
|
||||
if execution.Status != v1.AgentStatusRunning && execution.Status != v1.AgentStatusReady {
|
||||
return nil, fmt.Errorf("execution %q is not ready for prompts (status: %s)", execution.ID, execution.Status)
|
||||
}
|
||||
if sm.executionStore != nil {
|
||||
sm.executionStore.UpdateStatus(execution.ID, v1.AgentStatusRunning)
|
||||
}
|
||||
}
|
||||
|
||||
// Clear buffers before starting prompt
|
||||
execution.messageMu.Lock()
|
||||
execution.messageBuffer.Reset()
|
||||
execution.reasoningBuffer.Reset()
|
||||
execution.summaryBuffer.Reset()
|
||||
execution.messageMu.Unlock()
|
||||
|
||||
sm.logger.Info("sending prompt to agent",
|
||||
zap.String("execution_id", execution.ID),
|
||||
zap.Int("prompt_length", len(prompt)))
|
||||
|
||||
// Prompt is synchronous - blocks until agent completes
|
||||
resp, err := execution.agentctl.Prompt(ctx, prompt)
|
||||
if err != nil {
|
||||
sm.logger.Error("ACP prompt failed",
|
||||
zap.String("execution_id", execution.ID),
|
||||
zap.Error(err))
|
||||
return nil, fmt.Errorf("prompt failed: %w", err)
|
||||
}
|
||||
|
||||
// Extract accumulated content from buffers
|
||||
execution.messageMu.Lock()
|
||||
agentMessage := execution.messageBuffer.String()
|
||||
execution.messageBuffer.Reset()
|
||||
execution.reasoningBuffer.Reset()
|
||||
execution.summaryBuffer.Reset()
|
||||
execution.messageMu.Unlock()
|
||||
|
||||
stopReason := ""
|
||||
if resp != nil {
|
||||
stopReason = string(resp.StopReason)
|
||||
}
|
||||
|
||||
sm.logger.Info("ACP prompt completed",
|
||||
zap.String("execution_id", execution.ID),
|
||||
zap.String("stop_reason", stopReason))
|
||||
|
||||
// Publish prompt_complete event
|
||||
if sm.eventPublisher != nil {
|
||||
sm.eventPublisher.PublishPromptComplete(execution, agentMessage, "", "")
|
||||
}
|
||||
|
||||
// Mark as READY for next prompt
|
||||
if err := markReady(execution.ID); err != nil {
|
||||
sm.logger.Error("failed to mark execution as ready after prompt",
|
||||
zap.String("execution_id", execution.ID),
|
||||
zap.Error(err))
|
||||
}
|
||||
|
||||
return &PromptResult{
|
||||
StopReason: stopReason,
|
||||
AgentMessage: agentMessage,
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -6,19 +6,19 @@ import (
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/agentctl"
|
||||
agentctl "github.com/kandev/kandev/internal/agentctl/client"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
)
|
||||
|
||||
// StreamCallbacks defines callbacks for stream events
|
||||
type StreamCallbacks struct {
|
||||
OnSessionUpdate func(instance *AgentInstance, update agentctl.SessionUpdate)
|
||||
OnPermission func(instance *AgentInstance, notification *agentctl.PermissionNotification)
|
||||
OnGitStatus func(instance *AgentInstance, update *agentctl.GitStatusUpdate)
|
||||
OnFileChange func(instance *AgentInstance, notification *agentctl.FileChangeNotification)
|
||||
OnSessionUpdate func(execution *AgentExecution, update agentctl.SessionUpdate)
|
||||
OnPermission func(execution *AgentExecution, notification *agentctl.PermissionNotification)
|
||||
OnGitStatus func(execution *AgentExecution, update *agentctl.GitStatusUpdate)
|
||||
OnFileChange func(execution *AgentExecution, notification *agentctl.FileChangeNotification)
|
||||
}
|
||||
|
||||
// StreamManager manages WebSocket streams to agent instances
|
||||
// StreamManager manages WebSocket streams to agent executions
|
||||
type StreamManager struct {
|
||||
logger *logger.Logger
|
||||
callbacks StreamCallbacks
|
||||
@@ -32,21 +32,21 @@ func NewStreamManager(log *logger.Logger, callbacks StreamCallbacks) *StreamMana
|
||||
}
|
||||
}
|
||||
|
||||
// ConnectAll connects to all streams for an instance.
|
||||
// ConnectAll connects to all streams for an execution.
|
||||
// If ready is non-nil, it will be closed when the updates stream is connected.
|
||||
func (sm *StreamManager) ConnectAll(instance *AgentInstance, ready chan<- struct{}) {
|
||||
go sm.connectUpdatesStream(instance, ready)
|
||||
go sm.connectPermissionStream(instance)
|
||||
go sm.connectGitStatusStream(instance)
|
||||
go sm.connectFileChangesStream(instance)
|
||||
func (sm *StreamManager) ConnectAll(execution *AgentExecution, ready chan<- struct{}) {
|
||||
go sm.connectUpdatesStream(execution, ready)
|
||||
go sm.connectPermissionStream(execution)
|
||||
go sm.connectGitStatusStream(execution)
|
||||
go sm.connectFileChangesStream(execution)
|
||||
}
|
||||
|
||||
// ReconnectAll reconnects to all streams (used after backend restart).
|
||||
// This waits for agentctl to be ready before connecting to streams.
|
||||
func (sm *StreamManager) ReconnectAll(instance *AgentInstance) {
|
||||
func (sm *StreamManager) ReconnectAll(execution *AgentExecution) {
|
||||
sm.logger.Info("reconnecting to agent streams after recovery",
|
||||
zap.String("instance_id", instance.ID),
|
||||
zap.String("task_id", instance.TaskID))
|
||||
zap.String("instance_id", execution.ID),
|
||||
zap.String("task_id", execution.TaskID))
|
||||
|
||||
// Wait a moment for any startup operations to settle
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
@@ -55,28 +55,28 @@ func (sm *StreamManager) ReconnectAll(instance *AgentInstance) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := instance.agentctl.WaitForReady(ctx, 10*time.Second); err != nil {
|
||||
if err := execution.agentctl.WaitForReady(ctx, 10*time.Second); err != nil {
|
||||
sm.logger.Warn("agentctl not ready for stream reconnection",
|
||||
zap.String("instance_id", instance.ID),
|
||||
zap.String("instance_id", execution.ID),
|
||||
zap.Error(err))
|
||||
// Don't return - still try to connect to streams
|
||||
}
|
||||
|
||||
// Reconnect to WebSocket streams
|
||||
sm.ConnectAll(instance, nil)
|
||||
sm.ConnectAll(execution, nil)
|
||||
|
||||
sm.logger.Info("agent streams reconnected",
|
||||
zap.String("instance_id", instance.ID),
|
||||
zap.String("task_id", instance.TaskID))
|
||||
zap.String("instance_id", execution.ID),
|
||||
zap.String("task_id", execution.TaskID))
|
||||
}
|
||||
|
||||
// connectUpdatesStream handles the updates WebSocket stream with ready signaling
|
||||
func (sm *StreamManager) connectUpdatesStream(instance *AgentInstance, ready chan<- struct{}) {
|
||||
func (sm *StreamManager) connectUpdatesStream(execution *AgentExecution, ready chan<- struct{}) {
|
||||
ctx := context.Background()
|
||||
|
||||
err := instance.agentctl.StreamUpdates(ctx, func(update agentctl.SessionUpdate) {
|
||||
err := execution.agentctl.StreamUpdates(ctx, func(update agentctl.SessionUpdate) {
|
||||
if sm.callbacks.OnSessionUpdate != nil {
|
||||
sm.callbacks.OnSessionUpdate(instance, update)
|
||||
sm.callbacks.OnSessionUpdate(execution, update)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -89,29 +89,29 @@ func (sm *StreamManager) connectUpdatesStream(instance *AgentInstance, ready cha
|
||||
|
||||
if err != nil {
|
||||
sm.logger.Error("failed to connect to updates stream",
|
||||
zap.String("instance_id", instance.ID),
|
||||
zap.String("instance_id", execution.ID),
|
||||
zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// connectPermissionStream handles the permission WebSocket stream
|
||||
func (sm *StreamManager) connectPermissionStream(instance *AgentInstance) {
|
||||
func (sm *StreamManager) connectPermissionStream(execution *AgentExecution) {
|
||||
ctx := context.Background()
|
||||
|
||||
err := instance.agentctl.StreamPermissions(ctx, func(notification *agentctl.PermissionNotification) {
|
||||
err := execution.agentctl.StreamPermissions(ctx, func(notification *agentctl.PermissionNotification) {
|
||||
if sm.callbacks.OnPermission != nil {
|
||||
sm.callbacks.OnPermission(instance, notification)
|
||||
sm.callbacks.OnPermission(execution, notification)
|
||||
}
|
||||
})
|
||||
if err != nil {
|
||||
sm.logger.Error("failed to connect to permission stream",
|
||||
zap.String("instance_id", instance.ID),
|
||||
zap.String("instance_id", execution.ID),
|
||||
zap.Error(err))
|
||||
}
|
||||
}
|
||||
|
||||
// connectGitStatusStream handles git status stream with retry logic
|
||||
func (sm *StreamManager) connectGitStatusStream(instance *AgentInstance) {
|
||||
func (sm *StreamManager) connectGitStatusStream(execution *AgentExecution) {
|
||||
ctx := context.Background()
|
||||
|
||||
// Retry connection with exponential backoff
|
||||
@@ -119,9 +119,9 @@ func (sm *StreamManager) connectGitStatusStream(instance *AgentInstance) {
|
||||
backoff := 1 * time.Second
|
||||
|
||||
for attempt := 1; attempt <= maxRetries; attempt++ {
|
||||
err := instance.agentctl.StreamGitStatus(ctx, func(update *agentctl.GitStatusUpdate) {
|
||||
err := execution.agentctl.StreamGitStatus(ctx, func(update *agentctl.GitStatusUpdate) {
|
||||
if sm.callbacks.OnGitStatus != nil {
|
||||
sm.callbacks.OnGitStatus(instance, update)
|
||||
sm.callbacks.OnGitStatus(execution, update)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -131,7 +131,7 @@ func (sm *StreamManager) connectGitStatusStream(instance *AgentInstance) {
|
||||
}
|
||||
|
||||
sm.logger.Debug("git status stream connection failed, retrying",
|
||||
zap.String("instance_id", instance.ID),
|
||||
zap.String("instance_id", execution.ID),
|
||||
zap.Int("attempt", attempt),
|
||||
zap.Int("max_retries", maxRetries),
|
||||
zap.Error(err))
|
||||
@@ -143,12 +143,12 @@ func (sm *StreamManager) connectGitStatusStream(instance *AgentInstance) {
|
||||
}
|
||||
|
||||
sm.logger.Error("failed to connect to git status stream after retries",
|
||||
zap.String("instance_id", instance.ID),
|
||||
zap.String("instance_id", execution.ID),
|
||||
zap.Int("max_retries", maxRetries))
|
||||
}
|
||||
|
||||
// connectFileChangesStream handles file changes stream with retry logic
|
||||
func (sm *StreamManager) connectFileChangesStream(instance *AgentInstance) {
|
||||
func (sm *StreamManager) connectFileChangesStream(execution *AgentExecution) {
|
||||
ctx := context.Background()
|
||||
|
||||
// Retry connection with exponential backoff
|
||||
@@ -156,9 +156,9 @@ func (sm *StreamManager) connectFileChangesStream(instance *AgentInstance) {
|
||||
backoff := 1 * time.Second
|
||||
|
||||
for attempt := 1; attempt <= maxRetries; attempt++ {
|
||||
err := instance.agentctl.StreamFileChanges(ctx, func(notification *agentctl.FileChangeNotification) {
|
||||
err := execution.agentctl.StreamFileChanges(ctx, func(notification *agentctl.FileChangeNotification) {
|
||||
if sm.callbacks.OnFileChange != nil {
|
||||
sm.callbacks.OnFileChange(instance, notification)
|
||||
sm.callbacks.OnFileChange(execution, notification)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -168,7 +168,7 @@ func (sm *StreamManager) connectFileChangesStream(instance *AgentInstance) {
|
||||
}
|
||||
|
||||
sm.logger.Debug("file changes stream connection failed, retrying",
|
||||
zap.String("instance_id", instance.ID),
|
||||
zap.String("instance_id", execution.ID),
|
||||
zap.Int("attempt", attempt),
|
||||
zap.Int("max_retries", maxRetries),
|
||||
zap.Error(err))
|
||||
@@ -180,6 +180,6 @@ func (sm *StreamManager) connectFileChangesStream(instance *AgentInstance) {
|
||||
}
|
||||
|
||||
sm.logger.Error("failed to connect to file changes stream after retries",
|
||||
zap.String("instance_id", instance.ID),
|
||||
zap.String("instance_id", execution.ID),
|
||||
zap.Int("max_retries", maxRetries))
|
||||
}
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
// Package lifecycle manages agent execution lifecycles including tracking,
|
||||
// state transitions, and cleanup.
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
agentctl "github.com/kandev/kandev/internal/agentctl/client"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
)
|
||||
|
||||
// Default agentctl port
|
||||
const AgentCtlPort = 9999
|
||||
|
||||
// AgentExecution represents a running agent execution
|
||||
type AgentExecution struct {
|
||||
ID string
|
||||
TaskID string
|
||||
AgentProfileID string
|
||||
ContainerID string
|
||||
ContainerIP string // IP address of the container for agentctl communication
|
||||
WorkspacePath string // Path to the workspace (worktree or repository path)
|
||||
ACPSessionID string // ACP session ID to resume, if available
|
||||
AgentCommand string // Command to start the agent subprocess
|
||||
Status v1.AgentStatus
|
||||
StartedAt time.Time
|
||||
FinishedAt *time.Time
|
||||
ExitCode *int
|
||||
ErrorMessage string
|
||||
Progress int
|
||||
Metadata map[string]interface{}
|
||||
|
||||
// agentctl client for this execution
|
||||
agentctl *agentctl.Client
|
||||
|
||||
// Standalone mode info (when not using Docker)
|
||||
standaloneInstanceID string // Instance ID in standalone agentctl
|
||||
standalonePort int // Port of the standalone execution
|
||||
|
||||
// Buffers for accumulating agent response during a prompt
|
||||
messageBuffer strings.Builder
|
||||
reasoningBuffer strings.Builder
|
||||
summaryBuffer strings.Builder
|
||||
messageMu sync.Mutex
|
||||
}
|
||||
|
||||
// GetAgentCtlClient returns the agentctl client for this execution
|
||||
func (ae *AgentExecution) GetAgentCtlClient() *agentctl.Client {
|
||||
return ae.agentctl
|
||||
}
|
||||
|
||||
// LaunchRequest contains parameters for launching an agent
|
||||
type LaunchRequest struct {
|
||||
TaskID string
|
||||
SessionID string
|
||||
TaskTitle string // Human-readable task title for semantic worktree naming
|
||||
AgentProfileID string
|
||||
WorkspacePath string // Host path to workspace (original repository path)
|
||||
TaskDescription string // Task description to send via ACP prompt
|
||||
Env map[string]string // Additional env vars
|
||||
ACPSessionID string // ACP session ID to resume, if available
|
||||
Metadata map[string]interface{}
|
||||
|
||||
// Worktree configuration
|
||||
UseWorktree bool // Whether to use a Git worktree for isolation
|
||||
RepositoryID string // Repository ID for worktree tracking
|
||||
RepositoryPath string // Path to the main repository (for worktree creation)
|
||||
BaseBranch string // Base branch for the worktree (e.g., "main")
|
||||
}
|
||||
|
||||
// CredentialsManager interface for credential retrieval
|
||||
type CredentialsManager interface {
|
||||
GetCredentialValue(ctx context.Context, key string) (value string, err error)
|
||||
}
|
||||
|
||||
// AgentProfileInfo contains resolved profile information
|
||||
type AgentProfileInfo struct {
|
||||
ProfileID string
|
||||
ProfileName string
|
||||
AgentID string
|
||||
AgentName string // e.g., "auggie", "claude", "codex"
|
||||
Model string
|
||||
AutoApprove bool
|
||||
DangerouslySkipPermissions bool
|
||||
Plan string
|
||||
}
|
||||
|
||||
// ProfileResolver resolves agent profile IDs to profile information
|
||||
type ProfileResolver interface {
|
||||
ResolveProfile(ctx context.Context, profileID string) (*AgentProfileInfo, error)
|
||||
}
|
||||
|
||||
// ShellStreamStarter is called to start shell streaming for an agent execution
|
||||
type ShellStreamStarter interface {
|
||||
StartShellStream(ctx context.Context, taskID string) error
|
||||
}
|
||||
|
||||
// WorkspaceInfo contains information about a task's workspace for on-demand execution creation
|
||||
type WorkspaceInfo struct {
|
||||
TaskID string
|
||||
SessionID string // Task session ID (from task_sessions table)
|
||||
WorkspacePath string // Path to the workspace/repository
|
||||
AgentProfileID string // Optional - agent profile for the task
|
||||
AgentID string // Agent type ID (e.g., "auggie-agent") - required for runtime creation
|
||||
ACPSessionID string // Agent's session ID for conversation resumption (from session metadata)
|
||||
}
|
||||
|
||||
// WorkspaceInfoProvider provides workspace information for tasks
|
||||
type WorkspaceInfoProvider interface {
|
||||
// GetWorkspaceInfo returns workspace info for a task (uses most recent session)
|
||||
GetWorkspaceInfo(ctx context.Context, taskID string) (*WorkspaceInfo, error)
|
||||
// GetWorkspaceInfoForSession returns workspace info for a specific task session
|
||||
GetWorkspaceInfoForSession(ctx context.Context, taskID, sessionID string) (*WorkspaceInfo, error)
|
||||
}
|
||||
|
||||
// RecoveredExecution contains info about an execution recovered from a runtime.
|
||||
type RecoveredExecution struct {
|
||||
ExecutionID string
|
||||
TaskID string
|
||||
ContainerID string
|
||||
AgentProfileID string
|
||||
}
|
||||
|
||||
// PromptResult contains the result of a prompt operation
|
||||
type PromptResult struct {
|
||||
StopReason string // The reason the agent stopped (e.g., "end_turn")
|
||||
AgentMessage string // The agent's accumulated response message
|
||||
}
|
||||
|
||||
@@ -178,6 +178,32 @@ func (r *Registry) Get(id string) (*AgentTypeConfig, error) {
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// GetAgentType is an alias for Get for backward compatibility
|
||||
func (r *Registry) GetAgentType(id string) (*AgentTypeConfig, error) {
|
||||
return r.Get(id)
|
||||
}
|
||||
|
||||
// GetDefault returns the default agent type configuration.
|
||||
// It tries "augment-agent" first, then falls back to the first enabled agent.
|
||||
func (r *Registry) GetDefault() (*AgentTypeConfig, error) {
|
||||
r.mu.RLock()
|
||||
defer r.mu.RUnlock()
|
||||
|
||||
// Try augment-agent first
|
||||
if config, exists := r.agents["augment-agent"]; exists && config.Enabled {
|
||||
return config, nil
|
||||
}
|
||||
|
||||
// Fall back to first enabled agent
|
||||
for _, config := range r.agents {
|
||||
if config.Enabled {
|
||||
return config, nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("no default agent type available")
|
||||
}
|
||||
|
||||
// List returns all registered agent types
|
||||
func (r *Registry) List() []*AgentTypeConfig {
|
||||
r.mu.RLock()
|
||||
|
||||
+56
-11
@@ -1,4 +1,4 @@
|
||||
package agentctl
|
||||
package client
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -57,9 +57,18 @@ func (c *Client) Initialize(ctx context.Context, clientName, clientVersion strin
|
||||
}
|
||||
}()
|
||||
|
||||
respBody, err := readResponseBody(resp)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("initialize request failed with status %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
var result InitializeResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return nil, err
|
||||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse initialize response (status %d, body: %s): %w", resp.StatusCode, truncateBody(respBody), err)
|
||||
}
|
||||
if !result.Success {
|
||||
return nil, fmt.Errorf("initialize failed: %s", result.Error)
|
||||
@@ -101,9 +110,18 @@ func (c *Client) NewSession(ctx context.Context, cwd string) (string, error) {
|
||||
}
|
||||
}()
|
||||
|
||||
respBody, err := readResponseBody(resp)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return "", fmt.Errorf("new session request failed with status %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
var result NewSessionResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return "", err
|
||||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||
return "", fmt.Errorf("failed to parse new session response (status %d, body: %s): %w", resp.StatusCode, truncateBody(respBody), err)
|
||||
}
|
||||
if !result.Success {
|
||||
return "", fmt.Errorf("new session failed: %s", result.Error)
|
||||
@@ -138,12 +156,21 @@ func (c *Client) LoadSession(ctx context.Context, sessionID string) error {
|
||||
}
|
||||
}()
|
||||
|
||||
respBody, err := readResponseBody(resp)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("load session request failed with status %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Success bool `json:"success"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return err
|
||||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||
return fmt.Errorf("failed to parse load session response (status %d, body: %s): %w", resp.StatusCode, truncateBody(respBody), err)
|
||||
}
|
||||
if !result.Success {
|
||||
return fmt.Errorf("load session failed: %s", result.Error)
|
||||
@@ -191,9 +218,18 @@ func (c *Client) Prompt(ctx context.Context, text string) (*PromptResponse, erro
|
||||
}
|
||||
}()
|
||||
|
||||
respBody, err := readResponseBody(resp)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("prompt request failed with status %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
var result PromptResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return nil, err
|
||||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse prompt response (status %d, body: %s): %w", resp.StatusCode, truncateBody(respBody), err)
|
||||
}
|
||||
if !result.Success {
|
||||
return nil, fmt.Errorf("prompt failed: %s", result.Error)
|
||||
@@ -421,9 +457,18 @@ func (c *Client) RespondToPermission(ctx context.Context, pendingID, optionID st
|
||||
}
|
||||
}()
|
||||
|
||||
respBody, err := readResponseBody(resp)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("permission response request failed with status %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
var result PermissionRespondResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return err
|
||||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||
return fmt.Errorf("failed to parse permission response (status %d, body: %s): %w", resp.StatusCode, truncateBody(respBody), err)
|
||||
}
|
||||
if !result.Success {
|
||||
return fmt.Errorf("permission response failed: %s", result.Error)
|
||||
+119
-21
@@ -1,7 +1,8 @@
|
||||
// Package agentctl provides a client for communicating with agentctl running inside containers
|
||||
package agentctl
|
||||
package client
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
@@ -10,7 +11,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/kandev/kandev/internal/agentctl/process"
|
||||
"github.com/kandev/kandev/internal/agentctl/types"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
@@ -36,9 +37,10 @@ type StatusResponse struct {
|
||||
ProcessInfo map[string]interface{} `json:"process_info"`
|
||||
}
|
||||
|
||||
// IsAgentRunning returns true if the agent process is running
|
||||
// IsAgentRunning returns true if the agent process is running or starting
|
||||
// (i.e., the agent is active and should not be considered stale)
|
||||
func (s *StatusResponse) IsAgentRunning() bool {
|
||||
return s.AgentStatus == "running"
|
||||
return s.AgentStatus == "running" || s.AgentStatus == "starting"
|
||||
}
|
||||
|
||||
// NewClient creates a new agentctl client
|
||||
@@ -84,13 +86,73 @@ func (c *Client) GetStatus(ctx context.Context) (*StatusResponse, error) {
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
respBody, err := readResponseBody(resp)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return nil, fmt.Errorf("status request failed with status %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
var status StatusResponse
|
||||
if err := json.NewDecoder(resp.Body).Decode(&status); err != nil {
|
||||
return nil, err
|
||||
if err := json.Unmarshal(respBody, &status); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse status response (status %d, body: %s): %w", resp.StatusCode, truncateBody(respBody), err)
|
||||
}
|
||||
return &status, nil
|
||||
}
|
||||
|
||||
// ConfigureAgent configures the agent command. Must be called before Start().
|
||||
func (c *Client) ConfigureAgent(ctx context.Context, command string, env map[string]string) error {
|
||||
payload := struct {
|
||||
Command string `json:"command"`
|
||||
Env map[string]string `json:"env,omitempty"`
|
||||
}{
|
||||
Command: command,
|
||||
Env: env,
|
||||
}
|
||||
|
||||
body, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/api/v1/agent/configure", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
|
||||
resp, err := c.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
// Read the response body for better error handling
|
||||
respBody, err := readResponseBody(resp)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
// Check HTTP status code first
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("configure request failed with status %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Success bool `json:"success"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||
return fmt.Errorf("failed to parse configure response (status %d, body: %s): %w", resp.StatusCode, truncateBody(respBody), err)
|
||||
}
|
||||
if !result.Success {
|
||||
return fmt.Errorf("configure failed: %s", result.Error)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Start starts the agent process
|
||||
func (c *Client) Start(ctx context.Context) error {
|
||||
req, err := http.NewRequestWithContext(ctx, "POST", c.baseURL+"/api/v1/start", nil)
|
||||
@@ -104,12 +166,21 @@ func (c *Client) Start(ctx context.Context) error {
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
respBody, err := readResponseBody(resp)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("start request failed with status %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Success bool `json:"success"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return err
|
||||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||
return fmt.Errorf("failed to parse start response (status %d, body: %s): %w", resp.StatusCode, truncateBody(respBody), err)
|
||||
}
|
||||
if !result.Success {
|
||||
return fmt.Errorf("start failed: %s", result.Error)
|
||||
@@ -130,12 +201,21 @@ func (c *Client) Stop(ctx context.Context) error {
|
||||
}
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
respBody, err := readResponseBody(resp)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to read response body: %w", err)
|
||||
}
|
||||
|
||||
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
|
||||
return fmt.Errorf("stop request failed with status %d: %s", resp.StatusCode, string(respBody))
|
||||
}
|
||||
|
||||
var result struct {
|
||||
Success bool `json:"success"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
|
||||
return err
|
||||
if err := json.Unmarshal(respBody, &result); err != nil {
|
||||
return fmt.Errorf("failed to parse stop response (status %d, body: %s): %w", resp.StatusCode, truncateBody(respBody), err)
|
||||
}
|
||||
if !result.Success {
|
||||
return fmt.Errorf("stop failed: %s", result.Error)
|
||||
@@ -171,18 +251,18 @@ func (c *Client) BaseURL() string {
|
||||
return c.baseURL
|
||||
}
|
||||
|
||||
// Re-export types from process package for convenience
|
||||
// Re-export types from types package for convenience
|
||||
type (
|
||||
GitStatusUpdate = process.GitStatusUpdate
|
||||
FileInfo = process.FileInfo
|
||||
FileListUpdate = process.FileListUpdate
|
||||
FileEntry = process.FileEntry
|
||||
FileTreeNode = process.FileTreeNode
|
||||
FileTreeRequest = process.FileTreeRequest
|
||||
FileTreeResponse = process.FileTreeResponse
|
||||
FileContentRequest = process.FileContentRequest
|
||||
FileContentResponse = process.FileContentResponse
|
||||
FileChangeNotification = process.FileChangeNotification
|
||||
GitStatusUpdate = types.GitStatusUpdate
|
||||
FileInfo = types.FileInfo
|
||||
FileListUpdate = types.FileListUpdate
|
||||
FileEntry = types.FileEntry
|
||||
FileTreeNode = types.FileTreeNode
|
||||
FileTreeRequest = types.FileTreeRequest
|
||||
FileTreeResponse = types.FileTreeResponse
|
||||
FileContentRequest = types.FileContentRequest
|
||||
FileContentResponse = types.FileContentResponse
|
||||
FileChangeNotification = types.FileChangeNotification
|
||||
)
|
||||
|
||||
// StreamGitStatus opens a WebSocket connection for streaming git status updates
|
||||
@@ -516,3 +596,21 @@ func (c *Client) CloseShellStream() {
|
||||
c.shellConn = nil
|
||||
}
|
||||
}
|
||||
|
||||
// readResponseBody reads and returns the response body
|
||||
func readResponseBody(resp *http.Response) ([]byte, error) {
|
||||
var buf bytes.Buffer
|
||||
if _, err := buf.ReadFrom(resp.Body); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return buf.Bytes(), nil
|
||||
}
|
||||
|
||||
// truncateBody truncates body for error messages to avoid huge logs
|
||||
func truncateBody(body []byte) string {
|
||||
const maxLen = 200
|
||||
if len(body) > maxLen {
|
||||
return string(body[:maxLen]) + "..."
|
||||
}
|
||||
return string(body)
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
// Package agentctl provides a client for communicating with agentctl.
|
||||
// This file contains the StandaloneCtl client for the multi-instance control API.
|
||||
package agentctl
|
||||
package client
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
@@ -1,94 +0,0 @@
|
||||
package process
|
||||
|
||||
import "time"
|
||||
|
||||
// GitStatusUpdate represents a git status update
|
||||
type GitStatusUpdate struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Modified []string `json:"modified"`
|
||||
Added []string `json:"added"`
|
||||
Deleted []string `json:"deleted"`
|
||||
Untracked []string `json:"untracked"`
|
||||
Renamed []string `json:"renamed"`
|
||||
Ahead int `json:"ahead"`
|
||||
Behind int `json:"behind"`
|
||||
Branch string `json:"branch"`
|
||||
RemoteBranch string `json:"remote_branch,omitempty"`
|
||||
Files map[string]FileInfo `json:"files,omitempty"`
|
||||
}
|
||||
|
||||
// FileInfo represents information about a file
|
||||
type FileInfo struct {
|
||||
Path string `json:"path"`
|
||||
Status string `json:"status"` // modified, added, deleted, untracked, renamed
|
||||
Additions int `json:"additions,omitempty"`
|
||||
Deletions int `json:"deletions,omitempty"`
|
||||
OldPath string `json:"old_path,omitempty"` // For renamed files
|
||||
Diff string `json:"diff,omitempty"`
|
||||
}
|
||||
|
||||
// FileListUpdate represents a file listing update
|
||||
type FileListUpdate struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Files []FileEntry `json:"files"`
|
||||
}
|
||||
|
||||
// FileEntry represents a file in the workspace
|
||||
type FileEntry struct {
|
||||
Path string `json:"path"`
|
||||
IsDir bool `json:"is_dir"`
|
||||
Size int64 `json:"size,omitempty"`
|
||||
}
|
||||
|
||||
// FileTreeNode represents a node in the file tree
|
||||
type FileTreeNode struct {
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
IsDir bool `json:"is_dir"`
|
||||
Size int64 `json:"size,omitempty"`
|
||||
Children []*FileTreeNode `json:"children,omitempty"`
|
||||
}
|
||||
|
||||
// FileTreeRequest represents a request for file tree
|
||||
type FileTreeRequest struct {
|
||||
Path string `json:"path"` // Path to get tree for (relative to workspace root)
|
||||
Depth int `json:"depth"` // Depth to traverse (0 = unlimited, 1 = immediate children only)
|
||||
}
|
||||
|
||||
// FileTreeResponse represents a response with file tree
|
||||
type FileTreeResponse struct {
|
||||
RequestID string `json:"request_id"`
|
||||
Root *FileTreeNode `json:"root"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// FileContentRequest represents a request for file content
|
||||
type FileContentRequest struct {
|
||||
Path string `json:"path"` // Path to file (relative to workspace root)
|
||||
}
|
||||
|
||||
// FileContentResponse represents a response with file content
|
||||
type FileContentResponse struct {
|
||||
RequestID string `json:"request_id"`
|
||||
Path string `json:"path"`
|
||||
Content string `json:"content"`
|
||||
Size int64 `json:"size"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// FileChangeNotification represents a filesystem change notification
|
||||
type FileChangeNotification struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Path string `json:"path"`
|
||||
Operation string `json:"operation"` // create, write, remove, rename, chmod, refresh
|
||||
}
|
||||
|
||||
// GitStatusSubscriber is a channel that receives git status updates
|
||||
type GitStatusSubscriber chan GitStatusUpdate
|
||||
|
||||
// FilesSubscriber is a channel that receives file listing updates
|
||||
type FilesSubscriber chan FileListUpdate
|
||||
|
||||
// FileChangeSubscriber is a channel that receives file change notifications
|
||||
type FileChangeSubscriber chan FileChangeNotification
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@ import (
|
||||
"sync"
|
||||
|
||||
"github.com/coder/acp-go-sdk"
|
||||
acpclient "github.com/kandev/kandev/internal/agentctl/acp"
|
||||
acpclient "github.com/kandev/kandev/internal/agentctl/server/acp"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
+2
-2
@@ -6,8 +6,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/kandev/kandev/internal/agentctl/config"
|
||||
"github.com/kandev/kandev/internal/agentctl/instance"
|
||||
"github.com/kandev/kandev/internal/agentctl/server/config"
|
||||
"github.com/kandev/kandev/internal/agentctl/server/instance"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
+49
-2
@@ -7,8 +7,8 @@ import (
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/kandev/kandev/internal/agentctl/config"
|
||||
"github.com/kandev/kandev/internal/agentctl/process"
|
||||
"github.com/kandev/kandev/internal/agentctl/server/config"
|
||||
"github.com/kandev/kandev/internal/agentctl/server/process"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
@@ -60,6 +60,7 @@ func (s *Server) setupRoutes() {
|
||||
api.GET("/info", s.handleInfo)
|
||||
|
||||
// Process control
|
||||
api.POST("/agent/configure", s.handleAgentConfigure)
|
||||
api.POST("/start", s.handleStart)
|
||||
api.POST("/stop", s.handleStop)
|
||||
|
||||
@@ -162,6 +163,52 @@ func (s *Server) handleStart(c *gin.Context) {
|
||||
})
|
||||
}
|
||||
|
||||
// AgentConfigure request/response - configures the agent command before starting
|
||||
type AgentConfigureRequest struct {
|
||||
Command string `json:"command"`
|
||||
Env map[string]string `json:"env,omitempty"`
|
||||
}
|
||||
|
||||
type AgentConfigureResponse struct {
|
||||
Success bool `json:"success"`
|
||||
Message string `json:"message,omitempty"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func (s *Server) handleAgentConfigure(c *gin.Context) {
|
||||
var req AgentConfigureRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, AgentConfigureResponse{
|
||||
Success: false,
|
||||
Error: "invalid request: " + err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if req.Command == "" {
|
||||
c.JSON(http.StatusBadRequest, AgentConfigureResponse{
|
||||
Success: false,
|
||||
Error: "command is required",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
if err := s.procMgr.Configure(req.Command, req.Env); err != nil {
|
||||
s.logger.Error("failed to configure agent", zap.Error(err), zap.String("command", req.Command))
|
||||
c.JSON(http.StatusInternalServerError, AgentConfigureResponse{
|
||||
Success: false,
|
||||
Error: err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
s.logger.Info("agent configured", zap.String("command", req.Command))
|
||||
c.JSON(http.StatusOK, AgentConfigureResponse{
|
||||
Success: true,
|
||||
Message: "agent configured",
|
||||
})
|
||||
}
|
||||
|
||||
// Stop request/response
|
||||
type StopRequest struct {
|
||||
Force bool `json:"force"`
|
||||
+6
-6
@@ -5,7 +5,7 @@ import (
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/gorilla/websocket"
|
||||
"github.com/kandev/kandev/internal/agentctl/process"
|
||||
"github.com/kandev/kandev/internal/agentctl/types"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
@@ -171,28 +171,28 @@ func (s *Server) handleFileTree(c *gin.Context) {
|
||||
|
||||
tree, err := s.procMgr.GetWorkspaceTracker().GetFileTree(path, depth)
|
||||
if err != nil {
|
||||
c.JSON(400, process.FileTreeResponse{Error: err.Error()})
|
||||
c.JSON(400, types.FileTreeResponse{Error: err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(200, process.FileTreeResponse{Root: tree})
|
||||
c.JSON(200, types.FileTreeResponse{Root: tree})
|
||||
}
|
||||
|
||||
// handleFileContent handles file content requests via HTTP GET
|
||||
func (s *Server) handleFileContent(c *gin.Context) {
|
||||
path := c.Query("path")
|
||||
if path == "" {
|
||||
c.JSON(400, process.FileContentResponse{Error: "path is required"})
|
||||
c.JSON(400, types.FileContentResponse{Error: "path is required"})
|
||||
return
|
||||
}
|
||||
|
||||
content, size, err := s.procMgr.GetWorkspaceTracker().GetFileContent(path)
|
||||
if err != nil {
|
||||
c.JSON(400, process.FileContentResponse{Path: path, Error: err.Error(), Size: size})
|
||||
c.JSON(400, types.FileContentResponse{Path: path, Error: err.Error(), Size: size})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(200, process.FileContentResponse{Path: path, Content: content, Size: size})
|
||||
c.JSON(200, types.FileContentResponse{Path: path, Content: content, Size: size})
|
||||
}
|
||||
|
||||
// mustParseInt parses a string to int, returns 0 on error
|
||||
+1
-1
@@ -7,7 +7,7 @@ import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/agentctl/process"
|
||||
"github.com/kandev/kandev/internal/agentctl/server/process"
|
||||
)
|
||||
|
||||
// Instance represents a single agent instance running as a subprocess.
|
||||
+2
-2
@@ -10,8 +10,8 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/kandev/kandev/internal/agentctl/config"
|
||||
"github.com/kandev/kandev/internal/agentctl/process"
|
||||
"github.com/kandev/kandev/internal/agentctl/server/config"
|
||||
"github.com/kandev/kandev/internal/agentctl/server/process"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/pkg/agent"
|
||||
"go.uber.org/zap"
|
||||
+41
-3
@@ -11,9 +11,9 @@ import (
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/agentctl/adapter"
|
||||
"github.com/kandev/kandev/internal/agentctl/config"
|
||||
"github.com/kandev/kandev/internal/agentctl/shell"
|
||||
"github.com/kandev/kandev/internal/agentctl/server/adapter"
|
||||
"github.com/kandev/kandev/internal/agentctl/server/config"
|
||||
"github.com/kandev/kandev/internal/agentctl/server/shell"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/pkg/agent"
|
||||
"go.uber.org/zap"
|
||||
@@ -235,6 +235,44 @@ func (m *Manager) Start(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// Configure sets the agent command and optional environment variables.
|
||||
// This must be called before Start() if the instance was created without a command.
|
||||
func (m *Manager) Configure(command string, env map[string]string) error {
|
||||
m.startMu.Lock()
|
||||
defer m.startMu.Unlock()
|
||||
|
||||
if m.Status() == StatusRunning || m.Status() == StatusStarting {
|
||||
return fmt.Errorf("cannot configure while agent is running")
|
||||
}
|
||||
|
||||
if command == "" {
|
||||
return fmt.Errorf("agent command cannot be empty")
|
||||
}
|
||||
|
||||
// Parse the command string and update config
|
||||
args := config.ParseCommand(command)
|
||||
if len(args) == 0 {
|
||||
return fmt.Errorf("failed to parse agent command")
|
||||
}
|
||||
|
||||
m.cfg.AgentCommand = command
|
||||
m.cfg.AgentArgs = args
|
||||
|
||||
// Merge additional env vars
|
||||
if len(env) > 0 {
|
||||
for k, v := range env {
|
||||
m.cfg.AgentEnv = append(m.cfg.AgentEnv, fmt.Sprintf("%s=%s", k, v))
|
||||
}
|
||||
}
|
||||
|
||||
m.logger.Info("agent configured",
|
||||
zap.String("command", command),
|
||||
zap.Strings("args", args),
|
||||
zap.Int("env_count", len(env)))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// createAdapter creates the appropriate protocol adapter based on configuration
|
||||
func (m *Manager) createAdapter() error {
|
||||
protocol := m.cfg.Protocol
|
||||
+36
-35
@@ -14,6 +14,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
"github.com/kandev/kandev/internal/agentctl/types"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
@@ -24,14 +25,14 @@ type WorkspaceTracker struct {
|
||||
logger *logger.Logger
|
||||
|
||||
// Current state
|
||||
currentStatus GitStatusUpdate
|
||||
currentFiles FileListUpdate
|
||||
currentStatus types.GitStatusUpdate
|
||||
currentFiles types.FileListUpdate
|
||||
mu sync.RWMutex
|
||||
|
||||
// Subscribers
|
||||
gitStatusSubscribers map[GitStatusSubscriber]struct{}
|
||||
filesSubscribers map[FilesSubscriber]struct{}
|
||||
fileChangeSubscribers map[FileChangeSubscriber]struct{}
|
||||
gitStatusSubscribers map[types.GitStatusSubscriber]struct{}
|
||||
filesSubscribers map[types.FilesSubscriber]struct{}
|
||||
fileChangeSubscribers map[types.FileChangeSubscriber]struct{}
|
||||
subMu sync.RWMutex
|
||||
|
||||
// Filesystem watcher
|
||||
@@ -56,9 +57,9 @@ func NewWorkspaceTracker(workDir string, log *logger.Logger) *WorkspaceTracker {
|
||||
return &WorkspaceTracker{
|
||||
workDir: workDir,
|
||||
logger: log.WithFields(zap.String("component", "workspace-tracker")),
|
||||
gitStatusSubscribers: make(map[GitStatusSubscriber]struct{}),
|
||||
filesSubscribers: make(map[FilesSubscriber]struct{}),
|
||||
fileChangeSubscribers: make(map[FileChangeSubscriber]struct{}),
|
||||
gitStatusSubscribers: make(map[types.GitStatusSubscriber]struct{}),
|
||||
filesSubscribers: make(map[types.FilesSubscriber]struct{}),
|
||||
fileChangeSubscribers: make(map[types.FileChangeSubscriber]struct{}),
|
||||
watcher: watcher,
|
||||
fsChangeTrigger: make(chan struct{}, 1), // Buffered to avoid blocking
|
||||
stopCh: make(chan struct{}),
|
||||
@@ -147,7 +148,7 @@ func (wt *WorkspaceTracker) monitorLoop(ctx context.Context) {
|
||||
wt.updateGitStatus(ctx)
|
||||
wt.updateFiles(ctx)
|
||||
// Notify file change subscribers that workspace changed
|
||||
wt.notifyFileChangeSubscribers(FileChangeNotification{
|
||||
wt.notifyFileChangeSubscribers(types.FileChangeNotification{
|
||||
Timestamp: time.Now(),
|
||||
Path: "",
|
||||
Operation: "refresh",
|
||||
@@ -175,15 +176,15 @@ func (wt *WorkspaceTracker) updateGitStatus(ctx context.Context) {
|
||||
}
|
||||
|
||||
// getGitStatus retrieves the current git status
|
||||
func (wt *WorkspaceTracker) getGitStatus(ctx context.Context) (GitStatusUpdate, error) {
|
||||
update := GitStatusUpdate{
|
||||
func (wt *WorkspaceTracker) getGitStatus(ctx context.Context) (types.GitStatusUpdate, error) {
|
||||
update := types.GitStatusUpdate{
|
||||
Timestamp: time.Now(),
|
||||
Modified: []string{},
|
||||
Added: []string{},
|
||||
Deleted: []string{},
|
||||
Untracked: []string{},
|
||||
Renamed: []string{},
|
||||
Files: make(map[string]FileInfo),
|
||||
Files: make(map[string]types.FileInfo),
|
||||
}
|
||||
|
||||
// Get current branch
|
||||
@@ -233,7 +234,7 @@ func (wt *WorkspaceTracker) getGitStatus(ctx context.Context) (GitStatusUpdate,
|
||||
statusCode := line[:2]
|
||||
filePath := strings.TrimSpace(line[3:])
|
||||
|
||||
fileInfo := FileInfo{
|
||||
fileInfo := types.FileInfo{
|
||||
Path: filePath,
|
||||
}
|
||||
|
||||
@@ -271,7 +272,7 @@ func (wt *WorkspaceTracker) getGitStatus(ctx context.Context) (GitStatusUpdate,
|
||||
}
|
||||
|
||||
// enrichWithDiffData adds diff information (additions, deletions, diff content) to file info
|
||||
func (wt *WorkspaceTracker) enrichWithDiffData(ctx context.Context, update *GitStatusUpdate) {
|
||||
func (wt *WorkspaceTracker) enrichWithDiffData(ctx context.Context, update *types.GitStatusUpdate) {
|
||||
// Determine the base ref to compare against
|
||||
// Use remote branch if available, otherwise use HEAD
|
||||
baseRef := "HEAD"
|
||||
@@ -321,7 +322,7 @@ func (wt *WorkspaceTracker) enrichWithDiffData(ctx context.Context, update *GitS
|
||||
} else {
|
||||
// File might be committed but not in status (because it's committed)
|
||||
// Add it to the Files map
|
||||
fileInfo := FileInfo{
|
||||
fileInfo := types.FileInfo{
|
||||
Path: filePath,
|
||||
Status: "modified", // Assume modified if it has a diff
|
||||
Additions: additions,
|
||||
@@ -431,10 +432,10 @@ func (wt *WorkspaceTracker) updateFiles(ctx context.Context) {
|
||||
}
|
||||
|
||||
// getFileList retrieves the list of files in the workspace
|
||||
func (wt *WorkspaceTracker) getFileList(ctx context.Context) (FileListUpdate, error) {
|
||||
update := FileListUpdate{
|
||||
func (wt *WorkspaceTracker) getFileList(ctx context.Context) (types.FileListUpdate, error) {
|
||||
update := types.FileListUpdate{
|
||||
Timestamp: time.Now(),
|
||||
Files: []FileEntry{},
|
||||
Files: []types.FileEntry{},
|
||||
}
|
||||
|
||||
// Use git ls-files to get tracked files
|
||||
@@ -451,7 +452,7 @@ func (wt *WorkspaceTracker) getFileList(ctx context.Context) (FileListUpdate, er
|
||||
if line == "" {
|
||||
continue
|
||||
}
|
||||
update.Files = append(update.Files, FileEntry{
|
||||
update.Files = append(update.Files, types.FileEntry{
|
||||
Path: line,
|
||||
IsDir: false,
|
||||
})
|
||||
@@ -465,8 +466,8 @@ func (wt *WorkspaceTracker) getFileList(ctx context.Context) (FileListUpdate, er
|
||||
// Subscriber management methods
|
||||
|
||||
// SubscribeGitStatus creates a new git status subscriber
|
||||
func (wt *WorkspaceTracker) SubscribeGitStatus() GitStatusSubscriber {
|
||||
sub := make(GitStatusSubscriber, 10)
|
||||
func (wt *WorkspaceTracker) SubscribeGitStatus() types.GitStatusSubscriber {
|
||||
sub := make(types.GitStatusSubscriber, 10)
|
||||
|
||||
wt.subMu.Lock()
|
||||
wt.gitStatusSubscribers[sub] = struct{}{}
|
||||
@@ -490,7 +491,7 @@ func (wt *WorkspaceTracker) SubscribeGitStatus() GitStatusSubscriber {
|
||||
}
|
||||
|
||||
// UnsubscribeGitStatus removes a git status subscriber
|
||||
func (wt *WorkspaceTracker) UnsubscribeGitStatus(sub GitStatusSubscriber) {
|
||||
func (wt *WorkspaceTracker) UnsubscribeGitStatus(sub types.GitStatusSubscriber) {
|
||||
wt.subMu.Lock()
|
||||
delete(wt.gitStatusSubscribers, sub)
|
||||
wt.subMu.Unlock()
|
||||
@@ -498,8 +499,8 @@ func (wt *WorkspaceTracker) UnsubscribeGitStatus(sub GitStatusSubscriber) {
|
||||
}
|
||||
|
||||
// SubscribeFiles creates a new files subscriber
|
||||
func (wt *WorkspaceTracker) SubscribeFiles() FilesSubscriber {
|
||||
sub := make(FilesSubscriber, 10)
|
||||
func (wt *WorkspaceTracker) SubscribeFiles() types.FilesSubscriber {
|
||||
sub := make(types.FilesSubscriber, 10)
|
||||
|
||||
wt.subMu.Lock()
|
||||
wt.filesSubscribers[sub] = struct{}{}
|
||||
@@ -523,7 +524,7 @@ func (wt *WorkspaceTracker) SubscribeFiles() FilesSubscriber {
|
||||
}
|
||||
|
||||
// UnsubscribeFiles removes a files subscriber
|
||||
func (wt *WorkspaceTracker) UnsubscribeFiles(sub FilesSubscriber) {
|
||||
func (wt *WorkspaceTracker) UnsubscribeFiles(sub types.FilesSubscriber) {
|
||||
wt.subMu.Lock()
|
||||
delete(wt.filesSubscribers, sub)
|
||||
wt.subMu.Unlock()
|
||||
@@ -533,7 +534,7 @@ func (wt *WorkspaceTracker) UnsubscribeFiles(sub FilesSubscriber) {
|
||||
// Notification methods
|
||||
|
||||
// notifyGitStatusSubscribers notifies all git status subscribers
|
||||
func (wt *WorkspaceTracker) notifyGitStatusSubscribers(update GitStatusUpdate) {
|
||||
func (wt *WorkspaceTracker) notifyGitStatusSubscribers(update types.GitStatusUpdate) {
|
||||
wt.subMu.RLock()
|
||||
defer wt.subMu.RUnlock()
|
||||
|
||||
@@ -547,7 +548,7 @@ func (wt *WorkspaceTracker) notifyGitStatusSubscribers(update GitStatusUpdate) {
|
||||
}
|
||||
|
||||
// notifyFilesSubscribers notifies all files subscribers
|
||||
func (wt *WorkspaceTracker) notifyFilesSubscribers(update FileListUpdate) {
|
||||
func (wt *WorkspaceTracker) notifyFilesSubscribers(update types.FileListUpdate) {
|
||||
wt.subMu.RLock()
|
||||
defer wt.subMu.RUnlock()
|
||||
|
||||
@@ -563,8 +564,8 @@ func (wt *WorkspaceTracker) notifyFilesSubscribers(update FileListUpdate) {
|
||||
|
||||
|
||||
// SubscribeFileChanges creates a new file change subscriber
|
||||
func (wt *WorkspaceTracker) SubscribeFileChanges() FileChangeSubscriber {
|
||||
sub := make(FileChangeSubscriber, 100)
|
||||
func (wt *WorkspaceTracker) SubscribeFileChanges() types.FileChangeSubscriber {
|
||||
sub := make(types.FileChangeSubscriber, 100)
|
||||
|
||||
wt.subMu.Lock()
|
||||
wt.fileChangeSubscribers[sub] = struct{}{}
|
||||
@@ -574,7 +575,7 @@ func (wt *WorkspaceTracker) SubscribeFileChanges() FileChangeSubscriber {
|
||||
}
|
||||
|
||||
// UnsubscribeFileChanges removes a file change subscriber
|
||||
func (wt *WorkspaceTracker) UnsubscribeFileChanges(sub FileChangeSubscriber) {
|
||||
func (wt *WorkspaceTracker) UnsubscribeFileChanges(sub types.FileChangeSubscriber) {
|
||||
wt.subMu.Lock()
|
||||
delete(wt.fileChangeSubscribers, sub)
|
||||
wt.subMu.Unlock()
|
||||
@@ -582,7 +583,7 @@ func (wt *WorkspaceTracker) UnsubscribeFileChanges(sub FileChangeSubscriber) {
|
||||
}
|
||||
|
||||
// notifyFileChangeSubscribers notifies all file change subscribers
|
||||
func (wt *WorkspaceTracker) notifyFileChangeSubscribers(notification FileChangeNotification) {
|
||||
func (wt *WorkspaceTracker) notifyFileChangeSubscribers(notification types.FileChangeNotification) {
|
||||
wt.subMu.RLock()
|
||||
defer wt.subMu.RUnlock()
|
||||
|
||||
@@ -660,7 +661,7 @@ func (wt *WorkspaceTracker) addDirectoryRecursive(dir string) error {
|
||||
}
|
||||
|
||||
// GetFileTree returns the file tree for a given path and depth
|
||||
func (wt *WorkspaceTracker) GetFileTree(reqPath string, depth int) (*FileTreeNode, error) {
|
||||
func (wt *WorkspaceTracker) GetFileTree(reqPath string, depth int) (*types.FileTreeNode, error) {
|
||||
// Resolve the full path
|
||||
fullPath := filepath.Join(wt.workDir, reqPath)
|
||||
|
||||
@@ -680,8 +681,8 @@ func (wt *WorkspaceTracker) GetFileTree(reqPath string, depth int) (*FileTreeNod
|
||||
}
|
||||
|
||||
// buildFileTreeNode recursively builds a file tree node
|
||||
func (wt *WorkspaceTracker) buildFileTreeNode(fullPath, relPath string, info os.FileInfo, maxDepth, currentDepth int) (*FileTreeNode, error) {
|
||||
node := &FileTreeNode{
|
||||
func (wt *WorkspaceTracker) buildFileTreeNode(fullPath, relPath string, info os.FileInfo, maxDepth, currentDepth int) (*types.FileTreeNode, error) {
|
||||
node := &types.FileTreeNode{
|
||||
Name: info.Name(),
|
||||
Path: relPath,
|
||||
IsDir: info.IsDir(),
|
||||
@@ -700,7 +701,7 @@ func (wt *WorkspaceTracker) buildFileTreeNode(fullPath, relPath string, info os.
|
||||
}
|
||||
|
||||
// Build children
|
||||
node.Children = make([]*FileTreeNode, 0, len(entries))
|
||||
node.Children = make([]*types.FileTreeNode, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
// Skip hidden files and common ignore patterns
|
||||
name := entry.Name()
|
||||
@@ -2,7 +2,10 @@
|
||||
// This breaks import cycles between adapter and acp packages.
|
||||
package types
|
||||
|
||||
import "context"
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Permission action types - categorize the kind of action requiring approval
|
||||
const (
|
||||
@@ -56,3 +59,93 @@ type PermissionResponse struct {
|
||||
// PermissionHandler is called when the agent requests permission for an action
|
||||
type PermissionHandler func(ctx context.Context, req *PermissionRequest) (*PermissionResponse, error)
|
||||
|
||||
// GitStatusUpdate represents a git status update
|
||||
type GitStatusUpdate struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Modified []string `json:"modified"`
|
||||
Added []string `json:"added"`
|
||||
Deleted []string `json:"deleted"`
|
||||
Untracked []string `json:"untracked"`
|
||||
Renamed []string `json:"renamed"`
|
||||
Ahead int `json:"ahead"`
|
||||
Behind int `json:"behind"`
|
||||
Branch string `json:"branch"`
|
||||
RemoteBranch string `json:"remote_branch,omitempty"`
|
||||
Files map[string]FileInfo `json:"files,omitempty"`
|
||||
}
|
||||
|
||||
// FileInfo represents information about a file
|
||||
type FileInfo struct {
|
||||
Path string `json:"path"`
|
||||
Status string `json:"status"` // modified, added, deleted, untracked, renamed
|
||||
Additions int `json:"additions,omitempty"`
|
||||
Deletions int `json:"deletions,omitempty"`
|
||||
OldPath string `json:"old_path,omitempty"` // For renamed files
|
||||
Diff string `json:"diff,omitempty"`
|
||||
}
|
||||
|
||||
// FileListUpdate represents a file listing update
|
||||
type FileListUpdate struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Files []FileEntry `json:"files"`
|
||||
}
|
||||
|
||||
// FileEntry represents a file in the workspace
|
||||
type FileEntry struct {
|
||||
Path string `json:"path"`
|
||||
IsDir bool `json:"is_dir"`
|
||||
Size int64 `json:"size,omitempty"`
|
||||
}
|
||||
|
||||
// FileTreeNode represents a node in the file tree
|
||||
type FileTreeNode struct {
|
||||
Name string `json:"name"`
|
||||
Path string `json:"path"`
|
||||
IsDir bool `json:"is_dir"`
|
||||
Size int64 `json:"size,omitempty"`
|
||||
Children []*FileTreeNode `json:"children,omitempty"`
|
||||
}
|
||||
|
||||
// FileTreeRequest represents a request for file tree
|
||||
type FileTreeRequest struct {
|
||||
Path string `json:"path"` // Path to get tree for (relative to workspace root)
|
||||
Depth int `json:"depth"` // Depth to traverse (0 = unlimited, 1 = immediate children only)
|
||||
}
|
||||
|
||||
// FileTreeResponse represents a response with file tree
|
||||
type FileTreeResponse struct {
|
||||
RequestID string `json:"request_id"`
|
||||
Root *FileTreeNode `json:"root"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// FileContentRequest represents a request for file content
|
||||
type FileContentRequest struct {
|
||||
Path string `json:"path"` // Path to file (relative to workspace root)
|
||||
}
|
||||
|
||||
// FileContentResponse represents a response with file content
|
||||
type FileContentResponse struct {
|
||||
RequestID string `json:"request_id"`
|
||||
Path string `json:"path"`
|
||||
Content string `json:"content"`
|
||||
Size int64 `json:"size"`
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// FileChangeNotification represents a filesystem change notification
|
||||
type FileChangeNotification struct {
|
||||
Timestamp time.Time `json:"timestamp"`
|
||||
Path string `json:"path"`
|
||||
Operation string `json:"operation"` // create, write, remove, rename, chmod, refresh
|
||||
}
|
||||
|
||||
// GitStatusSubscriber is a channel that receives git status updates
|
||||
type GitStatusSubscriber chan GitStatusUpdate
|
||||
|
||||
// FilesSubscriber is a channel that receives file listing updates
|
||||
type FilesSubscriber chan FileListUpdate
|
||||
|
||||
// FileChangeSubscriber is a channel that receives file change notifications
|
||||
type FileChangeSubscriber chan FileChangeNotification
|
||||
|
||||
|
||||
@@ -55,7 +55,7 @@ type SimulatedAgentManagerClient struct {
|
||||
shouldFail bool
|
||||
failAfter int // Fail after N successful launches
|
||||
launchCount int32
|
||||
acpMessageFn func(taskID, instanceID string) []protocol.Message // Custom ACP messages
|
||||
acpMessageFn func(taskID, executionID string) []protocol.Message // Custom ACP messages
|
||||
stopCh chan struct{}
|
||||
}
|
||||
|
||||
@@ -102,7 +102,7 @@ func (s *SimulatedAgentManagerClient) SetFailAfter(n int) {
|
||||
}
|
||||
|
||||
// SetACPMessageFn sets a custom function to generate ACP messages
|
||||
func (s *SimulatedAgentManagerClient) SetACPMessageFn(fn func(taskID, instanceID string) []protocol.Message) {
|
||||
func (s *SimulatedAgentManagerClient) SetACPMessageFn(fn func(taskID, executionID string) []protocol.Message) {
|
||||
s.acpMessageFn = fn
|
||||
}
|
||||
|
||||
@@ -118,30 +118,37 @@ func (s *SimulatedAgentManagerClient) LaunchAgent(ctx context.Context, req *exec
|
||||
return nil, fmt.Errorf("simulated launch failure after %d attempts", s.failAfter)
|
||||
}
|
||||
|
||||
instanceID := uuid.New().String()
|
||||
containerID := "sim-container-" + instanceID[:8]
|
||||
executionID := uuid.New().String()
|
||||
containerID := "sim-container-" + executionID[:8]
|
||||
|
||||
s.mu.Lock()
|
||||
instance := &simulatedInstance{
|
||||
id: instanceID,
|
||||
id: executionID,
|
||||
taskID: req.TaskID,
|
||||
agentProfileID: req.AgentProfileID,
|
||||
status: v1.AgentStatusStarting,
|
||||
stopCh: make(chan struct{}),
|
||||
}
|
||||
s.instances[instanceID] = instance
|
||||
s.instances[executionID] = instance
|
||||
s.mu.Unlock()
|
||||
|
||||
// Simulate agent lifecycle in background
|
||||
go s.runAgentSimulation(instance, req)
|
||||
|
||||
return &executor.LaunchAgentResponse{
|
||||
AgentInstanceID: instanceID,
|
||||
AgentExecutionID: executionID,
|
||||
ContainerID: containerID,
|
||||
Status: v1.AgentStatusStarting,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// StartAgentProcess simulates starting the agent subprocess
|
||||
func (s *SimulatedAgentManagerClient) StartAgentProcess(ctx context.Context, agentExecutionID string) error {
|
||||
s.logger.Info("simulated: starting agent process",
|
||||
zap.String("agent_execution_id", agentExecutionID))
|
||||
return nil
|
||||
}
|
||||
|
||||
// runAgentSimulation simulates the agent execution lifecycle
|
||||
func (s *SimulatedAgentManagerClient) runAgentSimulation(instance *simulatedInstance, req *executor.LaunchAgentRequest) {
|
||||
// Wait for launch delay
|
||||
@@ -259,42 +266,42 @@ func (s *SimulatedAgentManagerClient) publishACPMessages(instance *simulatedInst
|
||||
}
|
||||
|
||||
// StopAgent simulates stopping an agent
|
||||
func (s *SimulatedAgentManagerClient) StopAgent(ctx context.Context, agentInstanceID string, force bool) error {
|
||||
func (s *SimulatedAgentManagerClient) StopAgent(ctx context.Context, agentExecutionID string, force bool) error {
|
||||
s.mu.Lock()
|
||||
instance, exists := s.instances[agentInstanceID]
|
||||
execution, exists := s.instances[agentExecutionID]
|
||||
s.mu.Unlock()
|
||||
|
||||
if !exists {
|
||||
return fmt.Errorf("agent instance %q not found", agentInstanceID)
|
||||
return fmt.Errorf("agent execution %q not found", agentExecutionID)
|
||||
}
|
||||
|
||||
close(instance.stopCh)
|
||||
instance.statusMu.Lock()
|
||||
instance.status = v1.AgentStatusStopped
|
||||
instance.statusMu.Unlock()
|
||||
close(execution.stopCh)
|
||||
execution.statusMu.Lock()
|
||||
execution.status = v1.AgentStatusStopped
|
||||
execution.statusMu.Unlock()
|
||||
|
||||
s.publishAgentEvent(events.AgentStopped, instance)
|
||||
s.publishAgentEvent(events.AgentStopped, execution)
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAgentStatus returns the status of a simulated agent
|
||||
func (s *SimulatedAgentManagerClient) GetAgentStatus(ctx context.Context, agentInstanceID string) (*v1.AgentInstance, error) {
|
||||
func (s *SimulatedAgentManagerClient) GetAgentStatus(ctx context.Context, agentExecutionID string) (*v1.AgentExecution, error) {
|
||||
s.mu.Lock()
|
||||
instance, exists := s.instances[agentInstanceID]
|
||||
execution, exists := s.instances[agentExecutionID]
|
||||
s.mu.Unlock()
|
||||
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("agent instance %q not found", agentInstanceID)
|
||||
return nil, fmt.Errorf("agent execution %q not found", agentExecutionID)
|
||||
}
|
||||
|
||||
instance.statusMu.Lock()
|
||||
status := instance.status
|
||||
instance.statusMu.Unlock()
|
||||
execution.statusMu.Lock()
|
||||
status := execution.status
|
||||
execution.statusMu.Unlock()
|
||||
|
||||
return &v1.AgentInstance{
|
||||
ID: instance.id,
|
||||
TaskID: instance.taskID,
|
||||
AgentProfileID: instance.agentProfileID,
|
||||
return &v1.AgentExecution{
|
||||
ID: execution.id,
|
||||
TaskID: execution.taskID,
|
||||
AgentProfileID: execution.agentProfileID,
|
||||
Status: status,
|
||||
}, nil
|
||||
}
|
||||
@@ -322,13 +329,13 @@ func (s *SimulatedAgentManagerClient) ListAgentTypes(ctx context.Context) ([]*v1
|
||||
}
|
||||
|
||||
// PromptAgent sends a follow-up prompt to a running agent
|
||||
func (s *SimulatedAgentManagerClient) PromptAgent(ctx context.Context, agentInstanceID string, prompt string) (*executor.PromptResult, error) {
|
||||
func (s *SimulatedAgentManagerClient) PromptAgent(ctx context.Context, agentExecutionID string, prompt string) (*executor.PromptResult, error) {
|
||||
s.mu.Lock()
|
||||
instance, exists := s.instances[agentInstanceID]
|
||||
execution, exists := s.instances[agentExecutionID]
|
||||
s.mu.Unlock()
|
||||
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("agent instance %q not found", agentInstanceID)
|
||||
return nil, fmt.Errorf("agent execution %q not found", agentExecutionID)
|
||||
}
|
||||
|
||||
// Simulate receiving prompt and generating response
|
||||
@@ -337,7 +344,7 @@ func (s *SimulatedAgentManagerClient) PromptAgent(ctx context.Context, agentInst
|
||||
|
||||
msg := protocol.Message{
|
||||
Type: protocol.MessageTypeLog,
|
||||
TaskID: instance.taskID,
|
||||
TaskID: execution.taskID,
|
||||
Timestamp: time.Now(),
|
||||
Data: map[string]interface{}{
|
||||
"level": "info",
|
||||
@@ -353,7 +360,7 @@ func (s *SimulatedAgentManagerClient) PromptAgent(ctx context.Context, agentInst
|
||||
}
|
||||
|
||||
event := bus.NewEvent(events.ACPMessage, "simulated-agent", msgData)
|
||||
subject := events.BuildACPSubject(instance.taskID)
|
||||
subject := events.BuildACPSubject(execution.taskID)
|
||||
if err := s.eventBus.Publish(context.Background(), subject, event); err != nil {
|
||||
s.logger.Warn("failed to publish simulated ACP message", zap.Error(err))
|
||||
}
|
||||
@@ -375,31 +382,31 @@ func (s *SimulatedAgentManagerClient) RespondToPermissionByTaskID(ctx context.Co
|
||||
}
|
||||
|
||||
// CompleteAgent marks an agent as completed
|
||||
func (s *SimulatedAgentManagerClient) CompleteAgent(instanceID string) {
|
||||
func (s *SimulatedAgentManagerClient) CompleteAgent(executionID string) {
|
||||
s.mu.Lock()
|
||||
instance, exists := s.instances[instanceID]
|
||||
execution, exists := s.instances[executionID]
|
||||
s.mu.Unlock()
|
||||
|
||||
if !exists {
|
||||
return
|
||||
}
|
||||
|
||||
instance.status = v1.AgentStatusCompleted
|
||||
s.publishAgentEvent(events.AgentCompleted, instance)
|
||||
execution.status = v1.AgentStatusCompleted
|
||||
s.publishAgentEvent(events.AgentCompleted, execution)
|
||||
}
|
||||
|
||||
// FailAgent marks an agent as failed
|
||||
func (s *SimulatedAgentManagerClient) FailAgent(instanceID string, reason string) {
|
||||
func (s *SimulatedAgentManagerClient) FailAgent(executionID string, reason string) {
|
||||
s.mu.Lock()
|
||||
instance, exists := s.instances[instanceID]
|
||||
execution, exists := s.instances[executionID]
|
||||
s.mu.Unlock()
|
||||
|
||||
if !exists {
|
||||
return
|
||||
}
|
||||
|
||||
instance.status = v1.AgentStatusFailed
|
||||
s.publishAgentEvent(events.AgentFailed, instance)
|
||||
execution.status = v1.AgentStatusFailed
|
||||
s.publishAgentEvent(events.AgentFailed, execution)
|
||||
}
|
||||
|
||||
// GetLaunchCount returns the number of times LaunchAgent was called
|
||||
@@ -412,8 +419,8 @@ func (s *SimulatedAgentManagerClient) Close() {
|
||||
close(s.stopCh)
|
||||
}
|
||||
|
||||
// GetRecoveredInstances returns recovered instances (none for simulated agent)
|
||||
func (s *SimulatedAgentManagerClient) GetRecoveredInstances() []executor.RecoveredInstanceInfo {
|
||||
// GetRecoveredExecutions returns recovered executions (none for simulated agent)
|
||||
func (s *SimulatedAgentManagerClient) GetRecoveredExecutions() []executor.RecoveredExecutionInfo {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -430,6 +437,10 @@ func (s *SimulatedAgentManagerClient) IsAgentRunningForTask(ctx context.Context,
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *SimulatedAgentManagerClient) CleanupStaleExecutionByTaskID(ctx context.Context, taskID string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// ORCHESTRATOR TEST SERVER
|
||||
// ============================================
|
||||
@@ -863,7 +874,7 @@ func TestOrchestratorStartTask(t *testing.T) {
|
||||
|
||||
assert.True(t, payload["success"].(bool))
|
||||
assert.Equal(t, taskID, payload["task_id"])
|
||||
assert.NotEmpty(t, payload["agent_instance_id"])
|
||||
assert.NotEmpty(t, payload["agent_execution_id"])
|
||||
|
||||
// Wait for ACP notifications
|
||||
time.Sleep(500 * time.Millisecond)
|
||||
@@ -1087,7 +1098,7 @@ func TestOrchestratorACPStreaming(t *testing.T) {
|
||||
defer ts.Close()
|
||||
|
||||
// Configure simulated agent to emit specific ACP messages
|
||||
ts.AgentManager.SetACPMessageFn(func(taskID, instanceID string) []protocol.Message {
|
||||
ts.AgentManager.SetACPMessageFn(func(taskID, executionID string) []protocol.Message {
|
||||
return []protocol.Message{
|
||||
{
|
||||
Type: protocol.MessageTypeProgress,
|
||||
@@ -1438,8 +1449,8 @@ func TestOrchestratorEndToEndWorkflow(t *testing.T) {
|
||||
var startPayload map[string]interface{}
|
||||
require.NoError(t, startResp.ParsePayload(&startPayload))
|
||||
assert.True(t, startPayload["success"].(bool))
|
||||
agentInstanceID := startPayload["agent_instance_id"].(string)
|
||||
assert.NotEmpty(t, agentInstanceID)
|
||||
agentExecutionID := startPayload["agent_execution_id"].(string)
|
||||
assert.NotEmpty(t, agentExecutionID)
|
||||
|
||||
// 6. Collect notifications during execution
|
||||
time.Sleep(400 * time.Millisecond)
|
||||
|
||||
@@ -68,11 +68,11 @@ func (c *Controller) StartTask(ctx context.Context, req dto.StartTaskRequest) (d
|
||||
}
|
||||
|
||||
resp := dto.StartTaskResponse{
|
||||
Success: true,
|
||||
TaskID: execution.TaskID,
|
||||
AgentInstanceID: execution.AgentInstanceID,
|
||||
TaskSessionID: execution.SessionID,
|
||||
State: string(execution.SessionState),
|
||||
Success: true,
|
||||
TaskID: execution.TaskID,
|
||||
AgentExecutionID: execution.AgentExecutionID,
|
||||
TaskSessionID: execution.SessionID,
|
||||
State: string(execution.SessionState),
|
||||
}
|
||||
|
||||
// Include worktree info if available
|
||||
@@ -94,11 +94,11 @@ func (c *Controller) ResumeTaskSession(ctx context.Context, req dto.ResumeTaskSe
|
||||
}
|
||||
|
||||
resp := dto.ResumeTaskSessionResponse{
|
||||
Success: true,
|
||||
TaskID: execution.TaskID,
|
||||
AgentInstanceID: execution.AgentInstanceID,
|
||||
TaskSessionID: execution.SessionID,
|
||||
State: string(execution.SessionState),
|
||||
Success: true,
|
||||
TaskID: execution.TaskID,
|
||||
AgentExecutionID: execution.AgentExecutionID,
|
||||
TaskSessionID: execution.SessionID,
|
||||
State: string(execution.SessionState),
|
||||
}
|
||||
|
||||
if execution.WorktreePath != "" {
|
||||
@@ -111,6 +111,19 @@ func (c *Controller) ResumeTaskSession(ctx context.Context, req dto.ResumeTaskSe
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// GetTaskSessionStatus returns the status of a task session including whether it's resumable
|
||||
func (c *Controller) GetTaskSessionStatus(ctx context.Context, req dto.TaskSessionStatusRequest) (dto.TaskSessionStatusResponse, error) {
|
||||
status, err := c.service.GetTaskSessionStatus(ctx, req.TaskID, req.TaskSessionID)
|
||||
if err != nil {
|
||||
return dto.TaskSessionStatusResponse{
|
||||
SessionID: req.TaskSessionID,
|
||||
TaskID: req.TaskID,
|
||||
Error: err.Error(),
|
||||
}, nil
|
||||
}
|
||||
return status, nil
|
||||
}
|
||||
|
||||
// StopTask stops task execution
|
||||
func (c *Controller) StopTask(ctx context.Context, req dto.StopTaskRequest) (dto.SuccessResponse, error) {
|
||||
reason := req.Reason
|
||||
@@ -174,13 +187,13 @@ func (c *Controller) GetTaskExecution(ctx context.Context, req dto.GetTaskExecut
|
||||
}
|
||||
|
||||
return dto.TaskExecutionResponse{
|
||||
HasExecution: true,
|
||||
TaskID: execution.TaskID,
|
||||
AgentInstanceID: execution.AgentInstanceID,
|
||||
AgentProfileID: execution.AgentProfileID,
|
||||
TaskSessionID: execution.SessionID,
|
||||
State: string(execution.SessionState),
|
||||
Progress: execution.Progress,
|
||||
StartedAt: execution.StartedAt.Format("2006-01-02T15:04:05Z"),
|
||||
HasExecution: true,
|
||||
TaskID: execution.TaskID,
|
||||
AgentExecutionID: execution.AgentExecutionID,
|
||||
AgentProfileID: execution.AgentProfileID,
|
||||
TaskSessionID: execution.SessionID,
|
||||
State: string(execution.SessionState),
|
||||
Progress: execution.Progress,
|
||||
StartedAt: execution.StartedAt.Format("2006-01-02T15:04:05Z"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
@@ -49,13 +49,13 @@ type StartTaskRequest struct {
|
||||
|
||||
// StartTaskResponse is the response for orchestrator.start
|
||||
type StartTaskResponse struct {
|
||||
Success bool `json:"success"`
|
||||
TaskID string `json:"task_id"`
|
||||
AgentInstanceID string `json:"agent_instance_id"`
|
||||
TaskSessionID string `json:"task_session_id,omitempty"`
|
||||
State string `json:"state"`
|
||||
WorktreePath *string `json:"worktree_path,omitempty"`
|
||||
WorktreeBranch *string `json:"worktree_branch,omitempty"`
|
||||
Success bool `json:"success"`
|
||||
TaskID string `json:"task_id"`
|
||||
AgentExecutionID string `json:"agent_execution_id"`
|
||||
TaskSessionID string `json:"task_session_id,omitempty"`
|
||||
State string `json:"state"`
|
||||
WorktreePath *string `json:"worktree_path,omitempty"`
|
||||
WorktreeBranch *string `json:"worktree_branch,omitempty"`
|
||||
}
|
||||
|
||||
// ResumeTaskSessionRequest is the payload for task.session.resume
|
||||
@@ -66,13 +66,44 @@ type ResumeTaskSessionRequest struct {
|
||||
|
||||
// ResumeTaskSessionResponse is the response for task.session.resume
|
||||
type ResumeTaskSessionResponse struct {
|
||||
Success bool `json:"success"`
|
||||
TaskID string `json:"task_id"`
|
||||
AgentInstanceID string `json:"agent_instance_id"`
|
||||
TaskSessionID string `json:"task_session_id,omitempty"`
|
||||
State string `json:"state"`
|
||||
WorktreePath *string `json:"worktree_path,omitempty"`
|
||||
WorktreeBranch *string `json:"worktree_branch,omitempty"`
|
||||
Success bool `json:"success"`
|
||||
TaskID string `json:"task_id"`
|
||||
AgentExecutionID string `json:"agent_execution_id"`
|
||||
TaskSessionID string `json:"task_session_id,omitempty"`
|
||||
State string `json:"state"`
|
||||
WorktreePath *string `json:"worktree_path,omitempty"`
|
||||
WorktreeBranch *string `json:"worktree_branch,omitempty"`
|
||||
}
|
||||
|
||||
// TaskSessionStatusRequest is the payload for task.session.status
|
||||
type TaskSessionStatusRequest struct {
|
||||
TaskID string `json:"task_id"`
|
||||
TaskSessionID string `json:"task_session_id"`
|
||||
}
|
||||
|
||||
// TaskSessionStatusResponse is the response for task.session.status
|
||||
type TaskSessionStatusResponse struct {
|
||||
// Session metadata
|
||||
SessionID string `json:"session_id"`
|
||||
TaskID string `json:"task_id"`
|
||||
State string `json:"state"`
|
||||
AgentProfileID string `json:"agent_profile_id,omitempty"`
|
||||
|
||||
// Runtime status
|
||||
IsAgentRunning bool `json:"is_agent_running"` // Agent process is currently running
|
||||
IsResumable bool `json:"is_resumable"` // Session can be resumed
|
||||
NeedsResume bool `json:"needs_resume"` // Session needs resumption (page reload scenario)
|
||||
ResumeReason string `json:"resume_reason,omitempty"` // Why resume is needed (e.g., "agent_not_running")
|
||||
|
||||
// ACP session info
|
||||
ACPSessionID string `json:"acp_session_id,omitempty"`
|
||||
|
||||
// Worktree info
|
||||
WorktreePath *string `json:"worktree_path,omitempty"`
|
||||
WorktreeBranch *string `json:"worktree_branch,omitempty"`
|
||||
|
||||
// Error info
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
// StopTaskRequest is the payload for orchestrator.stop
|
||||
@@ -132,12 +163,12 @@ type GetTaskExecutionRequest struct {
|
||||
|
||||
// TaskExecutionResponse is the response for task.execution
|
||||
type TaskExecutionResponse struct {
|
||||
HasExecution bool `json:"has_execution"`
|
||||
TaskID string `json:"task_id"`
|
||||
AgentInstanceID string `json:"agent_instance_id,omitempty"`
|
||||
AgentProfileID string `json:"agent_profile_id,omitempty"`
|
||||
TaskSessionID string `json:"task_session_id,omitempty"`
|
||||
State string `json:"state,omitempty"`
|
||||
Progress int `json:"progress,omitempty"`
|
||||
StartedAt string `json:"started_at,omitempty"`
|
||||
HasExecution bool `json:"has_execution"`
|
||||
TaskID string `json:"task_id"`
|
||||
AgentExecutionID string `json:"agent_execution_id,omitempty"`
|
||||
AgentProfileID string `json:"agent_profile_id,omitempty"`
|
||||
TaskSessionID string `json:"task_session_id,omitempty"`
|
||||
State string `json:"state,omitempty"`
|
||||
Progress int `json:"progress,omitempty"`
|
||||
StartedAt string `json:"started_at,omitempty"`
|
||||
}
|
||||
|
||||
@@ -33,31 +33,39 @@ type PromptResult struct {
|
||||
// AgentManagerClient is an interface for the Agent Manager service
|
||||
// This will be implemented via gRPC or HTTP client
|
||||
type AgentManagerClient interface {
|
||||
// LaunchAgent starts a new agent container for a task
|
||||
// LaunchAgent creates a new agentctl instance for a task (agent not started yet)
|
||||
LaunchAgent(ctx context.Context, req *LaunchAgentRequest) (*LaunchAgentResponse, error)
|
||||
|
||||
// StopAgent stops a running agent
|
||||
StopAgent(ctx context.Context, agentInstanceID string, force bool) error
|
||||
// StartAgentProcess starts the agent subprocess for an execution.
|
||||
// The command is built internally based on the execution's agent profile.
|
||||
StartAgentProcess(ctx context.Context, agentExecutionID string) error
|
||||
|
||||
// GetAgentStatus returns the status of an agent instance
|
||||
GetAgentStatus(ctx context.Context, agentInstanceID string) (*v1.AgentInstance, error)
|
||||
// StopAgent stops a running agent
|
||||
StopAgent(ctx context.Context, agentExecutionID string, force bool) error
|
||||
|
||||
// GetAgentStatus returns the status of an agent execution
|
||||
GetAgentStatus(ctx context.Context, agentExecutionID string) (*v1.AgentExecution, error)
|
||||
|
||||
// ListAgentTypes returns available agent types
|
||||
ListAgentTypes(ctx context.Context) ([]*v1.AgentType, error)
|
||||
|
||||
// PromptAgent sends a prompt to a running agent
|
||||
// Returns PromptResult indicating if the agent needs input
|
||||
PromptAgent(ctx context.Context, agentInstanceID string, prompt string) (*PromptResult, error)
|
||||
PromptAgent(ctx context.Context, agentExecutionID string, prompt string) (*PromptResult, error)
|
||||
|
||||
// RespondToPermission sends a response to a permission request
|
||||
RespondToPermissionByTaskID(ctx context.Context, taskID, pendingID, optionID string, cancelled bool) error
|
||||
|
||||
// GetRecoveredInstances returns instances recovered from Docker during startup
|
||||
GetRecoveredInstances() []RecoveredInstanceInfo
|
||||
// GetRecoveredExecutions returns executions recovered from Docker during startup
|
||||
GetRecoveredExecutions() []RecoveredExecutionInfo
|
||||
|
||||
// IsAgentRunningForTask checks if an agent is actually running for a task
|
||||
// This probes the actual agent (Docker container or standalone process) rather than relying on cached state
|
||||
IsAgentRunningForTask(ctx context.Context, taskID string) bool
|
||||
|
||||
// CleanupStaleExecutionByTaskID removes a stale agent execution from tracking without trying to stop it.
|
||||
// This is used when we detect the agent process has stopped but the execution is still tracked.
|
||||
CleanupStaleExecutionByTaskID(ctx context.Context, taskID string) error
|
||||
}
|
||||
|
||||
// LaunchAgentRequest contains parameters for launching an agent
|
||||
@@ -83,23 +91,23 @@ type LaunchAgentRequest struct {
|
||||
|
||||
// LaunchAgentResponse contains the result of launching an agent
|
||||
type LaunchAgentResponse struct {
|
||||
AgentInstanceID string
|
||||
ContainerID string
|
||||
Status v1.AgentStatus
|
||||
WorktreeID string
|
||||
WorktreePath string
|
||||
WorktreeBranch string
|
||||
AgentExecutionID string
|
||||
ContainerID string
|
||||
Status v1.AgentStatus
|
||||
WorktreeID string
|
||||
WorktreePath string
|
||||
WorktreeBranch string
|
||||
}
|
||||
|
||||
// TaskExecution tracks an active task execution (kept for API compatibility)
|
||||
type TaskExecution struct {
|
||||
TaskID string
|
||||
AgentInstanceID string
|
||||
AgentProfileID string
|
||||
StartedAt time.Time
|
||||
SessionState v1.TaskSessionState
|
||||
Progress int
|
||||
LastUpdate time.Time
|
||||
TaskID string
|
||||
AgentExecutionID string
|
||||
AgentProfileID string
|
||||
StartedAt time.Time
|
||||
SessionState v1.TaskSessionState
|
||||
Progress int
|
||||
LastUpdate time.Time
|
||||
// SessionID is the database ID of the agent session
|
||||
SessionID string
|
||||
// Worktree info for the agent
|
||||
@@ -110,14 +118,14 @@ type TaskExecution struct {
|
||||
// FromTaskSession converts a models.TaskSession to TaskExecution
|
||||
func FromTaskSession(s *models.TaskSession) *TaskExecution {
|
||||
execution := &TaskExecution{
|
||||
TaskID: s.TaskID,
|
||||
AgentInstanceID: s.AgentInstanceID,
|
||||
AgentProfileID: s.AgentProfileID,
|
||||
StartedAt: s.StartedAt,
|
||||
SessionState: agentSessionStateToV1(s.State),
|
||||
Progress: s.Progress,
|
||||
LastUpdate: s.UpdatedAt,
|
||||
SessionID: s.ID,
|
||||
TaskID: s.TaskID,
|
||||
AgentExecutionID: s.AgentExecutionID,
|
||||
AgentProfileID: s.AgentProfileID,
|
||||
StartedAt: s.StartedAt,
|
||||
SessionState: agentSessionStateToV1(s.State),
|
||||
Progress: s.Progress,
|
||||
LastUpdate: s.UpdatedAt,
|
||||
SessionID: s.ID,
|
||||
}
|
||||
if len(s.Worktrees) > 0 {
|
||||
execution.WorktreePath = s.Worktrees[0].WorktreePath
|
||||
@@ -202,40 +210,40 @@ func (e *Executor) LoadActiveSessionsFromDB(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// RecoveredInstanceInfo contains info about an instance recovered from Docker
|
||||
type RecoveredInstanceInfo struct {
|
||||
InstanceID string
|
||||
// RecoveredExecutionInfo contains info about an execution recovered from Docker
|
||||
type RecoveredExecutionInfo struct {
|
||||
ExecutionID string
|
||||
TaskID string
|
||||
ContainerID string
|
||||
AgentProfileID string
|
||||
}
|
||||
|
||||
// SyncWithRecoveredInstances ensures the executor's cache is in sync with
|
||||
// instances recovered from Docker by the lifecycle manager.
|
||||
// For each recovered instance, if not already in cache, add it.
|
||||
func (e *Executor) SyncWithRecoveredInstances(ctx context.Context, instances []RecoveredInstanceInfo) {
|
||||
// SyncWithRecoveredExecutions ensures the executor's cache is in sync with
|
||||
// executions recovered from Docker by the lifecycle manager.
|
||||
// For each recovered execution, if not already in cache, add it.
|
||||
func (e *Executor) SyncWithRecoveredExecutions(ctx context.Context, executions []RecoveredExecutionInfo) {
|
||||
e.mu.Lock()
|
||||
defer e.mu.Unlock()
|
||||
|
||||
for _, inst := range instances {
|
||||
if _, exists := e.executions[inst.TaskID]; exists {
|
||||
for _, exec := range executions {
|
||||
if _, exists := e.executions[exec.TaskID]; exists {
|
||||
continue // Already have this execution
|
||||
}
|
||||
|
||||
// Add to cache - this instance is running in Docker but wasn't in DB as active
|
||||
e.executions[inst.TaskID] = &TaskExecution{
|
||||
TaskID: inst.TaskID,
|
||||
AgentInstanceID: inst.InstanceID,
|
||||
AgentProfileID: inst.AgentProfileID,
|
||||
StartedAt: time.Now(), // We don't know exact start time
|
||||
SessionState: v1.TaskSessionStateRunning,
|
||||
Progress: 0,
|
||||
LastUpdate: time.Now(),
|
||||
// Add to cache - this execution is running in Docker but wasn't in DB as active
|
||||
e.executions[exec.TaskID] = &TaskExecution{
|
||||
TaskID: exec.TaskID,
|
||||
AgentExecutionID: exec.ExecutionID,
|
||||
AgentProfileID: exec.AgentProfileID,
|
||||
StartedAt: time.Now(), // We don't know exact start time
|
||||
SessionState: v1.TaskSessionStateRunning,
|
||||
Progress: 0,
|
||||
LastUpdate: time.Now(),
|
||||
}
|
||||
|
||||
e.logger.Info("synced recovered instance to executor cache",
|
||||
zap.String("task_id", inst.TaskID),
|
||||
zap.String("instance_id", inst.InstanceID))
|
||||
e.logger.Info("synced recovered execution to executor cache",
|
||||
zap.String("task_id", exec.TaskID),
|
||||
zap.String("execution_id", exec.ExecutionID))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -361,7 +369,7 @@ func (e *Executor) ExecuteWithProfile(ctx context.Context, task *v1.Task, agentP
|
||||
return nil, err
|
||||
}
|
||||
|
||||
session.AgentInstanceID = resp.AgentInstanceID
|
||||
session.AgentExecutionID = resp.AgentExecutionID
|
||||
session.ContainerID = resp.ContainerID
|
||||
session.State = models.TaskSessionStateStarting
|
||||
session.Progress = 0
|
||||
@@ -395,26 +403,39 @@ func (e *Executor) ExecuteWithProfile(ctx context.Context, task *v1.Task, agentP
|
||||
|
||||
// Track the execution in the in-memory cache
|
||||
execution := &TaskExecution{
|
||||
TaskID: task.ID,
|
||||
AgentInstanceID: resp.AgentInstanceID,
|
||||
AgentProfileID: agentProfileID,
|
||||
StartedAt: now,
|
||||
SessionState: v1.TaskSessionStateStarting,
|
||||
Progress: 0,
|
||||
LastUpdate: now,
|
||||
SessionID: sessionID,
|
||||
WorktreePath: resp.WorktreePath,
|
||||
WorktreeBranch: resp.WorktreeBranch,
|
||||
TaskID: task.ID,
|
||||
AgentExecutionID: resp.AgentExecutionID,
|
||||
AgentProfileID: agentProfileID,
|
||||
StartedAt: now,
|
||||
SessionState: v1.TaskSessionStateStarting,
|
||||
Progress: 0,
|
||||
LastUpdate: now,
|
||||
SessionID: sessionID,
|
||||
WorktreePath: resp.WorktreePath,
|
||||
WorktreeBranch: resp.WorktreeBranch,
|
||||
}
|
||||
|
||||
e.mu.Lock()
|
||||
e.executions[task.ID] = execution
|
||||
e.mu.Unlock()
|
||||
|
||||
// Start the agent process (agentctl execution was created above)
|
||||
go func() {
|
||||
startCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
if err := e.agentManager.StartAgentProcess(startCtx, resp.AgentExecutionID); err != nil {
|
||||
e.logger.Error("failed to start agent process",
|
||||
zap.String("task_id", task.ID),
|
||||
zap.String("agent_execution_id", resp.AgentExecutionID),
|
||||
zap.Error(err))
|
||||
}
|
||||
}()
|
||||
|
||||
e.logger.Info("agent launched successfully",
|
||||
zap.String("task_id", task.ID),
|
||||
zap.String("session_id", sessionID),
|
||||
zap.String("agent_instance_id", resp.AgentInstanceID),
|
||||
zap.String("agent_execution_id", resp.AgentExecutionID),
|
||||
zap.String("container_id", resp.ContainerID),
|
||||
zap.String("worktree_path", resp.WorktreePath),
|
||||
zap.String("worktree_branch", resp.WorktreeBranch))
|
||||
@@ -510,6 +531,9 @@ func (e *Executor) ResumeSession(ctx context.Context, task *v1.Task, session *mo
|
||||
if session.Metadata != nil {
|
||||
if acpSessionID, ok := session.Metadata["acp_session_id"].(string); ok && acpSessionID != "" {
|
||||
req.ACPSessionID = acpSessionID
|
||||
e.logger.Info("found acp_session_id in session metadata for resumption",
|
||||
zap.String("task_id", task.ID),
|
||||
zap.String("acp_session_id", acpSessionID))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -517,6 +541,7 @@ func (e *Executor) ResumeSession(ctx context.Context, task *v1.Task, session *mo
|
||||
zap.String("task_id", task.ID),
|
||||
zap.String("session_id", session.ID),
|
||||
zap.String("agent_profile_id", session.AgentProfileID),
|
||||
zap.String("acp_session_id", req.ACPSessionID),
|
||||
zap.Bool("use_worktree", req.UseWorktree))
|
||||
|
||||
resp, err := e.agentManager.LaunchAgent(ctx, req)
|
||||
@@ -528,7 +553,7 @@ func (e *Executor) ResumeSession(ctx context.Context, task *v1.Task, session *mo
|
||||
return nil, err
|
||||
}
|
||||
|
||||
session.AgentInstanceID = resp.AgentInstanceID
|
||||
session.AgentExecutionID = resp.AgentExecutionID
|
||||
session.ContainerID = resp.ContainerID
|
||||
session.Progress = 0
|
||||
session.ErrorMessage = ""
|
||||
@@ -578,22 +603,36 @@ func (e *Executor) ResumeSession(ctx context.Context, task *v1.Task, session *mo
|
||||
|
||||
now := time.Now().UTC()
|
||||
execution := &TaskExecution{
|
||||
TaskID: task.ID,
|
||||
AgentInstanceID: resp.AgentInstanceID,
|
||||
AgentProfileID: session.AgentProfileID,
|
||||
StartedAt: now,
|
||||
SessionState: v1.TaskSessionStateStarting,
|
||||
Progress: 0,
|
||||
LastUpdate: now,
|
||||
SessionID: session.ID,
|
||||
WorktreePath: worktreePath,
|
||||
WorktreeBranch: worktreeBranch,
|
||||
TaskID: task.ID,
|
||||
AgentExecutionID: resp.AgentExecutionID,
|
||||
AgentProfileID: session.AgentProfileID,
|
||||
StartedAt: now,
|
||||
SessionState: v1.TaskSessionStateStarting,
|
||||
Progress: 0,
|
||||
LastUpdate: now,
|
||||
SessionID: session.ID,
|
||||
WorktreePath: worktreePath,
|
||||
WorktreeBranch: worktreeBranch,
|
||||
}
|
||||
|
||||
e.mu.Lock()
|
||||
e.executions[task.ID] = execution
|
||||
e.mu.Unlock()
|
||||
|
||||
// Start the agent process (agentctl execution was created above)
|
||||
go func() {
|
||||
startCtx, cancel := context.WithTimeout(context.Background(), 5*time.Minute)
|
||||
defer cancel()
|
||||
|
||||
if err := e.agentManager.StartAgentProcess(startCtx, resp.AgentExecutionID); err != nil {
|
||||
e.logger.Error("failed to start agent process on resume",
|
||||
zap.String("task_id", task.ID),
|
||||
zap.String("session_id", session.ID),
|
||||
zap.String("agent_execution_id", resp.AgentExecutionID),
|
||||
zap.Error(err))
|
||||
}
|
||||
}()
|
||||
|
||||
return execution, nil
|
||||
}
|
||||
|
||||
@@ -606,11 +645,11 @@ func (e *Executor) Stop(ctx context.Context, taskID string, reason string, force
|
||||
|
||||
e.logger.Info("stopping execution",
|
||||
zap.String("task_id", taskID),
|
||||
zap.String("agent_instance_id", execution.AgentInstanceID),
|
||||
zap.String("agent_execution_id", execution.AgentExecutionID),
|
||||
zap.String("reason", reason),
|
||||
zap.Bool("force", force))
|
||||
|
||||
err = e.agentManager.StopAgent(ctx, execution.AgentInstanceID, force)
|
||||
err = e.agentManager.StopAgent(ctx, execution.AgentExecutionID, force)
|
||||
if err != nil {
|
||||
// Log the error but continue to clean up execution state
|
||||
// The agent instance may already be gone (container stopped externally)
|
||||
@@ -651,10 +690,10 @@ func (e *Executor) Prompt(ctx context.Context, taskID string, prompt string) (*P
|
||||
|
||||
e.logger.Info("sending prompt to agent",
|
||||
zap.String("task_id", taskID),
|
||||
zap.String("agent_instance_id", execution.AgentInstanceID),
|
||||
zap.String("agent_execution_id", execution.AgentExecutionID),
|
||||
zap.Int("prompt_length", len(prompt)))
|
||||
|
||||
return e.agentManager.PromptAgent(ctx, execution.AgentInstanceID, prompt)
|
||||
return e.agentManager.PromptAgent(ctx, execution.AgentExecutionID, prompt)
|
||||
}
|
||||
|
||||
// getOrLoadExecution gets execution from memory cache or loads from database
|
||||
@@ -722,6 +761,13 @@ func (e *Executor) GetExecution(taskID string) (*TaskExecution, bool) {
|
||||
if execution.SessionID != "" {
|
||||
_ = e.repo.UpdateTaskSessionState(ctx, execution.SessionID, models.TaskSessionStateCancelled, "agent process stopped")
|
||||
}
|
||||
|
||||
// Clean up the stale execution from the agent manager
|
||||
if err := e.agentManager.CleanupStaleExecutionByTaskID(ctx, taskID); err != nil {
|
||||
e.logger.Warn("failed to cleanup stale agent execution",
|
||||
zap.String("task_id", taskID),
|
||||
zap.Error(err))
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
@@ -744,6 +790,13 @@ func (e *Executor) GetExecution(taskID string) (*TaskExecution, bool) {
|
||||
zap.String("task_id", taskID),
|
||||
zap.String("session_id", session.ID))
|
||||
_ = e.repo.UpdateTaskSessionState(ctx, session.ID, models.TaskSessionStateCancelled, "agent not running after backend restart")
|
||||
|
||||
// Clean up the stale execution from the agent manager
|
||||
if err := e.agentManager.CleanupStaleExecutionByTaskID(ctx, taskID); err != nil {
|
||||
e.logger.Warn("failed to cleanup stale agent execution",
|
||||
zap.String("task_id", taskID),
|
||||
zap.Error(err))
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
@@ -775,6 +828,13 @@ func (e *Executor) GetExecutionWithContext(ctx context.Context, taskID string) (
|
||||
if execution.SessionID != "" {
|
||||
_ = e.repo.UpdateTaskSessionState(ctx, execution.SessionID, models.TaskSessionStateCancelled, "agent process stopped")
|
||||
}
|
||||
|
||||
// Clean up the stale execution from the agent manager
|
||||
if err := e.agentManager.CleanupStaleExecutionByTaskID(ctx, taskID); err != nil {
|
||||
e.logger.Warn("failed to cleanup stale agent execution",
|
||||
zap.String("task_id", taskID),
|
||||
zap.Error(err))
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
@@ -794,6 +854,13 @@ func (e *Executor) GetExecutionWithContext(ctx context.Context, taskID string) (
|
||||
zap.String("task_id", taskID),
|
||||
zap.String("session_id", session.ID))
|
||||
_ = e.repo.UpdateTaskSessionState(ctx, session.ID, models.TaskSessionStateCancelled, "agent not running after backend restart")
|
||||
|
||||
// Clean up the stale execution from the agent manager
|
||||
if err := e.agentManager.CleanupStaleExecutionByTaskID(ctx, taskID); err != nil {
|
||||
e.logger.Warn("failed to cleanup stale agent execution",
|
||||
zap.String("task_id", taskID),
|
||||
zap.Error(err))
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
@@ -958,27 +1025,34 @@ func (m *MockAgentManagerClient) LaunchAgent(ctx context.Context, req *LaunchAge
|
||||
zap.String("branch", req.Branch))
|
||||
|
||||
return &LaunchAgentResponse{
|
||||
AgentInstanceID: uuid.New().String(),
|
||||
ContainerID: "mock-container-" + uuid.New().String()[:8],
|
||||
Status: v1.AgentStatusStarting,
|
||||
AgentExecutionID: uuid.New().String(),
|
||||
ContainerID: "mock-container-" + uuid.New().String()[:8],
|
||||
Status: v1.AgentStatusStarting,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// StartAgentProcess mocks starting the agent subprocess
|
||||
func (m *MockAgentManagerClient) StartAgentProcess(ctx context.Context, agentExecutionID string) error {
|
||||
m.logger.Info("mock: starting agent process",
|
||||
zap.String("agent_execution_id", agentExecutionID))
|
||||
return nil
|
||||
}
|
||||
|
||||
// StopAgent mocks stopping an agent
|
||||
func (m *MockAgentManagerClient) StopAgent(ctx context.Context, agentInstanceID string, force bool) error {
|
||||
func (m *MockAgentManagerClient) StopAgent(ctx context.Context, agentExecutionID string, force bool) error {
|
||||
m.logger.Info("mock: stopping agent",
|
||||
zap.String("agent_instance_id", agentInstanceID),
|
||||
zap.String("agent_execution_id", agentExecutionID),
|
||||
zap.Bool("force", force))
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetAgentStatus mocks getting agent status
|
||||
func (m *MockAgentManagerClient) GetAgentStatus(ctx context.Context, agentInstanceID string) (*v1.AgentInstance, error) {
|
||||
func (m *MockAgentManagerClient) GetAgentStatus(ctx context.Context, agentExecutionID string) (*v1.AgentExecution, error) {
|
||||
m.logger.Info("mock: getting agent status",
|
||||
zap.String("agent_instance_id", agentInstanceID))
|
||||
zap.String("agent_execution_id", agentExecutionID))
|
||||
|
||||
return &v1.AgentInstance{
|
||||
ID: agentInstanceID,
|
||||
return &v1.AgentExecution{
|
||||
ID: agentExecutionID,
|
||||
Status: v1.AgentStatusRunning,
|
||||
AgentProfileID: "mock-agent",
|
||||
}, nil
|
||||
@@ -1001,9 +1075,9 @@ func (m *MockAgentManagerClient) ListAgentTypes(ctx context.Context) ([]*v1.Agen
|
||||
}
|
||||
|
||||
// PromptAgent mocks sending a prompt to an agent
|
||||
func (m *MockAgentManagerClient) PromptAgent(ctx context.Context, agentInstanceID string, prompt string) (*PromptResult, error) {
|
||||
func (m *MockAgentManagerClient) PromptAgent(ctx context.Context, agentExecutionID string, prompt string) (*PromptResult, error) {
|
||||
m.logger.Info("mock: prompting agent",
|
||||
zap.String("agent_instance_id", agentInstanceID),
|
||||
zap.String("agent_execution_id", agentExecutionID),
|
||||
zap.Int("prompt_length", len(prompt)))
|
||||
return &PromptResult{StopReason: "end_turn"}, nil
|
||||
}
|
||||
@@ -1018,8 +1092,8 @@ func (m *MockAgentManagerClient) RespondToPermissionByTaskID(ctx context.Context
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetRecoveredInstances mocks getting recovered instances (returns empty for mock)
|
||||
func (m *MockAgentManagerClient) GetRecoveredInstances() []RecoveredInstanceInfo {
|
||||
// GetRecoveredExecutions mocks getting recovered executions (returns empty for mock)
|
||||
func (m *MockAgentManagerClient) GetRecoveredExecutions() []RecoveredExecutionInfo {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1027,3 +1101,8 @@ func (m *MockAgentManagerClient) GetRecoveredInstances() []RecoveredInstanceInfo
|
||||
func (m *MockAgentManagerClient) IsAgentRunningForTask(ctx context.Context, taskID string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// CleanupStaleExecutionByTaskID mocks cleaning up a stale execution (no-op for mock)
|
||||
func (m *MockAgentManagerClient) CleanupStaleExecutionByTaskID(ctx context.Context, taskID string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -37,6 +37,7 @@ func (h *Handlers) RegisterHandlers(d *ws.Dispatcher) {
|
||||
d.RegisterFunc(ws.ActionPermissionRespond, h.wsRespondToPermission)
|
||||
d.RegisterFunc(ws.ActionTaskExecution, h.wsGetTaskExecution)
|
||||
d.RegisterFunc(ws.ActionTaskSessionResume, h.wsResumeTaskSession)
|
||||
d.RegisterFunc(ws.ActionTaskSessionStatus, h.wsGetTaskSessionStatus)
|
||||
}
|
||||
|
||||
// WS handlers
|
||||
@@ -281,3 +282,35 @@ func (h *Handlers) wsGetTaskExecution(ctx context.Context, msg *ws.Message) (*ws
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, resp)
|
||||
}
|
||||
|
||||
type wsGetTaskSessionStatusRequest struct {
|
||||
TaskID string `json:"task_id"`
|
||||
TaskSessionID string `json:"task_session_id"`
|
||||
}
|
||||
|
||||
func (h *Handlers) wsGetTaskSessionStatus(ctx context.Context, msg *ws.Message) (*ws.Message, error) {
|
||||
var req wsGetTaskSessionStatusRequest
|
||||
if err := msg.ParsePayload(&req); err != nil {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "Invalid request payload", nil)
|
||||
}
|
||||
|
||||
if req.TaskID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "task_id is required", nil)
|
||||
}
|
||||
if req.TaskSessionID == "" {
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeBadRequest, "task_session_id is required", nil)
|
||||
}
|
||||
|
||||
resp, err := h.controller.GetTaskSessionStatus(ctx, dto.TaskSessionStatusRequest{
|
||||
TaskID: req.TaskID,
|
||||
TaskSessionID: req.TaskSessionID,
|
||||
})
|
||||
if err != nil {
|
||||
h.logger.Error("failed to get task session status",
|
||||
zap.String("task_id", req.TaskID),
|
||||
zap.String("task_session_id", req.TaskSessionID),
|
||||
zap.Error(err))
|
||||
return ws.NewError(msg.ID, msg.Action, ws.ErrorCodeInternalError, "Failed to get task session status: "+err.Error(), nil)
|
||||
}
|
||||
return ws.NewResponse(msg.ID, msg.Action, resp)
|
||||
}
|
||||
|
||||
@@ -35,19 +35,23 @@ func (m *mockAgentManager) LaunchAgent(ctx context.Context, req *executor.Launch
|
||||
m.mu.Unlock()
|
||||
|
||||
return &executor.LaunchAgentResponse{
|
||||
AgentInstanceID: "agent-" + req.TaskID,
|
||||
ContainerID: "container-" + req.TaskID,
|
||||
Status: v1.AgentStatusRunning,
|
||||
AgentExecutionID: "agent-" + req.TaskID,
|
||||
ContainerID: "container-" + req.TaskID,
|
||||
Status: v1.AgentStatusRunning,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (m *mockAgentManager) StopAgent(ctx context.Context, agentInstanceID string, force bool) error {
|
||||
func (m *mockAgentManager) StartAgentProcess(ctx context.Context, agentExecutionID string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockAgentManager) GetAgentStatus(ctx context.Context, agentInstanceID string) (*v1.AgentInstance, error) {
|
||||
return &v1.AgentInstance{
|
||||
ID: agentInstanceID,
|
||||
func (m *mockAgentManager) StopAgent(ctx context.Context, agentExecutionID string, force bool) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockAgentManager) GetAgentStatus(ctx context.Context, agentExecutionID string) (*v1.AgentExecution, error) {
|
||||
return &v1.AgentExecution{
|
||||
ID: agentExecutionID,
|
||||
Status: v1.AgentStatusRunning,
|
||||
}, nil
|
||||
}
|
||||
@@ -56,7 +60,7 @@ func (m *mockAgentManager) ListAgentTypes(ctx context.Context) ([]*v1.AgentType,
|
||||
return []*v1.AgentType{}, nil
|
||||
}
|
||||
|
||||
func (m *mockAgentManager) PromptAgent(ctx context.Context, agentInstanceID string, prompt string) (*executor.PromptResult, error) {
|
||||
func (m *mockAgentManager) PromptAgent(ctx context.Context, agentExecutionID string, prompt string) (*executor.PromptResult, error) {
|
||||
return &executor.PromptResult{StopReason: "end_turn"}, nil
|
||||
}
|
||||
|
||||
@@ -64,7 +68,7 @@ func (m *mockAgentManager) RespondToPermissionByTaskID(ctx context.Context, task
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *mockAgentManager) GetRecoveredInstances() []executor.RecoveredInstanceInfo {
|
||||
func (m *mockAgentManager) GetRecoveredExecutions() []executor.RecoveredExecutionInfo {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -72,6 +76,10 @@ func (m *mockAgentManager) IsAgentRunningForTask(ctx context.Context, taskID str
|
||||
return false
|
||||
}
|
||||
|
||||
func (m *mockAgentManager) CleanupStaleExecutionByTaskID(ctx context.Context, taskID string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// testTaskRepository is an in-memory task repository for testing
|
||||
type testTaskRepository struct {
|
||||
tasks map[string]*v1.Task
|
||||
|
||||
@@ -14,6 +14,7 @@ import (
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
"github.com/kandev/kandev/internal/events"
|
||||
"github.com/kandev/kandev/internal/events/bus"
|
||||
"github.com/kandev/kandev/internal/orchestrator/dto"
|
||||
"github.com/kandev/kandev/internal/orchestrator/executor"
|
||||
"github.com/kandev/kandev/internal/orchestrator/queue"
|
||||
"github.com/kandev/kandev/internal/orchestrator/scheduler"
|
||||
@@ -188,12 +189,12 @@ func (s *Service) Start(ctx context.Context) error {
|
||||
s.logger.Warn("failed to load active sessions from database (non-fatal)", zap.Error(err))
|
||||
}
|
||||
|
||||
// Sync with instances recovered from Docker by the lifecycle manager
|
||||
// Sync with executions recovered from Docker by the lifecycle manager
|
||||
// This ensures we track containers that are running but weren't in the DB as active
|
||||
recovered := s.agentManager.GetRecoveredInstances()
|
||||
recovered := s.agentManager.GetRecoveredExecutions()
|
||||
if len(recovered) > 0 {
|
||||
s.logger.Info("syncing with recovered Docker instances", zap.Int("count", len(recovered)))
|
||||
s.executor.SyncWithRecoveredInstances(ctx, recovered)
|
||||
s.logger.Info("syncing with recovered Docker executions", zap.Int("count", len(recovered)))
|
||||
s.executor.SyncWithRecoveredExecutions(ctx, recovered)
|
||||
}
|
||||
|
||||
// Start the watcher first to begin receiving events
|
||||
@@ -400,6 +401,99 @@ func (s *Service) ResumeTaskSession(ctx context.Context, taskID, sessionID strin
|
||||
return execution, nil
|
||||
}
|
||||
|
||||
// GetActiveSessionID returns the active (running) session ID for a task
|
||||
func (s *Service) GetActiveSessionID(ctx context.Context, taskID string) (string, error) {
|
||||
return s.executor.GetActiveSessionID(ctx, taskID)
|
||||
}
|
||||
|
||||
// GetTaskSessionStatus returns the status of a task session including whether it's resumable
|
||||
func (s *Service) GetTaskSessionStatus(ctx context.Context, taskID, sessionID string) (dto.TaskSessionStatusResponse, error) {
|
||||
s.logger.Info("checking task session status",
|
||||
zap.String("task_id", taskID),
|
||||
zap.String("session_id", sessionID))
|
||||
|
||||
resp := dto.TaskSessionStatusResponse{
|
||||
SessionID: sessionID,
|
||||
TaskID: taskID,
|
||||
}
|
||||
|
||||
// 1. Load session from database
|
||||
session, err := s.repo.GetTaskSession(ctx, sessionID)
|
||||
if err != nil {
|
||||
resp.Error = "session not found"
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
if session.TaskID != taskID {
|
||||
resp.Error = "session does not belong to task"
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
resp.State = string(session.State)
|
||||
resp.AgentProfileID = session.AgentProfileID
|
||||
|
||||
// Extract ACP session ID from metadata - this is the key requirement for resumption
|
||||
var acpSessionID string
|
||||
if session.Metadata != nil {
|
||||
if id, ok := session.Metadata["acp_session_id"].(string); ok {
|
||||
acpSessionID = id
|
||||
resp.ACPSessionID = acpSessionID
|
||||
}
|
||||
}
|
||||
|
||||
// Extract worktree info
|
||||
if len(session.Worktrees) > 0 {
|
||||
wt := session.Worktrees[0]
|
||||
if wt.WorktreePath != "" {
|
||||
resp.WorktreePath = &wt.WorktreePath
|
||||
}
|
||||
if wt.WorktreeBranch != "" {
|
||||
resp.WorktreeBranch = &wt.WorktreeBranch
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Check if we have an active execution in memory and agent is running
|
||||
if exec, ok := s.executor.GetExecutionWithContext(ctx, taskID); ok && exec != nil {
|
||||
resp.IsAgentRunning = true
|
||||
resp.IsResumable = true
|
||||
resp.NeedsResume = false
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// 3. Session can be resumed if it has an ACP session ID
|
||||
// Any session type with an acp_session_id can be resumed
|
||||
if acpSessionID == "" {
|
||||
resp.IsAgentRunning = false
|
||||
resp.IsResumable = false
|
||||
resp.NeedsResume = false
|
||||
resp.Error = "session has no acp_session_id"
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// 4. Additional validations for resumption
|
||||
if session.AgentProfileID == "" {
|
||||
resp.Error = "session missing agent profile"
|
||||
resp.IsResumable = false
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// Check if worktree exists (if one was used)
|
||||
if len(session.Worktrees) > 0 && session.Worktrees[0].WorktreePath != "" {
|
||||
if _, err := os.Stat(session.Worktrees[0].WorktreePath); err != nil {
|
||||
resp.Error = "worktree not found"
|
||||
resp.IsResumable = false
|
||||
return resp, nil
|
||||
}
|
||||
}
|
||||
|
||||
resp.IsAgentRunning = false
|
||||
resp.IsResumable = true
|
||||
resp.NeedsResume = true
|
||||
resp.ResumeReason = "agent_not_running"
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// StopTask stops agent execution for a task
|
||||
func (s *Service) StopTask(ctx context.Context, taskID string, reason string, force bool) error {
|
||||
s.logger.Info("stopping task execution",
|
||||
@@ -534,7 +628,7 @@ func (s *Service) handleTaskStateChanged(ctx context.Context, data watcher.TaskE
|
||||
func (s *Service) handleAgentReady(ctx context.Context, data watcher.AgentEventData) {
|
||||
s.logger.Info("handling agent ready",
|
||||
zap.String("task_id", data.TaskID),
|
||||
zap.String("agent_instance_id", data.AgentInstanceID))
|
||||
zap.String("agent_execution_id", data.AgentExecutionID))
|
||||
|
||||
if s.markAgentReady(data.TaskID) {
|
||||
s.finalizeAgentReady(data.TaskID, "")
|
||||
@@ -596,7 +690,7 @@ func (s *Service) handleACPSessionCreated(ctx context.Context, data watcher.ACPS
|
||||
func (s *Service) handleAgentCompleted(ctx context.Context, data watcher.AgentEventData) {
|
||||
s.logger.Info("handling agent completed",
|
||||
zap.String("task_id", data.TaskID),
|
||||
zap.String("agent_instance_id", data.AgentInstanceID))
|
||||
zap.String("agent_execution_id", data.AgentExecutionID))
|
||||
|
||||
// Update scheduler and remove from queue
|
||||
s.scheduler.HandleTaskCompleted(data.TaskID, true)
|
||||
@@ -618,7 +712,7 @@ func (s *Service) handleAgentCompleted(ctx context.Context, data watcher.AgentEv
|
||||
func (s *Service) handleAgentFailed(ctx context.Context, data watcher.AgentEventData) {
|
||||
s.logger.Warn("handling agent failed",
|
||||
zap.String("task_id", data.TaskID),
|
||||
zap.String("agent_instance_id", data.AgentInstanceID),
|
||||
zap.String("agent_execution_id", data.AgentExecutionID),
|
||||
zap.String("error_message", data.ErrorMessage))
|
||||
|
||||
// Trigger retry logic
|
||||
|
||||
@@ -26,18 +26,18 @@ type TaskEventData struct {
|
||||
|
||||
// AgentEventData contains data from agent events
|
||||
type AgentEventData struct {
|
||||
TaskID string `json:"task_id"`
|
||||
AgentInstanceID string `json:"agent_instance_id"`
|
||||
AgentProfileID string `json:"agent_profile_id"`
|
||||
ExitCode *int `json:"exit_code,omitempty"`
|
||||
ErrorMessage string `json:"error_message,omitempty"`
|
||||
TaskID string `json:"task_id"`
|
||||
AgentExecutionID string `json:"agent_execution_id"`
|
||||
AgentProfileID string `json:"agent_profile_id"`
|
||||
ExitCode *int `json:"exit_code,omitempty"`
|
||||
ErrorMessage string `json:"error_message,omitempty"`
|
||||
}
|
||||
|
||||
// ACPSessionEventData contains data from ACP session events
|
||||
type ACPSessionEventData struct {
|
||||
TaskID string `json:"task_id"`
|
||||
AgentInstanceID string `json:"agent_instance_id"`
|
||||
ACPSessionID string `json:"acp_session_id"`
|
||||
TaskID string `json:"task_id"`
|
||||
AgentExecutionID string `json:"agent_execution_id"`
|
||||
ACPSessionID string `json:"acp_session_id"`
|
||||
}
|
||||
|
||||
// PromptCompleteData contains data from prompt_complete events
|
||||
@@ -360,7 +360,7 @@ func (w *Watcher) createAgentEventHandler(handler func(ctx context.Context, data
|
||||
w.logger.Debug("Handling agent event",
|
||||
zap.String("event_type", event.Type),
|
||||
zap.String("task_id", data.TaskID),
|
||||
zap.String("agent_instance_id", data.AgentInstanceID))
|
||||
zap.String("agent_execution_id", data.AgentExecutionID))
|
||||
|
||||
handler(ctx, data)
|
||||
return nil
|
||||
|
||||
@@ -275,10 +275,10 @@ func TestAgentEventHandling(t *testing.T) {
|
||||
// Simulate publishing an agent completed event
|
||||
exitCode := 0
|
||||
event := bus.NewEvent(events.AgentCompleted, "test", map[string]interface{}{
|
||||
"task_id": "task-123",
|
||||
"agent_instance_id": "agent-456",
|
||||
"agent_type": "test-agent",
|
||||
"exit_code": exitCode,
|
||||
"task_id": "task-123",
|
||||
"agent_execution_id": "agent-456",
|
||||
"agent_type": "test-agent",
|
||||
"exit_code": exitCode,
|
||||
})
|
||||
|
||||
_ = eventBus.Publish(context.Background(), events.AgentCompleted, event)
|
||||
@@ -294,8 +294,8 @@ func TestAgentEventHandling(t *testing.T) {
|
||||
if receivedData.TaskID != "task-123" {
|
||||
t.Errorf("expected task_id = 'task-123', got %s", receivedData.TaskID)
|
||||
}
|
||||
if receivedData.AgentInstanceID != "agent-456" {
|
||||
t.Errorf("expected agent_instance_id = 'agent-456', got %s", receivedData.AgentInstanceID)
|
||||
if receivedData.AgentExecutionID != "agent-456" {
|
||||
t.Errorf("expected agent_execution_id = 'agent-456', got %s", receivedData.AgentExecutionID)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -125,7 +125,7 @@ type TaskRepositoryDTO struct {
|
||||
type TaskSessionDTO struct {
|
||||
ID string `json:"id"`
|
||||
TaskID string `json:"task_id"`
|
||||
AgentInstanceID string `json:"agent_instance_id,omitempty"`
|
||||
AgentExecutionID string `json:"agent_execution_id,omitempty"`
|
||||
ContainerID string `json:"container_id,omitempty"`
|
||||
AgentProfileID string `json:"agent_profile_id,omitempty"`
|
||||
ExecutorID string `json:"executor_id,omitempty"`
|
||||
@@ -400,7 +400,7 @@ func FromTaskSession(session *models.TaskSession) TaskSessionDTO {
|
||||
result := TaskSessionDTO{
|
||||
ID: session.ID,
|
||||
TaskID: session.TaskID,
|
||||
AgentInstanceID: session.AgentInstanceID,
|
||||
AgentExecutionID: session.AgentExecutionID,
|
||||
ContainerID: session.ContainerID,
|
||||
AgentProfileID: session.AgentProfileID,
|
||||
ExecutorID: session.ExecutorID,
|
||||
|
||||
@@ -105,7 +105,7 @@ type Message struct {
|
||||
TaskSessionID string `json:"task_session_id"`
|
||||
TaskID string `json:"task_id,omitempty"`
|
||||
AuthorType MessageAuthorType `json:"author_type"`
|
||||
AuthorID string `json:"author_id,omitempty"` // User ID or Agent Instance ID
|
||||
AuthorID string `json:"author_id,omitempty"` // User ID or Agent Execution ID
|
||||
Content string `json:"content"`
|
||||
Type MessageType `json:"type,omitempty"` // Defaults to "message"
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
@@ -173,8 +173,8 @@ type TaskSessionWorktree struct {
|
||||
type TaskSession struct {
|
||||
ID string `json:"id"`
|
||||
TaskID string `json:"task_id"`
|
||||
AgentInstanceID string `json:"agent_instance_id"` // Docker container/agent instance
|
||||
ContainerID string `json:"container_id"` // Docker container ID for cleanup
|
||||
AgentExecutionID string `json:"agent_execution_id"` // Docker container/agent execution
|
||||
ContainerID string `json:"container_id"` // Docker container ID for cleanup
|
||||
AgentProfileID string `json:"agent_profile_id"` // ID of the agent profile used
|
||||
ExecutorID string `json:"executor_id"`
|
||||
EnvironmentID string `json:"environment_id"`
|
||||
@@ -198,10 +198,10 @@ type TaskSession struct {
|
||||
// TODO: Add v1.TaskSession type to pkg/api/v1/
|
||||
func (s *TaskSession) ToAPI() map[string]interface{} {
|
||||
result := map[string]interface{}{
|
||||
"id": s.ID,
|
||||
"task_id": s.TaskID,
|
||||
"agent_instance_id": s.AgentInstanceID,
|
||||
"container_id": s.ContainerID,
|
||||
"id": s.ID,
|
||||
"task_id": s.TaskID,
|
||||
"agent_execution_id": s.AgentExecutionID,
|
||||
"container_id": s.ContainerID,
|
||||
"agent_profile_id": s.AgentProfileID,
|
||||
"executor_id": s.ExecutorID,
|
||||
"environment_id": s.EnvironmentID,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,530 +0,0 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
)
|
||||
|
||||
func TestNewMemoryRepository(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
if repo == nil {
|
||||
t.Fatal("expected non-nil repository")
|
||||
}
|
||||
if repo.tasks == nil {
|
||||
t.Error("expected tasks map to be initialized")
|
||||
}
|
||||
if repo.workspaces == nil {
|
||||
t.Error("expected workspaces map to be initialized")
|
||||
}
|
||||
if repo.boards == nil {
|
||||
t.Error("expected boards map to be initialized")
|
||||
}
|
||||
if repo.columns == nil {
|
||||
t.Error("expected columns map to be initialized")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryRepository_Close(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
err := repo.Close()
|
||||
if err != nil {
|
||||
t.Errorf("expected no error on close, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Board CRUD tests
|
||||
|
||||
func TestMemoryRepository_BoardCRUD(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
ctx := context.Background()
|
||||
|
||||
workspace := &models.Workspace{ID: "ws-1", Name: "Workspace"}
|
||||
if err := repo.CreateWorkspace(ctx, workspace); err != nil {
|
||||
t.Fatalf("failed to create workspace: %v", err)
|
||||
}
|
||||
|
||||
// Create
|
||||
board := &models.Board{WorkspaceID: workspace.ID, Name: "Test Board", Description: "A test board"}
|
||||
if err := repo.CreateBoard(ctx, board); err != nil {
|
||||
t.Fatalf("failed to create board: %v", err)
|
||||
}
|
||||
if board.ID == "" {
|
||||
t.Error("expected board ID to be set")
|
||||
}
|
||||
if board.CreatedAt.IsZero() {
|
||||
t.Error("expected CreatedAt to be set")
|
||||
}
|
||||
|
||||
// Get
|
||||
retrieved, err := repo.GetBoard(ctx, board.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get board: %v", err)
|
||||
}
|
||||
if retrieved.Name != "Test Board" {
|
||||
t.Errorf("expected name 'Test Board', got %s", retrieved.Name)
|
||||
}
|
||||
|
||||
// Update
|
||||
board.Name = "Updated Name"
|
||||
if err := repo.UpdateBoard(ctx, board); err != nil {
|
||||
t.Fatalf("failed to update board: %v", err)
|
||||
}
|
||||
retrieved, _ = repo.GetBoard(ctx, board.ID)
|
||||
if retrieved.Name != "Updated Name" {
|
||||
t.Errorf("expected name 'Updated Name', got %s", retrieved.Name)
|
||||
}
|
||||
|
||||
// Delete
|
||||
if err := repo.DeleteBoard(ctx, board.ID); err != nil {
|
||||
t.Fatalf("failed to delete board: %v", err)
|
||||
}
|
||||
_, err = repo.GetBoard(ctx, board.ID)
|
||||
if err == nil {
|
||||
t.Error("expected board to be deleted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryRepository_BoardNotFound(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := repo.GetBoard(ctx, "nonexistent")
|
||||
if err == nil {
|
||||
t.Error("expected error for nonexistent board")
|
||||
}
|
||||
|
||||
err = repo.UpdateBoard(ctx, &models.Board{ID: "nonexistent", Name: "Test"})
|
||||
if err == nil {
|
||||
t.Error("expected error for updating nonexistent board")
|
||||
}
|
||||
|
||||
err = repo.DeleteBoard(ctx, "nonexistent")
|
||||
if err == nil {
|
||||
t.Error("expected error for deleting nonexistent board")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryRepository_ListBoards(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
ctx := context.Background()
|
||||
|
||||
_ = repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-1", Name: "Workspace 1"})
|
||||
_ = repo.CreateWorkspace(ctx, &models.Workspace{ID: "ws-2", Name: "Workspace 2"})
|
||||
|
||||
_ = repo.CreateBoard(ctx, &models.Board{ID: "board-1", WorkspaceID: "ws-1", Name: "Board 1"})
|
||||
_ = repo.CreateBoard(ctx, &models.Board{ID: "board-2", WorkspaceID: "ws-1", Name: "Board 2"})
|
||||
_ = repo.CreateBoard(ctx, &models.Board{ID: "board-3", WorkspaceID: "ws-2", Name: "Board 3"})
|
||||
|
||||
boards, err := repo.ListBoards(ctx, "ws-1")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to list boards: %v", err)
|
||||
}
|
||||
if len(boards) != 2 {
|
||||
t.Errorf("expected 2 boards, got %d", len(boards))
|
||||
}
|
||||
}
|
||||
|
||||
// Column CRUD tests
|
||||
|
||||
func TestMemoryRepository_ColumnCRUD(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
ctx := context.Background()
|
||||
|
||||
// Create
|
||||
column := &models.Column{BoardID: "board-123", Name: "To Do", Position: 0, State: v1.TaskStateTODO}
|
||||
if err := repo.CreateColumn(ctx, column); err != nil {
|
||||
t.Fatalf("failed to create column: %v", err)
|
||||
}
|
||||
if column.ID == "" {
|
||||
t.Error("expected column ID to be set")
|
||||
}
|
||||
|
||||
// Get
|
||||
retrieved, err := repo.GetColumn(ctx, column.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get column: %v", err)
|
||||
}
|
||||
if retrieved.Name != "To Do" {
|
||||
t.Errorf("expected name 'To Do', got %s", retrieved.Name)
|
||||
}
|
||||
|
||||
// Update
|
||||
column.Name = "Done"
|
||||
column.State = v1.TaskStateCompleted
|
||||
if err := repo.UpdateColumn(ctx, column); err != nil {
|
||||
t.Fatalf("failed to update column: %v", err)
|
||||
}
|
||||
retrieved, _ = repo.GetColumn(ctx, column.ID)
|
||||
if retrieved.Name != "Done" {
|
||||
t.Errorf("expected name 'Done', got %s", retrieved.Name)
|
||||
}
|
||||
|
||||
// Delete
|
||||
if err := repo.DeleteColumn(ctx, column.ID); err != nil {
|
||||
t.Fatalf("failed to delete column: %v", err)
|
||||
}
|
||||
_, err = repo.GetColumn(ctx, column.ID)
|
||||
if err == nil {
|
||||
t.Error("expected column to be deleted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryRepository_ColumnNotFound(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := repo.GetColumn(ctx, "nonexistent")
|
||||
if err == nil {
|
||||
t.Error("expected error for nonexistent column")
|
||||
}
|
||||
|
||||
err = repo.UpdateColumn(ctx, &models.Column{ID: "nonexistent", Name: "Test"})
|
||||
if err == nil {
|
||||
t.Error("expected error for updating nonexistent column")
|
||||
}
|
||||
|
||||
err = repo.DeleteColumn(ctx, "nonexistent")
|
||||
if err == nil {
|
||||
t.Error("expected error for deleting nonexistent column")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryRepository_ListColumns(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
ctx := context.Background()
|
||||
|
||||
_ = repo.CreateColumn(ctx, &models.Column{ID: "col-1", BoardID: "board-123", Name: "To Do"})
|
||||
_ = repo.CreateColumn(ctx, &models.Column{ID: "col-2", BoardID: "board-123", Name: "In Progress"})
|
||||
_ = repo.CreateColumn(ctx, &models.Column{ID: "col-3", BoardID: "board-456", Name: "Done"})
|
||||
|
||||
columns, err := repo.ListColumns(ctx, "board-123")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to list columns: %v", err)
|
||||
}
|
||||
if len(columns) != 2 {
|
||||
t.Errorf("expected 2 columns for board-123, got %d", len(columns))
|
||||
}
|
||||
}
|
||||
|
||||
// Task CRUD tests
|
||||
|
||||
func TestMemoryRepository_TaskCRUD(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
ctx := context.Background()
|
||||
|
||||
// Create
|
||||
task := &models.Task{
|
||||
WorkspaceID: "ws-1",
|
||||
BoardID: "board-123",
|
||||
ColumnID: "col-123",
|
||||
Title: "Test Task",
|
||||
Description: "A test task",
|
||||
State: v1.TaskStateTODO,
|
||||
Priority: 5,
|
||||
}
|
||||
if err := repo.CreateTask(ctx, task); err != nil {
|
||||
t.Fatalf("failed to create task: %v", err)
|
||||
}
|
||||
if task.ID == "" {
|
||||
t.Error("expected task ID to be set")
|
||||
}
|
||||
if task.CreatedAt.IsZero() {
|
||||
t.Error("expected CreatedAt to be set")
|
||||
}
|
||||
|
||||
// Get
|
||||
retrieved, err := repo.GetTask(ctx, task.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get task: %v", err)
|
||||
}
|
||||
if retrieved.Title != "Test Task" {
|
||||
t.Errorf("expected title 'Test Task', got %s", retrieved.Title)
|
||||
}
|
||||
|
||||
// Update
|
||||
task.Title = "Updated Task"
|
||||
task.Description = "Updated description"
|
||||
if err := repo.UpdateTask(ctx, task); err != nil {
|
||||
t.Fatalf("failed to update task: %v", err)
|
||||
}
|
||||
retrieved, _ = repo.GetTask(ctx, task.ID)
|
||||
if retrieved.Title != "Updated Task" {
|
||||
t.Errorf("expected title 'Updated Task', got %s", retrieved.Title)
|
||||
}
|
||||
|
||||
// Delete
|
||||
if err := repo.DeleteTask(ctx, task.ID); err != nil {
|
||||
t.Fatalf("failed to delete task: %v", err)
|
||||
}
|
||||
_, err = repo.GetTask(ctx, task.ID)
|
||||
if err == nil {
|
||||
t.Error("expected task to be deleted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryRepository_TaskNotFound(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := repo.GetTask(ctx, "nonexistent")
|
||||
if err == nil {
|
||||
t.Error("expected error for nonexistent task")
|
||||
}
|
||||
|
||||
err = repo.UpdateTask(ctx, &models.Task{ID: "nonexistent", Title: "Test"})
|
||||
if err == nil {
|
||||
t.Error("expected error for updating nonexistent task")
|
||||
}
|
||||
|
||||
err = repo.DeleteTask(ctx, "nonexistent")
|
||||
if err == nil {
|
||||
t.Error("expected error for deleting nonexistent task")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryRepository_UpdateTaskState(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
ctx := context.Background()
|
||||
|
||||
task := &models.Task{ID: "task-123", WorkspaceID: "ws-1", BoardID: "board-123", ColumnID: "col-123", Title: "Test", State: v1.TaskStateTODO}
|
||||
_ = repo.CreateTask(ctx, task)
|
||||
|
||||
err := repo.UpdateTaskState(ctx, "task-123", v1.TaskStateInProgress)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to update task state: %v", err)
|
||||
}
|
||||
|
||||
retrieved, _ := repo.GetTask(ctx, "task-123")
|
||||
if retrieved.State != v1.TaskStateInProgress {
|
||||
t.Errorf("expected state IN_PROGRESS, got %s", retrieved.State)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryRepository_UpdateTaskStateNotFound(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
ctx := context.Background()
|
||||
|
||||
err := repo.UpdateTaskState(ctx, "nonexistent", v1.TaskStateInProgress)
|
||||
if err == nil {
|
||||
t.Error("expected error for nonexistent task")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryRepository_ListTasks(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
ctx := context.Background()
|
||||
|
||||
_ = repo.CreateTask(ctx, &models.Task{ID: "task-1", WorkspaceID: "ws-1", BoardID: "board-123", ColumnID: "col-1", Title: "Task 1"})
|
||||
_ = repo.CreateTask(ctx, &models.Task{ID: "task-2", WorkspaceID: "ws-1", BoardID: "board-123", ColumnID: "col-1", Title: "Task 2"})
|
||||
_ = repo.CreateTask(ctx, &models.Task{ID: "task-3", WorkspaceID: "ws-1", BoardID: "board-456", ColumnID: "col-2", Title: "Task 3"})
|
||||
|
||||
tasks, err := repo.ListTasks(ctx, "board-123")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to list tasks: %v", err)
|
||||
}
|
||||
if len(tasks) != 2 {
|
||||
t.Errorf("expected 2 tasks for board-123, got %d", len(tasks))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryRepository_ListTasksByColumn(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
ctx := context.Background()
|
||||
|
||||
_ = repo.CreateTask(ctx, &models.Task{ID: "task-1", WorkspaceID: "ws-1", BoardID: "board-123", ColumnID: "col-1", Title: "Task 1"})
|
||||
_ = repo.CreateTask(ctx, &models.Task{ID: "task-2", WorkspaceID: "ws-1", BoardID: "board-123", ColumnID: "col-1", Title: "Task 2"})
|
||||
_ = repo.CreateTask(ctx, &models.Task{ID: "task-3", WorkspaceID: "ws-1", BoardID: "board-123", ColumnID: "col-2", Title: "Task 3"})
|
||||
|
||||
tasks, err := repo.ListTasksByColumn(ctx, "col-1")
|
||||
if err != nil {
|
||||
t.Fatalf("failed to list tasks by column: %v", err)
|
||||
}
|
||||
if len(tasks) != 2 {
|
||||
t.Errorf("expected 2 tasks for col-1, got %d", len(tasks))
|
||||
}
|
||||
}
|
||||
|
||||
// Message CRUD tests
|
||||
|
||||
func setupMemoryTestSession(ctx context.Context, repo *MemoryRepository, taskID string) string {
|
||||
session := &models.TaskSession{
|
||||
ID: "session-123",
|
||||
TaskID: taskID,
|
||||
AgentProfileID: "profile-123",
|
||||
State: models.TaskSessionStateStarting,
|
||||
}
|
||||
_ = repo.CreateTaskSession(ctx, session)
|
||||
return session.ID
|
||||
}
|
||||
|
||||
func TestMemoryRepository_MessageCRUD(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
ctx := context.Background()
|
||||
|
||||
// Create a task first
|
||||
task := &models.Task{ID: "task-123", BoardID: "board-123", ColumnID: "col-123", Title: "Test Task"}
|
||||
_ = repo.CreateTask(ctx, task)
|
||||
sessionID := setupMemoryTestSession(ctx, repo, task.ID)
|
||||
|
||||
// Create comment
|
||||
comment := &models.Message{
|
||||
TaskSessionID: sessionID,
|
||||
TaskID: "task-123",
|
||||
AuthorType: models.MessageAuthorUser,
|
||||
AuthorID: "user-123",
|
||||
Content: "This is a test comment",
|
||||
RequestsInput: false,
|
||||
}
|
||||
if err := repo.CreateMessage(ctx, comment); err != nil {
|
||||
t.Fatalf("failed to create comment: %v", err)
|
||||
}
|
||||
if comment.ID == "" {
|
||||
t.Error("expected comment ID to be set")
|
||||
}
|
||||
if comment.CreatedAt.IsZero() {
|
||||
t.Error("expected CreatedAt to be set")
|
||||
}
|
||||
|
||||
// Get comment
|
||||
retrieved, err := repo.GetMessage(ctx, comment.ID)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to get comment: %v", err)
|
||||
}
|
||||
if retrieved.Content != "This is a test comment" {
|
||||
t.Errorf("expected content 'This is a test comment', got %s", retrieved.Content)
|
||||
}
|
||||
if retrieved.AuthorType != models.MessageAuthorUser {
|
||||
t.Errorf("expected author type 'user', got %s", retrieved.AuthorType)
|
||||
}
|
||||
|
||||
// Delete comment
|
||||
if err := repo.DeleteMessage(ctx, comment.ID); err != nil {
|
||||
t.Fatalf("failed to delete comment: %v", err)
|
||||
}
|
||||
_, err = repo.GetMessage(ctx, comment.ID)
|
||||
if err == nil {
|
||||
t.Error("expected comment to be deleted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryRepository_MessageNotFound(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
ctx := context.Background()
|
||||
|
||||
_, err := repo.GetMessage(ctx, "nonexistent")
|
||||
if err == nil {
|
||||
t.Error("expected error for nonexistent comment")
|
||||
}
|
||||
|
||||
err = repo.DeleteMessage(ctx, "nonexistent")
|
||||
if err == nil {
|
||||
t.Error("expected error for deleting nonexistent comment")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryRepository_ListMessages(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
ctx := context.Background()
|
||||
|
||||
// Create a task
|
||||
task := &models.Task{ID: "task-123", BoardID: "board-123", ColumnID: "col-123", Title: "Test Task"}
|
||||
_ = repo.CreateTask(ctx, task)
|
||||
sessionID := setupMemoryTestSession(ctx, repo, task.ID)
|
||||
|
||||
// Create multiple comments
|
||||
_ = repo.CreateMessage(ctx, &models.Message{ID: "comment-1", TaskSessionID: sessionID, TaskID: "task-123", AuthorType: models.MessageAuthorUser, Content: "Comment 1"})
|
||||
_ = repo.CreateMessage(ctx, &models.Message{ID: "comment-2", TaskSessionID: sessionID, TaskID: "task-123", AuthorType: models.MessageAuthorAgent, Content: "Comment 2"})
|
||||
_ = repo.CreateMessage(ctx, &models.Message{ID: "comment-3", TaskSessionID: "session-456", TaskID: "task-456", AuthorType: models.MessageAuthorUser, Content: "Comment 3"})
|
||||
|
||||
comments, err := repo.ListMessages(ctx, sessionID)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to list comments: %v", err)
|
||||
}
|
||||
if len(comments) != 2 {
|
||||
t.Errorf("expected 2 comments for task-123, got %d", len(comments))
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryRepository_ListMessagesPagination(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
ctx := context.Background()
|
||||
|
||||
task := &models.Task{ID: "task-123", BoardID: "board-123", ColumnID: "col-123", Title: "Test Task"}
|
||||
_ = repo.CreateTask(ctx, task)
|
||||
sessionID := setupMemoryTestSession(ctx, repo, task.ID)
|
||||
|
||||
baseTime := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC)
|
||||
_ = repo.CreateMessage(ctx, &models.Message{
|
||||
ID: "comment-1",
|
||||
TaskSessionID: sessionID,
|
||||
TaskID: "task-123",
|
||||
AuthorType: models.MessageAuthorUser,
|
||||
Content: "Comment 1",
|
||||
CreatedAt: baseTime.Add(-2 * time.Minute),
|
||||
})
|
||||
_ = repo.CreateMessage(ctx, &models.Message{
|
||||
ID: "comment-2",
|
||||
TaskSessionID: sessionID,
|
||||
TaskID: "task-123",
|
||||
AuthorType: models.MessageAuthorUser,
|
||||
Content: "Comment 2",
|
||||
CreatedAt: baseTime.Add(-1 * time.Minute),
|
||||
})
|
||||
_ = repo.CreateMessage(ctx, &models.Message{
|
||||
ID: "comment-3",
|
||||
TaskSessionID: sessionID,
|
||||
TaskID: "task-123",
|
||||
AuthorType: models.MessageAuthorUser,
|
||||
Content: "Comment 3",
|
||||
CreatedAt: baseTime,
|
||||
})
|
||||
|
||||
comments, hasMore, err := repo.ListMessagesPaginated(ctx, sessionID, ListMessagesOptions{
|
||||
Limit: 2,
|
||||
Sort: "desc",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to list comments: %v", err)
|
||||
}
|
||||
if len(comments) != 2 {
|
||||
t.Fatalf("expected 2 comments, got %d", len(comments))
|
||||
}
|
||||
if !hasMore {
|
||||
t.Error("expected hasMore to be true")
|
||||
}
|
||||
if comments[0].ID != "comment-3" {
|
||||
t.Errorf("expected newest comment first, got %s", comments[0].ID)
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemoryRepository_MessageWithRequestsInput(t *testing.T) {
|
||||
repo := NewMemoryRepository()
|
||||
ctx := context.Background()
|
||||
|
||||
// Create a task
|
||||
task := &models.Task{ID: "task-123", BoardID: "board-123", ColumnID: "col-123", Title: "Test Task"}
|
||||
_ = repo.CreateTask(ctx, task)
|
||||
sessionID := setupMemoryTestSession(ctx, repo, task.ID)
|
||||
|
||||
// Create agent comment requesting input
|
||||
comment := &models.Message{
|
||||
TaskSessionID: sessionID,
|
||||
TaskID: "task-123",
|
||||
AuthorType: models.MessageAuthorAgent,
|
||||
AuthorID: "agent-123",
|
||||
Content: "What should I do next?",
|
||||
RequestsInput: true,
|
||||
}
|
||||
if err := repo.CreateMessage(ctx, comment); err != nil {
|
||||
t.Fatalf("failed to create comment: %v", err)
|
||||
}
|
||||
|
||||
retrieved, _ := repo.GetMessage(ctx, comment.ID)
|
||||
if !retrieved.RequestsInput {
|
||||
t.Error("expected RequestsInput to be true")
|
||||
}
|
||||
}
|
||||
@@ -237,7 +237,7 @@ func (r *SQLiteRepository) initSchema() error {
|
||||
CREATE TABLE IF NOT EXISTS task_sessions (
|
||||
id TEXT PRIMARY KEY,
|
||||
task_id TEXT NOT NULL,
|
||||
agent_instance_id TEXT NOT NULL DEFAULT '',
|
||||
agent_execution_id TEXT NOT NULL DEFAULT '',
|
||||
container_id TEXT NOT NULL DEFAULT '',
|
||||
agent_profile_id TEXT NOT NULL,
|
||||
executor_id TEXT DEFAULT '',
|
||||
@@ -1802,12 +1802,12 @@ func (r *SQLiteRepository) CreateTaskSession(ctx context.Context, session *model
|
||||
|
||||
_, err = r.db.ExecContext(ctx, `
|
||||
INSERT INTO task_sessions (
|
||||
id, task_id, agent_instance_id, container_id, agent_profile_id, executor_id, environment_id,
|
||||
id, task_id, agent_execution_id, container_id, agent_profile_id, executor_id, environment_id,
|
||||
repository_id, base_branch,
|
||||
agent_profile_snapshot, executor_snapshot, environment_snapshot, repository_snapshot,
|
||||
state, progress, error_message, metadata, started_at, completed_at, updated_at
|
||||
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`, session.ID, session.TaskID, session.AgentInstanceID, session.ContainerID, session.AgentProfileID,
|
||||
`, session.ID, session.TaskID, session.AgentExecutionID, session.ContainerID, session.AgentProfileID,
|
||||
session.ExecutorID, session.EnvironmentID, session.RepositoryID, session.BaseBranch,
|
||||
string(agentProfileSnapshotJSON), string(executorSnapshotJSON), string(environmentSnapshotJSON), string(repositorySnapshotJSON),
|
||||
string(session.State), session.Progress, session.ErrorMessage, string(metadataJSON),
|
||||
@@ -1828,13 +1828,13 @@ func (r *SQLiteRepository) GetTaskSession(ctx context.Context, id string) (*mode
|
||||
var completedAt sql.NullTime
|
||||
|
||||
err := r.db.QueryRowContext(ctx, `
|
||||
SELECT id, task_id, agent_instance_id, container_id, agent_profile_id, executor_id, environment_id,
|
||||
SELECT id, task_id, agent_execution_id, container_id, agent_profile_id, executor_id, environment_id,
|
||||
repository_id, base_branch,
|
||||
agent_profile_snapshot, executor_snapshot, environment_snapshot, repository_snapshot,
|
||||
state, progress, error_message, metadata, started_at, completed_at, updated_at
|
||||
FROM task_sessions WHERE id = ?
|
||||
`, id).Scan(
|
||||
&session.ID, &session.TaskID, &session.AgentInstanceID, &session.ContainerID, &session.AgentProfileID,
|
||||
&session.ID, &session.TaskID, &session.AgentExecutionID, &session.ContainerID, &session.AgentProfileID,
|
||||
&session.ExecutorID, &session.EnvironmentID,
|
||||
&session.RepositoryID, &session.BaseBranch,
|
||||
&agentProfileSnapshotJSON, &executorSnapshotJSON, &environmentSnapshotJSON, &repositorySnapshotJSON,
|
||||
@@ -1899,13 +1899,13 @@ func (r *SQLiteRepository) GetTaskSessionByTaskID(ctx context.Context, taskID st
|
||||
var completedAt sql.NullTime
|
||||
|
||||
err := r.db.QueryRowContext(ctx, `
|
||||
SELECT id, task_id, agent_instance_id, container_id, agent_profile_id, executor_id, environment_id,
|
||||
SELECT id, task_id, agent_execution_id, container_id, agent_profile_id, executor_id, environment_id,
|
||||
repository_id, base_branch,
|
||||
agent_profile_snapshot, executor_snapshot, environment_snapshot, repository_snapshot,
|
||||
state, progress, error_message, metadata, started_at, completed_at, updated_at
|
||||
FROM task_sessions WHERE task_id = ? ORDER BY started_at DESC LIMIT 1
|
||||
`, taskID).Scan(
|
||||
&session.ID, &session.TaskID, &session.AgentInstanceID, &session.ContainerID, &session.AgentProfileID,
|
||||
&session.ID, &session.TaskID, &session.AgentExecutionID, &session.ContainerID, &session.AgentProfileID,
|
||||
&session.ExecutorID, &session.EnvironmentID,
|
||||
&session.RepositoryID, &session.BaseBranch,
|
||||
&agentProfileSnapshotJSON, &executorSnapshotJSON, &environmentSnapshotJSON, &repositorySnapshotJSON,
|
||||
@@ -1970,7 +1970,7 @@ func (r *SQLiteRepository) GetActiveTaskSessionByTaskID(ctx context.Context, tas
|
||||
var completedAt sql.NullTime
|
||||
|
||||
err := r.db.QueryRowContext(ctx, `
|
||||
SELECT id, task_id, agent_instance_id, container_id, agent_profile_id, executor_id, environment_id,
|
||||
SELECT id, task_id, agent_execution_id, container_id, agent_profile_id, executor_id, environment_id,
|
||||
repository_id, base_branch,
|
||||
agent_profile_snapshot, executor_snapshot, environment_snapshot, repository_snapshot,
|
||||
state, progress, error_message, metadata, started_at, completed_at, updated_at
|
||||
@@ -1978,7 +1978,7 @@ func (r *SQLiteRepository) GetActiveTaskSessionByTaskID(ctx context.Context, tas
|
||||
WHERE task_id = ? AND state IN ('CREATED', 'STARTING', 'RUNNING', 'WAITING_FOR_INPUT')
|
||||
ORDER BY started_at DESC LIMIT 1
|
||||
`, taskID).Scan(
|
||||
&session.ID, &session.TaskID, &session.AgentInstanceID, &session.ContainerID, &session.AgentProfileID,
|
||||
&session.ID, &session.TaskID, &session.AgentExecutionID, &session.ContainerID, &session.AgentProfileID,
|
||||
&session.ExecutorID, &session.EnvironmentID,
|
||||
&session.RepositoryID, &session.BaseBranch,
|
||||
&agentProfileSnapshotJSON, &executorSnapshotJSON, &environmentSnapshotJSON, &repositorySnapshotJSON,
|
||||
@@ -2058,12 +2058,12 @@ func (r *SQLiteRepository) UpdateTaskSession(ctx context.Context, session *model
|
||||
|
||||
result, err := r.db.ExecContext(ctx, `
|
||||
UPDATE task_sessions SET
|
||||
agent_instance_id = ?, container_id = ?, agent_profile_id = ?, executor_id = ?, environment_id = ?,
|
||||
agent_execution_id = ?, container_id = ?, agent_profile_id = ?, executor_id = ?, environment_id = ?,
|
||||
repository_id = ?, base_branch = ?,
|
||||
agent_profile_snapshot = ?, executor_snapshot = ?, environment_snapshot = ?, repository_snapshot = ?,
|
||||
state = ?, progress = ?, error_message = ?, metadata = ?, completed_at = ?, updated_at = ?
|
||||
WHERE id = ?
|
||||
`, session.AgentInstanceID, session.ContainerID, session.AgentProfileID, session.ExecutorID, session.EnvironmentID,
|
||||
`, session.AgentExecutionID, session.ContainerID, session.AgentProfileID, session.ExecutorID, session.EnvironmentID,
|
||||
session.RepositoryID, session.BaseBranch,
|
||||
string(agentProfileSnapshotJSON), string(executorSnapshotJSON), string(environmentSnapshotJSON), string(repositorySnapshotJSON),
|
||||
string(session.State), session.Progress, session.ErrorMessage, string(metadataJSON), session.CompletedAt,
|
||||
@@ -2102,10 +2102,10 @@ func (r *SQLiteRepository) UpdateTaskSessionState(ctx context.Context, id string
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListAgentSessions returns all agent sessions for a task
|
||||
// ListTaskSessions returns all agent sessions for a task
|
||||
func (r *SQLiteRepository) ListTaskSessions(ctx context.Context, taskID string) ([]*models.TaskSession, error) {
|
||||
rows, err := r.db.QueryContext(ctx, `
|
||||
SELECT id, task_id, agent_instance_id, container_id, agent_profile_id, executor_id, environment_id,
|
||||
SELECT id, task_id, agent_execution_id, container_id, agent_profile_id, executor_id, environment_id,
|
||||
repository_id, base_branch,
|
||||
agent_profile_snapshot, executor_snapshot, environment_snapshot, repository_snapshot,
|
||||
state, progress, error_message, metadata, started_at, completed_at, updated_at
|
||||
@@ -2130,10 +2130,10 @@ func (r *SQLiteRepository) ListTaskSessions(ctx context.Context, taskID string)
|
||||
return sessions, nil
|
||||
}
|
||||
|
||||
// ListActiveAgentSessions returns all active agent sessions across all tasks
|
||||
// ListActiveTaskSessions returns all active agent sessions across all tasks
|
||||
func (r *SQLiteRepository) ListActiveTaskSessions(ctx context.Context) ([]*models.TaskSession, error) {
|
||||
rows, err := r.db.QueryContext(ctx, `
|
||||
SELECT id, task_id, agent_instance_id, container_id, agent_profile_id, executor_id, environment_id,
|
||||
SELECT id, task_id, agent_execution_id, container_id, agent_profile_id, executor_id, environment_id,
|
||||
repository_id, base_branch,
|
||||
agent_profile_snapshot, executor_snapshot, environment_snapshot, repository_snapshot,
|
||||
state, progress, error_message, metadata, started_at, completed_at, updated_at
|
||||
@@ -2227,7 +2227,7 @@ func (r *SQLiteRepository) scanTaskSessions(ctx context.Context, rows *sql.Rows)
|
||||
var completedAt sql.NullTime
|
||||
|
||||
err := rows.Scan(
|
||||
&session.ID, &session.TaskID, &session.AgentInstanceID, &session.ContainerID, &session.AgentProfileID,
|
||||
&session.ID, &session.TaskID, &session.AgentExecutionID, &session.ContainerID, &session.AgentProfileID,
|
||||
&session.ExecutorID, &session.EnvironmentID,
|
||||
&session.RepositoryID, &session.BaseBranch,
|
||||
&agentProfileSnapshotJSON, &executorSnapshotJSON, &environmentSnapshotJSON, &repositorySnapshotJSON,
|
||||
|
||||
@@ -735,9 +735,9 @@ func TestSQLiteRepository_TaskSessionCRUD(t *testing.T) {
|
||||
|
||||
// Create agent session
|
||||
session := &models.TaskSession{
|
||||
TaskID: "task-123",
|
||||
AgentInstanceID: "instance-abc",
|
||||
ContainerID: "container-xyz",
|
||||
TaskID: "task-123",
|
||||
AgentExecutionID: "execution-abc",
|
||||
ContainerID: "container-xyz",
|
||||
AgentProfileID: "profile-123",
|
||||
ExecutorID: "executor-1",
|
||||
EnvironmentID: "env-1",
|
||||
|
||||
@@ -1507,13 +1507,45 @@ func (s *Service) DeleteMessage(ctx context.Context, id string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateToolCallMessage updates a tool call message's status
|
||||
// UpdateToolCallMessage updates a tool call message's status.
|
||||
// It includes retry logic to handle race conditions where the complete event
|
||||
// may arrive before the message has been created by the start event.
|
||||
func (s *Service) UpdateToolCallMessage(ctx context.Context, sessionID, toolCallID, status, result string) error {
|
||||
message, err := s.repo.GetMessageByToolCallID(ctx, sessionID, toolCallID)
|
||||
const maxRetries = 5
|
||||
const retryDelay = 100 * time.Millisecond
|
||||
|
||||
var message *models.Message
|
||||
var err error
|
||||
|
||||
// Retry loop to handle race condition where complete event arrives before start event
|
||||
// has finished creating the message in the database
|
||||
for attempt := 0; attempt < maxRetries; attempt++ {
|
||||
message, err = s.repo.GetMessageByToolCallID(ctx, sessionID, toolCallID)
|
||||
if err == nil {
|
||||
break // Found the message, proceed with update
|
||||
}
|
||||
|
||||
// If context is cancelled, don't retry
|
||||
if ctx.Err() != nil {
|
||||
return ctx.Err()
|
||||
}
|
||||
|
||||
// Log retry attempt (only warn on final failure)
|
||||
if attempt < maxRetries-1 {
|
||||
s.logger.Debug("tool call message not found, retrying",
|
||||
zap.String("task_session_id", sessionID),
|
||||
zap.String("tool_call_id", toolCallID),
|
||||
zap.Int("attempt", attempt+1),
|
||||
zap.Int("max_retries", maxRetries))
|
||||
time.Sleep(retryDelay)
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
s.logger.Warn("tool call message not found for update",
|
||||
s.logger.Warn("tool call message not found for update after retries",
|
||||
zap.String("task_session_id", sessionID),
|
||||
zap.String("tool_call_id", toolCallID),
|
||||
zap.Int("retries", maxRetries),
|
||||
zap.Error(err))
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@ package v1
|
||||
|
||||
import "time"
|
||||
|
||||
// AgentStatus represents the status of an agent instance
|
||||
// AgentStatus represents the status of an agent execution
|
||||
type AgentStatus string
|
||||
|
||||
const (
|
||||
@@ -22,8 +22,8 @@ type ResourceLimits struct {
|
||||
DiskLimit string `json:"disk_limit"`
|
||||
}
|
||||
|
||||
// AgentInstance represents a running or completed agent container
|
||||
type AgentInstance struct {
|
||||
// AgentExecution represents a running or completed agent container
|
||||
type AgentExecution struct {
|
||||
ID string `json:"id"`
|
||||
TaskID string `json:"task_id"`
|
||||
AgentProfileID string `json:"agent_profile_id"`
|
||||
@@ -57,8 +57,8 @@ type AgentType struct {
|
||||
|
||||
// AgentLog represents a log entry from an agent
|
||||
type AgentLog struct {
|
||||
ID int64 `json:"id"`
|
||||
AgentInstanceID string `json:"agent_instance_id"`
|
||||
ID int64 `json:"id"`
|
||||
AgentExecutionID string `json:"agent_execution_id"`
|
||||
LogLevel string `json:"log_level"`
|
||||
Message string `json:"message"`
|
||||
Metadata map[string]interface{} `json:"metadata,omitempty"`
|
||||
|
||||
@@ -180,9 +180,16 @@ type Item struct {
|
||||
// For fileChange type
|
||||
Changes []FileChange `json:"changes,omitempty"`
|
||||
|
||||
// For reasoning type
|
||||
Summary []string `json:"summary,omitempty"`
|
||||
Content []string `json:"content,omitempty"`
|
||||
// For reasoning type - content can be objects like [{type: "text", text: "..."}]
|
||||
Summary []ContentPart `json:"summary,omitempty"`
|
||||
Content []ContentPart `json:"content,omitempty"`
|
||||
}
|
||||
|
||||
// ContentPart represents a content part in a Codex item.
|
||||
// This handles the OpenAI responses format where content is an array of typed objects.
|
||||
type ContentPart struct {
|
||||
Type string `json:"type,omitempty"` // "text", "output_text", "refusal", "input_text", etc.
|
||||
Text string `json:"text,omitempty"`
|
||||
}
|
||||
|
||||
// FileChange represents a file change in a fileChange item
|
||||
|
||||
@@ -65,6 +65,7 @@ const (
|
||||
ActionTaskExecution = "task.execution"
|
||||
ActionTaskSessionList = "task.session.list"
|
||||
ActionTaskSessionResume = "task.session.resume"
|
||||
ActionTaskSessionStatus = "task.session.status"
|
||||
|
||||
// Agent actions
|
||||
ActionAgentList = "agent.list"
|
||||
|
||||
@@ -57,8 +57,6 @@ type ErrorPayload struct {
|
||||
Details map[string]interface{} `json:"details,omitempty"`
|
||||
}
|
||||
|
||||
|
||||
|
||||
// NewRequest creates a new request message
|
||||
func NewRequest(id, action string, payload interface{}) (*Message, error) {
|
||||
data, err := json.Marshal(payload)
|
||||
|
||||
@@ -11,6 +11,7 @@ import { DEBUG_UI } from '@/lib/config';
|
||||
import { getWebSocketClient } from '@/lib/ws/connection';
|
||||
import { useRepositories } from '@/hooks/use-repositories';
|
||||
import { useTaskAgent } from '@/hooks/use-task-agent';
|
||||
import { useSessionResumption } from '@/hooks/use-session-resumption';
|
||||
import { useAppStore } from '@/components/state-provider';
|
||||
|
||||
type TaskPageClientProps = {
|
||||
@@ -38,18 +39,37 @@ export default function TaskPage({ task: initialTask, sessionId = null }: TaskPa
|
||||
}, [initialTask, kanbanTask]);
|
||||
const connectionStatus = useAppStore((state) => state.connection.status);
|
||||
|
||||
// Custom hooks for state management
|
||||
// Session resumption hook - handles auto-resume on page reload
|
||||
const {
|
||||
resumptionState,
|
||||
error: resumptionError,
|
||||
taskSessionState: resumedSessionState,
|
||||
worktreePath: resumedWorktreePath,
|
||||
worktreeBranch: resumedWorktreeBranch,
|
||||
} = useSessionResumption(task?.id ?? null, sessionId);
|
||||
|
||||
// Regular task agent hook for non-resumed sessions
|
||||
const {
|
||||
isAgentRunning,
|
||||
isAgentLoading,
|
||||
worktreePath,
|
||||
worktreeBranch,
|
||||
worktreePath: agentWorktreePath,
|
||||
worktreeBranch: agentWorktreeBranch,
|
||||
taskSessionId,
|
||||
taskSessionState,
|
||||
taskSessionState: agentSessionState,
|
||||
handleStartAgent,
|
||||
handleStopAgent,
|
||||
} = useTaskAgent(task);
|
||||
|
||||
// Merge state from resumption and regular agent hooks
|
||||
const activeSessionId = sessionId ?? taskSessionId;
|
||||
const isResuming = resumptionState === 'checking' || resumptionState === 'resuming';
|
||||
const isResumed = resumptionState === 'resumed' || resumptionState === 'running';
|
||||
|
||||
// Both hooks read taskSessionState from the store, so prefer resumedSessionState as it's always
|
||||
// updated when we have a sessionId from URL. For worktree, use resumed values when resuming/resumed.
|
||||
const taskSessionState = resumedSessionState ?? agentSessionState;
|
||||
const worktreePath = sessionId ? (resumedWorktreePath ?? agentWorktreePath) : agentWorktreePath;
|
||||
const worktreeBranch = sessionId ? (resumedWorktreeBranch ?? agentWorktreeBranch) : agentWorktreeBranch;
|
||||
|
||||
// Derive working state for debug overlay
|
||||
const isAgentWorking =
|
||||
@@ -107,6 +127,8 @@ export default function TaskPage({ task: initialTask, sessionId = null }: TaskPa
|
||||
task_state: task?.state ?? null,
|
||||
task_session_state: taskSessionState ?? null,
|
||||
is_agent_working: isAgentWorking,
|
||||
resumption_state: resumptionState,
|
||||
resumption_error: resumptionError,
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
@@ -118,8 +140,8 @@ export default function TaskPage({ task: initialTask, sessionId = null }: TaskPa
|
||||
baseBranch={task?.repositories?.[0]?.base_branch ?? undefined}
|
||||
onStartAgent={handleStartAgent}
|
||||
onStopAgent={handleStopAgent}
|
||||
isAgentRunning={isAgentRunning}
|
||||
isAgentLoading={isAgentLoading}
|
||||
isAgentRunning={isAgentRunning || isResumed}
|
||||
isAgentLoading={isAgentLoading || isResuming}
|
||||
worktreePath={worktreePath}
|
||||
worktreeBranch={worktreeBranch}
|
||||
repositoryPath={repository?.local_path ?? null}
|
||||
@@ -128,6 +150,7 @@ export default function TaskPage({ task: initialTask, sessionId = null }: TaskPa
|
||||
|
||||
<TaskLayout
|
||||
taskId={task?.id ?? null}
|
||||
sessionId={activeSessionId ?? null}
|
||||
onSendMessage={handleSendMessage}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -9,9 +9,10 @@ import { getWebSocketClient } from '@/lib/ws/connection';
|
||||
|
||||
type ShellTerminalProps = {
|
||||
taskId: string;
|
||||
sessionId: string | null;
|
||||
};
|
||||
|
||||
export function ShellTerminal({ taskId }: ShellTerminalProps) {
|
||||
export function ShellTerminal({ taskId, sessionId }: ShellTerminalProps) {
|
||||
const terminalRef = useRef<HTMLDivElement>(null);
|
||||
const xtermRef = useRef<Terminal | null>(null);
|
||||
const fitAddonRef = useRef<FitAddon | null>(null);
|
||||
@@ -74,7 +75,7 @@ export function ShellTerminal({ taskId }: ShellTerminalProps) {
|
||||
|
||||
// Handle user input
|
||||
terminal.onData((data) => {
|
||||
send('shell.input', { task_id: taskId, data });
|
||||
send('shell.input', { task_id: taskId, session_id: sessionId, data });
|
||||
});
|
||||
|
||||
// Handle resize
|
||||
@@ -89,7 +90,7 @@ export function ShellTerminal({ taskId }: ShellTerminalProps) {
|
||||
xtermRef.current = null;
|
||||
fitAddonRef.current = null;
|
||||
};
|
||||
}, [taskId, send]);
|
||||
}, [taskId, sessionId, send]);
|
||||
|
||||
// Write new output to terminal
|
||||
useEffect(() => {
|
||||
@@ -104,9 +105,14 @@ export function ShellTerminal({ taskId }: ShellTerminalProps) {
|
||||
}, [shellOutput]);
|
||||
|
||||
// Subscribe to shell on mount to start the shell stream
|
||||
// Uses retry logic to handle cases where agent isn't ready yet (e.g., session resumption)
|
||||
useEffect(() => {
|
||||
// Increment subscription ID to invalidate any pending requests
|
||||
const currentSubscriptionId = ++subscriptionIdRef.current;
|
||||
let retryCount = 0;
|
||||
const maxRetries = 10;
|
||||
const retryDelay = 1000; // 1 second between retries
|
||||
let retryTimeout: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
// Clear any stale output before subscribing to get fresh buffer
|
||||
storeApi.getState().clearShellOutput(taskId);
|
||||
@@ -117,10 +123,15 @@ export function ShellTerminal({ taskId }: ShellTerminalProps) {
|
||||
xtermRef.current.clear();
|
||||
}
|
||||
|
||||
const client = getWebSocketClient();
|
||||
if (client) {
|
||||
const attemptSubscribe = () => {
|
||||
const client = getWebSocketClient();
|
||||
if (!client) return;
|
||||
|
||||
// Check if this subscription is still valid
|
||||
if (subscriptionIdRef.current !== currentSubscriptionId) return;
|
||||
|
||||
client
|
||||
.request<{ success: boolean; buffer?: string }>('shell.subscribe', { task_id: taskId })
|
||||
.request<{ success: boolean; buffer?: string }>('shell.subscribe', { task_id: taskId, session_id: sessionId })
|
||||
.then((response) => {
|
||||
// Only process if this is still the current subscription (handles React Strict Mode)
|
||||
if (subscriptionIdRef.current !== currentSubscriptionId) return;
|
||||
@@ -132,10 +143,26 @@ export function ShellTerminal({ taskId }: ShellTerminalProps) {
|
||||
})
|
||||
.catch((err) => {
|
||||
if (subscriptionIdRef.current !== currentSubscriptionId) return;
|
||||
console.error('Failed to subscribe to shell:', err);
|
||||
|
||||
// Retry if agent not ready yet (common during session resumption)
|
||||
if (retryCount < maxRetries) {
|
||||
retryCount++;
|
||||
console.log(`[ShellTerminal] Retrying shell subscription (${retryCount}/${maxRetries})...`);
|
||||
retryTimeout = setTimeout(attemptSubscribe, retryDelay);
|
||||
} else {
|
||||
console.error('Failed to subscribe to shell after retries:', err);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [taskId, storeApi]);
|
||||
};
|
||||
|
||||
attemptSubscribe();
|
||||
|
||||
return () => {
|
||||
if (retryTimeout) {
|
||||
clearTimeout(retryTimeout);
|
||||
}
|
||||
};
|
||||
}, [taskId, sessionId, storeApi]);
|
||||
|
||||
return (
|
||||
<div
|
||||
|
||||
@@ -12,11 +12,13 @@ const DEFAULT_HORIZONTAL_LAYOUT: [number, number] = [75, 25];
|
||||
|
||||
type TaskLayoutProps = {
|
||||
taskId: string | null;
|
||||
sessionId: string | null;
|
||||
onSendMessage: (content: string) => Promise<void>;
|
||||
};
|
||||
|
||||
export const TaskLayout = memo(function TaskLayout({
|
||||
taskId,
|
||||
sessionId,
|
||||
onSendMessage,
|
||||
}: TaskLayoutProps) {
|
||||
const [horizontalLayout, setHorizontalLayout] = useState<[number, number]>(
|
||||
@@ -63,7 +65,7 @@ export const TaskLayout = memo(function TaskLayout({
|
||||
</ResizablePanel>
|
||||
<ResizableHandle className="w-px" />
|
||||
<ResizablePanel defaultSize={horizontalLayout[1]} minSize={20}>
|
||||
<TaskRightPanel topPanel={topFilesPanel} taskId={taskId ?? ''} />
|
||||
<TaskRightPanel topPanel={topFilesPanel} taskId={taskId ?? ''} sessionId={sessionId} />
|
||||
</ResizablePanel>
|
||||
</ResizablePanelGroup>
|
||||
</div>
|
||||
|
||||
@@ -13,11 +13,12 @@ import { ShellTerminal } from '@/components/task/shell-terminal';
|
||||
type TaskRightPanelProps = {
|
||||
topPanel: ReactNode;
|
||||
taskId: string;
|
||||
sessionId: string | null;
|
||||
};
|
||||
|
||||
const DEFAULT_RIGHT_LAYOUT: [number, number] = [55, 45];
|
||||
|
||||
const TaskRightPanel = memo(function TaskRightPanel({ topPanel, taskId }: TaskRightPanelProps) {
|
||||
const TaskRightPanel = memo(function TaskRightPanel({ topPanel, taskId, sessionId }: TaskRightPanelProps) {
|
||||
const [rightLayout, setRightLayout] = useState<[number, number]>(() =>
|
||||
getLocalStorage('task-layout-right', DEFAULT_RIGHT_LAYOUT)
|
||||
);
|
||||
@@ -179,7 +180,7 @@ const TaskRightPanel = memo(function TaskRightPanel({ topPanel, taskId }: TaskRi
|
||||
{terminalIds.map((id) => (
|
||||
<TabsContent key={id} value={`terminal-${id}`} className="flex-1 min-h-0">
|
||||
<div className="flex-1 min-h-0 h-full p-1">
|
||||
<ShellTerminal taskId={taskId} />
|
||||
<ShellTerminal taskId={taskId} sessionId={sessionId} />
|
||||
</div>
|
||||
</TabsContent>
|
||||
))}
|
||||
|
||||
@@ -0,0 +1,249 @@
|
||||
import { useCallback, useEffect, useState, useRef } from 'react';
|
||||
import { getWebSocketClient } from '@/lib/ws/connection';
|
||||
import { useAppStore } from '@/components/state-provider';
|
||||
import type { TaskSessionState } from '@/lib/types/http';
|
||||
|
||||
export type SessionStatus = {
|
||||
session_id: string;
|
||||
task_id: string;
|
||||
state: string;
|
||||
agent_profile_id?: string;
|
||||
is_agent_running: boolean;
|
||||
is_resumable: boolean;
|
||||
needs_resume: boolean;
|
||||
resume_reason?: string;
|
||||
acp_session_id?: string;
|
||||
worktree_path?: string;
|
||||
worktree_branch?: string;
|
||||
error?: string;
|
||||
};
|
||||
|
||||
export type ResumptionState = 'idle' | 'checking' | 'resuming' | 'resumed' | 'running' | 'error';
|
||||
|
||||
interface UseSessionResumptionReturn {
|
||||
resumptionState: ResumptionState;
|
||||
sessionStatus: SessionStatus | null;
|
||||
error: string | null;
|
||||
taskSessionState: TaskSessionState | null;
|
||||
worktreePath: string | null;
|
||||
worktreeBranch: string | null;
|
||||
resumeSession: () => Promise<boolean>;
|
||||
startNewSession: (agentProfileId: string) => Promise<boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook for handling session resumption on page reload.
|
||||
* When a sessionId is provided (from URL), it checks the session status
|
||||
* and automatically resumes if needed.
|
||||
*/
|
||||
export function useSessionResumption(
|
||||
taskId: string | null,
|
||||
sessionId: string | null
|
||||
): UseSessionResumptionReturn {
|
||||
const [resumptionState, setResumptionState] = useState<ResumptionState>('idle');
|
||||
const [sessionStatus, setSessionStatus] = useState<SessionStatus | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [worktreePath, setWorktreePath] = useState<string | null>(null);
|
||||
const [worktreeBranch, setWorktreeBranch] = useState<string | null>(null);
|
||||
const connectionStatus = useAppStore((state) => state.connection.status);
|
||||
// Read task session state from store so WebSocket updates are reflected
|
||||
const taskSessionState = useAppStore((state) => taskId ? state.taskSessionStatesByTaskId[taskId] ?? null : null);
|
||||
const setStoreTaskSessionState = useAppStore((state) => state.setTaskSessionState);
|
||||
const hasAttemptedResume = useRef(false);
|
||||
|
||||
// Check session status and auto-resume if needed
|
||||
useEffect(() => {
|
||||
if (!taskId || !sessionId) return;
|
||||
if (connectionStatus !== 'connected') return;
|
||||
if (hasAttemptedResume.current) return;
|
||||
|
||||
const checkAndResume = async () => {
|
||||
const client = getWebSocketClient();
|
||||
if (!client) return;
|
||||
|
||||
hasAttemptedResume.current = true;
|
||||
setResumptionState('checking');
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// 1. Check session status
|
||||
console.log('[useSessionResumption] Checking session status:', { taskId, sessionId });
|
||||
const status = await client.request<SessionStatus>('task.session.status', {
|
||||
task_id: taskId,
|
||||
task_session_id: sessionId,
|
||||
});
|
||||
console.log('[useSessionResumption] Session status:', status);
|
||||
setSessionStatus(status);
|
||||
|
||||
if (status.error) {
|
||||
setResumptionState('error');
|
||||
setError(status.error);
|
||||
return;
|
||||
}
|
||||
|
||||
// Update worktree info
|
||||
setWorktreePath(status.worktree_path ?? null);
|
||||
setWorktreeBranch(status.worktree_branch ?? null);
|
||||
if (taskId && status.state) {
|
||||
setStoreTaskSessionState(taskId, status.state as TaskSessionState);
|
||||
}
|
||||
|
||||
// 2. If agent is already running, we're good
|
||||
if (status.is_agent_running) {
|
||||
console.log('[useSessionResumption] Agent already running');
|
||||
setResumptionState('running');
|
||||
return;
|
||||
}
|
||||
|
||||
// 3. If session needs resume and is resumable, auto-resume
|
||||
if (status.needs_resume && status.is_resumable) {
|
||||
console.log('[useSessionResumption] Auto-resuming session');
|
||||
setResumptionState('resuming');
|
||||
|
||||
const resumeResp = await client.request<{
|
||||
success: boolean;
|
||||
state?: string;
|
||||
worktree_path?: string;
|
||||
worktree_branch?: string;
|
||||
error?: string;
|
||||
}>('task.session.resume', {
|
||||
task_id: taskId,
|
||||
task_session_id: sessionId,
|
||||
}, 30000);
|
||||
|
||||
if (resumeResp.success) {
|
||||
console.log('[useSessionResumption] Session resumed successfully');
|
||||
setResumptionState('resumed');
|
||||
if (taskId && resumeResp.state) {
|
||||
setStoreTaskSessionState(taskId, resumeResp.state as TaskSessionState);
|
||||
}
|
||||
if (resumeResp.worktree_path) {
|
||||
setWorktreePath(resumeResp.worktree_path);
|
||||
}
|
||||
if (resumeResp.worktree_branch) {
|
||||
setWorktreeBranch(resumeResp.worktree_branch);
|
||||
}
|
||||
} else {
|
||||
console.error('[useSessionResumption] Resume failed:', resumeResp.error);
|
||||
setResumptionState('error');
|
||||
setError(resumeResp.error ?? 'Failed to resume session');
|
||||
}
|
||||
} else if (!status.is_resumable) {
|
||||
// Session cannot be resumed (terminal state or missing data)
|
||||
console.log('[useSessionResumption] Session not resumable');
|
||||
setResumptionState('idle');
|
||||
} else {
|
||||
// Session exists but doesn't need resume (already running or other state)
|
||||
setResumptionState('idle');
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('[useSessionResumption] Error checking/resuming session:', err);
|
||||
setResumptionState('error');
|
||||
setError(err instanceof Error ? err.message : 'Unknown error');
|
||||
}
|
||||
};
|
||||
|
||||
checkAndResume();
|
||||
}, [taskId, sessionId, connectionStatus, setStoreTaskSessionState]);
|
||||
|
||||
// Manual resume function
|
||||
const resumeSession = useCallback(async (): Promise<boolean> => {
|
||||
if (!taskId || !sessionId) return false;
|
||||
|
||||
const client = getWebSocketClient();
|
||||
if (!client) return false;
|
||||
|
||||
setResumptionState('resuming');
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await client.request<{
|
||||
success: boolean;
|
||||
state?: string;
|
||||
worktree_path?: string;
|
||||
worktree_branch?: string;
|
||||
error?: string;
|
||||
}>('task.session.resume', {
|
||||
task_id: taskId,
|
||||
task_session_id: sessionId,
|
||||
}, 30000);
|
||||
|
||||
if (response.success) {
|
||||
setResumptionState('resumed');
|
||||
if (taskId && response.state) {
|
||||
setStoreTaskSessionState(taskId, response.state as TaskSessionState);
|
||||
}
|
||||
if (response.worktree_path) {
|
||||
setWorktreePath(response.worktree_path);
|
||||
}
|
||||
if (response.worktree_branch) {
|
||||
setWorktreeBranch(response.worktree_branch);
|
||||
}
|
||||
return true;
|
||||
} else {
|
||||
setResumptionState('error');
|
||||
setError(response.error ?? 'Failed to resume session');
|
||||
return false;
|
||||
}
|
||||
} catch (err) {
|
||||
setResumptionState('error');
|
||||
setError(err instanceof Error ? err.message : 'Unknown error');
|
||||
return false;
|
||||
}
|
||||
}, [taskId, sessionId, setStoreTaskSessionState]);
|
||||
|
||||
// Start new session function (fallback when resume fails)
|
||||
const startNewSession = useCallback(async (agentProfileId: string): Promise<boolean> => {
|
||||
if (!taskId) return false;
|
||||
|
||||
const client = getWebSocketClient();
|
||||
if (!client) return false;
|
||||
|
||||
setResumptionState('resuming');
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const response = await client.request<{
|
||||
success: boolean;
|
||||
task_session_id?: string;
|
||||
state?: string;
|
||||
worktree_path?: string;
|
||||
worktree_branch?: string;
|
||||
}>('orchestrator.start', {
|
||||
task_id: taskId,
|
||||
agent_profile_id: agentProfileId,
|
||||
}, 15000);
|
||||
|
||||
if (response.success) {
|
||||
setResumptionState('resumed');
|
||||
if (taskId && response.state) {
|
||||
setStoreTaskSessionState(taskId, response.state as TaskSessionState);
|
||||
}
|
||||
if (response.worktree_path) {
|
||||
setWorktreePath(response.worktree_path);
|
||||
}
|
||||
if (response.worktree_branch) {
|
||||
setWorktreeBranch(response.worktree_branch);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
} catch (err) {
|
||||
setResumptionState('error');
|
||||
setError(err instanceof Error ? err.message : 'Unknown error');
|
||||
return false;
|
||||
}
|
||||
}, [taskId, setStoreTaskSessionState]);
|
||||
|
||||
return {
|
||||
resumptionState,
|
||||
sessionStatus,
|
||||
error,
|
||||
taskSessionState,
|
||||
worktreePath,
|
||||
worktreeBranch,
|
||||
resumeSession,
|
||||
startNewSession,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user