From f39e7b06ca6469eae807ab7caf5a74b0fafa9392 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Salavisa?= Date: Thu, 21 May 2026 23:39:23 +0100 Subject: [PATCH] fix(agent): honor session passthrough snapshot when starting agent process (#1003) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 * 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 * 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 * 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 * 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 --------- Co-authored-by: Kandev Agent Co-authored-by: Claude Opus 4.7 --- apps/backend/cmd/kandev/adapters.go | 1 + .../agent/runtime/lifecycle/manager_launch.go | 2 + .../runtime/lifecycle/manager_startup.go | 81 +++++++-- .../runtime/lifecycle/manager_startup_test.go | 165 +++++++++++++++++- .../internal/agent/runtime/lifecycle/types.go | 16 ++ .../orchestrator/executor/executor.go | 8 + .../orchestrator/executor/executor_execute.go | 1 + .../executor/executor_interaction.go | 1 + .../orchestrator/executor/executor_resume.go | 1 + .../executor/executor_resume_test.go | 45 +++++ .../orchestrator/executor/executor_test.go | 59 +++++++ 11 files changed, 366 insertions(+), 14 deletions(-) diff --git a/apps/backend/cmd/kandev/adapters.go b/apps/backend/cmd/kandev/adapters.go index b279d4efa6..78071c0317 100644 --- a/apps/backend/cmd/kandev/adapters.go +++ b/apps/backend/cmd/kandev/adapters.go @@ -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, diff --git a/apps/backend/internal/agent/runtime/lifecycle/manager_launch.go b/apps/backend/internal/agent/runtime/lifecycle/manager_launch.go index b5b53b15d7..7a5dabacec 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/manager_launch.go +++ b/apps/backend/internal/agent/runtime/lifecycle/manager_launch.go @@ -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_ diff --git a/apps/backend/internal/agent/runtime/lifecycle/manager_startup.go b/apps/backend/internal/agent/runtime/lifecycle/manager_startup.go index 83e9f30779..300614f0d5 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/manager_startup.go +++ b/apps/backend/internal/agent/runtime/lifecycle/manager_startup.go @@ -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 { diff --git a/apps/backend/internal/agent/runtime/lifecycle/manager_startup_test.go b/apps/backend/internal/agent/runtime/lifecycle/manager_startup_test.go index e1801adc56..2932c78d9e 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/manager_startup_test.go +++ b/apps/backend/internal/agent/runtime/lifecycle/manager_startup_test.go @@ -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) + } +} diff --git a/apps/backend/internal/agent/runtime/lifecycle/types.go b/apps/backend/internal/agent/runtime/lifecycle/types.go index a610ef8337..b0e329726b 100644 --- a/apps/backend/internal/agent/runtime/lifecycle/types.go +++ b/apps/backend/internal/agent/runtime/lifecycle/types.go @@ -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.) diff --git a/apps/backend/internal/orchestrator/executor/executor.go b/apps/backend/internal/orchestrator/executor/executor.go index 63e8a1ac92..65cd1b11d8 100644 --- a/apps/backend/internal/orchestrator/executor/executor.go +++ b/apps/backend/internal/orchestrator/executor/executor.go @@ -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 diff --git a/apps/backend/internal/orchestrator/executor/executor_execute.go b/apps/backend/internal/orchestrator/executor/executor_execute.go index 1f02d43dd1..cc0fa956d5 100644 --- a/apps/backend/internal/orchestrator/executor/executor_execute.go +++ b/apps/backend/internal/orchestrator/executor/executor_execute.go @@ -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, } diff --git a/apps/backend/internal/orchestrator/executor/executor_interaction.go b/apps/backend/internal/orchestrator/executor/executor_interaction.go index 775511724d..3f2e85dd01 100644 --- a/apps/backend/internal/orchestrator/executor/executor_interaction.go +++ b/apps/backend/internal/orchestrator/executor/executor_interaction.go @@ -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, } diff --git a/apps/backend/internal/orchestrator/executor/executor_resume.go b/apps/backend/internal/orchestrator/executor/executor_resume.go index cb309f3b23..021d08affe 100644 --- a/apps/backend/internal/orchestrator/executor/executor_resume.go +++ b/apps/backend/internal/orchestrator/executor/executor_resume.go @@ -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, } diff --git a/apps/backend/internal/orchestrator/executor/executor_resume_test.go b/apps/backend/internal/orchestrator/executor/executor_resume_test.go index c245225f2f..31463b8366 100644 --- a/apps/backend/internal/orchestrator/executor/executor_resume_test.go +++ b/apps/backend/internal/orchestrator/executor/executor_resume_test.go @@ -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 diff --git a/apps/backend/internal/orchestrator/executor/executor_test.go b/apps/backend/internal/orchestrator/executor/executor_test.go index 38a6c2736e..52b393431f 100644 --- a/apps/backend/internal/orchestrator/executor/executor_test.go +++ b/apps/backend/internal/orchestrator/executor/executor_test.go @@ -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"}