feat(cli-mode): route Preview chat input through PTY stdin in passthrough sessions

Branch Executor.Prompt on lifecycle.Manager.IsPassthroughSession so that
follow-up prompts from any UI surface (the kanban Preview screen, mobile
session view, etc.) reach the running CLI agent via PTY stdin instead of
silently falling through to the ACP path. WritePassthroughStdin failures
propagate so Service.handlePromptError reverts session state and surfaces
the error; MarkPassthroughRunning failures are non-fatal because the data
is already in the PTY.

Closes the backend half of #989; the Preview-side UI compose box ships
in a follow-up commit.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
Kandev Agent
2026-05-23 15:45:10 +01:00
parent 7771155c8f
commit 85edb4546b
3 changed files with 233 additions and 3 deletions
@@ -117,6 +117,13 @@ func (e *Executor) StopByTaskID(ctx context.Context, taskID string, reason strin
return nil
}
// passthroughSubmitSequence is appended to a passthrough prompt before writing
// to PTY stdin. "\r" submits the current line in every TUI agent CLI currently
// supported in passthrough mode (Claude, Codex, OpenCode, Cursor, Auggie, …).
// If a future agent needs a different sequence, lift this into a per-agent
// PassthroughConfig field — see the plan for issue #989.
const passthroughSubmitSequence = "\r"
// Prompt sends a follow-up prompt to a running agent for a task
// Returns PromptResult indicating if the agent needs input
// Attachments (images) are passed to the agent if provided
@@ -147,6 +154,14 @@ func (e *Executor) Prompt(ctx context.Context, taskID, sessionID string, prompt
zap.Int("attachments_count", len(attachments)),
zap.Bool("dispatch_only", dispatchOnly))
// Passthrough sessions don't speak ACP — route the prompt through PTY stdin
// so the CLI agent actually receives it. The Preview-screen chat input (and
// any other surface that calls message.add against a passthrough session)
// reaches this branch via Service.PromptTask → Executor.Prompt.
if e.agentManager.IsPassthroughSession(ctx, sessionID) {
return e.promptPassthrough(ctx, taskID, sessionID, prompt)
}
result, err := e.agentManager.PromptAgent(ctx, executionID, prompt, attachments, dispatchOnly)
if err != nil {
if errors.Is(err, lifecycle.ErrExecutionNotFound) {
@@ -157,6 +172,31 @@ func (e *Executor) Prompt(ctx context.Context, taskID, sessionID string, prompt
return result, nil
}
// promptPassthrough delivers a user prompt to a passthrough (PTY) agent session.
// Attachments are intentionally ignored — passthrough mode has no protocol channel
// for them; the typed text reaches the CLI agent as if the user typed it into
// xterm and pressed Enter.
//
// A WritePassthroughStdin failure (no live PTY, runner unavailable) is returned
// as an error so Service.handlePromptError can revert session state and surface
// the failure to the user. A MarkPassthroughRunning failure is non-fatal — the
// data is already in the PTY; only the AgentRunning event is missed.
func (e *Executor) promptPassthrough(ctx context.Context, taskID, sessionID, prompt string) (*PromptResult, error) {
if prompt == "" {
return nil, fmt.Errorf("passthrough prompt cannot be empty (attachments are not supported in CLI passthrough mode)")
}
if err := e.agentManager.WritePassthroughStdin(ctx, sessionID, prompt+passthroughSubmitSequence); err != nil {
return nil, fmt.Errorf("failed to write to passthrough stdin: %w", err)
}
if err := e.agentManager.MarkPassthroughRunning(sessionID); err != nil {
e.logger.Warn("failed to mark passthrough as running after prompt; data already in PTY",
zap.String("task_id", taskID),
zap.String("session_id", sessionID),
zap.Error(err))
}
return &PromptResult{StopReason: "passthrough_dispatched"}, nil
}
// SwitchModel switches the model for a running session. It first attempts an in-place switch
// via ACP session/set_model (instant, no process restart). If the agent doesn't support
// in-place switching, it falls back to stopping and restarting the agent with the new model.
@@ -24,9 +24,22 @@ type mockAgentManager struct {
getExecutionIDForSessionFunc func(ctx context.Context, sessionID string) (string, error)
isAgentRunningForSessionFunc func(ctx context.Context, sessionID string) bool
cleanupStaleExecutionFunc func(ctx context.Context, sessionID string) error
promptAgentFunc func(ctx context.Context, agentExecutionID, prompt string, attachments []v1.MessageAttachment, dispatchOnly bool) (*PromptResult, error)
isPassthroughSessionFunc func(ctx context.Context, sessionID string) bool
writePassthroughStdinFunc func(ctx context.Context, sessionID, data string) error
markPassthroughRunningFunc func(sessionID string) error
launchAgentCallCount int
cleanupStaleExecutionCallCount int
isAgentRunningForSessionCallArgs []string
promptAgentCallCount int
writePassthroughStdinCalls []passthroughStdinCall
markPassthroughRunningCalls []string
}
// passthroughStdinCall captures one invocation of WritePassthroughStdin for assertions.
type passthroughStdinCall struct {
SessionID string
Data string
}
func (m *mockAgentManager) LaunchAgent(ctx context.Context, req *LaunchAgentRequest) (*LaunchAgentResponse, error) {
@@ -74,7 +87,11 @@ func (m *mockAgentManager) StopAgentWithReason(ctx context.Context, agentExecuti
return m.StopAgent(ctx, agentExecutionID, force)
}
func (m *mockAgentManager) PromptAgent(ctx context.Context, agentExecutionID string, prompt string, _ []v1.MessageAttachment, _ bool) (*PromptResult, error) {
func (m *mockAgentManager) PromptAgent(ctx context.Context, agentExecutionID string, prompt string, attachments []v1.MessageAttachment, dispatchOnly bool) (*PromptResult, error) {
m.promptAgentCallCount++
if m.promptAgentFunc != nil {
return m.promptAgentFunc(ctx, agentExecutionID, prompt, attachments, dispatchOnly)
}
return nil, nil
}
@@ -110,12 +127,26 @@ func (m *mockAgentManager) GetSessionAuthMethods(_ string) []streams.AuthMethodI
return nil
}
func (m *mockAgentManager) IsPassthroughSession(ctx context.Context, sessionID string) bool {
if m.isPassthroughSessionFunc != nil {
return m.isPassthroughSessionFunc(ctx, sessionID)
}
return false
}
func (m *mockAgentManager) WritePassthroughStdin(_ context.Context, _ string, _ string) error {
func (m *mockAgentManager) WritePassthroughStdin(ctx context.Context, sessionID string, data string) error {
m.writePassthroughStdinCalls = append(m.writePassthroughStdinCalls, passthroughStdinCall{
SessionID: sessionID,
Data: data,
})
if m.writePassthroughStdinFunc != nil {
return m.writePassthroughStdinFunc(ctx, sessionID, data)
}
return nil
}
func (m *mockAgentManager) MarkPassthroughRunning(_ string) error {
func (m *mockAgentManager) MarkPassthroughRunning(sessionID string) error {
m.markPassthroughRunningCalls = append(m.markPassthroughRunningCalls, sessionID)
if m.markPassthroughRunningFunc != nil {
return m.markPassthroughRunningFunc(sessionID)
}
return nil
}
@@ -0,0 +1,159 @@
package executor
import (
"context"
"errors"
"strings"
"testing"
"github.com/kandev/kandev/internal/task/models"
)
// seedPassthroughSession installs a task + session into the mock repo and wires
// the agent manager to claim a valid execution ID, so Executor.Prompt reaches
// the IsPassthroughSession branch instead of bailing on lookup errors.
func seedPassthroughSession(t *testing.T, repo *mockRepository, agentManager *mockAgentManager, taskID, sessionID, execID string) {
t.Helper()
repo.sessions[sessionID] = &models.TaskSession{
ID: sessionID,
TaskID: taskID,
State: models.TaskSessionStateWaitingForInput,
}
agentManager.getExecutionIDForSessionFunc = func(_ context.Context, sid string) (string, error) {
if sid != sessionID {
t.Fatalf("unexpected session lookup: got %q want %q", sid, sessionID)
}
return execID, nil
}
}
func TestExecutor_Prompt_PassthroughWritesStdin(t *testing.T) {
repo := newMockRepository()
agentManager := &mockAgentManager{
isPassthroughSessionFunc: func(_ context.Context, _ string) bool { return true },
}
seedPassthroughSession(t, repo, agentManager, "task-1", "sess-1", "exec-1")
exec := newTestExecutor(t, agentManager, repo)
result, err := exec.Prompt(context.Background(), "task-1", "sess-1", "hello agent", nil, false)
if err != nil {
t.Fatalf("Prompt returned error: %v", err)
}
if result == nil || result.StopReason != "passthrough_dispatched" {
t.Fatalf("expected passthrough_dispatched result, got %+v", result)
}
if got := len(agentManager.writePassthroughStdinCalls); got != 1 {
t.Fatalf("expected 1 WritePassthroughStdin call, got %d", got)
}
call := agentManager.writePassthroughStdinCalls[0]
if call.SessionID != "sess-1" {
t.Errorf("WritePassthroughStdin session = %q, want sess-1", call.SessionID)
}
wantData := "hello agent" + passthroughSubmitSequence
if call.Data != wantData {
t.Errorf("WritePassthroughStdin data = %q, want %q", call.Data, wantData)
}
if !strings.HasSuffix(call.Data, "\r") {
t.Errorf("expected submit sequence suffix \\r, got %q", call.Data)
}
if got := len(agentManager.markPassthroughRunningCalls); got != 1 {
t.Fatalf("expected 1 MarkPassthroughRunning call, got %d", got)
}
if agentManager.markPassthroughRunningCalls[0] != "sess-1" {
t.Errorf("MarkPassthroughRunning session = %q, want sess-1", agentManager.markPassthroughRunningCalls[0])
}
if agentManager.promptAgentCallCount != 0 {
t.Errorf("PromptAgent must not be called for passthrough sessions; call count = %d", agentManager.promptAgentCallCount)
}
}
func TestExecutor_Prompt_PassthroughWriteErrorReturnsError(t *testing.T) {
repo := newMockRepository()
writeErr := errors.New("session sess-1 is not in passthrough mode")
agentManager := &mockAgentManager{
isPassthroughSessionFunc: func(_ context.Context, _ string) bool { return true },
writePassthroughStdinFunc: func(_ context.Context, _ string, _ string) error { return writeErr },
}
seedPassthroughSession(t, repo, agentManager, "task-1", "sess-1", "exec-1")
exec := newTestExecutor(t, agentManager, repo)
result, err := exec.Prompt(context.Background(), "task-1", "sess-1", "hi", nil, false)
if err == nil {
t.Fatalf("expected error from Prompt, got nil (result=%+v)", result)
}
if !errors.Is(err, writeErr) {
t.Errorf("expected wrapped writeErr in chain, got %v", err)
}
if result != nil {
t.Errorf("expected nil result on error, got %+v", result)
}
// MarkPassthroughRunning must not be called when the write fails — otherwise
// the UI would flash "running" for a prompt the agent never received.
if got := len(agentManager.markPassthroughRunningCalls); got != 0 {
t.Errorf("MarkPassthroughRunning must not be called when stdin write fails; got %d call(s)", got)
}
}
func TestExecutor_Prompt_PassthroughMarkRunningErrorIsNonFatal(t *testing.T) {
repo := newMockRepository()
agentManager := &mockAgentManager{
isPassthroughSessionFunc: func(_ context.Context, _ string) bool { return true },
markPassthroughRunningFunc: func(_ string) error { return errors.New("status flip failed") },
}
seedPassthroughSession(t, repo, agentManager, "task-1", "sess-1", "exec-1")
exec := newTestExecutor(t, agentManager, repo)
result, err := exec.Prompt(context.Background(), "task-1", "sess-1", "hi", nil, false)
if err != nil {
t.Fatalf("expected nil error when MarkPassthroughRunning fails (data is already in PTY), got %v", err)
}
if result == nil || result.StopReason != "passthrough_dispatched" {
t.Fatalf("expected passthrough_dispatched result, got %+v", result)
}
if got := len(agentManager.writePassthroughStdinCalls); got != 1 {
t.Errorf("expected the stdin write to have happened exactly once, got %d", got)
}
}
func TestExecutor_Prompt_PassthroughEmptyPromptReturnsError(t *testing.T) {
repo := newMockRepository()
agentManager := &mockAgentManager{
isPassthroughSessionFunc: func(_ context.Context, _ string) bool { return true },
}
seedPassthroughSession(t, repo, agentManager, "task-1", "sess-1", "exec-1")
exec := newTestExecutor(t, agentManager, repo)
_, err := exec.Prompt(context.Background(), "task-1", "sess-1", "", nil, false)
if err == nil {
t.Fatal("expected error for empty passthrough prompt, got nil")
}
if got := len(agentManager.writePassthroughStdinCalls); got != 0 {
t.Errorf("WritePassthroughStdin must not be called for empty prompts; got %d call(s)", got)
}
}
func TestExecutor_Prompt_ACPPathUnchanged(t *testing.T) {
repo := newMockRepository()
agentManager := &mockAgentManager{
// IsPassthroughSession defaults to false; explicit false here for clarity.
isPassthroughSessionFunc: func(_ context.Context, _ string) bool { return false },
}
seedPassthroughSession(t, repo, agentManager, "task-1", "sess-1", "exec-1")
exec := newTestExecutor(t, agentManager, repo)
if _, err := exec.Prompt(context.Background(), "task-1", "sess-1", "hello", nil, false); err != nil {
t.Fatalf("Prompt returned error: %v", err)
}
if agentManager.promptAgentCallCount != 1 {
t.Errorf("expected PromptAgent to be called once, got %d", agentManager.promptAgentCallCount)
}
if got := len(agentManager.writePassthroughStdinCalls); got != 0 {
t.Errorf("WritePassthroughStdin must not be called in ACP mode; got %d", got)
}
if got := len(agentManager.markPassthroughRunningCalls); got != 0 {
t.Errorf("MarkPassthroughRunning must not be called in ACP mode; got %d", got)
}
}