feat(cli-mode): auto-inject task prompt + dynamic submit sequence + passthrough UX fixes (#923)
This commit is contained in:
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/agents"
|
||||
"github.com/kandev/kandev/internal/agent/registry"
|
||||
"github.com/kandev/kandev/internal/agent/runtime/agentctl"
|
||||
"github.com/kandev/kandev/internal/agent/runtime/lifecycle"
|
||||
@@ -360,6 +361,11 @@ func (a *lifecycleAdapter) WritePassthroughStdin(ctx context.Context, sessionID
|
||||
return a.mgr.WritePassthroughStdin(ctx, sessionID, data)
|
||||
}
|
||||
|
||||
// ResolvePassthroughConfig returns the resolved PassthroughConfig for a session's agent.
|
||||
func (a *lifecycleAdapter) ResolvePassthroughConfig(ctx context.Context, sessionID string) (agents.PassthroughConfig, error) {
|
||||
return a.mgr.ResolvePassthroughConfig(ctx, sessionID)
|
||||
}
|
||||
|
||||
func (a *lifecycleAdapter) MarkPassthroughRunning(sessionID string) error {
|
||||
return a.mgr.MarkPassthroughRunning(sessionID)
|
||||
}
|
||||
|
||||
@@ -252,6 +252,25 @@ type PassthroughConfig struct {
|
||||
ResumeFlag Param // generic "continue last session" (e.g. NewParam("-c"), NewParam("--resume", "latest"))
|
||||
SessionResumeFlag Param // resume a specific session by ID (e.g. NewParam("--resume"))
|
||||
WaitForTerminal bool
|
||||
// AutoInjectPrompt enables writing the task description to the PTY stdin
|
||||
// after the first idle window. Default false preserves today's behavior.
|
||||
AutoInjectPrompt bool
|
||||
// SubmitSequence is appended after the prompt text when auto-injecting
|
||||
// and when routing chat-compose messages to the PTY. "\r" for most TUIs.
|
||||
// Empty inherits DefaultPassthroughSubmitSequence at PTY write sites.
|
||||
SubmitSequence string
|
||||
// DisableBracketedPaste sends prompt bytes verbatim (plus SubmitSequence).
|
||||
// Claude Code enables bracketed-paste *mode* (?2004h) in its Ink TUI; injecting
|
||||
// ESC[200~…ESC[201~ delimiters breaks input (nothing appears in the prompt).
|
||||
DisableBracketedPaste bool
|
||||
// SubmitDelay is the wait inserted before each non-first chunk when writing the
|
||||
// prompt+submit sequence to PTY stdin. Ink-based TUIs (Claude Code) detect a
|
||||
// "paste burst" when many stdin bytes arrive in one read and absorb the
|
||||
// trailing \r into the pasted content instead of dispatching it as Enter.
|
||||
// Splitting the prompt body from the submit byte with a small delay forces the
|
||||
// submit to arrive as a discrete keystroke. 0 disables (other TUIs handle one
|
||||
// atomic write fine).
|
||||
SubmitDelay time.Duration
|
||||
}
|
||||
|
||||
// DefaultBufferMaxBytes is the default maximum buffer size for passthrough mode (2 MB).
|
||||
|
||||
@@ -35,15 +35,24 @@ func NewClaudeACP() *ClaudeACP {
|
||||
StandardPassthrough: StandardPassthrough{
|
||||
PermSettings: emptyPermSettings,
|
||||
Cfg: PassthroughConfig{
|
||||
Supported: true,
|
||||
Label: "CLI Passthrough",
|
||||
Description: "Show terminal directly instead of chat interface",
|
||||
PassthroughCmd: NewCommand("npx", "-y", "@anthropic-ai/claude-code", "--verbose"),
|
||||
ModelFlag: NewParam("--model", "{model}"),
|
||||
IdleTimeout: 3 * time.Second,
|
||||
BufferMaxBytes: DefaultBufferMaxBytes,
|
||||
ResumeFlag: NewParam("-c"),
|
||||
SessionResumeFlag: NewParam("--resume"),
|
||||
Supported: true,
|
||||
Label: "CLI Passthrough",
|
||||
Description: "Show terminal directly instead of chat interface",
|
||||
PassthroughCmd: NewCommand("npx", "-y", "@anthropic-ai/claude-code", "--verbose"),
|
||||
ModelFlag: NewParam("--model", "{model}"),
|
||||
IdleTimeout: 3 * time.Second,
|
||||
BufferMaxBytes: DefaultBufferMaxBytes,
|
||||
ResumeFlag: NewParam("-c"),
|
||||
SessionResumeFlag: NewParam("--resume"),
|
||||
AutoInjectPrompt: true,
|
||||
SubmitSequence: "\r",
|
||||
DisableBracketedPaste: true,
|
||||
// Claude Code's Ink TUI coalesces multi-byte stdin reads into a
|
||||
// paste burst, absorbing trailing "\r" into the input rather than
|
||||
// dispatching Enter. A short delay before the submit byte forces
|
||||
// it to arrive as a discrete keystroke. 150ms is just over Ink's
|
||||
// paste-detection window and still feels instant to the user.
|
||||
SubmitDelay: 150 * time.Millisecond,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -30,18 +30,34 @@ type CodexACP struct {
|
||||
StandardPassthrough
|
||||
}
|
||||
|
||||
// codexPassthroughPermSettings maps profile toggles to @openai/codex CLI flags.
|
||||
// The legacy --full-auto flag was removed; auto_approve uses --ask-for-approval never.
|
||||
var codexPassthroughPermSettings = map[string]PermissionSetting{
|
||||
"auto_approve": {
|
||||
Supported: true,
|
||||
Default: true,
|
||||
Label: "Auto approve",
|
||||
Description: "Skip command approval prompts (--ask-for-approval never)",
|
||||
ApplyMethod: PermissionApplyMethodCLIFlag,
|
||||
CLIFlag: "--ask-for-approval",
|
||||
CLIFlagValue: "never",
|
||||
},
|
||||
}
|
||||
|
||||
func NewCodexACP() *CodexACP {
|
||||
return &CodexACP{
|
||||
StandardPassthrough: StandardPassthrough{
|
||||
PermSettings: emptyPermSettings,
|
||||
PermSettings: codexPassthroughPermSettings,
|
||||
Cfg: PassthroughConfig{
|
||||
Supported: true,
|
||||
Label: "CLI Passthrough",
|
||||
Description: "Show terminal directly instead of chat interface",
|
||||
PassthroughCmd: NewCommand("npx", "-y", "@openai/codex", "--full-auto"),
|
||||
ModelFlag: NewParam("--model", "{model}"),
|
||||
IdleTimeout: 3 * time.Second,
|
||||
BufferMaxBytes: DefaultBufferMaxBytes,
|
||||
Supported: true,
|
||||
Label: "CLI Passthrough",
|
||||
Description: "Show terminal directly instead of chat interface",
|
||||
PassthroughCmd: NewCommand("npx", "-y", "@openai/codex"),
|
||||
ModelFlag: NewParam("--model", "{model}"),
|
||||
IdleTimeout: 3 * time.Second,
|
||||
BufferMaxBytes: DefaultBufferMaxBytes,
|
||||
AutoInjectPrompt: true,
|
||||
SubmitSequence: "\r",
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -149,7 +165,7 @@ func (a *CodexACP) InstallScript() string {
|
||||
func (a *CodexACP) BillingType() usage.BillingType { return codexBillingType() }
|
||||
|
||||
func (a *CodexACP) PermissionSettings() map[string]PermissionSetting {
|
||||
return emptyPermSettings
|
||||
return codexPassthroughPermSettings
|
||||
}
|
||||
|
||||
// InferenceConfig returns configuration for one-shot inference using ACP.
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"slices"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCodexACP_PassthroughCmd_NoRemovedFullAutoFlag(t *testing.T) {
|
||||
pt := NewCodexACP().PassthroughConfig().PassthroughCmd.Args()
|
||||
want := []string{"npx", "-y", "@openai/codex"}
|
||||
if !slices.Equal(pt, want) {
|
||||
t.Fatalf("PassthroughCmd = %#v, want %#v", pt, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexACP_BuildPassthroughCommand_AutoApprove(t *testing.T) {
|
||||
cmd := NewCodexACP().BuildPassthroughCommand(PassthroughOptions{
|
||||
PermissionValues: map[string]bool{"auto_approve": true},
|
||||
})
|
||||
want := []string{"npx", "-y", "@openai/codex", "--ask-for-approval", "never"}
|
||||
if !slices.Equal(cmd.Args(), want) {
|
||||
t.Fatalf("argv = %#v, want %#v", cmd.Args(), want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexACP_BuildPassthroughCommand_AutoApproveDisabled(t *testing.T) {
|
||||
cmd := NewCodexACP().BuildPassthroughCommand(PassthroughOptions{
|
||||
PermissionValues: map[string]bool{"auto_approve": false},
|
||||
})
|
||||
want := []string{"npx", "-y", "@openai/codex"}
|
||||
if !slices.Equal(cmd.Args(), want) {
|
||||
t.Fatalf("argv = %#v, want %#v", cmd.Args(), want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
bracketedPasteStart = "\x1b[200~"
|
||||
bracketedPasteEnd = "\x1b[201~"
|
||||
)
|
||||
|
||||
// PassthroughStdinChunk is one PTY stdin write planned for a passthrough prompt.
|
||||
// DelayBefore is sleep applied before writing this chunk; it is zero on the first
|
||||
// chunk and inherits PassthroughConfig.SubmitDelay on subsequent chunks. Splitting
|
||||
// the prompt body from the submit byte with a delay defeats Ink-style paste-burst
|
||||
// detection in TUIs like Claude Code (see PassthroughConfig.SubmitDelay).
|
||||
type PassthroughStdinChunk struct {
|
||||
Data string
|
||||
DelayBefore time.Duration
|
||||
}
|
||||
|
||||
// PassthroughSubmitSequence returns the byte sequence to append after passthrough
|
||||
// stdin text. Empty SubmitSequence inherits DefaultPassthroughSubmitSequence ("\r").
|
||||
func PassthroughSubmitSequence(cfg PassthroughConfig) string {
|
||||
return EffectiveSubmitSequence(cfg.SubmitSequence)
|
||||
}
|
||||
|
||||
// BuildPassthroughPayload assembles the bytes for one atomic PTY stdin write.
|
||||
// Multi-line prompts use bracketed paste so embedded newlines are not treated as
|
||||
// premature Enter presses, unless DisableBracketedPaste is set (Claude Code).
|
||||
func BuildPassthroughPayload(prompt string, cfg PassthroughConfig) string {
|
||||
submit := PassthroughSubmitSequence(cfg)
|
||||
if cfg.DisableBracketedPaste || !strings.Contains(prompt, "\n") {
|
||||
return prompt + submit
|
||||
}
|
||||
return bracketedPasteStart + prompt + bracketedPasteEnd + submit
|
||||
}
|
||||
|
||||
// PlanPassthroughStdinChunks plans PTY stdin writes for a passthrough prompt.
|
||||
// When SubmitDelay > 0 (Claude path) the prompt body and submit byte are emitted
|
||||
// as two chunks with DelayBefore set on the submit chunk so it arrives as a
|
||||
// discrete keystroke. Otherwise a single atomic write is returned, preserving
|
||||
// today's behavior for TUIs that handle prompt+submit in one read (Cursor, Codex,
|
||||
// OpenCode).
|
||||
func PlanPassthroughStdinChunks(prompt string, cfg PassthroughConfig) []PassthroughStdinChunk {
|
||||
if cfg.SubmitDelay > 0 {
|
||||
body := prompt
|
||||
if !cfg.DisableBracketedPaste && strings.Contains(prompt, "\n") {
|
||||
body = bracketedPasteStart + prompt + bracketedPasteEnd
|
||||
}
|
||||
return []PassthroughStdinChunk{
|
||||
{Data: body},
|
||||
{Data: PassthroughSubmitSequence(cfg), DelayBefore: cfg.SubmitDelay},
|
||||
}
|
||||
}
|
||||
return []PassthroughStdinChunk{{Data: BuildPassthroughPayload(prompt, cfg)}}
|
||||
}
|
||||
|
||||
// PlanPassthroughStdinWrites is the legacy string-only view of PlanPassthroughStdinChunks.
|
||||
// Retained for tests and call sites that don't need to honor per-chunk delays.
|
||||
func PlanPassthroughStdinWrites(prompt string, cfg PassthroughConfig) []string {
|
||||
chunks := PlanPassthroughStdinChunks(prompt, cfg)
|
||||
out := make([]string, len(chunks))
|
||||
for i, c := range chunks {
|
||||
out[i] = c.Data
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
package agents
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestPlanPassthroughStdinWrites_SingleAtomicWrite(t *testing.T) {
|
||||
cfg := PassthroughConfig{SubmitSequence: "\r"}
|
||||
got := PlanPassthroughStdinWrites("line1\nline2", cfg)
|
||||
if len(got) != 1 {
|
||||
t.Fatalf("got %d chunks, want 1 atomic write: %#v", len(got), got)
|
||||
}
|
||||
want := "\x1b[200~line1\nline2\x1b[201~\r"
|
||||
if got[0] != want {
|
||||
t.Errorf("payload = %q, want %q", got[0], want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPlanPassthroughStdinWrites_SingleLine(t *testing.T) {
|
||||
cfg := PassthroughConfig{SubmitSequence: "\r"}
|
||||
got := PlanPassthroughStdinWrites("hello", cfg)
|
||||
if len(got) != 1 || got[0] != "hello\r" {
|
||||
t.Fatalf("got %#v, want [\"hello\\r\"]", got)
|
||||
}
|
||||
}
|
||||
|
||||
// Claude's PassthroughConfig sets SubmitDelay so the submit byte arrives as a
|
||||
// discrete keystroke (defeats Ink's paste-burst detection). Single-line and
|
||||
// multi-line prompts both emit body+submit as two chunks; the submit chunk
|
||||
// carries DelayBefore = SubmitDelay.
|
||||
func TestPlanPassthroughStdinChunks_ClaudeSplitsSubmit(t *testing.T) {
|
||||
cfg := NewClaudeACP().PassthroughConfig()
|
||||
if cfg.SubmitDelay <= 0 {
|
||||
t.Fatalf("Claude config must set SubmitDelay > 0 for paste-burst workaround, got %v", cfg.SubmitDelay)
|
||||
}
|
||||
|
||||
for _, prompt := range []string{"hello", "### Review Comments\n\n> fix"} {
|
||||
chunks := PlanPassthroughStdinChunks(prompt, cfg)
|
||||
if len(chunks) != 2 {
|
||||
t.Fatalf("prompt %q: got %d chunks, want 2 (body, submit): %#v", prompt, len(chunks), chunks)
|
||||
}
|
||||
if chunks[0].Data != prompt {
|
||||
t.Errorf("prompt %q: body chunk = %q, want verbatim prompt", prompt, chunks[0].Data)
|
||||
}
|
||||
if chunks[0].DelayBefore != 0 {
|
||||
t.Errorf("prompt %q: body chunk DelayBefore = %v, want 0", prompt, chunks[0].DelayBefore)
|
||||
}
|
||||
if chunks[1].Data != "\r" {
|
||||
t.Errorf("prompt %q: submit chunk = %q, want \\r", prompt, chunks[1].Data)
|
||||
}
|
||||
if chunks[1].DelayBefore != cfg.SubmitDelay {
|
||||
t.Errorf("prompt %q: submit DelayBefore = %v, want %v", prompt, chunks[1].DelayBefore, cfg.SubmitDelay)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Non-Claude TUIs (SubmitDelay == 0) keep the single-atomic-write semantics so we
|
||||
// don't accidentally regress Cursor/Codex/OpenCode by splitting their submit.
|
||||
func TestPlanPassthroughStdinChunks_AtomicWhenNoDelay(t *testing.T) {
|
||||
cfg := PassthroughConfig{SubmitSequence: "\r"}
|
||||
chunks := PlanPassthroughStdinChunks("hello", cfg)
|
||||
if len(chunks) != 1 {
|
||||
t.Fatalf("got %d chunks, want 1 atomic write: %#v", len(chunks), chunks)
|
||||
}
|
||||
if chunks[0].DelayBefore != 0 {
|
||||
t.Errorf("atomic chunk DelayBefore = %v, want 0", chunks[0].DelayBefore)
|
||||
}
|
||||
if chunks[0].Data != "hello\r" {
|
||||
t.Errorf("atomic chunk Data = %q, want \"hello\\r\"", chunks[0].Data)
|
||||
}
|
||||
}
|
||||
|
||||
// Sanity: a custom config with SubmitDelay set but no Claude-specific flags
|
||||
// also splits — the field is the lever, not the Claude struct identity.
|
||||
func TestPlanPassthroughStdinChunks_SubmitDelayDrivesSplit(t *testing.T) {
|
||||
cfg := PassthroughConfig{SubmitSequence: "\r", DisableBracketedPaste: true, SubmitDelay: 50 * time.Millisecond}
|
||||
chunks := PlanPassthroughStdinChunks("hi", cfg)
|
||||
if len(chunks) != 2 || chunks[1].DelayBefore != 50*time.Millisecond || chunks[1].Data != "\r" {
|
||||
t.Fatalf("expected split with 50ms delay before \\r, got %#v", chunks)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package agents
|
||||
|
||||
// DefaultPassthroughSubmitSequence is appended after PTY prompt text when an agent
|
||||
// omits PassthroughConfig.SubmitSequence. Most TUI CLIs expect carriage-return.
|
||||
const DefaultPassthroughSubmitSequence = "\r"
|
||||
|
||||
// EffectiveSubmitSequence returns the bytes to append after passthrough stdin text.
|
||||
// Agents that leave SubmitSequence empty inherit DefaultPassthroughSubmitSequence.
|
||||
func EffectiveSubmitSequence(seq string) string {
|
||||
if seq == "" {
|
||||
return DefaultPassthroughSubmitSequence
|
||||
}
|
||||
return seq
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package agents
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestEffectiveSubmitSequence(t *testing.T) {
|
||||
if got := EffectiveSubmitSequence(""); got != "\r" {
|
||||
t.Errorf("empty = %q, want \\r", got)
|
||||
}
|
||||
if got := EffectiveSubmitSequence("\n"); got != "\n" {
|
||||
t.Errorf("explicit \\n = %q", got)
|
||||
}
|
||||
}
|
||||
@@ -372,12 +372,26 @@ var ErrCancelEscalated = errors.New("cancel escalated: agent did not acknowledge
|
||||
|
||||
// CancelAgentBySessionID cancels the current agent turn for a specific session.
|
||||
// Returns ErrNoExecutionForSession (wrapped) when no execution is tracked for the session.
|
||||
//
|
||||
// Passthrough sessions don't speak ACP — Ctrl-C (0x03) written to PTY stdin is
|
||||
// the only stop signal a TUI CLI understands. A write failure is non-fatal:
|
||||
// the caller still reconciles DB state so the UI unsticks even if the PTY is
|
||||
// already gone.
|
||||
func (m *Manager) CancelAgentBySessionID(ctx context.Context, sessionID string) error {
|
||||
execution, exists := m.executionStore.GetBySessionID(sessionID)
|
||||
if !exists {
|
||||
return fmt.Errorf("session %q: %w", sessionID, ErrNoExecutionForSession)
|
||||
}
|
||||
|
||||
if execution.PassthroughProcessID != "" {
|
||||
if err := m.WritePassthroughStdin(ctx, sessionID, "\x03"); err != nil {
|
||||
m.logger.Warn("failed to write Ctrl-C to passthrough stdin",
|
||||
zap.String("session_id", sessionID),
|
||||
zap.Error(err))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
return m.CancelAgent(ctx, execution.ID)
|
||||
}
|
||||
|
||||
|
||||
@@ -201,6 +201,19 @@ func (m *Manager) resolvePassthroughAgent(ctx context.Context, execution *AgentE
|
||||
}, nil
|
||||
}
|
||||
|
||||
// promptForPassthroughCommand returns the prompt that should be passed to
|
||||
// BuildPassthroughCommand. When the agent uses idle-based auto-inject and has
|
||||
// no PromptFlag, the prompt would otherwise be appended as a positional arg
|
||||
// (putting TUIs like Claude into non-interactive `-p` mode and exiting before
|
||||
// auto-inject fires). In that case we return "" so the prompt is delivered via
|
||||
// PTY stdin in autoInjectInitialPrompt.
|
||||
func promptForPassthroughCommand(pt agents.PassthroughConfig, taskDescription string) string {
|
||||
if pt.AutoInjectPrompt && pt.PromptFlag.IsEmpty() {
|
||||
return ""
|
||||
}
|
||||
return taskDescription
|
||||
}
|
||||
|
||||
// passthroughAgentCommand validates passthrough support and builds the command for a passthrough session.
|
||||
// Returns the PassthroughAgent, PassthroughConfig, RuntimeConfig pointer, command, and any error.
|
||||
func (m *Manager) passthroughAgentCommand(execution *AgentExecution, profileInfo *AgentProfileInfo) (agents.PassthroughAgent, agents.PassthroughConfig, *agents.RuntimeConfig, agents.Command, error) {
|
||||
@@ -217,11 +230,12 @@ func (m *Manager) passthroughAgentCommand(execution *AgentExecution, profileInfo
|
||||
pt := ptAgent.PassthroughConfig()
|
||||
rt := agentConfig.Runtime()
|
||||
taskDescription := getTaskDescriptionFromMetadata(execution)
|
||||
promptForCmd := promptForPassthroughCommand(pt, taskDescription)
|
||||
|
||||
cmd := ptAgent.BuildPassthroughCommand(agents.PassthroughOptions{
|
||||
Model: profileModel(profileInfo),
|
||||
SessionID: execution.ACPSessionID,
|
||||
Prompt: taskDescription,
|
||||
Prompt: promptForCmd,
|
||||
PermissionValues: profilePermissionValues(profileInfo),
|
||||
CLIFlagTokens: m.profileCLIFlagTokens(profileInfo),
|
||||
})
|
||||
@@ -330,6 +344,8 @@ func (m *Manager) startPassthroughSession(ctx context.Context, execution *AgentE
|
||||
go m.streamManager.connectWorkspaceStream(execution, nil)
|
||||
}
|
||||
|
||||
go m.autoInjectInitialPrompt(execution, pt)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -786,6 +802,9 @@ func (m *Manager) attemptResumeFallback(execution *AgentExecution, runner *proce
|
||||
if m.streamManager != nil && execution.agentctl != nil && execution.GetWorkspaceStream() == nil {
|
||||
go m.streamManager.connectWorkspaceStream(execution, nil)
|
||||
}
|
||||
|
||||
// Fallback path is a fresh session (no --resume) — re-inject the prompt.
|
||||
go m.autoInjectInitialPrompt(execution, pt)
|
||||
}
|
||||
|
||||
// attemptPassthroughRestart announces the restart on the terminal, waits the
|
||||
@@ -912,6 +931,104 @@ func isFastFailExit(startedAt, exitedAt time.Time, exitCode int, window time.Dur
|
||||
return exitedAt.Sub(startedAt) < window
|
||||
}
|
||||
|
||||
// passthroughRunner is the minimal seam autoInjectInitialPrompt needs from
|
||||
// *process.InteractiveRunner. Defined as an interface so tests can supply a
|
||||
// fake runner without spinning up a real PTY subprocess.
|
||||
type passthroughRunner interface {
|
||||
WaitForFirstIdle(ctx context.Context, processID string) error
|
||||
WriteStdin(processID string, data string) error
|
||||
}
|
||||
|
||||
// autoInjectInitialPrompt writes the task description to the PTY stdin once
|
||||
// the agent is idle (ready for input). Opt-in per agent via PassthroughConfig.
|
||||
// Called from startPassthroughSession and attemptResumeFallback only — never
|
||||
// from ResumePassthroughSession (would duplicate the prompt in agent history).
|
||||
func (m *Manager) autoInjectInitialPrompt(execution *AgentExecution, pt agents.PassthroughConfig) {
|
||||
runner := m.GetInteractiveRunner()
|
||||
if runner == nil {
|
||||
return
|
||||
}
|
||||
m.autoInjectInitialPromptWith(runner, execution, pt)
|
||||
}
|
||||
|
||||
// autoInjectInitialPromptWith is the testable inner of autoInjectInitialPrompt,
|
||||
// taking a runner seam so unit tests can avoid spawning a real PTY.
|
||||
func (m *Manager) autoInjectInitialPromptWith(runner passthroughRunner, execution *AgentExecution, pt agents.PassthroughConfig) {
|
||||
if !pt.AutoInjectPrompt {
|
||||
return
|
||||
}
|
||||
if !pt.PromptFlag.IsEmpty() {
|
||||
// The agent already received the prompt as a CLI flag.
|
||||
return
|
||||
}
|
||||
description := getTaskDescriptionFromMetadata(execution)
|
||||
if description == "" {
|
||||
return
|
||||
}
|
||||
processID := execution.PassthroughProcessID
|
||||
if processID == "" {
|
||||
m.logger.Warn("autoInjectInitialPrompt called without passthrough process",
|
||||
zap.String("execution_id", execution.ID))
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
|
||||
defer cancel()
|
||||
if err := runner.WaitForFirstIdle(ctx, processID); err != nil {
|
||||
m.logger.Warn("autoInjectInitialPrompt timed out waiting for idle",
|
||||
zap.String("execution_id", execution.ID),
|
||||
zap.String("process_id", processID),
|
||||
zap.Error(err))
|
||||
return
|
||||
}
|
||||
// WaitForFirstIdle also unblocks when the process exits — skip the write
|
||||
// during shutdown so we don't race the lifecycle manager's teardown. If the
|
||||
// process is already gone, WriteStdin returns "process not found" and the
|
||||
// existing error branch logs it.
|
||||
if m.IsShuttingDown() {
|
||||
return
|
||||
}
|
||||
// Mark RUNNING before the chunk loop so a composer/message.add fired during
|
||||
// the inter-chunk SubmitDelay window (150ms for Claude) is blocked by
|
||||
// checkSessionPromptable instead of racing into the same PTY mid-submit.
|
||||
if err := m.MarkPassthroughRunning(execution.SessionID); err != nil {
|
||||
m.logger.Warn("failed to mark passthrough as running before auto-inject",
|
||||
zap.String("execution_id", execution.ID),
|
||||
zap.String("session_id", execution.SessionID),
|
||||
zap.Error(err))
|
||||
}
|
||||
for _, chunk := range agents.PlanPassthroughStdinChunks(description, pt) {
|
||||
if chunk.DelayBefore > 0 {
|
||||
time.Sleep(chunk.DelayBefore)
|
||||
}
|
||||
if err := runner.WriteStdin(processID, chunk.Data); err != nil {
|
||||
m.logger.Warn("autoInjectInitialPrompt write failed",
|
||||
zap.String("execution_id", execution.ID),
|
||||
zap.String("process_id", processID),
|
||||
zap.Error(err))
|
||||
return
|
||||
}
|
||||
}
|
||||
m.logger.Info("autoInjectInitialPrompt wrote task description to PTY",
|
||||
zap.String("execution_id", execution.ID),
|
||||
zap.String("process_id", processID),
|
||||
zap.Int("description_len", len(description)))
|
||||
}
|
||||
|
||||
// ResolvePassthroughConfig returns the PassthroughConfig for a session's agent.
|
||||
// Used by callers outside this package (e.g. orchestrator) that need the submit
|
||||
// sequence to write to PTY stdin.
|
||||
func (m *Manager) ResolvePassthroughConfig(ctx context.Context, sessionID string) (agents.PassthroughConfig, error) {
|
||||
execution, exists := m.executionStore.GetBySessionID(sessionID)
|
||||
if !exists {
|
||||
return agents.PassthroughConfig{}, fmt.Errorf("no execution for session %q", sessionID)
|
||||
}
|
||||
resolved, err := m.resolvePassthroughAgent(ctx, execution)
|
||||
if err != nil {
|
||||
return agents.PassthroughConfig{}, err
|
||||
}
|
||||
return resolved.pt, nil
|
||||
}
|
||||
|
||||
// GetInteractiveRunner returns the interactive runner for passthrough mode.
|
||||
// Returns nil if the runtime is not available or doesn't support passthrough.
|
||||
func (m *Manager) GetInteractiveRunner() *process.InteractiveRunner {
|
||||
|
||||
@@ -0,0 +1,213 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/agents"
|
||||
)
|
||||
|
||||
// fakePassthroughRunner is a minimal stub of the passthroughRunner seam used
|
||||
// to drive autoInjectInitialPromptWith in tests without spawning a real PTY.
|
||||
type fakePassthroughRunner struct {
|
||||
mu sync.Mutex
|
||||
|
||||
// waitErr is returned from WaitForFirstIdle. If waitBlock is true, the call
|
||||
// blocks until ctx is canceled regardless of waitErr.
|
||||
waitErr error
|
||||
waitBlock bool
|
||||
|
||||
// writeErr is returned from WriteStdin.
|
||||
writeErr error
|
||||
|
||||
// captured data passed to WriteStdin (last call).
|
||||
writtenProcessID string
|
||||
writtenData string
|
||||
writeCalled bool
|
||||
|
||||
// every chunk passed to WriteStdin, in order. Used by SubmitDelay tests that
|
||||
// need to assert the body/submit split (the single-string captures above only
|
||||
// hold the most recent write).
|
||||
writes []string
|
||||
// writeTimes records the wall-clock time of each WriteStdin call so tests can
|
||||
// assert that SubmitDelay was honored between chunks without coupling to a
|
||||
// specific clock.
|
||||
writeTimes []time.Time
|
||||
}
|
||||
|
||||
func (f *fakePassthroughRunner) WaitForFirstIdle(ctx context.Context, processID string) error {
|
||||
if f.waitBlock {
|
||||
<-ctx.Done()
|
||||
return ctx.Err()
|
||||
}
|
||||
return f.waitErr
|
||||
}
|
||||
|
||||
func (f *fakePassthroughRunner) WriteStdin(processID string, data string) error {
|
||||
f.mu.Lock()
|
||||
defer f.mu.Unlock()
|
||||
f.writeCalled = true
|
||||
f.writtenProcessID = processID
|
||||
f.writtenData = data
|
||||
f.writes = append(f.writes, data)
|
||||
f.writeTimes = append(f.writeTimes, time.Now())
|
||||
return f.writeErr
|
||||
}
|
||||
|
||||
func newAutoInjectExecution(description string) *AgentExecution {
|
||||
exec := &AgentExecution{
|
||||
ID: "exec-1",
|
||||
SessionID: "sess-1",
|
||||
PassthroughProcessID: "proc-abc",
|
||||
}
|
||||
if description != "" {
|
||||
exec.Metadata = map[string]interface{}{
|
||||
"task_description": description,
|
||||
}
|
||||
}
|
||||
return exec
|
||||
}
|
||||
|
||||
func TestAutoInject_disabled_does_nothing(t *testing.T) {
|
||||
mgr := newTestManager()
|
||||
runner := &fakePassthroughRunner{}
|
||||
|
||||
mgr.autoInjectInitialPromptWith(runner, newAutoInjectExecution("do a thing"), agents.PassthroughConfig{
|
||||
AutoInjectPrompt: false,
|
||||
SubmitSequence: "\r",
|
||||
})
|
||||
|
||||
if runner.writeCalled {
|
||||
t.Fatalf("expected no stdin write when AutoInjectPrompt is false, got data=%q", runner.writtenData)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoInject_skipped_when_PromptFlag_set(t *testing.T) {
|
||||
mgr := newTestManager()
|
||||
runner := &fakePassthroughRunner{}
|
||||
|
||||
mgr.autoInjectInitialPromptWith(runner, newAutoInjectExecution("do a thing"), agents.PassthroughConfig{
|
||||
AutoInjectPrompt: true,
|
||||
SubmitSequence: "\r",
|
||||
PromptFlag: agents.NewParam("--prompt", "{prompt}"),
|
||||
})
|
||||
|
||||
if runner.writeCalled {
|
||||
t.Fatalf("expected no stdin write when PromptFlag is set, got data=%q", runner.writtenData)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoInject_skipped_when_description_empty(t *testing.T) {
|
||||
mgr := newTestManager()
|
||||
runner := &fakePassthroughRunner{}
|
||||
|
||||
mgr.autoInjectInitialPromptWith(runner, newAutoInjectExecution(""), agents.PassthroughConfig{
|
||||
AutoInjectPrompt: true,
|
||||
SubmitSequence: "\r",
|
||||
})
|
||||
|
||||
if runner.writeCalled {
|
||||
t.Fatalf("expected no stdin write when task description is empty, got data=%q", runner.writtenData)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoInject_writes_description_plus_submit(t *testing.T) {
|
||||
mgr := newTestManager()
|
||||
runner := &fakePassthroughRunner{}
|
||||
|
||||
mgr.autoInjectInitialPromptWith(runner, newAutoInjectExecution("hello world"), agents.PassthroughConfig{
|
||||
AutoInjectPrompt: true,
|
||||
SubmitSequence: "\r",
|
||||
})
|
||||
|
||||
if !runner.writeCalled {
|
||||
t.Fatalf("expected WriteStdin to be called")
|
||||
}
|
||||
if runner.writtenProcessID != "proc-abc" {
|
||||
t.Errorf("WriteStdin processID = %q, want %q", runner.writtenProcessID, "proc-abc")
|
||||
}
|
||||
if runner.writtenData != "hello world\r" {
|
||||
t.Errorf("WriteStdin data = %q, want %q", runner.writtenData, "hello world\r")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutoInject_returns_when_wait_errors exercises the WaitForFirstIdle
|
||||
// error-return path: the helper must skip the stdin write and exit cleanly
|
||||
// rather than panic or loop.
|
||||
func TestAutoInject_returns_when_wait_errors(t *testing.T) {
|
||||
mgr := newTestManager()
|
||||
runner := &fakePassthroughRunner{waitErr: context.DeadlineExceeded}
|
||||
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
mgr.autoInjectInitialPromptWith(runner, newAutoInjectExecution("hello"), agents.PassthroughConfig{
|
||||
AutoInjectPrompt: true,
|
||||
SubmitSequence: "\r",
|
||||
})
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatalf("autoInjectInitialPromptWith did not return within 2s")
|
||||
}
|
||||
|
||||
if runner.writeCalled {
|
||||
t.Fatalf("expected no stdin write on wait timeout, got data=%q", runner.writtenData)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAutoInject_SubmitDelay_splits_writes_with_pause is the Claude regression:
|
||||
// when SubmitDelay > 0 the helper must write the body chunk first, then sleep
|
||||
// SubmitDelay, then write the submit byte alone, so Ink's paste-burst detector
|
||||
// sees the trailing \r as a discrete keystroke instead of absorbing it into the
|
||||
// pasted text.
|
||||
func TestAutoInject_SubmitDelay_splits_writes_with_pause(t *testing.T) {
|
||||
mgr := newTestManager()
|
||||
runner := &fakePassthroughRunner{}
|
||||
|
||||
const delay = 40 * time.Millisecond
|
||||
mgr.autoInjectInitialPromptWith(runner, newAutoInjectExecution("hello world"), agents.PassthroughConfig{
|
||||
AutoInjectPrompt: true,
|
||||
SubmitSequence: "\r",
|
||||
DisableBracketedPaste: true,
|
||||
SubmitDelay: delay,
|
||||
})
|
||||
|
||||
if got := len(runner.writes); got != 2 {
|
||||
t.Fatalf("expected 2 writes (body, submit), got %d: %#v", got, runner.writes)
|
||||
}
|
||||
if runner.writes[0] != "hello world" {
|
||||
t.Errorf("body write = %q, want %q", runner.writes[0], "hello world")
|
||||
}
|
||||
if runner.writes[1] != "\r" {
|
||||
t.Errorf("submit write = %q, want %q", runner.writes[1], "\r")
|
||||
}
|
||||
// Allow generous slack — CI clocks are noisy but a 40ms gap is still easy
|
||||
// to detect. The submit write must arrive at least ~SubmitDelay after the
|
||||
// body write; if the two were back-to-back this delta would be sub-ms.
|
||||
gap := runner.writeTimes[1].Sub(runner.writeTimes[0])
|
||||
if gap < delay/2 {
|
||||
t.Errorf("submit write came too soon after body: gap=%v, want >= %v", gap, delay/2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAutoInject_skipped_when_process_id_missing(t *testing.T) {
|
||||
mgr := newTestManager()
|
||||
runner := &fakePassthroughRunner{}
|
||||
|
||||
exec := newAutoInjectExecution("hello")
|
||||
exec.PassthroughProcessID = ""
|
||||
|
||||
mgr.autoInjectInitialPromptWith(runner, exec, agents.PassthroughConfig{
|
||||
AutoInjectPrompt: true,
|
||||
SubmitSequence: "\r",
|
||||
})
|
||||
|
||||
if runner.writeCalled {
|
||||
t.Fatalf("expected no stdin write when PassthroughProcessID empty, got data=%q", runner.writtenData)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package lifecycle
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/agents"
|
||||
)
|
||||
|
||||
// TestPromptForPassthroughCommand asserts the gating used by passthroughAgentCommand:
|
||||
// AutoInjectPrompt + empty PromptFlag suppresses the positional prompt arg, so the
|
||||
// description is delivered exclusively via PTY stdin in autoInjectInitialPrompt.
|
||||
// Without this guard, BuildPassthroughCommand would append the description as a
|
||||
// positional arg and put Claude (and similar TUIs) into non-interactive `-p` mode.
|
||||
func TestPromptForPassthroughCommand(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
pt agents.PassthroughConfig
|
||||
desc string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "auto-inject suppresses prompt arg",
|
||||
pt: agents.PassthroughConfig{AutoInjectPrompt: true},
|
||||
desc: "refactor cron handler",
|
||||
want: "",
|
||||
},
|
||||
{
|
||||
name: "auto-inject off keeps prompt",
|
||||
pt: agents.PassthroughConfig{AutoInjectPrompt: false},
|
||||
desc: "refactor cron handler",
|
||||
want: "refactor cron handler",
|
||||
},
|
||||
{
|
||||
name: "auto-inject with explicit PromptFlag keeps prompt — flag delivery wins",
|
||||
pt: agents.PassthroughConfig{
|
||||
AutoInjectPrompt: true,
|
||||
PromptFlag: agents.NewParam("--prompt", "{prompt}"),
|
||||
},
|
||||
desc: "refactor cron handler",
|
||||
want: "refactor cron handler",
|
||||
},
|
||||
{
|
||||
name: "empty description always empty",
|
||||
pt: agents.PassthroughConfig{AutoInjectPrompt: true},
|
||||
desc: "",
|
||||
want: "",
|
||||
},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := promptForPassthroughCommand(tc.pt, tc.desc)
|
||||
if got != tc.want {
|
||||
t.Errorf("promptForPassthroughCommand = %q, want %q", got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -119,9 +119,11 @@ func (c *Controller) buildAvailableAgentDTO(ctx context.Context, ag agents.Agent
|
||||
if ptAgent, ok := ag.(agents.PassthroughAgent); ok {
|
||||
pt := ptAgent.PassthroughConfig()
|
||||
passthroughConfig = &dto.PassthroughConfigDTO{
|
||||
Supported: pt.Supported,
|
||||
Label: pt.Label,
|
||||
Description: pt.Description,
|
||||
Supported: pt.Supported,
|
||||
Label: pt.Label,
|
||||
Description: pt.Description,
|
||||
AutoInjectPrompt: pt.AutoInjectPrompt,
|
||||
SubmitSequence: pt.SubmitSequence,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -146,9 +146,11 @@ type PermissionSettingDTO struct {
|
||||
}
|
||||
|
||||
type PassthroughConfigDTO struct {
|
||||
Supported bool `json:"supported"`
|
||||
Label string `json:"label"`
|
||||
Description string `json:"description"`
|
||||
Supported bool `json:"supported"`
|
||||
Label string `json:"label"`
|
||||
Description string `json:"description"`
|
||||
AutoInjectPrompt bool `json:"auto_inject_prompt"`
|
||||
SubmitSequence string `json:"submit_sequence"`
|
||||
}
|
||||
|
||||
type ToolStatusDTO struct {
|
||||
|
||||
@@ -190,6 +190,11 @@ func (r *InteractiveRunner) resetIdleTimer(proc *interactiveProcess) {
|
||||
}
|
||||
|
||||
func (r *InteractiveRunner) emitTurnComplete(proc *interactiveProcess) {
|
||||
// Close firstIdleCh exactly once — used by callers that want to react to
|
||||
// the very first idle window (e.g. auto-injecting the task prompt).
|
||||
proc.firstIdleOnce.Do(func() {
|
||||
close(proc.firstIdleCh)
|
||||
})
|
||||
if r.turnCompleteCallback != nil {
|
||||
r.turnCompleteCallback(proc.info.SessionID)
|
||||
}
|
||||
|
||||
@@ -62,6 +62,13 @@ type interactiveProcess struct {
|
||||
// race with stdin echo (which would otherwise duplicate the command in output).
|
||||
firstOutputOnce sync.Once
|
||||
firstOutputCh chan struct{}
|
||||
|
||||
// firstIdleCh is closed the first time the idle detector fires for this
|
||||
// process — i.e. the CLI has finished its startup output and is ready for
|
||||
// input. Used by the lifecycle manager to auto-inject the task description
|
||||
// at the right moment when AutoInjectPrompt is enabled.
|
||||
firstIdleOnce sync.Once
|
||||
firstIdleCh chan struct{}
|
||||
}
|
||||
|
||||
// Start creates an interactive process entry and defers PTY creation until first resize.
|
||||
@@ -124,6 +131,7 @@ func (r *InteractiveRunner) Start(ctx context.Context, req InteractiveStartReque
|
||||
stopSignal: make(chan struct{}),
|
||||
waitDone: make(chan struct{}),
|
||||
firstOutputCh: make(chan struct{}),
|
||||
firstIdleCh: make(chan struct{}),
|
||||
// Store start parameters for deferred initialization
|
||||
started: false,
|
||||
startCmd: req.Command,
|
||||
@@ -349,6 +357,11 @@ func (r *InteractiveRunner) Stop(ctx context.Context, processID string) error {
|
||||
return fmt.Errorf("process not found: %s", processID)
|
||||
}
|
||||
|
||||
// Unblock anyone waiting on first-idle — the process is going away.
|
||||
proc.firstIdleOnce.Do(func() {
|
||||
close(proc.firstIdleCh)
|
||||
})
|
||||
|
||||
// Signal output reader to exit
|
||||
proc.stopOnce.Do(func() {
|
||||
close(proc.stopSignal)
|
||||
@@ -486,6 +499,11 @@ func (r *InteractiveRunner) get(id string) (*interactiveProcess, bool) {
|
||||
// 3. Adding a timeout here would leave the process unreachable and create leaks
|
||||
func (r *InteractiveRunner) wait(proc *interactiveProcess) {
|
||||
defer close(proc.waitDone)
|
||||
// Unblock first-idle waiters on exit so an early crash doesn't strand
|
||||
// callers (e.g. autoInjectInitialPrompt) until their context times out.
|
||||
// Callers can't distinguish "idle and ready" from "process exited" — the
|
||||
// subsequent WriteStdin returns "process not found" which is logged.
|
||||
defer proc.firstIdleOnce.Do(func() { close(proc.firstIdleCh) })
|
||||
|
||||
proc.mu.Lock()
|
||||
ptyHandle := proc.ptmx
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -149,3 +151,21 @@ func (r *InteractiveRunner) SetStateCallback(cb AgentStateCallback) {
|
||||
func createStatusDetector() StatusDetector {
|
||||
return NewIdleDetector()
|
||||
}
|
||||
|
||||
// WaitForFirstIdle blocks until the idle detector for processID fires for
|
||||
// the first time, or ctx is canceled. Returns nil on first-idle, error otherwise.
|
||||
// Returns an error immediately if processID is unknown.
|
||||
func (r *InteractiveRunner) WaitForFirstIdle(ctx context.Context, processID string) error {
|
||||
r.mu.RLock()
|
||||
proc, ok := r.processes[processID]
|
||||
r.mu.RUnlock()
|
||||
if !ok {
|
||||
return fmt.Errorf("process %q not found", processID)
|
||||
}
|
||||
select {
|
||||
case <-proc.firstIdleCh:
|
||||
return nil
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package process
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/agentctl/types"
|
||||
)
|
||||
|
||||
// newRunnerWithProcess installs a bare interactiveProcess into the runner's
|
||||
// map so tests can drive firstIdle semantics without spawning a real PTY.
|
||||
func newRunnerWithProcess(t *testing.T, processID string) (*InteractiveRunner, *interactiveProcess) {
|
||||
t.Helper()
|
||||
log := newTestLogger(t)
|
||||
runner := NewInteractiveRunner(nil, log, 2*1024*1024)
|
||||
|
||||
proc := &interactiveProcess{
|
||||
info: InteractiveProcessInfo{
|
||||
ID: processID,
|
||||
SessionID: "sess-" + processID,
|
||||
Status: types.ProcessStatusRunning,
|
||||
StartedAt: time.Now().UTC(),
|
||||
UpdatedAt: time.Now().UTC(),
|
||||
},
|
||||
stopSignal: make(chan struct{}),
|
||||
waitDone: make(chan struct{}),
|
||||
firstOutputCh: make(chan struct{}),
|
||||
firstIdleCh: make(chan struct{}),
|
||||
}
|
||||
|
||||
runner.mu.Lock()
|
||||
runner.processes[processID] = proc
|
||||
runner.mu.Unlock()
|
||||
return runner, proc
|
||||
}
|
||||
|
||||
func TestWaitForFirstIdle_fires_on_idle_event(t *testing.T) {
|
||||
runner, proc := newRunnerWithProcess(t, "proc-fires")
|
||||
|
||||
done := make(chan error, 1)
|
||||
go func() {
|
||||
done <- runner.WaitForFirstIdle(context.Background(), "proc-fires")
|
||||
}()
|
||||
|
||||
// emitTurnComplete is what fires the idle event in production.
|
||||
go runner.emitTurnComplete(proc)
|
||||
|
||||
select {
|
||||
case err := <-done:
|
||||
if err != nil {
|
||||
t.Fatalf("WaitForFirstIdle returned error: %v", err)
|
||||
}
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatalf("WaitForFirstIdle did not return after idle fired")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitForFirstIdle_returns_ctx_error(t *testing.T) {
|
||||
runner, _ := newRunnerWithProcess(t, "proc-ctx")
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
cancel()
|
||||
|
||||
err := runner.WaitForFirstIdle(ctx, "proc-ctx")
|
||||
if !errors.Is(err, context.Canceled) {
|
||||
t.Fatalf("WaitForFirstIdle err = %v, want context.Canceled", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitForFirstIdle_unknown_process_errors(t *testing.T) {
|
||||
log := newTestLogger(t)
|
||||
runner := NewInteractiveRunner(nil, log, 2*1024*1024)
|
||||
|
||||
err := runner.WaitForFirstIdle(context.Background(), "does-not-exist")
|
||||
if err == nil {
|
||||
t.Fatalf("WaitForFirstIdle returned nil error for unknown process")
|
||||
}
|
||||
}
|
||||
|
||||
func TestEmitTurnComplete_closes_firstIdle_only_once(t *testing.T) {
|
||||
runner, proc := newRunnerWithProcess(t, "proc-once")
|
||||
|
||||
runner.emitTurnComplete(proc)
|
||||
runner.emitTurnComplete(proc) // second call must not panic on double close
|
||||
|
||||
select {
|
||||
case <-proc.firstIdleCh:
|
||||
// ok
|
||||
default:
|
||||
t.Fatalf("firstIdleCh was not closed after emitTurnComplete")
|
||||
}
|
||||
}
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
"github.com/google/uuid"
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/agents"
|
||||
"github.com/kandev/kandev/internal/agent/runtime/agentctl"
|
||||
"github.com/kandev/kandev/internal/agent/runtime/lifecycle"
|
||||
"github.com/kandev/kandev/internal/agentctl/types/streams"
|
||||
@@ -491,6 +492,9 @@ func (s *SimulatedAgentManagerClient) IsPassthroughSession(ctx context.Context,
|
||||
func (s *SimulatedAgentManagerClient) WritePassthroughStdin(_ context.Context, _ string, _ string) error {
|
||||
return nil
|
||||
}
|
||||
func (s *SimulatedAgentManagerClient) ResolvePassthroughConfig(_ context.Context, _ string) (agents.PassthroughConfig, error) {
|
||||
return agents.PassthroughConfig{}, nil
|
||||
}
|
||||
func (s *SimulatedAgentManagerClient) MarkPassthroughRunning(_ string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/jmoiron/sqlx"
|
||||
_ "github.com/mattn/go-sqlite3"
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/agents"
|
||||
"github.com/kandev/kandev/internal/agent/runtime/agentctl"
|
||||
"github.com/kandev/kandev/internal/agent/runtime/lifecycle"
|
||||
"github.com/kandev/kandev/internal/agentctl/types/streams"
|
||||
@@ -148,6 +149,12 @@ type mockAgentManager struct {
|
||||
markPassthroughCalls []string // session IDs
|
||||
markPassthroughErr error
|
||||
|
||||
// Passthrough config resolution. When zero-valued and isPassthrough is true,
|
||||
// the mock returns a default config with SubmitSequence == "\r".
|
||||
passthroughConfig agents.PassthroughConfig
|
||||
passthroughConfigSet bool
|
||||
passthroughConfigErr error
|
||||
|
||||
// Optional override for GetExecutionIDForSession. When unset, the default
|
||||
// implementation reads from repoForExecutionLookup if provided so tests that
|
||||
// seed an executors_running row don't also have to mock this function.
|
||||
@@ -291,6 +298,20 @@ func (m *mockAgentManager) WritePassthroughStdin(_ context.Context, sessionID st
|
||||
m.passthroughStdinCalls = append(m.passthroughStdinCalls, passthroughStdinCall{SessionID: sessionID, Data: data})
|
||||
return m.passthroughStdinErr
|
||||
}
|
||||
func (m *mockAgentManager) ResolvePassthroughConfig(_ context.Context, _ string) (agents.PassthroughConfig, error) {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
if m.passthroughConfigErr != nil {
|
||||
return agents.PassthroughConfig{}, m.passthroughConfigErr
|
||||
}
|
||||
if m.passthroughConfigSet {
|
||||
return m.passthroughConfig, nil
|
||||
}
|
||||
if !m.isPassthrough {
|
||||
return agents.PassthroughConfig{Supported: false}, nil
|
||||
}
|
||||
return agents.PassthroughConfig{Supported: true, SubmitSequence: "\r"}, nil
|
||||
}
|
||||
func (m *mockAgentManager) MarkPassthroughRunning(sessionID string) error {
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
@@ -1042,9 +1063,12 @@ func TestDeliverPassthroughPrompt(t *testing.T) {
|
||||
agentMgr.mu.Lock()
|
||||
defer agentMgr.mu.Unlock()
|
||||
|
||||
// Should not call markPassthroughRunning when stdin write fails
|
||||
if len(agentMgr.markPassthroughCalls) != 0 {
|
||||
t.Errorf("markPassthroughRunning should not be called when stdin fails, got %d calls", len(agentMgr.markPassthroughCalls))
|
||||
// markPassthroughRunning now fires BEFORE any writes so concurrent
|
||||
// PromptTask calls are blocked during the inter-chunk SubmitDelay
|
||||
// window (Greptile P1). Expect exactly one mark call even when the
|
||||
// subsequent write fails.
|
||||
if len(agentMgr.markPassthroughCalls) != 1 {
|
||||
t.Errorf("markPassthroughRunning should fire once before the write; got %d calls", len(agentMgr.markPassthroughCalls))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
|
||||
"go.uber.org/zap"
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/agents"
|
||||
"github.com/kandev/kandev/internal/events"
|
||||
"github.com/kandev/kandev/internal/events/bus"
|
||||
"github.com/kandev/kandev/internal/orchestrator/executor"
|
||||
@@ -1057,17 +1058,39 @@ func (s *Service) drainQueuedMessageAfterTransition(ctx context.Context, session
|
||||
}
|
||||
|
||||
// deliverPassthroughPrompt writes a prompt to PTY stdin and marks the session as running.
|
||||
// Appends \r (carriage return) to simulate pressing Enter — TUI agents in raw terminal mode
|
||||
// expect CR, not LF, as the submit key. Returns an error only if writing fails.
|
||||
// Uses the per-agent PlanPassthroughStdinChunks so Claude's inter-chunk SubmitDelay is
|
||||
// honored here too (queued / workflow-auto-start path); other agents stay on the single
|
||||
// atomic write. Falls back to the simple "\r" append if config resolution fails so a
|
||||
// transient lookup error never silently swallows the prompt.
|
||||
func (s *Service) deliverPassthroughPrompt(ctx context.Context, sessionID, content string) error {
|
||||
if err := s.agentManager.WritePassthroughStdin(ctx, sessionID, content+"\r"); err != nil {
|
||||
return fmt.Errorf("write to passthrough stdin: %w", err)
|
||||
pt, cfgErr := s.agentManager.ResolvePassthroughConfig(ctx, sessionID)
|
||||
if cfgErr != nil {
|
||||
s.logger.Warn("failed to resolve passthrough config, falling back to \\r submit",
|
||||
zap.String("session_id", sessionID),
|
||||
zap.Error(cfgErr))
|
||||
}
|
||||
// Mark RUNNING before any writes so concurrent PromptTask / queued-message
|
||||
// delivery is blocked by checkSessionPromptable during the inter-chunk
|
||||
// SubmitDelay window (150ms for Claude). Mark error is non-fatal.
|
||||
if err := s.agentManager.MarkPassthroughRunning(sessionID); err != nil {
|
||||
s.logger.Warn("failed to mark passthrough as running",
|
||||
s.logger.Warn("failed to mark passthrough as running before prompt",
|
||||
zap.String("session_id", sessionID),
|
||||
zap.Error(err))
|
||||
}
|
||||
if cfgErr != nil {
|
||||
if err := s.agentManager.WritePassthroughStdin(ctx, sessionID, content+"\r"); err != nil {
|
||||
return fmt.Errorf("write to passthrough stdin: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, chunk := range agents.PlanPassthroughStdinChunks(content, pt) {
|
||||
if chunk.DelayBefore > 0 {
|
||||
time.Sleep(chunk.DelayBefore)
|
||||
}
|
||||
if err := s.agentManager.WritePassthroughStdin(ctx, sessionID, chunk.Data); err != nil {
|
||||
return fmt.Errorf("write to passthrough stdin: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1167,8 +1190,10 @@ func (s *Service) autoStartStepPrompt(
|
||||
// (HasKandevContext guard) so the pre-wrap doesn't double.
|
||||
// The HasKandevContext check on `prompt` also guards against any future
|
||||
// caller that ever pre-wraps before reaching here (none today).
|
||||
// Passthrough sessions skip the wrap: the prompt is typed straight into
|
||||
// the agent CLI's TTY and the user sees it verbatim.
|
||||
recordedPrompt := prompt
|
||||
if session.State == models.TaskSessionStateCreated && (prompt != "" || len(attachments) > 0) && !sysprompt.HasKandevContext(prompt) {
|
||||
if session.State == models.TaskSessionStateCreated && !session.IsPassthrough && (prompt != "" || len(attachments) > 0) && !sysprompt.HasKandevContext(prompt) {
|
||||
recordedPrompt = sysprompt.InjectKandevContext(taskID, sessionID, prompt)
|
||||
}
|
||||
s.recordAutoStartMessage(ctx, taskID, sessionID, recordedPrompt, planMode, origin)
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/agents"
|
||||
"github.com/kandev/kandev/internal/agent/runtime/agentctl"
|
||||
"github.com/kandev/kandev/internal/agent/runtime/lifecycle"
|
||||
"github.com/kandev/kandev/internal/agentctl/types/streams"
|
||||
@@ -151,6 +152,11 @@ type AgentManagerClient interface {
|
||||
// WritePassthroughStdin writes data to the agent's PTY stdin for passthrough sessions.
|
||||
WritePassthroughStdin(ctx context.Context, sessionID string, data string) error
|
||||
|
||||
// ResolvePassthroughConfig returns the resolved PassthroughConfig for a session's agent.
|
||||
// Used by the orchestrator to route chat-compose prompts and Stop button presses into
|
||||
// the agent's PTY stdin (with the correct submit sequence) instead of through ACP.
|
||||
ResolvePassthroughConfig(ctx context.Context, sessionID string) (agents.PassthroughConfig, error)
|
||||
|
||||
// MarkPassthroughRunning marks a passthrough execution as running.
|
||||
MarkPassthroughRunning(sessionID string) error
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/agents"
|
||||
"github.com/kandev/kandev/internal/agent/runtime/lifecycle"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
@@ -117,15 +118,11 @@ 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"
|
||||
stopReasonPassthrough = "passthrough_dispatched"
|
||||
)
|
||||
// stopReasonPassthrough is the StopReason returned by Executor.Prompt when a
|
||||
// passthrough session's prompt is dispatched to PTY stdin (no ACP turn to
|
||||
// observe). The submit sequence is resolved per-agent via ResolvePassthroughConfig
|
||||
// — see promptPassthrough below.
|
||||
const stopReasonPassthrough = "passthrough_dispatched"
|
||||
|
||||
// Prompt sends a follow-up prompt to a running agent for a task
|
||||
// Returns PromptResult indicating if the agent needs input
|
||||
@@ -182,6 +179,10 @@ func (e *Executor) Prompt(ctx context.Context, taskID, sessionID string, prompt
|
||||
// supplies any, we log a warning so an operator can see they were dropped
|
||||
// (image-only messages are rejected outright since there is nothing to write).
|
||||
//
|
||||
// The submit sequence is resolved per-agent via ResolvePassthroughConfig — most
|
||||
// TUI CLIs use "\r" but the config field lets a future agent override it
|
||||
// without touching this code path.
|
||||
//
|
||||
// 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
|
||||
@@ -196,15 +197,31 @@ func (e *Executor) promptPassthrough(ctx context.Context, taskID, sessionID, pro
|
||||
zap.String("session_id", sessionID),
|
||||
zap.Int("attachments_count", len(attachments)))
|
||||
}
|
||||
if err := e.agentManager.WritePassthroughStdin(ctx, sessionID, prompt+passthroughSubmitSequence); err != nil {
|
||||
return nil, fmt.Errorf("failed to write to passthrough stdin: %w", err)
|
||||
pt, err := e.agentManager.ResolvePassthroughConfig(ctx, sessionID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve passthrough config: %w", err)
|
||||
}
|
||||
// Mark RUNNING before the chunk loop so concurrent PromptTask calls are
|
||||
// blocked by checkSessionPromptable during the inter-chunk SubmitDelay
|
||||
// window (150ms for Claude). Otherwise a rapid double-send or workflow
|
||||
// event firing in parallel passes the WAITING_FOR_INPUT guard and writes
|
||||
// a second prompt onto the same PTY stdin mid-submit. Mark-error stays
|
||||
// non-fatal — at worst we miss the AgentRunning event but the prompt
|
||||
// still gets through.
|
||||
if err := e.agentManager.MarkPassthroughRunning(sessionID); err != nil {
|
||||
e.logger.Warn("failed to mark passthrough as running after prompt; data already in PTY",
|
||||
e.logger.Warn("failed to mark passthrough as running before prompt; concurrent send window is open",
|
||||
zap.String("task_id", taskID),
|
||||
zap.String("session_id", sessionID),
|
||||
zap.Error(err))
|
||||
}
|
||||
for _, chunk := range agents.PlanPassthroughStdinChunks(prompt, pt) {
|
||||
if chunk.DelayBefore > 0 {
|
||||
time.Sleep(chunk.DelayBefore)
|
||||
}
|
||||
if err := e.agentManager.WritePassthroughStdin(ctx, sessionID, chunk.Data); err != nil {
|
||||
return nil, fmt.Errorf("failed to write to passthrough stdin: %w", err)
|
||||
}
|
||||
}
|
||||
return &PromptResult{StopReason: stopReasonPassthrough}, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/agents"
|
||||
agentdto "github.com/kandev/kandev/internal/agent/dto"
|
||||
"github.com/kandev/kandev/internal/agent/runtime/agentctl"
|
||||
"github.com/kandev/kandev/internal/agentctl/types/streams"
|
||||
@@ -28,6 +29,7 @@ type mockAgentManager struct {
|
||||
isPassthroughSessionFunc func(ctx context.Context, sessionID string) bool
|
||||
writePassthroughStdinFunc func(ctx context.Context, sessionID, data string) error
|
||||
markPassthroughRunningFunc func(sessionID string) error
|
||||
resolvePassthroughConfigFunc func(ctx context.Context, sessionID string) (agents.PassthroughConfig, error)
|
||||
launchAgentCallCount int
|
||||
cleanupStaleExecutionCallCount int
|
||||
isAgentRunningForSessionCallArgs []string
|
||||
@@ -142,6 +144,17 @@ func (m *mockAgentManager) WritePassthroughStdin(ctx context.Context, sessionID
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (m *mockAgentManager) ResolvePassthroughConfig(ctx context.Context, sessionID string) (agents.PassthroughConfig, error) {
|
||||
if m.resolvePassthroughConfigFunc != nil {
|
||||
return m.resolvePassthroughConfigFunc(ctx, sessionID)
|
||||
}
|
||||
// Default to a sensible passthrough config (SubmitSequence "\r") when the
|
||||
// session is in passthrough mode, so most tests don't need to override.
|
||||
if m.isPassthroughSessionFunc != nil && m.isPassthroughSessionFunc(ctx, sessionID) {
|
||||
return agents.PassthroughConfig{Supported: true, SubmitSequence: "\r"}, nil
|
||||
}
|
||||
return agents.PassthroughConfig{}, nil
|
||||
}
|
||||
func (m *mockAgentManager) MarkPassthroughRunning(sessionID string) error {
|
||||
m.markPassthroughRunningCalls = append(m.markPassthroughRunningCalls, sessionID)
|
||||
if m.markPassthroughRunningFunc != nil {
|
||||
|
||||
@@ -5,7 +5,9 @@ import (
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/kandev/kandev/internal/agent/agents"
|
||||
"github.com/kandev/kandev/internal/task/models"
|
||||
v1 "github.com/kandev/kandev/pkg/api/v1"
|
||||
)
|
||||
@@ -51,7 +53,9 @@ func TestExecutor_Prompt_PassthroughWritesStdin(t *testing.T) {
|
||||
if call.SessionID != "sess-1" {
|
||||
t.Errorf("WritePassthroughStdin session = %q, want sess-1", call.SessionID)
|
||||
}
|
||||
wantData := "hello agent" + passthroughSubmitSequence
|
||||
// Mock's ResolvePassthroughConfig returns SubmitSequence "\r" by default
|
||||
// when isPassthroughSessionFunc reports the session is passthrough.
|
||||
wantData := "hello agent\r"
|
||||
if call.Data != wantData {
|
||||
t.Errorf("WritePassthroughStdin data = %q, want %q", call.Data, wantData)
|
||||
}
|
||||
@@ -91,10 +95,14 @@ func TestExecutor_Prompt_PassthroughWriteErrorReturnsError(t *testing.T) {
|
||||
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)
|
||||
// MarkPassthroughRunning is now called BEFORE the chunk loop so concurrent
|
||||
// PromptTask calls are blocked during the inter-chunk SubmitDelay window
|
||||
// (Greptile P1). The UI may briefly show "running" for a prompt that then
|
||||
// fails to deliver — preferable to a second prompt racing into the PTY
|
||||
// mid-submit. Expect exactly one MarkPassthroughRunning call even when the
|
||||
// subsequent write fails.
|
||||
if got := len(agentManager.markPassthroughRunningCalls); got != 1 {
|
||||
t.Errorf("MarkPassthroughRunning should be called once before the write; got %d call(s)", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -180,12 +188,84 @@ func TestExecutor_Prompt_PassthroughPreservesUnicodeAndMultiline(t *testing.T) {
|
||||
if _, err := exec.Prompt(context.Background(), "task-1", "sess-1", prompt, nil, false); err != nil {
|
||||
t.Fatalf("Prompt returned error: %v", err)
|
||||
}
|
||||
cfg := agents.PassthroughConfig{SubmitSequence: "\r"}
|
||||
want := agents.BuildPassthroughPayload(prompt, cfg)
|
||||
if len(agentManager.writePassthroughStdinCalls) != 1 {
|
||||
t.Fatalf("expected 1 atomic WritePassthroughStdin call for multiline, got %d", len(agentManager.writePassthroughStdinCalls))
|
||||
}
|
||||
if agentManager.writePassthroughStdinCalls[0].Data != want {
|
||||
t.Errorf("PTY payload = %q, want %q", agentManager.writePassthroughStdinCalls[0].Data, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExecutor_Prompt_PassthroughHonoursDynamicSubmitSequence verifies the
|
||||
// PTY submit suffix is taken from PassthroughConfig (per-agent) rather than
|
||||
// hardcoded. A future TUI that submits on "\n" or "\x0d\x0a" plugs in via
|
||||
// PassthroughConfig.SubmitSequence with no code change here.
|
||||
func TestExecutor_Prompt_PassthroughHonoursDynamicSubmitSequence(t *testing.T) {
|
||||
repo := newMockRepository()
|
||||
agentManager := &mockAgentManager{
|
||||
isPassthroughSessionFunc: func(_ context.Context, _ string) bool { return true },
|
||||
resolvePassthroughConfigFunc: func(_ context.Context, _ string) (agents.PassthroughConfig, error) {
|
||||
return agents.PassthroughConfig{Supported: true, SubmitSequence: "\n"}, nil
|
||||
},
|
||||
}
|
||||
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", "hi", nil, false); err != nil {
|
||||
t.Fatalf("Prompt returned error: %v", err)
|
||||
}
|
||||
if got := len(agentManager.writePassthroughStdinCalls); got != 1 {
|
||||
t.Fatalf("expected 1 WritePassthroughStdin call, got %d", got)
|
||||
}
|
||||
want := prompt + "\r"
|
||||
want := "hi\n"
|
||||
if agentManager.writePassthroughStdinCalls[0].Data != want {
|
||||
t.Errorf("PTY payload = %q, want %q", agentManager.writePassthroughStdinCalls[0].Data, want)
|
||||
t.Errorf("PTY payload = %q, want %q (dynamic SubmitSequence not applied)", agentManager.writePassthroughStdinCalls[0].Data, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExecutor_Prompt_PassthroughSubmitDelaySplitsWrites verifies the compose-box
|
||||
// follow-up path (Executor.Prompt → promptPassthrough) honors SubmitDelay: the
|
||||
// body and submit byte must arrive as two separate WritePassthroughStdin calls
|
||||
// with the body first and the submit ("\r") second, so Claude's Ink TUI sees the
|
||||
// trailing Enter as a discrete keystroke instead of absorbing it into a paste
|
||||
// burst. The auto-inject path is covered by manager_passthrough_autoinject_test.go;
|
||||
// this guards the executor path against regressing back to a single atomic write.
|
||||
func TestExecutor_Prompt_PassthroughSubmitDelaySplitsWrites(t *testing.T) {
|
||||
repo := newMockRepository()
|
||||
agentManager := &mockAgentManager{
|
||||
isPassthroughSessionFunc: func(_ context.Context, _ string) bool { return true },
|
||||
resolvePassthroughConfigFunc: func(_ context.Context, _ string) (agents.PassthroughConfig, error) {
|
||||
return agents.PassthroughConfig{
|
||||
Supported: true,
|
||||
SubmitSequence: "\r",
|
||||
DisableBracketedPaste: true,
|
||||
SubmitDelay: 20 * time.Millisecond,
|
||||
}, nil
|
||||
},
|
||||
}
|
||||
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 agent", nil, false); err != nil {
|
||||
t.Fatalf("Prompt returned error: %v", err)
|
||||
}
|
||||
|
||||
if got := len(agentManager.writePassthroughStdinCalls); got != 2 {
|
||||
t.Fatalf("expected 2 WritePassthroughStdin calls (body, submit), got %d: %#v", got, agentManager.writePassthroughStdinCalls)
|
||||
}
|
||||
if agentManager.writePassthroughStdinCalls[0].Data != "hello agent" {
|
||||
t.Errorf("body write Data = %q, want %q", agentManager.writePassthroughStdinCalls[0].Data, "hello agent")
|
||||
}
|
||||
if agentManager.writePassthroughStdinCalls[1].Data != "\r" {
|
||||
t.Errorf("submit write Data = %q, want %q", agentManager.writePassthroughStdinCalls[1].Data, "\r")
|
||||
}
|
||||
// MarkPassthroughRunning must still fire exactly once after both writes — the
|
||||
// session should flip to RUNNING for the UI even though the two writes were
|
||||
// split. Regressing this would leave the spinner stuck on the composer.
|
||||
if got := len(agentManager.markPassthroughRunningCalls); got != 1 {
|
||||
t.Errorf("expected 1 MarkPassthroughRunning call, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
"github.com/kandev/kandev/internal/agent/agents"
|
||||
"github.com/kandev/kandev/internal/agent/runtime/agentctl"
|
||||
"github.com/kandev/kandev/internal/agentctl/types/streams"
|
||||
"github.com/kandev/kandev/internal/common/logger"
|
||||
@@ -104,6 +105,9 @@ func (m *mockAgentManager) IsPassthroughSession(ctx context.Context, sessionID s
|
||||
func (m *mockAgentManager) WritePassthroughStdin(_ context.Context, _ string, _ string) error {
|
||||
return nil
|
||||
}
|
||||
func (m *mockAgentManager) ResolvePassthroughConfig(_ context.Context, _ string) (agents.PassthroughConfig, error) {
|
||||
return agents.PassthroughConfig{}, nil
|
||||
}
|
||||
func (m *mockAgentManager) MarkPassthroughRunning(_ string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -356,7 +356,10 @@ func (s *Service) StartCreatedSession(ctx context.Context, taskID, sessionID, ag
|
||||
// Message.ToAPI strips for display). Idempotent — upstream call sites that
|
||||
// record the user message themselves (wsAddMessage on CREATED sessions)
|
||||
// wrap first, and the HasKandevContext guard prevents a second wrap here.
|
||||
if (effectivePrompt != "" || len(attachments) > 0) && !sysprompt.HasKandevContext(effectivePrompt) {
|
||||
// Passthrough profiles skip the wrap: the prompt is typed straight into the
|
||||
// agent CLI's TTY and the user sees it verbatim — they don't want a wall of
|
||||
// MCP-tool boilerplate prepended to "hello".
|
||||
if (effectivePrompt != "" || len(attachments) > 0) && !sysprompt.HasKandevContext(effectivePrompt) && !session.IsPassthrough {
|
||||
effectivePrompt = sysprompt.InjectKandevContext(taskID, sessionID, effectivePrompt)
|
||||
}
|
||||
|
||||
@@ -568,7 +571,15 @@ func (s *Service) startTask(ctx context.Context, taskID string, agentProfileID s
|
||||
// recordAutoStartMessage) wrap before recording the user message so the DB
|
||||
// row carries the block; the HasKandevContext guard makes this orchestrator
|
||||
// pass a no-op in those cases instead of double-wrapping.
|
||||
if (effectivePrompt != "" || len(attachments) > 0) && !sysprompt.HasKandevContext(effectivePrompt) {
|
||||
// Passthrough sessions skip the wrap: the prompt is typed straight into the
|
||||
// agent CLI's TTY and the user sees it verbatim — they don't want a wall of
|
||||
// MCP-tool boilerplate prepended to "hello". Use the session snapshot, not a
|
||||
// live profile lookup, so a mid-run profile edit cannot change wrap behavior.
|
||||
skipKandevMCPWrap := false
|
||||
if launchSession, sessErr := s.repo.GetTaskSession(ctx, sessionID); sessErr == nil {
|
||||
skipKandevMCPWrap = launchSession.IsPassthrough
|
||||
}
|
||||
if (effectivePrompt != "" || len(attachments) > 0) && !sysprompt.HasKandevContext(effectivePrompt) && !skipKandevMCPWrap {
|
||||
effectivePrompt = sysprompt.InjectKandevContext(task.ID, sessionID, effectivePrompt)
|
||||
}
|
||||
|
||||
@@ -1861,6 +1872,17 @@ func (s *Service) PromptTask(ctx context.Context, taskID, sessionID string, prom
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// Inject config context for config-mode sessions (dedicated settings chat, not plan mode)
|
||||
effectivePrompt := prompt
|
||||
if cm, ok := session.Metadata["config_mode"].(bool); ok && cm {
|
||||
effectivePrompt = sysprompt.InjectConfigContext(sessionID, prompt)
|
||||
}
|
||||
|
||||
// Inject plan mode prefix for follow-up messages in plan mode sessions.
|
||||
if planMode {
|
||||
effectivePrompt = sysprompt.InjectPlanMode(effectivePrompt)
|
||||
}
|
||||
|
||||
// Ensure the agent process is actually running. After a lazy backend restart,
|
||||
// the session may be in WAITING_FOR_INPUT but no agent process exists yet.
|
||||
if err := s.ensureSessionRunning(ctx, sessionID, session); err != nil {
|
||||
@@ -1876,17 +1898,14 @@ func (s *Service) PromptTask(ctx context.Context, taskID, sessionID string, prom
|
||||
// freshly-persisted AgentExecutionID.
|
||||
if reloaded, err := s.repo.GetTaskSession(ctx, sessionID); err == nil && reloaded != nil {
|
||||
session = reloaded
|
||||
}
|
||||
|
||||
// Inject config context for config-mode sessions (dedicated settings chat, not plan mode)
|
||||
effectivePrompt := prompt
|
||||
if cm, ok := session.Metadata["config_mode"].(bool); ok && cm {
|
||||
effectivePrompt = sysprompt.InjectConfigContext(sessionID, prompt)
|
||||
}
|
||||
|
||||
// Inject plan mode prefix for follow-up messages in plan mode sessions.
|
||||
if planMode {
|
||||
effectivePrompt = sysprompt.InjectPlanMode(effectivePrompt)
|
||||
// Re-apply transforms in case metadata changed during ensureSessionRunning.
|
||||
effectivePrompt = prompt
|
||||
if cm, ok := session.Metadata["config_mode"].(bool); ok && cm {
|
||||
effectivePrompt = sysprompt.InjectConfigContext(sessionID, prompt)
|
||||
}
|
||||
if planMode {
|
||||
effectivePrompt = sysprompt.InjectPlanMode(effectivePrompt)
|
||||
}
|
||||
}
|
||||
|
||||
// Check if model switching is requested
|
||||
@@ -2107,6 +2126,9 @@ func (s *Service) CancelAgent(ctx context.Context, sessionID string) error {
|
||||
// just to host the cancel message.
|
||||
cancelTurnID := s.getActiveTurnID(sessionID)
|
||||
|
||||
// The agent manager routes the cancel to the right signal: ACP cancel for
|
||||
// regular sessions, Ctrl-C via PTY stdin for passthrough sessions. Service
|
||||
// stays protocol-agnostic; the seam is in lifecycle.Manager.CancelAgentBySessionID.
|
||||
if err := s.agentManager.CancelAgent(ctx, sessionID); err != nil {
|
||||
switch {
|
||||
case errors.Is(err, lifecycle.ErrNoExecutionForSession):
|
||||
|
||||
@@ -128,12 +128,15 @@ func TestPromptTask_PassthroughWriteFailureRevertsSession(t *testing.T) {
|
||||
t.Errorf("expected session reverted to WAITING_FOR_INPUT, got %q", updated.State)
|
||||
}
|
||||
|
||||
// MarkPassthroughRunning must NOT be called when the write failed — otherwise
|
||||
// the UI would flash "running" for a prompt the agent never received.
|
||||
// MarkPassthroughRunning now fires BEFORE the chunk loop so concurrent
|
||||
// PromptTask calls are blocked during the inter-chunk SubmitDelay window
|
||||
// (Greptile P1). When the subsequent write fails the session is still
|
||||
// reverted to WAITING_FOR_INPUT by handlePromptError above, so the brief
|
||||
// RUNNING flash is bounded and the UI re-enables the composer.
|
||||
agentMgr.mu.Lock()
|
||||
markCount := len(agentMgr.markPassthroughCalls)
|
||||
agentMgr.mu.Unlock()
|
||||
if markCount != 0 {
|
||||
t.Errorf("MarkPassthroughRunning must not fire on PTY write failure; got %d call(s)", markCount)
|
||||
if markCount != 1 {
|
||||
t.Errorf("MarkPassthroughRunning should fire once before the write; got %d call(s)", markCount)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -229,8 +229,11 @@ func (h *MessageHandlers) wsAddMessage(ctx context.Context, msg *ws.Message) (*w
|
||||
// block and bypass server-side injection of the canonical task/session/
|
||||
// tool context. Wrap unconditionally; the orchestrator's own guard sees
|
||||
// our wrap downstream and skips its second pass.
|
||||
// Passthrough sessions skip the wrap: the prompt is typed straight into
|
||||
// the agent CLI's TTY and the user sees it verbatim — they don't want a
|
||||
// wall of MCP-tool boilerplate prepended to "hello".
|
||||
storedContent := req.Content
|
||||
if isCreatedSession && (req.Content != "" || len(req.Attachments) > 0) {
|
||||
if isCreatedSession && !sessionResp.Session.IsPassthrough && (req.Content != "" || len(req.Attachments) > 0) {
|
||||
storedContent = sysprompt.InjectKandevContext(req.TaskID, req.TaskSessionID, req.Content)
|
||||
req.Content = storedContent
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { agentProfileId as toAgentProfileId, type AgentProfile } from "@/lib/types/http";
|
||||
import { isProfileDirty, type DraftProfile } from "./agent-save-helpers";
|
||||
import { isProfileDirty, toAgentProfilePatch, type DraftProfile } from "./agent-save-helpers";
|
||||
import type { ProfileFormData } from "@/components/settings/profile-form-fields";
|
||||
|
||||
const baseProfile: AgentProfile = {
|
||||
id: toAgentProfileId("p1"),
|
||||
@@ -23,6 +24,32 @@ const draftFrom = (saved: AgentProfile, overrides: Partial<DraftProfile> = {}):
|
||||
|
||||
const ALLOW_ALL_TOOLS_FLAG = "--allow-all-tools";
|
||||
|
||||
describe("toAgentProfilePatch", () => {
|
||||
it("maps snake_case form keys to camelCase AgentProfile fields", () => {
|
||||
const patch: Partial<ProfileFormData> = {
|
||||
name: "CLI",
|
||||
model: "claude-sonnet",
|
||||
mode: "default",
|
||||
allow_indexing: true,
|
||||
cli_passthrough: true,
|
||||
cli_flags: [{ flag: ALLOW_ALL_TOOLS_FLAG, enabled: true, description: "" }],
|
||||
};
|
||||
expect(toAgentProfilePatch(patch)).toEqual({
|
||||
name: "CLI",
|
||||
model: "claude-sonnet",
|
||||
mode: "default",
|
||||
allowIndexing: true,
|
||||
cliPassthrough: true,
|
||||
cliFlags: [{ flag: ALLOW_ALL_TOOLS_FLAG, enabled: true, description: "" }],
|
||||
});
|
||||
});
|
||||
|
||||
it("omits undefined keys so partial patches do not clobber unrelated fields", () => {
|
||||
expect(toAgentProfilePatch({ cli_passthrough: false })).toEqual({ cliPassthrough: false });
|
||||
expect(toAgentProfilePatch({})).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
describe("isProfileDirty", () => {
|
||||
it("returns false when draft equals saved", () => {
|
||||
expect(isProfileDirty(draftFrom(baseProfile), baseProfile)).toBe(false);
|
||||
|
||||
@@ -16,6 +16,25 @@ import type {
|
||||
} from "@/lib/types/http";
|
||||
import { permissionsToProfilePatch, arePermissionsDirty } from "@/lib/agent-permissions";
|
||||
import { areCLIFlagsEqual } from "@/lib/cli-flags";
|
||||
import type { ProfileFormData } from "@/components/settings/profile-form-fields";
|
||||
|
||||
/**
|
||||
* Translates a ProfileFormData patch (snake_case form keys) into a
|
||||
* Partial<AgentProfile> (camelCase). Profiles in client state use the
|
||||
* canonical camelCase AgentProfile shape, so without this translation
|
||||
* patches like { cli_passthrough: true } would land as a new snake_case
|
||||
* key and the camelCase reader would never see them.
|
||||
*/
|
||||
export function toAgentProfilePatch(patch: Partial<ProfileFormData>): Partial<AgentProfile> {
|
||||
const next: Partial<AgentProfile> = {};
|
||||
if (patch.name !== undefined) next.name = patch.name;
|
||||
if (patch.model !== undefined) next.model = patch.model;
|
||||
if (patch.mode !== undefined) next.mode = patch.mode;
|
||||
if (patch.allow_indexing !== undefined) next.allowIndexing = patch.allow_indexing;
|
||||
if (patch.cli_passthrough !== undefined) next.cliPassthrough = patch.cli_passthrough;
|
||||
if (patch.cli_flags !== undefined) next.cliFlags = patch.cli_flags;
|
||||
return next;
|
||||
}
|
||||
|
||||
function areEnvVarsEqual(a?: ProfileEnvVar[], b?: ProfileEnvVar[]): boolean {
|
||||
const left = a ?? [];
|
||||
|
||||
@@ -20,7 +20,7 @@ import { ProfileEnvVarsSection } from "@/components/settings/agent-profile-page"
|
||||
import { CustomCLIFlagsCard } from "@/components/settings/cli-flags-field";
|
||||
import type { Agent, ModelConfig, PermissionSetting, PassthroughConfig } from "@/lib/types/http";
|
||||
import { ProfileMcpConfigCard } from "./profile-mcp-config-card";
|
||||
import type { DraftProfile, DraftAgent } from "./agent-save-helpers";
|
||||
import { toAgentProfilePatch, type DraftProfile, type DraftAgent } from "./agent-save-helpers";
|
||||
|
||||
export type AgentHeaderProps = {
|
||||
displayName: string;
|
||||
@@ -124,7 +124,7 @@ export function ProfileCardItem({
|
||||
cli_passthrough: profile.cliPassthrough ?? false,
|
||||
cli_flags: profile.cliFlags ?? [],
|
||||
}}
|
||||
onChange={(patch) => onProfileChange(profile.id, patch)}
|
||||
onChange={(patch) => onProfileChange(profile.id, toAgentProfilePatch(patch))}
|
||||
modelConfig={currentAgentModelConfig}
|
||||
permissionSettings={permissionSettings}
|
||||
passthroughConfig={passthroughConfig}
|
||||
|
||||
@@ -12,6 +12,7 @@ import { Separator } from "@kandev/ui/separator";
|
||||
import { useToast } from "@/components/toast-provider";
|
||||
import { UnsavedChangesBadge, UnsavedSaveButton } from "@/components/settings/unsaved-indicator";
|
||||
import { ProfileFormFields, type ProfileFormData } from "@/components/settings/profile-form-fields";
|
||||
import { toAgentProfilePatch } from "@/app/settings/agents/[agentId]/agent-save-helpers";
|
||||
import { deleteAgentProfileAction, updateAgentProfileAction } from "@/app/actions/agents";
|
||||
import type { ActiveSessionInfo } from "@/lib/types/agent-profile-errors";
|
||||
import {
|
||||
@@ -171,17 +172,6 @@ function ProfileSettingsCard({
|
||||
);
|
||||
}
|
||||
|
||||
function toAgentProfilePatch(patch: Partial<ProfileFormData>): Partial<AgentProfile> {
|
||||
const next: Partial<AgentProfile> = {};
|
||||
if (patch.name !== undefined) next.name = patch.name;
|
||||
if (patch.model !== undefined) next.model = patch.model;
|
||||
if (patch.mode !== undefined) next.mode = patch.mode;
|
||||
if (patch.allow_indexing !== undefined) next.allowIndexing = patch.allow_indexing;
|
||||
if (patch.cli_passthrough !== undefined) next.cliPassthrough = patch.cli_passthrough;
|
||||
if (patch.cli_flags !== undefined) next.cliFlags = patch.cli_flags;
|
||||
return next;
|
||||
}
|
||||
|
||||
function useSyncAgentsToStore() {
|
||||
const setSettingsAgents = useAppStore((state) => state.setSettingsAgents);
|
||||
const setAgentProfiles = useAppStore((state) => state.setAgentProfiles);
|
||||
|
||||
@@ -23,7 +23,6 @@ function makeProps(
|
||||
isCreateMode: true,
|
||||
isEditMode: false,
|
||||
isTaskStarted: false,
|
||||
isPassthroughProfile: false,
|
||||
isCreatingSession: false,
|
||||
isCreatingTask: false,
|
||||
hasTitle: true,
|
||||
@@ -155,13 +154,15 @@ describe("computeDisabledReason (default)", () => {
|
||||
).toBe(REASON_DESCRIPTION);
|
||||
});
|
||||
|
||||
it("does not flag missing description for passthrough profiles", () => {
|
||||
it("requires description in session mode even for CLI/passthrough profiles", () => {
|
||||
// CLI-mode parity: the backend now auto-injects the prompt into the CLI's
|
||||
// stdin, so the prompt is required just like in ACP mode.
|
||||
expect(
|
||||
computeDisabledReason(
|
||||
makeProps({ isSessionMode: true, hasDescription: false, isPassthroughProfile: true }),
|
||||
makeProps({ isSessionMode: true, hasDescription: false }),
|
||||
KIND_DEFAULT,
|
||||
),
|
||||
).toBeNull();
|
||||
).toBe(REASON_DESCRIPTION);
|
||||
});
|
||||
|
||||
it("ignores base reasons in session mode to match DefaultSubmitButton disabled logic", () => {
|
||||
|
||||
@@ -151,7 +151,6 @@ type DefaultSubmitButtonProps = {
|
||||
isCreateMode: boolean;
|
||||
isEditMode: boolean;
|
||||
hasDescription: boolean;
|
||||
isPassthroughProfile: boolean;
|
||||
disabled: boolean;
|
||||
};
|
||||
|
||||
@@ -162,7 +161,6 @@ function DefaultSubmitButton({
|
||||
isCreateMode,
|
||||
isEditMode,
|
||||
hasDescription,
|
||||
isPassthroughProfile,
|
||||
disabled,
|
||||
}: DefaultSubmitButtonProps) {
|
||||
const planModeStyle =
|
||||
@@ -176,10 +174,7 @@ function DefaultSubmitButton({
|
||||
variant="default"
|
||||
className={`w-full h-10 cursor-pointer sm:w-auto sm:h-7 gap-1.5 ${planModeStyle}`}
|
||||
disabled={
|
||||
disabled ||
|
||||
isCreatingSession ||
|
||||
isCreatingTask ||
|
||||
(isSessionMode ? !hasDescription && !isPassthroughProfile : false)
|
||||
disabled || isCreatingSession || isCreatingTask || (isSessionMode ? !hasDescription : false)
|
||||
}
|
||||
>
|
||||
{(() => {
|
||||
@@ -211,7 +206,6 @@ export type TaskCreateDialogFooterProps = {
|
||||
isCreateMode: boolean;
|
||||
isEditMode: boolean;
|
||||
isTaskStarted: boolean;
|
||||
isPassthroughProfile: boolean;
|
||||
isCreatingSession: boolean;
|
||||
isCreatingTask: boolean;
|
||||
hasTitle: boolean;
|
||||
@@ -291,14 +285,10 @@ function baseReason(props: TaskCreateDialogFooterProps): string | null {
|
||||
return null;
|
||||
}
|
||||
|
||||
function missingSessionDescription(props: TaskCreateDialogFooterProps): boolean {
|
||||
return !props.hasDescription && !props.isPassthroughProfile;
|
||||
}
|
||||
|
||||
function sessionDefaultReason(props: TaskCreateDialogFooterProps): string | null {
|
||||
if (props.noCompatibleAgent) return noCompatibleAgentReason(props.executorProfileName);
|
||||
if (!props.agentProfileId) return REASON_AGENT;
|
||||
if (missingSessionDescription(props)) return REASON_DESCRIPTION;
|
||||
if (!props.hasDescription) return REASON_DESCRIPTION;
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -324,7 +314,7 @@ function resolveButtonKind(props: TaskCreateDialogFooterProps, showStartTask: bo
|
||||
|
||||
function computeFooterState(props: TaskCreateDialogFooterProps) {
|
||||
const showStartTask =
|
||||
(props.isCreateMode && (props.hasDescription || props.isPassthroughProfile)) ||
|
||||
(props.isCreateMode && props.hasDescription) ||
|
||||
Boolean(props.isEditMode && props.agentProfileId);
|
||||
const blocked = Boolean(props.submitBlockedReason);
|
||||
const altDisabled = computeBaseDisabled(props) || blocked;
|
||||
@@ -350,7 +340,6 @@ export const TaskCreateDialogFooter = memo(function TaskCreateDialogFooter(
|
||||
isCreateMode,
|
||||
isEditMode,
|
||||
isTaskStarted,
|
||||
isPassthroughProfile,
|
||||
isCreatingSession,
|
||||
isCreatingTask,
|
||||
hasTitle,
|
||||
@@ -417,7 +406,6 @@ export const TaskCreateDialogFooter = memo(function TaskCreateDialogFooter(
|
||||
isCreateMode={isCreateMode}
|
||||
isEditMode={isEditMode}
|
||||
hasDescription={hasDescription}
|
||||
isPassthroughProfile={isPassthroughProfile}
|
||||
disabled={defaultDisabled}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,12 @@
|
||||
import { createRef } from "react";
|
||||
import { render, screen } from "@testing-library/react";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { CreateEditSelectors, WorkflowSection } from "./task-create-dialog-form-body";
|
||||
import {
|
||||
CreateEditSelectors,
|
||||
DialogPromptSection,
|
||||
WorkflowSection,
|
||||
} from "./task-create-dialog-form-body";
|
||||
import type { DialogFormState, TaskFormInputsHandle } from "./task-create-dialog-types";
|
||||
|
||||
vi.mock("@/components/workflow-selector-row", () => ({
|
||||
WorkflowSelectorRow: ({ selectedWorkflowId }: { selectedWorkflowId: string | null }) => (
|
||||
@@ -8,6 +14,22 @@ vi.mock("@/components/workflow-selector-row", () => ({
|
||||
),
|
||||
}));
|
||||
|
||||
// Capture every render of TaskFormInputs so passthrough-related assertions can
|
||||
// inspect the props that DialogPromptSection forwards to the textarea.
|
||||
const taskFormInputsCalls: Array<Record<string, unknown>> = [];
|
||||
vi.mock("@/components/task-create-dialog-selectors", () => ({
|
||||
TaskFormInputs: (props: Record<string, unknown>) => {
|
||||
taskFormInputsCalls.push(props);
|
||||
return (
|
||||
<textarea
|
||||
data-testid="task-description-textarea"
|
||||
placeholder={(props.placeholder as string | undefined) ?? "default placeholder"}
|
||||
disabled={Boolean(props.disabled)}
|
||||
/>
|
||||
);
|
||||
},
|
||||
}));
|
||||
|
||||
const workflow = { id: "wf-1", name: "Development" };
|
||||
|
||||
function renderWorkflowSection(effectiveWorkflowId: string | null) {
|
||||
@@ -38,6 +60,133 @@ describe("WorkflowSection", () => {
|
||||
});
|
||||
});
|
||||
|
||||
function makeFs(): DialogFormState {
|
||||
return {
|
||||
taskName: "",
|
||||
setTaskName: () => {},
|
||||
hasTitle: false,
|
||||
setHasTitle: () => {},
|
||||
hasDescription: false,
|
||||
setHasDescription: () => {},
|
||||
draftDescription: "",
|
||||
openCycle: 0,
|
||||
currentDefaults: { name: "", description: "" },
|
||||
descriptionInputRef: createRef<TaskFormInputsHandle>(),
|
||||
repositories: [],
|
||||
setRepositories: () => {},
|
||||
addRepository: () => {},
|
||||
removeRepository: () => {},
|
||||
updateRepository: () => {},
|
||||
githubBranch: "",
|
||||
setGitHubBranch: () => {},
|
||||
agentProfileId: "",
|
||||
setAgentProfileId: () => {},
|
||||
executorId: "",
|
||||
setExecutorId: () => {},
|
||||
executorProfileId: "",
|
||||
setExecutorProfileId: () => {},
|
||||
discoveredRepositories: [],
|
||||
setDiscoveredRepositories: () => {},
|
||||
discoverReposLoading: false,
|
||||
setDiscoverReposLoading: () => {},
|
||||
discoverReposLoaded: false,
|
||||
setDiscoverReposLoaded: () => {},
|
||||
selectedWorkflowId: null,
|
||||
setSelectedWorkflowId: () => {},
|
||||
fetchedSteps: null,
|
||||
setFetchedSteps: () => {},
|
||||
isCreatingSession: false,
|
||||
setIsCreatingSession: () => {},
|
||||
isCreatingTask: false,
|
||||
setIsCreatingTask: () => {},
|
||||
useGitHubUrl: false,
|
||||
setUseGitHubUrl: () => {},
|
||||
githubUrl: "",
|
||||
setGitHubUrl: () => {},
|
||||
githubBranches: [],
|
||||
setGitHubBranches: () => {},
|
||||
githubBranchesLoading: false,
|
||||
setGitHubBranchesLoading: () => {},
|
||||
githubUrlError: null,
|
||||
setGitHubUrlError: () => {},
|
||||
githubPrHeadBranch: null,
|
||||
setGitHubPrHeadBranch: () => {},
|
||||
githubPrBaseBranch: null,
|
||||
setGitHubPrBaseBranch: () => {},
|
||||
workflowAgentProfileId: "",
|
||||
setWorkflowAgentProfileId: () => {},
|
||||
clearDraft: () => {},
|
||||
freshBranchEnabled: false,
|
||||
setFreshBranchEnabled: () => {},
|
||||
currentLocalBranch: "",
|
||||
setCurrentLocalBranch: () => {},
|
||||
currentLocalBranchLoading: false,
|
||||
setCurrentLocalBranchLoading: () => {},
|
||||
noRepository: false,
|
||||
setNoRepository: () => {},
|
||||
workspacePath: "",
|
||||
setWorkspacePath: () => {},
|
||||
};
|
||||
}
|
||||
|
||||
describe("DialogPromptSection (CLI-mode parity)", () => {
|
||||
it("keeps the prompt textarea enabled when the selected profile is passthrough", () => {
|
||||
taskFormInputsCalls.length = 0;
|
||||
render(
|
||||
<DialogPromptSection
|
||||
isSessionMode={false}
|
||||
isTaskStarted={false}
|
||||
initialDescription=""
|
||||
fs={makeFs()}
|
||||
handleKeyDown={(() => {}) as never}
|
||||
descriptionPlaceholder="Write a prompt for the agent..."
|
||||
/>,
|
||||
);
|
||||
|
||||
const textarea = screen.getByTestId("task-description-textarea") as HTMLTextAreaElement;
|
||||
expect(textarea.disabled).toBe(false);
|
||||
expect(textarea.placeholder).toBe("Write a prompt for the agent...");
|
||||
const last = taskFormInputsCalls.at(-1)!;
|
||||
expect(last.disabled).toBe(false);
|
||||
expect(last.placeholder).toBe("Write a prompt for the agent...");
|
||||
});
|
||||
|
||||
it("does not render the legacy 'Prompt ignored — passthrough mode active' warning", () => {
|
||||
const { container } = render(
|
||||
<DialogPromptSection
|
||||
isSessionMode={false}
|
||||
isTaskStarted={false}
|
||||
initialDescription="hello"
|
||||
fs={makeFs()}
|
||||
handleKeyDown={(() => {}) as never}
|
||||
/>,
|
||||
);
|
||||
|
||||
expect(container.textContent).not.toMatch(/prompt ignored/i);
|
||||
expect(container.textContent).not.toMatch(/passthrough mode/i);
|
||||
});
|
||||
|
||||
it("allows Jira/Linear import in passthrough (CLI) mode", () => {
|
||||
taskFormInputsCalls.length = 0;
|
||||
render(
|
||||
<DialogPromptSection
|
||||
isSessionMode={false}
|
||||
isTaskStarted={false}
|
||||
initialDescription=""
|
||||
fs={makeFs()}
|
||||
handleKeyDown={(() => {}) as never}
|
||||
workspaceId="ws-1"
|
||||
onJiraImport={() => {}}
|
||||
onLinearImport={() => {}}
|
||||
/>,
|
||||
);
|
||||
|
||||
const last = taskFormInputsCalls.at(-1)!;
|
||||
expect((last.jiraImport as { disabled: boolean } | undefined)?.disabled).toBe(false);
|
||||
expect((last.linearImport as { disabled: boolean } | undefined)?.disabled).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("CreateEditSelectors", () => {
|
||||
it("links credential setup to the selected executor profile", () => {
|
||||
const EmptySelector = () => <button type="button">selector</button>;
|
||||
|
||||
@@ -350,9 +350,7 @@ export const WorkflowSection = memo(function WorkflowSection({
|
||||
export type DialogPromptSectionProps = {
|
||||
isSessionMode: boolean;
|
||||
isTaskStarted: boolean;
|
||||
isPassthroughProfile: boolean;
|
||||
initialDescription: string;
|
||||
hasDescription: boolean;
|
||||
fs: DialogFormState;
|
||||
handleKeyDown: ReturnType<typeof useKeyboardShortcutHandler>;
|
||||
enhance?: { onEnhance: () => void; isLoading: boolean; isConfigured: boolean };
|
||||
@@ -380,19 +378,16 @@ export type DialogPromptSectionProps = {
|
||||
function importBindings<T>(
|
||||
enabled: boolean,
|
||||
workspaceId: string | null,
|
||||
isPassthroughProfile: boolean,
|
||||
onImport: ((value: T) => void) | undefined,
|
||||
) {
|
||||
if (!enabled || !onImport) return undefined;
|
||||
return { workspaceId, disabled: isPassthroughProfile, onImport };
|
||||
return { workspaceId, disabled: false, onImport };
|
||||
}
|
||||
|
||||
export function DialogPromptSection({
|
||||
isSessionMode,
|
||||
isTaskStarted,
|
||||
isPassthroughProfile,
|
||||
initialDescription,
|
||||
hasDescription,
|
||||
fs,
|
||||
handleKeyDown,
|
||||
enhance,
|
||||
@@ -406,9 +401,6 @@ export function DialogPromptSection({
|
||||
}: DialogPromptSectionProps) {
|
||||
const importsEnabled = !isSessionMode && !isTaskStarted;
|
||||
const ws = workspaceId ?? null;
|
||||
const placeholder = isPassthroughProfile
|
||||
? "Passthrough mode — prompt not supported"
|
||||
: descriptionPlaceholder;
|
||||
const shouldAutoFocus = autoFocusDescription ?? !isTaskStarted;
|
||||
return (
|
||||
<>
|
||||
@@ -421,18 +413,15 @@ export function DialogPromptSection({
|
||||
onDescriptionChange={fs.setHasDescription}
|
||||
onKeyDown={handleKeyDown}
|
||||
descriptionValueRef={fs.descriptionInputRef}
|
||||
disabled={isTaskStarted || isPassthroughProfile}
|
||||
placeholder={placeholder}
|
||||
disabled={isTaskStarted}
|
||||
placeholder={descriptionPlaceholder}
|
||||
onEnhancePrompt={enhance?.onEnhance}
|
||||
isEnhancingPrompt={enhance?.isLoading}
|
||||
isUtilityConfigured={enhance?.isConfigured}
|
||||
jiraImport={importBindings(importsEnabled, ws, isPassthroughProfile, onJiraImport)}
|
||||
linearImport={importBindings(importsEnabled, ws, isPassthroughProfile, onLinearImport)}
|
||||
jiraImport={importBindings(importsEnabled, ws, onJiraImport)}
|
||||
linearImport={importBindings(importsEnabled, ws, onLinearImport)}
|
||||
/>
|
||||
{extraFormSlot}
|
||||
{isPassthroughProfile && hasDescription && (
|
||||
<p className="text-xs text-amber-500">Prompt ignored — passthrough mode active</p>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -141,7 +141,7 @@ export function useAgentProfileOptions(agentProfiles: AgentProfileOption[]): Opt
|
||||
{isPassthrough && (
|
||||
<IconTerminal2
|
||||
className="size-3.5 text-muted-foreground"
|
||||
title="Passthrough terminal"
|
||||
title="CLI mode - your prompt will be auto-injected into the terminal"
|
||||
/>
|
||||
)}
|
||||
{profileLabel ? (
|
||||
|
||||
@@ -34,9 +34,7 @@ export function buildDialogFormBodyProps(
|
||||
onTaskNameChange: handlers.handleTaskNameChange,
|
||||
onRowRepositoryChange: handlers.handleRowRepositoryChange,
|
||||
onRowBranchChange: handlers.handleRowBranchChange,
|
||||
isPassthroughProfile: computed.isPassthroughProfile,
|
||||
initialDescription: fs.currentDefaults.description,
|
||||
hasDescription: fs.hasDescription,
|
||||
workspaceId: props.workspaceId,
|
||||
onJiraImport: setup.handleJiraImport,
|
||||
onLinearImport: setup.handleLinearImport,
|
||||
@@ -84,7 +82,6 @@ export function buildDialogFooterProps(
|
||||
isCreateMode: setup.isCreateMode,
|
||||
isEditMode: setup.isEditMode,
|
||||
isTaskStarted: setup.isTaskStarted,
|
||||
isPassthroughProfile: computed.isPassthroughProfile,
|
||||
isCreatingSession: fs.isCreatingSession,
|
||||
isCreatingTask: fs.isCreatingTask,
|
||||
hasTitle: fs.hasTitle,
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||
import { renderHook, act } from "@testing-library/react";
|
||||
import { createRef } from "react";
|
||||
|
||||
// All external module mocks must be declared with vi.mock before the import of
|
||||
// the unit under test so vitest hoists them. The mocks below capture the
|
||||
// arguments passed to the createTask / launchSession boundaries so we can
|
||||
// assert that handleCreateSubmit honours CLI-mode parity: empty prompt → no
|
||||
// create call; non-empty prompt → call with that prompt in the payload.
|
||||
|
||||
const pushMock = vi.fn();
|
||||
vi.mock("next/navigation", () => ({
|
||||
useRouter: () => ({ push: pushMock, replace: vi.fn(), back: vi.fn() }),
|
||||
}));
|
||||
|
||||
const toastMock = vi.fn();
|
||||
vi.mock("@/components/toast-provider", () => ({
|
||||
useToast: () => ({ toast: toastMock }),
|
||||
}));
|
||||
|
||||
vi.mock("@/components/state-provider", () => ({
|
||||
useAppStore: (selector: (s: unknown) => unknown) =>
|
||||
selector({ setActiveDocument: vi.fn(), setPlanMode: vi.fn() }),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/api", () => ({
|
||||
updateTask: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/services/session-launch-service", () => ({
|
||||
launchSession: vi.fn(async () => ({ session_id: "session-1" })),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/services/session-launch-helpers", () => ({
|
||||
buildStartRequest: () => ({ request: { taskId: "t", agentProfileId: "a" } }),
|
||||
}));
|
||||
|
||||
const buildCreateTaskPayloadMock = vi.fn((..._args: unknown[]) => ({
|
||||
workflow_step_id: "step-1",
|
||||
}));
|
||||
const validateCreateInputsMock = vi.fn((..._args: unknown[]) => true);
|
||||
vi.mock("@/components/task-create-dialog-helpers", () => ({
|
||||
activatePlanMode: vi.fn(),
|
||||
buildCreateTaskPayload: (...args: unknown[]) => buildCreateTaskPayloadMock(...args),
|
||||
buildRepositoriesPayload: () => [],
|
||||
validateCreateInputs: (...args: unknown[]) => validateCreateInputsMock(...args),
|
||||
toMessageAttachments: () => [],
|
||||
}));
|
||||
|
||||
const createTaskRetryMock = vi.fn(async (buildPayload: (consented: string[]) => unknown) => {
|
||||
// Invoke the build function so payload-construction side effects (and
|
||||
// assertions on it) run as they would in production.
|
||||
buildPayload([]);
|
||||
return { id: "task-1", session_id: "session-1" };
|
||||
});
|
||||
vi.mock("@/components/task-create-dialog-fresh-branch-consent", () => ({
|
||||
useFreshBranchConsent: () => ({
|
||||
pendingDiscard: null,
|
||||
ensureFreshBranchConsent: vi.fn(async () => []),
|
||||
createTaskWithFreshBranchRetry: (...args: unknown[]) =>
|
||||
createTaskRetryMock(args[0] as (consented: string[]) => unknown),
|
||||
}),
|
||||
}));
|
||||
|
||||
import { useTaskSubmitHandlers } from "./task-create-dialog-submit";
|
||||
import type { SubmitHandlersDeps, TaskFormInputsHandle } from "./task-create-dialog-types";
|
||||
|
||||
function makeRef(value: string): React.RefObject<TaskFormInputsHandle | null> {
|
||||
const ref = createRef<TaskFormInputsHandle>();
|
||||
ref.current = {
|
||||
getValue: () => value,
|
||||
setValue: () => {},
|
||||
getAttachments: () => [],
|
||||
};
|
||||
return ref;
|
||||
}
|
||||
|
||||
function makeDeps(overrides: Partial<SubmitHandlersDeps>): SubmitHandlersDeps {
|
||||
return {
|
||||
isSessionMode: false,
|
||||
isEditMode: false,
|
||||
isPassthroughProfile: false,
|
||||
taskName: "My CLI task",
|
||||
workspaceId: "ws-1",
|
||||
workflowId: "wf-1",
|
||||
effectiveWorkflowId: "wf-1",
|
||||
effectiveDefaultStepId: "step-1",
|
||||
repositories: [],
|
||||
discoveredRepositories: [],
|
||||
workspaceRepositories: [],
|
||||
useGitHubUrl: false,
|
||||
githubUrl: "",
|
||||
githubPrHeadBranch: null,
|
||||
githubPrBaseBranch: null,
|
||||
githubBranch: "",
|
||||
agentProfileId: "agent-1",
|
||||
executorId: "exec-1",
|
||||
executorProfileId: "execp-1",
|
||||
editingTask: null,
|
||||
onSuccess: vi.fn(),
|
||||
onOpenChange: vi.fn(),
|
||||
taskId: null,
|
||||
descriptionInputRef: makeRef(""),
|
||||
setIsCreatingSession: vi.fn(),
|
||||
setIsCreatingTask: vi.fn(),
|
||||
setHasTitle: vi.fn(),
|
||||
setHasDescription: vi.fn(),
|
||||
setTaskName: vi.fn(),
|
||||
setRepositories: vi.fn(),
|
||||
setGitHubBranch: vi.fn(),
|
||||
setAgentProfileId: vi.fn(),
|
||||
setExecutorId: vi.fn(),
|
||||
setSelectedWorkflowId: vi.fn(),
|
||||
setFetchedSteps: vi.fn(),
|
||||
clearDraft: vi.fn(),
|
||||
freshBranchEnabled: false,
|
||||
isLocalExecutor: false,
|
||||
repositoryLocalPath: "",
|
||||
noRepository: true,
|
||||
workspacePath: "",
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
buildCreateTaskPayloadMock.mockClear();
|
||||
validateCreateInputsMock.mockClear();
|
||||
createTaskRetryMock.mockClear();
|
||||
pushMock.mockClear();
|
||||
toastMock.mockClear();
|
||||
});
|
||||
|
||||
describe("useTaskSubmitHandlers — handleCreateSubmit (CLI-mode parity)", () => {
|
||||
it("skips create when prompt is empty even with cli_passthrough=true (prompt is now required)", async () => {
|
||||
const deps = makeDeps({
|
||||
isPassthroughProfile: true,
|
||||
descriptionInputRef: makeRef(""),
|
||||
});
|
||||
const { result } = renderHook(() => useTaskSubmitHandlers(deps));
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleSubmit({ preventDefault: () => {} } as never);
|
||||
});
|
||||
|
||||
// The plan-mode fallback (handleCreatePlanMode) is what runs when there's
|
||||
// no description; verify it was the only path exercised by inspecting the
|
||||
// build payload — handleCreatePlanMode builds with withAgent:false, while
|
||||
// a passthrough-with-prompt path would build with withAgent:true.
|
||||
const calls = buildCreateTaskPayloadMock.mock.calls;
|
||||
expect(calls.length).toBe(1);
|
||||
expect((calls[0]![0] as { withAgent: boolean }).withAgent).toBe(false);
|
||||
});
|
||||
|
||||
it("creates the task with the user's prompt when cli_passthrough=true and prompt is provided", async () => {
|
||||
const deps = makeDeps({
|
||||
isPassthroughProfile: true,
|
||||
descriptionInputRef: makeRef("run npm test"),
|
||||
});
|
||||
const { result } = renderHook(() => useTaskSubmitHandlers(deps));
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleSubmit({ preventDefault: () => {} } as never);
|
||||
});
|
||||
|
||||
expect(buildCreateTaskPayloadMock).toHaveBeenCalledTimes(1);
|
||||
const payloadArg = buildCreateTaskPayloadMock.mock.calls[0]![0] as {
|
||||
withAgent: boolean;
|
||||
trimmedDescription: string;
|
||||
};
|
||||
expect(payloadArg.withAgent).toBe(true);
|
||||
expect(payloadArg.trimmedDescription).toBe("run npm test");
|
||||
});
|
||||
|
||||
it("still creates the task in ACP mode when prompt is provided", async () => {
|
||||
const deps = makeDeps({
|
||||
isPassthroughProfile: false,
|
||||
descriptionInputRef: makeRef("refactor module"),
|
||||
});
|
||||
const { result } = renderHook(() => useTaskSubmitHandlers(deps));
|
||||
|
||||
await act(async () => {
|
||||
await result.current.handleSubmit({ preventDefault: () => {} } as never);
|
||||
});
|
||||
|
||||
const payloadArg = buildCreateTaskPayloadMock.mock.calls[0]![0] as {
|
||||
withAgent: boolean;
|
||||
trimmedDescription: string;
|
||||
};
|
||||
expect(payloadArg.withAgent).toBe(true);
|
||||
expect(payloadArg.trimmedDescription).toBe("refactor module");
|
||||
});
|
||||
});
|
||||
@@ -162,7 +162,7 @@ export function useTaskSubmitHandlers({
|
||||
const trimmedDescription = description.trim();
|
||||
const attachments = descriptionInputRef.current?.getAttachments() ?? [];
|
||||
if (!agentProfileId) return;
|
||||
if (!trimmedDescription && !isPassthroughProfile) return;
|
||||
if (!trimmedDescription) return;
|
||||
|
||||
if (onCreateSession) {
|
||||
onCreateSession({ prompt: trimmedDescription, agentProfileId, executorId });
|
||||
@@ -197,7 +197,6 @@ export function useTaskSubmitHandlers({
|
||||
agentProfileId,
|
||||
executorId,
|
||||
executorProfileId,
|
||||
isPassthroughProfile,
|
||||
onCreateSession,
|
||||
onOpenChange,
|
||||
router,
|
||||
@@ -467,7 +466,7 @@ export function useTaskSubmitHandlers({
|
||||
if (consent === null) return;
|
||||
setIsCreatingTask(true);
|
||||
try {
|
||||
if (trimmedDescription || isPassthroughProfile) {
|
||||
if (trimmedDescription) {
|
||||
const finalDescription = transformDescriptionBeforeSubmit
|
||||
? await transformDescriptionBeforeSubmit(trimmedDescription)
|
||||
: trimmedDescription;
|
||||
@@ -492,7 +491,6 @@ export function useTaskSubmitHandlers({
|
||||
}
|
||||
}, [
|
||||
taskName,
|
||||
isPassthroughProfile,
|
||||
validateForCreate,
|
||||
ensureFreshBranchConsent,
|
||||
performCreate,
|
||||
|
||||
@@ -321,9 +321,7 @@ export type DialogFormBodyProps = {
|
||||
isCreateMode: boolean;
|
||||
isEditMode: boolean;
|
||||
isTaskStarted: boolean;
|
||||
isPassthroughProfile: boolean;
|
||||
initialDescription: string;
|
||||
hasDescription: boolean;
|
||||
workspaceId: string | null;
|
||||
onJiraImport?: (ticket: JiraTicket) => void;
|
||||
onLinearImport?: (issue: LinearIssue) => void;
|
||||
|
||||
@@ -159,9 +159,7 @@ function CreateModeBody(props: DialogFormBodyProps) {
|
||||
<DialogPromptSection
|
||||
isSessionMode={false}
|
||||
isTaskStarted={isTaskStarted}
|
||||
isPassthroughProfile={props.isPassthroughProfile}
|
||||
initialDescription={props.initialDescription}
|
||||
hasDescription={props.hasDescription}
|
||||
fs={fs}
|
||||
handleKeyDown={props.handleKeyDown}
|
||||
enhance={props.enhance}
|
||||
@@ -199,9 +197,7 @@ function SessionModeBody(props: DialogFormBodyProps) {
|
||||
<DialogPromptSection
|
||||
isSessionMode
|
||||
isTaskStarted={props.isTaskStarted}
|
||||
isPassthroughProfile={props.isPassthroughProfile}
|
||||
initialDescription={props.initialDescription}
|
||||
hasDescription={props.hasDescription}
|
||||
fs={props.fs}
|
||||
handleKeyDown={props.handleKeyDown}
|
||||
enhance={props.enhance}
|
||||
|
||||
@@ -239,7 +239,7 @@ export function useChatPanelHandlers(
|
||||
return { handleCancelTurn };
|
||||
}
|
||||
|
||||
function PRMergedBanner({ taskId }: { taskId: string }) {
|
||||
export function PRMergedBanner({ taskId }: { taskId: string }) {
|
||||
const taskPRs = useAppStore((state) => state.taskPRs.byTaskId[taskId]);
|
||||
const [dismissed, setDismissed] = useState(false);
|
||||
const archiveAndSwitch = useArchiveAndSwitchTask();
|
||||
|
||||
@@ -39,7 +39,7 @@ import { ChangesPanel } from "./changes-panel";
|
||||
import { FilesPanel } from "./files-panel";
|
||||
import { TaskPlanPanel } from "./task-plan-panel";
|
||||
import { FileEditorPanel } from "./file-editor-panel";
|
||||
import { PassthroughTerminal } from "./passthrough-terminal";
|
||||
import { PassthroughToolbar } from "./passthrough-toolbar";
|
||||
import { PanelRoot, PanelBody } from "./panel-primitives";
|
||||
import { ContextMenuTab } from "./tab-context-menu";
|
||||
import { ChangesTab } from "./changes-tab";
|
||||
@@ -248,6 +248,7 @@ function ChatContent({ panelId, params }: { panelId: string; params: Record<stri
|
||||
const paramSessionId = params?.sessionId as string | undefined;
|
||||
const storeSessionId = useAppStore((state) => state.tasks.activeSessionId);
|
||||
const sessionId = paramSessionId ?? storeSessionId;
|
||||
const taskId = useAppStore((state) => state.tasks.activeTaskId);
|
||||
const { openFile } = useFileEditors();
|
||||
const isPassthrough = useAppStore((state) =>
|
||||
sessionId ? state.taskSessions.items[sessionId]?.is_passthrough === true : false,
|
||||
@@ -258,7 +259,7 @@ function ChatContent({ panelId, params }: { panelId: string; params: Record<stri
|
||||
return (
|
||||
<PanelRoot>
|
||||
<PanelBody padding={false} scroll={false}>
|
||||
<PassthroughTerminal sessionId={sessionId} mode="agent" />
|
||||
<PassthroughToolbar sessionId={sessionId} taskId={taskId} />
|
||||
</PanelBody>
|
||||
</PanelRoot>
|
||||
);
|
||||
|
||||
@@ -21,7 +21,7 @@ import { ChangesPanel } from "./changes-panel";
|
||||
import { FilesPanel } from "./files-panel";
|
||||
import { TaskPlanPanel } from "./task-plan-panel";
|
||||
import { FileEditorPanel } from "./file-editor-panel";
|
||||
import { PassthroughTerminal } from "./passthrough-terminal";
|
||||
import { PassthroughToolbar } from "./passthrough-toolbar";
|
||||
import { PanelRoot, PanelBody } from "./panel-primitives";
|
||||
import { ContextMenuTab } from "./tab-context-menu";
|
||||
import { ChangesTab } from "./changes-tab";
|
||||
@@ -192,6 +192,12 @@ function ChatContent({ panelId, params }: { panelId: string; params: Record<stri
|
||||
const paramSessionId = params?.sessionId as string | undefined;
|
||||
const storeSessionId = useAppStore((state) => state.tasks.activeSessionId);
|
||||
const sessionId = paramSessionId ?? storeSessionId;
|
||||
const taskId = useAppStore((state) => {
|
||||
if (sessionId) {
|
||||
return state.taskSessions.items[sessionId]?.task_id ?? state.tasks.activeTaskId;
|
||||
}
|
||||
return state.tasks.activeTaskId;
|
||||
});
|
||||
const { openFile } = useFileEditors();
|
||||
const isPassthrough = useAppStore((state) =>
|
||||
sessionId ? state.taskSessions.items[sessionId]?.is_passthrough === true : false,
|
||||
@@ -202,7 +208,7 @@ function ChatContent({ panelId, params }: { panelId: string; params: Record<stri
|
||||
return (
|
||||
<PanelRoot>
|
||||
<PanelBody padding={false} scroll={false}>
|
||||
<PassthroughTerminal sessionId={sessionId} mode="agent" />
|
||||
<PassthroughToolbar sessionId={sessionId} taskId={taskId} />
|
||||
</PanelBody>
|
||||
</PanelRoot>
|
||||
);
|
||||
|
||||
@@ -11,7 +11,7 @@ import { MobileChangesPanel } from "./mobile-changes-panel";
|
||||
import { ReviewDialog } from "@/components/review/review-dialog";
|
||||
import { useReviewDialog } from "../use-review-dialog";
|
||||
import { TaskFilesPanel } from "../task-files-panel";
|
||||
import { PassthroughTerminal } from "../passthrough-terminal";
|
||||
import { PassthroughToolbar } from "../passthrough-toolbar";
|
||||
import { MobileTerminalKeybar, KEYBAR_HEIGHT_PX } from "./mobile-terminal-keybar";
|
||||
import { MobileTerminalPane } from "./mobile-terminal-pane";
|
||||
import { MobileSessionsPicker } from "./mobile-sessions-section";
|
||||
@@ -67,11 +67,10 @@ function MobileChatPanelContent({
|
||||
</div>
|
||||
{isPassthroughMode ? (
|
||||
<div className="flex-1 min-h-0">
|
||||
<PassthroughTerminal
|
||||
<PassthroughToolbar
|
||||
key={effectiveSessionId}
|
||||
sessionId={effectiveSessionId}
|
||||
mode="agent"
|
||||
enableTouchScroll
|
||||
taskId={activeTaskId}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
|
||||
@@ -0,0 +1,124 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
useCallback,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useRef,
|
||||
useState,
|
||||
type KeyboardEvent,
|
||||
} from "react";
|
||||
import { IconSend } from "@tabler/icons-react";
|
||||
import { Button } from "@kandev/ui/button";
|
||||
import { Textarea } from "@kandev/ui/textarea";
|
||||
|
||||
// Cap matches the `max-h-32` Tailwind class on the textarea below — 128 px.
|
||||
const COMPOSER_MAX_HEIGHT_PX = 128;
|
||||
|
||||
/**
|
||||
* PassthroughComposer is the kandev-controlled compose box rendered alongside
|
||||
* the PTY in passthrough mode. Submitting forwards the typed text via the
|
||||
* onSubmit prop (which posts `message.add` over WS); the backend's
|
||||
* `Executor.Prompt` routes passthrough sessions to PTY stdin so the CLI agent
|
||||
* actually receives it. Enter submits; Shift+Enter inserts a newline.
|
||||
*/
|
||||
export function PassthroughComposer({
|
||||
onSubmit,
|
||||
onCancel,
|
||||
autoFocus = false,
|
||||
placeholder = "Message the CLI agent (Enter to send, Shift+Enter for newline)",
|
||||
header,
|
||||
}: {
|
||||
onSubmit: (content: string) => Promise<void>;
|
||||
onCancel?: () => void;
|
||||
autoFocus?: boolean;
|
||||
placeholder?: string;
|
||||
/** Optional content rendered above the textarea — e.g. a pending-comments preview. */
|
||||
header?: React.ReactNode;
|
||||
}) {
|
||||
const [value, setValue] = useState("");
|
||||
const [isSending, setIsSending] = useState(false);
|
||||
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
const trimmed = value.trim();
|
||||
const canSubmit = trimmed.length > 0 && !isSending;
|
||||
|
||||
// Auto-grow the textarea with content (Shift+Enter newlines, long pastes)
|
||||
// up to the max-h-32 cap. Done in JS so it works in browsers without
|
||||
// CSS field-sizing support.
|
||||
useLayoutEffect(() => {
|
||||
const el = textareaRef.current;
|
||||
if (!el) return;
|
||||
el.style.height = "auto";
|
||||
el.style.height = `${Math.min(el.scrollHeight, COMPOSER_MAX_HEIGHT_PX)}px`;
|
||||
}, [value]);
|
||||
|
||||
useEffect(() => {
|
||||
if (autoFocus) {
|
||||
textareaRef.current?.focus();
|
||||
}
|
||||
}, [autoFocus]);
|
||||
|
||||
const submit = useCallback(async () => {
|
||||
if (!canSubmit) return;
|
||||
setIsSending(true);
|
||||
try {
|
||||
await onSubmit(trimmed);
|
||||
setValue(""); // only clear on success — preserve text so user can retry on send failure
|
||||
} catch {
|
||||
// onSubmit already surfaced the error via toast; the user's typed value
|
||||
// stays in the textarea intentionally so they can retry without retyping.
|
||||
} finally {
|
||||
setIsSending(false);
|
||||
}
|
||||
}, [canSubmit, onSubmit, trimmed]);
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
if (e.nativeEvent.isComposing) return;
|
||||
e.preventDefault();
|
||||
void submit();
|
||||
return;
|
||||
}
|
||||
if (e.key === "Escape" && onCancel) {
|
||||
e.preventDefault();
|
||||
onCancel();
|
||||
}
|
||||
},
|
||||
[submit, onCancel],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex flex-col flex-shrink-0 border-t bg-card"
|
||||
data-testid="passthrough-composer"
|
||||
>
|
||||
{header}
|
||||
<div className="flex items-end gap-2 px-2 py-2">
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder={placeholder}
|
||||
rows={1}
|
||||
disabled={isSending}
|
||||
className="min-h-9 max-h-32 flex-1 resize-none overflow-y-auto"
|
||||
data-testid="passthrough-composer-textarea"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="default"
|
||||
onClick={() => void submit()}
|
||||
disabled={!canSubmit}
|
||||
className="cursor-pointer h-9 shrink-0"
|
||||
data-testid="passthrough-composer-submit"
|
||||
aria-label="Send message to CLI agent"
|
||||
>
|
||||
<IconSend className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,387 @@
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
// --- Constants declared before vi.mock so factories can reference them ---
|
||||
const TASK_ID = "task-1";
|
||||
const SESSION_ID = "session-1";
|
||||
|
||||
// data-testid constants to avoid sonarjs/no-duplicate-string warnings
|
||||
const TID_TOOLBAR = "passthrough-toolbar";
|
||||
const TID_COMPOSER = "passthrough-composer";
|
||||
const TID_TEXTAREA = "passthrough-composer-textarea";
|
||||
const TID_PROCEED = "passthrough-proceed-next-step";
|
||||
const TID_TOGGLE = "passthrough-toggle-composer";
|
||||
const TID_TOGGLE_COMMENTS = "passthrough-toggle-comments";
|
||||
const TID_COMMENTS_PANEL = "passthrough-comments-panel";
|
||||
const TID_COMMENT_CARD = "passthrough-comment-card";
|
||||
const TID_COMMENT_TEXTAREA = "passthrough-comment-textarea";
|
||||
const TID_COMMENT_REMOVE = "passthrough-comment-remove";
|
||||
const TID_COMMENT_FILE_REF = "passthrough-comment-file-ref";
|
||||
const TID_PENDING_COUNT = "passthrough-pending-count";
|
||||
const TID_PENDING_BANNER = "passthrough-pending-comments-banner";
|
||||
|
||||
// --- Mutable state for per-test overrides ---
|
||||
let mockSessionState: string | null = null;
|
||||
let mockPendingByFile: Record<string, import("@/lib/state/slices/comments").DiffComment[]> = {};
|
||||
let mockNextStep: {
|
||||
proceedStepName: string | null;
|
||||
proceed: ReturnType<typeof vi.fn>;
|
||||
isMoving: boolean;
|
||||
} = { proceedStepName: null, proceed: vi.fn(), isMoving: false };
|
||||
|
||||
const mockToast = vi.fn();
|
||||
const mockMarkCommentsSent = vi.fn();
|
||||
const mockUpdateComment = vi.fn();
|
||||
const mockRemoveComment = vi.fn();
|
||||
const mockOpenFile = vi.fn();
|
||||
let mockWsRequestFn = vi.fn();
|
||||
|
||||
// --- Module mocks (hoisted by Vitest) ---
|
||||
|
||||
vi.mock("@/components/state-provider", () => ({
|
||||
useAppStore: (selector: (state: Record<string, unknown>) => unknown) =>
|
||||
selector({
|
||||
taskSessions: {
|
||||
items: mockSessionState
|
||||
? { [SESSION_ID]: { id: SESSION_ID, state: mockSessionState } }
|
||||
: {},
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@/components/toast-provider", () => ({
|
||||
useToast: () => ({ toast: mockToast }),
|
||||
}));
|
||||
|
||||
vi.mock("@/hooks/domains/kanban/use-plan-actions", () => ({
|
||||
useNextWorkflowStep: () => mockNextStep,
|
||||
}));
|
||||
|
||||
vi.mock("@/hooks/domains/comments/use-diff-comments", () => ({
|
||||
usePendingDiffCommentsByFile: () => mockPendingByFile,
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/state/slices/comments/comments-store", () => ({
|
||||
useCommentsStore: (
|
||||
selector: (s: {
|
||||
markCommentsSent: typeof mockMarkCommentsSent;
|
||||
updateComment: typeof mockUpdateComment;
|
||||
removeComment: typeof mockRemoveComment;
|
||||
}) => unknown,
|
||||
) =>
|
||||
selector({
|
||||
markCommentsSent: mockMarkCommentsSent,
|
||||
updateComment: mockUpdateComment,
|
||||
removeComment: mockRemoveComment,
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@/hooks/use-file-editors", () => ({
|
||||
useFileEditors: () => ({ openFile: mockOpenFile }),
|
||||
}));
|
||||
|
||||
vi.mock("@/lib/ws/connection", () => ({
|
||||
getWebSocketClient: () => ({ request: mockWsRequestFn }),
|
||||
}));
|
||||
|
||||
// Stub heavy sub-components that involve xterm / canvas / WebGL.
|
||||
vi.mock("./passthrough-terminal", () => ({
|
||||
PassthroughTerminal: () => <div data-testid="passthrough-terminal-stub" />,
|
||||
}));
|
||||
|
||||
vi.mock("@/components/github/pr-status-chip", () => ({
|
||||
PRStatusChip: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("./chat/chat-input-area", () => ({
|
||||
PRMergedBanner: () => null,
|
||||
}));
|
||||
|
||||
vi.mock("@kandev/ui/tooltip", () => ({
|
||||
Tooltip: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
TooltipTrigger: ({
|
||||
asChild: _asChild,
|
||||
children,
|
||||
}: {
|
||||
asChild?: boolean;
|
||||
children: React.ReactNode;
|
||||
}) => <>{children}</>,
|
||||
TooltipContent: ({ children }: { children: React.ReactNode }) => <>{children}</>,
|
||||
}));
|
||||
|
||||
// Import after mocks
|
||||
import { PassthroughToolbar } from "./passthrough-toolbar";
|
||||
|
||||
// Helper to build a DiffComment with required fields
|
||||
function makeDiffComment(id: string): import("@/lib/state/slices/comments").DiffComment {
|
||||
return {
|
||||
id,
|
||||
source: "diff",
|
||||
sessionId: SESSION_ID,
|
||||
filePath: "src/foo.ts",
|
||||
startLine: 1,
|
||||
endLine: 1,
|
||||
side: "additions",
|
||||
codeContent: "const x = 1;",
|
||||
text: "Fix this",
|
||||
status: "pending",
|
||||
createdAt: new Date().toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
function renderToolbar() {
|
||||
return render(<PassthroughToolbar sessionId={SESSION_ID} taskId={TASK_ID} />);
|
||||
}
|
||||
|
||||
async function openComposer() {
|
||||
fireEvent.click(screen.getByTestId(TID_TOGGLE));
|
||||
await waitFor(() => expect(screen.getByTestId(TID_COMPOSER)).toBeTruthy());
|
||||
}
|
||||
|
||||
function resetMocks() {
|
||||
mockSessionState = null;
|
||||
mockPendingByFile = {};
|
||||
mockNextStep = { proceedStepName: null, proceed: vi.fn(), isMoving: false };
|
||||
mockWsRequestFn = vi.fn().mockResolvedValue(undefined);
|
||||
vi.clearAllMocks();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Default / idle state
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("PassthroughToolbar – default state", () => {
|
||||
afterEach(cleanup);
|
||||
|
||||
it("renders the toolbar and hides the composer when session is idle", () => {
|
||||
mockSessionState = "IDLE";
|
||||
renderToolbar();
|
||||
|
||||
expect(screen.getByTestId(TID_TOOLBAR)).toBeTruthy();
|
||||
expect(screen.queryByTestId(TID_COMPOSER)).toBeNull();
|
||||
expect(screen.queryByTestId(TID_PROCEED)).toBeNull();
|
||||
});
|
||||
|
||||
it("disables the Comments toggle when there are no pending comments", () => {
|
||||
mockSessionState = "IDLE";
|
||||
renderToolbar();
|
||||
|
||||
const toggle = screen.getByTestId(TID_TOGGLE_COMMENTS) as HTMLButtonElement;
|
||||
expect(toggle.disabled).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Composer open / close
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("PassthroughToolbar – composer toggle", () => {
|
||||
beforeEach(resetMocks);
|
||||
afterEach(cleanup);
|
||||
|
||||
it("clicking Chat toggle opens the composer and sets aria-pressed=true", async () => {
|
||||
renderToolbar();
|
||||
const toggle = screen.getByTestId(TID_TOGGLE);
|
||||
expect(toggle.getAttribute("aria-pressed")).toBe("false");
|
||||
|
||||
fireEvent.click(toggle);
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId(TID_COMPOSER)).toBeTruthy());
|
||||
expect(toggle.getAttribute("aria-pressed")).toBe("true");
|
||||
});
|
||||
|
||||
it("pressing Escape inside the composer closes it", async () => {
|
||||
renderToolbar();
|
||||
await openComposer();
|
||||
|
||||
fireEvent.keyDown(screen.getByTestId(TID_TEXTAREA), { key: "Escape" });
|
||||
|
||||
await waitFor(() => expect(screen.queryByTestId(TID_COMPOSER)).toBeNull());
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Send message
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("PassthroughToolbar – send message", () => {
|
||||
beforeEach(resetMocks);
|
||||
afterEach(cleanup);
|
||||
|
||||
it("send with no pending comments calls message.add with exact text and closes composer", async () => {
|
||||
renderToolbar();
|
||||
await openComposer();
|
||||
|
||||
fireEvent.change(screen.getByTestId(TID_TEXTAREA), { target: { value: "hello" } });
|
||||
fireEvent.keyDown(screen.getByTestId(TID_TEXTAREA), { key: "Enter" });
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mockWsRequestFn).toHaveBeenCalledWith(
|
||||
"message.add",
|
||||
{ task_id: TASK_ID, session_id: SESSION_ID, content: "hello" },
|
||||
10_000,
|
||||
),
|
||||
);
|
||||
await waitFor(() => expect(screen.queryByTestId(TID_COMPOSER)).toBeNull());
|
||||
expect(mockMarkCommentsSent).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("send with pending comments prepends review markdown and calls markCommentsSent", async () => {
|
||||
mockPendingByFile = { "src/foo.ts": [makeDiffComment("c1")] };
|
||||
renderToolbar();
|
||||
await openComposer();
|
||||
|
||||
fireEvent.change(screen.getByTestId(TID_TEXTAREA), { target: { value: "ship it" } });
|
||||
fireEvent.keyDown(screen.getByTestId(TID_TEXTAREA), { key: "Enter" });
|
||||
|
||||
await waitFor(() => expect(mockWsRequestFn).toHaveBeenCalledTimes(1));
|
||||
|
||||
const content = mockWsRequestFn.mock.calls[0][1].content as string;
|
||||
expect(content).toMatch(/^### Review Comments\n/);
|
||||
expect(content).toMatch(/ship it$/);
|
||||
|
||||
await waitFor(() => expect(mockMarkCommentsSent).toHaveBeenCalledWith(["c1"]));
|
||||
});
|
||||
|
||||
it("on failure keeps the composer open, shows an error toast, and does not call markCommentsSent", async () => {
|
||||
let rejectSend!: (err: Error) => void;
|
||||
mockWsRequestFn = vi.fn().mockReturnValue(new Promise<void>((_, rej) => (rejectSend = rej)));
|
||||
|
||||
renderToolbar();
|
||||
await openComposer();
|
||||
|
||||
fireEvent.change(screen.getByTestId(TID_TEXTAREA), { target: { value: "important" } });
|
||||
fireEvent.keyDown(screen.getByTestId(TID_TEXTAREA), { key: "Enter" });
|
||||
|
||||
rejectSend(new Error("network down"));
|
||||
|
||||
await waitFor(() =>
|
||||
expect(mockToast).toHaveBeenCalledWith(expect.objectContaining({ variant: "error" })),
|
||||
);
|
||||
expect(screen.getByTestId(TID_COMPOSER)).toBeTruthy();
|
||||
expect(mockMarkCommentsSent).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Pending-comment indicators
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("PassthroughToolbar – pending comment indicators", () => {
|
||||
beforeEach(resetMocks);
|
||||
afterEach(cleanup);
|
||||
|
||||
it("shows a numeric chip when the composer is collapsed and comments are pending", () => {
|
||||
mockPendingByFile = {
|
||||
"src/foo.ts": [makeDiffComment("c1"), makeDiffComment("c2"), makeDiffComment("c3")],
|
||||
};
|
||||
renderToolbar();
|
||||
|
||||
expect(screen.queryByTestId(TID_COMPOSER)).toBeNull();
|
||||
expect(screen.getByTestId(TID_PENDING_COUNT).textContent).toBe("3");
|
||||
});
|
||||
|
||||
it("renders the pending-comments banner inside the open composer when comments are pending", async () => {
|
||||
mockPendingByFile = { "src/foo.ts": [makeDiffComment("c1"), makeDiffComment("c2")] };
|
||||
renderToolbar();
|
||||
await openComposer();
|
||||
|
||||
const banner = screen.getByTestId(TID_PENDING_BANNER);
|
||||
expect(banner.textContent).toMatch(/2/);
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Comments panel
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("PassthroughToolbar – Comments panel", () => {
|
||||
beforeEach(resetMocks);
|
||||
afterEach(cleanup);
|
||||
|
||||
it("clicking Comments opens a panel with one card per pending comment", async () => {
|
||||
mockPendingByFile = {
|
||||
"src/foo.ts": [makeDiffComment("c1"), makeDiffComment("c2")],
|
||||
};
|
||||
renderToolbar();
|
||||
|
||||
fireEvent.click(screen.getByTestId(TID_TOGGLE_COMMENTS));
|
||||
|
||||
await waitFor(() => expect(screen.getByTestId(TID_COMMENTS_PANEL)).toBeTruthy());
|
||||
expect(screen.getAllByTestId(TID_COMMENT_CARD)).toHaveLength(2);
|
||||
});
|
||||
|
||||
it("editing a comment textarea calls updateComment with the new text", async () => {
|
||||
mockPendingByFile = { "src/foo.ts": [makeDiffComment("c1")] };
|
||||
renderToolbar();
|
||||
|
||||
fireEvent.click(screen.getByTestId(TID_TOGGLE_COMMENTS));
|
||||
await waitFor(() => expect(screen.getByTestId(TID_COMMENTS_PANEL)).toBeTruthy());
|
||||
|
||||
fireEvent.change(screen.getByTestId(TID_COMMENT_TEXTAREA), {
|
||||
target: { value: "Updated text" },
|
||||
});
|
||||
|
||||
expect(mockUpdateComment).toHaveBeenCalledWith("c1", { text: "Updated text" });
|
||||
});
|
||||
|
||||
it("clicking the file reference opens the file in an editor", async () => {
|
||||
mockPendingByFile = { "src/foo.ts": [makeDiffComment("c1")] };
|
||||
renderToolbar();
|
||||
|
||||
fireEvent.click(screen.getByTestId(TID_TOGGLE_COMMENTS));
|
||||
await waitFor(() => expect(screen.getByTestId(TID_COMMENTS_PANEL)).toBeTruthy());
|
||||
|
||||
fireEvent.click(screen.getByTestId(TID_COMMENT_FILE_REF));
|
||||
|
||||
expect(mockOpenFile).toHaveBeenCalledWith("src/foo.ts");
|
||||
});
|
||||
|
||||
it("clicking the remove button on a comment calls removeComment", async () => {
|
||||
mockPendingByFile = { "src/foo.ts": [makeDiffComment("c1")] };
|
||||
renderToolbar();
|
||||
|
||||
fireEvent.click(screen.getByTestId(TID_TOGGLE_COMMENTS));
|
||||
await waitFor(() => expect(screen.getByTestId(TID_COMMENTS_PANEL)).toBeTruthy());
|
||||
|
||||
fireEvent.click(screen.getByTestId(TID_COMMENT_REMOVE));
|
||||
|
||||
expect(mockRemoveComment).toHaveBeenCalledWith("c1");
|
||||
});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Proceed-next-step button
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe("PassthroughToolbar – proceed button", () => {
|
||||
beforeEach(resetMocks);
|
||||
afterEach(cleanup);
|
||||
|
||||
it("is absent when nextStepName is null", () => {
|
||||
mockNextStep = { proceedStepName: null, proceed: vi.fn(), isMoving: false };
|
||||
mockSessionState = "IDLE";
|
||||
renderToolbar();
|
||||
expect(screen.queryByTestId(TID_PROCEED)).toBeNull();
|
||||
});
|
||||
|
||||
it("is absent when nextStepName is set but the agent is RUNNING", () => {
|
||||
mockNextStep = { proceedStepName: "Review", proceed: vi.fn(), isMoving: false };
|
||||
mockSessionState = "RUNNING";
|
||||
renderToolbar();
|
||||
expect(screen.queryByTestId(TID_PROCEED)).toBeNull();
|
||||
});
|
||||
|
||||
it("is present with correct label and calls proceed on click when agent is idle", async () => {
|
||||
const proceedFn = vi.fn();
|
||||
mockNextStep = { proceedStepName: "Review", proceed: proceedFn, isMoving: false };
|
||||
mockSessionState = "IDLE";
|
||||
renderToolbar();
|
||||
|
||||
const btn = screen.getByTestId(TID_PROCEED);
|
||||
expect(btn.textContent).toMatch(/Review/);
|
||||
|
||||
fireEvent.click(btn);
|
||||
await waitFor(() => expect(proceedFn).toHaveBeenCalledTimes(1));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,529 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useMemo, useState } from "react";
|
||||
import {
|
||||
IconArrowRight,
|
||||
IconMessageCircle,
|
||||
IconMessageDots,
|
||||
IconSend,
|
||||
IconTrash,
|
||||
IconX,
|
||||
} from "@tabler/icons-react";
|
||||
import { Button } from "@kandev/ui/button";
|
||||
import { Textarea } from "@kandev/ui/textarea";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip";
|
||||
import { useToast } from "@/components/toast-provider";
|
||||
import { PRStatusChip } from "@/components/github/pr-status-chip";
|
||||
import { PassthroughComposer } from "./passthrough-composer";
|
||||
import { PRMergedBanner } from "./chat/chat-input-area";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { useNextWorkflowStep } from "@/hooks/domains/kanban/use-plan-actions";
|
||||
import { usePendingDiffCommentsByFile } from "@/hooks/domains/comments/use-diff-comments";
|
||||
import { useCommentsStore } from "@/lib/state/slices/comments/comments-store";
|
||||
import { useFileEditors } from "@/hooks/use-file-editors";
|
||||
import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint";
|
||||
import { formatReviewCommentsAsMarkdown } from "@/lib/state/slices/comments/format";
|
||||
import type { DiffComment } from "@/lib/diff/types";
|
||||
import { getWebSocketClient } from "@/lib/ws/connection";
|
||||
import { PassthroughTerminal } from "./passthrough-terminal";
|
||||
|
||||
/**
|
||||
* PassthroughToolbar wraps the PTY terminal with the kandev surface that the
|
||||
* full ACP `ChatStatusBar` + `ChatInputArea` provide for chat mode: PR status,
|
||||
* merge banner, "Move to next step" workflow advancement, a collapsible Chat
|
||||
* compose box, and a collapsible Comments panel showing pending review comments
|
||||
* (each editable inline with a clickable file reference).
|
||||
*
|
||||
* Default focus stays on the xterm terminal — both Chat and Comments are
|
||||
* collapsed behind toolbar buttons so the user can keep raw-terminal
|
||||
* interaction front-and-centre and only opt in when they want to compose a
|
||||
* follow-up or review what's about to be attached. Ctrl-C in the xterm
|
||||
* cancels the agent, so no dedicated Stop button is needed.
|
||||
*/
|
||||
export function PassthroughToolbar({
|
||||
sessionId,
|
||||
taskId,
|
||||
}: {
|
||||
sessionId: string | null | undefined;
|
||||
taskId: string | null;
|
||||
}) {
|
||||
const [composerOpen, setComposerOpen] = useState(false);
|
||||
const [commentsOpenState, setCommentsOpen] = useState(false);
|
||||
|
||||
const sessionState = useAppStore((state) =>
|
||||
sessionId ? (state.taskSessions.items[sessionId]?.state ?? null) : null,
|
||||
);
|
||||
const isAgentBusy = sessionState === "RUNNING" || sessionState === "STARTING";
|
||||
|
||||
const nextStep = useNextWorkflowStep(taskId);
|
||||
const showProceed = !!nextStep.proceedStepName && !isAgentBusy;
|
||||
|
||||
const { pendingComments, pendingCount } = usePendingPassthroughComments(sessionId);
|
||||
const { isMobile } = useResponsiveBreakpoint();
|
||||
const { openFile } = useFileEditors();
|
||||
|
||||
// Derive open state: auto-close when pending comments are cleared
|
||||
const commentsOpen = commentsOpenState && pendingCount > 0;
|
||||
|
||||
const handleSendMessage = useSendPassthroughMessage({
|
||||
taskId,
|
||||
sessionId,
|
||||
pendingComments,
|
||||
onSent: () => {
|
||||
setComposerOpen(false);
|
||||
setCommentsOpen(false);
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<div className="flex h-full flex-col bg-card" data-testid="passthrough-toolbar">
|
||||
<div className="flex-1 min-h-0">
|
||||
<PassthroughTerminal sessionId={sessionId} mode="agent" enableTouchScroll={isMobile} />
|
||||
</div>
|
||||
|
||||
{commentsOpen && pendingCount > 0 && (
|
||||
<CommentsPanel
|
||||
comments={pendingComments}
|
||||
openFile={openFile}
|
||||
onSend={() => handleSendMessage("")}
|
||||
/>
|
||||
)}
|
||||
|
||||
{composerOpen && (
|
||||
<PassthroughComposer
|
||||
onSubmit={handleSendMessage}
|
||||
onCancel={() => setComposerOpen(false)}
|
||||
autoFocus
|
||||
placeholder="Type a message, Shift+Enter for newline, Esc to close"
|
||||
header={pendingCount > 0 ? <PendingCommentsHint count={pendingCount} /> : null}
|
||||
/>
|
||||
)}
|
||||
|
||||
<PassthroughStatusRow
|
||||
taskId={taskId}
|
||||
nextStepName={nextStep.proceedStepName}
|
||||
onProceed={nextStep.proceed}
|
||||
isMoving={nextStep.isMoving}
|
||||
showProceed={showProceed}
|
||||
composerOpen={composerOpen}
|
||||
onToggleComposer={() => setComposerOpen((open) => !open)}
|
||||
commentsOpen={commentsOpen}
|
||||
onToggleComments={() => setCommentsOpen((open) => !open)}
|
||||
pendingCommentsCount={pendingCount}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function flattenComments(byFile: Record<string, DiffComment[]>): DiffComment[] {
|
||||
const all: DiffComment[] = [];
|
||||
for (const list of Object.values(byFile)) all.push(...list);
|
||||
return all;
|
||||
}
|
||||
|
||||
function usePendingPassthroughComments(sessionId: string | null | undefined) {
|
||||
const pendingCommentsByFile = usePendingDiffCommentsByFile(sessionId ?? null);
|
||||
const pendingComments = useMemo(
|
||||
() => flattenComments(pendingCommentsByFile),
|
||||
[pendingCommentsByFile],
|
||||
);
|
||||
return { pendingComments, pendingCount: pendingComments.length };
|
||||
}
|
||||
|
||||
function useSendPassthroughMessage({
|
||||
taskId,
|
||||
sessionId,
|
||||
pendingComments,
|
||||
onSent,
|
||||
}: {
|
||||
taskId: string | null;
|
||||
sessionId: string | null | undefined;
|
||||
pendingComments: DiffComment[];
|
||||
onSent: () => void;
|
||||
}) {
|
||||
const { toast } = useToast();
|
||||
const markCommentsSent = useCommentsStore((s) => s.markCommentsSent);
|
||||
|
||||
return useCallback(
|
||||
async (content: string) => {
|
||||
if (!taskId || !sessionId) {
|
||||
toast({ title: "Session not ready", variant: "error" });
|
||||
throw new Error("Session not ready");
|
||||
}
|
||||
const client = getWebSocketClient();
|
||||
if (!client) {
|
||||
toast({ title: "Not connected — please reload to retry", variant: "error" });
|
||||
throw new Error("WebSocket client not available");
|
||||
}
|
||||
// Format pending review comments as markdown and prepend so they reach
|
||||
// the agent's stdin alongside the user's typed prompt. Mark them sent
|
||||
// only after the WS request resolves so a failed send doesn't drop the
|
||||
// user's queued comments.
|
||||
const formatted =
|
||||
pendingComments.length > 0
|
||||
? formatReviewCommentsAsMarkdown(pendingComments) + content
|
||||
: content;
|
||||
try {
|
||||
await client.request(
|
||||
"message.add",
|
||||
{ task_id: taskId, session_id: sessionId, content: formatted },
|
||||
10_000,
|
||||
);
|
||||
if (pendingComments.length > 0) {
|
||||
markCommentsSent(pendingComments.map((c) => c.id));
|
||||
}
|
||||
onSent();
|
||||
} catch (error) {
|
||||
console.error("Failed to send passthrough message:", error);
|
||||
toast({ title: "Failed to send message", variant: "error" });
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
[taskId, sessionId, toast, pendingComments, markCommentsSent, onSent],
|
||||
);
|
||||
}
|
||||
|
||||
function ChatToggleButton({
|
||||
composerOpen,
|
||||
onToggle,
|
||||
}: {
|
||||
composerOpen: boolean;
|
||||
onToggle: () => void;
|
||||
}) {
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant={composerOpen ? "default" : "outline"}
|
||||
size="sm"
|
||||
className="h-6 gap-1 px-2.5 text-xs cursor-pointer"
|
||||
onClick={onToggle}
|
||||
data-testid="passthrough-toggle-composer"
|
||||
aria-pressed={composerOpen}
|
||||
>
|
||||
{composerOpen ? (
|
||||
<IconX className="h-3.5 w-3.5" />
|
||||
) : (
|
||||
<IconMessageCircle className="h-3.5 w-3.5" />
|
||||
)}
|
||||
Chat
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="max-w-xs">
|
||||
{composerOpen ? (
|
||||
<p>
|
||||
Close the compose box (or press <kbd>Esc</kbd> inside it). The CLI agent terminal keeps
|
||||
focus.
|
||||
</p>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
<p>
|
||||
Open a kandev-controlled compose box above the terminal to type a follow-up message.
|
||||
Press <kbd>Enter</kbd> to send, <kbd>Shift+Enter</kbd> for a newline.
|
||||
</p>
|
||||
<p className="text-muted-foreground">
|
||||
The text is delivered straight to the CLI agent's stdin — pending review comments
|
||||
(if any) are prepended automatically.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function commentsToggleClassName(count: number, commentsOpen: boolean): string {
|
||||
// Vivid amber when there are pending comments so the user sees "something
|
||||
// to do" — washes back to plain outline once they're cleared / sent.
|
||||
if (count === 0) return "h-6 gap-1 px-2.5 text-xs cursor-pointer";
|
||||
if (commentsOpen) return "h-6 gap-1 px-2.5 text-xs cursor-pointer";
|
||||
return "h-6 gap-1 px-2.5 text-xs cursor-pointer border-amber-500/60 bg-amber-500/15 text-amber-700 hover:bg-amber-500/25 hover:text-amber-700 dark:text-amber-300 dark:hover:text-amber-200";
|
||||
}
|
||||
|
||||
function CommentsToggleButton({
|
||||
commentsOpen,
|
||||
onToggle,
|
||||
pendingCommentsCount,
|
||||
}: {
|
||||
commentsOpen: boolean;
|
||||
onToggle: () => void;
|
||||
pendingCommentsCount: number;
|
||||
}) {
|
||||
const disabled = pendingCommentsCount === 0;
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant={commentsOpen ? "default" : "outline"}
|
||||
size="sm"
|
||||
className={commentsToggleClassName(pendingCommentsCount, commentsOpen)}
|
||||
onClick={onToggle}
|
||||
disabled={disabled}
|
||||
data-testid="passthrough-toggle-comments"
|
||||
aria-pressed={commentsOpen}
|
||||
>
|
||||
{commentsOpen ? (
|
||||
<IconX className="h-3.5 w-3.5" />
|
||||
) : (
|
||||
<IconMessageDots className="h-3.5 w-3.5" />
|
||||
)}
|
||||
Comments
|
||||
{pendingCommentsCount > 0 && (
|
||||
<span
|
||||
data-testid="passthrough-pending-count"
|
||||
className="ml-1 rounded-full bg-amber-500/40 px-1.5 py-0 text-[10px] font-semibold text-amber-900 dark:text-amber-100"
|
||||
>
|
||||
{pendingCommentsCount}
|
||||
</span>
|
||||
)}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="max-w-xs">
|
||||
<CommentsTooltipBody commentsOpen={commentsOpen} count={pendingCommentsCount} />
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function CommentsTooltipBody({ commentsOpen, count }: { commentsOpen: boolean; count: number }) {
|
||||
if (count === 0) {
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<p>No pending review comments.</p>
|
||||
<p className="text-muted-foreground">
|
||||
Add a comment from the diff or file view, then come back here to review and send it.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (commentsOpen) {
|
||||
return (
|
||||
<p>
|
||||
Hide the comment list. The comments stay queued and will still be sent next time you submit
|
||||
(here or from the chat box).
|
||||
</p>
|
||||
);
|
||||
}
|
||||
const plural = count === 1 ? "" : "s";
|
||||
return (
|
||||
<div className="space-y-1">
|
||||
<p>
|
||||
{count} pending review comment{plural}. Click to expand the list — you can edit each
|
||||
comment, click the file path to jump to the source, or remove a comment with the trash icon.
|
||||
</p>
|
||||
<p className="text-muted-foreground">
|
||||
Hit <strong>Send to agent</strong> inside the panel to deliver them to the CLI agent right
|
||||
away, or just open the chat box and type a follow-up — the comments will be prepended.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PendingCommentsHint({ count }: { count: number }) {
|
||||
return (
|
||||
<div
|
||||
data-testid="passthrough-pending-comments-banner"
|
||||
className="flex items-center gap-1.5 border-b bg-amber-500/10 px-2 py-1 text-xs text-amber-700 dark:text-amber-300"
|
||||
>
|
||||
<IconMessageDots className="h-3.5 w-3.5" />
|
||||
<span>
|
||||
{count} pending review comment{count === 1 ? "" : "s"} will be attached to this message.
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function CommentsPanel({
|
||||
comments,
|
||||
openFile,
|
||||
onSend,
|
||||
}: {
|
||||
comments: DiffComment[];
|
||||
openFile: (path: string) => void;
|
||||
onSend: () => Promise<void> | void;
|
||||
}) {
|
||||
const [isSending, setIsSending] = useState(false);
|
||||
const handleSend = useCallback(async () => {
|
||||
if (isSending) return;
|
||||
setIsSending(true);
|
||||
try {
|
||||
await onSend();
|
||||
} catch {
|
||||
// onSend already toasted the error; keep panel open so the user can retry.
|
||||
} finally {
|
||||
setIsSending(false);
|
||||
}
|
||||
}, [isSending, onSend]);
|
||||
|
||||
const count = comments.length;
|
||||
const plural = count === 1 ? "" : "s";
|
||||
return (
|
||||
<div
|
||||
data-testid="passthrough-comments-panel"
|
||||
className="flex max-h-72 flex-col border-t bg-amber-500/5"
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2 border-b border-amber-500/20 bg-amber-500/10 px-2 py-1 text-xs">
|
||||
<span className="font-medium text-amber-700 dark:text-amber-300">
|
||||
{count} review comment{plural} ready to send
|
||||
</span>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="default"
|
||||
onClick={handleSend}
|
||||
disabled={isSending}
|
||||
className="h-6 gap-1 px-2.5 text-xs cursor-pointer"
|
||||
data-testid="passthrough-send-comments"
|
||||
>
|
||||
<IconSend className="h-3.5 w-3.5" />
|
||||
Send to agent
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent className="max-w-xs">
|
||||
<p>
|
||||
Deliver these comments to the CLI agent's stdin as a single message — no need to
|
||||
open the chat box. The agent receives the same markdown that prepending to a typed
|
||||
message would produce.
|
||||
</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</div>
|
||||
<div className="flex-1 space-y-2 overflow-y-auto px-2 py-2">
|
||||
{comments.map((comment) => (
|
||||
<CommentCard key={comment.id} comment={comment} openFile={openFile} />
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function formatLineRange(comment: DiffComment): string {
|
||||
return comment.startLine === comment.endLine
|
||||
? `${comment.startLine}`
|
||||
: `${comment.startLine}-${comment.endLine}`;
|
||||
}
|
||||
|
||||
function CommentCard({
|
||||
comment,
|
||||
openFile,
|
||||
}: {
|
||||
comment: DiffComment;
|
||||
openFile: (path: string) => void;
|
||||
}) {
|
||||
const updateComment = useCommentsStore((s) => s.updateComment);
|
||||
const removeComment = useCommentsStore((s) => s.removeComment);
|
||||
const lineRange = formatLineRange(comment);
|
||||
|
||||
const handleOpenFile = useCallback(() => {
|
||||
openFile(comment.filePath);
|
||||
}, [openFile, comment.filePath]);
|
||||
|
||||
return (
|
||||
<div
|
||||
data-testid="passthrough-comment-card"
|
||||
className="rounded-md border border-amber-500/30 bg-card px-2 py-1.5 text-xs"
|
||||
>
|
||||
<div className="mb-1 flex items-center justify-between gap-2">
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleOpenFile}
|
||||
className="truncate text-left font-mono text-[11px] text-primary hover:underline cursor-pointer"
|
||||
data-testid="passthrough-comment-file-ref"
|
||||
title={`${comment.filePath}:${lineRange}`}
|
||||
>
|
||||
{comment.filePath}:{lineRange}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeComment(comment.id)}
|
||||
className="rounded p-0.5 text-muted-foreground hover:bg-destructive/10 hover:text-destructive cursor-pointer"
|
||||
aria-label="Remove comment"
|
||||
data-testid="passthrough-comment-remove"
|
||||
>
|
||||
<IconTrash className="h-3.5 w-3.5" />
|
||||
</button>
|
||||
</div>
|
||||
{comment.codeContent && (
|
||||
<pre className="mb-1 max-h-16 overflow-y-auto rounded bg-muted/50 px-1.5 py-1 text-[10px] font-mono leading-tight">
|
||||
{comment.codeContent}
|
||||
</pre>
|
||||
)}
|
||||
<Textarea
|
||||
value={comment.text}
|
||||
onChange={(e) => updateComment(comment.id, { text: e.target.value })}
|
||||
className="min-h-[2rem] resize-none text-xs"
|
||||
rows={Math.min(4, Math.max(1, comment.text.split("\n").length))}
|
||||
placeholder="Write a comment…"
|
||||
data-testid="passthrough-comment-textarea"
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type StatusRowProps = {
|
||||
taskId: string | null;
|
||||
nextStepName: string | null;
|
||||
onProceed: () => void;
|
||||
isMoving: boolean;
|
||||
showProceed: boolean;
|
||||
composerOpen: boolean;
|
||||
onToggleComposer: () => void;
|
||||
commentsOpen: boolean;
|
||||
onToggleComments: () => void;
|
||||
pendingCommentsCount: number;
|
||||
};
|
||||
|
||||
function PassthroughStatusRow({
|
||||
taskId,
|
||||
nextStepName,
|
||||
onProceed,
|
||||
isMoving,
|
||||
showProceed,
|
||||
composerOpen,
|
||||
onToggleComposer,
|
||||
commentsOpen,
|
||||
onToggleComments,
|
||||
pendingCommentsCount,
|
||||
}: StatusRowProps) {
|
||||
return (
|
||||
<div
|
||||
data-testid="passthrough-status-row"
|
||||
className="flex flex-shrink-0 items-center gap-1.5 border-t bg-card px-2 py-1 text-xs text-muted-foreground"
|
||||
>
|
||||
<ChatToggleButton composerOpen={composerOpen} onToggle={onToggleComposer} />
|
||||
<CommentsToggleButton
|
||||
commentsOpen={commentsOpen}
|
||||
onToggle={onToggleComments}
|
||||
pendingCommentsCount={pendingCommentsCount}
|
||||
/>
|
||||
|
||||
<div className="ml-auto flex items-center gap-1.5">
|
||||
<PRStatusChip taskId={taskId} />
|
||||
{taskId && <PRMergedBanner key={taskId} taskId={taskId} />}
|
||||
{showProceed && nextStepName && (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-6 gap-1 px-2.5 text-xs cursor-pointer text-primary"
|
||||
onClick={onProceed}
|
||||
disabled={isMoving}
|
||||
data-testid="passthrough-proceed-next-step"
|
||||
>
|
||||
{nextStepName}
|
||||
<IconArrowRight className="h-3.5 w-3.5" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>Move task to the next workflow step</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||
import { render, fireEvent, screen, cleanup, waitFor } from "@testing-library/react";
|
||||
import { PassthroughComposer } from "./preview-session-tabs";
|
||||
import { PassthroughComposer } from "./passthrough-composer";
|
||||
|
||||
const TEXTAREA_TID = "passthrough-composer-textarea";
|
||||
const SUBMIT_TID = "passthrough-composer-submit";
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
"use client";
|
||||
|
||||
import { useCallback, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { IconLoader2, IconSend } from "@tabler/icons-react";
|
||||
import { useCallback, useMemo } from "react";
|
||||
import { IconLoader2 } from "@tabler/icons-react";
|
||||
import { Button } from "@kandev/ui/button";
|
||||
import { Textarea } from "@kandev/ui/textarea";
|
||||
import { AgentLogo } from "@/components/agent-logo";
|
||||
import { GridSpinner } from "@/components/grid-spinner";
|
||||
import { SessionTabs, type SessionTab } from "@/components/session-tabs";
|
||||
@@ -15,7 +14,7 @@ import type { UseEnsureTaskSessionResult } from "@/hooks/domains/session/use-ens
|
||||
import type { AgentProfileOption } from "@/lib/state/slices";
|
||||
import type { TaskSession } from "@/lib/types/http";
|
||||
import { getWebSocketClient } from "@/lib/ws/connection";
|
||||
import { PassthroughTerminal } from "./passthrough-terminal";
|
||||
import { PassthroughToolbar } from "./passthrough-toolbar";
|
||||
import { TaskChatPanel } from "./task-chat-panel";
|
||||
import {
|
||||
buildAgentLabelsById,
|
||||
@@ -144,10 +143,6 @@ function SessionAgentLogo({ profile }: { profile: AgentProfileOption | null | un
|
||||
|
||||
function PreviewSessionBody({ session, taskId }: { session: TaskSession; taskId: string }) {
|
||||
const { toast } = useToast();
|
||||
// Used by the non-passthrough TaskChatPanel branch. Swallows errors after
|
||||
// surfacing a toast because the existing chat-input-state.handleSubmit
|
||||
// already optimistically clears the input before this resolves; rethrowing
|
||||
// here would surface as an unhandled rejection further up the chain.
|
||||
const handleSendMessage = useCallback(
|
||||
async (content: string) => {
|
||||
const client = getWebSocketClient();
|
||||
@@ -166,45 +161,8 @@ function PreviewSessionBody({ session, taskId }: { session: TaskSession; taskId:
|
||||
[taskId, session.id, toast],
|
||||
);
|
||||
|
||||
// Used by PassthroughComposer. Rethrows after toasting so the composer can
|
||||
// keep the user's typed text intact on failure (Composer.submit's catch
|
||||
// skips the setValue("") clear when onSubmit rejects). Separate from the
|
||||
// ACP handler above to avoid leaking unhandled rejections into the chat-
|
||||
// input-state chain that TaskChatPanel uses.
|
||||
const handleSendPassthroughMessage = useCallback(
|
||||
async (content: string) => {
|
||||
const client = getWebSocketClient();
|
||||
if (!client) {
|
||||
// Surface the disconnect to the user before re-throwing so the
|
||||
// composer's catch (which preserves the typed text) doesn't swallow
|
||||
// the failure silently.
|
||||
toast({ title: "Not connected — please reload to retry", variant: "error" });
|
||||
throw new Error("WebSocket client not available");
|
||||
}
|
||||
try {
|
||||
await client.request(
|
||||
"message.add",
|
||||
{ task_id: taskId, session_id: session.id, content },
|
||||
10000,
|
||||
);
|
||||
} catch (error) {
|
||||
console.error("Failed to send passthrough message:", error);
|
||||
toast({ title: "Failed to send message", variant: "error" });
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
[taskId, session.id, toast],
|
||||
);
|
||||
|
||||
if (session.is_passthrough) {
|
||||
return (
|
||||
<div className="flex h-full flex-col bg-card">
|
||||
<div className="flex-1 min-h-0">
|
||||
<PassthroughTerminal sessionId={session.id} mode="agent" />
|
||||
</div>
|
||||
<PassthroughComposer onSubmit={handleSendPassthroughMessage} />
|
||||
</div>
|
||||
);
|
||||
return <PassthroughToolbar sessionId={session.id} taskId={taskId} />;
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -214,94 +172,6 @@ function PreviewSessionBody({ session, taskId }: { session: TaskSession; taskId:
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* PassthroughComposer is the kandev-controlled compose box rendered alongside
|
||||
* the PTY in passthrough mode. Submitting forwards the typed text via the
|
||||
* onSubmit prop (which posts `message.add` over WS); the backend's
|
||||
* `Executor.Prompt` routes passthrough sessions to PTY stdin so the CLI agent
|
||||
* actually receives it. Enter submits; Shift+Enter inserts a newline.
|
||||
*/
|
||||
// Cap matches the `max-h-32` Tailwind class on the textarea below — 128 px.
|
||||
const COMPOSER_MAX_HEIGHT_PX = 128;
|
||||
|
||||
export function PassthroughComposer({
|
||||
onSubmit,
|
||||
}: {
|
||||
onSubmit: (content: string) => Promise<void>;
|
||||
}) {
|
||||
const [value, setValue] = useState("");
|
||||
const [isSending, setIsSending] = useState(false);
|
||||
const textareaRef = useRef<HTMLTextAreaElement | null>(null);
|
||||
const trimmed = value.trim();
|
||||
const canSubmit = trimmed.length > 0 && !isSending;
|
||||
|
||||
// Auto-grow the textarea with content (Shift+Enter newlines, long pastes)
|
||||
// up to the max-h-32 cap. Done in JS so it works in browsers without
|
||||
// CSS field-sizing support.
|
||||
useLayoutEffect(() => {
|
||||
const el = textareaRef.current;
|
||||
if (!el) return;
|
||||
el.style.height = "auto";
|
||||
el.style.height = `${Math.min(el.scrollHeight, COMPOSER_MAX_HEIGHT_PX)}px`;
|
||||
}, [value]);
|
||||
|
||||
const submit = useCallback(async () => {
|
||||
if (!canSubmit) return;
|
||||
setIsSending(true);
|
||||
try {
|
||||
await onSubmit(trimmed);
|
||||
setValue(""); // only clear on success — preserve text so user can retry on send failure
|
||||
} catch {
|
||||
// onSubmit (PreviewSessionBody.handleSendPassthroughMessage) already
|
||||
// surfaced the error via toast; the user's typed value stays in the
|
||||
// textarea intentionally so they can retry without retyping.
|
||||
} finally {
|
||||
setIsSending(false);
|
||||
}
|
||||
}, [canSubmit, onSubmit, trimmed]);
|
||||
|
||||
const handleKeyDown = useCallback(
|
||||
(e: KeyboardEvent<HTMLTextAreaElement>) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
void submit();
|
||||
}
|
||||
},
|
||||
[submit],
|
||||
);
|
||||
|
||||
return (
|
||||
<div
|
||||
className="flex flex-shrink-0 items-end gap-2 border-t bg-card px-2 py-2"
|
||||
data-testid="passthrough-composer"
|
||||
>
|
||||
<Textarea
|
||||
ref={textareaRef}
|
||||
value={value}
|
||||
onChange={(e) => setValue(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Message the CLI agent (Enter to send, Shift+Enter for newline)"
|
||||
rows={1}
|
||||
disabled={isSending}
|
||||
className="min-h-9 max-h-32 flex-1 resize-none overflow-y-auto"
|
||||
data-testid="passthrough-composer-textarea"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
size="sm"
|
||||
variant="default"
|
||||
onClick={() => void submit()}
|
||||
disabled={!canSubmit}
|
||||
className="cursor-pointer h-9 shrink-0"
|
||||
data-testid="passthrough-composer-submit"
|
||||
aria-label="Send message to CLI agent"
|
||||
>
|
||||
<IconSend className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function RunningSpinner() {
|
||||
return <GridSpinner className="text-muted-foreground shrink-0 text-[12px]" />;
|
||||
}
|
||||
|
||||
@@ -15,7 +15,7 @@ import { SessionPanel } from "@kandev/ui/pannel-session";
|
||||
import { TaskChatPanel } from "./task-chat-panel";
|
||||
import { TaskChangesPanel } from "./task-changes-panel";
|
||||
import { FileTabContent } from "./file-tab-content";
|
||||
import { PassthroughTerminal } from "./passthrough-terminal";
|
||||
import { PassthroughToolbar } from "./passthrough-toolbar";
|
||||
import type { OpenFileTab, FileContentResponse } from "@/lib/types/backend";
|
||||
import { useAppStore } from "@/components/state-provider";
|
||||
import { SessionTabs, type SessionTab } from "@/components/session-tabs";
|
||||
@@ -525,7 +525,7 @@ function ChatTabContent({
|
||||
style={{ minHeight: "200px" }}
|
||||
>
|
||||
<div className="flex-1 min-h-0 h-full" style={{ minHeight: "150px" }}>
|
||||
<PassthroughTerminal key={activeTaskId} sessionId={sessionId} mode="agent" />
|
||||
<PassthroughToolbar key={activeTaskId} sessionId={sessionId} taskId={activeTaskId} />
|
||||
</div>
|
||||
</TabsContent>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
import { type Page } from "@playwright/test";
|
||||
import { test, expect } from "../../fixtures/test-base";
|
||||
import { KanbanPage } from "../../pages/kanban-page";
|
||||
import { SessionPage } from "../../pages/session-page";
|
||||
import type { ApiClient } from "../../helpers/api-client";
|
||||
|
||||
/**
|
||||
* Regression for CLI passthrough: prompts sent via `message.add` (plan/editor
|
||||
* comment Run, passthrough composer, etc.) must reach PTY stdin with a submit
|
||||
* key so the mock TUI echoes "Processed: <text>".
|
||||
*
|
||||
* This spec exercises the passthrough composer UI; comment Run uses the same
|
||||
* `useRunComment` → `message.add` → `promptPassthrough` backend path.
|
||||
*
|
||||
* Related coverage:
|
||||
* - ACP plan comment Run: apps/web/e2e/tests/task/comment-run-not-queued.spec.ts
|
||||
* - Passthrough composer Enter: apps/web/e2e/tests/cli-mode/passthrough-toolbar.spec.ts
|
||||
* - Backend integration: TestPromptTask_PassthroughRoutesToPTYStdin
|
||||
*/
|
||||
test.describe("CLI mode: message.add submits to PTY", () => {
|
||||
test.describe.configure({ retries: 1 });
|
||||
|
||||
async function createPassthroughProfile(apiClient: ApiClient, name: string): Promise<string> {
|
||||
const { agents } = await apiClient.listAgents();
|
||||
if (agents.length === 0) throw new Error("no agents registered in this e2e profile");
|
||||
const profile = await apiClient.createAgentProfile(agents[0].id, name, {
|
||||
model: "mock-fast",
|
||||
auto_approve: true,
|
||||
cli_passthrough: true,
|
||||
});
|
||||
return profile.id;
|
||||
}
|
||||
|
||||
async function openPassthroughTask(
|
||||
testPage: Page,
|
||||
apiClient: ApiClient,
|
||||
seedData: {
|
||||
workspaceId: string;
|
||||
workflowId: string;
|
||||
startStepId: string;
|
||||
repositoryId: string;
|
||||
},
|
||||
profileId: string,
|
||||
taskTitle: string,
|
||||
): Promise<{ session: SessionPage; taskId: string; sessionId: string }> {
|
||||
const created = await apiClient.createTaskWithAgent(
|
||||
seedData.workspaceId,
|
||||
taskTitle,
|
||||
profileId,
|
||||
{
|
||||
description: "seed passthrough prompt",
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
repository_ids: [seedData.repositoryId],
|
||||
},
|
||||
);
|
||||
if (!created.session_id) throw new Error("createTaskWithAgent did not return session_id");
|
||||
|
||||
const kanban = new KanbanPage(testPage);
|
||||
await kanban.goto();
|
||||
const card = kanban.taskCardByTitle(taskTitle);
|
||||
await expect(card).toBeVisible({ timeout: 20_000 });
|
||||
await card.click();
|
||||
await expect(testPage).toHaveURL(/\/t\//, { timeout: 15_000 });
|
||||
|
||||
const session = new SessionPage(testPage);
|
||||
await session.waitForPassthroughLoad(20_000);
|
||||
await session.waitForPassthroughLoaded(20_000);
|
||||
await session.expectPassthroughHasText("Processed:", 20_000);
|
||||
|
||||
return { session, taskId: created.id, sessionId: created.session_id };
|
||||
}
|
||||
|
||||
test("passthrough composer send shows Processed in terminal", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
test.setTimeout(90_000);
|
||||
|
||||
const profileId = await createPassthroughProfile(apiClient, "CLI message.add");
|
||||
const { session } = await openPassthroughTask(
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
profileId,
|
||||
"CLI message.add Task",
|
||||
);
|
||||
|
||||
await testPage.getByTestId("passthrough-toggle-composer").click();
|
||||
await expect(testPage.getByTestId("passthrough-composer")).toBeVisible({ timeout: 5_000 });
|
||||
|
||||
const followUp = "passthrough message.add submit e2e";
|
||||
const textarea = testPage.getByTestId("passthrough-composer-textarea");
|
||||
await textarea.fill(followUp);
|
||||
await textarea.press("Enter");
|
||||
|
||||
await expect(testPage.getByTestId("passthrough-composer")).toBeHidden({ timeout: 10_000 });
|
||||
await session.expectPassthroughHasText(`Processed: ${followUp}`, 20_000);
|
||||
});
|
||||
|
||||
test("message.add via API (comment Run path) shows Processed in terminal", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
test.setTimeout(90_000);
|
||||
|
||||
const profileId = await createPassthroughProfile(apiClient, "CLI comment Run API");
|
||||
const { session, taskId, sessionId } = await openPassthroughTask(
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
profileId,
|
||||
"CLI comment Run API Task",
|
||||
);
|
||||
|
||||
const commentText = "passthrough comment run via message.add";
|
||||
await apiClient.addUserMessage(taskId, sessionId, commentText);
|
||||
|
||||
await session.expectPassthroughHasText(`Processed: ${commentText}`, 20_000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { test, expect } from "../../fixtures/test-base";
|
||||
import { KanbanPage } from "../../pages/kanban-page";
|
||||
|
||||
/**
|
||||
* CLI-mode parity: the create-task dialog must keep the prompt textarea
|
||||
* fully usable when the selected profile is a passthrough (CLI / PTY)
|
||||
* agent. The legacy "Prompt ignored — passthrough mode active" warning
|
||||
* has been removed; the backend now auto-injects the prompt into the
|
||||
* running CLI after the first idle window.
|
||||
*/
|
||||
test.describe("CLI mode: create-task dialog prompt", () => {
|
||||
test("prompt textarea is enabled, no 'prompt ignored' warning, and submit works", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
// Mark the pre-seeded agent profile as passthrough. The seedData
|
||||
// fixture pre-injects this profile id into localStorage, so the
|
||||
// create-task dialog auto-selects it without any UI plumbing.
|
||||
await apiClient.updateAgentProfile(seedData.agentProfileId, {
|
||||
cli_passthrough: true,
|
||||
});
|
||||
|
||||
const kanban = new KanbanPage(testPage);
|
||||
await kanban.goto();
|
||||
await expect(kanban.createTaskButton).toHaveCount(1);
|
||||
await kanban.createTaskButton.click();
|
||||
|
||||
const dialog = testPage.getByTestId("create-task-dialog");
|
||||
await expect(dialog).toBeVisible();
|
||||
|
||||
// The prompt textarea is the one rendered inside the dialog body.
|
||||
const textarea = testPage.getByTestId("task-description-input");
|
||||
await expect(textarea).toBeVisible();
|
||||
await expect(textarea).toBeEnabled();
|
||||
|
||||
// No legacy passthrough warning anywhere in the dialog.
|
||||
await expect(dialog).not.toContainText(/prompt ignored/i);
|
||||
await expect(dialog).not.toContainText(/passthrough mode active/i);
|
||||
await expect(dialog).not.toContainText(/prompt not supported/i);
|
||||
|
||||
// The placeholder should not advertise "passthrough mode".
|
||||
const placeholder = (await textarea.getAttribute("placeholder")) ?? "";
|
||||
expect(placeholder.toLowerCase()).not.toContain("passthrough mode");
|
||||
|
||||
// Fill title + description and confirm submit becomes enabled.
|
||||
await testPage.getByTestId("task-title-input").fill("CLI Mode Prompt Test");
|
||||
await textarea.fill("Refactor the cron handler");
|
||||
|
||||
const startBtn = testPage.getByTestId("submit-start-agent");
|
||||
await expect(startBtn).toBeEnabled({ timeout: 30_000 });
|
||||
|
||||
await startBtn.click();
|
||||
await expect(dialog).not.toBeVisible({ timeout: 10_000 });
|
||||
|
||||
// Navigated to the session page — confirms task created successfully.
|
||||
await expect(testPage).toHaveURL(/\/t\//, { timeout: 15_000 });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,61 @@
|
||||
import { test, expect } from "../../fixtures/test-base";
|
||||
import { KanbanPage } from "../../pages/kanban-page";
|
||||
import { SessionPage } from "../../pages/session-page";
|
||||
|
||||
/**
|
||||
* CLI-mode parity: when a task is created with a passthrough (CLI / PTY)
|
||||
* agent and a user-typed description, the backend delivers the prompt
|
||||
* into the running CLI. The mock TUI echoes a "Processed: <prompt>"
|
||||
* line back, so the rendered xterm buffer contains both the prompt
|
||||
* text and the response — proof the agent received it.
|
||||
*/
|
||||
test.describe("CLI mode: prompt injection into PTY", () => {
|
||||
test("creating a CLI-mode task lands the description in the terminal buffer", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
// Use the canonical e2e helper pattern: the e2e backend registers only
|
||||
// the mock-agent, so agents[0] is the passthrough-capable target.
|
||||
// Mirrors `createTUIProfile` in `apps/web/e2e/tests/terminal/terminal-agent.spec.ts`.
|
||||
const { agents } = await apiClient.listAgents();
|
||||
if (agents.length === 0) {
|
||||
throw new Error("no agents registered in this e2e profile");
|
||||
}
|
||||
const tui = await apiClient.createAgentProfile(agents[0].id, "CLI Inject", {
|
||||
model: "mock-fast",
|
||||
auto_approve: true,
|
||||
cli_passthrough: true,
|
||||
});
|
||||
|
||||
const description = "Refactor the cron handler";
|
||||
|
||||
await apiClient.createTaskWithAgent(seedData.workspaceId, "CLI Inject Task", tui.id, {
|
||||
description,
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
repository_ids: [seedData.repositoryId],
|
||||
});
|
||||
|
||||
const kanban = new KanbanPage(testPage);
|
||||
await kanban.goto();
|
||||
|
||||
const card = kanban.taskCardByTitle("CLI Inject Task");
|
||||
await expect(card).toBeVisible({ timeout: 15_000 });
|
||||
await card.click();
|
||||
await expect(testPage).toHaveURL(/\/t\//, { timeout: 15_000 });
|
||||
|
||||
const session = new SessionPage(testPage);
|
||||
|
||||
// Terminal panel becomes visible — passthrough terminal mounts for
|
||||
// CLI-mode sessions.
|
||||
await session.waitForPassthroughLoad(15_000);
|
||||
await session.waitForPassthroughLoaded(15_000);
|
||||
|
||||
// Generous timeout: passthrough idle window is 2s + buffer flush.
|
||||
// The prompt and the mock-agent's "Processed:" response should both
|
||||
// appear in the xterm buffer.
|
||||
await session.expectPassthroughHasText(description, 15_000);
|
||||
await session.expectPassthroughHasText("Processed:", 15_000);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,142 @@
|
||||
import { expect } from "@playwright/test";
|
||||
import { test } from "../../fixtures/test-base";
|
||||
import { KanbanPage } from "../../pages/kanban-page";
|
||||
import { SessionPage } from "../../pages/session-page";
|
||||
import type { ApiClient } from "../../helpers/api-client";
|
||||
|
||||
/**
|
||||
* CLI-mode parity: PassthroughToolbar mounts above the PTY in passthrough
|
||||
* sessions and exposes the kandev compose box + Stop button that ACP sessions
|
||||
* get via ChatInputArea. These tests verify:
|
||||
*
|
||||
* 1. The toolbar renders for passthrough sessions.
|
||||
* 2. The Chat toggle + send path forwards the typed message to the agent's
|
||||
* stdin (mock-agent echoes it as "Processed: <text>").
|
||||
* 3. No dedicated Stop button — users cancel via Ctrl-C in the xterm terminal
|
||||
* (the toolbar intentionally omits a duplicate control).
|
||||
*/
|
||||
test.describe("CLI mode: passthrough toolbar", () => {
|
||||
/** Create a passthrough agent profile and return its ID. */
|
||||
async function createPassthroughProfile(apiClient: ApiClient, name: string): Promise<string> {
|
||||
const { agents } = await apiClient.listAgents();
|
||||
if (agents.length === 0) throw new Error("no agents registered in this e2e profile");
|
||||
const profile = await apiClient.createAgentProfile(agents[0].id, name, {
|
||||
model: "mock-fast",
|
||||
auto_approve: true,
|
||||
cli_passthrough: true,
|
||||
});
|
||||
return profile.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Navigate to the kanban, click the task card, and wait for the passthrough
|
||||
* terminal to finish loading.
|
||||
*/
|
||||
async function openTaskAndWaitForTerminal(
|
||||
testPage: import("@playwright/test").Page,
|
||||
kanban: KanbanPage,
|
||||
session: SessionPage,
|
||||
taskTitle: string,
|
||||
) {
|
||||
const card = kanban.taskCardByTitle(taskTitle);
|
||||
await expect(card).toBeVisible({ timeout: 20_000 });
|
||||
await card.click();
|
||||
await expect(testPage).toHaveURL(/\/t\//, { timeout: 15_000 });
|
||||
await session.waitForPassthroughLoad(20_000);
|
||||
await session.waitForPassthroughLoaded(20_000);
|
||||
}
|
||||
|
||||
test("toolbar renders for passthrough sessions on the task page", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
const profileId = await createPassthroughProfile(apiClient, "CLI Toolbar Render");
|
||||
|
||||
await apiClient.createTaskWithAgent(seedData.workspaceId, "Toolbar Render Task", profileId, {
|
||||
description: "hello toolbar",
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
repository_ids: [seedData.repositoryId],
|
||||
});
|
||||
|
||||
const kanban = new KanbanPage(testPage);
|
||||
await kanban.goto();
|
||||
|
||||
const session = new SessionPage(testPage);
|
||||
await openTaskAndWaitForTerminal(testPage, kanban, session, "Toolbar Render Task");
|
||||
|
||||
await expect(testPage.getByTestId("passthrough-toolbar")).toBeVisible({ timeout: 10_000 });
|
||||
await expect(testPage.getByTestId("passthrough-toggle-composer")).toBeVisible({
|
||||
timeout: 5_000,
|
||||
});
|
||||
});
|
||||
|
||||
test("composer toggle + send forwards message to the agent", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
const profileId = await createPassthroughProfile(apiClient, "CLI Toolbar Send");
|
||||
|
||||
await apiClient.createTaskWithAgent(seedData.workspaceId, "Toolbar Send Task", profileId, {
|
||||
description: "initial prompt",
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
repository_ids: [seedData.repositoryId],
|
||||
});
|
||||
|
||||
const kanban = new KanbanPage(testPage);
|
||||
await kanban.goto();
|
||||
|
||||
const session = new SessionPage(testPage);
|
||||
await openTaskAndWaitForTerminal(testPage, kanban, session, "Toolbar Send Task");
|
||||
|
||||
// Wait for the initial prompt injection to complete
|
||||
await session.expectPassthroughHasText("Processed:", 20_000);
|
||||
|
||||
// Open the composer and send a follow-up message
|
||||
await testPage.getByTestId("passthrough-toggle-composer").click();
|
||||
await expect(testPage.getByTestId("passthrough-composer")).toBeVisible({ timeout: 5_000 });
|
||||
|
||||
const textarea = testPage.getByTestId("passthrough-composer-textarea");
|
||||
await textarea.fill("hello from e2e");
|
||||
await textarea.press("Enter");
|
||||
|
||||
// The composer closes on successful send
|
||||
await expect(testPage.getByTestId("passthrough-composer")).toBeHidden({ timeout: 10_000 });
|
||||
|
||||
// The mock-agent TUI echoes the prompt as "Processed: <text>"
|
||||
await session.expectPassthroughHasText("hello from e2e", 15_000);
|
||||
});
|
||||
|
||||
test("toolbar omits a Stop button; cancel is via Ctrl-C in the terminal", async ({
|
||||
testPage,
|
||||
apiClient,
|
||||
seedData,
|
||||
}) => {
|
||||
const profileId = await createPassthroughProfile(apiClient, "CLI Toolbar No Stop");
|
||||
|
||||
await apiClient.createTaskWithAgent(seedData.workspaceId, "Toolbar No Stop Task", profileId, {
|
||||
description: "initial prompt",
|
||||
workflow_id: seedData.workflowId,
|
||||
workflow_step_id: seedData.startStepId,
|
||||
repository_ids: [seedData.repositoryId],
|
||||
});
|
||||
|
||||
const kanban = new KanbanPage(testPage);
|
||||
await kanban.goto();
|
||||
|
||||
const session = new SessionPage(testPage);
|
||||
await openTaskAndWaitForTerminal(testPage, kanban, session, "Toolbar No Stop Task");
|
||||
|
||||
await expect(testPage.getByTestId("passthrough-toolbar")).toBeVisible({ timeout: 10_000 });
|
||||
// PassthroughToolbar deliberately has no Stop affordance — Ctrl-C in xterm is the path.
|
||||
await expect(testPage.getByTestId("passthrough-stop")).toHaveCount(0);
|
||||
|
||||
await session.passthroughTerminal.locator(".xterm").click();
|
||||
await testPage.keyboard.press("Control+c");
|
||||
// Terminal stays mounted; we only assert the UI never offered a misleading Stop button.
|
||||
await expect(testPage.getByTestId("passthrough-terminal")).toBeVisible({ timeout: 5_000 });
|
||||
});
|
||||
});
|
||||
@@ -14,7 +14,7 @@ const PLAN_CONTEXT_PATH = "plan:context";
|
||||
|
||||
const AUTO_TRANSITION_ACTIONS = ["move_to_next", "move_to_previous", "move_to_step"];
|
||||
|
||||
function useNextWorkflowStep(taskId: string | null) {
|
||||
export function useNextWorkflowStep(taskId: string | null) {
|
||||
const { toast } = useToast();
|
||||
const workflowId = useAppStore((s) => s.kanban.workflowId);
|
||||
const steps = useAppStore((s) => s.kanban.steps);
|
||||
|
||||
@@ -161,6 +161,8 @@ export type PassthroughConfig = {
|
||||
supported: boolean;
|
||||
label: string;
|
||||
description: string;
|
||||
auto_inject_prompt?: boolean;
|
||||
submit_sequence?: string;
|
||||
};
|
||||
|
||||
export type ToolStatus = {
|
||||
|
||||
@@ -105,6 +105,7 @@ System pages (Radarr/Sonarr-style) for status, disk usage, database maintenance,
|
||||
| [homebrew-core](homebrew-core/spec.md) | draft |
|
||||
| [public-share-links](public-share-links/spec.md) | draft |
|
||||
| [ssh-executor](ssh-executor/spec.md) | draft |
|
||||
| [cli-mode-parity](cli-mode-parity/spec.md) | draft |
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,153 @@
|
||||
---
|
||||
status: draft
|
||||
created: 2026-05-16
|
||||
owner: cfl
|
||||
issue: https://github.com/kdlbs/kandev/issues/906
|
||||
needs-upgrade: true
|
||||
---
|
||||
|
||||
# CLI-Mode Task Parity (Kanban)
|
||||
|
||||
## Why
|
||||
|
||||
Anthropic has announced that **agent-SDK / `claude -p` usage will draw from a paid API budget**, while the interactive `claude` CLI continues to draw from the user's Pro/Max subscription quota. Today kandev drives Claude almost exclusively through the ACP bridge (`@agentclientprotocol/claude-agent-acp`), which is an SDK-mode integration. After the change, every kandev task run by a subscription user would burn API dollars they do not have.
|
||||
|
||||
Kandev already supports a per-profile **CLI Passthrough** mode that launches the agent CLI under a PTY (`apps/backend/internal/agentctl/server/process/interactive_runner.go`). Users who enable it keep their subscription billing — but the experience is bare:
|
||||
|
||||
1. The task-create dialog **disables the prompt textarea** when a CLI agent is selected (legacy assumption: "you'll type your prompt directly into the terminal"). So the user can't even attach a description to a CLI-mode task.
|
||||
2. The task description that kandev would have sent through ACP is **not delivered to the CLI**. The user has to retype it.
|
||||
3. The chat compose box on a CLI-mode session does nothing — there is no path from kandev's UI into the agent's stdin for follow-up messages.
|
||||
|
||||
This spec brings CLI-passthrough mode up to feature parity with ACP for the **kanban** task-execution surface. Office (autonomous) mode is explicitly deferred.
|
||||
|
||||
## What
|
||||
|
||||
### Prompt allowed at task creation in CLI mode
|
||||
|
||||
The task-create dialog's prompt textarea is **enabled** when a CLI/passthrough-capable agent is selected. Users can write the prompt the same way they would for ACP. The control flow that today gates this off when `cli_passthrough` is true is removed.
|
||||
|
||||
### Task-prompt injection (idle-based, agent-agnostic)
|
||||
|
||||
When a passthrough session starts for a task that has a description:
|
||||
|
||||
1. Kandev launches the PTY as today.
|
||||
2. After the existing **idle detector** in `InteractiveRunner` fires for the first time (i.e. the CLI has stopped emitting output and is presumed to be at its input prompt), kandev writes the task description plus a configurable **submit sequence** to the PTY's stdin.
|
||||
3. Auto-injection is opt-in per agent via a new `PassthroughConfig.AutoInjectPrompt` flag (default false). Agents that already use `PromptFlag` (headless one-shot mode) are unaffected — their prompt is already on the CLI before launch.
|
||||
|
||||
No per-agent pattern matchers. The existing idle window is the only readiness signal. If an agent's CLI is unusual enough that an idle window misfires (writes a banner, then waits 5 seconds, then prompts), we make the idle window per-agent-configurable in `PassthroughConfig` (already exists as `IdleTimeout`). No new detection machinery.
|
||||
|
||||
For the Claude case: `claude_acp.go` sets `AutoInjectPrompt: true`, `DisableBracketedPaste: true` (Claude Code already enables bracketed-paste *mode* in its Ink TUI — injecting `ESC[200~`…`ESC[201~` delimiters breaks the prompt), and `SubmitViaBackslashEnter: true` (PTY writes: prompt, then `\`, then `\r` per [Claude terminal docs](https://code.claude.com/docs/en/terminal-config)). Ink may still treat programmatic Enter as newline only ([anthropics/claude-code#15553](https://github.com/anthropics/claude-code/issues/15553)) — if auto-submit fails, the user confirms with Enter. Other passthrough-capable agents use bracketed-paste delimiters for multi-line prompts and stay default-off for auto-inject unless configured.
|
||||
|
||||
### Follow-up prompts via PTY stdin (backend route landed; UI surface deferred)
|
||||
|
||||
The orchestrator's `PromptTask` handler branches on `IsPassthroughSession(sessionID)` and writes the prompt text + `SubmitSequence` to the agent's PTY stdin instead of sending over ACP. This is the same path used by auto-injection and is reachable today from any caller that hits `agent.prompt` for a passthrough session.
|
||||
|
||||
**UI gap (deferred):** kandev's chat compose box is rendered by `ChatInputArea`, which is replaced entirely by `PassthroughTerminal` when `session.is_passthrough` is true. There is no compose surface in passthrough mode today. Users send follow-ups by typing directly into the terminal (xterm forwards each keystroke to the PTY) — which works perfectly for the Claude CLI use case. A dedicated kandev compose box that drives the PTY (without replacing the terminal) is a follow-up.
|
||||
|
||||
### Stop sends Ctrl-C (backend route landed; UI surface deferred)
|
||||
|
||||
The orchestrator's `CancelAgent` handler branches on `IsPassthroughSession(sessionID)` and writes `\x03` to the PTY's stdin instead of sending an ACP cancel. DB reconciliation still runs so the UI unsticks regardless of the write outcome.
|
||||
|
||||
**UI gap (deferred):** Same root cause as the compose-box gap — `ChatInputArea` (which hosts the Stop button) is not rendered in passthrough mode. Users today press Ctrl-C directly in the xterm terminal, which travels through the same PTY stdin path. A dedicated Stop button overlay in `PassthroughTerminal` is a follow-up.
|
||||
|
||||
## Scenarios
|
||||
|
||||
### CLI-mode task can have a prompt
|
||||
- GIVEN a Claude profile with `cli_passthrough: true`
|
||||
- WHEN the user opens the task-create dialog and types in the prompt field
|
||||
- THEN the prompt textarea accepts input (today it is disabled / hidden)
|
||||
|
||||
### Prompt injection on fresh start
|
||||
- GIVEN a CLI-mode task whose agent has `AutoInjectPrompt: true` and a non-empty description
|
||||
- WHEN the task starts
|
||||
- THEN the PTY launches, the idle detector fires once after the CLI settles, and the task description is written to stdin followed by `SubmitSequence`
|
||||
- AND the description appears in the terminal output
|
||||
|
||||
### Resume does NOT re-inject
|
||||
- GIVEN a CLI-mode task whose PTY exited (backend restart, crash) and is resumed via `--resume`
|
||||
- WHEN the user reopens the terminal and the session resumes
|
||||
- THEN no auto-injection occurs (the conversation is already in the agent's history)
|
||||
|
||||
### Fresh-start fallback DOES inject
|
||||
- GIVEN a CLI-mode task whose resume launch fast-failed and the fresh-start fallback ran (existing `attemptResumeFallback` path)
|
||||
- THEN auto-injection runs against the new fresh session — because that fallback is functionally a new conversation
|
||||
|
||||
### Follow-up prompt route is in place (UI surface follow-up)
|
||||
- GIVEN a CLI-mode task running
|
||||
- WHEN any caller invokes `PromptTask` for the session (today: future kandev compose surface, integration tests)
|
||||
- THEN the text + `SubmitSequence` is written to the PTY
|
||||
- AND no ACP prompt is sent
|
||||
|
||||
### Stop / cancel route is in place (UI surface follow-up)
|
||||
- GIVEN a CLI-mode task running
|
||||
- WHEN any caller invokes `CancelAgent` for the session
|
||||
- THEN `\x03` is written to the PTY
|
||||
- AND DB reconciliation still completes so the session unsticks
|
||||
|
||||
### Agent without AutoInjectPrompt
|
||||
- GIVEN a passthrough-capable agent with `AutoInjectPrompt: false`
|
||||
- WHEN a task starts
|
||||
- THEN no stdin write happens (today's behavior preserved); the user pastes their prompt manually
|
||||
|
||||
## Kandev toolbar above the passthrough terminal
|
||||
|
||||
### Where it appears
|
||||
|
||||
`PassthroughToolbar` (`apps/web/components/task/passthrough-toolbar.tsx`) wraps `PassthroughTerminal` with the same kandev controls that ACP sessions get from `ChatStatusBar` + `ChatInputArea`. It is mounted:
|
||||
|
||||
- Full-page task view: `dockview-shared.tsx` (`DockviewSharedContent`) renders it for passthrough sessions in place of the chat input area; the dockview desktop layout in `task-center-panel.tsx` uses the same shared content.
|
||||
- Kanban Preview tab: `preview-session-tabs.tsx` renders `PassthroughComposer` directly (compose-only, no terminal wrap) for passthrough sessions in the side-peek surface.
|
||||
|
||||
### What it surfaces
|
||||
|
||||
The status row at the bottom of `PassthroughToolbar` contains, left to right:
|
||||
|
||||
- `PRStatusChip` — PR open/merged/draft indicator for the task.
|
||||
- `PRMergedBanner` — banner shown when the PR is merged.
|
||||
- `passthrough-proceed-next-step` button — moves the task to the next workflow step. Only shown when `nextStepName` is non-null and the agent is not busy (`sessionState` is not `RUNNING` or `STARTING`).
|
||||
- `ChatToggleButton` — toggles the `PassthroughComposer` open and closed. Shows `variant="default"` when the composer is open or when there are pending review comments; shows a numeric chip (`data-testid="passthrough-pending-count"`) when collapsed with pending comments.
|
||||
- Stop button (`data-testid="passthrough-stop"`) — disabled when the session is not `RUNNING` or `STARTING`.
|
||||
|
||||
### Default focus contract
|
||||
|
||||
The terminal (`PassthroughTerminal`) renders above the status row and fills the remaining height. The compose box is collapsed by default so xterm retains keyboard focus for raw PTY interaction. The user opts in to the kandev composer explicitly via the Chat button.
|
||||
|
||||
### How the composer formats and sends pending review comments
|
||||
|
||||
When `PassthroughComposer` submits:
|
||||
|
||||
1. `usePendingDiffCommentsByFile(sessionId)` provides comments grouped by file path.
|
||||
2. Non-empty `pendingComments` are formatted via `formatReviewCommentsAsMarkdown` (produces `### Review Comments\n…`) and prepended to the typed text.
|
||||
3. The combined string is sent via `client.request("message.add", { task_id, session_id, content }, 10_000)`.
|
||||
4. `markCommentsSent(ids)` is called only on WS success — a failed send leaves both the composer open (typed text preserved for retry) and the comments pending.
|
||||
5. A `PendingCommentsBanner` (`data-testid="passthrough-pending-comments-banner"`) renders inside the open composer when `pendingCount > 0`.
|
||||
|
||||
### How Stop maps to Ctrl-C
|
||||
|
||||
Clicking the Stop button calls `client.request("agent.cancel", { session_id }, 10_000)` over WS. The WS handler calls `Service.CancelAgent` → `agentManager.CancelAgentBySessionID` in `apps/backend/internal/agent/runtime/lifecycle/manager_interaction.go`, which branches on `execution.PassthroughProcessID != ""` and writes `\x03` to PTY stdin. DB reconciliation completes regardless of the write outcome so the UI unsticks.
|
||||
|
||||
### Not included
|
||||
|
||||
- `TodoIndicator` — ACP-only (requires message stream); not rendered in `PassthroughToolbar`.
|
||||
- Plan-comments and PR-feedback attachment — same pattern as diff comments if needed in future; deferred.
|
||||
- Per-message model/mode picker — ACP-only feature; not applicable to PTY sessions.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Office / autonomous-agent CLI mode — explicitly deferred. Office launches stay on ACP for now.
|
||||
- Parsing PTY output into `task_messages` (transcriber). The terminal panel shows live output; the chat transcript only shows user-sent text in CLI mode.
|
||||
- Billing-type / subscription-quota badge or DTO surface. That belongs to `subscription-usage.md`.
|
||||
- Adding passthrough support to agents that don't have it (`Supported: false`).
|
||||
- Migrating away from the current ACP bridge.
|
||||
- Headless `-p` mode for Claude (drains API credit; we deliberately do not use it).
|
||||
|
||||
## Follow-ups
|
||||
|
||||
- **Compose box in passthrough mode.** Surface a dedicated kandev compose input (alongside the PTY terminal) that writes to PTY stdin via the now-wired backend route. Today users type into xterm directly, which works but is inconsistent with kandev's ACP UX.
|
||||
- **Stop button overlay in `PassthroughTerminal`.** Small affordance that calls the existing cancel route. Today users press Ctrl-C inside xterm directly.
|
||||
- **AutoInjectPrompt on other passthrough agents** (Codex CLI, OpenCode TUI, etc.) — only Claude is opted in for v1. Adding others requires verifying their submit sequence and idle behavior.
|
||||
|
||||
## Open questions
|
||||
|
||||
- **Submit sequence for Claude TUI**: `"\r"` is the expected default. If the TUI swallows the first `\r` as a focus-acquisition event we may need a tiny pre-write delay or `"\r\n"`. Resolve empirically during dogfooding; the field is configurable per agent.
|
||||
- **Idle window for Claude TUI**: today's default (3s) should be enough — the TUI prints its banner and then sits at the prompt. Tune the per-agent `IdleTimeout` only if real sessions misfire.
|
||||
Reference in New Issue
Block a user