fix(agent): honor session passthrough snapshot when starting agent process (#1003)

* fix(agent): honor session passthrough snapshot when starting agent process

Tasks created in agent (ACP) mode got stuck in "starting" after toggling
the profile's cli_passthrough flag and restarting the server.
StartAgentProcess re-resolved the live profile each launch, so the new
flag rerouted existing ACP sessions into the passthrough path (and vice
versa), where the workspace plumbing didn't match.

Snapshot session.IsPassthrough onto LaunchAgentRequest /
lifecycle.LaunchRequest / AgentExecution and let StartAgentProcess use
that as the source of truth. Sessionless launches (legacy
controller.LaunchAgent) still fall back to live profile resolution.

Fixes #981.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(agent): make passthrough snapshot the sole routing signal in StartAgentProcess

Bot review feedback follow-up (#1003):

- Route on the snapshot alone (new routePassthrough helper). A transient
  ResolveProfile error no longer silently routes a passthrough session
  to ACP — the fresh path surfaces an explicit error, the resume path
  surfaces the existing resolvePassthroughAgent error.
- Add TestStartAgentProcess_PassthroughResume_SurvivesProfileResolveError
  and TestStartAgentProcess_FreshPassthrough_SurfacesProfileResolveError
  to lock the no-silent-ACP-fallback invariant.
- Add TestLaunchPreparedSession_PropagatesIsPassthrough mirroring the
  resume-path propagation test so both build paths are independently
  covered.
- Strip issue-number references from source/test comments per project
  convention.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(agent): avoid double ResolveProfile in sessionless passthrough path

routePassthrough now returns (bool, *AgentProfileInfo). When the
sessionless fallback path already resolved the profile, it threads it
back so StartAgentProcess can reuse it for command building instead of
calling ResolveProfile a second time. Snapshot-driven routing still
returns nil so the snapshot path resolves fresh — the snapshot
deliberately outlives any particular live profile state.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(agent): extract startPassthroughExecution to satisfy nestif

CI's golangci-lint flagged the nested-if complexity of the passthrough
dispatch block in StartAgentProcess after the previous round of fixes
pushed it past nestif's threshold of 5. Move the resume-vs-fresh
branching plus the lazy profile resolution into a startPassthroughExecution
helper so StartAgentProcess becomes a single short routing decision.

No behavior change.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* docs: drop caller reference from startPassthroughExecution comment

Per project convention, source comments shouldn't name the calling
function — the reason it's its own method is captured by its contract
(profileInfo nullability + routePassthrough handoff), not by the
caller's name.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
João Salavisa
2026-05-21 23:39:23 +01:00
committed by GitHub
parent 0f1081d423
commit f39e7b06ca
11 changed files with 366 additions and 14 deletions
+1
View File
@@ -93,6 +93,7 @@ func (a *lifecycleAdapter) LaunchAgent(ctx context.Context, req *executor.Launch
PreviousExecutionID: req.PreviousExecutionID,
McpMode: req.McpMode,
IsEphemeral: req.IsEphemeral,
IsPassthrough: req.IsPassthrough,
SetupScript: req.SetupScript,
// Worktree configuration for concurrent agent execution
UseWorktree: req.UseWorktree,
@@ -725,6 +725,7 @@ func (m *Manager) promoteWorkspaceExecution(ctx context.Context, execution *Agen
if req.PreviousExecutionID != "" {
execution.isResumedSession = true
}
execution.IsPassthrough = req.IsPassthrough
m.logger.Info("promoted workspace-only execution to agent execution",
zap.String("execution_id", execution.ID),
zap.String("session_id", req.SessionID),
@@ -853,6 +854,7 @@ func (m *Manager) buildExecutionFromInstance(
if req.PreviousExecutionID != "" {
execution.isResumedSession = true
}
execution.IsPassthrough = req.IsPassthrough
cmds := m.buildAgentCommand(req, profileInfo, agentConfig)
execution.AgentCommand = cmds.initial
execution.ContinueCommand = cmds.continue_
@@ -15,6 +15,60 @@ import (
"github.com/kandev/kandev/internal/task/models"
)
// startPassthroughExecution dispatches a passthrough-routed execution to the
// resume or fresh launch path. profileInfo may be nil — see routePassthrough's
// contract.
func (m *Manager) startPassthroughExecution(ctx context.Context, execution *AgentExecution, profileInfo *AgentProfileInfo) error {
if execution.isResumedSession {
// Resume reuses the launched session id; ResumePassthroughSession does
// its own profile lookup for command building.
return m.ResumePassthroughSession(ctx, execution.SessionID)
}
if profileInfo == nil {
// Snapshot-driven routing leaves profileInfo nil so we resolve fresh
// here for command building.
if execution.AgentProfileID == "" || m.profileResolver == nil {
return fmt.Errorf("execution %q is passthrough but has no resolvable profile", execution.ID)
}
resolved, err := m.profileResolver.ResolveProfile(ctx, execution.AgentProfileID)
if err != nil {
return fmt.Errorf("resolve profile for passthrough execution %q: %w", execution.ID, err)
}
profileInfo = resolved
}
return m.startPassthroughSession(ctx, execution, profileInfo)
}
// routePassthrough decides whether an execution should launch on the passthrough
// PTY path or the ACP path. The session-creation snapshot
// (execution.IsPassthrough) is authoritative for session-backed launches.
// Sessionless launches (legacy controller.LaunchAgent) fall back to live profile
// state so first-time launches reflect the current mode. A profile resolve
// failure on the fallback path is treated as "not passthrough" — callers that
// need profile info for command building handle the resolve error themselves.
//
// When the sessionless fallback path resolved the profile, the resolved
// *AgentProfileInfo is returned so the caller can reuse it for command building
// without a second round-trip. Snapshot-driven routing returns nil for the
// profile because the caller must resolve fresh — the snapshot deliberately
// outlives any particular live profile state.
func (m *Manager) routePassthrough(ctx context.Context, execution *AgentExecution) (bool, *AgentProfileInfo) {
if execution.IsPassthrough {
return true, nil
}
if execution.SessionID != "" || execution.AgentProfileID == "" || m.profileResolver == nil {
return false, nil
}
profileInfo, err := m.profileResolver.ResolveProfile(ctx, execution.AgentProfileID)
if err != nil || profileInfo == nil {
return false, nil
}
if !profileInfo.CLIPassthrough {
return false, nil
}
return true, profileInfo
}
// StartAgentProcess configures and starts the agent subprocess for an execution.
// This must be called after Launch() to actually start the agent (e.g., auggie, codex).
// The command is built internally based on the execution's agent profile.
@@ -24,17 +78,22 @@ func (m *Manager) StartAgentProcess(ctx context.Context, executionID string) err
return fmt.Errorf("execution %q not found", executionID)
}
// Check if this execution should use passthrough mode
if execution.AgentProfileID != "" && m.profileResolver != nil {
profileInfo, err := m.profileResolver.ResolveProfile(ctx, execution.AgentProfileID)
if err == nil && profileInfo.CLIPassthrough {
// On resume (e.g., after backend restart), use the resume command path
// so the agent receives resume flags (-c / --resume).
if execution.isResumedSession {
return m.ResumePassthroughSession(ctx, execution.SessionID)
}
return m.startPassthroughSession(ctx, execution, profileInfo)
}
// Decide passthrough vs ACP. The session-creation snapshot
// (execution.IsPassthrough, sourced from TaskSession.IsPassthrough) is
// the source of truth: a profile that toggles CLIPassthrough after the
// session was created must not strand existing sessions in the wrong
// launch path. Non-session launches (e.g. the low-level
// controller.LaunchAgent path) leave IsPassthrough false and fall back to
// live profile resolution so first-time launches still pick the current
// mode.
//
// Profile resolution is needed only for *command building* in the
// non-resume passthrough path; it is not part of the routing decision. A
// transient resolve error must not silently route a passthrough session
// to ACP — the resume branch routes on the snapshot alone, and the fresh
// branch surfaces the resolve error explicitly.
if isPassthrough, profileInfo := m.routePassthrough(ctx, execution); isPassthrough {
return m.startPassthroughExecution(ctx, execution, profileInfo)
}
if execution.agentctl == nil {
@@ -2,16 +2,23 @@ package lifecycle
import (
"context"
"errors"
"strings"
"testing"
)
// mockAgentProfileResolver returns a profile pointing to the mock-agent.
// When err is non-nil, ResolveProfile returns that error and a nil profile —
// simulating transient DB hiccups, network failures, or deleted profiles.
type mockAgentProfileResolver struct {
cliPassthrough bool
err error
}
func (m *mockAgentProfileResolver) ResolveProfile(_ context.Context, profileID string) (*AgentProfileInfo, error) {
if m.err != nil {
return nil, m.err
}
return &AgentProfileInfo{
ProfileID: profileID,
ProfileName: "Test Profile",
@@ -43,7 +50,9 @@ func TestStartAgentProcess_NonPassthrough_NoAgentctl(t *testing.T) {
SessionID: "sess-1",
AgentProfileID: "profile-1",
}
mgr.executionStore.Add(execution)
if err := mgr.executionStore.Add(execution); err != nil {
t.Fatalf("seed execution: %v", err)
}
err := mgr.StartAgentProcess(context.Background(), "exec-1")
if err == nil {
@@ -62,9 +71,12 @@ func TestStartAgentProcess_Passthrough_NotResumed(t *testing.T) {
ID: "exec-1",
SessionID: "sess-1",
AgentProfileID: "profile-1",
IsPassthrough: true,
isResumedSession: false,
}
mgr.executionStore.Add(execution)
if err := mgr.executionStore.Add(execution); err != nil {
t.Fatalf("seed execution: %v", err)
}
err := mgr.StartAgentProcess(context.Background(), "exec-1")
if err == nil {
@@ -84,9 +96,12 @@ func TestStartAgentProcess_Passthrough_Resumed(t *testing.T) {
ID: "exec-1",
SessionID: "sess-1",
AgentProfileID: "profile-1",
IsPassthrough: true,
isResumedSession: true,
}
mgr.executionStore.Add(execution)
if err := mgr.executionStore.Add(execution); err != nil {
t.Fatalf("seed execution: %v", err)
}
err := mgr.StartAgentProcess(context.Background(), "exec-1")
if err == nil {
@@ -102,3 +117,147 @@ func TestStartAgentProcess_Passthrough_Resumed(t *testing.T) {
t.Errorf("expected ResumePassthroughSession path (no 'for passthrough mode' suffix), got: %v", err)
}
}
// A session created in agent (ACP) mode must keep using the ACP launch path
// even after its profile has been toggled to CLIPassthrough — the
// session-snapshot wins so existing sessions don't get stranded.
func TestStartAgentProcess_AgentSession_IgnoresProfileToggleToPassthrough(t *testing.T) {
mgr := newTestManager()
// Profile currently advertises passthrough — simulates the post-toggle state.
mgr.profileResolver = &mockAgentProfileResolver{cliPassthrough: true}
execution := &AgentExecution{
ID: "exec-1",
SessionID: "sess-1",
AgentProfileID: "profile-1",
// Session snapshot: false (session was created when profile was ACP).
IsPassthrough: false,
}
if err := mgr.executionStore.Add(execution); err != nil {
t.Fatalf("seed execution: %v", err)
}
err := mgr.StartAgentProcess(context.Background(), "exec-1")
if err == nil {
t.Fatal("expected error (no agentctl client)")
}
// We must hit the ACP path, which errors on the missing agentctl client.
// Passthrough errors look like "interactive runner not available [...]"
// — seeing that here would mean the snapshot was ignored.
if !strings.Contains(err.Error(), "no agentctl client") {
t.Errorf("expected ACP path to fail on missing agentctl client, got: %v", err)
}
}
// Mirror of the bug fix in the opposite direction: a session created in
// passthrough mode must keep using the passthrough path even if the profile
// is later toggled back to ACP.
func TestStartAgentProcess_PassthroughSession_IgnoresProfileToggleToAgent(t *testing.T) {
mgr := newTestManager()
// Profile currently advertises ACP — simulates a toggle away from passthrough.
mgr.profileResolver = &mockAgentProfileResolver{cliPassthrough: false}
execution := &AgentExecution{
ID: "exec-1",
SessionID: "sess-1",
AgentProfileID: "profile-1",
// Session snapshot: true (session was created when profile was passthrough).
IsPassthrough: true,
}
if err := mgr.executionStore.Add(execution); err != nil {
t.Fatalf("seed execution: %v", err)
}
err := mgr.StartAgentProcess(context.Background(), "exec-1")
if err == nil {
t.Fatal("expected error (no interactive runner)")
}
if !strings.Contains(err.Error(), "interactive runner not available") {
t.Errorf("expected passthrough path to fail on missing interactive runner, got: %v", err)
}
}
// When ResolveProfile errors on a passthrough resume, the routing decision
// must still honor the snapshot and stay on the passthrough branch. The
// downstream command builder may then surface the resolve error explicitly —
// what matters is that we do NOT silently fall through to the ACP path (the
// bug that would otherwise strand the session in the wrong launch mode).
func TestStartAgentProcess_PassthroughResume_SurvivesProfileResolveError(t *testing.T) {
mgr := newTestManager()
mgr.profileResolver = &mockAgentProfileResolver{err: errors.New("transient DB error")}
execution := &AgentExecution{
ID: "exec-1",
SessionID: "sess-1",
AgentProfileID: "profile-1",
IsPassthrough: true,
isResumedSession: true,
}
if err := mgr.executionStore.Add(execution); err != nil {
t.Fatalf("seed execution: %v", err)
}
err := mgr.StartAgentProcess(context.Background(), "exec-1")
if err == nil {
t.Fatal("expected error from the passthrough branch")
}
// ACP-path "no agentctl client" error would mean the snapshot was
// ignored and routing silently picked the wrong branch.
if strings.Contains(err.Error(), "no agentctl client") {
t.Errorf("snapshot must keep us on the passthrough branch, got ACP error: %v", err)
}
}
// A fresh passthrough launch (not a resume) needs the profile for command
// building, so a profile-resolve error must surface as an explicit error
// rather than silently falling through to ACP.
func TestStartAgentProcess_FreshPassthrough_SurfacesProfileResolveError(t *testing.T) {
mgr := newTestManager()
mgr.profileResolver = &mockAgentProfileResolver{err: errors.New("transient DB error")}
execution := &AgentExecution{
ID: "exec-1",
SessionID: "sess-1",
AgentProfileID: "profile-1",
IsPassthrough: true,
}
if err := mgr.executionStore.Add(execution); err != nil {
t.Fatalf("seed execution: %v", err)
}
err := mgr.StartAgentProcess(context.Background(), "exec-1")
if err == nil {
t.Fatal("expected profile-resolve error to surface")
}
if !strings.Contains(err.Error(), "resolve profile") {
t.Errorf("expected resolve-profile error, got: %v", err)
}
if strings.Contains(err.Error(), "agentctl client") {
t.Errorf("snapshot must keep us on the passthrough branch, got ACP error: %v", err)
}
}
// Sessionless launches (e.g. the legacy controller.LaunchAgent path that
// doesn't carry a SessionID) still fall back to live profile resolution so
// first-time launches reflect the current mode.
func TestStartAgentProcess_NoSession_FallsBackToLiveProfile(t *testing.T) {
mgr := newTestManager()
mgr.profileResolver = &mockAgentProfileResolver{cliPassthrough: true}
execution := &AgentExecution{
ID: "exec-1",
AgentProfileID: "profile-1",
// No SessionID, no snapshot → use live profile state.
}
if err := mgr.executionStore.Add(execution); err != nil {
t.Fatalf("seed execution: %v", err)
}
err := mgr.StartAgentProcess(context.Background(), "exec-1")
if err == nil {
t.Fatal("expected error (no interactive runner)")
}
if !strings.Contains(err.Error(), "interactive runner not available") {
t.Errorf("expected passthrough path via live fallback, got: %v", err)
}
}
@@ -59,6 +59,13 @@ type AgentExecution struct {
standaloneInstanceID string // Instance ID in standalone agentctl
standalonePort int // Port of the standalone execution
// IsPassthrough captures the session's mode as decided at session-creation
// time (TaskSession.IsPassthrough snapshot). StartAgentProcess uses this
// instead of re-resolving the live profile so a profile that toggles
// CLIPassthrough after the session was created cannot strand existing
// sessions in the wrong launch path.
IsPassthrough bool
// Passthrough mode info (CLI passthrough without ACP)
PassthroughProcessID string // Process ID in the interactive runner (empty if not in passthrough mode)
PassthroughStartedAt time.Time // When the current passthrough process was launched; used to detect fast-fail exits and skip auto-restart loops
@@ -335,6 +342,15 @@ type LaunchRequest struct {
// Non-ephemeral tasks without a workspace path will not receive a fallback directory.
IsEphemeral bool
// IsPassthrough is the session's mode snapshot taken when the session was
// created (TaskSession.IsPassthrough). When the launch request originates
// from an existing session, this is the source of truth for the launch
// path so a profile that toggles CLIPassthrough after the session was
// created does not strand the session in the wrong mode. Non-session
// launches (e.g. the low-level controller.LaunchAgent path) leave this
// false and fall back to live profile resolution.
IsPassthrough bool
// Executor configuration - determines which runtime to use
ExecutorType string // Executor type (e.g., "local", "worktree", "local_docker") - determines runtime
ExecutorConfig map[string]string // Executor config (docker_host, git_token, etc.)
@@ -261,6 +261,14 @@ type LaunchAgentRequest struct {
IsEphemeral bool // Ephemeral task (quick chat) — enables fallback workspace creation
WorkspacePath string // Optional host folder for repo-less tasks (overrides scratch fallback)
// IsPassthrough is the session's mode snapshot (TaskSession.IsPassthrough)
// at session-creation time. Forwarded to the lifecycle manager so
// StartAgentProcess routes to the passthrough vs ACP path based on the
// session's original mode, not on live profile state — preventing
// existing sessions from getting stranded when a profile's
// CLIPassthrough flag is toggled after the session was created.
IsPassthrough bool
// Setup script from executor profile (runs in execution environment before agent starts)
SetupScript string
@@ -613,6 +613,7 @@ func (e *Executor) buildLaunchAgentRequest(ctx context.Context, task *v1.Task, s
SessionID: sessionID,
TaskEnvironmentID: session.TaskEnvironmentID,
IsEphemeral: task.IsEphemeral,
IsPassthrough: session.IsPassthrough,
WorkspacePath: session.WorkspacePath,
}
@@ -295,6 +295,7 @@ func (e *Executor) buildSwitchModelRequest(ctx context.Context, task *models.Tas
ExecutorType: execConfig.ExecutorType,
Metadata: execConfig.Metadata,
IsEphemeral: task.IsEphemeral,
IsPassthrough: session.IsPassthrough,
TaskEnvironmentID: session.TaskEnvironmentID,
}
@@ -500,6 +500,7 @@ func (e *Executor) buildResumeRequest(ctx context.Context, task *v1.Task, sessio
TaskDescription: task.Description,
Priority: task.Priority,
IsEphemeral: task.IsEphemeral,
IsPassthrough: session.IsPassthrough,
TaskEnvironmentID: session.TaskEnvironmentID,
}
@@ -229,6 +229,51 @@ func TestResumeSession_CancelledStateForceCleansUpStaleState(t *testing.T) {
}
}
// TestResumeSession_PropagatesIsPassthrough verifies the session's IsPassthrough
// snapshot taken at session-creation time is carried through the resume request
// to the lifecycle manager, so a profile that toggles CLIPassthrough after the
// session was created cannot strand existing sessions in the wrong launch path.
func TestResumeSession_PropagatesIsPassthrough(t *testing.T) {
cases := []struct {
name string
sessionIsPasstru bool
}{
{name: "agent_session_keeps_acp", sessionIsPasstru: false},
{name: "passthrough_session_keeps_passthrough", sessionIsPasstru: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
repo := newMockRepository()
setupLiveResumeTestFixture(repo)
repo.sessions["sess-1"].IsPassthrough = tc.sessionIsPasstru
var capturedReq *LaunchAgentRequest
agentMgr := &mockAgentManager{
launchAgentFunc: func(_ context.Context, req *LaunchAgentRequest) (*LaunchAgentResponse, error) {
capturedReq = req
return &LaunchAgentResponse{
AgentExecutionID: "exec-new",
Status: v1.AgentStatusStarting,
}, nil
},
isAgentRunningForSessionFunc: func(_ context.Context, _ string) bool { return false },
}
exec := newTestExecutor(t, agentMgr, repo)
if _, err := exec.ResumeSession(context.Background(), repo.sessions["sess-1"], true); err != nil {
t.Fatalf("expected resume success, got: %v", err)
}
if capturedReq == nil {
t.Fatal("expected LaunchAgent to be called with a request")
}
if capturedReq.IsPassthrough != tc.sessionIsPasstru {
t.Errorf("IsPassthrough = %v, want %v — without this the lifecycle manager would re-resolve live profile state and ignore the session's mode at creation time",
capturedReq.IsPassthrough, tc.sessionIsPasstru)
}
})
}
}
// TestResumeSession_PropagatesTaskEnvironmentID is a regression test for a
// post-restart bug where `buildResumeRequest` did not copy
// `session.TaskEnvironmentID` onto the LaunchAgentRequest. The lifecycle's
@@ -222,6 +222,65 @@ func TestLaunchPreparedSession_Success(t *testing.T) {
}
}
// TestLaunchPreparedSession_PropagatesIsPassthrough mirrors
// TestResumeSession_PropagatesIsPassthrough for the initial-launch path: the
// session's IsPassthrough snapshot must reach the LaunchAgentRequest so the
// lifecycle manager picks the right launch path. Without this guarantee, a
// profile that toggles CLIPassthrough after the session was prepared would
// re-route the session to the wrong mode at start time.
func TestLaunchPreparedSession_PropagatesIsPassthrough(t *testing.T) {
cases := []struct {
name string
sessionIsPasstru bool
}{
{name: "agent_session_keeps_acp", sessionIsPasstru: false},
{name: "passthrough_session_keeps_passthrough", sessionIsPasstru: true},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
repo := newMockRepository()
session := &models.TaskSession{
ID: "session-pt",
TaskID: "task-pt",
AgentProfileID: "profile-pt",
IsPassthrough: tc.sessionIsPasstru,
State: models.TaskSessionStateCreated,
StartedAt: time.Now(),
UpdatedAt: time.Now(),
}
repo.sessions[session.ID] = session
var capturedReq *LaunchAgentRequest
agentManager := &mockAgentManager{
launchAgentFunc: func(_ context.Context, req *LaunchAgentRequest) (*LaunchAgentResponse, error) {
capturedReq = req
return &LaunchAgentResponse{
AgentExecutionID: "exec-pt",
Status: v1.AgentStatusStarting,
}, nil
},
}
exec := newTestExecutor(t, agentManager, repo)
task := &v1.Task{ID: "task-pt", WorkspaceID: "ws-pt", Title: "passthrough test"}
if _, err := exec.LaunchPreparedSession(context.Background(), task, session.ID, LaunchOptions{
AgentProfileID: "profile-pt",
Prompt: "go",
StartAgent: true,
}); err != nil {
t.Fatalf("LaunchPreparedSession: %v", err)
}
if capturedReq == nil {
t.Fatal("expected LaunchAgent to be called")
}
if capturedReq.IsPassthrough != tc.sessionIsPasstru {
t.Errorf("IsPassthrough = %v, want %v — without this the lifecycle manager would re-resolve live profile state and ignore the session's mode at creation time",
capturedReq.IsPassthrough, tc.sessionIsPasstru)
}
})
}
}
func TestAssignLaunchTaskEnvironmentID(t *testing.T) {
t.Run("reuses existing task environment", func(t *testing.T) {
session := &models.TaskSession{ID: "session-1"}