Files
kandev/apps/backend/internal/agent/lifecycle/session.go
T
João Salavisa 2e108b040f 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
2026-01-16 22:14:19 +00:00

350 lines
11 KiB
Go

package lifecycle
import (
"context"
"fmt"
"time"
"go.uber.org/zap"
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
eventPublisher *EventPublisher
streamManager *StreamManager
executionStore *ExecutionStore
}
// NewSessionManager creates a new SessionManager
func NewSessionManager(log *logger.Logger) *SessionManager {
return &SessionManager{
logger: log,
}
}
// 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
AgentVersion string
SessionID string
}
// InitializeSession initializes an ACP session with the agent.
// It handles the initialize handshake and session creation/loading based on config.
//
// Session behavior:
// - If agentConfig.SessionConfig.ResumeViaACP is true AND existingSessionID is provided: use session/load
// - If agentConfig.SessionConfig.ResumeViaACP is false (CLI handles resume): always use session/new
// - Otherwise: use session/new
func (sm *SessionManager) InitializeSession(
ctx context.Context,
client *agentctl.Client,
agentConfig *registry.AgentTypeConfig,
existingSessionID string,
workspacePath string,
) (*InitializeResult, error) {
sm.logger.Info("initializing ACP session",
zap.String("agent_type", agentConfig.ID),
zap.String("workspace_path", workspacePath),
zap.Bool("resume_via_acp", agentConfig.SessionConfig.ResumeViaACP),
zap.String("existing_session_id", existingSessionID))
// Step 1: Send initialize request
sm.logger.Info("sending ACP initialize request",
zap.String("agent_type", agentConfig.ID))
agentInfo, err := client.Initialize(ctx, "kandev", "1.0.0")
if err != nil {
sm.logger.Error("ACP initialize failed",
zap.String("agent_type", agentConfig.ID),
zap.Error(err))
return nil, fmt.Errorf("initialize failed: %w", err)
}
result := &InitializeResult{
AgentName: "unknown",
AgentVersion: "unknown",
}
if agentInfo != nil {
result.AgentName = agentInfo.Name
result.AgentVersion = agentInfo.Version
}
sm.logger.Info("ACP initialize response received",
zap.String("agent_type", agentConfig.ID),
zap.String("agent_name", result.AgentName),
zap.String("agent_version", result.AgentVersion))
// Step 2: Create or resume ACP session based on configuration
sessionID, err := sm.createOrLoadSession(ctx, client, agentConfig, existingSessionID, workspacePath)
if err != nil {
return nil, err
}
result.SessionID = sessionID
return result, nil
}
// createOrLoadSession determines whether to create a new session or load an existing one
// based on the agent configuration and whether an existing session ID is provided.
func (sm *SessionManager) createOrLoadSession(
ctx context.Context,
client *agentctl.Client,
agentConfig *registry.AgentTypeConfig,
existingSessionID string,
workspacePath string,
) (string, error) {
// Use session/load only when:
// 1. ResumeViaACP is true (agent supports ACP-based resume)
// 2. An existing session ID is provided
shouldLoadSession := agentConfig.SessionConfig.ResumeViaACP && existingSessionID != ""
if shouldLoadSession {
return sm.loadSession(ctx, client, agentConfig, existingSessionID)
}
// Log why we're creating a new session when an existing session ID was provided
if existingSessionID != "" && !agentConfig.SessionConfig.ResumeViaACP {
sm.logger.Info("skipping ACP session/load (resume handled via CLI)",
zap.String("agent_type", agentConfig.ID),
zap.String("session_id", existingSessionID),
zap.String("resume_flag", agentConfig.SessionConfig.ResumeFlag))
}
return sm.createNewSession(ctx, client, agentConfig, workspacePath)
}
// loadSession loads an existing session via ACP session/load
func (sm *SessionManager) loadSession(
ctx context.Context,
client *agentctl.Client,
agentConfig *registry.AgentTypeConfig,
sessionID string,
) (string, error) {
sm.logger.Info("sending ACP session/load request",
zap.String("agent_type", agentConfig.ID),
zap.String("session_id", sessionID))
if err := client.LoadSession(ctx, sessionID); err != nil {
sm.logger.Error("ACP session/load failed",
zap.String("agent_type", agentConfig.ID),
zap.String("session_id", sessionID),
zap.Error(err))
return "", fmt.Errorf("session/load failed: %w", err)
}
sm.logger.Info("ACP session loaded successfully",
zap.String("agent_type", agentConfig.ID),
zap.String("session_id", sessionID))
return sessionID, nil
}
// createNewSession creates a new session via ACP session/new
func (sm *SessionManager) createNewSession(
ctx context.Context,
client *agentctl.Client,
agentConfig *registry.AgentTypeConfig,
workspacePath string,
) (string, error) {
sm.logger.Info("sending ACP session/new request",
zap.String("agent_type", agentConfig.ID),
zap.String("workspace_path", workspacePath))
sessionID, err := client.NewSession(ctx, workspacePath)
if err != nil {
sm.logger.Error("ACP session/new failed",
zap.String("agent_type", agentConfig.ID),
zap.String("workspace_path", workspacePath),
zap.Error(err))
return "", fmt.Errorf("session/new failed: %w", err)
}
sm.logger.Info("ACP session created successfully",
zap.String("agent_type", agentConfig.ID),
zap.String("session_id", sessionID))
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
}